From ajaksu at gmail.com Tue Dec 23 17:42:53 2008 From: ajaksu at gmail.com (ajaksu) Date: Tue, 23 Dec 2008 14:42:53 -0800 (PST) Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <826275b7-986a-4e70-9129-83cc0d10f0d0@q36g2000vbn.googlegroups.com> On Dec 23, 2:45?pm, Mark Dickinson wrote: > On Dec 23, 4:27?pm, ajaksu wrote: > > > Is "x ** 0 > 0." instead of "atan2(x, -1.) > 0." unreliable across > > platforms? > > x**0 doesn't distinguish between x = -0.0 and x = 0.0. > > I suspect you're confusing -0.0**0.0 with (-0.0)**0.0. Yes, fooled me :) Thanks for the heads-up! Daniel From lie.1296 at gmail.com Sun Dec 14 17:46:58 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 14 Dec 2008 22:46:58 +0000 (UTC) Subject: Looking for the best way to translate an idiom References: <4945406a$0$1127$426a74cc@news.free.fr> <2c5ad999-47f9-4040-85c9-4c9438afe4bb@b41g2000pra.googlegroups.com> Message-ID: On Sun, 14 Dec 2008 09:51:03 -0800, Paul Moore wrote: > On 14 Dec, 16:22, Bruno Desthuilliers > wrote: >> if you only want the first returned value, you can just apply a slice: >> >> def f(): >> ? ? return 1,2,3 >> >> a = f()[0] + 1 > > Hmm, true. I'm not sure it's any less ugly, though :-) > >> FWIW, Python 2.6 has NamedTuple objects... > > I know, but I want to target 2.5+ (I still have a number of systems > running 2.5) > Ah, that discounts python 3.0 Python 3.0 allows you to do this: a, b, *c = range(5) # a >> 0 # b >> 1 # c >> [2, 3, 4] *a, b, c = range(5) # a >> [0, 1, 2] # b >> 3 # c >> 4 a, *b, c = range(5) # a >> 0 # b >> [1, 2, 3] # C >> 4 From erichapkido at gmail.com Tue Dec 9 11:26:54 2008 From: erichapkido at gmail.com (Eric) Date: Tue, 9 Dec 2008 08:26:54 -0800 (PST) Subject: Google Summer of Code 2009 References: <713dd4d7-0427-4b74-a5bc-1e3538afed6c@n10g2000vbl.googlegroups.com> Message-ID: <8933ce79-0b6a-4690-8b13-7e151d817a40@z28g2000prd.googlegroups.com> On Dec 9, 6:26?am, Andr? wrote: > On Dec 8, 10:34?pm, Eric wrote: > > You should have a look athttp://wiki.python.org/moin/SummerOfCode > > It's still early, so there's nothing yet for 2009, but I am sure that > some ongoing projects mentioned in previous years [like Crunchy ;-)] > will be looking for volunteers. > > Andr? Thanks for the link. For some reason I hadn't seen Crunchy there before. I would be interested in doing something for Crunchy. The class room server seems like a good project if it hasn't been tackled yet. I also wouldn't mind trying to get the history menu going as a start. -Eric From milliondollarnow at gmail.com Thu Dec 25 10:37:21 2008 From: milliondollarnow at gmail.com (pal) Date: Thu, 25 Dec 2008 07:37:21 -0800 (PST) Subject: Rock Hard Erection Message-ID: <0e0a28c3-08f5-4460-be8d-c7dfab421e24@n33g2000pri.googlegroups.com> ?Would You Like To Know How To Get Rock Hard Erection And Last 60 Minutes Longer Between Her Legs, Enjoy Multiple Orgasms While Keeping Your Rock Hard, Full Length Erection.? Please visit http://godisgreat.wdarpkere.click2sell.eu From stefan_ml at behnel.de Sat Dec 27 04:04:10 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 27 Dec 2008 10:04:10 +0100 Subject: Getting a locked buffer from objects (PEP 3118) In-Reply-To: References: Message-ID: <4955ef8b$0$30225$9b4e6d93@newsspool1.arcor-online.net> KKH wrote: > it seems the whole locking-theme has gone from PEP 3118 (PyBUF_LOCK is > gone). Yet the string and byte objects seem to provide locked buffers > through PyArg_Parse arguments s*, y* and z* (documentation says so). Might be a left-over. All locking the buffer interface itself provides is the guarantee that the buffer will not move between getting and releasing a buffer. Everything else must be handled at the application level. > Could someone please clarify the situation for me: Is it save to release > the GIL after getting a reference to a buffer-object by the arguments > above and only talking to this buffer while the GIL is gone? The buffer interface is a pure C level interface. All you get is a pointer to a memory buffer plus some meta data. No Python references are involved from that point on. So it only depends on your own code if it's safe to free the GIL or not. > And while we are at it :-) Is "PyArg_Parse('[syz]*'..." the only way to > get a locked buffer-view from string/byte objects? What kind of locking do you need? Stefan From clp at rebertia.com Thu Dec 18 04:04:03 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 18 Dec 2008 01:04:03 -0800 Subject: importing csv file into sqlite In-Reply-To: <21068111.post@talk.nabble.com> References: <21067453.post@talk.nabble.com> <21068111.post@talk.nabble.com> Message-ID: <47c890dc0812180104g4c934a56ma8ef49d0bf6b4d80@mail.gmail.com> On Wed, Dec 17, 2008 at 11:20 PM, klia wrote: > klia wrote: >> >> hey guys, i have a hug .csv file which i need to insert it into sqlite >> database using python. >> my csv data looks like this >> Birthday2,12/5/2008,HTC,this is my birthday >> Sea,12/3/2008,kodak,sea >> birthday4,14/3/2009,samsung,birthday >> love,17/4/2009,SONY,view of island >> >> can any one give me a head start codes. >> >> thanks in advance >> > guys so far i came out with this but i get this error > waseem at Linux:~/Project2$ python experment.py > Traceback (most recent call last): > File "experment.py", line 13, in > curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item) > sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current > statement uses 4, and there are 1 supplied. > > here's the codes > > import sqlite3 > import csv > > f = open('/home/waseem/Project2/photos.txt') > csv.field_size_limit(100000) #see below! > input = csv.reader(f, delimiter='\t') > conn = sqlite3.connect('/home/waseem/Project2/picutres.db') > curse = conn.cursor() > > curse.execute('CREATE TABLE photos (Name VARCHAR(100) PRIMARY KEY, Date > INTEGER, Make VARCHAR(50), Tag VARCHAR(100))') > > for item in input: > curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item) I believe you need to change 'item' to '*item' to expand the list in the call so that the function gets 4 additional args rather than 1 additional arg that happens to be a list. But as I've never used the DB-API before, this is just a guess. Also, you should rename 'input' so that you don't shadow a built-in function, and you might want to rename 'item' to something like 'row' to emphasize that it is itself a list of items. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > curse.commit() From castironpi at gmail.com Mon Dec 22 18:36:15 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 22 Dec 2008 15:36:15 -0800 (PST) Subject: Are python objects thread-safe? References: Message-ID: <5306b56c-eb8c-4148-b426-013caa871375@b41g2000pra.googlegroups.com> On Dec 22, 2:59?am, Duncan Booth wrote: > RajNewbie wrote: > > Say, I have two threads, updating the same dictionary object - but for > > different parameters: > > Please find an example below: > > a = {file1Data : '', > > ? ? ? ?file2Data : ''} > > > Now, I send it to two different threads, both of which are looping > > infinitely: > > In thread1: > > a['file1Data'] = open(filename1).read > > ? ? ? ? ? and > > in thread2: > > a['file2Data'] = open(filename2).read > > > My question is ?- is this object threadsafe? - since we are working on > > two different parameters in the object. Or should I have to block the > > whole object? > > It depends exactly what you mean by 'threadsafe'. The GIL will guarantee > that you can't screw up Python's internal data structures: so your > dictionary always remains a valid dictionary rather than a pile of bits. > > However, when you dig a bit deeper, it makes very few guarantees at the > Python level. Individual bytecode instructions are not guaranteed > atomic: for example, any assignment (including setting a new value into > the dictionary) could overwrite an existing value and the value which is > overwritten may have a destructor written in Python. If that happens you > can get context switches within the assignment. Th.1 Th.2 a=X a=Y a=Z You are saying that if 'a=Z' interrupts 'a=Y' at the wrong time, the destructor for 'X' or 'Y' might not get called. Correct? In serial flow, the destructor for X is called, then Y. > Other nasty things can happen if you use dictionaries from multiple > threads. You cannot add or remove a dictionary key while iterating over > a dictionary. This isn't normally a big issue, but as soon as you try to > share the dictionary between threads you'll have to be careful never to > iterate through it. These aren't documented, IIRC. Did you just discover them by trial and error? > You will probably find it less error prone in the long run if you get > your threads to write (key,value) tuples into a queue which the > consuming thread can read and use to update the dictionary. Perhaps there's a general data structure which can honor 'fire-and- forget' method calls in serial. a= async( {} ) a[0]= X a[0]= Y --> obj_queue[a].put( a.__setitem__, 0, X ) obj_queue[a].put( a.__setitem__, 0, Y ) If you need the return value, you'll need to block. print a[0] --> res= obj_queue[a].put( a.__getitem__, 0 ) res.wait() return res print res Or you can use a Condition object. But you can also delegate the print farther down the line of processing: obj_queue[a].link( print ).link( a.__getitem__, 0 ) (As you can see, the author (I) finds it a more interesting problem to get required information in the right places at the right times in execution. The actual implementation is left to the reader; I'm merely claiming that there exists a consistent one taking the above instructions to be sufficient givens.) From martin.hellwig at dcuktec.org Fri Dec 12 04:47:39 2008 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Fri, 12 Dec 2008 09:47:39 +0000 Subject: Moving to subprocess from os.popen--pipe closes prematurely In-Reply-To: References: Message-ID: <4942333c$0$191$e4fe514c@news.xs4all.nl> Kevin Walzer wrote: > Hello, > > I'm trying to move from os.popen to using subprocess, and I'm having > trouble with the pipe suddenly closing. > > My old code looked something like this: > Hi Kevin, You could try something more like: >>> import subprocess >>> cmd = subprocess.Popen([executable_path, executable_options], stdout=subprocess.PIPE, stdout=subprocess.PIPE) >>> std_out, std_err = cmd.communicate(standard_in_value) std_out is a string though, you probably need to split it on newline to get the same sort of list and since it is buffered in memory you probably don't want to use .communicate if you expect megabytes of data back. -- mph From _karlo_ at _mosor.net_ Sat Dec 13 15:29:43 2008 From: _karlo_ at _mosor.net_ (Karlo Lozovina) Date: Sat, 13 Dec 2008 20:29:43 +0000 (UTC) Subject: curses and refreshing problem Message-ID: Hi, I'm trying to implement text output interface, something similar to wget, using curses module. There are just two things I can't find out how to do: prevent curses from clearing the terminal when starting my program, and leaving my output after the program closes. Any way to do this with curses? Thanks... -- _______ Karlo Lozovina - Mosor | | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163 | || _ | _ | Parce mihi domine quia Dalmata sum. |__|_|__||_____|_____| From metolone+gmane at gmail.com Sat Dec 6 14:20:26 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 6 Dec 2008 11:20:26 -0800 Subject: Python 3.0 automatic decoding of UTF16 References: <5u8o06xbqf.ln2@joeserver.homelan.net> <1mmq06x4g6.ln2@joeserver.homelan.net> Message-ID: "Johannes Bauer" wrote in message news:1mmq06x4g6.ln2 at joeserver.homelan.net... >John Machin schrieb: >> On Dec 6, 5:36 am, Johannes Bauer wrote: >>> So UTF-16 has an explicit EOF marker within the text? I cannot find one >>> in original file, only some kind of starting sequence I suppose >>> (0xfeff). The last characters of the file are 0x00 0x0d 0x00 0x0a, >>> simple \r\n line ending. >> >> Sorry, *WRONG*. It ends in 00 0d 00 0a 00. The file is 1559 bytes >> long, an ODD number, which shouldn't happen with utf16. The file is >> stuffed. Python 3.0 has a bug; it should give a meaningful error >> message. > >Yes, you are right. I fixed the file, yet another error pops up >(http://www.file-upload.net/download-1299688/2008_12_05_Handy_Backup.txt.html): > >Traceback (most recent call last): > File "./modify.py", line 12, in > a = AddressBook("2008_12_05_Handy_Backup.txt") > File "./modify.py", line 7, in __init__ > line = f.readline() > File "/usr/local/lib/python3.0/io.py", line 1807, in readline > while self._read_chunk(): > File "/usr/local/lib/python3.0/io.py", line 1556, in _read_chunk > self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) > File "/usr/local/lib/python3.0/io.py", line 1293, in decode > output = self.decoder.decode(input, final=final) > File "/usr/local/lib/python3.0/codecs.py", line 300, in decode > (result, consumed) = self._buffer_decode(data, self.errors, final) > File "/usr/local/lib/python3.0/encodings/utf_16.py", line 69, in >_buffer_decode > return self.decoder(input, self.errors, final) >UnicodeDecodeError: 'utf16' codec can't decode byte 0x0a in position 0: >truncated data > >File size is 1630 bytes - so this clearly cannot be. How about posting your code? The first file is incorrect. It contains an extra 0x00 byte at the end of the file, but is otherwise correctly encoded with a big-endian UTF16 BOM and data. The second file is a correct UTF16-BE file as well. This code (Python 2.6) decodes the first file, removing the trailing extra byte: raw = open('2008_11_05_Handy_Backup.txt').read() data = raw[:-1].decode('utf16') and this code (Python 2.6) decodes the second: raw = open('2008_12_05_Handy_Backup.txt').read() data = raw.decode('utf16') Python 3.0 also has no problems with decoding or accurate error messages: >>> data = open('2008_12_05_Handy_Backup.txt',encoding='utf16').read() >>> data = open('2008_11_05_Handy_Backup.txt',encoding='utf16').read() Traceback (most recent call last): File "", line 1, in File "C:\dev\python30\lib\io.py", line 1724, in read decoder.decode(self.buffer.read(), final=True)) File "C:\dev\python30\lib\io.py", line 1295, in decode output = self.decoder.decode(input, final=final) File "C:\dev\python30\lib\codecs.py", line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) File "c:\dev\python30\lib\encodings\utf_16.py", line 61, in _buffer_decode codecs.utf_16_ex_decode(input, errors, 0, final) UnicodeDecodeError: 'utf16' codec can't decode byte 0x00 in position 1558: trunc ated data -Mark From mludvig at logix.net.nz Mon Dec 29 07:45:00 2008 From: mludvig at logix.net.nz (Michal Ludvig) Date: Tue, 30 Dec 2008 01:45:00 +1300 Subject: Unicode encoding - ignoring errors In-Reply-To: <47c890dc0812290410u25f9e69oecdcc0e859f9b10e@mail.gmail.com> References: <4958BD31.1010801@logix.net.nz> <47c890dc0812290410u25f9e69oecdcc0e859f9b10e@mail.gmail.com> Message-ID: <4958C64C.7000400@logix.net.nz> Chris Rebert wrote: > On Mon, Dec 29, 2008 at 4:06 AM, Michal Ludvig wrote: >> Hi, >> >> in my script I have sys.stdout and sys.stderr redefined to output >> unicode strings in the current system encoding: >> >> encoding = locale.getpreferredencoding() >> sys.stdout = codecs.getwriter(encoding)(sys.stdout) >> >> However on some systems the locale doesn't let all the unicode chars be >> displayed and I eventually end up with UnicodeEncodeError exception. >> >> I know I could explicitly "sanitize" all output with: >> >> whatever.encode(encoding, "replace") >> >> but it's quite inconvenient. I'd much prefer to embed this "replace" >> operation into the sys.stdout writer. >> [...] > codecs.getwriter() returns a StreamWriter subclass (basically). > The constructor of said subclass has the signature: > StreamWriter(stream[, errors]) > You want the 'errors' argument. Thanks! (and I'm going to read the module docs, really ;-) Michal From af300wsm at gmail.com Mon Dec 8 16:33:38 2008 From: af300wsm at gmail.com (Andrew Falanga) Date: Mon, 8 Dec 2008 13:33:38 -0800 (PST) Subject: Calling C# COM (.NET) from python References: <65482a31-8091-486f-8a9b-8f6bdf947af6@w1g2000prk.googlegroups.com> Message-ID: <0e2ec315-a5ef-419e-a224-78ab965db99c@r15g2000prd.googlegroups.com> On Dec 8, 11:52?am, Mike Driscoll wrote: > On Dec 8, 11:14?am, Ben Kaplan wrote: > > > > > On Dec 8, 2008, at 11:53 AM, Andrew Falanga wrote: > > > > Hi, > > > > I've never programmed in python and only have a small understanding of > > > what is wrapped up in the terms COM and .NET. ?Is there a way of using > > > python to get a hold of objects written in C# as COM objects using > > > python? ?I'm looking for ways to avoid VBScript (which, after a couple > > > of weeks, I've determined to be horrid). ?That is, is there a way of > > > getting at COM objects in python that's similar to doing a > > > CreateObject call in VBScript (http://msdn.microsoft.com/en-us/ > > > library/ > > > dcw63t7z.aspx)? > > > > Thanks, > > > Andy > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > I would not deal with COM at all. I personally have not used it, but ? > > there is a version of python called IronPython that's written in C#, ? > > so it can use .NET and, I think, other C# objects. Other people will ? > > probably help you more, but you might want to look into that and maybe ? > > ask this on the python-win list. > > As I understand it, IronPython can use anything done in the CLR, so > technically I could write something in VB.NET, C# or any of the other > VS languages and then use them from within IronPython. It should be > noted that IronPython does not support most 3rd party packages that > are not pure python. As I recall, it doesn't have the complete builtin > library either, but it's close. > > Reads the docs and check it out at least. If you already know .NET > languages, then you'll probably find IronPython helpful. > > Mike To all, thanks for the great replies. I've got something to work with here. Thanks to for the link to PyWin32 and the mailing list. That sounds promising as does this IronPython. I wished I knew more of .NET and python more (as my original post claims, I've never written Python and I only wished I knew the .NET stuff better for better footing in this). I'm very much the proverbial, "fish out of water," as I'm a UNIX man now stuck in a Windows world. Thanks again, Andy From tjreedy at udel.edu Fri Dec 12 19:16:47 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 12 Dec 2008 19:16:47 -0500 Subject: __future__ and unrecognised flags In-Reply-To: <20081212215252.18112.qmail@s461.sureserver.com> References: <20081212215252.18112.qmail@s461.sureserver.com> Message-ID: Poor Yorick wrote: > I have a future statement in a script I intend to work on 2.6 and 3. Shouldn't __future__ statements basically be noops for versions that already support the feature? doctest is complaining about compiler flags. This illustrates the problem: > > Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win > 32 > Type "help", "copyright", "credits" or "license" for more information. > >>> from __future__ import unicode_literals > >>> src = 'a = "hello"' > >>> c1 = compile(src,'','exec',unicode_literals.compiler_flag) > Traceback (most recent call last): > File "", line 1, in > ValueError: compile(): unrecognised flags According to this "The optional arguments flags and dont_inherit control which future statements (see PEP 236) affect the compilation of source. If neither is present (or both are zero) the code is compiled with those future statements that are in effect in the code that is calling compile. " you do not need to duplicate the future option in the compile call. I tried doing the same without the flag and it works. That said, this seems like a bug to me, so if no one explains otherwise, report it at http://bugs.python.org I tried with 5th param True and got same error. On Winxp tjr From dieter at handshake.de Sat Dec 6 14:35:19 2008 From: dieter at handshake.de (Dieter Maurer) Date: 06 Dec 2008 20:35:19 +0100 Subject: Profiling Python In-Reply-To: <15e24533-472f-4147-9467-893b40ff2710@w35g2000yqm.googlegroups.com> References: <15e24533-472f-4147-9467-893b40ff2710@w35g2000yqm.googlegroups.com> Message-ID: esgameserver at gmail.com writes on Wed, 3 Dec 2008 07:13:14 -0800 (PST): > To clarify again, > Is there some function like profile.PrintStats() which dynamically > shows the stats before stopping the Profiler? Try to (deep) copy the profiler instance and than call "PrintStats()" on the copy. Of course, you will then profile also the "PrintStats" in the running profiler. Dieter From manu3d at gmail.com Thu Dec 11 19:00:31 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 11 Dec 2008 16:00:31 -0800 (PST) Subject: Preventing execution of a method References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> <764daeef-bfbe-411a-8521-bb114321e4ac@b38g2000prf.googlegroups.com> <19304f8c-e34f-4aa9-8df2-6a7d3553007a@e1g2000pra.googlegroups.com> <2eed8876-94d2-4304-88a5-eb4a78b4f41d@33g2000yqm.googlegroups.com> <307fe197-1b42-4305-af0e-94b7ebe3ce70@r15g2000prh.googlegroups.com> <49417c59$0$8491$426a74cc@news.free.fr> <6qdmthFc5ggdU1@mid.individual.net> Message-ID: <86f33456-4620-42ef-8ba9-eb1532aa2635@r10g2000prf.googlegroups.com> On Dec 11, 11:46?pm, greg wrote: > Emanuele D'Arrigo wrote: > > -IF- the application was single-user yes, it wouldn't be a big deal. > > But as it is potentially multi-user, I don't want one party to corrupt > > the application for everybody else. > > In that case you definitely want a client-server architecture, > with the server managing all the critical data. Yep, I agree, I think that's the way to go and although trickier it allows for some neatness and flexibility. Thank you! Manu From enleverlesX.XmcX at XmclaveauX.com Sat Dec 20 12:05:37 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sat, 20 Dec 2008 18:05:37 +0100 Subject: check whether a JPG is completed? In-Reply-To: References: Message-ID: <494d2756$0$18388$ba4acef3@news.orange.fr> Hi! Sometimes, PIL give an error. With "try: Except:", you can get info. Sometimes, non error, but the Jpeg is not correct. Difficult, in this case, to get info. Therefore, the answer is: "not in all cases". @-salutations -- Michel Claveau From iofferkicks24 at gmail.com Wed Dec 24 22:59:09 2008 From: iofferkicks24 at gmail.com (www.iofferkicks.com) Date: Wed, 24 Dec 2008 19:59:09 -0800 (PST) Subject: www.iofferkicks.com china cheap wholesale nike shoes,air jordan shoes,air force one shoes. Message-ID: <790bd96b-dbda-470b-bc33-b6813ea10e2c@k36g2000pri.googlegroups.com> Get Nike Shoes at Super Cheap Prices Discount Nike air jordans (www.iofferkicks.com) Discount Nike Air Max 90 Sneakers (www.iofferkicks.com) Discount Nike Air Max 91 Supplier (www.iofferkicks.com) Discount Nike Air Max 95 Shoes Supplier (www.iofferkicks.com) Discount Nike Air Max 97 Trainers (www.iofferkicks.com) Discount Nike Air Max 2003 Wholesale (www.iofferkicks.com) Discount Nike Air Max 2004 Shoes Wholesale (www.iofferkicks.com) Discount Nike Air Max 2005 Shop (www.iofferkicks.com) Discount Nike Air Max 2006 Shoes Shop (www.iofferkicks.com) Discount Nike Air Max 360 Catalogs (www.iofferkicks.com) Discount Nike Air Max Ltd Shoes Catalogs (www.iofferkicks.com) Discount Nike Air Max Tn Men's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 2 Women's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 3 Customize (www.iofferkicks.com) Discount Nike Air Max Tn 4 Shoes Customize ( www.iofferkicks.com) Discount Nike Air Max Tn 6 Supply (www.iofferkicks.com) Discount Nike Shox NZ Shoes Supply (www.iofferkicks.com) Discount Nike Shox OZ Sale (www.iofferkicks.com) Discount Nike Shox TL Store (www.iofferkicks.com) Discount Nike Shox TL 2 Shoes Store (www.iofferkicks.com) Discount Nike Shox TL 3 Distributor (www.iofferkicks.com) Discount Nike Shox Bmw Shoes Distributor (www.iofferkicks.com) Discount Nike Shox Elite Shoes Manufacturer (www.iofferkicks.com) Discount Nike Shox Monster Manufacturer (www.iofferkicks.com) Discount Nike Shox R4 Running Shoes (www.iofferkicks.com) Discount Nike Shox R5 Mens Shoes (www.iofferkicks.com) Discount Nike Shox Ride Womens Shoes (www.iofferkicks.com) Discount Nike Shox Rival Shoes Wholesaler (www.iofferkicks.com) Discount Nike Shox Energia Wholesaler (www.iofferkicks.com) Discount Nike Shox LV Sneaker (www.iofferkicks.com) Discount Nike Shox Turbo Suppliers (www.iofferkicks.com) Discount Nike Shox Classic Shoes Suppliers (www.iofferkicks.com) Discount Nike Shox Dendara Trainer (www.iofferkicks.com) Discount Nike Air Jordan 1 Seller (www.iofferkicks.com) Discount Nike Air Jordan 2 Shoes Seller (www.iofferkicks.com) Discount Nike Air Jordan 3 Collection (www.iofferkicks.com) Discount Nike Air Jordan 4 Shoes Collection (www.iofferkicks.com) Discount Nike Air Jordan 5 Chaussure Shoes (www.iofferkicks.com) Discount Nike Air Jordan 6 Catalog (www.iofferkicks.com) Discount Nike Air Jordan 7 Shoes Catalog (www.iofferkicks.com) Discount Nike Air Jordan 8 Customized (www.iofferkicks.com) Discount Nike Air Jordan 9 Shoes Customized (www.iofferkicks.com) Discount Nike Air Jordan 10 Wholesalers (www.iofferkicks.com) Discount Nike Jordan 11 Shoes Wholesalers (www.iofferkicks.com) Discount Nike Air Jordan 12 Factory (www.iofferkicks.com) Discount Nike Air Jordan 13 Shoes Factory (www.iofferkicks.com) Discount Nike Air Jordan 14 Shoes Sell (www.iofferkicks.com) Discount Nike Air Jordan 16 Exporter (www.iofferkicks.com) Discount Nike Air Jordan 17 Shoes Exporter (www.iofferkicks.com) Discount Nike Air Jordan 18 Offer (www.iofferkicks.com) Discount Nike Air Jordan 19 Shoes Offer (www.iofferkicks.com) Discount Nike Air Jordan 20 Manufacture (www.iofferkicks.com) Discount Nike Jordan 21 Shoes Manufacture (www.iofferkicks.com) EMAIL:IOFFERKICKS at GMAIL.COM MSN :IOFFERKICKS at MSN.COM From pavlovevidence at gmail.com Sat Dec 6 16:33:22 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 6 Dec 2008 13:33:22 -0800 (PST) Subject: Guido's new method definition idea References: Message-ID: On Dec 5, 8:21?pm, "Daniel Fetchinson" wrote: > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... > > The proposal is to allow this: > > class C: > ? ? def self.method( arg ): > ? ? ? ? self.value = arg > ? ? ? ? return self.value > > instead of this: > > class C: > ? ? def method( self, arg ): > ? ? ? ? self.value = arg > ? ? ? ? return self.value -1 I explained why deep in the thread but I'll elaborate more here. When I see a def statement, I mentally equate that to an assigment to the thing being def'ed. So for instance, when I see this: def (): I think of it like this: = Thus, if I were to see a function definition like this def foo.bar(): return 1 I would think you were defining a function and assigning it to foo.bar. IOW, it would be mostly equivalent to this: foo.bar = lambda: 1 (Analogously, I would expect a definition like this: def baz[10](): return 1 to be equivalent to this: baz[10] = lambda: 1 ) So, if, inside a class definition, I were to see this: def self.method(): return 1 Well, I'd understand that is was a method assigment, of course, but it would conflict with what I would expect the natural meaning of something like def a.b() would be. The above statement is not equivalent to: self.method = lambda: 1 but I think that's what it ought to be, in general. Carl Banks From david at hlacik.eu Sat Dec 13 14:00:07 2008 From: david at hlacik.eu (=?ISO-8859-2?Q?David_Hl=E1=E8ik?=) Date: Sat, 13 Dec 2008 20:00:07 +0100 Subject: [OT] stable algorithm with complexity O(n) In-Reply-To: <6qidmbFc4qduU1@mid.uni-berlin.de> References: <6qidmbFc4qduU1@mid.uni-berlin.de> Message-ID: > Unless I grossly miss out on something in computer science 101, the lower > bound for sorting is O(n * log_2 n). Which makes your task impossible, > unless there is something to be assumed about the distribution of numbers in > your sequence. There is n numbers from interval [1 , n^2] I should do measurement for : n = 500, 1000, 1500, 2000, ..., 4500, 5000 O(n) means linear complexivity, so complexivity of algorithmus must be linear, which i have to prove. > > Who has given you that assignment - a professor? Or some friend who's > playing tricks on you? It is official assignment , by professor from Data Structures & Algorithms course. Thanks in advance! > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > From exarkun at divmod.com Fri Dec 19 12:38:14 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 19 Dec 2008 12:38:14 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <494BD97F.5080205@gmail.com> Message-ID: <20081219173814.20272.1836750143.divmod.quotient.23074@ohm> On Fri, 19 Dec 2008 10:27:27 -0700, Michael Torrie wrote: >walterbyrd wrote: >> On Dec 19, 9:13 am, "Giampaolo Rodola'" wrote: >>> You can use the old 2.x syntax also in Python 3.x: >> >> Yeah, but it's deprecated, and - as I understand it - may be removed >> completely in future versions. Also, in the future, if you are working >> with code from another developer, it's likely that developer will use >> the new format. I suppose you can use both - but what an awful mess >> that would be. >> >> It seems to me that 3.0 is changing a lot of non-problems. And it's >> going to be slower to boot. > >How is this? With projects like PyPy eventually enabling the JIT'ing of >python3 code, I don't see how this is going to be "slower." If anything >we have a python that can be made to run faster than ever before. What makes you think PyPy is going to enabling JIT'ing of Python 3 code? Perhaps it will, someday, but I suspect it will provide a JIT for Python 2 long before. Jean-Paul From acherry at btinternet.com Tue Dec 23 10:20:05 2008 From: acherry at btinternet.com (Adrian Cherry) Date: 23 Dec 2008 15:20:05 GMT Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: r wrote in news:ae1bb365-7755-4c5f-8166-e704c51a755d at i20g2000prf.googlegro ups.com: > > Oh Steve... Listen, my words are ment as a wake-up-call to > all who still love Python, and i believe you are one of > them. Maybe old age has slowed your hand, that's OK, Us > "youngsters" will take the helm. And be serious, do you > really think this group is read by "hundreds-of- thousands > of news readers? I wish it were, but I highly doubt it. > Thus spake the artilleryman from Horsell Common! Adrian Cherry From bj_666 at gmx.net Sun Dec 14 04:21:19 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 14 Dec 2008 09:21:19 GMT Subject: Optimizing methods away or not? References: <0154b041$0$6988$c3e8da3@news.astraweb.com> <6qk1dhFcr01gU1@mid.uni-berlin.de> Message-ID: <6qk1gfFcr01gU2@mid.uni-berlin.de> On Sun, 14 Dec 2008 09:19:45 +0000, Marc 'BlackJack' Rintsch wrote: > class Parrot: > def __init__(self, *args): > print "Initialising instance..." > assert self.verify() Here I meant ``assert self._verify()`` of course. > def _verify(self): > print "Verifying..." > return None Ciao, Marc 'BlackJack' Rintsch From claird at lairds.us Wed Dec 3 05:09:58 2008 From: claird at lairds.us (Cameron Laird) Date: Wed, 3 Dec 2008 10:09:58 +0000 Subject: Multiple equates References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> <9m3h06-vhh.ln1@lairds.us> Message-ID: In article , Lawrence D'Oliveiro wrote: >Cameron Laird wrote: > >> def f1(Match): >> return > >Something missing here? Ugh; yes, sorry: def shell_escape(Arg) : """returns Arg suitably escaped for use as a command-line argument to Bash.""" pattern = r"[\<\>\"\'\|\&\$\#\;\(\)\[\]\{\}\`\!\~\ \\]" def f1(Match): return "\\" + Match.group(0) return re.sub(pattern, f1, Arg) # Need to catch anything that might be meaningful to shell #end shell_escape From martin at v.loewis.de Sun Dec 21 04:41:40 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 21 Dec 2008 10:41:40 +0100 Subject: Python for amd64 and mingw-w64 In-Reply-To: <5b8d13220812210056r58a01f53h585d59d0bf81e663@mail.gmail.com> References: <494B3F75.10104@v.loewis.de> <5b8d13220812210056r58a01f53h585d59d0bf81e663@mail.gmail.com> Message-ID: <494E0F54.9000907@v.loewis.de> > This is the only problem on python side of things to make extensions > buildable on windows x64 (all the other problems I have encountered so > far to make numpy build with mingw-w64 are numpy's or mingw-w64). Thanks! Martin From excord80 at gmail.com Fri Dec 19 14:43:12 2008 From: excord80 at gmail.com (excord80) Date: Fri, 19 Dec 2008 11:43:12 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: On Dec 19, 11:01?am, walterbyrd wrote: > > To me, it seems that this: > > print "%s=%d" % ('this',99) > > Is much easier, and faster, to type, and is also easier to read and > understand. [snip] > > This (if it's right) is much longer, and requires more special > characters. > > print( "{0}={1}".format('this',99)) > Yeah, I like the old way better too. It's got this nice elegant simplicity to it (using the percent sign for not only the things inside the string, but also to separate it from the tuple that follows). Also, I like having only *one* special symbol (`%') to worry about in my strings instead of two (`{' and `}'). But, Python is Python. So I'll keep using the old way until they deprecate it, and then just get used to the new way. One reason I use Python is because I really *don't* have the time or inclination to question every little design decision and argue about alternatives. If you want to tweak the language to suit your personal tastes, you might prefer Perl 6. From aahz at pythoncraft.com Sun Dec 14 23:56:09 2008 From: aahz at pythoncraft.com (Aahz) Date: 14 Dec 2008 20:56:09 -0800 Subject: Looking for the best way to translate an idiom References: Message-ID: In article , James Stroud wrote: > >In case its not obvious: Ah, so that's where Bruno's extra apostrophe came from! ;-) (Sorry about the spelling flame, but seeing three posts in quick succession with incorrect spelling of its/it's pushed me into making a public comment.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From david_v_wright at yahoo.com Wed Dec 17 12:47:23 2008 From: david_v_wright at yahoo.com (david wright) Date: Wed, 17 Dec 2008 09:47:23 -0800 (PST) Subject: getting object instead of string from dir() Message-ID: <207545.62974.qm@web31805.mail.mud.yahoo.com> --- On Wed, 12/17/08, Rominsky wrote: From: Rominsky Subject: getting object instead of string from dir() To: python-list at python.org Date: Wednesday, December 17, 2008, 12:16 PM I am trying to use dir to generate a list of methods, variables, etc. I would like to be able to go through the list and seperate the objects by type using the type() command, but the dir command returns a list of strings.? When I ask for the type of an element, the answer is always string.? How do I point at the variables themselves.? A quick example is: a = 5 b = 2.0 c = 'c' lst = dir() for el in lst: ? ? print type(el) Right now I am understandably getting all types being output as strings, how do i get the type of the actual objects returned from dir ()? -- http://mail.python.org/mailman/listinfo/python-list Forgive me if you are well aware of this, just thought i'd chime in with the "Duck typing speech": Pythonic programming style that determines an object's type by inspection of its method or attribute signature rather than by explicit relationship to some type object ("If it looks like a duck and quacks like a duck, it must be a duck.") By emphasizing interfaces rather than specific types, well-designed code improves its flexibility by allowing polymorphic substitution. Duck-typing avoids tests using type() or isinstance(). Instead, it typically employs the EAFP (Easier to Ask Forgiveness than Permission) style of programming. http://en.wikipedia.org/wiki/Duck_typing From google at mrabarnett.plus.com Tue Dec 9 09:28:51 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 09 Dec 2008 14:28:51 +0000 Subject: "as" keyword woes In-Reply-To: <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> Message-ID: <493E80A3.1070107@mrabarnett.plus.com> Paul Boddie wrote: > On 9 Des, 14:24, Steven D'Aprano cybersource.com.au> wrote: >> That is not what Guido said. What he actually said was: >> >> "That's possible with sufficiently powerful parser technology, but >> that's not how the Python parser (and most parsers, in my experience) >> treat reserved words." > > I accept that many parsers are operating on predetermined tokens where > keywords will already have been identified as such, regardless of > their eventual syntactic context, by the time the parser gets to see > them. What I wanted to point out was that other approaches are not > exactly unheard of or particularly rare. Every now and again, the > language gets extended and new keywords are sought in an excruciating > process akin to a group writing exercise involving the existing > keywords. A better parsing framework would alleviate these problems. > > [Car analogy cut] > In some languages (I think Delphi is one of them - it's been a while!) some words which would normally be identifiers have a special meaning in certain contexts, but the syntax precludes any ambiguity, and not in a difficult way. "as" in Python was one of those. I certainly wouldn't want something like PL/I, where "IF", "THEN" and "ELSE" could be identifiers, so you could have code like: IF IF = THEN THEN THEN = ELSE; ELSE ELSE = IF; See http://en.wikipedia.org/wiki/PL/I_(programming_language). >> What Guido is saying is that even if he agreed with the OP he couldn't >> add that feature. He's not saying that he agrees with the OP. The Zen >> gives good reasons for believing that even if Python's parser was >> sufficiently powerful, he'd still consider the feature undesirable. > > Well, I think it's more interesting to explore the boundaries of what > can be done, to debunk notions that such things aren't being done in > the mainstream, and to examine whether they could benefit usability, > than it is to defer to the Zen of Python as some kind of prescriptive, > near-religious text at every turn. > > Paul > -- > http://mail.python.org/mailman/listinfo/python-list > From walterbyrd at iname.com Sat Dec 20 18:39:24 2008 From: walterbyrd at iname.com (walterbyrd) Date: Sat, 20 Dec 2008 15:39:24 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> <59153e28-bf86-4158-96d9-23aa5b9f0205@j35g2000yqh.googlegroups.com> Message-ID: <7889a362-d96e-4f1f-a66b-ef52b9cdb047@q26g2000prq.googlegroups.com> On Dec 20, 4:34?pm, r wrote: > Walter, > > Would you be kind enough to translate this code to the new syntax? I am sorry, but I just don't know the new syntax well enough. I am not sure if the examples that I have posted, so far, are correct. From luismgz at gmail.com Fri Dec 12 09:04:39 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Fri, 12 Dec 2008 06:04:39 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> Message-ID: <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> On Dec 12, 10:43?am, sturlamolden wrote: > On Dec 12, 2:29 pm, sturlamolden wrote: > > > Creating a fast implementation of a dynamic language is almost rocket > > science. But it has been done. There is Stronghold, > > I meant of course Strongtalk... Blah, blah, blah... Why don't you guys google a little bit to know what's being done to address python's "slowness"?? It has been mentioned in this thread the pypy project (isn't it enough for you??) Other hints: shedskin, psyco, pyrex... From antoine at vo.lu Sun Dec 7 15:06:28 2008 From: antoine at vo.lu (Antoine De Groote) Date: Sun, 07 Dec 2008 21:06:28 +0100 Subject: Guido's new method definition idea In-Reply-To: <493c1ff6$0$4942$426a34cc@news.free.fr> References: <493a9fed$0$18973$426a34cc@news.free.fr> <493c1ff6$0$4942$426a34cc@news.free.fr> Message-ID: <92c3f$493c2cc2$d9a2276f$18933@news.hispeed.ch> Bruno Desthuilliers wrote: > Daniel Fetchinson a ?crit : > (snip) >> It doesn't add anything but makes something that exists a bit clearer > > Err... I fail to see how magically transforming def self.foo(...) into > def foo(self, ...) makes anything clearer about what really happens and > how Python's object model works. > >> and friendlier to newbies. > > I'd rather say "more acceptable to java-brainwashed developpers". Nicely put! :-) From arnodel at googlemail.com Sun Dec 7 10:14:37 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 07 Dec 2008 15:14:37 +0000 Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> Message-ID: Erik Max Francis writes: [about removing self] > P.S. You're beating a long-dead horse here; your precise proposal has > been brought up countless times on comp.lang.python and shot down > every single time for the same reason. It isn't going to happen. I guess it's part of the process of learning Python :) -- Arnaud From anders.olme at gmail.com Sat Dec 13 05:58:48 2008 From: anders.olme at gmail.com (a_olme) Date: Sat, 13 Dec 2008 02:58:48 -0800 (PST) Subject: Umlauts in idle References: <26880ecf-d0eb-42ab-8ebd-56f64c023999@v39g2000pro.googlegroups.com> <4943829B.9050606@v.loewis.de> Message-ID: On 13 Dec, 10:38, "Martin v. L?wis" wrote: > > When I try to use umlauts in idle it will only print out as Unicode > > escape characters. Is it possible to configure idle to print them as > > ordinary characters? > > Did you really use the print statement? They print out fine for me. > > Regards, > Martin No I just put the characters in quotes like this "???"[::-1] and pressed return. //olme From martin.hellwig at dcuktec.org Wed Dec 17 08:03:39 2008 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 17 Dec 2008 13:03:39 +0000 Subject: [ANN] EuroPython 2009 =?windows-1252?Q?=96_Call_for_Partic?= =?windows-1252?Q?ipation!_?= Message-ID: <4948F8AB.7060809@dcuktec.org> On behalf of the EuroPython 2009 organisation it is my privilege and honour to announce the 'Call for Participation' for EuroPython 2009! EuroPython is the conference for the communities around Python, including the Django, Zope and Plone communities. This year's conference will be held in Birmingham, UK from Monday 29th June to Saturday 4th July 2009. Talks & Themes Do you have something you wish to present at EuroPython? Go to http://www.europython.eu/talks/cfp/ for this year's themes and submissions criteria, the deadline is on 5th April 2009. Other Talks, Activities and Events Have you got something which does not fit the above? Visit http://www.europython.eu/talks/ . Help Us Out We could use a hand any contribution is welcome, please take a look at http://www.europython.eu/contact/ . Sponsors An unique opportunity to affiliate with the prestigious EuroPython conference! http://www.europython.eu/sponsors/ Spread the Word Improve our publicity by distributing this announcement in your corner of the community, please coordinate this with the organizers: http://www.europython.eu/contact/ General Information For more information about the conference, please visit http://www.europython.eu/ Looking forward to see you! The EuroPython Team From rt8396 at gmail.com Tue Dec 2 17:16:45 2008 From: rt8396 at gmail.com (r) Date: Tue, 2 Dec 2008 14:16:45 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> Message-ID: OK...so here are the stat's so far. 6+BDFL - who would support my crazy idea, or think it -might- be ok 11 - who are on the fence 6 - who think this is a complete waste of time, a stupid idea, or just simply want to kill me -> from these stats i can deduce the following: total_members_comp.lang.python = 14433 note: I will be fair and remove spammers or members that don't follow this list anymore by dividing the total number in half.(this should be generous enough) total_actual_members = (14433/2) = 7214 total_num_responders = 11 ->current stats: <11> percentFor = 31 percentNay = 27 percentOnFence = 40 ->Forecast of turnout: <7214> potentialFors = 2,236.34 potentialConverts = 2,885.34 totalPotentials = 5,121.68 even if only 10% of these act...that is 512 people. I still have hope! import hope while hope.amt > 0: continue From castironpi at gmail.com Mon Dec 8 15:09:47 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 8 Dec 2008 12:09:47 -0800 (PST) Subject: appending values into array instead of a list References: Message-ID: <039825e2-3a59-4dd5-9c4b-69b03f3e9fbb@v4g2000yqa.googlegroups.com> On Dec 8, 9:03?am, trias wrote: > Hi, > ?I have this little script: snip > So on the above I am appending values from signaldict indexed by i for every > object in the ref list. This way I calculate the sum of all values with > similar indexing i value. Would I be able to store the signaldict[i] for > every line individually in a multidimensional array? ? I think you want arrays of tuples, not parallel arrays. Just append a tuple instead of a plain number. >>> a= [] >>> a.append( ( 10, -1 ) ) >>> a.append( ( 20, -1.1 ) ) >>> a [(10, -1), (20, -1.1000000000000001)] For true multidimensional arrays of a uniform type, there is 'numpy'. From deets at nospam.web.de Mon Dec 8 16:47:58 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 Dec 2008 22:47:58 +0100 Subject: xml.dom.minidom bug ? In-Reply-To: References: Message-ID: <6q5j0eFaq0g7U1@mid.uni-berlin.de> Sampsa Riikonen schrieb: > Dear All, > > I am experiencing a weird problem with the > xml.dom.minidom module: > ---------------------------------------- > sampsa at linux-ty84:~/python> python easyxml.py > Traceback (most recent call last): > File "easyxml.py", line 1, in > import xml.dom.minidom > File "/usr/lib64/python2.5/site-packages/_xmlplus/dom/__init__.py", line > 236, in > import MessageSource > File "/usr/lib64/python2.5/site-packages/_xmlplus/dom/MessageSource.py", > line 21, in > _ = get_translator("dom") > File "/usr/lib64/python2.5/site-packages/_xmlplus/FtCore.py", line 54, in > get_translator > f = gettext.translation('4Suite', locale_dir).gettext > File "/usr/lib64/python2.5/gettext.py", line 478, in translation > t = _translations.setdefault(key, class_(open(mofile, 'rb'))) > File "/usr/lib64/python2.5/gettext.py", line 180, in __init__ > self._parse(fp) > File "/usr/lib64/python2.5/gettext.py", line 264, in _parse > unpack = struct.unpack > AttributeError: 'module' object has no attribute 'unpack' > ------------------- > > A bug in the module? > > And the weirdest thing is that I figured out how to > get around this problem long time ago, but now I don't > have a clue anymore... :/ > > Any help appreciated. You don't happen to have a struct.py or struct.pyc lying around? To test this, execute *in the same directory your above code fails!!* $ python >>> import struct >>> struct.__file__ The result should be something below /usr/lib/python2.5/, if it's not - that's your culprit. Diez From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 8 04:49:34 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 08 Dec 2008 10:49:34 +0100 Subject: gzip.GzipFile (was Re: Don't you just love writing this sort of thing :)) In-Reply-To: References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: <493cedae$0$2052$426a74cc@news.free.fr> Jorgen Grahn a ?crit : (snip) > > Also, making a decision based on the .gz part of the name isn't > always correct -- you miss files named foo.Z and similar. .tgz anyone ? > /Jorgen > From gabriel.rossetti at arimaz.com Wed Dec 10 03:44:56 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Wed, 10 Dec 2008 09:44:56 +0100 Subject: memory leak? In-Reply-To: References: <493EAB79.6070805@arimaz.com> Message-ID: <493F8188.1030700@arimaz.com> Terry Reedy wrote: > Gabriel Rossetti wrote: > >> I ran these tests on linux 2.6 (ubuntu 8.04) using python 2.5.2. > > Have you tried the much newer 2.6? 2.5.3 will be out soon with some > bug fixes. > Thanks for the reply Terry, I just tried the pyserial example with python 2.6 and it still has the same problem, here's the output (I just copy/pasted the example in a running python2.6 interactive interpreter) : test1 at 09:19am : $ ps waux | grep python2.6 1000 6730 0.2 0.4 6176 4120 pts/12 S+ 09:17 0:00 python2.6 if I try the SIGUSR1 method : $ kill -SIGUSR1 6730 #################################################################### # DEBUG: The object count is : 12536 #################################################################### test2 at 09:25am : $ ps waux | grep python2.6 1000 6730 0.0 0.9 12360 10168 pts/12 S+ 09:17 0:00 python2.6 and the SIGUSR1 method gives me : #################################################################### # DEBUG: The object count is : 25089 #################################################################### I also tried freeing the received string (del t) explicitly but the results are unchanged. Thank you, Gabriel From google at mrabarnett.plus.com Mon Dec 8 17:34:26 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 08 Dec 2008 22:34:26 +0000 Subject: Text parsing via regex In-Reply-To: <9fdb569a0812081259kdafcb96n285419ccaa9d416b@mail.gmail.com> References: <9fdb569a0812081259kdafcb96n285419ccaa9d416b@mail.gmail.com> Message-ID: <493DA0F2.2000000@mrabarnett.plus.com> Vlastimil Brom wrote: > 2008/12/8 Robocop : >> I'm having a little text parsing problem that i think would be really >> quick to troubleshoot for someone more versed in python and Regexes. >> I need to write a simple script that parses some arbitrarily long >> string every 50 characters, and does not parse text in the middle of >> words (but ultimately every parsed string should be 50 characters, >> ... > > Hi, not sure, if I understand the task completely, but maybe some of > the variants below using re may help (depending on what should be done > further with the resulting test segments); > in the first two possibilities the resulting lines are 50 characters > long + 1 for "\n"; possibly 49 would be used if needed. > > > import re > > input_txt = """I'm having a little text parsing problem that i think > would be really > quick to troubleshoot for someone more versed in python and Regexes. > I need to write a simple script that parses some arbitrarily long > string every 50 characters, and does not parse text in the middle of > words (but ultimately every parsed string should be 50 characters, so > adding in white spaces is necessary). So i immediately came up with > something along the lines of:""" > > # print re.sub(r"((?s).{1,50}\b)", lambda m: m.group().ljust(50) + > "\n", input_txt) # re.sub using a function > I also thought of r"(.{1,50}\b)", but then I realised that there's a subtle problem: it says that the captured text should end on a word boundary, when, in fact, we just don't want it to split within a word. It would still be acceptable if it split between 2 non-word characters. Aargh! :-) > # for m in re.finditer(r"((?s).{1,50}\b)", input_txt): # adjusting > the matches via finditer > # print m.group().ljust(50) > > print [chunk.ljust(50) for chunk in re.findall(r"((?s).{1,50}\b)", > input_txt)] # adjusting the matched parts in findall > From deets at nospam.web.de Mon Dec 8 16:38:05 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 Dec 2008 22:38:05 +0100 Subject: ORB for Python and PHP In-Reply-To: References: Message-ID: <6q5idtFb0dk0U1@mid.uni-berlin.de> Laszlo Nagy schrieb: > We have a problem here. We have a website written in PHP. and many > programs written in Python. The communication between the components is > messy. os.system calls are mixed with popen, xml-rpc and others. We > would like to make it consistent and portable. We would like to use free > software. What are our options? I checked these: > > - Bonobo is the most advanced, but it can only handle C language > - FNORB is good for Python, but not for PHP > - OmniORB would be very good for C and Python, but not PHP > > There are others but they do not support both Python and PHP. Should I > implement my own ORB, or do you know a suitable solution? The whole purpose of an ORB ist that it is interoperable. So if you have a good python orb (I personally prefer OmniORB), and a good one for PHP - connect them. I would suggest a consistent XMLRPC-interface though. Diez From cjw at ncf.ca Mon Dec 22 14:28:16 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Mon, 22 Dec 2008 14:28:16 -0500 Subject: Check file is In-Reply-To: <494cbef5$0$90267$14726298@news.sunsite.dk> References: <7caa7d45-ebbe-4c88-bb50-2f01f7315d07@s9g2000prg.googlegroups.com> <494cbef5$0$90267$14726298@news.sunsite.dk> Message-ID: gardsted wrote: > Harish wrote: >> Hi Friends >> Is there any utility in python which will help me to read any pdf >> files? >> >> Regards >> Harish > > Not sure, what you're after exactly, but I tried googling 'python read pdf' > and found this, so maybe 'reportlab' is what you're looking for: > > Re: Reading PDF files > #2 > Dec 20th, 2006 > To read and manage Portable Document Files you can use the open source > ReportLab toolkit (written in Python) from: > http://www.reportlab.org/rl_toolkit.html > > kind regards jorgen The ReportLab toolkit appears to be concerned with building Portable Document Files. I would be interested in any utility which will read any pdf - for example, to convert pdf -> html Colin W. From arnodel at googlemail.com Thu Dec 4 12:31:46 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 04 Dec 2008 17:31:46 +0000 Subject: Overriding a method at the instance level on a subclass of a builtin type References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> Message-ID: "Zac Burns" writes: > The class method seems to be the most promising, however I have more > 'state' methods to worry about so I might end up building new classes > on the fly rather than have a class per permutation of states! Now the > code isn't quite as clear as I thought it was going to be. > > It seems unfortunate to me that methods are always looked up on the > class for new style objects. Was this done for speed reasons? It's only special methods such as __getitem__, ... You can override normal method on a per-object basis just by adding a callable attribute with its name to the object: >>> class A(object): ... def foo(self): print 'A.foo' ... >>> a = A() >>> a.foo() A.foo >>> def a_foo(): print 'a.foo' ... >>> a.foo = a_foo >>> a.foo() a.foo -- Arnaud From arnodel at googlemail.com Wed Dec 10 16:31:49 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 10 Dec 2008 21:31:49 +0000 Subject: [OT] Google Groups in bad odour References: <4d5498bf-bbf0-4760-83fc-610729bcbce2@h20g2000yqn.googlegroups.com> Message-ID: Frank Millman writes: > Hi all > > I know there have been complaints about spam on Google Groups over the > last few months, with some members rejecting all traffic from them. > > You might be interested in this comment I got in a reply from someone > on comp.os.linux.setup - > > "If you want to be read by a wider audience, you really want to post > from > someplace other than Google Groups. Many (most?) readers of the > Linux > lists kill everything from there automatically." > > Unfortunately it seems that their newsgroup does not have a mail > gateway, so I cannot use gmane. (Please correct me if I am wrong). I > will therefore have to find a suitable news client. Any > recommendations? > > Frank Millman I use Gnus, I don't kill posts from groups.google.com and I don't get a lot of spam. When I do I just press 'Laep'. -- Arnaud From robert.kern at gmail.com Thu Dec 18 19:04:19 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 18 Dec 2008 18:04:19 -0600 Subject: Which sparse matrix package? In-Reply-To: <20081218231851.70dd91e2@Schlamber.localdomain> References: <20081218231851.70dd91e2@Schlamber.localdomain> Message-ID: Martin Manns wrote: > Should I use another type of matrix in scipy.sparse? If yes which? If you have a benchmark, you might just want to try all of them. Should be just a matter of a small script. Block Sparse Row (bsr_matrix) might be the most appropriate in terms of data structure, but it appears that a bunch of stuff important for your use case is unimplemented. > Does a different data-structure suit my above-stated needs better? Something similar to a quadtree might be more suitable. That should let you do queries along both dimensions easily. You probably don't want exactly a quadtree, though; it's good for scattered points, but probably not for largish blocks of points on a precise grid, which you will probably see frequently in a spreadsheet application. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From rocky at panix.com Fri Dec 12 23:14:53 2008 From: rocky at panix.com (R. Bernstein) Date: 12 Dec 2008 23:14:53 -0500 Subject: Deeper tracebacks? References: Message-ID: "Gabriel Genellina" writes: .. > No, last_traceback is the last *printed* traceback in the interactive > interpreter. Well more precisely the traceback that is passed to sys.excepthook() when an unhandled exception occcurs, since the hook that might not decide to print anything ;-) > Use the third element in sys.exc_info() instead: Hmm... I'm not sure what I was thinking when I read that way back when, but you are correct and caught a bug in my code. I really do need to do better about writing tests. Maybe next incarnation... Thanks. From google at mrabarnett.plus.com Sat Dec 13 20:29:59 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 14 Dec 2008 01:29:59 +0000 Subject: subprocess to C program In-Reply-To: <0ebd59c5-95a1-42d4-b597-d1c248490b8e@y1g2000pra.googlegroups.com> References: <0ebd59c5-95a1-42d4-b597-d1c248490b8e@y1g2000pra.googlegroups.com> Message-ID: <49446197.6020607@mrabarnett.plus.com> Aaron Brady wrote: > Hi, > > I am writing a C process and I want to read data from a file that I > write to in Python. I'm creating a pipe in Python, passing it to the > C process, and calling '_read'. It gives me error 9, bad file number. > > Python code: > > import subprocess as s, os > r, w= os.pipe( ) > os.write( w, 'abcdefghij\n' ) > a= s.Popen( [ r'C:\Documents and Settings\usr\Desktop\working > \try_start', '%i'%r, '%i'%w ] ) > > C code: > > char buf[ 16 ]; > memset( buf, 0, 16 ); > int readfd= atoi( argv[ 1 ] ); > int ct= _read( readfd, buf, 15 ); > printf( "\n\n'_read %i %i %i': %s\n", ct, readfd, errno, buf ); > > Output: > > '_read -1 3 9' > > meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9. I want 'ct' > to be 11 at this point. Thanks in advance. > It looks like the ids aren't system global. From prologic at shortcircuit.net.au Wed Dec 17 18:34:12 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 18 Dec 2008 09:34:12 +1000 Subject: The rule of literal string In-Reply-To: <47c890dc0812171525t527353e2m5c8b0597ee183e21@mail.gmail.com> References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> <_PmdnU59w62vGtTUnZ2dnUVZ_hSdnZ2d@pdx.net> <34028b73-7807-4e88-80bc-fe31a7b1a2a0@i20g2000prf.googlegroups.com> <47c890dc0812171525t527353e2m5c8b0597ee183e21@mail.gmail.com> Message-ID: On Thu, Dec 18, 2008 at 9:25 AM, Chris Rebert wrote: > As I stated previously, the key rule is: > > eval(repr(something)) == something This rule is only true for basic data types; For example: >>> eval(repr(1)) == 1 True >>> eval(repr([1, 2, 3])) == [1, 2, 3] True >>> eval(repr({"a": 1, "b": 2, "c": 3})) == {"a": 1, "b": 2, "c": 3} True >>> eval(repr("foo")) == "foo" True I guess the key thing here is that the repr implementation (__repr__) for str, int, float list and dict return sensible represenations that Python _can_ evaluate with eval(...) --JamesMills From tjreedy at udel.edu Tue Dec 9 13:18:26 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 09 Dec 2008 13:18:26 -0500 Subject: Python 3 For Python 2 Users In-Reply-To: References: Message-ID: Tim Daneliuk wrote: > I code in Python 2.x intermittently and have only casually watched the > 3.x development discussions. Now it's time to get up to speed. > Has someone written a tutorial for people in my situation. Yes, I've > looked at the release notes, but I'm looking for something that > motivates all the major changes to give me a better sense of the > Gestalt of the new language. All classes are subclasses of object. Text strings are unicode. Miscellaneous deletions. Some new stuff, especially ABCs, though it may be awhile before they really inpact Python practice. From iofferkicks24 at gmail.com Thu Dec 25 00:36:11 2008 From: iofferkicks24 at gmail.com (www.iofferkicks.com) Date: Wed, 24 Dec 2008 21:36:11 -0800 (PST) Subject: www.iofferkicks.com china cheap wholesale nike shoes,air jordan shoes,air force one shoes. Message-ID: <3308d5ee-ff78-4126-b314-a5dfa9516b88@l33g2000pri.googlegroups.com> Get Nike Shoes at Super Cheap Prices Discount Nike air jordans (www.iofferkicks.com) Discount Nike Air Max 90 Sneakers (www.iofferkicks.com) Discount Nike Air Max 91 Supplier (www.iofferkicks.com) Discount Nike Air Max 95 Shoes Supplier (www.iofferkicks.com) Discount Nike Air Max 97 Trainers (www.iofferkicks.com) Discount Nike Air Max 2003 Wholesale (www.iofferkicks.com) Discount Nike Air Max 2004 Shoes Wholesale (www.iofferkicks.com) Discount Nike Air Max 2005 Shop (www.iofferkicks.com) Discount Nike Air Max 2006 Shoes Shop (www.iofferkicks.com) Discount Nike Air Max 360 Catalogs (www.iofferkicks.com) Discount Nike Air Max Ltd Shoes Catalogs (www.iofferkicks.com) Discount Nike Air Max Tn Men's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 2 Women's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 3 Customize (www.iofferkicks.com) Discount Nike Air Max Tn 4 Shoes Customize ( www.iofferkicks.com) Discount Nike Air Max Tn 6 Supply (www.iofferkicks.com) Discount Nike Shox NZ Shoes Supply (www.iofferkicks.com) Discount Nike Shox OZ Sale (www.iofferkicks.com) Discount Nike Shox TL Store (www.iofferkicks.com) Discount Nike Shox TL 2 Shoes Store (www.iofferkicks.com) Discount Nike Shox TL 3 Distributor (www.iofferkicks.com) Discount Nike Shox Bmw Shoes Distributor (www.iofferkicks.com) Discount Nike Shox Elite Shoes Manufacturer (www.iofferkicks.com) Discount Nike Shox Monster Manufacturer (www.iofferkicks.com) Discount Nike Shox R4 Running Shoes (www.iofferkicks.com) Discount Nike Shox R5 Mens Shoes (www.iofferkicks.com) Discount Nike Shox Ride Womens Shoes (www.iofferkicks.com) Discount Nike Shox Rival Shoes Wholesaler (www.iofferkicks.com) Discount Nike Shox Energia Wholesaler (www.iofferkicks.com) Discount Nike Shox LV Sneaker (www.iofferkicks.com) Discount Nike Shox Turbo Suppliers (www.iofferkicks.com) Discount Nike Shox Classic Shoes Suppliers (www.iofferkicks.com) Discount Nike Shox Dendara Trainer (www.iofferkicks.com) Discount Nike Air Jordan 1 Seller (www.iofferkicks.com) Discount Nike Air Jordan 2 Shoes Seller (www.iofferkicks.com) Discount Nike Air Jordan 3 Collection (www.iofferkicks.com) Discount Nike Air Jordan 4 Shoes Collection (www.iofferkicks.com) Discount Nike Air Jordan 5 Chaussure Shoes (www.iofferkicks.com) Discount Nike Air Jordan 6 Catalog (www.iofferkicks.com) Discount Nike Air Jordan 7 Shoes Catalog (www.iofferkicks.com) Discount Nike Air Jordan 8 Customized (www.iofferkicks.com) Discount Nike Air Jordan 9 Shoes Customized (www.iofferkicks.com) Discount Nike Air Jordan 10 Wholesalers (www.iofferkicks.com) Discount Nike Jordan 11 Shoes Wholesalers (www.iofferkicks.com) Discount Nike Air Jordan 12 Factory (www.iofferkicks.com) Discount Nike Air Jordan 13 Shoes Factory (www.iofferkicks.com) Discount Nike Air Jordan 14 Shoes Sell (www.iofferkicks.com) Discount Nike Air Jordan 16 Exporter (www.iofferkicks.com) Discount Nike Air Jordan 17 Shoes Exporter (www.iofferkicks.com) Discount Nike Air Jordan 18 Offer (www.iofferkicks.com) Discount Nike Air Jordan 19 Shoes Offer (www.iofferkicks.com) Discount Nike Air Jordan 20 Manufacture (www.iofferkicks.com) Discount Nike Jordan 21 Shoes Manufacture (www.iofferkicks.com) EMAIL:IOFFERKICKS at GMAIL.COM MSN :IOFFERKICKS at MSN.COM From andre.roberge at gmail.com Wed Dec 17 22:34:44 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Wed, 17 Dec 2008 19:34:44 -0800 (PST) Subject: getting object instead of string from dir() References: <477b9c2e-a0ab-4b26-b643-4a9369c2aaac@r2g2000vbp.googlegroups.com> Message-ID: On Dec 17, 3:52?pm, Rominsky wrote: > > I do have some understanding of the pythonic methodology of > programming, though by far I still don't consider myself an expert. > The problem at hand is that I am coming from a matlab world and trying > to drag my coworkers with me. ?I have gotten a lot of them excited > about using python for this work, but the biggest gripe everytime is > they want their matlab ide. ?I am trying to experiment with making > similar pieces of the ide, in particular I am working on the workspace > window which lists all the current variables in the namespace, along > with their type, size, value, etc.... ?I am trying to create a python > equivalent. ? You might want to have a look at http://www.physics.ox.ac.uk/users/santoso/Software.WebLab.html Andr? From jstroud at mbi.ucla.edu Fri Dec 5 05:13:49 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 05 Dec 2008 02:13:49 -0800 Subject: dict subclass and pickle bug (?) Message-ID: Hello All, I subclassed dict and overrode __setitem__. When instances are unpickled, the __setstate__ is not called before the keys are assigned via __setitem__ in the unpickling protocol. I googled a bit and found that this a bug filed in 2003: http://bugs.python.org/issue826897 It is still "open" with "normal" priority. Am I missing something? Is there a workaround for this bug that makes fixing it pointless or has it just fallen through the cracks for the last 5 years? Here is an example: class DictPlus(dict): def __init__(self, *args, **kwargs): self.extra_thing = ExtraThingClass() dict.__init__(self, *args, **kwargs) def __setitem__(self, k, v): do_something_with(self.extra_thing, k, v) dict.__setitem__(self, k, v) Upon unpickling, the error would be: AttributeError: 'DictPlus' object has no attribute 'extra_thing' I'm still using python 2.5.1. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From george.sakkis at gmail.com Sun Dec 7 13:53:58 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 7 Dec 2008 10:53:58 -0800 (PST) Subject: how to get a beep, OS independent ? References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> Message-ID: On Dec 7, 7:49?am, Stef Mientki wrote: > Chris Rebert wrote: > > On Sun, Dec 7, 2008 at 1:27 AM, Stef Mientki wrote: > > >> Rainy wrote: > > >>> On Dec 6, 3:40 pm, Stef Mientki wrote: > > >>>> hello, > > >>>> I want to give a small beep, > >>>> for windows there's message-beep, > >>>> and there seems to be something like " curses" , > >>>> but that package seems to be totally broken in P2.5 for windows. > > >>>> Any other suggestions ? > > >>>> thanks, > >>>> Stef Mientki > > >>> For win there's winsound, you have to check sys.platform and do > >>> what's necessary for the platform in question. In linux I think > >>> you can just print '\a' (or does that only work in terminals?). > >>> If you know that ext. speakers are always on, you can do a nicer > >>> beep by using some wav file, in linux it's probably easiest to > >>> use an external program to play it, like wavplay. Basically, > >>> there is no single answer, it depends on circumstances. > >>> -- > >>>http://mail.python.org/mailman/listinfo/python-list > > >> '\a' or chr(7) prints an inverted "BEL". > > > Inverted bell? > > In the output window (stdout) which is black letters on white background, > it prints "bell" in white letters with a black background.> ?What do you mean? And what version dependency are you > > referring to? > > Well some of you actually hear something, > I don't, > so I expect that the Python version differs. Works for me on WinXP, Python 2.5: C:\>python -c "print chr(7)" makes a beep. George From nick at craig-wood.com Wed Dec 3 04:32:50 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 3 Dec 2008 09:32:50 +0000 Subject: Do more imported objects affect performance In-Reply-To: <493602CB.2020907@holdenweb.com> References: <1be78d220812010621u51dead9dnbaa0b4c8c9414362@mail.gmail.com> <493602CB.2020907@holdenweb.com> Message-ID: <20081203093250.GA17602@craig-wood.com> On Tue, Dec 02, 2008 at 10:53:47PM -0500, Steve Holden wrote: > Pardon me for intruding, but timings here are entirely the wrong focus > for a Python newcomer. Given that imports are super-optimized (i.e. the > code in the module is only performed once) such a small difference in > timing is inconsequential, I would suggest. > > As long as "from module import *" is only ever used with modules > specifically designed to support it, the other forms can be used as > required. Sure, there is a timing difference between > > import module > ... > module.something() > > and > > from module import something > ... > something() > > but that's hardly the point. Learning to write sound Python is *much* > more important that learning to write fast Python, and often the two > coincide anyway. > > It was true when Kernighan and Plauger wrote it forty years ago and it's > true now: "First, make it work. Then, *if it doesn't work fast enough*, > make it work faster". You are 100% right of course Steve. I was just trying to answer the specific question "which is faster" question which probably isn't helpful for new Python programmers to focus on. PS I enjoyed your book :-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From sjmachin at lexicon.net Mon Dec 8 23:44:53 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 8 Dec 2008 20:44:53 -0800 (PST) Subject: How to initialize a class variable once References: Message-ID: <804363f5-458a-4e72-8b2f-ad9c3c28b6cb@s9g2000prg.googlegroups.com> On Dec 9, 3:36?pm, Matimus wrote: > On Dec 8, 8:08?pm, Roy Smith wrote: > > > I've got a class with a class variable: > > > class Foo: > > ? ?_map = {} > > > How do I make sure this only gets initialized the *first* time the > > module containing the class is imported? ?What appears to be happening > > as it stands is each time the module gets imported, Foo._map get re- > > initialized. > > Unless you are calling reload() on the module, it will only ever get > _loaded_ once. Each additional import will just yield the existing > module. Perhaps if you post an example of the behavior that leads you > to believe that the class variables are getting reinitialized and change it to class Foo(object): because we care little about old-style classes these days and put a print statement in the module just before the class statement and print statements before and after each import statement so that we can see what is happening. From vedranf at vedranf.mine.nu Fri Dec 19 06:57:35 2008 From: vedranf at vedranf.mine.nu (=?ISO-8859-1?Q?Vedran_Furac=28?=) Date: Fri, 19 Dec 2008 12:57:35 +0100 Subject: List comprehension in if clause of another list comprehension In-Reply-To: References: Message-ID: Peter Otten wrote: > The problem is that list comprehensions do not introduce a new namespace. So > the inner and the outer list comp share the same i. You can either rename > the inner i > >>>> [i for i in a if i not in [k for k in b]] > ['b'] > > or use a generator expression which does give a new namespace: > >>>> list(x for x in "abc") > ['a', 'b', 'c'] >>>> x > Traceback (most recent call last): > File "", line 1, in > NameError: name 'x' is not defined > >>>> [i for i in a if i not in (i for i in b)] > ['b'] Thanks! From gagsl-py2 at yahoo.com.ar Tue Dec 9 01:51:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Dec 2008 04:51:14 -0200 Subject: close has no effect on Mac OSX Python 3.0 References: <83b43edf-81e5-4116-ad7b-2dcacde2d101@f3g2000yqf.googlegroups.com> Message-ID: En Mon, 08 Dec 2008 20:09:23 -0200, resi147 escribi?: > I'm wondering if it's really a bug since it's so trivial: > > fp = open('/etc/services') > ct = fp.read(1048) > print(ct[-80:], end='') > fp.close() > ct = fp.read(17) > print(ct) > > the second read should fail, but happily continues reading the file. > Really a bug? Looks like a real bug to me. In fact it is already reported: http://bugs.python.org/issue4604 -- Gabriel Genellina From lewis.sarah93 at yahoo.com Thu Dec 4 23:56:37 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 20:56:37 -0800 (PST) Subject: Earn Serous money Message-ID: <24612aa6-38dc-4695-b67e-b72a1b636a1d@d14g2000yqb.googlegroups.com> Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From almar.klein at gmail.com Mon Dec 1 03:38:30 2008 From: almar.klein at gmail.com (Almar Klein) Date: Mon, 1 Dec 2008 09:38:30 +0100 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: I did some image processing in Mathematica once. It allocated 2GB of memory to do display a normal size image. The professor (not of my university) who gave the course I was following then, was a big Mathematica fan. He also used lots of sentences containing "quite striking", "highly efficient", "extreme" and other power-terms. I know see whom he got it from. When I hear a person talk like that for long enough, everything he says starts to sound like lies. One good example was the bold statement that Mathematica is MUCH faster than Matlab. Clearly, when considering low level task like convolution both programs will use efficient C implementations, and I can't imagine one being faster than the other. Personally, I liked Mathematica for symbolic calculations, but for numerical stuff, frankly, it sucks. Glad to get that off my chest. Cheers, Almar 2008/12/1 Xah Lee > On Nov 30, 7:30 pm, Xah Lee wrote: > > Wolfram Research's Mathematica Version 7 has just been released. > > > > See: http://www.wolfram.com/products/mathematica/index.html > > > > Among it's marketing material, it has a section on how mathematica > > compares to competitors. > http://www.wolfram.com/products/mathematica/analysis/ > > Stephen Wolfram has a blog entry about Mathematica 7. Quite amazing: > > http://blog.wolfram.com/2008/11/18/surprise-mathematica-70-released-today/ > > Mathematica today in comparsion to all other existing langs, can be > perhaps compared to how lisp was to other langs in the say 1980s: > Quite far beyond all. > > Seeing how lispers today still talking about how to do basic list > processing with its unusable cons, and how they get giddy with 1980's > macros (as opposed to full term rewriting), and still lack pattern > matching, one feels kinda sad. > > see also: > > ? Fundamental Problems of Lisp > http://xahlee.org/UnixResource_dir/writ/lisp_problems.html > > Xah > ? http://xahlee.org/ > > ? > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gh at ghaering.de Thu Dec 4 08:13:37 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 04 Dec 2008 14:13:37 +0100 Subject: Pythonic design patterns In-Reply-To: References: Message-ID: Slaunger wrote: > Hi comp.lang.python > > I am this novice Python programmer, who is not educated as a computer > scientist (I am a physicist), and who (regrettably) has never read the > GOF on design patterns. [...] > I guess I could boost my productivity by learning these well-proven > and well-established design patterns by heart. At least for me I only getter better by actually training. For programming this means: write code. Revisit it later, improve on it. Of course one often wants to apply all cool new tricks you've learnt. That's normal, but remember: """ Brian Kernighan Law of Debugging Difficulty Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -- Brian Kernighan """ > I was therefore wondering if you could recommend a book or a resource > concerning design patterns with special focus on the possibilities in > Python? [...] I have this in my bookmarks: http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html -- Gerhard From martin.hellwig at dcuktec.org Sat Dec 6 13:46:47 2008 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Sat, 06 Dec 2008 18:46:47 +0000 Subject: Learning Python now coming from Perl In-Reply-To: <493ac32b$0$30907$426a74cc@news.free.fr> References: <493ac32b$0$30907$426a74cc@news.free.fr> Message-ID: <493ac897$0$190$e4fe514c@news.xs4all.nl> News123 wrote: > > What's more painful is to learn which functianilty is in which library > and which library exists. > Yes and one mistake I still often find myself doing is, when confronted with a particular problem, that I write some helper code to deal with it. Of course later on I discover that there is a standard module or built-in that does exactly what I want and better. :-) Somehow in the heat of the moment my mind is not thinking 'there must be something out there which does what I want' but rather 'hmmm I think I can do it this way, clicker-di-click'. In my opinion it is a positive attribute to the language that it makes solving problems so easy that you forget about searching for solutions. Maybe python should prompt every 10 lines of code a message saying 'Are you sure this can not be done with a built-in?' Most of the time it will be right anyway :-) -- mph From jpablo.romero at gmail.com Tue Dec 9 08:32:46 2008 From: jpablo.romero at gmail.com (=?ISO-8859-1?Q?Juan_Pablo_Romero_M=E9ndez?=) Date: Tue, 9 Dec 2008 07:32:46 -0600 Subject: Compiling and installing python 2.5.2 with Visual C++ 2008 Message-ID: Hello all, I need to compile python myself because of a module (pivy). So I downloaded MS Visual C++ 2008 express edition. It apparently compiled fine but I don't know how to install it to recreate the standard distribution. In linux i'd take "make install", but on windows? Regards, Juan Pablo From kenneth.m.mcdonald at sbcglobal.net Sun Dec 28 18:22:47 2008 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Sun, 28 Dec 2008 17:22:47 -0600 Subject: Any equivalent to Ruby's 'hpricot' html/xpath/css selector package? Message-ID: <6AA1A7D9-FA43-4413-9041-D5D2CB6EFE6F@sbcglobal.net> Ruby has a package called 'hpricot' which can perform limited xpath queries, and CSS selector queries. However, what makes it really useful is that it does a good job of handling the "broken" html that is so commonly found on the web. Does Python have anything similar, i.e. something that will not only do XPath queries, but will do so on imperfect HTML? (A good HTML neatener would also be fine, of course, as I could then pass the result to a Python XPath package.) And, what are people's favorite Python XPath solutions? Thanks, Ken McDonald From python.list at tim.thechases.com Wed Dec 10 14:33:19 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 10 Dec 2008 13:33:19 -0600 Subject: Python is slow In-Reply-To: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: <4940197F.8050705@tim.thechases.com> [nibbling a little flame-bait] > Python is even slower than PHP! > > Just go to any Python website and you will know. > An example is: > http://www2.ljworld.com/ I'm not sure I'm seeing what you're seeing -- the dynamic page loaded in under 2 seconds -- about on par with sun.com, python.org, php.net or msn.com all being pulled from non-cached servers. You sure you're not mistaking your bandwidth and/or browser-rendering slowness for Python-as-a-web-server slowness? Would it be nice if Python was faster? Sure, why not? Does it meet my needs speed-wise? 99% of the time, yes. With Psyco, 99.9% of the time. As has been shown repeatedly over the last couple months, algorithm-choice makes a far greater impact than some python tweaks. Most of my time spent waiting is usually on I/O (disk, network, or user). And those times I've experienced slowness where I'm not waiting on I/O, it's always been an algorithm aspect (an O(N**2) fuzzy comparison algorithm is my prime offender). A faster Python might shave a 30-60 seconds off a 10 minute run, but it's still a walk around the office either way. > Python is slow. Very slow. However until you have a use-case that *you* have implemented with *real code*, publicly vetted the algorithm, and THEN find it slow as demonstrated by profiled timings, I'm afraid it's all just unsubstantiated hot air to say categorically that "python is slow". It might be "too slow to do some particular CPU-intensive task", but it's repeatedly proven quite sufficient for a wide variety of development needs. -tkc From steve at holdenweb.com Tue Dec 9 23:31:55 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 09 Dec 2008 23:31:55 -0500 Subject: what's so difficult about namespace? In-Reply-To: <7480c61b-cece-47f8-9833-f739312a9e68@a3g2000prm.googlegroups.com> References: <67b23938-1761-4bd7-92b4-6972a73fedb6@d42g2000prb.googlegroups.com> <4491627a-eb71-4c2e-81cd-2b9a9bdbcdb6@r15g2000prd.googlegroups.com> <7480c61b-cece-47f8-9833-f739312a9e68@a3g2000prm.googlegroups.com> Message-ID: Xah Lee wrote: [...] > Steve Holden wrote: >> And therein lies the danger of imagination. > >> Typically the namespace components are looked up one by one, so for >> >> this.that.theother >> >> first "this" will be looked up and (hopefully) yield an object with a >> namespace, which will then be searched for "that", yielding another >> object with a namespace in which "theother" can be looked up. That's >> certainly how it works in Python: > > yes, but Steve, what is your point? > > The question is, what is the technical difficulty, if any, of > introducing namespace into a existing language. > > You pointed out that identifier lookup at least from the perspective > of language user is somewhat like a tree walking processing. However, > that does not answer the main question. > Yawn. My point was you oversimplified the problem due to your ignorance of the issues. You are a good writer when you stick to what you know and avoid the rabid profanity. Unfortunately that doesn't happen often enough for my taste. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From stef.mientki at gmail.com Fri Dec 26 19:41:40 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 27 Dec 2008 01:41:40 +0100 Subject: Is there a function to remove escape characters from a string ? In-Reply-To: <5a29b62a-c38f-409b-8887-6259ad072bf5@w1g2000prk.googlegroups.com> References: <0163882f$0$6988$c3e8da3@news.astraweb.com> <5a29b62a-c38f-409b-8887-6259ad072bf5@w1g2000prk.googlegroups.com> Message-ID: <495579C4.7050502@gmail.com> John Machin wrote: > On Dec 27, 12:05 am, Stef Mientki wrote: > > >> Yep, chr(254), because it's not in the human range of characters >> and it's accepted by windows ini-files. >> > > >>>> import unicodedata as ucd >>>> for i in (0,1,2,3,4,7,8): >>>> > ... s = chr(254) > ... enc = 'cp125' + str(i) > ... try: > ... u = s.decode(enc) > ... except UnicodeDecodeError: > ... continue > ... print enc, 'U+%04X' % ord(u), ucd.name(u) > ... > cp1250 U+0163 LATIN SMALL LETTER T WITH CEDILLA > cp1251 U+044E CYRILLIC SMALL LETTER YU > cp1252 U+00FE LATIN SMALL LETTER THORN > cp1253 U+03CE GREEK SMALL LETTER OMEGA WITH TONOS > cp1254 U+015F LATIN SMALL LETTER S WITH CEDILLA > cp1257 U+017E LATIN SMALL LETTER Z WITH CARON > cp1258 U+20AB DONG SIGN > > Either you have a strange and narrow definition of "human", or you are > so brave as to cheerfully insult (inter alia) Romanians, Russians, > Icelanders, Greeks, Turks, Czechs, Estonians, Finns, Slovaks, > Slovenians, and Vietnamese :-) > Sorry if I offended someone, that was certainly not my intention. And I guess you will be surprised, if I tell you, I don't (want) to understand any bit of the above code ;-) Come on, the home computer was invented about 1980. If we look at hardware, it follows the Moore's law, for software I would expect at least 0.1 of Moore's law ;-) I hope that clarifies my point. cheers, Stef From greg at cosc.canterbury.ac.nz Thu Dec 11 18:46:22 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 12 Dec 2008 12:46:22 +1300 Subject: Preventing execution of a method In-Reply-To: References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> <764daeef-bfbe-411a-8521-bb114321e4ac@b38g2000prf.googlegroups.com> <19304f8c-e34f-4aa9-8df2-6a7d3553007a@e1g2000pra.googlegroups.com> <2eed8876-94d2-4304-88a5-eb4a78b4f41d@33g2000yqm.googlegroups.com> <307fe197-1b42-4305-af0e-94b7ebe3ce70@r15g2000prh.googlegroups.com> <49417c59$0$8491$426a74cc@news.free.fr> Message-ID: <6qdmthFc5ggdU1@mid.individual.net> Emanuele D'Arrigo wrote: > -IF- the application was single-user yes, it wouldn't be a big deal. > But as it is potentially multi-user, I don't want one party to corrupt > the application for everybody else. In that case you definitely want a client-server architecture, with the server managing all the critical data. -- Greg From cmgui2 at gmail.com Mon Dec 22 13:42:49 2008 From: cmgui2 at gmail.com (cm_gui) Date: Mon, 22 Dec 2008 10:42:49 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> <6r6hpfFfb643U3@mid.uni-berlin.de> <494E6FDA.4070401@mrabarnett.plus.com> <4585c27d-d7a9-480f-991c-a869161be55c@g38g2000yqn.googlegroups.com> <3392a51b-d3fd-4986-9c59-fecccc7272da@p2g2000prn.googlegroups.com> Message-ID: <6aad831b-80ce-40df-9b6e-571b1e822795@s1g2000prg.googlegroups.com> On Dec 22, 6:51?am, Lou Pecora wrote: > In article , > ?"James Mills" wrote: > > > In case anyone is not aware, Python is > > also used for heavy scientific computational > > problems, games such as Civilisation and > > others, and I believe (correct me if I"m wrong) > > it's also used by NASA. > > > --JamesMills > i am referring mainly to Python for web applications. Python is slow. > Python has become very popular in scientific computation. ?You'll find > it in use lots of places (universities, national labs, defense labs). ?I > use it for solving partial differential equations for quantum chaos > calculations and went to C for speed up where needed using ctypes which > is very straightforward and plays nice with numpy array/matrix > libraries. ?I've been doing scientific programming for 30 years. ?Python > with C extensions and libraries is the best approach I've ever used. ? > Calculation speed is not a problem and the code can be "tweaked" to > increase it easily. ?Programming speed is incredible. ?I can get > substantial object oriented code up and running much faster than > anything I've ever used. > > -- > -- Lou Pecora From martin at v.loewis.de Fri Dec 19 01:30:13 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Fri, 19 Dec 2008 07:30:13 +0100 Subject: Python for amd64 and mingw-w64 In-Reply-To: References: Message-ID: <494B3F75.10104@v.loewis.de> > - Any extension requires the MS_WIN64 to be defined, but this symbol > is only defined for MS compiler (in PC/pyport.h). Why do you say that? It is only defined when _WIN64 is defined; this has nothing to do with a MS compiler. > Shouldn't it be > defined independantly of the compiler ? You mean, completely unconditional? Definitely not, it should only be defined when you are compiling for 64-bit mode. > - I have some link problems related to Py_InitModule4_64. I believe > the problem is in libpython26.a, which according to nm does not have > this symbol defined, whereas python26.dll has. It's a mistake if libpython26.a gets included in the Win64 installer at all; this library is only provided for 32-bit systems. My copy of mingw doesn't support Win64 at all. Regards, Martin From castironpi at gmail.com Sat Dec 13 21:54:37 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 13 Dec 2008 18:54:37 -0800 (PST) Subject: subprocess to C program References: <0ebd59c5-95a1-42d4-b597-d1c248490b8e@y1g2000pra.googlegroups.com> <8MidneyhDfIG-9nUnZ2dnUVZ_uadnZ2d@posted.visi> Message-ID: <36656830-63a8-479c-8c46-525f2b55eeea@z28g2000prd.googlegroups.com> On Dec 13, 7:51?pm, Grant Edwards wrote: > On 2008-12-14, MRAB wrote: > > > > >> I am writing a C process and I want to read data from a file that I > >> write to in Python. ?I'm creating a pipe in Python, passing it to the > >> C process, and calling '_read'. ?It gives me error 9, bad file number. snip > >> meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9. ?I want 'ct' > >> to be 11 at this point. ?Thanks in advance. > > > It looks like the ids aren't system global. > > They certainly aren't in Unix: Their a property of the process. > > -- > Grant I'm not on Unix. It has to be possible somehow. Do I need to set permissions on the IDs? Are Stdin and Stdout my only options? Or does Popen prevent sharing IDs somehow? From jstroud at mbi.ucla.edu Mon Dec 15 03:53:53 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 15 Dec 2008 00:53:53 -0800 Subject: alt.possessive.its.has.no.apostrophe In-Reply-To: <87r649g9dg.fsf@benfinney.id.au> References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > James Stroud writes: > >> Ben Finney wrote: >>> James Stroud writes: >>> >>>> Yes. I think it was the British who decided that the apostrophe >>>> rule for "it" would be reversed from normal usage relative to >>>> just about every other noun. > > It also seems an indefensible claim to say that anyone ?decided? it > would be that way, especially ?the British?. > >>> Remember that ?it? is a pronoun. I see no reversal: >> Ok. Pronouns are reversed. > > Or, more generally: Pronouns, which are different in just about every > other way from other nouns, are different in this way also. Is that > about right? > Can we start talking about python again? -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From rt8396 at gmail.com Fri Dec 12 12:59:55 2008 From: rt8396 at gmail.com (r) Date: Fri, 12 Dec 2008 09:59:55 -0800 (PST) Subject: newbie question... References: Message-ID: yes, but your script will need to know hoe to handle this.the following will open a file who's name was passed to the script if len(sys.argv) > 1: try: open_file(fname=sys.argv[1]) except: pass From manu3d at gmail.com Thu Dec 11 19:33:02 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 11 Dec 2008 16:33:02 -0800 (PST) Subject: Bidirectional Networking Message-ID: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> Hi everybody! A networking question! I've been looking at and tinkering a little with the various networking modules in python. The examples are pretty clear and a module such as the SimpleXMLRPCServer is actually simple! All the examples though are based on a client interrogating a server, with the client initiating the connection, obtaining something and then closing the connection. Basically the server is a reactive party: only if the client get in touch the server respond. What if the server wanted to notify the client of something of interest, i.e. new data that the client should take into consideration and potentially process? One option would be for the client to periodically poll the server for changes. Fair enough, that would work. But it'd be a bit of a waste if the changes aren't particularly frequent. Is it possible then to establish both a server and a client in the same application? I guess it must be possible but the examples all rely on some kind of server loop (i.e. SocketServer.serve_forever) that if started on both client and server sides would create two listening parties but no talking at all! Furthermore, other libraries might have their own loop, i.e. a graphical client has a loop to redraw the screen and the two loops would somehow have to be interleaved. I'm not quite seeing how this can be done other than we threads. Is that the way to do it? Place the listening loop in a thread while the rest of the application does its own thing? Or is it SocketServer.handle_request() the key? I could call this function periodically, but what happens if a request is made while the application is doing something else? Are the requests queued and dealt with one per loop? Thanks for your help! Manu From jspies at sun.ac.za Tue Dec 9 03:26:02 2008 From: jspies at sun.ac.za (Johann Spies) Date: Tue, 9 Dec 2008 10:26:02 +0200 Subject: Announcement: MindTree for Python beta -- feedback appreciated In-Reply-To: <20841316.post@talk.nabble.com> References: <20841316.post@talk.nabble.com> Message-ID: <20081209082602.GC25955@sun.ac.za> > The MindTree project can be found and downloaded here: > http://code.google.com/p/mindtree/ > I suppose it might be a python3-problem: % /usr/local/bin/python3.0 MindTree.pyw Traceback (most recent call last): File "MindTree.pyw", line 2, in from future_builtins import * ImportError: No module named future_builtins Regards Johann -- Johann Spies Telefoon: 021-808 4036 Informasietegnologie, Universiteit van Stellenbosch "Let not sin therefore reign in your mortal body, that ye should obey it in the lusts thereof." Romans 6:12 From xahlee at gmail.com Wed Dec 3 18:26:26 2008 From: xahlee at gmail.com (Xah Lee) Date: Wed, 3 Dec 2008 15:26:26 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> Message-ID: <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> > I'll pay $20 to see your improved version of the code. The only > references to PayPal I saw on your website were instructions to direct > the payment to x... at xahlee.org, please let me know if that is correct. > > What I want in return is you to execute and time Dr. Harrop's original > code, posting the results to this thread. Then, I would like you to > post your code with the timing results to this thread as well. > > By Dr. Harrop's original code, I specifically mean the code he posted > to this thread. I've pasted it below for clarity. Agreed. My paypal address is ?xah @@@ xahlee.org?. (replace the triple @ to single one.) Once you paid thru paypal, you can post receit here if you want to, or i'll surely acknowledge it here. Here's what i will do: I will give a version of Mathematica code that has the same behavior as his. And i will give timing result. The code will run in Mathematica version 4. (sorry, but that's what i have) As i understand, Jon is running Mathematica 6. However, i don't see anything that'd require Mathematica 6. If my code is not faster or in other ways not satisfactory (by your judgement), or it turns out Mathematica 6 is necessary, or any problem that might occure, i offer money back guarantee. Xah ? http://xahlee.org/ ? On Dec 3, 2:12 pm, "Thomas M. Hermann" wrote: > On Dec 3, 3:15 pm, Xah Lee wrote: > > > > > On Dec 3, 8:24 am, Jon Harrop wrote: > > > > My example demonstrates several of Mathematica's fundamental limitations. > > > enough babble Jon. > > > Come flying $5 to my paypal account, and i'll give you real code, > > amongest the programing tech geekers here for all to see. > > > I'll show, what kinda garbage you cooked up in your Mathematica code > > for ?comparison?. > > > You can actually just post your ?comparisons? to ?comp.soft- > > sys.math.mathematica?, and you'll be ridiculed to death for any > > reasonable judgement of claim on fairness. > > > > Consequently, there is great value in combining Mathematica with performant > > > high-level languages like OCaml and F#. This is what the vast majority of > > > Mathematica users do: they use it as a glorified graph plotter. > > > glorified your ass. > > > Yeah, NASA, Intel, NSA, ... all use Mathematica to glorify their > > pictures. LOL. > > > > What exactly do you believe is wrong with my code? > > > come flies $5 to my paypal, and i'll explain further. > > > > I am not trying to make Mathematica look bad. It is simply not suitable when > > > hierarchical solutions are preferable... > > > Certainly there are areas other langs are more suitable and better > > than Mathematica (for example: assembly langs). But not in the ways > > you painted it to peddle your F# and OCaml books. > > > You see Jon, you are this defensive, trollish guy, who takes every > > opportunity to slight other langs that's not one of your F#, OCml that > > you make a living of. In every opportunity, you injest your gribes > > about static typing and other things, and thru ensuring chaos paves > > the way for you to post urls to your website. > > > With your math and functional programing expertise and Doctor label, > > it can be quite intimidating to many geekers. But when you bump into > > me, i don't think you have a chance. > > > As a scientist, i think perhaps you should check your newsgroup > > demeanor a bit? I mean, you already have a reputation of being biased. > > Too much bias and peddling can be detrimental to your career, y'known? > > > to be sure, i still respect your expertise and in general think that a > > significant percentage of tech geeker's posts in debate with you are > > moronic, especially the Common Moron Lispers, and undoubtably the Java > > and imperative lang slaving morons who can't grope the simplest > > mathematical concepts. Throwing your Mathematica bad mouthing at me > > would be a mistake. > > > Come, fly $5 to my paypal account. Let the challenge begin. > > > Xah > > ?http://xahlee.org/ > > > ? > > Xah, > > I'll pay $20 to see your improved version of the code. The only > references to PayPal I saw on your website were instructions to direct > the payment to x... at xahlee.org, please let me know if that is correct. > > What I want in return is you to execute and time Dr. Harrop's original > code, posting the results to this thread. Then, I would like you to > post your code with the timing results to this thread as well. > > By Dr. Harrop's original code, I specifically mean the code he posted > to this thread. I've pasted it below for clarity. > > Jon Harrop coded a ray tracer in Mathematica: > > > delta = Sqrt[$MachineEpsilon]; > > > RaySphere[o_, d_, c_, r_] := > > Block[{v, b, disc, t1, t2}, > > v = c - o; > > b = v.d; > > disc = Sqrt[b^2 - v.v + r^2]; > > t2 = b + disc; > > If[Im[disc] != 0 || t2 <= 0, \[Infinity], > > t1 = b - disc; > > If[t1 > 0, t1, t2]] > > ] > > > Intersect[o_, d_][{lambda_, n_}, Sphere[c_, r_]] := > > Block[{lambda2 = RaySphere[o, d, c, r]}, > > If[lambda2 >= lambda, {lambda, n}, {lambda2, > > Normalize[o + lambda2 d - c]}] > > ] > > Intersect[o_, d_][{lambda_, n_}, Bound[c_, r_, s_]] := > > Block[{lambda2 = RaySphere[o, d, c, r]}, > > If[lambda2 >= lambda, {lambda, n}, > > Fold[Intersect[o, d], {lambda, n}, s]] > > ] > > > neglight = N at Normalize[{1, 3, -2}]; > > > nohit = {\[Infinity], {0, 0, 0}}; > > > RayTrace[o_, d_, scene_] := > > Block[{lambda, n, g, p}, > > {lambda, n} = Intersect[o, d][nohit, scene]; > > If[lambda == \[Infinity], 0, > > g = n.neglight; > > If[g <= 0, 0, > > {lambda, n} = > > Intersect[o + lambda d + delta n, neglight][nohit, scene]; > > If[lambda < \[Infinity], 0, g]]] > > ] > > > Create[level_, c_, r_] := > > Block[{obj = Sphere[c, r]}, > > If[level == 1, obj, > > Block[{a = 3*r/Sqrt[12], Aux}, > > Aux[x1_, z1_] := Create[level - 1, c + {x1, a, z1}, 0.5 r]; > > Bound[c, > > 3 r, {obj, Aux[-a, -a], Aux[a, -a], Aux[-a, a], Aux[a, a]}]]]] > > > scene = Create[1, {0, -1, 4}, 1]; > > > Main[level_, n_, ss_] := > > Block[{scene = Create[level, {0, -1, 4}, 1]}, > > Table[ > > Sum[ > > RayTrace[{0, 0, 0}, > > N at Normalize[{(x + s/ss/ss)/n - 1/2, (y + Mod[s, ss]/ss)/n - 1/2, > > 1}], scene], {s, 0, ss^2 - 1}]/ss^2, {y, 0, n - 1}, > > {x, 0, n - 1}]] > > > AbsoluteTiming[Export["image.pgm", Graphics at Raster@Main[9, 512, 4]]] From MrJean1 at gmail.com Sun Dec 21 15:43:47 2008 From: MrJean1 at gmail.com (MrJean1) Date: Sun, 21 Dec 2008 12:43:47 -0800 (PST) Subject: trapping all method calls in a class... References: <19ac19520812202312q71409182kb58a0f7aaf3b0e74@mail.gmail.com> Message-ID: <8674b360-1b56-41ee-b55c-6a1ec25b9684@z6g2000pre.googlegroups.com> The decorate_meths() function as given fails: TypeError: 'dictproxy' object does not support item assignment But this version avoids that error (on Python 2.2 thru 2.6): def decorate_meths(klass): for nam, val in klass.__dict__.items(): if callable(val): setattr(klass, nam, decorate(val)) return klass # ? /Jean Brouwers On Dec 20, 11:32?pm, "Chris Rebert" wrote: > On Sat, Dec 20, 2008 at 11:12 PM, Piyush Anonymous > > wrote: > > hi, > > i need to trap all method calls in a class in order to update a counter > > which is increased whenever a method is called and decreased whenever method > > returns. in order to that i am trying to write a decorator for all the > > methods. > > > see the code here with error. > > ------- > >http://codepad.org/2w7JVvDB > > ---- > > any suggestions? any other better way of doing it? > > I call unnecessary use of metaclasses! Here's my (untested) attempt at > a simpler class decorator approach: > > def decorate_meths(klass): > ? ? attrs = klass.__dict__.items() > ? ? ? ? for name, val in attrs: > ? ? ? ? ? ? ? ? if callable(val): > ? ? ? ? ? ? ? ? ? ? ? ? klass.__dict__[name] = decorate(val) > > def decorate(method): > ? ? #should be called for every method call in the class > ? ? def decorated(self, *args, **kwds): > ? ? ? ? print "2 Inside __call__()" > ? ? ? ? returnval = method(self, *args,**kwds) > ? ? ? ? print "3 After self.f(*args)" > ? ? ? ? return returnval > ? ? return decorated > > #@decorate_meths <-- this syntax requires a later Python version > class Person(object): > ? ? ? ? def testprint(self,val): > ? ? ? ? ? ? ? ? print "blah blah" > Person = decorate_meths(Person) > > #rest of code after the class definition would be the same > > Sidenotes about your code: > - `args` and `kwds` are the conventional names for the * and ** > special arguments > - the `methodname` variable was actually getting method objects, not > strings, as its values; this was probably part of the bug in your > program > > Cheers, > Chris > > -- > Follow the path of the Iguana...http://rebertia.com From wr4bbit at gmail.com Fri Dec 12 06:50:41 2008 From: wr4bbit at gmail.com (whiter4bbit) Date: Fri, 12 Dec 2008 03:50:41 -0800 (PST) Subject: Imaging library in jython Message-ID: <3178aaba-b1b1-48cd-a1bd-2bf457e41a09@p2g2000prf.googlegroups.com> Hi, Is there any ways to use python Imaging library in jython? From excord80 at gmail.com Sun Dec 14 23:15:27 2008 From: excord80 at gmail.com (excord80) Date: Sun, 14 Dec 2008 20:15:27 -0800 (PST) Subject: How do I manually uninstall setuptools (installed by egg)? References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> <375bd56a-d92b-4d33-bf70-5bea630a376a@q30g2000vbn.googlegroups.com> Message-ID: <4987e663-0fc8-4d5d-af16-8b4142fc5a23@f40g2000pri.googlegroups.com> On Dec 9, 10:48?pm, excor... at gmail.com wrote: > > Anyway, the direction I'm heading is to try and use setuptools *less*. > It seems like it might be too complicated for me. And, I notice that > the mailing list for it (distutils-sig, if that's the right one) is > loaded with questions on how to use it properly, so maybe I'm not > alone. Ah. This is interesting: http://www.b-list.org/weblog/2008/dec/14/packaging/ From xahlee at gmail.com Tue Dec 9 18:01:11 2008 From: xahlee at gmail.com (Xah Lee) Date: Tue, 9 Dec 2008 15:01:11 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> <0201522a-b15a-4401-a208-5d9af70bdd74@w24g2000prd.googlegroups.com> <8947211d-2ee8-403a-8c8a-c7599aea5f80@k24g2000pri.googlegroups.com> Message-ID: <9f86f78c-776e-4793-b931-67dadc0e24f1@i24g2000prf.googlegroups.com> On Dec 8, 4:56 pm, Jon Harrop wrote: > Xah Lee wrote: > > A moron, wrote: > > > You failed the challenge that you were given. > > > you didn't give me a challenge. > > Thomas gave you the challenge: > > "What I want in return is you to execute and time Dr. Harrop's original > code, posting the results to this thread... By Dr. Harrop's original code, > I specifically mean the code he posted to this thread. I've pasted it below > for clarity.". > > Thomas even quoted my code verbatim to make his requirements totally > unambiguous. Note the parameters [9, 512, 4] in the last line that he and I > both gave: > > AbsoluteTiming[Export["image.pgm", Graphics at Raster@Main[9, 512, 4]]] > > You have not posted timings of that, let alone optimized it. So you failed. The first parameter to your Main specifies some kinda recursively stacked spheres in the rendered image. The second parameter is the width and height of the pixels in the rendered image. I tried to run them but my computer went 100% cpu and after i recall 5 min its still going. So, i reduced your input. In the end, with reduced input, it shows my code is 5 times faster (running Mathematica v4 on OS X 10.4.x with PPC 1.9 GHz), and on the other guy's computer with Mathematica 6 he says it's twice as fast. Given your code's nature, it is reasonably to assume that with your original input my code would still be faster than yours. You claim it is not or that it is perhaps just slightly faster? It is possible you are right. I don't want to spend the energy to run your code and my code and possible hog my computer for hours or perhaps days. As i said, your recursive Intersect is very badly written Mathematica code. It might even start memory swapping. Also, all you did is talking bullshit. Thomas actually is the one took my challenge to you and gave me $20 to prove my argument to YOU. His requirement, after the payment, is actually, i quote: ?Alright, I've sent $20. The only reason I would request a refund is if you don't do anything. As long as you improve the code as you've described and post the results, I'll be satisfied. If the improvements you've described don't result in better performance, that's OK.? He haven't posted since nor emailed me. It is reasonable to assume he is satisfied as far as his payment to me to see my code goes. You, kept on babbling. Now you say that the input is different. Fine. How long does that input actually take on your computer? If days, i'm sorry i cannot run your toy code on my computer for days. If in few hours, i can then run the code overnight, and if necessary, give you another version that will be faster with your given input to shut you the fuck up. However, there's cost to me. What do i get to do your homework? It is possible, that if i spend the energy and time to do this, then you again refuse to acknowledge it, or kept on complaining about something else. You see, newsgroup is the bedrock of bullshit. You bullshit, he bullshits, everybody brags and bullshit because there is no stake. I want sincerity and responsibility backed up, with for example paypal deposits. You kept on bullshitting, Thomas gave me $20 and i produced a code that reasonably demonstrated at least how unprofessional your Mathematica code was. Here's the deal. Pay me $20, then i'll creat a version of Mathematica code that has the same input as yours. Your input is Main[9, 512, 4], as i have exposed, your use of interger in the last part for numerical computation is Mathematica incompetence. You didn't acknowledge even this. I'll give a version of Mathematica with input Main[9, 512, 4.] that will run faster than yours. If not, money back guaranteed. Also, pay me $300, then i can produce a Mathematica version no more than 10 times slower than your OCaml code, this should be a 70000 times improvement according to you. Again, money back guarantee. If i don't receive $20 or $300, this will be my last post to you in this thread. You are just a bullshitter. O wait... my code with Main[9, 512, 4.] and other numerical changes already makes your program run faster regardless of the input size. What a motherfucking bullshit you are. Scratch the $20. The $300 challenge still stands firm. Xah ? http://xahlee.org/ ? From anonymous.c.lisper at gmail.com Mon Dec 1 17:48:21 2008 From: anonymous.c.lisper at gmail.com (anonymous.c.lisper at gmail.com) Date: Mon, 1 Dec 2008 14:48:21 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: <3d81f880-6a90-4a11-8dd4-408741e5baed@j38g2000yqa.googlegroups.com> On Dec 1, 2:23?am, Xah Lee wrote: > On Nov 30, 7:30 pm, Xah Lee wrote: > >>some stuff Are you a bot? I think you failed the Turing test after the 8th time you posted the exact same thing... I'm completely serious. From steve at holdenweb.com Tue Dec 30 08:59:51 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Dec 2008 08:59:51 -0500 Subject: Python list's mail server in DNSBL ? In-Reply-To: <495A2825.4070000@shopzeus.com> References: <495A2825.4070000@shopzeus.com> Message-ID: <495A2957.6090805@holdenweb.com> Laszlo: Read the message again. There's nothing the list admins can do about this, you'll have to contact Postmaster at chello.at to have them remove the blacklisting, since it's their server that's imposing it. regards Steve Laszlo Nagy wrote: > I got this message when I tried to send something to this list, through > my ISP's SMTP server: > > > > This Message was undeliverable due to the following reason: > > Each of the following recipients was rejected by a remote mail server. > The reasons given by the server are included to help you determine why > each recipient was rejected. > > Recipient: > Reason: 5.7.1 : Recipient address > rejected: policyd-weight Mail appears to be spam or forged. Ask your > Mail-/DNS-Administrator to correct HELO and DNS MX settings and to get > removed from DNSBLs; in bogusmx.rfc-ignorant.org > > > Please reply to > if you feel this message to be in error. > > > > Reporting-MTA: dns; viefep19.chello.at > Arrival-Date: Tue, 30 Dec 2008 14:12:36 +0100 > Received-From-MTA: dns; edge04.upc.biz (192.168.13.239) > > Final-Recipient: RFC822; > Action: failed > Status: 5.1.1 > Remote-MTA: dns; mail.python.org (194.109.207.14) > Diagnostic-Code: smtp; 550 5.7.1 : Recipient > address rejected: policyd-weight Mail appears to be spam or forged. Ask > your Mail-/DNS-Administrator to correct HELO and DNS MX settings and to > get removed from DNSBLs; in bogusmx.rfc-ignorant.org > > > > Is python.org really blacklisted? Any admin please, try to remove it. > > Thanks > > Laszlo > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From bdesth.quelquechose at free.quelquepart.fr Wed Dec 17 16:19:43 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 17 Dec 2008 22:19:43 +0100 Subject: Why no lexical scoping for a method within a class? In-Reply-To: <6a76b501-f6dc-41b5-8828-b55fece68651@l33g2000pri.googlegroups.com> References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> <6a76b501-f6dc-41b5-8828-b55fece68651@l33g2000pri.googlegroups.com> Message-ID: <49497aa4$0$9084$426a74cc@news.free.fr> walterbyrd a ?crit : > On Dec 17, 9:04 am, rdmur... at bitdance.com wrote: > >> Yes. It's called Object Oriented Programming. > > I think you mean it's *Python* Object Oriented Programming. I am not > sure that every other OO language works like that. Every OO languages having such a thing as a global variable makes a distinction between an instance attributes and a global variable. Your problem is that you are confusing variables and attributes. In Python, 'anything.anyname' (note the dot) is the attribute 'anyname' of object 'anything'. From greg at cosc.canterbury.ac.nz Wed Dec 10 05:47:05 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 10 Dec 2008 23:47:05 +1300 Subject: Announcement: MindTree for Python beta -- feedback appreciated In-Reply-To: References: <20841316.post@talk.nabble.com> Message-ID: <6q9ksbFbef4kU1@mid.individual.net> Johann Spies wrote: > % /usr/local/bin/python3.0 MindTree.pyw > Traceback (most recent call last): > File "MindTree.pyw", line 2, in > from future_builtins import * > ImportError: No module named future_builtins Hmmm... does this mean that Python3 has no future? :-) -- Greg From pierre.quentel at gmail.com Mon Dec 29 14:18:06 2008 From: pierre.quentel at gmail.com (Pierre Quentel) Date: Mon, 29 Dec 2008 11:18:06 -0800 (PST) Subject: SQL, lite lite lite References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> Message-ID: <5147d0d3-d58c-44c6-b2c2-ab8ce6229a2c@p2g2000prf.googlegroups.com> On 29 d?c, 19:06, Aaron Brady wrote: > Hi all, > > About a year ago, I posted an idea I was having about thread > synchronization to the newsgroup. ?However, I did not explain it well, > and I really erred on the side of brevity. ?(After some finagling, Mr. > Bieber and I decided it wasn't exactly anything groundbreaking.) ?But > I think the brevity cost me some readers, who might have had more > interest. ?The affair was on the whole discouraging. ?So, I'm going to > try another idea, and assume that readers have some time, and will > spend it on it. > > I don't think relational data can be read and written very easily in > Python. ?There are some options, such as 'sqllite3', but they are not > easy. ?'sqllite3' statements are valid SQL expressions, which afford > the entire power of SQL, but contrary to its name, it is not that > 'lite'. ?To me, 'lite' is something you could learn (even make!) in an > afternoon, not a semester; something the size of an ActiveState > recipe, or a little bigger, maybe a file or two. ?If you think SQL is > a breeze, you probably won't find my idea exciting. ?I assume that the > basics of SQL are creating tables, selecting records, and updating > records. > > My idea is to create a 'Relation' class. ?The details are basically > open, such as whether to back it with 'sqllite3', 'shelve', 'mmap', or > just mapping and sequence objects; what the simplest syntax is that > can capture and permit all the basics, and how much and what else can > fit in at that level; how and whether it can include arbitrary Python > objects, and what constraints there are on them if not; how and > whether to permit transactions; and what the simplest and coolest > thing you can do with a little Python syntax is. > > This is basically an invitation for everyone to brainstorm. ?(No > hijackings, good humor & digression ok.) ?Lastly, ... > > **warning, spoiler! ?here's what I thought of already.** > > **repeat! ?spoiler! ?here's what I thought of already.** > > #Just the select and update syntax: > > >>> a= people._select( "firstname== 'Joe'" ) > > #select 'key' from 'people' where 'firstname'== 'joe'>>> a > > [Entry2864, Entry3076, Entry3172]>>> entry1= a[ 0 ] > >>> entry1.phone > > #select 'phone' from 'people' where 'key'==self.key > "555-2413">>> entry1.phone= "555-1234" > > #update 'people' set 'phone'= '555-1234' where 'key'==self.key>>> entry1.phone > > "555-1234" > > #Create table syntax (a-whole-nother beast in itself): > > >>> classes= db.Relation( 'class_', 'person', Unique( 'class_', 'person' ) ) > > #create table 'classes' ( 'key', 'class_', 'person' ) unique > ( 'class_', 'person' ) > > >>> classes._unique( 'class_', 'person' ) > >>> classes.class_.noneok= False #'class_' cannot be null > >>> classes.person.noneok= False > >>> classes._insert( 'Physics', 'Dan' ) > >>> classes._insert( 'Chem', 'Tim' ) > > Hoping-"good critic"-is-self-consistent-ly, hoping-to-hear-it's-too- > complicated-already-ly, > A. Brady Hi, PyDbLite (http://pydblite.sourceforge.net/) is not far from what you describe. The basic version stores data in cPickle format, and there are interfaces to use the same Pythonic syntax with SQLite and MySQL backends Regards, Pierre From clp at rebertia.com Sun Dec 7 04:34:22 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 7 Dec 2008 01:34:22 -0800 Subject: how to get a beep, OS independent ? In-Reply-To: <493B9701.2040402@gmail.com> References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> Message-ID: <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> On Sun, Dec 7, 2008 at 1:27 AM, Stef Mientki wrote: > Rainy wrote: >> >> On Dec 6, 3:40 pm, Stef Mientki wrote: >> >>> >>> hello, >>> >>> I want to give a small beep, >>> for windows there's message-beep, >>> and there seems to be something like " curses" , >>> but that package seems to be totally broken in P2.5 for windows. >>> >>> Any other suggestions ? >>> >>> thanks, >>> Stef Mientki >>> >> >> For win there's winsound, you have to check sys.platform and do >> what's necessary for the platform in question. In linux I think >> you can just print '\a' (or does that only work in terminals?). >> If you know that ext. speakers are always on, you can do a nicer >> beep by using some wav file, in linux it's probably easiest to >> use an external program to play it, like wavplay. Basically, >> there is no single answer, it depends on circumstances. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > '\a' or chr(7) prints an inverted "BEL". Inverted bell? What do you mean? And what version dependency are you referring to? Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > So it looks that Python version independency is even worse than OS > independency ;-) > I'll take a look at wxPython and Pygame if there's something useful. > > anyway thanks, > Stef > -- > http://mail.python.org/mailman/listinfo/python-list > From ppearson at nowhere.invalid Wed Dec 10 11:13:42 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 10 Dec 2008 16:13:42 GMT Subject: [OT] Google Groups in bad odour References: <4d5498bf-bbf0-4760-83fc-610729bcbce2@h20g2000yqn.googlegroups.com> Message-ID: <6qa85mFbj3klU1@mid.individual.net> On Wed, 10 Dec 2008 02:20:24 -0800 (PST), Frank Millman wrote: > . . . I will therefore have to find a suitable news client. Any > recommendations? I'm a happy user of slrn. -- To email me, substitute nowhere->spamcop, invalid->net. From mgreene at bdurham.com Wed Dec 24 03:04:57 2008 From: mgreene at bdurham.com (Malcolm Greene) Date: Wed, 24 Dec 2008 03:04:57 -0500 Subject: Strategy for determing difference between 2 very large dictionaries In-Reply-To: <1230105750.9108.1291619105@webmail.messagingengine.com> References: <1230102996.2303.1291616055@webmail.messagingengine.com> <1230105750.9108.1291619105@webmail.messagingengine.com> Message-ID: <1230105897.9336.1291620453@webmail.messagingengine.com> Hi Roger, By very large dictionary, I mean about 25M items per dictionary. Each item is a simple integer whose value will never exceed 2^15. I populate these dictionaries by parsing very large ASCII text files containing detailed manufacturing events. From each line in my log file I construct one or more keys and increment the numeric values associated with these keys using timing info also extracted from each line. Some of our log files are generated by separate monitoring equipment measuring the same process. In theory, these log files should be identical, but of course they are not. I'm looking for a way to determine the differences between the 2 dictionaries I will create from so-called matching sets of log files. At this point in time, I don't have concerns about memory as I'm running my scripts on a dedicated 64-bit server with 32Gb of RAM (but with budget approval to raise our total RAM to 64Gb if necessary). My main concern is am I applying a reasonably pythonic approach to my problem, eg. am I using appropriate python techniques and data structures? I am also interested in using reasonable techniques that will provide me with the fastest execution time. Thank you for sharing your thoughts with me. Regards, Malcolm ----- Original message ----- From: "Roger Binns" To: python-list at python.org Date: Tue, 23 Dec 2008 23:26:49 -0800 Subject: Re: Strategy for determing difference between 2 very large dictionaries -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 python at bdurham.com wrote: > Feedback on my proposed strategies (or better strategies) would be > greatly appreciated. Both strategies will work but I'd recommend the second approach since it uses already tested code written by other people - the chances of it being wrong are far lower than new code. You also neglected to mention what your concerns are or even what "very large" is. Example concerns are memory consumption, cpu consumption, testability, utility of output (eg as a generator getting each result on demand or a single list with complete results). Some people will think a few hundred entries is large. My idea of large is a working set larger than my workstation's 6GB of memory :-) In general the Pythonic approach is: 1 - Get the correct result 2 - Simple code (developer time is precious) 3 - Optimise for your data and environment Step 3 is usually not needed. Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAklR5DUACgkQmOOfHg372QSuWACgp0xrdpW+NSB6qqCM3oBY2e/I LIEAn080VgNvmEYj47Mm7BtV69J1GwXN =MKLl -----END PGP SIGNATURE----- -- http://mail.python.org/mailman/listinfo/python-list From walterbyrd at iname.com Fri Dec 5 15:52:59 2008 From: walterbyrd at iname.com (walterbyrd) Date: Fri, 5 Dec 2008 12:52:59 -0800 (PST) Subject: Can I load a python program at the interactive >>> prompt? Message-ID: <269e5d69-02b7-409b-ad53-b7702b6ec13a@i24g2000prf.googlegroups.com> I am running cygwin on xp. Much to my annoyance, I can not cut-and-paste from a windows app to the python prompt. I think I could do this with putty, but I do not have the permissions to install putty on my xp box. Can I load a file into the python interactive environment? For example I have a file called test.py that consists of the following: print "hello" print "hello again" Can I load that file into python at the >>> prompt? >>> load "test.py" or something like that? From jerry.carl.mi at gmail.com Sat Dec 27 19:02:51 2008 From: jerry.carl.mi at gmail.com (jerry.carl.mi at gmail.com) Date: Sat, 27 Dec 2008 16:02:51 -0800 (PST) Subject: math module for Decimals Message-ID: Hi, I have been looking for a Python module with math functions that would both eat and spit Decimals. The standard math module eats Decimals allright but spits floats... herefore exp(sin(Decimal())) produces exp () of a float :-( So far, i found: -AJDecimalMathAdditions (http://www.ajgs.com/programming/ PythonForDownload.html) -decimalfuncs (http://pypi.python.org/pypi/decimalfuncs/1.4) -and dmath (http://pypi.python.org/pypi/dmath/0.9) I tried using the AJDecimalMathAdditions, but ran into issues like dSin (1E4) would take forever to calculate and would result in sin() > 1 ... If i understand it correctly, the program is using maclaurin series to calculate the value and since it does not chop off all the multiples of 2*pi, the maclaurin approximation becomes useless when its too far from x=0. I also ran into some issues with the decimalfuncs, but i have never tried the dmath thing. Now, i can go and start modifying these modules to behave more like the standard math module but since i am neither mathematician or programer, i really hesitate. So my questions are: (1) what do folks use when they need to calculate something like exp (sin(Decimal())) or even more complex things? Any recommendations? Or am I completely missing something? (2) Is there any plan to provide a standard python module that would do that? (Python 4.0? ;-) Thanks for your comments and help, Jerry From pavlovevidence at gmail.com Tue Dec 2 17:43:47 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 2 Dec 2008 14:43:47 -0800 (PST) Subject: optimization References: Message-ID: <6754f396-d462-48de-b98f-bd92d7e4d095@x38g2000yqj.googlegroups.com> On Dec 2, 1:56?pm, Neal Becker wrote: > Robert Kern wrote: > > Neal Becker wrote: > >> Arnaud Delobelle wrote: > > >>> Neal Becker writes: > > >>>> I noticed in some profiling, that it seems that: > > >>>> def Func (): > >>>> ? def something(): > >>>> ? ? ... > > >>>> It appears that if Func is called many times, this nested func > >>>> definition will cause significant overhead. ?Is this true? ?I guess > >>>> I've become accustomed to decent compilers performing reasonable > >>>> transformations and so have tended to write code for clarity. > >>> If something() can be defined outside Func(), how is it clearer to > >>> define it inside? > > >> If it's only used inside. > > > I, for one, find that significantly less clear. I only expect functions to > > be defined inside of functions if they are going to use lexical scoping > > for some reason. If I read your code, I'd probably waste a good five > > minutes trying to figure out what part of the local scope you were using > > before I would conclude that you just did it because you thought it looked > > better. > > I'm using the inner function to prevent pollution of the global > namespace. ?Local variables also have this attribute. ?Code is > easier to understand when it is written with the greatest locality > - so you can see immediately that the inner function isn't used > somewhere else. Let me throw this out: The rule-of-thumb should not be whether something is used anywhere else, but rather if it is modified locally or depends on something that exists locally. Use outer scope when possible, inner scope only when necessary. Flat is better than nested. In this case, local variables are different from locally-defined functions, because local variables are typically rebound over the course of the function, or are constant but depend on the function's arguments. (Variables that aren't rebound within the function, or don't depend on the arguments, are considered constants and are typically defined in all caps at the module level.) Locally-defined functions, however, are constant, and unless they use values from the enclosing scope, they do not depend on the local environment. Therefore, by this criterion, the locally-defined function ought to be defined at the module level, just like constants are. I don't buy that nesting functions prevents namespace pollution. IMHO, namespace pollution occurs when you do things like "from module import *"; there is no pollution when you control the whole namespace yourself. Having said that, I do use local functions without closures here and there, when it's something either too silly or too specific to introduce a module-level function for. Judgment call, mostly, but typically I go to the module level. Carl Banks From tjreedy at udel.edu Mon Dec 1 20:42:39 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Dec 2008 20:42:39 -0500 Subject: end of print = lower productivity ? In-Reply-To: <98407948-e24f-4a89-8604-148279620f84@k24g2000pri.googlegroups.com> References: <98407948-e24f-4a89-8604-148279620f84@k24g2000pri.googlegroups.com> Message-ID: alex23 wrote: > On Dec 2, 5:12 am, Alan G Isaac wrote: >> One obvious cost is that working at the >> interpreter prompt is now slightly less >> convenient. > > Not if you use IPython: > > IPython 0.8.1 -- An enhanced Interactive Python. > ? -> Introduction to IPython's features. > %magic -> Information about IPython's 'magic' % functions. > help -> Python's own help system. > object? -> Details about 'object'. ?object also works, ?? prints more. > > In [1]: def prnt(x): print x > ...: > > In [2]: prnt "test" > ------> prnt("test") > test > > In [3]: prnt 1+1 > ------> prnt(1+1) > 2 And not in either Python or IDLE: >>> 'test' 'test' >>> 1+1 2 From floris.bruynooghe at gmail.com Wed Dec 24 17:33:25 2008 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Wed, 24 Dec 2008 14:33:25 -0800 (PST) Subject: Using exceptions in defined in an extension module inside another extension module References: <26443e22-0dd6-4fa9-a58e-8d9314001c6c@o4g2000pra.googlegroups.com> Message-ID: <3532637e-c748-4d0e-aa24-42f64be4e9e9@i20g2000prf.googlegroups.com> Christian Heimes wrote: > Floris Bruynooghe schrieb: > > What I can't work out however is how to then be able to raise this > > exception in another extension module. Just defining it as "extern" > > doesn't work, even if I make sure the first module -that creates the > > exception- gets loaded first. Because the symbol is defined in the > > first extension module the dynamic linker can't find it as it only > > seems to look in the main python executable for symbols used in > > dlloaded sofiles. > > > > Does anyone have an idea of how you can do this? > > The answer is so obvious that you are going to bang your head against > the next wall. You have to do exactly the same as you'd do with a pure > Python module: import it. :) Well, I hope the wall hurts as much as my head... Great tip, at first I wasn't looking forward to importing the module in every function where I wanted the exceptions. But then I realised they are global variables anyway so I could have them as such again and just assign them in the module init function. Thanks Floris From renton at 1gb.ru Tue Dec 2 01:55:33 2008 From: renton at 1gb.ru (Alexey Vlasov) Date: Tue, 2 Dec 2008 09:55:33 +0300 Subject: Import of egg packages installed with easy_install In-Reply-To: <6piqvpF839bkU2@mid.uni-berlin.de> References: <6piqvpF839bkU2@mid.uni-berlin.de> Message-ID: <20081202065533.GB9873@l2.in-solve.ru> Hi Diez. On Mon, Dec 01, 2008 at 08:09:29PM +0100, Diez B. Roggisch wrote: > It's not sufficient to add simply your local site-packages, you must install > it using the module site's addsitedir-function, like this: > > import site > site.addsitedir("/home/username/python/lib/python2.5/site-packages") Thanks for help. -- BRGDS. Alexey Vlasov. From pavlovevidence at gmail.com Thu Dec 4 15:19:44 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 4 Dec 2008 12:19:44 -0800 (PST) Subject: "as" keyword woes References: Message-ID: On Dec 3, 11:42?pm, "Warren DeLano" wrote: > Except that Python syntax has proven itself to be a non-backwards > compatible moving target. ?Eliminating cruft and adding new > functionality is one thing, but introducing a whole new two-letter > keyword so long after the game has begun? ?That seems well over the line > of what can be considered reasonable. "as" has been in the language as a hybrid keyword/identifier since Python 2.0, released in 2000, and it was always the plan to eventually make it a full keyword. (I'm not sure when they decided to finish the job in 2.6.) They could have just made it a keyword right then and broke backwards compatibility instantly, instead they gave developers an eight year transition period. I think that is reasonable enough. You know, with Python being the kind of language that does have frequent releases which do carefully break backwards compatibility, if you are using it and expecting your code to work with future versions, it's your respsonsibility to keep up with planned language changes. You didn't. You were the one who dropped the ball here, not the Python developers. So stop complaining. If you don't want to take a few minutes a year to visit Python.org to see what changes are planned for upcoming releases, then feel free to use a language like Java that has the corporate backing to keep bad decisions around for decades. Carl Banks From pavlovevidence at gmail.com Fri Dec 19 00:20:31 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 18 Dec 2008 21:20:31 -0800 (PST) Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> <6qv7kfFeuf65U1@mid.uni-berlin.de> <6qv9v4Ff1lv9U1@mid.uni-berlin.de> Message-ID: <494a8d63-7936-4071-9461-4bfffa02e867@z6g2000pre.googlegroups.com> On Dec 18, 9:53?am, "Diez B. Roggisch" wrote: > Neal Becker wrote: > > Diez B. Roggisch wrote: > > >> Neal Becker wrote: > > >>> Tino Wildenhain wrote: > > >>>> Neal Becker wrote: > >>>> ... > >>>>>>> So if __str__ is "meant for human eyes", then why isn't print using > >>>>>>> it! > >>>>>> it is: > > >>>>>> ?> print x > >>>>>> str > > >>>>>> but dict just uses repr() for all its childs to print. > > >>>>>> T. > >>>>> That makes no sense to me. ?If I call 'print' on a container, why > >>>>> wouldn't it recursively ?print on the contained objects? ?Since print > >>>>> means call str, printing a container should recursively call str on > >>>>> the objects. > > >>>> Every class is free on how to best implement __str__, you will find > >>>> the same behavior on tuple and list as well. > > >>>> Maybe its discussable to change the implementation sensibly, best if > >>>> you would come with a proposal? Perhaps pprint.pprint is a starting > >>>> point? > > >>>> Regards > >>>> Tino > > >>> First, I'd like to know if there is a rationale for the current design. > >>> Am I correct in thinking this is a defect? > > >> I don't think so. First of all, there is no "generic" way of printing a > >> collection. And the current implementation tries to give an overview what > >> is contained in the collection, without trying to make it "fancy" - any > >> such thing needed to be hand-coded anyway. > > >> Using repr for that is better suited, as for example string keys are > >> printed with quotes around them - making clear what they are, and not > >> irritating the user through potentially contained spaces or even things > >> that look as if they are python objects. > > >> For example, if repr *wasn't* used, > > >> { "{foo=bar}" : "baz"} > > >> would be printed > > >> {{foo=bar} : baz} > > >> Which is *not* what the dictionary actually contains! > > >> The same goes for unicode-objects. They appear with their "funny" > >> characters as \xXX-codes - instead of bailing out on you with > >> unicode-errors. > > >> So, IMHO the current behavior is desired. > > > So if I want to overload something in my custom class, so that I get a > > nice string whether it's printed directly, or as part of a container, what > > is the recommendation? ?Overload both __str__ and __repr__? > > Yep. I would say no. __repr__ should be specific--something that when evaled yields an equal object, if possible--about what the object is. Overloading __repr__ to return an unspecific human-readable message is a mistake, and will frustrate users who are debugging, logging, inspecting objects at the interactive prompt. Neal's problem seems to be with the behavior of dict's __str__ method, which prints repr() of objects when he wants str(). That is intended behavior, like it or not, so I would say the appropriate thing is not use dict's default printed representation, and just write a custom formating function for dicts. Carl Banks From arnodel at googlemail.com Mon Dec 22 17:36:15 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 22 Dec 2008 22:36:15 +0000 Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano writes: > Instead of just whinging, how about making a suggestion to fix it? Go on, > sit down for an hour or ten and try to work out how a BINARY OPERATOR > like % (that means it can only take TWO arguments) can deal with an > arbitrary number of arguments, *without* having any special cases. > > Go on. Take your time. I'll be waiting. Well that's easy. I see 'r' didn't answer so I will: only accept tuples on the right hand side of the %, so all arguments have to be put inside a tuple. >>> "%s" % 42 Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for %: 'str' and 'int' >>> "%s" % (42,) '42' Of course there would still be the possibility of uncaught bugs when people forget to put the argument in a tuple if the argument itself is a tuple of length 1. >>> def foo(x): ... print "foo(%s)" % x ... # should be % (x,) ... >>> foo('a') TypeError: unsupported operand type(s) for %: 'str' and 'str' >>> # But if x is a tuple of length 1 the error is not reported >>> foo((1,)) foo(1) That's why .format() is a better option IMHO. -- Arnaud From kyosohma at gmail.com Mon Dec 1 17:19:32 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 1 Dec 2008 14:19:32 -0800 (PST) Subject: Why doesn't doc has predifined name and location ? References: <493455AD.4040306@gmail.com> Message-ID: <562d585b-97d2-41d6-9df6-695782a99238@41g2000yqf.googlegroups.com> > Sidenote: what Python projects publish their docs in CHM besides > possibly Win32 GUI programs? Doing a quick search in my Python25 directory and all it's sub- folders, all I found was Python25.chm and PyWin32.chm. However, I know wxPython also has a help file in chm format, but it puts it in another directory by default... > > Cheers, > Chris > -- Mike From gauravkec2005 at gmail.com Thu Dec 4 05:30:55 2008 From: gauravkec2005 at gmail.com (gaurav kashyap) Date: Thu, 4 Dec 2008 02:30:55 -0800 (PST) Subject: receive data through a python program from javascript Message-ID: <49c9e72f-5032-437d-ac70-8aea009e9278@i24g2000prf.googlegroups.com> Hi all, I have a javascript.I want to send some data from this javascript to a python program that is on zope on my local system... What can be the python program From fetchinson at googlemail.com Wed Dec 3 22:58:47 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 3 Dec 2008 19:58:47 -0800 Subject: RELEASED Python 3.0 final In-Reply-To: <47c890dc0812031952r6d2adbfav20fde92431443751@mail.gmail.com> References: <47c890dc0812031952r6d2adbfav20fde92431443751@mail.gmail.com> Message-ID: >>> On behalf of the Python development team and the Python community, I >>> am happy to announce the release of Python 3.0 final. >>> >>> Python 3.0 (a.k.a. "Python 3000" or "Py3k") represents a major >>> milestone in Python's history, and was nearly three years in the >>> making. This is a new version of the language that is incompatible >>> with the 2.x line of releases, while remaining true to BDFL Guido van >>> Rossum's vision. Some things you will notice include: >>> >>> * Fixes to many old language warts >>> * Removal of long deprecated features and redundant syntax >>> * Improvements in, and a reorganization of, the standard library >>> * Changes to the details of how built-in objects like strings and >>> dicts work >>> * ...and many more new features >>> >>> While these changes were made without concern for backward >>> compatibility, Python 3.0 still remains very much "Pythonic". >>> >>> We are confident that Python 3.0 is of the same high quality as our >>> previous releases, such as the recently announced Python 2.6. We will >>> continue to support and develop both Python 3 and Python 2 for the >>> foreseeable future, and you can safely choose either version (or both) >>> to use in your projects. Which you choose depends on your own needs >>> and the availability of third-party packages that you depend on. Some >>> other things to consider: >>> >>> * Python 3 has a single Unicode string type; there are no more 8-bit >>> strings >>> * The C API has changed considerably in Python 3.0 and third-party >>> extension modules you rely on may not yet be ported >>> * Tools are available in both Python 2.6 and 3.0 to help you migrate >>> your code >>> * Python 2.6 is backward compatible with earlier Python 2.x releases >>> >>> We encourage you to participate in Python 3.0's development process by >>> joining its mailing list: >>> >>> http://mail.python.org/mailman/listinfo/python-3000 >>> >>> If you find things in Python 3.0 that are broken or incorrect, please >>> submit bug reports at: >>> >>> http://bugs.python.org/ >>> >>> For more information, links to documentation, and downloadable >>> distributions, see the Python 3.0 website: >>> >>> http://www.python.org/download/releases/3.0/ >>> >>> Enjoy, >>> - -Barry >>> >>> Barry Warsaw >>> barry at python.org >>> Python 2.6/3.0 Release Manager >>> (on behalf of the entire python-dev team) >> >> uname -a >> >> Linux fetch 2.6.23.1-42.fc8 #1 SMP Tue Oct 30 13:18:33 EDT 2007 x86_64 >> x86_64 x86_64 GNU/Linux >> >> tar xzvf Python-3.0.tgz >> cd Python-3.0 >> ./configure >> make >> >> Failed to find the necessary bits to build these modules: >> _tkinter > > Do you have Tcl/Tk and their dev libs installed? Tkinter is based on Tcl/Tk. > Also, that error isn't fatal, it just means that Tkinter won't be > installed because it can't find the libs. > > Cheers, > Chris > -- > Follow the path of the Iguana... > http://rebertia.com > >> To find the necessary bits, look in setup.py in detect_modules() for >> the module's name. >> >> >> Cheers, >> Daniel I thought I didn't have to download tcl/tk stuff separately. At least I never did that for python 2.x but maybe somewhere they are installed on my box anyway. But why I have this issue with 3.0 I don't quite get, of course you are right, it's not fatal. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From mdgeorge at cs.cornell.edu Wed Dec 3 17:04:21 2008 From: mdgeorge at cs.cornell.edu (Michael George) Date: Wed, 3 Dec 2008 17:04:21 -0500 Subject: building an extension module with autotools? In-Reply-To: <4936FD1C.1010700@ghaering.de> References: <4936FD1C.1010700@ghaering.de> Message-ID: <49370265.2090904@cs.cornell.edu> Gerhard H?ring wrote: > Michael George wrote: >> I've tried using automake, > > In my opinion, this is serious overkill. automake is good for making > stuff work on a herd of different Unixen with various combinations of > libc functions available etc. But for developing a Python extension, > it doesn't help much at all. All you need to know about Python is > available via macros if you import Python.h. > I'll definitely consider going the simpler route, although the other thing that autotools provides is a standard interface for end-users. For example I'm picky and don't let anything into /usr that isn't under the purview of the package manager. autotools makes life easy because I can just do ./configure --prefix=/opt/pkgname and I know I'm good. Custom build setups force me to figure them out before I can install (and sometimes even use) the program. Since I'll be eventually trying to attract users, I'd like to avoid scaring them away with custom build scripts :) > HTH > > -- Gerhard Thanks for the advice. --Mike From rhf22 at mole.bio.cam.ac.uk Tue Dec 9 14:18:27 2008 From: rhf22 at mole.bio.cam.ac.uk (Rasmus Fogh) Date: Tue, 9 Dec 2008 19:18:27 +0000 (GMT) Subject: Rich Comparisons Gotcha Message-ID: Mark Dickinson wrote: > On Dec 8, 2:24 pm, Rasmus Fogh wrote: >> So, I would much prefer a language change. I am not competent to even >> propose one properly, but I'll try. > I don't see any technical problems in what you propose: as > far as I can see it's entirely feasible. However: >> should. On the minus side there would be the difference between >> '__equal__' and '__eq__' to confuse people. > I think this is exactly what makes the idea a non-starter. There > are already enough questions on the lists about when to use 'is' > and when to use '==', without adding an 'equals' function into > the mix. It would add significant extra complexity to the core > language, for questionable (IMO) gain. So: It is perfectly acceptable behaviour to have __eq__ return a value that cannot be cast to a boolean, but it still does break the python list. The fixes proposed so far all get the thumbs down, for various good reasons. How about: - Define a new built-in Exception BoolNotDefinedError(ValueError) - Have list.__contains__ (etc.) use the following comparison internally: def newCollectionTest(x,y): if x is y: return True else: try: return bool(x == y) except BoolNotDefinedError: return False - Recommend that numpy.array.__nonzero__ and similar cases raise BoolNotDefinedError instead of ValueError Objects that choose to raise BoolNotDefinedError will now work in lists, with identity semantics. Objects that do not raise BoolNotDefinedError have no change in behaviour. Remains to be seen how hard it is to implement, and how much it slows down list.__contains__ Rasmus --------------------------------------------------------------------------- Dr. Rasmus H. Fogh Email: r.h.fogh at bioc.cam.ac.uk Dept. of Biochemistry, University of Cambridge, 80 Tennis Court Road, Cambridge CB2 1GA, UK. FAX (01223)766002 From michele.simionato at gmail.com Wed Dec 3 00:23:37 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 2 Dec 2008 21:23:37 -0800 (PST) Subject: porting modules to Python 3.0 Message-ID: <8f60c779-f1ec-4127-b173-f174c016aa96@a12g2000yqm.googlegroups.com> Python 3.0 is going to be released Real Soon now and I realized that there big holes in my understanding of how libraries working both with Python 2.X and Python 3.X should be written. Let me consider pure Python libraries for the moment. I see various possibilities: 1. I just release two different libraries, say lib2X.py and lib3X.py, the first for the 2.X series and the second for the 3.X series, and the source code of lib3X.py is generated from lib2X.py via 2to3; 2. I release a single library lib.py which consists in a big if: $ cat lib.py if sys.version >= '3': from lib3X import * else: from lib2X import * I am not really happy with any of the options. I think there should be some cooperation between PyPI and easy_install such than when the user type $ easy_install lib the user gets the 2.X version or the 3.X version according to the Python version she is using. Is there something like that already in place? What are the recommendations for library authors willing to support both Python 2.X and 3.X in parallel? Michele Simionato From lkcl at lkcl.net Wed Dec 3 04:34:11 2008 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Wed, 3 Dec 2008 09:34:11 +0000 Subject: [ANN] Pyjamas 0.4: Python Web Toolkit Release In-Reply-To: <3de8e1f70812022054g40f974a1x5bdd676b2d9527ea@mail.gmail.com> References: <3de8e1f70812022054g40f974a1x5bdd676b2d9527ea@mail.gmail.com> Message-ID: On Wed, Dec 3, 2008 at 4:54 AM, Banibrata Dutta wrote: > Amazing concept, and glad that someone thought of this and implemented this. > The book's formatting on IE and Chrome looked a bit unusual. Content wise it > is already firly decent (i.e. enough to get a programmer started), but > sometimes text appears in a long & narrow col. format instead of the more > usual page format ... and the (i) i.e. informative text icons to the left of > informative notes gives a jarring visual feel/urge to scroll to see more :). yehh, the formatter is written in about 100 lines of python as a wiki-like "thing" that turns the txt pages into DOM-model appendChild()s behind the scenes. i was experimenting with a new layout reader: i've removed the experimentation, should work ok.... other than the headings

and

don't appear to be added! darn. have to find out why. some day :) l. From Slaunger at gmail.com Mon Dec 1 08:40:22 2008 From: Slaunger at gmail.com (Slaunger) Date: Mon, 1 Dec 2008 05:40:22 -0800 (PST) Subject: How to instantiate in a lazy way? Message-ID: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> Hi comp.lang.python, I am a novice Python programmer working on a project where I deal with large binary files (>50 GB each) consisting of a series of variable sized data packets. Each packet consists of a small header with size and other information and a much large payload containing the actual data. Using Python 2.5, struct and numpy arrays I am capable of parsing such a file quite efficiently into Header and Payload objects which I then manipulate in various ways. The most time consuming part of the parsing is the conversion of a proprietary form of 32 bit floats into the IEEE floats used internally in Python in the payloads. For many use cases I am actually not interested in doing the parsing of the payload right when I pass through it, as I may want to use the attributes of the header to select the 1/1000 payload which I actually have to look into the data for and do the resourceful float conversion. I would therefore like to have two variants of a Payload class. One which is instantiated right away with the payload being parsed up in the float arrays available as instance attributes and another variant, where the Payload object at the time of instantiation only contains a pointer to the place (f.tell()) in file where the payload begins. Only when the non-existing attribute for a parsed up module is actully accessed should the data be read, parsed up and the attribute created. In pseudocode: class PayloadInstant(object): """ This is a normal Payload, where the data are parsed up when instantiated """ @classmethod def read_from_file(cls, f, size): """ Returns a PayloadInstant instance with float data parsed up and immediately accessible in the data attribute. Instantiation is slow but after instantiation, access is fast. """ def __init___(self, the_data): self.data = the_data class PayloadOnDemand(object): """ Behaves as a PayloadInstant object, but instantiation is faster as only the position of the payload in the file is stored initially in the object. Only when acessing the initially non-existing data attribute are the data actually read and the attribure created and bound to the instance. This will actually be a little slower than in PayloadInstant as the correct file position has to be seeked out first. On later calls the object has as efficient attribute access as PayloadInstant """ @classmethod def read_from_file(cls, f, size): pos = f.tell() f.seek(pos + size) #Skip to end of payload return cls(pos) # I probably need some __getattr__ or __getattribute__ magic here...?? def __init__(self, a_file_position): self.file_position = a_file_position My question is this a a pyhtonic way to do it, and they I would like a hint as to how to make the hook inside the PayloadOnDemand class, such that the inner lazy creation of the attribute is completely hidden from the outside. I guess I could also just make a single class, and let an OnDemand attribute decide how it should behave. My real application is considerably more complicated than this, but I think the example grasps the problem in a nutshell. -- Slaunger From bignose+hates-spam at benfinney.id.au Fri Dec 5 20:19:41 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 06 Dec 2008 12:19:41 +1100 Subject: RELEASED Python 3.0 final References: <874p1jux8u.fsf@benfinney.id.au> Message-ID: <87iqpyt80i.fsf@benfinney.id.au> aahz at pythoncraft.com (Aahz) writes: > In article <874p1jux8u.fsf at benfinney.id.au>, > Ben Finney wrote: > >James Stroud writes: > >> > >> comp.lang.python3k ? > > > >The language has undergone an incompatible divide. Hopefully the > >community need not do the same. > > Pish and tosh. James was clearly making a funny; there's not *that* > much difference between 2.x and 3.x. You appear to assume I was not going along with the funny. To be expected, I suppose, given the well-documented context lossage in a message-based medium. I hereby recommend ?pish and tosh? for use by anyone who wants to counter someone's point. It beats by a country furlong the invective that has become regrettably common here in recent months. -- \ ?I was once walking through the forest alone and a tree fell | `\ right in front of me, and I didn't hear it.? ?Steven Wright | _o__) | Ben Finney From Alvin.ONeal at gmail.com Mon Dec 22 11:19:31 2008 From: Alvin.ONeal at gmail.com (Alvin ONeal) Date: Mon, 22 Dec 2008 09:19:31 -0700 Subject: Python's popularity In-Reply-To: <18767.47566.709705.92@montanaro-dyndns-org.local> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <18767.47566.709705.92@montanaro-dyndns-org.local> Message-ID: I decided to start learning python for 2 reasons: #A The white-space is wonderful - you can't code unreadable code. #B I noticed that just about every application I use has extensions written in python. Although it isn't as "cool" as ruby, it certainly has been in widespread use longer. I think that job postings inflate apparant popularity. For example if you look up jobs for "Flex developers", you'll see a lot of posts. There are a lot of people that hear the buzz and they think that they want a programmer with that skill, but in reality what they should be looking for is a java dev who is willing to learn flex because there just aren't that many poeple that know flex yet). I imagine the same is true of ruby. Also worthy of mention: I've seen python pre-installed on consumer HP desktops (I think as part of a backup/restore script, but I'm not sure) I would believe that python is in the top 5 for sure. AJ ONeal -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Dec 24 04:10:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2008 07:10:16 -0200 Subject: Strategy for determing difference between 2 very large dictionaries References: <1230102996.2303.1291616055@webmail.messagingengine.com> <1230106980.12156.1291620725@webmail.messagingengine.com> Message-ID: En Wed, 24 Dec 2008 06:23:00 -0200, escribi?: > Hi Gabriel, > > Thank you very much for your feedback! > >> k1 = set(dict1.iterkeys()) > > I noticed you suggested .iterkeys() vs. .keys(). Is there any advantage > to using an iterator vs. a list as the basis for creating a set? I You've got an excelent explanation from Marc Rintsch. (Note that in Python 3.0 keys() behaves as iterkeys() in previous versions, so the above code is supposed to be written in Python 2.x) >>> can this last step be done via a simple list comprehension? > >> Yes; but isn't a dict comprehension more adequate? >> >> [key: (dict1[key], dict2[key]) for key in common_keys if >> dict1[key]!=dict2[key]} > > Cool!! I'm relatively new to Python and totally missed the ability to > work with dictionary comprehensions. Yes, your dictionary comprehension > technique is much better than the list comprehension approach I was > struggling with. Your dictionary comprehension statement describes > exactly what I wanted to write. This time, note that dict comprehensions require Python 3.0 -- so the code above won't work in Python 2.x. (It's not a good idea to mix both versions in the same post, sorry!) You might use instead: dict((key,(dict1[key],dict2[key])) for key in ...) but it's not as readable. -- Gabriel Genellina From rurpy at yahoo.com Tue Dec 16 01:00:32 2008 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Mon, 15 Dec 2008 22:00:32 -0800 (PST) Subject: ethical questions about global variables References: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> Message-ID: <0d9a9758-f338-4a58-971a-1bd29e40ce32@v5g2000prm.googlegroups.com> On Dec 15, 7:45 pm, "Giampaolo Rodola'" wrote: > in a module of mine (ftpserver.py) I'd want to add a (boolean) global > variable named "use_gmt_times" to decide whether the server has to > return times in GMT or localtime but I'm not sure if it is a good idea > because of the "ethical" doubts I'm gonna write below. > > In first place I've never liked global variables too much and always > preferred per-class-instance variables instead. By "per-class-instance variables", you are talking about instance attributes? I.e. "self.use_gmt_times"? I don't see much difference between global variables and instance attributes. One of the main problems that make global variables bad is that they can be referenced and set anywhere in a program, so it can be very difficult, when one finds a global has a wrong value at some point, to figure out how it got that value. Consider the following: ~~~ Snippet 1 ~~~ #my_module def func1(): global A A = 1 def func2 global A A = 2 def func3 global A #Yes, this is redundant print A ~~~ Snippet 2 ~~~ class my_class: def func1(): self.A = 1 def func2 self.A = 2 def func3 print self.A What's the difference between snippet 1 and snippet 2? In the snippet 1, one says "global A"; in the snippet 2, "self." -- in this case it is just a spelling difference. If globals are "evil" then so must be the isomorphic use of attributes in snippet 2. I suppose one can say that classes are generally smaller than modules so that the "globalish" aspect of attributes is acceptable. But then one must conclude that the prohibition against using globals also applies to using instance attributes in large classes. Or conversely, that globals are perfectly acceptable, even desirable, in small modules. Note also that the common workaround to eliminate globals, passing them as arguments, doesn't really change anything either: #my_module class Config: pass config = Config() def func1(state): config.A = 1 def func2(state) config.A = 2 def func3(state) print config.A In other words, it is not the "global" keyword that causes problems, it is the anti-pattern of making a variable accessible in a read/write manner to a large number of functions without much control over who can change it or when. That anti-pattern can exist with globals, with instance attributes, or with function arguments. Simply avoiding globals is not sufficient to avoid the anti-pattern. > The problem in my case is that I have to use such variable in two > separated classes: FTPHandler and VirtualFileSystem. Also, I want that > for no reason one class uses times in GMT and the other one local > times. > > Another doubt is the naming convention. PEP-8 states that global > variables should use the lower_case_naming_convention but I've seen a > lot of library module using the UPPER_CASE_NAMING_CONVENTION. What am > I supposed to do about it? I generally use an initial capital letter for my global variables. I think it is useful to have some signal that a variable may be set outside the scope of the local function/method. From clp at rebertia.com Mon Dec 15 20:19:08 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 15 Dec 2008 17:19:08 -0800 Subject: parse C expression? In-Reply-To: References: Message-ID: <47c890dc0812151719p56fbd665tcc614f764585c987@mail.gmail.com> On Mon, Dec 15, 2008 at 3:48 PM, Torsten Mohr wrote: > Hi, > > i found some examples when googling for the subject but nothing really > matched. > > Is there a standard module available that lets me parse a syntax like "C" > with numbers, operators, braces, variables and function calls? > > I'd like to use this to parse an own kind of configuration language > and preferred would be just standard modules. Is there something > available that is maybe based on shlex? No, nothing approaching C-syntax as it'd have be much more complicated than shlex and I can't imagine too many uses for such a module. If it's a configuration file, you might consider using either JSON (std lib module `json`) or INI (std lib module `ConfigParser`) as the format instead. Or if you need something really complex, just use Python itself. Custom config file formats are bad anyway. Should you have no control over the format, you'll need to write a proper parser grammar with something like pyparsing as was mentioned by James. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From rhodri at wildebst.demon.co.uk Tue Dec 23 00:48:37 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Tue, 23 Dec 2008 05:48:37 -0000 Subject: iterating initalizations In-Reply-To: <002696D3-E888-4D32-8416-0CFE4AC859AC@gmail.com> References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> <47c890dc0812221943g44bd7222t8c09c088d87e77df@mail.gmail.com> <002696D3-E888-4D32-8416-0CFE4AC859AC@gmail.com> Message-ID: On Tue, 23 Dec 2008 03:52:35 -0000, Aaron Stepp wrote: > Simply put, I just need enough arrays to hold a list of > pitches/rhythms. Then I'll have each list member returned to an > instrument defined in another module. One "array" can hold a list of pitches/rhythms. I'm still not terribly clear as to why you need so many. Is each list intended for a different instrument, so you're more looking at: violin_1 = [ ...stuff... ] violin_2 = [ ...other stuff...] viola = [ ...really sweet stuff... ] cello = [ ...really boring stuff... ] -- Rhodri James *-* Wildebeeste Herder to the Masses From stephane.chazelas at unicyclist.com Mon Dec 1 11:08:16 2008 From: stephane.chazelas at unicyclist.com (Stephane Chazelas) Date: Mon, 1 Dec 2008 16:08:16 +0000 (UTC) Subject: Python surpasses Perl in popularity? References: <5e87aee0-c7fd-4e9d-befb-0cc01cee64ec@f40g2000pri.googlegroups.com> <49316c95$0$2813$742ec2ed@news.sonic.net> <49322ea2$0$2747$742ec2ed@news.sonic.net> Message-ID: 2008-12-1, 10:16(+00), Andre Majorel: [...] >> Tru64: >> /bin/sh can behave either as a Bourne shell or a POSIX shell >> (ksh88) depending on the environment > > How does it decide ? argv[0] ? isatty (STDIN_FILENO) ? That was answered in another article with a quote of the sh man page on Tru64: via an environment variable: BIN_SH. >> most Linux based systems and most other Unices: >> /bin/sh is a POSIX compliant shell (bash generally for Linux) >> and there's no Bourne shell (either there has never been or it >> has been removed/replaced by a POSIX shell). > > Two other Unixen I know of that have a non-POSIX sh are SCO Open > Server and UnixWare. I'm not sure they even provide a > POSIX-compliant alternative like Solaris does. Again, see http://www.in-ulm.de/~mascheck/various/shells/ [...] > Many people assume "standard" equates "portable". As far as > shell programming is concerned, the safest way to get portability > is to ignore the standard and code for the Bourne shell. Yes, it's enough and relatively safe in most cases. It's the only option if you want to be portable to systems over 15 years old. But nowadays, especially since the specifications have been made public, I find that it is sufficiently widespread to make POSIX a safer bet. At least having a specification gives you some sort of guarantee: if you write your script by the rules that are clearly (most of the time) specified, then it should work on any compliant system. If it doesn't work, then it's not your fault (though it's true in many case, you'll still be the one who'll have to do something about it). -- St?phane From martin at v.loewis.de Wed Dec 3 01:21:17 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 03 Dec 2008 07:21:17 +0100 Subject: porting modules to Python 3.0 In-Reply-To: <8f60c779-f1ec-4127-b173-f174c016aa96@a12g2000yqm.googlegroups.com> References: <8f60c779-f1ec-4127-b173-f174c016aa96@a12g2000yqm.googlegroups.com> Message-ID: <4936255D.6000509@v.loewis.de> > Is there something like that already in place? What are the > recommendations for library > authors willing to support both Python 2.X and 3.X in parallel? My recommendation is to use 3.0's build_py_2to3 implementation of the build_py command. See Demo/distutils/test2to3. You will have a single lib.py, written in 2.x. When you install in 3.0, lib2to3 will convert it to 3.x in the build area, and then install the 3.0 version. That, of course, requires you to adjust lib.py in such a way that 2to3 will successfully and completely convert it. In my experience (with porting Django) and Mark Hammond's experience (with porting PythonWin), this should be always possible. You look at what 2to3 does, find out what additional modifications need to be done, and apply them to the input of 2to3 so that a) 2to3 leaves these changes in place b) they either have no effect or still work correctly when run in 2.x. Regards, Martin From renesd at gmail.com Mon Dec 8 04:18:25 2008 From: renesd at gmail.com (illume) Date: Mon, 8 Dec 2008 01:18:25 -0800 (PST) Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? References: <5ccd4a18-cd2b-4040-90c6-33723af15e96@b38g2000prf.googlegroups.com> <7e1a9226-c7a9-4b5e-bfbb-ea079639d6a2@t39g2000prh.googlegroups.com> Message-ID: <682de8aa-62b1-477a-8b31-ae7698b1ffe7@w1g2000prk.googlegroups.com> On Dec 8, 7:31?pm, alex23 wrote: > On Dec 8, 2:26?pm, illume wrote: > > > pygame is simpler to learn, since it doesn't require you to know how > > to create classes or functions. > > I'm not sure if I'd be quick to tout that as an advantage... :) Hi, It's easier to teach only requiring *using* classes, and functions than *creating* them. This is important if it's being used to teach programming - as you don't need to teach people two fairly large concepts before you can do anything. People are motivated by seeing results. So it can be good to let people do things without requiring much learning. Anyone teaching object oriented program will tell you that it's a hard concept to present to people. So if you can avoid teaching parts of OO, and a bunch of other concepts at the same time, it's easier for people to handle. It's quite nice to be able to handle events without requiring callbacks. Everyone hates callbacks, but lots of people use them for event systems. However callbacks aren't needed at all for event programming. Instead you can get an event as an object and then process it. Callbacks for events made more sense in languages like smalltalk where events and method calls were closely aligned concepts(method calls are messages in smalltalk). However in languages where you don't have such a close conceptual alignment(such as python), making events objects instead of method calls is much easier to understand. Also python has very slow function calls, so avoiding using callbacks is also faster. Imagine using callbacks for files? So you would have to subclass file, and make a read_data method. Then your class will call your read data method when some data arrives. Kind of annoying, and not needed. From geon at post.cz Sun Dec 28 03:43:20 2008 From: geon at post.cz (Pavel Kosina) Date: Sun, 28 Dec 2008 09:43:20 +0100 Subject: tkinter 3.0 multiple keyboard events together In-Reply-To: References: <600d4b68-6fe2-4c2c-b425-1a739430bb54@s9g2000prg.googlegroups.com> <7b5e466c-d75d-4e71-b559-f8a0d3718094@r15g2000prd.googlegroups.com> Message-ID: <49573C28.6000808@post.cz> janislaw napsal(a): > Um, I could be only guessing what are you meant to do, unless you > describe your problem in more detailed way. I.e. describe the desired > behaviour, show code which you have, and describe the current > behaviour. > > well, I am working on a tutorial for youngster (thats why i need to stay the code as easy as possible). In this game you are hunted by robots. I could use key"7" on numeric keypad for left-up moving but seems to me, that "4"+"8" is much more standard for them. >> This solution has disadvantage that after you release one key, that the >> function keyPressHandler stopped to be called by the other pressed keys. >> I would have not to build moving the player in KeyPresshandler, but on >> another new function that would have to read periodically "keys" and to >> act afterwards.... >> > > Hmmm. Maybe you'd like to hook into Tkinter event loop, i.e. by custom > events if you don't like periodical polling. > No, that would be even more difficult. I already have a code that use your idea: from Tkinter import * root = Tk() pressedKeys=set() def onKeyPress(event): pressedKeys.add(event.keysym) def onKeyRelease(event): pressedKeys.remove(event.keysym) def move(): print list(pressedKeys) root.after(100,move) root.bind("", onKeyPress) root.bind("", onKeyRelease) root.after(100,move) root.mainloop() well, I thought that gui?s have such a problem already built-in - so that i am not pressed to code it. You know, its not exactly about me - if I do it for myself, for my program, that there is no problem, but I need to explained it to begginners ..... And I do not want, as might be more usual, do my module, that would cover this "insanity" (look at it with 13-years old boy eyes ;-) ). Do you like to say me, that this is not a standard "function" neither in tkinter, not say gtk or the others, too? I would expect something like this: def onKeyTouch(event): print (event.keysymAll) root.bind("", onKeyTouch) and all the pressed keys are printed ....all the functions OnKeyPress, OnKeyRelease, move, even set pressedKeys are in onKeyTouch.... P. From google at mrabarnett.plus.com Tue Dec 30 18:15:35 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 30 Dec 2008 23:15:35 +0000 Subject: get method In-Reply-To: References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> Message-ID: <495AAB97.5010707@mrabarnett.plus.com> James Mills wrote: > On Tue, Dec 30, 2008 at 7:10 PM, Roel Schroeven > wrote: >> Hm, you just changed an O(n) algorithm to an O(n**2) algorithm. No big >> deal for short strings, but try your solution on a string with length >> 10000 and see the difference. On my computer the O(n) version takes >> 0.008 seconds, while your version takes 8.6 seconds. That's 1000 times >> slower. > > Yes you are right :) Sadly :/ > > I wonder if there is a way to implement > the same thing with close to O(n) > complexity using list/dict comprehensions. > A while back I posted a Python implementation of 'bag' (also called a multiset). The code would then become something like: >>> s = "James Mills and Danielle Van Sprang" >>> dict(bag(s).iteritems()) {'a': 5, ' ': 5, 'e': 3, 'd': 1, 'g': 1, 'i': 2, 'm': 1, 'J': 1, 'M': 1, 'l': 4, 'n': 4, 'p': 1, 's': 2, 'r': 1, 'V': 1, 'S': 1, 'D': 1} From kay.schluehr at gmx.net Tue Dec 2 12:15:16 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 2 Dec 2008 09:15:16 -0800 (PST) Subject: Python+Pyjamas+V8=ftw References: <56533d3d-c5cd-4a41-9bc3-525eaa44bba1@d23g2000yqc.googlegroups.com> Message-ID: On 2 Dez., 14:57, lkcl wrote: > ?as a general-purpose plugin replacement for /usr/bin/python, however, > it's not quite there. ?and, given that javascript cheerfully goes > about its way with the "undefined" concept, it's always going to be a > _bit_ tricky to provide absolutely _every_ language feature, > faithfully. For some reasons I'd do it the other way round and model JS entirely in Python first. This is rather gratefully supported by two facts 1) Python is far more powerful than JS and supports lots of metaprogramming facilities. For example providing a Python type that has JS prototype semantics isn't really a big deal. 2) JS is standardized and the standard is very well documented. When JS has been mapped onto a dedicated Python framework one can open the backchannel and translate the Python framework code to JS. Ideally the mapping P_JS -> P_PyJS -> P'_JS is an identity. PyJS is unambiguously fixed by this mapping. Now people may define mappings from Python types to PyJS types and all the checks and tests are performed as usual checks in Python code by API functions of the PyJS framework. The compiler hasn't anything to do with it anymore and can be somewhat liberated from hard work. This roundtrip breaks with the GWT scheme of one way translation for an obvious reasons: Python is not Java. Regards, Kay From scott.p.macdonald at gmail.com Tue Dec 16 13:15:30 2008 From: scott.p.macdonald at gmail.com (Scott MacDonald) Date: Tue, 16 Dec 2008 11:15:30 -0700 Subject: Python Dictionary Algorithm Question In-Reply-To: <3ca641b40812160951h3a13e69am291afb02965451a7@mail.gmail.com> References: <3ca641b40812160951h3a13e69am291afb02965451a7@mail.gmail.com> Message-ID: You might be interested in the "Beautiful Code" book: http://oreilly.com/catalog/9780596510046/ It has a chapter on Python's dict implementation that is pretty good. On Tue, Dec 16, 2008 at 10:51 AM, Brigette Hodson wrote: > Hello! I am in a beginning algorithms class this semester and I am working > on a presentation. I want to discuss in some detail the algorithm python > uses to determine the hash function for python dictionaries. Does anyone > know what this algorithm is? Or where I can go to find information on it? > > Thanks. > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at mrabarnett.plus.com Mon Dec 15 12:14:34 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 15 Dec 2008 17:14:34 +0000 Subject: Structure using whitespace vs logical whitespace In-Reply-To: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> References: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> Message-ID: <4946907A.8040504@mrabarnett.plus.com> cmdrrickhunter at yaho.com wrote: > I've been trying to search through the years of Python talk to find an > answer to this, but my Googlefu is weak. > > In most languages, I'll do something like this > > xmlWriter.BeginElement("parent"); > ----xmlWriter.BeginElement("child"); > ----------xml.Writer.Characters("subtext"); > ----xmlWriter.EndElement(); > xmlWriter.EndElement(); > > Where the dashes are indentation (since some newsgroup handlers don't > do tabs well). XML writing is just an example. > > In general, I'm using indentation to show logical flow through code. > Python's choice to give semantic meaning to whitespace prevents me > from doing such things. What was once reserved for logical use is now > used syntactically. In 90% of cases, its not needed, and whitespace > significance seems to be pretty effective. In that last 10%, however, > I've been frustrated many times. > > I've been using python for a few years, and gotten around this in one > way or another, but now I want to get other who work with me to pick > up Python. All newbies to Python have trouble with the idea of > whitespace sensitivity, but how can I convince them that "it just > works better" when I have this construct which I want to use but > can't. > > Has anybody found a way to emulate this behavior? I've often done it > by opening an expression for the whole thing, but there's a lot of > tasks where a single expression just isn't sufficient (such as things > with assignment). > > PS. In my opinion the solution would be to have the option of entering > a "whitespace insensitive" mode which uses C style {} and ;. The > token to enter it could be as complicated as you want (in fact, it may > make sense to make it complicated to discourage use unless it's really > advantageous). I'd sugest {{ and }} or something bigger like {={ } > =}. Only two problems: 1) I'm sure it would offend Guido's sense of > language aesthetics 2) I'm sure the idea has been hashed over on this > newsgroup to death... hence prefering a workaround instead. > You could use the "with" statement: class xml_element(object): def __init__(self, text): self.text = text def __enter__(self): xmlWriter.BeginElement(self.text) def __exit__(self, *args): xmlWriter.EndElement() with xml_element("parent"): with xml_element("child"): xmlWriter.Characters("subtext") From tjreedy at udel.edu Mon Dec 8 17:01:34 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Dec 2008 17:01:34 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Rasmus Fogh wrote: > For my personal problem I could indeed wrap all objects in a wrapper with > whatever 'correct' behaviour I want (thanks, TJR). It does seem a bit I was not suggesting that you wrap *everything*, merely an adaptor for numpy arrays in whatever subclass and source it is that feeds them to your code. It is fairly unusual, I think, to find numpy arrays 'in the wild', outside the constrained context of numerical code where the programmer uses them intentionally and hopefully understands their peculiarities. > much, though, just to get code like this to work as intended: > alist.append(x) > print ('x is present: ', x in alist) Even if rich comparisons as you propose, the above would *still* not necessarily work. Collection classes can define a __contains__ that overrides the default and that can do anything, though True/False is recommended. As best I can think of at the moment, the only things you can absolutely depend on is that builtin id(ob) will return an int, that 'ob1 is ob2' (based in id()) will be True or False, and that builtin type(ob) will be a class (at least in 3.0, not sure of 2.x). The names can be rebound but you can control that within the module you write. This is what I meant when I said that 'generic' nearly always needs to be qualified to something like 'generic for objects that meet the interface requirements'. Every function has that precondition as part of its implied contract. Your code has an interface requirement that 'x in y' not raise an exception. An x,y pair that does it outside its contract. Terry Jan Reedy From tjreedy at udel.edu Thu Dec 4 13:31:01 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Dec 2008 13:31:01 -0500 Subject: Python 3 read() function In-Reply-To: <16651e80812040900j257fe2acjf5d8817811d32da6@mail.gmail.com> References: <16651e80812040900j257fe2acjf5d8817811d32da6@mail.gmail.com> Message-ID: Jerry Hill wrote: > On Thu, Dec 4, 2008 at 11:48 AM, Christian Heimes wrote: >> Cro wrote: >>> vContent = io.StringIO() >>> vContent = huge.read() # This line takes hours to process !!! >> Do you really mean io.StringIO? I guess you want io.BytesIO() .. > > I don't think it matters. Here's a quick comparison between 2.5 and > 3.0 on a relatively small 17 meg file: > > C:\>c:\Python30\python -m timeit -n 1 > "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" > 1 loops, best of 3: 36.8 sec per loop > > C:\>c:\Python25\python -m timeit -n 1 > "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" > 1 loops, best of 3: 33 msec per loop > > That's 3 orders of magnitude slower on python3.0! Timing of os interaction may depend on os. I verified above on WinXp with 4 meg Pythonxy.chm file. Eye blink versus 3 secs, duplicated. I think something is wrong that needs fixing in 3.0.1. http://bugs.python.org/issue4533 tjr From skip at pobox.com Thu Dec 4 12:49:34 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 4 Dec 2008 11:49:34 -0600 Subject: Python 3 read() function In-Reply-To: <6e24be88-b042-425b-b880-c97d184fee07@s20g2000yqh.googlegroups.com> References: <6e24be88-b042-425b-b880-c97d184fee07@s20g2000yqh.googlegroups.com> Message-ID: <18744.6190.414364.952537@montanaro-dyndns-org.local> >>> huge = io.open("C:\HUGE_FILE.pcl",'r+b',0) Why do you want to disable buffering? From the io.open help: open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True) Open file and return a stream. Raise IOError upon failure. ... buffering is an optional integer used to set the buffering policy. By default full buffering is on. Pass 0 to switch buffering off (only allowed in binary mode), 1 to set line buffering, and an integer > 1 for full buffering. I think you will get better performance if you open the file without the third arg: huge = io.open("C:\HUGE_FILE.pcl",'r+b') -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From kirk at daycos.com Mon Dec 15 15:24:14 2008 From: kirk at daycos.com (Kirk Strauser) Date: Mon, 15 Dec 2008 14:24:14 -0600 Subject: tricky nested list unpacking problem References: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> Message-ID: <87fxkpxk41.fsf@daycos.com> At 2008-12-15T20:03:14Z, "Chris Rebert" writes: > You just need a recursive list-flattening function. There are many > recipes for these. Here's mine: >>>> flattened = flatten([1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]]) >>>> flattened > [1, 2, 3, 5, 6, 10, 11, 7, 9, 1, 2, 3, 4, 5] >>>> '-'.join(str(num) for num in flattened) > '1-2-3-5-6-10-11-7-9-1-2-3-4-5' He doesn't want to flatten them directly. He's using [1,2,3] sort of like a regular expression, so that 1,[2,3],4 means "1,2,4" or "1,3,4", not "1,2,3,4". -- Kirk Strauser The Day Companies From noZ.spamZ at ZZ.ZsvpZ.com Mon Dec 15 18:38:09 2008 From: noZ.spamZ at ZZ.ZsvpZ.com (Michel Claveau - NoSpam SVP ; merci) Date: Tue, 16 Dec 2008 00:38:09 +0100 Subject: Problem Python 2.6.1 vs 2.6 & pyWin32 In-Reply-To: References: <4946754f$0$19000$426a74cc@news.free.fr><4946D09F.6050300@v.loewis.de> Message-ID: <4946ed94$0$22011$426a74cc@news.free.fr> Hi! I noted, also, than, in some cases, Python26.dll is not copied in %WINDIR%\system32 After that, external softs don't find the DLL. But it's a detail, because it's easy to copy the DLL with install scripts. @-salutations -- Michel Claveau From deets at nospam.web.de Wed Dec 10 07:45:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 10 Dec 2008 13:45:43 +0100 Subject: How do I manually uninstall setuptools (installed by egg)? References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> <375bd56a-d92b-4d33-bf70-5bea630a376a@q30g2000vbn.googlegroups.com> Message-ID: <6q9rvnFbj6ogU1@mid.uni-berlin.de> excord80 at gmail.com wrote: > On Dec 9, 10:04?pm, "Chris Rebert" wrote: >> So, why do you think apt and not setuptools is The Right Way(tm)? > > I like to keep > 1 Python on my computer. > > 1. First, there's the system Python, which is installed by my OS and > which I try not to mess with too much. I'm guessing Ubuntu uses this > Python for various system jobs, preferences apps, etc. I try to only > use apt with *this* Python. Start using virtualenv. You need to install that single package, and you can create as many python-instances (derived of your system's python of course) that you like. And inside these, mess around with setuptools as much as you like. > 2. Then there's my *own* Python. Maybe installed in ``/opt/py-i.j.k, > or---more likely---``~/opt/py-i.j.k``. *This* is the one where I've > previously made regular use of setuptools and ``easy_install``. If I > break this one somehow, it doesn't foul up my system Python in any > way, and it's easy to scrap it and start anew if I like. > > So, I'd like to get my *system* Python back to its "fresh out of the > Ubuntu showroom" condition and remove *that* setuptools. > > As an aside, I'm a bit struck by how long the setuptools/easy_install > manuals are, and a bit dismayed at the lack of an easy_install > uninstall command. Thinking of trying life for a while without > setuptools/easy_install. Will have to see how far I get. :) To *long* manuals? So far I haven't heard that complaint in the FOSS world... Diez Diez From google at mrabarnett.plus.com Sun Dec 21 11:31:51 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 21 Dec 2008 16:31:51 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: <494E6F77.2000203@mrabarnett.plus.com> Aaron Brady wrote: > On Dec 20, 8:49 pm, MRAB wrote: >> Aaron Brady wrote: >>> On Dec 20, 7:38 pm, Steven D'Aprano >> cybersource.com.au> wrote: >>>> Instead of just whinging, how about making a suggestion to fix it? Go on, >>>> sit down for an hour or ten and try to work out how a BINARY OPERATOR >>>> like % (that means it can only take TWO arguments) can deal with an >>>> arbitrary number of arguments, *without* having any special cases. >>>> Go on. Take your time. I'll be waiting. >>> Hi, not to take sides, but, there is a possibility. >>> This behavior is currently legal: >>>>>> "%i %%i" % 0 % 1 >>> '0 1' >>> So, just extend it. (Unproduced.) >>>>>> "%i %i" % 0 % 1 >>> '0 1' >>>>>> "%r %i" % (2, 3, 4) % 1 >>> '(2, 3, 4) 1' >>>>>> "%r %i" % (2, 3, 4) >>> '(2, 3, 4) %i' >>> Which is quite clever and way ahead of its (posessive) time. >> A couple of problems: >> >> 1. How do you handle a literal '%'? If you just double up then you'll >> need to fix the string after all your substitutions. >> >> 2. What if a substitution introduces a '%'? >> >> I suppose a possible solution would be to introduce a special format >> string, including a literal, eg: >> >> f"%r %i" % (2, 3, 4) % 1 >> >> and then convert the result to a true string: >> >> print(str(f"%r %i" % (2, 3, 4) % 1)) >> >> (although print() would call __str__ anyway). >> >> The format string would track where the last substitution occurred. >> >> Hmm... I think I'll just learn the new method. :-) > > Now that I'm fighting 'r's war for him/her... > > Um, here's one possibility. On the first interpolation, flags are > noted and stored apart from subsequent interpolations. Then, use a > sentinel to terminate the interpolation. (Unproduced.) > >>>> "%r %i" % ( 2, 3 ) % 0 > '(2, 3) 0' >>>> "%% %r" % ( 2, 3 ) % str.interp_end > '% (2, 3)' >>>> "%sss%i" % "%d" % 0 > '%dss0' > > The first %s is replaced with %d, but doesn't hijack the '0'. If you > want to interpolate the %d, use the sentinel. The sentinel is what > causes '%%' to be handled. > >>>> "%sss%i" % "%d" % 0 % 1 > Traceback (most recent call last): > File "", line 1, in > TypeError: not all arguments converted during string formatting >>>> "%sss%i" % "%d" % 0 % str.interp_end % 1 > '1ss0' > > Treating tuples as a special case appears to be the simpler solution, > but this, 'chaining', to adopt the term, is still feasible. > A possible solution occurred to me shortly after I posted, but I decided that sleep was more important. :-) The original format is a string. The result of '%' is a string if there's only 1 placeholder to fill, or a (partial) format object (class "Format"?) if there's more than one. Similarly, the format object supports '%'. The result of '%' is a string if there's only 1 placeholder to fill, or a new (partial) format object if there's more than one. >>> f = "%r %i" >>> type(f) >>> f = f % (2, 3, 4) >>> type(f) >>> f = f % 1 >>> type(f) From james at agentultra.com Fri Dec 5 11:51:17 2008 From: james at agentultra.com (J Kenneth King) Date: Fri, 05 Dec 2008 11:51:17 -0500 Subject: Python 3.0 automatic decoding of UTF16 References: Message-ID: <85fxl24lbu.fsf@dozer.localdomain> Johannes Bauer writes: > Traceback (most recent call last): > File "./modify.py", line 12, in > a = AddressBook("2008_11_05_Handy_Backup.txt") > File "./modify.py", line 7, in __init__ > line = f.readline() > File "/usr/local/lib/python3.0/io.py", line 1807, in readline > while self._read_chunk(): > File "/usr/local/lib/python3.0/io.py", line 1556, in _read_chunk > self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) > File "/usr/local/lib/python3.0/io.py", line 1293, in decode > output = self.decoder.decode(input, final=final) > File "/usr/local/lib/python3.0/codecs.py", line 300, in decode > (result, consumed) = self._buffer_decode(data, self.errors, final) > File "/usr/local/lib/python3.0/encodings/utf_16.py", line 69, in > _buffer_decode > return self.decoder(input, self.errors, final) > UnicodeDecodeError: 'utf16' codec can't decode bytes in position 74-75: > illegal encoding It probably means what it says: that the input file contains characters it cannot read using the specified encoding. Are you generating the file from python using a file object with the same encoding? If not, then you might want to look at your input data and find a way to deal with the exception. From tinnews at isbd.co.uk Fri Dec 19 11:23:49 2008 From: tinnews at isbd.co.uk (tinnews at isbd.co.uk) Date: 19 Dec 2008 16:23:49 GMT Subject: mailbox.mbox.add() appears to set both access and modification times Message-ID: <494bca95$0$510$bed64819@news.gradwell.net> I'm using mailbox in Python 2.5.2 to filter incoming mail into separate mailboxes. I prefer mbox for various reasons and so I have used that format. It would appear then when I do:- dest = mailbox.mbox(destDir, factory=None) dest.add(m) it sets both the access and modification times of the mbox to the date and time now. This is a disaster for MUAs that detect new mail by looking to see if the mbox has been modified after it was accessed. Is this a known bug in mailbox.mbox.add(), or am I doing something wrong, or what? -- Chris Green From timr at probo.com Sun Dec 28 00:22:05 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 28 Dec 2008 05:22:05 GMT Subject: math.sqrt() in new 3.0 version : solution in input() References: Message-ID: David Lemper wrote: > >I cannot find a mention of this in "The Python Tutorial >release 3.1" The I&O section discusses output formatting >and reading & writing text files. >John pointed out its in Guido's "What's New in Python3.0" >Indeed its mentioned in PEP 3111, near end of What's New >and somewhat obscurely. " raw_input() was renamed to input(). >That is the new input() function function reads a line from >sys.stdin . . ." The issue, in my view, is that input() (and raw_input()) are almost exclusively relegated to the domain of beginners and tutorials. Real programs almost never use them. As a result, this change just isn't seen to be all that important. If you can figure out where this could have been written so that you would have seen it, I'm sure a documentation change could be made. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From Scott.Daniels at Acm.Org Fri Dec 5 12:12:58 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 05 Dec 2008 09:12:58 -0800 Subject: pretty strange behavior of "strip" FORGET THE LAST ONE In-Reply-To: References: <4938693F.6090709@yahoo.ca> <493936EC.9030606@yahoo.ca> Message-ID: Guy Doune wrote: > > > Guy Doune a ?crit : >> Ok, didn't show the whole problem... >> >> I will read the doc anyway, but why "questions.html" keep it "t"?? >> >> >>> test=['03.html', '06.html', 'questions.html', '04.html', >> 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] >> >>> test[4] >> 'toc.html' >> >>> test[4].strip('.html') >> 'oc' >> >>> test[2].strip('.html') >> 'questions' Well, why does ' a b c '.strip() leave two spaces? --Scott David Daniels Scott.Daniels at Acm.Org From bieffe62 at gmail.com Mon Dec 22 04:57:12 2008 From: bieffe62 at gmail.com (bieffe62 at gmail.com) Date: Mon, 22 Dec 2008 01:57:12 -0800 (PST) Subject: How to represent a sequence of raw bytes References: Message-ID: <6d84efe9-7ca9-4031-9ee7-902e4c873f54@a26g2000prf.googlegroups.com> On 22 Dic, 03:23, "Steven Woody" wrote: > Hi, > > What's the right type to represent a sequence of raw bytes. ?In C, we usually do > > 1. ?char buf[200] ?or > 2. ?char buf[] = {0x11, 0x22, 0x33, ... } > > What's the equivalent representation for above in Python? > > Thanks. > > - > narke Usually, if I have to manipulate bytes (e.g. computing checksum, etc...) i just use a list of numbers: buf = [11, 22, 33, ...] then when I need to put it in a buffer similar to the one in C (e.g. before sending a packet of bytes through a socket or another I/O channel), I use struct.pack import struct packed_buf = struct.pack('B'*len(buf), buf ) similarly, if I get a packet of bytes from an I/O channel and I need to do operation on them as single bytes, I do: buf = struct.unpack('B'*len(packed_buf), packed_buf ) Note that struct.pack and struct.unpack can trasform packed bytes in other kind of data, too ... There are other - maybe more efficient - way of handling bytes in python programs, like using array as already suggested, but, up to now, I never needed them in my python programs, which are not real- time stuff, but sometime need to process steady flows of data. Ciao ---- FB From pruebauno at latinmail.com Tue Dec 9 12:13:03 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Tue, 9 Dec 2008 09:13:03 -0800 (PST) Subject: Python 3 For Python 2 Users References: Message-ID: <0c7ddb07-535f-4231-8ba7-ad099ccc19fa@13g2000yql.googlegroups.com> On Dec 9, 11:58?am, Tim Daneliuk wrote: > I code in Python 2.x intermittently and have only casually watched the > 3.x development discussions. ?Now it's time to get up to speed. > Has someone written a tutorial for people in my situation. ?Yes, I've > looked at the release notes, but I'm looking for something that > motivates all the major changes to give me a better sense of the > Gestalt of the new language. > > TIA, > -- > ---------------------------------------------------------------------------- > Tim Daneliuk ? ? tun... at tundraware.com > PGP Key: ? ? ? ?http://www.tundraware.com/PGP/ For starters this should work: http://docs.python.org/dev/3.0/whatsnew/3.0.html From google at mrabarnett.plus.com Fri Dec 12 10:04:51 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 12 Dec 2008 15:04:51 +0000 Subject: Python is slow In-Reply-To: <8156b37b-d1f6-4142-ad6e-8488c95b6592@z28g2000prd.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> <8156b37b-d1f6-4142-ad6e-8488c95b6592@z28g2000prd.googlegroups.com> Message-ID: <49427D93.3090800@mrabarnett.plus.com> sturlamolden wrote: > On Dec 12, 3:04 pm, Luis M. Gonz?lez wrote: > >> Why don't you guys google a little bit to know what's being done to >> address python's "slowness"?? > > Nothing is being done, and woth Py3k it got even worse. > >> It has been mentioned in this thread the pypy project (isn't it enough >> for you??) >> Other hints: shedskin, psyco, pyrex... > > None of those projects addresses inefficacies in the CPython > interpreter, except for psyco - which died of an overdose PyPy. > > PyPy is interesting if they ever will be able to produce something > useful. They have yet to prove that. Even if PyPy can come up with a > Python JIT, they will still be decades behind the technologies of > Strongtalk and Java. That is the problem with reinventing the wheel > all over again. > > Not to forget LLVM and Parrot which also will support Python > frontends. > Python is developed and maintained by volunteers. If you'd like to have a go at writing a JIT interpreter for it, then go ahead. No-one here will stop you. From temotor at gmail.com Fri Dec 19 02:32:02 2008 From: temotor at gmail.com (Sergey Shepelev) Date: Thu, 18 Dec 2008 23:32:02 -0800 (PST) Subject: Python lex settings References: <0dfeb0c3-a524-4a72-aafd-4b88b71ff16c@w39g2000prb.googlegroups.com> Message-ID: On Dec 19, 2:16?am, Robert Kern wrote: > Sergey Shepelev wrote: > > Hello. > > > I'm trying to make almost-Python source to Erlang source translation > > tool. > > > Are there ready ply.lex settings for parsing python source? > > Yes! Andrew Dalke has implemented a PLY grammar for Python for experimenting > with almost-Python languages. > > ? ?http://www.dalkescientific.com/Python/python4ply.html > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > ? that is made terrible by our own mad attempt to interpret it as though it had > ? an underlying truth." > ? ?-- Umberto Eco Wow! Thank you very much, it's exactly what i was searching for. From google at mrabarnett.plus.com Thu Dec 4 12:51:46 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 04 Dec 2008 17:51:46 +0000 Subject: Python 3 read() function In-Reply-To: References: Message-ID: <493818B2.1020404@mrabarnett.plus.com> Cro wrote: > Good day. > I have installed Python 3 and i have a problem with the builtin read() > function. > > [code] > huge = open ( 'C:/HUGE_FILE.pcl', 'rb', 0 ) > import io > vContent = io.StringIO() > vContent = huge.read() # This line takes hours to process !!! > vSplitContent = vContent.split > ( 'BIN;SP1;PW0.3,1;PA100,700;PD625,700;PU;' ) # This one i have neve > tried... > [/code] > > The same thing, in Python 2.5 : > > [code] > huge = open ( 'C:/HUGE_FILE.pcl', 'rb', 0 ) > import StringIO > vContent = StringIO.StringIO() > vContent = huge.read() # This line takes 2 seconds !!! > vSplitContent = vContent.split > ( 'BIN;SP1;PW0.3,1;PA100,700;PD625,700;PU;' ) # This takes a few > seconds... > [/code] > > My "HUGE_FILE" has about 900 MB ... > I know this is not the best method to open the file and split the > content by that code... > Can anyone please suggest a good method to split the file with that > code very fast, in Python 3 ? > The memory is not important for me, i have 4GB of RAM and i rarely use > more than 300 MB of it. > > Thank you very very much. > Can't you read it without StringIO? huge = open('C:/HUGE_FILE.pcl', 'rb', 0) vContent = huge.read() vSplitContent = vContent.split(b'BIN;SP1;PW0.3,1;PA100,700;PD625,700;PU;') vContent will contain a bytestring (bytes), so I think you need to split on a bytestring b'...' (in Python 3 unmarked string literals are Unicode). From svalbardcolaco at gmail.com Fri Dec 5 01:17:45 2008 From: svalbardcolaco at gmail.com (svalbard colaco) Date: Fri, 5 Dec 2008 11:47:45 +0530 Subject: CONNECTION TIMED OUT ERROR using urllib2 Message-ID: <726d283d0812042217w41a0288eg3ee79d4ffdb5ff4b@mail.gmail.com> Hi all I have written a small code snippet to open a URL using urllib2 to open a web page , my python version is 2.4 but i get an urlopen error called connection timed out The following is the code snippet *import urllib2 f = urllib2.urlopen('http://www.google.com/') print f.read(100)* where as the same url http://www.google.com/ works through my browser. The following is the back trace : File "test_url.py", line 3, in ? f = urllib2.urlopen('http://www.google.com/') File "/usr/lib/python2.4/urllib2.py", line 130, in urlopen return _opener.open(url, data) File "/usr/lib/python2.4/urllib2.py", line 358, in open response = self._open(req, data) File "/usr/lib/python2.4/urllib2.py", line 376, in _open '_open', req) File "/usr/lib/python2.4/urllib2.py", line 337, in _call_chain result = func(*args) File "/usr/lib/python2.4/urllib2.py", line 1021, in http_open return self.do_open(httplib.HTTPConnection, req) File "/usr/lib/python2.4/urllib2.py", line 996, in do_open raise URLError(err) *urllib2.URLError: Any pointers in this regard will be of great help. Thanking you'll in advance. Regards, sv -------------- next part -------------- An HTML attachment was scrubbed... URL: From noone at lewscanon.com Mon Dec 1 20:29:44 2008 From: noone at lewscanon.com (Lew) Date: Mon, 01 Dec 2008 20:29:44 -0500 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: anonymous.c.lisper at gmail.com wrote: > A rational human would realize that not too many people peruse this > newsgroup, > and that most of them have already seen the wall of text post that you > generate every time. Just out of curiosity, what do you consider "this" newsgroup, given its wide crossposting? -- Lew From castironpi at gmail.com Sat Dec 13 15:33:34 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 13 Dec 2008 12:33:34 -0800 (PST) Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> Message-ID: <3f834c00-8f5c-4917-b849-239c6231a078@t39g2000prh.googlegroups.com> On Dec 12, 7:31?am, Steve Holden wrote: > sturlamolden wrote: > > On Dec 12, 1:56 pm, sturlamolden wrote: > > >> That is because integers are immutable. When x += 1 is done on an int, > >> there will be a rebinding. But try the same on say, a numpy array, and > >> the result will be different: snip > This was all thrashed out exhaustively in the still-feared call > semantics thread. Yes, augmented operations work differently on mutable > and immutable objects. Nothing to see here, move right along ... Lol! From google at mrabarnett.plus.com Sun Dec 21 21:42:56 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 22 Dec 2008 02:42:56 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <2dfbb87b-019e-43aa-a9ef-5de2b5ada846@s1g2000prg.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <2dfbb87b-019e-43aa-a9ef-5de2b5ada846@s1g2000prg.googlegroups.com> Message-ID: <494EFEB0.3040900@mrabarnett.plus.com> Aaron Brady wrote: > On Dec 21, 6:14 pm, MRAB wrote: >> Aaron Brady wrote: >>> On Dec 21, 10:58 am, MRAB wrote: >>>> Aaron Brady wrote: >>>>> On Dec 21, 10:31 am, MRAB wrote: >>> snip >>>>>> The original format is a string. The result of '%' is a string if >>>>>> there's only 1 placeholder to fill, or a (partial) format object (class >>>>>> "Format"?) if there's more than one. Similarly, the format object >>>>>> supports '%'. The result of '%' is a string if there's only 1 >>>>>> placeholder to fill, or a new (partial) format object if there's more >>>>>> than one. >>>>>> >>> f = "%r %i" >>>>>> >>> type(f) >>>>>> >>>>>> >>> f = f % (2, 3, 4) >>>>>> >>> type(f) >>>>>> >>>>>> >>> f = f % 1 >>>>>> >>> type(f) >>>>>> >>>>> Alright, so how are you handling: >>>>>>>> f= "%s %i" >>>>>>>> type( f ) >>>>> >>>>>>>> f= f% '%i' #now '%i %i' >>>>>>>> type( f ) >>>>> >>>>>>>> f= f% 1 >>>>>>>> type( f ) >>>>> ? >>>>> In other words, are you slipping '1' in to the very first available >>>>> slot, or the next, after the location of the prior? >>>> Let's assume that Format objects display their value like the equivalent >>>> string format: >>>> >>> f = "%r %i" >>>> >>> f >>>> '%r %i' >>>> >>> f = f % (2, 3, 4) >>>> >>> f >>>> >>>> >>> f = f % 1 >>>> >>> f >>>> '(2, 3, 4) 1' >>>> >>> f = "%s %i" >>>> >>> f >>>> '%s %i' >>>> >>> f = f % '%i' >>>> >>> f >>>> >>>> >>> f = f % 1 >>>> >>> f >>>> '%%i 1' >>> I assume you meant '%i 1' since there are no more flags in f, and it's >>> returned to a regular string. >> Correct. >> >>> 'f %= 1' doesn't work any more as in-place modulo, since one time, 'f' >>> is a Format object, the other, 'f' is a string. Just raise an >>> exception for that (or assign to __class__ IINM if I'm not mistaken). >> All assignments rebind, even the augmented form: >> >> >>> class C1(object): >> def __mod__(self, value): >> return C2() >> >> >>> class C2(object): >> def __mod__(self, value): >> return C2() >> >> >>> f = C1() >> >>> f >> <__main__.C1 object at 0x00D144F0> >> >>> f % 0 >> <__main__.C2 object at 0x00D143F0> >> >>> f %= 0 >> >>> f >> <__main__.C2 object at 0x00D145B0> >> >> >> >>> Actually, the class you showed is kind of nifty. Tuples are correctly >>> interpolated. I think on the whole you'll use more parenthesis, since >>> each term in the tuple appears separately, and might be an expression >>> (have a lower-precedence op.), as well as more modulo signs. >>> You can currently do-it-yourself, you just need a constructor in the >>> format string. >>>>>> f = Format("%r %i") >>>>>> type(f) >>> >>>>>> f = f % (2, 3, 4) >>>>>> type(f) >>> >>> Or, as someone suggested earlier, a new literal marking: >> Yes, I suggested that earlier, but it isn't needed because you can >> create a format object with "Format(string)". However, most of the time >> you won't bother to create a format object explicitly because of: >> >> class str(object): >> def __mod__(self, value): >> return Format(self) % value >> >>>>>> f = f"%r %i" >>>>>> type(f) >>> >> >>> # Explicitly >> >>> f = Format("%r %i") >> >>> f >> >> >>> f % (2, 3, 4) >> >> >>> >> >>> # Implicitly, relying on the __mod__ method of str >> >>> f = "%r %i" >> >>> f >> '%r %i' >> >>> f % (2, 3, 4) >> >> >> I'd also like to add that there's nothing to prevent format objects from >> having other methods where multiple placeholders can be filled in one call: >> >> >>> # By position >> >>> f = Format("%r %i") >> >>> f >> >> >>> f.fill([(2, 3, 4), 1]) >> '(2, 3, 4) 1' >> >>> >> >>> # By name >> >>> f = Format("%{tuple}r %{int}i") >> >>> f >> >> >>> f.fill({"tuple": (2, 3, 4), "int": 1}) >> '(2, 3, 4) 1' > > You're choosing to favor the '.chain()' method over the '.fill()' > method for the behavior of '%'. I don't think you've justified it > though. > >>>> Format( "%r %i" ).chain( ( 2, 3, 4 ) ).chain( 0 ) > '(2, 3, 4) 0' >>>> Format( "%r %i" ).fill( ( 2, 3, 4 ), 0 ) > '(2, 3, 4) 0' > > Plus, I almost think we've almost attained defeating the purpose. > The disadvantage of the chaining method is that it's positional, left-to-right. For the purposes of i18n you want tagged placeholders, whether they be integers or names. I think... OK, if the placeholders include a positional tag, eg "%(0)s %(1)s", then they could be filled in according to _that_ order. Not sure about named placeholders, though. Perhaps, like at present, if a dict is given to a format with named placeholders then several placeholders could be filled, the problem being how to fill a _single_ named placeholder with a dict. From michael at stroeder.com Thu Dec 4 11:45:05 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Thu, 04 Dec 2008 17:45:05 +0100 Subject: EBCDIC <--> ASCII In-Reply-To: <091f0404-2be3-4bda-8619-03627bd03fdc@k8g2000yqn.googlegroups.com> References: <091f0404-2be3-4bda-8619-03627bd03fdc@k8g2000yqn.googlegroups.com> Message-ID: martinjamesevans at gmail.com wrote: > I'm having a problem trying to use the codecs package to aid me in > converting some bytes from EBCDIC into ASCII. Which EBCDIC variant? > sEBCDIC = unicode(sSource, 'cp500', 'ignore') Are you sure CP500 is the EBCDIC variant for the language you want? http://www.ietf.org/rfc/rfc1345.txt lists it as: &charset IBM500 &rem source: IBM NLS RM Vol2 SE09-8002-01, March 1990 &alias CP500 &alias ebcdic-cp-be &alias ebcdic-cp-ch > Obviously I could just knock up a 255 character lookup table and do it > myself, I was just trying to be a little more Pythonic and use that > built in table. It's pythonic to implement a Unicode codec for unknown character tables. I've put these two on my web site: http://www.stroeder.com/pylib/encodings/ebcdicatde.py http://www.stroeder.com/pylib/encodings/cp273.py (needs ebcdicatde) Ciao, Michael. From ranjith.priya at gmail.com Fri Dec 19 01:12:55 2008 From: ranjith.priya at gmail.com (Priya Ranjith) Date: Thu, 18 Dec 2008 22:12:55 -0800 (PST) Subject: Openings for Release Management Message-ID: <988ff2f1-b4f3-460f-b087-2406cc6baa41@w1g2000prk.googlegroups.com> Position: Build and Release Engineer Experience Required: 2 - 7 yrs Qualification: B.E/M.E/M.C.A/B.Tech Skills Required: 1) Working experience in distributed version control system like Mercurial / Bazar / GIT or Subversion 2) Experience in RBuilder 3) Working experience in creating software appliance. 4) Experience in Python 5) Working experience in Ant / Maven 6) Should posses good communication skills: excellent English, both written and spoken is a must. 7) High level of professionalism The Release Engineer function has the following key areas of responsibility: 1) Continuous improvement of Release processes, methodologies and tools to ensure best quality for both product lines: Community Edition and Professional Edition. 2) Track and support the whole Release cycle, coordinating teams involved in the Release processes: engineering, QA, Beta Testers and Community. 3) Keep people informed about status, contents, dates, etc. 4) Support Senior Management to define the guidelines of whole release product strategy. From ldo at geek-central.gen.new_zealand Thu Dec 4 17:57:34 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 05 Dec 2008 11:57:34 +1300 Subject: Don't you just love writing this sort of thing :) References: Message-ID: In message , Duncan Booth wrote: > Have you ever considered trying to write readable code instead? > > (I must admit I haven't checked whether GZipFile works with the 'with' > statement... That's why I prefer writing _correct_ code instead. From pavlovevidence at gmail.com Mon Dec 15 14:53:40 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 15 Dec 2008 11:53:40 -0800 (PST) Subject: alt.possessive.its.has.no.apostrophe References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> Message-ID: <4f36bf19-40f2-4e88-8867-18a760000120@u18g2000pro.googlegroups.com> On Dec 15, 1:55?am, Ben Finney wrote: > James Stroud writes: > > Ben Finney wrote: > > > James Stroud writes: > > > >> Yes. I think it was the British who decided that the apostrophe > > >> rule for "it" would be reversed from normal usage relative to > > >> just about every other noun. > > It also seems an indefensible claim to say that anyone ?decided? it > would be that way, especially ?the British?. > > > > Remember that ?it? is a pronoun. I see no reversal: > > > Ok. Pronouns are reversed. > > Or, more generally: Pronouns, which are different in just about every > other way from other nouns, are different in this way also. Is that > about right? No. Most pronouns form their possessives the same way nouns do. E.g.: Someone's hat is over there. One does with one's hand whatever one pleases. Whoever's shoes are downstairs better get them. The computer that's power is still on is wasting energy. The seven personal pronouns and "who" are the only words to form their possessives irregularly. However "it" and "who" *pronounce* their possessives exactly as nouns do. They just spell them differently, for no really good reason. The way I see it, if the rule had been, "Use an apostrophe for any word that forms it's possessive by adding an s or z sound", it would have been less inconsistent. Sadly, that's not the rule. English spelling is the Perl of orthography. Carl Banks (...For that matter, if the rule had been, "Never augment your words spelling with an apostrophe", it would have really simplified things....) From google at mrabarnett.plus.com Sat Dec 20 21:21:36 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 21 Dec 2008 02:21:36 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> <88a122de-14c6-4025-b36c-9a39bdd50d86@i20g2000prf.googlegroups.com> Message-ID: <494DA830.1040502@mrabarnett.plus.com> bearophileHUGS at lycos.com wrote: > walterbyrd: >> As I understand it, that may have been true at one time. But, Ruby 1.9 >> very significantly sped up the language. While Python has been made >> slower, Ruby has been made much faster. > > I have already answered regarding Python3 in this thread. Regarding > Ruby you are right, in computer science there are lot of ways to speed > up things. So it may be quite possible for Ruby to become "faster" > than CPython. > For example this may speed up the PythonVM some: > "Optimizing direct threaded code by selective inlining": > http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.8829&rep=rep1&type=pdf > Interesting. The re module uses a form of bytecode. Not sure about the relative cost of the dispatch code, though. From __peter__ at web.de Mon Dec 8 06:05:47 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 08 Dec 2008 12:05:47 +0100 Subject: Determining whether a variable is less/greater than a range. References: <362ab93b-b804-4ebe-a22f-e422feb301c8@c1g2000yqg.googlegroups.com> Message-ID: simonharrison.uk at googlemail.com wrote: > Hi. I'm having another go at learning Python so I'll probably be > asking a few basic questions. Here is the first one. > > a = list(range(10, 21) > > b = 9 > > c = 21 > > How can I find out if b and c have values less or more than the values > in list a? >>> a = range(10, 21) >>> b = 9 >>> c = 21 Are there any items in a that are less than b or greater than c? >>> any(xc for x in a) False No. Are there any items in a that are greater than b? >>> any(x>b for x in a) True Yes. Peter From zaz600 at gmail.com Wed Dec 24 04:46:30 2008 From: zaz600 at gmail.com (NoName) Date: Wed, 24 Dec 2008 01:46:30 -0800 (PST) Subject: SyntaxError: encoding problem: with BOM Message-ID: i have 1.py in cp866 encoding: # -*- coding: cp866 -*- print ("ff") It's not work in Python 3.0 Error: File "", line 1 SyntaxError: encoding problem: with BOM what's wrong? From youcancallmeal at gmail.com Fri Dec 19 14:03:09 2008 From: youcancallmeal at gmail.com (youcancallmeal at gmail.com) Date: Fri, 19 Dec 2008 11:03:09 -0800 (PST) Subject: Segmentation fault in PyObjectMalloc on FreeBSD Message-ID: <2c36470f-8dff-4fcd-9e86-3abcc01e4c49@s9g2000prm.googlegroups.com> I have a multithreaded python app running on FreeBSD (both 7.0 and 6.3) that crashes with a segmentation fault coming from PyObjectMalloc. This first happened using Python 2.5 built from Ports. I then pulled down r261 from Subversion and built that so I would have debugging symbols; it still crashed. Below is a back trace from gdb: #0 PyObject_Malloc (nbytes=2) at Objects/obmalloc.c:758 #1 0x080942aa in PyString_FromStringAndSize (str=0x0, size=50) at Objects/stringobject.c:83 #2 0x0809b30b in PyString_FromFormatV (format=0x813c6d4 "%.50s instance has no attribute '%.400s'", vargs=0xbf6fa048 "??.\b?Q\031\b??>\b") at Objects/stringobject.c: 238 #3 0x080dcd48 in PyErr_Format (exception=0x8158660, format=0x813c6d4 "%.50s instance has no attribute '%.400s'") at Python/errors.c:538 #4 0x08064549 in instance_getattr1 (inst=0x833ed4c, name=0x81951b0) at Objects/classobject.c:717 #5 0x08067c9f in instance_nonzero (self=0x833ed4c) at Objects/ classobject.c:754 #6 0x0808a592 in PyObject_IsTrue (v=0x8473000) at Objects/object.c: 1532 #7 0x080cb6d3 in PyEval_EvalFrameEx (f=0x857860c, throwflag=0) at Python/ceval.c:2173 #8 0x080cef5d in PyEval_EvalFrameEx (f=0x8574e0c, throwflag=0) at Python/ceval.c:3765 #9 0x080cef5d in PyEval_EvalFrameEx (f=0x856980c, throwflag=0) at Python/ceval.c:3765 #10 0x080cfbe8 in PyEval_EvalCodeEx (co=0x82f7218, globals=0x49, locals=0x815dd40, args=0x819402c, argcount=4, kws=0x83a99a0, kwcount=0, defs=0x833e758, defcount=2, closure=0x0) at Python/ ceval.c:2942 #11 0x08124260 in function_call (func=0x83408b4, arg=0x846ee64, kw=0x845546c) at Objects/funcobject.c:524 #12 0x08060402 in PyObject_Call (func=0x83408b4, arg=0x846ee64, kw=0x845546c) at Objects/abstract.c:2487 #13 0x080cbdbc in PyEval_EvalFrameEx (f=0x856dc0c, throwflag=0) at Python/ceval.c:3978 #14 0x080cfbe8 in PyEval_EvalCodeEx (co=0x82f6cc8, globals=0x49, locals=0x815dd40, args=0x819402c, argcount=2, kws=0x8572154, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c: 2942 #15 0x080cdbda in PyEval_EvalFrameEx (f=0x857200c, throwflag=0) at Python/ceval.c:3774 #16 0x080cef5d in PyEval_EvalFrameEx (f=0x850860c, throwflag=0) at Python/ceval.c:3765 #17 0x080cef5d in PyEval_EvalFrameEx (f=0x850940c, throwflag=0) at Python/ceval.c:3765 #18 0x080cef5d in PyEval_EvalFrameEx (f=0x857680c, throwflag=0) at Python/ceval.c:3765 #19 0x080cfbe8 in PyEval_EvalCodeEx (co=0x83c5f50, globals=0x49, locals=0x815dd40, args=0x819402c, argcount=2, kws=0x8506364, kwcount=0, defs=0x83d1c78, defcount=1, closure=0x0) at Python/ ceval.c:2942 #20 0x080cdbda in PyEval_EvalFrameEx (f=0x850620c, throwflag=0) at Python/ceval.c:3774 #21 0x080cef5d in PyEval_EvalFrameEx (f=0x850980c, throwflag=0) at Python/ceval.c:3765 #22 0x080cef5d in PyEval_EvalFrameEx (f=0x84efa0c, throwflag=0) at Python/ceval.c:3765 #23 0x080cef5d in PyEval_EvalFrameEx (f=0x84ef80c, throwflag=0) at Python/ceval.c:3765 #24 0x080cef5d in PyEval_EvalFrameEx (f=0x84ef60c, throwflag=0) at Python/ceval.c:3765 #25 0x080cef5d in PyEval_EvalFrameEx (f=0x84ef40c, throwflag=0) at Python/ceval.c:3765 #26 0x080cef5d in PyEval_EvalFrameEx (f=0x84ef20c, throwflag=0) at Python/ceval.c:3765 #27 0x080cfbe8 in PyEval_EvalCodeEx (co=0x82cdf98, globals=0x49, locals=0x815dd40, args=0x819402c, argcount=1, kws=0x0, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2942 #28 0x08124260 in function_call (func=0x82e8b8c, arg=0x8471dec, kw=0x0) at Objects/funcobject.c:524 #29 0x08060402 in PyObject_Call (func=0x82e8b8c, arg=0x8471dec, kw=0x0) at Objects/abstract.c:2487 #30 0x08069bed in instancemethod_call (func=0x49, arg=0x8471dec, kw=0x0) at Objects/classobject.c:2579 #31 0x08060402 in PyObject_Call (func=0x83e8a7c, arg=0x819402c, kw=0x0) at Objects/abstract.c:2487 #32 0x080c87da in PyEval_CallObjectWithKeywords (func=0x83e8a7c, arg=0x819402c, kw=0x0) at Python/ceval.c:3548 #33 0x080fccdd in t_bootstrap (boot_raw=0x83a9910) at ./Modules/ threadmodule.c:425 #34 0x281b05cf in pthread_create () from /usr/lib/libthr.so.2 #35 0x00000000 in ?? () This part is particularly interesting: (gdb) frame 1 #1 0x080942aa in PyString_FromStringAndSize (str=0x0, size=50) at Objects/stringobject.c:83 83 op = (PyStringObject *)PyObject_MALLOC(sizeof (PyStringObject) + size); (gdb) print size $7 = 50 (gdb) print sizeof(PyStringObject) $8 = 24 (gdb) frame 0 #0 PyObject_Malloc (nbytes=2) at Objects/obmalloc.c:758 758 if ((pool->freeblock = *(block **)bp) ! = NULL) { (gdb) print nbytes $9 = 2 So 50 + 24 == 2? Or am I missing something? Can anyone suggest how to figure out what's really going on here? From rt8396 at gmail.com Mon Dec 22 22:38:29 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 19:38:29 -0800 (PST) Subject: iterating initalizations References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> Message-ID: <73f58305-b7f3-4536-b193-79d66d68d6f7@t3g2000yqa.googlegroups.com> >>> class test(): def __init__(self, name): self.name = 'My name is %d' %name >>> l = [] >>> for name in range(10): l.append(test(name)) >>> l [<__main__.test instance at 0x02852E18>, <__main__.test instance at 0x02852C38>, <__main__.test instance at 0x028528A0>, <__main__.test instance at 0x02852E90>, <__main__.test instance at 0x02852EE0>, <__main__.test instance at 0x02852F30>, <__main__.test instance at 0x02852F80>, <__main__.test instance at 0x02852FD0>, <__main__.test instance at 0x023AFC60>, <__main__.test instance at 0x02855030>] >>> l[0].name 'My name is 0' >>> l[1].name 'My name is 1' From steve at REMOVE-THIS-cybersource.com.au Sun Dec 21 05:14:24 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Dec 2008 10:14:24 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: <015e0e47$0$20656$c3e8da3@news.astraweb.com> On Sun, 21 Dec 2008 00:57:46 -0800, Patrick Mullen wrote: > 2) In my experience, major version changes tend to be slower than > before. When a lot of things change, especially if very low-level > things change, as happened in python 3.0, the new code has not yet went > through many years of revision and optimization that the old code has. I was around for the change from Python 1.5 -> 2.x. By memory, I skipped a couple of versions... I think I didn't make the move until Python 2.2 or 2.3 was released. Python 2.0 was significantly slower than 1.5 in a number of critical areas, but not for long. Actually, it's quite possible that Python 1.5 is still faster than Python 2.x in some areas -- but of course it misses a lot of features, and at the end of the day, the difference between your script completing in 0.03 seconds or in 0.06 seconds is meaningless. > In my opinion, python 3 was rushed out the door a bit. It could have > done with a few more months of optimization and polishing. However, on > the other hand, it is going to take so long for python infrastructure to > convert to python 3, that an earlier release makes sense, even if it > hasn't been excessively polished. The biggest reason for the speed > change is the rewritten stdio and unicode-everything. Hopefully this > stuff can be improved in future updates. I don't think anyone WANTS > cpython to be slower. I understand that the 3.0.1 release due out around Christmas will have some major speed-ups in stdio. -- Steven From jerry.carl.mi at gmail.com Sun Dec 28 10:55:24 2008 From: jerry.carl.mi at gmail.com (jerry.carl.mi at gmail.com) Date: Sun, 28 Dec 2008 07:55:24 -0800 (PST) Subject: math module for Decimals References: <41937dc9-4b67-43b5-9eab-6f8c851474cf@p2g2000prn.googlegroups.com> Message-ID: > - are you using Decimal for the base-10-ness or the > ? extra precision Decimal provides? ?Or significant zeros? > ? Or compatibility with existing Decimal code, or what? Oh boy, now I will finally prove myself illiterate... well, so be it. But i am after the extra precision: >>> from math import * >>> (1+1e-16)-1 0.0 ...in this trivial example above I will lose the 1e-16... which may be an issue if you code something that evaluates slightly more complex expressions. I would feel much more comfortable if I lose 1e-60. But in physics, one can get parts of an expression equal to 1e-16 while (by mistake or not) other parts are > 1. Hence it becomes a greater puzzle to debug the calculation. Having the possibility to increase precision would help. Sure, you can say, there is such a small market for this application, and maybe I should use other tools. Well, I found Python so much easier to use for other reasons. And, again, it seems like there is a desire for it outside of my own office. > - what 3 functions would you most like to see added? > ? For me, I think it would be something like sin, cos > ? and atan (or possibly atan2). ?Once you've got those > ? three, everything else is fairly easy. ?In particular, > ? atan/atan2 at least gives you access to pi. Agree: sin, cos and atan would do it. > FWIW, I'm the author of the current Decimal log, log10, exp > and pow functions, so I'm probably in a fairly good position > to try to implement reasonably high-quality versions of some > other elementary functions (again, just as an external > addition to the decimal module, not as part of the decimal > module itself). ?This is an itch I've often wanted > scratched, as well. ?I might just have a go.... > (Help in the form of code, tests, suggestions, etc. > would be welcome!) > > Mark Wow, i would never think my posting would go that high in the Python world. I can't wait to tell my colleagues after these holidays ;-) If I improve (in my view that is) the existing modules (dmath) etc. i will keep you posted. For now I am reducing large arguments of goniometric functions by adding the following into the dmath's sin(x) and cos(x): x=Decimal.__mod__(x,Decimal('2')*pi()) Works fine for what i need, but i am sure it's not the right way to do it. Thanks Mark! From sumerc at gmail.com Mon Dec 29 05:17:42 2008 From: sumerc at gmail.com (k3xji) Date: Mon, 29 Dec 2008 02:17:42 -0800 (PST) Subject: Read-Write Lock vs primitive Lock() References: Message-ID: <277c1be7-2560-4fd6-9610-0b4398dc3719@x16g2000prn.googlegroups.com> On 29 Aral?k, 11:52, "Gabriel Genellina" wrote: > En Mon, 29 Dec 2008 05:56:10 -0200, k3xji escribi?: > > > I ?am trying to see on which situations does the Read-Write Lock > > performs better on primitive Lock() itself. Below is the code I am > > using to test the performance: > > import threading > > import locks > > import time > > > class mylock(object): > > (I'm not convinced your lock is correct) No problem.:) > > GLOBAL_VAR = 1 > > #GLOBAL_LOCK = locks.ReadWriteLock() > > GLOBAL_LOCK = threading.Lock() > > #GLOBAL_LOCK = mylock() > > GLOBAL_LOOP_COUNT = 100000 > > GLOBAL_READER_COUNT = 1000 > > GLOBAL_WRITER_COUNT = 1 > > Only one writer? If this is always the case, you don't need a lock at all. No just used for testing. It does not matter, what I want to see is that I want to create a botleneck on readers. > > class wthread(threading.Thread): > > ? ? def run(self): > > ? ? ? ? ? ? try: > > ? ? ? ? ? ? ? ? #GLOBAL_LOCK.acquireWrite() > > ? ? ? ? ? ? ? ? #GLOBAL_LOCK.acquire_write() > > ? ? ? ? ? ? ? ? GLOBAL_LOCK.acquire() > > ? ? ? ? ? ? ? ? for i in range(GLOBAL_LOOP_COUNT): > > ? ? ? ? ? ? ? ? ? ? GLOBAL_VAR = 4 > > ? ? ? ? ? ? finally: > > ? ? ? ? ? ? ? ? #GLOBAL_LOCK.release_write() > > ? ? ? ? ? ? ? ? GLOBAL_LOCK.release() > > Note that the thread acquires the lock ONCE, repeats several thousand > times an assignment to a *local* variable called GLOBAL_VAR (!), finally > releases the lock and exits. As every thread does the same, they just run > one after another, they never have a significant overlap. If I put the for loop outside, in that case, readers will not overlap at all, and you would be amazed by the numbers for that test. They indicate primitive lock is faster than read-write lock, as it requires the lock, executes only one bytecode operation and releases the lock. So, in order to create a bottlenneck on readers, we need to somehow do not release the lock immediately. > Also, you should acquire the lock *before* the try block (you have to > ensure that, *after* acquiring the lock, it is always released; such > requisite does not apply *before* acquiring the lock) Yeah, you are right but it is irrelevant. > I'd test again with something like this: > > class wthread(threading.Thread): > ? ? ? def run(self): > ? ? ? ? ? global GLOBAL_VAR > ? ? ? ? ? for i in xrange(GLOBAL_LOOP_COUNT): > ? ? ? ? ? ? ? GLOBAL_LOCK.acquire() > ? ? ? ? ? ? ? try: > ? ? ? ? ? ? ? ? ? GLOBAL_VAR += 1 > ? ? ? ? ? ? ? finally: > ? ? ? ? ? ? ? ? ? GLOBAL_LOCK.release() With that, primitive locks perform 10 times better than Read-Write lock. See above. > > class rthread(threading.Thread): > > ? ? def run(self): > > ? ? ? ? ? ? try: > > ? ? ? ? ? ? ? ? #GLOBAL_LOCK.acquireRead() > > ? ? ? ? ? ? ? ? #GLOBAL_LOCK.acquire_read() > > ? ? ? ? ? ? ? ? GLOBAL_LOCK.acquire() > > ? ? ? ? ? ? ? ? for i in range(GLOBAL_LOOP_COUNT): > > ? ? ? ? ? ? ? ? ? ? GLOBAL_VAR = 3 > > ? ? ? ? ? ? finally: > > ? ? ? ? ? ? ? ? #GLOBAL_LOCK.release_read() > > ? ? ? ? ? ? ? ? GLOBAL_LOCK.release() > > Hmmm, it's a reader but attempts to modify the value? > You don't have to protect a read operation on a global variable - so a > lock isn't required here. This is just for testing. Suppose that I am actually reading the value. I don't understand why a lock is not required? Are you saying lock is not necesary beacuse GLOBAL_VALUE is an immutable object, if then, suppose it is not. This is just a test. Suppose GLOBAl_VAR is a list and we are calling append() on it which is nt an atomic operation. > > What I am doing is: I am creating multiple readers and try to do > > something. I had assumed that with using primitive Lock() on the above > > situation, it will create a bottleneck on the rthreads. But the > > numbers indicate that there are no difference at all. I had > > implemented my own READ-WRIET lock as can be seen above mylock and > > also used the one here: code.activestate.com/recipes/502283/. > > I hope you now understand why you got the same numbers always. Unfortunately, I do not understand anyhing. Thanks. From bearophileHUGS at lycos.com Sat Dec 13 09:13:20 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 13 Dec 2008 06:13:20 -0800 (PST) Subject: Shorter tracebacks Message-ID: When I write recursive code in Python I sometimes go past the maximum allowed stack depth, so I receive a really long traceback. The show of such traceback on my screen is very slow (despite a CPU able to perform billions of operations each second). So I think I'd like something to shorten them. I am thinking about something like: from __future__ import short_traceback That allows me to see only the first and last parts of the stack trace, and skips the (generally very redundant) middle part. Note that generally using sys.setrecursionlimit(limit) to set a smaller limit isn't good, because I may need a big depth anyway. Bye, bearophile From renesd at gmail.com Sun Dec 7 23:26:36 2008 From: renesd at gmail.com (illume) Date: Sun, 7 Dec 2008 20:26:36 -0800 (PST) Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? References: <5ccd4a18-cd2b-4040-90c6-33723af15e96@b38g2000prf.googlegroups.com> Message-ID: hello, PyOpenGL also has a raw module which includes python bindings closer to the C calls... however mostly you want to use the nicer more pythonic versions of functions. Recent pyopengl 3.x versions have been optimized for speed, including optional C level optimizations. So I imagine they are faster than pyglets wrappers(profiling/testing needed). PyOpenGL is also used a lot more by non-game people, so a wider array of functions are used. It's very unfortunate that pyglet and pyopengl don't share code... however recent versions of pyopengl tried to reuse some of pyglets code... not sure how much has been shared though. Maybe at some point they will come together. For now pyglet has created a fork in the python+opengl community, where the same code can't be reused automatically between the two as the opengl wrappers are slightly different. However it's not terribly difficult to port code from one to the other, as some projects have done. pygame doesn't require opengl be supported by the video card - it can use many different video drivers to get the job done. It's nice to be able to avoid using the 3D parts of gfx cards if you can - to reduce power consumption, and make your game run on more computers. pygame is also much more portable, has more people using it, has more developers, and a stable API. Code you wrote 5 years ago will most likely still work. Code you wrote for older versions of pyglet will not work without changes. pygame is simpler to learn, since it doesn't require you to know how to create classes or functions. Whereas pyglet requires you to sub class to do anything. http://pygame.org/wiki/about * disclaimer - I'm a pygame developer, and have in the past contributed to pyopengl - so obviously I prefer pygame and pyopengl. On Dec 8, 12:53?pm, alex23 wrote: > On Dec 8, 11:23?am, excor... at gmail.com wrote: > > > Does pyglet use PyOpenGL as its OpenGL wrapper? If not, any idea why? > > Seems like it would be a fairly substantial duplication of effort. > > Taken from:http://groups.google.com/group/pyglet-users/msg/832b15389fccd28d > > > > >> IIRC pyglet tries to minimize dependencies, so PyOpenGL won't be > >> used. ?However, pyglet's wrapping of OpenGL isn't meant to be > >> complete; it's only what pyglet itself uses. ?You'll need to use > >> PyOpenGL for the rest. > > That was more or less the original plan. ?pyglet wraps OpenGL at the > > lowest level, so it only provides glVertex3f, glVertex2d, etc., > > whereas PyOpenGL also provides polymorphic functions such as glVertex. > [...] > > pyglet provides all of the error-checking functionalities that > > PyOpenGL does (though these can be disabled for performance). ?At > > last check, pyglet was significantly faster than PyOpenGL 3, but > > slower than PyOpenGL 2. > > From Tribulations at Paralleles.invalid Tue Dec 2 09:09:53 2008 From: Tribulations at Paralleles.invalid (TP) Date: Tue, 02 Dec 2008 15:09:53 +0100 Subject: best way to do this Message-ID: Hi everybody, >>> c=[(5,3), (6,8)] >From c, I want to obtain a list with 5,3,6, and 8, in any order. I do this: >>> [i for (i,j) in c] + [ j for (i,j) in c] [5, 6, 3, 8] Is there a quicker way to do this? Thanks Julien -- python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z (55l4('])" "When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong." (first law of AC Clarke) From steve at REMOVE-THIS-cybersource.com.au Sat Dec 13 22:16:19 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Dec 2008 03:16:19 GMT Subject: [OT] stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> Message-ID: <01547201$0$6988$c3e8da3@news.astraweb.com> On Sat, 13 Dec 2008 19:17:41 +0000, Duncan Booth wrote: > I think you must have fallen asleep during CS101. The lower bound for > sorting where you make a two way branch at each step is O(n * log_2 n), > but if you can choose between k possible orderings in a single > comparison you can get O(n * log_k n). I think you might have been sleeping through Maths 101 :-) The difference between log_2 N and log_k N is a constant factor (log_2 k) and so doesn't effect the big-oh complexity. -- Steven From eckhardt at satorlaser.com Thu Dec 4 11:43:34 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 04 Dec 2008 17:43:34 +0100 Subject: EBCDIC <--> ASCII References: <091f0404-2be3-4bda-8619-03627bd03fdc@k8g2000yqn.googlegroups.com> Message-ID: martinjamesevans at gmail.com wrote: > I've tried starting with something like this, but I assume it is > expecting the source to be in unicode already? > > e.g. (pretend the second half are EBCDIC characters) > > sAll = "This bit is ASCII, " Why pretend? You can use this: "abcde\x81\x82\x83\x84" > sSource = sAll[19:] > > sEBCDIC = unicode(sSource, 'cp500', 'ignore') If you mean this sSource, then no. sSource is treated as byte string here which is converted to Unicode using 'cp500' as encoding. Note that in interactive mode, 'print x' will actually convert the string according to stdout's current encoding (typically ASCII or - I think - Latin 1). s1 = u'abcde' s2 = s1.encode('cp500') s3 = s1.encode('ascii') s4 = unicode( s2, 'cp500') s5 = unicode( s3, 'ascii') Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From rdmurray at bitdance.com Fri Dec 19 23:27:46 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Sat, 20 Dec 2008 04:27:46 +0000 (UTC) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c4ef2$0$20656$c3e8da3@news.astraweb.com> Message-ID: Quoth Steven D'Aprano : > Whether using % or format(), I don't see the need to change the code, > only the strings. > > Using positional arguments is not really that different: > > "{0} {1}".format("dead", "parrot") > "{0} {1}".format("perroquet", "mort") This should be something like: _("{0} {1}").format(_("dead"), _("parrot")) where il8n would substitute the template "{1} {0}" when doing French. > versus: > > "%s %s" % ("dead", "parrot") > "%s %s" % ("perroquet", "mort") > > In this case, the template on the left remains the same, you just have to > reorder the string arguments on the right. Clearly less satisfactory than > the solution using keyword substitution, but whatever solution you pick, > I don't see any advantage to format() over % formatting. Can you show an > example? Not less satisfactory, but rather unworkable. You can't do proper il8n with %s formatting, since there is no way for the il8n machinery to reorder the argument tuple. It can only translate the template string. So when doing il8n, the {} syntax wins out for brevity over the equivalent % syntax (%s(somename)s). Not that brevity is that important an argument. The new system is just so much more flexible than the old. As someone else said, the design is beautiful :) I have a couple thousand lines of python code I wrote a while back to layer on a system with this kind of flexibility...I was shocked and pleased when I saw the PEP, since it echoed so many of the ideas I had implemented in that code, plus more. And all done better of course :) --RDM From steve at REMOVE-THIS-cybersource.com.au Tue Dec 16 20:26:58 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 17 Dec 2008 01:26:58 GMT Subject: Does Python3 offer a FrozenDict? References: Message-ID: <01584ccb$0$20656$c3e8da3@news.astraweb.com> On Tue, 16 Dec 2008 17:59:30 +0100, Johannes Bauer wrote: > Hello group, > > is there anything like a frozen dict in Python3, so I could do a > > foo = { FrozenDict({"a" : "b"}): 3 } > > or something like that? If *all* you want is to use it as a key, then: tuple(sorted(some_dict.items)) may do the job. -- Steven From aahz at pythoncraft.com Sat Dec 6 12:24:36 2008 From: aahz at pythoncraft.com (Aahz) Date: 6 Dec 2008 09:24:36 -0800 Subject: Learning Python now coming from Perl References: Message-ID: In article , Bertilo Wennergren wrote: > >I don't suppose there is any introductory material out there that is >based on Python 3000 and that is also geared at people with a Perl >background? Too early for that I guess.. Honestly, the differences between 2.x and 3.0 are small enough that it doesn't much matter, as long as you're not the kind of person who gets put off by little problems. Because so much material is for 2.x, you may be better off just learning 2.x first and then moving to 3.x. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From simonharrison.uk at googlemail.com Mon Dec 8 08:32:06 2008 From: simonharrison.uk at googlemail.com (simonh) Date: Mon, 8 Dec 2008 05:32:06 -0800 (PST) Subject: Beginner trying to understand functions. Message-ID: In my attempt to learn Python I'm writing a small (useless) program to help me understand the various concepts. I'm going to add to this as I learn to serve as a single place to see how something works, hopefully. Here is the first approach: name = input('Please enter your name: ') print('Hello', name) while True: try: age = int(input('Please enter your age: ')) break except ValueError: print('That was not a valid number. Please try again.') permitted = list(range(18, 31)) if age in permitted: print('Come on in!') elif age < min(permitted): print('Sorry, too young.') elif age > max(permitted): print('Sorry, too old.') input('Press any key to exit.') That works fine. Then I've tried to use functions instead. The first two work fine, the third fails: def getName(): name = input('Please enter your name: ') print('Hello', name) def getAge(): while True: try: age = int(input('Please enter your age: ')) break except ValueError: print('That was not a valid number. Please try again.') def checkAge(): permitted = list(range(18, 31)) if age in permitted: print('Come on in!') elif age < min(permitted): print('Sorry, too young.') elif age > max(permitted): print('Sorry, too old.') getName() getAge() checkAge() I get this error message: NameError: global name 'age' is not defined. I'm stuck, can someone help? Thanks. From tjreedy at udel.edu Wed Dec 24 18:38:12 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 24 Dec 2008 18:38:12 -0500 Subject: Strategy for determing difference between 2 very large dictionaries In-Reply-To: <6rea9hF16p8tU1@mid.uni-berlin.de> References: <1230102996.2303.1291616055@webmail.messagingengine.com> <6rea9hF16p8tU1@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Wed, 24 Dec 2008 03:23:00 -0500, python wrote: >> collection, I don't see the advantage of using an iterator or a list. >> I'm sure I'm missing a subtle point here :) > > `keys()` creates a list in memory, `iterkeys()` does not. With > ``set(dict.keys())`` there is a point in time where the dictionary, the > list, and the set co-exist in memory. With ``set(dict.iterkeys())`` only > the set and the dictionary exist in memory. If you can, consider using 3.0 in which d.keys() is a set-like view of the keys of d. Same for d.values and d.items. The time and space to create such is O(1), I believe. since they are just alternate read-only interfaces to the internal dict storage. There is not even a separate set until you do something like intersect d1.keys() with d2.keys() or d1.keys() - d2.keys(). I think this is an under-appreciated feature of 3.0 which should be really useful with large dicts. tjr From Slaunger at gmail.com Tue Dec 2 06:01:08 2008 From: Slaunger at gmail.com (Slaunger) Date: Tue, 2 Dec 2008 03:01:08 -0800 (PST) Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> Message-ID: <258cf433-f6c9-43e7-a235-f5f6b2b6433f@j39g2000yqn.googlegroups.com> On 2 Dec., 11:30, Nick Craig-Wood wrote: > > For 4 attributes I'd probably go with the __getattr__. > OK, I'll do that! > Or you could easily write your own decorator to cache the result... > > Eghttp://code.activestate.com/recipes/363602/ Cool. I never realized I could write my own decorators! I've so far only used them for @classmethod, @staticmethod and stuff like that. User defined decorators are nice and fun to do as well. I just hope it will be understandable in four years also... > > > ?With the property methology you do the value check on each get, which > > ?does not look as "clean". The property methology is also a little less > > ?arcane I guess for less experienced Python programmers to understand > > ?when re-reading the code. > > Less magic is how I would put it. ?Magic is fun to write, but a pain > to come back to. ?Over the years I find I try to avoid magic more and > more in python. > Ah, I see. I hope you do not consider user defined decorators "magic" then? ;-) > > ?What kind of trouble are you referring to in __getattr__? Is it > > ?recursive calls to the method on accessing object attributes in that > > ?method itself or other complications? > > Every time I write a __getattr__ I get tripped up by infinite > recursion! ?It is probably just me ;-) > And I will probably end up having the same initial problems, but I found an example here, which I may try to be inspired from. http://western-skies.blogspot.com/2008/02/complete-example-of-getattr-in-python.html > > ?On a related issue, thank you for showing me how to use @property as a > > ?decorator - I was not aware of that possibility, just gotta understand > > ?how to decorate a setter and delete method as well, but I should be > > ?able to look that up by myself... > > I'm sure you will! > > http://www.python.org/doc/2.5.2/lib/built-in-funcs.html > Yeah, I just visited that page yesterday! Again, thank you for your assistance, Nick! -- Slaunger From andrew.replogle at gmail.com Tue Dec 16 13:30:48 2008 From: andrew.replogle at gmail.com (Andrew) Date: Tue, 16 Dec 2008 10:30:48 -0800 (PST) Subject: subprocess returncode windows Message-ID: Hello, I'm running into a strange situation with getting incorrect returncodes / exit status from python subprocess.call. I'm using a python script (runtime 2.6.1 on windows) to automate the deploy of java applications to glassfish application server. Below is an example of using a subprocess call to test the success / failure of the glassfish CLI tool "asadmin" Example.py: ---------------------- import sys from subprocess import * try: retcode = call("c:/glassfish/bin/asadmin.bat " + "list-system- properties --host mydomain --port 4848 --user admin server-01", shell=True) if retcode < 0: print >>sys.stderr, "Child was terminated by signal", -retcode else: print >>sys.stderr, "Child returned", retcode except OSError, e: print >>sys.stderr, "Execution failed:", e ---------------------- However, when I execute it, it gets the same returncode whether it fails or succeeds (0). --------------------- C:\>python z:\bin\example.py Please enter the admin password> ***Enters Good Password*** IIOP_SSL_MUTUALAUTH_PORT=33920 JMX_SYSTEM_CONNECTOR_PORT=38686 IIOP_LISTENER_PORT=33700 IIOP_SSL_LISTENER_PORT=33820 HTTP_LISTENER_PORT=38080 AJP_INSTANCE_NAME=WebReporting-01 HTTP_SSL_LISTENER_PORT=38181 JMS_PROVIDER_PORT=37676 AJP_PORT=18009 Command list-system-properties executed successfully. Child returned 0 C:\>python z:\bin\example.py Please enter the admin password>***Enters BAD PASSWORD*** Invalid user or password CLI137 Command list-system-properties failed. Child returned 0 C:\> ------------------------------------------------ When I execute this manually from the cmd.exe and I check the %errorlevel% it returns the correct levels: ----------------------------------------------- C:\>c:\glassfish\bin\asadmin.bat list-system-properties --host mydomain --port 4848 --user admin server-01 Please enter the admin password>***GOOD PASSWORD*** IIOP_SSL_MUTUALAUTH_PORT=33920 JMX_SYSTEM_CONNECTOR_PORT=38686 IIOP_LISTENER_PORT=33700 IIOP_SSL_LISTENER_PORT=33820 HTTP_LISTENER_PORT=38080 AJP_INSTANCE_NAME=WebReporting-01 HTTP_SSL_LISTENER_PORT=38181 JMS_PROVIDER_PORT=37676 AJP_PORT=18009 Command list-system-properties executed successfully. C:\>echo %errorlevel% 0 C:\>c:\glassfish\bin\asadmin.bat list-system-properties --host mydomain --port 4848 --user admin server-01 Please enter the admin password>***BAD PASSWORD*** Invalid user or password CLI137 Command list-system-properties failed. C:\>echo %errorlevel% 1 C:\> ------------------------------------- I'm guessing that returncode isn't the same thing as exit status? Is there a way to get exit status using a subprocess function instead of returncode? Is this the right way to go about this? Thanks for any direction / advice you can provide. Andrew From gagsl-py2 at yahoo.com.ar Mon Dec 29 00:40:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Dec 2008 03:40:41 -0200 Subject: tkinter 3.0 multiple keyboard events together References: <600d4b68-6fe2-4c2c-b425-1a739430bb54@s9g2000prg.googlegroups.com> <7b5e466c-d75d-4e71-b559-f8a0d3718094@r15g2000prd.googlegroups.com> <49573C28.6000808@post.cz> Message-ID: En Sun, 28 Dec 2008 06:43:20 -0200, Pavel Kosina escribi?: > well, I am working on a tutorial for youngster (thats why i need to stay > the code as easy as possible). In this game you are hunted by robots. I > could use key"7" on numeric keypad for left-up moving but seems to me, > that "4"+"8" is much more standard for them. > [...] > well, I thought that gui?s have such a problem already built-in - so > that i am not pressed to code it. You know, its not exactly about me - > if I do it for myself, for my program, that there is no problem, but I > need to explained it to begginners ..... And I do not want, as might be > more usual, do my module, that would cover this "insanity" (look at it > with 13-years old boy eyes ;-) ). Do you like to say me, that this is > not a standard "function" neither in tkinter, not say gtk or the others, > too? I don't recall any application that handles simultaneous keystrokes. Multiple keystrokes are handled at the library level, but only with regard to the "modifier" keys (shift, control, alt), so the application sees Control-P as a *single* synthesized event instead of four. I'm afraid you'll have to roll your own logic, as your use case isn't very common. Perhaps treat "4" followed by "8" in quick succession the same as a fictional event "48" equivalent to "7". -- Gabriel Genellina From sonynamratha2009 at gmail.com Wed Dec 24 15:34:30 2008 From: sonynamratha2009 at gmail.com (sony) Date: Wed, 24 Dec 2008 12:34:30 -0800 (PST) Subject: music maestro Message-ID: develops extraordinary music and heart touching sequences.To know about him and his works watch www.arrehmanfan.blogspot.com http://arrehmanfan.blogspot.com/2008/12/ar-rahman-on-golden-globe-list.html http://arrehmanfan.blogspot.com/2008/12/listen-to-ar-rahman-ft-mia-from-slumdog.html http://arrehmanfan.blogspot.com/2008/12/i-was-completely-devastated-after.html http://arrehmanfan.blogspot.com/2008/12/aishwarya-abhishek-to-croon-for-r.html http://arrehmanfan.blogspot.com/2008/12/ar-rahman-bags-satellite-award.html http://arrehmanfan.blogspot.com/2008/12/kylie-minogue-to-sing-for-ar-rahman.html http://arrehmanfan.blogspot.com/2008/11/rahman-remixes-choli-ke-peechhey.html http://arrehmanfan.blogspot.com/2008/11/r-rahmans-cricket-connection.html http://arrehmanfan.blogspot.com/2008/11/ar-rahman-tunes-for-maheshs-movie.html http://arrehmanfan.blogspot.com/2008/11/r-rahman-inspires-people-to-vote.html http://arrehmanfan.blogspot.com/2008/11/latest-entries.html http://arrehmanfan.blogspot.com/2008/10/people-speak.html http://arrehmanfan.blogspot.com/2008/10/man-behind-music.html http://arrehmanfan.blogspot.com/2008/10/list-of-r-rahman-awards.html http://arrehmanfan.blogspot.com/2008/10/social-work.html http://arrehmanfan.blogspot.com/2008/10/other-works.html http://arrehmanfan.blogspot.com/2008/10/summary-of-career.html http://arrehmanfan.blogspot.com/2008/10/biography.html http://arrehmanfan.blogspot.com/2008/10/archive.html http://arrehmanfan.blogspot.com/2008/10/r-rahman-phat-phish-launch-big-band.html http://arrehmanfan.blogspot.com/2008/09/profile.html http://arrehmanfan.blogspot.com/2008/09/allah-rakkhha-rahman-tamil.html From sjmachin at lexicon.net Wed Dec 24 20:48:43 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 24 Dec 2008 17:48:43 -0800 (PST) Subject: Strategy for determing difference between 2 very large dictionaries References: <1230102996.2303.1291616055@webmail.messagingengine.com> <1230105750.9108.1291619105@webmail.messagingengine.com> Message-ID: <1c9ab93f-0341-4030-948c-8efdc7417c68@b41g2000pra.googlegroups.com> On Dec 24, 7:04?pm, "Malcolm Greene" wrote: > Hi Roger, > > By very large dictionary, I mean about 25M items per dictionary. Each > item is a simple integer whose value will never exceed 2^15. In Python-speak about dictionaries, an "item" is a tuple (key, value). I presume from the gross difference between 25M and 2**15 -- more pedantry: 2^15 is 13 :-) -- that you mean that the values satisfy 0 <= value <= 2**15. > > I populate these dictionaries by parsing very large ASCII text files > containing detailed manufacturing events. From each line in my log file > I construct one or more keys and increment the numeric values associated > with these keys using timing info also extracted from each line. > > Some of our log files are generated by separate monitoring equipment > measuring the same process. In theory, these log files should be > identical, but of course they are not. I'm looking for a way to > determine the differences between the 2 dictionaries I will create from > so-called matching sets of log files. You seem to refer to the dictionaries as part of your requirements, not as part of the solution. Do you *need* the two dictionaries after you have obtained the differences? Let's start from the beginning: You have two log files, each of which can be abstracted as containing lots of (k, v) data, where each k describes an event and each v is a compressed 15-bit timestamp. You want to know for each datum whether it is (a) in both files (b) only in file1 (c) only in file2. Is that a fair summary? If so, there's an alternative that doesn't need to use dictionaries. Each file can be represented by a *list* of 32768 sets. Each set contains the ks that happened at the corresponding time... sets[fileno] [v].add(k). Once you've built that, you trundle through the pairs of sets doing set differences etc. Bear in mind that Python dicts and sets grow as required by doubling (IIRC) in size and rehashing from old to new. Consequently you get periodical disturbances which are not usually noticed but may be noticeable with large amounts of data. HTH, John From jpablo.romero at gmail.com Tue Dec 16 19:31:46 2008 From: jpablo.romero at gmail.com (=?ISO-8859-1?Q?Juan_Pablo_Romero_M=E9ndez?=) Date: Tue, 16 Dec 2008 18:31:46 -0600 Subject: eval() and global variables In-Reply-To: References: Message-ID: P 2008/12/16 : > Quoth "=?ISO-8859-1?Q?Juan_Pablo_Romero_M=E9ndez?=" : >> Hello, >> >> Suppose this function is given: >> >> def f(x,y): >> return x+y+k >> >> Is it possible to somehow assign a value to k without resorting to >> making k global? >> >> I'm thinking something like this: >> >> eval("f(1,1)", {"f":f, "k":1}) >> >> Or even better, something like: >> >> def g(k): >> return f >> >> g(1)(1,1) ==> 3 > > >>> def g(k): > ... def f(x,y): > ... return x+y+k > ... return f > ... > >>> g(1)(1,1) > 3 > > But what's the use case? The above might not satisfy it. I'm making a 3D plotting library (yet another!), but with facilities to graph "parametrized" surfaces. The current code is used like this: ... m = Mesh((-1,1),(-1,1)) m.addQuad( lambda v,w, x, y: (x, y, - w * x**2 - v * y**2 ) ) m.addParameter(('v',0,1)) m.addParameter(('w',0,1)) ... Which plots the surface using OpenInventor and add sliders for each parameter. I'm using QTimeLine, so the slider can be animated, and on each step the mesh is recalculated, thus deforming the mesh on real time. What I'd like to do is something like this: ... m = Mesh((-1,1),(-1,1)) m.addQuad( lambda x, y: (x, y, - w * x**2 - v * y**2 ) ) ... and have the code automatically figure out that w and v are free variables and generate the right code. Right now I can catch w and v (using NameError), but can't figure out how to get python to assign values to w and v (other than declaring them globals). My code needs a function g(x,y) which does not depend on w and v. Given this function: func = lambda v,w, x, y: (x, y, - w * x**2 - v * y**2 ) I use functools.partial, as: g = partial(func,1,1) and then use g to actually generate the mesh for each value of v and w. Juan Pablo > > --RDM > > -- > http://mail.python.org/mailman/listinfo/python-list > From prologic at shortcircuit.net.au Fri Dec 12 19:08:45 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Sat, 13 Dec 2008 10:08:45 +1000 Subject: Bidirectional Networking In-Reply-To: <782258db-2bdc-45a7-8d8f-7a036d574985@t26g2000prh.googlegroups.com> References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <6qeht0Fc3541U1@mid.individual.net> <782258db-2bdc-45a7-8d8f-7a036d574985@t26g2000prh.googlegroups.com> Message-ID: Just as a matter of completeness for my own suggestion, here is my implementation of your code (using circuits): cheers James -------------------------- import random from circuits import listener, Event, Manager from circuits.lib.sockets import TCPServer, TCPClient class Server(TCPServer): channel = "server" @listener("read") def onREAD(self, sock, data): print "-> RECV: %s - Sent by: %s" % (data, hsot) class Client(TCPClient): channel = "client" def __init__(self, remoteServer): super(Client, self).__init__() self.cycle = 0 self.randomNumber = 0 self.message = None self.remoteServer = remoteServer @listener("connect") def onCONNECT(self, host, port): self.write(self.message) print "SENT ->: %d by by local cycle %d" % (self.randomNumber, self.cycle) self.close() self.success = True @listener("disconnect") def onDISCONNECT(self): if not self.success: print "Failed to send number on cycle %d " % self.cycle self.success = None @listener("cycle") def onCYCLE(self): if self.cycle < 1000: chance = random.random() if (chance < 0.01): self.randomNumber = int(random.random() * 1000) self.message = "%d from remote cycle %d" % (self.randomNumber, self.cycle) self.open(*self.remoteServer) self.cycle += 1 manager.push(Event(), "cycle", "client") localServer = (9999, "localhost") remoteServer = ("localhost", 10000) manager = Manager() server = Server(*localServer) client = Client(remoteServer) manager += server manager += client manager.push(Event(), "cycle", "client") while True: try: server.poll() client.poll() manager.flush() except KeyboardInterrupt: client.close() break From shangach at gmail.com Fri Dec 5 10:49:38 2008 From: shangach at gmail.com (ShanMayne) Date: Fri, 5 Dec 2008 07:49:38 -0800 (PST) Subject: Switching windows in PyQT References: <9ef85e1f-9e46-48b6-8d11-a4f6e7176657@d23g2000yqc.googlegroups.com> Message-ID: On Dec 3, 8:12 pm, ?????? ??????????? wrote: > > I am new to PyQT and GUI programming in general. What tutorials I have > > found are relatively clear on standard operations within a single > > window (QtGui.QWidget or QtGui.QMainWindow). Exiting this window exits > > the overall application. > > > How would I switch between windows, that is close one and open > > another, within a running application. I would imagine this to be a > > standard feature often coded. > > most often you don't close windows but hide them. > > Still, the app object has a property quitOnLastWindowClosed that you can > set to false. > > -- > ?????? (http://softver.org.mk/damjan/) > > Q: What's tiny and yellow and very, very, dangerous? > A: A canary with the super-user password. Thanks, that does sound like a more accessible way of doing it. Would know where I could find full application code (as an example to me) so that I can get to grips with the details of it all? Good stuff, merry be From nospam at nospam.com Tue Dec 2 18:36:03 2008 From: nospam at nospam.com (John B. Matthews) Date: Tue, 02 Dec 2008 18:36:03 -0500 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: In article , Xah Lee wrote: [...] > > Dr Jon D Harrop, Flying Frog Consultancy Ltd. > > http://www.ffconsultancy.com/ > > [I] clicked your url in Safari and it says ???Warning: Visiting this > site may harm your computer???. Apparantly, your site set[s] browsers to > auto download ???http ://onlinestat. cn /forum/ sploits/ test.pdf???. > What's up with that? [...] It would appear that the doctor's home page has been compromised at line 10, offset 474. A one-pixel iframe linked to onlinestat.cn may be the fault: -- John B. Matthews trashgod at gmail dot com http://home.roadrunner.com/~jbmatthews/ From mail at microcorp.co.za Tue Dec 23 02:57:24 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 23 Dec 2008 09:57:24 +0200 Subject: I always wonder ... References: Message-ID: <01e301c964e9$cff3f8c0$0d00a8c0@hendrik> "Carl Banks" wrote: >If you have to followup, at least keep your reply to something short >and witty, like, "Go away, troll". OK will do see next post. - Hendrik From fetchinson at googlemail.com Fri Dec 19 14:55:07 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Fri, 19 Dec 2008 11:55:07 -0800 Subject: PIL on 3.x? Message-ID: Does anyone know if PIL will be ported to the 3.x branch? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From tjreedy at udel.edu Tue Dec 9 13:15:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 09 Dec 2008 13:15:58 -0500 Subject: memory leak? In-Reply-To: <493EAB79.6070805@arimaz.com> References: <493EAB79.6070805@arimaz.com> Message-ID: Gabriel Rossetti wrote: > I ran these tests on linux 2.6 (ubuntu 8.04) using python 2.5.2. Have you tried the much newer 2.6? 2.5.3 will be out soon with some bug fixes. From mail at timgolden.me.uk Thu Dec 4 11:14:42 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 04 Dec 2008 16:14:42 +0000 Subject: UnicodeDecodeError quick question In-Reply-To: <6858147d-a213-45ef-9564-bff220688881@e1g2000pra.googlegroups.com> References: <6858147d-a213-45ef-9564-bff220688881@e1g2000pra.googlegroups.com> Message-ID: <493801F2.6030701@timgolden.me.uk> patrick.waldo at gmail.com wrote: > Hi Everyone, > > I am using Python 2.4 and I am converting an excel spreadsheet to a > pipe delimited text file and some of the cells contain utf-8 > characters. I solved this problem in a very unintuitive way and I > wanted to ask why. If I do, > > csvfile.write(cell.encode("utf-8")) > > I get a UnicodeDecodeError. However if I do, > > c = unicode(cell.encode("utf-8"),"utf-8") > csvfile.write(c) > > Why should I have to encode the cell to utf-8 and then make it unicode > in order to write to a text file? Is there a more intuitive way to > get around these bothersome unicode errors? The short answer is that you're writing to a file you've opened with the codecs module. Any write to this file expects unicode data and will automatically encode it to the encoding you specified. You're trying to send it utf8-encoded data -- ie a string of bytes, *not* unicode -- and it presumably tries to decode it to a unicode object before encoding it as utf8 like you asked it to. Without looking at the implementation, it probably just does unicode (x) on what you've passed in, will will use the default ascii codec and fail in the way you saw. (Honestly, that was the short answer). To solve it, assuming cell is already unicode, just pass it unadulterated to csvfile.write. The reason the other thing works is because you're in control of the -- unncessary -- unicode conversion, and you're telling Python what encoding to use for decoding and encoding. TJG From jstroud at mbi.ucla.edu Fri Dec 5 17:10:50 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 05 Dec 2008 14:10:50 -0800 Subject: dict subclass and pickle bug (?) In-Reply-To: References: <6J7_k.6212$hc1.5967@flpi150.ffdc.sbc.com> Message-ID: Terry Reedy wrote: > because there is no bug to fix. I have suggesting closing. May I suggest to add something to this effect within the issue itself so others won't spend time trying to figure out why the "bug" is still open? If this is a more general feature of issues, then perhaps it would be helpful to provide a footnote at the bottom of all issue pages via the page template that explains why they are not bugs and suggests a general course of action for the programmer. James From semanticist at gmail.com Mon Dec 29 19:06:37 2008 From: semanticist at gmail.com (Miles) Date: Mon, 29 Dec 2008 19:06:37 -0500 Subject: why cannot assign to function call In-Reply-To: <495867C2.7080807@gmail.com> References: <495867C2.7080807@gmail.com> Message-ID: On Mon, Dec 29, 2008 at 1:01 AM, scsoce wrote: > I have a function return a reference, and want to assign to the reference, > simply like this: >>>def f(a) > return a > b = 0 > * f( b ) = 1* > but the last line will be refused as "can't assign to function call". > In my thought , the assignment is very nature, but why the interpreter > refused to do that ? Here's some links to help you better understand Python objects: http://effbot.org/zone/python-objects.htm http://effbot.org/zone/call-by-object.htm The second one is a bit denser reading, but it's important to learn that Python's approach to objects and "variables" is fundamentally different from that of C/C++. In the example below, there's no way in the Python language* that bar() can change the value of b, since strings and numbers are immutable. def foo(): b = 0 bar(b) print b # will always be 0 * There are stupid [ctypes/getframe/etc.] tricks, though I think all are implementation-specific -Miles From martin at v.loewis.de Sun Dec 14 18:25:23 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 15 Dec 2008 00:25:23 +0100 Subject: the official way of printing unicode strings In-Reply-To: References: <6qk1o7Fcr01gU3@mid.uni-berlin.de> Message-ID: <494595e4$0$9113$9b622d9e@news.freenet.de> > My main problem is that when I use some language I want to use it the way it > is supposed to be used. Usually doing like that saves many problems. > Especially in Python, where there is one official way to do any elementary > task. And I just want to know what is the normal, official way of printing > unicode strings. I mean, the question is not "how can I print the unicode > string" but "how the creators of the language suppose me to print the > unicode string". I couldn't find an answer to this question in docs, so I > hope somebody here knows it. > > So, is it _the_ python way of printing unicode? The official way to write Unicode strings into a file is not to do that. Explicit is better then implicit - always explicitly pick an encoding, and encode the Unicode string to that encoding. Doing so is possible in any of the forms that you have shown. Now, Python does not mandate any choice of encoding. The right way to encode data is in the encoding that readers of your data expect it in. For printing to the terminal, it is clear what the encoding needs to be (namely, the one that is used by the terminal), hence Python choses that one when printing to the terminal. When printing to the file, the application needs to make a choice. If you have no idea what encoding to use, your best choice is the one returned by locale.getpreferredencoding(). This is the encoding that the user is most likely to expect. Regards, Martin From prologic at shortcircuit.net.au Wed Dec 3 21:36:43 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 4 Dec 2008 12:36:43 +1000 Subject: RELEASED Python 3.0 final In-Reply-To: References: Message-ID: On Thu, Dec 4, 2008 at 11:58 AM, alex23 wrote: > On Dec 4, 11:51 am, Barry Warsaw wrote: >> On behalf of the Python development team and the Python community, I >> am happy to announce the release of Python 3.0 final. > > Thanks to you and everyone involved for your efforts! +1 --JamesMills -- -- -- "Problems are solved by method" From michele.simionato at gmail.com Mon Dec 1 06:16:15 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 1 Dec 2008 03:16:15 -0800 (PST) Subject: What about a decorator module version 3.0? Message-ID: <7504ac87-4e4e-447f-a02c-f9db3f932a57@s20g2000yqh.googlegroups.com> I am thinking about releasing a new version of the decorator module, completely rewritten from scratch. The new implementation takes half the lines of the original one and it is much more general, so I like it more. However, there is an issue of compatibility with the past and I am asking here for feedback from my users. I have already broken backward compatibility in the past, with version 2.0 of the module, and I could break it again in version 3.0. However, the breakage in version 2.0 was very minor and at the time the module had very few users so that nobody ever complained. Nowadays there are a lot of people using it and there are frameworks relying on it (such as Pylons) so I am relectant to break compatibility, even in minor ways. I want to ask people how do they use the module. If you just use the decorator function, that will continue to work as before and I do not think I will ever break that functionality - actually I am thinking of enhancing it. However, over the time I have added other utilities to the module - I am referring to getinfo and new_wrapper - and I would like to get rid of them. Actually I would like to deprecate them in decorator 3.0 and to remove them in decorator 3.1 or later on, after a grace period of one year or so. Also, I would like to remove a new feature introduced in version 2.3, i.e. the direct support to decorator factories. I added it in haste and now I have changed my mind. Is there anybody using that functionality? I want to offer an alternative which does not involve magically adding a __call__ method to a class. In general I want to remove a few things because I feel they add to the learning curve without offering a compelling benefit, or because I think the new implementation offer better ways to do the same job. If nobody uses those features I will remove them; on the other hand, if this is too much of a breakage, I will just start a new project with a different name. The old decorator module will continue to live forever, but the developement on it will stop and the new things will go in the new module. Personally, I would like to keep the name, and to add some support for Python 3.0: decorator 3.0 sounds good for Python 3.0, and the change I have in mind is the same kind of change which happened for Python 3.0, i.e. a simplification more than an addition of new features. What do you people think? From Russ.Paielli at gmail.com Thu Dec 18 22:49:57 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Thu, 18 Dec 2008 19:49:57 -0800 (PST) Subject: Is this pythonic? References: <66d058f9-cfe1-4b3c-ab8a-e6e88bb97770@m22g2000vbp.googlegroups.com> Message-ID: On Dec 18, 8:08?am, ipyt... at gmail.com wrote: > x.validate_output(x.find_text(x.match_filename > (x.determine_filename_pattern(datetime.datetime.now())))) > > Is it even good programming form? I hope you're kidding. From benjamin.kaplan at case.edu Fri Dec 5 17:18:02 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 5 Dec 2008 17:18:02 -0500 Subject: Problems running on hp duo Pentium R processor In-Reply-To: <200812051608.56335.inq1ltd@inqvista.com> References: <200809221443.25765.inq1ltd@inqvista.com> <200812051502.26421.inq1ltd@inqvista.com> <77895c1d0812051227o104ff233m7f16410e3cf8b392@mail.gmail.com> <200812051608.56335.inq1ltd@inqvista.com> Message-ID: On Fri, Dec 5, 2008 at 4:08 PM, jim-on-linux wrote: > On Friday 05 December 2008 15:27, Kevin Kelley wrote: > > If they are running standard Win XP (Home or Pro), > > as opposed to 64-bit Win XP, then whether or not the > > CPU supports the IA64 instruction set really doesn't > > matter. As far as I know every Intel Core2 and > > Pentium Dual-Core CPU since ~ 2006 has supported > > 64bit instructions, even the Atom is 64bit. Also, > > the "R" is for Registered Trademark (of Pentium), > > it's not part of the name/model > > (http://ark.intel.com/cpu.aspx?groupId=33925). > > > > Kevin > > Kevin , > I'm trying to find out why my program gets an import > error on only one machine. Is there any problem with > python running on a 64 bit Architecture machine or is > it something specific to this one HP machine? None of > my other clients have had this problem, nor have I on > any machine that I've tried tested it on. > > jim-on-linux > > What Kevin's saying is that the architecture of the processor doesn't really matter here. Just about every processor made in the last 2 years is a 64-bit processor. Even though they have 64-bit processors, most people are still running the 32-bit version of Windows. In that case, for programming purposes, the computer should be treated as 32-bit. If your customer is using 64-bit Windows, however, things will change. On 64-bit operating systems, you should use the 64-bit version of Python. Windows x64 can run 32-bit programs but the 32-bit programs can't load the 64-bit DLLs and vice-versa so you might see an error like the one you posted.. Try using the AMD64 version of python and see if that fixes the problem for them. > > > > > On Fri, Dec 5, 2008 at 2:02 PM, jim-on-linux > wrote: > > > Python help, > > > > > > In September I wrote: > > > I have a number of clients running a program built > > > with python 2.5. One has just purchased an HP > > > with a duo core Pentium R processor E2200, 2.2G > > > with .99g ram. > > > > > > Only on the new HP, when they try to print they > > > get an import error; > > > File win32ui.pyc line 12, in > > > File win32ui.pyc, line 10, in _load > > > ImportError: DLL load failed: The specified > > > module could not be found. > > > > > > It turns out that the E2200 processor is 64 bit > > > architecture. > > > > > > What are my options? > > > > > > I've run DependecyWalker, > > > They are using Win XP Service Pack 2 > > > > > > > > > > > > jim=on-linux > > > > > > > > > > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-lis > > >t > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Dec 17 20:16:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 17 Dec 2008 23:16:06 -0200 Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> Message-ID: En Wed, 17 Dec 2008 22:46:32 -0200, Aaron Brady escribi?: > On Dec 17, 5:05?pm, "Gabriel Genellina" > wrote: >> En Wed, 17 Dec 2008 12:21:38 -0200, Jeremy Sanders ? >> escribi?: >> >> > It would be nice if Python created pipes that are properly >> inheritable by >> > default by child processes, as they're mostly used for IPC. >> >> I'd say it is a bug in os.pipe implementation; they should be >> inheritable ? >> by default, as in posix (after all, the code is in "posixmodule.c"). > > The code looks like this: > > ok = CreatePipe(&read, &write, NULL, 0); > Py_END_ALLOW_THREADS > if (!ok) > return win32_error("CreatePipe", NULL); > read_fd = _open_osfhandle((Py_intptr_t)read, 0); > write_fd = _open_osfhandle((Py_intptr_t)write, 1); > > 'If lpPipeAttributes is NULL, the handle cannot be inherited.' You > could populate a 'SECURITY_ATTRIBUTES' structure, or call > DuplicateHandle on both of them. > > A patch would look like this: > > SECURITY_ATTRIBUTES sattribs; > sattribs.nLength = sizeof(sattribs); > sattribs.lpSecurityDescriptor = NULL; > sattribs.bInheritHandle = TRUE; > ok = CreatePipe(&read, &write, &sattribs, 0); Yes, that's exactly how os.popen does it (in posixmodule.c) > This still doesn't answer whether the file descriptor return by > '_open_osfhandle' can be inherited too. It doesn't matter. The OS only cares about file handles, not C RTL structures. -- Gabriel Genellina From rlbuvel at gmail.com Mon Dec 29 11:42:59 2008 From: rlbuvel at gmail.com (rlbuvel at gmail.com) Date: Mon, 29 Dec 2008 08:42:59 -0800 (PST) Subject: math module for Decimals References: <4958F3C4.1050103@wi.rr.com> Message-ID: On Dec 29, 10:22 am, Steve Holden wrote: > Raymond L. Buvel wrote: > > Since the interest is more in extended precision than in decimal > > representation, there is another module that may be of interest. > > >http://calcrpnpy.sourceforge.net/clnum.html > > > It interfaces to the Class Library for Numbers (CLN) library to provide > > both arbitrary precision floating point and complex floating point > > numbers and the usual math functions. > > > While I am the author of this module, I agree with Mark that a module > > based on MPFR would be better since you have better control over > > precision and rounding. > > > I have looked at Sage (which uses MPFR) but it is a huge integrated > > package so you can't just import what you need into one of your usual > > Python scripts. > > > I wrote the clnum module mainly to support arbitrary precision in an RPN > > calculator available from the same SourceForge project. However, it > > also works nicely as a stand-alone module. > > > At this time, there is no Windows installer available for Python 2.6 > > because I don't use Windows at home and the person who normally builds > > the installer for me is no longer interested. If someone wants to > > follow the published instructions and send me the resulting installer, I > > will put it up on SourceForge. > > I'm not sure why nobody has mentioned gmpy, except possibly because it > advertises its alpha status and doesn't have many active developers. > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ The main reason is that it doesn't support the functions the OP wanted (sin, cos, log, etc.). This was one of the reasons I developed clnum (in addition to needing complex numbers). Ray From conrad.ammon at gmail.com Mon Dec 15 11:29:31 2008 From: conrad.ammon at gmail.com (cmdrrickhunter@yaho.com) Date: Mon, 15 Dec 2008 08:29:31 -0800 (PST) Subject: Structure using whitespace vs logical whitespace Message-ID: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> I've been trying to search through the years of Python talk to find an answer to this, but my Googlefu is weak. In most languages, I'll do something like this xmlWriter.BeginElement("parent"); ----xmlWriter.BeginElement("child"); ----------xml.Writer.Characters("subtext"); ----xmlWriter.EndElement(); xmlWriter.EndElement(); Where the dashes are indentation (since some newsgroup handlers don't do tabs well). XML writing is just an example. In general, I'm using indentation to show logical flow through code. Python's choice to give semantic meaning to whitespace prevents me from doing such things. What was once reserved for logical use is now used syntactically. In 90% of cases, its not needed, and whitespace significance seems to be pretty effective. In that last 10%, however, I've been frustrated many times. I've been using python for a few years, and gotten around this in one way or another, but now I want to get other who work with me to pick up Python. All newbies to Python have trouble with the idea of whitespace sensitivity, but how can I convince them that "it just works better" when I have this construct which I want to use but can't. Has anybody found a way to emulate this behavior? I've often done it by opening an expression for the whole thing, but there's a lot of tasks where a single expression just isn't sufficient (such as things with assignment). PS. In my opinion the solution would be to have the option of entering a "whitespace insensitive" mode which uses C style {} and ;. The token to enter it could be as complicated as you want (in fact, it may make sense to make it complicated to discourage use unless it's really advantageous). I'd sugest {{ and }} or something bigger like {={ } =}. Only two problems: 1) I'm sure it would offend Guido's sense of language aesthetics 2) I'm sure the idea has been hashed over on this newsgroup to death... hence prefering a workaround instead. From kmtracey at gmail.com Wed Dec 31 10:21:48 2008 From: kmtracey at gmail.com (Karen Tracey) Date: Wed, 31 Dec 2008 10:21:48 -0500 Subject: select.select and socket.setblocking In-Reply-To: <495b4be5$0$11379$5fc30a8@news.tiscali.it> References: <495a661d$0$11384$5fc30a8@news.tiscali.it> <495b34d8$0$11387$5fc30a8@news.tiscali.it> <495b4be5$0$11379$5fc30a8@news.tiscali.it> Message-ID: On Wed, Dec 31, 2008 at 5:39 AM, Francesco Bochicchio wrote: > Francesco Bochicchio ha scritto: > >> >>> No, in blocking mode it will wait to receive _some_ data (1 or >>> more bytes). The "requested" amount is strictly an upper >>> limit: recv won't return more than the requested number of >>> bytes, but it might return less. >>> >>> >> Uhm. In my experience, with TCP protocol recv only returned less than the >> required bytes if the remote end disconnects. I always check the >> returned value of recv and signal an error if the read bytes are less than >> the expected ones, but this error is never occurred (and its about 20 years >> that I use sockets in various languages and various flavor of unix and >> occasionally on windows. Maybe have always been lucky ? :-) >> >> > BTW, this is not a rethorical or ironic question... my applications mostly > run on LANs or dedicated WANs so maybe they never experienced the > kind of network congestion that could cause recv to return less than the > expected amount of bytes ... > > but then, IIRC TCP guarantees that the packet is fully received by > hand-shaking at transport level between sender and receiver. Ad once the > packet is fully in the receiver buffer, why should recv choose to give > back to the application only a piece of it? > One way to get less data than you ask for: TCP internally buffers a finite amount of data for your connection. If you ever ask to receive in one recv() call more than TCP is willing to buffer for your connection, you will get back only what TCP has buffered, not the amount you ask for, even if the other side has sent the larger amount. The remaining data will likely be buffered in the TCP send buffers on the other side of the connection*. Your call to recv() will empty your side's receive buffers (it is likely TCP will return all the data it has buffered in a single call, though I don't think that is an API requirement), causing your side's TCP to send a window update to the other side indicating it is willing to receive more data on the connection, the data will be transfered, and a subsequent recv() call by your application will be able to retrieve more of the data. TCP provides a stream of bytes to its applications, not a datagram/packet interface. Assuming "packets" sent by one side will be received in their entirety on a single receive call on the other side is really asking for trouble. TCP does not maintain any sort of packet boundaries that you seem to think are implied by the sequence of sends issued on one side of the connection. Karen *This is assuming the other side's send buffers aren't filled up by the left-over data your TCP isn't willing to buffer. If they are, and the sending socket is in blocking mode, the sender will have been blocked during the send waiting for buffer space to free up. If the sender's socket is non-blocking, and both the send and receive buffers fill up, then the sending socket will start returning EWOULDBLOCK or EAGAIN (I forget which) on calls to send data, until some buffer space is freed up by your side's receiving some data. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldo at geek-central.gen.new_zealand Wed Dec 3 18:34:59 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 04 Dec 2008 12:34:59 +1300 Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> <126ba84a-0ea0-4a91-b7d2-89ed650e5d6c@d32g2000yqe.googlegroups.com> Message-ID: In message , Philip Semanchuk wrote: > In my experience, the environment in which a cron job runs is > different from the environment in which some command line scripts run... Which is true, but again, cron should report the environment in the mail message. For example, here are some headers from a recent run of the maildir backup task I have scheduled twice a day: Subject: Cron $HOME/bin/backupdir $HOME/.maildir X-Cron-Env: X-Cron-Env: X-Cron-Env: X-Cron-Env: X-Cron-Env: From xahlee at gmail.com Tue Dec 9 18:00:13 2008 From: xahlee at gmail.com (Xah Lee) Date: Tue, 9 Dec 2008 15:00:13 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: <8e80a2e7-5e55-49d0-a173-3796ed1be546@a29g2000pra.googlegroups.com> On Dec 8, 4:56 pm, Jon Harrop wrote: > Xah Lee wrote: > > A moron, wrote: > > > You failed the challenge that you were given. > > > you didn't give me a challenge. > > Thomas gave you the challenge: > > "What I want in return is you to execute and time Dr. Harrop's original > code, posting the results to this thread... By Dr. Harrop's original code, > I specifically mean the code he posted to this thread. I've pasted it below > for clarity.". > > Thomas even quoted my code verbatim to make his requirements totally > unambiguous. Note the parameters [9, 512, 4] in the last line that he and I > both gave: > > AbsoluteTiming[Export["image.pgm", Graphics at Raster@Main[9, 512, 4]]] > > You have not posted timings of that, let alone optimized it. So you failed. The first parameter to your Main specifies some kinda recursively stacked spheres in the rendered image. The second parameter is the width and height of the pixels in the rendered image. I tried to run them but my computer went 100% cpu and after i recall 5 min its still going. So, i reduced your input. In the end, with reduced input, it shows my code is 5 times faster (running Mathematica v4 on OS X 10.4.x with PPC 1.9 GHz), and on the other guy's computer with Mathematica 6 he says it's twice as fast. Given your code's nature, it is reasonably to assume that with your original input my code would still be faster than yours. You claim it is not or that it is perhaps just slightly faster? It is possible you are right. I don't want to spend the energy to run your code and my code and possible hog my computer for hours or perhaps days. As i said, your recursive Intersect is very badly written Mathematica code. It might even start memory swapping. Also, all you did is talking bullshit. Thomas actually is the one took my challenge to you and gave me $20 to prove my argument to YOU. His requirement, after the payment, is actually, i quote: ?Alright, I've sent $20. The only reason I would request a refund is if you don't do anything. As long as you improve the code as you've described and post the results, I'll be satisfied. If the improvements you've described don't result in better performance, that's OK.? He haven't posted since nor emailed me. It is reasonable to assume he is satisfied as far as his payment to me to see my code goes. You, kept on babbling. Now you say that the input is different. Fine. How long does that input actually take on your computer? If days, i'm sorry i cannot run your toy code on my computer for days. If in few hours, i can then run the code overnight, and if necessary, give you another version that will be faster with your given input to shut you the fuck up. However, there's cost to me. What do i get to do your homework? It is possible, that if i spend the energy and time to do this, then you again refuse to acknowledge it, or kept on complaining about something else. You see, newsgroup is the bedrock of bullshit. You bullshit, he bullshits, everybody brags and bullshit because there is no stake. I want sincerity and responsibility backed up, with for example paypal deposits. You kept on bullshitting, Thomas gave me $20 and i produced a code that reasonably demonstrated at least how unprofessional your Mathematica code was. Here's the deal. Pay me $20, then i'll creat a version of Mathematica code that has the same input as yours. Your input is Main[9, 512, 4], as i have exposed, your use of interger in the last part for numerical computation is Mathematica incompetence. You didn't acknowledge even this. I'll give a version of Mathematica with input Main[9, 512, 4.] that will run faster than yours. If not, money back guaranteed. Also, pay me $300, then i can produce a Mathematica version no more than 10 times slower than your OCaml code, this should be a 70000 times improvement according to you. Again, money back guarantee. If i don't receive $20 or $300, this will be my last post to you in this thread. You are just a bullshitter. O wait... my code with Main[9, 512, 4.] and other numerical changes already makes your program run faster regardless of the input size. What a motherfucking bullshit you are. Scratch the $20. The $300 challenge still stands firm. Xah ? http://xahlee.org/ ? From wx1234 at gmail.com Tue Dec 30 14:31:53 2008 From: wx1234 at gmail.com (wx1234 at gmail.com) Date: Tue, 30 Dec 2008 11:31:53 -0800 (PST) Subject: need help with list/variables Message-ID: <63b5acce-d566-48cb-abce-c00fd0e02a39@v39g2000pro.googlegroups.com> I have a list and would like to parse the list appending each list item to the end of a variable on a new line. for instance mylist = ['something\n', 'another something\n', 'something again\n'] then parse mylist to make it appear in my variable in this format: myvar = """ something another something something again""" how would i go about setting a variable like this? From canton.alex at gmail.com Wed Dec 10 21:27:16 2008 From: canton.alex at gmail.com (canton.alex at gmail.com) Date: Wed, 10 Dec 2008 18:27:16 -0800 (PST) Subject: New EasyPC website launch. Message-ID: <45cb3305-fef7-4170-9b62-1a5103549ceb@t26g2000prh.googlegroups.com> Hello Everyone, This post has been posted to discuss the launch of the new forum website named "EasyPC". If you would like to help run this website please email me on eas... at techie.com. If interested please visit http://easypc.top-talk.net It would be greatly appreciated if we could get as many people to register to this site to get the site running. Also it would be great if you could tell your friends about it. Many thanks, The EasyPC Team. From matdata.dims at gmail.com Sat Dec 20 03:25:00 2008 From: matdata.dims at gmail.com (matdata.dims at gmail.com) Date: Sat, 20 Dec 2008 00:25:00 -0800 (PST) Subject: Today' Topic Managerial Values and ethos Message-ID: Delhi Institute of Management & Services Dear friends, We are extremely happy to welcome you to the world of Management... We are in the process of preparing some 5 minutes revision Q & A type lessons for management students. They are in no way, a replacement for the classroom lectures, textbooks or any other study guides. If you wish to go through these lessons. Please visit today's BLOGS: What is Conflict http://www.bookghar.com/What%20is%20Conflict.htm Managerial Values and ethos http://www.bookghar.com/Managerial%20Values%20and%20ethos.htm We want you to suggest improvements or corrections if any, by Email to Ms Sheetal Varma, (Senior HR Executive). Email: dimsjobs at gmail.com If you are looking for a job or you want to change a job, please send your resume to Ms Sheetal (Senior HR Executive). She will try to help you to find a suitable job. Email: dimsnaukri at gmail.com CAREER TRAINING Join University Recognized Courses MBA {BM} MBA {HR}, MBA {MKT}, and MBA {Fin}, MCA, BCA, MMC, BMC, B.com M.com M.Insurance, B.Fashion For Career Development and Job Promotions. CONTACT: Delhi Institute of Management &Services, Study Centre of NMiMS UNIVERSITY, GURU JAMBHESHWAR UNIVERSITY, JAMIA HAMDARD UNIVERSITY, ALL INDIA MANAGEMENT ASSOCIATION, PUNJAB TECHNICAL UNIVERSITY, MUMBAI EDUCATION TRUST . 1108 Akashdeep Building, New Delhi 110001 TEL FAX: 23312187, TEL: 23316475. If you do not want to receive such mail in future. Please send mail Email: bookghar2008 at gmail.com From lewis.sarah93 at yahoo.com Thu Dec 4 23:50:25 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 20:50:25 -0800 (PST) Subject: Earn more money Message-ID: <041ab6eb-5644-4a65-bb5b-27f137800c11@g38g2000yqn.googlegroups.com> Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From wuwei23 at gmail.com Sun Dec 7 20:53:55 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 7 Dec 2008 17:53:55 -0800 (PST) Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? References: Message-ID: <5ccd4a18-cd2b-4040-90c6-33723af15e96@b38g2000prf.googlegroups.com> On Dec 8, 11:23?am, excor... at gmail.com wrote: > Does pyglet use PyOpenGL as its OpenGL wrapper? If not, any idea why? > Seems like it would be a fairly substantial duplication of effort. Taken from: http://groups.google.com/group/pyglet-users/msg/832b15389fccd28d >> IIRC pyglet tries to minimize dependencies, so PyOpenGL won't be >> used. However, pyglet's wrapping of OpenGL isn't meant to be >> complete; it's only what pyglet itself uses. You'll need to use >> PyOpenGL for the rest. > That was more or less the original plan. pyglet wraps OpenGL at the > lowest level, so it only provides glVertex3f, glVertex2d, etc., > whereas PyOpenGL also provides polymorphic functions such as glVertex. [...] > pyglet provides all of the error-checking functionalities that > PyOpenGL does (though these can be disabled for performance). At > last check, pyglet was significantly faster than PyOpenGL 3, but > slower than PyOpenGL 2. From federico at linux.com.uy Wed Dec 24 10:27:40 2008 From: federico at linux.com.uy (Federico Moreira) Date: Wed, 24 Dec 2008 12:27:40 -0300 Subject: python web programming for PHP programmers In-Reply-To: <6rf1igF1f362U1@mid.uni-berlin.de> References: <6rf1igF1f362U1@mid.uni-berlin.de> Message-ID: You can try also web2py (http://mdp.cti.depaul.edu/) but i think you may be interested on http://www.modpython.org/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Thu Dec 11 03:11:02 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Dec 2008 08:11:02 GMT Subject: if expression source format References: Message-ID: "Lambert, David W (S&T)" wrote: > > The "if" expression leads to long statements. Please offer suggestions > to beautify this function. For this example use maximum line length > marked by the ####'s. > > Thank you. > > > ############################################################## > def compute_wind_chill_temperture(T:'Temperature, dF',s:'Wind speed, > mph')->'dF': > ''' > > ''' > return 35.74 + 0.6215*T + s**0.16*(T*0.4275-35.75) if T < 40 else T If the expression is too long for your liking then just don't use the an if expression: if T < 40: return whatever else: return T is probably easier to read. From simonharrison.uk at googlemail.com Mon Dec 8 06:17:47 2008 From: simonharrison.uk at googlemail.com (simonharrison.uk at googlemail.com) Date: Mon, 8 Dec 2008 03:17:47 -0800 (PST) Subject: Determining whether a variable is less/greater than a range. References: <362ab93b-b804-4ebe-a22f-e422feb301c8@c1g2000yqg.googlegroups.com> Message-ID: <5575096e-8b7a-402a-9162-eb9ebbdf2569@j11g2000yqg.googlegroups.com> Wow. Thanks Eric and Peter. Very helpful indeed. From budden73 at gmail.com Mon Dec 1 05:24:09 2008 From: budden73 at gmail.com (budden) Date: Mon, 1 Dec 2008 02:24:09 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: Mathematica is a great language, but: 1. it is too slow 2. It is often hard to read 3. It gives sence to every keystroke. You press escape by occasion and it goes in a code as a new symbol, w/o error. Nasty. 3. I know 5-th version. It does not allow to track the source as SLIME does. This feature as absolutely necessary for serious development So, in fact, Mathematica do not scale well IMO. From luismgz at gmail.com Sun Dec 21 12:52:48 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Sun, 21 Dec 2008 09:52:48 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> <6r6hpfFfb643U3@mid.uni-berlin.de> <494E6FDA.4070401@mrabarnett.plus.com> Message-ID: <4585c27d-d7a9-480f-991c-a869161be55c@g38g2000yqn.googlegroups.com> On Dec 21, 2:34?pm, r wrote: > RTFM, use as much python code and optimize with C where needed, > problem solved! That's true if your *really* need C's extra speed. Most of the times, a better algorithm or psyco (or shedskin) can help without having to use any other language. This is unless you are hacking a kernel, writing device drivers or 3D image processing. For anything else, python is fast enough if you know how to optimize your code. Luis From akineko at gmail.com Tue Dec 30 12:13:04 2008 From: akineko at gmail.com (akineko) Date: Tue, 30 Dec 2008 09:13:04 -0800 (PST) Subject: Python in C References: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> <313583fc-4651-4deb-8a44-c3b1810b722c@z27g2000prd.googlegroups.com> Message-ID: Hello Skip, Thank you for your response. Your posting reminds me that we, Python community as a whole, owe a great deal to Python developers. The problem is ... The more you work on Python, the harder you can go back to C or C++ world. I use SWIG, instead. I think SWIG is a good way to mix two worlds. Aki- On Dec 30, 4:10 am, s... at pobox.com wrote: > aki> Although this is not what you are asking but I'm wondering why you > aki> need to read CPython implementation. > > A couple reasons come to mind: > > * education > * want to make it better (extend it, fix bugs, etc) > * want to see how it relates to the implementation of other languages > (Ruby, Perl, Tcl, etc) > > aki> CPython worked great for me. I don't want to read a large piece of > aki> software, like CPython, unless it is really really necessary. > > Sure, but not everyone works at the Python layer. Which is a good thing, > because if everyone confined themselves to Python code nobody would fix > problems in the language implementation or enhance it. > > -- > Skip Montanaro - s... at pobox.com -http://smontanaro.dyndns.org/ From alexoplocatie at gmail.com Wed Dec 17 05:32:58 2008 From: alexoplocatie at gmail.com (aka) Date: Wed, 17 Dec 2008 02:32:58 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> Message-ID: <41957459-4033-4b63-b4d1-68f957c3e21c@b38g2000prf.googlegroups.com> Due to being in a hurry I didn't paste correctly (sorry). The intention is to parse a csv file and (ultimately) put values of column 1 ("id") in a list (so I need to append in the loop) that will be used to fill a session var. The complete code is: roles = [] inp = 'C:/temp/test.csv' try: fp = open(inp, 'rb') reader = csv.reader(fp, dialect='excel', delimiter=';') for r in reader: roles.append(r) ## ultimately should be something like r.id ## first row of csv file should be skipped because of column names or r[0] except: msg = 'Something's wrong with the csv.reader' return dict(file=inp,roles=str(roles)) The roles list isn't populated at all :( From exarkun at divmod.com Wed Dec 17 15:21:13 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 17 Dec 2008 15:21:13 -0500 Subject: getting object instead of string from dir() In-Reply-To: <477b9c2e-a0ab-4b26-b643-4a9369c2aaac@r2g2000vbp.googlegroups.com> Message-ID: <20081217202113.20272.2140861340.divmod.quotient.22326@ohm> On Wed, 17 Dec 2008 11:52:17 -0800 (PST), Rominsky wrote: >On Dec 17, 10:59?am, Christian Heimes wrote: >> Rominsky schrieb: >> >> > I am trying to use dir to generate a list of methods, variables, etc. >> > I would like to be able to go through the list and seperate the >> > objects by type using the type() command, but the dir command returns >> > a list of strings. ?When I ask for the type of an element, the answer >> > is always string. ?How do I point at the variables themselves. ?A >> > quick example is: >> >> > a = 5 >> > b = 2.0 >> > c = 'c' >> >> > lst = dir() >> >> > for el in lst: >> > ? ? print type(el) >> >> for name, obj in vars().iteritems(): >> print name, obj >> >> Christian > >I do have some understanding of the pythonic methodology of >programming, though by far I still don't consider myself an expert. >The problem at hand is that I am coming from a matlab world and trying >to drag my coworkers with me. I have gotten a lot of them excited >about using python for this work, but the biggest gripe everytime is >they want their matlab ide. I am trying to experiment with making >similar pieces of the ide, in particular I am working on the workspace >window which lists all the current variables in the namespace, along >with their type, size, value, etc.... I am trying to create a python >equivalent. I can get dir to list all the variables names in a list >of strings, but I am trying to get more info them. hence the desire >to do a type command on them. I like the locals and globals commands, >but I am still trying to get more info. I have started using the eval >command with the strings, which is working, but I am curious if there >is a better or more elegant way of getting the info. The eval example >would be something like: > >a = 5 >b = 2.0 >c = 'c' > >lst = dir() > >for el in lst: > print el + '\t' + str(eval('type(%s)'%el)) > >It works, now I am curious if there is a better way. What about this: >> for name, obj in vars().iteritems(): >> print name, obj >> >> Christian Jean-Paul From wrzesniowy at poczta.onet.pl Thu Dec 25 16:52:43 2008 From: wrzesniowy at poczta.onet.pl (blady) Date: Thu, 25 Dec 2008 13:52:43 -0800 (PST) Subject: Big Tits and Big Boobs Message-ID: <9f7be2d5-c2d0-4051-9dcf-9732e2361abb@b41g2000pra.googlegroups.com> http://yeba.pl/show/movies/6044/pucybutka From Astley.lejasper at gmail.com Wed Dec 3 05:28:35 2008 From: Astley.lejasper at gmail.com (Astley Le Jasper) Date: Wed, 3 Dec 2008 02:28:35 -0800 (PST) Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> <9566ebea-d6b9-45bf-9bba-df259508efd3@w3g2000yqc.googlegroups.com> Message-ID: <8ab6010b-1e39-441b-b4ab-632f5b83b2be@f3g2000yqf.googlegroups.com> Ok ... this is odd. I tried gregory's suggestion of redirecting the stdout & stderr to a text file. This worked. I could see all the logging information. However, there was no error to see this time ... the application worked completely without any problems. I also then tried Jon's suggestion of attaching to the console ... this also allowed me to see all the logging info as it went through. Again, there were no problems as the application worked without any problems. Which suggests that it's the logging module or something with the output streams. Here is my logging setup in the primary module. It directs info to the main console and also to a logging file..... >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #Set up logging log = logging.getLogger('scrape_manager') log.setLevel(logging.INFO) my_filename = ss.compact_date() + '_' + time.strftime("%H%M") ensure_dir('logs/') #Checks to see if the dir is there and creates it if not log_file = 'logs/systemlog_' + my_filename + ".log" console_h = logging.StreamHandler() file_h = logging.FileHandler(log_file,'w') log.addHandler(console_h) log.addHandler(file_h) console_fmt = logging.Formatter('%(levelname)s (%(threadName)-10s) % (module)s %(message)s',) file_fmt = logging.Formatter('%(asctime)s\t%(levelname)s\t(% (threadName)-10s)\t%(module)s\t%(message)s',) console_h.setFormatter(console_fmt) file_h.setFormatter(file_fmt) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> I also call this from an auxiliary module that is use my the primary module: log = logging.getLogger('scrape_manager') If I change the name of the logger in the auxilary module then I loose all the loggiing information but the application works. What am I doing wrong with the logging setup? I can't see how I would change it. ALJ From Russ.Paielli at gmail.com Sun Dec 7 19:19:40 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 7 Dec 2008 16:19:40 -0800 (PST) Subject: Python for kids? References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> Message-ID: Thanks to everyone who replied. The information was very helpful. Someone might want to consider putting a kids section on python.org (if it doesn't have one already -- I didn't see one). From walterbyrd at iname.com Wed Dec 17 13:30:00 2008 From: walterbyrd at iname.com (walterbyrd) Date: Wed, 17 Dec 2008 10:30:00 -0800 (PST) Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> Message-ID: <6a76b501-f6dc-41b5-8828-b55fece68651@l33g2000pri.googlegroups.com> On Dec 17, 9:04?am, rdmur... at bitdance.com wrote: > Yes. ?It's called Object Oriented Programming. I think you mean it's *Python* Object Oriented Programming. I am not sure that every other OO language works like that. From s.selvamsiva at gmail.com Tue Dec 2 03:40:33 2008 From: s.selvamsiva at gmail.com (S.Selvam Siva) Date: Tue, 2 Dec 2008 14:10:33 +0530 Subject: Posting File as a parameter to PHP/HTML using HTTP POST In-Reply-To: References: Message-ID: I myself have found the solution. Instead of: br[br['uploadedfile']=open("C:/ > > Documents and Settings/user/Desktop/Today/newurl-ideas.txt") We Need to use: br.add_file(open("C:/ > > Documents and Settings/user/Desktop/Today/newurl-ideas.txt"), > filename="newurl-ideas.txt",name="uploadedfile") > On Tue, Dec 2, 2008 at 1:33 PM, S.Selvam Siva wrote: > I am trying to post file from python to php using HTTP POST method. I tried > mechanize but not able to pass the file object. > > from mechanize import Browser > br=Browser() > response=br.open("http://localhost/test.php") > br.select_form('form1') > br['uploadedfile']=open("C:/Documents and > Settings/user/Desktop/Today/newurl-ideas.txt") > response=br.submit() > print response.read() > > But, i get the error: > br['uploadedfile']=open("C:/Documents and > Settings/user/Desktop/Today/newurl > -ideas.txt") > File > "C:\Python25\lib\site-packages\clientform-0.2.9-py2.5.egg\ClientForm.py", > line 2880, in __setitem__ > ValueError: value attribute is readonly > > But, > When uploading is done using browser, it works. > -- > Yours, > S.Selvam > -- Yours, S.Selvam -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip at pobox.com Fri Dec 5 15:24:04 2008 From: skip at pobox.com (skip at pobox.com) Date: Fri, 5 Dec 2008 14:24:04 -0600 Subject: Centralized logging server... In-Reply-To: <413147e3-aaea-4ae3-a350-4c22a79fe77a@b38g2000prf.googlegroups.com> References: <413147e3-aaea-4ae3-a350-4c22a79fe77a@b38g2000prf.googlegroups.com> Message-ID: <18745.36324.222087.910108@montanaro-dyndns-org.local> Sam> I've been playing with the python logging module. I'd like all of Sam> these applications to write their logs to the same place in order Sam> to make analysis easier. Sam> Any ideas on best practices? Perhaps use logging.handlers.SysLogHandler? Sam> What are my options for a syslog server to receive the messages? Sam> Rsyslog looks like it would be good. Anyone know anything else? If you're running on a Unix system of any type you should have syslog by default. You shouldn't need to install anything. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From rdmurray at bitdance.com Thu Dec 11 11:35:47 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Thu, 11 Dec 2008 11:35:47 -0500 (EST) Subject: Preventing execution of a method In-Reply-To: References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> Message-ID: On Thu, 11 Dec 2008 at 08:16, alex23 wrote: > On Dec 12, 2:07?am, "Emanuele D'Arrigo" wrote: >> I.e. if I have a class with two methods, doSomethingSafe() and >> doSomethingDangerous(), is there a way to prevent another module from >> executing doSomethingDangerous() but allow the execution of >> doSomethingSafe()? >> >> My understanding is that in python this is not possible. Can you >> confirm? > > Your understanding is correct. > > The Python convention is to prefix non-public methods/classes etc with > an underscore, as in _doSomethingDangerous(). This is meant to > indicate to anyone using your module that they shouldn't use this > function, at least not without having a good understanding of what it > does. There is, however, also the possibility of prefixing the method name with '__'. The invokes 'name mangling', which makes it more difficult (though not impossible, the idea is to avoid accidents) for the method to be called from outside the class. http://www.python.org/doc/2.5.2/tut/node11.html#SECTION0011600000000000000000. --RDM From eliben at gmail.com Wed Dec 10 01:15:06 2008 From: eliben at gmail.com (eliben) Date: Tue, 9 Dec 2008 22:15:06 -0800 (PST) Subject: SequenceMatcher bug ? References: Message-ID: <67253331-5b36-4018-b15a-c0b86c5342d3@r37g2000prr.googlegroups.com> On Dec 10, 4:12?am, rdmur... at bitdance.com wrote: > On Mon, 8 Dec 2008 at 23:46, eliben wrote: > > This is about Python 2.5.2 - I don't know if there were fixes to this > > module in 2.6/3.0 > > > I think I ran into a bug with difflib.SequenceMatcherclass. > > Specifically, its ratio() method. The following: > > >SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + [5]).ratio > > () > > > returns 0.0 > > > While the same with 500 replaced by 100 returns .99... something > > Looking at the code ofSequenceMatcherthere's some caching going on > > when the sequences are longer than 200 elements (and indeed, I can > > reproduce the bug above 200 but not below). Can anyone confirm that > > this misbehaves and suggest a workaround ? > > Python 2.5.2 (r252:60911, Sep 29 2008, 20:34:04) > [GCC 4.3.1] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> from difflib importSequenceMatcher > >>>SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + > >>> [5]).ratio() > > 0.99900299102691925 > Strange. I could reproduce the problem both on ActiveState Python 2.5.2 for Windows, and in the online Try Python evaluator: http://try-python.mired.org/ Eli From gagsl-py2 at yahoo.com.ar Mon Dec 8 03:31:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Dec 2008 06:31:16 -0200 Subject: how to get a beep, OS independent ? In-Reply-To: References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> <014c575a$0$20670$c3e8da3@news.astraweb.com> Message-ID: En Sun, 07 Dec 2008 23:34:17 -0200, Joe Strout escribi?: > On Dec 7, 2008, at 4:43 PM, Steven D'Aprano wrote: > >> Of course, if you're volunteering to write such a standard system beep >> for Python, I for one would be grateful. > > I am. But where should I put it? Assuming we don't want to wait for > the (understandably) lengthy and contentious process required to add > something to the Python system libraries, where would be the next best > place for this sort of simple OS abstraction layer? The cookbook? http://www.activestate.com/ASPN/Python/Cookbook/ If you can make it run on several different architectures you could upload a patch as a feature request to http://bugs.python.org/ -- Gabriel Genellina From bearophileHUGS at lycos.com Mon Dec 22 19:26:46 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 22 Dec 2008 16:26:46 -0800 (PST) Subject: iterating initalizations References: Message-ID: Chris Rebert: > It likely goes without saying, but you ought to read the fine tutorial as well. I also suggest to fix the messed up indentations. Bye, bearophile From ss9260 at gmail.com Thu Dec 25 10:19:10 2008 From: ss9260 at gmail.com (sriya) Date: Thu, 25 Dec 2008 07:19:10 -0800 (PST) Subject: Topics on Electronics Message-ID: Electronics is the field of manipulating electrical currents and voltages using passive and active components that are connected together to create circuits. Electronic circuits range from a simple load resistor that converts a current to a voltage, to computer central-processing units (CPUs) that can contain more than a million transistors. The following indices and documents provide a basic reference for understanding electronic components, circuits, and applications. http://electronicstopics.blogspot.com/2008/10/welcome-to-world-of-electronics.html From joe at strout.net Fri Dec 19 17:20:08 2008 From: joe at strout.net (Joe Strout) Date: Fri, 19 Dec 2008 15:20:08 -0700 Subject: encoding problem In-Reply-To: <6r2hvjFfb5kpU6@mid.uni-berlin.de> References: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> <6r1m72Ffb5kpU3@mid.uni-berlin.de> <6r2hvjFfb5kpU6@mid.uni-berlin.de> Message-ID: <494C1E18.50606@strout.net> Marc 'BlackJack' Rintsch wrote: >> And because strings in Python, unlike in (say) REALbasic, do not know >> their encoding -- they're just a string of bytes. If they were a string >> of bytes PLUS an encoding, then every string would know what it is, and >> things like conversion to another encoding, or concatenation of two >> strings that may differ in encoding, could be handled automatically. >> >> I consider this one of the great shortcomings of Python, but it's mostly >> just a temporary inconvenience -- the world is moving to Unicode, and >> with Python 3, we won't have to worry about it so much. > > I don't see the shortcoming in Python <3.0. If you want real strings > with characters instead of just a bunch of bytes simply use `unicode` > objects instead of `str`. Fair enough -- that certainly is the best policy. But working with any other encoding (sometimes necessary when interfacing with any other software), it's still a bit of a PITA. > And does REALbasic really use byte strings plus an encoding!? You betcha! Works like a dream. > Sounds strange. When concatenating which encoding "wins"? The one that is a superset of the other, or if neither is, then both are converted to UTF-8 (which is the "standard" encoding in RB, though it works comfily with any other too). Cheers, - Joe From prologic at shortcircuit.net.au Mon Dec 15 00:00:33 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 15 Dec 2008 15:00:33 +1000 Subject: Python is slow In-Reply-To: References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> Message-ID: On Mon, Dec 15, 2008 at 2:59 PM, James Mills wrote: > On Mon, Dec 15, 2008 at 2:44 PM, Benjamin Kaplan > wrote: >> On Sun, Dec 14, 2008 at 11:38 PM, cm_gui wrote: >>> >>> hahaha, do you know how much money they are spending on hardware to >>> make >>> youtube.com fast??? >> >> Obviously not enough to get to the point where it's cheaper to have the >> programmers write C code. And the hardware is more for handling the intense >> traffic that YouTube gets, not for speeding up the site. > > Seriously cm_gui, you're a fool. > Python is not slow. And I should clarify that by stating that the CPython interpreter is NOT slow. --JamesMills From floris.bruynooghe at gmail.com Wed Dec 24 09:56:21 2008 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Wed, 24 Dec 2008 06:56:21 -0800 (PST) Subject: Using exceptions in defined in an extension module inside another extension module Message-ID: <26443e22-0dd6-4fa9-a58e-8d9314001c6c@o4g2000pra.googlegroups.com> Hello If I have an extension module and want to use an exception I can do by declaring the exception as "extern PyObject *PyExc_FooError" in the object files if I then link those together inside a module where the module has them declared the same (but no extern) and then initialises them in the PyMODINIT_FUNC using PyErr_NewException. What I can't work out however is how to then be able to raise this exception in another extension module. Just defining it as "extern" doesn't work, even if I make sure the first module -that creates the exception- gets loaded first. Because the symbol is defined in the first extension module the dynamic linker can't find it as it only seems to look in the main python executable for symbols used in dlloaded sofiles. Does anyone have an idea of how you can do this? Thanks Floris From bdesth.quelquechose at free.quelquepart.fr Sun Dec 21 14:14:49 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 21 Dec 2008 20:14:49 +0100 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> Message-ID: <494ea35c$0$12776$426a74cc@news.free.fr> r a ?crit : (snip clueless rant) > One more big complaint "THE BACKSLASH PLAGUE". ever tried regexp? Yes. exp = re.compile(r"no \problem \with \backslashes") >, or > file paths?. You mean _dos/windows_ file path separator ? It was indeed a stupid choice _from microsoft_ to choose the by then well established escape char (the backslash) as a file path separator. But hopefully, Python handles it gracefully: you can either use raw strings (which I stronly advise you learn about instead of whining) or just the traditional unix one (forward slash) instead. > All because that little backslash char is a line > continuation character, Totally clueless, as usual... Why don't you just READ THAT FUCKING MANUAL ? From Casper.Dik at Sun.COM Mon Dec 1 03:51:58 2008 From: Casper.Dik at Sun.COM (Casper H.S. Dik) Date: 01 Dec 2008 08:51:58 GMT Subject: Python surpasses Perl in popularity? References: <5e87aee0-c7fd-4e9d-befb-0cc01cee64ec@f40g2000pri.googlegroups.com> <49316c95$0$2813$742ec2ed@news.sonic.net> <49322ea2$0$2747$742ec2ed@news.sonic.net> Message-ID: <4933a5ae$0$185$e4fe514c@news.xs4all.nl> Stephane CHAZELAS writes: >It's true it was vague and misleading, >/bin is not the standard place to look for "sh" as far as the >"POSIX" standard is concerned. That doesn't mean that standard >commands (POSIX or not) cannot be found in /bin. But /bin/sh has >been made a non-standard place for "sh". It's the "legacy" >place. Those commands that have not undergone non-backward >compatible changes with POSIX can still be found in /bin, the >others are to be found in /usr/xpg/bin (for the standard >versions). The proper place is "`getconf PATH`". POSIX doesn't list any pathnames. Of course, the problem is then "where did getconf come from?". Casper -- Expressed in this posting are my opinions. They are in no way related to opinions held by my employer, Sun Microsystems. Statements on Sun products included here are not gospel and may be fiction rather than truth. From ndbecker2 at gmail.com Thu Dec 18 09:20:56 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 18 Dec 2008 09:20:56 -0500 Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> Message-ID: Tino Wildenhain wrote: > Neal Becker wrote: >> Reading some FAQ, I see that __str__ is "meant for human eyes". >> >> But it seems that: >> class X(object): >> def __str__(self): >> return "str" >> def __repr__(self): >> return "repr" >> >> x = X() >> d = {0 : x} >> print d >> {0: repr} >> >> So if __str__ is "meant for human eyes", then why isn't print using it! > > it is: > > > print x > str > > but dict just uses repr() for all its childs to print. > > T. That makes no sense to me. If I call 'print' on a container, why wouldn't it recursively print on the contained objects? Since print means call str, printing a container should recursively call str on the objects. From gandalf at shopzeus.com Thu Dec 18 10:34:38 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 18 Dec 2008 16:34:38 +0100 Subject: psycopg2 and large queries Message-ID: <494A6D8E.1050002@shopzeus.com> psycopg2 is said to be db api 2.0 compilant, but apparent it is buggy. By default, when I create a cursor with cur = conn.cursor() then it creates a cursor that will fetch all rows into memory, even if you call cur.fetchone() on it. (I tested it, see below.) I was looking for psycopg2 documentation, but I found nothing. However, I found some posts telling that named cursors do support fetching a single row at a time. Here is how to create a named cursor: cur = conn.cursor('mycursor') This is very strange, because DB API 2.0 does not have this feature. Why this feature was created, and how to use it? Not documented. Anyway, I wrote a program that uses named/nameless cursors, sets cur.arraysize to different values before callig cur.execute, then fetches all rows with fetchone(). I used the following query on a bigger table: select name from product limit 1000000 Here are the test results for fetchone(): Named cursor, arraysize=1 2613 rec/sec, query opens in 0.005 sec, uses only a few memory Named cursor, arraysize=1000 2831 rec/sec, query opens in 0.005 sec, uses only a few memory Nameless cursor, arraysize=1 41335 rec/sec, query opens in 28 sec, uses 100MB+ memory Nameless cursor, arraysize=1 39602 rec/sec, query opens in 25.8 sec, uses 100MB+ memory It is clear that named cursors have very bad performance, I cannot use them. Nameless cursors cannot be used either, because they are stressing the system, put 100% disk I/O and big memory usage, without any good reason. The only one solution I found is to use named cursors, and use fetchmany(100) instead of fetchone(). This results in fast opening (0.005 sec) of the cursor, and good speed (30 000 rec/sec, about 75% of the nameless version). (Do I really need to implement buffering in Python to be efficient???) However, this is also not usable, because named cursors do not have a ".description" property! You can try this: cur = conn.cursor('mycursor') cur.execute('select name from product limit 1000000') print repr(cur.description) # -> None This is unacceptable! This is not DB API 2.0 compilant. I have to know the names of the columns, how can I do that? What am I doing wrong? Please help me! Thanks, Laszlo p.s.: I tried to subscribe to the psycopg mailing list, but the confirmation email did not arrive in 6 hours... From ethan at stoneleaf.us Fri Dec 12 15:01:35 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 12 Dec 2008 12:01:35 -0800 Subject: newbie question: if var1 == var2: In-Reply-To: <49320E9B.9060606@gmail.com> References: <1drnn4s80telr$.1ofybdk342gmc$.dlg@40tude.net> <49320E9B.9060606@gmail.com> Message-ID: <4942C31F.5050807@stoneleaf.us> Andrew Robert wrote: > Two issues regarding script. > > You have a typo on the file you are trying to open. > > It is listed with a file extension of .in when it should be .ini . Pardon? The OPs original post used .in both in the python code and the command line. Doesn't look like a typo to me. Out of curiosity, what types of .ini files have one text string per line without = ? The ones I have seen follow this format: [section name] setting1 = a value setting2 = another value ~Ethan~ From s.selvamsiva at gmail.com Tue Dec 2 03:03:27 2008 From: s.selvamsiva at gmail.com (S.Selvam Siva) Date: Tue, 2 Dec 2008 13:33:27 +0530 Subject: Posting File as a parameter to PHP/HTML using HTTP POST Message-ID: I am trying to post file from python to php using HTTP POST method. I tried mechanize but not able to pass the file object. from mechanize import Browser br=Browser() response=br.open("http://localhost/test.php") br.select_form('form1') br['uploadedfile']=open("C:/Documents and Settings/user/Desktop/Today/newurl-ideas.txt") response=br.submit() print response.read() But, i get the error: br['uploadedfile']=open("C:/Documents and Settings/user/Desktop/Today/newurl -ideas.txt") File "C:\Python25\lib\site-packages\clientform-0.2.9-py2.5.egg\ClientForm.py", line 2880, in __setitem__ ValueError: value attribute is readonly But, When uploading is done using browser, it works. -- Yours, S.Selvam -------------- next part -------------- An HTML attachment was scrubbed... URL: From tino at wildenhain.de Mon Dec 15 07:35:43 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 15 Dec 2008 13:35:43 +0100 Subject: regex problem .. In-Reply-To: <3b10c2060812150421y1c3e7da6ha1b72c736e2a20d4@mail.gmail.com> References: <3b10c2060812150421y1c3e7da6ha1b72c736e2a20d4@mail.gmail.com> Message-ID: <49464F1F.7040703@wildenhain.de> Analog Kid wrote: > Hi All: > I am new to regular expressions in general, and not just re in python. > So, apologies if you find my question stupid :) I need some help with > forming a regex. Here is my scenario ... > I have strings coming in from a list, each of which I want to check > against a regular expression and see whether or not it "qualifies". By > that I mean I have a certain set of characters that are permissible and > if the string has characters which are not permissible, I need to flag > that string ... here is a snip ... > > flagged = list() > strs = ['HELLO', 'Hi%20There', '123123@#@'] > p = re.compile(r"""[^a-zA-Z0-9]""", re.UNICODE) > for s in strs: > if len(p.findall(s)) > 0: > flagged.append(s) > > print flagged > > my question is ... if I wanted to allow '%20' but not '%', how would my > current regex (r"""[^a-zA-Z0-9]""") be modified? You might want to normalize before checking, e.g. from urllib import unquote p=re.compile("[^a-zA-Z0-9 ]") flagged=[] for s in strs: if p.search(unquote(s)): flagged.append(s) be carefull however if you want to show the flagged ones back to the user. Best is always quote/unquote at the boundaries as appropriate. Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From mavikorsan7 at gmail.com Thu Dec 18 06:37:21 2008 From: mavikorsan7 at gmail.com (=?ISO-8859-9?Q?sevimli_arkada=FE?=) Date: Thu, 18 Dec 2008 03:37:21 -0800 (PST) Subject: www.webhizmetlerim.com Message-ID: <9b9eb8d1-a859-43cf-89a5-f52f3df6764f@r15g2000prd.googlegroups.com> Dear Readers; If you write us our web site's queue and page number at google then three of you can get prices from us.We are going to have a sweepstake for this. If you send more mails,you have more chance to win. Our competition is going to finish at 1 February 2009. Please write google 'web tasar?m' then write us that which queue and which page our web site www.webhizmetlerim.com is. Also you can help to hear your friends at your list by sending them mails for the competition. PR?CES 1.NOTEBOOK 2.MP4 3.MP3 Write us your name,surname and mail adress to www.webhizmetlerim.com communication part,then get the prize. And send this mail to your friends then they will get the prices too.Send mails every day and have more chance. From bignose+hates-spam at benfinney.id.au Mon Dec 15 00:50:01 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 15 Dec 2008 16:50:01 +1100 Subject: alt.possessive.its.has.no.apostrophe (was: Looking for the best way to translate an idiom) References: Message-ID: <87vdtmf0mu.fsf_-_@benfinney.id.au> James Stroud writes: > Yes. I think it was the British who decided that the apostrophe rule > for "it" would be reversed from normal usage relative to just about > every other noun. Remember that ?it? is a pronoun. I see no reversal: he she we they me you it he's she's we're they're I'm you're it's his hers ours theirs mine yours its No reversal there; the apostrophe rule is consistent. All pronouns take an apostrophe *only* for abbreviating the contraction of ?foo is? or ?foo has? or some other two-word form. The possessive never takes an apostrophe on a pronoun. You can find plenty of inconsistencies and rules with exceptions in the English language, but ?possessive pronoun doesn't use an apostrophe? isn't one of them. -- \ ?Don't you try to outweird me, I get stranger things than you | `\ free with my breakfast cereal.? ?Zaphod Beeblebrox, _The | _o__) Restaurant At The End Of The Universe_, Douglas Adams | Ben Finney From james at agentultra.com Sun Dec 21 22:40:53 2008 From: james at agentultra.com (J Kenneth King) Date: Sun, 21 Dec 2008 22:40:53 -0500 Subject: Are Django/Turbogears too specific? References: Message-ID: <85tz8wop16.fsf@agentultra.com> Gilles Ganault writes: > Hi > > I'd like to rewrite a Web 2.0 PHP application in Python with AJAX, and > it seems like Django and Turbogears are the frameworks that have the > most momentum. > > I'd like to use this opportunity to lower the load on servers, as the > PHP application wasn't built to fit the number of users hammering the > servers now. > > I'm concerned, though, that these frameworks they may be too specific > to the tasks they were originally developped for (news articles, > AFAIK). Do you think I should just use eg. CherryPy and some basic > AJAX? > > Thank you for any feedback. They're not "specific" in the sense that they only build certain types of applications. However, they do package their own batteries and expect applications to be designed a certain way. As long as you drink the kool-aid, everything is smooth sailing. That's what any "framework" banks on -- being useful to 85% of the web applications; not all. Even if they advertise themselves as such, it's just not true. My suggestion is web.py -- It too has its own set of conventions and philosophies, but in my experience it is the most loosely coupled in terms of internal dependencies. Import exactly what you want to use and deploy it the way that suits you. It gives you batteries but you have to pick and choose how to put the pieces together. Therefore, it takes a little longer to get running, but IMO that is the most flexibility you can ask for without writing your own servers and frameworks. Cheers. From ldo at geek-central.gen.new_zealand Fri Dec 5 05:17:42 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 05 Dec 2008 23:17:42 +1300 Subject: Don't you just love writing this sort of thing :) References: <0148b086$0$20670$c3e8da3@news.astraweb.com> Message-ID: In message <0148b086$0$20670$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > ... stupid formatting ... withallthedifferenttermsruntogetherintoonelinesoyoudon'tknowwhereoneendsandtheotherbeginsifthat'showyouliketowritecodefinethat'snothowIliketodoit From jeremiah.dodds at gmail.com Tue Dec 23 05:35:38 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Tue, 23 Dec 2008 05:35:38 -0500 Subject: Beep In-Reply-To: References: <47c890dc0812211620h6c19086dhf3a14a662a49fdf6@mail.gmail.com> <6r8qqpFq8rU1@mid.individual.net> Message-ID: <12cbbbfc0812230235l549f48dj2f367f614f32a50e@mail.gmail.com> On Mon, Dec 22, 2008 at 10:42 PM, Jeffrey Barish wrote: > > > On Ubuntu, it is possible to set visual and audible beeps separately. When > I set both, I get the visual beep, but not the audible one. It's not a > Python issue -- so I should take this thread to Ubuntu -- because I observe > this behavior even when I hit backspace at the beginning of a line in a > terminal. > -- > Jeffrey Barish > > -- > http://mail.python.org/mailman/listinfo/python-list > Well, I would try printing a bell character in another language, say ruby or perl, or just in the terminals on the machines that won't print them in python. If you get a bell from those, it's likely some issue with your python installation, otherwise it's likely a problem with Ubuntu configuration somewhere. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ibpet11 at gmail.com Wed Dec 31 04:52:51 2008 From: ibpet11 at gmail.com (ibpet11 at gmail.com) Date: Wed, 31 Dec 2008 01:52:51 -0800 (PST) Subject: SDC lite Message-ID: <0be22daf-17e4-4d62-962f-f3d7658107bf@r34g2000vbp.googlegroups.com> Did anybody have idea on how and what SDC lite looks like and how it works for data conversion. From trfilmographer at gmail.com Fri Dec 12 12:47:39 2008 From: trfilmographer at gmail.com (trfilmographer at gmail.com) Date: Fri, 12 Dec 2008 09:47:39 -0800 (PST) Subject: newbie question... Message-ID: Hi! Im new at python and I just want to know if (and how) it is possible to send parameters to a program. what I mean is that when we start python I can call a file that should be run like this: python myfile.py can I send additional parameters along with it? like::: python myfile.py myVar1 myVar2 Thanks!!! From rlight2 at gmail.com Wed Dec 24 13:24:42 2008 From: rlight2 at gmail.com (Ross) Date: Wed, 24 Dec 2008 10:24:42 -0800 (PST) Subject: Custom C Exception Subclasses References: <41f291ff-d7bd-4334-8689-636e95524cdc@b38g2000prf.googlegroups.com> Message-ID: <2c6c51ee-ba22-4c46-b6f6-c4d41af7ad83@x16g2000prn.googlegroups.com> On Dec 24, 9:24 am, "Gabriel Genellina" wrote: > In fact you can, you could store those pointers as attributes of the > exception object, using a PyCObject. Excellent. I was not aware of the PyCObject type. > Accessing those attributes isn't as easy as doing exc->field, but I think > it's easy enough. Inheriting from some exception type requires you to > define the type structure and fill it right, and IMHO is a lot harder. > > Perhaps there is a misunderstanding here. To subclass a type, you need the > type, not an instance of such type. Ah yes, I probably should have been more clear. In the docs about subclassing, they use a PyListObject as the first field of the Shoddy struct so that the fields are filled in correctly. Now, how would I go about adding methods to a custom exception object? From xi at gamma.dn.ua Sun Dec 28 19:30:36 2008 From: xi at gamma.dn.ua (Kirill Simonov) Date: Mon, 29 Dec 2008 02:30:36 +0200 Subject: [ANN] PyYAML-3.07: YAML parser and emitter for Python Message-ID: <49581A2C.80307@gamma.dn.ua> ======================== Announcing PyYAML-3.07 ======================== A new release of PyYAML is now available: http://pyyaml.org/wiki/PyYAML Changes ======= * The emitter learned to use an optional indentation indicator for block scalars; thus scalars with leading whitespaces could now be represented in a literal or folded style. * The test suite is now included in the source distribution. To run the tests, type 'python setup.py test'. * Refactored the test suite: dropped unittest in favor of a custom test appliance. * Fixed the path resolver in the LibYAML-based dumper. * Forced an explicit document end indicator when there is a possibility of parsing ambiguity. * More setup.py improvements: the package should be usable when any combination of setuptools, Pyrex and LibYAML is installed. * Windows binary packages are statically linked against LibYAML-0.1.2. * Other minor fixes and improvements (Thank to Ingy dot Net and Andrey Somov). Resources ========= PyYAML homepage: http://pyyaml.org/wiki/PyYAML PyYAML documentation: http://pyyaml.org/wiki/PyYAMLDocumentation TAR.GZ package: http://pyyaml.org/download/pyyaml/PyYAML-3.07.tar.gz ZIP package: http://pyyaml.org/download/pyyaml/PyYAML-3.07.zip Windows installer: http://pyyaml.org/download/pyyaml/PyYAML-3.07.win32-py2.3.exe http://pyyaml.org/download/pyyaml/PyYAML-3.07.win32-py2.4.exe http://pyyaml.org/download/pyyaml/PyYAML-3.07.win32-py2.5.exe http://pyyaml.org/download/pyyaml/PyYAML-3.07.win32-py2.6.exe PyYAML SVN repository: http://svn.pyyaml.org/pyyaml Submit a bug report: http://pyyaml.org/newticket?component=pyyaml YAML homepage: http://yaml.org/ YAML-core mailing list: http://lists.sourceforge.net/lists/listinfo/yaml-core About PyYAML ============ YAML is a data serialization format designed for human readability and interaction with scripting languages. PyYAML is a YAML parser and emitter for Python. PyYAML features a complete YAML 1.1 parser, Unicode support, pickle support, capable extension API, and sensible error messages. PyYAML supports standard YAML tags and provides Python-specific tags that allow to represent an arbitrary Python object. PyYAML is applicable for a broad range of tasks from complex configuration files to object serialization and persistance. Example ======= >>> import yaml >>> yaml.load(""" ... name: PyYAML ... description: YAML parser and emitter for Python ... homepage: http://pyyaml.org/wiki/PyYAML ... keywords: [YAML, serialization, configuration, persistance, pickle] ... """) {'keywords': ['YAML', 'serialization', 'configuration', 'persistance', 'pickle'], 'homepage': 'http://pyyaml.org/wiki/PyYAML', 'description': 'YAML parser and emitter for Python', 'name': 'PyYAML'} >>> print yaml.dump(_) name: PyYAML homepage: http://pyyaml.org/wiki/PyYAML description: YAML parser and emitter for Python keywords: [YAML, serialization, configuration, persistance, pickle] Copyright ========= The PyYAML module is written by Kirill Simonov . PyYAML is released under the MIT license. From fakeaddress at nowhere.org Thu Dec 4 14:56:10 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 04 Dec 2008 11:56:10 -0800 Subject: python an sqlite objects In-Reply-To: References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <18742.47391.389709.119341@montanaro-dyndns-org.local> <49382153.80604@mrabarnett.plus.com> Message-ID: skip at pobox.com wrote: > >> # Ensure that we're running Python 3 or later. > >> import sys > >> assert int(sys.version.split()[0].split('.')[0]) >= 3 > >> # If there's a better way to chek, please tell. [...] > Why split at all? Just use sys.version_info: > > >>> import sys > >>> assert sys.version_info[0] > 2, sys.version_info > Traceback (most recent call last): > File "", line 1, in ? > AssertionError: (2, 4, 5, 'final', 0) Thanks. Yes, that's better. To verify that the running version of Python is 3 or higher, import sys assert sys.version_info[0] >= 3 -- --Bryan From jeremiah.dodds at gmail.com Sat Dec 6 20:56:22 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Sat, 6 Dec 2008 20:56:22 -0500 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: <12cbbbfc0812061756l635b84deh831c83cdb7808450@mail.gmail.com> On Fri, Dec 5, 2008 at 9:21 PM, Daniel Fetchinson wrote: > > The proposal is to allow this: > > class C: > def self.method( arg ): > self.value = arg > return self.value > > instead of this: > > class C: > def method( self, arg ): > self.value = arg > return self.value > > I.e. explicit self stays only the syntax is slightly different and may > seem attractive to some. As pointed out by Guido classmethods would > work similarly: > > class C: > @classmethod > def cls.method( arg ): > cls.val = arg > return cls.val > > -1. It doesn't solve a real problem, just shuffles syntax around with very little, if any, gain in clarity. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Tue Dec 30 20:16:24 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Dec 2008 01:16:24 GMT Subject: string in files References: <62075511-08ad-405a-a3af-2da8d2f22c50@v39g2000pro.googlegroups.com> Message-ID: <016abee9$0$6988$c3e8da3@news.astraweb.com> On Tue, 30 Dec 2008 11:53:17 +0100, Glauco wrote: >> thanks brother >> i mean how do i particularly assign (u = this) >> (y = is).... >> in the strings up there. i have been able to split strings with any >> character sign. >> >> > > If i'm not wrong this is simple with RE: If that's your idea of "simple", I'd hate to see what you consider complicated! *Simple* is just using the split method. a, b, c, d, e, f = 'this is a python coding group'.split() -- Steven From Scott.Daniels at Acm.Org Sun Dec 14 19:43:26 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 14 Dec 2008 16:43:26 -0800 Subject: Python shows up checking votes Message-ID: I just saw an interesting post -- The video linked to on http://www.blog.wired.com in Kim Zetter's "Threat Level" blog, there is a video describing the software used to provide open access to ballots after an election. The software used for this system is an open-source system written in Python. Turns out they found election system failures in California's Humboldt County using this software. It also turns out that the failure was not large enough to change the result of any of the races or propositions this time. By Kim Zetter's blog for 8-Dec-08 entitled "Unique Transparency Program Uncovers Problems with Voting Software" --Scott David Daniels Scott.Daniels at Acm.Org From inq1ltd at inqvista.com Fri Dec 5 16:08:56 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Fri, 05 Dec 2008 16:08:56 -0500 Subject: Problems running on hp duo Pentium R processor In-Reply-To: <77895c1d0812051227o104ff233m7f16410e3cf8b392@mail.gmail.com> References: <200809221443.25765.inq1ltd@inqvista.com> <200812051502.26421.inq1ltd@inqvista.com> <77895c1d0812051227o104ff233m7f16410e3cf8b392@mail.gmail.com> Message-ID: <200812051608.56335.inq1ltd@inqvista.com> On Friday 05 December 2008 15:27, Kevin Kelley wrote: > If they are running standard Win XP (Home or Pro), > as opposed to 64-bit Win XP, then whether or not the > CPU supports the IA64 instruction set really doesn't > matter. As far as I know every Intel Core2 and > Pentium Dual-Core CPU since ~ 2006 has supported > 64bit instructions, even the Atom is 64bit. Also, > the "R" is for Registered Trademark (of Pentium), > it's not part of the name/model > (http://ark.intel.com/cpu.aspx?groupId=33925). > > Kevin Kevin , I'm trying to find out why my program gets an import error on only one machine. Is there any problem with python running on a 64 bit Architecture machine or is it something specific to this one HP machine? None of my other clients have had this problem, nor have I on any machine that I've tried tested it on. jim-on-linux > > On Fri, Dec 5, 2008 at 2:02 PM, jim-on-linux wrote: > > Python help, > > > > In September I wrote: > > I have a number of clients running a program built > > with python 2.5. One has just purchased an HP > > with a duo core Pentium R processor E2200, 2.2G > > with .99g ram. > > > > Only on the new HP, when they try to print they > > get an import error; > > File win32ui.pyc line 12, in > > File win32ui.pyc, line 10, in _load > > ImportError: DLL load failed: The specified > > module could not be found. > > > > It turns out that the E2200 processor is 64 bit > > architecture. > > > > What are my options? > > > > I've run DependecyWalker, > > They are using Win XP Service Pack 2 > > > > > > > > jim=on-linux > > > > > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-lis > >t From skip at pobox.com Mon Dec 8 13:57:10 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 8 Dec 2008 12:57:10 -0600 Subject: Public imports In-Reply-To: <66ecdd96-38dd-4054-8009-e145c0a78316@o40g2000prn.googlegroups.com> References: <9623b0a3-7053-41f1-b116-0cd5e54f39e9@v13g2000vbb.googlegroups.com> <493d1ec0$0$32048$426a34cc@news.free.fr> <66ecdd96-38dd-4054-8009-e145c0a78316@o40g2000prn.googlegroups.com> Message-ID: <18749.28166.594048.397131@montanaro-dyndns-org.local> M?rcio> So, no chance of doing this: M?rcio> # "A.py" M?rcio> from __future__ import division, with_statement M?rcio> # "B.py" M?rcio> from A import * M?rcio> print 1 / 2 M?rcio> ...and printing 0.5, right? Too bad :) "from __future__ ..." isn't really an import statement in the usual sense of the term. It affects the byte code compiler immediately and I believe only when using that syntax. That it actually adds a name to the module's namespace is not really used (at least, not often). -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From mrkafk at gmail.com Mon Dec 29 10:29:43 2008 From: mrkafk at gmail.com (mk) Date: Mon, 29 Dec 2008 16:29:43 +0100 Subject: multiprocessing vs thread performance In-Reply-To: References: Message-ID: Christian Heimes wrote: > mk wrote: >> Am I doing smth wrong in code below? Or do I have to use >> multiprocessing.Pool to get any decent results? > > You have missed an important point. A well designed application does > neither create so many threads nor processes. Except I was not developing "well designed application" but writing the test the goal of which was measuring the thread / process creation cost. > The creation of a thread > or forking of a process is an expensive operation. Sure. The point is, how expensive? While still being relatively expensive, it turns out that in Python creating a thread is much, much cheaper than creating a process via multiprocessing on Linux, while this seems to be not necessarily true on Mac OS X. > You should use a pool > of threads or processes. Probably true, except, again, that was not quite the point of this exercise.. > The limiting factor is not the creation time but the communication and > synchronization overhead between multiple threads or processes. Which I am probably going to test as well. From robin at reportlab.com Mon Dec 29 11:04:55 2008 From: robin at reportlab.com (Robin Becker) Date: Mon, 29 Dec 2008 16:04:55 +0000 Subject: Windows SSH (remote execution of commands) - Python Automation In-Reply-To: <7FAD6FCE52421841A11B441DEF3A88CA01F09006@ZMY16EXM70.ds.mot.com> References: <7FAD6FCE52421841A11B441DEF3A88CA01F09006@ZMY16EXM70.ds.mot.com> Message-ID: <4958F527.7030805@chamonix.reportlab.co.uk> Narasimhan Raghu-RBQG84 wrote: > Hi experts, > > I am looking for some information on how to automate remote login to a > UNIX machine using ssh from a windows XP box. > > Possible way: > > 1. Use putty (or any other ssh client from windows XP). -- Can be > automated with command line parameters. The problem is that I am able to > login - Putty window opens up as well. But obviously I am unable to run > any commands in that. I need to find something like a handle to that > Putty window so that I can execute commands there. > > Can anyone provide me some help in achieving this ? > > > Thanks, > > -- > Raghu ........ I have been using plink (companion to putty) without any problem eg plink app1 ls -l where app1 is defined by putty (as a connection) and ls -l etc etc are command args. I have modified the py package's SshGateway to use plink under windows and to allow very reasonable remote python behaviour. -- Robin Becker From s.bez_spamu at remove.that.informa.and.that.pl Thu Dec 4 09:32:31 2008 From: s.bez_spamu at remove.that.informa.and.that.pl (Sebastian Kaliszewski) Date: Thu, 04 Dec 2008 15:32:31 +0100 Subject: Python advocacy ... HELP! In-Reply-To: <5f8c1a52-545e-402e-863a-acdf23d04c78@h20g2000yqn.googlegroups.com> References: <5f8c1a52-545e-402e-863a-acdf23d04c78@h20g2000yqn.googlegroups.com> Message-ID: Michael_D_G wrote: > how do I refute > the notion that Python > is a "marginal" language because according to TOBIE it only less than > a 6% market share. According to the same TIOBE, C++ has less than 11%. So it must be niche then as well :) -- "Never underestimate the power of human stupidity" -- L. Lang -- http://www.tajga.org -- (some photos from my travels) From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 23 04:11:29 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 23 Dec 2008 10:11:29 +0100 Subject: Python's popularity In-Reply-To: References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <494fef38$0$12781$426a74cc@news.free.fr> Message-ID: <4950ab3b$0$27404$426a74cc@news.free.fr> Steve Holden a ?crit : > walterbyrd wrote: > [...]>> Fooled by version numbers ? >> No, but I am giving django the benefit of the doubt. The django >> project told people all along that django was not to be considered >> production ready before 1.0. I will accept that some people decided to >> wait until 1.0 came out to do any production development. Maybe django >> is only lagging because 1.0 just came out? >> > The Django people said no such thing. They maintained the trunk as > stable - they test so well that many people did indeed rely on the trunk > for production systems. Indeed - my first Django app has been in production for more than 3 years now. (snip) >>> My actual CTO is a big Ruby/Rails fan, yet he settled on Python/Django >>> for our current 'big' project. Wonder why ? >> Not knowing much about RoR: yes, I wonder why? Is it because python >> has a cleaner syntax? Or what? > > It's because he decided that Django was the best tool for the particular > job, making him unusually open-minded for a member of the pointy-haired > species. Being a CTO doesn't necessarily makes you pointy-haired !-) We're a small shop (12 peoples), and the guy is a developper too (and yes, an active one). > Unlike some on this list he doesn't let his prejudices blind > him to reality. Yes - that was the point. From clp at rebertia.com Tue Dec 9 10:57:39 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 9 Dec 2008 07:57:39 -0800 Subject: 'pretty print' for built in types In-Reply-To: <051e3a97-b9bc-4a67-8896-93628ca19f59@r15g2000prd.googlegroups.com> References: <051e3a97-b9bc-4a67-8896-93628ca19f59@r15g2000prd.googlegroups.com> Message-ID: <47c890dc0812090757s65771a5cr50e6a0b3bbb6cc71@mail.gmail.com> On Tue, Dec 9, 2008 at 7:31 AM, Robert Dailey wrote: > Hi, > > Is there a built in way to 'pretty print' a dict, list, and tuple > (Amongst other types)? Dicts probably print the ugliest of them all, > and it would be nice to see a way to print them in a readable way. I > can come up with my own function to do this, but I don't want to do > this if I don't have to. There's the `pprint` module in the std lib: http://docs.python.org/library/pprint.html Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > From Slaunger at gmail.com Wed Dec 10 06:37:47 2008 From: Slaunger at gmail.com (Slaunger) Date: Wed, 10 Dec 2008 03:37:47 -0800 (PST) Subject: Best way to report progress at fixed intervals References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> <817384d5-5f68-4c1f-9560-0bc7b7d2b1e3@v5g2000prm.googlegroups.com> <6ccb77a2-a3f1-4b6b-900c-d4626be9e939@s1g2000prg.googlegroups.com> <93371329-5989-4f96-ac79-58a54ba6b07f@35g2000pry.googlegroups.com> Message-ID: <8e368e62-4c0f-46ad-832d-f83f88228511@i20g2000prf.googlegroups.com> On 10 Dec., 12:08, eric wrote: > Don't mind if I give my shot ? > > def work(i): > ? ? """ > ? ? Dummy process function, which takes a random time in the interval > ? ? 0.0-0.5 secs to execute > ? ? """ > ? ? print "Work step %d" % i > ? ? time.sleep(0.5 * random.random()) > > def workAll(work, verbose=True, max_iter=20, progress_interval=1.0): > ? ? ''' > ? ? pass the real job as a callable > ? ? ''' > ? ? progress = time.time() > ? ? for i in range(max_iter): # do the requested loop > ? ? ? ? work(i) > ? ? ? ? if verbose: > ? ? ? ? ? ? print "Work through all %d steps reporting progress every > %3.1f secs..." %(max_iter, progress_interval) > ? ? ? ? interval = time.time()-progress > ? ? ? ? if interval>progress_interval: > ? ? ? ? ? ? print "Processed %d of %d at pace %s" % (i, max_iter, > interval) > ? ? ? ? ? ? progress +=interval > > if __name__=="__main__": > ? ? workAll(work, False) > > It's works fine, and the "pace" is 'almost' the required one. You earn > a no-thread-mess, and cleaner alg. > > But the loop is controlled by the caller (the WorkAll function) this > is also called ass-backward algorithm, and you cannot expect > algorithms to be assbackward (even if it's the best way to implement > them). > > You can use the yield statement, to turn ?easilly your alg into a > nice, stopable assbackward algo: > > def work(): > ? ? """ > ? ? Dummy process function, which takes a random time in the interval > ? ? 0.0-0.5 secs to execute > ? ? """ > ? ? for i in range(50): > ? ? ? ? print "Work step %d" % i > ? ? ? ? time.sleep(0.5 * random.random()) > ? ? ? ? yield i # kind-of "publish it and let the caller do whatever > it want s (good practice anyway) > > def workAll(work, verbose=True, max_iter=20, progress_interval=1.0): > ? ? ''' > ? ? pass the real job as a generator > ? ? ''' > ? ? progress = time.time() > ? ? i = 0 > ? ? for w in work: # do the requested loop > ? ? ? ? if verbose: > ? ? ? ? ? ? print "Work through all %d steps reporting progress every > %3.1f secs..." %(max_iter, progress_interval) > ? ? ? ? interval = time.time()-progress > ? ? ? ? if interval>progress_interval: > ? ? ? ? ? ? print "Processed %d at pace %s" % (w, interval) > ? ? ? ? ? ? progress +=interval > ? ? ? ? if i>=max_iter: > ? ? ? ? ? ? work.close() > ? ? ? ? i+=1 > > if __name__=="__main__": > ? ? workAll(work(), False) ? ? # note the calling difference > > hope it helps. Hi eric, No, I certainly don't mind you giving a try ;-) I actually started out doing something like your first version here, but I am a little annoyed by the fact that the progress report interval is not a sure thing. For instance in my real applications, I have seldomly occuring work steps, which may take significantly longer than the progress_interval, and I'd like to let it keep reporting that, oh, I am still woking, albeit on the same work step, to maintain a sense of the script being alive. I like you generator approach though. Anyway, I have now given my own proposal another iteration based on what I have seen here (and my personal preferences), and I have come up with this: ============ src ======================= """ Test module for testing generic ways of displaying progress information at regular intervals. """ import random import threading import time def work(i): """ Dummy process function, which takes a random time in the interval 0.0-0.5 secs to execute """ print "Work step %d" % i time.sleep(0.5 * random.random()) def workAll(verbose=True, max_iter=20, progress_interval=1.0): class ProgressReporter(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.setDaemon(True) self.i = 0 self.max = max_iter self.start_timer = verbose self.progress_interval = progress_interval def run(self): while self.start_timer: print "Processed %d of %d." % (self.i + 1, self.max) time.sleep(self.progress_interval) p = ProgressReporter() if verbose: print "Work through all %d steps reporting every %3.1f secs..." % \ (max_iter, progress_interval) p.start() for i in xrange(max_iter): work(i) p.i = i if verbose: print "Finished working through %d steps" % max_iter if __name__ == "__main__": workAll() ========= end src ================================ I like this much better than my own first attempt in my initial post on this thread. -- Slaunger From 00515879256 at fastwebnet.it Tue Dec 30 05:53:17 2008 From: 00515879256 at fastwebnet.it (Glauco) Date: Tue, 30 Dec 2008 11:53:17 +0100 Subject: string in files In-Reply-To: <62075511-08ad-405a-a3af-2da8d2f22c50@v39g2000pro.googlegroups.com> References: <62075511-08ad-405a-a3af-2da8d2f22c50@v39g2000pro.googlegroups.com> Message-ID: > > thanks brother > i mean how do i particularly assign (u = this) > (y = is).... > in the strings up there. i have been able to split strings with any > character sign. > If i'm not wrong this is simple with RE: In [1]: st = 'this is a python coding group' In [2]: import re In [3]: re.compile( "(?P.*) (?P.*) (?P.*) (?P.*) (?P.*) (?P.*)" ) Out[3]: <_sre.SRE_Pattern object at 0x9e93ac0> In [4]: rule = re.compile( "(?P.*) (?P.*) (?P.*) (?P.*) (?P.*) (?P.*)" ) In [5]: m = rule.match( st ) In [6]: dir(m) Out[6]: ['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict', 'groups', 'span', 'start'] In [7]: m.groupdict().items() Out[7]: [('si', 'group'), ('second', 'is'), ('t', 'a'), ('fi', 'coding'), ('fo', 'python'), ('first', 'this')] In [8]: dict(m.groupdict().items()) Out[8]: {'fi': 'coding', 'first': 'this', 'fo': 'python', 'second': 'is', 'si': 'group', 't': 'a'} Glauco From wuwei23 at gmail.com Mon Dec 8 23:31:38 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 8 Dec 2008 20:31:38 -0800 (PST) Subject: built-in functions as class attributes References: <75fdbf34-34d9-4373-bbe0-7e3f76dc4c3f@x38g2000yqj.googlegroups.com> Message-ID: <0631fe83-e857-46c0-ae2d-39fbf1febced@v39g2000pro.googlegroups.com> On Dec 8, 8:46?pm, Mark Dickinson wrote: > Here's a curiosity: ?after > > def my_hex(x): > ? ? return hex(x) > > one might expect hex and my_hex to be interchangeable > in most situations. ?But (with both Python 2.x and 3.x) > I get: > > >>> def my_hex(x): return hex(x) > ... > >>> class T(object): f = hex > ... > >>> class T2(object): f = my_hex > ... > >>> T().f(12345) > '0x3039' > >>> T2().f(12345) > > Traceback (most recent call last): > ? File "", line 1, in > TypeError: my_hex() takes exactly 1 argument (2 given) > [36412 refs] You're attaching 'my_hex' as a method to T2, which by default will automatically try to pass in the instance to 'f' when called. This is why you explicitly declare 'self' as the first argument for methods. And as Peter's post points out, this behaviour doesn't happen with built-in functions. However, when attaching 'my_hex', you can explicitly state that you don't want this behaviour by using the 'staticmethod' decorator: >>> def my_hex(x): return hex(x) ... >>> class T2(object): f = staticmethod(my_hex) ... >>> T2().f(12345) '0x3039' Hope this helps. From rt8396 at gmail.com Mon Dec 1 23:18:47 2008 From: rt8396 at gmail.com (r) Date: Mon, 1 Dec 2008 20:18:47 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> Message-ID: alex23, Ok...you don't like my idea...so why keep responding? ajaksu, You insulted me and accused me of trolling, but it looks like your interested. And you also included links. I think your really on board and just can't say it yet *wink*. Thank You Aaron, I agree to disagree with you...although you make some good points... and welcome your views on Lasch's reference to the pitfalls of a Narcissistic society. At least you DO know how to engage in intelligent conversation to the benefit of both parties, and not just flame. Thank you James, By far the most positive post since Greg's. I agree with your overview and welcome your constructive criticism. Thank You friend So I would defiantly say things are starting to turn. The butterfly effect is transforming my crazy idea to garner support for a SU Python integration into maybe becoming reality. I still have hope! All i need is one or two serious people and we could do this. I know you're out there. PS hey...even alex23's post are a little less mean. Either I am wearing him down or he is beginning to believe :) I would love to have you on board alex... i'm thinking... bouncer xD From gslindstrom at gmail.com Thu Dec 4 09:37:10 2008 From: gslindstrom at gmail.com (greg) Date: Thu, 4 Dec 2008 06:37:10 -0800 (PST) Subject: RELEASED Python 3.0 final References: Message-ID: On Dec 3, 7:51?pm, Barry Warsaw wrote: > On behalf of the Python development team and the Python community, I ? > am happy to announce the release of Python 3.0 final. Way to go and congratulations! --greg From eric at ericaro.net Fri Dec 5 09:21:04 2008 From: eric at ericaro.net (eric) Date: Fri, 5 Dec 2008 06:21:04 -0800 (PST) Subject: A more pythonic way of writting Message-ID: <35d176ed-df5f-46b4-8321-4814fcc4398c@f3g2000yqf.googlegroups.com> Hi, I've got this two pieces of code that works together, and fine def testit(): for vals in [[i&mask==mask for mask in [1<', flag(*vals) def flag(IGNORECASE=False, LOCALE=False, MULTILINE=False, DOTALL=False, UNICODE=False, VERBOSE=False): vals = [IGNORECASE, LOCALE, MULTILINE, DOTALL, UNICODE, VERBOSE] filtered = map( lambda m:m[1],filter( lambda m: m[0], zip(vals, 'iLmsux'))) return '?'+''.join( filtered ) testit() but I'm not proud of the way it is written. I dont find it very pythonic. I have to multiplex (using zip) bool and value, filter using only the bool, and demultiplex later using map the first simply parses all the possible combination of 6 boolean (can't hardly be made simpler) the second function, should simply return a string based on the boolean value i, L, m, s, u, x, True, False, False, True, True, False = ?isu that's should take only one line, shouldn't it? any idea ? From kyosohma at gmail.com Tue Dec 30 15:01:09 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 30 Dec 2008 12:01:09 -0800 (PST) Subject: embedding python in wxpython References: <191280cf-ecf9-4135-9737-9923061855d1@t39g2000prh.googlegroups.com> Message-ID: <26066df6-3983-45c7-87eb-81df570ff582@i18g2000prf.googlegroups.com> On Dec 30, 1:52?pm, 5lvqbw... at sneakemail.com wrote: > Hi, I've looked around for a way to allow a python console from within > a wxPython application, but have only found stuff on embedded/ > extending python with C/C++ or wxWidgets in C++, but not wxPython. > > Is this easy to do? ?Can someone point me in the right direction? > > Also, typically when you embed a scripting language into a larger > application, how do you get the console environment to share data with > the larger application? > > For instance, if the application has some gui stuff (for example > clicking on a object and dragging it around), how do you get > "object.select(x,y)" to print out on the console, and vice-versa: the > object gets selected if the user types "object.select(x,y)"? > > I'd like the console to be a bidirectional representation of what's > going on in the gui, plus a general purpose evaluation environment > where you can manipulate application data via some api which is > automatically exposed to the console when the application opens up. > > I'm looking for high-level hints/strategies/directions. > > Thank you > Michael You should ask the guys on the wxPython list for pointers: http://wxpython.org/maillist.php I'm pretty sure I've seen it discussed there before. They already have PyShell and PyCrumb that you could probably use within your program. The wxPython includes demos of them and lots of other widgets. Mike From atagar1 at gmail.com Wed Dec 10 03:46:37 2008 From: atagar1 at gmail.com (Damian Johnson) Date: Wed, 10 Dec 2008 00:46:37 -0800 Subject: Curses Blank Background Message-ID: Does anyone know how to instruct the Python curses bindings to leave the background alone (use the default terminal background)? I'm interested in keeping my semi-transparent background which curses can't replicate. This question was raised on this list before ( http://mail.python.org/pipermail/python-list/2001-July/094581.html) but it never got a reply. From the ncurses man page it looks like this functionality would be mapped to -1 but the Python curses module uses -1 for ERR. I'm new to curses so my apologies if I'm missing something obvious. Cheers! -Damian -------------- next part -------------- An HTML attachment was scrubbed... URL: From gnewsg at gmail.com Sun Dec 28 12:33:00 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sun, 28 Dec 2008 09:33:00 -0800 (PST) Subject: How to "kill" orphaned threads at program exit Message-ID: Hi, I know that it's not possible to "kill" threads but I'm wondering if does exist some workaround for my problem. I have a test suite which does a massive usage of threads. Sometimes happens that one test fails, the test suite keeps running until the end, and when it's finished the program hangs on and the only way to stop is to kill it manually. I noticed that, at the end of the program, I can call threading.enumerate() and see the pending thread objects: def test_main(): ... start_suite() print threading.enumerate() I was wondering if I can do anything with that. I took a look at test/test_support which has threading_setup() and threading_cleanup() functions. Could such functions be useful to me? Thanks in advance, --- Giampaolo http://code.google.com/p/pyftpdlib/ From carsten.kraus at gmail.com Tue Dec 23 08:44:32 2008 From: carsten.kraus at gmail.com (carsn) Date: Tue, 23 Dec 2008 05:44:32 -0800 (PST) Subject: PIL - font kerning Message-ID: Hey all, anybody know, if there?s a way to specify the kerning of a font, when you draw text with PIL? I?d like to achieve the same effect that you get, when you set a negative kerning in Gimp/Photshop - ie. reduce the spacing between glyphs. Can PIL do that or do I use another lib for that? Thx for any pointers & some nice xmas days to U all! carsten From gneuner2 at comcast.net Mon Dec 8 17:40:58 2008 From: gneuner2 at comcast.net (George Neuner) Date: Mon, 08 Dec 2008 17:40:58 -0500 Subject: Mathematica 7 compares to other languages References: <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> Message-ID: <8evqj4p342jvcma5saibf54thv7075r88g@4ax.com> On Sun, 7 Dec 2008 14:53:49 -0800 (PST), Xah Lee wrote: >The phenomenon of creating code that are inefficient is proportional >to the highlevelness or power of the lang. In general, the higher >level of the lang, the less possible it is actually to produce a code >that is as efficient as a lower level lang. This depends on whether someone has taken the time to create a high quality optimizing compiler. >For example, the level or power of lang can be roughly order as >this: > >assembly langs >C, pascal >C++, java, c# >unix shells >perl, python, ruby, php >lisp >Mathematica According to what "power" estimation? Assembly, C/C++, C#, Pascal, Java, Python, Ruby and Lisp are all Turing Complete. I don't know offhand whether Mathematica is also TC, but if it is then it is at most equally powerful. Grammatic complexity is not exactly orthogonal to expressive power, but it is mostly so. Lisp's SEXPRs are an existence proof that a Turing powerful language can have a very simple grammar. And while a 2D symbolic equation editor may be easier to use than spelling out the elements of an equation in a linear textual form, it is not in any real sense "more powerful". >the lower level the lang, the longer it consumes programer's time, but >faster the code runs. Higher level langs may or may not be crafted to >be as efficient. For example, code written in the level of langs such >as perl, python, ruby, will never run as fast as C, regardless what >expert a perler is. There is no language level reason that Perl could not run as fast as C ... it's just that no one has cared to implement it. >C code will never run as fast as assembler langs. For a large function with many variables and/or subcalls, a good C compiler will almost always beat an assembler programmer by sheer brute force - no matter how good the programmer is. I suspect the same is true for most HLLs that have good optimizing compilers. I've spent years doing hard real time programming and I am an expert in C and a number of assembly languages. It is (and has been for a long time) impractical to try to beat a good C compiler for a popular chip by writing from scratch in assembly. It's not just that it takes too long ... it's that most chips are simply too complex for a programmer to keep all the instruction interaction details straight in his/her head. Obviously results vary by programmer, but once a function grows beyond 100 or so instructions, the compiler starts to win consistently. By the time you've got 500 instructions (just a medium sized C function) it's virtually impossible to beat the compiler. In functional languages where individual functions tend to be much smaller, you'll still find very complex functions in the disassembly that arose from composition, aggressive inlining, generic specialization, inlined pattern matching, etc. Here an assembly programmer can quite often match the compiler for a particular function (because it is short), but overall will fail to match the compiler in composition. When maximum speed is necessary it's almost always best to start with an HLL and then hand optimize your optimizing compiler's output. Humans are quite often able to find additional optimizations in assembly code that they could not have written as well overall in the first place. George From xahlee at gmail.com Thu Dec 11 13:28:31 2008 From: xahlee at gmail.com (Xah Lee) Date: Thu, 11 Dec 2008 10:28:31 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <5ebe5a7d-cbdf-4d66-a816-a7d2a0a273c9@40g2000prx.googlegroups.com> Message-ID: <0434d1c7-809a-45bf-b244-d7f79aa37746@s9g2000prm.googlegroups.com> On Dec 11, 12:32?am, Gerard flanagan wrote: > Xah Lee wrote: > > On Dec 10, 2:47 pm, John W Kennedy wrote: > >> Xah Lee wrote: > >>> In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, > >>> you'll have 50 or hundreds lines. > [...] > > > Thanks to various replies. > > > I've now gather code solutions in ruby, python, C, Java, here: > > > ? A Example of Mathematica's Expressiveness > > ?http://xahlee.org/UnixResource_dir/writ/Mathematica_expressiveness.html > > > now lacking is perl, elisp, which i can do well in a condensed way. > > It'd be interesting also to have javascript... > > mmm, stone soup... > > javascript: > > var map = function(fn, a) { > ? ? ?var b = new Array(a.length); > ? ? ?for (i = 0; i < a.length; i++) { > ? ? ? ? ?b[i] = fn(a[i]); > ? ? ?} > ? ? ?return b > > }; > > var reduce = function(fn, a, init) { > ? ? ?var s = init; > ? ? ?for (i = 0; i < a.length; i++) { > ? ? ? ? ?s = fn(s, a[i]); > ? ? ?} > ? ? ?return s > > }; > > var sum = function(a) { > ? ? ?return reduce(function(x, y) { return x + y }, a, 0.0) > > }; > > var norm = function(a) { > ? ? ?var pow = Math.pow; > ? ? ?return Math.sqrt(sum(map(function(x) { return pow(x, 2) }, a))) > > }; > > var Unit = function(a) { > ? ? ?var N = norm(a); > ? ? ?return map(function(x) { return x/N }, a) > > }; thats about 15 lines. I'm pretty sure JavaScript doesn't need that many? Xah ? http://xahlee.org/ ? From pavlovevidence at gmail.com Mon Dec 22 15:10:31 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 22 Dec 2008 12:10:31 -0800 (PST) Subject: I always wonder ... References: Message-ID: On Dec 22, 11:53?am, s... at pobox.com wrote: > ... shouldn't people who spend all their time trolling be doing something > else: studying, working, writing patches which solve the problems they > perceive to exist in the troll subject? ?Is there some online troll game > running where the players earn points for generating responses to their > posts? ...shouldn't poeple who spend all their time following up to trolls, or starting new threads about trolls, being doing something else? Seriously, I participated briefly in the that thread when r still had benefit of the doubt over whether he had any credibility, but now there is no doubt that he none at all, so he's not worth replying to, so I don't. I suggest everyone else does likewise and ignores the fool. If you have to followup, at least keep your reply to something short and witty, like, "Go away, troll". Carl Banks From nospam at nospam.com Tue Dec 16 09:41:38 2008 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 16 Dec 2008 15:41:38 +0100 Subject: [cookielib] How to add cookies myself? Message-ID: <50ffk45borjjdg352t0s4lga2c26vr32uq@4ax.com> Hello I'm using urllib and urlib to download data from a web server that requires cookies. The issue I'm having, is the server uses JavaScript in the response to insert new cookies and send them with the next query, so I need to manually add a couple of cookies in the CookieJar, but I don't know how to do this and Google didn't return examples: ========= import urllib import urllib2 import cookielib headers = {'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' } cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) url = "http://www.acme.com/index.php" req = urllib2.Request(url, None, headers) response = urllib2.urlopen(req).read() print "Fetched cookies:" for index, cookie in enumerate(cj): print index, ' : ', cookie """ How to Add manually? crm_cookieEnabled=1 ctr=1 """ ========= Thanks for any tip. From kw at codebykevin.com Thu Dec 11 20:20:08 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 11 Dec 2008 20:20:08 -0500 Subject: Moving to subprocess from os.popen--pipe closes prematurely Message-ID: Hello, I'm trying to move from os.popen to using subprocess, and I'm having trouble with the pipe suddenly closing. My old code looked something like this: #build and format a list of all packages def getAllPackages(self): self.masterlist=[] for self.catname in self.catlist: time.sleep(.3) self.getpackages = os.popen('%s list --section=%s' % (self.finkpath, self.catname), 'r', os.O_NONBLOCK) for line in self.getpackages: newline = line.split('\t') rawcat = newline[0] if rawcat == '(i)': firstcat=rawcat.replace('(i)', 'outdated') elif rawcat == ' i ': firstcat=rawcat.replace('i', 'current') elif rawcat == ' p ': firstcat=rawcat.replace('p', 'provided') else: firstcat = rawcat self.packagelist = (firstcat, newline[1], newline[2], self.catname, newline[3].strip('\n')) self.masterlist.append(self.packagelist) Using the time.sleep function and adding the os.O_NONBLOCK to the os.popen call let the data stream come through uninterrupted. Here is the comparable code using subprocess: def getAllPackages(self): self.masterlist=[] self.showProgress() self.status.set('Getting all packages') self.update() for self.catname in self.catlist: self.update() self.status.set('Getting all packages by category: %s' % self.catname) self.getpackages = Popen('%s list --section=%s' % (self.finkpath, self.catname), shell=True, bufsize=0, stdout=PIPE).stdout time.sleep(5) fcntl.fcntl(self.getpackages, fcntl.F_SETFL, os.O_NONBLOCK) print "getting %s" % self.catname self.update() for line in self.getpackages: print line time.sleep(.1) self.update() newline = line.split('\t') rawcat = newline[0] if rawcat == '(i)': firstcat=rawcat.replace('(i)', 'outdated') elif rawcat == ' i ': firstcat=rawcat.replace('i', 'current') elif rawcat == ' p ': firstcat=rawcat.replace('p', 'provided') else: firstcat = rawcat self.packagelist = (firstcat, newline[1], newline[2], self.catname, newline[3].strip('\n')) I am using the fcntl call to set the pipe to nonblocking mode, and am trying to time.sleep to give the buffer time to get some data. However, this code crashes with the error "IOError: [Errno 35] Resource temporarily unavailable." Any advice to get the subprocess bits working so that the buffer does not close prematurely would be appreciated. Thank you, Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com From dfnsonfsduifb at gmx.de Sat Dec 6 11:43:13 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Sat, 06 Dec 2008 17:43:13 +0100 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: References: <5u8o06xbqf.ln2@joeserver.homelan.net> Message-ID: <1mmq06x4g6.ln2@joeserver.homelan.net> John Machin schrieb: > On Dec 6, 5:36 am, Johannes Bauer wrote: >> So UTF-16 has an explicit EOF marker within the text? I cannot find one >> in original file, only some kind of starting sequence I suppose >> (0xfeff). The last characters of the file are 0x00 0x0d 0x00 0x0a, >> simple \r\n line ending. > > Sorry, *WRONG*. It ends in 00 0d 00 0a 00. The file is 1559 bytes > long, an ODD number, which shouldn't happen with utf16. The file is > stuffed. Python 3.0 has a bug; it should give a meaningful error > message. Yes, you are right. I fixed the file, yet another error pops up (http://www.file-upload.net/download-1299688/2008_12_05_Handy_Backup.txt.html): Traceback (most recent call last): File "./modify.py", line 12, in a = AddressBook("2008_12_05_Handy_Backup.txt") File "./modify.py", line 7, in __init__ line = f.readline() File "/usr/local/lib/python3.0/io.py", line 1807, in readline while self._read_chunk(): File "/usr/local/lib/python3.0/io.py", line 1556, in _read_chunk self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) File "/usr/local/lib/python3.0/io.py", line 1293, in decode output = self.decoder.decode(input, final=final) File "/usr/local/lib/python3.0/codecs.py", line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) File "/usr/local/lib/python3.0/encodings/utf_16.py", line 69, in _buffer_decode return self.decoder(input, self.errors, final) UnicodeDecodeError: 'utf16' codec can't decode byte 0x0a in position 0: truncated data File size is 1630 bytes - so this clearly cannot be. Regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From inyeol.lee at gmail.com Mon Dec 8 02:06:09 2008 From: inyeol.lee at gmail.com (inyeol.lee at gmail.com) Date: Sun, 7 Dec 2008 23:06:09 -0800 (PST) Subject: tabs and spaces in py3k References: <774909e2-b248-4251-bbba-deb309e72714@x38g2000yqj.googlegroups.com> Message-ID: On Dec 7, 8:51 pm, ru... at yahoo.com wrote: > The following code works under 2.6 > ---- > def foo(): > a = 1 > <.tab..>b = 1 > ---- > but results in a TabError in Python 3k > > File "x.py", line 3 > b = 3 > ^ > TabError: inconsistent use of tabs and spaces in indentation > > The py3k docs say the same thing as the 2.6 docs, > namely that tabs are expanded to spaces prior to > determining the line's indentation. (Language > Ref, Lex Anal, Line Struct, Indentation) > (I wish someone would put the section numbers > back in the docs.) No mention of this change > (that I noticed) in What's New or NEWS.txt. > > Do the Py3k docs need correction? -tt option in python 2.x is now default in python 3.0. Apparently it got slipped from any documentation, including what's new. --Inyeol From nick at craig-wood.com Mon Dec 1 10:30:44 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 01 Dec 2008 09:30:44 -0600 Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> Message-ID: Slaunger wrote: > Slaunger wrote: > > > > class PayloadOnDemand(object): > > ? ? """ > > ? ? Behaves as a PayloadInstant object, but instantiation is faster > > ? ? as only the position of the payload in the file is stored > > initially in the object. > > ? ? Only when acessing the initially non-existing data attribute > > ? ? are the data actually read and the attribure created and bound to > > the instance. > > ? ? This will actually be a little slower than in PayloadInstant as > > the correct file position > > ? ? has to be seeked out first. > > ? ? On later calls the object has as efficient attribute access as > > PayloadInstant > > ? ? """ > > > > ? ? @classmethod > > ? ? def read_from_file(cls, f, size): > > ? ? ? ? pos = f.tell() > > ? ? ? ? f.seek(pos + size) #Skip to end of payload > > ? ? ? ? return cls(pos) > > Extend with ref to file instead: > return cls(f, pos) > > > > ? ? # I probably need some __getattr__ or __getattribute__ magic > > # there...?? > > To answer my own rethorical question I guess I should do something > like this > > def __getattr__(self, attr_name): > """ > Only called if attr_name is not in the __dict__ for the > instance > """ > if attr_name == 'data': > self.__dict__[attr_name] = read_data(self.f, > self.file_position) > > > > > ? ? def __init__(self, a_file_position): > > ? ? ? ? self.file_position = a_file_position > > > and then I need to also store a reference to the file in the > constructor... > > def __init__(self, a_file, a_file_position): > self.f = a_file > self.file_position = a_file_position > > Have I understood correctly how to to it the on demand way? I wouldn't use __getattr__ unless you've got lots of attributes to overload. __getattr__ is a recipe for getting yourself into trouble in my experience ;-) Just do it like this... class PayloadOnDemand(object): def __init__(self, a_file, a_file_position): self._data = None self.f = a_file self.file_position = a_file_position @property def data(self): if self._data is None: self._data = self.really_read_the_data() return self._data then you'll have a .data attribute which when you read it for the first time it will populate itself. If None is a valid value for data then make a sentinel, eg class PayloadOnDemand(object): sentinel = object() def __init__(self, a_file, a_file_position): self._data = self.sentinel self.f = a_file self.file_position = a_file_position @property def data(self): if self._data is self.sentinel: self._data = self.really_read_the_data() return self._data -- Nick Craig-Wood -- http://www.craig-wood.com/nick From martin at v.loewis.de Sun Dec 14 16:13:01 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 14 Dec 2008 22:13:01 +0100 Subject: Python 3.0 crashes displaying Unicode at interactive prompt In-Reply-To: References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> <49443531.5050304@v.loewis.de> <49448FC2.6030306@v.loewis.de> Message-ID: <494576DD.1050505@v.loewis.de> > But shouldn't the production of an object's representation via repr be > a "safe" operation? It's a trade-off. It should also be legible. Regards, Martin From __peter__ at web.de Wed Dec 10 04:29:24 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 10 Dec 2008 10:29:24 +0100 Subject: filter iterable based on predicate take from another iterable References: Message-ID: bernhard.voigt at gmail.com wrote: > is there is a neat way to select items from an iterable based on > predicates stored in another iterable without zipping? I can do > something like this: > > import itertools > foo = range(10) > # select even numbers > bar = map(lambda i: i%2, foo) > foobarselected = itertools.ifilterfalse(lambda t: t[0], itertools.izip > (bar,foo)) > # for simplicity I want to work with the single item list, not the > zipped one > fooselected = list(t[1] for t in foobarselected) > > However, it would be nice to have a function combining the last two > instructions. Something like > itertools.ifilterother(bar, foo) -> yield iterator with items from foo > where bar is true I think it's a good approach to keep the number of primitives low. I find the list comprehension combined with izip() quite readable: [v for f, v in izip(bar, foo) if not f(v)] Peter From stefan_ml at behnel.de Fri Dec 12 10:06:39 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 12 Dec 2008 16:06:39 +0100 Subject: Python is slow In-Reply-To: <0c3e89f2-b67c-4da5-bd33-87c98ee48812@z28g2000prd.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> <49427875$0$30229$9b4e6d93@newsspool1.arcor-online.net> <0c3e89f2-b67c-4da5-bd33-87c98ee48812@z28g2000prd.googlegroups.com> Message-ID: <49427dff$0$30223$9b4e6d93@newsspool1.arcor-online.net> sturlamolden wrote: > How is the numpy support in Cython going? It was supposed to know > about ndarrays natively. It does. > I.e. not treat them as Python objects, but > rather as known C structs. That way an operation like arr[n] would not > result in a callback to Python, but translate directly to fast pointer > arithmetics. http://docs.cython.org/docs/numpy_tutorial.html Stefan From michele.simionato at gmail.com Tue Dec 2 01:23:55 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 1 Dec 2008 22:23:55 -0800 (PST) Subject: What about a decorator module version 3.0? References: <7504ac87-4e4e-447f-a02c-f9db3f932a57@s20g2000yqh.googlegroups.com> Message-ID: <50b08bf6-550a-4033-92d8-0d8a067aae89@j38g2000yqa.googlegroups.com> On Dec 1, 9:18?pm, Terry Reedy wrote: > > Release a final 2.x version with whatever internal changes but with > external api unchanged or at least backward compatible. ?Mark items to > be deleted as deprecated. ?Keep that available indefinately. > > Then release a 3.0 version with Py3.0 support and deprecated items deleted. Uhm ... I don't like that. I want the 2.x versions to be fully compatible, without any annoying warning. The warnings will be in 3.0 and the functionality will be removed in 3.1. BTW, I have uploaded versions 2.3.2 on PyPI and it is intended to be the last version of the 2.x series. From bsk16 at case.edu Mon Dec 8 12:21:08 2008 From: bsk16 at case.edu (Ben Kaplan) Date: Mon, 8 Dec 2008 12:21:08 -0500 Subject: Guido's new method definition idea In-Reply-To: <79139d04-bd26-4f36-b8c9-19554e7d4e95@e18g2000yqo.googlegroups.com> References: <014a071a$0$20670$c3e8da3@news.astraweb.com> <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> <79139d04-bd26-4f36-b8c9-19554e7d4e95@e18g2000yqo.googlegroups.com> Message-ID: On Dec 8, 2008, at 11:59 AM, anthony.tolle at gmail.com wrote: > On Dec 6, 4:15 pm, Carl Banks wrote: >> On Dec 6, 12:47 am, "Patrick Mullen" wrote: >> >>> Could I do something like this: >> >>> def a.add(b): return a+b >> >>> Outside of a class? Of course then that makes you think you could >>> do >>> 5.add(6) or something craaaazy like that. (I mean, you can do >>> (5).__add__(6) but that's something else entirely) >> >> I'd be inclined to think that this defines an instancemethod on an >> existing object a. In other word, I'd read the following two lines >> as >> more or less equivalent. >> >> def a.add(b): return a+b >> >> a.add = lambda b: a+b >> >> Just as the following are equivalent: >> >> def foo(): return bar >> >> foo = lambda: bar >> >> I had been -0 on this, but now I think I'm -1. > > This brings up another question, what would one use when referencing > method names inside the class definition?: > > class C: > def self.method(arg): > self.value = arg > def self.othermethod(arg): > self.value = arg > # do this? > funcs = (self.method, self.othermethod) > # or this? > funcs = (method, othermethod) > > On another related note, I would be interested in seeing this syntax > adopted for a different purpose... > > Normally, if I'm defining a nested function that needs to be stored as > an object attribute, I have to use a dummy name, like the following: > > class C: > def createfunc(self, arg): > def _dummy(arg): > return arg + 1 > self.func = _dummy > > It would be nice to be able to do the following instead: > > class C: > def createfunc(self): > def self.func(arg): > return arg + 1 > > Or, after the class definition is done, to extend it dynamically: > > def C.method(self, arg): > self.value = arg > > ...which would be the equivalent of the following: > > def method(self, arg): > self.value = arg > C.method = method > > Since functions are first-class objects, it seems perfectly reasonable > to me. > -- > http://mail.python.org/mailman/listinfo/python-list I agree, this would be much nicer and would not require any special cases. I'm not convinced that this is needed, but at least this won't confuse newbies as much. From jason.scheirer at gmail.com Thu Dec 11 18:57:17 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Thu, 11 Dec 2008 15:57:17 -0800 (PST) Subject: newbie question: if var1 == var2: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> Message-ID: <44aa0191-e374-4bf0-b039-d05cfa996b1d@p2g2000prn.googlegroups.com> On Dec 11, 3:49?pm, John Machin wrote: > On Dec 12, 10:31?am, "Rhodri James" > wrote: > > > > > On Thu, 11 Dec 2008 19:49:23 -0000, Steve Holden ? > > wrote: > > > > Kirk Strauser wrote: > > >> At 2008-11-29T04:02:11Z, Mel writes: > > > >>> You could try > > > >>> for item in fname: > > >>> ? ? item = item.strip() > > > >> This is one case where I really miss Perl's "chomp" function. ?It ? > > >> removes a > > >> trailing newline and nothing else, so you don't have to worry about ? > > >> losing > > >> leading or trailing spaces if those are important to you. > > > > ... and it's so hard to write > > > > ? ? ?item = item[:-1] > > > Tsk. ?That would be "chop". ?"chomp" would be > > > ? ? ?if item[-1] == '\n': > > ? ? ? ? ?item = item[:-1] > > Better: > if item and item[-1] == '\n': > ? ? return item[:-1] > return item Best: return item \ if not (item and item.endswith('\n')) \ else item[:-1] Though really you should be using item.rstrip() From python.list at tim.thechases.com Tue Dec 16 08:42:59 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 16 Dec 2008 07:42:59 -0600 Subject: String slices work only for first string character ? In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF60249410A@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF60249410A@enbmail01.lsi.com> Message-ID: <4947B063.6030906@tim.thechases.com> > Can any one explain why the following string slice works only for the first character, but not for any other ? > > $ cat /tmp/tmp.py > #!/usr/bin/env python > > data = 'F0023209006-0101' > print data > print "|"+data[0:1]+"|" > print "|"+data[1:1]+"|" > print "|"+data[2:1]+"|" > > $ python `cygpath -w /tmp/tmp.py` > F0023209006-0101 > |F| > || > || Slices are defined by [start_idx:end_idx] not [start_idx:length] so you want data[0:1] data[1:2] data[2:3] -tkc From dotancohen at gmail.com Thu Dec 4 15:43:26 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 4 Dec 2008 22:43:26 +0200 Subject: Mathematica 7 compares to other languages In-Reply-To: <20081219033030.559@gmail.com> References: <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <4b6c3304-2396-4d35-a06f-e5d693cbbb12@f13g2000yqj.googlegroups.com> <20081219033030.559@gmail.com> Message-ID: <880dece00812041243y26e01b6ud0151fa614473102@mail.gmail.com> 2008/12/4 Kaz Kylheku : > Really? I will trade you one Xah Lee for three Jon Harrops and I will even > Xah Lee is interesting because he brings up lots of good points. Also, the few times we've seen his skilz he has shown that he really knows how to code. I am willing to put up with his AI-bot posts, but I do wish that he'd trade his lolcats speak for proper (or the best that he could do) English. English (or another Latin language) is not my native language either, but if a dumbbell like me can grasp it then I'm sure Xah could too. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-??-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From geekmail at usenot.de Sun Dec 7 12:27:21 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sun, 7 Dec 2008 18:27:21 +0100 Subject: Guido's new method definition idea References: Message-ID: <20081207182721.4033466d@usenot.de> On Sat, 6 Dec 2008 23:21:04 -0800 (PST) Lie wrote: > I think we have to test this on newbies. [snip] > Now that's talking like a programmer! Ideas on how such a survey could be conducted? Anyone? > If this dead horse is revived because of that reason, then I'd go with > changing the error message to something that is less confusing to > newbies[1]. + googol > I remember being tripped with the (thinking that python > miscounted the number of argument) when I was new. This has the > advantage of backward compatibility and no syntax change, just less > misleading error message. > > [1] anything could work, but I like this one: (c is an instance of > class C) > if the code is: c.foo(...), Error: "TypeError: c.foo() takes exactly 3 > argument" > while if the code is: C.foo(...), Error: "C.foo() takes exactly 4 > arguments" > You can implement c.foo as a curried C.foo function, catch C.foo's > TypeError exception then reraise it as c.foo exception. I'm not sure that I'd find that less confusing. Because a c.foo() *does* take four arguments, not three. It's just that the first one is implicit (Right?). How about: "TypeError: c.foo() takes exactly 3 arguments in addition to the implicit instance reference." or "TypeError: c.foo() takes exactly 4 arguments (5 given, including the implicit instance reference)" ... or something less kludgy in that general direction. This would explain exactly what is wrong. /W -- My real email address is constructed by swapping the domain with the recipient (local part). From steve at holdenweb.com Thu Dec 11 22:42:24 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 11 Dec 2008 22:42:24 -0500 Subject: Rename of .mdb file -- lock In-Reply-To: <99fbe43e-9b30-4ed2-8355-29a21935e55a@n41g2000yqh.googlegroups.com> References: <4049f296-2a04-4eee-9f09-aa37a973a8cf@r40g2000yqj.googlegroups.com> <8792708a-51c9-4fa6-b39d-4808ed1ffaed@t39g2000prh.googlegroups.com> <99fbe43e-9b30-4ed2-8355-29a21935e55a@n41g2000yqh.googlegroups.com> Message-ID: noydb wrote: > On Dec 11, 9:38 pm, "gudonghua+pyt... at gmail.com" > wrote: [...] > > Thanks! That was simple enough. > > And... > ##os.rename(new91mdb, (os.path.join(output_dir, uChoice))) > os.rename(new91mdb, (os.path.join(output_dir, "C:\TEMP\test1.mdb"))) > > ... of those two lines, the top one worked. The reason the second one didn't work is because "\t" is the tab character. Look for "raw strings" in the documentation. r"C:\TEMP\test1.mdb" should work. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From cs at zip.com.au Mon Dec 29 18:24:08 2008 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 30 Dec 2008 10:24:08 +1100 Subject: flushing of print statements ending with comma In-Reply-To: <25783efa-fa57-49c8-b20a-7bdf6f7cb256@w1g2000prk.googlegroups.com> Message-ID: <20081229232408.GA24226@cskk.homeip.net> On 29Dec2008 11:11, Grebekel wrote: | I have recently noticed that print statements ending with a comma are | not immediately flushed. I will warn you that neither are the more common uncommaed print statements, except on a terminal. | [...] Example: | | print 'Take a walk, because this will take a while...', | i = 0 | while i < 10**10: | i += 1 | print "we're done!" | | | Here the first string is not printed until the second print statement. [...] | Using sys.std.flush after the print fixes this issue, but doing so | each time seems cumbersome and somewhat counterintuitive. | Is there some reasoning behind this behavior or is it a bug? It's correct behaviour. The python print etc is layered on the C library stdio. A stdio stream can be buffered in three standard ways: unbuffered, line buffered and block buffered. On UNIX, on a terminal, stdout is normally line buffered: output is flushed when a newline is encoutered in the data, and this is pleasing to humans. Conversely, is stdout is _not_ attached to a terminal it will be block buffered by default; output is only flushed when the buffer is filled. This is much more _efficient_ in terms of I/O and program activity. By contrast, again by default, stderr is normally unbuffered. Being reserved for error messages, immediate output (before your program explodes:-) is considered more important than system efficiency. So you should sys.stdout.flush() if you want data output right now. For many purposes it is better to let the default behaviour obtain. Also, I suugest that progress reporting such as your be written to stderr anyway. It will appear in a timely fashion, and will also thus not pollute the output stream. Consider: your-program >datafile or your-program | process the output data... Sending your progress reports to stdout puts junk in the data stream. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Gentle suggestions being those which are written on rocks of less than 5lbs. - Tracy Nelson in comp.lang.c From list at qtrac.plus.com Fri Dec 19 11:07:00 2008 From: list at qtrac.plus.com (Mark Summerfield) Date: Fri, 19 Dec 2008 08:07:00 -0800 (PST) Subject: ANN: New Book: Programming in Python 3 References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> Message-ID: <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> Just a follow-up to say that the book has now been published in the U.S. It is now in stock at InformIT, and should reach other stores, e.g., Amazon, in a week or so. Also, the introduction, the first few pages of the first chapter, the whole of chapter 12 (regular expressions), and the index are now available for free download in a PDF from here: http://www.informit.com/store/product.aspx?isbn=0137129297 Oh, and I wrote a short article on descriptors which is here: http://www.informit.com/articles/article.aspx?p=1309289 (The third example is very similar to an example from Chapter 8 and shows a validation technique that combines class decorators with descriptors.) On 4 Dec, 15:02, Mark Summerfield wrote: > Now that Python 3 final has been released I thought it would be a good time > to mention that there's a new book to go with it: > > "Programming in Python 3: > A Complete Introduction to the Python Language" > ISBN 0137129297http://www.qtrac.eu/py3book.html > > I've been working on this for more than a year, testing the examples > against every Python 3 alpha and beta, and against the final release (using > Python's unit test and doctest modules of course:). > > The book has just gone into production and should be available in print at > the end of this month in the U.S., and a month or two later elsewhere. The > book's web page has links to a draft of the introduction and to safari > books online where you can read extracts. > > The book is aimed at a wide audience, but assumes some programming > experience (not necessarily Python, not necessarily object-oriented). It > teaches solid procedural style programming, then builds on that to teach > solid object-oriented programming, and then goes on to more advanced topics > (e.g., including a nice way to create validated attributes by combining > class decorators with descriptors). But even newcomers to Python 3 should > be able to write useful (although small and basic) programs after reading > chapter 1, and then go on to create larger and more sophisticated programs > as they work through the chapters. > > -- > Mark Summerfield, Qtrac Ltd,www.qtrac.eu From steve at holdenweb.com Fri Dec 12 11:00:38 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Dec 2008 11:00:38 -0500 Subject: concept of creating structures in python In-Reply-To: References: Message-ID: Joe Strout wrote: > On Dec 11, 2008, at 10:52 PM, navneet khanna wrote: > >> I want to create a structure within a structure i.e. nested structures >> in python. >> I tried with everything but its not working. >> my code is like this: >> >> class L(Structure): >> >> def __init__(self,Name='ND',Addr=0,ds_obj = D()): > > Change the default value of ds_obj here to None. Otherwise, you will > certainly confuse yourself (there would be just one default object > shared among all instances). > >> self.Name = Name >> self.Addr = Addr >> self.ds_obj = ds_obj >> >> >> class D(Structure): >> >> def __init__(self,dataName='ND',index = 0,ele_obj=E()): >> >> self.dataName = dataName >> self.index = index >> self.ele_obj = ele_obj > > Same thing here with ele_obj -- have it default to None to save yourself > grief. > > Otherwise, these look fine. > Joe missed a piece out here. If you change the signature of your D.__init__() to read def __init__(self, dataName='ND', index = 0, ele_obj=None): then you need to insert the following code at the top of the method: if ele_obj is None: ele_obj = E() [You'll note, by the way, I have inserted standard spacing into the "def" statement to enhance readbility: you should use spaces after all commas if you want your code to be easy for other programmers to read). This avoids a common beginner pitfall. Your original code would create a single E object that would be used as the defauilt for all Ds created without explicitly passing an ele_obj. Then if that object were changed (mutated) in some way, all such E's would see a change had been made to their ele_obj. With the extra code, a different ele_obj is created for each E that isn't passed one. The same argument applies to L.__init__()'s ds_obj argument. > >> these are two structures. I want to refer D structure in L one and use >> it. I want to access the value of D structure like L.D.index = 0. > [...] regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From musiccomposition at gmail.com Thu Dec 4 21:23:01 2008 From: musiccomposition at gmail.com (Benjamin) Date: Thu, 4 Dec 2008 18:23:01 -0800 (PST) Subject: Python 3.0 C API migration tools, or docs? References: <008877d2-8705-48a6-bb09-6c31c6b77970@p2g2000prf.googlegroups.com> Message-ID: <1a5cf43f-5802-4c69-9226-18cbc6256c0c@k19g2000yqg.googlegroups.com> On Dec 4, 7:45?pm, illume wrote: > Hi, > > are there migration tools for C API migration to python 3? > > I'm sure there must be some code somewhere to help change stuff over > right? > > I don't see any docs for migrating code from 2.x to 3.x either:http://docs.python.org/3.0/c-api/index.html At the moment all that is officially available is this rather incomplete howto: http://docs.python.org/howto/cporting.html > > Help needed with this! > > cheers, From skip at pobox.com Sat Dec 27 15:22:09 2008 From: skip at pobox.com (skip at pobox.com) Date: Sat, 27 Dec 2008 14:22:09 -0600 Subject: [2.4.4] creating a datetime.datetime from an XML xs:dateTime In-Reply-To: <5fa6c12e0812271208x4baccaedk262e51becb6e2076@mail.gmail.com> References: <5fa6c12e0812271208x4baccaedk262e51becb6e2076@mail.gmail.com> Message-ID: <18774.36465.346262.883182@montanaro-dyndns-org.local> martin> subject says it all. I'd like to create a python martin> datetime.datetime from an xs:string[1] ... martin> so I'd rather like to find some method (hopefully within the martin> standard lib) that had more peer review than only me :). Not in the standard lib, but you might want to check out the dateutil package. Its dateutil.parser module does an excellent job parsing a wide range of time formats. It's a bit weak in the timezone area though. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From rogerb at rogerbinns.com Fri Dec 19 20:54:22 2008 From: rogerb at rogerbinns.com (Roger Binns) Date: Fri, 19 Dec 2008 17:54:22 -0800 Subject: Jarow-Winkler algorithm: Measuring similarity between strings In-Reply-To: <4f351b3b-4da7-4fee-a1ac-c42179d430f5@s9g2000prm.googlegroups.com> References: <4f351b3b-4da7-4fee-a1ac-c42179d430f5@s9g2000prm.googlegroups.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 ?yvind wrote: > Based on examples and formulas from http://en.wikipedia.org/wiki/Jaro-Winkler. > Useful for measuring similarity between two strings. For example if > you want to detect that the user did a typo. Jaro-Winkler is best when dealing with names (Winkler works for the US census). There are pure Python and C accelerated implementations at http://bitpim.svn.sourceforge.net/viewvc/bitpim/trunk/bitpim/src/native/strings/ If you are concerned about typos then taking into account the keyboard layout will help. For example for a user with a US keyboard, the 'a' or 'd' keys would be a common typo for 's'. Also consider Levenshtein distance: http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Levenshtein_distance Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAklMUEkACgkQmOOfHg372QRTlQCfUoebzX2HRbQ4wLVZ6yRFMHd7 9yMAnjovqefVuQenX0zpHwn/rvv9FLe+ =bACc -----END PGP SIGNATURE----- From nikeshoe.nike30 at gmail.com Fri Dec 19 11:00:14 2008 From: nikeshoe.nike30 at gmail.com (nikeshoe.nike30 at gmail.com) Date: Fri, 19 Dec 2008 08:00:14 -0800 (PST) Subject: HTTP://WWW.STREETCANDY.ORG Message-ID: <8512b63e-02c4-4510-b955-5c9837f25165@d42g2000prb.googlegroups.com> Get Nike Shoes at Super Cheap Prices Discount Nike air jordans (www.streetcandy.org) Discount Nike Air Max 90 Sneakers (www.streetcandy.org) Discount Nike Air Max 91 Supplier (www.streetcandy.org) Discount Nike Air Max 95 Shoes Supplier (www.streetcandy.org) Discount Nike Air Max 97 Trainers (www.streetcandy.org) Discount Nike Air Max 2003 Wholesale (www.streetcandy.org) Discount Nike Air Max 2004 Shoes Wholesale (www.streetcandy.org) Discount Nike Air Max 2005 Shop (www.streetcandy.org) Discount Nike Air Max 2006 Shoes Shop (www.streetcandy.org) Discount Nike Air Max 360 Catalogs (www.streetcandy.orgm) Discount Nike Air Max Ltd Shoes Catalogs (www.streetcandy.org) Discount Nike Air Max Tn Men's Shoes (www.streetcandy.org) Discount Nike Air Max Tn 2 Women's Shoes (www.streetcandy.org) Discount Nike Air Max Tn 3 Customize (www.streetcandy.org) Discount Nike Air Max Tn 4 Shoes Customize ( www.streetcandy.orgm) Discount Nike Air Max Tn 6 Supply (www.streetcandy.org) Discount Nike Shox NZ Shoes Supply (www.streetcandy.org) Discount Nike Shox OZ Sale (www.streetcandy.org) Discount Nike Shox TL Store (www.streetcandy.org) Discount Nike Shox TL 2 Shoes Store (www.streetcandy.org) Discount Nike Shox TL 3 Distributor (www.streetcandy.org) Discount Nike Shox Bmw Shoes Distributor (www.streetcandy.org) Discount Nike Shox Elite Shoes Manufacturer (www.streetcandy.org) Discount Nike Shox Monster Manufacturer (www.streetcandy.org) Discount Nike Shox R4 Running Shoes (www.streetcandy.org) Discount Nike Shox R5 Mens Shoes (www.streetcandy.org) Discount Nike Shox Ride Womens Shoes (www.streetcandy.org) Discount Nike Shox Rival Shoes Wholesaler (www.streetcandy.org) Discount Nike Shox Energia Wholesaler (www.streetcandy.org) Discount Nike Shox LV Sneaker (www.streetcandy.org) Discount Nike Shox Turbo Suppliers (www.streetcandy.org) Discount Nike Shox Classic Shoes Suppliers (www.streetcandy.org) Discount Nike Shox Dendara Trainer (www.streetcandy.org) Discount Nike Air Jordan 1 Seller (www.streetcandy.org) Discount Nike Air Jordan 2 Shoes Seller (www.streetcandy.org) Discount Nike Air Jordan 3 Collection (www.streetcandy.org Discount Nike Air Jordan 4 Shoes Collection (www.streetcandy.org) Discount Nike Air Jordan 5 Chaussure Shoes (www.streetcandy.org) Discount Nike Air Jordan 6 Catalog (www.streetcandy.org) Discount Nike Air Jordan 7 Shoes Catalog (www.streetcandy.org) Discount Nike Air Jordan 8 Customized (www.streetcandy.org) Discount Nike Air Jordan 9 Shoes Customized (www.streetcandy.org) Discount Nike Air Jordan 10 Wholesalers (www.streetcandy.org) Discount Nike Jordan 11 Shoes Wholesalers (www.streetcandy.org) Discount Nike Air Jordan 12 Factory (www.streetcandy.org) Discount Nike Air Jordan 13 Shoes Factory (www.streetcandy.org) Discount Nike Air Jordan 14 Shoes Sell (www.streetcandy.org) Discount Nike Air Jordan 16 Exporter (www.streetcandy.org) Discount Nike Air Jordan 17 Shoes Exporter (www.streetcandy.org) Discount Nike Air Jordan 18 Offer (www.streetcandy.org) Discount Nike Air Jordan 19 Shoes Offer (www.streetcandy.org) Discount Nike Air Jordan 20 Manufacture (www.streetcandy.org) Discount Nike Jordan 21 Shoes Manufacture (www.streetcandy.org) From huwdjones at gmail.com Tue Dec 16 07:14:56 2008 From: huwdjones at gmail.com (huw_at1) Date: Tue, 16 Dec 2008 04:14:56 -0800 (PST) Subject: cx_Oracle issues References: <5b2dad81-2750-4347-8079-6ab31321d579@s1g2000prg.googlegroups.com> <9142a8f1-7f76-4fc0-9ca1-c9dec310f2ce@r37g2000prr.googlegroups.com> <9f436c9e-2319-499c-a306-d255996372fc@e22g2000vbe.googlegroups.com> Message-ID: <844152f0-e946-40f1-8969-4ee5031c68f8@35g2000pry.googlegroups.com> On Dec 15, 12:59?pm, "ron.re... at gmail.com" wrote: > On Dec 15, 2:44?am, huw_at1 wrote: > > > > > On Dec 11, 5:34?pm, "ron.re... at gmail.com" wrote: > > > > On Dec 10, 9:48?am, huw_at1 wrote: > > > > > Hey all. When usingcx_Oracleto run a procedure like: > > > > > cursor.execute("select (obj.function(value)) from table where > > > > id=blah") > > > > > I am getting the following error: > > > > > ORA-06502: PL/SQL: numeric or value error: character string buffer too > > > > small ORA-06512: at line 1 > > > > > Looking at cursor.description I get: > > > > > [('(obj.function(value))', , 4000, 4000, 0, > > > > 0, 1)] > > > > > Any tips - i have never seen this error before but am guessing that > > > > the value being returned is too big for the buffer size set for the > > > > cursor. the procedure fetches data from a LOB. > > > > > Any suggestions/confirmations? > > > > > Many thanks > > > > This error is a problem with the PL/SQL, notcx_Oracle. ?You need to > > > debug obj.function to see what kind of data is being accessed and then > > > a data analysis of that data to understand why this error occurs. ?I > > > can tell you the function is most likely expecting characters from a > > > column that are numeric [0 .. 9] and is getting alpha characters. > > > > -- > > > Ron Reidy > > > Sr. Oracle DBA > > > Hi thanks for the responses. Unfortunately the procedure in question > > is from a third party vendor so I can't really debug it so I'd say I > > was fairly stumped. Just out of interest how do you increase the > > output buffer size withcx_Oracle? > > > Many thanks- Hide quoted text - > > > - Show quoted text - > > Hi, > > Sure you can. ?You can see the PL/SQL source from the ditionary view > ALL_SOURCE: > select text from all_source where name = 'NAME_OF_FUNCTION'; > > From there, reverse engineeer which table(s) and column(s) are being > accesses and do the data analysis. > > -- > Ron Reidy Hi all, So I tried Rons query but unfortunately I got 0 records returned. However I can confirm that running the select query from a client does indeed generate the same error. Is there anything else I could try? Otherwise I'll just get in touch with the vendor I guess. From rdmurray at bitdance.com Tue Dec 9 22:15:51 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Tue, 9 Dec 2008 22:15:51 -0500 (EST) Subject: How do I manually uninstall setuptools (installed by egg)? In-Reply-To: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> Message-ID: On Tue, 9 Dec 2008 at 18:49, excord80 at gmail.com wrote: > On Ubuntu, I accidentally manually installed setuptools > http://pypi.python.org/pypi/setuptools/0.6c9 (by running the .egg file > as a shell script via sudo), and now realize I should just be using > apt to take care of my system Python packages. I also installed one or > two packages using its ``easy_install``. > > Looks like it lives in ``/usr/lib/python2.5/site-packages``. > > How can I manually remove those packages installed using that > ``easy_install``, and then manually remove the setuptools package I > installed? rm -r /usr/lib/python2.5/site-packages/ Then find the .pth file (in the site-packages directory) that references the egg, and delete the line referencing the egg. Setuptools has no uninstall function, as far as I know. --RDM From dotancohen at gmail.com Wed Dec 31 05:43:06 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 31 Dec 2008 12:43:06 +0200 Subject: Easy-to-use Python GUI In-Reply-To: References: Message-ID: <880dece00812310243y1c02e6cete667e37964e354b3@mail.gmail.com> I have been following this thread with interest. Is there a way to build Qt apps with relative easy? I use KDE and would prefer the Qt toolkit for my GUI apps. Thanks. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-??-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From wuwei23 at gmail.com Mon Dec 1 20:09:26 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 1 Dec 2008 17:09:26 -0800 (PST) Subject: end of print = lower productivity ? References: Message-ID: <98407948-e24f-4a89-8604-148279620f84@k24g2000pri.googlegroups.com> On Dec 2, 5:12?am, Alan G Isaac wrote: > One obvious cost is that working at the > interpreter prompt is now slightly less > convenient. Not if you use IPython: IPython 0.8.1 -- An enhanced Interactive Python. ? -> Introduction to IPython's features. %magic -> Information about IPython's 'magic' % functions. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: def prnt(x): print x ...: In [2]: prnt "test" ------> prnt("test") test In [3]: prnt 1+1 ------> prnt(1+1) 2 > My preferred transition would have been to > retain the `print` statement but add a `printf` > function (i.e., the new `print` function). > Presumably many would find this a repulsive > redundancy and a needless maintenance headache. Not to mention the endless "Which should I use, print or print()?" questions this list would get. From brendandetracey at yahoo.com Fri Dec 12 10:36:24 2008 From: brendandetracey at yahoo.com (Brendan) Date: Fri, 12 Dec 2008 07:36:24 -0800 (PST) Subject: Reading online zip files - zipfile and zlib, wbits References: <21ba0ff5-7698-481a-851c-80b9ddcd5814@q26g2000prq.googlegroups.com> Message-ID: On Dec 12, 10:46?am, Brendan wrote: > On Dec 12, 10:25?am, Brendan wrote: > > > I am fooling around with accessing contents of zip files online. I > > download the tail end of the zip and use zipfile to get the zip > > central directory structure. I download the section of the zip file I > > need, directly read the zip file headers and use that information with > > zlib to uncompress the data. The files I am examining will always be > > compressed using deflate, with a wbits value of -15(minus for > > headerless data because I am unsure whether the zip file header is > > what zlib expects). > > > I can not find anywhere in the PK Zip Application notes (http://www.pkware.com/documents/casestudies/APPNOTE.TXT) how to > > determine the value I should uze for wbits with zlib.decompress. I > > have determined it is -15 from experimentation. Does anyone know the > > answer to this? > > Okay, I found part of the answer here in the zip app notes > [quote] > general purpose bit flag: (2 bytes) > > ? ? ? ? ? Bit 0: If set, indicates that the file is encrypted. > > ? ? ? ? ? (For Method 6 - Imploding) > ? ? ? ? ? Bit 1: If the compression method used was type 6, > ? ? ? ? ? ? ? ? ?Imploding, then this bit, if set, indicates > ? ? ? ? ? ? ? ? ?an 8K sliding dictionary was used. ?If clear, > ? ? ? ? ? ? ? ? ?then a 4K sliding dictionary was used. > ? ? ? ? ? Bit 2: If the compression method used was type 6, > ? ? ? ? ? ? ? ? ?Imploding, then this bit, if set, indicates > ? ? ? ? ? ? ? ? ?3 Shannon-Fano trees were used to encode the > ? ? ? ? ? ? ? ? ?sliding dictionary output. ?If clear, then 2 > ? ? ? ? ? ? ? ? ?Shannon-Fano trees were used. > > ? ? ? ? ? (For Methods 8 and 9 - Deflating) > ? ? ? ? ? Bit 2 ?Bit 1 > ? ? ? ? ? ? 0 ? ? ?0 ? ?Normal (-en) compression option was used. > ? ? ? ? ? ? 0 ? ? ?1 ? ?Maximum (-exx/-ex) compression option was > used. > ? ? ? ? ? ? 1 ? ? ?0 ? ?Fast (-ef) compression option was used. > ? ? ? ? ? ? 1 ? ? ?1 ? ?Super Fast (-es) compression option was used. > [/quote] > > Now I just don't understand Why Normal deflate corresponds to 15 > wbits, and why I have to use headerless for the data, i.e. wbits = -15. Seems the bit flags are not properly set, bit 2 should be 0 and bit 1 should be 1, to correspond to maximum compression i.e. wbit = 15. Still don't know why wbits has to be negative. From bdesth.quelquechose at free.quelquepart.fr Tue Dec 30 15:49:45 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 30 Dec 2008 21:49:45 +0100 Subject: SQL, lite lite lite In-Reply-To: <6rvgihF3je6sU1@mid.uni-berlin.de> References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> <4959204f$0$15020$426a74cc@news.free.fr> <6rvgihF3je6sU1@mid.uni-berlin.de> Message-ID: <495a9719$0$25469$426a74cc@news.free.fr> Gerhard H?ring a ?crit : > Bruno Desthuilliers wrote: >> Aaron Brady a ?crit : >>> Hi all, >>> >> (snip) >> > >>> I don't think relational data can be read and written very easily in >>> Python. >> >> Did you try SQLAlchemy or Django's ORM ? >> [...] > > Using an ORM when you don't grasp the relational model and/or the SQL > query language is futile. Yes, indeed. And ? Aaron's post was mostly about a better integration of the relational model in Python - which obviously requires some knowledge of the topic. From NIE_DZIALA at gazeta.pl Sun Dec 14 00:48:19 2008 From: NIE_DZIALA at gazeta.pl (Piotr Sobolewski) Date: Sun, 14 Dec 2008 06:48:19 +0100 Subject: the official way of printing unicode strings Message-ID: Hello, in Python (contrary to Perl, for instance) there is one way to do common tasks. Could somebody explain me what is the official python way of printing unicode strings? I tried to do this such way: s = u"Stanis?aw Lem" print u.encode('utf-8') This works, but is very cumbersome. Then I tried to do this that way: s = u"Stanis?aw Lem" print u This breaks when I redirect the output of my program to some file, like that: $ example.py > log Then I tried to do this that way: sys.stdout = codecs.getwriter("utf-8")(sys.__stdout__) s = u"Stanis?aw Lem" print u This works but is even more combersome. So, my question is: what is the official, recommended Python way? From benjamin.kaplan at case.edu Fri Dec 12 18:40:02 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 12 Dec 2008 18:40:02 -0500 Subject: os.lstat : proper way to do this In-Reply-To: References: Message-ID: On Fri, Dec 12, 2008 at 6:06 PM, wrote: > I'm converting from Perl to Python, so I'm learning the basics - > please be gentle! :) > > In Perl, I can lstat($file) whether $file exists or not: > lstat($file); > unless (-e _) { > print STDERR "$file: No such file or directory\n"; > } > unless (-l _) { > print STDERR "$file: Not a symbolic link\n"; > } > > The lstat() returns normally whether the file exists or not, and I > check for existence with the "-e" conditional. Then I go on and check > other modes. > > In Python,if I os.lstat(file) and file doesn't exist, I get an error > from within the module: > OSError: [Errno 2] No such file or directory: '/etc/xxx' > > I can check first with os.path.exists(file), but then I'm doing two > stat() type calls which is inefficient (especially when we're talking > thousands of files). > > I want to be able to do something like this: > mode = os.lstat(file)[ST_MODE] > if not mode: > print >> sys.stderr, file, ": No such file or directory" > if not S_ISLNK(mode): > print >> sys.stderr, file, ": Not a symbolic link" > > Of course, this isn't valid. How can I do this efficiently without > getting "no such file" error? > In Python, people usually follow the "Easier to Ask Forgiveness than Permission" philosophy. Rather than prevent an error from occurring, just let it happen and deal with if when it does. Wrap your call to os.lstat in a try/except block and just print your error message if the lstat call fails. -------------- next part -------------- An HTML attachment was scrubbed... URL: From manu3d at gmail.com Sat Dec 13 10:21:43 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Sat, 13 Dec 2008 07:21:43 -0800 (PST) Subject: Bidirectional Networking References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> Message-ID: <98a6c3cd-181c-43c9-805b-fb0689c69544@a26g2000prf.googlegroups.com> Hey Bryan, thank you for your reply! On Dec 13, 3:51?am, Bryan Olson wrote: > > Is it possible then to establish both a server and a client in the > > same application? > > Possible, and not all that hard to program, but there's a gotcha. > Firewalls, including home routers and software firewalls, typically > default to disallowing connections in the 'wrong' direction. If the > client initiates all connections, you avoid a world of hassles. Ah yes, I can see that. Uhm. I have absolutely no idea right now how a firewall works from a programming point of view and what happens in normal "residential" circumstances. I.e. it's clear that firewalls are configured to allow http traffic because I can browse the internet. Is that done leaving a specific port open? Or does the browser request the firewall to open a specific port for it and the firewall trust the browser to handle safely anything that comes through? I.e. in the case of the code in this thread, would it be the responsibility of the application to tunnel through the firewall and listen for connections or would it be the responsibility of the user to configure the firewall so that the application can receive a connection? Thanks for your help! Manu From bruno.42.desthuilliers at websiteburo.invalid Thu Dec 4 09:54:26 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 04 Dec 2008 15:54:26 +0100 Subject: Python Runtime Method Call Binding In-Reply-To: References: Message-ID: <4937ef0e$0$27400$426a74cc@news.free.fr> k3xji a ?crit : > Hi, > > Is there a way to hook a function call in python? I know __getattr__ > is doing for variables, it is giving us a chance before a field is > initialized. Note that since the introduction of the "new-style" object model - that is, in Python 2.2 -, computed attributes are better handled with the descriptor protocol, and specially the general purpose 'property' class. The __getattr__ hook should only be used when you want to handle read access to an attribute that doesn't exist at all (ie : automatic delegation etc). Also note that a method is mostly a computed attribute (another application of the descriptor protocol FWIW)... > Do we have same functionality for methods? Which "functionality" ? What do you want to do ? automatically delegate method calls, or "wrap" method calls so you can ie log them or attach more behaviour ? > Example: > > class Foo(object): > def __call_method__(self, ...) # just pseudo > print 'A method is called in object...' > > f = Foo() > f.test_method() Ok, I guess this is the second case. The answer is "decorator". def log(func): def _logged(*args, **kw): print "func", func.__name__, " called with ", args, kw return func(*args, **kw) _logged.__name__ = "logged_%s" % func.__name__ _logged.__doc__ = func.__doc__ return _logged class Foo(object): @log def method(self, yadda=None): print "in Foo.method, yadda = ", yadda return yadda f = Foo() f.method() f.method(42) HTH From rhodri at wildebst.demon.co.uk Sat Dec 6 20:08:13 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Sun, 07 Dec 2008 01:08:13 -0000 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: On Sat, 06 Dec 2008 21:51:51 -0000, Daniel Fetchinson wrote: > Did you read the blog post? The advantage is having a less confusing > situation for newbies (confusing the number of arguments to a method > call). Experience suggests that newbies don't find this confusing, or at least not more than momentarily. I'm -0 on this at the moment. Maybe -0.5. I don't really like the potential for hideousness like @staticmethod def spam.alot(isa, silly, place): return silly + spam that's implied by making this a general feature of methods. -- Rhodri James *-* Wildebeeste Herder to the Masses From barry at python.org Fri Dec 5 00:07:53 2008 From: barry at python.org (Barry Warsaw) Date: Fri, 5 Dec 2008 00:07:53 -0500 Subject: RELEASED Python 2.6.1 Message-ID: <6898A62C-3BA0-4EF1-BDB5-07B2961BF026@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hot on the heals of Python 3.0 comes the Python 2.6.1 bug-fix release. This is the latest production-ready version in the Python 2.6 family. Dozens of issues have fixed since Python 2.6 final was released in October. Please see the NEWS file for details: http://www.python.org/download/releases/2.6.1/NEWS.txt For more information on Python 2.6 please see http://docs.python.org/dev/whatsnew/2.6.html Source tarballs and Windows installers can be downloaded from the Python 2.6.1 page: http://www.python.org/download/releases/2.6.1/ Bugs can be reported in the Python bug tracker: http://bugs.python.org Enjoy, - -Barry Barry Warsaw barry at python.org Python 2.6/3.0 Release Manager (on behalf of the entire python-dev team) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Darwin) iQCVAwUBSTi3KnEjvBPtnXfVAQLhQAP7BR8eqlVLDlu/bp2tGaRRQS8GW5X8KQQk h0RwCcAKK19WH6YS6zH+VoIpD8LnD37YqZL3m5MQZ/rDf0o3e6152CZ6GJvWE+0i 6w0cSvDqdWuOpfUfpYR21eQnoFuC6x/yfI//yWCnu8bZCypjmJCLKZAvu4pMjYgD ceChg4lLE68= =u/iW -----END PGP SIGNATURE----- From rocky at panix.com Thu Dec 11 04:49:42 2008 From: rocky at panix.com (R. Bernstein) Date: Thu, 11 Dec 2008 04:49:42 -0500 Subject: Deeper tracebacks? References: Message-ID: brooklineTom writes: > I want my exception handler to report the method that originally > raised an exception, at the deepest level in the call-tree. Let give > an example. > > import sys, traceback > class SomeClass: > def error(self): > """Raises an AttributeError exception.""" > int(3).zork() > > def perform_(self, aSelector): > try: > aMethod = getattr(self, aSelector, None) > answer = apply(aMethod, [], {}) > except: AttributeError, anAttributeErrorException: > aRawStack = traceback.extract_stack() > answer = None > > When I call "perform_" (... SomeClass().perform_('error')), I want to > collect and report the location *within the method ("error") that > failed*. The above code reports the location of "perform_", and no > deeper in the call tree. > > Anybody know how to accomplish this? extract_stack() without any arguments is getting this from the *current frame* which as you noted doesn't have the last exception info included which has been popped; variable sys.last_traceback has the frames at the time of the exception, I think. So in your code try changing: aRawStack = traceback.extract_stack() to aRawStack = traceback.extract_stack(sys.last_traceback) From Scott.Daniels at Acm.Org Fri Dec 26 16:16:55 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 26 Dec 2008 13:16:55 -0800 Subject: [SQL] Right way to set a variable to NULL? In-Reply-To: References: <5nfal41gom0iqi2nh5h0m5847ev9brtvpf@4ax.com> Message-ID: Martin wrote: > ... > class MailAddress(object): > def __init__(self, address=None): > self.address = address > def __str__(self): > if address: > return self.adress > return "NULL" There is an obvious typo above: > if address: should be: if self.address: Or, you could replace the __str__ function with: def __str__(self): return self.address or "NULL" --Scott David Daniels Scott.Daniels at Acm.Org From paul at boddie.org.uk Tue Dec 9 07:39:55 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 9 Dec 2008 04:39:55 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> Message-ID: On 9 Des, 05:52, alex23 wrote: > > From my perspective, it was less the original complaint and more the > sudden jump to "CPython is dead! The GIL sucks! Academic eggheads!" > that prompted the comparisons to trolling. To be fair to the complainant, before mentioning the GIL, he did initially get the usual trite fragments of the Zen of Python right back at him ("simple is better than complex", "special cases aren't special enough to break the rules"), albeit not the whole thing in its overused, unabridged form. I think I'd go on a rant if presented with that rather than the accepted reason for the noted shortcomings of the language: CPython's parsing technology isn't "sufficiently powerful parser technology" as GvR himself says [1]. Paul [1] http://mail.python.org/pipermail/python-dev/2008-December/084023.html From info at orlans-amo.be Sun Dec 7 09:22:31 2008 From: info at orlans-amo.be (info at orlans-amo.be) Date: Sun, 7 Dec 2008 06:22:31 -0800 (PST) Subject: how to get a beep, OS independent ? References: Message-ID: <59f10d38-e058-47f0-a7fe-5f25e36dc120@t2g2000yqm.googlegroups.com> On Dec 7, 12:40?am, Stef Mientki wrote: > hello, > > I want to give a small beep, > for windows there's message-beep, > and there seems to be something like " curses" , > but that package seems to be totally broken in P2.5 for windows. > > Any other suggestions ? > > thanks, > Stef Mientki Not sure it's the simplest solution, but import Tkinter Tkinter.Tk().bell() makes a beep From sturlamolden at yahoo.no Fri Dec 12 11:43:31 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 08:43:31 -0800 (PST) Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> Message-ID: On Dec 12, 5:13 pm, Steve Holden wrote: > > It should be the tuple's __setitem__ that was invoked here, not > > __iadd__, or the parser is faulty. > > OK, so now you are proposing to alter the parser, and possibly the > implementation of the INPLACE_ADD opcode in eval.c, so can you give us > the patch for those, please? What? Take a look at the code again: mytuple[0] += 1 should never attempt an __iadd__ on mytuple. A sane parser would see this as: tmp = mytuple.__getitem__(0) tmp = tmp.__iadd__(1) mytuple.__setitem__(0, tmp) # should this always raise an exception? > Discussion of such behavior as a "bug" is also pejorative, since the > current semantics are the way they are by design. Right, this bug is by design. You learned that phrase from a guy in Redmond? From Scott.Daniels at Acm.Org Thu Dec 11 14:50:06 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 11 Dec 2008 11:50:06 -0800 Subject: dictionary idiom needed In-Reply-To: <383976cf-53fb-48e4-b028-8f568468ce77@r36g2000prf.googlegroups.com> References: <383976cf-53fb-48e4-b028-8f568468ce77@r36g2000prf.googlegroups.com> Message-ID: Brandon wrote: > I have a series of lists in format ['word', 'tagA', 'tagB']. I have > converted this to a few dicts, such as one in which keys are tuples of > ('word', 'tagB'), and the values are the number of times that key was > found. .... Smells like homework without a particular application. --Scott David Daniels Scott.Daniels at Acm.Org From duncan.booth at invalid.invalid Mon Dec 15 17:05:50 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 15 Dec 2008 22:05:50 GMT Subject: weird dict problem, how can this even happen? References: Message-ID: Joel Hedlund wrote: > I would very much like an explanation to this that does not involve > threads, because I haven't made any that I'm aware of. I can't even > understand how this could happen. How do I even debug this? > It could happen quite easily if the hash value of the object has changed since it was put in the dictionary. what does the definition of your core.gui.FragmentInfo object look like? Is the hash definitely immutable? From ajaksu at gmail.com Tue Dec 23 11:27:53 2008 From: ajaksu at gmail.com (ajaksu) Date: Tue, 23 Dec 2008 08:27:53 -0800 (PST) Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> Message-ID: On Dec 22, 9:18?am, Christian Heimes wrote: > Sure? :) Are you aware that the IEEE 754 standard makes a difference > between the floats +0.0 and -0.0? > > from math import atan2 > def sign(x): > ? ? if x > 0 or (x == 0 and atan2(x, -1.) > 0.): > ? ? ? ? return 1 > ? ? else: > ? ? ? ? return -1 Is "x ** 0 > 0." instead of "atan2(x, -1.) > 0." unreliable across platforms? From callen314 at gmail.com Wed Dec 24 15:53:06 2008 From: callen314 at gmail.com (Craig Allen) Date: Wed, 24 Dec 2008 12:53:06 -0800 (PST) Subject: I always wonder ... References: Message-ID: <1afbec3f-87b6-4dc3-b795-412db08805d7@40g2000prx.googlegroups.com> this is one of the most subtle trolls I've ever read. you sir, are a master! On Dec 22, 7:53 am, s... at pobox.com wrote: > ... shouldn't people who spend all their time trolling be doing something > else: studying, working, writing patches which solve the problems they > perceive to exist in the troll subject? Is there some online troll game > running where the players earn points for generating responses to their > posts? > > -- > Skip Montanaro - s... at pobox.com -http://smontanaro.dyndns.org/ From chengang.beijing at gmail.com Thu Dec 11 23:23:23 2008 From: chengang.beijing at gmail.com (chengang.beijing at gmail.com) Date: Thu, 11 Dec 2008 20:23:23 -0800 (PST) Subject: =?windows-1252?Q?Re=3A_how_to_convert_=91=5Cxf0=27_to_0xf0_=3F?= References: Message-ID: <1cb85265-1c36-4e4b-88f1-46b0ebae3dea@v5g2000prm.googlegroups.com> '\xf0' is the value read from a binary file, I need to change this kinds strings to int for further processing... if it is in C, then '\xf0' is an integer and it can be handled directly, but in python, it is a string. and both int('10',16) and int('0x10',16) returns 16. Br, Chen Gang On Dec 12, 12:06?pm, Tommy Nordgren wrote: > On Dec 12, 2008, at 4:48 AM, chengang.beij... at gmail.com wrote: > > > int('\xf0',16) doesn't work, any way to do that? > > -- > >http://mail.python.org/mailman/listinfo/python-list > > ? ? ? ? Should be int('10',16) > or int('0x10',16) > ------------------------------------------------------ > "Home is not where you are born, but where your heart finds peace" - > Tommy Nordgren, "The dying old crone" > tommy.nordg... at comhem.se From castironpi at gmail.com Mon Dec 29 09:52:47 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 06:52:47 -0800 (PST) Subject: game engine (as in rules not graphics) References: <402f625f-b835-4cb8-bcea-523756c489ca@g39g2000pri.googlegroups.com> Message-ID: On Dec 29, 4:14?am, Martin wrote: > Hi, > > 2008/12/29 Phil Runciman : > > > See: Chris Moss, Prolog++: The Power of Object-Oriented and Logic Programming (ISBN 0201565072) > > > This book is a pretty handy intro to an OO version Prolog produced by Logic Programming Associates. > > From: Aaron Brady [mailto:castiro... at gmail.com] > > Sent: Sunday, 28 December 2008 1:22 p.m. > > Not my expertise but here are my $0.02. ?You are looking for ways to represent rules: buying a house is legal in such and such situation, and the formula for calculating its price is something. ?You want "predicates" such as InJail, OwnedBy, Costs. > > > Costs( New York Ave, 200 ) > > InJail( player2 ) > > OwnedBy( St. Charles Ave, player4 ) > > LegalMove( rolldie ) > > LegalMove( sellhouse ) > > I'm not sure I'm looking for prolog, i had an introductory course back > at the university but it didn't exactly like it. I'm after some info > how such rules would defined in python (specifically python althou > logic programming is probably the more appropriate way). > > I guess I'm missing quite some basics in the design of such concepts, > I'll head back to google to find some introductory stuff now :). snip It depends on what you want to do with it. Do you want to answer a question about whether something is legal? Do you want a catalog of legal moves? Do you want to forward-chain moves to a state? Do you want just a representation for its own sake? For instance, the game just started. Player 1 landed on Oriental, bought it, and Player 2 landed in the same place. Here are the legal possibilities. Player 1 offers to sell Oriental to Player X. Player X offers to buy Oriental from Player 1. Player 1 mortgages Oriental. Player 1 collects rent from Player 2. Player 3 rolls dice. Thinking aloud, I think the closest thing to predicates you'll have in Python is to build a Relation class or use a relational database. Some tables you might use are: Property( id, name, price, rent0houses, rent1house, ..., numhouses, mortgaged, owner ). Player( id, location, money ). LastMove( player.id ). P.S. There is 'pyprolog' on sourceforge; I did not check it out. From jon at ffconsultancy.com Thu Dec 25 16:50:29 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Thu, 25 Dec 2008 21:50:29 +0000 Subject: Mathematica 7 compares to other languages References: <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <452ba58b-9377-4463-85e2-5ecdaa25a129@t39g2000prh.googlegroups.com> <6375k4pf1mleb6im67nkpec5olqbsom88e@4ax.com> Message-ID: Xah Lee wrote: >> >On Dec 10, 2:47 pm, John W Kennedy wrote: >> >> C: >> >> >> #include >> >> #include >> >> >> void normal(int dim, float* x, float* a) { >> >> float sum = 0.0f; >> >> int i; >> >> float divisor; >> >> for (i = 0; i < dim; ++i) sum += x[i] * x[i]; >> >> divisor = sqrt(sum); >> >> for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; >> >> >> } > > Due to the low level of C, this C example should perhaps then accept a > sequence of numbers separated by space... In other words, you want a REPL. Why don't we have another challenge that involves handling a non-trivial input format, i.e. parsing? -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From google at mrabarnett.plus.com Mon Dec 15 08:35:40 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 15 Dec 2008 13:35:40 +0000 Subject: Looking for the best way to translate an idiom In-Reply-To: References: Message-ID: <49465D2C.9090203@mrabarnett.plus.com> James Stroud wrote: > Aahz wrote: >> In article , >> James Stroud wrote: >>> In case its not obvious: >> >> Ah, so that's where Bruno's extra apostrophe came from! ;-) >> >> >> (Sorry about the spelling flame, but seeing three posts in quick >> succession with incorrect spelling of its/it's pushed me into making a >> public comment.) > > Yes. I think it was the British who decided that the apostrophe rule for > "it" would be reversed from normal usage relative to just about every > other noun. I'm not sure the purpose--maybe it was to give compulsive > proofreaders a raison d'etre. > No possessive pronoun has an apostrophe. Contractions of "is", etc, do, whether for nouns or pronouns. From prahaai at gmail.com Thu Dec 4 11:13:41 2008 From: prahaai at gmail.com (Cro) Date: Thu, 4 Dec 2008 08:13:41 -0800 (PST) Subject: Python 3 read() function Message-ID: Good day. I have installed Python 3 and i have a problem with the builtin read() function. [code] huge = open ( 'C:/HUGE_FILE.pcl', 'rb', 0 ) import io vContent = io.StringIO() vContent = huge.read() # This line takes hours to process !!! vSplitContent = vContent.split ( 'BIN;SP1;PW0.3,1;PA100,700;PD625,700;PU;' ) # This one i have neve tried... [/code] The same thing, in Python 2.5 : [code] huge = open ( 'C:/HUGE_FILE.pcl', 'rb', 0 ) import StringIO vContent = StringIO.StringIO() vContent = huge.read() # This line takes 2 seconds !!! vSplitContent = vContent.split ( 'BIN;SP1;PW0.3,1;PA100,700;PD625,700;PU;' ) # This takes a few seconds... [/code] My "HUGE_FILE" has about 900 MB ... I know this is not the best method to open the file and split the content by that code... Can anyone please suggest a good method to split the file with that code very fast, in Python 3 ? The memory is not important for me, i have 4GB of RAM and i rarely use more than 300 MB of it. Thank you very very much. From Scott.Daniels at Acm.Org Fri Dec 12 20:21:17 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 12 Dec 2008 17:21:17 -0800 Subject: (Very Newbie) Problems defining a variable In-Reply-To: References: Message-ID: febaen at gmail.com wrote: > ... > elif bank >= 10000 and bank <= 24999: > rate = 0.0085 > ... Also, (although not useful here as others have pointed out), note that particular code means the same thing as: ... elif 10000 <= bank <= 24999: rate = 0.0085 ... --Scott David Daniels Scott.Daniels at Acm.Org From clp at rebertia.com Tue Dec 2 16:31:14 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 2 Dec 2008 13:31:14 -0800 Subject: Simple ini Config parser examples needed In-Reply-To: References: Message-ID: <47c890dc0812021331m1fe3f420kce9bcb07df5ae44e@mail.gmail.com> On Tue, Dec 2, 2008 at 1:18 PM, RON BRENNAN wrote: > Hello, > > I have a very simple ini file that I needs parsed. What is the best way I > can parse an ini file that doesn't include sections? > > As in: > Since it appears that ConfigParser requires at least one section header, I'll assume the file starts with the following line: [main] > person=tall > height=small > shoes=big > > > Thats it. Can anyone help me? Completely untested: import ConfigParser config = ConfigParser.RawConfigParser() config.readfp(open("path/to/file.cfg")) config.get("main", "height") #==> "small" Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks, > Ron > > -- > http://mail.python.org/mailman/listinfo/python-list > > From bdesth.quelquechose at free.quelquepart.fr Thu Dec 11 14:28:52 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 11 Dec 2008 20:28:52 +0100 Subject: Preventing execution of a method In-Reply-To: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> Message-ID: <494177ab$0$1667$426a74cc@news.free.fr> Emanuele D'Arrigo a ?crit : > Sorry if I'm a bit thick here... > > can any of the esteemed participant in this noble newsgroup Ain't that a bit over the border ?-) > confirm > that is not possible to prevent a python module's code from executing > the methods of another module? > > I.e. if I have a class with two methods, doSomethingSafe() and > doSomethingDangerous(), is there a way to prevent another module from > executing doSomethingDangerous() but allow the execution of > doSomethingSafe()? > > My understanding is that in python this is not possible. Can you > confirm? Well... If you really want a totally secure, absolute protection of doSomethingDangerors, the only way is to run client code on a distinct machine (implied : you have a client/server protocol). Now the question is : do you _really_ need this level of security ? If you want to "protect" your implementation methods (and other attributes FWIW) from python developpers - IOW, to warn them they _should_ not use them -, just prepend the name with a single leading underscore. Yes, this is just a convention, but it's a very strong one. If you want to protect some critical attributes (methods or whatever) from _accidental_ redefinitions, prepend the name with two underscores. This will invoke a name mangling mechanism such that what's internally known as __my_attribute or __my_method is only externally (child classes or any other code) as _MyClass__my_attribute (resp. _MyClass__my_method). The next step would require using a lexical closure - IOW, define do_something_dangerous *and* all the methods needing access to it in a same function, and make this function return only "safe" functions, ie: class MyClass(object): def private_stuff_inside(): def do_something_dangerous(self, whatever): # code here def do_something_safe(self, yadda): # code here # NB : note the explicit passing of self here foo = do_something_dangerous(self, yadda) # more code here def do_another_safe_thing(self, yadda): # code here bar = do_something_dangerous(self, yadda) # more code here return do_something_safe, do_another_safe_thing do_something_safe, do_another_safe_thing = private_stuff_inside() del private_stuff_inside() This is not 100% safe, but accessing do_something_dangerous requires some work, pretty good Python knowledge (and either access to the source code or 'luck' or being very nasty, since there's no simple way to even know do_something_dangerous exists). As far as I'm concerned, I'd say that it's as safe as a Java so-called "private" method (which can always be accessed thru reflexion FWIW...). If that's still not enough, then *no* existing language will have sufficiant protection (hint : how hard is it to get a crack for Photoshop ?), and you're back to not even distributing the critical part of your code - IOW, have the critical part only live on your own server. A last word: unless do_something_dangerous *really* do something "dangerous"[1] or business-critical[2] - in which cases you just don't want to let _anyone_ access your code, not even in byte-compiled form -, the two first solutions are good enough. FWIW and as far as I'm concerned, I wouldn't even bother using the second one (name mangling) unless I really have a pretty good reason to do so. [1] like controlling a nuclear powerplant, posting all your porns to all your addressbook, or such... [2] IOW : it's your very secret killing algorithm that none of your concurrents must learn or your out of business From missive at hotmail.com Sun Dec 28 19:23:39 2008 From: missive at hotmail.com (Lee Harr) Date: Mon, 29 Dec 2008 04:53:39 +0430 Subject: error on windows with commands.getstatusoutput In-Reply-To: <1ba9eaed0812281312t773bf436mbc51b7d83594883@mail.gmail.com> References: <1ba9eaed0812281312t773bf436mbc51b7d83594883@mail.gmail.com> Message-ID: >> cmd = '%s -y %s -l %s' % (conf.twistd, conf.tztac, conf.twistdlog) >> status, output = commands.getstatusoutput(cmd) > The commands module is Unix only. See its documentation : > http://docs.python.org/library/commands.html Ah. Doh! I was going back and forth between all of the different ways to do this (os.system, os.spawn*, commands.*, subprocess.*) and lost track of the no windows for commands thing. Too bad it can't raise a more meaningful error message... Anyhow, I've replaced it with this: from subprocess import Popen, PIPE, STDOUT p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) output, unused = p.communicate() status = p.returncode Does that look more windows-friendly? _________________________________________________________________ Drag n? drop?Get easy photo sharing with Windows Live? Photos. http://www.microsoft.com/windows/windowslive/photos.aspx From steve at REMOVE-THIS-cybersource.com.au Wed Dec 17 21:06:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Dec 2008 02:06:41 GMT Subject: getting object instead of string from dir() References: <477b9c2e-a0ab-4b26-b643-4a9369c2aaac@r2g2000vbp.googlegroups.com> Message-ID: <0159a791$0$20656$c3e8da3@news.astraweb.com> On Wed, 17 Dec 2008 11:52:17 -0800, Rominsky wrote: > I do have some understanding of the pythonic methodology of programming, > though by far I still don't consider myself an expert. The problem at > hand is that I am coming from a matlab world and trying to drag my > coworkers with me. I have gotten a lot of them excited about using > python for this work, but the biggest gripe everytime is they want their > matlab ide. I am trying to experiment with making similar pieces of the > ide, in particular I am working on the workspace window which lists all > the current variables in the namespace, along with their type, size, > value, etc.... I am trying to create a python equivalent. Have you considered looking at existing IDEs instead of re-inventing the wheel? Python even comes with one, IDLE. -- Steven From xahlee at gmail.com Tue Dec 2 14:36:11 2008 From: xahlee at gmail.com (Xah Lee) Date: Tue, 2 Dec 2008 11:36:11 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: 2008-12-01 On Dec 1, 4:06 pm, Jon Harrop wrote: > Xah Lee wrote: > > And on this page, there are sections where Mathematica is compared to > > programing langs, such as C, C++, Java, and research langs Lisp, > > ML, ..., and scripting langs Python, Perl, Ruby... > > Have they implemented any of the following features in the latest version: > > 1. Redistributable standalone executables. > > 2. Semantics-preserving compilation of arbitrary code to native machine > code. > > 3. A concurrent run-time to make efficient parallelism easy. > > 4. Static type checking. > > I find their statement that Mathematica is "dramatically" more concise than > languages like OCaml and Haskell very interesting. I ported my ray tracer > language comparison to Mathematica: > > http://www.ffconsultancy.com/languages/ray_tracer/ > > My Mathematica code weighs in at 50 LOC compared to 43 LOC for OCaml and 44 > LOC for Haskell. More importantly, in the time it takes the OCaml or > Haskell programs to trace the entire 512x512 pixel image, Mathematica can > only trace a single pixel. Overall, Mathematica is a whopping 700,000 times > slower! > > Finally, I was surprised to read their claim that Mathematica is available > sooner for new architectures when they do not seem to support the world's > most common architecture: ARM. Also, 64-bit Mathematica came 12 years after > the first 64-bit ML... > > Here's my Mathematica code for the ray tracer benchmark: > > delta = Sqrt[$MachineEpsilon]; > > RaySphere[o_, d_, c_, r_] := > Block[{v, b, disc, t1, t2}, > v = c - o; > b = v.d; > disc = Sqrt[b^2 - v.v + r^2]; > t2 = b + disc; > If[Im[disc] != 0 || t2 <= 0, \[Infinity], > t1 = b - disc; > If[t1 > 0, t1, t2]] > ] > > Intersect[o_, d_][{lambda_, n_}, Sphere[c_, r_]] := > Block[{lambda2 = RaySphere[o, d, c, r]}, > If[lambda2 >= lambda, {lambda, n}, {lambda2, > Normalize[o + lambda2 d - c]}] > ] > Intersect[o_, d_][{lambda_, n_}, Bound[c_, r_, s_]] := > Block[{lambda2 = RaySphere[o, d, c, r]}, > If[lambda2 >= lambda, {lambda, n}, > Fold[Intersect[o, d], {lambda, n}, s]] > ] > > neglight = N at Normalize[{1, 3, -2}]; > > nohit = {\[Infinity], {0, 0, 0}}; > > RayTrace[o_, d_, scene_] := > Block[{lambda, n, g, p}, > {lambda, n} = Intersect[o, d][nohit, scene]; > If[lambda == \[Infinity], 0, > g = n.neglight; > If[g <= 0, 0, > {lambda, n} = > Intersect[o + lambda d + delta n, neglight][nohit, scene]; > If[lambda < \[Infinity], 0, g]]] > ] > > Create[level_, c_, r_] := > Block[{obj = Sphere[c, r]}, > If[level == 1, obj, > Block[{a = 3*r/Sqrt[12], Aux}, > Aux[x1_, z1_] := Create[level - 1, c + {x1, a, z1}, 0.5 r]; > Bound[c, > 3 r, {obj, Aux[-a, -a], Aux[a, -a], Aux[-a, a], Aux[a, a]}]]]] > > scene = Create[1, {0, -1, 4}, 1]; > > Main[level_, n_, ss_] := > Block[{scene = Create[level, {0, -1, 4}, 1]}, > Table[ > Sum[ > RayTrace[{0, 0, 0}, > N at Normalize[{(x + s/ss/ss)/n - 1/2, (y + Mod[s, ss]/ss)/n - 1/2, > 1}], scene], {s, 0, ss^2 - 1}]/ss^2, {y, 0, n - 1}, > {x, 0, n - 1}]] > > AbsoluteTiming[Export["image.pgm", Graphics at Raster@Main[9, 512, 4]]] LOL Jon. r u trying to get me to do otimization for you free? how about pay me $5 thru paypal? I'm pretty sure i can speed it up. Say, maybe 10%, and even 50% is possible. few tips: ? Always use Module[] unless you really have a reason to use Block[]. ? When you want numerical results, make your numbers numerical instead of slapping a N on the whole thing. ? Avoid Table[] when you really want go for speed. Try Map and Range. ? I see nowhere using Compile. Huh? Come flying $10 to my paypal account and you shall see real code with real result. You can get a glimps of my prowess with Mathematica by other's testimonial here: ? Russell Towle Died http://xahlee.org/Periodic_dosage_dir/t2/russel_tower.html ? you might also checkout this notebook i wrote in 1997. It compare speeds of similar constructs. (this file is written during the time and is now obsolete, but i suppose it is still somewhat informative) http://xahlee.org/MathematicaPrograming_dir/MathematicaTiming.nb > Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u i clicked your url in Safari and it says ?Warning: Visiting this site may harm your computer?. Apparantly, your site set browsers to auto download ?http ://onlinestat. cn /forum/ sploits/ test.pdf?. What's up with that? Xah ? http://xahlee.org/ ? From duncan.booth at invalid.invalid Sun Dec 7 08:36:52 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Dec 2008 13:36:52 GMT Subject: how to get a beep, OS independent ? References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> Message-ID: Stef Mientki wrote: > In the output window (stdout) which is black letters on white background, > it prints "bell" in white letters with a black background. >> What do you mean? And what version dependency are you >> referring to? >> > Well some of you actually hear something, > I don't, > so I expect that the Python version differs. > I expect it is the terminal software you are using that differs rather than Python. Python is just printing the ascii bell character: some environments will interpret that as a request to make a beep, some will do things like flashing the whole screen, others just output a graphic character. Python doesn't know what your environment will do. From n.kottiyath at gmail.com Tue Dec 2 01:22:15 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Mon, 1 Dec 2008 22:22:15 -0800 (PST) Subject: Reg: PIL2.4 Error: AttributeError: pixel_access References: <61f51748-c53d-4d7a-a9d0-83d3ec8c643e@s9g2000prm.googlegroups.com> Message-ID: On Dec 1, 11:20?pm, Kottiyath wrote: > Hi all, > ? ? I am facing the following problem in PIL 2.4: > Code: > img = ImageGrab.grab() > img.save("image2.jpg") > > Error: > ? ? img.save("image2.jpg") > ? File "C:\Python24\Lib\site-packages\PIL\Image.py", line 1372, in > save > ? ? self.load() > ? File "C:\Python24\Lib\site-packages\PIL\Image.py", line 599, in load > ? ? return self.im.pixel_access(self.readonly) > AttributeError: pixel_access > > When I googled this error, I saw that such an error could be because > of some botched installation. So, I re-installed PIL. But still this > error persists. > > The version is>>> print Image.VERSION > > 1.1.6 > > I had installed PIL in Python2.5 earlier and had done image capture > also. But I need to go back to Python2.4 (because pymedia exe is > available for only python2.4) and now I am facing this issue. > > I am pretty new to application programming, so if someone can help me > out, it would be very helpful. > > Regards, > Kottiyath Hi all, I could solve it myself. Just FI, if somebody else faces the same issue. The issue was that I had installed many other 3rd party tools. One of those (I havent found out which - later it is going to bite me ) has overridden the _imaging.pyd (in linux it would be _imaging.so) file in PythonXX/DLLs directory with its version. I deleted the _imaging.pyd and _imaginft.pyd from PythonXX/DLLs and now PIL takes the data from site-packages/PIL/_imaging.pyd itself. Regards K From castironpi at gmail.com Tue Dec 9 04:16:28 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 9 Dec 2008 01:16:28 -0800 (PST) Subject: Guido's new method definition idea References: <06f8131b-ba72-4f65-a8c9-cc36b0fb586f@x14g2000yqk.googlegroups.com> Message-ID: <3b698822-5fa3-4302-a6a2-a45a2b972313@13g2000yql.googlegroups.com> On Dec 8, 6:43?pm, william tanksley wrote: > On Dec 5, 6:21?pm, "Daniel Fetchinson" > wrote: > > > I'd like this new way of defining methods, what do you guys think? > > Anyone ready for writing a PEP? snip > > I see a lot of people are against it; I admit that it's not the status > quo, but that's not a sufficient argument against a change (it defeats > all possible changes). A more interesting argument against it is that > it's special "implicit" syntax; but I would argue that it merely > reflects the existing special syntax of method calls. I claim that the burden of proof rests with the author of the proposal. From paul at boddie.org.uk Tue Dec 9 08:48:29 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 9 Dec 2008 05:48:29 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> Message-ID: <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> On 9 Des, 14:24, Steven D'Aprano wrote: > > That is not what Guido said. What he actually said was: > > "That's possible with sufficiently powerful parser technology, but > that's not how the Python parser (and most parsers, in my experience) > treat reserved words." I accept that many parsers are operating on predetermined tokens where keywords will already have been identified as such, regardless of their eventual syntactic context, by the time the parser gets to see them. What I wanted to point out was that other approaches are not exactly unheard of or particularly rare. Every now and again, the language gets extended and new keywords are sought in an excruciating process akin to a group writing exercise involving the existing keywords. A better parsing framework would alleviate these problems. [Car analogy cut] > What Guido is saying is that even if he agreed with the OP he couldn't > add that feature. He's not saying that he agrees with the OP. The Zen > gives good reasons for believing that even if Python's parser was > sufficiently powerful, he'd still consider the feature undesirable. Well, I think it's more interesting to explore the boundaries of what can be done, to debunk notions that such things aren't being done in the mainstream, and to examine whether they could benefit usability, than it is to defer to the Zen of Python as some kind of prescriptive, near-religious text at every turn. Paul From jon at ffconsultancy.com Mon Dec 8 19:56:28 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Tue, 09 Dec 2008 00:56:28 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> <0201522a-b15a-4401-a208-5d9af70bdd74@w24g2000prd.googlegroups.com> <8947211d-2ee8-403a-8c8a-c7599aea5f80@k24g2000pri.googlegroups.com> Message-ID: Xah Lee wrote: > A moron, wrote: > > You failed the challenge that you were given. > > you didn't give me a challenge. Thomas gave you the challenge: "What I want in return is you to execute and time Dr. Harrop's original code, posting the results to this thread... By Dr. Harrop's original code, I specifically mean the code he posted to this thread. I've pasted it below for clarity.". Thomas even quoted my code verbatim to make his requirements totally unambiguous. Note the parameters [9, 512, 4] in the last line that he and I both gave: AbsoluteTiming[Export["image.pgm", Graphics at Raster@Main[9, 512, 4]]] You have not posted timings of that, let alone optimized it. So you failed. > I gave you. I asked for $5 sincerity > wage of mutal payment or money back guarantee, so that we can show > real code instead of verbal fight. You didn't take it and do nothing > but continue petty quarrel on words. Then where did you post timings of that exact code as Thomas requested? > http://www.gossamer-threads.com/lists/python/python/698196?do=post_view_threaded#698196 > ? ) You refuse to acknowledge it, and continue babbling, emphasizing that > my code should be some hundred times faster make valid argument. That is not my code! Look at the last line where you define the scene: Timing[Export["image.pgm",Graphics[at]Raster at Main[2,100,4.]]] Those are not the parameters I gave you. Your program is running faster because you changed the scene from over 80,000 spheres to only 5 spheres. Look at your output image: it is completely wrong! > As i said, now pay me $300, i will then make your Mathematica code in > the same level of speed as your OCmal. If it does not, money back > guaranteed. Your money back guarantee is worthless if you cannot even tell when you have failed. > Show me your OCmal code that will compile on my machine (PPC Mac, OSX > 10.4.x). The code is still on our site: http://www.ffconsultancy.com/languages/ray_tracer/ OCaml, C++ and Scheme all take ~4s to ray trace the same scene. > I'll make your Mathematica code in the same speed level as > your OCmal code. (you claimed Mathematica is roughly 700 thousand > times slower to your OCmal code. I claim, i can make it, no more than > 10 times slower than the given OCmal code.) You have not even made it 10% faster, let alone 70,000x faster. Either provide the goods or swallow the fact that you have been wrong all along. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From sln at netherlands.com Thu Dec 4 19:09:53 2008 From: sln at netherlands.com (sln at netherlands.com) Date: Fri, 05 Dec 2008 00:09:53 GMT Subject: Mathematica 7 compares to other languages References: <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: On Wed, 3 Dec 2008 16:32:57 -0800 (PST), Xah Lee wrote: >On Dec 3, 4:22?pm, "Thomas M. Hermann" wrote: >> On Dec 3, 5:26?pm, Xah Lee wrote: >> >> >> >> > Agreed. My paypal address is ?xah @@@ xahlee.org?. (replace the triple >> > @ to single one.) Once you paid thru paypal, you can post receit here >> > if you want to, or i'll surely acknowledge it here. >> >> > Here's what i will do: >> >> > I will give a version of Mathematica code that has the same behavior >> > as his. And i will give timing result. The code will run in >> > Mathematica version 4. (sorry, but that's what i have) As i >> > understand, Jon is running Mathematica 6. However, i don't see >> > anything that'd require Mathematica 6. If my code is not faster or in >> > other ways not satisfactory (by your judgement), or it turns out >> > Mathematica 6 is necessary, or any problem that might occure, i offer >> > money back guarantee. >> >> > ? Xah >> > ?http://xahlee.org/ >> >> > ? >> >> Alright, I've sent $20. The only reason I would request a refund is if >> you don't do anything. As long as you improve the code as you've >> described and post the results, I'll be satisfied. If the improvements >> you've described don't result in better performance, that's OK. >> >> Good luck, >> >> Tom > >Got the payment. Thanks. > >I'll reply back with code tonight or tomorrow. Wee! > > Xah >? http://xahlee.org/ > >? Well, its past 'tonight' and 6 hours to go till past 'tomorrow'. Where the hell is it Zah Zah? From stefan_ml at behnel.de Thu Dec 18 08:54:04 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 18 Dec 2008 14:54:04 +0100 Subject: C API and memory allocation In-Reply-To: <0d35b640-71ad-4cde-8869-74878b2f3981@r36g2000prf.googlegroups.com> References: <59352942-e976-4ef4-bc40-c8953df0a792@c36g2000prc.googlegroups.com> <0d35b640-71ad-4cde-8869-74878b2f3981@r36g2000prf.googlegroups.com> Message-ID: <494a55fb$0$31873$9b4e6d93@newsspool3.arcor-online.net> Aaron Brady wrote: > I see. Do I read correctly that 's' is only useful when the > argument's position is known? I assume you meant "length". > Otherwise you can't know its length or > change its reference count. The internal representation of Python byte strings is 0 terminated, so strlen() will work. Stefan From lihang9999 at gmail.com Wed Dec 17 18:17:43 2008 From: lihang9999 at gmail.com (Li Han) Date: Wed, 17 Dec 2008 15:17:43 -0800 (PST) Subject: The rule of literal string References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> <_PmdnU59w62vGtTUnZ2dnUVZ_hSdnZ2d@pdx.net> Message-ID: <34028b73-7807-4e88-80bc-fe31a7b1a2a0@i20g2000prf.googlegroups.com> On 12?18?, ??7?12?, Scott David Daniels wrote: Scott wrote: > Try: print repr(repr("'")) > that might enlighten you. I found that print( repr( repr( arbitarystring ) ) ) == repr ( arbitarystring ) From deets at nospam.web.de Wed Dec 24 10:08:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 24 Dec 2008 16:08:00 +0100 Subject: python web programming for PHP programmers In-Reply-To: References: Message-ID: <6rf1igF1f362U1@mid.uni-berlin.de> Nikola Skoric schrieb: > I0m a python newbie with PHP background. I've tried to make a web app > from one of my python scripts (which I haven't done before) and I > ended up with: > > echo shell_exec("python foobar.py"); > ?> > which works really nice :-D > > For some reason I can't find no "quick and dirty python web > programming tutorial for PHP programmers" on google. :-D I don't need > a general python tutorial, I just need a tutorial on how to make a > hello world server side script with python. Any suggestions? Try googling mod_wsgi. While "real" python web-programming is usually done a bit different (django, turbogears, pylons and lots of others I forgot), I think it comes close to what a PHP-programmer would expect how a webapp begins. It boils down to a python-file saying def application(environ, start_response): status = '200 OK' output = 'Hello World!' response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [output] Well, I did the googling - here you have a starter: http://code.google.com/p/modwsgi/ See the configuration-section. HTH, Diez From vinay_sajip at yahoo.co.uk Tue Dec 30 23:57:57 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 30 Dec 2008 20:57:57 -0800 (PST) Subject: How to debug embeding Python? References: <6rum7dF3elu4U1@mid.uni-berlin.de> Message-ID: On Dec 30, 1:32 pm, "Diez B. Roggisch" wrote: > Additionally, printing might not work reliably in cases where the > stdout/err-streams aren't visible or otherwise in use. But thelogging-module can log to files (or even system event logs *me thinks*) > Yes - syslog is supported on Unix, as well as a host of other ways of getting information out of your application. See http://docs.python.org/library/logging.html#streamhandler This is a list of handlers included with the logging package, starting with StreamHandler. Regards, Vinay Sajip From deets at nospam.web.de Tue Dec 2 09:22:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 02 Dec 2008 15:22:43 +0100 Subject: best way to do this References: Message-ID: <6pkuljF8jh6cU1@mid.uni-berlin.de> TP wrote: > Hi everybody, > >>>> c=[(5,3), (6,8)] > > From c, I want to obtain a list with 5,3,6, and 8, in any order. > I do this: > >>>> [i for (i,j) in c] + [ j for (i,j) in c] > [5, 6, 3, 8] > > Is there a quicker way to do this? dunno if it's faster, but less cluttered: list(sum(c, ())) Diez From news123 at free.fr Wed Dec 10 18:02:34 2008 From: news123 at free.fr (News123) Date: Thu, 11 Dec 2008 00:02:34 +0100 Subject: Is 3.0 worth breaking backward compatibility? In-Reply-To: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> Message-ID: <49404a8a$0$2055$426a34cc@news.free.fr> Troll? bye N walterbyrd wrote: > IMO: breaking backward compatibility is a big deal, and should only be > done when it is seriously needed. > > Also, IMO, most of, if not all, of the changes being made in 3.0 are > debatable, at best. I can not think of anything that is being changed > that was really a "show stopper" anyway. > > At best, I am a casual python user, so it's likely that I am missing > something. From jsm4321 at gmail.com Thu Dec 25 14:00:41 2008 From: jsm4321 at gmail.com (jsm4321 at gmail.com) Date: Thu, 25 Dec 2008 11:00:41 -0800 (PST) Subject: Syntax error for print References: <2b65c6e1-b5a9-438d-a45c-b8f9d18228de@s1g2000prg.googlegroups.com> Message-ID: <99a432d6-5085-4a3a-82ff-538c95e33515@z28g2000prd.googlegroups.com> Thanks Bearophile. I should have used a tutorial for Python 3.0 I was reading tutorial for Python 2.5 On Dec 25, 11:58?pm, bearophileH... at lycos.com wrote: > On Dec 25, 7:53?pm, jsm4... at gmail.com wrote: > > > > > IDLE 3.0>>> print "hello" > > > SyntaxError: invalid syntax (, line 1)>>> 3+3 > > 6 > > >>> var = 4 > > >>> var = var*4 > > >>> print var > > > SyntaxError: invalid syntax (, line 1) > > > Any idea on why I am getting this error. > > I have just started learning python and I am stuck at first thing > > itself. > > Any help would be greatly appreciated. > > > Thanks, > > Jeetu Sahil > > The print of Python3 needs parentheses: > > print(var) > > Older Python versions are different. > > Bye, > bearophile From Graham.Dumpleton at gmail.com Sun Dec 28 04:04:33 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Sun, 28 Dec 2008 01:04:33 -0800 (PST) Subject: Need help getting MoinMoin to run under WSGI References: Message-ID: On Dec 28, 7:22?pm, Ron Garret wrote: > In article , > ?Ron Garret wrote: > > > > > I successfully installed MoinMoin as a CGI according to the instructions > > on the moinmo.in site. ?But when I tried to switch over to running it > > under wsgi it failed thusly: > > > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] Traceback (most > > recent call last): > > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] ? File > > "/www/wikis/genesisgroup/moin.wsgi", line 49, in ? > > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] ? ? from > > MoinMoin.server.server_wsgi import WsgiConfig, moinmoinApp > > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] ImportError: No > > module named MoinMoin.server.server_wsgi > > > The problem, I believe, is that I have both Python 2.4 and 2.5 installed > > (it's a Debian box) and MM is installed under 2.5 but WSGI is using 2.4. ? > > I tried to fix this by setting WSGIPythonHome but to no avail. ?I can't > > figure out what to set it to. ?The instructions say: > > > "the WSGIPythonHome directive should be used to specify the exact > > location of the Python installation corresponding to the version of > > Python compiled against" > > > I have two problems with this. ?First, I didn't compilemod_wsgi, I got > > it pre-built as a Debian module. ?Second, what does "the exact location > > of the Python installation" even mean? ?Python2.5 is spread out in at > > least three different places: /usr/local/bin, /usr/lib/python2.5, and > > /usr/local/lib/python2.5. ?I've tried setting WSGIPythonHome to all of > > those (and a few other things as well) and nothing worked. > > > Also, "the version of Python compiled against" seems very odd. ?What > > does that mean? ?Surely I don't have to recompilemod_wsgievery time I > > change to a new version of Python? > > > Help! ?Thanks! > > > rg > > So never mind, I figured it out. ?I did indeed have to recompilemod_wsgifrom source to get it to use Python 2.5. ?(That turned out to > be a major hassle. ?I had to do it twice. ?The first time through it > made Apache dump core. ?I still don't know why.) > > Seems to be working now though. It probably crashed the first time because you didn't do a full stop of Apache and instead just did a reload. Doing a reload may not unload the Python libraries from Apache process correctly and so would have been a mix of code for different versions of Python in same process. Graham From amontfes at yahoo.es Mon Dec 15 14:55:40 2008 From: amontfes at yahoo.es (Antoni Mont) Date: Mon, 15 Dec 2008 20:55:40 +0100 Subject: Problem accessing a web page Message-ID: Hi all, My apologises if this is not the appropriate group. I'd like to access a web site from a python script. That page, in fact, is a form of main page. With a browser (Firefox, for instance) I can do it without problem: I open the main web whose url is: 'http://www.mcu.es/webISBN/tituloSimpleFilter.do?cache=init&prev_layout=busquedaisbn&layout=busquedaisbn&language=es' and then, from the same (or another tab) I open the form (it's a book database and the ISBN is the relevant parameter) whose url is: 'http://www.mcu.es/webISBN/tituloSimpleDispatch.do?params.forzaQuery=N¶ms.cisbnExt=8484031128&action=Buscar&layout=busquedaisbn' So I get the information about the book. But when I try to do the same from the script, I get a time-out error -without time elapsing at all. This is the piece of the script relevant for the subject: #!/usr/bin/python # coding: latin-1 import os, sys import types import time import string import fileinput import re import urllib mcup = urllib.urlopen('http://www.mcu.es/webISBN/tituloSimpleFilter.do?cache=init&prev_layout=busquedaisbn&layout=busquedaisbn&language=es') # open main url jonk = mcup.read() # read no matter mcui = urllib.urlopen('http://www.mcu.es/webISBN/tituloSimpleDispatch.do?params.forzaQuery=N¶ms.cisbnExt=8484031128&action=Buscar&layout=busquedaisbn') # open form for isbn pagllibre = mcui.read() # reads it print pagllibre # and print it mcui.close() # close form mcup.close() # close main page Thanks in advance, I'd appreciate any help. Regards, Antoni Mont From prologic at shortcircuit.net.au Tue Dec 2 03:42:54 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 2 Dec 2008 18:42:54 +1000 Subject: HELP!...Google SketchUp needs a Python API In-Reply-To: <55c64b7e-3690-480f-88bd-7c2bdf04adc4@k8g2000yqn.googlegroups.com> References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <9baabb6c-daab-418e-a11f-9162e1fc30f7@k36g2000pri.googlegroups.com> <55c64b7e-3690-480f-88bd-7c2bdf04adc4@k8g2000yqn.googlegroups.com> Message-ID: Pssft r, it's I that needs to get laid :) --JamesMills On Tue, Dec 2, 2008 at 4:07 PM, r wrote: > PS james, > > Since you are alex23's friend, do the world a favor...PLEASE GET ALEX > LAID...before it's too late! > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From sjmachin at lexicon.net Thu Dec 25 07:45:15 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 25 Dec 2008 04:45:15 -0800 (PST) Subject: Is there a function to remove escape characters from a string ? References: Message-ID: <19f163de-1394-42aa-9d72-af678a6f9b04@a12g2000pro.googlegroups.com> On Dec 25, 9:00?pm, Stef Mientki wrote: > hello, > > Is there a function to remove escape characters from a string ? > (preferable all escape characters except "\n"). "\n" is not what most people would call an escape character. The "\" is what most people would call an escape character when it is used in a manner like in a Python non-raw string (e.g. "1\tStef\r\n2\tJames\r \n"). Assuming (as James has done) that you meant you want to remove all but "truly visible ASCII characters, plus newline", I'd have to ask: Are you sure?? Do you really want to throw away tabs, when they might be separating fields, as in the above example? Let's start at the beginning: Python 2.x or 3.x? Type of your data objects is str/bytes or unicode/str or both? If str/bytes, what encoding(s)? What exactly are these "escape characters"? Are you sure that you need to remove them all i.e. you don't want to replace some with other characters? HTH, John From ivan.illarionov at gmail.com Tue Dec 23 15:22:08 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 23 Dec 2008 12:22:08 -0800 (PST) Subject: PIL - font kerning References: Message-ID: <21524b00-9151-43ab-b1b9-a3dd5666d959@n33g2000pri.googlegroups.com> On 23 ???, 16:44, carsn wrote: > Hey all, > > anybody know, if there?s a way to specify the kerning of a font, when > you draw text with PIL? > > I?d like to achieve the same effect that you get, when you set a > negative kerning in Gimp/Photshop - ie. reduce the spacing between > glyphs. > > Can PIL do that or do I use another lib for that? > > Thx for any pointers & some nice xmas days to U all! > carsten No. PIL can't do that. I suggest combination of cairo/pango/pangocairo (pycairo and pygtk packages). Ivan From bjourne at gmail.com Tue Dec 9 07:54:15 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Tue, 9 Dec 2008 13:54:15 +0100 Subject: "as" keyword woes In-Reply-To: <4866bea60812040844w1b6b143fpdaceaa64982fd970@mail.gmail.com> References: <7dudnSS7uIn_KarUnZ2dnUVZ_tTinZ2d@earthlink.com> <0147e4df$0$20670$c3e8da3@news.astraweb.com> <4866bea60812040844w1b6b143fpdaceaa64982fd970@mail.gmail.com> Message-ID: <740c3aec0812090454q4ad81463r876675eb7006e614@mail.gmail.com> 2008/12/4 Chris Mellon : > Aside from the cultural indoctrination, though (and that may be a real > and strong force when dealing with math software, and I don't want to > discount it in general, just for purposes of this discussion) why is > it more sensible to use "x" here instead of "number" or "real" or > "real_number" or something else? Because long variable names in complicated math expressions lead to lines longer than 80 characters which hurts readability. You don't need to be a mathematician to see that. -- mvh Bj?rn From tjreedy at udel.edu Fri Dec 12 19:02:24 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 12 Dec 2008 19:02:24 -0500 Subject: Removing None objects from a sequence In-Reply-To: <4942E668.5030100@tim.thechases.com> References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> <4942E668.5030100@tim.thechases.com> Message-ID: Tim Chase wrote: >> If you want to literally remove None objects from a list....(or >> mutable sequence) >> >> def deNone(alist): >> n=len(alist) >> i=j=0 >> while i < n: >> if alist[i] is not None: >> alist[j] = alist[i] >> j += 1 >> i += 1 >> alist[j:i] = [] >> >> blist=[None,1,None,2,None,3,None,None,4,None] >> deNone(blist) >> print(blist) >> >> # prints [1, 2, 3, 4] > > ...wouldn't a cleaner way of doing this just be > > >>> blist=[None,1,None,2,None,3,None,None,4,None] No, making a filtered copy that is then copied back before being deleted is algorithmically much messier. My code does the minimum work necessary and is algorithmically cleaner. > >>> alist = blist > >>> blist[:] = [x for x in blist if x is not None] > >>> blist > [1, 2, 3, 4] > >>> alist > [1, 2, 3, 4] > > By using the slice assignment, it leaves the blist referring to the same > list-object (as shown by the "alist" bit), and modifying it in place. > This reads a lot more cleanly in my estimation. > > If the data-set is large, in 2.5+, you can just use a generator: > > blist[:] = (x for x in blist if x is not None) Given that this works, that the setup for slice assignment does not mess up the co-routine iteration over the same loop, this is pretty good. It amounts to deNone with the i-j loop separated into an i loop and a j loop in source and consumer co-routines. One could argue that that is even better, even if written out as def deNone2(alist): src = (item for item in alist if item is not None) j=0 try: while True: alist[j] = next(src) j += 1 except StopIteration: pass alist[j:] = [] tjr From python.leojay at gmail.com Sun Dec 14 01:52:34 2008 From: python.leojay at gmail.com (Leo Jay) Date: Sun, 14 Dec 2008 14:52:34 +0800 Subject: Why %e not in time.strftime directives? In-Reply-To: <4943D9AB.7040006@tim.thechases.com> References: <38f9c4ba-d96d-47e1-b718-562bdc6718e9@t26g2000prh.googlegroups.com> <4943D9AB.7040006@tim.thechases.com> Message-ID: <4e307e0f0812132252y35ed5cdep40eabaa54f1d8967@mail.gmail.com> On Sat, Dec 13, 2008 at 11:50 PM, Tim Chase wrote: >> Any special reasons? > > Because it is there (at least on my Debian box)? > But not on windows :( >>> import time >>> time.strftime("%e") '' >>> > tim at rubbish:~$ python > Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) > [GCC 4.2.4 (Debian 4.2.4-1)] on linux2 > Type "help", "copyright", "credits" or "license" for > more information. > > >>> import time > >>> time.strftime('%c') > 'Sat Dec 13 09:35:03 2008' > >>> time.strftime('%e') > '13' > > Taken from[1] > > The full set of format codes supported varies across > platforms, because Python calls the platform C library's > strftime() function, and platform variations are common. > > So if your underlying C implementation of strftime() supports "%e", then > Python will. My guess is that the same applies to time.strftime as it does > to datetime.strftime > > The docs list ones that are fairly cross-platform. However, it would seem > that not all platforms support "%e" > > > -tkc > > > [1] > http://docs.python.org/library/datetime.html#module-datetime > > -- Best Regards, Leo Jay From prologic at shortcircuit.net.au Wed Dec 10 22:17:20 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 11 Dec 2008 13:17:20 +1000 Subject: Python is slow In-Reply-To: <7a1e6b94-1618-470c-a7ed-a2a5ada87d30@w24g2000prd.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <4b0f6c1a-9d3f-4fd7-8506-314d29ee87a8@k36g2000yqe.googlegroups.com> <7a1e6b94-1618-470c-a7ed-a2a5ada87d30@w24g2000prd.googlegroups.com> Message-ID: @em_gui: You are outrightly wrong. Why ? Python's VM is not slow! In fact it's quite fast. What does tend to be slow is sloppy poorly designed code. Django/Turbogears (sorry for any devs reading this) are large frameworks with a lot of complexity - and yes they tend to be a little cumbersome and slow. CherryPy (1) on the other hand is quite fast, but it is not your kitchen-sink type framework as Django and Turbogears tends to be. Before you start making such ridiculous stupid claims about the performance of Python's VM and Python itself actually do some work, do some tests, show us some of your work ? And RYI, I'm the author of a (fairly) general purpose event driven library (framework) with a focus on Component architectures. This is called circuits (2). As well as being an event-driven library which performs really really well, it also has "Web Components" (circuits.lib.web) that make CherryPy look too hard to use and ~4x slower. Yes circuits on decent hardware performs (raw speeds) of ~3000 req/s. I have used circuits to build commercial web applications for clients in conjunction with ExtJS (3) and loading time for the entire app is usually ~1-2s. Data response times are usually in the order of 50-100ms. SLow ? I don't think so. --JamesMils References: 1. http://www.cherrypy.org/ 2. http://trac.softcircuit.com.au/circuits/ 3. http://www.extjs.com/ On Thu, Dec 11, 2008 at 9:39 AM, cm_gui wrote: > You guys are living in denial. > Python is SLOW, especially for web apps. > > Instead of getting mad, why don't get together and come up with a > faster VM/interpreter? > > The emperor doesn't like to be told he is not wearing any clothes? > > > On 10 Dec, 14:48, Luis M. Gonz?lez wrote: >> You are WRONG, WRONG, WRONG!! >> And when I say Wrong, I mean WRONG!!! >> >> And I am not saying that you are confussed. >> I say that you are WRONG! >> >> And when someone says so many times that you are wrong, it is because >> you are WRONG! >> And don't say that you are not wrong, because you are wrong! >> >> You are Wrong. Very Wrong. >> >> On Dec 10, 3:42 pm, cm_gui wrote: >> >> >http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-... >> >> > I fully agree with Krzysztof Kowalczyk . >> > Can't they build a faster VM for Python since they love the language >> > so much? >> >> > Python is SLOW. And I am not comparing it with compiled languages >> > like C. >> > Python is even slower than PHP! > > >> >> > Just go to any Python website and you will know. >> > An example is:http://www2.ljworld.com/ >> > And this site is created by the creators of Django! >> >> > And it is not just this Python site that is slow. There are many many >> > Python sites which are very slow. And please don't say that it could >> > be the web hosting or the server which is slow ? because when so many >> > Python sites are slower than PHP sites, it couldn't be the web >> > hosting. Also, Zope/Plone is even slower. >> >> > Python is slow. Very slow. >> >> > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From aahz at pythoncraft.com Fri Dec 12 23:17:54 2008 From: aahz at pythoncraft.com (Aahz) Date: 12 Dec 2008 20:17:54 -0800 Subject: Python, threading References: Message-ID: In article , SMALLp wrote: > >Hy. I have a problem! I'm making multi thread application (client, >server) using wxPython for GUI, and threading.Thread for threding. > >Clients connect and when they are connected (evry thread handles one >connection) threads change main window. > >I neded tip how to make communication between threeds. http://www.pythoncraft.com/OSCON2001/index.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From gagsl-py2 at yahoo.com.ar Tue Dec 16 03:16:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Dec 2008 06:16:28 -0200 Subject: Memory leak when using a C++ module for Python References: <13db1224-5d6d-4240-8184-ce852e10b422@d36g2000prf.googlegroups.com> Message-ID: En Thu, 11 Dec 2008 15:35:58 -0200, Jaume Bonet escribi?: > This is the function that is visible from python and the one that the > python code calls: > > static PyObject * IMFind (PyObject *self, PyObject *args, PyObject > *kwargs) { > Your function does not call any Python function except PyArg_ParseTupleAndKeywords (which does not modify reference counts). So it's unlikely that this could cause any memory leak. I'd revise how memory is allocated and deallocated on the C++ side. -- Gabriel Genellina From tim at burlyhost.com Wed Dec 31 15:35:14 2008 From: tim at burlyhost.com (Tim Greer) Date: Wed, 31 Dec 2008 12:35:14 -0800 Subject: Why not Ruby? References: Message-ID: <6IQ6l.57340$ly1.11422@newsfe19.iad> Giampaolo Rodola' wrote: > This is not a Ruby group. > I recommend you to go waste your time there. That poster has a frequent habit of cross posting to multiple, irrelevant news groups. There's no rhyme or reason to it. It's best to just filter the guy's posts. -- Tim Greer, CEO/Founder/CTO, BurlyHost.com, Inc. Shared Hosting, Reseller Hosting, Dedicated & Semi-Dedicated servers and Custom Hosting. 24/7 support, 30 day guarantee, secure servers. Industry's most experienced staff! -- Web Hosting With Muscle! From ranjith.priya at gmail.com Fri Dec 19 01:12:42 2008 From: ranjith.priya at gmail.com (Priya Ranjith) Date: Thu, 18 Dec 2008 22:12:42 -0800 (PST) Subject: Openings for Release Management Message-ID: <5487888c-d5ce-41a0-a915-8d70801aeccb@o4g2000pra.googlegroups.com> Position: Build and Release Engineer Experience Required: 2 - 7 yrs Qualification: B.E/M.E/M.C.A/B.Tech Skills Required: 1) Working experience in distributed version control system like Mercurial / Bazar / GIT or Subversion 2) Experience in RBuilder 3) Working experience in creating software appliance. 4) Experience in Python 5) Working experience in Ant / Maven 6) Should posses good communication skills: excellent English, both written and spoken is a must. 7) High level of professionalism The Release Engineer function has the following key areas of responsibility: 1) Continuous improvement of Release processes, methodologies and tools to ensure best quality for both product lines: Community Edition and Professional Edition. 2) Track and support the whole Release cycle, coordinating teams involved in the Release processes: engineering, QA, Beta Testers and Community. 3) Keep people informed about status, contents, dates, etc. 4) Support Senior Management to define the guidelines of whole release product strategy. From gagsl-py2 at yahoo.com.ar Mon Dec 29 21:34:21 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Dec 2008 00:34:21 -0200 Subject: Read-Write Lock vs primitive Lock() References: <277c1be7-2560-4fd6-9610-0b4398dc3719@x16g2000prn.googlegroups.com> Message-ID: En Mon, 29 Dec 2008 08:17:42 -0200, k3xji escribi?: > On 29 Aral?k, 11:52, "Gabriel Genellina" > wrote: >> En Mon, 29 Dec 2008 05:56:10 -0200, k3xji escribi?: >> >> > I ?am trying to see on which situations does the Read-Write Lock >> > performs better on primitive Lock() itself. Below is the code I am >> > using to test the performance: >> > import threading >> > import locks >> > import time >> >> > class mylock(object): >> >> (I'm not convinced your lock is correct) > > No problem.:) > >> > GLOBAL_VAR = 1 >> > #GLOBAL_LOCK = locks.ReadWriteLock() >> > GLOBAL_LOCK = threading.Lock() >> > #GLOBAL_LOCK = mylock() >> > GLOBAL_LOOP_COUNT = 100000 >> > GLOBAL_READER_COUNT = 1000 >> > GLOBAL_WRITER_COUNT = 1 >> >> Only one writer? If this is always the case, you don't need a lock at >> all. > > No just used for testing. It does not matter, what I want to see is > that I want to create a botleneck on readers. Is this a theoretical question? What do your readers/writers actually do? Just reading a global variable does not require any locking. If it is being modified, you either get the previous value, or the new value. >> Note that the thread acquires the lock ONCE, repeats several thousand >> times an assignment to a *local* variable called GLOBAL_VAR (!), finally >> releases the lock and exits. As every thread does the same, they just >> run >> one after another, they never have a significant overlap. > > If I put the for loop outside, in that case, readers will not overlap > at all, and you would be amazed by the numbers for that test. They > indicate primitive lock is faster than read-write lock, as it requires > the lock, executes only one bytecode operation and releases the lock. > So, in order to create a bottlenneck on readers, we need to somehow do > not release the lock immediately. Again, what is your specific use case? why do you think readers will see a bottleneck? > With that, primitive locks perform 10 times better than Read-Write > lock. See above. So what? You don't like such results? The read-write lock in the recipe you posted is rather complex, and isn't obvious whether it is correct or not, and the author doesn't prove it nor provide a reference. I'd stick to the standard Lock object unless I have specific needs. Note that threading.Lock objects are implemented in C and don't have significant overhead (other than the wait itself); even threading.RLock objects are a lot slower. So depending on what you really have to do, the overhead of using a class like ReadWriteLock may be worse than using a standard Lock. >> Hmmm, it's a reader but attempts to modify the value? >> You don't have to protect a read operation on a global variable - so a >> lock isn't required here. > > This is just for testing. Suppose that I am actually reading the > value. I don't understand why a lock is not required? Are you saying > lock is not necesary beacuse GLOBAL_VALUE is an immutable object, if > then, suppose it is not. This is just a test. Suppose GLOBAl_VAR is a > list and we are calling append() on it which is nt an atomic > operation. It doesn't matter whether it is mutable or immutable. Remember that, in Python, a global variable is just a *name* that refers to an object; you either get the old object referred, or the new one. If it is a list and it is being modified "in place", you always get the same list -- its contents may differ from one instant to another so iterating over it isn't safe. That's why I insist on knowing your use case: you may me doing things more complicated than they should. Attached there is a modified test using a shared list. A group of writers append elements; another group of writers pop elements. Readers continuously check the list sanity. The list starts empty, should be empty at the end, and should be equal to range(len(global_list)) at any time. Run the code as-is, with all locks enabled, and it should work fine. Disable the locking in each place, and things start going wrong. >> > What I am doing is: I am creating multiple readers and try to do >> > something. I had assumed that with using primitive Lock() on the above >> > situation, it will create a bottleneck on the rthreads. But the >> > numbers indicate that there are no difference at all. I had >> > implemented my own READ-WRIET lock as can be seen above mylock and >> > also used the one here: code.activestate.com/recipes/502283/. >> >> I hope you now understand why you got the same numbers always. > > Unfortunately, I do not understand anyhing. Each thread in your original code were like this: begin thread; wait for lock; execute something locally; release lock; exit thread; There was no shared state between threads. Even if you fix them to share some variable, they were a single, sequential, piece of code (the inner loop is irrelevant here). Once a thread gets the lock, it just runs to its end. No one waits more than once for the lock. So all of them run sequentially, in arbitrary order, but just one after the other. They never overlap. -- Gabriel Genellina -------------- next part -------------- A non-text attachment was scrubbed... Name: test_locking_k3xji.py Type: text/x-python Size: 2344 bytes Desc: not available URL: From prologic at shortcircuit.net.au Thu Dec 18 20:42:29 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Dec 2008 11:42:29 +1000 Subject: Factoring Polynomials In-Reply-To: <2980024c-e680-4010-b8c4-eccd7fd37b65@a37g2000pre.googlegroups.com> References: <269523e2-eba9-4b6b-b0fb-c5a7deb3ed76@o4g2000pra.googlegroups.com> <2980024c-e680-4010-b8c4-eccd7fd37b65@a37g2000pre.googlegroups.com> Message-ID: On Fri, Dec 19, 2008 at 11:37 AM, Collin D wrote: > Ahh. Great.. that answers a lot of questions. > Originally I was using just a = raw_input('a: ') > And was getting errors because you cant perform mathmatical operations > on strings. >.< > Thanks again! No worries. Please take an hour or two to go through the Python Tutorial at http://docs.python.org/ cheers James From thomasmallen at gmail.com Tue Dec 16 15:22:29 2008 From: thomasmallen at gmail.com (tmallen) Date: Tue, 16 Dec 2008 12:22:29 -0800 (PST) Subject: mod_python resources Message-ID: <78064e7e-ba2c-4959-b5f8-4d1b928bc5fe@y18g2000yqn.googlegroups.com> I'm trying again because I'm stubborn. Maybe the fourth time will be the charm... Are there any good tutorials out there for setting up Apache with mod_python? Thanks, Thomas From robert.kern at gmail.com Sat Dec 6 18:57:56 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 06 Dec 2008 17:57:56 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Terry Reedy wrote: > Rasmus Fogh wrote: >> Dear All, >> >> For the first time I have come across a Python feature that seems >> completely wrong. After the introduction of rich comparisons, equality >> comparison does not have to return a truth value, and may indeed return >> nothing at all and throw an error instead. As a result, code like >> if foo == bar: >> or >> foo in alist >> cannot be relied on to work. >> >> This is clearly no accident. According to the documentation all >> comparison >> operators are allowed to return non-booleans, or to throw errors. >> There is >> explicitly no guarantee that x == x is True. > > You have touched on a real and known issue that accompanies dynamic > typing and the design of Python. *Every* Python function can return any > Python object and may raise any exception either actively, by design, or > passively, by not catching exceptions raised in the functions *it* calls. > >> Personally I would like to get these !@#$%&* misfeatures removed, > > What you are calling a misfeature is an absence, not a presence that can > be removed. That's not quite true. Rich comparisons explicitly allow non-boolean return values. Breaking up __cmp__ into multiple __special__ methods was not the sole purpose of rich comparisons. One of the prime examples at the time was numpy (well, Numeric at the time). We wanted to use == to be able to return an array with boolean values where the two operand arrays were equal. E.g. In [1]: from numpy import * In [2]: array([1, 2, 3]) == array([4, 2, 3]) Out[2]: array([False, True, True], dtype=bool) SQLAlchemy uses these operators to build up objects that will be turned into SQL expressions. >>> print users.c.id==addresses.c.user_id users.id = addresses.user_id Basically, the idea was to turn these operators into full-fledged operators like +-/*. Returning a non-boolean violates neither the letter, nor the spirit of the feature. Unfortunately, if you do overload __eq__ to build up expressions or whatnot, the other places where users of __eq__ are implicitly expecting a boolean break. While I was (and am) a supporter of rich comparisons, I feel Rasmus's pain from time to time. It would be nice to have an alternate method to express the boolean "yes, this thing is equal in value to that other thing". Unfortunately, I haven't figured out a good way to fit it in now without sacrificing rich comparisons entirely. >> and constrain the __eq__ function to always return a truth value. > > It is impossible to do that with certainty by any mechanical > creation-time checking. So the implementation of operator.eq would have > to check the return value of the ob.__eq__ function it calls *every > time*. That would slow down the speed of the 99.xx% of cases where the > check is not needed and would still not prevent exceptions. And if the > return value was bad, all operator.eq could do is raise and exception > anyway. Sure, but then it would be a bug to return a non-boolean from __eq__ and friends. It is not a bug today. I think that's what Rasmus is proposing. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From ldo at geek-central.gen.new_zealand Wed Dec 3 22:52:32 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 04 Dec 2008 16:52:32 +1300 Subject: Multiple equates References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> Message-ID: In message , Cameron Laird wrote: > There's a realm within Pythonia that favors lambdalessness. Why is that? Was Rossum frightened in his cradle by a lambda when he was a baby? Are some people afraid of lambdas the way others are afraid of spiders? From alex at a13x.net Tue Dec 16 17:19:05 2008 From: alex at a13x.net (Aleksandar Radulovic) Date: Tue, 16 Dec 2008 22:19:05 +0000 Subject: mod_python resources In-Reply-To: <78064e7e-ba2c-4959-b5f8-4d1b928bc5fe@y18g2000yqn.googlegroups.com> References: <78064e7e-ba2c-4959-b5f8-4d1b928bc5fe@y18g2000yqn.googlegroups.com> Message-ID: <845b10c50812161419q4289c1eahdde6b44df7c82e41@mail.gmail.com> On Tue, Dec 16, 2008 at 8:22 PM, tmallen wrote: > Are there any good tutorials out there for setting up Apache with > mod_python? Apart from the (clear and concise) information in the mod_python documentation? Starts here: http://www.modpython.org/live/current/doc-html/installation.html Compiling is as easy as: $ ./configure --with-apxs=/usr/local/apache/bin/apxs $ make $ sudo make install (if you have sudo) Configuring Apache is as easy as adding the lines in the apache config file: LoadModule python_module libexec/mod_python.so Alias /py /somedirectory AllowOverride None Order allow,deny Allow from all AddHandler mod_python .py PythonHandler mod_python.publisher PythonDebug On That's about it.. For testing, continue reading the mod_python manual. -- a lex 13 x http://www.a13x.info From steven at REMOVE.THIS.cybersource.com.au Mon Dec 22 20:26:46 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 23 Dec 2008 01:26:46 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> Message-ID: On Mon, 22 Dec 2008 06:58:06 -0800, walterbyrd wrote: > On Dec 21, 12:28?pm, Bruno Desthuilliers > wrote: >> Strange enough, >> no one seems to complain about PHP or Ruby's performances... > > A few years back, there was a certain amount of chest thumping, when > python/django easily beat ror in a benchmark test. Now that ruby is > faster, I guess speed is no big issue. Who was doing this chest-thumping? Fanboys like "r"? Why should you tar all of us with their immaturity? > By the same reasoning, python advocates used to sneer at php because php > constantly broke backward compatibility. Now that python does it, > breaking backward compatibility is no big deal. No, breaking backward compatibility IS a big deal. That's why Python is doing it slowly and carefully: the minimum amount of breakage necessary, and with the Python 2.x series kept going in parallel for at least two additional versions. > I guess unicode support > was not that important, until python caught up to perl. Python has had unicode support for a long time. You just needed to write u'' instead of ''. > I guess, the way it works is: you first assume that python is superior, > then you figure out why. Just keep on trollin'. -- Steven From jstroud at mbi.ucla.edu Sun Dec 14 20:07:20 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 14 Dec 2008 17:07:20 -0800 Subject: Looking for the best way to translate an idiom In-Reply-To: References: Message-ID: drobinow at gmail.com wrote: > > I'm baffled by this discussion. > What's wrong with > a, dontcare, dontcare2 = f() > a = a + 1 > > Simple, clear, and correct. 1. This can't apply to a generalized f() that may return an arbitrary number of arguments >= len(num_assignments_you_care_about). 2. The example chosen was misleading. You don't want to add 1 to the first element of the tuple, you want to move the "start" of the returned tuple up 1 and start assignment on the left from there. James From nebson at gmail.com Sat Dec 27 23:53:57 2008 From: nebson at gmail.com (Ben Bush) Date: Sat, 27 Dec 2008 20:53:57 -0800 (PST) Subject: assignment with [:] Message-ID: Hi, I saw this line of code on a recent post: a1[:] = [x*3 for x in a1] Could somebody tells me what the [:] means? I can't find it anywhere. See context below if needed: On Dec 26, 4:46 pm, Tim Chase wrote: > > What does *not* work is > > 3 * [0,1,2] > > As you know, this gives > > [0,1,2,0,1,2,0,1,2] > > What I am hoping for is > > [0,3,6] > > I see that I can use > > numpy.multiply(3,range(3)) > > but this seems overkill to me. Can you tell I am coming to Python from > > Matlab? > > The common way to do this is just > > a1 = [0,1,2] > a2 = [x * 3 for x in a1] > > or, if you need a1 to be done in place: > > a1[:] = [x*3 for x in a1] > > -tkc From pydecker at gmail.com Fri Dec 26 08:37:46 2008 From: pydecker at gmail.com (Peter Decker) Date: Fri, 26 Dec 2008 08:37:46 -0500 Subject: Easy-to-use Python GUI In-Reply-To: References: Message-ID: On Thu, Dec 25, 2008 at 1:46 AM, Gabriel Genellina wrote: > En Wed, 24 Dec 2008 21:47:07 -0200, Joel Koltner > escribi?: > >> Is there an easy-to-use, "function"-based cross-platform GUI toolkit for >> Python out there that's a little more sophisticated than EasyGui? > > Try Dabo http://dabodev.com/ +1 for Dabo. I tried just about everything listed by others before I found Dabo a couple of years ago. Since then creating the GUI for my apps is the easiest part of the process. Now I can focus on what my app is supposed to do, rather than how to get a certain widget to look the way I need it to look. -- # p.d. From ldo at geek-central.gen.new_zealand Sun Dec 7 02:34:39 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 07 Dec 2008 20:34:39 +1300 Subject: Don't you just love writing this sort of thing :) References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: In message , Arnaud Delobelle wrote: > * you give the impression of being arrogant; Oddly enough, I wasn't the one who started by criticizing other people's code. I have no ego about my code; I gladly accept criticisms. But perhaps some other people are not so thick-skinned and do not like getting as they give... From rafesacks at gmail.com Mon Dec 1 03:30:03 2008 From: rafesacks at gmail.com (Rafe) Date: Mon, 1 Dec 2008 00:30:03 -0800 (PST) Subject: Do more imported objects affect performance References: Message-ID: On Dec 1, 7:26?am, "Filip Gruszczy?ski" wrote: > I have following question: if I use > > from module import * > > instead > > from module import Class > > am I affecting performance of my program? I believe, that all those > names must be stored somewhere, when they are imported and then > browsed when one of them is called. So am I putting a lot of "garbage" > to this storage and make those searches longer? > > -- > Filip Gruszczy?ski Why use it if you don't need it? Your post implies a choice and the '*' import can really make things muddy if it isn't actually necessary (rare). Why not just import the module and use what you need? It is way easier to read/debug and maintains the name-space. - Rafe From jstroud at mbi.ucla.edu Sun Dec 28 05:53:35 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 28 Dec 2008 02:53:35 -0800 Subject: assignment with [:] In-Reply-To: References: Message-ID: Ben Bush wrote: > On Dec 26, 4:46 pm, Tim Chase wrote: >>> What does *not* work is >>> 3 * [0,1,2] >>> As you know, this gives >>> [0,1,2,0,1,2,0,1,2] >>> What I am hoping for is >>> [0,3,6] >>> I see that I can use >>> numpy.multiply(3,range(3)) >>> but this seems overkill to me. Can you tell I am coming to Python from >>> Matlab? >> The common way to do this is just >> >> a1 = [0,1,2] >> a2 = [x * 3 for x in a1] >> >> or, if you need a1 to be done in place: >> >> a1[:] = [x*3 for x in a1] There is some subtlety here. The latter says to empty the list assigned to the name "a1" and refill it with the products. Other references to the same list will now reflect this operation. This procedure is not equivalent to reassigning the name "a1". For example: py> a = [1, 2, 3] py> a1 = a py> a1[:] = [x*3 for x in a1] py> a1 [3, 6, 9] py> a1 [3, 6, 9] Whereas: py> a = [1, 2, 3] py> a1 = a py> a1 [1, 2, 3] py> a1 = [x*3 for x in a1] py> a1 [3, 6, 9] py> a [1, 2, 3] James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From castironpi at gmail.com Wed Dec 17 02:34:02 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 16 Dec 2008 23:34:02 -0800 (PST) Subject: How to modify a program while it's running? References: <7xtz93qrog.fsf@ruckus.brouhaha.com> Message-ID: <228c638f-66a0-44d0-95ab-d4d31793b58b@e1g2000pra.googlegroups.com> On Dec 16, 11:47?pm, Paul Rubin wrote: > Joe Strout writes: > > So I'd like to restructure my app so that it can stay running and stay > > logged in, yet I can still update and reload at least most of the > > code. ?But I'm not sure what's the best way to do this. ?Should I move > > the reloadable code into its own module, and then when I give my bot a > > "reload" command, have it call reload on that module? ?Will that work, > > and is there a better way? > > If you are on Linux, an alternative might be to start a new version of > your program in a separate process, then transfer the open connections > from the old process to the new ones through Unix domain sockets. ?The > SCM_RIGHTS message lets you pass file descriptors around between > processes. ?I've never tried this myself but have always wanted to. ?I > think someone submitted a patch for Python's socket module a year or > so ago to support that operation, but I don't know if it was accepted. > You could always apply it yourself. > > Generally, trying to hot-patch code is messy and dangerous even in > systems that were designed for it. Sorry for the repeated posts, but sockets made me think of pickling. (You can't pickle sockets.) >>> class A: pass ... >>> a= A() >>> s= pickle.dumps( a ) >>> class A: pass ... >>> pickle.loads( s ) <__main__.A instance at 0x00B53328> So, 's' was unpickled to be an instance of a new class. Probably not the most elegant. Just make sure the sockets are preserved in a separate object. For yet another option, exec the code, and assign it to a method in a class. >>> class A: ... def f( self ): pass ... >>> a= A() >>> a.f() >>> exec "def f( self ): print 'new f'" >>> A.f= f >>> a.f() new f From gagsl-py2 at yahoo.com.ar Fri Dec 26 09:40:05 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 26 Dec 2008 12:40:05 -0200 Subject: Process with ftplib References: Message-ID: En Fri, 26 Dec 2008 11:07:30 -0200, nemo escribi?: > There seems something wrong when I use multiprocessing.Process with > ftplib, [...] > It works well but when I using the Process module, something seems > wrong: > ftp = qftp(host, port, user, password) > p = multiprocessing.Process(target = ftp.connect) > p.join() > ftp.ftp.pwd() #after join, i think a connection has > made, but it throws an exception > This give me a 'NoneType object has no attribute sendall' exception. I > wondered why? After p.join(), the second process has finished. The global variable ftp isn't shared between them - so it does not reflect the changes made in the other process. An introductory article to multiprocessing: http://www.doughellmann.com/articles/CompletelyDifferent-2007-10-multiprocessing/index.html -- Gabriel Genellina From sjmachin at lexicon.net Mon Dec 1 00:59:09 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 30 Nov 2008 21:59:09 -0800 (PST) Subject: incorrect line reported in traceback References: Message-ID: On Dec 1, 4:47?pm, "Patrick Stinson" wrote: > Is there any reason why the last item in the traceback is one frame > below the top of the stack? It would be great to show the real line in > my editor... Maybe your anonymous [HINT!] editor is confused. Do you get the same problem when you run your script at the shell prompt? From pruebauno at latinmail.com Thu Dec 4 09:50:31 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Thu, 4 Dec 2008 06:50:31 -0800 (PST) Subject: funny generator behaviour References: Message-ID: On Dec 4, 8:00 am, Edvin Fuglebakk wrote: > I have written a generator that puzzles me: > > The generator is supposed to create ordered selections of a set of > objects. repetition of objects is allowed and the selections should be > of a size determined by a pramter to the generator. > > Now, if I try to accummulate the generated selections into a list I get > some peculiar behaviour that I hope maybe some of you can help me > understand: > > Help much appreciated > -Edvin > > #straightforward acumulation. Does not give the expected result > >>> d=[] > >>> for f in orderedCombinations([1,2],3): > ... d.append(f) > ... > >>> d > [[1], [2], [1], [2], [1], [2], [1], [2]] > > #accumulating shallow copies of the genereated combinations works: > >>> d=[] > >>> for f in orderedCombinations([1,2],3): > ... d.append(f[:]) > ... > >>> d > [[1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 2, 2], [2, 1, 1], [2, 1, 2], [2, > 2, 1], [2, 2, 2]] > > #The generator: > def orderedCombinations(pool, k): > """ > Generator yielding ordered selections of size k with repetition from > pool. > """ > > if k == 1: > for m in pool: > yield [m] > > if k > 1: > > for m in pool: > for combo in orderedCombinations(pool, k-1): > > #insert and pop to avoid copying entire list > combo.insert(0,m) > yield combo > combo.pop(0) Functional style (like the recursion you are using) and mutable datastructures are hard to reason about. This version works for me: def orderedCombinations(pool, k): """ Generator yielding ordered selections of size k with repetition from pool. """ if k == 1: for m in pool: yield [m] if k > 1: for m in pool: for combo in orderedCombinations(pool, k-1): yield [m]+combo From mblume at socha.net Mon Dec 8 13:03:26 2008 From: mblume at socha.net (mblume) Date: 08 Dec 2008 18:03:26 GMT Subject: Equivalent of 'wget' for python? References: Message-ID: <493d616e$0$771$5402220f@news.sunrise.ch> Am Mon, 08 Dec 2008 08:22:55 -0800 schrieb Robert Dailey: > Hi, > > I'm looking for a portable way to download ZIP files on the internet > through Python. I don't want to do os.system() to invoke 'wget', since > this isn't portable on Windows. I'm hoping the core python library has a > library for this. Note that I'll be using Python 3.0. > > Thanks. > IIRC, wget also exists for Windows. Regards Martin From p.f.moore at gmail.com Sat Dec 13 12:27:23 2008 From: p.f.moore at gmail.com (Paul Moore) Date: Sat, 13 Dec 2008 09:27:23 -0800 (PST) Subject: Best way of debigging a C extension References: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> <6b20568d-8ce9-4240-8f83-b579c241d9a9@l33g2000pri.googlegroups.com> Message-ID: On 11 Dec, 23:57, Christian Heimes wrote: > Paul Moore schrieb: > > That's what I thought. I was just hoping that using a debug build of > > an extension would be usable with a standard release build of Python, > > as that's what will be easy for most people to set up. > > A debug build changes large parts of the ABI. Every PyObject struct > gains additional fields, lots of checks are added to Python's memory > allocation system and asserts are enabled. Debug extensions have a _d > suffix for a very good reason. We aren't just trying to make *your* life > harder. :) Ah. That's the bit of information I was missing. If the ABI changes, it's a wonder my hacking of my extension to build in debug mode worked at all! I suspect that if I could get distutils to let me specify that it keeps debug symbols in a release-mode build, I could get what I needed. But the arcane contortions needed to get distutils to do this are beyond me :-) I'll stick with printf - it's served me well enough so far :-) Thanks for clarifying, Paul. From Scott.Daniels at Acm.Org Thu Dec 4 15:37:04 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 04 Dec 2008 12:37:04 -0800 Subject: Good introductory book? In-Reply-To: <56616d73-312c-44e5-a484-5fb3e0054613@x38g2000yqj.googlegroups.com> References: <56616d73-312c-44e5-a484-5fb3e0054613@x38g2000yqj.googlegroups.com> Message-ID: Kottiyath wrote: > .... If you want more of examples of how everything is done, then Python > Cookbook is another one. > You can get many recipes at http://code.activestate.com/recipes/langs/python/ > too - the book is just selected recipes from this site.... Actually, it is significantly more than "just selected recipes" -- the recipes are picked in subject groups, edits applied, and introductions to each section are written by someone chosen for their expertise in that area. You defintely get more than the list of recipes to examine. --Scott David Daniels Scott.Daniels at Acm.Org From rt8396 at gmail.com Mon Dec 22 13:44:32 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 10:44:32 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: Steve Holden > What makes you assume this is a zero-sum game, and that Python won't > survive if any other language becomes popular. Every language borrows > from those that came before it. Terms like "outright plagiarism" don't > encourage rational debate, and make you seem like a troll who is more > interested in stirring up controversy than actually doing things to help > promote the language. This is a war Steve, and i will explain why. Python does not need to compete with perl, lisp, C, basic, etc, etc. WHY, well because python is SO radically different than those languages. Ruby on the other hand, took most from python, the only difference is Ruby's full OO integration.(12.method()). Since Ruby is so similar to python we must consider that some people who would have found only python in this niche now could go to Ruby. I am for choices, but this is out and out robbery! Of course we must stand on the shoulders of greater minds than our own to get ahead, but using someone's knowledge against them is wrong. If Ruby want's to incorporate so many Pythonian ideas into their language, at least put a note in the tutorial giving credit to Guido for his wisdom. Don't use our ideas and then bash python in the next breath! > I have an article about the Zen coming up in "Python Magazine" so I > won't steal its thunder. Suffice it to say that people take the Zen far > too seriously. Anyone who does so undermines their own credibility as a > Python commentator. This isn't a war. Stop being childish. I was speaking to the loyalty of Pythonista's. Of course we are not really going to slay mats, come on Steve, get real! > If all you want from a language is speed, go use C. I would avoid > assembly language though, since a modern optimizing C compiler will > often beat an assembly language programmer for execution speed, and the > programming time will definitely be shorter. But to make speed the > be-all and end-all is a witless approach. Speed is definitely not why > dynamic languages' popularity is increasing. Speed *is* still relevant > in certain areas, and completely irrelevant in others. Come on Steve, i am NOT saying speed is the only thing that matters here! But it is very important. I never compared Python to C, that is madness. But it must be better, faster, smarter than it's direct competition(ruby)... you agree?? > Much more of this kind of tripe and nobody will read what you write > anyway. You will hear the plonking of a hundred thousand newsreaders > every time you post. Oh Steve... Listen, my words are ment as a wake-up-call to all who still love Python, and i believe you are one of them. Maybe old age has slowed your hand, that's OK, Us "youngsters" will take the helm. And be serious, do you really think this group is read by "hundreds-of- thousands of news readers? I wish it were, but I highly doubt it. From ken at seehart.com Tue Dec 16 08:11:38 2008 From: ken at seehart.com (Ken Seehart) Date: Tue, 16 Dec 2008 05:11:38 -0800 Subject: Structure using whitespace vs logical whitespace In-Reply-To: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> References: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> Message-ID: <4947A90A.1070808@seehart.com> cmdrrickhunter at yaho.com wrote: > I've been trying to search through the years of Python talk to find an > answer to this, but my Googlefu is weak. > > In most languages, I'll do something like this > > xmlWriter.BeginElement("parent"); > ----xmlWriter.BeginElement("child"); > ----------xml.Writer.Characters("subtext"); > ----xmlWriter.EndElement(); > xmlWriter.EndElement(); > > Where the dashes are indentation (since some newsgroup handlers don't > do tabs well). XML writing is just an example. > Yes, I hate that too. IMO Newsgroup and email clients should not remove indentation. > In general, I'm using indentation to show logical flow through code. > Python's choice to give semantic meaning to whitespace prevents me > from doing such things. What was once reserved for logical use is now > used syntactically. In 90% of cases, its not needed, and whitespace > significance seems to be pretty effective. In that last 10%, however, > I've been frustrated many times. > When I first learned python I was occasionally bothered by this. Since then I have gotten used to it and would not have it any other way. I certainly would not consider changing the language for this. I consider the benefits of a uniform meaning of whitespace and the corresponding consistency of indentation style, as well as the lack of punctuation, to be well worth the price. Also, I have found over the years that, for reasons described below, that this "price" effectively drops to zero. > I've been using python for a few years, and gotten around this in one > way or another, but now I want to get other who work with me to pick > up Python. All newbies to Python have trouble with the idea of > whitespace sensitivity, but how can I convince them that "it just > works better" when I have this construct which I want to use but > can't. > I disagree with the generalization that "All newbies to Python have trouble with the idea...". I would say that perhaps most newbies that have experience with whitespace neutral languages experience some initial discomfort, which is expected for any change from what one is used to. I suspect that very few people who are new to programming dislike whitespace sensitivity. > Has anybody found a way to emulate this behavior? I've often done it > by opening an expression for the whole thing, but there's a lot of > tasks where a single expression just isn't sufficient (such as things > with assignment). > This would depend on the specific case. In general, if you are writing lots of code that contains structure other than program control structure, you probably are missing an opportunity to use a data-driven approach. In other words, ideally the structure in your python code should be /only /program control structure, in which case the indentation will be exactly where you would want it to be. For that other 10%, you probably should code your content as data (either in an external file or as data literals in your code). The case in point is your example: xmlWriter.BeginElement("parent"); ----xmlWriter.BeginElement("child"); ----------xml.Writer.Characters("subtext"); ----xmlWriter.EndElement(); xmlWriter.EndElement(); I would use a template system such as Genshi instead, so that kind of structure would not need to be in my python code in the first place. I know that this xmlWriter code is just an example, but I think that the principle I am describing really does apply more or less universally. If you are expressing nested structure other than program control structure, you should be expressing your structure as data. Here's another solution to your example that is more generally applicable to other situations: content = (element, "parent", [ (element, "child", [ (characters, "subtext"), ] ), ] ) do_something_with(content) (Sorry if the above indentation has been removed by evil software....) In this case I have made the code data-driven, but include the data in my python code. This means you have the extra task of implementing *do_something_with()* but that is usually a trivial task, and worth the effort IMO because it makes the structure more readable and easier to modify. It also separates content from implementation, which is also a really good idea. For example, if at some point in the future I decide to use something else instead of *xmlWriter *to process the data, I can do so by changing the implementation of *do_something_with()*. > PS. In my opinion the solution would be to have the option of entering > a "whitespace insensitive" mode which uses C style {} and ;. The > token to enter it could be as complicated as you want (in fact, it may > make sense to make it complicated to discourage use unless it's really > advantageous). I'd sugest {{ and }} or something bigger like {={ } > =}. Only two problems: 1) I'm sure it would offend Guido's sense of > language aesthetics 2) I'm sure the idea has been hashed over on this > newsgroup to death... hence prefering a workaround instead. > A definitive "Yes" to both 1 and 2 :-) And I wouldn't even consider my proposed solutions to be "workarounds" with respect to the alleged problem of syntactical whitespace. I would want to use the same approach in C or Java simply because I prefer a data-driven approach where appropriate. Python's container literals make it particularly easy to express data in your code. It just so happens that there is a high correlation between the temptation to use indentation for non-programmatic structure and the appropriateness of a data-driven implementation. The problem with adding redundant syntactical forms (such as your proposed {{...}}), is that it complicates the language. This has two effects: 1. In order to master the language you have to learn more (mastering the language includes the ability to read other peoples code as well as writing new code). 2. It produces greater variance in style based on personal preference. Generally, code is easier to read when everyone uses consistent style. One of the things that people like about python is the relative infrequency of special characters. This gives python a certain flavor. I happen to like this flavor a lot. Some people don't, and I recommend Perl to them. But switching between two distinct dialects of python does not seem like a wise idea. I hope this helps. Ken Seehart From petercable at gmail.com Thu Dec 11 23:43:42 2008 From: petercable at gmail.com (petercable at gmail.com) Date: Thu, 11 Dec 2008 20:43:42 -0800 (PST) Subject: =?windows-1252?Q?Re=3A_how_to_convert_=91=5Cxf0=27_to_0xf0_=3F?= References: Message-ID: <87b67976-b762-42db-9dee-21f3346e0a1a@g17g2000prg.googlegroups.com> On Dec 12, 4:48?am, chengang.beij... at gmail.com wrote: > int('\xf0',16) doesn't work, any way to do that? hex(ord('\xf0')) HTH, Pete From skip at pobox.com Mon Dec 29 07:30:21 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 29 Dec 2008 06:30:21 -0600 Subject: multiply each element of a list by a number In-Reply-To: <49580B2E.8050009@ncf.ca> References: <4955e7be$0$4066$ba4acef3@news.orange.fr> <49580B2E.8050009@ncf.ca> Message-ID: <18776.49885.802621.444836@montanaro-dyndns-org.local> >>>>> "Colin" == Colin J Williams writes: Colin> skip at pobox.com wrote: >> For extremely short lists, but not for much else: >> >> % for n in 1 10 100 1000 10000 100000 ; do >> > echo "len:" $n >> > echo -n "numpy: " >> > python -m timeit -s 'import numpy ; a = numpy.array(range('$n'))' 'a*3' >> > echo -n "list: " >> > python -m timeit -s 'a = range('$n')' '[3*x for x in a]' >> > done >> len: 1 >> numpy: 100000 loops, best of 3: 11.7 usec per loop >> list: 1000000 loops, best of 3: 0.698 usec per loop >> len: 10 >> numpy: 100000 loops, best of 3: 11.7 usec per loop >> list: 100000 loops, best of 3: 2.94 usec per loop >> len: 100 >> numpy: 100000 loops, best of 3: 12.1 usec per loop >> list: 10000 loops, best of 3: 24.4 usec per loop >> len: 1000 >> numpy: 100000 loops, best of 3: 15 usec per loop >> list: 1000 loops, best of 3: 224 usec per loop >> len: 10000 >> numpy: 10000 loops, best of 3: 41 usec per loop >> list: 100 loops, best of 3: 2.17 msec per loop >> len: 100000 >> numpy: 1000 loops, best of 3: 301 usec per loop >> list: 10 loops, best of 3: 22.2 msec per loop >> >> This is with Python 2.4.5 on Solaris 10. YMMV. Colin> Your comment is justified for len= 100 Colin> or 1,000 but not for len= 10,000 or 100,000. Look again at the time units per loop. Colin> I wonder about the variability of the number of loops in your Colin> data. That's how timeit works. It runs a few iterations to see how many to run to get a reasonable runtime. Colin> I have tried to repeat your test with the program below, but it Colin> fails to cope with numpy. I stand by my assertion that numpy will be much faster than pure Python for all but very short lists. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From Alvin.ONeal at gmail.com Mon Dec 22 15:28:08 2008 From: Alvin.ONeal at gmail.com (Alvin ONeal) Date: Mon, 22 Dec 2008 13:28:08 -0700 Subject: I always wonder ... In-Reply-To: References: Message-ID: > > What really is a troll? > *troll* /v.,n./ [From the Usenet group *alt.folklore.urban *] To utter a posting on Usenetdesigned to attract predictable responses or flame s. Derives from the phrase "trolling for newbies" which in turn comes from mainstream "trolling", a style of fishing in which one trails bait through a likely spot hoping for a bite. The well-constructed troll is a post that induces lots of newbies and flamers to make themselves look even more clueless than they already do, while subtly conveying to the more savvy and experienced that it is in fact a deliberate troll. If you don't fall for the joke, you get to be in on it. Some people claim that the troll is properly a narrower category than flame bait , that a troll is categorized by containing some assertion that is wrong but not overtly controversial. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeremiah.dodds at gmail.com Thu Dec 11 02:15:00 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Thu, 11 Dec 2008 02:15:00 -0500 Subject: Python is slow In-Reply-To: <49408E2E.1000302@mrabarnett.plus.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <49408E2E.1000302@mrabarnett.plus.com> Message-ID: <12cbbbfc0812102315y243977f8m85f851ef06329857@mail.gmail.com> Does anybody else think it's really funny when people argue over which language used for _web apps_ is fastest? I mean, I'm not aware of any language that's slow enough to make it noticeable compared to say, network latency or database access. I guess you might notice if you're not caching any content, and your language of choice is _really_ bad at generating strings in a for loop. As far as "slow" goes, the clear winner(?) is Ruby, and there are _plenty_ of sites written in ruby that aren't slow. The ones that are slow aren't slow because of ruby - they're slow primarily because of people not knowing how to write a database schema, as far as I can tell. There seems to be a lot of stigma against python as being a "slow" language, which I suppose it is when measured in certain ways - however it's more than fast enough for me, and is certainly fast enough for web-apps (I run a few sites on top of CherryPy, and have _never_ had an issue with them, even with a minor redditing on one of them). I had a freelance gig once porting an image-manipulation algorithm from C++ to python. It was a horrible mess of C++ code, but ran very fast (and did exactly what my employer needed it to do). Porting it to python in a literal led to (IIRC) a 10x speed-down. Changing that to more idiomatic python made it only 3-5x slower than the C++. After translating that into, I think, PyRex, it was barely slower than the original code. Certainly well within the "acceptable" range. When I did the above, I was really pretty new to python. If I did the same job again, I'd probably get better results, just from understanding the language better. But I digress. The only places that I'm aware of where performance would be enough of an issue to make Python a poor choice are places where using python would _never_ be considered anyhow. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Fri Dec 5 19:26:36 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 5 Dec 2008 16:26:36 -0800 (PST) Subject: Python 3.0 automatic decoding of UTF16 References: <5u8o06xbqf.ln2@joeserver.homelan.net> <0149b28c$0$20670$c3e8da3@news.astraweb.com> Message-ID: <7c150038-3c2d-4c3c-bb1a-66c8fde57d22@40g2000prx.googlegroups.com> On Dec 6, 10:35?am, Steven D'Aprano wrote: > On Fri, 05 Dec 2008 12:00:59 -0700, Joe Strout wrote: > >> So UTF-16 has an explicit EOF marker within the text? > > > No, it does not. ?I don't know what Terry's thinking of there, but text > > files do not have any EOF marker. ?They start at the beginning > > (sometimes including a byte-order mark), and go till the end of the > > file, period. > > Windows text files still interpret ctrl-Z as EOF, or at least Windows XP > does. Vista, who knows? This applies only to files being read in an 8-bit text mode. It is inherited from MS-DOS, which followed the CP/M convention, which was necessary because CP/M's file system recorded only the physical file length in 128-byte sectors, not the logical length. It is likely to continue in perpetuity, just as standard railway gauge is (allegedly) based on the axle-length of Roman chariots. None of this is relevant to the OP's problem; his file appears to have been truncated rather than having spurious data appended to it. From Scott.Daniels at Acm.Org Fri Dec 19 15:28:13 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 19 Dec 2008 12:28:13 -0800 Subject: Factoring Polynomials In-Reply-To: References: <5dfe1cf3-530d-4e31-833e-e26db85611be@d36g2000prf.googlegroups.com> Message-ID: <-5mdncPe2KRcntHUnZ2dnUVZ_iydnZ2d@pdx.net> Tim Rowe wrote: > 2008/12/18 Scott David Daniels : > >> def quadsolve(a, b, c): >> try: >> discriminant = sqrt(b**2 - 4 * a * c) > > The discriminant of a quadratic is more usually just the b**2 - 4 * a > * c part, not the square root of it. Testing that for negative, zero > or positive avoids the need to use an exception for a normal case. Absolutely right. Blame the oversight on my old CPU-stingy days. When the CPU was slow, avoiding a sqrt here or there (if you didn't have a sqrt opcode) was so important that I do it without thinking these days. Since I still have that disease, perhaps the variable should be renamed root_discriminant. As for the testing, I find using math.sqrt catches the negative cases and raises an exception by itself, leaving only the issue of whether or not to return a pair or singleton. Usually for my purposes, I'd let the exception fly and not return an (?the?) empty tuple. --Scott David Daniels Scott.Daniels at Acm.Org From scsoce at gmail.com Mon Dec 29 01:01:38 2008 From: scsoce at gmail.com (scsoce) Date: Mon, 29 Dec 2008 14:01:38 +0800 Subject: why cannot assign to function call Message-ID: <495867C2.7080807@gmail.com> I have a function return a reference, and want to assign to the reference, simply like this: >>def f(a) return a b = 0 * f( b ) = 1* but the last line will be refused as "can't assign to function call". In my thought , the assignment is very nature, but why the interpreter refused to do that ? thks From sturlamolden at yahoo.no Fri Dec 12 10:55:41 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 07:55:41 -0800 (PST) Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> Message-ID: <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> On Dec 12, 3:54 pm, Steve Holden wrote: > sturlamolden wrote: > > On Dec 12, 3:08 pm, Marc 'BlackJack' Rintsch wrote: > > >> No bug because a mutation *is* attempted. ``a += x`` calls `a.__iadd__` > >> which *always* returns the result which is *always* rebound to the name > >> `a`. Even with mutable objects where `__iadd__()` simply returns > >> `self`! > > > No, a mutation is not attempted, even if __iadd__() always returns a > > value. If a rebinding of a member to the same member is attempted, the > > tuple should not raise an exception. The tuple should check that it is > > actually being *mutated* before it raises any exception. There is an > > attempted write to the tuple, but not an attempted mutation of the > > tuple. The tuple should tell the difference. Immutability does not > > imply inwriteability, if the write operation changes nothing. But the > > tuple raises an exception on any write attempt. > > OK, so if you regard the current behavior as a bug explain how to modify > the tuple's __iadd__ method and the coding of the INPLACE_ADD operator. > At least in pseudocode. > > Criticism is easy. Now demonstrate that it's *informed* criticism. > Enough of the "should". I am always suspicious of suggestions that say > what the interpreter "should" or "should not" do. It makes it sound as > though you can wave a magic wand to achieve the desired behavior. > The interpreter "should not" have a GIL. > The tuple "should" check that > it is actually being mutated. How? In Python it would be something similar to: def __setitem__(self, index, value): if _buf[index] is not value: # given that _buf is the tuple's internal buffer raise TypeError, 'tuple' object does not support item assignment It should be the tuple's __setitem__ that was invoked here, not __iadd__, or the parser is faulty. S.M. From joel.hedlund at gmail.com Fri Dec 19 11:26:37 2008 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Fri, 19 Dec 2008 17:26:37 +0100 Subject: weird dict problem, how can this even happen? In-Reply-To: References: <01584e96$0$20656$c3e8da3@news.astraweb.com> Message-ID: Joel Hedlund wrote: > First off, please note that I consider my problem to be solved, many > thanks to c.l.p and especially Duncan Booth. But of course continued > discussion on this topic can be both enlightening and entertaining as > long as people are interested. So here goes: heh, nothing like a wall of text to kill off interest I guess. :-) But thank you all for your time and helpful advice! Aand happy holidays! /Joel From sturlamolden at yahoo.no Sat Dec 13 15:26:59 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 13 Dec 2008 12:26:59 -0800 (PST) Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> <87iqpoc1l0.fsf@mulj.homelinux.net> Message-ID: <4155583a-1f6d-4fca-8cf1-7fa809e6d448@q30g2000prq.googlegroups.com> On 13 Des, 02:20, Hrvoje Niksic wrote: > > tmp = mytuple.__getitem__(0) > > tmp = tmp.__iadd__(1) > > mytuple.__setitem__(0, tmp) # should this always raise an exception? > > What do you mean by "a sane parser"? ?This is exactly what happens in > current Python. ? Yes, but Steve Holden was suggesting mytuple.__iadd__ would be invoked. > The decision to also rebind > the result of __i*__ methods continues to baffle me. ? Python methods always have a return value, even those that seem to do not - they silently return None. Thus, __iadd__ must return self to avoid rebinding to None. From jerry.carl.mi at gmail.com Sun Dec 28 09:05:27 2008 From: jerry.carl.mi at gmail.com (jerry.carl.mi at gmail.com) Date: Sun, 28 Dec 2008 06:05:27 -0800 (PST) Subject: math module for Decimals References: <251111d8-a48a-45e3-a744-16fdb729fa33@i20g2000prf.googlegroups.com> <016729e4$0$6988$c3e8da3@news.astraweb.com> Message-ID: Hi Steven... thanks for your kind and extensive reply. Lots of good food for thought. I know it's easy to complain about lack of functionality, but it really was not my intention. Python is very cool as it is and I still know too little about it to even suggest anything. I just thought maybe I was missing something. Sure it would make my life much easier if i had a full set of Decimal (c)math functions and I suppose there are quite a few folks who would like it as well. *** It's not that it's 100% necessary, it just makes things easier. *** Just the fact that at least 3 people already tried to write a decimal math module speaks for how desired and how difficult it is. It's really just the goniometric functions that I am missing most at the moment, so maybe I can figure it out with help of what you said plus the already existing imperfect modules. Meantime maybe this discussion will caught Guido's eye... ;-) And btw I do expect that Python becomes better than Mathematica one day because it's free and open :-) Maybe when Wolfram retires ;-) Thanks again! From exarkun at divmod.com Wed Dec 10 09:05:50 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 10 Dec 2008 09:05:50 -0500 Subject: StringIO in 2.6 and beyond In-Reply-To: Message-ID: <20081210140550.20272.346887012.divmod.quotient.19016@ohm> On 10 Dec 2008 11:58:37 GMT, Bill McClain <20080915.20.wmcclain at spamgourmet.com> wrote: >On 2008-12-10, ajaksu wrote: >> On Dec 9, 5:24?pm, Bill McClain <20080915.20.wmccl... at spamgourmet.com> >> wrote: >> > On 2008-12-09, MRAB wrote: >> > >> > > In Python 2.x unmarked string literals are bytestrings. In Python 3.x >> > > they're Unicode. The intention is to make the transition from 2.x to 3.x >> > > easier by adding some features of 3.x to 2.x, but without breaking >> > > backwards compatibility (not entirely successfully!). >> > >> > It is a bit ugly. In 2.6 StringIO won't take bytestrings, so I apply u'x'. But >> > in 3.0 u'x' will be gone and I'll have to change the code again. > >> Try: > >> from __future__ import unicode_literals > >That works for: > > output.write('First line.\n') > >...but not for: > > print('Second line.', file=output) > >Maybe a combination of this and functools.partial as was suggested before. At >least the necessary edits would be at the top of the program. See http://bugs.python.org/issue4618, there's a comment with a workaround for this problem. Jean-Paul From fetchinson at googlemail.com Sat Dec 20 20:32:05 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 20 Dec 2008 17:32:05 -0800 Subject: PIL on 3.x? In-Reply-To: <3892784c-ddf4-4451-bcfd-dbc58b9b55f8@e1g2000pra.googlegroups.com> References: <3892784c-ddf4-4451-bcfd-dbc58b9b55f8@e1g2000pra.googlegroups.com> Message-ID: >> Does anyone know if PIL will be ported to the 3.x branch? > > Have you considered e-mail to the author? No, I haven't because in my experience open source software authors prefer to keep discussion of their software on mailing lists, forums, etc, where others can benefit from the answers too. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From kirk at daycos.com Fri Dec 12 14:58:02 2008 From: kirk at daycos.com (Kirk Strauser) Date: Fri, 12 Dec 2008 13:58:02 -0600 Subject: (Very Newbie) Problems defining a variable References: <878wqlz27z.fsf@daycos.com> <7f7e8811-4043-40d4-8aa4-f44e1d255632@o4g2000pra.googlegroups.com> Message-ID: <87r64dxj1x.fsf@daycos.com> At 2008-12-12T19:20:52Z, John Machin writes: > (1) you meant "if balance > threshold:" balance >= threshold. We both mistyped. :-) > (2) sequential search can be very fast if the sequence is in > descending order of probability of occurence ... you might like to > consider reversing the order Actually, I just wanted to point out a simplified version of the exact same algorithm. Given enough RAM and if the speed was indeed critical, you could turn that into a tuple of interest rates and jump straight to rate[balance] in O(1). -- Kirk Strauser The Day Companies From rt8396 at gmail.com Sun Dec 21 12:34:41 2008 From: rt8396 at gmail.com (r) Date: Sun, 21 Dec 2008 09:34:41 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> <6r6hpfFfb643U3@mid.uni-berlin.de> <494E6FDA.4070401@mrabarnett.plus.com> Message-ID: RTFM, use as much python code and optimize with C where needed, problem solved! From pavlovevidence at gmail.com Sat Dec 6 16:18:09 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 6 Dec 2008 13:18:09 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> <8b8d1fb3-f49e-49bf-8cfe-eeee5ed16109@r37g2000prr.googlegroups.com> Message-ID: <39750dd7-2135-4839-95ef-ab99b5ab60c2@l42g2000yqe.googlegroups.com> On Dec 6, 9:15?am, "Russ P." wrote: > On Dec 6, 4:32?am, Andreas Waldenburger wrote: > > > > > On Sat, 6 Dec 2008 04:02:54 -0800 (PST) bearophileH... at lycos.com wrote: > > > > class C: > > > ? ? def $method(arg): > > > ? ? ? ? $value = arg > > > > (Note there's no point after $, it's not currently possible). > > > Ruby uses @ and @@ for similar purposes. > > > I agree that the code looks worse, but also shorter to read and write, > > > so in lines of code that use many instance attributes, that short $ > > > syntax helps keep the line shorter. So I may grow to accept this > > > sugar... > > > But that is not the way Python is meant to work. There are several > > tennets in the Zen of Python that don't chime well with this approach. > > "self" is a speaking identifier, "$" isn't. > > Is "@" a "speaking identifier? How about "#" and "!="? Last I heard, > they were all part of Python. None of them are identifiers. $, used as proposed, would be. (Then again, _ is an identifier.) Carl Banks From greg at cosc.canterbury.ac.nz Tue Dec 9 02:04:38 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 09 Dec 2008 20:04:38 +1300 Subject: how to get a beep, OS independent ? In-Reply-To: References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> Message-ID: <6q6jf8Fau4iiU2@mid.individual.net> Duncan Booth wrote: > If I'm logged in to one of my servers in a large datacentre then I don't what > that system to beep as that would be pretty useless. It also might cause the datacentre operators some consternation when one of their servers starts mysteriously beeping... -- Greg From aisaac at american.edu Mon Dec 1 14:12:38 2008 From: aisaac at american.edu (Alan G Isaac) Date: Mon, 01 Dec 2008 14:12:38 -0500 Subject: end of print = lower productivity ? In-Reply-To: References: Message-ID: I actually trust that the developers had good reasons for this change, but I think it is silly to argue that it is costless. The question is, what is the cost-benefit trade-off? One obvious cost is that working at the interpreter prompt is now slightly less convenient. Just because the cost is small does not mean it should not be offset by a benefit. I am less sympathetic to the suggestion that there is an inconvenience when working in an editor, but clearly some people find one. My preferred transition would have been to retain the `print` statement but add a `printf` function (i.e., the new `print` function). Presumably many would find this a repulsive redundancy and a needless maintenance headache. Alan Isaac From manu3d at gmail.com Thu Dec 11 16:41:33 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 11 Dec 2008 13:41:33 -0800 (PST) Subject: Preventing execution of a method References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> <764daeef-bfbe-411a-8521-bb114321e4ac@b38g2000prf.googlegroups.com> <19304f8c-e34f-4aa9-8df2-6a7d3553007a@e1g2000pra.googlegroups.com> <2eed8876-94d2-4304-88a5-eb4a78b4f41d@33g2000yqm.googlegroups.com> <307fe197-1b42-4305-af0e-94b7ebe3ce70@r15g2000prh.googlegroups.com> <49417c59$0$8491$426a74cc@news.free.fr> Message-ID: On Dec 11, 7:48?pm, Bruno Desthuilliers wrote: > > or to provide read-only > > access. I.e. right now I'm working on the graphical client which > > potentially could be rewritten entirely by the users. It is necessary > > and perfectly reasonable for the client module to access some of the > > objects to be represented graphically, but those objects shouldn't be > > modifiable by it. > > Why so ? At worst, they'll break everything. -IF- the application was single-user yes, it wouldn't be a big deal. But as it is potentially multi-user, I don't want one party to corrupt the application for everybody else. Say I'm writing a multi-player version of a card game (I'm not). For the sake of the argument let's imagine that the players are all playing on the same computer, taking turns. However, they are using a GUI written by one of the players who unbeknown to them, has written it to modify the game state appropriately and give himself the right cards at the right time. If the game state is read-only and can only be queried but not modified by the GUI, the player can rewrite the GUI but cannot cheat. Isn't this a legitimate concern? Manu From ldo at geek-central.gen.new_zealand Thu Dec 4 19:27:35 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 05 Dec 2008 13:27:35 +1300 Subject: Don't you just love writing this sort of thing :) References: Message-ID: In message , Cong Ma wrote: > The "if ... != None" is not necessary... "if PatchDatePat.search(f)" is > OK. I don't do that. From prologic at shortcircuit.net.au Tue Dec 30 19:15:50 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 10:15:50 +1000 Subject: [ANN]: circuits-1.0b1 released! In-Reply-To: <1230681603.9684.17.camel@jmk> References: <1230681603.9684.17.camel@jmk> Message-ID: On Wed, Dec 31, 2008 at 10:00 AM, John Krukoff wrote: > I'm curious, you've a number of comparisons to Twisted on your site FAQ > section, but this sounds like a much closer project to Kamaelia > (http://www.kamaelia.org/Home). Are these actually similar or am I > missing something important that differentiates circuits? Glad you asked! Twisted and circuits aren't really that similar - they have very different architectures/designs. circuits is simpler :) They are similar only in that they are both event/asynchronous frameworks. circuits also has asynchronous/non-blocking sockets (TCPServer, TCPClient, UDPServer and UDPClient) as well as simple implementations of EchoServer, Telnet and others. There are also implementations of the HTTP and IRC protocols (all following the component design). With respect to Kamaelia, I have read about this and looged over their material briefly. I can only say one thing. circuits and Kamaelia share nothing in common really. Kamaelia claims to be of a Component design/architecture - but to be frank it's overly complicated - and I'd hate to write systems like that :) cheers James From saju.pillai at gmail.com Wed Dec 31 06:26:53 2008 From: saju.pillai at gmail.com (Saju Pillai) Date: Wed, 31 Dec 2008 03:26:53 -0800 (PST) Subject: select.select and socket.setblocking References: <495a661d$0$11384$5fc30a8@news.tiscali.it> <495b34d8$0$11387$5fc30a8@news.tiscali.it> Message-ID: <3652a957-eec6-494c-bd37-d150018bc0ed@p2g2000prf.googlegroups.com> On Dec 31, 2:01?pm, Francesco Bochicchio wrote: > Grant Edwards ha scritto: > > > On 2008-12-30, Francesco Bochicchio wrote: > > >> 3. AFAIK (sorry, I feel acronym-ly today ;), there is no difference in > >> select between blocking and non-blocking mode. The difference is in the > >> recv (again, assuming that you use TCP as protocol, that is AF_INET, > >> SOCK_STREAM), which in the blocking case would wait to receive all the > >> bytes that you requested, > > > No, in blocking mode it will wait to receive _some_ data (1 or > > more bytes). ?The "requested" amount is strictly an upper > > limit: recv won't return more than the requested number of > > bytes, but it might return less. > > Uhm. In my experience, with TCP protocol recv only returned less than > the required bytes if the remote end disconnects. I always check the What if the sending end actually sent less than you asked for ? -srp > returned value of recv and signal an error if the read bytes are less > than the expected ones, but this error is never occurred (and its about > 20 years that I use sockets in various languages and various flavor of > unix and occasionally on windows. Maybe ?have always been lucky ? :-) > > And, on some unices ?system call recv also returns when a signal > interrupts the syscall, but I half-remember reading that python recv in > such a case repeat the system call by itself ... although this might be > only my desire ... > > > In non-blocking mode, it will always return immediately, either > > with some data, no data (other end closed), or an EAGAIN or > > EWOULDBLOCK error (I forget which). > > >> [...] I myself tend to avoid using non-blocking sockets, since > >> blocking sockets are much easier to handle... > > > That depends on whether you can tolerate blocking or not. ?In > > an event-loop, blocking is generally not allowed. > > What I usually do, when I cannot block is: > > - use socket in blocking mode > - do a select with a very small timeout and do a recv only if the select > returns with input events > - (with TCP) do a recv for the exact amount of bytes that I expect ( > this mean having a user protocol that carries the message size in the > header, but this is usually the case ). > > This usually worked for me. > > If my process (or thread) has only to deal with socket I/O, I make a > blocking select, and then make an 'exact' recv on whichever socket the > select signals. > > Ciao > ---- > FB From Rick at youtellme.com Thu Dec 25 23:18:29 2008 From: Rick at youtellme.com (Rick van Hattem) Date: Fri, 26 Dec 2008 05:18:29 +0100 Subject: How to stop subprocesses from copying listening sockets In-Reply-To: References: Message-ID: <200812260518.30063.Rick@youtellme.com> On Friday 26 December 2008 04:05:43 Roy Smith wrote: > In article , > > Rick van Hattem wrote: > > Recently I've started building a program that spawns new processes when > > requested via http, since the http interface doesn't need to be fancy > > I've just used the BaseHTTPServer module for this, but... it seems I'm > > running into a little problem. When spawning a new process (which forks > > itself into a daemon, but isn't too relevant in this case) the listening > > socket is copied to the new process. > > The standard solution to this problem is to close all descriptors after > forking and before doing the exec. You can tell subprocess.Popen() to do > this by call it with "close_fds=True". Thank you very much, I completely forgot about the close_fds argument. That will fix the problem nicely :) From jeremy+complangpython at jeremysanders.net Mon Dec 1 06:53:03 2008 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Mon, 01 Dec 2008 11:53:03 +0000 Subject: Best way to dynamically get an attribute from a module from within the same module References: <18097f03-dfc9-4671-954a-2871ca0c1910@d42g2000prb.googlegroups.com> Message-ID: Rafe wrote: > I guess, in the end, I'd use getattr() because it feels more pythonic, > and more basic. I got pretty deep in to learning python before I had > to learn what the globals() dict could do for me. Why not store your individual classes inside another class or keep them in a dict? That would be clearer, would not mess around with global namespace, and more pythonic IMHO. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From jura.grozni at gmail.com Wed Dec 3 11:22:19 2008 From: jura.grozni at gmail.com (azrael) Date: Wed, 3 Dec 2008 08:22:19 -0800 (PST) Subject: python an sqlite objects Message-ID: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> is it possible to save a python object into a sqlite database as an atribute of type BLOB From digitig at gmail.com Fri Dec 12 14:49:40 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 12 Dec 2008 19:49:40 +0000 Subject: (Very Newbie) Problems defining a variable In-Reply-To: <7f7e8811-4043-40d4-8aa4-f44e1d255632@o4g2000pra.googlegroups.com> References: <878wqlz27z.fsf@daycos.com> <7f7e8811-4043-40d4-8aa4-f44e1d255632@o4g2000pra.googlegroups.com> Message-ID: 2008/12/12 John Machin : > (2) sequential search can be very fast if the sequence is in > descending order of probability of occurence ... you might like to > consider reversing the order I find it hard to imagine a bank with so many interest rate thresholds that the search of the table is likely to be a significant contribution to the run time! > (3) for a much longer table, binary search using a function from the > bisect module could be considered > (4) in practice, the "default" action would not be "return 0.0"; > perhaps something along these lines: > > if balance < -overdraft_limit: > raise Exception(...) That's more likely to be in the withdrawal routine (and is probably best not handled as an exception, because it's pretty much normal flow). If a bank provided a service such as the one implemented by this program, there'd be no need for it to know about overdraft limits because it's not making actual transactions. Why would they increase coupling unneccesarily? -- Tim Rowe From robert.kern at gmail.com Mon Dec 22 16:28:22 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 22 Dec 2008 15:28:22 -0600 Subject: Python's popularity In-Reply-To: <6rae73F9s47U1@mid.individual.net> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <6ra8t0F925rU1@mid.individual.net> <29feda0d-6432-4cb9-8809-e4d4a7798601@e1g2000pra.googlegroups.com> <6rae73F9s47U1@mid.individual.net> Message-ID: je.s.te.r at hehxduhmp.org wrote: > r wrote: >> We see where you stand. And also see that by removing your comments >> from the archive in 5 days, how small your acorns really are. > > What is "the archive", Google Groups? You do realize that's not the > entirety of Usenet, correct? It's the predominant archive of USENET, but it's not the only one that respects your X-No-Archive header. GMane, for example, will respect it if the list admin has not requested otherwise. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From toby at telegraphics.com.au Mon Dec 1 22:47:47 2008 From: toby at telegraphics.com.au (toby) Date: Mon, 1 Dec 2008 19:47:47 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: <92196910-c849-45d6-a5e9-4d16e1f569ee@x38g2000yqj.googlegroups.com> On Dec 1, 5:24?am, budden wrote: > Mathematica is a great language, but: > 1. it is too slow > 2. It is often hard to read > 3. It gives sence to every keystroke. You press escape by occasion and > it goes in a code as a new > symbol, w/o error. Nasty. > 3. I know 5-th version. It does not allow to track the source as SLIME > does. This feature as absolutely > necessary for serious development Worst of all, it's proprietary, which makes it next to useless. Money corrupts. > > So, in fact, Mathematica do not scale well IMO. From gamersunit at gmail.com Thu Dec 11 14:02:25 2008 From: gamersunit at gmail.com (Gregory Plantaine) Date: Thu, 11 Dec 2008 11:02:25 -0800 (PST) Subject: Find Files in a Folder Between 2 Dates References: <4c54b6c5-ae4d-4b89-8c6d-940c96de29bb@n33g2000pri.googlegroups.com> <94cd4bd7-a69f-48ba-90f7-382014844905@g1g2000pra.googlegroups.com> <862567e3-4469-43ae-b41b-1a1817124f50@k36g2000pri.googlegroups.com> Message-ID: <6b3bed68-3036-4e05-9571-e7dce0db2cff@r36g2000prf.googlegroups.com> On Dec 5, 3:14?pm, John Machin wrote: > On Dec 6, 9:41?am, GregoryPlantaine wrote: > > > That worked perfectly! > > > Thanks Tim! > > > Since we can print the files, does that mean the list of files is in a > > tuple, or something? ?Would there be a way to further split up the > > file names? > > > For example, now that the files are processed into the list, we want > > to look through that list to find different filetypes. > > > files > > > C:\Folder\File_200812051439.111 > > C:\Folder\File_200812051539.222 > > *DANGER* It looks like you are interested in the timestamps that are > embedded in the names of the files. Tim's code assumes [reasonably > given that your problem description was ambiguous and had no examples > of good and bad results] that you are interested in the last > modification time of the file. You may say "same thing". Yes, same > thing, until somebody sucks a file into a text editor, messes with it, > and saves it again. No, Murphy's Law has not been repealed. > > > > > Can we split up .111 files? > > > Actually, where would I look something like this up? > > In the Library Reference Manual ... there are all sorts of goodies in > the os and os.path modules e.g. like those used by Tim; make sure you > read the docs on the methods Tim used so that you understand what's > happening. > > HTH, > John Thanks for the advice John! I was going though the Manual, but I'm having some trouble figuring out how to iterate through each line. So from the same example, we've already created a list called "lists". Now how do I iterate through each line? For eachline in lists Find all .111 files. From rcdailey at gmail.com Mon Dec 8 17:56:19 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 8 Dec 2008 14:56:19 -0800 (PST) Subject: RuntimeError: dictionary changed size during iteration Message-ID: <274eb282-1635-40ca-95af-b82271c57802@v4g2000yqa.googlegroups.com> I'm executing the following code: def CopyBoost( libraries ): pass def CopyEmotionFX( libraries ): pass def Copy( library, aliases ): pass stuff = vars() for key in stuff: print( key, '--', stuff[key] ) I get the following error message: ('CopyEmotionFX', '--', ) Traceback (most recent call last): File "C:\IT\work\jewett\depends.py", line 12, in for key in stuff: RuntimeError: dictionary changed size during iteration Why is this happening? From starsareblueandfaraway at gmail.com Thu Dec 4 08:54:07 2008 From: starsareblueandfaraway at gmail.com (Roy H. Han) Date: Thu, 4 Dec 2008 08:54:07 -0500 Subject: RELEASED Python 3.0 final In-Reply-To: <1a73e3be-1753-4178-8091-eaa890b3e07e@l42g2000yqe.googlegroups.com> References: <1a73e3be-1753-4178-8091-eaa890b3e07e@l42g2000yqe.googlegroups.com> Message-ID: <6a5569ec0812040554h7f5bca4btd4d32c28ed04a0b6@mail.gmail.com> Hi, This is great, however, the link to the What's New page appears to be broken. http://docs.python.org/dev/3.0/whatsnew/3.1.html RHH On Thu, Dec 4, 2008 at 8:37 AM, Istvan Albert wrote: > Congratulations on a fantastic work! > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.dev.9 at gmail.com Fri Dec 12 14:42:24 2008 From: python.dev.9 at gmail.com (mercado) Date: Fri, 12 Dec 2008 14:42:24 -0500 Subject: Testing against different versions of Python Message-ID: <2678157f0812121142y2afcf3bey254dd2b74f61e423@mail.gmail.com> What is the best way to go about testing against different versions of Python? For example, I have 2.5.2 installed on my machine (Ubuntu Hardy 8.04), and I want to test a script against 2.5.2 and 2.5.1 (and possibly other versions as well). Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrea.francia at REMOVE-FROM-HERE.ohoihihoihoih.TO-HERE.gmx.it Tue Dec 16 14:13:00 2008 From: andrea.francia at REMOVE-FROM-HERE.ohoihihoihoih.TO-HERE.gmx.it (Andrea Francia) Date: Tue, 16 Dec 2008 19:13:00 GMT Subject: Where is a good open source python project to be used as example? Message-ID: <05T1l.219074$FR.507685@twister1.libero.it> I'm looking for a python project to use as example to learning python. The project should have these features: 1. is almost fully unit tested 2. use consistently the code convention recommended by PEP 8 3. it's elements are almost fully documented Extra point features are: 4. building, assembling, and release automation Did you know where are such projects? From aleksandr.goretoy at gmail.com Sat Dec 27 18:31:27 2008 From: aleksandr.goretoy at gmail.com (alex goretoy) Date: Sat, 27 Dec 2008 17:31:27 -0600 Subject: parsing csv files class In-Reply-To: References: <49562755.6050205@byoteki.com> Message-ID: I might as well add a UnicodeReader and UnicodeWriter and support for passing delimiter in from other classes. At the same time. Anyone have a good csv class I can pick thru? I'm planning on posting my mysql adn curl classes that I use in my projects I just want to make them better and have less error. On Sat, Dec 27, 2008 at 5:18 PM, alex goretoy wrote: > It's main concern is to grab the file into the buffer for use in other > classes. The self.soc.me_him is just so I know when its ENTERING or EXITING > in that function when I run it in terminal. It's prints it in color. My main > concern right now is to add error handling. I'm still learning how to use > assert and yield, but I got try,except down pat. All this class does is > grabs the file either from http or local storage into a buffer and I use > that in other classes. I want to add support for creating creating csv as > well. I read the doc on csv and will try some things out soon. Thanks for > helping me. > > > On Sat, Dec 27, 2008 at 2:15 PM, Gabriel Genellina > wrote: > >> En Sat, 27 Dec 2008 11:02:13 -0200, Gary M. Josack >> escribi?: >> >>> alex goretoy wrote: >>> >> >> I know it's messy with all those self.soc.* functions, but it works in >>>> one of my current project. I just want to make it more pythonic I also want >>>> to add capability for makeing csv file if I give it input like: >>>> 1234,something nice, hey this is something nice >>>> 2468,something else, something else >>>> >>> >> reader = csv.reader(file(filename, "rb")) >>>> try: >>>> for row in reader: >>>> self.buffer.append(row) >>>> s,a=[],{} >>>> >>> >> Do you know that there is a csv module in the standard library already? >>> >> >> I'd say he already knows, he even used it in the code. >> >> To Alex G.: I didn't understand what's the purpose of this class. Probably >> you want to do too much things in the same place; looks like it has multiple >> concerns, and that's not a good idea usually. >> >> -- >> Gabriel Genellina >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > > -- > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > > > > -- > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > -- ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Thu Dec 4 12:00:49 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 4 Dec 2008 12:00:49 -0500 Subject: Python 3 read() function In-Reply-To: References: Message-ID: <16651e80812040900j257fe2acjf5d8817811d32da6@mail.gmail.com> On Thu, Dec 4, 2008 at 11:48 AM, Christian Heimes wrote: > Cro wrote: >> vContent = io.StringIO() >> vContent = huge.read() # This line takes hours to process !!! > > Do you really mean io.StringIO? I guess you want io.BytesIO() .. I don't think it matters. Here's a quick comparison between 2.5 and 3.0 on a relatively small 17 meg file: C:\>c:\Python30\python -m timeit -n 1 "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" 1 loops, best of 3: 36.8 sec per loop C:\>c:\Python25\python -m timeit -n 1 "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" 1 loops, best of 3: 33 msec per loop That's 3 orders of magnitude slower on python3.0! -- Jerry From bblais at bryant.edu Fri Dec 26 20:30:43 2008 From: bblais at bryant.edu (Brian Blais) Date: Fri, 26 Dec 2008 20:30:43 -0500 Subject: multiply each element of a list by a number In-Reply-To: References: Message-ID: <6E23195F-E079-4F22-829E-ECBEBE891D3B@bryant.edu> On Dec 26, 2008, at 19:05 , Robert.T.Lynch at seagate.com wrote: > but this seems overkill to me. Can you tell I am coming to Python > from Matlab? if you're coming from matlab, then you should think of python lists more like cell arrays than matrices: you can have lists of arbitrary data types, so multiply is not going to work in the matrix way. check out http://web.bryant.edu/~bblais/bryant/numerical_computing/ python_matlab.pdf but more importantly, you need to install numpy (which has the matrix stuff) and scipy (which has the scientific packages). What I do is go to www.enthought.com and they have a single-download package geared specifically for scientists. bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From geon at post.cz Sat Dec 27 09:08:24 2008 From: geon at post.cz (Pavel Kosina) Date: Sat, 27 Dec 2008 15:08:24 +0100 Subject: tkinter 3.0 multiple keyboard events together In-Reply-To: <7b5e466c-d75d-4e71-b559-f8a0d3718094@r15g2000prd.googlegroups.com> References: <600d4b68-6fe2-4c2c-b425-1a739430bb54@s9g2000prg.googlegroups.com> <7b5e466c-d75d-4e71-b559-f8a0d3718094@r15g2000prd.googlegroups.com> Message-ID: <495636D8.3080807@post.cz> janislaw napsal(a): > Use google to find the appropriate site, or browse this site, there > are plenty of examples. You may want to examine the code I wrote to > you to catch the idea: > #---------------------- > import Tkinter > import pprint > > tk = Tkinter.Tk() > f = Tkinter.Frame(tk, width=100, height=100) > msg = Tkinter.StringVar() > msg.set('Hello') > l = Tkinter.Label(f, textvariable=msg) > l.pack() > f.pack() > > keys = set() > > def keyPressHandler(event): > keys.add(event.char) > display() > > def keyReleaseHandler(event): > keys.remove(event.char) > display() > > def display(): > msg.set(str(keys)) > > f.bind_all('', keyPressHandler) > f.bind_all('', keyReleaseHandler) > > f.mainloop() > Is this really the most simple solution how to do this in Tkinter? Is there nothing cleaner "build inside"? This solution has disadvantage that after you release one key, that the function keyPressHandler stopped to be called by the other pressed keys. I would have not to build moving the player in KeyPresshandler, but on another new function that would have to read periodically "keys" and to act afterwards.... I really tried to search for words mentioned in this subject, but nothing, not even this solution, was found by me. PK From joe.hrbek at gmail.com Wed Dec 3 13:40:14 2008 From: joe.hrbek at gmail.com (Joe Hrbek) Date: Wed, 3 Dec 2008 10:40:14 -0800 (PST) Subject: using os.walk to generate objects Message-ID: The code below works (in linux), but I'm wondering if there is a better/easier/cleaner way? It works on directory trees that don't have a lot of "."s in them or other special characters. I haven't implemented a good handler for that yet, so if you run this in your system, choose/make a simple directory structure to use as your root for os.walk(). Also, you must start from the top most directory level, like /test. /tmp/test as a root will not work (yet). :) I wanted to know if I could use os.walk() to construct an object based off of a directory tree. So, the following path: "/test/home/user" would get converted into "test.home.user" and I could then work with it that way in my python program, attaching attributes to those "directories" that I could use to keep track of things. This was more of an exercise in learning than anything, I wanted to see if I could do it. I've never used "type()" before to create new objects, so really that was the point. Can I do this an easier way though? ---- import os from os.path import join, getsize def remove_hidden(dirlist): """For a list containing directory names, remove any that start with a dot""" dirlist[:] = [d for d in dirlist if not d.startswith('.')] def recurse_dir_tree(context,dirs): """recurse through tree structure and add attributes as necessary""" for directory in dirs: fixedDir = directory.replace('.','_').lower() #print ("directory is:%s" % fixedDir) newAttrObj = type(("%s" % fixedDir),(),{}) if newAttrObj.__name__: #print newAttrObj.__name__ #print "context is "+context print "tree."+context setattr(eval ("tree."+context),newAttrObj.__name__,newAttrObj) class Tree(object): def __init__(self,wd): self.__name__ = wd pathroot = '/test' tree = Tree(pathroot) for root, dirs, files in os.walk(pathroot): tree.currentRoot = ".".join(map(str,root.split('/')[1:])) tree.currentRoot = tree.currentRoot.lower() print "currentRoot:" + tree.currentRoot if pathroot == root: #this is the start of the object tree tree.baseRoot = pathroot.split('/')[1] newAttrObj = type(("%s" % tree.currentRoot),(),{}) setattr(tree,newAttrObj.__name__,newAttrObj) #print dirs remove_hidden(dirs) #print dirs if dirs: recurse_dir_tree(tree.currentRoot,dirs) From geekmail at usenot.de Tue Dec 2 15:44:02 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Tue, 2 Dec 2008 21:44:02 +0100 Subject: Reverse zip() ? References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> Message-ID: <20081202214402.4a8a0cde@usenot.de> On Tue, 02 Dec 2008 21:12:19 +0100 Stefan Behnel wrote: > Andreas Waldenburger wrote: > > [snip] > > This is of course trivial to do via iteration or listcomps, BUT, I > > was wondering if there is a function I don't know about that does > > this nicely? > > I think you're asking about zip(): > > >>> l=[1,2,3] > >>> zip(l,l) > [(1, 1), (2, 2), (3, 3)] > >>> zip(*zip(l,l)) > [(1, 2, 3), (1, 2, 3)] > So I am. That sure was weird. Thanks for the quick and somewhat surreal help. Need I say that between posting this question and reading your reply I set out to implement this wonder-function? :) /W -- My real email address is constructed by swapping the domain with the recipient (local part). From gdamjan at gmail.com Mon Dec 15 19:44:15 2008 From: gdamjan at gmail.com (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Tue, 16 Dec 2008 01:44:15 +0100 Subject: Structure using whitespace vs logical whitespace References: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> Message-ID: > In most languages, I'll do something like this > > xmlWriter.BeginElement("parent"); > ----xmlWriter.BeginElement("child"); > ----------xml.Writer.Characters("subtext"); > ----xmlWriter.EndElement(); > xmlWriter.EndElement(); > > Where the dashes are indentation (since some newsgroup handlers don't > do tabs well). XML writing is just an example. Well, XML beeing just an example.. but still for XML in Python you probably want to use some XML templating library like Genshi. And for other stuff there are probably similar sollutions. -- ?????? ( http://softver.org.mk/damjan/ ) war is peace freedom is slavery restrictions are enablement From google at mrabarnett.plus.com Thu Dec 18 09:17:07 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 18 Dec 2008 14:17:07 +0000 Subject: re.match() performance In-Reply-To: <755bd716-f5f6-4953-87a7-04ee148c3298@i18g2000prf.googlegroups.com> References: <755bd716-f5f6-4953-87a7-04ee148c3298@i18g2000prf.googlegroups.com> Message-ID: <494A5B63.6060005@mrabarnett.plus.com> Emanuele D'Arrigo wrote: > Sorry for the previous post, hit the Enter button by mistake... here's > the complete one: > > Hi everybody! > > I've written the code below to test the differences in performance > between compiled and non-compiled regular expression matching but I > don't quite understand the results. It appears that the compiled the > pattern only takes 2% less time to process the match. Is there some > caching going on in the uncompiled section that prevents me from > noticing its otherwise lower speed? > [snip] Yes, the regular expression is compiled and cached internally. From steven at REMOVE.THIS.cybersource.com.au Mon Dec 8 21:41:47 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 09 Dec 2008 02:41:47 GMT Subject: Rich Comparisons Gotcha References: Message-ID: On Mon, 08 Dec 2008 14:24:59 +0000, Rasmus Fogh wrote: > For my personal problem I could indeed wrap all objects in a wrapper > with whatever 'correct' behaviour I want (thanks, TJR). It does seem a > bit much, though, just to get code like this to work as intended: > alist.append(x) > print ('x is present: ', x in alist) > > So, I would much prefer a language change. I am not competent to even > propose one properly, but I'll try. You think changing the language is easier than applying a wrapper to your own data??? Oh my, that's too funny for words. -- Steven From gagsl-py2 at yahoo.com.ar Tue Dec 9 01:58:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Dec 2008 04:58:50 -0200 Subject: [Python 2.x] Pickling a datetime.tzinfo subclass instance? References: Message-ID: En Mon, 08 Dec 2008 12:34:03 -0200, Cong Ma escribi?: > I'm writing a program that pickles an instance of a custom subclass of > datetime.tzinfo. I followed the guides given in the Library Reference > (version > 2.5.2, chapter 5.1.6), which contain the note: > > "Special requirement for pickling: A tzinfo subclass must have an > __init__ > method that can be called with no arguments, else it can be pickled but > possibly > not unpickled again. This is a technical requirement that may be relaxed > in the > future." > > I tried this with an example "FixedOffset" subclass instance given in the > Example section in the manual. It indeed failed to unpickle. To work > around > this, I found two possible solutions: > 1. Modify the __init__ method so that it takes optional arguments with > default > values; Doing that still works with 2.6 and 3.0 > 2. Implement the __getinitargs__ method so that it does the opposite of > __init__: returning a tuple from the instance's internal state that can > be used > to re-initialize an instance, retaining the old value. In fact, it doesn't matter *what* it returns, as far as they're valid arguments to __init__ > My questions: > 1. Is the "technical limitation" fixed in version 2.6 or 3.0? I can't > check it > for myself now... Python.org seems down and I can't find the docs. No, they behave the same (odd) way. > 2. To stick with version 2.5, which of the above 2 methods is better? > Both seems > to unpickle to the correct result, but are there subtle side-effects? > Or there > are better solutions? I'd use method 1, just because the __getinitargs__ are useless. -- Gabriel Genellina From ethan at stoneleaf.us Mon Dec 8 15:38:33 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 08 Dec 2008 12:38:33 -0800 Subject: datetime and the rich-companison operators In-Reply-To: <47c890dc0812080952q32adc09etbd5d4c1601914b98@mail.gmail.com> References: <493CCFBC.90104@stoneleaf.us> <47c890dc0812080952q32adc09etbd5d4c1601914b98@mail.gmail.com> Message-ID: <493D85C9.8040901@stoneleaf.us> Chris Rebert wrote: > On Sun, Dec 7, 2008 at 11:41 PM, Ethan Furman wrote: > >>Greetings All! >> >>I am implementing a NullDate class in order to mirror dates and datetimes >>that have no value (yes, this is for my dbf module :) >> >>I'm still a bit fuzzy about class methods, hashing, and __new__, but my >>question of the moment is this: it seems to me that with two dates or >>datetimes, they should either be equal, or one should precede the other, and >>this can be accomplished quite handily with __cmp__... so does anyone know >>why the rich comparisons were used in the datetime module? Was it simply a >>style choice, or is something being handled that __cmp__ couldn't cope with? > > > Probably because __cmp__ was removed in Python 3.0, thus requiring the > use of the rich comparison methods in its place. > See the earlier thread entitled "Python 3 __cmp__ semantic change?". > > Cheers, > Chris > Thanks, Chris! ~ethan~ From rileyrgdev at gmail.com Mon Dec 1 03:29:03 2008 From: rileyrgdev at gmail.com (Richard Riley) Date: Mon, 01 Dec 2008 09:29:03 +0100 Subject: Emacs vs. Eclipse vs. Vim References: Message-ID: Roy Smith writes: > Clay Hobbs wrote: >> The first real text editor I used was Vim, which I actually started >> using about a year ago. I've looked at Emacs and it just looks >> confusing. > > I've been using emacs for so many years (um let's see, it's got to be close > to 25 years now; first saw it on Columbia's TOPS-20 systems in the early > 80's) that my fingers know what they're doing without my even thinking > about it. In fact, I used to work with another emacs nut. Every so often, > one of use would watch the other do something and ask, "What was that?". > Inevitably, neither of us could evoke the keystrokes we had just typed. We > would just re-do it, and watch our fingers to see what we typed. It didn't > even have to be on a keyboard; we could air-type it, and that was good > enough. > > In any case, the basic logic behind emacs is pretty simple. C-F is forward > one character. C-B is back one character. C-N is Next line. C-P is > Previous line. It's worth pointing out to people making "loony" signs here that the arrow keys work too .... From clp at rebertia.com Mon Dec 1 16:37:42 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 1 Dec 2008 13:37:42 -0800 Subject: Python introspection and namespace weird question In-Reply-To: References: <47c890dc0812011037u64076950o186af7477269cc0a@mail.gmail.com> Message-ID: <47c890dc0812011337v7495a176s8fb29b62f2f2ad17@mail.gmail.com> On Mon, Dec 1, 2008 at 12:23 PM, Rayene Ben Rayana wrote: > Thanks Chris, > > Yeah it is kinda meta thing. My app allows to create a scene (a set of GUI > objects). A scene can be saved as a python script. And, it can be loaded > again using execfile(). > > each GUI object has a label. So, in the script scene, declaring an object in > a scene file should look like this: > > red_car = MyVehicleClass(label = 'red_car') > > But, I wanted to simplify the syntax of scene files and avoid repetition so > it would look like > > red_car = MyVehicleClass() > > with the label attribute automatically set to the name of the corresponding > variable. > I tried your locals().iteritems tip and it works perfectly. > > The question now is: Given what I just explained, do you still think it is > bad programming to do that ? Should I better use the first syntax ? Assuming the object declarations are all at the module-level and you have some rule for dealing with objects with multiple "names", using the trick I outlined but with globals() instead of locals() seems reasonable, albeit a bit of a hack, but since this is just a script, that seems acceptable. IMHO, it's an OK trade-off in order to comply with the DRY (Don't Repeat Yourself) principle in this case. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Cheers, > > Rayene, > > I want to use that to simplify the syntax of the > > On Mon, Dec 1, 2008 at 7:37 PM, Chris Rebert wrote: >> >> On Mon, Dec 1, 2008 at 6:04 AM, Rayene Ben Rayana >> wrote: >> > Hello everybody, >> > >> > Is there an easy way to do something like this in python ? >> > >> >>>> red_car = MyVehicleClass() >> >>>> car = red_car >> >>>> car.labels() >> > ['red_car' , 'car' ] >> > >> > In other words, does an instance has access to its name pointers ? >> >> In short, No. (Cue another debate over whether Python uses call-by-X >> semantics...) >> >> Typically people who want to do such things actually want/should use a >> dictionary mapping string keys to instance values instead. >> >> Note that in certain limited cases, voodoo involving the locals() or >> globals() built-in functions or the `inspect` module can work, but not >> in the common general case. But generally these techniques are >> considered bad style and kludgey unless you're writing a debugger or >> something equally meta, with using a dictionary as explained >> previously being much preferred. >> >> For example, for your particular code above, the following happens to >> work: >> [name for name, obj in locals().iteritems() if obj is car] #==> >> ['red_car' , 'car' ] >> >> But this will only give the names in the current function of the >> particular car object. Likewise, globals() works only for module-level >> names, and the `inspect` module's magic only works for names in >> calling functions (i.e. those below the current one in the callstack). >> >> Cheers, >> Chris >> -- >> Follow the path of the Iguana... >> http://rebertia.com >> >> > >> > Thanks in advance, >> > >> > Rayene >> > >> > >> > -- >> > http://mail.python.org/mailman/listinfo/python-list >> > >> > From cadmuxe at gmail.com Mon Dec 8 09:24:15 2008 From: cadmuxe at gmail.com (cadmuxe) Date: Mon, 8 Dec 2008 22:24:15 +0800 Subject: Beginner trying to understand functions. In-Reply-To: References: Message-ID: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> i think we should use raw_input('Please enter your name: ') instead of input('Please enter your name: ') 2008/12/8 Peter Otten <__peter__ at web.de> > simonh wrote: > > > In my attempt to learn Python I'm writing a small (useless) program to > > help me understand the various concepts. I'm going to add to this as I > > learn to serve as a single place to see how something works, > > hopefully. Here is the first approach: > > > That works fine. Then I've tried to use functions instead. The first > > two work fine, the third fails: > > > def getName(): > > name = input('Please enter your name: ') > > print('Hello', name) > > > > def getAge(): > > while True: > > try: > > age = int(input('Please enter your age: ')) > > break > > except ValueError: > > print('That was not a valid number. Please try again.') > > > > def checkAge(): > > permitted = list(range(18, 31)) > > if age in permitted: > > print('Come on in!') > > elif age < min(permitted): > > print('Sorry, too young.') > > elif age > max(permitted): > > print('Sorry, too old.') > > > > getName() > > getAge() > > checkAge() > > > > I get this error message: NameError: global name 'age' is not > > defined. > > > > I'm stuck, can someone help? Thanks. > > > Generally, when you calculate something within a function you tell it the > caller by returning it: > > >>> def get_age(): > ... return 74 > ... > >>> get_age() > 74 > >>> age = get_age() > >>> age > 74 > > And if you want a function to act upon a value you pass it explicitly: > > >>> def check_age(age): > ... if 18 <= age <= 30: > ... print("Come in") > ... else: > ... print("Sorry, you can't come in") > ... > >>> check_age(10) > Sorry, you can't come in > >>> check_age(20) > Come in > > To check the age determined by the get_age() function you do: > > >>> age = get_age() > >>> check_age(age) > Sorry, you can't come in > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul.nospam at rudin.co.uk Fri Dec 19 13:23:45 2008 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Fri, 19 Dec 2008 18:23:45 +0000 Subject: ANN: New Book: Programming in Python 3 References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> <6r25ckFejl4vU1@mid.individual.net> Message-ID: <877i5wxbv2.fsf@rudin.co.uk> Thomas Heller writes: > Steve Holden schrieb: >> Thomas Heller wrote: >>> Question from a non-native english speaker: is this now valid english? >>> >>> "One of Python?s great strengths" >>> ^ >>> "and also teaches Python?s functional programming features" >>> ^ >>> "The book?s approach is wholly practical" >>> ^ >> It always has been valid English. The apostrophe is only omitted from >> personal pronouns (hers, its, and so on). > > I see, thanks. But, is the apostrophe optional in the above fragments? No. From bayokrapht at googlemail.com Sat Dec 13 02:07:06 2008 From: bayokrapht at googlemail.com (boyombo) Date: Fri, 12 Dec 2008 23:07:06 -0800 (PST) Subject: Preventing execution of a method References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> <764daeef-bfbe-411a-8521-bb114321e4ac@b38g2000prf.googlegroups.com> <19304f8c-e34f-4aa9-8df2-6a7d3553007a@e1g2000pra.googlegroups.com> <2eed8876-94d2-4304-88a5-eb4a78b4f41d@33g2000yqm.googlegroups.com> <307fe197-1b42-4305-af0e-94b7ebe3ce70@r15g2000prh.googlegroups.com> <49417c59$0$8491$426a74cc@news.free.fr> <49421c07$0$3398$426a74cc@news.free.fr> Message-ID: <79a40af9-7f8b-41cf-97f8-92653f475a5d@r36g2000prf.googlegroups.com> On Dec 12, 9:09?am, Bruno Desthuilliers wrote: > Emanuele D'Arrigo a ?crit : > > > On Dec 11, 7:48 pm, Bruno Desthuilliers > > wrote: > >>> or to provide read-only > >>> access. I.e. right now I'm working on the graphical client which > >>> potentially could be rewritten entirely by the users. It is necessary > >>> and perfectly reasonable for the client module to access some of the > >>> objects to be represented graphically, but those objects shouldn't be > >>> modifiable by it. > >> Why so ? At worst, they'll break everything. > > > -IF- the application was single-user yes, it wouldn't be a big deal. > > But as it is potentially multi-user, I don't want one party to corrupt > > the application for everybody else. > > A multi-users application with a GUI usually implies that it's a > client-server app with the GUI deployed is on each client and the domain > logic hosted on the server. This is assuming the 'BAD GUY' does not have access to the server code, right? From drobinow at gmail.com Sun Dec 7 23:31:42 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Sun, 7 Dec 2008 20:31:42 -0800 (PST) Subject: how to get a beep, OS independent ? References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> <014c575a$0$20670$c3e8da3@news.astraweb.com> Message-ID: <962c4197-8730-4ddf-a925-88efe9a2fd84@k41g2000yqn.googlegroups.com> On Dec 7, 8:34?pm, Joe Strout wrote: > On Dec 7, 2008, at 4:43 PM, Steven D'Aprano wrote: > > > Of course, if you're volunteering to write such a standard system beep > > for Python, I for one would be grateful. > > I am. ?But where should I put it? ?Assuming we don't want to wait for ? > the (understandably) lengthy and contentious process required to add ? > something to the Python system libraries, where would be the next best ? > place for this sort of simple OS abstraction layer? > > Thanks, > - Joe Host it on your web site and send an announcement to comp.lang.python.announce If you don't have a web site (I don't) you might try http://pypi.python.org/pypi. See the tutorial there for instructions. If the setup.py requirement is too difficult ask for help here. From skip at pobox.com Tue Dec 30 07:10:22 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 30 Dec 2008 06:10:22 -0600 Subject: Python in C In-Reply-To: <313583fc-4651-4deb-8a44-c3b1810b722c@z27g2000prd.googlegroups.com> References: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> <313583fc-4651-4deb-8a44-c3b1810b722c@z27g2000prd.googlegroups.com> Message-ID: <18778.4014.114778.847498@montanaro-dyndns-org.local> aki> Although this is not what you are asking but I'm wondering why you aki> need to read CPython implementation. A couple reasons come to mind: * education * want to make it better (extend it, fix bugs, etc) * want to see how it relates to the implementation of other languages (Ruby, Perl, Tcl, etc) aki> CPython worked great for me. I don't want to read a large piece of aki> software, like CPython, unless it is really really necessary. Sure, but not everyone works at the Python layer. Which is a good thing, because if everyone confined themselves to Python code nobody would fix problems in the language implementation or enhance it. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From rt8396 at gmail.com Wed Dec 17 14:23:49 2008 From: rt8396 at gmail.com (r) Date: Wed, 17 Dec 2008 11:23:49 -0800 (PST) Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> <175fa5d5-f345-47b8-a686-e0e36e1b99e9@q37g2000vbn.googlegroups.com> <39eec12b-d7cc-44b5-aa65-bfa559dcba05@n33g2000pri.googlegroups.com> Message-ID: On Dec 17, 12:20?pm, walterbyrd wrote: > On Dec 17, 10:00?am, r wrote: > > > When writing > > procedural code how would you like it if vars inside functions were > > automatically global. Your code with be blowing chunks in no time. > > That was my point - I consider python's ordinary use of lexical > scoping to be a good thing, and I was wondering why this "good thing" > was not used in classes, as well as outside of classes. The whole point for even writing a class is for shared attributes. Write procedural code if you don't like classes. When ever you see self.var think of it as Class.instance(var)... makes total sense to me? Obliviously you have not done much procedural coding or you would know why this HAS to be. sorry if i sound rude. From ken at jots.org Sat Dec 6 10:10:11 2008 From: ken at jots.org (Ken D'Ambrosio) Date: Sat, 6 Dec 2008 10:10:11 -0500 (EST) Subject: Detaching e-mail attachments? Message-ID: <58772.75.67.216.99.1228576211.squirrel@webmail.jots.org> Hi, all. I've done some poking around, and can find roughly two million different ways to attach attachments to an e-mail... but darn few to detach them. Any suggestions? I'm assuming I'm just missing looking in The Right Place, but thus-far, my Googling has been for naught. Thanks! -Ken From fetchinson at googlemail.com Fri Dec 19 19:20:02 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Fri, 19 Dec 2008 16:20:02 -0800 Subject: mod_python resources In-Reply-To: References: <78064e7e-ba2c-4959-b5f8-4d1b928bc5fe@y18g2000yqn.googlegroups.com> <4lsl16-15a.ln1@archaeopteryx.softver.org.mk> Message-ID: > Here's my problem (it's a conceptual one). Coming from the world of > mod_php, each file can represent a page with no intervention. I was > not able to achieve the same with mod_python when I tried, and for > that matter, couldn't put the pieces together in a usable way. > > Let me start simply: If I wanted to create a trivial site, (Home, > About, Contact) with a header and footer included, in PHP, it would be > done as such: each page (index.php, about.php, contact.php) includes > the template bits (header.php, footer.php). Is this simplicity > achievable using Python? And by "simplicity," I'm referring to > simplicity in execution; not necessarily an identical approach. Yes, it is possible. As already advised by several posters, reading the documentation actually helps. You may want to have a look at: http://www.modpython.org/live/current/doc-html/pyapi-psp.html The spyce project you may also find helpful: http://spyce.sourceforge.net/ Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From jsm4321 at gmail.com Thu Dec 25 13:53:31 2008 From: jsm4321 at gmail.com (jsm4321 at gmail.com) Date: Thu, 25 Dec 2008 10:53:31 -0800 (PST) Subject: Syntax error for print Message-ID: <2b65c6e1-b5a9-438d-a45c-b8f9d18228de@s1g2000prg.googlegroups.com> IDLE 3.0 >>> print "hello" SyntaxError: invalid syntax (, line 1) >>> 3+3 6 >>> var = 4 >>> var = var*4 >>> print var SyntaxError: invalid syntax (, line 1) >>> Any idea on why I am getting this error. I have just started learning python and I am stuck at first thing itself. Any help would be greatly appreciated. Thanks, Jeetu Sahil From fetchinson at googlemail.com Sat Dec 27 19:44:27 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 27 Dec 2008 16:44:27 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: >> I agree that array.array is more efficient than a list but the input >> for my function will come from PIL and PIL returns a list. So I have a >> list to begin with which will be passed to the C function. > > With recent versions of PIL, numpy can create an array from an Image very > quickly, possibly without any copying of memory. What exactly do you mean? (1) PIL creates a list which can be easily converted by numpy to a numpy.array or (2) with the help of numpy one can create a numpy.array from an image directly? Since I will have to pass the list or numy.array to C anyway I don't see any advantage to (1) although (2) can be useful. Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From tgrav at mac.com Mon Dec 22 21:10:19 2008 From: tgrav at mac.com (Tommy Grav) Date: Mon, 22 Dec 2008 21:10:19 -0500 Subject: Python's popularity In-Reply-To: <495011B8.1050607@strout.net> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <18767.47566.709705.92@montanaro-dyndns-org.local> <495011B8.1050607@strout.net> Message-ID: <8FACC6D5-620D-4328-A0FA-8CFBDC293C75@mac.com> On Dec 22, 2008, at 5:16 PM, Joe Strout wrote: > Alvin ONeal wrote: > >> Also worthy of mention: >> I've seen python pre-installed on consumer HP desktops (I think as >> part of a backup/restore script, but I'm not sure) > > It's pre-installed on every Mac (both desktop and laptop), too. Mac and a lot of linux distros use python as an integral part of their OS development, so most of these actually come with some python pre-installed (and one should not remove it unless you want to screw up your OS). Cheers Tommy From tino at wildenhain.de Mon Dec 22 02:06:53 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 22 Dec 2008 08:06:53 +0100 Subject: How to represent a sequence of raw bytes In-Reply-To: References: <200812220327.36180.motoom@xs4all.nl> Message-ID: <494F3C8D.7040504@wildenhain.de> Steven Woody wrote: > On Mon, Dec 22, 2008 at 10:27 AM, Michiel Overtoom wrote: >> On Monday 22 December 2008 03:23:03 Steven Woody wrote: >> >>> 2. char buf[] = {0x11, 0x22, 0x33, ... } >>> >>> What's the equivalent representation for above in Python? >>>>> buf="\x11\x22\33" ... > I thing "\x11\x22\x33" in python is not the {0x11, 0x22, 0x33} in C. > Since, a string in python is immutable, I can _not_ do something like: > b[1] = "\x55". > > And, how about char buf[200] in my original question? The intension > is to allocate 200 undefined bytes in memory. Thanks. Well in most cases you don't need to do that, instead you could assemble your stream on the way out based on sequences, generators etc. Please note that char in your example is just a bit inapropriate (but common in C) shorthand for unsigned short int. There is no such type in python so you could use int() if you want to operate on the numeric value. Depending on your use case a big integer could also serve well and you can convert it into a byte string. If you want random access to the bytes, you can use list or array (see array module) or, if you want it with much more performance resort to numpy, scipy, they have arrays similar to C and also much more numeric datatypes. Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From prologic at shortcircuit.net.au Tue Dec 30 19:29:14 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 10:29:14 +1000 Subject: get method In-Reply-To: <71508d7a-f678-40ba-801c-0bbfbbab961e@r15g2000prh.googlegroups.com> References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> <495AAB97.5010707@mrabarnett.plus.com> <71508d7a-f678-40ba-801c-0bbfbbab961e@r15g2000prh.googlegroups.com> Message-ID: On Wed, Dec 31, 2008 at 10:22 AM, John Machin wrote: (snip) > The "crawl through the shrubbery looking for evidence" approach > stumbles on the actual code: Yes I found his implementation soon after :) Not bad actually... I wonder why bag() isn't shipped with the std lib - perhaps in teh set module ? --JamesMills From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 9 04:17:02 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 09 Dec 2008 10:17:02 +0100 Subject: Beginner trying to understand functions. In-Reply-To: <040a2896-be99-477e-909c-c55c5a0e6665@y1g2000pra.googlegroups.com> References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> <9df7549a-f28b-4d39-b105-90c099f472f2@z28g2000prd.googlegroups.com> <040a2896-be99-477e-909c-c55c5a0e6665@y1g2000pra.googlegroups.com> Message-ID: <493e3788$0$6842$426a74cc@news.free.fr> simonh a ?crit : > Thanks for the many replies. Thanks especially to Pierre. This works > perfectly: > (snip) Ok, now for some algorithmic stuff: > def checkAge(age,min=18,max=31): > if age in list(range(min, max)): > print('Come on in!') > elif age < min: > print('Sorry, too young.') > elif age >= max: > print('Sorry, too old.') if age is neither greater than max nor lesser than min, then it's it in range(min, max). IOW, you could just skip the first test: def checkAge(age,min=18,max=31): if age < min: print('Sorry, too young.') elif age >= max: print('Sorry, too old.') else: print('Come on in!') !-) From darcy at druid.net Thu Dec 18 16:54:08 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 18 Dec 2008 16:54:08 -0500 Subject: psycopg2 and large queries In-Reply-To: <494AC077.2060605@shopzeus.com> References: <762eed9d-4646-4c62-a9b7-d57d47f03b9e@e1g2000pra.googlegroups.com> <494AC077.2060605@shopzeus.com> Message-ID: <20081218165408.b40d11f1.darcy@druid.net> On Thu, 18 Dec 2008 22:28:23 +0100 Laszlo Nagy wrote: > - PyGresSQL: apparently, it does not support fetching one row, only > fetching all rows (see: > http://www.pygresql.org/pg.html#getresult-get-query-values-as-list-of-tuples), > so this is not an option. (Yes, it also has a db api compilant module, > but it is only a wrapper around pgqueryobject, and it does not support > server side cursors...) I'm not sure where you get that. The DB-API compliant execute function uses server side cursors with fetch. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From iofferkicks21 at gmail.com Wed Dec 24 19:14:38 2008 From: iofferkicks21 at gmail.com (www.iofferkicks.com) Date: Wed, 24 Dec 2008 16:14:38 -0800 (PST) Subject: www.iofferkicks.com china cheap wholesale nike shoes,air jordan shoes,air force one shoes. Message-ID: <79f56140-4828-4d9d-ac5c-ab692b133a9b@35g2000pry.googlegroups.com> Get Nike Shoes at Super Cheap Prices Discount Nike air jordans (www.iofferkicks.com) Discount Nike Air Max 90 Sneakers (www.iofferkicks.com) Discount Nike Air Max 91 Supplier (www.iofferkicks.com) Discount Nike Air Max 95 Shoes Supplier (www.iofferkicks.com) Discount Nike Air Max 97 Trainers (www.iofferkicks.com) Discount Nike Air Max 2003 Wholesale (www.iofferkicks.com) Discount Nike Air Max 2004 Shoes Wholesale (www.iofferkicks.com) Discount Nike Air Max 2005 Shop (www.iofferkicks.com) Discount Nike Air Max 2006 Shoes Shop (www.iofferkicks.com) Discount Nike Air Max 360 Catalogs (www.iofferkicks.com) Discount Nike Air Max Ltd Shoes Catalogs (www.iofferkicks.com) Discount Nike Air Max Tn Men's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 2 Women's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 3 Customize (www.iofferkicks.com) Discount Nike Air Max Tn 4 Shoes Customize ( www.iofferkicks.com) Discount Nike Air Max Tn 6 Supply (www.iofferkicks.com) Discount Nike Shox NZ Shoes Supply (www.iofferkicks.com) Discount Nike Shox OZ Sale (www.iofferkicks.com) Discount Nike Shox TL Store (www.iofferkicks.com) Discount Nike Shox TL 2 Shoes Store (www.iofferkicks.com) Discount Nike Shox TL 3 Distributor (www.iofferkicks.com) Discount Nike Shox Bmw Shoes Distributor (www.iofferkicks.com) Discount Nike Shox Elite Shoes Manufacturer (www.iofferkicks.com) Discount Nike Shox Monster Manufacturer (www.iofferkicks.com) Discount Nike Shox R4 Running Shoes (www.iofferkicks.com) Discount Nike Shox R5 Mens Shoes (www.iofferkicks.com) Discount Nike Shox Ride Womens Shoes (www.iofferkicks.com) Discount Nike Shox Rival Shoes Wholesaler (www.iofferkicks.com) Discount Nike Shox Energia Wholesaler (www.iofferkicks.com) Discount Nike Shox LV Sneaker (www.iofferkicks.com) Discount Nike Shox Turbo Suppliers (www.iofferkicks.com) Discount Nike Shox Classic Shoes Suppliers (www.iofferkicks.com) Discount Nike Shox Dendara Trainer (www.iofferkicks.com) Discount Nike Air Jordan 1 Seller (www.iofferkicks.com) Discount Nike Air Jordan 2 Shoes Seller (www.iofferkicks.com) Discount Nike Air Jordan 3 Collection (www.iofferkicks.com) Discount Nike Air Jordan 4 Shoes Collection (www.iofferkicks.com) Discount Nike Air Jordan 5 Chaussure Shoes (www.iofferkicks.com) Discount Nike Air Jordan 6 Catalog (www.iofferkicks.com) Discount Nike Air Jordan 7 Shoes Catalog (www.iofferkicks.com) Discount Nike Air Jordan 8 Customized (www.iofferkicks.com) Discount Nike Air Jordan 9 Shoes Customized (www.iofferkicks.com) Discount Nike Air Jordan 10 Wholesalers (www.iofferkicks.com) Discount Nike Jordan 11 Shoes Wholesalers (www.iofferkicks.com) Discount Nike Air Jordan 12 Factory (www.iofferkicks.com) Discount Nike Air Jordan 13 Shoes Factory (www.iofferkicks.com) Discount Nike Air Jordan 14 Shoes Sell (www.iofferkicks.com) Discount Nike Air Jordan 16 Exporter (www.iofferkicks.com) Discount Nike Air Jordan 17 Shoes Exporter (www.iofferkicks.com) Discount Nike Air Jordan 18 Offer (www.iofferkicks.com) Discount Nike Air Jordan 19 Shoes Offer (www.iofferkicks.com) Discount Nike Air Jordan 20 Manufacture (www.iofferkicks.com) Discount Nike Jordan 21 Shoes Manufacture (www.iofferkicks.com) EMAIL:IOFFERKICKS at GMAIL.COM MSN :IOFFERKICKS at MSN.COM From mail at microcorp.co.za Mon Dec 29 07:10:28 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 29 Dec 2008 14:10:28 +0200 Subject: poblem regarding opening a html file References: <022701c969a0$a4541ef0$5fc513ac@pwit.com> Message-ID: <006601c969ae$7823ae00$0d00a8c0@hendrik> Sibtey Mehdi wrote: >Hi > I have a GUI application (wxpython) that calls another GUI Application. I m using os.system (cmd) >to launch >The second GUI, in the second GUI I m trying to open the html file using the os.startfile (filename) function >but >It takes lots of time to open the html file. >If I am running only the second application then ?os.startfile? quickly open the html file. >Any one can help me to solve this problem. > Buy more memory? - Hendrik From robert.kern at gmail.com Sun Dec 7 19:14:24 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 07 Dec 2008 18:14:24 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: <014c55e9$0$20670$c3e8da3@news.astraweb.com> References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> <014c55e9$0$20670$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Sun, 07 Dec 2008 23:20:12 +0000, Steven D'Aprano wrote: > >> On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: >> >>> Rasmus Fogh wrote: >>> >>>> Current behaviour is both inconsistent and counterintuitive, as these >>>> examples show. >>>> >>>>>>> x = float('NaN') >>>>>>> x == x >>>> False >>> Blame IEEE for that one. Rich comparisons have nothing to do with that >>> one. >> There is nothing to blame them for. This is the correct behaviour. NaNs >> should *not* compare equal to themselves, that's mathematically >> incoherent. > > Sorry, I should explain why. > > Given: > > x = log(-5) # a NaN > y = log(-2) # the same NaN > x == y # Some people want this to be true for NaNs. > > Then: > > # Compare x and y directly. > log(-5) == log(-2) > # If x == y then exp(x) == exp(y) for all x, y. > exp(log(-5)) == exp(log(-2)) > -5 == -2 > > > and now the entire foundations of mathematics collapses into a steaming > pile of rubble. I didn't mean to suggest that it was incorrect, just that that particular surprising behavior is not related to rich comparisons. Even if the OP gets an __equals__() or some such, NaN will still not compare equal to NaN. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From rridge at csclub.uwaterloo.ca Wed Dec 3 15:21:20 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 03 Dec 2008 15:21:20 -0500 Subject: Debugging a Python Program that Hangs References: Message-ID: Kevin D. Smith wrote: >I have a fairly large python program that, when a certain combination >of options is used, hangs. I have no idea where it is hanging, so >simply putting in print statements to locate the spot would be quite >difficult. Unfortunately, ctrl-C'ing the program doesn't print a >traceback either. Have you tried catching the KeyboardInterrupt exception and printing an exception? Something like: try: rest_of_program() except KeyboardInterrupt: traceback.print_exc() raise Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From python.list at tim.thechases.com Sat Dec 27 10:28:10 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 27 Dec 2008 09:28:10 -0600 Subject: dummy needs help with Python In-Reply-To: References: Message-ID: <4956498A.5030408@tim.thechases.com> > I am trying to find somebody who can give me a simple python > program I can use to "program by analogy". I just want to > read two CSV files and match them on several fields, > manipulate some of the fields, and write a couple of output > files. ... > Please forgive me if this is so, and take pity on a stranger > in a strange land. Pittsburgh is a little strange, but not *that* bad :) Just for fun, I threw together a simple (about 30 lines) program to do what you describe. Consider it a bit of slightly belated Christmas pity on the assumption that this isn't classwork (a little googling suggests that it's not homework). It's 100% untested, so if it formats your hard-drive, steals your spouse, wrecks your truck, kicks your dog, makes a mess of your trailer-home, and drinks all your beer, caveat coder. But you've got the source, so you can vet it...and it's even commented a bit for pedagogical amusement if you plan to mung with it :) from csv import reader SMALL = 'a.txt' OTHER = 'b.txt' smaller_file = {} # key->line mapping dict for the smaller file f_a = file(SMALL) r_a = reader(f_a) #a_headers = reader.next() # optionally discard a header row # build up the map in smaller_file of key->line for i, line in enumerate(r_a): a1, a2, a3, a4, a5 = line # name the fields key = f1, f3, f5 if key in smaller_file: print "Duplicate key [%r] in %s:%i" % (key, SMALL, i+1) #continue # does the 1st or 2nd win? uncomment for 1st smaller_file[key] = line f_a.close() b = file(OTHER) r_b = reader(b) #b_headers = reader.next() # optionally discard a header row for i, line in enumerate(r_b): b1, b2, b3, b4, b5, b6, b7, b8, b9 = line key = b2, b8, b9 if key not in smaller_file: print "Key for line #%i (%r) not in %s" % (i+1, key, SMALL) continue a1, a2, a3, a4, a5 = smaller_file[key] # do manipulation with a[1-5]/b[1-9] here # and do something with them b.close() It makes more sense if instead of calling them a[1-5]/b[1-9], you actually use the field-names that may have be in the header rows such as cost_center, store, location, manager_id = line key = cost_center, store, location You may also have to manipulate some of the values to make key-matches work, such as cc, store, loc, mgr = line cc = cc.strip().upper() store = store.strip().title() key = cc, store, loc ensuring that you do the same manipulations for both files. The code above reads the entire smaller file into memory and uses it for fast lookup. However, if you have gargantuan files, you may need to process them differently. You don't detail the fields/organization of the files, so if they're both sorted by key, you can change the algorithm to behave like the standard *nix "join" command. Other asides: you may have to tweak treatment of a header-row (and correspondingly the line-numbers), as well as conflict-handling for keys in your a.txt source if they exist, along with the behavior when a key can't be found in a.txt but is requested in b.txt (maybe set some defaults instead of logging the error and skipping the row?), and then lastly and most importantly, you have to fill in the manipulations you desire and then actually do something with the processed results (write them to a file, upload them to a database, send them via email, output them to a text-to-speech engine and have it speak them, etc). > I come from 30 years of mainframe programming so I understand > how computers work at a bits/bytes /machine language/ source > vs.executable/reading core dumps level, and I can program in > a lot of languages most people using Python have never even > heard of, If there's such urgency, I hope you resorted to simply using one of these multitude of other languages you know -- Even in C, this wouldn't be too painful as projects go (there's a phrase you won't hear me utter frequently). Or maybe try your hand at it in pascal, shell-scripting (see the "join" command) or even assembly language. Not sure I'd use Logo, Haskel, Erlang, or Prolog. :) > My problem is that I want to do this all yesterday, and the > Python text I bought is not easy to understand. I don't have > time to work my way through the online Python tutorial. As Rick mentioned, there are a number of free online sources for tutorials, books, and the like. Dive Into Python is one of the classics. Searching the archives of comp.lang.python for "beginner books" will yield the same thread coming up every couple weeks. For future reference, if you've got time-sensitive projects to tackle "yesterday", it's usually not the best time to try and learn a new language. Good luck in your exploration of Python. -tkc From gagsl-py2 at yahoo.com.ar Thu Dec 25 01:46:39 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Dec 2008 04:46:39 -0200 Subject: ctypes & strings References: <334452.47084.qm@web30003.mail.mud.yahoo.com> Message-ID: En Wed, 24 Dec 2008 23:07:27 -0200, Red Rackham escribi?: > I would like to pass a string into a dll function.? I notice that to > pass using ctypes, it has to be a ctypes type.? Looking at the ctypes > doc page I don't see a c_string class.? Because the C language doesn't have a string type? Python strings are automatically converted to c_char_p if you set the argtypes attribute. > I tried to pass in?byref("name of string") and got back "TypeError: > byref() argument must be a ctypes instance, not 'str'" byref? Please post the prototype of the function you want to call. If it takes a const char*, or a char* but doesn't modify it, you don't have to use byref. If it takes a char* and modifies it, use create_string_buffer (also, the function SHOULD take the buffer size as an additional parameter...) > If I use astr = create_string_buffer( "name of string" ), and try to > pass that in, I get "ValueError: Procedure probably called with too many > arguments (4 bytes in excess)". Maybe you didn't set correctly the calling convention (cdecl? stdcall?). How did you load the dll and get the function? Libraries loaded using windll use the stdcall convention; cdll uses cdecl. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Sat Dec 27 15:15:58 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 27 Dec 2008 18:15:58 -0200 Subject: parsing csv files class References: <49562755.6050205@byoteki.com> Message-ID: En Sat, 27 Dec 2008 11:02:13 -0200, Gary M. Josack escribi?: > alex goretoy wrote: >> I know it's messy with all those self.soc.* functions, but it works in >> one of my current project. I just want to make it more pythonic I also >> want to add capability for makeing csv file if I give it input like: >> 1234,something nice, hey this is something nice >> 2468,something else, something else >> reader = csv.reader(file(filename, "rb")) >> try: >> for row in reader: >> self.buffer.append(row) >> s,a=[],{} > Do you know that there is a csv module in the standard library already? I'd say he already knows, he even used it in the code. To Alex G.: I didn't understand what's the purpose of this class. Probably you want to do too much things in the same place; looks like it has multiple concerns, and that's not a good idea usually. -- Gabriel Genellina From castironpi at gmail.com Sat Dec 20 20:06:24 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 20 Dec 2008 17:06:24 -0800 (PST) Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> <7e23a789-84c3-47b9-b040-ca7dd062d058@a37g2000pre.googlegroups.com> Message-ID: On Dec 18, 7:21?pm, "Gabriel Genellina" wrote: > En Thu, 18 Dec 2008 19:46:45 -0200, Aaron Brady ? > escribi?: snip > On Windows, file handles are the real OS stuff, the "true" reference to an ? > open file. File descriptors are not, they exist only to please the C ? > runtime library. Programs not written in C (directly, or indirectly like ? > Python) don't care at all about file descriptors. And in case one actually ? > cares, there is _open_osfhandle in the C RTL (available as ? > msvcrt.open_osfhandle from Python). > A subprocess may inherit handles from its parent [there are two filters: ? > the parameter "bInheritHandles" in the CreateProcess call provides global ? > control, and individual handles can be made inheritable or not, before ? > creating the new subprocess]. > "Anonymous" pipes are good to replace stdin/stdout/stderr, because there ? > is no need to explicitely communicate the handle value to the subprocess: ? > one just replaces the corresponding handle with the desired pipe, and the ? > subprocess might not even notice it. > In case this is not enough, one might pass the handle (as a number) in the ? > command line, but probably a "named pipe" would be better. As this is not ? > transparent for the child process, one must explicitely code such things. > > > Will it take calling > > 'CreatePipe' from ctypes directly if on Windows? ?Or can 'os.pipe' be > > made to abstract that? ?If Windows can't inherit descriptors, > > 'os.pipe' should return handles, and 'os.read' &co. should accept > > them. > > I think the best way would be to modify os.pipe so it returns inheritable ? > pipes, as it should have been from the beginning. > > > It is a fairly large patch. > > Not at all, you have already posted most of it. I have marginally tested the patch on a custom build. It works, but there is a catch. The descriptor can't be passed directly to the child on the command line. You need to call 'msvcrt.get_osfhandle' on the descriptor, pass the result, then call 'msvcrt.open_osfhandle' in the child. From gagsl-py2 at yahoo.com.ar Fri Dec 12 16:04:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 12 Dec 2008 19:04:14 -0200 Subject: Bidirectional Networking References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <6qeht0Fc3541U1@mid.individual.net> <782258db-2bdc-45a7-8d8f-7a036d574985@t26g2000prh.googlegroups.com> Message-ID: En Fri, 12 Dec 2008 15:22:34 -0200, Emanuele D'Arrigo escribi?: > Thank you both for the suggestions! Eventually I tried with threading > as illustrated in the code below. > And it works pretty well! The only problem I'm having with it is that > as the server is a daemon the program should end when the client > thread cease to be alive. But it doesn't seem to work that way and I'm > not sure what's going on! I did achieve my objective though. Two > separate instances of the code below will happily send random numbers > to each other for a few seconds! If you're using 2.5 or older, override serve_forever: def serve_forever(self): while not getattr(self, 'quit', False): self.handle_request() and set the server 'quit' attribute to True in response to some command from the client. Python 2.6 has a shutdown() method for the same purpose. -- Gabriel Genellina From pdorange at pas-de-pub-merci.mac.com Mon Dec 22 11:51:52 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Mon, 22 Dec 2008 17:51:52 +0100 Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> <1iscu14.oixxplpgajabN%pdorange@pas-de-pub-merci.mac.com> <9977fd77-9a17-4dcb-9193-49009763c683@33g2000yqm.googlegroups.com> Message-ID: <1isczzk.1ahgisd19z7dg7N%pdorange@pas-de-pub-merci.mac.com> Istvan Albert wrote: > try testing on a large number of candidates that are all (or mostly) > positive or all (or mostly) negative and you'll see performance > numbers that are substantially different than the ones you report: > > candidates = range(1000) > > In general the function sign_1() is expected to be the fastest because > in most cases will detect the sign with the fewest operations, it only > visits the rest of the comparison when it hits the corner cases. Only > if you have lots of +/-0.0 cases will it be slower than the rest, due > to having to call an expensive operation. You're right. On a range or a random list sign_1 is the fastest : with : candidates=[] for i in range(1000): candidates.append(1000.0*random.random()-500.0) In my first candidate list, the two ZERO (-0.0 and +0.0) make sign_1 less productive because it call atan2(). With random number sign_1 is faster, just a bit faster, except if the candidates contain some ZERO. I also make other test, with a range(1000), sign_1 became really faster : -41% (near twice faster than sign_0). I then rewrote a sign_0 version testing first positive, then negative and ZERO as the last test. I also made tests and return integer. It make it faster +20% but not as fast as sign_1 for a range. What is strange is that when testing with "range" list (0 1000) or (-500 +500), sign_1 is twice as fast as with a random generated list. The only thing a saw is that range generate an int list and random a float list... So it seems sign_1 is really fastest with integer, but not with float Range from -500 to +500 sign_0 : 0.38" sign_1 : 0.27" (-40%) Range from 0 to 1000 sign_0 : 0.32" sign_1 : 0.25" (-22%) Range from -1000 to 0 sign_0 : 0.46" sign_1 : 0.30" (-35%) 1000 Random from -500 to +500 sign_0 : 0.37" sign_1 : 0.42" (+13%) -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From manu3d at gmail.com Sun Dec 14 06:37:38 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Sun, 14 Dec 2008 03:37:38 -0800 (PST) Subject: Bidrectional Subprocess Communication References: Message-ID: <5b4f4146-ad39-4fe6-9055-e852bd127143@q26g2000prq.googlegroups.com> On Dec 14, 4:48?am, "Gabriel Genellina" wrote: > - you have to close server.stdin when you don't have more data to send. > The server will see an end-of-file and knows it has to exit the loop. > Same thing on the client side. Hi Gabriel, thanks for modifying the code to make it work. I've just tried tinkering with it to see how far it would go. On your two statements above: does this means that any data must be sent in one batch and then the subprocess must shut down? What I was trying to simulate is a client/server relationship through a subprocess, where the server (the subprocess) keeps listening and the client sends data when it wants to (and eventually viceversa). But when the server.stdin.close() statement is issued, the pipe is closed for good and can't be reopened (can it?). > - you have to wait until the server answers, else it will get a "broken > pipe" error or similar. So, if I want to interrogate the subprocess multiple times I must end and restart the ListenerThread multiple times then? In the meantime, I better brush up on my streams... =) Thanks for your help! Manu From gagsl-py2 at yahoo.com.ar Tue Dec 16 04:44:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Dec 2008 07:44:02 -0200 Subject: Interface & Implementation References: <11e2ac5b5eb.2364397661727502391.6806593866408074890@adventnet.com> Message-ID: En Fri, 12 Dec 2008 19:48:09 -0200, Lie Ryan escribi?: > but if you really want it, simple inheritance might be better anyway, > though not really pythonic: > > class MyIfc(object): > def myMeth1(self): return NotImplemented > def myMeth2(self): return NotImplemented > class MyClass(MyIfc): > def myMeth1(self): > # some implementation > def myMeth2(self): > # some implementation > > # some might notice the (ab)use of NotImplemented sentinel there I'd raise NotImplementedError instead. -- Gabriel Genellina From febaen at gmail.com Tue Dec 16 09:56:07 2008 From: febaen at gmail.com (feba) Date: Tue, 16 Dec 2008 06:56:07 -0800 (PST) Subject: Free place to host python files? References: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> Message-ID: <32599660-2393-4e18-8c48-05d64bccbbc1@t26g2000prh.googlegroups.com> On Dec 16, 8:29?am, s... at pobox.com wrote: > ? ? feba> I'm getting started in python, and it would be helpful to have a > ? ? feba> place to put up various code snippets I've made, so I don't have > ? ? feba> to send them individually to each person I want to show it to. > ? ? feba> I'd prefer to use something that would give me a directory for my > ? ? feba> use only, instead of something where you can only upload one at a > ? ? feba> time. ?I'd especially like to avoid stuff that uses CAPTCHAs > ? ? feba> and/or forced waiting periods. > > http://pastebin.com/? > > -- > Skip Montanaro - s... at pobox.com -http://smontanaro.dyndns.org/ well, ignoring the fact that pastebin doesn't work for me for some reason, I'm talking about hosting it as a .py downloadable, not a hunk of text. From nospam at nospam.com Fri Dec 26 15:33:32 2008 From: nospam at nospam.com (Gilles Ganault) Date: Fri, 26 Dec 2008 21:33:32 +0100 Subject: [SQL] Right way to set a variable to NULL? Message-ID: <5nfal41gom0iqi2nh5h0m5847ev9brtvpf@4ax.com> Hello I use regexes to extract information from a text file. Some of the records don't have e-mails or www addresses, so those must match Null in SQL, but None doesn't work as expected: ======= if itemmatch: web = itemmatch.group(1).strip() else: web = None sql = 'INSERT INTO mytable (name,address,web,mail) VALUES ("%s","%s","%s","%s","%s")' % (name,address,web,mail) ======= Is there a better way in Python to have a variable match NULL than building the SQL query step by step? Thank you. From martin.laloux at gmail.com Fri Dec 19 04:13:42 2008 From: martin.laloux at gmail.com (gene) Date: Fri, 19 Dec 2008 01:13:42 -0800 (PST) Subject: If programming languages were religions... Message-ID: very interesting http://www.aegisub.net/2008/12/if-programming-languages-were-religions.html "Python would be Humanism: It's simple, unrestrictive, and all you need to follow it is common sense. Many of the followers claim to feel relieved from all the burden imposed by other languages, and that they have rediscovered the joy of programming. There are some who say that it is a form of pseudo-code" compare to "Perl would be Voodoo - An incomprehensible series of arcane incantations that involve the blood of goats and permanently corrupt your soul. Often used when your boss requires you to do an urgent task at 21:00 on friday night." and others From exarkun at divmod.com Thu Dec 4 14:42:32 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 4 Dec 2008 14:42:32 -0500 Subject: Python 3 read() function In-Reply-To: Message-ID: <20081204194232.20272.544720092.divmod.quotient.15718@ohm> On Thu, 04 Dec 2008 14:25:48 -0500, Terry Reedy wrote: > [snip] > >In my test, I read Python25.chm with 2.5 and Python30.chm with 3.0. > >Rereading Python30.chm without closing *is* much faster. > >>> f=open('Doc/Python30.chm','rb') > >>> d=f.read() > >>> d=f.read() > >>> d=f.read() Did you think about what this does? Jean-Paul From mmanns at gmx.net Sun Dec 7 12:19:10 2008 From: mmanns at gmx.net (mmanns at gmx.net) Date: Sun, 7 Dec 2008 18:19:10 +0100 Subject: can graphs be made in python as we make in java References: <89ff42d1-6a4c-4d45-a646-238b43e7e8de@s9g2000prm.googlegroups.com> Message-ID: <20081207181910.2d63961c@Schlamber.localdomain> On Sun, 7 Dec 2008 00:29:13 -0800 (PST) suku wrote: > HI folks... > > i need some suggestion on making graphs. Will this be possible > with normal python setup file or do i need to download add ons for > that.. > > help me out rpy Martin From __peter__ at web.de Fri Dec 19 10:55:20 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2008 16:55:20 +0100 Subject: change string to unicode References: Message-ID: jyoung79 at kc.rr.com wrote: > If I have a string like so: > > a = '\\u03B1' > > and I want to make it display a Greek alpha character, is there a way to > convert it to unicode ('\u03B1')? I tried concatenating it like this: > > '\u' + '03B1' > > but that didn't work. I'm working in Python 3.0 and was curious if this > could be done. How about >>> "\\u03b1".encode("ascii").decode("unicode-escape") '?' Peter From stefan_ml at behnel.de Tue Dec 30 17:33:24 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 30 Dec 2008 23:33:24 +0100 Subject: Python in C In-Reply-To: References: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> <313583fc-4651-4deb-8a44-c3b1810b722c@z27g2000prd.googlegroups.com> Message-ID: <495aa1b4$0$31329$9b4e6d93@newsspool4.arcor-online.net> akineko wrote: > The more you work on Python, the harder you can go back to C or C++ > world. > > I use SWIG, instead. I think SWIG is a good way to mix two worlds. If you find it hard to go from Python back to C, you should have a look at Cython. http://cython.org/ Stefan From gagsl-py2 at yahoo.com.ar Wed Dec 17 18:05:21 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 17 Dec 2008 21:05:21 -0200 Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> Message-ID: En Wed, 17 Dec 2008 12:21:38 -0200, Jeremy Sanders escribi?: > Aaron Brady wrote: > >> I thought so too. The web seems to say that on Linux they are, and on >> Windows, you need to call DuplicateHandle for it. Or set bInheritHandle=True when creating the pipe initially. os.pipe() doesn't do that. > I hit this problem - it looks like pipes aren't very versatile on > Windows. > There's also the complicating factor that the handles in windows aren't > the > same as the file numbers that Python uses, so you have to convert between > them. > > It would be nice if Python created pipes that are properly inheritable by > default by child processes, as they're mostly used for IPC. I'd say it is a bug in os.pipe implementation; they should be inheritable by default, as in posix (after all, the code is in "posixmodule.c"). -- Gabriel Genellina From miki.tebeka at gmail.com Mon Dec 1 22:54:54 2008 From: miki.tebeka at gmail.com (Miki) Date: Mon, 1 Dec 2008 19:54:54 -0800 (PST) Subject: Loading required libraries for python script from shell just once References: Message-ID: <3181dc1c-a894-4fe8-8eca-fccc3e2170c4@q30g2000prq.googlegroups.com> > Is it possible to load all the modules used by run-test.py in > a pre-execution environment in order to prevent this delay? Only if you have one script the calls "main" (or any other entry point) in the tests. > I considered a rewrite of the shell script into python, but it has too > many dependencies on shell libraries and I don't want to go that route > (unless an alternative solution is impossible). One other option is to have the python libraries on local disk, but IMO the first solution is better. HTH, -- Miki http://pythonwise.blogspot.com From alexoplocatie at gmail.com Thu Dec 18 06:56:53 2008 From: alexoplocatie at gmail.com (aka) Date: Thu, 18 Dec 2008 03:56:53 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> <0d9ea7cc-b5fb-4edb-be32-490aae9e7204@b41g2000pra.googlegroups.com> <0de3a7bf-a4c4-4103-a4e0-44313405fa94@z28g2000prd.googlegroups.com> <23d6710f-2c6d-4115-817a-053b8e96f1ce@z28g2000prd.googlegroups.com> Message-ID: <5529f88b-8db4-4fad-ad41-42bf39469a08@w1g2000prk.googlegroups.com> On 18 dec, 00:06, John Machin wrote: > On Dec 18, 3:15?am, aka wrote: > > Do you mean that this file was created by whatever.UnicodeWriter? If > so, did you just now discover this information? > > How do you know that "the UnicodeWriter is functioning perfectly"? > What does "functioning perfectly mean to you"? In particular, what > encoding is it using? > > Which do you mean: > (a) you typed those lines into Notepad yourself > (b) you took a copy of a file created by whatever.UnicodeWriter, > opened it with Notepad, trimmed off some rows and columns, and saved > it again > ? > Here's a likely hypothesis: the file was written in utf16. In that > case: > either (i) you really want utf16 (why?), so: > > (1) the csv module will not cope with it, and is not expected to cope > with it > > (2) the whatever.UnicodeReader should (in order of preference): > (a) be allowed to find out for itself that 'utf16' is the go > (b) be told explicitly that 'utf16' is the go > (c) be served with a bug report > > OR (ii) you really want utf8, so: > > (1) the csv module should be happy > (2) the whatever.UnicodeWriter should be told to use 'utf8' > (3) the whatever.UnicodeReader should (in order of preference): > [as above but s/16/8/] > The csv file originally was created by the UnicodeWriter class and was used for a mailmerge function with Microsoft Word which all functioned perfectly. The reverse did not: read back the outputted file so at last I editted it in Notepad, cutting off columns, but I didn't know that the encoding would remain even after that because it still caused problems. Now after testing from the Python command line with a csv file generated from Excel I could get it working so it had to be the encoding. Because the write side of my code, which uses the UnicodeWriter, was ok I didn't pay attention to the fact that I had changed the UW class from UTF-8 to UTF-16 because of difficulties with dutch characters like ? and ?. Then at last I tried changing back to UTF-8 and noticed both out -and input was working, including those special characters, so it was my unjustifiable conclusion that I couldn't get around these special characters at the write side without UTF-16 which ultimately got me in trouble with the read side. With your help I got it straight. Once again minimizing the problem to its bare basics and to prevent big steps is the key. Thanks a lot for your help John. BTW, the TurboGears code by the way is not very different from Python, it just uses some extra identifiers. From NIE_DZIALA at gazeta.pl Sun Dec 14 05:16:56 2008 From: NIE_DZIALA at gazeta.pl (Piotr Sobolewski) Date: Sun, 14 Dec 2008 11:16:56 +0100 Subject: the official way of printing unicode strings References: <6qk1o7Fcr01gU3@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > I'd make that first line: > sys.stdout = codecs.getwriter('utf-8')(sys.stdout) > > Why is it even more cumbersome to execute that line *once* instead > encoding at every ``print`` statement? Oh, maybe it's not cumbersome, but a little bit strange - but sure, I can get used to it. My main problem is that when I use some language I want to use it the way it is supposed to be used. Usually doing like that saves many problems. Especially in Python, where there is one official way to do any elementary task. And I just want to know what is the normal, official way of printing unicode strings. I mean, the question is not "how can I print the unicode string" but "how the creators of the language suppose me to print the unicode string". I couldn't find an answer to this question in docs, so I hope somebody here knows it. So, is it _the_ python way of printing unicode? From mirandasnailvv at gmail.com Fri Dec 19 19:43:03 2008 From: mirandasnailvv at gmail.com (mirandasnailvv at gmail.com) Date: Fri, 19 Dec 2008 16:43:03 -0800 (PST) Subject: cause of paraphilias from behavioral prespective - Free Message-ID: <2d98ed6a-b487-4506-a21c-5c3ea563933d@o4g2000pra.googlegroups.com> cause of paraphilias from behavioral prespective . . . *******CLICK HERE******** http://club247.cn/cause-of-paraphilias-from-behavioral-prespective ***************************** . . . . . . . . . . . . cause of paraphilias from behavioral prespective From rdmurray at bitdance.com Thu Dec 4 15:22:19 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Thu, 4 Dec 2008 15:22:19 -0500 (EST) Subject: Why shouldn't you put config options in py files In-Reply-To: References: Message-ID: On Thu, 4 Dec 2008 at 11:35, HT wrote: > I can think of lots of arguments why this is a bad idea, but I don't > seem to be able to think of a really convincing one. I think it depends on the problem domain. As someone else said, there are issues with being able to inject arbitrary code via the config file. In some applications, this would be a feature, in others it would be a security hole. Another angle to look at is the audience for the config file. If they are all going to be python programmers or python-familiar, great. If not...think about the user reaction to the tracebacks resulting from typos. If you use a purpose-designed config file (whether it is based on ConfigParser or not), you can more easily generate helpful error messages. --RDM From psftw1 at gmail.com Sun Dec 14 17:03:54 2008 From: psftw1 at gmail.com (peter s.) Date: Sun, 14 Dec 2008 14:03:54 -0800 (PST) Subject: Building from source -- zlib/binascii problems 2.5.2/2.6.1 References: <71531b64-535f-49d0-a0c6-7704df83b251@f18g2000vbf.googlegroups.com> <49458079.1000304@v.loewis.de> Message-ID: <003b0307-c8df-489b-98e6-cfaa35d050a4@k1g2000prb.googlegroups.com> On Dec 14, 4:54?pm, "Martin v. L?wis" wrote: > > Target: x86_64-redhat-linux > > gcc -pthread -shared build/temp.linux-x86_64-2.5/location/of/ > > Python-2.5.2/Modules/zlibmodule.o -L/usr/local/lib -lz -o build/ > > lib.linux-x86_64-2.5/zlib.so > > /usr/bin/ld: skipping incompatible /usr/lib/libz.so when searching for > > -lz > > Do > > ? file /usr/lib/libz.so > > It might be a 32-bit library, in which case you can check whether > /usr/lib64 has a 64-bit library. I'm puzzled why it only > happens for -lz; perhaps you are better of compiling with a 32-bit > compiler. > > Regards, > Martin $ file /usr/lib/libz.s* /usr/lib/libz.so: symbolic link to `libz.so.1.2.3' /usr/lib/libz.so.1: symbolic link to `libz.so.1.2.3' /usr/lib/libz.so.1.2.3: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), stripped From prologic at shortcircuit.net.au Tue Dec 16 17:47:32 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 17 Dec 2008 08:47:32 +1000 Subject: Python is slow In-Reply-To: References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <355f1cfe-6abb-4d2c-8bf4-3aa62e713c1f@w34g2000yqm.googlegroups.com> Message-ID: n Wed, Dec 17, 2008 at 8:24 AM, r wrote: >> What kind of performance problem have you find in python that makes >> you so unhappy? >> What are you going to do with all the extra speed provided by c++ (a >> Hello World! ?)... > > Still no reply from cm_gui, he must have googled "C hello world" :D I must be mad for doing this - but I feel so strongly about this topic. In 99.9% of cases generally things are "feast enough"! So here goes: jmills at atomant:~$ cat - > hello.c int main (int argc, char ** argv) { printf("Hello World!\n!"); } jmills at atomant:~$ tcc hello.c -o hello jmills at atomant:~$ wc -l hello.c 3 hello.c jmills at atomant:~$ ls -l hello.c -rw-r--r-- 1 jmills jmills 69 2008-12-17 08:41 hello.c jmills at atomant:~$ ls -l hello -rwxr-xr-x 1 jmills jmills 2972 2008-12-17 08:41 hello jmills at atomant:~$ time ./hello Hello World! ! real 0m0.003s user 0m0.000s sys 0m0.004s jmills at atomant:~$ cat - > hello.py print "Hello World!" jmills at atomant:~$ time python hello.py Hello World! real 0m0.129s user 0m0.016s sys 0m0.020s OMG OMG OMG! Python is slower! If you compare "sys" times ~5x slower! BUT ... This is in fact a misleading as most of this is in the startup time. So let's be fairer: jmills at atomant:~$ time python -E -S hello.py Hello World! real 0m0.011s user 0m0.008s sys 0m0.004s Wow! Only ~2x as slow as C. --JamesMills PS: Yet another useless post! From gabriel.rossetti at arimaz.com Wed Dec 10 05:26:01 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Wed, 10 Dec 2008 11:26:01 +0100 Subject: memory leak? In-Reply-To: <493F8188.1030700@arimaz.com> References: <493EAB79.6070805@arimaz.com> <493F8188.1030700@arimaz.com> Message-ID: <493F9939.2020302@arimaz.com> Gabriel Rossetti wrote: > Terry Reedy wrote: >> Gabriel Rossetti wrote: >> >>> I ran these tests on linux 2.6 (ubuntu 8.04) using python 2.5.2. >> >> Have you tried the much newer 2.6? 2.5.3 will be out soon with some >> bug fixes. >> > Thanks for the reply Terry, I just tried the pyserial example with > python 2.6 and it still has the same problem, here's the output (I > just copy/pasted the example in a running python2.6 interactive > interpreter) : > > test1 at 09:19am : > > $ ps waux | grep python2.6 > 1000 6730 0.2 0.4 6176 4120 pts/12 S+ 09:17 0:00 > python2.6 > > if I try the SIGUSR1 method : > $ kill -SIGUSR1 6730 > > #################################################################### > # DEBUG: The object count is : 12536 > #################################################################### > > test2 at 09:25am : > > $ ps waux | grep python2.6 > 1000 6730 0.0 0.9 12360 10168 pts/12 S+ 09:17 0:00 > python2.6 > > and the SIGUSR1 method gives me : > > #################################################################### > # DEBUG: The object count is : 25089 > #################################################################### > > > I also tried freeing the received string (del t) explicitly but the > results are unchanged. > > Thank you, > Gabriel > Apparently the memory goes up when I use the SIGUSR1 code, If I don't call it, it seams to work fine, my original memory leak must come from somewhere else then..... sorry for the spam. Gabriel From lew at lewscanon.com Mon Dec 29 11:20:34 2008 From: lew at lewscanon.com (Lew) Date: Mon, 29 Dec 2008 08:20:34 -0800 (PST) Subject: HTML Correctness and Validators References: <2fb289be-00b3-440a-b153-ca88f0ba16c5@d42g2000prb.googlegroups.com> <6rsbahF33ndvU1@mid.individual.net> Message-ID: <9eba3125-07e7-42ff-98c0-0b9be6105315@r36g2000prf.googlegroups.com> Xah Lee wrote... >> recently [sic] i [sic] wrote a blog essay about html [sic] correctness and html [sic] >> validators, with relations [sic] to the programing [sic] lang [sic] communities. I hope >> programing [sic] lang [sic] fans will take more consideration on [sic] the correctness >> of the doc [sic] they produces [sic]. "Aaron Gray" wrote: > Do you enjoy spamming comp.lang.functional with OT cross-posts ? Is that a rhetorical question? -- Lew From lepto.python at gmail.com Sat Dec 20 06:20:11 2008 From: lepto.python at gmail.com (oyster) Date: Sat, 20 Dec 2008 19:20:11 +0800 Subject: check whether a JPG is completed? Message-ID: <6a4f17690812200320r5cf05523v39517243a5c33ae4@mail.gmail.com> there are some pics(most of them are JPGs) on my disk, but some are not completed, that is to say, if I view it in irfanview, the bottom is displayed as a gray block. so I want to check where they are completed. but how to do that in python? (No, I am not saying "how to tell the fileszie when I download a file from internet") thanx From python at bdurham.com Wed Dec 24 04:21:30 2008 From: python at bdurham.com (python at bdurham.com) Date: Wed, 24 Dec 2008 04:21:30 -0500 Subject: Most efficient way to build very large dictionaries In-Reply-To: References: <1230104615.5867.1291617213@webmail.messagingengine.com> <1230107768.14060.1291622121@webmail.messagingengine.com> Message-ID: <1230110490.21192.1291625281@webmail.messagingengine.com> Hi Roger, > The performance improvements you are seeing with Python over Oracle are exactly the same range people see with SQLite over Oracle. One common usage reported on the SQLite mailing list is people copying data out of Oracle and running their analysis in SQLite because of the performance advantages. I wasn't aware that SQLite was so fast compared to Oracle. That's great news. I will definitely take a look at SQLite for my current data analysis project. ... hey, you're the author of APSW! :) For those following this thread, see APSW: http://code.google.com/p/apsw/ > The pragmas tune things like cache sizes. The SQLite default is 2MB, relying on the operating system for caching beyond that. Bumping up that kind of size was my suggestion :-) I missed that nuance - a side effect of emailing at 4am :) Thanks again for your help Roger! Regards, Malcolm ----- Original message ----- From: "Roger Binns" To: python-list at python.org Date: Wed, 24 Dec 2008 00:50:49 -0800 Subject: Re: Most efficient way to build very large dictionaries -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 python at bdurham.com wrote: > Thank you for your suggestion about looking at SQLite. I haven't > compared the performance of SQLite to Python dictionaries, but I'm > skeptical that SQLite would be faster than in-memory Python dictionaries > for the type of analysis I'm doing. I'd recommend at least trying a test just to see. As an example SQLite uses indices which will be faster than Python dicts for some set operations. (And if you aren't careful, your various Python based optimizations will end up duplicating what SQLite does internally anyway :-) > Prior to my use of Python, my > customer used a very expensive Oracle system to analyze their log files. > My simple Python scripts are 4-20x faster than the Oracle PL/SQL they > are replacing - and run on much cheaper hardware. SQLite is not like Oracle or any similar database system. It does not operate over the network or similar connection. It is a library in your process that has an optimized disk storage format (single file) and a SQL parser that generates bytecode for a special purpose virtual machine in pretty much the same way CPython operates. The performance improvements you are seeing with Python over Oracle are exactly the same range people see with SQLite over Oracle. One common usage reported on the SQLite mailing list is people copying data out of Oracle and running their analysis in SQLite because of the performance advantages. > Note: Memory is currently not a concern for me so I don't need SQLite's > ability to work with data sets larger than my physical memory. The pragmas tune things like cache sizes. The SQLite default is 2MB, relying on the operating system for caching beyond that. Bumping up that kind of size was my suggestion :-) Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAklR9+UACgkQmOOfHg372QSMbwCdGS5S2/96fWW8knjfBVqReAfV AEwAn2Yc+L9BEZgT69OjwtyqxLtifVpU =mPfy -----END PGP SIGNATURE----- -- http://mail.python.org/mailman/listinfo/python-list From Astley.lejasper at gmail.com Thu Dec 4 04:21:50 2008 From: Astley.lejasper at gmail.com (Astley Le Jasper) Date: Thu, 4 Dec 2008 01:21:50 -0800 (PST) Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> <126ba84a-0ea0-4a91-b7d2-89ed650e5d6c@d32g2000yqe.googlegroups.com> Message-ID: <6a302e08-e8be-4d5e-b754-11fc18468cc8@v4g2000yqa.googlegroups.com> On Dec 4, 12:34?am, Lawrence D'Oliveiro wrote: > In message , Philip > > Semanchuk wrote: > > In my experience, the environment in which a cron job runs is > > different from the environment in which some command line scripts run... > > Which is true, but again, cron should report the environment in the mail > message. For example, here are some headers from a recent run of the > maildir backup task I have scheduled twice a day: > > ? ? Subject: Cron $HOME/bin/backupdir $HOME/.maildir > ? ? X-Cron-Env: > ? ? X-Cron-Env: > ? ? X-Cron-Env: > ? ? X-Cron-Env: > ? ? X-Cron-Env: Where do you get the emails from? From skip at pobox.com Tue Dec 23 08:41:24 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 23 Dec 2008 07:41:24 -0600 Subject: pseudo terminal usage from Python? Message-ID: <18768.60036.20440.46074@montanaro-dyndns-org.local> I ran into an interesting problem yesterday. The mpstat(1) command on Solaris formats its output like so: CPU minf mjf xcal intr ithr csw icsw migr smtx srw syscl usr sys wt idl 0 42 1 1184 812 265 227 12 44 37 0 1131 6 2 0 93 1 25 1 933 447 2 203 37 75 12 0 902 5 4 0 91 2 17 0 195 495 1 201 41 77 13 0 514 5 1 0 94 3 4 0 117 882 405 171 34 65 21 0 449 5 2 0 93 I'm only interested in presenting the CPU numbers and user+sys values prefixed by a timestamp. For example, the above might be formatted like so: 07:28:46.373328 0 8 1 9 2 6 3 7 The obvious solution might be something simple like this: mpstat 1 | python mympstat.py where mympstat.py does a trival amount of reformatting. The problem is that mpstat recognizes when its output is a pipe and block buffers it so the Python script sees input in massive blobs, not the second-by-second output you'd see running "mpstat 1" by itself. I've been reduced to a much more complicated solution which involves forking mpstat with output to a file, then reading the end of that file every second. A three-line Python script balloons into a one-page script. Yuck. Add to that I'm writing this for an admin who is considering Python as a scripting language. Double Yuck. (But not nyuk nyuk, this is not the Stooges.) I suspect there is some magic I can perform with pseudo terminals (this is on Solaris 10.) The documentation for the pty module contains no examples and I've been so far unable to find any using Google. Any pointers/examples? I will gladly add an example to the pty module docs (I have the power!) once I have a couple working examples (maybe one example each of reading and writing?) Thanks, -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From sumerc at gmail.com Mon Dec 15 15:13:03 2008 From: sumerc at gmail.com (k3xji) Date: Mon, 15 Dec 2008 12:13:03 -0800 (PST) Subject: Simple multithreaded profiler using decorators fails on some built-in methods Message-ID: <64fbf6f9-99e4-4adc-b1a1-638f1b8e57b7@w24g2000prd.googlegroups.com> Hi all, I have written a simple multithreaded profiler using decorators. Below is how it works: 1) Iterate all modules in sys.modules and iterate each function/ class methods inside them, means all of them including built-in methods. 2) Decorate the methods and functions to a global function. 3) This global function acquires a global lock and updates callCount, timeElapsed values, the list of running threads and the function that the thread is currently executing. 4) We have a result(..) function which acquires the global lock again and iterates the above info with showing it in the console. The problem arises when following happens: - we call result(..) function from Thread 1 - result(..) acquires the global lock to read the information - Then, somehow in the result __repr__() builtin function is being called and as we also have decorated this function, this leads to a deadlock. Above took me 3 hours of debugging effort, and the worse part is __repr__() is NOT being called in the same place always. It is sometimes called in somestring processing in the top of the function sometimes in the below. So, I ended up avoiding __repr__() profiling in the profiler . However, this situation puts me in a position that there may be other built-in calls that may end up with a deadlock. I can afford to avoid profiling of all built-in functions but how to do that? Or is there any idea on this? IMPORTANT: I am not sure, but this problem may be the real cause of why we don't see realtime profile results on cProfile or Profile libraries? All of these profilers are have to be stopped before showing you the results, that way I can avoid the necessity of locking () in the result(..) function. Regards, From ron.reidy at gmail.com Thu Dec 11 12:34:34 2008 From: ron.reidy at gmail.com (ron.reidy at gmail.com) Date: Thu, 11 Dec 2008 09:34:34 -0800 (PST) Subject: cx_Oracle issues References: <5b2dad81-2750-4347-8079-6ab31321d579@s1g2000prg.googlegroups.com> Message-ID: <9142a8f1-7f76-4fc0-9ca1-c9dec310f2ce@r37g2000prr.googlegroups.com> On Dec 10, 9:48?am, huw_at1 wrote: > Hey all. When using cx_Oracle to run a procedure like: > > cursor.execute("select (obj.function(value)) from table where > id=blah") > > I am getting the following error: > > ORA-06502: PL/SQL: numeric or value error: character string buffer too > small ORA-06512: at line 1 > > Looking at cursor.description I get: > > [('(obj.function(value))', , 4000, 4000, 0, > 0, 1)] > > Any tips - i have never seen this error before but am guessing that > the value being returned is too big for the buffer size set for the > cursor. the procedure fetches data from a LOB. > > Any suggestions/confirmations? > > Many thanks This error is a problem with the PL/SQL, not cx_Oracle. You need to debug obj.function to see what kind of data is being accessed and then a data analysis of that data to understand why this error occurs. I can tell you the function is most likely expecting characters from a column that are numeric [0 .. 9] and is getting alpha characters. -- Ron Reidy Sr. Oracle DBA From geekmail at usenot.de Thu Dec 4 14:21:30 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Thu, 4 Dec 2008 20:21:30 +0100 Subject: Please fix your clock [was Re: Multiple equates] References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> <0147f4b7$0$20670$c3e8da3@news.astraweb.com> <20081204170017.4be41c7f@usenot.de> Message-ID: <20081204202130.326377dc@usenot.de> On Thu, 4 Dec 2008 06:40:02 +0200 "Hendrik van Rooyen" wrote: > "Andreas Waldenburger" > > > On 04 Dec 2008 15:53:21 GMT Steven D'Aprano > > wrote: > > > > > Hendrik, I think your PC's clock is wrong. You seem to be posting > > > from the future. > > > > So? Maybe he is. What's your problem? > > It was probably playing hob with his threading reader... > Sorry, I should probably have enclosed that in a tag. ;) /W -- My real email address is constructed by swapping the domain with the recipient (local part). From paul at boddie.org.uk Thu Dec 18 12:34:39 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 18 Dec 2008 09:34:39 -0800 (PST) Subject: psycopg2 and large queries References: Message-ID: On 18 Des, 16:34, Laszlo Nagy wrote: > psycopg2 is said to be db api 2.0 compilant, but apparent it is buggy. > By default, when I create a cursor with > > cur = conn.cursor() > > then it creates a cursor that will fetch all rows into memory, even if > you call cur.fetchone() on it. (I tested it, see below.) Yes, I filed a bug against psycopg2 on this very subject, although the project doesn't seem to have a bug-tracker any more. > I was looking for psycopg2 documentation, but I found nothing. However, > I found some posts telling that named cursors do support fetching a > single row at a time. Here is how to create a named cursor: > > cur = conn.cursor('mycursor') > > This is very strange, because DB API 2.0 does not have this feature. Why > this feature was created, and how to use it? Not documented. The reason is that PostgreSQL supports server-side cursors through a DECLARE ... CURSOR statement, but that statement can only be used with certain SQL statements. Other DB-API modules employ simple but imperfect tricks to guess whether the statement being issued is compatible with DECLARE ... CURSOR before automatically creating a cursor, but the psycopg2 maintainers refused to introduce such a feature as part of the default behaviour. I didn't pursue the avenue of making a suitable set of patches to satisfy both them and myself, and I subsequently went back to using pyPgSQL instead. [...] > It is clear that named cursors have very bad performance, I cannot use > them. Nameless cursors cannot be used either, because they are stressing > the system, put 100% disk I/O and big memory usage, without any good reason. > > The only one solution I found is to use named cursors, and use > fetchmany(100) instead of fetchone(). This results in fast opening > (0.005 sec) of the cursor, and good speed (30 000 rec/sec, about 75% of > the nameless version). (Do I really need to implement buffering in > Python to be efficient???) You really don't want to be traversing large data sets using fetchone, anyway. My approach (using pyPgSQL) involves fetchmany and then looping over each batch of results, if I really have to process the data in Python; most of the time I can do the processing in the database itself. > However, this is also not usable, because named cursors do not have a > ".description" property! You can try this: > > cur = conn.cursor('mycursor') > cur.execute('select name from product limit 1000000') > print repr(cur.description) ?# -> None > > This is unacceptable! This is not DB API 2.0 compilant. I have to know > the names of the columns, how can I do that? > > What am I doing wrong? Please help me! I'm not really a user of the description property, so I can't advise you there. Strictly, psycopg2 is DB-API compliant, but the interaction between result sets and cursors really doesn't live up to what the specification suggests is possible. Paul From rocky at panix.com Tue Dec 30 05:04:10 2008 From: rocky at panix.com (R. Bernstein) Date: Tue, 30 Dec 2008 05:04:10 -0500 Subject: How do I DRY the following code? References: <0169d83a$0$6988$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano writes: > On Mon, 29 Dec 2008 21:13:55 -0500, R. Bernstein wrote: > >> How do I DRY the following code? >> >> class C(): > [snip code] > > Move the common stuff into methods (or possibly external functions). If > you really need to, make them private by appending an underscore to the > front of the name. > > > class C(): > def common1(self, *args): > return "common1" > def common2(self, *args): > return "common2" > def _more(self, *args): # Private, don't touch! > return "more stuff" > > def f1(self, arg1, arg2=None, globals=None, locals=None): > ... unique stuff #1 ... > self.common1() > ret = eval(args, globals, locals) > self._more() > return retval > > def f2(self, arg1, arg2=None, *args, **kwds): > ... unique stuff #2 ... > self.common1() > ret = arg1(args, *args, **kwds) > self.common2 > return retval > > def f3(self, arg1, globals=None, locals=None): > ... unique stuff #3 ... > self.common1() > exec cmd in globals, locals > self.common2() > return None # unneeded > > def f4(self, arg1, globals=None, locals=None): > ... unique stuff #4 ... > self.common1() > execfile(args, globals, locals) > self._more() > I realize I didn't mention this, but common1 contains "try:" and more contains "except ... finally". So for example there is self.start() try: res = func(*args, **kwds) # this line is different except ... finally: ... Perhaps related is the fact that common1 and common2 are really related and therefore breaking into the function into 3 parts sort of breaks up the flow of reading one individually. I had also considered say passing an extra parameter and having a case statement around the one line that changes, but that's ugly and complicates things too. > > An explicit "return None" is probably not needed. Python functions and > methods automatically return None if they reach the end of the function. "return None" is a perhaps a stylistic idiom. I like to put "returns" at the end of a function because it helps (and Emacs) me keep indentation straight. Generally, I'll put "return None" if the function otherwise returns a value and just "return" if I don't think there is a useable return value. I've also noticed that using pass at the end of blocks also helps me and Emacs keep indntation straight. For example: if foo(): bar() else baz() pass while True: something pass > > > > > >> Above there are two kinds of duplication: that within class C and that >> outside which creates an instance of the class C and calls the >> corresponding method. > > Do you really need them? Perhaps, because they may be the more common idioms. And by having that function there a temporary complex object can be garbage collected and doesn't pollute the parent namespace. Is this a big deal? I don't know but it doesn't hurt. > If so, you're repeating yourself by definition. > That's not necessarily a problem, the stand-alone functions are just > wrappers of methods. You can decrease (but not eliminate) the amount of > repeated code with a factory function: > > def build_standalone(methodname, docstring=None): > def function(arg, arg2=None, globals=None, locals=None): > c = C() > return c.getattr(methodname)(arg, arg2, globals, locals) > function.__name__ = methodname > function.__doc__ = docstring > return function > > f1 = build_standalone('f1', "Docstring f1") > f2 = build_standalone('f2', "Docstring f2") > f3 = build_standalone('f3', "Docstring f3") Yes, this is better than the lambda. Thanks! > > There's no way to avoid the repeated f1 etc. > > But honestly, with only three such functions, I'd consider that overkill. > Yeah, I think so too. > >> Lest the above be too abstract, those who want to look at the full >> (and redundant) code: >> >> http://code.google.com/p/pydbg/source/browse/trunk/api/pydbg/api/ > debugger.py > > > You have parameters called Globals and Locals. It's the usual Python > convention that names starting with a leading uppercase letter is a > class. To avoid shadowing the built-ins, it would be more conventional to > write them as globals_ and locals_. You may or may not care about > following the convention :) Ok. Yes, some earlier code used globals_ and locals_. Thanks. > > I notice you have code like the following: > > if Globals is None: > import __main__ > Globals = __main__.__dict__ > > > I would have written that like: > > if Globals is None: > Globals = globals() Yes, that's better. Thanks. > > or even > > if Globals is None: > from __main__ import __dict__ as Globals > > You also have at least one unnecessary pass statement: > > if not isinstance(expr, types.CodeType): > expr = expr+'\n' > pass > > The pass isn't needed. > > > In your runcall() method, you say: > > res = None > self.start(start_opts) > try: > res = func(*args, **kwds) > except DebuggerQuit: > pass > finally: > self.stop() > return res > > This is probably better written as: > > self.start(start_opts) > try: > return func(*args, **kwds) > except DebuggerQuit: > return None > finally: > self.stop() See above for why I use pass. Thanks for the suggestions! > > > > > -- > Steven From google at mrabarnett.plus.com Mon Dec 15 11:24:45 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 15 Dec 2008 16:24:45 +0000 Subject: alt.possessive.its.has.no.apostrophe In-Reply-To: <4946826E.7060001@tim.thechases.com> References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> <49467CE2.3060401@holdenweb.com> <4946826E.7060001@tim.thechases.com> Message-ID: <494684CD.3@mrabarnett.plus.com> Tim Chase wrote: > Steve Holden wrote: >> This led to a schism between the British and the >> newly-independent Americans, who responded by taking the "u" >> out of colour, valour, and aluminium. > > Darn Americans and their alminim.... ;-) > > Next thing you know, they'll be putting an I in TEAM.[1] > > > > -tkc > > > [1] http://www.quotedb.com/quotes/2417 > But there is ME in TEAM. From R.Bauer at fz-juelich.de Thu Dec 18 09:04:49 2008 From: R.Bauer at fz-juelich.de (Reimar Bauer) Date: Thu, 18 Dec 2008 15:04:49 +0100 Subject: something else instead of PIL? In-Reply-To: <6df075c4-2397-4c41-9c75-64c59e7c0dd3@x16g2000prn.googlegroups.com> References: <6df075c4-2397-4c41-9c75-64c59e7c0dd3@x16g2000prn.googlegroups.com> Message-ID: imageguy schrieb: > On Dec 17, 3:48 pm, Reimar Bauer wrote: >> Hi >> >> what has happened to PIL? No updates since two years. >> >> Or does one know an alternative lib for resizing images? >> >> cheers >> Reimar > > I have found the FreeImage library with the Python bindings quite > workable. I work with multi-page TIF images and this seemed to be the > best option. > > The FreeImage library seems to be actively maintained too (Last > release in July 08 with updates to many of the image processing plug- > ins). The python bindings took me a bit to understand as they try to > emulate PIL, however they are implemented using ctypes, so you can > change/manage yourself if needed. I found working directly with the > functions exported from the .dll the best option and gave the best > performance. > > Freeimage site: http://freeimage.sourceforge.net/ > Python bindings: http://freeimagepy.sourceforge.net/ > > Hope that helps. Good luck. Working with images/graphics can make my > brain hurt sometimes. > > g. > > thanks! Reimar From philip at semanchuk.com Wed Dec 3 13:49:29 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Wed, 3 Dec 2008 13:49:29 -0500 Subject: Running a Python script from crontab In-Reply-To: References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> <126ba84a-0ea0-4a91-b7d2-89ed650e5d6c@d32g2000yqe.googlegroups.com> Message-ID: <6395AA2A-834B-4C5F-9EC9-BDD63E53E3DD@semanchuk.com> On Dec 3, 2008, at 1:33 PM, Astley Le Jasper wrote: > On 3 Dec, 16:41, Philip Semanchuk wrote: >> On Dec 3, 2008, at 10:29 AM, Astley Le Jasper wrote: >> >>> I've included a switch to include or exclude theloggingto console. >>> Whenloggingonly to file, the script runs fine. >> >>> Of course, I still don't understand whyduallogging, and specifically >>> to the console, causes a problem and if anyone has any comments >>> about >>> thedualoutputloggingcode above then I'd still be happy to hear >>> about it. >> >> Trying to write non-ASCII characters perchance? > > Errmmm ... that's kind of spoookey. I using UTF-8 encoding as I have a > lot of European language characters. But would that cause a problem > when running from crontab but not in the terminal? > > Go on then ... spill the beans. Oh, I don't know exactly. It's just what I thought of when you said that the problem occurs when logging to the console but not to files. I don't have a deep Unix background so I can't give you the details on what "the console" means to a cron job. In my experience, the environment in which a cron job runs is different from the environment in which some command line scripts run (remember my earlier suggestion about needing to explicitly set the PATH?) and so if the console for a cron job differed from the console that a Python program sees when run in a terminal, that would not surprise me. Hope it's a useful suggestion Philip From kpalamartchouk at gmail.com Fri Dec 19 08:21:06 2008 From: kpalamartchouk at gmail.com (kpalamartchouk at gmail.com) Date: Fri, 19 Dec 2008 05:21:06 -0800 (PST) Subject: Subclassing standard class: how to write my own __init__? Message-ID: <3fd1e6e7-112d-4ee3-a2ae-23f5d6d644f4@l33g2000pri.googlegroups.com> Dear All, I am trying to create a class that would extend functionality of datetime.date by implementing some functions I need, for example an optional initialisation by (year, day_of_year) instead of (year, month, day). I would like the class constructor to behave in the datetime's default way if there are no keyword arguments and do my own stuff if there are some. Here is the minimal example: ========================================= from datetime import date, timedelta class MyDateTime(date): def __init__(self, *arg, **kw): if len(kw): year = kw['year'] doy = kw['doy'] my_date = date(year=year, month=1, day=1) + timedelta (days=doy-1) date.__init__(self, year = my_date.year, month = my_date.month, day = my_date.day) else: date.__init__(self, *arg) date1 = MyDateTime(2008, 12, 19) date2 = MyDateTime(year=2008, doy=354) ========================================= It works fine when I don't supply any keyword arguments. But if I do, TypeError is happening: TypeError: function takes exactly 3 arguments (1 given) Could you help me to understand where I am wrong? Thanks From clp at rebertia.com Wed Dec 10 22:49:03 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 10 Dec 2008 19:49:03 -0800 Subject: Deeper tracebacks? In-Reply-To: <7e1c74f0-8f72-4a88-935b-90b77fe5aaa5@s37g2000vbp.googlegroups.com> References: <7e1c74f0-8f72-4a88-935b-90b77fe5aaa5@s37g2000vbp.googlegroups.com> Message-ID: <47c890dc0812101949qa793c72h26411d74a1ec0ea@mail.gmail.com> On Wed, Dec 10, 2008 at 3:50 PM, brooklineTom wrote: > On Dec 10, 5:03 pm, "Gabriel Genellina" > wrote: >> En Wed, 10 Dec 2008 16:59:16 -0200, brooklineTom >> escribi?: >> >> > I want my exception handler to report the method that originally >> > raised an exception, at the deepest level in the call-tree. Let give >> > an example. >> >> That's the default behavior, you don't have to do anything special. >> >> > import sys, traceback >> > class SomeClass: >> > def error(self): >> > """Raises an AttributeError exception.""" >> > int(3).zork() >> >> > def perform_(self, aSelector): >> > try: >> > aMethod = getattr(self, aSelector, None) >> > answer = apply(aMethod, [], {}) >> > except: AttributeError, anAttributeErrorException: >> > aRawStack = traceback.extract_stack() >> > answer = None >> >> (I assume you're using Python < 3.0) >> Use the 3-names form of the except statement: >> >> try: >> aMethod = getattr(self, aSelector, None) >> answer = aMethod() >> except AttributeError, e, tb: >> # the tb variable holds the traceback up to the error >> # the same thing you see printed by Python when >> # an unhandled error happens >> answer = None >> >> Alternatively, you can obtain the same thing with sys.exc_info()[2] >> Remember to delete any reference to the traceback object as soon as you're >> done with it; seehttp://docs.python.org/library/sys.html#sys.exc_info >> >> -- >> Gabriel Genellina > > I'm using Python 2.5. > > As I understand it, "aRawStack" (above) has the same information as > sys.exc_info()[2]. > > The deepest entry in aRawStack is the perform_ invocation. The > contents of the two bottom-most stack frames are: >>>> aRawStack[8][3] > "answer = anObject.perform_('error')" >>>> aRawStack[9][3] > 'aRawStack = traceback.extract_stack()' > > > By the time the handler is called, "zork" -- the method that was > called when the exception was raised, and "error", the method that > invoked zork, have already been removed from the stack. There is no zork() method, so it *can't have been called* and therefore *can't be in the traceback*. The error lies in the method that's trying to call a _nonexistent_ method, and that's where Python reports the error. Recall that: x.zork() is equivalent to: _z = x.zork #error occurs here, in the attribute lookup _z() #Python never gets here So no call takes place because you get an AttributeError before Python can get any further. zork() would only in the traceback if (1) it was looked up and called successfully [not the case here] and (2) an error occurred in zork()'s method body [again, not the case because it's not defined]. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From steve at REMOVE-THIS-cybersource.com.au Sat Dec 6 00:25:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Dec 2008 05:25:53 GMT Subject: Can't get exclusive file lock when safely renaming a file Message-ID: <014a049b$0$20670$c3e8da3@news.astraweb.com> I'm trying to safely rename a file without over-writing any existing files, and I've run into a problem with file locks. Here's a naive way of renaming without over-writing: import os oldname = "ham.txt" newname = "spam.txt" if not os.path.exists(newname): os.rename(oldname, newname) It's naive because there's a race-condition: if file newname is created by another process after the call to exists(), but before the call to rename(), then it will be over-written. Here's my current solution, based on advice given by people on this thread: http://mail.python.org/pipermail/python-list/2006-October/411432.html and this recipe: http://code.activestate.com/recipes/65203/ but it isn't working for me. import os, fcntl oldname = "ham.txt" newname = "spam.txt" def lock_destination(name): fileno = os.open(name, os.O_CREAT | os.O_EXCL) fcntl.flock(fileno, fcntl.LOCK_EX) # POSIX systems only return fileno # Create a test file to be renamed. f = open(oldname, 'w') f.write('this is my file\n') f.close() fileno = lock_destination(newname) # At this point, I can see "ham.txt" plus an empty file # "spam.txt" in my file browser os.rename(oldname, newname) The rename works, but here is my problem: after getting what I thought was an exclusive lock on the new file, but before calling os.rename(), I can still over-write it from another process: $ echo "this comes from another process" > spam.txt $ cat spam.txt this comes from another process This is despite running lock_destination("spam.txt"). What am I doing wrong? Before anyone asks, yes I have checked that the Python process and the shell process are in the same working directory, and therefore are writing to the same file: >>> os.read(fileno, 200) 'this comes from another process\n' I'm using Linux (Fedora). -- Steven From clp at rebertia.com Thu Dec 4 00:31:44 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 3 Dec 2008 21:31:44 -0800 Subject: How can I do this (from Perl) in Python? (closures) In-Reply-To: <68b8294c-8771-4b02-bd46-2f25f5e01602@j35g2000yqh.googlegroups.com> References: <68b8294c-8771-4b02-bd46-2f25f5e01602@j35g2000yqh.googlegroups.com> Message-ID: <47c890dc0812032131x497f51bek4388a20c3827ab1@mail.gmail.com> On Wed, Dec 3, 2008 at 9:18 PM, wrote: > I just came across http://www.perl.com/pub/a/2002/05/29/closure.html > and wanted to try the "canonical example of closures" in Python. I > came up with the following, but it fails: > > ####################### > #!/usr/bin/env python > Depending on your version of Python, you need to do either (A) or (B). (A) requires Python 3.0 IIRC. > def make_counter(start_num): > start = start_num (B) replace prev line with: start = [start_num] > def counter(): (A) add: nonlocal start > start += 1 (B) replace prev line with: start[0] += 1 > return counter > > from_ten = make_counter(10) > from_three = make_counter(3) > > print from_ten() # 10 > print from_ten() # 11 > print from_three() # 3 > print from_ten() # 12 > print from_three() # 4 > #################### > > The error message is: "UnboundLocalError: local variable 'start' > referenced before assignment". The same thing happens if I omit start > and just use start_num directly. See http://www.python.org/dev/peps/pep-3104/ for more info. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > How can I do it in Python? > -- > http://mail.python.org/mailman/listinfo/python-list > From joel.hedlund at gmail.com Wed Dec 17 08:17:28 2008 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Wed, 17 Dec 2008 14:17:28 +0100 Subject: weird dict problem, how can this even happen? In-Reply-To: <01584e96$0$20656$c3e8da3@news.astraweb.com> References: <01584e96$0$20656$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Tue, 16 Dec 2008 14:32:39 +0100, Joel Hedlund wrote: >> Duncan Booth wrote: >>> Alternatively give up on defining hash and __eq__ for FragmentInfo and >>> rely on object identity instead. >> Object identity wouldn't work so well for caching. Objects would always >> be drawn as they appeared for the first time. No updates would be shown >> until the objects were flushed from the cache. > > Perhaps I don't understand your program structure, but I don't see how > that follows. First off, please note that I consider my problem to be solved, many thanks to c.l.p and especially Duncan Booth. But of course continued discussion on this topic can be both enlightening and entertaining as long as people are interested. So here goes: I'm making a scientific program that visualizes data. It can be thought of as a freely zoomable map viewer with a configurable stack of data feature renderers, themselves also configurable to enhance different aspects of the individual features. As you zoom in, it becomes possible to render more types of features in a visually recognizable manner, so consequentially more feature renderers become enabled. The determining properties for the final image are then the coordinates and zoom level of the view, and the current renderer stack configuration. Rendering may be time consuming, so I cache the resulting bitmap fragments using a "key object" called FragmentInfo that holds this information. Some renderers may take a very long time to do their work, so in order to keep the gui nice and responsive, I interrupt the rendering chain at that point, put the remainder of the rendering chain in a job pool, and postpone finishing up the rendering until there are cpu cycles to spare. At that time, I go through the job pool and ask the cache which fragment was most recently accessed. This fragment is the most likely to actually be in the current view, and thus the most interesting for the user to have finallized. Now, when the user navigates the view to any given point, the gui asks the cache if the bitmap fragments necessary to tile up the current view have already been rendered, and if so, retrieves them straight from the cache and paints them to the screen. And that's why object identity wouldn't work. If the user changes something in the config for the current renderer stack (=mutates the objects), the renderers still retain the same object identities and therefore the old versions would be retrieved from the cache, and no updates would be shown until the fragments are flushed from the cache, and the fragment subsequently redrawn. I guess you could delve deep into the data members and pull out all their object identities and hash wrt that if you'd really want to, but I don't really see the point. The stupid cache implementation that I originally employed used a dict to store the FragmentInfo:BitmapFragment items plus a use tracker (list) on the side. This obviously doesn't work, because as soon as the renderer stack mutates, list and dict go out of sync and I can no longer selectively flush old items from the dict, because it's not readily apparent how to reconstruct the old keys. Purely using lists here is vastly superior because I can just .pop() the least recently used items from the tail and be done with them. Also for lists as small as this, the cost in performance is at most negligible. >> I've been experimenting with a list cache now and I can't say I'm >> noticing any change in performance for a cache of 100 items. > > 100 items isn't very big though. If you have 50,000 items you may notice > significant slow down :) > > If having many items in the cache is possible, you should consider using > a binary search instead of a linear search through the cache. See the > bisect module. Thanks for the tip, but I don't forsee this cache ever needing to be that big. ~100 is quite enough for keeping the gui reasonably responsive in this case. /Joel From rt8396 at gmail.com Sat Dec 6 12:08:10 2008 From: rt8396 at gmail.com (r) Date: Sat, 6 Dec 2008 09:08:10 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> <20081206133704.1bed455c@usenot.de> <4d1a952e-25ad-4b36-ba46-ed35758331b0@e1g2000pra.googlegroups.com> Message-ID: <50bbef6f-02e3-47d8-810c-179b89ccf62a@d32g2000yqe.googlegroups.com> Bad idea having two ways to do this. Pick one or the other! From steve at REMOVE-THIS-cybersource.com.au Thu Dec 18 20:48:59 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2008 01:48:59 GMT Subject: re.match() performance References: <755bd716-f5f6-4953-87a7-04ee148c3298@i18g2000prf.googlegroups.com> Message-ID: <015af4e5$0$20656$c3e8da3@news.astraweb.com> On Thu, 18 Dec 2008 05:51:33 -0800, Emanuele D'Arrigo wrote: > I've written the code below to test the differences in performance ... > ## TIMED FUNCTIONS > startTime = time.clock() > for i in range(0, numberOfRuns): > re.match(pattern, longMessage) > patternMatchingTime = time.clock() - startTime ... You probably don't need to re-invent the wheel. See the timeit module. In my opinion, the best idiom for timing small code snippets is: from timeit import Timer t = Timer("func(arg)", "from __main__ import func, arg") time_taken = min(t.repeat(number=N))/N where N will depend on how patient you are, but probably shouldn't be less than 100. For small enough code snippets, the default of 1000000 is recommended. For testing re.match, I didn't have enough patience for one million iterations, so I used ten thousand. My results were: >>> t1 = Timer("re.match(pattern, longMessage)", ... "from __main__ import pattern, re, compiledPattern, longMessage") >>> t2 = Timer("compiledPattern.match(longMessage)", ... "from __main__ import pattern, re, compiledPattern, longMessage") >>> t1.repeat(number=10000) [3.8806509971618652, 3.4309241771697998, 4.2391560077667236] >>> t2.repeat(number=10000) [3.5613579750061035, 2.725193977355957, 2.936690092086792] which were typical over a few runs. That suggests that even with no effort made to defeat caching, using pre-compiled patterns is approximately 20% faster than re.match(pattern). However, over 100,000 iterations that advantage falls to about 10%. Given that each run took about 30 seconds, I suspect that the results are being contaminated with some other factor, e.g. networking events or other processes running in the background. But whatever is going on, 10% or 20%, pre-compiled patterns are slightly faster even with caching -- assuming of course that you don't count the time taken to compile it in the first place. -- Steven From dickinsm at gmail.com Tue Dec 23 11:45:37 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 23 Dec 2008 08:45:37 -0800 (PST) Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> Message-ID: On Dec 23, 4:27?pm, ajaksu wrote: > Is "x ** 0 > 0." instead of "atan2(x, -1.) > 0." unreliable across > platforms? x**0 doesn't distinguish between x = -0.0 and x = 0.0. I suspect you're confusing -0.0**0.0 with (-0.0)**0.0. Mark From stefan_ml at behnel.de Fri Dec 19 12:07:50 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 19 Dec 2008 18:07:50 +0100 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <6r219cFfc8ovU1@mid.individual.net> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> Message-ID: <494bd4e6$0$31863$9b4e6d93@newsspool3.arcor-online.net> Thomas Heller wrote: > Mark Summerfield schrieb: >> Just a follow-up to say that the book has now been published in the >> U.S. >> It is now in stock at InformIT, and should reach other stores, e.g., >> Amazon, in a week or so. >> >> Also, the introduction, the first few pages of the first chapter, the >> whole of chapter 12 (regular expressions), and the index are now >> available for free download in a PDF from here: >> http://www.informit.com/store/product.aspx?isbn=0137129297 > > Question from a non-native english speaker: is this now valid english? > > "One of Python?s great strengths" > ^ > "and also teaches Python?s functional programming features" > ^ > "The book?s approach is wholly practical" > ^ 'Always' has been. It's not valid German, though, if that's what you are asking. Stefan From cmgui2 at gmail.com Wed Dec 10 18:39:01 2008 From: cmgui2 at gmail.com (cm_gui) Date: Wed, 10 Dec 2008 15:39:01 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <4b0f6c1a-9d3f-4fd7-8506-314d29ee87a8@k36g2000yqe.googlegroups.com> Message-ID: <7a1e6b94-1618-470c-a7ed-a2a5ada87d30@w24g2000prd.googlegroups.com> You guys are living in denial. Python is SLOW, especially for web apps. Instead of getting mad, why don't get together and come up with a faster VM/interpreter? The emperor doesn't like to be told he is not wearing any clothes? On 10 Dec, 14:48, Luis M. Gonz?lez wrote: > You are WRONG, WRONG, WRONG!! > And when I say Wrong, I mean WRONG!!! > > And I am not saying that you are confussed. > I say that you are WRONG! > > And when someone says so many times that you are wrong, it is because > you are WRONG! > And don't say that you are not wrong, because you are wrong! > > You are Wrong. Very Wrong. > > On Dec 10, 3:42?pm, cm_gui wrote: > > >http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-... > > > I fully agree with Krzysztof Kowalczyk . > > Can't they build a faster VM for Python since they love the language > > so much? > > > Python is SLOW. ? ?And I am not comparing it with compiled languages > > like C. > > Python is even slower than PHP! > > > Just go to any Python website and you will know. > > An example is:http://www2.ljworld.com/ > > And this site is created by the creators of Django! > > > And it is not just this Python site that is slow. There are many many > > Python sites which are very slow. And please don?t say that it could > > be the web hosting or the server which is slow ? because when so many > > Python sites are slower than PHP sites, it couldn?t be the web > > hosting. ? Also, Zope/Plone is even slower. > > > Python is slow. Very slow. > > From iofferkicks007 at gmail.com Mon Dec 22 00:04:26 2008 From: iofferkicks007 at gmail.com (iofferkicks007 at gmail.com) Date: Sun, 21 Dec 2008 21:04:26 -0800 (PST) Subject: www.iofferkicks.com china cheap wholesale nike shoes,air jordan shoes,air force one shoes. Message-ID: <48819351-fd60-48ea-add1-485c67e026df@a26g2000prf.googlegroups.com> Get Nike Shoes at Super Cheap Prices Discount Nike air jordans (www.iofferkicks.com) Discount Nike Air Max 90 Sneakers (www.iofferkicks.com) Discount Nike Air Max 91 Supplier (www.iofferkicks.com) Discount Nike Air Max 95 Shoes Supplier (www.iofferkicks.com) Discount Nike Air Max 97 Trainers (www.iofferkicks.com) Discount Nike Air Max 2003 Wholesale (www.iofferkicks.com) Discount Nike Air Max 2004 Shoes Wholesale (www.iofferkicks.com) Discount Nike Air Max 2005 Shop (www.iofferkicks.com) Discount Nike Air Max 2006 Shoes Shop (www.iofferkicks.com) Discount Nike Air Max 360 Catalogs (www.iofferkicks.com) Discount Nike Air Max Ltd Shoes Catalogs (www.iofferkicks.com) Discount Nike Air Max Tn Men's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 2 Women's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 3 Customize (www.iofferkicks.com) Discount Nike Air Max Tn 4 Shoes Customize ( www.iofferkicks.com) Discount Nike Air Max Tn 6 Supply (www.iofferkicks.com) Discount Nike Shox NZ Shoes Supply (www.iofferkicks.com) Discount Nike Shox OZ Sale (www.iofferkicks.com) Discount Nike Shox TL Store (www.iofferkicks.com) Discount Nike Shox TL 2 Shoes Store (www.iofferkicks.com) Discount Nike Shox TL 3 Distributor (www.iofferkicks.com) Discount Nike Shox Bmw Shoes Distributor (www.iofferkicks.com) Discount Nike Shox Elite Shoes Manufacturer (www.iofferkicks.com) Discount Nike Shox Monster Manufacturer (www.iofferkicks.com) Discount Nike Shox R4 Running Shoes (www.iofferkicks.com) Discount Nike Shox R5 Mens Shoes (www.iofferkicks.com) Discount Nike Shox Ride Womens Shoes (www.iofferkicks.com) Discount Nike Shox Rival Shoes Wholesaler (www.iofferkicks.com) Discount Nike Shox Energia Wholesaler (www.iofferkicks.com) Discount Nike Shox LV Sneaker (www.iofferkicks.com) Discount Nike Shox Turbo Suppliers (www.iofferkicks.com) Discount Nike Shox Classic Shoes Suppliers (www.iofferkicks.com) Discount Nike Shox Dendara Trainer (www.iofferkicks.com) Discount Nike Air Jordan 1 Seller (www.iofferkicks.com) Discount Nike Air Jordan 2 Shoes Seller (www.iofferkicks.com) Discount Nike Air Jordan 3 Collection (www.iofferkicks.com) Discount Nike Air Jordan 4 Shoes Collection (www.iofferkicks.com) Discount Nike Air Jordan 5 Chaussure Shoes (www.iofferkicks.com) Discount Nike Air Jordan 6 Catalog (www.iofferkicks.com) Discount Nike Air Jordan 7 Shoes Catalog (www.iofferkicks.com) Discount Nike Air Jordan 8 Customized (www.iofferkicks.com) Discount Nike Air Jordan 9 Shoes Customized (www.iofferkicks.com) Discount Nike Air Jordan 10 Wholesalers (www.iofferkicks.com) Discount Nike Jordan 11 Shoes Wholesalers (www.iofferkicks.com) Discount Nike Air Jordan 12 Factory (www.iofferkicks.com) Discount Nike Air Jordan 13 Shoes Factory (www.iofferkicks.com) Discount Nike Air Jordan 14 Shoes Sell (www.iofferkicks.com) Discount Nike Air Jordan 16 Exporter (www.iofferkicks.com) Discount Nike Air Jordan 17 Shoes Exporter (www.iofferkicks.com) Discount Nike Air Jordan 18 Offer (www.iofferkicks.com) Discount Nike Air Jordan 19 Shoes Offer (www.iofferkicks.com) Discount Nike Air Jordan 20 Manufacture (www.iofferkicks.com) Discount Nike Jordan 21 Shoes Manufacture (www.iofferkicks.com) EMAIL:IOFFERKICKS at GMAIL.COM MSN :IOFFERKICKS at MSN.COM From martin.hellwig at dcuktec.org Tue Dec 16 15:12:51 2008 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Tue, 16 Dec 2008 20:12:51 +0000 Subject: [ANN] EuroPython 2009 =?windows-1252?Q?=96_Call_for_Partic?= =?windows-1252?Q?ipation!_?= Message-ID: <49480BC3.9030002@dcuktec.org> On behalf of the EuroPython 2009 organisation it is my privilege and honour to announce the 'Call for Participation' for EuroPython 2009! EuroPython is the conference for the communities around Python, including the Django, Zope and Plone communities. This years conference will be held in Birmingham, UK from Monday 29th June to Saturday 4th July 2009. Talk & Themes Do you have something you wish to present at EuroPython? Go to http://www.europython.eu/talks/cfp/ for this years themes and submissions criteria, the deadline is on 5th April 2009. Other Talks, Activities and Events Have you got something which does not fit the above? Visit http://www.europython.eu/talks/ . Help Us Out We could use a hand any contribution is welcome, please take a look at http://www.europython.eu/contact/ . Sponsors An unique opportunity to affiliate with the prestigious EuroPython conference! http://www.europython.eu/sponsors/ Spread the Word Improve our publicity by distributing this announcement in your corner of the community, please coordinate this with the organizers: http://www.europython.eu/contact/ General Information For more information about the conference, please visit http://www.europython.eu/ Looking forward to see you! The EuroPython Team From jody.goldberg at gmail.com Wed Dec 10 06:06:46 2008 From: jody.goldberg at gmail.com (JodyGnumeric) Date: Wed, 10 Dec 2008 03:06:46 -0800 (PST) Subject: getting error...... Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in open_workbook biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) File "C:\Python25\Lib\site-pack References: <6c76b050-5b47-46f3-9097-5c58979b6913@s9g2000prg.googlegroups.com> <16d767d6-be4a-49eb-af5c-3d9e74b45458@m22g2000vbl.googlegroups.com> Message-ID: <17fce6e8-194b-4263-b322-0a8e074b3204@f33g2000vbf.googlegroups.com> On Dec 8, 9:02?pm, John Machin wrote: > On Dec 9, 12:19?pm, JodyGnumeric wrote: > > > > > On Dec 8, 5:54?am, John Machin wrote: > > > > On Dec 8, 6:48?pm, "Gabriel Genellina" wrote: > > > > > En Fri, 05 Dec 2008 02:31:01 -0200, pk sahoo ? > > > > escribi?: > > > > > > hallo everybody, > > > > > when i am running the following command > > > > > >>>> import xlrd > > > > >>>> book=xlrd.open_workbook("C:\\a.xls") > > > > > > i am getting the following error.. > > > > > > *Traceback (most recent call last): > > > > > ? File "", line 1, in > > > > > ? File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in > > > > > open_workb > > > > > ook > > > > > ? ? biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) > > > > > ? File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 1323, in > > > > > getbof > > > > > ? ? raise XLRDError('Expected BOF record; found 0x%04x' % opcode) > > > > > xlrd.biffh.XLRDError: Expected BOF record; found 0x3f3c* > > > > > Looks like your a.xls file is not an Excel file (one of the formats ? > > > > supported by xlrd). > > > > As 0x3f3c corresponds to the characters ' > > > This can be verified easily by opening the file with a simple-minded > > > text editor (e.g. Notepad) ... if the first two lines are > > > """ > > > > > > > > > """ > > > then it's an Excel 2003 XML Spreadsheet that's been manually(?) > > > renamed from .xml to .xls. > > > > The current xlrd release supports only the binary ("BIFF") format .xls > > > files created by Excel 3.0 to Excel 2003. The next release (due out > > > Real Soon Now) will support Excel 2.1 and 2.0 formats [don't ask]. > > > Very soon after that will come support for Excel 2007 .xlsx which is a > > > bunch of XML files inside a ZIP file. Support for Excel 2003 > > > "SpreadsheetML" is way down the to-do list. > > > > If the OP wants to be able to read the file with xlrd: > > > (1) Open it with Excel 200[37] and save as a .xls file > > > or (2) rename it to .xml, start OpenOffice.org Calc, click on File, > > > click on Open, click on "Files of type", choose "Microsoft Excel 2003 > > > XML (*.xml)" from the (long, unsorted) drop-down list, ..., and save > > > as etc etc. Gnumeric is not an option. > > > > HTH, > > > John > > > Gnumeric can read this format. 'MS Excel (tm) 2003 SpreadsheetML' > > [Gnumeric 1.9.1 on Windows XP] > > I'm sorry; I thought I'd exhausted every possible way of trying to > open it. After looking at the file open dialogue box again, I've > spotted the "Advanced" button. Here is what you need to do: > > Have the file named whatever.xls. Click on File / Open , navigate to > correct directory, click on Advanced, choose 'MS Excel (tm) 2003 > SpreadsheetML' from the File-type drop-down list, choose the file, > click on OK. Anything else (Simple (non-Advanced), naming it > whatever.xml, ...) produces no response, yes that's zero bits of > information, not even a Bzzzzt! noise :-( > > *AND* when it does open up, a date cell defined by > ? > ... > ss:Type="DateTime">1999-12-31T00:00:00.000 > > is displayed as "00ort 31at1999" :-( Please send the file to bugzilla.gnome.org it sounds like I need to improve the probe function function for this format and add support for the magic named formats. From mensanator at aol.com Tue Dec 30 21:05:53 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 30 Dec 2008 18:05:53 -0800 (PST) Subject: TypeError: list indices must be integers References: <2e5a61c0-fa99-4170-81ca-eb3a10859400@k36g2000pri.googlegroups.com> Message-ID: <67a3debb-ae30-47d9-ab7b-35040cde730c@q26g2000prq.googlegroups.com> On Dec 30, 7:46?pm, dubux wrote: > here is a function i wrote that doesnt work. i wrote to parse a "news" > file that is going to work in conjunction with a website via mod_wsgi. > my head hurts from looking at it so long. please help! i will further > explain in the post. > > def news(x,y): > ? ? ? ? # usage news(date, number) > ? ? ? ? # x = date/news > ? ? ? ? # y = number > ? ? ? ? news_file = '/home/scam/Desktop/www/info/news' > ? ? ? ? news = open(news_file, 'r') > ? ? ? ? news_list = news.readlines() > ? ? ? ? news.close() > ? ? ? ? if x == 'date': > ? ? ? ? ? ? ? ? mylist = map(lambda i: news_list[i], filter(lambda i: i%2 == 0, range > (len(news_list)))) > ? ? ? ? ? ? ? ? date = mylist[y] > ? ? ? ? ? ? ? ? return '
%s

' % (date) > ? ? ? ? if x == 'news': > ? ? ? ? ? ? ? ? mylist = map(lambda i: news_list[i], filter(lambda i: i%2 == 1, range > (len(news_list)))) > ? ? ? ? ? ? ? ? news = mylist[y] > ? ? ? ? ? ? ? ? return '%s
' % (news) > ? ? ? ? else: > ? ? ? ? ? ? ? ? return news_list > > and call it with the follow syntax: news('[date/news]', [any number]) > > i keep getting "TypeError: list indices must be integers" on the > following line "date = mylist[y]" > can someone please explain this and give me the proper way to achieve > what im trying to do? The code you posted assumes y is an integer. The TypeError message shows that assumption is false. Nothing in this code will help you resolve the problem, it's in the code that calls this code. Throw a print type(y),y into tha start of the definition. From jpablo.romero at gmail.com Wed Dec 10 22:02:31 2008 From: jpablo.romero at gmail.com (=?ISO-8859-1?Q?Juan_Pablo_Romero_M=E9ndez?=) Date: Wed, 10 Dec 2008 21:02:31 -0600 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: In R: norm = function(v) v/sqrt(sum(v^2)) :) Juan Pablo 2008/12/10 Arnaud Delobelle : > "Dotan Cohen" writes: > >> 2008/12/10 : >>> On Dec 5, 9:51 am, Xah Lee wrote: >>>> >>>> For those of you who don't know linear algebra but knows coding, this >>>> means, we want a function whose input is a list of 3 elements say >>>> {x,y,z}, and output is also a list of 3 elements, say {a,b,c}, with >>>> the condition that >>>> >>>> a = x/Sqrt[x^2+y^2+z^2] >>>> b = y/Sqrt[x^2+y^2+z^2] >>>> c = z/Sqrt[x^2+y^2+z^2] >>> >>>> >>>> In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, >>>> you'll have 50 or hundreds lines. >>> >>> Ruby: >>> >>> def norm a >>> s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) >>> a.map{|x| x/s} >>> end >> >> If someone doesn't counter with a Python one-liner then I'm going to >> port that to brainfuck. > > def unit(v): > return map((sum(map(lambda x:x*x, v))**0.5).__rdiv__, v) > > The hard bit was to make it less readable than the Ruby version ;) > > -- > Arnaud > -- > http://mail.python.org/mailman/listinfo/python-list > From clp at rebertia.com Mon Dec 29 20:32:08 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 29 Dec 2008 17:32:08 -0800 Subject: Python in C In-Reply-To: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> References: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> Message-ID: <47c890dc0812291732p34ab7710u5b98b30eb926113c@mail.gmail.com> On Mon, Dec 29, 2008 at 5:22 PM, wrote: > 2. Have there been any suggestions in the past to rewrite Python's > mainstream implementation in C++ (or why wasn't it done this way from > the beginning)? I'm not a CPython dev (I bet one will pipe in), but I would speculate it's because C++ is so much more complicated and a bit less portable than C. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From rt8396 at gmail.com Mon Dec 22 14:50:29 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 11:50:29 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <6ra8t0F925rU1@mid.individual.net> Message-ID: <29feda0d-6432-4cb9-8809-e4d4a7798601@e1g2000pra.googlegroups.com> OK je.s.t... whatever, We see where you stand. And also see that by removing your comments from the archive in 5 days, how small your acorns really are. From gnewsg at gmail.com Tue Dec 16 12:45:42 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Tue, 16 Dec 2008 09:45:42 -0800 (PST) Subject: Free place to host python files? References: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> <32599660-2393-4e18-8c48-05d64bccbbc1@t26g2000prh.googlegroups.com> Message-ID: On 16 Dic, 15:56, feba wrote: > On Dec 16, 8:29?am, s... at pobox.com wrote: > > > ? ? feba> I'm getting started in python, and it would be helpful to have a > > ? ? feba> place to put up various code snippets I've made, so I don't have > > ? ? feba> to send them individually to each person I want to show it to. > > ? ? feba> I'd prefer to use something that would give me a directory for my > > ? ? feba> use only, instead of something where you can only upload one at a > > ? ? feba> time. ?I'd especially like to avoid stuff that uses CAPTCHAs > > ? ? feba> and/or forced waiting periods. > > >http://pastebin.com/? > > > -- > > Skip Montanaro - s... at pobox.com -http://smontanaro.dyndns.org/ > > well, ignoring the fact that pastebin doesn't work for me for some > reason, I'm talking about hosting it as a .py downloadable, not a hunk > of text. code.google.com? It also has a SVN repository. --- Giampaolo http://code.google.com/p/pyftpdlib/ From sjmachin at lexicon.net Wed Dec 31 09:56:33 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 31 Dec 2008 06:56:33 -0800 (PST) Subject: Parsing Excel spreadsheets References: <6a54de23-bea4-40c7-ad7c-22c6eba4bd8a@z6g2000pre.googlegroups.com> Message-ID: On Dec 31 2008, 4:02?pm, brooklineTom wrote: > andyh... at gmail.com wrote: > > Hi, > > > Can anybody recommend an approach for loading and parsing Excel > > spreadsheets in Python. Any well known/recommended libraries for this? > > > The only thing I found in a brief search washttp://www.lexicon.net/sjmachin/xlrd.htm, > > but I'd rather get some more input before going with something I don't > > know. > > > Thanks, > > Andy. > > I save the spreadsheets (in Excel) in xml format. Which means that you need to be on a Windows box with a licensed copy of Excel. I presume you talking about using Excel 2003 and saving as "XML Spreadsheet (*.xml)". Do you save the files manually, or using a COM script? What is the largest xls file that you've saved as xml, how big was the xml file, and how long did it take to parse the xml file? Do you extract formatting information or just cell contents? > I started with the > standard xml tools (xml.dom and xml.dom.minidom). I built a > pullparser, and then just crack them. The MS format is tedious and > overly complex (like all MS stuff), but straightforward. What do you think of the xml spat out by Excel 2007's (default) xlsx format? > Once I've > cracked them into their component parts (headers, rows, cells, etc), > then I walk through them doing whatever I want. > > I found this material to be no worse than doing similar crud with > xhtml. I know there are various python packages around that do it, but > I found the learning curve of those packages to be steeper than just > grokking the spreadsheet structure itself. I'm curious to know which are the "various python packages" with the so steep learning curves, and what the steep bits were. Cheers, John From robert.kern at gmail.com Mon Dec 8 13:54:31 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 08 Dec 2008 12:54:31 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> Message-ID: Rhamphoryncus wrote: > On Dec 7, 4:20 pm, Steven D'Aprano cybersource.com.au> wrote: >> On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: >>> Rasmus Fogh wrote: >>>> Current behaviour is both inconsistent and counterintuitive, as these >>>> examples show. >>>>>>> x = float('NaN') >>>>>>> x == x >>>> False >>> Blame IEEE for that one. Rich comparisons have nothing to do with that >>> one. >> There is nothing to blame them for. This is the correct behaviour. NaNs >> should *not* compare equal to themselves, that's mathematically >> incoherent. > > Mathematically, NaNs shouldn't be comparable at all. They should > raise an exception when compared. In fact, they should raise an > exception when *created*. But that's not what we want. What we want > is a dummy value that silently plods through our calculations. For a > dummy value it seems a lot more sense to pick an arbitrary yet > consistent sort order (I suggest just above -Inf), rather than quietly > screwing up the sort. Well, there are explicitly two kinds of NaNs: signalling NaNs and quiet NaNs, to accommodate both requirements. Additionally, there is significant flexibility in trapping the signals. > Regarding the mythical IEEE 754, although it's extremely rare to find > quotations, I have one on just this subject. And it does NOT say "x > == NaN gives false". It says it gives *unordered*. It is C and > probably most other languages that turn that into false (as they want > a dummy value, not an error.) > > http://groups.google.ca/group/sci.math.num-analysis/browse_thread/thread/ead0392e646b7cc0/a5bc354cd46f2c49?lnk=st&q=why+does+NaN+not+equal+itself%3F&rnum=3&hl=en&pli=1 Table 4 on page 9 of the standard is pretty clear on the subject. When the two operands are unordered, the operator == returns False. The standard defines how to do comparisons notionally; two operands can be "greater than", "less than", "equal" or "unordered". It then goes on to map these notional concepts to programming language boolean predicates. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From joe at strout.net Fri Dec 19 10:20:07 2008 From: joe at strout.net (Joe Strout) Date: Fri, 19 Dec 2008 08:20:07 -0700 Subject: encoding problem In-Reply-To: <6r1m72Ffb5kpU3@mid.uni-berlin.de> References: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> <6r1m72Ffb5kpU3@mid.uni-berlin.de> Message-ID: <494BBBA7.9000109@strout.net> Marc 'BlackJack' Rintsch wrote: >> The question is why the Python interpreter use the default encoding >> instead of "utf-8", which I explicitly declared in the source. > > Because the declaration is only for decoding unicode literals in that > very source file. And because strings in Python, unlike in (say) REALbasic, do not know their encoding -- they're just a string of bytes. If they were a string of bytes PLUS an encoding, then every string would know what it is, and things like conversion to another encoding, or concatenation of two strings that may differ in encoding, could be handled automatically. I consider this one of the great shortcomings of Python, but it's mostly just a temporary inconvenience -- the world is moving to Unicode, and with Python 3, we won't have to worry about it so much. Best, - Joe From matt.dubins at sympatico.ca Thu Dec 25 13:22:15 2008 From: matt.dubins at sympatico.ca (Matthew Dubins) Date: Thu, 25 Dec 2008 13:22:15 -0500 Subject: Exec inside a class method to call other class methods? Message-ID: <4953CF57.8080905@sympatico.ca> Hello all, I have made a python script to upload contact information from an excel worksheet to an online database. One part of the program that really tripped me up was when I wanted to call specific class methods that I had made to deal with specific types of contact information (Parent's name, Child's name, Phone #, etc). My first thought was to make it easy using the exec statement. The code (a method within a class) looked like this: ---------- def parse(self, data, data_type) exec "self.__parse_%s(data)" % data_type ---------- The data_type variable contains strings that exactly match the spellings of the 2nd word in the titles of the class methods that I wanted to call for each data_type inputted into the parse function. For some reason, *it didn't work*. Alternately, I found the ugly code shown below to be functional. As you can see, for each data_type, I call the corresponding class method that I've specified. Please help me to transform my ugly functional code into concise functional code. :) Thanks, Matthew ---------- def parse(self, data, data_type): if data_type == 'nocall': self.__parse_nocall(data) elif data_type == 'DOB': self.__parse_DOB(data) elif data_type == 'gender': self.__parse_gender(data) elif data_type == 'Prematurity': self.__parse_Prematurity(data) elif data_type == 'email': self.__parse_email(data) elif data_type == 'languages': self.__parse_languages(data) elif data_type == 'phone': self.__parse_phone(data) elif data_type == 'cname': self.__parse_cname(data) elif data_type == 'pname': self.__parse_pname(data) elif data_type == 'address': self.__parse_address(data) elif data_type == 'duedate': self.__parse_dudedate(data) From rdmurray at bitdance.com Tue Dec 16 11:29:36 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Tue, 16 Dec 2008 16:29:36 +0000 (UTC) Subject: Generator slower than iterator? References: Message-ID: Quoth Lie Ryan : > On Tue, 16 Dec 2008 12:07:14 -0300, Federico Moreira wrote: > > > Hi all, > > > > Im parsing a 4.1GB apache log to have stats about how many times an ip > > request something from the server. > > > > The first design of the algorithm was > > > > for line in fileinput.input(sys.argv[1:]): > > ip = line.split()[0] > > if match_counter.has_key(ip): > > match_counter[ip] += 1 > > else: > > match_counter[ip] = 1 > > nitpick: > dict.has_key is usually replaced with > if ip in match_counter: ... I'd say it's just slightly more than a nitpick nowadays: since Python 3.0 does not support has_key, it's time to get used to not using it :) --RDM From steven at REMOVE.THIS.cybersource.com.au Mon Dec 22 20:48:28 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 23 Dec 2008 01:48:28 GMT Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> <1iscu14.oixxplpgajabN%pdorange@pas-de-pub-merci.mac.com> Message-ID: On Mon, 22 Dec 2008 14:51:32 +0100, Pierre-Alain Dorange wrote: > I'm new to python and here i discover at least 4 methods, i just make a > small script for timing those methods (100 000 times each on a set of 10 > values). > I do not use timeit, i can't make it work easyly as it need a standalone > env for each test. But that's just what timeit does: it creates a standalone environment for each test. > ---- the test script -------------------- #!/usr/bin/env python > > from math import atan2 > import time > > > def sign_0(x): > if x==0.0: > return 0.0 > elif x>0.0: > return 1.0 > else: > return -1.0 > > def sign_1(x): > if x > 0 or (x == 0 and atan2(x, -1.) > 0.): > return 1 > else: > return -1 > > def sign_2(x): > return cmp(x, 0) > > sign_3 = lambda x:+(x > 0) or -(x < 0) > > def main(): > candidates=[1.1,0.0,-0.0,-1.2,2.4,5.6,-8.2,74.1,-23.4,7945.481] > > startTime = time.clock() time.clock() is low resolution on non-Windows systems. If you are using Windows, this is okay, if you are not, you are shooting yourself in the foot. > for i in range(100000): > for value in candidates: Horribly inaccurate, because you are including the time to build a range of 100,000 integers. In Python 3, that will only be a little bit inaccurate, but in Python 2.x that will have a MAJOR effect -- possibly swamping the actual function you are calling. > s=sign_0(value) > print "sign_0 : ",time.clock() - startTime You are (possibly) including the time taken to print to std out in your time. > startTime = time.clock() > for i in range(100000): > for value in candidates: > s=sign_1(value) > print "sign_1 : ",time.clock() - startTime Repeated code is poor coding practice. Write a function that takes a function as argument, and call that: def timer(function, candidates, count=100000): loop = [None]*count startTime = time.clock() for i in loop: for value in candidates: s = function(value) return time.clock() - startTime But this is just duplicating what timeit already does. Trust me, learn to use it, you won't be sorry. Here's a trick that took me a long time to learn: instead of copying your functions into the setup code of timeit, you can just import them. This is what I would do (untested): candidates=[1.1,0.0,-0.0,-1.2,2.4,5.6,-8.2,74.1,-23.4,7945.481] setup = "from __main__ import sign_%d, candidates" from timeit import Timer template = "for x in candidates: s = sign_%d(x)" for i in range(4): t = min( Timer(template % i, setup % i).repeat() ) print "Testing sign_%d:" % i, t, "seconds" > ---- conclusions ------------------------------- None of your conclusions are safe until you have re-tested with a better timing method. That doesn't mean you are wrong, only that your reasons for believing them are weak. -- Steven From nick at craig-wood.com Wed Dec 3 05:30:50 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 03 Dec 2008 04:30:50 -0600 Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> <258cf433-f6c9-43e7-a235-f5f6b2b6433f@j39g2000yqn.googlegroups.com> <33b4cc2f-2311-491c-a2e6-9cc5452b1a6b@g38g2000yqd.googlegroups.com> Message-ID: Slaunger wrote: > Just wanted to show the end result in its actual implementation! > > I ended up *not* making a decorator, as I already had a good idea > about how to do it > using __getattr__ > > class PayloadDualFrqIQOnDemand(PayloadDualFrqIQ): > """ > This class has the same interface as its parent, > but unlike its parent, it is instantiated without > its payload parsed up in its instance attributes > Q1, I1, Q2 and I2. Instead it stores a reference to > the file object in which the Payload data can be > read, the file position and > the version of the payload data. > > On accessing one of the data attributes, the actual > payload data are read from the file, and the reference to > the file object is unbound. > The constructor signature is therefore different from its > parent as it takes the file object, position and version > as arguments instead of the actual data. > """ > > @classmethod > def _unpack_from_file(cls, f, samples, ver): > bytes = samples * cls.bytes_per_sample > initial_pos = f.tell() > f.seek(initial_pos + bytes) #Skip over the payload > return cls(f, initial_pos, samples, ver) > > @classmethod > def unpack_from_ver3_file(cls, f, samples): > return cls._unpack_from_file(f, samples, ver=3) > > @classmethod > def unpack_from_ver4_file(cls, f, samples): > return cls._unpack_from_file(f, samples, ver=4) > > data_attr_names = frozenset(["Q1", "I1", "Q2", "I2"]) > > def __init__(self, a_file, a_file_position, samples, a_version): > """ > Returns an instance where the object knows where to > look for the payload but it will only be loaded on the > first attempt to read one of the data attributes > in a "normal" PayloadDualFrqIQ object. > """ > self.f = a_file > self.file_position = a_file_position > self.samples = samples > self.ver = a_version > > def __getattr__(self, attr_name): > """ > Checks if a request to read a non-existing data attribute > has an attribute corresponding to one of the data attributes > in a normal PayloadDualFrqIQ object. > > If true, the data attributes are created and bound to the > object using the file object instance, the file position > and the version. > > It is a prerequisite that the file object is still open. > The function leaves the file object at the file position > when it entered the method > > """ > cls = self.__class__ > if attr_name in cls.data_attr_names: self.data_attr_names should do instead of cls.data_attr_names unless you are overriding it in the instance (which you don't appear to be). > initial_pos = self.f.tell() > try: > bytes = self.samples * cls.bytes_per_sample > self.f.seek(self.file_position) > buf = self.f.read(bytes) > if self.ver == 3: > bytes_to_data = cls._v3_byte_str_to_data > elif self.ver == 4: > bytes_to_data = cls._v4_byte_str_to_data > else: > raise TermaNotImplemented, \ > "Support for ver. %d not implemented." % > self.ver > I1, Q1, I2, Q2 = bytes_to_data(buf) > self.__dict__["I1"] = I1 > self.__dict__["Q1"] = Q1 > self.__dict__["I2"] = I2 > self.__dict__["Q2"] = Q2 > return self.__dict__[attr_name] I think you want setattr() here - __dict__ is an implemetation detail - classes with __slots__ for instance don't have a __dict__. I'd probably do this for k, v in zip(("I1", "Q1", "I2", "Q2"), bytes_to_data(buf)): setattr(self, k, v) return object.__getattr__(self, attr_name) That then has duplicated a list of "I1", "Q1" etc which needs to be factored out. > finally: > # Restore file position > self.f.seek(initial_pos) > # Unbind lazy attributes > del self.f > del self.ver > del self.file_position > del self.samples > > This seems to work out well. No infinite loops in __getattr__! :-) I would probably factor out the contents of the if statement into a seperate method, but that is a matter of taste! > At least it passes the unit test cases I have come up with so far. > > No guarantees though, as I may simply not have been smart enough to > bring forth unit test cases which make it crash. > > Comments on the code is still appreciated though. Looks fine! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From fakeaddress at nowhere.org Thu Dec 4 12:56:31 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 04 Dec 2008 09:56:31 -0800 Subject: python an sqlite objects In-Reply-To: References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <18742.47391.389709.119341@montanaro-dyndns-org.local> Message-ID: Gerhard H?ring wrote: > Be sure to save it as BLOB, not TEXT. > > Suppose you have serialized your object as Python bytestring. > > serialized = ... > ... .execute("insert into mytable(mycolumn) values (?)", > (sqlite3.Binary(serialized),)) > > This way you will get a BLOB in the form of a Python buffer object when > you later select it from the database [...] Good advice for now, with Python 2.X. Python 3 resolves most of confusion with its distinction between the string type and the bytes types. The 3.x standard library sqlite3 module understands the 'bytes' and 'bytearray' types, and treats them appropriately. Here's a runnable Python 3 demo: # Ensure that we're running Python 3 or later. import sys assert int(sys.version.split()[0].split('.')[0]) >= 3 # If there's a better way to chek, please tell. # sqlite3 became part of the standard library as of Python 2.5. import sqlite3 # Create an in-memory database and one table. db = sqlite3.connect(':memory:') db.execute('CREATE TABLE demo (num INTEGER, txt TEXT, bin BLOB)') # Create a bytes object containing every possible byte value. input_blob = bytes(range(256)) # Demo the bytes object. assert len(input_blob) == 256 for i in range(256): assert input_blob[i] == i # Insert a test record. # The input blob goes into both a TEXT field and a BLOB field db.execute('INSERT INTO demo (num, txt, bin) VALUES (?, ?, ?)', (42537, input_blob, input_blob)) # Fetch back the one and only record. cursor = db.execute('SELECT num, txt, bin FROM demo') num, txt, blob = cursor.fetchone() # Verify that we got back what we stored. assert num == 42537 assert type(txt) == type(blob) == bytes assert txt == blob == input_blob If we change the input type from 'bytes' to 'bytearray', the demo still works in that the value selected back from the database is of type bytes. The database understands that the value is binary and not unicode, and he retrieved value is still the immutable bytes type, not bytearray. Why doesn't the column's declared type, 'TEXT' versus 'BLOB', matter? sqlite is type-loose, which its author considers a valuable feature and some us consider a defect. sqlite does not generally require that the value stored in a field (column) be of the field's declared type. When an inserted value's type does not match the field's declared type, most other database systems will try to convert the given object to the field's declared type. sqlite3 is different; it will try to make an exception to the field's declared type and store the object as the type with which it came in. -- --Bryan From robert.kern at gmail.com Mon Dec 8 00:04:08 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 07 Dec 2008 23:04:08 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: References: <014c593e$0$20670$c3e8da3@news.astraweb.com> Message-ID: James Stroud wrote: > Robert Kern wrote: >> James Stroud wrote: >>> I'm missing how a.all() solves the problem Rasmus describes, namely >>> that the order of a python *list* affects the results of containment >>> tests by numpy.array. E.g. "y in ll1" and "y in ll2" evaluate to >>> different results in his example. It still seems like a bug in numpy >>> to me, even if too much other stuff is broken if you fix it (in which >>> case it apparently becomes an "issue"). >> >> It's an issue, if anything, not a bug. There is no consistent >> implementation of bool(some_array) that works in all cases. numpy's >> predecessor Numeric used to implement this as returning True if at >> least one element was non-zero. This works well for bool(x!=y) (which >> is equivalent to (x!=y).any()) but does not work well for bool(x==y) >> (which should be (x==y).all()), but many people got confused and >> thought that bool(x==y) worked. When we made numpy, we decided to >> explicitly not allow bool(some_array) so that people will not write >> buggy code like this again. >> >> The deficiency is in the feature of rich comparisons, not numpy's >> implementation of it. __eq__() is allowed to return non-booleans; >> however, there are some parts of Python's implementation like >> list.__contains__() that still expect the return value of __eq__() to >> be meaningfully cast to a boolean. >> > > You have explained > > py> 112 = [1, y] > py> y in 112 > Traceback (most recent call last): > File "", line 1, in > ValueError: The truth value of an array with more than one element is... > > but not > > py> ll1 = [y,1] > py> y in ll1 > True > > It's this discrepancy that seems like a bug, not that a ValueError is > raised in the former case, which is perfectly reasonable to me. Nothing to do with numpy. list.__contains__() checks for identity with "is" before it goes to __eq__(). -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From stephen at thorne.id.au Fri Dec 12 17:38:21 2008 From: stephen at thorne.id.au (Stephen Thorne) Date: Sat, 13 Dec 2008 08:38:21 +1000 Subject: How do I manually uninstall setuptools (installed by egg)? In-Reply-To: References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> <47c890dc0812091904p12e75510sbe0b8858eb2f6d9e@mail.gmail.com> Message-ID: <20081212223821.GA4635@thorne.id.au> On 2008-12-12, Nick Craig-Wood wrote: > Failing that I'll use bdist_rpm then alien to convert to a deb which > works well enough I find. Ages ago there was a bdist_deb that was in the python bug tracker, long since that bug tracker has been transitioned to another one, and that attachment was lost. Another pythoneer still had it a few years later, and I got it from him. In an effort to help people create real packages from python software, rpms and debs, I put together a small program to download source from pypi and convert it into an OS installable package. This is known to work on some redhat systems (modulo a problem with the redhat macro for doing python byte compilation automatically on all packages), and debian based systems. You can find the work I did on: https://launchpad.net/packaging http://pypi.python.org/pypi/packaging And more importantly, you can find bdist_deb.py here: http://bazaar.launchpad.net/~jerub/packaging/trunk/annotate/11?file_id=bdist_deb.py-20080507003948-5c5mn3f68meq60hs-1 -- Regards, Stephen Thorne Development Engineer NetBox Blue - 1300 737 060 Scanned by the NetBox from NetBox Blue (http://netboxblue.com/) Can you afford to be without a NetBox? Find out the real cost of internet abuse with our ROI calculator. http://netboxblue.com/roi Scanned by the NetBox from NetBox Blue (http://netboxblue.com/) From manu3d at gmail.com Mon Dec 1 10:43:44 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Mon, 1 Dec 2008 07:43:44 -0800 (PST) Subject: Two attributes! Why? References: <76bc5df8-26fd-4e2d-a134-c5d13ea3b39a@n10g2000yqm.googlegroups.com> <0140c948$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Nov 29, 5:21?am, Steven D'Aprano wrote: > This is a side-effect of name-mangling. Double-underscore names are only > mangled when they are referred to directly as attributes, not when they > are passed to setattr, getattr etc. Those functions don't do any name > mangling. Ah! That make sense! Thank you! It's a bit of an obscure thing right now. I don't see mention of it in the description of the setattr/getattr built-ins: http://docs.python.org/library/functions.html Wouldn't be good to have a hint of the issue there? Manu From martin at marcher.name Fri Dec 26 20:29:39 2008 From: martin at marcher.name (Martin) Date: Sat, 27 Dec 2008 02:29:39 +0100 Subject: multiply each element of a list by a number In-Reply-To: References: Message-ID: <5fa6c12e0812261729t7a689799m92a17aa9d8204d22@mail.gmail.com> you might also want to look into the map(elem), and filter(elem) builtins >>> def multby3(elem): ... return elem * 3 ... >>> map(multby3, (1, 2, 3, )) [3, 6, 9] >>> help(map) >>> def even(elem): ... return not elem % 2 ... >>> filter(even, (1, 2, 3, )) (2,) >>> help(filter) KeyboardInterrupt >>> map(multby3, filter(even, (1, 2, 3, ))) [6] >>> hth martin 2008/12/27 Scott David Daniels : > Tim Chase wrote: >>> >>> What does *not* work is 3 * [0,1,2] >>> As you know, this gives >>> [0,1,2,0,1,2,0,1,2] >>> What I am hoping for is >>> [0,3,6] -- http://soup.alt.delete.co.at http://www.xing.com/profile/Martin_Marcher http://www.linkedin.com/in/martinmarcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From aahz at pythoncraft.com Sun Dec 7 15:09:23 2008 From: aahz at pythoncraft.com (Aahz) Date: 7 Dec 2008 12:09:23 -0800 Subject: [OT] [sort of] Malcom Reynolds? References: <20081207210016.751a33c9@usenot.de> Message-ID: In article <20081207210016.751a33c9 at usenot.de>, Andreas Waldenburger wrote: > >Just found this in the re module's docs: > > m = re.match(r"(?P\w+) (?P\w+)", "Malcom > Reynolds") > >Does this represent an attempt to phase out the gratuitous Monty Python >references in favor of gratuitous Firefly references? Because if so, >I'm all for it. Ask Georg Brandl: http://svn.python.org/view/python/trunk/Doc/library/re.rst?rev=67553&view=log -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From steve at REMOVE-THIS-cybersource.com.au Tue Dec 2 06:06:08 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Dec 2008 11:06:08 GMT Subject: optimization References: <6672532a-f162-4717-b0bb-c613214b57db@d32g2000yqe.googlegroups.com> Message-ID: <01450e77$0$20670$c3e8da3@news.astraweb.com> On Mon, 01 Dec 2008 19:06:24 -0600, Robert Kern wrote: > As Neal has observed, there is a performance hit for creating functions > inside of another function. True, but it's not a big hit, and I believe it is constant time regardless of the size of the function. The inner function has been (mostly) pre-compiled into bits, and assembling the bits is quite fast. On my desktop, I measure the cost of assembling the inner function to be around the same as two function lookups and calls. >>> def outer(): ... def inner(): ... return None ... return inner() ... >>> def ginner(): ... return None ... >>> def gouter(): ... return ginner() ... >>> from timeit import Timer >>> t1 = Timer('outer()', 'from __main__ import outer') >>> t2 = Timer('gouter()', 'from __main__ import gouter, ginner') >>> t1.repeat() [1.782930850982666, 0.96469783782958984, 0.96496009826660156] >>> t2.repeat() [1.362678050994873, 0.77759003639221191, 0.58583498001098633] Not very expensive. > Every time you go through the outer > function, you are creating new function objects for all of the inner > functions. That's how you can get lexical scoping. It is not equivalent > to defining the functions all at the top-level, where all of the > function objects are created at once. The compiler can't optimize that > overhead away because the overhead arises from implementing a real > feature. But the time it takes to parse the function and compile it to code is optimized away. >>> outer.func_code.co_consts (None, ", line 2>) Which makes me wonder, is there anything we can do with that code object from Python code? I can disassemble it: >>> import dis >>> dis.dis(outer.func_code.co_consts[1]) 3 0 LOAD_CONST 0 (None) 3 RETURN_VALUE Anything else? -- Steven From gandalf at shopzeus.com Tue Dec 30 08:42:32 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 30 Dec 2008 14:42:32 +0100 Subject: select.select and socket.setblocking Message-ID: <495A2548.8010007@shopzeus.com> I'm using this method to read from a socket: def read_data(self,size): """Read data from connection until a given size.""" res = "" fd = self.socket.fileno() while not self.stop_requested.isSet(): remaining = size - len(res) if remaining<=0: break # Give one second for an incoming connection so we can stop the # server in seconds when needed ready = select.select([fd], [], [], 1) if fd in ready[0]: data = self.socket.recv(min(remaining,8192)) # 8192 is recommended by socket.socket manual. if not data: # select returns the fd but there is no data to read -> connection closed! raise TransportError("Connection closed.") else: res += data else: pass if self.stop_requested.isSet(): raise SystemExit(0) return res This works: if I close the socket on the other side, then I see this in the traceback: File "/usr/home/gandalf/Python/Projects/OrbToy/orb/endpoint.py", line 233, in read_data raise TransportError("Connection closed.") TransportError: Connection closed. Also when I call stop_requested.set() then the thread stops within one seconds. Then I switch to non blocking mode, my code works exactly the same way, or at least I see no difference. I have read the socket programming howto ( http://docs.python.org/howto/sockets.html#sockets ) but it does not explain how a blocking socket + select is different from a non blocking socket + select. Is there any difference? Thanks From greg at cosc.canterbury.ac.nz Tue Dec 9 01:59:10 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 09 Dec 2008 19:59:10 +1300 Subject: Guido's new method definition idea In-Reply-To: <79139d04-bd26-4f36-b8c9-19554e7d4e95@e18g2000yqo.googlegroups.com> References: <014a071a$0$20670$c3e8da3@news.astraweb.com> <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> <79139d04-bd26-4f36-b8c9-19554e7d4e95@e18g2000yqo.googlegroups.com> Message-ID: <6q6j50Fau4iiU1@mid.individual.net> anthony.tolle at gmail.com wrote: > On another related note, I would be interested in seeing this syntax > adopted for a different purpose... > > class C: > def createfunc(self): > def self.func(arg): > return arg + 1 I agree -- this would be a much better use of the syntax, and I'd like to see this possibility left open. -- Greg From bertilow at gmail.com Sat Dec 6 09:01:29 2008 From: bertilow at gmail.com (Bertilo Wennergren) Date: Sat, 06 Dec 2008 23:01:29 +0900 Subject: Learning Python now coming from Perl In-Reply-To: References: Message-ID: Roy Smith wrote: > Bertilo Wennergren wrote: >> I'm planning to start learning Python now, using Python 3000. >> I have no previous Python skills, but I now Perl pretty well. >> I'm also well experienced with JavaScript. >> >> Any pointers and tips how I should go about getting into >> Python? > I assume you use Perl to solve real problems in whatever job you do. My > recommendation would be the next time some problem comes up that you would > normally solve with Perl, try doing it in Python. Having a real task that > you need to accomplish is a great way to focus the mind. For your first > project, pick something that's small enough that you think you could tackle > it in under 50 lines of Perl. Good advice. > One of the very first things you'll probably discover that's different > between Perl and Python is how they handle string pattern matching. In > Perl, it's a built in part of the language syntax. In Python, you use the > re module. The regular expressions themselves are the same, but the > mechanism you use to apply them to input text is quite different. Thanks. I don't suppose there is any introductory material out there that is based on Python 3000 and that is also geared at people with a Perl background? Too early for that I guess.. -- Bertilo Wennergren From press.saltmarch at gmail.com Thu Dec 4 06:45:45 2008 From: press.saltmarch at gmail.com (Shaguf) Date: Thu, 4 Dec 2008 03:45:45 -0800 (PST) Subject: Microsoft MVP Donald Belcham to Speak on Visual Studio, C# vNext, Aspect Oriented Programming, Live Mesh Message-ID: <99b9f43a-f583-4c94-a823-b17a1910f0be@y1g2000pra.googlegroups.com> Microsoft MVP Donald Belcham to Speak on Visual Studio, C# vNext, Aspect Oriented Programming, Live Mesh Bangalore, December 1, 2008: When writing Microsoft technology-related applications to have strong separations of concerns you inevitably run across some items that, while appearing as separate concerns, do not behave in the same manner as the other concerns. Instead of interacting only with their immediate neighbors, these concerns can interact with some or all of the concerns within the application. Donald Belcham is coming back this summer to India's biggest summit for the developer ecosystem - Great Indian Developer Summit ( http://www.developersummit.com ) to explore crosscutting concerns, how you can use Aspect Oriented Programming to maintain good separation of concerns in your code without losing the crosscutting functionality you also require. Microsoft MVP Donald will also conduct an early discussion of the impending changes in the upcoming version of Visual Studio and the C# language, and how they will affect your every day development work. On April 25, Donald will conduct a 3 hour workshop about Live Mesh for creating Software as a Service (SaaS) applications -- he will detail the architecture of Live Mesh (from the developer's standpoint), how to code to interact with the framework and what possibilities there may be for application in mainstream business software. The President of the Edmonton .NET User Group will also explore the problems encountered during the life of a project -- technical, social and management related. A battle hardened team lead who has survived trench warfare, Donald will explore the problems, solutions tried, successes and failures (there were many) that occurred along the way to help you get your project to near-utopian levels. About Great Indian Developer Summit Great Indian Developer Summit, produced by Saltmarch Media (http:// www.saltmarch.com/) is the biggest gathering of software developers from Java/J2EE, Microsoft computing technologies, Rich Internet Applications (RIA), Web 2.0, Ajax, Agile, SOA, and Enterprise IT. For both veterans and newcomers to the world of .NET, Java, and the Rich Web, the Great Indian Developer Summit provides participants with a well-balanced learning experience that guaranteed they went back with a richer understanding of the technologies that make a difference to their careers. See the GIDS 2008 Red Stripe Report: http://www.developersummit.com/2008/report/pdf/Red_Stripe_Report-GIDS08.zip Over 3000 qualified and talented delegates - Source, attended GIDS 2008: The Hindu - Monday, 26 May 2008 (http://www.developersummit.com/ 2008/report/postPress.html). With outstanding educational sessions, powerhouse speakers, a high-profile award ceremony, GIDS 2009 will feature premium knowledge, action plans and advise from been-there- done-it veterans, creators, and visionaries. For further information on GIDS 2009, please visit the summit on the web http://www.developersummit.com/. A Saltmarch Media Press Release E: info at saltmarch.com Ph: +91 80 4005 1000 From Scott.Daniels at Acm.Org Sat Dec 27 17:12:29 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 27 Dec 2008 14:12:29 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: Daniel Fetchinson wrote: > I'm trying to write an extension module in C which contains a single > function with the following prototype: > void func( int N, int * arg1, int * arg2, int * ret ); > Here arg1 and arg2 are length N arrays, and the function computes ret > which is also an N length array. From python I'd like to call this > function as > ret = func( [ 1, 2, 3 ], [ 2, 3, 4] ) This requirement pretty much dictates the slow answer you have. > Does this mean that I can only pass the arrays from python to C as > generic python objects and in a later operation I need to get the > elements from this generic python object, construct a C array and pass > that to the C function? ... What's the simplest way of doing this? Either use ctypes, look into array.array, or look into numpy.array. I'd just use numpy, myself: import numpy total = numpy.array([1, 2, 3]) + numpy.array([2, 3, 4]) --Scott David Daniels Scott.Daniels at Acm.Org From bj_666 at gmx.net Mon Dec 15 16:35:05 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 15 Dec 2008 21:35:05 GMT Subject: How can I return a non-zero status result from a python script? References: <74b53da4-bf07-431b-898b-49977f7a685c@r36g2000prf.googlegroups.com> Message-ID: <6qo0s9Fda9rhU2@mid.uni-berlin.de> On Mon, 15 Dec 2008 13:12:08 -0800, silverburgh.meryl at gmail.com wrote: > How can I return a non-zero status result from the script? Just do a > return 1? at the end? ``sys.exit(42)`` Ciao, Marc 'BlackJack' Rintsch From joe at strout.net Tue Dec 16 15:25:17 2008 From: joe at strout.net (Joe Strout) Date: Tue, 16 Dec 2008 13:25:17 -0700 Subject: How to modify a program while it's running? Message-ID: Here's my situation: I'm making an AIM bot, but the AIM server will get annoyed if you log in too frequently (and then lock you out for a while). So my usual build-a-little, test-a-little methodology doesn't work too well. So I'd like to restructure my app so that it can stay running and stay logged in, yet I can still update and reload at least most of the code. But I'm not sure what's the best way to do this. Should I move the reloadable code into its own module, and then when I give my bot a "reload" command, have it call reload on that module? Will that work, and is there a better way? Thanks, - Joe From sln at netherlands.com Tue Dec 9 21:09:00 2008 From: sln at netherlands.com (sln at netherlands.com) Date: Wed, 10 Dec 2008 02:09:00 GMT Subject: Mathematica 7 compares to other languages References: <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <4ridneQnkLrPkKDUnZ2dnUVZ8qbinZ2d@posted.plusnet> <986b6ea1-efba-4146-9704-5f9e3787c26a@a37g2000pre.googlegroups.com> Message-ID: On Tue, 9 Dec 2008 15:19:47 -0800 (PST), Xah Lee wrote: >On Dec 8, 4:07 am, Jon Harrop wrote: >> s... at netherlands.com wrote: >> > Well, its past 'tonight' and 6 hours to go till past 'tomorrow'. >> > Where the hell is it Zah Zah? >> >> Note that this program takes several days to compute in Mathematica (even >> though it takes under four seconds in other languages) so don't expect to >> see a genuinely optimized version any time soon... ;-) > >Note that Jon's Mathematica code is of very poor quality, as i've >given detailed analysis here: > >? A Mathematica Optimization Problem > http://xahlee.org/UnixResource_dir/writ/Mathematica_optimization.html > >I'm not sure he's intentionally making Mathematica look bad or just >sloppiness. I presume it is sloppiness, since the Mathematica code is >not shown in his public website on this speed comparison issue. (as >far as i know) I suppose, he initialled tried this draft version, saw >that it is too slow for comparsion, and probably among other reason he >didn't include it in the speed comparison. However, in this thread >about Mathematica 7, he wanted to insert his random gribe to pave >roads to post his website books and url on OCml/f#, so he took out >this piece of Mathematica to bad mouth it and bait. He ignored my >paypal challenge, but it so happens that someone else paid me $20 to >show a better code, and in the showdown, Jon went defensive that just >make him looking like a major idiot. > > Xah >? http://xahlee.org/ > >? Ad hominem From gagsl-py2 at yahoo.com.ar Wed Dec 24 13:48:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2008 16:48:06 -0200 Subject: Iterating over objects of a class References: <2df27de3-7fa3-4ac9-acd9-f946939517cf@r37g2000prr.googlegroups.com> <6rfb7iF1fg5rU1@mid.uni-berlin.de> <7f47994f-13b6-45c4-920a-83aa72282bec@i20g2000prf.googlegroups.com> Message-ID: En Wed, 24 Dec 2008 16:18:55 -0200, Kottiyath escribi?: >> The other thing to remember is that because the 'registry' contains >> references to the instances, they won't be garbage collected. > > Is there any other way out in this case? > I have factory methods - and I have to loop over them - sort of Chain > of Responsibility pattern. > Having a registry inside the class instance and looping through them > was the only clean thing I could think of. > I understand that garbage collection would be an issue - but is there > any way out? You may keep all that structures - just use weak references (see the weakref module). There isn't a WeakList nor WeakSet out-of-the-box but you may use a WeakKeyDictionary (set the value to anything, None by example). -- Gabriel Genellina From jelsas at gmail.com Wed Dec 10 11:45:44 2008 From: jelsas at gmail.com (jelsas) Date: Wed, 10 Dec 2008 08:45:44 -0800 (PST) Subject: Maintaining signature in help(decorated function) References: <48f2fd47-1fc3-4b2f-ad39-24adce7e9a5c@k36g2000yqe.googlegroups.com> <941d9581-6165-4513-b172-a1d6295285d3@b38g2000prf.googlegroups.com> Message-ID: <7859eb26-3ba8-4630-9d0d-ac39b2962180@i20g2000prf.googlegroups.com> Thanks! This is exactly what I needed. From lie.1296 at gmail.com Tue Dec 30 08:24:18 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 30 Dec 2008 13:24:18 +0000 (UTC) Subject: string in files References: <62075511-08ad-405a-a3af-2da8d2f22c50@v39g2000pro.googlegroups.com> Message-ID: On Tue, 30 Dec 2008 11:53:17 +0100, Glauco wrote: >> thanks brother >> i mean how do i particularly assign (u = this) >> (y = is).... >> in the strings up there. i have been able to split strings with any >> character sign. >> >> > > If i'm not wrong this is simple with RE: > Using Regular Expression for this is an overkill, you'd better use the str.split: longstring = 'this is a python string' splitted_string = longstring.split() result = ', '.join(splitted_string[:-1]) + ' and ' + splitted_string[-1] From steven at REMOVE.THIS.cybersource.com.au Mon Dec 8 23:00:21 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 09 Dec 2008 04:00:21 GMT Subject: RuntimeError: dictionary changed size during iteration References: <274eb282-1635-40ca-95af-b82271c57802@v4g2000yqa.googlegroups.com> Message-ID: On Mon, 08 Dec 2008 19:10:00 -0800, Robert Dailey wrote: > On Dec 8, 6:26?pm, Terry Reedy wrote: >> Robert Dailey wrote: >> > stuff = vars() >> >> ?>>> vars() is globals() >> True >> >> > for key in stuff: >> >> You just changed globals, which is aliased as stuff. Stuff changes. >> >> > ? ? print( key, '--', stuff[key] ) >> >> > I get the following error message: >> > ('CopyEmotionFX', '--', ) >> > Traceback (most recent call last): >> > ? File "C:\IT\work\jewett\depends.py", line 12, in >> > ? ? for key in stuff: >> > RuntimeError: dictionary changed size during iteration >> >> > Why is this happening? >> >> >> > How am I changing globals()? I'm simply iterating the keys in the dict. > Can someone explain what is going on please? You create an new name "key": for key in stuff I suppose you could do this: key = None stuff = vars() for key in stuff: but even better would be: for key in vars().copy(): because that protects you from cases where globals() change inside the for loop. -- Steven From sjmachin at lexicon.net Wed Dec 17 10:23:40 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 17 Dec 2008 07:23:40 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> <0d9ea7cc-b5fb-4edb-be32-490aae9e7204@b41g2000pra.googlegroups.com> <0de3a7bf-a4c4-4103-a4e0-44313405fa94@z28g2000prd.googlegroups.com> Message-ID: On Dec 18, 1:28?am, aka wrote: > Hi John, thanks. > You're right, I didn't past the method header because I thought it > didn't matter when the input filename is hardcoded. > The try/except isn't very helpful indeed so I commented it out. > You're right I wrongly referred to the UnicodeReader > class in my first post because that's ultimately where I want to go > so > I outcommented it here for you to see. > The fact is that neither csv.reader nor the UnicodeReader will read > the file, while writing with the UnicodeWriter > works like a charm. > That's why I put str() around roles to see any content. > I simplified the csv-file by cutting off columns without result. The > file looks now like: > > id;company;department > 12;Cadillac;Research > 11;Ford;Accounting > 10;Chrysler;Sales > > The dictionary on the return is because this code is part of my > TurboGears application. > The entire method is: > > import csv > from utilities.urw ? ? ? import UnicodeWriter, UnicodeReader Pardon my ignorance, but what is "utilities.urw"?? > > ? ? @expose(allow_json=True) Means what? Does what? Does the problem still happen without that? Funny, the indentation changed there --- for the very last time, is that the actual code of a standalone script that reproduces the problem? > ? ? def import_roles(self, input=None, *args, **kwargs): > ? ? ? ? inp = 'C:/temp/test.csv' > ? ? ? ? roles = [] > ? ? ? ? msg = '' > ? ? ? ? ## try: > ? ? ? ? fp = open(inp, 'rb') > ? ? ? ? reader = csv.reader(fp, dialect='excel', delimiter=';') > ? ? ? ? ## reader = UnicodeReader(fp, dialect='excel', delimiter=';') > ? ? ? ? for r in reader: > ? ? ? ? ? ? roles.append(r[0]) > ? ? ? ? fp.close() > ? ? ? ? ## except: > ? ? ? ? ? ? ## msg = "Something's wrong with the csv.reader" > ? ? ? ? return dict(filepath=inp, > ? ? ? ? ? ? ? ? ? ? roles=str(roles), > ? ? ? ? ? ? ? ? ? ? msg=msg) > > csv.reader results in: for r in reader: Error: line contains NULL > byte Looks like the file is stuffed. Have you tried inspecting it with a tool that would actually show a '\x00' or a '\xff' unambiguously? If you don't have a fancy one, use the Python interactive prompt: open('your_file.csv', 'rb').read() > > Use of UnicodeReader results in: UnicodeDecodeError: 'utf8' codec > can't decode byte 0xff in position 0: unexpected code byte > > Will post only complete code from now on thanks. Just make sure it's runnable and it's what you actually ran thanks. From hsoft at hardcoded.net Sat Dec 6 18:01:39 2008 From: hsoft at hardcoded.net (Virgil Dupras) Date: Sun, 7 Dec 2008 00:01:39 +0100 Subject: [Python-Dev] "as" keyword woes In-Reply-To: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> Message-ID: <1BA80D7C-44A6-4DE0-AC43-A99B50DF3F5E@hardcoded.net> On 06 Dec 2008, at 20:38, Warren DeLano wrote: > >> Date: Fri, 05 Dec 2008 22:22:38 -0800 >> From: Dennis Lee Bieber >> Subject: Re: "as" keyword woes >> To: python-list at python.org >> Message-ID: >> >> I'm still in the dark as to what type of data could >> even inspire the >> use of "as" as an object name... A collection of "a" objects? In >> which >> case, what are the "a"s? > > Please let me clarify. It is not "as" as a standalone object that we > specifically miss in 2.6/3, but rather, the ability to use ".as" > used as > a method or attribute name. > > In other words we have lost the ability to refer to "as" as the > generalized OOP-compliant/syntax-independent method name for casting: > > new_object = old_object.as(class_hint) > > # For example: > > float_obj = int_obj.as("float") > > # or > > float_obj = int_obj.as(float_class) > > # as opposed to something like > > float_obj = int_obj.asFloat() > > # which requires a separate method for each cast, or > > float_obj = (float)int_obj > > # which required syntax-dependent casting [language-based rather than > object-based]. > > Of course, use of explicit casting syntax "(float)" is fine if you're > restricting yourself to Python and other languages which support > casting, but that solution is unavailable inside of a pure OOP > message-passing paradigm where object.method(argument) invocations are > all you have to work with. > > Please note that use of object.asClassname(...) is a ubiqitous > convention for casting objects to specific classes (seen in > ObjectiveC, > Java, SmallTalk, etc.). > > There, I assert that 'object.as(class_reference)' is the simplest and > most elegant generalization of this widely-used convention. Indeed, > it > is the only obvious concise answer, if you are limited to using > methods > for casting. > > Although there are other valid domain-specific uses for "as" as > either a > local variable or attribute names (e.g. systematic naming: as, bs, > cs), > those aren't nearly as important compared to "as" being available as > the > name of a generalized casting method -- one that is now strictly > denied > to users of Python 2.6 and 3. > > As someone somewhat knowledgable of how parsers work, I do not > understand why a method/attribute name "object_name.as(...)" must > necessarily conflict with a standalone keyword " as ". It seems to me > that it should be possible to unambiguously separate the two without > ambiguity or undue complication of the parser. > > So, assuming I now wish to propose a corrective PEP to remedy this > situation for Python 3.1 and beyond, what is the best way to get > started > on such a proposal? > > Cheers, > Warren > As long as "as" is widely known as a keyword, I don't see the problem. Every python developer knows that the convention is to add a trailing underscore when you want to use a reserved word in your code. Besides, your examples are quite abstract. I'm sure it's possible to find good examples for "while", "with", "import", "from" (I often use "from_") or "try" as well. Or perhaps that the python keywords should be "as_" so we leave "as" free for eventual methods? As for the implicit proposition of allowing keywords only for methods, I agree with Guido about it being a slippery slope. So we would end up with a language where it is allowed to name methods after keywords, but not functions (they can be declared in the local scope)? Yikes! Oh well, maybe it's possible for an intelligent parser to distinguish between keywords and function references, but think of the poor grammar highlighters in all source editors! What a nightmare it will be for them. Anyway, is there any language that does this, allowing keywords as method names? I don't know, but if not, there's probably a reason for it. Your views on code elegance are also rather Javaish. I'd go for "class_reference(object)" (and why the heck would you "be limited to using method for casting"?). Ciao, Virgil From roy at panix.com Tue Dec 9 19:58:18 2008 From: roy at panix.com (Roy Smith) Date: Tue, 09 Dec 2008 19:58:18 -0500 Subject: How to initialize a class variable once References: <493E5700.4030107@aim.com> Message-ID: In article , Joe Strout wrote: > On Dec 9, 2008, at 4:31 AM, Brian Allen Vanderburg II wrote: > > > There is one situation where a module can be imported/executed > > twice, if it is the __main__ module. > Anyway, thanks for pointing this out; I bet it's the root cause of the > OP's observation. Wow, good diagnosis! This was happening in a test framework (using unittest). I had a class which had a @staticmethod factory function, and a class member dict where __init__() registered every instance of the class that got created. Something was going wrong, so in my test code (i.e. in __main__), I imported the module directly and printed the dict. Lo and behold, it was empty! As far as I could tell, class Foo: _map = {} was getting executed again, which made no sense. I even went as far as printing out id(Foo) in both places to make sure I really had the same class (I did). Thanks for the help. I never would have figured this out on my own. From gagsl-py2 at yahoo.com.ar Mon Dec 8 02:48:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Dec 2008 05:48:53 -0200 Subject: getting error...... Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in open_workbook biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) File "C:\Python25\Lib\site-pack References: Message-ID: En Fri, 05 Dec 2008 02:31:01 -0200, pk sahoo escribi?: > hallo everybody, > when i am running the following command > >>>> import xlrd >>>> book=xlrd.open_workbook("C:\\a.xls") > > i am getting the following error.. > > > *Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in > open_workb > ook > biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) > File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 1323, in > getbof > raise XLRDError('Expected BOF record; found 0x%04x' % opcode) > xlrd.biffh.XLRDError: Expected BOF record; found 0x3f3c* Looks like your a.xls file is not an Excel file (one of the formats supported by xlrd). As 0x3f3c corresponds to the characters ' Message-ID: <20081230205725.20272.1180724368.divmod.quotient.29340@ohm> On Tue, 30 Dec 2008 15:55:51 -0500, Jean-Paul Calderone wrote: >On Tue, 30 Dec 2008 14:41:17 -0600, Grant Edwards wrote: >>On 2008-12-30, Francesco Bochicchio wrote: >>>3. AFAIK (sorry, I feel acronym-ly today ;), there is no difference in >>>select between blocking and non-blocking mode. The difference is in the >>>recv (again, assuming that you use TCP as protocol, that is AF_INET, >>>SOCK_STREAM), which in the blocking case would wait to receive all the >>>bytes that you requested, >> >>No, in blocking mode it will wait to receive _some_ data (1 or >>more bytes). The "requested" amount is strictly an upper >>limit: recv won't return more than the requested number of >>bytes, but it might return less. > >Hi Grant, > >I don't think you read Francesco's message carefully enough. :) Ah, no, it was I who didn't read carefully enough. Nevermind. Jean-Paul From ken.faulkner at gmail.com Mon Dec 1 17:38:16 2008 From: ken.faulkner at gmail.com (Ken Faulkner) Date: Tue, 2 Dec 2008 09:38:16 +1100 Subject: pydoc enforcement. In-Reply-To: <1228147384.32081.5.camel@aalcdl07.lib.unc.edu> References: <6ccec696-a8bb-4818-a016-642514677b70@b38g2000prf.googlegroups.com> <1228147384.32081.5.camel@aalcdl07.lib.unc.edu> Message-ID: <8542922d0812011438g529b8806l29e185896274609e@mail.gmail.com> Hi Yeah, I was thinking about something at commit time for a VCS... catch is, soo many VCS's out there. And I wasn't thinking of the default action throwing compile errors, but would only do that if a particular flag was given. Still, just an idea. I'm just finding more and more public modules/API's/libraries that have so little documentation that it really does force reading a LOT of the source to figure out whats going on. Sure, a lot of the time thats required, but some modules are just painful.. oh well... was just a thought. Ken On Tue, Dec 2, 2008 at 3:03 AM, J. Cliff Dyer wrote: > > On Sun, 2008-11-30 at 16:27 -0800, ken.faulkner at gmail.com wrote: > > I've been thinking about implementing (although no idea yet *HOW*) the > > following features/extension for the python compile stage and would be > > interested in any thoughts/comments/flames etc. > > > > Basically I'm interested adding a check to see if: > > 1) pydoc's are written for every function/method. > > 2) There are entries for each parameter, defined by some > > predetermined syntax. > > > > My idea is that as much as I love dynamic typing, there are times when > > using some modules/API's that have less than stellar documentation. I > > was thinking that if it was possible to enable some switch that > > basically forced compilation to fail if certain documentation criteria > > weren't met. > > > > Yes, it should be up to developers to provide documentation in the > > first place. Or, the client developer might need to read the source > > (IF its available)... but having some "forced" documentation might at > > least ease the problem a little. > > > > For example (half borrowing from Javadoc). > > > > class Foo( object ): > > > > def bar( self, ui ): > > pass > > > > > > Would fail, since the bar method has an "unknown" parameter called > > "ui". > > What I think could be interesting is that the compiler forces some > > documentation such as: > > > > class Foo( object ): > > > > def bar( self, ui ): > > """ > > @Param: ui : blah blah blah. > > """ > > pass > > > > > > The compiler could check for @Param matching each parameter passed to > > the method/function. Sure, a lot of people might just not put a > > description in, so we'd be no better off. But at least its getting > > them *that* far, maybe it would encourage them to actually fill in > > details. > > > > Now ofcourse, in statically typed language, they might have the > > description as "Instance of UIClass" or something like that. For > > Python, maybe just a description of "Instance of abstract class UI" or > > "List of Dictionaries"... or whatever. Sure, precise class names > > mightn't be mentioned (since we mightn't know what is being used > > then), but having *some* description would certainly be helpful (I > > feel). > > > > Even if no-one else is interested in this feature, I think it could > > help my own development (and would be an interested "first change" > > into Python itself). > > > > Apart from bagging the idea, does anyone have a suggestion on where in > > the Python source I would start for implementing such an idea? > > > > Thanks > > > > Ken > > For the reasons already stated, I think it's probably a bad idea to > enforce this at compile time. I think it's a great idea to make sure > that this information is present in all your code, but unless you want > to see useless stubs, the correct time to enforce this is at commit > time. Don't accept any improperly documented patches. > > Syntax is not enough to ensure what you want to ensure. The semantics > have to be right as well. > > Cheers, > Cliff > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ken at seehart.com Mon Dec 15 03:38:57 2008 From: ken at seehart.com (Ken Seehart) Date: Mon, 15 Dec 2008 00:38:57 -0800 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: <494617A1.2000103@seehart.com> -*?* Admittedly a tough call. I see the attraction of the proposed syntax. Maybe somewhat more readable since the declaration syntax matches the usage syntax, which is nice. I think it would have been superior to the current syntax if it had been done that way in the first place. However, since newbies will still have to learn both syntaxes in order to read other peoples code, it does not simplify the language. The main thing I don't like about it is that it violates this principle: "There should be one-- and preferably only one --obvious way to do it." Ken Daniel Fetchinson wrote: > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html > > The proposal is to allow this: > > class C: > def self.method( arg ): > self.value = arg > return self.value > > instead of this: > > class C: > def method( self, arg ): > self.value = arg > return self.value > > I.e. explicit self stays only the syntax is slightly different and may > seem attractive to some. As pointed out by Guido classmethods would > work similarly: > > class C: > @classmethod > def cls.method( arg ): > cls.val = arg > return cls.val > > The fact that Guido says, > > "Now, I'm not saying that I like this better than the status quo. But > I like it a lot better than [...] but it has the great advantage that > it is backward compatible, and can be evolved into a PEP with a > reference implementation without too much effort." > > shows that the proposal is viable. > > I'd like this new way of defining methods, what do you guys think? > Anyone ready for writing a PEP? > > Cheers, > Daniel > > From MrJean1 at gmail.com Thu Dec 4 17:31:48 2008 From: MrJean1 at gmail.com (MrJean1) Date: Thu, 4 Dec 2008 14:31:48 -0800 (PST) Subject: simplest way to strip a comment from the end of a line? References: Message-ID: <641d1179-e9f4-4963-9b00-52467551a205@p2g2000prf.googlegroups.com> Using rsplit('#', 1) works for lines *with* comments: >>> 'this is a test'.rsplit('#', 1) ['this is a test'] >>> 'this is a test #with a comment'.rsplit('#', 1) ['this is a test ', 'with a comment'] >>> "this is a '#gnarlier' test #with a comment".rsplit('#', 1) ["this is a '#gnarlier' test ", 'with a comment'] But not if # occurs in lines without comments: >>> "this is a '#gnarlier' test".rsplit('#', 1) ["this is a '", "gnarlier' test"] /Jean Brouwers On Dec 4, 7:50?am, Joe Strout wrote: > I have lines in a config file which can end with a comment (delimited ? > by # as in Python), but which may also contain string literals ? > (delimited by double quotes). ?A comment delimiter within a string ? > literal doesn't count. ?Is there any easy way to strip off such a ? > comment, or do I need to use a loop to find each # and then count the ? > quotation marks to its left? > > Thanks, > - Joe From steve at REMOVE-THIS-cybersource.com.au Sun Dec 14 02:41:55 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Dec 2008 07:41:55 GMT Subject: Optimizing methods away or not? Message-ID: <0154b041$0$6988$c3e8da3@news.astraweb.com> I have a class with a method meant to verify internal program logic (not data supplied by the caller). Because it is time-consuming but optional, I treat it as a complex assertion statement, and optimize it away if __debug__ is false: class Parrot: def __init__(self, *args): print "Initialising instance..." if __debug__: self.verify() # check internal program state, not args if __debug__: def verify(self): print "Verifying..." If I run Python normally, I can do this: >>> p = Parrot() Initialising instance... Verifying... >>> p.verify() Verifying... and if I run Python with the -O flag, I get this: >>> p = Parrot() Initialising instance... >>> p.verify() Traceback (most recent call last): File "", line 1, in AttributeError: Parrot instance has no attribute 'verify' This is the behaviour I want, but I haven't seen it before in other code. What do people think? Is it a good idea or a bad? If you think it is a bad idea to have verify disappear under optimization, would you change your mind if it were called __verify instead? One possible alternative is to do something like this: class Parrot: def __init__(self, *args): print "Initialising instance..." if __debug__: self.verify() def verify(self): if __debug__: print "Verifying..." return None # this is optional else: warnings.warn("verify() is a null op") which now means that Parrot instances will always have a verify method, even if it does nothing. I'm not sure I like that. What do others think? Which do you consider better design? -- Steven From Ron.Barak at lsi.com Mon Dec 22 04:47:02 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Mon, 22 Dec 2008 09:47:02 +0000 Subject: Basic misunderstanding of generators Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6024944BB@enbmail01.lsi.com> Hi All, I want to use generators to print lines taken from a gzipped file. I've never used generators, so probably my problem is basic misunderstanding of generators. In the below program, I expected the last line ("print line_") to print the first line of the sac.log.gz file. Instead, I get: Could you tell me what I'm doing wrong (or point me to a URL that could set me straight) ? Thanks, Ron. $ cat LogManager_try.py #!/usr/bin/env python import gzip import os class LogStream(): """ """ def __init__(self, filename): self.filename = filename self.input_file = self.open_file(filename) def open_file(self, in_file): """ The gzip module checks if the input file is a gzipped file, only at the read stage. This is why the f.readline() is needed. """ try: f = gzip.GzipFile(in_file, "r") f.readline() except IOError: f = open(in_file, "r") f.readline() f.seek(0) return(f) def next_line(self, in_file): """ """ for line_ in in_file: yield line_.strip() if __name__ == "__main__": filename = "sac.log.gz" log_stream = LogStream(filename) line_ = log_stream.next_line(log_stream.input_file) print line_ $ python LogManager_try.py $ -- Ron Barak, System Development Engineer LSI Technologies Israel Ltd 63 Bar Yehuda Road, Nesher 36651 Israel Tel: (+972) 4 8203454 x1542 Fax: (+972) 4 8203464 [cid:263372909 at 22122008-2BEE][cid:263372909 at 22122008-2BF5] Remember, Ginger Rogers did everything Fred Astaire did, but backwards and in high heels. (Faith Whittlesey) -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image001.jpg Type: image/jpeg Size: 1512 bytes Desc: image001.jpg URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image003.jpg Type: image/jpeg Size: 1650 bytes Desc: image003.jpg URL: From pavlovevidence at gmail.com Sat Dec 6 16:15:19 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 6 Dec 2008 13:15:19 -0800 (PST) Subject: Guido's new method definition idea References: <014a071a$0$20670$c3e8da3@news.astraweb.com> Message-ID: <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> On Dec 6, 12:47?am, "Patrick Mullen" wrote: > Could I do something like this: > > def a.add(b): return a+b > > Outside of a class? ?Of course then that makes you think you could do > 5.add(6) or something craaaazy like that. ?(I mean, you can do > (5).__add__(6) but that's something else entirely) I'd be inclined to think that this defines an instancemethod on an existing object a. In other word, I'd read the following two lines as more or less equivalent. def a.add(b): return a+b a.add = lambda b: a+b Just as the following are equivalent: def foo(): return bar foo = lambda: bar I had been -0 on this, but now I think I'm -1. Carl Banks From jay.amorin at gmail.com Wed Dec 3 13:49:21 2008 From: jay.amorin at gmail.com (Jay Jesus Amorin) Date: Thu, 4 Dec 2008 02:49:21 +0800 Subject: python to parse excel file csv format In-Reply-To: References: Message-ID: This is how i do it, but it runs with error. Kindly help #!/usr/bin/env python import csv, sys, os filename = (sys.argv[1]) reader = csv.reader(open(filename, "rb"), delimiter=',', quoting=csv.QUOTE_NONE) try: for row in reader: os.popen("chown row[0] row[1]") except csv.Error, e: sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) ================================================================== testserver:~> ./promote2prod.py test.xls Traceback (most recent call last): File "./promote2prod.py", line 12, in ? sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) AttributeError: '_csv.reader' object has no attribute 'line_num' On Thu, Dec 4, 2008 at 2:25 AM, Jay Jesus Amorin wrote: > Hi all, > > Can anyone please help me. i need to parse the content of my csv excel file > and run the unix command chown. > > test.csv: > > "/dev/trunk/admin/sql/ADBPOS_CMSI_NATIONALITY.syn",814 > "/dev/trunk/bin/ADBPOSCMSDICED.ctl",405 > "/dev/trunk/discoverer/ADBPOS_BUSINESS_AREA.eex",215 > > > Please help me parse the csv file and run chown $csvfile_secondcolumn > $csvfile_firstcolumn. > > Here's how i want to run it. > > ./parsecsv.py test.csv > > > Many thanks. > > > Jay > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ibpet11 at gmail.com Tue Dec 30 05:12:41 2008 From: ibpet11 at gmail.com (ibpet11 at gmail.com) Date: Tue, 30 Dec 2008 02:12:41 -0800 (PST) Subject: string in files Message-ID: <9cda24d9-7a88-45db-b23c-fb43b7d567d4@r37g2000prr.googlegroups.com> guys i need info on how to call up different words in a line of a file using python example : file = 'this is a python coding group' i want to assign a xter to this, is, a, python , coding and group thanks From greg at cosc.canterbury.ac.nz Thu Dec 11 18:49:32 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 12 Dec 2008 12:49:32 +1300 Subject: newbie question: if var1 == var2: In-Reply-To: <87skouzbi5.fsf@daycos.com> References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> <87skouzbi5.fsf@daycos.com> Message-ID: <6qdn3fFc5ggdU2@mid.individual.net> Kirk Strauser wrote: > At 2008-12-11T19:49:23Z, Steve Holden writes: > >> item = item[:-1] > > It's easy - and broken. Bad things happen if you're using something other > than '\n' for EOL. Or if the last line of your file doesn't end with a newline. -- Greg From pyn00b at gmail.com Fri Dec 5 12:46:50 2008 From: pyn00b at gmail.com (n00b) Date: Fri, 5 Dec 2008 09:46:50 -0800 (PST) Subject: etree, minidom unicode Message-ID: <4c78e2e0-3de5-4f18-82f1-0d73ea66eb39@y1g2000pra.googlegroups.com> hi, i have a feew questions concnering unicode and utf-8 handling and would appreciate any insights. 1) i got a xml document, utf-8, encoded and been trying to use etree to parse and then commit to mysql db. using etree, everything i've been extracting is return as a string except ascii char > 127, which come back as a unicode. using minidom on the same document, however, i get all unicode. is there a way to 'force' etree to use unicode? 2) i'm using mysql 5.x on * nix (mac, linux) and after much messing around, have things working, i.e. i have unicode from the (minidom) parser, set all mysql and mysqldb attributes, i get back from mysql. is that expected behavior? #!/usr/bin/env python # -*- coding: UTF-8 -*- from xml.dom import minidom import MySQLdb import codecs from onix_model_01 import * db = MySQLdb.connect(host='localhost', user='root', passwd='', db='lsi', charset='utf8') cur = db.cursor() #cur.execute('SET NAMES utf8') #cur.execute('SET CHARACTER SET utf8') cur.execute('SET character_set_connection=utf8') cur.execute('SET character_set_server=utf8') cur.execute('''SHOW VARIABLES LIKE 'char%'; ''') ... >>> print 'firstname, lastname types from xml: ', type(a.firstname), type(a.lastname) >>>firstname, lastname types from xml: ... >>>cur.execute('''INSERT INTO encoding_test VALUES(null, %s, %s)''', (a.firstname, a.lastname)) ... now i'm getting the results back from mysql >>>cur.execute('SELECT * FROM encoding_test') >>>query = cur.fetchall() >>>for q in query: ....print q, type(q[0]), type(q[1]), type(q[2]) ....print q[1], q[2] ....print repr(q[1]), repr(q[2]) >>>(24L, 'Bront\xc3\xab', 'Charlotte ') >>> Bront? Charlotte >>>'Bront\xc3\xab' 'Charlotte ' so everything is coming back as it should, but i though i would get the sql results back as unicode not str ... what gives? finally, from a utf-8 perspective, is there any advantage using innodb over myisam? thx From imageguy1206 at gmail.com Thu Dec 18 08:56:34 2008 From: imageguy1206 at gmail.com (imageguy) Date: Thu, 18 Dec 2008 05:56:34 -0800 (PST) Subject: something else instead of PIL? References: Message-ID: <6df075c4-2397-4c41-9c75-64c59e7c0dd3@x16g2000prn.googlegroups.com> On Dec 17, 3:48?pm, Reimar Bauer wrote: > Hi > > what has happened to PIL? No updates since two years. > > Or does one know an alternative lib for resizing images? > > cheers > Reimar I have found the FreeImage library with the Python bindings quite workable. I work with multi-page TIF images and this seemed to be the best option. The FreeImage library seems to be actively maintained too (Last release in July 08 with updates to many of the image processing plug- ins). The python bindings took me a bit to understand as they try to emulate PIL, however they are implemented using ctypes, so you can change/manage yourself if needed. I found working directly with the functions exported from the .dll the best option and gave the best performance. Freeimage site: http://freeimage.sourceforge.net/ Python bindings: http://freeimagepy.sourceforge.net/ Hope that helps. Good luck. Working with images/graphics can make my brain hurt sometimes. g. From gandalf at shopzeus.com Thu Dec 18 16:28:23 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 18 Dec 2008 22:28:23 +0100 Subject: psycopg2 and large queries In-Reply-To: <762eed9d-4646-4c62-a9b7-d57d47f03b9e@e1g2000pra.googlegroups.com> References: <762eed9d-4646-4c62-a9b7-d57d47f03b9e@e1g2000pra.googlegroups.com> Message-ID: <494AC077.2060605@shopzeus.com> > Well, there are plenty of PostgreSQL modules around these days, and > even if pyPgSQL isn't suitable, I'm sure that there must be one which > can be made to work on Windows and to support server-side cursors. See > here for more: > > http://wiki.python.org/moin/PostgreSQL > I'm just looking for something that can replace psycopg2, because of the bug mentioned in my original post. Here are my options: - psycopg1: development stalled - psycopg2: memory bug and/or not db api compilant (see my original post) - pyPgSQL: looks like that the last release was in mid 2006 (and it depends on mxDateTime -> licensing problems) - mxODBC: commercial - PyGresSQL: apparently, it does not support fetching one row, only fetching all rows (see: http://www.pygresql.org/pg.html#getresult-get-query-values-as-list-of-tuples), so this is not an option. (Yes, it also has a db api compilant module, but it is only a wrapper around pgqueryobject, and it does not support server side cursors...) So there are many options, but do we have one that: 1. supports server side cursors (fetch some rows after opening the query, but not all of them) 2. open source, with no licensing problems 3. actively maintained Thanks, Laszlo From google at mrabarnett.plus.com Sat Dec 6 13:10:01 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 06 Dec 2008 18:10:01 +0000 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: <493ABFF9.9060702@mrabarnett.plus.com> Neal Becker wrote: > Daniel Fetchinson wrote: > >> Hi folks, >> >> The story of the explicit self in method definitions has been >> discussed to death and we all know it will stay. However, Guido >> himself acknowledged that an alternative syntax makes perfect sense >> and having both (old and new) in a future version of python is a >> possibility since it maintains backward compatibility. The alternative >> syntax will be syntactic sugar for the old one. This blog post of his >> is what I'm talking about: >> >> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html >> >> The proposal is to allow this: >> >> class C: >> def self.method( arg ): >> self.value = arg >> return self.value >> >> instead of this: >> >> class C: >> def method( self, arg ): >> self.value = arg >> return self.value >> >> I.e. explicit self stays only the syntax is slightly different and may >> seem attractive to some. As pointed out by Guido classmethods would >> work similarly: >> >> class C: >> @classmethod >> def cls.method( arg ): >> cls.val = arg >> return cls.val >> >> The fact that Guido says, >> >> "Now, I'm not saying that I like this better than the status quo. But >> I like it a lot better than [...] but it has the great advantage that >> it is backward compatible, and can be evolved into a PEP with a >> reference implementation without too much effort." >> >> shows that the proposal is viable. >> >> I'd like this new way of defining methods, what do you guys think? >> Anyone ready for writing a PEP? >> > What's the advantage? If there is not a good reason, I would strongly opposed polluting the language. > I wouldn't want to see $ for "self." and ? (cent) for "cls." either... From lists at cheimes.de Mon Dec 22 22:19:32 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 23 Dec 2008 04:19:32 +0100 Subject: python3 urlopen(...).read() returns bytes In-Reply-To: References: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> <5496b34d-7ce4-4281-9f01-aed12dab9fd3@f33g2000vbf.googlegroups.com> Message-ID: Glenn G. Chappell schrieb: > Okay, so I guess I didn't really *get* the whole unicode/text/binary > thing. Maybe I still don't, but I think I'm getting closer. Thanks to > everyone who replied. The basic principal is easy. On the one hand you have some text as unicode data, on the other hand you have some binary data that may contain text in an arbitrary encoding. In order to get the text you have to decode the byte data into unicode. The other way around is called encoding. Everybody in the whole world has to deal with unicode *unless* you are living in USA and all you have is plain and simple ASCII text. Python 2.x makes no difference between text in ASCII and arbitrary bytes. Both are stored in the str type. This makes it easy for ASCII country but the rest of the world suffers the consequences. Python 3.0 makes a hard break for ASCII people because with 3.0 really everybody has to deal with encodings. There is no more implicit conversion between ASCII text and unicode. http://www.joelonsoftware.com/articles/Unicode.html explains it in great detail. > > On Dec 22, 1:41 pm, ajaksu wrote: >> On Dec 22, 8:25 pm, Christian Heimes wrote: >> That said, a "decode to declared HTTP header encoding" version of >> urlopen could be useful to give some users the output they want (text >> from network io) or to make it clear why bytes is the safe way. > > Sounds like a great idea. More to the point, it sounds like it's > pretty much a necessary idea. > > Consider: reading a web page is an easy one-liner. Now, no one is > going to write that one-liner, and then spend 20 lines trying to get > the Content-Type and encoding figured out. Instead we're all going to > do it the short, easy, *wrong* way. So every program in the world that > uses urlopen gets to have the same bug. Not good. The *right* way > needs to be the *easy* way. Python 2.x suffers from the same problem. It just doesn't tell you from the beginning that you need to deal with the problem. With 2.x you can read websites fine - until you have to deal with a non English, non ASCII text. 3.0 forces the developer to think about the issue right from the beginning. No more excuses :) I suggest somebody makes a feature request for 3.1. A patch with unit test increases the changes for the patch by at least one magnitude. Christian From steve at holdenweb.com Fri Dec 19 23:02:10 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 19 Dec 2008 23:02:10 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <015c47ad$0$20656$c3e8da3@news.astraweb.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c47ad$0$20656$c3e8da3@news.astraweb.com> Message-ID: <494C6E42.8080008@holdenweb.com> Steven D'Aprano wrote: > On Fri, 19 Dec 2008 10:25:30 -0700, Michael Torrie wrote: > >> So funny that now that Python 3.0 is actually released we have people >> acting all surprised like they've never seen any of the new features in >> Python 3.0 coming. However these features have been discussed for >> years! And debated! > > Debated by who? The entire Python-using community? Every single Python > programmer? Or just the small proportion of Python developers who are > also core developers? > > Are you *really* surprised that some people had never heard of the > changes being debated until it was too late? > It isn't the least surprising that some people have been taken by surprise by the changes. Neither is it surprising that some of them don't like the changes that much. However, at least in the open source world one has the *opportunity* to make one's voice heard and one's opinion known, even thought he majority prefer to remain consumers of the output of open source projects. Where commercial projects are concerned the major influence one has is a post-facto vote with one's wallet. I hope, however, that those who don't like the changes but didn't bother to track developments don't feel in any way disenfranchised. They are still welcome to make their input, and of course there is nothing to stop them keeping Python 2.X alive for as long as they wish. [misconception about print's role] >> Furthermore, the new {} >> notation allows many, many more options for formatting to be used. Want >> to display a floating point number with $#.## notation, and ($#.##) for >> negative? It's all now possible. Couldn't be done before. > > Of course it could be. You just needed to write your own formatting > engine. What you mean is that it couldn't be done with % formatting and > nothing else. > > >> In short, this is a huge improvement, and backwards compatibility is >> preserved for the 2.x style for those that wish it. > > > There clearly is a need for a more heavyweight formatting solution than % > and string.Template. There are things that can't be done easily with % > alone, and format() will make them much simpler. I have no objection to > the addition of the format() method (although I wonder whether it might > have been better as a function). > That's doubtless a debate that will play for a long time, with no really clear advantage either way. Programmers just like to debate these things. Of course it's a trivial addition: def format(s, *args, **kw): return s.format(*args, **kw) [I put **kw in becuase it's easier than checking the docs to se whether keyword arguments are specified]. This doesn't mean there won't be fifteen more posts on this thread about it. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From grante at visi.com Sat Dec 13 20:51:23 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 13 Dec 2008 19:51:23 -0600 Subject: subprocess to C program References: <0ebd59c5-95a1-42d4-b597-d1c248490b8e@y1g2000pra.googlegroups.com> Message-ID: <8MidneyhDfIG-9nUnZ2dnUVZ_uadnZ2d@posted.visi> On 2008-12-14, MRAB wrote: >> I am writing a C process and I want to read data from a file that I >> write to in Python. I'm creating a pipe in Python, passing it to the >> C process, and calling '_read'. It gives me error 9, bad file number. >> >> Python code: >> >> import subprocess as s, os >> r, w= os.pipe( ) >> os.write( w, 'abcdefghij\n' ) >> a= s.Popen( [ r'C:\Documents and Settings\usr\Desktop\working >> \try_start', '%i'%r, '%i'%w ] ) >> >> C code: >> >> char buf[ 16 ]; >> memset( buf, 0, 16 ); >> int readfd= atoi( argv[ 1 ] ); >> int ct= _read( readfd, buf, 15 ); >> printf( "\n\n'_read %i %i %i': %s\n", ct, readfd, errno, buf ); >> >> Output: >> >> '_read -1 3 9' >> >> meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9. I want 'ct' >> to be 11 at this point. Thanks in advance. >> > It looks like the ids aren't system global. They certainly aren't in Unix: Their a property of the process. -- Grant From n.kottiyath at gmail.com Mon Dec 29 22:46:50 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Mon, 29 Dec 2008 19:46:50 -0800 (PST) Subject: Python module import loop issue References: <02bc8567-695a-4277-9698-a95549a0bc98@w39g2000prb.googlegroups.com> <4a0557b7-e901-49ff-b4db-53f4d8a7c0f8@r40g2000yqj.googlegroups.com> Message-ID: <54ed8839-7d47-4690-b1c0-7930aa517955@q30g2000prq.googlegroups.com> On Dec 30, 8:24?am, "Gabriel Genellina" wrote: > En Mon, 29 Dec 2008 19:47:51 -0200, Carl Banks ? > escribi?: > > > On Dec 29, 10:51?am, Kottiyath wrote: > >> Module Factory: > >> A1Factory: {'B1Tag':1.1.B1, 'C1Tag':1.2.C1, 'D1Tag':1.3.D1'} > >> A2Factory: {'B2Tag':2.1.B2, 'C2Tag':2.2.C2, 'D2Tag':2.3.D2'} > > >> But, since Module requires objects of B1, C1 etc, it has to import > >> Factory. > >> Now, there is a import loop. How can we avoid this loop? > > > I'm going to suggest three ways: a straightforward, good-enough way; a > > powerful, intelligent, badass way; and a sneaky way. > > In Python 2.6 (and 3.0) there is a fourth way: class decorators. > > > 1. The straightforward, good-enough way > > > Define functions in Factory.py called register_A1_subclass and > > register_A2_subclass, then call them whenever you create a new > > subclass. > > Class decorators are a clean variant of this approach (in my opinion). > > > package1/module1.py: > > ----------------------------- > > import Factory > > > class B1(A1): > > ? ? # define class B1 here > > > Factory.register_A1_subclass("B1Tag",B1) > > ----------------------------- > > That would become: > > @Factory.register_A1_subclass("B1Tag") > class B1(A1): > ? ?... > > (for an adequate variant of register_A1_subclass). The advantage is that ? > the "register" stuff appears prominently near the name of the class, and ? > there is no need to repeat the name. > Also, "B1Tag" can be left out, if it is stored as a class attribute of B1 ? > (in some cases using __name__ is enough) > > > 2. The powerful, intelligent, badass way > > > Metaclasses. ?I would guess you do not want to do this, and I wouldn't > > recommend it if you haven't studied up on how metaclasses work, but > > it's a textbook example of their usefulness. ?If you expect to use > > factory functions like this a lot, it might be worth your while to > > learn them. > > A problem with metaclasses is when you have intermediate subclasses that ? > are not meant to be registered, but the metaclass applies equally to all ? > of them. > > -- > Gabriel Genellina Hi Gabriel, Carl, Thank you very much for your help. I never knew about metaclassess and class decorators. Thank you again. I am actually inclined towards the straightforward way (1). But still one of the issues that I have mentioned in the first mail remains. How do I actually hit the code because my entry point is the EN module. Importing every module in EN module so that it hits the code atleast once is fraught with danger because later, someone might delete it to clean it up and will start facing issues. Could you give me some pointers in such a case? Regards K From sturlamolden at yahoo.no Sat Dec 13 15:35:41 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 13 Dec 2008 12:35:41 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> On 10 Des, 19:42, cm_gui wrote: > And it is not just this Python site that is slow. There are many many > Python sites which are very slow. And please don?t say that it could > be the web hosting or the server which is slow ? because when so many > Python sites are slower than PHP sites, it couldn?t be the web > hosting. ? Also, Zope/Plone is even slower. > > Python is slow. Very slow. By the way... I know of a very slow Python site called YouTube.com. In fact, it is so slow that nobody ever uses it. From stef.mientki at gmail.com Sat Dec 27 06:16:14 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 27 Dec 2008 12:16:14 +0100 Subject: Is there a function to remove escape characters from a string ? In-Reply-To: <01659326$0$6988$c3e8da3@news.astraweb.com> References: <0163882f$0$6988$c3e8da3@news.astraweb.com> <5a29b62a-c38f-409b-8887-6259ad072bf5@w1g2000prk.googlegroups.com> <01659326$0$6988$c3e8da3@news.astraweb.com> Message-ID: <49560E7E.1050307@gmail.com> Steven D'Aprano wrote: > On Sat, 27 Dec 2008 01:41:40 +0100, Stef Mientki wrote: > > >> Sorry if I offended someone, that was certainly not my intention. And I >> guess you will be surprised, if I tell you, I don't (want) to understand >> any bit of the above code ;-) Come on, the home computer was invented >> about 1980. If we look at hardware, it follows the Moore's law, for >> software I would expect at least 0.1 of Moore's law ;-) I hope that >> clarifies my point. >> > > No, that only makes it even more confusing. What does Moore's Law have to > do with your willful ignorance about the existence of human languages > other than English? > > Nothing. I even don't (want to) see what bits / bytes / escape sequences have to do with modern programming techniques, so I certainly don't see any relation between these and human languages. But the lack of Moore's law in software explains why we still need to concern about bits and bytes ;-) cheers, Stef From garlictrompet at gmail.com Mon Dec 15 07:21:20 2008 From: garlictrompet at gmail.com (Analog Kid) Date: Mon, 15 Dec 2008 17:51:20 +0530 Subject: regex problem .. Message-ID: <3b10c2060812150421y1c3e7da6ha1b72c736e2a20d4@mail.gmail.com> Hi All: I am new to regular expressions in general, and not just re in python. So, apologies if you find my question stupid :) I need some help with forming a regex. Here is my scenario ... I have strings coming in from a list, each of which I want to check against a regular expression and see whether or not it "qualifies". By that I mean I have a certain set of characters that are permissible and if the string has characters which are not permissible, I need to flag that string ... here is a snip ... flagged = list() strs = ['HELLO', 'Hi%20There', '123123@#@'] p = re.compile(r"""[^a-zA-Z0-9]""", re.UNICODE) for s in strs: if len(p.findall(s)) > 0: flagged.append(s) print flagged my question is ... if I wanted to allow '%20' but not '%', how would my current regex (r"""[^a-zA-Z0-9]""") be modified? TIA, AK -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Mon Dec 8 05:54:01 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 8 Dec 2008 02:54:01 -0800 (PST) Subject: getting error...... Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in open_workbook biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) File "C:\Python25\Lib\site-pack References: Message-ID: <6c76b050-5b47-46f3-9097-5c58979b6913@s9g2000prg.googlegroups.com> On Dec 8, 6:48?pm, "Gabriel Genellina" wrote: > En Fri, 05 Dec 2008 02:31:01 -0200, pk sahoo ? > escribi?: > > > > > hallo everybody, > > when i am running the following command > > >>>> import xlrd > >>>> book=xlrd.open_workbook("C:\\a.xls") > > > i am getting the following error.. > > > *Traceback (most recent call last): > > ? File "", line 1, in > > ? File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in > > open_workb > > ook > > ? ? biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) > > ? File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 1323, in > > getbof > > ? ? raise XLRDError('Expected BOF record; found 0x%04x' % opcode) > > xlrd.biffh.XLRDError: Expected BOF record; found 0x3f3c* > > Looks like your a.xls file is not an Excel file (one of the formats ? > supported by xlrd). > As 0x3f3c corresponds to the characters ' """ then it's an Excel 2003 XML Spreadsheet that's been manually(?) renamed from .xml to .xls. The current xlrd release supports only the binary ("BIFF") format .xls files created by Excel 3.0 to Excel 2003. The next release (due out Real Soon Now) will support Excel 2.1 and 2.0 formats [don't ask]. Very soon after that will come support for Excel 2007 .xlsx which is a bunch of XML files inside a ZIP file. Support for Excel 2003 "SpreadsheetML" is way down the to-do list. If the OP wants to be able to read the file with xlrd: (1) Open it with Excel 200[37] and save as a .xls file or (2) rename it to .xml, start OpenOffice.org Calc, click on File, click on Open, click on "Files of type", choose "Microsoft Excel 2003 XML (*.xml)" from the (long, unsorted) drop-down list, ..., and save as etc etc. Gnumeric is not an option. HTH, John From fetchinson at googlemail.com Sat Dec 27 18:50:34 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 27 Dec 2008 15:50:34 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: >> I have considered using ctypes but for my needs using the C API >> directly seems more reasonable. array.array and numpy.array doesn't >> fit my needs since I need to do long and complicated operations on the >> two (pretty large) integer arrays that would be too slow using >> array.array and numpy.array (I've verified this claim by benchmarking >> a numpy.array based solution). > > OK, but if you go to array.array or numpy.array or ctypes, you can > create a uniformly typed (C datatype) array , which is the key to > getting any speed out of the deal. If you insist on using python > lists, you are stuck with extracting data element by element from > its Python language wrap. I thought that going through the python C API will be more cross-platform than using ctypes, but I might be wrong. Anyway, the C API for such a simple thing as a single function doesn't seem too scary :) I agree that array.array is more efficient than a list but the input for my function will come from PIL and PIL returns a list. So I have a list to begin with which will be passed to the C function. I assume converting the list to an array.array and passing that to the C function doesn't make any difference in terms of speed since the operation itself will be done in the C function anyway. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From martin at v.loewis.de Tue Dec 2 14:56:30 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Tue, 02 Dec 2008 20:56:30 +0100 Subject: Multiple Versions of Python on Windows XP In-Reply-To: References: <4934de22$0$27863$9b622d9e@news.freenet.de> Message-ID: <493592EE.9090005@v.loewis.de> >>> What changes are made to the registry? >> >> For a complete list, see Tools/msi/msi.py in the source tree. > > I have scanned the file: > http://svn.python.org/projects/python/branches/py3k/Tools/msi/msi.py > > I don't find anything that addresses this issue. Read the add_registry function. You may need to first understand how the Registry table in an MSI file works. > I am seeking some mechanism such that any of Python 2.5, Python 2.6 or > Python 2.6 can be chosen as the currently active version. If Glenn Lindermann's answer doesn't help, you need to explain: what is a "currently active version"? How is one Python version more active than any other? > I was hoping that there is some simpler way than the "Repair" procedure. See Glenn Lindermann's answer. >> It would be good to be more specific with such statements: what troubles >> specifically? If I play dumb, I'd say "of course - windows explorer >> doesn't support editing Python files; you need a text editor". > > Yes, I should have been clearer. The PyScripter application locks up > and must be killed, using the Task Manager. I think you need to report that to the PyScripter authors as a bug. I can't imagine how the "currently active version" can affect what PyScripter does. Regards, Martin From michaeldg at gmail.com Thu Dec 4 01:52:19 2008 From: michaeldg at gmail.com (Michael_D_G) Date: Wed, 3 Dec 2008 22:52:19 -0800 (PST) Subject: Python advocacy ... HELP! Message-ID: <5f8c1a52-545e-402e-863a-acdf23d04c78@h20g2000yqn.googlegroups.com> I am a faculty member of a cs department. We currently teach C++ in our intro to programming course. I am teaching this class and it seems to me that we would be much better served teaching python in the intro course, C++ for Data structures, as we do now, and Java in object oriented programming, as we do now. Some of my colleagues agree with me but some still see python as a niche language and don't understand how we could teach anything beyond C, C++ or Java. I have looked at several interesting academic papers, on doing just this approach. I have also looked through the python web page to get examples of industry players using python in a non-trivial way. Yes, I know, Google, Microsoft, Sun, CIA website running on Plone, NOAA, NASA. If anyone has any recent articles, or if anyone on the list is at a fortune 500 company, how do I refute the notion that Python is a "marginal" language because according to TOBIE it only less than a 6% market share. -michael From arnodel at googlemail.com Wed Dec 10 17:19:17 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 10 Dec 2008 22:19:17 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: "Dotan Cohen" writes: > 2008/12/10 : >> On Dec 5, 9:51 am, Xah Lee wrote: >>> >>> For those of you who don't know linear algebra but knows coding, this >>> means, we want a function whose input is a list of 3 elements say >>> {x,y,z}, and output is also a list of 3 elements, say {a,b,c}, with >>> the condition that >>> >>> a = x/Sqrt[x^2+y^2+z^2] >>> b = y/Sqrt[x^2+y^2+z^2] >>> c = z/Sqrt[x^2+y^2+z^2] >> >>> >>> In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, >>> you'll have 50 or hundreds lines. >> >> Ruby: >> >> def norm a >> s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) >> a.map{|x| x/s} >> end > > If someone doesn't counter with a Python one-liner then I'm going to > port that to brainfuck. def unit(v): return map((sum(map(lambda x:x*x, v))**0.5).__rdiv__, v) The hard bit was to make it less readable than the Ruby version ;) -- Arnaud From rafesacks at gmail.com Mon Dec 1 03:27:08 2008 From: rafesacks at gmail.com (Rafe) Date: Mon, 1 Dec 2008 00:27:08 -0800 (PST) Subject: pydoc enforcement. References: <6ccec696-a8bb-4818-a016-642514677b70@b38g2000prf.googlegroups.com> Message-ID: <599b252d-5e05-4b30-9027-36a73a1875cc@w1g2000prk.googlegroups.com> On Dec 1, 7:27?am, "ken.faulk... at gmail.com" wrote: > I've been thinking about implementing (although no idea yet *HOW*) the > following features/extension for the python compile stage and would be > interested in any thoughts/comments/flames etc. > > Basically I'm interested adding a check to see if: > ? 1) pydoc's are written for every function/method. > ? 2) There are entries for each parameter, defined by some > predetermined syntax. > > My idea is that as much as I love dynamic typing, there are times when > using some modules/API's that have less than stellar documentation. I > was thinking that if it was possible to enable some switch that > basically forced compilation to fail if certain documentation criteria > weren't met. > > Yes, it should be up to developers to provide documentation in the > first place. Or, the client developer might need to read the source > (IF its available)... ?but having some "forced" documentation might at > least ease the problem a little. > > For example (half borrowing from Javadoc). > > class Foo( object ): > > ? def bar( self, ui ): > ? ? ?pass > > Would fail, since the bar method has an "unknown" parameter called > "ui". > What I think could be interesting is that the compiler forces some > documentation such as: > > class Foo( object ): > > ? def bar( self, ui ): > ? ? """ > ? ? @Param: ui : ?blah blah blah. > ? ? """ > ? ? ?pass > > The compiler could check for @Param matching each parameter passed to > the method/function. Sure, a lot of people might just not put a > description in, so we'd be no better off. But at least its getting > them *that* far, maybe it would encourage them to actually fill in > details. > > Now ofcourse, in statically ?typed language, they might have the > description as "Instance of UIClass" or something like that. For > Python, maybe just a description of "Instance of abstract class UI" or > "List of Dictionaries"... ?or whatever. Sure, precise class names > mightn't be mentioned (since we mightn't know what is being used > then), but having *some* description would certainly be helpful (I > feel). > > Even if no-one else is interested in this feature, I think it could > help my own development (and would be an interested "first change" > into Python itself). > > Apart from bagging the idea, does anyone have a suggestion on where in > the Python source I would start for implementing such an idea? > > Thanks > > Ken As long as it uses RST (reStructuredText) it could be interesting. Maybe as a wrapper on epydoc or something? I have been simply generating my docs and reading through them. This is fine for catching areas which are totally missing, but gets very time consuming to maintain small changes. What would be really great, is something which ties in to subversion to display an easy to see and find alert in the docs when the source has been updated. It would then require some manual action to hide the alert (hopefully someone would read the doc again before killing the alert). - Rafe From brian.wallace at hp.com Mon Dec 8 19:48:01 2008 From: brian.wallace at hp.com (Brian Wallace) Date: Mon, 08 Dec 2008 16:48:01 -0800 Subject: python-devel download and install Message-ID: <1228783681.6826.7.camel@bwallace-laptop.americas.hpqcorp.net> Hi Folks, I am developing in Python version 2.5.2 and need to install and download the python-devel library. (This is needed so I can build and install mysql-python.) Where can I find find this module to download and build/installation instructions? I have been unable to find the source online to download. I am not root on the box where I need to install this module so I need the source (rpm/deb packages will not do). Thank you in advance for the guidance! -Brian From stef.mientki at gmail.com Sat Dec 6 18:40:53 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 07 Dec 2008 00:40:53 +0100 Subject: how to get a beep, OS independent ? Message-ID: <493B0D85.3060404@gmail.com> hello, I want to give a small beep, for windows there's message-beep, and there seems to be something like " curses" , but that package seems to be totally broken in P2.5 for windows. Any other suggestions ? thanks, Stef Mientki From simon at brunningonline.net Mon Dec 22 04:56:59 2008 From: simon at brunningonline.net (Simon Brunning) Date: Mon, 22 Dec 2008 09:56:59 +0000 Subject: [Help] The pywinauto Can't select the MDI's menu using the MenuItems() which return []. In-Reply-To: <85676.52949.qm@web32801.mail.mud.yahoo.com> References: <85676.52949.qm@web32801.mail.mud.yahoo.com> Message-ID: <8c7f10c60812220156k4a290fa1re469bc8c4a4019ae@mail.gmail.com> 2008/12/21 : > The code below opens the Choose Font dialog on my Spanish Windows version: > > py> from pywinauto.application import Application > py> app = Application.start("Notepad.exe") Notepad's menus are build with MFC. Word's menus are not. Trust me, give it up. For automating Word, COM (with Mark Hammond's excellent Python/COM bridge) is the only way to go. -- Cheers, Simon B. simon at brunningonline.net From maresp1 at hotmail.com Mon Dec 22 04:17:03 2008 From: maresp1 at hotmail.com (maresp1 at hotmail.com) Date: Mon, 22 Dec 2008 01:17:03 -0800 (PST) Subject: =?windows-1252?Q?We_are_looking_for_boys_and_girls_to_have_fun=2C_orgie?= =?windows-1252?Q?s=2C_trios=2C_and_whatever=2E_If_you_want_a_do_it=2C_don=92t_be_shy_?= =?windows-1252?Q?and_contact=2E_That=92s_going_to_be_great=21?= Message-ID: We are looking for boys and girls to have fun, orgies, trios, and whatever. If you want a do it, don?t be shy and contact. That?s going to be great! By the way, we are bisexual and we don?t care about gender? Sign in to enjoy with us: http://xxxgente.chueca.com/sexocontacto/ http://galeon.com/sexocontacto/2451.html From pruebauno at latinmail.com Wed Dec 10 10:06:50 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Wed, 10 Dec 2008 07:06:50 -0800 (PST) Subject: StringIO in 2.6 and beyond References: Message-ID: On Dec 10, 6:58?am, Bill McClain <20080915.20.wmccl... at spamgourmet.com> wrote: > On 2008-12-10, ajaksu wrote: > > > On Dec 9, 5:24?pm, Bill McClain <20080915.20.wmccl... at spamgourmet.com> > > wrote: > > > On 2008-12-09, MRAB wrote: > > > > > In Python 2.x unmarked string literals are bytestrings. In Python 3.x > > > > they're Unicode. The intention is to make the transition from 2.x to 3.x > > > > easier by adding some features of 3.x to 2.x, but without breaking > > > > backwards compatibility (not entirely successfully!). > > > > It is a bit ugly. In 2.6 StringIO won't take bytestrings, so I apply u'x'. But > > > in 3.0 u'x' will be gone and I'll have to change the code again. > > Try: > > from __future__ import unicode_literals > > That works for: > > ? ? output.write('First line.\n') > > ...but not for: > > ? ?print('Second line.', file=output) > > Maybe a combination of this and functools.partial as was suggested before. At > least the necessary edits would be at the top of the program. > > -Bill > -- > Sattre Press ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Tales of Warhttp://sattre-press.com/? ? ? ? ? ? ? ? ? ? ? by Lord Dunsany > i... at sattre-press.com ? ? ? ?http://sattre-press.com/tow.html I think this combination might do the trick (I don't have 2.6 to test it right now): from __future__ import print_function from __future__ import unicode_literals from functools import partial import io print = partial(print, sep=" ", end="\n") out = io.StringIO() print("hello", file=out) What puzzles me is the documentation in 2.6 and 3.0: In 2.6 it says: "The StringIO object can accept either Unicode or 8- bit strings". Why does it fail with old str objects then? Why is there no documentation for StringIO in 3.0? From sturlamolden at yahoo.no Sat Dec 13 15:33:28 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 13 Dec 2008 12:33:28 -0800 (PST) Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> <87iqpoc1l0.fsf@mulj.homelinux.net> <4155583a-1f6d-4fca-8cf1-7fa809e6d448@q30g2000prq.googlegroups.com> Message-ID: <92adeebc-07ae-4261-b92d-22ff9f9195b1@y1g2000pra.googlegroups.com> On 13 Des, 21:26, sturlamolden wrote: > Python methods always have a return value, even those that seem to do > not - they silently return None. Thus, __iadd__ must return self to > avoid rebinding to None. Except for immutable types, for which __iadd__ must return a new instance. From kay.schluehr at gmx.net Sun Dec 21 01:13:49 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 20 Dec 2008 22:13:49 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c47ad$0$20656$c3e8da3@news.astraweb.com> Message-ID: On 20 Dez., 02:54, Steven D'Aprano wrote: > Debated by who? The entire Python-using community? Every single Python > programmer? Or just the small proportion of Python developers who are > also core developers? "If I'd asked people what they wanted, they would have asked for a better horse." Henry Ford From v+python at g.nevcal.com Tue Dec 2 02:19:31 2008 From: v+python at g.nevcal.com (Glenn Linderman) Date: Mon, 01 Dec 2008 23:19:31 -0800 Subject: Multiple Versions of Python on Windows XP In-Reply-To: <4934de22$0$27863$9b622d9e@news.freenet.de> References: <4934de22$0$27863$9b622d9e@news.freenet.de> Message-ID: <4934E183.9020404@g.nevcal.com> On approximately 12/1/2008 11:05 PM, came the following characters from the keyboard of Martin v. L?wis: >> Is there some way to specify a default version in such a way that it can >> be changed as necessary? >> > > What do you mean by "default version"? > > There is the version that is associated with the .py/.pyc extensions > at any point in time; you can change these by re-running the respective > installers from add-and-remove-programs. In a well-managed installation, > only one Python installation would have the "Register Extensions" > feature selected; to then change the default, one would unselect the > feature in one version, and reselect it in a different. If only the > default installation procedure was ever used, re-running the installer > in "Repair" mode (from ARP) will also restore the extension > associations. That seems a lot more cumbersome than just using the command line to change the ftype and assoc a bit. Here's how I set up my computer, for multiple versions. Now to change the "default", I just use the assoc command to change the association for .py to one of the three listed ftypes. Simple and quick. c:\>ftype Python25.File ftype Python25.File Python25.File="C:\Python25\python.exe" "%1" %* c:\>ftype Python26.File ftype Python26.File Python26.File="C:\Python26\python.exe" "%1" %* c:\>ftype Python30.File ftype Python30.File Python30.File="C:\Python30\python.exe" "%1" %* c:\>assoc .py assoc .py .py=Python25.File It would be nice if the ftypes were version specific as created by the installer; IIRC, I created the above three from the ftype Python.File as I installed each version. -- Glenn -- http://nevcal.com/ =========================== A protocol is complete when there is nothing left to remove. -- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking From marco at sferacarta.com Mon Dec 22 12:01:26 2008 From: marco at sferacarta.com (Marco Mariani) Date: Mon, 22 Dec 2008 18:01:26 +0100 Subject: Python's popularity In-Reply-To: References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: Richard Riley wrote: > One does not have to by a language maestro to try and assess its > popularity. While his numbers or his reading of the numbers might be > open to some questions, to suggest that one needs to be totally familiar > with a language to determine its popularity is, frankly, ridiculous. I was not judging his competency. But when I am naive on a subject, I don't usually show off like that. The polemic intents in his previous messages are quite clear (python is slow, py3k is an utter failure because it doesn't solve the whitespace issue, etc), and this thread is not different. It seems like a rehash of issues that have been dragged around here by generations of trolls for the last 10 years. Sorry for adding noise to the signal :-/ From bj_666 at gmx.net Fri Dec 19 18:02:08 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Dec 2008 23:02:08 GMT Subject: encoding problem References: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> <6r1m72Ffb5kpU3@mid.uni-berlin.de> <6r2hvjFfb5kpU6@mid.uni-berlin.de> Message-ID: <6r2nfgFfb5kpU7@mid.uni-berlin.de> On Fri, 19 Dec 2008 15:20:08 -0700, Joe Strout wrote: > Marc 'BlackJack' Rintsch wrote: > >>> And because strings in Python, unlike in (say) REALbasic, do not know >>> their encoding -- they're just a string of bytes. If they were a >>> string of bytes PLUS an encoding, then every string would know what it >>> is, and things like conversion to another encoding, or concatenation >>> of two strings that may differ in encoding, could be handled >>> automatically. >>> >>> I consider this one of the great shortcomings of Python, but it's >>> mostly just a temporary inconvenience -- the world is moving to >>> Unicode, and with Python 3, we won't have to worry about it so much. >> >> I don't see the shortcoming in Python <3.0. If you want real strings >> with characters instead of just a bunch of bytes simply use `unicode` >> objects instead of `str`. > > Fair enough -- that certainly is the best policy. But working with any > other encoding (sometimes necessary when interfacing with any other > software), it's still a bit of a PITA. But it has to be. There is no automagic guessing possible. >> And does REALbasic really use byte strings plus an encoding!? > > You betcha! Works like a dream. IMHO a strange design decision. A lot more hassle compared to an opaque unicode string type which uses some internal encoding that makes operations like getting a character at a given index easy or concatenating without the need to reencode. Ciao, Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Fri Dec 26 19:42:58 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 26 Dec 2008 16:42:58 -0800 (PST) Subject: Right way to set a variable to NULL? References: <5nfal41gom0iqi2nh5h0m5847ev9brtvpf@4ax.com> <098da1d1-640c-4aef-b005-5f0932f291cc@35g2000pry.googlegroups.com> Message-ID: <1836b10a-6186-4f27-9a65-96e539d5b174@w1g2000prm.googlegroups.com> On Dec 27, 11:05?am, Martin wrote: > 2008/12/26 John Machin : > > > The above all have the same characteristic: if the input is a zero- > > length string, then NULL is inserted into the database instead of a > > zero-length string. Some folks (not just pedants!) regard that as an > > important difference. > > agreed but I understood the OP specifically wanted NULL and not ''. He wanted None inserted into the database as NULL if his regex didn't match. He didn't invite you to change a matching '' to NULL with no announcement. From rurpy at yahoo.com Sun Dec 7 23:51:50 2008 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Sun, 7 Dec 2008 20:51:50 -0800 (PST) Subject: tabs and spaces in py3k Message-ID: <774909e2-b248-4251-bbba-deb309e72714@x38g2000yqj.googlegroups.com> The following code works under 2.6 ---- def foo(): a = 1 <.tab..>b = 1 ---- but results in a TabError in Python 3k File "x.py", line 3 b = 3 ^ TabError: inconsistent use of tabs and spaces in indentation The py3k docs say the same thing as the 2.6 docs, namely that tabs are expanded to spaces prior to determining the line's indentation. (Language Ref, Lex Anal, Line Struct, Indentation) (I wish someone would put the section numbers back in the docs.) No mention of this change (that I noticed) in What's New or NEWS.txt. Do the Py3k docs need correction? From malkarouri at gmail.com Fri Dec 5 08:44:22 2008 From: malkarouri at gmail.com (malkarouri) Date: Fri, 5 Dec 2008 05:44:22 -0800 (PST) Subject: RELEASED Python 2.6.1 References: Message-ID: On 5 Dec, 05:07, Barry Warsaw wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hot on the heals of Python 3.0 comes the Python 2.6.1 bug-fix ? > release. Nice work. Thanks. > Source tarballs and Windows installers can be downloaded from the ? > Python 2.6.1 page I note that OS X installers have not been released (yet). I don't know if you plan to, but I think it is important to release installers that do not suffer from the bug http://bugs.python.org/issue4017 which renders Tkinter unusable in the 2.6.0 release and which (I believe) is a build issue. Can we expect such an updated release? Many thanks, Muhammad Alkarouri From enleverlesX.XmcX at XmclaveauX.com Fri Dec 19 15:43:37 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Fri, 19 Dec 2008 21:43:37 +0100 Subject: PIL on 3.x? In-Reply-To: <3892784c-ddf4-4451-bcfd-dbc58b9b55f8@e1g2000pra.googlegroups.com> References: <3892784c-ddf4-4451-bcfd-dbc58b9b55f8@e1g2000pra.googlegroups.com> Message-ID: <494c0ad4$0$4096$ba4acef3@news.orange.fr> Hi! This info is interesting for many people. IMO, it's a good idea to write the question in this newsgroup. @-salutations -- Michel Claveau From acerimusdux at comcast.net Sun Dec 7 18:33:37 2008 From: acerimusdux at comcast.net (acerimusdux) Date: Sun, 07 Dec 2008 18:33:37 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: <493C5D51.6060102@comcast.net> James Stroud wrote: >
Rasmus > Fogh wrote: >> Current behaviour is both inconsistent and counterintuitive, as these >> examples show. >> >>>>> x = float('NaN') >>>>> x == x >> False > > Perhaps this should raise an exception? I think the problem is not > with comparisons in general but with the fact that nan is type float: > > py> type(float('NaN')) > > > No float can be equal to nan, but nan is a float. How can something be > not a number and a float at the same time? The illogicality of nan's > type creates the possibility for the illogical results of comparisons > to nan including comparing nan to itself. > > I initially thought that looked like a bug to me. But, this is apparently standard behavior required for "NaN". I'm only using Wikipedia as a reference here, but about 80% of the way down, under "standard operations": http://en.wikipedia.org/wiki/IEEE_754-1985 "Comparison operations. NaN is treated specially in that NaN=NaN always returns false." Presumably since floating point calculations return "NaN" for some operations, and one "Nan" is usually not equal to another, this is the required behavior. So not a Python issue (though understandably a bit confusing). The array issue seems to be with one 3rd party library, and one can choose to use or not use their library, to ask them to change it, or even to decide to override their == operator, if one doesn't like the way it is designed. From warren at delsci.com Thu Dec 4 04:28:56 2008 From: warren at delsci.com (Warren DeLano) Date: Thu, 4 Dec 2008 01:28:56 -0800 Subject: "as" keyword woes Message-ID: <896B75251BA19745A529B1B867893FA5DB0B@planet.delsci.local> > I don't know how you infer any of those from what I said, nor > from the process of introducing features in Python. None of > what you say there rings at all true with anything I've > experienced in Python's core or the attitudes surrounding > development if the language; indeed, quite the opposite. That has been my experience as well, which is why this particular action seems surprising and out of character. > Speaking of irony, you're complaining about namespace > conflicts with a -two character identifier- you've chosen. > Here's a hint: choose better names. Hey, come on now -- developers working on top of an existing language bear nowhere near the responsibility as the language & implementation maintainers. Also, note that the fields of math and science are filled with short identifiers with well-defined meanings -- brevity doesn't mean ambiguous within a given application domain! But regardless, our scripts use "as" in the same way as Python -- to change the effective appearance of an object, albeit in a representational rather than naming space. So if we're wrong in our choice, then so is Python. In addition, note that my choice of a concise method identifier affects only my users. Python's introduction of a new keyword affects the entire Python world code base, so perhaps you should be directing your "choose better names" criticism in another direction? > To match your honesty, I'm somewhat tired with the trend of > some people to hit -one- issue with Python and suddenly lash > out like children over all the same old tired crap. Have you > even looked at multiprocessing? Have you contributed to any > projects working on GIL- less implementations? Or are you > just regurgitating the same bullet points we've heard time > and time again? Multiprocessing solves some problems, but it is unsuitable for high-frequency handoffs of large (in memory) objects between many independent threads/processes -- the HPC object/data flow parallelization model in a nutshell. Furthermore, not every coder has the compsci chops to work on language & VM implementations (my PhD involved programming DNA and directing evolution in a test tube, not parse trees and state machines). But that isn't to say I didn't try: at one point I even sketched out a possible TLS-based GIL workaround for handling the issue without breaking the existing C/API. It was of course shunned by those who knew better...for performance reasons IIRC. > For chrissake, if you cannot do ANYTHING but BITCH about a > change, then you've no damn right to consider yourself a > programmer. Real programmers find solutions, not excuses. Though I have certainly bitched about the threading issue multiple times on mailing lists including baypiggies and python-dev, bitching is not the only thing I've done. Having come to grips with my own coding limitations, I also offered to contribute financial resources from my own Python-enhanced business in support of GIL-removal -- before Python 3.0 was finalized. Unfortunately, no one responded to my offer. Even today, I am indirectly proposing the solution of "as" not being a reserved keyword since it has worked just fine for years without it. Yes that's late, but I didn't see this particular trainwreck coming (since it is not actually our current code which breaks, but rather, quantities of code created years ago but which must still run with fidelity into the far off future). Installing a Python macro preprocessor is another after-the-fact possible solution which may bear further investigation... Also today, I am proposing a pragmatic general solution for projects like ours in addressing both the 2.6/3.0 compatibility and threading situations. Specifically: deliberate migration away from C/Python and on to alternate VMs which happen to support Python syntax. Obviously none of my past efforts yielded fruit -- but it is wrong and unfair of you to assume and accuse me of not trying to come up with solutions. Solutions are virtually the entire game! > > And if so, then thank you all for so many wonderful years of effort > > and participation! > > You're welcome. Don't let the door hit you on the ass on your way out. But who's leaving who exactly? Surely a language as beautiful as Python will easily transcend the limitations of its flagship implementation (if or to the extent that such an implementation cannot keep pace with the times). That's all well and good -- it may even end up being the next great leap forward for the language. I believe Guido has even said as much himself. Warren From Russ.Paielli at gmail.com Sun Dec 7 19:18:02 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 7 Dec 2008 16:18:02 -0800 (PST) Subject: Python for kids? References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> Message-ID: <3f1995ed-ccdf-4dd1-89ee-8a30b85db2df@i24g2000prf.googlegroups.com> On Dec 7, 12:13?pm, "Russ P." wrote: > I have a 12-year-old son who spends too much time playing Xbox live > and watching silly YouTube videos. I would like to try to get him > interested in programming. Is anyone aware of a good book or website > that addresses this concern, preferably (but not necessarily) using > Python? I could try to teach him Python myself, but I'm afraid I would > just frustrate him and kill his interest in programming. I did a > Google search and found a few things, but not a lot. Thanks. From bignose+hates-spam at benfinney.id.au Thu Dec 4 22:17:05 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 05 Dec 2008 14:17:05 +1100 Subject: RELEASED Python 3.0 final References: Message-ID: <874p1jux8u.fsf@benfinney.id.au> James Stroud writes: > comp.lang.python3k ? The language has undergone an incompatible divide. Hopefully the community need not do the same. -- \ ?People come up to me and say, ?Emo, do people really come up | `\ to you??? ?Emo Philips | _o__) | Ben Finney From levub137 at wi.rr.com Mon Dec 29 10:59:00 2008 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Mon, 29 Dec 2008 09:59:00 -0600 Subject: math module for Decimals Message-ID: <4958F3C4.1050103@wi.rr.com> Since the interest is more in extended precision than in decimal representation, there is another module that may be of interest. http://calcrpnpy.sourceforge.net/clnum.html It interfaces to the Class Library for Numbers (CLN) library to provide both arbitrary precision floating point and complex floating point numbers and the usual math functions. While I am the author of this module, I agree with Mark that a module based on MPFR would be better since you have better control over precision and rounding. I have looked at Sage (which uses MPFR) but it is a huge integrated package so you can't just import what you need into one of your usual Python scripts. I wrote the clnum module mainly to support arbitrary precision in an RPN calculator available from the same SourceForge project. However, it also works nicely as a stand-alone module. At this time, there is no Windows installer available for Python 2.6 because I don't use Windows at home and the person who normally builds the installer for me is no longer interested. If someone wants to follow the published instructions and send me the resulting installer, I will put it up on SourceForge. Ray Jerry Carl wrote: >> 1. mpmath? > 2. sympy? > 3. Sage? Haven't tried those, i guess i have some studying to do. > > x=Decimal.__mod__(x,Decimal('2')*pi()) > > Works fine for what i need, but i am sure it's not the right way to do > > it. > I don't know of any better way to deal with large arguments. > The main problem is that the reduction step can introduce fairly > large errors: for example, if you're using a value of pi > that's accurate to 10**-20, say, then reducing something of > magnitude 10**5*pi will give a result with error of around > 10**-15. As far as I know, this problem is essentially > unavoidable, and it's the reason why implementing sin for inputs > like 10**999999999 isn't feasible. Good point. No tool will work in all parts of the universe (which is especially true for the universal ski wax). Let me check the 3 modules you listed above! From prologic at shortcircuit.net.au Mon Dec 8 09:38:06 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 9 Dec 2008 00:38:06 +1000 Subject: Beginner trying to understand functions. In-Reply-To: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> Message-ID: On Tue, Dec 9, 2008 at 12:24 AM, cadmuxe wrote: > i think we should use raw_input('Please enter your name: ') instead of > input('Please enter your name: ') Good point :) OP: Please take notes :) cheers James -- -- -- "Problems are solved by method" From jarausch at igpm.rwth-aachen.de Wed Dec 3 05:50:48 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Wed, 03 Dec 2008 11:50:48 +0100 Subject: Is it safe to modify the dict returned by vars() or locals() In-Reply-To: References: <4934508b$0$2861$ba620e4c@news.skynet.be> <4935011A.9080406@igpm.rwth-aachen.de> Message-ID: <49366488.80602@igpm.rwth-aachen.de> Duncan Booth wrote: > Helmut Jarausch wrote: > >> Chris Rebert wrote: >>> On Mon, Dec 1, 2008 at 1:01 PM, Helmut Jarausch >>> wrote: >>>> Hi, >>>> >>>> I am looking for an elegant way to solve the following problem: >>>> >>>> Within a function >>>> >>>> def Foo(**parms) >>>> >>>> I have a list of names, say VList=['A','B','C1'] >>>> and I like to generate abbreviation >>>> _A identical to parms['A'] >>> Could you explain what you mean by that? Your sample code doesn't >>> seem to do any "abbreviation"... >>> Otherwise I don't see why you don't just have a proper parameter >>> list. >> In my application parms contains field names of an html form iff these >> fields have been modified. >> I'd like to use the short name _A instead of the longer expression >> parms['A'] >> >> > You haven't yet explained why you don't just do: > > def foo(A=None, **parms): > ... > > The code to call foo remains the same as before, but Python will unpack > the named parameter into the local variable A for you automatically. Any > other parms that you didn't know about in advance remain in the separate > dictionary. > Many thanks, that's a very elegant solution. Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From manu3d at gmail.com Sat Dec 13 19:05:48 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Sat, 13 Dec 2008 16:05:48 -0800 (PST) Subject: Bidirectional Networking References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <98a6c3cd-181c-43c9-805b-fb0689c69544@a26g2000prf.googlegroups.com> Message-ID: <29283382-3e26-492a-8612-9352f32c1c01@r15g2000prd.googlegroups.com> On Dec 13, 11:13 pm, Bryan Olson wrote: > Software firewalls will often simply refuse incoming connections. The > basic protection of the garden-variety home router comes from "network > address translation" (NAT), in which case TCP connections initiated from > the inside will generally work, regardless of port, and incoming > connections will fail. Ok, I think I'm getting the picture here. So this means that in most circumstances where the data flow from the server is frequent the client initiates the connection, usually requests some initial data and keeps polling the server periodically, issuing new requests. In this context can the client simply keep the connection alive and listen for new data from the server coming at any time rather than actively issuing requests? Are there drawbacks to this strategy? I.e. is there a limit to the number of simultaneous connections a server can keep alive? I've noticed that the socket pages mention a 5 connections limit. Is that it? What if I want to make a virtual room with 20 people connected simultaneously? > > or would it be the responsibility of the user > > to configure the firewall so that the application can receive a > > connection? > > That can be a huge hassle. The first choice is for the application to > conform to popular firewall policies, so no special configuration is > required. I agree, I'd rather have the user do nothing in this regard. I'm just wondering how it's done with data intensive application where the server needs to send new data to the client frequently. Does the client just keep the connection live at all time for the server to send stuff or does the client continuously open, sends a request, receives data and closes the connection every time? Here I'm thinking about an online game, with 100 players moving their avatars. Does the client requests their position nearly every frame? Manu From bj_666 at gmx.net Sat Dec 13 06:35:24 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 13 Dec 2008 11:35:24 GMT Subject: Umlauts in idle References: <26880ecf-d0eb-42ab-8ebd-56f64c023999@v39g2000pro.googlegroups.com> <4943829B.9050606@v.loewis.de> Message-ID: <6qhkvsFclvujU2@mid.uni-berlin.de> On Sat, 13 Dec 2008 02:58:48 -0800, a_olme wrote: > On 13 Dec, 10:38, "Martin v. L?wis" wrote: >> > When I try to use umlauts in idle it will only print out as Unicode >> > escape characters. Is it possible to configure idle to print them as >> > ordinary characters? >> >> Did you really use the print statement? They print out fine for me. >> >> Regards, >> Martin > > No I just put the characters in quotes like this "???"[::-1] and pressed > return. Then you have two problems: First, you don't have unicode characters but a bunch of bytes which encode the three characters you've showed above. Reversing the bytes might "break" them if your system uses multiple bytes to encode one character, e.g. UTF-8, because the order does matter. Second, if you don't ``print`` but let the interpreter show the result you get the `repr()` form of that character displayed, which always uses escapes for bytes that are non-printable or not within the ASCII range for strings. Ciao, Marc 'BlackJack' Rintsch From pietersteenekamp at gmail.com Wed Dec 3 03:32:22 2008 From: pietersteenekamp at gmail.com (pieter) Date: Wed, 3 Dec 2008 00:32:22 -0800 (PST) Subject: How to use a Python function that returns a double array in C++. Message-ID: <24b01c57-0197-4971-9489-47345a2777f7@h20g2000yqn.googlegroups.com> I want to use a Python function that returns a double array in C++. I don?t have a problem if the Python function returns a single variable of type double, using the following lines in my C++ code: myPythonObjectPointer = PyObject_CallObject(pFunc, pArgs); myCppDoubleVariable = PyFloat_AsDouble(myPyObjectPointer); (I have obviously done all the required thingies to embed Python in C+ + as per the Python documentation) I can achieve what I want by changing the Python function to a number of functions, each returning a single double variable and call them one by one, using code like above, and then passing them into an array in C++, but I would prefer a more elegant way of doing it, because my return variable could have hundreds, if not thousands, of values.. Can somebody help me please. Thanks Pieter Steenekamp. From jstroud at mbi.ucla.edu Thu Dec 4 21:39:35 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 04 Dec 2008 18:39:35 -0800 Subject: RELEASED Python 3.0 final In-Reply-To: References: Message-ID: Barry Warsaw wrote: > On behalf of the Python development team and the Python community, I am > happy to announce the release of Python 3.0 final. comp.lang.python3k ? From bearophileHUGS at lycos.com Sat Dec 6 07:02:54 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 6 Dec 2008 04:02:54 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> Message-ID: <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> Antoine De Groote: > Allowing "$" as a substitute for "self" wouldn't require this new syntax. > class C: > def method($, arg): > $.value = arg I think this (that is just sugar) may be a little better: class C: def method($, arg): $value = arg Or even this, combined with the idea suggested in the post by Guido: class C: def $method(arg): $value = arg (Note there's no point after $, it's not currently possible). Ruby uses @ and @@ for similar purposes. I agree that the code looks worse, but also shorter to read and write, so in lines of code that use many instance attributes, that short $ syntax helps keep the line shorter. So I may grow to accept this sugar... Bye, bearophile From paul.hermeneutic at gmail.com Tue Dec 16 11:38:56 2008 From: paul.hermeneutic at gmail.com (Paul Watson) Date: Tue, 16 Dec 2008 10:38:56 -0600 Subject: help I'm getting delimited In-Reply-To: <817cf531-225b-4c4e-b79b-10d7657b0749@35g2000pry.googlegroups.com> Message-ID: <1229445534.5328.0.camel@linux-3eb6.site> On Tue, 2008-12-16 at 08:26 -0800, aka wrote: > Hi, I'm going nuts over the csv.reader and UnicodeReader class. > Somehow I can't get this method working which is supposed to read a > csv file which name is inputted but here now hardcoded. What I need > for now is that the string version of the list is put out for control. > Later on I will only need to read the first column (id) of the csv > file to be able to fill in a session var with a list of all ids. > inp = c:/temp/test.csv > roles = [] > try: > fp = open(inp, 'rb') > reader = csv.reader(fp) > for r in reader: > rollen.append(r) > except: > msg = "Er is iets mis met de UnicodeReader" > > return dict(file=in,roles=str(roles)) > Any help greatly appreciated! > Cheers Did you intend inside the loop to write: roles.append(r) From joel.hedlund at gmail.com Tue Dec 16 03:36:38 2008 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Tue, 16 Dec 2008 09:36:38 +0100 Subject: weird dict problem, how can this even happen? In-Reply-To: References: Message-ID: Duncan Booth wrote: > It could happen quite easily if the hash value of the object has changed > since it was put in the dictionary. what does the definition of your > core.gui.FragmentInfo object look like? Dunno if it'll help much, but: class FragmentInfo(object): def __init__(self, renderer, render_area): self.renderer = renderer self.render_area = render_area def __hash__(self): return hash((FragmentInfo, self.renderer, self.render_area)) def __eq__(self, other): return (isinstance(other, self.__class__) and other.renderer == self.renderer and other.render_area == self.render_area) > Is the hash definitely immutable? No. It's a hash of a tuple of its key attributes, themselves similar objects. The program can be thought of as a map viewer. In the gui part, image fragments are cached for speed, and fragments are only half rendered if there's a lot of complex features to draw. The "pool" consists of semi rendered fragments. The reason I did it this way is the cache. The cache is a dict with a use tracker so when the hash changes, the older fragments eventually drop from the cache. Hmm... I'm starting to realise now why my implementation of this isn't so hot. I'm going to hazard a guess here, and then you can correct me ok? I create a dict and populate it with a key-value pair, and then the key's hash changes. When the key is returned by k = d.keys(), then k not in d, even though k in d.keys(). Simple example: > class moo(object): > def __init__(self, a): > self.a = a > def __hash__(self): > return hash(self.a) > > d = {moo(1): 1} > > k = d.keys()[0] > k.a = 2 > > k = d.keys()[0] > print k in d, k in d.keys() > d.pop(k) output: > False True > Traceback (most recent call last): > File "/bioinfo/yohell/eclipse/Test/src/test.py", line 14, in > d.pop(k) > KeyError: <__main__.moo object at 0x7f1c64120590> I'd say that's pretty similar to what I observed. I guess the logical outcome is that the cache dict will fill up with old junk that I can't access and can't selectively flush since the hashes have changed, unless I actually somehow save copies of the keys, which can get pretty complex and probably won't do wonders for execution speed. Yeah this was probably a bad soulution. I should probably do this with lists instead because I can't really think of a way of salvaging this. Am i right? Thanks for your help! /Joel From honey33145 at gmail.com Thu Dec 4 04:20:47 2008 From: honey33145 at gmail.com (navneet khanna) Date: Thu, 4 Dec 2008 14:50:47 +0530 Subject: TypeError: not enough arguments Message-ID: Hello Everbody I have imported a class from vb.net dll in Python. I am able to import all the functions, but its showing such error when trying to access it. g() is a simple function in dll which takes no argument but returns a string. print Class1.g() Traceback (most recent call last): File "", line 1, in print Class1.g() TypeError: not enough arguments Please help me out. Thanks Navneet -------------- next part -------------- An HTML attachment was scrubbed... URL: From notvalid2 at sbcglobal.net Tue Dec 16 21:46:30 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Tue, 16 Dec 2008 18:46:30 -0800 Subject: WinMerge--B/W Shading of Printed Copy to Show Differences? In-Reply-To: References: <3jX1l.6876$pr6.3299@flpi149.ffdc.sbc.com> Message-ID: Jason Scheirer wrote: > On Dec 16, 3:56 pm, "W. eWatson" wrote: >> Is there a way to highlight differences between the two files when printing >> in b/w? Help suggests there may be some texturing, but all I see is color >> choices. >> -- >> W. eWatson >> >> (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) >> Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet >> >> Web Page: > > WinMerge is written in C++ and not even remotely related to Python. Well, yes, but it has applicability to Python (and maybe other languages) in that I can use it to find differences between two sets of code. If not here, where? comp.lang.??? ? -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From ebuyvip at hotmail.com Mon Dec 22 00:32:50 2008 From: ebuyvip at hotmail.com (Jacky) Date: Sun, 21 Dec 2008 21:32:50 -0800 (PST) Subject: Discount (paypal) www.ebuyvip.com nfl jersey ugg boots Message-ID: <8f870e86-4af3-458d-92ea-8a01d291b739@s9g2000prm.googlegroups.com> Hi friend Thanks for your reply. The current stock list with the available jerseys and sizea in the add annex, pls check it. and the jerseys pictures you can check my ablum : http://likenfl.photo.163.com . the moq order: 10 pcs the price : $20 inc shipping fee and tax.If you worry do businees with me first. and cann't trust me, the payment we can by paypal. that we all can trust other. If you have any questions pls tell me , i will give you a satisfaction answer. Hope we can have a nice and long term cooperation. UGG BOOTS: $45 NFL JERSEY: $20 Website: www.ebuyvip.com MSN: ebuyvip at hotmail.com Waiting for your good news. Best Regard Jarky From Eric_Dexter at msn.com Mon Dec 15 12:08:30 2008 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Mon, 15 Dec 2008 09:08:30 -0800 (PST) Subject: Getting in to metaprogramming References: <6cd0d1c2-90ed-4dad-94bf-3e98ddf89118@o40g2000prn.googlegroups.com><842a1a1d-42bd-440d-b4b5-57170adb2f37@l42g2000yqe.googlegroups.com><7832d70e-7bb9-469d-9edd-0864c3bb357d@b38g2000prf.googlegroups.com><15fec804-feb6-48ce-85cc-efbb9a5e30cb@33g2000yqm.googlegroups.com><013d5a5b$0$11497$c3e8da3@news.astraweb.com> Message-ID: On Nov 27, 9:56?pm, "Hendrik van Rooyen" wrote: > ?"Steven D'Aprano" > > >GUI designer. You write a program to let the user create code by clicking > >buttons, dragging objects, drawing lines, etc. The GUI designer may use > >classes, but the purpose of those classes is to generate source code. > > Yikes, this is getting hairy- If "the problem" is to generate source code, > then you have to generate source code... > > >Testing code speed... you might have some functions with a loop, and you > >want to unroll the loop as an optimization. If you have one function, you > >can unroll it yourself. If you have a hundred such functions, you might > >want to write a program to do it. (Yes, I'm stretching...) > > Ok this one I'll buy - I can't think of a way to do this dynamically in a > class and get runnable code back. (but maybe I'm just not trying hard enough.) > > > > >Don't like that Python doesn't optimize tail-recursion? Then write a > >source-code analyzer that detects tail-recursion and re-writes the > >function using a while loop. > > This is like TJR's example (I think) > > > > > > >>> Thinking further back, when I was young and programming in Apple's > >>> Hypercard 4GL, I used to frequently use Hypercard scripts to generate > >>> new Hypercard scripts. That was to work around the limitations of the > >>> scripting language. > > >> What sort of stuff did you do, and would having had simple OO available > >> have rendered it unnecessary? > > >It's been 20-odd years, and the examples were pretty trivial... I don't > >really recall exactly, but it would have been something like this: > > >* design a GUI involving lots of buttons on screen, each one with quite > >similar but not identical code; > > >* since Hypercard didn't have a layout manager, write a script to > >generate each button, place it where needed, and set the button's code. > > >Hypercard did have a message passing hierarchy (like inheritance for > >objects), so often you could take the button's code and place it in a > >higher level of the hierarchy (the card, the background, the stack), but > >there were odd cases where that wasn't enough. > > >Another example: Hypercard had a very limited number of GUI elements > >(text fields and buttons, basically) but I designed a slider control > >using a few buttons, each button with a custom script. To avoid needing > >to create and place the buttons by hand each time I wanted a slider, I > >had a script that did it for me. The script not only created the buttons, > >but it created the scripts used by the buttons. This wasn't as difficult > >as it sounds -- it was basically taking a template and doing some text > >replacements, then telling the button to use it as a script. > > Ok I think I am beginning to get the picture - when you have to do stuff > that the language does not directly support, then you use the simple > available elements, and create source code that strings them together > to make more complex stuff. -in this case its probably not trivial to > do it at run time. > > The "make the source code" then run it, introduces a kind of compiler > stage. > > For an old assembler programmer, this is starting to sound like macros. > > So a different meta law would read like: > > One uses Code Generation Techniques when the language does not > have macros. > > *ducks* > > - Hendrik- Hide quoted text - > > - Show quoted text - I have been converting stuff like sound 100, 1 exc... and just writing like 100, 1 for a number of languages and then just loading it into a spreadsheet so that I can save little pieces of songs exc.. I can even use different compilers or libraries that way.. I have started doing that for quickbasic, qbasic, free basic, qb64, c++.... All I do is use strings and '\n'.. I get to use a large number of older sounds and effects (for basic) on newer compilers that have aditional options.. It just looks like another music tracker.. I am not sure if that fits what you are trying to do though. From wuwei23 at gmail.com Thu Dec 4 07:22:32 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 4 Dec 2008 04:22:32 -0800 (PST) Subject: "as" keyword woes References: Message-ID: On Dec 4, 7:28?pm, "Warren DeLano" wrote: > But who's leaving who exactly? ?Surely a language as beautiful as Python > will easily transcend the limitations of its flagship implementation (if > or to the extent that such an implementation cannot keep pace with the > times). ?That's all well and good -- it may even end up being the next > great leap forward for the language. ?I believe Guido has even said as > much himself. Warren, thank you for a far more reasonable response than my post warranted. There seems a trend on this group for frustration to turn into ultimatums, which is what really triggered my outburst. Well, that and a crappy day at work. As for your above comment, I totally agree. It's probably the main outcome I'd like to see arise from the PyPy project: faster and easier experimentation with implementations. Nothing like some additional evolutionary pressure to make Python more fit. Good luck with resolving your current issue. From wyldwolf at gmail.com Fri Dec 5 15:27:59 2008 From: wyldwolf at gmail.com (Kevin Kelley) Date: Fri, 5 Dec 2008 14:27:59 -0600 Subject: Problems running on hp duo Pentium R processor In-Reply-To: <200812051502.26421.inq1ltd@inqvista.com> References: <200809221443.25765.inq1ltd@inqvista.com> <200809221446.29472.inq1ltd@inqvista.com> <200812051502.26421.inq1ltd@inqvista.com> Message-ID: <77895c1d0812051227o104ff233m7f16410e3cf8b392@mail.gmail.com> If they are running standard Win XP (Home or Pro), as opposed to 64-bit Win XP, then whether or not the CPU supports the IA64 instruction set really doesn't matter. As far as I know every Intel Core2 and Pentium Dual-Core CPU since ~ 2006 has supported 64bit instructions, even the Atom is 64bit. Also, the "R" is for Registered Trademark (of Pentium), it's not part of the name/model (http://ark.intel.com/cpu.aspx?groupId=33925). Kevin On Fri, Dec 5, 2008 at 2:02 PM, jim-on-linux wrote: > Python help, > > In September I wrote: > I have a number of clients running a program built > with python 2.5. One has just purchased an HP with > a duo core Pentium R processor E2200, 2.2G with .99g > ram. > > Only on the new HP, when they try to print they get an > import error; > File win32ui.pyc line 12, in > File win32ui.pyc, line 10, in _load > ImportError: DLL load failed: The specified module > could not be found. > > It turns out that the E2200 processor is 64 bit > architecture. > > What are my options? > > I've run DependecyWalker, > They are using Win XP Service Pack 2 > > > > jim=on-linux > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From 5lvqbwl02 at sneakemail.com Sun Dec 28 03:44:51 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Sun, 28 Dec 2008 00:44:51 -0800 (PST) Subject: Doing set operation on non-hashable objects References: <3a87eb6a-13ff-4aea-8835-3a233cc6cfc4@w39g2000prb.googlegroups.com> Message-ID: <911b1a97-53e7-4f45-bb6f-ae1b8a3d34d1@g1g2000pra.googlegroups.com> > > ... "db" is a dict, where the values are also dicts. > > A function searches through db and returns a list of values, each of > > which is a dict as described above. > > I need to perform set operations on these lists (intersection and > > union) > > However the objects themselves are not hashable, and therefore can't > > be in a set, because they are dicts. > > I'm not sure how large each set will be, but the point is I'm trying > > to avoid anything looking like an O(n^2) algorithm, so I can't just > > use naive double-looping to check for intersection/union on a pair of > > lists. > > Well, if the lists are ordered, you can do intersection and union > in O(n) time. ?If they are orderable, you can sort each first, giving > O(n log n). ?Note you can do lst.sort(key=id) which will sort on ids. The lists are not ordered, since the elements of the list could be arbitrarily complex things consisting of resistors, capacitors, sub- circuits, etc. I'm trying do a little EDA program, taking the best parts from the different EDA/cad tools I've used. I finally came up with an idea using dictionaries in a certain way, so I'd like to be able to do set operators on arbitrary things that may themselves not be hashable. > > How do you get the object back from an ID in python? > > You don't; you remember the mapping in a dictionary and look it up. Exactly. A mapping between the ID and the thing itself. > If there were a way to go from id to object, the whole idea of garbage > collection and reference counts would fly out the window, leading to > nasty crashes (or you might get to an object that is the re-used id of > an older object). Yup, this makes perfect sense. It was rattling around in my head for a bit afer I wrote the original post, then this makes sense. > From steve at holdenweb.com Wed Dec 17 06:18:36 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 17 Dec 2008 06:18:36 -0500 Subject: regex problem .. In-Reply-To: <3b10c2060812170303w1cd8ecdmad7c97c42e44f08@mail.gmail.com> References: <3b10c2060812150421y1c3e7da6ha1b72c736e2a20d4@mail.gmail.com> <3b10c2060812170303w1cd8ecdmad7c97c42e44f08@mail.gmail.com> Message-ID: <4948E00C.2020006@holdenweb.com> Analog Kid wrote: > Hi guys: > Thanks for your responses. Points taken. Basically, I am looking for a > combination of the following ... > [^\w] and %(?!20) ... How do I do this in a single RE? > > Thanks for all you help. > Regards, > AK > > On Mon, Dec 15, 2008 at 10:54 PM, Steve Holden > wrote: > > Analog Kid wrote: > > Hi All: > > I am new to regular expressions in general, and not just re in python. > > So, apologies if you find my question stupid :) I need some help with > > forming a regex. Here is my scenario ... > > I have strings coming in from a list, each of which I want to check > > against a regular expression and see whether or not it "qualifies". By > > that I mean I have a certain set of characters that are > permissible and > > if the string has characters which are not permissible, I need to flag > > that string ... here is a snip ... > > > > flagged = list() > > strs = ['HELLO', 'Hi%20There', '123123@#@'] > > p = re.compile(r"""[^a-zA-Z0-9]""", re.UNICODE) > > for s in strs: > > if len(p.findall(s)) > 0: > > flagged.append(s) > > > > print flagged > > > > my question is ... if I wanted to allow '%20' but not '%', how > would my > > current regex (r"""[^a-zA-Z0-9]""") be modified? > > > The essence of the approach is to observe that each element is a > sequence of zero or more "character", where character is "either > letter/digit or escape." So you would use a pattern like > > "([a-zA-Z0-9]|%[0-9a-f][0-9a-f])+" > > Did you *try* the above pattern? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From victorsubervi at gmail.com Fri Dec 26 10:01:54 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 26 Dec 2008 16:01:54 +0100 Subject: =?ISO-8859-1?Q?Can=B4t_Surf_Python_Pages_in_Windoze?= Message-ID: <4dc0cfea0812260701q6baf0ccbj154c5b3fa2281cdb@mail.gmail.com> Hi; I try to surf to this code in Windoze and it doesn't work...just posts a small, black screen for a split second. Why? print "Content-Type: text/html" print print """ Yeah """ Also, Zope is installed, but when I go to: localhost:8080/manage_main or local:8080/Zope-Instance/manage_main I get a 404, after having started the service and everything is go. I have Python up. What gives? Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Tue Dec 23 03:46:59 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 23 Dec 2008 08:46:59 +0000 Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> <1iscu14.oixxplpgajabN%pdorange@pas-de-pub-merci.mac.com> Message-ID: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) writes: > def sign_0(x): > if x==0.0: > return 0.0 > elif x>0.0: > return 1.0 > else: > return -1.0 > This might be slightly faster: def sign(x): return 1 if x > 0 else x and -1 -- Arnaud From pavlovevidence at gmail.com Sat Dec 6 22:40:58 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 6 Dec 2008 19:40:58 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> <845f784f-8dcd-4f18-ae78-3f528f179b3e@r15g2000prd.googlegroups.com> Message-ID: <94791ba5-b58d-437c-89b6-fc08d142725f@j11g2000yqg.googlegroups.com> On Dec 6, 6:42?pm, "Russ P." wrote: > > But it's ugly. ?No amount of rationalization will make it not ugly. > > The dollar sign is ugly? I beg to differ. Nope, you're wrong. Carl Banks (See where this is going?) From jon at ffconsultancy.com Mon Dec 1 19:06:22 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Tue, 02 Dec 2008 00:06:22 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: Xah Lee wrote: > And on this page, there are sections where Mathematica is compared to > programing langs, such as C, C++, Java, and research langs Lisp, > ML, ..., and scripting langs Python, Perl, Ruby... Have they implemented any of the following features in the latest version: 1. Redistributable standalone executables. 2. Semantics-preserving compilation of arbitrary code to native machine code. 3. A concurrent run-time to make efficient parallelism easy. 4. Static type checking. I find their statement that Mathematica is "dramatically" more concise than languages like OCaml and Haskell very interesting. I ported my ray tracer language comparison to Mathematica: http://www.ffconsultancy.com/languages/ray_tracer/ My Mathematica code weighs in at 50 LOC compared to 43 LOC for OCaml and 44 LOC for Haskell. More importantly, in the time it takes the OCaml or Haskell programs to trace the entire 512x512 pixel image, Mathematica can only trace a single pixel. Overall, Mathematica is a whopping 700,000 times slower! Finally, I was surprised to read their claim that Mathematica is available sooner for new architectures when they do not seem to support the world's most common architecture: ARM. Also, 64-bit Mathematica came 12 years after the first 64-bit ML... Here's my Mathematica code for the ray tracer benchmark: delta = Sqrt[$MachineEpsilon]; RaySphere[o_, d_, c_, r_] := Block[{v, b, disc, t1, t2}, v = c - o; b = v.d; disc = Sqrt[b^2 - v.v + r^2]; t2 = b + disc; If[Im[disc] != 0 || t2 <= 0, \[Infinity], t1 = b - disc; If[t1 > 0, t1, t2]] ] Intersect[o_, d_][{lambda_, n_}, Sphere[c_, r_]] := Block[{lambda2 = RaySphere[o, d, c, r]}, If[lambda2 >= lambda, {lambda, n}, {lambda2, Normalize[o + lambda2 d - c]}] ] Intersect[o_, d_][{lambda_, n_}, Bound[c_, r_, s_]] := Block[{lambda2 = RaySphere[o, d, c, r]}, If[lambda2 >= lambda, {lambda, n}, Fold[Intersect[o, d], {lambda, n}, s]] ] neglight = N at Normalize[{1, 3, -2}]; nohit = {\[Infinity], {0, 0, 0}}; RayTrace[o_, d_, scene_] := Block[{lambda, n, g, p}, {lambda, n} = Intersect[o, d][nohit, scene]; If[lambda == \[Infinity], 0, g = n.neglight; If[g <= 0, 0, {lambda, n} = Intersect[o + lambda d + delta n, neglight][nohit, scene]; If[lambda < \[Infinity], 0, g]]] ] Create[level_, c_, r_] := Block[{obj = Sphere[c, r]}, If[level == 1, obj, Block[{a = 3*r/Sqrt[12], Aux}, Aux[x1_, z1_] := Create[level - 1, c + {x1, a, z1}, 0.5 r]; Bound[c, 3 r, {obj, Aux[-a, -a], Aux[a, -a], Aux[-a, a], Aux[a, a]}]]]] scene = Create[1, {0, -1, 4}, 1]; Main[level_, n_, ss_] := Block[{scene = Create[level, {0, -1, 4}, 1]}, Table[ Sum[ RayTrace[{0, 0, 0}, N at Normalize[{(x + s/ss/ss)/n - 1/2, (y + Mod[s, ss]/ss)/n - 1/2, 1}], scene], {s, 0, ss^2 - 1}]/ss^2, {y, 0, n - 1}, {x, 0, n - 1}]] AbsoluteTiming[Export["image.pgm", Graphics at Raster@Main[9, 512, 4]]] -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From clp at rebertia.com Sun Dec 21 01:56:07 2008 From: clp at rebertia.com (Chris Rebert) Date: Sat, 20 Dec 2008 22:56:07 -0800 Subject: Question: Evaluate an string variable's value to a variable In-Reply-To: <4be6e91b-9fcf-4c22-bfe8-fad73190f87c@b41g2000pra.googlegroups.com> References: <4be6e91b-9fcf-4c22-bfe8-fad73190f87c@b41g2000pra.googlegroups.com> Message-ID: <47c890dc0812202256t392dbd31s8fccded455893d53@mail.gmail.com> On Sat, Dec 20, 2008 at 10:49 PM, Mir Nazim wrote: > Just a quick question. > > For example I have > >>>> class X >>>> ....pass > > Then I do >>>> x = X() >>>> x.name = 'Nazim > > Now my question is whether something like below is possible and how >>>> y = 'name' >>>> print x.y # How can x.y can be evaluated to x.name print getattr(x, y) #==> Nazim There are also analogous setattr() and delattr() functions. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From google at mrabarnett.plus.com Thu Dec 4 13:28:35 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 04 Dec 2008 18:28:35 +0000 Subject: python an sqlite objects In-Reply-To: References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <18742.47391.389709.119341@montanaro-dyndns-org.local> Message-ID: <49382153.80604@mrabarnett.plus.com> Bryan Olson wrote: > Gerhard H?ring wrote: >> Be sure to save it as BLOB, not TEXT. >> >> Suppose you have serialized your object as Python bytestring. >> >> serialized = ... >> ... .execute("insert into mytable(mycolumn) values (?)", >> (sqlite3.Binary(serialized),)) >> >> This way you will get a BLOB in the form of a Python buffer object when >> you later select it from the database [...] > > Good advice for now, with Python 2.X. Python 3 resolves most of > confusion with its distinction between the string type and the bytes > types. The 3.x standard library sqlite3 module understands the 'bytes' > and 'bytearray' types, and treats them appropriately. > > Here's a runnable Python 3 demo: > > # Ensure that we're running Python 3 or later. > import sys > assert int(sys.version.split()[0].split('.')[0]) >= 3 > # If there's a better way to chek, please tell. > [snip] Why split on whitespace and then '.'? assert int(sys.version.split('.')[0]) >= 3 From python-url at phaseit.net Wed Dec 3 13:47:43 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Wed, 3 Dec 2008 18:47:43 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Dec 3) Message-ID: QOTW: "Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out." - GHUM Strategies for developing effective sets of unit tests: http://groups.google.com/group/comp.lang.python/t/e850a45655099217/ Python became more popular than Perl, acording to TIOBE index: http://groups.google.com/group/comp.lang.python/t/fb650cf462bf8f16/ A design problem shows that inheritance isn't always the right relationship between classes: http://groups.google.com/group/comp.lang.python/t/8f8c96c27f2425c2/ Another design question: instance attributes vs. class attributes vs. function arguments: http://groups.google.com/group/comp.lang.python/t/3982be22cc4a0633/ Modules are singletons usually, but beware of duplicate imports under different names: http://groups.google.com/group/comp.lang.python/t/51dd881f83adeb35/ Using module decorators (whatever that means): http://groups.google.com/group/comp.lang.python/t/215216a1e13ba2c6/ Nested functions: are they fast? make the code confusing? when is OK to use them? http://groups.google.com/group/comp.lang.python/t/9d458fc630554307/ Converting a fixed, static function definition into a more generic one: http://groups.google.com/group/comp.lang.python/t/54caf74fd3454b8d/ "Metaprogramming" in Python (Python code generating Python code): http://groups.google.com/group/comp.lang.python/t/d924498ae98e05d3/ Security implications of using open() on untrusted strings: http://groups.google.com/group/comp.lang.python/t/58acb08aac8b62a9/ \w (in a regular expression) does not match all Unicode characters it actually should: http://groups.google.com/group/comp.lang.python/t/669bb61bad1b58d5/ What different editors have to offer (emacs vs eclipse vs vim): http://groups.google.com/group/comp.lang.python/t/dee02886eccfaef2/ This was the longest thread this week - annoying? hilarious? paranoid? Probably worth reading only if you have plenty of time to waste: http://groups.google.com/group/comp.lang.python/t/c403b827231b9a4/ ======================================================================== 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 Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From bignose+hates-spam at benfinney.id.au Fri Dec 19 16:41:56 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 20 Dec 2008 08:41:56 +1100 Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <8763lfetaz.fsf@benfinney.id.au> Michael Torrie writes: > Personally the new string formatter is sorely needed in Python. And > they way it has been implemented is a thing of beauty. Basically the > burden of formatting strings has been moved from the print > statement/function to the objects themselves. This doesn't describe a difference between Python 2.x and Python 3.0. The string formatting in Python 2.x is nothing to do with ?print?, it's implemented in the function that handles the ?%? operator for strings. -- \ ?If consumers even know there's a DRM, what it is, and how it | `\ works, we've already failed.? ?Peter Lee, Disney corporation, | _o__) 2005 | Ben Finney From rhodri at wildebst.demon.co.uk Tue Dec 23 00:50:42 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Tue, 23 Dec 2008 05:50:42 -0000 Subject: Python's popularity In-Reply-To: <5uudnUmykoMD983UnZ2dnUVZ_rrinZ2d@posted.usinternet> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <18767.47566.709705.92@montanaro-dyndns-org.local> <5uudnUmykoMD983UnZ2dnUVZ_rrinZ2d@posted.usinternet> Message-ID: On Tue, 23 Dec 2008 04:35:42 -0000, Grant Edwards wrote: > IIRC, Python came pre-installed on my IBM Thinkpad. However, > it wasn't anyplace the average user would stumble across it... The suggestively named "IBMTOOLS" directory, I believe :-) -- Rhodri James *-* Wildebeeste Herder to the Masses From rt8396 at gmail.com Tue Dec 2 12:28:49 2008 From: rt8396 at gmail.com (r) Date: Tue, 2 Dec 2008 09:28:49 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <9baabb6c-daab-418e-a11f-9162e1fc30f7@k36g2000pri.googlegroups.com> <55c64b7e-3690-480f-88bd-7c2bdf04adc4@k8g2000yqn.googlegroups.com> Message-ID: At least -someone- besides myself has a sense of humor around here. PS James, i will look through my contact list and send you a few "easy" numbers... good luck :) From sjmachin at lexicon.net Wed Dec 3 15:51:44 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 3 Dec 2008 12:51:44 -0800 (PST) Subject: Converting a .xls file to .html References: Message-ID: <7fe462b5-c5df-429a-8fbe-dd2425d66ca4@r36g2000prf.googlegroups.com> On Dec 4, 12:57?am, Tino Wildenhain wrote: > Hi, > > tarun wrote: > > Hello All, > > > I've a .xml file (saved as .xls) that can be opened in Microsoft excel. The file extension is only a vague indication of the *format* of the contents. How was it created? > > Well if its an xml file then just attach a style to it and you can > just view it in a browser w/o involving excel in the first place. > > Also there are lots of xml libraries coming with python so you can > translate it directly into HTML of your choice. > > > I want to write python code that converts this excel file into .html (so > > that it can be viewed as is in an explorer). > > Whats an Explorer? I guess you mean Webbrowser here? > > Now if you manage to have it in Excel, then you could just save > it as HTML (or whatever Microsoft believes is HTML). Possibly an "Internet Explorer" :-) > > If the file is stored elsewhere in Excel-Format, then > you could script that using xlrd (google for it) I'm not sure what "stored elsewhere in Excel-Format" means. Currently xlrd reads only files written by Excel 2.0 up to Excel 2003 in the default "save as .XLS" binary format i.e. "BIFF2" to "BIFF8" format. I'd suggest that the OP inquire further in the python-excel group at http://groups.google.com/group/python-excel ... it would be a good idea to state how the file was created (or supply the first 100 or so bytes for inspection) plus what he really wants to achieve with the file and is this a one-off or regular exercise. HTH, John From castironpi at gmail.com Sat Dec 27 19:21:33 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 27 Dec 2008 16:21:33 -0800 (PST) Subject: game engine (as in rules not graphics) References: Message-ID: <402f625f-b835-4cb8-bcea-523756c489ca@g39g2000pri.googlegroups.com> On Dec 27, 3:02?pm, Martin wrote: > Hello, > > I'd like to get in touch with game development a bit. I'm not talking > about graphics but rather the game rules itself. Something likehttp://en.wikipedia.org/wiki/Monopoly_(game)#Rules, is there even a > general approach to that or should I just go sketch up my rules and > try to implement them. Being totally new to this topic I don't quite > now what to search for to get some decent results that let me make a > mental link between game rules and what the best practices are to > implement them in python (or any other programming language) > > thanks, > martin Not my expertise but here are my $0.02. You are looking for ways to represent rules: buying a house is legal in such and such situation, and the formula for calculating its price is something. You want "predicates" such as InJail, OwnedBy, Costs. Costs( New York Ave, 200 ) InJail( player2 ) OwnedBy( St. Charles Ave, player4 ) LegalMove( rolldie ) LegalMove( sellhouse ) There are rule-based languages out there, such as Prolog. They are equally expressive as Python (you can write a Turing machine in them), but they are more convenient for representing rules in a prog. language. Predicates are more or less equivalent to positive assertions about something. NewYorkAve.cost= 200 player2.injail= True... rolldie.islegal= True Some predicates have to be calculated, rather than stored, but Python descriptors go easy on you for that. Someone else will have to tell you how rule-based programming measures up against object-oriented programming. From ajaksu at gmail.com Tue Dec 23 01:00:36 2008 From: ajaksu at gmail.com (ajaksu) Date: Mon, 22 Dec 2008 22:00:36 -0800 (PST) Subject: python3 urlopen(...).read() returns bytes References: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> <5496b34d-7ce4-4281-9f01-aed12dab9fd3@f33g2000vbf.googlegroups.com> Message-ID: <42ad842c-8d8a-4ff5-a721-0688b7ae20f7@41g2000yqf.googlegroups.com> On Dec 22, 9:05?pm, Christian Heimes wrote: > ajaksu schrieb: > > > That said, a "decode to declared HTTP header encoding" version of > > urlopen could be useful to give some users the output they want (text > > from network io) or to make it clear why bytes is the safe way. > > Yeah, your idea sounds both useful and feasible. A patch is welcome! :) Would monkeypatching what urlopen returns be good enough or should we aim at a cleaner implementation? Glenn, does this sketch work for you? def urlopen_text(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): response = urlopen(url, data, timeout) _readline = response.readline _readlines = response.readlines _read = response.read charset = response.headers.get_charsets()[0] def readline(limit = -1): content = _readline() return str(content, encoding=charset) response.readline = readline def readlines(hint = None): content = _readlines() return [str(line, encoding=charset) for line in content] response.readlines = readlines def read(n = -1): content = _read() return str(content, encoding=charset) response.read = read return response Any comments/suggestions are very welcome. I could use some help from people that know urllib on the best way to get the charset. Maybe after some sleep I can code it in a less awful way :) Daniel From rt8396 at gmail.com Mon Dec 22 17:26:35 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 14:26:35 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <18767.47566.709705.92@montanaro-dyndns-org.local> Message-ID: <19b9ab88-6812-4416-9020-3be16b839fcd@m16g2000vbp.googlegroups.com> On Dec 22, 4:16?pm, Joe Strout wrote: > Alvin ONeal wrote: > > Also worthy of mention: > > I've seen python pre-installed on consumer HP desktops (I think as > > part of a backup/restore script, but I'm not sure) > > It's pre-installed on every Mac (both desktop and laptop), too. > > Cheers, > - Joe I am using a Vista HP right now that came pre-installed with Python. Blew my mind when i found out :). This single reason just reinforced my belief in Python. Now if we can get Python on every windows platform... From wrzesniowy at poczta.onet.pl Fri Dec 19 16:27:33 2008 From: wrzesniowy at poczta.onet.pl (blady) Date: Fri, 19 Dec 2008 13:27:33 -0800 (PST) Subject: Big Tits Big Boobs Message-ID: <10349e34-a52f-428c-aa6a-bf09c9786cf4@z28g2000prd.googlegroups.com> http://yeba.pl/show/movies/6044/pucybutka From benjamin.kaplan at case.edu Tue Dec 2 16:11:59 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 2 Dec 2008 16:11:59 -0500 Subject: Mathematica 7 compares to other languages In-Reply-To: <1B1C50D7-13B3-4E4C-A87F-F4EB4D9C508C@gmail.com> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <1B1C50D7-13B3-4E4C-A87F-F4EB4D9C508C@gmail.com> Message-ID: On Tue, Dec 2, 2008 at 3:39 PM, Petite Abeille wrote: > > On Dec 2, 2008, at 9:21 PM, Lew wrote: > > These are professional software development forums, not some script- >> kiddie cellphone-based chat room. "r" is spelled "are" and "u" should >> be "you". >> > > While Xah Lee arguably represents a cross between "Enfant Provocateur" [1] > and "Evil Clown" [2], this surely qualifies as a "Grammarian" [3] rebuke :D > > Cheers, > It's starting to look like Xah Lee is a Blowhard as well. > > -- > PA. > http://alt.textdrive.com/nanoki/ > > > [1] http://redwing.hutman.net/~mreed/warriorshtm/enfantprovocateur.htm > [2] http://redwing.hutman.net/~mreed/warriorshtm/evilclown.htm > [3] http://redwing.hutman.net/~mreed/warriorshtm/grammarian.htm > -- > > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Tue Dec 16 14:29:44 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 16 Dec 2008 19:29:44 +0000 Subject: Generator slower than iterator? References: Message-ID: Arnaud Delobelle writes: > match_total = dict((key, val()) for key, val in match_counter.iteritems()) Sorry I meant match_total = dict((key, val.next()) for key, val in match_counter.iteritems()) -- Arnaud From marduk at letterboxes.org Tue Dec 9 22:57:36 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Tue, 09 Dec 2008 22:57:36 -0500 Subject: Can't figure out where SyntaxError: can not delete variable 'x' referenced in nested scope us coming from in python >=2.6 In-Reply-To: <014eef7f$0$20670$c3e8da3@news.astraweb.com> References: <014eef7f$0$20670$c3e8da3@news.astraweb.com> Message-ID: <1228881456.11852.3.camel@blackwidow.nbk> On Tue, 2008-12-09 at 22:57 +0000, Steven D'Aprano wrote: [...] > > So is there a way to find the offending code w/o having to go > through > > every line of code in 'foo' by hand? > > Just search for "del x" in your code. Your editor does have a search > function, surely? > > Well, you'd think I'd be smart enough to think of that one, wouldn't you? Actually, how could you since you don't know me ;-)... Anway, I already did that and could not find the offending code. I submitted this bug [1]. I applied the given patch but the line it shows isn't a "del" anything so I'm even more confused. From harish.bhat.m at gmail.com Sat Dec 20 03:06:46 2008 From: harish.bhat.m at gmail.com (Harish) Date: Sat, 20 Dec 2008 00:06:46 -0800 (PST) Subject: Check file is Message-ID: <7caa7d45-ebbe-4c88-bb50-2f01f7315d07@s9g2000prg.googlegroups.com> Hi Friends Is there any utility in python which will help me to read any pdf files? Regards Harish From Alvin.ONeal at gmail.com Wed Dec 24 11:49:35 2008 From: Alvin.ONeal at gmail.com (Alvin ONeal) Date: Wed, 24 Dec 2008 09:49:35 -0700 Subject: Spam??? Message-ID: What's with all the spam on the list? I humbly request that recaptcha or some other sort of captcha be implemented on the registration page. AJ ONeal -------------- next part -------------- An HTML attachment was scrubbed... URL: From mgreene at bdurham.com Wed Dec 24 04:31:21 2008 From: mgreene at bdurham.com (Malcolm Greene) Date: Wed, 24 Dec 2008 04:31:21 -0500 Subject: Strategy for determing difference between 2 very large dictionaries In-Reply-To: <1230111025.22152.1291626575@webmail.messagingengine.com> References: <1230102996.2303.1291616055@webmail.messagingengine.com> <1230106980.12156.1291620725@webmail.messagingengine.com> <1230111025.22152.1291626575@webmail.messagingengine.com> Message-ID: <1230111081.22723.1291627105@webmail.messagingengine.com> Hi Gabriel, > in Python 3.0 keys() behaves as iterkeys() in previous versions, so the above code is supposed to be written in Python 2.x) I understand. Thank you. > note that dict comprehensions require Python 3.0 I'm relieved to know that I didn't miss that feature in my reading of Python's 2.5/2.6 documentation :) > You might use instead: > > dict((key,(dict1[key],dict2[key])) for key in ...) Excellent. Thank you. Regards, Malcolm ----- Original message ----- From: "Gabriel Genellina" To: python-list at python.org Date: Wed, 24 Dec 2008 07:10:16 -0200 Subject: Re: Strategy for determing difference between 2 very large dictionaries En Wed, 24 Dec 2008 06:23:00 -0200, escribi?: > Hi Gabriel, > > Thank you very much for your feedback! > >> k1 = set(dict1.iterkeys()) > > I noticed you suggested .iterkeys() vs. .keys(). Is there any advantage > to using an iterator vs. a list as the basis for creating a set? I You've got an excelent explanation from Marc Rintsch. (Note that in Python 3.0 keys() behaves as iterkeys() in previous versions, so the above code is supposed to be written in Python 2.x) >>> can this last step be done via a simple list comprehension? > >> Yes; but isn't a dict comprehension more adequate? >> >> [key: (dict1[key], dict2[key]) for key in common_keys if >> dict1[key]!=dict2[key]} > > Cool!! I'm relatively new to Python and totally missed the ability to > work with dictionary comprehensions. Yes, your dictionary comprehension > technique is much better than the list comprehension approach I was > struggling with. Your dictionary comprehension statement describes > exactly what I wanted to write. This time, note that dict comprehensions require Python 3.0 -- so the code above won't work in Python 2.x. (It's not a good idea to mix both versions in the same post, sorry!) You might use instead: dict((key,(dict1[key],dict2[key])) for key in ...) but it's not as readable. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list From deets at nospam.web.de Thu Dec 11 18:11:41 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 12 Dec 2008 00:11:41 +0100 Subject: HGE and Python (again) In-Reply-To: <8180969e-9289-4f8c-ab80-30fbc50914d1@g17g2000prg.googlegroups.com> References: <8180969e-9289-4f8c-ab80-30fbc50914d1@g17g2000prg.googlegroups.com> Message-ID: <6qdl1dFc3e1tU1@mid.uni-berlin.de> Cro schrieb: > Good day. > > I've been trying to port HGE (http://hge.relishgames.com) to Python > for more than 4 months now... > HGE is a hardware accelerated 2D game engine. > It comes with the source and examples. In the folder "include", you > can find "hge.h", the file that i am talking about in all the post. > > # > I tried to load the DLL functions with Python Ctypes like this : > [code] >>>> from ctypes import * >>>> HGE = cdll.LoadLibrary("C:/hge181/hge") >>>> HGE.hgeCreate(0x180) > [/code] > But i get this error : "Procedure called with not enough arguments (4 > bytes missing) or wrong calling convention". > The call should be done with hgeCreate(HGE_VERSION) and the constant > is defined as "#define HGE_VERSION 0x180"... > Number 0x180 means 384 in Python. I don't mean what it means in C. > So i am stuck. You are aware that ctypes knows another call for windows dlls with another calling convention? http://docs.python.org/library/ctypes.html#loading-dynamic-link-libraries Looking at the headers, I see #define CALL __stdcall So to me it looks as if you use the wrong DLL-loading mechanism. Diez From bruno.42.desthuilliers at websiteburo.invalid Fri Dec 12 07:56:22 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 12 Dec 2008 13:56:22 +0100 Subject: (Very Newbie) Problems defining a variable In-Reply-To: <11c53a4a-de1e-4bee-ad60-a05befb6cbf4@a12g2000yqm.googlegroups.com> References: <49425146$0$8495$426a74cc@news.free.fr> <11c53a4a-de1e-4bee-ad60-a05befb6cbf4@a12g2000yqm.googlegroups.com> Message-ID: <49425f5c$0$21931$426a74cc@news.free.fr> feba a ?crit : > On Dec 12, 5:56 am, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: (snip) >> I guess you wanted your first test to be: >> >> if bank <= 9999: >> ... (snip) > that's it, thanks! was confused with it being basically in a column of > all >= *. > > I replaced it with > > if bank <= 0: > print("You're in the red!") > quit() > elif bank >= 1 and bank <= 9999: > rate = 0.0060 > elif bank >= 10000 and bank <= 24999: > rate = 0.0085 > elif bank >= 25000 and bank <= 49999: > rate = 0.0124 > elif bank >= 50000 and bank <= 99999: > rate = 0.0149 > elif bank >= 100000: > rate = 0.0173 > else: > print("What's this doing here?") > > which also changes it to keep it from going on forever if you put in a > negative amount. Good point. > Out of curiosity, would you still recommend applying > an 'else' clause in this case? Yes, but I'd use it as a replacement for the last test: # code here ... elif bank >= 50000 and bank <= 99999: rate = 0.0149 else: rate = 0.0173 And finally, I'd simplify the whole damn thing: if bank < 1: print("You're in the red!") quit() elif bank < 10000: rate = 0.0060 elif bank < 25000: rate = 0.0085 elif bank < 50000: rate = 0.0124 elif bank < 100000: rate = 0.0149 else: rate = 0.0173 > I don't see how it could ever be > triggered, even if there's an error of some kind It couldn't, indeed. Which FWIW is a clear indication that the previous test ( elif bank >= 100000:) is redundant !-) HTH From n.kottiyath at gmail.com Sat Dec 6 09:42:57 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Sat, 6 Dec 2008 06:42:57 -0800 (PST) Subject: __import__ problem Message-ID: <8cd0e5b5-e7bc-4fc7-b17b-01e850f340eb@l39g2000yqn.googlegroups.com> Hi all, When I try to import a module via __import__, I am facing ImportError. But, when I tried to import it via usual 'import', it worked fine. Please see below: try: import exact except: logging.exception('Error during importing') try: code = __import__('exact') except: logging.exception('Is it still happening?') The error is as: 2008-12-06 20:06:59,328 ERROR Is it still happening? Traceback (most recent call last): File "C:\django\test\..\test\basic\views.py", line 166, in getValue code = __import__('exact') ImportError: No module named exact Could you please let me know why this is happening? I tried to __import__ 'sys etc, and it worked fine. Is it due to some issue in the path? Regards K From xahlee at gmail.com Mon Dec 8 18:14:18 2008 From: xahlee at gmail.com (Xah Lee) Date: Mon, 8 Dec 2008 15:14:18 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> <8evqj4p342jvcma5saibf54thv7075r88g@4ax.com> Message-ID: <9d5ecca4-3eb8-42ad-b4d8-951719ef874b@n33g2000pri.googlegroups.com> Dear George Neuner, Xah Lee wrote: > >The phenomenon of creating code that are inefficient is proportional > >to the highlevelness or power of the lang. In general, the higher > >level of the lang, the less possible it is actually to produce a code > >that is as efficient as a lower level lang. George Neuner wrote: > This depends on whether someone has taken the time to create a high > quality optimizing compiler. try to read the sentence. I quote: ?The phenomenon of creating code that are inefficient is proportional to the highlevelness or power of the lang. In general, the higher level of the lang, the less possible it is actually to produce a code that is as efficient as a lower level lang.? Xah Lee wrote: > >For example, > >the level or power of lang can be roughly order as > >this: > > >assembly langs > >C, pascal > >C++, java, c# > >unix shells > >perl, python, ruby, php > >lisp > >Mathematica George wrote: > According to what "power" estimation? Assembly, C/C++, C#, Pascal, > Java, Python, Ruby and Lisp are all Turing Complete. I don't know > offhand whether Mathematica is also TC, but if it is then it is at > most equally powerful. it's amazing that every tech geekers (aka idiots) want to quote ?Turing Complete? in every chance. Even a simple cellular automata, such as Conway's game of life or rule 110, are complete. http://en.wikipedia.org/wiki/Conway's_Game_of_Life http://en.wikipedia.org/wiki/Rule_110 in fact, according to Stephen Wolfram's controversial thesis by the name of ?Principle of computational equivalence?, every goddamn thing in nature is just about turing complete. (just imagine, when you take a piss, the stream of yellow fluid is actually doing turning complete computations!) for a change, it'd be far more interesting and effective knowledge showoff to cite langs that are not so-called fuck of the turing complete. the rest of you message went on stupidly on the turing complete point of view on language's power, mixed with lisp fanaticism, and personal gribes about merits and applicability assembly vs higher level langs. It's fine to go on with your gribes, but be careful in using me as a stepping stone. Xah ? http://xahlee.org/ ? From skip at pobox.com Wed Dec 17 16:01:39 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 17 Dec 2008 15:01:39 -0600 Subject: something else instead of PIL? In-Reply-To: References: Message-ID: <18761.26803.980404.494272@montanaro-dyndns-org.local> Reimar> Hi what has happened to PIL? No updates since two years. It's well-written, stable code. As far as I know it does what people want (at least it's done everything I've needed when I've used it). Why should it matter that there hasn't been an official release in two years? -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From clp at rebertia.com Thu Dec 25 19:24:12 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 25 Dec 2008 16:24:12 -0800 Subject: Exec inside a class method to call other class methods? In-Reply-To: <20081226001641.GA22946@sdf.lonestar.org> References: <4953CF57.8080905@sympatico.ca> <20081226001641.GA22946@sdf.lonestar.org> Message-ID: <47c890dc0812251624m7e1c5e55rb538996a52d56675@mail.gmail.com> On Thu, Dec 25, 2008 at 4:16 PM, J. Clifford Dyer wrote: > and so forth. Then your if/else chain can be pulled out to the place where you instantiate each field: > > if data_type=='address': > field=AddressDataField(data) > elif data_type=='due_date': > field=DueDateDataField(data) > else: > field = DataField(data) > And then you use a dictionary of data_type to class to get rid of the if-else chain altogether: type2klass = {'address' : AddressDataField, 'due_date' : DueDateDataField} #etc Klass = type2klass.get(data_type, DataField) #use DataField as fallback default field = Klass(data) Merry Christmas, Chris -- Follow the path of the Iguana... http://rebertia.com From bearophileHUGS at lycos.com Sat Dec 20 20:05:55 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 20 Dec 2008 17:05:55 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> <88a122de-14c6-4025-b36c-9a39bdd50d86@i20g2000prf.googlegroups.com> Message-ID: walterbyrd: > As I understand it, that may have been true at one time. But, Ruby 1.9 > very significantly sped up the language. While Python has been made > slower, Ruby has been made much faster. I have already answered regarding Python3 in this thread. Regarding Ruby you are right, in computer science there are lot of ways to speed up things. So it may be quite possible for Ruby to become "faster" than CPython. For example this may speed up the PythonVM some: "Optimizing direct threaded code by selective inlining": http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.8829&rep=rep1&type=pdf Bye, bearophile From castironpi at gmail.com Sun Dec 14 19:19:32 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 14 Dec 2008 16:19:32 -0800 (PST) Subject: stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <6qll2nFd5qv8U1@mid.individual.net> Message-ID: On Dec 14, 6:04?pm, greg wrote: > Lie Ryan wrote: > > "You know what you just did? You've > > just found a problem that was supposed to be an example of unsolvable > > problem." > > > It has happened before, why not again? > > There's a big difference between an unsolvable problem and an > unsolved problem. In the cases you're talking about, nobody > had solved the problem before, but neither had anybody proved > there was no solution. > > In the case at hand, there is a proof that such an algorithm > is impossible. Overturning that would require finding a > flaw in the proof, which for such a simple proof seems very > unlikely. It's more likely you'd circumvent the assumptions. That is, find an 'outside-the-box' solution. For instance, a deeply parallel architecture could escape the assumption that you can only compare two numbers at a time (per step). The proof's conclusion is still true if its assumption is. From reachrekhakn at gmail.com Fri Dec 26 08:36:15 2008 From: reachrekhakn at gmail.com (reachrekhakn at gmail.com) Date: Fri, 26 Dec 2008 05:36:15 -0800 (PST) Subject: Socket recv function taking longer time Message-ID: Hi, I have designed a recieving system in C. I have used the sockets recv function. The problem I m facing is that the sending system does not wait for the ACK(the amount of time it waits 4 the Ack is too less as the recv takes more time to read the msg), it keeps on sending the same msg again and again even before the recv func has read the whole message and my recieving system gets hanged. How do I solve this. Please Help. Thanks in Advance. From rdmurray at bitdance.com Mon Dec 15 08:13:11 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Mon, 15 Dec 2008 08:13:11 -0500 (EST) Subject: Having Issues with CMD and the 'python' command In-Reply-To: References: Message-ID: On Mon, 15 Dec 2008 at 23:01, James Mills wrote: > On Mon, Dec 15, 2008 at 10:51 PM, Lamonte Harris wrote: >> Every time I start cmd on windows it requires me to "set >> path=%path%;C:\python26" why? I'm getting annoyed... > > "cmd" has _nothing_ to do with Python. > (Top posting corrected.) But the answer is that you need to update your PATH string at the system level. You do that in Control Panel/System/Advanced/Environment variables (it's a button on the advanced screen, which is something that confused me the first time I went looking for it). ObPython: you know, it occurs to me that Windows follows exactly the opposite philosophy from Python when it comes to hierarchy. Python's Zen is "shallow is better than deep", whereas Windows' philosophy is "deep is better than shallow". Every release of Windows seems to bury the things one needs to do to administer the system deeper and deeper inside a nested set of windows...and every time I touch Windows I am reminded how sensible the Python Zen is :) --RDM From python.list at tim.thechases.com Thu Dec 4 12:02:06 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 04 Dec 2008 11:02:06 -0600 Subject: Please fix your clock [was Re: Multiple equates] In-Reply-To: <0147f4b7$0$20670$c3e8da3@news.astraweb.com> References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> <0147f4b7$0$20670$c3e8da3@news.astraweb.com> Message-ID: <49380D0E.7060309@tim.thechases.com> Steven D'Aprano wrote: > Hendrik, I think your PC's clock is wrong. You seem to be posting from > the future. further evidence of the Guido's time-machine[1]. For the secret cabal of core developers who borrow the time-machine, I recommend not sending email from within it. :) -tkc [1] http://catb.org/esr/jargon/html/G/Guido.html From rNOSPAMon at flownet.com Sun Dec 28 19:52:58 2008 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sun, 28 Dec 2008 16:52:58 -0800 Subject: Need help getting MoinMoin to run under SCGI References: Message-ID: So I have a MoinMoin installation running as a cgi and also under wsgi. Since I was on a roll I decided to press my luck and try running it under scgi. Following a suggestion in the following article: http://www.linuxjournal.com/article/9310 I wrote this little server adapter: from MoinMoin.server.server_cgi import CgiConfig, run class Config(CgiConfig): name = 'moin' import scgi import scgi.scgi_server class MoinHandler(scgi.scgi_server.SCGIHandler): def produce_cgilike(self, env, bodysize): run(Config) server = scgi.scgi_server.SCGIServer( handler_class=MoinHandler, port=4000 ) server.serve() It works -- sort of. I can fire it up and get to the login page, but it won't actually let me log in. I'm guessing this is because I haven't munged the CGI form data properly. I thought I'd ask if anyone with experience using SCGI can just tell me what I'm doing wrong before I dive into debugging this. Thanks, rg From wicijowski at gmail.com Mon Dec 29 09:59:18 2008 From: wicijowski at gmail.com (janislaw) Date: Mon, 29 Dec 2008 06:59:18 -0800 (PST) Subject: multiprocessing vs thread performance References: Message-ID: On 29 Gru, 15:52, mk wrote: > Hello everyone, > > After readinghttp://www.python.org/dev/peps/pep-0371/I was under > impression that performance of multiprocessing package is similar to > that of thread / threading. However, to familiarize myself with both > packages I wrote my own test of spawning and returning 100,000 empty > threads or processes (while maintaining at most 100 processes / threads > active at any one time), respectively. > > The results I got are very different from the benchmark quoted in PEP > 371. On twin Xeon machine the threaded version executed in 5.54 secs, > while multiprocessing version took over 222 secs to complete! > > Am I doing smth wrong in code below? Or do I have to use > multiprocessing.Pool to get any decent results? Oooh, 100000 processes! You're fortunate that your OS handled them in finite time. [quick browsing through the code] Ah, so there are 100 processes at time. 200secs still don't sound strange. JW From RBQG84 at motorola.com Mon Dec 29 04:28:47 2008 From: RBQG84 at motorola.com (Narasimhan Raghu-RBQG84) Date: Mon, 29 Dec 2008 17:28:47 +0800 Subject: Windows SSH (remote execution of commands) - Python Automation Message-ID: <7FAD6FCE52421841A11B441DEF3A88CA01F09006@ZMY16EXM70.ds.mot.com> Hi experts, I am looking for some information on how to automate remote login to a UNIX machine using ssh from a windows XP box. Possible way: 1. Use putty (or any other ssh client from windows XP). -- Can be automated with command line parameters. The problem is that I am able to login - Putty window opens up as well. But obviously I am unable to run any commands in that. I need to find something like a handle to that Putty window so that I can execute commands there. Can anyone provide me some help in achieving this ? Thanks, -- Raghu -------------- next part -------------- An HTML attachment was scrubbed... URL: From jpablo.romero at gmail.com Fri Dec 19 02:08:22 2008 From: jpablo.romero at gmail.com (=?ISO-8859-1?Q?Juan_Pablo_Romero_M=E9ndez?=) Date: Fri, 19 Dec 2008 01:08:22 -0600 Subject: eval() and global variables In-Reply-To: References: Message-ID: The hack given by Peter works fine, except in this case: >>> def aaaa(fn): ... f2 = lambda x,y:(x,y,fn(x,y)) ... function = type(f2) ... f3 = function(f2.func_code,dict()) ... print f3 ... >>> aaaa(lambda x,y:x+y) Traceback (most recent call last): File "", line 1, in File "", line 4, in aaaa TypeError: arg 5 (closure) must be tuple >>> Strange... 2008/12/17 Peter Otten <__peter__ at web.de>: > Juan Pablo Romero M?ndez wrote: > >> Suppose this function is given: >> >> def f(x,y): >> return x+y+k >> >> >> Is it possible to somehow assign a value to k without resorting to >> making k global? > > You can replace the function's global dictionary: > >>>> def f(x, y): > ... return x+y+k > ... >>>> function = type(f) >>>> function(f.func_code, dict(k=1))(2, 3) > 6 >>>> k > Traceback (most recent call last): > File "", line 1, in > NameError: name 'k' is not defined > > This is a hack, of course. > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list > From bearophileHUGS at lycos.com Wed Dec 31 03:52:40 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 31 Dec 2008 00:52:40 -0800 (PST) Subject: MemoryError when list append... plz help References: Message-ID: <84780059-0f81-453e-80a3-dc9141b69340@w1g2000prm.googlegroups.com> [BON]: > above sim is floating type. > s.append is totally coducted 60,494,500 times. > but this code raise MemoryError. > > My computer has 4G RAM. > i think it's enough. but it doesn't... Try creating it in a more clean way, here an array of doubles: >>> from array import array >>> a = array("d", [0.0]) * 60494500 This requires about 477 MB to me. Note that I have not used "append" that slows down code a lot and wastes memory, that's what I mean with "clean". If you really need the (i,j) part too (and you may not need it), then you can create two more "parallel arrays". Also a numpy array may be better for such large amount of data. Bye, bearophile From clp at rebertia.com Mon Dec 22 04:53:28 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 22 Dec 2008 01:53:28 -0800 Subject: Basic misunderstanding of generators In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF6024944BB@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF6024944BB@enbmail01.lsi.com> Message-ID: <47c890dc0812220153h2fb80c09ibed9836a9c36f489@mail.gmail.com> On Mon, Dec 22, 2008 at 1:47 AM, Barak, Ron wrote: > Hi All, > > I want to use generators to print lines taken from a gzipped file. > I've never used generators, so probably my problem is basic misunderstanding > of generators. > > In the below program, I expected the last line ("print line_") to print the > first line of the sac.log.gz file. > Instead, I get: > > > > Could you tell me what I'm doing wrong (or point me to a URL that could set > me straight) ? > > Thanks, > Ron. > > > $ cat LogManager_try.py > #!/usr/bin/env python > > import gzip > import os > > class LogStream(): > """ > """ > > def __init__(self, filename): > self.filename = filename > self.input_file = self.open_file(filename) > > def open_file(self, in_file): > """ > The gzip module checks if the input file is a gzipped file, only at > the read stage. > This is why the f.readline() is needed. > """ > try: > f = gzip.GzipFile(in_file, "r") > f.readline() > except IOError: > f = open(in_file, "r") > f.readline() > > f.seek(0) > return(f) > > def next_line(self, in_file): > """ > """ > for line_ in in_file: > yield line_.strip() > > if __name__ == "__main__": > filename = "sac.log.gz" > log_stream = LogStream(filename) generator = log_stream.next_line(log_stream.input_file) #create generator line_ = generator() #get next item from generator print line_ And as you can see, this makes next_line a bit of a misnomer. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From ndbecker2 at gmail.com Thu Dec 18 20:27:36 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 18 Dec 2008 20:27:36 -0500 Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> <6qv7kfFeuf65U1@mid.uni-berlin.de> <015ae9e9$0$20656$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > BTW Neal, your posts aren't word wrapped. When I read your posts, I get > each paragraph as one extremely LONG line scrolling way out to the side. > That's against the Internet standards for both email and Usenet, so could > you please configure your client to word-wrap at (say) 70 characters? > Sorry, it is configured to wrap @76, but it is beta software and perhaps is not working correctly? Odd, when I view my previous posts (knode/gmane) they look fine. From rileyrgdev at gmail.com Mon Dec 1 09:08:04 2008 From: rileyrgdev at gmail.com (Richard Riley) Date: Mon, 01 Dec 2008 15:08:04 +0100 Subject: pydoc enforcement. References: <6ccec696-a8bb-4818-a016-642514677b70@b38g2000prf.googlegroups.com> <6phmg0F82a0lU1@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch writes: > On Sun, 30 Nov 2008 16:27:07 -0800, ken.faulkner at gmail.com wrote: > >> Basically I'm interested adding a check to see if: >> 1) pydoc's are written for every function/method. > > Pylint warns for missing docstrings. > >> 2) There are entries for each parameter, defined by some > predetermined syntax. > > But which syntax? There are several in use out there. Even the (I > think) popular epydoc allows at least three, its own, something JavaDoc > like, and ReST. > > And I dislike forcing to document every parameter. There's lots of code > that is clear just by the names of the parameters and one or two usage > examples in the docs. Forcing to state the obvious again does not add > information for the user and is annoying for the programmer. > >> My idea is that as much as I love dynamic typing, there are times when >> using some modules/API's that have less than stellar documentation. I >> was thinking that if it was possible to enable some switch that >> basically forced compilation to fail if certain documentation criteria >> weren't met. > > But that doesn't enforce good or even real documentation either. Even > worse, you can't spot the undocumented parts of the code anymore, because > now every "docable" object has "documentation" like this just to make the > compiler happy: > > def spam(foo, bar): > """ > :param foo: a foo object. > :param bar: a bar object. > """ > > Which basically tells the same as no documentation at all. > > Ciao, > Marc 'BlackJack' Rintsch +1. Agreed 100%. There is nothing worse than auto generate "useless" documentation or over commenting of "obvious" variables/members. If anything it leads to problems later during maintenance. -- important and urgent problems of the technology of today are no longer the satisfactions of the primary needs or of archetypal wishes, but the reparation of the evils and damages by the technology of yesterday. ~Dennis Gabor, Innovations: Scientific, Technological and Social, 1970 From eckhardt at satorlaser.com Thu Dec 4 08:30:42 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 04 Dec 2008 14:30:42 +0100 Subject: sys.exit and '-i' Message-ID: <4l2l06-qoo.ln1@satorlaser.homedns.org> Hi! The unittest module will invoke sys.exit() after running the tests in order to signal success or failure. However, I sometimes don't want to exit the interpreter but instead e.g. inspect some state or just keep the window open. Normally, using '-i' as commandline argument works, but not in the case here. My questions are: 1. Is that a bug? After all, an explicit request on the commandline was ignored. Is it perhaps simply wrong how the unittest module handles error/success signalling? 2. I can catch the SystemExit exception and ignore it, but that doesn't actually help, because then I get a normal exit even in case of failures. Of course, I could pass that value to sys.exit(), but then I'd be back at the start. Any suggestions? Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From prologic at shortcircuit.net.au Thu Dec 4 06:17:34 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 4 Dec 2008 21:17:34 +1000 Subject: "as" keyword woes In-Reply-To: <10f6ca6d-35d8-45a6-9a3e-dbdd8aacdb78@d23g2000yqc.googlegroups.com> References: <7dudnSS7uIn_KarUnZ2dnUVZ_tTinZ2d@earthlink.com> <10f6ca6d-35d8-45a6-9a3e-dbdd8aacdb78@d23g2000yqc.googlegroups.com> Message-ID: On Thu, Dec 4, 2008 at 9:04 PM, Aaron Brady wrote: [... snip ...] > Does the OP hold the following should be legal? > > if if or or: > and( for ) > if not: > while( def ) I most certainly hope not! :) --JamesMills -- -- -- "Problems are solved by method" From jeff_barish at earthlink.net Sun Dec 21 19:16:41 2008 From: jeff_barish at earthlink.net (Jeffrey Barish) Date: Sun, 21 Dec 2008 17:16:41 -0700 Subject: Beep Message-ID: I use sys.stdout.write('\a') to beep. It works fine on Kubuntu, but not on two other platforms (one of which is Ubuntu). I presume that the problem is due to a system configuration issue. Can someone point me in the right direction? Thanks. -- Jeffrey Barish From bdesth.quelquechose at free.quelquepart.fr Wed Dec 10 14:23:49 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 10 Dec 2008 20:23:49 +0100 Subject: Python is slow In-Reply-To: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: <494024fc$0$7162$426a34cc@news.free.fr> cm_gui a ?crit : (snip FUD) see also: http://groups.google.com/group/comp.lang.python/browse_frm/thread/5cea684680f63c82 by the same troll^M^M^M^M^Msmart guy. From claird at lairds.us Tue Dec 2 20:23:53 2008 From: claird at lairds.us (Cameron Laird) Date: Wed, 3 Dec 2008 01:23:53 +0000 Subject: Multiple equates References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> Message-ID: <9m3h06-vhh.ln1@lairds.us> In article , Lawrence D'Oliveiro wrote: >In message , Cameron Laird wrote: > >> In article , >> Lawrence D'Oliveiro wrote: >> >>>Cameron Laird wrote: >>> >>>> I've been trying to decide if there's any sober reason to advocate >>>> the one-liner >>>> >>>> map(lambda i: a.__setitem__(i, False), [x1, x2, x3, ..., x1024]) >>> >>>Are lambdas like the Dark Side of Python? >>> >>>:) >> >> Enough so, apparently, that I'm reluctant even to touch that question. > >So how else would you express something like > > def shell_escape(Arg) : > """returns Arg suitably escaped for use as a command-line argument > to Bash.""" > return \ > re.sub \ > ( > r"[\<\>\"\'\|\&\$\#\;\(\)\[\]\{\}\`\!\~\ \\]", > lambda Match : "\\" + Match.group(0), > Arg > ) > # Need to catch anything that might be meaningful to shell > #end shell_escape > >? I suspect we're confusing each other. I *like* lambdas--at least, more than Guido does, which I recognize is a low standard. When I take your question at face value, my response is def shell_escape(Arg) : """returns Arg suitably escaped for use as a command-line argument to Bash.""" pattern = r"[\<\>\"\'\|\&\$\#\;\(\)\[\]\{\}\`\!\~\ \\]" def f1(Match): return return re.sub(pattern, f1, Arg) # Need to catch anything that might be meaningful to shell #end shell_escape 'cept that I'd hope to find a way to simplify pattern. Was that what you were asking? From rdcollum at gmail.com Sun Dec 28 15:06:25 2008 From: rdcollum at gmail.com (Roger) Date: Sun, 28 Dec 2008 12:06:25 -0800 (PST) Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <0167cbf7$0$6988$c3e8da3@news.astraweb.com> Message-ID: <676bffeb-4b07-4226-8c14-7da57d94351b@f13g2000yqj.googlegroups.com> > Curious. When I see a bare return, the first thing I think is that the > author forgot to include the return value and that it's a bug. > > The second thing I think is that maybe the function is a generator, and > so I look for a yield. If I don't see a yield, I go back to thinking > they've left out the return value, and have to spend time trying to > understand the function in order to determine whether that is the case or > not. > > In other words, even though it is perfectly valid Python, bare returns > always make the intent of the function less clear for me. I'm with Bruno > -- if you have a function with early exits, and you need to make the > intent of the function clear, explicitly return None. Otherwise, leave it > out altogether. > > -- > Steven To me this is the soundest argument. Thanks for the advice. I think I'll follow this as a rule of thumb hereafter. From hrishys at yahoo.co.uk Thu Dec 11 04:36:38 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Thu, 11 Dec 2008 09:36:38 +0000 (GMT) Subject: Equivalent of 'wget' for python? In-Reply-To: <16651e80812080954p23eb2aeaj8793be4a8d509c77@mail.gmail.com> Message-ID: <123129.76624.qm@web27402.mail.ukl.yahoo.com> Hi Please excuse my OOP but is my understanding correct urllib.urlretrieve(url_of_zip_file,destination_on_local_filesystem) is urllib --->Static Class on which the method urlretrieve method is invoked ? In that case what does the python 3.0 version mean import urllib.request urllib.request.urlretrieve(url, local_file_name) urllib -->static class request -->method urlretrieve--> what is this then ? regards Hrishy --- On Mon, 8/12/08, Jerry Hill wrote: > From: Jerry Hill > Subject: Re: Equivalent of 'wget' for python? > To: python-list at python.org > Date: Monday, 8 December, 2008, 5:54 PM > On Mon, Dec 8, 2008 at 11:53 AM, r0g > wrote: > > urllib.urlretrieve(url_of_zip_file, > destination_on_local_filesystem). > > In python 3.0, that appears to be: > > import urllib.request > urllib.request.urlretrieve(url, local_file_name) > > -- > Jerry > -- > http://mail.python.org/mailman/listinfo/python-list From sjmachin at lexicon.net Fri Dec 19 15:15:13 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 19 Dec 2008 12:15:13 -0800 (PST) Subject: PIL on 3.x? References: Message-ID: <3892784c-ddf4-4451-bcfd-dbc58b9b55f8@e1g2000pra.googlegroups.com> On Dec 20, 6:55?am, "Daniel Fetchinson" wrote: > Does anyone know if PIL will be ported to the 3.x branch? Have you considered e-mail to the author? From excord80 at gmail.com Fri Dec 19 14:52:26 2008 From: excord80 at gmail.com (excord80) Date: Fri, 19 Dec 2008 11:52:26 -0800 (PST) Subject: ANN: New Book: Programming in Python 3 References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> Message-ID: <400e99dc-90e2-441a-b7cf-5c2690915682@g38g2000yqd.googlegroups.com> On Dec 4, 2:42?pm, Alan G Isaac wrote: > Mark Summerfield wrote: > > "Programming in Python 3: > > A Complete Introduction to the Python Language" > > ISBN 0137129297 > >http://www.qtrac.eu/py3book.html > > OMG, you really wrote it in Lout? > I wish you would add to http://www.qtrac.eu/lout.html > a comment on what you get out of that > (compared to using e.g., LaTeX or > reStructuredText). I'm also curious about why you chose Lout over LaTeX or reST. From Slaunger at gmail.com Wed Dec 10 01:51:56 2008 From: Slaunger at gmail.com (Slaunger) Date: Tue, 9 Dec 2008 22:51:56 -0800 (PST) Subject: Best way to report progress at fixed intervals References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> <817384d5-5f68-4c1f-9560-0bc7b7d2b1e3@v5g2000prm.googlegroups.com> Message-ID: <6ccb77a2-a3f1-4b6b-900c-d4626be9e939@s1g2000prg.googlegroups.com> On 10 Dec., 03:44, George Sakkis wrote: > On Dec 9, 11:40?am, Slaunger wrote: > > > I would therefore like some feedback on this proposed generic "report > > progress at regular intervals" approach presented here. What could I > > do better? > > There is a pypi package that might do what you're looking for (haven't > used it though):http://pypi.python.org/pypi/progressbar/. > > HTH, > George Thank you. I will keep that in mind, if I ever get to doing GUI-based progress. -- Slaunger From python at rcn.com Fri Dec 19 06:31:07 2008 From: python at rcn.com (Raymond Hettinger) Date: Fri, 19 Dec 2008 03:31:07 -0800 (PST) Subject: Generator slower than iterator? References: Message-ID: <62013718-57e9-4690-a2be-11e63b9c135b@u18g2000pro.googlegroups.com> > FedericoMoreirawrote: > > Hi all, > > > Im parsing a 4.1GB apache log to have stats about how many times an ip > > request something from the server. > > > The first design of the algorithm was > > > for line in fileinput.input(sys.argv[1:]): > > ? ? ip = line.split()[0] > > ? ? if match_counter.has_key(ip): > > ? ? ? ? match_counter[ip] += 1 > > ? ? else: > > ? ? ? ? match_counter[ip] = 1 . . . > > Should i leave fileinput behind? Yes. fileinput is slow because it does a lot more than just read files. > > Am i using generators with the wrong aproach? No need for a generator here. The time is being lost with fileinput, split, and the counting code. Try this instead: match_counter = collections.defaultdict(int) for filename in sys.argv[1:]: for line in open(filename): ip, sep, rest = line.partition(' ') match_counter[ip] += 1 If you're on *nix, there's a fast command line approach: cut -d' ' -f1 filelist | sort | uniq -c From psaffrey at googlemail.com Thu Dec 18 06:36:06 2008 From: psaffrey at googlemail.com (psaffrey at googlemail.com) Date: Thu, 18 Dec 2008 03:36:06 -0800 (PST) Subject: Selecting a different superclass References: Message-ID: <5adf5202-d80f-4cd1-a5f2-2d1c5f47504f@e1g2000pra.googlegroups.com> On 17 Dec, 20:33, "Chris Rebert" wrote: > superclass = TraceablePointSet if tracing else PointSet > Perfect - many thanks. Good to know I'm absolved from evil, also ;) Peter From malaclypse2 at gmail.com Mon Dec 1 14:51:40 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 1 Dec 2008 14:51:40 -0500 Subject: Checking a string against multiple matches In-Reply-To: <99a3a677-a38d-40f5-9a94-a98865150b69@k19g2000yqg.googlegroups.com> References: <99a3a677-a38d-40f5-9a94-a98865150b69@k19g2000yqg.googlegroups.com> Message-ID: <16651e80812011151o1423aca5w603ed5d63c74a387@mail.gmail.com> On Mon, Dec 1, 2008 at 2:31 PM, Aaron Scott wrote: > Pseudocode: > > if "two" in ["one", "two", "three", "four"]: > return True That works, just like you wrote it: >>> "two" in ["one", "two", "three", "four"] True >>> "two" in ["one", "twofer", "three", "four"] False If that doesn't answer your question, maybe you could give some examples. -- Jerry From lie.1296 at gmail.com Mon Dec 8 02:30:52 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 8 Dec 2008 07:30:52 +0000 (UTC) Subject: Guido's new method definition idea References: <493abe2e$0$15998$426a34cc@news.free.fr> <62bcfe49-bee6-4348-8ec9-8ab85132c8ff@40g2000prx.googlegroups.com> <493bba28$0$8283$426a74cc@news.free.fr> Message-ID: On Sun, 07 Dec 2008 12:57:27 +0100, News123 wrote: > Lie wrote: >> On Dec 7, 1:02 am, News123 wrote: >>> What would be interesting would be some syntactical sugar to get rid >>> of the 'self' (at least in the code body). >>> >>> example: >>> class C: >>> class_elements a,b,c,d >>> >>> def method(self,arg): >>> global d >>> a,b,c = arg[0..3] >>> d = a + b >>> self.e = a + d >>> >>> >> Nah, that would make it not explicit. Explicit here also means that to >> refer to self's a, we need to explicitly refer to self. > > Well being explicit when trying to suggest an implicit syntax (in order > to reduce typing) is a little difficult ;-) > > Though you're right my main goal is not being implicit but would be > reducing typing and have shorter source code lines. > > If 'global '' is accepted inside a def, then moving > 'class_elements ' inside the def could be acceptable as well > though it would requiere, that this statement is repeated per def > The advantage of explicit self is to easily differentiate instance variable with local variable/names. When I need to shorten the code, I'll simply alias it to a local name, no need for syntax change or new keyword. class C(object): def __init__(self): self.a = 2 self.b = 2 self.c = 3 def x(self): #return ((-self.b + math.sqrt(self.b**2 - 4 * self.a * self.c)) / (2 * self.a)), ((-self.b - math.sqrt(self.b**2 - 4 * self.a * self.c)) / (2 * self.a)) a, b, c = self.a, self.b, self.c sq = math.sqrt return ((-b + sq(b**2 - 4*a*c)) / (2*a)), ((-b - sq(b**2 - 4*a*c)) / (2*a)) From zac256 at gmail.com Thu Dec 4 19:01:35 2008 From: zac256 at gmail.com (Zac Burns) Date: Thu, 4 Dec 2008 16:01:35 -0800 Subject: Overriding a method at the instance level on a subclass of a builtin type In-Reply-To: References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> Message-ID: <333edbe80812041601r6c1af7c4g7ae96eb7fe0a82a7@mail.gmail.com> Ok. Feature request then - assignment of a special method name to an instance raises an error. -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer (Digital Overlord) Zindagi Games On Thu, Dec 4, 2008 at 10:13 AM, George Sakkis wrote: > On Dec 4, 1:03 pm, "Zac Burns" wrote: >> Ok... but why are the special methods handled differently? > > Because otherwise they wouldn't be special ;-) And also for > performance and implementation reasons I believe. > > George > -- > http://mail.python.org/mailman/listinfo/python-list > From piyush.subscription at gmail.com Mon Dec 1 07:30:56 2008 From: piyush.subscription at gmail.com (Piyush Anonymous) Date: Mon, 1 Dec 2008 18:00:56 +0530 Subject: finding the difference between the two version of the python program... Message-ID: <19ac19520812010430s7e0e11a6sf787ca1f73e87f36@mail.gmail.com> is there a tool which, given two version of programs, finds the difference like set of classes added, deleted and modified? assuming the python program is written in oops way. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wolfgang.lipp at gmail.com Tue Dec 9 20:27:10 2008 From: wolfgang.lipp at gmail.com (_wolf) Date: Tue, 9 Dec 2008 17:27:10 -0800 (PST) Subject: forcing future re-import from with an imported module Message-ID: <533670ae-6d9d-4b10-9156-e41b31b678c7@g17g2000prg.googlegroups.com> following problem: i have a module importer_1 that first imports importer_2, then importee. importer_2 also imports importee. as we all know, follow-up imports are dealt out from the cache by python?s import mechanism, meaning the importee file gets only cached once. i can force module-level code in importee to be re-executed e.g. by deleting importee from sys.modules. but in this case, code of shich below, that does not work: if you delete importee from sys.modules *from within importee*, you get a nasty "ImportError: Loaded module importee not found in sys.modules" instead. but, the same line `import sys; del sys.modules[ 'importee' ]` does what it says on the tin. how can i say, approximately, "re-import the present module when it is imported the next time, don?t use the cache" in a simple way? i do not want to "reload" the module, that doesn?t help. greets _wolf #------------------------------------------ # importer_1.py #------------------------------------------ print 'this is importer 1' import importer_2 # import sys; del sys.modules[ 'importee' ] import importee print 'importer 1 finished' #------------------------------------------ # importer_2.py #------------------------------------------ print 'this is importer 2' import importee print 'importer 2 finished' #------------------------------------------ # importee.py #------------------------------------------ print 'this is importee' import sys; del sys.modules[ 'importee' ] print 'importee finished' #------------------------------------------ # Output #------------------------------------------ this is importer 1 this is importer 2 this is importee importee finished Traceback (most recent call last): File "C:\temp\active_imports\importer_1.py", line 2, in import importer_2 File "C:\temp\active_imports\importer_2.py", line 2, in import importee ImportError: Loaded module importee not found in sys.modules From ncoghlan at gmail.com Sat Dec 6 20:27:56 2008 From: ncoghlan at gmail.com (Nick Coghlan) Date: Sun, 07 Dec 2008 11:27:56 +1000 Subject: [Python-Dev] "as" keyword woes In-Reply-To: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> Message-ID: <493B269C.9020303@gmail.com> Warren DeLano wrote: > In other words we have lost the ability to refer to "as" as the > generalized OOP-compliant/syntax-independent method name for casting: Other possible spellings: # Use the normal Python idiom for avoiding keyword clashes # and append a trailing underscore new_object = old_object.as_(class_hint) float_obj = int_obj.as_("float") float_obj = int_obj.as_(float_class) # Use a different word (such as, oh, "cast" perhaps?) new_object = old_object.cast(class_hint) float_obj = int_obj.cast("float") float_obj = int_obj.cast(float_class) You could make a PEP if you really wanted to, but it's going to be rejected. Cheers, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia --------------------------------------------------------------- From paul at boddie.org.uk Sun Dec 14 18:32:42 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 14 Dec 2008 15:32:42 -0800 (PST) Subject: Python 3.0 crashes displaying Unicode at interactive prompt References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> <49443531.5050304@v.loewis.de> <49448FC2.6030306@v.loewis.de> <494576DD.1050505@v.loewis.de> Message-ID: <89022013-f7f6-4779-849f-b36fe618104e@r15g2000prh.googlegroups.com> On 14 Des, 22:13, "Martin v. L?wis" wrote: > > But shouldn't the production of an object's representation via repr be > > a "safe" operation? > > It's a trade-off. It should also be legible. Right. I can understand that unlike Python 2.x, a representation of a string in Python 3.x (whose equivalent in Python 2.x would be a Unicode object) must also be a string (as opposed to a byte string in Python 2.x), and that no decision can be taken to choose "safe" representations for characters which cannot be displayed in a terminal. In examples, for Python 2.x... >>> u"???" u'\xe6\xf8\xe5' >>> repr(u"???") "u'\\xe6\\xf8\\xe5'" ...and for Python 3.x... >>> "???" '???' >>> repr("???") "'???'" ...with an ISO-8859-15 terminal. Python 2.x could conceivably be smarter about encoding representations, but chooses not to be since the smarter behaviour would need to involve knowing that an "output situation" was imminent. Python 3.x, on the other hand, leaves issues of encoding to the generic I/O pipeline, causing the described problem. Of course, repr will always work if its output does not get sent to sys.stdout or an insufficiently capable output stream, but I suppose usage of repr for debugging purposes, where one may wish to inspect character values, must be superseded by usage of the ascii function, as you point out. It's unfortunate that the default behaviour isn't optimal at the interactive prompt for some configurations, though. Paul From prologic at shortcircuit.net.au Wed Dec 31 01:23:49 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 16:23:49 +1000 Subject: MemoryError when list append... plz help In-Reply-To: References: <21227745.post@talk.nabble.com> Message-ID: On Wed, Dec 31, 2008 at 4:17 PM, James Mills wrote: > I have no idea how many bytes of memory > storing each element of a list consumes > let alone each float object, but I assure you > it's not going to be anywhere near that of > 60494500 4-bytes spaces (do floats in C > normally consume 4 bytes) in C. Just creating a list of this many elements consumes 60% of my desktops RAM. YOu _SHOLD NOT_ be doing this. >>> L = list(xrange(N)) >>> len(L) 60494500 >>> L[10000] 10000 ps stats: 32351 jmills 20 0 962m 610m 1356 S 0.0 60.6 0:03.36 python It takes several seconds to create this list and several minutes for the Python interpreter to shutdown and deallocate all the memory. --JamesMills From kkylheku at gmail.com Mon Dec 8 23:36:28 2008 From: kkylheku at gmail.com (Kaz Kylheku) Date: Tue, 9 Dec 2008 04:36:28 +0000 (UTC) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> <0201522a-b15a-4401-a208-5d9af70bdd74@w24g2000prd.googlegroups.com> <8947211d-2ee8-403a-8c8a-c7599aea5f80@k24g2000pri.googlegroups.com> Message-ID: <20081224103256.892@gmail.com> On 2008-12-08, Xah Lee wrote: > So, pay me $300 as consulting fee. If the result does not comply to > the above spec, money back guaranteed. *LOL* Did you just offer someone the exciting wager of ``your money back or nothing? No matter what probability we assign to the outcomes, the /upper bound/ on the expected income from the bet is at most zero dollars. Now that's not so bad. Casino games and lotteries have that property too; the net gain is negative. But your game has no variability to suck someone in; the /maximum/ income from any trial is that you break even, which is considered winning. If you ever decide to open a casino, I suggest you stop playing with Mathematica for a while, and spend a little more time with Statistica, Probabilica, and especially Street-Smartica. :) From xahlee at gmail.com Sun Dec 7 17:53:49 2008 From: xahlee at gmail.com (Xah Lee) Date: Sun, 7 Dec 2008 14:53:49 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> For those interested in this Mathematica problem, i've now cleaned up the essay with additional comments here: ? A Mathematica Optimization Problem http://xahlee.org/UnixResource_dir/writ/Mathematica_optimization.html The result and speed up of my code can be verified by anyone who has Mathematica. Here's some additional notes i added to the above that is not previously posted. ------------------------- Advice For Mathematica Optimization Here's some advice for mathematica optimization, roughly from most important to less important: * Any experienced programer knows, that optimization at the algorithm level is far more important than at the level of code construction variation. So, make sure the algorithm used is good, as opposed to doodling with your code forms. If you can optimize your algorithm, the speed up may be a order of magnitude. (for example, various algorithm for sorting algorithms? illustrates this.) * If you are doing numerical computation, always make sure that your input and every intermediate step is using machine precision. This you do by making the numbers in your input using decimal form (e.g. use ?1.?, ?N[Pi]? instead of ?1?, ?Pi?). Otherwise Mathematica may use exact arithmetics. * For numerical computation, do not simply slap ?N[]? into your code. Because the intermediate computation may still be done using exact arithmetic or symbolic computation. * Make sure your core loop, where your calculation is repeated and takes most of the time spent, is compiled, by using Compile. * When optimizing speed, try to avoid pattern matching. If your function is ?f[x_]:= ...?, try to change it to the form of ?f=Function [x,...]? instead. * Do not use complicated patterns if not necessary. For example, use ?f[x_,y_]? instead of ?f[x_][y_]?. ------------------------------ ... Besides the above basic things, there are several aspects that his code can improve in speed. For example, he used rather complicated pattern matching to do intensive numerical computation part. Namely: Intersect[o_, d_][{lambda_, n_}, Bound[c_, r_, s_]] Intersect[o_, d_][{lambda_, n_}, Sphere[c_, r_]] Note that the way the parameters of Intersect defined above is a nested form. The code would be much faster if you just change the forms to: Intersect[o_, d_, {lambda_, n_}, Bound[c_, r_, s_]] Intersect[o_, d_, {lambda_, n_}, Sphere[c_, r_]] or even just this: Intersect[o_, d_, lambda_, n_, c_, r_, s_] Intersect[o_, d_, lambda_, n_, c_, r_] Also, note that the Intersect is recursive. Namely, the Intersect calls itself. Which form is invoked depends on the pattern matching of the parameters. However, not only that, inside one of the Intersect it uses Fold to nest itself. So, there are 2 recursive calls going on in Intersect. Reducing this recursion to a simple one would speed up the code possibly by a order of magnitude. Further, if Intersect is made to take a flat sequence of argument as in ?Intersect[o_, d_, lambda_, n_, c_, r_, s_]?, then pattern matching can be avoided by making it into a pure function ?Function?. And when it is a ?Function?, then Intersect or part of it may be compiled with Compile. When the code is compiled, the speed should be a order of magnitude faster. ----------------------------- Someone keeps claiming that Mathematica code is some ?5 order of magnitude slower?. It is funny how the order of magnitude is quantified. I'm not sure there's a standard interpretation other than hyperbole. There's a famous quote by Alan Perlis ( http://en.wikipedia.org/wiki/Alan_Perlis ) that goes: ?A Lisp programmer knows the value of everything, but the cost of nothing.? this quote captures the nature of lisp in comparison to most other langs at the time the quote is written. Lisp is a functional lang, and in functional langs, the concept of values is critical, because any lisp program is either a function definition or expression. Function and expression act on values and return values. The values along with definitions determines the program behavior. ?the cost of nothing? captures the sense that in high level langs, esp dynamic langs like lisp, it's easy to do something, but it is more difficult to know the algorithmic behavior of constructs. This is in contrast to langs like C, Pascal, or modern lang like Java, where almost anything you write in it is ?fast?, simply forced by the low level nature of the lang. In a similar way, Mathematica is far more higher level than any existing lang, counting other so-called computer algebra systems. A simple one-liner Mathematica construct easily equates to 10 or hundred lines of lisp, perl, python, and if you count its hundreds of mathematical functions such as Solve, Derivative, Integrate, each line of code is equivalent to a few thousands lines in other langs. However, there is a catch, that applies to any higher level langs, namely, it is extremely easy, to create a program that are very inefficient. This can typically be observed in student or beginner's code in lisp. The code may produce the right output, but may be extremely inefficient for lacking expertise with the language. The phenomenon of creating code that are inefficient is proportional to the highlevelness or power of the lang. In general, the higher level of the lang, the less possible it is actually to produce a code that is as efficient as a lower level lang. For example, the level or power of lang can be roughly order as this: assembly langs C, pascal C++, java, c# unix shells perl, python, ruby, php lisp Mathematica the lower level the lang, the longer it consumes programer's time, but faster the code runs. Higher level langs may or may not be crafted to be as efficient. For example, code written in the level of langs such as perl, python, ruby, will never run as fast as C, regardless what expert a perler is. C code will never run as fast as assembler langs. And if the task crafting a raytracing software, then perl, python, ruby, lisp, Mathematica, are simply not suitable, and are not likely to produce any code as fast as C or Java. On the other hand, higher level langs in many applications simply cannot be done with lower level lang for various practical reasons. For example, you can use Mathematica to solve some physics problem in few hours, or give Pi to gazillion digits in few seconds with just ?N [Pi,10000000000000]?. Sure, you can code a solution in lisp, perl, or even C, but that means few years of man hours. Similarly, you can do text processing in C, Java, but perl, python, ruby, php, emacs lisp, Mathematica, can reduce your man hours to 10% or 1% of coding effort. In the above, i left out functional langs that are roughly statically typed and compiled, such as Haskell, OCaml, etc. I do not have experience with these langs. I suppose they do maitain some advantage of low level lang's speed, yet has high level constructs. Thus, for computationally intensive tasks such as writing a raytracer, they may compete with C, Java in speed, yet easier to write with fewer lines of code. personally, i've made some effort to study Haskell but never went thru it. In my experience, i find langs that are (roughly called) strongly typed, difficult to learn and use. (i have reading knowledge of C and working knowledge of Java, but am never good with Java. The verbosity in Java turns me off thoroughly.) ----------------- as to how fast Mathematica can be in the raytracing toy code shown in this thread, i've given sufficient demonstration that it can be speed up significantly. Even Mathematica is not suitable for this task, but i'm pretty sure can make the code's speed in the some level of speed as OCaml. (as opposed to someone's claim that it must be some 700000 times slower or some ?5 orders of magnituted slower?). However, to do so will take me half a day or a day of coding. Come fly $300 to my paypal account, then we'll talk. Money back guaranteed, as i said before. Xah ? http://xahlee.org/ ? From gagsl-py2 at yahoo.com.ar Tue Dec 16 11:59:36 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Dec 2008 14:59:36 -0200 Subject: zipfile.is_zipfile() and string buffers References: <79196ccb-11fb-4a2d-9c2c-79801f108a05@f40g2000pri.googlegroups.com> Message-ID: En Tue, 16 Dec 2008 12:28:00 -0200, Brendan escribi?: > I would like zipfile.is_zipfile(), to operate on a cStringIO.StringIO > string buffer, but is seems only to accept file names as arguments. > Should it not be able to handle string buffers too? A version of zipfile.is_zipfile() accepting both file names and file objects: def _check_zipfile(fp): try: if _EndRecData(fp): return True # file has correct magic number except IOError: pass return False def is_zipfile(filename): """Quickly see if file is a ZIP file by checking the magic number.""" result = False try: if hasattr(filename, "read"): result = _check_zipfile(fp=filename) else: with open(filename, "rb") as fp: result = _check_zipfile(fp) except IOError: pass return result -- Gabriel Genellina From jon at ffconsultancy.com Wed Dec 10 18:02:08 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Wed, 10 Dec 2008 23:02:08 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <20081226055859.604@gmail.com> Message-ID: Xah Lee wrote: > Kaz Kylheku wrote: >> Really? ``50 or hundreds'' of lines in C? >> >> #include /* for sqrt */ >> >> void normalize(double *out, double *in) >> { >> double denom = sqrt(in[0] * in[0] + in[1] * in[1] + in[2] * >> in[2]); >> >> out[0] = in[0]/denom; >> out[1] = in[1]/denom; >> out[2] = in[2]/denom; >> } >> >> Doh? > > Kaz, pay attention: > > Xah wrote: ?Note, that the ?norm? as defined above works for vectors > of any dimention, i.e. list of any length.? That is still only 6 lines of C code and not 50 as you claimed: double il = 0.0; for (int i=0; i Message-ID: <20081231153100.20272.1701611299.divmod.quotient.29806@ohm> On Wed, 31 Dec 2008 15:48:50 +0100, Francesco Bochicchio wrote: >< ... > >>>Uhm. In my experience, with TCP protocol recv only returned less than >>>the required bytes if the remote end disconnects. I always check the >> >>What if the sending end actually sent less than you asked for ? >> >>-srp > >In blocking mode and with TCP protocol, the recv waits until more bytes are >received - mixing up the next message with the previous one and then >loosing the 'sync' and being unable to interpretate the received data - or >the remote end disconnects. Nope, this isn't how TCP works, whether your sockets are blocking or non- blocking. It's easy to see this: >>> s = socket.socket() >>> s.connect(('www.google.com', 80)) >>> s.sendall('GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: keep-alive\r\n\r\n') >>> len(s.recv(1024 * 1024)) 6191 >>> s.sendall('GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: keep-alive\r\n\r\n') >>> len(s.recv(1024 * 1024)) 6191 >>> s.sendall('GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: keep-alive\r\n\r\n') >>> len(s.recv(1024 * 1024)) 6191 >>> s.sendall('GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: keep-alive\r\n\r\n') >>> len(s.recv(1024 * 1024)) 6191 >>> Numerous blocking recv calls which returned fewer bytes than asked for without the connection having been closed. The only guarantee you get with a blocking socket is that the recv will return at least one byte and at most the number of bytes you asked for (or raise an exception instead). On a LAN, it's likely that you'll generally get the exact number of bytes which the sender passed to one call of send (until the sender starts to pass really huge strings to send, then it'll get split up) just because the network has lots of capacity compared to the traffic you're putting on it. However, even on a LAN it's not guaranteed, and on the internet, it's extremely likely that this won't happen most of the time. Jean-Paul From ross.jett at gmail.com Mon Dec 29 20:00:31 2008 From: ross.jett at gmail.com (Ross) Date: Mon, 29 Dec 2008 17:00:31 -0800 (PST) Subject: get method Message-ID: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> I am teaching myself Python by going through Allen Downing's "Think Python." I have come across what should be a simple exercise, but I am not getting the correct answer. Here's the exercise: Given: def histogram(s): d = dict() for c in s: if c not in d: d[c] = 1 else: d[c] += 1 return d Dictionaries have a method called get that takes a key and a default value. If the key appears in the dictionary, get returns the corresponding value; otherwise it returns the default value. For example: >>> h = histogram('a') >>> print h {'a': 1} >>> h.get('a', 0) 1 >>> h.get('b', 0) 0 Use get to write histogram more concisely. You should be able to eliminate the if statement. Here's my code: def histogram(s): d = dict() for c in s: d[c]= d.get(c,0) return d This code returns a dictionary of all the letters to any string s I give it but each corresponding value is incorrectly the default of 0. What am I doing wrong? From steven at REMOVE.THIS.cybersource.com.au Mon Dec 22 20:34:24 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 23 Dec 2008 01:34:24 GMT Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> Message-ID: On Mon, 22 Dec 2008 10:01:21 -0800, r wrote: > Walter, > I just look at the stats for comp.lang.python, and i am 9th place for > most post this month. And about 9,000th place for useful information. -- Steven From sjmachin at lexicon.net Wed Dec 17 07:44:11 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 17 Dec 2008 04:44:11 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> Message-ID: <0d9ea7cc-b5fb-4edb-be32-490aae9e7204@b41g2000pra.googlegroups.com> On Dec 17, 9:39?pm, aka wrote: > Due to being in a hurry I didn't paste correctly (sorry). > > The intention is to put values of column 1 ("id") in the roles list, > therefore appending within the loop, to fill a session var. > > The complete code is: It's *not* complete. It's missing "import csv". > > roles = [] > inp = 'C:/temp/test.csv' > try: > ? ? fp = open(inp, 'rb') > ? ? reader = csv.reader(fp, dialect='excel', delimiter=';') > ? ? for r in reader: > ? ? ? ? roles.append(r) > ? ? ? ? ## ultimately should be something like r.id or r[0] > ? ? ? ? ## first row of csv file should be skipped because of column > names > > except: > ? ? msg = 'Something's wrong with the csv.reader' But you don't print the message! In any case, using the try/except like that *hides* any useful diagnostic information; it gives only an indication that something is wrong, but not what is wrong and where it is wrong. If you throw away the try/except, you will get a more meaningful message -- possibly that "csv" is not defined!! -- and the traceback will tell you in which line the error occured. > return dict(file=inp,roles=str(roles)) Why do you think that you need (a) that complicated expression (b) the str() call? Assuming you are intending to make a function out of all that, what's wrong with returning a (simple) tuple: return inp, roles ? The above 'return' statement is not inside a function/method. You would have got this message: SyntaxError: 'return' outside function People will very soon lose patience with you if you persist in not posting the actual code that you ran. > The roles list isn't populated at all :( This could mean (if the code that was posted is moderately similar to that which was run) that the error happened before the first time that roles.append(r) was executed ;-) Please divulge the contents of test.csv -- but not if it's huge! Considering trying to get your code to work first with a data file of close-to-minimal size and complexity, like this: 8<--- id,other_info tom,1 dick,2 harry,3 8<--- By the way, you mentioned the UnicodeReader class in your original post, but you don't seem to use it ... From martin.hellwig at dcuktec.org Wed Dec 3 19:55:59 2008 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Thu, 04 Dec 2008 00:55:59 +0000 Subject: "as" keyword woes In-Reply-To: <01470229$0$20670$c3e8da3@news.astraweb.com> References: <493701f0$0$194$e4fe514c@news.xs4all.nl> <01470229$0$20670$c3e8da3@news.astraweb.com> Message-ID: <49372a9f$0$194$e4fe514c@news.xs4all.nl> Steven D'Aprano wrote: > On Wed, 03 Dec 2008 22:02:24 +0000, Martin P. Hellwig wrote: > >> Warren DeLano wrote: >>> A bottom line / pragmatic question... hopefully not a FAQ. >>> >>> Why was it necessary to make "as" a reserved keyword? >> >> Because it can be used at the import statement to let the imported thing >> be known under another name? >> Something like: >> >> >>> import xml.etree.ElementTree as ET > > Martin, that doesn't answer the OP's question *at all*. Python 2.5 uses > "as" in that way, and it is not a keyword. > Yes Steven, I realized after the apple fell on my head that I was barking at the wrong tree, in a totally different forest, sorry for the noise. -- mph From peke at iki.fi Sat Dec 6 14:40:48 2008 From: peke at iki.fi (=?ISO-8859-1?Q?Pekka_Kl=E4rck?=) Date: Sat, 6 Dec 2008 21:40:48 +0200 Subject: python book for non technical absolute beginner In-Reply-To: <493a7c6a$0$973$426a34cc@news.free.fr> References: <493a7c6a$0$973$426a34cc@news.free.fr> Message-ID: <7dedbb6d0812061140k25b03edcw84f24e9f070b7951@mail.gmail.com> 2008/12/6 News123 : > No my question does anybody know a nice beginners book (or a learning CD > or on line tutorial)? Ideally it shouldn't be too serious and have a lot > of small nice mini-examples How to Think Like a Computer Scientist - Learning with Python is a good book for beginners and it is available for free under the GNU license. http://www.greenteapress.com/thinkpython/thinkCSpy/ Cheers, .peke From python at bdurham.com Tue Dec 2 23:26:54 2008 From: python at bdurham.com (python at bdurham.com) Date: Tue, 02 Dec 2008 23:26:54 -0500 Subject: Determining number of dict key collisions in a dictionary In-Reply-To: <4935FD01.1000308@rogerbinns.com> References: <1228221594.807.1287801527@webmail.messagingengine.com> <1228271002.8425.1287938717@webmail.messagingengine.com> <4935FD01.1000308@rogerbinns.com> Message-ID: <1228278414.30562.1287962691@webmail.messagingengine.com> Roger, Apologies for responding directly to your email vs. the list (just realized this now). Thank you very much for your detailed answers and the reminder about premature optimization. You have answered all my questions. Regards, Malcolm ----- Original message ----- From: "Roger Binns" To: python at bdurham.com Date: Tue, 02 Dec 2008 19:29:05 -0800 Subject: Re: Determining number of dict key collisions in a dictionary -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 python at bdurham.com wrote: > Any ideas on why the Windows 64-bit version of Python has 32-bit vs. > 64-bit longs? (Is this the case for both the 2.6 and 3.0 64-bit versions > of Python for Windows?) It is part of the ABI for the platform. http://www.unix.org/version2/whatsnew/lp64_wp.html http://en.wikipedia.org/wiki/64-bit#64-bit_data_models http://blogs.msdn.com/oldnewthing/archive/2005/01/31/363790.aspx > If this is the case, then it sounds like Linux/Unix are much better > Python hosts than Windows when it comes to developing 64-bit Python > applications - especially when it comes to working with large > dictionaries (you point about hash collisions not withstanding)? Python uses a type Py_ssize_t which is typedef'ed to 64 bits on a 64 bit platform and 32 bits on a 32 bit platform for things like sizes (eg length of strings, number of items in a container) so there won't be any programmatic or correctness issues. You never said what your idea of large was in the original posting. For example you really only need to start worrying about hash collisions on LP64 if you have more than 4 billion items. Even then things will still work. For people who have really large data sets, it is usually beneficial to write their own custom code often resorting to assembly. This is because the data set is so much larger than caches and saving even a few instructions per item pays back due to how many there are. My advice would be to not worry about collisions, premature optimization etc initially. Get the code working and get it working right. Then do profiling and improve algorithms. You will have test code from earlier so you can verify that the optimizations are correctly. Finally you may have to rewrite core parts in assembly. but again the tests will be there to help. Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAkk1/P4ACgkQmOOfHg372QQdkACg3n0CrXCbctfyKOw3DQ0uTvvt J60AoMyikF/oJUXVrV9XOkQe6eprzPSh =9CYk -----END PGP SIGNATURE----- From beautifu_girl_1418 at hotmail.com Mon Dec 15 06:21:20 2008 From: beautifu_girl_1418 at hotmail.com (=?windows-1256?B?yOTKIMfh09rmz+3l?=) Date: Mon, 15 Dec 2008 03:21:20 -0800 (PST) Subject: =?windows-1256?B?3+3dIMrO3e0g0d7j3yDa5CDH4dDtIMrK1eEgyOU=?= Message-ID: ?? ??: ????? ???? ??? ??? ?? ???? ?? ???????? (?? ??? ??? ????) ????? ??????: ???? ????? ???? ???? ?? ??????? ====> TRA ZDOD ???? ??? ????? ??????? ??????? ????? (77127 )????? ??? ????? ??? ??????? ????? (95312) ????? ??? ????? ?????? ??? ????? (95206) ????? ????? (1081) ???????? ????? (6752) ????? ??? ????? ??????? ???????? ????? (85234) ????? ??? ????? ????????? ???????? ?????? ????? (1489) ??? ????? (2921) ???????? ???????? (2252) ?? ?????? ???????? ????? ??? (2420) ?? ?? From clp at rebertia.com Sun Dec 7 23:45:19 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 7 Dec 2008 20:45:19 -0800 Subject: infering the number of args a function takes at runtime In-Reply-To: References: Message-ID: <47c890dc0812072045g3b9d17c8r5768028afd22262d@mail.gmail.com> On Sun, Dec 7, 2008 at 8:39 PM, sniffer wrote: > hi all, > i am a python newbie, in a project currently doing i need to find out > the number of arguments that a function takes at runtime.? Is this > possible ,if so how do i do this,i ve looked through the python > documentation but couldnt find anything.any help will be great You want inspect.getargspec() or one of its friends in the `inspect` module. See http://docs.python.org/library/inspect.html#inspect.getargspec Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com I really should get back to studying now > > > TIA > -- > http://mail.python.org/mailman/listinfo/python-list > From geekmail at usenot.de Fri Dec 5 10:17:25 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Fri, 5 Dec 2008 16:17:25 +0100 Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> Message-ID: <20081205161725.3f35222b@usenot.de> On Thu, 4 Dec 2008 15:49:46 -0600 skip at pobox.com wrote: > > Andreas> Whenever has it been a pythonic ideal to "not allow" > Andreas> stuff? You get warnings. Everything else is up to you. > > It's more than warnings. With properly crafted combinations of > spaces and tabs you can get code which looks like it has a certain > indentation to the human observer but which looks like it has > different indentation (and thus different semantics) to the byte code > compiler. There is often no warning. > I just looked at "python --help", it seems that there is no warning per default. My point is: If you mix tabs and spaces in a way that breaks code, you'll find out pretty easily, because your program will not work. It's your choice, and I think it's pretty nice that Python lets you choose. After all, some people are of the "indentation for structure, spaces for alignment" faction. Why make their life harder? /W -- My real email address is constructed by swapping the domain with the recipient (local part). From bignose+hates-spam at benfinney.id.au Thu Dec 4 00:07:39 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 04 Dec 2008 16:07:39 +1100 Subject: RELEASED Python 3.0 final References: <1b9568f2-55a0-4f1e-886c-2675b16b58c9@g38g2000yqn.googlegroups.com> Message-ID: <87k5agv884.fsf@benfinney.id.au> Carl Banks writes: > On Dec 3, 7:51?pm, Barry Warsaw wrote: > > On behalf of the Python development team and the Python community, > > I am happy to announce the release of Python 3.0 final. > > Congratulations! This is a great day for the Python community. I'm rather disappointed that crucial information was not given in this announcement: Where is the release party? The public needs to know! :-) Congratulations, and thanks to the entire Python team. -- \ ?I used to work in a fire hydrant factory. You couldn't park | `\ anywhere near the place.? ?Steven Wright | _o__) | Ben Finney From steve at holdenweb.com Tue Dec 23 09:21:13 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 23 Dec 2008 09:21:13 -0500 Subject: pseudo terminal usage from Python? In-Reply-To: <18768.60036.20440.46074@montanaro-dyndns-org.local> References: <18768.60036.20440.46074@montanaro-dyndns-org.local> Message-ID: skip at pobox.com wrote: > I ran into an interesting problem yesterday. The mpstat(1) command on > Solaris formats its output like so: > > CPU minf mjf xcal intr ithr csw icsw migr smtx srw syscl usr sys wt idl > 0 42 1 1184 812 265 227 12 44 37 0 1131 6 2 0 93 > 1 25 1 933 447 2 203 37 75 12 0 902 5 4 0 91 > 2 17 0 195 495 1 201 41 77 13 0 514 5 1 0 94 > 3 4 0 117 882 405 171 34 65 21 0 449 5 2 0 93 > > I'm only interested in presenting the CPU numbers and user+sys values > prefixed by a timestamp. For example, the above might be formatted like so: > > 07:28:46.373328 0 8 1 9 2 6 3 7 > > The obvious solution might be something simple like this: > > mpstat 1 | python mympstat.py > > where mympstat.py does a trival amount of reformatting. > > The problem is that mpstat recognizes when its output is a pipe and block > buffers it so the Python script sees input in massive blobs, not the > second-by-second output you'd see running "mpstat 1" by itself. I've been > reduced to a much more complicated solution which involves forking mpstat > with output to a file, then reading the end of that file every second. A > three-line Python script balloons into a one-page script. Yuck. Add to > that I'm writing this for an admin who is considering Python as a scripting > language. Double Yuck. (But not nyuk nyuk, this is not the Stooges.) > > I suspect there is some magic I can perform with pseudo terminals (this is > on Solaris 10.) The documentation for the pty module contains no examples > and I've been so far unable to find any using Google. > > Any pointers/examples? I will gladly add an example to the pty module docs > (I have the power!) once I have a couple working examples (maybe one example > each of reading and writing?) > Look at the pexpect module - you can run interactive tasks through that. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steve at REMOVE-THIS-cybersource.com.au Sat Dec 20 20:38:35 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Dec 2008 01:38:35 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> Message-ID: <015d9566$0$20656$c3e8da3@news.astraweb.com> On Sat, 20 Dec 2008 16:20:38 -0800, r wrote: > On Dec 20, 6:05?pm, Roy Smith wrote: >> I had an interesting experience with this recently. ?I was giving a >> co-worker quick python into. ?He's an experienced programer in various >> languages, but this was his first exposure to python. >> >> He got really hung up on the % syntax. ?By (bad) luck, he was trying to >> print a tuple (let's call it "t"), did >> >> format % t >> >> and was surprised at the result. ?It set him off on a "but that's >> stupid, blah, blah, blah" rant. ?I haven't absorbed the new syntax well >> enough to figure out if people will get hung up by this with the new >> syntax. > > It is stupid, more reason to fix the current problem instead creating a > whole new one. Instead of just whinging, how about making a suggestion to fix it? Go on, sit down for an hour or ten and try to work out how a BINARY OPERATOR like % (that means it can only take TWO arguments) can deal with an arbitrary number of arguments, *without* having any special cases. Go on. Take your time. I'll be waiting. > One more big complaint "THE BACKSLASH PLAGUE". ever tried regexp?, or > file paths?. All because that little backslash char is a line > continuation character, maybe we should fix that. This makes no sense whatsoever. How does the line continuation character make any difference to backslashes inside a regex or a file path? Again, instead of whinging, what's your suggestion to fix it? Another suggestion, because your first: > Would your life end if '\' was not a continuation char? is just stupid. The line continuation character is *irrelevant* to the problem of backslashes inside strings. For all the use it is, you might as well suggest changing the name None to Null. -- Steven From gregturn at mindspring.com Tue Dec 9 14:06:24 2008 From: gregturn at mindspring.com (Goldfish) Date: Tue, 9 Dec 2008 11:06:24 -0800 (PST) Subject: Spring Python 0 .9.1 has been released Message-ID: I just released Spring Python 0.9.1. One of our users spotted an error in the IoC container involving constructor arguments, and I was able to reproduce the problem, patch it, and get it released quickly to the user community. You can download it right now. Links: * For more information, please visit the website at http://springpython.webfactional.com. * To download the 0.9.1 release, or an archived release, and for access to sample applications use http://www.springsource.com/download/community?project=Spring%20Extensions I cannot emphasize enough how valuable community feedback is to the success of this project. If you are having issues, please post an email to the list, or start a thread at the community forum, and we will examine the situation. Also note, the web site has been updated, which includes a link to API documentation, generated by pydoc. ============================== Release Notes - Spring Python - Version 0.9.1

Bug

  • [SESPRINGPYTHONPY-86] - XMLConfig doesn't properly lookup constructor-arg's, but instead returns ReferenceDef objects
=============================== Key Features of Spring Python include: * Inversion Of Control - The idea is to decouple two classes at the interface level. This lets you build many reusable parts in your software, and your whole application becomes more pluggable. You can use either the XmlApplicationContext or the DecoratorBasedApplicationContext. * Aspect-oriented Programming - Spring Python provides great ways to wrap advice around objects. It is utilized for remoting. Another use is for debug tracers and performance tracing. * DatabaseTemplate - Reading from the database requires a monotonous cycle of opening cursors, reading rows, and closing cursors, along with exception handlers. With this template class, all you need is the SQL query and row-handling function. Spring Python does the rest. * Database Transactions - Wrapping multiple database calls with transactions can make your code hard to read. This module provides multiple ways to define transactions without making things complicated. * Security - Plugin security interceptors to lock down access to your methods, utilizing both authentication and domain authorization. * Remoting - It is easy to convert your local application into a distributed one. If you have already built your client and server pieces using the IoC container, then going from local to distributed is just a configuration change. * Samples - to help demonstrate various features of Spring Python, some sample applications have been created: o PetClinic - Everybody's favorite Spring sample application has been rebuilt from the ground up using various web containers including: CherryPy. Go check it out for an example of how to use this framework. o Spring Wiki - Wikis are powerful ways to store and manage content, so we created a simple one as a demo! o Spring Bot - Use Spring Python to build a tiny bot to manage the IRC channel of your open source project. From davidandjoni123 at att.net Sun Dec 7 21:03:18 2008 From: davidandjoni123 at att.net (David and Joni) Date: Sun, 7 Dec 2008 18:03:18 -0800 (PST) Subject: The story of Christmas. Message-ID: Receive the TRUE story of Christmas via e mail, just click on the link. Thank you !! http://app.formassembly.com/forms/view/56128 From MM456Z at yahoo.com Wed Dec 3 05:16:20 2008 From: MM456Z at yahoo.com (MM456Z at yahoo.com) Date: Wed, 3 Dec 2008 02:16:20 -0800 (PST) Subject: Obama's Birth Certificate - Demand that US presidential electors investigate Obama's eligibility References: <89pZk.9151$be.4743@nlpi061.nbdc.sbc.com> Message-ID: On Dec 3, 12:53?am, Bryan Olson wrote: > girbarob... at yahoo.com wrote: > > This message is not about the meaningless computer printout called > > More importantly, it's not about Python. I'm setting follow-ups to > talk.politics. > > > "Certification of Live Birth" that Obama propaganda machine calls his > > "Birth Certificate". The American people are still waiting for a copy > > of Obama's original birth certificate that includes all his birth > > information. > > The document is what Hawaii provides as certified copy of birth record. > It contains all the information the federal government requires to prove > citizenship by birth, and it shows that Barack Hussein Obama was born 04 > August 1961 in Honolulu. See: > > ? ?http://www.factcheck.org/elections-2008/born_in_the_usa.html > This garbage on factcheck.org is a worthless piece of paper insufficient to prove a US citizenship much less a natural born one. You need to have a long version of legitimate birth certificate that includes all birth information. Hawaii officials never even confirmed this piece of garbage on factcheck.org > > Remind your US presidential electors of their constitutional duty to > > investigate Obama's natural-born citizen status. > > > No federal agency like FBI or Secret Service, no Hawaii bureaucrats > > have ever investigated Obama's birth in Hawaii. Many illegal aliens in > > USA have official "birth certificates" issued by state bureaucrats on > > the basis of falsified birth records. > > Janice Okubo of Hawaii's Department of Health confirmed that the state > has Obama?s original birth certificate on record: > > ? ?http://hawaii.gov/health/about/pr/2008/08-93.pdf > > [...] Do you have a sufficient IQ to actually grasp what this news release says? All it says is that Hawaii has "Obama?s original birth certificate". It does not say anything whether this "Obama?s original birth certificate" is from Hawaii or Kenya or from Indonesia. Under the Hawaii laws, a parent could use an original birth certificate from another country to register a child in Hawaii and get today "Certification of Live Birth". People actually born in Hawaii do not get such "Certification of Live Birth", they get another document with different name. Considering all the public pressure on Hawaii officials to confirm Obama's birth in Hawaii, they would start any response with confirmation that Obama was born in Hawaii. Instead, they give you carefully worded garbage so that your low IQ brain can swallow it and Obama propaganda machine can beat into your worthless brain until you repeat it like a low IQ moron. > > > Remind your US presidential electors that they have the legal standing > > and constitutional duty to investigate Obama's birth in Hawaii by > > demanding that Obama provide all his original birth records, and a > > federal agency like FBI or Secret Service fully investigate them. > > That's not what the Constitution says. US Constitution, Article IV, > Section 1: "Full Faith and Credit shall be given in each State to the > public Acts, Records, and judicial Proceedings of every other State. And > the Congress may by general Laws prescribe the Manner in which such > Acts, Records and Proceedings shall be proved, and the Effect thereof." > > These haters seek to make Obama prove his records in ways others have > not had to, and beyond any manner prescribed by Congress within its > constitutional authority. > You do not have enough brain cells to understand anything you just quoted. Get one thing straight for your own self interest! THERE ARE TENS OF MILLIONS OF GUN OWNERS IN USA ONLY WAITING TO USE THEM ON ANYBODY WHO THREATENS THE US CONSTITUTION - so better use all your brain cells in your own self interest to resolve this matter now and not later. Run to Obama and beg him to release all birth records or things will not get any better. You are playing with fire. From eliben at gmail.com Tue Dec 16 01:21:43 2008 From: eliben at gmail.com (eliben) Date: Mon, 15 Dec 2008 22:21:43 -0800 (PST) Subject: parse C expression? References: Message-ID: On Dec 16, 1:48?am, Torsten Mohr wrote: > Hi, > > i found some examples when googling for the subject but nothing really > matched. > > Is there a standard module available that lets me parse a syntax like "C" > with numbers, operators, braces, variables and function calls? > > I'd like to use this to parse an own kind of configuration language > and preferred would be just standard modules. ?Is there something > available that is maybe based on shlex? > > Thanks for any hints, > Torsten. Sorry for the "shameless plug", but pycparser (http://code.google.com/ p/pycparser/) is exactly what you're looking for. It's a complete, pure-Python parser for ANSI C. Eli From castironpi at gmail.com Mon Dec 29 10:35:46 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 07:35:46 -0800 (PST) Subject: multiprocessing vs thread performance References: Message-ID: <7846b653-127c-4879-b7f7-fe5b1e591cb4@g1g2000pra.googlegroups.com> On Dec 29, 8:52?am, mk wrote: > Hello everyone, > > After readinghttp://www.python.org/dev/peps/pep-0371/I was under > impression that performance of multiprocessing package is similar to > that of thread / threading. However, to familiarize myself with both > packages I wrote my own test of spawning and returning 100,000 empty > threads or processes (while maintaining at most 100 processes / threads > active at any one time), respectively. > > The results I got are very different from the benchmark quoted in PEP > 371. On twin Xeon machine the threaded version executed in 5.54 secs, > while multiprocessing version took over 222 secs to complete! > > Am I doing smth wrong in code below? Or do I have to use > multiprocessing.Pool to get any decent results? I'm running a 1.6 GHz. I only ran 10000 empty threads and 10000 empty processes. The threads were the ones you wrote. The processes were empty executables written in a lower language, also run 100 at a time, started with 'subprocess', not 'multiprocessing'. The threads took 1.2 seconds. The processes took 24 seconds. The processes you wrote had only finished 3000 after several minutes. From v+python at g.nevcal.com Fri Dec 5 02:34:01 2008 From: v+python at g.nevcal.com (Glenn Linderman) Date: Thu, 04 Dec 2008 23:34:01 -0800 Subject: Multiple Versions of Python on Windows XP In-Reply-To: <4937DB4B.7060001@ncf.ca> References: <4934de22$0$27863$9b622d9e@news.freenet.de> <493592EE.9090005@v.loewis.de> <49378804.2050807@g.nevcal.com> <4937DB4B.7060001@ncf.ca> Message-ID: <4938D969.6060609@g.nevcal.com> On approximately 12/4/2008 5:29 AM, came the following characters from the keyboard of Colin J. Williams: > > > Glenn Linderman wrote: >> >> The equivalent of those commands is available via Windows Explorer, >> Tools / Folder Options, File Types, scroll-scroll-scroll your way to >> .py, Click Advanced, fiddle, copy paste apply, and other twaddle. > Yes, but what's needed is a further level of indirection. Currently, > this allows .py to be associated with a particular editor. It would > be great if there were some way of associating "Python.File", which is > created in the install process, with a particular editor. Then, one > is left with associating "Python.File" with a given version of > Python. Meanwhile, your suggestion provides a workaround. Sure, it is possible to simply change the Python.File ftype -- just issue the command ftype Python.File="C:\PythonNN\python.exe" "%1" %* for NN = 25, 26 or 30 or whatever. But that is longer and harder to remember and type than the assoc which is why chose to keep three ftypes around and switch between them with the assoc command. But if you put them in a batch file, or shortcut, the length and complexity wouldn't be as much of an issue. But changing one or changing the other is roughly equivalent... ftype is an extra level of indirection over assoc... and it is designed to allow programs that handle multiple extensions to not proliferate the full command for each extensions. For example, a multi-image-format image program, could use something like: assoc .jpg=ImageProg.File assoc .gif=ImageProg.File assoc .tif=ImageProg.File ftype ImageProg.file="C:\Program Files\ImageProg\ImageProg.exe" "%1" %* In that situation, because of the potentially large number of extensions, changing the assoc isn't equivalent to changing the ftype, but for Python, I'm unaware of it needing to handle multiple extensions from the command line or via double clicking in Explorer, so was exploiting the extra level of indirection to save typing, and make the command simpler to remember. Not sure what your reference to an editor is about. ftype only fiddles with the Shell Open command; if you want to do tricks with different editors for different versions of Python, then you have to fiddle the Shell Edit command; this can be done with clever manipulation of the registry... it would be straightforward to create a .reg file that swaps both the Shell Open and Shell Edit commands for different versions of Python, if that is useful... and maybe it is if you use an IDE of some sort. Since I just use emacs to edit .py files, I ignored the Shell Edit command. Instead I have a Shell Emacs command that is set up to apply to all file types, and is available via the context menu from Windows Explorer... but I use that not only for different versions of Python, but source code in other languages, and text files of all types. -- Glenn -- http://nevcal.com/ =========================== A protocol is complete when there is nothing left to remove. -- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking From luismgz at gmail.com Mon Dec 29 16:37:48 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Mon, 29 Dec 2008 13:37:48 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <59dfc7f8-cfd4-4e22-ad83-52cd8ea57c1f@e18g2000yqo.googlegroups.com> On 19 dic, 13:01, walterbyrd wrote: > I have not worked with Python enough to really know. But, it seems to > me that more I look at python 3.0, the more I wonder if it isn't a > step backwards. > > To me, it seems that this: > > print "%s=%d" % ('this',99) > > Is much easier, and faster, to type, and is also easier to read and > understand. It also allows people to leverage their knowledge of C. > > This (if it's right) is much longer, and requires more special > characters. > > print( "{0}={1}".format('this',99)) > > Maybe it's worth all the extra trouble, and breaking backward > compatibilty, and all. But, I never had the idea that the old way was > all that big a problem. Of course, I could be wrong. Was the old way > all that big of a problem? Well, I was playing with python 3k a little bit and, as usual, after a few minutes everything felt natural. The new string formating is perhaps a little more typing, much is much more clear and readable. I know where it came from. Long ago, Guido took a look at Boo, which is a python-like .NET language, and he posted a comment saying how much he liked the string formating, which is identical to the new one in python. I still can't get used to add the parenthesis to "print", and this is the only thing I don't like, but I'm sure there's a good reason for this change... Luis From jsutar at gmail.com Mon Dec 8 08:21:20 2008 From: jsutar at gmail.com (J Sutar) Date: Mon, 8 Dec 2008 13:21:20 +0000 Subject: newbie - merging xls files using xldt and xlwt In-Reply-To: References: <527424.71115.qm@web32704.mail.mud.yahoo.com> Message-ID: Hi, I have been provided with the program below. Which sets out to merge singlesheet excel files into one multisheet excel workbook. Though it manages to merge multiple files into one workbook many of the formats are not preserved. For example, what was originally 22.92% is converted to 0.2292... I was hoping if somebody could please help me understand how this can be fixed. Ideally I would like to create a program which merges files whilst keeping all formats (if at all possible). ####################################### """ Merge all xls files in a given directory into one multisheet xls file. The sheets get the orginal file name, without the extension. File names should not exceed 29 characters """ import xlrd, xlwt import glob, os.path def merge_xls (in_dir, out_file="K:/Stats Jobs 2003/St0883 (CITB - J33882)/3. Results/Excel/merged_output.xls"): xls_files = glob.glob(in_dir + "*.xls") sheet_names = [os.path.basename(v)[:-4] for v in xls_files] sheet_excl = [os.path.basename(v)[:-4] for v in xls_files if len(os.path.basename(v)[:-4]) > 29] merged_book = xlwt.Workbook() if in_dir[-1:] != "/": in_dir = in_dir + "/" xls_files.sort() if xls_files: for k, xls_file in enumerate(xls_files): print "---> Processing file %s" % (xls_file) if len (sheet_names[k]) <= 29: book = xlrd.open_workbook(xls_file) if book.nsheets == 1: ws = merged_book.add_sheet(sheet_names[k]) sheet = book.sheet_by_index(0) for rx in range(sheet.nrows): for cx in range(sheet.ncols): ws.write(rx, cx, sheet.cell_value(rx, cx)) elif book.nsheets in range(2, 100): for sheetx in range(book.nsheets): sheet0n = sheet_names[k]+str(sheetx+1).zfill(2) ws = merged_book.add_sheet(sheet0n) sheet = book.sheet_by_index(sheetx) for rx in range(sheet.nrows): for cx in range(sheet.ncols): ws.write(rx, cx, sheet.cell_value(rx, cx)) else: print "ERROR *** File %s has %s sheets (maximum is 99)" % (xls_file, book.nsheets) raise else: print "WARNING *** File name too long: <%s.xls> (maximum is 29 chars) " % (sheet_names[k]) print "WARNING *** File <%s.xls> was skipped." % (sheet_names[k]) merged_book.save(out_file) print print "---> Merged xls file written to %s using the following source files: " % (out_file) for k, v in enumerate(sheet_names): if len(v) <= 29: print "\t", str(k+1).zfill(3), "%s.xls" % (v) print if sheet_excl: print "--> The following files were skipped because the file name exceeds 29 characters: " for k, v in enumerate(sheet_excl): print "\t", str(k+1).zfill(3), v else: print "NOTE *** No xls files in %s. Nothing to do." % (in_dir) merge_xls(in_dir="C:/temp/test merge xls/") ####################################### Many thanks in advance. Jigs 2008/11/3 J Sutar > Mr Roskam, > > We have interacted before on the SPSS listserve, you have helped me out > fair few times! > > I need a helping hand again, do you have the final solution to this > problem, mergin xls from a given directory? > > Also where do I download the relevant modules from? > > Cheers > Jigs > > 2008/10/15 Albert-jan Roskam > > Hi John, >> >> Thanks! Using a higher xlrd version did the trick! Regarding your other >> remarks: >> -yep, input files with multiple sheets don't work yet. I kinda repressed >> that ;-) Spss outputs only single-sheet xls files, but I agree it's nicer if >> the programs works in other cases too. >> -and no, I don't intend to use data fields. Wouldn't it be easier to >> convert those to string values if I ever came across them? >> >> Thanks again! >> Albert-Jan >> >> >> --- On Wed, 10/15/08, John Machin wrote: >> >> > From: John Machin >> > Subject: Re: newbie - merging xls files using xldt and xlwt >> > To: python-list at python.org >> > Date: Wednesday, October 15, 2008, 3:14 PM >> > On Oct 15, 9:16 pm, Albert-jan Roskam >> > wrote: >> > > Hi, >> > > >> > > I wrote the program below to merge all xls files in a >> > given directory into one multisheet xls file. It uses xlwt >> > and xlrd. The xls files I use for input are generated by >> > Spss. When I open and re-save the files in Excel, the >> > program works, but when I use the xls files as they were >> > created by Spss, the program returns an error message (see >> > below). Some details: Python 2.4, xlwt version 0.7.0, xlrd >> > version 0.5.2, Win NT. >> > > >> > > Any ideas? >> > >> > The version of xlrd that you are using is an antique. Go to >> > http://pypi.python.org/pypi/xlrd and get the latest >> > version. If that >> > doesn't work, send me a copy of one of the files that >> > is displaying >> > this problem. >> > > >> > > Thanks in advance! >> > > >> > > Albert-Jan >> > > >> > > """ >> > > Merge all xls files in a given directory into one >> > multisheet xls file. >> > > The sheets get the orginal file name, without the >> > extension. >> > > File names should not exceed 31 characters, as this is >> > the maximum >> > > sheet name length >> > > """ >> > > >> > > import xlrd, xlwt >> > > import glob, os.path >> > > >> > > def merge_xls (in_dir, >> > out_file="d:/merged_output.xls"): >> > > >> > > xls_files = glob.glob(in_dir + >> > "*.xls") >> > > sheet_names = [] >> > > merged_book = xlwt.Workbook() >> > > >> > > [sheet_names.append(os.path.basename(v)[:-4]) >> > for k, v in enumerate(xls_files)] >> > >> > Wah! Try this: >> > sheet_names = [os.path.basename(v)[:-4]) for v in >> > xls_files] >> > >> > >> > > for k, xls_file in enumerate(xls_files): >> > > if len (sheet_names[k]) <= 31: >> > > book = xlrd.open_workbook(xls_file) >> > > ws = >> > merged_book.add_sheet(sheet_names[k]) >> > > for sheetx in range(book.nsheets): >> > > sheet = >> > book.sheet_by_index(sheetx) >> > > for rx in range(sheet.nrows): >> > > for cx in >> > range(sheet.ncols): >> > > ws.write(rx, cx, >> > sheet.cell_value(rx, cx)) >> > >> > I presume that you're not too worried about any date >> > data. >> > >> > If an input file has more than 1 sheet, you are creating >> > only one >> > sheet in the output file, and overwriting cells. >> > >> > > else: >> > >[snip] >> > > >> > > merge_xls(in_dir="d:/temp/") >> > > >> > > *** WARNING: OLE2 inconsistency: SSCS size is 0 but >> > SSAT size is non-zero *** >> > > put_cell 0 1 >> > > >> > > Traceback (most recent call last): >> > [snip] >> > > self._cell_types[rowx][colx] = ctype >> > > IndexError: list assignment index out of range >> > >> > Yeah, symptom of an xls file with a DIMENSIONS records that >> > lies ... >> > xlrd has like Excel become more resilient over time :-) >> > >> > BTW, consider joining the python-excel group at >> > http://groups.google.com/group/python-excel >> > >> > Cheers, >> > John >> > -- >> > http://mail.python.org/mailman/listinfo/python-list >> >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From prologic at shortcircuit.net.au Mon Dec 22 17:10:31 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 23 Dec 2008 08:10:31 +1000 Subject: Are Django/Turbogears too specific? In-Reply-To: <4E95C128-E1BC-41F8-ACDF-597C77F04512@semanchuk.com> References: <494eb16e$0$22710$426a74cc@news.free.fr> <2B198A4F-5911-456D-A45B-E073DB121446@semanchuk.com> <494F392C.5060201@wildenhain.de> <4E95C128-E1BC-41F8-ACDF-597C77F04512@semanchuk.com> Message-ID: On Tue, Dec 23, 2008 at 12:35 AM, Philip Semanchuk wrote: > > On Dec 22, 2008, at 1:52 AM, Tino Wildenhain wrote: > >> Philip Semanchuk wrote: >> ... >>> >>> I prefer Mako over the other template languages I've seen. >> >> From what I can tell Mako is nearly identical to all other >> template languages you might have seen (e.g. PHP style >> tags). Thats why I personally would not consider it. Its just >> much of a hassle to mix code and design this way. >> >> I prefer TAL (template attribute language, ZPT) [1] >> much over the other attempts I've seen ( and I've seen a lot) > > That's an excellent example of how Python can accommodate different tastes. > =) I can't stand TAL; I find it awkward and unPythonic. Your comment makes > sense, though. Mako and TAL have very different design philosophies, and if > you really like one, you're probably going to find the other strange at > best. I agree! :) And just for the record I prefer Mako :) (Not that I really use it at all) :P --JamesMills PS: Web Services FTW From wuwei23 at gmail.com Mon Dec 8 04:59:48 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 8 Dec 2008 01:59:48 -0800 (PST) Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? References: <5ccd4a18-cd2b-4040-90c6-33723af15e96@b38g2000prf.googlegroups.com> <7e1a9226-c7a9-4b5e-bfbb-ea079639d6a2@t39g2000prh.googlegroups.com> <682de8aa-62b1-477a-8b31-ae7698b1ffe7@w1g2000prk.googlegroups.com> Message-ID: <4b2bcda5-cee2-484e-9fc7-47caaf7a165e@z27g2000prd.googlegroups.com> On Dec 8, 7:18?pm, illume wrote: > It's easier to teach only requiring *using* classes, and functions > than *creating* them. ?This is important if it's being used to teach > programming - as you don't need to teach people two fairly large > concepts before you can do anything. I'm just kind of aghast at the idea of "teaching" anyone how to program games by using large, imperative chunks of code. I don't see functions as being a "fairly large concept" at all, and utterly vital to being able to write anything but the most basic 'hello world' example code. > Also python has very slow function calls, so avoiding using callbacks > is also faster. Wouldn't it be better to teach people the basics of coding -before- setting out to optimise their code? From hard4forget at gmail.com Sun Dec 7 15:44:55 2008 From: hard4forget at gmail.com (philips) Date: Sun, 7 Dec 2008 12:44:55 -0800 (PST) Subject: hi here is video of 13years old pregnent girl showing her belly the new world record www.funreality.com Message-ID: <55b4b121-7cd1-4ef9-bfd7-059bad04e690@j39g2000yqn.googlegroups.com> hi here is video of 13years old pregnent girl showing her belly the new world record www.funreality.com From rt8396 at gmail.com Tue Dec 23 00:05:22 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 21:05:22 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> <7c02eb33-a919-4481-8eda-76062729f233@k19g2000yqg.googlegroups.com> Message-ID: <32d8e3f1-52a7-4bce-a70a-70db488a417b@h20g2000yqn.googlegroups.com> On Dec 22, 10:09?pm, Ben Kaplan wrote: > That's just because most of us don't say anything unless we have ? > something useful to say. We prefer to let the experts answer the ? > questions, but we read the threads so we can benefit from them. OK Ben, So you are saying 1.) do not question the gods! 2.) speak only when spoken to! 3.) do not have an opinion! Somehow this reminds me of some old and brainwashing religions, Not an OSS project. Just observations Ben. From jcd at sdf.lonestar.org Mon Dec 15 16:58:57 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 15 Dec 2008 16:58:57 -0500 Subject: Removing None objects from a sequence In-Reply-To: References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> <0152e35f$0$8244$c3e8da3@news.astraweb.com> Message-ID: <1229378337.31120.13.camel@aalcdl07.lib.unc.edu> On Mon, 2008-12-15 at 02:11 +0000, Lie Ryan wrote: > On Fri, 12 Dec 2008 22:55:20 +0000, Steven D'Aprano wrote: > > > On Fri, 12 Dec 2008 21:18:36 +0000, Lie Ryan wrote: > >> Personally, I'd prefer VB's version: > >> foo IsNot bar > >> > >> or in pseudo-python > >> foo isnot bar > >> > >> since that would make it less ambiguous. > > > > "a is not b" is no more ambiguous than "1+2*3". True, there's ambiguity > > if you are ignorant of the precedence rules, but that's no worse than > > saying that "+" is ambiguous if you don't know what "+" means. > > > > "What's this 'is' operator??? It's ambiguous, it could mean ANYTHING!!! > > Panic panic panic panic!!!" > > > > *wink* > > > > You're allowed to assume the normal conventions, and (lucky for me!) > > despite being Dutch Guido choose to assume the normal English convention > > that "a is not b" means the same as "not (a is b)" rather than "a is > > (not b)". That's probably because the use-cases for the second would be > > rather rare. > > > > So given the normal precedence rules of Python, there is no ambiguity. > > True, you have to learn the rules, but that's no hardship. > > *I* know about the precedence rule, but a newbie or a tired programmer > might not. He might want to reverse the truth value of argument b but > instead has just reversed the whole expression. Probably in a slightly > convoluted code like this: > > if a is not(b and c): > ... > A newbie might make that mistake, but a tired programmer would be testing for equality rather than identity in that case, and if she weren't, she'd have to fix her code in the morning anyway. Cheers, Cliff From clp at rebertia.com Mon Dec 15 20:13:25 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 15 Dec 2008 17:13:25 -0800 Subject: tricky nested list unpacking problem In-Reply-To: <87fxkpxk41.fsf@daycos.com> References: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> <87fxkpxk41.fsf@daycos.com> Message-ID: <47c890dc0812151713u5f912273g7ffd50b86d894f68@mail.gmail.com> On Mon, Dec 15, 2008 at 12:24 PM, Kirk Strauser wrote: > At 2008-12-15T20:03:14Z, "Chris Rebert" writes: > >> You just need a recursive list-flattening function. There are many >> recipes for these. Here's mine: > >>>>> flattened = flatten([1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]]) >>>>> flattened >> [1, 2, 3, 5, 6, 10, 11, 7, 9, 1, 2, 3, 4, 5] >>>>> '-'.join(str(num) for num in flattened) >> '1-2-3-5-6-10-11-7-9-1-2-3-4-5' > > He doesn't want to flatten them directly. He's using [1,2,3] sort of like a > regular expression, so that 1,[2,3],4 means "1,2,4" or "1,3,4", not > "1,2,3,4". Ah, my bad. Misinterpreted. Still, it's a similar principle involved. He just needs to code up the right recursive function. Not all that hard. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From mirnazim at gmail.com Sun Dec 21 02:05:35 2008 From: mirnazim at gmail.com (Mir Nazim) Date: Sat, 20 Dec 2008 23:05:35 -0800 (PST) Subject: Question: Evaluate an string variable's value to a variable References: <4be6e91b-9fcf-4c22-bfe8-fad73190f87c@b41g2000pra.googlegroups.com> Message-ID: <7ec1c381-675a-45e2-994a-b2cebb5a11d7@t39g2000prh.googlegroups.com> On Dec 21, 11:56?am, "Chris Rebert" wrote: > On Sat, Dec 20, 2008 at 10:49 PM, Mir Nazim wrote: > > Just a quick question. > > > For example I have > > >>>> class X > >>>> ....pass > > > Then I do > >>>> x = X() > >>>> x.name = 'Nazim > > > Now my question is whether something like below is possible and how > >>>> y = 'name' > >>>> print x.y ? # ?How can x.y can be evaluated to x.name > > print getattr(x, y) #==> Nazim > > There are also analogous setattr() and delattr() functions. > Damn Right. These functions simply eluded my mind for well 15 minutes Thanks a lot Chris. > Cheers, > Chris > > -- > Follow the path of the Iguana...http://rebertia.com From lihang9999 at gmail.com Wed Dec 17 00:32:30 2008 From: lihang9999 at gmail.com (Li Han) Date: Tue, 16 Dec 2008 21:32:30 -0800 (PST) Subject: The rule of literal string Message-ID: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> Hi! I just began to read the tutorial of python3.0 and I just can't figure out the rule of literal string. There is a example in the tuotrial: >>> '"Isn\'t," she said.' '"Isn\'t," she said.' It is not what I want, I just want '"Isn't," she said.' be printed, why the backslash failed? These don't work at all: >>> '''"Isn't," she said.''' '"Isn\'t," she said.' >>> r"Isn't," she said. SyntaxError: invalid syntax (, line 1) >>> r'"Isn't," she said.' SyntaxError: invalid syntax (, line 1) I have tried to solve it until my brain damaged and now I need to sleep. From rhamph at gmail.com Mon Dec 8 16:10:53 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 8 Dec 2008 13:10:53 -0800 (PST) Subject: Rich Comparisons Gotcha References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Dec 8, 1:04?pm, Robert Kern wrote: > Rhamphoryncus wrote: > > On Dec 8, 11:54 am, Robert Kern wrote: > >> Rhamphoryncus wrote: > >>> On Dec 7, 4:20 pm, Steven D'Aprano >>> cybersource.com.au> wrote: > >>>> On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: > >>>>> Rasmus Fogh wrote: > >>>>>> Current behaviour is both inconsistent and counterintuitive, as these > >>>>>> examples show. > >>>>>>>>> x = float('NaN') > >>>>>>>>> x == x > >>>>>> False > >>>>> Blame IEEE for that one. Rich comparisons have nothing to do with that > >>>>> one. > >>>> There is nothing to blame them for. This is the correct behaviour. NaNs > >>>> should *not* compare equal to themselves, that's mathematically > >>>> incoherent. > >>> Mathematically, NaNs shouldn't be comparable at all. ?They should > >>> raise an exception when compared. ?In fact, they should raise an > >>> exception when *created*. ?But that's not what we want. ?What we want > >>> is a dummy value that silently plods through our calculations. ?For a > >>> dummy value it seems a lot more sense to pick an arbitrary yet > >>> consistent sort order (I suggest just above -Inf), rather than quietly > >>> screwing up the sort. > >> Well, there are explicitly two kinds of NaNs: signalling NaNs and quiet NaNs, to > >> accommodate both requirements. Additionally, there is significant flexibility in > >> trapping the signals. > > > Right, but most of that's lower level. ?By the time it reaches Python > > we only care about quiet NaNs. > > No, signaling NaNs raise the exception that you are asking for. You're right > that if you get a Python float object that is a NaN, it is probably going to be > quiet, but signaling NaNs can affect Python in the way that you want. > > >>> Regarding the mythical IEEE 754, although it's extremely rare to find > >>> quotations, I have one on just this subject. ?And it does NOT say "x > >>> == NaN gives false". ?It says it gives *unordered*. ?It is C and > >>> probably most other languages that turn that into false (as they want > >>> a dummy value, not an error.) > >>>http://groups.google.ca/group/sci.math.num-analysis/browse_thread/thr... > >> Table 4 on page 9 of the standard is pretty clear on the subject. When the two > >> operands are unordered, the operator == returns False. The standard defines how > >> to do comparisons notionally; two operands can be "greater than", "less than", > >> "equal" or "unordered". It then goes on to map these notional concepts to > >> programming language boolean predicates. > > > Ahh, interesting. ?Still though, does it give an explanation for such > > behaviour, or use cases? ?There must be some situation where blindly > > returning false is enough benefit to trump screwing up sorting. > > Well, the standard was written in the days of Fortran. You didn't really have > generic sorting routines. You *could* implement whatever ordering you wanted > because you *had* to implement the ordering yourself. You didn't have to use a > limited boolean predicate. > > Basically, the boolean predicates have to return either True or False. Neither > one is really satisfactory, but that's the constraint you're under. "We've always done it that way" is NOT a use case! Certainly, it's a factor, but it seems quite weak compared to the sort use case. I suppose what I'm hoping for is an small example program (one or a few functions) that needs the "always false" behaviour of NaN. From Mr.HassanShabbir at gmail.com Wed Dec 10 17:49:22 2008 From: Mr.HassanShabbir at gmail.com (Explore_Imagination) Date: Wed, 10 Dec 2008 14:49:22 -0800 (PST) Subject: How to convert uint64 in C into Python 32bit Object [ I am using Python2.2 ] Message-ID: <069f0d65-a3d5-4e8f-a85b-c53743ab99d0@i18g2000prf.googlegroups.com> Hi all I am new to C and python ... I want to convert C data type uint64 variable into the Python 32bit Object. I am currently using Python 2.2 [ It is necessary to use it ] Kindly give your suggestion how and in which way I can achieve this task. Looking forward for your positive feedback. Cheers From vlastimil.brom at gmail.com Wed Dec 3 09:39:11 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Wed, 3 Dec 2008 15:39:11 +0100 Subject: generating a liste of characters In-Reply-To: References: Message-ID: <9fdb569a0812030639x78a4444du710c7e813d4c81a@mail.gmail.com> 2008/12/3 Yves Dorfsman : > Is there any built in way to generate a list of characters, something > along the line of range('a'-'z') ? > > Right now I am using: > > chars = [ chr(l) for l in range(0x30, 0x3a) ] # 0 - 9 > chars += [ chr(l) for l in range(0x41, 0x5b) ] # A - Z > chars += [ chr(l) for l in range(0x61, 0x7b) ] # a - z > > Is there a better, more straight forward way of doing that ? > > > > Thanks. > > > > Yves. > http://www.sollers.ca/blog/2008/swappiness > http://www.sollers.ca/blog/2008/swappiness/.fr > > -- > http://mail.python.org/mailman/listinfo/python-list > If you want tu use it generaly an any characters, maybe ord() can make it a bit simpler: >>> map(unichr, range(ord("a"), ord("z"))) [u'a', u'b', u'c', u'd', u'e', u'f', u'g', u'h', u'i', u'j', u'k', u'l', u'm', u'n', u'o', u'p', u'q', u'r', u's', u't', u'u', u'v', u'w', u'x', u'y'] >>> otherewise see the string module with some predefined ranges. hth, vbr From isabellknauer at googlemail.com Fri Dec 5 09:51:58 2008 From: isabellknauer at googlemail.com (isabellknauer at googlemail.com) Date: Fri, 5 Dec 2008 06:51:58 -0800 (PST) Subject: ftp retrlines with re... Message-ID: Hey! Ive been working on an application quite some time now and i wanted to include something to let the user load a new version. i therefore tried to include this here: from ftplib import FTP import string,re def handleDownload(block): processfile.write(block) print ".", def load_new_version(old_version): host='host.bla' user='usr_ftp_76512' password='45mhBLl3lXRX.332' account='usr_ftp_76512' download='' directory = 'htdocs' server = FTP(host) server.login(user,password,account) server.cwd(directory) filelist=server.retrlines('LIST') #okay this works :logged into the ftpserver,changed dir and now have a #string that tells the files like this: #-rw-r--r-- 1 usr_ftp_76512 ftpgroup 14454 Dec 5 14:10 Pict5.2.2.jpg #-rw-r--r-- 1 usr_ftp_76512 ftpgroup 16174 Dec 5 12:37 Picture 3.jpg #-rw-r--r-- 1 usr_ftp_76512 ftpgroup 14139 Dec 5 12:38 Picture 6.jpg #-rw-r--r-- 1 usr_ftp_76512 ftpgroup 42713 Dec 5 12:38 Picture 7.jpg #226 Transfer complete. print filelist files=re.findall(' .{2,20}[.][a-z]{3,3}', filelist,re.I|re.S) #the dot means every char, because of the flag re.S # re.I ignores case #{2,20} this means 2 to twenty of the char that is before it #heres the problem... if you copy the output and put it into a string he #finds all the files with findall, but not inside here... and i dont get why #help:( print files for file in files: number=re.findall('pict([0-9])[.]([0-9])[.]? ([0-9]?)',file,re.I) version=100*int(number[0][0])+ 10*int(number[0][1])+ int(number [0][2]) if version >old_version: print version print old_version old_version=version download=file if download : processfile = open(download, 'wb') server.retrbinary('RETR ' + download, handleDownload) processfile.close() server.close() return True else: server.close() return False load_new_version(201) #greetz From martinjamesevans at gmail.com Thu Dec 4 10:37:14 2008 From: martinjamesevans at gmail.com (martinjamesevans at gmail.com) Date: Thu, 4 Dec 2008 07:37:14 -0800 (PST) Subject: EBCDIC <--> ASCII Message-ID: <091f0404-2be3-4bda-8619-03627bd03fdc@k8g2000yqn.googlegroups.com> I'm having a problem trying to use the codecs package to aid me in converting some bytes from EBCDIC into ASCII. I have some 8bit text that is in mixed format. I extract the bytes that are coded for EBCDIC and would like to display them correctly. The bytes that are EBCDIC could values 0-255, I'm only really interested in the printable portions and could say leave the rest as dots. I've tried starting with something like this, but I assume it is expecting the source to be in unicode already? e.g. (pretend the second half are EBCDIC characters) sAll = "This bit is ASCII, " sSource = sAll[19:] sEBCDIC = unicode(sSource, 'cp500', 'ignore') sASCII = sEBCDIC.encode('ascii') Obviously I could just knock up a 255 character lookup table and do it myself, I was just trying to be a little more Pythonic and use that built in table. Thanks, Martin From mmanns at gmx.net Thu Dec 18 20:24:37 2008 From: mmanns at gmx.net (mmanns at gmx.net) Date: Fri, 19 Dec 2008 02:24:37 +0100 Subject: Which sparse matrix package? References: <20081218231851.70dd91e2@Schlamber.localdomain> Message-ID: <20081219022437.0362726e@Schlamber.localdomain> On Thu, 18 Dec 2008 18:04:19 -0600 Robert Kern wrote: > Martin Manns wrote: > > > Should I use another type of matrix in scipy.sparse? If yes which? > > If you have a benchmark, you might just want to try all of them. > Should be just a matter of a small script. Block Sparse Row > (bsr_matrix) might be the most appropriate in terms of data > structure, but it appears that a bunch of stuff important for your > use case is unimplemented. This was my first impulse until I saw that the syntax and the actually implemented methods vary considerably inside scipy.sparse (different authors?). Before I code around all of that, I would like to to see, which functionality is really provided by which matrix class. Do you know where to find an overview (some docs)? Currently, I stumble upon unimplemented things in my unit tests and figure out what is going on after reading the sparse code :-( Martin From castironpi at gmail.com Sun Dec 14 18:53:27 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 14 Dec 2008 15:53:27 -0800 (PST) Subject: subprocess to C program References: <0ebd59c5-95a1-42d4-b597-d1c248490b8e@y1g2000pra.googlegroups.com> <8MidneyhDfIG-9nUnZ2dnUVZ_uadnZ2d@posted.visi> <36656830-63a8-479c-8c46-525f2b55eeea@z28g2000prd.googlegroups.com> <6e8f11eb-d773-4ffc-851c-a381228d4ae2@v4g2000yqa.googlegroups.com> Message-ID: <3047f141-bf0e-4c57-baf7-91156024523a@k36g2000pri.googlegroups.com> On Dec 14, 6:32?am, bobicanprogram wrote: > On Dec 13, 10:09 pm, MRAB wrote: > > > > > Aaron Brady wrote: > > > On Dec 13, 7:51 pm, Grant Edwards wrote: > > >> On 2008-12-14, MRAB wrote: > > > >>>> I am writing a C process and I want to read data from a file that I > > >>>> write to in Python. ?I'm creating a pipe in Python, passing it to the > > >>>> C process, and calling '_read'. ?It gives me error 9, bad file number. > > > snip > > >>>> meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9. ?I want 'ct' > > >>>> to be 11 at this point. ?Thanks in advance. > > >>> It looks like the ids aren't system global. > > >> They certainly aren't in Unix: Their a property of the process. > > > >> -- > > >> Grant > > > > I'm not on Unix. ?It has to be possible somehow. ?Do I need to set > > > permissions on the IDs? ?Are Stdin and Stdout my only options? ?Or > > > does Popen prevent sharing IDs somehow? > > > You'd be better off using sockets. > > You might also consider using SIMPL (http://www.icanprogram.com/simpl) > SIMPL has had a Python interface for about 5 years now. ? There is an > online tutorial here. (http://www.icanprogram.com/06py/main.html) > > In one of your responses you mentioned that you were not on Unix (and > I presume Linux). ? SIMPL-Python has recently been extended to work > transparently from a Windows OS as well. > > bob > SIMPL project coordinator The engine uses a disk-based FIFO for interprocess. It's good if you're looking for one- or two- way sequential. From __peter__ at web.de Fri Dec 19 08:54:16 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2008 14:54:16 +0100 Subject: importing csv file into sqlite References: <21067453.post@talk.nabble.com> <7f64f5c6-b130-4f9b-a670-6b32eccba550@n33g2000pri.googlegroups.com> Message-ID: klia wrote: > > > John Machin wrote: >> >> On Dec 18, 6:20?pm, klia wrote: >>> klia wrote: >>> >>> > hey guys, i have a hug .csv file which i need to insert it into sqlite >>> > database using python. >>> > my csv data looks like this >>> > Birthday2,12/5/2008,HTC,this is my birthday >>> > Sea,12/3/2008,kodak,sea >>> > birthday4,14/3/2009,samsung,birthday >>> > love,17/4/2009,SONY,view of island >>> >>> > can any one give me a head start codes. >>> >>> > thanks in advance >>> >>> guys so far i came out with this but i get this error >>> waseem at Linux:~/Project2$ python experment.py >>> Traceback (most recent call last): >>> File "experment.py", line 13, in >>> curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item) >>> sqlite3.ProgrammingError: Incorrect number of bindings supplied. The >>> current >>> statement uses 4, and there are 1 supplied. >>> >>> here's the codes >>> >>> import sqlite3 >>> import csv >>> >>> f = open('/home/waseem/Project2/photos.txt') >>> csv.field_size_limit(100000) #see below! >> >> I see nothing "below" that looks at all like an attempt to justify >> setting the field size limit to 100000 -- why are you doing that? >> Tends to make one suspect a problem with your delimiter and/or your >> line separator. >> >>> input = csv.reader(f, delimiter='\t') >> >> Why \t??? Your data examples show commas -- could this be why you are >> getting one field per line (as Peter has pointed out)? >> >>> conn = sqlite3.connect('/home/waseem/Project2/picutres.db') >> >> Is it really called "picutres" instead of "pictures", or are you >> typing the code that you ran again from (your) memory? >> >>> curse = conn.cursor() >>> >>> curse.execute('CREATE TABLE photos (Name VARCHAR(100) PRIMARY KEY, Date >>> INTEGER, Make VARCHAR(50), Tag VARCHAR(100))') >> >> [OT but to save the next question] >> The column named "Date" is defined to be INTEGER but the data from the >> CSV file will be a str object e.g. "12/5/2008" ... I know sqlite >> cheerfully regards column types as vague reminders rather than >> enforceable constraints on your input, but wouldn't you like to >> convert your dates to e.g. "2008-05-12" before you poke them in? You >> may want to use "ORDER BY Date" at some stage, and so that ORDER BY >> isn't whacked and GROUP BY doesn't give ludicrous results, wouldn't it >> be a good idea to crunch 12/5/2008 and 12/05/2008 into a common format >> so that they compare equal? >>> >>> for item in input: >> >> I strongly suggest that you try to get a clue about exactly what you >> are getting from the csv reader e.g. >> >> for line_num, item in enumerate(input_renamed_as_suggested_by_anor): >> print line_num, repr(item) >> >>> curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item) >>> curse.commit() >>> >> >> HTH, >> John >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > hey guys > i took all of your suggestion but my goal ain't yet achieved :-(( > these are the codes after changes, john i couldn't really catch what do > you mean by renaming input, is it just normal renaming.i am testing the > code on just simple .csv file with few data in as follows before trying on > my hug csv file but still no joy > > "Bithday",12-05-08,"HTC","this is my birthday" > "Sea",12-03-08,"kodak","sea" > "girl","14-03-2009","samsung","birthday" > "love","17-04-2009","SONY","view of island" > > import sqlite3 > import csv > > f = open('/home/waseem/Project2/photos.csv') > input = csv.reader(f, delimiter=',') > conn = sqlite3.connect('/home/waseem/Project2/pictures.db') > curse = conn.cursor() > > curse.execute('CREATE TABLE photos (Name VARCHAR(100) PRIMARY KEY, Date > INTEGER, Make VARCHAR(50), Tag VARCHAR(100))') > for row in input: > curse.execute('INSERT INTO photos VALUES (?,?,?,?)', '*row') This will try to set Name="*" Date="r" Make="o" Tag="w" for all records. Can you work out why? > curse.commit() > > this time i got this error > > waseem at Linux:~/Project2$ python experment.py > Traceback (most recent call last): > File "experment.py", line 12, in > curse.execute('INSERT INTO photos VALUES (?,?,?,?)', '*row') > sqlite3.IntegrityError: column Name is not unique > > i removed the primary key and single quotation mark for '*row' to just > *row but i got the old error which is > > waseem at Linux:~/Project2$ python experment.py > Traceback (most recent call last): > File "experment.py", line 11, in > curse.execute('INSERT INTO photos VALUES (?,?,?,?)', *row) > TypeError: function takes at most 2 arguments (5 given) curse.execute('INSERT INTO photos VALUES (?,?,?,?)', row) (no '*') will work for the sample data you give above. If you get errors with your real data you have to fix that data. Follow John's advice to locate the problematic records. Peter From narkewoody at gmail.com Tue Dec 23 23:27:02 2008 From: narkewoody at gmail.com (Steven Woody) Date: Wed, 24 Dec 2008 12:27:02 +0800 Subject: Multi-dimension list Message-ID: Hi, In the book Python Essential Reference, Chapter 3, I see an example: From fakeaddress at nowhere.org Mon Dec 15 22:12:06 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 15 Dec 2008 19:12:06 -0800 Subject: socket and subprocess problem In-Reply-To: <6d3291c3-4e12-4bdd-884a-21f15f38d105@a12g2000pro.googlegroups.com> References: <6d3291c3-4e12-4bdd-884a-21f15f38d105@a12g2000pro.googlegroups.com> Message-ID: goatold at gmail.com wrote: > In my python code I use subprocess.Popen to run and external program > who will listen to a TCP port. And I also create a socket to connect > to the TCP port that the external program is listening. > I will get 'Connection refused, errno=111' when I try to socket.connect > (). Looks like a race. The first process tries to connect before the external program gets through socket.listen(). If you think about it, it's not that surprising. > But if I run my subprocess.Popen code and socket code in two separate > python process. Socket will connect just fine. It's still a race condition even if the side you want to win almost always does. -- --Bryan From sjmachin at lexicon.net Thu Dec 11 20:59:38 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 11 Dec 2008 17:59:38 -0800 (PST) Subject: newbie question: if var1 == var2: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> <44aa0191-e374-4bf0-b039-d05cfa996b1d@p2g2000prn.googlegroups.com> Message-ID: <37fc3229-b0a2-4d95-990f-61300fc2b257@r37g2000prr.googlegroups.com> On Dec 12, 11:39?am, MRAB wrote: > Jason Scheirer wrote: > > On Dec 11, 3:49 pm, John Machin wrote: > >> On Dec 12, 10:31 am, "Rhodri James" > >> wrote: > > >>> On Thu, 11 Dec 2008 19:49:23 -0000, Steve Holden ? > >>> wrote: > >>>> Kirk Strauser wrote: > >>>>> At 2008-11-29T04:02:11Z, Mel writes: > >>>>>> You could try > >>>>>> for item in fname: > >>>>>> ? ? item = item.strip() > >>>>> This is one case where I really miss Perl's "chomp" function. ?It ? > >>>>> removes a > >>>>> trailing newline and nothing else, so you don't have to worry about ? > >>>>> losing > >>>>> leading or trailing spaces if those are important to you. > >>>> ... and it's so hard to write > >>>> ? ? ?item = item[:-1] > >>> Tsk. ?That would be "chop". ?"chomp" would be > >>> ? ? ?if item[-1] == '\n': > >>> ? ? ? ? ?item = item[:-1] > >> Better: > >> if item and item[-1] == '\n': > >> ? ? return item[:-1] > >> return item > > > Best: > > > return item \ > > ? ? ? ?if not (item and item.endswith('\n')) \ > > ? ? ? ?else item[:-1] > > > Though really you should be using item.rstrip() > > Why not just: > > ? ? ?item[:-1] if item.endswith('\n') else item Some possible reasons: * because you might be supporting old versions of Python (my offering runs on 1.5) * because the " if else " syntax gives you the screaming dry Edgar Britts * because you'd prefer not to have the overhead of a method lookup and method call From rogerb at rogerbinns.com Wed Dec 24 03:50:49 2008 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 24 Dec 2008 00:50:49 -0800 Subject: Most efficient way to build very large dictionaries In-Reply-To: <1230107768.14060.1291622121@webmail.messagingengine.com> References: <1230104615.5867.1291617213@webmail.messagingengine.com> <1230107768.14060.1291622121@webmail.messagingengine.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 python at bdurham.com wrote: > Thank you for your suggestion about looking at SQLite. I haven't > compared the performance of SQLite to Python dictionaries, but I'm > skeptical that SQLite would be faster than in-memory Python dictionaries > for the type of analysis I'm doing. I'd recommend at least trying a test just to see. As an example SQLite uses indices which will be faster than Python dicts for some set operations. (And if you aren't careful, your various Python based optimizations will end up duplicating what SQLite does internally anyway :-) > Prior to my use of Python, my > customer used a very expensive Oracle system to analyze their log files. > My simple Python scripts are 4-20x faster than the Oracle PL/SQL they > are replacing - and run on much cheaper hardware. SQLite is not like Oracle or any similar database system. It does not operate over the network or similar connection. It is a library in your process that has an optimized disk storage format (single file) and a SQL parser that generates bytecode for a special purpose virtual machine in pretty much the same way CPython operates. The performance improvements you are seeing with Python over Oracle are exactly the same range people see with SQLite over Oracle. One common usage reported on the SQLite mailing list is people copying data out of Oracle and running their analysis in SQLite because of the performance advantages. > Note: Memory is currently not a concern for me so I don't need SQLite's > ability to work with data sets larger than my physical memory. The pragmas tune things like cache sizes. The SQLite default is 2MB, relying on the operating system for caching beyond that. Bumping up that kind of size was my suggestion :-) Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAklR9+UACgkQmOOfHg372QSMbwCdGS5S2/96fWW8knjfBVqReAfV AEwAn2Yc+L9BEZgT69OjwtyqxLtifVpU =mPfy -----END PGP SIGNATURE----- From huwdjones at gmail.com Tue Dec 16 07:17:51 2008 From: huwdjones at gmail.com (huw_at1) Date: Tue, 16 Dec 2008 04:17:51 -0800 (PST) Subject: cx_Oracle issues References: <5b2dad81-2750-4347-8079-6ab31321d579@s1g2000prg.googlegroups.com> <9142a8f1-7f76-4fc0-9ca1-c9dec310f2ce@r37g2000prr.googlegroups.com> <9f436c9e-2319-499c-a306-d255996372fc@e22g2000vbe.googlegroups.com> Message-ID: <09b53231-5a92-437c-859b-6e5d0ce106c8@k36g2000pri.googlegroups.com> On Dec 15, 12:59?pm, "ron.re... at gmail.com" wrote: > On Dec 15, 2:44?am, huw_at1 wrote: > > > > > On Dec 11, 5:34?pm, "ron.re... at gmail.com" wrote: > > > > On Dec 10, 9:48?am, huw_at1 wrote: > > > > > Hey all. When usingcx_Oracleto run a procedure like: > > > > > cursor.execute("select (obj.function(value)) from table where > > > > id=blah") > > > > > I am getting the following error: > > > > > ORA-06502: PL/SQL: numeric or value error: character string buffer too > > > > small ORA-06512: at line 1 > > > > > Looking at cursor.description I get: > > > > > [('(obj.function(value))', , 4000, 4000, 0, > > > > 0, 1)] > > > > > Any tips - i have never seen this error before but am guessing that > > > > the value being returned is too big for the buffer size set for the > > > > cursor. the procedure fetches data from a LOB. > > > > > Any suggestions/confirmations? > > > > > Many thanks > > > > This error is a problem with the PL/SQL, notcx_Oracle. ?You need to > > > debug obj.function to see what kind of data is being accessed and then > > > a data analysis of that data to understand why this error occurs. ?I > > > can tell you the function is most likely expecting characters from a > > > column that are numeric [0 .. 9] and is getting alpha characters. > > > > -- > > > Ron Reidy > > > Sr. Oracle DBA > > > Hi thanks for the responses. Unfortunately the procedure in question > > is from a third party vendor so I can't really debug it so I'd say I > > was fairly stumped. Just out of interest how do you increase the > > output buffer size withcx_Oracle? > > > Many thanks- Hide quoted text - > > > - Show quoted text - > > Hi, > > Sure you can. ?You can see the PL/SQL source from the ditionary view > ALL_SOURCE: > select text from all_source where name = 'NAME_OF_FUNCTION'; > > From there, reverse engineeer which table(s) and column(s) are being > accesses and do the data analysis. > > -- > Ron Reidy Hi all, So I tried Rons query but unfortunately I got 0 records returned. However I can confirm that running the select query from a client does indeed generate the same error. Is there anything else I could try? Otherwise I'll just get in touch with the vendor I guess. From michael.mabin at gmail.com Fri Dec 5 11:09:08 2008 From: michael.mabin at gmail.com (Michael Mabin) Date: Fri, 5 Dec 2008 10:09:08 -0600 Subject: To Troll or Not To Troll (aka: "as" keyword woes) In-Reply-To: <896B75251BA19745A529B1B867893FA5DB0E@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA5DB0E@planet.delsci.local> Message-ID: Warren, weren't you aware that Python.org is now a church. So you can never live up to the standards of the Pythonista high priests. You can only ask a question or submit your comment then cower, hoping the pythonista high priests don't beat you with clubs for heresy. ;) 2008/12/4 Warren DeLano > > From: Ben Finney > > > > > > "Chris Mellon" writes: > > > > > Peculiarities in usenet resulted in this discussion having several > > > threads and I missed some messages before I wrote this email. > > > > I'll put this more bluntly: Warren's messages to date > > egregiously break the flow of discussion. > > > > Warren, in the interest of sane discussion in these forums, please: > > > > * preserve attribution lines on quoted material so we can see who > > wrote what. > > > > * use the convention of ?New subject (was: Old subject)? when you > > change the ?Subject? field of a message. > > > > * switch to a client that preserves threading in messages you send, > > i.e. that properly constructs the ?References? and ?In-Reply-To? > > fields. > > > > General advice good for everyone, of course, but particularly > > apropos to this reply. Any one of the above is detrimental to > > omit; striking on all three makes a discussion almost > > impossible to follow. (Thank you, though, for avoiding the > > worse habit of top posting!) > > Thank so much for the suggestions Ben. Sorry that I am personally > unable to live up to your high standards, but it is nevertheless an > honor to partipicate in such a helpful and mutually respectful community > mailing list! > > Warren > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.panesse at gmail.com Sun Dec 21 06:29:29 2008 From: robert.panesse at gmail.com (McCoy Fan) Date: Sun, 21 Dec 2008 03:29:29 -0800 (PST) Subject: Read an image from a URL and write it to the browser Message-ID: I want to do something simple: read an image from an image URL and write the image to the browser in CGI style. I wrote a CGI script to do this (I'm new to Python) and got the following error: "FancyURLopener instance has no attribute 'tempcache'" in Hi, in a module of mine (ftpserver.py) I'd want to add a (boolean) global variable named "use_gmt_times" to decide whether the server has to return times in GMT or localtime but I'm not sure if it is a good idea because of the "ethical" doubts I'm gonna write below. In first place I've never liked global variables too much and always preferred per-class-instance variables instead. The problem in my case is that I have to use such variable in two separated classes: FTPHandler and VirtualFileSystem. Also, I want that for no reason one class uses times in GMT and the other one local times. Another doubt is the naming convention. PEP-8 states that global variables should use the lower_case_naming_convention but I've seen a lot of library module using the UPPER_CASE_NAMING_CONVENTION. What am I supposed to do about it? Thanks in advance for any comment. --- Giampaolo http://code.google.com/p/pyftpdlib/ From manu3d at gmail.com Sat Dec 13 15:19:29 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Sat, 13 Dec 2008 12:19:29 -0800 (PST) Subject: Bidrectional Subprocess Communication Message-ID: Hi everybody, I'm trying to replicate the positive results of the Client/Server scripts from the thread "Bidirectional Networking", but this time using a Process/SubProcess architecture. The SubProcess, acting as a server, is working just fine. But the Process executing the SubProcess, the client, somehow doesn't hear any of the standard output from the SubProcess. What am I missing? Below you can find the two short pieces of code. Thanks for your help! Manu ------------------------------------------- # serverTest.py import sys print("Starting Server!") while True: data = sys.stdin.readline().strip() if(data): print("SERVER RECV: '" + data + "'") if(data == "Stop!"): break print("Server Stopped!") ------------------------------------------- #clientTest.py import sys import threading from time import sleep from subprocess import Popen, PIPE ## Server Thread class ListenerThread(threading.Thread): def __init__(self, inChannel): threading.Thread.__init__(self) self.inChannel = inChannel def run(self): while True: data = self.inChannel.readline().strip() print("serverTest.py says: " + data) print("Starting Client!") server = Popen("python serverTest.py", stdin=PIPE, stdout=PIPE) listenerThread = ListenerThread(server.stdout) listenerThread.setDaemon(True) listenerThread.start() server.stdin.write("Something very meaningful!\n") server.stdin.write("Stop!") print("Client Stopped!") From castironpi at gmail.com Sun Dec 7 06:26:08 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 7 Dec 2008 03:26:08 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> <014b2a09$0$20670$c3e8da3@news.astraweb.com> <5e58fbc8-17df-40ae-8b18-7b07765e898f@v38g2000yqb.googlegroups.com> Message-ID: On Dec 6, 9:35?pm, Carl Banks wrote: > On Dec 6, 8:17?pm, Steven D'Aprano > I don't like "cast", because a cast is an instruction to the compiler to > > treat data as some type other than what it was defined as. > It doesn't > > create a new piece of data. (At least in C-like languages.) > > Actually, C-like languages do exactly that. ?(float)i doesn't take the > bits of int i and treat them as if they were a float, it creates new > data in the appropriate data type that matches the value of i > semantically, which would have a very different bit pattern. '(float&) i' does what he said. int i; float& f= ( (float&) i ); f= 1; printf( "%x %f\n", i, f ); /Output: 3f800000 1.000000 Sorry for the tangent. From _karlo_ at _mosor.net_ Sun Dec 14 06:52:15 2008 From: _karlo_ at _mosor.net_ (Karlo Lozovina) Date: Sun, 14 Dec 2008 11:52:15 +0000 (UTC) Subject: curses and refreshing problem References: <69d2698a-6f44-4d85-adc3-1180ab158632@r15g2000prd.googlegroups.com> Message-ID: Carl Banks wrote in news:69d2698a-6f44-4d85-adc3-1180ab158632 at r15g2000prd.googlegroups.com: > Unless you are referring to some wget screen mode I don't know about, > I suspect wget outputs its progress bar using carriage returns > without newlines. If that's all you want, there is no need to use > curses. > > Here is a little example program to illustrate: > > import time, sys > for i in range(21): > sys.stdout.write('\rProgress: [' + '='*i + ' '*(20-i) + ']') > sys.stdout.flush() > time.sleep(1) > sys.stdout.write("\nFinised!\n") Thanks, that's it! I just assumed wget uses curses for the progress bar, so the carriage return didn't even cross my mind ;). -- _______ Karlo Lozovina - Mosor | | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163 | || _ | _ | Parce mihi domine quia Dalmata sum. |__|_|__||_____|_____| From jeremiah.dodds at gmail.com Tue Dec 2 20:17:48 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Tue, 2 Dec 2008 20:17:48 -0500 Subject: Pyhon (with wxPython) on Windows' cygwin: can it be done fully ? In-Reply-To: <9c313975-874a-4d50-a05c-e984db6ee0f7@l42g2000yqe.googlegroups.com> References: <6p2l98F61ttqU1@mid.uni-berlin.de> <4a4fa55e-779c-47bd-a6bd-4829abaa4824@d42g2000prb.googlegroups.com> <2a7664b4-668c-4269-8feb-cb35e23260dd@o4g2000pra.googlegroups.com> <9c313975-874a-4d50-a05c-e984db6ee0f7@l42g2000yqe.googlegroups.com> Message-ID: <12cbbbfc0812021717o4fcbb16co9926cee5cc36212c@mail.gmail.com> On Mon, Dec 1, 2008 at 12:25 PM, Fernando H. Sanches < fernandohsanches at gmail.com> wrote: > At first I also disliked print's new syntax, but later I realised it > could be useful. > > However, I agree that the parentheses are annoying. Not because of the > parens theirselves, but because of the Shift key. > > Why programmers stilll can't have special keyboards with parens keys > that doesn't need pressing "shift"? Isn't time C programmers have a > "&" key and perl programmers a $ one? And why the heck we need shift > for "(" and not for "[" or "{", since the first one is much more used > (even outside programming)? > > Really, we don't need to change our syntax, we need to change our > keyboards. We are so blinded by tradition that we are losing > productivity. > -- > http://mail.python.org/mailman/listinfo/python-list > Obligatory: http://groups.google.com/group/comp.lang.lisp/msg/f499cca6b478260f?hl=en&pli=1 I've actually always wanted to try doing something like that, but haven't actually worked up the gumption to go anywhere past swapping caps and ctrl. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 9 08:50:58 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 09 Dec 2008 14:50:58 +0100 Subject: Beginner trying to understand functions. In-Reply-To: References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> <9df7549a-f28b-4d39-b105-90c099f472f2@z28g2000prd.googlegroups.com> <040a2896-be99-477e-909c-c55c5a0e6665@y1g2000pra.googlegroups.com> Message-ID: <493e77bb$0$28214$426a74cc@news.free.fr> simonh a ?crit : > Thanks for the extra tips Ivan and Bruno. Here is how the program > looks now. Any problems? > > > > import sys > > def get_name(): > name = input('Please enter your name: ') > print('Hello', name) This one would be better spelled "get_and_display_name" !-) > def get_age(): > try: > return int(input('Please enter your age: ')) > except ValueError: > print('That was not a valid number. Please try again.') > return get_age() Warning : there's a recursion limit in Python. While there are very few chances you hit it in this case, it may bite you one day if you start using recursion instead of iteration. > def check_age(age,min=18,max=31): > if age < min: > print('Sorry, too young.') > elif age >= max: > print('Sorry, too old.') > else: > print('Come on in!') > > def again(): > response = input('Try again? Y or N: ') > while response != "Y": You probably mean 'if response != "Y"' ? > if response == 'N': > print('Program finished.') > input('Press any key to exit.') > sys.exit() > else: > return response This return value is never used in the calling code. And if the user types anything else than "Y" or "N", the program will exit without even a goodbye message. > run() > def run(): > get_name() > a = get_age() > check_age(a) > again() As far as I'm concerned, I'd write it that way: def read_string(question, error=''): if not error: error = "That was not a valid string. Please try again." while True: result = input(question).strip() if result: return result else: print error def read_int(question, error=''): if not error: error = "That was not a valid number. Please try again." while True: try: return int(input(question).strip()) except ValueError: print(error) def check_in_range(obj, mini, maxi, if_ok=0, if_lesser=-1, if_greater=1) if obj < mini: return if_lesser elif age >= max: return if_greater else: return if_ok def again(question="Try again ?", yes="Y", no="N"): # XXX : see appropriate string formatting for Python 3 # in 2.x, I'd write it as: # prompt = "%s (%s or %s): " % (question, yes, no) prompt = question + " " + yes" + " or " + no + ": " while True: response = input(prompt) if response in (yes, no): return response == yes def run(): name = read_string("Please enter your name: ") print("Hello, ", name) age = read_int("Please enter your age: ") messages = { 0: "Come on in!", -1: "Sorry, too young", 1: "Sorry, too old", } message_key = check_in_range(age, 18, 31) print(messages[message_key]) def main(): while True: run() if not again(): print('Program finished.') input('Press any key to exit.') return if __name__ == "__main__": main() NB : the 'if __name__ == "__main__"' will allow you to use your code as both a script (ie : calling it as 'main' program) or as a module (importing it from within another script or module so you can reuse the functions), by only calling 'main()' if the file is used as a script. HTH From rdmurray at bitdance.com Fri Dec 12 10:25:48 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Fri, 12 Dec 2008 10:25:48 -0500 (EST) Subject: Interface & Implementation In-Reply-To: <11e2ac5b5eb.2364397661727502391.6806593866408074890@adventnet.com> References: <11e2ac5b5eb.2364397661727502391.6806593866408074890@adventnet.com> Message-ID: On Fri, 12 Dec 2008 at 16:07, J Ramesh Kumar wrote: > I am new to python. I require some help on implementing interface and > its implementation. I could not find any sample code in the web. Can > you please send me some sample code which is similar to the below java > code ? Thanks in advance for your help. > > ............ > public interface MyIfc > { > public void myMeth1(); > public void myMeth2(); > } > .... > public class MyClass implements MyIfc > { > public void myMeth1() > { > //do some implementation > } > > public void myMeth2() > { > //do some implementation > } > } > ... > > MyClass myc=new MyClass(); > Hashtable hash=new Hashtable(); > hash.put("MYIFC",myc); > ........ > MyIfc myi=(MyIfc)hash.get("MYIFC"); > myi.myMeth1(); > myi.myMeth2(); > ......... The python 2.x way to to this would be: class MyClass(object): def myMeth1(self): #do some implementation def myMeth2(self): #do some implementation myc = MyClass() hash = dict() hash["MYIFC"] = myc myi = hash["MYIFC"] myi.myMeth1() myi.myMeth2() Which is to say, python 2.x does not have any formal notion of interfaces. In python 3.0 if you have a need for an interface you can do this: from abc import ABCMeta, abstractmethod class MyIfc: __metaclass__ = ABCMeta @abstractmethod def myMeth1(self): pass @abstractmethod def myMeth2(self): pass class MyClass(MyIfc): [from here on just like above] Note however, that an Abstract Base Class is _not_ the same thing as a Java interface, though it can serve some of the same purposes. See http://docs.python.org/dev/3.0/whatsnew/2.6.html#pep-3119 for more. --RDM From invalid at invalid Tue Dec 23 12:35:11 2008 From: invalid at invalid (Grant Edwards) Date: Tue, 23 Dec 2008 11:35:11 -0600 Subject: pseudo terminal usage from Python? References: <5t-dnRgMi9Z4lszUnZ2dnUVZ_vOdnZ2d@posted.visi> Message-ID: On 2008-12-23, skip at pobox.com wrote: > Grant> Are you sure it's not Python buffering its input? Have you tried > Grant> "python -u mympstat.py"? > > Hmmm... No, I hadn't considered that. I'll check it out. Thanks... > > Grant> I had a Linux pty example running once upon a time. If "python > Grant> -u" doesn't work post again, and I'll try to find it. > > Would be helpful even if I don't need it for this task, as I've not been > able to find any simple examples on the net. (Maybe there's a recipe at > ActiveState, but Google didn't pick up anything with the search terms I was > using.) I'll try to dig it up. The application for which I was trying to use ptys needed to communication modem control/status line state info between master and slave (as well as parity and word-length settings), so I abandoned ptys when I found they only implement a small subset of the icotl's that are defined for tty devices. I've proposed enhancing the Linux pty driver so that it can actually be used to simulate a serial port, but the proposal has been ignored so far. -- Grant Edwards grante Yow! I'm definitely not at in Omaha! visi.com From rtw at freenet.co.uk Mon Dec 15 16:35:17 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Mon, 15 Dec 2008 15:35:17 -0600 Subject: How can I return a non-zero status result from a python script? References: <74b53da4-bf07-431b-898b-49977f7a685c@r36g2000prf.googlegroups.com> Message-ID: silverburgh.meryl at gmail.com wrote in news:74b53da4-bf07-431b-898b- 49977f7a685c at r36g2000prf.googlegroups.com in comp.lang.python: > Hi > > How can I return a non-zero status result from the script? Just do a > return 1? at the end? > >>> import sys >>> help( sys.exit ) Help on built-in function exit in module sys: exit(...) exit([status]) Exit the interpreter by raising SystemExit(status). If the status is omitted or None, it defaults to zero (i.e., success). If the status is numeric, it will be used as the system exit status. If it is another kind of object, it will be printed and the system exit status will be one (i.e., failure). >>> Rob. -- http://www.victim-prime.dsl.pipex.com/ From prologic at shortcircuit.net.au Tue Dec 2 04:20:59 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 2 Dec 2008 19:20:59 +1000 Subject: How to sort a list of file paths In-Reply-To: <2F0A3D19CA15C143B0688EC94220748720D1F89A61@SE-EX007.groupinfra.com> References: <2F0A3D19CA15C143B0688EC94220748720D1F89A61@SE-EX007.groupinfra.com> Message-ID: Hi Eriksson, It's nice to see people actually contribute what they've learned back to the community. Great problem, well thought out solution and congrats on the learning :) I can't say per say that I've actually run into a situation where I need to sort file paths in this way ... But if I do I'll be sure to use your function :) --JamesMills On Tue, Dec 2, 2008 at 6:36 PM, Eriksson, John wrote: > Hi, > > > > This weekend I had some problems to get a list containing file paths to be > sorted in a way that I could use. > > > > I also found a thread in this mailing list ( > http://mail.python.org/pipermail/python-list/2007-April/433590.html ) and > realized that others might be interested in a solution. > > > > So... here is my five cents regarding file path sorting: > > > > Problem description: > > > > You have a list containing some file names: > > > >>>> file_list = ["File2.txt","File1.txt","File10.txt"] > > > > If you sort this list in the conventional way you end up with a result like: > > > >>>> file_list.sort() > >>>> print file_list > > ['File1.txt','File10.txt','File2.txt'] > > > > Solution: > > > > Sort the list by splitting alphas and digits in to groups and compare them > separately. > > > > import re > > def true_alphanum_cmp(a,b): > > aa = re.findall(r'\d |\D ', a) > > bb = re.findall(r'\d |\D ', b) > > for i in range(min(len(aa),len(bb))): > > if aa[i].isdigit() and bb[i].isdigit(): > > c = cmp(int(aa[i]),int(bb[i])) > > else: > > c = cmp(aa[i],bb[i]) > > if c!=0: > > return c > > return cmp(len(aa),len(bb)) > > > > file_list = ["File2.txt","File1.txt","File10.txt"] > > file_list.sort(true_alphanum_cmp) > > > > If the formatting in this mail is messed up you can find the example at > http://arainyday.se/notebook/true_alphanum_cmp.php > > > > All comments and improvements are welcome! > > > > Best regards > > John Eriksson > > _________________________________________ > > > > Logica - Releasing your potential > > Tegsplan 2b > > 904 20 UME? > > Sweden > > > > T: +46 (0) 90 15 91 38 > > M: +46 (0) 70 366 16 77 > > E: john.eriksson at logica.com > > www.logica.se > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- -- -- "Problems are solved by method" From xahlee at gmail.com Tue Dec 9 18:19:47 2008 From: xahlee at gmail.com (Xah Lee) Date: Tue, 9 Dec 2008 15:19:47 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <4ridneQnkLrPkKDUnZ2dnUVZ8qbinZ2d@posted.plusnet> Message-ID: <986b6ea1-efba-4146-9704-5f9e3787c26a@a37g2000pre.googlegroups.com> On Dec 8, 4:07 am, Jon Harrop wrote: > s... at netherlands.com wrote: > > Well, its past 'tonight' and 6 hours to go till past 'tomorrow'. > > Where the hell is it Zah Zah? > > Note that this program takes several days to compute in Mathematica (even > though it takes under four seconds in other languages) so don't expect to > see a genuinely optimized version any time soon... ;-) Note that Jon's Mathematica code is of very poor quality, as i've given detailed analysis here: ? A Mathematica Optimization Problem http://xahlee.org/UnixResource_dir/writ/Mathematica_optimization.html I'm not sure he's intentionally making Mathematica look bad or just sloppiness. I presume it is sloppiness, since the Mathematica code is not shown in his public website on this speed comparison issue. (as far as i know) I suppose, he initialled tried this draft version, saw that it is too slow for comparsion, and probably among other reason he didn't include it in the speed comparison. However, in this thread about Mathematica 7, he wanted to insert his random gribe to pave roads to post his website books and url on OCml/f#, so he took out this piece of Mathematica to bad mouth it and bait. He ignored my paypal challenge, but it so happens that someone else paid me $20 to show a better code, and in the showdown, Jon went defensive that just make him looking like a major idiot. Xah ? http://xahlee.org/ ? From bearophileHUGS at lycos.com Mon Dec 8 09:37:30 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 8 Dec 2008 06:37:30 -0800 (PST) Subject: Public imports References: <9623b0a3-7053-41f1-b116-0cd5e54f39e9@v13g2000vbb.googlegroups.com> <8e382f56-3048-4fdc-881a-700416d29156@n41g2000yqh.googlegroups.com> Message-ID: <113b1ecc-58a4-46f8-8dd9-6a5b585bfa0b@l39g2000yqn.googlegroups.com> > D type system has several big holes, I meant "D module system", of course. Sorry. Bye, bearophile From Astley.lejasper at gmail.com Wed Dec 3 13:33:57 2008 From: Astley.lejasper at gmail.com (Astley Le Jasper) Date: Wed, 3 Dec 2008 10:33:57 -0800 (PST) Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> <126ba84a-0ea0-4a91-b7d2-89ed650e5d6c@d32g2000yqe.googlegroups.com> Message-ID: On 3 Dec, 16:41, Philip Semanchuk wrote: > On Dec 3, 2008, at 10:29 AM, Astley Le Jasper wrote: > > > I've included a switch to include or exclude theloggingto console. > > Whenloggingonly to file, the script runs fine. > > > Of course, I still don't understand whyduallogging, and specifically > > to the console, causes a problem and if anyone has any comments about > > thedualoutputloggingcode above then I'd still be happy to hear > > about it. > > Trying to write non-ASCII characters perchance? Errmmm ... that's kind of spoookey. I using UTF-8 encoding as I have a lot of European language characters. But would that cause a problem when running from crontab but not in the terminal? Go on then ... spill the beans. From steve at holdenweb.com Fri Dec 12 09:54:02 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Dec 2008 09:54:02 -0500 Subject: var or inout parm? In-Reply-To: <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> Message-ID: <49427B0A.50108@holdenweb.com> sturlamolden wrote: > On Dec 12, 3:08 pm, Marc 'BlackJack' Rintsch wrote: > >> No bug because a mutation *is* attempted. ``a += x`` calls `a.__iadd__` >> which *always* returns the result which is *always* rebound to the name >> `a`. Even with mutable objects where `__iadd__()` simply returns >> `self`! > > No, a mutation is not attempted, even if __iadd__() always returns a > value. If a rebinding of a member to the same member is attempted, the > tuple should not raise an exception. The tuple should check that it is > actually being *mutated* before it raises any exception. There is an > attempted write to the tuple, but not an attempted mutation of the > tuple. The tuple should tell the difference. Immutability does not > imply inwriteability, if the write operation changes nothing. But the > tuple raises an exception on any write attempt. > OK, so if you regard the current behavior as a bug explain how to modify the tuple's __iadd__ method and the coding of the INPLACE_ADD operator. At least in pseudocode. Criticism is easy. Now demonstrate that it's *informed* criticism. Enough of the "should". I am always suspicious of suggestions that say what the interpreter "should" or "should not" do. It makes it sound as though you can wave a magic wand to achieve the desired behavior. The interpreter "should not" have a GIL. The tuple "should" check that it is actually being mutated. How? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steven at REMOVE.THIS.cybersource.com.au Mon Dec 8 21:41:34 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 09 Dec 2008 02:41:34 GMT Subject: Calling function from a string References: <7bc1be6f-121e-409a-9e08-f2dd2a86f241@e25g2000vbe.googlegroups.com> Message-ID: On Mon, 08 Dec 2008 14:29:01 -0800, Chris Rebert wrote: > On Mon, Dec 8, 2008 at 2:23 PM, Robert Dailey > wrote: >> Hi, >> >> I have a string representing the name of a function in Python 3.0. How >> can I call the function name represented by this string *without* >> creating a mapping? > > Assuming the function is within scope: > > return_val = vars()[the_string](arguments, go, here) Or use eval("%s(arguments go here)" % the_string) (untested in Python 3, but should work) Are you aware of the great big enormous security hole you're creating if the_string is untrusted data? -- Steven From gagsl-py2 at yahoo.com.ar Fri Dec 26 09:12:37 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 26 Dec 2008 12:12:37 -0200 Subject: Socket recv function taking longer time References: Message-ID: En Fri, 26 Dec 2008 11:36:15 -0200, escribi?: > I have designed a recieving system in C. I have used the sockets > recv function. The problem I m facing is that the sending system does > not wait for the ACK(the amount of time it waits 4 the Ack is too less > as the recv takes more time to read the msg), it keeps on sending the > same msg again and again even before the recv func has read the whole > message and my recieving system gets hanged. How do I solve this. I don't understand the problem. If the receiving side is in C, I guess the sending side is written in Python? Then just wait for the ACK from the other side for a longer time... Or try to explain better what's your problem - posting some code would be good. -- Gabriel Genellina From rhf22 at mole.bio.cam.ac.uk Wed Dec 10 09:50:07 2008 From: rhf22 at mole.bio.cam.ac.uk (Rasmus Fogh) Date: Wed, 10 Dec 2008 14:50:07 +0000 (GMT) Subject: Rich Comparisons Gotcha Message-ID: Rhodri James wrote: > On Mon, 08 Dec 2008 14:24:59 -0000, Rasmus Fogh wrote: >> On the minus side there would be the difference between >> '__equal__' and '__eq__' to confuse people. > This is a very big minus. It would be far better to spell __equal__ in > such a way as to make it clear why it wasn't the same as __eq__, > otherwise > you end up with the confusion that the Perl "==" and "eq" operators > regularly cause. You are probably right, unfortunately. That proposal is unlikely to fly. Do you think my latest proposal, raising BoolNotDefinedError, has better chances? --------------------------------------------------------------------------- Dr. Rasmus H. Fogh Email: r.h.fogh at bioc.cam.ac.uk Dept. of Biochemistry, University of Cambridge, 80 Tennis Court Road, Cambridge CB2 1GA, UK. FAX (01223)766002 From python.list at tim.thechases.com Fri Dec 12 12:58:32 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 12 Dec 2008 11:58:32 -0600 Subject: newbie question... In-Reply-To: References: Message-ID: <4942A648.3020506@tim.thechases.com> > Im new at python and I just want to know if (and how) it is possible > to send parameters to a program. > > what I mean is that when we start python I can call a file that should > be run like this: python myfile.py > can I send additional parameters along with it? like::: python > myfile.py myVar1 myVar2 You're looking for sys.argv: tim at rubbish:~$ python - one two Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) [GCC 4.2.4 (Debian 4.2.4-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.argv ['-', 'one', 'two'] -tkc From mark.dufour at gmail.com Fri Dec 5 06:24:54 2008 From: mark.dufour at gmail.com (Mark Dufour) Date: Fri, 5 Dec 2008 12:24:54 +0100 Subject: ANN: Shed Skin 0.0.30, an experimental (restricted-)Python-to-C++ Compiler Message-ID: <8180ef690812050324j1dc6c570ib9644137bbc193c6@mail.gmail.com> Hi all, I have just released version 0.0.30 of Shed Skin, an experimental (restricted) Python-to-C++ compiler. Most importantly, this release adds (efficient) support for user-defined classes in generated extension modules, which should make it much easier to integrate compiled code within larger projects. More specifically, compiled classes can now be instantiated on the CPython side, and instances can be passed freely between CPython and Shed Skin without any conversion taking place. (Instances of builtin classes are still (recursively) copied, though, at the moment..) Another major improvement was contributed by FFAO: a new 'set' implementation, directly based on the CPython code. While I haven't tested it on many benchmarks, it is clear that is now much faster, and on one benchmark it even outperforms CPython on my system by about 35%. Other notable changes include complex number support, mapping None to NULL instead of 0 and printing it as 'None', as well as an important type inference fix. With support for user-defined classes in extension modules, it looks like all the major pieces are now there to do a 0.1 release. The only thing I'd really like to do before that, is to improve support for the 'os' module. Please let me know if you'd like to help out here! Hopefully, with many details out of the way, I can have another good look at type inference for 0.2.. Thanks, Mark. -- "One of my most productive days was throwing away 1000 lines of code" - Ken Thompson From rt8396 at gmail.com Sun Dec 21 16:40:47 2008 From: rt8396 at gmail.com (r) Date: Sun, 21 Dec 2008 13:40:47 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <494ea35c$0$12776$426a74cc@news.free.fr> Message-ID: <689c6f0f-f2a0-4978-b0d1-9ffdf5af73b7@r15g2000prh.googlegroups.com> Hey Bruno, Thanks for spelling it out for me :D From spooklight at gmail.com Sun Dec 14 16:51:20 2008 From: spooklight at gmail.com (uair01) Date: Sun, 14 Dec 2008 13:51:20 -0800 (PST) Subject: Output to file gets lost - don't know where to look ... References: <26a47940-c997-4da4-8f05-205b8d3001a8@d42g2000prb.googlegroups.com> Message-ID: > I will try the python program outside of IDLE. Yes, running the program from the Linux shell instead of from IDLE produces all output correctly. Now I'll have to look for a new simple development environment :-( I think I'll try SPE that has worked well for me ... From rt8396 at gmail.com Wed Dec 24 17:00:25 2008 From: rt8396 at gmail.com (r) Date: Wed, 24 Dec 2008 14:00:25 -0800 (PST) Subject: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> <9eae14b8-93d6-4c34-b7d3-56c27408b52f@a26g2000prf.googlegroups.com> Message-ID: <2725aa51-4c75-4a8f-8b74-9f36657522db@v4g2000vbb.googlegroups.com> On Dec 22, 6:55?pm, John Machin wrote: > On Dec 23, 10:24?am, r wrote: > > > Because my balls are so big i walk around bow-legged! > > Have you considered that your alleged testicular enormity may in fact > be an illusion caused by a hernia? John i see some troll rated your post with one star, so i rated it myself with 5. I actually thought it was quite amusing, and shows you yourself have a solid pair, unlike some others around here who's have not even dropped yet. :) From david.andrzejewski at gmail.com Tue Dec 2 16:34:15 2008 From: david.andrzejewski at gmail.com (DaveA) Date: Tue, 2 Dec 2008 13:34:15 -0800 (PST) Subject: Vista Compatibility Message-ID: <21331a9e-64d1-4090-a8c4-d2e3fd6f30f2@y18g2000yqn.googlegroups.com> There was a thread about this about a year ago, but I wanted to see if anyone could clarify this question for me - what is the first officially sanctioned version of Python that is known to be fully working under Windows Vista? The best I could find is some indications that point to 2.5 being the first. I'm asking because we have a Python 2.3.4 runtime for an application that we're now looking into running on Vista. Thanks! From bdesth.quelquechose at free.quelquepart.fr Tue Dec 30 16:12:31 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 30 Dec 2008 22:12:31 +0100 Subject: "return" in def In-Reply-To: <016969d3$0$6988$c3e8da3@news.astraweb.com> References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <40b1b762-459b-4d6f-91f0-0a6e68d233ae@a26g2000prf.googlegroups.com> <4d396242-13c9-4318-97ba-99f18564fbc5@o4g2000pra.googlegroups.com> <016969d3$0$6988$c3e8da3@news.astraweb.com> Message-ID: <495a9c6f$0$14467$426a74cc@news.free.fr> Steven D'Aprano a ?crit : (snip) > Avoiding early exits is an over-reaction to the Bad Old Days of spaghetti > code. Mostly, yes. It can also be a way to help avoiding "resource leaks" (memory or whatever) - just like try/finally blocks or the 'with' statement in Python. > But used wisely, early exists can simplify, not complicate, code. > > Consider the following: > > def find_ham(alist): > for item in alist: > if isinstance(item, Ham): > return item > raise ValueError('no ham found') > > > def find_spam(alist): > found_item = None > for item in alist: > if found_item is not None: > if isinstance(item, Spam): > found_item = item > if found_item is None: > raise ValueError('no spam found') > else: > return found_item > > The second version has double the number of lines of code of the first. And doesn't do the same thing (hint: you forgot a break statement). Also and FWIW, the "single exit" golden rule (hem) comes from languages without exception handling. So a fair comparison would be: def find_egg(alist): for item in alist: if isinstance(item, Egg): return item return None vs: def find_sausage(alist): found = None for item in alist: if isinstance(item, Sausage): found = item break return found Granted, this still doesn't make the second version better than the first !-) But: > I don't think the claim that the version with an early exit is more > complicated than the version without can justified. Certainly not in this simple (simplistic ?) example. Now in C or Pascal, functions tend to be much longer and complicated, thanks to all the gory details one has to take care of. Not that I'm advocating "no early return" as a "golden rule" - specially in Python where functions tend to be short and readable -, but there really are cases (depending on the language *and* concrete use case) where avoiding early returns makes for more readable and robust code. My 2 cents... From sjmachin at lexicon.net Tue Dec 30 17:57:44 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 30 Dec 2008 14:57:44 -0800 (PST) Subject: need help with list/variables References: <63b5acce-d566-48cb-abce-c00fd0e02a39@v39g2000pro.googlegroups.com> Message-ID: <05a4f4df-2e6c-4a36-ab06-31e10c9f2100@s9g2000prg.googlegroups.com> On Dec 31, 6:41?am, 5lvqbw... at sneakemail.com wrote: > On Dec 30, 11:31?am, wx1... at gmail.com wrote: > > > I have a list and would like to parse the list appending each list > > item to the end of a variable on a new line. > > > for instance > > > mylist = ['something\n', 'another something\n', 'something again\n'] > > > then parse mylist to make it appear in my variable in this format: > > > myvar = """ > > something > > another something > > something again""" > > > how would i go about setting a variable like this? > > I think you want to concatenate the three elements in your list and > then assign the resulting string to myvar. ?Strings that are defined > with tripple quotes still get the newline character as though they > were defined with double or single quotes and \n in them. > > >>> conc = lambda x,y: x[:] + y # concatenate 2 lists without side effects > >>> mylist = ['something\n', 'another something\n', 'something again\n'] > >>> myvar = reduce(conc, mylist) > >>> print myvar OTOH escapees from FORTRAN would prefer something like: TOT = '' for I in xrange(len(MYLIST)): TOT = TOT + MYLIST[I] FTNWRITE(6, '*', TOT) SNOpy, anyone? From rt8396 at gmail.com Mon Dec 22 15:56:05 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 12:56:05 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> <494febd1$0$20851$426a74cc@news.free.fr> Message-ID: <430191c4-6ab3-487c-a6f5-616d9dde5596@t26g2000prh.googlegroups.com> On Dec 22, 12:36?pm, Bruno Desthuilliers wrote: > As far as I'm concerned, I don't think Python is "superior" (OMG), I > think it's a good language that happens to fit my brain *and* solve more > than 80% of my programmer's needs. If you're not happy with Python's > perfs, please contribute, you are welcome. He is contributing, by bringing up the subject for debate. Volunteers exist on all levels, not just the people who write code for CPython. Every OOS project needs diversity. There is base code, maintenance code, tutorials, essays, promotion(even if you consider it fanboyism),etc, etc. """Every spoke on a wheel is just as important as all the rest""", Bruno. From sjmachin at lexicon.net Fri Dec 12 13:53:20 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 12 Dec 2008 10:53:20 -0800 (PST) Subject: (Very Newbie) Problems defining a variable References: Message-ID: On Dec 13, 4:50?am, Dennis Lee Bieber wrote: > On Fri, 12 Dec 2008 03:42:55 -0800 (PST), feb... at gmail.com declaimed the > following in comp.lang.python: > > > #!/usr/bin/python > > #Py3k, UTF-8 > > > bank = int(input("How much money is in your account?\n>>")) > > target = int(input("How much money would you like to earn each year? > > \n>>")) > > ? ? ? ? Just for my curiosity -- did Python 3.x (besides turning print into > a function) also change input() to behave as the old raw_input()? Yup. There've been some other tectonic plate shift effects, e.g.: xrange() -> range(); range() -> list(range()) dict.iteritems() -> dict.items(); dict.items() -> list(dict.items()) halfassci() -> repr(); repr() -> ascii() From marco at sferacarta.com Mon Dec 22 10:37:13 2008 From: marco at sferacarta.com (Marco Mariani) Date: Mon, 22 Dec 2008 16:37:13 +0100 Subject: Python's popularity In-Reply-To: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: walterbyrd wrote: > I have read that python is the world's 3rd most popular language, and > that python has surpassed perl in popularity, but I am not seeing it. In 20 days, you've gone from trying to import a module by using: > load "test.py" to questioning the popularity of python. You have many other subject you want to enlighten us about, I suppose? Cause I wonder what you'll come up with, next. From deets at nospam.web.de Thu Dec 4 09:58:38 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 04 Dec 2008 15:58:38 +0100 Subject: Python Runtime Method Call Binding References: Message-ID: <6pq9guF9cb20U1@mid.uni-berlin.de> k3xji wrote: > Hi, > > Is there a way to hook a function call in python? I know __getattr__ > is doing for variables, it is giving us a chance before a field is > initialized. Do we have same functionality for methods? > > Example: > > class Foo(object): > def __call_method__(self, ...) # just pseudo > print 'A method is called in object...' > > f = Foo() > f.test_method() > > I think you understand my point. The special method __call__ is your friend. class SomethingCallable(object): def __call__(self): print "I'm called, and you not!" SomethingCallable()() Diez From zhushenli at gmail.com Wed Dec 3 22:20:33 2008 From: zhushenli at gmail.com (Davy) Date: Wed, 3 Dec 2008 19:20:33 -0800 (PST) Subject: time.sleep() and Tkinter after()? Message-ID: <03613d37-ca4f-4962-bce2-eea0a3f65952@r15g2000prd.googlegroups.com> Hi all, I have used Tkinter after() to do loop update GUI in my previous post. See http://groups.google.com/group/comp.lang.python/browse_thread/thread/6b616abc236c345b/7df7684d33c969c5#7df7684d33c969c5 And I tried to change after() to time.sleep(), but it seems doesn't work at all, the Queue send and receive data properly, but the GUI didn't even appear? //-----code changed----- def draw_canvas_loop(canvas_b): while (True): board = data_queue.get(block = True, timeout=2) print 'get', data_queue.qsize() draw_canvas(board, canvas_b, x, y, block_width, block_height) time.sleep(0.3) ##canvas_b.after(300, lambda:draw_canvas_loop(canvas_b)) //-------------------------------- So, can I use time.sleep() in GUI application? Or Tkinter scheduler just ignore the sleep() function? And if I use after(), will the code form a recursive function call, and the memory usage will boost as the program goes (I have watched the task manager in WinXP and find the python.exe eat more and more memory...). //------code----------- def draw_canvas_loop(canvas_b): board = data_queue.get(block = True, timeout=1) print 'get', data_queue.qsize() draw_canvas(board, canvas_b, x, y, block_width, block_height) canvas_b.after(300, lambda:draw_canvas_loop(canvas_b)) //------------------------- Best regards, Davy From zaz600 at gmail.com Thu Dec 25 08:55:16 2008 From: zaz600 at gmail.com (NoName) Date: Thu, 25 Dec 2008 05:55:16 -0800 (PST) Subject: SyntaxError: encoding problem: with BOM References: <6res8tF1do1sU1@mid.uni-berlin.de> <400f176b-bd9a-4f26-b01b-1aa7c7dcf5ac@z6g2000pre.googlegroups.com> <6rf6m1F1e0f8U1@mid.uni-berlin.de> Message-ID: <26e21f3f-ded1-48ca-8897-2ebd05dd07ad@w39g2000prb.googlegroups.com> > NoName, Asking people to download a zip file from a website written in > a language and character set that they probably are not familiar with > is liable to make them rather nervous and not bother. It's not a good > way to ask for help. sorry:) Now i know where problem. But i dont know how to solve it. Error ---- C:\Documents and Settings\Ra\??????? ????>11.py File "", line 1 SyntaxError: encoding problem: with BOM No error ---- C:\Documents and Settings\Ra\??????? ????>python 11.py test Error when russian symbols in full path to py-script. Is it Python bug? or i need to modify some registry keys? OS: WinXP SP3 Russian. Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32 From benjamin.kaplan at case.edu Sun Dec 14 23:44:37 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 14 Dec 2008 23:44:37 -0500 Subject: Python is slow In-Reply-To: References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> Message-ID: On Sun, Dec 14, 2008 at 11:38 PM, cm_gui wrote: > > hahaha, do you know how much money they are spending on hardware to > make > youtube.com fast??? Obviously not enough to get to the point where it's cheaper to have the programmers write C code. And the hardware is more for handling the intense traffic that YouTube gets, not for speeding up the site. > > > > By the way... I know of a very slow Python site called YouTube.com. In > > fact, it is so slow that nobody ever uses it. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dstanek at dstanek.com Thu Dec 25 19:35:48 2008 From: dstanek at dstanek.com (David Stanek) Date: Thu, 25 Dec 2008 19:35:48 -0500 Subject: Exec inside a class method to call other class methods? In-Reply-To: <47c890dc0812251624m7e1c5e55rb538996a52d56675@mail.gmail.com> References: <4953CF57.8080905@sympatico.ca> <20081226001641.GA22946@sdf.lonestar.org> <47c890dc0812251624m7e1c5e55rb538996a52d56675@mail.gmail.com> Message-ID: You won't need the dictionary at all if each type has a parse method. On 12/25/08, Chris Rebert wrote: > On Thu, Dec 25, 2008 at 4:16 PM, J. Clifford Dyer > wrote: > >> and so forth. Then your if/else chain can be pulled out to the place >> where you instantiate each field: >> >> if data_type=='address': >> field=AddressDataField(data) >> elif data_type=='due_date': >> field=DueDateDataField(data) >> else: >> field = DataField(data) >> > > And then you use a dictionary of data_type to class to get rid of the > if-else chain altogether: > > type2klass = {'address' : AddressDataField, 'due_date' : DueDateDataField} > #etc > Klass = type2klass.get(data_type, DataField) #use DataField as fallback > default > field = Klass(data) > > Merry Christmas, > Chris > > -- > Follow the path of the Iguana... > http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > -- Sent from my mobile device David http://www.traceback.org From stef.mientki at gmail.com Thu Dec 11 13:12:32 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 11 Dec 2008 19:12:32 +0100 Subject: Mathematica 7 compares to other languages In-Reply-To: <20081211180751.4139f2ec@usenot.de> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <87r64f9sma.fsf@rudin.co.uk> <20081211180751.4139f2ec@usenot.de> Message-ID: <49415810.9010103@gmail.com> Andreas Waldenburger wrote: > On Thu, 11 Dec 2008 05:40:45 +0000 Paul Rudin > wrote: > > >> "Dotan Cohen" writes: >> >> >>> 2008/12/10 : >>> >>>> Ruby: >>>> >>>> def norm a >>>> s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) >>>> a.map{|x| x/s} >>>> end >>>> >>> If someone doesn't counter with a Python one-liner then I'm going to >>> port that to brainfuck. >>> >> from numpy.linalg import norm >> >> :) >> > > This is one line of Python code alright, but it's not a "one-liner" in > the "computes the a normalized vector"-sense (which was the original > challenge, if there ever was one). > > If anything, you are now ready to compute the *norm* of a vector in a > subseqent line. (Or, if you must, after a semicolon on the same line.) > > Couldn't we assume that when you doing these kinds of math, there's always import numpy or from numpy import * is always at the start of the program, so it doesn't belong to the functional code ? And for those who use VPython (and thus needs " from visual import *" ) can simply do a = norm ( v ) cheers, Stef From taskinoor.hasan at csebuet.org Tue Dec 2 00:24:29 2008 From: taskinoor.hasan at csebuet.org (Taskinoor Hasan) Date: Tue, 2 Dec 2008 11:24:29 +0600 Subject: Do more imported objects affect performance In-Reply-To: <1be78d220812010621u51dead9dnbaa0b4c8c9414362@mail.gmail.com> References: <1be78d220812010621u51dead9dnbaa0b4c8c9414362@mail.gmail.com> Message-ID: <79153a2e0812012124o7401df57m4ac21dfe37c2ec5@mail.gmail.com> On Mon, Dec 1, 2008 at 8:21 PM, Filip Gruszczy?ski wrote: > I see. Thanks for a really good explanation, I like to know, how to do > things in the proper way :) I always prefer to use import module and then use module.function. The reason is simple. It makes the code more readable and maintainable. > > > 2008/12/1 Nick Craig-Wood : > > Rafe wrote: > >> On Dec 1, 7:26?am, "Filip Gruszczy?ski" wrote: > >> > I have following question: if I use > >> > > >> > from module import * > >> > > >> > instead > >> > > >> > from module import Class > >> > > >> > am I affecting performance of my program? I believe, that all those > >> > names must be stored somewhere, when they are imported and then > >> > browsed when one of them is called. So am I putting a lot of "garbage" > >> > to this storage and make those searches longer? > >> > >> Why use it if you don't need it? Your post implies a choice and the > >> '*' import can really make things muddy if it isn't actually necessary > >> (rare). Why not just import the module and use what you need? It is > >> way easier to read/debug and maintains the name-space. > > > > Importing the module is actualy slower... If you import the name into > > your namespace then there is only one lookup to do. If you import the > > module there are two. > > > > $ python -m timeit -s 'from timeit import Timer' 'Timer' > > 10000000 loops, best of 3: 0.0784 usec per loop > > > > $ python -m timeit -s 'import timeit' 'timeit.Timer' > > 1000000 loops, best of 3: 0.243 usec per loop > > > > I'm not suggestion you should ever use "from module import *" only > > ever import the things you actually need, eg > > "from module import MyClass, my_function" > > > > And here is the test again, actually calling something with the same > > difference in execution speed :- > > > > $ python -m timeit -s 'from os import nice' 'nice(0)' > > 1000000 loops, best of 3: 1.21 usec per loop > > > > $ python -m timeit -s 'import os' 'os.nice(0)' > > 1000000 loops, best of 3: 1.48 usec per loop > > > > -- > > Nick Craig-Wood -- http://www.craig-wood.com/nick > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > Filip Gruszczy?ski > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eric at ericaro.net Fri Dec 5 10:44:21 2008 From: eric at ericaro.net (eric) Date: Fri, 5 Dec 2008 07:44:21 -0800 (PST) Subject: A more pythonic way of writting References: <35d176ed-df5f-46b4-8321-4814fcc4398c@f3g2000yqf.googlegroups.com> Message-ID: <8de7622d-28a7-4f96-9fb0-21cda357dcf3@r36g2000prf.googlegroups.com> On Dec 5, 3:44?pm, "Mark Tolonen" wrote: > "eric" wrote in message > > news:35d176ed-df5f-46b4-8321-4814fcc4398c at f3g2000yqf.googlegroups.com... > > > def flag(IGNORECASE=False, LOCALE=False, MULTILINE=False, > > DOTALL=False, UNICODE=False, VERBOSE=False): > > ? ?vals = [IGNORECASE, LOCALE, MULTILINE, DOTALL, UNICODE, VERBOSE] > > ? ?filtered = map( lambda m:m[1],filter( lambda m: m[0], > > zip(vals,'iLmsux'))) > > ? ?return '?'+''.join( filtered ?) > > ? ? filtered = [c for c,v in zip('iLmsux',vals) if v] > > -Mark thank you very much ! great ! I can't get used to this late 'if' syntax ! @Gerard nice hypercube function. But I'll keep with my implementation : I like to believe that the less the 'debug pointer' stands in the python code, the fastest the code is (or is potentially) I keep thinking that def hypercube(ndims) : for i in range(1< References: <38f9c4ba-d96d-47e1-b718-562bdc6718e9@t26g2000prh.googlegroups.com> Message-ID: <4943D9AB.7040006@tim.thechases.com> > Any special reasons? Because it is there (at least on my Debian box)? tim at rubbish:~$ python Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) [GCC 4.2.4 (Debian 4.2.4-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.strftime('%c') 'Sat Dec 13 09:35:03 2008' >>> time.strftime('%e') '13' Taken from[1] The full set of format codes supported varies across platforms, because Python calls the platform C library's strftime() function, and platform variations are common. So if your underlying C implementation of strftime() supports "%e", then Python will. My guess is that the same applies to time.strftime as it does to datetime.strftime The docs list ones that are fairly cross-platform. However, it would seem that not all platforms support "%e" -tkc [1] http://docs.python.org/library/datetime.html#module-datetime From steve at holdenweb.com Sun Dec 28 23:31:42 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 28 Dec 2008 23:31:42 -0500 Subject: ftp design question In-Reply-To: <74706983-5198-436b-b0ca-b0246a41c67e@v5g2000prm.googlegroups.com> References: <74706983-5198-436b-b0ca-b0246a41c67e@v5g2000prm.googlegroups.com> Message-ID: <495852AE.9030701@holdenweb.com> nemo wrote: > Hi,all. > I'm on a toy ftp project and I want it to be convinient for the user > to cancel an undergoing downloading while continue others. The > following code explains: > for file in download_files: > self.ftp.retrbinary('RETR '+file, fileHandler) > Thers seems not a solid way to cancel this transfer and I considered > thread or process but I can't handle this correctly. > Thread: I can't kill the thread in another thread, so... > Process: There seems something wrong(raise an EOFError exception) when > I use Process(target = download_fun, args = (dir,)) for each > downloading after connection built. > Some suggestions? How about for file in download_files: try: self.ftp.retrbinary('RETR %s' % file, fileHandler) except KeyboardInterrupt: print file, "transfer abandoned" Then you can cancel a single file transfer with Ctrl/C. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steve at REMOVE-THIS-cybersource.com.au Sun Dec 14 04:47:50 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Dec 2008 09:47:50 GMT Subject: Optimizing methods away or not? References: <0154b041$0$6988$c3e8da3@news.astraweb.com> <6qk1dhFcr01gU1@mid.uni-berlin.de> Message-ID: <0154cdc2$0$6988$c3e8da3@news.astraweb.com> On Sun, 14 Dec 2008 09:19:45 +0000, Marc 'BlackJack' Rintsch wrote: > On Sun, 14 Dec 2008 07:41:55 +0000, Steven D'Aprano wrote: > >> I have a class with a method meant to verify internal program logic >> (not data supplied by the caller). Because it is time-consuming but >> optional, I treat it as a complex assertion statement, and optimize it >> away if __debug__ is false: ... >> What do others >> think? Which do you consider better design? > > None of it. Why not simply: > > class Parrot: > def __init__(self, *args): > print "Initialising instance..." > assert self._verify() > > def _verify(self): > print "Verifying..." > return None For your method to work, I'd have to have _verify return a boolean flag instead of None, because assert None always fails. > If you compile with -O the ``assert`` is optimized away. But you still > can call `_verify()` at specific points even in optimized code if you > want or need. That's a reasonable approach, if my use-case was for the caller to call the verify method. It's not: it's verifying my program logic rather than the caller's data, and it's only meaningful to do that verification at initialisation time. -- Steven From castironpi at gmail.com Mon Dec 29 21:35:21 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 18:35:21 -0800 (PST) Subject: get method References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> <4819de67-72dc-415c-b4c8-2353581c2bc7@r2g2000vbp.googlegroups.com> <0169782e$0$6988$c3e8da3@news.astraweb.com> Message-ID: <1a88bbb6-605a-4035-8af0-c4db5f07e945@d42g2000prb.googlegroups.com> On Dec 29, 8:02?pm, Steven D'Aprano wrote: > On Mon, 29 Dec 2008 17:38:36 -0800, Ross wrote: > > On Dec 29, 8:07?pm, Scott David Daniels wrote: > >> Ross wrote: > >> > ... Use get to write histogram more concisely. You should be able to > >> > eliminate the if statement. > > >> > def histogram(s): > >> > ? ?d = dict() > >> > ? ?for c in s: > >> > ? ? ? ? ? ?d[c]= d.get(c,0) > >> > ? ?return d > > >> > This code returns a dictionary of all the letters to any string s I > >> > give it but each corresponding value is incorrectly the default of 0. > >> > What am I doing wrong? > > >> How is this code supposed to count? > > >> --Scott David Daniels > >> Scott.Dani... at Acm.Org > > > I realize the code isn't counting, but how am I to do this without using > > an if statement as the problem instructs? snip > So what you need is: > > * set d[c] to whatever d[c] already is plus one, or 0 plus one if it > isn't already there. > > It's a two character change to one line. Let us know if you still can't > see it. That's actually really sophisticated. Steven is being really clever here, by writing a number in an unusual way. He said: * set d[c] to whatever d[c] already is plus one, or 0 plus one if it isn't already there. It is the same as: * set d[c] to whatever d[c] already is plus one, or one if it isn't already there. Side-by-side. Perhaps you will learn his secret someday. It has to do with 0+1=1. Armed with it, he has: something something +1, something something something +1 Which brings us (to): ( something something, something something something ) +1 Three cheers for thinking. From castironpi at gmail.com Mon Dec 29 08:40:42 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 05:40:42 -0800 (PST) Subject: Get a list of functions in a file References: Message-ID: <44e9ff55-767c-4b61-a645-4e930fb255c7@t39g2000prh.googlegroups.com> On Dec 29, 3:50?am, "Chris Rebert" wrote: > On Sun, Dec 28, 2008 at 11:26 PM, member Basu wrote: > > I'm putting some utility functions in a file and then building a simple > > shell interface to them. Is their some way I can automatically get a list of > > all the functions in the file? I could wrap them in a class and then use > > attributes, but I'd rather leave them as simple functions. > > Assuming you've already imported the module as 'mod': > > func_names = [name for name in dir(mod) if callable(getattr(mod, name))] > funcs = [getattr(mod, name) for name in dir(mod) if > callable(getattr(mod, name))] > > Note that such lists will also include classes (as they too are > callable). There are ways of excluding classes (and other objects that > implement __call__), but it makes the code a bit more complicated. No, not in general. It's a weakness of one of the strengths of Python. For instance, if you define a function in a string, or return one from another function, there's no way to get at it. If you do want to import it, you can put any executable code inside an 'if __name__== "__main__"' block, so it won't get executed while you're trying to index/catalog it. If you're interested in something more hard-core, you might like the 'tokenize' module. And I think the pattern you're looking for is 'every "def" outside a string, and even some in one.' P.S. Did not receive the original message on Google Groups. From walterbyrd at iname.com Sun Dec 7 14:22:23 2008 From: walterbyrd at iname.com (walterbyrd) Date: Sun, 7 Dec 2008 11:22:23 -0800 (PST) Subject: Is 3.0 worth breaking backward compatibility? Message-ID: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> IMO: breaking backward compatibility is a big deal, and should only be done when it is seriously needed. Also, IMO, most of, if not all, of the changes being made in 3.0 are debatable, at best. I can not think of anything that is being changed that was really a "show stopper" anyway. At best, I am a casual python user, so it's likely that I am missing something. From python.list at tim.thechases.com Wed Dec 31 10:48:29 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 31 Dec 2008 09:48:29 -0600 Subject: change only the nth occurrence of a pattern in a string In-Reply-To: <0scs26-7a5.ln1@rama.fbx.proxad.net> References: <0scs26-7a5.ln1@rama.fbx.proxad.net> Message-ID: <495B944D.8020302@tim.thechases.com> > I would like to change only the nth occurence of a pattern in > a string. The problem with "replace" method of strings, and > "re.sub" is that we can only define the number of occurrences > to change from the first one. > >>>> v="coucou" >>>> v.replace("o","i",2) > 'ciuciu' >>>> import re >>>> re.sub( "o", "i", v,2) > 'ciuciu' >>>> re.sub( "o", "i", v,1) > 'ciucou' > > What is the best way to change only the nth occurence > (occurrence number n)? Well, there are multiple ways of doing this, including munging the regexp to skip over the first instances of a match. Something like the following untested: re.sub("((?:[^o]*o){2})o", r"\1i", s) However, for a more generic solution, you could use something like import re class Nth(object): def __init__(self, n_min, n_max, replacement): #assert n_min <= n_max, \ # "Hey, look, I don't know what I'm doing!" if n_max > n_min: # don't be a dope n_min, n_max = n_max, n_min self.n_min = n_min self.n_max = n_max self.replacement = replacement self.calls = 0 def __call__(self, matchobj): self.calls += 1 if self.n_min <= self.calls <= self.n_max: return self.replacement return matchobj.group(0) s = 'coucoucoucou' print "Initial:" print s print "Just positions 3-4:" print re.sub('o', Nth(3,4,'i'), s) for params in [ (1, 1, 'i'), # just the 1st (1, 2, 'i'), # 1-2 (2, 2, 'i'), # just the 2nd (2, 3, 'i'), # 2-3 (2, 4, 'i'), # 2-4 (4, 4, 'i'), # just the 4th ]: print "Nth(%i, %i, %s)" % params print re.sub('o', Nth(*params), s) > Why this default behavior? Can't answer that one, but with so many easy solutions, it's not been a big concern of mine. -tkc From kwmsmith at gmail.com Wed Dec 17 16:59:18 2008 From: kwmsmith at gmail.com (Kurt Smith) Date: Wed, 17 Dec 2008 15:59:18 -0600 Subject: getting object instead of string from dir() In-Reply-To: <477b9c2e-a0ab-4b26-b643-4a9369c2aaac@r2g2000vbp.googlegroups.com> References: <477b9c2e-a0ab-4b26-b643-4a9369c2aaac@r2g2000vbp.googlegroups.com> Message-ID: On Wed, Dec 17, 2008 at 1:52 PM, Rominsky wrote: > On Dec 17, 10:59 am, Christian Heimes wrote: > > Rominsky schrieb: > > > > > I am trying to use dir to generate a list of methods, variables, etc. > > > I would like to be able to go through the list and seperate the > > > objects by type using the type() command, but the dir command returns > > > a list of strings. When I ask for the type of an element, the answer > > > is always string. How do I point at the variables themselves. A > > > quick example is: > > > > > a = 5 > > > b = 2.0 > > > c = 'c' > > > > > lst = dir() > > > > > for el in lst: > > > print type(el) > > > > for name, obj in vars().iteritems(): > > print name, obj > > > > Christian > > I do have some understanding of the pythonic methodology of > programming, though by far I still don't consider myself an expert. > The problem at hand is that I am coming from a matlab world and trying > to drag my coworkers with me. I have gotten a lot of them excited > about using python for this work, but the biggest gripe everytime is > they want their matlab ide. I am trying to experiment with making > similar pieces of the ide, in particular I am working on the workspace > window which lists all the current variables in the namespace, along > with their type, size, value, etc.... I am trying to create a python > equivalent. I can get dir to list all the variables names in a list > of strings, but I am trying to get more info them. hence the desire Are you familiar with the ipython console? http://ipython.scipy.org/moin/ It is quite powerful; in particular, the %who and %whos 'magic functions' will do much of what you'd like: [501]$ ipython Python 2.5.2 (r252:60911, Jul 31 2008, 17:31:22) Type "copyright", "credits" or "license" for more information. IPython 0.8.1 -- An enhanced Interactive Python. ? -> Introduction to IPython's features. %magic -> Information about IPython's 'magic' % functions. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: a = 'foo' In [2]: b = 'bar' In [3]: c = 5.234 In [4]: import os In [5]: d = os In [6]: whos Variable Type Data/Info ------------------------------ a str foo b str bar c float 5.234 d module os module In [7]: import numpy as np In [8]: aa = np.zeros(100) In [9]: whos Variable Type Data/Info ------------------------------- a str foo aa ndarray 100: 100 elems, type `float64`, 800 bytes b str bar c float 5.234 d module np module ages/numpy/__init__.pyc'> os module And I trust you've heard of numpy, scipy and matplotlib? http://www.scipy.org/ http://matplotlib.sourceforge.net/ http://numpy.scipy.org/ Cheers, Kurt -------------- next part -------------- An HTML attachment was scrubbed... URL: From Scott.Daniels at Acm.Org Mon Dec 15 14:01:02 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 15 Dec 2008 11:01:02 -0800 Subject: Rename of .mdb file -- lock In-Reply-To: <4049f296-2a04-4eee-9f09-aa37a973a8cf@r40g2000yqj.googlegroups.com> References: <4049f296-2a04-4eee-9f09-aa37a973a8cf@r40g2000yqj.googlegroups.com> Message-ID: noydb wrote: > I have the code below, which unzips a zipfile containing only one > file. Once it is unzipped, I want to rename the file based on a user > provided name. But I get this (WindowsError: [Error 32] The process > cannot access the file because it is being used by another process) > error, which does not make sense to me as no other apps are open. > Any suggestions? Others have told you the reason you are currently having problems. You should also be aware that Windows can at "random" times be opening the new file in order to either index it or virus scan it, and it may fail to rename during that period. So, a failure should retry in a second a couple of times before giving up. This is my understanding, but someone deeply familiar with Windows internals might reveal that I am operating on older information. --Scott David Daniels Scott.Daniels at Acm.Org From claird at lairds.us Mon Dec 29 09:26:36 2008 From: claird at lairds.us (Cameron Laird) Date: Mon, 29 Dec 2008 14:26:36 +0000 Subject: Windows SSH (remote execution of commands) - Python Automation References: <7FAD6FCE52421841A11B441DEF3A88CA01F09006@ZMY16EXM70.ds.mot.com> Message-ID: In article , Tino Wildenhain wrote: . . . >> I am looking for some information on how to automate remote login to a >> UNIX machine using ssh from a windows XP box. >> >> Possible way: >> >> 1. Use putty (or any other ssh client from windows XP). -- Can be >> automated with command line parameters. The problem is that I am able to >> login - Putty window opens up as well. But obviously I am unable to run >> any commands in that. I need to find something like a handle to that >> Putty window so that I can execute commands there. > >Obviously putty is one (of several) terminal emulators (or in short gui >clients) for ssh protocol. This means they are made for interactive work >with mouse and keyboard rather then for command automation. > >Its easy if you just use one of the many command line ssh clients. You >can use os.popen() and friends or the command module to work with them. > >There is also another solution: > >http://www.lag.net/paramiko/ > >which implements the ssh protocol in python so you can do more and >have finer control over the processes and channels (for example >file transfer and command control w/o resort to multiple connections) > >This is a little bit harder of course. > >Also, sometimes its more easy and relieable to just use cron on unix >side. This works much much better then Task scheduler on windows btw. . . . Good advice, all around. I'll reinforce a few of your points: A. I entirely agree that Mr. Raghu would likely do well to learn about cron(8); automation of the sort that seems to be involved here is generally more convenient with standard Linux tools than from the Windows side. B. One of the Windows command-line automaters to which you alluded is a sibling of putty: plink . It shares configuration and infrastructure elements with putty, and might require the least adjustment. C. 'You think paramiko is harder? I find it a nice solution in many situations. From noZ.spamZ at ZZ.ZsvpZ.com Mon Dec 15 18:33:55 2008 From: noZ.spamZ at ZZ.ZsvpZ.com (Michel Claveau - NoSpam SVP ; merci) Date: Tue, 16 Dec 2008 00:33:55 +0100 Subject: Problem Python 2.6.1 vs 2.6 & pyWin32 In-Reply-To: <4946D09F.6050300@v.loewis.de> References: <4946754f$0$19000$426a74cc@news.free.fr> <4946D09F.6050300@v.loewis.de> Message-ID: <4946ea05$0$31992$426a74cc@news.free.fr> Hi! Thank you very much for your answer. I appreciate many to receive an answer of somebody as you. But I, always, install Python 2.6.1 "for all users" (and, on Vista, UAC is always deactivated). After some tests, the problem seems a bit more complex: call the Python-COM-servers run OK, from Python-Scripts. But it is not possible from others languages (but, I only try JScript, VBScript, JS.Net, ObjectPAL, Autoit). For the moment, I back my install procedures to Python 2.6 ; and, I hope a "global" solution for 2.6.1 @-salutations -- Michel Claveau From bignose+hates-spam at benfinney.id.au Mon Dec 15 06:29:29 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 15 Dec 2008 22:29:29 +1100 Subject: alt.possessive.its.has.no.apostrophe References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> Message-ID: <87myexfzhi.fsf@benfinney.id.au> James Stroud writes: > Ben Finney wrote: > > Or, more generally: Pronouns, which are different in just about > > every other way from other nouns, are different in this way also. > > Is that about right? > > Can we start talking about python again? Not with this thread subject :-) -- \ ?We are not gonna be great; we are not gonna be amazing; we are | `\ gonna be *amazingly* amazing!? ?Zaphod Beeblebrox, _The | _o__) Hitch-Hiker's Guide To The Galaxy_, Douglas Adams | Ben Finney From malkarouri at gmail.com Thu Dec 4 15:05:30 2008 From: malkarouri at gmail.com (malkarouri) Date: Thu, 4 Dec 2008 12:05:30 -0800 (PST) Subject: Why shouldn't you put config options in py files References: Message-ID: On 4 Dec, 19:35, HT wrote: > A colleague of mine is arguing that since it is easy to write config like: > > FOO = {'bar': ('a': 'b'), 'abc': ('z': 'x')} > > in config.py and just import it to get FOO, but difficult to achieve the > same using an ini file and ConfigParser, and since Python files are just > text, we should just write the config options in the Python file and > import it. > > I can think of lots of arguments why this is a bad idea, but I don't > seem to be able to think of a really convincing one. > > Anyone? Some people actually do that. IIRC, ipython is now configured using a python module. The idea, however, is dangerous from a security viewpoint. Because anybody can edit his configuration .py file, you are in effect injecting arbitrary code into your program. Think that your program starts with raw_input() and then goes on the execute whatever you get. Same problems with SQL injection for example. So people prefer to have a much more controlled environment for configuration. In particular, the idea of using json as Chris said should become a best practice now we have the json module. Regards, Muhammad Alkarouri From bearophileHUGS at lycos.com Fri Dec 5 09:52:11 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 5 Dec 2008 06:52:11 -0800 (PST) Subject: Small problem with Psyco Message-ID: <1d71a6ed-4d96-4e86-983c-a54e23fcf158@t3g2000yqa.googlegroups.com> I post it here because I am using a Psyco version that was compiled by people here. I am using Python 2.6.1, on Win, with Psyco (1, 6, 0, 'final', 0). This minimized code: from psyco.classes import psyobj class Bar(psyobj): def __init__(self, baz): pass b = Bar(0) Produces: C:\...\test.py:5: DeprecationWarning: object.__new__() takes no parameters b = Bar(0) Bye, bearophile From prologic at shortcircuit.net.au Thu Dec 18 20:30:33 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Dec 2008 11:30:33 +1000 Subject: Factoring Polynomials In-Reply-To: References: <269523e2-eba9-4b6b-b0fb-c5a7deb3ed76@o4g2000pra.googlegroups.com> Message-ID: UPDATE: jmills at atomant:~/tmp$ cat polycalc.py #!/usr/bin/env python from math import sqrt def f(a, b, c): if (b**2 - (4 * a * c)) < 0: return None, None # Can't solve x1 = -b - (sqrt(b**2 - (4 * a * c)) / (2 * a)) x2 = -b + (sqrt(b**2 - (4 * a * c)) / (2 * a)) return x1, x2 print "Polynomial Solver..." print while True: a = float(raw_input("a: ")) b = float(raw_input("b: ")) c = float(raw_input("c: ")) x = f(a, b, c) if None in x: print "Can't solve!" else: print "x = (%0.2f, %0.2f)" % x jmills at atomant:~/tmp$ ./polycalc.py Polynomial Solver... a: 1 b: 8 c: 5 x = (-11.32, -4.68) From prologic at shortcircuit.net.au Wed Dec 3 09:27:19 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 4 Dec 2008 00:27:19 +1000 Subject: generating a liste of characters In-Reply-To: References: Message-ID: On Thu, Dec 4, 2008 at 12:18 AM, Yves Dorfsman wrote: > Is there any built in way to generate a list of characters, something > along the line of range('a'-'z') ? > > Right now I am using: > > chars = [ chr(l) for l in range(0x30, 0x3a) ] # 0 - 9 > chars += [ chr(l) for l in range(0x41, 0x5b) ] # A - Z > chars += [ chr(l) for l in range(0x61, 0x7b) ] # a - z > > Is there a better, more straight forward way of doing that ? >>> from string import ascii_letters, digits >>> chars = ascii_letters + digits >>> chars 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' >>> cheers James -- -- -- "Problems are solved by method" From xahlee at gmail.com Tue Dec 9 23:36:28 2008 From: xahlee at gmail.com (Xah Lee) Date: Tue, 9 Dec 2008 20:36:28 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <9ecfa224-ce8f-44e9-abca-008314f44e87@40g2000prx.googlegroups.com> Message-ID: <501d76b2-45d1-4475-8d88-e0e51e19fc10@q26g2000prq.googlegroups.com> Jon Harrop moron wrote: > Only for trivial input and not for the challenge you were given. what challenge? > That code is evaluated once to build the scene. There is no point in > optimizing it. The point is optimizing your incompetence. > That performance issue only affects trivial problems and, in particular, > does not affect the problem you were trying to solve. solve your mom? Xah ? http://xahlee.org/ ? From cjw at ncf.ca Sat Dec 6 09:20:42 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 06 Dec 2008 09:20:42 -0500 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: <493A8A3A.6060203@ncf.ca> Daniel Fetchinson wrote: > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html > > The proposal is to allow this: > > class C: > def self.method( arg ): > self.value = arg > return self.value > > instead of this: > > class C: > def method( self, arg ): > self.value = arg > return self.value > > I.e. explicit self stays only the syntax is slightly different and may > seem attractive to some. As pointed out by Guido classmethods would > work similarly: > > class C: > @classmethod > def cls.method( arg ): > cls.val = arg > return cls.val > > The fact that Guido says, > > "Now, I'm not saying that I like this better than the status quo. But > I like it a lot better than [...] but it has the great advantage that > it is backward compatible, and can be evolved into a PEP with a > reference implementation without too much effort." > > shows that the proposal is viable. > > I'd like this new way of defining methods, what do you guys think? > Anyone ready for writing a PEP? > > Cheers, > Daniel > The quoted blogspot is not available. I like the idea but I don't see how explicit and implicit can co-exist. Version 3.0 is the time to introduce the enhancement. Colin W. From akineko at gmail.com Mon Dec 22 12:57:08 2008 From: akineko at gmail.com (akineko) Date: Mon, 22 Dec 2008 09:57:08 -0800 (PST) Subject: 64-bit / 128-bit data element type for array? Message-ID: Hello everyone, I need to handle binary files that contain 64-bit (or 128-bit in the furture) unsigned int data. Python's array seems not supporting unsigned int type beyond 32-bit ('L'). I would like to use Python array as I need to make my program work on both big-endian machines as well as on little-endian machines. What is the best way to deal with 64-bit / 128-bit data elements in Python (must support byteswap())? (must be machine-independent) Any idea, any hints, comments would be greatly appreciated. Thank you! Aki Niimura From ivan.illarionov at gmail.com Tue Dec 16 15:28:51 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 16 Dec 2008 12:28:51 -0800 (PST) Subject: Memory leak when using a C++ module for Python References: <13db1224-5d6d-4240-8184-ce852e10b422@d36g2000prf.googlegroups.com> Message-ID: On Dec 11, 8:35?pm, Jaume Bonet wrote: > ? ? ? ? //Here we take the info coming from python and transform it > into a vector (will allow us to work with numbers instead of > ? ? ? ? // strings) and shareInt which is an array of sets (form > std::set) > ? ? ? ? vector translator = string2int > (shareIntPy,root,shareInt,pSize,max); I guess if there are any problems with Python/C API in your example they are in string2int function. How do you retrieve Python data from 'shareIntPy' Python object? If you have memory leaks you probably forget to Py_DECREF something retrieved with Python/C API functions that return new references (like PyObject_GetAttrString). Ivan From roy at panix.com Mon Dec 1 08:46:06 2008 From: roy at panix.com (Roy Smith) Date: Mon, 01 Dec 2008 08:46:06 -0500 Subject: Emacs vs. Eclipse vs. Vim References: Message-ID: In article , Nick Craig-Wood wrote: > * Syntax colouring (not essential) I never used to use syntax coloring, until somebody turned me on to it a couple of years ago. I was griping on a company mailing list that some previous code monkey had commented out a big swath (more than a screenfull) of C++ code by sticking a "/*" at the beginning and a "*/" at the end. I had just wasted a bunch of time trying to debug a problem, not noticing that the code I was looking at was commented out. Somebody pointed out that if I turned on syntax coloring, it would be obvious. I've been hooked ever since. From zhushenli at gmail.com Wed Dec 3 22:23:11 2008 From: zhushenli at gmail.com (Davy) Date: Wed, 3 Dec 2008 19:23:11 -0800 (PST) Subject: Thread Tkinter problem References: <64c7402c-8b7b-4281-9d7d-1abdd6177d96@r15g2000prh.googlegroups.com> <35672781-eca1-4139-8b5d-88c457960d62@g1g2000pra.googlegroups.com> Message-ID: <98353009-15ea-4029-99d1-42f9d32e7c27@r15g2000prh.googlegroups.com> On Dec 4, 9:08?am, Davy wrote: > On Dec 4, 11:13?am, "Hendrik van Rooyen" wrote:> ?"Davy" wrote: > > > ? ? while(data_queue.full() == False): > > > This will fill the queue and stop. > > Use while true and if queue not full... > > Hi Hendrik, > > It works, thank you:) Add changed code: //------code changed --- def gen_board_thread(): print 'enter here' gen_flip = 1 while(True): time.sleep(0.3) if (data_queue.full() == False): if (gen_flip == 1): gen_flip = 0 data = board_1 else: gen_flip = 1 data = board_2 data_queue.put(data) print 'put', data_queue.qsize() //-------------------- > > Davy > > > > > > > - Hendrik- Hide quoted text - > > - Show quoted text - From steve at holdenweb.com Tue Dec 30 16:34:25 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Dec 2008 16:34:25 -0500 Subject: Triple quoted string in exec function ? In-Reply-To: <495A81A7.8030507@gmail.com> References: <495A253B.6010003@gmail.com> <495A81A7.8030507@gmail.com> Message-ID: Stef Mientki wrote: > ibpet11 at gmail.com wrote: >> On Dec 30, 2:48 pm, Steve Holden wrote: >> >>> Stef Mientki wrote: >>> >>>> hello, >>>> I'm running scripts, with the execute function (Python 2.5), >>>> and it seems that triple quoted strings are not allowed. >>>> Is there a workaround, >>>> or is this a fundamental problem of the exec-function ? >>>> >>> If you think about it, it should be obvious that you can't surround a >>> string to be compiled with any of the quotes that appear inside the >>> string to be compiled. That's about the only limitation I am aware of. >>> >>> And, by the way, exec is a *statement*, not a function! >>> > exec ( Init_Code, PG.P_Globals ) > > I've really doubt that this is a statement, > unless I don't understand what a statement is. We'll have to conclude you don't, then, won't we ;-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From castironpi at gmail.com Sat Dec 13 19:37:54 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 13 Dec 2008 16:37:54 -0800 (PST) Subject: subprocess to C program Message-ID: <0ebd59c5-95a1-42d4-b597-d1c248490b8e@y1g2000pra.googlegroups.com> Hi, I am writing a C process and I want to read data from a file that I write to in Python. I'm creating a pipe in Python, passing it to the C process, and calling '_read'. It gives me error 9, bad file number. Python code: import subprocess as s, os r, w= os.pipe( ) os.write( w, 'abcdefghij\n' ) a= s.Popen( [ r'C:\Documents and Settings\usr\Desktop\working \try_start', '%i'%r, '%i'%w ] ) C code: char buf[ 16 ]; memset( buf, 0, 16 ); int readfd= atoi( argv[ 1 ] ); int ct= _read( readfd, buf, 15 ); printf( "\n\n'_read %i %i %i': %s\n", ct, readfd, errno, buf ); Output: '_read -1 3 9' meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9. I want 'ct' to be 11 at this point. Thanks in advance. From exarkun at divmod.com Thu Dec 4 09:33:37 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 4 Dec 2008 09:33:37 -0500 Subject: schizophrenic view of what is white space In-Reply-To: <4937E8E5.2090306@chamonix.reportlab.co.uk> Message-ID: <20081204143337.20272.1236189783.divmod.quotient.15592@ohm> On Thu, 04 Dec 2008 14:27:49 +0000, Robin Becker wrote: >Is python of two minds about what is white space. I notice that split, strip >seem to regard u'\xa0' (NO-BREAK SPACE) as white, but that code is not >matched by the \s pattern. If this difference is intended can we rely on it >continuing? > > > >>> u'a b'.split() >[u'a', u'b'] > >>> u'a\xa0b'.split() >[u'a', u'b'] > >>> re.compile(r'\s').search(u'a b') ><_sre.SRE_Match object at 0x00DBB2C0> > >>> re.compile(r'\s').search(u'a\xa0b') > >>> > You have to give the re module an additional hint that you care about unicode: exarkun at charm:~$ python Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> print re.compile(r'\s').search(u'a\xa0b') None >>> print re.compile(r'\s', re.U).search(u'a\xa0b') <_sre.SRE_Match object at 0xb7dbb3a0> >>> Jean-Paul From rdmurray at bitdance.com Tue Dec 9 13:35:14 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Tue, 9 Dec 2008 13:35:14 -0500 (EST) Subject: Best way to report progress at fixed intervals In-Reply-To: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> Message-ID: On Tue, 9 Dec 2008 at 08:40, Slaunger wrote: > I am a novice Python 2.5 programmer, who write some cmd line scripts > for processing large amounts of data. > > I would like to have possibility to regularly print out the progress > made during the processing, say every 1 seconds, and i am wondering > what a proper generic way to do this is. > > I have created this test example to show the general problem. Running > the script gives me the output: > > Work through all 20 steps reporting progress every 1.0 secs... > Work step 0 > Work step 1 > Work step 2 > Work step 3 > Work step 4 > Processed 4 of 20 > Work step 5 [...] > Work step 19 > Finished working through 20 steps [...] > Quite frankly, I do not like what I have made! It is a mess, > responsibilities are mixed, and it seems overly complicated. But I > can't figure out how to do this right. > > I would therefore like some feedback on this proposed generic "report > progress at regular intervals" approach presented here. What could I > do better? I felt like a little lunchtime challenge, so I wrote something that I think matches your spec, based on your sample code. This is not necessarily the best implementation, but I think it is simpler and clearer than yours. The biggest change is that the work is being done in the subthread, while the main thread does the monitoring. It would be fairly simple to enhance this so that you could pass arbitrary arguments in to the worker function, in addition to or instead of the loop counter. ----------------------------------------------------------------------- """ Test module for testing generic ways of displaying progress information at regular intervals. """ import random import threading import time def work(i): """ Dummy process function, which takes a random time in the interval 0.0-0.5 secs to execute """ print "Work step %d" % i time.sleep(0.5 * random.random()) class Monitor(object): """ This class creates an object that will execute a worker function in a loop and at regular intervals emit a progress report on how many times the function has been called. """ def dowork(self): """ Call the worker function in a loop, keeping track of how many times it was called in self.no """ for self.no in xrange(self.max_iter): self.func(self.no) def __call__(self, func, verbose=True, max_iter=20, progress_interval=1.0): """ Repeatedly call 'func', passing it the loop count, for max_iter iterations, and every progress_interval seconds report how many times the function has been called. """ # Not all of these need to be instance variables, but they might # as well be in case we want to reference them in an enhanced # dowork function. self.func = func self.verbose = verbose self.max_iter=max_iter self.progress_interval=progress_interval if self.verbose: print ("Work through all %d steps reporting progress every " "%3.1f secs...") % (self.max_iter, self.progress_interval) # Create a thread to run the loop, and start it going. worker = threading.Thread(target=self.dowork) worker.start() # Monitoring loop. loops = 0 # We're going to loop ten times per second using an integer count, # so multiply the seconds parameter by 10 to give it the same # magnitude. intint = int(self.progress_interval*10) # isAlive will be false after dowork returns while worker.isAlive(): loops += 1 # Wait 0.1 seconds between checks so that we aren't chewing # CPU in a spin loop. time.sleep(0.1) # when the modulus (second element of divmod tuple) is zero, # then we have hit a new progress_interval, so emit the report. if not divmod(loops, intint)[1]: print "Processed %d of %d" % (self.no, self.max_iter) if verbose: print "Finished working through %d steps" % max_iter if __name__ == "__main__": #Create the monitor. monitor = Monitor() #Run the work function under monitoring. monitor(work) From malaclypse2 at gmail.com Mon Dec 8 12:54:46 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 8 Dec 2008 12:54:46 -0500 Subject: Equivalent of 'wget' for python? In-Reply-To: References: Message-ID: <16651e80812080954p23eb2aeaj8793be4a8d509c77@mail.gmail.com> On Mon, Dec 8, 2008 at 11:53 AM, r0g wrote: > urllib.urlretrieve(url_of_zip_file, destination_on_local_filesystem). In python 3.0, that appears to be: import urllib.request urllib.request.urlretrieve(url, local_file_name) -- Jerry From gagsl-py2 at yahoo.com.ar Wed Dec 10 16:44:51 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 10 Dec 2008 19:44:51 -0200 Subject: getting back into programming References: <8796344d-1c02-441e-8272-8a7638faae39@j39g2000yqn.googlegroups.com> Message-ID: En Wed, 10 Dec 2008 19:02:16 -0200, escribi?: > I used to program in C and Perl (up until 2001) (a little C++ and Java > too). Since then I've been a Business Analyst and only coded in VBA/ > Excel and written some SQL queries. (we use Sybase) > > I feel the need for other tools. > Primarily I want to write a bunch of small programs to query a > database and perform some calculations. While I can do this inside a > Sybase stored procedure, its a bit messy trying to "reimplement" a set > of calculations from Excel into Sybase. > > I would like to either: > - relearn Perl > or > - learn Python (I have heard its a nice language) I prefer Python over Perl because of its legibility (it's way more clear than Perl!), expressiveness (there is no big difference between "what I want" and "what I write"). (Anyway, I think most people here would say they like Python...) > 1. How good and easy to use is the Python database interface (to > Sybase)? Most database modules implement DBAPI 2.0, the Python standard API for database connectivity, see http://www.python.org/dev/peps/pep-0249/ Migrating from one database to another, if you stick to the API, may have little or no impact on your application. The first hit on Google for "python sybase" points to the python-sybase project on Sourceforge, which claims to be DBAPI 2 compliant, but I've never used it. > 2. Can you suggest some good books, and/or links for learning Python, > as well as teh database interface? If you had some programming experience then Dive into Python http://www.diveintopython.org/ would be a good choice > 3. How difficult is it to install Python vs Perl on PC/Windows > machines? Both, almost zero effort, just run the installer. -- Gabriel Genellina From tjreedy at udel.edu Thu Dec 4 14:25:48 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Dec 2008 14:25:48 -0500 Subject: Python 3 read() function In-Reply-To: References: Message-ID: ?????? ??????????? wrote: >> I don't think it matters. Here's a quick comparison between 2.5 and >> 3.0 on a relatively small 17 meg file: >> >> C:\>c:\Python30\python -m timeit -n 1 >> "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" >> 1 loops, best of 3: 36.8 sec per loop >> >> C:\>c:\Python25\python -m timeit -n 1 >> "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" >> 1 loops, best of 3: 33 msec per loop >> >> That's 3 orders of magnitude slower on python3.0! > > Isn't this because you have the file cached in memory on the second run? In my test, I read Python25.chm with 2.5 and Python30.chm with 3.0. Rereading Python30.chm without closing *is* much faster. >>> f=open('Doc/Python30.chm','rb') >>> d=f.read() >>> d=f.read() >>> d=f.read() Closing, reopening, and rereading is slower. From pofuk at email.t-com.hr Thu Dec 11 08:06:19 2008 From: pofuk at email.t-com.hr (SMALLp) Date: Thu, 11 Dec 2008 14:06:19 +0100 Subject: Python, threading Message-ID: Hy. I have a problem! I'm making multi thread application (client, server) using wxPython for GUI, and threading.Thread for threding. Clients connect and when they are connected (evry thread handles one connection) threads change main window. I neded tip how to make communication between threeds. From alexoplocatie at gmail.com Tue Dec 16 11:26:57 2008 From: alexoplocatie at gmail.com (aka) Date: Tue, 16 Dec 2008 08:26:57 -0800 (PST) Subject: help I'm getting delimited Message-ID: <817cf531-225b-4c4e-b79b-10d7657b0749@35g2000pry.googlegroups.com> Hi, I'm going nuts over the csv.reader and UnicodeReader class. Somehow I can't get this method working which is supposed to read a csv file which name is inputted but here now hardcoded. What I need for now is that the string version of the list is put out for control. Later on I will only need to read the first column (id) of the csv file to be able to fill in a session var with a list of all ids. inp = c:/temp/test.csv roles = [] try: fp = open(inp, 'rb') reader = csv.reader(fp) for r in reader: rollen.append(r) except: msg = "Er is iets mis met de UnicodeReader" return dict(file=in,roles=str(roles)) Any help greatly appreciated! Cheers From clp at rebertia.com Wed Dec 17 15:33:23 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 17 Dec 2008 12:33:23 -0800 Subject: Selecting a different superclass In-Reply-To: References: Message-ID: <47c890dc0812171233v3727106fifd91d9bd217e0e9@mail.gmail.com> On Wed, Dec 17, 2008 at 6:41 AM, psaffrey at googlemail.com wrote: > This might be a pure OO question, but I'm doing it in Python so I'll > ask here. > > > The problem is that IDPointSet and MicroArrayPointSet will need to > inherit from PointSet or TraceablePointSet based on whether I'm > handling traceable points or not. Can I select a superclass > conditionally like this in Python? Am I trying to do something really > evil here? You're doing something really dynamic; don't think I'd call it inherently evil though. All you have to do is use a variable in the inheritance syntax, it's really quite simple: superclass = TraceablePointSet if tracing else PointSet class IDPointSet(superclass): #body code here #use same trick for MicroArrayPointSet Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From fetchinson at googlemail.com Sat Dec 27 22:47:08 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 27 Dec 2008 19:47:08 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: >> This is the function I have, the corresponding python function will >> take two equal length lists of integers and the C function will >> compute their sum and return the result as a python tuple. >> >> >> static PyObject *func( PyObject * self, PyObject * args ) >> { >> int j, N; >> int * src1, * src2; >> PyObject *list1, *list2; >> >> list1 = PyTuple_GetItem( args, 0 ); >> N = PyList_Size( list1 ); >> src1 = ( int * ) malloc( N * sizeof( int ) ); >> for( j = 0; j < N; j++ ) >> { >> src1[j] = (int)PyInt_AsLong( PyList_GetItem( list1, j ) ); >> } >> >> list2 = PyTuple_GetItem( args, 1 ); >> N = PyList_Size( list2 ); >> src2 = ( int * ) malloc( N * sizeof( int ) ); >> for( j = 0; j < N; j++ ) >> { >> src2[j] = (int)PyInt_AsLong( PyList_GetItem( list2, j ) ); >> } >> >> PyObject * tuple; >> tuple = PyTuple_New( N ); >> for( j = 0; j < N; j++ ) >> { >> PyTuple_SetItem( tuple, j, PyInt_FromLong( (long)( src1[j] + >> src2[j] ) ) ); >> } >> >> free( src1 ); >> free( src2 ); >> >> return tuple; >> } > > As others already said, using a Numpy array or an array.array object would > be more efficient (and even easier - the C code gets a pointer to an array > of integers, as usual). I looked for this in the C API docs but couldn't find anything on how to make an array.array python object appear as a pointer to integers (or floats, etc) in C code. On http://docs.python.org/c-api/concrete.html#sequence-objects There is only list and tuple or maybe you mean byte array? That has only been introduced in python 2.6 and I'm working on 2.5. Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From rt8396 at gmail.com Thu Dec 18 11:32:53 2008 From: rt8396 at gmail.com (r) Date: Thu, 18 Dec 2008 08:32:53 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> Message-ID: <71ede5f0-fd88-4155-9f0d-42d0ad5f57dc@v42g2000yqj.googlegroups.com> w.unbind ( sequence, funcid=None ) This method deletes bindings on w for the event described by sequence. If the second argument is a callback bound to that sequence, that callback is removed and the rest, if any, are left in place. If the second argument is omitted, all bindings are deleted. see http://infohost.nmt.edu/tcc/help/pubs/tkinter/universal.html From willian.radicaled at gmail.com Wed Dec 17 09:51:50 2008 From: willian.radicaled at gmail.com (RadicalEd) Date: Wed, 17 Dec 2008 06:51:50 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: <84916f4e-4683-4063-8ebc-41b5ad5e1d2e@v31g2000vbb.googlegroups.com> On Dec 10, 1:42?pm, cm_gui wrote: > http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-... > > I fully agree with Krzysztof Kowalczyk . > Can't they build a faster VM for Python since they love the language > so much? > > Python is SLOW. ? ?And I am not comparing it with compiled languages > like C. > Python is even slower than PHP! > > Just go to any Python website and you will know. > An example is:http://www2.ljworld.com/ > And this site is created by the creators of Django! > > And it is not just this Python site that is slow. There are many many > Python sites which are very slow. And please don?t say that it could > be the web hosting or the server which is slow ? because when so many > Python sites are slower than PHP sites, it couldn?t be the web > hosting. ? Also, Zope/Plone is even slower. > > Python is slow. Very slow. I did a DataBase consult with MySQLdb and PHP with 300000 rows and who you think was the better and faster, YES, Python for almost 10 seconds, and I have to configure the php.ini for PHP could show me the DATA. He is just a futile troll frustrated with Python. From chris.gonnerman at newcenturycomputers.net Thu Dec 25 10:16:40 2008 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 25 Dec 2008 09:16:40 -0600 Subject: os.system('cls') In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF602494700@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF602494700@enbmail01.lsi.com> Message-ID: <4953A3D8.6040308@newcenturycomputers.net> Depends on what operating system you are using. The list of possible commands would be unbounded, if not truly infinite. > From: Dennis van Oosterhout [mailto:de.slotenzwemmer at gmail.com] > > Hi there! I was searching for a way to clear the 'DOS screen'/command > screen etc. and found that os.system('cls') works for this. I was just > wondering where I can find al the commands which can be used for > os.system(). I searched with google but I didn't find an answer. In the > official python tutorial it says os.system('command') executes the > command, but it doesn't say which commands exist (or I'm just blind). > > Does anyone have an answer for this question? > From steve at REMOVE-THIS-cybersource.com.au Thu Dec 4 09:08:30 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Dec 2008 14:08:30 GMT Subject: "as" keyword woes References: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> Message-ID: <0147dc24$0$20670$c3e8da3@news.astraweb.com> On Wed, 03 Dec 2008 17:15:21 -0800, Matimus wrote: >> Couldn't we have continued along just fine using a smarter parser >> without elevating "as" to reserved status (and thus potentially >> breaking a 10+ years of existing code)? > > Nothing broke your code. It works just fine under the version it was > developed for. Who forced you to upgrade to python2.6? Be reasonable. Python 2.5 is not very far away from being put into "security updates only" mode, and in a year or so it won't even get security updates. I dare say there are already platforms that use Python 2.6 as standard. Tying your software to an obsolete version of a language is a good way to force your software into obsolescence. Not that 2.5 is obsolete *now*. But it will be soon (for some definition of soon): in no more than a year or three, software that only runs on Python 2.5 would be like software that only runs on 2.3 now. -- Steven From rt8396 at gmail.com Thu Dec 18 15:26:47 2008 From: rt8396 at gmail.com (r) Date: Thu, 18 Dec 2008 12:26:47 -0800 (PST) Subject: IDLE cursor color References: <65c5974c-e5c5-46c1-9673-371a7c9ea047@a12g2000pro.googlegroups.com> <313c1a14-ac85-4326-a2dc-29955549a708@f11g2000vbf.googlegroups.com> Message-ID: <9f0efea8-a2a6-463a-ad02-ba5844b8328e@a12g2000yqm.googlegroups.com> also try the python forum, great place for beginners... http://www.python-forum.org/pythonforum/index.php From lihang9999 at gmail.com Wed Dec 17 08:47:41 2008 From: lihang9999 at gmail.com (Li Han) Date: Wed, 17 Dec 2008 05:47:41 -0800 (PST) Subject: The rule of literal string References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> Message-ID: <59fa1fe8-b43a-4679-9795-8ac333377b62@z27g2000prd.googlegroups.com> Thank you, Chris! You have made me learn more about Python. From castironpi at gmail.com Sun Dec 21 06:02:21 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 21 Dec 2008 03:02:21 -0800 (PST) Subject: How to transfer data structure or class from Python to C/C++? Message-ID: <7178badb-35a8-4525-8856-0b51b49e93dc@r36g2000prf.googlegroups.com> On Oct 16, 9:10 am, Hongtian wrote: snip > Not exactly. > In my C/C++ application, I have following function or flow: > void func1(....) > { > call PyFunc(struct Tdemo, struct &Tdemo1); > } > I mean I want to invoke Python function 'PyFunc' and transfer a data > structure 'Tdemo' to this function. After some process in Python, I > want it return 'Tdemo1' back to the C/C++ application. snip This is a correction of: Oct 17, 5:03 pm, "Aaron \"Castironpi\" Brady" http://groups.google.com/group/comp.lang.python/msg/f11ac4a34faaf766 Thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/68d59cb670a345ef Revised solution uses 'from_address' instead of '_ctypes._cast_addr'. import ng27ext import ctypes as c class TypeA( c.Structure ): _fields_= [ ( 'a', c.c_int ), ( 'b', c.c_float ) ] def exposed( pobj1, pobj2 ): obj1= TypeA.from_address( pobj1 ) obj2= TypeA.from_address( pobj2 ) print obj1.a, obj1.b obj2.a= c.c_int( 60 ) obj2.b= c.c_float( 65.5 ) print obj2.a, obj2.b print ng27ext.methA( exposed ) From skip at pobox.com Tue Dec 23 11:18:07 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 23 Dec 2008 10:18:07 -0600 Subject: pseudo terminal usage from Python? In-Reply-To: <5t-dnRgMi9Z4lszUnZ2dnUVZ_vOdnZ2d@posted.visi> References: <5t-dnRgMi9Z4lszUnZ2dnUVZ_vOdnZ2d@posted.visi> Message-ID: <18769.3903.26361.253778@montanaro-dyndns-org.local> Grant> Are you sure it's not Python buffering its input? Have you tried Grant> "python -u mympstat.py"? Hmmm... No, I hadn't considered that. I'll check it out. Thanks... Grant> I had a Linux pty example running once upon a time. If "python Grant> -u" doesn't work post again, and I'll try to find it. Would be helpful even if I don't need it for this task, as I've not been able to find any simple examples on the net. (Maybe there's a recipe at ActiveState, but Google didn't pick up anything with the search terms I was using.) Skip From martin at marcher.name Wed Dec 24 05:18:34 2008 From: martin at marcher.name (Martin) Date: Wed, 24 Dec 2008 11:18:34 +0100 Subject: Most efficient way to build very large dictionaries In-Reply-To: <1230107768.14060.1291622121@webmail.messagingengine.com> References: <1230104615.5867.1291617213@webmail.messagingengine.com> <1230107768.14060.1291622121@webmail.messagingengine.com> Message-ID: <5fa6c12e0812240218yc9a7185maaf5211dbddd8134@mail.gmail.com> Hi, 2008/12/24 : > Hi Roger, > >> you may want to consider using SQLite > > Thank you for your suggestion about looking at SQLite. I haven't > compared the performance of SQLite to Python dictionaries, but I'm > skeptical that SQLite would be faster than in-memory Python dictionaries > for the type of analysis I'm doing. I'd think he's talking about in memory SQLite Databases, this way you should be quite fast _and_ could dump all that to a persistent storage... regards martin -- http://soup.alt.delete.co.at http://www.xing.com/profile/Martin_Marcher http://www.linkedin.com/in/martinmarcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From zxo102 at gmail.com Thu Dec 25 04:27:03 2008 From: zxo102 at gmail.com (zxo102) Date: Thu, 25 Dec 2008 01:27:03 -0800 (PST) Subject: How to display Chinese in a list retrieved from database via python References: Message-ID: <22be506d-91c2-4727-ace7-2e3382b6d214@g3g2000pre.googlegroups.com> On 12?25?, ??3?35?, "Chris Rebert" wrote: > On Wed, Dec 24, 2008 at 11:29 PM, zxo102 wrote: > > Hi, > > I retrieve some info in Chinese from postgresql and assign it to a > > variable 'info' defined in javascript of a html page: > > var info = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce > > \xc4'] > > But I want it to be > > var info = ['??','??','??'] > > since in html pages (via javascript), the items in chinese out of the > > former :['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4'] can > > not be displayed correctly when it is inserted into a html page. If > > the list is var info = ['??','??','??'] , then everything works > > fine. > > > Anybody knows how to solve this problem? > > Upgrading to Python 2.6 would probably be beneficial due to its better > handling of Unicode. > Also, posting some of the actual code you're using (to generate > JavaScript, I guess?) would definitely help. > > Merry Christmas, > Chris > > -- > Follow the path of the Iguana...http://rebertia.com Hi Chris: I have to use python2.4 since many other python packages have not been updated to 2.6. Here is my demo: I create a table in postgresql: create table my_table ( id serial, name char(20), phone char(20) ); and insert two records into the table (4, '??', '1334995555555') (5, '??', '3434343434343') I would like to generate a html page dynamically, here is the demo script ############################################################ def do_search(a): # ??ODBC?? import odbc # ??ODBC??"my_odbc"??????????? cc = odbc.odbc('dsn=wisco') cursor1 = cc.cursor() # ??????????"my_table" #cursor1.execute("select * from my_table where name = '%s' "%a) cursor1.execute("select * from my_table where name like '%%%s%%' "%a) rr = cursor1.fetchall() # ????????? row01 = rr[0] row02 = rr[1] print row01, row02 html_str = '' #print "Content-Type: text/html\n\n" html_str += " test \n" html_str += "\n" html_str += " \n" html_str = html_str%(row01,row02) f = open('c:\\xbop_sinopec\\apache\\htdocs\\test01.html','w') f.write(html_str) f.close do_search('??') ######################################################### The html code is as follows test But the '??' is '\xd6\xd0\xce\xc4'. When row01 and row02 is called from somewhere, '\xd6\xd0\xce\xc4' can not be displayed correctly as '??' in html environment. Thanks for your help and Merry Christmas to you too. ouyang From sonicsai at gmail.com Tue Dec 23 23:25:16 2008 From: sonicsai at gmail.com (sai) Date: Tue, 23 Dec 2008 20:25:16 -0800 Subject: turtle ? In-Reply-To: References: <41d04d600812230210s5b90aa0cud8a3161ca816c80e@mail.gmail.com> Message-ID: <41d04d600812232025k63d1b8bcyff82c0fbbce8b3ac@mail.gmail.com> On Tue, Dec 23, 2008 at 2:29 AM, Gerhard H?ring wrote: > sai wrote: >> python newbie here :-) >> >> I am trying to get turtle to run but got stuck here: >> >> $ python >> Python 2.5.2 (r252:60911, Aug 5 2008, 16:17:28) >> [GCC 4.2.2 20071128 (prerelease) (4.2.2-3.1mdv2008.0)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> import turtle >> Traceback (most recent call last): >> File "", line 1, in >> ImportError: No module named turtle >> >> I have used google to search the web and the newsgroup but got >> nothing. The Linux distro is Mandriva, if that makes a difference. > > Mandriva have probably split Python into several packages. If so, > chances are one of them contains the tkinter GUI library. You should > look in your package management tool for a package called > python-tkinter, python-tk or similar and install it. > > HTH > > Gerhard > there is a Mandriva rpm called tkinter-apps ! thanks Gerhard. sai From rt8396 at gmail.com Wed Dec 24 11:49:28 2008 From: rt8396 at gmail.com (r) Date: Wed, 24 Dec 2008 08:49:28 -0800 (PST) Subject: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> <90f06b27-39da-4f1a-a878-f3972e942d57@s24g2000vbp.googlegroups.com> <62caf93b-0455-4450-9895-8a9d9554f75e@r32g2000vba.googlegroups.com> <1isezkk.51e05y1457jqrN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <3cb2a746-1a43-44a1-9825-7667af9fe2fa@s1g2000prg.googlegroups.com> 220 ratings and 1 star, WHOOOO!. I find this all quite amusing :D. Keep em coming. Oh, and FYI, I will always have 1 star! hahahahahha /"\ |\./| | | | | |>~<| | | /'\| |/'\ /~\| | | |__ | | } | | \ | | | | | \ | ~ ~ ~ ~ |` ) | / \ / \ / \ ____ / |--//''`\--| | (( +==)) | |--\_|_//--| From google at mrabarnett.plus.com Mon Dec 15 11:15:41 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 15 Dec 2008 16:15:41 +0000 Subject: alt.possessive.its.has.no.apostrophe In-Reply-To: <49467CE2.3060401@holdenweb.com> References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> <49467CE2.3060401@holdenweb.com> Message-ID: <494682AD.2030900@mrabarnett.plus.com> Steve Holden wrote: > Ben Finney wrote: >> James Stroud writes: >> >>> Ben Finney wrote: >>>> James Stroud writes: >>>> >>>>> Yes. I think it was the British who decided that the >>>>> apostrophe rule for "it" would be reversed from normal usage >>>>> relative to just about every other noun. >> It also seems an indefensible claim to say that anyone ?decided? it >> would be that way, especially ?the British?. >> > It's our language, dammit! Ours, ours, ours! > > This decision was actually taken at a meeting of the Society of > British pedants on November 23, 1786. This led to a schism between > the British and the newly-independent Americans, who responded by > taking the "u" out of colour, valour, and aluminium. > Actually the Americans have been a bit confused about how to spell aluminium. See http://en.wikipedia.org/wiki/Aluminium_(element). >>>> Remember that ?it? is a pronoun. I see no reversal: >>> Ok. Pronouns are reversed. >> Or, more generally: Pronouns, which are different in just about >> every other way from other nouns, are different in this way also. >> Is that about right? >> > > Just think of them as "nounpros" and you won't go wrong. > I've just remembered a pronoun that does take an apostrophe: the indefinite pronoun "one". Not that one uses it that often. :-) From alex.gaynor at gmail.com Tue Dec 9 02:25:12 2008 From: alex.gaynor at gmail.com (Alex_Gaynor) Date: Mon, 8 Dec 2008 23:25:12 -0800 (PST) Subject: Guido's new method definition idea References: <014a071a$0$20670$c3e8da3@news.astraweb.com> <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> <79139d04-bd26-4f36-b8c9-19554e7d4e95@e18g2000yqo.googlegroups.com> <6q6j50Fau4iiU1@mid.individual.net> Message-ID: <63a5723b-e078-4fe5-b046-6196ef5f61b1@n10g2000yqm.googlegroups.com> I'm a huge -1 on this, it adds nothing to the language, and IMO violates quite a few Zens. -Beautiful is better than ugly. A bit subjective, but this is ugly IMO. -Special cases aren't special enough to break the rules. -There should be one-- and preferably only one --obvious way to do it. From stef.mientki at gmail.com Sun Dec 7 07:49:06 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 07 Dec 2008 13:49:06 +0100 Subject: how to get a beep, OS independent ? In-Reply-To: <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> Message-ID: <493BC642.9010104@gmail.com> Chris Rebert wrote: > On Sun, Dec 7, 2008 at 1:27 AM, Stef Mientki wrote: > >> Rainy wrote: >> >>> On Dec 6, 3:40 pm, Stef Mientki wrote: >>> >>> >>>> hello, >>>> >>>> I want to give a small beep, >>>> for windows there's message-beep, >>>> and there seems to be something like " curses" , >>>> but that package seems to be totally broken in P2.5 for windows. >>>> >>>> Any other suggestions ? >>>> >>>> thanks, >>>> Stef Mientki >>>> >>>> >>> For win there's winsound, you have to check sys.platform and do >>> what's necessary for the platform in question. In linux I think >>> you can just print '\a' (or does that only work in terminals?). >>> If you know that ext. speakers are always on, you can do a nicer >>> beep by using some wav file, in linux it's probably easiest to >>> use an external program to play it, like wavplay. Basically, >>> there is no single answer, it depends on circumstances. >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >>> >> '\a' or chr(7) prints an inverted "BEL". >> > > Inverted bell? In the output window (stdout) which is black letters on white background, it prints "bell" in white letters with a black background. > What do you mean? And what version dependency are you > referring to? > Well some of you actually hear something, I don't, so I expect that the Python version differs. cheers, Stef > Cheers, > Chris > > From steve at REMOVE-THIS-cybersource.com.au Mon Dec 1 18:04:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 01 Dec 2008 23:04:45 GMT Subject: Two attributes! Why? References: <76bc5df8-26fd-4e2d-a134-c5d13ea3b39a@n10g2000yqm.googlegroups.com> <0140c948$0$20670$c3e8da3@news.astraweb.com> Message-ID: <01446567$0$20670$c3e8da3@news.astraweb.com> On Mon, 01 Dec 2008 07:43:44 -0800, Emanuele D'Arrigo wrote: > On Nov 29, 5:21?am, Steven D'Aprano cybersource.com.au> wrote: >> This is a side-effect of name-mangling. Double-underscore names are >> only mangled when they are referred to directly as attributes, not when >> they are passed to setattr, getattr etc. Those functions don't do any >> name mangling. > > Ah! That make sense! Thank you! > > It's a bit of an obscure thing right now. I don't see mention of it in > the description of the setattr/getattr built-ins: > > http://docs.python.org/library/functions.html > > Wouldn't be good to have a hint of the issue there? Not really. You seem to assume that name mangling always happens unless the docs say it doesn't. That's backwards. Name mangling *never* happens except where the docs say it does. Hence I can tell you that self.__dict__['__name'] will fail to find a name-mangled attribute self.__name without even trying it, because I know dictionary lookups don't do name-mangling either. -- Steven From lists at cheimes.de Tue Dec 23 09:51:48 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 23 Dec 2008 15:51:48 +0100 Subject: python3 urlopen(...).read() returns bytes In-Reply-To: <42ad842c-8d8a-4ff5-a721-0688b7ae20f7@41g2000yqf.googlegroups.com> References: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> <5496b34d-7ce4-4281-9f01-aed12dab9fd3@f33g2000vbf.googlegroups.com> <42ad842c-8d8a-4ff5-a721-0688b7ae20f7@41g2000yqf.googlegroups.com> Message-ID: ajaksu wrote: > On Dec 22, 9:05 pm, Christian Heimes wrote: >> ajaksu schrieb: >> >>> That said, a "decode to declared HTTP header encoding" version of >>> urlopen could be useful to give some users the output they want (text >>> from network io) or to make it clear why bytes is the safe way. >> Yeah, your idea sounds both useful and feasible. A patch is welcome! :) > > Would monkeypatching what urlopen returns be good enough or should we > aim at a cleaner implementation? If you want to do it right ... It should be a clean patch against the py3k svn branch including documentation and a unit test. Don't worry! It's not as hard as it sounds. Besides Python core development is fun. :) Christian From steve at REMOVE-THIS-cybersource.com.au Tue Dec 9 17:57:37 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Dec 2008 22:57:37 GMT Subject: Can't figure out where SyntaxError: can not delete variable 'x' referenced in nested scope us coming from in python >=2.6 References: Message-ID: <014eef7f$0$20670$c3e8da3@news.astraweb.com> On Tue, 09 Dec 2008 13:11:40 -0500, Albert Hopkins wrote: > The difference is under Python 2.4 I get a traceback with the lineno and > offending line, but I do not get a traceback in Pythons 2.6 and 3.0. If tracebacks are broken, surely that would be a pretty huge bug. It seems to be broken in 2.5 as well: >>> def a(x): ... def b(): ... x ... del x ... SyntaxError: can not delete variable 'x' referenced in nested scope > So is there a way to find the offending code w/o having to go through > every line of code in 'foo' by hand? Just search for "del x" in your code. Your editor does have a search function, surely? -- Steven From steven at REMOVE.THIS.cybersource.com.au Mon Dec 8 21:44:43 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 09 Dec 2008 02:44:43 GMT Subject: Rich Comparisons Gotcha References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Mon, 08 Dec 2008 10:20:56 -0800, Rhamphoryncus wrote: > On Dec 7, 4:20?pm, Steven D'Aprano cybersource.com.au> wrote: >> On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: >> > Rasmus Fogh wrote: >> >> >> Current behaviour is both inconsistent and counterintuitive, as >> >> these examples show. >> >> >>>>> x = float('NaN') >> >>>>> x == x >> >> False >> >> > Blame IEEE for that one. Rich comparisons have nothing to do with >> > that one. >> >> There is nothing to blame them for. This is the correct behaviour. NaNs >> should *not* compare equal to themselves, that's mathematically >> incoherent. > > Mathematically, NaNs shouldn't be comparable at all. They should raise > an exception when compared. In fact, they should raise an exception > when *created*. But that's not what we want. What we want is a dummy > value that silently plods through our calculations. For a dummy value > it seems a lot more sense to pick an arbitrary yet consistent sort order > (I suggest just above -Inf), rather than quietly screwing up the sort. > > Regarding the mythical IEEE 754, It's hardly mythical. http://ieeexplore.ieee.org/ISOL/standardstoc.jsp?punumber=4610933 > although it's extremely rare to find > quotations, I have one on just this subject. And it does NOT say "x == > NaN gives false". It says it gives *unordered*. Unordered means that none of the following is true: x > NaN x < NaN x == NaN It doesn't mean that comparing a NaN with something else is an error. -- Steven From xahlee at gmail.com Tue Dec 2 15:50:44 2008 From: xahlee at gmail.com (Xah Lee) Date: Tue, 2 Dec 2008 12:50:44 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: <591e8625-7e4d-4db8-ae6c-73c4370f8088@q26g2000prq.googlegroups.com> On Dec 2, 12:21 pm, Lew wrote: > Xah Lee wrote: > > LOL Jon. r u trying to get me to do otimization for you free? > > These are professional software development forums, not some script- > kiddie cellphone-based chat room. "r" is spelled "are" and "u" should > be "you". > > > how about pay me $5 thru paypal? I'm pretty sure i [sic] can speed it up. > > Say, maybe 10%, and even 50% is possible. > > The first word in a sentence should be capitalized. "PayPal" is a > trademark and should be capitalized accordingly. The word "I" in > English should be capitalized. > > Proper discipline in these matters helps the habit of mind for > languages like Java, where case counts. > > Jon Harrop has a reputation as an extremely accomplished software > maven and columnist. I find his claims of relative speed and > compactness credible. He was not asking you to speed up his code, but > claiming that yours was not going to be as effective. The rhetorical > device of asking him for money does nothing to counter his points, > indeed it reads like an attempt to deflect the point. Dear tech geeker Lew, If u would like to learn english lang and writing insights from me, peruse: ? Language and English http://xahlee.org/Periodic_dosage_dir/bangu/bangu.html In particular, i recommend these to start with: ? To An Or Not To An http://xahlee.org/Periodic_dosage_dir/bangu/an.html ? I versus i http://xahlee.org/Periodic_dosage_dir/bangu/i_vs_I.html ? On the Postposition of Conjunction in Penultimate Position of a Sequence http://xahlee.org/Periodic_dosage_dir/t2/1_2_and_3.html some analysis of common language use with respect to evolutionary psychology, culture, ethology, ethnology, can be seen ? for examples ? at: ? Hip-Hop Rap and the Quagmire of (American) Blacks http://xahlee.org/Periodic_dosage_dir/sanga_pemci/hiphop.html ? Take A Chance On Me http://xahlee.org/Periodic_dosage_dir/sanga_pemci/take_a_chance_on_me.html ? ????? (Age of Blossom) http://xahlee.org/Periodic_dosage_dir/sanga_pemci/hua3yang4nian2hua2.html As to questioning my expertise of Mathematica in relation to the functional lang expert Jon Harrop, perhaps u'd be surprised if u ask his opinion of me. My own opinion, is that my Mathematica expertise surpasses his. My opinion of his opinion of me is that, my opinion on Mathematica is not to be trifled with. Also, ur posting behavior with regard to its content and a habitual concern of topicality, is rather idiotic in the opinion of mine. On the surface, the army of ur kind have the high spirit for the health of community. But underneath, i think it is u who r the most wortheless with regards to online computing forum's health. I have published a lot essays regarding this issue. See: ? Netiquette Anthropology http://xahlee.org/Netiquette_dir/troll.html PS when it comes to english along with tech geeker's excitement of it, one cannot go by without mentioning shakespeare. ? The Tragedy Of Titus Andronicus, annotated by Xah Lee http://xahlee.org/p/titus/titus.html Please u peruse of it. Xah ? http://xahlee.org/ ? From jasnow1 at gmail.com Fri Dec 26 21:09:30 2008 From: jasnow1 at gmail.com (Al Snow) Date: Fri, 26 Dec 2008 18:09:30 -0800 (PST) Subject: ruby -> python translator exists? References: <04b51f42-e18e-4902-8a98-38f0538c1eda@s9g2000prg.googlegroups.com> <4a10794e-a3e7-4aa4-8d21-580152806277@c36g2000prc.googlegroups.com> Message-ID: <72c2df21-db59-4870-9388-ccaa47cf11e4@20g2000yqt.googlegroups.com> On Dec 26, 8:31?pm, bearophileH... at lycos.com wrote: > rogerdpack: > > > Hi all. ?My name is Roger. > > Hello Roger, my name is bearophile. > > > Anybody know of a Ruby -> Python translator at all? ?I'm looking for a > > way to have my Ruby code take advantage of the coolio speed of Psyco. > > I have never heard of such translator, so far. > > > Also question. Does psyco work with Python 3.0? > > It doesn't work with Python3 and you may need lot of time to see it > come out... if you will ever see it. > > Bye, > bearophile Search for the tool "Unholy". -- Al From rt8396 at gmail.com Sun Dec 21 13:47:21 2008 From: rt8396 at gmail.com (r) Date: Sun, 21 Dec 2008 10:47:21 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> <6r6hpfFfb643U3@mid.uni-berlin.de> <494E6FDA.4070401@mrabarnett.plus.com> <4585c27d-d7a9-480f-991c-a869161be55c@g38g2000yqn.googlegroups.com> Message-ID: <3392a51b-d3fd-4986-9c59-fecccc7272da@p2g2000prn.googlegroups.com> Could not have said it better myself Luis, i stay as far away from C as i can. But there are usage cases for it. From fetchinson at googlemail.com Sat Dec 27 21:40:52 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 27 Dec 2008 18:40:52 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: >> This is the function I have, the corresponding python function will >> take two equal length lists of integers and the C function will >> compute their sum and return the result as a python tuple. >> >> >> static PyObject *func( PyObject * self, PyObject * args ) >> { >> int j, N; >> int * src1, * src2; >> PyObject *list1, *list2; >> >> list1 = PyTuple_GetItem( args, 0 ); >> N = PyList_Size( list1 ); >> src1 = ( int * ) malloc( N * sizeof( int ) ); >> for( j = 0; j < N; j++ ) >> { >> src1[j] = (int)PyInt_AsLong( PyList_GetItem( list1, j ) ); >> } >> >> list2 = PyTuple_GetItem( args, 1 ); >> N = PyList_Size( list2 ); >> src2 = ( int * ) malloc( N * sizeof( int ) ); >> for( j = 0; j < N; j++ ) >> { >> src2[j] = (int)PyInt_AsLong( PyList_GetItem( list2, j ) ); >> } >> >> PyObject * tuple; >> tuple = PyTuple_New( N ); >> for( j = 0; j < N; j++ ) >> { >> PyTuple_SetItem( tuple, j, PyInt_FromLong( (long)( src1[j] + >> src2[j] ) ) ); >> } >> >> free( src1 ); >> free( src2 ); >> >> return tuple; >> } > > As others already said, using a Numpy array or an array.array object would > be more efficient (and even easier - the C code gets a pointer to an array > of integers, as usual). Thanks, I didn't know that an array.array can be passed to C code as a C pointer to an array. So I'll use an array.array because this is really convenient. >> Do I have to free the memory occupied by the python objects list1 and >> list2? > > No. Usually you don't do that for any Python object - just > increment/decrement its reference count (using Py_INCREF/Py_DECREF). Great, one headache less :) >> Do I have to do any refcounting for list1, list2, tuple? > > In this case list1 and list2 come from PyTuple_GetItem; the docs say it > returns a "borrowed reference" (that is, the function doesn't increment > the refcount itself). So you don't have to decrement it yourself (and it > isn't necesary to increment it in the first place, because the "args" > tuple holds a reference, so the object can't disappear until the function > exits, at least) > >> Any comment on the above code will be very appreciated! If I'm pushed >> in the right direction I'm a fast learner but the beginning steps are >> always hard :) > > You MUST check EVERY function call for errors! Yes, I know :) > And check the argument's type (how do you know it is a list?). Once you > are sure the first parameter *is* a list, you may use the "macro" version > of several functions, like PyList_GET_SIZE and PyList_GET_ITEM. The macro versions are preferable because they are faster? > You should check that both lists have the same length too. > And you should check that elements are integers, or convertible to > integers (in case of error, PyInt_AsLong returns -1 and PyErr_Occurred() > is true) > To fill the resulting tuple, use PyTuple_SET_ITEM instead. BTW, why return > a tuple and not a list? No particular reason, other than the fact that I won't need to modify these lists/tuples from python so whenever something will not change, I use a tuple because it's immutable. Or this is not a very good practice? There is no difference between lists and tuples in terms of speed I suppose (getitem, setitem, etc). Thanks a lot, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From darcy at druid.net Tue Dec 16 14:26:33 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 16 Dec 2008 14:26:33 -0500 Subject: Where is a good open source python project to be used as example? In-Reply-To: <05T1l.219074$FR.507685@twister1.libero.it> References: <05T1l.219074$FR.507685@twister1.libero.it> Message-ID: <20081216142633.3671422a.darcy@druid.net> On Tue, 16 Dec 2008 19:13:00 GMT Andrea Francia wrote: > I'm looking for a python project to use as example to learning python. > > The project should have these features: > > 1. is almost fully unit tested > 2. use consistently the code convention recommended by PEP 8 > 3. it's elements are almost fully documented > > Extra point features are: > > 4. building, assembling, and release automation > > Did you know where are such projects? http://www.PyGreSQL.org/. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From lie.1296 at gmail.com Tue Dec 16 11:04:24 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 16 Dec 2008 16:04:24 +0000 (UTC) Subject: Generator slower than iterator? References: Message-ID: On Tue, 16 Dec 2008 12:07:14 -0300, Federico Moreira wrote: > Hi all, > > Im parsing a 4.1GB apache log to have stats about how many times an ip > request something from the server. > > The first design of the algorithm was > > for line in fileinput.input(sys.argv[1:]): > ip = line.split()[0] > if match_counter.has_key(ip): > match_counter[ip] += 1 > else: > match_counter[ip] = 1 > > And it took 3min 58 seg to give me the stats > > Then i tried a generator solution like > > def generateit(): > for line in fileinput.input(sys.argv[1:]): > yield line.split()[0] > > for ip in generateit(): > ...the same if sentence > > Instead of being faster it took 4 min 20 seg > > Should i leave fileinput behind? > Am i using generators with the wrong aproach? What's fileinput? A file-like object (unlikely)? Also, what's fileinput.input? I guess the reason why you don't see much difference (and is in fact slower) lies in what fileinput.input does. Generators excels in processing huge data since it doesn't have to create huge intermediate lists which eats up memory, given an infinite memory, a generator solution is almost always slower than straight up solution using lists. However in real life we don't have infinite memory, hogging our memory with the huge intermediate list would make the system start swapping, swapping is very slow and is a big hit to performance. This is the way generator could be faster than list. From benjamin.kaplan at case.edu Wed Dec 31 16:30:31 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 31 Dec 2008 16:30:31 -0500 Subject: Creating an application for Linux In-Reply-To: <7d2fe328-064c-46da-9150-7305b6f9e94e@b41g2000pra.googlegroups.com> References: <7d2fe328-064c-46da-9150-7305b6f9e94e@b41g2000pra.googlegroups.com> Message-ID: On Wed, Dec 31, 2008 at 4:06 PM, Mike Driscoll wrote: > Hi, > > My boss wants me to port one of my applications to Ubuntu. I > successfully ported it without too many headaches but now I need a way > to distribute it to people that may or may not already have the > dependencies my application requires. I'm a newb with Linux so I'm not > even sure what they call the distribution (rpms, deb, source code). > Debian packages (debs) are basically a zipped directory with all of the files, descriptions of where to put them, and a list of dependencies. You can find more about them here. http://www.debian.org/doc/FAQ/ch-pkg_basics.en.html > After browsing the various "installer" docs out there, it looks like > bbfreeze or PyInstaller might work, but I couldn't find any examples. > Any advice is appreciated. Thanks! When you create a debian package, you are trying to create a program for one specific distro. Deb files are installers, closer to MSI files than EXE (I assume you're coming from Windows). Using the deb files, you can install the program into /usr/lib or /usr/local/lib, put the program on the system path, and add it to the applications menu. You don't need to create a binary for this- you can just run the python files directly. Using debian packages, you can also add documentation and man pages. Apt will ensure that all of the dependencies are installed before your program is. Using apt, you can also uninstall the program easily. I haven't created any packages, so I don't know how hard it is to generate the package. bbfreeze and PyInstaller work differently. They create a binary executible that the user can run. Everything the user needs (Python and all your libraries) are put into a single file (or into an executable and a bunch of library files). This is easier to distribute and will work on all versions of Linux, but it won't be "installed" (to remove it, you have to manually remove all the files). If you want to use these, you should probably look at gui2exe (http://code.google.com/p/gui2exe/) rather than trying to figure out the commands yourself. Andrea Gavana, the program's creator, follows the wxPython-users list if you need help with it. > > I am using Python 2.5.2 and this is a wxPython application with > SqlAlchemy and a few other external packages. > > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 23:29:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Dec 2008 04:29:45 GMT Subject: Don't you just love writing this sort of thing :) References: Message-ID: <0149f773$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 20:19:22 -0800, Istvan Albert wrote: > On Dec 3, 8:07?pm, Lawrence D'Oliveiro central.gen.new_zealand> wrote: > > > > Originally, like many others here I said YIKES! but on a second read, it > is not that bad. It actually grows on you. Just like a disfiguring skin disease. > After looking at it one more time I found it neat, very concise without > being unreadable. It would have been far more concise without the for statement (not the entire loop) being spread over EIGHT lines... one of which was a lonely colon, all by itself. -- Steven From nick-news at net4u.hr Wed Dec 24 09:40:31 2008 From: nick-news at net4u.hr (Nikola Skoric) Date: Wed, 24 Dec 2008 14:40:31 +0000 (UTC) Subject: python web programming for PHP programmers Message-ID: I0m a python newbie with PHP background. I've tried to make a web app from one of my python scripts (which I haven't done before) and I ended up with: which works really nice :-D For some reason I can't find no "quick and dirty python web programming tutorial for PHP programmers" on google. :-D I don't need a general python tutorial, I just need a tutorial on how to make a hello world server side script with python. Any suggestions? -- "Now the storm has passed over me I'm left to drift on a dead calm sea And watch her forever through the cracks in the beams Nailed across the doorways of the bedrooms of my dreams" From swapnak01 at gmail.com Thu Dec 4 08:57:37 2008 From: swapnak01 at gmail.com (sona) Date: Thu, 4 Dec 2008 05:57:37 -0800 (PST) Subject: operational amplifier Message-ID: <2b4c352e-df02-40e9-ae63-d56bb1bbfc23@r15g2000prh.googlegroups.com> An operational amplifier, often called an op-amp , is a DC-coupled high-gain electronic voltage amplifier with differential inputs and, usually, a single output. Typically the output of the op-amp is controlled either by negative feedback, which largely determines the magnitude of its output voltage gain, or by positive feedback, which facilitates regenerative gain and oscillation. High input impedance at the input terminals and low output impedance are important typical characteristics. http://electronicstopics.blogspot.com/2008/10/operational-amplifier.html From jon at ffconsultancy.com Mon Dec 8 07:08:48 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Mon, 08 Dec 2008 12:08:48 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> Message-ID: <4ridnecnkLopkKDUnZ2dnUVZ8qbinZ2d@posted.plusnet> Xah Lee wrote: > The result and speed up of my code can be verified by anyone who has > Mathematica. You changed the scene that is being rendered => your speedup is bogus! Trace the scene I originally gave and you will see that your program is no faster than mine was. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From theller at python.net Fri Dec 19 11:43:25 2008 From: theller at python.net (Thomas Heller) Date: Fri, 19 Dec 2008 17:43:25 +0100 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> Message-ID: <6r219cFfc8ovU1@mid.individual.net> Mark Summerfield schrieb: > Just a follow-up to say that the book has now been published in the > U.S. > It is now in stock at InformIT, and should reach other stores, e.g., > Amazon, in a week or so. > > Also, the introduction, the first few pages of the first chapter, the > whole of chapter 12 (regular expressions), and the index are now > available for free download in a PDF from here: > http://www.informit.com/store/product.aspx?isbn=0137129297 Question from a non-native english speaker: is this now valid english? "One of Python?s great strengths" ^ "and also teaches Python?s functional programming features" ^ "The book?s approach is wholly practical" ^ Curious, Thomas From lkcl at lkcl.net Tue Dec 2 07:45:02 2008 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Tue, 2 Dec 2008 12:45:02 +0000 Subject: [ANN] Pyjamas 0.4: Python Web Toolkit Release Message-ID: This is the 0.4 Release of Pyjamas, the python-to-javascript compiler and Web Widget set and framework. Download Pyjamas 0.4 here: https://sourceforge.net/project/showfiles.php?group_id=239074 http://code.google.com/p/pyjamas/downloads/list Pyjamas started as a port of Google's Web Toolkit, to python. Explaining why Pyjamas (and GWT) is so significant takes some doing: the summary is that comprehensive desktop-like user interfaces can be developed very simply, to run in any modern web browser, without having to write a single line of JavaScript. Further recommended reading is here: http://advogato.org/article/993.html http://advogato.org/article/981.html The homepage is http://pyjs.org The sister project, Pyjamas-Desktop, is at http://pyjd.org Documentation on Pyjamas is considerable, and includes: http://pyjs.org/book/output/Bookreader.html http://pyjs.org/showcase/Showcase.html http://pyjd.sf.net/api http://pyjd.sf.net/controls_tutorial.html http://lkcl.net/pyjamas-desktop/docs/output/docui.html Also, as the Pyjamas UI API is near-identical to that of GWT 1.5, the GWT JavaDoc reference guide is still relevant: http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/index.html From lie.1296 at gmail.com Sat Dec 13 22:31:14 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 14 Dec 2008 03:31:14 +0000 (UTC) Subject: Python 3.0 crashes displaying Unicode at interactive prompt References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> Message-ID: On Sat, 13 Dec 2008 14:09:04 -0800, John Machin wrote: > On Dec 14, 8:07?am, "Chris Rebert" wrote: >> On Sat, Dec 13, 2008 at 12:28 PM, John Machin >> wrote: >> >> > Python 2.6.1 (r261:67517, Dec ?4 2008, 16:51:00) [MSC v.1500 32 bit >> > (Intel)] on win32 >> > Type "help", "copyright", "credits" or "license" for more >> > information. >> >>>> x = u'\u9876' >> >>>> x >> > u'\u9876' >> >> > # As expected >> >> > Python 3.0 (r30:67507, Dec ?3 2008, 20:14:27) [MSC v.1500 32 bit >> > (Intel)] on win 32 >> > Type "help", "copyright", "credits" or "license" for more >> > information. >> >>>> x = '\u9876' >> >>>> x >> > Traceback (most recent call last): >> > ?File "", line 1, in >> > ?File "C:\python30\lib\io.py", line 1491, in write >> > ? ?b = encoder.encode(s) >> > ?File "C:\python30\lib\encodings\cp850.py", line 19, in encode >> > ? ?return codecs.charmap_encode(input,self.errors,encoding_map)[0] >> > UnicodeEncodeError: 'charmap' codec can't encode character '\u9876' >> > in position >> > 1: character maps to >> >> > # *NOT* as expected (by me, that is) >> >> > Is this the intended outcome? >> >> When Python tries to display the character, it must first encode it >> because IO is done in bytes, not Unicode codepoints. When it tries to >> encode it in CP850 (apparently your system's default encoding judging >> by the traceback), it unsurprisingly fails (CP850 is an old Western >> Europe codec, which obviously can't encode an Asian character like the >> one in question). To signal that failure, it raises an exception, thus >> the error you see. >> This is intended behavior. > > I see. That means that the behaviour in Python 1.6 to 2.6 (i.e. encoding > the text using the repr() function (as then defined) was not intended > behaviour? > >> Either change your default system/terminal encoding to one that can >> handle such characters or explicitly encode the string and use one of >> the provided options for dealing with unencodable characters. > > You are missing the point. I don't care about the visual representation. > What I care about is an unambiguous representation that can be used when > communicating about problems across cultures/ > networks/mail-clients/news-readers ... the sort of problems that are > initially advised as "I got this UnicodeEncodeError" and accompanied by > no data or garbled data. Python defaulted to using strict encoding, which means to throw errors on unencodable characters, but this is NOT the only behavior, you can change the behavior to "replace using placeholder character" or "ignore any errors and discard unencodable characters" | errors can be 'strict', 'replace' or 'ignore' and defaults | to 'strict'. If you don't like the default behavior or you want another kind of behavior, you're welcome to file a bug report at http://bugs.python.org >> Also, please don't call it a "crash" as that's very misleading. The >> Python interpreter didn't dump core, an exception was merely thrown. > > "spew nonsense on the screen and then stop" is about as useful and as > astonishing as "dump core". That's an interesting definition of crash. You're just like saying: "C has crashed because I made a bug in my program". In this context, it is your program that crashes, not python nor C, it is misleading to say so. It will be python's crash if: 1. Python 'segfault'ed 2. Python interpreter exits before there is instruction to exit (either implicit (e.g. falling to the last line of the script) or explicit (e.g sys.exit or raise SystemExit)) 3. Python core dumped 4. Python does something that is not documented From torriem at gmail.com Mon Dec 22 11:21:45 2008 From: torriem at gmail.com (Michael Torrie) Date: Mon, 22 Dec 2008 09:21:45 -0700 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: <494FBE99.6050507@gmail.com> r wrote: > Steven, > Would you like to elaborate on -why- escaped backslashes are needed in > strings... i waiting??? Some character was needed. It just happens that backslashes have been used in this manner for composing nonprintable sequences, codes, etc. It's only in use because someone arbitrarily picked it about 40 years ago. Any character could have been used; any such character would still be have to escaped. Kind of funny that you are complaining about Python in particular when this behavior is in almost all languages today, including Perl, Ruby, Don't blame python for a mistake that Microsoft made, that of choosing a commonly-accepted escape character (long before Python was even though of!) as their path delimiter. Fortunately sane operating systems use a standard slash. Even Windows APIs accept forward slashes as path delimiters. So really your complaint about the backslash is a bit silly. Are you going to campaign that C# and Java also "fix" this problem by choosing another character? From eric at ericaro.net Thu Dec 18 17:30:19 2008 From: eric at ericaro.net (eric) Date: Thu, 18 Dec 2008 14:30:19 -0800 (PST) Subject: Factoring Polynomials References: <5dfe1cf3-530d-4e31-833e-e26db85611be@d36g2000prf.googlegroups.com> Message-ID: On Dec 18, 9:40?pm, "J. Cliff Dyer" wrote: > On Thu, 2008-12-18 at 11:52 -0800, eric wrote: > > On Dec 18, 8:37 pm, collin.da... at gmail.com wrote: > > > I am trying to write a simple application to factor polynomials. I > > > wrote (simple) raw_input lines to collect the a, b, and c values from > > > the user, but I dont know how to implement the quadratic equation > > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > > into python. Any ideas? > > > with numpy: > > from numpy import * > > > s=[1,-1] > > x = -b+s*sqrt( b**2-4*a*c )/(2*a) > > > Eric > > Without the Nump. > > def polynomial(a, b, c): > ? ? N = ((b**2 - 4*a*c)**.5) / 2*a > ? ? return (-b + N, -b - N) there is a little mistake in your formula : def roots_of(a, b, c): N = ((b**2 - 4*a*c)**.5) return ((-b + N)/(2*a), (-b - N)/(2*a)) but I stick with numpy, numpy is heavy, but not as much as using a computer to solve this problem ! And numpy should be standard module for computer science student ! Eric http://codeslash.blogspot.com From febaen at gmail.com Tue Dec 16 09:10:31 2008 From: febaen at gmail.com (feba) Date: Tue, 16 Dec 2008 06:10:31 -0800 (PST) Subject: Free place to host python files? Message-ID: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> I'm getting started in python, and it would be helpful to have a place to put up various code snippets I've made, so I don't have to send them individually to each person I want to show it to. I'd prefer to use something that would give me a directory for my use only, instead of something where you can only upload one at a time. I'd especially like to avoid stuff that uses CAPTCHAs and/or forced waiting periods. I'd really rather not have to run a server off my own computer, if it can be avoided at all. From robin at reportlab.com Thu Dec 4 09:27:49 2008 From: robin at reportlab.com (Robin Becker) Date: Thu, 04 Dec 2008 14:27:49 +0000 Subject: schizophrenic view of what is white space Message-ID: <4937E8E5.2090306@chamonix.reportlab.co.uk> Is python of two minds about what is white space. I notice that split, strip seem to regard u'\xa0' (NO-BREAK SPACE) as white, but that code is not matched by the \s pattern. If this difference is intended can we rely on it continuing? >>> u'a b'.split() [u'a', u'b'] >>> u'a\xa0b'.split() [u'a', u'b'] >>> re.compile(r'\s').search(u'a b') <_sre.SRE_Match object at 0x00DBB2C0> >>> re.compile(r'\s').search(u'a\xa0b') >>> -- Robin Becker From steve at REMOVE-THIS-cybersource.com.au Fri Dec 12 07:21:55 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Dec 2008 12:21:55 GMT Subject: Removing None objects from a sequence References: Message-ID: <01524eee$0$20617$c3e8da3@news.astraweb.com> On Fri, 12 Dec 2008 10:18:35 +0100, Filip Gruszczy?ski wrote: > Hi! > > I would like to iterate over a sequence nad ignore all None objects. The > most obvious way is explicitly checking if element is not None, but it > takes too much space. Too much space??? seq = [x for x in seq if x is not None] It's one line, less than 40 characters. If your hard disk is so full that you're worrying about 40 characters, I suggest you need a bigger disk. > And I would like to get something faster. Faster than what? What speed do we have to beat? > I can use > [ sth for sth in self.__sth if not sth is None ], but I don't know if > that's the best way. Who cares if it's the "best" way? What's important is, is it good enough? It is easier to optimize correct code than to correct optimized code. Get your code working first, then worry about shaving microseconds off the runtime *if you need to*. > I checked itertools, but the only thing that seemed > ok, was ifilter - this requires seperate function though, so doesn't > seem too short. How can I get it the shortest and fastest way? You could do this: seq = filter(None, seq) but only if you know that seq doesn't contain any false objects other than None. -- Steven From martin at v.loewis.de Mon Dec 8 20:04:18 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 09 Dec 2008 02:04:18 +0100 Subject: python-devel download and install In-Reply-To: References: Message-ID: <493DC412.8060909@v.loewis.de> > I am developing in Python version 2.5.2 and need to install and download > the python-devel library. (This is needed so I can build and install > mysql-python.) Where can I find find this module to download and > build/installation instructions? I have been unable to find the source > online to download. > > I am not root on the box where I need to install this module so I need > the source (rpm/deb packages will not do). The sources of Python 2.5.2 are available from http://www.python.org/ftp/python/2.5.2/Python-2.5.2.tar.bz2 The term "python-devel" specifically refers to a rpm/deb package, though. You might need to layout the sources so that they meet your needs (e.g. by installing them locally). Regards, Martin From hniksic at xemacs.org Mon Dec 29 15:22:44 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 29 Dec 2008 21:22:44 +0100 Subject: multiprocessing vs thread performance References: Message-ID: <877i5ipw8b.fsf@mulj.homelinux.net> Roy Smith writes: > In article , > Christian Heimes wrote: > >> You have missed an important point. A well designed application does >> neither create so many threads nor processes. The creation of a thread >> or forking of a process is an expensive operation. You should use a pool >> of threads or processes. > > It's worth noting that forking a new process is usually a much more > expensive operation than creating a thread. If by "forking" you mean an actual fork() call, as opposed to invoking a different executable, the difference is not necessarily that great. Modern Unix systems tend to implement a 1:1 mapping between threads and kernel processes, so creating a thread and forking a process require similar amount of work. On my system, as measured by timeit, spawning and joining a thread takes 111 usecs, while forking and waiting for a process takes 260. Slower, but not catastrophically so. > Not that I would want to create 100,000 of either! Agreed. > Not everybody realizes it, but threads eat up a fair chunk of memory > (you get one stack per thread, which means you need to allocate a > hunk of memory for each stack). I did a quick look around; 256k > seems like a common default stack size. 1 meg wouldn't be unheard > of. Note that this memory is virtual memory, so it doesn't use up the physical RAM until actually used. I've seen systems running legacy Java applications that create thousands of threads where *virtual* memory was the bottleneck. From alex.pulver at gmail.com Sun Dec 21 10:52:02 2008 From: alex.pulver at gmail.com (Alex) Date: Sun, 21 Dec 2008 07:52:02 -0800 (PST) Subject: How to read stdout from subprocess as it is being produced References: <263c3946-86aa-4db0-bdaf-42d0c8e5e5d6@q18g2000vbn.googlegroups.com> Message-ID: <1651a451-dd38-4733-8685-5d9f1906785e@i24g2000prf.googlegroups.com> On Dec 19, 5:09?pm, Albert Hopkins wrote: > On Fri, 2008-12-19 at 06:34 -0800, Alex wrote: > > Hi, > > > I have a Pyhon GUI application that launches subprocess. > > I would like to read the subprocess' stdout as it is being produced > > (show it in GUI), without hanging the GUI. > > > I guess threading will solve the no-hanging issue, but as far as I > > searched for now, I've only seen how to read the stdout after > > subprocess is finished. > > I believe that's going to be highly dependent upon the particular, yet > unspecified, GUI toolkit/API. > > There are probably a few ways. You're toolkit might native support for > this, but one way would be to use a timer. ?Here is some pseudocode: > > class MyWindow(toolkit.Window): > ? ? def __init__(self, ...): > ? ? ? ? ... > ? ? ? ? self.subprocess = subprocess.Popen(..., stdout=subprocess.PIPE) > ? ? ? ? self.running = True > > ? ? ? ? ... > ? ? ? ? toolkit.set_timeout(TIMEOUT_VAL, self.read_stdout) > > ? ? def read_stdout(self, ...): > ? ? ? ? if not self.running: > ? ? ? ? ? ? return > ? ? ? ? char = self.subprocess.stdout.read(1) > ? ? ? ? if char == '': > ? ? ? ? ? ? self.running = False > ? ? ? ? ? ? return > ? ? ? ? self.update_something(char) > ? ? ? ? toolkit.set_timeout(TIMEOUT_VAL, self.read_stdout) Hi, Thanks a lot for the tip! Alex From bearophileHUGS at lycos.com Tue Dec 23 14:51:15 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 23 Dec 2008 11:51:15 -0800 (PST) Subject: 2to3 used in the Shootout Message-ID: <4f1a8f03-fd7f-49ea-8031-61f73fb0c0e8@x16g2000prn.googlegroups.com> They have translated the Python benchmarks of the Shootout site from Py2 to Py3 using 2to3: http://shootout.alioth.debian.org/u32/benchmark.php?test=all&lang=python3 It shows some "performance bugs" of Python3 itself (especially regarding the binary-trees benchmark, that was unexpected by me), and two points where 2to3 may be improved, for example after the translation this gives error: table=string.maketrans('ACBDGHK\nMNSRUTWVYacbdghkmnsrutwvy', 'TGVHCDM \nKNSYAAWBRTGVHCDMKNSYAAWBR')): Gives: TypeError: maketrans arguments must be bytes objects Bye, bearophile From tjreedy at udel.edu Fri Dec 19 02:43:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 19 Dec 2008 02:43:58 -0500 Subject: Factoring Polynomials In-Reply-To: <919062f9-765e-4279-aa26-2c130d4deacf@o4g2000pra.googlegroups.com> References: <919062f9-765e-4279-aa26-2c130d4deacf@o4g2000pra.googlegroups.com> Message-ID: Collin D wrote: > UPDATE: > ' > > #import > from math import sqrt > > # collect data > a = float(raw_input('Type a value: ')) > b = float(raw_input('Type b value: ')) > c = float(raw_input('Type c value: ')) > > # create solver > def solver(a,b,c): > if b**2 - 4*a*c < 0: > return 'No real solution.' > else: > sol1 = (-1 * b + (sqrt(b**2 - 4*a*c))) / 2*a > sol2 = (-1 * b - (sqrt(b**2 - 4*a*c))) / 2*a > return (sol1, sol2) > > # execute > print solver(a,b,c) TEST your code. From Allen.Chenal at gmail.com Fri Dec 5 03:09:08 2008 From: Allen.Chenal at gmail.com (Allen) Date: Fri, 5 Dec 2008 00:09:08 -0800 (PST) Subject: How to distribute C/C++ python extension module on Linux? Message-ID: I have build an extension module PyRPC.so (why not be libPyRPC.so?). The PyRPC.so uses API in libRPCPacker.so. How to distribute the PyRPC.so? I just put PyRPC.so and libRPCPacker.so in the same folder. And under this folder, run python. It tells PyRPC module cannot find a method in libRPCPacker.so. From __peter__ at web.de Wed Dec 17 03:48:01 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 17 Dec 2008 09:48:01 +0100 Subject: eval() and global variables References: Message-ID: Juan Pablo Romero M?ndez wrote: > Suppose this function is given: > > def f(x,y): > return x+y+k > > > Is it possible to somehow assign a value to k without resorting to > making k global? You can replace the function's global dictionary: >>> def f(x, y): ... return x+y+k ... >>> function = type(f) >>> function(f.func_code, dict(k=1))(2, 3) 6 >>> k Traceback (most recent call last): File "", line 1, in NameError: name 'k' is not defined This is a hack, of course. Peter From andrei.avk at gmail.com Sat Dec 6 18:47:51 2008 From: andrei.avk at gmail.com (Rainy) Date: Sat, 6 Dec 2008 15:47:51 -0800 (PST) Subject: how to get a beep, OS independent ? References: Message-ID: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> On Dec 6, 3:40?pm, Stef Mientki wrote: > hello, > > I want to give a small beep, > for windows there's message-beep, > and there seems to be something like " curses" , > but that package seems to be totally broken in P2.5 for windows. > > Any other suggestions ? > > thanks, > Stef Mientki For win there's winsound, you have to check sys.platform and do what's necessary for the platform in question. In linux I think you can just print '\a' (or does that only work in terminals?). If you know that ext. speakers are always on, you can do a nicer beep by using some wav file, in linux it's probably easiest to use an external program to play it, like wavplay. Basically, there is no single answer, it depends on circumstances. From research at johnohagan.com Fri Dec 19 21:34:33 2008 From: research at johnohagan.com (John O'Hagan) Date: Sat, 20 Dec 2008 02:34:33 +0000 Subject: Namespaces, multiple assignments, and exec() Message-ID: <200812200234.33852.research@johnohagan.com> I have a lot of repetitive assignments to make, within a generator, that use a function outside the generator: var1 = func("var1", args) var2 = func("var2", args) var3 = func("var3", args) etc... In each case the args are identical, but the first argument is a string of the name being assigned. It works fine but I'd like to reduce the clutter by doing the assignments in a loop. I've tried using exec(): for name in name_string_list: exec(name + ' = func(\"' + name + '\", args)') but in the local namespace it doesn't understand func(), and if I give it globals() it doesn't understand the args, which come from within the generator. What's a good way to do this kind of thing? Thanks, John From george.sakkis at gmail.com Mon Dec 15 10:34:01 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 15 Dec 2008 07:34:01 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <355f1cfe-6abb-4d2c-8bf4-3aa62e713c1f@w34g2000yqm.googlegroups.com> Message-ID: <504053d8-c482-4db0-8a2c-dcb3f1769eed@s24g2000vbp.googlegroups.com> On Dec 15, 8:15?am, Luis M. Gonz?lez wrote: > On Dec 15, 1:38?am, cm_gui wrote: > > > hahaha, do you know how much money they are spending on hardware to > > make > > youtube.com fast??? > > > > By the way... I know of a very slow Python site called YouTube.com. In > > > fact, it is so slow that nobody ever uses it. > > Buddy, just stop whining and go with c++ if it makes you happy. > By the way, what's the blazingly fast application you need to write so > desperately? > What kind of performance problem have you find in python that makes > you so unhappy? > What are you going to do with all the extra speed provided by c++ (a > Hello World! ?)... Folks, do you *really* feel the urge to feed this troll and his 8-year- old "arguments" again and again ? Please think twice before hitting send on this pointless thread. From lolekk1223 at wp.pl Tue Dec 2 10:48:28 2008 From: lolekk1223 at wp.pl (lolekk1223 at wp.pl) Date: Tue, 2 Dec 2008 07:48:28 -0800 (PST) Subject: Ideal girl dance WEBCAM ! Ideal boobs ! Message-ID: http://yeba.pl/show/movies/5257/Perfect_babe_-_Idealna_kobieta From joel.hedlund at gmail.com Tue Dec 16 08:32:39 2008 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Tue, 16 Dec 2008 14:32:39 +0100 Subject: weird dict problem, how can this even happen? In-Reply-To: References: Message-ID: Duncan Booth wrote: > I think you probably are correct. The only thing I can think that might > help is if you can catch all the situations where changes to the dependent > values might change the hash and wrap them up: before changing the hash pop > the item out of the dict, then reinsert it after the change. That would probably require a lot of uncomfortable signal handling, especially for a piece of functionality I'd like to be as unobtrusive as possible in the application. > Alternatively give up on defining hash and __eq__ for FragmentInfo and rely > on object identity instead. Object identity wouldn't work so well for caching. Objects would always be drawn as they appeared for the first time. No updates would be shown until the objects were flushed from the cache. I've been experimenting with a list cache now and I can't say I'm noticing any change in performance for a cache of 100 items. I'm still using the hash to "freeze" a sort of object tag in order to detect changes, and I require both hash and object equality for cache hits, like so: > def index(self, key): > h = hash(key) > for i, item in enumerate(self.items): > if item.hash == h and item.key == key: > return i > raise KeyError(key) This seems to do what I want and does OK performance wise. Thanks again! /Joel From bigblueswope at gmail.com Wed Dec 3 22:30:14 2008 From: bigblueswope at gmail.com (BJ Swope) Date: Wed, 3 Dec 2008 22:30:14 -0500 Subject: Obtaining SMTP address of a sender and receiver of an outlook mail In-Reply-To: References: Message-ID: If you have access to the AD server that hosts those DNs you can use python's ldap module to retrieve the smtp attribute for the DN you've just parsed from the message. On Wed, Dec 3, 2008 at 2:06 AM, venutaurus539 at gmail.com < venutaurus539 at gmail.com> wrote: > Hi all, > I am trying to use python for extracting contents of an outlook > email. For extracting the list of Recipients addresses I tried using > the "MAPI.message.Recipients.Address" property, but the problem I am > facing is that it is giving the complete DN name which is putting me > in further complications. Is there any way to obtain the actual SMTP > mail address (username at domain.com) from the above object? I searched > for it in the MSDN help but couldn't succeed. > > Thanks in advance, > Venu > -- > http://mail.python.org/mailman/listinfo/python-list > -- We are all slave to our own paradigm. -- Joshua Williams If the letters PhD appear after a person's name, that person will remain outdoors even after it's started raining. -- Jeff Kay Fascism is a term used to describe authoritarian nationalist political ideologies or mass movements that are concerned with notions of cultural decline or decadence and seek to achieve a millenarian national rebirth by exalting the nation or race, and promoting cults of unity, strength and purity. - Wikipedia -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Dec 8 09:00:54 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 08 Dec 2008 15:00:54 +0100 Subject: Beginner trying to understand functions. References: Message-ID: simonh wrote: > In my attempt to learn Python I'm writing a small (useless) program to > help me understand the various concepts. I'm going to add to this as I > learn to serve as a single place to see how something works, > hopefully. Here is the first approach: > That works fine. Then I've tried to use functions instead. The first > two work fine, the third fails: > def getName(): > name = input('Please enter your name: ') > print('Hello', name) > > def getAge(): > while True: > try: > age = int(input('Please enter your age: ')) > break > except ValueError: > print('That was not a valid number. Please try again.') > > def checkAge(): > permitted = list(range(18, 31)) > if age in permitted: > print('Come on in!') > elif age < min(permitted): > print('Sorry, too young.') > elif age > max(permitted): > print('Sorry, too old.') > > getName() > getAge() > checkAge() > > I get this error message: NameError: global name 'age' is not > defined. > > I'm stuck, can someone help? Thanks. Generally, when you calculate something within a function you tell it the caller by returning it: >>> def get_age(): ... return 74 ... >>> get_age() 74 >>> age = get_age() >>> age 74 And if you want a function to act upon a value you pass it explicitly: >>> def check_age(age): ... if 18 <= age <= 30: ... print("Come in") ... else: ... print("Sorry, you can't come in") ... >>> check_age(10) Sorry, you can't come in >>> check_age(20) Come in To check the age determined by the get_age() function you do: >>> age = get_age() >>> check_age(age) Sorry, you can't come in Peter From mohitranka at gmail.com Wed Dec 3 09:18:29 2008 From: mohitranka at gmail.com (Mohit Ranka) Date: Wed, 3 Dec 2008 19:48:29 +0530 Subject: hello In-Reply-To: <63fb26950812030543j2e019219r618390d96a1a493a@mail.gmail.com> References: <63fb26950812030543j2e019219r618390d96a1a493a@mail.gmail.com> Message-ID: <63fb26950812030618u4a957688u7119e15ede257ac6@mail.gmail.com> Hi, Apologies for the previous email. Some hacker/spammer hacked my email password, and sent email using it. Thanks and regards, Mohit Ranka -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp at rebertia.com Fri Dec 26 17:16:30 2008 From: clp at rebertia.com (Chris Rebert) Date: Fri, 26 Dec 2008 14:16:30 -0800 Subject: strange behavior of math.sqrt() in new 3.0 version In-Reply-To: References: Message-ID: <47c890dc0812261416t4c4bc19apc1b8652cee729b@mail.gmail.com> On Fri, Dec 26, 2008 at 1:52 PM, wrote: > I'm a newbee trying 3.0 Please help with math.sqrt() > > At the command line this function works correctly > >>> import math > n = input("enter a number > ") raw_input() was renamed input() in Python 3.0, and it returns a *string*, not a *number*. Therefore, you need to convert the string to an int or float. Change the line to: n = float(input("enter a number > ")) And it should work just fine. > s = math.sqrt(n) > An entry of 9 or 9.0 will yield 3.0 > > Yet the same code in a script gives an error message > Script1 > import math > n = input("enter a number > ") > s = math.sqrt(n) > > Traceback (most recent call last) : > File "", line 1, in > File "script1.py" line 3 in > s = math.sqrt(n) > TypeError : a float is required You're currently giving it a string, not a number, which is nonsensical, hence the TypeError. I presume ints would be coerced to floats by the function. > Entering 9 or 9.0 gives same error message. > > According to the math module the results of all > functions are floats. However it says nothing about > inputs. > > Strangely the above code runs fine in version 2.5 ( ? ) > and will handle large integers. > > I've read the documentation for 3.0 including the section > "Floating Point Arithmetic: Issues & Limitations" and it > helps nada. You should read "What's New in Python 3.0", it covers changes such as the one you've encountered - http://docs.python.org/3.0/whatsnew/3.0.html Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From robert.kern at gmail.com Thu Dec 18 16:27:17 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 18 Dec 2008 15:27:17 -0600 Subject: confused about __str__ vs. __repr__ In-Reply-To: References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> <6qv7kfFeuf65U1@mid.uni-berlin.de> <6qv9v4Ff1lv9U1@mid.uni-berlin.de> Message-ID: Mikael Olofsson wrote: > Diez B. Roggisch wrote: >> Yep. And it's easy enough if you don't care about them being different.. >> >> def __repr__(self): >> return str(self) > > If I ever wanted __str__ and __repr__ to return the same thing, I would > make them equal: > > def __str__(self): > return 'whatever you want' > __repr__ = __str__ > > That makes it more obvious to me what's going on. As a bonus, it saves > one method call for every repr call. Or just define __repr__(). str() falls back to __repr__() if __str__() is not defined. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From joe at strout.net Fri Dec 5 14:00:59 2008 From: joe at strout.net (Joe Strout) Date: Fri, 5 Dec 2008 12:00:59 -0700 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: <5u8o06xbqf.ln2@joeserver.homelan.net> References: <5u8o06xbqf.ln2@joeserver.homelan.net> Message-ID: On Dec 5, 2008, at 11:36 AM, Johannes Bauer wrote: >> I suspect that '?' after \n (\u0a00) is indicates not 'question-mark' >> but 'uninterpretable as a utf16 character'. The traceback below >> confirms that. It should be an end-of-file marker and should not be >> passed to Python. I strongly suspect that whatever wrote the file >> screwed up the (OS-specific) end-of-file marker. I have seen this >> occasionally on Dos/Windows with ascii byte files, with the same >> symptom >> of reading random garbage pass the end of the file. Or perhaps >> end-of-file does not work right with utf16. > > So UTF-16 has an explicit EOF marker within the text? No, it does not. I don't know what Terry's thinking of there, but text files do not have any EOF marker. They start at the beginning (sometimes including a byte-order mark), and go till the end of the file, period. > I cannot find one in original file, only some kind of starting > sequence I suppose > (0xfeff). That's your byte-order mark (BOM). > The last characters of the file are 0x00 0x0d 0x00 0x0a, > simple \r\n line ending. Sounds like a perfectly normal file to me. It's hard to imagine, but it looks to me like you've found a bug. Best, - Joe From news123 at free.fr Sun Dec 14 07:15:28 2008 From: news123 at free.fr (News123) Date: Sun, 14 Dec 2008 13:15:28 +0100 Subject: 1 or 1/0 doesn't raise an exception In-Reply-To: References: Message-ID: <4944f8e0$0$32019$426a74cc@news.free.fr> Hi. r wrote: > These are just the kind of things that make Python so beautiful ;) > Thanks Guido! You shouldn't forget to thank K&R ;-) Shortcutting logical operation shortcuts existed already in C and has been adopted by quite a lot of programming languages. bye N From tjreedy at udel.edu Mon Dec 8 17:09:34 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Dec 2008 17:09:34 -0500 Subject: Beginner trying to understand functions. In-Reply-To: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> Message-ID: cadmuxe wrote: > i think we should use raw_input('Please enter your name: ') instead of > input('Please enter your name: ') 3.0 input == 2.x raw_input 2.5 input == Posters: please include Python version used, as correct answers may depend on that. From steve at holdenweb.com Fri Dec 19 23:02:10 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 19 Dec 2008 23:02:10 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <015c47ad$0$20656$c3e8da3@news.astraweb.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c47ad$0$20656$c3e8da3@news.astraweb.com> Message-ID: <494C6E42.8080008@holdenweb.com> Steven D'Aprano wrote: > On Fri, 19 Dec 2008 10:25:30 -0700, Michael Torrie wrote: > >> So funny that now that Python 3.0 is actually released we have people >> acting all surprised like they've never seen any of the new features in >> Python 3.0 coming. However these features have been discussed for >> years! And debated! > > Debated by who? The entire Python-using community? Every single Python > programmer? Or just the small proportion of Python developers who are > also core developers? > > Are you *really* surprised that some people had never heard of the > changes being debated until it was too late? > It isn't the least surprising that some people have been taken by surprise by the changes. Neither is it surprising that some of them don't like the changes that much. However, at least in the open source world one has the *opportunity* to make one's voice heard and one's opinion known, even thought he majority prefer to remain consumers of the output of open source projects. Where commercial projects are concerned the major influence one has is a post-facto vote with one's wallet. I hope, however, that those who don't like the changes but didn't bother to track developments don't feel in any way disenfranchised. They are still welcome to make their input, and of course there is nothing to stop them keeping Python 2.X alive for as long as they wish. [misconception about print's role] >> Furthermore, the new {} >> notation allows many, many more options for formatting to be used. Want >> to display a floating point number with $#.## notation, and ($#.##) for >> negative? It's all now possible. Couldn't be done before. > > Of course it could be. You just needed to write your own formatting > engine. What you mean is that it couldn't be done with % formatting and > nothing else. > > >> In short, this is a huge improvement, and backwards compatibility is >> preserved for the 2.x style for those that wish it. > > > There clearly is a need for a more heavyweight formatting solution than % > and string.Template. There are things that can't be done easily with % > alone, and format() will make them much simpler. I have no objection to > the addition of the format() method (although I wonder whether it might > have been better as a function). > That's doubtless a debate that will play for a long time, with no really clear advantage either way. Programmers just like to debate these things. Of course it's a trivial addition: def format(s, *args, **kw): return s.format(*args, **kw) [I put **kw in becuase it's easier than checking the docs to se whether keyword arguments are specified]. This doesn't mean there won't be fifteen more posts on this thread about it. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From rayene.benrayana at gmail.com Mon Dec 1 15:23:10 2008 From: rayene.benrayana at gmail.com (Rayene Ben Rayana) Date: Mon, 1 Dec 2008 21:23:10 +0100 Subject: Python introspection and namespace weird question In-Reply-To: <47c890dc0812011037u64076950o186af7477269cc0a@mail.gmail.com> References: <47c890dc0812011037u64076950o186af7477269cc0a@mail.gmail.com> Message-ID: Thanks Chris, Yeah it is kinda meta thing. My app allows to create a scene (a set of GUI objects). A scene can be saved as a python script. And, it can be loaded again using execfile(). each GUI object has a label. So, in the script scene, declaring an object in a scene file should look like this: red_car = MyVehicleClass(*label* = 'red_car') But, I wanted to simplify the syntax of scene files and avoid repetition so it would look like red_car = MyVehicleClass() with the *label* attribute automatically set to the name of the corresponding variable. I tried your locals().iteritems tip and it works perfectly. The question now is: Given what I just explained, do you still think it is bad programming to do that ? Should I better use the first syntax ? Cheers, Rayene, I want to use that to simplify the syntax of the On Mon, Dec 1, 2008 at 7:37 PM, Chris Rebert wrote: > On Mon, Dec 1, 2008 at 6:04 AM, Rayene Ben Rayana > wrote: > > Hello everybody, > > > > Is there an easy way to do something like this in python ? > > > >>>> red_car = MyVehicleClass() > >>>> car = red_car > >>>> car.labels() > > ['red_car' , 'car' ] > > > > In other words, does an instance has access to its name pointers ? > > In short, No. (Cue another debate over whether Python uses call-by-X > semantics...) > > Typically people who want to do such things actually want/should use a > dictionary mapping string keys to instance values instead. > > Note that in certain limited cases, voodoo involving the locals() or > globals() built-in functions or the `inspect` module can work, but not > in the common general case. But generally these techniques are > considered bad style and kludgey unless you're writing a debugger or > something equally meta, with using a dictionary as explained > previously being much preferred. > > For example, for your particular code above, the following happens to work: > [name for name, obj in locals().iteritems() if obj is car] #==> > ['red_car' , 'car' ] > > But this will only give the names in the current function of the > particular car object. Likewise, globals() works only for module-level > names, and the `inspect` module's magic only works for names in > calling functions (i.e. those below the current one in the callstack). > > Cheers, > Chris > -- > Follow the path of the Iguana... > http://rebertia.com > > > > > Thanks in advance, > > > > Rayene > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at mrabarnett.plus.com Tue Dec 30 14:04:11 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 30 Dec 2008 19:04:11 +0000 Subject: duck typing at will In-Reply-To: <6e1bfdea0812301042x70ab57capf99ce73d364d54db@mail.gmail.com> References: <6e1bfdea0812301042x70ab57capf99ce73d364d54db@mail.gmail.com> Message-ID: <495A70AB.4020401@mrabarnett.plus.com> Jose Mora wrote: > Duck typing is called that way because "If it looks like a duck and > quacks like a duck, it must be a duck." I think it would be good to > have also "If the programmer wants to deal with it like a duck, it > must be a duck" > > I mean, some tasks are rather boring in python when compared with php, > for example, let's imagine we have a dictionary that contains > dictionaries that contain the times that a key appears. We, or at > least I, would like to write something as short as: > > dict[k1][k2] += 1 > > However we will have to do a longer code (this is the smallest code I > could come up with): > > dict = {} > if not k1 in dict: > dict[k1] = {} > if not k2 in dict[k1]: > dict[k1][k2] = 0 > dict[k1][k2] += 1 > > I know it is not the Apocalypse nor something really important when > compared with other things, but maybe it would be better if it wasn't > necessary to declare the variables when they are built-in types or to > initialize the keys in a dictionary, having special values (the > identity element of the operation that causes the initialization) to > initialize when it has not been done, initializing with the most > general type that supports the operation that causes the > initialization, casting to other type if necessary after that. > > This is just an idea, maybe I'm not the first one suggesting it, or > maybe it is completely impossible to implement it because it would > require deep changes in python, but I wanted to discuss it. > You could use defaultdict like this: from collections import defaultdict my_dict = defaultdict(lambda: defaultdict(int)) my_dict[k1][k2] += 1 The disadvantage is that my_dict will then return values even when you don't want it to: >>> print my_dict[unknown_key] defaultdict(, {}) so after you've filled it you might want to turn it into a 'normal' dict of dict: my_dict = dict((key, dict(inner.iteritems())) for key, inner in my_dict.iteritems()) From cjw at ncf.ca Fri Dec 19 19:32:22 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Fri, 19 Dec 2008 19:32:22 -0500 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <6r219cFfc8ovU1@mid.individual.net> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> Message-ID: Thomas Heller wrote: > Mark Summerfield schrieb: >> Just a follow-up to say that the book has now been published in the >> U.S. >> It is now in stock at InformIT, and should reach other stores, e.g., >> Amazon, in a week or so. >> >> Also, the introduction, the first few pages of the first chapter, the >> whole of chapter 12 (regular expressions), and the index are now >> available for free download in a PDF from here: >> http://www.informit.com/store/product.aspx?isbn=0137129297 > > Question from a non-native english speaker: is this now valid english? > > "One of Python???s great strengths" > ^ > "and also teaches Python???s functional programming features" > ^ > "The book???s approach is wholly practical" > ^ > > Curious, > Thomas No. Is this a quote from some advertising stuff or was it written by the author? Colin W. From aleksandr.goretoy at gmail.com Sat Dec 27 19:25:05 2008 From: aleksandr.goretoy at gmail.com (alex goretoy) Date: Sat, 27 Dec 2008 18:25:05 -0600 Subject: parsing csv files class In-Reply-To: References: <49562755.6050205@byoteki.com> Message-ID: How would I change this to work with numpy: (Would it be more feasible for storing big files? 300-30,000 records) for row in reader: self.buffer.append(row) s,a=[],{} for j in range(len(self.buffer[0])): a[self.buffer[0][j]]=row[j] self.bufferp.append(a) i+=1 self.total = i-1 Instead of doing self.buffer.append(row) would I initialize numpy like this: self.buffer=numpy.array() and then in the loop do: self.buffer.append(row) ? How do I achieve the same for lower code, where it appends to a dict with header of each column? Thank you. On Sat, Dec 27, 2008 at 5:31 PM, alex goretoy wrote: > I might as well add a UnicodeReader and UnicodeWriter and support for > passing delimiter in from other classes. At the same time. Anyone have a > good csv class I can pick thru? I'm planning on posting my mysql adn curl > classes that I use in my projects I just want to make them better and have > less error. > > > On Sat, Dec 27, 2008 at 5:18 PM, alex goretoy > wrote: > >> It's main concern is to grab the file into the buffer for use in other >> classes. The self.soc.me_him is just so I know when its ENTERING or EXITING >> in that function when I run it in terminal. It's prints it in color. My main >> concern right now is to add error handling. I'm still learning how to use >> assert and yield, but I got try,except down pat. All this class does is >> grabs the file either from http or local storage into a buffer and I use >> that in other classes. I want to add support for creating creating csv as >> well. I read the doc on csv and will try some things out soon. Thanks for >> helping me. >> >> >> On Sat, Dec 27, 2008 at 2:15 PM, Gabriel Genellina < >> gagsl-py2 at yahoo.com.ar> wrote: >> >>> En Sat, 27 Dec 2008 11:02:13 -0200, Gary M. Josack >>> escribi?: >>> >>>> alex goretoy wrote: >>>> >>> >>> I know it's messy with all those self.soc.* functions, but it works in >>>>> one of my current project. I just want to make it more pythonic I also want >>>>> to add capability for makeing csv file if I give it input like: >>>>> 1234,something nice, hey this is something nice >>>>> 2468,something else, something else >>>>> >>>> >>> reader = csv.reader(file(filename, "rb")) >>>>> try: >>>>> for row in reader: >>>>> self.buffer.append(row) >>>>> s,a=[],{} >>>>> >>>> >>> Do you know that there is a csv module in the standard library already? >>>> >>> >>> I'd say he already knows, he even used it in the code. >>> >>> To Alex G.: I didn't understand what's the purpose of this class. >>> Probably you want to do too much things in the same place; looks like it has >>> multiple concerns, and that's not a good idea usually. >>> >>> -- >>> Gabriel Genellina >>> >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> >> >> >> -- >> ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? >> ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? >> >> >> >> -- >> ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? >> ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? >> > > > > -- > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > -- ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp at rebertia.com Wed Dec 24 01:43:19 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 23 Dec 2008 22:43:19 -0800 Subject: socket send help In-Reply-To: References: Message-ID: <47c890dc0812232243l2923696aid4a36020a7acfa7a@mail.gmail.com> On Tue, Dec 23, 2008 at 9:59 PM, greywine at gmail.com wrote: > Hi everyone, > > New guy here. I'm trying to figure out sockets in order to one day do > a multiplayer game. Here's my problem: even the simplest examples > don't work on my computer: > > A simple server: > > from socket import * > myHost = '' > myPort = 21500 > > s = socket(AF_INET, SOCK_STREAM) # create a TCP socket > s.bind((myHost, myPort)) # bind it to the server port > s.listen(5) # allow 5 simultaneous connections > > while True: > connection, address = s.accept() > while True: > data = connection.recv(1024) > if data: > connection.send('echo -> ' + data) > else: > break > connection.close() # close socket > > And a simple client: > > import sys > from socket import * > serverHost = 'localhost' # servername is localhost > serverPort = 21500 # use arbitrary port > 1024 > > s = socket(AF_INET, SOCK_STREAM) # create a TCP socket > > > s.connect((serverHost, serverPort)) # connect to server on the port > s.send('Hello world') # send the data > data = s.recv(1024) # receive up to 1K bytes > print(data) > > > If I run testserver.py via the cmd prompt in Windows XP and then the > testclient.py program, I get the following error: > > Traceback (most recent call last): > File "C:\Python30\testclient.py", line 12, in > s.send('Hello world') # send the data > TypeError: send() argument 1 must be string or buffer, not str > > This happens in 2.6 or 3.0 and with different example client & server > programs from the web. What am I missing? The text of the error message seems outdated (it should probably say "bytes or bytearray" instead of "string or buffer"), but what it's trying to say is that you can only send() bytes, not unicode strings. For a byte literal, you need to add a 'b' prefix, e.g. b'Hello World' Alternatively, you can encode the unicode into bytes using .encode(), e.g. "Hello World".encode('utf8') Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From rhamph at gmail.com Mon Dec 8 13:20:56 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 8 Dec 2008 10:20:56 -0800 (PST) Subject: Rich Comparisons Gotcha References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Dec 7, 4:20?pm, Steven D'Aprano wrote: > On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: > > Rasmus Fogh wrote: > > >> Current behaviour is both inconsistent and counterintuitive, as these > >> examples show. > > >>>>> x = float('NaN') > >>>>> x == x > >> False > > > Blame IEEE for that one. Rich comparisons have nothing to do with that > > one. > > There is nothing to blame them for. This is the correct behaviour. NaNs > should *not* compare equal to themselves, that's mathematically > incoherent. Mathematically, NaNs shouldn't be comparable at all. They should raise an exception when compared. In fact, they should raise an exception when *created*. But that's not what we want. What we want is a dummy value that silently plods through our calculations. For a dummy value it seems a lot more sense to pick an arbitrary yet consistent sort order (I suggest just above -Inf), rather than quietly screwing up the sort. Regarding the mythical IEEE 754, although it's extremely rare to find quotations, I have one on just this subject. And it does NOT say "x == NaN gives false". It says it gives *unordered*. It is C and probably most other languages that turn that into false (as they want a dummy value, not an error.) http://groups.google.ca/group/sci.math.num-analysis/browse_thread/thread/ead0392e646b7cc0/a5bc354cd46f2c49?lnk=st&q=why+does+NaN+not+equal+itself%3F&rnum=3&hl=en&pli=1 From alexoplocatie at gmail.com Wed Dec 17 08:26:48 2008 From: alexoplocatie at gmail.com (aka) Date: Wed, 17 Dec 2008 05:26:48 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> <0d9ea7cc-b5fb-4edb-be32-490aae9e7204@b41g2000pra.googlegroups.com> Message-ID: <36eb36c0-333c-4084-8fc1-1a12d1d2d7d3@a37g2000pre.googlegroups.com> Hi John, thanks. You're right, I didn't past the method header because I thought it didn't matter when the input filename is hardcoded. The try/except isn't very helpful indeed so I commented it out. You're right I wrongly referred to the UnicodeReader class in my first post because that's ultimately where I want to go so I outcommented it here for you to see. The fact is that neither csv.reader nor the UnicodeReader will read the file, while writing with the UnicodeWriter works like a charm. That's why I put str() around roles to see any content. I simplified the csv-file by cutting off columns without result. The file looks now like: id;company;department 12;Cadillac;Research 11;Ford;Accounting 10;Chrysler;Sales The dictionary on the return is because this code is part of my TurboGears application. The entire method is: import csv from utilities.urw import UnicodeWriter, UnicodeReader @expose(allow_json=True) def import_roles(self, input=None, *args, **kwargs): inp = 'C:/temp/test.csv' roles = [] msg = '' ## try: fp = open(inp, 'rb') reader = csv.reader(fp, dialect='excel', delimiter=';') ## reader = UnicodeReader(fp, dialect='excel', delimiter=';') for r in reader: roles.append(r[0]) fp.close() ## except: ## msg = "Something's wrong with the csv.reader" return dict(filepath=inp, roles=str(roles), msg=msg) csv.reader results in: for r in myreader: Error: line contains NULL byte Use of UnicodeReader results in: UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: unexpected code byte Will post only complete code from now on thanks. From gubatron at gmail.com Wed Dec 3 12:54:51 2008 From: gubatron at gmail.com (Gubatron) Date: Wed, 3 Dec 2008 09:54:51 -0800 (PST) Subject: Jython: Packing several .py on .jar, problem importing .py modules within the .jar References: Message-ID: <0ad925d8-f890-4b12-b0e0-e8c3a7dacf8c@v4g2000yqa.googlegroups.com> I've managed to solve this problem. I can now run a python script that lives inside a Jar. The python script is now able to import other scripts within the same jar, and it's also able to import java classes that live within the jar. The problem was solved by giving the Jython Interpreter the proper initialization. This entails: - Giving it a class loader that has put the Jar on it's class path - Adding the path of the jar to the interpreter's sys.path Here's an example: org.python.core.PySystemState pySys = new org.python.core.PySystemState(); pySys.setClassLoader(((URLClassLoader) classLoaders.get(jarFile))); //We also have to pass the jar to JYTHON_PATH (sys.path) //so that it can properly import inner python modules. pySys.path.insert(0,new PyString(jarFile)); //We pass the PythonInterpreter the modified PySystemState PythonInterpreter i = new PythonInterpreter(null, pySys); i.exec(pythonScriptName); On Dec 3, 6:31?am, Gubatron wrote: > Hello all, > > I've a problem with Jython and importing .py inside a jar. > > I'm putting .class and .py files inside .jar files. > > myjar.jar > ? MyJar\SomeClass.class > ? MyJar\main.py > ? MyJar\otherModule.py > > So I add the myjar.jar to Jython's sys.path > > ? ? ? ? ? ? ? ? ? ? ? ? org.python.core.PySystemState pySys = new > org.python.core.PySystemState(); > ? ? ? ? ? ? ? ? ? ? ? ? pySys.path.insert(0,new PyString("/path/to/myjar.jar")); > > and execute main.py > > ? ? ? ? ? ? ? ? ? ? ? ? //We pass the PythonInterpreter the modified PySystemState > ? ? ? ? ? ? ? ? ? ? ? ? PythonInterpreter i = new PythonInterpreter(null, pySys); > > ? ? ? ? ? ? ? ? ? ? ? ? //Find the entry in the jar for the python file and execute it. > ? ? ? ? ? ? ? ? ? ? ? ? //It should be able to find any resource inside the jar. > ? ? ? ? ? ? ? ? ? ? ? ? JarFile jFile = new JarFile("/path/to/myjar.jar"); > ? ? ? ? ? ? ? ? ? ? ? ? ZipEntry zipEntry = jFile.getEntry("MyJar/main.py"); > > ? ? ? ? ? ? ? ? ? ? ? ? InputStream pythonInputStream = > jFile.getInputStream(zipEntry); > ? ? ? ? ? ? ? ? ? ? ? ? i.execfile(pythonInputStream); > > main.py will execute fine, it'll be able to do > > from MyJar import SomeClass > > with no problem > > However, If I try to import the other .py in the same jar, it won't > find it: > > from otherModule import * > > or > > from MyJar.otherModule import * > > I always get this: > > ImportError: no module named otherModule > > ? ? ? ? at org.python.core.Py.ImportError(Unknown Source) > ? ? ? ? at org.python.core.imp.import_first(Unknown Source) > ? ? ? ? at org.python.core.imp.import_name(Unknown Source) > ? ? ? ? at org.python.core.imp.importName(Unknown Source) > ? ? ? ? at org.python.core.ImportFunction.load(Unknown Source) > ? ? ? ? at org.python.core.ImportFunction.__call__(Unknown Source) > ? ? ? ? at org.python.core.PyObject.__call__(Unknown Source) > ? ? ? ? at org.python.core.__builtin__.__import__(Unknown Source) > ? ? ? ? at org.python.core.imp.importFromAs(Unknown Source) > ? ? ? ? at org.python.core.imp.importFrom(Unknown Source) > ? ? ? ? at org.python.pycode._pyx1.f$0(:26) > ? ? ? ? at org.python.pycode._pyx1.call_function() > ? ? ? ? at org.python.core.PyTableCode.call(Unknown Source) > ? ? ? ? at org.python.core.PyCode.call(Unknown Source) > ? ? ? ? at org.python.core.Py.runCode(Unknown Source) > ? ? ? ? at org.python.util.PythonInterpreter.execfile(Unknown Source) > > I've tried adding more paths to sys.path, with no luck: > > pySys.path.insert(0,new PyString("/path/to/myjar.jar/MyJar")); > pySys.path.insert(0,new PyString("file:jar:/path/to/myjar.jar!")); > > and nothing works, any ideas would help. I know this has to work, > because I previously had a problem where I couldn't do > > import os > > and then I added the "Lib/" folder inside jython.jar and now I'm able > to import all those standard jython modules, so, somehow, jython is > able to import .py within a .jar, help would be very much appreciated. > > Angel Leon From dfnsonfsduifb at gmx.de Fri Dec 5 12:28:04 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Fri, 05 Dec 2008 18:28:04 +0100 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: <85fxl24lbu.fsf@dozer.localdomain> References: <85fxl24lbu.fsf@dozer.localdomain> Message-ID: <4u4o06xkhf.ln2@joeserver.homelan.net> J Kenneth King schrieb: > It probably means what it says: that the input file contains characters > it cannot read using the specified encoding. No, it doesn't. The file is just fine, just as the example. > Are you generating the file from python using a file object with the > same encoding? If not, then you might want to look at your input data > and find a way to deal with the exception. I did. The file is fine. Could you try out the example? Regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From Slaunger at gmail.com Wed Dec 3 06:24:04 2008 From: Slaunger at gmail.com (Slaunger) Date: Wed, 3 Dec 2008 03:24:04 -0800 (PST) Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> <258cf433-f6c9-43e7-a235-f5f6b2b6433f@j39g2000yqn.googlegroups.com> <33b4cc2f-2311-491c-a2e6-9cc5452b1a6b@g38g2000yqd.googlegroups.com> Message-ID: <2772646a-623f-400b-a606-281a7e3220d4@20g2000yqt.googlegroups.com> On 3 Dec., 11:30, Nick Craig-Wood wrote: > > ? ? ? ? ?cls = self.__class__ > > ? ? ? ? ?if attr_name in cls.data_attr_names: > > self.data_attr_names should do instead of cls.data_attr_names unless > you are overriding it in the instance (which you don't appear to be). Yeah, I know. I just like the cls notation for code readability because it tells you that it is a class attribute, which is not instance- dependent. That may be legacy from my Java past, where I used to do it that way. I know perfectly well that self. would do it. i just find that notation a little misleading > > ? ? ? ? ? ? ? ? ?I1, Q1, I2, Q2 = bytes_to_data(buf) > > ? ? ? ? ? ? ? ? ?self.__dict__["I1"] = I1 > > ? ? ? ? ? ? ? ? ?self.__dict__["Q1"] = Q1 > > ? ? ? ? ? ? ? ? ?self.__dict__["I2"] = I2 > > ? ? ? ? ? ? ? ? ?self.__dict__["Q2"] = Q2 > > ? ? ? ? ? ? ? ? ?return self.__dict__[attr_name] > > I think you want setattr() here - __dict__ is an implemetation detail > - classes with __slots__ for instance don't have a __dict__. ?I'd > probably do this Oh my, I did not know that. __slots__?? Something new I got to understand. But you are right. thanks! > > ? ? ? ? ? ? ? ? ? ?for k, v in zip(("I1", "Q1", "I2", "Q2"), bytes_to_data(buf)): > ? ? ? ? ? ? ? ? ? ? ? ?setattr(self, k, v) > ? ? ? ? ? ? ? ? ? ?return object.__getattr__(self, attr_name) > And perhaps even more readable (how I do it now, no need to call __getattr__ for an attribute, whcih is already there): ... for attr, value in zip(cls.data_attr_names, bytes_to_data(buf)): setattr(self, attr, value) return getattr(self, attr_name) > :-) > > I would probably factor out the contents of the if statement into a > seperate method, but that is a matter of taste! Agreed. I thought about that myself for better code readability. As a final comment, I have actually refacted the code quite a bit as I have to do this ...OnDemand trick for several classes, which have different data attributes with different names. In this process I have actaully managed to isolate all the ...OnDemand stuff in an abstract PayloadOnDemand class I can now use this "decorator-like"/helper class to very easily make an ...OnDemand variant of a class by just doing multiple inheritance - no implementation: class PayloadBaconAndEggsOnDemand(PayloadOnDemand, PayloadBaconAndEggs): pass I guess this somewhat resembles the decorator approach - I just could not figure out how to kake a general purpose decorator. For this to actually work the "instant" PayloadBaconAndEggs class simply has to define and implement a few class attributes and static utility functions for the unpacking. -- Slaunger From asteinarson at gmail.com Sat Dec 6 16:47:26 2008 From: asteinarson at gmail.com (ats) Date: Sat, 6 Dec 2008 13:47:26 -0800 (PST) Subject: Source code generation using Python Message-ID: <82098706-978f-4920-ac75-57ef3573ac44@x38g2000yqj.googlegroups.com> Hello, This is my first posting to a Python group (and I'm starting with Python seriously only now) , so bear with me if I make some mistakes. I want to generate 3 different versions of a C++ source code, basically injecting different flavours of inline assembler depending on target compiler/CPU. Code generation should be integrated into a 'master source file' which is the processed and generates the right code for GCC / MSVC or other cases. Something like: int FastAdd( int t1, int t2 ){ int r; ##if USE_INLINE_ASM #ARG( eax, "t1") #ARG( ebx, "t2") #ASM( "add", ebx, eax ) #RES( eax, "r" ) ##else r = t1+t2; ##endif return r; } On processing, given constant USE_INLINE_ASM (or not) the right code is generated to a target file, which goes into the build process. I was looking for packages that can do this and came up with some candidates: - "empy" - http://www.alcyone.com/pyos/empy/ - It looks like it could do the job, but appears non-maintained since 2003. - "Cheetah" - Looks like more of a tool to do fix replacements of code snippets. There is some logic going on in the "ARG", "ASM" and "RES" sections, so I need to link code generation with true Python functions. The situation is really quite similar to HTML/PHP except, here we would have C++/Python. Any suggestions? Thanks, //Arne S. From bthayre at physics.ucsd.edu Thu Dec 11 18:38:14 2008 From: bthayre at physics.ucsd.edu (Robocop) Date: Thu, 11 Dec 2008 15:38:14 -0800 (PST) Subject: list organization question References: Message-ID: <3040d38a-cc25-41ea-a472-281072137044@c36g2000prc.googlegroups.com> On Dec 11, 3:31?pm, Arnaud Delobelle wrote: > Robocop writes: > > I have a list of objects, each object having two relevant attributes: > > date and id. ?I'd like not only organize by id, but also by date. > > I.e. i would like to parse my list into smaller lists such that each > > new mini-list has a unique date, but consists of only objects with a > > specific id. ?Are there any handy imports i could use to accomplish > > something like this? ?I'm relatively new to python and as such don't > > know all of the preloaded functions at my disposal. ?Thanks for any > > help in advance, the community here is always ridiculously helpful. > > Look at itertools.groupby. > > E.g. > > from itertools import groupby > > data = [ my objects ] > > def getdate(x): return x.date > > by_date = {} > for date, objs in groupby(sorted(data, key=getdate), getdate): > ? ? by_date[date] = list(objs) > ? ? # list(objs) is the list of all objects in data whose date is date > > I'm sorry if this is a bit terse... > > -- > Arnaud This looks to be exactly what i'm looking for! I will try and implement this immediately, thank you all for the suggestions. From temotor at gmail.com Thu Dec 18 18:04:14 2008 From: temotor at gmail.com (Sergey Shepelev) Date: Thu, 18 Dec 2008 15:04:14 -0800 (PST) Subject: Python lex settings Message-ID: <0dfeb0c3-a524-4a72-aafd-4b88b71ff16c@w39g2000prb.googlegroups.com> Hello. I'm trying to make almost-Python source to Erlang source translation tool. Are there ready ply.lex settings for parsing python source? From paul at boddie.org.uk Thu Dec 18 16:13:56 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 18 Dec 2008 13:13:56 -0800 (PST) Subject: psycopg2 and large queries References: Message-ID: <762eed9d-4646-4c62-a9b7-d57d47f03b9e@e1g2000pra.googlegroups.com> On 18 Des, 19:09, Steve Holden wrote: > > Hmm, pypgsql doesn't provide a 2.5 Windows installer. I take it you > aren't a Windows user ... ? Well, there are plenty of PostgreSQL modules around these days, and even if pyPgSQL isn't suitable, I'm sure that there must be one which can be made to work on Windows and to support server-side cursors. See here for more: http://wiki.python.org/moin/PostgreSQL Paul From skip at pobox.com Thu Dec 4 16:49:46 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 4 Dec 2008 15:49:46 -0600 Subject: RELEASED Python 3.0 final In-Reply-To: <20081204204525.414db889@usenot.de> References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> Message-ID: <18744.20602.92835.175628@montanaro-dyndns-org.local> Andreas> Whenever has it been a pythonic ideal to "not allow" stuff? You Andreas> get warnings. Everything else is up to you. It's more than warnings. With properly crafted combinations of spaces and tabs you can get code which looks like it has a certain indentation to the human observer but which looks like it has different indentation (and thus different semantics) to the byte code compiler. There is often no warning. Skip From iNkOhSnPaAtMon at free.fr Mon Dec 8 09:47:13 2008 From: iNkOhSnPaAtMon at free.fr (Pascal) Date: 08 Dec 2008 14:47:13 GMT Subject: [Py2exe-users] py2exe 0.6.9 released References: <49216608$0$9585$426a74cc@news.free.fr> Message-ID: <493d3371$0$15192$426a74cc@news.free.fr> On Mon, 17 Nov 2008 12:39:36 +0000, Pascal wrote: > On Sun, 16 Nov 2008 21:23:59 -0500, Chris Spencer wrote: > >> After I "compile" my program with py2exe 0.6.9 with Python 2.6, I'm >> still getting the "Application Did Not Initialize Properly" error >> dialog whenever I run my code. What am I doing wrong? > > I have exactly the same problem. > I have tried just anything I could think of to no avail : Copied the 3 > msvc_90.dll to the system32 subdir of Windows, to the directory of my > application, reinstalled the whole Microsoft Visual C++ 2008 > Redistributable Package, embedded the manifest data into the exe or kept > it in a .manifest file... > Could not make it work. Always got the "Application Did Not Initialize > Properly" message. > I'm with Windows XP SP3. I tried all this on 2 different systems and I > got the same results. I think I narrowed down a little bit the problem. It's not the common one when the msvc_90.dll are not located, though the result is similar. The problem is when you try to generate at least 2 exe in one setup (with 2 scripts specified in the "windows" command of the setup). This works OK with py2exe 0.6.9 for Python 2.5, but fails with Python 2.6 (and 2.6.1). None of the generated exe can be started. When I compare the content of library.zip in both versions, this file doesn't contain any .pyc for the scripts you want to generate an exe for with Python 2.5, but always contains a .pyc for one of the scripts you want to generate an .exe for with Python 2.6. Don't know if it's a clue for finding a fix. I have tested many ways to figure this out but I can't find any solution for the moment so I'm sticking with Python 2.5. From google at mrabarnett.plus.com Mon Dec 8 17:56:31 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 08 Dec 2008 22:56:31 +0000 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: <493DA61F.7020207@mrabarnett.plus.com> Terry Reedy wrote: > Rasmus Fogh wrote: > >> For my personal problem I could indeed wrap all objects in a wrapper with >> whatever 'correct' behaviour I want (thanks, TJR). It does seem a bit > > I was not suggesting that you wrap *everything*, merely an adaptor for > numpy arrays in whatever subclass and source it is that feeds them to > your code. It is fairly unusual, I think, to find numpy arrays 'in the > wild', outside the constrained context of numerical code where the > programmer uses them intentionally and hopefully understands their > peculiarities. > >> much, though, just to get code like this to work as intended: >> alist.append(x) >> print ('x is present: ', x in alist) > > Even if rich comparisons as you propose, the above would *still* not > necessarily work. Collection classes can define a __contains__ that > overrides the default and that can do anything, though True/False is > recommended. > If you have a list of results and you want to see whether one of them is Nan then the obvious way is "Nan in results", but __contains__ uses __eq__ and Nan == Nan returns False, so "Nan in results" returns False. Hmm... "Nan is Nan" returns True, so if there was a version of __contains__ which used "is" then "Nan in results" would return True. Perhaps "Nan is in results"? Or would that be too confusing, ie "in" vs "is in"? > As best I can think of at the moment, the only things you can absolutely > depend on is that builtin id(ob) will return an int, that 'ob1 is ob2' > (based in id()) will be True or False, and that builtin type(ob) will be > a class (at least in 3.0, not sure of 2.x). The names can be rebound > but you can control that within the module you write. > I wonder whether there could be some syntactic sugar which would wrap try...except... around an expression, eg "except(foo(), False)", which would return False if foo() raised an exception, otherwise return the result of foo(). > This is what I meant when I said that 'generic' nearly always needs to > be qualified to something like 'generic for objects that meet the > interface requirements'. Every function has that precondition as part > of its implied contract. Your code has an interface requirement that 'x > in y' not raise an exception. An x,y pair that does it outside its > contract. > From pacsciadmin at gmail.com Sun Dec 7 21:24:08 2008 From: pacsciadmin at gmail.com (pacsciadmin at gmail.com) Date: Sun, 7 Dec 2008 18:24:08 -0800 (PST) Subject: Infinite hangup when using CGI sys.stdin.read() Message-ID: I maintain a CGI framework named PyTin, and while previously the developer was only allowed to access GET and POST by cgi.FieldStorage. I'm trying to add code to my request gatherer that looks like: 1. request.rawpost = StringIO() # Just normal StringIO 2. request.rawpost.write(sys.stdin.read()) 3. request.rawpost.seek(0) 4. request.fields = cgi.FieldStorage(fp=request.rawpost) 5. request.rawpost.seek(0) Obviously, my actual code doesn't have the line numbers. I'm testing it out on the CGIHTTPRequestHandler with BaseHTTPServer, and whenever my test script reaches line 2, it hangs up. It doesn't spit out a traceback, or stop in less than a minute, whenever I use sys.stdin.read(). Can anyone explain what is going on? Regards, LeafStorm BDFL: Pacific Science From bruno.42.desthuilliers at websiteburo.invalid Thu Dec 4 08:26:02 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 04 Dec 2008 14:26:02 +0100 Subject: python an sqlite objects In-Reply-To: References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <4936bceb$0$16783$426a34cc@news.free.fr> <4936dab7$0$9107$426a74cc@news.free.fr> <493792a9$0$16763$426a74cc@news.free.fr> Message-ID: <4937da56$0$10438$426a74cc@news.free.fr> skip at pobox.com a ?crit : > Bruno> If you serialize a dict, you'll obviously get a dict back. Note > Bruno> that the point of json is *not* to replace pickle. json is a > Bruno> *data* serialization format meant to represent "basic" types > Bruno> (dicts, lists, strings and numbers) in human readable and > Bruno> (mostly) language-agnostic way. > > Right, which makes it unsuitable as a general object serialization format. which makes it unsuitable as a full-fledged generic Python serialization format, at least OOTB (Django knows how to get model objects back from json, and I think one could write a more generic json serializer / deserializer with about the same limitations as pickle). > The OP was unclear what he meant when he asked about storing Python objects > in a sqlite database. In the general case json doesn't cut it. I indeed assumed (possibly wrongly) that this would be enough, given the use of a relational database. But as I said: > Bruno> If you want a Python object store, you'll be better looking at > Bruno> ZODB, Durus or friends. -- > > Or SQLAlchemy or SQLObject. Not the same thing. From ldo at geek-central.gen.new_zealand Wed Dec 3 06:09:39 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 04 Dec 2008 00:09:39 +1300 Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> Message-ID: In message <21ddcf54-e64c-411e-835f-a2d06644dfa0 at x38g2000yqj.googlegroups.com>, Astley Le Jasper wrote: > The trouble is that obviously I get no console when using crontab so > can't see any traceback. Cron normally sends you mail if a cron task generated any output (this should include error messages). From __peter__ at web.de Sat Dec 13 09:44:45 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 13 Dec 2008 15:44:45 +0100 Subject: Shorter tracebacks References: Message-ID: bearophileHUGS at lycos.com wrote: > When I write recursive code in Python I sometimes go past the maximum > allowed stack depth, so I receive a really long traceback. The show of > such traceback on my screen is very slow (despite a CPU able to > perform billions of operations each second). So I think I'd like > something to shorten them. > I am thinking about something like: > from __future__ import short_traceback > > That allows me to see only the first and last parts of the stack > trace, and skips the (generally very redundant) middle part. > > Note that generally using sys.setrecursionlimit(limit) to set a > smaller limit isn't good, because I may need a big depth anyway. That's none of __future__'s business, I think. Python offers a hook which you can modify: >>> import sys, traceback >>> from functools import partial >>> sys.excepthook = partial(traceback.print_exception, limit=5) >>> x = 0 >>> def f(): ... global x ... x += 1 ... f() ... >>> f() Traceback (most recent call last): File "", line 1, in File "", line 4, in f File "", line 4, in f File "", line 4, in f File "", line 4, in f RuntimeError: maximum recursion depth exceeded >>> x 999 Peter From nick at craig-wood.com Mon Dec 1 06:30:44 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 01 Dec 2008 05:30:44 -0600 Subject: Do more imported objects affect performance References: Message-ID: Rafe wrote: > On Dec 1, 7:26?am, "Filip Gruszczy?ski" wrote: > > I have following question: if I use > > > > from module import * > > > > instead > > > > from module import Class > > > > am I affecting performance of my program? I believe, that all those > > names must be stored somewhere, when they are imported and then > > browsed when one of them is called. So am I putting a lot of "garbage" > > to this storage and make those searches longer? > > Why use it if you don't need it? Your post implies a choice and the > '*' import can really make things muddy if it isn't actually necessary > (rare). Why not just import the module and use what you need? It is > way easier to read/debug and maintains the name-space. Importing the module is actualy slower... If you import the name into your namespace then there is only one lookup to do. If you import the module there are two. $ python -m timeit -s 'from timeit import Timer' 'Timer' 10000000 loops, best of 3: 0.0784 usec per loop $ python -m timeit -s 'import timeit' 'timeit.Timer' 1000000 loops, best of 3: 0.243 usec per loop I'm not suggestion you should ever use "from module import *" only ever import the things you actually need, eg "from module import MyClass, my_function" And here is the test again, actually calling something with the same difference in execution speed :- $ python -m timeit -s 'from os import nice' 'nice(0)' 1000000 loops, best of 3: 1.21 usec per loop $ python -m timeit -s 'import os' 'os.nice(0)' 1000000 loops, best of 3: 1.48 usec per loop -- Nick Craig-Wood -- http://www.craig-wood.com/nick From anthony.tolle at gmail.com Mon Dec 8 12:01:18 2008 From: anthony.tolle at gmail.com (anthony.tolle at gmail.com) Date: Mon, 8 Dec 2008 09:01:18 -0800 (PST) Subject: Guido's new method definition idea References: <014a071a$0$20670$c3e8da3@news.astraweb.com> <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> Message-ID: On Dec 6, 4:15?pm, Carl Banks wrote: > On Dec 6, 12:47?am, "Patrick Mullen" wrote: > > > Could I do something like this: > > > def a.add(b): return a+b > > > Outside of a class? ?Of course then that makes you think you could do > > 5.add(6) or something craaaazy like that. ?(I mean, you can do > > (5).__add__(6) but that's something else entirely) > > I'd be inclined to think that this defines an instancemethod on an > existing object a. ?In other word, I'd read the following two lines as > more or less equivalent. > > def a.add(b): return a+b > > a.add = lambda b: a+b > > Just as the following are equivalent: > > def foo(): return bar > > foo = lambda: bar > > I had been -0 on this, but now I think I'm -1. This brings up another question, what would one use when referencing method names inside the class definition?: class C: def self.method(arg): self.value = arg def self.othermethod(arg): self.value = arg # do this? funcs = (self.method, self.othermethod) # or this? funcs = (method, othermethod) On another related note, I would be interested in seeing this syntax adopted for the very purpose Carl hinted at... Normally, if I'm defining a nested function that needs to be stored as an object attribute, I have to use a dummy name, like the following: class C: def createfunc(self, arg): def _dummy(arg): return arg + 1 self.func = _dummy It would be nice to be able to do the following instead: class C: def createfunc(self): def self.func(arg): return arg + 1 Or, after the class definition is done, to extend it dynamically: def C.method(self, arg): self.value = arg ...which would be the equivalent of the following: def method(self, arg): self.value = arg C.method = method Since functions are first-class objects, it seems perfectly reasonable to me. From steve at REMOVE-THIS-cybersource.com.au Sun Dec 28 09:31:11 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Dec 2008 14:31:11 GMT Subject: sys.stdout.write()'s bug or doc bug? References: Message-ID: <016784c1$0$6988$c3e8da3@news.astraweb.com> On Sun, 28 Dec 2008 02:37:55 -0800, Qiangning Hong wrote: >> > So, my question is, as sys.stdout IS a file object, why it does not >> > use its encoding attribute to convert the given unicode? An >> > implementation bug? A documenation bug? >> >> hmm I always thought "sys.stdout" is a "file-like object" not that it >> IS a file. > > In my original post, I have figured out that sys.stdout IS a file, by > using type() function. And isinstance() function tells the same: > > Python 2.5.2 (r252:60911, Dec 18 2008, 12:39:19) [GCC 4.2.1 (Apple Inc. > build 5564)] on darwin Type "help", "copyright", "credits" or "license" > for more information. >>>> import sys >>>> type(sys.stdout) is file > True >>>> isinstance(sys.stdout, file) > True > > So, sys.stdout SHOULD do what the doc says, otherwise there is a bug > either in implementation of sys.stdout, or in the documentation of file. The documentation says: file.encoding The encoding that this file uses. When Unicode strings are written to a file, they will be converted to byte strings using this encoding. In addition, when the file is connected to a terminal, the attribute gives the encoding that the terminal is likely to use (that information might be incorrect if the user has misconfigured the terminal). The attribute is read-only and may not be present on all file-like objects. It may also be None, in which case the file uses the system default encoding for converting Unicode strings. New in version 2.3. http://docs.python.org/library/stdtypes.html#file.encoding And I agree that sys.stdout is a file. Using Python 2.6: >>> type(sys.stdout) I can confirm the behaviour you report: >>> sys.stdout.encoding 'UTF-8' >>> u = u"\u554a" >>> print u ? >>> sys.stdout.write(u) Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\u554a' in position 0: ordinal not in range(128) But if you explicitly convert the string, it works: >>> sys.stdout.write(u.encode('utf-8')) ? I agree that this appears to be a bug, either of the write() method or the documentation. -- Steven From google at mrabarnett.plus.com Thu Dec 18 17:52:11 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 18 Dec 2008 22:52:11 +0000 Subject: Which sparse matrix package? In-Reply-To: References: <20081218231851.70dd91e2@Schlamber.localdomain> Message-ID: <494AD41B.3090501@mrabarnett.plus.com> James Mills wrote: > On Fri, Dec 19, 2008 at 8:18 AM, Martin Manns wrote: >> Hi: > > Hi, > >> I am writing a spreadsheet application in Python > > What's wrong with pyspread ? > > [ ... snip ... ] > >> The dict that I tried out is of the type: >> >> {(1,2,3): "2323", (1,2,545): "2324234", ... } >> >> It is too slow for my application when it grows. One slicing operation >> with list comprehensions takes about 1/2 s on my computer for 1E6 >> elements. > > Let me get this straight. > It's taking 0.5s to slice your matrix > of 1E7 (10000000.0 rows/columns) > > Are you mad ? This is TEN Millions and you > required it faster than 0.5s ? > No, 1E6, or ONLY 1 million. :-) > Am I missing something here ? > Would a matrix of matrices work better, ie a supermatrix where each element is either a submatrix of cells or None if the submatrix is empty? How much memory it would save would depend on how sparse the matrix is. From prologic at shortcircuit.net.au Mon Dec 8 01:09:13 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Dec 2008 16:09:13 +1000 Subject: A question about reference in Python. In-Reply-To: <493CB003.3080209@gmail.com> References: <493CB003.3080209@gmail.com> Message-ID: Hi, This is really really really pointless code and a really really pointless exercise, but nonetheless, here is a very very basic and minimal implementation of what you're expecting. This should almost *never* be done in Python! Python is a superior dynamic programming language, but it's NOT C! Here goes: jmills at atomant:~/tmp$ ./list.py >>> x[0] 0 >>> x[1] 1 >>> x[2] 2 >>> x[3] 3 >>> x[4] Traceback (most recent call last): File "", line 1, in File "./list.py", line 36, in __getitem__ return node.value AttributeError: 'NoneType' object has no attribute 'value' >>> jmills at atomant:~/tmp$ And the code: #!/home/jmills/bin/python -i class Node(object): value = None prev = None next = None def __init__(self, value, prev=None, next=None): self.value = value self.prev = prev self.next = next class List(object): data = None def __init__(self, *seq): if seq: first = prev = node = None for x in seq: if not first: first = Node(x) prev = node = first else: node = Node(x, prev) prev.next = node prev = node self.data = first def __getitem__(self, x): node = self.data for i in xrange(x): node = node.next return node.value x = List(0, 1, 2, 3) Notes: I have not implemented any error checking whatsoever. I have not implemented any of your normal list operations whatsoever (except 1). __getitem__. Have fun, cheers James On Mon, Dec 8, 2008 at 3:26 PM, Group wrote: > Hello, I'm studying algorithom. For concentrating on the question itself, I > intend to use Python to implement the algorithoms. > > Now, I want to write a Red-Black Tree, and a List structure. In C/C++, I can > use pointers to refer to children notes (or next notes). But, in Python, > how > can I do it? Except the sequence, I know not any way. > > You'd better help me understan how can I transform the following C code into > Python: > > /* a List */ > struct { > int data; > int *next; > int *prev; > } > > That's all. Thanks! > Kermit > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From bkamrani at gmail.com Thu Dec 4 04:26:13 2008 From: bkamrani at gmail.com (bkamrani at gmail.com) Date: Thu, 4 Dec 2008 01:26:13 -0800 (PST) Subject: performance question: dictionary or list, float or string? References: <434bf4e3-54f4-4e15-b8b0-510a988f25b8@z1g2000yqn.googlegroups.com> Message-ID: <904a19e9-3800-4d61-aea0-4bdabc0674fa@j32g2000yqn.googlegroups.com> Matt, really thanks for your comments! Even thogh it was not a direct answer to my questions, I like your coding style very much and I think you have a good point. About the number of line in the file, because I get that info from another in advance. Therefore I thought it could be hard coded. BTW, could you recommend a book or a note on points you have mentioned so that I can learn more like that? Thanks, /Ben On Dec 2, 8:37?pm, Matimus wrote: > On Dec 2, 3:51?am, bkamr... at gmail.com wrote: > > > > > I forgot to mention that I did a simple timeit test which doesn't > > show > > significant runtime difference 3.5 sec for dictionary case and 3.48 > > for > > list case. > > > def read_as_dictionary(): > > ? ? fil = open('myDataFile', 'r') > > ? ? forces = {} > > ? ? for region in range(25): > > ? ? ? ? forces[region] = {} > > > ? ? for step in range(20000): > > ? ? ? ? for region in range(25): > > ? ? ? ? ? ? line = fil.next(); spl = line.split() > > ? ? ? ? ? ? forces[region] [step] = spl > > > def read_as_list(): > > ? ? fil = open('myDataFile.txt', 'r') > > ? ? forces = [] > > ? ? for region in range(25): > > ? ? ? ? forces.append([]) > > > ? ? for step in range(20000): > > ? ? ? ? for region in range(25): > > ? ? ? ? ? ? line = fil.next(); spl = line.split() > > ? ? ? ? ? ? forces[region].append(spl) > > > Cheers, > > /Ben > > There really isn't enough information to recommend a particular > direction. A dictionary doesn't seem appropriate for > this information though. Also, you are hard coding the step range to > 20000. Is that the number of lines in the file? That isn't really a > safe way to do it. > > # this is just bad style in python: > line = fil.next(); spl = line.split() > # better written > spl = fil.next().split() > > I would just do it this way: > > def read_as_list(data, regions=25, maxlines=20000): > ? ? # If data is a filename, open the file. If it is a file > ? ? # object or any sequence of 'lines' it should just work. > > ? ? file_opened = False > ? ? if isinstance(data, basestring): > ? ? ? ? data = open(data, 'r') > ? ? ? ? file_opened = True > > ? ? forces = [[] for _ in xrange(regions)] > ? ? try: > ? ? ? ? for i, line in data: > ? ? ? ? ? ? if i == maxlines: > ? ? ? ? ? ? ? ? break > ? ? ? ? ? ? forces[i % 25].append(line.split()) > ? ? finally: > ? ? ? ? if file_opened: > ? ? ? ? ? ? f.close() > ? ? return forces > > Matt From jarausch at igpm.rwth-aachen.de Tue Dec 2 04:34:18 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Tue, 02 Dec 2008 10:34:18 +0100 Subject: Is it safe to modify the dict returned by vars() or locals() In-Reply-To: References: <4934508b$0$2861$ba620e4c@news.skynet.be> Message-ID: <4935011A.9080406@igpm.rwth-aachen.de> Chris Rebert wrote: > On Mon, Dec 1, 2008 at 1:01 PM, Helmut Jarausch wrote: >> Hi, >> >> I am looking for an elegant way to solve the following problem: >> >> Within a function >> >> def Foo(**parms) >> >> I have a list of names, say VList=['A','B','C1'] >> and I like to generate abbreviation >> _A identical to parms['A'] > > Could you explain what you mean by that? Your sample code doesn't seem > to do any "abbreviation"... > Otherwise I don't see why you don't just have a proper parameter list. In my application parms contains field names of an html form iff these fields have been modified. I'd like to use the short name _A instead of the longer expression parms['A'] -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From clp at rebertia.com Wed Dec 31 08:29:36 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 31 Dec 2008 05:29:36 -0800 Subject: Pass by reference In-Reply-To: References: <529e1d98-8932-49f0-b569-85285bd50f23@p2g2000prn.googlegroups.com> Message-ID: <47c890dc0812310529i73f5c673me1810bb2ac97a1fb@mail.gmail.com> On Wed, Dec 31, 2008 at 5:04 AM, iu2 wrote: > For the 2 targets I have the variables comm1 and comm2. They are of > some class I wrote, representing many properties of the communication, > including the IP address. > There is one function that sends data, and it receives a commX var > (comm1 or comm2) as the means for sending the data. > Before sending the data the function needs to initilze commX (if it is > still None), or creating it a new, if it sees that the IP for that > target has changed. Based on the naming alone (though further corroborated by your details), I can recommend that you use a dictionary instead of variables for the commX-s. Basically, remove the comm1, comm2, etc variables and instead do (you might want to use a defaultdict or list rather than a plain dict): comms = {1 : MyComm(...), 2 : None} > > Something like this: > > def send_data(comm, data, current_ip_from_gui): > if comm is None: > # I want to assign comm a new MyComm > elif comm.ip != current_ip_from_gui: > # I want to re-assign a new MyComm that uses the new IP > comm.socket.SendTo(comm.addr, data) # eventually send the data Instead that becomes: def send_data(comms, id_num, data, current_ip_from_gui): if comms[id_num] is None: comms[id_num] = MyComm(...) elif comms[id_num].ip != current_ip_from_gui: comms[id_num] = MyComm(current_ip_from_gui, ...) comm = comms[id_num] comm.socket.SendTo(comm.addr, data) # eventually send the data > But I guess I can achieve this using a class holding my vars, maybe > like this: That's similar to what I'm suggesting, but mine has less indirection. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From lie.1296 at gmail.com Tue Dec 9 17:10:19 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 9 Dec 2008 22:10:19 +0000 (UTC) Subject: Is 3.0 worth breaking backward compatibility? References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> <1228857008.4109.38.camel@brotherus.rdu.redhat.com> Message-ID: On Tue, 09 Dec 2008 16:10:08 -0500, Albert Hopkins wrote: > On Tue, 2008-12-09 at 20:56 +0000, Lie Ryan wrote: >> Actually I noticed a tendency from open-source projects to have slow >> increment of version number, while proprietary projects usually have >> big >> version numbers. >> >> Linux 2.x: 1991 Python 3.x.x: 1991. Apache 2.0: 1995. OpenOffice.org >> 3.0: >> acquired by Sun at 1999. GIMP 2.x: 1995. Wine 1.x: 1993. >> > One exeption would be GNU Emacs 22: 1984, but according to Wikipedia: > > "Versions 2 to 12 never existed. Earlier versions of GNU Emacs > had been numbered "1.x.x", but sometime after version 1.12 the > decision was made to drop the "1", as it was thought the major > number would never change." > > So you can think of Emacs 22 as being 1.22. most odd is TeX an METAFONT: TeX has an idiosyncratic version numbering system. Since version 3, updates have been indicated by adding an extra digit at the end, so that the version number asymptotically approaches ?. The current version is 3.1415926. This is a reflection of the fact that TeX is now very stable, and only minor updates are anticipated. TeX developer Donald Knuth has stated that the "absolutely final change (to be made after my death)" will be to change the version number to ?, at which point all remaining bugs will become permanent features. In a similar way, the version number of METAFONT asymptotically approaches e. From antoine at vo.lu Sat Dec 6 10:56:41 2008 From: antoine at vo.lu (Antoine De Groote) Date: Sat, 06 Dec 2008 16:56:41 +0100 Subject: Guido's new method definition idea In-Reply-To: References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> Message-ID: Russ P. wrote: > On Dec 6, 1:02 am, Antoine De Groote wrote: >> Allowing "$" as a substitute for "self" wouldn't require this new syntax. >> >> class C: >> def method($, arg): >> $.value = arg >> >> I'm strongly against this. This looks ugly and reminds me of Perl and >> Ruby. (I don't have anything against these languages, but there's a >> reason I use Python). > > It looks "ugly" simply because it is new to you. Once you get used to > it, I'll bet it will look fine. And resemblance to another language is > not a very good reason to reject it. I would not say that "ugly" and "new" (or "unused" for that matter) are the same. There are going to be a number of things in Python 3 that are new and to which one is not used, but they certainly are not ugly. Ugly is of course a matter of taste, I'll give you that, but to me it's still ugly. From joe at strout.net Mon Dec 15 10:29:37 2008 From: joe at strout.net (Joe Strout) Date: Mon, 15 Dec 2008 08:29:37 -0700 Subject: %s place holder does not let me insert ' in an sql query with python. In-Reply-To: <1229348763.31093.38.camel@krishna-laptop> References: <1229345178.31093.24.camel@krishna-laptop> <1229348763.31093.38.camel@krishna-laptop> Message-ID: <764E2489-284E-4064-B7B3-8736E41969B2@strout.net> On Dec 15, 2008, at 6:46 AM, Krishnakant wrote: > in this case, I get a problem when there is ' in any of the values > during insert or update. That's because ' is the SQL string literal delimiter. But any SQL- compliant database allows you to "escape" an apostrophe within a string literal by doubling it. So for each of your values, just do: value = value.replace("'", "''") before stuffing them into your INSERT or UPDATE statement. (If these values come from the user, and especially if they come over the network, then you probably want to do a few other replacements; google "SQL injection" for details.) Note that I'm not familiar with the cursor.execute binding that RDM pointed out, so that may provide a better solution... but the above should work. Best, - Joe From bsk16 at case.edu Mon Dec 22 23:09:05 2008 From: bsk16 at case.edu (Ben Kaplan) Date: Mon, 22 Dec 2008 23:09:05 -0500 Subject: Python's popularity In-Reply-To: <7c02eb33-a919-4481-8eda-76062729f233@k19g2000yqg.googlegroups.com> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> <7c02eb33-a919-4481-8eda-76062729f233@k19g2000yqg.googlegroups.com> Message-ID: <5590A15E-D3BC-4094-A3B5-5CCE2717F8AC@case.edu> On Dec 22, 2008, at 9:51 PM, r wrote: > On Dec 22, 7:34 pm, Steven D'Aprano > wrote: >> On Mon, 22 Dec 2008 10:01:21 -0800, r wrote: >>> Walter, >>> I just look at the stats for comp.lang.python, and i am 9th place >>> for >>> most post this month. >> >> And about 9,000th place for useful information. >> >> -- >> Steven > > I think you missed my point Steven, I was in no way proud of the fact > of my 9th place rating. It just proves my point to the small following > of this group. And frankly makes me feel bad. That's just because most of us don't say anything unless we have something useful to say. We prefer to let the experts answer the questions, but we read the threads so we can benefit from them. Steven was pointing out that the number of posts you made has nothing to do with the overall audience of this list or how much real content you are contributing From saju.pillai at gmail.com Thu Dec 11 05:41:21 2008 From: saju.pillai at gmail.com (saju.pillai at gmail.com) Date: Thu, 11 Dec 2008 02:41:21 -0800 (PST) Subject: Equivalent of 'wget' for python? References: Message-ID: On Dec 11, 3:36?pm, "saju.pil... at gmail.com" wrote: > On Dec 11, 2:36?pm, hrishy wrote: > > > Hi > > > Please excuse my OOP but is my understanding correct > > > urllib.urlretrieve(url_of_zip_file,destination_on_local_filesystem) > > > is urllib --->Static Class on which the method urlretrieve method is invoked ? > > No urllib is a "method". Use type(obj) to find out what python thinks typo c/method/module > the "type" of that object is. Note that "object" here is not meant in > the same sense as the OOP definition. > > > > > In that case what does the python 3.0 version mean > > > import urllib.request > > urllib.request.urlretrieve(url, local_file_name) > > > urllib -->static class > > request -->method > > urlretrieve--> what is this then ? > > A 'function'. urllib.request.urlretrieve is the fully qualified name > of the function urlretrieve. In other words urlretrieve lives in the > urllib.request namespace. > > -srp > > > > > regards > > Hrishy > > > --- On Mon, 8/12/08, Jerry Hill wrote: > > > > From: Jerry Hill > > > Subject: Re: Equivalent of 'wget' for python? > > > To: python-l... at python.org > > > Date: Monday, 8 December, 2008, 5:54 PM > > > On Mon, Dec 8, 2008 at 11:53 AM, r0g > > > wrote: > > > > urllib.urlretrieve(url_of_zip_file, > > > destination_on_local_filesystem). > > > > In python 3.0, that appears to be: > > > > import urllib.request > > > urllib.request.urlretrieve(url, local_file_name) > > > > -- > > > Jerry > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > From deets at nospam.web.de Thu Dec 11 18:55:30 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 12 Dec 2008 00:55:30 +0100 Subject: Best way of debigging a C extension In-Reply-To: References: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> <6qdjt7Fc1fg0U1@mid.uni-berlin.de> Message-ID: <6qdnjjFc3ic3U1@mid.uni-berlin.de> Christian Heimes schrieb: > Diez B. Roggisch schrieb: >> I never tried this on windows - but what happens if you start python >> inside GDB, and then set breakpoints inside your extension? >> >> This works flawlessly for me under *nix. >> >> The debug-build of python isn't needed for this - and I doubt a bit that >> it helps you much, as being inside the interpreter & getting detailed >> information isn't your goal - you want to see your extensions functions, >> what parameters they get and so on. > > It doesn't work well with all debugging symbols stripped and with -O2 > optimized code. The compiler rearranges the code. You could try to > compile your own code with different compiler arguments. I don't know if > that's easily possible on Windows with Python 2.5. As I said - as long as you don't care about the python debug code itself, it works pretty well. Usually, the problems are within your extension, which you have the full control over regarding symbols & optimization settings. Diez From barry at python.org Wed Dec 3 21:24:23 2008 From: barry at python.org (Barry Warsaw) Date: Wed, 3 Dec 2008 21:24:23 -0500 Subject: RELEASED Python 3.0 final In-Reply-To: <880dece00812031813t78ec560cy69dd3710fbd4c2a9@mail.gmail.com> References: <880dece00812031813t78ec560cy69dd3710fbd4c2a9@mail.gmail.com> Message-ID: <46FC4EDF-A0A6-4310-A854-4CB5F7A791EE@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Dec 3, 2008, at 9:13 PM, Dotan Cohen wrote: > On this page: > http://www.python.org/download/releases/3.0/ > > The text "This is a proeuction release" should probably read "This is > a production release". It would give a better first impression :) Fixed, thanks! - -Barry -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Darwin) iQCVAwUBSTc/WHEjvBPtnXfVAQL8TwP+M2Ryv7WY36ICEvzGU4EzlRG/gI4MolQe cD8DJUJfQuR6INTot/t7vTcL8oDHq7q9OHbfvd3jmSwH/ZytsMz2OvJUYlKDQjwG BcQRpioprcesoU6cufSmKAUiUP+L0RTAMmT0WDbbeCzzMZRq3Humd4Zs43nL26NT uFb83Dk6yWA= =qPjn -----END PGP SIGNATURE----- From wiggly at wiggly.org Wed Dec 10 11:48:40 2008 From: wiggly at wiggly.org (Nigel Rantor) Date: Wed, 10 Dec 2008 16:48:40 +0000 Subject: To Troll or Not To Troll (aka: "as" keyword woes) In-Reply-To: References: <20081205163107.1815df40@usenot.de> Message-ID: <493FF2E8.3080404@wiggly.org> James Stroud wrote: > Andreas Waldenburger wrote: >> Is it me, or has c.l.p. developed a slightly harsher tone recently? >> (Haven't been following for a while.) > > Yep. I can only post here for about a week or two until someone blows a > cylinder and gets ugly because they interpreted something I said as a > criticism of the language and took it personally by extension. Then I > have to take a 4 month break because I'm VERY prone to > reciprocating--nastily. I think its a symptom of the language's > maturing, getting popular, and a minority fraction* of the language's > most devout advocates developing an egotism that complements their > python worship in a most unsavory way. > > I wish they would instead spend their energy volunteering to moderate > this list and culling out some of the spam. > > *No names were mentioned in the making of this post. I joined this list some time ago, I am not a regular python user. I have maintained my list subscription because when I'm bored the flames here are very entertaining. I don't think I need to mention specifics really. Oh, and the weekly thread about immutable default arguments is a cracker...more please. n From gandalf at shopzeus.com Tue Dec 30 09:35:37 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 30 Dec 2008 15:35:37 +0100 Subject: Python list's mail server in DNSBL ? In-Reply-To: <495A2957.6090805@holdenweb.com> References: <495A2825.4070000@shopzeus.com> <495A2957.6090805@holdenweb.com> Message-ID: <495A31B9.6020507@shopzeus.com> Steve Holden wrote: > Laszlo: > > Read the message again. There's nothing the list admins can do about > this, you'll have to contact Postmaster at chello.at to have them remove > the blacklisting, since it's their server that's imposing it. > Maybe it is my bad English but this part: > Ask your > > Mail-/DNS-Administrator to correct HELO and DNS MX settings and to get > > removed from DNSBLs; in bogusmx.rfc-ignorant.org > > > > > > Please reply to > > if you feel this message to be in error. tells that the problem is with the MX record of python.org and/or the HELO message of the python.org smtp server. At least one of them is said to be RFC ignorant, and this is why the recipient is on the blacklist. Without making those changes, the python.org domain will not be removed from the blacklist. Changing the MX record / configuring the SMTP server needs to be done by the DNS or SMTP admin of python.org. At least I think if I ask chello.at to remove the entry, the first thing they will do is check if the changes has been made. From ronaldrdguez at gmail.com Sun Dec 21 16:46:16 2008 From: ronaldrdguez at gmail.com (Ronald Rodriguez) Date: Sun, 21 Dec 2008 13:46:16 -0800 Subject: noob trouble with IDLE Message-ID: <68f1552e0812211346i96bf18hf28dccc1f8dd1a99@mail.gmail.com> Hi, Im new to python and I've just started using Byte of Python, running the samples etc. Im using IDLE on Xp. Ok, here's the thing. A sample script makes a call to the os.system() function in order to zip some files. Everything works fine when running from the command line, but the same code fails when I try Run --> Run module on IDLE. Im using 7z to zip the files. Again, everything is OK when running from the command line. Remember, Im new to python and programming. I've done some google search without results. Maybe its just too simple :-( . Any help would be appreciated. Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mdgeorge at cs.cornell.edu Wed Dec 3 17:05:58 2008 From: mdgeorge at cs.cornell.edu (Michael George) Date: Wed, 3 Dec 2008 17:05:58 -0500 Subject: building an extension module with autotools? In-Reply-To: <4936FE6D.1000805@v.loewis.de> References: <4936FE6D.1000805@v.loewis.de> Message-ID: <493702C6.5030901@cs.cornell.edu> Martin v. L?wis wrote: >> I've tried using automake, however I'm worried about libtool not getting >> the options right while building my module. >> > > You should use python-config(1) to obtain the command line options > necessary to build and link extension modules. > > HTH, > Martin > Sweet, I think that's exactly what I wanted. Thanks! --Mike From pavlovevidence at gmail.com Wed Dec 24 15:52:02 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 24 Dec 2008 12:52:02 -0800 (PST) Subject: Doing set operation on non-hashable objects References: <3a87eb6a-13ff-4aea-8835-3a233cc6cfc4@w39g2000prb.googlegroups.com> Message-ID: <6c043bc7-19e6-4e3d-bf01-5ade35d8a90a@s1g2000prg.googlegroups.com> On Dec 24, 1:16?pm, 5lvqbw... at sneakemail.com wrote: > Hi, > > I'm writing an application which is structured roughly as follows: > > "db" is a dict, where the values are also dicts. > A function searches through db and returns a list of values, each of > which is a dict as described above. > I need to perform set operations on these lists (intersection and > union) > However the objects themselves are not hashable, and therefore can't > be in a set, because they are dicts. > I'm not sure how large each set will be, but the point is I'm trying > to avoid anything looking like an O(n^2) algorithm, so I can't just > use naive double-looping to check for intersection/union on a pair of > lists. > > The only way I can think of to do this right is to hash the dicts by > freezing them, turning them all into tuples, which can then be > hashed. ?But this is a problem because more dicts might be nested > inside. ?At any rate, I'd need to thaw them out when I'm done and turn > them back into dicts, which seems complicated and annoying, and all > this leads me to believe there is a better way. > > What I really need is a set of pointers, so at the end of the > operation I have the actual objects pointed to. ?Can I somehow use the > object IDs as set elements, then recreate a list with the actual > objects they point to? > > How do you get the object back from an ID in python? Quick and dirty way is to reference the dicts with a lightweight hashable object that uses the dict's identity. For instance: class Identity(object): def __init__(self,obj): self.obj = obj def __hash__(self): return hash(id(self.obj)) def __eq__(self,other): return self.obj is other.obj Then, instead of "s.add(d)" use "s.add(Identity(d))". Instead of "d = s.pop()" use "d = s.pop().obj". Instead of "d in s" use "Identity(d) in s". And so on. To do it a bit better, you could create an IdentitySet class that subclasses set and wraps the methods so that they automatically apply wrap and unwrap the arguments on their way in and out (I'd bet there's already a cookbook recipe to do that). Carl Banks From rt8396 at gmail.com Tue Dec 2 22:06:04 2008 From: rt8396 at gmail.com (r) Date: Tue, 2 Dec 2008 19:06:04 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> <00ab327a-c3fc-4b15-a084-4f8c6aed6a8e@o2g2000yqd.googlegroups.com> <8119ab7e-09f1-44de-bdbc-8fdff969d9e4@33g2000yqm.googlegroups.com> Message-ID: <36056737-3c78-499a-a81d-f6241e904460@t11g2000yqg.googlegroups.com> "If we can laugh what else would we do" I'd like to touch also on some comments by ajaksu: [ajaksu] I'd like to try hacking some form of Python to work in SketchUp (on top of Ruby, that is). Now, why won't I try to? I'm a Linux user and we don't get a SU version. So much for FREEDOM. BTW, some things in SU have encrypted Ruby code behind them :) [/ajaksu] You CAN use SketchUp on Linux...ajaksu...thru Wine, but I know this is not good enough. I would love to see FULL SketchUp support for linux and I HAVE made my voice heard. I urge you brother to make make your voice heard also. Go to this thread and let your voice be heard: http://groups.google.com/group/sketchupsuggestions/browse_thread/thread/7c0c810b88ad4d5/dfabe1e01bab12b3?hl=en#dfabe1e01bab12b3 This is the reason...amoung many others...that Linux has yet to take any noticable market from MS. Linux could...If the Linux devolpers would ban together and unite to make package managment and portability between all *nix's universal, OR one great linux distro that the average dummy can use(ubuntu looks promising, but still has a long way to go)...compete with microsoft on a grand level. We have to steal the idiots from under microsoft's feet, and they will come crumbling down. But as long as a poor n00b installs his shiny new *nix system and can't even connect to the network to see the latest janet jackson "wardrobe malfunction", or fiqure out how to mount a flash drive, Linux will be nothing more than our beloved oddessy. There will NEVER be good support on linux for most applications, games, etc... Until people start to get behind linux and support it. Now you say, well i don't have time to support this, my life is too busy, my back hurts. I say stop making excuses. You DON'T have to invest your life, just simply make your voice heard.(myself and other dedicated people will tow the load). But at least get off your bum and do something. It's time to change the world, the hour is upon us, Microsoft is asleep at the wheel, the time for revolution is NOW! From wicijowski at gmail.com Fri Dec 26 05:09:04 2008 From: wicijowski at gmail.com (janislaw) Date: Fri, 26 Dec 2008 02:09:04 -0800 (PST) Subject: tkinter 3.0 multiple keyboard events together References: Message-ID: <600d4b68-6fe2-4c2c-b425-1a739430bb54@s9g2000prg.googlegroups.com> On 26 Gru, 05:52, Pavel Kosina wrote: > Is it possible to catch in an event more that one key from keyboard? In > my code, I can handle always the only one, the first I press, the others > are omitted. Say, I press both "4" and "8" and only "4" is catched. > > def movePlayer(event): > ? ? print (event.keysym) > > Thank you. > > -- > geon > Pavel Kosina Each keypress triggers another event. Fortunately there are two types of events: reaction to press and release. The logic to write to recognize those as simultaneous clicks is up to you :) JW From rocky at panix.com Thu Dec 11 23:12:52 2008 From: rocky at panix.com (R. Bernstein) Date: 11 Dec 2008 23:12:52 -0500 Subject: pydb 1.24 References: <85vdtqejqr.fsf@dozer.localdomain> Message-ID: J Kenneth King writes: > > I watched the demo video, look forward to working with it. Any links to > that emacs front-end being used in the video? > > Cheers and thanks! In short, the emacs code is bundled in with the tar and should be installed when you run "make install" However if you install from a Debian distribution, Alex Moskalenko has done the work to make sure it will automatically be autoloaded from emacs. And it looks like Manfred Tremmel for SuSE (packman) did so as well. Mandriva gets kudos for being the first to make a package (RPM) for version 1.24 -- the day of the release! I'll dropping just a couple more names -- which is really my way to say thank you to all these kind people. The Emacs code got improved for Python as the result of Emacs some code and Python patches by Alberto Griggio. When pydb "annotation" is set to level 3, what you see is a bit more sophisticated than that shown in the demo. Finally, largely through the efforts of Anders Lindgren, the most sophisticated integration is in the emacs interface for the Ruby debugger, ruby-debug. (Although to my mind that code is still little bit incomplete.) There's no reason that code couldn't be modified to work for Python as well since the command interfaces between the two debuggers are very much the same. Ideally common code would be pulled out and could be used in other gdb-like debuggers as well (kshdb, zshdb, or bashdb). All's it takes is someone to do the work! :-) From stef.mientki at gmail.com Wed Dec 10 15:04:12 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 10 Dec 2008 21:04:12 +0100 Subject: Python is slow In-Reply-To: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: <494020BC.6020700@gmail.com> cm_gui wrote: > http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-a-faster-python-vm.html > > I fully agree with Krzysztof Kowalczyk . > Can't they build a faster VM for Python since they love the language > so much? > > Python is SLOW. And I am not comparing it with compiled languages > like C. > Python is even slower than PHP! > > Just go to any Python website and you will know. > An example is: > http://www2.ljworld.com/ > And this site is created by the creators of Django! > > And it is not just this Python site that is slow. There are many many > Python sites which are very slow. And please don?t say that it could > be the web hosting or the server which is slow ? because when so many > Python sites are slower than PHP sites, it couldn?t be the web > hosting. Also, Zope/Plone is even slower. > > Python is slow. Very slow. > > -- > http://mail.python.org/mailman/listinfo/python-list > Put this guy in the junk filter, in may of this year he (or it) started the same discussion. Stef From joe at strout.net Wed Dec 10 18:55:06 2008 From: joe at strout.net (Joe Strout) Date: Wed, 10 Dec 2008 16:55:06 -0700 Subject: var or inout parm? In-Reply-To: <1228951784.5698.1.camel@mctell> References: <493cda2a$0$17080$426a34cc@news.free.fr> <47c890dc0812080057r6d117bbcic377cb96de52d973@mail.gmail.com> <1228951784.5698.1.camel@mctell> Message-ID: <0AA900D0-F20F-4137-A42A-838468B23648@strout.net> On Dec 10, 2008, at 4:29 PM, J. Clifford Dyer wrote: >>>> mh at pixar.com wrote: >>>>> >>>>> How can I make a "var" parm, where the called function can modify >>>>> the value of the parameter in the caller? >>>>> >> See Also: the earlier heated debate thread over what evaluation >> strategy Python uses (Survey says!: call-by-object). >> > > Oh dear God. PLEASE don't see also that thread. That way lies > madness. > Just google for call-by-object, and ignore the hell out of that > thread. Agreed on that point! Anyway, to the OP, see for a detailed explanation of why you can't do quite what you're asking for in Python (or Java, for that matter). Best, - Joe From istvan.albert at gmail.com Thu Dec 4 08:37:45 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Thu, 4 Dec 2008 05:37:45 -0800 (PST) Subject: RELEASED Python 3.0 final References: Message-ID: <1a73e3be-1753-4178-8091-eaa890b3e07e@l42g2000yqe.googlegroups.com> Congratulations on a fantastic work! From hyugaricdeau at gmail.com Mon Dec 29 10:22:22 2008 From: hyugaricdeau at gmail.com (Hyuga) Date: Mon, 29 Dec 2008 07:22:22 -0800 (PST) Subject: I always wonder ... References: Message-ID: <3d10435f-7a6e-4e47-9ea5-a573151a86de@v5g2000prm.googlegroups.com> On Dec 22, 1:51?pm, Grant Edwards wrote: > On 2008-12-22, s... at pobox.com wrote: > > > ... shouldn't people who spend all their time trolling be > > doing something else: studying, working, writing patches which > > solve the problems they perceive to exist in the troll > > subject? > > I think you misunderstand the point of trolling. ?The author of > a troll post doesn't actually care about the "problems" (and > may not even genuinely perceive them as problems). > > > Is there some online troll game running where the players earn > > points for generating responses to their posts? > > Yup. It's called Usenet. a.k.a. multi-player Emacs in deathmatch mode on nightmare difficulty. ;) From goldnery at gmail.com Thu Dec 25 18:32:53 2008 From: goldnery at gmail.com (Gandalf) Date: Thu, 25 Dec 2008 15:32:53 -0800 (PST) Subject: python interpreter black window Message-ID: I use WX gui so the user doesn't actually need it, Is their any way to hide it? thanks From bj_666 at gmx.net Fri Dec 19 08:34:26 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Dec 2008 13:34:26 GMT Subject: encoding problem References: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> Message-ID: <6r1m72Ffb5kpU3@mid.uni-berlin.de> On Fri, 19 Dec 2008 04:05:12 -0800, digisatori at gmail.com wrote: > The below snippet code generates UnicodeDecodeError. > #!/usr/bin/env > python > #--*-- coding: utf-8 --*-- > s = '???' > u = unicode(s) > > > It seems that the system use the default encoding- ASCII to decode the > utf8 encoded string literal, and thus generates the error. > > The question is why the Python interpreter use the default encoding > instead of "utf-8", which I explicitly declared in the source. Because the declaration is only for decoding unicode literals in that very source file. Ciao, Marc 'BlackJack' Rintsch From ethan at stoneleaf.us Mon Dec 15 11:31:53 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 15 Dec 2008 08:31:53 -0800 Subject: Limit traceback from most recent call In-Reply-To: <49454B4E.30308@aim.com> References: <49454B4E.30308@aim.com> Message-ID: <49468679.4050705@stoneleaf.us> Brian Allen Vanderburg II wrote: > I've looked at traceback module but I can't find how to limit traceback > from the most recent call if it is possible. I see that extract_tb has > a limit parameter, but it limits from the start and not the end. > Currently I've made my own traceback code to do this but wonder if > python already has a way to do this build in: > > def format_partial_exc(limit=None): > > (type, value, tb) = sys.exc_info() > > items = traceback.extract_tb(tb) > > if limit: > > items = items[-limit:] # Get last 'limit' items and not first > > result = 'Traceback (most recent call last):\n' > > items = traceback.format_list(items) > > for i in items: > > result += i # Newline already included > > result += type.__name__ + ': ' + str(value) > > return result > > Is this possible currently from traceback or other python module? > > Brian A. Vanderburg II If memory serves, you can catch the exception, then re-raise it -- this should hide all the traceback below where you caught it, but still return the actual error. Hope this helps. ~Ethan~ From collin.day.0 at gmail.com Thu Dec 18 21:17:19 2008 From: collin.day.0 at gmail.com (Collin D) Date: Thu, 18 Dec 2008 18:17:19 -0800 (PST) Subject: Factoring Polynomials References: Message-ID: <919062f9-765e-4279-aa26-2c130d4deacf@o4g2000pra.googlegroups.com> On Dec 18, 6:12?pm, Collin D wrote: > On Dec 18, 11:37?am, collin.da... at gmail.com wrote: > > > I am trying to write a simple application to factor polynomials. I > > wrote (simple) raw_input lines to collect the a, b, and c values from > > the user, but I dont know how to implement the quadratic equation > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > into python. Any ideas? > > I completed the code: > > #import > from math import sqrt > > # collect data > a = float(raw_input('Type a value: ')) > b = float(raw_input('Type b value: ')) > c = float(raw_input('Type c value: ')) > > # create solver > def solver(a,b,c): > ? ? if b**2 - 4*a*c < 0: > ? ? ? ? return 'No real solution.' > ? ? else: > ? ? ? ? sol1 = -1 * b + (sqrt(b**2 - 4*a*c)) / 2*a > ? ? ? ? sol2 = -1 * b - (sqrt(b**2 - 4*a*c)) / 2*a > ? ? ? ? return (sol1, sol2) > > # execute > print solver(a,b,c) > > Thanks to everyone who helped... > This really expanded my knowledge on some of the mathematical > functions in Python. UPDATE: ' #import from math import sqrt # collect data a = float(raw_input('Type a value: ')) b = float(raw_input('Type b value: ')) c = float(raw_input('Type c value: ')) # create solver def solver(a,b,c): if b**2 - 4*a*c < 0: return 'No real solution.' else: sol1 = (-1 * b + (sqrt(b**2 - 4*a*c))) / 2*a sol2 = (-1 * b - (sqrt(b**2 - 4*a*c))) / 2*a return (sol1, sol2) # execute print solver(a,b,c) From rt8396 at gmail.com Mon Dec 22 23:50:06 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 20:50:06 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <18767.47566.709705.92@montanaro-dyndns-org.local> <5uudnUmykoMD983UnZ2dnUVZ_rrinZ2d@posted.usinternet> Message-ID: <8a43ed9b-51c6-4c3f-9f90-7caf0e910093@k36g2000yqe.googlegroups.com> The average user thinks python is only a very large snake! From bdesth.quelquechose at free.quelquepart.fr Sat Dec 6 10:08:59 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 06 Dec 2008 16:08:59 +0100 Subject: Pythonic design patterns In-Reply-To: <815c6e46-283f-44c3-ba78-b1f9223dd48b@v13g2000yqm.googlegroups.com> References: <815c6e46-283f-44c3-ba78-b1f9223dd48b@v13g2000yqm.googlegroups.com> Message-ID: <493aa345$0$14438$426a74cc@news.free.fr> r.grimm at science-computing.de a ?crit : > Hallo, >> users in this forum has been kind enough to point out. Only my >> implementations are often not that clean, and I may call things >> something different than the normal convention, which is a source of >> confusion for myself and others trying to communicate with me. > I think, you should start with the classical books of Design Patterns > to get a solid understanding and especially vocabulary to communicate > with your coworkers. Its easier and better to say, that you will use a > strategy pattern than to describe the architecture in many sentences > to your partner in a ambigious way. Indeed. But now there's the risk that coworkers implement this as: class AbstractFooStrategy(object): def run(self, yadda): raise NotImplementedError class SimpleFooStrategy(AbstractFooStrategy): def run(self, yadda): # code here class Bar(object): def __init__(self, foo_strategy): if not isinstance(foo_strategy, AbstractFooStrategy): raise ValueError("yadda yadda") self.foo_strategy = foo_strategy def do_this(self, yadda): return self.foo_strategy.run(yadda) b = Bar(SimpleFooStrategy()) instead of: class Bar(object): def __init__(self, foo_strategy): self.foo_strategy = foo_strategy def do_this(self, yadda): return self.foo_strategy(yadda) def baaz(yadda): # code here b = Bar(baaz) > Thats in my opinion the first and > the key benefit of Design Patterns. Totally agree - at least as long as coworkers clearly understand the difference between design and implementation. > Speaking in the same language. The > next step should be to apply your knowledge to your programming > language. Indeed !-) > So I will recommend the classical GOF Books While most implementation example are way over the top in the context of a hi-level dynamic language like Python, the GOF is one of the best book on OO design I've ever read - if not the only that was worth reading (disclaimer : I didn't read much dead-tree stuff on OO). From castironpi at gmail.com Tue Dec 16 23:09:47 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 16 Dec 2008 20:09:47 -0800 (PST) Subject: How to modify a program while it's running? References: <01584cbd$0$20656$c3e8da3@news.astraweb.com> <1fe20306-39ff-4169-b49e-5ae5dd8159af@v5g2000prm.googlegroups.com> Message-ID: On Dec 16, 7:54?pm, "James Mills" wrote: > @Aaron > > Your code and suggestion is way too complicated. > Just register your objects. When you need to > reload your module, destroy the existing > objects and re-creat them. > > This works well assuming you have a stable > running core that maintains the connection > and that code doesn't change much. > > --JamesMills The practical and general solutions aren't very similar. Practically, I agree. You could do something generic like reassign __dict__ (like the Borg pattern), or __class__. To be completely general, you'd need an object which passes the type test: "TypeError: unbound method f() must be called with A instance as first argument ( got B instance instead)". Then you could call it in anything, Cls.meth ( obj ), regardless of if you created it before or after the class was created. Or you could have a class that looked up its (posessive) methods' names on a deeper class which could be loaded later: the Delegate, Proxy, or Adapter patterns. Maybe Cls.meth( obj ) should be permitted to work on arbitrary objects by a compiler switch or __future__ import. From rt8396 at gmail.com Tue Dec 23 11:06:35 2008 From: rt8396 at gmail.com (r) Date: Tue, 23 Dec 2008 08:06:35 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: On Dec 23, 8:21?am, Thorsten Kampe wrote: > * r (Mon, 22 Dec 2008 10:44:32 -0800 (PST))> > > > Steve Holden > > > What makes you assume this is a zero-sum game, and that Python won't > > > survive if any other language becomes popular. Every language borrows > > > from those that came before it. Terms like "outright plagiarism" don't > > > encourage rational debate, and make you seem like a troll who is more > > > interested in stirring up controversy than actually doing things to help > > > promote the language. > > > This is a war Steve, and i will explain why. Python does not need to > > compete with perl, lisp, C, basic, etc, etc. WHY, well because python > > is SO radically different than those languages. Ruby on the other > > hand, took most from python, the only difference is Ruby's full OO > > integration.(12.method()). Since Ruby is so similar to python [...] > > You don't have a single clue about neither Python nor Ruby: > 'According to the Ruby FAQ, "If you like Perl, you will like Ruby and be > right at home with its syntax. [...] If you like Python, you may or may > not be put off by the huge difference in design philosophy between > Python and Ruby/Perl."'[1] > > Thorsten > [1]http://en.wikipedia.org/wiki/Ruby_(programming_language)#Semantics Thats "Thurstan", thank you very much! :) From t.gkikopoulos at dundee.ac.uk Mon Dec 8 10:03:37 2008 From: t.gkikopoulos at dundee.ac.uk (trias) Date: Mon, 8 Dec 2008 07:03:37 -0800 (PST) Subject: appending values into array instead of a list Message-ID: <20896957.post@talk.nabble.com> Hi, I have this little script: import csv import numpy signal=[] ref=[] for x in csv.reader(open('reffile.csv').readlines()): ref.append(x) for x in csv.reader(open('signalfile.csv').readlines()): signal.append(x) signalarray=numpy.array(signal, dtype=float) signaldict={} signaldict.update(dict(signalarray)) intarray=[0.0 for x in range(301)] cntarray=[0 for x in range(301)] for line in ref: print line locstr=line[1] endstr=line[2] loc=float(locstr) end=float(endstr) print loc print end i=0 while float(i) <= 300.0: if signaldict.has_key(end+float(i)): expr=signaldict[end+float(i)] print expr intarray[i]+=expr cntarray[i]+=1 y=i i+=1 print intarray print cntarray fo=file('outfile.txt','w') s=str(intarray) fo.write(s) fo.close() So on the above I am appending values from signaldict indexed by i for every object in the ref list. This way I calculate the sum of all values with similar indexing i value. Would I be able to store the signaldict[i] for every line individually in a multidimensional array? cheers -- View this message in context: http://www.nabble.com/appending-values-into-array-instead-of-a-list-tp20896957p20896957.html Sent from the Python - python-list mailing list archive at Nabble.com. From bertilow at gmail.com Sat Dec 6 21:05:15 2008 From: bertilow at gmail.com (Bertilo Wennergren) Date: Sun, 07 Dec 2008 11:05:15 +0900 Subject: Learning Python now coming from Perl In-Reply-To: References: Message-ID: Aahz wrote: > In article , > Bertilo Wennergren wrote: >> I don't suppose there is any introductory material out there that is >> based on Python 3000 and that is also geared at people with a Perl >> background? Too early for that I guess.. > Honestly, the differences between 2.x and 3.0 are small enough that it > doesn't much matter, as long as you're not the kind of person who gets > put off by little problems. Because so much material is for 2.x, you > may be better off just learning 2.x first and then moving to 3.x. The main reason I waited until Python 3000 came out is the new way Unicode is handled. The old way seemed really broken to me. Much of what I do when I program consists of juggling Unicode text (real Unicode text with lots of actual characters outside of Latin 1). So in my case learning version 2.x first might not be very convenient. I'd just get bogged down with the strange way 2.x handles such data. I'd rather skip that completely and just go with the Unicode handling in 3.0. -- Bertilo Wennergren From jeremiah.dodds at gmail.com Wed Dec 3 06:50:49 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Wed, 3 Dec 2008 06:50:49 -0500 Subject: Converting a .xls file to .html In-Reply-To: References: Message-ID: <12cbbbfc0812030350u26b8f41cw6569d7b17bf21d41@mail.gmail.com> On Wed, Dec 3, 2008 at 5:54 AM, tarun wrote: > Hello All, > > I've a .xml file (saved as .xls) that can be opened in Microsoft excel. I > want to write python code that converts this excel file into .html (so that > it can be viewed as is in an explorer). > > Can any one help? > > Regards, > Tarun > > -- > http://mail.python.org/mailman/listinfo/python-list > > A quick google search shows http://pyxlreader.sourceforge.net/ , and a few other libraries for reading xls files. I don't use excel, so I can't test it. There may not be a library for going straight from xls -> html, but if you can get xls -> text or a list or whatnot, then you could use pretty much any html generation tool you want on it, python's got plenty of templating libraries available. -------------- next part -------------- An HTML attachment was scrubbed... URL: From darcy at druid.net Tue Dec 16 17:24:16 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 16 Dec 2008 17:24:16 -0500 Subject: Need help improving number guessing game In-Reply-To: References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> <01564c98$0$21844$c3e8da3@news.astraweb.com> <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> <4946df78$0$19771$426a74cc@news.free.fr> <1f33580b-84f9-4059-a0f0-b6a8d71325af@b38g2000prf.googlegroups.com> <4947742c$0$25951$426a34cc@news.free.fr> Message-ID: <20081216172416.186e0d43.darcy@druid.net> On Tue, 16 Dec 2008 13:59:24 -0800 Scott David Daniels wrote: >> > def yesno(s): > > s = s.strip().lower() > > if not s in ("y", "n"): You could also do this to be a little more user friendly: if not (s and s[0] in ("y", "n")): Or reverse the test for clarity. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From fakeaddress at nowhere.org Mon Dec 15 01:59:24 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 14 Dec 2008 22:59:24 -0800 Subject: Bidirectional Networking In-Reply-To: References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <98a6c3cd-181c-43c9-805b-fb0689c69544@a26g2000prf.googlegroups.com> <29283382-3e26-492a-8612-9352f32c1c01@r15g2000prd.googlegroups.com> Message-ID: Brian Allen Vanderburg II wrote: > As for the backlog (5), this > doesn't mean that you can only have a maximum of 5 established > connections. Each established connection gets a new socket object. But > what I think it means is that during the listen for an incoming > connection on the listening socket, if multiple connection attempts are > coming in at one time it can keep a backlog of up to 5 of these > connection attempts for that individual socket. Right. An incoming connect adds a connection to the listen queue, and the application's accept() call removes one connections from the queue. The limited backlog is relevant to the OP's suggestion of calling SocketServer.handle_request() periodically. The accept() that pulls connections off the listen queue is within handle_request(), thus during the period between these calls incoming connections will queue up and could easily reach the limit. -- --Bryan From steve at REMOVE-THIS-cybersource.com.au Fri Dec 12 17:54:18 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Dec 2008 22:54:18 GMT Subject: concept of creating structures in python References: Message-ID: <0152e321$0$8244$c3e8da3@news.astraweb.com> On Fri, 12 Dec 2008 09:07:21 -0700, Joe Strout wrote: >> Joe missed a piece out here. If you change the signature of your >> D.__init__() to read >> >> def __init__(self, dataName='ND', index = 0, ele_obj=None): >> >> then you need to insert the following code at the top of the method: >> >> if ele_obj is None: >> ele_obj = E() > > Yes, if you really need to guarantee that ele_obj is not None, then this > is the way to do it. > > Of course this would mean that you can't get a None ele_obj even by > passing it in explicitly as the parameter value -- if you need to > support that as well, then the solution is a little more complex. > Perhaps best in that case would be to just not give ele_obj any default > value at all, so it becomes a required parameter. Just use a sentinel that isn't None. class D(...): sentinel = object() def __init__(self, dataName='ND', index = 0, ele_obj=sentinel): if ele_obj is D.sentinel: ... -- Steven From bdesth.quelquechose at free.quelquepart.fr Mon Dec 22 13:50:45 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 22 Dec 2008 19:50:45 +0100 Subject: Python's popularity In-Reply-To: References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: <494fef38$0$12781$426a74cc@news.free.fr> walterbyrd a ?crit : > On Dec 22, 10:13 am, r wrote: >> Since the >> advent of Ruby(Python closet competitor), Python's hold on this niche >> is slipping. > > About the only place I ever hear of ruby being used is web development > with RoR. When it comes to web development, it seems to me that ruby > (because of rails) is far more popular s/popular/hyped/ But being (perhaps over ?) hyped too soon is not necessarily the best move... > than python. It seems to me > that ruby is the niche player, and python (with fairly new frameworks) > is trying to catch up to ruby in that niche. It seems to me that the > python web framework that best competes with rails, is Django, and > Django 1.0 just came out a few months back. Fooled by version numbers ? Heck, Python 3.0 just came out a couple weeks ago, and PHP is already at 6.x !-) FWIW, I wrote my first django app years ago (and it's still in production). >> A lot of Ruby noobies don't even realize that most of >> Ruby is an out-right plagiarism of Python. I don't know who asserted such a stupid thing, but he manages to be equally clueless wrt/ both languages. > Maybe. But the rails framework seems to have a different philosophy > than the django, turbogears, or pylons, frameworks. RoR values > convention over configuration, and has a lot of "magic" whereas the > python frameworks seem to have the opposite philosophy - in those > regards. I see pros and cons to both approaches. I wonder what the > market with think? My actual CTO is a big Ruby/Rails fan, yet he settled on Python/Django for our current 'big' project. Wonder why ? From pavlovevidence at gmail.com Fri Dec 19 21:16:09 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 19 Dec 2008 18:16:09 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <863a4a88-5051-4526-b882-c448eb2ea2ad@k36g2000pri.googlegroups.com> On Dec 19, 12:10?pm, Christian Heimes wrote: > walterbyrd schrieb: > > > On Dec 19, 9:13 am, "Giampaolo Rodola'" wrote: > >> You can use the old 2.x syntax also in Python 3.x: > > > Yeah, but it's deprecated, and - as I understand it - may be removed > > completely in future versions. Also, in the future, if you are working > > with code from another developer, it's likely that developer will use > > the new format. I suppose you can use both - but what an awful mess > > that would be. > > It's not going to be removed for many years - if ever. The % string > formatting system is not deprecated in 3.0. For that very reason it must > stay until 3.2. We don't have plans to deprecate it in 3.1 so it will > stay at least until Python 3.3 which is to be released about 2014. I wish they would have at least deprecated or got rid of the % operator, because that's ugly. There's no reason they couldn't have added another method for printf-style formating, e.g.: "The answer is %s.".sprintf("yes") Carl Banks From mnordhoff at mattnordhoff.com Tue Dec 23 19:54:32 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Wed, 24 Dec 2008 00:54:32 +0000 Subject: using subprocess module in Python CGI In-Reply-To: References: Message-ID: <49518848.1080602@mattnordhoff.com> ANURAG BAGARIA wrote: > Hello, > > I am a Python Newbie and would like to call a short python script via > browser using a CGI script, but initially I am trying to call the same > python script directly through python command line. The script intends > to perform a few command line in a pipe and I have written the script (a > short one) as follows. > > #!/usr/bin/python > > import cgi, string, os, sys, cgitb, commands, subprocess > import posixpath, macpath > #file = "x.tar.gz" > #comd = "tar -xf %s" % (file) > #os.system(comd) > #commands.getoutput('tar -xf x.tar.gz | cd demo; cp README ../') > comd = [\ > "tar -xf x.tar.gz", \ > "cd demo", \ > "cp README ../", \ > ] That's not how subprocess.call() works. You're trying to run an executable called "tar -xf x.tar.gz", passing it the arguments "cd demo" and "cp README ../". > outFile = os.path.join(os.curdir, "output.log") > outptr = file(outFile, "w") > errFile = os.path.join(os.curdir, "error.log") > errptr = file(errFile, "w") > retval = subprocess.call(comd, 0, None, None, outptr, errptr) > errptr.close() > outptr.close() > if not retval == 0: > errptr = file(errFile, "r") > errData = errptr.read() > errptr.close() > raise Exception("Error executing command: " + repr(errData)) > > > but after trying to execute this independently, I get the following > error which I am unable to interpret : > > Traceback (most recent call last): > File "process.py", line 18, in > retval = subprocess.call(comd, 0, None, None, outptr, errptr) > File "/usr/lib/python2.5/subprocess.py", line 443, in call > return Popen(*popenargs, **kwargs).wait() > File "/usr/lib/python2.5/subprocess.py", line 593, in __init__ > errread, errwrite) > File "/usr/lib/python2.5/subprocess.py", line 1135, in _execute_child > raise child_exception > > > Could someone suggest where am I going wrong and if corrected, what is > the probability of this script being compatible with being called > through the browser. Thanking you people in advance. Well, you'd need to output something, but otherwise, sure, why not? print "Content-Type: text/html" print print "..." > Regards. Why do you even need to use subprocess to do this? All it's doing is extracting the README file from a tarball, right? You can use the tarfile module for that. -- From rtomek at ceti.com.pl Mon Dec 15 22:16:06 2008 From: rtomek at ceti.com.pl (Tomasz Rola) Date: Tue, 16 Dec 2008 04:16:06 +0100 (CET) Subject: Python is slow In-Reply-To: <25b4d503-5073-4e66-8914-ca5fa7b144e1@w39g2000prb.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <25b4d503-5073-4e66-8914-ca5fa7b144e1@w39g2000prb.googlegroups.com> Message-ID: On Fri, 12 Dec 2008, bearophileHUGS at lycos.com wrote: > In the next years people that use low-level languages like C may need > to invent a new language fitter for multi-core CPUs, able to be used > on GPUs too (see the OpenCL), less error-prone than C, able to use the > CPU vector instructions efficiently. (The D language is probably unfit > for this purpose, because even if it's meant to be a system language, > I don't think it can be used much to replace C everywhere it's used > now.) A C+ maybe? :-) > > Bye, > bearophile I would say, this probably will be some descendant of Erlang and/or Haskell. As evolutionary step, they look very promising to me, they just are "not quite there" yet. As of C++, I cannot tell before I read their new standard. Regards, Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** From darcy at druid.net Thu Dec 25 08:51:43 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 25 Dec 2008 08:51:43 -0500 Subject: os.system('cls') In-Reply-To: References: <05BADA85-33ED-48BF-B251-2CC830D6D55E@rgbaz.eu> Message-ID: <20081225085143.fc9be5c4.darcy@druid.net> On Thu, 25 Dec 2008 13:11:09 +0100 "Dennis van Oosterhout" wrote: > Btw...does that mean that system('cls') only works on Windows...or to > say it otherwise: the program isn't platform independant? Exactly - sort of. Unless, of course, you have a program called "cls" installed on other platforms. The "system" method is platform independent in that it runs system commands on all platforms but it has no control over what system commands happen to exist on your system. Depending on the command you run it may not even be portable to another Windows system of exactly the same version. BTW, "os.system('clear') will clear the screen on many Unix systems. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From clp at rebertia.com Thu Dec 18 01:08:02 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 17 Dec 2008 22:08:02 -0800 Subject: importing csv file into sqlite In-Reply-To: <21067453.post@talk.nabble.com> References: <21067453.post@talk.nabble.com> Message-ID: <47c890dc0812172208s4b827b2fw4f4bb946783108fa@mail.gmail.com> On Wed, Dec 17, 2008 at 9:58 PM, klia wrote: > > hey guys, i have a hug .csv file which i need to insert it into sqlite > database using python. > my csv data looks like this > Birthday2,12/5/2008,HTC,this is my birthday > Sea,12/3/2008,kodak,sea > birthday4,14/3/2009,samsung,birthday > love,17/4/2009,SONY,view of island > > can any one give me a head start codes. > Use the `csv` module to read the CSV file: http://docs.python.org/library/csv.html I think one who knows sqlite can quite easily figure it out from there. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From skip at pobox.com Tue Dec 9 21:07:24 2008 From: skip at pobox.com (Skip Montanaro) Date: Wed, 10 Dec 2008 02:07:24 +0000 (UTC) Subject: Test message - please ignore References: Message-ID: Skip Montanaro pobox.com> writes: > > Testing a new news-to-mail gateway on mail.python.org. > This post is from gmane. Please ignore. Test #4. Another one to ignore... S From bdesth.quelquechose at free.quelquepart.fr Fri Dec 12 14:41:57 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 12 Dec 2008 20:41:57 +0100 Subject: Python is slow In-Reply-To: <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> Message-ID: <4942cc3c$0$21936$426a74cc@news.free.fr> sturlamolden a ?crit : (snip) > Creating a fast implementation of a dynamic language is almost rocket > science. But it has been done. There is Stronghold, the fastest > version of Smalltalk known to man, on which the Sun Java VM is based. > On a recent benchmark Java 6 -server beats C compiled by GCC 4.2.3 cf bearophile's comment on this point (CPU architecture and RAM) > And > most of that magic comes from an implementation of a dynamically typed > language (Smalltalk). Err... Where is _Java_ "dynamic" actually ? A benchmark of _Smalltalk_ VM vs CPython VM would make more sense. > Second, there are other fast implementations of dynamic languages. The > CMUCL and SBCL versions of Common Lisp comes to min; you can see how > SBCL does in the same benchmark (CMUCL tends to be even faster). Could it be that there are some type hints in the lisp versions of the source code ? > So Python is a lot slower than it needs to be. Please fix it, you're welcome. From kirk at daycos.com Fri Dec 12 13:18:40 2008 From: kirk at daycos.com (Kirk Strauser) Date: Fri, 12 Dec 2008 12:18:40 -0600 Subject: (Very Newbie) Problems defining a variable References: Message-ID: <878wqlz27z.fsf@daycos.com> At 2008-12-12T18:12:39Z, "Tim Rowe" writes: > Is there a tidy way of making rates and thresholds local to get_rate, > without recalculating each time? I suppose going object oriented is > the proper way. > > #Py3k,UTF-8 > > rates = {0: 0.006, 10000: 0.0085, 25000: 0.0124, 50000: 0.0149, 100000: 0.0173} > thresholds = list(rates.keys()) > thresholds.sort() > thresholds.reverse() > > def get_rate(balance): > for threshold in thresholds: > if balance >= threshold: > return rates[threshold] > else: > return 0.0 How 'bout: def get_rate(balance): for threshold, rate in ((100000, .0173), (50000, .0149), (25000, .0124), (10000, .0085), (0, .006)): if balance > threshold: return rate return .0 -- Kirk Strauser The Day Companies From sumerc at gmail.com Thu Dec 4 09:23:28 2008 From: sumerc at gmail.com (k3xji) Date: Thu, 4 Dec 2008 06:23:28 -0800 (PST) Subject: Python Runtime Method Call Binding Message-ID: Hi, Is there a way to hook a function call in python? I know __getattr__ is doing for variables, it is giving us a chance before a field is initialized. Do we have same functionality for methods? Example: class Foo(object): def __call_method__(self, ...) # just pseudo print 'A method is called in object...' f = Foo() f.test_method() I think you understand my point. Thanks, From geekmail at usenot.de Thu Dec 4 14:41:21 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Thu, 4 Dec 2008 20:41:21 +0100 Subject: "as" keyword woes References: <7dudnSS7uIn_KarUnZ2dnUVZ_tTinZ2d@earthlink.com> <0147e4df$0$20670$c3e8da3@news.astraweb.com> Message-ID: <20081204204121.0fda015c@usenot.de> On Thu, 4 Dec 2008 10:44:33 -0600 "Chris Mellon" wrote: > Aside from the cultural indoctrination, though (and that may be a real > and strong force when dealing with math software, and I don't want to > discount it in general, just for purposes of this discussion) why is > it more sensible to use "x" here instead of "number" or "real" or > "real_number" or something else? I think "aside from" doesn't really apply. It is habitual to write mathematics in shorthand. That is a, if not *the* factor to consider. Also: Variable names in programs tend to describe what those things *do* not what they are. If I call a variable "number", the reader will usually none the wiser, because you deal with numbers a lot anyway. You'd call your numbers "counter", "height", "pressure" and the like. If however you do lots of numerical computations, your numbers tend to be just that, numbers. You'll gain nothing but confusion by calling them "number1", "number2", "number3". They are then much easier to discern by calling them x, y and z. I think. /W -- My real email address is constructed by swapping the domain with the recipient (local part). From rhodri at wildebst.demon.co.uk Sun Dec 7 18:26:14 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Sun, 07 Dec 2008 23:26:14 -0000 Subject: Don't you just love writing this sort of thing :) In-Reply-To: References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: On Sun, 07 Dec 2008 07:27:51 -0000, Lawrence D'Oliveiro wrote: > In message , Rhodri > James wrote: > >> Yes, it's very pretty, and you're terribly clever. In six months' time >> when you come back to make some engineering change and have to sit down >> and break it back down into those simple pieces to remind yourself what >> it's doing, "pretty" and "clever" will not be the words you are using. >> Trust me on this one. > > Considering I've been writing and maintaining and debugging code for > about > 30 years now, I figure I have the hard-earned right to judge what I will > be > able to understand in six months and what I won't... Huh. I can only claim 25 years, but I would still strongly discourage people from playing that sort of game. -- Rhodri James *-* Wildebeeste Herder to the Masses From __peter__ at web.de Thu Dec 18 09:19:49 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 18 Dec 2008 15:19:49 +0100 Subject: re.match() performance References: <755bd716-f5f6-4953-87a7-04ee148c3298@i18g2000prf.googlegroups.com> Message-ID: Emanuele D'Arrigo wrote: > I've written the code below to test the differences in performance > between compiled and non-compiled regular expression matching but I > don't quite understand the results. It appears that the compiled the > pattern only takes 2% less time to process the match. Is there some > caching going on in the uncompiled section that prevents me from > noticing its otherwise lower speed? Yes: >>> import re >>> re._cache {} >>> re.match("yadda", "") >>> re._cache {(, 'yadda', 0): <_sre.SRE_Pattern object at 0x2ac6e66e9e70>} Hint: questions like this are best answered by the source code, and Python is open source. You don't even have to open an editor: >>> import inspect >>> print(inspect.getsource(re.match)) def match(pattern, string, flags=0): """Try to apply the pattern at the start of the string, returning a match object, or None if no match was found.""" return _compile(pattern, flags).match(string) >>> print(inspect.getsource(re._compile)) def _compile(*key): # internal: compile pattern cachekey = (type(key[0]),) + key p = _cache.get(cachekey) if p is not None: return p pattern, flags = key if isinstance(pattern, _pattern_type): if flags: raise ValueError( "Cannot process flags argument with a compiled pattern") return pattern if not sre_compile.isstring(pattern): raise TypeError("first argument must be string or compiled pattern") p = sre_compile.compile(pattern, flags) if len(_cache) >= _MAXCACHE: _cache.clear() _cache[cachekey] = p return p Peter From philip at semanchuk.com Sun Dec 21 16:27:25 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Sun, 21 Dec 2008 16:27:25 -0500 Subject: Are Django/Turbogears too specific? In-Reply-To: <494eb16e$0$22710$426a74cc@news.free.fr> References: <494eb16e$0$22710$426a74cc@news.free.fr> Message-ID: <2B198A4F-5911-456D-A45B-E073DB121446@semanchuk.com> On Dec 21, 2008, at 3:14 PM, Bruno Desthuilliers wrote: > Philip Semanchuk a ?crit : > (snip) >> From the reading I did, I gathered that Django was really good if >> you want to do what Django is good at, but not as easy to customize >> as, say, Pylons. > > That was my first impression too, and was more or less true some > years ago. After more experience, having gained a deeper knowledge > of Django's internals, I can tell you this is just not true. You can > "customize" it as you want - meaning: you can use any ORM (or no ORM > at all) and any template language you want, as long as you don't > intend to use django's ORM and template language related features > (which just don't exist in Pylons). IOW : Django is just as flexible > as Pylons (or pretty close to), but has more to offer if you stick > to builtin components. Based on what I read, I got the idea that Django *can* be as flexible as Pylons, but most people find it *easier* to take advantage of Pylons' flexibility. In other words, no one is saying Django is incapable, but that it is less focused on making it easy to allow developers to mix & match components and more focused on providing a smooth tool with which to work. > NB : not to dismiss Pylons, which is a pretty great framework too, > and use IMHO better default components (namely SQLAlchemy and Mako). I prefer Mako over the other template languages I've seen. From iainking at gmail.com Wed Dec 3 05:54:55 2008 From: iainking at gmail.com (Iain King) Date: Wed, 3 Dec 2008 02:54:55 -0800 (PST) Subject: Obama's Birth Certificate - Demand that US presidential electors investigate Obama's eligibility References: <89pZk.9151$be.4743@nlpi061.nbdc.sbc.com> Message-ID: <6cf32afd-f167-4c3e-884a-48452eaa8f82@w34g2000yqm.googlegroups.com> On Dec 3, 10:16 am, MM4... at yahoo.com wrote: > On Dec 3, 12:53 am, Bryan Olson wrote: > > > > > girbarob... at yahoo.com wrote: > > > This message is not about the meaningless computer printout called > > > More importantly, it's not about Python. I'm setting follow-ups to > > talk.politics. > > > > "Certification of Live Birth" that Obama propaganda machine calls his > > > "Birth Certificate". The American people are still waiting for a copy > > > of Obama's original birth certificate that includes all his birth > > > information. > > > The document is what Hawaii provides as certified copy of birth record. > > It contains all the information the federal government requires to prove > > citizenship by birth, and it shows that Barack Hussein Obama was born 04 > > August 1961 in Honolulu. See: > > > http://www.factcheck.org/elections-2008/born_in_the_usa.html > > This garbage on factcheck.org is a worthless piece of paper > insufficient to prove a US citizenship much less a natural born one. > You need to have a long version of legitimate birth certificate that > includes all birth information. Hawaii officials never even confirmed > this piece of garbage on factcheck.org > > > > Remind your US presidential electors of their constitutional duty to > > > investigate Obama's natural-born citizen status. > > > > No federal agency like FBI or Secret Service, no Hawaii bureaucrats > > > have ever investigated Obama's birth in Hawaii. Many illegal aliens in > > > USA have official "birth certificates" issued by state bureaucrats on > > > the basis of falsified birth records. > > > Janice Okubo of Hawaii's Department of Health confirmed that the state > > has Obama?s original birth certificate on record: > > > http://hawaii.gov/health/about/pr/2008/08-93.pdf > > > [...] > > Do you have a sufficient IQ to actually grasp what this news release > says? > > All it says is that Hawaii has "Obama?s original birth certificate". > It does not say anything whether this "Obama?s original birth > certificate" is from Hawaii or Kenya or from Indonesia. Under the > Hawaii laws, a parent could use an original birth certificate from > another country to register a child in Hawaii and get today > "Certification of Live Birth". People actually born in Hawaii do not > get such "Certification of Live Birth", they get another document with > different name. > > Considering all the public pressure on Hawaii officials to confirm > Obama's birth in Hawaii, they would start any response with > confirmation that Obama was born in Hawaii. Instead, they give you > carefully worded garbage so that your low IQ brain can swallow it and > Obama propaganda machine can beat into your worthless brain until you > repeat it like a low IQ moron. > > > > > > > > Remind your US presidential electors that they have the legal standing > > > and constitutional duty to investigate Obama's birth in Hawaii by > > > demanding that Obama provide all his original birth records, and a > > > federal agency like FBI or Secret Service fully investigate them. > > > That's not what the Constitution says. US Constitution, Article IV, > > Section 1: "Full Faith and Credit shall be given in each State to the > > public Acts, Records, and judicial Proceedings of every other State. And > > the Congress may by general Laws prescribe the Manner in which such > > Acts, Records and Proceedings shall be proved, and the Effect thereof." > > > These haters seek to make Obama prove his records in ways others have > > not had to, and beyond any manner prescribed by Congress within its > > constitutional authority. > > You do not have enough brain cells to understand anything you just > quoted. > > Get one thing straight for your own self interest! THERE ARE TENS OF > MILLIONS OF GUN OWNERS IN USA ONLY WAITING TO USE THEM ON ANYBODY WHO > THREATENS THE US CONSTITUTION - so better use all your brain cells in > your own self interest to resolve this matter now and not later. Run > to Obama and beg him to release all birth records or things will not > get any better. You are playing with fire. Heh, you're awesome. Keep it up! From jules at REMOVETHIS.op59.net Wed Dec 10 06:58:25 2008 From: jules at REMOVETHIS.op59.net (Julian Smith) Date: Wed, 10 Dec 2008 11:58:25 +0000 Subject: Using the `email' module in a bazaar plugin Message-ID: <20081210115825.01853c3b.jules@REMOVETHIS.op59.net> I don't seem to be able to use the `email' module from within a bazaar plugin. Other modules work ok, e.g. nntplib. Here's my plugin, cut-down to show just the email problem: import sys print 'sys.version', sys.version import nntplib n = nntplib.NNTP( 'jsmith-ubuntu2' ) print n import email m=email.MIMEText.MIMEText('text of email') - and here's the output when i run any bazaar command: > bzr status sys.version 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] 'module' object has no attribute 'MIMEText' Unable to load plugin 'js_notify' from '/home/jsmith/.bazaar/plugins' ... The plugin runs fine on its own, it's only when loaded into Bazaar that things go wrong. I thought perhaps this could be caused by the `email' module's use of LazyImporter. I've tried various things such as `from email.mime.text import MIMEText', and they fail in similar ways. I'm using bzr-1.9, python 2.5.2, on Ubuntu-8.xx. Does anyone have any ideas ? Thanks, - Julian -- http://op59.net/ From castironpi at gmail.com Sun Dec 7 06:16:56 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 7 Dec 2008 03:16:56 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> Message-ID: On Dec 6, 2:29?pm, "Guido van Rossum" wrote: snip > > So, assuming I now wish to propose a corrective PEP to remedy this > > situation for Python 3.1 and beyond, what is the best way to get started > > on such a proposal? > > Don't bother writing a PEP to make 'as' available as an attribute > again. It has no chance of being accepted. Instead, think of a > different word you could use. You could use the Latin 'qua' or the Spanish 'como', for example. qua: -dictionary.com ?adverb as; as being; in the character or capacity of: The work of art qua art can be judged by aesthetic criteria only. From rhodri at wildebst.demon.co.uk Tue Dec 23 16:38:34 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Tue, 23 Dec 2008 21:38:34 -0000 Subject: iterating initalizations In-Reply-To: References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> <20081223092504.aaf25192.darcy@druid.net> Message-ID: On Tue, 23 Dec 2008 15:39:52 -0000, Aaron Stepp wrote: > import random > from rtcmix import * > from chimes_source import * # Chime.play() > from rhythmblock import * # rhythmBlock.rhythmTwist() and > rhythmBlock.printStuff() > from pitchblock import * # pitchBlock.pitchTwist() and > pitchBlock.printStuff() > from lenEval import * #greaterThan.sovler() > > indexrand = random.Random() > indexrand.seed(2) > > chime = Chime() > notes = pitchBlock() > rhythm = rhythmBlock() > solve = greaterThan() > > class arrayBlock: > > def __init__(self, theTempo, start): > self.__A = [] > self.__B = [] > self.__start = start > self.__tempo = theTempo > > def player(self, length, tempo, octave, pan, seed): > > tempo = (120, self.__tempo) > > for a in range(length): > > one = indexrand.randint(0, 3) > > two = indexrand.randint(0, 7) > > self.__A = self.__A + notes.pitchTwist(one , two) > > for b in range(length): > > one = indexrand.randint(0, 3) > > two = indexrand.randint(0, 7) > > self.__B = self.__B + rhythm.rhythmTwist(one , two) > > lenA = len(self.__A) > lenB = len(self.__B) > > var = solve.solver(lenA, lenB) > > > for c in range(var): > > print self.__A[c] > > self.__start = self.__start + tb(self.__B[var]) > > chime.play(self.__start, self.__A[var], octave, pan, seed) > > This almost does exactly what I want, and is far cleaner than my > previous attempts. > > The only problem is that now all my arguments are being passed as zeros! Which "all" your arguments? There are an awful lot there; what *exactly* do you mean? > I assume this has to do with WHEN I'm referencing self.__A and self.__B? If you mean __A and __B are full of zeroes, then you should suspect your notes.pitchTwist() and rhythm.rhythmTwist() methods of returning zeroes. -- Rhodri James *-* Wildebeeste Herder to the Masses From joe at strout.net Thu Dec 11 10:43:00 2008 From: joe at strout.net (Joe Strout) Date: Thu, 11 Dec 2008 08:43:00 -0700 Subject: Call by reference in SWIG? In-Reply-To: References: Message-ID: <9D295CD0-2DA3-4572-A2A5-57301D67BEED@strout.net> On Dec 10, 2008, at 10:19 PM, Nok wrote: > I can't get call-by-reference functions to work in SWIG... Python doesn't have any call-by-reference support at all [1], so I'm not surprised that a straight translation of the call-by-reference C function doesn't work. Unfortunately I don't know enough about SWIG to suggest a work- around. Hopefully someone more versed in SWIG will have a bright idea. If you don't find anything in the Python space, you might try poking around in Java references, since Java has the same call semantics as Python. Best wishes, - Joe [1] http://www.strout.net/info/coding/valref/ From nopsidy at gmail.com Sat Dec 27 23:57:33 2008 From: nopsidy at gmail.com (RP) Date: Sat, 27 Dec 2008 22:57:33 -0600 Subject: how to make a class to get all forms and input fields from webpage In-Reply-To: References: Message-ID: Thank you. On Sat, Dec 27, 2008 at 8:39 PM, Gabriel Genellina wrote: > En Sat, 27 Dec 2008 21:54:02 -0200, alex goretoy < > aleksandr.goretoy at gmail.com> escribi?: > > How do I make a class for retrieving all forms and input fields on a web >> page. Meaning, form name, form url,all input fields, >> text,textarea,select,etc...I have something currently and it kinda >> > > I'd use BeautifulSoup: http://pypi.python.org/pypi/BeautifulSoup/ > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -- ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Fri Dec 12 16:06:41 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 12 Dec 2008 21:06:41 +0000 (UTC) Subject: Testing against different versions of Python References: <2678157f0812121142y2afcf3bey254dd2b74f61e423@mail.gmail.com> Message-ID: On Fri, 12 Dec 2008 14:42:24 -0500, mercado wrote: > What is the best way to go about testing against different versions of > Python? For example, I have 2.5.2 installed on my machine (Ubuntu Hardy > 8.04), and I want to test a script against 2.5.2 and 2.5.1 (and possibly > other versions as well). definitely you need to have the test code first (unittest or doctest) then it's just a matter of running a shell script (or python script with subprocess) to check if the code generated any errors in any version. The problem might be how to install multiple sub-minor version of python. I often see a machine with multiple minor versions, but have no idea whether multiple sub-minor versions could coexists. From gnewsg at gmail.com Thu Dec 11 13:53:03 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 11 Dec 2008 10:53:03 -0800 (PST) Subject: How to know when it's possible to bind a socket on an unprivileged port? References: <799ba4ea-0ef8-499b-909e-507bf4abe4aa@z28g2000prd.googlegroups.com> Message-ID: On 11 Dic, 19:09, "Giampaolo Rodola'" wrote: > Hi, > For a purpose of testing I need a function which could tell me whether > it is possible to bind sockets on privileged ports or not. > I wrote down this simple function. It seems reasonably working to me > but I'd like to hear your opinion first. > > Thanks in advance. > > import socket, errno > > def bind_on_privileged_ports(port=21): > ? ? """Return True if it is possible to bind sockets on privileged > ? ? ports (< 1024).""" > ? ? try: > ? ? ? ? s = socket.socket() > ? ? ? ? s.bind(("", port)) > ? ? except socket.error, err: > ? ? ? ? if err[0] == errno.EACCES: > ? ? ? ? ? ? return False > ? ? s.close() > ? ? return True > Just to clarify: I don't really care *which* port to use for binding the socket. I just need to try to bind a socket on a free random privileged port and return True if that has been possible. --- Giampaolo http://code.google.com/p/pyftpdlib/ From luismgz at gmail.com Mon Dec 22 15:03:54 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Mon, 22 Dec 2008 12:03:54 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> <6r6hpfFfb643U3@mid.uni-berlin.de> <494E6FDA.4070401@mrabarnett.plus.com> <4585c27d-d7a9-480f-991c-a869161be55c@g38g2000yqn.googlegroups.com> <3392a51b-d3fd-4986-9c59-fecccc7272da@p2g2000prn.googlegroups.com> <6aad831b-80ce-40df-9b6e-571b1e822795@s1g2000prg.googlegroups.com> Message-ID: <1c7c21bd-62db-4397-a3cf-ed58431fb192@q26g2000prq.googlegroups.com> On Dec 22, 3:42?pm, cm_gui wrote: > Python is slow. Haven't you said that already? Well, you did it so many times that you convinced me... I'll tell the Google folks that they are a bunch of ignorant fools for choosing python. That's why their business is doing that bad. They will surely go to hell. This Google search engine and that silly site "youtube"... they won't work. THEY ARE SLOW! From castironpi at gmail.com Mon Dec 8 16:22:14 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 8 Dec 2008 13:22:14 -0800 (PST) Subject: Guido's new method definition idea References: <014a071a$0$20670$c3e8da3@news.astraweb.com> <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> Message-ID: On Dec 8, 2:55?pm, Arnaud Delobelle wrote: > anthony.to... at gmail.com writes: > > class C: > > ? ? def createfunc(self): > > ? ? ? ? def self.func(arg): > > ? ? ? ? ? ? return arg + 1 > > > Or, after the class definition is done, to extend it dynamically: > > > def C.method(self, arg): > > ? ? self.value = arg > > > ...which would be the equivalent of the following: > > > def method(self, arg): > > ? ? self.value = arg > > C.method = method > > What about the following then? > > functions = {} > > def functions['square'](x): > ? ? return x*x > > def functions['cube'](x): > ? ? return x**3 > > -- > Arnaud I agree that it's an extension (extrapolation) of the 'def self.meth' notation. For 'func_name', would you use the quoted string? Would you allow arbitrary expressions for the string, and the dictionary to add to? For example: def dict_val( )[ "name%i"% int_val( ) ]( self, arg, arg, arg ): ... It's not much worse than: (Unproduced) def anon( self, arg, arg, arg ): ... dict_val( )[ "name%i"% int_val( ) ]= anon #or if you really want the target before the def: @assign( dict_val( ), "name%i"% int_val( ) ) def _( self, arg, arg, arg ): ... And the latter are already both legal. But there have been PEPs accepted before that abbreviate 2 lines into 1. From inq1ltd at inqvista.com Thu Dec 11 16:16:13 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Thu, 11 Dec 2008 16:16:13 -0500 Subject: Problems running on HP Intel duo core machine In-Reply-To: <200812111458.16157.inq1ltd@inqvista.com> References: <200809221443.25765.inq1ltd@inqvista.com> <200812111458.16157.inq1ltd@inqvista.com> Message-ID: <200812111616.14104.inq1ltd@inqvista.com> Aaron, The TraceBack is : TraceBack: File win32ui.pyc, line 12, in File win32ui.pyc Line 10, in _load ImportError: DLL Load Failed: The specified module could not be found. On Thursday 11 December 2008 14:58, jim-on-linux wrote: > py help, > > I produced a program that runs on windows. > One client is using an HP machine with an Intel cpu > E2200 @ 2.2ghz., and with .99 G ram. > The machine is using Win XP Pro 32 bit OS with > service pack 2 > > I ran Dependency Walker and everything is OK. > > I used py2exe to build the exe file with bundle > files:1 and also 3, with the same traceback results. > > I created a test print module that imports both > win32api and win32ui modules and its only job is to > print a page of text. > > The first module that is imported is win32api. > line 8 of that module adds to the path the module > named 'win32api.pyd'. > The import is is completed without error. > > The next module that is imported is win32ui. > line 8 of that module adds to the path a module > named 'win32ui.pyd'. > The search for the win32ui.pyd module seems to be > the cause of the problem. > Traceback: > ImportError: Dll load failed: The specified module > could not be found. > > Both modules 'win32api.pyd' and win32ui.pyd are in > the same directory. > > Below is a copy of the win32ui.py module. The only > difference between this and win32api.py module is > the name that is installed when creating the path. > > def __load(): > import imp, os, sys > try: > dirname = > os.path.dirname(__loader__.archive) except > NameError: > dirname = sys.prefix > path = os.path.join(dirname, 'win32ui.pyd') > #print "py2exe extension module", __name__, > "->", path > mod = imp.load_dynamic(__name__, path) > ## mod.frozen = 1 > __load() > del __load > > The only difference I can find is that this program > works fine on every machine that it is tried on > except the HP duo core machine, with Intel E2200 > cpu. Somehow the path is affected? > > I've tried all of the suggestions and checked a lot > of things but I'm not there yet, Any suggestions > would be helpful. > > > jim-on-linux > > > > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From sjmachin at lexicon.net Mon Dec 1 18:40:37 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 1 Dec 2008 15:40:37 -0800 (PST) Subject: newbie question: parse a variable inside an RE? References: <6pj4svF832i3U1@mid.uni-berlin.de> Message-ID: On Dec 2, 8:56?am, "Diez B. Roggisch" wrote: > joemacbusin... at gmail.com schrieb: > > > Hi All, > > > How do I parse a variable inside an RE? > > What is the re.search() syntax when your > > search string is a variable? > > It's easy to parse hardcoded RE's but not > > if you use a variable. > > Both are exactly equal in difficulty. > > > > > > > Here is my code, input and runtime: > > > $ cat test45.py > > #!/usr/bin/python > > > import re > > > resp = raw_input('Selection: ') > > newresp = resp.strip() > > print "you chose ", newresp > > > fname = open('test44.in') > > for I in fname: > > # ? ?if re.search('^newresp', "%s"%(I)): ? ? # returns nothing > > # ? ?if re.search(^newresp, "%s"%(I)): ? ? ? # syntax error > > ? ? if re.search("^newresp", "%s"%(I)): ? ? ?# returns nothing > > ? ? ? ? print I, > > How should python know that you want the newresp being expanded? And not > that you want to search for the word "newresp"? > > You need to use the *variable* newresp: > > if re.search(newresp, I): ... > > If you want to alter it to have a "^" prepended before you use it, you > need to do so: > > newresp = "^" + newresp > > And as show above, > > "%s" % I > > is nothing but I - no need for the string-interpolation. In fact what the OP is trying to do amounts to a convoluted version of I.startswith(newresp) which probably isn't his real requirement anyway :-( From febaen at gmail.com Sat Dec 13 10:21:59 2008 From: febaen at gmail.com (feba) Date: Sat, 13 Dec 2008 07:21:59 -0800 (PST) Subject: Need help improving number guessing game References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> Message-ID: <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> #!/usr/bin/python #Py3k, UTF-8 import random def startup(): print("WELCOME TO THE SUPER NUMBER GUESSING GAME!") global pnum, play, player, p1sc, p2sc pnum = int(input("1 OR 2 PLAYERS?\n> ")) play = True player = "P1" #P1 goes first p1sc = 0 #Number of times... p2sc = 0 #player guessed before opponent def setup(): global target, guess, a, b a = 1 b = 99 target = random.randint(a, b) guess = 0 #Won't fall between 1 and 99 def playerswap(): global player if player == "P1": player = "P2" else: player = "P1" def guessing(): global guess, player, target, play, pnum, p1sc, p2sc, a, b guess = int(input("[%s-%s]%s>> " % (a, b, player))) #keeps the user aware of min/max if guess == target: if pnum == 1: print("CONGRATULATIONS!" ) else: if player == "P1": p1sc += 1 else: p2sc += 1 print("CONGRATULATIONS %s! SCORE -- P1:%s P2:%s" %(player, p1sc, p2sc)) playover = input("PLAY AGAIN? Y/N: ") if playover.strip().lower() == "y": play = True setup() else: play = False elif guess > b: print("NUMBER MUST BE IN RANGE") elif guess <= a: print("NUMBER MUST BE IN RANGE") elif guess > target: print("TOO HIGH") b = guess else: print("TOO LOW") a = guess if pnum ==2: playerswap() startup() setup() while play is True: guessing() This is what I have so far. better? worse? I'm guessing a mix of the two. It took me a lot longer to get working, but I think it works better. I also added a bit that tells you if you go higher or lower than an already specified too high/low markers; although it doesn't make you repeat that turn. I'm not sure if all those 'globals' are bad, but they don't seem like they're something that should be good. Functionally, it seems to work just fine. From rt8396 at gmail.com Sat Dec 20 21:23:00 2008 From: rt8396 at gmail.com (r) Date: Sat, 20 Dec 2008 18:23:00 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <015d9ca5$0$20656$c3e8da3@news.astraweb.com> Message-ID: <60b419d3-4cbc-4bba-af79-a6d6146ac472@e6g2000vbe.googlegroups.com> Answering a question with a question, that leaves me with a question of my own?? > Instead of just whinging, how about making a suggestion to fix it? Go on, > sit down for an hour or ten and try to work out how a BINARY OPERATOR > like % (that means it can only take TWO arguments) can deal with an > arbitrary number of arguments, *without* having any special cases. Instead of being a blind fanboy and chastising everyone who dares to question pydev, Guido, or YOU... why don't you offer a good rebuttal? If i did not give a rats behind about Python i would not be here arguing with you. I would give up and "require" my packages ;). I prefer to import I believe Python has the best chance of surviving and becoming the king of high level languages, IF we don't muck it up! From stepp.aaron at gmail.com Mon Dec 22 22:32:17 2008 From: stepp.aaron at gmail.com (Aaron Stepp) Date: Mon, 22 Dec 2008 22:32:17 -0500 Subject: iterating initalizations In-Reply-To: <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> Message-ID: On Dec 22, 2008, at 10:15 PM, r wrote: > I can't check you code because i don't have these modules but here is > the code with proper indention > > import random > from rtcmix import * > from chimes_source import * > from rhythmblock import * > from pitchblock import * > indexrand = random.Random() > indexrand.seed(2) > rhythm = rhythmBlock() > pitch = pitchBlock() > > class pitchAndRhythm: > def __init__(self): > self.__abet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' > def listCreate(self, num): > if num > 25: > print "Oops. This won't work" > else: > for a in range(num): > b = indexrand.randint(0, 3) > c = indexrand.randint(0, 7) > index = self.__abet[a] > index = [ ] > index = index.append(rhythm.rhythmTwist(b, c)) > > take 2: notice the "(" and ")" around the arg to __init__ Thanks for the help so far, I think I'm starting to get a hang of the syntax. I think I need to state my goal more clearly. Instead of writing a long list of initializations like so: A = [ ] B = [ ] ... Y = [ ] Z = [ ] I'd like to save space by more elegantly turning this into a loop. If I need to just write it out, I guess that's ok... but it would be much cleaner. I'm a composer, not a programmer, so some of this is quite above me. I usually ask as a last resort, but I've been through the tutorial and didn't find this. I've got a couple python books, but I'd like to finish this piece sooner than later. Thanks! AS From gagsl-py2 at yahoo.com.ar Wed Dec 31 13:57:03 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 31 Dec 2008 16:57:03 -0200 Subject: MemoryError when list append... plz help References: <016b25a5$0$6988$c3e8da3@news.astraweb.com> Message-ID: En Wed, 31 Dec 2008 06:34:48 -0200, Steven D'Aprano escribi?: > Each time you are appending to the list, you append a tuple: > > ((i, j), sim) > > where sim is a float and i and j are ints. How much memory does each of > those take? > >>>> sys.getsizeof( ((0, 1), 1.1) ) > 32 (On Windows, 32 bits, I get 36) > So each entry requires 32 bytes. 60 million times 32 bytes = almost 2GB > alone. Plus the list itself will require (approximately) between 230MB > and 460MB just for the pointers. That was just the size of the "outer" tuple; you have to add the size of each element too. First one is another 2-item tuple (36 bytes too) plus its elements (two integers, 12 bytes each). Second element is a float and takes 16 bytes. Total: 112 bytes per item; the final size may be a bit smaller because some objects may be shared (e.g. small integers) -- Gabriel Genellina From R.Brodie at rl.ac.uk Wed Dec 17 12:17:02 2008 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Wed, 17 Dec 2008 17:17:02 -0000 Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> Message-ID: "walterbyrd" wrote in message news:518b9dd9-69c5-4d5b-bd5f-ad567be6249b at b38g2000prf.googlegroups.com... > However in the methods are within a class, the scoping seems to work > differently. Not really, self is a formal parameter to the function. It would be a strange language where a function's own arguments weren't in scope. > def b(self): > print self.x Try changing it to: def b(somethingotherthanself): print self.x From steve at REMOVE-THIS-cybersource.com.au Sun Dec 14 20:48:43 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Dec 2008 01:48:43 GMT Subject: [OT] stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> Message-ID: <0155aef3$0$6988$c3e8da3@news.astraweb.com> On Sun, 14 Dec 2008 21:42:33 +0000, Lie Ryan wrote: > I'm sure someday, there will be a student who comes to class late and > sees this on the board: "Design a comparison sorting algorithm that has > better than O(n * log n) lower bound complexity." The unsuspecting > student copied it, thinking it's a homework. He crunched to the problem, > going to various meditations and yoga classes before finding a way that > works just before deadline, handing out the work a bit late. Six weeks > later, his professor called and said: "You know what you just did? > You've just found a problem that was supposed to be an example of > unsolvable problem." > > It has happened before, why not again? > http://www.snopes.com/college/homework/unsolvable.asp Because as you described it, it *hasn't* happened before. There is the world of difference between an unsolvABLE problem and one that is unsolvED. All the positive thinking in the world won't help you: * make a four-sided triangle; * write down a completely accurate rational expansion for pi or the square-root of 2; * split a magnet into two individual poles; * find an integer solution to 3*n = 7; * solve the Halting Problem; * fit n items into n-1 pigeonholes without putting two items in the one pigeonhole; * create a compression algorithm that will compress random data; * or design a comparison sort which does fewer than O(n*log n) two-way comparisons in the worst case, or fewer than O(n) comparisons in the best case. Some things really don't have a solution, no matter how much power of positive thinking you apply to it. -- Steven From skip at pobox.com Mon Dec 8 19:59:52 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 8 Dec 2008 18:59:52 -0600 Subject: how to add command line flags to distutils setup script? Message-ID: <18749.49928.182089.131317@montanaro-dyndns-org.local> Suppose I have a setup.py script which imports distutils.core.setup. Is there some way to, for example, add a command line flag to the build command so that I can run it like python setup.py build --frob=True ? I see that the setup function takes an options parameter but the distutils.core.setup doc says little other than that it is a string and "default options for the setup script". There is also a script_args parameter, but the docs are similarly mum about what exactly it's used for. A posting by Greg Ward announcing it in Aug 2000 says script_args is a sub for sys.argv[1:]. Pointers to other documentation or tutorials on the topic cheerfully appreciated. Thanks, -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From torriem at gmail.com Fri Dec 19 12:27:27 2008 From: torriem at gmail.com (Michael Torrie) Date: Fri, 19 Dec 2008 10:27:27 -0700 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <494BD97F.5080205@gmail.com> walterbyrd wrote: > On Dec 19, 9:13 am, "Giampaolo Rodola'" wrote: >> You can use the old 2.x syntax also in Python 3.x: > > Yeah, but it's deprecated, and - as I understand it - may be removed > completely in future versions. Also, in the future, if you are working > with code from another developer, it's likely that developer will use > the new format. I suppose you can use both - but what an awful mess > that would be. > > It seems to me that 3.0 is changing a lot of non-problems. And it's > going to be slower to boot. How is this? With projects like PyPy eventually enabling the JIT'ing of python3 code, I don't see how this is going to be "slower." If anything we have a python that can be made to run faster than ever before. Please qualify your remarks. Are you a Python core developer? From kyosohma at gmail.com Mon Dec 8 12:19:15 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 8 Dec 2008 09:19:15 -0800 (PST) Subject: Calling C# COM (.NET) from python References: Message-ID: <5788ade5-3334-47a2-8289-03dac8b193bc@41g2000yqf.googlegroups.com> On Dec 8, 10:53?am, Andrew Falanga wrote: > Hi, > > I've never programmed in python and only have a small understanding of > what is wrapped up in the terms COM and .NET. ?Is there a way of using > python to get a hold of objects written in C# as COM objects using > python? ?I'm looking for ways to avoid VBScript (which, after a couple > of weeks, I've determined to be horrid). ?That is, is there a way of > getting at COM objects in python that's similar to doing a > CreateObject call in VBScript (http://msdn.microsoft.com/en-us/library/ > dcw63t7z.aspx)? > > Thanks, > Andy You're probably looking for the PyWin32 package (AKA: Python for Windows extensions). It's an external package for Python created mainly by Mark Hammond. You can find it here: http://sourceforge.net/projects/pywin32/ It's a loose wrapper to the win32 bindings. It has a win32com module in it. You can usually take some VB type code and tweak it slightly to work with Python. There's some docs here: http://docs.activestate.com/activepython/2.4/pywin32/win32_modules.html You may also be able to use ctypes. Regardless, the PyWin32 package has a great mailing list with helpful people that I highly recommend: http://mail.python.org/mailman/listinfo/python-win32 Other than that, you have the option of using IronPython which can actually import .NET modules itself. I've messed with it a little, but I'm not fluent enough in .NET to be able to use a lot of its capabilities. Regardless, you should read up on it as it offers lots of interesting capabilities: http://www.codeplex.com/IronPython Mike From __peter__ at web.de Mon Dec 1 15:59:17 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 01 Dec 2008 21:59:17 +0100 Subject: Chmod to a group only References: <83e430f3-0c4c-4aae-84e3-7a8bb6dc1b74@t11g2000yqg.googlegroups.com> Message-ID: Kless wrote: > On 1 dic, 18:17, Kless wrote: >> How to chmod a file to: o-rwx ? (to change only the others mode) >> >> os.chmod(fname, ) >> >> I was reading this [1], but the truth is that anything as 'S_IRUSR' >> doesn't help enought. >> >> [1]http://www.python.org/doc/2.5.2/lib/os-file-dir.html > > I have tried: > > mode = os.stat(fname).st_mode > os.chmod(fname, mode | stat.S_IRWXO) => Changes to o+rwx How did the result of the above differ from what you want? The way I read your original post something like the above would have been my answer... Peter From rt8396 at gmail.com Sat Dec 6 11:52:53 2008 From: rt8396 at gmail.com (r) Date: Sat, 6 Dec 2008 08:52:53 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> <00ab327a-c3fc-4b15-a084-4f8c6aed6a8e@o2g2000yqd.googlegroups.com> <8119ab7e-09f1-44de-bdbc-8fdff969d9e4@33g2000yqm.googlegroups.com> <36056737-3c78-499a-a81d-f6241e904460@t11g2000yqg.googlegroups.com> Message-ID: [Lie] Sketchup's target users is not power users but those who need quick sketches, so scripting isn't an extremely important feature in Sketchup.[/Lie] Your Wrong, SketchUp PRO is marketed at ACAD users and other high profile CAD and CAM applications. SketchUp models can be exported to ACAD and ACAD models can be imported to SketckUp. Anyone who would say scripting is not important to a modeler has never spent much time modeling. Scripting is of upmost importance to the usefulness of SketchUP(or any CAD/CAM app), without it more advanced modeler types would not be interested. As far as Google earth goes...that is more a marketing ploy, and that Google is a cool company, rather than the primary use for SketchUP...and it has worked well! Your Right, creating a Python extension and getting people interested, is the gateway to convincing SketchUp DEV to include Python alongside Ruby.(and even if they don't it won't matter once the wrapping is there). I hang out a lot in the SketchUp Ruby Group, and a lots of people are turned off by Ruby. I think Python could help them get going. This is the reason for my crusade. Not just for me...but because there is a real void python can fill in SketchUp. Once there is a python wrapping of Ruby API I will take over, writing tutorials, writing example code, fielding Python related questions...This is my commitment to this project. I AM willing to work extremely hard to make this happen. If just ONE other person would get on board this will happen. No...I DO NOT know how to wrap the Ruby API myself...but once the Python wrapping is there i will take over and bring this to life. From that point on, i will not need any help. I will maintain the code, And i will be happy to let this person(s) take ALL the credit for bringing Python to SketchUp...I do not want the credit. From arnodel at googlemail.com Wed Dec 17 05:46:42 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 17 Dec 2008 10:46:42 +0000 Subject: Need help improving number guessing game References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> <01564c98$0$21844$c3e8da3@news.astraweb.com> <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> <4946df78$0$19771$426a74cc@news.free.fr> <1f33580b-84f9-4059-a0f0-b6a8d71325af@b38g2000prf.googlegroups.com> <4947742c$0$25951$426a34cc@news.free.fr> Message-ID: "D'Arcy J.M. Cain" writes: > On Tue, 16 Dec 2008 13:59:24 -0800 > Scott David Daniels wrote: >>> > def yesno(s): >> > s = s.strip().lower() >> > if not s in ("y", "n"): There was a thread about "is not" recently. Python also allows "not in". if s not in ("y", "n"): > You could also do this to be a little more user friendly: > if not (s and s[0] in ("y", "n")): Or: if s[:1] not in ("y", n"): -- Arnaud From tino at wildenhain.de Mon Dec 22 01:52:28 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 22 Dec 2008 07:52:28 +0100 Subject: Are Django/Turbogears too specific? In-Reply-To: <2B198A4F-5911-456D-A45B-E073DB121446@semanchuk.com> References: <494eb16e$0$22710$426a74cc@news.free.fr> <2B198A4F-5911-456D-A45B-E073DB121446@semanchuk.com> Message-ID: <494F392C.5060201@wildenhain.de> Philip Semanchuk wrote: ... > > I prefer Mako over the other template languages I've seen. From what I can tell Mako is nearly identical to all other template languages you might have seen (e.g. PHP style tags). Thats why I personally would not consider it. Its just much of a hassle to mix code and design this way. I prefer TAL (template attribute language, ZPT) [1] much over the other attempts I've seen ( and I've seen a lot) Cheers Tino [1] http://en.wikipedia.org/wiki/Template_Attribute_Language -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From hjtoi-better-remove-when_replying at comcast.net Wed Dec 10 14:16:16 2008 From: hjtoi-better-remove-when_replying at comcast.net (Heikki Toivonen) Date: Wed, 10 Dec 2008 11:16:16 -0800 Subject: pexpect and inconsistent exit codes Message-ID: I don't seem to be able to figure out how to get the exit values of commands executed with pexpect reliably. Here's first with regular shell: heikki at ubuntu:~$ true; echo $? 0 Let's try with pexpect. Below is the program: ---CLIP--- import sys, pexpect cmd = "true" print 'cmd=', cmd child = pexpect.spawn(cmd, logfile=sys.stdout) child.close() print 'child exitstatus=', child.exitstatus print 'child signalstatus=', child.signalstatus print 'child status=', child.status ---CLIP--- The output: (fabexp)heikki at ubuntu:~/python_virtualenvs/fabexp$ python dep.py cmd= true child exitstatus= 1 child signalstatus= None child status= 256 (fabexp)heikki at ubuntu:~/python_virtualenvs/fabexp$ python dep.py cmd= true child exitstatus= 0 child signalstatus= None child status= 0 (fabexp)heikki at ubuntu:~/python_virtualenvs/fabexp$ python dep.py cmd= true child exitstatus= None child signalstatus= 1 child status= 1 I have tried various other commands, and I just can't seem to be able to get reliable exit codes from commands I execute. Any ideas what is going on? -- Heikki Toivonen - http://heikkitoivonen.net From bkamrani at gmail.com Tue Dec 2 06:41:29 2008 From: bkamrani at gmail.com (bkamrani at gmail.com) Date: Tue, 2 Dec 2008 03:41:29 -0800 (PST) Subject: performance question: dictionary or list, float or string? Message-ID: Hi Python gurus! I'm going to read in an Ascii file containing float numbers in rows and columns (say 10 columns 500000 rows) for further numerical process. Which format is best to save them in, eg, dictionary, list, or numpy array when it comes to performance? Will it be beneficial to convert all strings to float directly after reading or it doesn't matter to save them as string and thereafter when it comes to calculation convert them to floats? Thank you! /Ben From pavlovevidence at gmail.com Sat Dec 6 16:01:53 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 6 Dec 2008 13:01:53 -0800 (PST) Subject: Learning Python now coming from Perl References: Message-ID: On Dec 6, 12:30?pm, Roy Smith wrote: > In article , a... at pythoncraft.com (Aahz) > wrote: > > > In article , > > Bertilo Wennergren ? wrote: > > > >I don't suppose there is any introductory material out there that is > > >based on Python 3000 and that is also geared at people with a Perl > > >background? Too early for that I guess.. > > > Honestly, the differences between 2.x and 3.0 are small enough that it > > doesn't much matter, as long as you're not the kind of person who gets > > put off by little problems. ?Because so much material is for 2.x, you > > may be better off just learning 2.x first and then moving to 3.x. > > I'm not sure I agree. ?If you're starting out, you might as well learn the > new stuff. ?Then there's no need to unlearn the old way. One disadvantage of learning Python 3 first is the availability of third-party libraries (especially extension libraries), most of which will not be updated for Python 3.x for quite a while. Also, I don't think it's really advisable to be completely ignorant of the 2.x difference even if one intends to start with 3.0. There is a lot of code and material out there for 2.x, and until these start to be widely available for 3.x, people will sometimes have to make do with the 2.x stuff. Carl Banks From lists at cheimes.de Tue Dec 16 13:12:08 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 16 Dec 2008 19:12:08 +0100 Subject: Python Dictionary Algorithm Question In-Reply-To: <3ca641b40812160951h3a13e69am291afb02965451a7@mail.gmail.com> References: <3ca641b40812160951h3a13e69am291afb02965451a7@mail.gmail.com> Message-ID: Brigette Hodson schrieb: > Hello! I am in a beginning algorithms class this semester and I am working > on a presentation. I want to discuss in some detail the algorithm python > uses to determine the hash function for python dictionaries. Does anyone > know what this algorithm is? Or where I can go to find information on it? Python's dict implementation doesn't have its own hashing algorithm. It completely relies upon the __hash__() function and the __eq__() comparison function of the objects that are used as keys. The source repository contains a document with some insights. Make your you read dictnotes.txt and the cmments in dictobject.c http://svn.python.org/view/python/branches/release25-maint/Objects/ Christian From stef.mientki at gmail.com Mon Dec 1 16:22:53 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 01 Dec 2008 22:22:53 +0100 Subject: Why doesn't doc has predifined name and location ? Message-ID: <493455AD.4040306@gmail.com> hello, I'm very satisfied about the great standardization of doc strings in python. Now in contrast to that, the general documentation of libraries, either in plain text, html, pdf, chm, ... doesn't have a standarized name nor location. Why is that ? thanks, Stef Mientki From castironpi at gmail.com Thu Dec 18 05:35:58 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 18 Dec 2008 02:35:58 -0800 (PST) Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> Message-ID: <51866e70-8a6e-4338-94bd-59913990e342@k36g2000pri.googlegroups.com> On Dec 17, 7:16?pm, "Gabriel Genellina" wrote: > En Wed, 17 Dec 2008 22:46:32 -0200, Aaron Brady ? > escribi?: > > > > > On Dec 17, 5:05?pm, "Gabriel Genellina" > > wrote: > >> En Wed, 17 Dec 2008 12:21:38 -0200, Jeremy Sanders ? > >> escribi?: > > >> > It would be nice if Python created pipes that are properly ? > >> inheritable by > >> > default by child processes, as they're mostly used for IPC. > > >> I'd say it is a bug in os.pipe implementation; they should be ? > >> inheritable ? > >> by default, as in posix (after all, the code is in "posixmodule.c"). > > > The code looks like this: > > > ? ?ok = CreatePipe(&read, &write, NULL, 0); > > ? ?Py_END_ALLOW_THREADS > > ? ?if (!ok) > > ? ? ? ? ? ?return win32_error("CreatePipe", NULL); > > ? ?read_fd = _open_osfhandle((Py_intptr_t)read, 0); > > ? ?write_fd = _open_osfhandle((Py_intptr_t)write, 1); > > > 'If lpPipeAttributes is NULL, the handle cannot be inherited.' ?You > > could populate a 'SECURITY_ATTRIBUTES' structure, or call > > DuplicateHandle on both of them. > > > A patch would look like this: > > > SECURITY_ATTRIBUTES sattribs; > > sattribs.nLength = sizeof(sattribs); > > sattribs.lpSecurityDescriptor = NULL; > > sattribs.bInheritHandle = TRUE; > > ok = CreatePipe(&read, &write, &sattribs, 0); > > Yes, that's exactly how os.popen does it (in posixmodule.c) > > > This still doesn't answer whether the file descriptor return by > > '_open_osfhandle' can be inherited too. > > It doesn't matter. The OS only cares about file handles, not C RTL ? > structures. > > -- > Gabriel Genellina Ah, I see. Was it an executive decision about what is Pythonic, or just a bug? Do you think the patch would be accepted? I probably ought to mimic a small Python embedding to see if it needs anything else. From gagsl-py2 at yahoo.com.ar Sat Dec 27 15:03:13 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 27 Dec 2008 18:03:13 -0200 Subject: ctypes & strings References: <334452.47084.qm@web30003.mail.mud.yahoo.com> <000f01c96822$5c300f00$0d00a8c0@hendrik> Message-ID: En Sat, 27 Dec 2008 10:54:32 -0200, Hendrik van Rooyen escribi?: > The c routine will actually break Python's normal string > immmutability and give you back a changed ins. ...so don't do that! If you require a mutable string to pass to C functions, use ctypes.create_string_buffer() > It is in general not a good idea to change the passed string > like I am doing - but you wanted to know how > to pass a python string, and the outs example should get > you going - a string is an array of characters in c... Hmmm, I don't think posting a potentially harmful example is actually a good idea... -- Gabriel Genellina From lewis.sarah93 at yahoo.com Fri Dec 5 00:11:00 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 21:11:00 -0800 (PST) Subject: Reduce Debt Message-ID: Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com Earn From bdesth.quelquechose at free.quelquepart.fr Sun Dec 14 11:23:55 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 14 Dec 2008 17:23:55 +0100 Subject: execution time In-Reply-To: References: Message-ID: <494540d1$0$1127$426a74cc@news.free.fr> David Hl??ik a ?crit : > Hi guys, > > #! /usr/bin/python > > import random > import bucket2 > > data = [ random.randint(1,25) for i in range(5)] > print "random data : %s" % data > print "result: %s" %bucket2.sort(data) > > How to write a test script which will outputs execution time for > bucket2.sort(data) ? http://docs.python.org/library/timeit.html HTH From sln at netherlands.com Tue Dec 9 21:46:02 2008 From: sln at netherlands.com (sln at netherlands.com) Date: Wed, 10 Dec 2008 02:46:02 GMT Subject: Mathematica 7 compares to other languages References: <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> <0201522a-b15a-4401-a208-5d9af70bdd74@w24g2000prd.googlegroups.com> <8947211d-2ee8-403a-8c8a-c7599aea5f80@k24g2000pri.googlegroups.com> <9f86f78c-776e-4793-b931-67dadc0e24f1@i24g2000prf.googlegroups.com> Message-ID: On Tue, 9 Dec 2008 15:01:11 -0800 (PST), Xah Lee wrote: > >On Dec 8, 4:56 pm, Jon Harrop wrote: >> Xah Lee wrote: >> > A moron, wrote: >> > > You failed the challenge that you were given. >> >> > you didn't give me a challenge. >> >> Thomas gave you the challenge: >> >> "What I want in return is you to execute and time Dr. Harrop's original >> code, posting the results to this thread... By Dr. Harrop's original code, >> I specifically mean the code he posted to this thread. I've pasted it below >> for clarity.". >> >> Thomas even quoted my code verbatim to make his requirements totally >> unambiguous. Note the parameters [9, 512, 4] in the last line that he and I >> both gave: >> >> AbsoluteTiming[Export["image.pgm", Graphics at Raster@Main[9, 512, 4]]] >> >> You have not posted timings of that, let alone optimized it. So you failed. > >The first parameter to your Main specifies some kinda recursively >stacked spheres in the rendered image. The second parameter is the >width and height of the pixels in the rendered image. > >I tried to run them but my computer went 100% cpu and after i recall 5 >min its still going. So, i reduced your input. In the end, with >reduced input, it shows my code is 5 times faster (running Mathematica >v4 on OS X 10.4.x with PPC 1.9 GHz), and on the other guy's computer >with Mathematica 6 he says it's twice as fast. > >Given your code's nature, it is reasonably to assume that with your >original input my code would still be faster than yours. You claim it >is not or that it is perhaps just slightly faster? > >It is possible you are right. I don't want to spend the energy to run >your code and my code and possible hog my computer for hours or >perhaps days. As i said, your recursive Intersect is very badly >written Mathematica code. It might even start memory swapping. > >Also, all you did is talking bullshit. Thomas actually is the one took >my challenge to you and gave me $20 to prove my argument to YOU. His >requirement, after the payment, is actually, i quote: > >?Alright, I've sent $20. The only reason I would request a refund is >if you don't do anything. As long as you improve the code as you've >described and post the results, I'll be satisfied. If the improvements >you've described don't result in better performance, that's OK.? > >He haven't posted since nor emailed me. It is reasonable to assume he >is satisfied as far as his payment to me to see my code goes. > >You, kept on babbling. Now you say that the input is different. Fine. >How long does that input actually take on your computer? If days, i'm >sorry i cannot run your toy code on my computer for days. If in few >hours, i can then run the code overnight, and if necessary, give you >another version that will be faster with your given input to shut you >the fuck up. > >However, there's cost to me. What do i get to do your homework? It is >possible, that if i spend the energy and time to do this, then you >again refuse to acknowledge it, or kept on complaining about something >else. > >You see, newsgroup is the bedrock of bullshit. You bullshit, he >bullshits, everybody brags and bullshit because there is no stake. I >want sincerity and responsibility backed up, with for example paypal >deposits. You kept on bullshitting, Thomas gave me $20 and i produced >a code that reasonably demonstrated at least how unprofessional your >Mathematica code was. > >Here's the deal. Pay me $20, then i'll creat a version of Mathematica >code that has the same input as yours. Your input is Main[9, 512, 4], >as i have exposed, your use of interger in the last part for numerical >computation is Mathematica incompetence. You didn't acknowledge even >this. I'll give a version of Mathematica with input Main[9, 512, 4.] >that will run faster than yours. If not, money back guaranteed. Also, >pay me $300, then i can produce a Mathematica version no more than 10 >times slower than your OCaml code, this should be a 70000 times >improvement according to you. Again, money back guarantee. > >If i don't receive $20 or $300, this will be my last post to you in >this thread. You are just a bullshitter. > >O wait... my code with Main[9, 512, 4.] and other numerical changes >already makes your program run faster regardless of the input size. >What a motherfucking bullshit you are. Scratch the $20. The $300 >challenge still stands firm. > > Xah >? http://xahlee.org/ > >? Ad hominem From sjmachin at lexicon.net Sat Dec 20 21:31:48 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 20 Dec 2008 18:31:48 -0800 (PST) Subject: PIL on 3.x? References: <3892784c-ddf4-4451-bcfd-dbc58b9b55f8@e1g2000pra.googlegroups.com> Message-ID: <56c72738-3f92-4c88-9e51-3a592f661b11@r15g2000prd.googlegroups.com> On Dec 21, 12:32?pm, "Daniel Fetchinson" wrote: > >> Does anyone know if PIL will be ported to the 3.x branch? > > > Have you considered e-mail to the author? > > No, I haven't because in my experience open source software authors > prefer to keep discussion of their software on mailing lists, forums, > etc, where others can benefit from the answers too. True, so try a forum where the author has been active within the last week: http://mail.python.org/mailman/listinfo/image-sig From kyosohma at gmail.com Thu Dec 11 13:50:25 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 11 Dec 2008 10:50:25 -0800 (PST) Subject: Python to open command script file References: Message-ID: On Dec 11, 12:04?pm, dave rose wrote: > Hello all > ?I would like to know how to do the following. ?I'd like to have a generic > python program that the user will open a command-script file to do actions. > > So, my python program will get a list of servers, enumerate them within a > checklistbox in wxpython. ?Then I want to open a command-file that will run > against each selected server that will look like this: > > ---------------------------SAMPLE------------------------ > copy abc.xyz from c:\source to u:\target > copy all ? ? from c:\source to u:\target > unload netshld from server1 > -------------------------END SAMPLE---------------------- > > (where I have a class serverfuncs, where I can: > s = serverfuncs() > s.unload('', '') > > Really, I can do all the actions, but I don't know how to trigger them from an > independent script file. > > Thanks! > -Dave I usually use python's included shutil module for copying files and directories. I think that would be a little more cross-platform friendly. However, if you want to execute those commands above, try using the subprocess module or os.system. Mike From fred at gmail.com Wed Dec 24 17:11:22 2008 From: fred at gmail.com (Dan) Date: Wed, 24 Dec 2008 17:11:22 -0500 Subject: Python 3 and my Mac (Leopard) Message-ID: <4952b38d$0$20300$607ed4bc@cv.net> Wanted to learn python, got Mark Summerfield's new book "Programming in Python 3". Having a hard time getting python 3 and IDLE working on my Mac with Leopard. The mac "resources" on the python.org site seem a bit out of date, and don't really mention python 3. Are there any resources out there? Is the python community just not interested in Macs? I've tried googling and the usual search strategies. Any help would be appreciated. DAN From bdesth.quelquechose at free.quelquepart.fr Tue Dec 9 14:39:35 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 09 Dec 2008 20:39:35 +0100 Subject: When (and why) to use del? In-Reply-To: References: Message-ID: <493ed72f$0$7090$426a74cc@news.free.fr> malkarouri a ?crit : (snip) > The del statement doesn't actually free memory. It just removes the > binding from the corresponding namespace. So in your first example, > my_string cannot be used after the deletion. Of course, if the string > referenced by my_string was referenced by some other name then it will > still stay in memory. And even if it wasn't, and as such ends up being garbage-collected, this doesn't mean the allocated memory will go back to the system. (snip) From robert.kern at gmail.com Mon Dec 8 02:13:26 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 08 Dec 2008 01:13:26 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: References: <014c593e$0$20670$c3e8da3@news.astraweb.com> Message-ID: James Stroud wrote: > Robert Kern wrote: >> James Stroud wrote: >>> py> 112 = [1, y] >>> py> y in 112 >>> Traceback (most recent call last): >>> File "", line 1, in >>> ValueError: The truth value of an array with more than one element is... >>> >>> but not >>> >>> py> ll1 = [y,1] >>> py> y in ll1 >>> True >>> >>> It's this discrepancy that seems like a bug, not that a ValueError is >>> raised in the former case, which is perfectly reasonable to me. >> >> Nothing to do with numpy. list.__contains__() checks for identity with >> "is" before it goes to __eq__(). > > ...but only for the first element of the list: > > py> import numpy > py> y = numpy.array([1,2,3]) > py> y > array([1, 2, 3]) > py> y in [1, y] > ------------------------------------------------------------ > Traceback (most recent call last): > File "", line 1, in > : The truth value of an array with more > than one element is ambiguous. Use a.any() or a.all() > py> y is [1, y][1] > True > > I think it skips straight to __eq__ if the element is not the first in > the list. No, it doesn't skip straight to __eq__(). "y is 1" returns False, so (y==1) is checked. When y is a numpy array, this returns an array of bools. list.__contains__() tries to convert this array to a bool and ndarray.__nonzero__() raises the exception. list.__contains__() checks "is" then __eq__() for each element before moving on to the next element. It does not try "is" for all elements, then try __eq__() for all elements. > That no one acknowledges this makes me feel like a conspiracy > is afoot. I don't know what you think I'm not acknowledging. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From manu3d at gmail.com Thu Dec 11 14:04:17 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 11 Dec 2008 11:04:17 -0800 (PST) Subject: Preventing execution of a method References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> <764daeef-bfbe-411a-8521-bb114321e4ac@b38g2000prf.googlegroups.com> <19304f8c-e34f-4aa9-8df2-6a7d3553007a@e1g2000pra.googlegroups.com> <2eed8876-94d2-4304-88a5-eb4a78b4f41d@33g2000yqm.googlegroups.com> Message-ID: <307fe197-1b42-4305-af0e-94b7ebe3ce70@r15g2000prh.googlegroups.com> Thank you all for the confirmation and the suggestions (including the tangential ones: I didn't know one could remove your his own posts!). As much as I really like Python (which I've been using full-time only for the past two months) I really wish it did have regular private/ protected/public methods. I'm building an application that can be extended by the users and I really wish there was a solid way to prevent them from accessing parts of the application that they shouldn't access or to provide read-only access. I.e. right now I'm working on the graphical client which potentially could be rewritten entirely by the users. It is necessary and perfectly reasonable for the client module to access some of the objects to be represented graphically, but those objects shouldn't be modifiable by it. I now wonder, would developing the graphical client as an entirely separate application, communicating with the server via the localhost network interface and messages, solve the problem? Would it keep the objects of the two applications (server/client) entirely separate? Manu From deets at nospam.web.de Mon Dec 8 14:57:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 Dec 2008 20:57:31 +0100 Subject: easy_install of module produces un-importable result In-Reply-To: References: Message-ID: <6q5chbFast45U1@mid.uni-berlin.de> Val schrieb: > I've written my first module, " " and uploaded it as an egg to > PyPI. I can use easy_istall to install my own module, but when I try > to import it I get an ImportError "No module named gpsparser". > > So I've done some research and found that in my site-packages/ > directory gpsparser exists as an egg file, while all the other > packages I've installed exist as an egg directory. > > If this makes any sense, can anyone explain what I've done wrong in > building my package that the installation process does not unpack the > egg file? This has nothing to do with that - it's simply that your egg is empty. Take a look at this: (gpsparser)mac-dir:Application Support deets$ unzip -l /Users/deets/.virtualenvs/gpsparser/lib/python2.5/site-packages/gpsparser-0.0.1-py2.5.egg Archive: /Users/deets/.virtualenvs/gpsparser/lib/python2.5/site-packages/gpsparser-0.0.1-py2.5.egg Length Date Time Name -------- ---- ---- ---- 1 12-08-08 12:04 EGG-INFO/dependency_links.txt 249 12-08-08 12:04 EGG-INFO/PKG-INFO 599 12-08-08 12:04 EGG-INFO/SOURCES.txt 1 12-08-08 12:04 EGG-INFO/top_level.txt 1 12-08-08 11:25 EGG-INFO/zip-safe -------- ------- 851 5 files (gpsparser)mac-dir:Application Support deets$ I presume you miss a packages=find_packages(), line in your setup.py, with from setuptools import setup, find_packages to actually get the find_packages. Diez From clp at rebertia.com Mon Dec 8 12:52:49 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 8 Dec 2008 09:52:49 -0800 Subject: datetime and the rich-companison operators In-Reply-To: <493CCFBC.90104@stoneleaf.us> References: <493CCFBC.90104@stoneleaf.us> Message-ID: <47c890dc0812080952q32adc09etbd5d4c1601914b98@mail.gmail.com> On Sun, Dec 7, 2008 at 11:41 PM, Ethan Furman wrote: > Greetings All! > > I am implementing a NullDate class in order to mirror dates and datetimes > that have no value (yes, this is for my dbf module :) > > I'm still a bit fuzzy about class methods, hashing, and __new__, but my > question of the moment is this: it seems to me that with two dates or > datetimes, they should either be equal, or one should precede the other, and > this can be accomplished quite handily with __cmp__... so does anyone know > why the rich comparisons were used in the datetime module? Was it simply a > style choice, or is something being handled that __cmp__ couldn't cope with? Probably because __cmp__ was removed in Python 3.0, thus requiring the use of the rich comparison methods in its place. See the earlier thread entitled "Python 3 __cmp__ semantic change?". Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks in advance! > ~ethan~ > -- > http://mail.python.org/mailman/listinfo/python-list > From hniksic at xemacs.org Wed Dec 3 04:17:20 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 03 Dec 2008 10:17:20 +0100 Subject: How to use a Python function that returns a double array in C++. References: <24b01c57-0197-4971-9489-47345a2777f7@h20g2000yqn.googlegroups.com> Message-ID: <87hc5lr527.fsf@mulj.homelinux.net> pieter writes: > I want to use a Python function that returns a double array in C++. Return an array.array('d') object, and use the buffer protocol (for example PyObject_AsReadBuffer()) to get the address of the underlying array of native doubles. From r.drew.davis at gmail.com Tue Dec 16 22:18:03 2008 From: r.drew.davis at gmail.com (r.drew.davis at gmail.com) Date: Tue, 16 Dec 2008 19:18:03 -0800 (PST) Subject: Need help improving number guessing game References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> <01564c98$0$21844$c3e8da3@news.astraweb.com> <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> Message-ID: On Dec 15, 1:29?pm, feba wrote: > 6; can anyone think of anything else to add on to/do with this game? > With the minr/maxr display, multiplayer, score keeping, and > automation, I'm just about all of ideas. All I can think of left to > add is 3 and 4 player modes, or a fork where player 2 can't win > (kekekekeke. Though I'm not sure how to do it...), both of which I > feel are somewhat pointless for a game like this. If I can't learn > anything more from it, I will probably go back to reading python > guides for a bit, and then try to make something else. Well, if you want to aim for several more rounds of refinement, how about having the game allow many players identified by name and have it keep records in a file: player name, number of times played, best score, best elapsed time for game completion - for each player. Can you do it in such a way that multiple people on different PC's can all play the game at the same time and not scribble over each other's scores? One approach would be to insist that the player's computers be able to share access to a particular directory, perhaps using a network mount of a disk from somewhere. A fancier approach would be to have a score keeping "service" that runs somewhere and each player's computer uses the network to interact with that score keeping service. Besides the game playing front end to the score keeping service, maybe you should have an administrative front end to the score keeping service to allow you to delete the names of deceased game players. (The only thing keeping him on his perch were tiny little nails through his feet). Can just anyone play the game or does the administrator have to add their name as an authorized player to the score keeping service before they are allowed to play? Is it "Scout's honor" that palyers are who they say they are, or is there some kind of authentication for a player to "prove" their identify before they are allowed to play? I remember many years ago back in graduate school, a friend implemented a clone of "pong" with record keeping. People would sit with that stupid game into the middle of the night striving to improve their standings in the best score display. May be more addictive with a "harder" game than this number guessing game but having your score being visible to other players can be powerful motivation to strive for better scores. If only my friend had figured out a way to have the little DEC GT40 demand quarters if the player wanted to play again, he'd have had most of his tuition nicely covered. If your mind is ready to try something completely different, another thing you could strive to do is change the game from a "tty" interface to something more screen oriented. e.g. instead of having a prompt for "play again (y or n):" you'd have buttons on the screen that the player can click that say "quit" or "start new game". Note that the player might decide to click on either of those buttons at any time, not just after they have completed a game. Python has several many different libraries that would give you a basis for building such a "graphical user interface" (GUI) version of your game, but I'm not experienced enough to tell you which GUI package you should look into. Not so much related to the business of making a niftier game, but another area you might want to look into is change management (e.g. "subversion") so you can track the evolution and refinement of your source code over time. The player-visible part of that is perhaps just to have something that announces which revision of the game they are running such that you can tell from that which revision of the source code to look at if you are tracking down a fix for a problem they have encountered and reported to you. Drew From ivlenin at gmail.com Sun Dec 7 15:56:40 2008 From: ivlenin at gmail.com (I V) Date: Sun, 07 Dec 2008 20:56:40 GMT Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> Message-ID: On Sat, 06 Dec 2008 16:34:56 -0800, Erik Max Francis wrote: > `$` as a shortcut for self, on the other hand, gives absolutely no > mnemonic indication what it stands for, and users would be simply left > guessing. However, $ is sometimes used as an alternative way of writing S? (I've attempted to write here S followed by U+0338 COMBINING LONG SOLIDUS OVERLAY, in order to produce an S with a stroke through it). This is the symbol of the "barred subject" in Lacanian psychoanalysis, which is the Lacanian symbol for the concept of the "self" (see http://nosubject.com/Bar ). So, if we want Python to the programming language of choice for Lacanian psychoanalysts, perhaps we should adopt the symbol "$" (or even, with Python 3's support for unicode identifiers, S followed by U+0388) instead of "self." From geekmail at usenot.de Sat Dec 6 07:37:04 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sat, 6 Dec 2008 13:37:04 +0100 Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> Message-ID: <20081206133704.1bed455c@usenot.de> On Sat, 6 Dec 2008 13:32:58 +0100 Andreas Waldenburger wrote: > On Sat, 6 Dec 2008 04:02:54 -0800 (PST) bearophileHUGS at lycos.com > suggested: > > > > class C: > > def $method(arg): > > $value = arg > > > > [snip] > > > [snip] > "self" is a speaking identifier, "$" isn't. > Also, nothing prevents you from replacing "self" with "s" if you really want it short. Same effect as your "s" suggestion (OK, plus one "."). /W -- My real email address is constructed by swapping the domain with the recipient (local part). From rileyrgdev at gmail.com Mon Dec 22 13:42:55 2008 From: rileyrgdev at gmail.com (Richard Riley) Date: Mon, 22 Dec 2008 19:42:55 +0100 Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: Marco Mariani writes: > Richard Riley wrote: > >> One does not have to by a language maestro to try and assess its >> popularity. While his numbers or his reading of the numbers might be >> open to some questions, to suggest that one needs to be totally familiar >> with a language to determine its popularity is, frankly, ridiculous. > > I was not judging his competency. But when I am naive on a subject, I > don't usually show off like that. I do not see what is showing off about judging a languages popularity. In many cases a languages popularity can be a useful metric in picking a language to do a job. > The polemic intents in his previous messages are quite clear (python > is slow, py3k is an utter failure because it doesn't solve the > whitespace issue, etc), and this thread is not different. It seems > like a rehash of issues that have been dragged around here by > generations of trolls for the last 10 years. I find it difficult myself to accept certain criticisms of certain things when I am close to them. This does not, however, make the criticisms unfair or untrue or even unimportant. > > Sorry for adding noise to the signal :-/ -- important and urgent problems of the technology of today are no longer the satisfactions of the primary needs or of archetypal wishes, but the reparation of the evils and damages by the technology of yesterday. ~Dennis Gabor, Innovations: Scientific, Technological and Social, 1970 From robert.kern at gmail.com Wed Dec 3 16:22:04 2008 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 03 Dec 2008 15:22:04 -0600 Subject: Numpy record array - field names for all dimensions In-Reply-To: <74c0e6f0-8caf-4e06-a162-1d107977ff3c@d32g2000yqe.googlegroups.com> References: <74c0e6f0-8caf-4e06-a162-1d107977ff3c@d32g2000yqe.googlegroups.com> Message-ID: ShanMayne wrote: > Greetings All Greetings! If you have more numpy questions, you will find numpy-discussion to be a better forum: http://www.scipy.org/Mailing_Lists > I am seeking to represent datasets where each data element is the > calculated result from several (4 for now) other data types. A matrix- > like (in the general mathematical sense) seems logical, where the > intersection of each of the 4 values (from different data sets) holds > the value derived from those 4 values here serving as indexes. > > So, each matrix/array element is associated with 4 fields. > eg: > matrix element/output value = 24.235 --> > 'Formula' = 'C12H24O2N2' > 'Solvent' = 'Acetonitrile' > 'fragmentation_method' = 'CID' > 'resolution' = 'unit' > > ideally I would like to call the output value by indexing the matrix > with the input information. eg: > > matrix['C12H24O2N2']['Acetonitrile']['CID']['unit'] = 24.235 > > Numpy's record arrays seemingly don't allow all dimensions to carry > field names. ie. each column/row carrying a label. Instead fieldname > usage appears to create a "new dimension" as denoted by square > brackets. Pretty much. You can make nested dtypes, but that's not really the data structure that you want. You probably want a simple dictionary. d = { ('C12H24O2N2','Acetonitrile','CID','unit'): 24.235, ... } assert d['C12H24O2N2','Acetonitrile','CID','unit'] == 24.235 If you want to make partial queries (e.g. Formula='C12H23O2N2' and resolution='unit'), this becomes more like a typical relational database, but you can probably get along with a few simple functions to loop over the dictionary and pull out the relevant keys pretty quickly. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From Slaunger at gmail.com Wed Dec 3 17:30:10 2008 From: Slaunger at gmail.com (Slaunger) Date: Wed, 3 Dec 2008 14:30:10 -0800 (PST) Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> <258cf433-f6c9-43e7-a235-f5f6b2b6433f@j39g2000yqn.googlegroups.com> <33b4cc2f-2311-491c-a2e6-9cc5452b1a6b@g38g2000yqd.googlegroups.com> <2772646a-623f-400b-a606-281a7e3220d4@20g2000yqt.googlegroups.com> Message-ID: <69d7fe1d-11d9-4d28-a3b7-8a6fb6ecbccc@h5g2000yqh.googlegroups.com> On 3 Dec., 15:30, Nick Craig-Wood wrote: > Slaunger wrote: > > ?On 3 Dec., 11:30, Nick Craig-Wood wrote: > > > > ? ? ? ? ?cls = self.__class__ > > > > ? ? ? ? ?if attr_name in cls.data_attr_names: > > > > self.data_attr_names should do instead of cls.data_attr_names unless > > > you are overriding it in the instance (which you don't appear to be). > > > ?Yeah, I know. I just like the cls notation for code readability > > ?because it tells you that it is a class attribute, which is not > > ?instance- dependent. > > > ?That may be legacy from my Java past, where I used to do it that > > ?way. ?I know perfectly well that self. would do it. i just find > > ?that notation a little misleading > > I quite like it... It looks in the instance, then in the class which I > find to be very elegant - you can set a default in the class and > override it on a per object or per subclass basis. > In principle yes. In the particular case in which it is used I happen to know that it would not make sense to have a different attribute at the instance level. That is, however quite hard to realize for outside reviewers based on the small snippets I have revealed here. So, i certainly understand your view point. The cls notation sort of emphasizes that instances are not supposed to override it (for me at least), and if they did, it would be ignored. In other applications, I would use self. too. > > > > ? ? ? ? ? ? ? ? ? ?for k, v in zip(("I1", "Q1", "I2", "Q2"), bytes_to_data(buf)): > > > ? ? ? ? ? ? ? ? ? ? ? ?setattr(self, k, v) > > > ? ? ? ? ? ? ? ? ? ?return object.__getattr__(self, attr_name) > > > ?And perhaps even more readable (how I do it now, no need to call > > ?__getattr__ for an attribute, whcih is already there): > > ? ? ? ? ? ? ? ? ?... > > ? ? ? ? ? ? ? ? ?for attr, value in zip(cls.data_attr_names, > > ?bytes_to_data(buf)): > > ? ? ? ? ? ? ? ? ? ? ?setattr(self, attr, value) > > > ? ? ? ? ? ? ? ? ?return getattr(self, attr_name) > > I wrote the object.__getattr__ call to stop recursion troubles. ?If > you are sure you've set the attribute then plain getattr() is OK I > guess... Ah, Ok. I am sure and my unit tests verify my assurance. > > > ?In this process I have actaully managed to isolate all the > > ?...OnDemand stuff in an abstract PayloadOnDemand class > > > ?I can now use this "decorator-like"/helper class to very easily > > ?make an ...OnDemand variant of a class by just doing multiple > > ?inheritance - no implementation: > > > ?class PayloadBaconAndEggsOnDemand(PayloadOnDemand, PayloadBaconAndEggs): pass > > You've reinvented a Mixin class! > > ?http://en.wikipedia.org/wiki/Mixin > > It is a good technique. > Wow, there is a name for it! It did not know that. Hmm... I never really took the time to study those GoF design patterns. (I am a physicist after all... and really a programmer) I guess I could save a lot of time constantly re-inventing the wheel. Are there any good design pattern books focused on applications in Python? (Actually, I will post that question in a separate thread) Once again, I am extremely pleased with your very thoughtful comments, Nick. Thanks! -- Slaunger From news123 at free.fr Wed Dec 10 18:36:04 2008 From: news123 at free.fr (News123) Date: Thu, 11 Dec 2008 00:36:04 +0100 Subject: Python for kids? In-Reply-To: <53f406ed-c261-4d86-a8dc-4001d10d05b5@s20g2000yqh.googlegroups.com> References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> <53f406ed-c261-4d86-a8dc-4001d10d05b5@s20g2000yqh.googlegroups.com> Message-ID: <49405265$0$24620$426a74cc@news.free.fr> Hi, bearophileHUGS at lycos.com wrote: > On Dec 7, 9:13 pm, "Russ P." wrote: >> I have a 12-year-old son who spends too much time playing Xbox live >> and watching silly YouTube videos. I would like to try to get him >> interested in programming. > . . . > But I think it's better for you to help him get interest in problem- > solving . . . > Once those interests are in place, he will > probably go looking by himself for things like programming languages, > . . . > > Otherwise you risk pushing a person to learn using a tool (programming > is interesting by itself, but it's mostly a tool still) before having > any use for such tool or desire to learn it. And this may lead to > someone with no passion to solve problems and learn. > People are different. I for example learnt programming at 13 without having any initial use for it. My main motivation was, that my father brought the first computer, I ever saw (AIM-65) from work, but didn't want to spent time to explain me what it does and how it works. Instead he just gave me a book about BASIC and hoped I wouldn't bother him anymore. (For me as a slightly stubborn teenager this was challenge enough to show, that I could write a (whatever) basic program. If the book, that teaches programming has just a few 'fun examples' it could be enough to get him (Rus' son) started thinking about his own problems he could then solve with writing programs. Russ should best be able to know what could be 'fun-examples' for his son. Fun-examples could be things like: - high low number guessing program - drawing funny pictures with turtle graphics - printing out all possible combinations / permutations of som digits letters. - towers of hanoi - a very basic pong game - writing a mini data base for his 'whatever' - collection It might however be a little more complicated to motivate somebody to write some small rather simple programsm when it's so simple to google and download so much SW without knowing anythng about programming. 20-30 years ago it was basically impossible to locate and download (even did'nt have a modem :-) ) ready made SW Depending on his interests he might also be more interested in learning a spreadsheet SW / a drawing program and then attack the related macros / scripting language bye N From duncan.booth at invalid.invalid Sun Dec 21 10:30:34 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Dec 2008 15:30:34 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <015da0a4$0$20656$c3e8da3@news.astraweb.com> <6r6uvbFfb643U5@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: >> a+b+c+d might execute a.__add__(b,c,d) allowing more efficient string >> concatenations or matrix operations, and a%b%c%d might execute as >> a.__mod__(b,c,d). > > But that needs special casing strings and ``%`` in the comiler, because > it might not be always safe to do this on arbitrary objects. Only in > cases where the type of `a` is known at compile time and ``a % b`` > returns an object of ``type(a)``. > I could be wrong, but I don't see that would be the case. I think it would be safe (in this hypothetical universe) any time that 'a' had a method __mod__ which accepted more than one argument. It might be simpler if I'd suggested an imaginary __mmod__ method so the opcode for multiple-mod could check for that method or fall back to doing mod of the first two values and then mmod of the result and any remaining values until only two remain. From pruebauno at latinmail.com Mon Dec 29 11:36:44 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Mon, 29 Dec 2008 08:36:44 -0800 (PST) Subject: 2to3 used in the Shootout References: <4f1a8f03-fd7f-49ea-8031-61f73fb0c0e8@x16g2000prn.googlegroups.com> <65a43a69-1ef2-4a41-b860-a370891aecbd@g39g2000pri.googlegroups.com> Message-ID: <67424d25-69c3-4c9d-ba38-0df208a28428@k19g2000yqg.googlegroups.com> On Dec 23, 5:21?pm, Isaac Gouy wrote: > On Dec 23, 11:51?am, bearophileH... at lycos.com wrote: > > > They have translated the Python benchmarks of the Shootout site from > > Py2 to Py3 using 2to3: > > >http://shootout.alioth.debian.org/u32/benchmark.php?test=all?=pyt... > > So please re-write those programs to remove problems created by > automatic translation and better take advantage of Python 3 > functionality... > > http://shootout.alioth.debian.org/u32/faq.php#play > > > It shows some "performance bugs" of Python3 itself (especially > > regarding the binary-trees benchmark, that was unexpected by me), and > > two points where 2to3 may be improved, for example after the > > translation this gives error: > > ? ? ? ? ?table=string.maketrans('ACBDGHK\nMNSRUTWVYacbdghkmnsrutwvy', > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 'TGVHCDM > > \nKNSYAAWBRTGVHCDMKNSYAAWBR')): > > > Gives: > > TypeError: maketrans arguments must be bytes objects > > > Bye, > > bearophile > > BTW I am not sure how to submit this or if this is actually valid to do, but I have a faster version for the pidigits program that uses basically the same algorithm but removes function calls and unused terms of the formula.
import time

def pi_digits(n, width):
    out = []
    wrt = out.append
    aq = 1
    ar = 0
    at = 1
    k = 0
    f = 1
    g = 2
    i = 0
    while i < n:
        y = (aq*3+ar)//at
        while y != ((aq*4+ar)//at):
            k += 1
            f += 2
            g += 4
            ar = aq*g+ar*f
            aq = aq*k
            at = at*f
            y = (aq*3+ar)//at
        aq = 10*aq
        ar = 10*ar-10*y*at
        i += 1
        wrt(str(y))
        if not i%width:
            wrt('\t:%d\n'%i)
    wrt(' '*(width-i%width))
    wrt('\t:%d\n'%i)
    return ''.join(out)


def main():
    begin = time.time()
    n = 1000
    width = 70
    print pi_digits(n,width)
    print 'Total Time:', time.time()-begin

main()

From skip at pobox.com Fri Dec 12 14:04:43 2008 From: skip at pobox.com (skip at pobox.com) Date: Fri, 12 Dec 2008 13:04:43 -0600 Subject: Python extension: callbacks blocked when holding button down In-Reply-To: <05533b81-de89-4ee2-90c5-8f19533b65a9@g17g2000prg.googlegroups.com> References: <05533b81-de89-4ee2-90c5-8f19533b65a9@g17g2000prg.googlegroups.com> Message-ID: <18754.46539.568766.995728@montanaro-dyndns-org.local> alan> I'm developing a Python extension. It's a wrapper for some alan> firmware, and simulates the target hardware environment. I'm using alan> wxPython. I pass a function to the extension so it can let Python alan> know about certain events. The code is currently single threaded. alan> My problem is that the callback seems to have no effect if it is alan> called while I am holding down a wxButton in the Python GUI. Long alan> button presses are significant in the firmware so this seems a bit alan> limiting. alan> Can anyone explain what is going on? What's the best workaround? You don't say what platform you're running on, but in many environments, holding down a menu button "grabs" the window server for the duration of the button press. This is certainly the case on Unix running the X Window System. In many cases multithreading is the best way around this problem. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From ndbecker2 at gmail.com Tue Dec 2 14:56:00 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 02 Dec 2008 14:56 -0500 Subject: optimization References: Message-ID: Robert Kern wrote: > Neal Becker wrote: >> Arnaud Delobelle wrote: >> >>> Neal Becker writes: >>> >>>> I noticed in some profiling, that it seems that: >>>> >>>> def Func (): >>>> def something(): >>>> ... >>>> >>>> It appears that if Func is called many times, this nested func >>>> definition will cause significant overhead. Is this true? I guess >>>> I've become accustomed to decent compilers performing reasonable >>>> transformations and so have tended to write code for clarity. >>> If something() can be defined outside Func(), how is it clearer to >>> define it inside? >> >> If it's only used inside. > > I, for one, find that significantly less clear. I only expect functions to > be defined inside of functions if they are going to use lexical scoping > for some reason. If I read your code, I'd probably waste a good five > minutes trying to figure out what part of the local scope you were using > before I would conclude that you just did it because you thought it looked > better. > I'm using the inner function to prevent pollution of the global namespace. Local variables also have this attribute. Code is easier to understand when it is written with the greatest locality - so you can see immediately that the inner function isn't used somewhere else. From mal at egenix.com Wed Dec 10 10:50:57 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 10 Dec 2008 16:50:57 +0100 Subject: Rich Comparisons Gotcha In-Reply-To: <1228923619.493fe2e3c3073@comuh.uh.cu> References: <1228923619.493fe2e3c3073@comuh.uh.cu> Message-ID: <493FE561.6030007@egenix.com> On 2008-12-10 16:40, Luis Zarrabeitia wrote: > Quoting Rasmus Fogh : >> Rhamphoryncus wrote: >>> You grossly overvalue using the "in" operator on lists. >> Maybe. But there is more to it than just 'in'. If you do: >>>>> c = numpy.zeros((2,)) >>>>> ll = [1, c, 3.] >> then the following all throw errors: >> 3 in ll, 3 not in ll, ll.index(3), ll.count(3), ll.remove(3) >> c in ll, c not in ll, ll.index(c), ll.count(c), ll.remove(c) >> >> Note how the presence of c in the list makes it behave wrong for 3 as >> well. > > I think I lost the first messages on this thread, but... Wouldn't be easier to > just fix numpy? I see no need to have the == return anything but a boolean, at > least on Numpy's case. The syntax 'a == b' is an equality test, not a detailed > summary of why they may be different, and (a==b).all() makes no little sense to > read unless you know beforehad that a and b are numpy arrays. When I'm comparing > normal objects, I do not expect (nor should I) the == operator to return an > attribute-by-attribute summary of what was equal and what wasn't. > > Why is numpy's == overloaded in such a counter intuitive way? I realize that an > elementwise comparison makes a lot of sense, but it could have been done instead > with a.compare_with(b) (or even better, a.compare_with(b, epsilon=e)). No > unexpected breakage, and you have the chance of specifying when you consider two > elements to be equal - very useful. Rich comparisons were added to Python at the request of the Numeric (now numpy) developers and they have been part of Python a Numeric for many many years. I don't think it's likely they'll change things back to the days of Python 1.5.2 ;-) > Even the transition itself could be done without breaking much code... Make the > == op return an object that wraps the array of bools (instead of the array > itself), give it the any() and all() methods, and make __nonzero__/__bool__ > equivalent to all(). That would cause a lot of confusion on its own, since such an object wouldn't behave in the same way as say a regular Python list (bool([0]) == True). -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 10 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-12-02: Released mxODBC.Connect 1.0.0 http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From exarkun at divmod.com Tue Dec 30 14:27:16 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 30 Dec 2008 14:27:16 -0500 Subject: select.select and socket.setblocking In-Reply-To: <495a661d$0$11384$5fc30a8@news.tiscali.it> Message-ID: <20081230192716.20272.501856153.divmod.quotient.29293@ohm> On Tue, 30 Dec 2008 19:19:08 +0100, Francesco Bochicchio wrote: > [snip] > >If you are interested in socket errors, you should >also fill the third 'fd-set' in the select call, and after select returns >check that fd is not in it anymore: > >ready = select.select( [fd],[], [fd] ) >if fd in ready[2]: > # raise your error here The third argument to select() isn't for monitoring sockets for errors. Its behavior is also rather platform sensitive. In general, you don't need it at all on POSIX, but on Windows you should pass the same list for it as you pass for the write-set, merge the results, and treat them all as writeable. Or use a higher-level library that deals with all the asinine details for you. ;) Jean-Paul From lists at cheimes.de Thu Dec 25 19:48:55 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 26 Dec 2008 01:48:55 +0100 Subject: SyntaxError: encoding problem: with BOM In-Reply-To: <26e21f3f-ded1-48ca-8897-2ebd05dd07ad@w39g2000prb.googlegroups.com> References: <6res8tF1do1sU1@mid.uni-berlin.de> <400f176b-bd9a-4f26-b01b-1aa7c7dcf5ac@z6g2000pre.googlegroups.com> <6rf6m1F1e0f8U1@mid.uni-berlin.de> <26e21f3f-ded1-48ca-8897-2ebd05dd07ad@w39g2000prb.googlegroups.com> Message-ID: NoName schrieb: >> NoName, Asking people to download a zip file from a website written in >> a language and character set that they probably are not familiar with >> is liable to make them rather nervous and not bother. It's not a good >> way to ask for help. > > sorry:) > > Now i know where problem. > But i dont know how to solve it. > > Error > ---- > C:\Documents and Settings\Ra\??????? ????>11.py > File "", line 1 > SyntaxError: encoding problem: with BOM > > No error > ---- > C:\Documents and Settings\Ra\??????? ????>python 11.py > test > > Error when russian symbols in full path to py-script. > Is it Python bug? or i need to modify some registry keys? > > OS: WinXP SP3 Russian. > Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit > (Intel)] on win32 It's a bug, please report it. I though we fixed all Windows path bugs for 3.0 but apparently one slipped through. Christian From fakeaddress at nowhere.org Sat Dec 13 18:13:39 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 13 Dec 2008 15:13:39 -0800 Subject: Bidirectional Networking In-Reply-To: <98a6c3cd-181c-43c9-805b-fb0689c69544@a26g2000prf.googlegroups.com> References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <98a6c3cd-181c-43c9-805b-fb0689c69544@a26g2000prf.googlegroups.com> Message-ID: Emanuele D'Arrigo wrote: > Hey Bryan, thank you for your reply! > > Bryan Olson wrote: >>> Is it possible then to establish both a server and a client in the >>> same application? >> Possible, and not all that hard to program, but there's a gotcha. >> Firewalls, including home routers and software firewalls, typically >> default to disallowing connections in the 'wrong' direction. If the >> client initiates all connections, you avoid a world of hassles. > > Ah yes, I can see that. Uhm. I have absolutely no idea right now how a > firewall works from a programming point of view and what happens in > normal "residential" circumstances. I.e. it's clear that firewalls are > configured to allow http traffic because I can browse the internet. Is > that done leaving a specific port open? Or does the browser request > the firewall to open a specific port for it and the firewall trust the > browser to handle safely anything that comes through? Software firewalls will often simply refuse incoming connections. The basic protection of the garden-variety home router comes from "network address translation" (NAT), in which case TCP connections initiated from the inside will generally work, regardless of port, and incoming connections will fail. Internet server farms often enforce the other side of the client-side policy, with firewalls configured to disallow outgoing initiation of connections. If the application need to work in restrictive environments where firewalls only pass known protocols, a popular approach to build the application protocol on top of HTTP, with all the required standard headers and a new content-type. > I.e. in the case of the code in this thread, would it be the > responsibility of the application to tunnel through the firewall and > listen for connections I'm not clear on what that means. > or would it be the responsibility of the user > to configure the firewall so that the application can receive a > connection? That can be a huge hassle. The first choice is for the application to conform to popular firewall policies, so no special configuration is required. -- --Bryan From mail at microcorp.co.za Wed Dec 3 16:09:17 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 3 Dec 2008 23:09:17 +0200 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> Message-ID: <001901c9558b$7e4c1420$0d00a8c0@hendrik> "Xah Lee" wrote: >Chances are, $10 is not enough for me to take the >trouble of disappearing from the face of this earth. What a pity. It would be cheap at the price. - Hendrik From rdcollum at gmail.com Thu Dec 18 14:38:58 2008 From: rdcollum at gmail.com (Roger) Date: Thu, 18 Dec 2008 11:38:58 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <71ede5f0-fd88-4155-9f0d-42d0ad5f57dc@v42g2000yqj.googlegroups.com> <61f45e65-2404-4cc0-9d81-f848c1ba566f@i18g2000prf.googlegroups.com> Message-ID: <553bb989-d445-4ebb-b0e4-0ba78ce67cb8@r15g2000prh.googlegroups.com> On Dec 18, 12:49?pm, r wrote: > Maybe someone will chime in with an answer, sorry i could not help. > ponder this, i must... Regardless, thanks for your help! I truly appreciate it. Roger. From prologic at shortcircuit.net.au Mon Dec 29 20:35:44 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 30 Dec 2008 11:35:44 +1000 Subject: get method In-Reply-To: References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> Message-ID: On Tue, Dec 30, 2008 at 11:32 AM, James Mills wrote: > Ross, the others have informed you that you are not > actually incrementing the count. I'll assume you've > fixed your function now :) ... I want to show you a far > simpler way to do this which takes advantage of > Python's list comprehensions and mappings (which are > really what dictionaries are): > >>>> s = "James Mills and Danielle Van Sprang" >>>> dict([(k, len([x for x in s if x == k])) for k in s]) > {'a': 5, ' ': 5, 'e': 3, 'd': 1, 'g': 1, 'i': 2, 'M': 1, 'J': 1, 'm': > 1, 'l': 4, 'n': 4, 'p': 1, 's': 2, 'r': 1, 'V': 1, 'S': 1, 'D': 1} >>>> > > Let us know when you get to the "List Comprehension" > section - They are very powerful - As as Generators > and Generator Expressions. > > Have fun learning Python, Also, here's a nice function: >>> def histogram(s): ... d = dict([(k, len([x for x in s if x == k])) for k in s]) ... for k, v in d.iteritems(): ... print "%s: %s" % (k, "*" * v) ... >>> histogram("Hello World!") !: * : * e: * d: * H: * l: *** o: ** r: * W: * cheers James From invalid at invalid Mon Dec 22 10:45:24 2008 From: invalid at invalid (Grant Edwards) Date: Mon, 22 Dec 2008 09:45:24 -0600 Subject: How to represent a sequence of raw bytes References: <200812220327.36180.motoom@xs4all.nl> <015f66d7$0$20615$c3e8da3@news.astraweb.com> Message-ID: On 2008-12-22, Steven D'Aprano wrote: > On Mon, 22 Dec 2008 14:56:45 +0800, Steven Woody wrote: > >> The intension is to allocate 200 undefined bytes in memory. > > You *want* undefined bytes? Out of curiosity, what do you intend to do > with them? Predict the future, of course. -- Grant Edwards grante Yow! MERYL STREEP is my at obstetrician! visi.com From gagsl-py2 at yahoo.com.ar Fri Dec 26 07:35:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 26 Dec 2008 10:35:00 -0200 Subject: Exec inside a class method to call other class methods? References: <4953CF57.8080905@sympatico.ca> <20081226001641.GA22946@sdf.lonestar.org> <47c890dc0812251624m7e1c5e55rb538996a52d56675@mail.gmail.com> <6706036c-98e0-46c1-b3c2-5a9a0a92af56@w39g2000prb.googlegroups.com> Message-ID: En Fri, 26 Dec 2008 03:59:25 -0200, Carl Banks escribi?: > To be honest I am a little concerned over the more-or-less knee-jerk > suggestions to refactor this into a highly object-oriented approach. > For the task at hand the OP's approach is fine (aside from the use of > exec). Yep. There is a simple solution that still nobody suggested: rename all of __parse_foo as _parse_foo (single leading underscore), then: def parse(self, data, data_type) return getattr(self, "_parse_%s" % data_type)(data) unless there are strong reasons to keep the __ names. -- Gabriel Genellina From jon at ffconsultancy.com Mon Dec 8 16:31:29 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Mon, 08 Dec 2008 21:31:29 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> <0201522a-b15a-4401-a208-5d9af70bdd74@w24g2000prd.googlegroups.com> Message-ID: Xah Lee wrote: > Also, in this discussion, thanks to Thomas M Hermann's $20 offered to > me for my challenge to you, that i have taken the time to show working > code that demonstrate many problems in your code. You failed the challenge that you were given. Specifically, your code is not measurably faster on the problem that I set. Moreover, you continued to write as if you had not failed and, worse, went on to give even more awful advice as if your credibility had not just been destroyed. > If you are a Mathematica expert, you could make it recurse yet have > the speed as other langs. No, you cannot. That is precisely why you just failed this challenge. You should accept the fact that Mathematica currently has these insurmountable limitations. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From john.rominsky at gmail.com Wed Dec 17 19:32:58 2008 From: john.rominsky at gmail.com (Rominsky) Date: Wed, 17 Dec 2008 16:32:58 -0800 (PST) Subject: getting object instead of string from dir() References: Message-ID: <1bb0df81-380c-46eb-a3aa-863c468c6aff@x14g2000yqk.googlegroups.com> On Dec 17, 1:21?pm, Jean-Paul Calderone wrote: > On Wed, 17 Dec 2008 11:52:17 -0800 (PST), Rominsky wrote: > >On Dec 17, 10:59?am, Christian Heimes wrote: > >> Rominsky schrieb: > > >> > I am trying to use dir to generate a list of methods, variables, etc. > >> > I would like to be able to go through the list and seperate the > >> > objects by type using the type() command, but the dir command returns > >> > a list of strings. ?When I ask for the type of an element, the answer > >> > is always string. ?How do I point at the variables themselves. ?A > >> > quick example is: > > >> > a = 5 > >> > b = 2.0 > >> > c = 'c' > > >> > lst = dir() > > >> > for el in lst: > >> > ? ? print type(el) > > >> for name, obj in vars().iteritems(): > >> ? ? print name, obj > > >> Christian > > >I do have some understanding of the pythonic methodology of > >programming, though by far I still don't consider myself an expert. > >The problem at hand is that I am coming from a matlab world and trying > >to drag my coworkers with me. ?I have gotten a lot of them excited > >about using python for this work, but the biggest gripe everytime is > >they want their matlab ide. ?I am trying to experiment with making > >similar pieces of the ide, in particular I am working on the workspace > >window which lists all the current variables in the namespace, along > >with their type, size, value, etc.... ?I am trying to create a python > >equivalent. ?I can get dir to list all the variables names in a list > >of strings, but I am trying to get more info them. ?hence the desire > >to do a type command on them. ?I like the locals and globals commands, > >but I am still trying to get more info. ?I have started using the eval > >command with the strings, which is working, but I am curious if there > >is a better or more elegant way of getting the info. ?The eval example > >would be something like: > > >a = 5 > >b = 2.0 > >c = 'c' > > >lst = dir() > > >for el in lst: > > ? print el + '\t' + str(eval('type(%s)'%el)) > > >It works, now I am curious if there is a better way. > > What about this: > > >> for name, obj in vars().iteritems(): > >> ? ? print name, obj > > >> Christian > > Jean-Paul vars seems to give an identical response as locals and globals, at least in my test name space. All three are new commands for me. I like the idea of adopting either vars or locals instead of dir as it sets up the value for me to use. I will play with them both a little more and read up on them to learn there uses and limitations. The key step for me is still to be able to automatically query the key names from vars or locals for what type the variable is. In my previous post I discussed using eval and the string in the key name such as eval('type(%s)'%vars().keys()[0]) I definitely have enough to move forward. Thanks everyone. If anyone has any other ideas I would still be interested in learning more. Thanks again. From danebarney at gmail.com Fri Dec 26 23:20:16 2008 From: danebarney at gmail.com (Jugdish) Date: Fri, 26 Dec 2008 20:20:16 -0800 (PST) Subject: raw_input can't handle pound sign? Message-ID: Hi, I'm having problems getting a pound sign to go through as input sent to the raw_input() command. I'm running Python 2.5.1 on Windows XP. Here's my simple little script: while True: response = raw_input("Please enter a file name: ") if os.path.exists(response): break Problem is if the filename has a "#" in it, the script interprets that as the beginning of a comment (not sure why -- isn't raw_input supposed to treat the user's input as raw text and not do any sort of evals?) Any ideas how to get a # to go through? Thanks! From stef.mientki at gmail.com Wed Dec 10 03:21:17 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 10 Dec 2008 09:21:17 +0100 Subject: Mathematica 7 compares to other languages In-Reply-To: <9ecfa224-ce8f-44e9-abca-008314f44e87@40g2000prx.googlegroups.com> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <9ecfa224-ce8f-44e9-abca-008314f44e87@40g2000prx.googlegroups.com> Message-ID: <3dfd60f20812100021j638bf420v37bb6d81fa02d064@mail.gmail.com> On 12/10/08, Xah Lee wrote: > On Dec 8, 5:25 pm, Terry Reedy wrote: >> Lest anyone doubt that problem size is important for comparing program >> run times, consider ... > > just in case there's any doubt: > > Simply change these lines in Jon's program: > > Main[9, 512, 4] to Main[9, 512, 4.] > > and it will run faster. > Who said Mathematica was a high level language ? cheers, Stef From amr at vimov.com Mon Dec 1 16:49:22 2008 From: amr at vimov.com (Amr) Date: Mon, 1 Dec 2008 13:49:22 -0800 (PST) Subject: Aviate, the Web Deployer Message-ID: Announcing the first public release of Aviate, a cross-platform web deployment tool written in Python. Aviate is designed to make deploying your web applications very easy, while providing you with a rich feature set to make repeated task performed in a snap, and being extensible so you can extend its features with your own Python code. Among its feature is being based on XML, an intuitive GUI to create deployment files, a large number of built-in commands, multiple protocol support, extensibility, language constructs, and more. More details on Aviate: http://www.vimov.com/aviate/ Download: http://www.vimov.com/aviate/download/ Front-end: http://blog.vimov.com/2008/11/aviate-front/ From musiccomposition at gmail.com Fri Dec 5 22:33:42 2008 From: musiccomposition at gmail.com (Benjamin) Date: Fri, 5 Dec 2008 19:33:42 -0800 (PST) Subject: Python 3.0 C API migration tools, or docs? References: <008877d2-8705-48a6-bb09-6c31c6b77970@p2g2000prf.googlegroups.com> <1a5cf43f-5802-4c69-9226-18cbc6256c0c@k19g2000yqg.googlegroups.com> Message-ID: <67098ab1-131b-4169-9f65-7efd4038d0ab@r40g2000yqj.googlegroups.com> On Dec 4, 9:06?pm, illume wrote: > Cool thanks Benjamin! > > Maybe it should be in a wiki as well? ?So that as people convert their > modules we can add notes as well. > > I started a wiki with that in mind here:http://wiki.python.org/moin/cporting > > It'd be good if there was a link from the 2to3 docs, and in the C API > docs to either/both of these resources. > > I thought there'd be much more help for people migrating considering > the 2to3 tool exists... but I'll get over it... hehe. Thanks for being so positive. If you'd like to help with the HowTo, feel free to email docs at python.org. > > cheers, From castironpi at gmail.com Mon Dec 22 18:53:38 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 22 Dec 2008 15:53:38 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> Message-ID: <80427165-02a0-4401-ade9-3cef1d520e6c@v39g2000pro.googlegroups.com> On Dec 22, 11:40?am, r wrote: > On Dec 22, 8:58?am, walterbyrd wrote: > > > > > On Dec 21, 12:28?pm, Bruno Desthuilliers > > > wrote: > > > Strange enough, > > > no one seems to complain about PHP or Ruby's performances... > > > A few years back, there was a certain amount of chest thumping, when > > python/django easily beat ror in a benchmark test. Now that ruby is > > faster, I guess speed is no big issue. > > > By the same reasoning, python advocates used to sneer at php because > > php constantly broke backward compatibility. Now that python does it, > > breaking backward compatibility is no big deal. I guess unicode > > support was not that important, until python caught up to perl. > > > I guess, the way it works is: you first assume that python is > > superior, then you figure out why. > > I think what walter is saying is the loyalty is gone. > > community: > """If python makes great, if it doesn't, why should "i" care if it > goes down the toilet? ?i just move to ruby""" > > Were is your loyalty pyfans?, Has the fight left you??? Point: It is not rational for the crew to go down with the ship, only the captain. Case: Loyalty is a complex emotion, and it's not clear that it's our highest priority, or that it's anyone's. I want to use a good language. If Python stops being good (that is, a good version of Python stops being maintained and supported), then I'll stop using it, and that's the rational thing to do. Just to be fair, though, it's (contraction) not obviously irrational for a captain to go down with the ship. The mentality, commitments, and principles that it lets him keep and make may be better on the whole in the long run for captains, crews, and ships, only if they have that consequence. That is, captains that will go down with the ship are better captains of ships, and captains that have the capacity to betray, forge, or abandon principles make worse captains; therefore a good captain will go down, and can't change his mind. However, as critics and fans of Python, our actions don't really have the same consequences as the captains. That is, it is not rational for the crew to go down with the ship, only the captain. From banibrata.dutta at gmail.com Thu Dec 4 00:31:32 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Thu, 4 Dec 2008 11:01:32 +0530 Subject: Good introductory book? In-Reply-To: <56616d73-312c-44e5-a484-5fb3e0054613@x38g2000yqj.googlegroups.com> References: <56616d73-312c-44e5-a484-5fb3e0054613@x38g2000yqj.googlegroups.com> Message-ID: <3de8e1f70812032131t49715c61r194fb39b7650655@mail.gmail.com> 1+ for "Dive into Python"... get's you started very fast. After you are thru with DiP book, it's time to keep google (or ur favourite search engine) handy... search at the ActivePython site in the cookbooks, PEP's, mailing-list archive... the answer is generally found within first 4-5 hits. And then, a good Language Reference is indipespensible... for which the standard Python docs are pretty good. On Thu, Dec 4, 2008 at 10:48 AM, Kottiyath wrote: > On Dec 3, 7:44 pm, "Ken D'Ambrosio" wrote: >> Hi, all. I'm getting ready to do some projects in Python, and I've cut my >> teeth a little bit, but I've found the "Learning|Programming Python" books >> from O'Reilly to be more-or-less useless (to my surprise -- I'm usually an >> O'Reilly fan). I really, really like "Python Essential Reference", but >> it's -- well, more of a reference than an intro. So, an introductory text >> that actually assumes some previous programming experience (as opposed to >> "Learning Python" which must be the most slowly-paced programming book >> ever) would be terrific. >> >> Thanks for your suggestions! >> >> -Ken > > Dive into python is a very good one. It is free too. > http://diveintopython.org/ > > Try it out. > If you want more of examples of how everything is done, then Python > Cookbook is another one. > You can get many recipes at http://code.activestate.com/recipes/langs/python/ > too - the book is just selected recipes from this site. > > > Regards > K > -- > http://mail.python.org/mailman/listinfo/python-list > -- regards, Banibrata http://www.linkedin.com/in/bdutta http://octapod.wordpress.com From kyosohma at gmail.com Wed Dec 24 19:37:40 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 24 Dec 2008 16:37:40 -0800 (PST) Subject: Easy-to-use Python GUI References: Message-ID: <26db7a5a-5636-4d47-a593-7a4e8b6e3a01@s9g2000prg.googlegroups.com> On Dec 24, 5:47?pm, "Joel Koltner" wrote: > Is there an easy-to-use, "function"-based cross-platform GUI toolkit for > Python out there that's a little more sophisticated than EasyGui? ?EasyGui > looks good, but it's a little more restrictive than what I'd like to have, yet > I'm (stubbornly :-) ) resistant to stepping up to a "full service" GUI toolkit > such as pyGTK or wxPython where it's all about event loops and callbacks and > you need to start planning how the GUI affects the overall program flow rather > than just using a "forms" (or "Wizard")-type approach where you put up a few > dialogs, users fill in some variables, and your program just sits around > waiting until "OK" or "Cancel" is clicked. > > One approach that I like comes from SAX BASIC/WinWrap, which is more or less a > clone of Microsoft's Visual BASIC for Applications, but they (apparently) > wanted everything to still be human-readable, so they have a simple GUI > ("form") builder that generates code that looks like this: > > --- > > ?Begin Dialog UserDialog 850,497,"Export Control" ' %GRID:10,7,1,1 > > ? GroupBox 20,7,360,217,"Drill File Generation",.GroupBox1 > ? CheckBox 40,35,130,14,"Output drill file(s)",.genDrill > ? Text 40,63,270,28,"Identify via layers as any that contain this text in > their names:",.Text > ? TextBox 40,98,220,21,.viaLayerName > ? Text 40,140,100,14,"Output method:",.Text8 > ? DropListBox 160,140,180,21,DrillStyle(),.drillStyle > ? Text 40,175,130,28,"Select drill table units:",.Text2 > ? ListBox 200,175,120,28,unitNames(),.unitName > > ? OKButton 310,469,90,21 > ? CancelButton 410,469,90,21 > > ?End Dialog > > ' GUI builder generates or modifies everything above, but can also be edited > by hand > ' You write the following code... > > ?Dim dlg As UserDialog > > ?dlg.genDrill = 1 > ?ReDim DrillStyle(1) > ?DrillStyle(0) = "All Via Layers In One File" > ?DrillStyle(1) = "One File Per Via Layer" > ?dlg.drillStyle = 1 > > ?func=Dialog(dlg) > > --- > > This is pretty darned easy for me understand and modify either by hand or with > the GUI builder. ?Still, it's quite powerful, since it supports all the common > GUI elements (text, group boxes, checkboxes, drop-down lists, text boxes, > buttons, etc.). ?This is about the level of sophistication I'm looking for. > > Anything like this for Python? > > Thanks, > ---Joel Some people like Boa Constructor, XRC or wxGlade: http://boa-constructor.sourceforge.net/ http://wxglade.sourceforge.net/ http://wiki.wxpython.org/XRCTutorial Technically, you can switch to IronPython and then use Visual Studio to design your GUIs and IronPython to control it. I think there's something similar to Jython and Cocoa as well. Probably not what you wanted though. Mike From pdorange at pas-de-pub-merci.mac.com Sun Dec 14 18:25:36 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Mon, 15 Dec 2008 00:25:36 +0100 Subject: Game to test : MicroWar 2.0 alpha 6 Message-ID: <1iryrns.1xzj14rqka5s0N%pdorange@pas-de-pub-merci.mac.com> MicroWar 2.0 alpha 3 for test purpose Download : http://microwar.sourceforge.net/ Presentation ----------------- MicroWar is "Space Invaders" style arcade game, in the cruel world of micro-compter industry. You're a Macintosh faced to invading Wintel hordes year after year, kill more PC. Bonuses let you improve your Mac performances or restore life... Minimum Configuration (Macintosh) ------------------------------------------------ Processor : PowerPC G4 minimum System : MacOS X 10.3.9 or more Memory : 512 MB Screen : 1024 x 768 pixels The bundled application is only available for Mac now. The source code, is therefore cross-platform and can run on Macintosh, Windows and Linux : see source documentation for details Change log : ----------------- * handle mouse for menus * option to play the game with the keyboard (default) or the mouse * loading advancement feedback on splash screen * default option : fullscreen * bug fix : display year information correctly for 0 and 1 line. * first run screen, user can choose it default language * automatic game update check over internet and download to the desktop * adding Clarus Power-Up Bonus (give 5 super-bomb) * adding Saucer explosion : generate Virus that can infect PC * clean the screens handling -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From vlastimil.brom at gmail.com Mon Dec 22 05:07:45 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Mon, 22 Dec 2008 11:07:45 +0100 Subject: wxpython for python 3.0 ? In-Reply-To: References: Message-ID: <9fdb569a0812220207l2dc1a966xdce9b434fcaa747c@mail.gmail.com> >> The wxpython web describes compatability with python 2.4 & 2.5 . >> Does it work with 3.0 ? If not, anyone have a clue as to when ? > > This question was asked a couple of times on the wxpython-users mailing > list. It's probably going to take a while. For now, I'd stick to python 2.x. > The next version of wxPython should support 2.6, so use that and try to make > your code relatively compatible with Python 3 ... The last version of wxPython (2.8.9.1) available on http://wxpython.org/download.php already supports python 2.6; there are prebuilt binaries for this version too. The 3.0 will probably need a bit more time. vbr From nemokingdom at gmail.com Sun Dec 28 07:44:11 2008 From: nemokingdom at gmail.com (nemo) Date: Sun, 28 Dec 2008 04:44:11 -0800 (PST) Subject: ftp EOF error, thread and process Message-ID: <8feadf33-0798-4eaf-ac7c-d16392692722@e1g2000pra.googlegroups.com> Hi all, My code like this raise an EOFError, It happens if I use the Process module, while, if I use thread.start_new_thread(ftp.pwd,()), it seems works well. And I wondered why. from ftplib import FTP import thread from multiprocessing import Process if __name__ == '__main__': ftp = FTP('localhost', 'movie', 'movie') print ftp.pwd() p = Process(target = ftp.pwd) # thread.start_new_thread (ftp.pwd,()), p.start() p.join() From bj_666 at gmx.net Sun Dec 21 04:35:22 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Dec 2008 09:35:22 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: <6r6gupFfb643U1@mid.uni-berlin.de> On Sat, 20 Dec 2008 22:15:23 -0800, r wrote: > It would be nice to get a vote together and see what does the average > pythoneer want? What do they like, What do they dislike. What is the > state of the Python Union? Does anybody know, Does anybody care? I think > python is slipping away from it's dominate foothold on the world. > Google's use of python may be the only thing holding this house of cards > together. Ruby's "hype" is defiantly growing and unless we strive for > greatness, python may fail. I think ruby may have their act together a > little better than us right now. And since Ruby is such a hodge-podge of > different languages, the __init__ hold is there for many. > > what does joe-python want??? That's not completely irrelevant but I think one of Python's strength is that we have a BDFL who decides carefully what he thinks is best for the language instead of integrating every random idea some newbie comes up with and which might sound useful at first sight. Python has its quirks but even with things I don't like I often realize later it was a wise decision that integrates well into the language whereas my ideas for "fixes" of the quirks wouldn't. "joe-python" most often doesn't see the whole picture and demands changes that look easy at first sight, but are hard to implement right and efficient or just shifts the problem somewhere else where the next "joe-python" trips over it. Ciao, Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Mon Dec 8 23:27:44 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 8 Dec 2008 20:27:44 -0800 (PST) Subject: RuntimeError: dictionary changed size during iteration References: <274eb282-1635-40ca-95af-b82271c57802@v4g2000yqa.googlegroups.com> Message-ID: <8c67c6b0-50f7-40ae-93e4-09edd07d6946@r36g2000prf.googlegroups.com> On Dec 9, 3:00?pm, Steven D'Aprano wrote: > On Mon, 08 Dec 2008 19:10:00 -0800, Robert Dailey wrote: > > On Dec 8, 6:26?pm, Terry Reedy wrote: > >> Robert Dailey wrote: > >> > stuff = vars() > > >> ?>>> vars() is globals() > >> True > > >> > for key in stuff: > > >> You just changed globals, which is aliased as stuff. Stuff changes. > > >> > ? ? print( key, '--', stuff[key] ) > > >> > I get the following error message: > >> > ('CopyEmotionFX', '--', ) > >> > Traceback (most recent call last): > >> > ? File "C:\IT\work\jewett\depends.py", line 12, in > >> > ? ? for key in stuff: > >> > RuntimeError: dictionary changed size during iteration > > >> > Why is this happening? > > > How am I changing globals()? I'm simply iterating the keys in the dict. > > Can someone explain what is going on please? > > You create an new name "key": > > for key in stuff > > I suppose you could do this: > > key = None > stuff = vars() > for key in stuff: but both 'key' and 'stuff' will appear in the dict, possibly causing confusion; another reason why > even better would be: > > for key in vars().copy(): > > because that protects you from cases where globals() change inside the > for loop. From hniksic at xemacs.org Fri Dec 12 08:34:17 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 12 Dec 2008 14:34:17 +0100 Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> Message-ID: <87wse5ms9y.fsf@mulj.homelinux.net> sturlamolden writes: > On Dec 12, 1:44 pm, "Chris Rebert" wrote: > >> Python begs to differ, as those two statements are both semantically >> identical in this case: > > That is because integers are immutable. When x += 1 is done on an int, > there will be a rebinding. But try the same on say, a numpy array, and > the result will be different: The result will be different, but a still occurs! You usually don't notice it because augmented assignments with side effect are normally careful to return the same object, so rebinding is a no-op. But in some cases, that can byte you. For example, tupleobj[0] += 1 raises an exception even when tupleobj[0] is mutable. Taking the numpy example: >>> import numpy >>> t = (numpy.zeros(10),) >>> t (array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]),) >>> t[0] += 1 Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment Of course, the side effect occurs before the exception, so: >>> t[0] array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) From kirk at daycos.com Thu Dec 11 15:45:54 2008 From: kirk at daycos.com (Kirk Strauser) Date: Thu, 11 Dec 2008 14:45:54 -0600 Subject: newbie question: if var1 == var2: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> Message-ID: <87skouzbi5.fsf@daycos.com> At 2008-12-11T19:49:23Z, Steve Holden writes: > ... and it's so hard to write > > item = item[:-1] It's easy - and broken. Bad things happen if you're using something other than '\n' for EOL. -- Kirk Strauser The Day Companies From mail at microcorp.co.za Thu Dec 4 14:05:58 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 4 Dec 2008 21:05:58 +0200 Subject: time.sleep() and Tkinter after()? References: <03613d37-ca4f-4962-bce2-eea0a3f65952@r15g2000prd.googlegroups.com> Message-ID: <001901c95648$5bfcd4a0$0d00a8c0@hendrik> "Davy" wrote: > I have used Tkinter after() to do loop update GUI in my previous post. > And I tried to change after() to time.sleep(), but it seems doesn't > work at all, the Queue send and receive data properly, but the GUI > didn't even appear? > > //-----code changed----- > def draw_canvas_loop(canvas_b): > while (True): > board = data_queue.get(block = True, timeout=2) Do you want it to block, or do you want it to time out? > print 'get', data_queue.qsize() > draw_canvas(board, canvas_b, x, y, block_width, block_height) > time.sleep(0.3) this will make the gui unresponsive for the time > ##canvas_b.after(300, lambda:draw_canvas_loop(canvas_b)) and then the control runs off the end of the function. > So, can I use time.sleep() in GUI application? Or Tkinter scheduler > just ignore the sleep() function? time.sleep(sleep_time) will effectively suspend the gui mainloop (if it is in the mainloop) for the sleep_time, making the gui unresponsive for that time. Eschew it here. Use it in other, non GUI helper threads. > > And if I use after(), will the code form a recursive function call, only if it is coded that way - yours does not look recursive to me > and the memory usage will boost as the program goes (I have watched > the task manager in WinXP and find the python.exe eat more and more > memory...). > def draw_canvas_loop(canvas_b): > board = data_queue.get(block = True, timeout=1) > print 'get', data_queue.qsize() > draw_canvas(board, canvas_b, x, y, block_width, block_height) Here you draw a new canvas object - what has happened to the previous one? Is it possibly still hanging around? Should you do something about it? - Hendrik From gagsl-py2 at yahoo.com.ar Tue Dec 9 09:33:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Dec 2008 12:33:14 -0200 Subject: Compiling and installing python 2.5.2 with Visual C++ 2008 References: Message-ID: En Tue, 09 Dec 2008 11:32:46 -0200, Juan Pablo Romero M?ndez escribi?: > I need to compile python myself because of a module (pivy). So I > downloaded MS Visual C++ 2008 express edition. It apparently compiled > fine but I don't know how to install it to recreate the standard > distribution. In linux i'd take "make install", but on windows? See Tools/msi/README.txt BTW, do you really have to recompile Python? Unless the project requires some specific compiler flags incompatible with the standard build, usually there is no need to recompile Python just because of an extension. -- Gabriel Genellina From mirandasnailvv at gmail.com Fri Dec 19 19:42:28 2008 From: mirandasnailvv at gmail.com (mirandasnailvv at gmail.com) Date: Fri, 19 Dec 2008 16:42:28 -0800 (PST) Subject: interracial wife galleries - Free Message-ID: interracial wife galleries . . . *******CLICK HERE******** http://club247.cn/interracial-wife-galleries ***************************** . . . . . . . . . . . . interracial wife galleries From metolone+gmane at gmail.com Sat Dec 27 14:16:35 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 27 Dec 2008 11:16:35 -0800 Subject: ctypes & strings References: <334452.47084.qm@web30003.mail.mud.yahoo.com> <000f01c96822$5c300f00$0d00a8c0@hendrik> Message-ID: "Hendrik van Rooyen" wrote in message news:000f01c96822$5c300f00$0d00a8c0 at hendrik... > > Red Rackham wrote: > >>I would like to pass a string into a dll function. I notice that to pass >>using > ctypes, it has to be a ctypes type. >Looking at the ctypes doc page I > don't see > a c_string class. > > The following seems to work for me: > > In the c programme: > > /* > This routine outputs and inputs a symmetric block of bytes, writing > the outputs out and reading the inputs in, replacing the chars in the > original output string > */ > > unsigned char read_write (unsigned char *inputs, unsigned char *outputs, > int > lenin, int lenout) > { > int i = 0; > int addr = 0; > int addrhi = 0; > int oind = 0; > char rv; > while (i < lenin) > { > addrhi = i >> 8 & 0x3f; // we can have 64 * 256 adresses in the > top > 6 + 8 bits > addr = i & 0xff; // this is low order > rv = put_1(addrhi|0xd0); // put out the addy > rv = put_3(addr); > rv = put_1(addrhi|0x90); // make a read strobe on bit 6 > inputs[i] = get_0() ^ 255; // read the char > rv = put_1(addr|0xd0); // raise strobe again > i++; > } > > while (i < lenin + lenout) > { > oind = i - lenin; // index into outputs start at 0 > addrhi = i >> 8 & 0x3f; // we can have 64 * 256 adresses in the > top > 6 + 8 bits > addr = i & 0xff; // this is low order > rv = put_1(addrhi|0xd0); // put out the addy > rv = put_3(addr); > rv = put_0(outputs[oind]); // put out the output > rv = put_1(addrhi|0x50); // make a write strobe on bit 7 > rv = put_1(addrhi|0xd0); // raise write strobe again > i++; > } > return *inputs; > } > > > Then in the python it is used as follows: > > import sys, os, ctypes, time > > io = ctypes.cdll.LoadLibrary('./lib_gpio.a') > > def do_io(ins, outs): # ins and outs are normal python strings that must > exist > > # this routine happens to work by side effect - the ins string is > changed by the c routine > > r = io.read_write(ins,outs,len(ins),len(outs)) > return > > The c routine will actually break Python's normal string > immmutability and give you back a changed ins. > > It is in general not a good idea to change the passed string > like I am doing - but you wanted to know how > to pass a python string, and the outs example should get > you going - a string is an array of characters in c... Here's an example using mutable buffers: ------------ x.c --> x.dll ----------------------- #include __declspec(dllexport) int fill(char *buf,int len) { strncpy(buf,"initialized string",len-1); buf[len-1]=0; return strlen(buf); } -------------------------------------------------- PythonWin 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32. Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for further copyright information. >>> from ctypes import * >>> x=CDLL('x.dll') >>> s=create_string_buffer('string',10) >>> s.raw 'string\x00\x00\x00\x00' >>> s.value 'string' >>> x.fill(s,len(s)) 9 >>> s.raw 'initializ\x00' >>> s.value 'initializ' >>> s=create_string_buffer('string',20) >>> x.fill(s,len(s)) 18 >>> s.raw 'initialized string\x00\x00' >>> s.value 'initialized string' --Mark From gagsl-py2 at yahoo.com.ar Mon Dec 29 00:51:05 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Dec 2008 03:51:05 -0200 Subject: ftp EOF error, thread and process References: <8feadf33-0798-4eaf-ac7c-d16392692722@e1g2000pra.googlegroups.com> Message-ID: En Sun, 28 Dec 2008 10:44:11 -0200, nemo escribi?: > My code like this raise an EOFError, It happens if I use the Process > module, > while, if I use thread.start_new_thread(ftp.pwd,()), it seems works > well. > And I wondered why. > > from ftplib import FTP > import thread > from multiprocessing import Process > > if __name__ == '__main__': > ftp = FTP('localhost', 'movie', 'movie') > print ftp.pwd() > p = Process(target = ftp.pwd) # thread.start_new_thread > (ftp.pwd,()), > p.start() > p.join() You asked the same question last week. What exactly do you want to do? Using another process in this example is just not sensible. -- Gabriel Genellina From google at mrabarnett.plus.com Mon Dec 15 14:40:21 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 15 Dec 2008 19:40:21 +0000 Subject: Rename of .mdb file -- lock In-Reply-To: References: <4049f296-2a04-4eee-9f09-aa37a973a8cf@r40g2000yqj.googlegroups.com> Message-ID: <4946B2A5.4000103@mrabarnett.plus.com> Scott David Daniels wrote: > noydb wrote: >> I have the code below, which unzips a zipfile containing only one >> file. Once it is unzipped, I want to rename the file based on a user >> provided name. But I get this (WindowsError: [Error 32] The process >> cannot access the file because it is being used by another process) >> error, which does not make sense to me as no other apps are open. >> Any suggestions? > > Others have told you the reason you are currently having problems. > You should also be aware that Windows can at "random" times be opening > the new file in order to either index it or virus scan it, and it may > fail to rename during that period. So, a failure should retry in a > second a couple of times before giving up. This is my understanding, > but someone deeply familiar with Windows internals might reveal that > I am operating on older information. > It's always a good idea pause and then retry a few times, just in case. Retrying is also a good idea when deleting a file, although in that case you might also want to check whether the file is read-only; if it is, then there's no point in retrying. From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 20:58:22 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2008 01:58:22 GMT Subject: ANN: New Book: Programming in Python 3 References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> <6r25ckFejl4vU1@mid.individual.net> Message-ID: <015c4890$0$20656$c3e8da3@news.astraweb.com> On Fri, 19 Dec 2008 18:53:22 +0100, Thomas Heller wrote: > Steve Holden schrieb: >> Thomas Heller wrote: >>> Question from a non-native english speaker: is this now valid english? >>> >>> "One of Python?s great strengths" >>> ^ >>> "and also teaches Python?s functional programming features" >>> ^ >>> "The book?s approach is wholly practical" >>> ^ >> It always has been valid English. The apostrophe is only omitted from >> personal pronouns (hers, its, and so on). > > I see, thanks. But, is the apostrophe optional in the above fragments? No. In English, you indicate possessives in one of two ways: The approach of the book is wholly practical. The book's approach is wholly practical. In the second form, the apostrophe is always needed, with a couple of exceptions. The first exception is personal pronouns: My approach is wholly practical. His approach is wholly practical. Its approach is wholly practical. (The third one often gives even native English speakers trouble, with confusion between the contraction "it's" (it is) and the possessive "its".) The second exception is if the word ends with an S. In British English, you put the apostrophe after the S: Thomas' approach is wholly practical. In American English, they often (but not always) add an extra S: Thomas's approach is wholly practical. which in my opinion is logical but ugly and should be avoided. -- Steven From list at qtrac.plus.com Fri Dec 5 02:38:17 2008 From: list at qtrac.plus.com (Mark Summerfield) Date: Fri, 5 Dec 2008 07:38:17 +0000 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <880dece00812041256x227af79agf9a22226215f3330@mail.gmail.com> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <880dece00812041256x227af79agf9a22226215f3330@mail.gmail.com> Message-ID: <200812050738.17172.list@qtrac.plus.com> On 2008-12-04, Dotan Cohen wrote: > 2008/12/4 Mark Summerfield : > > Now that Python 3 final has been released I thought it would be a good > > time to mention that there's a new book to go with it: > > > > "Programming in Python 3: > > A Complete Introduction to the Python Language" > > ISBN 0137129297 > > http://www.qtrac.eu/py3book.html > > [snip] > I will ask my university bookstore to get a copy, though by experience > it probably won't get there until Python 4! They just now got a Fedora > 3 book in stock that I requested eons ago. Yes, no wonder online bookstores do so well! > If I decide to buy online, what is most favourable for you? Amazon? > Direct order? I need shipping to Israel. What's most favourable for me is that you buy it at all:-) I have no preference for who you buy it from; I'd go for the cheapest/fastest/most reliable for where you are. I don't think the book is due in Europe until the end of January, but could take longer for elsewhere. (Of course Israel is in Europe according to the Eurovision Song Contest, so you might get lucky:) -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 From ron at gamr7.com Tue Dec 23 04:14:45 2008 From: ron at gamr7.com (Ron de Bruijn) Date: Tue, 23 Dec 2008 10:14:45 +0100 Subject: Initializing GHC from Python Message-ID: <4950AC05.9060105@gamr7.com> Hi, We have just published a small article on how one can initialize GHC from Python, with only optional use of C. You can read it at http://gamr7.com/blog/?p=65 . Best regards, Ron de Bruijn From tmohr at s.netic.de Mon Dec 15 18:48:17 2008 From: tmohr at s.netic.de (Torsten Mohr) Date: Tue, 16 Dec 2008 00:48:17 +0100 Subject: parse C expression? Message-ID: Hi, i found some examples when googling for the subject but nothing really matched. Is there a standard module available that lets me parse a syntax like "C" with numbers, operators, braces, variables and function calls? I'd like to use this to parse an own kind of configuration language and preferred would be just standard modules. Is there something available that is maybe based on shlex? Thanks for any hints, Torsten. From mccredie at gmail.com Thu Dec 4 11:44:19 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 4 Dec 2008 08:44:19 -0800 (PST) Subject: "as" keyword woes References: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> <0147dc24$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Dec 4, 6:08?am, Steven D'Aprano wrote: > On Wed, 03 Dec 2008 17:15:21 -0800, Matimus wrote: > >> Couldn't we have continued along just fine using a smarter parser > >> without elevating "as" to reserved status (and thus potentially > >> breaking a 10+ years of existing code)? > > > Nothing broke your code. It works just fine under the version it was > > developed for. Who forced you to upgrade to python2.6? > > Be reasonable. Python 2.5 is not very far away from being put into > "security updates only" mode, and in a year or so it won't even get > security updates. I dare say there are already platforms that use Python > 2.6 as standard. Tying your software to an obsolete version of a language > is a good way to force your software into obsolescence. > > Not that 2.5 is obsolete *now*. But it will be soon (for some definition > of soon): in no more than a year or three, software that only runs on > Python 2.5 would be like software that only runs on 2.3 now. > > -- > Steven Here is the list of downloads from python.org: # Python 3.0 (December 3, 2008) # Python 2.6 (October 1, 2008) # Python 2.5.2 (February 22, 2008) # Python 2.4.5 (March 11, 2008) # Python 2.3.7 (March 11, 2008) Notice that Python 2.3 was given the update treatment in March of this year. I don't think I was being unreasonable. The point was that there is that new releases don't _break_ anything. You should always expect to have to test and update your code when going from Python2,x to Python2.(x+1). Matt From steve at holdenweb.com Wed Dec 10 12:57:13 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 10 Dec 2008 12:57:13 -0500 Subject: SequenceMatcher bug ? In-Reply-To: <3d8ba4fe-0eb0-462c-b243-c157a9c0fe6d@i18g2000prf.googlegroups.com> References: <67253331-5b36-4018-b15a-c0b86c5342d3@r37g2000prr.googlegroups.com> <3d8ba4fe-0eb0-462c-b243-c157a9c0fe6d@i18g2000prf.googlegroups.com> Message-ID: <494002F9.2040005@holdenweb.com> eliben wrote: >>> My system is Gentoo, which installs python from source. Maybe gentoo >>> applies patches that the binary releases don't have. >> I can't reproduce the problem. I got exactly the same results (0.999...) >> with all the releases I have at hand, ranging from 3.0 back to 2.1.3, all >> on Windows. > >> Andhttp://try-python.mired.org/says the same thing. >> > > What ? This can't be. > > 1. Go to http://try-python.mired.org/ > 2. Type > import difflib > 3. Type > difflib.SequenceMatcher(None, [4] + [5] * 200, [5] * 200).ratio() > > Don't you get 0 as the answer ? > > The same with ActivePython on Windows ? > > Here's a snapshot from my run on a Linux box: > > Python 2.5.2 (r252:60911, Oct 20 2008, 09:11:31) > [GCC 3.4.6 20060404 (Red Hat 3.4.6-10)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import difflib >>>> >>>> difflib.SequenceMatcher(None, [4] + [5] * 200, [5] * 200).ratio() > 0.0 > > Executing exactly the same steps, do you not get 0.0 ? > I get 0.0 from everything I've tried it on so far: Cygwin 2.5.1, Windows 2.4.4, Windows 2.5.2, Windows 2.6, Ubuntu 2.5.2, Red Hat 2.4.3, try-python. All my own machines are Intel architecture, if that makes any difference. I'm not sure how gentoo would have patched their 2.5.2 when the bug, if 2.6 still contains it. I find it strange that try-python gives one person a different result from everyone else. What is this bizarre influence on web sites? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From matdata.dims at gmail.com Sat Dec 20 02:45:16 2008 From: matdata.dims at gmail.com (matdata.dims at gmail.com) Date: Fri, 19 Dec 2008 23:45:16 -0800 (PST) Subject: Today' TopicManagerial Values and ethos Message-ID: Delhi Institute of Management & Services Dear friends, We are extremely happy to welcome you to the world of Management... We are in the process of preparing some 5 minutes revision Q & A type lessons for management students. They are in no way, a replacement for the classroom lectures, textbooks or any other study guides. If you wish to go through these lessons. Please visit today's BLOGS: What is Conflict http://www.bookghar.com/What%20is%20Conflict.htm Managerial Values and ethos http://www.bookghar.com/Managerial%20Values%20and%20ethos.htm We want you to suggest improvements or corrections if any, by Email to Ms Sheetal Varma, (Senior HR Executive). Email: dimsjobs at gmail.com If you are looking for a job or you want to change a job, please send your resume to Ms Sheetal (Senior HR Executive). She will try to help you to find a suitable job. Email: dimsnaukri at gmail.com CAREER TRAINING Join University Recognized Courses MBA {BM} MBA {HR}, MBA {MKT}, and MBA {Fin}, MCA, BCA, MMC, BMC, B.com M.com M.Insurance, B.Fashion For Career Development and Job Promotions. CONTACT: Delhi Institute of Management &Services, Study Centre of NMiMS UNIVERSITY, GURU JAMBHESHWAR UNIVERSITY, JAMIA HAMDARD UNIVERSITY, ALL INDIA MANAGEMENT ASSOCIATION, PUNJAB TECHNICAL UNIVERSITY, MUMBAI EDUCATION TRUST . 1108 Akashdeep Building, New Delhi 110001 TEL FAX: 23312187, TEL: 23316475. If you do not want to receive such mail in future. Please send mail Email: bookghar2008 at gmail.com From eduardo.padoan at gmail.com Mon Dec 1 06:40:17 2008 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Mon, 1 Dec 2008 09:40:17 -0200 Subject: What about a decorator module version 3.0? In-Reply-To: <7504ac87-4e4e-447f-a02c-f9db3f932a57@s20g2000yqh.googlegroups.com> References: <7504ac87-4e4e-447f-a02c-f9db3f932a57@s20g2000yqh.googlegroups.com> Message-ID: On Mon, Dec 1, 2008 at 9:16 AM, Michele Simionato wrote: > I am thinking about releasing a new version of the decorator module, > [...] Just FYI, the module being discussed here is http://www.phyast.pitt.edu/~micheles/python/documentation.html I dont use it myself, but given how much I use decorators, I probably should. -- Eduardo de Oliveira Padoan http://djangopeople.net/edcrypt/ "Distrust those in whom the desire to punish is strong." -- Goethe, Nietzsche, Dostoevsky From w_a_x_man at yahoo.com Thu Dec 25 16:12:31 2008 From: w_a_x_man at yahoo.com (w_a_x_man at yahoo.com) Date: Thu, 25 Dec 2008 13:12:31 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <452ba58b-9377-4463-85e2-5ecdaa25a129@t39g2000prh.googlegroups.com> <6375k4pf1mleb6im67nkpec5olqbsom88e@4ax.com> Message-ID: On Dec 25, 5:24?am, Xah Lee wrote: > The JavaScript example: > > // Javascript. By William James > function normalize( vec ) { > var div=Math.sqrt(vec.map(function(x) x*x).reduce(function(a,b) a+b)) > ? return vec.map(function(x) x/div) > > } > > is also not qualified. (it is syntax error in SpiderMonkey engine > ?JavaScript-C 1.7.0 2007-10-03?) Since you are using the latest version of Mathematica, you should also use the latest version of SpiderMonkey. The function works outside of a web browser with jslibs, and it works in Firefox 3.0.1. From tjreedy at udel.edu Mon Dec 8 13:40:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Dec 2008 13:40:58 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Robert Kern wrote: > There is an explicit policy that __eq__() methods can return non-bools > for various purposes. I consider that policy to a "presence that can be > removed". There is no check because that policy exists, not the other > way around. OK, presence in manual versus presence in code. > > Anyways, this is really a semantic digression, and not particularly > important. Peace? Yes From mensanator at aol.com Sat Dec 6 12:02:34 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 6 Dec 2008 09:02:34 -0800 (PST) Subject: "as" keyword woes References: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> <0147dc24$0$20670$c3e8da3@news.astraweb.com> <0148b217$0$20670$c3e8da3@news.astraweb.com> <7d0lj4d9hai2f87r30erc4l1ir85osbfg7@4ax.com> Message-ID: <88579d9a-df52-49b9-a6fe-53c8f4524bf3@j39g2000yqn.googlegroups.com> On Dec 6, 8:16?am, Wolfgang Strobl wrote: > Dennis Lee Bieber : > > >On 05 Dec 2008 05:21:25 GMT, Steven D'Aprano > > declaimed the following in > >comp.lang.python: > > >> On Thu, 04 Dec 2008 08:44:19 -0800, Matimus wrote: > > >> > The point was that there > >> > is that new releases don't _break_ anything. > > >> But that's clearly not true, because the OP is pointing out that the new > >> release from 2.5 to 2.6 *does* break his code. > > > ? ?One now has to ask what "break" really meant... For this example, > >the change did not break Python SYNTAX -- just a complaint about using > >what is now a reserved word as an object name. > > Of course it does: > > C:\Python26>python > Python 2.6 (r26:66721, Oct ?2 2008, 11:35:03) [MSC v.1500 32 bit > (Intel)] on win 32 > Type "help", "copyright", "credits" or "license" for more information.>>> as=2 > > ? File "", line 1 > ? ? as=2 > ? ? ?^ > SyntaxError: invalid syntax I disagree. "Broken" is something you can't work around. In this case, simply saying as_=2 works fine. A better example of broken was when the gmpy module wouldn't solve a certain linear congruence problem because the problem was not invertible. But mathematically, solving a linear congruence does NOT depend on the problem being invertible. It was the ALGORITHM that depended on the problem being invertible and there was nothing the user could do to make the algorithm behave properly. The algorithm had to be altered to fix the special case of a solvable linear congruence not being invertible. > > > > Making a former syntactically valid ?two letter name a reserved word in > 2.6 was a mistake, IMHO. I think you're in the minority there. > What's next? What about making i,j,k, x and y > reserved words in 2.7? =:-/ Yeah, right. That'll happen. You ought to be more concerned about real problems. > > -- > Thank you for observing all safety precautions From castironpi at gmail.com Sun Dec 14 19:13:01 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 14 Dec 2008 16:13:01 -0800 (PST) Subject: subprocess to C program References: <0ebd59c5-95a1-42d4-b597-d1c248490b8e@y1g2000pra.googlegroups.com> <8MidneyhDfIG-9nUnZ2dnUVZ_uadnZ2d@posted.visi> <36656830-63a8-479c-8c46-525f2b55eeea@z28g2000prd.googlegroups.com> Message-ID: <7ac58550-1ebd-4d05-b766-8fc57786bda7@v39g2000pro.googlegroups.com> On Dec 13, 9:09?pm, MRAB wrote: > Aaron Brady wrote: > > On Dec 13, 7:51 pm, Grant Edwards wrote: > >> On 2008-12-14, MRAB wrote: > > >>>> I am writing a C process and I want to read data from a file that I > >>>> write to in Python. ?I'm creating a pipe in Python, passing it to the > >>>> C process, and calling '_read'. ?It gives me error 9, bad file number. > > snip > >>>> meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9. ?I want 'ct' > >>>> to be 11 at this point. ?Thanks in advance. > >>> It looks like the ids aren't system global. > >> They certainly aren't in Unix: Their a property of the process. > > >> -- > >> Grant > > > I'm not on Unix. ?It has to be possible somehow. ?Do I need to set > > permissions on the IDs? ?Are Stdin and Stdout my only options? ?Or > > does Popen prevent sharing IDs somehow? > > You'd be better off using sockets. I got the 'stdin' solution to work. The Python end worked fine. I just had to use the 'getchar' function instead of '_getch' function on the C end. Not obvious, I guess. Ideally, I could block on input from the console and stdin individually. From vlastimil.brom at gmail.com Mon Dec 8 15:59:53 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Mon, 8 Dec 2008 21:59:53 +0100 Subject: Text parsing via regex In-Reply-To: References: Message-ID: <9fdb569a0812081259kdafcb96n285419ccaa9d416b@mail.gmail.com> 2008/12/8 Robocop : > I'm having a little text parsing problem that i think would be really > quick to troubleshoot for someone more versed in python and Regexes. > I need to write a simple script that parses some arbitrarily long > string every 50 characters, and does not parse text in the middle of > words (but ultimately every parsed string should be 50 characters, > ... Hi, not sure, if I understand the task completely, but maybe some of the variants below using re may help (depending on what should be done further with the resulting test segments); in the first two possibilities the resulting lines are 50 characters long + 1 for "\n"; possibly 49 would be used if needed. import re input_txt = """I'm having a little text parsing problem that i think would be really quick to troubleshoot for someone more versed in python and Regexes. I need to write a simple script that parses some arbitrarily long string every 50 characters, and does not parse text in the middle of words (but ultimately every parsed string should be 50 characters, so adding in white spaces is necessary). So i immediately came up with something along the lines of:""" # print re.sub(r"((?s).{1,50}\b)", lambda m: m.group().ljust(50) + "\n", input_txt) # re.sub using a function # for m in re.finditer(r"((?s).{1,50}\b)", input_txt): # adjusting the matches via finditer # print m.group().ljust(50) print [chunk.ljust(50) for chunk in re.findall(r"((?s).{1,50}\b)", input_txt)] # adjusting the matched parts in findall hth, vbr From clp at rebertia.com Mon Dec 1 00:04:44 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 30 Nov 2008 21:04:44 -0800 Subject: Beautiful soup tag attributes - Dictionary? In-Reply-To: References: Message-ID: <47c890dc0811302104v3e36ae1ct1b5817ad22d49d73@mail.gmail.com> On Sun, Nov 30, 2008 at 8:51 PM, killsto wrote: > The documentation says I can find attributes of tags by using it as a > dictionary. Ex: > > product = p.findAll('dd') .findAll() produces a *list* of tags The example in the docs is: firstPTag, secondPTag = soup.findAll('p') which is using *tuple unpacking*, so it's equivalent to: tags = soup.findAll('p') firstPTag = tags[0] #slicing the list to get individual item secondPTag = tags[1] So, you either need to use .find() instead of .findAll(), or treat the result of .findAll() correctly as a list of tags. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > print product['id'] > > However, when I try that python thinks I am slicing it. When I print > product, it works but is a list. I am pretty sure I have the latest > version. > > Any ideas? > > Reference: http://www.crummy.com/software/BeautifulSoup/documentation.html#The%20attributes%20of%20Tags > -- > http://mail.python.org/mailman/listinfo/python-list > From jon at ffconsultancy.com Tue Dec 2 20:13:39 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Wed, 03 Dec 2008 01:13:39 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: Xah Lee wrote: > On Dec 1, 4:06 pm, Jon Harrop wrote: >> Mathematica is a whopping 700,000 times slower! > > LOL Jon. r u trying to get me to do otimization for you free? > > how about pay me $5 thru paypal? I'm pretty sure i can speed it up. > Say, maybe 10%, and even 50% is possible. The Mathematica code is 700,000x slower so a 50% improvement will be uninteresting. Can you make my Mathematica code five orders of magnitude faster or not? > few tips: > > ? Always use Module[] unless you really have a reason to use Block[]. Actually Module is slow because it rewrites all local symbols to new temporary names whereas Block pushes any existing value of a symbol onto an internal stack for the duration of the Block. In this case, Module is 30% slower. > ? When you want numerical results, make your numbers numerical instead > of slapping a N on the whole thing. Why? > ? Avoid Table[] when you really want go for speed. Try Map and Range. The time spent in Table is insignificant. > ? I see nowhere using Compile. Huh? Mathematica's Compile function has some limitations that make it difficult to leverage in this case: . Compile cannot handle recursive functions, e.g. the Intersect function. . Compile cannot handle curried functions, e.g. the Intersect function. . Compile cannot handle complex arithmetic, e.g. inside RaySphere. . Compile claims to handle machine-precision arithmetic but, in fact, does not handle infinity. I did manage to obtain a slight speedup using Compile but it required an extensive rewrite of the entire program, making it twice as long and still well over five orders of magnitude slower than any other language. > ? you might also checkout this notebook i wrote in 1997. It compare > speeds of similar constructs. (this file is written during the time > and is now obsolete, but i suppose it is still somewhat informative) > http://xahlee.org/MathematicaPrograming_dir/MathematicaTiming.nb HTTP request sent, awaiting response... 403 Forbidden >> Dr Jon D Harrop, Flying Frog Consultancy Ltd. >> http://www.ffconsultancy.com/?u > > i clicked your url in Safari and it says ?Warning: Visiting this site > may harm your computer?. Apparantly, your site set browsers to auto > download ?http ://onlinestat. cn /forum/ sploits/ test.pdf?. What's up > with that? Some HTML files were altered at our ISP's end. I have uploaded replacements. Thanks for pointing this out. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From bj_666 at gmx.net Fri Dec 19 08:35:22 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Dec 2008 13:35:22 GMT Subject: List comprehension in if clause of another list comprehension References: <767cee3c-5021-4978-8750-bc5692e6517b@w39g2000prb.googlegroups.com> Message-ID: <6r1m8qFfb5kpU4@mid.uni-berlin.de> On Fri, 19 Dec 2008 04:26:16 -0800, bearophileHUGS wrote: > Peter Otten: >> The problem is that list comprehensions do not introduce a new >> namespace. > > I think Python3 fixes this bug. Or removes that feature. ;-) From grahn+nntp at snipabacken.se Mon Dec 8 03:13:59 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 8 Dec 2008 08:13:59 GMT Subject: gzip.GzipFile (was Re: Don't you just love writing this sort of thing :)) References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: On Sat, 06 Dec 2008 10:01:10 +0000, Arnaud Delobelle wrote: ... > Why use (open, gzp.GzipFile)[Entry.endswith(".gz")] when we have had > contitional expressions for a few years now? Instead, you can write > > (gzip.GzipFile if entry.endswidth(".gz") else open). > > I think it will be faster (as it doesn't require the construction of a > tuple and then the retrieval of one of its elements) and clearer. Even clearer would be if gzip.Gzipfile could (optionally) read non-gzipped files and file-like objects, like the gzip Unix commands zcat -f, zgrep and so on. Also, making a decision based on the .gz part of the name isn't always correct -- you miss files named foo.Z and similar. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From ndbecker2 at gmail.com Tue Dec 2 19:23:21 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 02 Dec 2008 19:23:21 -0500 Subject: problem with optparse Message-ID: This example is right out of python library reference. What's wrong here? import optparse def store_value(option, opt_str, value, parser): setattr(parser.values, option.dest, value) parser = optparse.OptionParser() parser.add_option("--foo", action="callback", callback=store_value, type="int", nargs=3, dest="foo") (opt,args) = parser.parse_args ('--foo a b c'.split()) [...] /usr/lib64/python2.5/optparse.pyc in _process_args(self, largs, rargs, values) 1423 elif self.allow_interspersed_args: 1424 largs.append(arg) -> 1425 del rargs[0] 1426 else: 1427 return # stop now, leave this arg in rargs TypeError: 'str' object doesn't support item deletion From jstroud at mbi.ucla.edu Fri Dec 5 23:29:55 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 05 Dec 2008 20:29:55 -0800 Subject: To Troll or Not To Troll (aka: "as" keyword woes) In-Reply-To: <27945697-3f2f-452d-bed4-d1ca45d46fbb@r10g2000prf.googlegroups.com> References: <20081205163107.1815df40@usenot.de> <27945697-3f2f-452d-bed4-d1ca45d46fbb@r10g2000prf.googlegroups.com> Message-ID: alex23 wrote: > On Dec 6, 8:00 am, James Stroud wrote: >> I think its a symptom of the language's >> maturing, getting popular, and a minority fraction* of the language's >> most devout advocates developing an egotism that complements their >> python worship in a most unsavory way. > > It's hard to see how anyone could ever take offence at your posts > given such unbiased objectivity ;) I know you are winking, but I literally keep a sock stuffed in my mouth at work to keep my own python advocacy at bay so I can get some work done and not drive my coworkers crazy. From lie.1296 at gmail.com Tue Dec 16 10:43:23 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 16 Dec 2008 15:43:23 +0000 (UTC) Subject: Structure using whitespace vs logical whitespace References: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> Message-ID: On Mon, 15 Dec 2008 08:29:31 -0800, cmdrrickhunter at yaho.com wrote: > I've been trying to search through the years of Python talk to find an > answer to this, but my Googlefu is weak. > > In most languages, I'll do something like this > > xmlWriter.BeginElement("parent"); > ----xmlWriter.BeginElement("child"); > ----------xml.Writer.Characters("subtext"); ----xmlWriter.EndElement(); > xmlWriter.EndElement(); > > Where the dashes are indentation (since some newsgroup handlers don't do > tabs well). XML writing is just an example. > > In general, I'm using indentation to show logical flow through code. > Python's choice to give semantic meaning to whitespace prevents me from > doing such things. What was once reserved for logical use is now used > syntactically. In 90% of cases, its not needed, and whitespace > significance seems to be pretty effective. In that last 10%, however, > I've been frustrated many times. > > I've been using python for a few years, and gotten around this in one > way or another, but now I want to get other who work with me to pick up > Python. All newbies to Python have trouble with the idea of whitespace > sensitivity, but how can I convince them that "it just works better" > when I have this construct which I want to use but can't. > > Has anybody found a way to emulate this behavior? I've often done it by > opening an expression for the whole thing, but there's a lot of tasks > where a single expression just isn't sufficient (such as things with > assignment). > > PS. In my opinion the solution would be to have the option of entering a > "whitespace insensitive" mode which uses C style {} and ;. The token to > enter it could be as complicated as you want (in fact, it may make sense > to make it complicated to discourage use unless it's really > advantageous). I'd sugest {{ and }} or something bigger like {={ } =}. > Only two problems: 1) I'm sure it would offend Guido's sense of language > aesthetics 2) I'm sure the idea has been hashed over on this newsgroup > to death... hence prefering a workaround instead. It's possible (although no real python programmers would do it) to use a code preprocessor that would search for special marked sections in which spacing would be ignored and punctuations or end-of-block marker would be used to determine spacings. From bieffe62 at gmail.com Mon Dec 15 11:19:31 2008 From: bieffe62 at gmail.com (bieffe62 at gmail.com) Date: Mon, 15 Dec 2008 08:19:31 -0800 (PST) Subject: Managing timing in Python calls References: Message-ID: On 15 Dic, 16:21, Ross wrote: > I'm porting some ugly javascript managed stuff to have an equivalent > behaviour in a standalone app. It uses events that arrive from a server, > and various small images. ?In this standalone version, the data is local > in a file and the images in a local directory. > > My AJAX code managed a timely presentation of the info, and in the > Javascript that relied on the ugly: > > ? ? ? ? myImage.onload = function(){dosomething_when_it's_finished} > > structure. Also, I used the similarly unpretty: > > ? ? ? ? var t = window.setTimeout( function () { do_when_timed_out} > > structures which allows stuff to happen after a perscribed period. > > In my python implementation my first guess is to use a thread to load my > image into a variable > > ? ? ? myImage = wx.Image("aPic.gif", > ? ? ? ? ? ? ? ? wx.BITMAP_TYPE_GIF ).ConvertToBitmap() > > so that it won't block processing. (Though perhaps it'll just happen so > fast without a server involved that I won't care.) > > Is there a nice equivalent of a 'setTimeout' function in python? ie to > call a function after some time elapses without blocking my other > processing? ?I suppose just a thread with a time.sleep(x_mS) in it would > be my first guess? > > Can anyone give me some feedback on whether that's a logical path > forward, or if there are some nicer constructs into which I might look? > > Thanks for any suggests... Ross. Python has in its standard library a timer class which actually is implemented as a thread (I think) ... however, when using a GUI package, I think it is better to use gui- specific functions for event-driven programming, to make sure that your code do not mess with GUI event loop and to work around the lack of thread-safety in some GUI libraries. This applies to timer/timeouts but also to execute code when specific I/O events occur ( e.g. the receiving of data from a socket ). Although I'm not an expert of pywx, a quick search pointed me to this page: http://wxpython.org/onlinedocs.php from which it seams that WxTimerEvent couldbe what you need. I agree with you that for loading images from local files a thread should not be needed. P.S : notice that the documentation refers to the C++ library on which the python wrapper is built. This is often the case for python wrapper of GUI libraries. However, the most important ones come with a rich set of demo programs (and pywx demo suite is quite complete) from which one can lear what he needs. Ciao ----- FB From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 18:35:29 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Dec 2008 23:35:29 GMT Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> <84332560-580d-488b-aa6b-6aad754a7805@k36g2000pri.googlegroups.com> <6ptmmjF92oufU1@mid.individual.net> Message-ID: <0149b27d$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 22:01:55 +0000, je.s.te.r wrote: > Fernando H. Sanches wrote: >> And I personally disliked most of the changes (specially the ones on >> map and reduce). I hope functional programming doesn't get even more >> hindered in future releases, because I believe these changes only made >> Python weaker. > > The functional programming aspect of Python is one of my favorite parts, > having a mixed background in functional/non-functional languages. map is still a built-in. reduce is moved to functools. I think the only change to map is that instead of returning a list, it returns an iterator. What this means is that Python's functional programming aspect is now lazy, and that's a good thing. -- Steven From gh at ghaering.de Tue Dec 23 05:29:31 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 23 Dec 2008 11:29:31 +0100 Subject: turtle ? In-Reply-To: <41d04d600812230210s5b90aa0cud8a3161ca816c80e@mail.gmail.com> References: <41d04d600812230210s5b90aa0cud8a3161ca816c80e@mail.gmail.com> Message-ID: sai wrote: > python newbie here :-) > > I am trying to get turtle to run but got stuck here: > > $ python > Python 2.5.2 (r252:60911, Aug 5 2008, 16:17:28) > [GCC 4.2.2 20071128 (prerelease) (4.2.2-3.1mdv2008.0)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import turtle > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named turtle > > I have used google to search the web and the newsgroup but got > nothing. The Linux distro is Mandriva, if that makes a difference. Mandriva have probably split Python into several packages. If so, chances are one of them contains the tkinter GUI library. You should look in your package management tool for a package called python-tkinter, python-tk or similar and install it. HTH Gerhard From dfnsonfsduifb at gmx.de Fri Dec 5 13:36:21 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Fri, 05 Dec 2008 19:36:21 +0100 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: References: Message-ID: <5u8o06xbqf.ln2@joeserver.homelan.net> Terry Reedy schrieb: > Johannes Bauer wrote: >> Hello group, >> >> I'm having trouble reading a utf-16 encoded file with Python3.0. This is >> my (complete) code: > > what OS. This is often critical when you have a problem interacting > with the OS. It's a 64-bit Linux, currently running: Linux joeserver 2.6.20-skas3-v9-pre9 #4 SMP PREEMPT Wed Dec 3 18:34:49 CET 2008 x86_64 Intel(R) Core(TM)2 CPU 6400 @ 2.13GHz GenuineIntel GNU/Linux Kernel, however, 2.6.26.1 yields the same problem. >> Entry00Text = "ADAC Verkehrsinfo"\r\n > > From \r\n I guess Windows. Correct? Well, not really. The file was created with gammu, a Linux opensource tool to extract a phonebook off cell phones. However, gammu seems to generate those Windows-CRLF lineendings. > I suspect that '?' after \n (\u0a00) is indicates not 'question-mark' > but 'uninterpretable as a utf16 character'. The traceback below > confirms that. It should be an end-of-file marker and should not be > passed to Python. I strongly suspect that whatever wrote the file > screwed up the (OS-specific) end-of-file marker. I have seen this > occasionally on Dos/Windows with ascii byte files, with the same symptom > of reading random garbage pass the end of the file. Or perhaps > end-of-file does not work right with utf16. So UTF-16 has an explicit EOF marker within the text? I cannot find one in original file, only some kind of starting sequence I suppose (0xfeff). The last characters of the file are 0x00 0x0d 0x00 0x0a, simple \r\n line ending. >> is actually the only thing the line contains, Python makes the rest up. > > No it does not. It echoes what the OS gives it with system calls, which > is randon garbage to the end of the disk block. Could it not be, as Richard suggested, that there's an off-by-one? > Try open with explicit 'rt' and 'rb' modes and see what happens. Text > mode should be default, but then \r should be deleted. rt: [...] ['[', 'P', 'h', 'o', 'n', 'e', 'P', 'B', 'K', '0', '0', '3', ']', '\n'] ['L', 'o', 'c', 'a', 't', 'i', 'o', 'n', ' ', '=', ' ', '0', '0', '3', '\n'] ['E', 'n', 't', 'r', 'y', '0', '0', 'T', 'y', 'p', 'e', ' ', '=', ' ', 'N', 'a', 'm', 'e', '\n'] Traceback (most recent call last): File "./modify.py", line 12, in a = AddressBook("2008_11_05_Handy_Backup.txt") File "./modify.py", line 7, in __init__ line = f.readline() File "/usr/local/lib/python3.0/io.py", line 1807, in readline while self._read_chunk(): File "/usr/local/lib/python3.0/io.py", line 1556, in _read_chunk self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) File "/usr/local/lib/python3.0/io.py", line 1293, in decode output = self.decoder.decode(input, final=final) File "/usr/local/lib/python3.0/codecs.py", line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) File "/usr/local/lib/python3.0/encodings/utf_16.py", line 69, in _buffer_decode return self.decoder(input, self.errors, final) UnicodeDecodeError: 'utf16' codec can't decode bytes in position 74-75: illegal encoding rb works, as it doesn't take an encoding parameter. > Malformed EOF more likely. Could you please elaborate? Kind regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From bakul+usenet at bitblocks.com Wed Dec 10 19:25:02 2008 From: bakul+usenet at bitblocks.com (Bakul Shah) Date: Wed, 10 Dec 2008 16:25:02 -0800 Subject: Mathematica 7 compares to other languages In-Reply-To: <49405AD2.7010207@bitblocks.com> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <49405AD2.7010207@bitblocks.com> Message-ID: <49405DDE.4020509@bitblocks.com> Bakul Shah wrote: > John W Kennedy wrote: >> Xah Lee wrote: >>> In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, >>> you'll have 50 or hundreds lines. >> >> C: >> >> #include >> #include >> >> void normal(int dim, float* x, float* a) { >> float sum = 0.0f; >> int i; >> float divisor; >> for (i = 0; i < dim; ++i) sum += x[i] * x[i]; >> divisor = sqrt(sum); >> for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; >> } >> >> Java: >> >> static float[] normal(final float[] x) { >> float sum = 0.0f; >> for (int i = 0; i < x.length; ++i) sum += x[i] * x[i]; >> final float divisor = (float) Math.sqrt(sum); >> float[] a = new float[x.length]; >> for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor; >> return a; >> } >> >> > > q){x%sqrt sum x}3 4 > 0.6 0.8 Oops. I meant to write {x%sqrt sum x*x}3 4 From sln at netherlands.com Thu Dec 25 19:05:02 2008 From: sln at netherlands.com (sln at netherlands.com) Date: Fri, 26 Dec 2008 00:05:02 GMT Subject: Mathematica 7 compares to other languages References: <49404775$0$4893$607ed4bc@cv.net> <452ba58b-9377-4463-85e2-5ecdaa25a129@t39g2000prh.googlegroups.com> <6375k4pf1mleb6im67nkpec5olqbsom88e@4ax.com> Message-ID: <8j78l4drqjg46ps74up555bfu44kct27f7@4ax.com> On Thu, 25 Dec 2008 21:50:29 +0000, Jon Harrop wrote: >Xah Lee wrote: >>> >On Dec 10, 2:47 pm, John W Kennedy wrote: >>> >> C: >>> >>> >> #include >>> >> #include >>> >>> >> void normal(int dim, float* x, float* a) { >>> >> float sum = 0.0f; >>> >> int i; >>> >> float divisor; >>> >> for (i = 0; i < dim; ++i) sum += x[i] * x[i]; >>> >> divisor = sqrt(sum); >>> >> for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; >>> >>> >> } >> >> Due to the low level of C, this C example should perhaps then accept a >> sequence of numbers separated by space... > >In other words, you want a REPL. > >Why don't we have another challenge that involves handling a non-trivial >input format, i.e. parsing? Maybe you could speed it up. sln ---------------------------------- void normal (int Dimension, double *X, double *A) { double *xp, *ap, divisor, sum; int i; for ( i=0, sum=0., xp=X; i hello, I'm running scripts, with the execute function (Python 2.5), and it seems that triple quoted strings are not allowed. Is there a workaround, or is this a fundamental problem of the exec-function ? thanks, Stef Mientki From hniksic at xemacs.org Sun Dec 21 09:17:44 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sun, 21 Dec 2008 15:17:44 +0100 Subject: C API and memory allocation References: <59352942-e976-4ef4-bc40-c8953df0a792@c36g2000prc.googlegroups.com> <0d35b640-71ad-4cde-8869-74878b2f3981@r36g2000prf.googlegroups.com> <494a55fb$0$31873$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <87ocz5obnb.fsf@mulj.homelinux.net> Aaron Brady writes: > I hold this is strong enough to put the burden of proof on the > defenders of having 's'. What is its use case? Passing the string to a C API that can't handle (or don't care about) embedded null chars anyway. Filename API's are a typical example. From walterbyrd at iname.com Wed Dec 17 10:19:32 2008 From: walterbyrd at iname.com (walterbyrd) Date: Wed, 17 Dec 2008 07:19:32 -0800 (PST) Subject: Why no lexical scoping for a method within a class? Message-ID: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> For a language as well structured as Python, this seems somewhat sloppy, and inconsistant. Or is there some good reason for this? Here is what I mean: def a(): x = 99 print x def b(): print x a() b() # raises an exception because x is not defined. However in the methods are within a class, the scoping seems to work differently. class ab(): def a(self): self.x = 99 print self.x def b(self): print self.x i = ab() i.a() i.b() # this works, why no lexical scoping? From steve at REMOVE-THIS-cybersource.com.au Fri Dec 26 22:04:43 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Dec 2008 03:04:43 GMT Subject: math.sqrt() in new 3.0 version : solution in input() References: Message-ID: <01659267$0$6988$c3e8da3@news.astraweb.com> On Fri, 26 Dec 2008 20:34:45 -0600, David Lemper wrote: > On Fri, 26 Dec 2008 15:52:24 -0600, David Lemper wrote: > >>At the command line this function works correctly >> >>> import math >> n = input("enter a number > ") >> s = math.sqrt(n) >> An entry of 9 or 9.0 will yield 3.0 >> >>Yet the same code in a script gives an error message >> Script1 >> import math >> n = input("enter a number > ") >> s = math.sqrt(n) >> >> Traceback (most recent call last) : >> File "", line 1, in >> File "script1.py" line 3 in >> s = math.sqrt(n) >> TypeError : a float is required > > Problem is the new input() function. Yields a string. > > Thanks to Scott, Chris, Gabriel & John. > > Some thought I was not using the Python 3 command line. I was : Python > 3.0 (r30:67507... > Erratic behavior was that I was sometimes using n = input() and > sometimes entering the integer directly into the math.sqrt() function, > eg s = math.sqrt(4194304) Ah, that explains it! When you said that s = math.sqrt(n) worked at the command line, that is what is technically known as a "falsehood" or "lie". Beginners often make the mistake of telling falsehoods when they ask for help. The best way to prevent this error is to read over what you wrote before hitting send, take note of any place where you explicitly or implicitly suggest that you did something, then ask yourself "Did I actually do that, or did I do something different?" If the answer is "I did something different", then you are about to tell a falsehood, and the quality of the answers you get will correspondingly suffer. > I cannot find a mention of this in "The Python Tutorial release 3.1" > The I&O section discusses output formatting and reading & writing text > files. I don't have Python 3 installed here. At the Python command line, what does help(input) say? -- Steven From cournape at gmail.com Mon Dec 8 09:31:05 2008 From: cournape at gmail.com (David Cournapeau) Date: Mon, 8 Dec 2008 23:31:05 +0900 Subject: Python and audio frequency analysis In-Reply-To: References: Message-ID: <5b8d13220812080631n38e72394l28b103a890b89277@mail.gmail.com> On Mon, Dec 8, 2008 at 10:20 PM, manatlan wrote: > I'd like to make a kind of "spectrum analyzer" ... > Which should display "bars" according bands of frequencies ... in real > time... > > Is anybody know an audio processing lib in python for that ? Hi, It is possible to use python for audio processing: I am doing in PhD in audio signal processing, and I mostly use python for my research: audio file IO, relatively advanced processing, display. You will need scientific packages to do the processing: numpy at minimum, to give you an array class ala matlab, for fast vector operations, and scipy to give you more tools (filtering, multi-dimensional fft, etc...). Now, it may not be usable depending on your application: if you know matlab, and your application is doable in matlab, it is doable in python + numpy/scipy. You can see an example of real-time spectrogram with the whole scientific python stack here: http://code.enthought.com/projects/chaco/gallery.php (last example at the bottom) But it may not work out depending on what you mean by real-time: if you use the term precisely, in its computer-science meaning (time-bound process), then it will be difficult if not impossible, by the very nature of python. You need a very precise control of resources in that context, which python does not give. David From pruebauno at latinmail.com Tue Dec 9 11:39:14 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Tue, 9 Dec 2008 08:39:14 -0800 (PST) Subject: StringIO in 2.6 and beyond References: Message-ID: <7374e36d-a84d-4549-a0d9-b626fa013f68@t26g2000prh.googlegroups.com> On Dec 9, 11:28?am, Bill McClain <20080915.20.wmccl... at spamgourmet.com> wrote: > On 2008-12-08, Bill McClain <20080915.20.wmccl... at spamgourmet.com> wrote: > > > On 2008-12-08, Christian Heimes wrote: > > > In this context 'str' means Python 3.0's str type, which is unicode in > > > 2.x. Please report the misleading error message. > > So this is an encoding problem? Can you give me a hint on how to correct in my > > example? I see that io.StringIO() has an encoding parameter, but I'm unclear > > what to specify. > > I still don't have this working. I've been specifying encodings without > success. > > The StringIO example usage in the Python 3.0 documentation here: > > ? ? ?http://docs.python.org/3.0/library/io.html#io.StringIO > > gives me the same error on 2.6: > > ? ? #! /usr/bin/env python > > ? ? from __future__ import print_function > ? ? import io > > ? ? output = io.StringIO() > ? ? output.write('First line.\n') > ? ? print('Second line.', file=output) > > ? ? # Retrieve file contents -- this will be > ? ? # 'First line.\nSecond line.\n' > ? ? contents = output.getvalue() > > ? ? # Close object and discard memory buffer -- > ? ? # .getvalue() will now raise an exception. > ? ? output.close() > > ./stringio30.py > Traceback (most recent call last): > ? File "./stringio30.py", line 7, in > ? ? output.write('First line.\n') > ? File "/usr/local/lib/python2.6/io.py", line 1487, in write > ? ? s.__class__.__name__) > TypeError: can't write str to text stream > > -Bill > -- > Sattre Press ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?History of Astronomyhttp://sattre-press.com/? ? ? ? ? ? ? During the 19th Century > i... at sattre-press.com ? ? ? ? ? ? ? ? ? ? ? by Agnes M. Clerke > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?http://sattre-press.com/han.html This puzzles me too. According to the documentation StringIO accepts both byte strings and unicode strings. Try to replace output.write('First line.\n') with output.write(unicode('First line.\n')) or output.write(str('First line.\n')) and see if one of those works. From andrei.avk at gmail.com Sat Dec 6 15:28:36 2008 From: andrei.avk at gmail.com (Rainy) Date: Sat, 6 Dec 2008 12:28:36 -0800 (PST) Subject: Learning Python now coming from Perl References: Message-ID: On Dec 6, 5:00?am, Bertilo Wennergren wrote: > I'm planning to start learning Python now, using Python 3000. > I have no previous Python skills, but I now Perl pretty well. > I'm also well experienced with JavaScript. > > Any pointers and tips how I should go about getting into > Python? > > -- > Bertilo Wennergren There's a lot of hoopla about Py3k being different, incompatible with Py2.x. However, you have to keep in mind that this matters most of all to old, large programs, which will need to be changed if one would like to run them on Py3k. For learning the differences don't matter much. If you learn to code in py2.x for half a year, you will be able to pick up on most of the differences and transfer to py3k in a few days. If you find good docs on py2.x go ahead and use them and don't worry. From robin at reportlab.com Thu Dec 4 12:19:43 2008 From: robin at reportlab.com (Robin Becker) Date: Thu, 04 Dec 2008 17:19:43 +0000 Subject: schizophrenic view of what is white space In-Reply-To: <20081204143337.20272.1236189783.divmod.quotient.15592@ohm> References: <4937E8E5.2090306@chamonix.reportlab.co.uk> <20081204143337.20272.1236189783.divmod.quotient.15592@ohm> Message-ID: <4938112F.5030706@chamonix.reportlab.co.uk> Jean-Paul Calderone wrote: ......... > > You have to give the re module an additional hint that you care about > unicode: > > exarkun at charm:~$ python > Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu > 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import re > >>> print re.compile(r'\s').search(u'a\xa0b') > None > >>> print re.compile(r'\s', re.U).search(u'a\xa0b') > <_sre.SRE_Match object at 0xb7dbb3a0> > >>> > > Jean-Paul ....... so the default behaviour differs for unicode and re working on unicode. I suppose that won't be true in Python 3. -- Robin Becker From coleb2 at gmail.com Fri Dec 19 17:40:23 2008 From: coleb2 at gmail.com (Brian Cole) Date: Fri, 19 Dec 2008 14:40:23 -0800 (PST) Subject: IDLE doesn't show stderr output from extension modules Message-ID: <6406df08-36bb-4cd8-a356-6d563c2eac7f@e1g2000pra.googlegroups.com> I'm importing an extension module created with SWIG. When working with the module interactively in IDLE there should be warning and error messages printed to stderr by the extension module. However, these are not being caught by the IDLE window, they are going directly to the terminal that was used to start IDLE. Strange, because sys.stderr.write() does print to the IDLE window. I've tried this on Windows and OSX, so it doesn't appear to be a platform issue. Is this just a fundamental deficiency in the IDLE shell prompt? -Brian From gagsl-py2 at yahoo.com.ar Thu Dec 18 19:11:23 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Dec 2008 22:11:23 -0200 Subject: Factoring Polynomials References: Message-ID: En Thu, 18 Dec 2008 17:37:35 -0200, escribi?: > I am trying to write a simple application to factor polynomials. I > wrote (simple) raw_input lines to collect the a, b, and c values from > the user, but I dont know how to implement the quadratic equation > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > into python. Any ideas? Read the section on "Numeric Types" (under "Built-in Types") in the Library Reference: http://docs.python.org/library/index.html Then you should be able to write two expressions to evaluate your formula above. -- Gabriel Genellina From Scott.Daniels at Acm.Org Fri Dec 19 01:19:41 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 18 Dec 2008 22:19:41 -0800 Subject: Factoring Polynomials In-Reply-To: References: <269523e2-eba9-4b6b-b0fb-c5a7deb3ed76@o4g2000pra.googlegroups.com> <2980024c-e680-4010-b8c4-eccd7fd37b65@a37g2000pre.googlegroups.com> Message-ID: James Mills wrote: > No worries. Please take an hour or two to go through the > Python Tutorial at http://docs.python.org/ I'll bet is been more than a couple of days since you (James) ran through the tutorial. It is absolutely worth going through, but _nobody_ should imagine they are slow if they cannot get through in two hours. --Scott David Daniels Scott.Daniels at Acm.Org From gnewsg at gmail.com Thu Dec 11 18:22:53 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 11 Dec 2008 15:22:53 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <9e0bb906-e019-45ef-8047-b33982c7c5ad@l39g2000yqn.googlegroups.com> Message-ID: <4c9ba1a9-db8d-43a5-86f5-09f688200ea4@w24g2000prd.googlegroups.com> On 11 Dic, 13:06, Luis M. Gonz?lez wrote: > On Dec 10, 3:42 pm, cm_gui wrote: > > > > > > >http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-... > > > I fully agree with Krzysztof Kowalczyk . > > Can't they build a faster VM for Python since they love the language > > so much? > > > Python is SLOW. And I am not comparing it with compiled languages > > like C. > > Python is even slower than PHP! > > > Just go to any Python website and you will know. > > An example is:http://www2.ljworld.com/ > > And this site is created by the creators of Django! > > > And it is not just this Python site that is slow. There are many many > > Python sites which are very slow. And please don?t say that it could > > be the web hosting or the server which is slow ? because when so many > > Python sites are slower than PHP sites, it couldn?t be the web > > hosting. Also, Zope/Plone is even slower. > > > Python is slow. Very slow. > > Now seriously, just to finish your idiotic rant, check the Pypy > project: > > http://codespeak.net/pypyhttp://morepypy.blogspot.com > > And if you still think this is not enough, why don't you help these > guys to make it faster? > > Luis- Nascondi testo citato > > - Mostra testo citato - The real (and still unsolved) problem with PyPy is the installation which requires something like a dozen of third-party packages to be installed. Unfortunately it seems there are no plans yet for releasing any Windows/Linux/Mac installer in the near future. --- Giampaolo http://code.google.com/p/pyftpdlib/ From siona at chiark.greenend.org.uk Tue Dec 23 06:23:16 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 23 Dec 2008 11:23:16 +0000 (GMT) Subject: Very basic question References: <21ab1917-f0c9-48fb-baa9-02e5bf229bf5@s9g2000prm.googlegroups.com> Message-ID: Sengly wrote: >I would like to calculate a string expression to a float. For example, >I have ('12/5') and I want 2.4 as a result. I tried to use eval but it >only gives me 2 instead of 2.5 py> from __future__ import division py> print eval('12/5') 2.4 py> print eval('12//5') 2 Or switch to 3.0 which gives you this behaviour without the __future__ import. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From duncan.booth at invalid.invalid Sun Dec 21 10:30:34 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Dec 2008 15:30:34 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <015da0a4$0$20656$c3e8da3@news.astraweb.com> <015e4162$0$20656$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: >> a+b+c+d might execute a.__add__(b,c,d) allowing more efficient string >> concatenations or matrix operations, and a%b%c%d might execute as >> a.__mod__(b,c,d). > > That's only plausible if the operations are associative. Addition is > associative, but string interpolation is not: Addition is not associative on arbitrary types. > >>>> "%%%s" % ("%s" % "b") > '%b' >>>> ("%%%s" % "%s") % "b" > Traceback (most recent call last): > File "", line 1, in > TypeError: not all arguments converted during string formatting > > Since string interpolation isn't associative, your hypothetical > __mod__ method might take multiple arguments, but it would have to > deal with them two at a time, unlike concatenation where the compiler > could do them all at once. So whether __mod__ takes two arguments or > many is irrelevant: its implementation must rely on some other > function which takes two arguments and must succeed or fail on that. I don't see that. What I suggested was that a % b % c would map to a.__mod__(b,c). (a % b) % c would also map to that, but a % (b % c) could only possibly map to a.__mod__(b.__mod__(c)) From robert.kern at gmail.com Mon Dec 8 16:51:23 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 08 Dec 2008 15:51:23 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> Message-ID: Rhamphoryncus wrote: > On Dec 8, 1:04 pm, Robert Kern wrote: >> Rhamphoryncus wrote: >>> On Dec 8, 11:54 am, Robert Kern wrote: >>>> Rhamphoryncus wrote: >>>>> On Dec 7, 4:20 pm, Steven D'Aprano >>>> cybersource.com.au> wrote: >>>>>> On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: >>>>>>> Rasmus Fogh wrote: >>>>>>>> Current behaviour is both inconsistent and counterintuitive, as these >>>>>>>> examples show. >>>>>>>>>>> x = float('NaN') >>>>>>>>>>> x == x >>>>>>>> False >>>>>>> Blame IEEE for that one. Rich comparisons have nothing to do with that >>>>>>> one. >>>>>> There is nothing to blame them for. This is the correct behaviour. NaNs >>>>>> should *not* compare equal to themselves, that's mathematically >>>>>> incoherent. >>>>> Mathematically, NaNs shouldn't be comparable at all. They should >>>>> raise an exception when compared. In fact, they should raise an >>>>> exception when *created*. But that's not what we want. What we want >>>>> is a dummy value that silently plods through our calculations. For a >>>>> dummy value it seems a lot more sense to pick an arbitrary yet >>>>> consistent sort order (I suggest just above -Inf), rather than quietly >>>>> screwing up the sort. >>>> Well, there are explicitly two kinds of NaNs: signalling NaNs and quiet NaNs, to >>>> accommodate both requirements. Additionally, there is significant flexibility in >>>> trapping the signals. >>> Right, but most of that's lower level. By the time it reaches Python >>> we only care about quiet NaNs. >> No, signaling NaNs raise the exception that you are asking for. You're right >> that if you get a Python float object that is a NaN, it is probably going to be >> quiet, but signaling NaNs can affect Python in the way that you want. >> >>>>> Regarding the mythical IEEE 754, although it's extremely rare to find >>>>> quotations, I have one on just this subject. And it does NOT say "x >>>>> == NaN gives false". It says it gives *unordered*. It is C and >>>>> probably most other languages that turn that into false (as they want >>>>> a dummy value, not an error.) >>>>> http://groups.google.ca/group/sci.math.num-analysis/browse_thread/thr... >>>> Table 4 on page 9 of the standard is pretty clear on the subject. When the two >>>> operands are unordered, the operator == returns False. The standard defines how >>>> to do comparisons notionally; two operands can be "greater than", "less than", >>>> "equal" or "unordered". It then goes on to map these notional concepts to >>>> programming language boolean predicates. >>> Ahh, interesting. Still though, does it give an explanation for such >>> behaviour, or use cases? There must be some situation where blindly >>> returning false is enough benefit to trump screwing up sorting. >> Well, the standard was written in the days of Fortran. You didn't really have >> generic sorting routines. You *could* implement whatever ordering you wanted >> because you *had* to implement the ordering yourself. You didn't have to use a >> limited boolean predicate. >> >> Basically, the boolean predicates have to return either True or False. Neither >> one is really satisfactory, but that's the constraint you're under. > > "We've always done it that way" is NOT a use case! Certainly, it's a > factor, but it seems quite weak compared to the sort use case. I didn't say it was. I was explaining that sorting was probably *not* a use case for the boolean predicates at the time of writing of the standard. In fact, it suggests implementing a Compare() function that returns "greater than", "less than", "equal" or "unordered" in addition to the boolean predicates. That Python eventually chose to use a generic boolean predicate as the basis of its sorting routine many years after the IEEE-754 standard is another matter entirely. In any case, the standard itself is quite short, and does not spend much time justifying itself in any detail. > I suppose what I'm hoping for is an small example program (one or a > few functions) that needs the "always false" behaviour of NaN. Steven D'Aprano gave one earlier in the thread. Additionally, (x!=x) is a simple test for NaNs if an IsNaN(x) function is not available. Really, though, the result falls out from the way that IEEE-754 constructed the logic of the system. It is not defined that (NaN==NaN) should return False, per se. Rather, all of the boolean predicates are defined in terms of that Compare(x,y) function. If that function returns "unordered", then (x==y) is False. It doesn't matter if one or both are NaNs; in either case, the result is "unordered". -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From Juergen.Hermann at 1und1.de Wed Dec 17 05:48:48 2008 From: Juergen.Hermann at 1und1.de (jhermann) Date: Wed, 17 Dec 2008 02:48:48 -0800 (PST) Subject: Python 3.0 crashes displaying Unicode at interactive prompt References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> <49443531.5050304@v.loewis.de> <49448FC2.6030306@v.loewis.de> <494576DD.1050505@v.loewis.de> <89022013-f7f6-4779-849f-b36fe618104e@r15g2000prh.googlegroups.com> <494599CD.3030408@v.loewis.de> Message-ID: <854e02a8-eaa4-4e02-b668-7b6d4a36fd12@e1g2000pra.googlegroups.com> Assuming those survived the switch to 3.0, you can use site.py und sys.displayhook to customize to the old behaviour (i.e. change it to a version using ascii instead of repr). Since this only affects interactive use, it's also no problem for portability of code, unlike "solutions" like forcing the defaultencoding etc. From philip at semanchuk.com Sat Dec 6 17:19:27 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Sat, 6 Dec 2008 17:19:27 -0500 Subject: Source code generation using Python In-Reply-To: <82098706-978f-4920-ac75-57ef3573ac44@x38g2000yqj.googlegroups.com> References: <82098706-978f-4920-ac75-57ef3573ac44@x38g2000yqj.googlegroups.com> Message-ID: On Dec 6, 2008, at 4:47 PM, ats wrote: > Hello, > > This is my first posting to a Python group (and I'm starting with > Python seriously only now) , so bear with me if I make some mistakes. > > I want to generate 3 different versions of a C++ source code, > basically injecting different flavours of inline assembler depending > on target compiler/CPU. > > Code generation should be integrated into a 'master source file' which > is the processed and generates the right code for GCC / MSVC or other > cases. Something like: > > int FastAdd( int t1, int t2 ){ > int r; > ##if USE_INLINE_ASM > #ARG( eax, "t1") > #ARG( ebx, "t2") > #ASM( "add", ebx, eax ) > #RES( eax, "r" ) > ##else > r = t1+t2; > ##endif > return r; > } > > On processing, given constant USE_INLINE_ASM (or not) the right code > is generated to a target file, which goes into the build process. > > I was looking for packages that can do this and came up with some > candidates: > > - "empy" - http://www.alcyone.com/pyos/empy/ - It looks like it could > do the job, but appears non-maintained since 2003. > - "Cheetah" - Looks like more of a tool to do fix replacements of code > snippets. > > > There is some logic going on in the "ARG", "ASM" and "RES" sections, > so I need to link code generation with true Python functions. Hi Arne, There are *lots* of packages for Python that replace chunks of predefined templates. Most are HTML-focused, some more so than others. I've used Mako (http://www.makotemplates.org/) to generate both HTML and Apache config files. It could certainly do C++. Some alternatives to Mako are mentioned in the documentation -- Kid, Genshi and Cheetah. Rather than invite a flame war as to which is a better templating engine, I'll just say that I'm happy with how Mako addresses *my* needs. =) Good luck finding something that addresses yours. Cheers Philip > > > The situation is really quite similar to HTML/PHP except, here we > would have C++/Python. > > Any suggestions? > > Thanks, > //Arne S. > -- > http://mail.python.org/mailman/listinfo/python-list From arnodel at googlemail.com Wed Dec 3 14:11:47 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 03 Dec 2008 19:11:47 +0000 Subject: Overriding a method at the instance level on a subclass of a builtin type References: Message-ID: "Zac Burns" writes: > Sorry for the long subject. > > I'm trying to create a subclass dictionary that runs extra init code > on the first __getitem__ call. However, the performance of __getitem__ > is quite important - so I'm trying in the subclassed __getitem__ > method to first run some code and then patch in the original dict > method for the instance to avoid even the check to see if the init > code has been run. Various recipes using instancemethod and the like > have failed me. > > Curiously if __slots__ is not specified no error occurs when setting > self.__getitem__ but the function is not overriden. If __slots__ is > ['__getitem__'] however it complains that __getitem__ is read only. I > do not understand that behavior. You can change the class on the fly to achieve what you want: >>> class D1(dict): ... def __getitem__(self, key): ... print 'first call' ... self.__class__ = D2 ... return dict.__getitem__(self, key) ... >>> class D2(dict): ... pass ... >>> d = D1(foo=42) >>> d['foo'] first call 42 >>> d['foo'] 42 >>> HTH -- Arnaud From arnodel at googlemail.com Sun Dec 14 07:29:10 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 14 Dec 2008 12:29:10 +0000 Subject: Optimizing methods away or not? References: <0154b041$0$6988$c3e8da3@news.astraweb.com> <0154df65$0$6988$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano writes: > On Sun, 14 Dec 2008 10:52:25 +0000, Arnaud Delobelle wrote: > >> You could also not use the metaclass and use post_verify as a decorator > > Except that self.verify doesn't exist if __debug__ is false. OK I wrote this as an afterthought. I'm, sure it's not beyond your ability to add if not __debug__: return method at the start of the post_verify function :) -- Arnaud From msdark at archlinux.us Thu Dec 18 21:38:23 2008 From: msdark at archlinux.us (=?ISO-8859-1?Q?Mat=EDas_Hern=E1ndez?=) Date: Thu, 18 Dec 2008 23:38:23 -0300 Subject: python mysql hash generator Message-ID: <494B091F.6010808@archlinux.us> sorry for my english, but i'm speak spanish) Hi list.. this is my first post... and obviously if for help.. I try to implement the password function of mysql in a python script. I read that the password function of mysql was implemented with a double sha1() I python i try this: example1: if __name__=="__main__": s = hashlib.sha1() s.update('test') s2 = hashlib.sha1() s2.update(s.digest() print s2.hexdigest() This script show me the same hash that password function of mysql, but when i implement this in a class the hash is different??? why??? And if is posible??? can you show a example code of old_password function of mysql in python??? THNX From jstroud at mbi.ucla.edu Sun Dec 14 20:24:34 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 14 Dec 2008 17:24:34 -0800 Subject: Looking for the best way to translate an idiom In-Reply-To: References: Message-ID: James Stroud wrote: > inspect.stack()[1][0].f_locals[name] = val I just double checked this. Because of the way locals are implemented in cPython, this won't have the desired affect. James From XX.XmcX at XX.XmclaveauX.com Fri Dec 19 02:11:53 2008 From: XX.XmcX at XX.XmclaveauX.com (MC) Date: Fri, 19 Dec 2008 08:11:53 +0100 Subject: Very Slow PythonWin 2.6.1 Startup on Windows XP SP3 References: <_PG2l.570$P5.31@nwrddc02.gnilink.net> Message-ID: Hi! Perhaps, if you copy DLL in others strategic places, it's better... -- @-salutations Michel Claveau From ldo at geek-central.gen.new_zealand Fri Dec 5 20:20:55 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 06 Dec 2008 14:20:55 +1300 Subject: Don't you just love writing this sort of thing :) References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: In message <32cf4a79-a6e3-4250-9b5a-1ec80c748618 at j32g2000yqn.googlegroups.com>, Aaron Brady wrote: > On Dec 5, 4:32?am, Lawrence D'Oliveiro central.gen.new_zealand> wrote: > >> The code people write is probably a direct reflection of their thinking >> processes: For example, slow, plodding, one step at a time, incapable of >> imaginative leaps, versus those who operate directly on larger patterns >> at once... > > That distinction operates indirectly on smaller patterns. Do you find this (open, gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir, Entry), "r") complicated or hard to understand? It's made up of very simple pieces, combined according to very simple rules, viz:- A tuple of candidate functions: (open, gzip.GzipFile) A choice from that tuple according to a condition: [Entry.endswith(".gz")] And finally, arguments to pass to the chosen function: (os.path.join(PatchesDir, Entry), "r") See, it's so simple, a child could understand it. A child who isn't burdened with the preconceptions that seem to afflict some participants in this noisegroup... From pecora at anvil.nrl.navy.mil Mon Dec 22 09:51:01 2008 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Mon, 22 Dec 2008 09:51:01 -0500 Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> <6r6hpfFfb643U3@mid.uni-berlin.de> <494E6FDA.4070401@mrabarnett.plus.com> <4585c27d-d7a9-480f-991c-a869161be55c@g38g2000yqn.googlegroups.com> <3392a51b-d3fd-4986-9c59-fecccc7272da@p2g2000prn.googlegroups.com> Message-ID: In article , "James Mills" wrote: > In case anyone is not aware, Python is > also used for heavy scientific computational > problems, games such as Civilisation and > others, and I believe (correct me if I"m wrong) > it's also used by NASA. > > --JamesMills Python has become very popular in scientific computation. You'll find it in use lots of places (universities, national labs, defense labs). I use it for solving partial differential equations for quantum chaos calculations and went to C for speed up where needed using ctypes which is very straightforward and plays nice with numpy array/matrix libraries. I've been doing scientific programming for 30 years. Python with C extensions and libraries is the best approach I've ever used. Calculation speed is not a problem and the code can be "tweaked" to increase it easily. Programming speed is incredible. I can get substantial object oriented code up and running much faster than anything I've ever used. -- -- Lou Pecora From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 8 08:20:03 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 08 Dec 2008 14:20:03 +0100 Subject: Guido's new method definition idea In-Reply-To: <49d12ec1-2be9-497b-80bc-9f0402a9086d@s20g2000yqh.googlegroups.com> References: <493a9fed$0$18973$426a34cc@news.free.fr> <493c1ff6$0$4942$426a34cc@news.free.fr> <49d12ec1-2be9-497b-80bc-9f0402a9086d@s20g2000yqh.googlegroups.com> Message-ID: <493d1f03$0$32048$426a34cc@news.free.fr> Philip Slate a ?crit : > On Dec 7, 1:13 pm, Bruno Desthuilliers > wrote: > >>> and friendlier to newbies. >> I'd rather say "more acceptable to java-brainwashed developpers". > > And I'd rather say you're trolling, Almost, indeed. But not as much as you !-) From prahaai at gmail.com Thu Dec 4 11:57:31 2008 From: prahaai at gmail.com (Cro) Date: Thu, 4 Dec 2008 08:57:31 -0800 (PST) Subject: Python 3 read() function References: Message-ID: <6e24be88-b042-425b-b880-c97d184fee07@s20g2000yqh.googlegroups.com> > Do you really mean io.StringIO? I guess you want io.BytesIO() .. > > Christian Mmm... i don't know. I also tried : [code] IDLE 3.0 >>> import io >>> vContent = io.BytesIO() >>> huge = io.open("C:\HUGE_FILE.pcl",'r+b',0) >>> vContent = huge.read() [/code] It still waits a lot... i don't have the patience to wait for the file to load completely... it takes a lot! Thank you for your reply. From philip at semanchuk.com Wed Dec 3 10:41:16 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Wed, 3 Dec 2008 10:41:16 -0500 Subject: Running a Python script from crontab In-Reply-To: <126ba84a-0ea0-4a91-b7d2-89ed650e5d6c@d32g2000yqe.googlegroups.com> References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> <126ba84a-0ea0-4a91-b7d2-89ed650e5d6c@d32g2000yqe.googlegroups.com> Message-ID: On Dec 3, 2008, at 10:29 AM, Astley Le Jasper wrote: > I've included a switch to include or exclude the logging to console. > When logging only to file, the script runs fine. > > Of course, I still don't understand why dual logging, and specifically > to the console, causes a problem and if anyone has any comments about > the dual output logging code above then I'd still be happy to hear > about it. Trying to write non-ASCII characters perchance? From sturlamolden at yahoo.no Fri Dec 12 08:04:12 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 05:04:12 -0800 (PST) Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> Message-ID: On Dec 12, 1:56 pm, sturlamolden wrote: > That is because integers are immutable. When x += 1 is done on an int, > there will be a rebinding. But try the same on say, a numpy array, and > the result will be different: And a consequence of this is, if you have a function like def foobar(x): x += 1 then the parameter x will be modified given that x have mutable type. However, if we have a function like def foobar(x): x = x + 1 then x will not be modified, mutable or not. (Well, you could abuse operator overlaoding to make unexpected side effects in the latter case. But except for such insanity it will not have side-effects.) From steve at REMOVE-THIS-cybersource.com.au Sat Dec 6 19:10:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 00:10:45 GMT Subject: Learning Python now coming from Perl References: <014a96e0$0$20670$c3e8da3@news.astraweb.com> Message-ID: <014b0c3a$0$20670$c3e8da3@news.astraweb.com> On Sat, 06 Dec 2008 14:15:28 -0500, Roy Smith wrote: > In article <014a96e0$0$20670$c3e8da3 at news.astraweb.com>, > Steven D'Aprano wrote: > >> On Sat, 06 Dec 2008 08:50:20 -0500, Roy Smith wrote: >> >> > For your first >> > project, pick something that's small enough that you think you could >> > tackle it in under 50 lines of Perl. >> >> Is there anything which *can't* be written in under 50 lines of Perl? > [...] >> Also, Perl REs are faster than Python REs, or so I'm told. Between the >> speed and the convenience, Perl programmers tend to use RE's for >> everything they can. Python programmers tend to use REs only for >> problems that *should* be solved with REs rather than *can* be solved >> with a RE. > > Well, as an old-time unix hacker (who learned REs long before Perl > existed), my question to you would be, "Is there any problem which > *shouldn't* be solved with an RE?" :-) I think you've answered your own question: > One of the reasons REs don't get used in Python as much as in Perl is > because strings have useful methods like startswith(), endswith(), and > split(), and also the "in" operator. These combine to give you easy > ways to do many things you might otherwise do with REs. Also: * splitting pathnames and file extensions * dealing with arbitrarily nested parentheses * any time you need a full-blown parser (e.g. parsing HTML or XML) * sanitizing untrusted user input ("I bet I can think of *every* bad input and detect them all with this regex!") * validating email addresses http://northernplanets.blogspot.com/2007/03/how-not-to-validate-email-addresses.html * testing prime numbers http://jtauber.com/blog/2007/03/18/python_primality_regex/ * doing maths http://blog.stevenlevithan.com/archives/algebra-with-regexes http://weblogs.asp.net/rosherove/archive/2004/11/08/253992.aspx There's probably more. -- Steven From Lie.1296 at gmail.com Sun Dec 7 02:21:04 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 6 Dec 2008 23:21:04 -0800 (PST) Subject: Guido's new method definition idea References: Message-ID: On Dec 6, 9:21?am, "Daniel Fetchinson" wrote: > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... > > The proposal is to allow this: > > class C: > ? ? def self.method( arg ): > ? ? ? ? self.value = arg > ? ? ? ? return self.value > > instead of this: > > class C: > ? ? def method( self, arg ): > ? ? ? ? self.value = arg > ? ? ? ? return self.value > > I.e. explicit self stays only the syntax is slightly different and may > seem attractive to some. As pointed out by Guido classmethods would > work similarly: > > class C: > ? ? @classmethod > ? ? def cls.method( arg ): > ? ? ? ? cls.val = arg > ? ? ? ? return cls.val To sum up: Arguments on Status Quo: + Andreas Waldenburger: it works and there just is no need to change it + need no change + Andreas Waldenburger: Getting the Python comunity to replace self with something shorter will never compensate for the time you spent bullying it through - Confusion for number of parameters - The standard 'self' is too long - Newbie FAQ - It is ugly Arguments on "def self.method(" as "def method(self" inside a class: + OP: It reduces confusion for number of parameters + Patrick Mullen: The symetry of "def self.func(blah)==def func (self,blah)" and "ob.func(blah)==func(ob.blah)" is kind of neat. + OP: Backward compatible + OP: It is explicit - Marc 'Blackjack' Rintsch: they [newcomers] will run into *both* variants in tutorials, code, and books, so it might be even more confusing. - Carl Banks: def (): == = , but def self.method(): return 1 != self.method = lambda: 1 - `self` in this context might be misconstrued as the class object and thus `def self.foo` might be misunderstood ... as a defining a classmethod rather than an instance method. - It is ugly ? Syntax sugar or replacement? Many people prefers this to be replacement to reduce confusion. Arguments on variants of $ + Russ P.: looks like S(elf) + Russ P.: more succinct with no loss of readability - Antoine de Groote: slightly less readable. - Antoine de Groote: wouldn't require this new syntax (def meth($, args): $.foo) - Andreas Waldenburger: "self" is a speaking identifier, "$" isn't - Obscure symbol - It is ugly Unresolved: ? Patrick Mullen: Outside a class definition? I think we have to test this on newbies. Personally, I think the new syntax would confuse newbies too, though not as much as the tricky error message we currently have (code: foo.bar(1, 2, 3, 4); Error: TypeError: foo() takes exactly 4 arguments (5 given); Newbie: "what the... 1.. 2.. 3.. 4.., I correctly gave 4 arguments, python counted the wrong number of arguments"). If this dead horse is revived because of that reason, then I'd go with changing the error message to something that is less confusing to newbies[1]. I remember being tripped with the (thinking that python miscounted the number of argument) when I was new. This has the advantage of backward compatibility and no syntax change, just less misleading error message. [1] anything could work, but I like this one: (c is an instance of class C) if the code is: c.foo(...), Error: "TypeError: c.foo() takes exactly 3 argument" while if the code is: C.foo(...), Error: "C.foo() takes exactly 4 arguments" You can implement c.foo as a curried C.foo function, catch C.foo's TypeError exception then reraise it as c.foo exception. From febaen at gmail.com Sat Dec 13 03:57:12 2008 From: febaen at gmail.com (feba) Date: Sat, 13 Dec 2008 00:57:12 -0800 (PST) Subject: Need help improving number guessing game Message-ID: #!/usr/bin/python/ #Py3k, UTF-8 import random print(" --- WELCOME TO THE SUPER NUMBER GUESSING GAME --- " + ("\n" * 5)) pnum = int(input("1 OR 2 PLAYER?\nP#: ")) target = random.randint(1, 99) #Pick a random number under two digits guess1 = 0 #Zero will never be picked as target... guess2 = 0 #so it makes a good default value p1score = 0 #For two player mode... p2score = 0 #let's keep score! print("LET'S START THE GAME. \nGUESS ANY WHOLE NUMBER FROM 1 TO 99.") while True: if pnum == 1: #1p mode while True: guess1 = int(input("\n>> ")) if guess1 > 100: print("ONLY NUMBERS FROM 1 TO 99") elif guess1 > target: print("TOO HIGH") elif guess1 == target: print("CONGLATGURATIONS! PLAY AGAIN?") target = random.randint(1, 99) #Set up the game again play = int(input("0 TO END: ")) if play == 0: print("GOOD BYE. PLAY AGAIN SOON!") quit() else: print("TOO LOW") if pnum == 2: #2p mode while True: guess1 = int(input("\nP1> ")) #Player 1's turn if guess1 > 100: print("ONLY NUMBERS FROM 1 to 99") elif guess1 > target: print("TOO HIGH") elif guess1 == target: p1score += 1 print("GOOD JOB, PLAYER 1! THE SCORE IS:\nP1: %s --- P2: %s\nPLAY AGAIN?" % (p1score, p2score)) target = random.randint(1, 99) #Set up game again play = int(input("0 TO END: ")) if play == 0: print("GOOD BYE. PLAY AGAIN SOON!") else: print("TOO LOW") guess2 = int(input("\nP2> ")) #Player 2's turn if guess2 > 100: print("ONLY NUMBERS FROM 1 to 99") elif guess2 > target: print("TOO HIGH") elif guess2 == target: p2score += 1 print("GOOD JOB, PLAYER 2! THE SCORE IS:\nP1: %s --- P2: %s\nPLAY AGAIN?" % (p1score, p2score)) target = random.randint(1, 99) #Set up game again play = int(input("0 TO END: ")) if play == 0: print("GOOD BYE. PLAY AGAIN SOON!") else: print("TOO LOW") else: print("INVALID PLAYER SELECTION") pnum = int(input("1 OR 2 PLAYER?\nPN#: ")) I have one major problem with this; the 'replay' selection. It quits if you put in 0, as it should, and continues if you put in any other number. However, if you just press enter, it exits with an error. it also looks really ugly, and I'm sure there has to be plenty of better ways to do it. I'd also appreciate tips on how it could be better in general. I should think that P1 and P2's turns shouldn't have to be completely repeated; but I'm not quite sure how to def something like that. From python.list at tim.thechases.com Mon Dec 15 11:14:38 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 15 Dec 2008 10:14:38 -0600 Subject: alt.possessive.its.has.no.apostrophe In-Reply-To: <49467CE2.3060401@holdenweb.com> References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> <49467CE2.3060401@holdenweb.com> Message-ID: <4946826E.7060001@tim.thechases.com> Steve Holden wrote: > This led to a schism between the British and the > newly-independent Americans, who responded by taking the "u" > out of colour, valour, and aluminium. Darn Americans and their alminim.... ;-) Next thing you know, they'll be putting an I in TEAM.[1] -tkc [1] http://www.quotedb.com/quotes/2417 From kw at codebykevin.com Sat Dec 27 22:13:59 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Sat, 27 Dec 2008 22:13:59 -0500 Subject: Python 3 and my Mac (Leopard) In-Reply-To: <4952b38d$0$20300$607ed4bc@cv.net> References: <4952b38d$0$20300$607ed4bc@cv.net> Message-ID: <4956EEF7.60407@codebykevin.com> Dan wrote: > Wanted to learn python, got Mark Summerfield's new book "Programming in > Python 3". Having a hard time getting python 3 and IDLE working on my > Mac with Leopard. The mac "resources" on the python.org site seem a bit > out of date, and don't really mention python 3. Are there any resources > out there? Is the python community just not interested in Macs? I've > tried googling and the usual search strategies. Any help would be > appreciated. > > DAN > There's a mailing list devoted to Python on the Mac: http://mail.python.org/mailman/listinfo/pythonmac-sig It is a pretty good resource, better than the Python wiki, more up to date. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From warren at delsci.com Thu Dec 4 15:53:53 2008 From: warren at delsci.com (Warren DeLano) Date: Thu, 4 Dec 2008 12:53:53 -0800 Subject: "as" keyword woes Message-ID: <896B75251BA19745A529B1B867893FA50679D9@planet.delsci.local> > I still have not > >> seen a single post from you even hinting that you might have any > >> responsibility in the matter. > > > > Well then, let me set the record straight on that one point: > > > > I admit that it was entirely my mistake (and mine alone) to implicitly > > assume, by adopting such a logging & persistence architecture (dating > > back to 1.5.2, mind you!), that new keywords would not be introduced > > into the Python language so as to potentially break all existing Python > > code. > > > > Silly me! How unreasonable. > > > > Pythons backwards compatibility policy is available here: > http://www.python.org/dev/peps/pep-0005/ Thank you! Just to end on a more positive note: As someone who makes a living from Python rather than someone who lives to make Python, I recognize that there will be ancillary casualties in every major battle. Though I may whine incessantly about all of our pre-2.5 log-file/documents being one such casualty (your various accusations notwithstanding, we did indeed patch our own code as soon as the deprecation warnings appeared in 2.5!), if the Python 2.6 "as" keyword break is truly for the greater good, then so be it. Warren From marduk at letterboxes.org Tue Dec 23 09:41:06 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Tue, 23 Dec 2008 09:41:06 -0500 Subject: print to console without a line break In-Reply-To: References: Message-ID: <1230043266.22581.1.camel@brotherus.rdu.redhat.com> On Tue, 2008-12-23 at 13:18 +0000, Lie Ryan wrote: > On Tue, 23 Dec 2008 11:50:59 +0100, Qian Xu wrote: > > > Hello All, > > > > Is it possible to print something to console without a line break? > > > > I tried: > > sys.stdout.write("Testing something ...") // nothing will be printed > > time.sleep(1) > > sys.stdout.write("done\n") // now, the whole string will be printed > > Probably because your stdout is line-buffered. Try: sys.stdout.write("Testing something...") sys.stout.flush() # flush the stdout buffer From huwdjones at gmail.com Thu Dec 18 05:34:13 2008 From: huwdjones at gmail.com (huw_at1) Date: Thu, 18 Dec 2008 02:34:13 -0800 (PST) Subject: cx_Oracle issues References: <5b2dad81-2750-4347-8079-6ab31321d579@s1g2000prg.googlegroups.com> <9142a8f1-7f76-4fc0-9ca1-c9dec310f2ce@r37g2000prr.googlegroups.com> <9f436c9e-2319-499c-a306-d255996372fc@e22g2000vbe.googlegroups.com> <09b53231-5a92-437c-859b-6e5d0ce106c8@k36g2000pri.googlegroups.com> Message-ID: <75a97df3-7ee9-41ce-9f10-e525c42a7653@e18g2000vbe.googlegroups.com> On Dec 16, 12:17?pm, huw_at1 wrote: > On Dec 15, 12:59?pm, "ron.re... at gmail.com" > wrote: > > > > > On Dec 15, 2:44?am, huw_at1 wrote: > > > > On Dec 11, 5:34?pm, "ron.re... at gmail.com" wrote: > > > > > On Dec 10, 9:48?am, huw_at1 wrote: > > > > > > Hey all. When usingcx_Oracleto run a procedure like: > > > > > > cursor.execute("select (obj.function(value)) from table where > > > > > id=blah") > > > > > > I am getting the following error: > > > > > > ORA-06502: PL/SQL: numeric or value error: character string buffer too > > > > > small ORA-06512: at line 1 > > > > > > Looking at cursor.description I get: > > > > > > [('(obj.function(value))', , 4000, 4000, 0, > > > > > 0, 1)] > > > > > > Any tips - i have never seen this error before but am guessing that > > > > > the value being returned is too big for the buffer size set for the > > > > > cursor. the procedure fetches data from a LOB. > > > > > > Any suggestions/confirmations? > > > > > > Many thanks > > > > > This error is a problem with the PL/SQL, notcx_Oracle. ?You need to > > > > debug obj.function to see what kind of data is being accessed and then > > > > a data analysis of that data to understand why this error occurs. ?I > > > > can tell you the function is most likely expecting characters from a > > > > column that are numeric [0 .. 9] and is getting alpha characters. > > > > > -- > > > > Ron Reidy > > > > Sr. Oracle DBA > > > > Hi thanks for the responses. Unfortunately the procedure in question > > > is from a third party vendor so I can't really debug it so I'd say I > > > was fairly stumped. Just out of interest how do you increase the > > > output buffer size withcx_Oracle? > > > > Many thanks- Hide quoted text - > > > > - Show quoted text - > > > Hi, > > > Sure you can. ?You can see the PL/SQL source from the ditionary view > > ALL_SOURCE: > > select text from all_source where name = 'NAME_OF_FUNCTION'; > > > From there, reverse engineeer which table(s) and column(s) are being > > accesses and do the data analysis. > > > -- > > Ron Reidy > > Hi all, > > So I tried Rons query but unfortunately I got 0 records returned. > However I can confirm that running the select query from a client does > indeed generate the same error. Is there anything else I could try? > Otherwise I'll just get in touch with the vendor I guess. Hi again. A further update to these issues is that I found some java executable which seemed to execute the SQL query without hitch. My Java isn't great but from what I could make out it seems that the query is broken down from: select (obj.function(value)) from table where id=blah to: select value from table where id=blah obj.function(value) So make two queries. In the first retrieve the BLOB (value) and store it in a java.sql.blob object. Then pass this back in to the stored procedure. I'm a bit puzzled as to why this way would work over just performing the straight select statement. Culd it be the jdbc connector handles BLOBs better? Anyway I was wondering if I could implement something similar using cx_Oracle. however I am a bit stuck on how to pass a BLOB in to the second query - specifically: cursor.execute(obj.function(value)) where value is the BLOB. I get an error: cx_Oracle.NotSupportedError: Variable_TypeByValue(): unhandled data type cx_Oracle.LOB So I wonder if I need to set something for the input type but I do not know how to do this. Any suggestions? Many thanks again. From conrad.ammon at gmail.com Mon Dec 15 16:00:11 2008 From: conrad.ammon at gmail.com (cmdrrickhunter@yaho.com) Date: Mon, 15 Dec 2008 13:00:11 -0800 (PST) Subject: stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> <015612ac$0$20639$c3e8da3@news.astraweb.com> <52cfb77e-4baf-4fba-8eac-cc6c7ddb5be5@k1g2000prb.googlegroups.com> <5504f9ac0812150828m14f6999ak6112c5975042dc88@mail.gmail.com> Message-ID: <1ffd301f-16d3-4dc7-988c-7741d658ca10@z28g2000prd.googlegroups.com> Just because its such an interesting problem, I'll take a stab at it. It can be proven that you cannot sort an arbitrarily large set of numbers, given no extra information, faster than O(n log n). It is provable using information theory. However, if your teacher is giving you evil problems, there's no reason you can't be evil in return: Evil trick 1: Allocate an array of n^2 booleans, initialized to false (This is O(n^2)). Declare this to be "before the sort" Then iterate through the list and set each matching entry in the array to True (This is O(n)). Now you have them "sorted." To get access to the data, you need to iterate across the array O(n^2), but this is "after the sort" Evil trick 2: inserting into a set is O(1), so you could insert n items into a set. This is O(n). Then you can argue that, since the set cares not about order, it is as good as ordered! Evil trick 3: pull up your python debugger, and have your program search for the right answer in your teacher's test library. If done smart, this could even be an O(1) sort O_o (queue Nukees reference: "Welcome to my computer security course. Your grades have already been entered into the school's grading systems as Fs. You have one semester to change that, good luck") ... these are fun =) From quian.xu at stud.tu-ilmenau.de Tue Dec 23 09:52:50 2008 From: quian.xu at stud.tu-ilmenau.de (Qian Xu) Date: Tue, 23 Dec 2008 15:52:50 +0100 Subject: print to console without a line break References: Message-ID: Lie Ryan wrote: > If you don't mind an extra space, you can use this: > > print 'Testing something ...', > # note the trailing comma Thanks. However, the contents will be saved in buffer and will not be shown until print "(last piece)" sys.stdout.flush() can solve this problem :-) From xahlee at gmail.com Mon Dec 8 17:32:59 2008 From: xahlee at gmail.com (Xah Lee) Date: Mon, 8 Dec 2008 14:32:59 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> <0201522a-b15a-4401-a208-5d9af70bdd74@w24g2000prd.googlegroups.com> Message-ID: <8947211d-2ee8-403a-8c8a-c7599aea5f80@k24g2000pri.googlegroups.com> 2008-12-08 Xah Lee wrote: > > Also, in this discussion, thanks to Thomas M Hermann's $20 offered to > > me for my challenge to you, that i have taken the time to show working > > code that demonstrate many problems in your code. A moron, wrote: > You failed the challenge that you were given. you didn't give me a challenge. I gave you. I asked for $5 sincerity wage of mutal payment or money back guarantee, so that we can show real code instead of verbal fight. You didn't take it and do nothing but continue petty quarrel on words. Thomas was nice to pay me, which results in my code that is demonstratably faster than yours. (verified by a post from ?jason-sage @@@ creativetrax.com?, quote: ?So Xah's code is about twice as fast as Jon's code, on my computer.?, message can be seen at ? http://www.gossamer-threads.com/lists/python/python/698196?do=post_view_threaded#698196 ? ) You refuse to acknowledge it, and continue babbling, emphasizing that my code should be some hundred times faster make valid argument. As i said, now pay me $300, i will then make your Mathematica code in the same level of speed as your OCmal. If it does not, money back guaranteed. Here's more precise terms i ask: Show me your OCmal code that will compile on my machine (PPC Mac, OSX 10.4.x). I'll make your Mathematica code in the same speed level as your OCmal code. (you claimed Mathematica is roughly 700 thousand times slower to your OCmal code. I claim, i can make it, no more than 10 times slower than the given OCmal code.) So, pay me $300 as consulting fee. If the result does not comply to the above spec, money back guaranteed. > You should accept the fact that Mathematica currently has these > insurmountable limitations. insurmountable ur mom. Xah ? http://xahlee.org/ ? From malkarouri at gmail.com Mon Dec 8 07:39:29 2008 From: malkarouri at gmail.com (malkarouri) Date: Mon, 8 Dec 2008 04:39:29 -0800 (PST) Subject: how to get a beep, OS independent ? References: Message-ID: <85932553-02a8-481e-add2-945effc77b22@j39g2000yqn.googlegroups.com> On 6 Dec, 23:40, Stef Mientki wrote: > hello, > > I want to give a small beep, Just to add to the options here. Where ncurses work you can use: python -c 'from curses import *;wrapper(lambda s:beep())' To try it just enter the whole line above in the command line.. Regards, Muhammad Alkarouri From lie.1296 at gmail.com Sun Dec 14 21:11:10 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 15 Dec 2008 02:11:10 +0000 (UTC) Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> <0152e35f$0$8244$c3e8da3@news.astraweb.com> Message-ID: On Fri, 12 Dec 2008 22:55:20 +0000, Steven D'Aprano wrote: > On Fri, 12 Dec 2008 21:18:36 +0000, Lie Ryan wrote: >> Personally, I'd prefer VB's version: >> foo IsNot bar >> >> or in pseudo-python >> foo isnot bar >> >> since that would make it less ambiguous. > > "a is not b" is no more ambiguous than "1+2*3". True, there's ambiguity > if you are ignorant of the precedence rules, but that's no worse than > saying that "+" is ambiguous if you don't know what "+" means. > > "What's this 'is' operator??? It's ambiguous, it could mean ANYTHING!!! > Panic panic panic panic!!!" > > *wink* > > You're allowed to assume the normal conventions, and (lucky for me!) > despite being Dutch Guido choose to assume the normal English convention > that "a is not b" means the same as "not (a is b)" rather than "a is > (not b)". That's probably because the use-cases for the second would be > rather rare. > > So given the normal precedence rules of Python, there is no ambiguity. > True, you have to learn the rules, but that's no hardship. *I* know about the precedence rule, but a newbie or a tired programmer might not. He might want to reverse the truth value of argument b but instead has just reversed the whole expression. Probably in a slightly convoluted code like this: if a is not(b and c): ... From weir009 at sina.com Tue Dec 30 04:23:52 2008 From: weir009 at sina.com (weir009 at sina.com) Date: Tue, 30 Dec 2008 01:23:52 -0800 (PST) Subject: How to debug embeding Python? References: Message-ID: <0c5f8b3f-873b-4b41-8435-9191c0fec875@w39g2000prb.googlegroups.com> Using udp to send out message is a convenient way, you may define a log function like following, and start a udp server to lisen. ############# from socket import * udpSock = socket(AF_INET,SOCK_DGRAM) def log(s): udpSock.sendto(s, ('127.0.0.1', 514)) log('hello') From nemokingdom at gmail.com Sun Dec 28 22:11:06 2008 From: nemokingdom at gmail.com (nemo) Date: Sun, 28 Dec 2008 19:11:06 -0800 (PST) Subject: ftp design question Message-ID: <74706983-5198-436b-b0ca-b0246a41c67e@v5g2000prm.googlegroups.com> Hi,all. I'm on a toy ftp project and I want it to be convinient for the user to cancel an undergoing downloading while continue others. The following code explains: for file in download_files: self.ftp.retrbinary('RETR '+file, fileHandler) Thers seems not a solid way to cancel this transfer and I considered thread or process but I can't handle this correctly. Thread: I can't kill the thread in another thread, so... Process: There seems something wrong(raise an EOFError exception) when I use Process(target = download_fun, args = (dir,)) for each downloading after connection built. Some suggestions? From rdmurray at bitdance.com Thu Dec 18 11:14:31 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Thu, 18 Dec 2008 16:14:31 +0000 (UTC) Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> <6qv7kfFeuf65U1@mid.uni-berlin.de> Message-ID: Quoth "Diez B. Roggisch" : > Neal Becker wrote: > > > Tino Wildenhain wrote: > > > >> Neal Becker wrote: > >> ... > >>> That makes no sense to me. If I call 'print' on a container, why > >>> wouldn't it recursively print on the contained objects? Since print > >>> means call str, printing a container should recursively call str on the > >>> objects. [...] > >> Every class is free on how to best implement __str__, you will find > >> the same behavior on tuple and list as well. > >> > >> Maybe its discussable to change the implementation sensibly, best if you > >> would come with a proposal? Perhaps pprint.pprint is a starting point? > >> > >> Regards > >> Tino > > > > First, I'd like to know if there is a rationale for the current design. > > Am I correct in thinking this is a defect? > > I don't think so. First of all, there is no "generic" way of printing a > collection. And the current implementation tries to give an overview what > is contained in the collection, without trying to make it "fancy" - any > such thing needed to be hand-coded anyway. > > Using repr for that is better suited, as for example string keys are printed > with quotes around them - making clear what they are, and not irritating > the user through potentially contained spaces or even things that look as > if they are python objects. > > For example, if repr *wasn't* used, > > { "{foo=bar}" : "baz"} > > would be printed > > {{foo=bar} : baz} > > Which is *not* what the dictionary actually contains! > > The same goes for unicode-objects. They appear with their "funny" characters > as \xXX-codes - instead of bailing out on you with unicode-errors. Note that this last is no longer true in Python 3.0. There, repr prints into the current encoding of the output, and so you may get decode errors. This is an accepted usability tradeoff, as it allows people using these character sets (and who therefore will have terminals set to display them!) to actually see the characters in their data. If you need the old behavior you use 'ascii'. --RDM From rhamph at gmail.com Tue Dec 9 14:34:31 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Tue, 9 Dec 2008 11:34:31 -0800 (PST) Subject: Rich Comparisons Gotcha References: Message-ID: <874a0b69-b5f3-4b9c-8fe3-d6a3275da422@w1g2000prm.googlegroups.com> You grossly overvalue using the "in" operator on lists. It's far more common to use a dict or set for containment tests, due to O(1) performance rather than O(n). I doubt the numpy array supports hashing, so an error for misuse is all you should expect. In the rare case that you want to test for identity in a list, you can easily write your own function to do it upfront: def idcontains(seq, obj): for i in seq: if i is obj: return True return False From steve at REMOVE-THIS-cybersource.com.au Wed Dec 31 03:34:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Dec 2008 08:34:48 GMT Subject: MemoryError when list append... plz help References: Message-ID: <016b25a5$0$6988$c3e8da3@news.astraweb.com> On Tue, 30 Dec 2008 22:02:49 -0800, [BON] wrote: > ====================== > s=[] > for i in range(11000-1): > for j in range(i+1, 11000): > .... > s.append(((i,j),sim)) > ====================== > above sim is floating type. > s.append is totally coducted 60,494,500 times. but this code raise > MemoryError. > > My computer has 4G RAM. > i think it's enough. but it doesn't... Your computer might have 4GB, but how much memory can Python allocate? What operating system are you using? Each time you are appending to the list, you append a tuple: ((i, j), sim) where sim is a float and i and j are ints. How much memory does each of those take? >>> sys.getsizeof( ((0, 1), 1.1) ) 32 So each entry requires 32 bytes. 60 million times 32 bytes = almost 2GB alone. Plus the list itself will require (approximately) between 230MB and 460MB just for the pointers. What are you expecting to do with this enormous list, and why do you need it all at once? -- Steven From arnodel at googlemail.com Fri Dec 5 15:27:27 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 05 Dec 2008 20:27:27 +0000 Subject: Overriding a method at the instance level on a subclass of a builtin type References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> Message-ID: Arnaud Delobelle writes: > "Zac Burns" writes: > >> Ok. Feature request then - assignment of a special method name to an >> instance raises an error. > > I haven't got the time to implement it, but I'm sure you can obtain the > behaviour you want. OK I've had half an hour to fill this afternoon so I tried to implement it. I've restriced the ability to override special methods to __getitem__ but this could be extended to any special method AFAICS. It combines a metaclass and two descriptors (one for the metaclass and one for the class), there may be a simpler way! It is proof-of-concept code, I have not tried to make it behave sensibly when no __getitem__ method is defined (although that would be straighforward) and I have not thought about how it would work with (multiple) inheritance (this may require lots more thinking). Here it is, tested very succintly on Python 2.5: class ClassGetItem(object): def __get__(self, obj, objtype=None): return obj._getitem_ def __set__(self, obj, val): obj._getitem_ = val class GetItem(object): def __get__(self, obj, objtype=None): return obj._getitem_ def __set__(self, obj, val): obj._getitem_ = val class MetaOverrideSpecial(type): def __new__(meta, name, bases, attrs): if '__getitem__' in attrs: attrs['_getitem_'] = attrs['__getitem__'] attrs['__getitem__'] = GetItem() return type.__new__(meta, name, bases, attrs) __getitem__ = ClassGetItem() class OverrideSpecial(object): __metaclass__ = MetaOverrideSpecial Here is an example that shows it in action: >>> class Foo(OverrideSpecial): ... def __getitem__(self, key): return 'Class getitem(%s)' % key ... >>> foo=Foo() >>> foo[3] 'Class getitem(3)' Override the class's __getitem__ special method: >>> Foo.__getitem__ = lambda self, key: 'Overriden class getitem(%s)' % key >>> foo['bar'] 'Overriden class getitem(bar)' Override the instance's __getitem__ special method: >>> foo.__getitem__ = lambda key: 'Instance getitem(%s)' % key >>> foo['baz'] 'Instance getitem(baz)' What-a-way-to-waste-time'ly yours -- Arnaud From steven at REMOVE.THIS.cybersource.com.au Mon Dec 22 20:25:48 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 23 Dec 2008 01:25:48 GMT Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: On Mon, 22 Dec 2008 07:11:02 -0800, walterbyrd wrote: > I have read that python is the world's 3rd most popular language Oh, well if it's written down it must be true. > But, I can't help but wonder how python's popularity was determined. Why don't you ask the people who made the claim? -- Steven From nick at craig-wood.com Tue Dec 2 13:30:47 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 02 Dec 2008 12:30:47 -0600 Subject: Do more imported objects affect performance References: <1be78d220812010621u51dead9dnbaa0b4c8c9414362@mail.gmail.com> <79153a2e0812012124o7401df57m4ac21dfe37c2ec5@mail.gmail.com> <01453438$0$20670$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Tue, 02 Dec 2008 11:12:31 +0000, Nick Craig-Wood wrote: > > > I prefer the "from module import function". That means that if "module" > > doesn't supply "function" it raises an exception at compile time, not > > run time when you try to run "module.function". > > Wanna bet? > > > >>> def spam(): > ... from math import harmonic_series > ... return harmonic_series() > ... > >>> dis.dis(spam) > 2 0 LOAD_CONST 1 (-1) > 3 LOAD_CONST 2 (('harmonic_series',)) > 6 IMPORT_NAME 0 (math) > 9 IMPORT_FROM 1 (harmonic_series) > 12 STORE_FAST 0 (harmonic_series) > 15 POP_TOP > > 3 16 LOAD_FAST 0 (harmonic_series) > 19 CALL_FUNCTION 0 > 22 RETURN_VALUE > >>> spam() > Traceback (most recent call last): > File "", line 1, in > File "", line 2, in spam > ImportError: cannot import name harmonic_series > > > The same thing happens if the from...import is at the top level of the > module, except that compilation is immediately followed by > execution. You are technically right I am sure. However the error happens when you import the module with the error in, not when you run stuff from it which is the major difference. $ echo -e "from os import sausage\n" > import_test.py $ python Python 2.5.2 (r252:60911, Sep 29 2008, 21:15:13) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> # This does produce an error >>> import import_test Traceback (most recent call last): File "", line 1, in File "import_test.py", line 1, in from os import sausage ImportError: cannot import name sausage >>> $ # This produces an error also $ python import_test.py Traceback (most recent call last): File "import_test.py", line 1, in from os import sausage ImportError: cannot import name sausage $ Unlike $ echo -e "import os\ndef f(): os.sausage\n" > import_test.py $ python Python 2.5.2 (r252:60911, Sep 29 2008, 21:15:13) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> # This doesn't produce an error >>> import import_test >>> # Until you actually call it >>> import_test.f() Traceback (most recent call last): File "", line 1, in File "import_test.py", line 2, in f def f(): os.sausage AttributeError: 'module' object has no attribute 'sausage' >>> $ # No error here either $ python import_test.py $ > > It then becomes very easy to see which functions you use from any > > given module too. > > If that's important to you. Personally, I find it more useful to know > where a function is defined. We can agree to differ there I'm sure ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From stef.mientki at gmail.com Tue Dec 23 07:53:07 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 23 Dec 2008 13:53:07 +0100 Subject: Why MyHDL? In-Reply-To: <4950d063$0$2853$ba620e4c@news.skynet.be> References: <4950d063$0$2853$ba620e4c@news.skynet.be> Message-ID: <4950DF33.3010100@gmail.com> hello Jan, Jan Decaluwe wrote: > Hello: > > MyHDL is a Python package for using Python as a > Hardware Description Language. > > A new release is upcoming, and on this occasion > we have prepared a page about why MyHDL may > be useful to you: > > http://www.myhdl.org/doku.php/why > Very Interesting, I'm no expert at all (but as an exercise I'm just now writing an EDIF-v2 to SystemC converter in Python) , I wonder why I only see comparison with VHDL and SystemVerilog, and not with SystemC ? thanks, Stef From hackingkk at gmail.com Mon Dec 15 13:00:43 2008 From: hackingkk at gmail.com (Krishnakant) Date: Mon, 15 Dec 2008 23:30:43 +0530 Subject: %s place holder does not let me insert ' in an sql query with python. In-Reply-To: <49469568.2090203@holdenweb.com> References: <1229345178.31093.24.camel@krishna-laptop> <49469568.2090203@holdenweb.com> Message-ID: <1229364043.31093.67.camel@krishna-laptop> Hi steve. you are right. Thanks for all you who helped to understand how to and *not* to pass queries through psycopg2 which is a module based on python dbapi. the following query worked. cursor.execute("insert into vendors values(%s,%s)", lstParams) lstParams contained all the values and yes one had an ' in it. thanks again for all the help. happy hacking. Krishnakant. On Mon, 2008-12-15 at 12:35 -0500, Steve Holden wrote: > Lamonte Harris wrote: > > I had this problem too. If you've upgraded to python 2.6 you need to > > use the new sytnax "format > > > > queryString = "insert into venders > > values('{0}','{1}','{2}'".format(field1,field2,field3) > > > Will all readers of this thread kindly regard this as an example of how > *not* to generate and execute SQL queries in Python. Study the > cursor.execute() method, and provide parameterized queries and a data > tuple instead. > > Please also note that the above technique explicitly continues to > generate SQL syntax errors in Krishnakan's case where the data values > themselves contain apostrophes. > > regards > Steve From bblais at bryant.edu Sun Dec 7 15:27:08 2008 From: bblais at bryant.edu (Brian Blais) Date: Sun, 7 Dec 2008 15:27:08 -0500 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: On Dec 5, 2008, at 21:21 , Daniel Fetchinson wrote: > The proposal is to allow this: > > class C: > def self.method( arg ): > self.value = arg > return self.value > > instead of this: > > class C: > def method( self, arg ): > self.value = arg > return self.value > I have never understood the objection to the explicit self. As far as I can tell it just stems from laziness, and perhaps (more legitimately) from an unclear error message about arguments. When I was a python newbie, a short while ago, I would have to look twice at the number of arguments in the error, but quickly learned what this meant. Forgetting self, which I still do, makes me do a face slap, but I always felt that it is *my* problem, and I still do. It is far clearer what is going on with the explicit self. Even if I were lazy, and didn't want to type it, it seems as if the proposal saves me nothing there....so why have it? It is also confusing, because when you're reading the code, "self" is not defined at the time, so it looks weird to have self.method pop up. Allowing both would be *ultra* confusing. I teach python to a lot of students who are new programmers, and for them to see two different forms for the same thing would be very bad, and I see absolutely no benefit, even to experienced programmers. What problem is it supposed to solve? +1 on changing the error text, however, perhaps even with a suggestion..."possibly missing 'self' argument." bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at microcorp.co.za Tue Dec 23 05:21:18 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 23 Dec 2008 12:21:18 +0200 Subject: Python's popularity (a bit OT) References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> <7c02eb33-a919-4481-8eda-76062729f233@k19g2000yqg.googlegroups.com> Message-ID: <01e601c964e9$d1b7a1c0$0d00a8c0@hendrik> "r" wrote: >I think you missed my point Steven, I was in no way proud of the fact >of my 9th place rating. It just proves my point to the small following >of this group. And frankly makes me feel bad. This spurt of high frequency posts is something that seems to happen to most newcomers to the group. (I think - I have done no stats on it, but I get the feeling...) So maybe the advice is to settle down and enjoy using the resource, because it is an amazing one - there are some hyper intelligent people around. Some of them have some experience. Some of them even know a little python... It also helps if you answer some of the newbie questions, as it crystallises your own knowledge of the language. - that is the way to show how big your cojones are. Nobody believes your claims based on mere descriptions. As you go along, you will find that this group will rarely let you get away with talking nonsense - It has been my experience that my slightest error or fumble has almost always been pitilessly pointed out. I think it is because the volume is high, and people get irritated if they have to wade through stuff like this post that has more to do with etiquette than python. - Hendrik From Scott.Daniels at Acm.Org Mon Dec 29 14:05:52 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 29 Dec 2008 11:05:52 -0800 Subject: why cannot assign to function call In-Reply-To: <97a11245-a034-4558-82d4-0c87e02bdb7e@u18g2000pro.googlegroups.com> References: <97a11245-a034-4558-82d4-0c87e02bdb7e@u18g2000pro.googlegroups.com> Message-ID: <47-dnUx1_OP7gsTUnZ2dnUVZ_r6dnZ2d@pdx.net> John Machin wrote: > On Dec 29, 5:01 pm, scsoce wrote: >> I have a function return a reference, > > Stop right there. You don't have (and can't have, in Python) a > function which returns a reference that acts like a pointer in C or C+ > +. Please tell us what manual, tutorial, book, blog or Usenet posting > gave you that idea, and we'll get the SWAT team sent out straight > away. Perhaps we can send the the Pennsylvania State University out after them. I don't know why, but some fairly substantial people here are scared of the PSU. ... Oh, I have just been informed by my captors that the are the Python Secre.... From rt8396 at gmail.com Tue Dec 2 19:24:06 2008 From: rt8396 at gmail.com (r) Date: Tue, 2 Dec 2008 16:24:06 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> Message-ID: <00ab327a-c3fc-4b15-a084-4f8c6aed6a8e@o2g2000yqd.googlegroups.com> I added you name to my "for" list. thanks From martin at marcher.name Fri Dec 26 15:42:34 2008 From: martin at marcher.name (Martin) Date: Fri, 26 Dec 2008 21:42:34 +0100 Subject: [SQL] Right way to set a variable to NULL? In-Reply-To: <5nfal41gom0iqi2nh5h0m5847ev9brtvpf@4ax.com> References: <5nfal41gom0iqi2nh5h0m5847ev9brtvpf@4ax.com> Message-ID: <5fa6c12e0812261242l34d26484k3e1661e3f567cad8@mail.gmail.com> Hi, I'd create a simple wrapper object class MailAddress(object): def __init__(self, address=None): self.address = address def __str__(self): if address: return self.adress return "NULL" you can keep most of your code just replace the original instantiation of the mail str-instance with the MailAddress This is just scratched up quickly. Hope it helps Martin 2008/12/26 Gilles Ganault : > sql = 'INSERT INTO mytable (name,address,web,mail) VALUES > ("%s","%s","%s","%s","%s")' % (name,address,web,mail) > ======= > > Is there a better way in Python to have a variable match NULL than > building the SQL query step by step? > > Thank you. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://soup.alt.delete.co.at http://www.xing.com/profile/Martin_Marcher http://www.linkedin.com/in/martinmarcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From sturlamolden at yahoo.no Fri Dec 12 08:43:05 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 05:43:05 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> Message-ID: <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> On Dec 12, 2:29 pm, sturlamolden wrote: > Creating a fast implementation of a dynamic language is almost rocket > science. But it has been done. There is Stronghold, I meant of course Strongtalk... From shao.tu at gmail.com Fri Dec 12 01:50:06 2008 From: shao.tu at gmail.com (stalex) Date: Thu, 11 Dec 2008 22:50:06 -0800 (PST) Subject: Py_GetPath() C API in python 3 References: <772bb62b-1ef1-4ffa-90f6-c1cbdc728fdd@q30g2000prq.googlegroups.com> Message-ID: On 12?11?, ??5?53?, stalex wrote: > Hi all, > > I want to build a new, requires total control, python interpreter. So > I implement my own version of Py_GetPath(), Py_GetPrefix(), > Py_GetExecPrefix() and Py_GetProgramFullPath(). When compiling, I > always get error messages, for each API function, look like > followings: > > /opt/python-3.0/lib/python3.0/config/libpython3.0.a(getpath.o)(.text > +0x211c): In function `Py_GetPath': > ./Modules/getpath.c:739: multiple definition of `Py_GetPath' > myApp.o(.text+0x0):/home/alex/workspace/develop/src/myApp.c:11: first > defined here > /usr/bin/ld: Warning: size of symbol `Py_GetPath' changed from 126 in > system.o to 32 in /opt/python-3.0/lib/python3.0/config/libpython3.0.a > (getpath.o) > collect2: ld returned 1 exit status > > If I compile my application with python 2.x, everything's just okay > and my application as well. Any ideas on how to get this working for > python 3? Nobody could answer this question? From martin at v.loewis.de Mon Dec 8 20:04:18 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 09 Dec 2008 02:04:18 +0100 Subject: python-devel download and install In-Reply-To: References: Message-ID: <493DC412.8060909@v.loewis.de> > I am developing in Python version 2.5.2 and need to install and download > the python-devel library. (This is needed so I can build and install > mysql-python.) Where can I find find this module to download and > build/installation instructions? I have been unable to find the source > online to download. > > I am not root on the box where I need to install this module so I need > the source (rpm/deb packages will not do). The sources of Python 2.5.2 are available from http://www.python.org/ftp/python/2.5.2/Python-2.5.2.tar.bz2 The term "python-devel" specifically refers to a rpm/deb package, though. You might need to layout the sources so that they meet your needs (e.g. by installing them locally). Regards, Martin From bsk16 at case.edu Mon Dec 8 12:14:56 2008 From: bsk16 at case.edu (Ben Kaplan) Date: Mon, 8 Dec 2008 12:14:56 -0500 Subject: Calling C# COM (.NET) from python In-Reply-To: References: Message-ID: <2CE93A19-C4D3-4AA0-890C-43BB9F6747CE@case.edu> On Dec 8, 2008, at 11:53 AM, Andrew Falanga wrote: > Hi, > > I've never programmed in python and only have a small understanding of > what is wrapped up in the terms COM and .NET. Is there a way of using > python to get a hold of objects written in C# as COM objects using > python? I'm looking for ways to avoid VBScript (which, after a couple > of weeks, I've determined to be horrid). That is, is there a way of > getting at COM objects in python that's similar to doing a > CreateObject call in VBScript (http://msdn.microsoft.com/en-us/ > library/ > dcw63t7z.aspx)? > > Thanks, > Andy > -- > http://mail.python.org/mailman/listinfo/python-list I would not deal with COM at all. I personally have not used it, but there is a version of python called IronPython that's written in C#, so it can use .NET and, I think, other C# objects. Other people will probably help you more, but you might want to look into that and maybe ask this on the python-win list. From gandalf at shopzeus.com Sun Dec 7 13:27:05 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Sun, 07 Dec 2008 19:27:05 +0100 Subject: How to Write to csv file to create bulk address book In-Reply-To: <5387c7a1-eb04-4d27-826c-d6257298e2db@f40g2000pri.googlegroups.com> References: <5387c7a1-eb04-4d27-826c-d6257298e2db@f40g2000pri.googlegroups.com> Message-ID: <493C1579.7030302@shopzeus.com> > I am new to scripting, I am working on script which would create 'n' > number address book entries into a csv file which would be used to > import into a address book. I need suggestions for the same > Please check out the 'csv' module. It comes with Python. Batteries included. :-) http://docs.python.org/library/csv.html There are nice examples at the end of that page. From vinay_sajip at yahoo.co.uk Sun Dec 7 07:21:57 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Sun, 7 Dec 2008 04:21:57 -0800 (PST) Subject: Select, interrupted system call, log rotation? References: <2b8928dd-4d0c-4e90-ba1e-1c68068c73d1@t3g2000yqa.googlegroups.com> Message-ID: <0a3e3a05-4815-4325-97dc-8aa5e77e1f8d@l16g2000yqo.googlegroups.com> On Dec 6, 8:39 pm, Rainy wrote: > I got an interrupted system call exception in select and I don't know > what could have caused it. Here's the error: > > select.select(inputs, [], [], 9) > error: (4, 'Interrupted system call') > Caught an exception, shutting down... > > It's py2.3, on mach architecture. > > I'm trying to figure out what caused it, and the only idea I have so > far is that it could be that I have python's logging system log > rotation thing running and I think I've seen a reference somewhere > that it uses SIGALRM when log file reaches set size to stop and switch Python's logging package doesn't use signals, as it's cross-platform. The handler just checks when a log event is handled whether rotation should occur, and if it should, then the log files are rotated. Regards, Vinay Sajip From tjreedy at udel.edu Thu Dec 4 14:37:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Dec 2008 14:37:58 -0500 Subject: schizophrenic view of what is white space In-Reply-To: <49381C2E.3060707@mrabarnett.plus.com> References: <4937E8E5.2090306@chamonix.reportlab.co.uk> <20081204143337.20272.1236189783.divmod.quotient.15592@ohm> <4938112F.5030706@chamonix.reportlab.co.uk> <49381C2E.3060707@mrabarnett.plus.com> Message-ID: MRAB wrote: > Robin Becker wrote: >> Jean-Paul Calderone wrote: >> ......... >>> >>> You have to give the re module an additional hint that you care about >>> unicode: >>> >>> exarkun at charm:~$ python >>> Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu >>> 4.2.3-2ubuntu7)] on linux2 >>> Type "help", "copyright", "credits" or "license" for more information. >>> >>> import re >>> >>> print re.compile(r'\s').search(u'a\xa0b') >>> None >>> >>> print re.compile(r'\s', re.U).search(u'a\xa0b') >>> <_sre.SRE_Match object at 0xb7dbb3a0> >>> >>> >>> >>> Jean-Paul >> ....... >> >> so the default behaviour differs for unicode and re working on >> unicode. I suppose that won't be true in Python 3. > > > I'm not sure why the Unicode flag is needed in the API. I reckon that it > should just look at the text that the regular expression is being > applied to: if it's Unicode then follow the Unicode rules, if not then > don't. I presume because \b is interpreted and replaced when the re is compiled into internal state machine form. From mail at microcorp.co.za Fri Dec 5 13:54:11 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 5 Dec 2008 20:54:11 +0200 Subject: Guido's new method definition idea References: Message-ID: <006201c95745$12e30e80$0d00a8c0@hendrik> "James Stroud" wrote: > Consider the maverick who insists on 8<--------example with "me" instead of "self" -------- > What's the interpreter going to do with our maverick's code? Took me a while, but after I remembered that a "maverick" is an unmarked, wild member of the bovine species that is effectively res nullius, I suppose the answer should be that he or she be brought back into the fold by being branded in the normal fashion - the application of a hot iron, in the shape of the standard python logo, to the buttocks. - Hendrik From Eric_Dexter at msn.com Mon Dec 1 03:39:08 2008 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Mon, 1 Dec 2008 00:39:08 -0800 (PST) Subject: tkinter question References: <538f4349-02a1-4c2b-b892-a01f1f48cb5b@l64g2000hse.googlegroups.com> Message-ID: On Oct 26, 7:02?am, "Chuckk Hubbard" wrote: > Hello. > How about this? ?I changed the if statements so the coordinates are > always updated, but only changed if within the right limits, otherwise > updated to the existing value. ?Now if you drag outside the limits of > one dimension, it still moves in the other dimension. ?Not sure if > that's what you want. ?I'm amazed that this can be so simple, I came > up with an intricate system for my app, not realizing I could bind > events to canvas items! > BTW, I've never come across csoundroutines, can you give me a synopsis > of what it's for? ?I'm using thePythonCsoundAPI. ?This is why I > commented out all the references to csoundroutines, I don't have it > installed at the moment. > -Chuckk > > #!/usr/bin/python > from Tkinter import * > #import csoundroutines as cs > > root = Tk() > > global canv > xx = {} > > def makeFrame(root): > ? global canv > # ?test = cs.csdInstrumentlist3('bay-at-night.csd') > ? canv = Canvas (root, height = 200, width = 350) > > # ?for i in range (0, len(test.instr_number)): > ? for i in range (0, 4): > # ? ?canv.create_text(10, i *10, text=str(test.instr_number[i]) + > ? ? canv.create_text(10, i *10, text=str(i) + > '...', tags=('movable')) > ? ? xx[i] = canv.tag_bind('movable', '', slide) #B1-motion > is a drag with left button down > ? ? canv.pack() > > def slide (event): > ? ''' > ? triggered when something is dragged on the canvas - move thing > under > mouse ('current') to new position > ? ''' > ? if 0 < event.x < 200: > ? ? ? newx = event.x > ? else: newx = canv.coords('current')[0] > ? if 0 < event.y < 100: > ? ? newy = event.y > ? else: newy = canv.coords('current')[1] > ? canv.coords('current', newx, newy) > > makeFrame(root) > root.mainloop() > > > > > > On Fri, Oct 3, 2008 at 3:44 PM, Eric_Dex... at msn.com wrote: > > I saw this (close to this anyway) lieing around on the internet and > > was wanting to use it to define a start point exc but I need the > > graphics to stay within a set y coords and I am not realy sure how to > > do that. ?I have no idea on how to bind a min/max y to it. ?(the > > concept is inspired by the javacsoundblue). > > > #!/usr/bin/python > > from Tkinter import * > > import csoundroutines as cs > > > root = Tk() > > > global canv > > xx = {} > > > def makeFrame(root): > > ? global canv > > ? test = cs.csdInstrumentlist3('bay-at-night.csd') > > ? canv = Canvas (root, height = 200, width = 350) > > > ? for i in range (0, len(test.instr_number)): > > ? ? canv.create_text(10, i *10, text=str(test.instr_number[i]) + > > '...', tags=('movable')) > > ? ? xx[i] = canv.tag_bind('movable', '', slide) #B1-motion > > is a drag with left button down > > ? ? canv.pack() > > > def slide (event): > > ? ''' > > ? triggered when something is dragged on the canvas - move thing > > under > > mouse ('current') to new position > > ? ''' > > ? newx = event.x > > ? if event.y < 10 and event.y > 0: > > ? ? newy = event.y > > ? ? canv.coords('current', newx, newy) > > > makeFrame(root) > > root.mainloop() > > -- > >http://mail.python.org/mailman/listinfo/python-list > > --http://www.badmuthahubbard.com- Hide quoted text - > > - Show quoted text - sorry to take so long to reply... You should be able to find the latest version of csound routines in the csound blog.. an older version is in dex tracker available on source forge.. From castironpi at gmail.com Mon Dec 29 21:52:59 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 18:52:59 -0800 (PST) Subject: multiprocessing vs thread performance References: <26f7d44e-552c-41e9-9290-17e5c4e6deb9@q30g2000prq.googlegroups.com> Message-ID: On Dec 29, 7:40?pm, "James Mills" wrote: > On Tue, Dec 30, 2008 at 11:34 AM, Aaron Brady wrote: > > The OP may be interested in Erlang, which Wikipedia (end-all, be-all) > > claims is a 'distribution oriented language'. snip > I'm presently looking at Virtual Synchrony and > other distributed processing architectures - but > circuits is meant to be general purpose enough > to fit event-driven applications/systems. I noticed a while ago that threads can be used to simulate generators. 'next', 'send', and 'yield' are merely replaced by synchronizor calls (coining the term). Not the other way around, though, unless the generator guarantees a yield frequently. 'settrace' anyone? From bearophileHUGS at lycos.com Wed Dec 31 13:42:42 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 31 Dec 2008 10:42:42 -0800 (PST) Subject: How to initialize an array with a large number of members ? References: <5m4nl4hs8f9q6rfcp7b1jt7nk1o6sq6r0f@4ax.com> Message-ID: <2ef1ba2a-ae6f-4206-990e-d148a80dd17a@p2g2000prf.googlegroups.com> MRAB: > ?>>> # With a list > ?>>> tally = array('H', [0] * 75) > ?>>> > ?>>> # With a generator > ?>>> tally = array('H', (0 for i in range(75))) Time ago we have had a long discussion about this, the right way is: tally = array(someformat, [0]) * 75 (If you need to initialize it to something that isn't constant then you may have to do something different). Bye, bearophile From gagsl-py2 at yahoo.com.ar Sat Dec 13 23:10:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 14 Dec 2008 02:10:41 -0200 Subject: Bidirectional Networking References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <6qeht0Fc3541U1@mid.individual.net> <782258db-2bdc-45a7-8d8f-7a036d574985@t26g2000prh.googlegroups.com> <2cf74767-e331-4fa6-8915-8f87ba01ca34@l33g2000pri.googlegroups.com> Message-ID: En Sat, 13 Dec 2008 13:03:17 -0200, Emanuele D'Arrigo escribi?: > On Dec 12, 9:04 pm, "Gabriel Genellina" > wrote: >> If you're using 2.5 or older, override serve_forever: >> >> def serve_forever(self): >> while not getattr(self, 'quit', False): >> self.handle_request() >> >> and set the server 'quit' attribute to True in response to some command >> from the client. > > Ok, I've tried this method and it would work if I wanted to shut down > the server from the remote client. But if I want the server to shut > down from the server itself upon some condition it doesn't work > because the while statement is evaluated again only after there has > been a request. If requests are infrequent or have ceased the Yes, this is the problem with this simple approach, handle_request is blocking. Python 2.6 has great improvements on this situation. > The problem was that in my code I used: > > asyncServer.daemon = True > > but somehow that doesn't work. I then tried: > > asyncServer.setDaemon(True) > > and that does work: daemon became a property in Python 2.6; setDaemon was the only way to set it in previous versions. > Thanks for your help! Thanks for sharing your code! -- Gabriel Genellina From bearophileHUGS at lycos.com Sun Dec 7 15:27:45 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 7 Dec 2008 12:27:45 -0800 (PST) Subject: Is 3.0 worth breaking backward compatibility? References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> Message-ID: walterbyrd: > I can not think of anything that is being changed that was really a "show stopper" anyway.< I agree, but Python and its culture has a characteristic that not many other languages share: it tries to be a tidy language, to have one obvious way to do most things, it values readability and sometimes even elegance. So even if those problems aren't "showstoppers" for most languages, for the Python culture they are bad enough to need a fix. The amount of warts in the language that a Python programmer is used to tolerate in the the language is probably 1/20 of the warts a C++ programmer digests with no problem every day. Different languages, different cultures, and sometimes even different psychology & cognitive profile of the programmer. Bye, bearophile From zip610041 at gmail.com Sun Dec 7 08:14:01 2008 From: zip610041 at gmail.com (zip610041 at gmail.com) Date: Sun, 7 Dec 2008 05:14:01 -0800 (PST) Subject: Free Partitioning Software Introduction Message-ID: <6e756b72-3325-4282-aa00-e36da90fb097@k36g2000pri.googlegroups.com> Free Partitioning Software (Partition Editors, Managers, and Recovery Tools) The partition manager (editors,software,recovery tools) listed as below: Cute Partition Manager GParted LiveCD Partition Logic SwissKnife SystemRescueCD Ultimate Boot CD Ranish Partition Manager The Partition Resizer Diskman NTFS Resize TestDisk Extended FDISK More Detail http://partition-manager.blogspot.com/2008/12/free-partitioning-software-introduction.html From __peter__ at web.de Fri Dec 19 06:45:56 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2008 12:45:56 +0100 Subject: List comprehension in if clause of another list comprehension References: Message-ID: Vedran Furac( wrote: > Hi! > > In [69]: a = 'a b c' > In [70]: b = 'a b, c d' > > In [74]: [i for i in a.split() if i not in b.split()] > Out[74]: ['b'] > > Everything ok. > > In [77]: b.split() == [i for i in b.split()] > Out[77]: True > > As expected. Now, put this in the first list comprehension: > > In [80]: [i for i in a.split() if i not in [i for i in b.split()] ] > Out[80]: ['d'] > > Hmmmm... why is that? >>> a = "abc" >>> b = "a b, c d".split() >>> b ['a', 'b,', 'c', 'd'] >>> [i for i in a if i not in b] ['b'] As expected, so far, but now comes the critical step: >>> [i for i in a if i not in [i for i in b]] ['d'] The problem is that list comprehensions do not introduce a new namespace. So the inner and the outer list comp share the same i. You can either rename the inner i >>> [i for i in a if i not in [k for k in b]] ['b'] or use a generator expression which does give a new namespace: >>> list(x for x in "abc") ['a', 'b', 'c'] >>> x Traceback (most recent call last): File "", line 1, in NameError: name 'x' is not defined >>> [i for i in a if i not in (i for i in b)] ['b'] Peter From jason-sage at creativetrax.com Thu Dec 4 21:09:23 2008 From: jason-sage at creativetrax.com (jason-sage at creativetrax.com) Date: Thu, 04 Dec 2008 20:09:23 -0600 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: <49388D53.7020808@creativetrax.com> Xah Lee wrote: > alright, here's my improved code, pasted near the bottom. > > let me say a few things about Jon's code. > > If we rate that piece of mathematica code on the level of: Beginner > Mathematica programer, Intermediate, Advanced, where Beginner is > someone who just learned tried to program Mathematica no more than 6 > months, then that piece of code is Beginner level. > > Here's some basic analysis and explanation. > > The program has these main functions: > > ? RaySphere > ? Intersect > ? RayTrace > ? Create > ? Main > > The Main calls Create then feed it to RayTrace. > Create calls itself recursively, and basically returns a long list of > a repeating element, each of the element differ in their parameter. > > RayTrace calls Intersect 2 times. Intersect has 2 forms, one of them > calls itself recursively. Both forms calls RaySphere once. > > So, the core loop is with the Intersect function and RaySphere. Some > 99.99% of time are spent there. > > ------------------ > > I didn't realize until after a hour, that if Jon simply give numerical > arguments to Main and Create, the result timing by a factor of 0.3 of > original. What a incredible sloppiness! and he intended this to show > Mathematica speed with this code? > > The Main[] function calls Create. The create has 3 parameters: level, > c, and r. The level is a integer for the recursive level of > raytracing . The c is a vector for sphere center i presume. The r is > radius of the sphere. His input has c and r as integers, and this in > Mathematica means computation with exact arithmetics (and automatic > kicks into infinite precision if necessary). Changing c and r to float > immediately reduced the timing to 0.3 of original. > > ------------------ > now, back to the core loop. > > The RaySphere function contain codes that does symbolic computation by > calling Im, which is the imaginary part of a complex number!! and if > so, it returns the symbol Infinity! The possible result of Infinity is > significant because it is used in Intersect to do a numerical > comparison in a If statement. So, here in these deep loops, > Mathematica's symbolic computation is used for numerical purposes! > > So, first optimization at the superficial code form level is to get > rid of this symbolic computation. > > Instead of checking whethere his ?disc = Sqrt[b^2 - v.v + r^2]? has > imaginary part, one simply check whether the argument to sqrt is > negative. > > after getting rid of the symbolic computation, i made the RaySphere > function to be a Compiled function. > > I stopped my optimization at this step. > > The above are some _fundamental_ things any dummy who claims to code > Mathematica for speed should know. Jon has written a time series > Mathematica package that he's selling commercially. So, either he got > very sloppy with this Mathematica code, or he intentionally made it > look bad, or that his Mathematica skill is truely beginner level. Yet > he dares to talk bullshit in this thread. > > Besides the above basic things, there are several aspects that his > code can improve in speed. For example, he used pattern matching to do > core loops. > e.g. Intersect[o_, d_][{lambda_, n_}, Bound[c_, r_, s_]] > > any Mathematica expert knows that this is something you don't want to > do if it is used in a core loop. Instead of pattern matching, one can > change the form to Function and it'll speed up. > > Also, he used ?Block?, which is designed for local variables and the > scope is dynamic scope. However the local vars used in this are local > constants. A proper code would use ?With? instead. (in lisp, this is > various let, let*. Lispers here can imagine how lousy the code is > now.) > > Here's a improved code. The timing of this code is about 0.2 of the > original. Also, optimization is purely based on code doodling. That > is, i do not know what his code is doing, i do not have experience in > writing a ray tracer. All i did is eyeballing his code flow, and > improved the form. > > norm=Function[#/Sqrt@(Plus@@(#^2))]; > delta=Sqrt[$MachineEpsilon]; > myInfinity=10000.; > > Clear[RaySphere]; > RaySphere = Compile[{o1, o2, o3, d1, d2, d3, c1, c2, c3, r}, > Block[{v = {c1 - o1, c2 - o2, c3 - o3}, > b = d1*(c1 - o1) + d2*(c2 - o2) + d3*(c3 - o3), > discriminant = -(c1 - o1)^2 - (c2 - o2)^2 + > (d1*(c1 - o1) + d2*(c2 - o2) + d3*(c3 - o3))^2 - > (c3 - o3)^2 + r^2, disc, t1, t2}, > If[discriminant < 0., myInfinity, > disc = Sqrt[discriminant]; If[(t1 = b - disc) > 0., > t1, If[(t2 = b + disc) <= 0., myInfinity, t2]]]]]; > > Remove[Intersect]; > Intersect[{o1_,o2_,o3_},{d1_,d2_,d3_}][{lambda_,n_},Sphere > [{c1_,c2_,c3_},r_]]:= > Block[{lambda2=RaySphere[o1,o2,o3,d1,d2,d3,c1,c2,c3,r]}, > If[lambda2?lambda,{lambda,n},{lambda2, > norm[{o1,o2,o3}+lambda2 *{d1,d2,d3}-{c1,c2,c3}]}]] > > Intersect[{o1_,o2_,o3_},{d1_,d2_,d3_}][{lambda_,n_}, > Bound[{c1_,c2_,c3_},r_,s_]]:= > Block[{lambda2=RaySphere[o1,o2,o3,d1,d2,d3,c1,c2,c3,r]}, > If[lambda2?lambda,{lambda,n}, > Fold[Intersect[{o1,o2,o3},{d1,d2,d3}],{lambda,n},s]]] > > Clear[neglight,nohit] > neglight=N at norm[{1,3,-2}]; > nohit={myInfinity,{0.,0.,0.}}; > > Clear[RayTrace]; > RayTrace[o_,d_,scene_]:= > Block[{lambda,n,g,p},{lambda,n}=Intersect[o,d][nohit,scene]; > If[lambda\[Equal]myInfinity,0,g=n.neglight; > If[g?0, > 0,{lambda,n}=Intersect[o+lambda d+delta n,neglight] > [nohit,scene]; > If[lambda > Clear[Create]; > Create[level_,c_,r_]:= > Block[{obj=Sphere[c,r]}, > If[level\[Equal]1,obj, > Block[{a=3*r/Sqrt[12],Aux}, > Aux[x1_,z1_]:=Create[level-1,c+{x1,a,z1},0.5 r]; > Bound[c,3 r,{obj,Aux[-a,-a],Aux[a,-a],Aux[-a,a],Aux[a,a]}] > ] > ]] > > Main[level_,n_,ss_]:= > With[{scene=Create[level,{0.,-1.,4.},1.]}, > Table[Sum[ > RayTrace[{0,0,0}, > N at norm[{(x+s/ss/ss)/n-1/2,(y+Mod[s,ss]/ss)/ > n-1/2,1}],scene],{s,0, > ss^2-1}]/ss^2,{y,0,n-1},{x,0,n-1}]] > > Timing[Export["image.pgm",Graphics at Raster@Main[2,100,4.]]] > > > Note to those who have Mathematica. > Mathematica 6 has Normalize, but that's not in Mathematica 4, so i > cooked up above. > Also, Mathematica 6 has AbsoluteTiming, which is intended to be > equivalent if you use stop watch to measure timing. Mathematica 4 has > only Timing, which measures CPU time. My speed improvement is based on > Timing. But the same factor will shown when using Mathematica 6 too. > > For the interested, with MMA 6, on a Pentium 4 3.8Ghz: The code that Jon posted: Timing[Export["image-jon.pgm", Graphics at Raster@Main[2, 100, 4]]] {80.565, "image-jon.pgm"} The code that Xah posted: Timing[Export["image-xah.pgm", Graphics at Raster@Main[2, 100, 4.]]] {42.3186, "image-xah.pgm"} So Xah's code is about twice as fast as Jon's code, on my computer. The resulting files were identical (and both looked like pure white images; I thought they'd be interesting!). -J From prologic at shortcircuit.net.au Tue Dec 30 17:32:13 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 08:32:13 +1000 Subject: get method In-Reply-To: References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> Message-ID: On Tue, Dec 30, 2008 at 7:10 PM, Roel Schroeven wrote: > Hm, you just changed an O(n) algorithm to an O(n**2) algorithm. No big > deal for short strings, but try your solution on a string with length > 10000 and see the difference. On my computer the O(n) version takes > 0.008 seconds, while your version takes 8.6 seconds. That's 1000 times > slower. Yes you are right :) Sadly :/ I wonder if there is a way to implement the same thing with close to O(n) complexity using list/dict comprehensions. cheers James From pyth0nc0d3r at gmail.com Mon Dec 15 08:21:55 2008 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Mon, 15 Dec 2008 07:21:55 -0600 Subject: %s place holder does not let me insert ' in an sql query with python. In-Reply-To: References: <1229345178.31093.24.camel@krishna-laptop> Message-ID: sorry about that queryString = "insert into venders values('{0}','{1}','{2}')".format(field1,field2,field3) On Mon, Dec 15, 2008 at 7:21 AM, Lamonte Harris wrote: > I had this problem too. If you've upgraded to python 2.6 you need to use > the new sytnax "format > > queryString = "insert into venders > values('{0}','{1}','{2}'".format(field1,field2,field3) > > > On Mon, Dec 15, 2008 at 6:46 AM, Krishnakant wrote: > >> hello all hackers. >> This is some kind of an interesting situation although many of you must >> have already gone through it. >> I am facing a situation where I have to use psycopg2 and insert rows in >> a postgresql table. >> That's pritty easy and no need to say that it works well. But there are >> some entries which have an ' in the value. >> I have a venders table in my database and one of the values tryed was >> "His Master's Voice " >> now the master's word has the ' which is used for starting and ending a >> varchar value for postgresql or almost any standard RDBMS. >> Does any one know what is the way out of this? >> how do you let the ' go as a part of the string? >> I have used %s as placeholder as in >> queryString = "insert into venders values ('%s,%s,%s" % >> (field1,field2,field3 ) ... >> This is not working for the ' values. >> can any one suggest a suitable solution? >> happy hacking. >> Krishnakant. >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From marco at sferacarta.com Fri Dec 5 08:06:37 2008 From: marco at sferacarta.com (Marco Mariani) Date: Fri, 05 Dec 2008 14:06:37 +0100 Subject: Don't you just love writing this sort of thing :) In-Reply-To: <01490cc5$0$20670$c3e8da3@news.astraweb.com> References: <01490cc5$0$20670$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Gosh Lawrence, do tell, which category do YOU fall into? I suppose a mix-up between a cowbody (or Fonzie) coder and a troll. His programs have an inner poetry that we're obviously too stupid to understand. From jstroud at mbi.ucla.edu Mon Dec 15 01:33:11 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 14 Dec 2008 22:33:11 -0800 Subject: Looking for the best way to translate an idiom In-Reply-To: References: Message-ID: I V wrote: > On Sun, 14 Dec 2008 21:08:33 -0800, James Stroud wrote: >> Yes. I think it was the British who decided that the apostrophe rule for >> "it" would be reversed from normal usage relative to just about every >> other noun. I'm not sure the purpose--maybe it was to give compulsive >> proofreaders a raison d'etre. > > It's because "it" is a pronoun; you don't put an apostrophe in "his," > either. Its called humor. From geekmail at usenot.de Sun Dec 7 14:41:26 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sun, 7 Dec 2008 20:41:26 +0100 Subject: Is 3.0 worth breaking backward compatibility? References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> <20081207203553.7d62434a@usenot.de> Message-ID: <20081207204126.344bb814@usenot.de> On Sun, 7 Dec 2008 20:35:53 +0100 Andreas Waldenburger wrote: > On Sun, 7 Dec 2008 11:22:23 -0800 (PST) walterbyrd > wrote: > > > At best, I am a casual python user, so it's likely that I am missing > > something. > Yes, the big picture. > OK, that was a bit harsh. I apologize. But my point remains. To reiterate: * It's not like they rewrote Pascal and called it Python 3. * There is a script that helps you porting. Jeez. * Also: Spilt milk. Sorry, I do get agitated over things like this. /W -- My real email address is constructed by swapping the domain with the recipient (local part). From castironpi at gmail.com Thu Dec 4 05:38:36 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 4 Dec 2008 02:38:36 -0800 (PST) Subject: Overriding a method at the instance level on a subclass of a builtin type References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> Message-ID: <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> On Dec 3, 1:25?pm, Jason Scheirer wrote: > On Dec 2, 6:13?pm, Aaron Brady wrote: > > >>> class A: > > > ... ? ? def methA( self ): > > ... ? ? ? ? ? ? print 'methA' > > ... ? ? ? ? ? ? self.meth= self.methB > > ... ? ? meth= methA > > ... ? ? def methB( self ): > > ... ? ? ? ? ? ? print 'methB' > > ...>>> a= A() > > >>> a.meth() > > methA > > >>> a.meth() > > > methB > > The problem with using this this pattern in the way that you've > specified is that you have a potential memory leak/object lifetime > issue. Assigning a bound method of an instance (which itself holds a > reference to self) to another attribute in that same instance creates > a kind of circular dependency that I have discovered can trip up the > GC more often than not. > > You can subclass it as easily: > > class dictsubclass(dict): > ? ? def __getitem__(self, keyname): > ? ? ? ? if not hasattr(self, '_run_once'): > ? ? ? ? ? ? self.special_code_to_run_once() > ? ? ? ? ? ? self._run_once = True > ? ? ? ? return super(self, dict).__getitem__(keyname) > > If that extra ~16 bytes associated with the subclass is really a > problem: > > class dictsubclass(dict): > ? ? def __getitem__(self, keyname): > ? ? ? ? self.special_code_to_run_once() > ? ? ? ? self.__class__ = dict > ? ? ? ? return super(self, dict).__getitem__(keyname) > > But I don't think that's a good idea at all. Interesting. The following code ran, and process memory usage rose to 150MB. It failed to return to normal afterward. >>> for x in range( 10000000 ): ... a= [] ... a.append(a) ... However, the following code succeeded in returning usage to normal. >>> import gc >>> gc.collect() It was in version 2.6. So, the GC succeeded in collecting circularly linked garbage when invoked manually. That might have implications in the OP's use case. In another language, it would work differently, if it lacked unbound method descriptors. C++ for example, untested: class C { public: func_t meth; C( ) { meth= methA; } void methA( ) { meth= methB; } void methB( ) { } }; It has no problems with memory consumption (an extra pointer per object), or circular references; functions are not first-class objects. However they are in Python, which creates an entire bound method object per instance. The OP stated: > run some code and then patch in the original dict > method for the instance to avoid even the check to see if the init > code has been run. So your, Arnaud's, and Bryan's '.__class__' solution is probably best, and possibly even truer to the intent of the State Pattern. It is too bad that you can't assign an unbound method to the member, and derive the bound method on the fly. That might provide a middle- ground solution. From collin.day.0 at gmail.com Thu Dec 18 17:31:45 2008 From: collin.day.0 at gmail.com (Collin D) Date: Thu, 18 Dec 2008 14:31:45 -0800 (PST) Subject: Factoring Polynomials References: <5dfe1cf3-530d-4e31-833e-e26db85611be@d36g2000prf.googlegroups.com> Message-ID: On Dec 18, 1:09?pm, Mark Dickinson wrote: > On Dec 18, 8:47?pm, Scott David Daniels wrote: > > > ? ? ?else: # a single result (discriminant is zero) > > ? ? ? ? ?return (-b / (2 * a),) > > Maybe make that (-b / (2. * a)) to avoid getting funny results > when a and b are integers. ?(Or do a from __future__ import > division, or use Python 3.0, or ....) > > And to make the function more bullet-proof, you might want to > do something like (untested): > > ? ? from math import copysign > > ? ? [rest of example as in Scott's post] > > ? ? if discriminant: # two results > ? ? ? ? root1 = (-b - copysign(discriminant, b))/(2*a) > ? ? ? ? root2 = c/(a*root1) > ? ? ? ? return (root1, root2) > > to avoid numerical problems when b*b is much larger > than abs(a*c). Compare with the results of the usual > formula when a = c = 1, b = 10**9, for example. ?But > that still doesn't help you when the computation > of the discriminant underflows or overflows... > > Isn't floating-point a wonderful thing! ?:) > > Mark Thanks for all your help! Its good to know how to do it w/ without numpy. And yes, floating point is the best thing since sliced bread. ^^ -CD From bj_666 at gmx.net Fri Dec 12 11:21:29 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 12 Dec 2008 16:21:29 GMT Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> <31443882-cb41-420b-8269-b1590581783d@c36g2000prc.googlegroups.com> Message-ID: <6qfhc9Fc3a5jU5@mid.uni-berlin.de> On Fri, 12 Dec 2008 07:56:58 -0800, sturlamolden wrote: > On Dec 12, 4:55 pm, sturlamolden wrote: > >> def __setitem__(self, index, value): >> if _buf[index] is not value: # given that _buf is the tuple's >> internal buffer >> raise TypeError, 'tuple' object does not support item >> assignment > > bl?h, that should be self._buf[index] But then the error message is not true anymore because tuples *would* support item assignment when the old and new value are the same. Which leads to strange things like code that may or may not raise that exception, depending on implementation details: t = (1, 2) t[0] = 1 # Maybe okay -- maybe not. t[1] += 0 # Same here. I'd find that quite odd. Ciao, Marc 'BlackJack' Rintsch From list at qtrac.plus.com Sat Dec 20 05:37:46 2008 From: list at qtrac.plus.com (Mark Summerfield) Date: Sat, 20 Dec 2008 02:37:46 -0800 (PST) Subject: ANN: New Book: Programming in Python 3 References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> Message-ID: <06daa32b-aff7-4104-99bb-3cd1365be600@w1g2000prm.googlegroups.com> On 20 Dec, 00:32, "Colin J. Williams" wrote: > Thomas Heller wrote: > > Mark Summerfield schrieb: > >> Just a follow-up to say that the book has now been published in the > >> U.S. > >> It is now in stock at InformIT, and should reach other stores, e.g., > >> Amazon, in a week or so. > > >> Also, the introduction, the first few pages of the first chapter, the > >> whole of chapter 12 (regular expressions), and the index are now > >> available for free download in a PDF from here: > >>http://www.informit.com/store/product.aspx?isbn=0137129297 > > > Question from a non-native english speaker: is this now valid english? > > > ? "One of Python's great strengths" > > ? ? ? ? ? ? ? ? ^ > > ? "and also teaches Python's functional programming features" > > ? ? ? ? ? ? ? ? ? ? ? ? ? ^ > > ? "The book's approach is wholly practical" > > ? ? ? ? ? ?^ > > > Curious, > > Thomas > > No. ?Is this a quote from some > advertising stuff or was it written by > the author? > > Colin W. All three fragments are taken from the book's Introduction, and all are correct English---both U.S. and British as it happens. (You can read them in context by downloading the sample pages PDF.) See: http://en.wikipedia.org/wiki/Apostrophe You'll also find a few instances of possessive plurals (s') in later chapters:-) The whole book was proof read by a professional (American) proof reader---in addition to the several technical reviewers who read it. There is one point of (minor) controversy in my English usage---I make my writing gender-neutral by using singular they. This is valid in both U.S. and British English but doesn't seem to be very common, but I much prefer it to all the alternatives I've seen. http://en.wikipedia.org/wiki/Singular_they With two dozen postings on my use of English I'm now rather nervous about the feeback I'll get on my Python 3! PS Although Amazon.com still says the publication date is the 27th, they now expect to have it in stock on Monday (the 22nd). From arkanes at gmail.com Tue Dec 9 13:23:24 2008 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 9 Dec 2008 12:23:24 -0600 Subject: "as" keyword woes In-Reply-To: References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> Message-ID: <4866bea60812091023p6b85b328q9c5510a7d3ef8b83@mail.gmail.com> On Tue, Dec 9, 2008 at 6:39 AM, Paul Boddie wrote: > On 9 Des, 05:52, alex23 wrote: >> >> From my perspective, it was less the original complaint and more the >> sudden jump to "CPython is dead! The GIL sucks! Academic eggheads!" >> that prompted the comparisons to trolling. > > To be fair to the complainant, before mentioning the GIL, he did > initially get the usual trite fragments of the Zen of Python right > back at him ("simple is better than complex", "special cases aren't > special enough to break the rules"), albeit not the whole thing in its > overused, unabridged form. I think I'd go on a rant if presented with > that rather than the accepted reason for the noted shortcomings of the > language: CPython's parsing technology isn't "sufficiently powerful > parser technology" as GvR himself says [1]. > > Paul > So hold up a second. I'm out of line for calling someone on making a trollish post that's not relevant to the topic, and for being pretty late to the party even with the part that *was* on topic, and for (even in the original post) going the ad-hominem route by not so subtly implying that Python is an ivory tower language that's not good enough for people with real problems - a clearly false statement by any standards, and doubly offensive from someone who *is* using it for real problems and who himself is a less than shining example of responsible software management, but the OPs lapse into ranting in response to trite but accurate answers to a question he could have answered for himself, in detail, had he bothered to read the threads from the time when the issue actually matter is a reasonable response that we should support and validate? Sometimes you're not a crusader for thinking differently and change by confrontation and speaking truth to power. Sometimes you're just an asshole. For clarification: The OPs original complaint is legitimate, if dated and partially his own fault. His phrasing of the problem, the tone and content of his email, and his lapse into flaming when he wasn't immediately hailed as a herald of sanity is not legitimate. From sturlamolden at yahoo.no Fri Dec 12 08:39:35 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 05:39:35 -0800 (PST) Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> Message-ID: <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> On Dec 12, 2:34 pm, Hrvoje Niksic wrote: > >>> import numpy > >>> t = (numpy.zeros(10),) > >>> t > > (array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]),)>>> t[0] += 1 > > Traceback (most recent call last): > File "", line 1, in > TypeError: 'tuple' object does not support item assignment > > Of course, the side effect occurs before the exception, so: > > >>> t[0] > array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) Actually I would consider this to be a bug. The tuple is immutable, but no mutation of the tuple is ever attempted. Sturla Molden From tjreedy at udel.edu Mon Dec 15 13:10:19 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 15 Dec 2008 13:10:19 -0500 Subject: Structure using whitespace vs logical whitespace In-Reply-To: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> References: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> Message-ID: cmdrrickhunter at yaho.com wrote: > I've been trying to search through the years of Python talk to find an > answer to this, but my Googlefu is weak. > > In most languages, I'll do something like this > > xmlWriter.BeginElement("parent"); > ----xmlWriter.BeginElement("child"); > ----------xml.Writer.Characters("subtext"); > ----xmlWriter.EndElement(); > xmlWriter.EndElement(); > > Where the dashes are indentation (since some newsgroup handlers don't > do tabs well). XML writing is just an example. > > In general, I'm using indentation to show logical flow through code. That, of course, is what Python does. > Python's choice to give semantic meaning to whitespace prevents me > from doing such things. You, of course, also want to giving semantic meaning to whitespace, but one that happens to be different from Python's. 'Logical control flow' versus 'output text structure'. > What was once reserved for logical use is now used syntactically. False opposition. > In 90% of cases, its not needed, and whitespace > significance seems to be pretty effective. In that last 10%, however, > I've been frustrated many times. > > I've been using python for a few years, and gotten around this in one > way or another, but now I want to get other who work with me to pick > up Python. All newbies to Python have trouble with the idea of > whitespace sensitivity, Absolutely not true. Python's indentation is +/- the same as what people routinely (but usually optionally) do when writing other algorithmic languages, including most pseudocode. It also mimics standard outline mode and other structured text (as you with to do). I choose Python in part *because* it has a standard mandated indentation scheme versus the multiple optional schemes of C programmers. Enough of the endless C whitespace wars. I strongly suggest that you not project *your* troubles onto others. Let them come upon it by themselves -- or not. > but how can I convince them that "it just works better" The tradeoff is between personal flexibility (a loss to you) and uniformity across programs (you can read *any* Python program and understand the meaning of the indentation). Someone who does not see the latter as a gain perhaps should not use Python. > when I have this construct which I want to use but can't. Yet > Has anybody found a way to emulate this behavior? New question: this answer has perhaps been posted before. For your example, write a context manager 'Element' (possible in 2.5+, but I use 3.0). class Element(): def __init__(self, item): self.item = item def __enter__(self): print('' % self.item) def __exit__(self, t,v,tb): print('') # Then with Element('parent'): with Element('child'): print("subtext") # prints subtext Of course, the element class(es) could be in a module with global indent and delta, methods that add and subtract the delta as appropriate, and a print function that prepends the current indent to get something like subtext To me, this Python-style construct is better. You get the Element closure written 'for free'. Less need to match indent levels, no possibility of forgetting closures. If there are multiple container elements with different closures, you get the right one automatically and cannot mismatch. > I've often done it > by opening an expression for the whole thing, but there's a lot of > tasks where a single expression just isn't sufficient (such as things > with assignment). I do not understand this without a concrete example. > PS. In my opinion the solution would be to have the option of entering > a "whitespace insensitive" mode which uses C style {} and ;. I think the above is much better ;-). And yes, such ideas have been discussed and rejected. Terry Jan Reedy From alitosis at gmail.com Thu Dec 18 20:53:46 2008 From: alitosis at gmail.com (alito) Date: Thu, 18 Dec 2008 17:53:46 -0800 (PST) Subject: psycopg2 and large queries References: Message-ID: <1de36399-f94f-42b3-87ea-3812fed4bd86@r36g2000prf.googlegroups.com> On Dec 19, 2:34?am, Laszlo Nagy wrote: > > I was looking for psycopg2 documentation, but I found nothing. However, > I found some posts telling that named cursors do support fetching a > single row at a time. Here is how to create a named cursor: > > cur = conn.cursor('mycursor') > > This is very strange, because DB API 2.0 does not have this feature. Why > this feature was created, and how to use it? Not documented. > The feature was created to use server-side cursors. The DB API doesn't specify how to create them. I've got no idea why it isn't documented. > However, this is also not usable, because named cursors do not have a > ".description" property! You can try this: > > cur = conn.cursor('mycursor') > cur.execute('select name from product limit 1000000') > print repr(cur.description) ?# -> None > They do have a description attribute, but it is only populated after you fetch a row. eg try cur = conn.cursor(name='mycursor') cur.execute('select name from blah') cur.fetchone() print cur.description > This is unacceptable! Really? I accepted it just fine. > > p.s.: I tried to subscribe to the psycopg mailing list, but the > confirmation email did not arrive in 6 hours... psycopg website and development in general seems to be comatose. Emails to the list are being silently dropped. Also, don't believe the front page, development stopped happening on that svn branch a while ago and moved to a bzr branch, which has failed to respond for the last few weeks. Maybe the relevant people are on holidays. If this persists for a while someone will fork it, since quite a few people are interested in its continued development. From castironpi at gmail.com Fri Dec 19 19:59:53 2008 From: castironpi at gmail.com (Aaron Brady) Date: Fri, 19 Dec 2008 16:59:53 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <063b192e-fbde-4614-b90f-2d88f4dc51b5@z6g2000pre.googlegroups.com> On Dec 19, 1:43?pm, excord80 wrote: snip cons of Python > But, Python is Python. It's always surprising to me to hear this, but especially so in writing. It speech, it has connotations. A millionaire can say (dismissively), "Two bucks is two bucks." A poor person can say (wondrously), "Two bucks is two bucks." Without knowing the expository (the facts about the speakers), you could glean some of the context from the tone and pitch. You could say, 'The speaker sounds wondrous', or 'The speaker sounds dismissive.' I take the repetition to mean, roughly, 'But these is the speaker's overall evaluation of the subject.' The stereotypical case is a girl or boy in a tough social situation; and I don't know what countries they do this in, or even how widespread it is in mine. A friend says, "What s/he is doing is no good." You say, "But it's [person's name]." Literally, that doesn't add any information to the debate, which is stereotypically over a decision or resolution. It does facilitate expression (free expression is good), but I think it would have been more productive, informative, fruitful, etc., to leave the last word with the opposition; that is, when the friend says, "What s/he is doing is no good." Period. The facts merit it, and it's merely escapist to withdraw back to the big picture, since it is the small details in the situation that need the concentration and attention. Without context, in writing, 'Two bucks is two bucks' is exactly the same as 'Two bucks is two bucks'. Readers can't hear pitch, and do not have context about fiscal status. Excord, was your tone dismissive, or wondrous? Or a little whiny? Or authoritative? The statement carried no more information than "A square is a square" or "A bachelor is unmarried", and to readers, even lacked the expressive value too. (No .WAV file attached!) From castironpi at gmail.com Sun Dec 21 10:40:25 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 21 Dec 2008 07:40:25 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <015da0a4$0$20656$c3e8da3@news.astraweb.com> <6r6uvbFfb643U5@mid.uni-berlin.de> Message-ID: <9a6cd17c-667e-4ad0-90d9-c09f34dba606@w39g2000prb.googlegroups.com> On Dec 21, 7:34?am, Marc 'BlackJack' Rintsch wrote: > On Sun, 21 Dec 2008 12:45:32 +0000, Duncan Booth wrote: > > You seem to have made an unwarranted assumption, namely that a binary > > operator has to compile to a function with two operands. There is no > > particular reason why this has to always be the case: for example, I > > believe that C# when given several strings to add together optimises > > this into a single call to a concatenation method. > > > Python *could* do something similar if the appropriate opcodes/methods > > supported more than two arguments: > > > a+b+c+d might execute a.__add__(b,c,d) allowing more efficient string > > concatenations or matrix operations, and a%b%c%d might execute as > > a.__mod__(b,c,d). > > But that needs special casing strings and ``%`` in the comiler, because > it might not be always safe to do this on arbitrary objects. ?Only in > cases where the type of `a` is known at compile time and ``a % b`` > returns an object of ``type(a)``. 'x+y' makes no guarantees whatsoever. It could return an object of type(x), type(y), or neither. 'a%b' in the case of strings is just, str.__mod__, returning string. In a+b+c, 'a' gets dibs over what the rest see, so there's no more danger in the multi-ary case, than in binary; and that hasn't stopped us before. You might be confusing the cases of arbitrary operators vs. uniform operators. 'a' does not get dibs in 'a+b*c'; 'b*c' are allowed to carry out their affairs. But in 'a+b+c', 'a*b*c', 'a%b%c', and so on, 'a' has final say on b's and c's behaviors via its return value, so loses nothing by combining such a call. In short, you can force it anyway, so it's syntactic sugar after that. From wuwei23 at gmail.com Mon Dec 1 20:01:35 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 1 Dec 2008 17:01:35 -0800 (PST) Subject: Checking a string against multiple matches References: <99a3a677-a38d-40f5-9a94-a98865150b69@k19g2000yqg.googlegroups.com> Message-ID: <200af09b-adba-4d8f-9ed9-2343030f9718@i24g2000prf.googlegroups.com> On Dec 2, 5:31?am, Aaron Scott wrote: > I was using .index on the > list, but it would return True for strings that contained the search > string rather than match it exactly, leading to false positives in my > code. Are you sure? That doesn't seem like standard behaviour. >>> l = ["one", "two", "three", "four"] >>> l.index('on') Traceback (most recent call last): File "", line 1, in ValueError: list.index(x): x not in list >>> l.index('thre') Traceback (most recent call last): File "", line 1, in ValueError: list.index(x): x not in list The only time I'd expect it to do partial matches is if you were doing string.index(string), rather than list.index(string): >>> "four".index('our') 1 From martin at marcher.name Sat Dec 27 15:55:33 2008 From: martin at marcher.name (Martin) Date: Sat, 27 Dec 2008 21:55:33 +0100 Subject: [2.4.4] creating a datetime.datetime from an XML xs:dateTime In-Reply-To: <18774.36465.346262.883182@montanaro-dyndns-org.local> References: <5fa6c12e0812271208x4baccaedk262e51becb6e2076@mail.gmail.com> <18774.36465.346262.883182@montanaro-dyndns-org.local> Message-ID: <5fa6c12e0812271255l4f4893e8w9f96e9ace73ea50c@mail.gmail.com> Hi, 2008/12/27 : > Not in the standard lib, but you might want to check out the dateutil > package. Its dateutil.parser module does an excellent job parsing a wide > range of time formats. It's a bit weak in the timezone area though. is that http://labix.org/python-dateutil, I'll have a look at it. -- http://soup.alt.delete.co.at http://www.xing.com/profile/Martin_Marcher http://www.linkedin.com/in/martinmarcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From svalbardcolaco at gmail.com Fri Dec 5 03:44:47 2008 From: svalbardcolaco at gmail.com (svalbard colaco) Date: Fri, 5 Dec 2008 14:14:47 +0530 Subject: CONNECTION TIMED OUT ERROR using urllib2 In-Reply-To: <180b672e0812042317v55308ff1x42959d08dfe63bb5@mail.gmail.com> References: <726d283d0812042217w41a0288eg3ee79d4ffdb5ff4b@mail.gmail.com> <180b672e0812042227j12a4d647k84e507dfae77d665@mail.gmail.com> <726d283d0812042236j792f4706v373ca6449861e3e2@mail.gmail.com> <180b672e0812042317v55308ff1x42959d08dfe63bb5@mail.gmail.com> Message-ID: <726d283d0812050044y22eecd02xf541c469c8440f2@mail.gmail.com> Hi I set my http_proxy and now i get the following error *urllib2.HTTPError: HTTP Error 403: Forbidden ( The ISA Server denied the specified Uniform Resource Locator (URL). * what other variables have to be set ? Regards, sv On Fri, Dec 5, 2008 at 12:47 PM, rishi pathak wrote: > Before executing script do > export http_proxy=http://:/ > > > > On Fri, Dec 5, 2008 at 12:06 PM, svalbard colaco > wrote: > >> Hi rishi, >> >> Thanks for ur reply, >> yes i set the following enviroment variables (FC6 platform) >> http_proxy,http_user,http_password >> >> But i get the same error; Can u tell me which other variables i need to >> set or am i going wrong in the syntax of these >> variables? >> >> Regards >> sv >> >> >> On Fri, Dec 5, 2008 at 11:57 AM, rishi pathak wrote: >> >>> Are you sitting behind a proxy. If so then you have to set proxy for http >>> >>> On Fri, Dec 5, 2008 at 11:47 AM, svalbard colaco < >>> svalbardcolaco at gmail.com> wrote: >>> >>>> Hi all >>>> >>>> I have written a small code snippet to open a URL using urllib2 to open >>>> a web page , my python version is 2.4 but i get an urlopen error called >>>> connection timed out >>>> >>>> The following is the code snippet >>>> >>>> *import urllib2 >>>> >>>> f = urllib2.urlopen('http://www.google.com/') >>>> print f.read(100)* >>>> >>>> >>>> where as the same url http://www.google.com/ works through my browser. >>>> >>>> The following is the back trace : >>>> >>>> File "test_url.py", line 3, in ? >>>> f = urllib2.urlopen('http://www.google.com/') >>>> File "/usr/lib/python2.4/urllib2.py", line 130, in urlopen >>>> return _opener.open(url, data) >>>> File "/usr/lib/python2.4/urllib2.py", line 358, in open >>>> response = self._open(req, data) >>>> File "/usr/lib/python2.4/urllib2.py", line 376, in _open >>>> '_open', req) >>>> File "/usr/lib/python2.4/urllib2.py", line 337, in _call_chain >>>> result = func(*args) >>>> File "/usr/lib/python2.4/urllib2.py", line 1021, in http_open >>>> return self.do_open(httplib.HTTPConnection, req) >>>> File "/usr/lib/python2.4/urllib2.py", line 996, in do_open >>>> raise URLError(err) >>>> *urllib2.URLError: >>>> >>>> >>>> Any pointers in this regard will be of great help. >>>> >>>> Thanking you'll in advance. >>>> >>>> Regards, >>>> sv >>>> >>>> >>>> >>>> -- >>>> http://mail.python.org/mailman/listinfo/python-list >>>> >>>> >>> >>> >>> -- >>> Regards-- >>> Rishi Pathak >>> Pune-Maharastra >>> >> >> > > > -- > Regards-- > Rishi Pathak > Pune-Maharastra > -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Sun Dec 21 07:45:32 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Dec 2008 12:45:32 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <015da0a4$0$20656$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Errors should never pass silently, unless explicitly silenced. You > have implicitly silenced the TypeError you get from not having enough > arguments for the first format operation. That means that you will > introduce ambiguity and bugs. > > "%i %i %i %i" % 5 % 3 %7 > > Here I have four slots and only three numbers. Which output did I > expect? > > '%i 5 3 7' > '5 %i 3 7' > '5 3 %i 7' > '5 3 7 %i' > > Or more likely, the three numbers is a mistake, there is supposed to > be a fourth number there somewhere, only now instead of the error > being caught immediately, it won't be discovered until much later. > You seem to have made an unwarranted assumption, namely that a binary operator has to compile to a function with two operands. There is no particular reason why this has to always be the case: for example, I believe that C# when given several strings to add together optimises this into a single call to a concatenation method. Python *could* do something similar if the appropriate opcodes/methods supported more than two arguments: a+b+c+d might execute a.__add__(b,c,d) allowing more efficient string concatenations or matrix operations, and a%b%c%d might execute as a.__mod__(b,c,d). In that alternate universe your example: "%i %i %i %i" % 5 % 3 %7 simply throws "TypeError: not enough arguments for format string", and "%s" % (1,2,3) just converts the tuple as a single argument. It also provides the answer to how you put a percent in the format string (double it) and what happens if a substitution inserts a percent (it doesn't interact with the formatting operators). From skip at pobox.com Mon Dec 29 10:19:58 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 29 Dec 2008 09:19:58 -0600 Subject: multiply each element of a list by a number In-Reply-To: <4958E794.1070704@ncf.ca> References: <4955e7be$0$4066$ba4acef3@news.orange.fr> <49580B2E.8050009@ncf.ca> <4958E794.1070704@ncf.ca> Message-ID: <18776.60062.360057.614861@montanaro-dyndns-org.local> Colin> That's interesting but that's not the Colin> way timeit is documented for Python 2.5: Colin> timeit( [number=1000000]) That's how it works when invoked as a main program using -m. Colin> In spite of the fact that your own data doesn't support the Colin> assertion? Colin> I would have expected numpy to be the clear winner for len > Colin> 1,500. It is. In fact, it's the clear winner well below that. Below I have reorganized the timeit output so the units are the same for all runs (*microseconds* per loop): length numpy pure python 1 11.7 0.698 10 11.7 2.94 100 12.1 24.4 1000 15 224 10000 41 2170 100000 301 22200 -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From Scott.Daniels at Acm.Org Wed Dec 31 14:12:40 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 31 Dec 2008 11:12:40 -0800 Subject: select.select and socket.setblocking In-Reply-To: References: Message-ID: Jean-Paul Calderone wrote: > ... > On a LAN, it's likely that you'll generally get the exact number of bytes > which the sender passed to one call of send (until the sender starts to > pass really huge strings to send, then it'll get split up) just because > the network has lots of capacity compared to the traffic you're putting > on it. However, even on a LAN it's not guaranteed, and on the internet, > it's extremely likely that this won't happen most of the time. I don't mean to rebut your point here,rather to "pile on" with a bit more information. One point I haven't seen mentioned in this discussion is that nodes in the internet that carry the TCP/IP traffic are allowed to, for their own purposes, break large packets up into several smaller packets, and combine several smaller packets into a single larger packet. So, no matter how your TCP/IP packets leave your machine, there is no guarantee they will reach the destination in the same clumps. It is the stream, and not the packets, that is provided by TCP/IP. --Scott David Daniels Scott.Daniels at Acm.Org From Slaunger at gmail.com Tue Dec 9 11:40:53 2008 From: Slaunger at gmail.com (Slaunger) Date: Tue, 9 Dec 2008 08:40:53 -0800 (PST) Subject: Best way to report progress at fixed intervals Message-ID: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> Hi comp.lang.python I am a novice Python 2.5 programmer, who write some cmd line scripts for processing large amounts of data. I would like to have possibility to regularly print out the progress made during the processing, say every 1 seconds, and i am wondering what a proper generic way to do this is. I have created this test example to show the general problem. Running the script gives me the output: Work through all 20 steps reporting progress every 1.0 secs... Work step 0 Work step 1 Work step 2 Work step 3 Work step 4 Processed 4 of 20 Work step 5 Work step 6 Work step 7 Work step 8 Processed 8 of 20 Work step 9 Work step 10 Work step 11 Work step 12 Work step 13 Processed 13 of 20 Work step 14 Work step 15 Work step 16 Work step 17 Processed 17 of 20 Work step 18 Work step 19 Finished working through 20 steps The script that does this is as follows: testregularprogress.py: """ Test module for testing generic ways of displaying progress information at regular intervals. """ import random import threading import time def work(i): """ Dummy process function, which takes a random time in the interval 0.0-0.5 secs to execute """ print "Work step %d" % i time.sleep(0.5 * random.random()) def workAll(verbose=True, max_iter=20, progress_interval=1.0): class _Progress(object): def __init__(self): self.no = 0 self.max = max_iter self.start_timer = verbose def __str__(self): self.start_timer = True # I do not like this appraoch return "Processed %d of %d" % (self.no, self.max) p = _Progress() def report_progress(): print p if verbose: print "Work through all %d steps reporting progress every %3.1f secs..." % \ (max_iter, progress_interval) for i in xrange(max_iter): if p.start_timer : p.start_timer = False # Let the progress instance set the flag timer = threading.Timer(progress_interval, report_progress) timer.start() work(i) p.no = i + 1 # Kill the last timer, which is still active at this time timer.cancel() if verbose: print "Finished working through %d steps" % max_iter if __name__ == "__main__": workAll() Quite frankly, I do not like what I have made! It is a mess, responsibilities are mixed, and it seems overly complicated. But I can't figure out how to do this right. I would therefore like some feedback on this proposed generic "report progress at regular intervals" approach presented here. What could I do better? -- Slaunger From rdcollum at gmail.com Thu Dec 18 14:19:40 2008 From: rdcollum at gmail.com (Roger) Date: Thu, 18 Dec 2008 11:19:40 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <71ede5f0-fd88-4155-9f0d-42d0ad5f57dc@v42g2000yqj.googlegroups.com> <61f45e65-2404-4cc0-9d81-f848c1ba566f@i18g2000prf.googlegroups.com> Message-ID: On Dec 18, 12:49?pm, r wrote: > Maybe someone will chime in with an answer, sorry i could not help. > ponder this, i must... Regardless, thanks for your help! I truly appreciate it. Roger. From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 29 07:23:08 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 29 Dec 2008 13:23:08 +0100 Subject: "return" in def In-Reply-To: <7f340e90-c288-4592-8a4c-b008c24cf62a@q26g2000prq.googlegroups.com> References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <0167cbf7$0$6988$c3e8da3@news.astraweb.com> <676bffeb-4b07-4226-8c14-7da57d94351b@f13g2000yqj.googlegroups.com> <3afba310-dcde-4dc1-825a-7c63b97e2a40@w1g2000prk.googlegroups.com> <495897c4$0$8481$426a74cc@news.free.fr> <7f340e90-c288-4592-8a4c-b008c24cf62a@q26g2000prq.googlegroups.com> Message-ID: <4958c12b$0$16065$426a34cc@news.free.fr> John Machin a ?crit : > On Dec 29, 8:26 pm, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: >> John Machin a ?crit : (snip) >>> Please don't. Follow MRAB's advice, with the corollary that a >>> generator is forced by the compiler to be a "procedure" in MRAB's >>> terminology. >> I fail to see any *practical* difference between MRAB's and Steven's >> POVs. In both cases, it boils down to >> - don't use a bare return at the end of a def statement's body, >> - either use only bare returns ('procedure') or explicitely return None >> ('function') > > Steven's treatment was somewhat discursive, and didn't explicitly > mention the 'procedure' possibility. In fact, this sentence "if you > have a function with early exits, and you need to make the intent of > the function clear, explicitly return None." would if applied to a > 'procedure' cause a stylistic horror as bad as a bare return at the > end of the def. Ok. You're right. From yinon.me at gmail.com Tue Dec 16 09:32:20 2008 From: yinon.me at gmail.com (Yinon Ehrlich) Date: Tue, 16 Dec 2008 06:32:20 -0800 (PST) Subject: os.environ.get('SSH_ORIGINAL_COMMAND') returns None References: Message-ID: On Dec 15, 8:51?pm, Tzury Bar Yochay wrote: > Trying to follow a technique found at bzr I did the following > > added to ~/.ssh/authorized_keys the command="my_parder" parameter > which point to a python script file named 'my_parser' and located in / > usr/local/bin ?(file was chmoded as 777) > > in that script file '/usr/local/bin/my_parser' I got the following > lines: > > #!/usr/bin/env python > import os > print os.environ.get('SSH_ORIGINAL_COMMAND', None) > > When trying to ssh e.g. 'ssh localhost' > I get None on the terminal and then the connection is closed. > You should define SSH_ORIGINAL_COMMAND in environment of the calling shell/application. From andreas at kostyrka.org Fri Dec 12 12:18:33 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 12 Dec 2008 18:18:33 +0100 Subject: Python is slow In-Reply-To: <8156b37b-d1f6-4142-ad6e-8488c95b6592@z28g2000prd.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> <8156b37b-d1f6-4142-ad6e-8488c95b6592@z28g2000prd.googlegroups.com> Message-ID: <20081212171833.GC25004@hell.kostyrka.org> On Fri, Dec 12, 2008 at 06:17:43AM -0800, sturlamolden wrote: > None of those projects addresses inefficacies in the CPython > interpreter, except for psyco - which died of an overdose PyPy. Bullshit. All that discussion about performance forgets that performance is a function of the whole system, not the language. Worse you can measure it really badly. E.g. it's relative simple to compare CPython versus IronPython versus Jython. For a given benchmark program. As programs do not trivially translate from language A to language B, nor does fluency in language A make you automatically fluent in language B after learning the syntax. > > PyPy is interesting if they ever will be able to produce something > useful. They have yet to prove that. Even if PyPy can come up with a > Python JIT, they will still be decades behind the technologies of > Strongtalk and Java. That is the problem with reinventing the wheel > all over again. Well, it's reinventing the wheel. The problem that Java is a different kind of wheel (boxed vs. unboxed objects, plus more static compile time bindings), Smalltalk is also different (e.g. multiple inheritence), so you need to have a specific toolbox for the wheel, sorry. Keeping and enhancing the tribal wisdom about toolbox design is what a subtribe of the Computer Scientists do. Btw, Psyco is not a JIT like most JVMs had them, it's a specializing compiler. JVM JITs traditionally speeded up the unboxed data type operations. Psyco does something comparable, but it has to specialize first on data types. The end effect is similiar, but the background of what happens is quite different. > > Not to forget LLVM and Parrot which also will support Python > frontends. When they do, they'll do. There have flown quite a bit of Python version since the time that it was announced that Parrot will have a Python frontend. Andreas From jon at ffconsultancy.com Wed Dec 10 17:23:54 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Wed, 10 Dec 2008 22:23:54 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <40b4b23f-c1eb-4ac5-bb42-e0f6276e97bf@r37g2000prr.googlegroups.com> Message-ID: Xah Lee wrote: > On Dec 10, 12:37 pm, w_a_x_... at yahoo.com wrote: >> Ruby: >> >> def norm a >> s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) >> a.map{|x| x/s} >> end > > I don't know ruby, but i tried to run it and it does not work. > > #ruby > def norm a > s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) > a.map{|x| x/s} > end > > v = [3,4] > > p norm(v) # returns [0.6, 0.8] That is the correct answer. > The correct result for that input would be 5. No, you're confusing normalization with length. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From phd at phd.pp.ru Mon Dec 1 08:48:24 2008 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 1 Dec 2008 16:48:24 +0300 Subject: SQLObject 0.9.8 Message-ID: <20081201134824.GD19187@phd.pp.ru> Hello! I'm pleased to announce version 0.9.8, a minor bug fix release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.9.8 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.9.7 ---------------- * Changed interpretation of strings in the DB URI for boolean parameters: '0', 'no', 'off' and 'false' are now interpreted as False. * Fixed a bug with incorrect handling of calls like connectionForURI(dburi, cache=False) when dburi already contains some parameters in the URI. * Convert decimal.to_eng_string() to str to work around a bug in Python 2.5.2; see http://mail.python.org/pipermail/python-dev/2008-March/078189.html * Added test_default_style.py. * Fixed a minor bug in SQLiteConnection that fails to parse Enum columns. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From gagsl-py2 at yahoo.com.ar Sat Dec 27 21:39:54 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 28 Dec 2008 00:39:54 -0200 Subject: how to make a class to get all forms and input fields from webpage References: Message-ID: En Sat, 27 Dec 2008 21:54:02 -0200, alex goretoy escribi?: > How do I make a class for retrieving all forms and input fields on a web > page. Meaning, form name, form url,all input fields, > text,textarea,select,etc...I have something currently and it kinda I'd use BeautifulSoup: http://pypi.python.org/pypi/BeautifulSoup/ -- Gabriel Genellina From rdmurray at bitdance.com Wed Dec 17 10:51:53 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Wed, 17 Dec 2008 15:51:53 +0000 (UTC) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> <0d9ea7cc-b5fb-4edb-be32-490aae9e7204@b41g2000pra.googlegroups.com> <0de3a7bf-a4c4-4103-a4e0-44313405fa94@z28g2000prd.googlegroups.com> Message-ID: Quoth John Machin : > On Dec 18, 1:28 am, aka wrote: > > @expose(allow_json=True) > > Means what? Does what? > Does the problem still happen without that? Means what he's posting is not a standalone script :) He says it's part of his turbogears ap. @expose says that this method is callable by name from a URL, and allow_json means it can be called with a parameter requesting a json formatted response instead of html. > Funny, the indentation changed there --- for the very last time, is > that the actual code of a standalone script that reproduces the > problem? Alex, I would strongly suggest that you move your code out into a standalone script and debug it there (you'll get more help from this group if you do, for one thing!). After you get it working standalone you can incorporate it back into your Turbogears ap. --RDM From bdesth.quelquechose at free.quelquepart.fr Sun Dec 7 13:18:49 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 07 Dec 2008 19:18:49 +0100 Subject: Guido's new method definition idea In-Reply-To: <493bba28$0$8283$426a74cc@news.free.fr> References: <493abe2e$0$15998$426a34cc@news.free.fr> <62bcfe49-bee6-4348-8ec9-8ab85132c8ff@40g2000prx.googlegroups.com> <493bba28$0$8283$426a74cc@news.free.fr> Message-ID: <493c2141$0$4942$426a34cc@news.free.fr> News123 a ?crit : > Lie wrote: >> On Dec 7, 1:02 am, News123 wrote: >>> What would be interesting would be some syntactical sugar to get rid of >>> the 'self' (at least in the code body). This has been debated to hell and back. And it's *not* going to happen. >>> example: >>> class C: >>> class_elements a,b,c,d >>> >>> def method(self,arg): >>> global d >>> a,b,c = arg[0..3] >>> d = a + b >>> self.e = a + d >>> >> Nah, that would make it not explicit. Explicit here also means that to >> refer to self's a, we need to explicitly refer to self. > > Well being explicit when trying to suggest an implicit syntax (in order > to reduce typing) is a little difficult ;-) > > Though you're right my main goal is not being implicit but would be > reducing typing and have shorter source code lines. then use 's' instead of 'self'. > If 'global '' is accepted inside a def, then moving > 'class_elements ' inside the def could be acceptable as well self.x is an instance attribute, not a class attribute. Aslo, the def statement creates a function, not a method, so the notion of "class_element" or however you name it is totally irrelevant here. From jerry.carl.mi at gmail.com Sun Dec 28 13:16:29 2008 From: jerry.carl.mi at gmail.com (jerry.carl.mi at gmail.com) Date: Sun, 28 Dec 2008 10:16:29 -0800 (PST) Subject: math module for Decimals References: <41937dc9-4b67-43b5-9eab-6f8c851474cf@p2g2000prn.googlegroups.com> <0896c2d8-78ff-489e-801d-abef957601d0@s9g2000prg.googlegroups.com> <59c08a51-da39-467b-9576-fa0cc1db3207@i18g2000prf.googlegroups.com> Message-ID: <1fb93396-6a0c-435d-9115-859df2f32fbc@g3g2000pre.googlegroups.com> mpmath... wow... just did what i needed :-) Thanks, Mark! Hopefully i did not waste too much of your time... and perhaps this discussion will send other lost sheeps in the right direction. (Still, it would make sense to have the goniometric functions in decimal.) From eric at ericaro.net Fri Dec 5 05:56:48 2008 From: eric at ericaro.net (eric) Date: Fri, 5 Dec 2008 02:56:48 -0800 (PST) Subject: simplest way to strip a comment from the end of a line? References: <52e3f2a9-6fb1-42ef-9871-c904ede5520e@t3g2000yqa.googlegroups.com> <9cdc9039-6b7b-42fb-b261-4ad721ccd1d4@j39g2000yqn.googlegroups.com> Message-ID: <340697a3-3f17-477a-aea2-c85344da93d4@k41g2000yqn.googlegroups.com> On Dec 4, 11:35?pm, Paul McGuire wrote: > Yowza! ?My eyes glaze over when I see re's like "r'(?m)^(?P.*? > (".*?".*?)*)(?:#.*?)?$"! > yeah, I know ... :( ( I love complicated regexp ... it's like a puzzle game for me) > from pyparsing import quotedString, Suppress, restOfLine > > comment = Suppress('#' + restOfLine) > recognizer = quotedString | comment > > for t in tests: > ? ? print t > ? ? print recognizer.transformString(t) > ? ? print > > Prints: > > this is a test 1 > this is a test 1 > > this is a test 2 #with a comment > this is a test 2 > > this is a '#gnarlier' test #with a comment > this is a '#gnarlier' test > > this is a "#gnarlier" test #with a comment > this is a "#gnarlier" test > > For some added fun, add a parse action to quoted strings, to know when > we've really done something interesting: > > def detectGnarliness(tokens): > ? ? if '#' in tokens[0]: > ? ? ? ? print "Ooooh, how gnarly! ->", tokens[0] > quotedString.setParseAction(detectGnarliness) > > Now our output becomes: > > this is a test 1 > this is a test 1 > > this is a test 2 #with a comment > this is a test 2 > > this is a '#gnarlier' test #with a comment > Ooooh, how gnarly! -> '#gnarlier' > this is a '#gnarlier' test > > this is a "#gnarlier" test #with a comment > Ooooh, how gnarly! -> "#gnarlier" > this is a "#gnarlier" test > > -- Paul I didn't knew pyparsing. It's amazing ! thanks From iainking at gmail.com Thu Dec 4 07:31:31 2008 From: iainking at gmail.com (Iain King) Date: Thu, 4 Dec 2008 04:31:31 -0800 (PST) Subject: RELEASED Python 3.0 final References: Message-ID: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> On Dec 4, 1:51 am, Barry Warsaw wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > On behalf of the Python development team and the Python community, I > am happy to announce the release of Python 3.0 final. > > Python 3.0 (a.k.a. "Python 3000" or "Py3k") represents a major > milestone in Python's history, and was nearly three years in the > making. This is a new version of the language that is incompatible > with the 2.x line of releases, while remaining true to BDFL Guido van > Rossum's vision. Some things you will notice include: > > * Fixes to many old language warts > * Removal of long deprecated features and redundant syntax > * Improvements in, and a reorganization of, the standard library > * Changes to the details of how built-in objects like strings and > dicts work > * ...and many more new features > > While these changes were made without concern for backward > compatibility, Python 3.0 still remains very much "Pythonic". > > We are confident that Python 3.0 is of the same high quality as our > previous releases, such as the recently announced Python 2.6. We will > continue to support and develop both Python 3 and Python 2 for the > foreseeable future, and you can safely choose either version (or both) > to use in your projects. Which you choose depends on your own needs > and the availability of third-party packages that you depend on. Some > other things to consider: > > * Python 3 has a single Unicode string type; there are no more 8-bit > strings > * The C API has changed considerably in Python 3.0 and third-party > extension modules you rely on may not yet be ported > * Tools are available in both Python 2.6 and 3.0 to help you migrate > your code > * Python 2.6 is backward compatible with earlier Python 2.x releases > > We encourage you to participate in Python 3.0's development process by > joining its mailing list: > > http://mail.python.org/mailman/listinfo/python-3000 > > If you find things in Python 3.0 that are broken or incorrect, please > submit bug reports at: > > http://bugs.python.org/ > > For more information, links to documentation, and downloadable > distributions, see the Python 3.0 website: > > http://www.python.org/download/releases/3.0/ > > Enjoy, > - -Barry > > Barry Warsaw > ba... at python.org > Python 2.6/3.0 Release Manager > (on behalf of the entire python-dev team) > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.9 (Darwin) > > iQCVAwUBSTc3pXEjvBPtnXfVAQI69wP/dPHh8IL3GxziEV9QzlveKG+KyZb2X16x > fxJnTCiXAbiAhT5C+m43OEnbF1PJgMDKtcZ5b7aQb4TQ0mJxISTQh0RfLCpArmlo > tdTbzCLnh13KzB+3sUHCx+MeQNXERoWDV8hLz+4Ae71UsuUGynhtyP7ZJMJDue8j > so2gv3fOMSs= > =vkiy > -----END PGP SIGNATURE----- Props. I just looked through the What's New and the change log, but I couldn't find the answer to something: has any change been made to how tabs and spaces are used as indentation? Can they still be (inadvisably) mixed in one file? Or, more extremely, has one or the other been abolished? Iain From roy at panix.com Thu Dec 4 15:44:57 2008 From: roy at panix.com (Roy Smith) Date: Thu, 4 Dec 2008 12:44:57 -0800 (PST) Subject: Checking if an int fits in 32 bits? References: <6pqt56F9bvoiU1@mid.individual.net> Message-ID: On Dec 4, 3:33?pm, Thomas Heller wrote: > Roy Smith schrieb: > > > I'm working with marshaling data over a binary wire protocol. ?I'm > > using struct.pack() to handle the low-level encoding of ints. ?One of > > the things I need to do is make sure an int can be represented in 4 > > bytes. > You could try something like this: > > import ctypes > def int_fits_in_32bit(value): ? > ? return ctypes.c_int32(value) == value Good idea! It turns out you've got to do types.c_int32(value).value() == value, but that does indeed seem to do exactly what I want. Thanks. From steve at holdenweb.com Mon Dec 22 11:57:27 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 22 Dec 2008 11:57:27 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> Message-ID: walterbyrd wrote: > On Dec 21, 12:28 pm, Bruno Desthuilliers > wrote: >> Strange enough, >> no one seems to complain about PHP or Ruby's performances... > > A few years back, there was a certain amount of chest thumping, when > python/django easily beat ror in a benchmark test. Now that ruby is > faster, I guess speed is no big issue. > A fairly limited amount of chest-thumping, as I remember it. > By the same reasoning, python advocates used to sneer at php because > php constantly broke backward compatibility. Now that python does it, > breaking backward compatibility is no big deal. I guess unicode > support was not that important, until python caught up to perl. > Python advocates shouldn't sneer at other languages. There's no need. If you like Python, use it because of its merits, not because it's better than something else. Having said which, I must say that Python's "breaking backward incompatibility" is of a somewhat different nature than (say) Visual Basic's. It was known about for *several years* in advance, even before Guido went to work for Google and finally had time to get the work underway. Also it's defined to be a singular event, not a continuous set of creeping changes. Python 3's updated syntax now constrains the developers in the same way that Python 2's used to. I wouldn't say that could remotely be described as "constantly" breaking backward compatibility. > I guess, the way it works is: you first assume that python is > superior, then you figure out why. > That's the way some people operate, but by no means all. Is it the language or the people that are pissing you off. You sound a little discontented for a c.l.py reader. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 20:54:43 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2008 01:54:43 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> <88ff7c46-2b23-49e4-865e-781d23433799@l33g2000pri.googlegroups.com> Message-ID: <015c47b6$0$20656$c3e8da3@news.astraweb.com> On Fri, 19 Dec 2008 10:44:25 -0800, r wrote: > And lets not forget Python forcing of indention, that is Pythons > greatest strength! Oh "r", haven't you heard? Python has braces too. Just start your code with from __future__ import braces and see what happens. -- Steven From cournape at gmail.com Sun Dec 21 03:56:42 2008 From: cournape at gmail.com (David Cournapeau) Date: Sun, 21 Dec 2008 17:56:42 +0900 Subject: Python for amd64 and mingw-w64 In-Reply-To: <494B3F75.10104@v.loewis.de> References: <494B3F75.10104@v.loewis.de> Message-ID: <5b8d13220812210056r58a01f53h585d59d0bf81e663@mail.gmail.com> On Fri, Dec 19, 2008 at 3:30 PM, "Martin v. L?wis" wrote: >> - Any extension requires the MS_WIN64 to be defined, but this symbol >> is only defined for MS compiler (in PC/pyport.h). > > Why do you say that? It is only defined when _WIN64 is defined; this > has nothing to do with a MS compiler. > >> Shouldn't it be >> defined independantly of the compiler ? > > You mean, completely unconditional? Definitely not, it should only > be defined when you are compiling for 64-bit mode. I put a more detailed explanation of the problem with an example + a patch on the bug tracker: http://bugs.python.org/issue4709 This is the only problem on python side of things to make extensions buildable on windows x64 (all the other problems I have encountered so far to make numpy build with mingw-w64 are numpy's or mingw-w64). David From geekmail at usenot.de Sun Dec 7 14:47:42 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sun, 7 Dec 2008 20:47:42 +0100 Subject: Importing the re module fails References: <20081207202326.4b5ab73d@usenot.de> <6q2muqFahsfnU1@mid.uni-berlin.de> Message-ID: <20081207204742.67ca7ee2@usenot.de> On Sun, 07 Dec 2008 20:36:58 +0100 "Diez B. Roggisch" wrote: > Andreas Waldenburger schrieb: > > This is a little puzzling. > > > > > > Using ipython: > > > > [wildemar at localhost Logstuff]$ ipython > > Python 2.5.2 (r252:60911, Sep 30 2008, 15:41:38) > > Type "copyright", "credits" or "license" for more information. > > > > [snip ipython help message] > > > > In [1]: import re > > > > > > This works fine. But with the regular python interpreter I get this: > > > > [wildemar at localhost Logstuff]$ python > > Python 2.5.2 (r252:60911, Sep 30 2008, 15:41:38) > > [GCC 4.3.2 20080917 (Red Hat 4.3.2-4)] on linux2 > > Type "help", "copyright", "credits" or "license" for more > > information. > > >>> import re > > Traceback (most recent call last): > > File "", line 1, in > > File "/usr/lib/python2.5/re.py", line 10, in > > # AB (info at pythonware.com). > > AttributeError: 'module' object has no attribute 'compile' > > > > > > What gives? Has Fedora-10 botched python or does anybody else have > > that problem es well? > > In my re.py module on line 10, there is no import - it has way to > much comments on the module beginning. > > So - how does your /usr/lib/python2.5/re.py look like? Just like the error message says: " # AB (info at pythonware.com)." on line ten. That's what confused me so much (among being confused anyway). > And what > about some modules lying around (potentially *pycs) that mask system > modules? > Bullseye. I had a re.pyc in the current directory, because I stupidly created a testbed called re.py. Realizing my folly I renamed it to something else, while forgetting to delete the already created re.pyc. Thanks, and sorry for the noise. (I do wonder why ipython didn't complain, though.) /W -- My real email address is constructed by swapping the domain with the recipient (local part). From istvan.albert at gmail.com Fri Dec 5 13:54:39 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Fri, 5 Dec 2008 10:54:39 -0800 (PST) Subject: slow Python 3.0 write performance? Message-ID: Could someone run the code below on both Python 2.5 and 3.0 For me (on Windows) it runs over 7 times slower with Python 3.0 import time lo, hi, step = 10**5, 10**6, 10**5 # writes increasingly more lines to a file for N in range(lo, hi, step): fp = open('foodata.txt', 'wt') start = time.time() for i in range( N ): fp.write( '%s\n' % i) fp.close() stop = time.time() print ( "%s\t%s" % (N, stop-start) ) From geekmail at usenot.de Fri Dec 5 11:40:26 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Fri, 5 Dec 2008 17:40:26 +0100 Subject: Whitespace in Python (3) [was: RELEASED Python 3.0 final] References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> <20081205161725.3f35222b@usenot.de> <534215df-0ba3-471a-b4d4-e495a3e4daf7@w35g2000yqm.googlegroups.com> Message-ID: <20081205174026.17b24a9a@usenot.de> On Fri, 5 Dec 2008 07:46:02 -0800 (PST) bearophileHUGS at lycos.com wrote: > Andreas Waldenburger: > > My point is: If you mix tabs and spaces in a way that breaks code, > > you'll find out pretty easily, because your program will not work. > > - Most newbies don't know that. > - Sometimes it may produce wrong results. > - And even if you are an expert when you go changing a little a source > code that mixes tabs and spaces you usually break the code. > Is this enough for you? > No. While you are right on all accounts, forcing uniformity would still interfere with (some) people's coding styles, "wrong" as they might be. Python is not Gnome. Maybe having Python issue warnings for inconsistent whitespace per default might be a good idea. But that's about as far as I would go. /W -- My real email address is constructed by swapping the domain with the recipient (local part). From steve at REMOVE-THIS-cybersource.com.au Sat Dec 6 10:50:01 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Dec 2008 15:50:01 GMT Subject: Learning Python now coming from Perl References: Message-ID: <014a96e0$0$20670$c3e8da3@news.astraweb.com> On Sat, 06 Dec 2008 08:50:20 -0500, Roy Smith wrote: > For your first > project, pick something that's small enough that you think you could > tackle it in under 50 lines of Perl. Is there anything which *can't* be written in under 50 lines of Perl? :-) > One of the very first things you'll probably discover that's different > between Perl and Python is how they handle string pattern matching. In > Perl, it's a built in part of the language syntax. In Python, you use > the re module. The regular expressions themselves are the same, but > the mechanism you use to apply them to input text is quite different. Also, Perl REs are faster than Python REs, or so I'm told. Between the speed and the convenience, Perl programmers tend to use RE's for everything they can. Python programmers tend to use REs only for problems that *should* be solved with REs rather than *can* be solved with a RE. Well, I say "tend", but in truth we get our fair share of questions like "Hi, how do I factorize a 20 digit number with a regular expression?" too. Probably the biggest difference is that in Python, you always refer to objects the same way, regardless of what sort of data they contain. Regardless of whether x is a scalar or a vector, you always call it just plain x. -- Steven From grante at visi.com Wed Dec 31 11:34:21 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 31 Dec 2008 10:34:21 -0600 Subject: Graphics Library with Standard Interaction Features, 2D and 3D References: <69c3eca8-5e17-49fb-8354-5fdc0bd73f9a@r15g2000prd.googlegroups.com> Message-ID: On 2008-12-31, Benjamin Blundell wrote: > Hi all. I've had a look around the forums and the we and im looking > for a library (or a set of libraries) for dealing with Visualisation > and Interaction in Python. Have you looked at VTK? http://www.vtk.org/ I've only used some of the numerical stuff (rather than the visualization stuff). The parts I've used have a rather screwy, overly complex API because it's a thinly wrapped C++ library. But, it appears to be quite powerful and well documented. http://cens.ioc.ee/projects/pyvtk/ http://www.imaging.robarts.ca/~dgobbi/vtk/vtkpython.html -- Grant From excord80 at gmail.com Tue Dec 9 22:48:10 2008 From: excord80 at gmail.com (excord80 at gmail.com) Date: Tue, 9 Dec 2008 19:48:10 -0800 (PST) Subject: How do I manually uninstall setuptools (installed by egg)? References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> <375bd56a-d92b-4d33-bf70-5bea630a376a@q30g2000vbn.googlegroups.com> Message-ID: On Dec 9, 10:29?pm, "Chris Rebert" wrote: > On Tue, Dec 9, 2008 at 7:16 PM, ? wrote: > > On Dec 9, 10:04 pm, "Chris Rebert" wrote: > >> So, why do you think apt and not setuptools is The Right Way(tm)? > > > I like to keep > 1 Python on my computer. > > Ah, now I get it. I had no idea setuptools could install Python > *itself* until I checked just now. That's kinda neat, but mostly > silly, because, as you point out, management of Python itself is much > better left to the platform's package manager. > Not sure what you mean, Chris. I install my own Python using the usual procedure (``./configure -- prefix=/home/me/opt/py-..; make; make install``). Never heard of using setuptools (``easy_install``?) to install Python itself. Sounds kooky. :) Anyway, the direction I'm heading is to try and use setuptools *less*. It seems like it might be too complicated for me. And, I notice that the mailing list for it (distutils-sig, if that's the right one) is loaded with questions on how to use it properly, so maybe I'm not alone. From febaen at gmail.com Mon Dec 15 04:06:51 2008 From: febaen at gmail.com (feba) Date: Mon, 15 Dec 2008 01:06:51 -0800 (PST) Subject: Need help improving number guessing game References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> Message-ID: >Seems ok. You may want to use arguments with default values for a and b >(and possibly to use more meaningfull names): I changed it to minr and maxr. Mini is fine, but I can't name a variable maxi unless I have a good feminine hygiene joke to use with it. I don't see the aim of your changes to setup(). I can kinda understand checking to make sure that you didn't make the minimum higher than the maximum, but I think where you put minr/maxr would make it use the same minr/maxr as the end of the previous game, wouldn't it? >Minor point for a short program, but still good practice : use >constants. IE : I had done this initially, but it seemed wasteful and needlessly confusing in this situation. >I assume 'p1sc' means "player_1_score" ? >If so, you may want to use a dict for scores: I don't really understand dicts yet; actually, the tutorial I'm following (http://www.briggs.net.nz/log/writing/snake-wrangling-for- kids/ , designed for tweens, but other than the pointless anecdote and joke here and there, I've found it a very good guide) doesn't even seem to mention them, from a search of the pdf. Actually, apparently I stopped and started working on this just before the chapter on functions and modules. I'll look into that later on, but for now I'm pretty happy with how it works. >Is it really necessary to WRITE THIS IN ALL UPPERS ?-) If you didn't notice, in the original it was "CONGLATURATIONS". I could also make a "VIDEO GAME BAND. Heavy Metal's Not Dead." joke here, but I'm afraid a disappointingly small amount of people will get it. >Python has proper booleans too Yeah, I had those initially too, but "play = True" was causing trouble for some reason when I copy/pasted it into IDLE to try to troubleshoot, so I changed it to 1. I'll probably change it back later. >You should either put this in it's own function (could be named 'main'), >or at least "protect" it with an "if __name__ == '__main__':" test. Could you go into a bit more detail on this? I don't understand what should be its own function, nor do I understand what that line would do or how to use it. James, could you work that into a section of what I have to make it a bit easier to understand? From philip at semanchuk.com Sun Dec 14 10:07:36 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Sun, 14 Dec 2008 10:07:36 -0500 Subject: changing string encoding to different charset? In-Reply-To: <4c0a037d0812140621j5d4f4d47mb4a3097586bacac5@mail.gmail.com> References: <4c0a037d0812140621j5d4f4d47mb4a3097586bacac5@mail.gmail.com> Message-ID: <4D15DF85-C6F6-40CC-AF5D-EF09E8A72E63@semanchuk.com> On Dec 14, 2008, at 9:21 AM, Daniel Woodhouse wrote: > Is it possible to re-encode a string to a different character set in > python? To be more specific, I want to change a text file encoded in > windows-1251 to UTF-8. > I've tried using string.encode, but get the error: > UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position > 0: > ordinal not in range(128) Without seeing your code, I can't be sure, but I suspect that first you need to decode the file to Unicode. # Untested -- s = file("in.txt").read() s = s.decode("win-1251") # Might be "cp1251" instead assert(isinstance(s, unicode)) s = s.encode("utf-8") file("out.txt", "w").write(s) From martin at v.loewis.de Sat Dec 13 23:46:58 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 14 Dec 2008 05:46:58 +0100 Subject: Python 3.0 crashes displaying Unicode at interactive prompt In-Reply-To: References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> <49443531.5050304@v.loewis.de> Message-ID: <49448FC2.6030306@v.loewis.de> > "Sure" as in "sure, it was not intended behaviour"? It was intended behavior, and still is in 3.0. >> This behavior has not changed. It still uses repr(). >> >> Of course, the string type has changed in 3.0, and now uses a different >> definition of repr. > > So was the above-reported non-crash consequence of the change of > definition of repr intended? Yes. If you want a display that is guaranteed to work on your terminal, use the ascii() builtin function. py> x = '\u9876' py> ascii(x) "'\\u9876'" py> print(ascii(x)) '\u9876' Regards, Martin From davidgshi at yahoo.co.uk Wed Dec 3 13:20:27 2008 From: davidgshi at yahoo.co.uk (David Shi) Date: Wed, 3 Dec 2008 18:20:27 +0000 (GMT) Subject: Python calling COM compliant .dll Message-ID: <740322.52556.qm@web26308.mail.ukl.yahoo.com> Hello, there. ? I am looking for a concise working example of Python script calling COM compliant .dll. ? Regards. ? David -------------- next part -------------- An HTML attachment was scrubbed... URL: From invalid at invalid Tue Dec 9 10:52:52 2008 From: invalid at invalid (Grant Edwards) Date: Tue, 09 Dec 2008 09:52:52 -0600 Subject: how to get a beep, OS independent ? References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> <6q6jf8Fau4iiU2@mid.individual.net> Message-ID: On 2008-12-09, greg wrote: > Duncan Booth wrote: > >> If I'm logged in to one of my servers in a large datacentre >> then I don't what that system to beep as that would be pretty >> useless. > > It also might cause the datacentre operators some > consternation when one of their servers starts mysteriously > beeping... If they can hear it. Those tiny fans they put in rack-mount stuff are awfully loud. -- Grant Edwards grante Yow! Where do your SOCKS at go when you lose them in visi.com th' WASHER? From walterbyrd at iname.com Fri Dec 19 12:16:19 2008 From: walterbyrd at iname.com (walterbyrd) Date: Fri, 19 Dec 2008 09:16:19 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: On Dec 19, 9:13?am, "Giampaolo Rodola'" wrote: > You can use the old 2.x syntax also in Python 3.x: Yeah, but it's deprecated, and - as I understand it - may be removed completely in future versions. Also, in the future, if you are working with code from another developer, it's likely that developer will use the new format. I suppose you can use both - but what an awful mess that would be. It seems to me that 3.0 is changing a lot of non-problems. And it's going to be slower to boot. From geekmail at usenot.de Thu Dec 11 12:07:51 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Thu, 11 Dec 2008 18:07:51 +0100 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <87r64f9sma.fsf@rudin.co.uk> Message-ID: <20081211180751.4139f2ec@usenot.de> On Thu, 11 Dec 2008 05:40:45 +0000 Paul Rudin wrote: > "Dotan Cohen" writes: > > > 2008/12/10 : > >> Ruby: > >> > >> def norm a > >> s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) > >> a.map{|x| x/s} > >> end > > > > If someone doesn't counter with a Python one-liner then I'm going to > > port that to brainfuck. > > from numpy.linalg import norm > > :) This is one line of Python code alright, but it's not a "one-liner" in the "computes the a normalized vector"-sense (which was the original challenge, if there ever was one). If anything, you are now ready to compute the *norm* of a vector in a subseqent line. (Or, if you must, after a semicolon on the same line.) :) /W -- My real email address is constructed by swapping the domain with the recipient (local part). From google at mrabarnett.plus.com Sat Dec 13 22:09:08 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 14 Dec 2008 03:09:08 +0000 Subject: subprocess to C program In-Reply-To: <36656830-63a8-479c-8c46-525f2b55eeea@z28g2000prd.googlegroups.com> References: <0ebd59c5-95a1-42d4-b597-d1c248490b8e@y1g2000pra.googlegroups.com> <8MidneyhDfIG-9nUnZ2dnUVZ_uadnZ2d@posted.visi> <36656830-63a8-479c-8c46-525f2b55eeea@z28g2000prd.googlegroups.com> Message-ID: <494478D4.40201@mrabarnett.plus.com> Aaron Brady wrote: > On Dec 13, 7:51 pm, Grant Edwards wrote: >> On 2008-12-14, MRAB wrote: >> >> >> >>>> I am writing a C process and I want to read data from a file that I >>>> write to in Python. I'm creating a pipe in Python, passing it to the >>>> C process, and calling '_read'. It gives me error 9, bad file number. > snip >>>> meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9. I want 'ct' >>>> to be 11 at this point. Thanks in advance. >>> It looks like the ids aren't system global. >> They certainly aren't in Unix: Their a property of the process. >> >> -- >> Grant > > I'm not on Unix. It has to be possible somehow. Do I need to set > permissions on the IDs? Are Stdin and Stdout my only options? Or > does Popen prevent sharing IDs somehow? > You'd be better off using sockets. From exarkun at divmod.com Fri Dec 19 12:36:47 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 19 Dec 2008 12:36:47 -0500 Subject: IMAP: How to implement GMail-like threaded conversations view In-Reply-To: Message-ID: <20081219173647.20272.584484393.divmod.quotient.23072@ohm> On Fri, 19 Dec 2008 08:47:18 -0800 (PST), Martin wrote: >Currently I am trying to get used to Python's imaplib and email >modules. >I'like to create a webmail client simmilar to GMail. I'd suggest using Twisted's IMAP4 client. It's somewhat easier to use than Python's imaplib because it does much more parsing of IMAP4's complex syntax for you. It will also be easier to do IMAP4 and HTTP simultaneously if you're using Twisted. Twisted won't help with the threading feature you want to implement though, it lets you use the email package if you want to examine the structure of the messages you retrieve. Jean-Paul From senthilkas at gmail.com Mon Dec 8 13:42:30 2008 From: senthilkas at gmail.com (Senthil Kumar) Date: Mon, 8 Dec 2008 10:42:30 -0800 (PST) Subject: Catching Python exceptions in C Message-ID: Hi Pythoneers ! Can somebody give a quick solution? I am trying to raise exceptions in python and trying to handle it in C. I am able to raise exceptions successfully. However could not catch those in C. I am using the following function to run the python from C: Pyrun_SimpleString(). After the exception is raised, I am checking PyErr_Occurred(). It always returns NULL, and I cannot catch the exception. Pls help me a way out. Thanx in advance ! From Eric_Dexter at msn.com Mon Dec 1 03:41:40 2008 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Mon, 1 Dec 2008 00:41:40 -0800 (PST) Subject: tkinter question References: <538f4349-02a1-4c2b-b892-a01f1f48cb5b@l64g2000hse.googlegroups.com> Message-ID: On Oct 26, 7:02?am, "Chuckk Hubbard" wrote: > Hello. > How about this? ?I changed the if statements so the coordinates are > always updated, but only changed if within the right limits, otherwise > updated to the existing value. ?Now if you drag outside the limits of > one dimension, it still moves in the other dimension. ?Not sure if > that's what you want. ?I'm amazed that this can be so simple, I came > up with an intricate system for my app, not realizing I could bind > events to canvas items! > BTW, I've never come across csoundroutines, can you give me a synopsis > of what it's for? ?I'm using thePythonCsoundAPI. ?This is why I > commented out all the references to csoundroutines, I don't have it > installed at the moment. > -Chuckk > > #!/usr/bin/python > from Tkinter import * > #import csoundroutines as cs > > root = Tk() > > global canv > xx = {} > > def makeFrame(root): > ? global canv > # ?test = cs.csdInstrumentlist3('bay-at-night.csd') > ? canv = Canvas (root, height = 200, width = 350) > > # ?for i in range (0, len(test.instr_number)): > ? for i in range (0, 4): > # ? ?canv.create_text(10, i *10, text=str(test.instr_number[i]) + > ? ? canv.create_text(10, i *10, text=str(i) + > '...', tags=('movable')) > ? ? xx[i] = canv.tag_bind('movable', '', slide) #B1-motion > is a drag with left button down > ? ? canv.pack() > > def slide (event): > ? ''' > ? triggered when something is dragged on the canvas - move thing > under > mouse ('current') to new position > ? ''' > ? if 0 < event.x < 200: > ? ? ? newx = event.x > ? else: newx = canv.coords('current')[0] > ? if 0 < event.y < 100: > ? ? newy = event.y > ? else: newy = canv.coords('current')[1] > ? canv.coords('current', newx, newy) > > makeFrame(root) > root.mainloop() > > > > > > On Fri, Oct 3, 2008 at 3:44 PM, Eric_Dex... at msn.com wrote: > > I saw this (close to this anyway) lieing around on the internet and > > was wanting to use it to define a start point exc but I need the > > graphics to stay within a set y coords and I am not realy sure how to > > do that. ?I have no idea on how to bind a min/max y to it. ?(the > > concept is inspired by the javacsoundblue). > > > #!/usr/bin/python > > from Tkinter import * > > import csoundroutines as cs > > > root = Tk() > > > global canv > > xx = {} > > > def makeFrame(root): > > ? global canv > > ? test = cs.csdInstrumentlist3('bay-at-night.csd') > > ? canv = Canvas (root, height = 200, width = 350) > > > ? for i in range (0, len(test.instr_number)): > > ? ? canv.create_text(10, i *10, text=str(test.instr_number[i]) + > > '...', tags=('movable')) > > ? ? xx[i] = canv.tag_bind('movable', '', slide) #B1-motion > > is a drag with left button down > > ? ? canv.pack() > > > def slide (event): > > ? ''' > > ? triggered when something is dragged on the canvas - move thing > > under > > mouse ('current') to new position > > ? ''' > > ? newx = event.x > > ? if event.y < 10 and event.y > 0: > > ? ? newy = event.y > > ? ? canv.coords('current', newx, newy) > > > makeFrame(root) > > root.mainloop() > > -- > >http://mail.python.org/mailman/listinfo/python-list > > --http://www.badmuthahubbard.com- Hide quoted text - > > - Show quoted text - haven't tried this yet but I look foward to trying it out.. From benjamin.kaplan at case.edu Tue Dec 9 00:04:32 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 9 Dec 2008 00:04:32 -0500 Subject: How to initialize a class variable once In-Reply-To: <804363f5-458a-4e72-8b2f-ad9c3c28b6cb@s9g2000prg.googlegroups.com> References: <804363f5-458a-4e72-8b2f-ad9c3c28b6cb@s9g2000prg.googlegroups.com> Message-ID: On Mon, Dec 8, 2008 at 11:44 PM, John Machin wrote: > On Dec 9, 3:36 pm, Matimus wrote: > > On Dec 8, 8:08 pm, Roy Smith wrote: > > > > > I've got a class with a class variable: > > > > > class Foo: > > > _map = {} > > > > > How do I make sure this only gets initialized the *first* time the > > > module containing the class is imported? What appears to be happening > > > as it stands is each time the module gets imported, Foo._map get re- > > > initialized. > > > > Unless you are calling reload() on the module, it will only ever get > > _loaded_ once. Each additional import will just yield the existing > > module. Perhaps if you post an example of the behavior that leads you > > to believe that the class variables are getting reinitialized > > and change it to > class Foo(object): > because we care little about old-style classes these days unless the OP is using Python 3 in which case that would be redundant. This is going to be really confusing unless every poster lists their python version. > > and put a print statement in the module just before the class > statement and print statements before and after each import statement > so that we can see what is happening. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From exarkun at divmod.com Thu Dec 4 17:27:55 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 4 Dec 2008 17:27:55 -0500 Subject: schizophrenic view of what is white space In-Reply-To: <878wqvy5y9.fsf@mulj.homelinux.net> Message-ID: <20081204222755.20272.1632534177.divmod.quotient.15780@ohm> On Thu, 04 Dec 2008 22:40:46 +0100, Hrvoje Niksic wrote: > [snip] > >Whitespace is probably not controversial, but many parsers tend to >expect things like \d to match [0-9], not any Unicode character marked >as "digit". For example, I'm not sure if this behavior would be a >good default: > >>>> re.match(r'\d', u'\u0660', re.UNICODE) ><_sre.SRE_Match object at 0xb7da0250> > >What digit is \u0660, out of 0-9? Hard to say. Why's it hard? int(u'\u0660') == 0 :) Jean-Paul From deets at nospam.web.de Sun Dec 7 06:13:59 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 07 Dec 2008 12:13:59 +0100 Subject: var or inout parm? In-Reply-To: References: Message-ID: <6q1pfoFaapofU1@mid.uni-berlin.de> mh at pixar.com schrieb: > How can I make a "var" parm, where the called function can modify > the value of the parameter in the caller? > > def f(x): > x = x + 1 > > n = 1 > f(n) > # n should now be 2 Chris showed one way, another is simply returning it. As python can return ad-hoc created tuples & unpack them, some C++-wrappers for example treat out/inout vars like this: def foo(in, inout): return inout, out1, out2 x, y, z = foo(a, x) Obviously you are responsible for properly assigning the returned inout to the right name again. Diez From eric at ericaro.net Fri Dec 19 11:21:42 2008 From: eric at ericaro.net (eric) Date: Fri, 19 Dec 2008 08:21:42 -0800 (PST) Subject: best way to code Message-ID: hi, I need to find a "good" design pattern to instanciate, and add specific code all in one. Let me explain it : I need to define "some" code, better be in a class, something like class LinkA(object): def mystuff(self): class LinkB(object): def mystuff(self): AND I need an instance of this class { "stuff A": LinkA() "stuff B": LinkB() } This kind of code "would" be fine, I mean, the result effect in memory is fine for me. But I don't like the way I have to 1/ give a useless name to LinkA, linkB (there can be hundreds of names like that) 2/ I have to write it down two times (and that's one time too much) any ideas ? something like [ new object(): def mystuff(self): , new object(): def mystuff(self): ] would be really perfect (but I know it does not work, or at least, I don't know how to make it work) In fact, I would like to define a class, and an instance in a single statement thanks -- Eric http://codeslash.blogspot.com From prologic at shortcircuit.net.au Mon Dec 8 08:10:48 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Dec 2008 23:10:48 +1000 Subject: A question about reference in Python. In-Reply-To: References: <493CB003.3080209@gmail.com> <47c890dc0812072213q20cb415fjbd4c80e7af7a7ef5@mail.gmail.com> Message-ID: In case the OP is interested here is a more complete implementation (others are welcome to comment): http://codepad.org/drIhqb7Z Enjoy :) cheers James -- -- -- "Problems are solved by method" From thorsten at thorstenkampe.de Tue Dec 23 09:21:42 2008 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 23 Dec 2008 15:21:42 +0100 Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: * r (Mon, 22 Dec 2008 10:44:32 -0800 (PST))> > Steve Holden > > What makes you assume this is a zero-sum game, and that Python won't > > survive if any other language becomes popular. Every language borrows > > from those that came before it. Terms like "outright plagiarism" don't > > encourage rational debate, and make you seem like a troll who is more > > interested in stirring up controversy than actually doing things to help > > promote the language. > > This is a war Steve, and i will explain why. Python does not need to > compete with perl, lisp, C, basic, etc, etc. WHY, well because python > is SO radically different than those languages. Ruby on the other > hand, took most from python, the only difference is Ruby's full OO > integration.(12.method()). Since Ruby is so similar to python [...] You don't have a single clue about neither Python nor Ruby: 'According to the Ruby FAQ, "If you like Perl, you will like Ruby and be right at home with its syntax. [...] If you like Python, you may or may not be put off by the huge difference in design philosophy between Python and Ruby/Perl."'[1] Thorsten [1] http://en.wikipedia.org/wiki/Ruby_(programming_language)#Semantics From carsten.kraus at gmail.com Tue Dec 30 15:41:18 2008 From: carsten.kraus at gmail.com (carsn) Date: Tue, 30 Dec 2008 12:41:18 -0800 (PST) Subject: PIL - font kerning References: <21524b00-9151-43ab-b1b9-a3dd5666d959@n33g2000pri.googlegroups.com> <013a0d90-e70e-49e9-ad7c-73d93e7bd79a@z28g2000prd.googlegroups.com> Message-ID: On Dec 23, 9:51 pm, Ivan Illarionov wrote: > On Dec 23, 11:22 pm, Ivan Illarionov > wrote: > > > > > On 23 ???, 16:44, carsn wrote: > > > > Hey all, > > > > anybody know, if there?s a way to specify the kerning of a font, when > > > you draw text withPIL? > > > > I?d like to achieve the same effect that you get, when you set a > > > negative kerning in Gimp/Photshop - ie. reduce the spacing between > > > glyphs. > > > > CanPILdo that or do I use another lib for that? > > > > Thx for any pointers & some nice xmas days to U all! > > > carsten > > > No.PILcan't do that. I suggest combination of cairo/pango/pangocairo > > (pycairo and pygtk packages). > > > Ivan > > I found a little helper function that does what you want (and more) > > import cairo > import pango > import pangocairo > > def draw_text(surface, context, text, font="sans 14", position=None, > color=None, > box_width=None, > alignment=pango.ALIGN_CENTER, > line_spacing=None, letter_spacing=None, > extra_kerning=None): > if color is None: > color = (0.0, 0.0, 0.0) > context.set_source_rgb(*color) > pc = pangocairo.CairoContext(context) > layout = pc.create_layout() > layout.set_text(text) > layout.set_font_description(pango.FontDescription(font)) > if box_width: layout.set_width(box_width) > layout.set_alignment(alignment) > if line_spacing: layout.set_spacing(spacing) > alist = pango.AttrList() > if letter_spacing: > alist.insert(pango.AttrLetterSpacing(letter_spacing, 0, len > (text))) > if extra_kerning: > for pos, kern in extra_kerning.iteritems(): > alist.insert(pango.AttrLetterSpacing(kern, pos, pos > +1)) > layout.set_attributes(alist) > if position is None: > width, height = surface.get_width(), surface.get_height() > w, h = layout.get_pixel_size() > position = (width/2.0 - w/2.0, height/2.0 - h/2.0) > context.move_to(*position) > pc.show_layout(layout) > > And example usage: > > surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) > context = cairo.Context(surface) > draw_text(surface, context, 'Hello world!', > font="sans 52", color=(.25,.28,.33), > letter_spacing=-6000, > extra_kerning={0:-9000, 1:-1000, 6:6000, 7:-15000, 8:5000, > 9:-7000}) > > surface.write_to_png("hello.png") > > -- > Ivan Works great, thanks a lot!! From steve at holdenweb.com Sat Dec 20 08:21:43 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 20 Dec 2008 08:21:43 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <494cc88c$0$31344$9b4e6d93@newsspool4.arcor-online.net> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c47ad$0$20656$c3e8da3@news.astraweb.com> <494cc88c$0$31344$9b4e6d93@newsspool4.arcor-online.net> Message-ID: Stefan Behnel wrote: [...] > I think '...'.format() makes sense given that we already have '...'.join(). > Sure it does, but that doesn't stop a lot of people disliking str.join() regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From robert.kern at gmail.com Sat Dec 20 22:37:28 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 20 Dec 2008 21:37:28 -0600 Subject: linecache vs egg - reading line of a file in an egg In-Reply-To: References: Message-ID: R. Bernstein wrote: > Does linecache work with source in Python eggs? If not, is it > contemplated that this is going to be fixed or is there something else > like linecache that currently works? linecache works with eggs and other zipped Python source, but it had to extend the API in order to do so. Some of the debuggers don't use the extended API. This will be fixed in the next 2.6.x bugfix release, but not in 2.5.3. http://bugs.python.org/issue4201 -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From cjw at ncf.ca Sat Dec 6 08:18:07 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 06 Dec 2008 08:18:07 -0500 Subject: Multiple Versions of Python on Windows XP In-Reply-To: References: <4934de22$0$27863$9b622d9e@news.freenet.de> <4934E183.9020404@g.nevcal.com> <4934E3BF.7000403@v.loewis.de> Message-ID: <493A7B8F.8070806@ncf.ca> Glenn Linderman wrote: > On approximately 12/1/2008 11:29 PM, came the following characters from > the keyboard of Martin v. L?wis: >>> It would be nice if the ftypes were version specific as created by the >>> installer; IIRC, I created the above three from the ftype Python.File as >>> I installed each version. >>> >> >> That's a good idea; please submit a wish list item to bugs.python.org. >> There may be issues (such as people relying on this being Python.File), >> but I can't see any problems off-hand. >> >> Regards, >> Martin >> > > OK, Issue 4485 created. My first one, so let me know if I goofed. I > elaborated a bit from the original email, upon reflection. Seemed > useful, but also seemed complex by the time I got done. > > I don't really have a clue what the uninstaller should do with these; > nor have I fiddled to know if it presently removes Python.File. I > suppose it should delete them, if and only if the ftype and assoc have > the same content as was created by the corresponding version installation. > Here's another approach to handling multiple versions of Python, thanks to the PyScripter List. It does not address the need to access different versions of the Python Interpreter. Here is the full story. There are two types of Python installation a) For all users Python creates registry entries at HKEY_LOCAL_MACHINE\SOFTWARE\Python \PythonCore\2.x with installation info and puts the dll in c:\Windows \System32. b) For a single user Python creates registry entries at HKEY_CURRENT_USER\SOFTWARE\Python \PythonCore\2.x with installation info and does not put the dll in c: \Windows\System32. PyScripter without any command line flags looks at the registry to find the latest version of Python and then for an all user installation tries to load the relevant Python dll from the system path. For a single user installation tries to load the DLL from the Install path that is in the registry. When PyScripter is used with a --PYTHONxx flag then it does the above but searching only for the specific version. The Registry lookup does not take place when Python is used with the -- PYTHONDLLPATH. Instead PyScripter tries to load the Python dll from the specified path. The --PYTHONDLLPATH flag should be used with the --PYTHONxx flag. See http://pyscripter.googlepages.com/portablepython for an example of using PyScripter with portable Python. The %PYTHONHOME% variable is not used by PyScripter directly but by Python to find the installed libraries. See the Python documentation for its use. Colin W. From trfilmographer at gmail.com Fri Dec 12 13:55:14 2008 From: trfilmographer at gmail.com (trfilmographer at gmail.com) Date: Fri, 12 Dec 2008 10:55:14 -0800 (PST) Subject: newbie question... References: Message-ID: On Dec 12, 12:59?pm, r wrote: > yes, but your script will need to know hoe to handle this.the > following will open a file who's name was passed to the script > > if len(sys.argv) > 1: > ? ? try: > ? ? ? ? open_file(fname=sys.argv[1]) > ? ? except: > ? ? ? ? pass ah, ok. now what if I want the variable to be an integer that I send? for instance if I send 99 to the program, it is picking it up as a string instead of an integer value. How do I handle this with python?? From kirk at daycos.com Fri Dec 12 10:59:56 2008 From: kirk at daycos.com (Kirk Strauser) Date: Fri, 12 Dec 2008 09:59:56 -0600 Subject: newbie question: if var1 == var2: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> <87y6ymzecp.fsf@daycos.com> Message-ID: <87myf1z8n7.fsf@daycos.com> At 2008-12-12T15:35:11Z, "J. Cliff Dyer" writes: > Python has a version equally good: > > def chomp(s): > return s.rstrip('\r\n') > > You'll hardly miss Perl at all. ;) I haven't missed Perl in years! I just wish there was a basestring.stripeol method because I seem to end up writing the inline version of "chomp" every time I iterate across a file. -- Kirk Strauser The Day Companies From steve at holdenweb.com Mon Dec 22 20:31:16 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 22 Dec 2008 20:31:16 -0500 Subject: Python's popularity In-Reply-To: References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <494fef38$0$12781$426a74cc@news.free.fr> Message-ID: walterbyrd wrote: [...]>> Fooled by version numbers ? > > No, but I am giving django the benefit of the doubt. The django > project told people all along that django was not to be considered > production ready before 1.0. I will accept that some people decided to > wait until 1.0 came out to do any production development. Maybe django > is only lagging because 1.0 just came out? > The Django people said no such thing. They maintained the trunk as stable - they test so well that many people did indeed rely on the trunk for production systems. They did, sensibly in my opinion, refuse to promise that the 1.0 release would be backward-compatible with the development versions. Indeed they frequently changed the trunk in incompatible ways while they were working to find the best APIs, and this only affected those brave or stupid enough to update their Django installation automatically as checkins were made. Anyone would expect trouble doing that, and yet the affected sites were usually easily fixed, thanks to the project's conscientious maintenance of a list of incompatible changes. >> My actual CTO is a big Ruby/Rails fan, yet he settled on Python/Django >> for our current 'big' project. Wonder why ? > > Not knowing much about RoR: yes, I wonder why? Is it because python > has a cleaner syntax? Or what? It's because he decided that Django was the best tool for the particular job, making him unusually open-minded for a member of the pointy-haired species. Unlike some on this list he doesn't let his prejudices blind him to reality. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From ldo at geek-central.gen.new_zealand Mon Dec 1 02:57:24 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 01 Dec 2008 20:57:24 +1300 Subject: end of print = lower productivity ? References: Message-ID: In message , cptnwillard at gmail.com wrote: > Now the print statement disappeared, and I have to write print("f") > instead. These parentheses not only take time to write, they also make > me think twice about using print for debugging purposes. Trouble is, print defaulted to printing to stdout, and I usually wanted debug messages to go to stderr. So print saved me nothing, which is why I never got into the habit of using it. From antoine at vo.lu Sat Dec 6 08:56:54 2008 From: antoine at vo.lu (Antoine De Groote) Date: Sat, 06 Dec 2008 14:56:54 +0100 Subject: Guido's new method definition idea In-Reply-To: <7c56a65c-ca99-4d00-b425-ae6385ff1a0a@v42g2000yqv.googlegroups.com> References: <7c56a65c-ca99-4d00-b425-ae6385ff1a0a@v42g2000yqv.googlegroups.com> Message-ID: Aaron Brady wrote: > On Dec 5, 8:21 pm, "Daniel Fetchinson" > wrote: >> Hi folks, >> >> The story of the explicit self in method definitions has been >> discussed to death and we all know it will stay. However, Guido >> himself acknowledged that an alternative syntax makes perfect sense >> and having both (old and new) in a future version of python is a >> possibility since it maintains backward compatibility. The alternative >> syntax will be syntactic sugar for the old one. This blog post of his >> is what I'm talking about: >> >> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... >> >> The proposal is to allow this: >> >> class C: >> def self.method( arg ): >> self.value = arg >> return self.value >> >> instead of this: >> >> class C: >> def method( self, arg ): >> self.value = arg >> return self.value >> >> I.e. explicit self stays only the syntax is slightly different and may >> seem attractive to some. > ... > > Would it be valid outside class definitions too? (As follows...) > > def sequence.shuffle( ): > x= sequence[ 0 ] > sequence[ 0 ]= sequence[ -1 ] > ...etc. > > shuffle( listA ) This is not what was intended. The discussion was explicitly only about class methods. What you are describing is weird and not generalizable. What if your method takes more than one parameter? You might argue that "sequence" would be the first argument in the list, like def sequence.shuffle(a, b): """ a, b: dummy arguments, just for the sake of the example """ x = sequence[0] sequence[0] = sequence[-1 ...etc. shuffle(listA, 1, 1) I can't think of any good reason to do this. What's more, the whole discussion was partly due to error messages like Traceback (most recent call last): File "classes.py", line 9, in obj.m2(1) TypeError: m2() takes exactly 3 arguments (2 given) Your proposition (well actually it is only a question) would result in error messages exactly like this one when one would not carefully read the method signature for example. > > Can you still call it by class membership? (As follows...) > > C.method( inst, arg ) That should not change at all, as the alternative syntax would actually be only syntactic sugar. From exarkun at divmod.com Mon Dec 8 11:36:36 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 8 Dec 2008 11:36:36 -0500 Subject: Equivalent of 'wget' for python? In-Reply-To: <6q50bfFaqa0aU1@mid.uni-berlin.de> Message-ID: <20081208163636.20272.716624751.divmod.quotient.17901@ohm> On Mon, 08 Dec 2008 17:29:35 +0100, "Diez B. Roggisch" wrote: >Robert Dailey wrote: > >> Hi, >> >> I'm looking for a portable way to download ZIP files on the internet >> through Python. I don't want to do os.system() to invoke 'wget', since >> this isn't portable on Windows. I'm hoping the core python library has >> a library for this. Note that I'll be using Python 3.0. > >Module urllib2 > There isn't such a module in Python 3.0. Jean-Paul From lists at cheimes.de Thu Dec 11 18:48:43 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 12 Dec 2008 00:48:43 +0100 Subject: Best way of debigging a C extension In-Reply-To: <6qdjt7Fc1fg0U1@mid.uni-berlin.de> References: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> <6qdjt7Fc1fg0U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch schrieb: > I never tried this on windows - but what happens if you start python > inside GDB, and then set breakpoints inside your extension? > > This works flawlessly for me under *nix. > > The debug-build of python isn't needed for this - and I doubt a bit that > it helps you much, as being inside the interpreter & getting detailed > information isn't your goal - you want to see your extensions functions, > what parameters they get and so on. It doesn't work well with all debugging symbols stripped and with -O2 optimized code. The compiler rearranges the code. You could try to compile your own code with different compiler arguments. I don't know if that's easily possible on Windows with Python 2.5. Christian From fuzzyman at gmail.com Sun Dec 14 17:59:26 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 14 Dec 2008 14:59:26 -0800 (PST) Subject: Looking for the best way to translate an idiom References: <4945406a$0$1127$426a74cc@news.free.fr> <2c5ad999-47f9-4040-85c9-4c9438afe4bb@b41g2000pra.googlegroups.com> Message-ID: On Dec 14, 5:51?pm, Paul Moore wrote: > On 14 Dec, 16:22, Bruno Desthuilliers > > wrote: > > if you only want the first returned value, you can just apply a slice: > > > def f(): > > ? ? return 1,2,3 > > > a = f()[0] + 1 > > Hmm, true. I'm not sure it's any less ugly, though :-) > > > FWIW, Python 2.6 has NamedTuple objects... > > I know, but I want to target 2.5+ (I still have a number of systems > running 2.5) > There is a Python implementation of NamedTuple on the Python cookbook that is compatible with Python 2.5. Michael Foord http://www.ironpythoninaction.com/ From rdmurray at bitdance.com Tue Dec 9 21:12:04 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Tue, 9 Dec 2008 21:12:04 -0500 (EST) Subject: SequenceMatcher bug ? In-Reply-To: References: Message-ID: On Mon, 8 Dec 2008 at 23:46, eliben wrote: > This is about Python 2.5.2 - I don't know if there were fixes to this > module in 2.6/3.0 > > I think I ran into a bug with difflib.SequenceMatcher class. > Specifically, its ratio() method. The following: > > SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + [5]).ratio > () > > returns 0.0 > > While the same with 500 replaced by 100 returns .99... something > Looking at the code of SequenceMatcher there's some caching going on > when the sequences are longer than 200 elements (and indeed, I can > reproduce the bug above 200 but not below). Can anyone confirm that > this misbehaves and suggest a workaround ? Python 2.5.2 (r252:60911, Sep 29 2008, 20:34:04) [GCC 4.3.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from difflib import SequenceMatcher >>> SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + >>> [5]).ratio() 0.99900299102691925 --RDM From antoine at vo.lu Tue Dec 9 06:38:25 2008 From: antoine at vo.lu (Antoine De Groote) Date: Tue, 09 Dec 2008 12:38:25 +0100 Subject: primera Message-ID: <16149$493e58b1$d9a2276f$4726@news.hispeed.ch> zalli, du spills jo net mat am volley oder? mengs de du kinns dann mat mengem auto an den MCM an eventuell op sandweiler fueren? well m?indes ass volley, densdes fussball, an mettwochs ass schon hellejen owend... nuecht antoine From bj_666 at gmx.net Fri Dec 12 11:13:56 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 12 Dec 2008 16:13:56 GMT Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> Message-ID: <6qfgu4Fc3a5jU4@mid.uni-berlin.de> On Fri, 12 Dec 2008 16:51:15 +0100, Marco Mariani wrote: > Filip Gruszczy?ski wrote: > > >> I am not doing it, because I need it. I can as well use "if not elem is >> None", > > I suggest "if elem is not None", which is not quite the same. In which way is it not the same? Has the same behavior at least: In [256]: elem = None In [257]: not elem is None Out[257]: False In [258]: elem is not None Out[258]: False In [259]: elem = 42 In [260]: not elem is None Out[260]: True In [261]: elem is not None Out[261]: True > If you slip such an error in a post, I suggest to practice some time > writing correct code before having one-liner contests with your > perl-loving friends :) If you call something an error, make sure it really is one. :-) Ciao, Marc 'BlackJack' Rintsch From 5lvqbwl02 at sneakemail.com Fri Dec 26 20:28:10 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Fri, 26 Dec 2008 17:28:10 -0800 (PST) Subject: Doing set operation on non-hashable objects References: <3a87eb6a-13ff-4aea-8835-3a233cc6cfc4@w39g2000prb.googlegroups.com> <6c043bc7-19e6-4e3d-bf01-5ade35d8a90a@s1g2000prg.googlegroups.com> Message-ID: <73bb9180-ee52-4718-8041-c03ed33f0441@a29g2000pra.googlegroups.com> On Dec 24, 12:52?pm, Carl Banks wrote: > On Dec 24, 1:16?pm, 5lvqbw... at sneakemail.com wrote: > > > > > > > Hi, > > > I'm writing an application which is structured roughly as follows: > > > "db" is a dict, where the values are also dicts. > > A function searches through db and returns a list of values, each of > > which is a dict as described above. > > I need to perform set operations on these lists (intersection and > > union) > > However the objects themselves are not hashable, and therefore can't > > be in a set, because they are dicts. > > I'm not sure how large each set will be, but the point is I'm trying > > to avoid anything looking like an O(n^2) algorithm, so I can't just > > use naive double-looping to check for intersection/union on a pair of > > lists. > > > The only way I can think of to do this right is to hash the dicts by > > freezing them, turning them all into tuples, which can then be > > hashed. ?But this is a problem because more dicts might be nested > > inside. ?At any rate, I'd need to thaw them out when I'm done and turn > > them back into dicts, which seems complicated and annoying, and all > > this leads me to believe there is a better way. > > > What I really need is a set of pointers, so at the end of the > > operation I have the actual objects pointed to. ?Can I somehow use the > > object IDs as set elements, then recreate a list with the actual > > objects they point to? > > > How do you get the object back from an ID in python? > > Quick and dirty way is to reference the dicts with a lightweight > hashable object that uses the dict's identity. ?For instance: > > class Identity(object): > ? ? def __init__(self,obj): > ? ? ? ? self.obj = obj > ? ? def __hash__(self): > ? ? ? ? return hash(id(self.obj)) > ? ? def __eq__(self,other): > ? ? ? ? return self.obj is other.obj > > Then, instead of "s.add(d)" use "s.add(Identity(d))". > > Instead of "d = s.pop()" use "d = s.pop().obj". > > Instead of "d in s" use "Identity(d) in s". > > And so on. > > To do it a bit better, you could create an IdentitySet class that > subclasses set and wraps the methods so that they automatically apply > wrap and unwrap the arguments on their way in and out (I'd bet there's > already a cookbook recipe to do that). > > Carl Banks Thank you, I like this idea a lot. It's close to what I've been thinking but a bit cleaner. Michael From jstroud at mbi.ucla.edu Sun Dec 7 03:41:10 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 07 Dec 2008 00:41:10 -0800 Subject: Brain going crazy with recursive functions In-Reply-To: <181d6cf8-8df3-46d4-9d21-197d34b3de87@d36g2000prf.googlegroups.com> References: <181d6cf8-8df3-46d4-9d21-197d34b3de87@d36g2000prf.googlegroups.com> Message-ID: 5lvqbwl02 at sneakemail.com wrote: > I'm trying to solve the 9-tile puzzle using as functional an approach > as possible. I've recently finished reading SICP and am deliberately > avoiding easy python-isms for the more convoluted scheme/functional > methods. The following function is trivial to do with for loops and > directly accessing arrays with [] syntax. I'm trying to limit myself > to the types of idioms/semantics one finds in minimal scheme, such as > in SICP. I want eventually to port this to scheme, but I know python > better, so that's where I'm starting. > > My current problem is the following. The 9-tile puzzle consists of a > list of lists like this [[1,2,3],[4,5,6],[7,8,0]], where the numbers > can be jumbled up. I'm looking for the location of the zero using > *only* recursion and operators that are similar to car/cdr. The > return value should be the row,col of the zero. For example above the > return value would be (2,2). > > I'm also trying to define a single "linear_search(...)" function which > does the search for within the row (an inner list above) and within > the whole list. linear_search takes as an argument a "truth_function" > which does the actual work. What's tricky is that the truth function > for the array-as-a-whole is also the linear_search for a row. Once > I'm in linear_search for the array, I also call linear_search for each > row. > > The problem is the line where it says acc.insert(0,idx) looks fishy to > me. It works fine and returns the row,col of the location of the zero > tile, but it seems to be mutating a variable, and that's the thing I'm > trying to avoid. In a sense, it's not hard enough and python is > making this too easy :) (although it took a bit of mind-wrenching to > get to this point. Recursion makes you either dumber or smarter, I'm > not sure which). > > How do I accumulate the inner value of the search so it pops out at > the end, without resorting to a mutable variable? I did a bit of > search and the word "monad" came up, but I'm not sure what that is (I > know it relates to haskell and some other purely functional stuff, but > I get very lost when trying to read that stuff). > > def linear_search(array, truth_func, acc): > # Goes through each element of array and applies truth_func. > # Returns index if found, otherwise returns None > def linear_search_iter(idx, truth_func, arr, acc): > if arr: > tf = truth_func(arr[0]) > if tf or type(tf) is int: > acc.insert(0,idx) > return idx, acc+[idx] > else: > return linear_search_iter(idx+1, truth_func, arr[1:], acc) > return linear_search_iter(0, truth_func, array, acc) > > > > def locate_zero(p): > # Locates empty tile. Returns (r,c) tuple > def find_zero_in_row(row): > return linear_search(row, lambda x: x==0, acc) > > acc = [] > ls = linear_search(p, find_zero_in_row, acc) > print acc > return acc > thanks > Michael I am honestly getting lost in your code. The following fulfills your requirements as far as I can tell. It uses None as a sentinel for the truth function matching no elements of the array. Some assignments are made within the code simply to make it more readable. They are not necessary. The first element that the truth function evaluates to True is returned. I hope it helps. James def linear_search(array, truth_func, loc=(0,0)): idx1, idx2 = loc if idx1 >= len(array): return None if idx2 >= len(array[idx1]): return linear_search(array, truth_func, (idx1+1, 0)) value = array[idx1][idx2] tf = truth_func(value) if tf: return loc else: return linear_search(array, truth_func, (idx1, idx2+1)) a = [[5, 3, 4], [2, 0, 1], [8, 6, 7]] linear_search(a, lambda x: x==0) From Slaunger at gmail.com Tue Dec 2 10:01:44 2008 From: Slaunger at gmail.com (Slaunger) Date: Tue, 2 Dec 2008 07:01:44 -0800 (PST) Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> <258cf433-f6c9-43e7-a235-f5f6b2b6433f@j39g2000yqn.googlegroups.com> Message-ID: <33b4cc2f-2311-491c-a2e6-9cc5452b1a6b@g38g2000yqd.googlegroups.com> Just wanted to show the end result in its actual implementation! I ended up *not* making a decorator, as I already had a good idea about how to do it using __getattr__ class PayloadDualFrqIQOnDemand(PayloadDualFrqIQ): """ This class has the same interface as its parent, but unlike its parent, it is instantiated without its payload parsed up in its instance attributes Q1, I1, Q2 and I2. Instead it stores a reference to the file object in which the Payload data can be read, the file position and the version of the payload data. On accessing one of the data attributes, the actual payload data are read from the file, and the reference to the file object is unbound. The constructor signature is therefore different from its parent as it takes the file object, position and version as arguments instead of the actual data. """ @classmethod def _unpack_from_file(cls, f, samples, ver): bytes = samples * cls.bytes_per_sample initial_pos = f.tell() f.seek(initial_pos + bytes) #Skip over the payload return cls(f, initial_pos, samples, ver) @classmethod def unpack_from_ver3_file(cls, f, samples): return cls._unpack_from_file(f, samples, ver=3) @classmethod def unpack_from_ver4_file(cls, f, samples): return cls._unpack_from_file(f, samples, ver=4) data_attr_names = frozenset(["Q1", "I1", "Q2", "I2"]) def __init__(self, a_file, a_file_position, samples, a_version): """ Returns an instance where the object knows where to look for the payload but it will only be loaded on the first attempt to read one of the data attributes in a "normal" PayloadDualFrqIQ object. """ self.f = a_file self.file_position = a_file_position self.samples = samples self.ver = a_version def __getattr__(self, attr_name): """ Checks if a request to read a non-existing data attribute has an attribute corresponding to one of the data attributes in a normal PayloadDualFrqIQ object. If true, the data attributes are created and bound to the object using the file object instance, the file position and the version. It is a prerequisite that the file object is still open. The function leaves the file object at the file position when it entered the method """ cls = self.__class__ if attr_name in cls.data_attr_names: initial_pos = self.f.tell() try: bytes = self.samples * cls.bytes_per_sample self.f.seek(self.file_position) buf = self.f.read(bytes) if self.ver == 3: bytes_to_data = cls._v3_byte_str_to_data elif self.ver == 4: bytes_to_data = cls._v4_byte_str_to_data else: raise TermaNotImplemented, \ "Support for ver. %d not implemented." % self.ver I1, Q1, I2, Q2 = bytes_to_data(buf) self.__dict__["I1"] = I1 self.__dict__["Q1"] = Q1 self.__dict__["I2"] = I2 self.__dict__["Q2"] = Q2 return self.__dict__[attr_name] finally: # Restore file position self.f.seek(initial_pos) # Unbind lazy attributes del self.f del self.ver del self.file_position del self.samples This seems to work out well. No infinite loops in __getattr__! At least it passes the unit test cases I have come up with so far. No guarantees though, as I may simply not have been smart enough to bring forth unit test cases which make it crash. Comments on the code is still appreciated though. I am still a novice Python programmer, and I may have overlooked more Pythonic ways to do it. -- Slaunger From wuwei23 at gmail.com Wed Dec 3 00:40:31 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 2 Dec 2008 21:40:31 -0800 (PST) Subject: Debugging a Python Program that Hangs References: Message-ID: On Dec 3, 2:19?am, Kevin D. Smith wrote: > I have a fairly large python program that, when a certain combination > of options is used, hangs. ?I have no idea where it is hanging, so > simply putting in print statements to locate the spot would be quite > difficult. ?Unfortunately, ctrl-C'ing the program doesn't print a > traceback either. ?Looking through the python debugger documentation, I > don't see how to run a python program and interactively stopping it > while it is running. ?Is there a way to stop within a running python > program to see where it is getting hung up? Hey Kevin, long time fan of your films! (I bet you get that a lot...) The trace module might help you identify where it's getting caught up: http://www.python.org/doc/2.5.2/lib/trace-cli.html From gherron at islandtraining.com Wed Dec 10 15:26:40 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 10 Dec 2008 12:26:40 -0800 Subject: How to pass out the result from iterated function In-Reply-To: References: Message-ID: <49402600.8040202@islandtraining.com> JD wrote: > I got a iterated function like this: > > def iterSomething(list): > has_something = False > for cell in list: > if something in cell: > has_something = True > output = something > if has_something: > iterSomething(output) > else: > final_out = outupt > > The problem is how can I read this final_out outside of the function. > I tried the global statement, it seems not work. Any idea? > Without examining the intent of your code, I'll suggest this: if has_something: return iterSomething(output) else: return output So either way, *something* is returned, and in the case of the recursive call, the innermost result is returned back up through all levels of the recursion. Is that what you wanted? Gary Herron From manu3d at gmail.com Tue Dec 16 11:25:59 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Tue, 16 Dec 2008 08:25:59 -0800 (PST) Subject: Bidirectional Networking References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <98a6c3cd-181c-43c9-805b-fb0689c69544@a26g2000prf.googlegroups.com> <29283382-3e26-492a-8612-9352f32c1c01@r15g2000prd.googlegroups.com> Message-ID: <60d40b0a-079c-4f87-a055-6d952526dfb3@i24g2000prf.googlegroups.com> Thanks everybody and in particular Gabriel and Bryan for their contributions to this thread. Very much useful information. Manu From steve at holdenweb.com Wed Dec 10 13:13:22 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 10 Dec 2008 13:13:22 -0500 Subject: get todays files In-Reply-To: <3090b59b-a0b2-4bfb-a08f-6d6accfb363a@k36g2000pri.googlegroups.com> References: <3090b59b-a0b2-4bfb-a08f-6d6accfb363a@k36g2000pri.googlegroups.com> Message-ID: Andrew D wrote: > On Dec 10, 5:55 pm, Steve Holden wrote: >> Andrew D wrote: >>> I have a script that will login to my ftp server and download all the >>> backup files, but I want it to only download the files that were >>> created today, e.g. if I ran the script today I want it to only fetch >>> files created today. >>> I am really not sure about how to do this, but it is quite important >>> to me, so all help is highly appreciated! >> IIRC there's an "ftpmirror" script in the Tools directory (if you're on >> Windows - Linux/Unix users have to download the source). I adapted it to >> several different purposes. >> > > Thanks Steve, > > I don't want to sound rude here, but I really want some code to add to > my script so that it will only download todays files. > That's OK. Maybe somebody's already got that code ready to go. I don't ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From rdmurray at bitdance.com Tue Dec 9 18:11:40 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Tue, 9 Dec 2008 18:11:40 -0500 (EST) Subject: Best way to report progress at fixed intervals In-Reply-To: References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> Message-ID: On Tue, 9 Dec 2008 at 13:27, Slaunger wrote: > On 9 Dec., 19:35, rdmur... at bitdance.com wrote: >> >> I felt like a little lunchtime challenge, so I wrote something that >> I think matches your spec, based on your sample code. ?This is not >> necessarily the best implementation, but I think it is simpler and >> clearer than yours. ?The biggest change is that the work is being >> done in the subthread, while the main thread does the monitoring. >> > Well, thank you for spending your lunch time break on my little > problem. > >> It would be fairly simple to enhance this so that you could pass >> arbitrary arguments in to the worker function, in addition to >> or instead of the loop counter. >> > Yes, I agree > >> ----------------------------------------------------------------------- >> """ >> Test module for testing generic ways of displaying progress >> information at regular intervals. >> """ >> import random >> import threading >> import time >> >> def work(i): >> ? ? ?""" >> ? ? ?Dummy process function, which takes a random time in the interval >> ? ? ?0.0-0.5 secs to execute >> ? ? ?""" >> ? ? ?print "Work step %d" % i >> ? ? ?time.sleep(0.5 * random.random()) >> >> class Monitor(object): >> ? ? ?""" >> ? ? ?This class creates an object that will execute a worker function >> ? ? ?in a loop and at regular intervals emit a progress report on >> ? ? ?how many times the function has been called. >> ? ? ?""" >> >> ? ? ?def dowork(self): >> ? ? ? ? ?""" >> ? ? ? ? ?Call the worker function in a loop, keeping track of how >> ? ? ? ? ?many times it was called in self.no >> ? ? ? ? ?""" >> ? ? ? ? ?for self.no in xrange(self.max_iter): >> ? ? ? ? ? ? ?self.func(self.no) >> >> ? ? ?def __call__(self, func, verbose=True, max_iter=20, progress_interval=1.0): > I had to look up the meaning of __call__, to grasp this, but I get > your methology >> ? ? ? ? ?""" >> ? ? ? ? ?Repeatedly call 'func', passing it the loop count, for max_iter >> ? ? ? ? ?iterations, and every progress_interval seconds report how >> ? ? ? ? ?many times the function has been called. >> ? ? ? ? ?""" >> ? ? ? ? ?# Not all of these need to be instance variables, but they might >> ? ? ? ? ?# as well be in case we want to reference them in an enhanced >> ? ? ? ? ?# dowork function. >> ? ? ? ? ?self.func = func >> ? ? ? ? ?self.verbose = verbose >> ? ? ? ? ?self.max_iter=max_iter >> ? ? ? ? ?self.progress_interval=progress_interval >> >> ? ? ? ? ?if self.verbose: >> ? ? ? ? ? ? ?print ("Work through all %d steps reporting progress every " >> ? ? ? ? ? ? ? ? ?"%3.1f secs...") % (self.max_iter, self.progress_interval) >> >> ? ? ? ? ?# Create a thread to run the loop, and start it going. >> ? ? ? ? ?worker = threading.Thread(target=self.dowork) >> ? ? ? ? ?worker.start() >> >> ? ? ? ? ?# Monitoring loop. >> ? ? ? ? ?loops = 0 >> ? ? ? ? ?# We're going to loop ten times per second using an integer count, >> ? ? ? ? ?# so multiply the seconds parameter by 10 to give it the same >> ? ? ? ? ?# magnitude. >> ? ? ? ? ?intint = int(self.progress_interval*10) > Is this not an unnecessary complication? >> ? ? ? ? ?# isAlive will be false after dowork returns >> ? ? ? ? ?while worker.isAlive(): >> ? ? ? ? ? ? ?loops += 1 >> ? ? ? ? ? ? ?# Wait 0.1 seconds between checks so that we aren't chewing >> ? ? ? ? ? ? ?# CPU in a spin loop. >> ? ? ? ? ? ? ?time.sleep(0.1) > Why not just call this with progress_interval directly? Because then the program make take up to progress_interval seconds to complete even after all the work is done. For a long running program and a short progress_interval that might not matter, so yes, that would be a reasonable simplification depending on your requirements. >> ? ? ? ? ? ? ?# when the modulus (second element of divmod tuple) is zero, >> ? ? ? ? ? ? ?# then we have hit a new progress_interval, so emit the report. > And then avoid this if expression? >> ? ? ? ? ? ? ?if not divmod(loops, intint)[1]: >> ? ? ? ? ? ? ? ? ?print "Processed %d of %d" % (self.no, self.max_iter) >> >> ? ? ? ? ?if verbose: >> ? ? ? ? ? ? ?print "Finished working through %d steps" % max_iter >> >> if __name__ == "__main__": >> ? ? ?#Create the monitor. >> ? ? ?monitor = Monitor() >> ? ? ?#Run the work function under monitoring. >> ? ? ?monitor(work) > I was unfamiliar with this notation, but now I understand it simply > invokes __call__. Thank you for showing me that! Yes, it is a very nice feature of python :) > OK. I agree this is a more elegant implementation, although I my mind, > I find it more natural if the reporting goes on in a subthread, but You could pretty easily rewrite it to put the reporter in the subthread, it was just more natural to _me_ to put the worker in the subthread, so that's how I coded it. Note, however, that if you were to write a GUI front end it might be important to put the worker in the background because on some OSes it is hard to update GUI windows from anything other than the main thread. (I ran into this in a Windows GUI ap I wrote using wxPython). > that is a matter of taste, I guess. Anyway: Thank you again for > spending your lunch break on this! No problem, it was fun. --RDM From clp at rebertia.com Mon Dec 29 04:50:07 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 29 Dec 2008 01:50:07 -0800 Subject: Get a list of functions in a file In-Reply-To: References: Message-ID: <47c890dc0812290150m1a1651bexaed7d59a9bf6911f@mail.gmail.com> On Sun, Dec 28, 2008 at 11:26 PM, member Basu wrote: > I'm putting some utility functions in a file and then building a simple > shell interface to them. Is their some way I can automatically get a list of > all the functions in the file? I could wrap them in a class and then use > attributes, but I'd rather leave them as simple functions. Assuming you've already imported the module as 'mod': func_names = [name for name in dir(mod) if callable(getattr(mod, name))] funcs = [getattr(mod, name) for name in dir(mod) if callable(getattr(mod, name))] Note that such lists will also include classes (as they too are callable). There are ways of excluding classes (and other objects that implement __call__), but it makes the code a bit more complicated. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From __peter__ at web.de Sun Dec 21 07:25:16 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 21 Dec 2008 13:25:16 +0100 Subject: Read an image from a URL and write it to the browser References: Message-ID: McCoy Fan wrote: > I want to do something simple: read an image from an image URL and > write the image to the browser in CGI style. > > I wrote a CGI script to do this (I'm new to Python) and got the > following error: > > "FancyURLopener instance has no attribute 'tempcache'" in method FancyURLopener.__del__ of > I have no idea what that error means and neither does Google. > > Any idea where I went wrong in the code below? > import urllib > > urlString = "http://www.google.com/google_logo.jpg" > imgStream = urllib.urlopen(urlString) > imgBuffer = imgStream.read() > imgStream.close() > print "Content-Type: image/jpeg" > print > print imgBuffer Your script runs without error here, but I can provoke the attribute error by passing an invalid proxies argument to urlopen(): $ python -c"import urllib; urllib.urlopen('whatever', proxies=42)" Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/urllib.py", line 75, in urlopen opener = FancyURLopener(proxies=proxies) File "/usr/lib/python2.5/urllib.py", line 609, in __init__ URLopener.__init__(self, *args, **kwargs) File "/usr/lib/python2.5/urllib.py", line 117, in __init__ assert hasattr(proxies, 'has_key'), "proxies must be a mapping" AssertionError: proxies must be a mapping Exception exceptions.AttributeError: "FancyURLopener instance has no attribute 'tempcache'" in > ignored Please post your complete traceback, Python version, and OS to allow for a more detailed diagnosis. You can also try to run your script with > imgStream = urllib.urlopen(urlString) changed to imgStream = urllib.urlopen(urlString, proxies={}) to bypass the code in which I suppose the failure to occur. Peter From pyn00b at gmail.com Tue Dec 9 00:36:59 2008 From: pyn00b at gmail.com (n00b) Date: Mon, 8 Dec 2008 21:36:59 -0800 (PST) Subject: fuzzy or boolean text search Message-ID: <104335ff-e507-4429-9ad3-baecb63da8b3@k36g2000yqe.googlegroups.com> hi, i'm looking for advice/suggestions for text search, preferably with boolean or even fuzzy capabilities, and for use with mysql innodb tables. asking too much :) ??? thx a bunch From febaen at gmail.com Fri Dec 12 07:58:36 2008 From: febaen at gmail.com (feba) Date: Fri, 12 Dec 2008 04:58:36 -0800 (PST) Subject: (Very Newbie) Problems defining a variable References: <49425146$0$8495$426a74cc@news.free.fr> <11c53a4a-de1e-4bee-ad60-a05befb6cbf4@a12g2000yqm.googlegroups.com> <7cb69ff5-9034-41cc-b667-d69329707b18@d36g2000prf.googlegroups.com> Message-ID: Actually, I have gedit set to four spaces per tab. I have no reason why it's showing up that large on copy/paste, but the file itself is fine. Thanks for the advice Chris, Stephen, I can definitely see how those are both far better ways of doing it. I have it as: #!/usr/bin/python #Py3k, UTF-8 bank = int(input("How much money is in your account?\n>>")) if bank <=0: print("You need a postive amount to gain interest.") quit() target = int(input("How much money would you like to earn each year? \n>>")) interest = 0 i = 0 while interest < target: #determine the interest rate to use if bank >= 100000: rate = 0.0173 elif bank >= 50000: rate = 0.0149 elif bank >= 25000: rate = 0.0124 elif bank >= 10000: rate = 0.0085 else: rate = 0.0060 #Now that we know what interest rate to use, apply it... lastbank = bank #To calculate interest... bank += (bank * rate) #Update earnings... interest = bank - lastbank #And figure out how much interest is made! i += 1 #So we can see which year a calculation represents print("Year %s, at %s rate: %s paid, %s in bank." % (i, rate, interest, bank)) now it checks to make sure the account is positive before moving on, in addition to using your recommendations on readability and efficiency in getting the rate From pete.forman at westerngeco.com Tue Dec 16 03:53:54 2008 From: pete.forman at westerngeco.com (Pete Forman) Date: Tue, 16 Dec 2008 08:53:54 +0000 Subject: alt.possessive.its.has.no.apostrophe References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> Message-ID: Steve Holden writes: > Ben Finney wrote: >> James Stroud writes: >> >>> Ben Finney wrote: >>>> James Stroud writes: >>>> >>>>> Yes. I think it was the British who decided that the apostrophe >>>>> rule for "it" would be reversed from normal usage relative to >>>>> just about every other noun. >> >> It also seems an indefensible claim to say that anyone "decided" it >> would be that way, especially "the British". >> > It's our language, dammit! Ours, ours, ours! > > This decision was actually taken at a meeting of the Society of > British pedants on November 23, 1786. This led to a schism between > the British and the newly-independent Americans, who responded by > taking the "u" out of colour, valour, and aluminium. I'd thought that the main schism was triggered by a tax on tea but it turns out that it was due to an apostrophe after t. ;-) -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- the opinion of Schlumberger or http://petef.22web.net -./\.- WesternGeco. From roy at panix.com Wed Dec 31 10:23:05 2008 From: roy at panix.com (Roy Smith) Date: Wed, 31 Dec 2008 10:23:05 -0500 Subject: change only the nth occurrence of a pattern in a string References: <0scs26-7a5.ln1@rama.fbx.proxad.net> Message-ID: In article <0scs26-7a5.ln1 at rama.fbx.proxad.net>, TP wrote: > Hi everybody, > > I would like to change only the nth occurence of a pattern in a string. It's a little ugly, but the following looks like it works. The gist is to split the string on your pattern, then re-join the pieces using the original delimiter everywhere except for the n'th splice. Split() is a wonderful tool. I'm a hard-core regex geek, but I find that most things I might have written a big hairy regex for are easier solved by doing split() and then attacking the pieces. There may be some fencepost errors here. I got the basics working, and left the details as an exercise for the reader :-) This version assumes the pattern is a literal string. If it's really a regex, you'll need to put the pattern in parens when you call split(); this will return the exact text matched each time as elements of the list. And then your post-processing gets a little more complicated, but nothing that's too bad. This does a couple of passes over the data, but at least all the operations are O(n), so the whole thing is O(n). #!/usr/bin/python import re v = "coucoucoucou" pattern = "o" n = 2 parts = re.split(pattern, v) print parts first = parts[:n] last = parts[n:] print first print last j1 = pattern.join(first) j2 = pattern.join(last) print j1 print j2 print "i".join([j1, j2]) print v From fakeaddress at nowhere.org Wed Dec 3 00:53:18 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 02 Dec 2008 21:53:18 -0800 Subject: Obama's Birth Certificate - Demand that US presidential electors investigate Obama's eligibility In-Reply-To: References: Message-ID: <89pZk.9151$be.4743@nlpi061.nbdc.sbc.com> girbarobert at yahoo.com wrote: > This message is not about the meaningless computer printout called More importantly, it's not about Python. I'm setting follow-ups to talk.politics. > "Certification of Live Birth" that Obama propaganda machine calls his > "Birth Certificate". The American people are still waiting for a copy > of Obama's original birth certificate that includes all his birth > information. The document is what Hawaii provides as certified copy of birth record. It contains all the information the federal government requires to prove citizenship by birth, and it shows that Barack Hussein Obama was born 04 August 1961 in Honolulu. See: http://www.factcheck.org/elections-2008/born_in_the_usa.html > Remind your US presidential electors of their constitutional duty to > investigate Obama's natural-born citizen status. > > No federal agency like FBI or Secret Service, no Hawaii bureaucrats > have ever investigated Obama's birth in Hawaii. Many illegal aliens in > USA have official "birth certificates" issued by state bureaucrats on > the basis of falsified birth records. Janice Okubo of Hawaii's Department of Health confirmed that the state has Obama?s original birth certificate on record: http://hawaii.gov/health/about/pr/2008/08-93.pdf [...] > Remind your US presidential electors that they have the legal standing > and constitutional duty to investigate Obama's birth in Hawaii by > demanding that Obama provide all his original birth records, and a > federal agency like FBI or Secret Service fully investigate them. That's not what the Constitution says. US Constitution, Article IV, Section 1: "Full Faith and Credit shall be given in each State to the public Acts, Records, and judicial Proceedings of every other State. And the Congress may by general Laws prescribe the Manner in which such Acts, Records and Proceedings shall be proved, and the Effect thereof." These haters seek to make Obama prove his records in ways others have not had to, and beyond any manner prescribed by Congress within its constitutional authority. -- --Bryan From __peter__ at web.de Fri Dec 19 11:35:11 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2008 17:35:11 +0100 Subject: best way to code References: Message-ID: eric wrote: > hi, > > I need to find a "good" design pattern to instanciate, and add > specific code all in one. Let me explain it : > > I need to define "some" code, better be in a class, something like > > class LinkA(object): > def mystuff(self): > > > class LinkB(object): > def mystuff(self): > > > > AND I need an instance of this class > { "stuff A": LinkA() > "stuff B": LinkB() > } > > This kind of code "would" be fine, I mean, the result effect in memory > is fine for me. > But I don't like the way I have to > 1/ give a useless name to LinkA, linkB (there can be hundreds of names > like that) > 2/ I have to write it down two times (and that's one time too much) > > any ideas ? > > something like > [ > new object(): > def mystuff(self): > > , > new object(): > def mystuff(self): > > ] > > would be really perfect (but I know it does not work, or at least, I > don't know how to make it work) > > In fact, I would like to define a class, and an instance in a single > statement >>> class Register: ... def __init__(self): ... self.items = [] ... def __call__(self, method): ... class Link(object): ... mystuff = method ... self.items.append(Link()) ... >>> register = Register() >>> @register ... def mystuff(self): print "first" ... >>> @register ... def mystuff(self): print "second" ... >>> for item in register.items: ... item.mystuff() ... first second Peter From google at mrabarnett.plus.com Sat Dec 13 14:20:54 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 13 Dec 2008 19:20:54 +0000 Subject: [OT] stable algorithm with complexity O(n) In-Reply-To: <6qidmbFc4qduU1@mid.uni-berlin.de> References: <6qidmbFc4qduU1@mid.uni-berlin.de> Message-ID: <49440B16.8070000@mrabarnett.plus.com> Diez B. Roggisch wrote: > David Hl??ik schrieb: >> Hi guys, >> >> i am really sorry for making offtopic, hope you will not kill me, but >> this is for me life important problem which needs to be solved within >> next 12 hours.. >> >> I have to create stable algorithm for sorting n numbers from interval >> [1,n^2] with time complexity O(n) . >> >> Can someone please give me a hint. Would be very very thankful! > > Unless I grossly miss out on something in computer science 101, the > lower bound for sorting is O(n * log_2 n). Which makes your task > impossible, unless there is something to be assumed about the > distribution of numbers in your sequence. > > Who has given you that assignment - a professor? Or some friend who's > playing tricks on you? > I'm assuming that the numbers are integers. I can think of an O(n) algorithm for this particular problem provided that n isn't huge, but if it's your assignment then it's up to you to discover it. From Scott.Daniels at Acm.Org Wed Dec 17 18:12:11 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 17 Dec 2008 15:12:11 -0800 Subject: The rule of literal string In-Reply-To: References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> Message-ID: <_PmdnU59w62vGtTUnZ2dnUVZ_hSdnZ2d@pdx.net> Li Han wrote: > But what repr() do remain a black hole! > Han > Try: print repr(repr("'")) that might enlighten you. From delmararlee at gmail.com Tue Dec 9 09:17:09 2008 From: delmararlee at gmail.com (delmararlee at gmail.com) Date: Tue, 9 Dec 2008 06:17:09 -0800 (PST) Subject: our real femme Message-ID: <7677bccb-03df-4126-ab2d-4b2ed0dd33fd@k24g2000pri.googlegroups.com> Some of our real femme http://wesexy.byethost8.com/ From __peter__ at web.de Sun Dec 14 10:49:06 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 14 Dec 2008 16:49:06 +0100 Subject: 1 or 1/0 doesn't raise an exception References: <49446E39.6020807@tim.thechases.com> Message-ID: Grant Edwards wrote: > Short circuit evaluation of booleans is very common (and has > been for decades), so I don't know why people would expect > something else. Visual Basic ;) From kyosohma at gmail.com Tue Dec 30 13:44:33 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 30 Dec 2008 10:44:33 -0800 (PST) Subject: wxPython.button.disabled still catching clicks References: <8cb6da6a-7df4-4cce-a28e-385448a25b26@w39g2000prb.googlegroups.com> <1ff2aad7-29a1-48cd-b3de-29fab443aa3e@u18g2000pro.googlegroups.com> <0e9a5ab7-8078-4d12-adb2-aaf92a78b007@s9g2000prm.googlegroups.com> <007bab05-6451-48c8-94bc-a34631795e32@v5g2000prm.googlegroups.com> Message-ID: On Dec 30, 3:04?am, mynthon wrote: > On Dec 23, 6:12?pm, Mike Driscoll wrote: > > > > > On Dec 23, 7:27?am,mynthon wrote: > > > > On Dec 23, 11:58?am, Aaron Brady wrote: > > > > > On Dec 23, 4:50?am,mynthon wrote: > > > > > > Hello! (sorry for my english) > > > > > > I have a problem with buttons in wxPython. When button is disabled > > > > > (by .Disable() or .Enable(False)) it is grayed out but still receive > > > > > clicks. > > > > > > Eg. i have button that disable itself, runs long action and enable > > > > > itself: > > > > > > def onClick(self, evt): > > > > > ? ? self.btn.Enable(False) > > > > > ? ? for i in range (1000): > > > > > ? ? ? ? print i > > > > > ? ? self.btn.Enable(True) > > > > > > when for loop is running button is greyed out and when i click on it > > > > > nothing happens but when loop ends another one is started because > > > > > button "remebered" thad i click on it when was diabled. My only idea > > > > > is to reposition button outside frame instead of disabling it but this > > > > > solution is...not good. > > > > > > thanks for any help. Ive searched groups, google and it looks that > > > > > only i have this problem :) > > > > > No, it is very common. ?During your for loop, the loop is dominating > > > > the process completely. ?Events are just building up in the app's > > > > message queue, and don't get handled until after you yield on control. > > > > > If you need to run a long task, look into threading, the OnIdle > > > > method, the 'multiprocessing' module, or pump messages during your > > > > long task. > > > > ok, maybe someone will need it. I dont know how it works because i > > > didnt have time to read docs and i cannot explain everything. I used > > > google and wxPython demo (in tree: wxpython overview / process and > > > events / process) > > > > class leftPanel(wx.Panel): > > > ? ? def __init__(self, parent, id): > > > ? ? ? ? wx.Panel.__init__(self, parent, id, style=wx.BORDER_SUNKEN) > > > > ? ? ? ? # here you have to define new process, IDLE event, and > > > onPRocessEnd event > > > ? ? ? ? self.process = None > > > ? ? ? ? self.GetParent().Bind(wx.EVT_IDLE, self.onIdle) > > > ? ? ? ? self.Bind(wx.EVT_END_PROCESS, self.onProcessEnd) > > > > ? ? ? ? # create button and bind event to it > > > ? ? ? ? self.runScriptBtn = wx.Button(self, -1, 'RUN ME!', (10,220)) > > > ? ? ? ? self.runScriptBtn.Bind(wx.EVT_BUTTON, self.onClick, > > > self.runScriptBtn) > > > > ? ? def onClick(self, evt): > > > ? ? ? ? # disable button > > > ? ? ? ? self.runScriptBtn.Enable(False) > > > > ? ? ? ? # here you have to enter command to run > > > ? ? ? ? # previusly i heve here exec('pythonmyScript.py') > > > ? ? ? ? # but now it will be a subprocess > > > ? ? ? ? cmd = 'pythonxxx1.py' > > > > ? ? ? ? #create new process > > > ? ? ? ? self.process = wx.Process(self) > > > > ? ? ? ? # dont know what it is for > > > ? ? ? ? self.process.Redirect() > > > > ? ? ? ? # execute cmd command > > > ? ? ? ? pid = wx.Execute(cmd, wx.EXEC_ASYNC, self.process) > > > > ? ? def onIdle(self, evt): > > > ? ? ? ? # beacuse this method is called only when app enters idle mode > > > ? ? ? ? # the line below is nedded to "simulate" entering idle mode > > > ? ? ? ? # dont know how it works but it works > > > ? ? ? ? evt.RequestMore(True) > > > > ? ? ? ? # here is some code to catch subprocess output > > > ? ? ? ? if self.process is not None: > > > ? ? ? ? ? ? stream = self.process.GetInputStream() > > > ? ? ? ? ? ? if stream.CanRead(): > > > ? ? ? ? ? ? ? ? text = stream.read() > > > ? ? ? ? ? ? ? ? print text > > > > ? ? def onProcessEnd(self, evt): > > > ? ? ? ? # here is some code to catch subprocess output > > > ? ? ? ? # when it is destroyed > > > ? ? ? ? stream = self.process.GetInputStream() > > > ? ? ? ? if stream.CanRead(): > > > ? ? ? ? ? ? text = stream.read() > > > ? ? ? ? ? ? print text > > > > ? ? ? ? # dont know it is necessary > > > ? ? ? ? self.process.CloseOutput() > > > > ? ? ? ? # remove (clear) process object > > > ? ? ? ? self.process.Destroy() > > > ? ? ? ? self.process = None > > > > ? ? ? ? # show button again > > > ? ? ? ? self.runScriptBtn.Enable() > > > I'm pretty sure there's a better way to do this. If you disable the > > button and click on it, you'll notice that it isn't firing events, so > > something else is going on here. It seems like the wx.Frame or > > wx.Application is queuing the mouse button clicks or something. I > > would post to the wxPython mailing list:http://wxpython.org/maillist.php > > > They'll be better able to address this and they'll probably have a > > simpler solution too. > > > Mike > > I changed it. Now i'm running separate thread instead of process. > First example at:http://wiki.wxpython.org/LongRunningTasks I should have posted that link when I posted originally. Oh well. Glad you found a workaround. Mike From bockman at virgilio.it Wed Dec 31 05:39:32 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: Wed, 31 Dec 2008 11:39:32 +0100 Subject: select.select and socket.setblocking In-Reply-To: <495b34d8$0$11387$5fc30a8@news.tiscali.it> References: <495a661d$0$11384$5fc30a8@news.tiscali.it> <495b34d8$0$11387$5fc30a8@news.tiscali.it> Message-ID: <495b4be5$0$11379$5fc30a8@news.tiscali.it> Francesco Bochicchio ha scritto: >> >> No, in blocking mode it will wait to receive _some_ data (1 or >> more bytes). The "requested" amount is strictly an upper >> limit: recv won't return more than the requested number of >> bytes, but it might return less. >> > > Uhm. In my experience, with TCP protocol recv only returned less than > the required bytes if the remote end disconnects. I always check the > returned value of recv and signal an error if the read bytes are less > than the expected ones, but this error is never occurred (and its about > 20 years that I use sockets in various languages and various flavor of > unix and occasionally on windows. Maybe have always been lucky ? :-) > BTW, this is not a rethorical or ironic question... my applications mostly run on LANs or dedicated WANs so maybe they never experienced the kind of network congestion that could cause recv to return less than the expected amount of bytes ... but then, IIRC TCP guarantees that the packet is fully received by hand-shaking at transport level between sender and receiver. Ad once the packet is fully in the receiver buffer, why should recv choose to give back to the application only a piece of it? Ciao ----- FB From kylefranki at gmail.com Wed Dec 24 16:32:10 2008 From: kylefranki at gmail.com (kylefranki at gmail.com) Date: Wed, 24 Dec 2008 13:32:10 -0800 (PST) Subject: Lesbians cuple USA Message-ID: <0d1af4d7-9987-4d62-a3a7-f9810144951e@c36g2000prc.googlegroups.com> Lesbi cuple want sex right now http://lesbicouple.pornblink.com/ From prologic at shortcircuit.net.au Thu Dec 18 19:41:37 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Dec 2008 10:41:37 +1000 Subject: Factoring Polynomials In-Reply-To: References: Message-ID: On Fri, Dec 19, 2008 at 10:11 AM, Gabriel Genellina wrote: > En Thu, 18 Dec 2008 17:37:35 -0200, escribi?: > >> I am trying to write a simple application to factor polynomials. I >> wrote (simple) raw_input lines to collect the a, b, and c values from >> the user, but I dont know how to implement the quadratic equation >> >> x = (-b +or- (b^2 - 4ac)^1/2) / 2a Why is this so hard ? This is simple simple expression. Reading through the Python tutorial and reading up on how to define functions is all you need! :) Here goes: >>> def f(a, b, c): ... x = (-1 * b) + ((b**2 - (4 * a * c)) / (2 * a)) ... return (-1 * x), x ... >>> f(1, 2, 3) (6, -6) >>> cheers James From aspersieman at gmail.com Tue Dec 9 10:45:32 2008 From: aspersieman at gmail.com (aspersieman) Date: Tue, 09 Dec 2008 17:45:32 +0200 Subject: 'pretty print' for built in types In-Reply-To: <051e3a97-b9bc-4a67-8896-93628ca19f59@r15g2000prd.googlegroups.com> References: <051e3a97-b9bc-4a67-8896-93628ca19f59@r15g2000prd.googlegroups.com> Message-ID: On Tue, 09 Dec 2008 17:31:41 +0200, Robert Dailey wrote: > > Is there a built in way to 'pretty print' a dict, list, and tuple > (Amongst other types)? Dicts probably print the ugliest of them all, > and it would be nice to see a way to print them in a readable way. I > can come up with my own function to do this, but I don't want to do > this if I don't have to. For lists use 'join'. >>> lista = ['a', 'b', 'c', 4] >>> ','.join(lista) >>> a,b,c,4 For more info google 'python join' or see [1] Regards Nicol [1] http://docs.python.org/library/stdtypes.html#string-methods -- Christopher Columbus was, after all, a super intelligent hypersquirrel from the planet Klepton. How else could he have known where to find america? From steve at holdenweb.com Tue Dec 16 13:42:14 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 16 Dec 2008 13:42:14 -0500 Subject: Python Dictionary Algorithm Question In-Reply-To: <3ca641b40812160951h3a13e69am291afb02965451a7@mail.gmail.com> References: <3ca641b40812160951h3a13e69am291afb02965451a7@mail.gmail.com> Message-ID: <4947F686.2040904@holdenweb.com> Brigette Hodson wrote: > Hello! I am in a beginning algorithms class this semester and I am > working on a presentation. I want to discuss in some detail the > algorithm python uses to determine the hash function for python > dictionaries. Does anyone know what this algorithm is? Or where I can go > to find information on it? > > Thanks. > Look in http://svn.python.org/view/python/tags/r26/Objects/ for dictnotes.txt and dictobject.c. Good luck with the class! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steve at REMOVE-THIS-cybersource.com.au Sun Dec 28 02:28:55 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Dec 2008 07:28:55 GMT Subject: math module for Decimals References: <01671a9e$0$6988$c3e8da3@news.astraweb.com> Message-ID: <016721cc$0$6988$c3e8da3@news.astraweb.com> On Sun, 28 Dec 2008 06:58:18 +0000, Steven D'Aprano wrote: > def make_decimal(f, precision=16): > # choose how many decimal places you want to keep return > Decimal.from_float(f, precision) Ah crap, I forgot that from_float() has been left out of the decimal API. That's very annoying. Sorry about that. -- Steven From ivan.illarionov at gmail.com Wed Dec 24 12:00:36 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Wed, 24 Dec 2008 09:00:36 -0800 (PST) Subject: Custom C Exception Subclasses References: <41f291ff-d7bd-4334-8689-636e95524cdc@b38g2000prf.googlegroups.com> Message-ID: On Dec 24, 6:42?pm, Ross wrote: > For a project that I am doing, it would be useful to have an exception > class that stores some additional data along with the message. > However, I want to be able to store a couple pointers to C++ classes, > so I can't just use an exception created with PyExc_NewException. ?If > I were to subclass the built-in Exception type, I would need to have > access to the PyExc_ExceptionObject, but the headers only give > PyExc_Exception, the type object. ?This seems like a rather > straightforward task, but I can't seem to find any documentation for > it. ?Does anyone know how to do this? ?Thanks! When you raise an exception in C++ you can set it to ANY Python object via PyErr_SetObject and that object could store pointers to C++ classes. Ivan From ferdinandsousa at gmail.com Wed Dec 17 07:11:46 2008 From: ferdinandsousa at gmail.com (Ferdinand Sousa) Date: Wed, 17 Dec 2008 17:41:46 +0530 Subject: Transferring a file over sockets Message-ID: I am using sockets to transfer a file over LAN. There are 2 scripts, the server opens a listens for connection and the client is run on another machine. I always make sure the server is run first. The strange thing is that if the the server script is double-clicked and executed (run in a console with title %Python path%python.exe) the output file saved on the server is truncated. It works just fine if you open the server script in IDLE and then run it. The client script can be run in either way, it still works. You could try using any arbitrary file to test this behaviour after changing the file name in both the scripts. ========================================================== # file receiver # work in progress import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) HOST = '192.168.1.17' PORT = 31400 s.bind((HOST, PORT)) s.listen(3) conn, addr = s.accept() print 'conn at address',addr conn.send('READY') f = open('C:\\Documents and Settings\\USER\\Desktop\\test.pdf','wb') fsize=int(conn.recv(8)) print 'File size',fsize f.write(conn.recv(fsize)) f.close() conn.close() s.close() raw_input('Press any key to exit') =========================================================== # file sender !!! # Work in progress import socket, os from stat import ST_SIZE HOST = '192.168.1.17' PORT = 31400 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST,PORT)) if s.recv(5)!='READY': raw_input('Unable to connect \n\n Press any key to exit ...') s.close() exit() f=open('C:\\Documents and Settings\\USER\\Desktop\\t.pdf', 'rb') fsize=os.stat(f.name)[ST_SIZE] s.send(str(fsize)) s.send(f.read()) s.close() f.close() =========================================================== Thanks for reading!! Best regards, Ferdi -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Dec 19 12:07:50 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 19 Dec 2008 12:07:50 -0500 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <6r219cFfc8ovU1@mid.individual.net> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> Message-ID: Thomas Heller wrote: > Mark Summerfield schrieb: >> Just a follow-up to say that the book has now been published in the >> U.S. >> It is now in stock at InformIT, and should reach other stores, e.g., >> Amazon, in a week or so. >> >> Also, the introduction, the first few pages of the first chapter, the >> whole of chapter 12 (regular expressions), and the index are now >> available for free download in a PDF from here: >> http://www.informit.com/store/product.aspx?isbn=0137129297 > > Question from a non-native english speaker: is this now valid english? > > "One of Python?s great strengths" > ^ > "and also teaches Python?s functional programming features" > ^ > "The book?s approach is wholly practical" > ^ It always has been valid English. The apostrophe is only omitted from personal pronouns (hers, its, and so on). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From digitig at gmail.com Fri Dec 12 06:24:56 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 12 Dec 2008 11:24:56 +0000 Subject: Removing None objects from a sequence In-Reply-To: <1be78d220812120315y70688a4do455bdf41d7e53b03@mail.gmail.com> References: <1be78d220812120315y70688a4do455bdf41d7e53b03@mail.gmail.com> Message-ID: 2008/12/12 Filip Gruszczy?ski : > I don't mean memory, but space in code ;-) Trying to save printer paper for your listings, then? -- Tim Rowe From gabriel.rossetti at arimaz.com Tue Dec 9 12:31:37 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Tue, 09 Dec 2008 18:31:37 +0100 Subject: memory leak? Message-ID: <493EAB79.6070805@arimaz.com> I have been debugging a distributed application for about 2 days that has a memory leak. My app is a Twisted app, so I thought that maybe it was on the twisted side, I finally isolated it to no being a Twisted problem but a Python problem. The problem comes from the code that uses wxPython and pySerial, these each run in a different process. I wrote test programs, one "pure" wxPython, one "pure" pySerial and let them run. The number of objects in the wxPython code doubles in about an hour, the pySerial code doubles about every 10 minutes. I think there is something wrong with the GC/memory management or C lib. The wxPython lib is big, so it may have bugs, but pySerial is small and pure python (no C/C++ directly, event thought it uses os.open/close & termios that themselves use C (unless I mistaking)) and I reviewed it's code and I see nothing that could cause this. I ran these tests on linux 2.6 (ubuntu 8.04) using python 2.5.2. I used the "ps" command to see the memory usage and also a recipe that I found that counts the number of objects. I attached the pyserial, wxPython code & the recipe. To test them just run each example and run "ps waux | grep python" once in a while, or send the process a SIGUSR1 and it will print in the terminal the object count. The wxCode has a refresh problem, if you use the SIGUSR1/object count method you have to right click on the taskbar icon to have it show up in the terminal. I hope I wrong and the problem is elsewhere though. Thank you very much, Gabriel -------------- next part -------------- A non-text attachment was scrubbed... Name: debug_utils.py Type: text/x-python Size: 1431 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: pyserial_meme_leak_test.py Type: text/x-python Size: 627 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: wxPythonTaskBarTest3.py Type: text/x-python Size: 4487 bytes Desc: not available URL: From steven at REMOVE.THIS.cybersource.com.au Sun Dec 7 22:39:09 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 08 Dec 2008 03:39:09 GMT Subject: Rich Comparisons Gotcha References: Message-ID: On Sun, 07 Dec 2008 16:23:59 +0000, Rasmus Fogh wrote: > Just to keep you from shooting at straw men: > > I would have liked it to be part of the design contract (a convention, > if you like) that > 1) bool(x == y) should return a boolean and never throw an error Can't be done without making bool a "magic function". If x==y raises an exception, bool() won't even be called. The only way around that would be for the Python compiler to recognise bool(x=y) and perform special magic. What if you did this? trueorfalse = bool # I don't like George Boole trueoffalse( [x][0].__class__.__getattr__('__dict__')['__eq__'](y) ) Should that have special magic performed too? Just how much work must the compiler put in to special-casing bool? > 2) x == x return True Which goes against the IEEE 754 floating-point standard. http://grouper.ieee.org/groups/754/ Python used to optimize x==x and always return True. This was removed because it caused problems. > I do *not* say that bool(x) should never throw an error. I do *not* say > that Python should guess a return value if an __eq__ function throws an > error, But to get what you want, the above is implied. I suppose, just barely, that you could avoid making bool() magic and just make if magic. When the compiler sees "if expr": it could swallow all exceptions inside expr and force it to evaluate to True or False. (How? By guessing? Randomly?) This would cause many problems, but it could be done, and much easier than ensuring that bool(x) always succeeds. > only that it should have been considered a bug, or at least bad > form, for __eq__ functions to do so. It's certainly *unusual* for comparisons to return non-bools, but it's not bad form. > What might be a sensible behaviour (unlike your proposed wrapper) What do you dislike about my wrapper class? Perhaps it is fixable. > would be the following: > > def eq(x, y): > if x is y: > return True I've already mentioned NaNs. Sentinel values also sometimes need to compare not equal with themselves. Forcing them to compare equal will cause breakage. > else: > try: > return (x == y) > except Exception: > return False Why False? Why not True? If an error occurs inside __eq__, how do you know that the correct result was False? class Broken(object): def __eq__(self, other): return Treu # oops, raises NameError -- Steven From hamish at valvesoftware.com Wed Dec 31 15:35:20 2008 From: hamish at valvesoftware.com (Hamish McKenzie) Date: Wed, 31 Dec 2008 12:35:20 -0800 Subject: type conversion In-Reply-To: <613a20bf-6e5a-435e-9a83-36766e12f0ab@k8g2000yqn.googlegroups.com> References: <4b7188db-63b2-4ac5-80cb-d1326ca3694a@q26g2000prq.googlegroups.com> <613a20bf-6e5a-435e-9a83-36766e12f0ab@k8g2000yqn.googlegroups.com> Message-ID: sometimes I want to be able to initialize an instance with a variety of different data types. as an obvious example I might want to initialize a 4x4 matrix with either 16 floats, a list/tuple or 16 floats, another matrix or a quaternion. is there any other way to do it other than putting case statements in the __init__ method of the class, or having a Matrix.FromQuaternion( quat )? thx From george.sakkis at gmail.com Tue Dec 2 12:33:00 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 2 Dec 2008 09:33:00 -0800 (PST) Subject: Scanner class References: <737a0550-0b92-4f65-829e-953882d74419@y18g2000yqn.googlegroups.com> Message-ID: <5d73aeb2-a4f1-4dd4-9c16-67db39df9e0c@u14g2000yqg.googlegroups.com> On Dec 1, 5:42?pm, Arnaud Delobelle wrote: > George Sakkis writes: > > Is there any stdlib or (more likely) 3rd party module that provides a > > similar functionality to the java.util.Scanner class [1] ? If not, > > would there be any interest in porting it (with a more Pythonic API of > > course) or are there better alternatives ? > > > George > > > [1]http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html > > Have you looked at: > > >>> import re > >>> re.Scanner > > > > Last time I checked it was undocumented though, although I vaguely > recall a Cookbook recipe. ?Ah here it is: > > http://code.activestate.com/recipes/457664/ Thanks, didn't know about it. I also found Plex [1] which seems more powerful. George [1] http://www.cosc.canterbury.ac.nz/greg.ewing/python/Plex/version/doc/index.html From rhf22 at mole.bio.cam.ac.uk Sat Dec 6 11:42:54 2008 From: rhf22 at mole.bio.cam.ac.uk (Rasmus Fogh) Date: Sat, 6 Dec 2008 16:42:54 +0000 (GMT) Subject: Rich Comparisons Gotcha Message-ID: Dear All, For the first time I have come across a Python feature that seems completely wrong. After the introduction of rich comparisons, equality comparison does not have to return a truth value, and may indeed return nothing at all and throw an error instead. As a result, code like if foo == bar: or foo in alist cannot be relied on to work. This is clearly no accident. According to the documentation all comparison operators are allowed to return non-booleans, or to throw errors. There is explicitly no guarantee that x == x is True. Personally I would like to get these !@#$%&* misfeatures removed, and constrain the __eq__ function to always return a truth value. That is clearly not likely to happen. Unless I have misunderstood something, could somebody explain to me 1) Why was this introduced? I can understand relaxing the restrictions on '<', '<=' etc. - after all you cannot define an ordering for all types of object. But surely you can define an equal/unequal classification for all types of object, if you want to? Is it just the numpy people wanting to type 'a == b' instead of 'equals(a,b)', or is there a better reason? 2) If I want to write generic code, can I somehow work around the fact that if foo == bar: or foo in alist does not work for arbitrary objects? Yours, Rasmus Some details: CCPN has a table display class that maintains a list of arbitrary objects, one per line in the table. The table class is completely generic, and subclassed for individual cases. It contains the code: if foo in tbllist: ... else: ... tbllist.append(foo) ... One day the 'if' statement gave this rather obscure error: "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()" A subclass had used objects passed in from some third party code, and as it turned out foo happened to be a tuple containing a tuple containing a numpy array. Some more precise tests gave the following: # Python 2.5.2 (r252:60911, Jul 31 2008, 17:31:22) # [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 # set up import numpy a = float('NaN') b = float('NaN') ll = [a,b] c = numpy.zeros((2,3)) d = numpy.zeros((2,3)) mm = [c,d] # try NaN print (a == a) # gives False print (a is a) # gives True print (a == b) # gives False print (a is b) # gives False print (a in ll) # gives True print (b in ll) # gives True print (ll.index(a)) # gives 0 print (ll.index(b)) # gives 1 # try numpy array print (c is c) # gives True print (c is d) # gives False print (c in mm) # gives True print (mm.index(c)) # 0 print (c == c) # gives [[ True True True][ True True True]] print (c == d) # gives [[ True True True][ True True True]] print (bool(1 == c)) # raises error - see below print (d in mm) # raises error - see below print (mm.index(d)) # raises error - see below print (c in ll) # raises error - see below print (ll.index(c)) # raises error - see below The error was the same in each case: "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()" --------------------------------------------------------------------------- Dr. Rasmus H. Fogh Email: r.h.fogh at bioc.cam.ac.uk Dept. of Biochemistry, University of Cambridge, 80 Tennis Court Road, Cambridge CB2 1GA, UK. FAX (01223)766002 From nad at acm.org Tue Dec 30 14:13:47 2008 From: nad at acm.org (Ned Deily) Date: Tue, 30 Dec 2008 11:13:47 -0800 Subject: duck typing at will References: <6e1bfdea0812301042x70ab57capf99ce73d364d54db@mail.gmail.com> Message-ID: In article <6e1bfdea0812301042x70ab57capf99ce73d364d54db at mail.gmail.com>, "Jose Mora" wrote: >[...] > I mean, some tasks are rather boring in python when compared with php, > for example, let's imagine we have a dictionary that contains > dictionaries that contain the times that a key appears. We, or at > least I, would like to write something as short as: > > dict[k1][k2] += 1 > > However we will have to do a longer code (this is the smallest code I > could come up with): > > dict = {} > if not k1 in dict: > dict[k1] = {} > if not k2 in dict[k1]: > dict[k1][k2] = 0 > dict[k1][k2] += 1 How about one line plus an import? $ python2.5 Python 2.5.3c1 (release25-maint, Dec 17 2008, 21:50:37) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from collections import defaultdict >>> dic = defaultdict(lambda : defaultdict(int)) >>> dic["spam"]["eggs"] += 1 >>> dic[42][3] += 1 >>> dic[42][3] += 1 >>> dic[42][3] 2 >>> dic defaultdict( at 0x661f0>, {42: defaultdict(, {3: 2}), 'spam': defaultdict(, {'eggs': 1})}) -- Ned Deily, nad at acm.org From gagsl-py2 at yahoo.com.ar Mon Dec 8 02:49:10 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Dec 2008 05:49:10 -0200 Subject: mod_python and files directory References: <200812061326.40226.metebilgin48@gmail.com> Message-ID: En Sat, 06 Dec 2008 09:26:40 -0200, mete escribi?: > but i want to take it somewhere else...i want to it work some other path > in > other system. os.path.dirname(os.path.abspath(__file__)) returns the directory where the current file resides. Execute it early in your code. -- Gabriel Genellina From google at mrabarnett.plus.com Wed Dec 24 13:00:26 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 24 Dec 2008 18:00:26 +0000 Subject: How to change a generator ? In-Reply-To: References: <7F0503CD69378F49BE0DC30661C6CCF6024946E6@enbmail01.lsi.com> <49526B7E.20904@mrabarnett.plus.com> Message-ID: <495278BA.7040301@mrabarnett.plus.com> Gabriel Genellina wrote: > En Wed, 24 Dec 2008 15:03:58 -0200, MRAB > escribi?: > >>> I have a generator whose aim is to returns consecutive lines from a >>> file (the listing below is a simplified version). >>> However, as it is written now, the generator method changes the text >>> file pointer to end of file after first invocation. >>> Namely, the file pointer changes from 0 to 6623 on line 24. >>> >> It might be that the generator method of self.input_file is reading >> the file a chunk at a time for efficiency even though it's yielding a >> line at a time. > > I think this is the case too. > I can think of 3 alternatives: > > a) open the file unbuffered (bufsize=0). But I think this would greatly > decrease performance. > > b) keep track internally of file position (by adding each line length). > The file should be opened in binary mode in this case (to avoid any '\n' > translation). > > c) return line numbers only, instead of file positions. Seeking to a > certain line number requires to re-read the whole file from start; > depending on how often this is required, and how big is the file, this > might be acceptable. > readline() appears to work as expected, leaving the file position at the start of the next line. From linda_octa at yahoo.com Wed Dec 3 07:13:45 2008 From: linda_octa at yahoo.com (Linda Octalina) Date: Wed, 3 Dec 2008 04:13:45 -0800 (PST) Subject: Converting a .xls file to .html References: <12cbbbfc0812030350u26b8f41cw6569d7b17bf21d41@mail.gmail.com> Message-ID: <524848.86507.qm@web30802.mail.mud.yahoo.com> Do you have styles attached to the text of the document in the xls? (bold, italic, etc) if not, then you can just do the mapping by creating table and cells by yourself... (or xslt) {^(00)^} LiNdA OcTaLiNa ---GeEeEee--- ________________________________ From: Jeremiah Dodds To: python-list at python.org Sent: Wednesday, December 3, 2008 9:50:49 PM Subject: Re: Converting a .xls file to .html On Wed, Dec 3, 2008 at 5:54 AM, tarun wrote: Hello All, I've a .xml file (saved as .xls) that can be opened in Microsoft excel. I want to write python code that converts this excel file into .html (so that it can be viewed as is in an explorer). Can any one help? Regards, Tarun -- http://mail.python.org/mailman/listinfo/python-list A quick google search shows http://pyxlreader.sourceforge.net/ , and a few other libraries for reading xls files. I don't use excel, so I can't test it. There may not be a library for going straight from xls -> html, but if you can get xls -> text or a list or whatnot, then you could use pretty much any html generation tool you want on it, python's got plenty of templating libraries available. -------------- next part -------------- An HTML attachment was scrubbed... URL: From federico at linux.com.uy Sat Dec 20 13:14:32 2008 From: federico at linux.com.uy (Federico Moreira) Date: Sat, 20 Dec 2008 21:14:32 +0300 Subject: Generator slower than iterator? In-Reply-To: References: <62013718-57e9-4690-a2be-11e63b9c135b@u18g2000pro.googlegroups.com> Message-ID: Wow, thanks again =) -------------- next part -------------- An HTML attachment was scrubbed... URL: From eckhardt at satorlaser.com Thu Dec 11 03:24:28 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 11 Dec 2008 09:24:28 +0100 Subject: Memory leak when using a C++ module for Python References: Message-ID: Jaume Bonet wrote: > When I test the code from C++ each time I delete a vector the consumed > memory decreases, but it does not happen when the module is called > from python. What is a "vector" for you? Do you mean std::vector? A vector allocated using malloc()? A vector allocated using new? Just provide a simple piece of C++ and Python example code that demonstrates the problem and you will probably get help immediatel. > I've read that the even when you delete the content of the vectors the > memory is not freed when you are working with python. Is that so? There are things like that, but without context it's pretty hard to tell what's going on. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From cjw at ncf.ca Mon Dec 1 19:49:36 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Mon, 01 Dec 2008 19:49:36 -0500 Subject: Multiple Versions of Python on Windows XP Message-ID: Could anyone please point me to documentation on the way the msi installer handles multiple versions eg. Python 2.5, 2.6 and 3.0? What changes are made to the registry? Is there some way to specify a default version in such a way that it can be changed as necessary? PyScripter uses an option to select a version eg. C:\Program Files\PyScripter\PyScripter.exe --python26 but I'm having some trouble with it when I attempt edit a python file from the Windows Explorer. I would appreciate any information. Colin W. From castironpi at gmail.com Wed Dec 17 19:46:32 2008 From: castironpi at gmail.com (Aaron Brady) Date: Wed, 17 Dec 2008 16:46:32 -0800 (PST) Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> Message-ID: On Dec 17, 5:05?pm, "Gabriel Genellina" wrote: > En Wed, 17 Dec 2008 12:21:38 -0200, Jeremy Sanders ? > escribi?: > > > Aaron Brady wrote: > > >> I thought so too. ?The web seems to say that on Linux they are, and on > >> Windows, you need to call DuplicateHandle for it. > > Or set bInheritHandle=True when creating the pipe initially. os.pipe() ? > doesn't do that. > > > I hit this problem - it looks like pipes aren't very versatile on ? > > Windows. > > There's also the complicating factor that the handles in windows aren't ? > > the > > same as the file numbers that Python uses, so you have to convert between > > them. > > > It would be nice if Python created pipes that are properly inheritable by > > default by child processes, as they're mostly used for IPC. > > I'd say it is a bug in os.pipe implementation; they should be inheritable ? > by default, as in posix (after all, the code is in "posixmodule.c"). The code looks like this: ok = CreatePipe(&read, &write, NULL, 0); Py_END_ALLOW_THREADS if (!ok) return win32_error("CreatePipe", NULL); read_fd = _open_osfhandle((Py_intptr_t)read, 0); write_fd = _open_osfhandle((Py_intptr_t)write, 1); 'If lpPipeAttributes is NULL, the handle cannot be inherited.' You could populate a 'SECURITY_ATTRIBUTES' structure, or call DuplicateHandle on both of them. A patch would look like this: SECURITY_ATTRIBUTES sattribs; sattribs.nLength = sizeof(sattribs); sattribs.lpSecurityDescriptor = NULL; sattribs.bInheritHandle = TRUE; ok = CreatePipe(&read, &write, &sattribs, 0); This still doesn't answer whether the file descriptor return by '_open_osfhandle' can be inherited too. From rdmurray at bitdance.com Mon Dec 15 08:03:38 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Mon, 15 Dec 2008 08:03:38 -0500 (EST) Subject: %s place holder does not let me insert ' in an sql query with python. In-Reply-To: <1229345178.31093.24.camel@krishna-laptop> References: <1229345178.31093.24.camel@krishna-laptop> Message-ID: On Mon, 15 Dec 2008 at 18:16, Krishnakant wrote: > how do you let the ' go as a part of the string? > I have used %s as placeholder as in > queryString = "insert into venders values ('%s,%s,%s" % > (field1,field2,field3 ) ... > This is not working for the ' values. This is untested, but I think what you want is: cursor.execute("insert into venders values (?, ?, ?)", field1, field2, field3) This uses parameter binding and should properly quote the values. It's also the "right way" to do it to avoid sql injection attacks and for efficiency if you run the same query multiple times. --RDM From bj_666 at gmx.net Sun Dec 7 09:46:53 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Dec 2008 14:46:53 GMT Subject: how to get a beep, OS independent ? References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> Message-ID: <6q25utFa7km1U1@mid.uni-berlin.de> On Sun, 07 Dec 2008 07:17:30 -0700, Joe Strout wrote: > But invoking the standard system beep is such a basic function that it > ought to be easier than this. I'm pretty sure it's a single OS call on > all platforms. On OS X, for example, it's > > void NSBeep(void); > > declared in NSGraphics.h. I'm sure it's something similarly simple on > other platforms. I'm not so sure. Under Unix the "system beep" is usually in the terminal emulation and triggered by sending '\a' to it. AFAIK there is no standard beep in X-Windows so every desktop environment implements something like audio notifications. Ciao, Marc 'BlackJack' Rintsch From arkanes at gmail.com Thu Dec 4 15:40:16 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 4 Dec 2008 14:40:16 -0600 Subject: To Troll or Not To Troll In-Reply-To: <896B75251BA19745A529B1B867893FA50679D3@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA50679D3@planet.delsci.local> Message-ID: <4866bea60812041240o1f57ba3bq84e9978800a5c17b@mail.gmail.com> On Thu, Dec 4, 2008 at 2:11 PM, Warren DeLano wrote: >> I still would have to call your management of the problem considerably >> into question - your expertise at writing mathematical software may >> not be in question, but your skills and producing and managing a >> software product are. You have nobody at your organization, which >> sells a product that relies on Python, who follows python-dev? Or who >> even reads the changelogs for new python versions? You should have >> known about the "as" keyword change *over a year ago*, even if the >> import bug was masking the deprecation warning. Everything else aside, >> I can't get past that issue with your complaints. I *have* gone back >> now and read all the posts in all the threads and I still have not >> seen a single post from you even hinting that you might have any >> responsibility in the matter. > > Well then, let me set the record straight on that one point: > > I admit that it was entirely my mistake (and mine alone) to implicitly > assume, by adopting such a logging & persistence architecture (dating > back to 1.5.2, mind you!), that new keywords would not be introduced > into the Python language so as to potentially break all existing Python > code. > > Silly me! How unreasonable. > Pythons backwards compatibility policy is available here: http://www.python.org/dev/peps/pep-0005/ From istvan.albert at gmail.com Mon Dec 22 09:33:12 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Mon, 22 Dec 2008 06:33:12 -0800 (PST) Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> <1iscu14.oixxplpgajabN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <9977fd77-9a17-4dcb-9193-49009763c683@33g2000yqm.googlegroups.com> > ---- conclusions ------------------------------- try testing on a large number of candidates that are all (or mostly) positive or all (or mostly) negative and you'll see performance numbers that are substantially different than the ones you report: candidates = range(1000) In general the function sign_1() is expected to be the fastest because in most cases will detect the sign with the fewest operations, it only visits the rest of the comparison when it hits the corner cases. Only if you have lots of +/-0.0 cases will it be slower than the rest, due to having to call an expensive operation. i. From steve at holdenweb.com Fri Dec 19 20:56:57 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 19 Dec 2008 20:56:57 -0500 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> Message-ID: Colin J. Williams wrote: > Steve Holden wrote: >> Thomas Heller wrote: [...] >>> Question from a non-native english speaker: is this now valid english? >>> >>> "One of Python???s great strengths" >>> ^ >>> "and also teaches Python???s functional programming features" >>> ^ >>> "The book???s approach is wholly practical" >>> ^ >> It always has been valid English. The apostrophe is only omitted from >> personal pronouns (hers, its, and so on). >> >> regards >> Steve > > What is the subject of "teaches"? > > I have no problem with the second sentence. > I don't have a problem with any of the three, which are all correct usage. Of course they aren't sentences but fragments thereof, so we don't know the subject of the verb in the second example (though we might guess it's the advertised book). Why would it matter? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From badmuthahubbard at usenet.cnntp.org Fri Dec 19 04:02:35 2008 From: badmuthahubbard at usenet.cnntp.org (Bad Mutha Hubbard) Date: 19 Dec 2008 09:02:35 GMT Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <494b5f47$0$17068$6e1ede2f@read.cnntp.org> Message-ID: <494b632b$0$17070$6e1ede2f@read.cnntp.org> Bad Mutha Hubbard wrote: > Roger wrote: > >> I've done a lot of googling for this topic and I fear that it's not >> possible. I have a widget that is overloaded with several bindings. >> I want to be able to unbind one method form the same Event without >> destroying all the other bindings to the same event that's associated >> to the same widget. >> >> For example: >> >> import Tkinter >> >> def test(): >> print 'test' >> >> def test2(): >> print 'test2' >> >> root = Tkinter.Tk() >> funcid1 = root.bind("<1>", lambda e: test()) >> funcid2 = root.bind("<1>", lambda e: test2(), add='+') >> root.unbind("<1>", funcid2) >> root.mainloop() >> >> When run neither <1> binding will exist against the root because the >> unbind will unbind all the functions associated with that event. >> However, in this example, I only want to unbind test2 not test1. >> >> Any help is greatly appreciated. Thanks! >> Roger. > > I believe you've discovered a bug. Aside from recommending trying > wxWidgets, here's the source of the unbind function in Tkinter.py: > > def unbind(self, sequence, funcid=None): > """Unbind for this widget for event SEQUENCE the > function identified with FUNCID.""" > self.tk.call('bind', self._w, sequence, '') > if funcid: > self.deletecommand(funcid) > > ------------------------------------------- > First, it replaces all bindings for the sequence with the empty string, > i.e., it deletes all bindings for that event unconditionally. THEN it > calls deletecommand() with the funcid, who knows what that does. My Tcl > is not so sharp. > I have an idea for a workaround, let me see if it works... > -Chuckk Alas, my workaround doesn't work either. Tkinter.py also states that calling bind with only an event sequence will return all bindings for that sequence; I was thinking I could then remove the function in question from that list and call bind again with each of the functions in the remaning list as argument. I had high hopes. The return value of calling bind with no target function is just about Tcl nonsense: #!/usr/bin/env python import Tkinter def test(event): print 'test' def test2(event): print 'test2' root = Tkinter.Tk() funcid1 = root.bind("<1>", test) funcid2 = root.bind("<1>", test2, add='+') print funcid1, funcid2 bound = root.bind('') print "bound:", bound #root.unbind("<1>", funcid=funcid2) root.mainloop() --------------------------- Note that I took out the lambdas and gave event arguments to the functions; if you did that on purpose, because you need to call the same functions without events, then just ignore that... SO, the other workaround, which I've used, is to bind the event to a generic function, and have that generic function conditionally call the functions you want. I'll go back and try to make an example from your example. -Chuckk From vkseashoremack at googlemail.com Sat Dec 20 11:56:38 2008 From: vkseashoremack at googlemail.com (vkseashoremack at googlemail.com) Date: Sat, 20 Dec 2008 08:56:38 -0800 (PST) Subject: sapphic er - Free Message-ID: <7cc1abe7-8e1e-4da7-9578-48360e5431b7@g1g2000pra.googlegroups.com> sapphic er . . . *******CLICK HERE******** http://club247.cn/sapphic-er ***************************** . . . . . . . . . . . . sapphic er From news123 at free.fr Sat Dec 6 17:08:08 2008 From: news123 at free.fr (News123) Date: Sat, 06 Dec 2008 23:08:08 +0100 Subject: operators as variables In-Reply-To: References: <103920.71204.qm@web26006.mail.ukl.yahoo.com> Message-ID: <493af7c8$0$2062$426a74cc@news.free.fr> Terry Reedy wrote: > macc_200 wrote: >> Hi, >> just starting programming and have an elementary question after >> playing around with lists but cannot find the answer with googling. >> I have a list of variables and I would like some of those variables to >> be integers and some to be operators so the list would look something >> like [5 * 4 - 4 + 6] and then be able to evaluate the result (i.e. get >> 10). How do you make the interpreter see the operator as that instead >> of a string and just echo the list back to me. > Without sanity checking following would work: a= [ '1' , '+' , '3' ] txt= ' '.join(a) rslt = eval(txt) bye N From bruno.42.desthuilliers at websiteburo.invalid Thu Dec 4 08:32:23 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 04 Dec 2008 14:32:23 +0100 Subject: receive data through a python program from javascript In-Reply-To: <49c9e72f-5032-437d-ac70-8aea009e9278@i24g2000prf.googlegroups.com> References: <49c9e72f-5032-437d-ac70-8aea009e9278@i24g2000prf.googlegroups.com> Message-ID: <4937dbd4$0$12623$426a74cc@news.free.fr> gaurav kashyap a ?crit : > Hi all, > I have a javascript.I want to send some data from this javascript to a > python program that is on zope on my local system... google for Ajax. > What can be the python program Anything on your zope instance that can handle an HTTP request. From the server side POV, how the request is made is mostly (if not totally) irrelevant [1]. [1] ok, you may want the request handler to put something specific in the response... but that's still HTTP anyway). From eric at ericaro.net Fri Dec 5 20:50:07 2008 From: eric at ericaro.net (eric) Date: Fri, 5 Dec 2008 17:50:07 -0800 (PST) Subject: A more pythonic way of writting References: <35d176ed-df5f-46b4-8321-4814fcc4398c@f3g2000yqf.googlegroups.com> <8de7622d-28a7-4f96-9fb0-21cda357dcf3@r36g2000prf.googlegroups.com> <0149aea6$0$20670$c3e8da3@news.astraweb.com> Message-ID: <57e915f5-13a3-4ada-b684-fa7e75405fda@g38g2000yqn.googlegroups.com> On Dec 6, 12:19?am, Steven D'Aprano wrote: > On Fri, 05 Dec 2008 07:44:21 -0800, eric wrote: > > I like to believe that the less the 'debug pointer' stands in the python > > code, the fastest the code is (or is potentially) > > What's a debug pointer? > > Pre-mature optimization is the root of evil in programming. Unless you > have actually *measured* the speed of the code, how do you know you > aren't making it slower instead of faster? > > Experience with other languages often is misleading when programming with > Python. If you are used to programming in C, for example, then you will > tend to program one way because comparisons are fast and moving records > is slow. But in Python, comparisons can be slow and moving records is > fast, so the C programmer's intuitions about "fast code" are often > pessimations instead of optimizations. > > -- > Steven you are right about premature optimization. I cannot disagree. My 'rule of thumb' was more about that: 1/ keep the code the more descriptive and the less procedural as possible. 2/ the less instructions you write, the more optimization you'll get from the others the hypercube function is cool, and I would use it, if I weren't in charge of maintaining the code. I've done some 'timeit' import timeit t1 = timeit.Timer( """ h1 = hypercube(6) """, """def hypercube(ndims): return [[i&mask==mask for mask in [1< Message-ID: <4fb8097d-44b3-418e-84c6-231e5be6487b@a29g2000pra.googlegroups.com> On Dec 10, 10:06?am, prueba... at latinmail.com wrote: > On Dec 10, 6:58?am, Bill McClain > > > > <20080915.20.wmccl... at spamgourmet.com> wrote: > > On 2008-12-10, ajaksu wrote: > > > > On Dec 9, 5:24?pm, Bill McClain <20080915.20.wmccl... at spamgourmet.com> > > > wrote: > > > > On 2008-12-09, MRAB wrote: > > > > > > In Python 2.x unmarked string literals are bytestrings. In Python 3.x > > > > > they're Unicode. The intention is to make the transition from 2.x to 3.x > > > > > easier by adding some features of 3.x to 2.x, but without breaking > > > > > backwards compatibility (not entirely successfully!). > > > > > It is a bit ugly. In 2.6 StringIO won't take bytestrings, so I apply u'x'. But > > > > in 3.0 u'x' will be gone and I'll have to change the code again. > > > Try: > > > from __future__ import unicode_literals > > > That works for: > > > ? ? output.write('First line.\n') > > > ...but not for: > > > ? ?print('Second line.', file=output) > > > Maybe a combination of this and functools.partial as was suggested before. At > > least the necessary edits would be at the top of the program. > > > -Bill > > -- > > Sattre Press ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Tales of Warhttp://sattre-press.com/?? ? ? ? ? ? ? ? ? ? by Lord Dunsany > > i... at sattre-press.com ? ? ? ?http://sattre-press.com/tow.html > > I think this combination might do the trick (I don't have 2.6 to test > it right now): > > from __future__ import print_function > from __future__ import unicode_literals > from functools import partial > import io > print = partial(print, sep=" ", end="\n") > out = io.StringIO() > print("hello", file=out) > > What puzzles me is the documentation in 2.6 and 3.0: > In 2.6 it says: "The StringIO object can accept either Unicode or 8- > bit strings". Why does it fail with old str objects then? > Why is there no documentation for StringIO in 3.0? OK I found StringIO it is called io.StringIO now. From robert.kern at gmail.com Thu Dec 18 17:52:01 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 18 Dec 2008 16:52:01 -0600 Subject: Which sparse matrix package? In-Reply-To: References: <20081218231851.70dd91e2@Schlamber.localdomain> Message-ID: James Mills wrote: > On Fri, Dec 19, 2008 at 8:18 AM, Martin Manns wrote: >> Hi: > > Hi, > >> I am writing a spreadsheet application in Python > > What's wrong with pyspread ? pyspread *is* the spreadsheet application he is writing. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From prologic at shortcircuit.net.au Mon Dec 29 22:23:50 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 30 Dec 2008 13:23:50 +1000 Subject: print a vs print '%s' % a vs print '%f' a In-Reply-To: <5b8d13220812291919h700f1586q5ab68ec6edb927f1@mail.gmail.com> References: <5b8d13220812291919h700f1586q5ab68ec6edb927f1@mail.gmail.com> Message-ID: On Tue, Dec 30, 2008 at 1:19 PM, David Cournapeau wrote: (... snip ...) > print '%f' % a # -> print '1.#INF' Would this not be controlled by: 1. float(a) or a.__float__() 2. tp_print cheers James From tjreedy at udel.edu Fri Dec 19 21:38:12 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 19 Dec 2008 21:38:12 -0500 Subject: Namespaces, multiple assignments, and exec() In-Reply-To: <200812200234.33852.research@johnohagan.com> References: <200812200234.33852.research@johnohagan.com> Message-ID: John O'Hagan wrote: > I have a lot of repetitive assignments to make, within a generator, that use a > function outside the generator: > > var1 = func("var1", args) > var2 = func("var2", args) > var3 = func("var3", args) > etc... > > In each case the args are identical, but the first argument is a string of the > name being assigned. It works fine but I'd like to reduce the clutter by > doing the assignments in a loop. I've tried using exec(): > > for name in name_string_list: > exec(name + ' = func(\"' + name + '\", args)') > > but in the local namespace it doesn't understand func(), and if I give it > globals() it doesn't understand the args, which come from within the > generator. > > What's a good way to do this kind of thing? Put everything in your own namespace myvars={} for name in namelist: myvars[name]=func(name,args) From hrishys at yahoo.co.uk Thu Dec 11 05:52:18 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Thu, 11 Dec 2008 10:52:18 +0000 (GMT) Subject: Equivalent of 'wget' for python? In-Reply-To: Message-ID: <904110.93273.qm@web27404.mail.ukl.yahoo.com> Hi Saju Thanks for helping the oop challenged regards Hrishy --- On Thu, 11/12/08, saju.pillai at gmail.com wrote: > From: saju.pillai at gmail.com > Subject: Re: Equivalent of 'wget' for python? > To: python-list at python.org > Date: Thursday, 11 December, 2008, 10:41 AM > On Dec 11, 3:36?pm, "saju.pil... at gmail.com" > > wrote: > > On Dec 11, 2:36?pm, hrishy > wrote: > > > > > Hi > > > > > Please excuse my OOP but is my understanding > correct > > > > > > urllib.urlretrieve(url_of_zip_file,destination_on_local_filesystem) > > > > > is urllib --->Static Class on which the method > urlretrieve method is invoked ? > > > > No urllib is a "method". Use type(obj) to > find out what python thinks > > typo c/method/module > > > the "type" of that object is. Note that > "object" here is not meant in > > the same sense as the OOP definition. > > > > > > > > > In that case what does the python 3.0 version > mean > > > > > import urllib.request > > > urllib.request.urlretrieve(url, local_file_name) > > > > > urllib -->static class > > > request -->method > > > urlretrieve--> what is this then ? > > > > A 'function'. urllib.request.urlretrieve is > the fully qualified name > > of the function urlretrieve. In other words > urlretrieve lives in the > > urllib.request namespace. > > > > -srp > > > > > > > > > regards > > > Hrishy > > > > > --- On Mon, 8/12/08, Jerry Hill > wrote: > > > > > > From: Jerry Hill > > > > > Subject: Re: Equivalent of 'wget' > for python? > > > > To: python-l... at python.org > > > > Date: Monday, 8 December, 2008, 5:54 PM > > > > On Mon, Dec 8, 2008 at 11:53 AM, r0g > > > > wrote: > > > > > urllib.urlretrieve(url_of_zip_file, > > > > destination_on_local_filesystem). > > > > > > In python 3.0, that appears to be: > > > > > > import urllib.request > > > > urllib.request.urlretrieve(url, > local_file_name) > > > > > > -- > > > > Jerry > > > > -- > > > > >http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From george.sakkis at gmail.com Tue Dec 9 11:57:22 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 9 Dec 2008 08:57:22 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> Message-ID: On Dec 9, 9:28?am, MRAB wrote: > I certainly wouldn't want something like PL/I, where "IF", "THEN" and > "ELSE" could be identifiers, so you could have code like: > > ? ? ?IF IF = THEN THEN > ? ? ? ? ?THEN = ELSE; > ? ? ?ELSE > ? ? ? ? ?ELSE = IF; Although I agree with the sentiment, you can write uncomprehensibly insane code in any language; Python already gives a lot of horsepower to run wild with metaclass magic, bytecode hacking, etc. The fact that you *can* write abominations as the above doesn't mean that you should; the OP's use case - using "foo.as(int)" - is pretty reasonable and readable. I believe the responsibility to not abuse the power of the language should be on the application programmer, not the language designer. George From martin at v.loewis.de Tue Dec 16 16:58:17 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 16 Dec 2008 22:58:17 +0100 Subject: Problem Python 2.6.1 vs 2.6 & pyWin32 In-Reply-To: References: <4946754f$0$19000$426a74cc@news.free.fr> <4946D09F.6050300@v.loewis.de> <4946e680$0$9099$9b622d9e@news.freenet.de> Message-ID: <49482479$0$3997$9b622d9e@news.freenet.de> > Sorry for not being explicit. With "installer" I meant the binary > Windows installer you create with command "python setup.py > bdist_wininst". In the past we've been able to use > "package-version.win32.exe" files created with Python 2.5 on older > version, but that doesn't seem to be case with 2.6. I see. This has nothing to do with the OP's question, then. For Python 2.6, we switched to VS 2008. Apparently, the bdist_msi installers now get linked with the VS 2008 CRT (msvcr90.dll), which must be present on the system (in WinSxS) for the installer to run; one way of installing the CRT is to install Python for all users, another is to install it "just for me", and put \python26 into PATH (so that the installer can find msvcr90.dll). Regards, Martin From no.spam at from.net Thu Dec 11 15:51:40 2008 From: no.spam at from.net (Giuseppe Di Martino) Date: 11 Dec 2008 20:51:40 GMT Subject: Problems running on HP Intel duo core machine References: <200809221443.25765.inq1ltd@inqvista.com> <200812051608.56335.inq1ltd@inqvista.com> Message-ID: <49417d5c$0$18157$4fafbaef@reader3.news.tin.it> Il Thu, 11 Dec 2008 14:58:16 -0500, jim-on-linux ha scritto: > The first module that is imported is win32api. line 8 of that module > adds to the path the module named 'win32api.pyd'. > The import is is completed without error. > > The next module that is imported is win32ui. line 8 of that module adds > to the path a module named 'win32ui.pyd'. > The search for the win32ui.pyd module seems to be the cause of the > problem. > Traceback: > ImportError: Dll load failed: The specified module could not be found. > > Both modules 'win32api.pyd' and win32ui.pyd are in the same directory. Have you checked if there is a file named "win32api.pyd" somewhere in the system path (c:\windows\, c:\windows\system32, etc. ) ? Try to add the path to the folder containing your win32api.pyd and win32ui.pyd to the PATH enviroinment variable, before running your application. Giuseppe From rt8396 at gmail.com Mon Dec 22 22:03:09 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 19:03:09 -0800 (PST) Subject: noob trouble with IDLE References: <68f1552e0812211346i96bf18hf28dccc1f8dd1a99@mail.gmail.com> Message-ID: <16bf1bde-af9e-45bf-acfd-e776442000ac@q30g2000vbn.googlegroups.com> Yea, if you use Tkinter in concert with IDLE, your script will lock up. From rcdailey at gmail.com Mon Dec 8 22:10:00 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 8 Dec 2008 19:10:00 -0800 (PST) Subject: RuntimeError: dictionary changed size during iteration References: <274eb282-1635-40ca-95af-b82271c57802@v4g2000yqa.googlegroups.com> Message-ID: On Dec 8, 6:26?pm, Terry Reedy wrote: > Robert Dailey wrote: > > stuff = vars() > > ?>>> vars() is globals() > True > > > for key in stuff: > > You just changed globals, which is aliased as stuff. > Stuff changes. > > > ? ? print( key, '--', stuff[key] ) > > > I get the following error message: > > ('CopyEmotionFX', '--', ) > > Traceback (most recent call last): > > ? File "C:\IT\work\jewett\depends.py", line 12, in > > ? ? for key in stuff: > > RuntimeError: dictionary changed size during iteration > > > Why is this happening? > > How am I changing globals()? I'm simply iterating the keys in the dict. Can someone explain what is going on please? From notvalid2 at sbcglobal.net Wed Dec 17 08:02:55 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Wed, 17 Dec 2008 05:02:55 -0800 Subject: WinMerge--B/W Shading of Printed Copy to Show Differences? In-Reply-To: References: <3jX1l.6876$pr6.3299@flpi149.ffdc.sbc.com> Message-ID: W. eWatson wrote: > Jason Scheirer wrote: >> On Dec 16, 3:56 pm, "W. eWatson" wrote: >>> Is there a way to highlight differences between the two files when >>> printing >>> in b/w? Help suggests there may be some texturing, but all I see is >>> color >>> choices. >>> -- >>> W. eWatson >>> >>> (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) >>> Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet >>> >>> Web Page: >> >> WinMerge is written in C++ and not even remotely related to Python. > Well, yes, but it has applicability to Python (and maybe other > languages) in that I can use it to find differences between two sets of > code. > > If not here, where? comp.lang.??? ? > Hmm, I guess no one here uses it. I did find a winmerge mailing list, so will work it out there. -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From cmr.pent at gmail.com Mon Dec 22 13:59:46 2008 From: cmr.pent at gmail.com (=?UTF-8?B?0JDQvdC00YDQtdC5INCf0LDRgNCw0LzQvtC90L7Qsg==?=) Date: Mon, 22 Dec 2008 21:59:46 +0300 Subject: Calling ImageMagick's convert In-Reply-To: <47c890dc0812220033g49d35ae9w24aede0b438adb4b@mail.gmail.com> References: <47c890dc0812220033g49d35ae9w24aede0b438adb4b@mail.gmail.com> Message-ID: <5f0660120812221059w32175880ya9aac8982640365f@mail.gmail.com> 2008/12/22 Chris Rebert : > I think this needs to be: > > subprocess.call(['convert', 'in.png', '-resize', '640x480', 'out.png']) > > Otherwise, it gets '-resize 640x480' as a single escaped option when > it's really 2 options, which is the error message you're getting. > You have to split the arguments up just like the shell would, which > basically means at whitespace unless quoting is used, which is not the > case here. > > Cheers, > Chris It worked, many thanks! Andrey From fred.sells at adventistcare.org Wed Dec 24 23:24:35 2008 From: fred.sells at adventistcare.org (Sells, Fred) Date: Wed, 24 Dec 2008 23:24:35 -0500 Subject: Python advocacy . HELP! In-Reply-To: <5f8c1a52-545e-402e-863a-acdf23d04c78@h20g2000yqn.googlegroups.com> References: <5f8c1a52-545e-402e-863a-acdf23d04c78@h20g2000yqn.googlegroups.com> Message-ID: Prof. Kanabar (kanabar.bu.edu) is planning to offer a python course there soon. Perhaps he could help. Tell him you got his name from me (Fred Sells). > -----Original Message----- > From: python-list-bounces+frsells=adventistcare.org at python.org > [mailto:python-list-bounces+frsells=adventistcare.org at python.org] On > Behalf Of Michael_D_G > Sent: Thursday, December 04, 2008 1:52 AM > To: python-list at python.org > Subject: Python advocacy . HELP! > > > I am a faculty member of a cs department. We currently teach C++ in > our intro to programming course. I am teaching this class and it seems > to me that we would be much better served teaching python in the intro > course, C++ for Data structures, as we do now, and Java in object > oriented programming, as we do now. > Some of my colleagues agree with me but some still see python as a > niche language and don't understand > how we could teach anything beyond C, C++ or Java. > > I have looked at several interesting academic papers, on doing just > this approach. I have also looked through the > python web page to get examples of industry players using python in a > non-trivial way. Yes, I know, Google, > Microsoft, Sun, CIA website running on Plone, NOAA, NASA. If anyone > has any recent articles, > or if anyone on the list is at a fortune 500 company, how do I refute > the notion that Python > is a "marginal" language because according to TOBIE it only less than > a 6% market share. > > -michael > -- > http://mail.python.org/mailman/listinfo/python-list From bradcausey at gmail.com Wed Dec 24 13:27:51 2008 From: bradcausey at gmail.com (Brad Causey) Date: Wed, 24 Dec 2008 12:27:51 -0600 Subject: VERY simple string comparison issue Message-ID: <89f89940812241027o40e3d079v9f9d76e76b1af4a6@mail.gmail.com> Python Version: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 List, I am trying to do some basic log parsing, and well, I am absolutely floored at this seemingly simple problem. I am by no means a novice in python, but yet this is really stumping me. I have extracted the pertinent code snippets and modified them to function as a standalone script. Basically I am reading a log file ( in this case, testlog.log) for entries and comparing them to entries in a safe list (in this case, safelist.lst). I have spent numerous hours doing this several ways and this is the most simple way I can come up with: import string safelistfh = file('safelist.lst', 'r') safelist = safelistfh.readlines() logfh = file('testlog.log', 'r') loglines = logfh.readlines() def safecheck(line): for entry in safelist: print 'I am searching for\n' print entry print '\n' print 'to exist in\n' print line comp = line.find(entry) if comp <> -1: out = 'Failed' else: out = 'Passed' return out for log in loglines: finalentry = safecheck(log) if finalentry == 'Failed': print 'This is an internal site' else: print 'This is an external site' The contents of the two files are as follows: http://www.mysite.com http://www.mysite.com/images/homepage/xmlslideshow-personal.swf It seems that no matter what I do, I can't get this to fail the " if comp <> -1:" check. (My goal is for the check to fail so that I know this is just a URL to a safe[internal] site) My assumption is that the HTTP:// is somehow affecting the searching capabilities of the string.find function. But I can't seem to locate any documentation online that outlines restrictions when using special characters. Any thoughts? Thanks! -Brad -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at mrabarnett.plus.com Tue Dec 9 13:40:03 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 09 Dec 2008 18:40:03 +0000 Subject: "as" keyword woes In-Reply-To: References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> Message-ID: <493EBB83.5080108@mrabarnett.plus.com> Aaron Brady wrote: > On Dec 9, 8:28 am, MRAB wrote: > snip >> In some languages (I think Delphi is one of them - it's been a while!) >> some words which would normally be identifiers have a special meaning in >> certain contexts, but the syntax precludes any ambiguity, and not in a >> difficult way. "as" in Python was one of those. >> >> I certainly wouldn't want something like PL/I, where "IF", "THEN" and >> "ELSE" could be identifiers, so you could have code like: >> >> IF IF = THEN THEN >> THEN = ELSE; >> ELSE >> ELSE = IF; >> >> See http://en.wikipedia.org/wiki/PL/I_(programming_language). > snip > > The following are semantically equivalent: > > I certainly wouldn't want something like PL/I, where "IF", "THEN" and > "ELSE" could be identifiers. > > I wouldn't want something like PL/I, where "IF", "THEN" and "ELSE" > could be identifiers. > > That is, 'certainly' doesn't change the meaning of your statement > any. You wouldn't want it, but King George III didn't want the > American Revolution. > It's called emphasis. > You wouldn't want it. What does that mean for me (the generic > reader), and Python? What can I learn from that fact? > From wuwei23 at gmail.com Thu Dec 4 07:28:03 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 4 Dec 2008 04:28:03 -0800 (PST) Subject: performance question: dictionary or list, float or string? References: <434bf4e3-54f4-4e15-b8b0-510a988f25b8@z1g2000yqn.googlegroups.com> <904a19e9-3800-4d61-aea0-4bdabc0674fa@j32g2000yqn.googlegroups.com> <842b13b2-1df5-4b34-af14-7b082970682b@41g2000yqf.googlegroups.com> Message-ID: <796f927e-5def-4637-bb31-88965b9bcb44@z28g2000prd.googlegroups.com> On Dec 4, 8:12?pm, bkamr... at gmail.com wrote: > About the piece of code you posted, there is something I don't > understand. > > ? ? ? ? for i, line in data: > > where data is a file object. Is it legal to write that? > I believe it results in "too many values to unpack" or do I miss > something? >From the context, my guess is Matimus intended to write: for i, line in enumerate(data): From gagsl-py2 at yahoo.com.ar Sat Dec 6 13:47:40 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 06 Dec 2008 16:47:40 -0200 Subject: Python calling COM compliant .dll References: <740322.52556.qm@web26308.mail.ukl.yahoo.com> Message-ID: En Wed, 03 Dec 2008 16:20:27 -0200, David Shi escribi?: > I am looking for a concise working example of Python script calling COM > compliant .dll. The best source of information is Mark Hammond's book "Python Programming in Win32". The sample chapters available are about using COM objects, AFAIR. -- Gabriel Genellina From nick at craig-wood.com Fri Dec 12 11:30:54 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 12 Dec 2008 10:30:54 -0600 Subject: How do I manually uninstall setuptools (installed by egg)? References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> <47c890dc0812091904p12e75510sbe0b8858eb2f6d9e@mail.gmail.com> Message-ID: David Cournapeau wrote: > On Thu, Dec 11, 2008 at 10:30 PM, Nick Craig-Wood wrote: > > David Cournapeau wrote: > >> On Wed, Dec 10, 2008 at 12:04 PM, Chris Rebert wrote: > >> > On Tue, Dec 9, 2008 at 6:49 PM, wrote: > >> >> On Ubuntu, I accidentally manually installed setuptools > >> >> http://pypi.python.org/pypi/setuptools/0.6c9 (by running the .egg file > >> >> as a shell script via sudo), and now realize I should just be using > >> >> apt to take care of my system Python packages. > >> > > >> > Really, why? setuptools has more Python packages/programs available > >> > and updates faster than Debian. > >> > It's also likely that some of the Debian Python packages are installed > >> > using setuptools anyway. > >> > So, why do you think apt and not setuptools is The Right Way(tm)? > >> > >> Setuptools is certainly not the right way to install packages > >> system-wide on debian, it is very likely to break the whole thing. > > > > It wouldn't be too difficult to make a .deb target which would collect > > all the files that did get installed into a package. It would be a > > rather rough and ready package but would do the job. > > Depends what you mean by would do the job: rather rough certainly does > not mean "would do the job" for something as essential as a package > IMO. Essentially a package has files in it in a fixed possition in the filesystem. The package manager's (dpkg at this level) job is to keep track of those file and tell you about conflicts. You can use alien to turn a tar.gz into a perfectly usable debian package. It won't have dependencies, or help or any of the other things a package needs to be a proper package, but it satisfies my basic needs that all software is installed as packages, so it can be uninstalled cleanly. > > The .deb would then be uninstallable in the usual (dpkg --purge) way. > > > > Did anyone think about that? > > Yes, there is stddeb which does that (make a .deb package from a > setuptools package). Cool, I've not seen that before. Probably because it isn't in debian! > > easy_install can do that I think... > > Not without a lot of hoola, unfortunately; for example, it breaks > stow, so I have to use specialy scripts to circumvent the damn thing > and make it what I tell him to do. I never understood what's easy > about easy install: it is broken in so many ways, and has caused me so > many pains - even when I was not using - that I do not trust it at > all. I only use it to download packages (and even then it manage to > fail more than work), and always install them from setup.py afterwards > (at which step I of course also have to circumvent setuptools if the > package uses setuptools). ;-) As a mostly linux developer I always install stuff in packages if possible. Failing that I'll use bdist_rpm then alien to convert to a deb which works well enough I find. However when I have to make my stuff work on Windows, I find easy_install to be a fantastic timesaver as compared to looking for the package on a web site, downloading it, unpacking it installing it and then repeating for all the dependencies. easy_install is a long way from being a proper package manager though :-( I guess it is aiming at the same territory as the cpan installer with perl. My experiences with that is that it works very well, but again splatters untracked files all over your filesystem. Debian comes with dh-make-perl which can use CPAN directly to make .debs which works quite well. Something similar based on easy_install for python would be ideal. It looks like stdeb could become that one day. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From steve at holdenweb.com Tue Dec 23 09:19:26 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 23 Dec 2008 09:19:26 -0500 Subject: On Whose Desktop In-Reply-To: <4950db7e$0$14770$426a74cc@news.free.fr> References: <4950db7e$0$14770$426a74cc@news.free.fr> Message-ID: Fuzzyman wrote: > On Dec 23, 12:06 pm, Steve Holden wrote: >> Thanks to Barry Warsaw the "On Your Desktop" blog now has a new entry: >> >> http://onyourdesktop.blogspot.com/ >> >> Who would you like to see profiled next? > > Guido (of course), Brett Cannon, Martin v Loewis, Jim Hugunin, Ted > Leung, Dino Viehland (core developer of IronPython), Titus Brown, Ivan > Kristic, Mark Shuttleworth, Tim Golden, Michele Simionato, Thomas > Heller, Greg Ewing - any and all of these would be great. > > Any women in Python you could ask - how about Anna Ravenscroft? > Bruno Desthuilliers wrote: > > The effbot ? > skip at pobox.com wrote: > Maybe Martin v. Loewis? He contributes so much to Python. I met him once > several years ago at a Python conference (or maybe it was still just a > workshop then), but beyond seeing his titanic contributions to Python, I > know little about the guy. I hope *everyone* knows that Martin was the winner of this year's Frank Willison Award: http://www.python.org/community/awards/frank-willison/#martin-von-l-wis-2008 Great! Keep the suggestions coming, please! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From google at mrabarnett.plus.com Wed Dec 10 22:51:10 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 11 Dec 2008 03:51:10 +0000 Subject: Python is slow In-Reply-To: References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> Message-ID: <49408E2E.1000302@mrabarnett.plus.com> Benjamin Kaplan wrote: > > > On Wed, Dec 10, 2008 at 10:25 PM, Carl Banks > wrote: > > On Dec 10, 12:42 pm, cm_gui > wrote: > > Python is SLOW. And I am not comparing it with compiled languages > > like C. > > Python is even slower than PHP! > > > cm_gui is TROLL. And I am not compring it with bots like Aaron > Castironpi Brody. cm_gui is even troller than Xah Lee! > > > actually Castironpi has made some coherent replies lately. Xah Lee is > worse than ever though. > Perhaps there's a Law of Conservation of Trolling. :-) From hakan.hagenrud at ikea.com Mon Dec 8 04:26:05 2008 From: hakan.hagenrud at ikea.com (=?ISO-8859-1?Q?H=E5kan_Hagenrud?=) Date: Mon, 8 Dec 2008 10:26:05 +0100 Subject: Shutdown Mac OSX computer using python Message-ID: <0D77FD19-CA33-48BC-9D7D-72E336143D1C@ikea.com> Hello, i'm a python noob! But I would like to shutdown a 10.5.x mac computer using python (2.5.1) this is my code: #!/usr/bin/python import SystemEvents down = SystemEvents.Power_Suite.Power_Suite_Events() down.shut_down() the last call needs an additional argument, I cant find any documentation about this. Anybody knows? Thank you! H?kan Hagenrud From deets at nospam.web.de Sun Dec 7 16:21:46 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 07 Dec 2008 22:21:46 +0100 Subject: how to get a beep, OS independent ? In-Reply-To: <6q2sjfFai65qU1@mid.individual.net> References: <6q2sjfFai65qU1@mid.individual.net> Message-ID: <6q2t3aFajp2pU1@mid.uni-berlin.de> Peter Pearson schrieb: > On Sun, 07 Dec 2008 00:40:53 +0100, Stef Mientki wrote: >> I want to give a small beep, >> for windows there's message-beep, >> and there seems to be something like " curses" , >> but that package seems to be totally broken in P2.5 for windows. >> >> Any other suggestions ? > > Many people have suggested sending an ASCII 07 to your > terminal window, but sometimes you don't have a terminal > window. > > Then there's the question of using the sound card versus > using the PC speaker. Too complicated for me. > > I used a kluge: a short C program that beeps the way I want, > in this case using ioctl(fd,KDMKTONE,arg) on /dev/tty0 (this > is Linux). The program has enough privileges to execute > even when run by unprivileged users, and of course can be > invoked by whatever language you're working in. This can be done with python also, no need for C. See the module fcntl. The privilege-problem persists of course. Diez From philip.slate at gmail.com Sun Dec 7 17:23:50 2008 From: philip.slate at gmail.com (Philip Slate) Date: Sun, 7 Dec 2008 14:23:50 -0800 (PST) Subject: Guido's new method definition idea References: <493a9fed$0$18973$426a34cc@news.free.fr> <493c1ff6$0$4942$426a34cc@news.free.fr> Message-ID: <49d12ec1-2be9-497b-80bc-9f0402a9086d@s20g2000yqh.googlegroups.com> On Dec 7, 1:13?pm, Bruno Desthuilliers wrote: > > and friendlier to newbies. > > I'd rather say "more acceptable to java-brainwashed developpers". And I'd rather say you're trolling, but that's ok since you're preaching to the converted. You conveniently forgot to mention the C++/ Eiffel/Smalltalk/pretty-much-every-OO-lang "brainwashed" developers too. In reality Python, with its kludgy OO and objects being essentially glorified dicts, is the odd one out, not the other way around. From walterbyrd at iname.com Sat Dec 20 18:14:44 2008 From: walterbyrd at iname.com (walterbyrd) Date: Sat, 20 Dec 2008 15:14:44 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> On Dec 19, 12:43?pm, excord80 wrote: > Also, I like having only *one* special symbol (`%') to worry > about in my strings instead of two (`{' and `}'). > Actually the new way has, at least three special symbols: ( '{', '}' , '.') as well as the method name "format" so "%s=%s" % (k, v) for k, v in params.items() becomes: "{0}={1}".format((k, v) for k, v in params.items()) or something like that. From bearophileHUGS at lycos.com Thu Dec 11 13:39:03 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 11 Dec 2008 10:39:03 -0800 (PST) Subject: dictionary idiom needed References: <383976cf-53fb-48e4-b028-8f568468ce77@r36g2000prf.googlegroups.com> <0c4950c1-4833-40c7-ac19-260b61d5289f@k24g2000pri.googlegroups.com> Message-ID: bearophile: > you can do with a dict > that has the tuple ('word', 'tagB') as key, and as value has a > collections.defaultdict(int) that maps 'tagB' to its count. Where's 'tagA'? Probably I haven't understood your problem well enough. I need a better example of your data and what you need... Sorry, bye, bearophile From excord80 at gmail.com Sun Dec 7 19:43:05 2008 From: excord80 at gmail.com (excord80 at gmail.com) Date: Sun, 7 Dec 2008 16:43:05 -0800 (PST) Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? Message-ID: Trying to decide which to get started with. Can anyone suggest some pros and cons to each of them? Would PyOpenGL be in the same camp as Pygame and pyglet? Do either of Pygame or pyglet make use of PyOpenGL behind the scenes? From arnodel at googlemail.com Mon Dec 1 17:42:24 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 01 Dec 2008 22:42:24 +0000 Subject: Scanner class References: <737a0550-0b92-4f65-829e-953882d74419@y18g2000yqn.googlegroups.com> Message-ID: George Sakkis writes: > Is there any stdlib or (more likely) 3rd party module that provides a > similar functionality to the java.util.Scanner class [1] ? If not, > would there be any interest in porting it (with a more Pythonic API of > course) or are there better alternatives ? > > George > > [1] http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html Have you looked at: >>> import re >>> re.Scanner Last time I checked it was undocumented though, although I vaguely recall a Cookbook recipe. Ah here it is: http://code.activestate.com/recipes/457664/ HTH -- Arnaud From john.rominsky at gmail.com Wed Dec 17 12:16:35 2008 From: john.rominsky at gmail.com (Rominsky) Date: Wed, 17 Dec 2008 09:16:35 -0800 (PST) Subject: getting object instead of string from dir() Message-ID: I am trying to use dir to generate a list of methods, variables, etc. I would like to be able to go through the list and seperate the objects by type using the type() command, but the dir command returns a list of strings. When I ask for the type of an element, the answer is always string. How do I point at the variables themselves. A quick example is: a = 5 b = 2.0 c = 'c' lst = dir() for el in lst: print type(el) Right now I am understandably getting all types being output as strings, how do i get the type of the actual objects returned from dir ()? From riklaunim at gmail.com Wed Dec 31 12:08:46 2008 From: riklaunim at gmail.com (riklaunim at gmail.com) Date: Wed, 31 Dec 2008 09:08:46 -0800 (PST) Subject: Desktop/File management support on MS Windows Message-ID: <4b7188db-63b2-4ac5-80cb-d1326ca3694a@q26g2000prq.googlegroups.com> Are there any Python libraries that can trash files (move to Trash, not delete) or for example return a list of applications that can open given file? I can't find anything related to this for Windows. From rocky at panix.com Mon Dec 29 21:13:55 2008 From: rocky at panix.com (R. Bernstein) Date: Mon, 29 Dec 2008 21:13:55 -0500 Subject: How do I DRY the following code? Message-ID: How do I DRY the following code? class C(): def f1(self, arg1, arg2=None, globals=None, locals=None): ... unique stuff #1 ... ... some common stuff #1 ... ret = eval(args, globals, locals) ... more stuff #2 ... return retval def f2(self, arg1, arg2=None, *args, **kwds): ... unique stuff #2 ... ... some common stuff #1 ... ret = arg1(args, *args, **kwds) ... more common stuff #2 ... return retval def f3(self, arg1, globals=None, locals=None): ... unique stuff #3 ... ... some common stuff #1 ... exec cmd in globals, locals ... more common stuff #2 ... return None def f4(self, arg1, globals=None, locals=None): ... unique stuff #4 ... ... some common stuff #1 ... execfile(args, globals, locals) ... more stuff #2 ... return None f1(...): "Docstring f1" c = C() return c.f1(...) f2(...): "Docstring f2" c = C() return c.f2(...) f3(...): "Docstring f3" c = C() return c.f3(...) Above there are two kinds of duplication: that within class C and that outside which creates an instance of the class C and calls the corresponding method. For the outside duplication, I considered trying: _call_internal = lambda name, *args, **kwds \ c = C() \ fn = getattr(c, name) \ return fn(*args, **kwds) f1 = lambda arg, arg2=None, globals=None, locals=None: _call_internal('f1', ...) f1.__doc__ = """ Docstring f1 """ f2= lambda arg, arg1=None, arg2, *args, **kwds: _call_internal('f2', ...) f2.__doc__ = """ Docstring f2 """ However this strikes me as a little bit cumbersome, and harder understand and maintain than the straightforward duplicated code. Thoughts? Lest the above be too abstract, those who want to look at the full (and redundant) code: http://code.google.com/p/pydbg/source/browse/trunk/api/pydbg/api/debugger.py From tjreedy at udel.edu Mon Dec 15 13:30:08 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 15 Dec 2008 13:30:08 -0500 Subject: stable algorithm with complexity O(n) In-Reply-To: <5504f9ac0812150828m14f6999ak6112c5975042dc88@mail.gmail.com> References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> <015612ac$0$20639$c3e8da3@news.astraweb.com> <52cfb77e-4baf-4fba-8eac-cc6c7ddb5be5@k1g2000prb.googlegroups.com> <5504f9ac0812150828m14f6999ak6112c5975042dc88@mail.gmail.com> Message-ID: Dan Upton wrote: > And if n is small and sparse (ie, k > n) , O(k*n) for radix sort could > be worse than O(n^2). You could also ask why people make such a big > deal about quicksort over mergesort, since mergesort has a guaranteed > O(n log n) time whereas quicksort can be O(n^2) on pathological cases. Python's current list.sort uses mergesort because it better exploits existing structure in a list. > I think I remember learning in my algorithms class that for small > sorts (n < ~40) , bubblesort can actually be the fastest (or close to > the fastest) in terms of wall-clock time because it has a relatively > small constant factor in its O(n^2) complexity. It uses binary insert sort for n < 64 (chosen empirically) . That also does O(n logn) comparisons and is only O(n**2) for data movement, which a decent C compiler translates into fast block-move assembly instructions. tjr From icanbob at gmail.com Sun Dec 14 07:32:46 2008 From: icanbob at gmail.com (bobicanprogram) Date: Sun, 14 Dec 2008 04:32:46 -0800 (PST) Subject: subprocess to C program References: <0ebd59c5-95a1-42d4-b597-d1c248490b8e@y1g2000pra.googlegroups.com> <8MidneyhDfIG-9nUnZ2dnUVZ_uadnZ2d@posted.visi> <36656830-63a8-479c-8c46-525f2b55eeea@z28g2000prd.googlegroups.com> Message-ID: <6e8f11eb-d773-4ffc-851c-a381228d4ae2@v4g2000yqa.googlegroups.com> On Dec 13, 10:09 pm, MRAB wrote: > Aaron Brady wrote: > > On Dec 13, 7:51 pm, Grant Edwards wrote: > >> On 2008-12-14, MRAB wrote: > > >>>> I am writing a C process and I want to read data from a file that I > >>>> write to in Python. I'm creating a pipe in Python, passing it to the > >>>> C process, and calling '_read'. It gives me error 9, bad file number. > > snip > >>>> meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9. I want 'ct' > >>>> to be 11 at this point. Thanks in advance. > >>> It looks like the ids aren't system global. > >> They certainly aren't in Unix: Their a property of the process. > > >> -- > >> Grant > > > I'm not on Unix. It has to be possible somehow. Do I need to set > > permissions on the IDs? Are Stdin and Stdout my only options? Or > > does Popen prevent sharing IDs somehow? > > You'd be better off using sockets. You might also consider using SIMPL (http://www.icanprogram.com/simpl) SIMPL has had a Python interface for about 5 years now. There is an online tutorial here. (http://www.icanprogram.com/06py/main.html) In one of your responses you mentioned that you were not on Unix (and I presume Linux). SIMPL-Python has recently been extended to work transparently from a Windows OS as well. bob SIMPL project coordinator From febaen at gmail.com Fri Dec 12 06:42:55 2008 From: febaen at gmail.com (febaen at gmail.com) Date: Fri, 12 Dec 2008 03:42:55 -0800 (PST) Subject: (Very Newbie) Problems defining a variable Message-ID: #!/usr/bin/python #Py3k, UTF-8 bank = int(input("How much money is in your account?\n>>")) target = int(input("How much money would you like to earn each year? \n>>")) interest = 0 i = 0 while interest < target: #determine the interest rate to use if bank >= 9999: rate = 0.006 elif bank >= 10000 and bank <= 24999: rate = 0.0085 elif bank >= 25000 and bank <= 49999: rate = 0.0124 elif bank >= 50000 and bank <= 99999: rate = 0.0149 elif bank >= 100000: rate = 0.0173 #Now that we know what interest rate to use, apply it... lastbank = bank #To calculate interest... bank += (bank * rate) #Update earnings... interest = bank - lastbank #And figure out how much interest is made! i += 1 #So we can see which year a calculation represents print("Year %s, at %s rate: %s paid, %s in bank." % (i, rate, interest, bank)) I wrote this expanding off an 'interest' exercise in a tutorial, which was fairly simple (assume %1, calculate for ten years). It's intended to take how much the user has in the bank and determine how long it will be until it generates a certain amount in interest each year. The problem is that rates are not solid, and increase at certain points. I put the rates from the basic account option at my bank in as an example. I'm pretty certain that that is also the problem in the code. I'm pretty sure it's a problem with the 'if' statements', and it looks like it's one of those mistakes that's so simple you look back on it and laugh at yourself. If you put in a bank number <= 9999, it fails, saying "NameError: name 'rate' is not defined". If you put in one higher, it runs correctly, but thinks that the rate is 0.006 I tried def'ing a function for it, which didn't work any better. I'm having a hard time figuring out exactly why it is those if statements are wrong. From ethan at stoneleaf.us Mon Dec 8 09:44:53 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 08 Dec 2008 06:44:53 -0800 Subject: dBase III files and Visual Foxpro 6 files In-Reply-To: <917126a8-c2c6-49c5-b001-07c953992dac@q26g2000prq.googlegroups.com> References: <917126a8-c2c6-49c5-b001-07c953992dac@q26g2000prq.googlegroups.com> Message-ID: <493D32E5.1030000@stoneleaf.us> sniffer wrote: > On Dec 8, 12:53 pm, Ethan Furman wrote: >> Greetings All! >> >> I nearly have support complete for dBase III dbf/dbt files -- just >> wrapping up support for dates. The null value has been a hindrance for >> awhile but I nearly have that solved as well. >> >> For any who know of a cool dbf module already in existence for dBase III >> and Visual Foxpro -- where were you six months ago when I was searching? >> ;) Seriously, though, this has been a great learning experience for me. >> >> As I said -- dbf/dbt files are 99% ready. idx files -- no support: for >> my purposes I just don't need them. I've found no problem in loading >> tables up to 300,000 records with 50 fields per record, and re-ordering >> them on the fly in memory. >> >> However, after putting much effort into this code, and wanting it to be >> useful to others in the community, are there others who work with dbf >> files that would need idx/cdx support? Or tables so large they won't >> fit comfortably into memory? >> >> ~ethan~ > > hi ethan, > great to hear that someone has finally written something for > interacting with vfp6 data,when do you plan to release it Well, let's see... A couple more days to have the datetime bit worked out (I don't support datetimes prior to 1981 in vfp tables), longer for currency types, and of course, no idx/cdx support at this point. Tell you what -- I'll trade you a copy of the code as it stands with date and datetime working for null values, for an answer of whether you need idx/cdx file support. ;) ~ethan~ From timr at probo.com Sun Dec 28 00:46:29 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 28 Dec 2008 05:46:29 GMT Subject: parsing csv files class References: Message-ID: "alex goretoy" wrote: > >class parsercsvy(object): > """Return a line from a csv file or total amount of lines""" > def __init__(self,file_name=""): > self.func_me_color="white_on_black" > self.soc=stdout_colours.stdout_colors() > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > self.filename = file_name > self.buffer = [] > self.bufferp= [] > if string.find(self.filename,"http") != -1: > resp=urllib2.urlopen(self.filename) > file=resp.read() > lfi=len(string.split(self.filename,"/")) > filename = "/tmp/"+string.split(self.filename,"/")[lfi-1] Style issue: unless you are running Python 1.x, you virtually never need to import the "string" module. Also, you can always refer to the last element of a list or tuple by using [-1]: parts = self.filename.split( "/" ) filename = "/tmp/" + parts[-1] > def parse(self,filename,ret=0): > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > i = 0 > try: > reader = csv.reader(file(filename, "rb")) > try: > for row in reader: > self.buffer.append(row) > s,a=[],{} > > for j in range(len(self.buffer[0])): > a[self.buffer[0][j]]=row[j] > self.bufferp.append(a) > i+=1 > self.total = i-1 You might consider keeping the header line separate. reader = csv.reader(open(filename, "rb")) header = reader.next() self.buffer = list(reader) self.bufferp = [ dict( zip( header, line ) ) for line in reader ] self.header = header Also, you don't really need a separate "total" variable, since it's equal to len(self.buffer). > def total(self): > """return total number of lines in csv file""" > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > self.soc.me_him(['RETURN:',self.total,__name__],self.func_me_color) > return self.total There's a problem here, as this was originally written. "self.total" starts out being a function (this one here). But after self.parse runs, "self.total" will be an integer, and this function is lost. You need to decide whether you want users to just access the self.total integer, or force them to use the function. In the latter case, you can change the counter to self._total. On the other hand, the self.total counter is unnecessary: def total(self): return len(self.buffer) > def find_and_replace(self,li,fi,re): > """ > find and replace a string inside a string, return list > find_and_replace(list,find,replace) > """ > this=[] > for l in li: ># found_index=string.find(l,fi) > this.append(l.replace(fi,re)) > return this def find_and_replace(self,li,fi,re): return [l.replace(fi,re) for l in li] I'm not sure why this is a member of the class; it doesn't use any of the members. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From duncan.booth at invalid.invalid Tue Dec 9 13:55:05 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Dec 2008 18:55:05 GMT Subject: When (and why) to use del? References: Message-ID: Albert Hopkins wrote: > def otherfunction(): > try: > # some stuff > except SomeException, e: > # more stuff > del e > return > > > I think this looks ugly, but also does it not hurt performance by > preempting the gc? My feeling is that this is a misuse of 'del'. Am I > wrong? Is there any advantage of doing the above? > It is probably a complete waste of time, but there are situations where code similar to this can be useful: def otherfunction(): try: # some stuff except SomeException, e: # more stuff del e raise return The point of code like this is that when a function exits by throwing an exception the traceback includes a reference to the stack frame and all the local variables. In some situations that can result in large data structures not being freed for a very long time (e.g. until another exception is thrown that is handled at the same level). So, *in very specialised situations* it may be important to delete particular names from the local namespace. From steve at REMOVE-THIS-cybersource.com.au Tue Dec 2 05:27:00 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Dec 2008 10:27:00 GMT Subject: optimization References: Message-ID: <0145054b$0$20670$c3e8da3@news.astraweb.com> On Mon, 01 Dec 2008 18:11:16 -0600, Robert Kern wrote about nested functions: > I, for one, find that significantly less clear. I only expect functions > to be defined inside of functions if they are going to use lexical > scoping for some reason. If I read your code, I'd probably waste a good > five minutes trying to figure out what part of the local scope you were > using before I would conclude that you just did it because you thought > it looked better. Hah, I bet you aren't an ex-Pascal programmer :-) Speaking as one, it took me a long time to teach myself not to bother nesting functions for the purpose of avoiding scoping clashes. I'd write something like this: def parrot(): def colour(): return "Blue" return "Norwegian %s" % colour() def cardinal(x): def colour(): return "crimson" return "Cardinal Fang wears a %s robe" % colour() Except of course that's a trivially silly example. (For the sake of the argument, let's pretend the two functions colour() do actual calculations.) These days, I'd write them something like this: def parrot_colour(): return "Blue" def cardinal_colour(): return "crimson" def parrot(): return "Norwegian %s" % parrot_colour() def cardinal(x): return "Cardinal Fang wears a %s robe" % cardinal_colour() These days, almost the only time I use nested functions is for function factories. -- Steven From cousinstanley at gmail.com Wed Dec 10 11:28:50 2008 From: cousinstanley at gmail.com (Cousin Stanley) Date: Wed, 10 Dec 2008 17:28:50 +0100 (CET) Subject: [OT] Google Groups in bad odour References: <4d5498bf-bbf0-4760-83fc-610729bcbce2@h20g2000yqn.googlegroups.com> Message-ID: > .... > I will therefore have to find a suitable news client. > Any recommendations ? Frank .... You might try the python-based xpn news client .... http://xpn.altervista.org/index-en.html To thine own snake be true .... :-) -- Stanley C. Kitching Human Being Phoenix, Arizona From rhamph at gmail.com Wed Dec 10 13:39:40 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Wed, 10 Dec 2008 10:39:40 -0800 (PST) Subject: Rich Comparisons Gotcha References: Message-ID: On Dec 10, 7:49?am, Rasmus Fogh wrote: > Rhamphoryncus wrote: > > You grossly overvalue using the "in" operator on lists. > > Maybe. But there is more to it than just 'in'. If you do:>>> c = numpy.zeros((2,)) > >>> ll = [1, c, 3.] > > then the following all throw errors: > 3 in ll, 3 not in ll, ll.index(3), ll.count(3), ll.remove(3) > c in ll, c not in ll, ll.index(c), ll.count(c), ll.remove(c) > > Note how the presence of c in the list makes it behave wrong for 3 as > well. All of these are O(n). Use a set or dict. What is your use case anyway? > > It's far more > > common to use a dict or set for containment tests, due to O(1) > > performance rather than O(n). ?I doubt the numpy array supports > > hashing, so an error for misuse is all you should expect. > > Indeed it doees not. So there is not much to be gained from modifying > equality comparison with sets/dicts. > > > In the rare case that you want to test for identity in a list, you can > > easily write your own function to do it upfront: > > def idcontains(seq, obj): > > ? ? for i in seq: > > ? ? ? ? if i is obj: > > ? ? ? ? ? ? return True > > ? ? return False > > Again, you can code around any particular case (though wrappers look like > a more robust solution). Still, why not get rid of this wart, if we can > find a way? The wart is a feature. I agree that it's confusing, but the cost of adding a special case to work around it is far in excess of the original problem. Now if you phrased it as a hypothetical discussion for the purpose of learning about language design, that'd be another matter. From theller at python.net Fri Dec 19 12:53:22 2008 From: theller at python.net (Thomas Heller) Date: Fri, 19 Dec 2008 18:53:22 +0100 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> Message-ID: <6r25ckFejl4vU1@mid.individual.net> Steve Holden schrieb: > Thomas Heller wrote: >> Question from a non-native english speaker: is this now valid english? >> >> "One of Python?s great strengths" >> ^ >> "and also teaches Python?s functional programming features" >> ^ >> "The book?s approach is wholly practical" >> ^ > It always has been valid English. The apostrophe is only omitted from > personal pronouns (hers, its, and so on). I see, thanks. But, is the apostrophe optional in the above fragments? Thomas From castironpi at gmail.com Tue Dec 30 11:11:20 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 30 Dec 2008 08:11:20 -0800 (PST) Subject: thread, multiprocessing: communication overhead References: Message-ID: On Dec 30, 9:46?am, mk wrote: > Hello everyone, > > This time I decided to test communication overhead in multithreaded / > multiprocess communication. The results are rather disappointing, that > is, communication overhead seems to be very high. In each of the > following functions, I send 10,000 numbers to the function / 10 threads > / 10 processes, which simply returns it in its respective way. > > Function: notfun ? ? ? ? ? ?Best: 0.00622 sec ? Average: 0.00633 sec > (simple function) > > Function: threadsemfun ? ? ?Best: 0.64428 sec ? Average: 0.64791 sec > (10 threads synchronizing using semaphore) > > Function: threadlockfun ? ? Best: 0.66288 sec ? Average: 0.66453 sec > (10 threads synchronizing using locks) > > Function: procqueuefun ? ? ?Best: 1.16291 sec ? Average: 1.17217 sec > (10 processes communicating with main process using queues) > > Function: procpoolfun ? ? ? Best: 1.18648 sec ? Average: 1.19577 sec > (a pool of 10 processes) > > If I'm doing smth wrong in the code below (smth that would result in > performance suffering), please point it out. snips > def threadsemfun(): > ? ? ? ? ?sem = threading.Semaphore() > def threadlockfun(): > ? ? ? ? ?sem = threading.Semaphore() You used a Semaphore for both lock objects here. 'multiprocessing' is a really high level layer that makes a lot of decisions about trade-offs, has highly redundant communication, and is really easy to use. If you want to save a byte, you'll have to make your own decisions about trade-offs and redundancies (possibly even looking at real result data to make them). I actually think 'multiprocessing' is really good, and even if I hand- wrote my own IPC, it would be slower! CMIIW, but I believe your timing function includes the time to launch the actual processes and threads, create the synch. objects, etc. You might try it again, creating them first, starting the timer, then loading them. From lie.1296 at gmail.com Sun Dec 7 15:07:56 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 7 Dec 2008 20:07:56 +0000 (UTC) Subject: Brain going crazy with recursive functions References: <6470511f-093e-42c2-a6c2-4bb90b336ac9@r15g2000prd.googlegroups.com> Message-ID: On Sat, 06 Dec 2008 23:33:35 -0800, 5lvqbwl02 wrote: > I'm trying to solve the 9-tile puzzle using as functional an approach as > possible. I've recently finished reading SICP and am deliberately > avoiding easy python-isms for the more convoluted scheme/functional > methods. The following function is trivial to do with for loops and > directly accessing arrays with [] syntax. I'm trying to limit myself to > the types of idioms/semantics one finds in minimal scheme, such as in > SICP. I want eventually to port this to scheme, but I know python > better, so that's where I'm starting. > > My current problem is the following. The 9-tile puzzle consists of a > list of lists like this [[1,2,3],[4,5,6],[7,8,0]], where the numbers can > be jumbled up. I'm looking for the location of the zero using *only* > recursion and operators that are similar to car/cdr. The return value > should be the row,col of the zero. For example above the > return value would be (2,2). > > I'm also trying to define a single "linear_search(...)" function which > does the search for within the row (an inner list above) and within the > whole list. linear_search takes as an argument a "truth_function" > which does the actual work. What's tricky is that the truth function > for the array-as-a-whole is also the linear_search for a row. Once I'm > in linear_search for the array, I also call linear_search for each > row. > > The problem is the line where it says acc.insert(0,idx) looks fishy to > me. It works fine and returns the row,col of the location of the zero > tile, but it seems to be mutating a variable, and that's the thing I'm > trying to avoid. In a sense, it's not hard enough and python is making > this too easy :) (although it took a bit of mind-wrenching to get to > this point. Recursion makes you either dumber or smarter, I'm not sure > which). > > How do I accumulate the inner value of the search so it pops out at the > end, without resorting to a mutable variable? I did a bit of search and > the word "monad" came up, but I'm not sure what that is (I know it > relates to haskell and some other purely functional stuff, but > I get very lost when trying to read that stuff). > > > > > def linear_search(array, truth_func, acc): > # Goes through each element of array and applies truth_func. # Returns > index if found, otherwise returns None def linear_search_iter(idx, > truth_func, arr, acc): > if arr: > tf = truth_func(arr[0]) > if tf or type(tf) is int: > acc.insert(0,idx) > return idx, acc+[idx] > else: > return linear_search_iter(idx+1, truth_func, arr[1:], acc) > return linear_search_iter(0, truth_func, array, acc) > > > > def locate_zero(p): > # Locates empty tile. Returns (r,c) tuple def find_zero_in_row (row): > return linear_search(row, lambda x: x==0, acc) > > acc = [] > ls = linear_search(p, find_zero_in_row, acc) print acc > return acc > > locate_zero([[5, 3, 4], [2, 0, 1], [8, 6, 7]]) correctly returns (1,1) In most functional languages, their natural data types differs. For example, Haskell's list is a linked list, which if expressed in python would look like this: Python: [1, 2, 3, 4, 5] Haskell-in-Python: [1, [2, [3, [4, [5, []]]]]] linked list is more natural to use with recursive functions, so your locate zero would be like this: def search_tile(row, depth = 0): head, tail = row if head == 0: return depth elif len(tail) == 0: return None else: return search_tile(tail, depth + 1) def search_row(grid, depth = 0): head, tail = grid st = search_tile(head) if st is not None: return depth, st elif tail == []: return None else: return search_row(tail, depth + 1) Now, you noticed that lots of the code is similar, we want to generalize it. It's easy: def search_linear(list_, checker, depth = 0): head, tail = list_ if checker(head): return depth, () if checker(head) is True else checker(head) # I intentionally doesn't factor out checker(head) # as most functional language would automatically # do so because side-effect is impossible elif tail == (): return () else: return search_linear(tail, checker, depth + 1) data = (1, (2, (3, (0, ())))) print search_linear(data, lambda x: x == 0) # (3, ()) data = (0, (2, (3, (4, ())))) print search_linear(data, lambda x: x == 0) #(0, ()) data = (1, (2, (3, (4, ())))) print search_linear(data, lambda x: x == 0) #() data = ((5, (3, (4, ()))), ((2, (0, (1, ()))), ((8, (6, (7, ()))), ()))) print search_linear(data, lambda row: search_linear(row, lambda tile: tile == 0)) #(1, (1, ())) From jcd at sdf.lonestar.org Thu Dec 18 10:03:44 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Thu, 18 Dec 2008 10:03:44 -0500 Subject: help I'm getting delimited In-Reply-To: <0de3a7bf-a4c4-4103-a4e0-44313405fa94@z28g2000prd.googlegroups.com> References: <1229445534.5328.0.camel@linux-3eb6.site> <0d9ea7cc-b5fb-4edb-be32-490aae9e7204@b41g2000pra.googlegroups.com> <0de3a7bf-a4c4-4103-a4e0-44313405fa94@z28g2000prd.googlegroups.com> Message-ID: <1229612624.5928.15.camel@aalcdl07.lib.unc.edu> On Wed, 2008-12-17 at 06:28 -0800, aka wrote: > Hi John, thanks. > You're right, I didn't past the method header because I thought it > didn't matter when the input filename is hardcoded. > The try/except isn't very helpful indeed so I commented it out. > You're right I wrongly referred to the UnicodeReader > class in my first post because that's ultimately where I want to go > so > I outcommented it here for you to see. > The fact is that neither csv.reader nor the UnicodeReader will read > the file, while writing with the UnicodeWriter > works like a charm. > That's why I put str() around roles to see any content. > I simplified the csv-file by cutting off columns without result. The > file looks now like: > > id;company;department > 12;Cadillac;Research > 11;Ford;Accounting > 10;Chrysler;Sales > > > The dictionary on the return is because this code is part of my > TurboGears application. > The entire method is: > > > import csv > from utilities.urw import UnicodeWriter, UnicodeReader > > > @expose(allow_json=True) > def import_roles(self, input=None, *args, **kwargs): > inp = 'C:/temp/test.csv' > roles = [] > msg = '' > ## try: > fp = open(inp, 'rb') > reader = csv.reader(fp, dialect='excel', delimiter=';') > ## reader = UnicodeReader(fp, dialect='excel', delimiter=';') > for r in reader: > roles.append(r[0]) > fp.close() > ## except: > ## msg = "Something's wrong with the csv.reader" > return dict(filepath=inp, > roles=str(roles), > msg=msg) > > > csv.reader results in: for r in reader: Error: line contains NULL > byte > > > Use of UnicodeReader results in: UnicodeDecodeError: 'utf8' codec > can't decode byte 0xff in position 0: unexpected code byte > This looks like the problem might be in your choice of codec. A UTF-8 file will never have 0xff in it, and would be unlikely to have 0x00 either. My guess is that you will need to decode your input from UTF-16. (and then use the UnicodeReader). > > Will post only complete code from now on thanks. > > -- > http://mail.python.org/mailman/listinfo/python-list > From info at egenix.com Tue Dec 2 05:10:38 2008 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Tue, 02 Dec 2008 11:10:38 +0100 Subject: ANN: eGenix mxODBC Connect - Python Database Interface 1.0.0 Message-ID: <4935099E.6080708@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com mxODBC Connect Python Database Interface Version 1.0.0 Our new client-server product for connecting Python applications to relational databases - from all major platforms This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-mxODBC-Connect-1.0.0-GA.html ________________________________________________________________________ INTRODUCTION The mxODBC Connect Database Interface for Python allows users to easily connect Python applications to all major databases on the market today in a highly portable and convenient way. Unlike our mxODBC Python extension, mxODBC Connect is designed as client-server application, so you no longer need to find production quality ODBC drivers for all the platforms you target with your Python application. Instead you use an easy to install Python client library which connects directly to the mxODBC Connect database server over the network. This makes mxODBC Connect the ideal basis for writing cross-platform database programs and utilities in Python, especially if you run applications that need to communicate with databases such as MS SQL Server and MS Access, Oracle Database, IBM DB2 and Informix, Sybase ASE and Sybase Anywhere, MySQL, PostgreSQL, SAP MaxDB and many more, that run on Windows or Linux machines. By removing the need to install and configure ODBC drivers on the client side, mxODBC Connect greatly simplifies setup and configuration of database driven client applications, while at the same time making the network communication between client and database server more efficient and more secure. For more information, please see the product page: http://www.egenix.com/products/python/mxODBCConnect/ ________________________________________________________________________ NEWS mxODBC Connect 1.0.0 is the first general availability release of our new mxODBC Connect product. With this release we have further improved the performance and round-trip times of the mxODBC Connect network layer even more. We are now able to achieve a *more than 10 times better performance* for a typical multi-tier application that runs on Linux and connects to a MS SQL Server database running on a Windows host, compared to the same application using mxODBC and the FreeTDS ODBC driver. Thanks to everyone who participated in the public beta ! ________________________________________________________________________ DOWNLOADS The download archives as well as instructions for installation and configuration of the product can be found on the product page: http://www.egenix.com/products/python/mxODBCConnect/ Evaluation licenses for the server part are available free of charge: http://www.egenix.com/products/python/mxODBCConnect/#Evaluation The client part of mxODBC Connect is always free of charge. _______________________________________________________________________ SUPPORT Commercial support for this product is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 02 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-12-02: Released mxODBC.Connect 1.0.0 http://python.egenix.com/ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From steve at REMOVE-THIS-cybersource.com.au Tue Dec 2 08:47:14 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Dec 2008 13:47:14 GMT Subject: Do more imported objects affect performance References: <1be78d220812010621u51dead9dnbaa0b4c8c9414362@mail.gmail.com> <79153a2e0812012124o7401df57m4ac21dfe37c2ec5@mail.gmail.com> Message-ID: <01453438$0$20670$c3e8da3@news.astraweb.com> On Tue, 02 Dec 2008 11:12:31 +0000, Nick Craig-Wood wrote: > I prefer the "from module import function". That means that if "module" > doesn't supply "function" it raises an exception at compile time, not > run time when you try to run "module.function". Wanna bet? >>> def spam(): ... from math import harmonic_series ... return harmonic_series() ... >>> dis.dis(spam) 2 0 LOAD_CONST 1 (-1) 3 LOAD_CONST 2 (('harmonic_series',)) 6 IMPORT_NAME 0 (math) 9 IMPORT_FROM 1 (harmonic_series) 12 STORE_FAST 0 (harmonic_series) 15 POP_TOP 3 16 LOAD_FAST 0 (harmonic_series) 19 CALL_FUNCTION 0 22 RETURN_VALUE >>> spam() Traceback (most recent call last): File "", line 1, in File "", line 2, in spam ImportError: cannot import name harmonic_series The same thing happens if the from...import is at the top level of the module, except that compilation is immediately followed by execution. > It then becomes very > easy to see which functions you use from any given module too. If that's important to you. Personally, I find it more useful to know where a function is defined. -- Steven From arnodel at googlemail.com Fri Dec 5 16:59:11 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 05 Dec 2008 21:59:11 +0000 Subject: Overriding a method at the instance level on a subclass of a builtin type References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> Message-ID: Arnaud Delobelle writes: [...] > class ClassGetItem(object): > def __get__(self, obj, objtype=None): > return obj._getitem_ > def __set__(self, obj, val): > obj._getitem_ = val > > class GetItem(object): > def __get__(self, obj, objtype=None): > return obj._getitem_ > def __set__(self, obj, val): > obj._getitem_ = val It's funny how the brain works. I didn't realise both classes were the same until I read my own post! [...] -- Arnaud From Chris.Rathman at gmail.com Wed Dec 10 21:43:07 2008 From: Chris.Rathman at gmail.com (Chris Rathman) Date: Wed, 10 Dec 2008 18:43:07 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <5ebe5a7d-cbdf-4d66-a816-a7d2a0a273c9@40g2000prx.googlegroups.com> Message-ID: <16459ac1-32b7-408c-80ff-16469af4228a@l33g2000pri.googlegroups.com> On Dec 10, 6:51?pm, Xah Lee wrote: > I've now gather code solutions in ruby, python, C, Java, here: > > now lacking is perl, elisp, which i can do well in a condensed way. > It'd be interesting also to have javascript... and perhaps erlang, > OCaml/F#, Haskell too. Pay me $600 for my time and I'll even throw in an Algol-68 version. :-) From knabberknusperhaus at yahoo.de Thu Dec 25 08:56:10 2008 From: knabberknusperhaus at yahoo.de (KKH) Date: Thu, 25 Dec 2008 13:56:10 +0000 (GMT) Subject: Getting a locked buffer from objects (PEP 3118) Message-ID: <603279.94632.qm@web24403.mail.ird.yahoo.com> Hi, it seems the whole locking-theme has gone from PEP 3118 (PyBUF_LOCK is gone). Yet the string and byte objects seem to provide locked buffers through PyArg_Parse arguments s*, y* and z* (documentation says so). Could someone please clarify the situation for me: Is it save to release the GIL after getting a reference to a buffer-object by the arguments above and only talking to this buffer while the GIL is gone? And while we are at it :-) Is "PyArg_Parse('[syz]*'..." the only way to get a locked buffer-view from string/byte objects? Regards ebfe From rt8396 at gmail.com Tue Dec 23 11:38:05 2008 From: rt8396 at gmail.com (r) Date: Tue, 23 Dec 2008 08:38:05 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: Benjamin Kaplin wrote: You're the one who keeps bringing up the need to spread python. For most people, this is a forum to ask questions and have experts respond to them. Most people who post here aren't looking for your opinion, they want answers. If you know the answer to a question, answer it. If not, read the answers of people who have seen it before. When you post your opinions, you're just creating more noise. School time son, This forum is much more than a question answer session, son. Sure people are welcome to ask a Python related question. But this forum is really the main highway of Python development and future. If your a n00b go to the "Python forum.org", you will feel more comfy over there. If you have no opinion(Benjamin) thats your perogitive, don't tell me how to live my life, or what "I" should do when i visit this forum. Do I go to any of "your" threads and start a ruckus? NO, because if i do not like what you are saying I will just ignore it. Take an example son! Sure i may have went off in thread, by i have kept my thought true to the thread subject. A troll go's from thread to thread posting off subject insults and attacks on other posters... hmmm, i have seen some of those kind in this thread?? Know of who i speak, Bennie? From martin at v.loewis.de Sat Dec 13 17:20:33 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 13 Dec 2008 23:20:33 +0100 Subject: Python 3.0 crashes displaying Unicode at interactive prompt In-Reply-To: References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> Message-ID: <49443531.5050304@v.loewis.de> >> This is intended behavior. > > I see. That means that the behaviour in Python 1.6 to 2.6 (i.e. > encoding the text using the repr() function (as then defined) was not > intended behaviour? Sure. This behavior has not changed. It still uses repr(). Of course, the string type has changed in 3.0, and now uses a different definition of repr. Regards, Martin From fetchinson at googlemail.com Sat Dec 27 16:45:38 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 27 Dec 2008 13:45:38 -0800 Subject: C API: array of floats/ints from python to C and back Message-ID: I'm trying to write an extension module in C which contains a single function with the following prototype: void func( int N, int * arg1, int * arg2, int * ret ); Here arg1 and arg2 are length N arrays, and the function computes ret which is also an N length array. From python I'd like to call this function as ret = func( [ 1, 2, 3 ], [ 2, 3, 4] ) I've read through the docs at http://docs.python.org/extending/extending.html and also http://docs.python.org/c-api/arg.html from which I learned how to pass a fixed number of basic datatypes (int, float, string) from python to C and back. What I don't know is how to pass an array back and forth. As far as I can see PyArg_ParseTuple is the function I should use for converting the python arguments to C but the format string passed to PyArg_ParseTuple can only be one of the basic data types ("s", "i", etc) or a generic python object ("O"). Does this mean that I can only pass the arrays from python to C as generic python objects and in a later operation I need to get the elements from this generic python object, construct a C array and pass that to the C function? Since I assume this is a frequent operation I'd think there are some shortcuts, aren't there? Or what's the simplest way of doing this? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From cournape at gmail.com Fri Dec 12 09:27:43 2008 From: cournape at gmail.com (David Cournapeau) Date: Fri, 12 Dec 2008 23:27:43 +0900 Subject: Python is slow In-Reply-To: <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> Message-ID: <5b8d13220812120627l5e5a4657i6406d47ac17a5562@mail.gmail.com> On Fri, Dec 12, 2008 at 11:04 PM, Luis M. Gonz?lez wrote: > It has been mentioned in this thread the pypy project (isn't it enough > for you??) Since pypy can't be used today for most production use (most python packages can't work on it), I don't see how it could be enough for anyone interested in solving problems today. I want faster function calls to use with numpy: do you know of any solution ? Pypy certainly isn't, at least today. cheers, David From deets at nospam.web.de Sat Dec 20 06:52:34 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 20 Dec 2008 12:52:34 +0100 Subject: PIL on 3.x? In-Reply-To: <494c0ad4$0$4096$ba4acef3@news.orange.fr> References: <3892784c-ddf4-4451-bcfd-dbc58b9b55f8@e1g2000pra.googlegroups.com> <494c0ad4$0$4096$ba4acef3@news.orange.fr> Message-ID: <6r44k2Fff3hbU1@mid.uni-berlin.de> M?ta-MCI (MVP) schrieb: > Hi! > > This info is interesting for many people. > IMO, it's a good idea to write the question in this newsgroup. Which only makes sense if the author of PIL reads it. Which he seems not to (or at least doesn't answer here, as he used to). Diez From antoine at vo.lu Tue Dec 9 06:53:49 2008 From: antoine at vo.lu (Antoine De Groote) Date: Tue, 09 Dec 2008 12:53:49 +0100 Subject: primera In-Reply-To: <16149$493e58b1$d9a2276f$4726@news.hispeed.ch> References: <16149$493e58b1$d9a2276f$4726@news.hispeed.ch> Message-ID: <2cac8$493e5c4d$d9a2276f$7521@news.hispeed.ch> Oops, sorry, this message was not intended for the group. Apologies Antoine De Groote wrote: > zalli, > > du spills jo net mat am volley oder? mengs de du kinns dann mat mengem > auto an den MCM an eventuell op sandweiler fueren? well m?indes ass > volley, densdes fussball, an mettwochs ass schon hellejen owend... > > nuecht > antoine From nospam at forMe.thks Mon Dec 15 10:21:03 2008 From: nospam at forMe.thks (Ross) Date: Mon, 15 Dec 2008 10:21:03 -0500 Subject: Managing timing in Python calls Message-ID: I'm porting some ugly javascript managed stuff to have an equivalent behaviour in a standalone app. It uses events that arrive from a server, and various small images. In this standalone version, the data is local in a file and the images in a local directory. My AJAX code managed a timely presentation of the info, and in the Javascript that relied on the ugly: myImage.onload = function(){dosomething_when_it's_finished} structure. Also, I used the similarly unpretty: var t = window.setTimeout( function () { do_when_timed_out} structures which allows stuff to happen after a perscribed period. In my python implementation my first guess is to use a thread to load my image into a variable myImage = wx.Image("aPic.gif", wx.BITMAP_TYPE_GIF ).ConvertToBitmap() so that it won't block processing. (Though perhaps it'll just happen so fast without a server involved that I won't care.) Is there a nice equivalent of a 'setTimeout' function in python? ie to call a function after some time elapses without blocking my other processing? I suppose just a thread with a time.sleep(x_mS) in it would be my first guess? Can anyone give me some feedback on whether that's a logical path forward, or if there are some nicer constructs into which I might look? Thanks for any suggests... Ross. From benjamin.kaplan at case.edu Sun Dec 14 12:09:33 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 14 Dec 2008 12:09:33 -0500 Subject: 1 or 1/0 doesn't raise an exception In-Reply-To: References: <49446E39.6020807@tim.thechases.com> Message-ID: On Sun, Dec 14, 2008 at 2:38 AM, Gabriel Genellina wrote: > En Sun, 14 Dec 2008 02:40:10 -0200, Benjamin Kaplan > escribi?: > > On Sat, Dec 13, 2008 at 10:49 PM, Daniel Fetchinson < >> fetchinson at googlemail.com> wrote: >> >> >> Is it a feature that >>> >> >>> >> 1 or 1/0 >>> >> >>> >> returns 1 and doesn't raise a ZeroDivisionError? If so, what's the >>> >> rationale? >>> > >>> > http://en.wikipedia.org/wiki/Short-circuit_evaluation >>> >>> Let me just point out that unsuspecting people (like me) might rely on >>> the whole expression to be evaluated and rely on exceptions being >>> raised if needed. >>> >> >> If you want both expressions evaluated, you can use & and |, just like in >> C >> and Java (&& and || are used for short circuit evaluation in those >> languages). >> > > No: &, | (and ^, too) perform bitwise operations in Python, C and Java: > Perhaps I should have mentioned that you have to restrict yourself to bools (or 0 and 1) when doing this. I know that they perform bitwise operations when you do them with ints- I was assuming the OP was dealing with bools. > > py> 1 & 2 > 0 > > && and || --in both C and Java-- are like `and` and `or` in Python; they > perform logical operations, and short-circuit evaluation of their operands. > If you want to evaluate a logical expression without short circuiting, do > that explicitely: > > a = first part > b = second part > if a or b: ... > > -- > Gabriel Genellina > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Russ.Paielli at gmail.com Sat Dec 6 11:01:40 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 6 Dec 2008 08:01:40 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> <8b8d1fb3-f49e-49bf-8cfe-eeee5ed16109@r37g2000prr.googlegroups.com> <014a932b$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Dec 6, 7:34?am, Steven D'Aprano wrote: > On Sat, 06 Dec 2008 07:15:27 -0800, Russ P. wrote: > > On Dec 6, 4:32?am, Andreas Waldenburger wrote: > >> On Sat, 6 Dec 2008 04:02:54 -0800 (PST) bearophileH... at lycos.com wrote: > > >> > class C: > >> > ? ? def $method(arg): > >> > ? ? ? ? $value = arg > > >> > (Note there's no point after $, it's not currently possible). > > If -- and that's a HUGE if -- the compiler is changed to allow $method, > it could certainly be changed to allow $.method. > > >> > Ruby > >> > uses @ and @@ for similar purposes. I agree that the code looks > >> > worse, but also shorter to read and write, so in lines of code that > >> > use many instance attributes, that short $ syntax helps keep the line > >> > shorter. So I may grow to accept this sugar... > > If a line of code uses too many instance attributes to fit comfortably on > a line, spread it over two lines. There is no newline shortage, they are > a renewable resource. > > >> But that is not the way Python is meant to work. There are several > >> tennets in the Zen of Python that don't chime well with this approach. > >> "self" is a speaking identifier, "$" isn't. > > > Is "@" a "speaking identifier? How about "#" and "!="? Last I heard, > > they were all part of Python. > > Yes they are. > > @f > > is pronounced "at f" or "decorate f". > > # comment > > is pronounced "hash comment" or even not pronounced at all. > > x != y > > is pronounced "x not equal to y" > > The proposed > > def $method(arg): > > would be pronounced "def dollar method arg" or "def method self arg". The > first is ugly to my ears, the second confusing. Regarding "$" as a stand-in for "self" is less of a stretch than the examples you gave. > -2 on this proposal. Did you get two votes in the Presidential election too? 8^) From bj_666 at gmx.net Sat Dec 20 06:14:31 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 20 Dec 2008 11:14:31 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <1332da3c-8075-4552-9498-3ceb23faca8f@v31g2000vbb.googlegroups.com> Message-ID: <6r42cnFfc57aU1@mid.uni-berlin.de> On Fri, 19 Dec 2008 17:12:00 -0800, r wrote: > Marc, > Why move away from a concise and widely accepted way of sting > formatting, just to supposedly make it a little easier for n00bs? (which > i disagree this is easier) In turn, creating more syntactical clutter. > (%s %f %d) is all you need to remember. If people can't understand that, > i fear for the future of Humans as a species! Yeah, doomsday is near. Curly brackets and a number instead of a percent sign followed by an 's' is a sure sign of the end? You're a funny little troll, Sir. Ciao, Marc 'BlackJack' Rintsch From benjamin.kaplan at case.edu Sat Dec 13 16:13:29 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sat, 13 Dec 2008 16:13:29 -0500 Subject: Python is slow In-Reply-To: <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> Message-ID: On Sat, Dec 13, 2008 at 3:35 PM, sturlamolden wrote: > On 10 Des, 19:42, cm_gui wrote: > > > And it is not just this Python site that is slow. There are many many > > Python sites which are very slow. And please don't say that it could > > be the web hosting or the server which is slow ? because when so many > > Python sites are slower than PHP sites, it couldn't be the web > > hosting. Also, Zope/Plone is even slower. > > > > Python is slow. Very slow. > > > By the way... I know of a very slow Python site called YouTube.com. In > fact, it is so slow that nobody ever uses it. > And there's also a web crawler written in Python, used by a site called Google, that's so slow that the search engine gives very few results. > > > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Fri Dec 26 17:27:52 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 26 Dec 2008 20:27:52 -0200 Subject: strange behavior of math.sqrt() in new 3.0 version References: Message-ID: En Fri, 26 Dec 2008 19:52:24 -0200, escribi?: > I'm a newbee trying 3.0 Please help with math.sqrt() > > At the command line this function works correctly > >>> import math > n = input("enter a number > ") > s = math.sqrt(n) > An entry of 9 or 9.0 will yield 3.0 > > Yet the same code in a script gives an error message > Script1 > import math > n = input("enter a number > ") > s = math.sqrt(n) > Traceback (most recent call last) : > File "", line 1, in > File "script1.py" line 3 in > s = math.sqrt(n) > TypeError : a float is required > Entering 9 or 9.0 gives same error message. > > According to the math module the results of all > functions are floats. However it says nothing about > inputs. > > Strangely the above code runs fine in version 2.5 ( ? ) > and will handle large integers. > > I've read the documentation for 3.0 including the section > "Floating Point Arithmetic: Issues & Limitations" and it > helps nada. And you won't find nothing - the change is in "input" behavior, not in the math functions. For versions prior to 3.0, there are: raw_input(message) -> string typed input(message) -> result of evaluating the string typed raw_input just returns whatever you type, as a string. Using the input function, Python evaluates whatever you type to obtain a result: if you type the three characters "nine" "dot" "zero" the result is the double 9.0; you can even type (17+1)/2.0 to get the same value (try it with your Python 2.5) Since version 3.0, input behaves as raw_input in the older versions, and there is no builtin function equivalent to the old input function. Use this instead: n = float(input("enter a number > ")) -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Tue Dec 30 20:15:35 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Dec 2008 01:15:35 GMT Subject: Triple quoted string in exec function ? References: <495A253B.6010003@gmail.com> Message-ID: <016abeb8$0$6988$c3e8da3@news.astraweb.com> On Tue, 30 Dec 2008 21:16:39 +0100, Stef Mientki wrote: > I guess I've to remove all triple quoted strings from my code. There's no problem with triple-quoted strings. You just have to quote them properly. >>> text = """x = 1 ... y = x+2 ... del x ... print y ... """ >>> exec text 3 You can even embed triple-quoted strings inside the string to be executed. >>> text = "s = '''%s'''" % """This is a ... triple quoted ... string""" >>> >>> exec text >>> s 'This is a\ntriple quoted\nstring' If you're going to remove anything, I'd look at why you are using exec in the first place. To me, it's a code smell -- not necessarily wrong, but exec is awfully open to abuse and potential security flaws. -- Steven From ldo at geek-central.gen.new_zealand Fri Dec 5 05:32:49 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 05 Dec 2008 23:32:49 +1300 Subject: Don't you just love writing this sort of thing :) References: Message-ID: In message , Duncan Booth wrote: > ... but the mess you posted is going to be virtually untestable ... The "mess" I posted did actually work as written. > ... whereas splitting it up into small testable functions will make it > much easier for you to actually get somewhere near your goal of correct > code. The code people write is probably a direct reflection of their thinking processes: For example, slow, plodding, one step at a time, incapable of imaginative leaps, versus those who operate directly on larger patterns at once... From deets at nospam.web.de Thu Dec 18 09:20:48 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 18 Dec 2008 15:20:48 +0100 Subject: confused about __str__ vs. __repr__ References: Message-ID: <6qv4i0FenjboU1@mid.uni-berlin.de> Neal Becker wrote: > Reading some FAQ, I see that __str__ is "meant for human eyes". > > But it seems that: > class X(object): > ? ? def __str__(self): > ? ? ? ? return "str" > ? ? def __repr__(self): > ? ? ? ? return "repr" > > x = X() > d = {0 : x} > print d > {0: repr} > > So if __str__ is "meant for human eyes", then why isn't print using it! Because the __str__ of dict uses __repr__. Do a print x to see that print itself does use __str__. BTW, could you configure your newsreader to not put the GMANE-group as follow-up? NNTP doesn't work for that. Diez From lewis.sarah93 at yahoo.com Thu Dec 4 23:52:58 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 20:52:58 -0800 (PST) Subject: Earn More Noney Message-ID: <8b1cdd10-5803-44c7-b400-df6d89db1bb0@t3g2000yqa.googlegroups.com> Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From nick at craig-wood.com Tue Dec 2 06:12:31 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 2 Dec 2008 11:12:31 +0000 Subject: Do more imported objects affect performance In-Reply-To: <79153a2e0812012124o7401df57m4ac21dfe37c2ec5@mail.gmail.com> References: <1be78d220812010621u51dead9dnbaa0b4c8c9414362@mail.gmail.com> <79153a2e0812012124o7401df57m4ac21dfe37c2ec5@mail.gmail.com> Message-ID: <20081202111231.GA13523@craig-wood.com> On Tue, Dec 02, 2008 at 11:24:29AM +0600, Taskinoor Hasan wrote: > On Mon, Dec 1, 2008 at 8:21 PM, Filip Gruszczy?ski wrote: > > > I see. Thanks for a really good explanation, I like to know, how to do > > things in the proper way :) > > I always prefer to use import module and then use module.function. The > reason is simple. It makes the code more readable and maintainable. I prefer the "from module import function". That means that if "module" doesn't supply "function" it raises an exception at compile time, not run time when you try to run "module.function". It then becomes very easy to see which functions you use from any given module too. It is also very slightly faster but that isn't a major consideration. PEP 8 endorses this style somewhat http://www.python.org/dev/peps/pep-0008/ - see the Imports section. [...] it's okay to say this though: from subprocess import Popen, PIPE [...] When importing a class from a class-containing module, it's usually okay to spell this from myclass import MyClass from foo.bar.yourclass import YourClass If this spelling causes local name clashes, then spell them import myclass import foo.bar.yourclass and use "myclass.MyClass" and "foo.bar.yourclass.YourClass" Ultimately it is a matter of taste I think! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From aioe.org at technicalbloke.com Sat Dec 6 01:56:55 2008 From: aioe.org at technicalbloke.com (r0g) Date: Sat, 06 Dec 2008 01:56:55 -0500 Subject: Quick Newbie Question References: Message-ID: Josh wrote: > Can Python be used on one Linux machine to drive another Linux machine > through SSH? I am currently running Putty on my XP box to run tests on a > Linux box. I need to automate these tests and thought it would be fun to > do so from a Linux VMWare Image I recently setup. Does this sound > do-able without too much effort? I already know the Linux commands I > need to run but just need an interactive shell connection through SSH. > Again is Python a good choice for this or something else? > Thanks, > > JR Yep, python has several options, I've been using paramiko for this for a couple of years: http://www.lag.net/paramiko/ Roger Heathocte From rdmurray at bitdance.com Thu Dec 11 14:06:34 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Thu, 11 Dec 2008 14:06:34 -0500 (EST) Subject: internal circular class references In-Reply-To: <49414EDA.2050509@stoneleaf.us> References: <49414EDA.2050509@stoneleaf.us> Message-ID: On Thu, 11 Dec 2008 at 09:33, Ethan Furman wrote: > Carl Banks wrote: >> On Dec 10, 5:26 pm, Ethan Furman wrote: >> First of all, do you even need to wrap the datetime.date class? With >> Python's duck typing ability, you could have a separate NullDate class >> to go alongside the datetime.date, and use a regular datetime.date >> object when the date is present, and NullDate when it's absent. If >> necessary you can subclass datetime.date to add any new methods it >> would have to have. Use a factory function to return either NullDate >> or a datetime.date depending on whether the dbf cell is empty. >> >> class ValidDate(datetime.date): >> def is_valid(self): >> return True >> >> class NullDate(object): >> # implement any necessary methods of datetime.date interface here >> def is_valid(self): >> return False >> >> def create_date_from_dbf_cell(dbf_cell): >> if dbf_cell.empty(): >> return NullDate() >> return ValidDate(dbf_cell.value) >> >> >> If you do this, you don't have to muck around with __getattr__ or >> __new__ or snooping to datetime.date's class dict anything like that. >> >> >> Carl Banks > > Good question. My goal with NullDate is to have a date object that I can > treat the same regardless of whether or not it actually holds a date. > NullDates with no value should sort before any NullDates with a value, should > be comparable to dates as well as NullDates, and should support all the same > methods. In other words, I don't want to have to worry about whether my date > object has an actual date under most circumstances (printing, using as > dictionary keys, comparing, etc.). > > Does my design make more sense given these expanded requirements, or could it > still be done simpler? For that matter, do my requirements make sense? What Carl is saying is that since python uses duck typing ("if it quacks like a duck, it is a duck"), all you need to do is make your NullDate object quack enough like a date to handle your use cases, and then you can freely mix dates and NullDates _without having to care which one a given object is_ (python won't care). (Until you do care, at which point you can use isinstance to find out if it is a NullDate). As far as I can see, your requirements as you've outlined them can be met by mixing date objects and appropriately implemented NullDate objects. And that way NullDates will _only_ represent null dates, thus making its name more meaningful :). To do this you just need to implement on NullDate those methods that are going to give NullDate the behavior you need: the rich comparison operators, __str__, __hash__, etc. Or it might be easier to subclass date and override some of the methods. Unless I'm misunderstanding your requirements, of course :) --RDM From aahz at pythoncraft.com Fri Dec 5 18:51:43 2008 From: aahz at pythoncraft.com (Aahz) Date: 5 Dec 2008 15:51:43 -0800 Subject: RELEASED Python 3.0 final References: <874p1jux8u.fsf@benfinney.id.au> Message-ID: In article <874p1jux8u.fsf at benfinney.id.au>, Ben Finney wrote: >James Stroud writes: >> >> comp.lang.python3k ? > >The language has undergone an incompatible divide. Hopefully the >community need not do the same. Pish and tosh. James was clearly making a funny; there's not *that* much difference between 2.x and 3.x. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From deets at nospam.web.de Thu Dec 18 09:16:02 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 18 Dec 2008 15:16:02 +0100 Subject: re.match() performance References: <755bd716-f5f6-4953-87a7-04ee148c3298@i18g2000prf.googlegroups.com> Message-ID: <6qv492Feuto8U1@mid.uni-berlin.de> Emanuele D'Arrigo wrote: > Sorry for the previous post, hit the Enter button by mistake... here's > the complete one: > > Hi everybody! > > I've written the code below to test the differences in performance > between compiled and non-compiled regular expression matching but I > don't quite understand the results. It appears that the compiled the > pattern only takes 2% less time to process the match. Is there some > caching going on in the uncompiled section that prevents me from > noticing its otherwise lower speed? Yes. There is even a purge-function to clear that cache, for whatever reason. To answer that question yourself, you could have taken a look into the python library, it's not as scary as you might think :) Diez From msdark at archlinux.us Tue Dec 16 08:33:53 2008 From: msdark at archlinux.us (=?ISO-8859-1?Q?Mat=EDas_Hern=E1ndez?=) Date: Tue, 16 Dec 2008 10:33:53 -0300 Subject: mysql hash generator in python Message-ID: <4947AE41.8010204@archlinux.us> (sorry for my english, but i'm speak spanish) Hi list.. this is my first post... and obviously if for help.. I try to implement the password function of mysql in a python script. I read that the password function of mysql was implemented with a double sha1() I python i try this: example1: if __name__=="__main__": s = hashlib.sha1() s.update('test') s2 = hashlib.sha1() s2.update(s.digest() print s2.hexdigest() This script show me the same hash that password function of mysql, but when i implement this in a class the hash is different??? why??? And if is posible??? can you show a example code of old_password function of mysql in python??? THNX From aahz at pythoncraft.com Mon Dec 15 10:41:55 2008 From: aahz at pythoncraft.com (Aahz) Date: 15 Dec 2008 07:41:55 -0800 Subject: Looking for the best way to translate an idiom References: <494611c2$0$21934$426a34cc@news.free.fr> Message-ID: In article <494611c2$0$21934$426a34cc at news.free.fr>, Bruno Desthuilliers wrote: >Aahz a ?crit : >> In article , >> James Stroud wrote: >>> >>> In case its not obvious: >> >> Ah, so that's where Bruno's extra apostrophe came from! ;-) > >Err... Which one exactly ? Don't remember, it was a post I read about five minutes earlier that had something like, "...has it's place..." -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From jurgenex at hotmail.com Wed Dec 3 23:45:39 2008 From: jurgenex at hotmail.com (Jürgen Exner) Date: Wed, 03 Dec 2008 20:45:39 -0800 Subject: Mathematica 7 compares to other languages References: <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <4b6c3304-2396-4d35-a06f-e5d693cbbb12@f13g2000yqj.googlegroups.com> Message-ID: toby wrote: >On Dec 3, 4:15 pm, Xah Lee wrote: >> On Dec 3, 8:24 am, Jon Harrop wrote: >> >> > My example demonstrates several of Mathematica's fundamental limitations. >> >> enough babble Jon. >> >> Come flying $5 to my paypal account, and i'll give you real code, > >I'll give you $5 to go away if you add "and never come back" then count me in, too. jue From metolone+gmane at gmail.com Mon Dec 29 14:19:48 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Mon, 29 Dec 2008 11:19:48 -0800 Subject: How to display Chinese in a list retrieved from database via python References: <22be506d-91c2-4727-ace7-2e3382b6d214@g3g2000pre.googlegroups.com><979fdf6d-0500-47ba-87fd-0f0361ca3059@p2g2000prf.googlegroups.com><19680ed2-c78f-4ab9-8ca0-8ce26fd5b6a7@o4g2000pra.googlegroups.com><2560a6e0-c103-46d2-aa5a-8604de4d1968@b38g2000prf.googlegroups.com> <7e38e76a-d5ee-41d9-9ed5-73a2e2993733@w1g2000prm.googlegroups.com> Message-ID: "zxo102" wrote in message news:7e38e76a-d5ee-41d9-9ed5-73a2e2993733 at w1g2000prm.googlegroups.com... > On 12?29?, ??5?06?, "Mark Tolonen" wrote: >> "zxo102" wrote in message >> >> news:2560a6e0-c103-46d2-aa5a-8604de4d1968 at b38g2000prf.googlegroups.com... >> [snip] >> That said, learn to use Unicode strings by trying the following program, >> but >> set the first line to the encoding *your editor* saves files in. You can >> use the actual Chinese characters instead of escape codes this way. The >> encoding used for the source code and the encoding used for the html file >> don't have to match, but the charset declared in the file and the >> encoding >> used to write the file *do* have to match. >> >> # coding: utf8 >> >> import codecs >> >> mydict = {} >> mydict['JUNK'] = [u'??',u'??',u'??'] >> >> def conv_list2str(value): >> return u'["' + u'","'.join(s for s in value) + u'"]' >> >> f_str = u''' >> >> test >> >> >> ''' >> >> s = conv_list2str(mydict['JUNK']) >> f=codecs.open('test04.html','wt',encoding='gb2312') >> f.write(f_str % s) >> f.close() >> >> -Mark >> >> P.S. Python 3.0 makes this easier for what you want to do, because the >> representation of a dictionary changes. You'll be able to skip the >> conv_list2str() function and all strings are Unicode by default. > > Thanks for your comments, Mark. I understand it now. The list(escape > codes): ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4'] is > from a postgresql database with "select" statement.I will postgresql > database configurations and see if it is possible to return ['??','? > ?','??'] directly with "select" statement. > > ouyang The trick with working with Unicode is convert anything read into the program (from a file, database, etc.) to Unicode characters, manipulate it, then convert it back to a specific encoding when writing it back. So if postgresql is returning gb2312 data, use: data.decode('gb2312') to get the Unicode equivalent: >>> '\xd6\xd0\xce\xc4'.decode('gb2312') u'\u4e2d\u6587' >>> print '\xd6\xd0\xce\xc4'.decode('gb2312') ?? Google for some Python Unicode tutorials. -Mark From nebson at gmail.com Wed Dec 24 17:56:45 2008 From: nebson at gmail.com (Sponge Nebson) Date: Wed, 24 Dec 2008 14:56:45 -0800 (PST) Subject: PythonCard timer/thread tutorial Message-ID: <59e602b0-937c-4bd5-bc71-30094e1cd596@r36g2000prf.googlegroups.com> Hello all, This is my first post. Nice to meet you all! Could one of you walk me through this code? def myThread(*argtuple): """ A little thread we've added """ print "myThread: entered" q = argtuple[0] print "myThread: starting loop" x = 10 while True: time.sleep(10) # time unit is seconds print "myThread x=%d" % x q.put(str(x)) # stick something on message queue wx.WakeUpIdle() # triggers 'idle' handlers x += 10 It is from David McNab and Alex Tweedly's tutorial on timers and threads, which can be found here: http://pythoncard.sourceforge.net/timers-threads.html Among my questions are: """ A little thread we've added""" seems to be an isolated string. It does not seem to be doing anything there, almost like a comment. Why is it there? What is argtuple for? how does it work? What is the queue for? Thanks! -Ben From luke.leighton at googlemail.com Tue Dec 2 08:57:00 2008 From: luke.leighton at googlemail.com (lkcl) Date: Tue, 2 Dec 2008 05:57:00 -0800 (PST) Subject: Python+Pyjamas+V8=ftw References: Message-ID: <56533d3d-c5cd-4a41-9bc3-525eaa44bba1@d23g2000yqc.googlegroups.com> > Another project similar-ish to Pyjamas is > HotRuby:http://hotruby.yukoba.jp/ also there's RubyJS: http://rubyforge.org/projects/rubyjs/ it's again a javascript compiler - ruby to javascript - and the beginnings of a port of GWT to Ruby, called rwt. this project _definitely_ needs more attention. michael's talk (included in the docs/) shows that he has spent considerable effort in ensuring that not only is the compiler faithful to the features of ruby, but also that the features are translated _efficiently_. which takes a hell of a lot of doing. the nice thing about michael's work is that he's leading the way in showing the pyjamas compiler how it _really_ should be done. pyjamas is capable of running a very significant amount of python, but it _is_ missing some crucial features: **kwargs for example, and the 0.4 release has just added a _very_ basic type of exception handling. that having been said: for the majority of purposes - most web development - pyjamas is _more_ than adequate. as a general-purpose plugin replacement for /usr/bin/python, however, it's not quite there. and, given that javascript cheerfully goes about its way with the "undefined" concept, it's always going to be a _bit_ tricky to provide absolutely _every_ language feature, faithfully. that having been said, the speedup factor of pyv8 should make the pyjamas compiler a _really_ attractive option, and i think that when it becomes the "norm" to have a javascript interpreter as part of a sysadmin's / developer's dailiy life in the same way that /usr/bin/ perl and /usr/bin/python are, then compilers like RubyJS, Pyjamas and GWT will have a much bigger significance. l. From jarausch at igpm.rwth-aachen.de Tue Dec 2 04:34:18 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Tue, 02 Dec 2008 10:34:18 +0100 Subject: Is it safe to modify the dict returned by vars() or locals() In-Reply-To: References: <4934508b$0$2861$ba620e4c@news.skynet.be> Message-ID: <4935011A.9080406@igpm.rwth-aachen.de> Chris Rebert wrote: > On Mon, Dec 1, 2008 at 1:01 PM, Helmut Jarausch wrote: >> Hi, >> >> I am looking for an elegant way to solve the following problem: >> >> Within a function >> >> def Foo(**parms) >> >> I have a list of names, say VList=['A','B','C1'] >> and I like to generate abbreviation >> _A identical to parms['A'] > > Could you explain what you mean by that? Your sample code doesn't seem > to do any "abbreviation"... > Otherwise I don't see why you don't just have a proper parameter list. In my application parms contains field names of an html form iff these fields have been modified. I'd like to use the short name _A instead of the longer expression parms['A'] -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From lambertdw at corning.com Thu Dec 11 12:04:16 2008 From: lambertdw at corning.com (lambertdw at corning.com) Date: Thu, 11 Dec 2008 09:04:16 -0800 (PST) Subject: if expression source format References: Message-ID: <662cc393-d9bd-48d2-9b6e-54b9ae416c94@m15g2000vbp.googlegroups.com> Consider following snippets: # must examine code carefully to see that result has a value if condition: result = expression1 else: result = another_expression return result # result has a value but difficult to understand how it comes about result = expression1 if condition else another_expression return result # must examine code carefully to ensure that it always # returns a computed value if condition: return true_expression else: return false_expression # Ahh! I do use this idiom quite often. if condition: return true_expression return default_expression Actually, I was simply wondering if there is yet a preferred way to write the python ternary expression. Samples: # break expression near convenient max line length A) true_expression if condition else (fa lse_expression) # break expression near convenient max line length B) # ("Humans be damned!" form.) true_expr \ ession if cond \ ition else \ false_e \ xpressi \ on # ternary nature of expression extremely visible (true_expression if condition else false_expression) # I use this form but not happily, # providing functions as necessary to make it fit onto two lines # loosely guided by the K&R admonition (or maybe it was K&P) that # "a conditional expression is too complicated if you can't read # it to your mother over the phone" or something like that. (true_expression if condition else false_expression) From bearophileHUGS at lycos.com Fri Dec 5 10:46:02 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 5 Dec 2008 07:46:02 -0800 (PST) Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> <20081205161725.3f35222b@usenot.de> Message-ID: <534215df-0ba3-471a-b4d4-e495a3e4daf7@w35g2000yqm.googlegroups.com> Andreas Waldenburger: > My point is: If you mix tabs and spaces in a way that breaks code, > you'll find out pretty easily, because your program will not work. - Most newbies don't know that. - Sometimes it may produce wrong results. - And even if you are an expert when you go changing a little a source code that mixes tabs and spaces you usually break the code. Is this enough for you? Bye, bearophile From steve at REMOVE-THIS-cybersource.com.au Sat Dec 27 00:00:26 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Dec 2008 05:00:26 GMT Subject: raw_input can't handle pound sign? References: Message-ID: <0165ad86$0$6988$c3e8da3@news.astraweb.com> On Fri, 26 Dec 2008 20:20:16 -0800, Jugdish wrote: > Hi, I'm having problems getting a pound sign to go through as input sent > to the raw_input() command. I'm running Python 2.5.1 on Windows XP. > Here's my simple little script: > > while True: > response = raw_input("Please enter a file name: ") if > os.path.exists(response): > break > > Problem is if the filename has a "#" in it, the script interprets that > as the beginning of a comment (not sure why -- isn't raw_input supposed > to treat the user's input as raw text and not do any sort of evals?) Yes it is. What makes you think it is being interpreted as a comment? What results are you getting? > Any ideas how to get a # to go through? Thanks! Works for me (although I'm not using Windows XP). Can you execute this line at the interactive interpreter? print raw_input("Type something with a hash sign: ") At the prompt, type "test # string" (without the quotes) and show us what result you get. When I do this, I get the following: >>> print raw_input("Type something with a hash sign: ") Type something with a hash sign: test # string test # string -- Steven From kyosohma at gmail.com Wed Dec 24 19:59:23 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 24 Dec 2008 16:59:23 -0800 (PST) Subject: PythonCard timer/thread tutorial References: <59e602b0-937c-4bd5-bc71-30094e1cd596@r36g2000prf.googlegroups.com> Message-ID: <6f7164cc-56dc-4022-8943-067b8ca44e61@40g2000prx.googlegroups.com> On Dec 24, 4:56?pm, Sponge Nebson wrote: > Hello all, > > This is my first post. Nice to meet you all! Could one of you walk me > through this code? > > ? ?def myThread(*argtuple): > ? ? ? ? """ > ? ? ? ? A little thread we've added > ? ? ? ? """ > ? ? ? ? print "myThread: entered" > ? ? ? ? q = argtuple[0] > ? ? ? ? print "myThread: starting loop" > ? ? ? ? x = 10 > ? ? ? ? while True: > ? ? ? ? ? ? time.sleep(10) # time unit is seconds > ? ? ? ? ? ? print "myThread x=%d" % x > ? ? ? ? ? ? q.put(str(x)) # stick something on message queue > ? ? ? ? ? ? wx.WakeUpIdle() # triggers 'idle' handlers > ? ? ? ? ? ? x += 10 > > It is from David McNab and Alex Tweedly's tutorial on timers and > threads, which can be found here: > > ?http://pythoncard.sourceforge.net/timers-threads.html > > Among my questions are: > """ A little thread we've added""" seems to be an isolated string. It > does not seem to be doing anything there, almost like a comment. Why > is it there? That's what some people call a doc string. It is like a comment in that it helps the user know what the function is for. Notice the triple quotes. If you were to type "help(myFunction)", it would grab the functions doc string and display it. You can read up on them here: http://diveintopython.org/getting_to_know_python/documenting_functions.html > > What is argtuple for? how does it work? This allows the programmer to pass an arbitrarily long argument list to the function. It took a little digging, but I found it in the docs (scroll down towards the bottom): http://docs.python.org/tutorial/controlflow.html#SECTION006600000000000000000 > > What is the queue for? > > Thanks! > > -Ben I haven't messed with queues as yet, but they are one way of dealing with multiple threads in GUI programming. The idea is to stick something in the queue for the GUI thread (or potentially some other thread) to pick up when it's not busy. So one thread sticks something on the queue and another thread checks the queue periodically to see if there's something there and if there is, it picks it up. At least, that's my understanding. You can read up on various methods of messing with threads in wxPython here: http://wiki.wxpython.org/LongRunningTasks And here are the queue docs (for 2.6...): http://docs.python.org/library/queue.html I recommend learning how to use Google effectively. I found about half the links above using it. You might also find joining the wxPython mailing list beneficial. I learn a lot there just by reading and posting to it: http://wxpython.org/maillist.php - Mike From hatchar at gmail.com Fri Dec 26 20:30:32 2008 From: hatchar at gmail.com (kather) Date: Fri, 26 Dec 2008 17:30:32 -0800 (PST) Subject: online money earnings In-Reply-To: References: Message-ID: <21180899.post@talk.nabble.com> Classical program and new investment programs . Join here : Paying : http://www.geniusfunds.com/?c=501251 http://www.geniusfunds.com/ Seem not bad : http://www.forexinv.net/?refer=jhon1092 http://www.forexinv.net/ -- View this message in context: http://www.nabble.com/online-money-earnings-tp17422431p21180899.html Sent from the Python - python-list mailing list archive at Nabble.com. From huwdjones at gmail.com Mon Dec 15 04:44:06 2008 From: huwdjones at gmail.com (huw_at1) Date: Mon, 15 Dec 2008 01:44:06 -0800 (PST) Subject: cx_Oracle issues References: <5b2dad81-2750-4347-8079-6ab31321d579@s1g2000prg.googlegroups.com> <9142a8f1-7f76-4fc0-9ca1-c9dec310f2ce@r37g2000prr.googlegroups.com> Message-ID: <9f436c9e-2319-499c-a306-d255996372fc@e22g2000vbe.googlegroups.com> On Dec 11, 5:34?pm, "ron.re... at gmail.com" wrote: > On Dec 10, 9:48?am, huw_at1 wrote: > > > > > Hey all. When using cx_Oracle to run a procedure like: > > > cursor.execute("select (obj.function(value)) from table where > > id=blah") > > > I am getting the following error: > > > ORA-06502: PL/SQL: numeric or value error: character string buffer too > > small ORA-06512: at line 1 > > > Looking at cursor.description I get: > > > [('(obj.function(value))', , 4000, 4000, 0, > > 0, 1)] > > > Any tips - i have never seen this error before but am guessing that > > the value being returned is too big for the buffer size set for the > > cursor. the procedure fetches data from a LOB. > > > Any suggestions/confirmations? > > > Many thanks > > This error is a problem with the PL/SQL, not cx_Oracle. ?You need to > debug obj.function to see what kind of data is being accessed and then > a data analysis of that data to understand why this error occurs. ?I > can tell you the function is most likely expecting characters from a > column that are numeric [0 .. 9] and is getting alpha characters. > > -- > Ron Reidy > Sr. Oracle DBA Hi thanks for the responses. Unfortunately the procedure in question is from a third party vendor so I can't really debug it so I'd say I was fairly stumped. Just out of interest how do you increase the output buffer size with cx_Oracle? Many thanks From steve at holdenweb.com Wed Dec 24 07:59:17 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 24 Dec 2008 07:59:17 -0500 Subject: Multi-dimension list In-Reply-To: References: Message-ID: James Stroud wrote: > Steven Woody wrote: >> Hi, >> >> In the book Python Essential Reference, Chapter 3, when talking about >> extended slicing, it gives an example: a = m[0:10, 3:20]. But I >> don't understand how the 'm' was defined. What should it looks like? > > m could be an instance of the Krayzee class. > > py> class Krayzee(object): > ... def __getitem__(self, i): > ... try: > ... r = ['WTF?' for j in i] > ... except: > ... r = 'WTF?' > ... return r > ... > py> m = Krayzee() > py> m[1:2:3, 4:5:6] > ['WTF?', 'WTF?'] > py> m['your moms'] > ['WTF?', 'WTF?', 'WTF?', 'WTF?', 'WTF?', 'WTF?', 'WTF?', 'WTF?', 'WTF?'] > > I'm not sure what this is supposed to prove. It might be more helpful to show what's actually going on ... >>> class k(object): ... def __getitem__(self, i): ... try: ... r = [j for j in i] ... except Exception, e: ... print i, ":", e ... r = i ... return r ... >>> m = k() >>> m[1:2:3, 4:5:6] [slice(1, 2, 3), slice(4, 5, 6)] >>> m["help!"] ['h', 'e', 'l', 'p', '!'] >>> As you can see, no exceptions are raised here, and the x:y:z notation introduces a slice object, which the code doesn't handle in any way shape or form. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From dmitrey.kroshko at scipy.org Mon Dec 15 17:32:23 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Mon, 15 Dec 2008 14:32:23 -0800 (PST) Subject: OpenOpt 0.21 (free optimization framework) Message-ID: Hi all, OpenOpt 0.21, free optimization framework (license: BSD) with some own solvers and connections to tens of 3rd party ones, has been released. All details here: http://openopt.blogspot.com/2008/12/openopt-release-021.html Regards, OpenOpt developers. From duncan.booth at invalid.invalid Mon Dec 1 04:54:01 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Dec 2008 09:54:01 GMT Subject: Emacs vs. Eclipse vs. Vim References: Message-ID: Roy Smith wrote: > Clay Hobbs wrote: >> The first real text editor I used was Vim, which I actually started >> using about a year ago. I've looked at Emacs and it just looks >> confusing. > > I've been using emacs for so many years (um let's see, it's got to be > close to 25 years now; first saw it on Columbia's TOPS-20 systems in > the early 80's) that my fingers know what they're doing without my > even thinking about it. In fact, I used to work with another emacs > nut. Every so often, one of use would watch the other do something > and ask, "What was that?". Inevitably, neither of us could evoke the > keystrokes we had just typed. We would just re-do it, and watch our > fingers to see what we typed. It didn't even have to be on a > keyboard; we could air-type it, and that was good enough. > I also started using Emacs about 25 years ago, but then when I moved to using DOS machines which at the time weren't capable of running Emacs I suffered withdrawal symptoms until I found Epsilon (http://lugaru.com) which started life as an Emacs style editor on DOS. I still use Epsilon today, even when I'm using Linux: it isn't free software in any sense of the word, but I find that a lot of the things I use it for it actually does better than Emacs. If you are willing to consider paying for an editor then download the evaluation copy of Epsilon and give it a go. -- Duncan Booth http://kupuguy.blogspot.com From cmpython at gmail.com Mon Dec 22 05:10:22 2008 From: cmpython at gmail.com (CM) Date: Mon, 22 Dec 2008 02:10:22 -0800 (PST) Subject: wxpython for python 3.0 ? References: Message-ID: <3381d5f8-2a62-45ec-900c-d9849e3cc554@x38g2000yqj.googlegroups.com> On Dec 21, 4:42?pm, dlemper wrote: > The wxpython web describes compatability with python 2.4 & 2.5 . > Does it work with 3.0 ? ? If not, anyone have a clue as to when ? Not yet. I think it will be a while until then. From fetchinson at googlemail.com Sun Dec 28 02:44:29 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 27 Dec 2008 23:44:29 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: >>> As others already said, using a Numpy array or an array.array object >>> would >>> be more efficient (and even easier - the C code gets a pointer to an >>> array >>> of integers, as usual). >> >> I looked for this in the C API docs but couldn't find anything on how >> to make an array.array python object appear as a pointer to integers >> (or floats, etc) in C code. On >> >> http://docs.python.org/c-api/concrete.html#sequence-objects >> >> There is only list and tuple or maybe you mean byte array? That has >> only been introduced in python 2.6 and I'm working on 2.5. > > array is a library module, and isn't really part of the API. You're > looking for the buffer protocol: > PyObject_AsReadBuffer/PyObject_AsWriteBuffer; see > http://docs.python.org/c-api/objbuffer.html > > Given an array.array('l') (containing C long integers): > > int do_something(PyObject* obj) > { > long *vec; > Py_ssize_t nbytes, nitems, i; > > if (PyObject_AsReadBuffer(obj, (const void **)&vec, &nbytes) != 0) > return NULL; > nitems = nbytes/sizeof(long); > for (i=0; i /* do something with vec[i] */ > } > return ret; > } > > From Python you can get "vec" and "nitems" using the buffer_info() method > of array objects. Thanks very much, this was very helpful! Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From bearophileHUGS at lycos.com Thu Dec 25 13:55:51 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 25 Dec 2008 10:55:51 -0800 (PST) Subject: Exec inside a class method to call other class methods? References: Message-ID: <3dc6f013-3f10-425f-bd65-d44b5ffe5a67@40g2000prx.googlegroups.com> Matthew Dubins: > def parse(self, data, data_type) > ? ? exec "self.__parse_%s(data)" % data_type > For some reason, *it didn't work*. You can try defining this class attribute: data_types = set("nocall DOB gender Prematurity email languages phone cname pname address duedate".split()) And then a possible method can be: def parse(self, data, data_type): if data_type in Classname.data_types: getattr(self, "__parse_" + data_type)(data) If performance isn't a problem you can move data_types inside the parse method. If performance is a problem, data_types may become a dict, whose values are references to the methods. That you can use as: def parse(self, data, data_type): if data_type in data_types: data_types[data_type](data) Or even as (but may be a little slower): def parse(self, data, data_type): data_types.get(data_type, lambda x: None)(data) Bye, bearophile From ht at example.com Thu Dec 4 14:35:43 2008 From: ht at example.com (HT) Date: Thu, 04 Dec 2008 11:35:43 -0800 Subject: Why shouldn't you put config options in py files Message-ID: A colleague of mine is arguing that since it is easy to write config like: FOO = {'bar': ('a': 'b'), 'abc': ('z': 'x')} in config.py and just import it to get FOO, but difficult to achieve the same using an ini file and ConfigParser, and since Python files are just text, we should just write the config options in the Python file and import it. I can think of lots of arguments why this is a bad idea, but I don't seem to be able to think of a really convincing one. Anyone? From expora at gmail.com Mon Dec 8 21:01:38 2008 From: expora at gmail.com (Edwin) Date: Mon, 8 Dec 2008 18:01:38 -0800 (PST) Subject: Programming exercises/challenges References: <1d6140d1-7eff-49ee-bc2c-5b3d8868897a@13g2000yql.googlegroups.com> <9fd90236-63bd-4e60-8c88-c0d69b06b84f@41g2000yqf.googlegroups.com> Message-ID: <57a0b1da-b0e5-4626-90bb-7824d8328ee4@v42g2000yqv.googlegroups.com> On Nov 22, 2:15?am, Arnaud Delobelle wrote: > I'm only a very occasional user of vi, so I don't really know how vim > integrates with MacOS X but have you tried aquamacs > (http://aquamacs.org/)? > > -- > Arnaud I've tried it but I ended up using original (I'm sure there's a better adjective) Emacs compiled --with-ns... it's very nice (at least for what I do, in the little experience I've gained). Cheers, From MLDSpenser at aol.com Thu Dec 25 21:24:41 2008 From: MLDSpenser at aol.com (MLDSpenser at aol.com) Date: Thu, 25 Dec 2008 21:24:41 EST Subject: dummy needs help with Python Message-ID: I am trying to find somebody who can give me a simple python program I can use to "program by analogy". I just want to read two CSV files and match them on several fields, manipulate some of the fields, and write a couple of output files. I come from 30 years of mainframe programming so I understand how computers work at a bits/bytes /machine language/ source vs.executable/reading core dumps level, and I can program in a lot of languages most people using Python have never even heard of, but I don't know any of the modern jargon; the Python home site is full of statements that mean nothing to me. I can't understand the descriptions of most of the software in the Python Package Index. I can't even figure out most of the descriptions of the help available in the Python community, so sending this e-mail may be highly inappropriate. Please forgive me if this is so, and take pity on a stranger in a strange land. I have done some Python programming in a module supplied by the author of software (Readerware) I bought; he takes care of all the file handling outside of the module he lets you mess with; I just manipulated selected fields he had defined. It seems like a fantastic language but I need help. My problem is that I want to do this all yesterday, and the Python text I bought is not easy to understand. I don't have time to work my way through the online Python tutorial. I've tried a couple of forums but nobody has answered my questions. A simple program with comments that say "here's where I read File A and define/map/ the fields in it" would let me learn by testing and trying things out, the same way I learned to work with the fields in the module. Peace on earth to all people of good will. Margie Spenser Pittsburgh, PA -------------- next part -------------- An HTML attachment was scrubbed... URL: From joe at strout.net Fri Dec 12 11:07:21 2008 From: joe at strout.net (Joe Strout) Date: Fri, 12 Dec 2008 09:07:21 -0700 Subject: concept of creating structures in python In-Reply-To: References: Message-ID: <25EDE674-3566-4720-BCEB-6A4D3865C9E2@strout.net> On Dec 12, 2008, at 9:00 AM, Steve Holden wrote: >> Change the default value of ds_obj here to None. Otherwise, you will >> certainly confuse yourself (there would be just one default object >> shared among all instances). >> > Joe missed a piece out here. If you change the signature of your > D.__init__() to read > > def __init__(self, dataName='ND', index = 0, ele_obj=None): > > then you need to insert the following code at the top of the method: > > if ele_obj is None: > ele_obj = E() Yes, if you really need to guarantee that ele_obj is not None, then this is the way to do it. Of course this would mean that you can't get a None ele_obj even by passing it in explicitly as the parameter value -- if you need to support that as well, then the solution is a little more complex. Perhaps best in that case would be to just not give ele_obj any default value at all, so it becomes a required parameter. Best, - Joe From steve at holdenweb.com Mon Dec 15 10:47:28 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 15 Dec 2008 10:47:28 -0500 Subject: Looking for the best way to translate an idiom In-Reply-To: References: Message-ID: James Stroud wrote: > Aahz wrote: >> In article , >> James Stroud wrote: >>> In case its not obvious: >> >> Ah, so that's where Bruno's extra apostrophe came from! ;-) >> >> >> (Sorry about the spelling flame, but seeing three posts in quick >> succession with incorrect spelling of its/it's pushed me into making a >> public comment.) > > Yes. I think it was the British who decided that the apostrophe rule for > "it" would be reversed from normal usage relative to just about every > other noun. I'm not sure the purpose--maybe it was to give compulsive > proofreaders a raison d'etre. In fact it applies to personal pronouns generally, though in English most personal pronouns have an irregular genitive. I me my mine you you your yours he him his his she her her hers it it its its we us our ours you you your yours they them their theirs regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From walterbyrd at iname.com Thu Dec 11 13:21:55 2008 From: walterbyrd at iname.com (walterbyrd) Date: Thu, 11 Dec 2008 10:21:55 -0800 (PST) Subject: Is 3.0 worth breaking backward compatibility? References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> <20081207203553.7d62434a@usenot.de> Message-ID: <4731f7cf-ef15-4328-85a4-de4437009f2e@40g2000prx.googlegroups.com> On Dec 7, 12:35?pm, Andreas Waldenburger wrote: > Pleeeeze. Python 3 is shipping now, and so is 2.x, where x > 5. Python > 2 is going to be around for quite some time. What is everybody's > problem? A possible, potential, problem, could arise if you were using python 2.x, but some other code, that you wanted to include, was writen in python 3.x. It always surprises me that so many python developers never consider the possibility that you may not always be working with your own code. From rcdailey at gmail.com Mon Dec 8 11:22:55 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 8 Dec 2008 08:22:55 -0800 (PST) Subject: Equivalent of 'wget' for python? Message-ID: Hi, I'm looking for a portable way to download ZIP files on the internet through Python. I don't want to do os.system() to invoke 'wget', since this isn't portable on Windows. I'm hoping the core python library has a library for this. Note that I'll be using Python 3.0. Thanks. From nils.krahnstoever at gmail.com Thu Dec 11 00:19:51 2008 From: nils.krahnstoever at gmail.com (Nok) Date: Wed, 10 Dec 2008 21:19:51 -0800 (PST) Subject: Call by reference in SWIG? Message-ID: I can't get call-by-reference functions to work in SWIG... Even when wrapping a trivial example like this: /* File : trivial.i */ %module trivial %inline %{ class test { public: void foo(int *t) { *t=42; } }; %} I get a TypeError when trying to use it: import trivial x=10 c=trivial.test() c.foo(x) The error is: def foo(*args): return _trivial.test_foo(*args) TypeError: in method 'test_foo', argument 2 of type 'int &' From wuwei23 at gmail.com Mon Dec 8 23:39:34 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 8 Dec 2008 20:39:34 -0800 (PST) Subject: How to initialize a class variable once References: Message-ID: <707edf86-c223-4cf5-b6ca-a7c396a5edce@t26g2000prh.googlegroups.com> On Dec 9, 2:08?pm, Roy Smith wrote: > I've got a class with a class variable: > > class Foo: > ? ?_map = {} > > How do I make sure this only gets initialized the *first* time the > module containing the class is imported? ?What appears to be happening > as it stands is each time the module gets imported, Foo._map get re- > initialized. What you're asking for is actually the default behaviour. The Foo class should only be created once, on the first import, and all subsequent imports should refer to it: foo.py: class Foo: _map = {} a.py: from foo import Foo Foo._map['a'] = 1 b.py: from foo import Foo print Foo._map c.py: import a import b This outputs "{'a': 1}", as expected. The Foo._map that b.py prints is the same Foo._map that a.py has modified. You might need to provide some more details about your code. From google at mrabarnett.plus.com Sun Dec 21 19:14:22 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 22 Dec 2008 00:14:22 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: <494EDBDE.3020307@mrabarnett.plus.com> Aaron Brady wrote: > On Dec 21, 10:58 am, MRAB wrote: >> Aaron Brady wrote: >>> On Dec 21, 10:31 am, MRAB wrote: > snip >>>> The original format is a string. The result of '%' is a string if >>>> there's only 1 placeholder to fill, or a (partial) format object (class >>>> "Format"?) if there's more than one. Similarly, the format object >>>> supports '%'. The result of '%' is a string if there's only 1 >>>> placeholder to fill, or a new (partial) format object if there's more >>>> than one. >>>> >>> f = "%r %i" >>>> >>> type(f) >>>> >>>> >>> f = f % (2, 3, 4) >>>> >>> type(f) >>>> >>>> >>> f = f % 1 >>>> >>> type(f) >>>> >>> Alright, so how are you handling: >>>>>> f= "%s %i" >>>>>> type( f ) >>> >>>>>> f= f% '%i' #now '%i %i' >>>>>> type( f ) >>> >>>>>> f= f% 1 >>>>>> type( f ) >>> ? >>> In other words, are you slipping '1' in to the very first available >>> slot, or the next, after the location of the prior? >> Let's assume that Format objects display their value like the equivalent >> string format: >> >> >>> f = "%r %i" >> >>> f >> '%r %i' >> >>> f = f % (2, 3, 4) >> >>> f >> >> >>> f = f % 1 >> >>> f >> '(2, 3, 4) 1' >> >>> >> >>> f = "%s %i" >> >>> f >> '%s %i' >> >>> f = f % '%i' >> >>> f >> >> >>> f = f % 1 >> >>> f >> '%%i 1' > > I assume you meant '%i 1' since there are no more flags in f, and it's > returned to a regular string. > Correct. > 'f %= 1' doesn't work any more as in-place modulo, since one time, 'f' > is a Format object, the other, 'f' is a string. Just raise an > exception for that (or assign to __class__ IINM if I'm not mistaken). > All assignments rebind, even the augmented form: >>> class C1(object): def __mod__(self, value): return C2() >>> class C2(object): def __mod__(self, value): return C2() >>> f = C1() >>> f <__main__.C1 object at 0x00D144F0> >>> f % 0 <__main__.C2 object at 0x00D143F0> >>> f %= 0 >>> f <__main__.C2 object at 0x00D145B0> > Actually, the class you showed is kind of nifty. Tuples are correctly > interpolated. I think on the whole you'll use more parenthesis, since > each term in the tuple appears separately, and might be an expression > (have a lower-precedence op.), as well as more modulo signs. > > You can currently do-it-yourself, you just need a constructor in the > format string. > >>>> f = Format("%r %i") >>>> type(f) > >>>> f = f % (2, 3, 4) >>>> type(f) > > > Or, as someone suggested earlier, a new literal marking: > Yes, I suggested that earlier, but it isn't needed because you can create a format object with "Format(string)". However, most of the time you won't bother to create a format object explicitly because of: class str(object): def __mod__(self, value): return Format(self) % value >>>> f = f"%r %i" >>>> type(f) > > >>> # Explicitly >>> f = Format("%r %i") >>> f >>> f % (2, 3, 4) >>> >>> # Implicitly, relying on the __mod__ method of str >>> f = "%r %i" >>> f '%r %i' >>> f % (2, 3, 4) I'd also like to add that there's nothing to prevent format objects from having other methods where multiple placeholders can be filled in one call: >>> # By position >>> f = Format("%r %i") >>> f >>> f.fill([(2, 3, 4), 1]) '(2, 3, 4) 1' >>> >>> # By name >>> f = Format("%{tuple}r %{int}i") >>> f >>> f.fill({"tuple": (2, 3, 4), "int": 1}) '(2, 3, 4) 1' From bockman at virgilio.it Wed Dec 31 03:31:57 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: Wed, 31 Dec 2008 09:31:57 +0100 Subject: MemoryError when list append... plz help In-Reply-To: References: Message-ID: <495b2dfe$0$11377$5fc30a8@news.tiscali.it> [BON] ha scritto: > ====================== > s=[] > for i in range(11000-1): > for j in range(i+1, 11000): > .... > s.append(((i,j),sim)) > ====================== > above sim is floating type. > s.append is totally coducted 60,494,500 times. > but this code raise MemoryError. > > My computer has 4G RAM. > i think it's enough. but it doesn't... > > So, i've tested below code. > ====================== > a=[] > i=0 > while i<60494500 : > a.append(i) > i+=1 > ====================== > but this code raise also MemoryError. > > How can i resolve this problem? > please, help... > > Regards, If you _really_ have to store so many numbers in memory (hint: if you are processing them sequentially, you don't need to store all them - use generators instead) then you may have better luck using mmap module to create a huge file-memory object, that you can access both as a file and as a list, and put numbers in it after packing/unpacking with struct. Something like this (only marginally tested ): >>> memory = mmap.mmap(-1, 60494500*4) >>> def memory_put(offset, f): ... memory[offset*4:(offset+1)*4] = struct.pack( "%f", f ) >>> def memory_get(offset): ... return struct.unpack( "f", memory[offset*4:(offset+1)*4] )[0] >>> memory_put(12, 3.14 ) >>> memory_get(12) 3.1400001049041748 Ciao ------ FB From Scott.Daniels at Acm.Org Tue Dec 16 16:59:24 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 16 Dec 2008 13:59:24 -0800 Subject: Need help improving number guessing game In-Reply-To: <4947742c$0$25951$426a34cc@news.free.fr> References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> <01564c98$0$21844$c3e8da3@news.astraweb.com> <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> <4946df78$0$19771$426a74cc@news.free.fr> <1f33580b-84f9-4059-a0f0-b6a8d71325af@b38g2000prf.googlegroups.com> <4947742c$0$25951$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > .... The generic version of your above code could be: > > def safeinput(prompt, convert): > while True: > x = input(prompt) > try: > x = convert(x) > except ValueError, e: > print("Bad input : %s" % e) > else: > return x Or (I think more straightforwardly): def safeinput(prompt, convert): while True: text = input(prompt) try: return convert(text) except ValueError as e: print("Bad input ({0!r}): {1}".format(text, e)) > ... > > def yesno(s): > s = s.strip().lower() > if not s in ("y", "n"): > raise ValueError("please answer with 'y' or 'n'") > # we return a boolean > return s == 'y' def yesno(s): s = s.strip().lower() if s in ("y", "n"): return s == 'y' # return a boolean raise ValueError("please answer with 'y' or 'n'") > def int_in_range(x, mini, maxi): > x = int(x) > if not mini <= x <= maxi: > raise ValueError("%s is not in range (%s, %s)" % (x, mini, maxi)) > return x def int_in_range(x, below, above): x = int(x) # may cause ValueError on its own if below < x < above: return x raise ValueError("{0} is not between {1} and {2}".format( x, mini, maxi)) These changes are mostly: (1) Negated tests are harder yo read (2) raise and return change the flow of control, so if ...: else: ... is "fat" (more trouble to read). (3) Adopting to the new 3.0 string formatting. --Scott David Daniels Scott.Daniels at Acm.Org From sukeerthmex at gmail.com Sun Dec 7 03:29:13 2008 From: sukeerthmex at gmail.com (suku) Date: Sun, 7 Dec 2008 00:29:13 -0800 (PST) Subject: can graphs be made in python as we make in java Message-ID: <89ff42d1-6a4c-4d45-a646-238b43e7e8de@s9g2000prm.googlegroups.com> HI folks... i need some suggestion on making graphs. Will this be possible with normal python setup file or do i need to download add ons for that.. help me out From darcy at druid.net Wed Dec 24 11:44:45 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 24 Dec 2008 11:44:45 -0500 Subject: python web programming for PHP programmers In-Reply-To: References: Message-ID: <20081224114445.a954ed62.darcy@druid.net> On Wed, 24 Dec 2008 14:40:31 +0000 (UTC) Nikola Skoric wrote: > a general python tutorial, I just need a tutorial on how to make a > hello world server side script with python. Any suggestions? #! /usr/bin/env python import sys, re colour = re.sub('=', '=#', ''.join(sys.argv[1:])) print """Content-type: text/html Hello World

Hello World

""" % colour print """

Hello World """ -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From castironpi at gmail.com Mon Dec 29 11:03:54 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 08:03:54 -0800 (PST) Subject: why cannot assign to function call References: Message-ID: On Dec 29, 12:01?am, scsoce wrote: > I have a function return a reference, and want to assign to the > reference, simply like this: > ?>>def f(a) > ? ? ? ? ? return a > ? ? ?b = 0 > ? ? * f( b ) = 1* > but the last line will be refused as "can't assign to function call". > In my thought , the assignment is very nature, ?but ?why the interpreter > refused to do that ? 'Why' is a long question. The syntax has advantages and disadvantages (pros and cons), which weigh different amounts in different languages. In Python, the cons weigh more. In C, the pros weigh more. The short answer is, there is no such thing as assigning to objects, only to variables. You are talking like it could save you ten lines of code or something. From icanbob at gmail.com Wed Dec 10 15:32:02 2008 From: icanbob at gmail.com (bobicanprogram) Date: Wed, 10 Dec 2008 12:32:02 -0800 (PST) Subject: upgrading my SIMPL Programming with Python nofee online course need some volunteer testers Message-ID: <8576fde2-b407-4ab8-b92d-4d76f1d469d9@r36g2000prf.googlegroups.com> SIMPL is an open source project which has been around for almost 10 years. It maintains a very compact interprocesss communication library which gives Linux developers the Send/Receive/Reply messaging paradigm first popularized by QNX almost 30 years ago. (http://www.icanprogram.com/simpl). SIMPL has had a Python shared library for almost 5 years now. I believe that the SIMPL-Python hooks are one of the underused gems in the SIMPL project. I also maintain a couple of nofee online courses including one whose subject is this Python interface into the SIMPL world (although I'm not the author of the lesson material). http://www.icanprogram.com/06py/main.html There is active work in the SIMPL project to bring two upgrades in the Python area. a) the ability to run Python code on Windows and seamlessly interface with a SIMPL application running under Linux b) the ability to interface to a SIMPL-Python application from a simple browser interface The plan is to enhance this course material with this new functionality just as soon as it arrives. Meanwhile I've been working to upgrade the course installation experience with a self installing archive. http://www.icanprogram.com/python.self.html I'm exactly the wrong person to debug this stuff as I'm not a Python programmer and I'm too close in to spot the obvious flaws. I'm looking for Python/Linux volunteers to give this stuff a spin and supply constructive criticism to help improve the student installation experience. Thanks in advance. bob SIMPL project coordinator PS. If anyone is interested in reading more about SIMPL and SIMPL-Python I'm the co-author of a recent book on the subject. Google Books has a free preview of many of the chapters. (see http://www.icanprogram.com/lulu.html). From nagle at animats.com Thu Dec 4 12:24:54 2008 From: nagle at animats.com (John Nagle) Date: Thu, 04 Dec 2008 09:24:54 -0800 Subject: "as" keyword woes In-Reply-To: <493701f0$0$194$e4fe514c@news.xs4all.nl> References: <493701f0$0$194$e4fe514c@news.xs4all.nl> Message-ID: <49380c25$0$2766$742ec2ed@news.sonic.net> > Warren DeLano wrote: >> Why was it necessary to make "as" a reserved keyword? Embrace the pain. John Nagle From geekmail at usenot.de Sat Dec 6 05:30:00 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sat, 6 Dec 2008 11:30:00 +0100 Subject: Guido's new method definition idea References: <48db9$493a3e2b$d9a2276f$10794@news.hispeed.ch> <6puuasFa29upU1@mid.uni-berlin.de> Message-ID: <20081206113000.4da8b7df@usenot.de> On 6 Dec 2008 09:18:20 GMT Marc 'BlackJack' Rintsch wrote: > On Sat, 06 Dec 2008 09:56:12 +0100, Antoine De Groote wrote: > > [snip reference to "preferably only one way to do it"] > > The reason why I'm against that change too. It adds a second, > alternative way to express something that is already in the language. > > > I agree that for newcomers to Python, the class method definition > > might seem strange. > > And after the change it continues to because they will run into > *both* variants in tutorials, code, and books, so it might be even > more confusing. > I agree with that view. Not much to add to it, just increasing the weight. /W -- My real email address is constructed by swapping the domain with the recipient (local part). From gandalf at shopzeus.com Tue Dec 9 03:52:38 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 09 Dec 2008 09:52:38 +0100 Subject: ORB for Python and PHP In-Reply-To: <6q5idtFb0dk0U1@mid.uni-berlin.de> References: <6q5idtFb0dk0U1@mid.uni-berlin.de> Message-ID: <493E31D6.9010106@shopzeus.com> >> >> There are others but they do not support both Python and PHP. Should >> I implement my own ORB, or do you know a suitable solution? > > > The whole purpose of an ORB ist that it is interoperable. So if you > have a good python orb (I personally prefer OmniORB), and a good one > for PHP - connect them. Are all ORBs compatible with each other? I know that this is offtopic, but do you know any ORB for PHP? I couldn't find any. > I would suggest a consistent XMLRPC-interface though. Unfortunately, this would not be good. Sometimes we need to pass through binary data (image file), do session management (which is hard to do with xml-rpc, where each request is a new connection) and optimize speed for communication when the parties are on the same machine. Laszlo From deets at nospam.web.de Tue Dec 2 14:58:47 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 02 Dec 2008 20:58:47 +0100 Subject: help me~!about base64 In-Reply-To: <0ff1ba7b-8a17-4647-99fc-9c8e32f83de7@g1g2000pra.googlegroups.com> References: <0ff1ba7b-8a17-4647-99fc-9c8e32f83de7@g1g2000pra.googlegroups.com> Message-ID: <6plibnF8qbjoU1@mid.uni-berlin.de> ylj798 at gmail.com schrieb: > my code? > ????????????????????????????????????? > import base64 > def deflashget(st): > if st.startswith('Flashget://'): > return base64.decodestring(st[len('Flashget://'):])[10:-10] > elif st.startswith('http://') or st.startswith('ftp://'): > return 'Flashget://' + base64.encodestring('[FLASHGET]' + st > +'[FLASHGET]').replace('\n', '') > > st='Flashget:// > W0ZMQVNIR0VUXWh0dHA6Ly9kb3duLnJub3ZlbC5jb20vYm9va3R4dC8zLzEzNjgyLzEzNjgyLnppcFtGTEFTSEdFVF0=&1064' > print deflashget(st) > ???????????????????????????????????????? > it's run ,Eric gave me error,the error is "'module' object has no > attribute 'decodestring'", > what can I do? who can help me? How is the file called that the above code is in? I *bet* it is called base64.py, or has been called that way. Jerry had the same idea, however you must make sure that the code he gave you is run from inside the above module - because only then you'll have the same environment. Python on the commandline isn't sufficient. Diez From metebilgin48 at gmail.com Mon Dec 15 02:25:19 2008 From: metebilgin48 at gmail.com (mete) Date: Mon, 15 Dec 2008 09:25:19 +0200 Subject: mod_python and files directory In-Reply-To: References: <200812061326.40226.metebilgin48@gmail.com> Message-ID: <200812150925.20246.metebilgin48@gmail.com> On Monday 08 December 2008 10:31:28 Gabriel Genellina wrote: > os.path.dirname(os.path.abspath(__file__)) thanks a lot it's working. From pyth0nc0d3r at gmail.com Mon Dec 15 07:51:07 2008 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Mon, 15 Dec 2008 06:51:07 -0600 Subject: Having Issues with CMD and the 'python' command Message-ID: Every time I start cmd on windows it requires me to "set path=%path%;C:\python26" why? I'm getting annoyed... -------------- next part -------------- An HTML attachment was scrubbed... URL: From asteinarson at gmail.com Sat Dec 6 18:04:55 2008 From: asteinarson at gmail.com (ats) Date: Sat, 6 Dec 2008 15:04:55 -0800 (PST) Subject: Source code generation using Python References: <82098706-978f-4920-ac75-57ef3573ac44@x38g2000yqj.googlegroups.com> Message-ID: <52736f53-1676-4400-a181-20badc0a2b01@k19g2000yqg.googlegroups.com> On Dec 6, 11:19?pm, Philip Semanchuk wrote: > On Dec 6, 2008, at 4:47 PM, ats wrote: > > > > > Hello, > > > This is my first posting to a Python group (and I'm starting with > > Python seriously only now) , so bear with me if I make some mistakes. > > > I want to generate 3 different versions of a C++ source code, > > basically injecting different flavours of inline assembler depending > > on target compiler/CPU. > > > Code generation should be integrated into a 'master source file' which > > is the processed and generates the right code for GCC / MSVC or other > > cases. Something like: > > > ?int FastAdd( int t1, int t2 ){ > > ? ?int r; > > ? ?##if USE_INLINE_ASM > > ? ? ?#ARG( eax, "t1") > > ? ? ?#ARG( ebx, "t2") > > ? ? ?#ASM( "add", ebx, eax ) > > ? ? ?#RES( eax, "r" ) > > ? ?##else > > ? ? ?r = t1+t2; > > ? ?##endif > > ? ?return r; > > ?} > > > On processing, given constant USE_INLINE_ASM (or not) the right code > > is generated to a target file, which goes into the build process. > > > I was looking for packages that can do this and came up with some > > candidates: > > > - "empy" -http://www.alcyone.com/pyos/empy/- It looks like it could > > do the job, but appears non-maintained since 2003. > > - "Cheetah" - Looks like more of a tool to do fix replacements of code > > snippets. > > > There is some logic going on in the "ARG", "ASM" and "RES" sections, > > so I need to link code generation with true Python functions. > > Hi Arne, > There are *lots* of packages for Python that replace chunks of ? > predefined templates. Most are HTML-focused, some more so than others. ? > I've used Mako (http://www.makotemplates.org/) to generate both HTML ? > and Apache config files. It could certainly do C++. Some alternatives ? > to Mako are mentioned in the documentation -- Kid, Genshi and Cheetah. > > Rather than invite a flame war as to which is a better templating ? > engine, I'll just say that I'm happy with how Mako addresses *my* ? > needs. =) Good luck finding something that addresses yours. > > Cheers > Philip > > > > > The situation is really quite similar to HTML/PHP except, here we > > would have C++/Python. > > > Any suggestions? > > > Thanks, > > //Arne S. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Thanks, Mako looks neat. Regards // Arne S. From BrianVanderburg2 at aim.com Sat Dec 13 21:40:00 2008 From: BrianVanderburg2 at aim.com (Brian Allen Vanderburg II) Date: Sat, 13 Dec 2008 21:40:00 -0500 Subject: Bidirectional Networking In-Reply-To: <29283382-3e26-492a-8612-9352f32c1c01@r15g2000prd.googlegroups.com> References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <98a6c3cd-181c-43c9-805b-fb0689c69544@a26g2000prf.googlegroups.com> <29283382-3e26-492a-8612-9352f32c1c01@r15g2000prd.googlegroups.com> Message-ID: <49447200.4030302@aim.com> manu3d at gmail.com wrote: > On Dec 13, 11:13 pm, Bryan Olson wrote: > >> Software firewalls will often simply refuse incoming connections. The >> basic protection of the garden-variety home router comes from "network >> address translation" (NAT), in which case TCP connections initiated from >> the inside will generally work, regardless of port, and incoming >> connections will fail. >> > > Ok, I think I'm getting the picture here. So this means that in most > circumstances where the data flow from the server is frequent the > client initiates the connection, usually requests some initial data > and keeps polling the server periodically, issuing new requests. In > this context can the client simply keep the connection alive and > listen for new data from the server coming at any time rather than > actively issuing requests? Are there drawbacks to this strategy? I.e. > is there a limit to the number of simultaneous connections a server > can keep alive? I've noticed that the socket pages mention a 5 > connections limit. Is that it? What if I want to make a virtual room > with 20 people connected simultaneously? > I've done some network programming not much. I think if you need to receive update from a server frequently a constant connection would be better than connect-request-disconnect. As for the backlog (5), this doesn't mean that you can only have a maximum of 5 established connections. Each established connection gets a new socket object. But what I think it means is that during the listen for an incoming connection on the listening socket, if multiple connection attempts are coming in at one time it can keep a backlog of up to 5 of these connection attempts for that individual socket. Brian Vanderburg II From ibpet11 at gmail.com Tue Dec 30 05:31:21 2008 From: ibpet11 at gmail.com (ibpet11 at gmail.com) Date: Tue, 30 Dec 2008 02:31:21 -0800 (PST) Subject: string in files References: Message-ID: <62075511-08ad-405a-a3af-2da8d2f22c50@v39g2000pro.googlegroups.com> On Dec 30, 11:17?am, "Narasimhan Raghu-RBQG84" wrote: > Simple solution: us result=yourString.split(" ") and you get a list with > all the words. > > -----Original Message----- > From: python-list-bounces+rbqg84=motorola.... at python.org > > [mailto:python-list-bounces+rbqg84=motorola.... at python.org] On Behalf Of > ibpe... at gmail.com > Sent: Tuesday, December 30, 2008 3:43 PM > To: python-l... at python.org > Subject: string in files > > guys i need info on how to call up different words in a line of a file > using python example : file = 'this is a python coding group' > > i want to assign a xter to this, is, a, python , coding and group > > thanks > --http://mail.python.org/mailman/listinfo/python-list > > thanks brother i mean how do i particularly assign (u = this) (y = is).... in the strings up there. i have been able to split strings with any character sign. From ebuyvip at hotmail.com Sat Dec 20 06:57:19 2008 From: ebuyvip at hotmail.com (Jacky) Date: Sat, 20 Dec 2008 03:57:19 -0800 (PST) Subject: New sell cheap Jordan Air max Shox AF1 sneakers NBA NFL NHL Jersey Message-ID: <7dd75638-469f-49d5-8040-310f81129371@s9g2000prg.googlegroups.com> Hi friend My company wholesale all kinds brand products: shoes=$28, T-shirt=$12, hair straightener=$45-$60,purses=$16, sunglass=$14,jeans=$38,hat=$6,jacky=$55,nfl jersey=$20,handbag= $45,watches=$45,memory card=$5-$22, ugg=$45 this price inc shipping fee and tax. 1)payment: western union,T/T,money gram, paypal 2)shipment: ems,dpex,ups,dhl,fedex,tnt 3)delivery times: 4-7 days (send door to door) more details,please contact me: www.ebuyvip.com email/msn: ebuyvip at hotmail.com best regards Jarky From castironpi at gmail.com Tue Dec 30 09:29:19 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 30 Dec 2008 06:29:19 -0800 (PST) Subject: multiprocessing vs thread performance References: <26f7d44e-552c-41e9-9290-17e5c4e6deb9@q30g2000prq.googlegroups.com> Message-ID: <47cfc6de-4b13-4a74-accc-c1d027c44d5a@35g2000pry.googlegroups.com> On Dec 29, 9:08?pm, "James Mills" wrote: > On Tue, Dec 30, 2008 at 12:52 PM, Aaron Brady wrote: > > On Dec 29, 7:40 pm, "James Mills" > > wrote: > >> On Tue, Dec 30, 2008 at 11:34 AM, Aaron Brady wrote: > >> > The OP may be interested in Erlang, which Wikipedia (end-all, be-all) > >> > claims is a 'distribution oriented language'. > > snip > >> I'm presently looking at Virtual Synchrony and > >> other distributed processing architectures - but > >> circuits is meant to be general purpose enough > >> to fit event-driven applications/systems. > > > I noticed a while ago that threads can be used to simulate > > generators. ?'next', 'send', and 'yield' are merely replaced by > > synchronizor calls (coining the term). > > > Not the other way around, though, unless the generator guarantees a > > yield frequently. ?'settrace' anyone? > > Aaron, circuits doesn't use generators :) > What did your comment have to do with this ? > > I have often seen generators used to > facilitate coroutine and coooperative > programming though. > > cheers > James James, Hi. I'm glad you asked; I never know how "out there" my comments are (but surmise that feedback is always a good thing). What I was thinking was, I didn't know Virtual Synchrony, and I've never used Erlang, but I'm interested in concurrency especially as it pertains to units of work, division of labor, and division of context; and generators are another way to divide context. So: I wanted to put more of my background and interests on the table. What I said wasn't directly relevant, I see. But it's not like I "dissertated" (discussed) the Tibettan-Austrian spice trade. I think I just want to say stuff about threading! Maybe I'm just excited to meet people who share my interests... not unheard of. In Economics, you can divide a market into vertical and horizontal dimensions, vertical being the chain from raw resources to finished products, and horizontal being market coverage. With a similar division in tasks, horizontal units would handle incoming events, prepare them, then pass them on to a next unit, which processes a little, then passes it on, like an assembly line (bucket brigade/ alternating current); and vertical units would take one incoming event, and see it through start to finish (direct current). You don't have to use that depiction. The terminology is transposed from that of a distributed matrix multiplication task depiction, where horizontal works start-to-finish, and vertical takes handoffs from its predecessor. 'Circuits' doesn't use generators. I think generators are an underexplored technique. Is 'circuits' assembly line or start-to- finish, if my analogy makes any sense? 'Circuits' is event-driven, but I don't see any difference between 'event-driven' and multithreaded in general. (I think contrast can create a good picture and a clear understanding.) What is special about an 'event-driven' architecture? Are you distinguishing blocking from polling? From gardsted at yahoo.com Sat Dec 20 04:46:26 2008 From: gardsted at yahoo.com (gardsted) Date: Sat, 20 Dec 2008 10:46:26 +0100 Subject: Check file is In-Reply-To: <7caa7d45-ebbe-4c88-bb50-2f01f7315d07@s9g2000prg.googlegroups.com> References: <7caa7d45-ebbe-4c88-bb50-2f01f7315d07@s9g2000prg.googlegroups.com> Message-ID: <494cbef5$0$90267$14726298@news.sunsite.dk> Harish wrote: > Hi Friends > Is there any utility in python which will help me to read any pdf > files? > > Regards > Harish Not sure, what you're after exactly, but I tried googling 'python read pdf' and found this, so maybe 'reportlab' is what you're looking for: Re: Reading PDF files #2 Dec 20th, 2006 To read and manage Portable Document Files you can use the open source ReportLab toolkit (written in Python) from: http://www.reportlab.org/rl_toolkit.html kind regards jorgen From steve at REMOVE-THIS-cybersource.com.au Wed Dec 24 02:19:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 24 Dec 2008 07:19:48 GMT Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> <1iscu14.oixxplpgajabN%pdorange@pas-de-pub-merci.mac.com> <1isenn3.1g8fxa21aqzibkN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <0161d9c7$0$20621$c3e8da3@news.astraweb.com> On Tue, 23 Dec 2008 14:36:53 +0100, Pierre-Alain Dorange wrote: > Steven D'Aprano wrote: > >> But this is just duplicating what timeit already does. Trust me, learn >> to use it, you won't be sorry. Here's a trick that took me a long time >> to learn: instead of copying your functions into the setup code of >> timeit, you can just import them. > > Thanks for the advise, i made the test using timeit and your very > interesting method to import... Now i know how to use timeit simply ;-) > > New results on 1000 float values randomized from -500.0 to +500.0. Each > test is timeit(1000) > > sign_0 : 0.375 > sign_1 : 0.444 (+18%) > sign_2 : 0.661 (+76%) > sign_3 : 0.498 (+33%) Looking at those results, and remembering that each time is for one million iterations of one thousand calls each, I'd say that there's so little difference in speed between them, that you should choose whichever function is easier to understand. At least until you profile your application and discover that the sign() function is the bottleneck keeping your program slow. -- Steven From list at qtrac.plus.com Fri Dec 19 17:21:15 2008 From: list at qtrac.plus.com (Mark Summerfield) Date: Fri, 19 Dec 2008 14:21:15 -0800 (PST) Subject: ANN: New Book: Programming in Python 3 References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <400e99dc-90e2-441a-b7cf-5c2690915682@g38g2000yqd.googlegroups.com> Message-ID: <93e24f4e-a5d6-4952-93ce-f79b192a3666@a29g2000pra.googlegroups.com> On 19 Dec, 19:52, excord80 wrote: > On Dec 4, 2:42?pm, Alan G Isaac wrote: > > > Mark Summerfield wrote: > > > "Programming in Python 3: > > > A Complete Introduction to the Python Language" > > > ISBN 0137129297 > > >http://www.qtrac.eu/py3book.html > > > OMG, you really wrote it in Lout? > > I wish you would add tohttp://www.qtrac.eu/lout.html > > a comment on what you get out of that > > (compared to using e.g., LaTeX or > > reStructuredText). > > I'm also curious about why you chose Lout over LaTeX or reST. It seems to me that markups can be broken into two groups: semantics- oriented (reST, docbook, etc), and output oriented (lout, LaTeX). For books I want the best possible typesetting control and don't care about semantics (since I don't repurpose my text), so I chose an output oriented markup. (I know this is a gross simplification --- I'm not trying to start a religious debate.) I haven't used LaTeX much, but here're my main reasons for using lout: - easy to do easy stuff; hard stuff possible - everything in one package (tables, equations, drawing, charts, etc) - I can't draw but I can tell lout to draw for me and that works well for my simple needs - embedding graphics (e.g., screenshots) is easy (just convert to EPS) - lout lets me specify Type1 fonts so I can easily use my own custom Venus font for code & it is easy to embed it which makes publication easier - lots of books that use LaTeX have a certain sameness & I don't like the computer modern fonts (IMO -- no offence intended) - after more than a decade of using lout I can pretty well get it to do anything & everything I want (but I don't claim to be an expert user) IMO lout has three major downsides: - doesn't support Unicode - doesn't support Type1 fonts (well, apparently it does but I haven't managed it) - is much slower than LaTeX; so I'm told, but never been a problem for me except: - the design of the support for indexes is awful & index generation is slowwww (If you want to know how more about lout please ask me off-list or ask on the lout mailing list since this is now way off-topic:-) From enleverlesX.XmcX at XmclaveauX.com Tue Dec 2 15:59:01 2008 From: enleverlesX.XmcX at XmclaveauX.com (=?utf-8?Q?M=C3=A9ta-MCI_=28MVP=29?=) Date: Tue, 2 Dec 2008 21:59:01 +0100 Subject: Multiple Versions of Python on Windows XP In-Reply-To: References: Message-ID: <4935a3d1$0$945$ba4acef3@news.orange.fr> Hi! Multiple versions of Python is possible (example: Python standard + Python by OOo). But, multiple versions of Python+PyWin32 is not possible. Suggestion: use VirtualBox or Virtual-PC. @-salutations -- Michel Claveau From prologic at shortcircuit.net.au Mon Dec 29 19:05:06 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 30 Dec 2008 10:05:06 +1000 Subject: multiprocessing vs thread performance In-Reply-To: References: Message-ID: On Tue, Dec 30, 2008 at 12:52 AM, mk wrote: > Hello everyone, > > After reading http://www.python.org/dev/peps/pep-0371/ I was under > impression that performance of multiprocessing package is similar to that of > thread / threading. However, to familiarize myself with both packages I > wrote my own test of spawning and returning 100,000 empty threads or > processes (while maintaining at most 100 processes / threads active at any > one time), respectively. > > The results I got are very different from the benchmark quoted in PEP 371. > On twin Xeon machine the threaded version executed in 5.54 secs, while > multiprocessing version took over 222 secs to complete! > > Am I doing smth wrong in code below? Or do I have to use > multiprocessing.Pool to get any decent results? The overhead in starting OS level processes is quite high. This is why event-driven, single process servers can perform far better than ones that fork (spawn multiple processes) per request. As others have mentioned, it's not suprising that spawning even 100 processes took some time. Bottom line: multiprocessing should not be used this way. (nor should threading). cheers James From prologic at shortcircuit.net.au Mon Dec 15 19:00:38 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 16 Dec 2008 10:00:38 +1000 Subject: parse C expression? In-Reply-To: References: Message-ID: On Tue, Dec 16, 2008 at 9:48 AM, Torsten Mohr wrote: > Hi, > > i found some examples when googling for the subject but nothing really > matched. > > Is there a standard module available that lets me parse a syntax like "C" > with numbers, operators, braces, variables and function calls? Try pyparsing. cheers James From clp at rebertia.com Mon Dec 1 16:30:51 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 1 Dec 2008 13:30:51 -0800 Subject: Why doesn't doc has predifined name and location ? In-Reply-To: <493455AD.4040306@gmail.com> References: <493455AD.4040306@gmail.com> Message-ID: <47c890dc0812011330m1965757cgc7d21f971f01c305@mail.gmail.com> On Mon, Dec 1, 2008 at 1:22 PM, Stef Mientki wrote: > hello, > > I'm very satisfied about the great standardization of doc strings in python. > Now in contrast to that, > the general documentation of libraries, > either in plain text, html, pdf, chm, ... > doesn't have a standarized name nor location. > > Why is that ? I suppose the need for such standardization has just never arisen. Googling for docs, checking the library's website, or doing `locate library-name-here | grep doc` in bash seems to work well enough for people that no one has found it necessary to pursue the creation of such a standard. Sidenote: what Python projects publish their docs in CHM besides possibly Win32 GUI programs? Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > thanks, > Stef Mientki > -- > http://mail.python.org/mailman/listinfo/python-list > From Lie.1296 at gmail.com Sat Dec 6 06:37:48 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 6 Dec 2008 03:37:48 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> <00ab327a-c3fc-4b15-a084-4f8c6aed6a8e@o2g2000yqd.googlegroups.com> <8119ab7e-09f1-44de-bdbc-8fdff969d9e4@33g2000yqm.googlegroups.com> <36056737-3c78-499a-a81d-f6241e904460@t11g2000yqg.googlegroups.com> Message-ID: On Dec 3, 10:06?am, r wrote: > "If we can laugh what else would we do" > > I'd like to touch also on some comments by ajaksu: > [ajaksu] > I'd like to try hacking some form of Python to work in SketchUp (on > top of Ruby, that is). Now, why won't I try to? I'm a Linux user and > we don't get a SU version. So much for FREEDOM. BTW, some things in > SU > have encrypted Ruby code behind them :) > [/ajaksu] > > You CAN use SketchUp on Linux...ajaksu...thru Wine, but I know this is > not good enough. I would love to see FULL SketchUp support for linux > and I HAVE made my voice heard. I urge you brother to make make your > voice heard also. > > Go to this thread and let your voice be heard:http://groups.google.com/group/sketchupsuggestions/browse_thread/thre... > > This is the reason...amoung many others...that Linux has yet to take > any noticable market from MS. Linux could...If the Linux devolpers > would ban together and unite to make package managment and portability > between all *nix's universal, OR one great linux distro that the > average dummy can use(ubuntu looks promising, but still has a long way > to go)...compete with microsoft on a grand level. We have to steal the > idiots from under microsoft's feet, and they will come crumbling down. > But as long as a poor n00b installs his shiny new *nix system and > can't even connect to the network to see the latest janet jackson > "wardrobe malfunction", or fiqure out how to mount a flash drive, > Linux will be nothing more than our beloved oddessy. > > There will NEVER be good support on linux for most applications, > games, etc... Until people start to get behind linux and support it. > Now you say, well i don't have time to support this, my life is too > busy, my back hurts. I say stop making excuses. You DON'T have to > invest your life, just simply make your voice heard.(myself and other > dedicated people will tow the load). But at least get off your bum and > do something. > > It's time to change the world, the hour is upon us, Microsoft is > asleep at the wheel, the time for revolution is NOW! Action speaks louder than words. Not that I have done anything than talking lately though. For Google to implement a huge feature like python scripting, they would want to calculate its business feasibility (though Google is one of the rare companies that is extremely lax on this side). Sketchup's target users is not power users but those who need quick sketches, so scripting isn't an extremely important feature in Sketchup. Moreover, if they implement python scripting because someone wants it, other languages would demand the same. So, it does have to start from you creating a python-extension and getting enough users to make Google think: "There are much more python programmers than Ruby programmers in Sketchup, implementing python scripting would be a sound decision." From bearophileHUGS at lycos.com Fri Dec 26 20:31:39 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 26 Dec 2008 17:31:39 -0800 (PST) Subject: ruby -> python translator exists? References: <04b51f42-e18e-4902-8a98-38f0538c1eda@s9g2000prg.googlegroups.com> Message-ID: <4a10794e-a3e7-4aa4-8d21-580152806277@c36g2000prc.googlegroups.com> rogerdpack: > Hi all. ?My name is Roger. Hello Roger, my name is bearophile. > Anybody know of a Ruby -> Python translator at all? ?I'm looking for a > way to have my Ruby code take advantage of the coolio speed of Psyco. I have never heard of such translator, so far. > Also question. Does psyco work with Python 3.0? It doesn't work with Python3 and you may need lot of time to see it come out... if you will ever see it. Bye, bearophile From gagsl-py2 at yahoo.com.ar Sat Dec 27 21:33:36 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 28 Dec 2008 00:33:36 -0200 Subject: math module for Decimals References: Message-ID: En Sat, 27 Dec 2008 22:02:51 -0200, escribi?: > I have been looking for a Python module with math functions that would > both eat and spit Decimals. The standard math module eats Decimals > allright but spits floats... herefore exp(sin(Decimal())) produces exp > () of a float :-( Which math functions? ln, log10, exp, sqrt already exist as methods of Decimal instances. At the end of the Decimal docs there are a few examples, including computing sin and cos (but apparently they na?vely use a McLaurin series like you noticed in other module). There is a way to convert a float into a Decimal object with no loss in precision, see the FAQ (using float.as_integer_ratio(), I think such function was implemented for exactly this use case) So you might convert to float, operate, and go back -- if the precision of "double" operands is enough for you. -- Gabriel Genellina From ivlenin at gmail.com Mon Dec 15 00:49:45 2008 From: ivlenin at gmail.com (I V) Date: Mon, 15 Dec 2008 05:49:45 GMT Subject: Looking for the best way to translate an idiom References: Message-ID: On Sun, 14 Dec 2008 21:08:33 -0800, James Stroud wrote: > Yes. I think it was the British who decided that the apostrophe rule for > "it" would be reversed from normal usage relative to just about every > other noun. I'm not sure the purpose--maybe it was to give compulsive > proofreaders a raison d'etre. It's because "it" is a pronoun; you don't put an apostrophe in "his," either. From __peter__ at web.de Wed Dec 24 03:46:51 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 24 Dec 2008 09:46:51 +0100 Subject: Strategy for determing difference between 2 very large dictionaries References: <1230102996.2303.1291616055@webmail.messagingengine.com> Message-ID: Gabriel Genellina wrote: > En Wed, 24 Dec 2008 05:16:36 -0200, escribi?: [I didn't see the original post] >> I'm looking for suggestions on the best ('Pythonic') way to >> determine the difference between 2 very large dictionaries >> containing simple key/value pairs. >> By difference, I mean a list of keys that are present in the >> first dictionary, but not the second. And vice versa. And a list >> of keys in common between the 2 dictionaries whose values are >> different. >> The 2 strategies I'm considering are: >> 1. Brute force: Iterate through first dictionary's keys and >> determine which keys it has that are missing from the second >> dictionary. If keys match, then verify that the 2 dictionaries >> have identical values for the same key. Repeat this process for >> the second dictionary. >> 2. Use sets: Create sets from each dictionary's list of keys and >> use Python's set methods to generate a list of keys present in >> one dictionary but not the other (for both dictionaries) as well >> as a set of keys the 2 dictionaries have in common. > > I cannot think of any advantage of the first approach - so I'd use sets. > > k1 = set(dict1.iterkeys()) > k2 = set(dict2.iterkeys()) > k1 - k2 # keys in dict1 not in dict2 > k2 - k1 # keys in dict2 not in dict1 > k1 & k2 # keys in both > >> Using the set >> of keys in common, compare values across dictionaries to >> determine which keys have different values (can this last step be >> done via a simple list comprehension?) If you are not interested in the intermediate results and the dictionary values are hashable you can get the difference by >>> a = dict(a=1, b=2, c=3) >>> b = dict(b=2, c=30, d=4) >>> dict(set(a.iteritems()) ^ set(b.iteritems())) {'a': 1, 'c': 3, 'd': 4} Peter From luismgz at gmail.com Fri Dec 12 12:36:40 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Fri, 12 Dec 2008 09:36:40 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> <8156b37b-d1f6-4142-ad6e-8488c95b6592@z28g2000prd.googlegroups.com> Message-ID: On Dec 12, 11:17?am, sturlamolden wrote: > On Dec 12, 3:04 pm, Luis M. Gonz?lez wrote: > > > Why don't you guys google a little bit to know what's being done to > > address python's "slowness"?? > > Nothing is being done, and woth Py3k it got even worse. > > > It has been mentioned in this thread the pypy project (isn't it enough > > for you??) > > Other hints: shedskin, psyco, pyrex... > > None of those projects addresses inefficacies in the CPython > interpreter, except for psyco - which died of an overdose PyPy. > > PyPy is interesting if they ever will be able to produce something > useful. They have yet to prove that. Even if PyPy can come up with a > Python JIT, they will still be decades behind the technologies of > Strongtalk and Java. That is the problem with reinventing the wheel > all over again. > > Not to forget LLVM and Parrot which also will support Python > frontends. So, what's your conclusion? From mark at qtrac.eu Thu Dec 4 10:02:21 2008 From: mark at qtrac.eu (Mark Summerfield) Date: Thu, 04 Dec 2008 15:02:21 +0000 Subject: ANN: New Book: Programming in Python 3 Message-ID: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> Now that Python 3 final has been released I thought it would be a good time to mention that there's a new book to go with it: "Programming in Python 3: A Complete Introduction to the Python Language" ISBN 0137129297 http://www.qtrac.eu/py3book.html I've been working on this for more than a year, testing the examples against every Python 3 alpha and beta, and against the final release (using Python's unit test and doctest modules of course:). The book has just gone into production and should be available in print at the end of this month in the U.S., and a month or two later elsewhere. The book's web page has links to a draft of the introduction and to safari books online where you can read extracts. The book is aimed at a wide audience, but assumes some programming experience (not necessarily Python, not necessarily object-oriented). It teaches solid procedural style programming, then builds on that to teach solid object-oriented programming, and then goes on to more advanced topics (e.g., including a nice way to create validated attributes by combining class decorators with descriptors). But even newcomers to Python 3 should be able to write useful (although small and basic) programs after reading chapter 1, and then go on to create larger and more sophisticated programs as they work through the chapters. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu From narkewoody at gmail.com Sun Dec 21 21:23:03 2008 From: narkewoody at gmail.com (Steven Woody) Date: Mon, 22 Dec 2008 10:23:03 +0800 Subject: How to represent a sequence of raw bytes Message-ID: Hi, What's the right type to represent a sequence of raw bytes. In C, we usually do 1. char buf[200] or 2. char buf[] = {0x11, 0x22, 0x33, ... } What's the equivalent representation for above in Python? Thanks. - narke From zhushenli at gmail.com Thu Dec 4 08:37:04 2008 From: zhushenli at gmail.com (Davy) Date: Thu, 4 Dec 2008 05:37:04 -0800 (PST) Subject: time.sleep() and Tkinter after()? References: <03613d37-ca4f-4962-bce2-eea0a3f65952@r15g2000prd.googlegroups.com> Message-ID: On Dec 5, 3:05?am, "Hendrik van Rooyen" wrote: > "Davy" wrote: > > I have used Tkinter after() to do loop update GUI in my previous post. > > And I tried to change after() to time.sleep(), but it seems doesn't > > work at all, the Queue send and receive data properly, but the GUI > > didn't even appear? > > > //-----code changed----- > > def draw_canvas_loop(canvas_b): > > ? ? while (True): > > ? ? ? ? board = data_queue.get(block = True, timeout=2) > > Do you want it to block, or do you want it to time out? Hi Hendrik, nice comments :-) Do you think block and time out are contradict to each other? > > > ? ? ? ? print 'get', data_queue.qsize() > > ? ? ? ? draw_canvas(board, canvas_b, x, y, block_width, block_height) > > ? ? ? ? time.sleep(0.3) > > this will make the gui unresponsive for the time > > > ? ? ##canvas_b.after(300, lambda:draw_canvas_loop(canvas_b)) > > and then the control runs off the end of the function. > > > So, can I use time.sleep() in GUI application? Or Tkinter scheduler > > just ignore the sleep() function? > > time.sleep(sleep_time) will effectively suspend the gui mainloop > (if it is in the mainloop) for the sleep_time, making the gui unresponsive > for that time. ?Eschew it here. ?Use it in other, non GUI helper threads. Although I don't understand your explaination very well(I guess maybe .after() re-schedule is better than .sleep unresponsive in GUI application?)I will take it as a golden rule. > > > > > And if I use after(), will the code form a recursive function call, > > only if it is coded that way - yours does not look recursive to me > > > and the memory usage will boost as the program goes (I have watched > > the task manager in WinXP and find the python.exe eat more and more > > memory...). > > def draw_canvas_loop(canvas_b): > > ? ? board = data_queue.get(block = True, timeout=1) > > ? ? print 'get', data_queue.qsize() > > ? ? draw_canvas(board, canvas_b, x, y, block_width, block_height) > > Here you draw a new canvas object - what has happened to the > previous one? Is it possibly still hanging around? Should you > do something about it? Yeah, I forgot to *delete* the rectangle object I generate before. One more question, besides create/delete method, can I just create two rectangles (one black/one white), and assign two tags to these two rectangles, and place rectangle by just using tags(that is, can I place one object on several places of the canvas)? > > - Hendrik From steve at holdenweb.com Tue Dec 2 22:53:47 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 02 Dec 2008 22:53:47 -0500 Subject: Do more imported objects affect performance In-Reply-To: <1be78d220812010621u51dead9dnbaa0b4c8c9414362@mail.gmail.com> References: <1be78d220812010621u51dead9dnbaa0b4c8c9414362@mail.gmail.com> Message-ID: <493602CB.2020907@holdenweb.com> Filip Gruszczy?ski wrote: [something I moved to after Nick's reply, where it belongs] > 2008/12/1 Nick Craig-Wood : >> Rafe wrote: >>> On Dec 1, 7:26?am, "Filip Gruszczy?ski" wrote: >>>> I have following question: if I use >>>> >>>> from module import * >>>> >>>> instead >>>> >>>> from module import Class >>>> >>>> am I affecting performance of my program? I believe, that all those >>>> names must be stored somewhere, when they are imported and then >>>> browsed when one of them is called. So am I putting a lot of "garbage" >>>> to this storage and make those searches longer? >>> Why use it if you don't need it? Your post implies a choice and the >>> '*' import can really make things muddy if it isn't actually necessary >>> (rare). Why not just import the module and use what you need? It is >>> way easier to read/debug and maintains the name-space. >> Importing the module is actualy slower... If you import the name into >> your namespace then there is only one lookup to do. If you import the >> module there are two. >> >> $ python -m timeit -s 'from timeit import Timer' 'Timer' >> 10000000 loops, best of 3: 0.0784 usec per loop >> >> $ python -m timeit -s 'import timeit' 'timeit.Timer' >> 1000000 loops, best of 3: 0.243 usec per loop >> >> I'm not suggestion you should ever use "from module import *" only >> ever import the things you actually need, eg >> "from module import MyClass, my_function" >> >> And here is the test again, actually calling something with the same >> difference in execution speed :- >> >> $ python -m timeit -s 'from os import nice' 'nice(0)' >> 1000000 loops, best of 3: 1.21 usec per loop >> >> $ python -m timeit -s 'import os' 'os.nice(0)' >> 1000000 loops, best of 3: 1.48 usec per loop >> > I see. Thanks for a really good explanation, I like to know, how to do > things in the proper way :) > Pardon me for intruding, but timings here are entirely the wrong focus for a Python newcomer. Given that imports are super-optimized (i.e. the code in the module is only performed once) such a small difference in timing is inconsequential, I would suggest. As long as "from module import *" is only ever used with modules specifically designed to support it, the other forms can be used as required. Sure, there is a timing difference between import module ... module.something() and from module import something ... something() but that's hardly the point. Learning to write sound Python is *much* more important that learning to write fast Python, and often the two coincide anyway. It was true when Kernighan and Plauger wrote it forty years ago and it's true now: "First, make it work. Then, *if it doesn't work fast enough*, make it work faster". regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From banibrata.dutta at gmail.com Sat Dec 27 01:10:47 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Sat, 27 Dec 2008 11:40:47 +0530 Subject: ruby -> python translator exists? In-Reply-To: <9c579c5a-ac9f-4716-8300-6d41ed52fd72@a26g2000prf.googlegroups.com> References: <04b51f42-e18e-4902-8a98-38f0538c1eda@s9g2000prg.googlegroups.com> <4a10794e-a3e7-4aa4-8d21-580152806277@c36g2000prc.googlegroups.com> <72c2df21-db59-4870-9388-ccaa47cf11e4@20g2000yqt.googlegroups.com> <9c579c5a-ac9f-4716-8300-6d41ed52fd72@a26g2000prf.googlegroups.com> Message-ID: <3de8e1f70812262210oa41d804g4cb2ec4c6ded3e40@mail.gmail.com> http://github.com/why/unholy/tree/master On Sat, Dec 27, 2008 at 11:19 AM, rogerdpack wrote: > > Search for the tool "Unholy". -- Al > > Thank you for your replies. > -=r > -- > http://mail.python.org/mailman/listinfo/python-list > -- regards, Banibrata http://www.linkedin.com/in/bdutta http://octapod.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 8 08:18:57 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 08 Dec 2008 14:18:57 +0100 Subject: Public imports In-Reply-To: <9623b0a3-7053-41f1-b116-0cd5e54f39e9@v13g2000vbb.googlegroups.com> References: <9623b0a3-7053-41f1-b116-0cd5e54f39e9@v13g2000vbb.googlegroups.com> Message-ID: <493d1ec0$0$32048$426a34cc@news.free.fr> M?rcio Faustino a ?crit : > Hi, > > Does Python support public imports instead of the default private? Python has no notion of "public" or "private" !-) > Something like D's "public import" (see 2.0/module.html>) Python imports don't work as D imports (as far as I can tell from the above link). The Python import statement binds imported name - whether the module object itself[1] or the explicitely[2] or implicitely[3] specified names from the module object - into the importing module's namespace. [1] import some_module [2] from some_module import some_name [3] from some_module import * IOW, if module_b imports module_a and module_c import module_a, module_a will be accessible in module_c as module_b.module_a. If module_b import name_x from module_a and module_c imports module_b, name_x will be accessible in module_c as module_b.name_x. Etc, etc.... HTH From zaz600 at gmail.com Thu Dec 25 07:36:17 2008 From: zaz600 at gmail.com (NoName) Date: Thu, 25 Dec 2008 04:36:17 -0800 (PST) Subject: SyntaxError: encoding problem: with BOM References: <6res8tF1do1sU1@mid.uni-berlin.de> <400f176b-bd9a-4f26-b01b-1aa7c7dcf5ac@z6g2000pre.googlegroups.com> <6rf6m1F1e0f8U1@mid.uni-berlin.de> Message-ID: On 25 ???, 03:35, "Diez B. Roggisch" wrote: > NoName schrieb: > > > > > On 25 ???, 00:37, "Diez B. Roggisch" wrote: > >> NoName schrieb: > > >>> i have 1.py in cp866 encoding: > >>> # -*- coding: cp866 -*- > >>> print ("ff") > >>> It's not work in Python 3.0 > >>> Error: > >>> File "", line 1 > >>> SyntaxError: encoding problem: with BOM > >>> what's wrong? > >> I can only guess, but just because you write the coding-header that > >> doesn't mean that the editor you use does actually *use* that encoding. > >> What I presume it does is to use utf-8, and write that stupid BOM > >> microsoft uses for denoting utf-8-content as first byte. Try using a > >> different editor, or alter it's settings to really use your desired > >> encoding. > > >> Diez > > > I used Far Manager editor. and it *really* used cp866 > > I can print hex dump of source file. > > I don't want to use UTF-8 for py-file! > > How about you show us the python file in question? > > diez you can get it here http://slil.ru/26481345 From excord80 at gmail.com Tue Dec 9 22:28:48 2008 From: excord80 at gmail.com (excord80 at gmail.com) Date: Tue, 9 Dec 2008 19:28:48 -0800 (PST) Subject: How do I manually uninstall setuptools (installed by egg)? References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> Message-ID: <7ca0d6d8-983c-4354-b49a-84461fe5a034@g17g2000prg.googlegroups.com> On Dec 9, 10:15?pm, rdmur... at bitdance.com wrote: > On Tue, 9 Dec 2008 at 18:49, excor... at gmail.com wrote: > > On Ubuntu, I accidentally manually installed setuptools > >http://pypi.python.org/pypi/setuptools/0.6c9(by running the .egg file > > as a shell script via sudo), and now realize I should just be using > > apt to take care of my system Python packages. I also installed one or > > two packages using its ``easy_install``. > > > Looks like it lives in ``/usr/lib/python2.5/site-packages``. > > > How can I manually remove those packages installed using that > > ``easy_install``, and then manually remove the setuptools package I > > installed? > > rm -r /usr/lib/python2.5/site-packages/ Ok. "" presumably refers to the packages I installed using the ``easy_install`` command. I'm guessing I should also jettison the ``setuptools-0.6c9-py2.5.egg`` and ``setuptools.pth`` files. > Then find the .pth file (in the site-packages directory) that > references the egg, and delete the line referencing the egg. I guess you mean the ``easy-install.pth`` file. Ok. I should probably also get rid of ``/usr/bin/easy_install`` and ``/usr/ bin/easy_install-2.5``... > Setuptools has no uninstall function, as far as I know. Unfortunate. It's usually one of the first things I look for in a piece of software. Thanks. From kirk at daycos.com Thu Dec 11 11:24:13 2008 From: kirk at daycos.com (Kirk Strauser) Date: Thu, 11 Dec 2008 10:24:13 -0600 Subject: newbie question: if var1 == var2: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> Message-ID: <87abb21xzm.fsf@daycos.com> At 2008-11-29T04:02:11Z, Mel writes: > You could try > > for item in fname: > item = item.strip() This is one case where I really miss Perl's "chomp" function. It removes a trailing newline and nothing else, so you don't have to worry about losing leading or trailing spaces if those are important to you. -- Kirk Strauser The Day Companies From skip at pobox.com Tue Dec 23 15:05:31 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 23 Dec 2008 14:05:31 -0600 Subject: pseudo terminal usage from Python? In-Reply-To: References: <5t-dnRgMi9Z4lszUnZ2dnUVZ_vOdnZ2d@posted.visi> Message-ID: <18769.17547.722458.304993@montanaro-dyndns-org.local> Grant> Are you sure it's not Python buffering its input? Have you tried Grant> "python -u mympstat.py"? >> Nope. -u unbuffers stdout and stderr, not stdin. It really must be >> mpstat being uncooperative. Grant> That's not what my python man page says: Grant> -u Force stdin, stdout and stderr to be totally Grant> unbuffered. On systems where it matters, also put Grant> stdin, stdout and stderr in binary mode. Grant> That's for 2.5.2, but that's how I remember previous versions Grant> working as well. I'm still running 2.4.5 at work. It's -u help: -u : unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x) see man page for details on internal buffering relating to '-u' Was stdin unbuffering maybe added in 2.5? Skip From bearophileHUGS at lycos.com Fri Dec 12 07:14:19 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 12 Dec 2008 04:14:19 -0800 (PST) Subject: (Very Newbie) Problems defining a variable References: <49425146$0$8495$426a74cc@news.free.fr> <11c53a4a-de1e-4bee-ad60-a05befb6cbf4@a12g2000yqm.googlegroups.com> Message-ID: <7cb69ff5-9034-41cc-b667-d69329707b18@d36g2000prf.googlegroups.com> feba: > ? ? ? ? if bank <= 0: > ? ? ? ? ? ? ? ? print("You're in the red!") > ? ? ? ? ? ? ? ? quit() > ? ? ? ? elif bank >= 1 and bank <= 9999: > ? ? ? ? ? ? ? ? rate = 0.0060 > ? ? ? ? elif bank >= 10000 and bank <= 24999: > ? ? ? ? ? ? ? ? rate = 0.0085 > ? ? ? ? elif bank >= 25000 and bank <= 49999: > ? ? ? ? ? ? ? ? rate = 0.0124 > ? ? ? ? elif bank >= 50000 and bank <= 99999: > ? ? ? ? ? ? ? ? rate = 0.0149 > ? ? ? ? elif bank >= 100000: > ? ? ? ? ? ? ? ? rate = 0.0173 > ? ? ? ? else: > ? ? ? ? ? ? ? ? print("What's this doing here?") I think your indents are a little too much large (the soft standard is 4 spaces). The last else can be removed. Does bank == 0 mean being in red? That list of if-elif seems bug-prone. In the future you will learn ways to write that in a less bug-prone (but also probably more complex to read and understand) way. Bye, bearophile From castironpi at gmail.com Mon Dec 29 20:34:46 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 17:34:46 -0800 (PST) Subject: multiprocessing vs thread performance References: Message-ID: <26f7d44e-552c-41e9-9290-17e5c4e6deb9@q30g2000prq.googlegroups.com> On Dec 29, 6:05?pm, "James Mills" wrote: > On Tue, Dec 30, 2008 at 12:52 AM, mk wrote: > > Hello everyone, > > > After readinghttp://www.python.org/dev/peps/pep-0371/I was under > > impression that performance of multiprocessing package is similar to that of > > thread / threading. However, to familiarize myself with both packages I > > wrote my own test of spawning and returning 100,000 empty threads or > > processes (while maintaining at most 100 processes / threads active at any > > one time), respectively. snip > As others have mentioned, it's not suprising > that spawning even 100 processes took some > time. > > Bottom line: multiprocessing should not be used this way. > (nor should threading). The OP may be interested in Erlang, which Wikipedia (end-all, be-all) claims is a 'distribution oriented language'. You might also find it interesting to examine a theoretical OS that is optimized for process overhead. In other words, what is the minimum overhead possible? Can processes be as small as threads? Can entire threads be only a few bytes (words) big? Also, could generators provide any of the things you need with your multiple threads? You could, say, call 'next()' on many items in a list, and just remove them on StopIteration. From deets at nospam.web.de Sat Dec 20 06:59:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 20 Dec 2008 12:59:00 +0100 Subject: [OT] Re: IMAP: How to implement GMail-like threaded conversations view In-Reply-To: References: Message-ID: <6r4504FfpdmiU1@mid.uni-berlin.de> > Anything else is madness. And the fact the Outlook doesn't do proper > referral fields just infuriates me. Sigh. I'm overjoyed about the opaque winmail.dat attachments I get. Which seem to appear randomly from the same sender sending the same stuff (like a meeting invitation) to me - depending on the moon cycle or something I presume... Diez From israelu at elbit.co.il Wed Dec 31 08:04:15 2008 From: israelu at elbit.co.il (iu2) Date: Wed, 31 Dec 2008 05:04:15 -0800 (PST) Subject: Pass by reference References: <529e1d98-8932-49f0-b569-85285bd50f23@p2g2000prn.googlegroups.com> Message-ID: On Dec 31, 1:48?pm, "Chris Rebert" wrote: ... > > Not really, or at the very least it'll be kludgey. Python uses > call-by-object (http://effbot.org/zone/call-by-object.htm), not > call-by-value or call-by-reference. > > Could you explain why you have to set so many variables to the same > value (if they're None)? It's a bit strange and could be a sign that > there's a better way to structure your program (e.g. use a > dictionary). We might be able to offer more helpful suggestions if you > explain. > > Cheers, > Chris > > -- Hi, thanks for your reply. Well, I wrote an application that talks via UDP to several targets (embedded). Currently there are only two of them connected to my PC, but there could be more. Let's call them target 1 and target 2. Now, each target has its own IP address, and is connected straight to my PC, no DHCP or common bus or whatsover The GUI of my application enables the user to enter the IP for each target. The user can disconnect one target, and then connect a different one with a different IP. Let's say he replaces target 2 with a different one. Then he must tell the python app that target 2 now has a different IP. He does that by entering a different IP for target 2 in the GUI. When the app sends data to a target, it must know whether to create a new socket or use the previous one for that target. It deduces this by observing a change in the IP address in the GUI for that target. For the 2 targets I have the variables comm1 and comm2. They are of some class I wrote, representing many properties of the communication, including the IP address. There is one function that sends data, and it receives a commX var (comm1 or comm2) as the means for sending the data. Before sending the data the function needs to initilze commX (if it is still None), or creating it a new, if it sees that the IP for that target has changed. Something like this: def send_data(comm, data, current_ip_from_gui): if comm is None: # I want to assign comm a new MyComm elif comm.ip != current_ip_from_gui: # I want to re-assign a new MyComm that uses the new IP comm.socket.SendTo(comm.addr, data) # eventually send the data I could re-design it to have send_data be a method of MyComm. But I don't think I should, beacuse I planned MyComm to have only properties. I'd like functions to receive it and manipulate it. MyComm could also be a mere string just as well... Since I can apply this idiom in C (pointer), Lisp (macro), tcl (upvar) and C# (ref) I wondered what the python way was. But I guess I can achieve this using a class holding my vars, maybe like this: class CommVars: comm1 = None comm2 = None myvars = CommVars() and then change a value like this: def set_var(dict0, varname, val): dict0[varname] = val set_var(myvars.__dict__, 'comm1', MyComm(...)) From stef.mientki at gmail.com Thu Dec 25 05:00:18 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 25 Dec 2008 11:00:18 +0100 Subject: Is there a function to remove escape characters from a string ? Message-ID: <495359B2.10201@gmail.com> hello, Is there a function to remove escape characters from a string ? (preferable all escape characters except "\n"). thanks, Stef From aioe.org at technicalbloke.com Fri Dec 5 19:52:20 2008 From: aioe.org at technicalbloke.com (r0g) Date: Fri, 05 Dec 2008 19:52:20 -0500 Subject: Progressive download with Urllib2. Message-ID: Hi There, I am trying to download some video with python but have run aground on the rocky shores of pseudostreaming. Fingers crossed someone else here has some experience with this! Here's what I've done so far... The initial link is foo.asx so I download that with... handle = urllib2.urlopen( 'http://www.example.com/foo.asx' ) mime_type = url_handle.info().getheader("Content-Type","") data = urllib2.read() It comes back with mime type of 'video/x-ms-asf' and the content... 'ASF http://www.example.com/foo-100.wmv' I then used the same code again to grab the URL (ditching the 'ASF ' bit) and this time it comes back with a mime type of 'video/x-ms-wvx' and two URLs... Ref1=http://www.example.com/foo-100.wmv?MSWMExt=.asf Ref2=http://192.168.0.1/foo-100.wmv?MSWMExt=.asf The latter is no use as it's on a private LAN and the second is the same URL as last time, just with a different mime type and naturally it returns the same thing if I use Urllib2 open and read to fetch it with or without the '?MSWMExt=.asf' part. So... I fired up wireshark and spotted these lines coming back in the headers: Server: Cougar/9.01.01.3862 Supported: com.microsoft.wm.srvppair, com.microsoft.wm.sswitch, com.microsoft.wm.predstrm, com.microsoft.wm.fastcache, com.microsoft.wm.startupprofile Euw... I suspected for a second that meant I have to connect with a MS media player or something but the same URL works fine when I paste it into Firefox and the video starts pseudostreaming away so... How can I get their server to give me the video data? Do I need to ask for the file with some other protocol? RTSP? or change my user_agent string and pretend to be Windows Media Player?? Do I need another module as opposed to urllib2? and if so which one? I've had a search but drawn a blank. I guess I'll plug on in wireshark and see what some other programs do but I'd appreciate it if anyone can put me out of my misery! Yours stuck, Roger Heathcote. From castironpi at gmail.com Sat Dec 6 07:03:21 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 6 Dec 2008 04:03:21 -0800 (PST) Subject: Guido's new method definition idea References: Message-ID: <7c56a65c-ca99-4d00-b425-ae6385ff1a0a@v42g2000yqv.googlegroups.com> On Dec 5, 8:21?pm, "Daniel Fetchinson" wrote: > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... > > The proposal is to allow this: > > class C: > ? ? def self.method( arg ): > ? ? ? ? self.value = arg > ? ? ? ? return self.value > > instead of this: > > class C: > ? ? def method( self, arg ): > ? ? ? ? self.value = arg > ? ? ? ? return self.value > > I.e. explicit self stays only the syntax is slightly different and may > seem attractive to some. ... Would it be valid outside class definitions too? (As follows...) def sequence.shuffle( ): x= sequence[ 0 ] sequence[ 0 ]= sequence[ -1 ] ...etc. shuffle( listA ) Can you still call it by class membership? (As follows...) C.method( inst, arg ) From castironpi at gmail.com Sat Dec 6 06:48:55 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 6 Dec 2008 03:48:55 -0800 (PST) Subject: Don't you just love writing this sort of thing :) References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: <26f4ec27-91b9-4f87-9c12-023e1af0c86f@v13g2000yqm.googlegroups.com> On Dec 5, 7:20?pm, Lawrence D'Oliveiro wrote: > In message <32cf4a79-a6e3-4250-9b5a-1ec80c748... at j32g2000yqn.googlegroups.com>, Aaron Brady wrote: > > > On Dec 5, 4:32?am, Lawrence D'Oliveiro > central.gen.new_zealand> wrote: > > >> The code people write is probably a direct reflection of their thinking > >> processes: For example, slow, plodding, one step at a time, incapable of > >> imaginative leaps, versus those who operate directly on larger patterns > >> at once... > > > That distinction operates indirectly on smaller patterns. Well, I was trying to be funny. But sarcasm is defined as something said in jest that someone else would say seriously; so perhaps it's not the most reliable tone for text. Chalk it up to a failed communication, even though a successful expression. I agree that programming takes imaginative leaps and operates on large patterns. You implied that people's thinking processes vary by "pattern size", which I thought was interesting. But 'leaps' implies carelessness (wrong word, possibly). Is it possible to tackle a large pattern one step at a time? Say, writing a quick sort in assembly? > Do you find this > > (open, gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir, Entry), "r") > > complicated or hard to understand? It's not easy. I can't understand it at a glance, if that is your question. But it's not obfuscated, that is true. If I can compare programming to chess: I look at a board and you tell me, 'white to play, mate in 5 moves.' If the board is busy (not just Rook and King), it could take a long time to find the mate. It's complicated, but not hard to understand. It requires "holding" (introducing a term) several things in mind at once: first expose the Bishop, then capture the Pawn, etc. But it is not easy in the same way that a 'mate in one' board is, even though the pieces are the same. > It's made up of very simple pieces, > combined according to very simple rules, viz:- > > A tuple of candidate functions: > > ? ? (open, gzip.GzipFile) > > A choice from that tuple according to a condition: > > ? ? [Entry.endswith(".gz")] > > And finally, arguments to pass to the chosen function: > > ? ? (os.path.join(PatchesDir, Entry), "r") As you explain, your program (taking the fragment to be an entire program) is composed of three "very simple pieces". I would say, write them as three very simple pieces. Here's a possible compromise between yours and Arnaud's: if Entry.endswith(".gz"): opener= gzip.GzipFile else: opener= open opener( os.path.join(PatchesDir, Entry), "r" ) It's kind of swampy, I concede. About the same number of characters, 5x the lines. Maybe something in between: opener= (open, gzip.GzipFile)[Entry.endswith(".gz")] path= os.path.join(PatchesDir, Entry) opener( path, "r" ) > See, it's so simple, a child could understand it. A child who isn't burdened > with the preconceptions that seem to afflict some participants in this > noisegroup... 'No preconceptions' is a pretty tall order. The most basic facts about the natural numbers weren't formalized until the 1880s, but people used them successfully for thousands of years before, evidently on preconception alone. To be plodding and slow (as well as meticulous and deliberate, by the way), the child would need 'preconceptions' about tuples, functions, Boolean variables, etc. You might call those plain 'conceptions', and use the other definition, 'bias' for noisegroup participants. Emotions are biased, as are small sample sizes (small-sized samples). I think it's also a tall order to ask a group of people to keep objective for any length of time. Thus, since we're people, and we're interacting, and we can't keep objective forever, we'll be non- objective sometimes, and therefore won't all understand your program. Perhaps you are wanting to write a 'preconception-tolerant' program: a program that is tolerant of (can be read by) readers with preconceptions. But I'll bite: what preconceptions? Favoritism? From benjamin.kaplan at case.edu Tue Dec 9 17:25:59 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 9 Dec 2008 17:25:59 -0500 Subject: Is 3.0 worth breaking backward compatibility? In-Reply-To: References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> Message-ID: On Tue, Dec 9, 2008 at 3:56 PM, Lie Ryan wrote: > On Sun, 07 Dec 2008 21:48:46 +0000, Tim Rowe wrote: > > > 2008/12/7 walterbyrd : > >> IMO: breaking backward compatibility is a big deal, and should only be > >> done when it is seriously needed. > >> > >> Also, IMO, most of, if not all, of the changes being made in 3.0 are > >> debatable, at best. I can not think of anything that is being changed > >> that was really a "show stopper" anyway. > > > > > > But that's what a major release number does for you. Modula2 was quite a > > break from Modula. Think of Python3.0 it as a new language, if you like, > > that's inspired by Python2. You can stay with Python2 or you can adopt > > the new language. That way you won't have to think of it in terms of > > breaking any sort of backwards compatibility because there is no > > backwards ;-) > > > > -- > > Tim Rowe > > Actually I noticed a tendency from open-source projects to have slow > increment of version number, while proprietary projects usually have big > version numbers. > > Linux 2.x: 1991 Python 3.x.x: 1991. Apache 2.0: 1995. OpenOffice.org 3.0: > acquired by Sun at 1999. GIMP 2.x: 1995. Wine 1.x: 1993. > Wine actually timed the 1.0 release to be at about t the 15th "birthday" of the project. > > Compare with > Windows: NT 3.1-NT 6.x: 1993. Visual Studio 97, 6.0, .NET, .NET > 2003, .NET 2005, 2008: 1997. Photoshop (11 versions to CS4): 1987. > Microsoft Office 3, 4, 95, 97, 2000, XP, 2003, 2007: 1990. Flash MX, 9, > CS 1-4. iTunes 8: 2001. RealPlayer 4-11: 1995. Macintosh 1.0-9: > 1984-2001, X.5: 2001. Winzip 12.0: early 1990s. > Just to note: Office 2007 is also known as Office 12, if you want to look at version numbers. Also, Mac OS hasn't increased the major version number past 10 since they switched from their own proprietary kernel to using the open-source Darwin. > > Interestingly, many linux _distro_ also inhibit this quick version number > change. Fedora 10, Ubuntu is 2 years old, version 8 (they start from > version 6 not 1). > That's because 8 isn't the verison number- it's the year the version was released (8.10 is October 2008, not the 10th update to version 8). > Probably having higher version numbers sells better and looks more > attractive (since it'd make it seem like the software is not a new > product), having quick changing version number also makes users doesn't > mind compatibility breaks. Also a pattern is that prop software often > change how they version their product, (extreme example: visual studio: > from using years, version number, .NET, .NET + Year, back to year). > Changing how you version your product would make it "looks" like it's a > fresh new product (boring ol' photoshop 9 looks fresh with the new CS- > tag). > By having quick changing version number and often changing how product is > versioned, vendors could also say: "its two/three major version away, we > don't support that feature anymore since a veeery long time". > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rileyrgdev at gmail.com Tue Dec 2 17:04:58 2008 From: rileyrgdev at gmail.com (Richard Riley) Date: Tue, 02 Dec 2008 23:04:58 +0100 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: Petite Abeille writes: > On Dec 2, 2008, at 9:21 PM, Lew wrote: > >> These are professional software development forums, not some script- >> kiddie cellphone-based chat room. "r" is spelled "are" and "u" should >> be "you". > > While Xah Lee arguably represents a cross between "Enfant Provocateur" > [1] and "Evil Clown" [2], this surely qualifies as a "Grammarian" > [3] rebuke :D > > Cheers, >From being mildly shocked at such a telling off for minor shortcuts I would suggest more of a http://redwing.hutman.net/~mreed/warriorshtm/android.htm It would seem the soul contributions made are rebukes and petty prodding. Every group has one. > > -- > PA. > http://alt.textdrive.com/nanoki/ > > > [1] http://redwing.hutman.net/~mreed/warriorshtm/enfantprovocateur.htm > [2] http://redwing.hutman.net/~mreed/warriorshtm/evilclown.htm > [3] http://redwing.hutman.net/~mreed/warriorshtm/grammarian.htm -- important and urgent problems of the technology of today are no longer the satisfactions of the primary needs or of archetypal wishes, but the reparation of the evils and damages by the technology of yesterday. ~Dennis Gabor, Innovations: Scientific, Technological and Social, 1970 From prologic at shortcircuit.net.au Wed Dec 10 01:00:20 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 10 Dec 2008 16:00:20 +1000 Subject: List Problem In-Reply-To: References: Message-ID: On Wed, Dec 10, 2008 at 3:40 PM, dongzhi wrote: > If I execute part[1], I have got 'a'. If I execute part[2], I have > got ' '. But, if I execute part[1::2], I have got ['a', '', '']. I > don't know why. Please tell me why. Perhaps you meant: part[1:2] pydoc list This will tell you there are 3 arguments to __getslice__ i, j, y Without doing any further reading I presume from my experience that this works much like range and xrange and that the 3rd parameter is the step size. Consider this: >>> x = [9, 1, 2, 3, 4] >>> x [9, 1, 2, 3, 4] >>> x[1:2] [1] >>> x[1::2] [1, 3] >>> x[1::1] [1, 2, 3, 4] >>> x[1::2] [1, 3] >>> x[1::3] [1, 4] >>> cheers James -- -- -- "Problems are solved by method From njuk.njuk at gmail.com Thu Dec 4 21:54:42 2008 From: njuk.njuk at gmail.com (njuk.njuk at gmail.com) Date: Thu, 4 Dec 2008 18:54:42 -0800 (PST) Subject: allocating an unsigned int memory buffer for C (swig) struct Message-ID: <30e7f6aa-eae4-4b4e-bced-797b27aee2e1@r37g2000prr.googlegroups.com> i am using python (via swig) to interface with the comedi (http:// www.comedi.org/) library for some simple data acquisition. a general category of problems i am having has to do with basic comedi structs whose members require being set to a pointer of an allocated memory buffer. one specific example is the 'insn' struct that has a 'data' member that should point to a buffer i have previously allocated. the comedi type is 'lsampl_t*' but underneath this is simply an 'unsigned int*'. for the life of me, i haven't been able to figure out how to instantiate a memory buffer of the correct underlying type in python. whatever i try always fails when i set the struct member. TypeError: in method 'comedi_insn_struct_data_set', argument 2 of type 'lsampl_t *' [the underlying swig code seems to be (correctly) checking for an unsigned int pointer]. aside: i am currently running python v2.4.4 but could upgrade to a 2.5 version. thanks for any help. From mwilson at the-wire.com Sun Dec 14 11:52:27 2008 From: mwilson at the-wire.com (Mel) Date: Sun, 14 Dec 2008 11:52:27 -0500 Subject: 1 or 1/0 doesn't raise an exception References: <49446E39.6020807@tim.thechases.com> Message-ID: Daniel Fetchinson wrote: [ ... ] > Let me just point out that unsuspecting people (like me) might rely on > the whole expression to be evaluated and rely on exceptions being > raised if needed. There are a lot of threads on comp.lang.python that mention beginners' possible reactions to language features, so I'll mention this paper relating to teaching programming: . ? The early draft which I've read, , references quite a lot of literature on what new programmers do, discusses a new test for programming aptitude. ? ? ? ? Mel. From the.brown.dragon.blog at gmail.com Thu Dec 11 10:24:00 2008 From: the.brown.dragon.blog at gmail.com (the.brown.dragon.blog at gmail.com) Date: Thu, 11 Dec 2008 07:24:00 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <91bf5d87-0154-472b-9350-e3290ab867e1@k1g2000prb.googlegroups.com> Message-ID: <43743da2-7ad2-4ec9-86d1-b2e548d11cf1@k24g2000pri.googlegroups.com> On Dec 11, 7:50?pm, the.brown.dragon.b... at gmail.com wrote: > On Dec 11, 4:53?pm, "William James" wrote: > > > > > William James wrote: > > > John W Kennedy wrote: > > > > > Xah Lee wrote: > > > > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or > > > > > Java, you'll have 50 or hundreds lines. > > > > > Java: > > > > > static float[] normal(final float[] x) { > > > > ? ?float sum = 0.0f; > > > > ? ?for (int i = 0; i < x.length; ++i) sum += x[i] * x[i]; > > > > ? ?final float divisor = (float) Math.sqrt(sum); > > > > ? ?float[] a = new float[x.length]; > > > > ? ?for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor; > > > > ? ?return a; > > > > } > > > > "We don't need no stinkin' loops!" > > > > SpiderMonkey Javascript: > > > > function normal( ary ) > > > { div=Math.sqrt(ary.map(function(x) x*x).reduce(function(a,b) a+b)) > > > ? return ary.map(function(x) x/div) > > > } > > > The variable "div" shouldn't be global. > > > function normal( ary ) > > { var div = Math.sqrt( > > ? ? ary.map(function(x) x*x).reduce(function(a,b) a+b) ) > > ? return ary.map(function(x) x/div) > > > } > > Chicken Scheme: > > (require 'srfi-1) > (define (norm vec) > ? (map (cute / <> (sqrt (reduce + 0 (map (cute expt <> 2) vec)))) > vec)) > > Cute huh? ;-) Haskell looks the best though: norm v = map (/ (sqrt (sum (map (^2) v)))) v From quian.xu at stud.tu-ilmenau.de Mon Dec 22 07:54:56 2008 From: quian.xu at stud.tu-ilmenau.de (Qian Xu) Date: Mon, 22 Dec 2008 13:54:56 +0100 Subject: pg_result_status Message-ID: Hi All, I am using the pg module (http://www.pygresql.org/pg.html) for database testing. I have got a problem now: I want to check the result status of postgresql database, which can be done in php by using pg_result_status (http://www.phpbuilder.com/manual/en/function.pg-result-status.php) How can I do the same thing in python (2.5)? Thanks in advance -- Qian Xu From mccredie at gmail.com Wed Dec 3 20:15:21 2008 From: mccredie at gmail.com (Matimus) Date: Wed, 3 Dec 2008 17:15:21 -0800 (PST) Subject: "as" keyword woes References: Message-ID: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> > What I want to understand is why this parser change was necessary in > order to enable new 2.6/3.0 features. Was this change potentially > avoidable? Does it really matter? The change occurred and it isn't going to go back. What you should be asking yourself is whether the affect it had on your code could have been avoided. What could you have done to prevent your current situation? > Couldn't we have continued along just fine using a smarter parser > without elevating "as" to reserved status (and thus potentially breaking > a 10+ years of existing code)? Nothing broke your code. It works just fine under the version it was developed for. Who forced you to upgrade to python2.6? 'as' was already coming close to being a keyword with its use in import statements. It be came a full fledged keyword to support context managers: with open('filename.x', 'w') as fout: # do stuff > (Unfortunately, our project may now have to maintain a branch at 2.5.x > in order to preserve compatibility with existing third-party scripts & > infrastructure which routinely rely upon "as" as an object method. > Sigh.) Not necessarily. You can do something like this: import sys import warnings class MyClass(object): def new_as(self): # call this something appropriate, it is your new 'as' method pass # do what 'as' does if sys.version[:3] <= '2.5': def _old_as(self): warnings.warn( DeprecationWarning( 'This method is deprecated, use `new_as` instead')) return self.new_as() exec 'as = _old_as' You could even write a metaclass that does this (a little more elegantly). Your users will get a nice warning telling them not to use the 'as' method anymore. It will work in both code bases, and you can schedule to remove it at some later version after customers have had the opportunity to remove 'as' from their code. Matt From Python.LeoJay at gmail.com Sat Dec 13 10:28:05 2008 From: Python.LeoJay at gmail.com (Leo jay) Date: Sat, 13 Dec 2008 07:28:05 -0800 (PST) Subject: Why %e not in time.strftime directives? Message-ID: <38f9c4ba-d96d-47e1-b718-562bdc6718e9@t26g2000prh.googlegroups.com> Any special reasons? Thanks. From phd at phd.pp.ru Mon Dec 8 12:07:59 2008 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 8 Dec 2008 20:07:59 +0300 Subject: SQLObject 0.9.9 Message-ID: <20081208170759.GG7441@phd.pp.ru> Hello! I'm pleased to announce version 0.9.10, a minor bugfix release of 0.9 branch of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.9.9 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.9.8 ---------------- * Backported from the trunk: under MySQL use the connection's dbEncoding instead of ascii, when converting a unicode value from python to database for a StringCol. * Fixed createSQL constrains generation under MySQL when the table's name includes the database's name (contains a dot). For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From steve at REMOVE-THIS-cybersource.com.au Sun Dec 7 07:17:02 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 12:17:02 GMT Subject: var or inout parm? References: Message-ID: <014bb66f$0$20670$c3e8da3@news.astraweb.com> On Sun, 07 Dec 2008 08:54:46 +0000, mh wrote: > How can I make a "var" parm, where the called function can modify the > value of the parameter in the caller? By using another language. > def f(x): > x = x + 1 > > n = 1 > f(n) > # n should now be 2 Python doesn't work like that. You should read this: http://effbot.org/zone/python-objects.htm Some work arounds, in order from worst-to-best: (1) Use a hard-coded global name: x = 1 def f(): global x x = x + 1 f() assert x == 2 (2) Wrap the value you want to change in a list, then modify the list in place. n = [1] def f(alist): alist[0] = alist[0] + 1 f(n) assert n[0] == 2 (4) Just use an ordinary function. Functions can return multiple values. n = 1 def f(x): return (x+1, 99) n, y = f(n) assert y == 99 assert n == 2 (5) Find another way to solve your problem. Why do you think you need var parameters? What problem are you hoping to solve by using them? As a former Pascal programmer, I missed var parameters at first, but now I don't. -- Steven From python.leojay at gmail.com Thu Dec 11 03:30:01 2008 From: python.leojay at gmail.com (Leo Jay) Date: Thu, 11 Dec 2008 16:30:01 +0800 Subject: Why optimization mode is slower than normal mode? Message-ID: <4e307e0f0812110030m6d82b063oa98cdc14cdafe6a8@mail.gmail.com> Hi all, I'm using python 2.6 in a windows xp box, when I try pystone, I get: C:\Python26\Lib\test>python pystone.py 500000 Pystone(1.1) time for 500000 passes = 5.93632 This machine benchmarks at 84227.3 pystones/second C:\Python26\Lib\test>python -OO pystone.py 500000 Pystone(1.1) time for 500000 passes = 6.00515 This machine benchmarks at 83261.8 pystones/second I tried many times, and get the same result. Why optimization mode is slower than normal mode? -- Best Regards, Leo Jay From aioe.org at technicalbloke.com Mon Dec 8 13:42:00 2008 From: aioe.org at technicalbloke.com (r0g) Date: Mon, 08 Dec 2008 13:42:00 -0500 Subject: Text parsing via regex References: Message-ID: Robocop wrote: > I'm having a little text parsing problem that i think would be really > quick to troubleshoot for someone more versed in python and Regexes. > I need to write a simple script that parses some arbitrarily long > string every 50 characters, and does not parse text in the middle of > words (but ultimately every parsed string should be 50 characters, so > adding in white spaces is necessary). So i immediately came up with > something along the lines of: > > string = "a bunch of nonsense that could be really long, or really > short depending on the situation" > r = re.compile(r".{50}") > m = r.match(string) > > then i started to realize that i didn't know how to do exactly what i > wanted. At this point i wanted to find a way to simply use something > like: > > parsed_1, parsed_2,...parsed_n = m.groups() > > However i'm having several problems. I know that playskool regular > expression i wrote above will only parse every 50 characters, and will > blindly cut words in half if the parsed string doesn't end with a > whitespace. I'm relatively new to regexes and i don't know how to > have it take that into account, or even what type of logic i would > need to fill in the extra whitespaces to make the string the proper > length when avoiding cutting words up. So that's problem #1. Problem > #2 is that because the string is of arbitrary length, i never know how > many parsed strings i'll have, and thus do not immediately know how > many variables need to be created to accompany them. It's easy enough > with each pass of the function to find how many i will have by doing: > mag = len(string) > upper_lim = mag/50 + 1 > But i'm not sure how to declare and set them to my parsed strings. > Now problem #1 isn't as pressing, i can technically get away with > cutting up the words, i'd just prefer not to. The most pressing > problem right now is #2. Any help, or suggestions would be great, > anything to get me thinking differently is helpful. Hi Robocop, What do you mean by "parses some arbitrarily long string every 50 characters"? What does your source data look like? Can you give us an example of of a) it and b) what a match would look like. I think you will get good mileage out of using '\b' to match word boundaries and that you may be better off rexing your string into a list and then padding it with whitespace after the fact but I can't say for sure. Please clarify. From __peter__ at web.de Mon Dec 1 06:08:01 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 01 Dec 2008 12:08:01 +0100 Subject: Is there any library that can convert RGB colors to ANSI colors? References: <52e45dc6-d4f5-4275-a424-dea91d1ccf26@a37g2000pre.googlegroups.com> Message-ID: ZelluX wrote: > Convert RGB colors to the closest ANSI colors. For example, given RGB > color FF0000, it should print [31m. from functools import partial def to_rgb(color): return (color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF target_colors = { 0x000000: "\33[30m", 0xFF0000: "\33[31m", # ... 0xFFFFFF: "\33[37m",} def euclidian(c1, c2): r, g, b = to_rgb(c1) s, h, c = to_rgb(c2) r -= s g -= h b -= c return r*r+g*g+b*b def closest_color(color, target_colors=target_colors, dist=euclidian): return min(target_colors, key=partial(dist, color)) if __name__ == "__main__": black = target_colors[0] for color in 0xff0000, 0x00ff00, 0x808080, 0x008000: bestmatch = closest_color(color) code = target_colors[bestmatch] print "#%06x --> %sSAMPLE%s" % (color, code, black) If the results are not good enough for your application you can convert to another colorspace before calculating the distance. Peter From cousinstanley at gmail.com Thu Dec 4 09:55:10 2008 From: cousinstanley at gmail.com (Cousin Stanley) Date: Thu, 4 Dec 2008 15:55:10 +0100 (CET) Subject: Python advocacy ... HELP! References: <5f8c1a52-545e-402e-863a-acdf23d04c78@h20g2000yqn.googlegroups.com> Message-ID: > .... > I have looked at several interesting academic papers, on doing just > this approach. I have also looked through the > python web page to get examples of industry players using python in a > non-trivial way. Yes, I know, Google, Microsoft, Sun, CIA website > running on Plone, NOAA, NASA. If anyone has any recent articles, > or if anyone on the list is at a fortune 500 company, how do I > refute the notion that Python is a "marginal" language > because according to TOBIE it only less than a 6% market share. Michael .... If you haven't seen it, The Python Success Stories page might provide a quick overview for those that are currently unaware of the rather diverse nature of Python usage among a wide group of well known users .... http://pythonology.org/success -- Stanley C. Kitching Human Being Phoenix, Arizona From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 06:42:23 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Dec 2008 11:42:23 GMT Subject: Don't you just love writing this sort of thing :) References: <0148b086$0$20670$c3e8da3@news.astraweb.com> Message-ID: <01490b5f$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 23:28:48 +1300, Lawrence D'Oliveiro wrote: > In message <0148b086$0$20670$c3e8da3 at news.astraweb.com>, Steven D'Aprano > wrote: > >> Since the context has been deleted, it's hard to tell whether the code >> as written by Lawrence ... > > If you want to reply to my message, reply to my message, don't reply to > my reply to someone else's reply to my message. I did reply to your message. It was your message that was missing all the context necessary to tell what you were rabbiting on about. -- Steven From nadiasvertex at gmail.com Mon Dec 8 11:24:58 2008 From: nadiasvertex at gmail.com (Christopher) Date: Mon, 8 Dec 2008 08:24:58 -0800 (PST) Subject: Guido's new method definition idea References: Message-ID: > > I'd like this new way of defining methods, what do you guys think? > Anyone ready for writing a PEP? I don't really see any advantage. IMHO, it is not clearer, it is not more concise, it makes the definition of class shared variables look really out of place. It also makes the new programmer wonder where the function attaches if you *don't* specify self. I also give it a -1. From rt8396 at gmail.com Wed Dec 24 18:39:22 2008 From: rt8396 at gmail.com (r) Date: Wed, 24 Dec 2008 15:39:22 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <0161d999$0$20621$c3e8da3@news.astraweb.com> Message-ID: On Dec 24, 1:19?am, Steven D'Aprano wrote: > On Tue, 23 Dec 2008 08:06:35 -0800, the anonymous troll known only as "r" > replied to Thorsten Kampe and said: > > > Thats "Thurstan", thank you very much! :) > > I think Thorsten knows how to spell his own name. > > -- > Steven OK Steven, you caught me fair and square. This is my first mistake and i will admit it. Sorry "Thorsten" From rileyrgdev at gmail.com Mon Dec 1 09:09:05 2008 From: rileyrgdev at gmail.com (Richard Riley) Date: Mon, 01 Dec 2008 15:09:05 +0100 Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <3a30f601-7128-4e5f-a97e-9f899404912c@o40g2000prn.googlegroups.com> <4f31c483-8382-480e-8417-b7eef1b1792d@z1g2000yqn.googlegroups.com> <8c856b01-7f0c-4d5b-a1d2-cfe7dc74389f@w3g2000yqc.googlegroups.com> <1680020c-521c-4498-8e74-92e99c03da6b@w35g2000yqm.googlegroups.com> <0d9d2404-cb3f-4390-b97c-79251db8ac95@k8g2000yqn.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> Message-ID: cptnwillard at gmail.com writes: > Don't feed the troll. > Yet you did and made the previous post visible to me. If you don't want people to feed the troll, do not do it yourself. From aspersieman at gmail.com Wed Dec 3 05:53:27 2008 From: aspersieman at gmail.com (Aspersieman) Date: Wed, 03 Dec 2008 12:53:27 +0200 Subject: How to send body and attachements in an email message? In-Reply-To: <140952.77709.qm@web7901.mail.in.yahoo.com> References: <140952.77709.qm@web7901.mail.in.yahoo.com> Message-ID: On Wed, 03 Dec 2008 12:40:30 +0200, srinivasan srinivas wrote: > HI, > I would like to send an email message with body-content 'test' and?an > attachment. > The snippet i used is: > outer = email.mime.multipart.MIMEMultipart() > msg1 = email.mime.text.MIMEText(, _subtype = 'text') > msg1.add_header('Content-Disposition', 'attachment') > outer.attach(msg1) > > body = email.mime.text.MIMEText(, _subtype = 'text') > outer.attach(body) > > smtp_client = smtplib.SMTP() > smtp_client.connect() > smtp_client.sendmail(, , outer.as_string()) > smtp_client.close() > > If i do like above, i am receiving the body also as an attachment. How > to set body to Multipart email message? > > Thanks, > Srini > > > Add more friends to your messenger and enjoy! Go to > http://messenger.yahoo.com/invite/ > -- > http://mail.python.org/mailman/listinfo/python-list Hi there I have used this method for a while. Works pretty good. (Apologies if the formatting is a bit wonky - gmail reformats my stuff) import mimetypes import poplib import email import smtplib import os from email import * from email.mime import * def SendMail(self, send_from, send_to, subject, text, files=[], server="localhost", username = None, password = None): # {{{ """ Sends an email. With optional attachment files. """ assert type(send_to)==list assert type(files)==list msg = MIMEMultipart.MIMEMultipart() msg['From'] = send_from msg['To'] = Utils.COMMASPACE.join(send_to) msg['Date'] = Utils.formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText.MIMEText(text)) for f in files: part = MIMEBase.MIMEBase("application", "octet-stream") part.set_payload(open(f,"rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server, 25) smtp.sock.settimeout(120) try: if username and password: smtp.login(username, password) smtp.sendmail(send_from, send_to, msg.as_string()) else: smtp.sendmail(send_from, send_to, msg.as_string()) except Exception, err: print "Error sending to " + str(send_to) + " ERROR : " + str(err) if self.logger: self.logger.error("Email error - error sending message to : " + str(send_to) + " Error : " + str(err)) smtp.close() # }}} HTH Nicol -- Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo From jstroud at mbi.ucla.edu Sun Dec 14 19:25:02 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 14 Dec 2008 16:25:02 -0800 Subject: Looking for the best way to translate an idiom In-Reply-To: References: Message-ID: James Stroud wrote: > py> class mytuple(tuple): > def magic(self, astr): > names = astr.split() > for name, val in zip(names, self): > globals()[name] = val > ... > py> t = mytuple((1,2,3)) > py> t.magic('a b') > py> a > 1 > py> b > 2 > > James In case its not obvious: def f(): return mytuple((1,2,3)) f().magic('a b') You can parameterize lobbing off values, or use more magic: py> class mytuple(tuple): ... def magic(self, astr): ... names = astr.split() ... for name, val in zip(names, self): ... globals()[name] = val ... def __add__(self, other): ... if isinstance(other, tuple): ... return mytuple(tuple.__add__(self, other)) ... else: ... return mytuple(self[other:]) ... py> t = mytuple((1,2,3)) py> t + 1 (2, 3) py> def f(): return mytuple((1,2,3)) ... py> (f() + 1).magic('a b') py> a 2 py> b 3 It's not as bad as a lot of the cynics are about to tell you it is. If it has any badness at all, it's because of the need (according to what I infer from your specification) to use the global namespace. If you want to modify a "more local" namespace, you can use some stack frame inspection to do some real magic: py> import inspect py> class mytuple(tuple): def magic(self, astr): names = astr.split() for name, val in zip(names, self): inspect.stack()[1][0].f_locals[name] = val def __add__(self, other): if isinstance(other, tuple): return mytuple(tuple.__add__(self, other)) else: return mytuple(self[other:]) ... py> def f(): return mytuple((6,7,8)) ... py> (f() + 1).magic('a b') py> a 7 py> b 8 James From exarkun at divmod.com Tue Dec 16 13:17:53 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 16 Dec 2008 13:17:53 -0500 Subject: AIM client code for Python? In-Reply-To: <732D7AE5-1429-4482-82FA-78328D6C3CF5@strout.net> Message-ID: <20081216181753.20272.1787674525.divmod.quotient.21873@ohm> On Tue, 16 Dec 2008 10:54:38 -0700, Joe Strout wrote: >I'd like to write an AIM bot in Python. I found and tried >, but it doesn't work for me: > >Connecting... >Traceback (most recent call last): > File "aimbot-1.py", line 17, in > bot.go() > File "/Users/jstrout/Documents/Python-Dev/AIMbot/toc.py", line 62, in go > self.process_loop() > File "/Users/jstrout/Documents/Python-Dev/AIMbot/toc.py", line 156, in >process_loop > event = self.recv_event() > File "/Users/jstrout/Documents/Python-Dev/AIMbot/toc.py", line 230, in >recv_event > dtemp = self._socket.recv(buflen - len(data)) >socket.error: (54, 'Connection reset by peer') > > >I wrote to the author a week ago, but never got a reply. It could be as >simple as changing the server addresses in toc.py, currently: > >TOC_SERV_AUTH = ("login.oscar.aol.com", 29999 ) >TOC_SERV = ( "toc.oscar.aol.com", 9898 ) > >...but I don't understand AIM well enough to know the correct values (and >was rather hoping that I wouldn't have to). > >Does anyone know how to get Py-TOC to work, or have another Python TOC >implementation to suggest? > You need an OSCAR-based AIM library. AOL discontinued TOC support several years ago. No TOC-based client can work on the AIM network. Twisted includes a (somewhat crufty) OSCAR implementation. There are probably also other Python OSCAR implementations. Jean-Paul From markguildwars1 at hotmail.com Tue Dec 16 21:54:54 2008 From: markguildwars1 at hotmail.com (Mark Jordaan) Date: Wed, 17 Dec 2008 04:54:54 +0200 Subject: unsubscribe In-Reply-To: References: Message-ID: > From: p.f.moore at gmail.com> Subject: Re: Does Python3 offer a FrozenDict?> Date: Tue, 16 Dec 2008 09:56:57 -0800> To: python-list at python.org> > On 16 Dec, 17:28, bearophileH... at lycos.com wrote:> > Johannes Bauer:> >> > > is there anything like a frozen dict in Python3, so I could do a> > > foo = { FrozenDict({"a" : "b"}): 3 }> >> > You can adapt this code to Python3 (and post a new recipe? It may be> > positive to create a new section of the Cookbook for Py3 only):http://code.activestate.com/recipes/414283/> > There's actually only tiny changes needed (I believe)> - Change exception syntax: raise AttributeError("A frozendict cannot> be modified.")> - (bugfix for the original version): add **kw arg to __new__ (passed> to dict.__init__)> > Simple testing looks OK. And the resulting code is OK for both 2.x and> 3.0.> > Moral - don't assume that all code needs to be rewritten for Python> 3.0 :-)> > Paul.> > PS I imagine that 2to3 would have fixed this up fine, but it was so> easy to do by hand that I didn't bother :-)> --> http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Get the next generation of Free Windows Live Services http://get.live.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Dec 12 11:50:38 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Dec 2008 11:50:38 -0500 Subject: Removing None objects from a sequence In-Reply-To: <87ej0dz894.fsf@daycos.com> References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> Message-ID: Kirk Strauser wrote: > At 2008-12-12T15:51:15Z, Marco Mariani writes: > >> Filip Gruszczy?ski wrote: >> >>> I am not doing it, because I need it. I can as well use "if not elem >>> is None", > >> I suggest "if elem is not None", which is not quite the same. > > So what's the difference exactly? "foo is not None" is actually surprising > to me, since "not None" is True. "0 is True" is False, but "0 is not None" > is True. Why is that? "is not" is an operator, so the parse is foo (is not) None not foo is (not None) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From research at johnohagan.com Sat Dec 20 09:47:29 2008 From: research at johnohagan.com (John O'Hagan) Date: Sat, 20 Dec 2008 14:47:29 +0000 Subject: Namespaces, multiple assignments, and exec() In-Reply-To: References: Message-ID: <200812201447.29230.research@johnohagan.com> On Sat, 20 Dec 2008, Arnaud Delobelle wrote: > John O'Hagan writes: > > I have a lot of repetitive assignments to make, within a generator, > > that use a function outside the generator: > > > > var1 = func("var1", args) > > var2 = func("var2", args) > > var3 = func("var3", args) > > etc... > > > > In each case the args are identical, but the first argument is a > > string of the name being assigned. It works fine but I'd like to > > reduce the clutter by doing the assignments in a loop. I've tried > > using exec(): > > > > for name in name_string_list: > > exec(name + ' = func(\"' + name + '\", args)') > > > > but in the local namespace it doesn't understand func(), and if I give > > it globals() it doesn't understand the args, which come from within > > the generator. > > > > What's a good way to do this kind of thing? > > Your problem is describe in too vague a way to get good answers IMHO. > Are var1, var2, ... globals or local to the generator? Can you give > some sample code to show what doesn't work? The vars are all local to the generator. This is what doesn't work (I have omitted some functions called by the first function for brevity): def iterizer(options_dict): """Convert controllable option values to generators""" range_ctrls = ['length', 'variety', 'z_depth', 'z_variety'] numerical_ctrls = ['bank', 'bell', 'channel', 'click', 'chord', 'descend', 'divisor', 'forte', 'inv', 'large_scaly', 'metarandomt', 'metat', 'mirrors', 'part', 'pause', 'prime', 'program', 'rand', 'randomt', 'rotate', 'shuffle_phrase', 'split', 'small_scaly', 'tempo', 'translate', 'transpose', 'updown' , 'voice', 'volume'] list_ctrls = ['all_check', 'degrees', 'exclude', 'finelist', 'nondegrees', 'include', 'only', 'pattern', 'rhythm', 'z_test'] generators = {} for item in options_dict.iteritems(): opt, value = item[0], item[1] if value is not None: if value[0] == "C": ctrl_opts = optparse(value[1:]) iterator = sequence_engine(ctrl_opts) if opt in numerical_ctrls: iterator = numerical_iter(iterator) elif opt in range_ctrls: iterator = range_iter(iterator) else: iterator = dummy_ctrl(value) if opt not in list_ctrls: iterator = numerical_iter(iterator) generators[opt] = iterator return generators def inext(option, generators, options_dict): """Cycling version of next()""" if generators.has_key(option): try : return generators[option].next() except StopIteration: minidict = {option:options_dict[option]} minigens = iterizer(minidict) generators.update(minigens) return generators[option].next() def sequence_engine(options): """Produce Sequence instances""" engine_opts = ['length', 'variety', 'z_depth', 'z_variety', 'descend', 'divisor', 'forte', 'inv', 'large_scaly', 'mirrors', 'part', 'prime', 'rand', 'rotate', 'shuffle_phrase', 'split', 'small_scaly', 'translate', 'transpose', 'updown' , 'voice', 'all_check', 'degrees', 'exclude', 'finelist', 'nondegrees','include', 'only', 'pattern', 'z_test', 'cardinal'] engine_dict = {} for item in engine_opts: engine_dict[item] = options.__dict__[item] generators = iterizer(engine_dict) for name in engine_opts: exec(name + ' = inext(\"' + name + '\" ,generators, engine_dict)') ....etc.. The last loop fails to assign any names for the reasons described in the OP. Regards, John From ylj798 at gmail.com Tue Dec 2 14:08:48 2008 From: ylj798 at gmail.com (ylj798 at gmail.com) Date: Tue, 2 Dec 2008 11:08:48 -0800 (PST) Subject: help me~!about base64 References: <0ff1ba7b-8a17-4647-99fc-9c8e32f83de7@g1g2000pra.googlegroups.com> Message-ID: On 12?3?, ??1?50?, "Jerry Hill" wrote: > 2008/12/2 : > > > it's run ,Eric gave me error,the error is "'module'objecthasno > >attribute'decodestring'", > > Do you have your own base64.py (or base64.pyc) that's shadowing the > standardmodulebase64? Try this: > > >>> import base64 > >>> print base64.__file__ > > C:\Python25\lib\base64.py > > > > What does that say when you do it? > > -- > Jerry look,when i work it,tell me blow >>>print base64.__file__ /usr/lib/python2.5/base64.pyc From warren at delsci.com Thu Dec 4 15:11:15 2008 From: warren at delsci.com (Warren DeLano) Date: Thu, 4 Dec 2008 12:11:15 -0800 Subject: To Troll or Not To Troll Message-ID: <896B75251BA19745A529B1B867893FA50679D3@planet.delsci.local> > I still would have to call your management of the problem considerably > into question - your expertise at writing mathematical software may > not be in question, but your skills and producing and managing a > software product are. You have nobody at your organization, which > sells a product that relies on Python, who follows python-dev? Or who > even reads the changelogs for new python versions? You should have > known about the "as" keyword change *over a year ago*, even if the > import bug was masking the deprecation warning. Everything else aside, > I can't get past that issue with your complaints. I *have* gone back > now and read all the posts in all the threads and I still have not > seen a single post from you even hinting that you might have any > responsibility in the matter. Well then, let me set the record straight on that one point: I admit that it was entirely my mistake (and mine alone) to implicitly assume, by adopting such a logging & persistence architecture (dating back to 1.5.2, mind you!), that new keywords would not be introduced into the Python language so as to potentially break all existing Python code. Silly me! How unreasonable. From steve at REMOVE-THIS-cybersource.com.au Wed Dec 24 02:19:01 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 24 Dec 2008 07:19:01 GMT Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: <0161d999$0$20621$c3e8da3@news.astraweb.com> On Tue, 23 Dec 2008 08:06:35 -0800, the anonymous troll known only as "r" replied to Thorsten Kampe and said: > Thats "Thurstan", thank you very much! :) I think Thorsten knows how to spell his own name. -- Steven From steve at REMOVE-THIS-cybersource.com.au Mon Dec 29 21:02:16 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Dec 2008 02:02:16 GMT Subject: get method References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> <4819de67-72dc-415c-b4c8-2353581c2bc7@r2g2000vbp.googlegroups.com> Message-ID: <0169782e$0$6988$c3e8da3@news.astraweb.com> On Mon, 29 Dec 2008 17:38:36 -0800, Ross wrote: > On Dec 29, 8:07?pm, Scott David Daniels wrote: >> Ross wrote: >> > ... Use get to write histogram more concisely. You should be able to >> > eliminate the if statement. >> >> > def histogram(s): >> > ? ?d = dict() >> > ? ?for c in s: >> > ? ? ? ? ? ?d[c]= d.get(c,0) >> > ? ?return d >> >> > This code returns a dictionary of all the letters to any string s I >> > give it but each corresponding value is incorrectly the default of 0. >> > What am I doing wrong? >> >> How is this code supposed to count? >> >> --Scott David Daniels >> Scott.Dani... at Acm.Org > > I realize the code isn't counting, but how am I to do this without using > an if statement as the problem instructs? You don't increment a value using if. This would be silly: # increment x if x == 0: x = 1 elif x == 1: x = 2 elif x == 2: x = 3 # can I stop yet? else: x = "I can't count that high!" You increment a value using + 1: x = x + 1 or x += 1 In the original code, the program did this: def histogram(s): d = dict() for c in s: if c not in d: d[c] = 1 else: d[c] += 1 * look for c in the dict * if it isn't there, set d[c] to 1 * but if it is there, increment d[c] by 1 Your attempt was quite close: def histogram(s): d = dict() for c in s: d[c]= d.get(c,0) return d which is pretty much the same as: * set d[c] to whatever d[c] already is, or 0 if it isn't already there. So what you need is: * set d[c] to whatever d[c] already is plus one, or 0 plus one if it isn't already there. It's a two character change to one line. Let us know if you still can't see it. -- Steven From ajaksu at gmail.com Mon Dec 29 17:18:25 2008 From: ajaksu at gmail.com (ajaksu) Date: Mon, 29 Dec 2008 14:18:25 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <59dfc7f8-cfd4-4e22-ad83-52cd8ea57c1f@e18g2000yqo.googlegroups.com> Message-ID: <523f88c6-d3ff-4b9f-b585-a435e112b05e@k8g2000yqn.googlegroups.com> On Dec 29, 7:37?pm, Luis M. Gonz?lez wrote: > I still can't get used to add the parenthesis to "print", and this is > the only thing I don't like, but I'm sure there's a good reason for > this change... I should know better than to post such an awful hack: __past__.py: from sys import excepthook as sys_excepthook from sys import modules --- def printhook(exctype, value, traceback): skip = True if isinstance(value, SyntaxError): if 'print ' in value.text: printable = value.text.replace('print ', '')[:-1] skip = False toprint = 'print(' + printable +')' print('Trying to convert your mess into', toprint) try: exec(toprint) except NameError as ne: name = str(ne).replace("name '", '').replace("' is not defined", '') try: var = str(getattr(modules['__main__'], name)) exec('print(' + printable.replace(name, var) + ')') except AttributeError as ae: sys_excepthook(NameError, ne, traceback) except SyntaxError as se: print('NameError workaround replaced something bad') skip = True except NameError as ne2: print('Too many names to map to objects :P') skip = True except: print('Sorry, something went wrong and I am too lazy to find out what') skip = True except: raise skip = True if skip: sys_excepthook(exctype, value, traceback) --- Then, as I'd check some stuff in parallel on 2.5 and 3.0, I do this on the 3.0 prompt: --- import sys exchook = sys.excepthook from __past__ import printhook sys.excepthook = printhook --- As soon as I wrote that mess^H^H^H^H helper, remembering to use print () became easier (I think the trauma helped) and I haven't imported much from __past__ since. Should I hit 'send'? Daniel From benjamin.kaplan at case.edu Sat Dec 13 22:25:07 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sat, 13 Dec 2008 22:25:07 -0500 Subject: 1 or 1/0 doesn't raise an exception In-Reply-To: References: Message-ID: Not that I'm against promoting Python, but most languages have support for short circuit evaluation. That's why you usually use && and || in C, C++, C# and Java- & and | will always evaluate both sides. Short circuit evaluation is what allows you to write things like "if foo is not None and foo.isTrue()". On Sat, Dec 13, 2008 at 9:57 PM, r wrote: > These are just the kind of things that make Python so beautiful ;) > Thanks Guido! > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From callen314 at gmail.com Tue Dec 16 15:37:26 2008 From: callen314 at gmail.com (Craig Allen) Date: Tue, 16 Dec 2008 12:37:26 -0800 (PST) Subject: How to modify a program while it's running? References: Message-ID: <6e2cfc09-5aae-480c-b32d-d5a942044ba3@i24g2000prf.googlegroups.com> On Dec 16, 10:25 am, Joe Strout wrote: > Here's my situation: I'm making an AIM bot, but the AIM server will > get annoyed if you log in too frequently (and then lock you out for a > while). So my usual build-a-little, test-a-little methodology doesn't > work too well. > > So I'd like to restructure my app so that it can stay running and stay > logged in, yet I can still update and reload at least most of the > code. But I'm not sure what's the best way to do this. Should I move > the reloadable code into its own module, and then when I give my bot a > "reload" command, have it call reload on that module? Will that work, > and is there a better way? > > Thanks, > - Joe yes you want reload. Design the high level part that knows how to log in to be able to reload the stuff that changes. My guess is that is the best way, though I wouldn't be surprised if there are other solutions. From jarausch at skynet.be Mon Dec 1 16:01:00 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Mon, 01 Dec 2008 22:01:00 +0100 Subject: Is it safe to modify the dict returned by vars() or locals() Message-ID: <4934508b$0$2861$ba620e4c@news.skynet.be> Hi, I am looking for an elegant way to solve the following problem: Within a function def Foo(**parms) I have a list of names, say VList=['A','B','C1'] and I like to generate abbreviation _A identical to parms['A'] for that I could write def Foo(**parms) : for N in VList : if N in parms : vars()[N]= parms[N] else : vars()[N]= None Does this work, is it typical Python? Many thanks for a hint, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From invalid at invalid Mon Dec 22 13:51:46 2008 From: invalid at invalid (Grant Edwards) Date: Mon, 22 Dec 2008 12:51:46 -0600 Subject: I always wonder ... References: Message-ID: On 2008-12-22, skip at pobox.com wrote: > ... shouldn't people who spend all their time trolling be > doing something else: studying, working, writing patches which > solve the problems they perceive to exist in the troll > subject? I think you misunderstand the point of trolling. The author of a troll post doesn't actually care about the "problems" (and may not even genuinely perceive them as problems). > Is there some online troll game running where the players earn > points for generating responses to their posts? Yup. It's called Usenet. I'm sure we all have our, um, "non-productive" hobbies and forms of entertainment. A well done troll [which, I admit, is somewhat rare] is a bit of an art, and can be rather entertaining to watch. Of course there's the other, much larger, category of posters (sometimes confused with trollers): the lazy, ignorant whingers. Apart from being much more common, they're also much less entertaining to everybody except the ranting flamer. As you can see, Usenet is a rather complex eco-system with a lot of niches... -- Grant Edwards grante Yow! What PROGRAM are they at watching? visi.com From stef.mientki at gmail.com Tue Dec 16 18:02:56 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 17 Dec 2008 00:02:56 +0100 Subject: Python is slow In-Reply-To: References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <355f1cfe-6abb-4d2c-8bf4-3aa62e713c1f@w34g2000yqm.googlegroups.com> Message-ID: <494833A0.7050905@gmail.com> r wrote: > On Dec 15, 7:15 am, Luis M. Gonz?lez wrote: > >> On Dec 15, 1:38 am, cm_gui wrote: >> >> >>> hahaha, do you know how much money they are spending on hardware to >>> make >>> youtube.com fast??? >>> >>>> By the way... I know of a very slow Python site called YouTube.com. In >>>> fact, it is so slow that nobody ever uses it. >>>> >> Buddy, just stop whining and go with c++ if it makes you happy. >> By the way, what's the blazingly fast application you need to write so >> desperately? >> What kind of performance problem have you find in python that makes >> you so unhappy? >> What are you going to do with all the extra speed provided by c++ (a >> Hello World! ?)... >> > > Still no reply from cm_gui, he must have googled "C hello world" :D > or cm_gui is slow, btw I thought r was a statistic package ;-) cheers, Stef > -- > http://mail.python.org/mailman/listinfo/python-list > From febaen at gmail.com Mon Dec 15 16:23:30 2008 From: febaen at gmail.com (feba) Date: Mon, 15 Dec 2008 13:23:30 -0800 (PST) Subject: Need help improving number guessing game References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> <01564c98$0$21844$c3e8da3@news.astraweb.com> <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> Message-ID: I added the ability to select your own range. It takes two new modules: def customrange(game, lowunsafe=True): game['defrang'] = False #Keeps setup from changing range to defaults while lowunsafe: #makes sure that the low number is positive picklow = int(input("PLEASE PICK THE LOW NUMBER: ")) if picklow < 0: print("LOW NUMBER MUST BE POSTIVE") else: lowunsafe = False pickhigh = int(input("PLEASE PICK THE HIGH NUMBER: ")) if pickhigh - picklow <= 2: #see setup(). print("HIGH MUST BE AT LEAST THREE GREATER THAN LOW") else: game['minr'], game['maxr'] = picklow, pickhigh print("RANGE IS [%s-%s]!" % (game['minr'], game['maxr'])) def wantcustom(game, unsure=True): #Allows user to decide their own range for guessing. while unsure: pickrange = input("WOULD YOU LIKE TO CREATE A CUSTOM RANGE? Y/ N: ") if pickrange.lower() == "n": game['minr'], game['maxr'] = 1, 99 #Default range unsure = False elif pickrange.lower() == "y": customrange(game) unsure = False else: print("INVALID INPUT") A slightly updated setup (it needed it anyway): def setup(game): #minr, maxr make minimum and maximum. Can be adjusted. #Make sure that maxr - minr is at least 3. #1 or less would be impossible. 2 would only have one guess for victory #The first would be unplayable, the second would play itself if game['maxr'] - game['minr'] <= 2: raise ValueError("INVALID RANGE!") game['gcount'] = 0 #Reset guess count game['target'] = random.randint(game['minr'], game['maxr']) and putting wantcustom(game) immediately before setup(game) in main(). From roy at panix.com Tue Dec 9 08:31:02 2008 From: roy at panix.com (Roy Smith) Date: Tue, 09 Dec 2008 08:31:02 -0500 Subject: Learning Python now coming from Perl References: Message-ID: Nick Craig-Wood wrote: > > On the other hand, leaving out the parens returns the function itself, > > which you can then call later. I've often used this to create data-driven > > logic. > > I didn't say it wasn't useful, just that if you came from Perl like I > did, it is an easy mistake to make ;-) Agreed. > OO lore says whenever you see a type field in an instance you've gone > wrong - types should be represented by what sort of object you've got, > not by a type field. OO lore lives in an ivory tower sometimes :-) I'm working with an existing system, where objects are marshaled on the wire as type codes followed by a type-specific number of bytes of data. Internally, it calls these AnyVals and the concept is pervasive in the architecture. I could work within the existing architecture, or I could try to fight it. Yes, I could get rid of the dispatch table and create 20 or 30 classes to represent all the possible types. I'd end up with several times as much code, most of it boilerplate. Instead of having a dispatch table of read/write functions, I'd have a dispatch table of classes, each of which has a read method and a write method. It doesn't buy anything, and I'd still have the type codes exposed because I need them to read and write values to the wire. From tjreedy at udel.edu Fri Dec 5 13:24:34 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 05 Dec 2008 13:24:34 -0500 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: References: Message-ID: Johannes Bauer wrote: > Hello group, > > I'm having trouble reading a utf-16 encoded file with Python3.0. This is > my (complete) code: what OS. This is often critical when you have a problem interacting with the OS. > #!/usr/bin/python3.0 > > class AddressBook(): > def __init__(self, filename): > f = open(filename, "r", encoding="utf16") > while True: > line = f.readline() > if line == "": break > print([line[x] for x in range(len(line))]) > f.close() > > a = AddressBook("2008_11_05_Handy_Backup.txt") > > This is the file (only 1 kB, if hosting doesn't work please tell me and > I'll see if I can put it someplace else): > > http://www.file-upload.net/download-1297291/2008_11_05_Handy_Backup.txt.gz.html > > What I get: The file reads file the first few lines. Then, in the last > line, I get lots of garbage (looking like uninitialized memory): > > ['E', 'n', 't', 'r', 'y', '0', '0', 'T', 'e', 'x', 't', ' ', '=', ' ', > '"', 'A', 'D', 'A', 'C', ' ', 'V', 'e', 'r', 'k', 'e', 'h', 'r', 's', > 'i', 'n', 'f', 'o', '"', '\u0d00', '\u0a00', '?', '?', '?', '?', '? > ', '\u3000', '\u3100', '?', '?', '?', '?', '\u2000', '?', '\u2000', > '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', > '\u0d00', '\u0a00', '?', '?', '?', '?', '?', '\u3000', '\u3100', ' > ?', '?', '?', '?', '\u2000', '?', '\u2000', '?', '?', '?', '?', > '\u3100', '?', '?', '?', '?', '?', '?', '?', '?', '\u0d00', > '\u0a00', '\u0d00', '\u0a00', '?', '?', '?', '?', '?', '?', '?', > '?', '?', '\u3000', '\u3000', '?', '?', '\u0d00', '\u0a00'] > > Where the line > > Entry00Text = "ADAC Verkehrsinfo"\r\n From \r\n I guess Windows. Correct? I suspect that '?' after \n (\u0a00) is indicates not 'question-mark' but 'uninterpretable as a utf16 character'. The traceback below confirms that. It should be an end-of-file marker and should not be passed to Python. I strongly suspect that whatever wrote the file screwed up the (OS-specific) end-of-file marker. I have seen this occasionally on Dos/Windows with ascii byte files, with the same symptom of reading random garbage pass the end of the file. Or perhaps end-of-file does not work right with utf16. > is actually the only thing the line contains, Python makes the rest up. No it does not. It echoes what the OS gives it with system calls, which is randon garbage to the end of the disk block. Try open with explicit 'rt' and 'rb' modes and see what happens. Text mode should be default, but then \r should be deleted. > The actual file is much longer and contains private numbers, so I > truncated them away. When I let python process the original file, it > dies with another error: > > Traceback (most recent call last): > File "./modify.py", line 12, in > a = AddressBook("2008_11_05_Handy_Backup.txt") > File "./modify.py", line 7, in __init__ > line = f.readline() > File "/usr/local/lib/python3.0/io.py", line 1807, in readline > while self._read_chunk(): > File "/usr/local/lib/python3.0/io.py", line 1556, in _read_chunk > self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) > File "/usr/local/lib/python3.0/io.py", line 1293, in decode > output = self.decoder.decode(input, final=final) > File "/usr/local/lib/python3.0/codecs.py", line 300, in decode > (result, consumed) = self._buffer_decode(data, self.errors, final) > File "/usr/local/lib/python3.0/encodings/utf_16.py", line 69, in > _buffer_decode > return self.decoder(input, self.errors, final) > UnicodeDecodeError: 'utf16' codec can't decode bytes in position 74-75: > illegal encoding > > With the place where it dies being exactly the place where it outputs > the weird garbage in the shortened file. I guess it runs over some page > boundary here or something? Malformed EOF more likely. Terry Jan Reedy From mrkafk at gmail.com Mon Dec 29 10:14:14 2008 From: mrkafk at gmail.com (mk) Date: Mon, 29 Dec 2008 16:14:14 +0100 Subject: multiprocessing vs thread performance In-Reply-To: References: Message-ID: janislaw wrote: > Ah, so there are 100 processes at time. 200secs still don't sound > strange. I ran the PEP 371 code on my system (Linux) on Python 2.6.1: Linux SLES (9.156.44.174) [15:18] root ~/tmp/src # ./run_benchmarks.py empty_func.py Importing empty_func Starting tests ... non_threaded (1 iters) 0.000005 seconds threaded (1 threads) 0.000235 seconds processes (1 procs) 0.002607 seconds non_threaded (2 iters) 0.000006 seconds threaded (2 threads) 0.000461 seconds processes (2 procs) 0.004514 seconds non_threaded (4 iters) 0.000008 seconds threaded (4 threads) 0.000897 seconds processes (4 procs) 0.008557 seconds non_threaded (8 iters) 0.000010 seconds threaded (8 threads) 0.001821 seconds processes (8 procs) 0.016950 seconds This is very different from PEP 371. It appears that the PEP 371 code was written on Mac OS X. The conclusion I get from comparing above costs sis that OS X must have very low cost of creating the process, at least when compared to Linux, not that multiprocessing is a viable alternative to thread / threading module. :-( From kyosohma at gmail.com Mon Dec 1 09:21:37 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 1 Dec 2008 06:21:37 -0800 (PST) Subject: How to distribute a Python app together with its dependencies? References: Message-ID: <2343b577-215b-4b4c-8ea0-00dd49369df1@x38g2000yqj.googlegroups.com> On Nov 30, 6:22?am, Alessio Pace wrote: > Hi, > > I have to distribute a Python application which relies on an external > library, and I'm not very fluent in this kind of stuff with Python (I > come from the Java world where I would have used the Maven build tool > to create an "assembly with dependencies" of all it is needed to run > the app), so I was wondering if someone here could give me some > suggestions :-) > > The external library is generally not present on the machines where I > have to distribute my app, and the set of machines on which I have to > distribute this application is not known a priori (it is just known > they are Unix systems). In fact by means of SSH I will have to copy > (and install) the app+library and make it runnable onto the specified > destination(s). > > My question is: how would you do that? ?At the moment my current > solution is to make a tarball of the sources of my app + the > "distutils" archive of the external library, copy all into the target > machine, decompress and install via distutils(*) the external library, > setup some PYTHONPATH stuff on the destination machine, and finally be > able to launch the application. > > (*) specifying a prefix into the user home, as I'm not root there > > So in the end I was wondering if there is a more elegant way of doing > this because, as I said before, I'm not very experienced in these kind > of tasks in Python. > > Thanks in advance for any suggestion or comment. > > Alessio Pace. I recommend GUI2Exe, a nice wrapper to py2exe, py2app, PyInstaller, cx_Freeze and bbFreeze: http://code.google.com/p/gui2exe/ I've only used the py2exe portion of the program, but it works great and the developers behind the project are very responsive and helpful. Mike From castironpi at gmail.com Tue Dec 23 05:46:08 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 23 Dec 2008 02:46:08 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com><6ra8t0F925rU1@mid.individual.net><29feda0d-6432-4cb9-8809-e4d4a7798601@e1g2000pra.googlegroups.com><6raeb8F9s47U2@mid.individual.net><25b1ece0-712b-4516-af28-88c50d00ab8c@s9g2000prg.googlegroups.com> Message-ID: On Dec 23, 2:33?am, "Hendrik van Rooyen" wrote: > "r" wrote: > >Now thats the kind of friendly banter this group could use. Instead of > >people acting as if their bowel-movements smell like bakery fresh > >cinnamon rolls! > > What an amazing thing to say! > > Doesn't yours? > > - Hendrik You think your ships don't sink? From hniksic at xemacs.org Fri Dec 12 09:51:31 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 12 Dec 2008 15:51:31 +0100 Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> Message-ID: <87oczhmop8.fsf@mulj.homelinux.net> sturlamolden writes: > On Dec 12, 3:08 pm, Marc 'BlackJack' Rintsch wrote: > >> No bug because a mutation *is* attempted. ``a += x`` calls `a.__iadd__` >> which *always* returns the result which is *always* rebound to the name >> `a`. Even with mutable objects where `__iadd__()` simply returns >> `self`! > > No, a mutation is not attempted, even if __iadd__() always returns a > value. Mutation is attempted. A += x (where "A" could be anything valid at the left-hand side of assignment, including item subscript) is not implemented intuitivaly, as: if hasattr(b, '__iadd__'): A.__iadd__(x) # ignore return value else: A = A.__add__(x) It is implemented as something like: if hasattr(b, '__iadd__'): newval = A.__iadd__(x) else: newval = A.__add__(x) A = newval So the only difference between __add__ and __iadd__ is that __iadd__ is only consulted on +=, where as __add__ is consulted on both + and += (in the latter case only if __iadd__ is missing). > The tuple should check that it is > actually being *mutated* before it raises any exception. Tuple has no way to check that. What tuple sees is only the last line: t[0] = newval At that point, the information about what is really going on is long lost. The only thing tuple could do is detect that the same object is being written that's already there, but tuple doesn't do that by design. From enleverlesX.XmcX at XmclaveauX.com Sat Dec 27 03:30:41 2008 From: enleverlesX.XmcX at XmclaveauX.com (=?UTF-8?Q?M=C3=A9ta-MCI_=28MVP=29?=) Date: Sat, 27 Dec 2008 09:30:41 +0100 Subject: multiply each element of a list by a number In-Reply-To: References: Message-ID: <4955e7be$0$4066$ba4acef3@news.orange.fr> Hi! > map(multby3, (1, 2, 3, )) ...with lambda: map(lambda x: x*3, [1,2,3]) @-salutations -- Michel Claveau From prologic at shortcircuit.net.au Wed Dec 31 00:02:21 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 15:02:21 +1000 Subject: How to get back a list object from its string representation? In-Reply-To: <78f8019c0812302046j31fa38aeif33d659ec5f2c84e@mail.gmail.com> References: <78f8019c0812302046j31fa38aeif33d659ec5f2c84e@mail.gmail.com> Message-ID: On Wed, Dec 31, 2008 at 2:46 PM, Harish Vishwanath wrote: > Hello, > Consider : >>>> li = [1,2,3] >>>> repr(li) > '[1, 2, 3]' > Is there a standard way to get back li, from repr(li) ? Normally you would use eval(..) however this is considered by many to be evil and bad practise (especially by me!) I would advise you use pickle instead. Using eval (evil): >>> li = [1, 2, 3] >>> s = repr(li) >>> s '[1, 2, 3]' >>> lii = eval(s) >>> lii [1, 2, 3] >>> lii == li True Using pickle (better): >>> from pickle import dumps, loads >>> li = [1, 2, 3] >>> s = dumps(li) >>> s '(lp0\nI1\naI2\naI3\na.' >>> lii = loads(s) >>> lii [1, 2, 3] >>> lii == li True cheers James From rt8396 at gmail.com Mon Dec 22 22:15:20 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 19:15:20 -0800 (PST) Subject: iterating initalizations References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> Message-ID: <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> I can't check you code because i don't have these modules but here is the code with proper indention import random from rtcmix import * from chimes_source import * from rhythmblock import * from pitchblock import * indexrand = random.Random() indexrand.seed(2) rhythm = rhythmBlock() pitch = pitchBlock() class pitchAndRhythm: def __init__(self): self.__abet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def listCreate(self, num): if num > 25: print "Oops. This won't work" else: for a in range(num): b = indexrand.randint(0, 3) c = indexrand.randint(0, 7) index = self.__abet[a] index = [ ] index = index.append(rhythm.rhythmTwist(b, c)) take 2: notice the "(" and ")" around the arg to __init__ From onidaito at gmail.com Wed Dec 31 07:37:00 2008 From: onidaito at gmail.com (Benjamin Blundell) Date: Wed, 31 Dec 2008 04:37:00 -0800 (PST) Subject: Graphics Library with Standard Interaction Features, 2D and 3D Message-ID: <69c3eca8-5e17-49fb-8354-5fdc0bd73f9a@r15g2000prd.googlegroups.com> Hi all. I've had a look around the forums and the we and im looking for a library (or a set of libraries) for dealing with Visualisation and Interaction in Python. At the moment i've been using Flash with the Five3D library to do most of the work. Sadly this isnt an option anymore but it is a good example. Pretty,anti-aliased 2D and 3D graphics, simple interaction and no need to rewrite the wheel. Im a fan of OpenGL and PyOpenGL is fairly cool but I really dont want to have to write yet another camera, another way of dealing with Vectors, texture organiser, picking, etc etc. Is there a library or set of libraries that people are aware of that might do this? I remember a few in C++ and C but it'd be nicer to stick to working with Python Cheers Ben From walterbyrd at iname.com Sun Dec 21 00:11:16 2008 From: walterbyrd at iname.com (walterbyrd) Date: Sat, 20 Dec 2008 21:11:16 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> On Dec 20, 5:05?pm, Roy Smith > He got really hung up on the % syntax. I guess it's good to know that there is, at least, one person in the world doesn't like the % formatting. As least the move was not entirely pointless. But, you must admit, of all the things people complain about with Python, the % formatting is probably one of the least common complaints. Complaints about Python's speed seem much more common. Yet, 3.0 makes the speed worse, and "fixes" a non-problem. I can see where the new formatting might be helpful in some cases. But, I am not sure it's worth the cost. From pruebauno at latinmail.com Mon Dec 15 11:05:25 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Mon, 15 Dec 2008 08:05:25 -0800 (PST) Subject: stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> <015612ac$0$20639$c3e8da3@news.astraweb.com> Message-ID: <52cfb77e-4baf-4fba-8eac-cc6c7ddb5be5@k1g2000prb.googlegroups.com> > Non-comparison sorts are a useful technique, but it's changing the > problem, and they are only useful in very limited circumstances. There's > a good reason that most sort routines are based on O(n*log n) comparison > sorts instead of O(n) bucket sorts or radix sorts. > This is an assumption that I never quite understood. What most people want is to have sorted data, they don't care if I used a sorting or non-sorting comparison to do it. I think it is just that in most cases n is not very big anyway and comparison sorts make it easier on the programmer to create arbitrary types that are sortable. From the.brown.dragon.blog at gmail.com Thu Dec 11 09:50:18 2008 From: the.brown.dragon.blog at gmail.com (the.brown.dragon.blog at gmail.com) Date: Thu, 11 Dec 2008 06:50:18 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> Message-ID: <91bf5d87-0154-472b-9350-e3290ab867e1@k1g2000prb.googlegroups.com> On Dec 11, 4:53?pm, "William James" wrote: > William James wrote: > > John W Kennedy wrote: > > > > Xah Lee wrote: > > > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or > > > > Java, you'll have 50 or hundreds lines. > > > > Java: > > > > static float[] normal(final float[] x) { > > > ? ?float sum = 0.0f; > > > ? ?for (int i = 0; i < x.length; ++i) sum += x[i] * x[i]; > > > ? ?final float divisor = (float) Math.sqrt(sum); > > > ? ?float[] a = new float[x.length]; > > > ? ?for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor; > > > ? ?return a; > > > } > > > "We don't need no stinkin' loops!" > > > SpiderMonkey Javascript: > > > function normal( ary ) > > { div=Math.sqrt(ary.map(function(x) x*x).reduce(function(a,b) a+b)) > > ? return ary.map(function(x) x/div) > > } > > The variable "div" shouldn't be global. > > function normal( ary ) > { var div = Math.sqrt( > ? ? ary.map(function(x) x*x).reduce(function(a,b) a+b) ) > ? return ary.map(function(x) x/div) > > } > > Chicken Scheme: (require 'srfi-1) (define (norm vec) (map (cute / <> (sqrt (reduce + 0 (map (cute expt <> 2) vec)))) vec)) Cute huh? ;-) From kylefranki at gmail.com Thu Dec 25 08:38:22 2008 From: kylefranki at gmail.com (kylefranki at gmail.com) Date: Thu, 25 Dec 2008 05:38:22 -0800 (PST) Subject: Canada lesbian couple Message-ID: <1a933c28-e2d5-43c5-877a-c89349d9046b@a12g2000pro.googlegroups.com> couple de lesbienne cherche sex occasionnelle femme seulement http://canada-lesbi.blogbugs.org/ From sjmachin at lexicon.net Fri Dec 19 19:38:25 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 19 Dec 2008 16:38:25 -0800 (PST) Subject: Jarow-Winkler algorithm: Measuring similarity between strings References: <4f351b3b-4da7-4fee-a1ac-c42179d430f5@s9g2000prm.googlegroups.com> Message-ID: On Dec 20, 10:02?am, ?yvind wrote: > Based on examples and formulas fromhttp://en.wikipedia.org/wiki/Jaro-Winkler. For another Python implementation, google "febrl". > Useful for measuring similarity between two strings. For example if > you want to detect that the user did a typo. You mean like comparing the user's input word with some collection of valid words? You would need to be using something else as a quick-and- dirty filter ... Jaro-Winkler is relatively slow. > > def jarow(s1,s2): > > ? ? """ ?Returns a number between 1 and 0, where 1 is the most similar > > ? ? ? ? example: > > ? ? ? ? print jarow("martha","marhta") > > ? ? ? ? """ > ? ? m= jarow_m(s1,s2) > ? ? t1 = jarow_t(s1,s2) > ? ? t2 = jarow_t(s2,s1) > ? ? t = float(t1)/float(t2) Huh? t1 and t2 are supposed to be counts of transpositions. So is t. So how come t is a ratio of t1 to t2?? BTW, suppose t2 is zero. One usually prefers symmetry i.e dist(s1, s2) == dist(s2, s1). You can't have symmetry if t = t1/t2. Also as the Wikipedia article says, it's not a metric. I.e. it doesn't satisfy dist(a, c) <= dist(a, b) + dist(b, c). > > ? ? d = 0.1 > > ? ? # this is the jaro-distance > ? ? d_j = 1.0/3.0 * ((m/len(s1)) + (m/len(s2)) + ((m - t)/float(m))) > > ? ? # if the strings are prefixed similar, they are weighted more > heavily > ? ? l = winkler_l(s1,s2) > ? ? print l > ? ? return d_j + (l * 0.1 * (1 - d_j)) > > def winkler_l(s1,s2): > ? ? """ Number of the four first characters matching """ > > ? ? l = 0 > ? ? counter = 0 > ? ? for s_j,s_i in zip(s1,s2): > > ? ? ? ? if s_j == s_i: > > ? ? ? ? ? ? l += 1 > ? ? ? ? counter += 1 > > ? ? ? ? if counter > 4: > ? ? ? ? ? ? break > > ? ? return l > > def jarow_m(s1,s2): > > ? ? """ Number of matching characters """ This code ignores the caveat from the Wikipedia article """ Two characters from s1 and s2 respectively, are considered matching only if they are not farther than \left\lfloor\frac{\max(|s_1|,|s_2|)} {2}\right\rfloor-1. """ which looks as though it is missing the words "characters apart" or some such from the end of it. FWIW I've never seen this "distance apart" restriction expressed unambiguously in the case where the strings are of unequal length. > ? ? m = 0 > ? ? d = {} > ? ? for s in s1: > > ? ? ? ? d[s] = True > > ? ? for s in s2: > > ? ? ? ? if d.has_key(s): > > ? ? ? ? ? ? m += 1 > ? ? return m The above code is not symmetrical; jarow_m(s1, s2) does not necessarily equal jarow_m(s2, s1). The article talks about one "m", not two of them. > def jarow_t(s1,s2): > > ? ? """ > ? ? Number of transpositions > > ? ? """ > > ? ? t= 0 > ? ? pos ={} > ? ? counter = 0 > ? ? for s in s1: > > ? ? ? ? pos[s] = counter > ? ? ? ? counter += 1 > ? ? counter = 0 > ? ? for s in s2: > > ? ? ? ? if pos.has_key(s): > > ? ? ? ? ? ? if pos[s] != counter: This test is likely to come up with the wrong answer if the string lengths differ. > > ? ? ? ? ? ? ? ? t += 1 > > ? ? ? ? counter += 1 > > ? ? return t Cheers, John From steve at REMOVE-THIS-cybersource.com.au Thu Dec 18 20:02:07 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2008 01:02:07 GMT Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> <6qv7kfFeuf65U1@mid.uni-berlin.de> Message-ID: <015ae9e9$0$20656$c3e8da3@news.astraweb.com> On Thu, 18 Dec 2008 10:49:27 -0500, Neal Becker wrote: > So if I want to overload something in my custom class, so that I get a > nice string whether it's printed directly, or as part of a container, > what is the recommendation? Overload both __str__ and __repr__? Either or both or neither, whatever you feel is best. Or create a pretty- print method, and call that manually. I've done all of the above at times. Remember though, that ideally you should be able to round-trip your objects to strings and back again: obj = MyClass(args) eval(repr(obj)) == obj should be true. This isn't compulsory, and it isn't always possible, but unless you have good reason to avoid it, you should aim for that behaviour. BTW Neal, your posts aren't word wrapped. When I read your posts, I get each paragraph as one extremely LONG line scrolling way out to the side. That's against the Internet standards for both email and Usenet, so could you please configure your client to word-wrap at (say) 70 characters? -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun Dec 7 18:51:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 23:51:45 GMT Subject: Rich Comparisons Gotcha References: Message-ID: <014c593e$0$20670$c3e8da3@news.astraweb.com> On Sun, 07 Dec 2008 13:57:54 -0800, James Stroud wrote: > Rasmus Fogh wrote: >> Current behaviour is both inconsistent and counterintuitive, as these >> examples show. >> >>>>> x = float('NaN') >>>>> x == x >> False > > Perhaps this should raise an exception? Why on earth would you want checking equality on NaN to raise an exception??? What benefit does it give? > I think the problem is not with > comparisons in general but with the fact that nan is type float: > > py> type(float('NaN')) > > > No float can be equal to nan, but nan is a float. How can something be > not a number and a float at the same time? Because floats are not real numbers. They are *almost* numbers, they often (but not always) behave like numbers, but they're actually not numbers. The difference is subtle enough that it is easy to forget that floats are not numbers, but it's easy enough to find examples proving it: Some perfectly good numbers don't exist as floats: >>> 2**-10000 == 0.0 True Try as you might, you can't get the number 0.1 *exactly* as a float: >>> 0.1 0.10000000000000001 For any numbers x and y not equal to zero, x+y != x. But that fails for floats: >>> 1001.0 + 1e99 == 1e99 True The above is because of overflow. But even avoiding overflow doesn't solve the problem. With a little effort, you can also find examples of "ordinary sized" floats where (x+y)-y != x. >>> 0.9+0.1-0.9 == 0.1 False >>>>> import numpy >>>>> y = numpy.zeros((3,)) >>>>> y >> array([ 0., 0., 0.]) >>>>> bool(y==y) >> Traceback (most recent call last): >> File "", line 1, in >> ValueError: The truth value of an array with more than one element is >> ambiguous. Use a.any() or a.all() > > But the equality test is not what fails here. It's the cast to bool that > fails And it is right to do so, because it is ambiguous and the library designers rightly avoided the temptation of guessing what result is needed. >>>>> ll1 = [y,1] >>>>> y in ll1 >> True >>>>> ll2 = [1,y] >>>>> y in ll2 >> Traceback (most recent call last): >> File "", line 1, in >> ValueError: The truth value of an array with more than one element is >> ambiguous. Use a.any() or a.all() > > I think you could be safe calling this a bug with numpy. Only in the sense that there are special cases where the array elements are all true, or all false, and numpy *could* safely return a bool. But special cases are not special enough to break the rules. Better for the numpy caller to write this: a.all() # or any() instead of: try: bool(a) except ValueError: a.all() as they would need to do if numpy sometimes returned a bool and sometimes raised an exception. -- Steven From bthayre at physics.ucsd.edu Mon Dec 8 17:43:32 2008 From: bthayre at physics.ucsd.edu (Robocop) Date: Mon, 8 Dec 2008 14:43:32 -0800 (PST) Subject: Text parsing via regex References: Message-ID: Wow! Thanks for all the input, it looks like that textwrapper will work great for my needs. And thanks for the regex help everyone. Also, i was thinking of using a list, but i haven't used them much in python. Is there anything in python that is equivalent to pushback in c++ for vectors? As in, could i just initialize a list, and then pushback values into it as i need them? Thanks again! From mirandasnailvv at gmail.com Fri Dec 19 19:42:11 2008 From: mirandasnailvv at gmail.com (mirandasnailvv at gmail.com) Date: Fri, 19 Dec 2008 16:42:11 -0800 (PST) Subject: tonya cooley softcore porn - Free Message-ID: tonya cooley softcore porn . . . *******CLICK HERE******** http://club247.cn/tonya-cooley-softcore-porn ***************************** . . . . . . . . . . . . tonya cooley softcore porn From sjmachin at lexicon.net Sun Dec 28 17:12:11 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 28 Dec 2008 14:12:11 -0800 (PST) Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <0167cbf7$0$6988$c3e8da3@news.astraweb.com> <676bffeb-4b07-4226-8c14-7da57d94351b@f13g2000yqj.googlegroups.com> Message-ID: <3afba310-dcde-4dc1-825a-7c63b97e2a40@w1g2000prk.googlegroups.com> On Dec 29, 7:06?am, Roger wrote: > > Curious. When I see a bare return, the first thing I think is that the > > author forgot to include the return value and that it's a bug. > > > The second thing I think is that maybe the function is a generator, and > > so I look for a yield. If I don't see a yield, I go back to thinking > > they've left out the return value, and have to spend time trying to > > understand the function in order to determine whether that is the case or > > not. > > > In other words, even though it is perfectly valid Python, bare returns > > always make the intent of the function less clear for me. I'm with Bruno > > -- if you have a function with early exits, and you need to make the > > intent of the function clear, explicitly return None. Otherwise, leave it > > out altogether. > > > -- > > Steven > > To me this is the soundest argument. ?Thanks for the advice. ?I think > I'll follow this as a rule of thumb hereafter. Please don't. Follow MRAB's advice, with the corollary that a generator is forced by the compiler to be a "procedure" in MRAB's terminology. From quian.xu at stud.tu-ilmenau.de Tue Dec 23 05:50:59 2008 From: quian.xu at stud.tu-ilmenau.de (Qian Xu) Date: Tue, 23 Dec 2008 11:50:59 +0100 Subject: print to console without a line break Message-ID: Hello All, Is it possible to print something to console without a line break? I tried: sys.stdout.write("Testing something ...") // nothing will be printed time.sleep(1) sys.stdout.write("done\n") // now, the whole string will be printed What I want, is to see "Testing something ..." first. And after 1 second, to see "done" (with a line break) The only one solution I have found is to call "echo -n 'my_string'". But it is not nice. Because I have to escape all special chars in the string manually. Any advice? Best regards -- Qian Xu From http Wed Dec 17 00:47:11 2008 From: http (Paul Rubin) Date: 16 Dec 2008 21:47:11 -0800 Subject: How to modify a program while it's running? References: Message-ID: <7xtz93qrog.fsf@ruckus.brouhaha.com> Joe Strout writes: > So I'd like to restructure my app so that it can stay running and stay > logged in, yet I can still update and reload at least most of the > code. But I'm not sure what's the best way to do this. Should I move > the reloadable code into its own module, and then when I give my bot a > "reload" command, have it call reload on that module? Will that work, > and is there a better way? If you are on Linux, an alternative might be to start a new version of your program in a separate process, then transfer the open connections from the old process to the new ones through Unix domain sockets. The SCM_RIGHTS message lets you pass file descriptors around between processes. I've never tried this myself but have always wanted to. I think someone submitted a patch for Python's socket module a year or so ago to support that operation, but I don't know if it was accepted. You could always apply it yourself. Generally, trying to hot-patch code is messy and dangerous even in systems that were designed for it. From gagsl-py2 at yahoo.com.ar Tue Dec 30 09:12:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Dec 2008 12:12:32 -0200 Subject: Python module import loop issue References: <02bc8567-695a-4277-9698-a95549a0bc98@w39g2000prb.googlegroups.com> <4a0557b7-e901-49ff-b4db-53f4d8a7c0f8@r40g2000yqj.googlegroups.com> Message-ID: En Tue, 30 Dec 2008 01:32:48 -0200, Carl Banks escribi?: > Gabriel Genellina wrote: >> A problem with metaclasses is when you have intermediate subclasses that >> are not meant to be registered, but the metaclass applies equally to all >> of them. > > Not the way I wrote it. If you'll note, the metaclass only added the > class to the factory map if a tag attribute was defined in the class > dict. Ah, I didn't notice that, sorry! -- Gabriel Genellina From google at mrabarnett.plus.com Fri Dec 5 15:59:06 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 05 Dec 2008 20:59:06 +0000 Subject: slow Python 3.0 write performance? In-Reply-To: References: Message-ID: <4939961A.8080205@mrabarnett.plus.com> Istvan Albert wrote: > On Dec 5, 3:06 pm, s... at pobox.com wrote: > >> It should get faster over time. It will get faster over a shorter period of >> time if people contribute patches. > > I see, thanks for the clarification. > > I will make the point though that this makes python 3.0 unsuited for > anyone who has to process data. One could live with slowdowns of say > 20-50 percent, to get the goodies that 3.0 offers, but when a process > that takes 1 second suddenly starts to take 10, it is makes the > situation untenable. > Does pysco with with Python 3.0 (the homepage says 2.5)? If it does then that might help! :-) From steve at REMOVE-THIS-cybersource.com.au Thu Dec 18 20:51:38 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2008 01:51:38 GMT Subject: Factoring Polynomials References: <015aebdf$0$20656$c3e8da3@news.astraweb.com> Message-ID: <015af585$0$20656$c3e8da3@news.astraweb.com> On Fri, 19 Dec 2008 01:10:28 +0000, Steven D'Aprano wrote: > Because this looks like homework... Homework or not, of course others have answered it completely, more or less error-free. -- Steven From federico at linux.com.uy Fri Dec 19 12:03:53 2008 From: federico at linux.com.uy (Federico Moreira) Date: Fri, 19 Dec 2008 14:03:53 -0300 Subject: Generator slower than iterator? In-Reply-To: <494BC8CC.6020706@mrabarnett.plus.com> References: <62013718-57e9-4690-a2be-11e63b9c135b@u18g2000pro.googlegroups.com> <494BC8CC.6020706@mrabarnett.plus.com> Message-ID: Yep i meant split sorry. Thanks for the answer! -------------- next part -------------- An HTML attachment was scrubbed... URL: From fakeaddress at nowhere.org Mon Dec 15 01:43:55 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 14 Dec 2008 22:43:55 -0800 Subject: Bidirectional Networking In-Reply-To: <29283382-3e26-492a-8612-9352f32c1c01@r15g2000prd.googlegroups.com> References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <98a6c3cd-181c-43c9-805b-fb0689c69544@a26g2000prf.googlegroups.com> <29283382-3e26-492a-8612-9352f32c1c01@r15g2000prd.googlegroups.com> Message-ID: Emanuele D'Arrigo wrote: > Bryan Olson wrote: >> Software firewalls will often simply refuse incoming connections. The >> basic protection of the garden-variety home router comes from "network >> address translation" (NAT), in which case TCP connections initiated from >> the inside will generally work, regardless of port, and incoming >> connections will fail. > > Ok, I think I'm getting the picture here. So this means that in most > circumstances where the data flow from the server is frequent the > client initiates the connection, usually requests some initial data > and keeps polling the server periodically, issuing new requests. In > this context can the client simply keep the connection alive and > listen for new data from the server coming at any time rather than > actively issuing requests? Sure. You might include a method for the client to ensure the connection is alive, either with TCP keep-alive or your own messages over the connection. > Are there drawbacks to this strategy? I.e. > is there a limit to the number of simultaneous connections a server > can keep alive? I've noticed that the socket pages mention a 5 > connections limit. Is that it? What if I want to make a virtual room > with 20 people connected simultaneously? Five is not the connection limit. Twenty connections is no problem, and modern systems should support hundreds by default, and thousands with a bit of care and tuning. >>> or would it be the responsibility of the user >>> to configure the firewall so that the application can receive a >>> connection? >> That can be a huge hassle. The first choice is for the application to >> conform to popular firewall policies, so no special configuration is >> required. > > I agree, I'd rather have the user do nothing in this regard. I'm just > wondering how it's done with data intensive application where the > server needs to send new data to the client frequently. Does the > client just keep the connection live at all time for the server to > send stuff or does the client continuously open, sends a request, > receives data and closes the connection every time? Here I'm thinking > about an online game, with 100 players moving their avatars. Does the > client requests their position nearly every frame? I'd say keeping an open connection to each client is reasonable there. SocketServer and its descendants may not be sophisticated enough for such an application. -- --Bryan From mrkafk at gmail.com Mon Dec 29 12:11:37 2008 From: mrkafk at gmail.com (mk) Date: Mon, 29 Dec 2008 18:11:37 +0100 Subject: multiprocessing vs thread performance In-Reply-To: References: Message-ID: Jarkko Torppa wrote: > On the PEP371 it says "All benchmarks were run using the following: > Python 2.5.2 compiled on Gentoo Linux (kernel 2.6.18.6)" Right... I overlooked that. My tests I quoted above were done on SLES 10, kernel 2.6.5. > With python2.5 and pyProcessing-0.52 > > iTaulu:src torppa$ python2.5 run_benchmarks.py empty_func.py > Importing empty_func > Starting tests ... > non_threaded (1 iters) 0.000003 seconds > threaded (1 threads) 0.000143 seconds > processes (1 procs) 0.002794 seconds > > non_threaded (2 iters) 0.000004 seconds > threaded (2 threads) 0.000277 seconds > processes (2 procs) 0.004046 seconds > > non_threaded (4 iters) 0.000005 seconds > threaded (4 threads) 0.000598 seconds > processes (4 procs) 0.007816 seconds > > non_threaded (8 iters) 0.000008 seconds > threaded (8 threads) 0.001173 seconds > processes (8 procs) 0.015504 seconds There's smth wrong with numbers posted in PEP. This is what I got on 4-socket Xeon (+ HT) with Python 2.6.1 on Debian (Etch), with kernel upgraded to 2.6.22.14: non_threaded (1 iters) 0.000004 seconds threaded (1 threads) 0.000159 seconds processes (1 procs) 0.001067 seconds non_threaded (2 iters) 0.000005 seconds threaded (2 threads) 0.000301 seconds processes (2 procs) 0.001754 seconds non_threaded (4 iters) 0.000006 seconds threaded (4 threads) 0.000581 seconds processes (4 procs) 0.003906 seconds non_threaded (8 iters) 0.000009 seconds threaded (8 threads) 0.001148 seconds processes (8 procs) 0.008178 seconds From rdmurray at bitdance.com Tue Dec 9 15:27:42 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Tue, 9 Dec 2008 15:27:42 -0500 (EST) Subject: When (and why) to use del? In-Reply-To: References: Message-ID: On Tue, 9 Dec 2008 at 18:55, Duncan Booth wrote: > Albert Hopkins wrote: > >> def otherfunction(): >> try: >> # some stuff >> except SomeException, e: >> # more stuff >> del e >> return >> >> >> I think this looks ugly, but also does it not hurt performance by >> preempting the gc? My feeling is that this is a misuse of 'del'. Am I >> wrong? Is there any advantage of doing the above? >> > It is probably a complete waste of time, but there are situations where > code similar to this can be useful: > > def otherfunction(): > try: > # some stuff > except SomeException, e: > # more stuff > del e > raise > return > > The point of code like this is that when a function exits by throwing an > exception the traceback includes a reference to the stack frame and all the > local variables. In some situations that can result in large data > structures not being freed for a very long time (e.g. until another > exception is thrown that is handled at the same level). So, *in very > specialised situations* it may be important to delete particular names from > the local namespace. If I'm reading http://www.python.org/dev/peps/pep-3110/ right, Python 3.0 eliminates even this use case :) I have had occasions to use del, when I don't want the variable in the namespace anymore for some reason (for example, when I'm later going to be scanning the namespace for some reason). --RDM From manu3d at gmail.com Sun Dec 14 08:01:18 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Sun, 14 Dec 2008 05:01:18 -0800 (PST) Subject: Bidirectional Networking References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <98a6c3cd-181c-43c9-805b-fb0689c69544@a26g2000prf.googlegroups.com> <29283382-3e26-492a-8612-9352f32c1c01@r15g2000prd.googlegroups.com> Message-ID: <606a02c9-ae34-42c6-82b2-94582d22dab2@r15g2000prh.googlegroups.com> On Dec 14, 2:40?am, Brian Allen Vanderburg II wrote: > But what I think it means is that during the listen for an incoming > connection on the listening socket, if multiple connection attempts are > coming in at one time it can keep a backlog of up to 5 of these > connection attempts for that individual socket. Ah, Gotcha! Thank you, that makes sense! Manu From mensanator at aol.com Wed Dec 3 19:08:23 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 3 Dec 2008 16:08:23 -0800 (PST) Subject: "as" keyword woes References: <493701f0$0$194$e4fe514c@news.xs4all.nl> <01470229$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Dec 3, 4:38?pm, Steven D'Aprano wrote: > On Wed, 03 Dec 2008 22:02:24 +0000, Martin P. Hellwig wrote: > > Warren DeLano wrote: > >> A bottom line / pragmatic question... hopefully not a FAQ. > > >> Why was it necessary to make "as" a reserved keyword? > > > > Because it can be used at the import statement to let the imported thing > > be known under another name? > > Something like: > > > ?>>> import xml.etree.ElementTree as ET > > Martin, that doesn't answer the OP's question *at all*. Python 2.5 uses > "as" in that way, and it is not a keyword. > > >>> import math as MATHS > >>> MATHS > > >>> as = 45 > > :1: Warning: 'as' will become a reserved keyword in Python 2.6>>> as > > :1: Warning: 'as' will become a reserved keyword in Python 2.6 > 45 > > I'd guess that the change was to simplify the CPython parser. I have no > idea if it was a tiny change or a significant change, if it made a huge > difference to Python-dev or a little difference. Perhaps someone on the > dev team could comment. > > While I feel sympathy for the OP, I do have to ask: he's been using > Python 2.5 for, what, a couple of years now? How many times did he see > the depreciation warning, and almost certainly the pending depreciation > warning before that? Python-dev has been talking about making "as" a > keyword since at least Python 2.3. Why wait until after version 2.6 is > released before saying anything? When I brought this up a short while ago (because sympy crashed in Python 2.6) someone said that there was a bug in Python 2.5 that prevented the display of the deprecation message (when "as" appeared inside imported modules). So apparently, the sympy developers never saw a deprecation warning in all the years they were using 2.5. There was, however, no excuse for not testing it in 2.6. > > -- > Steven From Ron.Barak at lsi.com Tue Dec 16 03:00:21 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Tue, 16 Dec 2008 08:00:21 +0000 Subject: tutorial on parser In-Reply-To: References: Message-ID: <7F0503CD69378F49BE0DC30661C6CCF602494098@enbmail01.lsi.com> Hi John, You may want to read http://nedbatchelder.com/text/python-parsers.html Bye, Ron. -----Original Message----- From: John Fabiani [mailto:jfabiani at yolo.com] Sent: Tuesday, December 16, 2008 08:47 To: python-list at python.org Subject: tutorial on parser Hi, I'm attempting to learn how to convert MsSQl Transact-SQL to postgres pgsql. So far my readings have led me to finding a parser. I'm looking for a tutorial on how to get it done. I did find a commercial product but they want over $10,000 us. This way beyond my means. Therefore, I need to get it done either myself to find a open source project. Thanks in advance. John Fabiani From riklaunim at gmail.com Mon Dec 1 02:43:14 2008 From: riklaunim at gmail.com (riklaunim at gmail.com) Date: Sun, 30 Nov 2008 23:43:14 -0800 (PST) Subject: Cross platform desktop operations in Python Message-ID: Hi I'm looking for a cross platform (Linux/Win/Mac) solution of common desktop operations like: * Getting system icon theme (icons for files, folders etc.) * Determine mimetype (better than mimetypes using mapped extension to mime) Under Unix/Linux there are freedesktop.org standards and pyxdg that can do that, but it won't work for example on Windows. Are there solutions for this, or do I have to implement a backed for every system? From clp at rebertia.com Sun Dec 28 07:04:13 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 28 Dec 2008 04:04:13 -0800 Subject: What is site-packages? In-Reply-To: References: Message-ID: <47c890dc0812280404w233c2977sf1b75f33945b3ae3@mail.gmail.com> On Sun, Dec 28, 2008 at 3:40 AM, Hussein B wrote: > Hey, > What is /usr/lib/pythonx.y/site-packages folder and for what it is > used usually? I believe it's where third-party libraries are typically installed to. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From clp at rebertia.com Fri Dec 12 18:28:13 2008 From: clp at rebertia.com (Chris Rebert) Date: Fri, 12 Dec 2008 15:28:13 -0800 Subject: var or inout parm? In-Reply-To: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> Message-ID: <47c890dc0812121528s58638b4eha9a2c02e2cd45ee6@mail.gmail.com> On Fri, Dec 12, 2008 at 4:56 AM, sturlamolden wrote: > On Dec 12, 1:44 pm, "Chris Rebert" wrote: > >> Python begs to differ, as those two statements are both semantically >> identical in this case: > > That is because integers are immutable. When x += 1 is done on an int, > there will be a rebinding. But try the same on say, a numpy array, and > the result will be different: Yes, I know that. Did you not read the end of my email? Here it is again: """ If you were talking about lists rather than integers though, you'd be absolutely correct, as the += ends up being a method call to __iadd__ instead of a plain assignment. """ Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From google at mrabarnett.plus.com Fri Dec 5 14:36:16 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 05 Dec 2008 19:36:16 +0000 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: References: <5u8o06xbqf.ln2@joeserver.homelan.net> Message-ID: <493982B0.2050903@mrabarnett.plus.com> Joe Strout wrote: > On Dec 5, 2008, at 11:36 AM, Johannes Bauer wrote: > >>> I suspect that '?' after \n (\u0a00) is indicates not 'question-mark' >>> but 'uninterpretable as a utf16 character'. The traceback below >>> confirms that. It should be an end-of-file marker and should not be >>> passed to Python. I strongly suspect that whatever wrote the file >>> screwed up the (OS-specific) end-of-file marker. I have seen this >>> occasionally on Dos/Windows with ascii byte files, with the same symptom >>> of reading random garbage pass the end of the file. Or perhaps >>> end-of-file does not work right with utf16. >> >> So UTF-16 has an explicit EOF marker within the text? > > No, it does not. I don't know what Terry's thinking of there, but text > files do not have any EOF marker. They start at the beginning > (sometimes including a byte-order mark), and go till the end of the > file, period. > Text files _do_ sometimes have an EOF marker, such as character 0x1A. It can occur in text files in Windows. >> I cannot find one in original file, only some kind of starting >> sequence I suppose >> (0xfeff). > > That's your byte-order mark (BOM). > >> The last characters of the file are 0x00 0x0d 0x00 0x0a, >> simple \r\n line ending. > > Sounds like a perfectly normal file to me. > > It's hard to imagine, but it looks to me like you've found a bug. > From sjmachin at lexicon.net Wed Dec 31 08:55:57 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 31 Dec 2008 05:55:57 -0800 (PST) Subject: TypeError: list indices must be integers References: <2e5a61c0-fa99-4170-81ca-eb3a10859400@k36g2000pri.googlegroups.com> <98f638c1-d191-4f95-9668-01bc3c47526c@i20g2000prf.googlegroups.com> Message-ID: <00f88aeb-5651-424a-b324-04695a0d397a@w39g2000prb.googlegroups.com> On Dec 31 2008, 3:26?pm, dubux wrote: > thanks for help everyone. it turned out the function itself worked > fine.. it was the way i was calling it that was messing everything up. > i ended up re-doing the whole thing as follows, and it now works > perfectly. > > def news(x,y): > ? ? ? ? news_file = '/home/scam/Desktop/www/info/news' > ? ? ? ? news = open(news_file, 'r') > ? ? ? ? news_list = news.readlines() > ? ? ? ? news.close() > ? ? ? ? if x == 'date': > ? ? ? ? ? ? ? ? mylist = map(lambda i: news_list[i], filter(lambda i: i%2 == 0, range > (len(news_list)))) > ? ? ? ? ? ? ? ? date = mylist[y].replace("\n","") > ? ? ? ? ? ? ? ? return '

%s

\n\n' % (date) > ? ? ? ? if x == 'news': > ? ? ? ? ? ? ? ? mylist = map(lambda i: news_list[i], filter(lambda i: i%2 == 1, range > (len(news_list)))) > ? ? ? ? ? ? ? ? news = mylist[y].replace("\n","") > ? ? ? ? ? ? ? ? return '

%s

\n
\n' % (news) > ? ? ? ? else: > ? ? ? ? ? ? ? ? return news_list > > news_parse, count, news_list = " ", 0, news('list','list') > newss = map(lambda i: news_list[i], filter(lambda i: i%2 == 1, range > (len(news_list)))) > while count < len(newss): > ? ? ? ? get_date = news('date', count) > ? ? ? ? get_news = news('news', count) > ? ? ? ? news_parse = '%s %s %s' % (news_parse, get_date, get_news) > ? ? ? ? count = count + 1 Unless I'm sorely mistaken, the whole of the above can be replaced by something like (untested): news_file = '/home/scam/Desktop/www/info/news' news = open(news_file, 'r') accum = [] for lineno, line in enumerate(news): accum.append('

%s

\n%s\n' % (line.strip(), ('', '
')[lineno % 1])) news_parse = ' '.join(accum) news.close() count = (lineno + 1) // 2 # if indeed count is needed with the virtues of brevity and speed ... if there are N (date, news) items, your code reads the file 2*N+1 times!!! How big is N? From nick at craig-wood.com Mon Dec 1 06:30:44 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 01 Dec 2008 05:30:44 -0600 Subject: distinct fcntl flags for stdin and stdout References: Message-ID: mbuna wrote: > Hello, > when I set non blocking flag with fcntl on sys.stdin, then sys.stdout > turns into non blocking mode too. Is it normal behaviour? How can I > turn stdin into non blocking mode but not stdout? Thanks. > > This is a quick program that shows the (my?) problem: > > import fcntl > import os > import sys > > print "STDIN", sys.stdin, "fd=%d" % sys.stdin.fileno() > print "STDOUT", sys.stdout, "fd=%d" % sys.stdout.fileno() > print "os.O_NDELAY=%04x" % os.O_NDELAY > def state(): > flag = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL) > print "stdin: flag=%04x" % flag > flag = fcntl.fcntl(sys.stdout.fileno(), fcntl.F_GETFL) > print "stdout: flag=%04x" % flag > state() > print "setting non blocking on stdin..." > flag = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL) > fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, flag | os.O_NDELAY) > state() > print "removing non blocking on stdin..." > flag = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL) > fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, flag & ~os.O_NDELAY) > state() > > > RESULT > STDIN ', mode 'r' at 0x2aaaaaacd120> fd=0 > STDOUT ', mode 'w' at 0x2aaaaaacd198> fd=1 > os.O_NDELAY=0800 > stdin: flag=8002 > stdout: flag=8002 > setting non blocking on stdin... > stdin: flag=8802 > stdout: flag=8802 > removing non blocking on stdin... > stdin: flag=8002 > stdout: flag=8002 If you try this with output redirected to a file, you get this (under linux) STDIN ', mode 'r' at 0xb7d03020> fd=0 STDOUT ', mode 'w' at 0xb7d03068> fd=1 os.O_NDELAY=0800 stdin: flag=0002 stdout: flag=8001 setting non blocking on stdin... stdin: flag=0802 stdout: flag=8001 removing non blocking on stdin... stdin: flag=0002 stdout: flag=8001 So I suspect your result is because stdin and stdout refer to the same file (eg /dev/tty0 or /dev/pts/25). No idea whether this is correct behaviour or not though! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From geekmail at usenot.de Fri Dec 5 10:09:30 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Fri, 5 Dec 2008 16:09:30 +0100 Subject: "as" keyword woes References: <7dudnSS7uIn_KarUnZ2dnUVZ_tTinZ2d@earthlink.com> <0147e4df$0$20670$c3e8da3@news.astraweb.com> <01485198$0$20670$c3e8da3@news.astraweb.com> Message-ID: <20081205160930.6e297c00@usenot.de> On 04 Dec 2008 22:29:41 GMT Steven D'Aprano wrote: > Thank goodness we don't have to program in verbose, explicit English! Then you'll HATE Inform 7: http://en.wikipedia.org/wiki/Inform_7#Example_game_2 :) /W -- My real email address is constructed by swapping the domain with the recipient (local part). From zac256 at gmail.com Tue Dec 2 20:19:41 2008 From: zac256 at gmail.com (Zac Burns) Date: Tue, 2 Dec 2008 17:19:41 -0800 Subject: Reverse zip() ? In-Reply-To: <333edbe80812021647i4621271p7f87dff8d0926951@mail.gmail.com> References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> <333edbe80812021647i4621271p7f87dff8d0926951@mail.gmail.com> Message-ID: <333edbe80812021719x6bb03418pe3041fbdd387337f@mail.gmail.com> More succinct failure: keys, values = zip(*{}.iteritems()) -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer (Digital Overlord) Zindagi Games On Tue, Dec 2, 2008 at 4:47 PM, Zac Burns wrote: > There is a problem with this however, which prompted me to actually > write an unzip function. > > One might expect to be able to do something like so (pseudocode)... > > def filesAndAttributes(): > files = walk() > attributes = [attr(f) for f in files] > return zip(files, attributes) > > files, attributes = zip(*filesAndAttributes()) > > The corner case is when dealing with empty lists and there aren't > enough items to unpack. > > The unzip function therefore has an elementsForEmpty keyword that > handles this case. Perhaps something like this could be added to zip? > I have not (yet) dealt with the PEP process, so I'm not sure where > that starts. Perhaps a discussion could start here. > > -- > Zachary Burns > (407)590-4814 > Aim - Zac256FL > Production Engineer (Digital Overlord) > Zindagi Games > > > > On Tue, Dec 2, 2008 at 4:14 PM, John Machin wrote: >> On Dec 3, 7:12 am, Stefan Behnel wrote: >>> Andreas Waldenburger wrote: >>> > we all know about the zip builtin that combines several iterables into >>> > a list of tuples. >>> >>> > I often find myself doing the reverse, splitting a list of tuples into >>> > several lists, each corresponding to a certain element of each tuple >>> > (e.g. matplotlib/pyplot needs those, rather than lists of points). >>> >>> > This is of course trivial to do via iteration or listcomps, BUT, I was >>> > wondering if there is a function I don't know about that does this >>> > nicely? >>> >>> I think you're asking about zip(): >>> >>> >>> l=[1,2,3] >>> >>> zip(l,l) >>> [(1, 1), (2, 2), (3, 3)] >>> >>> zip(*zip(l,l)) >>> [(1, 2, 3), (1, 2, 3)] >>> >> >> Here's a version that makes it slightly easier to comprehend: >> >> Q: I know how to zip sequences together: >> | >>> a = (1, 2, 3) >> | >>> b = (4, 5, 6) >> | >>> z = zip(a, b) >> | >>> z >> | [(1, 4), (2, 5), (3, 6)] >> but how do I reverse the process? >> >> A: Use zip()! >> | >>> a2, b2 = zip(*z) >> | >>> a2 >> | (1, 2, 3) >> | >>> b2 >> | (4, 5, 6) >> >> Cheers, >> John >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > From mail at timgolden.me.uk Fri Dec 5 16:05:55 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 05 Dec 2008 21:05:55 +0000 Subject: Can I load a python program at the interactive >>> prompt? In-Reply-To: <269e5d69-02b7-409b-ad53-b7702b6ec13a@i24g2000prf.googlegroups.com> References: <269e5d69-02b7-409b-ad53-b7702b6ec13a@i24g2000prf.googlegroups.com> Message-ID: <493997B3.20707@timgolden.me.uk> walterbyrd wrote: > I am running cygwin on xp. .... and I just noticed this vital bit. So not sure how much of my other post applies. Sorry. Maybe it'll help anyway. :) TJG From rt8396 at gmail.com Wed Dec 17 12:00:01 2008 From: rt8396 at gmail.com (r) Date: Wed, 17 Dec 2008 09:00:01 -0800 (PST) Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> Message-ID: <175fa5d5-f345-47b8-a686-e0e36e1b99e9@q37g2000vbn.googlegroups.com> I think there is a simpler answer to all this(not to take away from the other ones here though which are all great). When writing procedural code how would you like it if vars inside functions were automatically global. Your code with be blowing chunks in no time. Thats the reason for global declarations and instance.var :) From mickey at localhost.vanille.zapto.org Thu Dec 11 17:34:21 2008 From: mickey at localhost.vanille.zapto.org (Michael 'Mickey' Lauer) Date: 11 Dec 2008 22:34:21 GMT Subject: using distutils to cross-compile extensions? References: Message-ID: <6qdircFbgacnU1@mid.dfncis.de> Michael George wrote: > I have an extension module that I've built using distutils. I wonder if > it's possible to use distutils to cross-compile it for windows on my > linux box, and whether the pain involved is great. Can anyone point me > in the right direction? Take a look at OpenEmbedded; I have patches against distutils that make it crosscompile most packages. :M: From geekmail at usenot.de Sat Dec 6 05:15:54 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sat, 6 Dec 2008 11:15:54 +0100 Subject: Don't you just love writing this sort of thing :) References: <0148b086$0$20670$c3e8da3@news.astraweb.com> <01490b5f$0$20670$c3e8da3@news.astraweb.com> Message-ID: <20081206111554.0bb35558@usenot.de> On Sat, 06 Dec 2008 20:28:17 +1300 Lawrence D'Oliveiro wrote: > Does that make any sense to you, or should I start drawing simple > diagrams? People, please! Is some civility too much to ask? /W -- My real email address is constructed by swapping the domain with the recipient (local part). From mdgeorge at cs.cornell.edu Thu Dec 4 17:42:03 2008 From: mdgeorge at cs.cornell.edu (Michael George) Date: Thu, 4 Dec 2008 17:42:03 -0500 Subject: using distutils to cross-compile extensions? Message-ID: <49385CBB.7060207@cs.cornell.edu> Hi, Please CC me in replying as I am off list. I have an extension module that I've built using distutils. I wonder if it's possible to use distutils to cross-compile it for windows on my linux box, and whether the pain involved is great. Can anyone point me in the right direction? Thanks, --Mike From steve at REMOVE-THIS-cybersource.com.au Sat Dec 13 05:03:35 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Dec 2008 10:03:35 GMT Subject: Need help improving number guessing game References: Message-ID: <01537ffa$0$6988$c3e8da3@news.astraweb.com> On Sat, 13 Dec 2008 00:57:12 -0800, feba wrote: > I have one major problem with this; the 'replay' selection. It quits if > you put in 0, as it should, and continues if you put in any other > number. However, if you just press enter, it exits with an error. it > also looks really ugly, and I'm sure there has to be plenty of better > ways to do it. Start by refactoring your code into small, easy to understand functions. For example, You mix in the same piece of code the logic for: - error handling; - starting a new game; - quiting (although you use a function for this, well done); - and game logic and then you have to repeat it all again, almost word-for-word, for one player mode and two player mode. Start with a high-level approach. The guessing game has the following structure: while you want to play a game: play a game ask play again? which in Python might look like this: playing = True while playing: play_one_game() playing = play_again() def play_again(): # For Python 3, change "raw_input" to "input". response = raw_input("Would you like to play again? y/n ") return response.strip().lower() == "y" This function accepts *only* Y or y to play another game. Later, after you've got the game working, you can come back to this and modify it so that it accepts Yes or just enter on it's own. Make it work as simply as possible first, then come back and make it more complicated later. Now do the same thing for playing one game. A single game in two player mode looks something like this: pick a target number start with one person as the guesser until the target is guessed: guess a number let the other person be the guesser which in Python might look like this: def play_one_game(): target = pick_target() # you need to write this function guessed = False player = "Player One" while not guessed: guess = guess_number(player) # you need to write this too if guess == target: guessed = True else: player = swap_player(player) # player one <=> player two # When we exit the loop, player is the person who guessed correctly. if player == "Player One": p1score += 1 else: p2score += 1 Best of all, you can change from two player mode to one player mode just by skipping the line "player = swap_player(player)". The rest of the code remains exactly the same, and you don't need to repeat everything. Have a play around with this approach, and then come back to us if you need more hints. -- Steven From bdesth.quelquechose at free.quelquepart.fr Mon Dec 22 13:36:14 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 22 Dec 2008 19:36:14 +0100 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> Message-ID: <494febd1$0$20851$426a74cc@news.free.fr> walterbyrd a ?crit : > On Dec 21, 12:28 pm, Bruno Desthuilliers > wrote: >> Strange enough, >> no one seems to complain about PHP or Ruby's performances... > > A few years back, there was a certain amount of chest thumping, when > python/django easily beat ror in a benchmark test. I don't remember it, and honestly, I just don't give a damn. > Now that ruby is > faster, "faster" than what ? Than Python ? or than it's previous version ? > I guess speed is no big issue. Please use your google-fu (if you have any). As far as I'm concerned, my position didn't change these 7+ past years: Python is (and has always been) fast enough for most of what I use it for (and when it isn't, neither PHP nor Ruby are going to be solution anyway). Now improvements are always welcomes, and if you compare 1.5.2 with 2.5.1, you'll find out that the core developpers did improve Python's perfs. Now do you have any serious argument, or are you just trolling ? > By the same reasoning, python advocates used to sneer at php because > php constantly broke backward compatibility. Now that python does it, > breaking backward compatibility is no big deal. There's a lot 1.5.2 days code still running *unmodified* on 2.6.x. You'll have hard time finding (non-trivial, and even then) PHP3 code running unmodified on PHP5. > I guess unicode > support was not that important, until python caught up to perl. > > I guess, the way it works is: you first assume that python is > superior, then you figure out why. Whoever said Python was "superior" (except your good friend 'r') ? As far as I'm concerned, I don't think Python is "superior" (OMG), I think it's a good language that happens to fit my brain *and* solve more than 80% of my programmer's needs. If you're not happy with Python's perfs, please contribute, you are welcome. From nmiyasato at gmail.com Sat Dec 20 19:26:25 2008 From: nmiyasato at gmail.com (miya) Date: Sat, 20 Dec 2008 16:26:25 -0800 (PST) Subject: best way to code References: Message-ID: <041d4bd9-c847-4130-8188-1817908f83dc@r24g2000vbp.googlegroups.com> On Dec 19, 2:35?pm, Peter Otten <__pete... at web.de> wrote: > eric wrote: > > hi, > > > I need to find a "good" design pattern to instanciate, and add > > specific code all in one. Let me explain it : > > > I need to define "some" code, better be in a class, something like > > > class LinkA(object): > > ? ? def mystuff(self): > > ? ? ? ? ? > > > class LinkB(object): > > ? ? def mystuff(self): > > ? ? ? ? ? > > > AND I need an instance of this class > > { "stuff A": LinkA() > > ? "stuff B": LinkB() > > } > > > This kind of code "would" be fine, I mean, the result effect in memory > > is fine for me. > > But I don't like the way I have to > > 1/ give a useless name to LinkA, linkB (there can be hundreds of names > > like that) > > 2/ I have to write it down two times (and that's one time too much) > > > any ideas ? > > > something like > > [ > > new object(): > > ? ? def mystuff(self): > > ? ? ? ? > > , > > new object(): > > ? ? def mystuff(self): > > ? ? ? ? > > ] > > > would be really perfect (but I know it does not work, or at least, I > > don't know how to make it work) > > > In fact, I would like to define a class, and an instance in a single > > statement > >>> class Register: > > ... ? ? def __init__(self): > ... ? ? ? ? ? ? self.items = [] > ... ? ? def __call__(self, method): > ... ? ? ? ? ? ? class Link(object): > ... ? ? ? ? ? ? ? ? ? ? mystuff = method > ... ? ? ? ? ? ? self.items.append(Link()) > ...>>> register = Register() > >>> @register > > ... def mystuff(self): print "first" > ...>>> @register > > ... def mystuff(self): print "second" > ...>>> for item in register.items: > > ... ? ? item.mystuff() > ... > first > second > > Peter Wow, loved this solution. Never thought about using decorators to solve this kinda problems. nice - Nicol?s Miyasato (miya) http://myPythonNotes.wordpress.com http://nmiyasato.blogspot.com From luismgz at gmail.com Mon Dec 15 08:15:30 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Mon, 15 Dec 2008 05:15:30 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> Message-ID: <355f1cfe-6abb-4d2c-8bf4-3aa62e713c1f@w34g2000yqm.googlegroups.com> On Dec 15, 1:38?am, cm_gui wrote: > hahaha, do you know how much money they are spending on hardware to > make > youtube.com fast??? > > > By the way... I know of a very slow Python site called YouTube.com. In > > fact, it is so slow that nobody ever uses it. > > Buddy, just stop whining and go with c++ if it makes you happy. By the way, what's the blazingly fast application you need to write so desperately? What kind of performance problem have you find in python that makes you so unhappy? What are you going to do with all the extra speed provided by c++ (a Hello World! ?)... From n.kottiyath at gmail.com Thu Dec 4 00:18:19 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Wed, 3 Dec 2008 21:18:19 -0800 (PST) Subject: Good introductory book? References: Message-ID: <56616d73-312c-44e5-a484-5fb3e0054613@x38g2000yqj.googlegroups.com> On Dec 3, 7:44?pm, "Ken D'Ambrosio" wrote: > Hi, all. ?I'm getting ready to do some projects in Python, and I've cut my > teeth a little bit, but I've found the "Learning|Programming Python" books > from O'Reilly to be more-or-less useless (to my surprise -- I'm usually an > O'Reilly fan). ?I really, really like "Python Essential Reference", but > it's -- well, more of a reference than an intro. ?So, an introductory text > that actually assumes some previous programming experience (as opposed to > "Learning Python" which must be the most slowly-paced programming book > ever) would be terrific. > > Thanks for your suggestions! > > -Ken Dive into python is a very good one. It is free too. http://diveintopython.org/ Try it out. If you want more of examples of how everything is done, then Python Cookbook is another one. You can get many recipes at http://code.activestate.com/recipes/langs/python/ too - the book is just selected recipes from this site. Regards K From pavlovevidence at gmail.com Thu Dec 4 16:08:46 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 4 Dec 2008 13:08:46 -0800 (PST) Subject: "as" keyword woes References: <777c7313-267f-4dc2-b6fd-fad0c9714f41@l42g2000yqe.googlegroups.com> Message-ID: On Dec 4, 2:42?pm, Albert Hopkins wrote: > It's been a while so I can't remember, but it seems like "yield" was > dropped in to python relatively quickly in 2.2. ?Was there a similar > outrage when "yield" became a keyword? This is just one guy complaining. Yes, I'd imagine when "yield" and "with" were made into keywords there was probably someone, somewhere who complained about that, too. I doubt there will much outrage over "as". It has been in the works for eight years and six releases, after all. Anyone who was paying attention wouldn't have been using "as" as an identifier. Among those who weren't paying attention, anyone smart wouldn't have been using "as" as an identifier because A) it is used as a syntactic element, and even if it's not a keyword it's poor style to use it also as an identifier, and B) you had to suspect sooner or later they would make it into a real keyword. Among those who were using "as" as an identifier, the vast majority will simply do an interactive search-and-replace to fix it. People like Warren here who have distributed codebases they can't easily fix up, and who were neither smart nor informed enough to avoid using "as", are a pretty tiny minority, I would guess. Carl Banks From pythonnutter at gmail.com Sat Dec 6 20:54:49 2008 From: pythonnutter at gmail.com (Python Nutter) Date: Sun, 7 Dec 2008 12:54:49 +1100 Subject: Learning Python now coming from Perl In-Reply-To: References: <014a96e0$0$20670$c3e8da3@news.astraweb.com> Message-ID: > In article <014a96e0$0$20670$c3e8da3 at news.astraweb.com>, > Steven D'Aprano wrote: > > Well, as an old-time unix hacker (who learned REs long before Perl > existed), my question to you would be, "Is there any problem which > *shouldn't* be solved with an RE?" :-) > > One of the reasons REs don't get used in Python as much as in Perl is > because strings have useful methods like startswith(), endswith(), and > split(), and also the "in" operator. These combine to give you easy ways > to do many things you might otherwise do with REs. I agree, I'm going through the new book Python for Unix and Linux Administration now and although in general I like what they say, they take you through the built in string functions and then introduce REs and end the chapter leaving the reader with the impression that REs are the better solution and I only agree with the case of the problem/program they presented. However I used the built ins more effectively using the indexes returned within the string and I've built plenty of scripts that did not need to move to REs to perform the text/file processing that I did. This intermediate use of string built-in functions was missing between the first string-function and RE versions of code and imho it is not letting the readers see that string-functions are even more powerful than the reader is lead to believe and that REs are pushed more towards edge cases than the impression the reader seems to be left with which is to use REs more. At least if you push REs inform the readers where to get the a RE GUI builder written in Python so they can build and *test* the complex and unwieldy REs to perform anything beyond the basic pattern searches. Cheers, PN From max at alcyone.com Mon Dec 29 01:56:27 2008 From: max at alcyone.com (Erik Max Francis) Date: Sun, 28 Dec 2008 22:56:27 -0800 Subject: why cannot assign to function call In-Reply-To: References: Message-ID: scsoce wrote: > I have a function return a reference, and want to assign to the > reference, simply like this: > >>def f(a) > return a > b = 0 > * f( b ) = 1* > but the last line will be refused as "can't assign to function call". > In my thought , the assignment is very nature, but why the interpreter > refused to do that ? Because, as in most languages, it's not even clear what you might mean by this syntax. It doesn't have any meaning; assignments are made to variables, not the results of function calls. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Only love is worth the risk -- Oleta Adams From tgrav at mac.com Mon Dec 22 12:59:37 2008 From: tgrav at mac.com (Tommy Grav) Date: Mon, 22 Dec 2008 12:59:37 -0500 Subject: Python's popularity In-Reply-To: References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: On Dec 22, 2008, at 12:48 PM, walterbyrd wrote: >> Now since Python *is not* the only language on it's block, we have to >> compete with our main nemesis(Ruby) for survival > > I think both python and ruby will "survive." I think python is also > competing with perl in the sysadmin space - although I see perl as > being much more popular there. Python is making great headway in the physical sciences. Especially in astronomy Python has become a real player as not only a tool for quick and dirty calculations, but more serious number crunching using the great numpy and scipy libraries. With Cython, I, think it will even start taking over some of the speed critical niche from C and Fortran. Cheers Tommy From roy at panix.com Mon Dec 8 23:08:04 2008 From: roy at panix.com (Roy Smith) Date: Mon, 8 Dec 2008 20:08:04 -0800 (PST) Subject: How to initialize a class variable once Message-ID: I've got a class with a class variable: class Foo: _map = {} How do I make sure this only gets initialized the *first* time the module containing the class is imported? What appears to be happening as it stands is each time the module gets imported, Foo._map get re- initialized. From clp at rebertia.com Mon Dec 8 03:57:44 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 8 Dec 2008 00:57:44 -0800 Subject: var or inout parm? In-Reply-To: <493cda2a$0$17080$426a34cc@news.free.fr> References: <493cda2a$0$17080$426a34cc@news.free.fr> Message-ID: <47c890dc0812080057r6d117bbcic377cb96de52d973@mail.gmail.com> On Mon, Dec 8, 2008 at 12:26 AM, Bruno Desthuilliers wrote: > Colin J. Williams a ?crit : >> >> mh at pixar.com wrote: >>> >>> How can I make a "var" parm, where the called function can modify >>> the value of the parameter in the caller? >>> >>> def f(x): >>> x = x + 1 >>> >>> n = 1 >>> f(n) >>> # n should now be 2 >>> >>> Many TIA!! >>> Mark >>> >>> >> >> Why not run it and see? >> >> Your function returns None. >> >> The function in effect takes a copy of n. > > Nope, it takes the object bound to global name 'n'. See Also: the earlier heated debate thread over what evaluation strategy Python uses (Survey says!: call-by-object). Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > -- > http://mail.python.org/mailman/listinfo/python-list > From benjamin.kaplan at case.edu Wed Dec 10 14:57:23 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 10 Dec 2008 14:57:23 -0500 Subject: "as" keyword woes In-Reply-To: References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> <493FD8F6.3050803@mrabarnett.plus.com> Message-ID: On Wed, Dec 10, 2008 at 12:22 PM, Patrick Mullen wrote: > On Wed, Dec 10, 2008 at 6:57 AM, MRAB wrote: > > Aaron Brady wrote: > >> > >> On Dec 9, 12:40 pm, MRAB wrote: > >>> > >>> Aaron Brady wrote: > >>>> > >>>> On Dec 9, 8:28 am, MRAB wrote: > >>>> snip > >>>>> > >>>>> In some languages (I think Delphi is one of them - it's been a > while!) > >>>>> some words which would normally be identifiers have a special meaning > >>>>> in > >>>>> certain contexts, but the syntax precludes any ambiguity, and not in > a > >>>>> difficult way. "as" in Python was one of those. > >>>>> I certainly wouldn't want something like PL/I, where "IF", "THEN" and > >>>>> "ELSE" could be identifiers, so you could have code like: > >>>>> IF IF = THEN THEN > >>>>> THEN = ELSE; > >>>>> ELSE > >>>>> ELSE = IF; > >>>>> Seehttp://en.wikipedia.org/wiki/PL/I_(programming_language) > . > >>>> > >>>> snip > >>>> That is, 'certainly' doesn't change the meaning of your statement > >>>> any. You wouldn't want it, but King George III didn't want the > >>>> American Revolution. > >>> > >>> It's called emphasis. > >> > >> I just take you to have meant, then, +1 on excluding keywords from > >> identifiers. You said it the long way though, so I thought I missed > >> something deeper, that didn't come across. > >> > > IIRC, most computer languages have an LL(1) grammar, which means that > when > > they are parsed you need to look at only the next word. If you're about > to > > parse a statement and the next word is "IF" then you know it's an > > IF-statement, if it's an identifier then it's either a call or an > assignment > > statement (OK, you don't know exactly what kind of statement it is at > that > > point, but it works out just fine!). > > > > In the example from PL/I, "IF" could be the start of an IF-statement "IF > > THEN" or an assignment statement "IF = ". It's a > bit > > more tricky for the parser as well as the programmer. > > > > Life is easier if words having special meanings are reserved. > > > > However, that doesn't mean that all special words /must/ be reserved > > (pragmatism beats purity). Sometimes the syntax makes it clear and > > unambiguous, so you can get away with not making it a reserved word. The > > word "as" in Python doesn't need to be reserved because the syntax > precludes > > ambiguity, but it's the only such word in the language, so it's just > tidier > > to make it reserved too. > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > I don't have a huge stake in this, but I wouldn't mind a change to > allow anything proceeding a "." or preceeding a "(" to not be > identified as a keyword. It is obvious to me a s a human reader that > something.if is quite a bit different than just a bare if. And as far > as parsing technology goes, isn't it supposed to go for the biggest > match first? I would not be for allowing bare keywords to be used in > the situations described above, but since we are so used to being able > to being able to have say, myclass.dir() or myclass.len() without them > overwriting the builtin functions, it makes sense to me to be able to > define a myclass.as() or myclass.with() without overwriting the > keywords. Though I know the semantics behind these two things are > very different, the rules I go through when reading the code are very > similar. The parser change might be a hassle, and it might not be > worth it at all of course, but from a conceptual point of view it is > simple. I mean, even now you can do class.__dict__["as"]. > so what happens here? if(some_condition()) : do_something(a) Yes, I know you don't need the parenthesis there in Python, but you still can use it. > I guess I'm -1 for full PL/1 craziness, but +1 for qualified keyword usage. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From n.kottiyath at gmail.com Sun Dec 21 13:27:57 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Sun, 21 Dec 2008 10:27:57 -0800 (PST) Subject: Twisted for non-networking applications Message-ID: <82e49b84-43c9-452f-a139-c77378c12908@a12g2000pro.googlegroups.com> Hi all, Is it a good idea to use Twisted inside my application, even though it has no networking part in it? Basically, my application needs lots of parallel processing - but I am rather averse to using threads - due to myraid issues it can cause. So, I was hoping to use a reactor pattern to avoid the threads. I am using twisted in another part of the application for networking, so I was hoping to use the same for the non-networking part for reusing the reactor pattern. If somebody can help me on this, it would be very helpful. Regards K From gagsl-py2 at yahoo.com.ar Wed Dec 10 07:46:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 10 Dec 2008 10:46:53 -0200 Subject: forcing future re-import from with an imported module References: <533670ae-6d9d-4b10-9156-e41b31b678c7@g17g2000prg.googlegroups.com> Message-ID: En Tue, 09 Dec 2008 23:27:10 -0200, _wolf escribi?: > how can i say, approximately, "re-import the present module when it is > imported the next time, don?t use the cache" in a simple way? i do not > want to "reload" the module, that doesn?t help. I'd say you're using modules the wrong way then. The code inside a module is executed *once*, and that's by design. If you want to execute something more than once, put that code inside a function, and call it as many times as you want. -- Gabriel Genellina From newsgroups at debain.org Sun Dec 28 14:29:35 2008 From: newsgroups at debain.org (Samuel) Date: Sun, 28 Dec 2008 19:29:35 +0000 (UTC) Subject: Apache/mod_python: Registering a request handler dynamically Message-ID: Hi, Is there a way to dynamically overwrite the request handler from within mod_python scripts? Something along those lines: --------------- from mod_python import apache def myhandler(request): request.content_type = 'text/plain' request.write('Hello world') apache.set_default_handler(myhandler) --------------- I specifically want to avoid changing the Apache directive, as this code is supposed to function in a place where the user has no permission to override the Apache directive. The reason is that I am trying to hide the difference between different environments (such as mod_python or CGI) from the developer, such that the following is possible: --------------- #!/usr/bin/python import os, os.path os.chdir(os.path.dirname(__file__)) from PleaseHideMyEnvironment import RequestHandler def index(request): request.write('Hello World') RequestHandler(index) --------------- So at the time at which RequestHandler() is created, I need a way to make sure that mod_python calls to the RequestHandler instead of the normal handler, whenever a new request is made. Any idea? -Samuel From lists at cheimes.de Mon Dec 22 06:18:27 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 22 Dec 2008 12:18:27 +0100 Subject: no sign() function ? In-Reply-To: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> Message-ID: Pierre-Alain Dorange schrieb: > I don't find any sign(x) function in the math library (return the sign > of the value). > I've read that math module is a wrapper to C math lib and that C math > lib has not sign(), so... Starting with Python 2.6 the math and cmath modules have a copysign function. > I've implement my own sign function of course (it's easy) but a standard > one in math would be better and could be faster. Sure? :) Are you aware that the IEEE 754 standard makes a difference between the floats +0.0 and -0.0? from math import atan2 def sign(x): if x > 0 or (x == 0 and atan2(x, -1.) > 0.): return 1 else: return -1 From xahlee at gmail.com Wed Dec 3 19:32:57 2008 From: xahlee at gmail.com (Xah Lee) Date: Wed, 3 Dec 2008 16:32:57 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: On Dec 3, 4:22?pm, "Thomas M. Hermann" wrote: > On Dec 3, 5:26?pm, Xah Lee wrote: > > > > > Agreed. My paypal address is ?xah @@@ xahlee.org?. (replace the triple > > @ to single one.) Once you paid thru paypal, you can post receit here > > if you want to, or i'll surely acknowledge it here. > > > Here's what i will do: > > > I will give a version of Mathematica code that has the same behavior > > as his. And i will give timing result. The code will run in > > Mathematica version 4. (sorry, but that's what i have) As i > > understand, Jon is running Mathematica 6. However, i don't see > > anything that'd require Mathematica 6. If my code is not faster or in > > other ways not satisfactory (by your judgement), or it turns out > > Mathematica 6 is necessary, or any problem that might occure, i offer > > money back guarantee. > > > ? Xah > > ?http://xahlee.org/ > > > ? > > Alright, I've sent $20. The only reason I would request a refund is if > you don't do anything. As long as you improve the code as you've > described and post the results, I'll be satisfied. If the improvements > you've described don't result in better performance, that's OK. > > Good luck, > > Tom Got the payment. Thanks. I'll reply back with code tonight or tomorrow. Wee! Xah ? http://xahlee.org/ ? From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 20:54:35 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2008 01:54:35 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <015c47ad$0$20656$c3e8da3@news.astraweb.com> On Fri, 19 Dec 2008 10:25:30 -0700, Michael Torrie wrote: > So funny that now that Python 3.0 is actually released we have people > acting all surprised like they've never seen any of the new features in > Python 3.0 coming. However these features have been discussed for > years! And debated! Debated by who? The entire Python-using community? Every single Python programmer? Or just the small proportion of Python developers who are also core developers? Are you *really* surprised that some people had never heard of the changes being debated until it was too late? > Personally the new string formatter is sorely needed in Python. And > they way it has been implemented is a thing of beauty. Basically the > burden of formatting strings has been moved from the print > statement/function to the objects themselves. That's clearly not true. The print statement was not involved in formatting strings in the past. From Python 2.5: >>> s = "%s and %s" % ("spam", "eggs") >>> list(s) ['s', 'p', 'a', 'm', ' ', 'a', 'n', 'd', ' ', 'e', 'g', 'g', 's'] No print required until well after the string substitution was completed. > Furthermore, the new {} > notation allows many, many more options for formatting to be used. Want > to display a floating point number with $#.## notation, and ($#.##) for > negative? It's all now possible. Couldn't be done before. Of course it could be. You just needed to write your own formatting engine. What you mean is that it couldn't be done with % formatting and nothing else. > In short, this is a huge improvement, and backwards compatibility is > preserved for the 2.x style for those that wish it. There clearly is a need for a more heavyweight formatting solution than % and string.Template. There are things that can't be done easily with % alone, and format() will make them much simpler. I have no objection to the addition of the format() method (although I wonder whether it might have been better as a function). -- Steven From ianare at gmail.com Tue Dec 16 12:01:17 2008 From: ianare at gmail.com (=?ISO-8859-1?B?aWFuYXLp?=) Date: Tue, 16 Dec 2008 09:01:17 -0800 (PST) Subject: ethical questions about global variables References: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> Message-ID: <148d911b-5c43-48a1-baea-5a46c04cacfd@o4g2000pra.googlegroups.com> For anything more complicated than a simple script, I find it easier to use some sort of config object. This could be a simple dictionnary type class, where the values can be set/retrieved by the other classes directly, or a more elaborate class including functions to set/ retrieve the variables. This way setting/retrieving can be 'smart' -- possibly looking at other variables, program states, thread count, whatever, for the requested config option. It also allows for a lot of expansion down the line if need be, rather than dealing with all sorts of global variables floating around - which gets annoying pretty quickly. On Dec 15, 9:45?pm, "Giampaolo Rodola'" wrote: > Hi, > in a module of mine (ftpserver.py) I'd want to add a (boolean) global > variable named "use_gmt_times" to decide whether the server has to > return times in GMT or localtime but I'm not sure if it is a good idea > because of the "ethical" doubts I'm gonna write below. > > In first place I've never liked global variables too much and always > preferred per-class-instance variables instead. > The problem in my case is that I have to use such variable in two > separated classes: FTPHandler and VirtualFileSystem. Also, I want that > for no reason one class uses times in GMT and the other one local > times. > > Another doubt is the naming convention. PEP-8 states that global > variables should use the lower_case_naming_convention but I've seen a > lot of library module using the UPPER_CASE_NAMING_CONVENTION. What am > I supposed to do about it? > > Thanks in advance for any comment. > > --- Giampaolohttp://code.google.com/p/pyftpdlib/ From kay.schluehr at gmx.net Wed Dec 3 14:04:44 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Wed, 3 Dec 2008 11:04:44 -0800 (PST) Subject: Debugging a Python Program that Hangs References: Message-ID: On 2 Dez., 17:19, Kevin D. Smith wrote: > I have a fairly large python program that, when a certain combination > of options is used, hangs. ?I have no idea where it is hanging, so > simply putting in print statements to locate the spot would be quite > difficult. ?Unfortunately, ctrl-C'ing the program doesn't print a > traceback either. ?Looking through the python debugger documentation, I > don't see how to run a python program and interactively stopping it > while it is running. ?Is there a way to stop within a running python > program to see where it is getting hung up? > > -- > Kevin D. Smith You might approximate the critical location using exceptions instead of prints. That's more costly of course because the program has to be restarted more often but it will serve the same purpose. From yohell at ifm.liu.se Mon Dec 15 16:50:45 2008 From: yohell at ifm.liu.se (Joel Hedlund) Date: Mon, 15 Dec 2008 22:50:45 +0100 Subject: weird dict problem, how can this even happen? Message-ID: I'm having a very hard time explaining why this snippet *sometimes* raises KeyError: snippet: > print type(self.pool) > for frag in self.pool.keys(): > if frag is fragment_info: > print "the fragment_info *is* in the pool", hash(frag), hash(fragment_info), hash(frag) == hash(fragment_info), frag == fragment_info, frag in self.pool, frag in self.pool.keys() > try: > renderer_index = self.pool.pop(fragment_info) > except KeyError: > print "Glorious KeyError!" > for frag in self.pool.keys(): > if frag is fragment_info: > print "the fragment_info *is* in the pool", hash(frag), hash(fragment_info), hash(frag) == hash(fragment_info), frag == fragment_info, frag in self.pool, frag in self.pool.keys() > raise output: > > the fragment_info *is* in the pool 987212075 987212075 True True False True > Glorious KeyError! > the fragment_info *is* in the pool 987212075 987212075 True True False True > Traceback (most recent call last): > File "/home/yohell/workspace/missy/core/gui.py", line 92, in process_job > renderer_index = self.pool.pop(fragment_info) > KeyError: This snippet is part of a much larger gtk program, and the problem only from time to time, predominantly when the cpu is under heavy load and this method gets called a lot. If I didn't know better I'd say it's a bug in python's dict implementation, but I do know better, so I know it's far more likely that I've made a mistake somewhere. I'll be damned if I can figure out what and where though. I've reproduced this bug (?) with python-2.5.2 on Ubuntu 8.10 and python-2.5.1 on WinXP. I would very much like an explanation to this that does not involve threads, because I haven't made any that I'm aware of. I can't even understand how this could happen. How do I even debug this? Please help, I feel like I've taken crazy pills here! /Joel Hedlund From gruszczy at gmail.com Mon Dec 1 09:21:54 2008 From: gruszczy at gmail.com (=?UTF-8?Q?Filip_Gruszczy=C5=84ski?=) Date: Mon, 1 Dec 2008 15:21:54 +0100 Subject: Do more imported objects affect performance In-Reply-To: References: Message-ID: <1be78d220812010621u51dead9dnbaa0b4c8c9414362@mail.gmail.com> I see. Thanks for a really good explanation, I like to know, how to do things in the proper way :) 2008/12/1 Nick Craig-Wood : > Rafe wrote: >> On Dec 1, 7:26?am, "Filip Gruszczy?ski" wrote: >> > I have following question: if I use >> > >> > from module import * >> > >> > instead >> > >> > from module import Class >> > >> > am I affecting performance of my program? I believe, that all those >> > names must be stored somewhere, when they are imported and then >> > browsed when one of them is called. So am I putting a lot of "garbage" >> > to this storage and make those searches longer? >> >> Why use it if you don't need it? Your post implies a choice and the >> '*' import can really make things muddy if it isn't actually necessary >> (rare). Why not just import the module and use what you need? It is >> way easier to read/debug and maintains the name-space. > > Importing the module is actualy slower... If you import the name into > your namespace then there is only one lookup to do. If you import the > module there are two. > > $ python -m timeit -s 'from timeit import Timer' 'Timer' > 10000000 loops, best of 3: 0.0784 usec per loop > > $ python -m timeit -s 'import timeit' 'timeit.Timer' > 1000000 loops, best of 3: 0.243 usec per loop > > I'm not suggestion you should ever use "from module import *" only > ever import the things you actually need, eg > "from module import MyClass, my_function" > > And here is the test again, actually calling something with the same > difference in execution speed :- > > $ python -m timeit -s 'from os import nice' 'nice(0)' > 1000000 loops, best of 3: 1.21 usec per loop > > $ python -m timeit -s 'import os' 'os.nice(0)' > 1000000 loops, best of 3: 1.48 usec per loop > > -- > Nick Craig-Wood -- http://www.craig-wood.com/nick > -- > http://mail.python.org/mailman/listinfo/python-list > -- Filip Gruszczy?ski From jonas.esp at googlemail.com Mon Dec 1 15:10:11 2008 From: jonas.esp at googlemail.com (Kless) Date: Mon, 1 Dec 2008 12:10:11 -0800 (PST) Subject: Chmod to a group only References: Message-ID: <83e430f3-0c4c-4aae-84e3-7a8bb6dc1b74@t11g2000yqg.googlegroups.com> On 1 dic, 18:17, Kless wrote: > How to chmod a file to: o-rwx ? (to change only the others mode) > > os.chmod(fname, ) > > I was reading this [1], but the truth is that anything as 'S_IRUSR' > doesn't help enought. > > [1]http://www.python.org/doc/2.5.2/lib/os-file-dir.html I have tried: mode = os.stat(fname).st_mode os.chmod(fname, mode | stat.S_IRWXO) => Changes to o+rwx and if is used: os.chmod(fname, mode & stat.S_IRWXO) => Delete all modes Any help? please From johnroth1 at gmail.com Sat Dec 6 09:49:08 2008 From: johnroth1 at gmail.com (John Roth) Date: Sat, 6 Dec 2008 06:49:08 -0800 (PST) Subject: Guido's new method definition idea References: Message-ID: <36e2dafd-f4ba-4348-8080-8d6786043653@n41g2000yqh.googlegroups.com> On Dec 5, 7:21?pm, "Daniel Fetchinson" wrote: > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... > > The proposal is to allow this: > > class C: > ? ? def self.method( arg ): > ? ? ? ? self.value = arg > ? ? ? ? return self.value > > instead of this: > > class C: > ? ? def method( self, arg ): > ? ? ? ? self.value = arg > ? ? ? ? return self.value > > I.e. explicit self stays only the syntax is slightly different and may > seem attractive to some. As pointed out by Guido classmethods would > work similarly: > > class C: > ? ? @classmethod > ? ? def cls.method( arg ): > ? ? ? ? cls.val = arg > ? ? ? ? return cls.val > > The fact that Guido says, > > "Now, I'm not saying that I like this better than the status quo. But > I like it a lot better than [...] but it has the great advantage that > it is backward compatible, and can be evolved into a PEP with a > reference implementation without too much effort." > > shows that the proposal is viable. > > I'd like this new way of defining methods, what do you guys think? > Anyone ready for writing a PEP? > > Cheers, > Daniel > > -- > Psss, psss, put it down! -http://www.cafepress.com/putitdown Sigh. If you make --both-- self and cls keywords, then 90% of the problems that Guido mentions in the blogspot post just vanish because whether it's an instance method, a class method or a static method can be inferred from the method body. In particular, the decorator problem goes away (the decorators are irrelevant, and can be ignored) and so does the problem with injecting a method into an object. It is, of course, harder to implement, and it would not be backwards compatible because all the internal wrappers vanish as well. That makes problems for anyone who is looking through __dict__ to find particular kinds of method. John Roth From google at mrabarnett.plus.com Sat Dec 20 18:47:53 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 20 Dec 2008 23:47:53 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> Message-ID: <494D8429.8050508@mrabarnett.plus.com> walterbyrd wrote: > On Dec 19, 12:43 pm, excord80 wrote: > >> Also, I like having only *one* special symbol (`%') to worry >> about in my strings instead of two (`{' and `}'). >> > > Actually the new way has, at least three special symbols: ( '{', '}' , > '.') as well as the method name "format" so > > "%s=%s" % (k, v) for k, v in params.items() > > becomes: > > "{0}={1}".format((k, v) for k, v in params.items()) > > or something like that. > "{0}={1}".format(k, v) for k, v in params.items() or: "{0}={1}".format(*i) for i in params.items() From p.f.moore at gmail.com Thu Dec 11 17:12:11 2008 From: p.f.moore at gmail.com (Paul Moore) Date: Thu, 11 Dec 2008 14:12:11 -0800 (PST) Subject: Best way of debigging a C extension References: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> Message-ID: <6b20568d-8ce9-4240-8f83-b579c241d9a9@l33g2000pri.googlegroups.com> On 11 Dec, 21:57, Christian Heimes wrote: > You have to build Python on your own to get debug builds. Only debug > builds allow to do extension debugging like memory leak finding. The trouble is, I only have mingw to build extensions, not MSVC7.1 - so I can't build Python (and I don't know if I still have the toolkit compiler to build with that - I certainly don't have all the pieces installed). With Python 2.6, I guess things will be better as I have VS2008 Express, so I can use this to build a debug Python plus my extension. It's more work than I really want to do to go that way, but I guess it'll work. > You are working against the system ;) > On Windows all extensions and shared libraries of a debug build have a > _d suffix. That's what I thought. I was just hoping that using a debug build of an extension would be usable with a standard release build of Python, as that's what will be easy for most people to set up. Ah, well, I'll stick to printf, combined with hacking a debug build to work with a release Python. It's ugly and unreliable, maybe, but good enough. Maybe sometime (probably not until I'm targeting 2.6 only) I'll set up my own debug build of Python, in a virtual machine somewhere. Thanks for the explanation. Paul. From skip.montanaro at gmail.com Tue Dec 9 21:06:14 2008 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Tue, 9 Dec 2008 18:06:14 -0800 (PST) Subject: Test posting #2 - please ignore References: Message-ID: On Dec 9, 3:40?pm, Skip Montanaro wrote: > This is another posting you can ignore. ?This time posted > via Google Groups. Test #3. Still fiddling around... Skip From darcy at druid.net Tue Dec 23 09:25:04 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 23 Dec 2008 09:25:04 -0500 Subject: iterating initalizations In-Reply-To: References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> Message-ID: <20081223092504.aaf25192.darcy@druid.net> On Mon, 22 Dec 2008 22:32:17 -0500 Aaron Stepp wrote: > Instead of writing a long list of initializations like so: > > A = [ ] > B = [ ] > ... > Y = [ ] > Z = [ ] > > I'd like to save space by more elegantly turning this into a loop. If Well, if all you want is a loop: for v in vars: locals()[v] = [] It's hard to tell if that's what you actually need though without deeper analysis of your requirements. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From martin at v.loewis.de Sun Dec 14 16:54:01 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 14 Dec 2008 22:54:01 +0100 Subject: Building from source -- zlib/binascii problems 2.5.2/2.6.1 In-Reply-To: <71531b64-535f-49d0-a0c6-7704df83b251@f18g2000vbf.googlegroups.com> References: <71531b64-535f-49d0-a0c6-7704df83b251@f18g2000vbf.googlegroups.com> Message-ID: <49458079.1000304@v.loewis.de> > Target: x86_64-redhat-linux > gcc -pthread -shared build/temp.linux-x86_64-2.5/location/of/ > Python-2.5.2/Modules/zlibmodule.o -L/usr/local/lib -lz -o build/ > lib.linux-x86_64-2.5/zlib.so > /usr/bin/ld: skipping incompatible /usr/lib/libz.so when searching for > -lz Do file /usr/lib/libz.so It might be a 32-bit library, in which case you can check whether /usr/lib64 has a 64-bit library. I'm puzzled why it only happens for -lz; perhaps you are better of compiling with a 32-bit compiler. Regards, Martin From adi at lspl.net Mon Dec 8 13:06:28 2008 From: adi at lspl.net (sniffer) Date: Mon, 8 Dec 2008 10:06:28 -0800 (PST) Subject: dBase III files and Visual Foxpro 6 files References: <917126a8-c2c6-49c5-b001-07c953992dac@q26g2000prq.googlegroups.com> Message-ID: <7d5b9758-e16e-4774-bee7-aac74e207bb9@q30g2000prq.googlegroups.com> On Dec 8, 7:44?pm, Ethan Furman wrote: > sniffer wrote: > > On Dec 8, 12:53 pm, Ethan Furman wrote: > >> Greetings All! > > >> I nearly have support complete for dBase III dbf/dbt files -- just > >> wrapping up support for dates. ?The null value has been a hindrance for > >> awhile but I nearly have that solved as well. > > >> For any who know of a cool dbf module already in existence for dBase III > >> and Visual Foxpro -- where were you six months ago when I was searching? > >> ? ;) ?Seriously, though, this has been a great learning experience for me. > > >> As I said -- dbf/dbt files are 99% ready. ?idx files -- no support: ?for > >> my purposes I just don't need them. ?I've found no problem in loading > >> tables up to 300,000 records with 50 fields per record, and re-ordering > >> them on the fly in memory. > > >> However, after putting much effort into this code, and wanting it to be > >> useful to others in the community, are there others who work with dbf > >> files that would need idx/cdx support? ?Or tables so large they won't > >> fit comfortably into memory? > > >> ~ethan~ > > > hi ethan, > > great to hear that someone has finally written something for > > interacting with vfp6 data,when do you plan to release it > > Well, let's see... > > A couple more days to have the datetime bit worked out (I don't support > datetimes prior to 1981 in vfp tables), > longer for currency types, and of course, no idx/cdx support at this point. > > Tell you what -- ?I'll trade you a copy of the code as it stands with > date and datetime working for null values, for an answer of whether you > need idx/cdx file support. ?;) > > ~ethan~ well ethan luckily i dont require idx/cdx support From simon at brunningonline.net Thu Dec 18 08:28:54 2008 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 18 Dec 2008 13:28:54 +0000 Subject: [Help] The pywinauto Can't select the MDI's menu using the MenuItems() which return []. In-Reply-To: References: Message-ID: <8c7f10c60812180528k2f755d6aj1564a19efb813db0@mail.gmail.com> 2008/12/18 ???? : > This problem also use the following discription: > How to use pywinauto to open WORD and select its Menu. > I can't do that and have no idea why! > Looking forward your help,Thanks! Word can be automated with COM. My golden rule is that automation via GUI driving is always a last resort. -- Cheers, Simon B. simon at brunningonline.net From philip at semanchuk.com Wed Dec 10 17:25:13 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Wed, 10 Dec 2008 17:25:13 -0500 Subject: When (and why) to use del? In-Reply-To: References: <1228840517.4109.10.camel@brotherus.rdu.redhat.com> Message-ID: <4F7C906E-807A-473A-A3C8-F659D79A11BD@semanchuk.com> On Dec 10, 2008, at 5:23 PM, Gabriel Genellina wrote: > En Tue, 09 Dec 2008 15:29:17 -0200, Philip Semanchuk > escribi?: >> On Dec 9, 2008, at 11:35 AM, Albert Hopkins wrote: >> >>> def myfunction(): >>> # do some stuff stuff >>> my_string = function_that_returns_string() >>> # do some stuff with my_string >>> del my_string >>> # do some other stuff >>> return >>> >>> I think this looks ugly, but also does it not hurt performance by >>> preempting the gc? My feeling is that this is a misuse of 'del'. >>> Am I >>> wrong? Is there any advantage of doing the above? >> >> The code above doesn't pre-empt the GC, it just provides it with a >> useful hint. When you del a variable you just tell the GC, "I'm >> done with this, so you might be able to get rid of it next time you >> collect garbage". If the variable wasn't explicitly del-ed, you'd >> still hold a reference and the GC would be unable to collect it >> while the section "do some other stuff" runs. > > Note that CPython has a garbage collector AND uses reference counts. > Objects are deallocated *immediately* as soon as their reference > count reaches zero. The GC is used only to detect and dispose of > reference cycles. > So, if you `del` a name and it happens to be the last reference to > certain object, the object is immediately destroyed; the GC isn't > involved at all. Thanks for the clarification -- I didn't know that. From pavlovevidence at gmail.com Thu Dec 4 15:32:08 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 4 Dec 2008 12:32:08 -0800 (PST) Subject: "as" keyword woes References: Message-ID: <777c7313-267f-4dc2-b6fd-fad0c9714f41@l42g2000yqe.googlegroups.com> On Dec 4, 3:44?am, James Stroud wrote: > You probably aren't a developer for the cPython implementation, but, if > you were, I'd recommend taking rants like Warren's to heart because they > are born of honest frustration and practical concern. Hopefully > developers for python 2.7 are listening and won't break backward > compatibility just because the "Zen of Python" suggests it might be a > good idea. I think they should. Python didn't get to where it is by being bogged down with obsolesence. It has grown and grown in popularity in spite of (and, I would say, in part because of) a history of backward- incompatible changes with every major release. It's not like Python has ignored the users; it's been very careful and considerate when making backwards-incompatible change. This change was planned for eight freaking years. Carl Banks From robert.kern at gmail.com Tue Dec 2 16:11:15 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 02 Dec 2008 15:11:15 -0600 Subject: optimization In-Reply-To: References: Message-ID: Neal Becker wrote: > Robert Kern wrote: > >> Neal Becker wrote: >>> Arnaud Delobelle wrote: >>> >>>> Neal Becker writes: >>>> >>>>> I noticed in some profiling, that it seems that: >>>>> >>>>> def Func (): >>>>> def something(): >>>>> ... >>>>> >>>>> It appears that if Func is called many times, this nested func >>>>> definition will cause significant overhead. Is this true? I guess >>>>> I've become accustomed to decent compilers performing reasonable >>>>> transformations and so have tended to write code for clarity. >>>> If something() can be defined outside Func(), how is it clearer to >>>> define it inside? >>> If it's only used inside. >> I, for one, find that significantly less clear. I only expect functions to >> be defined inside of functions if they are going to use lexical scoping >> for some reason. If I read your code, I'd probably waste a good five >> minutes trying to figure out what part of the local scope you were using >> before I would conclude that you just did it because you thought it looked >> better. > > I'm using the inner function to prevent pollution of the global namespace. Local variables also have this attribute. Code is easier to understand when it is written with the greatest locality - so you can see immediately that the inner function isn't used somewhere else. I don't think that the greatest locality metric is the only factor in understandability. You're introducing more nesting, which means more context switching as I read the code. I like shortish functions with one coherent idea per function. I like to see the argument spec, the docstring, and the body of the code all on one page. If the functions it calls are reasonably well-named, or their calls are commented, I can read that function all the way through without having to page around. By nesting the definitions of the functions inside, I have to skip from the argument spec and docstring down to the body. And I'm still going to spend time trying to figure out what lexical scoping you are using before giving up. I still think that defining a function inside of a function for organizational purposes is a (mild) abuse of the feature. Packages, modules, __all__, and the _underscoring conventions are the language features for organizing namespaces of functions. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From metolone+gmane at gmail.com Mon Dec 29 04:06:18 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Mon, 29 Dec 2008 01:06:18 -0800 Subject: How to display Chinese in a list retrieved from database via python References: <22be506d-91c2-4727-ace7-2e3382b6d214@g3g2000pre.googlegroups.com><979fdf6d-0500-47ba-87fd-0f0361ca3059@p2g2000prf.googlegroups.com><19680ed2-c78f-4ab9-8ca0-8ce26fd5b6a7@o4g2000pra.googlegroups.com> <2560a6e0-c103-46d2-aa5a-8604de4d1968@b38g2000prf.googlegroups.com> Message-ID: "zxo102" wrote in message news:2560a6e0-c103-46d2-aa5a-8604de4d1968 at b38g2000prf.googlegroups.com... > I have a list in a dictionary and want to insert it into the html > file. I test it with following scripts of CASE 1, CASE 2 and CASE 3. I > can see "??" in CASE 1 but that is not what I want. CASE 2 does not > show me correct things. > So, in CASE 3, I hacked the script of CASE 2 with a function: > conv_list2str() to 'convert' the list into a string. CASE 3 can show > me "??". I don't know what is wrong with CASE 2 and what is right with > CASE 3. > > Without knowing why, I have just hard coded my python application > following CASE 3 for displaying Chinese characters from a list in a > dictionary in my web application. > > Any ideas? > See below each case...????? > Happy a New Year: 2009 > > ouyang > > > > CASE 1: > ######################################################## > f=open('test.html','wt') > f.write(''' > > test > > > ''') > f.close() In CASE 1, the *4 bytes* D6 D0 CE C4 are written to the file, which is the correct gb2312 encoding for ??. > CASE 2: > ####################################################### > mydict = {} > mydict['JUNK'] = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce > \xc4'] > f_str = ''' > > test > > > ''' > > f_str = f_str%mydict > f=open('test02.html','wt') > f.write(f_str) > f.close() In CASE 2, the *16 characters* "\xd6\xd0\xce\xc4" are written to the file, which is NOT the correct gb2312 encoding for ??, and will be interpreted however javascript pleases. This is because the str() representation of mydict['JUNK'] in Python 2.x is the characters "['\xd6\xd0\xce\xc4', '\xd6\xd0\xce\xc4', '\xd6\xd0\xce\xc4']". > CASE 3: > ################################################### > mydict = {} > mydict['JUNK'] = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce > \xc4'] > > f_str = ''' > > test > > > ''' > > import string > > def conv_list2str(value): > list_len = len(value) > list_str = "[" > for ii in range(list_len): > list_str += '"'+string.strip(str(value[ii])) + '"' > if ii != list_len-1: > list_str += "," > list_str += "]" > return list_str > > mydict['JUNK'] = conv_list2str(mydict['JUNK']) > > f_str = f_str%mydict > f=open('test03.html','wt') > f.write(f_str) > f.close() CASE 3 works because you build your own, correct, gb2312 representation of mydict['JUNK'] (value[ii] above is the correct 4-byte sequence for ??). That said, learn to use Unicode strings by trying the following program, but set the first line to the encoding *your editor* saves files in. You can use the actual Chinese characters instead of escape codes this way. The encoding used for the source code and the encoding used for the html file don't have to match, but the charset declared in the file and the encoding used to write the file *do* have to match. # coding: utf8 import codecs mydict = {} mydict['JUNK'] = [u'??',u'??',u'??'] def conv_list2str(value): return u'["' + u'","'.join(s for s in value) + u'"]' f_str = u''' test ''' s = conv_list2str(mydict['JUNK']) f=codecs.open('test04.html','wt',encoding='gb2312') f.write(f_str % s) f.close() -Mark P.S. Python 3.0 makes this easier for what you want to do, because the representation of a dictionary changes. You'll be able to skip the conv_list2str() function and all strings are Unicode by default. From mr.spoon21 at gmail.com Thu Dec 18 05:34:42 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Thu, 18 Dec 2008 11:34:42 +0100 Subject: OT: Binary tree logarithms properties In-Reply-To: References: <8f67b6f80812170914m377191f4g81345ffe5d0b7f26@mail.gmail.com> Message-ID: <8f67b6f80812180234u103b31e2kcde80c2cd7f250e3@mail.gmail.com> 2008/12/17 Terry Reedy : > Nodes only have single number indexes if you arrange them linearly. Then the > index depends on how you arrange them, whether you start the array indexes > with 0 or 1, and whether you start the level numbers with 0 or 1. Call the > breadth-first sequence bf. Then the 1-based slice for 1-first level k is > bf[2**(k-1):2**k)]. Again, proof by induction. Yes, I was referring to the heap numeration. Anyway, Francesco Guerrieri answered me in a private message and explained me the formula. But actually I was searching for other similar properties. From grahn+nntp at snipabacken.se Fri Dec 5 07:10:52 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 5 Dec 2008 12:10:52 GMT Subject: Python surpasses Perl in popularity? References: <5e87aee0-c7fd-4e9d-befb-0cc01cee64ec@f40g2000pri.googlegroups.com> <49316c95$0$2813$742ec2ed@news.sonic.net> Message-ID: ["Followup-To:" header set to comp.unix.shell.] On 29 Nov 2008 16:23:49 GMT, Tam Ha wrote: > Jorgen Grahn wrote: >>(I could get away with using Bash in these cases. It has functions, >>local variables and so on. Writing portable Bourne shell is not as >>much fun.) > > Can you explain this? Sorry for the late answer. No, it's actually what I said: I could get away with using bash in these cases, so I did it. It was an in-house application, it had already unknown dependencies to bash, and to Linux versions of other utilities. If I had asked for time to modify it to make sure it was portable Bourne shell, people would have laughed at me. > Bourne is always more portable than Bash. > That's why you'll find experienced shell programmers writing everything > that doesn't absolutely require a bash feature in /bin/sh. Boot scripts, > install scripts, etc. should never be written in bash and if where you > find one using bash you can be sure a Linux-only newbie has written it. Sure, nothing controversial about that. I don't argue that people should use bash features in any random script they write. I just noted that if you decide to use it, it's a pretty useful language. Probably more useful than Python in my case, where most of the work was about starting and managing external commands and pipelines. > For one there are too many versions of bash, for two it is not installed > by default on every Unix/Linux OS, for three it has poor backwards > (and forwards) compatibility. Worse compatibility than Perl or Python? The Bourne shell timescale is probably impressive, but often you aren't interested in decades. > It is also found at different places on > the path. Surely that applies to almost any interpreter, like perl and python. It's a problem (on the non-free Unixes at least) but if you let it be the deciding factor, you could use no scripting language except /bin/sh and awk. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From phd at phd.pp.ru Mon Dec 8 12:09:21 2008 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 8 Dec 2008 20:09:21 +0300 Subject: SQLObject 0.10.4 Message-ID: <20081208170921.GK7441@phd.pp.ru> Hello! I'm pleased to announce version 0.10.4, a minor bugfix release of 0.10 branch of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.10.4 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.10.3 ----------------- * Fixed createSQL constrains generation under MySQL when the table's name includes the database's name (contains a dot). For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From ndbecker2 at gmail.com Thu Dec 18 09:09:05 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 18 Dec 2008 09:09:05 -0500 Subject: confused about __str__ vs. __repr__ Message-ID: Reading some FAQ, I see that __str__ is "meant for human eyes". But it seems that: class X(object): def __str__(self): return "str" def __repr__(self): return "repr" x = X() d = {0 : x} print d {0: repr} So if __str__ is "meant for human eyes", then why isn't print using it! From rt8396 at gmail.com Mon Dec 22 17:47:52 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 14:47:52 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <6ra8t0F925rU1@mid.individual.net> <29feda0d-6432-4cb9-8809-e4d4a7798601@e1g2000pra.googlegroups.com> <6raeb8F9s47U2@mid.individual.net> <6rahpaFav7kU2@mid.individual.net> Message-ID: <97e49a8c-6730-42f2-b4d0-35eaff38b69f@y1g2000pra.googlegroups.com> On Dec 22, 4:14?pm, je.s.t... at hehxduhmp.org wrote: > r wrote: > > Would you trust my words more if i used a name like "Thurstan Howell > > III".... Come on, don't tell me you are that shallow. To attack my > > credibility solely based on my user name is the sport of small minded > > people. Surely you can bring more thought, and intelligence to this > > thread than that?... > > I'm just saying that there's absolutely no more credibility attached > to some random & anonymous account than there is to someone due to > not having X-No-Archive. ?You are no more accountable for your words than > I am. ?So you might be throwing stones at my use of X-No-Archive, but > you are living in a glass house. > > And for the record, the obfuscation of my email address and the use of > X-No-Archive has a lot more to do with random people being able to > track me via the internet than it does with believing/not believing what > I'm saying. ?If one wanted to put in some small bit of effort, it isn't > particularly difficult to track down usenet posts authored by me from > 15ish years ago, but I raise the bar so that any random joker probably won't > bother (and making the reverse mapping - knowing my real identity and then > looking for recent net activity - is much more difficult to do). An exercise in thought... To go a bit further, what if we could post a picture of ourselves on the Usenet?? What would stop me from posting a picture of someone else besides myself? NOTHING! Do not put your trust in such weak beliefs. My name and picture mean squat on a this medium. If you want to validate my intelligence, use my words, not shallow assumptions. Your logic is like that fruitcake my auntie makes every Christmas. Please put more thought into you post. My words are here and they will stay here, sure some may disagree with my thoughts, but i will not be ashamed of them! Thats called having "brass Cohones" mi hijo. From dickinsm at gmail.com Mon Dec 8 05:46:12 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 8 Dec 2008 02:46:12 -0800 (PST) Subject: built-in functions as class attributes Message-ID: <75fdbf34-34d9-4373-bbe0-7e3f76dc4c3f@x38g2000yqj.googlegroups.com> Here's a curiosity: after def my_hex(x): return hex(x) one might expect hex and my_hex to be interchangeable in most situations. But (with both Python 2.x and 3.x) I get: >>> def my_hex(x): return hex(x) ... >>> class T(object): f = hex ... >>> class T2(object): f = my_hex ... >>> T().f(12345) '0x3039' >>> T2().f(12345) Traceback (most recent call last): File "", line 1, in TypeError: my_hex() takes exactly 1 argument (2 given) [36412 refs] Anyone know what the precise rules that lead to this behaviour are, or where they're documented? Surprised'ly yours, Mark From Astley.lejasper at gmail.com Tue Dec 2 14:05:21 2008 From: Astley.lejasper at gmail.com (Astley Le Jasper) Date: Tue, 2 Dec 2008 11:05:21 -0800 (PST) Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> Message-ID: <24f0dc02-9461-4b93-a2f8-a56fa5919ffc@n10g2000yqm.googlegroups.com> James ... thanks for the suggestion. I have done this and the error logging usually catches all my errors and logs them. I wondered if logging itself was failing! Philip ... thanks also. I did wonder about making the everything explicit. I've seen that mentioned elsewhere. Writing out the stdout & stderr to another file is a great idea. I'll have ago. But I think our dinner guests are starting to make comments so I'd better go! From bdesth.quelquechose at free.quelquepart.fr Fri Dec 12 14:31:09 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 12 Dec 2008 20:31:09 +0100 Subject: (Very Newbie) Problems defining a variable In-Reply-To: References: <878wqlz27z.fsf@daycos.com> Message-ID: <4942c9b4$0$1651$426a34cc@news.free.fr> Tim Rowe a ?crit : > 2008/12/12 Kirk Strauser : > >> def get_rate(balance): >> for threshold, rate in ((100000, .0173), >> (50000, .0149), >> (25000, .0124), >> (10000, .0085), >> (0, .006)): >> if balance > threshold: >> return rate >> return .0 > > Yes, once it's changed from a dictionary to tuples it becomes easier, > doesn't it? D'oh! > A sequence of pairs and a dict are _almost_ interchangeable (mmm... is that the correct word ?) representations of a same data set[1] - the main difference being ordering. If ordering matters, choose a sequence of pairs as main representation - you can easily build a dict from it if/when you need it. [1] >>> d = dict(a=1, b=2, c=3) >>> dict(d.items()) == d True >>> From mark at thomaszone.com Mon Dec 29 07:40:22 2008 From: mark at thomaszone.com (Mark Thomas) Date: Mon, 29 Dec 2008 04:40:22 -0800 (PST) Subject: Any equivalent to Ruby's 'hpricot' html/xpath/css selector package? References: Message-ID: On Dec 28, 6:22?pm, Kenneth McDonald wrote: > Ruby has a package called 'hpricot' which can perform limited xpath ? > queries, and CSS selector queries. However, what makes it really ? > useful is that it does a good job of handling the "broken" html that ? > is so commonly found on the web. Does Python have anything similar, ? > i.e. something that will not only do XPath queries, but will do so on ? > imperfect HTML? Hpricot is a fine package but I prefer Nokogiri (see http://www.rubyinside.com/nokogiri-ruby-html-parser-and-xml-parser-1288.html) because it is based on libxml2 and therefore is faster, conforms to the full XPath 1.0 spec, works on imperfect HTML, and exposes the Hpricot API. In python, the equivalent is lxml (http://codespeak.net/lxml/), which is similarly based on libxml2, very fast, XPath-1.0 conformant, and exposes the now-standard ElementTree API. The main difference is that lxml doesn't have CSS selector syntax, but IMHO that's a gimmick when you have a full XPath 1.0 engine at your disposal. -- Mark. From pavlovevidence at gmail.com Sun Dec 14 00:15:17 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 13 Dec 2008 21:15:17 -0800 (PST) Subject: curses and refreshing problem References: Message-ID: <69d2698a-6f44-4d85-adc3-1180ab158632@r15g2000prd.googlegroups.com> On Dec 13, 2:29?pm, Karlo Lozovina <_karlo_ at _mosor.net_> wrote: > Hi, I'm trying to implement text output interface, something similar to > wget, using curses module. There are just two things I can't find out how > to do: prevent curses from clearing the terminal when starting my program, > and leaving my output after the program closes. Any way to do this with > curses? Unless you are referring to some wget screen mode I don't know about, I suspect wget outputs its progress bar using carriage returns without newlines. If that's all you want, there is no need to use curses. Here is a little example program to illustrate: import time, sys for i in range(21): sys.stdout.write('\rProgress: [' + '='*i + ' '*(20-i) + ']') sys.stdout.flush() time.sleep(1) sys.stdout.write("\nFinised!\n") Notice I'm using sys.stdout.write instead of print, because print automatically appends a newline (which we don't want here). Yes you can suppress the newline on print by using a trailing comma, but that creates an undesirable artifact--a leading space--on the following cycle. Notice the '\r' at the beginning of the sys.stdout.write call. This tells the terminal to move the cursor back to the beginning of the line, whence it draws the new progress bar over the old progress bar. And finally, notice the call to sys.stdout.flush(). When a program is run on a terminal the underlying I/O is usually line-buffered, meaning that nothing actually gets output until a newline character is sent. Therefore we have to call sys.stdout.flush() to flush the buffer manually. Carl Banks From steve at REMOVE-THIS-cybersource.com.au Thu Dec 25 08:56:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Dec 2008 13:56:21 GMT Subject: Is there a function to remove escape characters from a string ? References: Message-ID: <0163882f$0$6988$c3e8da3@news.astraweb.com> On Thu, 25 Dec 2008 11:00:18 +0100, Stef Mientki wrote: > hello, > > Is there a function to remove escape characters from a string ? > (preferable all escape characters except "\n"). Can you explain what you mean? I can think of at least four alternatives: (1) Remove literal escape sequences (backslash-char): "abc\\t\\ad" => "abcd" r"abc\t\ad" => "abcd" (2) Replace literal escape sequences with the character they represent: "abc\\t\\ad" => "abc\t\ad" (3) Remove characters generated by escape sequences: "abc\t\ad" => "abcd" "abc" => "abc" but "a\x62c" => "ac" This is likely to be impossible without deep magic. (4) Remove so-called binary characters which are typically inserted using escape sequences: "abc\t\ad" => "abcd" "abc" => "abc" but "a\x62c" => "abc" This is probably the easiest, assuming you have bytes instead of unicode. import string table = string.maketrans('', '') delchars =''.join(chr(n) for n in range(32)) s = string.translate(s, table, delchars) -- Steven From kay.schluehr at gmx.net Sat Dec 6 01:55:38 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Fri, 5 Dec 2008 22:55:38 -0800 (PST) Subject: Guido's new method definition idea References: Message-ID: <9e9d9410-a1a0-4736-a635-490f5e80454b@l39g2000yqn.googlegroups.com> On 6 Dez., 03:21, "Daniel Fetchinson" wrote: > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... > > The proposal is to allow this: > > class C: > def self.method( arg ): > self.value = arg > return self.value > > instead of this: > > class C: > def method( self, arg ): > self.value = arg > return self.value > > I.e. explicit self stays only the syntax is slightly different and may > seem attractive to some. As pointed out by Guido classmethods would > work similarly: > > class C: > @classmethod > def cls.method( arg ): > cls.val = arg > return cls.val > > The fact that Guido says, > > "Now, I'm not saying that I like this better than the status quo. But > I like it a lot better than [...] but it has the great advantage that > it is backward compatible, and can be evolved into a PEP with a > reference implementation without too much effort." > > shows that the proposal is viable. So both forms are dual to each other ( "backwards compatibility" ) and can be used both? I'm -0 on this although I think the proposition fits better with the method call syntax. From gagsl-py2 at yahoo.com.ar Sun Dec 14 16:30:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 14 Dec 2008 19:30:41 -0200 Subject: Bidirectional Networking References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <6qeht0Fc3541U1@mid.individual.net> <782258db-2bdc-45a7-8d8f-7a036d574985@t26g2000prh.googlegroups.com> <2cf74767-e331-4fa6-8915-8f87ba01ca34@l33g2000pri.googlegroups.com> Message-ID: En Sun, 14 Dec 2008 11:00:18 -0200, Emanuele D'Arrigo escribi?: > On Dec 14, 4:10 am, "Gabriel Genellina" > wrote: >> daemon became a property in Python 2.6; setDaemon was the only way to >> set >> it in previous versions. > > I thought that might be the case! The documentation is a bit vague: > > http://docs.python.org/library/threading.html?highlight=threading#threading.Thread.setDaemon > > Should we maybe add "New in 2.6" to the Thread.daemon paragraph? That would be a nice addition, but if you are using Python 2.5, you should read the 2.5 version of the docs: http://www.python.org/doc/2.5.2/lib/thread-objects.html -- Gabriel Genellina From ethan at stoneleaf.us Mon Dec 8 02:53:23 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Sun, 07 Dec 2008 23:53:23 -0800 Subject: dBase III files and Visual Foxpro 6 files Message-ID: <493CD273.90404@stoneleaf.us> Greetings All! I nearly have support complete for dBase III dbf/dbt files -- just wrapping up support for dates. The null value has been a hindrance for awhile but I nearly have that solved as well. For any who know of a cool dbf module already in existence for dBase III and Visual Foxpro -- where were you six months ago when I was searching? ;) Seriously, though, this has been a great learning experience for me. As I said -- dbf/dbt files are 99% ready. idx files -- no support: for my purposes I just don't need them. I've found no problem in loading tables up to 300,000 records with 50 fields per record, and re-ordering them on the fly in memory. However, after putting much effort into this code, and wanting it to be useful to others in the community, are there others who work with dbf files that would need idx/cdx support? Or tables so large they won't fit comfortably into memory? ~ethan~ From jstroud at mbi.ucla.edu Mon Dec 8 03:10:20 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 08 Dec 2008 00:10:20 -0800 Subject: Rich Comparisons Gotcha In-Reply-To: References: <014c593e$0$20670$c3e8da3@news.astraweb.com> Message-ID: Robert Kern wrote: > James Stroud wrote: >> I think it skips straight to __eq__ if the element is not the first in >> the list. > > No, it doesn't skip straight to __eq__(). "y is 1" returns False, so > (y==1) is checked. When y is a numpy array, this returns an array of > bools. list.__contains__() tries to convert this array to a bool and > ndarray.__nonzero__() raises the exception. > > list.__contains__() checks "is" then __eq__() for each element before > moving on to the next element. It does not try "is" for all elements, > then try __eq__() for all elements. Ok. Thanks for the explanation. > > That no one acknowledges this makes me feel like a conspiracy > > is afoot. > > I don't know what you think I'm not acknowledging. Sorry. That was a failed attempt at humor. James From Astley.lejasper at gmail.com Wed Dec 3 10:29:25 2008 From: Astley.lejasper at gmail.com (Astley Le Jasper) Date: Wed, 3 Dec 2008 07:29:25 -0800 (PST) Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> Message-ID: <126ba84a-0ea0-4a91-b7d2-89ed650e5d6c@d32g2000yqe.googlegroups.com> I've included a switch to include or exclude the logging to console. When logging only to file, the script runs fine. Of course, I still don't understand why dual logging, and specifically to the console, causes a problem and if anyone has any comments about the dual output logging code above then I'd still be happy to hear about it. ALJ From kyosohma at gmail.com Thu Dec 25 08:38:17 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 25 Dec 2008 05:38:17 -0800 (PST) Subject: PythonCard timer/thread tutorial References: <59e602b0-937c-4bd5-bc71-30094e1cd596@r36g2000prf.googlegroups.com> <6f7164cc-56dc-4022-8943-067b8ca44e61@40g2000prx.googlegroups.com> <0163809d$0$6988$c3e8da3@news.astraweb.com> Message-ID: <76e23107-b4c6-41cb-8199-f2a80b61cda7@v39g2000pro.googlegroups.com> On Dec 25, 7:24?am, Steven D'Aprano wrote: > On Wed, 24 Dec 2008 16:59:23 -0800, Mike Driscoll wrote: > >> Among my questions are: > >> """ A little thread we've added""" seems to be an isolated string. It > >> does not seem to be doing anything there, almost like a comment. Why is > >> it there? > > > That's what some people call a doc string. > > Other people call it "Maurice". *wink* > > A doc[umentation] string is the accepted name for it. Anytime a function, > class or module starts immediately with a loan string, that string is > stored by the Python compiler in an attribute __doc__. E.g.: > > >>> def parrot(x): > > ... ? ? "This is a doc string." > ... ? ? return "Norwegian Blue" > ...>>> parrot.__doc__ > > 'This is a doc string.' > > > It is like a comment in that > > it helps the user know what the function is for. Notice the triple > > quotes. > > Triple quotes are a red herring. Any string literal will do. > > -- > Steven Thanks for clearing that up. I suppose that's more of a recommended style choice than a requirement. I'm pretty sure some of the Python books I've read have implied that the triple quotes matter...oh well. Live and learn. Merry Christmas! Mike From pavlovevidence at gmail.com Sat Dec 6 22:35:42 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 6 Dec 2008 19:35:42 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> <014b2a09$0$20670$c3e8da3@news.astraweb.com> Message-ID: <5e58fbc8-17df-40ae-8b18-7b07765e898f@v38g2000yqb.googlegroups.com> On Dec 6, 8:17?pm, Steven D'Aprano wrote: > On Sun, 07 Dec 2008 11:27:56 +1000, Nick Coghlan wrote: > > Warren DeLano wrote: > >> In other words we have lost the ability to refer to "as" as the > >> generalized OOP-compliant/syntax-independent method name for casting: > > > Other possible spellings: > > > # Use the normal Python idiom for avoiding keyword clashes # and append > > a trailing underscore > > new_object = old_object.as_(class_hint) float_obj = int_obj.as_("float") > > float_obj = int_obj.as_(float_class) > > > # Use a different word (such as, oh, "cast" perhaps?) new_object = > > old_object.cast(class_hint) float_obj = int_obj.cast("float") > > float_obj = int_obj.cast(float_class) > > I don't like "cast", because a cast is an instruction to the compiler to > treat data as some type other than what it was defined as. It doesn't > create a new piece of data. (At least in C-like languages.) Actually, C-like languages do exactly that. (float)i doesn't take the bits of int i and treat them as if they were a float, it creates new data in the appropriate data type that matches the value of i semantically, which would have a very different bit pattern. Pointer-to-int and pointer-to-pointer typecasts are really the only ones that tend to preserve the bits of the data (which, since they are the most common kinds of typecast, has misled some people to think that typecasts in C are all about preserving bits). However, in general typecasts preserve the semantic value of the original data. That's exactly what these methods would be doing, changing the type while preserving the semantic value as much as possble, so cast is a perfectly appropriate name for it. (BTW, in C++, even pointer-to-pointer static casts don't always preserve the bits.) Carl Banks From steve at holdenweb.com Tue Dec 23 11:10:52 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 23 Dec 2008 11:10:52 -0500 Subject: iterating initalizations In-Reply-To: <20081223105911.9b265bf2.darcy@druid.net> References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> <20081223092504.aaf25192.darcy@druid.net> <20081223105911.9b265bf2.darcy@druid.net> Message-ID: D'Arcy J.M. Cain wrote: > On Tue, 23 Dec 2008 10:20:59 -0500 > Steve Holden wrote: >> D'Arcy J.M. Cain wrote: >>> Well, if all you want is a loop: >>> >>> for v in vars: >>> locals()[v] = [] >>> >> Note that this isn't guaranteed to work. While locals() will return a >> dict containing the names and values from the local namespace, you won't >> affect the local namespace by assigning values to the appropriate keys: >> >>>>> def f(): >> ... a = "hello" >> ... locals()["a"] = "goodbye" >> ... print a > > This was my test: > >>>> locals()['x'] = "hello" >>>> x > 'hello' >>>> locals()['x'] = "goodbye" >>>> x > 'goodbye' > > Just didn't want people to think that I post without testing. > > In any case, even if that worked as expected I am pretty sure that it > is the wrong solution but without knowing more about what the OP is > doing it is impossible to know what the right answer is. > The thing you overlooked was that the locals of a function are special. The locals of a module are the globals! >>> def lisg(): ... return locals() is globals() ... >>> locals() is globals() True >>> lisg() False >>> regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From jon at ffconsultancy.com Mon Dec 8 07:07:10 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Mon, 08 Dec 2008 12:07:10 +0000 Subject: Mathematica 7 compares to other languages References: <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: <4ridneQnkLrPkKDUnZ2dnUVZ8qbinZ2d@posted.plusnet> sln at netherlands.com wrote: > Well, its past 'tonight' and 6 hours to go till past 'tomorrow'. > Where the hell is it Zah Zah? Note that this program takes several days to compute in Mathematica (even though it takes under four seconds in other languages) so don't expect to see a genuinely optimized version any time soon... ;-) -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From Russ.Paielli at gmail.com Sat Dec 6 10:15:27 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 6 Dec 2008 07:15:27 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> Message-ID: <8b8d1fb3-f49e-49bf-8cfe-eeee5ed16109@r37g2000prr.googlegroups.com> On Dec 6, 4:32?am, Andreas Waldenburger wrote: > On Sat, 6 Dec 2008 04:02:54 -0800 (PST) bearophileH... at lycos.com wrote: > > > class C: > > ? ? def $method(arg): > > ? ? ? ? $value = arg > > > (Note there's no point after $, it's not currently possible). > > Ruby uses @ and @@ for similar purposes. > > I agree that the code looks worse, but also shorter to read and write, > > so in lines of code that use many instance attributes, that short $ > > syntax helps keep the line shorter. So I may grow to accept this > > sugar... > > But that is not the way Python is meant to work. There are several > tennets in the Zen of Python that don't chime well with this approach. > "self" is a speaking identifier, "$" isn't. Is "@" a "speaking identifier? How about "#" and "!="? Last I heard, they were all part of Python. From Slaunger at gmail.com Wed Dec 10 02:50:45 2008 From: Slaunger at gmail.com (Slaunger) Date: Tue, 9 Dec 2008 23:50:45 -0800 (PST) Subject: Best way to report progress at fixed intervals References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> <817384d5-5f68-4c1f-9560-0bc7b7d2b1e3@v5g2000prm.googlegroups.com> <6ccb77a2-a3f1-4b6b-900c-d4626be9e939@s1g2000prg.googlegroups.com> Message-ID: On 10 Dec., 08:03, Arnaud Delobelle wrote: > Slaunger writes: > > On 10 Dec., 03:44, George Sakkis wrote: > >> On Dec 9, 11:40?am, Slaunger wrote: > > >> > I would therefore like some feedback on this proposed generic "report > >> > progress at regular intervals" approach presented here. What could I > >> > do better? > > >> There is a pypi package that might do what you're looking for (haven't > >> used it though):http://pypi.python.org/pypi/progressbar/. > > >> HTH, > >> George > > > Thank you. I will keep that in mind, if I ever get to doing GUI-based > > progress. > > > -- Slaunger > > It's a text progress bar > > -- > Arnaud- Skjul tekst i anf?rselstegn - > > - Vis tekst i anf?rselstegn - Sorry, apparently I did not realize that at first sight. Anyway, I'd rather avoid using further external modules besides the standard batteries, as I would have to update several workstations with different OSes (some of which I do not have admin access to) to use the new module. -- Slaunger From gh at ghaering.de Wed Dec 3 16:21:54 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 03 Dec 2008 22:21:54 +0100 Subject: python an sqlite objects In-Reply-To: References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <18742.47391.389709.119341@montanaro-dyndns-org.local> Message-ID: <4936F872.2020207@ghaering.de> azrael wrote: > It logical that it would be more efficient and logical to use a object > oriented database, but in this case I ask because of the portable > nature of sqlite. > > so, if I get it right, this should be possible [...] Did you try it? Did it work? If so,it was pure luck. Attached is a script that shows how to do it right. -- Gerhard -------------- next part -------------- A non-text attachment was scrubbed... Name: sqlite_serialize.py Type: text/x-python Size: 1642 bytes Desc: not available URL: From prologic at shortcircuit.net.au Tue Dec 30 18:58:34 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 09:58:34 +1000 Subject: get method In-Reply-To: <495AAB97.5010707@mrabarnett.plus.com> References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> <495AAB97.5010707@mrabarnett.plus.com> Message-ID: On Wed, Dec 31, 2008 at 9:15 AM, MRAB wrote: (snip) > A while back I posted a Python implementation of 'bag' (also called a > multiset). The code would then become something like: What complexity is this ? cheers James From steven at REMOVE.THIS.cybersource.com.au Tue Dec 9 23:10:30 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 10 Dec 2008 04:10:30 GMT Subject: Can't figure out where SyntaxError: can not delete variable 'x' referenced in nested scope us coming from in python >=2.6 References: <014eef7f$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Tue, 09 Dec 2008 22:57:36 -0500, Albert Hopkins wrote: > On Tue, 2008-12-09 at 22:57 +0000, Steven D'Aprano wrote: [...] >> > So is there a way to find the offending code w/o having to go >> through >> > every line of code in 'foo' by hand? >> >> Just search for "del x" in your code. Your editor does have a search >> function, surely? >> >> >> > Well, you'd think I'd be smart enough to think of that one, wouldn't > you? Actually, how could you since you don't know me ;-)... Anway, I > already did that and could not find the offending code. You should have said :) > I submitted this bug [1]. I applied the given patch but the line it > shows isn't a "del" anything so I'm even more confused. Ouch. You have my sympathies. I guess you're going to have to just import each module one at a time until you find the module that fails, then search that one. -- Steven From python at bdurham.com Wed Dec 24 02:16:36 2008 From: python at bdurham.com (python at bdurham.com) Date: Wed, 24 Dec 2008 02:16:36 -0500 Subject: Strategy for determing difference between 2 very large dictionaries Message-ID: <1230102996.2303.1291616055@webmail.messagingengine.com> I'm looking for suggestions on the best ('Pythonic') way to determine the difference between 2 very large dictionaries containing simple key/value pairs. By difference, I mean a list of keys that are present in the first dictionary, but not the second. And vice versa. And a list of keys in common between the 2 dictionaries whose values are different. The 2 strategies I'm considering are: 1. Brute force: Iterate through first dictionary's keys and determine which keys it has that are missing from the second dictionary. If keys match, then verify that the 2 dictionaries have identical values for the same key. Repeat this process for the second dictionary. 2. Use sets: Create sets from each dictionary's list of keys and use Python's set methods to generate a list of keys present in one dictionary but not the other (for both dictionaries) as well as a set of keys the 2 dictionaries have in common. Using the set of keys in common, compare values across dictionaries to determine which keys have different values (can this last step be done via a simple list comprehension?) Feedback on my proposed strategies (or better strategies) would be greatly appreciated. Thank you, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip at pobox.com Wed Dec 3 12:37:21 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 3 Dec 2008 11:37:21 -0600 Subject: python an sqlite objects In-Reply-To: <4936bceb$0$16783$426a34cc@news.free.fr> References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <4936bceb$0$16783$426a34cc@news.free.fr> Message-ID: <18742.50129.573798.742119@montanaro-dyndns-org.local> Bruno> Or if you want something more portable, serialize the object to Bruno> json. At least you'll have a chance to deserialize it with some Bruno> other language. Assuming json can serialize more-or-less arbitrary Python objects. Can it serialize class instances? Skip From n.kottiyath at gmail.com Wed Dec 24 12:37:31 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Wed, 24 Dec 2008 09:37:31 -0800 (PST) Subject: Iterating over objects of a class Message-ID: <2df27de3-7fa3-4ac9-acd9-f946939517cf@r37g2000prr.googlegroups.com> Hi, How can I iterate over all the objects of a class? I wrote the code like following: class baseClass(object): __registry = [] def __init__(self, name): self.__registry.append(self) self.name = name def __iter__(self): baseClass.item = 0 return self.__registry[0] def next(self): if baseClass.item >= len(self.__registry): raise StopIteration baseClass.item += 1 return self.__registry[baseClass.item - 1] For testing, create the following objects- a = baseClass("Test1") b = baseClass("Test2") class subClass (baseClass): pass c = subClass("Test3") ---->Actual Iteration<---- for i in a: print i.name Test1 Test2 Test3 --------------------------------------------------- I see the following problems in the code: 1. I have to iterate over any of the objects. For correctness, I wanted to iterate over the class, like for i in baseClass(): do x but that will will create one more object - which I do not want. 2. If the subclass wants to do somethings in its constructor, I am not sure how to update the registry. class subClass (baseClass): def __init__(self, name): **do something** super.init(self, name) ----> This errors out, saying it needs super, not subClass Another method I thought of implementing it was using generators - where-in baseClass.objects() is a generator which will yield the objects one by one - but even then the second issue remains. If somebody can help me out, I would be very thankful. Regards K From ldo at geek-central.gen.new_zealand Fri Dec 5 05:16:08 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 05 Dec 2008 23:16:08 +1300 Subject: Don't you just love writing this sort of thing :) References: <0148b086$0$20670$c3e8da3@news.astraweb.com> Message-ID: In message <0148b086$0$20670$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > On Fri, 05 Dec 2008 13:27:35 +1300, Lawrence D'Oliveiro wrote: > >> In message , Cong >> Ma wrote: >> >>> The "if ... != None" is not necessary... "if PatchDatePat.search(f)" >>> is OK. >> >> I don't do that. > > Perhaps you should? I prefer using explicitly Boolean values for conditions. From andrea.francia at REMOVE-FROM-HERE.ohoihihoihoih.TO-HERE.gmx.it Tue Dec 16 15:03:21 2008 From: andrea.francia at REMOVE-FROM-HERE.ohoihihoihoih.TO-HERE.gmx.it (Andrea Francia) Date: Tue, 16 Dec 2008 20:03:21 GMT Subject: Where is a good open source python project to be used as example? In-Reply-To: References: <05T1l.219074$FR.507685@twister1.libero.it> Message-ID: D'Arcy J.M. Cain wrote: > On Tue, 16 Dec 2008 19:13:00 GMT > Andrea Francia wrote: >> I'm looking for a python project to use as example to learning python. >> >> The project should have these features: >> >> 1. is almost fully unit tested >> 2. use consistently the code convention recommended by PEP 8 >> 3. it's elements are almost fully documented >> >> Extra point features are: >> >> 4. building, assembling, and release automation >> >> Did you know where are such projects? > > http://www.PyGreSQL.org/. > Thanks! But I can't find any unit test in the code. From mrkafk at gmail.com Tue Dec 30 11:22:47 2008 From: mrkafk at gmail.com (mk) Date: Tue, 30 Dec 2008 17:22:47 +0100 Subject: thread, multiprocessing: communication overhead In-Reply-To: References: Message-ID: Aaron Brady wrote: > snips >> def threadsemfun(): >> sem = threading.Semaphore() >> def threadlockfun(): >> sem = threading.Semaphore() > > You used a Semaphore for both lock objects here. Right... I corrected that (simply changed to threading.Lock() in threadlockfun) and the result is much better, though still an order of magnitude worse than plain function: Function: threadlockfun Best: 0.08665 sec Average: 0.08910 sec Function: notfun Best: 0.00987 sec Average: 0.01003 sec > 'multiprocessing' is a really high level layer that makes a lot of > decisions about trade-offs, has highly redundant communication, and is > really easy to use. If you want to save a byte, you'll have to make > your own decisions about trade-offs and redundancies (possibly even > looking at real result data to make them). Hmm, do you think that lower-level 'thread' module might work more efficiently? > I actually think 'multiprocessing' is really good, and even if I hand- > wrote my own IPC, it would be slower! > > CMIIW, but I believe your timing function includes the time to launch > the actual processes and threads, create the synch. objects, etc. You > might try it again, creating them first, starting the timer, then > loading them. Except I don't know how to do that using timeit.Timer. :-/ From asmodai at in-nomine.org Thu Dec 25 04:49:11 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 25 Dec 2008 10:49:11 +0100 Subject: How to display Chinese in a list retrieved from database via python In-Reply-To: References: Message-ID: <20081225094911.GS12670@nexus.in-nomine.org> -On [20081225 08:30], zxo102 (zxo102 at gmail.com) wrote: > Anybody knows how to solve this problem? You are assigning/pushing out Python byte sequences, not Unicode. Look at u'' string variables, x.encode() and x.decode() to help you. It's widely documented on the Internet, a quick Python Unicode (with encode or decode) should get you there. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B Knowledge is soon changed, then lost in the mist, an echo half-heard... From antoine at vo.lu Tue Dec 9 06:06:13 2008 From: antoine at vo.lu (Antoine De Groote) Date: Tue, 09 Dec 2008 12:06:13 +0100 Subject: Guido's new method definition idea In-Reply-To: <79139d04-bd26-4f36-b8c9-19554e7d4e95@e18g2000yqo.googlegroups.com> References: <014a071a$0$20670$c3e8da3@news.astraweb.com> <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> <79139d04-bd26-4f36-b8c9-19554e7d4e95@e18g2000yqo.googlegroups.com> Message-ID: <1349e$493e5125$d9a2276f$3662@news.hispeed.ch> anthony.tolle at gmail.com wrote: > On Dec 6, 4:15 pm, Carl Banks wrote: [...] > > This brings up another question, what would one use when referencing > method names inside the class definition?: > > class C: > def self.method(arg): > self.value = arg > def self.othermethod(arg): > self.value = arg > # do this? > funcs = (self.method, self.othermethod) > # or this? > funcs = (method, othermethod) > > On another related note, I would be interested in seeing this syntax > adopted for a different purpose... > > Normally, if I'm defining a nested function that needs to be stored as > an object attribute, I have to use a dummy name, like the following: > > class C: > def createfunc(self, arg): > def _dummy(arg): > return arg + 1 > self.func = _dummy > > It would be nice to be able to do the following instead: > > class C: > def createfunc(self): > def self.func(arg): > return arg + 1 > > Or, after the class definition is done, to extend it dynamically: > > def C.method(self, arg): > self.value = arg > > ...which would be the equivalent of the following: > > def method(self, arg): > self.value = arg > C.method = method > > Since functions are first-class objects, it seems perfectly reasonable > to me. A decorator might be more advisable here. class C: def createfunc(self): @some_decorator_name def func(arg): return arg + 1 Altough I'm not a huge fan of decorators, this would be more in line what Python already can do an would lean on the @staticmethod and @classmethod decorators. From ivan.illarionov at gmail.com Tue Dec 9 04:42:21 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 9 Dec 2008 01:42:21 -0800 (PST) Subject: Catching Python exceptions in C References: <72713421-97ed-453f-8f2f-06cc5f0ca355@o40g2000prn.googlegroups.com> Message-ID: On Dec 9, 12:33?pm, Ivan Illarionov wrote: > On Dec 8, 9:42?pm, Senthil Kumar wrote: > > > Hi Pythoneers ! > > Can somebody give a quick solution? > > I am trying to raise exceptions in python and trying to handle it in > > C. > > I am able to raise exceptions successfully. However could not catch > > those in C. > > I am using the following function to run the python from C: > > Pyrun_SimpleString(). > > After the exception is raised, I am checking PyErr_Occurred(). It > > always returns NULL, and I cannot catch the exception. > > Pls help me a way out. > > > Thanx in advance ! > > I use something like this: > > if (PyErr_Occurred()) { > ? ? if (PyErr_ExceptionMatches(ExceptionName)) { > ? ? ? ? /* do something about ExceptionName */ > ? ? } else if (PyErr_ExceptionMatches(AnotherExceptionName)) { > ? ? /* if we want to get the exception string */ > ? ? ? ? PyObject *errtype, *errvalue, *traceback; > ? ? ? ? PyErr_Fetch(&errtype, &errvalue, &traceback); > ? ? ? ? if(errvalue != NULL) { > ? ? ? ? ? ? ?PyObject *s = PyObject_Str(errvalue); > ? ? ? ? ? ? ?/* ? ?Now 'PyString_AS_STRING(s)' > ? ? ? ? ? ? ? contains C string of error message > ? ? ? ? ? ? ? do something with it > ? ? ? ? ? ? ?*/ > ? ? ? ? ? ? ?Py_DECREF(s); > ? ? ? ? } > ? ? ? ? Py_XDECREF(errvalue); > ? ? ? ? Py_XDECREF(errtype); > ? ? ? ? Py_XDECREF(traceback); > ? ? } > > } > > Goof luck. And, as others have said, use 'PyRun_String', not 'PyRun_SimpleString' Sorry, I missed this in previous reply. From cesium5500 at yahoo.ca Fri Dec 5 09:13:00 2008 From: cesium5500 at yahoo.ca (Guy Doune) Date: Fri, 05 Dec 2008 09:13:00 -0500 Subject: pretty strange behavior of "strip" In-Reply-To: <4938693F.6090709@yahoo.ca> References: <4938693F.6090709@yahoo.ca> Message-ID: <493936EC.9030606@yahoo.ca> Ok, didn't show the whole problem... I will read the doc anyway, but why "questions.html" keep it "t"?? >>> test=['03.html', '06.html', 'questions.html', '04.html', 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] >>> test[4] 'toc.html' >>> test[4].strip('.html') 'oc' >>> test[2].strip('.html') 'questions' Thanks. Guy Guy Doune a ?crit : > Hi everybody, > > Could it be a bug????? > > Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> test=['03.html', '06.html', 'questions.html', '04.html', > 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test > ['03.html', '06.html', 'questions.html', '04.html', 'toc.html', > '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test[4] > 'toc.html' > >>> test[4].strip('.html') > 'oc' > > Can't figure out what is going on, really. > > Guy > From deets at nospam.web.de Thu Dec 11 09:38:01 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 11 Dec 2008 15:38:01 +0100 Subject: Python, threading References: Message-ID: <6qcmu9Fbna75U1@mid.uni-berlin.de> SMALLp wrote: > Hy. I have a problem! I'm making multi thread application (client, > server) using wxPython for GUI, and threading.Thread for threding. > > Clients connect and when they are connected (evry thread handles one > connection) threads change main window. > > I neded tip how to make communication between threeds. Are you aware that mixing multi-threading and GUIs usually not works the naive way? Read up on your toolkits documentation how to deal with multi-threading. Diez From deets at nospam.web.de Wed Dec 17 10:41:09 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 17 Dec 2008 16:41:09 +0100 Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> Message-ID: <6qskslFehsbrU1@mid.uni-berlin.de> walterbyrd wrote: > For a language as well structured as Python, this seems somewhat > sloppy, and inconsistant. Or is there some good reason for this? > > Here is what I mean: > > def a(): > x = 99 > print x > > def b(): > print x > > a() > b() # raises an exception because x is not defined. > > However in the methods are within a class, the scoping seems to work > differently. > > class ab(): > def a(self): > self.x = 99 > print self.x > def b(self): > print self.x > > i = ab() > i.a() > i.b() # this works, why no lexical scoping? Because what you do is to create instance variables. Why do you expect them not working if you explicitly access them? The real analog of your example would be this: class ab(): def a(self): x = 100 print x def b(self): print x which provokes the same error. however, there *are* different scoping rules, classes don't create a lexical scope for their own variables: class foo(object): x = 100 def a(self): print x Diez From jgardner at jonathangardner.net Tue Dec 30 17:00:39 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Tue, 30 Dec 2008 14:00:39 -0800 (PST) Subject: need help with list/variables References: <63b5acce-d566-48cb-abce-c00fd0e02a39@v39g2000pro.googlegroups.com> Message-ID: On Dec 30, 11:41?am, 5lvqbw... at sneakemail.com wrote: > > >>> conc = lambda x,y: x[:] + y # concatenate 2 lists without side effects > >>> mylist = ['something\n', 'another something\n', 'something again\n'] > >>> myvar = reduce(conc, mylist) > >>> print myvar > "conc"? "side effects"? Missing Lisp much? ;-) Let's try to Pythonize your lisp. One: Assigning a lambda to a variable? Just use def. It's pretty much the same thing. >>> def conc(x,y): return x[:]+y Two: I don't think x+y affects x at all when x and y are lists. (Is that a lispism?) So x[:]+y has an unnecessary array copy. >>> def conc(x,y): return x+y Three: Python may still be slow at string concatenation. (Perl is fast.) Rather than concatenating one at a time, it's better, I understand, to build up a list and then join() them together. The other posters got the right answer in the pythonic way. From steve at REMOVE-THIS-cybersource.com.au Wed Dec 31 17:26:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Dec 2008 22:26:45 GMT Subject: type conversion References: <4b7188db-63b2-4ac5-80cb-d1326ca3694a@q26g2000prq.googlegroups.com> <613a20bf-6e5a-435e-9a83-36766e12f0ab@k8g2000yqn.googlegroups.com> Message-ID: <016be89e$0$6988$c3e8da3@news.astraweb.com> On Wed, 31 Dec 2008 12:35:20 -0800, Hamish McKenzie wrote: > sometimes I want to be able to initialize an instance with a variety of > different data types. Type conversion is a bit of a misleading subject line. You're not really converting different types, just initialising from different types. > as an obvious example I might want to initialize a 4x4 matrix with > either 16 floats, a list/tuple or 16 floats, another matrix or a > quaternion. > > is there any other way to do it other than putting case statements in > the __init__ method of the class, or having a Matrix.FromQuaternion( > quat )? You could have an external function qtom: def qtom(quaternion): a, b, c, d = quaternion return Matrix([ a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 0, 0, 0, 0, d]) But the first two solutions seem reasonable to me, except of course Python doesn't have a case statement you have to use an if...elseif block. -- Steven From ilikefbsd at web.de Sun Dec 28 03:15:12 2008 From: ilikefbsd at web.de (Marco) Date: Sun, 28 Dec 2008 09:15:12 +0100 Subject: python and rcp, portbind communication Message-ID: <49573590.9010308@web.de> Hello python list, i want to write a program in python which can communicate with rpcservices. At the first stage it shall talk with portbind on port 111 and figure out the running rpc services. Is there already a implementation for python to do so? Best regards, marco From 20080915.20.wmcclain at spamgourmet.com Mon Dec 8 16:30:44 2008 From: 20080915.20.wmcclain at spamgourmet.com (Bill McClain) Date: 8 Dec 2008 21:30:44 GMT Subject: StringIO in 2.6 and beyond References: Message-ID: On 2008-12-08, Christian Heimes wrote: > In this context 'str' means Python 3.0's str type, which is unicode in > 2.x. Please report the misleading error message. So this is an encoding problem? Can you give me a hint on how to correct in my example? I see that io.StringIO() has an encoding parameter, but I'm unclear what to specify. -Bill -- Sattre Press History of Astronomy http://sattre-press.com/ During the 19th Century info at sattre-press.com by Agnes M. Clerke http://sattre-press.com/han.html From v+python at g.nevcal.com Tue Dec 2 22:47:59 2008 From: v+python at g.nevcal.com (Glenn Linderman) Date: Tue, 02 Dec 2008 19:47:59 -0800 Subject: Simple ini Config parser examples needed In-Reply-To: <47c890dc0812021522g7f42b00o2a831bac1e15aa05@mail.gmail.com> References: <47c890dc0812021331m1fe3f420kce9bcb07df5ae44e@mail.gmail.com> <4935BBE5.3020607@g.nevcal.com> <47c890dc0812021522g7f42b00o2a831bac1e15aa05@mail.gmail.com> Message-ID: <4936016F.8010401@g.nevcal.com> On approximately 12/2/2008 3:22 PM, came the following characters from the keyboard of Chris Rebert: > On Tue, Dec 2, 2008 at 2:51 PM, Glenn Linderman wrote: > >> On approximately 12/2/2008 1:31 PM, came the following characters from the >> keyboard of Chris Rebert: >> >>> On Tue, Dec 2, 2008 at 1:18 PM, RON BRENNAN >>> wrote: >>> >>> >>>> Hello, >>>> >>>> I have a very simple ini file that I needs parsed. What is the best way >>>> I >>>> can parse an ini file that doesn't include sections? >>>> > > *Bangs head against wall repeatedly* > I merely glossed the question and missed that all-important second > sentence! fsck! > My apologies, I shouldn't write email before having coffee :) > Fortunately Tim followed quickly with the correct answer to the OP. > Tim provided a correct-looking answer, albeit somewhat complex, as it doesn't reuse the logic in the ConfigParser. That's why I suggested yet another alternative, yet left one key item off myself (added below). >>>> As in: >>>> >>> Since it appears that ConfigParser requires at least one section >>> header, I'll assume the file starts with the following line: >>> >>> [main] >>> >>> >>>> person=tall >>>> height=small >>>> shoes=big >>>> >>>> >>>> Thats it. Can anyone help me? >>>> >>>> >>> Completely untested: >>> >>> import ConfigParser >>> config = ConfigParser.RawConfigParser() >>> config.readfp(open("path/to/file.cfg")) >>> config.get("main", "height") #==> "small" >>> >>> Cheers, >>> Chris >>> >>> >> Of course the OP question was that the line you assume isn't there. But if >> the ini is simple, maybe it is short enough to read into a string, then >> prepend the line, then parse with ConfigParser. >> And I meant to add "parse with ConfigParser by passing the combined string in via StringIO. -- Glenn -- http://nevcal.com/ =========================== A protocol is complete when there is nothing left to remove. -- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking From lists at cheimes.de Tue Dec 16 15:24:44 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 16 Dec 2008 21:24:44 +0100 Subject: sys.maxint in Python 2.6.1 (amd64) on Windows XP x64 In-Reply-To: <7a629cb1-0fbc-41d4-ac51-d0be68df1df5@r36g2000prf.googlegroups.com> References: <4bddf65a-bb9f-406c-a544-8c38b27547a7@b38g2000prf.googlegroups.com> <7a629cb1-0fbc-41d4-ac51-d0be68df1df5@r36g2000prf.googlegroups.com> Message-ID: Lin schrieb: > Ah, this makes sense. Thanks...... The main reason I'm trying 64-bit > Python is that I want to write files bigger than 4GB. This should work > on Windows x64, right? (i.e., are the pointers bona fide 64 bit?) You can create files with more than 4GB on a 32bit OS, too. It depends on the file system. It works with NTFS but I'm not sure how FAT32 deals with large files. My DVB-S receiver with USB port chokes on files with more than 2 GB. Christian From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 00:21:25 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Dec 2008 05:21:25 GMT Subject: "as" keyword woes References: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> <0147dc24$0$20670$c3e8da3@news.astraweb.com> Message-ID: <0148b217$0$20670$c3e8da3@news.astraweb.com> On Thu, 04 Dec 2008 08:44:19 -0800, Matimus wrote: > The point was that there > is that new releases don't _break_ anything. But that's clearly not true, because the OP is pointing out that the new release from 2.5 to 2.6 *does* break his code. -- Steven From hongqn at gmail.com Fri Dec 26 00:44:11 2008 From: hongqn at gmail.com (Qiangning Hong) Date: Thu, 25 Dec 2008 21:44:11 -0800 (PST) Subject: sys.stdout.write()'s bug or doc bug? Message-ID: >>> u = u'\u554a' >>> print u ? >>> sys.stdout.write(u) Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\u554a' in position 0: ordinal not in range(128) >>> type(sys.stdout) >>> sys.stdout.encoding 'UTF-8' Quote from file object's documentation: encoding The encoding that this file uses. When Unicode strings are written to a file, they will be converted to byte strings using this encoding. ..... So, my question is, as sys.stdout IS a file object, why it does not use its encoding attribute to convert the given unicode? An implementation bug? A documenation bug? From clp at rebertia.com Sun Dec 7 04:05:55 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 7 Dec 2008 01:05:55 -0800 Subject: var or inout parm? In-Reply-To: References: Message-ID: <47c890dc0812070105l24953730tc450c49ea30658ed@mail.gmail.com> On Sun, Dec 7, 2008 at 12:54 AM, wrote: > How can I make a "var" parm, where the called function can modify > the value of the parameter in the caller? Not directly possible or encouraged. You can emulate it by sticking the value in a container object (e.g. list) though: def f(x): x[0] += 1 #non-augmented assignment would work too n = [1] f(n) print n[0] #==> 2 Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > def f(x): > x = x + 1 > > n = 1 > f(n) > # n should now be 2 > > Many TIA!! > Mark > > > -- > Mark Harrison > Pixar Animation Studios > -- > http://mail.python.org/mailman/listinfo/python-list > From rocky at panix.com Wed Dec 10 16:07:15 2008 From: rocky at panix.com (R. Bernstein) Date: Wed, 10 Dec 2008 16:07:15 -0500 Subject: pydb 1.24 Message-ID: This release is to clear out some old issues. It contains some bugfixes, document corrections, and enhancements. Tests were revised for Python 2.6 and Python without readline installed. A bug involving invoking from ipython was fixed. The "frame" command is a little more like gdb's. Exceptions are now caught in runcall(). This is the last release contemplated before a major rewrite. download: https://sourceforge.net/project/showfiles.php?group_id=61395&package_id=175827 bug reports: https://sourceforge.net/tracker/?group_id=61395&atid=497159 From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 29 07:19:38 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 29 Dec 2008 13:19:38 +0100 Subject: AttributeError: 'module' object has no attribute 'DatagramHandler' (ubuntu-8.10, python 2.5.2) In-Reply-To: <4c6f0831-c05f-401f-b956-376600b38e06@r15g2000prd.googlegroups.com> References: <4c6f0831-c05f-401f-b956-376600b38e06@r15g2000prd.googlegroups.com> Message-ID: <4958c059$0$16065$426a34cc@news.free.fr> Tzury Bar Yochay a ?crit : > $ ~/devel/ice/snoip/freespeech$ python > Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) > [GCC 4.3.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import logging >>>> logging.DatagramHandler > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute 'DatagramHandler' > > > That is odd since the documentation says there is DatagramHandler for > module logging It also says that DatagramHandler is located in the logging.handlers modules: http://www.python.org/doc/2.5.2/lib/node415.html HTH From google at mrabarnett.plus.com Thu Dec 4 14:40:49 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 04 Dec 2008 19:40:49 +0000 Subject: Python 3 read() function In-Reply-To: References: Message-ID: <49383241.4050708@mrabarnett.plus.com> Terry Reedy wrote: > ?????? ??????????? wrote: >>> I don't think it matters. Here's a quick comparison between 2.5 and >>> 3.0 on a relatively small 17 meg file: >>> >>> C:\>c:\Python30\python -m timeit -n 1 >>> "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" >>> 1 loops, best of 3: 36.8 sec per loop >>> >>> C:\>c:\Python25\python -m timeit -n 1 >>> "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" >>> 1 loops, best of 3: 33 msec per loop >>> >>> That's 3 orders of magnitude slower on python3.0! >> >> Isn't this because you have the file cached in memory on the second run? > > In my test, I read Python25.chm with 2.5 and Python30.chm with 3.0. > > Rereading Python30.chm without closing *is* much faster. > >>> f=open('Doc/Python30.chm','rb') > >>> d=f.read() > >>> d=f.read() > >>> d=f.read() > Closing, reopening, and rereading is slower. > It certainly is faster if you're already at the end of the file. :-) From kirk at daycos.com Thu Dec 11 11:31:36 2008 From: kirk at daycos.com (Kirk Strauser) Date: Thu, 11 Dec 2008 10:31:36 -0600 Subject: Do more imported objects affect performance References: Message-ID: <874p1a1xnb.fsf@daycos.com> At 2008-12-01T11:30:44Z, Nick Craig-Wood writes: > Importing the module is actualy slower... If you import the name into > your namespace then there is only one lookup to do. If you import the > module there are two. Note that if you're importing the entire module but want to call a function that many times, you can do something like: import timeit Timer = timeit.Timer for _ in xrange(1000000): Timer -- Kirk Strauser The Day Companies From rt8396 at gmail.com Thu Dec 18 16:41:30 2008 From: rt8396 at gmail.com (r) Date: Thu, 18 Dec 2008 13:41:30 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <71ede5f0-fd88-4155-9f0d-42d0ad5f57dc@v42g2000yqj.googlegroups.com> <61f45e65-2404-4cc0-9d81-f848c1ba566f@i18g2000prf.googlegroups.com> Message-ID: <9136d71c-01cf-48fa-a5cf-6b445e882eb1@n10g2000vbl.googlegroups.com> On Dec 18, 1:48?pm, Roger wrote: > On Dec 18, 12:49?pm, r wrote: > > > Maybe someone will chime in with an answer, sorry i could not help. > > ponder this, i must... > > Regardless, thanks for your help! I truly appreciate it. > > Roger. 'no problema mi amigo!'.to_english(no problem my friend!) :) From prologic at shortcircuit.net.au Tue Dec 16 01:03:55 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 16 Dec 2008 16:03:55 +1000 Subject: socket and subprocess problem In-Reply-To: <73dca20d-3378-4c96-aa30-f0617f111fa0@i18g2000prf.googlegroups.com> References: <6d3291c3-4e12-4bdd-884a-21f15f38d105@a12g2000pro.googlegroups.com> <73dca20d-3378-4c96-aa30-f0617f111fa0@i18g2000prf.googlegroups.com> Message-ID: On Tue, Dec 16, 2008 at 3:30 PM, wrote: > Guys thanks to point it out. > Yes, it's a race problem. I tried sleep long enough, then I can > connect to the socket. I should add code to try to connect to the > socket for a given time out. This is where event-driven approaches become really useful :) subprocess process: #1. When my subprocess process has successfully started notify the parent. #2. When my subprocess process has successfully created a listening socket, notify the parent. parent process: #1. When our subprocess process has successfully started a listening socket initiate a connection. I could implement a prototype of this if the OP is interested. --JamesMills From clp at rebertia.com Tue Dec 23 02:11:53 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 22 Dec 2008 23:11:53 -0800 Subject: String Format Error. In-Reply-To: References: Message-ID: <47c890dc0812222311m2a67b798v167b40de9dfcd53d@mail.gmail.com> On Mon, Dec 22, 2008 at 10:19 PM, Paulo Repreza wrote: > Hi, > > I'm a newbie with python and I recently bought Beginning with Python (Which > is a book I recommend) but the problem that I'm facing it's the following: > > This is the code: > > #!/usr/bin/python2.5 > # Filename: str_format.py > > age = 25 > name = 'foobar' > > print('{0} is {1} years old'.format(name, age)) > print('Why is {0} playing with that python?'.format(name)) > > > But when I run the script I receive this error: > > Traceback (most recent call last): > File "str_format.py", line 7, in > print('{0} is {1} years old'.format(name, age)) > AttributeError: 'str' object has no attribute 'format' > > > It is an error because of the version that I'm using ? Python 2.5.2 (Debian > lenny) Yes, Python 2.6 or higher is required to use .format() according to http://docs.python.org/whatsnew/2.6.html Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From rhodri at wildebst.demon.co.uk Thu Dec 11 20:58:22 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Fri, 12 Dec 2008 01:58:22 -0000 Subject: newbie question: if var1 == var2: In-Reply-To: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> Message-ID: On Thu, 11 Dec 2008 23:49:10 -0000, John Machin wrote: > On Dec 12, 10:31?am, "Rhodri James" > wrote: >> On Thu, 11 Dec 2008 19:49:23 -0000, Steve Holden ? >> wrote: >> > ... and it's so hard to write >> >> > ? ? ?item = item[:-1] >> >> Tsk. ?That would be "chop". ?"chomp" would be >> >> ? ? ?if item[-1] == '\n': >> ? ? ? ? ?item = item[:-1] > > Better: > if item and item[-1] == '\n': > return item[:-1] > return item If we aren't going for rstrip, yes, but I was trying to stick to Steve's metier. -- Rhodri James *-* Wildebeeste Herder to the Masses From eric at ericaro.net Fri Dec 19 12:36:31 2008 From: eric at ericaro.net (eric) Date: Fri, 19 Dec 2008 09:36:31 -0800 (PST) Subject: best way to code References: Message-ID: On Dec 19, 5:35?pm, Peter Otten <__pete... at web.de> wrote: > eric wrote: > > hi, > > > I need to find a "good" design pattern to instanciate, and add > > specific code all in one. Let me explain it : > > > I need to define "some" code, better be in a class, something like > > > class LinkA(object): > > ? ? def mystuff(self): > > ? ? ? ? ? > > > class LinkB(object): > > ? ? def mystuff(self): > > ? ? ? ? ? > > > AND I need an instance of this class > > { "stuff A": LinkA() > > ? "stuff B": LinkB() > > } > > > This kind of code "would" be fine, I mean, the result effect in memory > > is fine for me. > > But I don't like the way I have to > > 1/ give a useless name to LinkA, linkB (there can be hundreds of names > > like that) > > 2/ I have to write it down two times (and that's one time too much) > > > any ideas ? > > > something like > > [ > > new object(): > > ? ? def mystuff(self): > > ? ? ? ? > > , > > new object(): > > ? ? def mystuff(self): > > ? ? ? ? > > ] > > > would be really perfect (but I know it does not work, or at least, I > > don't know how to make it work) > > > In fact, I would like to define a class, and an instance in a single > > statement > >>> class Register: > > ... ? ? def __init__(self): > ... ? ? ? ? ? ? self.items = [] > ... ? ? def __call__(self, method): > ... ? ? ? ? ? ? class Link(object): > ... ? ? ? ? ? ? ? ? ? ? mystuff = method > ... ? ? ? ? ? ? self.items.append(Link()) > ...>>> register = Register() > >>> @register > > ... def mystuff(self): print "first" > ...>>> @register > > ... def mystuff(self): print "second" > ...>>> for item in register.items: > > ... ? ? item.mystuff() > ... > first > second > > Peter hi, I've tried something like this : import inspect class Test(object): class Inner(object): def mystuff(self): print "hello stuff" class InnerB(object): def mystuff(self): print "hello B" def filter(member): return inspect.isclass(member) and not member==Test.__class__ d = dict( (name, c()) for name, c in inspect.getmembers(Test, filter ) ) print d it works too, but I prefer your method thanks -- Eric http://codeslash.blogspot.com From christophedeze at gmail.com Tue Dec 23 03:23:50 2008 From: christophedeze at gmail.com (Toff) Date: Tue, 23 Dec 2008 00:23:50 -0800 (PST) Subject: join a samba domain References: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> <494fd597$0$90267$14726298@news.sunsite.dk> <73194a24-f14e-46f1-8789-886ba4729084@r15g2000prd.googlegroups.com> Message-ID: <1a326512-3c74-404d-9c51-fde35f39702e@t39g2000prh.googlegroups.com> On 22 d?c, 19:37, Toff wrote: > On 22 d?c, 18:59, Jens Henrik Leonhard Jensen > > wrote: > > Toff wrote: > > > ? ?d = c.Win32_ComputerSystem > > > ? ?d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") > > > Shouldn't r"admin\\mydom" be "admin\\mydom" or r"admin\mydom". > > Or maybe just "admin" > > > /Jens Henrik > > you are right but i've got the same error. the more i look at my script the more i think it s a BUG. #ALL works great import wmi c = wmi.WMI() for computer in c.Win32_ComputerSystem(): if computer.PartOfDomain: print computer.Domain #DOMCD print computer.SystemStartupOptions # (u'"Microsoft Windows XP Professionnel" /noexecute=optin /fastdetect',) #error message computer.JoinDomainOrWorkGroup('DOMCD', 'adminLocal', 'admin\ \DOMCD',None,3 ) ############## DOMCD (u'"Microsoft Windows XP Professionnel" /noexecute=optin / fastdetect',) Traceback (most recent call last): File "integrdom.py", line 51, in main() File "integrdom.py", line 13, in main joindom() File "integrdom.py", line 47, in joindom computer.JoinDomainOrWorkGroup('DOMCD', 'adminLocal', 'admin\ \DOMCD',None,3 ) File "c:\Python25\Lib\site-packages\wmi.py", line 493, in __getattr__ handle_com_error (error_info) File "c:\Python25\Lib\site-packages\wmi.py", line 189, in handle_com_error raise x_wmi, "\n".join (exception_string) wmi.x_wmi From skip at pobox.com Thu Dec 4 19:33:40 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 4 Dec 2008 18:33:40 -0600 Subject: Importing Version Specific Modules In-Reply-To: <558b73fb0812041529g313a27bpcfd09fc90f474f6e@mail.gmail.com> References: <558b73fb0812041529g313a27bpcfd09fc90f474f6e@mail.gmail.com> Message-ID: <18744.30436.32591.969670@montanaro-dyndns-org.local> Michael> if sys.version_info[:2] >= (2, 5): Michael> from string import Template Michael> else: Michael> from our.compat.string import Template This is "look before you leap" (LBYL). Michael> try: Michael> from string import Template Michael> except ImportError: Michael> from our.compat.string import Template This is "easier to ask forgiveness than permission" (EAFP). This tends to be more Pythonic (and thus, preferred). You don't *really* care what the version just, but whether or not the string module has a Template object. Besides, what if some bright admin at some customer decides to backport the Template implementation to their 2.4 installation? The first form would load your compatibility version, probably not what they were hoping when they put in the effort to backport. This might be more obvious if the example was ctypes, a module which is available recently as part of Python proper, but can also be built for older versions of Python (for some vague definition of "older"). Some of your customers might have installed the external version to work with their Python installation. Your simple version test would miss that. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From lewis.sarah93 at yahoo.com Thu Dec 4 23:43:25 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 20:43:25 -0800 (PST) Subject: Reduice Debt Message-ID: <7dc218e0-caba-4834-85eb-44fb5eefa469@w34g2000yqm.googlegroups.com> Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From warren at delsci.com Sat Dec 6 14:38:51 2008 From: warren at delsci.com (Warren DeLano) Date: Sat, 6 Dec 2008 11:38:51 -0800 Subject: "as" keyword woes Message-ID: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> > Date: Fri, 05 Dec 2008 22:22:38 -0800 > From: Dennis Lee Bieber > Subject: Re: "as" keyword woes > To: python-list at python.org > Message-ID: > > I'm still in the dark as to what type of data could > even inspire the > use of "as" as an object name... A collection of "a" objects? In which > case, what are the "a"s? Please let me clarify. It is not "as" as a standalone object that we specifically miss in 2.6/3, but rather, the ability to use ".as" used as a method or attribute name. In other words we have lost the ability to refer to "as" as the generalized OOP-compliant/syntax-independent method name for casting: new_object = old_object.as(class_hint) # For example: float_obj = int_obj.as("float") # or float_obj = int_obj.as(float_class) # as opposed to something like float_obj = int_obj.asFloat() # which requires a separate method for each cast, or float_obj = (float)int_obj # which required syntax-dependent casting [language-based rather than object-based]. Of course, use of explicit casting syntax "(float)" is fine if you're restricting yourself to Python and other languages which support casting, but that solution is unavailable inside of a pure OOP message-passing paradigm where object.method(argument) invocations are all you have to work with. Please note that use of object.asClassname(...) is a ubiqitous convention for casting objects to specific classes (seen in ObjectiveC, Java, SmallTalk, etc.). There, I assert that 'object.as(class_reference)' is the simplest and most elegant generalization of this widely-used convention. Indeed, it is the only obvious concise answer, if you are limited to using methods for casting. Although there are other valid domain-specific uses for "as" as either a local variable or attribute names (e.g. systematic naming: as, bs, cs), those aren't nearly as important compared to "as" being available as the name of a generalized casting method -- one that is now strictly denied to users of Python 2.6 and 3. As someone somewhat knowledgable of how parsers work, I do not understand why a method/attribute name "object_name.as(...)" must necessarily conflict with a standalone keyword " as ". It seems to me that it should be possible to unambiguously separate the two without ambiguity or undue complication of the parser. So, assuming I now wish to propose a corrective PEP to remedy this situation for Python 3.1 and beyond, what is the best way to get started on such a proposal? Cheers, Warren From manu3d at gmail.com Sun Dec 14 08:00:18 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Sun, 14 Dec 2008 05:00:18 -0800 (PST) Subject: Bidirectional Networking References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <6qeht0Fc3541U1@mid.individual.net> <782258db-2bdc-45a7-8d8f-7a036d574985@t26g2000prh.googlegroups.com> <2cf74767-e331-4fa6-8915-8f87ba01ca34@l33g2000pri.googlegroups.com> Message-ID: On Dec 14, 4:10 am, "Gabriel Genellina" wrote: > daemon became a property in Python 2.6; setDaemon was the only way to set > it in previous versions. I thought that might be the case! The documentation is a bit vague: http://docs.python.org/library/threading.html?highlight=threading#threading.Thread.setDaemon Should we maybe add "New in 2.6" to the Thread.daemon paragraph? Manu From jcd at sdf.lonestar.org Fri Dec 12 10:35:11 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Fri, 12 Dec 2008 10:35:11 -0500 Subject: newbie question: if var1 == var2: In-Reply-To: <87y6ymzecp.fsf@daycos.com> References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> <87y6ymzecp.fsf@daycos.com> Message-ID: <1229096111.26125.3.camel@aalcdl07.lib.unc.edu> On Thu, 2008-12-11 at 13:44 -0600, Kirk Strauser wrote: > At 2008-12-11T17:24:44Z, rdmurray at bitdance.com writes: > > > >>> ' ab c \r\n'.rstrip('\r\n') > > ' ab c ' > > >>> ' ab c \n'.rstrip('\r\n') > > ' ab c ' > > >>> ' ab c '.rstrip('\r\n') > > ' ab c ' > > I didn't say it couldn't be done. I just like the Perl version better. Python has a version equally good: def chomp(s): return s.rstrip('\r\n') chomp("foo\n") chomp("foo") chomp("perl\r\n") You'll hardly miss Perl at all. ;) From jody.goldberg at gmail.com Mon Dec 8 20:19:27 2008 From: jody.goldberg at gmail.com (JodyGnumeric) Date: Mon, 8 Dec 2008 17:19:27 -0800 (PST) Subject: getting error...... Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in open_workbook biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) File "C:\Python25\Lib\site-pack References: <6c76b050-5b47-46f3-9097-5c58979b6913@s9g2000prg.googlegroups.com> Message-ID: <16d767d6-be4a-49eb-af5c-3d9e74b45458@m22g2000vbl.googlegroups.com> On Dec 8, 5:54?am, John Machin wrote: > On Dec 8, 6:48?pm, "Gabriel Genellina" wrote: > > > > > En Fri, 05 Dec 2008 02:31:01 -0200, pk sahoo ? > > escribi?: > > > > hallo everybody, > > > when i am running the following command > > > >>>> import xlrd > > >>>> book=xlrd.open_workbook("C:\\a.xls") > > > > i am getting the following error.. > > > > *Traceback (most recent call last): > > > ? File "", line 1, in > > > ? File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in > > > open_workb > > > ook > > > ? ? biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) > > > ? File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 1323, in > > > getbof > > > ? ? raise XLRDError('Expected BOF record; found 0x%04x' % opcode) > > > xlrd.biffh.XLRDError: Expected BOF record; found 0x3f3c* > > > Looks like your a.xls file is not an Excel file (one of the formats ? > > supported by xlrd). > > As 0x3f3c corresponds to the characters ' > This can be verified easily by opening the file with a simple-minded > text editor (e.g. Notepad) ... if the first two lines are > """ > > > """ > then it's an Excel 2003 XML Spreadsheet that's been manually(?) > renamed from .xml to .xls. > > The current xlrd release supports only the binary ("BIFF") format .xls > files created by Excel 3.0 to Excel 2003. The next release (due out > Real Soon Now) will support Excel 2.1 and 2.0 formats [don't ask]. > Very soon after that will come support for Excel 2007 .xlsx which is a > bunch of XML files inside a ZIP file. Support for Excel 2003 > "SpreadsheetML" is way down the to-do list. > > If the OP wants to be able to read the file with xlrd: > (1) Open it with Excel 200[37] and save as a .xls file > or (2) rename it to .xml, start OpenOffice.org Calc, click on File, > click on Open, click on "Files of type", choose "Microsoft Excel 2003 > XML (*.xml)" from the (long, unsorted) drop-down list, ..., and save > as etc etc. Gnumeric is not an option. > > HTH, > John Gnumeric can read this format. 'MS Excel (tm) 2003 SpreadsheetML' From rt8396 at gmail.com Mon Dec 22 12:13:41 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 09:13:41 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: I think when Python was first brought to this dark world by a genius named Guido van Rossum, it had complete dominance in it's niche, actually Python created a niche where none existed before. Since the advent of Ruby(Python closet competitor), Python's hold on this niche is slipping. A lot of Ruby noobies don't even realize that most of Ruby is an out-right plagiarism of Python. But I guess that's OK, because Python has borrowed from other languages itself.. just not in such a -sell your soul- kind of way as Ruby!. Now since Python *is not* the only language on it's block, we have to compete with our main nemesis(Ruby) for survival(I wonder if mats would have been so revolutionary to introduce indention if Guido had not done it first??, it seems to me he is a braces fanboy ;) Now more than ever we must stick to the Zen and clean up Python's warts to keep the dream alive and regain our right full crown. Python is better than Ruby, I have no doubt in my mind, but if we let ruby become -faster- than Python, people will gravitate away from Python. Speed IS important even in high level languages. We must never forget that! The war is not over just because we have Google, Nasa, and ILM. On the Contrary, it has just begun. I believe mats is not going to accept Ruby as 2nd best to Python, he will wage war on Pythonia. And if we fail to preempt this attack, we shall be like the burning ships of pearl harbor! Maybe Guido has a secret weapon up his sleeve(big boy), but 3.0 was defiantly not the bomb! Mats will now take advantage of the weaknesses in Py3000 and run with them. Whispering in everyones ear how much faster Ruby is to Python. And weather you like to hear it or not, this ROR thing is exploding, we must counter attack this vile disgrace to Pythonia. Do not sit back and say "well we are the best and we don't need to try any harder". For you will be left in the evolutionary dust of Ruby. And next year, left wanting... We need to sound the battle cries and gather the legions. Then we shall march across Rubonia and *raise* their cities to the ground. We shall encompass thy house O' Ruby -- and lay waste to it! After we slay thee, we shall breed with thy women and convert thy children. We shall rule with an iron fist!, crushing all resistance to Python's absolute power. Like the great kings of olde, monuments will be erected so all generations shall be witness of our power, and glory. """ O' Python, for the sound of thy chariots will be so fear full no army could stand against thee!""" We shall avenge the atrocities and hypocrocies you have brought upon this world Ruby! And then you shall know that we are the Lord of this world, when our vengeance is cast upon you! I will be monitoring comp.lang.python and over the next 6 months I will conduct a census of the users of this group. So far I have only seen maybe 20 regulars here. I had hoped they numbered several thousand, but i am starting to think more in the hundreds or even less :(. I will post my findings to this group. It shall be a wake up call for those of you who think the war is over. Get off your bums you lazy-coach-potatos, the fight is not over yet. Do not let your eye's become "wide shut"!!! Truth shall be the judge... From castironpi at gmail.com Tue Dec 16 20:36:22 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 16 Dec 2008 17:36:22 -0800 (PST) Subject: How to modify a program while it's running? References: <01584cbd$0$20656$c3e8da3@news.astraweb.com> Message-ID: <1fe20306-39ff-4169-b49e-5ae5dd8159af@v5g2000prm.googlegroups.com> On Dec 16, 7:26?pm, Steven D'Aprano wrote: > On Tue, 16 Dec 2008 13:25:17 -0700, Joe Strout wrote: > > So I'd like to restructure my app so that it can stay running and stay > > logged in, yet I can still update and reload at least most of the code. > > But I'm not sure what's the best way to do this. ?Should I move the > > reloadable code into its own module, and then when I give my bot a > > "reload" command, have it call reload on that module? ?Will that work, > > and is there a better way? > > That should work for functions, but less successfully with classes. The > problem is that existing objects will still have the old behaviour even > after reloading the class. Good catch, Mr. Steven. You could re-query on every call to a method with __getattr__. def __getattr__( I, name ): cls= module.class_to_query return cls.__getattr__( I, name ) #need to call __get__ on this That way, when 'class_to_query' changes, the behavior changes. Here's the implementation: >>> class Behavior( object ): ... def methA( I ): ... print 'methA one' ... >>> class Dynamic( object ): ... def __getattr__( I, key ): ... return getattr( Behavior, key ).__get__( I, Behavior ) ... >>> x= Dynamic( ) >>> x.methA( ) methA one >>> class Behavior( object ): ... def methA( I ): ... print 'methA two' ... >>> x.methA( ) methA two You would have to soft-code 'Behavior' into the initializer of 'Dynamic' as a string, not the class object. From warren at delsci.com Sat Dec 6 23:19:08 2008 From: warren at delsci.com (Warren DeLano) Date: Sat, 6 Dec 2008 20:19:08 -0800 Subject: "as" keyword woes Message-ID: <896B75251BA19745A529B1B867893FA5DB11@planet.delsci.local> > Date: Sat, 6 Dec 2008 12:13:16 -0800 (PST) > From: Carl Banks > Subject: Re: "as" keyword woes > To: python-list at python.org > Message-ID: > > (snip) > > If you write a PEP, I advise you to try to sound less whiny and than > you have in this thread. > > (snip) Ehem, well, such comments notwithstanding, I thank everyone who responded to my latest post on this topic for taking my inquiry seriously, and for providing cogent, focused, well-reasoned feedback while not resorting to name-calling, to false accusations on top of baseless assumptions, or to explicit personal attacks on my competence, sincerity, experience, credibility, or form. To you especially, I am grateful for your input for your years of service to the community and to the noble ideals you embody in the Python project. May the rest of us (not just myself) be ashamed of our lesser conduct and learn from you exemplary performance. So to summarize, having assimilated all responses over the past several days (python-list as well as python-dev, for the newcomers), I now accept the following as self-evident: -> "as", as a Python keyword, is a here to stay: Love it or leave it. -> Likewise ditto for the GIL: if you truly need Python concurrency within a single process, then use a Python implementation other than CPython. Season's greetings to all! Peace. Cheers, Warren From see.signature at no.spam Tue Dec 16 10:51:58 2008 From: see.signature at no.spam (Eric Brunel) Date: Tue, 16 Dec 2008 16:51:58 +0100 Subject: Structure using whitespace vs logical whitespace References: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> Message-ID: On Tue, 16 Dec 2008 10:00:32 +0100, Gabriel Genellina wrote: > En Mon, 15 Dec 2008 14:29:31 -0200, cmdrrickhunter at yaho.com > escribi?: > >> PS. In my opinion the solution would be to have the option of entering >> a "whitespace insensitive" mode which uses C style {} and ;. The >> token to enter it could be as complicated as you want (in fact, it may >> make sense to make it complicated to discourage use unless it's really >> advantageous). I'd sugest {{ and }} or something bigger like {={ } >> =}. Only two problems: 1) I'm sure it would offend Guido's sense of >> language aesthetics 2) I'm sure the idea has been hashed over on this >> newsgroup to death... hence prefering a workaround instead. > > It's a hidden feature, already implemented. Try: > > from __future__ import braces I was almost shocked so I tried it. It's much clearer now... ;-) -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From David Fri Dec 26 21:34:45 2008 From: David (David) Date: Fri, 26 Dec 2008 20:34:45 -0600 Subject: math.sqrt() in new 3.0 version : solution in input() References: Message-ID: On Fri, 26 Dec 2008 15:52:24 -0600, David Lemper wrote: >At the command line this function works correctly > >>> import math > n = input("enter a number > ") > s = math.sqrt(n) > An entry of 9 or 9.0 will yield 3.0 > >Yet the same code in a script gives an error message > Script1 > import math > n = input("enter a number > ") > s = math.sqrt(n) > > Traceback (most recent call last) : > File "", line 1, in > File "script1.py" line 3 in > s = math.sqrt(n) > TypeError : a float is required Problem is the new input() function. Yields a string. Thanks to Scott, Chris, Gabriel & John. Some thought I was not using the Python 3 command line. I was : Python 3.0 (r30:67507... Erratic behavior was that I was sometimes using n = input() and sometimes entering the integer directly into the math.sqrt() function, eg s = math.sqrt(4194304) I cannot find a mention of this in "The Python Tutorial release 3.1" The I&O section discusses output formatting and reading & writing text files. John pointed out its in Guido's "What's New in Python3.0" Indeed its mentioned in PEP 3111, near end of What's New and somewhat obscurely. " raw_input() was renamed to input(). That is the new input() function function reads a line from sys.stdin . . ." Dave Lemper, Texas From google at mrabarnett.plus.com Thu Dec 11 19:39:24 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 12 Dec 2008 00:39:24 +0000 Subject: newbie question: if var1 == var2: In-Reply-To: <44aa0191-e374-4bf0-b039-d05cfa996b1d@p2g2000prn.googlegroups.com> References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> <44aa0191-e374-4bf0-b039-d05cfa996b1d@p2g2000prn.googlegroups.com> Message-ID: <4941B2BC.7080806@mrabarnett.plus.com> Jason Scheirer wrote: > On Dec 11, 3:49 pm, John Machin wrote: >> On Dec 12, 10:31 am, "Rhodri James" >> wrote: >> >> >> >>> On Thu, 11 Dec 2008 19:49:23 -0000, Steve Holden >>> wrote: >>>> Kirk Strauser wrote: >>>>> At 2008-11-29T04:02:11Z, Mel writes: >>>>>> You could try >>>>>> for item in fname: >>>>>> item = item.strip() >>>>> This is one case where I really miss Perl's "chomp" function. It >>>>> removes a >>>>> trailing newline and nothing else, so you don't have to worry about >>>>> losing >>>>> leading or trailing spaces if those are important to you. >>>> ... and it's so hard to write >>>> item = item[:-1] >>> Tsk. That would be "chop". "chomp" would be >>> if item[-1] == '\n': >>> item = item[:-1] >> Better: >> if item and item[-1] == '\n': >> return item[:-1] >> return item > > Best: > > return item \ > if not (item and item.endswith('\n')) \ > else item[:-1] > > Though really you should be using item.rstrip() > Why not just: item[:-1] if item.endswith('\n') else item From Graham.Dumpleton at gmail.com Sat Dec 20 03:42:42 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Sat, 20 Dec 2008 00:42:42 -0800 (PST) Subject: mod_python resources References: <78064e7e-ba2c-4959-b5f8-4d1b928bc5fe@y18g2000yqn.googlegroups.com> <4lsl16-15a.ln1@archaeopteryx.softver.org.mk> Message-ID: On Dec 20, 2:47?pm, "Anjanesh Lekshminarayanan" wrote: > Same requirement here. > But isnt there any mod_python for Python 3.0 ? > Or do we need to build it from source ourselves ? > > I was hoping there would bemod_wsgibinaries for Python 3.0. At this stage it looks like there will not be a mod_python for Python 3.0. If you want the ability to run Python embedded in Apache like mod_python did, use a framework that can host on top of WSGI and host it on mod_wsgi instead. The version of mod_wsgi in subversion repository already supports Python 3.0. Graham From igouy2 at yahoo.com Sat Dec 13 10:17:00 2008 From: igouy2 at yahoo.com (Isaac Gouy) Date: Sat, 13 Dec 2008 07:17:00 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <25b4d503-5073-4e66-8914-ca5fa7b144e1@w39g2000prb.googlegroups.com> Message-ID: <4bb159b5-528c-481e-bfde-9b326a37daa6@u18g2000pro.googlegroups.com> On Dec 12, 6:58?am, bearophileH... at lycos.com wrote: > sturlamolden: > > > On a recent benchmark Java 6 -server beats C compiled by GCC 4.2.3 And > > most of that magic comes from an implementation of a dynamically typed > > language (Smalltalk). [...] > >http://shootout.alioth.debian.org/u32q/benchmark.php?test=all?=all > > That is indeed a nice result, JavaVM has come a long way from the > first one used for applets. That result comes mostly from the fact > that this is a test on a 4-core CPU, that is less easy to manage from > C. You can see that in the single 64-bit core tests:http://shootout.alioth.debian.org/u64/benchmark.php?test=all?=all Whether or not it's less easy to manage from C is unclear, but you are correct to point out few of those C programs have been updated to exploit quadcore - so the reasonable comparison is with C++. And the benchmarks game also provides x86 measurements with programs forced onto a single core which shows GCC ahead http://shootout.alioth.debian.org/u32/benchmark.php?test=all&lang=all > And take a look at the memory used too, up to 34 times higher for the > JVM on the 4-core CPU. > > In the next years people that use low-level languages like C may need > to invent a new language fitter for multi-core CPUs, able to be used > on GPUs too (see the OpenCL), less error-prone than C, able to use the > CPU vector instructions efficiently. (The D language is probably unfit > for this purpose, because even if it's meant to be a system language, > I don't think it can be used much to replace C everywhere it's used > now.) A C+ maybe? :-) > > I agree that CPython may quite enjoy having something built-in like > Psyco, but it's a lot of work for an open source project. Probably > with 1/3 or 1/2 of the work poured on PyPy you may create that > improvement for CPython. Maybe PyPy will someday produce some fruit, > but I think they have used the wrong strategy: instead of trying to > create something very new that someday will work, it's often better to > try to improve something that today everybody uses, AND try to be > useful from almost the very beginning. > > Bye, > bearophile From m.faustino at gmail.com Mon Dec 8 07:47:49 2008 From: m.faustino at gmail.com (=?ISO-8859-1?Q?M=E1rcio_Faustino?=) Date: Mon, 8 Dec 2008 04:47:49 -0800 (PST) Subject: Public imports Message-ID: <9623b0a3-7053-41f1-b116-0cd5e54f39e9@v13g2000vbb.googlegroups.com> Hi, Does Python support public imports instead of the default private? Something like D's "public import" (see ) or even Perl's "export_to_level". Thanks, From casey.mcginty at gmail.com Mon Dec 1 22:19:42 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Mon, 1 Dec 2008 17:19:42 -1000 Subject: Google App Engine Code Challenge - write a tetris playing algorithm In-Reply-To: References: Message-ID: On Sun, Nov 30, 2008 at 2:41 PM, russ.au wrote: > I've got more features to add, depending on how > popular it is.. > Are you going to create a leader board to track the high scores? -------------- next part -------------- An HTML attachment was scrubbed... URL: From rt8396 at gmail.com Tue Dec 23 11:21:57 2008 From: rt8396 at gmail.com (r) Date: Tue, 23 Dec 2008 08:21:57 -0800 (PST) Subject: Python's popularity References: 6rch06Fk4p2U1@mid.individual.net Message-ID: On Dec 23, 10:12?am, je.s.t... at hehxduhmp.org wrote: > r wrote: > > You are the epitimy of an internet troll. A troll tries to hide his > > identity. Why are you so concerned about your TRUE identity. Are the > > I've already stated, and you've already proven, that it's pretty trivial > to ascertain my true identity, if one actually cares. ?OTOH, that's > *not* the case with you. ?Who is hiding now? I told you, my name is Thurstan Howell III. Do you want to know my favorite color too? From aioe.org at technicalbloke.com Mon Dec 8 11:53:08 2008 From: aioe.org at technicalbloke.com (r0g) Date: Mon, 08 Dec 2008 11:53:08 -0500 Subject: Equivalent of 'wget' for python? References: Message-ID: Robert Dailey wrote: > Hi, > > I'm looking for a portable way to download ZIP files on the internet > through Python. I don't want to do os.system() to invoke 'wget', since > this isn't portable on Windows. I'm hoping the core python library has > a library for this. Note that I'll be using Python 3.0. > > Thanks. urllib.urlretrieve(url_of_zip_file, destination_on_local_filesystem). There's also a third argument you can use to link a progress update function of your choosing if you need it. Roger. From ajaksu at gmail.com Tue Dec 23 00:12:01 2008 From: ajaksu at gmail.com (ajaksu) Date: Mon, 22 Dec 2008 21:12:01 -0800 (PST) Subject: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> Message-ID: <90f06b27-39da-4f1a-a878-f3972e942d57@s24g2000vbp.googlegroups.com> On Dec 22, 9:24?pm, r wrote: > You know what i hate more than a troll, a spineless jellyfish who goes > around rating peoples post with one star. You are the lowest form of > life. You are the same type of person who would key someones car in > the parking lot. You do not have the balls to face you enemy. > > If who made a rating were visible, then i would have respect for you, > but since you lurk in the shadows, you are scum. Come out and face me > if you dare! > > I never have rated a post UNLESS i rate it with 5 stars, WHY, you ask, > Because my balls are so big i walk around bow-legged! F'in ?Cowards! That would be me, for at least a dozen of your posts. Glad to know it was more effective than telling you to shut up or calm down. Cnidaria-ly y'rs, Daniel From sjmachin at lexicon.net Mon Dec 8 21:02:07 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 8 Dec 2008 18:02:07 -0800 (PST) Subject: getting error...... Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in open_workbook biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) File "C:\Python25\Lib\site-pack References: <6c76b050-5b47-46f3-9097-5c58979b6913@s9g2000prg.googlegroups.com> <16d767d6-be4a-49eb-af5c-3d9e74b45458@m22g2000vbl.googlegroups.com> Message-ID: On Dec 9, 12:19?pm, JodyGnumeric wrote: > On Dec 8, 5:54?am, John Machin wrote: > > > > > On Dec 8, 6:48?pm, "Gabriel Genellina" wrote: > > > > En Fri, 05 Dec 2008 02:31:01 -0200, pk sahoo ? > > > escribi?: > > > > > hallo everybody, > > > > when i am running the following command > > > > >>>> import xlrd > > > >>>> book=xlrd.open_workbook("C:\\a.xls") > > > > > i am getting the following error.. > > > > > *Traceback (most recent call last): > > > > ? File "", line 1, in > > > > ? File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in > > > > open_workb > > > > ook > > > > ? ? biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) > > > > ? File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 1323, in > > > > getbof > > > > ? ? raise XLRDError('Expected BOF record; found 0x%04x' % opcode) > > > > xlrd.biffh.XLRDError: Expected BOF record; found 0x3f3c* > > > > Looks like your a.xls file is not an Excel file (one of the formats ? > > > supported by xlrd). > > > As 0x3f3c corresponds to the characters ' > > This can be verified easily by opening the file with a simple-minded > > text editor (e.g. Notepad) ... if the first two lines are > > """ > > > > > > """ > > then it's an Excel 2003 XML Spreadsheet that's been manually(?) > > renamed from .xml to .xls. > > > The current xlrd release supports only the binary ("BIFF") format .xls > > files created by Excel 3.0 to Excel 2003. The next release (due out > > Real Soon Now) will support Excel 2.1 and 2.0 formats [don't ask]. > > Very soon after that will come support for Excel 2007 .xlsx which is a > > bunch of XML files inside a ZIP file. Support for Excel 2003 > > "SpreadsheetML" is way down the to-do list. > > > If the OP wants to be able to read the file with xlrd: > > (1) Open it with Excel 200[37] and save as a .xls file > > or (2) rename it to .xml, start OpenOffice.org Calc, click on File, > > click on Open, click on "Files of type", choose "Microsoft Excel 2003 > > XML (*.xml)" from the (long, unsorted) drop-down list, ..., and save > > as etc etc. Gnumeric is not an option. > > > HTH, > > John > > Gnumeric can read this format. 'MS Excel (tm) 2003 SpreadsheetML' [Gnumeric 1.9.1 on Windows XP] I'm sorry; I thought I'd exhausted every possible way of trying to open it. After looking at the file open dialogue box again, I've spotted the "Advanced" button. Here is what you need to do: Have the file named whatever.xls. Click on File / Open , navigate to correct directory, click on Advanced, choose 'MS Excel (tm) 2003 SpreadsheetML' from the File-type drop-down list, choose the file, click on OK. Anything else (Simple (non-Advanced), naming it whatever.xml, ...) produces no response, yes that's zero bits of information, not even a Bzzzzt! noise :-( *AND* when it does open up, a date cell defined by ... 1999-12-31T00:00:00.000 is displayed as "00ort 31at1999" :-( From steve at REMOVE-THIS-cybersource.com.au Wed Dec 10 07:03:07 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 10 Dec 2008 12:03:07 GMT Subject: [OT] Google Groups in bad odour References: <4d5498bf-bbf0-4760-83fc-610729bcbce2@h20g2000yqn.googlegroups.com> Message-ID: <014fa796$0$20670$c3e8da3@news.astraweb.com> On Wed, 10 Dec 2008 02:20:24 -0800, Frank Millman wrote: > Unfortunately it seems that their newsgroup does not have a mail > gateway, so I cannot use gmane. (Please correct me if I am wrong). I > will therefore have to find a suitable news client. Any recommendations? Pan and KNode. -- Steven From grflanagan at gmail.com Sun Dec 28 12:56:23 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Sun, 28 Dec 2008 09:56:23 -0800 (PST) Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> Message-ID: <40b1b762-459b-4d6f-91f0-0a6e68d233ae@a26g2000prf.googlegroups.com> On Dec 28, 5:19?pm, Roger wrote: > Hi Everyone, [...] > When I define a method I always include a return statement out of > habit even if I don't return anything explicitly: > > def something(): > ? ? ? ? # do something > ? ? ? ? return > > Is this pythonic or excessive? ?Is this an unnecessary affectation > that only adds clock ticks to my app and would I be better off > removing "returns" where nothing is returned or is it common practice > to have returns. > It's not particularly excessive but it is uncommon. A nekkid return can sometimes be essential within a function body, so a non-essential nekkid return could be considered just noise. G. From gagsl-py2 at yahoo.com.ar Thu Dec 18 19:11:19 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Dec 2008 22:11:19 -0200 Subject: [Help] The pywinauto Can't select the MDI's menu using the MenuItems() which return []. References: <8c7f10c60812180528k2f755d6aj1564a19efb813db0@mail.gmail.com> Message-ID: En Thu, 18 Dec 2008 11:28:54 -0200, Simon Brunning escribi?: > 2008/12/18 ???? : >> This problem also use the following discription: >> How to use pywinauto to open WORD and select its Menu. >> I can't do that and have no idea why! >> Looking forward your help,Thanks! > > Word can be automated with COM. My golden rule is that automation via > GUI driving is always a last resort. To complement that answer: You'll need the pywin32 package by Mark Hammond http://sourceforge.net/projects/pywin32/ He coauthored the book "Python Programming On Win32"; automating Word (or any other COM application) is covered on that book. I think the freely available chapters cover this specific topic exactly. -- Gabriel Genellina From clp at rebertia.com Mon Dec 22 03:33:56 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 22 Dec 2008 00:33:56 -0800 Subject: Calling ImageMagick's convert In-Reply-To: References: Message-ID: <47c890dc0812220033g49d35ae9w24aede0b438adb4b@mail.gmail.com> On Mon, Dec 22, 2008 at 12:15 AM, cmr.Pent at gmail.com wrote: > Hello group! > > I'm a Python beginner. I'm trying to call ImageMagick's convert > program from my code. > My OS is Debian testing, and my version of Python is 2.5. > > I've just stumbled upon a problem: > > (1) subprocess.call('convert in.png -resize 640x480 out.png', shell = > True) > > works, but none of the following does: > > (2) subprocess.call('convert in.png -resize 640x480 out.png') > (3) subprocess.call(['convert', 'in.png', '-resize 640x480', > 'out.png']) I think this needs to be: subprocess.call(['convert', 'in.png', '-resize', '640x480', 'out.png']) Otherwise, it gets '-resize 640x480' as a single escaped option when it's really 2 options, which is the error message you're getting. You have to split the arguments up just like the shell would, which basically means at whitespace unless quoting is used, which is not the case here. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > (4) subprocess.call(['convert', 'in.png', '-resize 640x480', > 'out.png'], shell = True) > > In these cases, convert program says 'unrecognized option -resize > 640x480'. > At the same time, > > subprocess.call(['ls', '-l']) > > works as expected. > > I'd like to use variant (3), as it seems the most handy. I don't > understand why is shell = True required in case of convert. Is it a > bug in Python, in ImageMagick, or am I missing something very basic > here? > Any hint appreciated. > > Andrey > -- > http://mail.python.org/mailman/listinfo/python-list > From bkamrani at gmail.com Thu Dec 4 05:12:44 2008 From: bkamrani at gmail.com (bkamrani at gmail.com) Date: Thu, 4 Dec 2008 02:12:44 -0800 (PST) Subject: performance question: dictionary or list, float or string? References: <434bf4e3-54f4-4e15-b8b0-510a988f25b8@z1g2000yqn.googlegroups.com> <904a19e9-3800-4d61-aea0-4bdabc0674fa@j32g2000yqn.googlegroups.com> Message-ID: <842b13b2-1df5-4b34-af14-7b082970682b@41g2000yqf.googlegroups.com> About the piece of code you posted, there is something I don't understand. for i, line in data: where data is a file object. Is it legal to write that? I believe it results in "too many values to unpack" or do I miss something? /Ben On Dec 4, 10:26?am, bkamr... at gmail.com wrote: > Matt, really thanks for your comments! > Even thogh it was not a direct answer to my questions, > I like your coding style very much and I think you have a good point. > > About the number of line in the file, because I get that info from > another > in advance. Therefore I thought it could be hard coded. > > BTW, could you recommend a book or a note on points you have mentioned > so that I can learn more like that? > > Thanks, > /Ben > > > # this is just bad style in python: > > line = fil.next(); spl = line.split() > > # better written > > spl = fil.next().split() > > > I would just do it this way: > > > def read_as_list(data, regions=25, maxlines=20000): > > ? ? # If data is a filename, open the file. If it is a file > > ? ? # object or any sequence of 'lines' it should just work. > > > ? ? file_opened = False > > ? ? if isinstance(data, basestring): > > ? ? ? ? data = open(data, 'r') > > ? ? ? ? file_opened = True > > > ? ? forces = [[] for _ in xrange(regions)] > > ? ? try: > > ? ? ? ? for i, line in data: > > ? ? ? ? ? ? if i == maxlines: > > ? ? ? ? ? ? ? ? break > > ? ? ? ? ? ? forces[i % 25].append(line.split()) > > ? ? finally: > > ? ? ? ? if file_opened: > > ? ? ? ? ? ? f.close() > > ? ? return forces > > > Matt > > From wicijowski at gmail.com Sat Dec 27 06:38:31 2008 From: wicijowski at gmail.com (janislaw) Date: Sat, 27 Dec 2008 03:38:31 -0800 (PST) Subject: tkinter 3.0 multiple keyboard events together References: <600d4b68-6fe2-4c2c-b425-1a739430bb54@s9g2000prg.googlegroups.com> Message-ID: <7b5e466c-d75d-4e71-b559-f8a0d3718094@r15g2000prd.googlegroups.com> On 26 Gru, 17:44, Pavel Kosina wrote: > janislaw napsal(a): > > > On 26 Gru, 05:52, Pavel Kosina wrote: > > >> Is it possible to catch in an event more that one key from keyboard? In > >> my code, I can handle always the only one, the first I press, the others > >> are omitted. Say, I press both "4" and "8" and only "4" is catched. > > >> def movePlayer(event): > >> ? ? print (event.keysym) > > > Each keypress triggers another event. Fortunately there are two types > > of events: reaction to press and release. The logic to write to > > recognize those as simultaneous clicks is up to you :) > > Might you give me a little bit more? Just a link to a site where this is > explained and showed would be OK. I really did my best but everything is > bad. > > geon Use google to find the appropriate site, or browse this site, there are plenty of examples. You may want to examine the code I wrote to you to catch the idea: #---------------------- import Tkinter import pprint tk = Tkinter.Tk() f = Tkinter.Frame(tk, width=100, height=100) msg = Tkinter.StringVar() msg.set('Hello') l = Tkinter.Label(f, textvariable=msg) l.pack() f.pack() keys = set() def keyPressHandler(event): keys.add(event.char) display() def keyReleaseHandler(event): keys.remove(event.char) display() def display(): msg.set(str(keys)) f.bind_all('', keyPressHandler) f.bind_all('', keyReleaseHandler) f.mainloop() #---------------- Regards, JW From rogerb at rogerbinns.com Tue Dec 2 14:38:49 2008 From: rogerb at rogerbinns.com (Roger Binns) Date: Tue, 02 Dec 2008 11:38:49 -0800 Subject: Determining number of dict key collisions in a dictionary In-Reply-To: <1228221594.807.1287801527@webmail.messagingengine.com> References: <1228221594.807.1287801527@webmail.messagingengine.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 python at bdurham.com wrote: > Background: I'm working on a project using very large dictionaries (64 > bit Python) and question from my client is how effective is Python's > default hash technique for our data set? Python hash functions return a long which in a 64 bit process is 32 bits on Windows and 64 bits on pretty much every other 64 bit environment. > Their concern is based on the > belief that Python's default dictionary hash scheme is optimized for 32 > bit vs. 64 bit environments and may not have anticipated the additional > range of keys that can be generated in a 64 bit environment. Our keys > are based on 20 to 44 byte ASCII (7-bit) alpha-numeric strings. Why not have them look at the source code? It is well commented and there is another file with various notes. Look at Objects/dictobject.c and Objects/dictnotes.txt A teaser comment for you: Most hash schemes depend on having a "good" hash function, in the sense of simulating randomness. Python doesn't. Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAkk1jsUACgkQmOOfHg372QTeEQCeJwkRphiPeDefkANg1IdG3HH1 oocAoICJk6NGxVmtZTZtLOL4Sv4aCw1n =IqsO -----END PGP SIGNATURE----- From sturlamolden at yahoo.no Fri Dec 12 09:41:27 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 06:41:27 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> Message-ID: On Dec 12, 3:27 pm, "David Cournapeau" wrote: > I want faster function > calls to use with numpy: do you know of any solution ? Pypy certainly > isn't, at least today. An interesting thing for numpy would be to use CUDA. If we can move floating point ops to the GPU, a common desktop computer could yield teraflops. A subclass of ndarray could be written for the nvidia GPU. Using OpenMP within NumPy would also be interesting. There are desktop computers available today with two quadcore processors. There is multiprocessing, which works nicely with numpy. You can even have multiple processes working on ndarrys that point to the same shared memory. Just allocate a multiprocessing.Array and use its buffer to create ndarray views. From aioe.org at technicalbloke.com Mon Dec 8 12:45:00 2008 From: aioe.org at technicalbloke.com (r0g) Date: Mon, 08 Dec 2008 12:45:00 -0500 Subject: How to Write to csv file to create bulk address book References: <5387c7a1-eb04-4d27-826c-d6257298e2db@f40g2000pri.googlegroups.com> Message-ID: k.i.n.g. wrote: > Hi , > > I am new to scripting, I am working on script which would create 'n' > number address book entries into a csv file which would be used to > import into a address book. I need suggestions for the same > > The fileds for csv file are as follows > > ""Title","First Name","Middle Name","Last > Name","Suffix","Company","Department","Job Title","Business > Street","Business Street 2","Business Street 3","Business > City","Business State","Business Postal Code","Business Country","Home > Street","Home Street 2","Home Street 3","Home City","Home State","Home > Postal Code","Home Country","Other Street","Other Street 2","Other > Street 3","Other City","Other State","Other Postal Code","Other > Country","Assistant's Phone","Business Fax","Business Phone","Business > Phone 2","Callback","Car Phone","Company Main Phone","Home Fax","Home > Phone","Home Phone 2","ISDN","Mobile Phone","Other Fax","Other > Phone","Pager","Primary Phone","Radio Phone","TTY/TDD > Phone","Telex","Account","Anniversary","Assistant's Name","Billing > Information","Birthday","Business Address PO > Box","Categories","Children","Directory Server","E-mail Address","E- > mail Type","E-mail Display Name","E-mail 2 Address","E-mail 2 Type","E- > mail 2 Display Name","E-mail 3 Address","E-mail 3 Type","E-mail 3 > Display Name","Gender","Government ID Number","Hobby","Home Address PO > Box","Initials","Internet Free > Busy","Keywords","Language","Location","Manager's > Name","Mileage","Notes","Office Location","Organizational ID > Number","Other Address PO > Box","Priority","Private","Profession","Referred > By","Sensitivity","Spouse","User 1","User 2","User 3","User 4","Web > Page"" > > All the entries written by csv file by script can be random & dummy as > this address book is used for testing purpose. > > > Thank you in advance, > Kanthi Hi Kanthi, the simple case is to make yourself a list of the fields. For each field specify what type of data to generate and a lower and upper bound for it's length/value. fields = [ ("Title", "txt", 0, 4), ("First", "txt", 0, 40), ("Tel", num, 8, 15) etc...] Then repeatedly loop though that list generating random values of the appropriate type and appending them to another list to build records. import random new_record = [] for each_field in fields: if each_field[1] == "txt": r = random.randint( each_field[2], each_field[3] ) new_record.append( r ) elif each_field[1] == "num": r = random.randint( each_field[2], each_field[3] ) s = "".join( [random.choice("qwerty...etc.") for i in range( r )] ) new_record.append( s ) print new_record() Then basically make a big list of these records and squirt them out to file. You might need read up on the random, csv and copy modules and you'll probably want to expand on the data types it can generate. Also I use the following class to choose random words from a specified word list... class WordList: def __init__(self, dictionary_filename): self.dictionary_list = [] f = open(dictionary_filename,'r') for each in f: #print each self.dictionary_list.append(each.rstrip()) f.close() self.dictionary_length = len(self.dictionary_list) def random(self,x): outlist = [] for each in range(0,x): outlist.append(self.dictionary_list[random.randrange(0, self.dictionary_length-1)]) return ' '.join(outlist) This would allow you to say: firstnames = Wordlist('big_list_of_first_names.txt') name = firstnames.random(1) From sjmachin at lexicon.net Mon Dec 22 15:51:11 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 22 Dec 2008 12:51:11 -0800 (PST) Subject: Python-list Digest, Vol 63, Issue 420 References: Message-ID: On Dec 23, 5:31?am, wblu... at verizon.net wrote: > Sent from my Verizon Wireless BlackBerry [snip] That was kind of your parents to let you open your Christmas presents early. From virtual at gmx.de Tue Dec 23 17:08:40 2008 From: virtual at gmx.de (Nikolas Tautenhahn) Date: Tue, 23 Dec 2008 23:08:40 +0100 Subject: SuSE11.1 eclipse 64 pydev can't add python path In-Reply-To: References: Message-ID: Hi, Reimar Bauer wrote: > I can install pydev using the update manager in eclipse for 64 bit from the > SuSE 11.1 repo. But I can't configure pydev without crashing it. > I can select the interpreter /usr/bin/python > and I do see the System PYTHONPATH > Forced builtin libs also looks good. > > But Apply gives me > # > # An unexpected error has been detected by Java Runtime Environment: > # > # SIGSEGV (0xb) at pc=0x00007f2d7abebaed, pid=6544, tid=139832007596368 > # > # Java VM: IcedTea 64-Bit Server VM (1.7.0-b24 mixed mode linux-amd64) > # Problematic frame: > # V [libjvm.so+0x21baed] > # > # An error report file with more information is saved as: > # /home/user/hs_err_pid6544.log > # > # If you would like to submit a bug report, please visit: > # http://icedtea.classpath.org/bugzilla > # The crash happened outside the Java Virtual Machine in native code. > # See problematic frame for where to report the bug. unfortunately I can't help but reproduce the problem. My eclipse was already configured when I updated openSuSE 11.0 to 11.1 so it is not *that* bad for me (only when I install new eggs and want pydev to take notice of them). The question is who is responsible for this... java? pydev? (suse?) If you open a ticket in a bugtracker, please post the url here and I will add myself, too Best regards, Nikolas Tautenhahn From banibrata.dutta at gmail.com Sat Dec 20 03:51:00 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Sat, 20 Dec 2008 14:21:00 +0530 Subject: Check file is In-Reply-To: <7caa7d45-ebbe-4c88-bb50-2f01f7315d07@s9g2000prg.googlegroups.com> References: <7caa7d45-ebbe-4c88-bb50-2f01f7315d07@s9g2000prg.googlegroups.com> Message-ID: <3de8e1f70812200051y73329b4eq95c9c620512e9f0b@mail.gmail.com> AFAI can tell... (from a quick google search), there is only a commercial product that can "read" PDF... i.e. PageCatcher from ReportLabs.http://www.reportlab.org/devfaq.html (look at item 2.1.5) BTW, an apparently, non platform-neutral way may be described here: http://www.daniweb.com/code/snippet618.html Alternatively, you could always use tools like "pdf2txt" to convert PDF into text, and then read it in, however, as you could guess, you completely miss out on the graphics (i.e. images), and the formatting aspects. On Sat, Dec 20, 2008 at 1:36 PM, Harish wrote: > Hi Friends > Is there any utility in python which will help me to read any pdf > files? > > Regards > Harish > -- > http://mail.python.org/mailman/listinfo/python-list > -- regards, Banibrata http://www.linkedin.com/in/bdutta http://octapod.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Dec 24 15:21:12 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2008 18:21:12 -0200 Subject: Doing set operation on non-hashable objects References: <3a87eb6a-13ff-4aea-8835-3a233cc6cfc4@w39g2000prb.googlegroups.com> Message-ID: En Wed, 24 Dec 2008 17:16:59 -0200, <5lvqbwl02 at sneakemail.com> escribi?: > I'm writing an application which is structured roughly as follows: > > "db" is a dict, where the values are also dicts. > A function searches through db and returns a list of values, each of > which is a dict as described above. > I need to perform set operations on these lists (intersection and > union) > However the objects themselves are not hashable, and therefore can't > be in a set, because they are dicts. See this thread from last week: http://groups.google.com/group/comp.lang.python/t/d6818ff713bd4421 > What I really need is a set of pointers, so at the end of the > operation I have the actual objects pointed to. Can I somehow use the > object IDs as set elements, then recreate a list with the actual > objects they point to? If you *only* care about object identity, you might use a dictionary that only compares by identity to anyone else: class nc_dict(dict): "A hashable dictionary that isn't equal to anyone else" def __eq__(self, other): return cmp(id(self),id(other))==0 def __hash__(self): return hash(id(self)) d1 = nc_dict(a=1, b=2, c=3) d2 = nc_dict(b=2, c=0, d=4) d3 = nc_dict(a=1, c=3, e=5) dd1 = nc_dict(x=d1, y=d2) dd2 = nc_dict(x=d1, y=d3) dd3 = nc_dict(y=d2, z=d3, w=d1) l1 = [dd1, dd2] l2 = [dd2, dd3] s1 = set(l1) s2 = set(l2) print s1-s2 print s2-s1 print s1&s2 # instances of nc_dict with the same contents are NOT equal d4 = nc_dict(a=1, b=2, c=3) print d1, d4, d1==d4 # output: False # but we can use this function to compare contents def cmp_contents(d1, d2): try: return cmp(sorted(d1.items()), sorted(d2.items())) except Exception: return 1 # assume they're unequal print cmp_contents(d1,d4)==0 # output: True > How do you get the object back from an ID in python? You don't :) -- Gabriel Genellina From marduk at letterboxes.org Tue Dec 9 16:10:08 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Tue, 09 Dec 2008 16:10:08 -0500 Subject: Is 3.0 worth breaking backward compatibility? In-Reply-To: References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> Message-ID: <1228857008.4109.38.camel@brotherus.rdu.redhat.com> On Tue, 2008-12-09 at 20:56 +0000, Lie Ryan wrote: > Actually I noticed a tendency from open-source projects to have slow > increment of version number, while proprietary projects usually have > big > version numbers. > > Linux 2.x: 1991 Python 3.x.x: 1991. Apache 2.0: 1995. OpenOffice.org > 3.0: > acquired by Sun at 1999. GIMP 2.x: 1995. Wine 1.x: 1993. > One exeption would be GNU Emacs 22: 1984, but according to Wikipedia: "Versions 2 to 12 never existed. Earlier versions of GNU Emacs had been numbered "1.x.x", but sometime after version 1.12 the decision was made to drop the "1", as it was thought the major number would never change." So you can think of Emacs 22 as being 1.22. From stefan_ml at behnel.de Tue Dec 2 15:12:19 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 02 Dec 2008 21:12:19 +0100 Subject: Reverse zip() ? In-Reply-To: <20081202210930.2ac88ec6@usenot.de> References: <20081202210930.2ac88ec6@usenot.de> Message-ID: <493596A3.4010306@behnel.de> Andreas Waldenburger wrote: > we all know about the zip builtin that combines several iterables into > a list of tuples. > > I often find myself doing the reverse, splitting a list of tuples into > several lists, each corresponding to a certain element of each tuple > (e.g. matplotlib/pyplot needs those, rather than lists of points). > > This is of course trivial to do via iteration or listcomps, BUT, I was > wondering if there is a function I don't know about that does this > nicely? I think you're asking about zip(): >>> l=[1,2,3] >>> zip(l,l) [(1, 1), (2, 2), (3, 3)] >>> zip(*zip(l,l)) [(1, 2, 3), (1, 2, 3)] Stefan From tjreedy at udel.edu Mon Dec 1 13:59:51 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Dec 2008 13:59:51 -0500 Subject: optimization In-Reply-To: <18740.10122.833580.878015@montanaro-dyndns-org.local> References: <18740.10122.833580.878015@montanaro-dyndns-org.local> Message-ID: skip at pobox.com wrote: > Neal> I noticed in some profiling, that it seems that: > > Neal> def Func (): > Neal> def something(): > Neal> ... > > Neal> It appears that if Func is called many times, this nested func > Neal> definition will cause significant overhead. Is this true? I > Neal> guess I've become accustomed to decent compilers performing > Neal> reasonable transformations and so have tended to write code for > Neal> clarity. > > It could. OTOH, the code object which implements the something body is > stored as a local var (or a constant, can't remember off the top of my > head), so it's not compiled over and over again. Constant. With 3.0... >>> def f(): def g(): pass >>> import dis >>> dis.dis(f) 2 0 LOAD_CONST 1 (", line 2>) 3 MAKE_FUNCTION 0 6 STORE_FAST 0 (g) 9 LOAD_CONST 0 (None) 12 RETURN_VALUE If the inner function is constant and does not directly access outer function locals, and if every last tick of speed is a concern, then it can be move out and given a name like _outer_helper. I would go for clarity and correctness first, but I would also wonder whether an inner function that is independent of its setting and therefore movable might be turned into something of more general use and usefully moved out for purposes other than just speed. Terry Jan Reedy From alessio.pace at gmail.com Mon Dec 1 12:35:31 2008 From: alessio.pace at gmail.com (Alessio Pace) Date: Mon, 1 Dec 2008 09:35:31 -0800 (PST) Subject: How to distribute a Python app together with its dependencies? References: <2343b577-215b-4b4c-8ea0-00dd49369df1@x38g2000yqj.googlegroups.com> Message-ID: <066f1687-64f4-4d3e-b307-6f1df96a399a@20g2000yqt.googlegroups.com> On 1 Dic, 15:21, Mike Driscoll wrote: > On Nov 30, 6:22?am, Alessio Pace wrote: > > > > > Hi, > > > I have to distribute a Python application which relies on an external > > library, and I'm not very fluent in this kind of stuff with Python (I > > come from the Java world where I would have used the Maven build tool > > to create an "assembly with dependencies" of all it is needed to run > > the app), so I was wondering if someone here could give me some > > suggestions :-) > > > The external library is generally not present on the machines where I > > have to distribute my app, and the set of machines on which I have to > > distribute this application is not known a priori (it is just known > > they are Unix systems). In fact by means of SSH I will have to copy > > (and install) the app+library and make it runnable onto the specified > > destination(s). > > > My question is: how would you do that? ?At the moment my current > > solution is to make a tarball of the sources of my app + the > > "distutils" archive of the external library, copy all into the target > > machine, decompress and install via distutils(*) the external library, > > setup some PYTHONPATH stuff on the destination machine, and finally be > > able to launch the application. > > > (*) specifying a prefix into the user home, as I'm not root there > > > So in the end I was wondering if there is a more elegant way of doing > > this because, as I said before, I'm not very experienced in these kind > > of tasks in Python. > > > Thanks in advance for any suggestion or comment. > > > Alessio Pace. > > I recommend GUI2Exe, a nice wrapper to py2exe, py2app, PyInstaller, > cx_Freeze and bbFreeze: > > http://code.google.com/p/gui2exe/ > > I've only used the py2exe portion of the program, but it works great > and the developers behind the project are very responsive and helpful. > > Mike Hi all and thanks for the replies. Apparenlty I managed to make the standalone application with bbfreeze (used directly), I still have to tune a little bit how it can pack in it also classes which are loaded dynamically, and which from a static examination of the code are not found then... I'll try to give a look at GUI2Exe also, thank you for the suggestion. Regards, Alessio Pace. From steve at holdenweb.com Fri Dec 12 11:53:53 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Dec 2008 11:53:53 -0500 Subject: var or inout parm? In-Reply-To: References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> Message-ID: sturlamolden wrote: > On Dec 12, 5:13 pm, Steve Holden wrote: > >>> It should be the tuple's __setitem__ that was invoked here, not >>> __iadd__, or the parser is faulty. >> OK, so now you are proposing to alter the parser, and possibly the >> implementation of the INPLACE_ADD opcode in eval.c, so can you give us >> the patch for those, please? > > What? Take a look at the code again: > > mytuple[0] += 1 > > should never attempt an __iadd__ on mytuple. > > A sane parser would see this as: > > tmp = mytuple.__getitem__(0) > tmp = tmp.__iadd__(1) > mytuple.__setitem__(0, tmp) # should this always raise an exception? > > >> Discussion of such behavior as a "bug" is also pejorative, since the >> current semantics are the way they are by design. > > Right, this bug is by design. You learned that phrase from a guy in > Redmond? > "It's not a bug, it's a feature" predates Microsoft by several years. If I say you are ugly, that doesn't make it true. Neither does your calling this a bug make it a bug. The fact is that Python doesn't behave the way you want it to. If your friend doesn't want to do what you do, does that make it a bug in his behavior. You're being a little juvenile here. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From pyth0nc0d3r at gmail.com Mon Dec 15 01:56:05 2008 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Mon, 15 Dec 2008 00:56:05 -0600 Subject: HTTPConnection Sending Cookies to server Message-ID: Right now I can login to www.phpbb.com's forums import httplib, urllib params = urllib.urlencode({'username':'TheInfernoSin','password':'PASSWORD','login':1,'sid':'','redirect':'index.php','autologin':1}) headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"} con = httplib.HTTPConnection(url) con.request("POST","/community/ucp.php?mode=login",params,headers) data = con.getresponse() #print data.read() hdrs = data.getheader('set-cookie') header = {"Cookie": hdrs} print header #print hdrs con2 = httplib.HTTPConnection(url) #con2.request("GET","/community/ucp.php",None,header) con2.connect() con2.putrequest("POST","/community/ucp.php") con2.putheader("Cookie",hdrs) con2.endheaders() data = con2.getresponse() print data.read() The first block of code logins in and if printed it'll show the logged in successful html code, but when trying to go to another page and sending that cookie back to the server, it wont allow me to stay logged in. -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Sat Dec 13 17:18:34 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 13 Dec 2008 22:18:34 +0000 Subject: [OT] stable algorithm with complexity O(n) References: Message-ID: "David Hl??ik" writes: > Hi guys, > > i am really sorry for making offtopic, hope you will not kill me, but > this is for me life important problem which needs to be solved within > next 12 hours.. > > I have to create stable algorithm for sorting n numbers from interval > [1,n^2] with time complexity O(n) . > > Can someone please give me a hint. Would be very very thankful! > > Thanks in advance! > D. I don't have an algorithm but I have an implementation :) def sort2(numbers): "sort n positive integers in O(n) provided that they are all < n^2" N = len(numbers) units = [[] for i in xrange(N)] tens = [[] for i in xrange(N)] for n in numbers: units[n % N].append(n) for l in units: for n in l: tens[n / N].append(n) return [n for l in tens for n in l] -- Arnaud From steve at REMOVE-THIS-cybersource.com.au Tue Dec 16 20:34:37 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 17 Dec 2008 01:34:37 GMT Subject: weird dict problem, how can this even happen? References: Message-ID: <01584e96$0$20656$c3e8da3@news.astraweb.com> On Tue, 16 Dec 2008 14:32:39 +0100, Joel Hedlund wrote: > Duncan Booth wrote: >> I think you probably are correct. The only thing I can think that might >> help is if you can catch all the situations where changes to the >> dependent values might change the hash and wrap them up: before >> changing the hash pop the item out of the dict, then reinsert it after >> the change. > > That would probably require a lot of uncomfortable signal handling, > especially for a piece of functionality I'd like to be as unobtrusive as > possible in the application. > >> Alternatively give up on defining hash and __eq__ for FragmentInfo and >> rely on object identity instead. > > Object identity wouldn't work so well for caching. Objects would always > be drawn as they appeared for the first time. No updates would be shown > until the objects were flushed from the cache. Perhaps I don't understand your program structure, but I don't see how that follows. > I've been experimenting with a list cache now and I can't say I'm > noticing any change in performance for a cache of 100 items. 100 items isn't very big though. If you have 50,000 items you may notice significant slow down :) If having many items in the cache is possible, you should consider using a binary search instead of a linear search through the cache. See the bisect module. -- Steven From almar.klein at gmail.com Wed Dec 3 07:09:22 2008 From: almar.klein at gmail.com (Almar Klein) Date: Wed, 3 Dec 2008 13:09:22 +0100 Subject: Multiple equates In-Reply-To: <12cbbbfc0812030345m5afa83d3m518e108d11d3e0fb@mail.gmail.com> References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> <9m3h06-vhh.ln1@lairds.us> <12cbbbfc0812030345m5afa83d3m518e108d11d3e0fb@mail.gmail.com> Message-ID: Hi, what about numpy? import numpy a = numpy.ones((10,),dtype=numpy.bool) I = [1,3,8] a[I]=False print a gives: [ True False True False True True True True False True] Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From info at orlans-amo.be Sun Dec 7 09:32:30 2008 From: info at orlans-amo.be (info at orlans-amo.be) Date: Sun, 7 Dec 2008 06:32:30 -0800 (PST) Subject: how to get a beep, OS independent ? References: <59f10d38-e058-47f0-a7fe-5f25e36dc120@t2g2000yqm.googlegroups.com> Message-ID: <5a3fe3be-0bbc-45d2-b79d-c01ae8319c50@f20g2000yqg.googlegroups.com> Sorry, with import Tkinter Tkinter.Tk().bell() you get a new window for the same price... So it's usefull only when using tkinter From rtw at freenet.co.uk Tue Dec 30 16:35:28 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Tue, 30 Dec 2008 15:35:28 -0600 Subject: Triple quoted string in exec function ? References: Message-ID: Stef Mientki wrote in news:mailman.6399.1230668197.3487.python- list at python.org in comp.lang.python: >>> And, by the way, exec is a *statement*, not a function! >>> > exec ( Init_Code, PG.P_Globals ) > > I've really doubt that this is a statement, > unless I don't understand what a statement is. >>> > In python 2.x the above is a statement that is passed a tuple: http://docs.python.org/reference/simple_stmts.html#exec its a statement like print is: >>> print ( 1,2 ) (1, 2) >>> In 3.x it is a function: http://docs.python.org/3.0/library/functions.html#exec print is also a function in python 3.x, so: >>> print(1, 2) 1 2 >>> Rob. -- http://www.victim-prime.dsl.pipex.com/ From robert.kern at gmail.com Thu Dec 4 18:45:06 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 04 Dec 2008 17:45:06 -0600 Subject: pretty strange behavior of "strip" In-Reply-To: <4938693F.6090709@yahoo.ca> References: <4938693F.6090709@yahoo.ca> Message-ID: Guy Doune wrote: > Hi everybody, > > Could it be a bug????? > > Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> test=['03.html', '06.html', 'questions.html', '04.html', > 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test > ['03.html', '06.html', 'questions.html', '04.html', 'toc.html', > '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test[4] > 'toc.html' > >>> test[4].strip('.html') > 'oc' > > Can't figure out what is going on, really. http://docs.python.org/library/stdtypes.html#str.strip str.strip([chars]) Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped: >>> ' spacious '.strip() 'spacious' >>> 'www.example.com'.strip('cmowz.') 'example' -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From zo0omafrinzocheck at gmail.com Wed Dec 17 16:24:53 2008 From: zo0omafrinzocheck at gmail.com (zo0oma) Date: Wed, 17 Dec 2008 13:24:53 -0800 (PST) Subject: Meet Singles From All Over The World .. FOR FREE !! Message-ID: Meet Singles In Your Area Arabs, American, Russian Singles >From All Over The World Waiting For You At Frinzo Join Frinzo And Start Your Love Life Now Join Frinzo Now For Free !! Enjoy exciting features offered by our site: * Profiles with galleries and audio/video * Personal weblogs and friends-lists * Audio/video chat, IM and recorder * SPAM-blocking and anti-SPAM system * ZIP-codes search, matchmaking and so much more!! http://www.frinzo.com From febaen at gmail.com Mon Dec 15 19:39:09 2008 From: febaen at gmail.com (feba) Date: Mon, 15 Dec 2008 16:39:09 -0800 (PST) Subject: Need help improving number guessing game References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> <01564c98$0$21844$c3e8da3@news.astraweb.com> <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> <4946df78$0$19771$426a74cc@news.free.fr> Message-ID: <1f33580b-84f9-4059-a0f0-b6a8d71325af@b38g2000prf.googlegroups.com> > .strip() returns a copy of the string without leading and ending whitespaces (inlcuding newlines, tabs etc). Ahh. I had removed it because it didn't seem to do anything, but I've readded it. And I understand your dictionary stuff correctly now, I think, and I worked it in. Currently, I have: import random def safeint(prompt="y"): while True: x = input(prompt) try: x = int(x) except ValueError: print("BAD INPUT!") else: break return x def safestr(prompt="y"): while True: x = input(prompt) try: x = str(x) except ValueError: print("BAD INPUT!") else: break return x def customrange(game, lowunsafe=True): game['defrang'] = False #Keeps setup from changing range to defaults while lowunsafe: #makes sure that the low number is positive picklow = safeint(prompt="PLEASE PICK THE LOW NUMBER: ") if picklow < 0: print("LOW NUMBER MUST BE POSITIVE") else: lowunsafe = False pickhigh = safeint(prompt="PLEASE PICK THE HIGH NUMBER: ") if pickhigh - picklow <= 2: #see setup(). print("HIGH MUST BE AT LEAST THREE GREATER THAN LOW") else: game['minr'], game['maxr'] = picklow, pickhigh print("RANGE IS [%s-%s]!" % (game['minr'], game['maxr'])) def wantcustom(game, unsure=True): #Allows user to decide their own range for guessing. while unsure: tryrange = safestr(prompt=\ "WOULD YOU LIKE TO CREATE A CUSTOM RANGE? "\ +"Y/N: ") if tryrange.strip().lower() == "n": game['minr'], game['maxr'] = 1, 99 #Default range. see setup unsure = False elif tryrange.strip().lower() == "y": customrange(game) unsure = False else: print("INVALID INPUT") def samesettings(game, unsure=True): while unsure: keepset = safestr(prompt="USE SAME SETTINGS? Y/N: ") if keepset.strip().lower() == "y": game['minr'], game['maxr'] = 1, 99 #Default range. see setup unsure = False elif keepset.strip().lower() == "n": wantcustom(game) numplayers(game) unsure = False else: print("INVALID INPUT") def setup(game): #minr, maxr make minimum and maximum. Can be adjusted. #Make sure that maxr - minr is at least 3. #1 or less would be impossible. 2 would only have one guess for victory #The first would be unplayable, the second would play itself if game['maxr'] - game['minr'] <= 2: raise ValueError("INVALID RANGE!") #If this fails, check line 43 game['gcount'] = 0 #Reset guess count game['target'] = random.randint(game['minr'], game['maxr']) def playerswitch(game): #Player Switch #if player's a witch: burn(her) if game['player'] is game['player1']: game['player'] = game['player2'] else: game['player'] = game['player1'] def youwin(game): if game['pnum'] == 1: print("CONGRATULATIONS! IT TOOK YOU %s GUESSES" % game ['gcount']) else: game['player']['score'] += 1 end = "CONGRATULATIONS %s! SCORE -- P1:%s P2:%s" print(end % (game['player']['name'],\ game['player1']['score'], game['player2']['score'])) def playagain(game, unsure=True): while unsure: playover = safestr(prompt="PLAY AGAIN? Y/N: ") if playover.strip().lower() == "y": game['play'] = True samesettings(game) setup(game) unsure = False elif playover.strip().lower() == "n": print("GOOD BYE. PLAY AGAIN SOON!") game['play'] = False unsure = False else: print("INVALID INPUT") def autofinish(game): if game['maxr'] - game['minr'] == 2: print("...ONLY ONE OPTION LEFT!") youwin(game) playagain(game) def numplayers(game, unsafe=True): while unsafe: num = safeint(prompt="1 OR 2 PLAYERS?\n> ") if num == 1 or 2: #ONLY allow 1 or 2P. unsafe = False else: print("INVALID INPUT") game['pnum'] = num def guesses(game, unsafe=True): while unsafe: guess = safeint(prompt="[%s-%s]%s>> " % \ #Shows range (game['minr'], game['maxr'],\ #And which player's turn game['player']['name'])) if guess >= game['maxr']: print("NUMBER MUST BE IN RANGE") guesses(game) guesscheck(game) elif guess <= game['minr']: print("NUMBER MUST BE IN RANGE") guesses(game) guesscheck(game) else: unsafe = False game['guess'] = guess def guesscheck(game): if game['guess'] == game['target']: if game['pnum'] == 1: game['gcount'] += 1 youwin(game) playagain(game) elif game['guess'] > game['target']: print("TOO HIGH") if game['pnum'] == 1: game['gcount'] += 1 game['maxr'] = game['guess'] else: print("TOO LOW") if game['pnum'] == 1: game['gcount'] += 1 game['minr'] = game['guess'] def guessing(game): guesses(game) guesscheck(game) if game['pnum'] == 2: playerswitch(game) autofinish(game) def main(game=None): player1, player2 = dict(name="P1",score=0), dict (name="P2",score=0) if game is None: game = dict( player1 = player1, player2 = player2, player = player1, play = True ) print("WELCOME TO THE SUPER NUMBER GUESSING GAME!") wantcustom(game) numplayers(game) setup(game) while game['play'] is True: guessing(game) if __name__ == "__main__": main() >rewrite it once again using objects instead of dicts ? I'd need to find out how those work, and I have a list of python stuff to read piling up anyway... That said, I think for something like that, something that's not a major flaw, I'd prefer to make something else, and maybe work on this again later on. There is only so much guessing numbers one person can take. From anders.olme at gmail.com Fri Dec 12 15:51:42 2008 From: anders.olme at gmail.com (a_olme) Date: Fri, 12 Dec 2008 12:51:42 -0800 (PST) Subject: Umlauts in idle Message-ID: <26880ecf-d0eb-42ab-8ebd-56f64c023999@v39g2000pro.googlegroups.com> Hello all, When I try to use umlauts in idle it will only print out as Unicode escape characters. Is it possible to configure idle to print them as ordinary characters? Best Regards Anders Olme From http Mon Dec 29 20:51:43 2008 From: http (Paul Rubin) Date: 29 Dec 2008 17:51:43 -0800 Subject: Python in C References: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> Message-ID: <7x8wpyph00.fsf@ruckus.brouhaha.com> thmpsn.m.k at gmail.com writes: > 1. Can anyone explain to me what kind of program structuring technique > (which paradigm, etc) CPython uses? How do modules interact together? > What conventions does it use? There are a bunch of docs about this, you could read them. The program is written about the way you would expect if you have worked on interpreters written in C before. > 2. Have there been any suggestions in the past to rewrite Python's > mainstream implementation in C++ (or why wasn't it done this way from > the beginning)? I don't think there has ever been any interest in this. There is an effort under way to rewrite Python in Python. This is called PyPy (you should be able to websearch for it easily) and should be much more advanced than the C implementation. It works now, under some preliminary definition of "working", but it will be a while before it is ready for wide deployment. From LambertDW at Corning.com Thu Dec 11 02:02:15 2008 From: LambertDW at Corning.com (Lambert, David W (S&T)) Date: Thu, 11 Dec 2008 02:02:15 -0500 Subject: if expression source format Message-ID: <84B204FFB016BA4984227335D8257FBA625678@CVCV0XI05.na.corning.com> The "if" expression leads to long statements. Please offer suggestions to beautify this function. For this example use maximum line length marked by the ####'s. Thank you. ############################################################## def compute_wind_chill_temperture(T:'Temperature, dF',s:'Wind speed, mph')->dF: ''' ''' return 35.74 + 0.6215*T + s**0.16*(T*0.4275-35.75) if T < 40 else T From jason.dusek at gmail.com Tue Dec 23 16:31:11 2008 From: jason.dusek at gmail.com (Jason Dusek) Date: Tue, 23 Dec 2008 13:31:11 -0800 Subject: [Haskell-cafe] Initializing GHC from Python In-Reply-To: <4950AC05.9060105@gamr7.com> References: <4950AC05.9060105@gamr7.com> Message-ID: <42784f260812231331h6b8628b0tf8d4c0da0277f269@mail.gmail.com> I upmodded this on Reddit. Thank you for your work. -- Jason Dusek From org.python.pythonlist at pooryorick.com Sat Dec 13 06:29:17 2008 From: org.python.pythonlist at pooryorick.com (=?utf-8?Q?Poor=20Yorick?=) Date: Sat, 13 Dec 2008 11:29:17 +0000 Subject: =?utf-8?B?X19mdXR1cmVfXyBhbmQgY29tcGlsZTogIHVucmVjb2duaXNlZCBmbGFncw==?= Message-ID: <20081213112917.6209.qmail@s461.sureserver.com> I have a future statement in a script which is intended to work in 2.6 and 3. Shouldn't compile flags in __future__ objects essentially be noops for versions that already support the feature? doctest is complaining about unrecognised flags. This illustrates the problem: Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> from __future__ import unicode_literals >>> src = 'a = "hello"' >>> c1 = compile(src,'','exec',unicode_literals.compiler_flag) Traceback (most recent call last): File "", line 1, in ValueError: compile(): unrecognised flags -- Yorick From google at mrabarnett.plus.com Wed Dec 10 12:38:39 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 10 Dec 2008 17:38:39 +0000 Subject: "as" keyword woes In-Reply-To: References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> <493FD8F6.3050803@mrabarnett.plus.com> Message-ID: <493FFE9F.7030000@mrabarnett.plus.com> Patrick Mullen wrote: > On Wed, Dec 10, 2008 at 6:57 AM, MRAB > wrote: >> Aaron Brady wrote: >>> On Dec 9, 12:40 pm, MRAB wrote: >>>> Aaron Brady wrote: >>>>> On Dec 9, 8:28 am, MRAB wrote: >>>>> snip >>>>>> In some languages (I think Delphi is one of them - it's >>>>>> been a while!) some words which would normally be >>>>>> identifiers have a special meaning in certain contexts, but >>>>>> the syntax precludes any ambiguity, and not in a difficult >>>>>> way. "as" in Python was one of those. I certainly wouldn't >>>>>> want something like PL/I, where "IF", "THEN" and "ELSE" >>>>>> could be identifiers, so you could have code like: IF IF = >>>>>> THEN THEN THEN = ELSE; ELSE ELSE = IF; >>>>>> Seehttp://en.wikipedia.org/wiki/PL/I_(programming_language). >>>>>> >>>>> snip That is, 'certainly' doesn't change the meaning of your >>>>> statement any. You wouldn't want it, but King George III >>>>> didn't want the American Revolution. >>>> It's called emphasis. >>> I just take you to have meant, then, +1 on excluding keywords >>> from identifiers. You said it the long way though, so I thought >>> I missed something deeper, that didn't come across. >>> >> IIRC, most computer languages have an LL(1) grammar, which means >> that when they are parsed you need to look at only the next word. >> If you're about to parse a statement and the next word is "IF" then >> you know it's an IF-statement, if it's an identifier then it's >> either a call or an assignment statement (OK, you don't know >> exactly what kind of statement it is at that point, but it works >> out just fine!). >> >> In the example from PL/I, "IF" could be the start of an >> IF-statement "IF THEN" or an assignment statement "IF = >> ". It's a bit more tricky for the parser as well as the >> programmer. >> >> Life is easier if words having special meanings are reserved. >> >> However, that doesn't mean that all special words /must/ be >> reserved (pragmatism beats purity). Sometimes the syntax makes it >> clear and unambiguous, so you can get away with not making it a >> reserved word. The word "as" in Python doesn't need to be reserved >> because the syntax precludes ambiguity, but it's the only such word >> in the language, so it's just tidier to make it reserved too. >> > > I don't have a huge stake in this, but I wouldn't mind a change to > allow anything proceeding a "." or preceeding a "(" to not be > identified as a keyword. Don't you mean 'following a "."'? IMHO if you forbid "bar = True" then you should also forbid "foo.bar = True". As for preceding a "(", what about the call "if(True)"? It looks like an if-statement! > It is obvious to me a s a human reader that something.if is quite a > bit different than just a bare if. And as far as parsing technology > goes, isn't it supposed to go for the biggest match first? I would > not be for allowing bare keywords to be used in the situations > described above, but since we are so used to being able to being able > to have say, myclass.dir() or myclass.len() without them overwriting > the builtin functions, it makes sense to me to be able to define a > myclass.as() or myclass.with() without overwriting the keywords. > Though I know the semantics behind these two things are very > different, the rules I go through when reading the code are very > similar. The parser change might be a hassle, and it might not be > worth it at all of course, but from a conceptual point of view it is > simple. I mean, even now you can do class.__dict__["as"]. > > I guess I'm -1 for full PL/1 craziness, but +1 for qualified keyword > usage. > Parsing isn't about the biggest match. Ideally you want something that's simple without being simplistic. Python is a good example. From lewis.sarah93 at yahoo.com Thu Dec 4 23:57:54 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 20:57:54 -0800 (PST) Subject: Get Debt Fre Message-ID: <82c3f62b-e713-4e22-a484-20233656b8de@33g2000yqm.googlegroups.com> Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From lists at cheimes.de Fri Dec 5 15:41:50 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 05 Dec 2008 21:41:50 +0100 Subject: slow Python 3.0 write performance? In-Reply-To: References: Message-ID: Istvan Albert wrote: > I see, thanks for the clarification. > > I will make the point though that this makes python 3.0 unsuited for > anyone who has to process data. One could live with slowdowns of say > 20-50 percent, to get the goodies that 3.0 offers, but when a process > that takes 1 second suddenly starts to take 10, it is makes the > situation untenable. The speed issue slipped through the alpha and beta releases. Apparently no user has tested Python 3.0 with large files so far. Some bugs just can't be found by the developers. I've fixed the read() slowness yesterday. You'll get the fix in the next release of Python 3.0 in a couple of weeks. Christian From bdesth.quelquechose at free.quelquepart.fr Sun Dec 21 14:28:55 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 21 Dec 2008 20:28:55 +0100 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> Message-ID: <494ea6ab$0$7769$426a74cc@news.free.fr> walterbyrd a ?crit : > On Dec 20, 5:05 pm, Roy Smith > >> He got really hung up on the % syntax. > > I guess it's good to know that there is, at least, one person in the > world doesn't like the % formatting. As least the move was not > entirely pointless. > > But, you must admit, of all the things people complain about with > Python, the % formatting is probably one of the least common > complaints. Complaints about Python's speed seem much more common. People complaining about the perceived issues wrt/ Python's speed are welcome to fix it. As far as I'm concerned, I find the perfs more than acceptable when you take Python's dynamism into account. Strange enough, no one seems to complain about PHP or Ruby's performances... > Yet, 3.0 makes the speed worse, first make it right, then make it fast... > and "fixes" a non-problem. > > I can see where the new formatting might be helpful in some cases. > But, I am not sure it's worth the cost. Err... _Which_ cost exactly ? From nick at craig-wood.com Thu Dec 4 07:30:47 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 04 Dec 2008 06:30:47 -0600 Subject: How can I do this (from Perl) in Python? (closures) References: <68b8294c-8771-4b02-bd46-2f25f5e01602@j35g2000yqh.googlegroups.com> Message-ID: Duncan Booth wrote: > excord80 at gmail.com wrote: > > > I just came across http://www.perl.com/pub/a/2002/05/29/closure.html > > and wanted to try the "canonical example of closures" in Python. I > > came up with the following, but it fails: > > > > def make_counter(start_num): > > start = start_num > > def counter(): > > start += 1 > > return counter > > The other answers you got will work, but here's an alternative to > consider: you can convert the function into a generator and then just > move the variable inside. > > >>> def make_counter(start_num): > def counter(): > start = start_num > while 1: > yield start > start += 1 > return counter().next Interesting... You can also write it without nested functions / closures def counter(x): while 1: yield x x += 1 def make_counter(start_num): return counter(start_num).next I expect the machinery is similar between generators and closures, but with generators it is a lot more obvious exactly which version of which variable you are using! In fact you can always do what you can do with a closure with the above technique I think... def make_closure(*args, **kwargs): # initialisation to local vars def closure(): # stuff, being careful with nonlocal args & kwargs return result vs def closure(*args, **kwargs): # initialisation to local vars while 1: # normal stuff using args and kwargs yield result def make_closure(*args, **kwargs): return closure(*args, **kwargs).next I still prefer doing it explicitly with a class though ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From jstroud at mbi.ucla.edu Sun Dec 7 06:57:07 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 07 Dec 2008 03:57:07 -0800 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Rasmus Fogh wrote: > Dear All, > > For the first time I have come across a Python feature that seems > completely wrong. After the introduction of rich comparisons, equality > comparison does not have to return a truth value, and may indeed return > nothing at all and throw an error instead. As a result, code like > if foo == bar: > or > foo in alist > cannot be relied on to work. > > This is clearly no accident. According to the documentation all comparison > operators are allowed to return non-booleans, or to throw errors. There is > explicitly no guarantee that x == x is True. I'm not a computer scientist, so my language and perspective on the topic may be a bit naive, but I'll try to demonstrate my caveman understanding example. First, here is why the ability to throw an error is a feature: class Apple(object): def __init__(self, appleness): self.appleness = appleness def __cmp__(self, other): assert isinstance(other, Apple), 'must compare apples to apples' return cmp(self.appleness, other.appleness) class Orange(object): pass Apple(42) == Orange() Second, consider that any value in python also evaluates to a truth value in boolean context. Third, every function returns something. A function's returning nothing is not a possibility in the python language. None is something but evaluates to False in boolean context. > But surely you can define an equal/unequal classification for all > types of object, if you want to? This reminds me of complex numbers: would 4 + 4i be equal to sqrt(32)? Even in the realm of pure mathematics, the generality of objects (i.e. numbers) can not be assumed. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From bearophileHUGS at lycos.com Fri Dec 5 17:19:35 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 5 Dec 2008 14:19:35 -0800 (PST) Subject: slow Python 3.0 write performance? References: Message-ID: <012eed1c-78ee-4ea6-9ed3-9ca5ea012b73@d23g2000yqc.googlegroups.com> Christian Heimes: > I've fixed the read() slowness yesterday. You'll get the fix in the next > release of Python 3.0 in a couple of weeks. Thank you. Bye, bearophile From enleverlesX.XmcX at XmclaveauX.com Mon Dec 22 11:44:13 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Mon, 22 Dec 2008 17:44:13 +0100 Subject: join a samba domain In-Reply-To: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> References: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> Message-ID: <494fc690$0$9382$ba4acef3@news.orange.fr> Hi! If you are under Vista, you must change the LSA parameter. See: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa LMCompatibilityLevel try with value 1 or 0 And use a Samba not too old. @-salutations -- Michel Claveau From aboudouvas at panafonet.gr Sun Dec 7 12:39:02 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Sun, 7 Dec 2008 09:39:02 -0800 (PST) Subject: Netbeans Early Access and Python3 References: Message-ID: On Dec 6, 12:54?pm, king kikapu wrote: > Hi, > > have anyone using this release of NetBeans (6.5 with Python support) > with Python 3 without any problems ? I mean, does it work with Python3 > or only with 2.x ? No-one is using NetBeans for Python development ?? From fakeaddress at nowhere.org Tue Dec 2 20:55:27 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 02 Dec 2008 17:55:27 -0800 Subject: Reverse zip() ? In-Reply-To: References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> Message-ID: <6ElZk.8756$Ei5.6992@flpi143.ffdc.sbc.com> Zac Burns wrote: > There is a problem with this however, which prompted me to actually > write an unzip function. > > One might expect to be able to do something like so (pseudocode)... > > def filesAndAttributes(): > files = walk() > attributes = [attr(f) for f in files] > return zip(files, attributes) You could do away with that zip and just let the list comprehension return tuples. [(f, attr(f)) for f in walker()] > files, attributes = zip(*filesAndAttributes()) > > The corner case is when dealing with empty lists and there aren't > enough items to unpack. Can you give a concrete example? > The unzip function therefore has an elementsForEmpty keyword that > handles this case. Perhaps something like this could be added to zip? The built-in zip stops when any of the given iterables stops. The itertools module has izip_longest (or zip_longest in Python 3), which takes a fillvalue argument. Perhaps that's what you want? -- --Bryan From ldo at geek-central.gen.new_zealand Fri Dec 5 05:28:48 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 05 Dec 2008 23:28:48 +1300 Subject: Don't you just love writing this sort of thing :) References: <0148b086$0$20670$c3e8da3@news.astraweb.com> Message-ID: In message <0148b086$0$20670$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > Since the context has been deleted, it's hard to tell whether the code as > written by Lawrence ... If you want to reply to my message, reply to my message, don't reply to my reply to someone else's reply to my message. From prologic at shortcircuit.net.au Tue Dec 16 20:35:53 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 17 Dec 2008 11:35:53 +1000 Subject: How to modify a program while it's running? In-Reply-To: <01584cbd$0$20656$c3e8da3@news.astraweb.com> References: <01584cbd$0$20656$c3e8da3@news.astraweb.com> Message-ID: On Wed, Dec 17, 2008 at 11:26 AM, Steven D'Aprano wrote: >> So I'd like to restructure my app so that it can stay running and stay >> logged in, yet I can still update and reload at least most of the code. >> But I'm not sure what's the best way to do this. Should I move the >> reloadable code into its own module, and then when I give my bot a >> "reload" command, have it call reload on that module? Will that work, >> and is there a better way? > > That should work for functions, but less successfully with classes. The > problem is that existing objects will still have the old behaviour even > after reloading the class. You need to build a subscribe/unsubscribe facility. Or a plugin system :) My IRC/Jabber bot kdb uses such features and is capable of loading/unloading/reloading plugins on the fly. YOu're welcome to borrow some of it's code :) http://hg.softcircuit.com.au/projects/kdb/ cheers James From Scott.Daniels at Acm.Org Mon Dec 29 20:07:32 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 29 Dec 2008 17:07:32 -0800 Subject: get method In-Reply-To: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> Message-ID: Ross wrote: > ... Use get to write histogram more concisely. You should be able to > eliminate the if statement. > > def histogram(s): > d = dict() > for c in s: > d[c]= d.get(c,0) > return d > > This code returns a dictionary of all the letters to any string s I > give it but each corresponding value is incorrectly the default of 0. > What am I doing wrong? How is this code supposed to count? --Scott David Daniels Scott.Daniels at Acm.Org From jstroud at mbi.ucla.edu Mon Dec 15 05:40:08 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 15 Dec 2008 02:40:08 -0800 Subject: Need help improving number guessing game In-Reply-To: References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> Message-ID: feba wrote: > I don't see the aim of your changes to setup(). I can kinda understand > checking to make sure that you didn't make the minimum higher than the > maximum, but I think where you put minr/maxr would make it use the > same minr/maxr as the end of the previous game, wouldn't it? No. Each function call creates its own name space. The function as Bruno has written it will have default values (mini & maxi). A call to this function can set different values optionally: setup(2) #==> range from 2 to 99 setup(maxi=101) #==> range from 1 to 101 setup(5, 10) #==> range from 5 to 10 setup(10, 5) #==> throws an error >> Minor point for a short program, but still good practice : use >> constants. IE : > > I had done this initially, but it seemed wasteful and needlessly > confusing in this situation. No. Tracking down and changing hard-coded values within a module is wasteful and needlessly confusing. Creating well named and well documented module level constants is good style and will make your life easier in the long run. >> I assume 'p1sc' means "player_1_score" ? >> If so, you may want to use a dict for scores: > > I don't really understand dicts yet; actually, the tutorial I'm > following (http://www.briggs.net.nz/log/writing/snake-wrangling-for- > kids/ , designed for tweens, but other than the pointless anecdote and > joke here and there, I've found it a very good guide) doesn't even > seem to mention them, from a search of the pdf. Actually, apparently I > stopped and started working on this just before the chapter on > functions and modules. scores = {'player 1' : 0, 'player 2' : 0 } scores['player 2'] = 10 #==> now player 2's score is 10 scores['player 1'] += 1 #==> now player 1's score is 1 print scores['player 0'] #==> prints "0" print scores['player 2'] * 2 #==> prints "20" If you get that, you'll have about all you need to know about dicts to use them for keeping track of scores (and other values) in your game. > I'll look into that later on, but for now I'm pretty happy with how it > works. Try it sooner rather than later. I didn't get this kind of advice when I was first learning. It would have shaved months from my learning curve. >> You should either put this in it's own function (could be named 'main'), >> or at least "protect" it with an "if __name__ == '__main__':" test. > > Could you go into a bit more detail on this? I don't understand what > should be its own function, nor do I understand what that line would > do or how to use it. The idea is that everything you write is reusable and can be imported as a module. Upon importing a module, it's code is executed. So, as written, if someone imports it as a library module, they will start playing the game. Wrapping in the "if __name__ == '__main__':" test prevents the main loop of the game from executing on import. Only when the module is "__main__" will that test evaluate to true and its commands execute. For small programs like you have here, I'd do it like this (again combining ideas): def num_players(game, prompt='1 or 2 Players?\n> '): while True: num = input(prompt) try: num = int(num) except ValueError: print "Bad Value" else: break game['pnum'] = num def main(game=None): if game is None: game = {} print("WELCOME TO THE SUPER NUMBER GUESSING GAME!") num_players(game) game['play'] = 1 # P1 goes first game['player'] = "P1" #Scores, keep track of times player guessed first. game['p1sc'], game['p2sc'] = 0, 0 setup(game) while game['play'] == 1: guessing(game) if __name__ == "__main__": main() I just threw a little advanced stuff at you. But you would be doing yourself a huge favor if you struggled to understand it. The idea is that since game is a dict, you can modify game inside of the functions, and all you do is pass the game around to functions that need the values of its contents. For example: def setup(game): game['a'], game['b'] = 1, 99 game['target'] = random.randint(a, b) def playagain(game): playover = input("PLAY AGAIN? Y/N: ") if playover.strip().lower() == "y": game['play'] = 1 setup(game) else: print("GOOD BYE. PLAY AGAIN SOON!") quit() Notice that I just made return values obsolete. You will also notice that management of all of your values now becomes more tractable using the mutability of dict ("game"). Long, ugly lines now become simple function calls. See if you can understand what I'm doing here and try to propagate the idea through your game using the game dict. If you can do it, you'll be at least 80% of the way to understanding object oriented programming, by the way. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From zapwireDASHgroups at yahoo.com Mon Dec 29 18:49:46 2008 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Mon, 29 Dec 2008 15:49:46 -0800 Subject: Easy-to-use Python GUI References: Message-ID: Thanks to everyone who responded; I'll be checking out the various toolkits people have listed! ---Joel From venutaurus539 at gmail.com Wed Dec 3 02:06:50 2008 From: venutaurus539 at gmail.com (venutaurus539 at gmail.com) Date: Tue, 2 Dec 2008 23:06:50 -0800 (PST) Subject: Obtaining SMTP address of a sender and receiver of an outlook mail Message-ID: Hi all, I am trying to use python for extracting contents of an outlook email. For extracting the list of Recipients addresses I tried using the "MAPI.message.Recipients.Address" property, but the problem I am facing is that it is giving the complete DN name which is putting me in further complications. Is there any way to obtain the actual SMTP mail address (username at domain.com) from the above object? I searched for it in the MSDN help but couldn't succeed. Thanks in advance, Venu From mh at pixar.com Wed Dec 10 16:47:18 2008 From: mh at pixar.com (mh at pixar.com) Date: Wed, 10 Dec 2008 21:47:18 GMT Subject: var or inout parm? References: Message-ID: Chris Rebert wrote: > Not directly possible or encouraged. You can emulate it by sticking > the value in a container object (e.g. list) though: Thanks, that's just what I needed. I'm using this to monkeypatch a test driver into some code that I can't touch, otherwise I would just have the function return a tuple with the replacement values. Cheers! Mark -- Mark Harrison Pixar Animation Studios From simonharrison.uk at googlemail.com Tue Dec 9 06:21:29 2008 From: simonharrison.uk at googlemail.com (simonh) Date: Tue, 9 Dec 2008 03:21:29 -0800 (PST) Subject: Beginner trying to understand functions. References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> <9df7549a-f28b-4d39-b105-90c099f472f2@z28g2000prd.googlegroups.com> <040a2896-be99-477e-909c-c55c5a0e6665@y1g2000pra.googlegroups.com> Message-ID: Thanks for the extra tips Ivan and Bruno. Here is how the program looks now. Any problems? import sys def get_name(): name = input('Please enter your name: ') print('Hello', name) def get_age(): try: return int(input('Please enter your age: ')) except ValueError: print('That was not a valid number. Please try again.') return get_age() def check_age(age,min=18,max=31): if age < min: print('Sorry, too young.') elif age >= max: print('Sorry, too old.') else: print('Come on in!') def again(): response = input('Try again? Y or N: ') while response != "Y": if response == 'N': print('Program finished.') input('Press any key to exit.') sys.exit() else: return response run() def run(): get_name() a = get_age() check_age(a) again() run() From jstroud at mbi.ucla.edu Fri Dec 5 17:13:37 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 05 Dec 2008 14:13:37 -0800 Subject: dict subclass and pickle bug (?) In-Reply-To: References: <6J7_k.6212$hc1.5967@flpi150.ffdc.sbc.com> Message-ID: James Stroud wrote: > Terry Reedy wrote: >> because there is no bug to fix. I have suggesting closing. > > May I suggest to add something to this effect within the issue itself so > others won't spend time trying to figure out why the "bug" is still > open? Sorry, you did that. James From rdmurray at bitdance.com Fri Dec 19 21:42:14 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Sat, 20 Dec 2008 02:42:14 +0000 (UTC) Subject: ANN: New Book: Programming in Python 3 References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> <6r25ckFejl4vU1@mid.individual.net> <015c4890$0$20656$c3e8da3@news.astraweb.com> Message-ID: Quoth Steven D'Aprano : >The second exception is if the word ends with an S. In British English, >you put the apostrophe after the S: > >Thomas' approach is wholly practical. > >In American English, they often (but not always) add an extra S: > >Thomas's approach is wholly practical. > >which in my opinion is logical but ugly and should be avoided. I disagree. For indicating the possessive of the plural ("the books' spines were damaged), putting the apostrophe after makes perfect sense. However, when a word like "Thomas" is made possessive in American English, it is pronounced differently (eg: "Thomases"). In that case, spelling it Thomas's makes it read more like it sounds. So you may find it ugly, but I find it reads better to my ear :) --RDM From rocky at panix.com Sat Dec 20 22:18:44 2008 From: rocky at panix.com (R. Bernstein) Date: Sat, 20 Dec 2008 22:18:44 -0500 Subject: linecache vs egg - reading line of a file in an egg Message-ID: Does linecache work with source in Python eggs? If not, is it contemplated that this is going to be fixed or is there something else like linecache that currently works? Right now, I think pdb and pydb (and probably other debuggers) are broken when they try to trace into code that is part of an egg. Here's what I tried recently: Using this egg: http://pypi.python.org/packages/2.5/t/tracer/tracer-0.1.0-py2.5.egg I install that and look for the filename of one of the functions. Here's a sample session: >>> import tracer >>> tracer >>> tracer.size >>> tracer.size.func_code.co_filename 'build/bdist.linux-i686/egg/tracer.py' >>> tracer.size.func_code.co_firstlineno 216 >>> To read the source for tracer.py, information from "Accessing Package Resources" (http://peak.telecommunity.com/DevCenter/PythonEggs#accessing-package-resources) suggests: >>> from pkg_resources import resource_string >>> print resource_string('tracer', 'tracer.py') This gives me one long string which I can split and then index. Note that I used "tracer.py" above, not "build/bdist.linux-8686/egg/tracer.py" How do tracebacks and things that read frame information deal with the discrepency? Before reinventing the wheel and trying to extend linecache to do something like the above, has someone already come up with a solution? Thanks From rt8396 at gmail.com Mon Dec 22 22:09:06 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 19:09:06 -0800 (PST) Subject: iterating initalizations References: Message-ID: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> I can't check you code because i don't have these modules but here is the code with proper indention import random from rtcmix import * from chimes_source import * from rhythmblock import * from pitchblock import * indexrand = random.Random() indexrand.seed(2) rhythm = rhythmBlock() pitch = pitchBlock() class pitchAndRhythm: def __init__self: self.__abet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def listCreate(self, num): if num > 25: print "Oops. This won't work" else: for a in range(num): b = indexrand.randint(0, 3) c = indexrand.randint(0, 7) index = self.__abet[a] index = [ ] index = index.append(rhythm.rhythmTwist(b, c)) From mikael at isy.liu.se Thu Dec 18 11:05:32 2008 From: mikael at isy.liu.se (Mikael Olofsson) Date: Thu, 18 Dec 2008 17:05:32 +0100 Subject: confused about __str__ vs. __repr__ In-Reply-To: <6qv9v4Ff1lv9U1@mid.uni-berlin.de> References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> <6qv7kfFeuf65U1@mid.uni-berlin.de> <6qv9v4Ff1lv9U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Yep. And it's easy enough if you don't care about them being different.. > > def __repr__(self): > return str(self) If I ever wanted __str__ and __repr__ to return the same thing, I would make them equal: def __str__(self): return 'whatever you want' __repr__ = __str__ That makes it more obvious to me what's going on. As a bonus, it saves one method call for every repr call. /MiO From stefan_ml at behnel.de Fri Dec 12 09:43:01 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 12 Dec 2008 15:43:01 +0100 Subject: Python is slow In-Reply-To: References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> Message-ID: <49427875$0$30229$9b4e6d93@newsspool1.arcor-online.net> David Cournapeau wrote: > I want faster function > calls to use with numpy: do you know of any solution ? http://cython.org/ Stefan From noone at lewscanon.com Tue Dec 2 22:28:23 2008 From: noone at lewscanon.com (Lew) Date: Tue, 02 Dec 2008 22:28:23 -0500 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <591e8625-7e4d-4db8-ae6c-73c4370f8088@q26g2000prq.googlegroups.com> Message-ID: George Sakkis wrote: > As a Slashdotter would put it... you must be new here ;-) For certain values of "here". I've seen Xah before, and I'm happy to engage if he behaves himself. Some of his initial ideas I actually find engaging. His followups leave a lot to be desired. f/u set to comp.lang.functional. It looks like he's got nothing to offer us Java weenies this time around. -- Lew From phd at phd.pp.ru Mon Dec 1 08:49:27 2008 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 1 Dec 2008 16:49:27 +0300 Subject: SQLObject 0.10.3 Message-ID: <20081201134927.GG19187@phd.pp.ru> Hello! I'm pleased to announce version 0.10.3, a minor bugfix release of 0.10 branch of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.10.3 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.10.2 ----------------- * Changed interpretation of strings in the DB URI for boolean parameters: '0', 'no', 'off' and 'false' are now interpreted as False. * Fixed a bug with incorrect handling of calls like connectionForURI(dburi, cache=False) when dburi already contains some parameters in the URI. * Convert decimal.to_eng_string() to str to work around a bug in Python 2.5.2; see http://mail.python.org/pipermail/python-dev/2008-March/078189.html * Added test_default_style.py. * Fixed a minor bug in SQLiteConnection that fails to parse Enum columns. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From prologic at shortcircuit.net.au Tue Dec 30 18:44:53 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 09:44:53 +1000 Subject: [ANN]: circuits-1.0b1 released! Message-ID: Hi all, I'm pleased to announce the release of circuits-1.0b1 Overview ====== circuits is an event-driven framework with a focus on Component Software Architectures where System Functionality is defined in Components. Components communicate with one another by propagating events throughout the system. Each Component can react to events and expose events to other parts of the system Components are able to manage their own events and can also be linked to other Components. circuits has a clean architecture and has no external dependencies on any other library. It's simplistic design is unmatchable but yet delivers a powerful framework for building large, scalable, maintainable applications and systems. circuits was a core integral part of the pymills library developed in 2006 and was partly inspired by the Trac architecture. Quick Examples -------------------- Hello World! ~~~~~~~~ >>> from circuits.core import listener, Component, Event, Manager >>> >>> class Hello(Component): ... @listener("hello") ... def onHELLO(self): ... print "Hello World!" >>> manager = Manager() >>> manager += Hello() >>> manager.push(Event(), "hello") >>> manager.flush() Hello World! Hello Web! ~~~~~~~ from circuits.lib.web import Server, Controller class HelloWorld(Controller): def index(self): return "Hello World!" server = Server(8000) server += HelloWorld() server.run() Hello Web! (WSGI) ~~~~~~~~~~~~ from circuits.lib.web import Application, Controller class HelloWorld(Controller): def index(self): return "Hello World!" application = Application() application += HelloWorld() Download circuits using easy_install or from here: http://trac.softcircuit.com.au/circuits/downloads or from the Python Package Index. Please visit the circuits website for more information about circuits, or to file bug reports or enhancements. http://trac.softcircuit.com.au/circuits/ --JamesMills -- -- -- "Problems are solved by method" From clp at rebertia.com Thu Dec 11 19:08:11 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 11 Dec 2008 16:08:11 -0800 Subject: Dictionary as Keyword Arguments In-Reply-To: References: Message-ID: <47c890dc0812111608n712c9f2fr2a1949df6b02b75e@mail.gmail.com> On Thu, Dec 11, 2008 at 4:02 PM, bfrederi wrote: > I was wondering if I had a dictionary of keywords and values like so: > > keyword_arg_dict = { > 'attribute': 'stone', > 'contents': 'cave people', > 'path': '/path/to/cave', > 'name': 'Ogg's Cave', > } > > And I had a function that accepted keyword arguments like so: > > make_dwelling( > attribute='stone', > contents='cave people', > path='/path/to/cave', > name='Ogg's Cave', > ) > > Is there any way I could use my keyword_arg_dict as my keyword args > for the make_dwelling function, since I am not the creator of the > make_dwelling function, and need to take that dictionary of key-value > pairs and turn it into keyword-value arguments for the make_dwelling > function? make_dwelling(**keyword_arg_dict) Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > From patrickstinson.lists at gmail.com Mon Dec 1 01:05:35 2008 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Sun, 30 Nov 2008 21:05:35 -0900 Subject: incorrect line reported in traceback In-Reply-To: References: Message-ID: <6214d7a20811302205tad3bdf5n8f690a873d93eaa4@mail.gmail.com> No, I've embedded the interpreter and an editor in my app, which might have something to do with it. I can't run the scripts at the command line because my app provides an API to built-ins that isn't availbel in the standard interpreter. I am simply calling a python method in the script module using PyObject_CallObject(), and fetching the traceback using PyErr_Fetch() and PyErr_Normalize(), like this: PyObject *type, *value, *traceback; PyErr_Fetch(&type, &value, &traceback); PyErr_NormalizeException(&type, &value, &traceback); if(traceback) // traceback.tb_lineno *lineno = ((PyTracebackObject *) traceback)->tb_lineno; On Sun, Nov 30, 2008 at 8:59 PM, John Machin wrote: > On Dec 1, 4:47 pm, "Patrick Stinson" > wrote: >> Is there any reason why the last item in the traceback is one frame >> below the top of the stack? It would be great to show the real line in >> my editor... > > Maybe your anonymous [HINT!] editor is confused. Do you get the same > problem when you run your script at the shell prompt? > -- > http://mail.python.org/mailman/listinfo/python-list > From xahlee at gmail.com Thu Dec 11 13:36:42 2008 From: xahlee at gmail.com (Xah Lee) Date: Thu, 11 Dec 2008 10:36:42 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> Message-ID: <76f52f8a-5520-4cf6-9be6-fe7acb3483f6@s1g2000prg.googlegroups.com> Xah Lee wrote: ? A Example of Mathematica's Expressiveness http://xahlee.org/UnixResource_dir/writ/Mathematica_expressiveness.html On Dec 11, 3:53 am, "William James" wrote: > function normal( ary ) > { var div = Math.sqrt( > ary.map(function(x) x*x).reduce(function(a,b) a+b) ) > return ary.map(function(x) x/div) > > } I run your code in SpiderMonkey: // SpiderMonkey javascript. By William James. function normal(v) { var div=Math.sqrt(v.map(function(x) x*x).reduce(function(a,b) a+b)) return v.map(function(x) x/div) } print normal [3,4]; i got: /Users/xah/Documents/temp/xx.js:3: SyntaxError: missing { before function body: /Users/xah/Documents/temp/xx.js:3: var div=Math.sqrt(v.map(function(x) x*x).reduce(function(a,b) a+b)) /Users/xah/Documents/temp/xx.js: 3: ....................................^ Xah ? http://xahlee.org/ ? From pdorange at pas-de-pub-merci.mac.com Sat Dec 27 03:13:58 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Sat, 27 Dec 2008 09:13:58 +0100 Subject: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> <90f06b27-39da-4f1a-a878-f3972e942d57@s24g2000vbp.googlegroups.com> <62caf93b-0455-4450-9895-8a9d9554f75e@r32g2000vba.googlegroups.com> <1isezkk.51e05y1457jqrN%pdorange@pas-de-pub-merci.mac.com> <3cb2a746-1a43-44a1-9825-7667af9fe2fa@s1g2000prg.googlegroups.com> <1isi4sn.11mpft612g7udcN%pdorange@pas-de-pub-merci.mac.com> <1isk1kn.1s8efppxapfeaN%pdorange@pas-de-pub-merci.mac.com> <301a2968-21d6-475d-958c-890e0fc27249@m15g2000vbl.googlegroups.com> Message-ID: <1islo9k.bm5j6213cuveoN%pdorange@pas-de-pub-merci.mac.com> r wrote: > > > Go to Google groups... it looks perfect :) > > > > It's a usenet group here, nothing to do with google groups. > > To get back to the group subject, what is your actual python projects ? > > I am crusading to bring python scripting to Google SketchUp, do want > to get on board? I've other real project on the run, no crusade just programming. Google sketchup doesn't really interest me, sorry... -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From duncan.booth at invalid.invalid Tue Dec 30 14:40:17 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Dec 2008 19:40:17 GMT Subject: thread, multiprocessing: communication overhead References: Message-ID: mk wrote: >> CMIIW, but I believe your timing function includes the time to launch >> the actual processes and threads, create the synch. objects, etc. You >> might try it again, creating them first, starting the timer, then >> loading them. > > Except I don't know how to do that using timeit.Timer. :-/ > Easy enough: put the code into a class which creates the worker pool when instantiated and has a method to execute the code you want to time. Then you create an instance from the setup argument and time a call to the method. From tn.pablo at gmail.com Tue Dec 9 09:45:06 2008 From: tn.pablo at gmail.com (ptn) Date: Tue, 9 Dec 2008 06:45:06 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> <8b8d1fb3-f49e-49bf-8cfe-eeee5ed16109@r37g2000prr.googlegroups.com> Message-ID: <57eea3ce-0171-44ce-a8cf-d2510b7834e9@a29g2000pra.googlegroups.com> On Dec 6, 10:15?am, "Russ P." wrote: > On Dec 6, 4:32?am, Andreas Waldenburger wrote: > > > > > On Sat, 6 Dec 2008 04:02:54 -0800 (PST) bearophileH... at lycos.com wrote: > > > > class C: > > > ? ? def $method(arg): > > > ? ? ? ? $value = arg > > > > (Note there's no point after $, it's not currently possible). > > > Ruby uses @ and @@ for similar purposes. > > > I agree that the code looks worse, but also shorter to read and write, > > > so in lines of code that use many instance attributes, that short $ > > > syntax helps keep the line shorter. So I may grow to accept this > > > sugar... > > > But that is not the way Python is meant to work. There are several > > tennets in the Zen of Python that don't chime well with this approach. > > "self" is a speaking identifier, "$" isn't. > > Is "@" a "speaking identifier? How about "#" and "!="? Last I heard, > they were all part of Python. Those are operators and the comment starter, not identifiers. I think that the more used an operator/variable is, the least mnemonic it' name has to be. Given that you'll be useing it all the time, you don't need it's name reminding you what it's supposed to be used for. So the "it's not a speaking-identifier" argument is not a good one, in my opinion. However, $ being ugly is a very strong argument. Python is supposed to be beautiful. And sure you can get used to it, just as you can get used to Pearl, assembly language or Brainfuck. By beautiful we mean beautiful at first sight. From steve at holdenweb.com Tue Dec 30 13:46:14 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Dec 2008 13:46:14 -0500 Subject: Parsing Excel spreadsheets In-Reply-To: <495A6033.6040908@wildenhain.de> References: <6a54de23-bea4-40c7-ad7c-22c6eba4bd8a@z6g2000pre.googlegroups.com> <4894d0fe-a238-4675-9e79-0b0755c001e8@y1g2000pra.googlegroups.com> <495A6033.6040908@wildenhain.de> Message-ID: Tino Wildenhain wrote: > r wrote: >> On Dec 30, 10:07 am, "andyh... at gmail.com" wrote: >>> Hi, >>> >>> Can anybody recommend an approach for loading and parsing Excel >>> spreadsheets in Python. Any well known/recommended libraries for this? >>> >>> The only thing I found in a brief search >>> washttp://www.lexicon.net/sjmachin/xlrd.htm, >>> but I'd rather get some more input before going with something I don't >>> know. >>> >>> Thanks, >>> Andy. >> >> xlrd(read only) >> also see pyExcelerator > > which is now replaced by xlwt :-) > I've had very good results with xlrd, having used it to extract data from spreadsheets for storage into a relational database. It's also cross-platform, which means you don't need to run under Windows. I don't know anything at all about xlwt. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From mu at problemlos.ch Thu Dec 18 09:28:36 2008 From: mu at problemlos.ch (Kurt Mueller) Date: Thu, 18 Dec 2008 15:28:36 +0100 Subject: Minor Typo in doc Message-ID: <494A5E14.10508@problemlos.ch> Hi There is a minor typo in the new doc in: http://www.python.org/doc/2.6/library/signal.html ------------------------------------------------------------------ signal.SIG_DFL? This is one of two standard signal handling options; it will simply perform the default function for the signal. For example, on most systems the default action for SIGQUIT is to dump core and exit, while the default action for SIGCLD is to simply ignore it. ------------------------------------------------------------------ SIGCLD should be SIGCHLD Should I make a bug report in http://bugs.python.org? Gr?essli -- Kurt M?ller, mu at problemlos.ch From Ron.Barak at lsi.com Thu Dec 25 02:27:23 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Thu, 25 Dec 2008 07:27:23 +0000 Subject: How to change a generator ? - resolved In-Reply-To: <495278BA.7040301@mrabarnett.plus.com> References: <7F0503CD69378F49BE0DC30661C6CCF6024946E6@enbmail01.lsi.com> <49526B7E.20904@mrabarnett.plus.com> <495278BA.7040301@mrabarnett.plus.com> Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6024946EC@enbmail01.lsi.com> Hi Gabriel, Your remarks fixed my problem. Now my code looks as below, and behaves as expected. Thanks Gabriel. Merry Christmas and Happy Hanukkah, Ron. $ cat generator.py #!/usr/bin/env python import gzip from Debug import _line as line class LogStream(): def __init__(self, filename): self.filename = filename self.input_file = self.open_file(filename) def open_file(self, in_file): try: f = gzip.GzipFile(in_file, "r") f.readline() except IOError: f = open(in_file, "r") f.readline() f.seek(0) return(f) def line_generator(self): print line()+". self.input_file.tell()==",self.input_file.tell() while True: line_ = self.input_file.readline() print line()+". self.input_file.tell()==",self.input_file.tell() if not line_: break yield line_.strip() if __name__ == "__main__": filename = "sac.log.50lines" log_stream = LogStream(filename) log_stream.input_file.seek(0) line_generator = log_stream.line_generator() line_ = line_generator.next() $ python generator.py 23. self.input_file.tell()== 0 26. self.input_file.tell()== 247 $ !wc wc -c sac.log.50lines 6623 sac.log.50lines $ -----Original Message----- From: MRAB [mailto:google at mrabarnett.plus.com] Sent: Wednesday, December 24, 2008 20:00 To: python-list at python.org Subject: Re: How to change a generator ? Gabriel Genellina wrote: > En Wed, 24 Dec 2008 15:03:58 -0200, MRAB > escribi?: > >>> I have a generator whose aim is to returns consecutive lines from a >>> file (the listing below is a simplified version). >>> However, as it is written now, the generator method changes the text >>> file pointer to end of file after first invocation. >>> Namely, the file pointer changes from 0 to 6623 on line 24. >>> >> It might be that the generator method of self.input_file is reading >> the file a chunk at a time for efficiency even though it's yielding a >> line at a time. > > I think this is the case too. > I can think of 3 alternatives: > > a) open the file unbuffered (bufsize=0). But I think this would > greatly decrease performance. > > b) keep track internally of file position (by adding each line length). > The file should be opened in binary mode in this case (to avoid any '\n' > translation). > > c) return line numbers only, instead of file positions. Seeking to a > certain line number requires to re-read the whole file from start; > depending on how often this is required, and how big is the file, this > might be acceptable. > readline() appears to work as expected, leaving the file position at the start of the next line. -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.simionato at gmail.com Thu Dec 4 04:19:41 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 4 Dec 2008 01:19:41 -0800 (PST) Subject: Pythonic design patterns References: Message-ID: <7cfb208a-cdf7-4932-9356-00c0428a8497@d14g2000yqb.googlegroups.com> On Dec 4, 10:09?am, Slaunger wrote: > Hi comp.lang.python > > I am this novice Python programmer, who is not educated as a computer > scientist (I am a physicist), and who (regrettably) has never read the > GOF on design patterns. > > I find myself spending a lot of time in Python making some designs, to > solve some task, which is the end turn out to be closely related to > well established design patterns / programming idioms, which other > users in this forum has been kind enough to point out. Only my > implementations are often not that clean, and I may call things > something different than the normal convention, which is a source of > confusion for myself and others trying to communicate with me. > > I guess I could boost my productivity by learning these well-proven > and well-established design patterns by heart. > > I was therefore wondering if you could recommend a book or a resource > concerning design patterns with special focus on the possibilities in > Python? > > In that manner I may be able to both learn programming more pythonic > AND learn the design patterns. > > -- Slaunger The Python Cookbook (the printed version) is the best you can find in this direction. Also, consider the more recent "Expert Python Programming" by Tarek Ziade'. From sjmachin at lexicon.net Thu Dec 4 18:11:16 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 4 Dec 2008 15:11:16 -0800 (PST) Subject: Checking if an int fits in 32 bits? References: Message-ID: On Dec 5, 7:11?am, Roy Smith wrote: > At first I thought pack() might raise an exception on a value > overflow, that but doesn't seem to be the case: > > >>> [hex(ord(c)) for c in struct.pack('!i', 999999999999999999999L)] > > ['0xde', '0x9f', '0xff', '0xff'] Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 >>> import struct >>> [hex(ord(c)) for c in struct.pack('!i', 999999999999999999999L)] __main__:1: DeprecationWarning: struct integer overflow masking is deprecated ['0xde', '0x9f', '0xff', '0xff'] You must be using an older version of Python. I'd go with Jean-Paul's suggestion of (inline no-function-call- overhead portable no-bit-twiddling) bounds checking. Cheers, John From cournape at gmail.com Fri Dec 12 19:41:09 2008 From: cournape at gmail.com (David Cournapeau) Date: Sat, 13 Dec 2008 09:41:09 +0900 Subject: How do I manually uninstall setuptools (installed by egg)? In-Reply-To: References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> <47c890dc0812091904p12e75510sbe0b8858eb2f6d9e@mail.gmail.com> Message-ID: <5b8d13220812121641u3b3d90dgaa242eec3a9ffc43@mail.gmail.com> On Sat, Dec 13, 2008 at 1:30 AM, Nick Craig-Wood wrote: > David Cournapeau wrote: >> On Thu, Dec 11, 2008 at 10:30 PM, Nick Craig-Wood wrote: >> > David Cournapeau wrote: >> >> On Wed, Dec 10, 2008 at 12:04 PM, Chris Rebert wrote: >> >> > On Tue, Dec 9, 2008 at 6:49 PM, wrote: >> >> >> On Ubuntu, I accidentally manually installed setuptools >> >> >> http://pypi.python.org/pypi/setuptools/0.6c9 (by running the .egg file >> >> >> as a shell script via sudo), and now realize I should just be using >> >> >> apt to take care of my system Python packages. >> >> > >> >> > Really, why? setuptools has more Python packages/programs available >> >> > and updates faster than Debian. >> >> > It's also likely that some of the Debian Python packages are installed >> >> > using setuptools anyway. >> >> > So, why do you think apt and not setuptools is The Right Way(tm)? >> >> >> >> Setuptools is certainly not the right way to install packages >> >> system-wide on debian, it is very likely to break the whole thing. >> > >> > It wouldn't be too difficult to make a .deb target which would collect >> > all the files that did get installed into a package. It would be a >> > rather rough and ready package but would do the job. >> >> Depends what you mean by would do the job: rather rough certainly does >> not mean "would do the job" for something as essential as a package >> IMO. > > Essentially a package has files in it in a fixed possition in the > filesystem. The package manager's (dpkg at this level) job is to keep > track of those file and tell you about conflicts. Yes, but this description is so high level that it hides the difficulty of the task :) First, and firstmost, it is difficult if not impossible to automatically translate from distutils/setuptools file locations to a typical debian (or most other distribution for that matter - the one which follow the FHS) description. Because distutils does not make the distinction between doc, data, etc... as well as for example autotools does. > > You can use alien to turn a tar.gz into a perfectly usable debian > package. It won't have dependencies, or help or any of the other > things a package needs to be a proper package, but it satisfies my > basic needs that all software is installed as packages, so it can be > uninstalled cleanly. This only works for very simple packages - pure python or no dependencies, no post/pre install scripts, etc... If you want to install a web framework, it won't be enough. If you want to install a package which depends on C libraries, it won't work either. > > However when I have to make my stuff work on Windows, I find > easy_install to be a fantastic timesaver as compared to looking for > the package on a web site, downloading it, unpacking it installing it > and then repeating for all the dependencies. I agree that its features are useful. I just don't think the implementation and the design are right - partly because it inherits some fundamental distutils deficiencies with respect to package description. David From python-url at phaseit.net Mon Dec 29 07:44:19 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 29 Dec 2008 12:44:19 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Dec 29) Message-ID: QOTW: "The fundamental economics of software development leads you to open-source software." David Rivas http://www.ddj.com/linux-open-source/212201757 Python 2.5.4 final released (replaces 2.5.3 due to a critical bug) http://groups.google.com/group/comp.lang.python/t/4042c08bbbb783c2/ Doing set operations with non-hashable objects: http://groups.google.com/group/comp.lang.python/t/83972f948754ee36/ Reading a file one line at a time *and* getting accurate line offsets: http://groups.google.com/group/comp.lang.python/t/7cd79e287ebf51cf/ Moving from C to Python: how to represent a sequence of bytes? http://groups.google.com/group/comp.lang.python/t/1ee718148cecc39f/ Keeping track of all instances of a class: http://groups.google.com/group/comp.lang.python/t/3ceee5e64d909bce/ return, return None, or nothing? Which is the right one to choose? http://groups.google.com/group/comp.lang.python/t/99d0ba4075f6684e/ Best way to find the differences between two large dictionaries: http://groups.google.com/group/comp.lang.python/t/4f3220dce8a3cf23/ xkcd Christmas special contains another Python reference: http://xkcd.com/521/ ======================================================================== 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 Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From alia_khouri at yahoo.com Sun Dec 7 07:03:47 2008 From: alia_khouri at yahoo.com (Alia Khouri) Date: Sun, 7 Dec 2008 04:03:47 -0800 (PST) Subject: Source code generation using Python References: <82098706-978f-4920-ac75-57ef3573ac44@x38g2000yqj.googlegroups.com> Message-ID: <3b44efcd-a909-4465-b2aa-f05544aa1c4b@k8g2000yqn.googlegroups.com> > Any suggestions? I've happily used Cheetah with Leo (http://webpages.charter.net/ edreamleo/front.html) to organise and script my code generation needs, but you may also be happy with cog (http://nedbatchelder.com/code/ cog/). AK From clp at rebertia.com Tue Dec 9 22:04:22 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 9 Dec 2008 19:04:22 -0800 Subject: How do I manually uninstall setuptools (installed by egg)? In-Reply-To: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> Message-ID: <47c890dc0812091904p12e75510sbe0b8858eb2f6d9e@mail.gmail.com> On Tue, Dec 9, 2008 at 6:49 PM, wrote: > On Ubuntu, I accidentally manually installed setuptools > http://pypi.python.org/pypi/setuptools/0.6c9 (by running the .egg file > as a shell script via sudo), and now realize I should just be using > apt to take care of my system Python packages. Really, why? setuptools has more Python packages/programs available and updates faster than Debian. It's also likely that some of the Debian Python packages are installed using setuptools anyway. So, why do you think apt and not setuptools is The Right Way(tm)? Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From muhamed.hmd at gmail.com Wed Dec 10 14:09:14 2008 From: muhamed.hmd at gmail.com (john adam) Date: Wed, 10 Dec 2008 11:09:14 -0800 (PST) Subject: conratulations....... Message-ID: conratulatios...... Here's my dear friend largest mobile library programs All you care programs : Witness all the programs in the modern world Alkmiotr Honored by your visit You'll see in the blogger 1.If you are suffering from a virus protection programs most important to you AVG Anti-Virus Free Edition "avG" http://mesotheliomame.blogspot.com/2008/11/pericardial-mesothelioma-and-modern.html 2.If you turn suffering from transmitting the files LimeWire Pro 4.14.7 http://mesotheliomame.blogspot.com/2008/11/overview-of-mesothelioma-cancer.html 3.If you have files you spy on your computer solution Ad-Aware 2008 http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawsuits-faq.html 4.You stronger virus program Ante 2008 Avira AntiVir Personal - Free Antivirus http://mesotheliomame.blogspot.com/2008/11/number-form-of-mesothelioma-pleural.html 5.Now a program of protection and anti-virus and anti-spy files Avast Home Edition http://mesotheliomame.blogspot.com/2008/11/what-to-look-for-in-california.html 6.If you are suffering from non-fast you download this program FrostWire http://mesotheliomame.blogspot.com/2008/11/if-you-are-diagnosed-with-mesothelioma_15.html 7.If you have difficulty loading of the Diaspora and Google Orbit Downloader http://mesotheliomame.blogspot.com/2008/11/if-you-are-diagnosed-with-mesothelioma.html 8.If you have difficulty difficult compression "file" winrar http://mesotheliomame.blogspot.com/2008/11/contacting-mesothelioma-lawyer.html 9.If you are suffering from aAdware/Malware files you solution Malwarebytes' Anti-Malware http://mesotheliomame.blogspot.com/2008/11/scientists-conduct-clincial-trials-of.html 10.Now the most powerful video chat in the world Camfrog Video Chat http://mesotheliomame.blogspot.com/2008/11/new-drug-study-for-abdominal.html 11.Program chat world is a lot mIRC http://mesotheliomame.blogspot.com/2008/11/ohio-mesothelioma-lawyer-help-you-get.html 12.If you have difficulty reading flv files FLV Player http://mesotheliomame.blogspot.com/2008/11/detailed-information-on-mesothelioma.html 13.If you have difficulty download from youtube YouTube Downloader http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawyers-in-high-demand.html 14.If you are suffering from penetrating the strongest program you repel breakthroughs in the world Spybot - Search & Destroy http://mesotheliomame.blogspot.com/2008/11/chemotherapy-treatment-for-mesothelioma.html 15.If you have difficulty with the way they spread the images IrfanView http://mesotheliomame.blogspot.com/2008/11/california-mesothelioma-laws-and.html 16.Now have a major program of the torrent file and upload files BitComet http://mesotheliomame.blogspot.com/2008/11/facing-mesothelioma-without-california.html 17.The program is exclusive download from the Web at high speed Download Accelerator Plus http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-diagnoses-increase_15.html 18.If you are suffering from problems with the performance of the solution you Smart Defrag http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-diagnoses-increase.html 19.If you have difficulty in performing the solution you Advanced WindowsCare Personal http://mesotheliomame.blogspot.com/2008/11/mesothelioma-is-deadly-cancer.html 20.If you have difficulty in operating the sound and video files you solution real player http://mesotheliomame.blogspot.com/2008/11/facts-and-misconceptions-about.html 21.Here is the most important video player program in America GOM Media Player http://mesotheliomame.blogspot.com/2008/11/how-severe-is-mesothelioma-disease.html 22.If you have difficulty operating Flash Games Flash Player http://mesotheliomame.blogspot.com/2008/11/glimpse-at-mesothelioma-info-from-past.html 23.If you have difficulty in cleaning Riggstir professionally you the best solution http://mesotheliomame.blogspot.com/2008/11/detection-of-asbestos-mesothelioma.html 24.If you turn suffering from your computer and the difficulty you download this program"System Mechanic" http://mesotheliomame.blogspot.com/2008/11/brief-overview-of-malignant.html 25.If you are suffering from problems in the cleaning solution you Riggstir http://mesotheliomame.blogspot.com/2008/11/mesothelioma-and-911.html 26.Use the latest hour computer in the world in the magnificence of beauty http://mesotheliomame.blogspot.com/2008/11/precise-idea-about-pericardial.html 27.If you have difficulty in maintaining from hard disk http://mesotheliomame.blogspot.com/2008/11/mesothelioma-at-glance.html 28.If you have difficulty in managing personal and protection of your system you program http://mesotheliomame.blogspot.com/2008/11/financial-burden-of-mesothelioma.html 29.If you have difficulty in recording data and operation of your system http://mesotheliomame.blogspot.com/2008/11/how-to-find-mesothelioma-lawyer.html 30.Here's this program that offers you much time http://mesotheliomame.blogspot.com/2008/11/hurricane-victims-at-risk-for.html 31.If you have difficulty in browsing files http://mesotheliomame.blogspot.com/2008/11/3-top-florida-mesothelioma-lawyer.html 32.Here's this program, which automatically corrects the mistakes of your system security http://mesotheliomame.blogspot.com/2008/11/if-diagnosed-with-mesothelioma-call.html 33.The enjoyment of this program to register images from camera to the computer during the talk http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-diagnosed-questions.html 34.If you have difficulty transforming stretches in games or votes you this giant http://mesotheliomame.blogspot.com/2008/11/mesothelioma-ready-reckoner.html 35.If you have difficulty in operation all formats video files http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawyers-how-to-choose-them.html 36.If you have difficulty in the organization and ease of cleaning solution you http://mesotheliomame.blogspot.com/2008/11/mesothelioma-exposure-could-be-fatal.html 37.Very popular program in the compression winzip http://mesotheliomame.blogspot.com/2008/11/mesothelioma-greed-cancer-profits.html 38..If you want to broadcast material on the Internet you solution Virtual DJ Software http://mesotheliomame.blogspot.com/2008/11/abc-mesothelioma-new-treatments-for.html 39.now The creation of program files pdf PrimoPDF http://mesotheliomame.blogspot.com/2008/11/abc-mesothelioma-treatments-for.html 40..If you have difficulty operating the extensions you solution "MPEG-1, MPEG-2, MPEG-DivX, mp3, ogg VLC Media Player http://mesotheliomame.blogspot.com/2008/11/brachytherapy-for-treatment-of.html 41.If you have difficulty browser you this treasure Mozilla Firefox http://mesotheliomame.blogspot.com/2008/11/asbestos-mesothelioma-treatment-how.html 42.If you are difficult to clean your computer you solution Glary Utilities http://mesotheliomame.blogspot.com/2008/11/mesothelioma-treatment-research.html 43.very Free program to repair and improve and see photos PhotoScape http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-history.html 44.If you have difficulty operating films and cartoons BS.Player http://mesotheliomame.blogspot.com/2008/11/mesothelioma-attorney.html 45.Conversion formulas giant cylinders to the chimerical not want the program ... PowerISO http://mesotheliomame.blogspot.com/2008/11/deadly-mesothelioma-symptoms-could-be_15.html 46.You program the operator of high-quality video DivX for Windows with DivX Player http://mesotheliomame.blogspot.com/2008/11/deadly-mesothelioma-symptoms-could-be.html 47.If you have difficulty copies of CDs nero "9"new http://mesotheliomame.blogspot.com/2008/11/association-of-asbestos-and.html 48.If you have difficulty audio chat on the net you the solution Windows Live Messenger http://mesotheliomame.blogspot.com/2008/11/need-for-mesothelioma-lawyer-to-fight.html 49.If you have difficulty download on the net ActiveX Download Control http://mesotheliomame.blogspot.com/2008/11/funding-for-mesothelioma-research-noble_15.html 50.If you have difficulty in registration at the sites and forums you solution RoboForm http://mesotheliomame.blogspot.com/2008/11/funding-for-mesothelioma-research-noble.html 51.If you are an amateur or design you a solution designed sites you Adobe Photoshop CS3 Extended http://mesotheliomame.blogspot.com/2008/11/brief-overview-of-peritoneal.html 52.If you have difficulty cleaning you stronger cleaning program in the world ccleaner http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawyers-helping-hands.html 53.If you have difficulty in Alturrent know what files you need them all uTorrent http://mesotheliomame.blogspot.com/2008/11/how-to-proceed-with-mesothelioma_15.html 54.If you have difficulty in loading files from the iPod Lalai iTunes http://mesotheliomame.blogspot.com/2008/11/how-to-proceed-with-mesothelioma.html 55.If you have difficulty converting audio files to any formulas you solution Easy CD-DA Extractor http://mesotheliomame.blogspot.com/2008/11/difference-between-pleural-and.html 56.If you have difficulty converting video files to the formula psp PSP Video 9 http://mesotheliomame.blogspot.com/2008/11/positive-guideline-to-deal-with.html 57.If you have difficulty in the work of videos from YouTube to evict you like you solution Windows Movie Maker http://mesotheliomame.blogspot.com/2008/11/history-of-asbestos-related.html 58.If you have difficulty in Works with all audio files extranet windows media player http://mesotheliomame.blogspot.com/2008/11/tips-on-choosing-your-mesothelioma.html 59.If you have difficulty in Browser you the most powerful browser in the world Avant Browse http://mesotheliomame.blogspot.com/2008/11/good-mesothelioma-attorney-is-hard-to.html 60.If you have difficulty in Video-sharing to you this wonderful program BearFlix http://mesotheliomame.blogspot.com/2008/11/peritoneal-mesothelioma-information.html 61.If you have difficulty in Survey of spyware on your computer SpywareBlaster http://mesotheliomame.blogspot.com/2008/11/how-to-care-for-someone-with.html 62.If you are suffering from problems in Alhard Disek you this legend smart PerfectDisk http://mesotheliomame.blogspot.com/2008/11/why-is-mesothelioma-so-deadly.html 63.If you have difficulty in the liberation of files "pdf" http://mesotheliomame.blogspot.com/2008/11/when-do-you-need-mesothelioma-attorney.html 64.If you have difficulty in personal control of your system next to you http://mesotheliomame.blogspot.com/2008/11/all-about-mesothelioma-lawyer.html 65.If you have difficulty in the key to jump easily be you next http://mesotheliomame.blogspot.com/2008/11/what-is-mesothelioma-cancer.html 66.If you have difficulty playing in the pictures and the amendment http://mesotheliomame.blogspot.com/2008/11/mesothelioma-information.html 67.If you have difficulty in protecting your system security followed CAPS http://mesotheliomame.blogspot.com/2008/11/symptoms-of-mesothelioma.html 68.If you have difficulty in speed of your computer you this program http://mesotheliomame.blogspot.com/2008/11/what-radical-mesothelioma-treatments.html 69.If you have difficulty maintaining a malfunction in your computer that you legend http://mesotheliomame.blogspot.com/2008/11/can-washington-mesothelioma-attorneys.html 70.If you have difficulty in the transfer of files between disks http://mesotheliomame.blogspot.com/2008/11/causes-of-mesothelioma-cancer.html 71.Discovered the most important program on the Web EZ Macros http://mesotheliomame.blogspot.com/2008/11/mesothelioma-treatment-radiation-or.html 72.If you are suffering from similar files, you repeat this unique program http://mesotheliomame.blogspot.com/2008/11/types-of-mesothelioma-cancer.html http://mesotheliomame.blogspot.com/ From R.Bauer at fz-juelich.de Thu Dec 18 08:56:44 2008 From: R.Bauer at fz-juelich.de (Reimar Bauer) Date: Thu, 18 Dec 2008 14:56:44 +0100 Subject: something else instead of PIL? In-Reply-To: References: Message-ID: skip at pobox.com schrieb: > Reimar> Hi what has happened to PIL? No updates since two years. > > It's well-written, stable code. As far as I know it does what people want > (at least it's done everything I've needed when I've used it). Why should > it matter that there hasn't been an official release in two years? > I am interested to get some new features added e.g. some special conversion routines for colorblind people. http://scien.stanford.edu/class/psych221/projects/05/ofidaner/colorblindness_project.htm How can that be archieved? cheers Reimar From castironpi at gmail.com Wed Dec 10 01:45:03 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 9 Dec 2008 22:45:03 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> Message-ID: On Dec 9, 12:40?pm, MRAB wrote: > Aaron Brady wrote: > > On Dec 9, 8:28 am, MRAB wrote: > > snip > >> In some languages (I think Delphi is one of them - it's been a while!) > >> some words which would normally be identifiers have a special meaning in > >> certain contexts, but the syntax precludes any ambiguity, and not in a > >> difficult way. "as" in Python was one of those. > > >> I certainly wouldn't want something like PL/I, where "IF", "THEN" and > >> "ELSE" could be identifiers, so you could have code like: > > >> ? ? ?IF IF = THEN THEN > >> ? ? ? ? ?THEN = ELSE; > >> ? ? ?ELSE > >> ? ? ? ? ?ELSE = IF; > > >> Seehttp://en.wikipedia.org/wiki/PL/I_(programming_language). > > snip > > That is, 'certainly' doesn't change the meaning of your statement > > any. ?You wouldn't want it, but King George III didn't want the > > American Revolution. > > It's called emphasis. I just take you to have meant, then, +1 on excluding keywords from identifiers. You said it the long way though, so I thought I missed something deeper, that didn't come across. From info at egenix.com Fri Dec 19 05:05:35 2008 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Fri, 19 Dec 2008 11:05:35 +0100 Subject: ANN: eGenix pyOpenSSL Distribution 0.8.0-0.9.8i-1 Message-ID: <494B71EF.20200@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com pyOpenSSL Distribution Version 0.8.0-0.9.8i-1 An easy to install and use repackaged distribution of the pyOpenSSL Python interface for OpenSSL - available on Windows and Unix platforms This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-pyOpenSSL-Distribution-0.8.0-0.9.8i-1-GA.html ________________________________________________________________________ INTRODUCTION The eGenix.com pyOpenSSL Distribution includes everything you need to get started with SSL in Python. It comes with an easy to use installer that includes the most recent OpenSSL library versions in pre-compiled form. pyOpenSSL is an open-source Python add-on (http://pyopenssl.sf.net/) that allows writing SSL aware networking applications as well as certificate management tools. OpenSSL is an open-source implementation of the SSL protocol (http://www.openssl.org/). For more information, please see the product page: http://www.egenix.com/products/python/pyOpenSSL/ ________________________________________________________________________ NEWS This third release of the eGenix.com pyOpenSSL Distribution upgrades pyOpenSSL to version 0.8, which includes a few bug fixes related to threading. Please note that OpenSSL, the underlying SSL engine, does not allow sharing connections between threads. This is a little known fact which could in the past cause pyOpenSSL to crash Python. Jean-Paul Calderone, the maintainer of pyOpenSSL, has added fixes in 0.8 to prevent those crashes. We have also fixed several compiler warnings found in the code. The version of pyOpenSSL you find in the source release has those patches applied. Binaries are available for Linux x86 and x64 as well as Windows x86 and include pyOpenSSL 0.8.0 as well as the OpenSSL 0.9.8i libraries. ________________________________________________________________________ DOWNLOADS The download archives and instructions for installing the package can be found at: http://www.egenix.com/products/python/pyOpenSSL/ ________________________________________________________________________ UPGRADING Before installing this version of pyOpenSSL, please make sure that you uninstall any previously installed pyOpenSSL version. Otherwise, you could end up not using the included OpenSSL libs. _______________________________________________________________________ SUPPORT Commercial support for these packages is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 19 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-12-02: Released mxODBC.Connect 1.0.0 http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From gagsl-py2 at yahoo.com.ar Mon Dec 29 01:12:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Dec 2008 04:12:02 -0200 Subject: /kolab/bin/python: double free or corruption (fasttop) References: <78edebdd-030f-4517-b9ed-5225511724d7@t39g2000prh.googlegroups.com> Message-ID: En Sun, 28 Dec 2008 12:10:06 -0200, aspineux escribi?: > I got this. > This is a test script, to help me to understand why I have unexpected > result in application. > But I got a more unexpected result, and probably wrong error message > about the read-only cursor. > def server(): > dbenv, db=init_db(read_only=False) > > update_thread=threading.Thread(target=lambda : cleanup(db)) > update_thread.setDaemon(True) > update_thread.start() I'd write it as update_thread = threading.Thread(target=cleanup, args=(db,)) or: update_thread = threading.Thread(target=lambda db=db: cleanup(db)) The original code is creating a closure and I'm unsure how closures interact with threads. -- Gabriel Genellina From prologic at shortcircuit.net.au Mon Dec 8 08:56:10 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Dec 2008 23:56:10 +1000 Subject: Beginner trying to understand functions. In-Reply-To: References: Message-ID: On Mon, Dec 8, 2008 at 11:32 PM, simonh wrote: > That works fine. Then I've tried to use functions instead. The first > two work fine, the third fails: [ ... snip ... ] Try this: def getName(): name = input('Please enter your name: ') print('Hello', name) return name def getAge(): while True: try: return int(input('Please enter your age: ')) except ValueError: print('That was not a valid number. Please try again.') def checkAge(age): permitted = list(range(18, 31)) if age in permitted: print('Come on in!') return True elif age < min(permitted): print('Sorry, too young.') elif age > max(permitted): print('Sorry, too old.') return False name = getName() age = getAge() if checkAge(age): # Do something else: # Do something else cheers James PS: Read the Tutorial :) -- -- -- "Problems are solved by method" From debl2NoSpam at verizon.net Fri Dec 19 01:04:42 2008 From: debl2NoSpam at verizon.net (David Lees) Date: Fri, 19 Dec 2008 06:04:42 GMT Subject: Very Slow PythonWin 2.6.1 Startup on Windows XP SP3 Message-ID: <_PG2l.570$P5.31@nwrddc02.gnilink.net> PythonWin used to startup in a second or two on my Windows XP desktop. now it takes around 20 seconds. I tried turning off Google Desktop indexing and Norton AV, but it still takes a long time to start. Other random apps such as Firefox 3.0 (which I just updated to) and Thunderbird have normal startup times. Does anyone have suggestions on how to speed up Python startup? David Lees From collin.day.0 at gmail.com Thu Dec 18 19:59:04 2008 From: collin.day.0 at gmail.com (Collin D) Date: Thu, 18 Dec 2008 16:59:04 -0800 (PST) Subject: Factoring Polynomials References: Message-ID: <269523e2-eba9-4b6b-b0fb-c5a7deb3ed76@o4g2000pra.googlegroups.com> On Dec 18, 4:41?pm, "James Mills" wrote: > On Fri, Dec 19, 2008 at 10:11 AM, Gabriel Genellina > > wrote: > > En Thu, 18 Dec 2008 17:37:35 -0200, escribi?: > > >> I am trying to write a simple application to factor polynomials. I > >> wrote (simple) raw_input lines to collect the a, b, and c values from > >> the user, but I dont know how to implement the quadratic equation > > >> x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > Why is this so hard ? This is simple simple > expression. Reading through the Python > tutorial and reading up on how to define > functions is all you need! :) > > Here goes: > > >>> def f(a, b, c): > > ... ? ? x = (-1 * b) + ((b**2 - (4 * a * c)) / (2 * a)) > ... ? ? return (-1 * x), x > ... > > >>> f(1, 2, 3) > (6, -6) > > cheers > James Hiya James! Just one small problem with your equation above... The quadratic formula is: x = -b +or- (b**2 - (4 * a * c))^1/2 / 2a You just forgot the square root which makes quadratic a bit more complicated. You would have to download and import sqrt() from numpy or **.5 Also.. I need to build in functionality so the user does not have to directly call the function like: f(a,b,c) Instead.. they should be able to just raw_input their values. Also.. as with some of the examples above its a good idea to analyze the discriminant to make sure we have a real solution. Of course.. thats all pretty simple to build in. Thanks a lot! From w_a_x_man at yahoo.com Thu Dec 11 06:46:34 2008 From: w_a_x_man at yahoo.com (William James) Date: 11 Dec 2008 11:46:34 GMT Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> Message-ID: John W Kennedy wrote: > Xah Lee wrote: > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or > > Java, you'll have 50 or hundreds lines. > > Java: > > static float[] normal(final float[] x) { > float sum = 0.0f; > for (int i = 0; i < x.length; ++i) sum += x[i] * x[i]; > final float divisor = (float) Math.sqrt(sum); > float[] a = new float[x.length]; > for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor; > return a; > } "We don't need no stinkin' loops!" SpiderMonkey Javascript: function normal( ary ) { div=Math.sqrt(ary.map(function(x) x*x).reduce(function(a,b) a+b)) return ary.map(function(x) x/div) } From bearophileHUGS at lycos.com Tue Dec 16 13:42:11 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 16 Dec 2008 10:42:11 -0800 (PST) Subject: Does Python3 offer a FrozenDict? References: Message-ID: <451520af-b9ff-4b63-ba0c-27b11f5043ce@a26g2000prf.googlegroups.com> Paul Moore: > Moral - don't assume that all code needs to be rewritten for Python > 3.0 :-) In practice this time your moral is of little use: having a place that allows you to choose Py3 OR Py2 code is much better and tidier, helps you save time, helps you avoid wasting some time, etc. Bye, bearophile From lie.1296 at gmail.com Sun Dec 14 16:42:33 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 14 Dec 2008 21:42:33 +0000 (UTC) Subject: [OT] stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> Message-ID: On Sat, 13 Dec 2008 19:17:41 +0000, Duncan Booth wrote: > "Diez B. Roggisch" wrote: > >> David Hl????ik schrieb: >>> Hi guys, >>> >>> i am really sorry for making offtopic, hope you will not kill me, but >>> this is for me life important problem which needs to be solved within >>> next 12 hours.. >>> >>> I have to create stable algorithm for sorting n numbers from interval >>> [1,n^2] with time complexity O(n) . >>> >>> Can someone please give me a hint. Would be very very thankful! >> >> Unless I grossly miss out on something in computer science 101, the >> lower bound for sorting is O(n * log_2 n). Which makes your task >> impossible, unless there is something to be assumed about the >> distribution of numbers in your sequence. >> >> Who has given you that assignment - a professor? Or some friend who's >> playing tricks on you? >> > I think you must have fallen asleep during CS101. The lower bound for > sorting where you make a two way branch at each step is O(n * log_2 n), > but if you can choose between k possible orderings in a single > comparison you can get O(n * log_k n). > > To beat n * log_2 n just use a bucket sort: for numbers with a known > maximum you can sort them digit by digit for O(n log_k n), and if you > don't restrict yourself to decimal then k can be as large as you want, > so for the problem in question I think you can set k=n and (log_n n)==1 > so you get O(n) > I'm sure someday, there will be a student who comes to class late and sees this on the board: "Design a comparison sorting algorithm that has better than O(n * log n) lower bound complexity." The unsuspecting student copied it, thinking it's a homework. He crunched to the problem, going to various meditations and yoga classes before finding a way that works just before deadline, handing out the work a bit late. Six weeks later, his professor called and said: "You know what you just did? You've just found a problem that was supposed to be an example of unsolvable problem." It has happened before, why not again? http://www.snopes.com/college/homework/unsolvable.asp From tleeuwenburg at gmail.com Mon Dec 15 00:26:24 2008 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: Sun, 14 Dec 2008 21:26:24 -0800 (PST) Subject: Unit tests / build tools Message-ID: <754749aa-820c-43c0-867a-33c4fa6ae228@k1g2000prb.googlegroups.com> Hi all, I don't know if there is an equivalent to Maven for Python, or whether Maven could be used for Python projects. However, it would be great if there were something available that would let me produce unit test and code coverage statistics, then have those presented through an attractive web system. I am looking to integrate more testing, profiling and analysis into a significant codebase, and would like to automate as much of this as possible to make my workload lighter. Thanks, -Tennessee From marco at sferacarta.com Fri Dec 12 11:20:51 2008 From: marco at sferacarta.com (Marco Mariani) Date: Fri, 12 Dec 2008 17:20:51 +0100 Subject: Removing None objects from a sequence In-Reply-To: <87ej0dz894.fsf@daycos.com> References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> Message-ID: Kirk Strauser wrote: > So what's the difference exactly? "foo is not None" is actually surprising > to me, since "not None" is True. "0 is True" is False, but "0 is not None" > is True. Why is that? Cause I was tired of course, and got the not precedente not right!! Argh From mrtot at gmx.de Fri Dec 19 11:47:18 2008 From: mrtot at gmx.de (Martin) Date: Fri, 19 Dec 2008 08:47:18 -0800 (PST) Subject: IMAP: How to implement GMail-like threaded conversations view Message-ID: Currently I am trying to get used to Python's imaplib and email modules. I'like to create a webmail client simmilar to GMail. My Questions: a) Is there any feature hidden in Python's built-in modules (imaplib, email) that already can group all my mails into threads? b) If not a... what would be the best way to implement this? I can think of two approaches: b.1) Use the "References:" field of the messages in order to find out which messages are related to each other. I tried a first implementation which works quite well but I don't know if there can occur situations where one message is related to two parents. Also I don't know what happens if someone is too lazy to type my address. He might click at "Reply", delete topic and old mail-text and compose a new mail. Theoretically his mail client would set the "References:" field accordingly never the less, wouldn't it? Therefore my mail client would consider that completely new mail as part of an older conversation. The thoughts above might lead to the second approach: b.2) Use the "Subject:" field of the messages. I also tried this implementation and it also works (at first glance). I stripped all subjects of all mails so that all those "Re:", "Fw:" tags at the beginning get deleted. Afterwards I grouped those having the same subject and the same participants. Problem: I have no clue what "Re:"-tags might exist around the world. I guess each mail client and each language uses different ones, right? c) Does anyone know good resources to gain more knowledge about imap / mailing? Currently I am using those sites as a reference: http://www.devshed.com/c/a/Python/Python-Email-Libraries-part-2-IMAP/ (as a start *g) http://tools.ietf.org/html/rfc3501 http://tools.ietf.org/html/rfc2822 http://docs.python.org/library/imaplib.html http://docs.python.org/library/email.html Maybe there are other sources of interest on the web? :) This is my first post in this newsgroup. So: "Hello everybody!" :-) I've been reading this group for quite a while and I am really astonished how fast people give valuable answers here. This is a really great community! Many thanks in advance for all ideas! Greetz, Martin From __peter__ at web.de Fri Dec 19 09:03:29 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2008 15:03:29 +0100 Subject: How to parsing a sequence of integers References: <494ba258$0$18998$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Steven Woody a ?crit : >> In additional to max/min, is there something like average()? > > Not AFAIK, but it's really trivial > > def average(lst): > """ assume lst is a list of numerics """ > return sum(lst) / len(lst) If you are using Python 2.x: >>> def average(lst): ... return sum(lst)/len(lst) ... >>> average([1,2]) 1 So you better throw in a float(...): >>> def average(lst): ... return sum(lst)/float(len(lst)) ... >>> average([1,2]) 1.5 Peter From skip at pobox.com Wed Dec 3 11:51:43 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 3 Dec 2008 10:51:43 -0600 Subject: python an sqlite objects In-Reply-To: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> Message-ID: <18742.47391.389709.119341@montanaro-dyndns-org.local> azrael> is it possible to save a python object into a sqlite database as azrael> an atribute of type BLOB Sure. Just pickle the object and save the resulting string. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From rt8396 at gmail.com Fri Dec 19 12:41:08 2008 From: rt8396 at gmail.com (r) Date: Fri, 19 Dec 2008 09:41:08 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <6e232ab0-306a-4598-969a-211c4054e836@f40g2000pri.googlegroups.com> I was actually looking forward to 3.0, but the more I hear about 3.0, the more I am turned off. I think there are a lot of other pythonista's and pythoneers out there who agree but are not saying anything. This syntax for string formatting is completely ridiculous. What is the purpose of breaking backward compatibility just to write a print() function. This is going to push people away from python. I am trying to bring people to Python. I heard map is going away too, is that true also??, and there was talk at one time(serious talk from Guido) about removing lambda functions. Is this planned for the future?? Python has been beautifully designed from the beginning. But, I feel a shift from this now. Are they scared of Ruby, if they are, why the hell should they be. We do not need to lose any of the great pythonista's right now, and we damn sure don't want to turn off the new recruits. It seems like most of the backward breaks are really just for dumb reasons(sorry but its true). What is the logic behind this? The whole reason for not having a print function was the need to use it so much in debugging. And I was actually going to overlook that until I saw this perl/ruby like format method. WTF! From marduk at letterboxes.org Tue Dec 9 11:35:17 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Tue, 09 Dec 2008 11:35:17 -0500 Subject: When (and why) to use del? Message-ID: <1228840517.4109.10.camel@brotherus.rdu.redhat.com> I'm looking at a person's code and I see a lot of stuff like this: def myfunction(): # do some stuff stuff my_string = function_that_returns_string() # do some stuff with my_string del my_string # do some other stuff return and also def otherfunction(): try: # some stuff except SomeException, e: # more stuff del e return I think this looks ugly, but also does it not hurt performance by preempting the gc? My feeling is that this is a misuse of 'del'. Am I wrong? Is there any advantage of doing the above? From gherron at islandtraining.com Tue Dec 16 11:30:00 2008 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 16 Dec 2008 08:30:00 -0800 Subject: Generator slower than iterator? In-Reply-To: References: Message-ID: <4947D788.3040508@islandtraining.com> Lie Ryan wrote: > On Tue, 16 Dec 2008 12:07:14 -0300, Federico Moreira wrote: > > >> Hi all, >> >> Im parsing a 4.1GB apache log to have stats about how many times an ip >> request something from the server. >> >> The first design of the algorithm was >> >> for line in fileinput.input(sys.argv[1:]): >> ip = line.split()[0] >> if match_counter.has_key(ip): >> match_counter[ip] += 1 >> else: >> match_counter[ip] = 1 >> >> And it took 3min 58 seg to give me the stats >> >> Then i tried a generator solution like >> >> def generateit(): >> for line in fileinput.input(sys.argv[1:]): >> yield line.split()[0] >> >> for ip in generateit(): >> ...the same if sentence >> >> Instead of being faster it took 4 min 20 seg >> >> Should i leave fileinput behind? >> Am i using generators with the wrong aproach? >> > > What's fileinput? A file-like object (unlikely)? Also, what's > fileinput.input? I guess the reason why you don't see much difference > (and is in fact slower) lies in what fileinput.input does. > > Fileinput is a standard module distributed with Python: >From the manual: 11.2 fileinput -- Iterate over lines from multiple input streams This module implements a helper class and functions to quickly write a loop over standard input or a list of files. The typical use is: import fileinput for line in fileinput.input(): process(line) ... > Generators excels in processing huge data since it doesn't have to create > huge intermediate lists which eats up memory, given an infinite memory, a > generator solution is almost always slower than straight up solution > using lists. However in real life we don't have infinite memory, hogging > our memory with the huge intermediate list would make the system start > swapping, swapping is very slow and is a big hit to performance. This is > the way generator could be faster than list. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From rdmurray at bitdance.com Thu Dec 4 12:07:42 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Thu, 4 Dec 2008 12:07:42 -0500 (EST) Subject: simplest way to strip a comment from the end of a line? In-Reply-To: References: Message-ID: On Thu, 4 Dec 2008 at 08:50, Joe Strout wrote: > I have lines in a config file which can end with a comment (delimited by # as > in Python), but which may also contain string literals (delimited by double > quotes). A comment delimiter within a string literal doesn't count. Is > there any easy way to strip off such a comment, or do I need to use a loop to > find each # and then count the quotation marks to its left? >>> from shlex import split >>> split("this is a test") ['this', 'is', 'a', 'test'] >>> split("this is a test #with a comment") ['this', 'is', 'a', 'test', '#with', 'a', 'comment'] >>> split("this is a test #with a comment", comments=True) ['this', 'is', 'a', 'test'] >>> split("this is a '#gnarlier' test #with a comment", comments=True) ['this', 'is', 'a', '#gnarlier', 'test'] http://docs.python.org/library/shlex.html --RDM From jstroud at mbi.ucla.edu Sat Dec 13 05:19:08 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 13 Dec 2008 02:19:08 -0800 Subject: Need help improving number guessing game In-Reply-To: References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> Message-ID: I forgot to return target: def guess(player, p1score, p2score): target = None guess1 = int(input("\n>> ")) if guess1 > 100: print("ONLY NUMBERS FROM 1 TO 99") elif guess1 > target: print("TOO HIGH") elif guess1 == target: print("GOOD JOB, PLAYER %s! THE SCORE IS:" % player) print("P1: %s --- P2: %s" % (p1score, p2score))) print("PLAY AGAIN?") #Set up the game again play = int(input("0 TO END: ")) if play == 0: print("GOOD BYE. PLAY AGAIN SOON!") quit() else: target = random.randint(1, 99) else: print("TOO LOW") return target -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From castironpi at gmail.com Tue Dec 23 05:48:39 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 23 Dec 2008 02:48:39 -0800 (PST) Subject: Very basic question References: <21ab1917-f0c9-48fb-baa9-02e5bf229bf5@s9g2000prm.googlegroups.com> Message-ID: On Dec 23, 4:46?am, Sengly wrote: > Hello all, > > I would like to calculate a string expression to a float. For example, > I have ('12/5') and I want 2.4 as a result. I tried to use eval but it > only gives me 2 instead of 2.5 > > Help!!! > > Regards, > > Sengly >>> float('12')/float('5') 2.3999999999999999 >>> print float('12')/float('5') 2.4 >>> float(12/5) 2.0 >>> print float(12/5) 2.0 From narkewoody at gmail.com Mon Dec 22 01:56:45 2008 From: narkewoody at gmail.com (Steven Woody) Date: Mon, 22 Dec 2008 14:56:45 +0800 Subject: How to represent a sequence of raw bytes In-Reply-To: <200812220327.36180.motoom@xs4all.nl> References: <200812220327.36180.motoom@xs4all.nl> Message-ID: On Mon, Dec 22, 2008 at 10:27 AM, Michiel Overtoom wrote: > On Monday 22 December 2008 03:23:03 Steven Woody wrote: > >> 2. char buf[] = {0x11, 0x22, 0x33, ... } >> >> What's the equivalent representation for above in Python? > >>>> buf="\x11\x22\33" >>>> for b in buf: print ord(b) > ... > 17 > 34 > 27 >>>> > Hi, Michiel I thing "\x11\x22\x33" in python is not the {0x11, 0x22, 0x33} in C. Since, a string in python is immutable, I can _not_ do something like: b[1] = "\x55". And, how about char buf[200] in my original question? The intension is to allocate 200 undefined bytes in memory. Thanks. Regards, From clp at rebertia.com Tue Dec 23 00:58:10 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 22 Dec 2008 21:58:10 -0800 Subject: iterating initalizations In-Reply-To: <002696D3-E888-4D32-8416-0CFE4AC859AC@gmail.com> References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> <47c890dc0812221943g44bd7222t8c09c088d87e77df@mail.gmail.com> <002696D3-E888-4D32-8416-0CFE4AC859AC@gmail.com> Message-ID: <47c890dc0812222158r551265e2p81a12488e72b19de@mail.gmail.com> On Mon, Dec 22, 2008 at 7:52 PM, Aaron Stepp wrote: > > On Dec 22, 2008, at 10:43 PM, Chris Rebert wrote: > >> On Mon, Dec 22, 2008 at 7:32 PM, Aaron Stepp >> wrote: >> >>> >>> Thanks for the help so far, I think I'm starting to get a hang of the >>> syntax. >>> >>> I think I need to state my goal more clearly. >>> >>> Instead of writing a long list of initializations like so: >>> >>> A = [ ] >>> B = [ ] >>> ... >>> Y = [ ] >>> Z = [ ] >>> >>> I'd like to save space by more elegantly turning this into a loop. If I >>> need to just write it out, I guess that's ok... but it would be much >>> cleaner. I'm a composer, not a programmer, so some of this is quite >>> above >>> me. >>> >> >> So, are these variables supposed to be module-level, or attributes of >> class pitchAndRhythm, or what? >> Also, are you going to use the variables normally or are you going to >> need "variable variables" (e.g. like $$var in PHP, which gives the >> value of the variable with the name of the string stored in $var)? >> >> Cheers, >> Chris >> >> -- >> Follow the path of the Iguana... >> http://rebertia.com > > > The're going to only be part of the pitchAndRhythm class. Simply put, I > just need enough arrays to hold a list of pitches/rhythms. Then I'll have > each list member returned to an instrument defined in another module. > > As I'm hacking away at the code, I'm realizing that maybe I can do this with > just and A = [] and B = []. But I'm not sure... > Do you really need to name them, or are the names arbitrary and you only really care about having N distinct lists? Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From skip at pobox.com Thu Dec 4 07:20:59 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 4 Dec 2008 06:20:59 -0600 Subject: python an sqlite objects In-Reply-To: <493792a9$0$16763$426a74cc@news.free.fr> References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <4936bceb$0$16783$426a34cc@news.free.fr> <4936dab7$0$9107$426a74cc@news.free.fr> <493792a9$0$16763$426a74cc@news.free.fr> Message-ID: <18743.52011.536628.470841@montanaro-dyndns-org.local> Bruno> If you serialize a dict, you'll obviously get a dict back. Note Bruno> that the point of json is *not* to replace pickle. json is a Bruno> *data* serialization format meant to represent "basic" types Bruno> (dicts, lists, strings and numbers) in human readable and Bruno> (mostly) language-agnostic way. Right, which makes it unsuitable as a general object serialization format. The OP was unclear what he meant when he asked about storing Python objects in a sqlite database. In the general case json doesn't cut it. Bruno> If you want a Python object store, you'll be better looking at Bruno> ZODB, Durus or friends. -- Or SQLAlchemy or SQLObject. Skip From raj.indian.08 at gmail.com Mon Dec 22 00:25:10 2008 From: raj.indian.08 at gmail.com (RajNewbie) Date: Sun, 21 Dec 2008 21:25:10 -0800 (PST) Subject: Twisted for non-networking applications References: <82e49b84-43c9-452f-a139-c77378c12908@a12g2000pro.googlegroups.com> Message-ID: <9faa4fa5-6fd1-4ebb-bf1b-382a7d74ba0a@d42g2000prb.googlegroups.com> On Dec 22, 3:26?am, "James Mills" wrote: > On Mon, Dec 22, 2008 at 4:27 AM, Kottiyath wrote: > > Hi all, > > ? Is it a good idea to use Twisted inside my application, even though > > it has no networking part in it? > > ? Basically, my application needs lots of parallel processing - but I > > am rather averse to using threads - due to myraid issues it can cause. > > So, I was hoping to use a reactor pattern to avoid the threads. I am > > using twisted in another part of the application for networking, so I > > was hoping to use the same for the non-networking part for reusing the > > reactor pattern. > > ? If somebody can help me on this, it would be very helpful. > > Alternatively you could give circuits (1) > a go. It _can_ be a nice alternative to > Twisted and isn't necessarily focused on > Networking applications. > > cheers > James > > 1.http://trac.softcircuit.com.au/circuits/ I was unable to see documentation explaining this - so asking again. Suppose the event handlers in the component is doing blocking work, how is it handled? I went through ciruits.core, but was unable to understand exactly how blocking mechanisms are handled. My scenario is as follows: I have 4 loops, 1 small and high priority, 3 quite large and blocking (takes upto 3 seconds) and comparatively low priority. The small loops goes through everytime and does some work - and optionally uses the data sent by the other 3 loops. I do not want the smaller loop to get blocked by the other loops. So, if the event handler does blocking work, can that cause the whole loop to block? From jelsas at gmail.com Wed Dec 10 11:07:14 2008 From: jelsas at gmail.com (jelsas) Date: Wed, 10 Dec 2008 08:07:14 -0800 (PST) Subject: Maintaining signature in help(decorated function) Message-ID: <48f2fd47-1fc3-4b2f-ad39-24adce7e9a5c@k36g2000yqe.googlegroups.com> Hi -- I can't seem to maintain the function signature when applying a decorator. I'm using functools.wraps. Example: >>> def mydecorator(fn): ... from functools import wraps ... # simple decorator ... @wraps(fn) ... def wrapped(*args, **kwargs): ... print 'i\'m wrapped!' ... return fn(*args, **kwargs) ... return wrapped ... >>> >>> @mydecorator ... def f(foo, bar): ... '''docstring for f''' ... pass ... >>> >>> help(f) displays: Help on function f in module __main__: f(*args, **kwargs) docstring for f I would like to maintain f's signature in the help message, (foo, bar) instead of (*args, **kwargs) Thanks in advance! From castironpi at gmail.com Sat Dec 27 19:40:39 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 27 Dec 2008 16:40:39 -0800 (PST) Subject: C API: array of floats/ints from python to C and back References: Message-ID: On Dec 27, 6:06?pm, Scott David Daniels wrote: > Daniel Fetchinson wrote: > >.... I have a list to begin with which will be passed to the C function. > > ?> I assume converting the list to an array.array and passing that to the C > > > function doesn't make any difference in terms of speed since the > > operation itself will be done in the C function anyway. > > Right, but why bother to do the conversion in C where you'll have to > fiddle with refcounts and error propogation? ?convert in python, and > go to the underlying data in C. I think you could use ctypes.c_int* 20, which is an awesome data type-- a 20-element array of integers. You could also use this, which I just discovered, and is actually moderately disturbing. #WARNING unsafe code >>> from ctypes import * >>> i= c_int(42) >>> pi= pointer(i) >>> pi[0] 42 >>> pi[1] 0 >>> pi[2] 0 >>> pi[1]= 20 >>> pi <__main__.LP_c_long object at 0x00A97D00> >>> pi[1] 20 What memory is it overwriting? From tarun.kap at gmail.com Fri Dec 19 14:35:51 2008 From: tarun.kap at gmail.com (TkNeo) Date: Fri, 19 Dec 2008 11:35:51 -0800 (PST) Subject: pymssql for python 2.6 ? Message-ID: when would pymssql come out with a release that is compatible with python 2.6 ? Thanks -TK From hniksic at xemacs.org Tue Dec 2 09:36:01 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 02 Dec 2008 15:36:01 +0100 Subject: best way to do this References: Message-ID: <87ljuyr6em.fsf@mulj.homelinux.net> TP writes: > Hi everybody, > >>>> c=[(5,3), (6,8)] > > From c, I want to obtain a list with 5,3,6, and 8, in any order. > I do this: > >>>> [i for (i,j) in c] + [ j for (i,j) in c] > [5, 6, 3, 8] > > Is there a quicker way to do this? Quicker? Hard to say. Using itertools elegantly? Definitely: list(chain(*c)) As an added benefit, it works regardless of the number of elements in the tuple. (Also assumes from itertools import chain for effect.) From mail at microcorp.co.za Fri Dec 19 01:19:23 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 19 Dec 2008 08:19:23 +0200 Subject: Is this pythonic? References: <66d058f9-cfe1-4b3c-ab8a-e6e88bb97770@m22g2000vbp.googlegroups.com> <494a761c$0$20035$426a34cc@news.free.fr> Message-ID: <000001c961a4$c4611f80$0d00a8c0@hendrik> "Bruno Desthuilliers" wrote: >ipytest at gmail.com a ?crit : >> x.validate_output(x.find_text(x.match_filename >> (x.determine_filename_pattern(datetime.datetime.now())))) >> >> Is it even good programming form? > >functional programming addicts might say yes. But as far as I'm >concerned, I find it a bit too nested... > +1 I would call it onionskin programming. There is of course nothing technically wrong with it, and you can do the same kind of thing in C, but every time I see something like it, my reaction is WTF. - Hendrik From vinay_sajip at yahoo.co.uk Tue Dec 30 23:53:15 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 30 Dec 2008 20:53:15 -0800 (PST) Subject: AttributeError: 'module' object has no attribute 'DatagramHandler' (ubuntu-8.10, python 2.5.2) References: <4c6f0831-c05f-401f-b956-376600b38e06@r15g2000prd.googlegroups.com> Message-ID: On Dec 29, 12:18 pm, "Chris Rebert" wrote: > There's your answer. I do agree though that the "class logging.DatagramHandler" line in the docs is misleading to say the > least. Perhaps a docs bug should be filed... I've raised it on the sphinx-dev Google group. The documentation source markup for the class just says "DatagramHandler", and the "logging" prefix is added by Sphinx at HTML generation time. Regards, Vinay Sajip From kkylheku at gmail.com Wed Dec 10 16:37:34 2008 From: kkylheku at gmail.com (Kaz Kylheku) Date: Wed, 10 Dec 2008 21:37:34 +0000 (UTC) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: <20081226055859.604@gmail.com> On 2008-12-05, Xah Lee wrote: > Let's say for example, we want to write a function that takes a vector > (of linear algebra), and return a vector in the same direction but > with length 1. In linear algebar terminology, the new vector is called > the ?normalized? vector of the original. > > For those of you who don't know linear algebra but knows coding, this If I were to guess who that would be ... > means, we want a function whose input is a list of 3 elements say > {x,y,z}, and output is also a list of 3 elements, say {a,b,c}, with > the condition that > > a = x/Sqrt[x^2+y^2+z^2] > b = y/Sqrt[x^2+y^2+z^2] > c = z/Sqrt[x^2+y^2+z^2] > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, > you'll have 50 or hundreds lines. Really? ``50 or hundreds'' of lines in C? #include /* for sqrt */ void normalize(double *out, double *in) { double denom = sqrt(in[0] * in[0] + in[1] * in[1] + in[2] * in[2]); out[0] = in[0]/denom; out[1] = in[1]/denom; out[2] = in[2]/denom; } Doh? Now try writing a device driver for your wireless LAN adapter in Mathematica. From gagsl-py2 at yahoo.com.ar Mon Dec 8 03:36:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Dec 2008 06:36:53 -0200 Subject: ftp retrlines with re... In-Reply-To: References: Message-ID: En Fri, 05 Dec 2008 12:51:58 -0200, isabellknauer at googlemail.com escribi?: > Ive been working on an application quite some time now and i wanted to > include something to let the user load a new version. i therefore > tried to include this here: Too much code, unclear question... please post again, shortening code to the minimum necesary to show the problem. And tell us *what* is the problem, what did you expect to happen, what actually happened... -- Gabriel Genellina From Sengly.Heng at gmail.com Tue Dec 23 05:49:44 2008 From: Sengly.Heng at gmail.com (Sengly) Date: Tue, 23 Dec 2008 02:49:44 -0800 (PST) Subject: Very basic question References: <21ab1917-f0c9-48fb-baa9-02e5bf229bf5@s9g2000prm.googlegroups.com> Message-ID: <38f6b145-8615-4bcc-88f6-1988f9a7f68f@q30g2000prq.googlegroups.com> I can hack it by doing eval('1.0*12/5') but is there any better method? From 5lvqbwl02 at sneakemail.com Tue Dec 30 14:52:08 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Tue, 30 Dec 2008 11:52:08 -0800 (PST) Subject: embedding python in wxpython Message-ID: <191280cf-ecf9-4135-9737-9923061855d1@t39g2000prh.googlegroups.com> Hi, I've looked around for a way to allow a python console from within a wxPython application, but have only found stuff on embedded/ extending python with C/C++ or wxWidgets in C++, but not wxPython. Is this easy to do? Can someone point me in the right direction? Also, typically when you embed a scripting language into a larger application, how do you get the console environment to share data with the larger application? For instance, if the application has some gui stuff (for example clicking on a object and dragging it around), how do you get "object.select(x,y)" to print out on the console, and vice-versa: the object gets selected if the user types "object.select(x,y)"? I'd like the console to be a bidirectional representation of what's going on in the gui, plus a general purpose evaluation environment where you can manipulate application data via some api which is automatically exposed to the console when the application opens up. I'm looking for high-level hints/strategies/directions. Thank you Michael From benjamin.kaplan at case.edu Wed Dec 10 14:29:25 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 10 Dec 2008 14:29:25 -0500 Subject: Python is slow In-Reply-To: <075d8c52-93e9-40f4-9eb6-794ce275651e@g38g2000yqd.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <075d8c52-93e9-40f4-9eb6-794ce275651e@g38g2000yqd.googlegroups.com> Message-ID: On Wed, Dec 10, 2008 at 2:07 PM, Paul McGuire wrote: > On Dec 10, 12:42 pm, cm_gui wrote: > > Python is slow. Very slow. > > And... ? Was there a question or specific suggestion in there > somewhere? > > Do you go to your mechanic and say "My car wont go as fast as the > other cars on the road! They should make it faster!"? > > Good luck to you in your futile, uh I meant, *future* endeavors. (No > wait, I really meant "futile".) > > -- Paul > Don't bother arguing. It's just a pathetic attempt to start a flame war. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Fri Dec 12 17:23:33 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 12 Dec 2008 17:23:33 -0500 Subject: Removing None objects from a sequence In-Reply-To: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> Message-ID: If you want to literally remove None objects from a list....(or mutable sequence) def deNone(alist): n=len(alist) i=j=0 while i < n: if alist[i] is not None: alist[j] = alist[i] j += 1 i += 1 alist[j:i] = [] blist=[None,1,None,2,None,3,None,None,4,None] deNone(blist) print(blist) # prints [1, 2, 3, 4] Terry Jan Reedy From bj_666 at gmx.net Sun Dec 21 04:42:47 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Dec 2008 09:42:47 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <6r6hcmFfb643U2@mid.uni-berlin.de> On Sat, 20 Dec 2008 15:27:43 -0800, walterbyrd wrote: > On Dec 19, 10:25?am, Michael Torrie wrote: > >> Personally the new string formatter is sorely needed in Python. > > Really? You know, it's funny, but when I read problems that people have > with python, I don't remember seeing that. Loads of people complain > about the white space issue. Some people complain about the speed. Lots > of complaints about certain quirky behavior, but I have not come across > any complaints about the string formatting. Many newbie code I have seen avoids it by string concatenation: greeting = 'Hello, my name is ' + name + ' and I am ' + str(age) + ' old.' That's some kind of indirect complaint. :-) > In fact, from what I have seen, many of the "problems" being "fixed" > seem to be non-problems. And even if nobody has problems with the limitations of ``%`` string formatting why shouldn't they add a more flexible and powerful way!? Python?3.0 is not a bug fix release. Ciao, Marc 'BlackJack' Rintsch From prahaai at gmail.com Thu Dec 11 11:20:08 2008 From: prahaai at gmail.com (Cro) Date: Thu, 11 Dec 2008 08:20:08 -0800 (PST) Subject: HGE and Python (again) Message-ID: <8180969e-9289-4f8c-ab80-30fbc50914d1@g17g2000prg.googlegroups.com> Good day. I've been trying to port HGE (http://hge.relishgames.com) to Python for more than 4 months now... HGE is a hardware accelerated 2D game engine. It comes with the source and examples. In the folder "include", you can find "hge.h", the file that i am talking about in all the post. # I tried to load the DLL functions with Python Ctypes like this : [code] >>> from ctypes import * >>> HGE = cdll.LoadLibrary("C:/hge181/hge") >>> HGE.hgeCreate(0x180) [/code] But i get this error : "Procedure called with not enough arguments (4 bytes missing) or wrong calling convention". The call should be done with hgeCreate(HGE_VERSION) and the constant is defined as "#define HGE_VERSION 0x180"... Number 0x180 means 384 in Python. I don't mean what it means in C. So i am stuck. I also tried to modify the "hge.h" file on line 408, and export the rest of the classes... [code] __declspec (dllexport) hgeVertex; __declspec (dllexport) hgeTriple; __declspec (dllexport) hgeQuad; __declspec (dllexport) hgeInputEvent; [/code] But after compilation, i am not able to access them from Python "ctypes". They seem to remain invisible. Perhaps i am not doing it right?... # I tried Cython. I tried to load "hge.h" in Cython and use the structures. The first error i get is at line 173: "typedef bool (*hgeCallback) ();". I am not that good in C/C++ to understand what it means. So i commented it... The second big error is at line 408: "extern "C" { EXPORT HGE * CALL hgeCreate(int ver); }". This should be the DLL export. I comented that too... I used this code in Cython, loading from "hge.h": [code] # file HGE.pyx cdef extern from "windows.h": pass cdef extern from "hge.h": pass [/code] And i get this errors: [code] ..\hge.h(215) : error C2061: syntax error : identifier 'hgeVertex' ..\hge.h(218) : error C2059: syntax error : '}' ..\hge.h(226) : error C2061: syntax error : identifier 'hgeVertex' ..\hge.h(229) : error C2059: syntax error : '}' ..\hge.h(274) : error C2061: syntax error : identifier 'HGE' ..\hge.h(274) : error C2059: syntax error : ';' ..\hge.h(275) : error C2449: found '{' at file scope (missing function header?) ..\hge.h(407) : error C2059: syntax error : '}' [/code] Then i tried to define hgeVertex in Cython like: [code] struct hgeVertex: float x, y # screen position float z # Z-buffer depth 0..1 DWORD col # color float tx, ty # texture coordinates [/code] But i get the exact same errors. If i comment all the structures hgeVertex and Triple and Quad and the HGE class, the Cython file compiles !... But it's not useful at all. My Cython is okay, i compiled a few programs before, so that's not a problem... # Then i tried Swig (and it worked with the examples )... But the problems with "hge,h" seem to be somewhat similar. I call swig like this : "swig -c++ -python hge.i" And the file "hge.i" contains: [code] /* File : hge.i */ %module hge %{ #include "hge.h" %} /* Let's just grab the original header file here */ %include "hge.h" [/code] And the error i get after commenting the HGE callback and DLL export is this : "hge.h(276): Error: Syntax error in input(3)." Line 276 is exactly the first call of HGE class : "virtual void CALL Release() = 0;". # I tried Boost.Python (and it works with embedding and extending examples), but i could't compile "hge.h" even after commenting the structures and classes. I have to write some wrapper code in "hge.h" and i am probably doing it completely wrong. [code] BOOST_PYTHON_MODULE(hge) { using namespace boost::python; class_ base("hgeVertex"); } [/code] So i am stuck again... I am not that good in neither C or Python. Can anyone suggest any ideas? Please? I really really really want to port HGE in Python. It's the greatest game engine i have ever seen. The particle engine is EXCELLENT and i need it. Thank you in advance. From andre.roberge at gmail.com Tue Dec 30 23:21:06 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Tue, 30 Dec 2008 20:21:06 -0800 (PST) Subject: Memory leak problem (while using tkinter) Message-ID: I have written a small program (my first Tkinter-based app) to play around the idea mentioned on http://rogeralsing.com/2008/12/07/genetic-programming-evolution-of-mona-lisa/ and, in doing so, have encountered a memory leak problem. I have seen mentions on the web of using the delete() method of canvas to prevent such problems - which I have tried to do with limited success. Below is the code I wrote; to run it, you will need a small image file (I used the one found on http://alteredqualia.com/visualization/evolve/) that is saved under "mona_lisa.png". Any help would be greatly appreciated. Andr? ========== from Tkinter import Canvas, Tk, Label import Image, ImageTk, ImageChops, ImageStat # PIL import aggdraw from random import randint import time import copy FITNESS_OFFSET = 0 saved = [None, None] def fitness(im1, im2): """Calculate a value derived from the root mean squared of the difference between two images. It is normalized so that when a black image is compared with the original one (img1), the fitness given is 0, and when the image is identical, the fitness value is 100.""" global FITNESS_OFFSET stat = ImageStat.Stat(ImageChops.difference(im1, im2)) fit = 1. - sum(stat.rms[:3])/(255*3) if FITNESS_OFFSET == 0: black_image = aggdraw.Draw("RGBA", im1.size, "black") s = black_image.tostring() raw = Image.fromstring('RGBA', im1.size, s) stat = ImageStat.Stat(ImageChops.difference(im1, raw)) FITNESS_OFFSET = 1. - sum(stat.rms[:3])/(255*3) return 100*(fit-FITNESS_OFFSET)/(1.-FITNESS_OFFSET) class DNA(object): def __init__(self, width, height, polygons=50, edges=6): self.polygons = polygons self.edges = edges self.width = width self.height = height self.dna = [] def init_dna(self): for i in range(self.polygons): self.dna.append(self.random_polygon()) def random_polygon(self): edges = [] for i in range(self.edges): edges.append(randint(0, self.width)) edges.append(randint(0, self.height)) col = [randint(0, 255), randint(0, 255), randint(0, 255), randint(0, 255)] return edges, col def mutate(self): selected = randint(0, self.polygons-1) _type = randint(0, 2) if _type == 0: # colour col_index = randint(0, 3) self.dna[selected][1][col_index] = randint(0, 255) elif _type == 1: # x coordinate coord = randint(0, self.edges-1) self.dna[selected][0][2*coord] = randint(0, self.width) elif _type == 2: # y coordinate coord = randint(0, self.edges-1) self.dna[selected][0][2*coord+1] = randint(0, self.height) class AggDrawCanvas(Canvas): def __init__(self, width, height, win): Canvas.__init__(self, win) self.image_id = None self.win = win self._width = width self._height = height self._size = width, height self.config(width=width, height=height+20) self.info = self.create_text(width/2, height+20) self.pack() self.dna = DNA(self._width, self._height) self.mutations = 0 def draw_dna(self): img = Image.new("RGBA", self._size, "black") self.context = aggdraw.Draw(img) for gene in self.dna.dna: brush = aggdraw.Brush(tuple(gene[1][0:3]), opacity=gene[1] [3]) self.context.polygon(gene[0], brush) self.delete(img) self.redraw() def redraw(self): self.mutations += 1 s = self.context.tostring() self.delete(self.context) raw = Image.fromstring('RGBA', self._size, s) self.fitness = fitness(mona_lisa, raw) self.itemconfig(self.info, text="%2.2f %d"%(self.fitness, self.mutations), fill="black") self.image = ImageTk.PhotoImage(raw) self.delete(self.image_id) self.image_id = self.create_image(self._width/2, self._height/ 2, image=self.image) self.update() win = Tk() mona_lisa = Image.open("mona_lisa.png") img = ImageTk.PhotoImage(mona_lisa) original_image = Canvas(win) original_image.pack() fitness_label = Label(win) _w, _h = img.width(), img.height() original_image.config(width=_w, height=_h) original_image.create_image(_w/2, _h/2, image=img) best_fit = AggDrawCanvas(_w, _h, win) best_fit.dna.dna = [] best_fit.draw_dna() current_fit = AggDrawCanvas(_w, _h, win) current_fit.dna.init_dna() current_fit.draw_dna() while True: current_fit.dna.mutate() current_fit.draw_dna() if current_fit.fitness > best_fit.fitness: best_fit.dna.dna = copy.deepcopy(current_fit.dna.dna) best_fit.draw_dna() else: current_fit.dna.dna = copy.deepcopy(best_fit.dna.dna) if __name__ == '__main__': win.mainloop() From Ron.Barak at lsi.com Thu Dec 25 07:23:39 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Thu, 25 Dec 2008 12:23:39 +0000 Subject: os.system('cls') In-Reply-To: References: Message-ID: <7F0503CD69378F49BE0DC30661C6CCF602494700@enbmail01.lsi.com> Hi Dennis, print dir(os.system) print os.__dict__ might help Bye, Ron. ________________________________ From: Dennis van Oosterhout [mailto:de.slotenzwemmer at gmail.com] Sent: Thursday, December 25, 2008 12:22 To: python-list at python.org Subject: os.system('cls') Hi there! I was searching for a way to clear the 'DOS screen'/command screen etc. and found that os.system('cls') works for this. I was just wondering where I can find al the commands which can be used for os.system(). I searched with google but I didn't find an answer. In the official python tutorial it says os.system('command') executes the command, but it doesn't say which commands exist (or I'm just blind). Does anyone have an answer for this question? Thanks, Devilly -------------- next part -------------- An HTML attachment was scrubbed... URL: From fetchinson at googlemail.com Sun Dec 7 14:39:43 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sun, 7 Dec 2008 11:39:43 -0800 Subject: Guido's new method definition idea In-Reply-To: <493c2276$0$9254$426a34cc@news.free.fr> References: <493c2276$0$9254$426a34cc@news.free.fr> Message-ID: >>>> The story of the explicit self in method definitions has been >>>> discussed to death and we all know it will stay. However, Guido >>>> himself acknowledged that an alternative syntax makes perfect sense >>>> and having both (old and new) in a future version of python is a >>>> possibility since it maintains backward compatibility. The alternative >>>> syntax will be syntactic sugar for the old one. This blog post of his >>>> is what I'm talking about: >>>> >>>> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html >>>> >>>> The proposal is to allow this: >>>> >>>> class C: >>>> def self.method( arg ): >>>> self.value = arg >>>> return self.value >>>> >>>> instead of this: >>>> >>>> class C: >>>> def method( self, arg ): >>>> self.value = arg >>>> return self.value >>>> >>>> I.e. explicit self stays only the syntax is slightly different and may >>>> seem attractive to some. As pointed out by Guido classmethods would >>>> work similarly: >>>> >>>> class C: >>>> @classmethod >>>> def cls.method( arg ): >>>> cls.val = arg >>>> return cls.val >>>> >>>> The fact that Guido says, >>>> >>>> "Now, I'm not saying that I like this better than the status quo. But >>>> I like it a lot better than [...] but it has the great advantage that >>>> it is backward compatible, and can be evolved into a PEP with a >>>> reference implementation without too much effort." >>>> >>>> shows that the proposal is viable. >>>> >>>> I'd like this new way of defining methods, what do you guys think? >>>> Anyone ready for writing a PEP? >>>> >>> What's the advantage? If there is not a good reason, I would strongly >>> opposed polluting the language. >> >> Did you read the blog post? The advantage is having a less confusing >> situation for newbies > > Once again: how is adding "magical" syntax going to reduce confusion ? > >> (confusing the number of arguments to a method >> call). > > This is only confusing the first time. The correct solution to this > problem is IMHO to better document Python's object model, specially how > the descriptor protocol turns functions into methods. As I've said in another reply the argument that "def self.meth( arg )" is confusing because "self" doesn't exist in the current scope as an instance is convincing to me. So I no longer like the alternate syntax mentioned by Guido. Still, improved error messages would be desirable (concerning the number of arguments passed to an instance method). Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From wyldwolf at gmail.com Mon Dec 22 10:22:58 2008 From: wyldwolf at gmail.com (Kevin Kelley) Date: Mon, 22 Dec 2008 09:22:58 -0600 Subject: Python's popularity In-Reply-To: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: <77895c1d0812220722x45a85c0eq55a39deff75f0345@mail.gmail.com> Python has it's place, usually getting things done, rather than being flashy. For example, while Java is still the "Enterprise King", both the leading application servers (Weblogic and Websphere) adopted Jython as their internal scripting language last year (or was it 2006?). It's used heavily for internal game scripting (Eve Online uses it very heavily (specifically Stackless), as does BF 2142). I don't know if in fact Python is the 3rd most popular language, but I would not be surprised by it passing up other high level scripting languages like Perl and Ruby. Kevin On Mon, Dec 22, 2008 at 9:11 AM, walterbyrd wrote: > I have read that python is the world's 3rd most popular language, and > that python has surpassed perl in popularity, but I am not seeing it. > > >From what I have seen: > > - in unix/linux sysadmin, perl is far more popular than python, > windows sysadmins typically don't use either. > - in web-development, php is far more popular than python - it's not > even close. > - when I did a search on dice, I found over 20X more jobs advertised > for ruby on rails developers, than for python dango developers. > - application development is dominated by java, c/c++, and maybe a > little visual basic. > - as I understand it, fortran is still the most popular language for > numberical programming. > > Of course, these are just observations on my part, nothing scientific > about it. But, I can't help but wonder how python's popularity was > determined. I suspect that a lot of people use python as a secondary > skill. For example, I use ms-word, but I'm not an ms-word > professional. > > Please note: I am not confusing popularity with quality. I am not > saying that php is better for web-dev, or anything like that. I am > just wondering how python is rated as being so popular, when python > does not seem to dominate anything. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From spooklight at gmail.com Sun Dec 14 16:35:44 2008 From: spooklight at gmail.com (uair01) Date: Sun, 14 Dec 2008 13:35:44 -0800 (PST) Subject: Output to file gets lost - don't know where to look ... Message-ID: <26a47940-c997-4da4-8f05-205b8d3001a8@d42g2000prb.googlegroups.com> I'm running python in IDLE on suse11. I have a python program and after writing 100kB to 200kB to a file, the write statements seem to stop working. Basically the print statements look like this: some loops: logFile.write(string1) logFile.write(string2) end of loops print(stringA) logFile.write(string3) logFile.write(string4) print(stringB) String1 and sometimes string2 / string3 (or a part of it) will end up in the file, but string4 not. stringsA and stringB get printed to the concole as expected. Stepping through the program with a debugger shows that *all* write- statements get executed. I use several logFile.flush() statements and a logFile.close() at the end. Is there some kind of file-size-limit or some kind of memory or buffer problem? Or could it be a bug in IDLE? I don't know where to look further. OH ... maybe just writing this message has helped. Now I see the following error messages inside the window from where I started IDLE. Could that be the cause? Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 1403, in __call__ return self.func(*args) File "/usr/lib/python2.5/idlelib/MultiCall.py", line 151, in handler r = l[i](event) File "/usr/lib/python2.5/idlelib/CallTips.py", line 62, in refresh_calltip_event self.open_calltip(False) File "/usr/lib/python2.5/idlelib/CallTips.py", line 65, in open_calltip self._remove_calltip_window() File "/usr/lib/python2.5/idlelib/CallTips.py", line 41, in _remove_calltip_window self.calltip.hidetip() File "/usr/lib/python2.5/idlelib/CallTipWindow.py", line 126, in hidetip self.label.destroy() AttributeError: 'NoneType' object has no attribute 'destroy' I will try the python program outside of IDLE. From xahlee at gmail.com Thu Dec 25 06:24:31 2008 From: xahlee at gmail.com (Xah Lee) Date: Thu, 25 Dec 2008 03:24:31 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <452ba58b-9377-4463-85e2-5ecdaa25a129@t39g2000prh.googlegroups.com> <6375k4pf1mleb6im67nkpec5olqbsom88e@4ax.com> Message-ID: > >On Dec 10, 2:47 pm, John W Kennedy wrote: > >> C: > > >> #include > >> #include > > >> void normal(int dim, float* x, float* a) { > >> float sum = 0.0f; > >> int i; > >> float divisor; > >> for (i = 0; i < dim; ++i) sum += x[i] * x[i]; > >> divisor = sqrt(sum); > >> for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; > > >> } Due to the low level of C, this C example should perhaps then accept a sequence of numbers separated by space, and print the output. Having dimension as part of input is not acceptable. For examples in other langs that can take any input (in source code) and print output, see: http://xahlee.org/UnixResource_dir/writ/Mathematica_expressiveness.html A new addition is in Scheme Lisp: ;; Scheme Lisp. By Bakul Shah (define (normalize vec) (let ((d (sqrt (apply + (map (lambda (x) (* x x)) vec))))) (map (lambda (x) (/ x d)) vec))) (normalize '(3 4)) The JavaScript example: // Javascript. By William James function normalize( vec ) { var div=Math.sqrt(vec.map(function(x) x*x).reduce(function(a,b) a+b)) return vec.map(function(x) x/div) } is also not qualified. (it is syntax error in SpiderMonkey engine ?JavaScript-C 1.7.0 2007-10-03?) Xah ? http://xahlee.org/ ? From mirandasnailvv at gmail.com Fri Dec 19 19:43:25 2008 From: mirandasnailvv at gmail.com (mirandasnailvv at gmail.com) Date: Fri, 19 Dec 2008 16:43:25 -0800 (PST) Subject: old bay shrimp boil recipe - Free Message-ID: <544e07fe-ea30-4b78-9328-43c7d36608dd@r15g2000prd.googlegroups.com> old bay shrimp boil recipe . . . *******CLICK HERE******** http://club247.cn/old-bay-shrimp-boil-recipe ***************************** . . . . . . . . . . . . old bay shrimp boil recipe From pavlovevidence at gmail.com Sat Dec 6 19:19:31 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 6 Dec 2008 16:19:31 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> Message-ID: On Dec 6, 4:39?pm, "Russ P." wrote: > On Dec 6, 1:21?pm, Carl Banks wrote: > > > > > On Dec 6, 9:12?am, "Russ P." wrote: > > > > On Dec 6, 1:02?am, Antoine De Groote wrote: > > > > > Allowing "$" as a substitute for "self" wouldn't require this new syntax. > > > > > class C: > > > > ? ? def method($, arg): > > > > ? ? ? ? $.value = arg > > > > > I'm strongly against this. This looks ugly and reminds me of Perl and > > > > Ruby. (I don't have anything against these languages, but there's a > > > > reason I use Python). > > > > > Russ P. wrote: > > > > > On Dec 5, 6:21 pm, "Daniel Fetchinson" > > > > > wrote: > > > > >> Hi folks, > > > > > >> The story of the explicit self in method definitions has been > > > > >> discussed to death and we all know it will stay. However, Guido > > > > >> himself acknowledged that an alternative syntax makes perfect sense > > > > >> and having both (old and new) in a future version of python is a > > > > >> possibility since it maintains backward compatibility. The alternative > > > > >> syntax will be syntactic sugar for the old one. This blog post of his > > > > >> is what I'm talking about: > > > > > >>http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... > > > > > >> The proposal is to allow this: > > > > > >> class C: > > > > >> ? ? def self.method( arg ): > > > > >> ? ? ? ? self.value = arg > > > > >> ? ? ? ? return self.value > > > > > >> instead of this: > > > > > >> class C: > > > > >> ? ? def method( self, arg ): > > > > >> ? ? ? ? self.value = arg > > > > >> ? ? ? ? return self.value > > > > > >> I.e. explicit self stays only the syntax is slightly different and may > > > > >> seem attractive to some. As pointed out by Guido classmethods would > > > > >> work similarly: > > > > > >> class C: > > > > >> ? ? @classmethod > > > > >> ? ? def cls.method( arg ): > > > > >> ? ? ? ? cls.val = arg > > > > >> ? ? ? ? return cls.val > > > > > >> The fact that Guido says, > > > > > >> "Now, I'm not saying that I like this better than the status quo. But > > > > >> I like it a lot better than [...] but it has the great advantage that > > > > >> it is backward compatible, and can be evolved into a PEP with a > > > > >> reference implementation without too much effort." > > > > > >> shows that the proposal is viable. > > > > > >> I'd like this new way of defining methods, what do you guys think? > > > > >> Anyone ready for writing a PEP? > > > > > >> Cheers, > > > > >> Daniel > > > > > >> -- > > > > >> Psss, psss, put it down! -http://www.cafepress.com/putitdown > > > > > > I like it. > > > > > > I'll even go a step further and suggest that "$" be allowed as a > > > > > substitute for "self". It looks like a capital "S" (for Self), and it > > > > > stands out clearly. It also makes code more succinct with no loss of > > > > > readability. Think of the line wraps that could be avoided. > > > > It looks "ugly" simply because it is new to you. Once you get used to > > > it, I'll bet it will look fine. And resemblance to another language is > > > not a very good reason to reject it. > > > Perl is not new to me and I am familiar with the syntax, such as it > > is. ?I find it unspeakably ugly. ?So, no, you would lose your bet if > > it were me. > > > Carl Banks > > I don't know much about Perl, but my understanding is that a dollar > sign must be used every time a variable is dereferenced, as in bash or > other shell languages. What we are proposing here is something > entirely different: the dollar sign would simply be a shorthand for > "self". In Perl, the dollar sign is clutter, but in this case it > actually reduces clutter. But it's ugly. No amount of rationalization will make it not ugly. > Python already uses shorthand extensively. How about "def"? For people > who are so worried about self-explanatory symbols, what the heck does > that stand for? Default? Defeat? Defect? Defunct? Defer? > > At some time in the past, a conscious decision was made to save three > characters in the word "define" by abbreviating it as "def". The > suggestion to abbreviate "self" as "$" also saves three characters. > And "self" appears much more often than "def", so an abbreviation is > equally or more justified in my opinion. def isn't ugly. Carl Banks From gagsl-py2 at yahoo.com.ar Thu Dec 18 19:11:15 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Dec 2008 22:11:15 -0200 Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> <51866e70-8a6e-4338-94bd-59913990e342@k36g2000pri.googlegroups.com> Message-ID: En Thu, 18 Dec 2008 08:35:58 -0200, Aaron Brady escribi?: > On Dec 17, 7:16?pm, "Gabriel Genellina" > wrote: >> En Wed, 17 Dec 2008 22:46:32 -0200, Aaron Brady ? >> escribi?: >> >> >> >> > On Dec 17, 5:05?pm, "Gabriel Genellina" >> > wrote: >> >> En Wed, 17 Dec 2008 12:21:38 -0200, Jeremy Sanders ? >> >> escribi?: >> >> >> > It would be nice if Python created pipes that are properly ? >> >> inheritable by >> >> > default by child processes, as they're mostly used for IPC. >> >> >> I'd say it is a bug in os.pipe implementation; they should be ? >> >> inheritable ? >> >> by default, as in posix (after all, the code is in "posixmodule.c"). >> >> > The code looks like this: >> >> > ? ?ok = CreatePipe(&read, &write, NULL, 0); >> > ? ?Py_END_ALLOW_THREADS >> > ? ?if (!ok) >> > ? ? ? ? ? ?return win32_error("CreatePipe", NULL); >> > ? ?read_fd = _open_osfhandle((Py_intptr_t)read, 0); >> > ? ?write_fd = _open_osfhandle((Py_intptr_t)write, 1); >> >> > 'If lpPipeAttributes is NULL, the handle cannot be inherited.' ?You >> > could populate a 'SECURITY_ATTRIBUTES' structure, or call >> > DuplicateHandle on both of them. >> >> > A patch would look like this: >> >> > SECURITY_ATTRIBUTES sattribs; >> > sattribs.nLength = sizeof(sattribs); >> > sattribs.lpSecurityDescriptor = NULL; >> > sattribs.bInheritHandle = TRUE; >> > ok = CreatePipe(&read, &write, &sattribs, 0); >> >> Yes, that's exactly how os.popen does it (in posixmodule.c) >> >> > This still doesn't answer whether the file descriptor return by >> > '_open_osfhandle' can be inherited too. >> >> It doesn't matter. The OS only cares about file handles, not C RTL ? >> structures. >> >> -- >> Gabriel Genellina > > Ah, I see. Was it an executive decision about what is Pythonic, or > just a bug? Do you think the patch would be accepted? I probably > ought to mimic a small Python embedding to see if it needs anything > else. I don't know - I guess someone (years ago) blindly just replaced the pipe() system call by a CreatePipe call without further analysis. This is how I would summarize the issue: Pros (of changing os.pipe() to return inheritable pipes): - it isn't explicitely documented whether os.pipe() returns inheritable pipes or not, so both versions are "right" according to the documentation. - if someone relies on pipes being non-inheritable on Windows, that is undocumented behaviour, and Python has the right to change it. - the change would improve POSIX compatibility, it mimics what os.pipe() does on those OS. - inheritable pipes are less surprising for guys coming from other OS - inheritable pipes are a lot more useful than non-inheritable ones when doing IPC (probably its main usage). Cons: - os.pipe has behaved that way since long time ago. - some programs *might* break, if they relied on pipes being non-inheritable on Windows, even if that was undocumented behaviour. -- Gabriel Genellina From manu3d at gmail.com Fri Dec 12 12:22:34 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Fri, 12 Dec 2008 09:22:34 -0800 (PST) Subject: Bidirectional Networking References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <6qeht0Fc3541U1@mid.individual.net> Message-ID: <782258db-2bdc-45a7-8d8f-7a036d574985@t26g2000prh.googlegroups.com> Thank you both for the suggestions! Eventually I tried with threading as illustrated in the code below. And it works pretty well! The only problem I'm having with it is that as the server is a daemon the program should end when the client thread cease to be alive. But it doesn't seem to work that way and I'm not sure what's going on! I did achieve my objective though. Two separate instances of the code below will happily send random numbers to each other for a few seconds! Manu ------------------------- To use the following code, cut&paste into two separate *.py files and invert the port numbers in one file. Then, start them in two separate shells. WARNING: as mentioned above the two program do not exit and must be killed, i.e. through the Windows Task Manager or the unix kill command. ------------------------- import SocketServer import socket import threading import random from time import sleep ## Network request handler class MyTCPHandler(SocketServer.StreamRequestHandler): def handle(self): self.data = self.rfile.readline().strip() print "-> RECV: " + self.data + " - Sent by:" + self.client_address[0] ## Server Thread class AsyncServer(threading.Thread): def __init__(self, localServer): threading.Thread.__init__(self) self.server = SocketServer.TCPServer(localServer, MyTCPHandler) def run(self): self.server.serve_forever() ## Client Thread class AsyncClient(threading.Thread): def __init__(self, remoteServer): threading.Thread.__init__(self) self.remoteServer = remoteServer def run(self): cycle = 0 while cycle < 1000: chance = random.random() if(chance < 0.01): randomNumber = int(random.random() * 1000) message = str(randomNumber) + " from remote cycle " + str(cycle) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(self.remoteServer) sock.send(message + "\n") sock.close() print("SENT ->: "+str(randomNumber)+ " by local cycle "+str(cycle)) except: print("Failed to send number on cycle "+str (cycle)) pass cycle += 1 sleep(0.01) ## Simulating local/remote servers with different ports localServer = ("localhost", 9999) remoteServer = ("localhost", 10000) asyncServer = AsyncServer(localServer) asyncServer.daemon = True asyncServer.start() asyncClient = AsyncClient(remoteServer) asyncClient.start() From bernhard.voigt at gmail.com Wed Dec 10 03:56:48 2008 From: bernhard.voigt at gmail.com (bernhard.voigt at gmail.com) Date: Wed, 10 Dec 2008 00:56:48 -0800 (PST) Subject: filter iterable based on predicate take from another iterable Message-ID: Hi, is there is a neat way to select items from an iterable based on predicates stored in another iterable without zipping? I can do something like this: import itertools foo = range(10) # select even numbers bar = map(lambda i: i%2, foo) foobarselected = itertools.ifilterfalse(lambda t: t[0], itertools.izip (bar,foo)) # for simplicity I want to work with the single item list, not the zipped one fooselected = list(t[1] for t in foobarselected) However, it would be nice to have a function combining the last two instructions. Something like itertools.ifilterother(bar, foo) -> yield iterator with items from foo where bar is true Thanks! Bernhard From python at bdurham.com Wed Dec 24 03:39:56 2008 From: python at bdurham.com (python at bdurham.com) Date: Wed, 24 Dec 2008 03:39:56 -0500 Subject: Strategy for determing difference between 2 very large dictionaries In-Reply-To: <6rea9hF16p8tU1@mid.uni-berlin.de> References: <1230102996.2303.1291616055@webmail.messagingengine.com> <6rea9hF16p8tU1@mid.uni-berlin.de> Message-ID: <1230107996.14276.1291622859@webmail.messagingengine.com> Hi Marc, > `keys()` creates a list in memory, `iterkeys()` does not. With > ``set(dict.keys())`` there is a point in time where the dictionary, the > list, and the set co-exist in memory. With ``set(dict.iterkeys())`` > only the set and the dictionary exist in memory. Perfect explanation. Thank you! Malcolm ----- Original message ----- From: "Marc 'BlackJack' Rintsch" To: python-list at python.org Date: 24 Dec 2008 08:30:41 GMT Subject: Re: Strategy for determing difference between 2 very large dictionaries On Wed, 24 Dec 2008 03:23:00 -0500, python wrote: > Hi Gabriel, > > Thank you very much for your feedback! > >> k1 = set(dict1.iterkeys()) > > I noticed you suggested .iterkeys() vs. .keys(). Is there any advantage > to using an iterator vs. a list as the basis for creating a set? I > understand that an iterator makes sense if you're working with a large > set of items one at a time, but if you're creating a non-filtered > collection, I don't see the advantage of using an iterator or a list. > I'm sure I'm missing a subtle point here :) `keys()` creates a list in memory, `iterkeys()` does not. With ``set(dict.keys())`` there is a point in time where the dictionary, the list, and the set co-exist in memory. With ``set(dict.iterkeys())`` only the set and the dictionary exist in memory. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list From dotancohen at gmail.com Sat Dec 6 10:06:44 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Sat, 6 Dec 2008 17:06:44 +0200 Subject: RELEASED Python 3.0 final In-Reply-To: <006101c95745$124bfea0$0d00a8c0@hendrik> References: <874p1jux8u.fsf@benfinney.id.au> <87iqpyt80i.fsf@benfinney.id.au> <006101c95745$124bfea0$0d00a8c0@hendrik> Message-ID: <880dece00812060706k480735d4o8f03c65918309f93@mail.gmail.com> 2008/12/5 Hendrik van Rooyen : > I second the motion to use pish and tosh for a first level of disagreement. > > I recommend the rather archaic "Balderdash" as the next step in the > escalation of disagreement... > http://bash.org/?23396 -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-??-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From riklaunim at gmail.com Tue Dec 23 11:29:45 2008 From: riklaunim at gmail.com (riklaunim at gmail.com) Date: Tue, 23 Dec 2008 08:29:45 -0800 (PST) Subject: Get applications to open a given file (Mac and, or Windows) Message-ID: Under Linux/Unix I use GIO (pygobject) or gnome-vfs-python to get a list of installed applications that can open given file (for example image in graphics software). Is there something that can be used for MS Windows or Mac OS X? From bearophileHUGS at lycos.com Thu Dec 25 13:58:14 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 25 Dec 2008 10:58:14 -0800 (PST) Subject: Syntax error for print References: <2b65c6e1-b5a9-438d-a45c-b8f9d18228de@s1g2000prg.googlegroups.com> Message-ID: On Dec 25, 7:53?pm, jsm4... at gmail.com wrote: > IDLE 3.0>>> print "hello" > > SyntaxError: invalid syntax (, line 1)>>> 3+3 > 6 > >>> var = 4 > >>> var = var*4 > >>> print var > > SyntaxError: invalid syntax (, line 1) > > > > Any idea on why I am getting this error. > I have just started learning python and I am stuck at first thing > itself. > Any help would be greatly appreciated. > > Thanks, > Jeetu Sahil The print of Python3 needs parentheses: print(var) Older Python versions are different. Bye, bearophile From your.master at gmail.com Thu Dec 11 12:08:04 2008 From: your.master at gmail.com (Brandon) Date: Thu, 11 Dec 2008 09:08:04 -0800 (PST) Subject: dictionary idiom needed Message-ID: <383976cf-53fb-48e4-b028-8f568468ce77@r36g2000prf.googlegroups.com> Hi all, I have a series of lists in format ['word', 'tagA', 'tagB']. I have converted this to a few dicts, such as one in which keys are tuples of ('word', 'tagB'), and the values are the number of times that key was found. I need an dictionary idiom whereby I can find all instances of a given 'word' with any 'tagB', and then subdivide into all instances of a given 'tagB'. In both cases I would want the value as a count of all instances found. Can this be done with dictionaries? Or should I back up and do this with lists? All of the nested for loops I have tried return replicated results, so I can't trust those values. Thanks for any pointers, Brandon From lists at cheimes.de Mon Dec 22 18:05:58 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 23 Dec 2008 00:05:58 +0100 Subject: python3 urlopen(...).read() returns bytes In-Reply-To: <5496b34d-7ce4-4281-9f01-aed12dab9fd3@f33g2000vbf.googlegroups.com> References: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> <5496b34d-7ce4-4281-9f01-aed12dab9fd3@f33g2000vbf.googlegroups.com> Message-ID: ajaksu schrieb: > That said, a "decode to declared HTTP header encoding" version of > urlopen could be useful to give some users the output they want (text > from network io) or to make it clear why bytes is the safe way. Yeah, your idea sounds both useful and feasible. A patch is welcome! :) Christian From elbertlev at hotmail.com Sun Dec 14 00:53:17 2008 From: elbertlev at hotmail.com (Lev Elbert) Date: Sat, 13 Dec 2008 21:53:17 -0800 (PST) Subject: stable algorithm with complexity O(n) References: Message-ID: <42d4f840-47d4-4473-be58-7a6793dfdfae@o4g2000pra.googlegroups.com> 1. Comparison sorts have n*ln(n) complexity - does not do 2. Counting sort has the complexity O(d), where d is domain (in our case n^2) - does not do. 3. Radix sorts have the complexity O(n*k), where k is number of bits in integer. (32?) There are 2 variants: a. most significant digit (MSD), b. least significant digit (LSD). The LSD radix sort is stable. Good luck. From iofferkicks003 at gmail.com Sun Dec 21 08:58:13 2008 From: iofferkicks003 at gmail.com (www.iofferkicks.com) Date: Sun, 21 Dec 2008 05:58:13 -0800 (PST) Subject: www.iofferkicks.com china cheap wholesale nike shoes,air jordan shoes,air force one shoes. Message-ID: Get Nike Shoes at Super Cheap Prices Discount Nike air jordans (www.iofferkicks.com) Discount Nike Air Max 90 Sneakers (www.iofferkicks.com) Discount Nike Air Max 91 Supplier (www.iofferkicks.com) Discount Nike Air Max 95 Shoes Supplier (www.iofferkicks.com) Discount Nike Air Max 97 Trainers (www.iofferkicks.com) Discount Nike Air Max 2003 Wholesale (www.iofferkicks.com) Discount Nike Air Max 2004 Shoes Wholesale (www.iofferkicks.com) Discount Nike Air Max 2005 Shop (www.iofferkicks.com) Discount Nike Air Max 2006 Shoes Shop (www.iofferkicks.com) Discount Nike Air Max 360 Catalogs (www.iofferkicks.com) Discount Nike Air Max Ltd Shoes Catalogs (www.iofferkicks.com) Discount Nike Air Max Tn Men's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 2 Women's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 3 Customize (www.iofferkicks.com) Discount Nike Air Max Tn 4 Shoes Customize ( www.iofferkicks.com) Discount Nike Air Max Tn 6 Supply (www.iofferkicks.com) Discount Nike Shox NZ Shoes Supply (www.iofferkicks.com) Discount Nike Shox OZ Sale (www.iofferkicks.com) Discount Nike Shox TL Store (www.iofferkicks.com) Discount Nike Shox TL 2 Shoes Store (www.iofferkicks.com) Discount Nike Shox TL 3 Distributor (www.iofferkicks.com) Discount Nike Shox Bmw Shoes Distributor (www.iofferkicks.com) Discount Nike Shox Elite Shoes Manufacturer (www.iofferkicks.com) Discount Nike Shox Monster Manufacturer (www.iofferkicks.com) Discount Nike Shox R4 Running Shoes (www.iofferkicks.com) Discount Nike Shox R5 Mens Shoes (www.iofferkicks.com) Discount Nike Shox Ride Womens Shoes (www.iofferkicks.com) Discount Nike Shox Rival Shoes Wholesaler (www.iofferkicks.com) Discount Nike Shox Energia Wholesaler (www.iofferkicks.com) Discount Nike Shox LV Sneaker (www.iofferkicks.com) Discount Nike Shox Turbo Suppliers (www.iofferkicks.com) Discount Nike Shox Classic Shoes Suppliers (www.iofferkicks.com) Discount Nike Shox Dendara Trainer (www.iofferkicks.com) Discount Nike Air Jordan 1 Seller (www.iofferkicks.com) Discount Nike Air Jordan 2 Shoes Seller (www.iofferkicks.com) Discount Nike Air Jordan 3 Collection (www.iofferkicks.com) Discount Nike Air Jordan 4 Shoes Collection (www.iofferkicks.com) Discount Nike Air Jordan 5 Chaussure Shoes (www.iofferkicks.com) Discount Nike Air Jordan 6 Catalog (www.iofferkicks.com) Discount Nike Air Jordan 7 Shoes Catalog (www.iofferkicks.com) Discount Nike Air Jordan 8 Customized (www.iofferkicks.com) Discount Nike Air Jordan 9 Shoes Customized (www.iofferkicks.com) Discount Nike Air Jordan 10 Wholesalers (www.iofferkicks.com) Discount Nike Jordan 11 Shoes Wholesalers (www.iofferkicks.com) Discount Nike Air Jordan 12 Factory (www.iofferkicks.com) Discount Nike Air Jordan 13 Shoes Factory (www.iofferkicks.com) Discount Nike Air Jordan 14 Shoes Sell (www.iofferkicks.com) Discount Nike Air Jordan 16 Exporter (www.iofferkicks.com) Discount Nike Air Jordan 17 Shoes Exporter (www.iofferkicks.com) Discount Nike Air Jordan 18 Offer (www.iofferkicks.com) Discount Nike Air Jordan 19 Shoes Offer (www.iofferkicks.com) Discount Nike Air Jordan 20 Manufacture (www.iofferkicks.com) Discount Nike Jordan 21 Shoes Manufacture (www.iofferkicks.com) EMAIL:IOFFERKICKS at GMAIL.COM MSN :IOFFERKICKS at MSN.COM From bkamrani at gmail.com Thu Dec 4 04:11:17 2008 From: bkamrani at gmail.com (bkamrani at gmail.com) Date: Thu, 4 Dec 2008 01:11:17 -0800 (PST) Subject: performance question: dictionary or list, float or string? References: <01453507$0$20670$c3e8da3@news.astraweb.com> Message-ID: Thanks for your questions. Here come some answer below. On Dec 2, 2:50?pm, Steven D'Aprano wrote: > On Tue, 02 Dec 2008 03:41:29 -0800,bkamraniwrote: > > Hi Python gurus! > > I'm going to read in an Ascii file containing float numbers in rows and > > columns (say 10 columns 500000 rows) for further numerical process. > > Which format is best to save them in, eg, dictionary, list, or numpy > > array when it comes to performance? > > That depends on: > > (1) What do you mean by performance? Speed or memory use? Well, I think the speed is more important in this case as the volume of data is not large. > (2) Do you care about the performance of reading the data in, or the > performance of working with the data later, or both? The reading process is pretty fast and in range of some second, but I meant the performance of working with data. > (3) What do you intend to do with the numbers later? Normal numercal calcualtion such as sum, multiplication. (but not matrix multiplication) Thanks /Ben > > Will it be beneficial to convert all strings to float directly after > > reading or it doesn't matter to save them as string and thereafter when > > it comes to calculation convert them to floats? > > That depends on what you intend to do with them. Since you're doing > numerical processing, it's probably a good idea to convert them to > numbers rather than strings. > > -- > Steven From prologic at shortcircuit.net.au Tue Dec 30 19:56:11 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 10:56:11 +1000 Subject: get method In-Reply-To: <495AC2B3.7040706@mrabarnett.plus.com> References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> <495AAB97.5010707@mrabarnett.plus.com> <71508d7a-f678-40ba-801c-0bbfbbab961e@r15g2000prh.googlegroups.com> <495AC2B3.7040706@mrabarnett.plus.com> Message-ID: On Wed, Dec 31, 2008 at 10:54 AM, MRAB wrote: > Occasionally someone posts here wanting to count items and solutions > involving dict or defaultdict are suggested, and I think that a 'bag' class > would be useful. The 'set' class was introduced first in a module, but it > soon became a builtin. My posting was intended a possible reference > implementation. I think it would be a nice addition to the collections module. cheers James From steve at holdenweb.com Sun Dec 28 09:29:51 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 28 Dec 2008 09:29:51 -0500 Subject: strange behavior of math.sqrt() in new 3.0 version In-Reply-To: References: Message-ID: Tim Roberts wrote: > Scott David Daniels wrote: >> I avoid using single-letter variables except where I know the types >>from the name (so I use i, j, k, l, m, n as integers, s as string, >> and w, x, y, and z I am a little looser with (but usually float or >> complex). > > It's amazing to me that Fortran continues to live on in the hearts and > minds of today's programmers. Well I think it's more that the original Fortran programmers were applied mathematicians, who have always tended to use i through m as integer variables, and that usage continues both in programming and mathematics today. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From prabhu.ranjith at gmail.com Wed Dec 10 21:12:22 2008 From: prabhu.ranjith at gmail.com (free online study about computer language) Date: Wed, 10 Dec 2008 18:12:22 -0800 (PST) Subject: @ you can study through online freely all the computer language. Easy way and free registration. Visit www.tiketin.blogspot.com @ Message-ID: Now easy way to clear all your computer language doubts and to learn more visit www.tiketin.blogspot.com everything is free. You can also get e-books freely. No need to waste time and money visit www.tiketin.blogspot.com way to learn from your home itself visit www.tiketin.blogspot.com From tjreedy at udel.edu Wed Dec 10 21:59:07 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 10 Dec 2008 21:59:07 -0500 Subject: internal circular class references In-Reply-To: References: Message-ID: James Stroud wrote: > I resisted posting a similar question recently. After much > consideration, I realized that the inability to reference a class inside > its own definition must have been a deliberate design of the language. The class *does not exist* to be referenced from inside its body until after the body is executed and type(name, bases, namespace) is called. class name(bases): body is more or less equivalent to name = type('name', bases, exec(body,{})) except that the exec function (in 3.0) returns None instead of the passed in namespace. I think is would be possible to create and name-bind a blank class first, but then there would need to be a mechanism delete the class if the body execution failed. Because class definition can be nested, the mechanism would need a stack of classes. In addition, this would be a change in sequence from the usual assignment statement. tjr From benjamin.kaplan at case.edu Mon Dec 8 09:48:27 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 8 Dec 2008 09:48:27 -0500 Subject: Beginner trying to understand functions. In-Reply-To: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> Message-ID: On Mon, Dec 8, 2008 at 9:24 AM, cadmuxe wrote: > i think we should use raw_input('Please enter your name: ') instead of > input('Please enter your name: ') > Print is a function in this code and range returns an iterator (or else list(range(18,31)) is redundant). I think the OP is using python 3. Guess we're all going to have to get used to some of the changes, like raw_input being renamed to input. > 2008/12/8 Peter Otten <__peter__ at web.de> > > simonh wrote: >> >> > In my attempt to learn Python I'm writing a small (useless) program to >> > help me understand the various concepts. I'm going to add to this as I >> > learn to serve as a single place to see how something works, >> > hopefully. Here is the first approach: >> >> > That works fine. Then I've tried to use functions instead. The first >> > two work fine, the third fails: >> >> > def getName(): >> > name = input('Please enter your name: ') >> > print('Hello', name) >> > >> > def getAge(): >> > while True: >> > try: >> > age = int(input('Please enter your age: ')) >> > break >> > except ValueError: >> > print('That was not a valid number. Please try again.') >> > >> > def checkAge(): >> > permitted = list(range(18, 31)) >> > if age in permitted: >> > print('Come on in!') >> > elif age < min(permitted): >> > print('Sorry, too young.') >> > elif age > max(permitted): >> > print('Sorry, too old.') >> > >> > getName() >> > getAge() >> > checkAge() >> > >> > I get this error message: NameError: global name 'age' is not >> > defined. >> > >> > I'm stuck, can someone help? Thanks. >> >> >> Generally, when you calculate something within a function you tell it the >> caller by returning it: >> >> >>> def get_age(): >> ... return 74 >> ... >> >>> get_age() >> 74 >> >>> age = get_age() >> >>> age >> 74 >> >> And if you want a function to act upon a value you pass it explicitly: >> >> >>> def check_age(age): >> ... if 18 <= age <= 30: >> ... print("Come in") >> ... else: >> ... print("Sorry, you can't come in") >> ... >> >>> check_age(10) >> Sorry, you can't come in >> >>> check_age(20) >> Come in >> >> To check the age determined by the get_age() function you do: >> >> >>> age = get_age() >> >>> check_age(age) >> Sorry, you can't come in >> >> Peter >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Tue Dec 9 01:59:10 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Dec 2008 04:59:10 -0200 Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <1228766842.5709.28.camel@aalcdl07.lib.unc.edu> Message-ID: En Mon, 08 Dec 2008 18:07:22 -0200, J. Cliff Dyer escribi?: > On Wed, 2008-12-03 at 21:42 -0800, Warren DeLano wrote: >> Anyway, it seems obvious that the right decision for our customers (or >> more importantly, for their countless lines of autogenerated-Python >> log, >> state, and code files from the past decade) is to stick with C/Python >> 2.5.x for the time being and plan to make the jump to a > > All that broken code does sound like a hassle. However, I think the > workaround would be a fairly simple refactor: > > 1) make 'as_type' (or some other equivalent name like 'as_') a synonym > for 'as': Another workaround was posted last Wednesday by Matimus in message http://groups.google.com/group/comp.lang.python/msg/128a2cec74a96d3d Both seem like a reasonable solution. -- Gabriel Genellina From aahz at pythoncraft.com Sat Dec 6 23:18:35 2008 From: aahz at pythoncraft.com (Aahz) Date: 6 Dec 2008 20:18:35 -0800 Subject: Learning Python now coming from Perl References: Message-ID: In article , Bertilo Wennergren wrote: > >The main reason I waited until Python 3000 came out is the new way >Unicode is handled. The old way seemed really broken to me. Much of >what I do when I program consists of juggling Unicode text (real >Unicode text with lots of actual characters outside of Latin 1). So in >my case learning version 2.x first might not be very convenient. I'd >just get bogged down with the strange way 2.x handles such data. I'd >rather skip that completely and just go with the Unicode handling in >3.0. Sounds like you have a good use-case for 3.0 -- go to it! -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From basu at archlinux.us Mon Dec 29 02:26:52 2008 From: basu at archlinux.us (member Basu) Date: Mon, 29 Dec 2008 02:26:52 -0500 Subject: Get a list of functions in a file Message-ID: I'm putting some utility functions in a file and then building a simple shell interface to them. Is their some way I can automatically get a list of all the functions in the file? I could wrap them in a class and then use attributes, but I'd rather leave them as simple functions. Thanks, Basu -------------- next part -------------- An HTML attachment was scrubbed... URL: From eric at ericaro.net Thu Dec 18 14:52:52 2008 From: eric at ericaro.net (eric) Date: Thu, 18 Dec 2008 11:52:52 -0800 (PST) Subject: Factoring Polynomials References: Message-ID: <5dfe1cf3-530d-4e31-833e-e26db85611be@d36g2000prf.googlegroups.com> On Dec 18, 8:37?pm, collin.da... at gmail.com wrote: > I am trying to write a simple application to factor polynomials. I > wrote (simple) raw_input lines to collect the a, b, and c values from > the user, but I dont know how to implement the quadratic equation > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > into python. Any ideas? with numpy: from numpy import * s=[1,-1] x = -b+s*sqrt( b**2-4*a*c )/(2*a) Eric http://codeslash.blogspot.com From dickinsm at gmail.com Tue Dec 9 06:22:11 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 9 Dec 2008 03:22:11 -0800 (PST) Subject: Rich Comparisons Gotcha References: Message-ID: <07cbe992-97a0-4c30-9244-ad4acb75e743@q26g2000prq.googlegroups.com> On Dec 8, 2:24?pm, Rasmus Fogh wrote: > So, I would much prefer a language change. I am not competent to even > propose one properly, but I'll try. I don't see any technical problems in what you propose: as far as I can see it's entirely feasible. However: > should. On the minus side there would be the difference between > '__equal__' and '__eq__' to confuse people. I think this is exactly what makes the idea a non-starter. There are already enough questions on the lists about when to use 'is' and when to use '==', without adding an 'equals' function into the mix. It would add significant extra complexity to the core language, for questionable (IMO) gain. There are certainly other languages for which this distinction would make sense; I just don't think it's appropriate for Python, with its emphasis on practicality and and simplicity. Mark On the plus side the behaviour > of objects inside collections would now be explicitly defined, and __eq__ > and __equal__ would be so similar that most people could ignore the > distinction. > > Some examples: > > # NaN: > # For floats, __equal__ would be the same as __eq__. For NaN this gives>>> x = float('NaN') > >>> y = float('NaN') > >>> x == x > False > >>> equal(x,x) > True > >>> equal(x,y) > > False > # It may be problematical mathematically, but computationally it makes > # perfect sense that looking in a given storage location will give you the > # same value every time, even if the actual value happens to be undefined. > # The behaviour is simple to describe, and indeed NaN does behave this way > # in collections at the moment. All we are doing is documenting it clearly. > > # numpy > Numpy would have no __equal__ function, so we would have pure identity > semantics - 'equals(x,y)' would be the same as 'x is y' > > # ordinary numbers. > Any Python object with value semantics would need an __equal__ function > with the correct behaviour. > Mark Dickinson pointed out the thread "Comparing float and decimal", which > shows that comparisons between float and decimal numbers do not currently > satisfy 3). It would not be attractive to have __equal__ and __eq__ behave > differently for ordinary numbers, so if the relevant __eq__ can not be > fixed that is a problem for my proposal. > > At this point I shall try to retire gracefully. Regrettably I am not > competent to discuss if this can be done, how it can be done, and how > much work is required. > > Rasmus > > --------------------------------------------------------------------------- > Dr. Rasmus H. Fogh ? ? ? ? ? ? ? ? ?Email: r.h.f... at bioc.cam.ac.uk > Dept. of Biochemistry, University of Cambridge, > 80 Tennis Court Road, Cambridge CB2 1GA, UK. ? ? FAX (01223)766002 From bearophileHUGS at lycos.com Sun Dec 21 12:51:58 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 21 Dec 2008 09:51:58 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> <88a122de-14c6-4025-b36c-9a39bdd50d86@i20g2000prf.googlegroups.com> Message-ID: <9b3e509d-25d4-44d1-99a2-ee3515225f88@w24g2000prd.googlegroups.com> MRAB: > Interesting. The re module uses a form of bytecode. Not sure about the > relative cost of the dispatch code, though. I was talking about the main CPython VM, but the same ideas may be adapted for the RE engine too. Bye, bearophile From rcdailey at gmail.com Mon Dec 8 17:23:19 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 8 Dec 2008 14:23:19 -0800 (PST) Subject: Calling function from a string Message-ID: <7bc1be6f-121e-409a-9e08-f2dd2a86f241@e25g2000vbe.googlegroups.com> Hi, I have a string representing the name of a function in Python 3.0. How can I call the function name represented by this string *without* creating a mapping? From nad at acm.org Thu Dec 4 13:53:06 2008 From: nad at acm.org (Ned Deily) Date: Thu, 04 Dec 2008 10:53:06 -0800 Subject: Pythonic design patterns References: Message-ID: In article , Slaunger wrote: > I was therefore wondering if you could recommend a book or a resource > concerning design patterns with special focus on the possibilities in > Python? Check out any or all of Alex Martelli's talks on Python Design Patterns (search YouTube for "google developer python alex"), and download the notes at . -- Ned Deily, nad at acm.org From gagsl-py2 at yahoo.com.ar Mon Dec 8 03:30:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Dec 2008 06:30:56 -0200 Subject: Don't you just love writing this sort of thing :) In-Reply-To: References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: En Sun, 07 Dec 2008 05:34:39 -0200, Lawrence D'Oliveiro escribi?: > In message , Arnaud Delobelle wrote: > >> * you give the impression of being arrogant; > > Oddly enough, I wasn't the one who started by criticizing other people's > code. I have no ego about my code; I gladly accept criticisms. But > perhaps > some other people are not so thick-skinned and do not like getting as > they > give... May I ask then *why* did you chose to post your code fragment? Did I miss something? -- Gabriel Genellina From castironpi at gmail.com Thu Dec 18 20:45:21 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 18 Dec 2008 17:45:21 -0800 (PST) Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> <51866e70-8a6e-4338-94bd-59913990e342@k36g2000pri.googlegroups.com> Message-ID: <7f601ac7-fe98-464e-a661-2b4eebf38ffb@o40g2000prn.googlegroups.com> On Dec 18, 6:11?pm, "Gabriel Genellina" wrote: > En Thu, 18 Dec 2008 08:35:58 -0200, Aaron Brady > escribi?: > > > > > On Dec 17, 7:16?pm, "Gabriel Genellina" > > wrote: > >> En Wed, 17 Dec 2008 22:46:32 -0200, Aaron Brady ? > >> escribi?: > > >> > On Dec 17, 5:05?pm, "Gabriel Genellina" > >> > wrote: > >> >> En Wed, 17 Dec 2008 12:21:38 -0200, Jeremy Sanders ? > >> >> escribi?: > > >> >> > It would be nice if Python created pipes that are properly ? > >> >> inheritable by > >> >> > default by child processes, as they're mostly used for IPC. > > >> >> I'd say it is a bug in os.pipe implementation; they should be ? > >> >> inheritable ? > >> >> by default, as in posix (after all, the code is in "posixmodule.c"). > > >> > The code looks like this: > > >> > ? ?ok = CreatePipe(&read, &write, NULL, 0); > >> > ? ?Py_END_ALLOW_THREADS > >> > ? ?if (!ok) > >> > ? ? ? ? ? ?return win32_error("CreatePipe", NULL); > >> > ? ?read_fd = _open_osfhandle((Py_intptr_t)read, 0); > >> > ? ?write_fd = _open_osfhandle((Py_intptr_t)write, 1); > > >> > 'If lpPipeAttributes is NULL, the handle cannot be inherited.' ?You > >> > could populate a 'SECURITY_ATTRIBUTES' structure, or call > >> > DuplicateHandle on both of them. > > >> > A patch would look like this: > > >> > SECURITY_ATTRIBUTES sattribs; > >> > sattribs.nLength = sizeof(sattribs); > >> > sattribs.lpSecurityDescriptor = NULL; > >> > sattribs.bInheritHandle = TRUE; > >> > ok = CreatePipe(&read, &write, &sattribs, 0); > > >> Yes, that's exactly how os.popen does it (in posixmodule.c) > > >> > This still doesn't answer whether the file descriptor return by > >> > '_open_osfhandle' can be inherited too. > > >> It doesn't matter. The OS only cares about file handles, not C RTL ? > >> structures. > > >> -- > >> Gabriel Genellina > > > Ah, I see. ?Was it an executive decision about what is Pythonic, or > > just a bug? ?Do you think the patch would be accepted? ?I probably > > ought to mimic a small Python embedding to see if it needs anything > > else. > > I don't know - I guess someone (years ago) blindly just replaced the > pipe() system call by a CreatePipe call without further analysis. > > This is how I would summarize the issue: > > Pros (of changing os.pipe() to return inheritable pipes): > > - it isn't explicitely documented whether os.pipe() returns inheritable > pipes or not, so both versions are "right" according to the documentation. > - if someone relies on pipes being non-inheritable on Windows, that is > undocumented behaviour, and Python has the right to change it. > - the change would improve POSIX compatibility, it mimics what os.pipe() > does on those OS. > - inheritable pipes are less surprising for guys coming from other OS > - inheritable pipes are a lot more useful than non-inheritable ones when > doing IPC (probably its main usage). > > Cons: > > - os.pipe has behaved that way since long time ago. > - some programs *might* break, if they relied on pipes being > non-inheritable on Windows, even if that was undocumented behaviour. > > -- > Gabriel Genellina Hi, Microsoft has this example: http://msdn.microsoft.com/en-us/library/aa298531.aspx It creates two descriptors (not handles) with '_pipe'. Then it spawns a subprocess using 'spawnl', which correctly inherits a descriptor. So, if 'Popen' could mimic 'spawnl', then 'os.pipe', and consequently, 'os.read', 'os.write', &c. could stay as is. From nopsidy at gmail.com Tue Dec 9 00:53:20 2008 From: nopsidy at gmail.com (RP) Date: Mon, 8 Dec 2008 23:53:20 -0600 Subject: Password input in console/terminal Message-ID: Hello All, This is my first REAL post(question) to Python-List. I know I can take input from a user with raw_input() How do I take password input in console? Any Help would be Greatly Appreciated. Thank You. RP -------------- next part -------------- An HTML attachment was scrubbed... URL: From warren at delsci.com Thu Dec 4 00:42:37 2008 From: warren at delsci.com (Warren DeLano) Date: Wed, 3 Dec 2008 21:42:37 -0800 Subject: "as" keyword woes Message-ID: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> > > Why was it necessary to make "as" a reserved keyword? > > I can't answer for the Python developers as to why they *did* make it > a reserved word. > > But I can offer what I believe is a good reason why it *should* be a > reserved word: Because simple is better than complex, and special > cases aren't special enough to break the rules. So you prefer broken code to broken rules, eh? Your customers must love that! This is exactly the kind of ivory-tower thinking I feared might be behind the decision (form over function, damn the users to hell, etc.) > > And more to the point, why was it necessary to prevent developers > > from being able to refer to attributes named "as"? > > There aren't special rules for which names can be use in which way, > and that's a *good* thing. Any name that is valid in one area of > Python syntax is valid in all Python syntax. Except that Python syntax has proven itself to be a non-backwards compatible moving target. Eliminating cruft and adding new functionality is one thing, but introducing a whole new two-letter keyword so long after the game has begun? That seems well over the line of what can be considered reasonable. > > Why can't the parser distinguish between a standalone " as " keyword > > and ".as" used as an object/attribute reference? > > Because that would require special-casing some names as being > forbidden in syntax where other names are allowed. Special cases in > language syntax are to be avoided where feasible. Am I the only one picking up on the irony here? "as" exists largely to provide a mechanism for working around namespace conflicts -- except, apparently, conflicts involving "as". The fact that "as" itself creates an insurmountable namespace collision is just killing me! How absurd. Anyway, it seems obvious that the right decision for our customers (or more importantly, for their countless lines of autogenerated-Python log, state, and code files from the past decade) is to stick with C/Python 2.5.x for the time being and plan to make the jump to a threads-capable and hopefully backwards-compatible Python implementation as soon as possible (IronPython perhaps?). That seems like a sensible path around the breakage and enduring limitations of C/Python 2.6 or 3. Or in other words, if we're all going to go through a Python compatibility-disconnect, then we might as well kill as many birds as possible in a single pass -- and that single-threaded interpreter bird is definitely a "dodo" in danger of extinction. By the way, congratulations on 3.0 final! But to be brutally honest...in this many-core world we must all accept and deal with today, it is hard to imagine how a non-multithreaded AND non-backwards compatible Python implementation can have much of a life ahead of it, with or without an "as" keyword. I do sincerely hope I am wrong about this, but it is seems quite possible that C/Python's glory days are now behind us. And if so, then thank you all for so many wonderful years of effort and participation! C/Python has had a great run, and Python syntax, in a multiplicity of forms, will surely live on for many decades to come. Python has changed the world, and very much so for the better. Well done! Cheers, Warren From steve at REMOVE-THIS-cybersource.com.au Mon Dec 29 20:00:59 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Dec 2008 01:00:59 GMT Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <40b1b762-459b-4d6f-91f0-0a6e68d233ae@a26g2000prf.googlegroups.com> <4d396242-13c9-4318-97ba-99f18564fbc5@o4g2000pra.googlegroups.com> Message-ID: <016969d3$0$6988$c3e8da3@news.astraweb.com> On Mon, 29 Dec 2008 05:31:17 -0800, Aaron Brady wrote: > One style of coding I heard about once only permits returns at the end > of a function. It claims it makes it easier to see the function as a > mathematical object. That's silly. You treat the function as a black box: input comes in, and output comes out. You have no idea of what happens inside the black box: it could loop a thousand times, take 150 different branches, or take one of 37 different exit points. From the outside, it's still exactly like a mathematical object. Internal complexity is irrelevant. This is why mathematicians can perform algebra on complicated functions like Bessel's function (of the first or second kind), without needing to care that actually calculating Bessel's function is quite tricky. What I think the one-return-per-function style is aiming at is that it is (sometimes) easier to analyse the internals of the function if there are few branches. The more complicated branches you have, the harder it is to analyse the function. Early exits on their own are not the cause of the complexity: it's the number of branches leading to the early exit that causes the problem. Avoiding early exits is an over-reaction to the Bad Old Days of spaghetti code. But used wisely, early exists can simplify, not complicate, code. Consider the following: def find_ham(alist): for item in alist: if isinstance(item, Ham): return item raise ValueError('no ham found') def find_spam(alist): found_item = None for item in alist: if found_item is not None: if isinstance(item, Spam): found_item = item if found_item is None: raise ValueError('no spam found') else: return found_item The second version has double the number of lines of code of the first. It introduces an extra variable "found_item" and two extra if blocks. I don't think the claim that the version with an early exit is more complicated than the version without can justified. -- Steven From flarefight at googlemail.com Wed Dec 10 07:30:22 2008 From: flarefight at googlemail.com (ff) Date: Wed, 10 Dec 2008 04:30:22 -0800 (PST) Subject: Flushing PyQt's Event Queue Message-ID: <19d41195-a734-4974-ad02-b6ddf62c316f@v5g2000prm.googlegroups.com> Hi, I am writing an app which models growth of a system over time visually which is activated by button clicks, and when the loop finishes running i dont want any events [mainly clicking on buttons] that happened during the loop to be put into action since then it may run multiple times without the user realising what they have done, is there way to flush the event queue when the loop has finished?? ff From Russ.Paielli at gmail.com Sat Dec 6 17:39:34 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 6 Dec 2008 14:39:34 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> Message-ID: <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> On Dec 6, 1:21?pm, Carl Banks wrote: > On Dec 6, 9:12?am, "Russ P." wrote: > > > > > On Dec 6, 1:02?am, Antoine De Groote wrote: > > > > Allowing "$" as a substitute for "self" wouldn't require this new syntax. > > > > class C: > > > ? ? def method($, arg): > > > ? ? ? ? $.value = arg > > > > I'm strongly against this. This looks ugly and reminds me of Perl and > > > Ruby. (I don't have anything against these languages, but there's a > > > reason I use Python). > > > > Russ P. wrote: > > > > On Dec 5, 6:21 pm, "Daniel Fetchinson" > > > > wrote: > > > >> Hi folks, > > > > >> The story of the explicit self in method definitions has been > > > >> discussed to death and we all know it will stay. However, Guido > > > >> himself acknowledged that an alternative syntax makes perfect sense > > > >> and having both (old and new) in a future version of python is a > > > >> possibility since it maintains backward compatibility. The alternative > > > >> syntax will be syntactic sugar for the old one. This blog post of his > > > >> is what I'm talking about: > > > > >>http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... > > > > >> The proposal is to allow this: > > > > >> class C: > > > >> ? ? def self.method( arg ): > > > >> ? ? ? ? self.value = arg > > > >> ? ? ? ? return self.value > > > > >> instead of this: > > > > >> class C: > > > >> ? ? def method( self, arg ): > > > >> ? ? ? ? self.value = arg > > > >> ? ? ? ? return self.value > > > > >> I.e. explicit self stays only the syntax is slightly different and may > > > >> seem attractive to some. As pointed out by Guido classmethods would > > > >> work similarly: > > > > >> class C: > > > >> ? ? @classmethod > > > >> ? ? def cls.method( arg ): > > > >> ? ? ? ? cls.val = arg > > > >> ? ? ? ? return cls.val > > > > >> The fact that Guido says, > > > > >> "Now, I'm not saying that I like this better than the status quo. But > > > >> I like it a lot better than [...] but it has the great advantage that > > > >> it is backward compatible, and can be evolved into a PEP with a > > > >> reference implementation without too much effort." > > > > >> shows that the proposal is viable. > > > > >> I'd like this new way of defining methods, what do you guys think? > > > >> Anyone ready for writing a PEP? > > > > >> Cheers, > > > >> Daniel > > > > >> -- > > > >> Psss, psss, put it down! -http://www.cafepress.com/putitdown > > > > > I like it. > > > > > I'll even go a step further and suggest that "$" be allowed as a > > > > substitute for "self". It looks like a capital "S" (for Self), and it > > > > stands out clearly. It also makes code more succinct with no loss of > > > > readability. Think of the line wraps that could be avoided. > > > It looks "ugly" simply because it is new to you. Once you get used to > > it, I'll bet it will look fine. And resemblance to another language is > > not a very good reason to reject it. > > Perl is not new to me and I am familiar with the syntax, such as it > is. ?I find it unspeakably ugly. ?So, no, you would lose your bet if > it were me. > > Carl Banks I don't know much about Perl, but my understanding is that a dollar sign must be used every time a variable is dereferenced, as in bash or other shell languages. What we are proposing here is something entirely different: the dollar sign would simply be a shorthand for "self". In Perl, the dollar sign is clutter, but in this case it actually reduces clutter. Python already uses shorthand extensively. How about "def"? For people who are so worried about self-explanatory symbols, what the heck does that stand for? Default? Defeat? Defect? Defunct? Defer? At some time in the past, a conscious decision was made to save three characters in the word "define" by abbreviating it as "def". The suggestion to abbreviate "self" as "$" also saves three characters. And "self" appears much more often than "def", so an abbreviation is equally or more justified in my opinion. From google at mrabarnett.plus.com Tue Dec 30 19:54:11 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 31 Dec 2008 00:54:11 +0000 Subject: get method In-Reply-To: References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> <495AAB97.5010707@mrabarnett.plus.com> <71508d7a-f678-40ba-801c-0bbfbbab961e@r15g2000prh.googlegroups.com> Message-ID: <495AC2B3.7040706@mrabarnett.plus.com> James Mills wrote: > On Wed, Dec 31, 2008 at 10:22 AM, John Machin wrote: > (snip) > >> The "crawl through the shrubbery looking for evidence" approach >> stumbles on the actual code: > > Yes I found his implementation soon after :) > Not bad actually... I wonder why bag() isn't > shipped with the std lib - perhaps in teh set > module ? > Occasionally someone posts here wanting to count items and solutions involving dict or defaultdict are suggested, and I think that a 'bag' class would be useful. The 'set' class was introduced first in a module, but it soon became a builtin. My posting was intended a possible reference implementation. From arnodel at googlemail.com Tue Dec 16 05:15:08 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 16 Dec 2008 10:15:08 +0000 Subject: tricky nested list unpacking problem References: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> Message-ID: bearophileHUGS at lycos.com writes: > I was waiting to answer because so far I have found a bad-looking > solution only. Seeing there's only your solution, I show mine too. It > seems similar to your one. I think that the solution below is a bit clearer, although I think it is more resource intensive than my first one. I've switched to a generator function to make it more easily comparable. It's true that it's a problem that seems designed for Scheme! l1 = [1,2,3,[5,6]] l2 = [1,2,3,[5,6],[7,8,9]] l3 = [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]] def flatten(x): if isinstance(x, list): for y in x: for z in flatten(y): yield z else: yield x def unpack(lst, acc=[]): i = len(acc) if i == len(lst): yield '-'.join(map(str, acc)) else: for x in flatten(lst[i]): for res in unpack(lst, acc + [x]): yield res -- Arnaud From version5 at gmail.com Sun Dec 7 16:31:59 2008 From: version5 at gmail.com (nnp) Date: Sun, 7 Dec 2008 21:31:59 +0000 Subject: Is 3.0 worth breaking backward compatibility? In-Reply-To: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> Message-ID: <28749c0e0812071331p1a509ad6w74fb258d766a518c@mail.gmail.com> Have a read of this http://www.b-list.org/weblog/2008/dec/05/python-3000/ It's a response to questions similar to yours by James Bennett On Sun, Dec 7, 2008 at 7:22 PM, walterbyrd wrote: > IMO: breaking backward compatibility is a big deal, and should only be > done when it is seriously needed. > > Also, IMO, most of, if not all, of the changes being made in 3.0 are > debatable, at best. I can not think of anything that is being changed > that was really a "show stopper" anyway. > > At best, I am a casual python user, so it's likely that I am missing > something. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.unprotectedhex.com http://www.smashthestack.org From george.sakkis at gmail.com Thu Dec 4 10:17:20 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 4 Dec 2008 07:17:20 -0800 (PST) Subject: Pythonic design patterns References: <0147e8b9$0$20670$c3e8da3@news.astraweb.com> Message-ID: <45fdd23c-0ccc-4135-b10c-1ef1d5ea4e6b@p2g2000prf.googlegroups.com> On Dec 4, 10:02?am, Steven D'Aprano wrote: > On Thu, 04 Dec 2008 01:09:08 -0800, Slaunger wrote: > > I find myself spending a lot of time in Python making some designs, to > > solve some task, which is the end turn out to be closely related to well > > established design patterns / programming idioms, which other users in > > this forum has been kind enough to point out. Only my implementations > > are often not that clean, and I may call things something different than > > the normal convention, which is a source of confusion for myself and > > others trying to communicate with me. > > > I guess I could boost my productivity by learning these well-proven and > > well-established design patterns by heart. > > This is all very good, but don't drink the design pattern Kool-Aid and > start pushing design patterns everywhere. (Not everything needs to be a > singleton. No, really.) Obligatory reading: http://www.mortendahl.dk/thoughts/blog/view.aspx?id=122 George From jcd at sdf.lonestar.org Thu Dec 18 15:56:11 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Thu, 18 Dec 2008 15:56:11 -0500 Subject: confused about __str__ vs. __repr__ In-Reply-To: References: <494A5ACA.8060205@wildenhain.de> Message-ID: <1229633772.10976.13.camel@aalcdl07.lib.unc.edu> On Thu, 2008-12-18 at 13:35 -0500, Neal Becker wrote: > Mel wrote: > > > Neal Becker wrote: > > > >> Tino Wildenhain wrote: > >> > >>> Neal Becker wrote: > >>>> Reading some FAQ, I see that __str__ is "meant for human eyes". > >>>> > >>>> But it seems that: > >>>> class X(object): > >>>> def __str__(self): > >>>> return "str" > >>>> def __repr__(self): > >>>> return "repr" > >>>> > >>>> x = X() > >>>> d = {0 : x} > >>>> print d > >>>> {0: repr} > >>>> > >>>> So if __str__ is "meant for human eyes", then why isn't print using it! > >>> > >>> it is: > >>> > >>> > print x > >>> str > >>> > >>> but dict just uses repr() for all its childs to print. > >>> > >>> T. > >> That makes no sense to me. If I call 'print' on a container, why > >> wouldn't > >> it recursively print on the contained objects? Since print means call > >> str, printing a container should recursively call str on the objects. > > > > Basically because there are too many right ways to format the resulting > > report. Space separated? Tab separated? One per line? Boxes around > > them? As HTML definition lists? Creating a standard report form would > > take a lot of work and wouldn't, finally, solve very many peoples' > > problems. > > > > Mel. > > > Thanks, but the question of how to format the container is different from how to format the primitive elements of the container. I was suggesting that printing an element of a container should be consistent with printing the element without the container, i.e., > > print [a] > should be consistent with > print a > > Well, first of all, an object is an object. Whether it is a container or not is a matter of semantic convenience. And how an object prints itself is up to that object and that object alone. If the object chooses to recursively call __str__ on its elements, it is free to do so, but since that causes ambiguity (as many people have pointed out), python has (wisely) chosen to use repr instead. If I wanted to implement a list-like class that doesn't show it's elements at all when printed, but instead shows its length, I am free to do so. For example: >>> hl = HiddenList(1,2,3) >>> hl >>> hl[1] 2 (Implementation of HiddenList left as an exercise for the reader.) If you want to implement a list-like object that returns the str of its elements, go right ahead, or implement a function that digs into containers and creates its own list representation for them. But that's not how python works by default, nor should it be, for reasons already explained by others. Cheers, Cliff From gagsl-py2 at yahoo.com.ar Thu Dec 18 19:11:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Dec 2008 22:11:27 -0200 Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> <6qv7kfFeuf65U1@mid.uni-berlin.de> <6qv9v4Ff1lv9U1@mid.uni-berlin.de> Message-ID: En Thu, 18 Dec 2008 14:05:32 -0200, Mikael Olofsson escribi?: > Diez B. Roggisch wrote: >> Yep. And it's easy enough if you don't care about them being different.. >> def __repr__(self): >> return str(self) > > If I ever wanted __str__ and __repr__ to return the same thing, I would > make them equal: > > def __str__(self): > return 'whatever you want' > __repr__ = __str__ > > That makes it more obvious to me what's going on. As a bonus, it saves > one method call for every repr call. It's even easier to define only __repr__, __str__ defaults to it: >>> class OnlyRepr(object): ... def __repr__(self): return "repr called" ... >>> class OnlyStr(object): ... def __str__(self): return "str called" ... >>> class Both(OnlyRepr, OnlyStr): ... pass ... >>> r = OnlyRepr() >>> s = OnlyStr() >>> b = Both() >>> print "only repr:", repr(r), str(r) only repr: repr called repr called >>> print "only str: ", repr(s), str(s) only str: <__main__.OnlyStr object at 0x00BA10F0> str called >>> print "both: ", repr(b), str(b) both: repr called str called -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Wed Dec 31 13:05:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 31 Dec 2008 16:05:07 -0200 Subject: How to get back a list object from its string representation? References: <78f8019c0812302046j31fa38aeif33d659ec5f2c84e@mail.gmail.com> <016b07b4$0$6988$c3e8da3@news.astraweb.com> Message-ID: En Wed, 31 Dec 2008 04:27:01 -0200, Steven D'Aprano escribi?: > On Wed, 31 Dec 2008 03:08:29 -0200, Gabriel Genellina wrote: > >> eval is like Pandora?s box, all kind of bad things can come from it. Do >> not use it with any user-supplied string. If you can restrict the values >> to be just constants, there is a "safe eval" recipe in >> http://code.activestate.com > > The ast module in Python 2.6 includes a "literal eval" function: > >>>> ast.literal_eval("[1, 2, 3]") > [1, 2, 3] That's a very nice addition! -- Gabriel Genellina From lists at cheimes.de Tue Dec 23 09:59:36 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 23 Dec 2008 15:59:36 +0100 Subject: no sign() function ? In-Reply-To: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> Message-ID: All algorithm including my own suffer from one mistake. Nobody accounts for NaN (not a number). You have to check for NaNs, too. NaNs have no sign at all. You could also try to do some fancy bit mask operation like >>> ord(struct.pack("d", 0.)[7]) & 0x80 0 >>> ord(struct.pack("d", -0.)[7]) & 0x80 128 But you have to take care of little endian, big endian and mixd endian IEEE 754 platforms, too. There are also platforms that don't have IEEE 754 floats at all ... Have fun :) Christian From banshee.welton at gmail.com Thu Dec 18 13:40:19 2008 From: banshee.welton at gmail.com (banshee.welton at gmail.com) Date: Thu, 18 Dec 2008 10:40:19 -0800 (PST) Subject: Adjusting filename and line number Message-ID: <4f1456af-ab2e-4b71-bc88-776fd6bd3a69@q30g2000prq.googlegroups.com> Hello, I'm working with some embedded python and would like to be able to adjust the reported filename and line number of some embedded user- written code so that errors returned coincide with things the user might actually be familiar with. In perl I could do this by adjusting the filename and line within a script like so: foo.pl ------ #!/usr/bin/env perl #line 1000 "myfile.txt" this is a syntax error $ perl foo.pl Can't locate object method "a" via package "syntax" (perhaps you forgot to load "syntax"?) at myfile.txt line 1000. For what it's worth, the same directive also works as a "C" preprocessor macro. I have searched for ways of managing this in python, but so far have not found any way of accomplishing this. Anyone know how it could be done? Thanks From manatlan at gmail.com Fri Dec 5 13:20:11 2008 From: manatlan at gmail.com (manatlan) Date: Fri, 5 Dec 2008 10:20:11 -0800 (PST) Subject: pytz and timezone specialists Message-ID: <1f6172c1-4f70-42ea-8010-b72beb0af487@w24g2000prd.googlegroups.com> Here is a really simple code : ------------------------------------------------------- from datetime import datetime from pytz import timezone tz=timezone("Europe/Paris") d=datetime(2008,12,12,19,00,00,tzinfo=tz) print d.isoformat() d=datetime.now(tz) print d.isoformat() ------------------------------------------------------- when I run it, it displays (according current time ;-): 2008-12-12T19:00:00+00:09 2008-12-05T19:15:38.135467+01:00 The Europe/Paris timezone is GMT+1 ... the second date seems to be right (+01:00 at the end) But why the first date ends with "+00:09" ?!? it should be +01:00 ... no ?! Where's the bug ?!? (sure : it's me ;-) ... but i don't understand this simple thing) From darcy at druid.net Wed Dec 10 15:22:38 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 10 Dec 2008 15:22:38 -0500 Subject: Python is slow In-Reply-To: <494020BC.6020700@gmail.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <494020BC.6020700@gmail.com> Message-ID: <20081210152238.6b98626c.darcy@druid.net> On Wed, 10 Dec 2008 21:04:12 +0100 Stef Mientki wrote: > cm_gui wrote: > > [...] > Put this guy in the junk filter, What's the point if people like you are just going to repost his entire message like that? -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From duncan.booth at invalid.invalid Sat Dec 13 14:17:41 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Dec 2008 19:17:41 GMT Subject: [OT] stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote: > David Hl????ik schrieb: >> Hi guys, >> >> i am really sorry for making offtopic, hope you will not kill me, but >> this is for me life important problem which needs to be solved within >> next 12 hours.. >> >> I have to create stable algorithm for sorting n numbers from interval >> [1,n^2] with time complexity O(n) . >> >> Can someone please give me a hint. Would be very very thankful! > > Unless I grossly miss out on something in computer science 101, the > lower bound for sorting is O(n * log_2 n). Which makes your task > impossible, unless there is something to be assumed about the > distribution of numbers in your sequence. > > Who has given you that assignment - a professor? Or some friend who's > playing tricks on you? > I think you must have fallen asleep during CS101. The lower bound for sorting where you make a two way branch at each step is O(n * log_2 n), but if you can choose between k possible orderings in a single comparison you can get O(n * log_k n). To beat n * log_2 n just use a bucket sort: for numbers with a known maximum you can sort them digit by digit for O(n log_k n), and if you don't restrict yourself to decimal then k can be as large as you want, so for the problem in question I think you can set k=n and (log_n n)==1 so you get O(n) i.e. digit by digit bucket sort the numbers in base n. Something like (untested): n = len(data) buckets1 = [[] for i in range(n)] buckets2 = [[] for i in range(n)] for x in data: buckets1[x % n].append(x) for x in (v for b in buckets1 for v in reversed(b)): buckets2[x // n].append(x) for x in (v for b in buckets2 for v in b): print x All loops are order n (the last two have about 2*n steps). I lied about the untested: >>> def f(data): n = len(data) buckets1 = [[] for i in range(n)] buckets2 = [[] for i in range(n)] for x in data: buckets1[x % n].append(x) for x in (v for b in buckets1 for v in reversed(b)): buckets2[x // n].append(x) for x in (v for b in buckets2 for v in b): print x >>> import random >>> data = [ random.randint(1,100) for i in range(10)] >>> f(data) 1 16 30 35 70 70 75 76 82 99 From Scott.Daniels at Acm.Org Wed Dec 24 15:28:29 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 24 Dec 2008 12:28:29 -0800 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <494febd1$0$20851$426a74cc@news.free.fr> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> <494febd1$0$20851$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > ... Now improvements are always welcomes, and if you compare 1.5.2 with > 2.5.1, you'll find out that the core developpers did improve Python's > perfs. Cool, palindromic inverses as compatible versions! From silverburgh.meryl at gmail.com Mon Dec 15 16:12:08 2008 From: silverburgh.meryl at gmail.com (silverburgh.meryl at gmail.com) Date: Mon, 15 Dec 2008 13:12:08 -0800 (PST) Subject: How can I return a non-zero status result from a python script? Message-ID: <74b53da4-bf07-431b-898b-49977f7a685c@r36g2000prf.googlegroups.com> Hi How can I return a non-zero status result from the script? Just do a return 1? at the end? From scalet at yebu.de Tue Dec 9 07:06:03 2008 From: scalet at yebu.de (resi147) Date: Tue, 9 Dec 2008 04:06:03 -0800 (PST) Subject: close has no effect on Mac OSX Python 3.0 References: <83b43edf-81e5-4116-ad7b-2dcacde2d101@f3g2000yqf.googlegroups.com> Message-ID: On 9 Dez., 07:51, "Gabriel Genellina" wrote: > En Mon, 08 Dec 2008 20:09:23 -0200, resi147 escribi?: > > > I'm wondering if it's really a bug since it's so trivial: > > > fp = open('/etc/services') > > ct = fp.read(1048) > > print(ct[-80:], end='') > > fp.close() > > ct = fp.read(17) > > print(ct) > > > the second read should fail, but happily continues reading the file. > > Really a bug? > > Looks like a real bug to me. In fact it is already reported:http://bugs.python.org/issue4604 > > -- > Gabriel Genellina Thanks to Skip Montanaro, he did it (for me, thanks :-) Karl. From exarkun at divmod.com Mon Dec 15 10:36:45 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 15 Dec 2008 10:36:45 -0500 Subject: %s place holder does not let me insert ' in an sql query with python. In-Reply-To: <1229345178.31093.24.camel@krishna-laptop> Message-ID: <20081215153645.20272.1331140571.divmod.quotient.21352@ohm> On Mon, 15 Dec 2008 18:16:18 +0530, Krishnakant wrote: >hello all hackers. >This is some kind of an interesting situation although many of you must >have already gone through it. >I am facing a situation where I have to use psycopg2 and insert rows in >a postgresql table. >That's pritty easy and no need to say that it works well. But there are >some entries which have an ' in the value. >I have a venders table in my database and one of the values tryed was >"His Master's Voice " >now the master's word has the ' which is used for starting and ending a >varchar value for postgresql or almost any standard RDBMS. >Does any one know what is the way out of this? >how do you let the ' go as a part of the string? >I have used %s as placeholder as in >queryString = "insert into venders values ('%s,%s,%s" % >(field1,field2,field3 ) ... >This is not working for the ' values. >can any one suggest a suitable solution? You got pretty close to the right approach. All you have to do is stop doing Python string interpolation. Don't do this: cursor.execute("foo (%s, %s, %s)" % (f1, f2, f3)) Instead, do this: cursor.execute("foo (%s, %s, %s)", (f1, f2, f3)) This works for all data and avoid numerous potential security issues. Doing it this way is called using "bind parameters". You should always use bind parameters when executing a statement with variable data. You should never ever use Python string interpolation as in the code you included in your original post (or in some of the other responses you received). Jean-Paul From research at johnohagan.com Wed Dec 10 20:21:24 2008 From: research at johnohagan.com (John O'Hagan) Date: Thu, 11 Dec 2008 01:21:24 +0000 Subject: Python music sequencer timing problems In-Reply-To: <3b52b652-df61-4eb4-bcff-0d1fb6f20891@r15g2000prh.googlegroups.com> References: <3b52b652-df61-4eb4-bcff-0d1fb6f20891@r15g2000prh.googlegroups.com> Message-ID: <200812110121.25825.research@johnohagan.com> On Wed, 10 Dec 2008, badmuthahubbard wrote: > I've been trying to get the timing right for a music sequencer using > Tkinter. First I just loaded the Csound API module and ran a Csound > engine in its own performance thread. The score timing was good, > being controlled internally by Csound, but any time I moved the mouse > I got audio dropouts. > It was suggested I run the audio engine as a separate process, with > elevated/realtime priority and use sockets to tell it what to play, > and that way, too, people could set up servers for the audio on > different CPUs. But I've found that the method I came up with for > timing the beats/notes is too slow (using threading.Timer on a > function that calls itself over and over), and the whole thing played > too slowly (and still gave me noise when moving the mouse). I've been > using subprocesses, but I'm now wondering if sockets would or could > make a difference. > > The overall goal is this: when the user wants to audition a piece, > create an audio engine process with elevated/realtime priority. This > engine also has all the synthesis and sound processing rules for the > various instruments, due to the way Csound is structured. Set up a > scheduler- possibly in another process, or just another thread- and > fill it with all the notes from the score and their times. Also, the > user should be able to see a time-cursor moving across the piece so > they can see where they are in the score. As this last bit is GUI, > the scheduler should be able to send callbacks back to the GUI as well > as notes to the audio engine. But neither the scheduler nor the audio > engine should wait for Tkinter's updating of the location of the time- > cursor. Naturally, all notes will have higher priorities in the > scheduler than all GUI updates, but they won't necessarily always be > at the same time. > > So, I have a few ideas about how to proceed, but I want to know if > I'll need to learn more general things first: > 1. > Create both the scheduler and the audio engine as separate processes > and communicate with them through sockets. When all events are > entered in the scheduler, open a server socket in the main GUI process > and listen for callbacks to move the cursor (is it possible to do this > using Tkinter's mainloop, so the mouse can be moved, albeit > sluggishly, at the same time the cursor is moving continuously?); the > audio engine runs at as high priority as possible, and the scheduler > runs somewhere between that and the priority of the main GUI, which > should even perhaps be temporarily lowered below default for good > measure. > > or > > 2. > Create the audio engine as an elevated priority process, and the > scheduler as a separate thread in the main process. The scheduler > sends notes to the audio engine and callbacks within its own process > to move the GUI cursor. Optionally, every tiny update of the cursor > could be a separate thread that dies an instant later. > > 3. > Closer to my original idea, but I'm hoping to avoid this. All note > scheduling and tempo control is done by Csound as audio engine, and a > Csound channel is set aside for callbacks to update the cursor > position. Maybe this would be smoothest, as timing is built into > Csound already, but the Csound score will be full of thousands of > pseudo-notes that only exist for those callbacks. Down the road I'd > like to have notes sound whenever they are added or moved on the > score, not just when playing the piece, as well as the option of > adjusting the level, pan, etc. of running instruments. > Hi Chuckk, I've recently been fooling with something involving timing and synchronising multiple note-on/note-off events, and also tried threading and subprocesses without much success - out of the box, the high-tempo precision wasn't there. But I had more luck with this approach, if it's not way too simple for your purpose (I'm not using a gui, for example); in psuedocode: from time import time, sleep start = time() for event in music: duration=len(event) #Really, the length of the event play(event) while 1: timer = time() remaining = start + duration - timer if remaining < 0.001: break else: sleep(remaining / 2) stop(event) start += duration IOW, just check the time, wait half the remaining note duration, check the time again, etc, till you've reached your desired precision level (in this case 0.001 sec). The halving of each succesive sleep() means that there is only a handful of calls to time() per note, 5-10 depending on the tempo. (Of course it could be any fraction, I just pulled that out of a hat; it would probably be better too if the fraction decremented as the deadline approached). Even with this naive algorithm, I'm getting accuracy of <0.001 sec consistently, up to stupidly high tempos like 3000 bpm (as measured by inserting a "print remaining" in the loop) without using a separate timing thread or "sync pulse", and with only a few calls. Any processes started this way stay in sync, even if individual events are delayed, because the "start" variable is incremented by the correct (not actual) duration of the note. (But I guess that's just scheduling, right? :) ) Obviously there is a limit imposed by arithmetical precision, but I've left things running all day without seeing a discrepancy. In terms of audio process communication, I'm using sox in a subprocess to play samples (and its cheesey synth sound!), and fluidsynth via a socket for midi. The latter is far superior and seems to handle whatever is thrown at it, and with the jack driver with realtime priority, the dropouts you mentioned caused by mouse movements and so on disappear. Of course, this doesn't prove that using a socket is better; I don't think sox is jack-aware, and if the subprocesses could have different priorities from the parent process, that may help with the difficulties we're having with them. Anyone out there know about that? I've been putting off getting into Csound, but by all accounts it's _the_ audio language. Good luck with your project, it sounds interesting. Regards, john From mail at timgolden.me.uk Mon Dec 22 11:02:49 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 22 Dec 2008 16:02:49 +0000 Subject: join a samba domain In-Reply-To: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> References: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> Message-ID: <494FBA29.30207@timgolden.me.uk> Toff wrote: > hi, > > I 'm trying to write a script to make my computer join a samba. > > domeone have any idea ?? Ummm. It's not clear if you're saying that your code doesn't work, or asking for general advice, or what? I'm not in a position to have my machine join a domain or workgroup, but you seem to have got most things in place already. The only thing I would expect to have to change is this last line: > import wmi > c = wmi.WMI() > d = c.Win32_ComputerSystem > d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") because the d is only a WMI *class*, not a WMI *instance*, so doesn't refer as it should to your computer system but to the class of computer systems. Try something like this (untested): import wmi c = wmi.WMI () for d in c.Win32_ComputerSystem (): d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") TJG From rt8396 at gmail.com Fri Dec 19 22:07:49 2008 From: rt8396 at gmail.com (r) Date: Fri, 19 Dec 2008 19:07:49 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c4ef2$0$20656$c3e8da3@news.astraweb.com> Message-ID: <2d53cd36-52b0-4a1a-913d-0c545cfadc23@v15g2000vbb.googlegroups.com> Thanks Steven, We need a real Pepsi challenge here to show the insignificance of this change. I am not against change. But when we lose something as - compact- as %formating i'm going to want to see a damn good reason for it! Especially when this breaks code, and the "French Connection" is not good enough reason for me :) Christian said this was not going to be depreciated until 3.2, but that still puts the accepted way on the chopping block. From clp at rebertia.com Mon Dec 8 00:36:42 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 7 Dec 2008 21:36:42 -0800 Subject: A question about reference in Python. In-Reply-To: <493CB003.3080209@gmail.com> References: <493CB003.3080209@gmail.com> Message-ID: <47c890dc0812072136v4e36dc1crbf0c913760f477d4@mail.gmail.com> On Sun, Dec 7, 2008 at 9:26 PM, Group wrote: > Hello, I'm studying algorithom. For concentrating on the question itself, I > intend to use Python to implement the algorithoms. > > Now, I want to write a Red-Black Tree, and a List structure. In C/C++, I can > use pointers to refer to children notes (or next notes). But, in Python, > how > can I do it? Except the sequence, I know not any way. > > You'd better help me understan how can I transform the following C code into > Python: > > /* a List */ > struct { > int data; > int *next; > int *prev; > } Possibly not an exact literal translation, but: class ListNode(object): def __init__(self, data, prev=None, next=None) self.data = data self.prev = prev self.next = next Keep in mind that Python uses call-by-object (google it), so it doesn't have pointers/references per-se. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > That's all. Thanks! > Kermit > > -- > http://mail.python.org/mailman/listinfo/python-list > From badmuthahubbard at usenet.cnntp.org Sun Dec 14 09:29:10 2008 From: badmuthahubbard at usenet.cnntp.org (Bad Mutha Hubbard) Date: 14 Dec 2008 14:29:10 GMT Subject: Python music sequencer timing problems References: <3b52b652-df61-4eb4-bcff-0d1fb6f20891@r15g2000prh.googlegroups.com> Message-ID: <49451835$0$17068$6e1ede2f@read.cnntp.org> John O'Hagan wrote: > On Wed, 10 Dec 2008, badmuthahubbard wrote: >> I've been trying to get the timing right for a music sequencer using >> Tkinter. First I just loaded the Csound API module and ran a Csound >> engine in its own performance thread. The score timing was good, >> being controlled internally by Csound, but any time I moved the mouse >> I got audio dropouts. >> It was suggested I run the audio engine as a separate process, with >> elevated/realtime priority and use sockets to tell it what to play, >> and that way, too, people could set up servers for the audio on >> different CPUs. But I've found that the method I came up with for >> timing the beats/notes is too slow (using threading.Timer on a >> function that calls itself over and over), and the whole thing played >> too slowly (and still gave me noise when moving the mouse). I've been >> using subprocesses, but I'm now wondering if sockets would or could >> make a difference. >> >> The overall goal is this: when the user wants to audition a piece, >> create an audio engine process with elevated/realtime priority. This >> engine also has all the synthesis and sound processing rules for the >> various instruments, due to the way Csound is structured. Set up a >> scheduler- possibly in another process, or just another thread- and >> fill it with all the notes from the score and their times. Also, the >> user should be able to see a time-cursor moving across the piece so >> they can see where they are in the score. As this last bit is GUI, >> the scheduler should be able to send callbacks back to the GUI as well >> as notes to the audio engine. But neither the scheduler nor the audio >> engine should wait for Tkinter's updating of the location of the time- >> cursor. Naturally, all notes will have higher priorities in the >> scheduler than all GUI updates, but they won't necessarily always be >> at the same time. >> >> So, I have a few ideas about how to proceed, but I want to know if >> I'll need to learn more general things first: >> 1. >> Create both the scheduler and the audio engine as separate processes >> and communicate with them through sockets. When all events are >> entered in the scheduler, open a server socket in the main GUI process >> and listen for callbacks to move the cursor (is it possible to do this >> using Tkinter's mainloop, so the mouse can be moved, albeit >> sluggishly, at the same time the cursor is moving continuously?); the >> audio engine runs at as high priority as possible, and the scheduler >> runs somewhere between that and the priority of the main GUI, which >> should even perhaps be temporarily lowered below default for good >> measure. >> >> or >> >> 2. >> Create the audio engine as an elevated priority process, and the >> scheduler as a separate thread in the main process. The scheduler >> sends notes to the audio engine and callbacks within its own process >> to move the GUI cursor. Optionally, every tiny update of the cursor >> could be a separate thread that dies an instant later. >> >> 3. >> Closer to my original idea, but I'm hoping to avoid this. All note >> scheduling and tempo control is done by Csound as audio engine, and a >> Csound channel is set aside for callbacks to update the cursor >> position. Maybe this would be smoothest, as timing is built into >> Csound already, but the Csound score will be full of thousands of >> pseudo-notes that only exist for those callbacks. Down the road I'd >> like to have notes sound whenever they are added or moved on the >> score, not just when playing the piece, as well as the option of >> adjusting the level, pan, etc. of running instruments. >> > > Hi Chuckk, > > I've recently been fooling with something involving timing and synchronising > multiple note-on/note-off events, and also tried threading and subprocesses > without much success - out of the box, the high-tempo precision wasn't there. > > But I had more luck with this approach, if it's not way too simple for your > purpose (I'm not using a gui, for example); in psuedocode: > > from time import time, sleep > > start = time() > for event in music: > duration=len(event) #Really, the length of the event > play(event) > while 1: > timer = time() > remaining = start + duration - timer > if remaining < 0.001: > break > else: > sleep(remaining / 2) > stop(event) > start += duration > > IOW, just check the time, wait half the remaining note duration, check the > time again, etc, till you've reached your desired precision level (in this > case 0.001 sec). The halving of each succesive sleep() means that there is > only a handful of calls to time() per note, 5-10 depending on the tempo. (Of > course it could be any fraction, I just pulled that out of a hat; it would > probably be better too if the fraction decremented as the deadline > approached). > > Even with this naive algorithm, I'm getting accuracy of <0.001 sec > consistently, up to stupidly high tempos like 3000 bpm (as measured by > inserting a "print remaining" in the loop) without using a separate timing > thread or "sync pulse", and with only a few calls. > > Any processes started this way stay in sync, even if individual events are > delayed, because the "start" variable is incremented by the correct (not > actual) duration of the note. (But I guess that's just scheduling, > right? :) ) > > Obviously there is a limit imposed by arithmetical precision, but I've left > things running all day without seeing a discrepancy. > > In terms of audio process communication, I'm using sox in a subprocess to play > samples (and its cheesey synth sound!), and fluidsynth via a socket for midi. > The latter is far superior and seems to handle whatever is thrown at it, and > with the jack driver with realtime priority, the dropouts you mentioned > caused by mouse movements and so on disappear. > > Of course, this doesn't prove that using a socket is better; I don't think sox > is jack-aware, and if the subprocesses could have different priorities from > the parent process, that may help with the difficulties we're having with > them. Anyone out there know about that? > > I've been putting off getting into Csound, but by all accounts it's _the_ > audio language. Good luck with your project, it sounds interesting. > > Regards, > > john Hi John. Very interesting approach, halving the remaining duration. Right now I'm not working with note-offs, Csound takes care of the duration. I just need to be able to call the notes at the right times. I've managed to get all the networking/IPC stuff working, I just need to test the sched.scheduler functioning. If it isn't accurate enough, as some have told me it won't be, I'll have to fall back on using Csound to time the notes; it's a C library, so I think it will be pretty fast. I have nothing but respect and awe for sox. I chose Csound partially because I want the app to work cross-platform. Csound and the Csound API work fine with Jack, but for some reason I got the audio static even connected to Jack with realtime preemption. There are ways for the subprocesses to have different priorities; they inherit the parent's priority, but any later changes made by, e.g., os.nice() only affect the parent. So one could run os.nice(-2), then spawn a subprocess, then run os.nice(4), to leave the child process -2 from the default and the parent process +2. I also like and respect Fluidsynth, but I'm working on a pretty microtonal system, and MIDI doesn't have enough microtonal support. Csound is the shiznet. It's pretty engrossing, though. I've written a fraction of the amount of music I wrote before since I discovered it! -Chuckk From raj.indian.08 at gmail.com Mon Dec 1 10:35:48 2008 From: raj.indian.08 at gmail.com (RajNewbie) Date: Mon, 1 Dec 2008 07:35:48 -0800 (PST) Subject: 11001, 'getaddrinfo failed' : Error in httplib but not in urllib2 References: Message-ID: <0de72923-08b7-4631-a48d-b5249150dd1b@p2g2000prf.googlegroups.com> On Dec 1, 7:43?pm, Tim Golden wrote: > RajNewbie wrote: > > Hi all, > > ? ? I am trying to connect to localhost via httplib, but it fails. > > ? ? To check whether it is a firewall problem etc, I tried to connect > > via urllib2, but it went through fine. > > ? ? ?Could some one help me out on this? I cannot use urllib2 in the > > > program because I have to send files via post to a url, and urllib2 > > doesn't support it (Python2.4) > > > Please see the code below: > > -->HTTPLIB<-- > > h = httplib.HTTPConnection("http://127.0.0.1:8000") > > h.request('GET', "/accounts/") > > res = h.getresponse() > > Which aspect of the documentation: > > http://docs.python.org/library/httplib.html > > leads you to think that the first parameter to > httplib.HTTPConnection should be a URL? > > >>> import httplib > >>> httplib.HTTPConnection ("127.0.0.1") > > >>> httplib.HTTPConnection ("localhost") > > > > > > > > TJG oops. My mistake. I am sorry to post such a braindead question here. I mistook the host for the url here. Sorry. From jason-sage at creativetrax.com Wed Dec 3 13:30:56 2008 From: jason-sage at creativetrax.com (jason-sage at creativetrax.com) Date: Wed, 03 Dec 2008 12:30:56 -0600 Subject: Mathematica 7 compares to other languages In-Reply-To: <673ca33e-9c1e-4c8e-a81d-d46828fe47b1@n10g2000yqm.googlegroups.com> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <673ca33e-9c1e-4c8e-a81d-d46828fe47b1@n10g2000yqm.googlegroups.com> Message-ID: <4936D060.9090004@creativetrax.com> bearophileHUGS at lycos.com wrote: > > So when you need an algorithm, you can often find it already inside, > for example in the large Combinatorics package. So it has WAY more > batteries included, compared to Python. I'd like to see something as > complete as that Combinatorics package in Python. > Sage (http://www.sagemath.org/, based on Python) already has some pretty powerful and comprehensive combinatorics functionality (including lots of things that Mma doesn't have). What's more, one of the most comprehensive combinatorics libraries out there, MuPAD combinat, is currently in the process of switching to Sage (and becoming the Sage-combinat project). See http://wiki.sagemath.org/combinat/. If you are interested in graph theory, then you might be interested in the comparison to the Combinatorica package at http://wiki.sagemath.org/CombinatoricaCompare . This page is a little old, but it gives you an idea of how things compare. Jason From lists at cheimes.de Mon Dec 8 13:55:31 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 08 Dec 2008 19:55:31 +0100 Subject: StringIO in 2.6 and beyond In-Reply-To: References: Message-ID: Bill McClain wrote: > I've just installed 2.6, had been using 2.4. > > This was working for me: > > #! /usr/bin/env python > import StringIO > out = StringIO.StringIO() > print >> out, 'hello' > > I used 2to3, and added import from future to get: > > #! /usr/bin/env python > from __future__ import print_function > import io > out = io.StringIO() > print('hello', file=out) > > ....which gives an error: > > Traceback (most recent call last): > File "./example.py", line 5, in > print('hello', file=out) > File "/usr/local/lib/python2.6/io.py", line 1487, in write > s.__class__.__name__) > TypeError: can't write str to text stream > > ....which has me stumped. Why can't it? In this context 'str' means Python 3.0's str type, which is unicode in 2.x. Please report the misleading error message. Christian From adi at lspl.net Mon Dec 8 05:40:03 2008 From: adi at lspl.net (sniffer) Date: Mon, 8 Dec 2008 02:40:03 -0800 (PST) Subject: infering the number of args a function takes at runtime References: Message-ID: <25dcb5a7-1f31-4ef3-8b07-fb355dfd31e5@p2g2000prf.googlegroups.com> On Dec 8, 9:39?am, sniffer wrote: > hi all, > i am a python newbie, in a project currently doing i need to find out > the number of arguments that a function takes at runtime.? Is this > possible ,if so how do i do this,i ve looked through the python > documentation but couldnt find anything.any help will be great > > TIA Thanks guys , i think this should work for me.btw as enquired i am working o a mvc thingie where in need to call functions in a controller,and pass the arguments as recieved from the end user so i need to make sure that the number of arguments passed from the front end are correct or not in the context of the function being called From fakeaddress at nowhere.org Tue Dec 23 06:36:16 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 23 Dec 2008 03:36:16 -0800 Subject: Very basic question In-Reply-To: <38f6b145-8615-4bcc-88f6-1988f9a7f68f@q30g2000prq.googlegroups.com> References: <21ab1917-f0c9-48fb-baa9-02e5bf229bf5@s9g2000prm.googlegroups.com> <38f6b145-8615-4bcc-88f6-1988f9a7f68f@q30g2000prq.googlegroups.com> Message-ID: Sengly wrote: > I can hack it by doing eval('1.0*12/5') but is there any better method? Where did you get the string? If you generated it, you might as well make one or both the operands float to begin with. If you got it as input, calling eval() on it is a world of security hurt. The right way would be to parse the expression, so you can evaluate it as you wish. Security defects aside, just prepending '1.0 *' doesn't work in general, because the string could be something like '5 + 12 / 5'. If you replace each '/' that isn't immediately followed by another '/' with '* 1.0 /', that might work... or maybe someone fill find counter-examples. Python 3 does what you want. The / operator is float division. The // operator is still integer division. -- --Bryan From prologic at shortcircuit.net.au Mon Dec 29 20:32:35 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 30 Dec 2008 11:32:35 +1000 Subject: get method In-Reply-To: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> Message-ID: On Tue, Dec 30, 2008 at 11:00 AM, Ross wrote: > I am teaching myself Python by going through Allen Downing's "Think > Python." I have come across what should be a simple exercise, but I am > not getting the correct answer. Here's the exercise: > > Given: > > def histogram(s): > d = dict() > for c in s: > if c not in d: > d[c] = 1 > else: > d[c] += 1 > return d > > > Dictionaries have a method called get that takes a key and a default > value. If the key appears in the dictionary, get returns the > corresponding value; otherwise it returns the default value. For > example: > >>>> h = histogram('a') >>>> print h > {'a': 1} >>>> h.get('a', 0) > 1 >>>> h.get('b', 0) > 0 > > Use get to write histogram more concisely. You should be able to > eliminate the if statement. > > Here's my code: > > def histogram(s): > d = dict() > for c in s: > d[c]= d.get(c,0) > return d > > This code returns a dictionary of all the letters to any string s I > give it but each corresponding value is incorrectly the default of 0. > What am I doing wrong? Ross, the others have informed you that you are not actually incrementing the count. I'll assume you've fixed your function now :) ... I want to show you a far simpler way to do this which takes advantage of Python's list comprehensions and mappings (which are really what dictionaries are): >>> s = "James Mills and Danielle Van Sprang" >>> dict([(k, len([x for x in s if x == k])) for k in s]) {'a': 5, ' ': 5, 'e': 3, 'd': 1, 'g': 1, 'i': 2, 'M': 1, 'J': 1, 'm': 1, 'l': 4, 'n': 4, 'p': 1, 's': 2, 'r': 1, 'V': 1, 'S': 1, 'D': 1} >>> Let us know when you get to the "List Comprehension" section - They are very powerful - As as Generators and Generator Expressions. Have fun learning Python, cheers James From roy at panix.com Sat Dec 6 14:15:28 2008 From: roy at panix.com (Roy Smith) Date: Sat, 06 Dec 2008 14:15:28 -0500 Subject: Learning Python now coming from Perl References: <014a96e0$0$20670$c3e8da3@news.astraweb.com> Message-ID: In article <014a96e0$0$20670$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > On Sat, 06 Dec 2008 08:50:20 -0500, Roy Smith wrote: > > > For your first > > project, pick something that's small enough that you think you could > > tackle it in under 50 lines of Perl. > > Is there anything which *can't* be written in under 50 lines of Perl? [...] > Also, Perl REs are faster than Python REs, or so I'm told. Between the > speed and the convenience, Perl programmers tend to use RE's for > everything they can. Python programmers tend to use REs only for problems > that *should* be solved with REs rather than *can* be solved with a RE. Well, as an old-time unix hacker (who learned REs long before Perl existed), my question to you would be, "Is there any problem which *shouldn't* be solved with an RE?" :-) It's easy to go nuts with REs, and create write-only code. On the other hand, they are an extremely powerful tool. If you are wise in the ways of RE-fu, they can not only be the most compact way to write something, but also the most efficient and even the most comprehensible. Unfortunately, REs seem to be regarded as some kind of monster these days and few people take the time to master them fully. Which is a shame. One really nice feature of REs in Python is the VERBOSE flag. It lets you write some way-complicated REs in a way which is still easy for somebody to read and understand. Python's raw strings, and triple-quoted strings, also help reduce the sea of backslashes which often make REs seem much worse than they really are. One of the reasons REs don't get used in Python as much as in Perl is because strings have useful methods like startswith(), endswith(), and split(), and also the "in" operator. These combine to give you easy ways to do many things you might otherwise do with REs. From lists at cheimes.de Tue Dec 9 06:14:22 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 09 Dec 2008 12:14:22 +0100 Subject: python3.0 - any hope it will get faster? In-Reply-To: <6q70udFb5dmqU1@mid.dfncis.de> References: <6q70udFb5dmqU1@mid.dfncis.de> Message-ID: Helmut Jarausch wrote: > I know that processing unicode is inherently slower, > but still I was surprised that it's so much slower. > > Is there any hope Python-3.0 will get faster or > is the main potential for optimizations exhausted, already? > > That's not to start a flame war! > I know computers get faster, we human beings don't (me, at least) Don't worry, it's going to get faster. Our top priority was feature completeness and stability. With the first final version out we are focusing on bug fixes and speed ups. We have a fair bunch of speed patches and ideas in our work queue. For example Mark and Victor are working on long integer optimizations, Alexandre and I are focusing on the new IO library and so on. Some of the speedup will make it into 3.0.1 and future patch releases of the 3.0 series. Larger and more complex chances can be expected for Python 3.1. There are interesting experiments with LLVM and threaded code (not to confuse with multithreading) going on. Gr??e an die andere Seite von Aachen Christian From jay.amorin at gmail.com Thu Dec 4 09:57:48 2008 From: jay.amorin at gmail.com (Jay Jesus Amorin) Date: Thu, 4 Dec 2008 22:57:48 +0800 Subject: python to parse excel file csv format In-Reply-To: <4936ECF7.3040400@wildenhain.de> References: <4936DC35.6010404@mrabarnett.plus.com> <4936ECF7.3040400@wildenhain.de> Message-ID: This is what i have done and its giving me error. #!/usr/bin/env python import csv, sys, os filename = (sys.argv[1]) reader = csv.reader(open(filename, "rb"), delimiter=',', quoting=csv.QUOTE_NONE) try: #for row in reader: for fmodes,fname in reader: os.chmod(fname,fmodes) except csv.Error, e: sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) testserver:~> ./parsecsv.py chown.csv Traceback (most recent call last): File "./promote2prod.py", line 10, in ? os.chmod(fname,fmodes) TypeError: an integer is required Please help I'm a complete newbie to python. Many thanks. Jay On Thu, Dec 4, 2008 at 4:32 AM, Tino Wildenhain wrote: > MRAB wrote: > >> Jay Jesus Amorin wrote: >> >>> This is how i do it, but it runs with error. Kindly help >>> >>> >>> #!/usr/bin/env python >>> >>> import csv, sys, os >>> filename = (sys.argv[1]) >>> reader = csv.reader(open(filename, "rb"), delimiter=',', >>> quoting=csv.QUOTE_NONE) >>> >>> try: >>> for row in reader: >>> os.popen("chown row[0] row[1]") >>> >> This should be: >> >> os.popen("chown %s %s" % (row[0], row[1])) >> >> or: >> >> os.popen("chown %s %s" % tuple(row)) >> > > No, it should really be os.popen(("chown",row[0],row[1])) > or better yet, > > for fmodes,fname in reader: > os.popen(("chown",fmodes,fname)) > > or even plus better: > > for fmodes,fname in reader: > os.chmod(fname,fmodes) > > (Both my examples avoid problems with unquoted filenames) > > Regards > Tino > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Mon Dec 15 10:56:29 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 15 Dec 2008 10:56:29 -0500 Subject: Having Issues with CMD and the 'python' command In-Reply-To: References: Message-ID: On Mon, Dec 15, 2008 at 8:13 AM, wrote: > On Mon, 15 Dec 2008 at 23:01, James Mills wrote: > >> On Mon, Dec 15, 2008 at 10:51 PM, Lamonte Harris >> wrote: >> >>> Every time I start cmd on windows it requires me to "set >>> path=%path%;C:\python26" why? I'm getting annoyed... >>> >> >> "cmd" has _nothing_ to do with Python. >> >> > (Top posting corrected.) > > But the answer is that you need to update your PATH string at the system > level. You do that in Control Panel/System/Advanced/Environment variables > (it's a button on the advanced screen, which is something that confused > me the first time I went looking for it). > > ObPython: you know, it occurs to me that Windows follows exactly the > opposite philosophy from Python when it comes to hierarchy. Python's > Zen is "shallow is better than deep", whereas Windows' philosophy > is "deep is better than shallow". Every release of Windows seems > to bury the things one needs to do to administer the system deeper > and deeper inside a nested set of windows...and every time I touch > Windows I am reminded how sensible the Python Zen is :) > It's not a question of sensibility. It's a question of purpose. The Zen is the philosophy of a language that tries to be easy to learn and easy to use. Python is used by programmers who want to experiment with it, but who usually know enough not to os.system("rm -r /") or anything similar. Windows, on the other hand, wants to hide everything that can potentially ruin the system as deep as possible so that many of the idiots who use that system don't do stupid things like delete the registry, wipe the environment settings, turn off the "Nag Screen" (UAC), and other things of that nature. > --RDM > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Tue Dec 9 13:20:27 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 9 Dec 2008 10:20:27 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> Message-ID: <1ddabaf6-c129-4395-8d81-738e67e6f3ca@q26g2000prq.googlegroups.com> On Dec 9, 7:48?am, Paul Boddie wrote: > On 9 Des, 14:24, Steven D'Aprano > cybersource.com.au> wrote: > > > That is not what Guido said. What he actually said was: > > > "That's possible with sufficiently powerful parser technology, but > > that's not how the Python parser (and most parsers, in my experience) > > treat reserved words." > > I accept that many parsers are operating on predetermined tokens where > keywords will already have been identified as such, regardless of > their eventual syntactic context, by the time the parser gets to see > them. What I wanted to point out was that other approaches are not > exactly unheard of or particularly rare. Every now and again, the > language gets extended and new keywords are sought in an excruciating > process akin to a group writing exercise involving the existing > keywords. A better parsing framework would alleviate these problems. And introduce an assload of new ones. > > What Guido is saying is that even if he agreed with the OP he couldn't > > add that feature. He's not saying that he agrees with the OP. The Zen > > gives good reasons for believing that even if Python's parser was > > sufficiently powerful, he'd still consider the feature undesirable. > > Well, I think it's more interesting to explore the boundaries of what > can be done, to debunk notions that such things aren't being done in > the mainstream, and to examine whether they could benefit usability, > than it is to defer to the Zen of Python as some kind of prescriptive, > near-religious text at every turn. As GvR mentioned in this thread, someone already did that with regard to "parsing frameworks", and the result was PL/1. Seriously, that's not a good thing. To hell with the parser, what is everyone focusing on the parser in this thread? What about the human reader? Do you want the human reader to have to have all kinds of rules to memorize about when a symbol is an identifier and when it's a syntactic element? Do you want people to have to learn when to escape a symbol so that the parser treats it as an identifier instead of syntax? I'm not saying "as" alone was causing that--for once again Python showed what the best way to enter unpleasant waters is: with a lot of restraint--but a "better parsing framework" that eliminated keywords would cause lots of confusion. And finally: it's just plain bad style to use a syntactic element as an identifier, even when allowed. Carl Banks From andyhume at gmail.com Tue Dec 30 11:07:24 2008 From: andyhume at gmail.com (andyhume at gmail.com) Date: Tue, 30 Dec 2008 08:07:24 -0800 (PST) Subject: Parsing Excel spreadsheets Message-ID: <6a54de23-bea4-40c7-ad7c-22c6eba4bd8a@z6g2000pre.googlegroups.com> Hi, Can anybody recommend an approach for loading and parsing Excel spreadsheets in Python. Any well known/recommended libraries for this? The only thing I found in a brief search was http://www.lexicon.net/sjmachin/xlrd.htm, but I'd rather get some more input before going with something I don't know. Thanks, Andy. From sumerc at gmail.com Mon Dec 29 02:56:10 2008 From: sumerc at gmail.com (k3xji) Date: Sun, 28 Dec 2008 23:56:10 -0800 (PST) Subject: Read-Write Lock vs primitive Lock() Message-ID: Hi, I am trying to see on which situations does the Read-Write Lock performs better on primitive Lock() itself. Below is the code I am using to test the performance: import threading import locks import time class mylock(object): def __init__(self): self.__notreading = threading.Event() self.__notwriting = threading.Event() self.__notreading.set() self.__notwriting.set() def acquire_read(self): self.__notreading.clear() self.__notwriting.wait() def acquire_write(self): self.__notreading.wait() self.__notwriting.clear() def release_read(self): self.__notreading.set() def release_write(self): self.__notwriting.set() GLOBAL_VAR = 1 #GLOBAL_LOCK = locks.ReadWriteLock() GLOBAL_LOCK = threading.Lock() #GLOBAL_LOCK = mylock() GLOBAL_LOOP_COUNT = 100000 GLOBAL_READER_COUNT = 1000 GLOBAL_WRITER_COUNT = 1 class wthread(threading.Thread): def run(self): try: #GLOBAL_LOCK.acquireWrite() #GLOBAL_LOCK.acquire_write() GLOBAL_LOCK.acquire() for i in range(GLOBAL_LOOP_COUNT): GLOBAL_VAR = 4 finally: #GLOBAL_LOCK.release_write() GLOBAL_LOCK.release() class rthread(threading.Thread): def run(self): try: #GLOBAL_LOCK.acquireRead() #GLOBAL_LOCK.acquire_read() GLOBAL_LOCK.acquire() for i in range(GLOBAL_LOOP_COUNT): GLOBAL_VAR = 3 finally: #GLOBAL_LOCK.release_read() GLOBAL_LOCK.release() # module executed? if __name__ == "__main__": starttime = time.clock() threads = [] for i in range(GLOBAL_READER_COUNT): rt = rthread() threads.append(rt) for i in range(GLOBAL_WRITER_COUNT): wt = wthread() threads.append(wt) for thread in threads: thread.start() for thread in threads: thread.join() print "All operations took " + str(time.clock() - starttime) + " msecs" What I am doing is: I am creating multiple readers and try to do something. I had assumed that with using primitive Lock() on the above situation, it will create a bottleneck on the rthreads. But the numbers indicate that there are no difference at all. I had implemented my own READ-WRIET lock as can be seen above mylock and also used the one here: code.activestate.com/recipes/502283/. Both have the same numbers: above test with primitive Lock: C:\Python25\mytest>python test_rw.py All operations took 14.4584082614 msecs above test with mylock: C:\Python25\mytest>python test_rw.py All operations took 14.5185156214 msecs abive test with the one in recipe: C:\Python25\mytest>python test_rw.py All operations took 14.4641975447 msecs So, I am confused in which situations Read-Write lock scales better? Thanks, From grante at visi.com Wed Dec 31 11:28:30 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 31 Dec 2008 10:28:30 -0600 Subject: select.select and socket.setblocking References: <495a661d$0$11384$5fc30a8@news.tiscali.it> <495b34d8$0$11387$5fc30a8@news.tiscali.it> Message-ID: On 2008-12-31, Francesco Bochicchio wrote: > Grant Edwards ha scritto: >> On 2008-12-30, Francesco Bochicchio wrote: >> >>> 3. AFAIK (sorry, I feel acronym-ly today ;), there is no difference in >>> select between blocking and non-blocking mode. The difference is in the >>> recv (again, assuming that you use TCP as protocol, that is AF_INET, >>> SOCK_STREAM), which in the blocking case would wait to receive all the >>> bytes that you requested, >> >> No, in blocking mode it will wait to receive _some_ data (1 or >> more bytes). The "requested" amount is strictly an upper >> limit: recv won't return more than the requested number of >> bytes, but it might return less. > > Uhm. In my experience, with TCP protocol recv only returned less than > the required bytes if the remote end disconnects. I've no idea how you got recv() to behave that way, because I've never seen it do that. Take a look at the echo client/server examples at http://docs.python.org/library/socket.html. If recv worked the way you claimed it did, those programs wouldn't work -- they would deadlock. But, that example does work. In that example, the server program calls recv(1024), and yet it returns 12 bytes. The manual page for recv() specifically states that the "len" parameter is a maximum: The maximum amount of data to be received at once is specified by bufsize. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero. Note: For best match with hardware and network realities, the value of bufsize should be a relatively small power of 2, for example, 4096. The Linux man page for recv() also says len is the length of the receive buffer and is an upper limit on the number of bytes to read. Can you post an example program that exhibits the behavior you describe? > [...] > What I usually do, when I cannot block is: > > - use socket in blocking mode > - do a select with a very small timeout and do a recv only if the select > returns with input events > - (with TCP) do a recv for the exact amount of bytes that I expect ( > this mean having a user protocol that carries the message size in the > header, but this is usually the case ). > > This usually worked for me. Yes that will usually (almost always) work. But, IIRC, there are theoretically situraitons where something happens after select returns and before you call recv() that could cause recv() to block. -- Grant Edwards From rocky at panix.com Sun Dec 21 05:07:18 2008 From: rocky at panix.com (R. Bernstein) Date: Sun, 21 Dec 2008 05:07:18 -0500 Subject: linecache vs egg - reading line of a file in an egg References: Message-ID: Robert Kern writes: > R. Bernstein wrote: >> Does linecache work with source in Python eggs? If not, is it >> contemplated that this is going to be fixed or is there something else >> like linecache that currently works? > > linecache works with eggs and other zipped Python source, but it had > to extend the API in order to do so. Some of the debuggers don't use > the extended API. This will be fixed in the next 2.6.x bugfix release, > but not in 2.5.3. Ok. I have committed a change in pydb sources to deal with the 2 and 3 argument linecache.getline interface which should cover Python releases both before and after version 2.5. > > http://bugs.python.org/issue4201 Many thanks! I should have dug deeper myself. For pdb/bdb though isn't there still a problem in reporting the file location? There is that weird "build" name that seems to be stored in func_code.co_filename mentioned in the original post. I just tried patching pdb/bdb along from the current 2.6 svn sources and here is what I see: $ pdb /tmp/lc.py > /tmp/lc.py(1)() -> import tracer (Pdb) s --Call-- > /src/external-vcs/python/build/bdist.linux-i686/egg/tracer.py(6)() The above filename is wrong. It's very possible I did something wrong, so I'd be grateful if someone else double checked. Furthermore, if there is a problem I'm not sure I see how to fix this. I can think of heuristics to tell if module lives an inside an egg, but is there a reliable way? Is there a standard convention for reporting a file location inside of an egg? Thanks again. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco From eric at ericaro.net Fri Dec 19 14:28:12 2008 From: eric at ericaro.net (eric) Date: Fri, 19 Dec 2008 11:28:12 -0800 (PST) Subject: best way to code References: Message-ID: <04476e1e-a077-4abc-9a37-4e27a67ae7cc@v5g2000prm.googlegroups.com> On Dec 19, 6:36?pm, eric wrote: > On Dec 19, 5:35?pm, Peter Otten <__pete... at web.de> wrote: > > > > > eric wrote: > > > hi, > > > > I need to find a "good" design pattern to instanciate, and add > > > specific code all in one. Let me explain it : > > > > I need to define "some" code, better be in a class, something like > > > > class LinkA(object): > > > ? ? def mystuff(self): > > > ? ? ? ? ? > > > > class LinkB(object): > > > ? ? def mystuff(self): > > > ? ? ? ? ? > > > > AND I need an instance of this class > > > { "stuff A": LinkA() > > > ? "stuff B": LinkB() > > > } > > > > This kind of code "would" be fine, I mean, the result effect in memory > > > is fine for me. > > > But I don't like the way I have to > > > 1/ give a useless name to LinkA, linkB (there can be hundreds of names > > > like that) > > > 2/ I have to write it down two times (and that's one time too much) > > > > any ideas ? > > > > something like > > > [ > > > new object(): > > > ? ? def mystuff(self): > > > ? ? ? ? > > > , > > > new object(): > > > ? ? def mystuff(self): > > > ? ? ? ? > > > ] > > > > would be really perfect (but I know it does not work, or at least, I > > > don't know how to make it work) > > > > In fact, I would like to define a class, and an instance in a single > > > statement > > >>> class Register: > > > ... ? ? def __init__(self): > > ... ? ? ? ? ? ? self.items = [] > > ... ? ? def __call__(self, method): > > ... ? ? ? ? ? ? class Link(object): > > ... ? ? ? ? ? ? ? ? ? ? mystuff = method > > ... ? ? ? ? ? ? self.items.append(Link()) > > ...>>> register = Register() > > >>> @register > > > ... def mystuff(self): print "first" > > ...>>> @register > > > ... def mystuff(self): print "second" > > ...>>> for item in register.items: > > > ... ? ? item.mystuff() > > ... > > first > > second > > > Peter > > hi, > > I've tried something like this : > > import inspect > > class Test(object): > ? ? class Inner(object): > ? ? ? ? def mystuff(self): > ? ? ? ? ? ? print "hello stuff" > > ? ? class InnerB(object): > ? ? ? ? def mystuff(self): > ? ? ? ? ? ? print "hello B" > > def filter(member): > ? ? return inspect.isclass(member) and not member==Test.__class__ > d = dict( (name, c()) for name, c in inspect.getmembers(Test, > filter ) ) > print d > > it works too, but I prefer your method > > thanks > > -- > Erichttp://codeslash.blogspot.com Finally here is my 'final' shot: context: when building a glade GUI I wanted to connect 'nicely' signals (I hate coding the same info in several places) here is my main : if __name__=="__main__": pathname = os.path.dirname(sys.argv[0]) startup = os.path.join(pathname, 'pyshow/pyshow.glade') xml = gtk.glade.XML(startup) #'filename.glade') #the stuff starts here m = MainApp() for widget_name, codget in m.items(): codget.set_widget( xml.get_widget(widget_name) ) gtk.main() and here is the 'MainApp' code, based on the question, and finally I get stuck to my second solution import inspect class Controller(dict): def __init__(self): dict.__init__(self) self.update( (name, c()) for name, c in inspect.getmembers (self.__class__, lambda member: inspect.isclass(member) and not member==self.__class__.__class__ ) ) class MainApp(Controller): def __init__(self): Controller.__init__(self) class main_window(codget): def on_destroy(self, widget, modget): print "bye bye" class play(codget): def on_clicked(self, widget, modget): print "you have clicked" the business is hidden in codget ( as COntroller gaDGET), and what's interesting for me, is that every signal handler has a 'modget' ( as in model gadget) that it can use to do the job (part of the MVC pattern) thanks Peter anyway, I didn't use your solution in this specific case, but I loved the solution anyway, and I'm sure that I'll use it one day. From cournape at gmail.com Fri Dec 5 03:36:45 2008 From: cournape at gmail.com (David Cournapeau) Date: Fri, 5 Dec 2008 17:36:45 +0900 Subject: How to distribute C/C++ python extension module on Linux? In-Reply-To: References: Message-ID: <5b8d13220812050036m7637c83p63646ac44170832f@mail.gmail.com> On Fri, Dec 5, 2008 at 5:09 PM, Allen wrote: > I have build an extension module PyRPC.so (why not be libPyRPC.so?). > The PyRPC.so uses API in libRPCPacker.so. > How to distribute the PyRPC.so? The simple answer is you can't. Depending on the distribution, the python interpreter is built differently in an ABI-incompatible way. As on other platforms, the binary also depends on the python version. The only real solution is to package it using the native package manager of the distributions you are interested in supporting (rpm, deb, etc...); you still have to build the package for all different combinations, though. Something like the opensuse build service can help in those situations. > I just put PyRPC.so and libRPCPacker.so in the same folder. > And under this folder, run python. > It tells PyRPC module cannot find a method in libRPCPacker.so. We need more informations on how you built the extension, and about the exact error message. Note also that on Linux, by default, libraries are not looked in the current directory, so it is likely that PyRPC.so does not look in the libRPCPaker.so in your current directory, but from another path (you can check how the loader resolves libraries paths with the command ldd). David From eric at ericaro.net Thu Dec 4 11:15:47 2008 From: eric at ericaro.net (eric) Date: Thu, 4 Dec 2008 08:15:47 -0800 (PST) Subject: simplest way to strip a comment from the end of a line? References: Message-ID: <52e3f2a9-6fb1-42ef-9871-c904ede5520e@t3g2000yqa.googlegroups.com> On Dec 4, 4:50?pm, Joe Strout wrote: > I have lines in a config file which can end with a comment (delimited ? > by # as in Python), but which may also contain string literals ? > (delimited by double quotes). ?A comment delimiter within a string ? > literal doesn't count. ?Is there any easy way to strip off such a ? > comment, or do I need to use a loop to find each # and then count the ? > quotation marks to its left? > > Thanks, > - Joe Hi, if the string literal you wan't to escape, is not escaped (i.e contains \" ) then a regexp like .*?(?:".*?".*?)*#(?P .*?)$ (not tested) .*? everything but keep it greedy ".*?" the string literal not escaped From prologic at shortcircuit.net.au Thu Dec 18 20:33:27 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Dec 2008 11:33:27 +1000 Subject: Which sparse matrix package? In-Reply-To: <20081219014932.7846a547@Schlamber.localdomain> References: <20081218231851.70dd91e2@Schlamber.localdomain> <20081219014932.7846a547@Schlamber.localdomain> Message-ID: On Fri, Dec 19, 2008 at 10:49 AM, wrote: > On Fri, 19 Dec 2008 08:33:28 +1000 > "James Mills" wrote: > >> > The dict that I tried out is of the type: >> > >> > {(1,2,3): "2323", (1,2,545): "2324234", ... } >> > >> > It is too slow for my application when it grows. One slicing >> > operation with list comprehensions takes about 1/2 s on my computer >> > for 1E6 elements. >> >> Let me get this straight. >> It's taking 0.5s to slice your matrix >> of 1E7 (10000000.0 rows/columns) > > My benchmark is as follows: > > 1) Each of the numbers in the 3-tuple is in the range [0, 1E7). > 2) There are 1 000 000 elements in the dict (randomly distributed). > 3) The content string is a random number in the range [0, 1E10) that is > casted into a string. > 4) Measure the time that retrieving all elements in a 10000x100x10 cube > requires. Does a spreadsheet really get this complex ? >> Are you mad ? This is TEN Millions and you >> required it faster than 0.5s ? > > Think about how often a spreadsheet re-calculates cells. > Furthermore, people tend to copy&paste cells. > > I had some small example (Wagner-Whitin algorithm demo) > with hundreds of slicing operations on one screen. I believe that > no-one wants to wait for 1/2 s times 500 == 250 s each time the > spreadsheet is updated. Hmmm From fetchinson at googlemail.com Sat Dec 6 16:51:51 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 6 Dec 2008 13:51:51 -0800 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: >> Hi folks, >> >> The story of the explicit self in method definitions has been >> discussed to death and we all know it will stay. However, Guido >> himself acknowledged that an alternative syntax makes perfect sense >> and having both (old and new) in a future version of python is a >> possibility since it maintains backward compatibility. The alternative >> syntax will be syntactic sugar for the old one. This blog post of his >> is what I'm talking about: >> >> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html >> >> The proposal is to allow this: >> >> class C: >> def self.method( arg ): >> self.value = arg >> return self.value >> >> instead of this: >> >> class C: >> def method( self, arg ): >> self.value = arg >> return self.value >> >> I.e. explicit self stays only the syntax is slightly different and may >> seem attractive to some. As pointed out by Guido classmethods would >> work similarly: >> >> class C: >> @classmethod >> def cls.method( arg ): >> cls.val = arg >> return cls.val >> >> The fact that Guido says, >> >> "Now, I'm not saying that I like this better than the status quo. But >> I like it a lot better than [...] but it has the great advantage that >> it is backward compatible, and can be evolved into a PEP with a >> reference implementation without too much effort." >> >> shows that the proposal is viable. >> >> I'd like this new way of defining methods, what do you guys think? >> Anyone ready for writing a PEP? >> > What's the advantage? If there is not a good reason, I would strongly > opposed polluting the language. Did you read the blog post? The advantage is having a less confusing situation for newbies (confusing the number of arguments to a method call). > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From exarkun at divmod.com Mon Dec 22 10:05:42 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 22 Dec 2008 10:05:42 -0500 Subject: Event Driven programming - Doubts In-Reply-To: <80f360e4-2880-4c66-a6b4-e05d6dbc9031@b41g2000pra.googlegroups.com> Message-ID: <20081222150542.20272.906262414.divmod.quotient.25533@ohm> On Mon, 22 Dec 2008 06:57:55 -0800 (PST), Kottiyath wrote: >Hi, > I have been looking at Twisted and lately Circuits as examples for >event driven programming in Python. > [snip] > > My question is as follows: > I have not understood how the callbacks are hit without (a) >blocking the code or (b) having new threads. There is blocking code - but just in one place. For example, http://twistedmatrix.com/trac/browser/trunk/twisted/internet/selectreactor.py#L93 Jean-Paul From bdesth.quelquechose at free.quelquepart.fr Sun Dec 14 11:29:40 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 14 Dec 2008 17:29:40 +0100 Subject: 1 or 1/0 doesn't raise an exception In-Reply-To: References: <49446E39.6020807@tim.thechases.com> Message-ID: <4945422a$0$1127$426a74cc@news.free.fr> Grant Edwards a ?crit : > On 2008-12-14, Daniel Fetchinson wrote: > >> Let me just point out that unsuspecting people (like me) might rely on >> the whole expression to be evaluated and rely on exceptions being >> raised if needed. > > Short circuit evaluation of booleans is very common (and has > been for decades), so I don't know why people would expect > something else. > Because they either have no previous programming experience, or only experience with one of the few languages that don't do short-circuit evaluation ? You can consider that short-circuit is the norm and it's absence the exception. From n.kottiyath at gmail.com Mon Dec 1 13:20:51 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Mon, 1 Dec 2008 10:20:51 -0800 (PST) Subject: Reg: PIL2.4 Error: AttributeError: pixel_access Message-ID: <61f51748-c53d-4d7a-a9d0-83d3ec8c643e@s9g2000prm.googlegroups.com> Hi all, I am facing the following problem in PIL 2.4: Code: img = ImageGrab.grab() img.save("image2.jpg") Error: img.save("image2.jpg") File "C:\Python24\Lib\site-packages\PIL\Image.py", line 1372, in save self.load() File "C:\Python24\Lib\site-packages\PIL\Image.py", line 599, in load return self.im.pixel_access(self.readonly) AttributeError: pixel_access When I googled this error, I saw that such an error could be because of some botched installation. So, I re-installed PIL. But still this error persists. The version is >>> print Image.VERSION 1.1.6 I had installed PIL in Python2.5 earlier and had done image capture also. But I need to go back to Python2.4 (because pymedia exe is available for only python2.4) and now I am facing this issue. I am pretty new to application programming, so if someone can help me out, it would be very helpful. Regards, Kottiyath From steve at REMOVE-THIS-cybersource.com.au Sun Dec 7 18:44:00 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 23:44:00 GMT Subject: Is 3.0 worth breaking backward compatibility? References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> Message-ID: <014c576d$0$20670$c3e8da3@news.astraweb.com> On Sun, 07 Dec 2008 11:22:23 -0800, walterbyrd wrote: > IMO: breaking backward compatibility is a big deal, and should only be > done when it is seriously needed. > > Also, IMO, most of, if not all, of the changes being made in 3.0 are > debatable, at best. I can not think of anything that is being changed > that was really a "show stopper" anyway. > > At best, I am a casual python user, so it's likely that I am missing > something. To answer your subject line: "Is 3.0 worth breaking backward compatibility?" That depends on what you are doing with Python. Python 3 is the future of Python. "Show stopper" or not, all the new (mis)features in Python 3 are here to stay, and all the (mis)features in Python 2 are on the way out. You can start moving to Python 3 now, or you can do it later, but *eventually* you will have to move. -- Steven From castironpi at gmail.com Mon Dec 29 08:31:17 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 05:31:17 -0800 (PST) Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <40b1b762-459b-4d6f-91f0-0a6e68d233ae@a26g2000prf.googlegroups.com> Message-ID: <4d396242-13c9-4318-97ba-99f18564fbc5@o4g2000pra.googlegroups.com> On Dec 28, 11:56?am, Gerard Flanagan wrote: > On Dec 28, 5:19?pm, Roger wrote: > > > Hi Everyone, > [...] > > When I define a method I always include a return statement out of > > habit even if I don't return anything explicitly: > > > def something(): > > ? ? ? ? # do something > > ? ? ? ? return > > > Is this pythonic or excessive? ?Is this an unnecessary affectation > > that only adds clock ticks to my app and would I be better off > > removing "returns" where nothing is returned or is it common practice > > to have returns. > > It's not particularly excessive but it is uncommon. A nekkid return > can sometimes be essential within a function body, so a non-essential > nekkid return could be considered just noise. One style of coding I heard about once only permits returns at the end of a function. It claims it makes it easier to see the function as a mathematical object. It's a slick idea, but multiple exit points are really practical. Incidentally, generators have multiple entry points. They "yield multiple times, they have more than one entry point and their execution can be suspended" -- http://docs.python.org/reference/expressions.html#yield-expressions The discussion makes me think that 'clear' is subjective, just like 'natural' has 39 definitions. From martin at v.loewis.de Tue Dec 23 15:21:01 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 23 Dec 2008 21:21:01 +0100 Subject: [ANN] Python 2.5.4 (final) Message-ID: <4951482D.8050302@v.loewis.de> On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.5.4 (final). Python 2.5.3 unfortunately contained an incorrect patch that could cause interpreter crashes; the only change in Python 2.5.4 relative to 2.5.4 is the reversal of this patch. 2.5.4 is the last bug fix release of Python 2.5. Future 2.5.x releases will only include security fixes. According to the release notes, about 80 bugs and patches have been addressed since Python 2.5.2, many of them improving the stability of the interpreter, and improving its portability. See the release notes at the website (also available as Misc/NEWS in the source distribution) for details of bugs fixed; most of them prevent interpreter crashes (and now cause proper Python exceptions in cases where the interpreter may have crashed before). For more information on Python 2.5.4, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.5.4 Highlights of the previous major Python releases are available from the Python 2.5 page, at http://www.python.org/2.5/highlights.html Enjoy this release, Martin Martin v. Loewis martin at v.loewis.de Python Release Manager (on behalf of the entire python-dev team) From rt8396 at gmail.com Wed Dec 31 12:23:15 2008 From: rt8396 at gmail.com (r) Date: Wed, 31 Dec 2008 09:23:15 -0800 (PST) Subject: Desktop/File management support on MS Windows References: <4b7188db-63b2-4ac5-80cb-d1326ca3694a@q26g2000prq.googlegroups.com> Message-ID: <613a20bf-6e5a-435e-9a83-36766e12f0ab@k8g2000yqn.googlegroups.com> On Dec 31, 11:08?am, "riklau... at gmail.com" wrote: > Are there any Python libraries that can trash files (move to Trash, > not delete) or for example return a list of applications that can open > given file? I can't find anything related to this for Windows. try pywin32 http://python.net/crew/mhammond/win32/Downloads.html From wuwei23 at gmail.com Mon Dec 1 20:12:27 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 1 Dec 2008 17:12:27 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <4f31c483-8382-480e-8417-b7eef1b1792d@z1g2000yqn.googlegroups.com> <8c856b01-7f0c-4d5b-a1d2-cfe7dc74389f@w3g2000yqc.googlegroups.com> <1680020c-521c-4498-8e74-92e99c03da6b@w35g2000yqm.googlegroups.com> <0d9d2404-cb3f-4390-b97c-79251db8ac95@k8g2000yqn.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> Message-ID: On Dec 2, 6:29?am, r wrote: > In such a society of constant competition, there can be no allies, and > little transparency. The threats to acquisitions of social symbols are > so numerous, varied and frequently incomprehensible, that > defensiveness, as well as competitiveness, becomes a way of life. Any > real sense of community is undermined -- or even destroyed -- to be > replaced by virtual equivalents that strive, unsuccessfully, to > synthesize a sense of community. It can mean also many other things. Right. Like we're going to take lessons in "community" from someone who has done nothing to understand the one he's currently antagonising. > -food for thought- I sincerely hope you choke on it. From alooha at live.co.kr Wed Dec 31 01:02:49 2008 From: alooha at live.co.kr (BON) Date: Tue, 30 Dec 2008 22:02:49 -0800 (PST) Subject: MemoryError when list append... plz help Message-ID: <21227745.post@talk.nabble.com> ====================== s=[] for i in range(11000-1): for j in range(i+1, 11000): .... s.append(((i,j),sim)) ====================== above sim is floating type. s.append is totally coducted 60,494,500 times. but this code raise MemoryError. My computer has 4G RAM. i think it's enough. but it doesn't... So, i've tested below code. ====================== a=[] i=0 while i<60494500 : a.append(i) i+=1 ====================== but this code raise also MemoryError. How can i resolve this problem? please, help... Regards, -- View this message in context: http://www.nabble.com/MemoryError-when-list-append...-plz-help-tp21227745p21227745.html Sent from the Python - python-list mailing list archive at Nabble.com. From renton at 1gb.ru Mon Dec 1 11:37:44 2008 From: renton at 1gb.ru (Alexey Vlasov) Date: Mon, 1 Dec 2008 19:37:44 +0300 Subject: Import of egg packages installed with easy_install Message-ID: <20081201163744.GA9873@l2.in-solve.ru> Hi. There's an already installed with easy_install packet, let's say flup, to the home catalog: $ ls -la ~/python/lib/python2.5/site-packages/ total 176 drwxr-xr-x 3 4096 Nov 29 18:57 . drwxr-xr-x 3 4096 Nov 29 18:51 .. -rw-r--r-- 1 208 Nov 29 18:57 easy-install.pth -rw-r--r-- 1 134573 Nov 29 18:51 flup-1.0.1-py2.5.egg -rw-r--r-- 1 2362 Nov 29 18:51 site.py -rw-r--r-- 1 1853 Nov 29 18:51 site.pyc $ cat ~/python/lib/python2.5/site-packages/easy-install.pth import sys; sys.__plen = len(sys.path) ./flup-1.0.1-py2.5.egg import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sys.path[p:p]=new; sys.__egginsert = p+len(new) $ echo $PYTHONPATH /usr/lib64/portage/pym:/home/username/python/lib64/python2.5/site-packages $ python Python 2.5.2 (r252:60911, Nov 13 2008, 15:01:36) [GCC 4.1.2 (Gentoo 4.1.2 p1.1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import flup No errors. Then I create a simple CGI script: ======== #!/usr/bin/python print "Content-type: text/plain"; print import sys sys.path.insert (0, '/home/username/python/lib64/python2.5/site-packages') print sys.path import flup ======== Browser says: ['/home/username/python/lib64/python2.5/site-packages', '/home/username/http', '/usr/lib64/python25.zip', '/usr/lib64/python2.5', '/usr/lib64/python2.5/plat-linux2', '/usr/lib64/python2.5/lib-tk', '/usr/lib64/python2.5/lib-dynload', '/usr/lib64/python2.5/site-packages'] in error log: [Sat Nov 29 19:41:15 2008] [error] Traceback (most recent call last): [Sat Nov 29 19:41:15 2008] [error] File "path.cgi", line 9, in [Sat Nov 29 19:41:15 2008] [error] import flup [Sat Nov 29 19:41:15 2008] [error] ImportError: No module named flup If you start it with console, you get the same, but there appears also another path: /home/username/python/lib64/python2.5/site-packages/flup-1.0.1-py2.5.egg As I understand it is the problem actually, but I can't get why sys.path doesn't contain this path when I request with HTTP. -- BRGDS. Alexey Vlasov. From jhlj at statsbiblioteket.dk Mon Dec 22 12:59:51 2008 From: jhlj at statsbiblioteket.dk (Jens Henrik Leonhard Jensen) Date: Mon, 22 Dec 2008 18:59:51 +0100 Subject: join a samba domain In-Reply-To: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> References: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> Message-ID: <494fd597$0$90267$14726298@news.sunsite.dk> Toff wrote: > d = c.Win32_ComputerSystem > d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") Shouldn't r"admin\\mydom" be "admin\\mydom" or r"admin\mydom". Or maybe just "admin" /Jens Henrik From lewis.sarah93 at yahoo.com Thu Dec 4 23:44:59 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 20:44:59 -0800 (PST) Subject: Reduce Debt Message-ID: Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From steve at holdenweb.com Mon Dec 15 12:35:36 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 15 Dec 2008 12:35:36 -0500 Subject: %s place holder does not let me insert ' in an sql query with python. In-Reply-To: References: <1229345178.31093.24.camel@krishna-laptop> Message-ID: <49469568.2090203@holdenweb.com> Lamonte Harris wrote: > I had this problem too. If you've upgraded to python 2.6 you need to > use the new sytnax "format > > queryString = "insert into venders > values('{0}','{1}','{2}'".format(field1,field2,field3) > Will all readers of this thread kindly regard this as an example of how *not* to generate and execute SQL queries in Python. Study the cursor.execute() method, and provide parameterized queries and a data tuple instead. Please also note that the above technique explicitly continues to generate SQL syntax errors in Krishnakan's case where the data values themselves contain apostrophes. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From castironpi at gmail.com Wed Dec 17 19:51:03 2008 From: castironpi at gmail.com (Aaron Brady) Date: Wed, 17 Dec 2008 16:51:03 -0800 (PST) Subject: C API and memory allocation References: Message-ID: On Dec 17, 6:42?pm, "Gabriel Genellina" wrote: > En Wed, 17 Dec 2008 21:35:04 -0200, Floris Bruynooghe ? > escribi?: > Yes; but you don't have to dig into the implementation; from ?http://docs.python.org/c-api/arg.html: > > s (string or Unicode object) [const char *] > Convert a Python string or Unicode object to a C pointer to a character ? > string. You must not provide storage for the string itself; a pointer to ? > an existing string is stored into the character pointer variable whose ? > address you pass. > > > But how can python now know how long to keep that buffer object in > > memory for? > > It doesn't - *you* have to ensure that the original string object isn't ? > destroyed (by example, incrementing its reference count as long as you ? > keep the pointer), or copy the string contents into your own buffer. I missed something. How did you get a reference to the original string object, with which to increment its reference count? How do you know its length to copy it into your own buffer? From robert.kern at gmail.com Sat Dec 27 19:37:30 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 27 Dec 2008 19:37:30 -0500 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: Daniel Fetchinson wrote: > I agree that array.array is more efficient than a list but the input > for my function will come from PIL and PIL returns a list. So I have a > list to begin with which will be passed to the C function. With recent versions of PIL, numpy can create an array from an Image very quickly, possibly without any copying of memory. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From gagsl-py2 at yahoo.com.ar Thu Dec 11 13:33:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 11 Dec 2008 16:33:08 -0200 Subject: Deeper tracebacks? References: Message-ID: En Thu, 11 Dec 2008 07:49:42 -0200, R. Bernstein escribi?: > brooklineTom writes: > >> I want my exception handler to report the method that originally >> raised an exception, at the deepest level in the call-tree. Let give >> an example. > extract_stack() without any arguments is getting this from the > *current frame* which as you noted doesn't have the last exception > info included which has been popped; variable sys.last_traceback has the > frames > at the time of the exception, I think. > > So in your code try changing: > aRawStack = traceback.extract_stack() > to > aRawStack = traceback.extract_stack(sys.last_traceback) No, last_traceback is the last *printed* traceback in the interactive interpreter. Use the third element in sys.exc_info() instead: import sys, traceback class SomeClass: def error(self): """Raises an AttributeError exception.""" int(3).zork() def perform_(self, aSelector): try: aMethod = getattr(self, aSelector) answer = aMethod() except AttributeError: tb = sys.exc_info()[2] try: print "Using traceback.print_tb:" traceback.print_tb(tb) print "Using traceback.print_exception:" traceback.print_exception(*sys.exc_info()) print "Using traceback.extract_tb:" print traceback.extract_tb(tb) finally: del tb SomeClass().perform_("error") output: Using traceback.print_tb: File "test_tb.py", line 11, in perform_ answer = aMethod() File "test_tb.py", line 6, in error int(3).zork() Using traceback.print_exception: Traceback (most recent call last): File "test_tb.py", line 11, in perform_ answer = aMethod() File "test_tb.py", line 6, in error int(3).zork() AttributeError: 'int' object has no attribute 'zork' Using traceback.extract_tb: [('test_tb.py', 11, 'perform_', 'answer = aMethod()'), ('test_tb.py', 6, 'error' , 'int(3).zork()')] (The "3-name form of the except clause" that I menctioned previously only exists in my imagination :) ) -- Gabriel Genellina From mensanator at aol.com Sat Dec 6 21:09:07 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 6 Dec 2008 18:09:07 -0800 (PST) Subject: "as" keyword woes References: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> <0147dc24$0$20670$c3e8da3@news.astraweb.com> <0148b217$0$20670$c3e8da3@news.astraweb.com> <7d0lj4d9hai2f87r30erc4l1ir85osbfg7@4ax.com> <88579d9a-df52-49b9-a6fe-53c8f4524bf3@j39g2000yqn.googlegroups.com> <70llj41hie2svs68o5efn22i97f649svfh@4ax.com> <1cda9a9a-1641-424b-9f3d-c4e2635efed7@j38g2000yqa.googlegroups.com> <014b0f94$0$20670$c3e8da3@news.astraweb.com> Message-ID: <4469f2ed-f012-400d-9d4f-bd44cd075d0d@w34g2000yqm.googlegroups.com> On Dec 6, 6:25?pm, Steven D'Aprano wrote: > On Sat, 06 Dec 2008 14:36:07 -0800, Mensanator wrote: > > It was extremely simple for me to fix the sympy module where I noticed > > it. I'm not saying it wasn't a problem, I'm saying it wasn't BROKEN. > > If it wasn't broken, why did you need to fix it? If my tire is flat, I have to fix it. But it may just need air, in which case it's not broken. > > "Broken" means "not working", not "unfixable". So, you're saying that Python is broken and will remain so forever, since "as" will remain a keyword? Are you advocating that we all switch to Ruby? > > -- > Steven From mail at timgolden.me.uk Mon Dec 1 09:43:07 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 01 Dec 2008 14:43:07 +0000 Subject: 11001, 'getaddrinfo failed' : Error in httplib but not in urllib2 In-Reply-To: References: Message-ID: <4933F7FB.2010204@timgolden.me.uk> RajNewbie wrote: > Hi all, > I am trying to connect to localhost via httplib, but it fails. > To check whether it is a firewall problem etc, I tried to connect > via urllib2, but it went through fine. Could some one help me out on this? I cannot use urllib2 in the > program because I have to send files via post to a url, and urllib2 > doesn't support it (Python2.4) > > Please see the code below: > -->HTTPLIB<-- > h = httplib.HTTPConnection("http://127.0.0.1:8000") > h.request('GET', "/accounts/") > res = h.getresponse() Which aspect of the documentation: http://docs.python.org/library/httplib.html leads you to think that the first parameter to httplib.HTTPConnection should be a URL? >>> import httplib >>> httplib.HTTPConnection ("127.0.0.1") >>> httplib.HTTPConnection ("localhost") >>> TJG From rcdailey at gmail.com Tue Dec 9 10:20:43 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 9 Dec 2008 07:20:43 -0800 (PST) Subject: RuntimeError: dictionary changed size during iteration References: <274eb282-1635-40ca-95af-b82271c57802@v4g2000yqa.googlegroups.com> <8c67c6b0-50f7-40ae-93e4-09edd07d6946@r36g2000prf.googlegroups.com> Message-ID: On Dec 8, 10:27?pm, John Machin wrote: > On Dec 9, 3:00?pm, Steven D'Aprano > > > > wrote: > > On Mon, 08 Dec 2008 19:10:00 -0800, Robert Dailey wrote: > > > On Dec 8, 6:26?pm, Terry Reedy wrote: > > >> Robert Dailey wrote: > > >> > stuff = vars() > > > >> ?>>> vars() is globals() > > >> True > > > >> > for key in stuff: > > > >> You just changed globals, which is aliased as stuff. Stuff changes. > > > >> > ? ? print( key, '--', stuff[key] ) > > > >> > I get the following error message: > > >> > ('CopyEmotionFX', '--', ) > > >> > Traceback (most recent call last): > > >> > ? File "C:\IT\work\jewett\depends.py", line 12, in > > >> > ? ? for key in stuff: > > >> > RuntimeError: dictionary changed size during iteration > > > >> > Why is this happening? > > > > How am I changing globals()? I'm simply iterating the keys in the dict. > > > Can someone explain what is going on please? > > > You create an new name "key": > > > for key in stuff > > > I suppose you could do this: > > > key = None > > stuff = vars() > > for key in stuff: > > but both 'key' and 'stuff' will appear in the dict, possibly causing > confusion; another reason why > > > even better would be: > > > for key in vars().copy(): > > > because that protects you from cases where globals() change inside the > > for loop. > > When I do: for key in stuff.keys(): It works! I wonder why .keys() makes a difference. It is using a 'view', which is a new concept in Python 3.0 that I'm not totally familiar with yet. From paul.hermeneutic at gmail.com Thu Dec 4 16:01:26 2008 From: paul.hermeneutic at gmail.com (Paul Watson) Date: Thu, 04 Dec 2008 15:01:26 -0600 Subject: Running Python 2 and Python 3 on the same machine Message-ID: <1228424486.5873.6.camel@linux-3eb6.site> The migration strategy detailed in PEP 3000 using 2to3 is quite nice. However, I am looking for suggestions for migrating to 3 while I still have code that requires 2. Since the source code is incompatible, I was expecting the Python executable to have a new name such as 'python3' or for the default source code filename to change to '.py3' or something. Yes, I have searched some on the web and the newsgroup, so please don't beat me up if this is well known. Thanks. From exarkun at divmod.com Thu Dec 4 17:32:30 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 4 Dec 2008 17:32:30 -0500 Subject: Checking if an int fits in 32 bits? In-Reply-To: Message-ID: <20081204223230.20272.353777632.divmod.quotient.15783@ohm> On Thu, 4 Dec 2008 12:11:08 -0800 (PST), Roy Smith wrote: >I'm working with marshaling data over a binary wire protocol. I'm >using struct.pack() to handle the low-level encoding of ints. One of >the things I need to do is make sure an int can be represented in 4 >bytes. Is there a portable way to do that? For now, I'm doing signed >ints, but I'll certainly have to do unsigned 32-bit ints (and 64-bit >ints) at some point. Not to mention shorts and chars. > >At first I thought pack() might raise an exception on a value >overflow, that but doesn't seem to be the case: > >>>> [hex(ord(c)) for c in struct.pack('!i', 999999999999999999999L)] >['0xde', '0x9f', '0xff', '0xff'] > >Should I be thinking more along the lines of bit masking (and worrying >about all the niggling 2-complement issues) in the Python code? Or is >there some cleaner way to do this? How about simple bounds checking? An integer fits in an unsigned 32bit representation if it is greater than or equal to 0 and less than 2 ** 32. The bounds for the sizes are similarly simple to determine and check. Jean-Paul From walterbyrd at iname.com Wed Dec 17 13:31:57 2008 From: walterbyrd at iname.com (walterbyrd) Date: Wed, 17 Dec 2008 10:31:57 -0800 (PST) Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> Message-ID: On Dec 17, 10:17?am, "Richard Brodie" wrote: > Not really, self is a formal parameter to the function. It would be > a strange language where a function's own arguments weren't in scope. Thank you, that makes sense to me. From sjmachin at lexicon.net Fri Dec 19 18:38:26 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 19 Dec 2008 15:38:26 -0800 (PST) Subject: encoding problem References: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> <6r1m72Ffb5kpU3@mid.uni-berlin.de> <6r2hvjFfb5kpU6@mid.uni-berlin.de> <6r2nfgFfb5kpU7@mid.uni-berlin.de> Message-ID: <2a3d8359-b614-44df-988c-7ebe2187e46d@e1g2000pra.googlegroups.com> On Dec 20, 10:02?am, Marc 'BlackJack' Rintsch wrote: > On Fri, 19 Dec 2008 15:20:08 -0700, Joe Strout wrote: > > Marc 'BlackJack' Rintsch wrote: > > >>> And because strings in Python, unlike in (say) REALbasic, do not know > >>> their encoding -- they're just a string of bytes. ?If they were a > >>> string of bytes PLUS an encoding, then every string would know what it > >>> is, and things like conversion to another encoding, or concatenation > >>> of two strings that may differ in encoding, could be handled > >>> automatically. > > >>> I consider this one of the great shortcomings of Python, but it's > >>> mostly just a temporary inconvenience -- the world is moving to > >>> Unicode, and with Python 3, we won't have to worry about it so much. > > >> I don't see the shortcoming in Python <3.0. ?If you want real strings > >> with characters instead of just a bunch of bytes simply use `unicode` > >> objects instead of `str`. > > > Fair enough -- that certainly is the best policy. ?But working with any > > other encoding (sometimes necessary when interfacing with any other > > software), it's still a bit of a PITA. > > But it has to be. ?There is no automagic guessing possible. > > >> And does REALbasic really use byte strings plus an encoding!? > > > You betcha! ?Works like a dream. > > IMHO a strange design decision. ?A lot more hassle compared to an opaque > unicode string type which uses some internal encoding that makes > operations like getting a character at a given index easy or > concatenating without the need to reencode. In general I quite agree with you ... hoever with Unicode "getting a character at a given index" is fine unless and until you stray (or are dragged!) outside the BMP and you have only a 16-bit Unicode implementation. From steve at holdenweb.com Thu Dec 18 13:09:37 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 18 Dec 2008 13:09:37 -0500 Subject: psycopg2 and large queries In-Reply-To: References: Message-ID: Paul Boddie wrote: [...]> > You really don't want to be traversing large data sets using fetchone, > anyway. My approach (using pyPgSQL) involves fetchmany and then > looping over each batch of results, if I really have to process the > data in Python; most of the time I can do the processing in the > database itself. Hmm, pypgsql doesn't provide a 2.5 Windows installer. I take it you aren't a Windows user ... ? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From jim.hefferon at gmail.com Sat Dec 20 17:37:36 2008 From: jim.hefferon at gmail.com (Jim) Date: Sat, 20 Dec 2008 14:37:36 -0800 (PST) Subject: ANN: New Book: Programming in Python 3 References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <400e99dc-90e2-441a-b7cf-5c2690915682@g38g2000yqd.googlegroups.com> <93e24f4e-a5d6-4952-93ce-f79b192a3666@a29g2000pra.googlegroups.com> Message-ID: I too will be interested in seeing the book. Nothing wrong with Lout -- and you can choose what suits you best, of course -- but just a couple of comments on the alternative. On Dec 19, 5:21 pm, Mark Summerfield wrote: : > - I can't draw but I can tell lout to draw for me and that works well > for my simple needs There are very competent and widely used packages to draw in LaTeX. Two are PSTricks and TikZ (you can google them each). > - embedding graphics (e.g., screenshots) is easy (just convert to EPS) Similarly for LaTeX. > - lout lets me specify Type1 fonts so I can easily use my own custom > Venus font for code & it is easy to embed it which makes publication > easier Current distributions of LaTeX contain XeLaTeX which allows you to use any T1 font that you have (to use it in mathematical text you need to do more, but I don't expect that you have a lot of mathematical text in your book). > - lots of books that use LaTeX have a certain sameness & I don't like > the computer modern fonts (IMO -- no offence intended) There are many alternative document styles and fonts available. > - after more than a decade of using lout I can pretty well get it to > do anything & everything I want (but I don't claim to be an expert > user) Fair enough. Jim From wolfgang.lipp at gmail.com Wed Dec 10 17:53:12 2008 From: wolfgang.lipp at gmail.com (_wolf) Date: Wed, 10 Dec 2008 14:53:12 -0800 (PST) Subject: forcing future re-import from with an imported module References: <533670ae-6d9d-4b10-9156-e41b31b678c7@g17g2000prg.googlegroups.com> Message-ID: On Dec 10, 1:46 pm, "Gabriel Genellina" wrote: > En Tue, 09 Dec 2008 23:27:10 -0200, _wolf > escribi?: > > > how can i say, approximately, "re-import the present module when it is > > imported the next time, don?t use the cache" in a simple way? i do not > > want to "reload" the module, that doesn?t help. > > I'd say you're using modules the wrong way then. The code inside a module > is executed *once*, and that's by design. If you want to execute something > more than once, put that code inside a function, and call it as many times > as you want. > > -- > Gabriel Genellina thanks for your answer. i am aware that imports are not designed to have side-effects, but this is exactly what i want: to trigger an action with `import foo`. you get foo, and doing this can have a side- effect for the module, in roughly the way that a `from __future__ import with_statement` changes the interpretation of the current module (of course, i do not intend to effect syntactic changes---my idea is to look into the module namespace and modify it). think of it as ?metamodule programming? (? la metaclass programming). maybe import hooks are the way to go? somtimes it would be good if there was a signalling system that broadcasts all kinds of system state change. cheers & ~flow ok so the question is: how to make it so each import of a given module has a side-effect, even repeated imports? From clp at rebertia.com Sun Dec 21 02:32:14 2008 From: clp at rebertia.com (Chris Rebert) Date: Sat, 20 Dec 2008 23:32:14 -0800 Subject: trapping all method calls in a class... In-Reply-To: <19ac19520812202312q71409182kb58a0f7aaf3b0e74@mail.gmail.com> References: <19ac19520812202312q71409182kb58a0f7aaf3b0e74@mail.gmail.com> Message-ID: <47c890dc0812202332n8be3837v2b1252416e60d334@mail.gmail.com> On Sat, Dec 20, 2008 at 11:12 PM, Piyush Anonymous wrote: > hi, > i need to trap all method calls in a class in order to update a counter > which is increased whenever a method is called and decreased whenever method > returns. in order to that i am trying to write a decorator for all the > methods. > > see the code here with error. > ------- > http://codepad.org/2w7JVvDB > ---- > any suggestions? any other better way of doing it? I call unnecessary use of metaclasses! Here's my (untested) attempt at a simpler class decorator approach: def decorate_meths(klass): attrs = klass.__dict__.items() for name, val in attrs: if callable(val): klass.__dict__[name] = decorate(val) def decorate(method): #should be called for every method call in the class def decorated(self, *args, **kwds): print "2 Inside __call__()" returnval = method(self, *args,**kwds) print "3 After self.f(*args)" return returnval return decorated #@decorate_meths <-- this syntax requires a later Python version class Person(object): def testprint(self,val): print "blah blah" Person = decorate_meths(Person) #rest of code after the class definition would be the same Sidenotes about your code: - `args` and `kwds` are the conventional names for the * and ** special arguments - the `methodname` variable was actually getting method objects, not strings, as its values; this was probably part of the bug in your program Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From noZ.spamZ at ZZ.ZsvpZ.com Mon Dec 15 10:13:20 2008 From: noZ.spamZ at ZZ.ZsvpZ.com (Michel Claveau - NoSpam SVP ; merci) Date: Mon, 15 Dec 2008 16:13:20 +0100 Subject: Problem Python 2.6.1 vs 2.6 & pyWin32 Message-ID: <4946754f$0$19000$426a74cc@news.free.fr> Hi, all! I have several softwares using Python+PyWin32, often as COM?server. Ok with Python 2.5.x. I want migrate to Python 2.6. But when I install python-2.6.1.msi + pywin32-212.win32-py2.6, my softs don't run. Tried on five machines (two XP & three Vista). But... if I install python-2.6.msi , IT'S OK!!! And, if I installl 2.6.1 once again, after 2.6, ... don't run ???!!! ;-((( In reality, soft run, but COM server can not be used. I get these messages : File "C:\Python26\Lib\site-packages\win32com\server\policy.py", line 728, in resolve_func module = _import_module(mname) File "C:\Python26\Lib\site-packages\win32com\server\policy.py", line 747, in _import_module __import__(mname) File "C:\Ponx\ponx.py", line 54, in import socket File "C:\Python26\lib\socket.py", line 46, in import _socket : DLL load failed: Le module sp?cifi? est introuvable. "Erreur non sp?cifi?e" (with call from JScript test, or VBScript test). (These tests run OK with 2.6 or 2.5.x) I am very disappointed. Help me, please. Thanks in advance. *** and sorry for my bad english *** @-salutations -- Michel Claveau From clp at rebertia.com Wed Dec 17 16:04:34 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 17 Dec 2008 13:04:34 -0800 Subject: something else instead of PIL? In-Reply-To: References: Message-ID: <47c890dc0812171304u4bfd1d9eq2f55b2681e7302e4@mail.gmail.com> On Wed, Dec 17, 2008 at 12:48 PM, Reimar Bauer wrote: > Hi > > what has happened to PIL? No updates since two years. The Python Imaging Library is still current; I guess they just haven't found any new bugs or seen fit to add new functionality in a while, though I presume they'll start working on a Python 3.0 port eventually. If you don't like PIL, there's always the (much less popular) Python bindings to ImageMagick: http://www.imagemagick.org/script/api.php#python Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From mirnazim at gmail.com Sun Dec 21 01:49:29 2008 From: mirnazim at gmail.com (Mir Nazim) Date: Sat, 20 Dec 2008 22:49:29 -0800 (PST) Subject: Question: Evaluate an string variable's value to a variable Message-ID: <4be6e91b-9fcf-4c22-bfe8-fad73190f87c@b41g2000pra.googlegroups.com> Just a quick question. For example I have >>> class X >>> ....pass Then I do >>> x = X() >>> x.name = 'Nazim Now my question is whether something like below is possible and how >>> y = 'name' >>> print x.y # How can x.y can be evaluated to x.name PS: In PHP this can be done by a $x->$y. I sure there is some way in Python also Thanks in advance. From lists at cheimes.de Thu Dec 11 16:57:39 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 11 Dec 2008 22:57:39 +0100 Subject: Best way of debigging a C extension In-Reply-To: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> References: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> Message-ID: <49418CD3.6080509@cheimes.de> Paul Moore wrote: > I have gdb (although I've hardly used it, but I can learn :-)) but if > I try building my extension with python setup.py build --debug, I get > an error because -lpython25_d does not exist. I'm not surprised by > this, as I don't have a debug build of Python - but that should be OK, > I'm only looking for debugging info from my code. You have to build Python on your own to get debug builds. Only debug builds allow to do extension debugging like memory leak finding. > I tried copying libpython25.a to libpython25_d.a - my extension now > builds, but the resulting pyd is XXX_d.pyd, which won't import. If I > rename this to XXX.pyd, I can import and things seem to work - but it > seems a bit of a roundabout way of doing things. Is there a simpler > way that I've missed? It seems to me that this (debugging a C > extension without compiling a debug build of Python) would be a fairly > common situation, so I would have expected a "cleaner" way of doing > it. You are working against the system ;) On Windows all extensions and shared libraries of a debug build have a _d suffix. > At the very least, a documentation patch to explain the best way of > doing things might be useful. I'll see what I can put together based > on the responses I get here. http://svn.python.org/view/python/branches/release25-maint/PCbuild/readme.txt?rev=51333&view=auto Christian From ed at leafe.com Wed Dec 3 22:29:41 2008 From: ed at leafe.com (Ed Leafe) Date: Wed, 3 Dec 2008 21:29:41 -0600 Subject: RELEASED Python 3.0 final In-Reply-To: References: Message-ID: <20739B1C-8B6F-4A7A-B699-76DD938DA2E3@leafe.com> On Dec 3, 2008, at 7:51 PM, Barry Warsaw wrote: > On behalf of the Python development team and the Python community, I > am happy to announce the release of Python 3.0 final. Props to all the folks whose hard work made this possible! You guys rock! -- Ed Leafe From prologic at shortcircuit.net.au Sun Dec 14 18:10:26 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 15 Dec 2008 09:10:26 +1000 Subject: Python 3.0 crashes displaying Unicode at interactive prompt In-Reply-To: <3fad7e29-c9ac-4b2e-aabe-e23a4cc5cb2c@q30g2000prq.googlegroups.com> References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> <3fad7e29-c9ac-4b2e-aabe-e23a4cc5cb2c@q30g2000prq.googlegroups.com> Message-ID: On Mon, Dec 15, 2008 at 9:03 AM, Fuzzyman wrote: > It seems to me to be a generally accepted term when an application > stops due to an unhandled error to say that it crashed. it == application Yes. -------------------- #!/usr/bin/env python from traceback import format_exc def foo(): print "Hello World!" def main(): try: foo() except Exception, error: print "ERROR: %s" % error print format_exc() if __name__ == "__main__": main() -------------------- --JamesMills From aleksandr.goretoy at gmail.com Tue Dec 30 22:39:23 2008 From: aleksandr.goretoy at gmail.com (alex goretoy) Date: Wed, 31 Dec 2008 03:39:23 +0000 Subject: pycurl urllib fallback Message-ID: Hello All, I have this class I like to call pcrunchly. That works to do all my request via libcurl library. What I want to do is add capability for this class to fallback to urllib if pycurl module is not install or is not importable for some reason. I'm posting my whole class. Use it however you want, just please help me to make it better. As you can see from the code I've already started to add this functionality. I found some code on Google that I'm trying to combine with my class, so that it can achieve this task. I want to ask the reader of this thread. Is this a good conservative thing to do. Will this make my class to bulky. Is this something I want? or do I want something else? Is there a better way to achieve this perhaps? I would appreciate any comments on this matter. I would like this class to be able to handle any protocol you throw at it. So as to make it other apps that need to use a different protocol and stuff. Please notice the first huge comment. That is what I'm currently combining into my working pycurl class. Is this good? Oh yeah, please don't mind all those self.soc functions calls. They print things in color to my terminal for me. #!/usr/bin/env python from ctypes import * import os, sys, types, urllib, urllib2, urlparse import stdout_colours #1. #!/usr/bin/env python #2. # -*- coding: UTF-8 -*- #3. #4. import cookielib #5. import urllib #6. import urllib2 #7. #8. cj = cookielib.CookieJar() #9. opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(c j)) #10. resp = opener.open('http://www.amm.com/login.asp') # save a cookie #11. #12. theurl = 'http://www.amm.com/login.asp' #13. # an example url that sets a cookie, try different urls here and see the cookie collection you can make ! #14. body={'username':'AMMT54590570','password':'AMMT32 564288'} #15. txdata = urllib.urlencode(body) #16. # if we were making a POST type request, we could encode a dictionary of values here - using urllib.urlencode #17. txheaders = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'} #18. # fake a user agent, some websites (like google) don't like automated exploration #19. #20. #21. try: #22. req = urllib2.Request(theurl, txdata, txheaders) # create a request object #23. handle = opener.open(req) # and open it to return a handle on the url #24. HTMLSource = handle.read() #25. f = file('test.html', 'w') #26. f.write(HTMLSource) #27. f.close() #28. #29. except IOError, e: #30. print 'We failed to open "%s".' % theurl #31. if hasattr(e, 'code'): #32. print 'We failed with error code - %s.' % e.code #33. elif hasattr(e, 'reason'): #34. print "The error object has the following 'reason' attribute :", e.reason #35. print "This usually means the server doesn't exist, is down, or we don't have an internet connection." #36. sys.exit() #37. #38. else: #39. print 'Here are the headers of the page :' #40. print handle.info() # handle.read() returns the page, handle.geturl() returns the true url of the page fetched (in case urlopen has followed any redirects, which it sometimes does) class curl(object): "Encapsulate user operations on CGIs through curl." def __init__(self, base_url=""): self.func_me_color="white_on_black" self.soc=stdout_colours.stdout_colors() self.soc.me_him(['ENTER:',__name__],self.func_me_color) # These members might be set. self.base_url = base_url self.verbose = 0 self.response = "" self.PYCURL=None try: import pycurl self.PYCURL = True except ImportError,e: import cookielib import urllib import urllib2 self.PYCURL = False #print "\ntrouble with importing pycurl %s\n" % e #sys.exit(1) # Nothing past here should be modified by the caller. if self.PYCURL: self.curlobj = pycurl.Curl() # Verify that we've got the right site... #self.curlobj.setopt(pycurl.SSL_VERIFYHOST, 2) # Follow redirects in case it wants to take us to a CGI... self.curlobj.setopt(pycurl.FOLLOWLOCATION, 1) #self.curlobj.setopt(pycurl.MAXREDIRS, 15) # Setting this option with even a nonexistent file makes libcurl # handle cookie capture and playback automatically. self.curlobj.setopt(pycurl.COOKIEFILE, "/dev/null") # Set timeouts to avoid hanging too long self.curlobj.setopt(pycurl.CONNECTTIMEOUT, 60) self.curlobj.setopt(pycurl.TIMEOUT, 600) #self.set_verbosity(self.verbose) # Set up a callback to capture else: self.cj=cookielib.CookieJar() print "\nurllib:\n" def response_callback(x): self.soc.me_him(['ENTER:',__name__],self.func_me_color) if self.PYCURL: self.response += x self.curlobj.setopt(pycurl.WRITEFUNCTION, response_callback) self.soc.me_him(['EXIT:',__name__],self.func_me_color) def set_verbosity(self, level): "Set verbosity to 1 to see transactions." self.soc.me_him(['ENTER:',__name__],self.func_me_color) if self.PYCURL: self.verbose=int(level) self.curlobj.setopt(pycurl.VERBOSE, self.verbose) self.soc.me_him(['EXIT:',__name__],self.func_me_color) def get(self, cgi, params=""): "Ship a GET request to a specified CGI, capture the response body." self.soc.me_him(['ENTER:',__name__],self.func_me_color) if self.PYCURL: if params: cgi += "?" + urllib.urlencode(params) self.curlobj.setopt(pycurl.URL, os.path.join(self.base_url, cgi)) self.curlobj.setopt(pycurl.HTTPGET, 1) self.response = "" self.curlobj.perform() # if self.verbose > 0: # print self.response self.soc.me_him(['EXIT:',__name__],self.func_me_color) def post(self, cgi, params): "Ship a POST request to a specified CGI, capture the response body.." self.soc.me_him(['ENTER:',__name__],self.func_me_color) if self.PYCURL: self.curlobj.setopt(pycurl.URL, os.path.join(self.base_url, cgi)) self.curlobj.setopt(pycurl.POST, 1) self.curlobj.setopt(pycurl.POSTFIELDS, urllib.urlencode(params)) self.response = "" self.curlobj.perform() # if self.verbose>0: # print self.response self.soc.me_him(['EXIT:',__name__],self.func_me_color) def upload(self, cgi, file_name, file): "POST file from localhost to location/cgi." self.soc.me_him(['ENTER:',__name__],self.func_me_color) if self.PYCURL: self.curlobj.setopt(pycurl.URL, os.path.join(self.base_url, cgi)) self.curlobj.setopt(pycurl.HTTPPOST,[(file_name, (pycurl.FORM_FILE,file))]) self.response = "" self.curlobj.perform() if self.verbose>0: print self.response self.soc.me_him(['EXIT:',__name__],self.func_me_color) # -------------------------------- # DJANGO RECEIVE TEST APPLICATION # -------------------------------- # --------- urls.py ---------------- #from django.conf.urls.defaults import * #urlpatterns = patterns('', #(r'^receive/$', 'web.views.receive'), #) # --------- web\views.py ---------------- #def receive(request): #assert request.method=="POST" #print "receive.META.SERVER_PORT", request.META["SERVER_PORT"], request.POST #files = [] #for multipart_name in request.FILES.keys(): #multipart_obj = request.FILES[multipart_name] #content_type = multipart_obj['content-type'] #filename = multipart_obj['filename'] #content = multipart_obj['content'] #files.append((filename, content_type, content)) #import datetime # write file to the system - add timestamp in the name #file("c:\\tmp\\%s_%s" % (datetime.datetime.now().isoformat().replace(":", "-"), filename), "wb").write(content) #fnames = ",".join([fname for fname, ct, c in files]) #return HttpResponse("me-%s-RECEIVE-OK[POST=%s,files=%s]" % (request.META["SERVER_PORT"], request.POST.values(), fnames )) def answered(self, check): "Does a given check string occur in the response?" self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.soc.me_him(['RETURN:',__name__],self.func_me_color) if self.PYCURL: return self.response.find(check) >= 0 def close(self): "Close a session, freeing resources." self.soc.me_him(['ENTER:',__name__],self.func_me_color) if self.PYCURL: self.curlobj.close() self.soc.me_him(['EXIT:',__name__],self.func_me_color) class session(curl): def login(self, cgisite,username, password): """login - cgi="login.php",params=(("username",name),("password",pass),("foo","bar")) """ self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.post(cgisite, (("username",username), ("password",password))) self.soc.me_him(['EXIT:',__name__],self.func_me_color) def logout(self, cgisite): """logout - cgi="logout.php" """ self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.get(cgisite) self.soc.me_him(['EXIT:',__name__],self.func_me_color) if __name__ == "__main__": if len(sys.argv) < 3: print "Usage: %s \"schema://site/cgi\" \"username\" \"password\"" % sys.argv[0] site=sys.argv[1] username=sys.argv[2] password=sys.argv[3] sess=session("") sess.set_verbosity(1) sess.login(site,username,password) a="" for i in range(len(password)): a+="*" print "YOU ARE LOGGED IN!",site,username,a sess.logout() sess.close() -- ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? -------------- next part -------------- An HTML attachment was scrubbed... URL: From denisbz at t-online.de Mon Dec 22 12:29:36 2008 From: denisbz at t-online.de (denisbz at t-online.de) Date: Mon, 22 Dec 2008 09:29:36 -0800 (PST) Subject: stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> <015612ac$0$20639$c3e8da3@news.astraweb.com> <52cfb77e-4baf-4fba-8eac-cc6c7ddb5be5@k1g2000prb.googlegroups.com> <5504f9ac0812150828m14f6999ak6112c5975042dc88@mail.gmail.com> <1ffd301f-16d3-4dc7-988c-7741d658ca10@z28g2000prd.googlegroups.com> Message-ID: On Dec 15, 10:00?pm, "cmdrrickhun... at yaho.com" wrote: > It can be proven that you cannot sort an arbitrarily large set of > numbers, given no extra information, faster than O(n log n). Cormen Leiserson and Rivest, "Algorithms", have a short clear chapter on "Sorting in linear time": " ... counting sort, radix sort and bucket sort ... use operations other than comparisons. Consequently, the Omega( n lg n ) lower bound does not apply to them." Some of the book is in books.google.com; enjoy From rNOSPAMon at flownet.com Sun Dec 28 03:22:49 2008 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sun, 28 Dec 2008 00:22:49 -0800 Subject: Need help getting MoinMoin to run under WSGI References: Message-ID: In article , Ron Garret wrote: > I successfully installed MoinMoin as a CGI according to the instructions > on the moinmo.in site. But when I tried to switch over to running it > under wsgi it failed thusly: > > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] Traceback (most > recent call last): > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] File > "/www/wikis/genesisgroup/moin.wsgi", line 49, in ? > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] from > MoinMoin.server.server_wsgi import WsgiConfig, moinmoinApp > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] ImportError: No > module named MoinMoin.server.server_wsgi > > The problem, I believe, is that I have both Python 2.4 and 2.5 installed > (it's a Debian box) and MM is installed under 2.5 but WSGI is using 2.4. > I tried to fix this by setting WSGIPythonHome but to no avail. I can't > figure out what to set it to. The instructions say: > > "the WSGIPythonHome directive should be used to specify the exact > location of the Python installation corresponding to the version of > Python compiled against" > > I have two problems with this. First, I didn't compile mod_wsgi, I got > it pre-built as a Debian module. Second, what does "the exact location > of the Python installation" even mean? Python2.5 is spread out in at > least three different places: /usr/local/bin, /usr/lib/python2.5, and > /usr/local/lib/python2.5. I've tried setting WSGIPythonHome to all of > those (and a few other things as well) and nothing worked. > > Also, "the version of Python compiled against" seems very odd. What > does that mean? Surely I don't have to recompile mod_wsgi every time I > change to a new version of Python? > > Help! Thanks! > > rg So never mind, I figured it out. I did indeed have to recompile mod_wsgi from source to get it to use Python 2.5. (That turned out to be a major hassle. I had to do it twice. The first time through it made Apache dump core. I still don't know why.) Seems to be working now though. rg From gandalf at shopzeus.com Tue Dec 30 08:54:45 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 30 Dec 2008 14:54:45 +0100 Subject: Python list's mail server in DNSBL ? Message-ID: <495A2825.4070000@shopzeus.com> I got this message when I tried to send something to this list, through my ISP's SMTP server: This Message was undeliverable due to the following reason: Each of the following recipients was rejected by a remote mail server. The reasons given by the server are included to help you determine why each recipient was rejected. Recipient: Reason: 5.7.1 : Recipient address rejected: policyd-weight Mail appears to be spam or forged. Ask your Mail-/DNS-Administrator to correct HELO and DNS MX settings and to get removed from DNSBLs; in bogusmx.rfc-ignorant.org Please reply to if you feel this message to be in error. Reporting-MTA: dns; viefep19.chello.at Arrival-Date: Tue, 30 Dec 2008 14:12:36 +0100 Received-From-MTA: dns; edge04.upc.biz (192.168.13.239) Final-Recipient: RFC822; Action: failed Status: 5.1.1 Remote-MTA: dns; mail.python.org (194.109.207.14) Diagnostic-Code: smtp; 550 5.7.1 : Recipient address rejected: policyd-weight Mail appears to be spam or forged. Ask your Mail-/DNS-Administrator to correct HELO and DNS MX settings and to get removed from DNSBLs; in bogusmx.rfc-ignorant.org Is python.org really blacklisted? Any admin please, try to remove it. Thanks Laszlo From clp at rebertia.com Mon Dec 15 15:03:14 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 15 Dec 2008 12:03:14 -0800 Subject: tricky nested list unpacking problem In-Reply-To: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> References: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> Message-ID: <47c890dc0812151203m7931ec0eif71b2ca8451465aa@mail.gmail.com> On Mon, Dec 15, 2008 at 11:06 AM, Reckoner wrote: > Hi, > > I have lists of the following type: > > [1,2,3,[5,6]] > > and I want to produce the following strings from this as > > '0-1-2-3-5' > '0-1-2-3-6' > > That was easy enough. The problem is that these can be nested. For > example: > > [1,2,3,[5,6],[7,8,9]] > > which should produce > > '0-1-2-3-5-7' > '0-1-2-3-5-8' > '0-1-2-3-5-9' > '0-1-2-3-6-7' > '0-1-2-3-6-8' > '0-1-2-3-6-9' > > also, > > [1,2,3,[5,6],7,[9]] > > should produce > > '0-1-2-3-5-7-9' > '0-1-2-3-6-7-9' > > obviously, these are nested loops over the lists. The problem is that > I don't know ahead of time how many lists there are or how deep they > go. In other words, you could have: > > [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]] > > Any help appreciated. I've really been having trouble with this. > > I hope that made sense. You just need a recursive list-flattening function. There are many recipes for these. Here's mine: def flatten(lst): if isinstance(lst, list): result = [] for item in lst: result += flatten(item) return result else: return [lst] >>> flattened = flatten([1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]]) >>> flattened [1, 2, 3, 5, 6, 10, 11, 7, 9, 1, 2, 3, 4, 5] >>> '-'.join(str(num) for num in flattened) '1-2-3-5-6-10-11-7-9-1-2-3-4-5' Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From bdesth.quelquechose at free.quelquepart.fr Sun Dec 7 13:23:57 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 07 Dec 2008 19:23:57 +0100 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: <493c2276$0$9254$426a34cc@news.free.fr> Daniel Fetchinson a ?crit : >>> Hi folks, >>> >>> The story of the explicit self in method definitions has been >>> discussed to death and we all know it will stay. However, Guido >>> himself acknowledged that an alternative syntax makes perfect sense >>> and having both (old and new) in a future version of python is a >>> possibility since it maintains backward compatibility. The alternative >>> syntax will be syntactic sugar for the old one. This blog post of his >>> is what I'm talking about: >>> >>> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html >>> >>> The proposal is to allow this: >>> >>> class C: >>> def self.method( arg ): >>> self.value = arg >>> return self.value >>> >>> instead of this: >>> >>> class C: >>> def method( self, arg ): >>> self.value = arg >>> return self.value >>> >>> I.e. explicit self stays only the syntax is slightly different and may >>> seem attractive to some. As pointed out by Guido classmethods would >>> work similarly: >>> >>> class C: >>> @classmethod >>> def cls.method( arg ): >>> cls.val = arg >>> return cls.val >>> >>> The fact that Guido says, >>> >>> "Now, I'm not saying that I like this better than the status quo. But >>> I like it a lot better than [...] but it has the great advantage that >>> it is backward compatible, and can be evolved into a PEP with a >>> reference implementation without too much effort." >>> >>> shows that the proposal is viable. >>> >>> I'd like this new way of defining methods, what do you guys think? >>> Anyone ready for writing a PEP? >>> >> What's the advantage? If there is not a good reason, I would strongly >> opposed polluting the language. > > Did you read the blog post? The advantage is having a less confusing > situation for newbies Once again: how is adding "magical" syntax going to reduce confusion ? > (confusing the number of arguments to a method > call). This is only confusing the first time. The correct solution to this problem is IMHO to better document Python's object model, specially how the descriptor protocol turns functions into methods. From lie.1296 at gmail.com Mon Dec 8 07:16:24 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 8 Dec 2008 12:16:24 +0000 (UTC) Subject: infering the number of args a function takes at runtime References: <25dcb5a7-1f31-4ef3-8b07-fb355dfd31e5@p2g2000prf.googlegroups.com> Message-ID: On Mon, 08 Dec 2008 02:40:03 -0800, sniffer wrote: > On Dec 8, 9:39?am, sniffer wrote: >> hi all, >> i am a python newbie, in a project currently doing i need to find out >> the number of arguments that a function takes at runtime.? Is this >> possible ,if so how do i do this,i ve looked through the python >> documentation but couldnt find anything.any help will be great >> >> TIA > > Thanks guys , i think this should work for me.btw as enquired i am > working o a mvc thingie where in need to call functions in a > controller,and pass the arguments as recieved from the end user so i > need to make sure that the number of arguments passed from the front end > are correct or not in the context of the function being called In python, usually you'll just pass the them all and maybe catch errors. def callback(*args, **kargs): try: return func(*args, **kargs) except TypeError: print('An error happened') From gagsl-py2 at yahoo.com.ar Thu Dec 25 15:58:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Dec 2008 18:58:07 -0200 Subject: How to display Chinese in a list retrieved from database via python References: <22be506d-91c2-4727-ace7-2e3382b6d214@g3g2000pre.googlegroups.com> Message-ID: En Thu, 25 Dec 2008 07:27:03 -0200, zxo102 escribi?: > On 12?25?, ??3?35?, "Chris Rebert" wrote: >> On Wed, Dec 24, 2008 at 11:29 PM, zxo102 wrote: >> > Hi, >> > I retrieve some info in Chinese from postgresql and assign it to a >> > variable 'info' defined in javascript of a html page: >> > var info = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce >> > \xc4'] >> > But I want it to be >> > var info = ['??','??','??'] >> > since in html pages (via javascript), the items in chinese out of the >> > former :['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4'] can >> > not be displayed correctly when it is inserted into a html page. If >> > the list is var info = ['??','??','??'] , then everything works >> > fine. >> > > The html code is as follows > > test > > > > But the '??' is '\xd6\xd0\xce\xc4'. When row01 and row02 is called > from somewhere, > '\xd6\xd0\xce\xc4' can not be displayed correctly as '??' in html > environment. You forgot to specify the page encoding, gb2312 presumably. If adding the encoding does not help, I'd say the problem must reside on how you later use row01 and row02 (your html page does not those variables for anything). '??' is the same as '\xd6\xd0\xce\xc4', and both javascript and Python share the same representation for strings (mostly) so this should not be an issue. My PC is unable to display those characters, but I get "true" from this: test -- Gabriel Genellina From pdorange at pas-de-pub-merci.mac.com Mon Dec 22 05:18:00 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Mon, 22 Dec 2008 11:18:00 +0100 Subject: no sign() function ? Message-ID: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> I don't find any sign(x) function in the math library (return the sign of the value). I've read that math module is a wrapper to C math lib and that C math lib has not sign(), so... I've implement my own sign function of course (it's easy) but a standard one in math would be better and could be faster. How do you implement this or is there any other module with a sign() function ? -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From clp at rebertia.com Sat Dec 6 16:53:56 2008 From: clp at rebertia.com (Chris Rebert) Date: Sat, 6 Dec 2008 13:53:56 -0800 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: <47c890dc0812061353x6214cfb4s1d729d36ab93f3dc@mail.gmail.com> On Sat, Dec 6, 2008 at 1:33 PM, Carl Banks wrote: > On Dec 5, 8:21 pm, "Daniel Fetchinson" > wrote: >> Hi folks, >> >> The story of the explicit self in method definitions has been >> discussed to death and we all know it will stay. However, Guido >> himself acknowledged that an alternative syntax makes perfect sense >> and having both (old and new) in a future version of python is a >> possibility since it maintains backward compatibility. The alternative >> syntax will be syntactic sugar for the old one. This blog post of his >> is what I'm talking about: >> >> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... >> >> The proposal is to allow this: >> >> class C: >> def self.method( arg ): >> self.value = arg >> return self.value >> >> instead of this: >> >> class C: >> def method( self, arg ): >> self.value = arg >> return self.value > > > > -1 > > I explained why deep in the thread but I'll elaborate more here. When > I see a def statement, I mentally equate that to an assigment to the > thing being def'ed. So for instance, when I see this: > > def (): > > I think of it like this: > > = > > > Thus, if I were to see a function definition like this > > def foo.bar(): return 1 > > I would think you were defining a function and assigning it to > foo.bar. IOW, it would be mostly equivalent to this: > > foo.bar = lambda: 1 > > > (Analogously, I would expect a definition like this: > > def baz[10](): return 1 > > to be equivalent to this: > > baz[10] = lambda: 1 ) > > > So, if, inside a class definition, I were to see this: > > def self.method(): return 1 > > Well, I'd understand that is was a method assigment, of course, but it > would conflict with what I would expect the natural meaning of > something like def a.b() would be. The above statement is not > equivalent to: > > self.method = lambda: 1 > > but I think that's what it ought to be, in general. Similarly, to those coming from Ruby or those operating under the frequent misunderstanding that the `def`s are happening in the context of a class object (which in reality has yet to be created), `self` in this context might be misconstrued as the class object and thus `def self.foo` might be misunderstood (through the intuitive equivalence you mention) as a defining a classmethod rather than an instance method. I also strongly echo the TOOWTDI arguments against adding this duplicative syntax. It's a minor gain but costs much more than it's worth for violating The Zen. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > > > Carl Banks > > > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Mon Dec 15 19:08:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 15 Dec 2008 22:08:18 -0200 Subject: Bidrectional Subprocess Communication References: <6qjspkFcv81kU1@mid.individual.net> Message-ID: En Sun, 14 Dec 2008 06:03:26 -0200, greg escribi?: > Gabriel Genellina wrote: > >> (Pipes don't work the same as sockets, although unix-like systems try >> hard to hide the differences...) > > BSD-based unixes implement pipes using socketpair(), so > pipes actually *are* sockets (or at least they used to be, > not sure whether it's still true). But not on Linux; a visible difference is that pipes are half-duplex on Linux (it seems that's enough for POSIX). I don't know for sure how they're implemented on Windows but they seem to be file system objects (they use functions like CreateFile, ReadFile, WriteFile, etc.) -- Gabriel Genellina From ajaksu at gmail.com Wed Dec 10 00:29:25 2008 From: ajaksu at gmail.com (ajaksu) Date: Tue, 9 Dec 2008 21:29:25 -0800 (PST) Subject: StringIO in 2.6 and beyond References: Message-ID: On Dec 9, 5:24?pm, Bill McClain <20080915.20.wmccl... at spamgourmet.com> wrote: > On 2008-12-09, MRAB wrote: > > > In Python 2.x unmarked string literals are bytestrings. In Python 3.x > > they're Unicode. The intention is to make the transition from 2.x to 3.x > > easier by adding some features of 3.x to 2.x, but without breaking > > backwards compatibility (not entirely successfully!). > > It is a bit ugly. In 2.6 StringIO won't take bytestrings, so I apply u'x'. But > in 3.0 u'x' will be gone and I'll have to change the code again. Try: from __future__ import unicode_literals From cjw at ncf.ca Mon Dec 1 19:56:44 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Mon, 01 Dec 2008 19:56:44 -0500 Subject: Why doesn't doc has predifined name and location ? In-Reply-To: References: <493455AD.4040306@gmail.com> Message-ID: Chris Rebert wrote: > On Mon, Dec 1, 2008 at 1:22 PM, Stef Mientki wrote: >> hello, >> >> I'm very satisfied about the great standardization of doc strings in python. >> Now in contrast to that, >> the general documentation of libraries, >> either in plain text, html, pdf, chm, ... >> doesn't have a standarized name nor location. >> >> Why is that ? > > I suppose the need for such standardization has just never arisen. > Googling for docs, checking the library's website, or doing `locate > library-name-here | grep doc` in bash seems to work well enough for > people that no one has found it necessary to pursue the creation of > such a standard. > > Sidenote: what Python projects publish their docs in CHM besides > possibly Win32 GUI programs? Python for windows or PyScripter. Colin W. > > Cheers, > Chris From psftw1 at gmail.com Sun Dec 14 14:00:16 2008 From: psftw1 at gmail.com (peter s.) Date: Sun, 14 Dec 2008 11:00:16 -0800 (PST) Subject: Building from source -- zlib/binascii problems 2.5.2/2.6.1 Message-ID: <71531b64-535f-49d0-a0c6-7704df83b251@f18g2000vbf.googlegroups.com> I am trying to build Python from source on a RHEL system where I do not have root access. There are two modules that I am having trouble with: zlib & binascii. zlib -- This seems like a make configuration issue. I have noticed that 'gcc -v' returns '--with-system-zlib': $ gcc -v Using built-in specs. Target: x86_64-redhat-linux Configured with: ../configure --prefix=/usr --mandir=/usr/share/man -- infodir=/usr/share/info --enable-shared --enable-threads=posix -- enable-checking=release --with-system-zlib --enable-__cxa_atexit -- disable-libunwind-exceptions --enable-libgcj-multifile --enable- languages=c,c++,objc,obj-c++,java,fortran,ada --enable-java-awt=gtk -- disable-dssi --enable-plugin --with-java-home=/usr/lib/jvm/java-1.4.2- gcj-1.4.2.0/jre --with-cpu=generic --host=x86_64-redhat-linux Thread model: posix gcc version 4.1.2 20071124 (Red Hat 4.1.2-42) and then when I run 'make' I see: building 'zlib' extension gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - Wstrict-prototypes -I. -I/location/of/Python-2.5.2/./Include -I. - IInclude -I./Include -I/usr/local/include -I/location/of/Python-2.5.2/ Include -I/location/of/Python-2.5.2 -c /location/of/Python-2.5.2/ Modules/zlibmodule.c -o build/temp.linux-x86_64-2.5/location/of/ Python-2.5.2/Modules/zlibmodule.o gcc -pthread -shared build/temp.linux-x86_64-2.5/location/of/ Python-2.5.2/Modules/zlibmodule.o -L/usr/local/lib -lz -o build/ lib.linux-x86_64-2.5/zlib.so /usr/bin/ld: skipping incompatible /usr/lib/libz.so when searching for -lz /usr/bin/ld: skipping incompatible /usr/lib/libz.a when searching for - lz /usr/bin/ld: cannot find -lz collect2: ld returned 1 exit status It seems as though I need to force the build process to use the zlib that comes with python source. binascii -- I have no idea what binascii requires in order to compile, so I am clueless. It properly compiles with 2.5.2, but fails to build in 2.6.1. I am OK using 2.5.2 if I could get zlib to work. Thanks, Peter From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 23 07:37:25 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 23 Dec 2008 13:37:25 +0100 Subject: On Whose Desktop In-Reply-To: References: Message-ID: <4950db7e$0$14770$426a74cc@news.free.fr> Steve Holden a ?crit : > Thanks to Barry Warsaw the "On Your Desktop" blog now has a new entry: > > http://onyourdesktop.blogspot.com/ > > Who would you like to see profiled next? The effbot ? > regards > Steve From cheney at halliburton.com Mon Dec 1 05:16:36 2008 From: cheney at halliburton.com (Andre Majorel) Date: Mon, 1 Dec 2008 10:16:36 +0000 (UTC) Subject: Python surpasses Perl in popularity? References: <5e87aee0-c7fd-4e9d-befb-0cc01cee64ec@f40g2000pri.googlegroups.com> <49316c95$0$2813$742ec2ed@news.sonic.net> <49322ea2$0$2747$742ec2ed@news.sonic.net> Message-ID: On 2008-11-30, Stephane Chazelas wrote: > 2008-11-30, 06:11(+00), Tam Ha: >> Stephane CHAZELAS wrote: >>> There's a common confusion in this in the nature of /bin/sh. >>> There's no standard (neither POSIX nor Unix) that specifies that >>> /bin/sh should be any variant of the Bourne shell. >> >> Sure there is, POSIX. > [...] > > And on this. First, POSIX has no juridiction on defining the > Bourne shell, let alone its location as the Bourne shell is > completely outside POSIX, it's a legacy shell and as been for > years. Then, POSIX makes it clear that the location of its sh > utility (again, which the Bourne shell is not) is unspecified, > only that the lookup of "sh" via $PATH in a conformant > environment should resolve to a conformant "sh". > > And if you need some examples to be convinced, see the different > choices of those 4 different POSIX conformant Unices: > > Solaris (7, 8, 9 at least): > /bin/sh: legacy Bourne/SVr4 shell > /usr/xpg4/bin/sh: a POSIX compliant shell (actually ksh88) > Solaris choice was to keep /bin/sh as the Bourne shell for > backward compatibility (as changing it for a POSIX shell > introduces a slight chance of breaking some existing scripts > as there are a few corner-case areas where the POSIX shells > are not backward compatible with the Bourne shell), and make > /bin a non standard place. How to get a conformant environment > (typically one where /usr/xpg4/bin/sh is before /bin) is > described in standards(5). The default one is not, which makes > Solaris a pain when porting scripts. > > HPUX (10.10 and newer at least): > /usr/bin/sh (and /bin/sh if there's a symlink /bin -> > usr/bin): a POSIX compliant shell (based on ksh88) > > /usr/old/bin/sh: the Bourne shell (though I think nowadays, > it's part of an optional package). > > Tru64: > /bin/sh can behave either as a Bourne shell or a POSIX shell > (ksh88) depending on the environment How does it decide ? argv[0] ? isatty (STDIN_FILENO) ? > most Linux based systems and most other Unices: > /bin/sh is a POSIX compliant shell (bash generally for Linux) > and there's no Bourne shell (either there has never been or it > has been removed/replaced by a POSIX shell). Two other Unixen I know of that have a non-POSIX sh are SCO Open Server and UnixWare. I'm not sure they even provide a POSIX-compliant alternative like Solaris does. On the other hand, their utilities (awk, grep, sed et al.) seem to be POSIX-compliant, at least to the extent that I've always managed. Unlike Solaris where I've often had to use the ones in /usr/xpg4/bin. Many people assume "standard" equates "portable". As far as shell programming is concerned, the safest way to get portability is to ignore the standard and code for the Bourne shell. -- Andr? Majorel "After 15 minutes, I wanted to marry her. After a half hour, I completely gave up the idea of snatching her purse." -- _Take the Money and Run_ From jcd at sdf.lonestar.org Tue Dec 2 09:33:35 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 02 Dec 2008 09:33:35 -0500 Subject: pydoc enforcement. In-Reply-To: <8542922d0812011438g529b8806l29e185896274609e@mail.gmail.com> References: <6ccec696-a8bb-4818-a016-642514677b70@b38g2000prf.googlegroups.com> <1228147384.32081.5.camel@aalcdl07.lib.unc.edu> <8542922d0812011438g529b8806l29e185896274609e@mail.gmail.com> Message-ID: <1228228415.5945.3.camel@aalcdl07.lib.unc.edu> On Tue, 2008-12-02 at 09:38 +1100, Ken Faulkner wrote: > Hi > > Yeah, I was thinking about something at commit time for a VCS... > catch is, soo many VCS's out there. > And I wasn't thinking of the default action throwing compile errors, > but would only do that if a particular flag was given. > Still, just an idea. > I meant more that a cultural solution might work better than a technical one. Don't allow commits that aren't documented, and *properly* documented. If you find them, back them out, scold the commiter, and revise. > I'm just finding more and more public modules/API's/libraries that > have so little documentation that it really does force reading a LOT > of the source to figure out whats going on. Sure, a lot of the time > thats required, but some modules are just painful.. > > oh well... was just a thought. > > Ken > > > > On Tue, Dec 2, 2008 at 3:03 AM, J. Cliff Dyer > wrote: > > > On Sun, 2008-11-30 at 16:27 -0800, ken.faulkner at gmail.com > wrote: > > I've been thinking about implementing (although no idea yet > *HOW*) the > > following features/extension for the python compile stage > and would be > > interested in any thoughts/comments/flames etc. > > > > Basically I'm interested adding a check to see if: > > 1) pydoc's are written for every function/method. > > 2) There are entries for each parameter, defined by some > > predetermined syntax. > > > > My idea is that as much as I love dynamic typing, there are > times when > > using some modules/API's that have less than stellar > documentation. I > > was thinking that if it was possible to enable some switch > that > > basically forced compilation to fail if certain > documentation criteria > > weren't met. > > > > Yes, it should be up to developers to provide documentation > in the > > first place. Or, the client developer might need to read the > source > > (IF its available)... but having some "forced" > documentation might at > > least ease the problem a little. > > > > For example (half borrowing from Javadoc). > > > > class Foo( object ): > > > > def bar( self, ui ): > > pass > > > > > > Would fail, since the bar method has an "unknown" parameter > called > > "ui". > > What I think could be interesting is that the compiler > forces some > > documentation such as: > > > > class Foo( object ): > > > > def bar( self, ui ): > > """ > > @Param: ui : blah blah blah. > > """ > > pass > > > > > > The compiler could check for @Param matching each parameter > passed to > > the method/function. Sure, a lot of people might just not > put a > > description in, so we'd be no better off. But at least its > getting > > them *that* far, maybe it would encourage them to actually > fill in > > details. > > > > Now ofcourse, in statically typed language, they might have > the > > description as "Instance of UIClass" or something like that. > For > > Python, maybe just a description of "Instance of abstract > class UI" or > > "List of Dictionaries"... or whatever. Sure, precise class > names > > mightn't be mentioned (since we mightn't know what is being > used > > then), but having *some* description would certainly be > helpful (I > > feel). > > > > Even if no-one else is interested in this feature, I think > it could > > help my own development (and would be an interested "first > change" > > into Python itself). > > > > Apart from bagging the idea, does anyone have a suggestion > on where in > > the Python source I would start for implementing such an > idea? > > > > Thanks > > > > Ken > > > For the reasons already stated, I think it's probably a bad > idea to > enforce this at compile time. I think it's a great idea to > make sure > that this information is present in all your code, but unless > you want > to see useless stubs, the correct time to enforce this is at > commit > time. Don't accept any improperly documented patches. > > Syntax is not enough to ensure what you want to ensure. The > semantics > have to be right as well. > > Cheers, > Cliff > > > > > From cmgui2 at gmail.com Sun Dec 14 23:38:58 2008 From: cmgui2 at gmail.com (cm_gui) Date: Sun, 14 Dec 2008 20:38:58 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> Message-ID: hahaha, do you know how much money they are spending on hardware to make youtube.com fast??? > By the way... I know of a very slow Python site called YouTube.com. In > fact, it is so slow that nobody ever uses it. From steve at holdenweb.com Sun Dec 28 12:38:50 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 28 Dec 2008 12:38:50 -0500 Subject: "return" in def In-Reply-To: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> Message-ID: Roger wrote: > Hi Everyone, > > First I want to thank everyone that posts to this group. I read it > daily and always learn something new even if I never feel like I have > anything to contribute but my questions. > > When I define a method I always include a return statement out of > habit even if I don't return anything explicitly: > > def something(): > # do something > return > > Is this pythonic or excessive? Is this an unnecessary affectation > that only adds clock ticks to my app and would I be better off > removing "returns" where nothing is returned or is it common practice > to have returns. > It's an unnecessary affectation, but I don't believe it adds any clock ticks to your app, as the function has to return anyway. The dis module shows you they both generate exactly the same code: >>> from dis import dis >>> def f1(): ... print "hello" ... >>> def f2(): ... print "hello" ... return ... >>> dis(f1) 2 0 LOAD_CONST 1 ('hello') 3 PRINT_ITEM 4 PRINT_NEWLINE 5 LOAD_CONST 0 (None) 8 RETURN_VALUE >>> dis(f2) 2 0 LOAD_CONST 1 ('hello') 3 PRINT_ITEM 4 PRINT_NEWLINE 3 5 LOAD_CONST 0 (None) 8 RETURN_VALUE >>> > Even when I'm not explicitly returning something I like to add > "return" because it's a good additional visual marker for me to see > where a method definition ends especially in cases where I may use a > nested method. > Well, I suppose at least you aren't writing "return None" ... Normally a blank line or two suffices for me. Take a look at PEP 8 for some discussion for Python coding style. http://www.python.org/dev/peps/pep-0008/ regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From andrew at doadesweb.co.uk Thu Dec 11 14:03:57 2008 From: andrew at doadesweb.co.uk (Andrew Doades) Date: Thu, 11 Dec 2008 19:03:57 +0000 Subject: get todays files In-Reply-To: <4941628E.7070902@tim.thechases.com> References: <4632c353-0462-485b-9e1b-6a5c56682363@s9g2000prg.googlegroups.com> <494015F7.3020302@tim.thechases.com> <49415258.2010101@doadesweb.co.uk> <4941628E.7070902@tim.thechases.com> Message-ID: <4941641D.8050209@doadesweb.co.uk> Tim Chase wrote: >> I know this will sound like I am being very cheeky, but is there a >> way you can make this for where the ftp server is actually windows >> server? > > For Windows Server, I don't have a Windows FTP server to test with -- > I've got the company Linux server, and the previous testing site I > used (I think I used ftp.mozilla.org) which also likely runs some > flavor of Linux. Neither supports the NLST from my testing. > >> curr_date = strftime("%d %B %Y", gmtime()) > > The first thing I noticed was that your strftime formating needs to > match the format of the date that comes back from the FTP site. In my > test, that was "YYYYMMDD". As such, your "%d %B %Y" would likely need > to be "%Y%m%d". > >> ftp.retrlines('NLST',makelist) > > The servers I tried didn't support the NLST command so I can't exactly > follow along here. However assuming that it correctly populates the > list of files here > >> for ff in files: > > correctly, that's immaterial to me. > >> ftp = FTP(ftp_server) >> ftp.set_pasv(False) >> resp = ftp.login(ftp_uname,ftp_pwd) > > Just curious why you're logging into the server each pass through the > loop -- I'd just connect once at the beginning of the loop, pull the > files, and then disconnect at the end of the loop. I support it would be somewhat better to download in a 'bulk' download rather that a file at a time, this script was not written by me, I am just the developer who has to make a new or modify the old one. > >> assert code == "213", "Unexpected result" > > Does this assert fail at any point? Nope, nothing shows up in my logs or on screen. > >> if stamp[:8] == today: > > Given the above date-formatting, this should fail *every* time unless > your FTP server is returning the date in some format other than > "YYYYMMDDhhmmss" This line appears to just get missed in the code, I think it might be one of the problems when it downloads all the files. > > > > It's hard to pinpoint actual problems as this block of code has been > modified, or doesn't run...there's some bogus indentation in your post: > >> log('Transferring: ' + ff[0]) >> # make parameters to wget the backup file >> params = ' ftp://' + ftp_server + '/' + ff[0] >> rcode = subprocess.call('c:/wget.exe ' + params) >> log('Return code from wget = ' + str(rcode)) >> if (rcode == 0): >> ff[1] = 1 >> else: >> log('File ' + ff[0] + ' already exists locally, not >> transferring') > > because this "else" is hanging oddly. Additionally, the FTP object > has methods for downloading the content of a file, so I'd not bother > shelling out to wget as an additional dependency I am running kubuntu 8.04 and have edited the code in kate, It seemed to indent on every line, so I just 'pulled' it back a little. > . > > -tkc Thanks for you comments, I think I will try and start from scratch and see what I get. Andrew > > > > From lewis.sarah93 at yahoo.com Fri Dec 5 00:14:30 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 21:14:30 -0800 (PST) Subject: Reduce Debt Message-ID: Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From hongqn at gmail.com Sun Dec 28 05:37:55 2008 From: hongqn at gmail.com (Qiangning Hong) Date: Sun, 28 Dec 2008 02:37:55 -0800 (PST) Subject: sys.stdout.write()'s bug or doc bug? References: Message-ID: On Dec 27, 12:31 am, Martin wrote: > Python 2.4.4 (#2, Oct 22 2008, 19:52:44) > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> u = u"\u554a" > >>> print u > ? > >>> sys.stdout.write(u + "\n") > > Traceback (most recent call last): > File "", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode character u'\u554a' in > position 0: ordinal not in range(128) > > >>> # you are trying to write unicode, you need to encode it to something that suits your needs > >>> sys.stdout.write(u.encode("UTF-8") + "\n") > ? > >>> # now go and write a hundred times "Unicode is not an encoding" :) Actually, I know relationship between unicode and str objects very well. That's why I only quoted the unicode-related part of file.encoding's documentation in my original post. Thank you. > > So, my question is, as sys.stdout IS a file object, why it does not > > use its encoding attribute to convert the given unicode? An > > implementation bug? A documenation bug? > > hmm I always thought "sys.stdout" is a "file-like object" not that it IS a file. In my original post, I have figured out that sys.stdout IS a file, by using type() function. And isinstance() function tells the same: Python 2.5.2 (r252:60911, Dec 18 2008, 12:39:19) [GCC 4.2.1 (Apple Inc. build 5564)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> type(sys.stdout) is file True >>> isinstance(sys.stdout, file) True So, sys.stdout SHOULD do what the doc says, otherwise there is a bug either in implementation of sys.stdout, or in the documentation of file. From python at bdurham.com Wed Dec 24 03:36:08 2008 From: python at bdurham.com (python at bdurham.com) Date: Wed, 24 Dec 2008 03:36:08 -0500 Subject: Most efficient way to build very large dictionaries In-Reply-To: References: <1230104615.5867.1291617213@webmail.messagingengine.com> Message-ID: <1230107768.14060.1291622121@webmail.messagingengine.com> Hi Roger, > you may want to consider using SQLite Thank you for your suggestion about looking at SQLite. I haven't compared the performance of SQLite to Python dictionaries, but I'm skeptical that SQLite would be faster than in-memory Python dictionaries for the type of analysis I'm doing. Prior to my use of Python, my customer used a very expensive Oracle system to analyze their log files. My simple Python scripts are 4-20x faster than the Oracle PL/SQL they are replacing - and run on much cheaper hardware. Note: Memory is currently not a concern for me so I don't need SQLite's ability to work with data sets larger than my physical memory. Regards, Malcolm ----- Original message ----- From: "Roger Binns" To: python-list at python.org Date: Wed, 24 Dec 2008 00:19:56 -0800 Subject: Re: Most efficient way to build very large dictionaries -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 python at bdurham.com wrote: > I would appreciate your thoughts on whether there are advantages to > working with a pre-built dictionary and if so, what are the best ways to > create a pre-loaded dictionary. Based on this and your other thread, you may want to consider using SQLite (standard Python module is available for it). SQL queries are very similar to set operations and indices take care of performance (by using more storage). You also get transactions for free. If you look into SQLite pragmas you can get it to use more RAM to improve performance. And by using a SQL layer you can later switch to another database should you need really hard core storage. It also makes the data available to other programs in a uniform way. Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAklR8KgACgkQmOOfHg372QSrHQCfVJzueXVKme8QZcxoLf70BL4K RL8AoM9QOFykOLrr5QXtpmZ5f7CFHm6e =zAPG -----END PGP SIGNATURE----- -- http://mail.python.org/mailman/listinfo/python-list From nebson at gmail.com Wed Dec 24 19:57:47 2008 From: nebson at gmail.com (Sponge Nebson) Date: Wed, 24 Dec 2008 16:57:47 -0800 (PST) Subject: Easy-to-use Python GUI References: Message-ID: <68d3a930-2cb6-4c6c-bcaf-cf50cb76093f@x16g2000prn.googlegroups.com> On Dec 24, 3:47?pm, "Joel Koltner" wrote: > Is there an easy-to-use, "function"-based cross-platform GUI toolkit for > Python out there that's a little more sophisticated than EasyGui? ?EasyGui > looks good, but it's a little more restrictive than what I'd like to have, yet > I'm (stubbornly :-) ) resistant to stepping up to a "full service" GUI toolkit > such as pyGTK or wxPython where it's all about event loops and callbacks and > you need to start planning how the GUI affects the overall program flow rather > than just using a "forms" (or "Wizard")-type approach where you put up a few > dialogs, users fill in some variables, and your program just sits around > waiting until "OK" or "Cancel" is clicked. > > One approach that I like comes from SAX BASIC/WinWrap, which is more or less a > clone of Microsoft's Visual BASIC for Applications, but they (apparently) > wanted everything to still be human-readable, so they have a simple GUI > ("form") builder that generates code that looks like this: > > --- > > ?Begin Dialog UserDialog 850,497,"Export Control" ' %GRID:10,7,1,1 > > ? GroupBox 20,7,360,217,"Drill File Generation",.GroupBox1 > ? CheckBox 40,35,130,14,"Output drill file(s)",.genDrill > ? Text 40,63,270,28,"Identify via layers as any that contain this text in > their names:",.Text > ? TextBox 40,98,220,21,.viaLayerName > ? Text 40,140,100,14,"Output method:",.Text8 > ? DropListBox 160,140,180,21,DrillStyle(),.drillStyle > ? Text 40,175,130,28,"Select drill table units:",.Text2 > ? ListBox 200,175,120,28,unitNames(),.unitName > > ? OKButton 310,469,90,21 > ? CancelButton 410,469,90,21 > > ?End Dialog > > ' GUI builder generates or modifies everything above, but can also be edited > by hand > ' You write the following code... > > ?Dim dlg As UserDialog > > ?dlg.genDrill = 1 > ?ReDim DrillStyle(1) > ?DrillStyle(0) = "All Via Layers In One File" > ?DrillStyle(1) = "One File Per Via Layer" > ?dlg.drillStyle = 1 > > ?func=Dialog(dlg) > > --- > > This is pretty darned easy for me understand and modify either by hand or with > the GUI builder. ?Still, it's quite powerful, since it supports all the common > GUI elements (text, group boxes, checkboxes, drop-down lists, text boxes, > buttons, etc.). ?This is about the level of sophistication I'm looking for. > > Anything like this for Python? > > Thanks, > ---Joel You may want to try PythonCard. It is a GUI toolkit that runs on wxPython, but it is much easier to use. Visit http://pythoncard.sourceforge.net/ and check out all the samples and screenshots. You may also want to listen to this podcast: http://libsyn.com/media/awaretek/Python411_070509_GUItoolkits.mp3 It discusses python GUI toolkits in general. You should also listen to: http://media.libsyn.com/media/awaretek/Python411_060730_PythonCard.mp3 which discusses PythonCard in detail. The python podcast collection can be found at: http://www.awaretek.com/python/ I just started out with PythonCard and I'm picking it up really fast. Hope this helps! -Sponge From srimogroupin at gmail.com Fri Dec 5 01:45:43 2008 From: srimogroupin at gmail.com (srimo) Date: Thu, 4 Dec 2008 22:45:43 -0800 (PST) Subject: Free Domain Name for life. supports for CNAME, A, MX, NS records! - Full DNS control - URL forwarding Message-ID: <05f28c1d-ac36-4b3f-bad5-6f0a45636477@y18g2000yqn.googlegroups.com> Register A Domain Name Free for life. Up to 2 free domain names. - You can transfer ownership of you domain to another person. Get a cool, simple and FREE domain! No Ads supports for CNAME, A, MX, NS records! Search for the domain you want - if it's available, register it today for FREE! Full DNS control and domain management provides free DNS and MX services. URL forwarding - Turn your long and boring URL http://www.sreemoo.com From bdesth.quelquechose at free.quelquepart.fr Sun Dec 7 13:54:10 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 07 Dec 2008 19:54:10 +0100 Subject: Guido's new method definition idea In-Reply-To: References: <493c2276$0$9254$426a34cc@news.free.fr> Message-ID: <493c298a$0$9254$426a34cc@news.free.fr> Daniel Fetchinson a ?crit : (snip) > > Still, improved error messages would be desirable (concerning the > number of arguments passed to an instance method). Then count me as +2 on this !-) From google at mrabarnett.plus.com Wed Dec 3 14:21:25 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 03 Dec 2008 19:21:25 +0000 Subject: python to parse excel file csv format In-Reply-To: References: Message-ID: <4936DC35.6010404@mrabarnett.plus.com> Jay Jesus Amorin wrote: > This is how i do it, but it runs with error. Kindly help > > > #!/usr/bin/env python > > import csv, sys, os > filename = (sys.argv[1]) > reader = csv.reader(open(filename, "rb"), delimiter=',', > quoting=csv.QUOTE_NONE) > > try: > for row in reader: > os.popen("chown row[0] row[1]") This should be: os.popen("chown %s %s" % (row[0], row[1])) or: os.popen("chown %s %s" % tuple(row)) > > except csv.Error, e: You could try adding: print e and perhaps: print repr(reader), dir(reader) here to see what the message was and why the following line raises an exception. > sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) > > > ================================================================== > > > testserver:~> ./promote2prod.py test.xls > Traceback (most recent call last): > File "./promote2prod.py", line 12, in ? > sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) > AttributeError: '_csv.reader' object has no attribute 'line_num' > From martin at v.loewis.de Fri Dec 19 01:30:13 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Fri, 19 Dec 2008 07:30:13 +0100 Subject: Python for amd64 and mingw-w64 In-Reply-To: References: Message-ID: <494B3F75.10104@v.loewis.de> > - Any extension requires the MS_WIN64 to be defined, but this symbol > is only defined for MS compiler (in PC/pyport.h). Why do you say that? It is only defined when _WIN64 is defined; this has nothing to do with a MS compiler. > Shouldn't it be > defined independantly of the compiler ? You mean, completely unconditional? Definitely not, it should only be defined when you are compiling for 64-bit mode. > - I have some link problems related to Py_InitModule4_64. I believe > the problem is in libpython26.a, which according to nm does not have > this symbol defined, whereas python26.dll has. It's a mistake if libpython26.a gets included in the Win64 installer at all; this library is only provided for 32-bit systems. My copy of mingw doesn't support Win64 at all. Regards, Martin From bj_666 at gmx.net Fri Dec 12 09:00:23 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 12 Dec 2008 14:00:23 GMT Subject: (Very Newbie) Problems defining a variable References: <49425146$0$8495$426a74cc@news.free.fr> <11c53a4a-de1e-4bee-ad60-a05befb6cbf4@a12g2000yqm.googlegroups.com> <7cb69ff5-9034-41cc-b667-d69329707b18@d36g2000prf.googlegroups.com> Message-ID: <6qf93mFc3a5jU2@mid.uni-berlin.de> On Fri, 12 Dec 2008 04:58:36 -0800, feba wrote: > Actually, I have gedit set to four spaces per tab. I have no reason why > it's showing up that large on copy/paste, but the file itself is fine. The file contains one tab character per indentation level and it depends on the software you use to look at the text how many spaces will be displayed. Better use four real spaces to indent one level so it looks the same everywhere. Ciao, Marc 'BlackJack' Rintsch From benjamin.kaplan at case.edu Fri Dec 19 14:49:57 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 19 Dec 2008 14:49:57 -0500 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <6r25ckFejl4vU1@mid.individual.net> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> <6r25ckFejl4vU1@mid.individual.net> Message-ID: On Fri, Dec 19, 2008 at 12:53 PM, Thomas Heller wrote: > Steve Holden schrieb: > > Thomas Heller wrote: > >> Question from a non-native english speaker: is this now valid english? > >> > >> "One of Python's great strengths" > >> ^ > >> "and also teaches Python's functional programming features" > >> ^ > >> "The book's approach is wholly practical" > >> ^ > > It always has been valid English. The apostrophe is only omitted from > > personal pronouns (hers, its, and so on). > > I see, thanks. But, is the apostrophe optional in the above fragments? > No. The apostrophe on the nouns is used to denote possession. If you don't include it, the word becomes plural (which makes no sense on proper nouns). The way to write the sentance without the apostrophe would be "One of the great strengths of Python" and "The approach of the book is wholly practical". To a native English speaker, this alternative is much more awkward. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ee1394 at gmail.com Thu Dec 11 14:44:46 2008 From: ee1394 at gmail.com (ee1394 at gmail.com) Date: Thu, 11 Dec 2008 11:44:46 -0800 (PST) Subject: EARN 15,000$ /- PER MONTH Message-ID: <86a0d986-65e7-457b-9719-1885fffc62f0@o4g2000pra.googlegroups.com> TURN YOUR PC INTO A CASH GENERATING, MACHINE.WORK ONLINE FROM HOME. GUARANTEED,EXTRA CASH, 15,000$ /- PER MONTH. NO INVESTMENT http://fishery.homestead.com/ From greywine at gmail.com Wed Dec 24 20:43:31 2008 From: greywine at gmail.com (greywine at gmail.com) Date: Wed, 24 Dec 2008 17:43:31 -0800 (PST) Subject: socket send help References: Message-ID: Chris & Gabriel, Thank you so much. My simple example now works. It was very frustrating that even the simple example didn't work, so your help is most appreciated. b'hello world' was the key. As for the error, I do still get it with 3.0 final so I'll go ahead and report it. John. On Dec 24, 12:03?am, "Gabriel Genellina" wrote: > En Wed, 24 Dec 2008 03:59:42 -0200, greyw... at gmail.com ? > escribi?: > > > New guy here. ?I'm trying to figure out sockets in order to one day do > > a multiplayer game. ?Here's my problem: ?even the simplest examples > > don't work on my computer: > > > A simple server: > > > fromsocketimport * > > myHost = '' > > Try with myHost = '127.0.0.1' instead - a firewall might be blocking your ? > server. > > > s.listen(5) ? ? ? ? ? ? ? ? ? ? ? ? # allow 5 simultaneous connections > > Not exactly: your server program only handles a single connection at a ? > time. The 5 above specifies how many connections may exist "on hold" ? > waiting for you to accept() them. > > > ? ? ? ? ? ? connection.send('echo -> ' + data) > > That's fine for Python 2.6, but you must use b'echo -> ' with 3.0 > > > And a simple client: > > > s.send('Hello world') ? ? ? ? ? ? ? # send the data > > Same as above, should be b'Hello world' with Python 3.0 > > > If I run testserver.py via the cmd prompt in Windows XP and then the > > testclient.py program, I get the following error: > > > Traceback (most recent call last): > > ? File "C:\Python30\testclient.py", line 12, in > > ? ? s.send('Hello world') ? ? ? ? ? ? ? # send the data > > TypeError: send() argument 1 must be string or buffer, not str > > The above error message is wrong (and I think it was corrected on the 3.0 ? > final release; if you got it with 3.0 final, file a bug report at ?http://bugs.python.org/) > > > This happens in 2.6 or 3.0 and with different example client & server > > programs from the web. ?What am I missing? > > The error above surely comes from 3.0; with 2.6 you should get a different ? > error (if it fails at all). Try again with 2.6.1. I didn't run the code ? > but it looks fine -- if you got it from a book or article, unless it ? > explicitely says "Python 3.0", assume it was written for the 2.x series. > > -- > Gabriel Genellina From duncan.booth at invalid.invalid Tue Dec 2 07:52:55 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Dec 2008 12:52:55 GMT Subject: optimization References: <6672532a-f162-4717-b0bb-c613214b57db@d32g2000yqe.googlegroups.com> <01450e77$0$20670$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Which makes me wonder, is there anything we can do with that code object > from Python code? I can disassemble it: > >>>> import dis >>>> dis.dis(outer.func_code.co_consts[1]) > 3 0 LOAD_CONST 0 (None) > 3 RETURN_VALUE > > Anything else? Provided it doesn't take any arguments you can run the code with exec or eval: >>> def outer(): def inner(): print "inner called" return inner() >>> eval(outer.func_code.co_consts[1]) inner called More usefully you could use the code object to construct another function, e.g. if you wanted to change the values of some default arguments. >>> types.FunctionType(outer.func_code.co_consts[1], globals())() inner called -- Duncan Booth http://kupuguy.blogspot.com From kyosohma at gmail.com Fri Dec 5 17:17:49 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 5 Dec 2008 14:17:49 -0800 (PST) Subject: To Troll or Not To Troll (aka: "as" keyword woes) References: <20081205163107.1815df40@usenot.de> Message-ID: <98e6c908-2bc5-49bd-8b2a-845b4de4b287@f3g2000yqf.googlegroups.com> On Dec 5, 4:00?pm, James Stroud wrote: > Andreas Waldenburger wrote: > > Is it me, or has c.l.p. developed a slightly harsher tone recently? > > (Haven't been following for a while.) > > Yep. I can only post here for about a week or two until someone blows a > cylinder and gets ugly because they interpreted something I said as a > criticism of the language and took it personally by extension. Then I > have to take a 4 month break because I'm VERY prone to > reciprocating--nastily. I think its a symptom of the language's > maturing, getting popular, and a minority fraction* of the language's > most devout advocates developing an egotism that complements their > python worship in a most unsavory way. > > I wish they would instead spend their energy volunteering to moderate > this list and culling out some of the spam. > > *No names were mentioned in the making of this post. I really like Python, but I seem to get blasted enough on this list that I don't post much on here any more without being extremely careful in how I word my answers. Bleh! Oh well. You win some, you lose some. Mike From Tribulations at Paralleles.invalid Wed Dec 31 09:40:32 2008 From: Tribulations at Paralleles.invalid (TP) Date: Wed, 31 Dec 2008 15:40:32 +0100 Subject: change only the nth occurrence of a pattern in a string Message-ID: <0scs26-7a5.ln1@rama.fbx.proxad.net> Hi everybody, I would like to change only the nth occurence of a pattern in a string. The problem with "replace" method of strings, and "re.sub" is that we can only define the number of occurrences to change from the first one. >>> v="coucou" >>> v.replace("o","i",2) 'ciuciu' >>> import re >>> re.sub( "o", "i", v,2) 'ciuciu' >>> re.sub( "o", "i", v,1) 'ciucou' What is the best way to change only the nth occurence (occurrence number n)? Why this default behavior? For the user, it would be easier to put re.sub or replace in a loop to change the first n occurences. Thanks Julien -- python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\ 9&1+,\'Z4(55l4('])" "When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong." (first law of AC Clarke) From jantod at gmail.com Wed Dec 3 10:08:52 2008 From: jantod at gmail.com (Janto Dreijer) Date: Wed, 3 Dec 2008 07:08:52 -0800 (PST) Subject: Reverse zip() ? References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> <20081203095154.1bb33d4d@usenot.de> <8000d0b0-c9e5-4dbd-a6a0-e35b83277e72@d42g2000prb.googlegroups.com> <20081203114855.3915af9e@usenot.de> Message-ID: I'd like to point out that since your where thinking in terms of matplotlib, you might actually find numpy's own transpose useful, instead of using zip(*seq) :) untested: t = linspace(0,2*pi*3) seq = asarray(zip(t, sin(t))) t, y = seq.T # or seq.transpose() or numpy.transpose(seq) pylab.plot(t,y) Regards Janto Andreas Waldenburger wrote: > On Wed, 3 Dec 2008 02:11:51 -0800 (PST) alex23 > wrote: > > > On Dec 3, 6:51?pm, Andreas Waldenburger wrote: > > > On Tue, 02 Dec 2008 18:16:13 -0800 Bryan Olson > > > > zip as its own inverse might be even easier to comprehend if we > > > > call zip by its more traditional name, "transpose". > > > > > > Sounds like a Py4k change to me. > > > > Nah, just add the following to your sitecustomize.py: > > > > transpose = zip > > > > :) > > Gaaahh! > > :) > /W > > -- > My real email address is constructed by swapping the domain with the > recipient (local part). From steve at holdenweb.com Wed Dec 17 22:03:49 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 17 Dec 2008 22:03:49 -0500 Subject: getting object instead of string from dir() In-Reply-To: <0159a791$0$20656$c3e8da3@news.astraweb.com> References: <477b9c2e-a0ab-4b26-b643-4a9369c2aaac@r2g2000vbp.googlegroups.com> <0159a791$0$20656$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Wed, 17 Dec 2008 11:52:17 -0800, Rominsky wrote: > >> I do have some understanding of the pythonic methodology of programming, >> though by far I still don't consider myself an expert. The problem at >> hand is that I am coming from a matlab world and trying to drag my >> coworkers with me. I have gotten a lot of them excited about using >> python for this work, but the biggest gripe everytime is they want their >> matlab ide. I am trying to experiment with making similar pieces of the >> ide, in particular I am working on the workspace window which lists all >> the current variables in the namespace, along with their type, size, >> value, etc.... I am trying to create a python equivalent. > > > Have you considered looking at existing IDEs instead of re-inventing the > wheel? Python even comes with one, IDLE. > > > I realise there are some very competent Python programmers whose primary environment is IDLE, but I'm afraid I always end up frustrated with it. I think Rominsky will learn a lot by noodling around in the way he proposes - he does, after all, confess he is experimenting, and that sounds to me like a great way to find out a lot in a fairly short time. Matlab is a very specific environment, and students have told me that there are pieces of its IDE that they really miss in Python, so this work may result in something that attracts more users to Python. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From de.slotenzwemmer at gmail.com Thu Dec 25 05:22:01 2008 From: de.slotenzwemmer at gmail.com (Dennis van Oosterhout) Date: Thu, 25 Dec 2008 11:22:01 +0100 Subject: os.system('cls') Message-ID: Hi there! I was searching for a way to clear the 'DOS screen'/command screen etc. and found that os.system('cls') works for this. I was just wondering where I can find al the commands which can be used for os.system(). I searched with google but I didn't find an answer. In the official python tutorial it says os.system('command') executes the command, but it doesn't say which commands exist (or I'm just blind). Does anyone have an answer for this question? Thanks, Devilly -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Mon Dec 29 09:01:58 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 06:01:58 -0800 (PST) Subject: poblem regarding opening a html file References: <022701c969a0$a4541ef0$5fc513ac@pwit.com> Message-ID: On Dec 29, 6:10?am, "Hendrik van Rooyen" wrote: > Sibtey Mehdi ?wrote: > >Hi > > ? ? ? ? ? ?I have a GUI application (wxpython) that calls another GUI > > Application. I m using os.system (cmd) >to launch>The second GUI, in the second GUI I m trying to open the html file using the > > os.startfile (filename) function >but > > >It takes lots of time to open the html file. > >If I am running only the second application then ?os.startfile? quickly open > the html file. > >Any one can help me to solve this problem. > > Buy more memory? > > - Hendrik You might be running into problems with duelling message pumps in the GUI loops. The 'os.system' call runs in a subprocess, not in an independent one. If you use 'subprocess.Popen', you can explicitly wait on the second process, which will hang your first GUI, but may cause the second one to run better. Or, you have the option to not wait for it. I see that 'os.system' waits for the second process to complete, while 'startfile' does not. Just a thought, are you looking for the 'webbrowser' module? Another option is to run it from a separate thread. From google at mrabarnett.plus.com Mon Dec 8 09:21:40 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 08 Dec 2008 14:21:40 +0000 Subject: gzip.GzipFile (was Re: Don't you just love writing this sort of thing :)) In-Reply-To: References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: <493D2D74.5060708@mrabarnett.plus.com> Jorgen Grahn wrote: > On Sat, 06 Dec 2008 10:01:10 +0000, Arnaud Delobelle wrote: > > ... >> Why use (open, gzp.GzipFile)[Entry.endswith(".gz")] when we have had >> contitional expressions for a few years now? Instead, you can write >> >> (gzip.GzipFile if entry.endswidth(".gz") else open). >> >> I think it will be faster (as it doesn't require the construction of a >> tuple and then the retrieval of one of its elements) and clearer. > > Even clearer would be if gzip.Gzipfile could (optionally) read > non-gzipped files and file-like objects, like the gzip Unix commands > zcat -f, zgrep and so on. > > Also, making a decision based on the .gz part of the name isn't > always correct -- you miss files named foo.Z and similar. > gzip is for reading gzipped files. IMHO it would be better to have a de-archive module which uses the gzip, tarfile, etc, modules as necessary. From pdorange at pas-de-pub-merci.mac.com Mon Dec 8 05:17:36 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Mon, 8 Dec 2008 11:17:36 +0100 Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? References: <5ccd4a18-cd2b-4040-90c6-33723af15e96@b38g2000prf.googlegroups.com> Message-ID: <1irmm85.6rh7brf6my0eN%pdorange@pas-de-pub-merci.mac.com> illume wrote: > pygame is also much more portable, has more people using it, has more > developers, and a stable API. Code you wrote 5 years ago will most > likely still work. Code you wrote for older versions of pyglet will > not work without changes. I'm a new python and pygame user (i came from C/C++), very easy to learn and you got results very fast. I've done a low investigation before choosing pygame over pyglet. I choose pygame because i only need 2D and also because it seems there is more documentations, samples, books and developers for pygame. pygame is really easy to learn and seems fast to me and easy to extend (derivate class), support image, sound, etc... And can be bundled with py2app (Mac) : important to distribute the project. I just run a bug whn using background music, py2app fail ti create the bundle... On my iMac intel, i run my small arcade game (a spaceinvader like) between 800-1400 fps using dirtyrect. I can also run without modification on Windows and Unbuntu using WMWare on the same machine. -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From collin.day.0 at gmail.com Thu Dec 18 20:42:28 2008 From: collin.day.0 at gmail.com (Collin D) Date: Thu, 18 Dec 2008 17:42:28 -0800 (PST) Subject: Factoring Polynomials References: <015aebdf$0$20656$c3e8da3@news.astraweb.com> Message-ID: On Dec 18, 5:10?pm, Steven D'Aprano wrote: > On Thu, 18 Dec 2008 11:37:35 -0800, collin.day.0 wrote: > > I am trying to write a simple application to factor polynomials. I wrote > > (simple) raw_input lines to collect the a, b, and c values from the > > user, but I dont know how to implement the quadratic equation > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > into python. Any ideas? > > def quadratic_solution(a, b, c): > ? ? sol1 = (-b + (b**2 - 4*a*c)**0.5)/2*a > ? ? sol2 = (-b - (b**2 - 4*a*c)**0.5)/2*a > ? ? return (sol1, sol2) > > Because this looks like homework, I've deliberately left in two errors in > the above. One of them is duplicated in the two lines above the return, > and you must fix it or you'll get radically wrong answers. > > The second is more subtle, and quite frankly if this is homework you > could probably leave it in and probably not even lose marks. You will > need to do significant research into numerical methods to learn what it > is, but you will then get significantly more accurate results. > > -- > Steven The corrected function is: def quadratic_solution(a,b,c) sol1 = -1*b + ((b**2 - 4*a*c)**.5)/2*a sol1 = -1*b - ((b**2 - 4*a*c)**.5)/2*a return (sol1, sol2) Squaring the -b would give you some strange solutions.... :D -CD From onidaito at gmail.com Wed Dec 31 08:12:59 2008 From: onidaito at gmail.com (Benjamin Blundell) Date: Wed, 31 Dec 2008 05:12:59 -0800 (PST) Subject: Graphics Library with Standard Interaction Features, 2D and 3D References: <69c3eca8-5e17-49fb-8354-5fdc0bd73f9a@r15g2000prd.googlegroups.com> Message-ID: On Dec 31, 12:55?pm, Python wrote: > On 31 dec 2008, at 13:37, Benjamin Blundell wrote: > > > > > Hi all. I've had a look around the forums and the we and im looking > > for a library (or a set of libraries) for dealing with Visualisation > > and Interaction in Python. At the moment i've been using Flash with > > the Five3D library to do most of the work. Sadly this isnt an option > > anymore but it is a good example. Pretty,anti-aliased 2D and 3D > > graphics, simple interaction and no need to rewrite the wheel. > > > Im a fan of OpenGL and PyOpenGL is fairly cool but I really dont want > > to have to write yet another camera, another way of dealing with > > Vectors, texture organiser, picking, etc etc. Is there a library or > > set of libraries that people are aware of that might do this? I > > remember a few in C++ and C but it'd be nicer to stick to working with > > Python > > > Cheers > > Ben > > Hey Ben, > > dunno if this is exactly what you;re looking for, > yet you could have a look at Blenderhttp://blender.org/http://wiki.blender.org/index.php/Scripts > > it's an open source 3D application and has a python > scripting engine... (just like maya from Autodesk) > > gr > Arno Sorry, I should have explained a little more. I've used Blender quite a bit and its an ace program. But what im after is a set of tools for creating a visualisation program. A while ago, we used QT with the OpenGL plugins and this library: http://www.libqglviewer.com/ Essentially, you mashed these 3 together and you got a proper OpenGL window with basic mouse looks, picks and all the rest of the 'standard' stuff you cant be arsed coding for the 15th time or so ;) Model loading is also supported from a small array of formats. im not uber keen that it has to be opengl but im sure there must be a similar set of python libs out there. PyGame isnt a bad one at all but its graphic manipulation routines can be a pain (rotations) and its 2D only but its certainly along the right lines. Cheers Ben From deets at nospam.web.de Sat Dec 13 14:35:58 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 13 Dec 2008 20:35:58 +0100 Subject: [OT] stable algorithm with complexity O(n) In-Reply-To: References: <6qidmbFc4qduU1@mid.uni-berlin.de> Message-ID: <6qih4uFconetU1@mid.uni-berlin.de> Duncan Booth schrieb: > "Diez B. Roggisch" wrote: > >> David Hl????ik schrieb: >>> Hi guys, >>> >>> i am really sorry for making offtopic, hope you will not kill me, but >>> this is for me life important problem which needs to be solved within >>> next 12 hours.. >>> >>> I have to create stable algorithm for sorting n numbers from interval >>> [1,n^2] with time complexity O(n) . >>> >>> Can someone please give me a hint. Would be very very thankful! >> Unless I grossly miss out on something in computer science 101, the >> lower bound for sorting is O(n * log_2 n). Which makes your task >> impossible, unless there is something to be assumed about the >> distribution of numbers in your sequence. >> >> Who has given you that assignment - a professor? Or some friend who's >> playing tricks on you? >> > I think you must have fallen asleep during CS101. The lower bound for > sorting where you make a two way branch at each step is O(n * log_2 n), but > if you can choose between k possible orderings in a single comparison you > can get O(n * log_k n). > > To beat n * log_2 n just use a bucket sort: for numbers with a known > maximum you can sort them digit by digit for O(n log_k n), and if you don't > restrict yourself to decimal then k can be as large as you want, so for the > problem in question I think you can set k=n and (log_n n)==1 so you get > O(n) Thanks. I *totally* forgot about that. Diez From steve at REMOVE-THIS-cybersource.com.au Wed Dec 3 17:38:22 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 03 Dec 2008 22:38:22 GMT Subject: "as" keyword woes References: <493701f0$0$194$e4fe514c@news.xs4all.nl> Message-ID: <01470229$0$20670$c3e8da3@news.astraweb.com> On Wed, 03 Dec 2008 22:02:24 +0000, Martin P. Hellwig wrote: > Warren DeLano wrote: >> A bottom line / pragmatic question... hopefully not a FAQ. >> >> Why was it necessary to make "as" a reserved keyword? > > Because it can be used at the import statement to let the imported thing > be known under another name? > Something like: > > >>> import xml.etree.ElementTree as ET Martin, that doesn't answer the OP's question *at all*. Python 2.5 uses "as" in that way, and it is not a keyword. >>> import math as MATHS >>> MATHS >>> as = 45 :1: Warning: 'as' will become a reserved keyword in Python 2.6 >>> as :1: Warning: 'as' will become a reserved keyword in Python 2.6 45 I'd guess that the change was to simplify the CPython parser. I have no idea if it was a tiny change or a significant change, if it made a huge difference to Python-dev or a little difference. Perhaps someone on the dev team could comment. While I feel sympathy for the OP, I do have to ask: he's been using Python 2.5 for, what, a couple of years now? How many times did he see the depreciation warning, and almost certainly the pending depreciation warning before that? Python-dev has been talking about making "as" a keyword since at least Python 2.3. Why wait until after version 2.6 is released before saying anything? -- Steven From rNOSPAMon at flownet.com Sun Dec 28 17:26:23 2008 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sun, 28 Dec 2008 14:26:23 -0800 Subject: Need help getting MoinMoin to run under WSGI References: Message-ID: In article , Graham Dumpleton wrote: > On Dec 28, 7:22?pm, Ron Garret wrote: > > In article , > > ?Ron Garret wrote: > > > > > > > > > I successfully installed MoinMoin as a CGI according to the instructions > > > on the moinmo.in site. ?But when I tried to switch over to running it > > > under wsgi it failed thusly: > > > > > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] Traceback (most > > > recent call last): > > > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] ? File > > > "/www/wikis/genesisgroup/moin.wsgi", line 49, in ? > > > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] ? ? from > > > MoinMoin.server.server_wsgi import WsgiConfig, moinmoinApp > > > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] ImportError: No > > > module named MoinMoin.server.server_wsgi > > > > > The problem, I believe, is that I have both Python 2.4 and 2.5 installed > > > (it's a Debian box) and MM is installed under 2.5 but WSGI is using 2.4. > > > ? > > > I tried to fix this by setting WSGIPythonHome but to no avail. ?I can't > > > figure out what to set it to. ?The instructions say: > > > > > "the WSGIPythonHome directive should be used to specify the exact > > > location of the Python installation corresponding to the version of > > > Python compiled against" > > > > > I have two problems with this. ?First, I didn't compilemod_wsgi, I got > > > it pre-built as a Debian module. ?Second, what does "the exact location > > > of the Python installation" even mean? ?Python2.5 is spread out in at > > > least three different places: /usr/local/bin, /usr/lib/python2.5, and > > > /usr/local/lib/python2.5. ?I've tried setting WSGIPythonHome to all of > > > those (and a few other things as well) and nothing worked. > > > > > Also, "the version of Python compiled against" seems very odd. ?What > > > does that mean? ?Surely I don't have to recompilemod_wsgievery time I > > > change to a new version of Python? > > > > > Help! ?Thanks! > > > > > rg > > > > So never mind, I figured it out. ?I did indeed have to > > recompilemod_wsgifrom source to get it to use Python 2.5. ?(That turned out > > to > > be a major hassle. ?I had to do it twice. ?The first time through it > > made Apache dump core. ?I still don't know why.) > > > > Seems to be working now though. > > It probably crashed the first time because you didn't do a full stop > of Apache and instead just did a reload. Doing a reload may not unload > the Python libraries from Apache process correctly and so would have > been a mix of code for different versions of Python in same process. > > Graham Yes, I don't specifically recall exactly what happened now, but that seems likely. Thanks, rg From google at mrabarnett.plus.com Fri Dec 19 11:16:12 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 19 Dec 2008 16:16:12 +0000 Subject: Generator slower than iterator? In-Reply-To: References: <62013718-57e9-4690-a2be-11e63b9c135b@u18g2000pro.googlegroups.com> Message-ID: <494BC8CC.6020706@mrabarnett.plus.com> Federico Moreira wrote: > Great, 2min 34 secs with the open method =) > > but why? > > ip, sep, rest = line.partition(' ') > match_counter[ip] += 1 > > instead of > > match_counter[line.strip()[0]] += 1 > > strip really takes more time than partition? > > I'm having the same results with both of them right now. > I think you meant split(), not strip(). split() might split the string into many parts, but you want only the first part (at most 1 split), so the extra splits are unnecessary and waste time. split(None, 1) and partition(' ') do at most 1 split, so they don't do unnecessary work. From collin.day.0 at gmail.com Thu Dec 18 21:31:11 2008 From: collin.day.0 at gmail.com (Collin D) Date: Thu, 18 Dec 2008 18:31:11 -0800 (PST) Subject: Factoring Polynomials References: <919062f9-765e-4279-aa26-2c130d4deacf@o4g2000pra.googlegroups.com> <4479b464-3a9b-4dd8-bf66-fea7d9471091@n33g2000pri.googlegroups.com> Message-ID: <661fd2d0-251d-4899-a015-8d257310a159@q26g2000prq.googlegroups.com> On Dec 18, 6:27?pm, Collin D wrote: > On Dec 18, 6:23?pm, "Russ P." wrote: > > > > > > > On Dec 18, 6:17?pm, Collin D wrote: > > > > On Dec 18, 6:12?pm, Collin D wrote: > > > > > On Dec 18, 11:37?am, collin.da... at gmail.com wrote: > > > > > > I am trying to write a simple application to factor polynomials. I > > > > > wrote (simple) raw_input lines to collect the a, b, and c values from > > > > > the user, but I dont know how to implement the quadratic equation > > > > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > > > > into python. Any ideas? > > > > > I completed the code: > > > > > #import > > > > from math import sqrt > > > > > # collect data > > > > a = float(raw_input('Type a value: ')) > > > > b = float(raw_input('Type b value: ')) > > > > c = float(raw_input('Type c value: ')) > > > > > # create solver > > > > def solver(a,b,c): > > > > ? ? if b**2 - 4*a*c < 0: > > > > ? ? ? ? return 'No real solution.' > > > > ? ? else: > > > > ? ? ? ? sol1 = -1 * b + (sqrt(b**2 - 4*a*c)) / 2*a > > > > ? ? ? ? sol2 = -1 * b - (sqrt(b**2 - 4*a*c)) / 2*a > > > > ? ? ? ? return (sol1, sol2) > > > > > # execute > > > > print solver(a,b,c) > > > > > Thanks to everyone who helped... > > > > This really expanded my knowledge on some of the mathematical > > > > functions in Python. > > > > UPDATE: > > > ' > > > > #import > > > from math import sqrt > > > > # collect data > > > a = float(raw_input('Type a value: ')) > > > b = float(raw_input('Type b value: ')) > > > c = float(raw_input('Type c value: ')) > > > > # create solver > > > def solver(a,b,c): > > > ? ? if b**2 - 4*a*c < 0: > > > ? ? ? ? return 'No real solution.' > > > ? ? else: > > > ? ? ? ? sol1 = (-1 * b + (sqrt(b**2 - 4*a*c))) / 2*a > > > ? ? ? ? sol2 = (-1 * b - (sqrt(b**2 - 4*a*c))) / 2*a > > > ? ? ? ? return (sol1, sol2) > > > > # execute > > > print solver(a,b,c) > > > You need to put your denominator, 2*a, in parens. The way it stands, > > you are dividing by 2, then multiplying by a. That's not what you > > want. > > > Also, for better style, I suggest you compute the discriminanat once > > and store it for reuse rather than repeating the expression three > > times.- Hide quoted text - > > > - Show quoted text - > > I see what you mean on the denominator and discriminant. Ill do that.- Hide quoted text - > > - Show quoted text - UPDATE: #import from math import sqrt # collect data a = float(raw_input('Type a value: ')) b = float(raw_input('Type b value: ')) c = float(raw_input('Type c value: ')) # find discriminant disc = b**2 - 4*a*c # create solver def solver(a,b,c): if disc < 0: return 'No real solution.' else: sol1 = (-1 * b + (sqrt(disc))) / (2*a) sol2 = (-1 * b - (sqrt(disc))) / (2*a) return (sol1, sol2) # execute print solver(a,b,c) From lists at cheimes.de Wed Dec 17 12:59:03 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 17 Dec 2008 18:59:03 +0100 Subject: getting object instead of string from dir() In-Reply-To: References: Message-ID: Rominsky schrieb: > I am trying to use dir to generate a list of methods, variables, etc. > I would like to be able to go through the list and seperate the > objects by type using the type() command, but the dir command returns > a list of strings. When I ask for the type of an element, the answer > is always string. How do I point at the variables themselves. A > quick example is: > > a = 5 > b = 2.0 > c = 'c' > > lst = dir() > > for el in lst: > print type(el) for name, obj in vars().iteritems(): print name, obj Christian From nad at acm.org Mon Dec 29 13:46:11 2008 From: nad at acm.org (Ned Deily) Date: Mon, 29 Dec 2008 10:46:11 -0800 Subject: SQL, lite lite lite References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> Message-ID: In article , Philip Semanchuk wrote: > On Dec 29, 2008, at 1:06 PM, Aaron Brady wrote: > > I don't think relational data can be read and written very easily in > > Python. There are some options, such as 'sqllite3', but they are not > > easy. 'sqllite3' statements are valid SQL expressions, which afford > > the entire power of SQL, but contrary to its name, it is not that > > 'lite'. To me, 'lite' is something you could learn (even make!) in an > > afternoon, not a semester; something the size of an ActiveState > > recipe, or a little bigger, maybe a file or two. > [...] > After a look at the syntax you're proposing, I wonder how you feel it > differs from ORMs like SQLAlchemy (for instance). ... and Elixir, a declarative layer on top of SQLAlchemy: -- Ned Deily, nad at acm.org From Edvin.Fuglebakk at ii.uib.no Thu Dec 4 08:00:24 2008 From: Edvin.Fuglebakk at ii.uib.no (Edvin Fuglebakk) Date: Thu, 04 Dec 2008 14:00:24 +0100 Subject: funny generator behaviour Message-ID: <4937D468.1030201@ii.uib.no> I have written a generator that puzzles me: The generator is supposed to create ordered selections of a set of objects. repetition of objects is allowed and the selections should be of a size determined by a pramter to the generator. Now, if I try to accummulate the generated selections into a list I get some peculiar behaviour that I hope maybe some of you can help me understand: Help much appreciated -Edvin #straightforward acumulation. Does not give the expected result >>> d=[] >>> for f in orderedCombinations([1,2],3): ... d.append(f) ... >>> d [[1], [2], [1], [2], [1], [2], [1], [2]] #accumulating shallow copies of the genereated combinations works: >>> d=[] >>> for f in orderedCombinations([1,2],3): ... d.append(f[:]) ... >>> d [[1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 2, 2], [2, 1, 1], [2, 1, 2], [2, 2, 1], [2, 2, 2]] #The generator: def orderedCombinations(pool, k): """ Generator yielding ordered selections of size k with repetition from pool. """ if k == 1: for m in pool: yield [m] if k > 1: for m in pool: for combo in orderedCombinations(pool, k-1): #insert and pop to avoid copying entire list combo.insert(0,m) yield combo combo.pop(0) From marco at sferacarta.com Fri Dec 12 10:51:15 2008 From: marco at sferacarta.com (Marco Mariani) Date: Fri, 12 Dec 2008 16:51:15 +0100 Subject: Removing None objects from a sequence In-Reply-To: References: <01524eee$0$20617$c3e8da3@news.astraweb.com> Message-ID: Filip Gruszczy?ski wrote: > I am not doing it, because I need it. I can as well use "if not elem > is None", I suggest "if elem is not None", which is not quite the same. If you slip such an error in a post, I suggest to practice some time writing correct code before having one-liner contests with your perl-loving friends :) From bdesth.quelquechose at free.quelquepart.fr Sat Dec 6 09:54:44 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 06 Dec 2008 15:54:44 +0100 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: <493a9fed$0$18973$426a34cc@news.free.fr> Daniel Fetchinson a ?crit : > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html > > The proposal is to allow this: > > class C: > def self.method( arg ): > self.value = arg > return self.value > > instead of this: > > class C: > def method( self, arg ): > self.value = arg > return self.value > (snip) > I'd like this new way of defining methods, what do you guys think? -1 As far as I'm concerned, it doesn't add anything to the language, nor doesn't save any typing, so I just don't see the point. And having it co-existing with the normal syntax will only add more confusion. NB : FWIW, I would eventually have voted -0 if it had been proposed for Python 3, and as a _replacement_ (not _alternative_) to the current syntax. But Python 3 is now released, so... From mdgeorge at cs.cornell.edu Wed Dec 3 16:12:54 2008 From: mdgeorge at cs.cornell.edu (Michael George) Date: Wed, 3 Dec 2008 16:12:54 -0500 Subject: building an extension module with autotools? Message-ID: <4936F656.40104@cs.cornell.edu> Hello, (Please CC me in replies, as I am off-list) I'm building an application (a game) in python, with a single C module containing some performance-critical code. I'm trying to figure out the best way to set it up to build. Distutils seems to be designed only for building and distributing code that lives in site-packages. I'd prefer not to install it in the global site-packages, but rather group all of the files together. I've tried using automake, however I'm worried about libtool not getting the options right while building my module. It seems to me like the ideal frankenstein monster would be for automake to invoke distutils to do the actual building. However I'm relatively new to both autotools and distutils, so getting this rigged up has been a bit of a challenge. Can anybody point me to a good example of something like this or give me any pointers? Thanks! --Mike From steve at REMOVE-THIS-cybersource.com.au Wed Dec 17 20:46:18 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Dec 2008 01:46:18 GMT Subject: The rule of literal string References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> <_PmdnU59w62vGtTUnZ2dnUVZ_hSdnZ2d@pdx.net> <34028b73-7807-4e88-80bc-fe31a7b1a2a0@i20g2000prf.googlegroups.com> Message-ID: <0159a2cc$0$20656$c3e8da3@news.astraweb.com> On Wed, 17 Dec 2008 15:25:41 -0800, Chris Rebert wrote: > 2008/12/17 Li Han : >> On 12?18?, ??7?12?, Scott David Daniels wrote: >> Scott wrote: >>> Try: print repr(repr("'")) >>> that might enlighten you. >> >> I found that print( repr( repr( arbitarystring ) ) ) == repr ( >> arbitarystring ) > > As I stated previously, the key rule is: > > eval(repr(something)) == something > > That is, repr() gives a string of Python code that, when evaluated, > results in what you gave to repr(). That is not true in general. >>> from urllib2 import HTTPError >>> h = HTTPError("404 quoth the Raven", None, None, None, None) >>> eval(repr(h)) Traceback (most recent call last): File "", line 1, in File "", line 1, in TypeError: __init__() takes exactly 6 arguments (1 given) Even for built-ins, it's not always true: >>> eval(repr(float('inf'))) Traceback (most recent call last): File "", line 1, in File "", line 1, in NameError: name 'inf' is not defined In other words, there is no guarantee that repr(obj) will round-trip correctly, or at all. It's a Nice To Have, and it will often work, but it's not something you should rely on for arbitrary objects. However, I believe it is true for strings. -- Steven From stefan_ml at behnel.de Thu Dec 18 01:43:21 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 18 Dec 2008 07:43:21 +0100 Subject: C API and memory allocation In-Reply-To: References: Message-ID: <4949f109$0$31329$9b4e6d93@newsspool4.arcor-online.net> Floris Bruynooghe wrote: > I'm slightly confused about some memory allocations in the C API. If you want to reduce the number of things you have to get your head around, learn Cython instead of the raw C-API. It's basically Python, does all the reference counting for you and also reduces the amount of memory handling you have to care about. http://cython.org/ Stefan From stef.mientki at gmail.com Wed Dec 3 10:52:31 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 3 Dec 2008 16:52:31 +0100 Subject: Debugging a Python Program that Hangs In-Reply-To: References: Message-ID: <3dfd60f20812030752p156d307enb3ddd95c29e8eb1f@mail.gmail.com> check winpdb / rpdb2, cheers, Stef On 12/3/08, alex23 wrote: > On Dec 3, 2:19 am, Kevin D. Smith wrote: >> I have a fairly large python program that, when a certain combination >> of options is used, hangs. I have no idea where it is hanging, so >> simply putting in print statements to locate the spot would be quite >> difficult. Unfortunately, ctrl-C'ing the program doesn't print a >> traceback either. Looking through the python debugger documentation, I >> don't see how to run a python program and interactively stopping it >> while it is running. Is there a way to stop within a running python >> program to see where it is getting hung up? > > Hey Kevin, long time fan of your films! (I bet you get that a lot...) > > The trace module might help you identify where it's getting caught up: > > http://www.python.org/doc/2.5.2/lib/trace-cli.html > > -- > http://mail.python.org/mailman/listinfo/python-list > From skip at pobox.com Wed Dec 24 12:10:46 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 24 Dec 2008 11:10:46 -0600 Subject: Spam??? In-Reply-To: References: Message-ID: <18770.27926.482932.23654@montanaro-dyndns-org.local> Alvin> What's with all the spam on the list? Alvin> I humbly request that recaptcha or some other sort Alvin> of captcha be implemented on the registration page. Known issue. The spam filters are currently not applied to messages gatewayed to the mailing list from Usenet. I have been working on a solution as I have time, but it's not there yet. Even if/when the spam filtering on the list gets better you should run your own spam filter anyway. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From robert.kern at gmail.com Mon Dec 22 18:21:23 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 22 Dec 2008 17:21:23 -0600 Subject: 64-bit / 128-bit data element type for array? In-Reply-To: References: <880c8478-8b40-40e0-8597-aef960612f09@s9g2000prg.googlegroups.com> Message-ID: akineko wrote: > Hello Robert, > >> Is that actually a 2s-complement 128-bit unsigned integer, or is it just a >> 128-bit-long chunk of data? > > That is a good question. > A 128-bit data can be anything. > A 128-bit data can be an instrution code (VLIW machines use such wide > instruction). A 128-bit can be a packed ascill (16 chrs). > A 128-bit can be a descriptor (a structure of various fields). > It is probably safe to say that only unsigned 128-bit is required. > (I cannot think of any situations where signed 128-bit is necessary) Ah, good. numpy lets you construct your own data types from the primitives. Since you don't actually need uint128 arithmetic, you don't need a uint128 primitive. You can just use dtype('V16') (meaning "void, 16 bytes long") for the "anything" and "instruction codes" and possible as an intermediate format. Byteswapping will work just fine. Use can use dtype('S16') for the ASCII. If the structure can be described by bytes, then the structured dtypes will work just fine. Unfortunately, we don't support bit-fields. If you need bit-field support, you may want to take a look at Construct. Actually, you may want to look at Construct anyways. http://construct.wikispaces.com/ -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From fakeaddress at nowhere.org Mon Dec 1 08:53:51 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 01 Dec 2008 05:53:51 -0800 Subject: unicode and hashlib In-Reply-To: References: <8af54b5f-d21b-4794-9bce-afc96ea4db74@j11g2000yqg.googlegroups.com> Message-ID: Jeff H wrote: > [...] So once I have character strings transformed > internally to unicode objects, I should encode them in 'utf-8' before > attempting to do things that guess at the proper way to encode them > for further processing.(i.e. hashlib) It looks like hashlib in Python 3 will not even attempt to digest a unicode object. Trying to hash 'abcdefg' in in Python 3.0rc3 I get: TypeError: object supporting the buffer API required I think that's good behavior, except that the error message is likely to send beginners to look up the obscure buffer interface before they find they just need mystring.decode('utf8') or bytes(mystring, 'utf8'). >>>> a='Andr?' >>>> b=unicode(a,'cp1252') >>>> b > u'Andr\xc3\xa9' >>>> hashlib.md5(b.encode('utf-8')).hexdigest() > 'b4e5418a36bc4badfc47deb657a2b50c' Incidentally, MD5 has fallen and SHA-1 is falling. Python's hashlib also includes the stronger SHA-2 family. -- --Bryan From traef at ebasedsecurity.com Sun Dec 21 20:36:33 2008 From: traef at ebasedsecurity.com (Thomas Raef) Date: Sun, 21 Dec 2008 19:36:33 -0600 Subject: Threads, forks, multiplexing - oh my Message-ID: I have a program that was created by someone else and it does it's job beautifully. I now want to run multiple instances of this program on a client, after receiving the command line and args from a broker, dispatcher, whatever you want to call it. This dispatcher will listen for a connection from a client and then pass this client the command line to run this python program. The client will receive the command line, run the python program and then go get another one to run. It might run this program 4 times simultaneously (or so it will seem). I've read where forks will run programs but they replace the calling program - is that correct? Am I reading that right? If so, then my client program will have to use forks so it can run a program. Then are threads to run functions and not full-fledged programs? When, if ever, would I want to look at implementing multiplexing? Please help me clarify and if possible give me some direction for this. Thank you in advance. Thomas J. Raef www.ebasedsecurity.com www.wewatchyourwebsite.com "We Watch Your Website because - you don't" -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp at rebertia.com Mon Dec 22 22:43:46 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 22 Dec 2008 19:43:46 -0800 Subject: iterating initalizations In-Reply-To: References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> Message-ID: <47c890dc0812221943g44bd7222t8c09c088d87e77df@mail.gmail.com> On Mon, Dec 22, 2008 at 7:32 PM, Aaron Stepp wrote: > > Thanks for the help so far, I think I'm starting to get a hang of the > syntax. > > I think I need to state my goal more clearly. > > Instead of writing a long list of initializations like so: > > A = [ ] > B = [ ] > ... > Y = [ ] > Z = [ ] > > I'd like to save space by more elegantly turning this into a loop. If I > need to just write it out, I guess that's ok... but it would be much > cleaner. I'm a composer, not a programmer, so some of this is quite above > me. > So, are these variables supposed to be module-level, or attributes of class pitchAndRhythm, or what? Also, are you going to use the variables normally or are you going to need "variable variables" (e.g. like $$var in PHP, which gives the value of the variable with the name of the string stored in $var)? Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From clp at rebertia.com Mon Dec 8 01:25:12 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 7 Dec 2008 22:25:12 -0800 Subject: A question about reference in Python. In-Reply-To: References: <493CB003.3080209@gmail.com> <47c890dc0812072213q20cb415fjbd4c80e7af7a7ef5@mail.gmail.com> Message-ID: <47c890dc0812072225u7cde16eh9ba69a2f4cdacd16@mail.gmail.com> On Sun, Dec 7, 2008 at 10:17 PM, James Mills wrote: > On Mon, Dec 8, 2008 at 4:13 PM, Chris Rebert wrote: >> The following three lines serve no purpose and can only lead to confusion: >>> value = None >>> prev = None >>> next = None > > You are absolutely right :) > > Updated code: > > > cheers > Jaems > > PS: Sorry Chris :) No apology necessary of course, i just didn't want the newbie OP to pick up any bad Python coding habits. Apologies that I might have phrased my criticism a bit harshly. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > -- > -- > -- "Problems are solved by method" > From jon at ffconsultancy.com Mon Dec 8 08:10:32 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Mon, 08 Dec 2008 13:10:32 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> Message-ID: Xah Lee wrote: > For those interested in this Mathematica problem, i've now cleaned up > the essay with additional comments here: > > ? A Mathematica Optimization Problem > http://xahlee.org/UnixResource_dir/writ/Mathematica_optimization.html In that article you say: > Further, if Intersect is made to take a flat sequence of argument as > in ?Intersect[o_, d_, lambda_, n_, c_, r_, s_]?, then pattern matching can > be avoided by making it into a pure function ?Function?. And when it is > a ?Function?, then Intersect or part of it may be compiled with Compile. > When the code is compiled, the speed should be a order of magnitude > faster. That is incorrect. Mathematica's Compile function cannot handle recursive functions like Intersect. For example: In[1]:= Compile[{n_, _Integer}, If[# == 0, 1, #0[[# n - 1]] #1] &[n]] During evaluation of In[1]:= Compile::fun: Compilation of (If[#1==0,1,#0[[#1 n-1]] #1]&)[Compile`FunctionVariable$435] cannot proceed. It is not possible to compile pure functions with arguments that represent the function itself. >> -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From stefan_ml at behnel.de Fri Dec 19 04:46:22 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 19 Dec 2008 10:46:22 +0100 Subject: C API and memory allocation In-Reply-To: References: <59352942-e976-4ef4-bc40-c8953df0a792@c36g2000prc.googlegroups.com> <0d35b640-71ad-4cde-8869-74878b2f3981@r36g2000prf.googlegroups.com> <494a55fb$0$31873$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <494b6d6e$0$31861$9b4e6d93@newsspool3.arcor-online.net> Aaron Brady wrote: >>> Otherwise you can't know its length or change its reference count. >> The internal representation of Python byte strings is 0 terminated, so >> strlen() will work. > > As MRAB said, Python strings can contain null bytes, Sure, they can. Most byte strings I've seen didn't, though. And if you know that they don't contain any null bytes (UTF-8 serialised XML, for example, or ASCII encoded text, or ...), 's' is just fine. If you need content *and* length, use 's#'. Matter of use case, as usual. Stefan From bthayre at physics.ucsd.edu Mon Dec 8 13:13:20 2008 From: bthayre at physics.ucsd.edu (Robocop) Date: Mon, 8 Dec 2008 10:13:20 -0800 (PST) Subject: Text parsing via regex Message-ID: I'm having a little text parsing problem that i think would be really quick to troubleshoot for someone more versed in python and Regexes. I need to write a simple script that parses some arbitrarily long string every 50 characters, and does not parse text in the middle of words (but ultimately every parsed string should be 50 characters, so adding in white spaces is necessary). So i immediately came up with something along the lines of: string = "a bunch of nonsense that could be really long, or really short depending on the situation" r = re.compile(r".{50}") m = r.match(string) then i started to realize that i didn't know how to do exactly what i wanted. At this point i wanted to find a way to simply use something like: parsed_1, parsed_2,...parsed_n = m.groups() However i'm having several problems. I know that playskool regular expression i wrote above will only parse every 50 characters, and will blindly cut words in half if the parsed string doesn't end with a whitespace. I'm relatively new to regexes and i don't know how to have it take that into account, or even what type of logic i would need to fill in the extra whitespaces to make the string the proper length when avoiding cutting words up. So that's problem #1. Problem #2 is that because the string is of arbitrary length, i never know how many parsed strings i'll have, and thus do not immediately know how many variables need to be created to accompany them. It's easy enough with each pass of the function to find how many i will have by doing: mag = len(string) upper_lim = mag/50 + 1 But i'm not sure how to declare and set them to my parsed strings. Now problem #1 isn't as pressing, i can technically get away with cutting up the words, i'd just prefer not to. The most pressing problem right now is #2. Any help, or suggestions would be great, anything to get me thinking differently is helpful. From rt8396 at gmail.com Tue Dec 23 10:55:32 2008 From: rt8396 at gmail.com (r) Date: Tue, 23 Dec 2008 07:55:32 -0800 (PST) Subject: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> <90f06b27-39da-4f1a-a878-f3972e942d57@s24g2000vbp.googlegroups.com> Message-ID: <62caf93b-0455-4450-9895-8a9d9554f75e@r32g2000vba.googlegroups.com> On Dec 22, 11:12?pm, ajaksu wrote: > On Dec 22, 9:24?pm, r wrote: > > > You know what i hate more than a troll, a spineless jellyfish who goes > > around rating peoples post with one star. You are the lowest form of > > life. You are the same type of person who would key someones car in > > the parking lot. You do not have the balls to face you enemy. > > > If who made a rating were visible, then i would have respect for you, > > but since you lurk in the shadows, you are scum. Come out and face me > > if you dare! > > > I never have rated a post UNLESS i rate it with 5 stars, WHY, you ask, > > Because my balls are so big i walk around bow-legged! F'in ?Cowards! > > That would be me, for at least a dozen of your posts. Glad to know it > was more effective than telling you to shut up or calm down. > > Cnidaria-ly y'rs, > Daniel Well that shows that even lads with tiny nads can be brave, any of the other trolls want to expose them selfs? From mail at johnohagan.com Sat Dec 20 10:27:50 2008 From: mail at johnohagan.com (John O'Hagan) Date: Sat, 20 Dec 2008 15:27:50 +0000 Subject: Namespaces, multiple assignments, and exec() In-Reply-To: <015c5ab8$0$20656$c3e8da3@news.astraweb.com> References: <200812200234.33852.research@johnohagan.com> <015c5ab8$0$20656$c3e8da3@news.astraweb.com> Message-ID: <200812201527.51146.mail@johnohagan.com> On Sat, 20 Dec 2008, Steven D'Aprano wrote: > On Sat, 20 Dec 2008 02:53:16 +0000, MRAB wrote: > > If you're sure you want to use the current namespace then: > > > > for name in namelist: > > vars()[name] = func(name, args) > > Doesn't work inside a function: > >>> def parrot(): > > ... for name in ['A', 'B', 'C']: > ... vars()[name] = ord(name) > ... print vars() > ... print A > ... > > >>> parrot() > > {'A': 65, 'C': 67, 'B': 66, 'name': 'C'} > Traceback (most recent call last): > File "", line 1, in > File "", line 5, in parrot > NameError: global name 'A' is not defined Historical note: I found an old post which stated that this used to work in a function which invoked exec(): http://mail.python.org/pipermail/python-list/2000-September/050840.html but I tried it in 2.5 and it doesn't any longer. Regards, John From andrei.avk at gmail.com Sat Dec 6 15:39:17 2008 From: andrei.avk at gmail.com (Rainy) Date: Sat, 6 Dec 2008 12:39:17 -0800 (PST) Subject: Select, interrupted system call, log rotation? Message-ID: <2b8928dd-4d0c-4e90-ba1e-1c68068c73d1@t3g2000yqa.googlegroups.com> I got an interrupted system call exception in select and I don't know what could have caused it. Here's the error: select.select(inputs, [], [], 9) error: (4, 'Interrupted system call') Caught an exception, shutting down... It's py2.3, on mach architecture. I'm trying to figure out what caused it, and the only idea I have so far is that it could be that I have python's logging system log rotation thing running and I think I've seen a reference somewhere that it uses SIGALRM when log file reaches set size to stop and switch the files. The program was running for about a week without any problem and then I got this exception and after I restarted it it's been running for a few days and I only got the exception once in all that time. Am I going in a completely wrong direction here? I'm thinking of just putting select in try: except: , is that a good idea here? I don't understand signals all that well. Thanks. From bj_666 at gmx.net Tue Dec 9 17:55:02 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 9 Dec 2008 22:55:02 GMT Subject: Is 3.0 worth breaking backward compatibility? References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> Message-ID: <6q8ba6Fb9jsuU1@mid.uni-berlin.de> On Tue, 09 Dec 2008 20:56:19 +0000, Lie Ryan wrote: > Interestingly, many linux _distro_ also inhibit this quick version > number change. Fedora 10, Ubuntu is 2 years old, version 8 (they start > from version 6 not 1). Ubuntu's version numbers don't follow the usual rules but are year and month of release. So this year's releases have "version" 8 and the latest is from october so it is 8.10. Ciao, Marc 'BlackJack' Rintsch From manu3d at gmail.com Sat Dec 13 10:06:48 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Sat, 13 Dec 2008 07:06:48 -0800 (PST) Subject: Bidirectional Networking References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <6qeht0Fc3541U1@mid.individual.net> <782258db-2bdc-45a7-8d8f-7a036d574985@t26g2000prh.googlegroups.com> Message-ID: <8adf1135-ca47-4bed-b490-ab8ae8ccb89f@i18g2000prf.googlegroups.com> On Dec 13, 12:08?am, "James Mills" wrote: > Just as a matter of completeness for my own suggestion, here > is my implementation of your code (using circuits): It's longer! But I bet is a little bit more resilient against all sorts of problems that arise while using network connections. Well, thank you for that. The code I posted in this thread it was just a test to understand how it all works and how it all works with python out of the box. When I get to write the actual application I might end up using circuits instead! Thank you again! Manu From ivan.illarionov at gmail.com Tue Dec 16 16:22:38 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 16 Dec 2008 13:22:38 -0800 (PST) Subject: How to modify a program while it's running? References: Message-ID: <2a748fce-1931-4202-814d-3223fa31e85f@u18g2000pro.googlegroups.com> On Dec 16, 11:25?pm, Joe Strout wrote: > Here's my situation: I'm making an AIM bot, but the AIM server will ? > get annoyed if you log in too frequently (and then lock you out for a ? > while). ?So my usual build-a-little, test-a-little methodology doesn't ? > work too well. > > So I'd like to restructure my app so that it can stay running and stay ? > logged in, yet I can still update and reload at least most of the ? > code. ?But I'm not sure what's the best way to do this. ?Should I move ? > the reloadable code into its own module, and then when I give my bot a ? > "reload" command, have it call reload on that module? ?Will that work, ? > and is there a better way? > > Thanks, > - Joe Take a look at: http://code.djangoproject.com/browser/django/trunk/django/utils/autoreload.py From theiviaxx at gmail.com Wed Dec 10 20:19:01 2008 From: theiviaxx at gmail.com (TheIvIaxx) Date: Wed, 10 Dec 2008 17:19:01 -0800 (PST) Subject: lxml.etree error: xmlSchematronSetValidStructuredErrors References: <33c18d97-598e-4c8c-ac1d-b7c839862eda@a26g2000prf.googlegroups.com> Message-ID: nvm, i got it working. Checking the docs for libxsltmod i was given the tip to add: export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib From saju.pillai at gmail.com Wed Dec 17 01:42:58 2008 From: saju.pillai at gmail.com (Saju Pillai) Date: Tue, 16 Dec 2008 22:42:58 -0800 (PST) Subject: Can anyone suggest a good HTTP/1.1 web client? References: Message-ID: <03019813-2c1c-4489-b370-7e2dbb7f35ce@e1g2000pra.googlegroups.com> On Dec 17, 1:18?am, Kottiyath wrote: > Hi all, > ? ? I have to connect to a secure website every second to get the data > and then post to it. I have been investigating on many web clients in > python, but nothing fits the bill properly. > ? ? The ones I tried implementing are: > ? ? 1. httplib based - I created myself. (I cannot use urllib2 since I > have to transfer files, and urllib2 doesnt have multipart content-type > support) > ? ? 2. Twisted web client. > ? ? I also looked at mechanize etc too. > > ? ? The problems I face are - > ? ? 1. I liked twisted a lot, but when I implemented it, I found that > client support is there only for twisted.web and not twisted.web2. > Since I connect to the same website every time, I would like to have > persistent connections and since twisted.web is HTTP/1.0, persistent > connection support is not yet there. Without persistent connections, I > would have to have TCP connection handshake everytime and it is taking > too much time. > ? ? 2. Since I connect to the website every second, I have to have > many connections running at the same time. I am worried that creating > threads for each connection is going to be a big problem (esp if the > server response is slow), since the processor will get swamped - > especially since there are many other activities going on in the > machine. > ? ?3. I would also like to pipe line the requests - esp if the > response is slow. > > ? ?Other requirements: > ? ?1. HTTPS Support > ? ?2. Connection through proxy. You could take a look at pycurl - python bindings for libcurl. http://pycurl.sourceforge.net/ srp > > ? ?Is there any good web client which I can use straight up? Or would > I have to implement the whole thing myself? It looks like a big beast > and I was wondering whether python provides it straight up. > > Regards > K From jonas.esp at googlemail.com Sun Dec 21 07:21:30 2008 From: jonas.esp at googlemail.com (Kless) Date: Sun, 21 Dec 2008 04:21:30 -0800 (PST) Subject: HMAC with RIPEMD-160 Message-ID: Is there any way of use HMAC with RIPEMD-160? Since that to create a ripemd-160 hash there is to use: h = hashlib.new('ripemd160') it looks that isn't possible For HMAC-SHA256 would be: --------- import hashlib import hmac hm = hmac.new('key', msg='message', digestmod=hashlib.sha256) --------- http://docs.python.org/library/hashlib.html http://docs.python.org/library/hmac.html From lance.ellinghaus at eds.com Thu Dec 25 15:15:48 2008 From: lance.ellinghaus at eds.com (Ellinghaus, Lance) Date: Thu, 25 Dec 2008 15:15:48 -0500 Subject: odfpy examples Message-ID: <752A61D5C34D41478E638FC92AF9051B035638BB@usahm207.amer.corp.eds.com> Has anyone created any complex spreadsheets using odfpy? The samples that come with odfpy are pretty simple and I need some examples of more complex spreadsheets. Thank you, lance -------------- next part -------------- An HTML attachment was scrubbed... URL: From bthayre at physics.ucsd.edu Thu Dec 11 18:17:06 2008 From: bthayre at physics.ucsd.edu (Robocop) Date: Thu, 11 Dec 2008 15:17:06 -0800 (PST) Subject: list organization question References: Message-ID: <79587def-2112-48dd-bab2-95427a2dca8b@y1g2000pra.googlegroups.com> I'm currently trying something along the lines of a sort.compare, but as i'm never sure how many mini-lists i'll end up with, i'm not sure how exactly to begin. Maybe something like a C vector, i.e. a list of pointers to other lists? Or more specifically, compare dates in my list, push that into some empty dates[], then do something along the lines of for looping over dates to create subset lists, and nesting some more compares within these lists to further sort the data by id. Sound crazy or plausible? From lists at cheimes.de Fri Dec 5 16:39:32 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 05 Dec 2008 22:39:32 +0100 Subject: slow Python 3.0 write performance? In-Reply-To: <4939961A.8080205@mrabarnett.plus.com> References: <4939961A.8080205@mrabarnett.plus.com> Message-ID: MRAB wrote: > Does pysco with with Python 3.0 (the homepage says 2.5)? If it does then > that might help! :-) No, it won't help. From info at wingware.com Mon Dec 15 13:04:26 2008 From: info at wingware.com (Wingware) Date: Mon, 15 Dec 2008 13:04:26 -0500 Subject: Wing IDE 3.1.6 released Message-ID: <49469C2A.2050202@wingware.com> Hi, Wingware has released version 3.1.6 of Wing IDE, a bugfix release for all three product levels of Wing IDE. *Release Highlights* This release includes the following: * Added previously missing support for x64 Python on Windows * Avoid auto-starting batch searches when a project is opened * Several vi mode fixes * Added 'watch' item to editor context menu * Recognize type of 'x' in 'from x import y' * Allow debugger to start even if replacing sys.stdin fails * Store list of test files in shared project file (*.wpr) * About 16 other bug fixes: see the change log for details: http://wingware.com/pub/wingide/3.1.6/CHANGELOG.txt *Downloads* Wing IDE Professional and Wing IDE Personal are commercial software and require a license to run. A free trial license can be obtained directly from the product when launched. Wing IDE Pro 3.1.6 http://wingware.com/downloads/wingide/3.1 Wing IDE Personal 3.1.6 http://wingware.com/downloads/wingide-personal/3.1 Wing IDE 101 3.1.6 http://wingware.com/downloads/wingide-101/3.1 *About Wing IDE* Wing IDE is an integrated development environment for the Python programming language. It provides powerful debugging, editing, code intelligence, testing, and search capabilities that reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. Wing IDE is available in three product levels: Wing IDE Professional is the full-featured Python IDE, Wing IDE Personal offers a reduced feature set at a low price, and Wing IDE 101 is a free simplified version designed for teaching entry level programming courses with Python. System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit). Wing IDE 3.1 supports Python versions 2.0.x through 2.5.x. *New Features in Wing 3.1* This release adds the following features not found in Wing 3.0.x: * Support for zip archives * Support for pkg_resources name spaces and eggs * Support for doctest and nose style unit tests (*) * Scan for sys.path changes such as those used in buildout * How-To and support for Google App Engine * Inline context appropriate templates/snippets integrated with autocompleter (*) * Word list driven auto-completion in non-Python files (**) * Quick navigation to files and symbols by typing a fragment (**) * Improved support for Stackless Python * Preference to strip trailing white space on save * Display gi_running and gi_frame for generators * Improved code analysis for Python 2.5 * Other minor features and bug fixes not found in Wing 3.0.x (*)'d items are available in Wing IDE Professional only. (**)'d items are available in Wing IDE Personal or Professional only. Please see the change log for a detailed list of changes: http://wingware.com/pub/wingide/3.1.6/CHANGELOG.txt *Purchasing and Upgrading* Wing 3.1 is a free upgrade for all Wing IDE 3.0 and 3.1 users. Any 2.x license sold after May 2nd 2006 is free to upgrade; others cost 1/2 the normal price to upgrade. Upgrade a 2.x license: https://wingware.com/store/upgrade Purchase a 3.x license: https://wingware.com/store/purchase -- The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com From roy at panix.com Mon Dec 8 10:28:36 2008 From: roy at panix.com (Roy Smith) Date: Mon, 08 Dec 2008 10:28:36 -0500 Subject: Learning Python now coming from Perl References: Message-ID: In article , Nick Craig-Wood wrote: > My favourite mistake when I made the transition was calling methods > without parentheses. In perl it is common to call methods without > parentheses - in python this does absolutely nothing! pychecker does > warn about it though. > > perl -> $object->method > python -> object.method() On the other hand, leaving out the parens returns the function itself, which you can then call later. I've often used this to create data-driven logic. For example, I'm currently working on some code that marshals objects of various types to a wire protocol. I've got something like: encoders = { SM_INT: write_int, SM_SHORT: write_short, SM_FLOAT: write_float, # and so on } class AnyVal: def __init__(self, type, value): self.type = type self.value = value def write_anyval(any): encoders[any.type](any.value) The fact that functions are objects which can be assigned and stored in containers makes this easy to do. From bj_666 at gmx.net Fri Dec 19 08:32:31 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Dec 2008 13:32:31 GMT Subject: How to parsing a sequence of integers References: Message-ID: <6r1m3eFfb5kpU2@mid.uni-berlin.de> On Fri, 19 Dec 2008 21:20:48 +0800, Steven Woody wrote: > Hi, > > I am a newbie and is reading the python book. Could anyone tell me, how > to parsing the following string > "123 100 12 37 ..." > into a list of integers on which I can then apply max()/min()? In [376]: '123 100 12 37'.split() Out[376]: ['123', '100', '12', '37'] In [377]: map(int, '123 100 12 37'.split()) Out[377]: [123, 100, 12, 37] In [378]: max(map(int, '123 100 12 37'.split())) Out[378]: 123 > In additional to max/min, is there something like average()? No, but it's easy to implement with `sum()`, `len()` and ``/``. Ciao, Marc 'BlackJack' Rintsch From jstroud at mbi.ucla.edu Sun Dec 7 04:11:25 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 07 Dec 2008 01:11:25 -0800 Subject: can graphs be made in python as we make in java In-Reply-To: <89ff42d1-6a4c-4d45-a646-238b43e7e8de@s9g2000prm.googlegroups.com> References: <89ff42d1-6a4c-4d45-a646-238b43e7e8de@s9g2000prm.googlegroups.com> Message-ID: suku wrote: > HI folks... > > i need some suggestion on making graphs. Will this be possible > with normal python setup file or do i need to download add ons for > that.. > > help me out I like pychart. It has the advantage of being pure python and makes very nice looking plots. You might also check out matplotlib if you are into heavyweight plotting and interactive application development. James From walterbyrd at iname.com Sat Dec 20 10:19:06 2008 From: walterbyrd at iname.com (walterbyrd) Date: Sat, 20 Dec 2008 07:19:06 -0800 (PST) Subject: WAGs on when django will use Python 3.0? Message-ID: <7f6a70f9-4b97-44f9-86fe-db84ae733077@g1g2000pra.googlegroups.com> Will Django be primarily using Python 3.0 one year from now? Two years from now? Any WAGs? From argus.max at googlemail.com Sun Dec 14 12:43:01 2008 From: argus.max at googlemail.com (Max Argus) Date: Sun, 14 Dec 2008 18:43:01 +0100 Subject: Deepcopying slice objects Message-ID: I stumbled across a thread about that suggests fixing deepcopy to let it copy slice objects. ( http://mail.python.org/pipermail/python-list/2006-August/398206.html). I expected this to work and don't see any reason why it shouldn't in case there is a good reason why it dosen't work can someone please explain it. Max Argus -------------- next part -------------- An HTML attachment was scrubbed... URL: From pacsciadmin at gmail.com Mon Dec 15 21:49:46 2008 From: pacsciadmin at gmail.com (pacsciadmin at gmail.com) Date: Mon, 15 Dec 2008 18:49:46 -0800 (PST) Subject: Copying files in directory Message-ID: <2a815b7d-f01f-4666-bfc6-e9c43a75019b@t3g2000yqa.googlegroups.com> I'm writing a project management system, and I need the ability to accept a directory name and move its contents to another directory. Can someone give me a code sample that will handle this? I can't find any "copying" functions in os or os.path. Regards, LeafStorm From ldo at geek-central.gen.new_zealand Sat Dec 6 02:32:13 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 06 Dec 2008 20:32:13 +1300 Subject: Don't you just love writing this sort of thing :) References: Message-ID: In message , Istvan Albert wrote: > Originally, like many others here I said YIKES! but on a second read, > it is not that bad. It actually grows on you. > > After looking at it one more time I found it neat, very concise > without being unreadable. The key thing is, it's functional, not procedural. Instead of a sequence of statements performing actions, it uses expressions that compute values. Here's another one (from ): def MapRect(SrcRect, DstRect) : """returns a Matrix that does appropriate scaling and translation to map the corners of SrcRect to DstRect.""" return \ ( Matrix.translation(- SrcRect.topleft()) * Matrix.scaling(DstRect.dimensions() / SrcRect.dimensions()) * Matrix.translation(DstRect.topleft()) ) #end MapRect From KDawg44 at gmail.com Tue Dec 16 16:26:56 2008 From: KDawg44 at gmail.com (KDawg44) Date: Tue, 16 Dec 2008 13:26:56 -0800 (PST) Subject: Using Mechanize to Fill Out a Form References: Message-ID: On Dec 16, 3:44?pm, KDawg44 wrote: > Hi, > > I am trying to use the Mechanize module to browse to a site, fill out > a form, and login. ?However, it hangs on the opening of the URL. ?The > URL is https, will this cause the open from mechanize to fail? > > Thanks. > > Kevin Apparently, the HTTPS does not matter, but it is still hanging on the open(URL). I am trying to login to Yahoo!. Code below: #!/usr/bin/python import urllib import urllib2 import mechanize baseURL = 'https://login.yahoo.com/' br = mechanize.Browser() br.set_handle_robots(False) br.addheaders = [('User-Agent', 'Firefox')] #try: br.open(baseURL) It just hangs until I kill it. When I kill it, it gives me the following traceback: Traceback (most recent call last): File "FantasyHockeyLoginAndGetTeam.py", line 14, in br.open(baseURL) File "build/bdist.linux-i686/egg/mechanize/_mechanize.py", line 209, in open File "build/bdist.linux-i686/egg/mechanize/_mechanize.py", line 236, in _mech_open File "build/bdist.linux-i686/egg/mechanize/_opener.py", line 202, in open File "build/bdist.linux-i686/egg/mechanize/_http.py", line 578, in http_response KeyboardInterrupt Thanks for any advice. Kevin From tjreedy at udel.edu Mon Dec 8 20:02:38 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Dec 2008 20:02:38 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Robert Kern wrote: > Terry Reedy wrote: >> Rasmus Fogh wrote: > >>> much, though, just to get code like this to work as intended: >>> alist.append(x) >>> print ('x is present: ', x in alist) >> >> Even if rich comparisons as you propose, the above would *still* not >> necessarily work. Collection classes can define a __contains__ that >> overrides the default and that can do anything, though True/False is >> recommended. > > No, it's actually required. > > In [4]: class A(object): > def __contains__(self, other): > return 'foo' > ...: > ...: > > In [7]: a = A() > > In [8]: 1 in a > Out[8]: True > > > Okay, so it will coerce to True/False for you, but unlike rich > comparisons, the return value must be interpretable as a boolean. Interesting. I did not expect that from "Should return true if item is in self, false otherwise.", but maybe the lowercase true/false is an (undocumented?) abbreviation for 'object with Boolean value True/False'. Of course, if the return value is not so interpretable, or if __contains__ raises an exception, there is no coercion and the OP's code will not work. A different summary of my main point in this thread: Dynamic binding and special method hooks make somewhat generic code possible, but the same special method hooks make absolutely generic code nearly impossible. tjr From xahlee at gmail.com Wed Dec 10 17:08:12 2008 From: xahlee at gmail.com (Xah Lee) Date: Wed, 10 Dec 2008 14:08:12 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <20081226055859.604@gmail.com> Message-ID: Xah Lee wrote: > > Let's say for example, we want to write a function that takes a vector > > (of linear algebra), and return a vector in the same direction but > > with length 1. In linear algebar terminology, the new vector is called > > the ?normalized? vector of the original. > > > For those of you who don't know linear algebra but knows coding, this > > If I were to guess who that would be ... > > > means, we want a function whose input is a list of 3 elements say > > {x,y,z}, and output is also a list of 3 elements, say {a,b,c}, with > > the condition that > > > a = x/Sqrt[x^2+y^2+z^2] > > b = y/Sqrt[x^2+y^2+z^2] > > c = z/Sqrt[x^2+y^2+z^2] > > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, > > you'll have 50 or hundreds lines. Kaz Kylheku wrote: > Really? ``50 or hundreds'' of lines in C? > > #include /* for sqrt */ > > void normalize(double *out, double *in) > { > double denom = sqrt(in[0] * in[0] + in[1] * in[1] + in[2] * in[2]); > > out[0] = in[0]/denom; > out[1] = in[1]/denom; > out[2] = in[2]/denom; > } > > Doh? Kaz, pay attention: Xah wrote: ?Note, that the ?norm? as defined above works for vectors of any dimention, i.e. list of any length.? The essay on the example of Mathematica expressiveness of defining Normalize is now cleaned up and archived at: ? A Example of Mathematica's Expressiveness http://xahlee.org/UnixResource_dir/writ/Mathematica_expressiveness.html Xah ? http://xahlee.org/ ? From bruno.42.desthuilliers at websiteburo.invalid Thu Dec 11 08:22:27 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 11 Dec 2008 14:22:27 +0100 Subject: var or inout parm? In-Reply-To: References: <493cda2a$0$17080$426a34cc@news.free.fr> <47c890dc0812080057r6d117bbcic377cb96de52d973@mail.gmail.com> <1228951784.5698.1.camel@mctell> Message-ID: <494113ff$0$1703$426a34cc@news.free.fr> Joe Strout a ?crit : > On Dec 10, 2008, at 4:29 PM, J. Clifford Dyer wrote: > >>>>> mh at pixar.com wrote: >>>>>> >>>>>> How can I make a "var" parm, where the called function can modify >>>>>> the value of the parameter in the caller? >>>>>> >>> See Also: the earlier heated debate thread over what evaluation >>> strategy Python uses (Survey says!: call-by-object). >>> >> >> Oh dear God. PLEASE don't see also that thread. That way lies madness. >> Just google for call-by-object, and ignore the hell out of that thread. > > Agreed on that point! > > Anyway, to the OP, see Do you really want to start a new flame war, Joe ?-) From python at rgbaz.eu Thu Dec 25 07:17:30 2008 From: python at rgbaz.eu (Python) Date: Thu, 25 Dec 2008 13:17:30 +0100 Subject: os.system('cls') In-Reply-To: References: <05BADA85-33ED-48BF-B251-2CC830D6D55E@rgbaz.eu> Message-ID: On 25 dec 2008, at 12:56, Dennis van Oosterhout wrote: > Hello Arno, > > thanks for the explanation! I have one more question: on the python > site it says it's better to replace the system commands by subprocess > and Popen. > Now I searched for some good example for my specific case (as I have > no idea how it should work and I don't get it any clearer by reading > http://docs.python.org/3.0/library/subprocess.html#module-subprocess) > and I found this: > >> import subprocess >> def clear(): >> subProcess.Popen('clear') > never used it myself either, but from reading the manual i think you need import subprocess subprocess.Open('cls') what you did is create a function that you need to call to execute it (and a capital P typo in subprocess) 'clear' is for *nix systems it won;t work in DOS i think (I'm don;t have windows here...) > But it just doesn't seem to work. Would you have any idea how it > would work? > > Once more thanks for the first answer, >> you;re welcome :) From 20080915.20.wmcclain at spamgourmet.com Mon Dec 8 13:46:16 2008 From: 20080915.20.wmcclain at spamgourmet.com (Bill McClain) Date: 8 Dec 2008 18:46:16 GMT Subject: StringIO in 2.6 and beyond Message-ID: I've just installed 2.6, had been using 2.4. This was working for me: #! /usr/bin/env python import StringIO out = StringIO.StringIO() print >> out, 'hello' I used 2to3, and added import from future to get: #! /usr/bin/env python from __future__ import print_function import io out = io.StringIO() print('hello', file=out) ...which gives an error: Traceback (most recent call last): File "./example.py", line 5, in print('hello', file=out) File "/usr/local/lib/python2.6/io.py", line 1487, in write s.__class__.__name__) TypeError: can't write str to text stream ...which has me stumped. Why can't it? -Bill -- Sattre Press History of Astronomy http://sattre-press.com/ During the 19th Century info at sattre-press.com by Agnes M. Clerke http://sattre-press.com/han.html From david at boddie.org.uk Fri Dec 12 19:17:25 2008 From: david at boddie.org.uk (David Boddie) Date: Sat, 13 Dec 2008 01:17:25 +0100 Subject: PyQt: Pulling Abstract Item Data from Mime Data using Drag and Drop. References: <150086b2-b02d-4204-8c06-b08c0aa119c4@k1g2000prb.googlegroups.com> Message-ID: On Friday 12 December 2008 02:05, Mudcat wrote: > The drag is working up until the point I try to actually retrieve the > data. At that point I get an unhandled Runtime Error saying "no access > to protected functions or signals for objects not created in Python". That's correct, retrieveData() is a protected function in C++ and the QMimeData object was created by the framework, not you, in this case. > Obviously I am not retrieving them in the correct format. Does anyone > know how to convert/retrieve the information into a Python list? You could use the data() method to get the serialized data then try to extract the list item-by-item using the QDataStream class, or perhaps PyQt has a convenience function to unpack the items. Alternatively - and this is a bit speculative - perhaps you can copy the data to another QMimeData object which you have created, and use its retrieveData() method to retrieve the items. You might get a more detailed response by asking on the PyQt mailing list: http://www.riverbankcomputing.com/mailman/listinfo/pyqt Hope this helps, David From jstroud at mbi.ucla.edu Sun Dec 7 19:39:09 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 07 Dec 2008 16:39:09 -0800 Subject: Rich Comparisons Gotcha In-Reply-To: <014c593e$0$20670$c3e8da3@news.astraweb.com> References: <014c593e$0$20670$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Sun, 07 Dec 2008 13:57:54 -0800, James Stroud wrote: > >> Rasmus Fogh wrote: >>>>>> ll1 = [y,1] >>>>>> y in ll1 >>> True >>>>>> ll2 = [1,y] >>>>>> y in ll2 >>> Traceback (most recent call last): >>> File "", line 1, in >>> ValueError: The truth value of an array with more than one element is >>> ambiguous. Use a.any() or a.all() >> I think you could be safe calling this a bug with numpy. > > Only in the sense that there are special cases where the array elements > are all true, or all false, and numpy *could* safely return a bool. But > special cases are not special enough to break the rules. Better for the > numpy caller to write this: > > a.all() # or any() > > instead of: > > try: > bool(a) > except ValueError: > a.all() > > as they would need to do if numpy sometimes returned a bool and sometimes > raised an exception. I'm missing how a.all() solves the problem Rasmus describes, namely that the order of a python *list* affects the results of containment tests by numpy.array. E.g. "y in ll1" and "y in ll2" evaluate to different results in his example. It still seems like a bug in numpy to me, even if too much other stuff is broken if you fix it (in which case it apparently becomes an "issue"). James From joe at strout.net Sun Dec 7 14:56:14 2008 From: joe at strout.net (Joe Strout) Date: Sun, 7 Dec 2008 12:56:14 -0700 Subject: how to get a beep, OS independent ? In-Reply-To: References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> Message-ID: <320A8AF5-DF3F-482F-93BE-073C74AA6462@strout.net> On Dec 7, 2008, at 8:48 AM, Grant Edwards wrote: > On 2008-12-07, Joe Strout wrote: > >> But invoking the standard system beep > > What makes you think there is such a thing as "the standard system > beep"? Because OS X (the platform with which I'm most familiar) certainly has one, and REALbasic has had a "Beep" method for years which works on all platforms. If RB can do it, we can do it too. Best, - Joe From kyosohma at gmail.com Mon Dec 8 16:54:00 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 8 Dec 2008 13:54:00 -0800 (PST) Subject: Calling C# COM (.NET) from python References: <65482a31-8091-486f-8a9b-8f6bdf947af6@w1g2000prk.googlegroups.com> <0e2ec315-a5ef-419e-a224-78ab965db99c@r15g2000prd.googlegroups.com> Message-ID: On Dec 8, 3:33?pm, Andrew Falanga wrote: > On Dec 8, 11:52?am, Mike Driscoll wrote: > > > > > On Dec 8, 11:14?am, Ben Kaplan wrote: > > > > On Dec 8, 2008, at 11:53 AM, Andrew Falanga wrote: > > > > > Hi, > > > > > I've never programmed in python and only have a small understanding of > > > > what is wrapped up in the terms COM and .NET. ?Is there a way of using > > > > python to get a hold of objects written in C# as COM objects using > > > > python? ?I'm looking for ways to avoid VBScript (which, after a couple > > > > of weeks, I've determined to be horrid). ?That is, is there a way of > > > > getting at COM objects in python that's similar to doing a > > > > CreateObject call in VBScript (http://msdn.microsoft.com/en-us/ > > > > library/ > > > > dcw63t7z.aspx)? > > > > > Thanks, > > > > Andy > > > > -- > > > >http://mail.python.org/mailman/listinfo/python-list > > > > I would not deal with COM at all. I personally have not used it, but ? > > > there is a version of python called IronPython that's written in C#, ? > > > so it can use .NET and, I think, other C# objects. Other people will ? > > > probably help you more, but you might want to look into that and maybe ? > > > ask this on the python-win list. > > > As I understand it, IronPython can use anything done in the CLR, so > > technically I could write something in VB.NET, C# or any of the other > > VS languages and then use them from within IronPython. It should be > > noted that IronPython does not support most 3rd party packages that > > are not pure python. As I recall, it doesn't have the complete builtin > > library either, but it's close. > > > Reads the docs and check it out at least. If you already know .NET > > languages, then you'll probably find IronPython helpful. > > > Mike > > To all, thanks for the great replies. ?I've got something to work with > here. ?Thanks to for the link to PyWin32 and the mailing list. ?That > sounds promising as does this IronPython. ?I wished I knew more > of .NET and python more (as my original post claims, I've never > written Python and I only wished I knew the .NET stuff better for > better footing in this). ?I'm very much the proverbial, "fish out of > water," as I'm a UNIX man now stuck in a Windows world. > > Thanks again, > Andy Andy, Welcome to the wonderful world of Python programming. It's fun and cool! Windows is a complex place, but the Python crew on that PyWin32 mailing list will help you out with that stuff and the people here will help you with your more general questions. Last week, there was another beginner who needed some clues for where to go for learning the language. I suggest you read that thread as it had lots of good examples: http://groups.google.com/group/comp.lang.python/browse_frm/thread/29278b3db85a1341# I recommend the Dive Into Python online book too, which is listed in the link above. There are also lots of quality physical books out there. Let me know if you need any suggestions for those. Have a nice day! Mike From wuwei23 at gmail.com Thu Dec 11 12:22:21 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 11 Dec 2008 09:22:21 -0800 (PST) Subject: Preventing execution of a method References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> Message-ID: <764daeef-bfbe-411a-8521-bb114321e4ac@b38g2000prf.googlegroups.com> On Dec 12, 2:35?am, rdmur... at bitdance.com wrote: > There is, however, also the possibility of prefixing the method name > with '__'. ?The invokes 'name mangling', which makes it more difficult > (though not impossible, the idea is to avoid accidents) for the method > to be called from outside the class. That only works for methods, it has no effect on functions or classes within modules: module.py: def __f(): pass class __F(object): def __f(): pass >>> import module as m >>> m.__f >>> m.__F >>> f = m.__F() >>> f.__f Traceback (most recent call last): File "", line 1, in AttributeError: '__F' object has no attribute '__f' >>> f._F__f > From arnodel at googlemail.com Sat Dec 20 04:28:55 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 20 Dec 2008 09:28:55 +0000 Subject: Namespaces, multiple assignments, and exec() References: Message-ID: John O'Hagan writes: > I have a lot of repetitive assignments to make, within a generator, > that use a function outside the generator: > > var1 = func("var1", args) > var2 = func("var2", args) > var3 = func("var3", args) > etc... > > In each case the args are identical, but the first argument is a > string of the name being assigned. It works fine but I'd like to > reduce the clutter by doing the assignments in a loop. I've tried > using exec(): > > for name in name_string_list: > exec(name + ' = func(\"' + name + '\", args)') > > but in the local namespace it doesn't understand func(), and if I give > it globals() it doesn't understand the args, which come from within > the generator. > > What's a good way to do this kind of thing? Your problem is describe in too vague a way to get good answers IMHO. Are var1, var2, ... globals or local to the generator? Can you give some sample code to show what doesn't work? -- Arnaud From martin at v.loewis.de Mon Dec 15 19:05:58 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 16 Dec 2008 01:05:58 +0100 Subject: Problem Python 2.6.1 vs 2.6 & pyWin32 In-Reply-To: <4946ed94$0$22011$426a74cc@news.free.fr> References: <4946754f$0$19000$426a74cc@news.free.fr><4946D09F.6050300@v.loewis.de> <4946ed94$0$22011$426a74cc@news.free.fr> Message-ID: <4946f0e6$0$6492$9b622d9e@news.freenet.de> > I noted, also, than, in some cases, Python26.dll is not copied in > %WINDIR%\system32 > After that, external softs don't find the DLL. Right. Only in "for all users" installations, python26.dll is put into system32. In a "just for me" installation, the user is not expected to have permissions to system32, hence the DLL is put into c:\python26. Regards, Martin From tjreedy at udel.edu Thu Dec 4 13:43:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Dec 2008 13:43:02 -0500 Subject: schizophrenic view of what is white space In-Reply-To: <4938112F.5030706@chamonix.reportlab.co.uk> References: <4937E8E5.2090306@chamonix.reportlab.co.uk> <20081204143337.20272.1236189783.divmod.quotient.15592@ohm> <4938112F.5030706@chamonix.reportlab.co.uk> Message-ID: > so the default behaviour differs for unicode and re working on unicode. > I suppose that won't be true in Python 3. import re print(re.compile(r'\s').search('a b')) print(re.compile(r'\s').search('a\xa0b') ) >>> ================================ RESTART =============== >>> <_sre.SRE_Match object at 0x00ADAA68> <_sre.SRE_Match object at 0x00ADAA68> From jobs.teaching.english.asia at gmail.com Fri Dec 5 23:28:04 2008 From: jobs.teaching.english.asia at gmail.com (Jobs Teaching English in Asia) Date: Fri, 5 Dec 2008 20:28:04 -0800 (PST) Subject: Cambodia TEFL - Gap Year, Travel & Study, Paid Teaching Job - http://www.cambodiatefl.com Message-ID: <00091596-dee3-4435-b675-e02322f8df94@a29g2000pra.googlegroups.com> Cambodia TEFL - Gap Year, Travel & Study, Paid Teaching Job http://www.cambodiatefl.com From lie.1296 at gmail.com Mon Dec 8 02:06:06 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 8 Dec 2008 07:06:06 +0000 (UTC) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> Message-ID: On Sun, 07 Dec 2008 20:56:40 +0000, I V wrote: > So, if we want Python to the programming language of choice for Lacanian > psychoanalysts, perhaps we should adopt the symbol "$" (or even, with > Python 3's support for unicode identifiers, S followed by U+0388) > instead of "self." Is that supposed to be a serious argument or a joke? :) From joe at strout.net Sun Dec 7 20:34:17 2008 From: joe at strout.net (Joe Strout) Date: Sun, 7 Dec 2008 18:34:17 -0700 Subject: how to get a beep, OS independent ? In-Reply-To: <014c575a$0$20670$c3e8da3@news.astraweb.com> References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> <014c575a$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Dec 7, 2008, at 4:43 PM, Steven D'Aprano wrote: > Of course, if you're volunteering to write such a standard system beep > for Python, I for one would be grateful. I am. But where should I put it? Assuming we don't want to wait for the (understandably) lengthy and contentious process required to add something to the Python system libraries, where would be the next best place for this sort of simple OS abstraction layer? Thanks, - Joe From lewis.sarah93 at yahoo.com Thu Dec 4 23:49:12 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 20:49:12 -0800 (PST) Subject: Get out of Debt Message-ID: Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 18:19:06 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Dec 2008 23:19:06 GMT Subject: A more pythonic way of writting References: <35d176ed-df5f-46b4-8321-4814fcc4398c@f3g2000yqf.googlegroups.com> <8de7622d-28a7-4f96-9fb0-21cda357dcf3@r36g2000prf.googlegroups.com> Message-ID: <0149aea6$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 07:44:21 -0800, eric wrote: > I like to believe that the less the 'debug pointer' stands in the python > code, the fastest the code is (or is potentially) What's a debug pointer? Pre-mature optimization is the root of evil in programming. Unless you have actually *measured* the speed of the code, how do you know you aren't making it slower instead of faster? Experience with other languages often is misleading when programming with Python. If you are used to programming in C, for example, then you will tend to program one way because comparisons are fast and moving records is slow. But in Python, comparisons can be slow and moving records is fast, so the C programmer's intuitions about "fast code" are often pessimations instead of optimizations. -- Steven From febaen at gmail.com Fri Dec 12 07:05:21 2008 From: febaen at gmail.com (feba) Date: Fri, 12 Dec 2008 04:05:21 -0800 (PST) Subject: (Very Newbie) Problems defining a variable References: <49425146$0$8495$426a74cc@news.free.fr> Message-ID: <11c53a4a-de1e-4bee-ad60-a05befb6cbf4@a12g2000yqm.googlegroups.com> On Dec 12, 5:56?am, Bruno Desthuilliers wrote: > feb... at gmail.com a ?crit : > > > > > #!/usr/bin/python > > #Py3k, UTF-8 > > > bank = int(input("How much money is in your account?\n>>")) > > target = int(input("How much money would you like to earn each year? > > \n>>")) > > > interest = 0 > > i = 0 > > > while interest < target: > > #determine the interest rate to use > > ? ?if bank >= 9999: > > ? ? ? ? ? ?rate = 0.006 > > ? ?elif bank >= 10000 and bank <= 24999: > > ? ? ? ? ? ?rate = 0.0085 > > ? ?elif bank >= 25000 and bank <= 49999: > > ? ? ? ? ? ?rate = 0.0124 > > ? ?elif bank >= 50000 and bank <= 99999: > > ? ? ? ? ? ?rate = 0.0149 > > ? ?elif bank >= 100000: > > ? ? ? ? ? ?rate = 0.0173 > > (snip) > > > I'm pretty certain that that is also the problem in the code. I'm > > pretty sure it's a problem with the 'if' statements', and it looks > > like it's one of those mistakes that's so simple you look back on it > > and laugh at yourself. If you put in a bank number <= 9999, it fails, > > saying ?"NameError: name 'rate' is not defined". ?If you put in one > > higher, it runs correctly, but thinks that the rate is 0.006 > > Indeed. That's what you asked for. If bank is >= 9999, then rate will be > set to 0.006, and the following tests will be skipped. Else - since you > just don't handle the case -, rate is not defined at all. > > I guess you wanted your first test to be: > > ? ? if bank <= 9999: > ? ? ? ?... > > FWIW, when using if/elif that way, make sure you always end with a > "default" else clause (even if just to signal you didn't expect to be > there...) > > HTH that's it, thanks! was confused with it being basically in a column of all >= *. I replaced it with if bank <= 0: print("You're in the red!") quit() elif bank >= 1 and bank <= 9999: rate = 0.0060 elif bank >= 10000 and bank <= 24999: rate = 0.0085 elif bank >= 25000 and bank <= 49999: rate = 0.0124 elif bank >= 50000 and bank <= 99999: rate = 0.0149 elif bank >= 100000: rate = 0.0173 else: print("What's this doing here?") which also changes it to keep it from going on forever if you put in a negative amount. Out of curiosity, would you still recommend applying an 'else' clause in this case? I don't see how it could ever be triggered, even if there's an error of some kind From python.list at tim.thechases.com Sun Dec 14 14:34:24 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 14 Dec 2008 13:34:24 -0600 Subject: Why %e not in time.strftime directives? In-Reply-To: <4e307e0f0812132252y35ed5cdep40eabaa54f1d8967@mail.gmail.com> References: <38f9c4ba-d96d-47e1-b718-562bdc6718e9@t26g2000prh.googlegroups.com> <4943D9AB.7040006@tim.thechases.com> <4e307e0f0812132252y35ed5cdep40eabaa54f1d8967@mail.gmail.com> Message-ID: <49455FC0.5070807@tim.thechases.com> >>> Any special reasons? >> Because it is there (at least on my Debian box)? > > But not on windows :( >>>> import time >>>> time.strftime("%e") > '' Guess you'll have to take it up with the authors of strftime() at Microsoft :) >> The full set of format codes supported varies across >> platforms, because Python calls the platform C library's >> strftime() function, and platform variations are common. >> >> So if your underlying C implementation of strftime() supports "%e", then >> Python will. My guess is that the same applies to time.strftime as it does >> to datetime.strftime >> >> The docs list ones that are fairly cross-platform. However, it would seem >> that not all platforms support "%e" If you don't have any luck convincing Microsoft to add "%e" to their strftime implementation, you can use strftime('%d').lstrip('0').rjust(2) to replicate the desired behavior :) -tkc From Mr.HassanShabbir at gmail.com Thu Dec 11 08:45:13 2008 From: Mr.HassanShabbir at gmail.com (Explore_Imagination) Date: Thu, 11 Dec 2008 05:45:13 -0800 (PST) Subject: How to convert uint64 in C into Python 32bit Object [ I am using Python2.2 ] References: <069f0d65-a3d5-4e8f-a85b-c53743ab99d0@i18g2000prf.googlegroups.com> <8485fb8f-4425-436d-9e0b-2079c80c9802@q26g2000prq.googlegroups.com> Message-ID: <6b710b67-0e91-4c55-8ef7-23891addfc51@q26g2000prq.googlegroups.com> On Dec 11, 4:45 am, John Machin wrote: > On Dec 11, 9:49 am, Explore_Imagination > wrote: > > > Hi all > > > I am new to C and python ... I want to convert C data type uint64 > > variable into the Python 32bit Object. I am currently using Python 2.2 > > [ It is necessary to use it ] > > > Kindly give your suggestion how and in which way I can achieve this > > task. > > I'm not sure what you mean by "the Python 32bit Object". A Python int > object holds a signed 32-bit integer. A Python long object holds a > signed integer of arbitrary size. You will need to convert your uint64 > into a Python long; then, if necessary, check that the result will fit > in an int (result <= sys.maxint). > > If the "C variable" is in an 8-byte string that you have read from a > file, the unpack function in the struct module will do the job. > Assuming your computer is little-endian: > > >>> maxu64 = '\xff' * 8 # example input string > >>> import struct > >>> result = struct.unpack(' >>> result > > 18446744073709551615L>>> 2 ** 64 - 1 > > 18446744073709551615L > > If however you mean that in C code you need to build a Python object > to pass over to Python code: According to the Python/C API Reference > Manual (http://www.python.org/doc/2.2.3/api/longObjects.html): > > PyObject* PyLong_FromUnsignedLongLong(unsigned long long v) > Return value: New reference. > Returns a new PyLongObject object from a C unsigned long long, or > NULL on failure. > > If however you mean something else, .... > > HTH, > John Thanks for your feedback ... Actually I want to pass unit64 variable in C to python but at the same time I want to have a generic code which should work on both little-endian and big endian architectures Any suggestions ? From castironpi at gmail.com Sat Dec 13 15:53:11 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 13 Dec 2008 12:53:11 -0800 (PST) Subject: stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> Message-ID: <1ff0d642-b560-433c-b793-3a05f5b051b9@g1g2000pra.googlegroups.com> On Dec 13, 1:17?pm, Duncan Booth wrote: > "Diez B. Roggisch" wrote: > > > > > David Hl??ik schrieb: > >> Hi guys, > > >> i am really sorry for making offtopic, hope you will not kill me, but > >> this is for me life important problem which needs to be solved within > >> next 12 hours.. > > >> I have to create stable algorithm for sorting n numbers from interval > >> [1,n^2] with time complexity O(n) . > > >> Can someone please give me a hint. Would be very very thankful! > > > Unless I grossly miss out on something in computer science 101, the > > lower bound for sorting is O(n * log_2 n). Which makes your task > > impossible, unless there is something to be assumed about the > > distribution of numbers in your sequence. > > > Who has given you that assignment - a professor? Or some friend who's > > playing tricks on you? > > I think you must have fallen asleep during CS101. The lower bound for > sorting where you make a two way branch at each step is O(n * log_2 n), but > if you can choose between k possible orderings in a single comparison you > can get O(n * log_k n). > > To beat n * log_2 n just use a bucket sort: for numbers with a known > maximum you can sort them digit by digit for O(n log_k n), and if you don't > restrict yourself to decimal then k can be as large as you want, so for the > problem in question I think you can set k=n and (log_n n)==1 so you get > O(n) Minor detail: with k= n, you have log_n (n^2)= 2, so you get O(2n)= O (n). Same answer. The generic sort theorems also assume you can compare arbitrarily large numbers in constant time, which isn't true. That is, for any given machine, there exist numbers that you can't compare on them in constant time. But with a known upper bound k, you can just use a k- bit machine. So, what's the group policy on helping with homework? From steve at holdenweb.com Tue Dec 30 08:48:31 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Dec 2008 08:48:31 -0500 Subject: Triple quoted string in exec function ? In-Reply-To: <495A253B.6010003@gmail.com> References: <495A253B.6010003@gmail.com> Message-ID: Stef Mientki wrote: > hello, > > I'm running scripts, with the execute function (Python 2.5), > and it seems that triple quoted strings are not allowed. > > Is there a workaround, > or is this a fundamental problem of the exec-function ? > If you think about it, it should be obvious that you can't surround a string to be compiled with any of the quotes that appear inside the string to be compiled. That's about the only limitation I am aware of. And, by the way, exec is a *statement*, not a function! >>> exec """print '''This is ... a long string''' ... """ This is a long string >>> regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From alessio.pace at gmail.com Mon Dec 1 08:36:16 2008 From: alessio.pace at gmail.com (Alessio Pace) Date: Mon, 1 Dec 2008 05:36:16 -0800 (PST) Subject: How to distribute a Python app together with its dependencies? References: <35377946-378c-484d-88cc-396145090d2f@l39g2000yqn.googlegroups.com> Message-ID: On 1 Dic, 10:37, BlueBird wrote: > Alessio Pace wrote: > > Hi, > > > I have to distribute a Python application which relies on an external > > library, and I'm not very fluent in this kind of stuff with Python (I > > come from the Java world where I would have used the Maven build tool > > to create an "assembly with dependencies" of all it is needed to run > > the app), so I was wondering if someone here could give me some > > suggestions :-) > > > The external library is generally not present on the machines where I > > have to distribute my app, and the set of machines on which I have to > > distribute this application is not known a priori (it is just known > > they are Unix systems). In fact by means of SSH I will have to copy > > (and install) the app+library and make it runnable onto the specified > > destination(s). > > I have never used it myself, but bbfreeze claims to create packaged > versions of an application, for windows and Unix : > > http://pypi.python.org/pypi/bbfreeze/0.95.2 > Thank you. What's the difference with "Freeze" shipped with Python, or with PyInstaller ? Do you have experiences with any of them? From prologic at shortcircuit.net.au Thu Dec 4 05:53:38 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 4 Dec 2008 20:53:38 +1000 Subject: "as" keyword woes In-Reply-To: <7dudnSS7uIn_KarUnZ2dnUVZ_tTinZ2d@earthlink.com> References: <7dudnSS7uIn_KarUnZ2dnUVZ_tTinZ2d@earthlink.com> Message-ID: One of the things I'd like to point out here is what we've been learning in new job during Induction Training... That is, it's part of the coding standard and design standards to name variables sensibly. For instance, naming a variable "db" when it's really a "database" object is a no no. Instead you should be naming it "db". Another example, "db_id" vs. "database_id". So my point here is that you should not really/ideally be naming variables with such short un-meaningful names such as "as", "if", "id", "xs" or what not. Readability of your code becomes very important especially if you're working with many developers over time. 1. Use sensible meaningful names. 2. Don't use abbreviations. cheers James On Thu, Dec 4, 2008 at 8:43 PM, Dennis Lee Bieber wrote: > On Thu, 4 Dec 2008 01:28:56 -0800, "Warren DeLano" > declaimed the following in comp.lang.python: > >> In addition, note that my choice of a concise method identifier affects >> only my users. Python's introduction of a new keyword affects the >> entire Python world code base, so perhaps you should be directing your >> "choose better names" criticism in another direction? >> > Dropping in... > > If a "chosen name" mirrors a syntactic element -- whether reserved > or not -- I'd consider that name potentially ambiguous or conflicted. > > While "if" has been long a reserved word, I can as easily see > someone using "if" as a shorthand name for "interface". And if "if" were > not a reserved word, one might encounter code on the lines of > > if = if + 1 > > which is quite obnoxious to my eyes... or maybe > > if if.connected: > if.close() > > > Since > > import x as y > > has been a syntactic capability for some time, even if not reserved, I'd > have avoided using "as" as anything other than that usage... > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From kkylheku at gmail.com Wed Dec 10 19:34:00 2008 From: kkylheku at gmail.com (Kaz Kylheku) Date: Thu, 11 Dec 2008 00:34:00 +0000 (UTC) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <20081226055859.604@gmail.com> Message-ID: <20081226091336.487@gmail.com> On 2008-12-10, Xah Lee wrote: > Xah Lee wrote: >> > means, we want a function whose input is a list of 3 elements say ^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^ > Kaz, pay attention: [ reformatted to 7 bit USASCII ] > Xah wrote: Note, that the norm > of any dimention, i.e. list of any length. It was coded to the above requirements. From anthony.tolle at gmail.com Mon Dec 8 12:09:30 2008 From: anthony.tolle at gmail.com (anthony.tolle at gmail.com) Date: Mon, 8 Dec 2008 09:09:30 -0800 (PST) Subject: Guido's new method definition idea References: <014a071a$0$20670$c3e8da3@news.astraweb.com> <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> Message-ID: <08049caf-04a4-45ff-afbc-212ab40a43a1@v13g2000yqm.googlegroups.com> On Dec 8, 12:01?pm, anthony.to... at gmail.com wrote: > > It would be nice to be able to do the following instead: > > class C: > ? ? def createfunc(self): > ? ? ? ? def self.func(arg): > ? ? ? ? ? ? return arg + 1 > The above example should have read as follows: class C: def createfunc(self, arg): def self.func(arg): return arg + 1 ----- Anthony Tolle From n.kottiyath at gmail.com Wed Dec 24 14:08:27 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Wed, 24 Dec 2008 11:08:27 -0800 (PST) Subject: Iterating over objects of a class References: <2df27de3-7fa3-4ac9-acd9-f946939517cf@r37g2000prr.googlegroups.com> <6rfb7iF1fg5rU1@mid.uni-berlin.de> <7f47994f-13b6-45c4-920a-83aa72282bec@i20g2000prf.googlegroups.com> Message-ID: <77eaa70f-971b-4274-8136-0961313a34a7@f40g2000pri.googlegroups.com> On Dec 24, 11:48?pm, "Gabriel Genellina" wrote: > En Wed, 24 Dec 2008 16:18:55 -0200, Kottiyath ? > escribi?: > > >> The other thing to remember is that because the 'registry' contains > >> references to the instances, they won't be garbage collected. > > > Is there any other way out in this case? > > I have factory methods - and I have to loop over them - sort of Chain > > of Responsibility pattern. > > Having a registry inside the class instance and looping through them > > was the only clean thing I could think of. > > I understand that garbage collection would be an issue - but is there > > any way out? > > You may keep all that structures - just use weak references (see the ? > weakref module). > There isn't a WeakList nor WeakSet out-of-the-box but you may use a ? > WeakKeyDictionary (set the value to anything, None by example). > > -- > Gabriel Genellina Thank you very much, Gabriel. I am very thankful to everyone. From steve at holdenweb.com Thu Dec 18 16:37:45 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 18 Dec 2008 16:37:45 -0500 Subject: confused about __str__ vs. __repr__ In-Reply-To: References: <494A5ACA.8060205@wildenhain.de> Message-ID: Neal Becker wrote: > Mel wrote: > >> Neal Becker wrote: >> >>> Tino Wildenhain wrote: >>> >>>> Neal Becker wrote: >>>>> Reading some FAQ, I see that __str__ is "meant for human eyes". >>>>> >>>>> But it seems that: >>>>> class X(object): >>>>> def __str__(self): >>>>> return "str" >>>>> def __repr__(self): >>>>> return "repr" >>>>> >>>>> x = X() >>>>> d = {0 : x} >>>>> print d >>>>> {0: repr} >>>>> >>>>> So if __str__ is "meant for human eyes", then why isn't print using it! >>>> it is: >>>> >>>> > print x >>>> str >>>> >>>> but dict just uses repr() for all its childs to print. >>>> >>>> T. >>> That makes no sense to me. If I call 'print' on a container, why >>> wouldn't >>> it recursively print on the contained objects? Since print means call >>> str, printing a container should recursively call str on the objects. >> Basically because there are too many right ways to format the resulting >> report. Space separated? Tab separated? One per line? Boxes around >> them? As HTML definition lists? Creating a standard report form would >> take a lot of work and wouldn't, finally, solve very many peoples' >> problems. >> >> Mel. >> > Thanks, but the question of how to format the container is different from how to format the primitive elements of the container. I was suggesting that printing an element of a container should be consistent with printing the element without the container, i.e., > > print [a] > should be consistent with > print a > Indeed, but that only demonstrates that you have failed to take the point of the more perspicacious replied to your query. Python is trying to avoid throwing away useful information. The only people who would want to see a representation of a data structure such as a list are programmers: if you want to show a list of values to a regular user you format it in some required way. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From skip at pobox.com Sun Dec 21 09:59:53 2008 From: skip at pobox.com (skip at pobox.com) Date: Sun, 21 Dec 2008 08:59:53 -0600 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <6r6hcmFfb643U2@mid.uni-berlin.de> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <6r6hcmFfb643U2@mid.uni-berlin.de> Message-ID: <18766.23017.450136.943072@montanaro-dyndns-org.local> Marc> Many newbie code I have seen avoids it by string concatenation: Marc> greeting = 'Hello, my name is ' + name + ' and I am ' + str(age) + ' old.' Marc> That's some kind of indirect complaint. :-) I see Python code like that written by people with a C/C++ background. I don't think you can necessarily chalk that up to %-string avoidance. They learn that + will concatenate two strings and don't look further. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From prologic at shortcircuit.net.au Tue Dec 2 09:44:23 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 3 Dec 2008 00:44:23 +1000 Subject: Running a Python script from crontab In-Reply-To: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> Message-ID: Put your main function in a big try, except. Catch any and all errors and log them. Example: def main(): try: do_something() except Exception, error: log("ERROR: %s" % error) log(format_exc()) Hope this helps. cheers James On Wed, Dec 3, 2008 at 12:35 AM, Astley Le Jasper wrote: > I need help ... I've been looking at this every evening for over a > week now. I'd like to see my kids again! > > I have script that runs fine in the terminal but when I try to run it > in a crontab for either myself or root, it bails out. > > The trouble is that obviously I get no console when using crontab so > can't see any traceback. I use logging which shows 'info' messages as > the script is working, but no error messages. I've peppered it with > debug messages to try to track it down to a line, but it stops it the > middle of appending data to a list. I'd expect it to bail out when > calling a module or reading/writing to a different file. > > Is there any way of getting more info from the app, like popping up a > console while its running? > > my crontab is: > > 30 15 * * * cd /home/myusername/src && python myscript.py > > ALJ > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From benjamin.kaplan at case.edu Fri Dec 12 15:52:40 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 12 Dec 2008 15:52:40 -0500 Subject: Testing against different versions of Python In-Reply-To: <2678157f0812121142y2afcf3bey254dd2b74f61e423@mail.gmail.com> References: <2678157f0812121142y2afcf3bey254dd2b74f61e423@mail.gmail.com> Message-ID: On Fri, Dec 12, 2008 at 2:42 PM, mercado wrote: > What is the best way to go about testing against different versions of > Python? For example, I have 2.5.2 installed on my machine (Ubuntu Hardy > 8.04), and I want to test a script against 2.5.2 and 2.5.1 (and possibly > other versions as well). > There are no incompatibilities between 2.5.2 and 2.5.1, unless you were relying on a bug in your code. AFAIK, the only way to test it against both would be to compile 2.5.1 yourself. Then, /usr/bin/python would point to 2.5.2 and /usr/local/bin/python would point to python 2.5.1. To test your script against 2.4, just install the Python2.4 package from apt and invoke the interpreter with the command python2.4 instead of python. The same thing goes for python 2.3. Intrepid has a package for Python 3 as well, if you are willing to do a distro upgrade. > > Thanks in advance. > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstroud at mbi.ucla.edu Sun Dec 7 22:36:17 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 07 Dec 2008 19:36:17 -0800 Subject: Rich Comparisons Gotcha In-Reply-To: References: <014c593e$0$20670$c3e8da3@news.astraweb.com> Message-ID: Robert Kern wrote: > James Stroud wrote: >> I'm missing how a.all() solves the problem Rasmus describes, namely >> that the order of a python *list* affects the results of containment >> tests by numpy.array. E.g. "y in ll1" and "y in ll2" evaluate to >> different results in his example. It still seems like a bug in numpy >> to me, even if too much other stuff is broken if you fix it (in which >> case it apparently becomes an "issue"). > > It's an issue, if anything, not a bug. There is no consistent > implementation of bool(some_array) that works in all cases. numpy's > predecessor Numeric used to implement this as returning True if at least > one element was non-zero. This works well for bool(x!=y) (which is > equivalent to (x!=y).any()) but does not work well for bool(x==y) (which > should be (x==y).all()), but many people got confused and thought that > bool(x==y) worked. When we made numpy, we decided to explicitly not > allow bool(some_array) so that people will not write buggy code like > this again. > > The deficiency is in the feature of rich comparisons, not numpy's > implementation of it. __eq__() is allowed to return non-booleans; > however, there are some parts of Python's implementation like > list.__contains__() that still expect the return value of __eq__() to be > meaningfully cast to a boolean. > You have explained py> 112 = [1, y] py> y in 112 Traceback (most recent call last): File "", line 1, in ValueError: The truth value of an array with more than one element is... but not py> ll1 = [y,1] py> y in ll1 True It's this discrepancy that seems like a bug, not that a ValueError is raised in the former case, which is perfectly reasonable to me. All I can imagine is that something like the following lives in the bowels of the python code for list: def __contains__(self, other): foundit = False for i, v in enumerate(self): if i == 0: # evaluates to bool numpy array foundit = one_kind_of_test(v, other) else: # raises exception for numpy array foundit = another_kind_of_test(v, other) if foundit: break return foundit I'm trying to imagine some other way to get the results mentioned but I honestly can't. It's beyond me why someone would do such a thing, but perhaps it's an optimization of some sort. James From upton at virginia.edu Sat Dec 13 14:08:19 2008 From: upton at virginia.edu (Dan Upton) Date: Sat, 13 Dec 2008 14:08:19 -0500 Subject: [OT] stable algorithm with complexity O(n) In-Reply-To: References: <6qidmbFc4qduU1@mid.uni-berlin.de> Message-ID: <5504f9ac0812131108n25d867d4x3ff247dae5230fe5@mail.gmail.com> On Sat, Dec 13, 2008 at 2:00 PM, David Hl??ik wrote: >> Unless I grossly miss out on something in computer science 101, the lower >> bound for sorting is O(n * log_2 n). Which makes your task impossible, >> unless there is something to be assumed about the distribution of numbers in >> your sequence. This is only true for comparison-based sorts. > > There is n numbers from interval [1 , n^2] > I should do measurement for : > n = 500, 1000, 1500, 2000, ..., 4500, 5000 > > O(n) means linear complexivity, so complexivity of algorithmus must be > linear, which i have to prove. > > >> >> Who has given you that assignment - a professor? Or some friend who's >> playing tricks on you? > > It is official assignment , by professor from Data Structures & > Algorithms course. > > Thanks in advance! >> >> Diez >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > -- > http://mail.python.org/mailman/listinfo/python-list > Look at things like bucket sort and radix sort. You can also do tricky things like translating your problem domain by making a fixed number of linear-time passes without affecting the asymptotic run time. (Hopefully that's helpful... don't want to give too much away on a homework assignment, plus tricky algorithms have never been my strong suit.) From jcd at sdf.lonestar.org Mon Dec 8 16:05:36 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 08 Dec 2008 16:05:36 -0500 Subject: how to get a beep, OS independent ? In-Reply-To: <6q2sjfFai65qU1@mid.individual.net> References: <6q2sjfFai65qU1@mid.individual.net> Message-ID: <1228770336.5709.37.camel@aalcdl07.lib.unc.edu> On Sun, 2008-12-07 at 21:13 +0000, Peter Pearson wrote: > On Sun, 07 Dec 2008 00:40:53 +0100, Stef Mientki wrote: > > > > I want to give a small beep, > > for windows there's message-beep, > > and there seems to be something like " curses" , > > but that package seems to be totally broken in P2.5 for windows. > > > > Any other suggestions ? > > Many people have suggested sending an ASCII 07 to your > terminal window, but sometimes you don't have a terminal > window. > > Then there's the question of using the sound card versus > using the PC speaker. Too complicated for me. > > I used a kluge: a short C program that beeps the way I want, > in this case using ioctl(fd,KDMKTONE,arg) on /dev/tty0 (this > is Linux). The program has enough privileges to execute > even when run by unprivileged users, and of course can be > invoked by whatever language you're working in. > If you're already using /dev/tty0, why not just open a file object on /dev/tty0, and write "\a"=="\x07" to that. No C required. #!/usr/bin/env python nonstdout = file("/dev/tty0") nonstdout.write("\a") nonstdout.flush() (same permissions caveats apply) On the other hand, the OP was looking for a cross-platform solution. I don't think Windows has a /dev/tty0, but I don't work on windows, so I can't help with cross platform issues. Cheers, Cliff From xahlee at gmail.com Mon Dec 1 02:23:43 2008 From: xahlee at gmail.com (Xah Lee) Date: Sun, 30 Nov 2008 23:23:43 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: On Nov 30, 7:30 pm, Xah Lee wrote: > Wolfram Research's Mathematica Version 7 has just been released. > > See: http://www.wolfram.com/products/mathematica/index.html > > Among it's marketing material, it has a section on how mathematica > compares to competitors. http://www.wolfram.com/products/mathematica/analysis/ Stephen Wolfram has a blog entry about Mathematica 7. Quite amazing: http://blog.wolfram.com/2008/11/18/surprise-mathematica-70-released-today/ Mathematica today in comparsion to all other existing langs, can be perhaps compared to how lisp was to other langs in the say 1980s: Quite far beyond all. Seeing how lispers today still talking about how to do basic list processing with its unusable cons, and how they get giddy with 1980's macros (as opposed to full term rewriting), and still lack pattern matching, one feels kinda sad. see also: ? Fundamental Problems of Lisp http://xahlee.org/UnixResource_dir/writ/lisp_problems.html Xah ? http://xahlee.org/ ? From news123 at free.fr Sun Dec 7 06:43:13 2008 From: news123 at free.fr (News123) Date: Sun, 07 Dec 2008 12:43:13 +0100 Subject: Guido's new method definition idea In-Reply-To: References: <493abe2e$0$15998$426a34cc@news.free.fr> Message-ID: <493bb6d1$0$10599$426a74cc@news.free.fr> Sorry Dennis, I don't understand your answer. I'm not very knowledgable with all the OO vocabulary, but just use OO. self.a , self.b , self.c are stored in the object and could later be used by other object-methods. like def print_a_b_c(self): print self,a,self.b,self.c the name 'class_elements' was just a suggestion it could be also something like 'auto_prepend_self' or whatever. bye N Dennis Lee Bieber wrote: > On Sat, 06 Dec 2008 19:02:22 +0100, News123 declaimed > the following in comp.lang.python: > > >> example: >> class C: >> class_elements a,b,c,d >> >> def method(self,arg): >> global d >> a,b,c = arg[0..3] >> d = a + b >> self.e = a + d >> >> instead of >> class C: >> def method(self,arg): >> self.a,self.b,self.c,self.d = arg[0..4] >> self.e = self.a + self.b >> > I would declare this a poor example, since a, b, c, aren't used as > attributes -- they are just invocation locals. From wmacintosh91834 at live.ca Mon Dec 8 21:42:58 2008 From: wmacintosh91834 at live.ca (Wesley MacIntosh) Date: Mon, 08 Dec 2008 21:42:58 -0500 Subject: Mathematica 7 compares to other languages In-Reply-To: <8947211d-2ee8-403a-8c8a-c7599aea5f80@k24g2000pri.googlegroups.com> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> <0201522a-b15a-4401-a208-5d9af70bdd74@w24g2000prd.googlegroups.com> <8947211d-2ee8-403a-8c8a-c7599aea5f80@k24g2000pri.googlegroups.com> Message-ID: A flamer wrote: > A moron, wrote: [snip] > my machine (PPC Mac, OSX 10.4.x). Well, that explains a great deal. Actually, I suspect all these newsgroups are being trolled. From tjreedy at udel.edu Sat Dec 6 13:49:47 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 06 Dec 2008 13:49:47 -0500 Subject: operators as variables In-Reply-To: <103920.71204.qm@web26006.mail.ukl.yahoo.com> References: <103920.71204.qm@web26006.mail.ukl.yahoo.com> Message-ID: macc_200 wrote: > Hi, > just starting programming and have an elementary question after playing > around with lists but cannot find the answer with googling. > I have a list of variables and I would like some of those variables to > be integers and some to be operators so the list would look something > like [5 * 4 - 4 + 6] and then be able to evaluate the result (i.e. get > 10). How do you make the interpreter see the operator as that instead > of a string and just echo the list back to me. I am not sure what you actually want to do, but the following may help: 1. Strings can be evaluated. 2. Operators are syntax sugar for functions. The functions are available in the operator module. IDLE 3.0 >>> eval('5 * 4 - 4 + 6') 22 >>> import operator as op >>> op.add(2,3) 5 tjr From timr at probo.com Wed Dec 31 02:39:59 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 31 Dec 2008 07:39:59 GMT Subject: why cannot assign to function call References: <495867C2.7080807@gmail.com> <5e807c67-7d97-4b8a-8c5f-a3b97f5c5003@i20g2000prf.googlegroups.com> <5fb29c80-a6a4-4cb4-aa62-0d2aeb437662@o4g2000pra.googlegroups.com> Message-ID: Aaron Brady wrote: > >I think the problem goes deeper than just English. In any language >that has a plural, the propositions in question come out as, 'one >thing is two things' or 'two things are one thing'. According to some >rules, these are ungrammatical sentences, due to plurality >disagreement. Ex: > >The Morning Star is ... >The Evening Star is ... >*The Morning Star and The Evening Star is... >*The Morning Star and The Evening Star are... > >Neither of the latter two is correct. (* marks ungrammatical.) As >such, the listener isn't sure what meaning to take. This is taking a serious twist into off-topicness, but I need to dispute this. I will assert that the 4th line is, in fact, grammatically correct, modulo the capitalization of the second "The". The fragment is clearly of the form "X and Y are...", and regardless of the substitution of X and Y, the plurality of the subject agrees with the verb. The Morning Star and the Evening Star are bright tonight. Ignoring the fact that we can't see both at the same time, why is the meaning of that unclear? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From castironpi at gmail.com Tue Dec 9 11:30:26 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 9 Dec 2008 08:30:26 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> Message-ID: On Dec 9, 8:28?am, MRAB wrote: snip > In some languages (I think Delphi is one of them - it's been a while!) > some words which would normally be identifiers have a special meaning in > certain contexts, but the syntax precludes any ambiguity, and not in a > difficult way. "as" in Python was one of those. > > I certainly wouldn't want something like PL/I, where "IF", "THEN" and > "ELSE" could be identifiers, so you could have code like: > > ? ? ?IF IF = THEN THEN > ? ? ? ? ?THEN = ELSE; > ? ? ?ELSE > ? ? ? ? ?ELSE = IF; > > See http://en.wikipedia.org/wiki/PL/I_(programming_language). snip The following are semantically equivalent: I certainly wouldn't want something like PL/I, where "IF", "THEN" and "ELSE" could be identifiers. I wouldn't want something like PL/I, where "IF", "THEN" and "ELSE" could be identifiers. That is, 'certainly' doesn't change the meaning of your statement any. You wouldn't want it, but King George III didn't want the American Revolution. You wouldn't want it. What does that mean for me (the generic reader), and Python? What can I learn from that fact? From arkanes at gmail.com Thu Dec 11 14:02:26 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 11 Dec 2008 13:02:26 -0600 Subject: Call by reference in SWIG? In-Reply-To: <9D295CD0-2DA3-4572-A2A5-57301D67BEED@strout.net> References: <9D295CD0-2DA3-4572-A2A5-57301D67BEED@strout.net> Message-ID: <4866bea60812111102t7780a613lede2ab07ea3db8ef@mail.gmail.com> On Thu, Dec 11, 2008 at 9:43 AM, Joe Strout wrote: > On Dec 10, 2008, at 10:19 PM, Nok wrote: > >> I can't get call-by-reference functions to work in SWIG... > > Python doesn't have any call-by-reference support at all [1], so I'm not > surprised that a straight translation of the call-by-reference C function > doesn't work. > > Unfortunately I don't know enough about SWIG to suggest a work-around. > Hopefully someone more versed in SWIG will have a bright idea. If you > don't find anything in the Python space, you might try poking around in Java > references, since Java has the same call semantics as Python. > I'm not sure if SWIG has tools to do this for you or if you need to do the mapping by hand, but the usual idiom is to translate them into return values (keeping the original arg if the passed in value matters also). From feinepost at bluewin.ch Tue Dec 9 02:32:19 2008 From: feinepost at bluewin.ch (feinepost at bluewin.ch) Date: Tue, 9 Dec 2008 08:32:19 +0100 Subject: Python & LEGO Mindstorm control... Message-ID: <000001c959d0$49b1f9c0$dd15ed40$@ch> Hi Toni Meyer, I would be quite interested in your Python extension to send ir signals to the rcx. I am quite new to this stuff, hope I'll understand what you did? Could you send it to me? Thanks a lot! Daniel Rupp -------------- next part -------------- An HTML attachment was scrubbed... URL: From wuwei23 at gmail.com Thu Dec 11 12:25:16 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 11 Dec 2008 09:25:16 -0800 (PST) Subject: Preventing execution of a method References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> <764daeef-bfbe-411a-8521-bb114321e4ac@b38g2000prf.googlegroups.com> Message-ID: <19304f8c-e34f-4aa9-8df2-6a7d3553007a@e1g2000pra.googlegroups.com> On Dec 12, 3:22?am, alex23 wrote: > On Dec 12, 2:35?am, rdmur... at bitdance.com wrote: > > > There is, however, also the possibility of prefixing the method name > > with '__'. ?The invokes 'name mangling', which makes it more difficult > > (though not impossible, the idea is to avoid accidents) for the method > > to be called from outside the class. > > That only works for methods, it has no effect on functions or classes > within modules: And of course -now- I realise that the OP was asking for protecting methods. Please disregard my last post :) From timr at probo.com Sun Dec 28 00:13:14 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 28 Dec 2008 05:13:14 GMT Subject: strange behavior of math.sqrt() in new 3.0 version References: Message-ID: Scott David Daniels wrote: > >I avoid using single-letter variables except where I know the types >from the name (so I use i, j, k, l, m, n as integers, s as string, >and w, x, y, and z I am a little looser with (but usually float or >complex). It's amazing to me that Fortran continues to live on in the hearts and minds of today's programmers. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From dfnsonfsduifb at gmx.de Sun Dec 7 10:05:53 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Sun, 07 Dec 2008 16:05:53 +0100 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: References: <5u8o06xbqf.ln2@joeserver.homelan.net> <1mmq06x4g6.ln2@joeserver.homelan.net> Message-ID: John Machin schrieb: > He did. Ugly stuff using readline() :-) Should still work, though. Well, well, I'm a C kinda guy used to while (fgets(b, sizeof(b), f)) kinda loops :-) But, seriously - I find that whole "while True:" and "if line == """ construct ugly as hell, too. How can reading a file line by line be achieved in a more pythonic kind of way? Regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From sgeiger at ncee.net Wed Dec 3 09:22:28 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Wed, 03 Dec 2008 09:22:28 -0500 Subject: generating a liste of characters In-Reply-To: References: Message-ID: <49369624.7020103@ncee.net> import string alphabet=list(string.letters[0:26]) print alphabet Yves Dorfsman wrote: > Is there any built in way to generate a list of characters, something > along the line of range('a'-'z') ? > > Right now I am using: > > chars = [ chr(l) for l in range(0x30, 0x3a) ] # 0 - 9 > chars += [ chr(l) for l in range(0x41, 0x5b) ] # A - Z > chars += [ chr(l) for l in range(0x61, 0x7b) ] # a - z > > Is there a better, more straight forward way of doing that ? > > > > Thanks. > > > > Yves. > http://www.sollers.ca/blog/2008/swappiness > http://www.sollers.ca/blog/2008/swappiness/.fr > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From steve at REMOVE-THIS-cybersource.com.au Thu Dec 18 20:15:35 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2008 01:15:35 GMT Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> <6qv7kfFeuf65U1@mid.uni-berlin.de> <6qv9v4Ff1lv9U1@mid.uni-berlin.de> Message-ID: <015aed12$0$20656$c3e8da3@news.astraweb.com> On Thu, 18 Dec 2008 22:11:27 -0200, Gabriel Genellina wrote: > En Thu, 18 Dec 2008 14:05:32 -0200, Mikael Olofsson > escribi?: ... >> If I ever wanted __str__ and __repr__ to return the same thing, I would >> make them equal: >> >> def __str__(self): >> return 'whatever you want' >> __repr__ = __str__ >> >> That makes it more obvious to me what's going on. As a bonus, it saves >> one method call for every repr call. > > It's even easier to define only __repr__, __str__ defaults to it: Easier, yes, but less obvious. I can never remember whether __repr__ calls __str__ or __str__ calls __repr__ if one or the other is missing. And it costs a failed method lookup. The method lookup is a micro-optimization, and therefore not important, but as far as I'm concerned the extra clarity of doing __repr__ = __str__ is valuable. -- Steven From digitig at gmail.com Mon Dec 15 09:11:20 2008 From: digitig at gmail.com (Tim Rowe) Date: Mon, 15 Dec 2008 14:11:20 +0000 Subject: 1 or 1/0 doesn't raise an exception In-Reply-To: <8972c415-2fbb-479f-8a03-b8b29b20ac42@g38g2000yqn.googlegroups.com> References: <49446E39.6020807@tim.thechases.com> <8972c415-2fbb-479f-8a03-b8b29b20ac42@g38g2000yqn.googlegroups.com> Message-ID: Unfortunately, >>>> bool('Ruby totally pwn3s Python!') > True Using Python is not total protection against buggy programs ;-) -- Tim Rowe From ethan at stoneleaf.us Mon Dec 8 02:41:48 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Sun, 07 Dec 2008 23:41:48 -0800 Subject: datetime and the rich-companison operators Message-ID: <493CCFBC.90104@stoneleaf.us> Greetings All! I am implementing a NullDate class in order to mirror dates and datetimes that have no value (yes, this is for my dbf module :) I'm still a bit fuzzy about class methods, hashing, and __new__, but my question of the moment is this: it seems to me that with two dates or datetimes, they should either be equal, or one should precede the other, and this can be accomplished quite handily with __cmp__... so does anyone know why the rich comparisons were used in the datetime module? Was it simply a style choice, or is something being handled that __cmp__ couldn't cope with? Thanks in advance! ~ethan~ From steve at REMOVE-THIS-cybersource.com.au Sat Dec 20 21:49:43 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Dec 2008 02:49:43 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <015d9ca5$0$20656$c3e8da3@news.astraweb.com> <60b419d3-4cbc-4bba-af79-a6d6146ac472@e6g2000vbe.googlegroups.com> Message-ID: <015da611$0$20656$c3e8da3@news.astraweb.com> On Sat, 20 Dec 2008 18:23:00 -0800, r wrote: > Answering a question with a question, that leaves me with a question of > my own?? > >> Instead of just whinging, how about making a suggestion to fix it? Go >> on, sit down for an hour or ten and try to work out how a BINARY >> OPERATOR like % (that means it can only take TWO arguments) can deal >> with an arbitrary number of arguments, *without* having any special >> cases. > > Instead of being a blind fanboy and chastising everyone who dares to > question pydev, Guido, or YOU... why don't you offer a good rebuttal? Because I thought it was obvious even you could see it. I'm disappointed to be proven wrong. A binary operator can only take two arguments: one on the left, and one on the right: 2 + 3 5 * 7 x == 2 "%i" % 7 The typical use-case for string formatting operations requires more than two arguments. Since % is a binary operator, it can only take two arguments. One of those arguments must be the template string, so the other argument has to wrap all the rest of the arguments into one object: "The %s ate %d slices of %s." % ("python", 7, "spam") Python could have insisted that even single arguments be wrapped in a tuple: "%s" % ("python",) At the cost of breaking backwards compatibility, that would solve the problem of treating tuples as a special case, but it seems wasteful and silly to be forced to write this: "The answer is: %d" % (5,) instead of "The answer is: %d" % 5 especially when people will invariably leave out the comma and then complain about the "wart" or "bug" that: "The answer is: %d" % (5) doesn't do what they expect. So tuples are treated as a special case: you only need to wrap a single argument in a tuple if that argument itself is a tuple: "%s" % ((0, 1, 2),) and everything else just works as you would expect. Again, at the cost of breaking backwards compatibility, Python could change the special case from tuples to something else, but what? And why bother? There will always be a special case, one way or another. Consequently, there is no way to "fix" the special casing of tuples without just shifting the problem. The problem is fundamental to the nature of binary operators: you can't fit an arbitrary number of arguments into two places (the left hand side, and the right hand side) of the % operator without having to special case something. The real solution is to stop trying to force arbitrary numbers of arguments into a single place, and instead use a function or method that takes multiple arguments. That's what the "".format() method and the format() function do. -- Steven From wuwei23 at gmail.com Fri Dec 12 04:45:55 2008 From: wuwei23 at gmail.com (alex23) Date: Fri, 12 Dec 2008 01:45:55 -0800 (PST) Subject: Removing None objects from a sequence References: Message-ID: On Dec 12, 7:18?pm, "Filip Gruszczy?ski" wrote: > Hi! > > I would like to iterate over a sequence nad ignore all None objects. > The most obvious way is explicitly checking if element is not None, > but it takes too much space. And I would like to get something faster. > I can use > [ sth for sth in self.__sth if not sth is None ], but I don't know if > that's the best way. I checked itertools, but the only thing that > seemed ok, was ifilter - this requires seperate function though, so > doesn't seem too short. How can I get it the shortest and fastest way? Rather than a list comprehension, use a generator expression: for item in (x for x in sequence if x is not None): do_something(x) This doesn't generate the intermediate list with None elements removed, rather it steps one at a time through the original sequence and only returns the non-None elements. From steve at REMOVE-THIS-cybersource.com.au Thu Dec 4 10:48:33 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Dec 2008 15:48:33 GMT Subject: Python Runtime Method Call Binding References: Message-ID: <0147f396$0$20670$c3e8da3@news.astraweb.com> On Thu, 04 Dec 2008 06:23:28 -0800, k3xji wrote: > Hi, > > Is there a way to hook a function call in python? I know __getattr__ is > doing for variables, What do you mean "variables"? Do you mean attributes? > it is giving us a chance before a field is > initialized. What field? Is a field the same as a variable, or something else? > Do we have same functionality for methods? Yes, methods are attributes too, they are reached by the exact same mechanism as any other attribute. Any object with a __call__ method can be called. Normally you create objects with a __call__ method by using def or lambda. > Example: > > class Foo(object): > def __call_method__(self, ...) # just pseudo > print 'A method is called in object...' > > f = Foo() > f.test_method() > > I think you understand my point. I wish I did. It might have helped if you actually showed the expected output of your "test_method", instead of expecting us to *guess* what you expect to happen. I'm going to guess what you mean, and show you one possible solution. Read it carefully: it shows three examples of __getattr__, starting from the simplest to the relatively complicated. class Parrot(object): def __getattr__(self, name): if name == "colour": return "red" elif name == "talk": return lambda x: "Hi, I'm %s the talking parrot" % x elif name == "speak": class Birdy(object): def __init__(self, name): self.name = name def __call__(self): return "I'm the talking Parrot %s" % self.name return Birdy('Fred') else: raise AttributeError And in use: >>> p = Parrot() >>> p.colour 'red' >>> p.talk # get the attribute "talk" at 0x81fab1c> >>> >>> p.talk("Fred") # call the attribute (method) "talk" "Hi, I'm Fred the talking parrot" >>> >>> p.speak <__main__.Birdy object at 0x820076c> >>> p.speak() "I'm the talking Parrot Fred" -- Steven From pavlovevidence at gmail.com Thu Dec 25 17:53:51 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 25 Dec 2008 14:53:51 -0800 (PST) Subject: Exec inside a class method to call other class methods? References: Message-ID: On Dec 25, 12:22?pm, Matthew Dubins wrote: > Hello all, > > I have made a python script to upload contact information from an excel > worksheet to an online database. ?One part of the program that really > tripped me up was when I wanted to call specific class methods that I > had made to deal with specific types of contact information (Parent's > name, Child's name, Phone #, etc). ?My first thought was to make it easy > using the exec statement. Bad idea. You should not use exec and eval unless it's your intention to allow the user to run arbitrary Python code. Any other time you think you need to use exec (such as when constructing an attribute name), you should find out whether there's another way to do it, and there usually is. Such is the case here; there is a function, getattr, that does what you want. See below. > The code (a method within a class) looked like this: > ---------- > def parse(self, data, data_type) > ? ? exec "self.__parse_%s(data)" % data_type > ---------- I presume you're aware that the double underscore is a sort of private variable. It causes the Python compiler to mangle the name when used inside a class definition (it converts __parse_email to _Parser__parse_email under the covers, assuming Parser is the class name). Well, it turns out that the Python compiler doesn't know that the string in the exec statement is part of the class, so it doesn't mangle the name for you. If you want to get the method name from within the exec statement, you have to mangle it by hand, like so: def parse(self,data,data_ype): exec "self._Parser__parse_%s(data)" % data_type However, you shouldn't do that. Instead, use getattr, which is a function that was designed exactly for that purpose, and is much less of a security risk. def parse(self,data,data_ype): method = getattr(self,"_Parser__parse_%s" % data_type) method(data) Note that you still have to use the mangled version of the name with getattr (getattr doesn't know it's inside the class, either). And, although this is much safer than exec, you should still be wary of passing user input into it. Here is why you shouldn't use exec for this. You say this program reads data from a spreadsheet. What would happen if, in the data type field, a malicious user were to enter the following string (without surrounding quotes): "email(); import os; os.system('format c:');" Your exec statement would blindly execute this, oops, it happened to format your hard disk. exec and eval are prone to security holes like this, and they usually entail a performance penalty (since the compiler has to be invoked for every call), so please use them only what they were intended for. Carl Banks From gagsl-py2 at yahoo.com.ar Sun Dec 28 23:33:19 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Dec 2008 02:33:19 -0200 Subject: How to "kill" orphaned threads at program exit References: Message-ID: En Sun, 28 Dec 2008 15:47:24 -0200, Roy Smith escribi?: > In article > , > "Giampaolo Rodola'" wrote: > >> I know that it's not possible to "kill" threads but I'm wondering if >> does exist some workaround for my problem. >> I have a test suite which does a massive usage of threads. >> Sometimes happens that one test fails, the test suite keeps running >> until the end, and when it's finished the program hangs on and the >> only way to stop is to kill it manually. > > You don't say how you're creating your threads, so I'll assume you're > using > threading.Thread(). After creating each thread, and before calling > start() > on it, call setDaemon(True). The hard part is, then, to figure out some condition for the non-daemon thread to wait for before exiting. As a last resort -let's say, after waiting for N seconds for all threads to exit- one can use PyThreadState_SetAsyncExc to "inject" an exception into the unfinished threads. I think there is a recipe in the Python Cookbook for doing that using ctypes. -- Gabriel Genellina From google at mrabarnett.plus.com Fri Dec 19 21:19:24 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 20 Dec 2008 02:19:24 +0000 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <015c4890$0$20656$c3e8da3@news.astraweb.com> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> <6r25ckFejl4vU1@mid.individual.net> <015c4890$0$20656$c3e8da3@news.astraweb.com> Message-ID: <494C562C.1070301@mrabarnett.plus.com> Steven D'Aprano wrote: > On Fri, 19 Dec 2008 18:53:22 +0100, Thomas Heller wrote: > >> Steve Holden schrieb: >>> Thomas Heller wrote: >>>> Question from a non-native english speaker: is this now valid english? >>>> >>>> "One of Python?s great strengths" >>>> ^ >>>> "and also teaches Python?s functional programming features" >>>> ^ >>>> "The book?s approach is wholly practical" >>>> ^ >>> It always has been valid English. The apostrophe is only omitted from >>> personal pronouns (hers, its, and so on). >> I see, thanks. But, is the apostrophe optional in the above fragments? > > No. In English, you indicate possessives in one of two ways: > > The approach of the book is wholly practical. > The book's approach is wholly practical. > > In the second form, the apostrophe is always needed, with a couple of > exceptions. The first exception is personal pronouns: > > My approach is wholly practical. > His approach is wholly practical. > Its approach is wholly practical. > > (The third one often gives even native English speakers trouble, with > confusion between the contraction "it's" (it is) and the possessive > "its".) > > The second exception is if the word ends with an S. In British English, > you put the apostrophe after the S: > > Thomas' approach is wholly practical. > > In American English, they often (but not always) add an extra S: > > Thomas's approach is wholly practical. > > which in my opinion is logical but ugly and should be avoided. > There's disagreement on the subject. A simple rule is to follow speech: if you say /tomasIz/ (as I do) then add "'s", therefore "Thomas's". From Ron.Barak at lsi.com Tue Dec 16 08:35:27 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Tue, 16 Dec 2008 13:35:27 +0000 Subject: String slices work only for first string character ? In-Reply-To: References: Message-ID: <7F0503CD69378F49BE0DC30661C6CCF60249410A@enbmail01.lsi.com> Hi, Can any one explain why the following string slice works only for the first character, but not for any other ? $ cat /tmp/tmp.py #!/usr/bin/env python data = 'F0023209006-0101' print data print "|"+data[0:1]+"|" print "|"+data[1:1]+"|" print "|"+data[2:1]+"|" $ python `cygpath -w /tmp/tmp.py` F0023209006-0101 |F| || || $ Thanks, Ron. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Scott.Daniels at Acm.Org Thu Dec 18 16:29:44 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 18 Dec 2008 13:29:44 -0800 Subject: confused about __str__ vs. __repr__ In-Reply-To: References: <494A5ACA.8060205@wildenhain.de> Message-ID: J. Cliff Dyer wrote: > ... how an object prints itself is up to that object and that object alone.... > If I wanted to implement a list-like class that doesn't show it's elements at > all when printed, but instead shows its length, I am free to do so. > For example: > >>>> hl = HiddenList(1,2,3) >>>> hl > >>>> hl[1] > 2 > > (Implementation of HiddenList left as an exercise for the reader.) And just so some of you who wonder how hard this implementation is: (2.4.X, 2.5.X, 2.6.X): class HiddenList(list): def __repr__(self): return '<%s object: length=%s>' % ( type(self).__name__, len(self)) (3.0): class HiddenList(list): def __repr__(self): return '<{0} object: length={1}>'.format( type(self).__name__, len(self)) --Scott David Daniels Scott.Daniels at Acm.Org From arnodel at googlemail.com Thu Dec 4 12:14:17 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 04 Dec 2008 17:14:17 +0000 Subject: simplest way to strip a comment from the end of a line? References: Message-ID: Joe Strout writes: > I have lines in a config file which can end with a comment (delimited > by # as in Python), but which may also contain string literals > (delimited by double quotes). A comment delimiter within a string > literal doesn't count. Is there any easy way to strip off such a > comment, or do I need to use a loop to find each # and then count the > quotation marks to its left? > > Thanks, > - Joe FWIW this is what comes to mind. >>> def strip_comment(line): ... i = -1 ... while True: ... i = line.find('#', i+1) ... if i == -1: ... return line ... if line.count('"', 0, i) % 2 == 0: ... return line[:i] ... >>> strip_comment('foo=1 # set foo') 'foo=1 ' >>> strip_comment('foo="bar" # set foo') 'foo="bar" ' >>> strip_comment('foo="bar # set foo"') 'foo="bar # set foo"' >>> strip_comment('foo="bar # set foo" # set foo') 'foo="bar # set foo" ' >>> strip_comment('foo="bar # set foo" + "baz ## fubar" # set foo') 'foo="bar # set foo" + "baz ## fubar" ' >>> strip_comment('foo="bar # set foo" + "baz ## fubar # set foo"') 'foo="bar # set foo" + "baz ## fubar # set foo"' >>> strip_comment(r'foo="bar\" baz" # this breaks') 'foo="bar\\" baz" # this breaks' As the last example shows, it won't work if there is an escaped double quote in the string. -- Arnaud From castironpi at gmail.com Sun Dec 21 18:17:12 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 21 Dec 2008 15:17:12 -0800 (PST) Subject: Are python objects thread-safe? References: Message-ID: <012b2014-de2a-498f-adbf-43f1727a109f@b41g2000pra.googlegroups.com> On Dec 21, 12:51?pm, RajNewbie wrote: > Say, I have two threads, updating the same dictionary object - but for > different parameters: > Please find an example below: > a = {file1Data : '', > ? ? ? ?file2Data : ''} > > Now, I send it to two different threads, both of which are looping > infinitely: > In thread1: > a['file1Data'] = open(filename1).read > ? ? ? ? ? and > in thread2: > a['file2Data'] = open(filename2).read > > My question is ?- is this object threadsafe? - since we are working on > two different parameters in the object. Or should I have to block the > whole object? Threads take turns with the Global Interpreter Lock, so a Python thread is sure to have the GIL before it calls a method on some object. So yes, with the rare exception (that I don't want to not mention) that if you've got non-Python threads running in your process somehow, they don't make the guarantee of enforcing that. From zac256 at gmail.com Thu Dec 4 13:03:40 2008 From: zac256 at gmail.com (Zac Burns) Date: Thu, 4 Dec 2008 10:03:40 -0800 Subject: Overriding a method at the instance level on a subclass of a builtin type In-Reply-To: References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> Message-ID: <333edbe80812041003i2e653d6dp31e64eab7bb62701@mail.gmail.com> Ok... but why are the special methods handled differently? -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer (Digital Overlord) Zindagi Games On Thu, Dec 4, 2008 at 9:57 AM, George Sakkis wrote: > On Dec 4, 12:31 pm, Arnaud Delobelle wrote: >> "Zac Burns" writes: >> > The class method seems to be the most promising, however I have more >> > 'state' methods to worry about so I might end up building new classes >> > on the fly rather than have a class per permutation of states! Now the >> > code isn't quite as clear as I thought it was going to be. >> >> > It seems unfortunate to me that methods are always looked up on the >> > class for new style objects. Was this done for speed reasons? >> >> It's only special methods such as __getitem__, ... >> >> You can override normal method on a per-object basis just by adding a >> callable attribute with its name to the object: >> >> >>> class A(object): >> >> ... def foo(self): print 'A.foo' >> ...>>> a = A() >> >>> a.foo() >> A.foo >> >>> def a_foo(): print 'a.foo' >> ... >> >>> a.foo = a_foo >> >>> a.foo() > > Note that the overriden "method" here is a plain function; it doesn't > take self as the first argument. If you want to bind it to a callable > that expects the first argument to be self, you have to bind > explicitly self to the object: > >>>> def a_foo(self): print 'a.foo' >>>> a.foo = a_foo >>>> a.foo() > TypeError: a_foo() takes exactly 1 argument (0 given) >>>> from functools import partial >>>> a.foo = partial(a_foo,a) >>>> a.foo() > a_foo > > George > -- > http://mail.python.org/mailman/listinfo/python-list > From castironpi at gmail.com Sun Dec 21 06:37:50 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 21 Dec 2008 03:37:50 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: On Dec 20, 8:49?pm, MRAB wrote: > Aaron Brady wrote: > > On Dec 20, 7:38 pm, Steven D'Aprano > cybersource.com.au> wrote: > >> Instead of just whinging, how about making a suggestion to fix it? Go on, > >> sit down for an hour or ten and try to work out how a BINARY OPERATOR > >> like % (that means it can only take TWO arguments) can deal with an > >> arbitrary number of arguments, *without* having any special cases. > > >> Go on. Take your time. I'll be waiting. > > > Hi, not to take sides, but, there is a possibility. > > > This behavior is currently legal: > > >>>> "%i %%i" % 0 % 1 > > '0 1' > > > So, just extend it. ?(Unproduced.) > > >>>> "%i %i" % 0 % 1 > > '0 1' > >>>> "%r %i" % (2, 3, 4) % 1 > > '(2, 3, 4) 1' > >>>> "%r %i" % (2, 3, 4) > > '(2, 3, 4) %i' > > > Which is quite clever and way ahead of its (posessive) time. > > A couple of problems: > > 1. How do you handle a literal '%'? If you just double up then you'll > need to fix the string after all your substitutions. > > 2. What if a substitution introduces a '%'? > > I suppose a possible solution would be to introduce a special format > string, including a literal, eg: > > ? ? ?f"%r %i" % (2, 3, 4) % 1 > > and then convert the result to a true string: > > ? ? ?print(str(f"%r %i" % (2, 3, 4) % 1)) > > (although print() would call __str__ anyway). > > The format string would track where the last substitution occurred. > > Hmm... I think I'll just learn the new method. :-) Now that I'm fighting 'r's war for him/her... Um, here's one possibility. On the first interpolation, flags are noted and stored apart from subsequent interpolations. Then, use a sentinel to terminate the interpolation. (Unproduced.) >>> "%r %i" % ( 2, 3 ) % 0 '(2, 3) 0' >>> "%% %r" % ( 2, 3 ) % str.interp_end '% (2, 3)' >>> "%sss%i" % "%d" % 0 '%dss0' The first %s is replaced with %d, but doesn't hijack the '0'. If you want to interpolate the %d, use the sentinel. The sentinel is what causes '%%' to be handled. >>> "%sss%i" % "%d" % 0 % 1 Traceback (most recent call last): File "", line 1, in TypeError: not all arguments converted during string formatting >>> "%sss%i" % "%d" % 0 % str.interp_end % 1 '1ss0' Treating tuples as a special case appears to be the simpler solution, but this, 'chaining', to adopt the term, is still feasible. From jervisau at gmail.com Tue Dec 30 16:09:21 2008 From: jervisau at gmail.com (Jervis Whitley) Date: Wed, 31 Dec 2008 08:09:21 +1100 Subject: embedding python in wxpython In-Reply-To: <495A82D9.3000902@gmail.com> References: <191280cf-ecf9-4135-9737-9923061855d1@t39g2000prh.googlegroups.com> <495A82D9.3000902@gmail.com> Message-ID: <8e63a5ce0812301309p705b2fe0x9ad5d0b039a0dad4@mail.gmail.com> On Wed, Dec 31, 2008 at 7:21 AM, Stef Mientki wrote: > 5lvqbwl02 at sneakemail.com wrote: > >> Hi, I've looked around for a way to allow a python console from within >> a wxPython application, but have only found stuff on embedded/ >> extending python with C/C++ or wxWidgets in C++, but not wxPython. >> >> Is this easy to do? Can someone point me in the right direction? >> >> Also, typically when you embed a scripting language into a larger >> application, how do you get the console environment to share data with >> the larger application? >> >> For instance, if the application has some gui stuff (for example >> clicking on a object and dragging it around), how do you get >> "object.select(x,y)" to print out on the console, and vice-versa: the >> object gets selected if the user types "object.select(x,y)"? >> >> I'd like the console to be a bidirectional representation of what's >> going on in the gui, plus a general purpose evaluation environment >> where you can manipulate application data via some api which is >> automatically exposed to the console when the application opens up. >> >> I'm looking for high-level hints/strategies/directions. >> >> > If you're looking for "high-level", > I don't understand why you want to see what's going on in the gui, > as I see the gui just a tool to control the real data. > For a pretty high level data manipulation, > something like PyLab_Works ? > http://code.google.com/p/pylab-works/ > > cheers, > Stef > > -- > http://mail.python.org/mailman/listinfo/python-list > Try checking out the wxPython demo package. There is an example of a widget inspection tool in the help menu. This tool has an embedded python console and allows introspection of live widgets and sizers in an application. Cheers, Jervis -------------- next part -------------- An HTML attachment was scrubbed... URL: From kkylheku at gmail.com Wed Dec 3 23:54:31 2008 From: kkylheku at gmail.com (Kaz Kylheku) Date: Thu, 4 Dec 2008 04:54:31 +0000 (UTC) Subject: Mathematica 7 compares to other languages References: <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <4b6c3304-2396-4d35-a06f-e5d693cbbb12@f13g2000yqj.googlegroups.com> Message-ID: <20081219033030.559@gmail.com> On 2008-12-04, J?rgen Exner wrote: > toby wrote: >>On Dec 3, 4:15 pm, Xah Lee wrote: >>> On Dec 3, 8:24 am, Jon Harrop wrote: >>> >>> > My example demonstrates several of Mathematica's fundamental limitations. >>> >>> enough babble Jon. >>> >>> Come flying $5 to my paypal account, and i'll give you real code, >> >>I'll give you $5 to go away > > if you add "and never come back" then count me in, too. Really? I will trade you one Xah Lee for three Jon Harrops and I will even throw in a free William James. From sri_annauni at yahoo.co.in Wed Dec 3 05:40:30 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Wed, 3 Dec 2008 16:10:30 +0530 (IST) Subject: How to send body and attachements in an email message? Message-ID: <140952.77709.qm@web7901.mail.in.yahoo.com> HI, I would like to send an email message with body-content 'test' and?an attachment. The snippet i used is: outer = email.mime.multipart.MIMEMultipart() msg1 = email.mime.text.MIMEText(, _subtype = 'text') msg1.add_header('Content-Disposition', 'attachment') outer.attach(msg1) body = email.mime.text.MIMEText(, _subtype = 'text') outer.attach(body) smtp_client = smtplib.SMTP() smtp_client.connect() smtp_client.sendmail(, , outer.as_string()) smtp_client.close() If i do like above, i am receiving the body also as an attachment. How to set body to Multipart email message? Thanks, Srini Add more friends to your messenger and enjoy! Go to http://messenger.yahoo.com/invite/ From mynthon1 at gmail.com Tue Dec 30 04:04:33 2008 From: mynthon1 at gmail.com (mynthon) Date: Tue, 30 Dec 2008 01:04:33 -0800 (PST) Subject: wxPython.button.disabled still catching clicks References: <8cb6da6a-7df4-4cce-a28e-385448a25b26@w39g2000prb.googlegroups.com> <1ff2aad7-29a1-48cd-b3de-29fab443aa3e@u18g2000pro.googlegroups.com> <0e9a5ab7-8078-4d12-adb2-aaf92a78b007@s9g2000prm.googlegroups.com> Message-ID: <007bab05-6451-48c8-94bc-a34631795e32@v5g2000prm.googlegroups.com> On Dec 23, 6:12?pm, Mike Driscoll wrote: > On Dec 23, 7:27?am,mynthon wrote: > > > > > On Dec 23, 11:58?am, Aaron Brady wrote: > > > > On Dec 23, 4:50?am,mynthon wrote: > > > > > Hello! (sorry for my english) > > > > > I have a problem with buttons in wxPython. When button is disabled > > > > (by .Disable() or .Enable(False)) it is grayed out but still receive > > > > clicks. > > > > > Eg. i have button that disable itself, runs long action and enable > > > > itself: > > > > > def onClick(self, evt): > > > > ? ? self.btn.Enable(False) > > > > ? ? for i in range (1000): > > > > ? ? ? ? print i > > > > ? ? self.btn.Enable(True) > > > > > when for loop is running button is greyed out and when i click on it > > > > nothing happens but when loop ends another one is started because > > > > button "remebered" thad i click on it when was diabled. My only idea > > > > is to reposition button outside frame instead of disabling it but this > > > > solution is...not good. > > > > > thanks for any help. Ive searched groups, google and it looks that > > > > only i have this problem :) > > > > No, it is very common. ?During your for loop, the loop is dominating > > > the process completely. ?Events are just building up in the app's > > > message queue, and don't get handled until after you yield on control. > > > > If you need to run a long task, look into threading, the OnIdle > > > method, the 'multiprocessing' module, or pump messages during your > > > long task. > > > ok, maybe someone will need it. I dont know how it works because i > > didnt have time to read docs and i cannot explain everything. I used > > google and wxPython demo (in tree: wxpython overview / process and > > events / process) > > > class leftPanel(wx.Panel): > > ? ? def __init__(self, parent, id): > > ? ? ? ? wx.Panel.__init__(self, parent, id, style=wx.BORDER_SUNKEN) > > > ? ? ? ? # here you have to define new process, IDLE event, and > > onPRocessEnd event > > ? ? ? ? self.process = None > > ? ? ? ? self.GetParent().Bind(wx.EVT_IDLE, self.onIdle) > > ? ? ? ? self.Bind(wx.EVT_END_PROCESS, self.onProcessEnd) > > > ? ? ? ? # create button and bind event to it > > ? ? ? ? self.runScriptBtn = wx.Button(self, -1, 'RUN ME!', (10,220)) > > ? ? ? ? self.runScriptBtn.Bind(wx.EVT_BUTTON, self.onClick, > > self.runScriptBtn) > > > ? ? def onClick(self, evt): > > ? ? ? ? # disable button > > ? ? ? ? self.runScriptBtn.Enable(False) > > > ? ? ? ? # here you have to enter command to run > > ? ? ? ? # previusly i heve here exec('pythonmyScript.py') > > ? ? ? ? # but now it will be a subprocess > > ? ? ? ? cmd = 'pythonxxx1.py' > > > ? ? ? ? #create new process > > ? ? ? ? self.process = wx.Process(self) > > > ? ? ? ? # dont know what it is for > > ? ? ? ? self.process.Redirect() > > > ? ? ? ? # execute cmd command > > ? ? ? ? pid = wx.Execute(cmd, wx.EXEC_ASYNC, self.process) > > > ? ? def onIdle(self, evt): > > ? ? ? ? # beacuse this method is called only when app enters idle mode > > ? ? ? ? # the line below is nedded to "simulate" entering idle mode > > ? ? ? ? # dont know how it works but it works > > ? ? ? ? evt.RequestMore(True) > > > ? ? ? ? # here is some code to catch subprocess output > > ? ? ? ? if self.process is not None: > > ? ? ? ? ? ? stream = self.process.GetInputStream() > > ? ? ? ? ? ? if stream.CanRead(): > > ? ? ? ? ? ? ? ? text = stream.read() > > ? ? ? ? ? ? ? ? print text > > > ? ? def onProcessEnd(self, evt): > > ? ? ? ? # here is some code to catch subprocess output > > ? ? ? ? # when it is destroyed > > ? ? ? ? stream = self.process.GetInputStream() > > ? ? ? ? if stream.CanRead(): > > ? ? ? ? ? ? text = stream.read() > > ? ? ? ? ? ? print text > > > ? ? ? ? # dont know it is necessary > > ? ? ? ? self.process.CloseOutput() > > > ? ? ? ? # remove (clear) process object > > ? ? ? ? self.process.Destroy() > > ? ? ? ? self.process = None > > > ? ? ? ? # show button again > > ? ? ? ? self.runScriptBtn.Enable() > > I'm pretty sure there's a better way to do this. If you disable the > button and click on it, you'll notice that it isn't firing events, so > something else is going on here. It seems like the wx.Frame or > wx.Application is queuing the mouse button clicks or something. I > would post to the wxPython mailing list:http://wxpython.org/maillist.php > > They'll be better able to address this and they'll probably have a > simpler solution too. > > Mike I changed it. Now i'm running separate thread instead of process. First example at: http://wiki.wxpython.org/LongRunningTasks From collin.day.0 at gmail.com Thu Dec 18 21:48:08 2008 From: collin.day.0 at gmail.com (Collin D) Date: Thu, 18 Dec 2008 18:48:08 -0800 (PST) Subject: Factoring Polynomials References: <919062f9-765e-4279-aa26-2c130d4deacf@o4g2000pra.googlegroups.com> <4479b464-3a9b-4dd8-bf66-fea7d9471091@n33g2000pri.googlegroups.com> <661fd2d0-251d-4899-a015-8d257310a159@q26g2000prq.googlegroups.com> Message-ID: On Dec 18, 6:41?pm, "Russ P." wrote: > On Dec 18, 6:31?pm, Collin D wrote: > > > > > > > On Dec 18, 6:27?pm, Collin D wrote: > > > > On Dec 18, 6:23?pm, "Russ P." wrote: > > > > > On Dec 18, 6:17?pm, Collin D wrote: > > > > > > On Dec 18, 6:12?pm, Collin D wrote: > > > > > > > On Dec 18, 11:37?am, collin.da... at gmail.com wrote: > > > > > > > > I am trying to write a simple application to factor polynomials. I > > > > > > > wrote (simple) raw_input lines to collect the a, b, and c values from > > > > > > > the user, but I dont know how to implement the quadratic equation > > > > > > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > > > > > > into python. Any ideas? > > > > > > > I completed the code: > > > > > > > #import > > > > > > from math import sqrt > > > > > > > # collect data > > > > > > a = float(raw_input('Type a value: ')) > > > > > > b = float(raw_input('Type b value: ')) > > > > > > c = float(raw_input('Type c value: ')) > > > > > > > # create solver > > > > > > def solver(a,b,c): > > > > > > ? ? if b**2 - 4*a*c < 0: > > > > > > ? ? ? ? return 'No real solution.' > > > > > > ? ? else: > > > > > > ? ? ? ? sol1 = -1 * b + (sqrt(b**2 - 4*a*c)) / 2*a > > > > > > ? ? ? ? sol2 = -1 * b - (sqrt(b**2 - 4*a*c)) / 2*a > > > > > > ? ? ? ? return (sol1, sol2) > > > > > > > # execute > > > > > > print solver(a,b,c) > > > > > > > Thanks to everyone who helped... > > > > > > This really expanded my knowledge on some of the mathematical > > > > > > functions in Python. > > > > > > UPDATE: > > > > > ' > > > > > > #import > > > > > from math import sqrt > > > > > > # collect data > > > > > a = float(raw_input('Type a value: ')) > > > > > b = float(raw_input('Type b value: ')) > > > > > c = float(raw_input('Type c value: ')) > > > > > > # create solver > > > > > def solver(a,b,c): > > > > > ? ? if b**2 - 4*a*c < 0: > > > > > ? ? ? ? return 'No real solution.' > > > > > ? ? else: > > > > > ? ? ? ? sol1 = (-1 * b + (sqrt(b**2 - 4*a*c))) / 2*a > > > > > ? ? ? ? sol2 = (-1 * b - (sqrt(b**2 - 4*a*c))) / 2*a > > > > > ? ? ? ? return (sol1, sol2) > > > > > > # execute > > > > > print solver(a,b,c) > > > > > You need to put your denominator, 2*a, in parens. The way it stands, > > > > you are dividing by 2, then multiplying by a. That's not what you > > > > want. > > > > > Also, for better style, I suggest you compute the discriminanat once > > > > and store it for reuse rather than repeating the expression three > > > > times.- Hide quoted text - > > > > > - Show quoted text - > > > > I see what you mean on the denominator and discriminant. Ill do that.- Hide quoted text - > > > > - Show quoted text - > > > UPDATE: > > > #import > > from math import sqrt > > > # collect data > > a = float(raw_input('Type a value: ')) > > b = float(raw_input('Type b value: ')) > > c = float(raw_input('Type c value: ')) > > > # find discriminant > > disc = b**2 - 4*a*c > > > # create solver > > def solver(a,b,c): > > ? ? if disc < 0: > > ? ? ? ? return 'No real solution.' > > ? ? else: > > ? ? ? ? sol1 = (-1 * b + (sqrt(disc))) / (2*a) > > ? ? ? ? sol2 = (-1 * b - (sqrt(disc))) / (2*a) > > ? ? ? ? return (sol1, sol2) > > > # execute > > print solver(a,b,c) > > A couple of style points. I would use -b rather than -1 * b. Also, you > don't need the else clause. You can simplify it to > > def solver(a, b, c): > > ? ? disc = b**2 - 4 * a * c > > ? ? if disc < 0: return "No real solution." > > ? ? sol1 = (-b + sqrt(disc)) / (2*a) > ? ? sol2 = (-b - sqrt(disc)) / (2*a) > > ? ? return sol1, sol2- Hide quoted text - > > - Show quoted text - UPDATE: #import from math import sqrt # collect data a = float(raw_input('Type a value: ')) b = float(raw_input('Type b value: ')) c = float(raw_input('Type c value: ')) # create solver def solver(a,b,c): disc = b**2 - 4*a*c if disc < 0: return 'No real solution.' else: sol1 = (-b + (sqrt(disc))) / (2*a) sol2 = (-b - (sqrt(disc))) / (2*a) return (sol1, sol2) # execute print solver(a,b,c) From ethan at stoneleaf.us Tue Dec 9 18:43:10 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 09 Dec 2008 15:43:10 -0800 Subject: Don't you just love writing this sort of thing :) In-Reply-To: References: Message-ID: <493F028E.5050608@stoneleaf.us> Lawrence D'Oliveiro wrote: > for \ > Entry \ > in \ > sorted \ > ( > f for f in os.listdir(PatchesDir) if PatchDatePat.search(f) != None > ) \ > : > Patch = (open, gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir, Entry), "r") > ... read from Patch ... > Patch.close() > #end for Not all code has to be written for everyone. Not all code will be read by the masses. Some code you write for yourself... an expression of who you are, how you think... While my own quirks are not as visually entertaining, I think it's another mark in Python's favor that such self-expression is possible, and functional. Yes, Lawrence, I do love writing fun code. ~ethan~ From steve at holdenweb.com Mon Dec 15 10:50:58 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 15 Dec 2008 10:50:58 -0500 Subject: alt.possessive.its.has.no.apostrophe In-Reply-To: <87r649g9dg.fsf@benfinney.id.au> References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> Message-ID: <49467CE2.3060401@holdenweb.com> Ben Finney wrote: > James Stroud writes: > >> Ben Finney wrote: >>> James Stroud writes: >>> >>>> Yes. I think it was the British who decided that the apostrophe >>>> rule for "it" would be reversed from normal usage relative to >>>> just about every other noun. > > It also seems an indefensible claim to say that anyone ?decided? it > would be that way, especially ?the British?. > It's our language, dammit! Ours, ours, ours! This decision was actually taken at a meeting of the Society of British pedants on November 23, 1786. This led to a schism between the British and the newly-independent Americans, who responded by taking the "u" out of colour, valour, and aluminium. >>> Remember that ?it? is a pronoun. I see no reversal: >> Ok. Pronouns are reversed. > > Or, more generally: Pronouns, which are different in just about every > other way from other nouns, are different in this way also. Is that > about right? > Just think of them as "nounpros" and you won't go wrong. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From fetchinson at googlemail.com Wed Dec 17 16:09:04 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 17 Dec 2008 13:09:04 -0800 Subject: something else instead of PIL? In-Reply-To: <47c890dc0812171304u4bfd1d9eq2f55b2681e7302e4@mail.gmail.com> References: <47c890dc0812171304u4bfd1d9eq2f55b2681e7302e4@mail.gmail.com> Message-ID: >> what has happened to PIL? No updates since two years. > > The Python Imaging Library is still current; I guess they just haven't > found any new bugs or seen fit to add new functionality in a while, > though I presume they'll start working on a Python 3.0 port > eventually. That's actually an interesting question. Does anybody know if PIL is being ported to 3.0? Are there such plans? Maybe even code? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From endroussandrodelperkasa at gmail.com Fri Dec 12 07:24:51 2008 From: endroussandrodelperkasa at gmail.com (andrew) Date: Fri, 12 Dec 2008 04:24:51 -0800 (PST) Subject: IF YOU WANT TO LIVE LONGER, YOU SHOULD CHECK THIS!! Message-ID: <0905b402-2630-4057-87eb-11e15b9dad97@d42g2000prb.googlegroups.com> http://www.associatedcontent.com/article/995306/parameningeal_infection_brain_abscess.html?cat=70 From sjmachin at lexicon.net Tue Dec 30 19:22:09 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 30 Dec 2008 16:22:09 -0800 (PST) Subject: get method References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> <495AAB97.5010707@mrabarnett.plus.com> Message-ID: <71508d7a-f678-40ba-801c-0bbfbbab961e@r15g2000prh.googlegroups.com> On Dec 31, 10:58?am, "James Mills" wrote: > On Wed, Dec 31, 2008 at 9:15 AM, MRAB wrote: > > (snip) > > > A while back I posted a Python implementation of 'bag' (also called a > > multiset). The code would then become something like: > > What complexity is this ? The "armchair philosopher" approach: bag has an iteritems method so it's probably using a dict internally in which case a reasonable assumption is that the counting is implemented efficiently ... guess: bag(iterable) is O(len(iterable)) The "crawl through the shrubbery looking for evidence" approach stumbles on the actual code: def __init__(self, iterable=None): self._items = {} if iterable is not None: for item in iterable: self._items[item] = self._items.get(item, 0) + 1 confirming the guess. From yves at zioup.com Wed Dec 3 09:18:32 2008 From: yves at zioup.com (Yves Dorfsman) Date: Wed, 03 Dec 2008 14:18:32 GMT Subject: generating a liste of characters Message-ID: Is there any built in way to generate a list of characters, something along the line of range('a'-'z') ? Right now I am using: chars = [ chr(l) for l in range(0x30, 0x3a) ] # 0 - 9 chars += [ chr(l) for l in range(0x41, 0x5b) ] # A - Z chars += [ chr(l) for l in range(0x61, 0x7b) ] # a - z Is there a better, more straight forward way of doing that ? Thanks. Yves. http://www.sollers.ca/blog/2008/swappiness http://www.sollers.ca/blog/2008/swappiness/.fr From ibpet11 at gmail.com Tue Dec 30 10:30:55 2008 From: ibpet11 at gmail.com (ibpet11 at gmail.com) Date: Tue, 30 Dec 2008 07:30:55 -0800 (PST) Subject: folder extraction Message-ID: how do i get along with this task of extracting multiples folder and generating their names individually in a their respective files as they were generated. From fuzzyman at gmail.com Sun Dec 14 18:03:01 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 14 Dec 2008 15:03:01 -0800 (PST) Subject: Python 3.0 crashes displaying Unicode at interactive prompt References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> Message-ID: <3fad7e29-c9ac-4b2e-aabe-e23a4cc5cb2c@q30g2000prq.googlegroups.com> > That's an interesting definition of crash. You're just like saying: "C > has crashed because I made a bug in my program". In this context, it is > your program that crashes, not python nor C, it is misleading to say so. > > It will be python's crash if: > 1. Python 'segfault'ed > 2. Python interpreter exits before there is instruction to exit (either > implicit (e.g. falling to the last line of the script) or explicit (e.g > sys.exit or raise SystemExit)) > 3. Python core dumped > 4. Python does something that is not documented It seems to me to be a generally accepted term when an application stops due to an unhandled error to say that it crashed. Michael Foord http://www.ironpythoninaction.com/ From org.python.python-list at pooryorick.com Wed Dec 3 09:06:02 2008 From: org.python.python-list at pooryorick.com (=?utf-8?Q?Poor=20Yorick?=) Date: Wed, 03 Dec 2008 14:06:02 +0000 Subject: =?utf-8?B?UHl0aG9uMzogc29ydGluZyBpbWFnZSBvYmplY3RzIGFjY29yZGluZyB0byBhIGNtcCBmdW5jdGlvbg==?= Message-ID: <20081203140602.10205.qmail@s461.sureserver.com> I'm looking for a Python3-compatible way to sort a list of PIL image objects based on a computed difference between the two images. In 2.x, this would work: imagelist.sort(cmp=image_diff(a,b)) Maybe this could be done by creating a new class with the appropriate __lt__, ____gt__, __eq__ methods, but that seems like more work than should be necessary. Any suggestions? -- Yorick From suppertravel at gmail.com Fri Dec 12 15:40:38 2008 From: suppertravel at gmail.com (suppertravel at gmail.com) Date: Fri, 12 Dec 2008 12:40:38 -0800 (PST) Subject: No Scams plz! Read only if you are interested to work from home. Message-ID: <74e37d4a-5389-4ce8-b74f-e8d1ae90380b@e1g2000pra.googlegroups.com> Lowest air fares, tickets, packages, all inclusive, lower than any other agencies, we beat other prices: http://suppertravel.worldventures.com/ Become a travel agent and work from home make $$$$, we even pay for your car payment and mortgage: http://suppertravel.worldventures.biz/ From jcd at sdf.lonestar.org Sun Dec 14 16:55:07 2008 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Sun, 14 Dec 2008 16:55:07 -0500 Subject: the official way of printing unicode strings In-Reply-To: <6qk1o7Fcr01gU3@mid.uni-berlin.de> References: <6qk1o7Fcr01gU3@mid.uni-berlin.de> Message-ID: <20081214215507.GA28375@sdf.lonestar.org> On Sun, 2008-12-14 at 11:16 +0100, Piotr Sobolewski wrote: > Marc 'BlackJack' Rintsch wrote: > > > I'd make that first line: > > sys.stdout = codecs.getwriter('utf-8')(sys.stdout) > > > > Why is it even more cumbersome to execute that line *once* instead > > encoding at every ``print`` statement? > > Oh, maybe it's not cumbersome, but a little bit strange - but sure, I can > get used to it. > > My main problem is that when I use some language I want to use it the way it > is supposed to be used. Usually doing like that saves many problems. > Especially in Python, where there is one official way to do any elementary > task. And I just want to know what is the normal, official way of printing > unicode strings. I mean, the question is not "how can I print the unicode > string" but "how the creators of the language suppose me to print the > unicode string". I couldn't find an answer to this question in docs, so I > hope somebody here knows it. > > So, is it _the_ python way of printing unicode? > The "right way" to print a unicode string is to encode it in the encoding that is appropriate for your needs (which may or may not be UTF-8), and then to print it. What this means in terms of your three examples is that the first and third are correct, and the second is incorrect. The second one breaks when writing to a file, so don't use it. Both the first and third behave in the way that I suggest. The first (print u'foo'.encode('utf-8')) is less cumbersome if you do it once, but the third method (rebinding sys.stdout using codecs.open) is less cumbersome if you'll be doing a lot of printing on stdout. In the end, they are the same method, but one of them introduces another layer of abstraction. If you'll be using more than two print statements that need to be bound to a non-ascii encoding, I'd recommend the third, as it rapidly becomes less cumbersome, the more you print. That said, you should also consider whether you want to rebind sys.stdout or not. It makes your print statements less verbose, but it also loses your reference to the basic stdout. What if you want to print using UTF-8 for a while, but then you need to switch to another encoding later? If you've used a new name, you can still refer back to the original sys.stdout. Right: my_out = codecs.getwriter('utf-8')(sys.stdout) print >> my_out u"Stuff" my_out = codecs.getwriter('ebcdic')(sys.stdout) print >> my_out u"Stuff" Wrong sys.stdout = codecs.getwriter('utf-8')(sys.stdout) print u"Stuff" sys.stdout = codecs.getwriter('ebcdic')(sys.stdout) # Now sys.stdout is geting encoded twice, and you'll probably # get garbage out. :( print u"Stuff" Though I guess this is why the OP is doing: sys.stdout = codecs.getwriter('utf-8')(sys.__stdout__) That avoids the problem by not rebinding the original file object. sys.__stdout__ is still in its original state. Carry on, then. Cheers, Cliff From prologic at shortcircuit.net.au Tue Dec 16 20:54:59 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 17 Dec 2008 11:54:59 +1000 Subject: How to modify a program while it's running? In-Reply-To: <1fe20306-39ff-4169-b49e-5ae5dd8159af@v5g2000prm.googlegroups.com> References: <01584cbd$0$20656$c3e8da3@news.astraweb.com> <1fe20306-39ff-4169-b49e-5ae5dd8159af@v5g2000prm.googlegroups.com> Message-ID: @Aaron Your code and suggestion is way too complicated. Just register your objects. When you need to reload your module, destroy the existing objects and re-creat them. This works well assuming you have a stable running core that maintains the connection and that code doesn't change much. --JamesMills From bdesth.quelquechose at free.quelquepart.fr Sun Dec 7 13:13:18 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 07 Dec 2008 19:13:18 +0100 Subject: Guido's new method definition idea In-Reply-To: References: <493a9fed$0$18973$426a34cc@news.free.fr> Message-ID: <493c1ff6$0$4942$426a34cc@news.free.fr> Daniel Fetchinson a ?crit : (snip) > It doesn't add anything but makes something that exists a bit clearer Err... I fail to see how magically transforming def self.foo(...) into def foo(self, ...) makes anything clearer about what really happens and how Python's object model works. > and friendlier to newbies. I'd rather say "more acceptable to java-brainwashed developpers". From rogerb at rogerbinns.com Sun Dec 7 15:30:01 2008 From: rogerb at rogerbinns.com (Roger Binns) Date: Sun, 07 Dec 2008 12:30:01 -0800 Subject: Source code generation using Python In-Reply-To: <82098706-978f-4920-ac75-57ef3573ac44@x38g2000yqj.googlegroups.com> References: <82098706-978f-4920-ac75-57ef3573ac44@x38g2000yqj.googlegroups.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 ats wrote: > I want to generate 3 different versions of a C++ source code, > basically injecting different flavours of inline assembler depending > on target compiler/CPU. Are you aware that there are also packages that let you generate and call C code from Python on the fly? I find it most productive to write my code in all Python first and to also develop a comprehensive test suite. Then profile and replace selected portions with lower level C code with the tests being able to confirm your code is correct. Here are some packages that take an alternate approach: http://www.cs.tut.fi/~ask/cinpy/ http://code.google.com/p/shedskin/ http://pyinline.sourceforge.net/ http://scipy.org/Weave http://mdevan.nfshost.com/llvm-py/ I like LLVM the most. Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAkk8MkUACgkQmOOfHg372QRhsgCcCUzWHAHmjC1490yYba7c9Xrt DxMAnj/Ur2GoJkQgMrx65hYEqPwKLdVV =CvGB -----END PGP SIGNATURE----- From acerimusdux at comcast.net Wed Dec 10 21:33:51 2008 From: acerimusdux at comcast.net (acerimusdux) Date: Wed, 10 Dec 2008 21:33:51 -0500 Subject: Python is slow In-Reply-To: <7a1e6b94-1618-470c-a7ed-a2a5ada87d30@w24g2000prd.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <4b0f6c1a-9d3f-4fd7-8506-314d29ee87a8@k36g2000yqe.googlegroups.com> <7a1e6b94-1618-470c-a7ed-a2a5ada87d30@w24g2000prd.googlegroups.com> Message-ID: <49407C0F.10509@comcast.net> cm_gui wrote: > You guys are living in denial. > Python is SLOW, especially for web apps. > > Instead of getting mad, why don't get together and come up with a > faster VM/interpreter? > > The emperor doesn't like to be told he is not wearing any clothes? > > > O The one in denial is the one without any evidence to back his assertions. as someone once said, "In God we Trust. All others must have data." For example, the most recent benchmarks from The Computer Language Benchmark Game: http://shootout.alioth.debian.org/u64/benchmark.php?test=all&lang=al http://shootout.alioth.debian.org/u32/benchmark.php?test=all&lang=all http://shootout.alioth.debian.org/gp4/benchmark.php?test=all&lang=all On Gentoo on a Pentium 4 for example: mean 07.10 Python Psyco 19.34 Lua 23.00 Python 28.27 Perl 30.00 PHP 66.28 Javascript SpiderMonkey 75.12 Ruby I have no idea about Zope, but if that's slow, go complain to the devlopers of Zope. The Python interpreter is one of the fastest for a dynamically interpreted language. And Psyco is competitive with many other JIT compilers. I would think someone who has been obsessing about the speed of Python since May, and especially interested in a Python "VM" would have learned by now about Psyco? From steve at holdenweb.com Sat Dec 13 08:03:10 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 13 Dec 2008 08:03:10 -0500 Subject: __future__ and compile: unrecognised flags In-Reply-To: <20081213112917.6209.qmail@s461.sureserver.com> References: <20081213112917.6209.qmail@s461.sureserver.com> Message-ID: Poor Yorick wrote: > I have a future statement in a script which is intended to work in 2.6 and 3. > Shouldn't compile flags in __future__ objects essentially be noops for versions > that already support the feature? doctest is complaining about unrecognised > flags. This illustrates the problem: > > Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win > 32 > Type "help", "copyright", "credits" or "license" for more information. > >>> from __future__ import unicode_literals > >>> src = 'a = "hello"' > >>> c1 = compile(src,'','exec',unicode_literals.compiler_flag) > Traceback (most recent call last): > File "", line 1, in > ValueError: compile(): unrecognised flags > This could arguably be classed as a bug given that the 2.6 documentation for __future__ says "No feature description will ever be deleted from __future__." However I suspect that the feature has been removed because all string literals are Unicode in 3.0 and up, and 3.0 is allowed to break compatibility. One question is whether the 2to3 translator will remove such an import. If it does then one could argue this is just another of the many expected incompatibilities between 2.x and 3.x. If it doesn't, it should probably be made to. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steve at REMOVE-THIS-cybersource.com.au Thu Dec 4 09:45:46 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Dec 2008 14:45:46 GMT Subject: "as" keyword woes References: <7dudnSS7uIn_KarUnZ2dnUVZ_tTinZ2d@earthlink.com> Message-ID: <0147e4df$0$20670$c3e8da3@news.astraweb.com> On Thu, 04 Dec 2008 20:53:38 +1000, James Mills wrote: > Readability of your code becomes very important especially if you're > working with many developers over time. > > 1. Use sensible meaningful names. > 2. Don't use abbreviations. This is excellent advice, but remember, what is a sensible meaningful name is domain-specific. In a maths library, this would be sensible: def poly(x): return 4*x**3 -2*x**2 +3*x -7 and this ridiculous: def poly(real_number): return 4*real_number**3 -2*real_number**2 +3*real_number -7 Sometimes there are name clashes between keywords and sensible names in your problem space. I'm sure every regular Python developer has found themselves writing something like: prnt print_ print2 cls klass class_ or similar. In the standard library, the random module uses an argument "lambd" because lambda is a keyword. -- Steven From jstroud at mbi.ucla.edu Fri Dec 5 23:35:07 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 05 Dec 2008 20:35:07 -0800 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: Daniel Fetchinson wrote: > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html > > The proposal is to allow this: > > class C: > def self.method( arg ): > self.value = arg > return self.value > > instead of this: > > class C: > def method( self, arg ): > self.value = arg > return self.value > I'd like this new way of defining methods, what do you guys think? Consider the maverick who insists on class C: def me.method(arg): self.value = arg which should be equivalent to class C: def method(me, arg): me.value = arg What's the interpreter going to do with our maverick's code? James From rogerb at rogerbinns.com Wed Dec 24 05:44:59 2008 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 24 Dec 2008 02:44:59 -0800 Subject: Most efficient way to build very large dictionaries In-Reply-To: <5fa6c12e0812240218yc9a7185maaf5211dbddd8134@mail.gmail.com> References: <1230104615.5867.1291617213@webmail.messagingengine.com> <1230107768.14060.1291622121@webmail.messagingengine.com> <5fa6c12e0812240218yc9a7185maaf5211dbddd8134@mail.gmail.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Martin wrote: > I'd think he's talking about in memory SQLite Databases, this way you > should be quite fast _and_ could dump all that to a persistent > storage... I was just talking about regular on disk SQLite databases. In terms of priming the pump, you can just open/read/close the whole database file which will cause the database to be in the operating system cache buffers, or just let SQLite do its thing. For anyone who is curious about what Martin is referring to, SQLite does support the database file being memory (although it isn't a file at that point). It has a fake filename of :memory:. As an example you can copy the table 'example' to memory using: ATTACH ':memory:' as memdb; CREATE TABLE memdb.memexample AS select * from example; As with Python, all this stuff is premature optimization. Get it working right first and then try tweaks to improve performance. Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAklSEqcACgkQmOOfHg372QTPpgCgvSKGMCJAKhnm5I8qHdmZtRh3 SgMAoI3DVhWCVdUE1TLck9ZEfp/Ln1H5 =5kNT -----END PGP SIGNATURE----- From digitalarena.tk at gmail.com Thu Dec 4 06:44:05 2008 From: digitalarena.tk at gmail.com (anum) Date: Thu, 4 Dec 2008 03:44:05 -0800 (PST) Subject: hi Message-ID: www.digitalarena.tk From geekmail at usenot.de Sun Dec 7 14:35:53 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sun, 7 Dec 2008 20:35:53 +0100 Subject: Is 3.0 worth breaking backward compatibility? References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> Message-ID: <20081207203553.7d62434a@usenot.de> On Sun, 7 Dec 2008 11:22:23 -0800 (PST) walterbyrd wrote: > IMO: breaking backward compatibility is a big deal, and should only be > done when it is seriously needed. > Pleeeeze. Python 3 is shipping now, and so is 2.x, where x > 5. Python 2 is going to be around for quite some time. What is everybody's problem? > Also, IMO, most of, if not all, of the changes being made in 3.0 are > debatable, at best. I can not think of anything that is being changed > that was really a "show stopper" anyway. > Right. But warts accumulate, and some day you'll have a troglodyte of a language. Better to scrubb off some warts every now and then, so the whole thing remains agile. > At best, I am a casual python user, so it's likely that I am missing > something. Yes, the big picture. Also, being a casual Python user (like myself, just to clarify), *you* will least be bitten by the incombatibilties. I *really* don't get all the outrage. It's a major new version. What better time to tighten things up a bit? /W -- My real email address is constructed by swapping the domain with the recipient (local part). From w_a_x_man at yahoo.com Wed Dec 10 15:37:50 2008 From: w_a_x_man at yahoo.com (w_a_x_man at yahoo.com) Date: Wed, 10 Dec 2008 12:37:50 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: On Dec 5, 9:51?am, Xah Lee wrote: > > For those of you who don't know linear algebra but knows coding, this > means, we want a function whose input is a list of 3 elements say > {x,y,z}, and output is also a list of 3 elements, say {a,b,c}, with > the condition that > > a = x/Sqrt[x^2+y^2+z^2] > b = y/Sqrt[x^2+y^2+z^2] > c = z/Sqrt[x^2+y^2+z^2] > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, > you'll have 50 or hundreds lines. Ruby: def norm a s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) a.map{|x| x/s} end From ndbecker2 at gmail.com Sat Dec 6 13:03:11 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Sat, 06 Dec 2008 13:03:11 -0500 Subject: Guido's new method definition idea References: Message-ID: Daniel Fetchinson wrote: > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html > > The proposal is to allow this: > > class C: > def self.method( arg ): > self.value = arg > return self.value > > instead of this: > > class C: > def method( self, arg ): > self.value = arg > return self.value > > I.e. explicit self stays only the syntax is slightly different and may > seem attractive to some. As pointed out by Guido classmethods would > work similarly: > > class C: > @classmethod > def cls.method( arg ): > cls.val = arg > return cls.val > > The fact that Guido says, > > "Now, I'm not saying that I like this better than the status quo. But > I like it a lot better than [...] but it has the great advantage that > it is backward compatible, and can be evolved into a PEP with a > reference implementation without too much effort." > > shows that the proposal is viable. > > I'd like this new way of defining methods, what do you guys think? > Anyone ready for writing a PEP? > What's the advantage? If there is not a good reason, I would strongly opposed polluting the language. From vniboris at hotmail.com Tue Dec 2 10:19:35 2008 From: vniboris at hotmail.com (B R) Date: Tue, 2 Dec 2008 15:19:35 +0000 Subject: "server chain" with python socket module Message-ID: dear all, I want to connect my A machine to the E server via servers B, C and D, is there a way to set-up such "server chain" with python socket module (or other module) ? many thanks boris vn%ibo%ris[at]hotmail.com _________________________________________________________________ News, entertainment and everything you care about at Live.com. Get it now! http://www.live.com/getstarted.aspx -------------- next part -------------- An HTML attachment was scrubbed... URL: From mnordhoff at mattnordhoff.com Tue Dec 9 03:11:08 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Tue, 09 Dec 2008 08:11:08 +0000 Subject: html codes In-Reply-To: References: Message-ID: <493E281C.1030609@mattnordhoff.com> Daniel Fetchinson wrote: > Hi folks, > > I came across a javascript library that returns all sorts of html > codes in the cookies it sets and I need my web framework (written in > python :)) to decode them. I'm aware of htmlentitydefs but > htmlentitydefs.entitydefs.keys( ) are of the form '&#xxx' but this > javascript library uses stuff like '%3A' for the ':' for example. The > conversion is here: > > http://www.ascii.cl/htmlcodes.htm > > Is there a python package/module/whatever that does the conversion for > me or do I have to write a little wrapper myself (and introduce bugs > while doing so :))? > > Cheers, > Daniel >>> import urllib >>> urllib.unquote('%20') ' ' -- From mal at egenix.com Wed Dec 10 16:17:40 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 10 Dec 2008 22:17:40 +0100 Subject: getting back into programming In-Reply-To: <8796344d-1c02-441e-8272-8a7638faae39@j39g2000yqn.googlegroups.com> References: <8796344d-1c02-441e-8272-8a7638faae39@j39g2000yqn.googlegroups.com> Message-ID: <494031F4.7060004@egenix.com> On 2008-12-10 22:02, usawargamer at yahoo.com wrote: > I used to program in C and Perl (up until 2001) (a little C++ and Java > too). Since then I've been a Business Analyst and only coded in VBA/ > Excel and written some SQL queries. (we use Sybase) > > I feel the need for other tools. > Primarily I want to write a bunch of small programs to query a > database and perform some calculations. While I can do this inside a > Sybase stored procedure, its a bit messy trying to "reimplement" a set > of calculations from Excel into Sybase. > > I would like to either: > - relearn Perl > or > - learn Python (I have heard its a nice language) > > 1. How good and easy to use is the Python database interface (to > Sybase)? If you're looking for a reliable database interface to Sybase, I'd suggest mxODBC: http://www.egenix.com/products/python/mxODBC/ It's been used in production by many banks for years and so far without problems. > 2. Can you suggest some good books, and/or links for learning Python, > as well as teh database interface? One of the best books is "Learning Python": http://oreilly.com/catalog/9781565924642/ > 3. How difficult is it to install Python vs Perl on PC/Windows > machines? There's an MSI installer, so it's basically just a few clicks away: http://www.python.org/download/ Hope that helps, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 10 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-12-02: Released mxODBC.Connect 1.0.0 http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From prologic at shortcircuit.net.au Mon Dec 8 01:17:57 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Dec 2008 16:17:57 +1000 Subject: A question about reference in Python. In-Reply-To: <47c890dc0812072213q20cb415fjbd4c80e7af7a7ef5@mail.gmail.com> References: <493CB003.3080209@gmail.com> <47c890dc0812072213q20cb415fjbd4c80e7af7a7ef5@mail.gmail.com> Message-ID: On Mon, Dec 8, 2008 at 4:13 PM, Chris Rebert wrote: > The following three lines serve no purpose and can only lead to confusion: >> value = None >> prev = None >> next = None You are absolutely right :) Updated code: #!/home/jmills/bin/python -i class Node(object): def __init__(self, value, prev=None, next=None): self.value = value self.prev = prev self.next = next class List(object): def __init__(self, *seq): if seq: first = prev = node = None for x in seq: if not first: first = Node(x) prev = node = first else: node = Node(x, prev) prev.next = node prev = node self.data = first else: self.data = None def __getitem__(self, x): node = self.data for i in xrange(x): node = node.next return node.value x = List(0, 1, 2, 3) cheers Jaems PS: Sorry Chris :) -- -- -- "Problems are solved by method" From lists at cheimes.de Mon Dec 22 17:25:10 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 22 Dec 2008 23:25:10 +0100 Subject: python3 urlopen(...).read() returns bytes In-Reply-To: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> References: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> Message-ID: Glenn G. Chappell schrieb: > I just ran 2to3 on a py2.5 script that does pattern matching on the > text of a web page. The resulting script crashed, because when I did > > f = urllib.request.urlopen(url) > text = f.read() > > then "text" is a bytes object, not a string, and so I can't do a > regexp on it. > > Of course, this is easy to patch: just do "f.read().decode()". > However, it strikes me as an obvious bug, which ought to be fixed. > That is, read() should return a string, as it did in py2.5. It's not possible unless you know the encoding of the bytes. Network io only returns byte and you must encode it explicitly. You "patch" breaks as soon as a remote sites returns the data in a different encoding. It also breaks if the site returns an image/*, appliation/*, audio/* or any other mimetype than text. There is no generic and simple way to detect the encoding of a remote site. Sometimes the encoding is mentioned in the HTTP header, sometimes it's embedded in the section of the HTML document. > This change breaks pretty much every Python program that opens a > webpage, doesn't it? 2to3 doesn't catch it, and, in any case, why > should read() return bytes, not string? Am I missing something? I hope I was able to explain the issue. By the way Python 2.x and 3.0 are both returning bytes (str in 2.x, bytes in 3.0). Christian From geekmail at usenot.de Fri Dec 5 15:39:52 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Fri, 5 Dec 2008 21:39:52 +0100 Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> <84332560-580d-488b-aa6b-6aad754a7805@k36g2000pri.googlegroups.com> Message-ID: <20081205213952.35e9ec3e@usenot.de> On Fri, 5 Dec 2008 12:16:47 -0800 (PST) "Fernando H. Sanches" wrote: > On Dec 4, 5:45?pm, Andreas Waldenburger wrote: > > On Thu, 4 Dec 2008 11:52:38 -0600 s... at pobox.com wrote: > > [snip] > > Whenever has it been a pythonic ideal to "not allow" stuff? You get > > warnings. Everything else is up to you. > > > > [snip] > > Python has "not allowed stuff" for a long time. > > For example, it disallows statements in lambdas. > Which is sensible (for Python) because it does not have block delimiters. Also, lambdas are syntactic sugar for special use cases. It's not like they are needed at all. But sometimes mixing tabs and spaces can be needed (think coding standards). What else is disallowed? > "Disallowing" is not bad. Disallowing bad practices (like mixing tabs > and spaces) is actually good! > This presupposes that mixing tabs and spaces is "bad". That's like saying C++ is bad. > I agree that the tab/space thing should be changed. Would it be too > hard to make the parser see if the indentation is consistent in the > whole file? Maybe not, but it would be rather hard to agree on what can be called consistent and what can not, I think. You can mix spaces and tabs consistently, just as you can use any one consistently. > This is a annoying source of problems, specially since > you can't tell a whitespace from a tab just looking at it. > There are editors that let you show different symbols for spaces and tabs (I know, I know ...). > And I personally disliked most of the changes (specially the ones on > map and reduce). I hope functional programming doesn't get even more > hindered in future releases, because I believe these changes only made > Python weaker. > +1 /W -- My real email address is constructed by swapping the domain with the recipient (local part). From steve at REMOVE-THIS-cybersource.com.au Sat Dec 13 06:07:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Dec 2008 11:07:53 GMT Subject: Removing None objects from a sequence References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> <4942E668.5030100@tim.thechases.com> Message-ID: <01538f0c$0$6988$c3e8da3@news.astraweb.com> On Fri, 12 Dec 2008 19:02:24 -0500, Terry Reedy wrote: > Tim Chase wrote: >>> If you want to literally remove None objects from a list....(or >>> mutable sequence) >>> >>> def deNone(alist): >>> n=len(alist) >>> i=j=0 >>> while i < n: >>> if alist[i] is not None: >>> alist[j] = alist[i] >>> j += 1 >>> i += 1 >>> alist[j:i] = [] >>> >>> blist=[None,1,None,2,None,3,None,None,4,None] deNone(blist) >>> print(blist) >>> >>> # prints [1, 2, 3, 4] >> >> ...wouldn't a cleaner way of doing this just be >> >> >>> blist=[None,1,None,2,None,3,None,None,4,None] > > No, making a filtered copy that is then copied back before being deleted > is algorithmically much messier. My code does the minimum work > necessary and is algorithmically cleaner. Er what? You're joking, right? Your function has eight lines, all of which are very low level: you're dealing with not one but TWO list indexes yourself. You have three internal names to deal with, although in fairness one is set once then used as a constant from then on. The algorithm is unclear: try explaining what you are doing in English, and see how difficult it is. "Keep two indexes into the list. If the first index isn't pointing at None, copy that value to the second index, which is either the same as the first index, or pointing at None. Then advance the second index, and the first index, as needed. It will never over-write a non-None value, but just try proving it." Contrast that with the alternative suggested by Tim: def deNone2(alist): alist[:] = [x for x in alist if x is not None] It's one line, with one internal variable. You don't have to manipulate index variables. The explanation is simple: "Make a new list with the non-None values and assign it in-place to the old list." Clear, succinct, and understandable, with no corner cases like empty lists to worry about. Here's another low-level algorithm, the classical delete items in place algorithm. Three lines, one index, lousy O(N**2) performance. def deNone3(alist): for i in xrange(len(alist)-1, -1, -1): if alist[i] is None: del alist[i] Now, let's do a shoot-out. Do they return the same thing? >>> masterlist = [None]*2 + range(5) + [None]*3 + range(5, 10) + [None]*4 + [10, None, 11, None, 12, None] >>> alist = masterlist[:] >>> blist = masterlist[:] >>> clist = masterlist[:] >>> deNone(alist) >>> deNone2(blist) >>> deNone3(clist) >>> alist == blist == clist True Which is faster? >>> from timeit import Timer >>> setup = "from __main__ import deNone, deNone2, deNone3;" \ ... " from __main__ import masterlist as m" >>> t1 = Timer("a=m[:];deNone(a)", setup) >>> t2 = Timer("a=m[:];deNone2(a)", setup) >>> t3 = Timer("a=m[:];deNone3(a)", setup) >>> t1.repeat(number=10000) [0.39079904556274414, 0.38915109634399414, 0.39700794219970703] >>> t2.repeat(number=10000) [0.17854905128479004, 0.1782989501953125, 0.17886185646057129] >>> t3.repeat(number=10000) [0.26834988594055176, 0.25835609436035156, 0.25850009918212891] Not surprisingly, Tim's version is twice as fast as yours. Surprisingly, even the deNone3 function is faster than yours. What about a real test? None of these piddly toy data sets, with 25 items. Something *real*. >>> masterlist = masterlist*100 >>> masterlist += range(1000) >>> masterlist += [None]*1000 >>> masterlist += [None, 0]*1000 >>> masterlist += [1]*10000 >>> len(masterlist) 16500 >>> t1.repeat(number=100) [2.1611621379852295, 1.2539350986480713, 1.2424759864807129] >>> t2.repeat(number=100) [0.93860101699829102, 0.44704914093017578, 0.41285014152526855] >>> t3.repeat(number=100) [4.5643420219421387, 3.216562032699585, 3.2176508903503418] Not surprisingly, my version really suffers. But so does yours: it's now three times slower than Tim's. I expect that Tim's version will look better and better until the list is so huge that memory paging to disk becomes a factor. Now, sure, most of the work in Tim's version is executed in fast C code instead of slow Python code. If we were programming in C, your version might perform better relative to Tim's. But even if performance was better, I wouldn't describe the algorithm as particularly clean. -- Steven. From skip at pobox.com Sat Dec 27 13:54:00 2008 From: skip at pobox.com (Skip Montanaro) Date: Sat, 27 Dec 2008 18:54:00 +0000 (UTC) Subject: Test message - please ignore Message-ID: Test post via gmane. Please ignore. From rogerb at rogerbinns.com Wed Dec 24 03:19:56 2008 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 24 Dec 2008 00:19:56 -0800 Subject: Most efficient way to build very large dictionaries In-Reply-To: <1230104615.5867.1291617213@webmail.messagingengine.com> References: <1230104615.5867.1291617213@webmail.messagingengine.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 python at bdurham.com wrote: > I would appreciate your thoughts on whether there are advantages to > working with a pre-built dictionary and if so, what are the best ways to > create a pre-loaded dictionary. Based on this and your other thread, you may want to consider using SQLite (standard Python module is available for it). SQL queries are very similar to set operations and indices take care of performance (by using more storage). You also get transactions for free. If you look into SQLite pragmas you can get it to use more RAM to improve performance. And by using a SQL layer you can later switch to another database should you need really hard core storage. It also makes the data available to other programs in a uniform way. Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAklR8KgACgkQmOOfHg372QSrHQCfVJzueXVKme8QZcxoLf70BL4K RL8AoM9QOFykOLrr5QXtpmZ5f7CFHm6e =zAPG -----END PGP SIGNATURE----- From bdesth.quelquechose at free.quelquepart.fr Thu Dec 4 14:35:01 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 Dec 2008 20:35:01 +0100 Subject: Python Runtime Method Call Binding In-Reply-To: <0ad65087-9b50-4d11-85a4-0ebf7e8e01a0@c1g2000yqg.googlegroups.com> References: <0147f396$0$20670$c3e8da3@news.astraweb.com> <0ad65087-9b50-4d11-85a4-0ebf7e8e01a0@c1g2000yqg.googlegroups.com> Message-ID: <49383e9e$0$16497$426a74cc@news.free.fr> k3xji a ?crit : > test failed !-) From martin at v.loewis.de Tue Dec 2 13:56:19 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 02 Dec 2008 19:56:19 +0100 Subject: Multiple Versions of Python on Windows XP In-Reply-To: <4934F82D.1090601@g.nevcal.com> References: <4934de22$0$27863$9b622d9e@news.freenet.de> <4934E183.9020404@g.nevcal.com> <4934E3BF.7000403@v.loewis.de> <4934F82D.1090601@g.nevcal.com> Message-ID: <493584D3.1090301@v.loewis.de> > OK, Issue 4485 created. My first one, so let me know if I goofed. I > elaborated a bit from the original email, upon reflection. Seemed > useful, but also seemed complex by the time I got done. Looks about right to me. > I don't really have a clue what the uninstaller should do with these; > nor have I fiddled to know if it presently removes Python.File. I > suppose it should delete them, if and only if the ftype and assoc have > the same content as was created by the corresponding version installation. The uninstaller will currently just remove it all. Conditional removal of the associations will be tricky; I'll look into it. I also wonder whether assoc only changes the settings for the current user. In that case, uninstalling a Python version that was per-machine would not affect the user's association, anyway. Regards, Martin From ionut.vancea at gmail.com Thu Dec 4 08:56:53 2008 From: ionut.vancea at gmail.com (Ionut Vancea) Date: Thu, 4 Dec 2008 13:56:53 +0000 Subject: RELEASED Python 3.0 final In-Reply-To: <6a5569ec0812040554h7f5bca4btd4d32c28ed04a0b6@mail.gmail.com> References: <1a73e3be-1753-4178-8091-eaa890b3e07e@l42g2000yqe.googlegroups.com> <6a5569ec0812040554h7f5bca4btd4d32c28ed04a0b6@mail.gmail.com> Message-ID: <368177940812040556i679ba4fewfee395a8923a4a6d@mail.gmail.com> Hi On Thu, Dec 4, 2008 at 1:54 PM, Roy H. Han wrote: > Hi, > > This is great, however, the link to the What's New page appears to be > broken. > http://docs.python.org/dev/3.0/whatsnew/3.1.html replace 3.1 with 3.0 :), so it has to be: http://docs.python.org/dev/3.0/whatsnew/3.0.html Cheers, -- === Ioan Vancea http://www.vioan.ro From lihang9999 at gmail.com Wed Dec 17 18:00:35 2008 From: lihang9999 at gmail.com (Li Han) Date: Wed, 17 Dec 2008 15:00:35 -0800 (PST) Subject: The rule of literal string References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> Message-ID: But what repr() do remain a black hole! Han From wuwei23 at gmail.com Wed Dec 3 00:28:04 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 2 Dec 2008 21:28:04 -0800 (PST) Subject: best way to do this References: <137514ca-d16c-4713-b14f-e12ab4f607ab@c36g2000prc.googlegroups.com> Message-ID: <8f29535d-56e6-4818-ba34-7e128e05c197@d36g2000prf.googlegroups.com> On Dec 3, 1:38?pm, thor wrote: > >>> c = [(5, 3), (6, 8)] > >>> [x for t in zip(*c) for x in t] > [5, 6, 3, 8] The zip here is superfluous. >>> c = [(5, 3), (6, 8)] >>> zip(*c) [(5, 6), (3, 8)] Unless you're -only- using it to ensure your result is the same order as the OP...but he also stressed that order was unimportant. Leaving out the zip call gives you Arnaud's solution, which seems the clearest. From news123 at free.fr Sat Dec 6 13:02:22 2008 From: news123 at free.fr (News123) Date: Sat, 06 Dec 2008 19:02:22 +0100 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: <493abe2e$0$15998$426a34cc@news.free.fr> Daniel Fetchinson wrote: > The proposal is to allow this: > > class C: > def self.method( arg ): > self.value = arg > return self.value > > instead of this: > > class C: > def method( self, arg ): > self.value = arg > return self.value Hmm, I'd give the proposal a -1. Perhaps I'm missing something though. Does this really justify an enhancement? Whether the implicit parameter is prepended with a dot or whether it's the first parameter with the parantheses doesn't save me any typing and the benefit of 'visualizing' how the function should be called seems minor to me. What would be interesting would be some syntactical sugar to get rid of the 'self' (at least in the code body). example: class C: class_elements a,b,c,d def method(self,arg): global d a,b,c = arg[0..3] d = a + b self.e = a + d instead of class C: def method(self,arg): self.a,self.b,self.c,self.d = arg[0..4] self.e = self.a + self.b As far as I understood (I never really followed any of these threads), getting rid of self has already been discussed and rejected many times. bye N From duncan.booth at invalid.invalid Tue Dec 16 05:10:24 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Dec 2008 10:10:24 GMT Subject: weird dict problem, how can this even happen? References: Message-ID: Joel Hedlund wrote: > I should probably do this with lists instead because I can't really > think of a way of salvaging this. Am i right? > I think you probably are correct. The only thing I can think that might help is if you can catch all the situations where changes to the dependent values might change the hash and wrap them up: before changing the hash pop the item out of the dict, then reinsert it after the change. Alternatively give up on defining hash and __eq__ for FragmentInfo and rely on object identity instead. -- Duncan Booth http://kupuguy.blogspot.com From Shawn.Gong at drdc-rddc.gc.ca Thu Dec 11 16:04:38 2008 From: Shawn.Gong at drdc-rddc.gc.ca (Gong, Shawn (Contractor)) Date: Thu, 11 Dec 2008 16:04:38 -0500 Subject: Python 2.5.2 error on Solaris, No module named _md5 Message-ID: hi list, I tried to build Python 2.5.2 on Solaris 9 with gcc 3.4.6 under my user account. (there is already an older 2.5.1 on /usr/local/, so I used "make -I install") When I "import md5", I got: Python 2.5.2 (r252:60911, Dec 11 2008, 15:16:41) [GCC 3.4.6] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import md5 Traceback (most recent call last): File "", line 1, in File "/home/sgong/dev181/dist/lib/python2.5/md5.py", line 6, in from hashlib import md5 File "/home/sgong/dev181/dist/lib/python2.5/hashlib.py", line 133, in md5 = __get_builtin_constructor('md5') File "/home/sgong/dev181/dist/lib/python2.5/hashlib.py", line 60, in __get_builtin_constructor import _md5 ImportError: No module named _md5 I then tried Python 2.6.1 but with the same error. Any help is appreciated. thanks, Shawn -------------- next part -------------- An HTML attachment was scrubbed... URL: From bdesth.quelquechose at free.quelquepart.fr Tue Dec 30 15:52:47 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 30 Dec 2008 21:52:47 +0100 Subject: SQL, lite lite lite In-Reply-To: <186e44f7-f949-45e2-b1e2-a913560acf94@s9g2000prg.googlegroups.com> References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> <8da5c6b1-951f-4abd-8ee7-07b63802b9f6@13g2000yql.googlegroups.com> <186e44f7-f949-45e2-b1e2-a913560acf94@s9g2000prg.googlegroups.com> Message-ID: <495a97ce$0$25469$426a74cc@news.free.fr> Aaron Brady a ?crit : > On Dec 30, 11:16 am, prueba... at latinmail.com wrote: (snip) >> You really do like to reinvent the wheels do you? :-) Nothing wrong >> with that. Just be aware that most people that really need what you >> are proposing are probably already using mature feature rich libraries >> for that. >> >> http://wiki.python.org/moin/HigherLevelDatabaseProgramming > > Look at these options! Who invents the wheel? Naturally, I've had > time to master every one. > Oh, so that's why you propose to add yet another item to the list ? From metebilgin48 at gmail.com Fri Dec 5 09:52:01 2008 From: metebilgin48 at gmail.com (mete bilgin) Date: Fri, 5 Dec 2008 16:52:01 +0200 Subject: mod_python and files directory Message-ID: Hi all, I try to make a websevice with python and mod_python. ? try to make a po files, but i can not reach them in the page. When i ask the page like " os.listdir('.') " but i want to get files directory, what can i do? sorry for my bad describe of that. Thanks a lot... -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrew at doadesweb.co.uk Thu Dec 11 12:48:08 2008 From: andrew at doadesweb.co.uk (Andrew Doades) Date: Thu, 11 Dec 2008 17:48:08 +0000 Subject: get todays files In-Reply-To: <494015F7.3020302@tim.thechases.com> References: <4632c353-0462-485b-9e1b-6a5c56682363@s9g2000prg.googlegroups.com> <494015F7.3020302@tim.thechases.com> Message-ID: <49415258.2010101@doadesweb.co.uk> Tim Chase wrote: >> This looks very good and I have tested successfully, but is there a >> way I can set the today to automatically become todays date in that >> format? > > Yes...see the python datetime module[1]...particularly the strftime() > call on date/datetime objects. > > -tkc > > [1] > http://docs.python.org/library/datetime.html I know this will sound like I am being very cheeky, but is there a way you can make this for where the ftp server is actually windows server? The script runs and it shows the date the file was modified, but still downloads them, I have attached the script I am now using with your code in. import os from ftplib import FTP import subprocess from datetime import datetime from time import gmtime, strftime curr_date = strftime("%d %B %Y", gmtime()) # config ftp_uname = '' ftp_pwd = '' ftp_server = '' # end of config fileroot = 'DBBackup_' os.chdir('c:/') files = [] logfile = open('c:/dbbackup/getmdbackups.log','a+') def makelist(line): if (line.startswith(fileroot)): fs = [line] files.append(fs) def log(line): ll = str(datetime.now()) + ' : ' + str(line) print ll logfile.write(ll + '\n') def fileexists(ff, size): if (os.path.exists(ff)): stat = os.stat(ff) if (stat.st_size == size): return True return False try: # first connect using ftp to get a list of valid backup failes available log('Connecting to ftp server') ftp = FTP(ftp_server) ftp.set_pasv(False) #ftp.set_debuglevel(2) resp = ftp.login(ftp_uname,ftp_pwd) log(resp) ftp.retrlines('NLST',makelist) log(str(files)) ftp.quit() # fetch files in a loop using wget. for ff in files: ftp = FTP(ftp_server) ftp.set_pasv(False) resp = ftp.login(ftp_uname,ftp_pwd) log(resp) size = ftp.size(ff[0]) log('Size of server file = ' + str(size)) #ftp.quit() try: if (not fileexists(ff[0],size)): results = ftp.sendcmd("MDTM %s" % ff[0]) code, stamp = results.split(None, 1) assert code == "213", "Unexpected result" print "%s was modified on %s" % (ff[0], stamp) today = curr_date if stamp[:8] == today: log('Transferring: ' + ff[0]) # make parameters to wget the backup file params = ' ftp://' + ftp_server + '/' + ff[0] rcode = subprocess.call('c:/wget.exe ' + params) log('Return code from wget = ' + str(rcode)) if (rcode == 0): ff[1] = 1 else: log('File ' + ff[0] + ' already exists locally, not transferring') ff[1] = 1 except Exception, e: log(str(e)) log('Transfer complete') # delete the server files that have been transferred or are already here with the right filesize. for ff in files: if (ff[1] == 1): log('delete ' + ff[0]) except Exception,e: log(str(e)) # clean up temp files log('Finished.') logfile.close() From robert.kern at gmail.com Thu Dec 4 17:46:53 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 04 Dec 2008 16:46:53 -0600 Subject: using distutils to cross-compile extensions? In-Reply-To: <49385CBB.7060207@cs.cornell.edu> References: <49385CBB.7060207@cs.cornell.edu> Message-ID: <49385DDD.2030108@gmail.com> Michael George wrote: > Hi, > > Please CC me in replying as I am off list. > > I have an extension module that I've built using distutils. I wonder if > it's possible to use distutils to cross-compile it for windows on my > linux box, and whether the pain involved is great. Can anyone point me > in the right direction? It *might* be possible with a number of ugly hacks, but the pain involved would, indeed, be great. distutils does not support cross-compiling at all. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From deets at nospam.web.de Mon Dec 1 14:09:29 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 01 Dec 2008 20:09:29 +0100 Subject: Import of egg packages installed with easy_install References: Message-ID: <6piqvpF839bkU2@mid.uni-berlin.de> Alexey Vlasov wrote: > Hi. > > There's an already installed with easy_install packet, let's say flup, > to the home catalog: > $ ls -la ~/python/lib/python2.5/site-packages/ > total 176 > drwxr-xr-x 3 4096 Nov 29 18:57 . > drwxr-xr-x 3 4096 Nov 29 18:51 .. > -rw-r--r-- 1 208 Nov 29 18:57 easy-install.pth > -rw-r--r-- 1 134573 Nov 29 18:51 flup-1.0.1-py2.5.egg > -rw-r--r-- 1 2362 Nov 29 18:51 site.py > -rw-r--r-- 1 1853 Nov 29 18:51 site.pyc > > > $ cat ~/python/lib/python2.5/site-packages/easy-install.pth > import sys; sys.__plen = len(sys.path) > ./flup-1.0.1-py2.5.egg > import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; > p=getattr(sys,'__egginsert',0); sys.path[p:p]=new; sys.__egginsert = > p+len(new) > > $ echo $PYTHONPATH > /usr/lib64/portage/pym:/home/username/python/lib64/python2.5/site-packages > > $ python > Python 2.5.2 (r252:60911, Nov 13 2008, 15:01:36) > [GCC 4.1.2 (Gentoo 4.1.2 p1.1)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import flup > > No errors. > > Then I create a simple CGI script: > ======== > #!/usr/bin/python > > print "Content-type: text/plain"; > print > > import sys > sys.path.insert (0, > '/home/username/python/lib64/python2.5/site-packages') > print sys.path > import flup > ======== > > Browser says: > ['/home/username/python/lib64/python2.5/site-packages', > '/home/username/http', '/usr/lib64/python25.zip', > '/usr/lib64/python2.5', '/usr/lib64/python2.5/plat-linux2', > '/usr/lib64/python2.5/lib-tk', '/usr/lib64/python2.5/lib-dynload', > '/usr/lib64/python2.5/site-packages'] > > in error log: > [Sat Nov 29 19:41:15 2008] [error] Traceback (most recent call last): > [Sat Nov 29 19:41:15 2008] [error] File "path.cgi", line 9, in > [Sat Nov 29 19:41:15 2008] [error] import flup > [Sat Nov 29 19:41:15 2008] [error] ImportError: No module named flup > > > If you start it with console, you get the same, but there appears also > another path: > /home/username/python/lib64/python2.5/site-packages/flup-1.0.1-py2.5.egg > > As I understand it is the problem actually, but I can't get why sys.path > doesn't contain this path when I request with HTTP. It's not sufficient to add simply your local site-packages, you must install it using the module site's addsitedir-function, like this: import site site.addsitedir("/home/username/python/lib/python2.5/site-packages") The reason is that otherwise the *.pth-files in the site-packages aren't picked up. Diez From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 21:07:33 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2008 02:07:33 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <015c4ab6$0$20656$c3e8da3@news.astraweb.com> On Fri, 19 Dec 2008 19:10:59 +0100, Christian Heimes wrote about % formatting in Python 3: > It's not going to be removed for many years - if ever. The % string > formatting system is not deprecated in 3.0. For that very reason it must > stay until 3.2. We don't have plans to deprecate it in 3.1 so it will > stay at least until Python 3.3 which is to be released about 2014. I am very glad to hear that. -- Steven From steve at holdenweb.com Sat Dec 20 11:31:38 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 20 Dec 2008 11:31:38 -0500 Subject: WAGs on when django will use Python 3.0? In-Reply-To: <7f6a70f9-4b97-44f9-86fe-db84ae733077@g1g2000pra.googlegroups.com> References: <7f6a70f9-4b97-44f9-86fe-db84ae733077@g1g2000pra.googlegroups.com> Message-ID: walterbyrd wrote: > Will Django be primarily using Python 3.0 one year from now? Two years > from now? > I doubt they will drop 2.X support in the next two years. 3.0 will likely be supported fairly fully in the next year. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From prahaai at gmail.com Thu Dec 11 11:31:40 2008 From: prahaai at gmail.com (Cro) Date: Thu, 11 Dec 2008 08:31:40 -0800 (PST) Subject: Why optimization mode is slower than normal mode? References: Message-ID: <58a5020b-cc39-4ff8-8530-a680ec90ff2f@k36g2000pri.googlegroups.com> Not-optimised: Pystone(1.1) time for 1000000 passes = 12.8366 This machine benchmarks at 77902 pystones/second Optimised: Pystone(1.1) time for 1000000 passes = 13.0574 This machine benchmarks at 76584.8 pystones/second It is probably the way it should be. :) From steve at REMOVE-THIS-cybersource.com.au Sat Dec 6 19:25:04 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 00:25:04 GMT Subject: "as" keyword woes References: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> <0147dc24$0$20670$c3e8da3@news.astraweb.com> <0148b217$0$20670$c3e8da3@news.astraweb.com> <7d0lj4d9hai2f87r30erc4l1ir85osbfg7@4ax.com> <88579d9a-df52-49b9-a6fe-53c8f4524bf3@j39g2000yqn.googlegroups.com> <70llj41hie2svs68o5efn22i97f649svfh@4ax.com> <1cda9a9a-1641-424b-9f3d-c4e2635efed7@j38g2000yqa.googlegroups.com> Message-ID: <014b0f94$0$20670$c3e8da3@news.astraweb.com> On Sat, 06 Dec 2008 14:36:07 -0800, Mensanator wrote: > It was extremely simple for me to fix the sympy module where I noticed > it. I'm not saying it wasn't a problem, I'm saying it wasn't BROKEN. If it wasn't broken, why did you need to fix it? "Broken" means "not working", not "unfixable". -- Steven From callen314 at gmail.com Mon Dec 1 16:38:25 2008 From: callen314 at gmail.com (Craig Allen) Date: Mon, 1 Dec 2008 13:38:25 -0800 (PST) Subject: Emacs vs. Eclipse vs. Vim References: Message-ID: I would never tell someone what editor to use in the same way I wouldn't tell someone what religion to believe in. Which is to say, I would tell my kids or other trusting soul... I used emacs for years, I was eventually convinced to start using nedit, which is quite nice. For an IDE, which I need for GUI debugging more than all the other sometimes-nice bells and whistles, I use WingIDE and have found it pretty cool but not free. In terms of using it, it's much like any IDE these days and I think learning one is a good platform for learning how IDEs tend to work in general, at least until something genuinely different comes along in that space. I would say a beginner willing to face a learning curve should make sure they know how to edit their project outside of the IDE, understand something about how the IDE makes their project, and so on. From russell.sayers at gmail.com Tue Dec 2 00:21:44 2008 From: russell.sayers at gmail.com (russ) Date: Tue, 2 Dec 2008 16:21:44 +1100 Subject: Google App Engine Code Challenge - write a tetris playing algorithm In-Reply-To: References: <10304c580812011932l7ef375fcv4149f66064d02a30@mail.gmail.com> Message-ID: <10304c580812012121j33adb109n19109e1775f85af7@mail.gmail.com> > > what if you wanted to move a piece to the left or right after its past some > vertical obstruction? > Not _presently_ supporting moving the piece left or right. I've thought about it, and would make things a bit more complicated - just wanted to get something simple "out there", and see how much interest it gets. I've intentionally made the response format so I that I could add this in the future without breaking backward compatibility. On Tue, Dec 2, 2008 at 3:21 PM, Casey McGinty wrote: > Well, I think its a cool idea. I might try it out if I can find some free > cycles. > > And does the game logic assume the pieces come straight down? For example, > what if you wanted to move a piece to the left or right after its past some > vertical obstruction? For example If you place and upside down 'j' or 'l', > is there any way to fill in the two blocked squares, without removing the > top portion first? > > - Casey > -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Mon Dec 1 08:41:17 2008 From: roy at panix.com (Roy Smith) Date: Mon, 01 Dec 2008 08:41:17 -0500 Subject: Emacs vs. Eclipse vs. Vim References: Message-ID: In article , Richard Riley wrote: > Roy Smith writes: > > > Clay Hobbs wrote: > >> The first real text editor I used was Vim, which I actually started > >> using about a year ago. I've looked at Emacs and it just looks > >> confusing. > > > > I've been using emacs for so many years (um let's see, it's got to be close > > to 25 years now; first saw it on Columbia's TOPS-20 systems in the early > > 80's) that my fingers know what they're doing without my even thinking > > about it. In fact, I used to work with another emacs nut. Every so often, > > one of use would watch the other do something and ask, "What was that?". > > Inevitably, neither of us could evoke the keystrokes we had just typed. We > > would just re-do it, and watch our fingers to see what we typed. It didn't > > even have to be on a keyboard; we could air-type it, and that was good > > enough. > > > > In any case, the basic logic behind emacs is pretty simple. C-F is forward > > one character. C-B is back one character. C-N is Next line. C-P is > > Previous line. > > It's worth pointing out to people making "loony" signs here that the > arrow keys work too .... Yeah, I guess. I use the arrows keys to mindlessly scroll around in a file, especially when I just want to show some code to somebody. It serves two purposes. First, I can lean way back from the keyboard and reach out with one hand (giving the other person better visibility). Second, it makes it easier for a non-emacs person to jump in and drive for a while (they saw me use the arrow keys and do the same, no explanations needed). For any serious editing, however, it's strictly the keys on the main part of the keyboard. It's just so much faster when your hands never have to leave their home position. To use the arrow keys, I need to pick my hand up and move it over to the arrow key cluster. Slow, slow, slow. From cjw at ncf.ca Sat Dec 6 10:14:04 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 06 Dec 2008 10:14:04 -0500 Subject: Learning Python now coming from Perl In-Reply-To: References: Message-ID: Bertilo Wennergren wrote: > Roy Smith wrote: > >> Bertilo Wennergren wrote: > >>> I'm planning to start learning Python now, using Python 3000. >>> I have no previous Python skills, but I now Perl pretty well. >>> I'm also well experienced with JavaScript. >>> >>> Any pointers and tips how I should go about getting into >>> Python? > >> I assume you use Perl to solve real problems in whatever job you do. >> My recommendation would be the next time some problem comes up that >> you would normally solve with Perl, try doing it in Python. Having a >> real task that you need to accomplish is a great way to focus the >> mind. For your first project, pick something that's small enough that >> you think you could tackle it in under 50 lines of Perl. > > Good advice. > >> One of the very first things you'll probably discover that's different >> between Perl and Python is how they handle string pattern matching. >> In Perl, it's a built in part of the language syntax. In Python, you >> use the re module. The regular expressions themselves are the same, >> but the mechanism you use to apply them to input text is quite different. > > Thanks. > > I don't suppose there is any introductory material out there > that is based on Python 3000 and that is also geared at people > with a Perl background? Too early for that I guess.. > This is from a post within the last few days: http://www.qtrac.eu/pyqtbook.html Colin W. From martin at v.loewis.de Tue Dec 16 17:09:30 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 16 Dec 2008 23:09:30 +0100 Subject: What does the at sign do? In-Reply-To: References: Message-ID: <4948271a$0$9119$9b622d9e@news.freenet.de> > I'm reading a lot of python code lately, django code to be exact, and > I keep bumping into expressions that look like this > @register.filter > > I see nothing importing @register, so I assume it's not just a > function name. That can't be. register must be a bound name - not necessarily an imported function; it could also be something being set through assignment (register = Registry()). > Yet I cannot figure where this @ sign came from. That's a function decorator; see PEP 318. Regards, Martin From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 9 04:26:54 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 09 Dec 2008 10:26:54 +0100 Subject: Guido's new method definition idea In-Reply-To: <06f8131b-ba72-4f65-a8c9-cc36b0fb586f@x14g2000yqk.googlegroups.com> References: <06f8131b-ba72-4f65-a8c9-cc36b0fb586f@x14g2000yqk.googlegroups.com> Message-ID: <493e39d8$0$2073$426a34cc@news.free.fr> william tanksley a ?crit : > On Dec 5, 6:21 pm, "Daniel Fetchinson" > wrote: >> I'd like this new way of defining methods, what do you guys think? >> Anyone ready for writing a PEP? > > I think it's an awesome proposal. It's about time! With this change, > defining methods uses the same special syntax hack that calling them > does. except that self doesn't exist when the method is defined. Or, should I say, when the function is defined - because that's really a function. It only becomes a method when looked up on the class (either directly or thru an instance), thanks to the descriptor protocol (hint : there's *no* "syntax hack" involved when calling inst.method - just partial evaluation). IOW : this def self.stuff thing only empeds correct understanding of Python's object model. (snip) > I see a lot of people are against it; I admit that it's not the status > quo, but that's not a sufficient argument against a change (it defeats > all possible changes). A more interesting argument against it is that > it's special "implicit" syntax; but I would argue that it merely > reflects the existing special syntax of method calls. Once again, there's *nothing* like an "existing special syntax of method calls". Just the use of the descriptor protocol (the very same mechanism that's powers properties) and partial application. I've already described this more than once in details in this newsgroup FWIW. From bearophileHUGS at lycos.com Fri Dec 5 08:16:48 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 5 Dec 2008 05:16:48 -0800 (PST) Subject: generating a liste of characters References: Message-ID: Mark Tolonen: > Writing a helper function reduces code repetition and improves readability: > ? ? def crange(startch,endch): > ? ? ? ? '''Return a list of characters from startch to endch, inclusive.''' > ? ? ? ? return [chr(c) for c in xrange(ord(startch),ord(endch)+1)] In Python ranges are open on the right, so I name cinterval such function. Bye, bearophile From steve at REMOVE-THIS-cybersource.com.au Tue Dec 30 19:49:04 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Dec 2008 00:49:04 GMT Subject: get method References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> <495AAB97.5010707@mrabarnett.plus.com> <71508d7a-f678-40ba-801c-0bbfbbab961e@r15g2000prh.googlegroups.com> Message-ID: <016ab880$0$6988$c3e8da3@news.astraweb.com> On Wed, 31 Dec 2008 10:29:14 +1000, James Mills wrote: > On Wed, Dec 31, 2008 at 10:22 AM, John Machin > wrote: (snip) > >> The "crawl through the shrubbery looking for evidence" approach >> stumbles on the actual code: > > Yes I found his implementation soon after :) Not bad actually... I > wonder why bag() isn't shipped with the std lib - perhaps in teh set > module ? What set module? >>> import set Traceback (most recent call last): File "", line 1, in ImportError: No module named set Adding a multi-set or bag class to the collections module would be a good idea though. Perhaps you should put in a feature request? -- Steven From aaron.hildebrandt at gmail.com Mon Dec 1 15:29:43 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Mon, 1 Dec 2008 12:29:43 -0800 (PST) Subject: Checking a string against multiple matches References: <99a3a677-a38d-40f5-9a94-a98865150b69@k19g2000yqg.googlegroups.com> Message-ID: <279c426a-214c-4b6f-aaf2-989abd197744@v4g2000yqa.googlegroups.com> Damn you, Python, and your loose documentation! It never occurred to me to actually TRY my pseudocode, since I couldn't find anything on that type of statement. Anyway, feel free to ignore me from now on. From aspineux at gmail.com Sun Dec 28 09:10:06 2008 From: aspineux at gmail.com (aspineux) Date: Sun, 28 Dec 2008 06:10:06 -0800 (PST) Subject: /kolab/bin/python: double free or corruption (fasttop) Message-ID: <78edebdd-030f-4517-b9ed-5225511724d7@t39g2000prh.googlegroups.com> I got this. This is a test script, to help me to understand why I have unexpected result in application. But I got a more unexpected result, and probably wrong error message about the read-only cursor. The full script is at the end. db cleanup, 326 records deleted, 9990 remains Exception in thread Thread-1: Traceback (most recent call last): File "/kolab/lib/python/threading.py", line 486, in __bootstrap_inner self.run() File "/kolab/lib/python/threading.py", line 446, in run self.__target(*self.__args, **self.__kwargs) File "./test/test_bdb.py", line 85, in update_thread=threading.Thread(target=lambda : cleanup(db)) File "./test/test_bdb.py", line 72, in cleanup cursor.delete() DBPermissionsError: (1, 'Operation not permitted -- Write attempted on read- only cursor') Traceback (most recent call last): File "./test/test_bdb.py", line 130, in server() File "./test/test_bdb.py", line 92, in server db[str(last)]=str(last) KeyboardInterrupt *** glibc detected *** /kolab/bin/python: double free or corruption (fasttop): 0 x09d521a8 *** ======= Backtrace: ========= /lib/i686/nosegneg/libc.so.6[0x4444ccfd] /lib/i686/nosegneg/libc.so.6(cfree+0x90)[0x444503b0] /kolab/bin/python(__db_c_destroy+0x60)[0x81fa6f0] /kolab/bin/python(__db_refresh+0x165)[0x81f3515] /kolab/bin/python(__db_close+0x64)[0x81f3cb4] /kolab/bin/python(__db_close_pp+0xa1)[0x8204b61] /kolab/bin/python[0x812123f] /kolab/bin/python[0x8159534] /kolab/bin/python[0x815fb0a] /kolab/bin/python[0x811abbc] /kolab/bin/python[0x811abc9] /kolab/bin/python[0x80b0229] /kolab/bin/python(PyDict_SetItem+0x6e)[0x80b1c0e] /kolab/bin/python(PyDict_SetItemString+0x42)[0x80b1ce2] /kolab/bin/python(PyImport_Cleanup+0xd4)[0x8108294] /kolab/bin/python(Py_Finalize+0xbf)[0x8113f1f] /kolab/bin/python(Py_Main+0x468)[0x80845c8] /kolab/bin/python(main+0x22)[0x8084052] /lib/i686/nosegneg/libc.so.6(__libc_start_main+0xdc)[0x443fbdec] /kolab/bin/python[0x8083fa1] ======= Memory map: ======== 00110000-001d7000 rwxp 00110000 00:00 0 001d7000-001da000 r-xp 00000000 ca:03 973941 /kolab/lib/python/lib- dynload/ t ime.so 001da000-001dc000 rwxp 00002000 ca:03 973941 /kolab/lib/python/lib- dynload/ t ime.so 001dc000-001e0000 r-xp 00000000 ca:03 973938 /kolab/lib/python/lib- dynload/ s trop.so 001e0000-001e2000 rwxp 00003000 ca:03 973938 /kolab/lib/python/lib- dynload/ s trop.so 001e2000-001e3000 r-xp 00000000 ca:03 973911 /kolab/lib/python/lib- dynload/ _ weakref.so 001e3000-001e4000 rwxp 00000000 ca:03 973911 /kolab/lib/python/lib- dynload/ _ weakref.so 001e4000-001ea000 rwxs 00000000 ca:03 1747650 /tmp/db/__db.001 001ea000-001fc000 rwxs 00000000 ca:03 1747651 /tmp/db/__db.002 001fc000-0023e000 rwxs 00000000 ca:03 1747652 /tmp/db/__db.003 00388000-003e0000 rwxs 00000000 ca:03 1747653 /tmp/db/__db.004 00450000-00452000 r-xp 00000000 ca:03 1132355 /lib/libutil-2.5.so 00452000-00453000 r-xp 00001000 ca:03 1132355 /lib/libutil-2.5.so 00453000-00454000 rwxp 00002000 ca:03 1132355 /lib/libutil-2.5.so 00459000-0047e000 r-xp 00000000 ca:03 1132349 /lib/i686/nosegneg/ libm-2.5.so 0047e000-0047f000 r-xp 00024000 ca:03 1132349 /lib/i686/nosegneg/ libm-2.5.so 0047f000-00480000 rwxp 00025000 ca:03 1132349 /lib/i686/nosegneg/ libm-2.5.so 0063e000-0063f000 r-xp 0063e000 00:00 0 [vdso] 0097a000-0098d000 r-xp 00000000 ca:03 1134447 /lib/i686/nosegneg/ libpthread-2 . 5.so 0098d000-0098e000 r-xp 00012000 ca:03 1134447 /lib/i686/nosegneg/ libpthread-2 . 5.so 0098e000-0098f000 rwxp 00013000 ca:03 1134447 /lib/i686/nosegneg/ libpthread-2 . 5.so 0098f000-00991000 rwxp 0098f000 00:00 0 009a8000-009e9000 rwxp 009a8000 00:00 0 00b80000-00d80000 r-xp 00000000 ca:03 845325 /usr/lib/locale/ locale-archive 00ec9000-00ecc000 r-xp 00000000 ca:03 973916 /kolab/lib/python/lib- dynload/ c StringIO.so 00ecc000-00ecd000 rwxp 00003000 ca:03 973916 /kolab/lib/python/lib- dynload/ c StringIO.so 00fd2000-00fd6000 r-xp 00000000 ca:03 973918 /kolab/lib/python/lib- dynload/ c ollections.so 00fd6000-00fd7000 rwxp 00004000 ca:03 973918 /kolab/lib/python/lib- dynload/ c ollections.so 00fd7000-00fd8000 --xp 00fd7000 00:00 0 00fd8000-019d8000 rwxp 00fd8000 00:00 0 08048000-08433000 r-xp 00000000 ca:03 430731 /kolab/bin/python 08433000-0846e000 rwxp 003eb000 ca:03 430731 /kolab/bin/python 0846e000-08478000 rwxp 0846e000 00:00 0 09ce5000-09da5000 rwxp 09ce5000 00:00 0 443c4000-443dd000 r-xp 00000000 ca:03 1132323 /lib/ld-2.5.so 443dd000-443de000 r-xp 00018000 ca:03 1132323 /lib/ld-2.5.so 443de000-443df000 rwxp 00019000 ca:03 1132323 /lib/ld-2.5.so 443e6000-44521000 r-xp 00000000 ca:03 1134399 /lib/i686/nosegneg/ libc-2.5.so 44521000-44523000 r-xp 0013a000 ca:03 1134399 /lib/i686/nosegneg/ libc-2.5.so 44523000-44524000 rwxp 0013c000 ca:03 1134399 /lib/i686/nosegneg/ libc-2.5.so 44524000-44527000 rwxp 44524000 00:00 0 44529000-4452b000 r-xp 00000000 ca:03 1134402 /lib/libdl-2.5.so 4452b000-4452c000 r-xp 00001000 ca:03 1134402 /lib/libdl-2.5.so 4452c000-4452d000 rwxp 00002000 ca:03 1134402 /lib/libdl-2.5.so 44622000-4462d000 r-xp 00000000 ca:03 1134413 /lib/ libgcc_s-4.1.1-20070105.so . 1Aborted #!/kolab/bin/python import os, sys, logging, time, threading import marshal import bsddb.db # this is a test to see how bsddb is reliable # The server count in the db, and the client search for missing value # run on server in a terminal, and a client in another # ====================================================================== # db functions # ====================================================================== db_dir='/tmp/db' db_filename=os.path.join(db_dir, 'test.bdb') try: os.mkdir(db_dir) except OSError: pass freq=100 # new sample per/sec timeout=3 # in sec, how long I wait for them retention=100 # in sec, how long they stay in the db def init_db(read_only=True): # open the environement dbenv=db=None try: db_env=bsddb.db.DBEnv(0) flags=bsddb.db.DB_CREATE | bsddb.db.DB_INIT_CDB | bsddb.db.DB_INIT_MPOOL db_env.open(db_dir, flags) db=bsddb.db.DB(db_env) flags = bsddb.db.DB_DIRTY_READ | ( bsddb.db.DB_RDONLY if read_only else bsddb.db.DB_CREATE ) db.open(db_filename, dbtype=bsddb.db.DB_HASH,flags=flags) except Exception: print 'error opening db' raise else: print 'db opened' return dbenv, db # ---------------------------------------------------------------------- def close_db(dbenv, db): try: if db: db.close() if dbenv: db_env.close() except Exception: log.rcpt.exception('closing db') else: log.rcpt.info('db closed') # ---------------------------------------------------------------------- def now(): return int(time.time()*freq) def cleanup(db): while True: cursor=db.cursor(None, bsddb.db.DB_WRITECURSOR) count=remain=0 c=cursor.first() limit=now()-retention*freq while c: k, v=c t=int(k) if t<=limit: cursor.delete() count+=1 else: remain+=1 c=cursor.next() cursor.close() print 'db cleanup, %d records deleted, %d remains' % (count, remain) time.sleep(timeout) def server(): dbenv, db=init_db(read_only=False) update_thread=threading.Thread(target=lambda : cleanup(db)) update_thread.setDaemon(True) update_thread.start() last=now() while True: while lastmax_delay: max_delay=delay print 'delay', max_delay last+=1 close_db(dbenv, db) if sys.argv[1]=='c': client() elif sys.argv[1]=='s': server() From steve at holdenweb.com Fri Dec 19 17:45:37 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 19 Dec 2008 17:45:37 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <88ff7c46-2b23-49e4-865e-781d23433799@l33g2000pri.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> <88ff7c46-2b23-49e4-865e-781d23433799@l33g2000pri.googlegroups.com> Message-ID: r wrote: [...] > Like Python?s forcing of empty tuple in function calls, that is a good > idea. This allows you to clearly see arguments in source code. I like > in Python there is only one, or a very minimal number of ways to do > something(but usually only one is the best). Ruby is littered with > different ways to do the same thing. I think this will be Ruby?s > undoing?. And Pythons if we follow down this road. > > And lets not forget Python forcing of indention, that is Pythons > greatest strength! > Kindly allow me to disabuse you of the notion that a function call with no arguments is a function reference followed by an empty tuple. It might *look* like that, but it isn't. Otherwise we'd write a function call with one argument as f(a, ) - which readers will have noticed we don't. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From stephen at thorne.id.au Fri Dec 12 01:01:48 2008 From: stephen at thorne.id.au (Stephen Thorne) Date: Fri, 12 Dec 2008 16:01:48 +1000 Subject: how to convert '\xf0' to 0xf0 ? In-Reply-To: <8f5b95c0-486d-48ce-b75c-e18a86d73f50@l33g2000pri.googlegroups.com> References: <1cb85265-1c36-4e4b-88f1-46b0ebae3dea@v5g2000prm.googlegroups.com> <8f5b95c0-486d-48ce-b75c-e18a86d73f50@l33g2000pri.googlegroups.com> Message-ID: <20081212060148.GA25165@thorne.id.au> On 2008-12-11, chengang.beijing at gmail.com wrote: > Hi, > > ord('\xf0') works and it only works for char. Do you know any way to > convet > '\xf0\xf0' and '\xf0\xf0\xff\xfe' to integer? Perhaps you want the 'struct' module. >>> struct.unpack('!hi', '\xf0\xf0\xf0\xf0\xff\xfe') (-3856, -252641282) help(struct) for more information -- Regards, Stephen Thorne Development Engineer NetBox Blue - 1300 737 060 Scanned by the NetBox from NetBox Blue (http://netboxblue.com/) From sjmachin at lexicon.net Thu Dec 18 06:30:02 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 18 Dec 2008 03:30:02 -0800 (PST) Subject: importing csv file into sqlite References: <21067453.post@talk.nabble.com> Message-ID: <7f64f5c6-b130-4f9b-a670-6b32eccba550@n33g2000pri.googlegroups.com> On Dec 18, 6:20?pm, klia wrote: > klia wrote: > > > hey guys, i have a hug .csv file which i need to insert it into sqlite > > database using python. > > my csv data looks like this > > Birthday2,12/5/2008,HTC,this is my birthday > > Sea,12/3/2008,kodak,sea > > birthday4,14/3/2009,samsung,birthday > > love,17/4/2009,SONY,view of island > > > can any one give me a head start codes. > > > thanks in advance > > guys so far i came out with this but i get this error > waseem at Linux:~/Project2$ python experment.py > Traceback (most recent call last): > ? File "experment.py", line 13, in > ? ? curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item) > sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current > statement uses 4, and there are 1 supplied. > > here's the codes > > import sqlite3 > import csv > > f = open('/home/waseem/Project2/photos.txt') > csv.field_size_limit(100000) #see below! I see nothing "below" that looks at all like an attempt to justify setting the field size limit to 100000 -- why are you doing that? Tends to make one suspect a problem with your delimiter and/or your line separator. > input = csv.reader(f, delimiter='\t') Why \t??? Your data examples show commas -- could this be why you are getting one field per line (as Peter has pointed out)? > conn = sqlite3.connect('/home/waseem/Project2/picutres.db') Is it really called "picutres" instead of "pictures", or are you typing the code that you ran again from (your) memory? > curse = conn.cursor() > > curse.execute('CREATE TABLE photos (Name VARCHAR(100) PRIMARY KEY, Date > INTEGER, Make VARCHAR(50), Tag VARCHAR(100))') [OT but to save the next question] The column named "Date" is defined to be INTEGER but the data from the CSV file will be a str object e.g. "12/5/2008" ... I know sqlite cheerfully regards column types as vague reminders rather than enforceable constraints on your input, but wouldn't you like to convert your dates to e.g. "2008-05-12" before you poke them in? You may want to use "ORDER BY Date" at some stage, and so that ORDER BY isn't whacked and GROUP BY doesn't give ludicrous results, wouldn't it be a good idea to crunch 12/5/2008 and 12/05/2008 into a common format so that they compare equal? > > for item in input: I strongly suggest that you try to get a clue about exactly what you are getting from the csv reader e.g. for line_num, item in enumerate(input_renamed_as_suggested_by_anor): print line_num, repr(item) > ? ? ? ? curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item) > curse.commit() > HTH, John From Scott.Daniels at Acm.Org Thu Dec 11 14:45:25 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 11 Dec 2008 11:45:25 -0800 Subject: Python, threading In-Reply-To: References: Message-ID: SMALLp wrote: > ... I need a tip on how to communicat4 between threads. Typically inter-thread communication is done via Queue.Queue. Look up the Queue module in your docs. a "Simple" example: import Queue shared_work = Queue.Queue() combined_replies = Queue.Queue() ... [distributor] in loop: shared_work.put(something_to_do) ... for n in range(workers): shared_work.put(None) # tell everybody to stop for thread in workers: thread.join(worker) # wait til they all finish combined_replies.put(None) # tell service to stop thread.join(writer) # wait til it is done. ... [workers] ... for work in iter(shared_work.get, None): combined_replies.put('whatever') ... ... [writer] for results in iter(combined_results.get, None): --Scott David Daniels Scott.Daniels at Acm.Org From kay.schluehr at gmx.net Fri Dec 5 01:07:44 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 4 Dec 2008 22:07:44 -0800 (PST) Subject: Porting to 3.0, test coverage References: <8f25bd4f-fd2f-4908-88ee-852624cf3234@z6g2000pre.googlegroups.com> Message-ID: <692ca265-95bf-4fca-ad80-0edee496e5b2@t2g2000yqm.googlegroups.com> On 4 Dez., 23:40, Paul Hildebrandt wrote: > I was just reading what's new with Python 3.0http://docs.python.org/dev/3.0/whatsnew/3.0.html > > I like this prerequisite to porting: "Start with excellent test > coverage" > > May I suggest looking into Pythoscope for those looking to boost test > coverage. > > http://pythoscope.org > > Paul This is surely interesting but occasionally it would be just too nice if *someone else* would advertise ones own projects ;) Here is more stuff http://www.pycheesecake.org/wiki/PythonTestingToolsTaxonomy From iNkOhSnPaAtMon at free.fr Mon Dec 8 12:17:20 2008 From: iNkOhSnPaAtMon at free.fr (Pascal) Date: 08 Dec 2008 17:17:20 GMT Subject: [Py2exe-users] py2exe 0.6.9 released References: <49216608$0$9585$426a74cc@news.free.fr> <493d3371$0$15192$426a74cc@news.free.fr> Message-ID: <493d56a0$0$4643$426a74cc@news.free.fr> On Mon, 08 Dec 2008 14:47:13 +0000, Pascal wrote: > On Mon, 17 Nov 2008 12:39:36 +0000, Pascal wrote: > >> On Sun, 16 Nov 2008 21:23:59 -0500, Chris Spencer wrote: >> >>> After I "compile" my program with py2exe 0.6.9 with Python 2.6, I'm >>> still getting the "Application Did Not Initialize Properly" error >>> dialog whenever I run my code. What am I doing wrong? >> >> I have exactly the same problem. >> I have tried just anything I could think of to no avail : Copied the 3 >> msvc_90.dll to the system32 subdir of Windows, to the directory of my >> application, reinstalled the whole Microsoft Visual C++ 2008 >> Redistributable Package, embedded the manifest data into the exe or >> kept it in a .manifest file... >> Could not make it work. Always got the "Application Did Not Initialize >> Properly" message. >> I'm with Windows XP SP3. I tried all this on 2 different systems and I >> got the same results. > > > I think I narrowed down a little bit the problem. It's not the common > one when the msvc_90.dll are not located, though the result is similar. > The problem is when you try to generate at least 2 exe in one setup > (with 2 scripts specified in the "windows" command of the setup). This > works OK with py2exe 0.6.9 for Python 2.5, but fails with Python 2.6 > (and 2.6.1). None of the generated exe can be started. When I compare > the content of library.zip in both versions, this file doesn't contain > any .pyc for the scripts you want to generate an exe for with Python > 2.5, but always contains a .pyc for one of the scripts you want to > generate an .exe for with Python 2.6. Don't know if it's a clue for > finding a fix. > I have tested many ways to figure this out but I can't find any solution > for the moment so I'm sticking with Python 2.5. Got it ! If you want to generate an exe for a script of your own named abc.py, rename it because this will never work with that original name. The reason seems to be an abc.pyc file compiled by default by Python 2.6 and included in library.zip (abc stands in this case for "Abstract Base Classes"), and using this name for your own script makes nothing work ! From cjw at ncf.ca Sat Dec 27 17:14:27 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 27 Dec 2008 17:14:27 -0500 Subject: multiply each element of a list by a number In-Reply-To: <4955e7be$0$4066$ba4acef3@news.orange.fr> References: <4955e7be$0$4066$ba4acef3@news.orange.fr> Message-ID: M?ta-MCI (MVP) wrote: > Hi! > >> map(multby3, (1, 2, 3, )) > > ....with lambda: map(lambda x: x*3, [1,2,3]) > > @-salutations More lines but perhaps faster than numpy: PythonWin 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32. Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for further copyright information. >>> lst= [1,2,3] >>> trippleList= [3*a for a in lst] >>> trippleList [3, 6, 9] >>> Colin W. From nospam at forMe.thks Mon Dec 15 11:29:39 2008 From: nospam at forMe.thks (Ross) Date: Mon, 15 Dec 2008 11:29:39 -0500 Subject: Managing timing in Python calls In-Reply-To: References: Message-ID: bieffe62 at gmail.com wrote: > > Python has in its standard library a timer class which actually is > implemented as a thread (I think) ... > however, when using a GUI package, I think it is better to use gui- > specific functions for event-driven programming, > to make sure that your code do not mess with GUI event loop and to > work around the lack of thread-safety in some GUI libraries. > This applies to timer/timeouts but also to execute code when specific > I/O events occur ( e.g. the receiving of data from a socket ). > > Although I'm not an expert of pywx, a quick search pointed me to this > page: > > http://wxpython.org/onlinedocs.php > > from which it seams that WxTimerEvent couldbe what you need. > > I agree with you that for loading images from local files a thread > should not be needed. > > P.S : notice that the documentation refers to the C++ library on which > the python wrapper is built. This is often the case for > python wrapper of GUI libraries. However, the most important ones come > with a rich set of demo programs (and pywx demo suite is quite > complete) from which one can lear what he needs. > > Ciao > ----- > FB > The wxTimerEvent does sound attractive - I'll look into that. Thanks too for the opinion on loading images - gives me some guts to just give it a try without threading it and see how it goes. I appreciate the quick input :) Ross. From martin at marcher.name Fri Dec 26 19:05:16 2008 From: martin at marcher.name (Martin) Date: Sat, 27 Dec 2008 01:05:16 +0100 Subject: Right way to set a variable to NULL? In-Reply-To: <098da1d1-640c-4aef-b005-5f0932f291cc@35g2000pry.googlegroups.com> References: <5nfal41gom0iqi2nh5h0m5847ev9brtvpf@4ax.com> <098da1d1-640c-4aef-b005-5f0932f291cc@35g2000pry.googlegroups.com> Message-ID: <5fa6c12e0812261605n765ea64aha5117de7bb759676@mail.gmail.com> 2008/12/26 John Machin : > The above all have the same characteristic: if the input is a zero- > length string, then NULL is inserted into the database instead of a > zero-length string. Some folks (not just pedants!) regard that as an > important difference. agreed but I understood the OP specifically wanted NULL and not ''. of course for data gathering in web apps I'd personally make the mail attribute a NOT NULL and reject anybody who wouldn't give me their mail address. After all mail is the way to get in touch with my customers/user if they register on my site, and if it's only for a password reset link. /martin -- http://soup.alt.delete.co.at http://www.xing.com/profile/Martin_Marcher http://www.linkedin.com/in/martinmarcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From steve at holdenweb.com Tue Dec 16 12:18:07 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 16 Dec 2008 12:18:07 -0500 Subject: tricky nested list unpacking problem In-Reply-To: <47c890dc0812151203m7931ec0eif71b2ca8451465aa@mail.gmail.com> References: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> <47c890dc0812151203m7931ec0eif71b2ca8451465aa@mail.gmail.com> Message-ID: Chris Rebert wrote: > On Mon, Dec 15, 2008 at 11:06 AM, Reckoner wrote: >> Hi, >> >> I have lists of the following type: >> >> [1,2,3,[5,6]] >> >> and I want to produce the following strings from this as >> >> '0-1-2-3-5' >> '0-1-2-3-6' >> >> That was easy enough. The problem is that these can be nested. For >> example: >> >> [1,2,3,[5,6],[7,8,9]] >> >> which should produce >> >> '0-1-2-3-5-7' >> '0-1-2-3-5-8' >> '0-1-2-3-5-9' >> '0-1-2-3-6-7' >> '0-1-2-3-6-8' >> '0-1-2-3-6-9' >> >> also, >> >> [1,2,3,[5,6],7,[9]] >> >> should produce >> >> '0-1-2-3-5-7-9' >> '0-1-2-3-6-7-9' >> >> obviously, these are nested loops over the lists. The problem is that >> I don't know ahead of time how many lists there are or how deep they >> go. In other words, you could have: >> >> [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]] >> >> Any help appreciated. I've really been having trouble with this. >> >> I hope that made sense. > > You just need a recursive list-flattening function. There are many > recipes for these. Here's mine: > > def flatten(lst): > if isinstance(lst, list): > result = [] > for item in lst: > result += flatten(item) > return result > else: > return [lst] > >>>> flattened = flatten([1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]]) >>>> flattened > [1, 2, 3, 5, 6, 10, 11, 7, 9, 1, 2, 3, 4, 5] >>>> '-'.join(str(num) for num in flattened) > '1-2-3-5-6-10-11-7-9-1-2-3-4-5' > Read the problem description again ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From george.sakkis at gmail.com Tue Dec 2 11:50:32 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 2 Dec 2008 08:50:32 -0800 (PST) Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> <258cf433-f6c9-43e7-a235-f5f6b2b6433f@j39g2000yqn.googlegroups.com> <33b4cc2f-2311-491c-a2e6-9cc5452b1a6b@g38g2000yqd.googlegroups.com> Message-ID: <652449ff-3a5b-41be-a033-c3c355d277b8@z1g2000yqn.googlegroups.com> On Dec 2, 10:01?am, Slaunger wrote: > Just wanted to show the end result in its actual implementation! > > I ended up *not* making a decorator, as I already had a good idea > about how to do it > using __getattr__ > > class PayloadDualFrqIQOnDemand(PayloadDualFrqIQ): > ? ? """ > ? ? This class has the same interface as its parent, > ? ? but unlike its parent, it is instantiated without > ? ? its payload parsed up in its instance attributes > ? ? Q1, I1, Q2 and I2. Instead it stores a reference to > ? ? the file object in which the Payload data can be > ? ? read, the file position and > ? ? the version of the payload data. > > ? ? On accessing one of the data attributes, the actual > ? ? payload data are read from the file, and the reference to > ? ? the file object is unbound. > ? ? The constructor signature is therefore different from its > ? ? parent as it takes the file object, position and version > ? ? as arguments instead of the actual data. > ? ? """ > > ? ? @classmethod > ? ? def _unpack_from_file(cls, f, samples, ver): > ? ? ? ? bytes = samples * cls.bytes_per_sample > ? ? ? ? initial_pos = f.tell() > ? ? ? ? f.seek(initial_pos + bytes) #Skip over the payload > ? ? ? ? return cls(f, initial_pos, samples, ver) > > ? ? @classmethod > ? ? def unpack_from_ver3_file(cls, f, samples): > ? ? ? ? return cls._unpack_from_file(f, samples, ver=3) > > ? ? @classmethod > ? ? def unpack_from_ver4_file(cls, f, samples): > ? ? ? ? return cls._unpack_from_file(f, samples, ver=4) > > ? ? data_attr_names = frozenset(["Q1", "I1", "Q2", "I2"]) > > ? ? def __init__(self, a_file, a_file_position, samples, a_version): > ? ? ? ? """ > ? ? ? ? Returns an instance where the object knows where to > ? ? ? ? look for the payload but it will only be loaded on the > ? ? ? ? first attempt to read one of the data attributes > ? ? ? ? in a "normal" PayloadDualFrqIQ object. > ? ? ? ? """ > ? ? ? ? self.f = a_file > ? ? ? ? self.file_position = a_file_position > ? ? ? ? self.samples = samples > ? ? ? ? self.ver = a_version > > ? ? def __getattr__(self, attr_name): > ? ? ? ? """ > ? ? ? ? Checks if a request to read a non-existing data attribute > ? ? ? ? has an attribute corresponding to one of the data attributes > ? ? ? ? in a normal PayloadDualFrqIQ object. > > ? ? ? ? If true, the data attributes are created and bound to the > ? ? ? ? object using the file object instance, the file position > ? ? ? ? and the version. > > ? ? ? ? It is a prerequisite that the file object is still open. > ? ? ? ? The function leaves the file object at the file position > ? ? ? ? when it entered the method > > ? ? ? ? """ > ? ? ? ? cls = self.__class__ > ? ? ? ? if attr_name in cls.data_attr_names: > ? ? ? ? ? ? initial_pos = self.f.tell() > ? ? ? ? ? ? try: > ? ? ? ? ? ? ? ? bytes = self.samples * cls.bytes_per_sample > ? ? ? ? ? ? ? ? self.f.seek(self.file_position) > ? ? ? ? ? ? ? ? buf = self.f.read(bytes) > ? ? ? ? ? ? ? ? if self.ver == 3: > ? ? ? ? ? ? ? ? ? ? bytes_to_data = cls._v3_byte_str_to_data > ? ? ? ? ? ? ? ? elif self.ver == 4: > ? ? ? ? ? ? ? ? ? ? bytes_to_data = cls._v4_byte_str_to_data > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? raise TermaNotImplemented, \ > ? ? ? ? ? ? ? ? ? ? ? ? "Support for ver. %d not implemented." % > self.ver > ? ? ? ? ? ? ? ? I1, Q1, I2, Q2 = bytes_to_data(buf) > ? ? ? ? ? ? ? ? self.__dict__["I1"] = I1 > ? ? ? ? ? ? ? ? self.__dict__["Q1"] = Q1 > ? ? ? ? ? ? ? ? self.__dict__["I2"] = I2 > ? ? ? ? ? ? ? ? self.__dict__["Q2"] = Q2 > ? ? ? ? ? ? ? ? return self.__dict__[attr_name] > ? ? ? ? ? ? finally: > ? ? ? ? ? ? ? ? # Restore file position > ? ? ? ? ? ? ? ? self.f.seek(initial_pos) > ? ? ? ? ? ? ? ? # Unbind lazy attributes > ? ? ? ? ? ? ? ? del self.f > ? ? ? ? ? ? ? ? del self.ver > ? ? ? ? ? ? ? ? del self.file_position > ? ? ? ? ? ? ? ? del self.samples > > This seems to work out well. No infinite loops in __getattr__! > > At least it passes the unit test cases I have come up with so far. > > No guarantees though, as I may simply not have been smart enough to > bring forth unit test cases which make it crash. > > Comments on the code is still appreciated though. A trivial improvement: replace > I1, Q1, I2, Q2 = bytes_to_data(buf) > self.__dict__["I1"] = I1 > self.__dict__["Q1"] = Q1 > self.__dict__["I2"] = I2 > self.__dict__["Q2"] = Q2 with: self.__dict__.update(zip(self.data_attr_names, bytes_to_data (buf))) where data_attr_names = ("I1", "Q1", "I2", "Q2") instead of a frozenset. A linear search in a size-4 tuple is unlikely to be the bottleneck with much I/O anyway. George From jyoung79 at kc.rr.com Fri Dec 19 10:19:28 2008 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Fri, 19 Dec 2008 9:19:28 -0600 Subject: change string to unicode Message-ID: <20081219151928.6I5XU.331464.root@hrndva-web01-z02> If I have a string like so: a = '\\u03B1' and I want to make it display a Greek alpha character, is there a way to convert it to unicode ('\u03B1')? I tried concatenating it like this: '\u' + '03B1' but that didn't work. I'm working in Python 3.0 and was curious if this could be done. Thanks. Jay From 5lvqbwl02 at sneakemail.com Tue Dec 30 14:41:47 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Tue, 30 Dec 2008 11:41:47 -0800 (PST) Subject: need help with list/variables References: <63b5acce-d566-48cb-abce-c00fd0e02a39@v39g2000pro.googlegroups.com> Message-ID: On Dec 30, 11:31?am, wx1... at gmail.com wrote: > I have a list and would like to parse the list appending each list > item to the end of a variable on a new line. > > for instance > > mylist = ['something\n', 'another something\n', 'something again\n'] > > then parse mylist to make it appear in my variable in this format: > > myvar = """ > something > another something > something again""" > > how would i go about setting a variable like this? I think you want to concatenate the three elements in your list and then assign the resulting string to myvar. Strings that are defined with tripple quotes still get the newline character as though they were defined with double or single quotes and \n in them. >>> conc = lambda x,y: x[:] + y # concatenate 2 lists without side effects >>> mylist = ['something\n', 'another something\n', 'something again\n'] >>> myvar = reduce(conc, mylist) >>> print myvar something another something something again Hope this helps michael From Ron.Barak at lsi.com Tue Dec 16 08:51:10 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Tue, 16 Dec 2008 13:51:10 +0000 Subject: String slices work only for first string character ? In-Reply-To: <20081216084452.f1a3002a.darcy@druid.net> References: <7F0503CD69378F49BE0DC30661C6CCF60249410A@enbmail01.lsi.com> <20081216084452.f1a3002a.darcy@druid.net> Message-ID: <7F0503CD69378F49BE0DC30661C6CCF602494115@enbmail01.lsi.com> Hi Mr. Cain, Mae culpa: obviously, I erroneously understood the number after the ':' as the string length. Thanks, Ron. -----Original Message----- From: D'Arcy J.M. Cain [mailto:darcy at druid.net] Sent: Tuesday, December 16, 2008 15:45 To: Barak, Ron Cc: python-list at python.org Subject: Re: String slices work only for first string character ? On Tue, 16 Dec 2008 13:35:27 +0000 "Barak, Ron" wrote: > Can any one explain why the following string slice works only for the first character, but not for any other ? I think that you need to reread the docs on slices. > print "|"+data[0:1]+"|" > print "|"+data[1:1]+"|" If you want the second character use "data[1:2]". -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From jstroud at mbi.ucla.edu Sat Dec 6 02:57:41 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 05 Dec 2008 23:57:41 -0800 Subject: Guido's new method definition idea In-Reply-To: <014a071a$0$20670$c3e8da3@news.astraweb.com> References: <014a071a$0$20670$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Fri, 05 Dec 2008 20:35:07 -0800, James Stroud wrote: >> Daniel Fetchinson wrote: >>> I'd like this new way of defining methods, what do you guys think? >> Consider the maverick who insists on >> >> class C: >> def me.method(arg): >> self.value = arg > > Replace "self" with "me". Yes, I corrected myself one minute after I made the typo. >> which should be equivalent to >> >> class C: >> def method(me, arg): >> me.value = arg >> >> What's the interpreter going to do with our maverick's code? > > I don't see why you think this is a problem. The behavior was unspecified as far as I could tell and I was curious as to whether "me" would still be allowed as a reference to self. Allowing alternatives to "self" would maintain backwards compatibility as the use of self has been a convention and not enforced by the language. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From gagsl-py2 at yahoo.com.ar Sat Dec 27 21:44:29 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 28 Dec 2008 00:44:29 -0200 Subject: ctypes & strings References: <334452.47084.qm@web30003.mail.mud.yahoo.com> <000f01c96822$5c300f00$0d00a8c0@hendrik> <23bb633f-494a-4390-9158-15ee0f1967e5@l33g2000pri.googlegroups.com> Message-ID: En Sat, 27 Dec 2008 22:06:23 -0200, Aaron Brady escribi?: > On Dec 27, 2:03?pm, "Gabriel Genellina" > wrote: >> En Sat, 27 Dec 2008 10:54:32 -0200, Hendrik van Rooyen ? >> escribi?: >> >> > The c routine will actually break Python's normal string >> > immmutability and give you back a changed ins. >> >> Hmmm, I don't think posting a potentially harmful example is actually a >> good idea... > > Hendrik is right, though. The ctypes module allows us to break string > immutability within Python code. Ok, it *can* be done, but it's far from being a recommended practice... and I would never use such wizardry in production code. -- Gabriel Genellina From castironpi at gmail.com Thu Dec 4 06:10:16 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 4 Dec 2008 03:10:16 -0800 (PST) Subject: "as" keyword woes References: Message-ID: <04441f9e-62ba-49c1-bc2f-b0b89a12d29b@s20g2000yqh.googlegroups.com> On Dec 4, 3:28?am, "Warren DeLano" wrote: > > Have you > > even looked at multiprocessing? > Multiprocessing solves some problems, but it is unsuitable for > high-frequency handoffs of large (in memory) objects between many > independent threads/processes -- the HPC object/data flow > parallelization model in a nutshell. ? I think 'mmap' combined with 'ctypes.Structure' is an underrated approach to such use cases. There is also POSH, Python Object Sharing. From kay.schluehr at gmx.net Fri Dec 12 22:49:23 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Fri, 12 Dec 2008 19:49:23 -0800 (PST) Subject: ActivePython 2.6.1.1 and 3.0.0.0 released! References: Message-ID: <58cd9ea1-9cf5-4c90-81ba-411774a878b7@o4g2000pra.googlegroups.com> On 13 Dez., 00:16, Trent Mick wrote: > Note that currently PyWin32 is not included in ActivePython 3.0. Is there any activity in this direction? From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 06:48:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Dec 2008 11:48:21 GMT Subject: Don't you just love writing this sort of thing :) References: Message-ID: <01490cc5$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 23:32:49 +1300, Lawrence D'Oliveiro wrote: > In message , Duncan Booth wrote: > >> ... but the mess you posted is going to be virtually untestable ... > > The "mess" I posted did actually work as written. > >> ... whereas splitting it up into small testable functions will make it >> much easier for you to actually get somewhere near your goal of correct >> code. > > The code people write is probably a direct reflection of their thinking > processes: For example, slow, plodding, one step at a time, incapable of > imaginative leaps, versus those who operate directly on larger patterns > at once... Gosh Lawrence, do tell, which category do YOU fall into? I'd probably be able to work it out on my own, if not for me being one of the plodders incapable of imaginative leaps. -- Steven From Ron.Barak at lsi.com Mon Dec 22 05:16:16 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Mon, 22 Dec 2008 10:16:16 +0000 Subject: Basic misunderstanding of generators - resolved In-Reply-To: <47c890dc0812220153h2fb80c09ibed9836a9c36f489@mail.gmail.com> References: <7F0503CD69378F49BE0DC30661C6CCF6024944BB@enbmail01.lsi.com> <47c890dc0812220153h2fb80c09ibed9836a9c36f489@mail.gmail.com> Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6024944C7@enbmail01.lsi.com> Hi Chris, Thanks for the super fast reply. I tried your fix (with a slight modification, namely, I changed your line to be: line_ = generator.next()) And I got the printout I expected. Many thanks, Ron. P.S.: My program looks like so, with your suggestion: $ cat LogManager_try.py #!/usr/bin/env python import gzip import os class LogStream(): """ """ def __init__(self, filename): self.filename = filename self.input_file = self.open_file(filename) def open_file(self, in_file): """ The gzip module checks if the input file is a gzipped file, only at the read stage. This is why the f.readline() is needed. """ try: f = gzip.GzipFile(in_file, "r") f.readline() except IOError: f = open(in_file, "r") f.readline() f.seek(0) return(f) def next_line(self, in_file): """ """ for line_ in in_file: yield line_.strip() if __name__ == "__main__": filename = "sac.log.gz" log_stream = LogStream(filename) generator = log_stream.next_line(log_stream.input_file) #create generator line_ = generator.next() #get next item from generator print line_ -----Original Message----- From: cvrebert at gmail.com [mailto:cvrebert at gmail.com] On Behalf Of Chris Rebert Sent: Monday, December 22, 2008 11:53 To: Barak, Ron Cc: python-list at python.org Subject: Re: Basic misunderstanding of generators On Mon, Dec 22, 2008 at 1:47 AM, Barak, Ron wrote: > Hi All, > > I want to use generators to print lines taken from a gzipped file. > I've never used generators, so probably my problem is basic > misunderstanding of generators. > > In the below program, I expected the last line ("print line_") to > print the first line of the sac.log.gz file. > Instead, I get: > > > > Could you tell me what I'm doing wrong (or point me to a URL that > could set me straight) ? > > Thanks, > Ron. > > > $ cat LogManager_try.py > #!/usr/bin/env python > > import gzip > import os > > class LogStream(): > """ > """ > > def __init__(self, filename): > self.filename = filename > self.input_file = self.open_file(filename) > > def open_file(self, in_file): > """ > The gzip module checks if the input file is a gzipped file, > only at the read stage. > This is why the f.readline() is needed. > """ > try: > f = gzip.GzipFile(in_file, "r") > f.readline() > except IOError: > f = open(in_file, "r") > f.readline() > > f.seek(0) > return(f) > > def next_line(self, in_file): > """ > """ > for line_ in in_file: > yield line_.strip() > > if __name__ == "__main__": > filename = "sac.log.gz" > log_stream = LogStream(filename) generator = log_stream.next_line(log_stream.input_file) #create generator line_ = generator() #get next item from generator print line_ And as you can see, this makes next_line a bit of a misnomer. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From stef.mientki at gmail.com Mon Dec 1 16:42:13 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 01 Dec 2008 22:42:13 +0100 Subject: Why doesn't doc has predifined name and location ? In-Reply-To: <47c890dc0812011330m1965757cgc7d21f971f01c305@mail.gmail.com> References: <493455AD.4040306@gmail.com> <47c890dc0812011330m1965757cgc7d21f971f01c305@mail.gmail.com> Message-ID: <49345A35.3080606@gmail.com> Chris Rebert wrote: > On Mon, Dec 1, 2008 at 1:22 PM, Stef Mientki wrote: > >> hello, >> >> I'm very satisfied about the great standardization of doc strings in python. >> Now in contrast to that, >> the general documentation of libraries, >> either in plain text, html, pdf, chm, ... >> doesn't have a standarized name nor location. >> >> Why is that ? >> > > I suppose the need for such standardization has just never arisen. > Googling for docs, checking the library's website, or doing `locate > library-name-here | grep doc` in bash seems to work well enough for > people that no one has found it necessary to pursue the creation of > such a standard. > > Not I, but my program wants to locate all the available documentation, that's why I'm interested. > Sidenote: what Python projects publish their docs in CHM besides > possibly Win32 GUI programs? > what about Python25.chm ;-) cheers, Stef > Cheers, > Chris > From dfnsonfsduifb at gmx.de Fri Dec 5 09:25:23 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Fri, 05 Dec 2008 15:25:23 +0100 Subject: Python 3.0 automatic decoding of UTF16 Message-ID: Hello group, I'm having trouble reading a utf-16 encoded file with Python3.0. This is my (complete) code: #!/usr/bin/python3.0 class AddressBook(): def __init__(self, filename): f = open(filename, "r", encoding="utf16") while True: line = f.readline() if line == "": break print([line[x] for x in range(len(line))]) f.close() a = AddressBook("2008_11_05_Handy_Backup.txt") This is the file (only 1 kB, if hosting doesn't work please tell me and I'll see if I can put it someplace else): http://www.file-upload.net/download-1297291/2008_11_05_Handy_Backup.txt.gz.html What I get: The file reads file the first few lines. Then, in the last line, I get lots of garbage (looking like uninitialized memory): ['E', 'n', 't', 'r', 'y', '0', '0', 'T', 'e', 'x', 't', ' ', '=', ' ', '"', 'A', 'D', 'A', 'C', ' ', 'V', 'e', 'r', 'k', 'e', 'h', 'r', 's', 'i', 'n', 'f', 'o', '"', '\u0d00', '\u0a00', '?', '?', '?', '?', '? ', '\u3000', '\u3100', '?', '?', '?', '?', '\u2000', '?', '\u2000', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '\u0d00', '\u0a00', '?', '?', '?', '?', '?', '\u3000', '\u3100', ' ?', '?', '?', '?', '\u2000', '?', '\u2000', '?', '?', '?', '?', '\u3100', '?', '?', '?', '?', '?', '?', '?', '?', '\u0d00', '\u0a00', '\u0d00', '\u0a00', '?', '?', '?', '?', '?', '?', '?', '?', '?', '\u3000', '\u3000', '?', '?', '\u0d00', '\u0a00'] Where the line Entry00Text = "ADAC Verkehrsinfo"\r\n is actually the only thing the line contains, Python makes the rest up. The actual file is much longer and contains private numbers, so I truncated them away. When I let python process the original file, it dies with another error: Traceback (most recent call last): File "./modify.py", line 12, in a = AddressBook("2008_11_05_Handy_Backup.txt") File "./modify.py", line 7, in __init__ line = f.readline() File "/usr/local/lib/python3.0/io.py", line 1807, in readline while self._read_chunk(): File "/usr/local/lib/python3.0/io.py", line 1556, in _read_chunk self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) File "/usr/local/lib/python3.0/io.py", line 1293, in decode output = self.decoder.decode(input, final=final) File "/usr/local/lib/python3.0/codecs.py", line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) File "/usr/local/lib/python3.0/encodings/utf_16.py", line 69, in _buffer_decode return self.decoder(input, self.errors, final) UnicodeDecodeError: 'utf16' codec can't decode bytes in position 74-75: illegal encoding With the place where it dies being exactly the place where it outputs the weird garbage in the shortened file. I guess it runs over some page boundary here or something? Kind regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From roy at panix.com Sun Dec 28 12:47:24 2008 From: roy at panix.com (Roy Smith) Date: Sun, 28 Dec 2008 12:47:24 -0500 Subject: How to "kill" orphaned threads at program exit References: Message-ID: In article , "Giampaolo Rodola'" wrote: > Hi, > I know that it's not possible to "kill" threads but I'm wondering if > does exist some workaround for my problem. > I have a test suite which does a massive usage of threads. > Sometimes happens that one test fails, the test suite keeps running > until the end, and when it's finished the program hangs on and the > only way to stop is to kill it manually. You don't say how you're creating your threads, so I'll assume you're using threading.Thread(). After creating each thread, and before calling start() on it, call setDaemon(True). From ptmcg at austin.rr.com Wed Dec 10 14:07:01 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 10 Dec 2008 11:07:01 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: <075d8c52-93e9-40f4-9eb6-794ce275651e@g38g2000yqd.googlegroups.com> On Dec 10, 12:42?pm, cm_gui wrote: > Python is slow. Very slow. And... ? Was there a question or specific suggestion in there somewhere? Do you go to your mechanic and say "My car wont go as fast as the other cars on the road! They should make it faster!"? Good luck to you in your futile, uh I meant, *future* endeavors. (No wait, I really meant "futile".) -- Paul From ionut.vancea at gmail.com Thu Dec 4 08:32:03 2008 From: ionut.vancea at gmail.com (Ionut Vancea) Date: Thu, 4 Dec 2008 13:32:03 +0000 Subject: RELEASED Python 3.0 final In-Reply-To: References: Message-ID: <368177940812040532y2e7bfe0ev48226aee50bac531@mail.gmail.com> Hello, On Thu, Dec 4, 2008 at 1:51 AM, Barry Warsaw wrote: > -----BEGIN PGP SIGNED MESSAGE----- > We will continue to > support and develop both Python 3 and Python 2 for the foreseeable future, > and you can safely choose either version (or both) to use in your projects. > Which you choose depends on your own needs and the availability of > third-party packages that you depend on. I would like to ask, how long will Python 2 be developed? Just for curiosity. Thank you for your work. Cheers, - === Ioan Vancea http://www.vioan.ro From ndbecker2 at gmail.com Thu Dec 18 09:51:01 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 18 Dec 2008 09:51:01 -0500 Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> Message-ID: Tino Wildenhain wrote: > Neal Becker wrote: > ... >>>> So if __str__ is "meant for human eyes", then why isn't print using it! >>> it is: >>> >>> > print x >>> str >>> >>> but dict just uses repr() for all its childs to print. >>> >>> T. >> That makes no sense to me. If I call 'print' on a container, why >> wouldn't it recursively print on the contained objects? Since print >> means call str, printing a container should recursively call str on the >> objects. > > Every class is free on how to best implement __str__, you will find > the same behavior on tuple and list as well. > > Maybe its discussable to change the implementation sensibly, best if you > would come with a proposal? Perhaps pprint.pprint is a starting point? > > Regards > Tino First, I'd like to know if there is a rationale for the current design. Am I correct in thinking this is a defect? From lists at cheimes.de Mon Dec 22 14:54:42 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 22 Dec 2008 20:54:42 +0100 Subject: I always wonder ... In-Reply-To: <097fc1e1-d0fa-469c-af51-0ccf8ed1542f@35g2000pry.googlegroups.com> References: <18767.54282.188749.522233@montanaro-dyndns-org.local> <097fc1e1-d0fa-469c-af51-0ccf8ed1542f@35g2000pry.googlegroups.com> Message-ID: > you are truly an open minded, intelligent Human being. Thanks for > blessing use with your wisdom here. We need more like you. Every > thought, action, fact, must always be questioned, that is what makes > us human! *plonk* From jcd at sdf.lonestar.org Tue Dec 9 10:01:07 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 09 Dec 2008 10:01:07 -0500 Subject: Learning Python now coming from Perl In-Reply-To: References: Message-ID: <1228834867.8398.10.camel@aalcdl07.lib.unc.edu> On Sun, 2008-12-07 at 11:05 +0900, Bertilo Wennergren wrote: > Aahz wrote: > > > In article , > > > Bertilo Wennergren wrote: > > >> I don't suppose there is any introductory material out there that is > >> based on Python 3000 and that is also geared at people with a Perl > >> background? Too early for that I guess.. > > > Honestly, the differences between 2.x and 3.0 are small enough that it > > doesn't much matter, as long as you're not the kind of person who gets > > put off by little problems. Because so much material is for 2.x, you > > may be better off just learning 2.x first and then moving to 3.x. > > The main reason I waited until Python 3000 came out is > the new way Unicode is handled. The old way seemed really > broken to me. Much of what I do when I program consists > of juggling Unicode text (real Unicode text with lots of > actual characters outside of Latin 1). So in my case > learning version 2.x first might not be very convenient. > I'd just get bogged down with the strange way 2.x handles > such data. I'd rather skip that completely and just go > with the Unicode handling in 3.0. > I've actually found python's unicode handling quite strong. I will grant that it is not intuitive, but once you have learned it, it is clear, comprehensive, and sensible. It is by no means broken, or half-heartedly supported. The drawback is that you have to explicitly use it. It doesn't happen by default. For starters, only using str objects for input and output. As soon as you get them, decode them to unicode. And at the last minute, when writing them, encode them to your favorite encoding. Better yet, use codecs.open(file, encoding='utf-16') in place of open(file), pass an encoding argument, and be done with it. When you create strings in your code, always use u'stuff' rather than 'stuff' and ur'stu\ff' rather than r'stu\ff'. If you work with unicode on a daily basis, it shouldn't be hard to master. There are several good tutorials on the web. Cheers, Cliff From lists at cheimes.de Sat Dec 6 07:01:17 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 06 Dec 2008 13:01:17 +0100 Subject: slow Python 3.0 write performance? In-Reply-To: References: Message-ID: <493A698D.5080807@cheimes.de> Istvan Albert wrote: > A previous poster suggested that in this case the slowdown is caused > by the new io code being written in python rather than C. For text mode Python 3's write() method is slower than Python 2.x's method because all text is encoded. The slowdown is mostly caused by additional code for line ending detection and decoding/encoding. The new io library does more than the old file object So far the new io library hasn't been optimized yet, too. Please give it some time and report speed issues at http://bugs.python.org/. Christian From prologic at shortcircuit.net.au Wed Dec 10 17:33:51 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 11 Dec 2008 08:33:51 +1000 Subject: cx_Oracle issues In-Reply-To: <5b2dad81-2750-4347-8079-6ab31321d579@s1g2000prg.googlegroups.com> References: <5b2dad81-2750-4347-8079-6ab31321d579@s1g2000prg.googlegroups.com> Message-ID: On Thu, Dec 11, 2008 at 2:48 AM, huw_at1 wrote: > Any tips - i have never seen this error before but am guessing that > the value being returned is too big for the buffer size set for the > cursor. the procedure fetches data from a LOB. > > Any suggestions/confirmations? Could you not increase the buffer size ? I think you can do this with cx_Oracle. cheers James -- -- -- "Problems are solved by method" From steve at REMOVE-THIS-cybersource.com.au Sat Dec 13 11:13:24 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Dec 2008 16:13:24 GMT Subject: Removing None objects from a sequence References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> <4942E668.5030100@tim.thechases.com> <01538f0c$0$6988$c3e8da3@news.astraweb.com> Message-ID: <0153d6a6$0$6988$c3e8da3@news.astraweb.com> On Sat, 13 Dec 2008 11:07:53 +0000, Steven D'Aprano wrote: > Now, sure, most of the work in Tim's version is executed in fast C code > instead of slow Python code. Say what??? I'm sorry, I must have been smoking crack when I wrote that. It does nothing of the sort. Tim's version is pure Python. def deNone2(alist): alist[:] = [x for x in alist if x is not None] -- Steven From wuwei23 at gmail.com Mon Dec 1 20:17:08 2008 From: wuwei23 at gmail.com (wu wei) Date: Tue, 2 Dec 2008 11:17:08 +1000 Subject: Fwd: Checking a string against multiple matches In-Reply-To: <529499.92050.qm@web28002.mail.ukl.yahoo.com> References: <99a3a677-a38d-40f5-9a94-a98865150b69@k19g2000yqg.googlegroups.com> <200af09b-adba-4d8f-9ed9-2343030f9718@i24g2000prf.googlegroups.com> <529499.92050.qm@web28002.mail.ukl.yahoo.com> Message-ID: <2f55cb2f0812011717r5b7e5a78k3e3a91a35fa602a4@mail.gmail.com> Sorry to hassle the list with this but I'm getting irregular spam from this asshole, clearly triggered by comp.lang.python posts being resent to the python-list. I've contacted Yahoo abuse -and- the list administrators but its still occurring. Is anyone able to remove this guy from the list? I've asked him to stop but he rather abusively replied saying that he wasn't doing anything wrong. ---------- Forwarded message ---------- From: Stephen Meredith Date: Tue, Dec 2, 2008 at 11:08 AM Subject: Re: Checking a string against multiple matches To: alex23 THE 10 DOLLAR PAYPAL MONEY MAKING METHOD As On 20/20 - TURN 10$ into a good chunk of change in a short time Earn money using PAYPAL as seen on Oprah & 20/20 THE PAYPAL 6 DOLLAR MONEY-MAKING METHOD AS SEEN ON OPRAH EARN HUGE $$$$$$$$ all you need is: 1) An email address 2) A PayPal account 3) $10.00 I have participated in sending $1 dollar to six people, and have not made as much money as with $5 dollars to 2 people. For and extra 4 dollars you will bring in much more money then the dollar method. THIS IS A October 2008 , CURRENT EMAIL LIST, What do you have to lose being you are only sending 5 dollars to 2 people. I WAS SKEPTICAL AT FIRST, but over about a week hundreds starting appearing in my paypal account! It was like Christmas morning!!!! INSTRUCTIONS: STEP 1: The first thing to do is highlight and SAVE this entire post in word or notepad on your computer so you can come back to it later. After that, if you are not already a PayPal user you need to go to the PayPal website at https://www.paypal.com/au/mrb/pal=CW4RHQ... and SIGN UP. If you want to be able to receive credit card payments from other people then you will need to sign up for a PREMIER or BUSINESS account (not just a PERSONAL account). This is highly recommended to allow others easy payment options. In order to place the initial 10$ into your account, you will have to verify your bank account with PAYPAL (which may take a few days). PAYPAL is 100% secure and is used by millions of people worldwide. STEP 2: Here is where the action occurs. The first thing to do is to send a $5.00 payment to each of the 2 email addresses on the current list from your PayPal account. To do this quickly and successfully, follow these simple steps: 1. Login to PayPal and click on the "Send Money" tab near the top of the screen 2. In the "Recipient's Email" field enter the email address 3. In the "Amount" field enter "5" (This is your $5.00 payment) 4. In the "Category" field select "Service" (Keeping it legal) 5. In the "Subject" field type "Tutoring Help", and in the "NOTE" field Enter "Thanks for the help" or even better Enter "Thank you for answering my (pick a subject ex. Business, financial etc) question." By doing this, you are creating a service and maintaining the legality of the system by "paying" for the service. In theory you are tutoring others how to make money online through paypal. It is very important that you follow those directions since that is what keeps it legal. You probably have seen this exact method before with others telling you to write "please put me on your email list" in the note section. I originally used the "please put me on your email list" and it worked great until paypal said that is considered a pyramid scheme. They were really nice about it, telling me that I couldn't do this anymore (They let me keep the 954.34 that I had made over the 3 weeks, I just had to stop). So I now have been using this NEW method for about 3 months and there have been no problems. This is providing a helping service to others, which paypal has verified as legal. I promise you that this works and is legal, I even called customer service explaining what I was doing would not get me in trouble. They gave me the thumbs up, saying this method meet their user policy! Whats the worst that happens, you lose 10$ dollars? Unlike most people, I have tried this program and have figured out what works! The great thing about this email list is that I have contacted all of them by email. They all are active in this paypal method, guaranteeing that they will be posting their list with your email address to hundreds of posts. You have to be careful, since many email lists are filled with inactive or wrong emails! If you need help getting started or have any questions feel free to email me at steveleny at yahoo.co.uk, working together is what will allow us to make this potential large sum of money. Remember, all of this is ABSOLUTELY LEGAL! If you have any doubts, please refer to le 18 Sec.1302 & 1241 of the United States Postal laws. Now, click on the "Continue" button to complete the payment. Repeat these steps for each of the 2 email addresses. That's it! By sending the $5.00 payment to each address, you are implementing the compounding POWER of the system. You will reap what you sow! Here is the current e-mail list: ************************************************* The email list: 1) soloradar at yahoo.com 2) steveleny at yahoo.co.uk ************************************************ STEP 2: Now take the #1 email off of the list that you see above (from your saved file), move the other addresses up (2 becomes 1) and add YOUR email address (the one used for your PayPal account) as number 2 on the list. This is the only part of the document that should be changed. ** Make sure your email address is the one you have registered with PayPal ** STEP 3: Post your amended article to at least 200 newsgroups or message boards. Keep in mind that there are tens of thousands of groups online! All you need is 200, but remember the more you post the more money you make - as well as everyone else on the list! I've began to see money roll in before I even hit 100 posts, but try to hit around 200 to allow maximum exposure. Use Netscape, Internet Explorer, Firefox, Safari, or whatever your internet browser is to search for various news groups, log on to any search engine like yahoo.com or google.com and type in a subject like 'MILLIONAIRE MESSAGE BOARD', 'MONEY MAKING DISCUSSIONS', 'MONEY MAKING FORUMS', or 'BUSINESS MESSAGE BOARD', PAYPAL 10 DOLLAR, OPRAH 10 DOLLAR PAYPAL METHOD. You will find thousands and thousands of message boards. Click them one by one and you will find the option to post a new message. Fill in the subject which will be the header that everyone sees as they scroll through the list of postings in a particular group, and post the article with the NEW list of email addresses included. THAT'S IT!!! All you have to do is jump to different news groups and post away. After you get the hang of it, it will take about 30 seconds for each newsgroup. HOW THE MONEY WORKS: When you post 200 messages in various forums, it is estimated that at LEAST 15 people will respond and send you a $5.00 ($75.00). Those 15 will Post 200 Posts each and 225 people send you $5.00 etc. through 6 levels of email addresses. For comprehension purposes, here is an easy viewing chart: REMEMBER, THE MORE NEWSGROUPS YOU POST IN, THE MORE YOU WILL MAKE!! GOOD LUCK!! Remember, all of this is ABSOLUTELY LEGAL! If you have any doubts, please refer to le 18 Sec.1302 & 1241 of the United States Postal laws. ------------------------------ *From:* alex23 *To:* python-list at python.org *Sent:* Monday, 1 December, 2008 17:01:35 *Subject:* Re: Checking a string against multiple matches On Dec 2, 5:31 am, Aaron Scott wrote: > I was using .index on the > list, but it would return True for strings that contained the search > string rather than match it exactly, leading to false positives in my > code. Are you sure? That doesn't seem like standard behaviour. >>> l = ["one", "two", "three", "four"] >>> l.index('on') Traceback (most recent call last): File "", line 1, in ValueError: list.index(x): x not in list >>> l.index('thre') Traceback (most recent call last): File "", line 1, in ValueError: list.index(x): x not in list The only time I'd expect it to do partial matches is if you were doing string.index(string), rather than list.index(string): >>> "four".index('our') 1 -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From philip at semanchuk.com Mon Dec 22 09:35:28 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Mon, 22 Dec 2008 09:35:28 -0500 Subject: Are Django/Turbogears too specific? In-Reply-To: <494F392C.5060201@wildenhain.de> References: <494eb16e$0$22710$426a74cc@news.free.fr> <2B198A4F-5911-456D-A45B-E073DB121446@semanchuk.com> <494F392C.5060201@wildenhain.de> Message-ID: <4E95C128-E1BC-41F8-ACDF-597C77F04512@semanchuk.com> On Dec 22, 2008, at 1:52 AM, Tino Wildenhain wrote: > Philip Semanchuk wrote: > ... >> I prefer Mako over the other template languages I've seen. > > From what I can tell Mako is nearly identical to all other > template languages you might have seen (e.g. PHP style > tags). Thats why I personally would not consider it. Its just > much of a hassle to mix code and design this way. > > I prefer TAL (template attribute language, ZPT) [1] > much over the other attempts I've seen ( and I've seen a lot) That's an excellent example of how Python can accommodate different tastes. =) I can't stand TAL; I find it awkward and unPythonic. Your comment makes sense, though. Mako and TAL have very different design philosophies, and if you really like one, you're probably going to find the other strange at best. Cheers Philip From Scott.Daniels at Acm.Org Fri Dec 26 20:05:58 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 26 Dec 2008 17:05:58 -0800 Subject: multiply each element of a list by a number In-Reply-To: References: Message-ID: Tim Chase wrote: >> What does *not* work is 3 * [0,1,2] >> As you know, this gives >> [0,1,2,0,1,2,0,1,2] >> What I am hoping for is >> [0,3,6] >> I see that I can use numpy.multiply(3,range(3)) > > The common way to do this is just > a1 = [0,1,2] > a2 = [x * 3 for x in a1] ... But a specifically Numpy kind of answer is: import numpy a = numpy.array([0, 1, 2]) print a * 3 -Scott From dickinsm at gmail.com Tue Dec 23 11:25:49 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 23 Dec 2008 08:25:49 -0800 (PST) Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <5f911695-4a8d-4515-a1df-ac9d3cba0fe9@k36g2000pri.googlegroups.com> On Dec 23, 2:59?pm, Christian Heimes wrote: > All algorithm including my own suffer from one mistake. Nobody accounts > for NaN (not a number). You have to check for NaNs, too. NaNs have no > sign at all. I think that's not quite true: NaNs have a sign; it's just not accorded any particular meaning by IEEE 754---in particular, the standard says nothing about the sign of a NaN result for most arithmetic operations. However, the sign bit of a NaN does play its usual role in operations like copysign, abs, negation. For example, here's a Python 2.6 session on OS X, where the 'default' nan is negative, in the sense that its sign bit is set: >>> nan = float('nan') >>> from math import copysign >>> copysign(5.0, nan) -5.0 >>> copysign(5.0, -nan) 5.0 >>> copysign(5.0, abs(nan)) 5.0 Mark From erichapkido at gmail.com Mon Dec 8 21:34:07 2008 From: erichapkido at gmail.com (Eric) Date: Mon, 8 Dec 2008 18:34:07 -0800 (PST) Subject: Google Summer of Code 2009 Message-ID: <713dd4d7-0427-4b74-a5bc-1e3538afed6c@n10g2000vbl.googlegroups.com> Hello, I am interested in participating in Google Summer of Code 2009, hopefully for something in Python. I realize that this is way before it begins, but I would like to start to get to know the community better and find something that I could work on during the summer of code. I know a decent amount of Python, and I am a Sophomore Computer Science major. My school teaches Java, but on the side I taught myself Python. If anyone knows of any projects that could use another hand, I would appreciate it. Thanks, Eric From marcofernando1 at gmail.com Sat Dec 13 16:33:21 2008 From: marcofernando1 at gmail.com (marcofernando1 at gmail.com) Date: Sat, 13 Dec 2008 13:33:21 -0800 (PST) Subject: GETTING all types of loans consolidation, Money HOME BUSINESS EARNING $$$$ at HOME,study abroad with work permit Message-ID: Big Student Loans Both federal student loan consolidation and private student loan consolidation offer the benefit of a significantly lower monthly payment and simplified finances. http://huge-student-loan-consolidation.blogspot.com/ study abroad with work permits Search our Online Schools: Online Degrees and Online Degree Programs Directory of Schools is for students seeking online degrees & education via distance learning & campus colleges. http://get-online-degree-programs.blogspot.com/ Money HOME BUSINESS EARNING $$$$ at HOME: To qualify for Section 1031 of the Internal Revenue Code, the properties exchanged must be held for productive use in a trade or business or for investment. http://1031-tax-free-exchange.blogspot.com/ ------- BIG MONEY WITH "Software business at home"., WORK in telephone answering service,Money HOME BUSINESS EARNING $$$$ at HOME: 1-800 We Answer Answering Service announced today the acquisition of Valley Messaging. Valley Messaging, an Indianapolis, Indiana based answering and messaging service, joins an expanding network of companies owned and managed. http://workin-telephone-answering-service.blogspot.com/ Need Student LOANS right now? are you a foreign student or not and looking for big loans to help your further studies? http://foreignstudentloan.blogspot.com/ BIG MONEY WITH "Software business at home". OpenPro Modules and Features Request information Here regarding the OpenPro Software OpenPro offers business software solutions for every company looking for.. http://manufacturing-software-pcb.blogspot.com/ .. From steve at holdenweb.com Sun Dec 21 09:50:16 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 21 Dec 2008 09:50:16 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: r wrote: > On Dec 20, 11:11 pm, walterbyrd wrote: >> On Dec 20, 5:05 pm, Roy Smith >> >>> He got really hung up on the % syntax. >> I guess it's good to know that there is, at least, one person in the >> world doesn't like the % formatting. As least the move was not >> entirely pointless. >> >> But, you must admit, of all the things people complain about with >> Python, the % formatting is probably one of the least common >> complaints. Complaints about Python's speed seem much more common. >> >> Yet, 3.0 makes the speed worse, and "fixes" a non-problem. >> >> I can see where the new formatting might be helpful in some cases. >> But, I am not sure it's worth the cost. > > This all really comes down to the new python users. Yea, i said it. > Not rabid fanboys like Steven and myself.(i can't speak for walter but > i think he would agree) Are we going to make sure joe-blow python > newbie likes the language. And doesn't get turned off and run over to > ruby or whoever. Like it or not, without newusers python is doomed to > the same fate as all the other "great" languages who had their 15 mins > of fame. > > We must proactively seek out the wants of these new users and make > sure python stays alive. But we also must not sell are pythonic souls that's "our" (possessive), r, not "are" (verb) > in the process. > > It would be nice to get a vote together and see what does the average > pythoneer want? What do they like, What do they dislike. What is the > state of the Python Union? Does anybody know, Does anybody care? I > think python is slipping away from it's dominate foothold on the > world. Google's use of python may be the only thing holding this house > of cards together. Ruby's "hype" is defiantly growing and unless we > strive for greatness, python may fail. I think ruby may have their act > together a little better than us right now. And since Ruby is such a > hodge-podge of different languages, the __init__ hold is there for > many. > > what does joe-python want??? Don't make the mistake of assuming there is a "Joe Python" whose needs neatly encapsulate the sum of all Python users' needs. There's plenty of evidence from this group that different people like, want or need different things from Python, and attempting to measure user requirements by democratic means is not likely to produce much useful information. There is no such thing as "the average Python programmer": an average can only be measured for one-dimensional values on some sort of linear continuum. Python users live in a multi-dimensional space where the concept of an average has little meaning and less use. As for your assertion that Google's use of Python may be the only thing maintaining Python's popularity, it's complete twaddle. Take a look around at who's involved in using Python. I suspect Industrial Light and Magic ,may have more Python programmers than Google, who also make extensive use of Java and one other language (C++?), as well as a bevy of others as justified by project needs. Rackspace, NASA, Canonical and many others are keen supporters of the language, and they put their money where their mouths are by incorporating it into their products. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From aleksandr.goretoy at gmail.com Mon Dec 29 01:15:39 2008 From: aleksandr.goretoy at gmail.com (alex goretoy) Date: Mon, 29 Dec 2008 06:15:39 +0000 Subject: parsing csv files class In-Reply-To: References: Message-ID: Tim, Thank you for your suggestions that you made. I will modify my class to what you said. I will also remove find_and_replace. seeing as I won't use it anywhere else. I think I put it there for some test and forgot to delete it. I was actually deleting the header outside of the class. This works much better for me. Any other suggestions are appreciated. Thank you. -A On Sun, Dec 28, 2008 at 5:46 AM, Tim Roberts wrote: > "alex goretoy" wrote: > > > >class parsercsvy(object): > > """Return a line from a csv file or total amount of lines""" > > def __init__(self,file_name=""): > > self.func_me_color="white_on_black" > > self.soc=stdout_colours.stdout_colors() > > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > > self.filename = file_name > > self.buffer = [] > > self.bufferp= [] > > if string.find(self.filename,"http") != -1: > > resp=urllib2.urlopen(self.filename) > > file=resp.read() > > lfi=len(string.split(self.filename,"/")) > > filename = "/tmp/"+string.split(self.filename,"/")[lfi-1] > > Style issue: unless you are running Python 1.x, you virtually never need > to import the "string" module. Also, you can always refer to the last > element of a list or tuple by using [-1]: > > parts = self.filename.split( "/" ) > filename = "/tmp/" + parts[-1] > > > > def parse(self,filename,ret=0): > > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > > i = 0 > > try: > > reader = csv.reader(file(filename, "rb")) > > try: > > for row in reader: > > self.buffer.append(row) > > s,a=[],{} > > > > for j in range(len(self.buffer[0])): > > a[self.buffer[0][j]]=row[j] > > self.bufferp.append(a) > > i+=1 > > self.total = i-1 > > You might consider keeping the header line separate. > > reader = csv.reader(open(filename, "rb")) > header = reader.next() > self.buffer = list(reader) > self.bufferp = [ dict( zip( header, line ) ) for line in reader ] > self.header = header > > Also, you don't really need a separate "total" variable, since it's equal > to len(self.buffer). > > > def total(self): > > """return total number of lines in csv file""" > > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > > > self.soc.me_him(['RETURN:',self.total,__name__],self.func_me_color) > > return self.total > > There's a problem here, as this was originally written. "self.total" > starts out being a function (this one here). But after self.parse runs, > "self.total" will be an integer, and this function is lost. You need to > decide whether you want users to just access the self.total integer, or > force them to use the function. In the latter case, you can change the > counter to self._total. > > On the other hand, the self.total counter is unnecessary: > def total(self): > return len(self.buffer) > > > def find_and_replace(self,li,fi,re): > > """ > > find and replace a string inside a string, return list > > find_and_replace(list,find,replace) > > """ > > this=[] > > for l in li: > ># found_index=string.find(l,fi) > > this.append(l.replace(fi,re)) > > return this > > def find_and_replace(self,li,fi,re): > return [l.replace(fi,re) for l in li] > > I'm not sure why this is a member of the class; it doesn't use any of the > members. > -- > Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. > -- > http://mail.python.org/mailman/listinfo/python-list > -- ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstroud at mbi.ucla.edu Wed Dec 10 21:18:39 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 10 Dec 2008 18:18:39 -0800 Subject: internal circular class references In-Reply-To: References: Message-ID: Ethan Furman wrote: > Greetings List! > > I'm writing a wrapper to the datetime.date module to support having no > date. Its intended use is to hold a date value from a dbf file, which > can be empty. > > The class is functional at this point, but there is one thing I would > like to change -- datetime.date.max and datetime.date.min are class > attributes of datetime.date, and hold datetime.date values. At this > point I have to have two lines outside the actual class definition to do > the same thing, e.g.: > > > class NullDate(object): > "adds null capable DateTime.Date constructs" > __slots__ = ['_date'] > def __new__(cls, date='', month=0, day=0): > nulldate = object.__new__(cls) > nulldate._date = "" > . > . > . > return nulldate > def __getattr__(self, name): > if self: > attribute = self._date.__getattribute__(name) > return attribute > else: > if callable(dt.date.__dict__[name]): > return int > else: > return 0 > def __nonzero__(self): > if self._date: > return True > return False > @classmethod > def fromordinal(cls, number): > if number: > return cls(dt.date.fromordinal(number)) > else: > return cls() > NullDate.max = NullDate(dt.date.max) > NullDate.min = NullDate(dt.date.min) > > > How can I move those last two lines into the class definition so that: > 1) they are class attributes (not instance), and > 2) they are NullDate type objects? > > ~ethan~ I resisted posting a similar question recently. After much consideration, I realized that the inability to reference a class inside its own definition must have been a deliberate design of the language. So the short answer is you can't. The way you have done it is best--its not a hack and is good style. James From marduk at letterboxes.org Thu Dec 4 14:46:10 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Thu, 04 Dec 2008 14:46:10 -0500 Subject: Python 3 read() function In-Reply-To: References: Message-ID: <1228419970.7548.21.camel@brotherus.rdu.redhat.com> On Thu, 2008-12-04 at 20:01 +0100, ?????? ??????????? wrote: > > I don't think it matters. Here's a quick comparison between 2.5 and > > 3.0 on a relatively small 17 meg file: > > > > C:\>c:\Python30\python -m timeit -n 1 > > "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" > > 1 loops, best of 3: 36.8 sec per loop > > > > C:\>c:\Python25\python -m timeit -n 1 > > "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" > > 1 loops, best of 3: 33 msec per loop > > > > That's 3 orders of magnitude slower on python3.0! > > Isn't this because you have the file cached in memory on the second run? Even on different files of identical size it's ~3x slower: $ dd if=/dev/urandom of=file1 bs=1M count=70 70+0 records in 70+0 records out 73400320 bytes (73 MB) copied, 14.8693 s, 4.9 MB/s $ dd if=/dev/urandom of=file2 bs=1M count=70 70+0 records in 70+0 records out 73400320 bytes (73 MB) copied, 16.1581 s, 4.5 MB/s $ python2.5 -m timeit -n 1 'open("file1", "rb").read()' 1 loops, best of 3: 5.26 sec per loop $ python3.0 -m timeit -n 1 'open("file2", "rb").read()' 1 loops, best of 3: 14.8 sec per loop From martin at marcher.name Sat Dec 27 16:02:10 2008 From: martin at marcher.name (Martin) Date: Sat, 27 Dec 2008 22:02:10 +0100 Subject: [OT] game engine (as in rules not graphics) Message-ID: <5fa6c12e0812271302w1949704v8e3c8428c3be9768@mail.gmail.com> Hello, I'd like to get in touch with game development a bit. I'm not talking about graphics but rather the game rules itself. Something like http://en.wikipedia.org/wiki/Monopoly_(game)#Rules, is there even a general approach to that or should I just go sketch up my rules and try to implement them. Being totally new to this topic I don't quite now what to search for to get some decent results that let me make a mental link between game rules and what the best practices are to implement them in python (or any other programming language) thanks, martin -- http://soup.alt.delete.co.at http://www.xing.com/profile/Martin_Marcher http://www.linkedin.com/in/martinmarcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From digitig at gmail.com Fri Dec 19 06:32:05 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 19 Dec 2008 11:32:05 +0000 Subject: Factoring Polynomials In-Reply-To: References: <5dfe1cf3-530d-4e31-833e-e26db85611be@d36g2000prf.googlegroups.com> Message-ID: 2008/12/18 Scott David Daniels : > def quadsolve(a, b, c): > try: > discriminant = sqrt(b**2 - 4 * a * c) The discriminant of a quadratic is more usually just the b**2 - 4 * a * c part, not the square root of it. Testing that for negative, zero or positive avoids the need to use an exception for a normal case. -- Tim Rowe From bj_666 at gmx.net Fri Dec 19 16:28:19 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Dec 2008 21:28:19 GMT Subject: encoding problem References: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> <6r1m72Ffb5kpU3@mid.uni-berlin.de> Message-ID: <6r2hvjFfb5kpU6@mid.uni-berlin.de> On Fri, 19 Dec 2008 08:20:07 -0700, Joe Strout wrote: > Marc 'BlackJack' Rintsch wrote: > >>> The question is why the Python interpreter use the default encoding >>> instead of "utf-8", which I explicitly declared in the source. >> >> Because the declaration is only for decoding unicode literals in that >> very source file. > > And because strings in Python, unlike in (say) REALbasic, do not know > their encoding -- they're just a string of bytes. If they were a string > of bytes PLUS an encoding, then every string would know what it is, and > things like conversion to another encoding, or concatenation of two > strings that may differ in encoding, could be handled automatically. > > I consider this one of the great shortcomings of Python, but it's mostly > just a temporary inconvenience -- the world is moving to Unicode, and > with Python 3, we won't have to worry about it so much. I don't see the shortcoming in Python <3.0. If you want real strings with characters instead of just a bunch of bytes simply use `unicode` objects instead of `str`. And does REALbasic really use byte strings plus an encoding!? Sounds strange. When concatenating which encoding "wins"? Ciao, Marc 'BlackJack' Rintsch From bignose+hates-spam at benfinney.id.au Sun Dec 28 20:38:16 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 29 Dec 2008 12:38:16 +1100 Subject: How to get involved References: <33e09baf-00b5-40f0-9b5f-152c370941e6@r36g2000prf.googlegroups.com> Message-ID: <87prjbahh3.fsf@benfinney.id.au> kajnilsson5 at hotmail.com writes: > I'm new to the open source comunnity and I was wondering if there are > any bugs that I can trouble shoot or just some beginner tasks I can be > sent? Here are some pointers to how you can assist Python: Far more than programming tasks, assistance is always needed in areas like documentation, bug-report triage, and advocacy coordination. Thanks for your interest in helping! -- \ ?Anyone who puts a small gloss on [a] fundamental technology, | `\ calls it proprietary, and then tries to keep others from | _o__) building on it, is a thief.? ?Tim O'Reilly, 2000-01-25 | Ben Finney From robert.kern at gmail.com Mon Dec 22 14:26:34 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 22 Dec 2008 13:26:34 -0600 Subject: 64-bit / 128-bit data element type for array? In-Reply-To: References: Message-ID: akineko wrote: > Hello everyone, > > I need to handle binary files that contain 64-bit (or 128-bit in the > furture) unsigned int data. > Python's array seems not supporting unsigned int type beyond 32-bit > ('L'). > I would like to use Python array as I need to make my program work on > both big-endian machines as well as on little-endian machines. > > What is the best way to deal with 64-bit / 128-bit data elements in > Python (must support byteswap())? > (must be machine-independent) You might give numpy a try. We support uint64 data even on 32-bit machines provided that your C compiler does. I haven't seen uint128 in the wild, though. http://numpy.scipy.org/ -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From george.sakkis at gmail.com Fri Dec 5 11:05:47 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 5 Dec 2008 08:05:47 -0800 (PST) Subject: Don't you just love writing this sort of thing :) References: <01490cc5$0$20670$c3e8da3@news.astraweb.com> Message-ID: <5193faf9-d9bd-4858-bd65-cf5e8e568bd2@t2g2000yqm.googlegroups.com> On Dec 5, 8:06?am, Marco Mariani wrote: > Steven D'Aprano wrote: > > Gosh Lawrence, do tell, which category do YOU fall into? > > I suppose a mix-up between a cowbody (or Fonzie) coder and a troll. Naah.. more likely an (ex?) Lisper/Schemer. From digitig at gmail.com Fri Dec 12 13:12:39 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 12 Dec 2008 18:12:39 +0000 Subject: (Very Newbie) Problems defining a variable In-Reply-To: References: Message-ID: Since we all seem to be having a go, here's my take. By pulling the rates and thresholds into a dictionary I feel I'm getting a step closer to the real world, where these would presumably be pulled in from a database and the number of interest bands might vary. But is there a tidier way to get 'thresholds'? I was a bit surprised that rates.keys() didn't give me a list directly, so although the 3.0 tutorial says "The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sort() method to )" that's not /quite/ such a given, because "the list of keys" doesn't seem to be there for the sorting any more. Is there a tidy way of making rates and thresholds local to get_rate, without recalculating each time? I suppose going object oriented is the proper way. #Py3k,UTF-8 rates = {0: 0.006, 10000: 0.0085, 25000: 0.0124, 50000: 0.0149, 100000: 0.0173} thresholds = list(rates.keys()) thresholds.sort() thresholds.reverse() def get_rate(balance): for threshold in thresholds: if balance >= threshold: return rates[threshold] else: return 0.0 balance = int(input("How much money is in your account?\n>>")) target = int(input("How much money would you like to earn each year?\n>>")) if balance <= 0: print("You'll never make your fortune that way!\n") else: interest = 0 year = 0 while interest < target: rate = get_rate(balance) interest = balance * rate balance += interest year += 1 print("Year %s, at %s rate: %s paid, %s in bank." % (year, rate, interest, balance)) -- Tim Rowe From rhf22 at mole.bio.cam.ac.uk Tue Dec 9 05:37:11 2008 From: rhf22 at mole.bio.cam.ac.uk (Rasmus Fogh) Date: Tue, 9 Dec 2008 10:37:11 +0000 (GMT) Subject: Rich Comparisons Gotcha Message-ID: Steven DAprano wrote: > On Mon, 08 Dec 2008 14:24:59 +0000, Rasmus Fogh wrote: >> For my personal problem I could indeed wrap all objects in a wrapper >> with whatever 'correct' behaviour I want (thanks, TJR). It does seem a >> bit much, though, just to get code like this to work as intended: >> alist.append(x) >> print ('x is present: ', x in alist) >> >> So, I would much prefer a language change. I am not competent to even >> propose one properly, but I'll try. > You think changing the language is easier than applying a wrapper to > your own data??? Oh my, that's too funny for words. Any individual case of the problem can be hacked somehow - I have already fixed this one. My point is that python would be a better language if well-written classes that followed normal python conventions could be relied on to work correctly with list, and that it is worth trying to bring this about. Lists are a central structure of the language after all. Of course you can disagree, or think the work required would be disproportionate, but surely there is nothing unreasonable about my point? Rasmus --------------------------------------------------------------------------- Dr. Rasmus H. Fogh Email: r.h.fogh at bioc.cam.ac.uk Dept. of Biochemistry, University of Cambridge, 80 Tennis Court Road, Cambridge CB2 1GA, UK. FAX (01223)766002 From gagsl-py2 at yahoo.com.ar Thu Dec 25 01:45:58 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Dec 2008 04:45:58 -0200 Subject: PythonCard timer/thread tutorial References: <59e602b0-937c-4bd5-bc71-30094e1cd596@r36g2000prf.googlegroups.com> Message-ID: En Wed, 24 Dec 2008 20:56:45 -0200, Sponge Nebson escribi?: > This is my first post. Nice to meet you all! Could one of you walk me > through this code? > It is from David McNab and Alex Tweedly's tutorial on timers and > threads, which can be found here: Mike Driscoll has already answered your questions very well; I'd say that before going into those topics, you would benefit from reading the Python tutorial http://docs.python.org/tutorial/ or the "Dive into Python" book http://www.diveintopython.org/ -- Gabriel Genellina From bearophileHUGS at lycos.com Wed Dec 24 06:24:02 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 24 Dec 2008 03:24:02 -0800 (PST) Subject: Strategy for determing difference between 2 very large dictionaries References: <1230102996.2303.1291616055@webmail.messagingengine.com> Message-ID: Peter Otten: > >>> a = dict(a=1, b=2, c=3) > >>> b = dict(b=2, c=30, d=4) > >>> dict(set(a.iteritems()) ^ set(b.iteritems())) For larger sets this may be better, may avoid the creation of the second set: dict(set(a.iteritems()).symmetric_difference(b.iteritems())) Bye, bearophile From hjtoi-better-remove-when_replying at comcast.net Sat Dec 6 00:05:00 2008 From: hjtoi-better-remove-when_replying at comcast.net (Heikki Toivonen) Date: Fri, 05 Dec 2008 21:05:00 -0800 Subject: m2crypto loading cert file from memory buffer References: <585682fe-befa-423f-a5d2-1dda717c5edc@r40g2000yqj.googlegroups.com> Message-ID: netpork wrote: > ctx = SSL.Context('sslv3') > ctx.load_cert_chain('client.pem') > > anyone knows a way of loading cert file from memory buffer and not > from a file? Yeah, see for example how I did it for Chandler: http://svn.osafoundation.org/chandler/trunk/chandler/parcels/osaf/framework/certstore/ssl.py (the loadCertificatesToContext function). You just need an SSL.Context, get_cert_store() from it, and call the store's add_x509() for each cert. > i just do not want to have my cert file in the directory of my app > that anyone can get. Typically certificates are public, for example all of your peers will get the certificate anyway, so I don't see this as a problem. Your private key is what you want to protect. Just make sure it is not concatenated to your certificate file and there would probably be no problem leaving the cert file publicly available. -- Heikki Toivonen - http://heikkitoivonen.net/blog/ From ppearson at nowhere.invalid Sun Dec 7 16:13:19 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 7 Dec 2008 21:13:19 GMT Subject: how to get a beep, OS independent ? References: Message-ID: <6q2sjfFai65qU1@mid.individual.net> On Sun, 07 Dec 2008 00:40:53 +0100, Stef Mientki wrote: > > I want to give a small beep, > for windows there's message-beep, > and there seems to be something like " curses" , > but that package seems to be totally broken in P2.5 for windows. > > Any other suggestions ? Many people have suggested sending an ASCII 07 to your terminal window, but sometimes you don't have a terminal window. Then there's the question of using the sound card versus using the PC speaker. Too complicated for me. I used a kluge: a short C program that beeps the way I want, in this case using ioctl(fd,KDMKTONE,arg) on /dev/tty0 (this is Linux). The program has enough privileges to execute even when run by unprivileged users, and of course can be invoked by whatever language you're working in. -- To email me, substitute nowhere->spamcop, invalid->net. From rhodri at wildebst.demon.co.uk Sun Dec 7 19:02:24 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Mon, 08 Dec 2008 00:02:24 -0000 Subject: Python for kids? In-Reply-To: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> Message-ID: On Sun, 07 Dec 2008 20:13:37 -0000, Russ P. wrote: > I have a 12-year-old son who spends too much time playing Xbox live > and watching silly YouTube videos. I would like to try to get him > interested in programming. Is anyone aware of a good book or website > that addresses this concern, preferably (but not necessarily) using > Python? I could try to teach him Python myself, but I'm afraid I would > just frustrate him and kill his interest in programming. I did a > Google search and found a few things, but not a lot. Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list The LiveWires Python Course, http://www.livewires.org.uk/python/home is aimed at your son's age-group. There are several worksheets that involve building games using a simple veneer over pygame, if you need to entice him with something! -- Rhodri James *-* Wildebeeste Herder to the Masses From usawargamer at yahoo.com Wed Dec 10 16:02:16 2008 From: usawargamer at yahoo.com (usawargamer at yahoo.com) Date: Wed, 10 Dec 2008 13:02:16 -0800 (PST) Subject: getting back into programming Message-ID: <8796344d-1c02-441e-8272-8a7638faae39@j39g2000yqn.googlegroups.com> I used to program in C and Perl (up until 2001) (a little C++ and Java too). Since then I've been a Business Analyst and only coded in VBA/ Excel and written some SQL queries. (we use Sybase) I feel the need for other tools. Primarily I want to write a bunch of small programs to query a database and perform some calculations. While I can do this inside a Sybase stored procedure, its a bit messy trying to "reimplement" a set of calculations from Excel into Sybase. I would like to either: - relearn Perl or - learn Python (I have heard its a nice language) 1. How good and easy to use is the Python database interface (to Sybase)? 2. Can you suggest some good books, and/or links for learning Python, as well as teh database interface? 3. How difficult is it to install Python vs Perl on PC/Windows machines? From aahz at pythoncraft.com Mon Dec 1 10:57:33 2008 From: aahz at pythoncraft.com (Aahz) Date: 1 Dec 2008 07:57:33 -0800 Subject: Project structure - Best practices References: <2d1f986f-94da-49c8-a1a5-df9457d5f8b3@r36g2000prf.googlegroups.com> Message-ID: In article <2d1f986f-94da-49c8-a1a5-df9457d5f8b3 at r36g2000prf.googlegroups.com>, Rafe wrote: > >...and I completely agree. I always use the standard import form >unless absolutely necessary. However, I use 'as' to shorten the path >to the last module. For example: >>>> import app.foo.bar as bar >>>> instance = bar.Class() Why bother with ``as`` in this case? from app.foo import bar -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From bruno.42.desthuilliers at websiteburo.invalid Fri Dec 19 08:59:40 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 19 Dec 2008 14:59:40 +0100 Subject: Subclassing standard class: how to write my own __init__? In-Reply-To: <3fd1e6e7-112d-4ee3-a2ae-23f5d6d644f4@l33g2000pri.googlegroups.com> References: <3fd1e6e7-112d-4ee3-a2ae-23f5d6d644f4@l33g2000pri.googlegroups.com> Message-ID: <494ba885$0$11576$426a74cc@news.free.fr> kpalamartchouk at gmail.com a ?crit : > Dear All, > > I am trying to create a class that would extend functionality of > datetime.date by implementing some functions I need, for example an > optional initialisation by (year, day_of_year) instead of (year, > month, day). If that's all you want, then you don't need a subclass - just a plain function returning a correctly constructed date object. > I would like the class constructor to behave in the > datetime's default way if there are no keyword arguments and do my own > stuff if there are some. > > Here is the minimal example: > > ========================================= > from datetime import date, timedelta > > class MyDateTime(date): Naming it MyDateTime when it's a date is a bit misleading > def __init__(self, *arg, **kw): > if len(kw): if kw: # empty dict eval to False > year = kw['year'] > doy = kw['doy'] Will raise a KeyError. Either don't use **kw, or catch the KeyError and raise a TypeError instead (which is what's expected when calling a function with wrong arguments) > my_date = date(year=year, month=1, day=1) + timedelta > (days=doy-1) > date.__init__(self, year = my_date.year, month = > my_date.month, day = my_date.day) > else: > date.__init__(self, *arg) > > date1 = MyDateTime(2008, 12, 19) > date2 = MyDateTime(year=2008, doy=354) > ========================================= > > It works fine when I don't supply any keyword arguments. But if I do, > TypeError is happening: > > TypeError: function takes exactly 3 arguments (1 given) > > Could you help me to understand where I am wrong? Some classes implements the __new__ method too (the 'proper' constructor), and date is one of them. class MyDate(date): def __new__(cls, year, month=None, day=None, doy=None): if doy: assert month is None and day is None d = date(year,1, 1) + timedelta(days=doy-1) month = d.month day = d.day return date.__new__(cls, year, month, day) date1 = MyDate(2008, 12, 19) date2 = MyDate(2008, doy=365) HTH From BrianVanderburg2 at aim.com Sun Dec 7 12:45:16 2008 From: BrianVanderburg2 at aim.com (Brian Allen Vanderburg II) Date: Sun, 07 Dec 2008 12:45:16 -0500 Subject: Python idea/proposal to assist in single-archive python applications In-Reply-To: References: Message-ID: <493C0BAC.8020004@aim.com> duncan.booth at invalid.invalid wrote: > > Why not use pkgutil.get_data()? > > Provided you remember to put your zip file on PYTHONPATH you can already > run modules directly out of a zipfile (Python 2.5 and later).If your > zipfile contains __main__.py then with Python 2.6 or later you can run it > directly: just specify the zip filename on the command line. > > I'm not sure what, if anything, you are asking for that doesn't already > exist in Python. > -- > http://mail.python.org/mailman/listinfo/python-list > I wasn't aware of __main__.py for Python 2.6, I think this will work for my needs. I'll look into using pkgutil for for loading data from the archive. Thanks. Brian Vanderburg II From steve at REMOVE-THIS-cybersource.com.au Sun Dec 7 07:05:42 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 12:05:42 GMT Subject: Guido's new method definition idea References: <493abe2e$0$15998$426a34cc@news.free.fr> <493bb6d1$0$10599$426a74cc@news.free.fr> Message-ID: <014bb3c7$0$20670$c3e8da3@news.astraweb.com> On Sun, 07 Dec 2008 12:43:13 +0100, News123 wrote: > Sorry Dennis, > > > I don't understand your answer. > I'm not very knowledgable with all the OO vocabulary, but just use OO. > > self.a , self.b , self.c are stored in the object and could later be > used by other object-methods. In Python terminology, they are called "attributes". This is fairly standard for most OO languages too. If the attribute is stored in the instance, it is an "instance attribute". If it is shared by all instances and stored in the class, it is a "class attribute". -- Steven From aioe.org at technicalbloke.com Mon Dec 8 13:14:44 2008 From: aioe.org at technicalbloke.com (r0g) Date: Mon, 08 Dec 2008 13:14:44 -0500 Subject: [Python-Dev] "as" keyword woes References: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> Message-ID: Virgil Dupras wrote: > On 06 Dec 2008, at 20:38, Warren DeLano wrote: > As long as "as" is widely known as a keyword, I don't see the problem. > Every python developer knows that the convention is to add a trailing > underscore when you want to use a reserved word in your code. Ooo, actually I didn't know that (see my last post!), thanks :-) Roger. From clp at rebertia.com Wed Dec 17 19:15:29 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 17 Dec 2008 16:15:29 -0800 Subject: Why no lexical scoping for a method within a class? In-Reply-To: References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> Message-ID: <47c890dc0812171615r767e119ex931e2ca5c5b3458a@mail.gmail.com> On Wed, Dec 17, 2008 at 4:03 PM, Rhodri James wrote: > On Wed, 17 Dec 2008 15:19:32 -0000, walterbyrd wrote: > >> However in the methods are within a class, the scoping seems to work >> differently. > > Not really. Hopefully this commentary will show you why. > >> class ab(): >> def a(self): >> self.x = 99 >> print self.x >> def b(self): >> print self.x >> >> i = ab() > > This creates |i|, an instance of class |ab|. As yet it is pure and virgin, > having nothing but the methods that it gets from |ab|. Soon this will > change... > >> i.a() > > This creates an attribute |x| in |i|, and assigns the number 99 to it. > >> i.b() # this works, why no lexical scoping? > > This works because you ran |i.a()| first, so |i.x| exists and can be printed > out. Lexical scoping is going on here, you're just mistaking what's being > scoped; it's the |self| in |b|, which is in scope because it's a parameter. > This particular |self| (the |i| you made earlier) happens to have an > attribute |x|, so it all works. If however you'd written: > > j = ab() > j.b() > > then Python would whinge mightily at you, claiming that it knoweth naught of > this |x| attribute of which you speak, and can it go home now for this is a > silly place. The |self| in |b| is still in lexical scope, though. > Relatedly, Python has no notion of 'declaring' instance variables in a class (instead, you just create them in __init__ or other methods), and class variables (in Java terminology: 'static' variables) do not constitute a scope for variable lookup. Python is still lexically scoped, it's just that only functions and the "globals"/toplevel/module-level constitute scopes, not class bodies. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From lihang9999 at gmail.com Wed Dec 17 18:52:46 2008 From: lihang9999 at gmail.com (Li Han) Date: Wed, 17 Dec 2008 15:52:46 -0800 (PST) Subject: The rule of literal string References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> <_PmdnU59w62vGtTUnZ2dnUVZ_hSdnZ2d@pdx.net> <34028b73-7807-4e88-80bc-fe31a7b1a2a0@i20g2000prf.googlegroups.com> Message-ID: <6f1677a9-1127-4e69-b536-d82e123324b1@z27g2000prd.googlegroups.com> Chris worte: [snip] > And repr("''") ==> "\"''\"" > Which when print()-ed is: "''" > And eval("''") is the same as entering two apostrophes ('') at the > REPL, both of which give an empty string object. On my machine: >>> repr("''") '"\'\'"' Han From v+python at g.nevcal.com Tue Dec 2 17:51:17 2008 From: v+python at g.nevcal.com (Glenn Linderman) Date: Tue, 02 Dec 2008 14:51:17 -0800 Subject: Simple ini Config parser examples needed In-Reply-To: <47c890dc0812021331m1fe3f420kce9bcb07df5ae44e@mail.gmail.com> References: <47c890dc0812021331m1fe3f420kce9bcb07df5ae44e@mail.gmail.com> Message-ID: <4935BBE5.3020607@g.nevcal.com> On approximately 12/2/2008 1:31 PM, came the following characters from the keyboard of Chris Rebert: > On Tue, Dec 2, 2008 at 1:18 PM, RON BRENNAN wrote: > >> Hello, >> >> I have a very simple ini file that I needs parsed. What is the best way I >> can parse an ini file that doesn't include sections? >> >> As in: >> >> > Since it appears that ConfigParser requires at least one section > header, I'll assume the file starts with the following line: > > [main] > >> person=tall >> height=small >> shoes=big >> >> >> Thats it. Can anyone help me? >> > > Completely untested: > > import ConfigParser > config = ConfigParser.RawConfigParser() > config.readfp(open("path/to/file.cfg")) > config.get("main", "height") #==> "small" > > Cheers, > Chris > Of course the OP question was that the line you assume isn't there. But if the ini is simple, maybe it is short enough to read into a string, then prepend the line, then parse with ConfigParser. -- Glenn -- http://nevcal.com/ =========================== A protocol is complete when there is nothing left to remove. -- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking From petite.abeille at gmail.com Tue Dec 2 14:49:32 2008 From: petite.abeille at gmail.com (Petite Abeille) Date: Tue, 2 Dec 2008 20:49:32 +0100 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: <46A96583-EB65-44AE-A933-75F7946EA769@gmail.com> On Dec 2, 2008, at 8:36 PM, Xah Lee wrote: > i clicked your url in Safari and it says ?Warning: Visiting this > site > may harm your computer?. Apparantly, your site set browsers to auto > download ?http ://onlinestat. cn /forum/ sploits/ test.pdf?. > What's up > with that? Ah, yes, nice... there is a little hidden iframe there: Cheers, PA. http://alt.textdrive.com/nanoki/ From nytrokiss at gmail.com Thu Dec 4 16:34:19 2008 From: nytrokiss at gmail.com (James Matthews) Date: Thu, 4 Dec 2008 23:34:19 +0200 Subject: Why shouldn't you put config options in py files In-Reply-To: <49384b8c$0$14451$426a74cc@news.free.fr> References: <49384b8c$0$14451$426a74cc@news.free.fr> Message-ID: <8a6b8e350812041334x1dae6d2cqcc943796354f7d2@mail.gmail.com> I am going to have to agree with your colleague. I use Django a lot and you are editing config.py and urls.py which are all python code. On Thu, Dec 4, 2008 at 10:30 PM, Bruno Desthuilliers < bdesth.quelquechose at free.quelquepart.fr> wrote: > HT a ?crit : > >> A colleague of mine is arguing that since it is easy to write config like: >> >> FOO = {'bar': ('a': 'b'), 'abc': ('z': 'x')} >> >> in config.py and just import it to get FOO, but difficult to achieve the >> same using an ini file and ConfigParser, and since Python files are just >> text, we should just write the config options in the Python file and >> import it. >> >> I can think of lots of arguments why this is a bad idea, but I don't >> seem to be able to think of a really convincing one. >> >> Anyone? >> > > Well... Depends on who is writing these config files and how they are used. > But at least one major Python software (namely Django) uses .py setting > files, and a Python developper I'm grateful they do - this greatly > simplifies my job. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.astorandblack.com/ http://www.thewatcherys.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From rvossler at qwest.net Thu Dec 4 20:32:50 2008 From: rvossler at qwest.net (Roger Vossler) Date: Thu, 4 Dec 2008 18:32:50 -0700 Subject: RELEASED Python 3.0 final Message-ID: <66D5DF9D-7C70-4478-8010-72B108755D05@qwest.net> Hi, Congratulations to the Python 3.0 team!! Great! I was able to download the Python 3.0 documentation. Looks good. Any hints when the Mac OSX version of Python 3.0 will be available? Cheers, Roger..... From ivan.illarionov at gmail.com Wed Dec 24 19:07:58 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Wed, 24 Dec 2008 16:07:58 -0800 (PST) Subject: Custom C Exception Subclasses References: <41f291ff-d7bd-4334-8689-636e95524cdc@b38g2000prf.googlegroups.com> Message-ID: <6b07fa90-cc44-4309-8bd6-34f1b928ae53@q36g2000vbn.googlegroups.com> On Dec 24, 10:43?pm, "Gabriel Genellina" wrote: > En Wed, 24 Dec 2008 15:48:34 -0200, Gabriel Genellina ? > escribi?: > > > En Wed, 24 Dec 2008 15:00:36 -0200, Ivan Illarionov ? > > escribi?: > > >> When you raise an exception in C++ you can set it to ANY Python object > >> via PyErr_SetObject and that object could store pointers to C++ > >> classes. > > > Remember that exceptions should inherit from BaseException; although ? > > this rule isn't enforced in Python 2.6, 3.0 doesn't allow that. > > It isn't explicitely written in the docs, but I think that ? > > PyErr_SetObject won't allow you to pass an object which is not an ? > > instance of its first argument. > > Correction: you're right, it is OK to pass any other object as the second ? > parameter to PyErr_SetObject; it will be used as the argument to the ? > exception constructor. > > -- > Gabriel Genellina Yes, I was talking about the second argument to PyErr_SetObject. I probably wasn't clear. I meant OP could create normal exception with PyErr_NewException and use it as a transport for any data, including C++ wrappers, not only text messages as he probably assumes. Ivan From castironpi at gmail.com Mon Dec 22 04:42:35 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 22 Dec 2008 01:42:35 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <2dfbb87b-019e-43aa-a9ef-5de2b5ada846@s1g2000prg.googlegroups.com> Message-ID: <819479ab-0073-49fb-ab29-327aebd97c54@z6g2000pre.googlegroups.com> On Dec 21, 8:42?pm, MRAB wrote: > Aaron Brady wrote: > > On Dec 21, 6:14 pm, MRAB wrote: snip > >> Yes, I suggested that earlier, but it isn't needed because you can > >> create a format object with "Format(string)". However, most of the time > >> you won't bother to create a format object explicitly because of: > > >> class str(object): > >> ? ? ?def __mod__(self, value): > >> ? ? ? ? ?return Format(self) % value > > >>>>>> f = f"%r %i" > >>>>>> type(f) > >>> > >> ?>>> # Explicitly > >> ?>>> f = Format("%r %i") > >> ?>>> f > >> > >> ?>>> f % (2, 3, 4) > >> > > >> ?>>> # Implicitly, relying on the __mod__ method of str > >> ?>>> f = "%r %i" > >> ?>>> f > >> '%r %i' > >> ?>>> f % (2, 3, 4) > >> > > >> I'd also like to add that there's nothing to prevent format objects from > >> having other methods where multiple placeholders can be filled in one call: > > >> ?>>> # By position > >> ?>>> f = Format("%r %i") > >> ?>>> f > >> > >> ?>>> f.fill([(2, 3, 4), 1]) > >> '(2, 3, 4) 1' > > >> ?>>> # By name > >> ?>>> f = Format("%{tuple}r %{int}i") > >> ?>>> f > >> > >> ?>>> f.fill({"tuple": (2, 3, 4), "int": 1}) > >> '(2, 3, 4) 1' > > > You're choosing to favor the '.chain()' method over the '.fill()' > > method for the behavior of '%'. ?I don't think you've justified it > > though. > > >>>> Format( "%r %i" ).chain( ( 2, 3, 4 ) ).chain( 0 ) > > '(2, 3, 4) 0' > >>>> Format( "%r %i" ).fill( ( 2, 3, 4 ), 0 ) > > '(2, 3, 4) 0' > > > Plus, I almost think we've almost attained defeating the purpose. > > The disadvantage of the chaining method is that it's positional, > left-to-right. For the purposes of i18n you want tagged placeholders, > whether they be integers or names. I think... OK, if the placeholders > include a positional tag, eg "%(0)s %(1)s", then they could be filled in > according to _that_ order. Not sure about named placeholders, though. > Perhaps, like at present, if a dict is given to a format with named > placeholders then several placeholders could be filled, the problem > being how to fill a _single_ named placeholder with a dict. Just pass a keyword argument to chain. >>> Format( "%(tup)r %(int_)i" ).chain( tup= ( 2, 3, 4 ) ).chain( int_= 0 ) '(2, 3, 4) 0' You might want to call it 'fchain' or 'chainf'. From rt8396 at gmail.com Thu Dec 18 12:49:59 2008 From: rt8396 at gmail.com (r) Date: Thu, 18 Dec 2008 09:49:59 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <71ede5f0-fd88-4155-9f0d-42d0ad5f57dc@v42g2000yqj.googlegroups.com> Message-ID: <61f45e65-2404-4cc0-9d81-f848c1ba566f@i18g2000prf.googlegroups.com> Maybe someone will chime in with an answer, sorry i could not help. ponder this, i must... From prasannaksahoo at gmail.com Thu Dec 4 23:31:01 2008 From: prasannaksahoo at gmail.com (pk sahoo) Date: Fri, 5 Dec 2008 10:01:01 +0530 Subject: getting error...... Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in open_workbook biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) File "C:\Python25\Lib\site-pack Message-ID: hallo everybody, when i am running the following command >>> import xlrd >>> book=xlrd.open_workbook("C:\\a.xls") i am getting the following error.. *Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in open_workb ook biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 1323, in getbof raise XLRDError('Expected BOF record; found 0x%04x' % opcode) xlrd.biffh.XLRDError: Expected BOF record; found 0x3f3c* what is the reason.... pz help me out.. regards prasanna * * -------------- next part -------------- An HTML attachment was scrubbed... URL: From money.maker20096 at gmail.com Sat Dec 27 00:10:04 2008 From: money.maker20096 at gmail.com (money_maker) Date: Fri, 26 Dec 2008 21:10:04 -0800 (PST) Subject: Online Trading Message-ID: Online Trading http://209.188.94.20/~x69/?p=81 The Best Online Money Maker Ever http://209.188.94.20/~x69/?p=66 Google Adsense Program Is Like Finding Money In The Street http://209.188.94.20/~x69/?p=99 Hit Success Street With Google Adsense http://209.188.94.20/~x69/?p=98 Earn Money Running Ads http://209.188.94.20/~x69/?p=96 How And Where To Get Jobs At Home? http://209.188.94.20/~x69/?p=94 How Do You Become A Successful Affiliate Marketer? http://209.188.94.20/~x69/?p=93 7 Ways You Can Make Money On-line http://209.188.94.20/~x69/?p=92 Why Do Most People Fail At Working From Home? http://209.188.94.20/~x69/?p=90 Earn $500 To $1000 Daily Working From Home http://209.188.94.20/~x69/?p=88 Earn Money Online Securely http://209.188.94.20/~x69/?p=86 How do I make money from home? http://209.188.94.20/~x69/?p=84 The Best Online Money Maker Ever http://209.188.94.20/~x69/?p=186 3Quick Ways To Make Money Online http://209.188.94.20/~x69/?p=169 Online Trading http://209.188.94.20/~x69/?p=168 HOW TO START AND OPERATE YOUR OWN PROFITABLE IMPORT/EXPORT BUSINESS AT HOME http://209.188.94.20/~x69/?p=61 Why read online stock-trading articles? http://209.188.94.20/~x69/?p=60 Online Trading http://209.188.94.20/~x69/?p=59 Quick Ways To Make Money Online 3 http://209.188.94.20/~x69/?p=58 Remergent Skin Care Products Restore Dna And Promote Healthy Skin From mail at microcorp.co.za Sat Dec 27 07:54:32 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 27 Dec 2008 14:54:32 +0200 Subject: ctypes & strings References: <334452.47084.qm@web30003.mail.mud.yahoo.com> Message-ID: <000f01c96822$5c300f00$0d00a8c0@hendrik> Red Rackham wrote: >I would like to pass a string into a dll function. I notice that to pass using ctypes, it has to be a ctypes type. >Looking at the ctypes doc page I don't see a c_string class. The following seems to work for me: In the c programme: /* This routine outputs and inputs a symmetric block of bytes, writing the outputs out and reading the inputs in, replacing the chars in the original output string */ unsigned char read_write (unsigned char *inputs, unsigned char *outputs, int lenin, int lenout) { int i = 0; int addr = 0; int addrhi = 0; int oind = 0; char rv; while (i < lenin) { addrhi = i >> 8 & 0x3f; // we can have 64 * 256 adresses in the top 6 + 8 bits addr = i & 0xff; // this is low order rv = put_1(addrhi|0xd0); // put out the addy rv = put_3(addr); rv = put_1(addrhi|0x90); // make a read strobe on bit 6 inputs[i] = get_0() ^ 255; // read the char rv = put_1(addr|0xd0); // raise strobe again i++; } while (i < lenin + lenout) { oind = i - lenin; // index into outputs start at 0 addrhi = i >> 8 & 0x3f; // we can have 64 * 256 adresses in the top 6 + 8 bits addr = i & 0xff; // this is low order rv = put_1(addrhi|0xd0); // put out the addy rv = put_3(addr); rv = put_0(outputs[oind]); // put out the output rv = put_1(addrhi|0x50); // make a write strobe on bit 7 rv = put_1(addrhi|0xd0); // raise write strobe again i++; } return *inputs; } Then in the python it is used as follows: import sys, os, ctypes, time io = ctypes.cdll.LoadLibrary('./lib_gpio.a') def do_io(ins, outs): # ins and outs are normal python strings that must exist # this routine happens to work by side effect - the ins string is changed by the c routine r = io.read_write(ins,outs,len(ins),len(outs)) return The c routine will actually break Python's normal string immmutability and give you back a changed ins. It is in general not a good idea to change the passed string like I am doing - but you wanted to know how to pass a python string, and the outs example should get you going - a string is an array of characters in c... HTH - Hendrik From tjreedy at udel.edu Tue Dec 9 13:25:10 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 09 Dec 2008 13:25:10 -0500 Subject: RuntimeError: dictionary changed size during iteration In-Reply-To: References: <274eb282-1635-40ca-95af-b82271c57802@v4g2000yqa.googlegroups.com> <8c67c6b0-50f7-40ae-93e4-09edd07d6946@r36g2000prf.googlegroups.com> Message-ID: Robert Dailey wrote: > When I do: > > for key in stuff.keys(): > > > It works! I wonder why .keys() makes a difference. It is using a > 'view', which is a new concept in Python 3.0 that I'm not totally > familiar with yet. Because stuff.keys() is evaluated *once* and the result is a separate object from stuff == globals(), so creating the new entry 'key' in globals == stuff does not change that new object. From rt8396 at gmail.com Fri Dec 19 20:12:00 2008 From: rt8396 at gmail.com (r) Date: Fri, 19 Dec 2008 17:12:00 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <1332da3c-8075-4552-9498-3ceb23faca8f@v31g2000vbb.googlegroups.com> Scott, Oh, so Python 3.0 is an Equal Opportunity Enigma, now i get it :D Steve, Obviously i was referring to the look, not the actuality of a tuple Marc, Why move away from a concise and widely accepted way of sting formatting, just to supposedly make it a little easier for n00bs? (which i disagree this is easier) In turn, creating more syntactical clutter. (%s %f %d) is all you need to remember. If people can't understand that, i fear for the future of Humans as a species! [bearophile], """So I think it's right to make Python3 become a little higher level language even if this slows it down a little. For the kind of programs Python is often used for, I think this is a Win. (Ruby programs are often slower than Python ones (because Ruby is a little higher level than Python) but it's very useful anyway). If Python will continue to develop in the following years (think about a Python4000) then I think it may become good to make it become even more slower, if this will help make it a little more higher level still.""" [/bearophile], Yea, if your keeping up with the "Rubies" i guess. Python's strengths are in it's simplicity -and- it's constraints. Turning Python into a language so stupid a monkey could use it(there by slowing it down in the process),is counter intuitive, and will chase away core followers. Let Ruby try to include every way possible known to man to do one simple process, just to please the most people. Are we Python coders or "Corrupt Politicians" looking to grab every vote by trying to please the masses thereby sacrificing our souls in the process --> Ruby. *It may be time to start hacking my own personal version of the Python interpreter. hmm... Keep you ears to the ground... From kirk at daycos.com Thu Dec 11 14:44:22 2008 From: kirk at daycos.com (Kirk Strauser) Date: Thu, 11 Dec 2008 13:44:22 -0600 Subject: newbie question: if var1 == var2: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> Message-ID: <87y6ymzecp.fsf@daycos.com> At 2008-12-11T17:24:44Z, rdmurray at bitdance.com writes: > >>> ' ab c \r\n'.rstrip('\r\n') > ' ab c ' > >>> ' ab c \n'.rstrip('\r\n') > ' ab c ' > >>> ' ab c '.rstrip('\r\n') > ' ab c ' I didn't say it couldn't be done. I just like the Perl version better. -- Kirk Strauser The Day Companies From gandalf at shopzeus.com Fri Dec 19 02:54:26 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 19 Dec 2008 08:54:26 +0100 Subject: psycopg2 and large queries In-Reply-To: <1de36399-f94f-42b3-87ea-3812fed4bd86@r36g2000prf.googlegroups.com> References: <1de36399-f94f-42b3-87ea-3812fed4bd86@r36g2000prf.googlegroups.com> Message-ID: <494B5332.3090407@shopzeus.com> > They do have a description attribute, but it is only populated after > you fetch a row. eg try > cur = conn.cursor(name='mycursor') > cur.execute('select name from blah') > cur.fetchone() > print cur.description > Oh, great. I should have known. Thanks. Maybe I can live with psycopg2, because combining server side (named) cursors with fetchmany(100) gives fast query opening and relatively fast row fetching. Thank you for all! Laszlo From martin at marcher.name Sat Dec 27 21:19:06 2008 From: martin at marcher.name (Martin) Date: Sun, 28 Dec 2008 03:19:06 +0100 Subject: Is there a function to remove escape characters from a string ? In-Reply-To: <49560E7E.1050307@gmail.com> References: <0163882f$0$6988$c3e8da3@news.astraweb.com> <5a29b62a-c38f-409b-8887-6259ad072bf5@w1g2000prk.googlegroups.com> <01659326$0$6988$c3e8da3@news.astraweb.com> <49560E7E.1050307@gmail.com> Message-ID: <5fa6c12e0812271819t1b218c7h4bef3b426e477754@mail.gmail.com> 2008/12/27 Stef Mientki : > Steven D'Aprano wrote: >> No, that only makes it even more confusing. What does Moore's Law have to >> do with your willful ignorance about the existence of human languages other >> than English? >> > Nothing. > I even don't (want to) see what bits / bytes / escape sequences have to do > with modern programming techniques, > so I certainly don't see any relation between these and human languages. > > But the lack of Moore's law in software explains why we still need to > concern about bits and bytes ;-) http://www.joelonsoftware.com/articles/Unicode.html -- http://soup.alt.delete.co.at http://www.xing.com/profile/Martin_Marcher http://www.linkedin.com/in/martinmarcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From prologic at shortcircuit.net.au Mon Dec 8 01:37:19 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Dec 2008 16:37:19 +1000 Subject: A question about reference in Python. In-Reply-To: <47c890dc0812072225u7cde16eh9ba69a2f4cdacd16@mail.gmail.com> References: <493CB003.3080209@gmail.com> <47c890dc0812072213q20cb415fjbd4c80e7af7a7ef5@mail.gmail.com> <47c890dc0812072225u7cde16eh9ba69a2f4cdacd16@mail.gmail.com> Message-ID: On Mon, Dec 8, 2008 at 4:25 PM, Chris Rebert wrote: > No apology necessary of course, i just didn't want the newbie OP to > pick up any bad Python coding habits. Apologies that I might have > phrased my criticism a bit harshly. No not at all :) I do use class variables in some places in my library as well as instance variables. Force of habit :) Actually to be honest I think I only use it in one or two places! Haha :) *meh* Hope the OP learns what he needs to! cheers James -- -- -- "Problems are solved by method" From Ron.Barak at lsi.com Wed Dec 17 02:43:16 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Wed, 17 Dec 2008 07:43:16 +0000 Subject: String slices work only for first string character ? In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF60249410A@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF60249410A@enbmail01.lsi.com> Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6024941AE@enbmail01.lsi.com> Thanks to all who pointed my wrong understanding of how string slices are defined. Bye, Ron. ________________________________ From: Barak, Ron [mailto:Ron.Barak at lsi.com] Sent: Tuesday, December 16, 2008 15:35 To: python-list at python.org Subject: String slices work only for first string character ? Hi, Can any one explain why the following string slice works only for the first character, but not for any other ? $ cat /tmp/tmp.py #!/usr/bin/env python data = 'F0023209006-0101' print data print "|"+data[0:1]+"|" print "|"+data[1:1]+"|" print "|"+data[2:1]+"|" $ python `cygpath -w /tmp/tmp.py` F0023209006-0101 |F| || || $ Thanks, Ron. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gdamjan at gmail.com Wed Dec 3 15:12:13 2008 From: gdamjan at gmail.com (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Wed, 03 Dec 2008 21:12:13 +0100 Subject: Switching windows in PyQT References: <9ef85e1f-9e46-48b6-8d11-a4f6e7176657@d23g2000yqc.googlegroups.com> Message-ID: > I am new to PyQT and GUI programming in general. What tutorials I have > found are relatively clear on standard operations within a single > window (QtGui.QWidget or QtGui.QMainWindow). Exiting this window exits > the overall application. > > How would I switch between windows, that is close one and open > another, within a running application. I would imagine this to be a > standard feature often coded. most often you don't close windows but hide them. Still, the app object has a property quitOnLastWindowClosed that you can set to false. -- ?????? ( http://softver.org.mk/damjan/ ) Q: What's tiny and yellow and very, very, dangerous? A: A canary with the super-user password. From google at mrabarnett.plus.com Sun Dec 14 10:43:46 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 14 Dec 2008 15:43:46 +0000 Subject: 1 or 1/0 doesn't raise an exception In-Reply-To: <6e2d11cd-a57e-4cd4-9cd7-a65eb08f220e@u18g2000pro.googlegroups.com> References: <49446E39.6020807@tim.thechases.com> <6e2d11cd-a57e-4cd4-9cd7-a65eb08f220e@u18g2000pro.googlegroups.com> Message-ID: <494529B2.60108@mrabarnett.plus.com> Rohannes wrote: > 'Dive into Python' has a very memorable and interesting section on the > exact behaviour of 'and' and 'or' in Python: > > http://diveintopython.org/power_of_introspection/and_or.html > >> No: &, | (and ^, too) perform bitwise operations in Python, C and Java: > > "In complete evaluation ... both expressions are always evaluated. To > obtain complete evaluation in Java, you use & rather than && ... and > use | in place of ||" - Walter Savitch, Absolute Java 2nd ed. > > Although & IS the bitwise-AND operator in Java: > http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html > > I guess it's a matter of context. > Java has a bool type that's distinct from the int type. &, | and ^ are bitwise for int and Boolean for bool, and in both cases they are strict. && and || are for bool only and they are lazy. In Pascal the behaviour of "and" and "or" is implementation-dependant... From martin at v.loewis.de Mon Dec 8 19:55:43 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 09 Dec 2008 01:55:43 +0100 Subject: Number of Python 3.x packages at the PyPI In-Reply-To: <3b2464a1-84d4-4833-ac26-accd317d978d@k19g2000yqg.googlegroups.com> References: <9c1ab0f3-6686-4c0f-8a6c-12e20539f354@41g2000yqf.googlegroups.com> <493b954e$0$4021$9b622d9e@news.freenet.de> <2d656e64-deff-40ed-8066-57b6f8874ec4@b38g2000prf.googlegroups.com> <493c29a7$0$27869$9b622d9e@news.freenet.de> <3b2464a1-84d4-4833-ac26-accd317d978d@k19g2000yqg.googlegroups.com> Message-ID: <493DC20F.7040606@v.loewis.de> >> On second thought: can't you just include the source of both versions >> in a single source distribution file? > > The .tar.gz distributions are built by distutils/setuptools. If I > manually combine them into a single archive That's not what I'm proposing, though. Assuming you have two different versions of your package, they should both live next to each other, in a single root directory, e.g. foo/ setup.py bar_2x/ bar_3x/ Then sdist should package it all, through a MANIFEST.in, and install/bdist/... should package it version-dependent: if sys.version >= (3,0): package_dir = {'bar':'bar_3x'} else: package_dir = {'bar':'bar_2x'} setup(... package=dir = package_dir, ... ) > I'm guessing that > 'easy_install appscript' won't know how to read that custom archive > when building and installing from source. (Which also raises a further > question: if I do eventually manage to upload both 2.x and 3.x > versions under the same PyPI entry, will easy_install know which one > to download?) See above. Won't this solve these problems? (although I don't know what the "appscript" command does) Regards, Martin From bj_666 at gmx.net Sun Dec 14 04:25:27 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 14 Dec 2008 09:25:27 GMT Subject: the official way of printing unicode strings References: Message-ID: <6qk1o7Fcr01gU3@mid.uni-berlin.de> On Sun, 14 Dec 2008 06:48:19 +0100, Piotr Sobolewski wrote: > Then I tried to do this that way: > sys.stdout = codecs.getwriter("utf-8")(sys.__stdout__) > s = u"Stanis?aw Lem" > print u > This works but is even more combersome. > > So, my question is: what is the official, recommended Python way? I'd make that first line: sys.stdout = codecs.getwriter('utf-8')(sys.stdout) Why is it even more cumbersome to execute that line *once* instead encoding at every ``print`` statement? Ciao, Marc 'BlackJack' Rintsch From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 20:46:13 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2008 01:46:13 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> Message-ID: <015c45b8$0$20656$c3e8da3@news.astraweb.com> On Fri, 19 Dec 2008 09:55:01 -0800, bearophileHUGS wrote: > C string formatting is short and a flexible enough, but it's out of > place in a language as high level as Python3. The new syntax allows more > flexibility, and it's better for most people that don't know C already, > like newbies, etc. I'm somebody who frequently argues that we shouldn't assume that everybody knows C. But on the other hand, we shouldn't assume that newbies don't know C either! % formatting is so very common that even a duffer like me who never learned C came to Python already knowing the basics of % formatting. -- Steven From muhamed.hmd at gmail.com Wed Dec 10 14:09:50 2008 From: muhamed.hmd at gmail.com (john adam) Date: Wed, 10 Dec 2008 11:09:50 -0800 (PST) Subject: hi...hi.....hi Message-ID: <2560fe66-626b-49b5-afc1-77d7c9bbd76e@d36g2000prf.googlegroups.com> conratulatios...... Here's my dear friend largest mobile library programs All you care programs : Witness all the programs in the modern world Alkmiotr Honored by your visit You'll see in the blogger 1.If you are suffering from a virus protection programs most important to you AVG Anti-Virus Free Edition "avG" http://mesotheliomame.blogspot.com/2008/11/pericardial-mesothelioma-and-modern.html 2.If you turn suffering from transmitting the files LimeWire Pro 4.14.7 http://mesotheliomame.blogspot.com/2008/11/overview-of-mesothelioma-cancer.html 3.If you have files you spy on your computer solution Ad-Aware 2008 http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawsuits-faq.html 4.You stronger virus program Ante 2008 Avira AntiVir Personal - Free Antivirus http://mesotheliomame.blogspot.com/2008/11/number-form-of-mesothelioma-pleural.html 5.Now a program of protection and anti-virus and anti-spy files Avast Home Edition http://mesotheliomame.blogspot.com/2008/11/what-to-look-for-in-california.html 6.If you are suffering from non-fast you download this program FrostWire http://mesotheliomame.blogspot.com/2008/11/if-you-are-diagnosed-with-mesothelioma_15.html 7.If you have difficulty loading of the Diaspora and Google Orbit Downloader http://mesotheliomame.blogspot.com/2008/11/if-you-are-diagnosed-with-mesothelioma.html 8.If you have difficulty difficult compression "file" winrar http://mesotheliomame.blogspot.com/2008/11/contacting-mesothelioma-lawyer.html 9.If you are suffering from aAdware/Malware files you solution Malwarebytes' Anti-Malware http://mesotheliomame.blogspot.com/2008/11/scientists-conduct-clincial-trials-of.html 10.Now the most powerful video chat in the world Camfrog Video Chat http://mesotheliomame.blogspot.com/2008/11/new-drug-study-for-abdominal.html 11.Program chat world is a lot mIRC http://mesotheliomame.blogspot.com/2008/11/ohio-mesothelioma-lawyer-help-you-get.html 12.If you have difficulty reading flv files FLV Player http://mesotheliomame.blogspot.com/2008/11/detailed-information-on-mesothelioma.html 13.If you have difficulty download from youtube YouTube Downloader http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawyers-in-high-demand.html 14.If you are suffering from penetrating the strongest program you repel breakthroughs in the world Spybot - Search & Destroy http://mesotheliomame.blogspot.com/2008/11/chemotherapy-treatment-for-mesothelioma.html 15.If you have difficulty with the way they spread the images IrfanView http://mesotheliomame.blogspot.com/2008/11/california-mesothelioma-laws-and.html 16.Now have a major program of the torrent file and upload files BitComet http://mesotheliomame.blogspot.com/2008/11/facing-mesothelioma-without-california.html 17.The program is exclusive download from the Web at high speed Download Accelerator Plus http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-diagnoses-increase_15.html 18.If you are suffering from problems with the performance of the solution you Smart Defrag http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-diagnoses-increase.html 19.If you have difficulty in performing the solution you Advanced WindowsCare Personal http://mesotheliomame.blogspot.com/2008/11/mesothelioma-is-deadly-cancer.html 20.If you have difficulty in operating the sound and video files you solution real player http://mesotheliomame.blogspot.com/2008/11/facts-and-misconceptions-about.html 21.Here is the most important video player program in America GOM Media Player http://mesotheliomame.blogspot.com/2008/11/how-severe-is-mesothelioma-disease.html 22.If you have difficulty operating Flash Games Flash Player http://mesotheliomame.blogspot.com/2008/11/glimpse-at-mesothelioma-info-from-past.html 23.If you have difficulty in cleaning Riggstir professionally you the best solution http://mesotheliomame.blogspot.com/2008/11/detection-of-asbestos-mesothelioma.html 24.If you turn suffering from your computer and the difficulty you download this program"System Mechanic" http://mesotheliomame.blogspot.com/2008/11/brief-overview-of-malignant.html 25.If you are suffering from problems in the cleaning solution you Riggstir http://mesotheliomame.blogspot.com/2008/11/mesothelioma-and-911.html 26.Use the latest hour computer in the world in the magnificence of beauty http://mesotheliomame.blogspot.com/2008/11/precise-idea-about-pericardial.html 27.If you have difficulty in maintaining from hard disk http://mesotheliomame.blogspot.com/2008/11/mesothelioma-at-glance.html 28.If you have difficulty in managing personal and protection of your system you program http://mesotheliomame.blogspot.com/2008/11/financial-burden-of-mesothelioma.html 29.If you have difficulty in recording data and operation of your system http://mesotheliomame.blogspot.com/2008/11/how-to-find-mesothelioma-lawyer.html 30.Here's this program that offers you much time http://mesotheliomame.blogspot.com/2008/11/hurricane-victims-at-risk-for.html 31.If you have difficulty in browsing files http://mesotheliomame.blogspot.com/2008/11/3-top-florida-mesothelioma-lawyer.html 32.Here's this program, which automatically corrects the mistakes of your system security http://mesotheliomame.blogspot.com/2008/11/if-diagnosed-with-mesothelioma-call.html 33.The enjoyment of this program to register images from camera to the computer during the talk http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-diagnosed-questions.html 34.If you have difficulty transforming stretches in games or votes you this giant http://mesotheliomame.blogspot.com/2008/11/mesothelioma-ready-reckoner.html 35.If you have difficulty in operation all formats video files http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawyers-how-to-choose-them.html 36.If you have difficulty in the organization and ease of cleaning solution you http://mesotheliomame.blogspot.com/2008/11/mesothelioma-exposure-could-be-fatal.html 37.Very popular program in the compression winzip http://mesotheliomame.blogspot.com/2008/11/mesothelioma-greed-cancer-profits.html 38..If you want to broadcast material on the Internet you solution Virtual DJ Software http://mesotheliomame.blogspot.com/2008/11/abc-mesothelioma-new-treatments-for.html 39.now The creation of program files pdf PrimoPDF http://mesotheliomame.blogspot.com/2008/11/abc-mesothelioma-treatments-for.html 40..If you have difficulty operating the extensions you solution "MPEG-1, MPEG-2, MPEG-DivX, mp3, ogg VLC Media Player http://mesotheliomame.blogspot.com/2008/11/brachytherapy-for-treatment-of.html 41.If you have difficulty browser you this treasure Mozilla Firefox http://mesotheliomame.blogspot.com/2008/11/asbestos-mesothelioma-treatment-how.html 42.If you are difficult to clean your computer you solution Glary Utilities http://mesotheliomame.blogspot.com/2008/11/mesothelioma-treatment-research.html 43.very Free program to repair and improve and see photos PhotoScape http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-history.html 44.If you have difficulty operating films and cartoons BS.Player http://mesotheliomame.blogspot.com/2008/11/mesothelioma-attorney.html 45.Conversion formulas giant cylinders to the chimerical not want the program ... PowerISO http://mesotheliomame.blogspot.com/2008/11/deadly-mesothelioma-symptoms-could-be_15.html 46.You program the operator of high-quality video DivX for Windows with DivX Player http://mesotheliomame.blogspot.com/2008/11/deadly-mesothelioma-symptoms-could-be.html 47.If you have difficulty copies of CDs nero "9"new http://mesotheliomame.blogspot.com/2008/11/association-of-asbestos-and.html 48.If you have difficulty audio chat on the net you the solution Windows Live Messenger http://mesotheliomame.blogspot.com/2008/11/need-for-mesothelioma-lawyer-to-fight.html 49.If you have difficulty download on the net ActiveX Download Control http://mesotheliomame.blogspot.com/2008/11/funding-for-mesothelioma-research-noble_15.html 50.If you have difficulty in registration at the sites and forums you solution RoboForm http://mesotheliomame.blogspot.com/2008/11/funding-for-mesothelioma-research-noble.html 51.If you are an amateur or design you a solution designed sites you Adobe Photoshop CS3 Extended http://mesotheliomame.blogspot.com/2008/11/brief-overview-of-peritoneal.html 52.If you have difficulty cleaning you stronger cleaning program in the world ccleaner http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawyers-helping-hands.html 53.If you have difficulty in Alturrent know what files you need them all uTorrent http://mesotheliomame.blogspot.com/2008/11/how-to-proceed-with-mesothelioma_15.html 54.If you have difficulty in loading files from the iPod Lalai iTunes http://mesotheliomame.blogspot.com/2008/11/how-to-proceed-with-mesothelioma.html 55.If you have difficulty converting audio files to any formulas you solution Easy CD-DA Extractor http://mesotheliomame.blogspot.com/2008/11/difference-between-pleural-and.html 56.If you have difficulty converting video files to the formula psp PSP Video 9 http://mesotheliomame.blogspot.com/2008/11/positive-guideline-to-deal-with.html 57.If you have difficulty in the work of videos from YouTube to evict you like you solution Windows Movie Maker http://mesotheliomame.blogspot.com/2008/11/history-of-asbestos-related.html 58.If you have difficulty in Works with all audio files extranet windows media player http://mesotheliomame.blogspot.com/2008/11/tips-on-choosing-your-mesothelioma.html 59.If you have difficulty in Browser you the most powerful browser in the world Avant Browse http://mesotheliomame.blogspot.com/2008/11/good-mesothelioma-attorney-is-hard-to.html 60.If you have difficulty in Video-sharing to you this wonderful program BearFlix http://mesotheliomame.blogspot.com/2008/11/peritoneal-mesothelioma-information.html 61.If you have difficulty in Survey of spyware on your computer SpywareBlaster http://mesotheliomame.blogspot.com/2008/11/how-to-care-for-someone-with.html 62.If you are suffering from problems in Alhard Disek you this legend smart PerfectDisk http://mesotheliomame.blogspot.com/2008/11/why-is-mesothelioma-so-deadly.html 63.If you have difficulty in the liberation of files "pdf" http://mesotheliomame.blogspot.com/2008/11/when-do-you-need-mesothelioma-attorney.html 64.If you have difficulty in personal control of your system next to you http://mesotheliomame.blogspot.com/2008/11/all-about-mesothelioma-lawyer.html 65.If you have difficulty in the key to jump easily be you next http://mesotheliomame.blogspot.com/2008/11/what-is-mesothelioma-cancer.html 66.If you have difficulty playing in the pictures and the amendment http://mesotheliomame.blogspot.com/2008/11/mesothelioma-information.html 67.If you have difficulty in protecting your system security followed CAPS http://mesotheliomame.blogspot.com/2008/11/symptoms-of-mesothelioma.html 68.If you have difficulty in speed of your computer you this program http://mesotheliomame.blogspot.com/2008/11/what-radical-mesothelioma-treatments.html 69.If you have difficulty maintaining a malfunction in your computer that you legend http://mesotheliomame.blogspot.com/2008/11/can-washington-mesothelioma-attorneys.html 70.If you have difficulty in the transfer of files between disks http://mesotheliomame.blogspot.com/2008/11/causes-of-mesothelioma-cancer.html 71.Discovered the most important program on the Web EZ Macros http://mesotheliomame.blogspot.com/2008/11/mesothelioma-treatment-radiation-or.html 72.If you are suffering from similar files, you repeat this unique program http://mesotheliomame.blogspot.com/2008/11/types-of-mesothelioma-cancer.html http://mesotheliomame.blogspot.com/ From ivan.illarionov at gmail.com Tue Dec 9 05:43:38 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 9 Dec 2008 02:43:38 -0800 (PST) Subject: Beginner trying to understand functions. References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> <9df7549a-f28b-4d39-b105-90c099f472f2@z28g2000prd.googlegroups.com> <040a2896-be99-477e-909c-c55c5a0e6665@y1g2000pra.googlegroups.com> Message-ID: On Dec 8, 9:02?pm, simonh wrote: > Thanks for the many replies. Thanks especially to Pierre. This works > perfectly: > def getAge(): > ? ? while True: > ? ? ? ? try: > ? ? ? ? ? ? age = int(input('Please enter your age: ')) > ? ? ? ? ? ? return age > > ? ? ? ? except ValueError: > ? ? ? ? ? ? print('That was not a valid number. Please try again.') You could also drop the while loop and the 'age' variable: def getAge(): try: return int(input('Please enter your age: ')) except ValueError: print('That was not a valid number. Please try again.') return getAge() From lew at lewscanon.com Tue Dec 2 16:57:35 2008 From: lew at lewscanon.com (Lew) Date: Tue, 2 Dec 2008 13:57:35 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <591e8625-7e4d-4db8-ae6c-73c4370f8088@q26g2000prq.googlegroups.com> Message-ID: Xah Lee wrote: > If [yo]u would like to learn [the] [E]nglish lang[uage] and writing insights from me, > peruse: /Au contraire/, I was suggesting a higher standard for your posts. > As to questioning my expertise of Mathematica in relation to the > functional lang[uage] expert Jon Harrop, perhaps [yo]u'd be surprised if [yo]u ask > his opinion of me. My own opinion, is that my Mathematica expertise > surpasses his. My opinion of his opinion of me is that, my opinion on > Mathematica is not to be trifled with. I have no assertion or curiosity about Jon Harrop's expertise compared to yours. I was expressing my opinion of his expertise, which is high. > Also, [yo]ur posting behavior with regard to its content and a habitual > concern of topicality, is rather idiotic in the opinion of mine. On There is no reason for you to engage in an /ad hominem/ attack. It does not speak well of you to resort to deflection when someone expresses a contrary opinion, as you did with both Jon Harrop and with me. I suggest that your ideas will be taken more seriously if you engage in more responsible behavior. > the surface, the army of [yo]ur kind have the high spirit for the health > of community. But underneath, i [sic] think it is [yo]u who [a]r[e] the most > wortheless with regards to online computing forum's health. You are entitled to your opinion. I take no offense at your attempts to insult me. How does your obfuscatory behavior in any way support your technical points? -- Lew From boyee118 at gmail.com Thu Dec 18 06:25:27 2008 From: boyee118 at gmail.com (=?UTF-8?B?5Li654ix6ICM55Sf?=) Date: Thu, 18 Dec 2008 19:25:27 +0800 Subject: [Help] The pywinauto Can't select the MDI's menu using the MenuItems() which return []. In-Reply-To: References: Message-ID: This problem also use the following discription:How to use pywinauto to open WORD and select its Menu. I can't do that and have no idea why! Looking forward your help,Thanks! 2008/12/17 ???? > I can't use the MenuItems() in my MDI application. > Any example is very nice!!!! Thanks a lot! > > -- > "OpenBookProject"-?????????? > ??: http://groups.google.com/group/OpenBookProject > ??: http://wiki.woodpecker.org.cn/ > -- "OpenBookProject"-?????????? ??: http://groups.google.com/group/OpenBookProject ??: http://wiki.woodpecker.org.cn/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From h0leforfun at gmail.com Wed Dec 17 09:33:53 2008 From: h0leforfun at gmail.com (Hole) Date: Wed, 17 Dec 2008 06:33:53 -0800 (PST) Subject: Python, XML and XPath References: <49490c49$0$1115$4fafbaef@reader3.news.tin.it> Message-ID: > > I need to use XML parsing with xpath: a simple xml reader. > > You can try lxml, have a look herehttp://codespeak.net/lxml/xpathxslt.html Thanks a lot to everyone! From 20080915.20.wmcclain at spamgourmet.com Wed Dec 10 13:55:10 2008 From: 20080915.20.wmcclain at spamgourmet.com (Bill McClain) Date: 10 Dec 2008 18:55:10 GMT Subject: StringIO in 2.6 and beyond References: Message-ID: On 2008-12-10, pruebauno at latinmail.com wrote: > I think this combination might do the trick (I don't have 2.6 to test > it right now): > from __future__ import print_function > from __future__ import unicode_literals > from functools import partial > import io > print = partial(print, sep=" ", end="\n") > out = io.StringIO() > print("hello", file=out) The example works, but unicode_literals causes problems elsewhere, in optparse for example. I didn't look into it too closely. I'll probably give up trying to anticipate 3.0 with 2.6 too closely. -Bill -- Sattre Press Tales of War http://sattre-press.com/ by Lord Dunsany info at sattre-press.com http://sattre-press.com/tow.html From google at mrabarnett.plus.com Fri Dec 12 13:30:19 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 12 Dec 2008 18:30:19 +0000 Subject: (Very Newbie) Problems defining a variable In-Reply-To: References: Message-ID: <4942ADBB.8030309@mrabarnett.plus.com> Tim Rowe wrote: > Since we all seem to be having a go, here's my take. By pulling the > rates and thresholds into a dictionary I feel I'm getting a step > closer to the real world, where these would presumably be pulled in > from a database and the number of interest bands might vary. But is > there a tidier way to get 'thresholds'? I was a bit surprised that > rates.keys() didn't give me a list directly, so although the 3.0 > tutorial says "The keys() method of a dictionary object returns a list > of all the keys used in the dictionary, in arbitrary order (if you > want it sorted, just apply the sort() method to )" that's not /quite/ > such a given, because "the list of keys" doesn't seem to be there for > the sorting any more. > > Is there a tidy way of making rates and thresholds local to get_rate, > without recalculating each time? I suppose going object oriented is > the proper way. > > #Py3k,UTF-8 > > rates = {0: 0.006, 10000: 0.0085, 25000: 0.0124, 50000: 0.0149, 100000: 0.0173} > thresholds = list(rates.keys()) > thresholds.sort() > thresholds.reverse() > Why are you putting them into a dict at all? Surely a list of tuples is better? # I could've just written the list in descending order here! rates = [(0, 0.006), (10000, 0.0085), (25000, 0.0124), (50000, 0.0149), (100000, 0.0173)] thresholds.sort(reversed=True) > def get_rate(balance): > for threshold in thresholds: > if balance >= threshold: > return rates[threshold] > else: > return 0.0 > def get_rate(balance): for threshold, rate in thresholds: if balance >= threshold: return rate return 0.0 > balance = int(input("How much money is in your account?\n>>")) > target = int(input("How much money would you like to earn each year?\n>>")) > > if balance <= 0: > print("You'll never make your fortune that way!\n") > else: > interest = 0 > year = 0 > while interest < target: > rate = get_rate(balance) > interest = balance * rate > balance += interest > year += 1 > print("Year %s, at %s rate: %s paid, %s in bank." % (year, > rate, interest, balance)) > From jstroud at mbi.ucla.edu Wed Dec 10 05:44:11 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 10 Dec 2008 02:44:11 -0800 Subject: filter iterable based on predicate take from another iterable In-Reply-To: References: Message-ID: <%3N%k.9174$x%.5002@nlpi070.nbdc.sbc.com> Peter Otten wrote: > bernhard.voigt at gmail.com wrote: > >> is there is a neat way to select items from an iterable based on >> predicates stored in another iterable without zipping? I can do >> something like this: >> >> import itertools >> foo = range(10) >> # select even numbers >> bar = map(lambda i: i%2, foo) >> foobarselected = itertools.ifilterfalse(lambda t: t[0], itertools.izip >> (bar,foo)) >> # for simplicity I want to work with the single item list, not the >> zipped one >> fooselected = list(t[1] for t in foobarselected) >> >> However, it would be nice to have a function combining the last two >> instructions. Something like >> itertools.ifilterother(bar, foo) -> yield iterator with items from foo >> where bar is true > > I think it's a good approach to keep the number of primitives low. I find > the list comprehension combined with izip() quite readable: > > [v for f, v in izip(bar, foo) if not f(v)] > > Peter If you want an iterator without requiring making a list, you can simply use parentheses instead of brackets: agenerator = (v for f, v in izip(bar, foo) if not f(v)) This is perfectly lazy but not immune to problems when foo or bar is changed before the generator is fully consumed. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From christophedeze at gmail.com Mon Dec 22 13:37:56 2008 From: christophedeze at gmail.com (Toff) Date: Mon, 22 Dec 2008 10:37:56 -0800 (PST) Subject: join a samba domain References: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> <494fd597$0$90267$14726298@news.sunsite.dk> Message-ID: <73194a24-f14e-46f1-8789-886ba4729084@r15g2000prd.googlegroups.com> On 22 d?c, 18:59, Jens Henrik Leonhard Jensen wrote: > Toff wrote: > > ? ?d = c.Win32_ComputerSystem > > ? ?d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") > > Shouldn't r"admin\\mydom" be "admin\\mydom" or r"admin\mydom". > Or maybe just "admin" > > /Jens Henrik you are right but i've got the same error. From bdesth.quelquechose at free.quelquepart.fr Thu Dec 4 15:30:10 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 Dec 2008 21:30:10 +0100 Subject: Why shouldn't you put config options in py files In-Reply-To: References: Message-ID: <49384b8c$0$14451$426a74cc@news.free.fr> HT a ?crit : > A colleague of mine is arguing that since it is easy to write config like: > > FOO = {'bar': ('a': 'b'), 'abc': ('z': 'x')} > > in config.py and just import it to get FOO, but difficult to achieve the > same using an ini file and ConfigParser, and since Python files are just > text, we should just write the config options in the Python file and > import it. > > I can think of lots of arguments why this is a bad idea, but I don't > seem to be able to think of a really convincing one. > > Anyone? Well... Depends on who is writing these config files and how they are used. But at least one major Python software (namely Django) uses .py setting files, and a Python developper I'm grateful they do - this greatly simplifies my job. From jonanin at gmail.com Wed Dec 10 00:13:36 2008 From: jonanin at gmail.com (Jon Morton) Date: Tue, 9 Dec 2008 21:13:36 -0800 (PST) Subject: Best way to report progress at fixed intervals References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> <817384d5-5f68-4c1f-9560-0bc7b7d2b1e3@v5g2000prm.googlegroups.com> Message-ID: <14672e99-00bf-4f6b-bed7-afa7a02dc629@g38g2000yqn.googlegroups.com> I think there is something I've run into, and it will only ever get _loaded_ once. See below for sour output of an easy example case of my problem. The wxPython lib is big, so it may have bugs, but pySer l and pure python (no C/C++ directly, event thought it uses os.open/ close & termios that themselves use mistaking)) and I see nothing that could cause this. I used the "ps" command to see the memory usage recipe that I found that counts the number of objects. To test them just run each example and run "ps python" once in a few days. This is probably just bias from my last programming environment, though. From mrkafk at gmail.com Mon Dec 29 09:52:07 2008 From: mrkafk at gmail.com (mk) Date: Mon, 29 Dec 2008 15:52:07 +0100 Subject: multiprocessing vs thread performance Message-ID: Hello everyone, After reading http://www.python.org/dev/peps/pep-0371/ I was under impression that performance of multiprocessing package is similar to that of thread / threading. However, to familiarize myself with both packages I wrote my own test of spawning and returning 100,000 empty threads or processes (while maintaining at most 100 processes / threads active at any one time), respectively. The results I got are very different from the benchmark quoted in PEP 371. On twin Xeon machine the threaded version executed in 5.54 secs, while multiprocessing version took over 222 secs to complete! Am I doing smth wrong in code below? Or do I have to use multiprocessing.Pool to get any decent results? # multithreaded version #!/usr/local/python2.6/bin/python import thread import time class TCalc(object): def __init__(self): self.tactivnum = 0 self.reslist = [] self.tid = 0 self.tlock = thread.allocate_lock() def testth(self, tid): if tid % 1000 == 0: print "== Thread %d working ==" % tid self.tlock.acquire() self.reslist.append(tid) self.tactivnum -= 1 self.tlock.release() def calc_100thousand(self): tid = 1 while tid <= 100000: while self.tactivnum > 99: time.sleep(0.01) self.tlock.acquire() self.tactivnum += 1 self.tlock.release() t = thread.start_new_thread(self.testth, (tid,)) tid += 1 while self.tactivnum > 0: time.sleep(0.01) if __name__ == "__main__": tc = TCalc() tstart = time.time() tc.calc_100thousand() tend = time.time() print "Total time: ", tend-tstart # multiprocessing version #!/usr/local/python2.6/bin/python import multiprocessing import time def testp(pid): if pid % 1000 == 0: print "== Process %d working ==" % pid def palivelistlen(plist): pll = 0 for p in plist: if p.is_alive(): pll += 1 else: plist.remove(p) p.join() return pll def testp_100thousand(): pid = 1 proclist = [] while pid <= 100000: while palivelistlen(proclist) > 99: time.sleep(0.01) p = multiprocessing.Process(target=testp, args=(pid,)) p.start() proclist.append(p) pid += 1 print "=== Main thread waiting for all processes to finish ===" for p in proclist: p.join() if __name__ == "__main__": tstart = time.time() testp_100thousand() tend = time.time() print "Total time:", tend - tstart From invalid at invalid Mon Dec 22 16:02:37 2008 From: invalid at invalid (Grant Edwards) Date: Mon, 22 Dec 2008 15:02:37 -0600 Subject: Check file is References: <7caa7d45-ebbe-4c88-bb50-2f01f7315d07@s9g2000prg.googlegroups.com> Message-ID: On 2008-12-20, Harish wrote: > Is there any utility in python which will help me to read any > pdf files? There are two things I can think off the top of my head 1) The Poppler library. I don't know if there's a Python binding for it. The poppler home page and Wikipedia page would probably be a good place to start reading. 2) Qoppa Software has some Java PDF libraries that you could probably use with Jython. -- Grant Edwards grante Yow! Did I do an INCORRECT at THING?? visi.com From andrew.gregory at npl.co.uk Fri Dec 19 10:14:47 2008 From: andrew.gregory at npl.co.uk (andrew.gregory at npl.co.uk) Date: Fri, 19 Dec 2008 07:14:47 -0800 (PST) Subject: Tix.Balloon crashes in Python 2.61 Windows Message-ID: I've found that Tix GUI applications crash after switching to Python 2.6.1 (Windows XP) when Balloons are used. IDLE gives this error message: Traceback (most recent call last): File "D:\PyFiles\InstrumentSetup\Automenu.py", line 217, in else: displayedwidget=MainWidget(root, CS) File "D:\PyFiles\InstrumentSetup\Automenu.py", line 155, in __init__ b = Tix.Balloon(MyFrame) File "C:\Python26\lib\lib-tk\Tix.py", line 529, in __init__ TixWidget.__init__(self, master, 'tixBalloon', static, cnf, kw) File "C:\Python26\lib\lib-tk\Tix.py", line 307, in __init__ self.tk.call(widgetName, self._w, *extra) TclError: unknown color name "{#ffff60}" A Windows message box came up also. It gave the message: The exception unknown exception (0x40000015) occurred in the application at location 0x1e03a63b Perhaps Tix.Balloon has been omitted from the test suite? I tried searching but cannot see this reported elsewhere. Can anyone else confirm this behaviour? Where is the best place to report this bug? I can supply a script demonstrating the problem. Andrew. From jon at ffconsultancy.com Sun Dec 7 12:39:30 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Sun, 07 Dec 2008 17:39:30 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: Xah Lee wrote: > I didn't realize until after a hour, that if Jon simply give numerical > arguments to Main and Create, the result timing by a factor of 0.3 of > original. What a incredible sloppiness! and he intended this to show > Mathematica speed with this code? > > The Main[] function calls Create. The create has 3 parameters: level, > c, and r. The level is a integer for the recursive level of > raytracing . The c is a vector for sphere center i presume. The r is > radius of the sphere. His input has c and r as integers, and this in > Mathematica means computation with exact arithmetics (and automatic > kicks into infinite precision if necessary). Changing c and r to float > immediately reduced the timing to 0.3 of original. That is only true if you solve a completely different and vastly simpler problem, which I see you have (see below). > The RaySphere function contain codes that does symbolic computation by > calling Im, which is the imaginary part of a complex number!! and if > so, it returns the symbol Infinity! The possible result of Infinity is > significant because it is used in Intersect to do a numerical > comparison in a If statement. So, here in these deep loops, > Mathematica's symbolic computation is used for numerical purposes! Infinity is a floating point number. > So, first optimization at the superficial code form level is to get > rid of this symbolic computation. That does not speed up the original computation. > Instead of checking whethere his ?disc = Sqrt[b^2 - v.v + r^2]? has > imaginary part, one simply check whether the argument to sqrt is > negative. That does not speed up the original computation. > after getting rid of the symbolic computation, i made the RaySphere > function to be a Compiled function. That should improve performance but the Mathematica remains well over five orders of magnitude slower than OCaml, Haskell, Scheme, C, C++, Fortran, Java and even Lisp! > Besides the above basic things, there are several aspects that his > code can improve in speed. For example, he used pattern matching to do > core loops. > e.g. Intersect[o_, d_][{lambda_, n_}, Bound[c_, r_, s_]] > > any Mathematica expert knows that this is something you don't want to > do if it is used in a core loop. Instead of pattern matching, one can > change the form to Function and it'll speed up. Your code does not implement this change. > Also, he used ?Block?, which is designed for local variables and the > scope is dynamic scope. However the local vars used in this are local > constants. A proper code would use ?With? instead. (in lisp, this is > various let, let*. Lispers here can imagine how lousy the code is > now.) Earlier, you said that "Module" should be used. Now you say "With". Which is it and why? Your code does not implement this change either. > Here's a improved code. The timing of this code is about 0.2 of the > original. > ... > Timing[Export["image.pgm",Graphics at Raster@Main[2,100,4.]]] You have only observed a speedup because you have drastically simplified the scene being rendered. Specifically, the scene I gave contained over 80,000 spheres but you are benchmarking with only 5 spheres and half of the image is blank! Using nine levels of spheres as I requested originally, your version is not measurably faster at all. Perhaps you should give a refund? -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From stephen.thorne at gmail.com Fri Dec 12 05:49:48 2008 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Fri, 12 Dec 2008 20:49:48 +1000 Subject: Removing None objects from a sequence In-Reply-To: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> Message-ID: <20081212104948.GA3254@thorne.id.au> On 2008-12-12, Filip Gruszczy?ski wrote: > Hi! > > I would like to iterate over a sequence nad ignore all None objects. > The most obvious way is explicitly checking if element is not None, > but it takes too much space. And I would like to get something faster. > I can use > [ sth for sth in self.__sth if not sth is None ], but I don't know if > that's the best way. I checked itertools, but the only thing that > seemed ok, was ifilter - this requires seperate function though, so > doesn't seem too short. How can I get it the shortest and fastest way? There's a little hack that will remove all elements from a list that are 'False' when considered as a boolean. So None, [], '', False, etc. filter(None, myseq) an example: >>> l = ['1', 2, 0, None, '5'] >>> filter(None, l) ['1', 2, '5'] -- Regards, Stephen Thorne Development Engineer NetBox Blue - 1300 737 060 Scanned by the NetBox from NetBox Blue (http://netboxblue.com/) Can you afford to be without a NetBox? Find out the real cost of internet abuse with our ROI calculator. http://netboxblue.com/roi Scanned by the NetBox from NetBox Blue (http://netboxblue.com/) From kermit.mei at gmail.com Mon Dec 8 00:44:09 2008 From: kermit.mei at gmail.com (Kermit Mei) Date: Mon, 08 Dec 2008 13:44:09 +0800 Subject: A question about reference in Python. In-Reply-To: <47c890dc0812072136v4e36dc1crbf0c913760f477d4@mail.gmail.com> References: <493CB003.3080209@gmail.com> <47c890dc0812072136v4e36dc1crbf0c913760f477d4@mail.gmail.com> Message-ID: <493CB429.2050103@gmail.com> Chris Rebert wrote: > On Sun, Dec 7, 2008 at 9:26 PM, Group wrote: > >> Hello, I'm studying algorithom. For concentrating on the question itself, I >> intend to use Python to implement the algorithoms. >> >> Now, I want to write a Red-Black Tree, and a List structure. In C/C++, I can >> use pointers to refer to children notes (or next notes). But, in Python, >> how >> can I do it? Except the sequence, I know not any way. >> >> You'd better help me understan how can I transform the following C code into >> Python: >> >> /* a List */ >> struct { >> int data; >> int *next; >> int *prev; >> } >> > > Possibly not an exact literal translation, but: > > class ListNode(object): > def __init__(self, data, prev=None, next=None) > self.data = data > self.prev = prev > self.next = next > > > Keep in mind that Python uses call-by-object (google it), so it > doesn't have pointers/references per-se. > > Cheers, > Chris > Yes, I see. Thank you, very much! From rogerpack2005 at gmail.com Fri Dec 26 20:19:23 2008 From: rogerpack2005 at gmail.com (rogerdpack) Date: Fri, 26 Dec 2008 17:19:23 -0800 (PST) Subject: ruby -> python translator exists? Message-ID: <04b51f42-e18e-4902-8a98-38f0538c1eda@s9g2000prg.googlegroups.com> Hi all. My name is Roger. Anyway question. Anybody know of a Ruby -> Python translator at all? I'm looking for a way to have my Ruby code take advantage of the coolio speed of Psyco. Also question. Does psyco work with Python 3.0? Thanks! -=r From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 23 04:03:36 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 23 Dec 2008 10:03:36 +0100 Subject: Are Django/Turbogears too specific? In-Reply-To: References: Message-ID: <4950a963$0$32051$426a74cc@news.free.fr> Daniel Fetchinson a ?crit : (snip) > The 1.x branch of tg is built on cherrypy, the 2.x branch is built on > pylons. Both branches depend on external packages for most of their > functionality which makes them very flexible. Django is monolithic Except that 1/ you can use each component (request handler/dispatcher, templating system and ORM) standalone, and 2/ you can use any other ORM or templating system. > and was intended to be monolithic. "highly integrated" would be more accurate than "monolithic" IMHO. > Of course you can customize it and use > different components than the defaults, but after all *everything* is > customizable since the source code is there and you can modify it. You don't need to touch the source to swap ORM or templating system. > The > point is that tg was designed with flexibility and customizability in > mind, while django was designed with a monolithic infrastructure in > mind. s/monolithic/integrated/ From python at bdurham.com Wed Dec 24 03:23:00 2008 From: python at bdurham.com (python at bdurham.com) Date: Wed, 24 Dec 2008 03:23:00 -0500 Subject: Strategy for determing difference between 2 very large dictionaries In-Reply-To: References: <1230102996.2303.1291616055@webmail.messagingengine.com> Message-ID: <1230106980.12156.1291620725@webmail.messagingengine.com> Hi Gabriel, Thank you very much for your feedback! > k1 = set(dict1.iterkeys()) I noticed you suggested .iterkeys() vs. .keys(). Is there any advantage to using an iterator vs. a list as the basis for creating a set? I understand that an iterator makes sense if you're working with a large set of items one at a time, but if you're creating a non-filtered collection, I don't see the advantage of using an iterator or a list. I'm sure I'm missing a subtle point here :) >> can this last step be done via a simple list comprehension? > Yes; but isn't a dict comprehension more adequate? > > [key: (dict1[key], dict2[key]) for key in common_keys if > dict1[key]!=dict2[key]} Cool!! I'm relatively new to Python and totally missed the ability to work with dictionary comprehensions. Yes, your dictionary comprehension technique is much better than the list comprehension approach I was struggling with. Your dictionary comprehension statement describes exactly what I wanted to write. Regards, Malcolm ----- Original message ----- From: "Gabriel Genellina" To: python-list at python.org Date: Wed, 24 Dec 2008 05:46:04 -0200 Subject: Re: Strategy for determing difference between 2 very large dictionaries En Wed, 24 Dec 2008 05:16:36 -0200, escribi?: > I'm looking for suggestions on the best ('Pythonic') way to > determine the difference between 2 very large dictionaries > containing simple key/value pairs. > By difference, I mean a list of keys that are present in the > first dictionary, but not the second. And vice versa. And a list > of keys in common between the 2 dictionaries whose values are > different. > The 2 strategies I'm considering are: > 1. Brute force: Iterate through first dictionary's keys and > determine which keys it has that are missing from the second > dictionary. If keys match, then verify that the 2 dictionaries > have identical values for the same key. Repeat this process for > the second dictionary. > 2. Use sets: Create sets from each dictionary's list of keys and > use Python's set methods to generate a list of keys present in > one dictionary but not the other (for both dictionaries) as well > as a set of keys the 2 dictionaries have in common. I cannot think of any advantage of the first approach - so I'd use sets. k1 = set(dict1.iterkeys()) k2 = set(dict2.iterkeys()) k1 - k2 # keys in dict1 not in dict2 k2 - k1 # keys in dict2 not in dict1 k1 & k2 # keys in both > Using the set > of keys in common, compare values across dictionaries to > determine which keys have different values (can this last step be > done via a simple list comprehension?) Yes; but isn't a dict comprehension more adequate? [key: (dict1[key], dict2[key]) for key in common_keys if dict1[key]!=dict2[key]} (where common_keys=k1&k2 as above) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list From jpablo.romero at gmail.com Tue Dec 16 18:48:13 2008 From: jpablo.romero at gmail.com (=?ISO-8859-1?Q?Juan_Pablo_Romero_M=E9ndez?=) Date: Tue, 16 Dec 2008 17:48:13 -0600 Subject: eval() and global variables Message-ID: Hello, Suppose this function is given: def f(x,y): return x+y+k Is it possible to somehow assign a value to k without resorting to making k global? I'm thinking something like this: eval("f(1,1)", {"f":f, "k":1}) Or even better, something like: def g(k): return f g(1)(1,1) ==> 3 Regards, Juan Pablo From rdcollum at gmail.com Mon Dec 29 16:01:33 2008 From: rdcollum at gmail.com (Roger) Date: Mon, 29 Dec 2008 13:01:33 -0800 (PST) Subject: tkInter constraining the width only References: Message-ID: <2d06d584-f398-4bf2-9452-bc2d915b1d17@k19g2000yqg.googlegroups.com> On Dec 29, 3:23?pm, akineko wrote: > Hello everyone, > > I'm writing a Tkinter program and trying to constraint the window > size. > I want to set the minimum of the width and the height and the maximum > of the width, but not the height. You want to set the max height to 0. I know this is counter- intuitive. Both values must be a number or None, not mixed. So to do what you want to do it would be this: some_window.wm_minsize(width=min_width, height=min_height) some_window.wm_maxsize(width=max_width, height=0) Note that these numbers are in pixels if you're using .pack() and according to the docs it's in grid coordinates if you're using .grid() Good luck! Roger. From timr at probo.com Tue Dec 16 02:23:02 2008 From: timr at probo.com (Tim Roberts) Date: Tue, 16 Dec 2008 07:23:02 GMT Subject: os.environ.get('SSH_ORIGINAL_COMMAND') returns None References: Message-ID: Tzury Bar Yochay wrote: > >added to ~/.ssh/authorized_keys the command="my_parder" parameter >which point to a python script file named 'my_parser' and located in / >usr/local/bin (file was chmoded as 777) > >in that script file '/usr/local/bin/my_parser' I got the following >lines: > >#!/usr/bin/env python >import os >print os.environ.get('SSH_ORIGINAL_COMMAND', None) > >When trying to ssh e.g. 'ssh localhost' >I get None on the terminal and then the connection is closed. > >I wonder if anyone have done such or alike in the past and can help me >with this. >Is there anything I should do in my python file in order to get that >environment variable? The SSH_ORIGINAL_COMMAND variable is set to the command that was passed in on the ssh command line. Since you are not specifying a command, you aren't going to find anything in that variable. Try this: ssh localhost 'ls -l' -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From kyosohma at gmail.com Tue Dec 23 12:12:11 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 23 Dec 2008 09:12:11 -0800 (PST) Subject: wxPython.button.disabled still catching clicks References: <8cb6da6a-7df4-4cce-a28e-385448a25b26@w39g2000prb.googlegroups.com> <1ff2aad7-29a1-48cd-b3de-29fab443aa3e@u18g2000pro.googlegroups.com> <0e9a5ab7-8078-4d12-adb2-aaf92a78b007@s9g2000prm.googlegroups.com> Message-ID: On Dec 23, 7:27?am, mynthon wrote: > On Dec 23, 11:58?am, Aaron Brady wrote: > > > > > On Dec 23, 4:50?am, mynthon wrote: > > > > Hello! (sorry for my english) > > > > I have a problem with buttons in wxPython. When button is disabled > > > (by .Disable() or .Enable(False)) it is grayed out but still receive > > > clicks. > > > > Eg. i have button that disable itself, runs long action and enable > > > itself: > > > > def onClick(self, evt): > > > ? ? self.btn.Enable(False) > > > ? ? for i in range (1000): > > > ? ? ? ? print i > > > ? ? self.btn.Enable(True) > > > > when for loop is running button is greyed out and when i click on it > > > nothing happens but when loop ends another one is started because > > > button "remebered" thad i click on it when was diabled. My only idea > > > is to reposition button outside frame instead of disabling it but this > > > solution is...not good. > > > > thanks for any help. Ive searched groups, google and it looks that > > > only i have this problem :) > > > No, it is very common. ?During your for loop, the loop is dominating > > the process completely. ?Events are just building up in the app's > > message queue, and don't get handled until after you yield on control. > > > If you need to run a long task, look into threading, the OnIdle > > method, the 'multiprocessing' module, or pump messages during your > > long task. > > ok, maybe someone will need it. I dont know how it works because i > didnt have time to read docs and i cannot explain everything. I used > google and wxPython demo (in tree: wxpython overview / process and > events / process) > > class leftPanel(wx.Panel): > ? ? def __init__(self, parent, id): > ? ? ? ? wx.Panel.__init__(self, parent, id, style=wx.BORDER_SUNKEN) > > ? ? ? ? # here you have to define new process, IDLE event, and > onPRocessEnd event > ? ? ? ? self.process = None > ? ? ? ? self.GetParent().Bind(wx.EVT_IDLE, self.onIdle) > ? ? ? ? self.Bind(wx.EVT_END_PROCESS, self.onProcessEnd) > > ? ? ? ? # create button and bind event to it > ? ? ? ? self.runScriptBtn = wx.Button(self, -1, 'RUN ME!', (10,220)) > ? ? ? ? self.runScriptBtn.Bind(wx.EVT_BUTTON, self.onClick, > self.runScriptBtn) > > ? ? def onClick(self, evt): > ? ? ? ? # disable button > ? ? ? ? self.runScriptBtn.Enable(False) > > ? ? ? ? # here you have to enter command to run > ? ? ? ? # previusly i heve here exec('python myScript.py') > ? ? ? ? # but now it will be a subprocess > ? ? ? ? cmd = 'python xxx1.py' > > ? ? ? ? #create new process > ? ? ? ? self.process = wx.Process(self) > > ? ? ? ? # dont know what it is for > ? ? ? ? self.process.Redirect() > > ? ? ? ? # execute cmd command > ? ? ? ? pid = wx.Execute(cmd, wx.EXEC_ASYNC, self.process) > > ? ? def onIdle(self, evt): > ? ? ? ? # beacuse this method is called only when app enters idle mode > ? ? ? ? # the line below is nedded to "simulate" entering idle mode > ? ? ? ? # dont know how it works but it works > ? ? ? ? evt.RequestMore(True) > > ? ? ? ? # here is some code to catch subprocess output > ? ? ? ? if self.process is not None: > ? ? ? ? ? ? stream = self.process.GetInputStream() > ? ? ? ? ? ? if stream.CanRead(): > ? ? ? ? ? ? ? ? text = stream.read() > ? ? ? ? ? ? ? ? print text > > ? ? def onProcessEnd(self, evt): > ? ? ? ? # here is some code to catch subprocess output > ? ? ? ? # when it is destroyed > ? ? ? ? stream = self.process.GetInputStream() > ? ? ? ? if stream.CanRead(): > ? ? ? ? ? ? text = stream.read() > ? ? ? ? ? ? print text > > ? ? ? ? # dont know it is necessary > ? ? ? ? self.process.CloseOutput() > > ? ? ? ? # remove (clear) process object > ? ? ? ? self.process.Destroy() > ? ? ? ? self.process = None > > ? ? ? ? # show button again > ? ? ? ? self.runScriptBtn.Enable() I'm pretty sure there's a better way to do this. If you disable the button and click on it, you'll notice that it isn't firing events, so something else is going on here. It seems like the wx.Frame or wx.Application is queuing the mouse button clicks or something. I would post to the wxPython mailing list: http://wxpython.org/maillist.php They'll be better able to address this and they'll probably have a simpler solution too. Mike From deets at nospam.web.de Mon Dec 8 16:49:57 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 Dec 2008 22:49:57 +0100 Subject: Public imports In-Reply-To: <66ecdd96-38dd-4054-8009-e145c0a78316@o40g2000prn.googlegroups.com> References: <9623b0a3-7053-41f1-b116-0cd5e54f39e9@v13g2000vbb.googlegroups.com> <493d1ec0$0$32048$426a34cc@news.free.fr> <66ecdd96-38dd-4054-8009-e145c0a78316@o40g2000prn.googlegroups.com> Message-ID: <6q5j45Faq0g7U2@mid.uni-berlin.de> M?rcio Faustino schrieb: > So, no chance of doing this: > > # "A.py" > from __future__ import division, with_statement > > # "B.py" > from A import * > print 1 / 2 > > ...and printing 0.5, right? Too bad :) Au contraire - *very* good. If it were otherwise, what would happen to code that _relies_ on / returning an int - some 3rd-party-lib for example? The same goes for code that contains "with" as variable name or some such. Diez From bearophileHUGS at lycos.com Fri Dec 19 12:55:01 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 19 Dec 2008 09:55:01 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> r: > I always thought of Python as an intuitive way to write C code.< C is a very low level language, not far from assembly, and often it's not intuitive at all. C string formatting is short and a flexible enough, but it's out of place in a language as high level as Python3. The new syntax allows more flexibility, and it's better for most people that don't know C already, like newbies, etc. ------------------ walterbyrd: >It seems to me that 3.0 is changing a lot of non-problems. And it's going to be slower to boot.< They are non-problems for people that already know lot of Python (and some C). But for all the other people, especially newbies, it's better in most things. Most language designers (and generally people very used a certain language) become so accustomed to their language that they most of the times become like "blind" to the defects and warts of their language (I have said this four years ago too, when I have started learning Python, listing many problems in Python, and among them there were C string formatting too). So I think it was a feat for the Python developers to see many characteristics of the Python2.x as what they are: warts, bugs, etc, and fix them (and most of the times their newer designs are "the right thing" with just few exceptions, I have counted only 3 of them, and they are small). They have gained even more of my respect. Regarding the speed of Python3 programs, they will go faster because people will be forced to use things like lazy ranges, lazy map and filter, lazy keys and values, and the "key" of sort/sorted. All those things can be used in Python2.x too, but lot of people aren't expert enough (or they are just lazy) and don't use them, so the average Python3 program will probably be faster (and use less memory) thanks to them. Python3 programs will go slower because they use 2-byte long Unicode strings by default (it can be compiled for 4-byte Unicode too, and I think this has to become the default, eventually, because I think it will become silly to save few bytes for strings when you will have 8-16-32+ GB of RAM), and they use multi-precision integers only. Such strings and numbers allow to reduce some troubles, even "bugs", etc. At the moment Python3 isn't much optimized for speed, you can think of it an experimental release still. I/O and multiprecision integers will probably be speed up (and some form of transparent on-the-fly compression or smart representation can in most times halve the memory used by Py3 strings, putting the performance almost back to the Py2.x one. In computer science there are LOT of tricks that can be used if you have the brain and time to invent and implement them. You can see that for example in how Psyco manages internally string/list/tuple slices). Anyway, CPUs and computers are now much faster than the CPUs present when Python was created. And Python is first of all designed for the programmer and not for the CPU. So I think it's right to make Python3 become a little higher level language even if this slows it down a little. For the kind of programs Python is often used for, I think this is a Win. (Ruby programs are often slower than Python ones (because Ruby is a little higher level than Python) but it's very useful anyway). If Python will continue to develop in the following years (think about a Python4000) then I think it may become good to make it become even more slower, if this will help make it a little more higher level still. Bye, bearophile From arnodel at googlemail.com Tue Dec 23 03:54:41 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 23 Dec 2008 08:54:41 +0000 Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: skip at pobox.com writes: > If you look back at the Tour de France results from the 80's I > believe Greg Lemond won it one year without ever winning a stage. Well I think it was actually in 1990, his last win sadly. -- Arnaud From exarkun at divmod.com Tue Dec 30 15:22:07 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 30 Dec 2008 15:22:07 -0500 Subject: Triple quoted string in exec function ? In-Reply-To: <495A81A7.8030507@gmail.com> Message-ID: <20081230202207.20272.1714261156.divmod.quotient.29322@ohm> On Tue, 30 Dec 2008 21:16:39 +0100, Stef Mientki wrote: >ibpet11 at gmail.com wrote: >>On Dec 30, 2:48 pm, Steve Holden wrote: >> >>>Stef Mientki wrote: >>> >>>>hello, >>>> I'm running scripts, with the execute function (Python 2.5), >>>>and it seems that triple quoted strings are not allowed. >>>> Is there a workaround, >>>>or is this a fundamental problem of the exec-function ? >>>> >>>If you think about it, it should be obvious that you can't surround a >>>string to be compiled with any of the quotes that appear inside the >>>string to be compiled. That's about the only limitation I am aware of. >>> >>>And, by the way, exec is a *statement*, not a function! >>> > exec ( Init_Code, PG.P_Globals ) > >I've really doubt that this is a statement, >unless I don't understand what a statement is. What do you think a statement is? According to the Python grammar, exec is this: exec_stmt: 'exec' expr ['in' test [',' test]] "stmt" is short for "statement". :) A more satisfying demonstration of the statementness of exec is this, though: >>> x = exec "foo" File "", line 1 x = exec "foo" ^ SyntaxError: invalid syntax >>> And no, putting parenthesis around the expression given to exec doesn't make a difference: >>> x = exec("foo") File "", line 1 x = exec("foo") ^ SyntaxError: invalid syntax >>> Jean-Paul From george.sakkis at gmail.com Thu Dec 4 14:19:53 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 4 Dec 2008 11:19:53 -0800 (PST) Subject: Python 3 read() function References: Message-ID: On Dec 4, 2:01?pm, ?????? ??????????? wrote: > > I don't think it matters. ?Here's a quick comparison between 2.5 and > > 3.0 on a relatively small 17 meg file: > > > C:\>c:\Python30\python -m timeit -n 1 > > "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" > > 1 loops, best of 3: 36.8 sec per loop > > > C:\>c:\Python25\python -m timeit -n 1 > > "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" > > 1 loops, best of 3: 33 msec per loop > > > That's 3 orders of magnitude slower on python3.0! > > Isn't this because you have the file cached in memory on the second run? That's probably it; I see much more modest slowdown (2-3X) if I repeat many times each run. George From fakeaddress at nowhere.org Tue Dec 2 21:16:13 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 02 Dec 2008 18:16:13 -0800 Subject: Reverse zip() ? In-Reply-To: References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> Message-ID: John Machin wrote: > Here's a version that makes it slightly easier to comprehend: > > Q: I know how to zip sequences together: > | >>> a = (1, 2, 3) > | >>> b = (4, 5, 6) > | >>> z = zip(a, b) > | >>> z > | [(1, 4), (2, 5), (3, 6)] > but how do I reverse the process? > > A: Use zip()! > | >>> a2, b2 = zip(*z) > | >>> a2 > | (1, 2, 3) > | >>> b2 > | (4, 5, 6) zip as its own inverse might be even easier to comprehend if we call zip by its more traditional name, "transpose". -- --Bryan From cma at mail.bnu.edu.cn Thu Dec 4 04:39:15 2008 From: cma at mail.bnu.edu.cn (Cong Ma) Date: Thu, 04 Dec 2008 17:39:15 +0800 Subject: Don't you just love writing this sort of thing :) In-Reply-To: References: Message-ID: Lawrence D'Oliveiro wrote: > for \ > Entry \ > in \ > sorted \ > ( > f for f in os.listdir(PatchesDir) if PatchDatePat.search(f) != None > ) \ > : > Patch = (open, gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir, Entry), "r") > ... read from Patch ... > Patch.close() > #end for > > -- > http://mail.python.org/mailman/listinfo/python-list > The "if ... != None" is not necessary... "if PatchDatePat.search(f)" is OK. And I don't like it... From jstroud at mbi.ucla.edu Thu Dec 4 03:59:00 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 04 Dec 2008 00:59:00 -0800 Subject: How can I do this (from Perl) in Python? (closures) In-Reply-To: <68b8294c-8771-4b02-bd46-2f25f5e01602@j35g2000yqh.googlegroups.com> References: <68b8294c-8771-4b02-bd46-2f25f5e01602@j35g2000yqh.googlegroups.com> Message-ID: excord80 at gmail.com wrote: > from_ten = make_counter(10) > from_three = make_counter(3) > > print from_ten() # 10 > print from_ten() # 11 > print from_three() # 3 > print from_ten() # 12 > print from_three() # 4 > #################### > > The error message is: "UnboundLocalError: local variable 'start' > referenced before assignment". The same thing happens if I omit start > and just use start_num directly. > > How can I do it in Python? Since no one has suggested it: class make_counter(object): def __init__(self, i): self.i = i def __call__(self): i = self.i self.i += 1 return i James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From rdmurray at bitdance.com Tue Dec 9 22:05:40 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Tue, 9 Dec 2008 22:05:40 -0500 (EST) Subject: Text parsing via regex In-Reply-To: References: Message-ID: On Mon, 8 Dec 2008 at 16:51, Robert Kern wrote: > Robocop wrote: >> Wow! Thanks for all the input, it looks like that textwrapper will >> work great for my needs. And thanks for the regex help everyone. >> Also, i was thinking of using a list, but i haven't used them much in >> python. Is there anything in python that is equivalent to pushback in >> c++ for vectors? > > list.append() Fun with lists: >>> l = list() >>> l.append('a') >>> l ['a'] >>> l.extend(['b', 'c']) >>> l ['a', 'b', 'c'] >>> l[1:] = [1, 2, 3] >>> l ['a', 1, 2, 3] >>> l.pop() 3 >>> l ['a', 1, 2] >>> l[:0] = ['z'] >>> l ['z', 'a', 1, 2] --RDM From google at mrabarnett.plus.com Tue Dec 16 12:50:15 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 16 Dec 2008 17:50:15 +0000 Subject: help I'm getting delimited In-Reply-To: <1229445534.5328.0.camel@linux-3eb6.site> References: <1229445534.5328.0.camel@linux-3eb6.site> Message-ID: <4947EA57.9060509@mrabarnett.plus.com> Paul Watson wrote: > On Tue, 2008-12-16 at 08:26 -0800, aka wrote: >> Hi, I'm going nuts over the csv.reader and UnicodeReader class. >> Somehow I can't get this method working which is supposed to read a >> csv file which name is inputted but here now hardcoded. What I need >> for now is that the string version of the list is put out for control. >> Later on I will only need to read the first column (id) of the csv >> file to be able to fill in a session var with a list of all ids. >> inp = c:/temp/test.csv >> roles = [] >> try: >> fp = open(inp, 'rb') >> reader = csv.reader(fp) >> for r in reader: >> rollen.append(r) >> except: >> msg = "Er is iets mis met de UnicodeReader" >> >> return dict(file=in,roles=str(roles)) >> Any help greatly appreciated! >> Cheers > > Did you intend inside the loop to write: > > roles.append(r) > Also, the bare "except" will catch _all_ exceptions. You should catch only those you expect. In this case, it's catching your use of "rollen" instead of "roles" (probably unintentional) and then complaining about UnicodeReader, even though that's (probably, again!) not the problem. From jaume.bonet at gmail.com Tue Dec 16 14:04:01 2008 From: jaume.bonet at gmail.com (Jaume Bonet) Date: Tue, 16 Dec 2008 11:04:01 -0800 (PST) Subject: Memory leak when using a C++ module for Python References: <13db1224-5d6d-4240-8184-ce852e10b422@d36g2000prf.googlegroups.com> Message-ID: <15733cb7-c520-40d7-bacd-3f4e18d5fe3c@u18g2000pro.googlegroups.com> When I tried the C++ function with a C++ main() (skipping the Python part) it didn't show any memory problem, but I'll re-check it anyway, thanks... On Dec 16, 9:16?am, "Gabriel Genellina" wrote: > En Thu, 11 Dec 2008 15:35:58 -0200, Jaume Bonet ? > escribi?: > > > This is the function that is visible from python and the one that the > > python code calls: > > > static PyObject * IMFind (PyObject *self, PyObject *args, PyObject > > *kwargs) { > > Your function does not call any Python function except ? > PyArg_ParseTupleAndKeywords (which does not modify reference counts). > So it's unlikely that this could cause any memory leak. I'd revise how ? > memory is allocated and deallocated on the C++ side. > > -- > Gabriel Genellina From castironpi at gmail.com Tue Dec 23 11:57:14 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 23 Dec 2008 08:57:14 -0800 (PST) Subject: On Whose Desktop References: <4950db7e$0$14770$426a74cc@news.free.fr> Message-ID: <89ca6cc9-fa26-42c9-be67-35aad569500b@i18g2000prf.googlegroups.com> On Dec 23, 8:19?am, Steve Holden wrote: > Fuzzyman wrote: > > On Dec 23, 12:06 pm, Steve Holden wrote: > >> Thanks to Barry Warsaw the "On Your Desktop" blog now has a new entry: > > >> ?http://onyourdesktop.blogspot.com/ > > >> Who would you like to see profiled next? > > > Guido (of course), Brett Cannon, Martin v Loewis, Jim Hugunin, Ted > > Leung, Dino Viehland (core developer of IronPython), Titus Brown, Ivan > > Kristic, Mark Shuttleworth, Tim Golden, Michele Simionato, Thomas > > Heller, Greg Ewing - any and all of these would be great. > > > Any women in Python you could ask - how about Anna Ravenscroft? > > Bruno Desthuilliers wrote: > > > The effbot ? > > s... at pobox.com wrote: > > Maybe Martin v. Loewis? ?He contributes so much to Python. ?I met him once > > several years ago at a Python conference (or maybe it was still just a > > workshop then), but beyond seeing his titanic contributions to Python, I > > know little about the guy. > > I hope *everyone* knows that Martin was the winner of this year's Frank > Willison Award: > > http://www.python.org/community/awards/frank-willison/#martin-von-l-w... > > Great! Keep the suggestions coming, please! +1 whose (posessive) From bearophileHUGS at lycos.com Mon Dec 15 18:24:13 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 15 Dec 2008 15:24:13 -0800 (PST) Subject: tricky nested list unpacking problem References: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> Message-ID: Arnaud Delobelle: > Here is a not thought out solution: >... I was waiting to answer because so far I have found a bad-looking solution only. Seeing there's only your solution, I show mine too. It seems similar to your one. def xflatten(seq): if isinstance(seq, list): stack = [iter(seq)] while stack: for item in stack[-1]: if isinstance(item, list): stack.append(iter(item)) break yield item else: stack.pop() else: yield seq def product(pools): if isinstance(pools, list): result = [[]] for pool in pools: if isinstance(pool, list): result = [x+[y] for x in result for y in xflatten(list (product(pool)))] else: result = [x+[pool] for x in result] for prod in result: yield prod else: yield pools s1 = [1,[2, 3, 4], 5,[6, 7]] s2 = [1,[2, [3, 4]], 5,[6,7],8,[9]] s3 = [1,2,3,[4,5,[6, 7]],8,[9,[10, 11, 12, 13, 14]]] def stringify(seq): for el in product(seq): yield "0-" + "-".join(map(str, el)) for seq in [s1, s2, s3]: for txt in stringify(seq): print txt print It's ugly, I agree. No much tested. *surely* there are shorter and much nicer solutions. It reminds me the exercises of the "Little Schemer" :-) Bye, bearophile From ndbecker2 at gmail.com Sat Dec 13 23:05:03 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Sat, 13 Dec 2008 23:05:03 -0500 Subject: subprocess to pipe through several processes? Message-ID: How would I use suprocess to do the equivalent of: cat - | program_a | program_b From fakeaddress at nowhere.org Mon Dec 22 22:50:40 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 22 Dec 2008 19:50:40 -0800 Subject: Twisted for non-networking applications In-Reply-To: <82e49b84-43c9-452f-a139-c77378c12908@a12g2000pro.googlegroups.com> References: <82e49b84-43c9-452f-a139-c77378c12908@a12g2000pro.googlegroups.com> Message-ID: Kottiyath wrote: > Is it a good idea to use Twisted inside my application, even though > it has no networking part in it? > Basically, my application needs lots of parallel processing - but I > am rather averse to using threads - With or without threads, the Python interpreter does not do parallel processing. You could use multiple processes, or a thread could call an extension module that releases Python's global interpreter lock, but Python itself does not offer parallel processing. > due to myraid issues it can cause. > So, I was hoping to use a reactor pattern to avoid the threads. The reactor pattern describes event-driven I/0, not parallel processing. -- --Bryan From nad at acm.org Fri Dec 5 14:46:47 2008 From: nad at acm.org (Ned Deily) Date: Fri, 05 Dec 2008 11:46:47 -0800 Subject: pytz and timezone specialists References: <1f6172c1-4f70-42ea-8010-b72beb0af487@w24g2000prd.googlegroups.com> Message-ID: In article <1f6172c1-4f70-42ea-8010-b72beb0af487 at w24g2000prd.googlegroups.com>, manatlan wrote: > Here is a really simple code : > ------------------------------------------------------- > from datetime import datetime > from pytz import timezone > > tz=timezone("Europe/Paris") > > d=datetime(2008,12,12,19,00,00,tzinfo=tz) > print d.isoformat() > > d=datetime.now(tz) > print d.isoformat() > ------------------------------------------------------- > when I run it, it displays (according current time ;-): > > 2008-12-12T19:00:00+00:09 > 2008-12-05T19:15:38.135467+01:00 > > The Europe/Paris timezone is GMT+1 ... the second date seems to be > right (+01:00 at the end) > > But why the first date ends with "+00:09" ?!? it should be +01:00 ... > no ?! > Where's the bug ?!? (sure : it's me ;-) ... but i don't understand > this simple thing) >>> tz = timezone("Europe/Paris") >>> d = tz.localize(datetime(2008,12,12,19,00,00)) >>> print d.isoformat() 2008-12-12T19:00:00+01:00 "This library only supports two ways of building a localized time. The first is to use the .localize() method provided by the pytz library. This is used to localize a naive datetime (datetime with no timezone information). ... Unfortunately using the tzinfo argument of the standard datetime constructors ''does not work'' with pytz for many timezones." -- Ned Deily, nad at acm.org From tjreedy at udel.edu Tue Dec 23 17:07:16 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Dec 2008 17:07:16 -0500 Subject: 2to3 used in the Shootout In-Reply-To: <4f1a8f03-fd7f-49ea-8031-61f73fb0c0e8@x16g2000prn.googlegroups.com> References: <4f1a8f03-fd7f-49ea-8031-61f73fb0c0e8@x16g2000prn.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > They have translated the Python benchmarks of the Shootout site from > Py2 to Py3 using 2to3: > > http://shootout.alioth.debian.org/u32/benchmark.php?test=all&lang=python3 > > It shows some "performance bugs" of Python3 itself (especially > regarding the binary-trees benchmark, that was unexpected by me), and > two points where 2to3 may be improved, for example after the > translation this gives error: > table=string.maketrans('ACBDGHK\nMNSRUTWVYacbdghkmnsrutwvy', > 'TGVHCDM > \nKNSYAAWBRTGVHCDMKNSYAAWBR')): > > Gives: > TypeError: maketrans arguments must be bytes objects Perhaps you could file a tracker item. From cadmuxe at gmail.com Tue Dec 9 03:05:58 2008 From: cadmuxe at gmail.com (cadmuxe) Date: Tue, 9 Dec 2008 00:05:58 -0800 (PST) Subject: Password input in console/terminal References: Message-ID: <36579eb6-df1e-4ab7-86b0-dde3f0235080@p2g2000prf.googlegroups.com> On 12?9?, ??2?01?, "Chris Rebert" wrote: > On Mon, Dec 8, 2008 at 9:53 PM, RP wrote: > > Hello All, > > > This is my first REAL post(question) to Python-List. I know I can take input > > from a user with raw_input() > > How do I take password input in console? Any Help would be Greatly > > Appreciated. Thank You. RP > > You use the appropriately-named `getpass` module:http://docs.python.org/library/getpass.html > > Cheers, > Chris > > -- > Follow the path of the Iguana...http://rebertia.com you can use getpass() import getpass passwd = getpass.getpass() ------- >>> import getpass >>> passwd = getpass.getpass() Password: From mirandasnailvv at gmail.com Fri Dec 19 19:42:02 2008 From: mirandasnailvv at gmail.com (mirandasnailvv at gmail.com) Date: Fri, 19 Dec 2008 16:42:02 -0800 (PST) Subject: tickling handjob video torrent - Free Message-ID: tickling handjob video torrent . . . *******CLICK HERE******** http://club247.cn/tickling-handjob-video-torrent ***************************** . . . . . . . . . . . . tickling handjob video torrent From xi at gamma.dn.ua Tue Dec 30 17:03:16 2008 From: xi at gamma.dn.ua (Kirill Simonov) Date: Wed, 31 Dec 2008 00:03:16 +0200 Subject: [ANN] PyYAML-3.08: Now with Python 3 support Message-ID: <495A9AA4.4050406@gamma.dn.ua> ======================== Announcing PyYAML-3.08 ======================== A new release of PyYAML is now available: http://pyyaml.org/wiki/PyYAML This release features complete support for Python 3. For compatibility notes between Python 2 and Python 3 versions, please see http://pyyaml.org/wiki/PyYAMLDocumentation#Python3support Changes ======= * Python 3 support (Thank to Erick Tryzelaar). * Use Cython instead of Pyrex to build LibYAML bindings. Note that the source package is distributed with a pre-generated '_yaml.c' file so you don't need Cython installed to build LibYAML bindings. * Refactored support for unicode and byte input/output streams. Resources ========= PyYAML homepage: http://pyyaml.org/wiki/PyYAML PyYAML documentation: http://pyyaml.org/wiki/PyYAMLDocumentation TAR.GZ package: http://pyyaml.org/download/pyyaml/PyYAML-3.08.tar.gz ZIP package: http://pyyaml.org/download/pyyaml/PyYAML-3.08.zip Windows installers: http://pyyaml.org/download/pyyaml/PyYAML-3.08.win32-py2.3.exe http://pyyaml.org/download/pyyaml/PyYAML-3.08.win32-py2.4.exe http://pyyaml.org/download/pyyaml/PyYAML-3.08.win32-py2.5.exe http://pyyaml.org/download/pyyaml/PyYAML-3.08.win32-py2.6.exe http://pyyaml.org/download/pyyaml/PyYAML-3.08.win32-py3.0.exe PyYAML SVN repository: http://svn.pyyaml.org/pyyaml Submit a bug report: http://pyyaml.org/newticket?component=pyyaml YAML homepage: http://yaml.org/ YAML-core mailing list: http://lists.sourceforge.net/lists/listinfo/yaml-core About PyYAML ============ YAML is a data serialization format designed for human readability and interaction with scripting languages. PyYAML is a YAML parser and emitter for Python. PyYAML features a complete YAML 1.1 parser, Unicode support, pickle support, capable extension API, and sensible error messages. PyYAML supports standard YAML tags and provides Python-specific tags that allow to represent an arbitrary Python object. PyYAML is applicable for a broad range of tasks from complex configuration files to object serialization and persistance. Example ======= >>> import yaml >>> yaml.load(""" ... name: PyYAML ... description: YAML parser and emitter for Python ... homepage: http://pyyaml.org/wiki/PyYAML ... keywords: [YAML, serialization, configuration, persistance, pickle] ... """) {'keywords': ['YAML', 'serialization', 'configuration', 'persistance', 'pickle'], 'homepage': 'http://pyyaml.org/wiki/PyYAML', 'description': 'YAML parser and emitter for Python', 'name': 'PyYAML'} >>> print yaml.dump(_) name: PyYAML homepage: http://pyyaml.org/wiki/PyYAML description: YAML parser and emitter for Python keywords: [YAML, serialization, configuration, persistance, pickle] Copyright ========= The PyYAML module is written by Kirill Simonov . PyYAML is released under the MIT license. From mal at egenix.com Wed Dec 10 14:44:45 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 10 Dec 2008 20:44:45 +0100 Subject: Rich Comparisons Gotcha In-Reply-To: <200812101401.35786.kyrie@uh.cu> References: <1228923619.493fe2e3c3073@comuh.uh.cu> <493FE561.6030007@egenix.com> <200812101401.35786.kyrie@uh.cu> Message-ID: <49401C2D.4050209@egenix.com> On 2008-12-10 20:01, Luis Zarrabeitia wrote: > On Wednesday 10 December 2008 10:50:57 am M.-A. Lemburg wrote: >> On 2008-12-10 16:40, Luis Zarrabeitia wrote: >>> Quoting Rasmus Fogh : >>>> Rhamphoryncus wrote: >> Rich comparisons were added to Python at the request of the >> Numeric (now numpy) developers and they have been part of Python >> a Numeric for many many years. >> >> I don't think it's likely they'll change things back to the days >> of Python 1.5.2 ;-) > > Please define "rich comparisons" for me. It seems that I do not understand the > term - I was thinking it meant the ability to override the comparison > operators, and specially, the ability to override them independently. That's one of the features, rich comparisons added. Another is the ability to return arbitrary objects instead of just booleans or integers: http://www.python.org/dev/peps/pep-0207/ David was a Numeric developer at the time (among other things). > Even in statically typed languages, when you override the equality > operator/function you can choose not to return a valid answer (raise an > exception). And it would break all the cases mentioned above (element in > list, etc). But that isn't the right thing to do. The language doesn't/can't > prohibit you from breaking the equality test, but that shouldn't be > considered a feature. (a==b).all() makes no sense. Perhaps not in your application, but it does make sense in other numeric applications, e.g. ones that work on vectors or matrixes. I'd suggest you simply wrap the comparison in a function and then have that apply the necessary conversion to a boolean. >>> Even the transition itself could be done without breaking much code... >>> Make the == op return an object that wraps the array of bools (instead of >>> the array itself), give it the any() and all() methods, and make >>> __nonzero__/__bool__ equivalent to all(). >> That would cause a lot of confusion on its own, since such an >> object wouldn't behave in the same way as say a regular Python >> list (bool([0]) == True). > > I'm certain that something could be worked out. A quick paragraph that took me > just a few minutes to type shouldn't be construed as a PEP that will solve > all the problems :D. As always: the Devil is in the details :-) -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 10 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-12-02: Released mxODBC.Connect 1.0.0 http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From james at agentultra.com Thu Dec 4 10:21:28 2008 From: james at agentultra.com (J Kenneth King) Date: Thu, 04 Dec 2008 10:21:28 -0500 Subject: RELEASED Python 3.0 final References: Message-ID: <85tz9k3r0n.fsf@dozer.localdomain> Barry Warsaw writes: > On behalf of the Python development team and the Python community, I > am happy to announce the release of Python 3.0 final. Yay! Thanks for all the great work. From ronen.agranat at gmail.com Sun Dec 14 05:32:41 2008 From: ronen.agranat at gmail.com (Rohannes) Date: Sun, 14 Dec 2008 02:32:41 -0800 (PST) Subject: 1 or 1/0 doesn't raise an exception References: <49446E39.6020807@tim.thechases.com> Message-ID: <6e2d11cd-a57e-4cd4-9cd7-a65eb08f220e@u18g2000pro.googlegroups.com> 'Dive into Python' has a very memorable and interesting section on the exact behaviour of 'and' and 'or' in Python: http://diveintopython.org/power_of_introspection/and_or.html > No: &, | (and ^, too) perform bitwise operations in Python, C and Java: "In complete evaluation ... both expressions are always evaluated. To obtain complete evaluation in Java, you use & rather than && ... and use | in place of ||" - Walter Savitch, Absolute Java 2nd ed. Although & IS the bitwise-AND operator in Java: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html I guess it's a matter of context. From thatiparthysreenivas at gmail.com Tue Dec 30 07:21:28 2008 From: thatiparthysreenivas at gmail.com (Sreenivas) Date: Tue, 30 Dec 2008 04:21:28 -0800 (PST) Subject: using def in pythons References: <235ffe4b-9f36-4d41-bee8-24cb4a69728d@q30g2000prq.googlegroups.com> Message-ID: On Dec 30, 3:37?pm, ibpe... at gmail.com wrote: > hi, > > i want to have a broad knowledge on the use of "def" in python as i > know i might need it > to my string handling and for a lot of things in general. > > I will really appreciate anybody who can support my mission of > becoming a python Programmer > as per constant chatting and support or manuals to read. > > thanks go through this link http://www.python.org/doc/2.5.1/ref/function.html From lie.1296 at gmail.com Wed Dec 10 09:45:26 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 10 Dec 2008 14:45:26 +0000 (UTC) Subject: Is 3.0 worth breaking backward compatibility? References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> Message-ID: On Tue, 09 Dec 2008 17:25:59 -0500, Benjamin Kaplan wrote: > On Tue, Dec 9, 2008 at 3:56 PM, Lie Ryan wrote: > >> On Sun, 07 Dec 2008 21:48:46 +0000, Tim Rowe wrote: >> >> > >> > But that's what a major release number does for you. Modula2 was >> > quite a break from Modula. Think of Python3.0 it as a new language, >> > if you like, that's inspired by Python2. You can stay with Python2 or >> > you can adopt the new language. That way you won't have to think of >> > it in terms of breaking any sort of backwards compatibility because >> > there is no backwards ;-) >> > >> > -- >> > Tim Rowe >> >> Actually I noticed a tendency from open-source projects to have slow >> increment of version number, while proprietary projects usually have >> big version numbers. >> >> Linux 2.x: 1991 Python 3.x.x: 1991. Apache 2.0: 1995. OpenOffice.org >> 3.0: acquired by Sun at 1999. GIMP 2.x: 1995. Wine 1.x: 1993. >> >> > Wine actually timed the 1.0 release to be at about t the 15th "birthday" > of the project. 15 years is a very long time to get to version 1.0, many other (usually commercial or commercial-oriented front of a software) software release version 1.0 after 2-3 years of development, often shorter. wine has been used by a lot of people, not only a few internal developers and beta testers. > >> Compare with >> Windows: NT 3.1-NT 6.x: 1993. Visual Studio 97, 6.0, .NET, .NET 2003, >> .NET 2005, 2008: 1997. Photoshop (11 versions to CS4): 1987. Microsoft >> Office 3, 4, 95, 97, 2000, XP, 2003, 2007: 1990. Flash MX, 9, CS 1-4. >> iTunes 8: 2001. RealPlayer 4-11: 1995. Macintosh 1.0-9: 1984-2001, X.5: >> 2001. Winzip 12.0: early 1990s. >> >> > Just to note: Office 2007 is also known as Office 12, if you want to > look at version numbers. Also, Mac OS hasn't increased the major version > number past 10 since they switched from their own proprietary kernel to > using the open-source Darwin. > > > >> Interestingly, many linux _distro_ also inhibit this quick version >> number change. Fedora 10, Ubuntu is 2 years old, version 8 (they start >> from version 6 not 1). >> >> > That's because 8 isn't the verison number- it's the year the version was > released (8.10 is October 2008, not the 10th update to version 8). I know about that, but in my definition (and Wikipedia's), it is still the version number (maybe I forget to put a footnote). My point is that commercial software and commercial front of a free software (linux distros, Cedega 6.1) prefers having big version numbers. From collin.day.0 at gmail.com Thu Dec 18 15:13:46 2008 From: collin.day.0 at gmail.com (Collin D) Date: Thu, 18 Dec 2008 12:13:46 -0800 (PST) Subject: Factoring Polynomials References: <5dfe1cf3-530d-4e31-833e-e26db85611be@d36g2000prf.googlegroups.com> Message-ID: <0459f66d-fb43-4c42-a0d2-926b4b04fa06@z6g2000pre.googlegroups.com> On Dec 18, 11:52?am, eric wrote: > On Dec 18, 8:37?pm, collin.da... at gmail.com wrote: > > > I am trying to write a simple application to factor polynomials. I > > wrote (simple) raw_input lines to collect the a, b, and c values from > > the user, but I dont know how to implement the quadratic equation > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > into python. Any ideas? > > with numpy: > from numpy import * > > s=[1,-1] > x = -b+s*sqrt( b**2-4*a*c )/(2*a) > > Erichttp://codeslash.blogspot.com Ahh. Great.. thank you. I didnt know about the sqrt function.. saves me from doing "^1/2". Thanks again. -CD From rileyrgdev at gmail.com Mon Dec 22 11:33:34 2008 From: rileyrgdev at gmail.com (Richard Riley) Date: Mon, 22 Dec 2008 17:33:34 +0100 Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: Marco Mariani writes: > walterbyrd wrote: > >> I have read that python is the world's 3rd most popular language, and >> that python has surpassed perl in popularity, but I am not seeing it. > > > In 20 days, you've gone from trying to import a module by using: > >> load "test.py" > > > to questioning the popularity of python. > > You have many other subject you want to enlighten us about, I suppose? > Cause I wonder what you'll come up with, next. > One does not have to by a language maestro to try and assess its popularity. While his numbers or his reading of the numbers might be open to some questions, to suggest that one needs to be totally familiar with a language to determine its popularity is, frankly, ridiculous. -- important and urgent problems of the technology of today are no longer the satisfactions of the primary needs or of archetypal wishes, but the reparation of the evils and damages by the technology of yesterday. ~Dennis Gabor, Innovations: Scientific, Technological and Social, 1970 From jyoung79 at kc.rr.com Fri Dec 19 13:14:53 2008 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Fri, 19 Dec 2008 18:14:53 +0000 Subject: change string to unicode Message-ID: <20081219181453.43GVB.336864.root@hrndva-web05-z02> Hi Steven and Peter, Thank you both very much for taking the time to answer my question. Your solutions work perfect! :-) Thanks again! Jay > How about > > >>> "\\u03b1".encode("ascii").decode("unicode-escape") > '?' > > Peter From lists at cheimes.de Mon Dec 29 10:17:37 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 29 Dec 2008 16:17:37 +0100 Subject: multiprocessing vs thread performance In-Reply-To: References: Message-ID: mk wrote: > Am I doing smth wrong in code below? Or do I have to use > multiprocessing.Pool to get any decent results? You have missed an important point. A well designed application does neither create so many threads nor processes. The creation of a thread or forking of a process is an expensive operation. You should use a pool of threads or processes. The limiting factor is not the creation time but the communication and synchronization overhead between multiple threads or processes. Christian From febaen at gmail.com Tue Dec 16 07:51:58 2008 From: febaen at gmail.com (feba) Date: Tue, 16 Dec 2008 04:51:58 -0800 (PST) Subject: Need help improving number guessing game References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> <01564c98$0$21844$c3e8da3@news.astraweb.com> <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> <4946df78$0$19771$426a74cc@news.free.fr> <1f33580b-84f9-4059-a0f0-b6a8d71325af@b38g2000prf.googlegroups.com> <4947742c$0$25951$426a34cc@news.free.fr> Message-ID: <19ad95bd-519f-4256-8bd9-1dfbbddf615f@s1g2000prg.googlegroups.com> >The good news is that Python functions are objects too, so you can pass >them as params to another function. duh, duh, duh, duh, duh! I knew I was missing something there. Thanks. >if not mini <= x <= maxi: also thanks for this, I forgot about that. But I have it as if not minr < guess < maxr: because it's to DISALLOW the numbers to stay the same. >That was just a suggestion, and it would have been pretty >interesting IMHO as a basis for a "from Q&D procedural scripting to OO >application programing" tutorial. Yeah, I can see that. From darcy at druid.net Thu Dec 11 10:03:12 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 11 Dec 2008 10:03:12 -0500 Subject: How can I understan the "for" here? In-Reply-To: <49412744.8040301@gmail.com> References: <49412744.8040301@gmail.com> Message-ID: <20081211100312.9d68eeab.darcy@druid.net> On Thu, 11 Dec 2008 22:44:20 +0800 Kermit Mei wrote: > >>> ["%s=%s" % (k, v) for k, v in params.items()] > ['pwd=secret', 'database=master', 'uid=sa', 'server=mpilgrim'] > > I can't understand the second sentence because of the "for ... in". > I consider that the syntactics of "for" should be: > > for k,v in params.items(): I think you are binding ':' here too tightly to the 'for' construct in your mind. The for construct is "for in " which can be used as : in block constructs. The above is not a block construct but a list comprehension so it follows different rules. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From zhang_killer at hotmail.com Thu Dec 11 00:03:48 2008 From: zhang_killer at hotmail.com (frendy zhang) Date: Thu, 11 Dec 2008 13:03:48 +0800 Subject: encrypt and descrypt a created file Message-ID: if form.accepts(request.vars,session): for table in db.tables: rows=db(db[table].id).select() print rows open(str(os.sep).join([os.getcwd(), 'applications', request.application, 'databases', table+'.csv']),'w').write(str(db(db[table].id).select ())) How can i encrypt and descrypt the created file above?? thanks in advance... _________________________________________________________________ NEW! Get Windows Live FREE. http://www.get.live.com/wl/all -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmurray at bitdance.com Sat Dec 13 09:33:36 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Sat, 13 Dec 2008 09:33:36 -0500 (EST) Subject: Shorter tracebacks In-Reply-To: References: Message-ID: On Sat, 13 Dec 2008 at 06:13, bearophileHUGS at lycos.com wrote: > When I write recursive code in Python I sometimes go past the maximum > allowed stack depth, so I receive a really long traceback. The show of > such traceback on my screen is very slow (despite a CPU able to > perform billions of operations each second). So I think I'd like > something to shorten them. > I am thinking about something like: > from __future__ import short_traceback > > That allows me to see only the first and last parts of the stack > trace, and skips the (generally very redundant) middle part. _If_ such a feature were to be added, it should be a runtime option to the interpreter, not a __future__ import. --RDM From lie.1296 at gmail.com Tue Dec 9 15:56:19 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 9 Dec 2008 20:56:19 +0000 (UTC) Subject: Is 3.0 worth breaking backward compatibility? References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> Message-ID: On Sun, 07 Dec 2008 21:48:46 +0000, Tim Rowe wrote: > 2008/12/7 walterbyrd : >> IMO: breaking backward compatibility is a big deal, and should only be >> done when it is seriously needed. >> >> Also, IMO, most of, if not all, of the changes being made in 3.0 are >> debatable, at best. I can not think of anything that is being changed >> that was really a "show stopper" anyway. > > > But that's what a major release number does for you. Modula2 was quite a > break from Modula. Think of Python3.0 it as a new language, if you like, > that's inspired by Python2. You can stay with Python2 or you can adopt > the new language. That way you won't have to think of it in terms of > breaking any sort of backwards compatibility because there is no > backwards ;-) > > -- > Tim Rowe Actually I noticed a tendency from open-source projects to have slow increment of version number, while proprietary projects usually have big version numbers. Linux 2.x: 1991 Python 3.x.x: 1991. Apache 2.0: 1995. OpenOffice.org 3.0: acquired by Sun at 1999. GIMP 2.x: 1995. Wine 1.x: 1993. Compare with Windows: NT 3.1-NT 6.x: 1993. Visual Studio 97, 6.0, .NET, .NET 2003, .NET 2005, 2008: 1997. Photoshop (11 versions to CS4): 1987. Microsoft Office 3, 4, 95, 97, 2000, XP, 2003, 2007: 1990. Flash MX, 9, CS 1-4. iTunes 8: 2001. RealPlayer 4-11: 1995. Macintosh 1.0-9: 1984-2001, X.5: 2001. Winzip 12.0: early 1990s. Interestingly, many linux _distro_ also inhibit this quick version number change. Fedora 10, Ubuntu is 2 years old, version 8 (they start from version 6 not 1). Probably having higher version numbers sells better and looks more attractive (since it'd make it seem like the software is not a new product), having quick changing version number also makes users doesn't mind compatibility breaks. Also a pattern is that prop software often change how they version their product, (extreme example: visual studio: from using years, version number, .NET, .NET + Year, back to year). Changing how you version your product would make it "looks" like it's a fresh new product (boring ol' photoshop 9 looks fresh with the new CS- tag). By having quick changing version number and often changing how product is versioned, vendors could also say: "its two/three major version away, we don't support that feature anymore since a veeery long time". From benjamin.kaplan at case.edu Wed Dec 10 22:32:31 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 10 Dec 2008 22:32:31 -0500 Subject: Python is slow In-Reply-To: <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> Message-ID: On Wed, Dec 10, 2008 at 10:25 PM, Carl Banks wrote: > On Dec 10, 12:42 pm, cm_gui wrote: > > Python is SLOW. And I am not comparing it with compiled languages > > like C. > > Python is even slower than PHP! > > > cm_gui is TROLL. And I am not compring it with bots like Aaron > Castironpi Brody. cm_gui is even troller than Xah Lee! > actually Castironpi has made some coherent replies lately. Xah Lee is worse than ever though. > > > Carl Banks > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Dec 12 08:27:59 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Dec 2008 08:27:59 -0500 Subject: Removing None objects from a sequence In-Reply-To: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> Message-ID: Filip Gruszczy?ski wrote: > Hi! > > I would like to iterate over a sequence nad ignore all None objects. > The most obvious way is explicitly checking if element is not None, > but it takes too much space. And I would like to get something faster. > I can use > [ sth for sth in self.__sth if not sth is None ], but I don't know if > that's the best way. I checked itertools, but the only thing that > seemed ok, was ifilter - this requires seperate function though, so > doesn't seem too short. How can I get it the shortest and fastest way? > The problem with the list comprehension you quote above is that it creates a new list, which costs both time and memory. You might want to try using a generator expression instead: (sth for sth in self.__sth if not sth is None) This will give you the same sequence of values, but will produce them only as they need to be consumed, saving the memory and compute overhead of creating a second list. >>> lst = [1, None, 3, None, "five", None] >>> mylst = [l for l in lst if l is not None] >>> mygen = (l for l in lst if l is not None) >>> mylst, mygen ([1, 3, 'five'], ) >>> for l in mylst: print l, ... 1 3 five >>> for l in mygen: print l, ... 1 3 five >>> regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From drexeldragon at gmail.com Wed Dec 24 22:23:41 2008 From: drexeldragon at gmail.com (Mark) Date: Wed, 24 Dec 2008 22:23:41 -0500 Subject: Python 3 and my Mac (Leopard) In-Reply-To: <4952b38d$0$20300$607ed4bc@cv.net> References: <4952b38d$0$20300$607ed4bc@cv.net> Message-ID: <3e3cae6c0812241923h797d0661l2d713c6beb3e123e@mail.gmail.com> On Wed, Dec 24, 2008 at 5:11 PM, Dan wrote: > > Wanted to learn python, got Mark Summerfield's new book "Programming in Python 3". Having a hard time getting python 3 and IDLE working on my Mac with Leopard. The mac "resources" on the python.org site seem a bit out of date, and don't really mention python 3. Are there any resources out there? Is the python community just not interested in Macs? I've tried googling and the usual search strategies. Any help would be appreciated. > > DAN I used the following link when installing Python 3 on my Mac running Leopard, it worked like a charm: http://farmdev.com/thoughts/66/python-3-0-on-mac-os-x-alongside-2-6-2-5-etc-/ These instructions are based around installing Python 3 alongside your existing install, which is what I was looking for. YMMV, especially concerning IDLE, I haven't used it with 3.0 as of yet. -Mark From huffman at tokyo.email.ne.jp Fri Dec 26 20:18:13 2008 From: huffman at tokyo.email.ne.jp (Tokyo Dan) Date: Fri, 26 Dec 2008 17:18:13 -0800 (PST) Subject: SVG & Canvas: Graphics for the Web Message-ID: <767f7870-9d62-407e-99e8-9bdc437b582e@d42g2000prb.googlegroups.com> Is there a Python library that can draw/write graphics to web browsers vis SVG & Canvas via some kind of Python to javascript translation/ compilation? From python.list at tim.thechases.com Tue Dec 30 14:51:53 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 30 Dec 2008 13:51:53 -0600 Subject: need help with list/variables In-Reply-To: <63b5acce-d566-48cb-abce-c00fd0e02a39@v39g2000pro.googlegroups.com> References: <63b5acce-d566-48cb-abce-c00fd0e02a39@v39g2000pro.googlegroups.com> Message-ID: <495A7BD9.9090801@tim.thechases.com> > I have a list and would like to parse the list appending each list > item to the end of a variable on a new line. > > for instance > > mylist = ['something\n', 'another something\n', 'something again\n'] > > then parse mylist to make it appear in my variable in this format: > > myvar = """ > something > another something > something again""" Just use the join() method on an empty string: myvar = "".join(mylist) (though your example would need to be tweaked to make the newlines match the newlines in your result, given the newlines in your list) myvar = """something another something something again """ Or you can do something like myvar = '\n'.join(s.rstrip('\n') for s in mylist) Mix and match to get your desired output. -tkc From nicolas.delanos at gmail.com Thu Dec 25 08:51:18 2008 From: nicolas.delanos at gmail.com (Nicolas Delanos) Date: Thu, 25 Dec 2008 08:51:18 -0500 Subject: DomainKey library for python Message-ID: Hello, Do you know if there is a domainkey library for python ? thanks From david at abbottdavid.com Tue Dec 2 16:15:19 2008 From: david at abbottdavid.com (David) Date: Tue, 02 Dec 2008 16:15:19 -0500 Subject: Running a Python script from crontab In-Reply-To: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> Message-ID: <4935A567.2030208@abbottdavid.com> Astley Le Jasper wrote: > >> my crontab is: >> >> 30 15 * * * cd /home/myusername/src && python myscript.py I create a file runmyscript.sh and put it in /usr/bin #!/bin/bash cd /home/myusername.src python /path/to/myscript then chmod a+x /usr/bin/runmyscript.sh test it ./runmyscript add it to the crontab 30 15 * * * /usr/bin/runmyscript.sh -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From delroth at gmail.com Sun Dec 28 16:12:43 2008 From: delroth at gmail.com (Pierre Bourdon) Date: Sun, 28 Dec 2008 22:12:43 +0100 Subject: error on windows with commands.getstatusoutput In-Reply-To: References: Message-ID: <1ba9eaed0812281312t773bf436mbc51b7d83594883@mail.gmail.com> The commands module is Unix only. See its documentation : http://docs.python.org/library/commands.html On Sun, Dec 28, 2008 at 10:03 PM, Lee Harr wrote: > > My application is trying to start twistd in a cross-platform way. > > Unfortunately, it works fine on my linux system, but I do not > have windows, and I am trying to debug this remotely on a > system I never use :o( > > Anyhow, here is the error I am getting: > > cmd = '%s -y %s -l %s' % (conf.twistd, conf.tztac, conf.twistdlog) > status, output = commands.getstatusoutput(cmd) > > > > Error code: 1 > Command: C:/Python25/Scripts/twistd.bat -y tzmud.tac -l var/log/twistd.log > Output: > '{' is not recognized as an internal or external command, > operable program or batch file. > > > Apparently, the Command works fine from the command line. > > > So... > > Can I run a .bat file on windows with getstatusoutput? > > Anyone recognize this kind of error? > > > Thanks for any assistance. > > > _________________________________________________________________ > Show them the way! Add maps and directions to your party invites. > http://www.microsoft.com/windows/windowslive/events.aspx > -- > http://mail.python.org/mailman/listinfo/python-list > From skip at pobox.com Mon Dec 15 19:42:48 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 15 Dec 2008 18:42:48 -0600 Subject: Insatlling python on compute-node-linux (Cray). In-Reply-To: References: Message-ID: <18758.63880.530636.366516@montanaro-dyndns-org.local> Rahul> Has anyone tried installing Python on Compute Node Linux (on a Rahul> cray)? I was having trouble getting it running. I see that CNL Rahul> does not support dynamic libraries but I am not sure what the Rahul> best way then is to get Python running. In the Modules directory note there is a file named Setup (or Setup.dist, which you can copy to Setup to start. Scan that file looking for modules you want to support in your installation, uncomment the relevant line(s) and adjust as necessary. Then do the normal configure/make dance. Those modules which you've enabled will be statically linked into the Python interpreter executable and not built as shared objects. At least that's how I recall it from the days before Python supported shared libraries. It's been awhile. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From deets at nospam.web.de Thu Dec 18 10:53:08 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 18 Dec 2008 16:53:08 +0100 Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> <6qv7kfFeuf65U1@mid.uni-berlin.de> Message-ID: <6qv9v4Ff1lv9U1@mid.uni-berlin.de> Neal Becker wrote: > Diez B. Roggisch wrote: > >> Neal Becker wrote: >> >>> Tino Wildenhain wrote: >>> >>>> Neal Becker wrote: >>>> ... >>>>>>> So if __str__ is "meant for human eyes", then why isn't print using >>>>>>> it! >>>>>> it is: >>>>>> >>>>>> > print x >>>>>> str >>>>>> >>>>>> but dict just uses repr() for all its childs to print. >>>>>> >>>>>> T. >>>>> That makes no sense to me. If I call 'print' on a container, why >>>>> wouldn't it recursively print on the contained objects? Since print >>>>> means call str, printing a container should recursively call str on >>>>> the objects. >>>> >>>> Every class is free on how to best implement __str__, you will find >>>> the same behavior on tuple and list as well. >>>> >>>> Maybe its discussable to change the implementation sensibly, best if >>>> you would come with a proposal? Perhaps pprint.pprint is a starting >>>> point? >>>> >>>> Regards >>>> Tino >>> >>> First, I'd like to know if there is a rationale for the current design. >>> Am I correct in thinking this is a defect? >> >> I don't think so. First of all, there is no "generic" way of printing a >> collection. And the current implementation tries to give an overview what >> is contained in the collection, without trying to make it "fancy" - any >> such thing needed to be hand-coded anyway. >> >> Using repr for that is better suited, as for example string keys are >> printed with quotes around them - making clear what they are, and not >> irritating the user through potentially contained spaces or even things >> that look as if they are python objects. >> >> For example, if repr *wasn't* used, >> >> { "{foo=bar}" : "baz"} >> >> would be printed >> >> {{foo=bar} : baz} >> >> Which is *not* what the dictionary actually contains! >> >> The same goes for unicode-objects. They appear with their "funny" >> characters as \xXX-codes - instead of bailing out on you with >> unicode-errors. >> >> So, IMHO the current behavior is desired. >> > > So if I want to overload something in my custom class, so that I get a > nice string whether it's printed directly, or as part of a container, what > is the recommendation? Overload both __str__ and __repr__? Yep. And it's easy enough if you don't care about them being different.. def __repr__(self): return str(self) BTW, you newsreader still produces bogus follow-ups, which makes replying to you unnerving. Diez From andrew at doadesweb.co.uk Wed Dec 10 12:42:04 2008 From: andrew at doadesweb.co.uk (Andrew D) Date: Wed, 10 Dec 2008 09:42:04 -0800 (PST) Subject: get todays files Message-ID: I have a script that will login to my ftp server and download all the backup files, but I want it to only download the files that were created today, e.g. if I ran the script today I want it to only fetch files created today. I am really not sure about how to do this, but it is quite important to me, so all help is highly appreciated! Andrew From google at mrabarnett.plus.com Thu Dec 4 10:13:44 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 04 Dec 2008 15:13:44 +0000 Subject: python to parse excel file csv format In-Reply-To: References: <4936DC35.6010404@mrabarnett.plus.com> <4936ECF7.3040400@wildenhain.de> Message-ID: <4937F3A8.7080108@mrabarnett.plus.com> Jay Jesus Amorin wrote: > This is what i have done and its giving me error. > > #!/usr/bin/env python > > import csv, sys, os > filename = (sys.argv[1]) > reader = csv.reader(open(filename, "rb"), delimiter=',', > quoting=csv.QUOTE_NONE) > > try: > #for row in reader: > for fmodes,fname in reader: fmodes and fname are both strings. > os.chmod(fname,fmodes) os.chmod() expects its second argument to be an int: os.chmod(fname, int(fmodes)) > > except csv.Error, e: > sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) > > > testserver:~> ./parsecsv.py chown.csv > Traceback (most recent call last): > File "./promote2prod.py", line 10, in ? > os.chmod(fname,fmodes) > TypeError: an integer is required > > > Please help I'm a complete newbie to python. > > Many thanks. > From db3l.net at gmail.com Sat Dec 6 17:01:24 2008 From: db3l.net at gmail.com (David Bolen) Date: Sat, 06 Dec 2008 17:01:24 -0500 Subject: Python 3.0 automatic decoding of UTF16 References: <55d79070-0c11-4fb9-8cf5-b8cc7c54b5d2@v42g2000yqv.googlegroups.com> Message-ID: Johannes Bauer writes: > This is very strange - when using "utf16", endianness should be detected > automatically. When I simply truncate the trailing zero byte, I receive: Any chance that whatever you used to "simply truncate the trailing zero byte" also removed the BOM at the start of the file? Without it, utf16 wouldn't be able to detect endianness and would, I believe, fall back to native order. -- David From kyosohma at gmail.com Wed Dec 31 16:54:22 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 31 Dec 2008 13:54:22 -0800 (PST) Subject: Creating an application for Linux References: <7d2fe328-064c-46da-9150-7305b6f9e94e@b41g2000pra.googlegroups.com> Message-ID: <67d1e9f1-5515-47ea-a0c1-1e8faf9c056c@a12g2000pro.googlegroups.com> On Dec 31, 3:36?pm, lkcl wrote: > hiya mike: where do i know you from? ?i've heard your name somewhere > and for the life of me can't remember where! ?anyway... onwards. > I don't know...while your username looks vaguely familiar, I don't think I've communicated with you recently. I spend most of my time on the wxPython list now... > your simplest bet is to take advantage of the .deb install system, > which, if you follow that, will allow you to pull in all of the > dependencies _without_ screwing around with the ubuntu distribution, > or requiring that you build "special" versions of the dependencies. > > so - your first port of call is to locate a similar app to your own > one: > > apt-cache ?search wxwidgets > [rose-tinted filter on the results...] > cryptonit - A client side PKI (X.509) cryptographic tool > fontypython - A GUI tool to manage ttf fonts > jmdlx - jugglemaster deluxe using wxWidgets > wxmaxima - a wxWidgets GUI for the computer algebra system maxima > multiget - graphical download manager > > then, do apt-cache show , paying particular attention to > the dependencies. ?apt-cache show fontypython looks like a good > candidate. > > so, do apt-get source fontypython (or other candidate) > > also do apt-get build-essential dh-make dpkg-dev debutils python-dev > devscripts python-setuptools juuust for fun, but the essential ones > are probably dh-make and dpkg-dev. > > then you have something to work from (an example - the source of the > deb-wrapped fontypython) and you will have most of the debian > developer utils etc. etc. > > _then_ you go to e.g. oooo this:http://www.pythonmark.com/python-library/debian/howto-build-a-debian-... > the preamble for which says "don't bother with that annoying ubuntu > python deb howto video, particularly on the basis that who gives a > stuff about _verbal_ instructions when you actually want stuff you can > READ!" > > :) > > the most important thing that _you_ need to remember is that you > _must_ identify the correct libraries (and their debian packagenames - > can't bring myself to say ubuntu packagenames) and make damn sure that > you add them into the dependencies in the debian/control file. > > do _not_ be tempted to "bundle" customised versions of python- > pysqlite, python-sqlalchemy etc. etc. > > testing: you should really use a debootstrap absolute "basic" > environment (set up a chroot, or a virtual KVM or other virtual PC, > qemu, whatever, or even a real machine) do NOT do a "full" install of > ubuntu, do an absolute minimalist install (netbook, businesscard, > whatever). I thought the general practice was to test on the closest software/ hardware combo that your application was most likely to run on. I have heard of doing testing on the lowest common denominator before though. Unfortunately, I don't have time to set up a bare-bones VM since we're closing soon, but I may give this a go on Friday and report back. > > ... and _then_ install your .deb (with dpkg -i) followed by apt-get -f > install (to pull in all of the dependencies). > > then, use export DISPLAY=192.168.1.5:0.0 (adapt as necessary), run > xhost + on 192.168.1.5 (adapt as necessary), and _then_ fire up your > test app. > > if you get a python library not found runtime error, you know that you > got your dependencies wrong, in the debian/control file. > > if you install a "vanilla" ubuntu desktop, various other packages will > pull in the dependencies for you - and you will never find out if you > got all of the dependencies correct. > > that having been said, if you don't _care_ about correctness, skip the > above six sentences :) > > l. > Thanks for the instructions. Mike From prologic at shortcircuit.net.au Thu Dec 18 20:26:14 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Dec 2008 11:26:14 +1000 Subject: Factoring Polynomials In-Reply-To: <269523e2-eba9-4b6b-b0fb-c5a7deb3ed76@o4g2000pra.googlegroups.com> References: <269523e2-eba9-4b6b-b0fb-c5a7deb3ed76@o4g2000pra.googlegroups.com> Message-ID: Hi Collin, Here you go: jmills at atomant:~/tmp$ cat polycalc.py #!/usr/bin/env python from math import sqrt def f(a, b, c): if (b**2 - (4 * a * c)) < 0: return None, None # Can't solve x = (-1 * b) + (((b**2 - (4 * a * c)) ** 0.5) / (2 * a)) return (-1 * x), x print "Polynomial Solver..." print while True: a = float(raw_input("a: ")) b = float(raw_input("b: ")) c = float(raw_input("c: ")) x = f(a, b, c) if None in x: print "Can't solve!" else: print "x = -%0.2f" % x[0] print "x = +%0.2f" % x[1] jmills at atomant:~/tmp$ cheers James From bj_666 at gmx.net Mon Dec 15 16:42:23 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 15 Dec 2008 21:42:23 GMT Subject: Structure using whitespace vs logical whitespace References: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> <89b3cbe5-e61b-49eb-926a-e96a43a35fe5@s1g2000prg.googlegroups.com> Message-ID: <6qo19vFda9rhU3@mid.uni-berlin.de> On Mon, 15 Dec 2008 12:27:12 -0800, cmdrrickhunter at yaho.com wrote: > On Dec 15, 11:10?am, Terry Reedy wrote: >> > In general, I'm using indentation to show logical flow through code. >> >> That, of course, is what Python does. >> > Python does NOT use indentation to show logical flow. It uses it to > show syntactical flow. What the heck is "syntactical flow"? Of course Python uses indentation for logical flow -- the indentation reflects the program logic. > The XML writer is the perfect example of a case where they are > different. No the program flow there is just some linear calls to methods. It's the XML structure that is not reflected by the indentation, the program flow is represented just fine here. Ciao, Marc 'BlackJack' Rintsch From jstroud at mbi.ucla.edu Mon Dec 8 01:05:54 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 07 Dec 2008 22:05:54 -0800 Subject: Rich Comparisons Gotcha In-Reply-To: References: <014c593e$0$20670$c3e8da3@news.astraweb.com> Message-ID: Robert Kern wrote: > James Stroud wrote: >> py> 112 = [1, y] >> py> y in 112 >> Traceback (most recent call last): >> File "", line 1, in >> ValueError: The truth value of an array with more than one element is... >> >> but not >> >> py> ll1 = [y,1] >> py> y in ll1 >> True >> >> It's this discrepancy that seems like a bug, not that a ValueError is >> raised in the former case, which is perfectly reasonable to me. > > Nothing to do with numpy. list.__contains__() checks for identity with > "is" before it goes to __eq__(). ...but only for the first element of the list: py> import numpy py> y = numpy.array([1,2,3]) py> y array([1, 2, 3]) py> y in [1, y] ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in : The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() py> y is [1, y][1] True I think it skips straight to __eq__ if the element is not the first in the list. That no one acknowledges this makes me feel like a conspiracy is afoot. From digitig at gmail.com Fri Dec 12 15:07:42 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 12 Dec 2008 20:07:42 +0000 Subject: newbie question... In-Reply-To: References: Message-ID: 2008/12/12 : > ah, ok. now what if I want the variable to be an integer that I > send? for instance if I send 99 to the program, it is picking it up > as a string instead of an integer value. How do I handle this with > python?? As 'r' has said, you can cast it to integer. In the real world you'd want to handle the case where the user passes in something that isn't an integer, or passes in nothing at all -- it's generally a good idea to check anything the user enters for validity. It's possibly too early for you to try to code it, but it's never too early to start thinking about what you would /want/ it to do. What do you think it will do for invalid or no command line arguments at the moment? Try it! -- Tim Rowe From R.Bauer at fz-juelich.de Tue Dec 23 07:49:11 2008 From: R.Bauer at fz-juelich.de (Reimar Bauer) Date: Tue, 23 Dec 2008 13:49:11 +0100 Subject: SuSE11.1 eclipse 64 pydev can't add python path Message-ID: Hi I can install pydev using the update manager in eclipse for 64 bit from the SuSE 11.1 repo. But I can't configure pydev without crashing it. I can select the interpreter /usr/bin/python and I do see the System PYTHONPATH Forced builtin libs also looks good. But Apply gives me # # An unexpected error has been detected by Java Runtime Environment: # # SIGSEGV (0xb) at pc=0x00007f2d7abebaed, pid=6544, tid=139832007596368 # # Java VM: IcedTea 64-Bit Server VM (1.7.0-b24 mixed mode linux-amd64) # Problematic frame: # V [libjvm.so+0x21baed] # # An error report file with more information is saved as: # /home/user/hs_err_pid6544.log # # If you would like to submit a bug report, please visit: # http://icedtea.classpath.org/bugzilla # The crash happened outside the Java Virtual Machine in native code. # See problematic frame for where to report the bug. That problem happens also with the recent eclipse-cpp-ganymede-SR1-linux-gtk-x86_64.tar.gz What can be the cause for this problem? Do you know a workaround e.g. manually configuring pydev? Does one have pydev or eclipse working on SuSE11.1? cheers Reimar From rhodri at wildebst.demon.co.uk Mon Dec 22 20:29:31 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Tue, 23 Dec 2008 01:29:31 -0000 Subject: noob trouble with IDLE In-Reply-To: <68f1552e0812211346i96bf18hf28dccc1f8dd1a99@mail.gmail.com> References: <68f1552e0812211346i96bf18hf28dccc1f8dd1a99@mail.gmail.com> Message-ID: On Sun, 21 Dec 2008 21:46:16 -0000, Ronald Rodriguez wrote: > Hi, Im new to python and I've just started using Byte of Python, running > the > samples etc. Im using IDLE on Xp. Ok, here's the thing. > A sample script makes a call to the os.system() function in order to zip > some files. Everything works fine when running from the command line, but > the same code fails when I try Run --> Run module on IDLE. Im using 7z to > zip the files. Again, everything is OK when running from the command > line. > Remember, Im new to python and programming. I've done some google search > without results. Maybe its just too simple :-( . Any help would be > appreciated. Thanks in advance. When you say "the same code fails" when run via IDLE, what exactly do you mean? Does it produce huge amounts of traceback and whinging? Does it lock up IDLE entirely? Does it thumb its nose at you and go off to dance the night away in Ibiza? Absent that information, my best guess is that 7z has its own internal event loop (a quick Google suggests that it's a GUI tool) which fights for dominance with IDLE's event loop. This is a fairly common problem, and a good reason for avoiding using IDLE's "Run Module" for anything but the most straightforward Python code. -- Rhodri James *-* Wildebeeste Herder to the Masses From rNOSPAMon at flownet.com Sun Dec 28 00:57:15 2008 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sat, 27 Dec 2008 21:57:15 -0800 Subject: Need help getting MoinMoin to run under WSGI Message-ID: I successfully installed MoinMoin as a CGI according to the instructions on the moinmo.in site. But when I tried to switch over to running it under wsgi it failed thusly: [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] Traceback (most recent call last): [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] File "/www/wikis/genesisgroup/moin.wsgi", line 49, in ? [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] from MoinMoin.server.server_wsgi import WsgiConfig, moinmoinApp [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] ImportError: No module named MoinMoin.server.server_wsgi The problem, I believe, is that I have both Python 2.4 and 2.5 installed (it's a Debian box) and MM is installed under 2.5 but WSGI is using 2.4. I tried to fix this by setting WSGIPythonHome but to no avail. I can't figure out what to set it to. The instructions say: "the WSGIPythonHome directive should be used to specify the exact location of the Python installation corresponding to the version of Python compiled against" I have two problems with this. First, I didn't compile mod_wsgi, I got it pre-built as a Debian module. Second, what does "the exact location of the Python installation" even mean? Python2.5 is spread out in at least three different places: /usr/local/bin, /usr/lib/python2.5, and /usr/local/lib/python2.5. I've tried setting WSGIPythonHome to all of those (and a few other things as well) and nothing worked. Also, "the version of Python compiled against" seems very odd. What does that mean? Surely I don't have to recompile mod_wsgi every time I change to a new version of Python? Help! Thanks! rg From sjmachin at lexicon.net Sun Dec 7 17:20:03 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 7 Dec 2008 14:20:03 -0800 (PST) Subject: Python 3.0 automatic decoding of UTF16 References: <5u8o06xbqf.ln2@joeserver.homelan.net> <1mmq06x4g6.ln2@joeserver.homelan.net> Message-ID: <66cb8fac-d903-4324-a0b9-e12949d639f0@y1g2000pra.googlegroups.com> On Dec 8, 2:05?am, Johannes Bauer wrote: > John Machin schrieb: > > > He did. Ugly stuff using readline() :-) Should still work, though. > > Well, well, I'm a C kinda guy used to while (fgets(b, sizeof(b), f)) > kinda loops :-) > > But, seriously - I find that whole "while True:" and "if line == """ > construct ugly as hell, too. How can reading a file line by line be > achieved in a more pythonic kind of way? By using for line in open(.....) as mentioned in (1) my message that you were replying to (2) the tutorial: http://docs.python.org/3.0/tutorial/inputoutput.html#reading-and-writing-files ... skip the stuff on readline() and readlines() this time :-) While waiting for the bug to be fixed, you'll need something like the following: def utf16_getlines(fname, newline_terminated=True): f = open(fname, 'rb') raw_bytes = f.read() f.close() decoded = raw_bytes.decode('utf16') if newline_terminated: normalised = decoded.replace('\r\n', '\n') lines = normalised.splitlines(True) else: lines = decoded.splitlines() return lines That avoids the chunk-reading problem by reading the whole file in one go. In fact given the way I've written it, there can be 4 copies of the file contents. Fortunately your files are tiny. HTH, John From steve at REMOVE-THIS-cybersource.com.au Sat Dec 20 21:26:34 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Dec 2008 02:26:34 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: <015da0a4$0$20656$c3e8da3@news.astraweb.com> On Sat, 20 Dec 2008 17:55:35 -0800, Aaron Brady wrote: > On Dec 20, 7:38?pm, Steven D'Aprano cybersource.com.au> wrote: >> Instead of just whinging, how about making a suggestion to fix it? Go >> on, sit down for an hour or ten and try to work out how a BINARY >> OPERATOR like % (that means it can only take TWO arguments) can deal >> with an arbitrary number of arguments, *without* having any special >> cases. >> >> Go on. Take your time. I'll be waiting. > > Hi, not to take sides, but, there is a possibility. > > This behavior is currently legal: > >>>> "%i %%i" % 0 % 1 > '0 1' > > So, just extend it. (Unproduced.) > >>>> "%i %i" % 0 % 1 > '0 1' Errors should never pass silently, unless explicitly silenced. You have implicitly silenced the TypeError you get from not having enough arguments for the first format operation. That means that you will introduce ambiguity and bugs. "%i %i %i %i" % 5 % 3 %7 Here I have four slots and only three numbers. Which output did I expect? '%i 5 3 7' '5 %i 3 7' '5 3 %i 7' '5 3 7 %i' Or more likely, the three numbers is a mistake, there is supposed to be a fourth number there somewhere, only now instead of the error being caught immediately, it won't be discovered until much later. (BTW, if you want that behaviour, you should look at the string module.) -- Steven From tjreedy at udel.edu Wed Dec 17 14:09:53 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 17 Dec 2008 14:09:53 -0500 Subject: OT: Binary tree logarithms properties In-Reply-To: <8f67b6f80812170914m377191f4g81345ffe5d0b7f26@mail.gmail.com> References: <8f67b6f80812170914m377191f4g81345ffe5d0b7f26@mail.gmail.com> Message-ID: Mr.SpOOn wrote: > Hi, > I'm searching for a clear explanation of binary tree properties, > expecially the ones related to logarithms. > > For example, I know that in a tree with 2n-1 nodes, we have log(n) > levels, from 0 to log(n). A *complete* binary tree with n levels has 2**n - 1 nodes. This is easily shown by induction. (Try Wikipedia for induction proof if you are not familiar with such.) > So, if k is the level, the nodes on a level have indexes between 2^k > and 2^(k+1)-1. > > For k=0 we have 2 and 3. > For k=1 we have 4, 5, 6, 7 > and so on. Nodes only have single number indexes if you arrange them linearly. Then the index depends on how you arrange them, whether you start the array indexes with 0 or 1, and whether you start the level numbers with 0 or 1. Call the breadth-first sequence bf. Then the 1-based slice for 1-first level k is bf[2**(k-1):2**k)]. Again, proof by induction. Terry Jan Reedy From pavlovevidence at gmail.com Wed Dec 10 22:19:16 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 10 Dec 2008 19:19:16 -0800 (PST) Subject: internal circular class references References: Message-ID: <419f5539-9787-48a5-b6af-09a6b923e3f9@f24g2000vbf.googlegroups.com> On Dec 10, 8:18?pm, James Stroud wrote: > Ethan Furman wrote: > > Greetings List! > > > I'm writing a wrapper to the datetime.date module to support having no > > date. ?Its intended use is to hold a date value from a dbf file, which > > can be empty. > > > The class is functional at this point, but there is one thing I would > > like to change -- datetime.date.max and datetime.date.min are class > > attributes of datetime.date, and hold datetime.date values. ?At this > > point I have to have two lines outside the actual class definition to do > > the same thing, e.g.: > > > > > ? class NullDate(object): > > ? ? ? "adds null capable DateTime.Date constructs" > > ? ? ? __slots__ = ['_date'] > > ? ? ? def __new__(cls, date='', month=0, day=0): > > ? ? ? ? ? nulldate = object.__new__(cls) > > ? ? ? ? ? nulldate._date = "" > > ? ? ? ? ? . > > ? ? ? ? . > > ? ? ? ? . > > ? ? ? ? return nulldate > > ? ? ? def __getattr__(self, name): > > ? ? ? ? ? if self: > > ? ? ? ? ? ? ? attribute = self._date.__getattribute__(name) > > ? ? ? ? ? ? ? return attribute > > ? ? ? ? ? else: > > ? ? ? ? ? ? ? if callable(dt.date.__dict__[name]): > > ? ? ? ? ? ? ? ? ? return int > > ? ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? ? return 0 > > ? ? ? def __nonzero__(self): > > ? ? ? ? ? if self._date: > > ? ? ? ? ? ? ? return True > > ? ? ? ? ? return False > > ? ? ? @classmethod > > ? ? ? def fromordinal(cls, number): > > ? ? ? ? ? if number: > > ? ? ? ? ? ? ? return cls(dt.date.fromordinal(number)) > > ? ? ? ? ? else: > > ? ? ? ? ? ? ? return cls() > > ? NullDate.max = NullDate(dt.date.max) > > ? NullDate.min = NullDate(dt.date.min) > > > > > How can I move those last two lines into the class definition so that: > > ? 1) they are class attributes (not instance), and > > ? 2) they are NullDate type objects? > > > ~ethan~ > > I resisted posting a similar question recently. After much > consideration, I realized that the inability to reference a class inside > its own definition must have been a deliberate design of the language. I think mostly it's just a logistical issue. It's reasonable for a class's attributes to be objects of that class (the datetime.date class is a perfect example of when it's useful). It would be preferrable to assign such objects inside the class scope like all other class attributes. Problem is, the class doesn't exist until after all the statements in the class scope have been evaluated. > So the short answer is you can't. > > The way you have done it is best--its not a hack and is good style. Yes, it's straightforward and readable, a perfectly good workaround for a very minor style issue. Carl Banks From pavlovevidence at gmail.com Wed Dec 3 23:12:10 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 3 Dec 2008 20:12:10 -0800 (PST) Subject: RELEASED Python 3.0 final References: Message-ID: <1b9568f2-55a0-4f1e-886c-2675b16b58c9@g38g2000yqn.googlegroups.com> On Dec 3, 7:51?pm, Barry Warsaw wrote: > On behalf of the Python development team and the Python community, I > am happy to announce the release of Python 3.0 final. Congratulations! This is a great day for the Python community. Carl Banks From xahlee at gmail.com Fri Dec 5 10:51:20 2008 From: xahlee at gmail.com (Xah Lee) Date: Fri, 5 Dec 2008 07:51:20 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: On Dec 4, 6:09 pm, jason-s... at creativetrax.com wrote: > For the interested, with MMA 6, on a Pentium 4 3.8Ghz: > > The code that Jon posted: > > Timing[Export["image-jon.pgm", Graphics at Raster@Main[2, 100, 4]]] > {80.565, "image-jon.pgm"} > > The code that Xah posted: > > Timing[Export["image-xah.pgm", Graphics at Raster@Main[2, 100, 4.]]] > {42.3186, "image-xah.pgm"} > > So Xah's code is about twice as fast as Jon's code, on my computer. > > The resulting files were identical (and both looked like pure white > images; I thought they'd be interesting!). The result is not pure white images. They are ray traced spheres stacked in some recursive way. Here's the output in both my and jon's version: http://xahlee.org/xx/image.pgm also, note that Mathematica 6 has the function Normalize builtin, which is used in Jon's code deeply in the core. Normalize is not in Mathematica 4, so i had to code it myself, in this line: ?norm=Function [#/Sqrt@(Plus@@(#^2))];?. This possibly slow down my result a lot. You might want to replace any call of ?norm? in my program by the builtin Normalize. Also, each version of Mathematica has more optimizations. So, that might explain why on v4 the speed factor is ~0.2 on my machine while in v6 you see ~0.5. My machine is OS X 10.4.x, PPC G5 1.9 Ghz. ------------------------- let me take the opportunity to explain some high powered construct of Mathematica. Let's say for example, we want to write a function that takes a vector (of linear algebra), and return a vector in the same direction but with length 1. In linear algebar terminology, the new vector is called the ?normalized? vector of the original. For those of you who don't know linear algebra but knows coding, this means, we want a function whose input is a list of 3 elements say {x,y,z}, and output is also a list of 3 elements, say {a,b,c}, with the condition that a = x/Sqrt[x^2+y^2+z^2] b = y/Sqrt[x^2+y^2+z^2] c = z/Sqrt[x^2+y^2+z^2] For much of the history of Mathematica, normalize is not a builtin function. It was introduced in v6, released sometimes in 2007. See bottom of: http://reference.wolfram.com/mathematica/ref/Normalize.html Now, suppose our task is to write this function. In my code, you see it is: norm=Function[#/Sqrt@(Plus@@(#^2))]; let me explain how it is so succinct. Mathematica's syntax support what's called FullForm, which is basically a fully nested notation like lisp's. In fact, the Mathematica compiler works with FullForm. The FullForm is not something internal. A programer can type his code that way if he so pleases. in FullForm, the above expression is this: Set[ norm, Function[ Times[Slot[1], Power[ Sqrt[ Apply[ Plus, Power [ Slot[1], 2 ] ] ], -1 ] ] ] Now, in this norm=Function[#/Sqrt@(Plus@@(#^2))] The ?Function? is your lisper's ?lambda?. The ?#? is the formal parameter. So, in the outset we set ?norm? to be a pure function. Now, note that the ?#? is not just a number, but can be any argument, including vector of the form {x,y,z}. So, we see here that math operations are applied to list entities directly. For example, in Mathematica, {3,4,5}/2 returns {3/2,2,5/2} and {3,4,5}^2 returns {9,16,25}. In typical lang such as python, including lisp, you would have to map the operation into each lisp elements instead. The ?Sqrt at ...? is a syntax shortcut for ?Sqrt[...]?, and the ?Plus@@...? is a syntax shortcut for ?Apply[Plus, ...]?, which is lisp's ?funcall?. So, taking the above all together, the code for ?norm? given above is _syntactically equivalent_ to this: norm=Function[ #/Sqrt[ Apply[Plus, #^2] ]] this means, square the vector, add them together, take the square root, then have the original vector divide it. The ?#? is in fact a syntax shortcut for ?Slot[1]?, meaning the first formal parameter. The ?=? is in fact a syntax shortcut for ?Set[]?. The ?^? is a shortcut for ?Power[]?, and the ?/? is a shortcut for ?Power[..., -1]?. Putting all these today, you can see how the code is syntactically equivalent to the above nested FullFolm. Note, that the ?norm? as defined above works for any dimentional vectors, i.e. list of any length. In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, you'll have 50 or hundreds lines. For more detail on syntax, see: ? The Concepts and Confusions of Prefix, Infix, Postfix and Fully Nested Notations http://xahlee.org/UnixResource_dir/writ/notations.html Xah ? http://xahlee.org/ ? From martin at v.loewis.de Wed Dec 3 16:47:25 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 03 Dec 2008 22:47:25 +0100 Subject: building an extension module with autotools? In-Reply-To: References: Message-ID: <4936FE6D.1000805@v.loewis.de> > I've tried using automake, however I'm worried about libtool not getting > the options right while building my module. You should use python-config(1) to obtain the command line options necessary to build and link extension modules. HTH, Martin From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 10:35:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2008 15:35:53 GMT Subject: change string to unicode References: Message-ID: <015bb6ae$0$20656$c3e8da3@news.astraweb.com> On Fri, 19 Dec 2008 09:19:28 -0600, jyoung79 wrote: > If I have a string like so: > > a = '\\u03B1' > > and I want to make it display a Greek alpha character, is there a way to > convert it to unicode ('\u03B1')? I tried concatenating it like this: > > '\u' + '03B1' > > but that didn't work. I'm working in Python 3.0 and was curious if this > could be done. This is from Python 2.5: >>> print unichr(0x03B1) ? I don't have Python 3 here, but I guess that you would just use chr() instead of unichr(). If you literally have to start with the actual string '\\u03B1' (that is, backslash lowercase-U zero three uppercase-B one), then I'd do this: >>> s = '\\u03B1' >>> if s.startswith('\\u'): ... s = s[2:] ... >>> print unichr(int(s, 16)) ? -- Steven From alwaseem307ster at yahoo.com Thu Dec 18 00:58:31 2008 From: alwaseem307ster at yahoo.com (klia) Date: Wed, 17 Dec 2008 21:58:31 -0800 (PST) Subject: importing csv file into sqlite Message-ID: <21067453.post@talk.nabble.com> hey guys, i have a hug .csv file which i need to insert it into sqlite database using python. my csv data looks like this Birthday2,12/5/2008,HTC,this is my birthday Sea,12/3/2008,kodak,sea birthday4,14/3/2009,samsung,birthday love,17/4/2009,SONY,view of island can any one give me a head start codes. thanks in advance -- View this message in context: http://www.nabble.com/importing-csv-file-into-sqlite-tp21067453p21067453.html Sent from the Python - python-list mailing list archive at Nabble.com. From xahlee at gmail.com Thu Dec 11 13:41:59 2008 From: xahlee at gmail.com (Xah Lee) Date: Thu, 11 Dec 2008 10:41:59 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> Message-ID: <452ba58b-9377-4463-85e2-5ecdaa25a129@t39g2000prh.googlegroups.com> On Dec 10, 2:47?pm, John W Kennedy wrote: > Xah Lee wrote: > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, > > you'll have 50 or hundreds lines. > > C: > > #include > #include > > void normal(int dim, float* x, float* a) { > ? ? float sum = 0.0f; > ? ? int i; > ? ? float divisor; > ? ? for (i = 0; i < dim; ++i) sum += x[i] * x[i]; > ? ? divisor = sqrt(sum); > ? ? for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; > > } i don't have experience coding C. The code above doesn't seems to satisfy the spec. The input should be just a vector, array, list, or whatever the lang supports. The output is the same datatype of the same dimension. Xah ? http://xahlee.org/ ? From cjw at ncf.ca Tue Dec 2 14:50:03 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Tue, 02 Dec 2008 14:50:03 -0500 Subject: Multiple Versions of Python on Windows XP In-Reply-To: <4934de22$0$27863$9b622d9e@news.freenet.de> References: <4934de22$0$27863$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: >> Could anyone please point me to documentation on the way the msi >> installer handles multiple versions eg. Python 2.5, 2.6 and 3.0? > > I don't think that is documented anywhere. > >> What changes are made to the registry? > > For a complete list, see Tools/msi/msi.py in the source tree. I have scanned the file: http://svn.python.org/projects/python/branches/py3k/Tools/msi/msi.py I don't find anything that addresses this issue. > >> Is there some way to specify a default version in such a way that it can >> be changed as necessary? > > What do you mean by "default version"? I am seeking some mechanism such that any of Python 2.5, Python 2.6 or Python 2.6 can be chosen as the currently active version. > > There is the version that is associated with the .py/.pyc extensions > at any point in time; you can change these by re-running the respective > installers from add-and-remove-programs. In a well-managed installation, > only one Python installation would have the "Register Extensions" > feature selected; to then change the default, one would unselect the > feature in one version, and reselect it in a different. If only the > default installation procedure was ever used, re-running the installer > in "Repair" mode (from ARP) will also restore the extension > associations. I was hoping that there is some simpler way than the "Repair" procedure. > >> PyScripter uses an option to select a version eg. >> >> C:\Program Files\PyScripter\PyScripter.exe --python26 >> >> but I'm having some trouble with it when I attempt edit a python file >> from the Windows Explorer. > > It would be good to be more specific with such statements: what troubles > specifically? If I play dumb, I'd say "of course - windows explorer > doesn't support editing Python files; you need a text editor". Yes, I should have been clearer. The PyScripter application locks up and must be killed, using the Task Manager. Many thanks for your response. Best wishes, Colin W. > > Regards, > Martin From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 29 04:26:28 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 29 Dec 2008 10:26:28 +0100 Subject: "return" in def In-Reply-To: <3afba310-dcde-4dc1-825a-7c63b97e2a40@w1g2000prk.googlegroups.com> References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <0167cbf7$0$6988$c3e8da3@news.astraweb.com> <676bffeb-4b07-4226-8c14-7da57d94351b@f13g2000yqj.googlegroups.com> <3afba310-dcde-4dc1-825a-7c63b97e2a40@w1g2000prk.googlegroups.com> Message-ID: <495897c4$0$8481$426a74cc@news.free.fr> John Machin a ?crit : > On Dec 29, 7:06 am, Roger wrote: >>> Curious. When I see a bare return, the first thing I think is that the >>> author forgot to include the return value and that it's a bug. >>> The second thing I think is that maybe the function is a generator, and >>> so I look for a yield. If I don't see a yield, I go back to thinking >>> they've left out the return value, and have to spend time trying to >>> understand the function in order to determine whether that is the case or >>> not. >>> In other words, even though it is perfectly valid Python, bare returns >>> always make the intent of the function less clear for me. I'm with Bruno >>> -- if you have a function with early exits, and you need to make the >>> intent of the function clear, explicitly return None. Otherwise, leave it >>> out altogether. >>> -- >>> Steven >> To me this is the soundest argument. Thanks for the advice. I think >> I'll follow this as a rule of thumb hereafter. > > Please don't. Follow MRAB's advice, with the corollary that a > generator is forced by the compiler to be a "procedure" in MRAB's > terminology. I fail to see any *practical* difference between MRAB's and Steven's POVs. In both cases, it boils down to - don't use a bare return at the end of a def statement's body, - either use only bare returns ('procedure') or explicitely return None ('function') From malaclypse2 at gmail.com Tue Dec 2 14:26:50 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 2 Dec 2008 14:26:50 -0500 Subject: help me~!about base64 In-Reply-To: References: <0ff1ba7b-8a17-4647-99fc-9c8e32f83de7@g1g2000pra.googlegroups.com> Message-ID: <16651e80812021126g303a8d6ai5862857dd0038b7a@mail.gmail.com> On Tue, Dec 2, 2008 at 2:08 PM, wrote: >>>>print base64.__file__ > /usr/lib/python2.5/base64.pyc That looks fine, and matches what I have on my linux box. Your code works fine for me when I run it, so I'm out of ideas. -- Jerry From ivlenin at gmail.com Mon Dec 8 14:22:14 2008 From: ivlenin at gmail.com (I V) Date: Mon, 08 Dec 2008 19:22:14 GMT Subject: Text parsing via regex References: Message-ID: On Mon, 08 Dec 2008 13:42:00 -0500, r0g wrote: > Robocop wrote: >> However i'm having several problems. I know that playskool regular >> expression i wrote above will only parse every 50 characters, and will >> blindly cut words in half if the parsed string doesn't end with a >> whitespace. I'm relatively new to regexes and i don't know how to have >> it take that into account, or even what type of logic i would need to >> fill in the extra whitespaces to make the string the proper length when >> avoiding cutting words up. So that's problem #1. Regexps may not be the solution here. You could consider the textwrap module ( http://docs.python.org/library/textwrap.html ), although that will only split your text into strings up to 50 characters long, rather than padding with whitespace to exactly 50 characters. If you really need the strings to be exactly 50 characters long (and, are you sure you do?), try: # Split the input up into separate words words = input_string.split() groups = [] current_string = '' current_length = 0 for word in words: if current_length + len(word) +1 <= 50: # If adding a space followed by the current word # wouldn't take us over 50 chars, add the word. current_string += ' ' + word current_length += len(word)+1 else: # Pad the string with spaces, and add it to our # list of string current_string += ' ' * (50 - current_length) groups.append(current_string) current_string = word current_length = len(word) >> Problem #2 is that >> because the string is of arbitrary length, i never know how many parsed >> strings i'll have, and thus do not immediately know how many variables >> need to be created to accompany them. It's easy enough with each pass >> of the function to find how many i will have by doing: mag = >> len(string) >> upper_lim = mag/50 + 1 >> But i'm not sure how to declare and set them to my parsed strings. Whenever you find yourself thinking "I don't know how many variables I need," the answer is almost always that you need one variable, which is a list. In the code above, the 50-char-long strings will all get put in the list called "groups". From steve at holdenweb.com Tue Dec 23 06:49:11 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 23 Dec 2008 06:49:11 -0500 Subject: String Format Error. In-Reply-To: <47c890dc0812222311m2a67b798v167b40de9dfcd53d@mail.gmail.com> References: <47c890dc0812222311m2a67b798v167b40de9dfcd53d@mail.gmail.com> Message-ID: Chris Rebert wrote: > On Mon, Dec 22, 2008 at 10:19 PM, Paulo Repreza wrote: >> Hi, >> >> I'm a newbie with python and I recently bought Beginning with Python (Which >> is a book I recommend) but the problem that I'm facing it's the following: >> >> This is the code: >> >> #!/usr/bin/python2.5 >> # Filename: str_format.py >> >> age = 25 >> name = 'foobar' >> >> print('{0} is {1} years old'.format(name, age)) >> print('Why is {0} playing with that python?'.format(name)) >> >> >> But when I run the script I receive this error: >> >> Traceback (most recent call last): >> File "str_format.py", line 7, in >> print('{0} is {1} years old'.format(name, age)) >> AttributeError: 'str' object has no attribute 'format' >> >> >> It is an error because of the version that I'm using ? Python 2.5.2 (Debian >> lenny) > > Yes, Python 2.6 or higher is required to use .format() according to > http://docs.python.org/whatsnew/2.6.html > For a replacement that will work in 2.5, see the "%" sign as an operator (sometimes called "string interpolation"). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From Slaunger at gmail.com Tue Dec 9 11:45:37 2008 From: Slaunger at gmail.com (Slaunger) Date: Tue, 9 Dec 2008 08:45:37 -0800 (PST) Subject: When (and why) to use del? References: Message-ID: On 9 Dec., 17:35, Albert Hopkins wrote: > I'm looking at a person's code and I see a lot of stuff like this: > > ? ? ? ? def myfunction(): > ? ? ? ? ? ? # do some stuff stuff > ? ? ? ? ? ? my_string = function_that_returns_string() > ? ? ? ? ? ? # do some stuff with my_string > ? ? ? ? ? ? del my_string > ? ? ? ? ? ? # do some other stuff > ? ? ? ? ? ? return > > and also > > ? ? ? ? def otherfunction(): > ? ? ? ? ? ? try: > ? ? ? ? ? ? ? ? # some stuff > ? ? ? ? ? ? except SomeException, e: > ? ? ? ? ? ? ? ? # more stuff > ? ? ? ? ? ? ? ? del e > ? ? ? ? ? ? return > > I think this looks ugly, but also does it not hurt performance by > preempting the gc? ?My feeling is that this is a misuse of 'del'. Am I > wrong? ?Is there any advantage of doing the above? I agree with you. In my mind there is no reason for such kinds of deletes. The code seems to have been made by a person who ?sually programs in a language which does not have a garbage collector. I do not know if it has any noticeable impact on the performance. -- Slaunger From tjreedy at udel.edu Sat Dec 6 15:12:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 06 Dec 2008 15:12:02 -0500 Subject: "as" keyword woes In-Reply-To: <7d0lj4d9hai2f87r30erc4l1ir85osbfg7@4ax.com> References: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> <0147dc24$0$20670$c3e8da3@news.astraweb.com> <0148b217$0$20670$c3e8da3@news.astraweb.com> <7d0lj4d9hai2f87r30erc4l1ir85osbfg7@4ax.com> Message-ID: In my opinion, this thread is a crock of balony. Python *occasionally* adds keywords after giving a warning or requiring a future import in previous versions. In 2.2, one had to 'from __future__ import generators' to make a generator because doing so required the new 'yield' keyword. In 2.3, yield became a keyword without the import. In 2.5, one had to 'from __future__ import with_statement' to make a 'with' statement. In 2.6, with because a keyword without the import. And no one seems to have noticed. No '"with" keyword woes. In 2.6, 'as' also because a full-time keyword after several releases of being an anomalous part-time contextual keyword. tjr From ajaksu at gmail.com Wed Dec 24 10:57:40 2008 From: ajaksu at gmail.com (ajaksu) Date: Wed, 24 Dec 2008 07:57:40 -0800 (PST) Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> <1iscu14.oixxplpgajabN%pdorange@pas-de-pub-merci.mac.com> <1isenn3.1g8fxa21aqzibkN%pdorange@pas-de-pub-merci.mac.com> <0161d9c7$0$20621$c3e8da3@news.astraweb.com> <1isg3dq.1yyxrjp5eqcj5N%pdorange@pas-de-pub-merci.mac.com> Message-ID: <5d46665d-7d53-414d-8ae0-b8499b951781@n10g2000yqm.googlegroups.com> On Dec 24, 5:59?am, pdora... at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) wrote: > > For me sign_0 is the simplest one to understood. > So in the domain of my little arcade game, this is what i'll use. > I don't need the accuraccy of sign_1, because in the application i just > need to know if the target is right or left or if the speed direction is > right or left. If there is a chance of getting bogus input to sign_0 (like a list, None or other non-numeric types) it might be worth to add a quick check like: def sign_0(x): x + 0 if x==0.0: ... From castironpi at gmail.com Thu Dec 4 10:05:53 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 4 Dec 2008 07:05:53 -0800 (PST) Subject: funny generator behaviour References: Message-ID: <2e89735b-0a0e-42f1-a620-37459e51a4c3@v38g2000yqb.googlegroups.com> On Dec 4, 7:00?am, Edvin Fuglebakk wrote: ... > def orderedCombinations(pool, k): > ? ? """ > ? ? Generator yielding ordered selections of size k with repetition from > pool. > ? ? """ > > ? ? if k == 1: > ? ? ? ? for m in pool: > ? ? ? ? ? ? yield [m] > > ? ? if k > 1: > > ? ? ? ? for m in pool: > ? ? ? ? ? ? for combo in orderedCombinations(pool, k-1): > > ? ? ? ? ? ? ? ? #insert and pop to avoid copying entire list > ? ? ? ? ? ? ? ? combo.insert(0,m) > ? ? ? ? ? ? ? ? yield combo > ? ? ? ? ? ? ? ? combo.pop(0) 'combo.pop' is the problem. When the caller saves the iteration variable, the generator modifies it on the next call. >>> a= [] >>> b= [0] >>> a.append( b ) >>> a [[0]] >>> b.insert( 0, 1 ) >>> a [[1, 0]] If you want your output to have X lists, you need to create X lists. Perhaps copy is not the most efficient, but you can't have one list try do be X different lists when viewed from different angles. Though that would be cool. From icanbob at gmail.com Thu Dec 11 20:03:24 2008 From: icanbob at gmail.com (bobicanprogram) Date: Thu, 11 Dec 2008 17:03:24 -0800 (PST) Subject: problem adding custom module in cgi script Message-ID: Problem: Apache server serving an HTML file to a Firefox Browser containing a form and a CGI python CGI script. HTML works fine, meat of the CGI script works fine except that when a home grown and ordinarily functional module that is to be imported is added, the interpreter cannot find it. Running cgi.test() reveals that PYTHONPATH is correctly set. Still nada. Adding the sys.* stuff still nada. Items: Firefox Browser, Apache server, Python 2.5. ======================================= The CGI script: #! /usr/bin/python import cgi #cgi.test() import sys #sys.path.append("/myModulePath") #sys.path.insert(0, "/myModulePath") import myModule **************** Problem here ******************** =========================================== httpd error_log excerpt: [Wed Dec 10 13:39:46 2008] [error] [client 192.168.1.1] Traceback (most recent call last):, referer: http://192.168.1.1/nee.html [Wed Dec 10 13:39:46 2008] [error] [client 192.168.1.1] File "/var/www/cgi-bin/noo.py", line 11, in , referer: http://192.168.1.1/nee.html [Wed Dec 10 13:39:46 2008] [error] [client 192.168.1.1] import myModule, referer: http://192.168.1.1/nee.html [Wed Dec 10 13:39:46 2008] [error] [client 192.168.1.1] ImportError: No module named myModule, referer: http://192.168.1.1/nee.html ============================================= Relevant lines from http.conf: ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" SetEnv PYTHONPATH /myModulePath PassEnv PYTHONPATH Thanks in advance for any pointers. bob From kyrie at uh.cu Wed Dec 10 17:58:49 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Wed, 10 Dec 2008 17:58:49 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: <200812101758.50276.kyrie@uh.cu> On Sunday 07 December 2008 09:21:18 pm Robert Kern wrote: > The deficiency is in the feature of rich comparisons, not numpy's > implementation of it. __eq__() is allowed to return non-booleans; however, > there are some parts of Python's implementation like list.__contains__() > that still expect the return value of __eq__() to be meaningfully cast to a > boolean. list.__contains__, tuple.__contains__, the 'if' keyword... How do can you suggest to fix the list.__contains__ implementation? Should I wrap all my "if"s with this?: if isinstance(a, numpy.array) or isisntance(b,numpy.array): res = compare_numpy(a,b) elif isinstance(a,some_otherclass) or isinstance(b,someotherclass): res = compare_someotherclass(a,b) ... else: res = (a == b) if res: # do whatever -- Luis Zarrabeitia (aka Kyrie) Fac. de Matem?tica y Computaci?n, UH. http://profesores.matcom.uh.cu/~kyrie From steve at holdenweb.com Thu Dec 18 10:36:23 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 18 Dec 2008 10:36:23 -0500 Subject: Minor Typo in doc In-Reply-To: <494A5E14.10508@problemlos.ch> References: <494A5E14.10508@problemlos.ch> Message-ID: Kurt Mueller wrote: > Hi > > > > There is a minor typo in the new doc in: > http://www.python.org/doc/2.6/library/signal.html > > ------------------------------------------------------------------ > signal.SIG_DFL? > This is one of two standard signal handling options; > it will simply perform the default function for the signal. > For example, on most systems the default action for SIGQUIT > is to dump core and exit, while the default action for > SIGCLD > is to simply ignore it. > ------------------------------------------------------------------ > > SIGCLD > should be > SIGCHLD > > > Should I make a bug report in http://bugs.python.org? > Yes. The documentation give you a link to follow from the bottom of each page. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steve at holdenweb.com Mon Dec 22 12:56:06 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 22 Dec 2008 12:56:06 -0500 Subject: Python's popularity In-Reply-To: References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: r wrote: > I think when Python was first brought to this dark world by a genius > named Guido van Rossum, it had complete dominance in it's niche, > actually Python created a niche where none existed before. Since the > advent of Ruby(Python closet competitor), Python's hold on this niche > is slipping. A lot of Ruby noobies don't even realize that most of > Ruby is an out-right plagiarism of Python. But I guess that's OK, > because Python has borrowed from other languages itself.. just not in > such a -sell your soul- kind of way as Ruby!. > > Now since Python *is not* the only language on it's block, we have to > compete with our main nemesis(Ruby) for survival(I wonder if mats > would have been so revolutionary to introduce indention if Guido had > not done it first??, it seems to me he is a braces fanboy ;) > What makes you assume this is a zero-sum game, and that Python won't survive if any other language becomes popular. Every language borrows from those that came before it. Terms like "outright plagiarism" don't encourage rational debate, and make you seem like a troll who is more interested in stirring up controversy than actually doing things to help promote the language. > Now more than ever we must stick to the Zen and clean up Python's > warts to keep the dream alive and regain our right full crown. Python > is better than Ruby, I have no doubt in my mind, but if we let ruby > become -faster- than Python, people will gravitate away from Python. > Speed IS important even in high level languages. We must never forget > that! The war is not over just because we have Google, Nasa, and ILM. > On the Contrary, it has just begun. I believe mats is not going to > accept Ruby as 2nd best to Python, he will wage war on Pythonia. And > if we fail to preempt this attack, we shall be like the burning ships > of pearl harbor! Maybe Guido has a secret weapon up his sleeve(big > boy), but 3.0 was defiantly not the bomb! > I have an article about the Zen coming up in "Python Magazine" so I won't steal its thunder. Suffice it to say that people take the Zen far too seriously. Anyone who does so undermines their own credibility as a Python commentator. This isn't a war. Stop being childish. > Mats will now take advantage of the weaknesses in Py3000 and run with > them. Whispering in everyones ear how much faster Ruby is to Python. > And weather you like to hear it or not, this ROR thing is exploding, > we must counter attack this vile disgrace to Pythonia. Do not sit back > and say "well we are the best and we don't need to try any harder". > For you will be left in the evolutionary dust of Ruby. And next year, > left wanting... > If all you want from a language is speed, go use C. I would avoid assembly language though, since a modern optimizing C compiler will often beat an assembly language programmer for execution speed, and the programming time will definitely be shorter. But to make speed the be-all and end-all is a witless approach. Speed is definitely not why dynamic languages' popularity is increasing. Speed *is* still relevant in certain areas, and completely irrelevant in others. > We need to sound the battle cries and gather the legions. Then we > shall march across Rubonia and *raise* their cities to the ground. We > shall encompass thy house O' Ruby -- and lay waste to it! After we > slay thee, we shall breed with thy women and convert thy children. We > shall rule with an iron fist!, crushing all resistance to Python's > absolute power. Like the great kings of olde, monuments will be > erected so all generations shall be witness of our power, and glory. > """ O' Python, for the sound of thy chariots will be so fear full no > army could stand against thee!""" We shall avenge the atrocities and > hypocrocies you have brought upon this world Ruby! And then you shall > know that we are the Lord of this world, when our vengeance is cast > upon you! > > I will be monitoring comp.lang.python and over the next 6 months I > will conduct a census of the users of this group. So far I have only > seen maybe 20 regulars here. I had hoped they numbered several > thousand, but i am starting to think more in the hundreds or even > less :(. I will post my findings to this group. It shall be a wake up > call for those of you who think the war is over. Get off your bums you > lazy-coach-potatos, the fight is not over yet. Do not let your eye's > become "wide shut"!!! > > Truth shall be the judge... Much more of this kind of tripe and nobody will read what you write anyway. You will hear the plonking of a hundred thousand newsreaders every time you post. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From sjmachin at lexicon.net Fri Dec 26 17:05:47 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 26 Dec 2008 14:05:47 -0800 (PST) Subject: Right way to set a variable to NULL? References: <5nfal41gom0iqi2nh5h0m5847ev9brtvpf@4ax.com> Message-ID: <098da1d1-640c-4aef-b005-5f0932f291cc@35g2000pry.googlegroups.com> On Dec 27, 8:16?am, Scott David Daniels wrote: > Martin wrote: > > ... > > class MailAddress(object): > > ? def __init__(self, address=None): > > ? ? self.address = address > > ? def __str__(self): > > ? ? if address: > > ? ? ? return self.adress > > ? ? return "NULL" > > There is an obvious typo above: > ?> ? ? if address: > should be: > ? ? ? ?if self.address: > > Or, you could replace the __str__ function with: > ? ? ?def __str__(self): > ? ? ? ? ?return self.address or "NULL" The above all have the same characteristic: if the input is a zero- length string, then NULL is inserted into the database instead of a zero-length string. Some folks (not just pedants!) regard that as an important difference. From rdmurray at bitdance.com Thu Dec 11 17:04:11 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Thu, 11 Dec 2008 17:04:11 -0500 (EST) Subject: Preventing execution of a method In-Reply-To: References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> <764daeef-bfbe-411a-8521-bb114321e4ac@b38g2000prf.googlegroups.com> <19304f8c-e34f-4aa9-8df2-6a7d3553007a@e1g2000pra.googlegroups.com> <2eed8876-94d2-4304-88a5-eb4a78b4f41d@33g2000yqm.googlegroups.com> <307fe197-1b42-4305-af0e-94b7ebe3ce70@r15g2000prh.googlegroups.com> <49417c59$0$8491$426a74cc@news.free.fr> Message-ID: On Thu, 11 Dec 2008 at 13:41, Emanuele D'Arrigo wrote: > On Dec 11, 7:48?pm, Bruno Desthuilliers > wrote: >>> or to provide read-only >>> access. I.e. right now I'm working on the graphical client which >>> potentially could be rewritten entirely by the users. It is necessary >>> and perfectly reasonable for the client module to access some of the >>> objects to be represented graphically, but those objects shouldn't be >>> modifiable by it. >> >> Why so ? At worst, they'll break everything. > > -IF- the application was single-user yes, it wouldn't be a big deal. > But as it is potentially multi-user, I don't want one party to corrupt > the application for everybody else. Say I'm writing a multi-player > version of a card game (I'm not). For the sake of the argument let's > imagine that the players are all playing on the same computer, taking > turns. However, they are using a GUI written by one of the players who > unbeknown to them, has written it to modify the game state > appropriately and give himself the right cards at the right time. If > the game state is read-only and can only be queried but not modified > by the GUI, the player can rewrite the GUI but cannot cheat. Isn't > this a legitimate concern? In that case, you've got much bigger problems than a lack of private methods. As someone else pointed out, _no_ language is secure in the face of this requirement. Proving this kind of interface requires a lot of careful security oriented thinking. Whole operating systems have been designed to address these kinds of issues... --RDM From skip at pobox.com Tue Dec 23 10:33:11 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 23 Dec 2008 09:33:11 -0600 Subject: pseudo terminal usage from Python? In-Reply-To: References: <18768.60036.20440.46074@montanaro-dyndns-org.local> Message-ID: <18769.1207.160812.2745@montanaro-dyndns-org.local> Steve> Look at the pexpect module - you can run interactive tasks Steve> through that. Thanks. Worked like a charm. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From katrinalovers at gmail.com Thu Dec 25 11:52:36 2008 From: katrinalovers at gmail.com (Katrina Lovers) Date: Thu, 25 Dec 2008 08:52:36 -0800 (PST) Subject: Celebrity wars (personal blog) @ http://www.bestbollywoodwallpapers.blogspot.com & http://www.besthollywoodwallpapers.blogspot.com Message-ID: <2b1ef63d-de33-449e-b797-f4c99c04f1e3@a29g2000pra.googlegroups.com> Celebrity wars, BOLLYWOOD ACTRESSES (http://www.bestbollywoodwallpapers.blogspot.com) Aishwarya Rai - http://www.hotandsexyaishwaryaraiwallpapers.blogspot.com Katrina Kaif - http://www.sexykatrinakaifwallpapers.blogspot.com PriyankaChopra - http://www.hotpriyankachoprawallpapers.blogspot.com Bipasha Basu - http://www.hotbipashabasuwallpapers.blogspot.com Kareena Kapoor - http://www.hotkareenakapoorwallpapers.blogspot.com Deepika Padokone - http://www.deepikapadokonewallpapers.blogspot.com Mallika Sherawat - http://www.hotmallikasherawatwallpapers.blogspot.com Riya Sen - http://www.hotriyasenwallpapers.blogspot.com Rakhi Sawant - http://www.rakhisawantwallpapers.blogspot.com Sayali Bhagat - http://www.sayalibhagatwallpapers.blogspot.com Diya Mirza - http://www.diyamirzawallpapers.blogspot.com Ayesha Takia - http://www.hotayeshatakiawallpapers.blogspot.com Neha Dhupia - http://www.hotnehadhupiawallpapers.blogspot.com Celina Jaitley - http://www.hotcelinajaitleywallpapers.blogspot.com Lara Dutta - http://www.hotlaraduttawallpapers.blogspot.com Sameera Reddy - http://www.sameerareddywallpapers.blogspot.com Hansika Motwani - http://www.hansikamotwaniwallpapers.blogspot.com Amrita Arora - http://www.hotamritaarorawallpapers.blogspot.com Amrita Rao - http://www.hotamritaraowallpapers.blogspot.com Aarti Chhabria - http://www.aartichhabriawallpapers.blogspot.com Preity Zinta - http://www.preityzintawallpapers.blogspot.com Shamita Shetty - http://www.shamitashettywallpapers.blogspot.com Isha Koppikar - http://www.ishakoppikarwallpapers.blogspot.com Geeta Basra - http://www.geetabasrawallpapers.blogspot.com Brinda Parekh - http://www.brindaparekhwallpapers.blogspot.com Genelia Dsouza - http://www.geneliadsouzawallpapers.blogspot.com Esha Deol - http://www.eshadeolwallpapers.blogspot.com Kangana Ranaut - http://www.kanganaranautwallpapers.blogspot.com Nisha Kothari - http://www.nishakothariwallpapers.blogspot.com Masumi Makhija - http://www.masumimakhijawallpapers.blogspot.com Manjari Fadnis - http://www.manjarifadniswallpapers.blogspot.com Thanks, Katrina From pydecker at gmail.com Fri Dec 12 14:12:38 2008 From: pydecker at gmail.com (Peter Decker) Date: Fri, 12 Dec 2008 13:12:38 -0600 Subject: [wxpython-users] Dabo 0.9.0 Released In-Reply-To: <47C9D05A-1D50-4690-8062-03939E1C9AE7@leafe.com> References: <47C9D05A-1D50-4690-8062-03939E1C9AE7@leafe.com> Message-ID: On Wed, Dec 10, 2008 at 1:24 PM, Ed Leafe wrote: > We are proud (and relieved!) to finally release Dabo 0.9.0, the first > official release of the framework in six months. We haven't been taking it > easy during that period; rather, we made some changes that clean up some > weak spots in the codebase, and as a result can offer a much more solid > framework, and are on course for a 1.0 release in the near future. Thanks for all your great work. I've been using Dabo for a couple of years now, and it just keeps getting better and better! -- # p.d. From ajaksu at gmail.com Mon Dec 22 17:13:50 2008 From: ajaksu at gmail.com (ajaksu) Date: Mon, 22 Dec 2008 14:13:50 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: <4a3150a1-531a-4aed-a7c9-c359b1f97323@s9g2000prg.googlegroups.com> On Dec 22, 4:44?pm, r wrote: > Oh Steve... Listen, my words are ment as a wake-up-call to all who r, can you do me a favor? Go read the archives of this newsgroup for a month or two, then come back with some perspective. I hope that will make your posts a little less nonsensical and annoying. My words are 'ment' as a shut-up-call, you make as much sense as jeff here: http://www.python.org/doc/humor/#nolo-contendre Daniel P.S.: You think Steve 'one of those who love python'? Geez, he's the one that made us weak in this war by sabotaging a major source of revenue for Python! -> http://pyfound.blogspot.com/2006/04/python-25-licensing-change.html From cma at mail.bnu.edu.cn Mon Dec 8 09:34:03 2008 From: cma at mail.bnu.edu.cn (Cong Ma) Date: Mon, 08 Dec 2008 22:34:03 +0800 Subject: [Python 2.x] Pickling a datetime.tzinfo subclass instance? Message-ID: Hello, I'm writing a program that pickles an instance of a custom subclass of datetime.tzinfo. I followed the guides given in the Library Reference (version 2.5.2, chapter 5.1.6), which contain the note: "Special requirement for pickling: A tzinfo subclass must have an __init__ method that can be called with no arguments, else it can be pickled but possibly not unpickled again. This is a technical requirement that may be relaxed in the future." I tried this with an example "FixedOffset" subclass instance given in the Example section in the manual. It indeed failed to unpickle. To work around this, I found two possible solutions: 1. Modify the __init__ method so that it takes optional arguments with default values; 2. Implement the __getinitargs__ method so that it does the opposite of __init__: returning a tuple from the instance's internal state that can be used to re-initialize an instance, retaining the old value. My questions: 1. Is the "technical limitation" fixed in version 2.6 or 3.0? I can't check it for myself now... Python.org seems down and I can't find the docs. 2. To stick with version 2.5, which of the above 2 methods is better? Both seems to unpickle to the correct result, but are there subtle side-effects? Or there are better solutions? Regards, Cong. From steve at holdenweb.com Fri Dec 12 08:21:16 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Dec 2008 08:21:16 -0500 Subject: File names, character sets and Unicode In-Reply-To: <49423DBB.9090401@logix.net.nz> References: <49423DBB.9090401@logix.net.nz> Message-ID: Michal Ludvig wrote: > Hi all, > > is there any way to determine what's the charset of filenames returned > by os.walk()? > > The trouble is, if I pass argument to os.walk() I get the > filenames as byte-strings. Possibly UTF-8 encoded Unicode, who knows. > > OTOH If I pass to os.walk() all the filenames I get in > the loop are already unicode()d. > > However with some locales settings os.walk() dies with for example: > Traceback (most recent call last): > File "tst.py", line 10, in > for root, dirs, files in filelist: > File "/usr/lib/python2.5/os.py", line 303, in walk > for x in walk(path, topdown, onerror): > File "/usr/lib/python2.5/os.py", line 293, in walk > if isdir(join(top, name)): > File "/usr/lib/python2.5/posixpath.py", line 65, in join > path += '/' + b > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1: > ordinal not in range(128) > > I can't even skip over these files with 'os.walk(..., onerror=handler)' > the handler() is never called. > > That happens for instance when the file names have some non-ascii > characters and locales are set to ascii, but reportedly in some other > cases as well. > > What's the right and safe way to walk the filesystem and get some > meaningful filenames? > > > Related question - if the directory is given name on a command line > what's the right way to preprocess the argument before passing it down > to os.walk()? > > For instance with LANG=en_NZ.UTF-8 (i.e. UTF-8 system): > * directory is called 'smile?' > * sys.argv[1] will be 'smile\xe2\x98\xba' (type str) > * after .decode("utf-8") I get u'smile\u263a' (type unicode) > > But how should I decode() it when running on a system where $LANG > doesn't end with "UTF-8"? Apparently some locales have non-ascii default > charsets. For instance zh_TW is BIG5 charset by default, ru_RU is > ISO-8850-5, etc. How do I detect that to get the right charset for decode()? > > I tend to have everything internally in Unicode but it's often unclear > how to convert some inputs to Unicode in the first place. What are the > best practices for dealing with these chraset issues in Python? > There's currently a huge thread on python-dev dealing with (or rather discussing) this very tortuous issue. Look for "Python-3.0, unicode, and os.environ" in the archives. (The same issue, by the way, also applies to environment variables). In a nutshell, this is likely to cause pain until all file systems are standardized on a particular encoding of Unicode. Probably only about another fifteen years to go ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From cmgui2 at gmail.com Wed Dec 10 13:42:40 2008 From: cmgui2 at gmail.com (cm_gui) Date: Wed, 10 Dec 2008 10:42:40 -0800 (PST) Subject: Python is slow Message-ID: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-a-faster-python-vm.html I fully agree with Krzysztof Kowalczyk . Can't they build a faster VM for Python since they love the language so much? Python is SLOW. And I am not comparing it with compiled languages like C. Python is even slower than PHP! Just go to any Python website and you will know. An example is: http://www2.ljworld.com/ And this site is created by the creators of Django! And it is not just this Python site that is slow. There are many many Python sites which are very slow. And please don?t say that it could be the web hosting or the server which is slow ? because when so many Python sites are slower than PHP sites, it couldn?t be the web hosting. Also, Zope/Plone is even slower. Python is slow. Very slow. From benjamin.kaplan at case.edu Wed Dec 3 14:09:51 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 3 Dec 2008 14:09:51 -0500 Subject: Reverse zip() ? In-Reply-To: <20081203171957.1a476f75@usenot.de> References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> <20081203095154.1bb33d4d@usenot.de> <8000d0b0-c9e5-4dbd-a6a0-e35b83277e72@d42g2000prb.googlegroups.com> <20081203114855.3915af9e@usenot.de> <20081203171957.1a476f75@usenot.de> Message-ID: On Wed, Dec 3, 2008 at 11:19 AM, Andreas Waldenburger wrote: > On Wed, 3 Dec 2008 07:08:52 -0800 (PST) Janto Dreijer > wrote: > > > I'd like to point out that since your where thinking in terms of > > matplotlib, you might actually find numpy's own transpose useful, > > instead of using zip(*seq) :) > > > This was, of course, to be expected. :) > > Whenever will I have an original problem that has not been solved > millions of times yet? > > /W > When GvR's time machine breaks. > > > -- > My real email address is constructed by swapping the domain with the > recipient (local part). > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fetchinson at googlemail.com Sat Dec 13 21:08:37 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 13 Dec 2008 18:08:37 -0800 Subject: 1 or 1/0 doesn't raise an exception Message-ID: Is it a feature that 1 or 1/0 returns 1 and doesn't raise a ZeroDivisionError? If so, what's the rationale? -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From hongtian.info at gmail.com Thu Dec 25 09:50:31 2008 From: hongtian.info at gmail.com (Hongtian) Date: Thu, 25 Dec 2008 06:50:31 -0800 (PST) Subject: question; C/C++ with Python Message-ID: <123f104c-0edc-423f-841d-70d8d9492ddd@r15g2000prd.googlegroups.com> Hi friends, I have a C/C++ application and I wrote a .py file to extend it. The .py file includes some simple functions without import any other modules. Today, I want to update my .py file and import SMTP library in the file, but it seems fail to import SMTP library. So I want to ask: when the .py file is used to extend C/C++ application, can it import other modules? How to do that? should I copy all pythons libs to my C/C++ application directory? That could be terrible... Thanks. From sturlamolden at yahoo.no Fri Dec 12 07:34:48 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 04:34:48 -0800 (PST) Subject: var or inout parm? References: Message-ID: On Dec 7, 9:54 am, m... at pixar.com wrote: > How can I make a "var" parm, where the called function can modify > the value of the parameter in the caller? > > def f(x): > x = x + 1 Short ansver: You can modify function parameters if they are mutable. If they are immutable any attempt to modify the parameter will trigger a copy. You cannot modify parameters by rebinding. x = x + 1 is a rebinding. x += 1 is not. If you need to modify immutable parameters or do the modification by rebinding, pass the variable back. Python allows multiple return values. From 00515879256 at fastwebnet.it Wed Dec 31 03:29:19 2008 From: 00515879256 at fastwebnet.it (Glauco) Date: Wed, 31 Dec 2008 09:29:19 +0100 Subject: string in files In-Reply-To: <016abee9$0$6988$c3e8da3@news.astraweb.com> References: <62075511-08ad-405a-a3af-2da8d2f22c50@v39g2000pro.googlegroups.com> <016abee9$0$6988$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano ha scritto: > On Tue, 30 Dec 2008 11:53:17 +0100, Glauco wrote: > > >>> thanks brother >>> i mean how do i particularly assign (u = this) >>> (y = is).... >>> in the strings up there. i have been able to split strings with any >>> character sign. >>> >>> >> If i'm not wrong this is simple with RE: > > If that's your idea of "simple", I'd hate to see what you consider > complicated! > > *Simple* is just using the split method. > > a, b, c, d, e, f = 'this is a python coding group'.split() > I've done a lot of file import procedure and IMHO this solution help you in all situation. You can validate line before import, you can do a specific RE for check a more detailed line and so on, it's more powerful. For simple i mean simple programming code. Glauco From bignose+hates-spam at benfinney.id.au Thu Dec 4 18:04:44 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 05 Dec 2008 10:04:44 +1100 Subject: To Troll or Not To Troll References: <896B75251BA19745A529B1B867893FA50679CE@planet.delsci.local> Message-ID: <878wqvv8xf.fsf@benfinney.id.au> "Chris Mellon" writes: > Peculiarities in usenet resulted in this discussion having several > threads and I missed some messages before I wrote this email. I'll put this more bluntly: Warren's messages to date egregiously break the flow of discussion. Warren, in the interest of sane discussion in these forums, please: * preserve attribution lines on quoted material so we can see who wrote what. * use the convention of ?New subject (was: Old subject)? when you change the ?Subject? field of a message. * switch to a client that preserves threading in messages you send, i.e. that properly constructs the ?References? and ?In-Reply-To? fields. General advice good for everyone, of course, but particularly apropos to this reply. Any one of the above is detrimental to omit; striking on all three makes a discussion almost impossible to follow. (Thank you, though, for avoiding the worse habit of top posting!) -- \ ?The cost of education is trivial compared to the cost of | `\ ignorance.? ?Thomas Jefferson | _o__) | Ben Finney From excord80 at gmail.com Tue Dec 9 22:16:32 2008 From: excord80 at gmail.com (excord80 at gmail.com) Date: Tue, 9 Dec 2008 19:16:32 -0800 (PST) Subject: How do I manually uninstall setuptools (installed by egg)? References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> Message-ID: <375bd56a-d92b-4d33-bf70-5bea630a376a@q30g2000vbn.googlegroups.com> On Dec 9, 10:04?pm, "Chris Rebert" wrote: > So, why do you think apt and not setuptools is The Right Way(tm)? I like to keep > 1 Python on my computer. 1. First, there's the system Python, which is installed by my OS and which I try not to mess with too much. I'm guessing Ubuntu uses this Python for various system jobs, preferences apps, etc. I try to only use apt with *this* Python. 2. Then there's my *own* Python. Maybe installed in ``/opt/py-i.j.k, or---more likely---``~/opt/py-i.j.k``. *This* is the one where I've previously made regular use of setuptools and ``easy_install``. If I break this one somehow, it doesn't foul up my system Python in any way, and it's easy to scrap it and start anew if I like. So, I'd like to get my *system* Python back to its "fresh out of the Ubuntu showroom" condition and remove *that* setuptools. As an aside, I'm a bit struck by how long the setuptools/easy_install manuals are, and a bit dismayed at the lack of an easy_install uninstall command. Thinking of trying life for a while without setuptools/easy_install. Will have to see how far I get. :) From warren at delsci.com Thu Dec 4 14:10:12 2008 From: warren at delsci.com (Warren DeLano) Date: Thu, 4 Dec 2008 11:10:12 -0800 Subject: To Troll or Not To Troll Message-ID: <896B75251BA19745A529B1B867893FA50679CE@planet.delsci.local> > Yet Another Python Troll (the ivory tower reference, as well as the > abrupt shift from complaining about keywords to multiprocessing), I > have to point out that Python does add new keywords, it has done so in > the past, and there was a considerable amount of warning, including an > automated deprecation warning in the very version you are going to > recommend to your "customers' (I don't actually think you have any > customers). ROFL! I'm sorry, you're right -- this has all been a figment of my imagination... http://www.pymolwiki.org/index.php/Covers http://images.google.com/images?q=pymol So don't mind me -- I clearly don't know what I'm talking about. From castironpi at gmail.com Mon Dec 22 19:18:59 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 22 Dec 2008 16:18:59 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <6ra8t0F925rU1@mid.individual.net> <29feda0d-6432-4cb9-8809-e4d4a7798601@e1g2000pra.googlegroups.com> <6raeb8F9s47U2@mid.individual.net> Message-ID: <25b1ece0-712b-4516-af28-88c50d00ab8c@s9g2000prg.googlegroups.com> On Dec 22, 4:07?pm, r wrote: > On Dec 22, 3:15?pm, je.s.t... at hehxduhmp.org wrote: > > > r wrote: > > > We see where you stand. And also see that by removing your comments > > > from the archive in 5 days, how small your acorns really are. > > > Also, it is pretty hard to take such accusations seriously from someone > > who themselves is using a generic gmail address w/o their real name > > attached to it. ?If I didn't care about using a proper NNTP client, I > > could quite easily create some dufus account on Gmail and post through > > that just like you did - I'm sure that'd really increase my credibility! > > Would you trust my words more if i used a name like "Thurstan Howell > III".... Come on, don't tell me you are that shallow. To attack my > credibility solely based on my user name is the sport of small minded > people. Surely you can bring more thought, and intelligence to this > thread than that?... Us small-minded people have hopes and dreams just like anybody else, Thurston. From martin at v.loewis.de Thu Dec 4 19:44:51 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 05 Dec 2008 01:44:51 +0100 Subject: RELEASED Python 3.0 final In-Reply-To: References: Message-ID: <49387983$0$27885$9b622d9e@news.freenet.de> > I would like to ask, how long will Python 2 be developed? Just for curiosity. > There won't be a 2.10 release of Python. Whether that means that 2.9 will be the last one, or whether development stops earlier, remains to be seen. Regards, Martin From benjamin.kaplan at case.edu Thu Dec 18 20:05:54 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 18 Dec 2008 20:05:54 -0500 Subject: Factoring Polynomials In-Reply-To: <269523e2-eba9-4b6b-b0fb-c5a7deb3ed76@o4g2000pra.googlegroups.com> References: <269523e2-eba9-4b6b-b0fb-c5a7deb3ed76@o4g2000pra.googlegroups.com> Message-ID: On Thu, Dec 18, 2008 at 7:59 PM, Collin D wrote: > On Dec 18, 4:41 pm, "James Mills" > wrote: > > On Fri, Dec 19, 2008 at 10:11 AM, Gabriel Genellina > > > > wrote: > > > En Thu, 18 Dec 2008 17:37:35 -0200, escribi?: > > > > >> I am trying to write a simple application to factor polynomials. I > > >> wrote (simple) raw_input lines to collect the a, b, and c values from > > >> the user, but I dont know how to implement the quadratic equation > > > > >> x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > > Why is this so hard ? This is simple simple > > expression. Reading through the Python > > tutorial and reading up on how to define > > functions is all you need! :) > > > > Here goes: > > > > >>> def f(a, b, c): > > > > ... x = (-1 * b) + ((b**2 - (4 * a * c)) / (2 * a)) > > ... return (-1 * x), x > > ... > > > > >>> f(1, 2, 3) > > (6, -6) > > > > cheers > > James > > Hiya James! > > Just one small problem with your equation above... > The quadratic formula is: > x = -b +or- (b**2 - (4 * a * c))^1/2 / 2a > > You just forgot the square root which makes quadratic a bit more > complicated. > You would have to download and import sqrt() from numpy or **.5 > why do you need sqrt from numpy? Is there a problem with math.sqrt or does no one realize that it exists? > > Also.. I need to build in functionality so the user does not have to > directly call the function like: > f(a,b,c) > a = float(raw_input("a=")) b = float(raw_input("b=")) c = float(raw_input("c=")) result = f(a,b,c) > > Instead.. they should be able to just raw_input their values. > Also.. as with some of the examples above its a good idea to analyze > the discriminant to make sure we have a real solution. > Of course.. thats all pretty simple to build in. Thanks a lot! > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From antoine at vo.lu Sat Dec 6 08:38:50 2008 From: antoine at vo.lu (Antoine De Groote) Date: Sat, 06 Dec 2008 14:38:50 +0100 Subject: Guido's new method definition idea In-Reply-To: <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Antoine De Groote: >> Allowing "$" as a substitute for "self" wouldn't require this new syntax. >> class C: >> def method($, arg): >> $.value = arg > > I think this (that is just sugar) may be a little better: > > class C: > def method($, arg): > $value = arg Well, in this case there would be no need to have the $ in the arguments list, as it would be like a "keyword", or a keysymbol in this case, like the "this" keyword in Java for instance. I dislike this even more than the dotted version. > > Or even this, combined with the idea suggested in the post by Guido: > > class C: > def $method(arg): > $value = arg > > (Note there's no point after $, it's not currently possible). > Ruby uses @ and @@ for similar purposes. > I agree that the code looks worse, but also shorter to read and write, > so in lines of code that use many instance attributes, that short $ > syntax helps keep the line shorter. So I may grow to accept this > sugar... > > Bye, > bearophile From noone at lewscanon.com Thu Dec 4 09:19:04 2008 From: noone at lewscanon.com (Lew) Date: Thu, 04 Dec 2008 09:19:04 -0500 Subject: Mathematica 7 compares to other languages In-Reply-To: <20081204111115.7cee2ecc@usenot.de> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <20081204111115.7cee2ecc@usenot.de> Message-ID: Andreas Waldenburger wrote: > On Wed, 03 Dec 2008 20:38:44 -0500 Lew wrote: > >> Xah Lee wrote: >>> enough babble ... >> Good point. Plonk. Guun dun! >> > > I vaguely remember you plonking the guy before. Did you unplonk him in > the meantime? Or was that just a figure of speech? I have had some hard drive and system changes that wiped out my old killfiles. -- Lew From ivanov.maxim at gmail.com Mon Dec 1 10:03:28 2008 From: ivanov.maxim at gmail.com (redbaron) Date: Mon, 1 Dec 2008 07:03:28 -0800 (PST) Subject: setuptools - library dependencies Message-ID: <66735aa9-b9e7-4006-8516-101cd4d295ce@z1g2000yqn.googlegroups.com> I try to write setup.py which compiles C Extenstion (A). The problem is the fact, that my C Extension depends on another C lib (B). I've digged it setuptools sources a bit and found "libraries" option for setuptools.setup. Now it compile B library at build_clib stage and A Extenstion at build_ext stage. But it doesn't pack B library in final egg file, only A one. Even more, it compiles B as static lib, but links it to A as dynamic, it leads to undefined symbols in A. How could I either: 1) link A with B staticaly? 2) put B in final egg in same dir as A? From steve at REMOVE-THIS-cybersource.com.au Sun Dec 7 09:44:55 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 14:44:55 GMT Subject: Rich Comparisons Gotcha References: Message-ID: <014bd916$0$20670$c3e8da3@news.astraweb.com> On Sun, 07 Dec 2008 13:03:43 +0000, Rasmus Fogh wrote: > Jamed Stroud Wrote: ... >> Second, consider that any value in python also evaluates to a truth >> value in boolean context. But bool(x) can fail too. So not every object in Python can be interpreted as a truth value. >> Third, every function returns something. Unless it doesn't return at all. >> A function's returning nothing >> is not a possibility in the python language. None is something but >> evaluates to False in boolean context. > > Indeed. The requirement would be not that return_value was a boolean, > but that bool(return_value) was defined and gave the correct result. If __bool__ or __nonzero__ raises an exception, you would like Python to ignore the exception and return True or False. Which should it be? How do you know what the correct result should be? >From the Zen of Python: "In the face of ambiguity, refuse the temptation to guess." All binary operators are ambiguous when dealing with vector or array operands. Should the operator operate on the array as a whole, or on each element? The numpy people have decided that element-wise equality testing is more useful for them, and this is their prerogative to do so. In fact, the move to rich comparisons was driven by the needs of numpy. http://www.python.org/dev/peps/pep-0207/ It is a *VERY* important third-party library, and this was not the first and probably won't be the last time that their needs will move into Python the language. Python encourages such domain-specific behaviour. In fact, that's what operator-overloading is all about: classes can define what any operator means for *them*. There's no requirement that the infinity of potential classes must all define operators in a mutually compatible fashion, not even for comparison operators. For example, consider a class implementing one particular version of three-value logic. It isn't enough for == to only return True or False, because you also need Maybe: True == False => returns False True == True => returns True True == Maybe => returns Maybe etc. Or consider fuzzy logic, where instead of two truth values, you have a continuum of truth values between 0.0 and 1.0. What should comparing two such fuzzy values for equality return? A boolean True/False? Another fuzzy value? Another one from the Zen: "Special cases aren't special enough to break the rules." The rules are that classes can customize their behaviour, that methods can fail, and that Python should not try to guess what the correct value should have been in the event of such a failure. Equality is a special case, but it isn't so special that it needs to be an exception from those rules. If you really need a guaranteed-can't-fail[1] equality test, try something like this untested wrapper class: class EqualityWrapper(object): def __init__(self, obj): self.wrapped = obj def __eq__(self, other): try: return bool(self.wrapped == other) except Exception: return False # or maybe True? Now wrap all your data: data = [a list of arbitrary objects] data = map(EqualityWrapper, data) process(data) [1] Not a guarantee. -- Steven From duncan.booth at invalid.invalid Wed Dec 10 03:41:18 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Dec 2008 08:41:18 GMT Subject: how to get a beep, OS independent ? References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> <6q6jf8Fau4iiU2@mid.individual.net> Message-ID: Grant Edwards wrote: > On 2008-12-09, greg wrote: >> Duncan Booth wrote: >> >>> If I'm logged in to one of my servers in a large datacentre >>> then I don't what that system to beep as that would be pretty >>> useless. >> >> It also might cause the datacentre operators some >> consternation when one of their servers starts mysteriously >> beeping... > > If they can hear it. Those tiny fans they put in rack-mount > stuff are awfully loud. > http://www.thinkgeek.com/gadgets/electronic/8c52/ -- Duncan Booth http://kupuguy.blogspot.com From ivan.illarionov at gmail.com Thu Dec 18 06:11:46 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 18 Dec 2008 03:11:46 -0800 (PST) Subject: C API and memory allocation References: <59352942-e976-4ef4-bc40-c8953df0a792@c36g2000prc.googlegroups.com> Message-ID: <7e3387a0-2159-4965-aa99-3f8fa7e4ccc0@l33g2000pri.googlegroups.com> On 18 ???, 14:09, Ivan Illarionov wrote: > ... PyArg_ParseTuple(args, "O!", &PyStringObject, &pystr) ... Sorry, I must have said &PyString_Type, not &PyStringObject From pavlovevidence at gmail.com Thu Dec 11 13:56:13 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 11 Dec 2008 10:56:13 -0800 (PST) Subject: internal circular class references References: Message-ID: <5db5a57e-483d-437e-bfab-0ae897ee3680@o4g2000pra.googlegroups.com> On Dec 11, 11:33?am, Ethan Furman wrote: > Good question. ?My goal with NullDate is to have a date object that I > can treat the same regardless of whether or not it actually holds a > date. ?NullDates with no value should sort before any NullDates with a > value, should be comparable to dates as well as NullDates, and should > support all the same methods. ?In other words, I don't want to have to > worry about whether my date object has an actual date under most > circumstances (printing, using as dictionary keys, comparing, etc.). > > Does my design make more sense given these expanded requirements, or > could it still be done simpler? ?For that matter, do my requirements > make sense? Your requirements make sense, but I think your approach is overkill. In particular, I think you are unnecessarily constraining yourself by forcing the dates and non-dates to be of the same data type. There's usually no reason for that. Python's duck typing allows you to write code that supports multiple types, as long as each type provides the same methods and operations and such. For instance, say you have a function like this that works for ordinary datetime.date objects: def print_date(date): print date.strftime() Now you want to be able to pass it a particular object that indicates no date was specified. Just define the class, like so: class NullDate(object): def strftime(self): print "" Now you could pass either a regular datetime.date object, or a NullDate object, like so: print_date(datetime.date(1976,10,6)) print_date(NullDate()) So, to (almost) get what you want, you need to just define a NullDate class that implements all the methods of datetime.date. Then the only thing you have to do is, when you're extracting the date from your dbf file, instead of always creating a datetime.date, create a datetime.date object when the date is specified, and a NullDate object when it's not. You could write a factory function to do it, for instance: def create_date_or_not(dbf_cell): if dbf_cell.contents: return datetime.date.fromordinal(dbf_cell.contents) return NullDate() Now, you did throw one little curveball into the requirements above: that NullDate needs to be comparable with datetime.date objects. I'd handle this by subclassing datetime.date to allow comparisons with NullDates. class ValidDate(datetime.date): def __eq__(self,other): if isinstance(other,NullDate): return False return super(ValidDate,self).__eq__(other) # and so on class NullDate(object): def __eq__(self,other): if isinstance(other,NullDate): return True return False # note: in Python 3.0 you would want to throw exceptions # for unexpected types Then use ValidDate instead of datetime.date when the date is specified. Carl Banks From nick at craig-wood.com Thu Dec 4 05:30:47 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 04 Dec 2008 04:30:47 -0600 Subject: How can I do this (from Perl) in Python? (closures) References: <68b8294c-8771-4b02-bd46-2f25f5e01602@j35g2000yqh.googlegroups.com> Message-ID: excord80 at gmail.com wrote: > I just came across http://www.perl.com/pub/a/2002/05/29/closure.html > and wanted to try the "canonical example of closures" in Python. I > came up with the following, but it fails: > > def make_counter(start_num): > start = start_num > def counter(): > start += 1 > return counter > > from_ten = make_counter(10) > from_three = make_counter(3) > > print from_ten() # 10 > print from_ten() # 11 > print from_three() # 3 > print from_ten() # 12 > print from_three() # 4 > > The error message is: "UnboundLocalError: local variable 'start' > referenced before assignment". The same thing happens if I omit start > and just use start_num directly. > > How can I do it in Python? With a class is the best way IMHO. class make_counter(object): def __init__(self, start_num): self.x = start_num def __call__(self): x = self.x self.x += 1 return x -- Nick Craig-Wood -- http://www.craig-wood.com/nick From frank at chagford.com Wed Dec 10 05:20:24 2008 From: frank at chagford.com (Frank Millman) Date: Wed, 10 Dec 2008 02:20:24 -0800 (PST) Subject: [OT] Google Groups in bad odour Message-ID: <4d5498bf-bbf0-4760-83fc-610729bcbce2@h20g2000yqn.googlegroups.com> Hi all I know there have been complaints about spam on Google Groups over the last few months, with some members rejecting all traffic from them. You might be interested in this comment I got in a reply from someone on comp.os.linux.setup - "If you want to be read by a wider audience, you really want to post from someplace other than Google Groups. Many (most?) readers of the Linux lists kill everything from there automatically." Unfortunately it seems that their newsgroup does not have a mail gateway, so I cannot use gmane. (Please correct me if I am wrong). I will therefore have to find a suitable news client. Any recommendations? Frank Millman From rafesacks at gmail.com Mon Dec 1 04:01:45 2008 From: rafesacks at gmail.com (Rafe) Date: Mon, 1 Dec 2008 01:01:45 -0800 (PST) Subject: noob needs help References: Message-ID: <507189ab-751f-4699-adca-fc1ed924c820@v5g2000prm.googlegroups.com> On Dec 1, 12:50?am, toveysnake wrote: > I decided that I want to learn python, and have no previous > programming experience. I was reading the guide A byte of python and > got to the part where you create and run the program helloworld.py I > used kate to create this program and save it as helloworld.py. I then > entered the command python helloworld.py into the terminal(I am using > ubuntu 8.10) and I get this error: > > collin at collin-laptop:~$ python helloworld.py > python: can't open file 'helloworld.py': [Errno 2] No such file or > directory > > Am I saving the file in the wrong spot?(I saved it in documents) > Should I use a different editor? Is there a better python book > available online? if you go to the directory where you put the file and run the python command, it should work (or supply the full path and not just 'helloworld.py') - Rafe From miki.tebeka at gmail.com Thu Dec 11 16:13:35 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 11 Dec 2008 13:13:35 -0800 (PST) Subject: Best way of debigging a C extension References: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> Message-ID: <4de560df-3c1f-4861-915b-582c66799d0a@i24g2000prf.googlegroups.com> Hello Paul, > I'm writing a C extension. My environment is Python 2.5, with the > mingw compiler, on Windows XP. At the moment I'm debugging by > scattering printf() statements around, but it's not always easy. Is > there a better way of debugging - particularly for diagnosing crashes? No guaranteed to work ... * Download WinDbg from http://www.microsoft.com/whdc/devtools/debugging/installx86.mspx#a * Add "hard" breakpoints in your code using __asm int 3; * Run your program If everything works well, when a breakpoint is reached you'll get message box asking if you want to debug the program. When you hit "OK", WinDbg should open with your code. Just point it to the source location and you should be set. HTH, -- Miki http://pythonwise.blogspot.com From benjamin.kaplan at case.edu Tue Dec 2 13:44:02 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 2 Dec 2008 13:44:02 -0500 Subject: HELP!...Google SketchUp needs a Python API In-Reply-To: <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> Message-ID: On Tue, Dec 2, 2008 at 1:36 PM, Craig Allen wrote: > > Just remember thought that if you threat Python like a > > hammer, suddenly everything will look like a bail. > > > > don't you mean if you use Python like a pitchfork? Or that everything else looks like a nail. B and N are right next to each other, so that seems more likely to me. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sun Dec 14 20:55:33 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Dec 2008 01:55:33 GMT Subject: execution time References: Message-ID: <0155b08d$0$6988$c3e8da3@news.astraweb.com> On Sun, 14 Dec 2008 18:35:24 +0100, Andreas Kostyrka wrote: > On Sun, Dec 14, 2008 at 05:03:38PM +0100, David Hl??ik wrote: >> Hi guys, >> >> #! /usr/bin/python >> >> import random >> import bucket2 >> >> data = [ random.randint(1,25) for i in range(5)] print "random data : >> %s" % data >> print "result: %s" %bucket2.sort(data) >> >> How to write a test script which will outputs execution time for >> bucket2.sort(data) ? > > Well: > > import time > > starttime = time.time() > > .... > > endtime = time.time() > print "Whatever .... does, it took %5.3fs to do." % (endtime - > starttime) Is subject to lots of timing errors for small code snippets. Sorting five numbers is (probably) going to be very quick, so the random timing errors will probably be larger than the time it actually takes to sort! Just for reference, here's the size of errors from timing naively on my machine: def timer(alist): from time import time t = time() alist.sort() return time() - t def make_list(): from random import random return [random() for i in range(5)] data = [timer(make_list()) for i in range(100)] mean = sum(data)/len(data) average_error = sum(abs(x-mean) for x in data)/len(data) print "The average timing is %f seconds." % mean print "The average error is %f seconds." % average_error print "Percentage error: %f%%" % (average_error/mean*100) And here is the output: The average timing is 0.000050 seconds. The average error is 0.000089 seconds. Percentage error: 177.953157% What this tells us is that the likely error in any one timing of a small code snippet using time.time() directly is so large that it is useless for anything other than the most crude measurements. Using time() on its own is a good example of "measure with micrometer, mark with chalk, cut with axe". This is precisely the problem the timeit module is written to solve. > Alternativly take a look at the timeit standard module. I'd reverse that recommendation: start with the timeit module first, and if and only if it is unsuitable, consider writing your own solution. -- Steven From skip.montanaro at gmail.com Tue Dec 9 16:40:44 2008 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Tue, 9 Dec 2008 13:40:44 -0800 (PST) Subject: Test posting #2 - please ignore Message-ID: This is another posting you can ignore. This time posted via Google Groups. Skip Montanaro From robert.kern at gmail.com Tue Dec 2 19:59:53 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 02 Dec 2008 18:59:53 -0600 Subject: problem with optparse In-Reply-To: References: Message-ID: Neal Becker wrote: > Robert Kern wrote: > >> Neal Becker wrote: >>> This example is right out of python library reference. What's wrong >>> here? >>> >>> import optparse >>> >>> def store_value(option, opt_str, value, parser): >>> setattr(parser.values, option.dest, value) >>> >>> parser = optparse.OptionParser() >>> parser.add_option("--foo", >>> action="callback", callback=store_value, >>> type="int", nargs=3, dest="foo") >>> >>> (opt,args) = parser.parse_args ('--foo a b c'.split()) >>> >>> [...] >>> /usr/lib64/python2.5/optparse.pyc in _process_args(self, largs, rargs, >>> values) >>> 1423 elif self.allow_interspersed_args: >>> 1424 largs.append(arg) >>> -> 1425 del rargs[0] >>> 1426 else: >>> 1427 return # stop now, leave this >>> arg in rargs >>> >>> TypeError: 'str' object doesn't support item deletion >> Dunno. It works for me (i.e. I get the expected "error: option --foo: >> invalid integer value: 'a'"). Have you tried it outside of IPython? >> > yes: > python test_opt.py > Traceback (most recent call last): > File "test_opt.py", line 12, in > (opt,args) = parser.parse_args ('--foo') Ah, that's different. parse_args() takes a list, not a string. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From igouy2 at yahoo.com Sat Dec 13 10:18:28 2008 From: igouy2 at yahoo.com (Isaac Gouy) Date: Sat, 13 Dec 2008 07:18:28 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <4942cc3c$0$21936$426a74cc@news.free.fr> Message-ID: <9927611c-d15e-43d9-96da-2fd28d4f464a@x16g2000prn.googlegroups.com> On Dec 12, 11:41?am, Bruno Desthuilliers wrote: > sturlamolden a ?crit : > (snip) > > > Creating a fast implementation of a dynamic language is almost rocket > > science. But it has been done. There is Stronghold, the fastest > > version of Smalltalk known to man, on which the Sun Java VM is based. > > On a recent benchmark Java 6 -server beats C compiled by GCC 4.2.3 > > cf bearophile's comment on this point (CPU architecture and RAM) > > > And > > most of that magic comes from an implementation of a dynamically typed > > language (Smalltalk). > > Err... Where is _Java_ "dynamic" actually ? A benchmark of _Smalltalk_ > VM vs CPython VM would make more sense. http://shootout.alioth.debian.org/u32/benchmark.php?test=all&lang=vw&lang2=python > > > Second, there are other fast implementations of dynamic languages. The > > CMUCL and SBCL versions of Common Lisp comes to min; you can see how > > SBCL does in the same benchmark (CMUCL tends to be even faster). > > Could it be that there are some type hints in the lisp versions of the > source code ? > > > So Python is a lot slower than it needs to be. > > Please fix it, you're welcome. From pavlovevidence at gmail.com Tue Dec 2 18:47:03 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 2 Dec 2008 15:47:03 -0800 (PST) Subject: optimization References: Message-ID: <442729e3-2735-4d8e-a701-48d3f3219eee@v15g2000yqn.googlegroups.com> On Dec 1, 11:41?am, Neal Becker wrote: > I guess I've become accustomed to decent compilers performing > reasonable transformations and so have tended to write code for > clarity. Python isn't that language. It'll do what it can, but a very aggressive optimizing compiler wouldn't be possible with Python's dynamicism, at least not without a lot of effort (both man and computer). Python does not actually compile the function every invocation, but it does create a function object from the compiled code object, which does take a bit of time. If it is a concern, run it through a profiler to get an idea of how much it costs, so you can make an informed decision. Carl Banks From toby at telegraphics.com.au Wed Dec 3 23:19:01 2008 From: toby at telegraphics.com.au (toby) Date: Wed, 3 Dec 2008 20:19:01 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> Message-ID: <4b6c3304-2396-4d35-a06f-e5d693cbbb12@f13g2000yqj.googlegroups.com> On Dec 3, 4:15 pm, Xah Lee wrote: > On Dec 3, 8:24 am, Jon Harrop wrote: > > > My example demonstrates several of Mathematica's fundamental limitations. > > enough babble Jon. > > Come flying $5 to my paypal account, and i'll give you real code, I'll give you $5 to go away --T From mu at problemlos.ch Fri Dec 19 04:04:34 2008 From: mu at problemlos.ch (Kurt Mueller) Date: Fri, 19 Dec 2008 10:04:34 +0100 Subject: Minor Typo in doc In-Reply-To: References: <494A5E14.10508@problemlos.ch> Message-ID: <494B63A2.6050803@problemlos.ch> Steve Holden schrieb: > Kurt Mueller wrote: >> Hi >> There is a minor typo in the new doc in: >> http://www.python.org/doc/2.6/library/signal.html >> ------------------------------------------------------------------ >> signal.SIG_DFL? >> This is one of two standard signal handling options; >> it will simply perform the default function for the signal. >> For example, on most systems the default action for SIGQUIT >> is to dump core and exit, while the default action for >> SIGCLD >> is to simply ignore it. >> ------------------------------------------------------------------ >> SIGCLD >> should be >> SIGCHLD >> Should I make a bug report in http://bugs.python.org > Yes. The documentation give you a link to follow from the bottom of > each page. > regards > Steve Yesterday evening I made a bug report on bugs.python.org. (I opened a issue). This morning it has already been fixed. (It has been assigned to benjamin.peterson. He has fixed it. The issue has been closed.) > Benjamin Peterson added the comment: > Thanks for the report! Fixed in r67848. > ---------- > nosy: +benjamin.peterson > resolution: -> fixed > status: open -> closed So, that is a great community! isn't it? Thanks to all who make this possible. Gr?essli -- Kurt Mueller -- Kurt M?ller, mu at problemlos.ch From castironpi at gmail.com Mon Dec 8 15:26:34 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 8 Dec 2008 12:26:34 -0800 (PST) Subject: Guido's new method definition idea References: <493a9fed$0$18973$426a34cc@news.free.fr> <493c1ff6$0$4942$426a34cc@news.free.fr> <49d12ec1-2be9-497b-80bc-9f0402a9086d@s20g2000yqh.googlegroups.com> Message-ID: <699ea750-8dd9-472f-a7aa-90492c32c519@z1g2000yqn.googlegroups.com> On Dec 7, 4:23?pm, Philip Slate wrote: > On Dec 7, 1:13?pm, Bruno Desthuilliers > > wrote: > > > and friendlier to newbies. > > > I'd rather say "more acceptable to java-brainwashed developpers". > > And I'd rather say you're trolling, but that's ok since you're > preaching to the converted. You conveniently forgot to mention the C++/ > Eiffel/Smalltalk/pretty-much-every-OO-lang "brainwashed" developers > too. In reality Python, with its kludgy OO and objects being > essentially glorified dicts, is the odd one out, not the other way > around. That's true. But what would a Python-brainwashed developer be? From skip at pobox.com Thu Dec 18 09:53:35 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 18 Dec 2008 08:53:35 -0600 Subject: something else instead of PIL? In-Reply-To: References: Message-ID: <18762.25583.71898.279331@montanaro-dyndns-org.local> Reimar> I am interested to get some new features added e.g. some special Reimar> conversion routines for colorblind people. Reimar> http://scien.stanford.edu/class/psych221/projects/05/ofidaner/colorblindness_project.htm Reimar> How can that be archieved? Contact Fredrik Lundh? http://effbot.org/ Skip From bakul+usenet at bitblocks.com Fri Dec 12 16:19:29 2008 From: bakul+usenet at bitblocks.com (Bakul Shah) Date: Fri, 12 Dec 2008 13:19:29 -0800 Subject: Mathematica 7 compares to other languages In-Reply-To: <6375k4pf1mleb6im67nkpec5olqbsom88e@4ax.com> References: <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <452ba58b-9377-4463-85e2-5ecdaa25a129@t39g2000prh.googlegroups.com> <6375k4pf1mleb6im67nkpec5olqbsom88e@4ax.com> Message-ID: <4942D561.5020203@bitblocks.com> George Neuner wrote: > On Thu, 11 Dec 2008 10:41:59 -0800 (PST), Xah Lee > wrote: > >> On Dec 10, 2:47 pm, John W Kennedy wrote: >>> Xah Lee wrote: >>>> In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, >>>> you'll have 50 or hundreds lines. >>> C: >>> >>> #include >>> #include >>> >>> void normal(int dim, float* x, float* a) { >>> float sum = 0.0f; >>> int i; >>> float divisor; >>> for (i = 0; i < dim; ++i) sum += x[i] * x[i]; >>> divisor = sqrt(sum); >>> for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; >>> >>> } >> i don't have experience coding C. > > Then why do you talk about it as if you know something? > >> The code above doesn't seems to satisfy the spec. > > It does. > >> The input should be just a vector, array, list, or >> whatever the lang supports. The output is the same >> datatype of the same dimension. > > C's native arrays are stored contiguously. Multidimensional arrays > can be accessed as a vector of length (dim1 * dim2 * ... * dimN). > > This code handles arrays of any dimensionality. The poorly named > argument 'dim' specifies the total number of elements in the array. > > George Only if the length in each dimension is known at compile time (or in C99, if this is an automatic array). When this is not the case, you may have to implement something like the following (not the only way, just one way): float** new_matrix(int rows, int cols) { float** m = malloc(sizeof(float*)*rows); int i; for (i = 0; i < rows; i++) m[i] = malloc(sizeof(float)*cols); return m; } In this case normal() fails since matrix m is not in a single contiguous area. But I suspect Xah is complaining because the function doesn't *return* a value of the same type; instead you have to pass in the result vector. But such is life if you code in C! From ron.reidy at gmail.com Mon Dec 15 07:59:50 2008 From: ron.reidy at gmail.com (ron.reidy at gmail.com) Date: Mon, 15 Dec 2008 04:59:50 -0800 (PST) Subject: cx_Oracle issues References: <5b2dad81-2750-4347-8079-6ab31321d579@s1g2000prg.googlegroups.com> <9142a8f1-7f76-4fc0-9ca1-c9dec310f2ce@r37g2000prr.googlegroups.com> <9f436c9e-2319-499c-a306-d255996372fc@e22g2000vbe.googlegroups.com> Message-ID: On Dec 15, 2:44?am, huw_at1 wrote: > On Dec 11, 5:34?pm, "ron.re... at gmail.com" wrote: > > > > > > > On Dec 10, 9:48?am, huw_at1 wrote: > > > > Hey all. When usingcx_Oracleto run a procedure like: > > > > cursor.execute("select (obj.function(value)) from table where > > > id=blah") > > > > I am getting the following error: > > > > ORA-06502: PL/SQL: numeric or value error: character string buffer too > > > small ORA-06512: at line 1 > > > > Looking at cursor.description I get: > > > > [('(obj.function(value))', , 4000, 4000, 0, > > > 0, 1)] > > > > Any tips - i have never seen this error before but am guessing that > > > the value being returned is too big for the buffer size set for the > > > cursor. the procedure fetches data from a LOB. > > > > Any suggestions/confirmations? > > > > Many thanks > > > This error is a problem with the PL/SQL, notcx_Oracle. ?You need to > > debug obj.function to see what kind of data is being accessed and then > > a data analysis of that data to understand why this error occurs. ?I > > can tell you the function is most likely expecting characters from a > > column that are numeric [0 .. 9] and is getting alpha characters. > > > -- > > Ron Reidy > > Sr. Oracle DBA > > Hi thanks for the responses. Unfortunately the procedure in question > is from a third party vendor so I can't really debug it so I'd say I > was fairly stumped. Just out of interest how do you increase the > output buffer size withcx_Oracle? > > Many thanks- Hide quoted text - > > - Show quoted text - Hi, Sure you can. You can see the PL/SQL source from the ditionary view ALL_SOURCE: select text from all_source where name = 'NAME_OF_FUNCTION'; >From there, reverse engineeer which table(s) and column(s) are being accesses and do the data analysis. -- Ron Reidy From Scott.Daniels at Acm.Org Wed Dec 24 14:19:03 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 24 Dec 2008 11:19:03 -0800 Subject: Strategy for determing difference between 2 very large dictionaries In-Reply-To: References: <1230102996.2303.1291616055@webmail.messagingengine.com> <1230106980.12156.1291620725@webmail.messagingengine.com> Message-ID: Gabriel Genellina wrote: > En Wed, 24 Dec 2008 06:23:00 -0200, escribi?: >> ... k1 = set(dict1.iterkeys()) > You've got an excelent explanation from Marc Rintsch. (Note that in > Python 3.0 keys() behaves as iterkeys() in previous versions, so the > above code is supposed to be written in Python 2.x) And, in fact, a dictionary iterates its keys, so: k1 = set(dict1) works in 2.4, 2.5, 2.6, and 3.0 --Scott David Daniels Scott.Daniels at Acm.Org From python.list at tim.thechases.com Sat Dec 13 21:23:53 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 13 Dec 2008 20:23:53 -0600 Subject: 1 or 1/0 doesn't raise an exception In-Reply-To: References: Message-ID: <49446E39.6020807@tim.thechases.com> > Is it a feature that > > 1 or 1/0 > > returns 1 and doesn't raise a ZeroDivisionError? If so, what's the rationale? Yes, it's a feature: http://en.wikipedia.org/wiki/Short-circuit_evaluation When you have "True or False", you know it's true by the time you've got the first piece, so there's no need to evaluate the 2nd piece. The opposite is helpful too: lst = [some list or an empty list] ... if lst and lst[0] == 42: This ensures that the "lst[0]" doesn't fail if lst is empty, because lst evaluating to false (an empty list) short-circuits preventing the evaluation of "lst[0]". -tkc From vschmidt13 at gmail.com Mon Dec 8 16:47:59 2008 From: vschmidt13 at gmail.com (Val) Date: Mon, 8 Dec 2008 13:47:59 -0800 (PST) Subject: easy_install of module produces un-importable result References: <6q5chbFast45U1@mid.uni-berlin.de> Message-ID: <352dc248-600b-4415-9354-cb1aab5f6889@41g2000yqf.googlegroups.com> On Dec 8, 2:57?pm, "Diez B. Roggisch" wrote: > Val schrieb:> I've written my first module, " > > " and uploaded it as an egg to > > > PyPI. I can use easy_istall to install my own module, but when I try > > to import it I get an ImportError "No module named gpsparser". > > > So I've done some research and found that in my site-packages/ > > directory gpsparser exists as an egg file, while all the other > > packages I've installed exist as an egg directory. > > > If this makes any sense, can anyone explain what I've done wrong in > > building my package that the installation process does not unpack the > > egg file? > > This has nothing to do with that - it's simply that your egg is empty. > Take a look at this: > > (gpsparser)mac-dir:Application Support deets$ unzip -l > /Users/deets/.virtualenvs/gpsparser/lib/python2.5/site-packages/gpsparser-0 .0.1-py2.5.egg > Archive: > /Users/deets/.virtualenvs/gpsparser/lib/python2.5/site-packages/gpsparser-0 .0.1-py2.5.egg > ? ?Length ? ? Date ? Time ? ?Name > ? -------- ? ?---- ? ---- ? ?---- > ? ? ? ? ?1 ?12-08-08 12:04 ? EGG-INFO/dependency_links.txt > ? ? ? ?249 ?12-08-08 12:04 ? EGG-INFO/PKG-INFO > ? ? ? ?599 ?12-08-08 12:04 ? EGG-INFO/SOURCES.txt > ? ? ? ? ?1 ?12-08-08 12:04 ? EGG-INFO/top_level.txt > ? ? ? ? ?1 ?12-08-08 11:25 ? EGG-INFO/zip-safe > ? -------- ? ? ? ? ? ? ? ? ? ------- > ? ? ? ?851 ? ? ? ? ? ? ? ? ? 5 files > (gpsparser)mac-dir:Application Support deets$ > > I presume you miss a > > ? ? ?packages=find_packages(), > > line in your setup.py, with > > from setuptools import setup, find_packages > > to actually get the find_packages. > > Diez You are absolutely right. How embarrassing. Thank you SO much! -Val From castironpi at gmail.com Tue Dec 2 21:13:56 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 2 Dec 2008 18:13:56 -0800 (PST) Subject: Overriding a method at the instance level on a subclass of a builtin type References: Message-ID: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> On Dec 2, 6:58?pm, "Zac Burns" wrote: > Sorry for the long subject. > > I'm trying to create a subclass dictionary that runs extra init code > on the first __getitem__ call. However, the performance of __getitem__ > is quite important - so I'm trying in the subclassed __getitem__ > method to first run some code and then patch in the original dict > method for the instance to avoid even the check to see if the init > code has been run. Various recipes using instancemethod and the like > have failed me. > > Curiously if __slots__ is not specified no error occurs when setting > self.__getitem__ but the function is not overriden. If __slots__ is > ['__getitem__'] however it complains that __getitem__ is read only. I > do not understand that behavior. > > -- > Zachary Burns > (407)590-4814 > Aim - Zac256FL > Production Engineer (Digital Overlord) > Zindagi Games That sounds like the State Pattern, from GoF. http://en.wikipedia.org/wiki/State_pattern I like the idea of 'renaming', not redefining, but reassigning methods at different points during an object's lifetime. I often wish I had more experience with it, and more docs talked about it. It's hard on memory usage, since each instance has its own function attribute, even if there's still only one instance of the function. Without it, the function attribute is just looked up on the class. Not thoroughly tested: >>> class A: ... def methA( self ): ... print 'methA' ... self.meth= self.methB ... meth= methA ... def methB( self ): ... print 'methB' ... >>> a= A() >>> a.meth() methA >>> a.meth() methB From akineko at gmail.com Mon Dec 22 16:13:08 2008 From: akineko at gmail.com (akineko) Date: Mon, 22 Dec 2008 13:13:08 -0800 (PST) Subject: 64-bit / 128-bit data element type for array? References: Message-ID: <880c8478-8b40-40e0-8597-aef960612f09@s9g2000prg.googlegroups.com> Hello, bearophile and Robert, thank you for your prompt response. I will try NumPy (this is a good execuse to learn and to use a new package). > I haven't seen uint128 in the wild, though. Of course, not many applications require uinit128 as a scalar value. I may need to deal with 128-bit data as it is now not uncommon to have 128-bit data bus (or even 256-bit wide and beyond) in ASICs (microchip) design. Unfortunately, some designs use big-endian and others use little-endian ... Thank you and Happy Holidays! Aki Niimura On Dec 22, 11:26 am, Robert Kern wrote: > akineko wrote: > > Hello everyone, > > > I need to handle binary files that contain 64-bit (or 128-bit in the > > furture) unsigned int data. > > Python's array seems not supporting unsigned int type beyond 32-bit > > ('L'). > > I would like to use Python array as I need to make my program work on > > both big-endian machines as well as on little-endian machines. > > > What is the best way to deal with 64-bit / 128-bit data elements in > > Python (must support byteswap())? > > (must be machine-independent) > > You might give numpy a try. We support uint64 data even on 32-bit machines > provided that your C compiler does. I haven't seen uint128 in the wild, though. > > http://numpy.scipy.org/ > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco From rhf22 at mole.bio.cam.ac.uk Sun Dec 7 08:03:43 2008 From: rhf22 at mole.bio.cam.ac.uk (Rasmus Fogh) Date: Sun, 7 Dec 2008 13:03:43 +0000 (GMT) Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Jamed Stroud Wrote: > Rasmus Fogh wrote: >> Dear All, >> For the first time I have come across a Python feature that seems >> completely wrong. After the introduction of rich comparisons, equality >> comparison does not have to return a truth value, and may indeed return >> nothing at all and throw an error instead. As a result, code like >> if foo == bar: >> or >> foo in alist >> cannot be relied on to work. >> This is clearly no accident. According to the documentation all >> comparison operators are allowed to return non-booleans, or to throw >> errors. There is >> explicitly no guarantee that x == x is True. > I'm not a computer scientist, so my language and perspective on the > topic may be a bit naive, but I'll try to demonstrate my caveman > understanding example. > First, here is why the ability to throw an error is a feature: > class Apple(object): > def __init__(self, appleness): > self.appleness = appleness > def __cmp__(self, other): > assert isinstance(other, Apple), 'must compare apples to apples' > return cmp(self.appleness, other.appleness) > class Orange(object): pass > Apple(42) == Orange() True, but that does not hold for __eq__, only for __cmp__, and for__gt__, __le__, etc. Consider: Class Apple(object): def __init__(self, appleness): self.appleness = appleness def __gt__(self, other): assert isinstance(other, Apple), 'must compare apples to apples' return (self.appleness > other.appleness) def __eq__(self, other): if isinstance(other, Apple): return (self.appleness == other.appleness) else: return False > Second, consider that any value in python also evaluates to a truth > value in boolean context. > > Third, every function returns something. A function's returning nothing > is not a possibility in the python language. None is something but > evaluates to False in boolean context. Indeed. The requirement would be not that return_value was a boolean, but that bool(return_value) was defined and gave the correct result. I understand that in some old Numeric/numpy version the numpy array __eq__ function returned a non-empty array, so that bool(numarray1 == numarray2) was true for any pair of arguments, which is one way of breaking '=='. In current numpy, even bool(numarray1 == 1) throws an error, which is another way of breaking '=='. >> But surely you can define an equal/unequal classification for all >> types of object, if you want to? > This reminds me of complex numbers: would 4 + 4i be equal to sqrt(32)? > Even in the realm of pure mathematics, the generality of objects (i.e. > numbers) can not be assumed. It sounds like that problem is simpler in computing. sqrt(32) evaluates to 5.6568542494923806 on my computer. A complex number c with non-zero imaginary part would be unequal to sqrt(32) even if it so happened that c*c==32. Yours, Rasmus --------------------------------------------------------------------------- Dr. Rasmus H. Fogh Email: r.h.fogh at bioc.cam.ac.uk Dept. of Biochemistry, University of Cambridge, 80 Tennis Court Road, Cambridge CB2 1GA, UK. FAX (01223)766002 From goldnery at gmail.com Tue Dec 30 16:22:19 2008 From: goldnery at gmail.com (Gandalf) Date: Tue, 30 Dec 2008 13:22:19 -0800 (PST) Subject: win32gui Message-ID: I'm searching the win32gui hooks for a function to get the windowClass position any idea? thanks! From akineko at gmail.com Mon Dec 29 15:23:15 2008 From: akineko at gmail.com (akineko) Date: Mon, 29 Dec 2008 12:23:15 -0800 (PST) Subject: tkInter constraining the width only Message-ID: Hello everyone, I'm writing a Tkinter program and trying to constraint the window size. I want to set the minimum of the width and the height and the maximum of the width, but not the height. I can use minsize(width=min_width, height=min_height) from Wm method to limit the minimum sizes. Similarly I thought I could use maxsize(width=max_width, height=None) to limit the maximum sizes. Unfortunately, it didn't work. maxsize() complained if only width is given. Is there any easy way to constraint a Tkinter window so that the sizes are set except it can grow vertically. Any suggestions are greatly appreciated. Best regards, Aki Niimura From george.sakkis at gmail.com Wed Dec 10 12:21:14 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 10 Dec 2008 09:21:14 -0800 (PST) Subject: Best way to report progress at fixed intervals References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> <817384d5-5f68-4c1f-9560-0bc7b7d2b1e3@v5g2000prm.googlegroups.com> <6ccb77a2-a3f1-4b6b-900c-d4626be9e939@s1g2000prg.googlegroups.com> Message-ID: On Dec 10, 2:50?am, Slaunger wrote: > > Sorry, apparently I did not realize that at first sight. Anyway, I'd > rather avoid using further external modules besides the standard > batteries, as I would have to update several workstations with > different OSes (some of which I do not have admin access to) to use > the new module. How is this different from writing your own module from scratch ? You don't need admin access to use a 3rd party package. George From jstroud at mbi.ucla.edu Sun Dec 7 03:47:13 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 07 Dec 2008 00:47:13 -0800 Subject: Brain going crazy with recursive functions In-Reply-To: References: <181d6cf8-8df3-46d4-9d21-197d34b3de87@d36g2000prf.googlegroups.com> Message-ID: James Stroud wrote: > def linear_search(array, truth_func, loc=(0,0)): > idx1, idx2 = loc > if idx1 >= len(array): > return None > if idx2 >= len(array[idx1]): > return linear_search(array, truth_func, (idx1+1, 0)) > value = array[idx1][idx2] > tf = truth_func(value) > if tf: > return loc > else: > return linear_search(array, truth_func, (idx1, idx2+1)) > > a = [[5, 3, 4], [2, 0, 1], [8, 6, 7]] > linear_search(a, lambda x: x==0) PS: If I just made it to easy for you, you can practice by generalizing this to an N-dimensional array using recursion. I'm tempted to do it myself but I'm going to try to resist instead and do some work that pays. From sjmachin at lexicon.net Thu Dec 11 22:43:53 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 11 Dec 2008 19:43:53 -0800 (PST) Subject: newbie question: if var1 == var2: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> <44aa0191-e374-4bf0-b039-d05cfa996b1d@p2g2000prn.googlegroups.com> <37fc3229-b0a2-4d95-990f-61300fc2b257@r37g2000prr.googlegroups.com> Message-ID: <4977851c-40ea-4397-99ee-f7a343cba73e@z28g2000prd.googlegroups.com> On Dec 12, 1:11?pm, MRAB wrote: > John Machin wrote: > > On Dec 12, 11:39 am, MRAB wrote: > >> Jason Scheirer wrote: > >>> On Dec 11, 3:49 pm, John Machin wrote: > >>>> On Dec 12, 10:31 am, "Rhodri James" > >>>> wrote: > >>>>> On Thu, 11 Dec 2008 19:49:23 -0000, Steve Holden ? > >>>>> wrote: > >>>>>> Kirk Strauser wrote: > >>>>>>> At 2008-11-29T04:02:11Z, Mel writes: > >>>>>>>> You could try > >>>>>>>> for item in fname: > >>>>>>>> ? ? item = item.strip() > >>>>>>> This is one case where I really miss Perl's "chomp" function. ?It ? > >>>>>>> removes a > >>>>>>> trailing newline and nothing else, so you don't have to worry about ? > >>>>>>> losing > >>>>>>> leading or trailing spaces if those are important to you. > >>>>>> ... and it's so hard to write > >>>>>> ? ? ?item = item[:-1] > >>>>> Tsk. ?That would be "chop". ?"chomp" would be > >>>>> ? ? ?if item[-1] == '\n': > >>>>> ? ? ? ? ?item = item[:-1] > >>>> Better: > >>>> if item and item[-1] == '\n': > >>>> ? ? return item[:-1] > >>>> return item > >>> Best: > >>> return item \ > >>> ? ? ? ?if not (item and item.endswith('\n')) \ > >>> ? ? ? ?else item[:-1] > >>> Though really you should be using item.rstrip() > >> Why not just: > > >> ? ? ?item[:-1] if item.endswith('\n') else item > > > Some possible reasons: > > * because you might be supporting old versions of Python (my offering > > runs on 1.5) > > * because the " if else " syntax > > gives you the screaming dry Edgar Britts > > * because you'd prefer not to have the overhead of a method lookup and > > method call > > OK: > > ? ? ?if item[-1:] == '\n': > ? ? ? ? ?return item[:-1] > ? ? ?return item I'll pay that :-) From steven at REMOVE.THIS.cybersource.com.au Mon Dec 8 21:45:17 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 09 Dec 2008 02:45:17 GMT Subject: Rich Comparisons Gotcha References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> <014c55e9$0$20670$c3e8da3@news.astraweb.com> <11d8b41a-a910-4915-8969-fc90e978350b@j11g2000yqg.googlegroups.com> Message-ID: On Sun, 07 Dec 2008 16:24:58 -0800, George Sakkis wrote: > On Dec 7, 6:37?pm, Steven D'Aprano cybersource.com.au> wrote: ... >> Given: >> >> x = log(-5) ?# a NaN >> y = log(-2) ?# the same NaN >> x == y ?# Some people want this to be true for NaNs. >> >> Then: >> >> # Compare x and y directly. >> log(-5) == log(-2) >> # If x == y then exp(x) == exp(y) for all x, y. exp(log(-5)) == >> exp(log(-2)) >> -5 == -2 >> >> and now the entire foundations of mathematics collapses into a steaming >> pile of rubble. > > And why doesn't this happen with the current behavior if x = y = log > (-5) ? According to the same proof, -5 != -5. You're right, I was a little sloppy in my "proof". There are additional subtleties going on. -- Steven From rdmurray at bitdance.com Wed Dec 17 21:36:57 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Thu, 18 Dec 2008 02:36:57 +0000 (UTC) Subject: getting object instead of string from dir() References: <1bb0df81-380c-46eb-a3aa-863c468c6aff@x14g2000yqk.googlegroups.com> Message-ID: Quoth Rominsky : > vars seems to give an identical response as locals and globals, at > least in my test name space. All three are new commands for me. I Without arguments vars() returns the same thing as locals(). > like the idea of adopting either vars or locals instead of dir as it > sets up the value for me to use. I will play with them both a little > more and read up on them to learn there uses and limitations. The key > step for me is still to be able to automatically query the key names > from vars or locals for what type the variable is. In my previous > post I discussed using eval and the string in the key name such as > > eval('type(%s)'%vars().keys()[0]) >>> eval('type(%s)'%vars().keys()[0]) >>> vars().keys()[0] '__builtins__' >>> vars().values()[0] >>> type(vars().values()[0]) >>> for name, obj in vars().items(): ... print "%s (%s)" % (name, type(obj)) ... __builtins__ () __name__ () __doc__ () __package__ () From prologic at shortcircuit.net.au Mon Dec 22 00:46:29 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Dec 2008 15:46:29 +1000 Subject: Twisted for non-networking applications In-Reply-To: <9faa4fa5-6fd1-4ebb-bf1b-382a7d74ba0a@d42g2000prb.googlegroups.com> References: <82e49b84-43c9-452f-a139-c77378c12908@a12g2000pro.googlegroups.com> <9faa4fa5-6fd1-4ebb-bf1b-382a7d74ba0a@d42g2000prb.googlegroups.com> Message-ID: On Mon, Dec 22, 2008 at 3:25 PM, RajNewbie wrote: > I was unable to see documentation explaining this - so asking again. Documentation is available here: http://trac.softcircuit.com.au/circuits/wiki/docs And here: pydoc circuits The code itself is heavily documented. I'm still writing better online references, tutorials and what not ... :) Please see the examples/ > Suppose the event handlers in the component is doing blocking work, > how is it handled? You have a few options. 1. Do your work in a thread. 2. Do your work in a process. You could utilize the Worker component for such things. I'm also building a Process component that uses the multiprocessing module. > I went through ciruits.core, but was unable to understand exactly how > blocking mechanisms are handled. They aren't. It's up to you to handle such situations. If your "event-handler" blocks, everything, it will block every other event handler from being processes. In what situation would you have this ? I'm curious :) > My scenario is as follows: > I have 4 loops, 1 small and high priority, 3 quite large and blocking > (takes upto 3 seconds) and comparatively low priority. > The small loops goes through everytime and does some work - and > optionally uses the data sent by the other 3 loops. > I do not want the smaller loop to get blocked by the other loops. This sounds complex :) What is your application ? What's being processes ? > So, if the event handler does blocking work, can that cause the whole > loop to block? Yes. If you decide to use circuits, I suggest you restructure your program. Try to do your work (if it's blocking) in Worker components (threads). cheers James From christophedeze at gmail.com Tue Dec 23 04:36:56 2008 From: christophedeze at gmail.com (Toff) Date: Tue, 23 Dec 2008 01:36:56 -0800 (PST) Subject: join a samba domain References: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> <494fd597$0$90267$14726298@news.sunsite.dk> <73194a24-f14e-46f1-8789-886ba4729084@r15g2000prd.googlegroups.com> <1a326512-3c74-404d-9c51-fde35f39702e@t39g2000prh.googlegroups.com> Message-ID: Or maybe could I try with LoadLibrary("netapi32.dll"); and the netjoindomain function ? but it doesn't look very easy .... From zaz600 at gmail.com Wed Dec 24 10:09:30 2008 From: zaz600 at gmail.com (NoName) Date: Wed, 24 Dec 2008 07:09:30 -0800 (PST) Subject: SyntaxError: encoding problem: with BOM References: <6res8tF1do1sU1@mid.uni-berlin.de> Message-ID: <400f176b-bd9a-4f26-b01b-1aa7c7dcf5ac@z6g2000pre.googlegroups.com> On 25 ???, 00:37, "Diez B. Roggisch" wrote: > NoName schrieb: > > > i have 1.py in cp866 encoding: > > > # -*- coding: cp866 -*- > > print ("ff") > > > It's not work in Python 3.0 > > Error: > > > File "", line 1 > > SyntaxError: encoding problem: with BOM > > > what's wrong? > > I can only guess, but just because you write the coding-header that > doesn't mean that the editor you use does actually *use* that encoding. > What I presume it does is to use utf-8, and write that stupid BOM > microsoft uses for denoting utf-8-content as first byte. Try using a > different editor, or alter it's settings to really use your desired > encoding. > > Diez I used Far Manager editor. and it *really* used cp866 I can print hex dump of source file. I don't want to use UTF-8 for py-file! From clp at rebertia.com Tue Dec 2 18:22:41 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 2 Dec 2008 15:22:41 -0800 Subject: Simple ini Config parser examples needed In-Reply-To: <4935BBE5.3020607@g.nevcal.com> References: <47c890dc0812021331m1fe3f420kce9bcb07df5ae44e@mail.gmail.com> <4935BBE5.3020607@g.nevcal.com> Message-ID: <47c890dc0812021522g7f42b00o2a831bac1e15aa05@mail.gmail.com> On Tue, Dec 2, 2008 at 2:51 PM, Glenn Linderman wrote: > On approximately 12/2/2008 1:31 PM, came the following characters from the > keyboard of Chris Rebert: >> >> On Tue, Dec 2, 2008 at 1:18 PM, RON BRENNAN >> wrote: >> >>> >>> Hello, >>> >>> I have a very simple ini file that I needs parsed. What is the best way >>> I >>> can parse an ini file that doesn't include sections? *Bangs head against wall repeatedly* I merely glossed the question and missed that all-important second sentence! fsck! My apologies, I shouldn't write email before having coffee :) Fortunately Tim followed quickly with the correct answer to the OP. - Chris >>> >>> As in: >>> >>> >> >> Since it appears that ConfigParser requires at least one section >> header, I'll assume the file starts with the following line: >> >> [main] >> >>> >>> person=tall >>> height=small >>> shoes=big >>> >>> >>> Thats it. Can anyone help me? >>> >> >> Completely untested: >> >> import ConfigParser >> config = ConfigParser.RawConfigParser() >> config.readfp(open("path/to/file.cfg")) >> config.get("main", "height") #==> "small" >> >> Cheers, >> Chris >> > > Of course the OP question was that the line you assume isn't there. But if > the ini is simple, maybe it is short enough to read into a string, then > prepend the line, then parse with ConfigParser. > > -- > Glenn -- http://nevcal.com/ > =========================== > A protocol is complete when there is nothing left to remove. > -- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking > > -- Follow the path of the Iguana... http://rebertia.com From duncan.booth at invalid.invalid Tue Dec 9 08:05:36 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Dec 2008 13:05:36 GMT Subject: how to get a beep, OS independent ? References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> <6q6jf8Fau4iiU2@mid.individual.net> Message-ID: greg wrote: > Duncan Booth wrote: >> If I'm logged in to one of my servers in a large datacentre then I >> don't what that system to beep as that would be pretty useless. > > It also might cause the datacentre operators some consternation > when one of their servers starts mysteriously beeping... > That could be fun, especially if I can have a proximity sensor so I can stop the beeping whenever someone comes near the rack. :^) -- Duncan Booth http://kupuguy.blogspot.com From googler.1.webmaster at spamgourmet.com Fri Dec 5 03:26:58 2008 From: googler.1.webmaster at spamgourmet.com (googler.1.webmaster at spamgourmet.com) Date: Fri, 5 Dec 2008 00:26:58 -0800 (PST) Subject: Python C API Message-ID: <54fbb55d-3c39-459d-86a3-302b69721f0f@s20g2000yqh.googlegroups.com> Hi :) I have a main() function of my app which intializes the Python Interpreter and some other stuff. When I am finished I call: PyGILState state = PyGILState_Ensure() //call PyRun_String() PyGILStateRelease(state); The first question is, I found out the API contains other commands lik PyEval_AcquireLock(). I don't really understand if I have to use them too, could anyone explain? Thanks. Okay, back to topic. In PyRun_String() I call a wrapped function. This wrapped function does some internal calculations and takes a pointer to another function which is called in another thread while it calculates the stuff. void MyProgressbar(Real p, void* hook) // this function wil be called in another thread { PyGILState_STATE gilstate = PyGILState_Ensure(); PyObject* func = (PyObject*)hook; //do some python stuff PyGILState_Release(gilstate) } PyObject *pyMyFunction(PyObject *pSelf, PyObject *args, PyObject *keywords) { static char *kwlist[] = {"hook", NULL}; PyObject *hook=NULL; if (!PyArg_ParseTupleAndKeywords(args, keywords, "O!", kwlist, &PyFunction_Type, &hook)) return NULL; LONG ok = MyFunction(myprogress, hook); //hook is a pointer which is passed to the threaded function. Py_RETURN_INT(ok); } I want to do the same in Python. I want to pass a reference of a function to the function which is called from the other thread. But it stops (not crash) here: PyGILState_STATE gilstate = PyGILState_Ensure (); What can I do? Thank you very much. From zxo102 at gmail.com Mon Dec 29 00:08:12 2008 From: zxo102 at gmail.com (zxo102) Date: Sun, 28 Dec 2008 21:08:12 -0800 (PST) Subject: How to display Chinese in a list retrieved from database via python References: <22be506d-91c2-4727-ace7-2e3382b6d214@g3g2000pre.googlegroups.com> <979fdf6d-0500-47ba-87fd-0f0361ca3059@p2g2000prf.googlegroups.com> <19680ed2-c78f-4ab9-8ca0-8ce26fd5b6a7@o4g2000pra.googlegroups.com> Message-ID: <2560a6e0-c103-46d2-aa5a-8604de4d1968@b38g2000prf.googlegroups.com> On 12?27?, ??4?08?, "Gabriel Genellina" wrote: > En Sat, 27 Dec 2008 03:03:24 -0200,zxo102 escribi?: > > > > > On 12?26?, ??3?16?, "Mark Tolonen" ? > > wrote: > > >> I was able to display ?? successfully with this code: > > >> f=open('test.html','wt') > >> f.write(''' > >> > >> test > >> \xd6\xd0\xce\xc4''') > >> f.close() > > > Mark, > > ? ?I have exactly copied your code into the htdocs of my Apache > > server, > > > > > > > test > > \xd6\xd0\xce\xc4 > > > but it still shows me \xd6\xd0\xce\xc4. Any ideas? > > That's not the same thing as Mark T. said. > The original was Python code to *write* a test file that you could open in > a browser. Things like "\xd6\xd0" are escape sequences interpreted by > Python, not meant to literally appear in a file. Like \n -- it means > "start a new line", one wants a new line in the output, *not* a backslash > and a letter n. "\xd6\xd0" generate *two* bytes, not eight. If the file is ? > interpreted as containing latin-1 characters, you see them as ??. But due ? > to the "charset=gb2312" line, those two bytes together make the ideograph ? > ?. > > So, write the Python code (from f=open... up to f.close()) in a file and > execute it. Then open the generated test.html file. You should see the two > ideographs. > > -- > Gabriel Genellina Thanks for your explanation. The example works now. It is close to my real case. I have a list in a dictionary and want to insert it into the html file. I test it with following scripts of CASE 1, CASE 2 and CASE 3. I can see "??" in CASE 1 but that is not what I want. CASE 2 does not show me correct things. So, in CASE 3, I hacked the script of CASE 2 with a function: conv_list2str() to 'convert' the list into a string. CASE 3 can show me "??". I don't know what is wrong with CASE 2 and what is right with CASE 3. Without knowing why, I have just hard coded my python application following CASE 3 for displaying Chinese characters from a list in a dictionary in my web application. Any ideas? Happy a New Year: 2009 ouyang CASE 1: ######################################################## f=open('test.html','wt') f.write(''' test ''') f.close() CASE 2: ####################################################### mydict = {} mydict['JUNK'] = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce \xc4'] f_str = ''' test ''' f_str = f_str%mydict f=open('test02.html','wt') f.write(f_str) f.close() CASE 3: ################################################### mydict = {} mydict['JUNK'] = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce \xc4'] f_str = ''' test ''' import string def conv_list2str(value): list_len = len(value) list_str = "[" for ii in range(list_len): list_str += '"'+string.strip(str(value[ii])) + '"' if ii != list_len-1: list_str += "," list_str += "]" return list_str mydict['JUNK'] = conv_list2str(mydict['JUNK']) f_str = f_str%mydict f=open('test03.html','wt') f.write(f_str) f.close() From rhamph at gmail.com Mon Dec 8 14:32:18 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 8 Dec 2008 11:32:18 -0800 (PST) Subject: Rich Comparisons Gotcha References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Dec 8, 11:54?am, Robert Kern wrote: > Rhamphoryncus wrote: > > On Dec 7, 4:20 pm, Steven D'Aprano > cybersource.com.au> wrote: > >> On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: > >>> Rasmus Fogh wrote: > >>>> Current behaviour is both inconsistent and counterintuitive, as these > >>>> examples show. > >>>>>>> x = float('NaN') > >>>>>>> x == x > >>>> False > >>> Blame IEEE for that one. Rich comparisons have nothing to do with that > >>> one. > >> There is nothing to blame them for. This is the correct behaviour. NaNs > >> should *not* compare equal to themselves, that's mathematically > >> incoherent. > > > Mathematically, NaNs shouldn't be comparable at all. ?They should > > raise an exception when compared. ?In fact, they should raise an > > exception when *created*. ?But that's not what we want. ?What we want > > is a dummy value that silently plods through our calculations. ?For a > > dummy value it seems a lot more sense to pick an arbitrary yet > > consistent sort order (I suggest just above -Inf), rather than quietly > > screwing up the sort. > > Well, there are explicitly two kinds of NaNs: signalling NaNs and quiet NaNs, to > accommodate both requirements. Additionally, there is significant flexibility in > trapping the signals. Right, but most of that's lower level. By the time it reaches Python we only care about quiet NaNs. > > Regarding the mythical IEEE 754, although it's extremely rare to find > > quotations, I have one on just this subject. ?And it does NOT say "x > > == NaN gives false". ?It says it gives *unordered*. ?It is C and > > probably most other languages that turn that into false (as they want > > a dummy value, not an error.) > > >http://groups.google.ca/group/sci.math.num-analysis/browse_thread/thr... > > Table 4 on page 9 of the standard is pretty clear on the subject. When the two > operands are unordered, the operator == returns False. The standard defines how > to do comparisons notionally; two operands can be "greater than", "less than", > "equal" or "unordered". It then goes on to map these notional concepts to > programming language boolean predicates. Ahh, interesting. Still though, does it give an explanation for such behaviour, or use cases? There must be some situation where blindly returning false is enough benefit to trump screwing up sorting. From google at mrabarnett.plus.com Sat Dec 6 12:54:55 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 06 Dec 2008 17:54:55 +0000 Subject: "as" keyword woes In-Reply-To: <88579d9a-df52-49b9-a6fe-53c8f4524bf3@j39g2000yqn.googlegroups.com> References: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> <0147dc24$0$20670$c3e8da3@news.astraweb.com> <0148b217$0$20670$c3e8da3@news.astraweb.com> <7d0lj4d9hai2f87r30erc4l1ir85osbfg7@4ax.com> <88579d9a-df52-49b9-a6fe-53c8f4524bf3@j39g2000yqn.googlegroups.com> Message-ID: <493ABC6F.5090501@mrabarnett.plus.com> Mensanator wrote: > On Dec 6, 8:16?am, Wolfgang Strobl wrote: >> Dennis Lee Bieber : >> >>> On 05 Dec 2008 05:21:25 GMT, Steven D'Aprano >>> declaimed the following in >>> comp.lang.python: >>>> On Thu, 04 Dec 2008 08:44:19 -0800, Matimus wrote: >>>>> The point was that there >>>>> is that new releases don't _break_ anything. >>>> But that's clearly not true, because the OP is pointing out that the new >>>> release from 2.5 to 2.6 *does* break his code. >>> ? ?One now has to ask what "break" really meant... For this example, >>> the change did not break Python SYNTAX -- just a complaint about using >>> what is now a reserved word as an object name. >> Of course it does: >> >> C:\Python26>python >> Python 2.6 (r26:66721, Oct ?2 2008, 11:35:03) [MSC v.1500 32 bit >> (Intel)] on win 32 >> Type "help", "copyright", "credits" or "license" for more information.>>> as=2 >> >> ? File "", line 1 >> ? ? as=2 >> ? ? ?^ >> SyntaxError: invalid syntax > > I disagree. "Broken" is something you can't work > around. In this case, simply saying as_=2 works fine. > > A better example of broken was when the gmpy module > wouldn't solve a certain linear congruence problem > because the problem was not invertible. But > mathematically, solving a linear congruence does > NOT depend on the problem being invertible. It was > the ALGORITHM that depended on the problem being > invertible and there was nothing the user could do > to make the algorithm behave properly. The algorithm > had to be altered to fix the special case of a > solvable linear congruence not being invertible. > >> >> >> Making a former syntactically valid ?two letter name a reserved word in >> 2.6 was a mistake, IMHO. > > I think you're in the minority there. > I think that its special use is clear from the syntax, so IMHO it could've been left for Python 3, but I'm not going to lose any sleep over it. >> What's next? What about making i,j,k, x and y >> reserved words in 2.7? =:-/ > > Yeah, right. That'll happen. You ought to be more > concerned about real problems. > From Sengly.Heng at gmail.com Tue Dec 23 06:58:24 2008 From: Sengly.Heng at gmail.com (Sengly) Date: Tue, 23 Dec 2008 03:58:24 -0800 (PST) Subject: Very basic question References: <21ab1917-f0c9-48fb-baa9-02e5bf229bf5@s9g2000prm.googlegroups.com> <38f6b145-8615-4bcc-88f6-1988f9a7f68f@q30g2000prq.googlegroups.com> Message-ID: <91ccfbbd-806c-4770-a121-597df3f4aff3@r10g2000prf.googlegroups.com> Thank you very much everyone. Regards, -- Sengly From bdesth.quelquechose at free.quelquepart.fr Mon Dec 15 16:27:27 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 15 Dec 2008 22:27:27 +0100 Subject: %s place holder does not let me insert ' in an sql query with python. In-Reply-To: References: <1229345178.31093.24.camel@krishna-laptop> <1229348763.31093.38.camel@krishna-laptop> Message-ID: <4946d975$0$15020$426a74cc@news.free.fr> Joe Strout a ?crit : > On Dec 15, 2008, at 6:46 AM, Krishnakant wrote: > >> in this case, I get a problem when there is ' in any of the values >> during insert or update. > > That's because ' is the SQL string literal delimiter. But any > SQL-compliant database allows you to "escape" an apostrophe within a > string literal by doubling it. So for each of your values, just do: > > value = value.replace("'", "''") > > before stuffing them into your INSERT or UPDATE statement. (If these > values come from the user, and especially if they come over the network, > then you probably want to do a few other replacements; google "SQL > injection" for details.) Or just learn to make proper use of the db-api, ie use cursor.execute( "select yadda from mytable where foo=%s or bar=%s", (foo, bar) ) NB : replace '%s' with '?' or whatever is the correct placeholder for you particular db-api connector. From brendandetracey at yahoo.com Fri Dec 12 09:46:38 2008 From: brendandetracey at yahoo.com (Brendan) Date: Fri, 12 Dec 2008 06:46:38 -0800 (PST) Subject: Reading online zip files - zipfile and zlib, wbits References: Message-ID: <21ba0ff5-7698-481a-851c-80b9ddcd5814@q26g2000prq.googlegroups.com> On Dec 12, 10:25?am, Brendan wrote: > I am fooling around with accessing contents of zip files online. I > download the tail end of the zip and use zipfile to get the zip > central directory structure. I download the section of the zip file I > need, directly read the zip file headers and use that information with > zlib to uncompress the data. The files I am examining will always be > compressed using deflate, with a wbits value of -15(minus for > headerless data because I am unsure whether the zip file header is > what zlib expects). > > I can not find anywhere in the PK Zip Application notes (http://www.pkware.com/documents/casestudies/APPNOTE.TXT) how to > determine the value I should uze for wbits with zlib.decompress. I > have determined it is -15 from experimentation. Does anyone know the > answer to this? Okay, I found part of the answer here in the zip app notes [quote] general purpose bit flag: (2 bytes) Bit 0: If set, indicates that the file is encrypted. (For Method 6 - Imploding) Bit 1: If the compression method used was type 6, Imploding, then this bit, if set, indicates an 8K sliding dictionary was used. If clear, then a 4K sliding dictionary was used. Bit 2: If the compression method used was type 6, Imploding, then this bit, if set, indicates 3 Shannon-Fano trees were used to encode the sliding dictionary output. If clear, then 2 Shannon-Fano trees were used. (For Methods 8 and 9 - Deflating) Bit 2 Bit 1 0 0 Normal (-en) compression option was used. 0 1 Maximum (-exx/-ex) compression option was used. 1 0 Fast (-ef) compression option was used. 1 1 Super Fast (-es) compression option was used. [/quote] Now I just don't understand Why Normal deflate corresponds to 15 wbits, and why I have to use headerless for the data, i.e. wbits = -15. From Russ.Paielli at gmail.com Sat Dec 6 10:21:40 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 6 Dec 2008 07:21:40 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> <20081206133704.1bed455c@usenot.de> Message-ID: <4d1a952e-25ad-4b36-ba46-ed35758331b0@e1g2000pra.googlegroups.com> On Dec 6, 4:37?am, Andreas Waldenburger wrote: > On Sat, 6 Dec 2008 13:32:58 +0100 Andreas Waldenburger > > wrote: > > On Sat, 6 Dec 2008 04:02:54 -0800 (PST) bearophileH... at lycos.com > > suggested: > > > > class C: > > > ? ? def $method(arg): > > > ? ? ? ? $value = arg > > > > [snip] > > > [snip] > > "self" is a speaking identifier, "$" isn't. > > Also, nothing prevents you from replacing "self" with "s" if you really > want it short. Same effect as your "s" suggestion (OK, plus one "."). Yes, you can always use "s". But single-letter identifiers are not usually a good idea, because they are hard to search on. A slightly better option is "S", which is a little better for searching but not as good as "$". I have considered using "S" extensively in my code, but I hesitate because it is not recognized in official Python coding standards. From prabhu.ranjith at gmail.com Wed Dec 10 19:50:22 2008 From: prabhu.ranjith at gmail.com (free online study about computer language) Date: Wed, 10 Dec 2008 16:50:22 -0800 (PST) Subject: @ you can study through online freely all the computer language. Easy way and free registration. Visit www.tiketin.blogspot.com @ Message-ID: <1ed142af-346c-451c-a3ec-0d88170828d3@x8g2000yqk.googlegroups.com> Now easy way to clear all your computer language doubts and to learn more visit www.tiketin.blogspot.com everything is free. You can also get e-books freely. No need to waste time and money visit www.tiketin.blogspot.com way to learn from your home itself visit www.tiketin.blogspot.com From david at boddie.org.uk Thu Dec 18 18:28:00 2008 From: david at boddie.org.uk (David Boddie) Date: Fri, 19 Dec 2008 00:28:00 +0100 Subject: how to dock another application under Linux ? References: Message-ID: On Thursday 18 December 2008 20:09, Stef Mientki wrote: > Under windows it's fairly easy to capture an application > and dock in to your own wxPython application, > something like this: > - start the external application from within wxPython > - give the caption of the application a special name > - find de windows handler of the applications mainform > - tell the applications mainform, that some wxpanel is the parent > > I use this to dock VPython in wxPython. > > Is there a similar solution for Linux ( and Mac) ? On X11 systems, you can use the X11Embed protocol to do this. I would be surprised if wxWidgets doesn't have a component for this given that there's one for GTK+: http://library.gnome.org/devel/gtk/stable/GtkSocket.html David From ron.longo at cox.net Thu Dec 4 15:02:06 2008 From: ron.longo at cox.net (Ron Longo) Date: Thu, 4 Dec 2008 12:02:06 -0800 (PST) Subject: Announcement: MindTree for Python beta -- feedback appreciated Message-ID: <20841316.post@talk.nabble.com> I would like to take the time to announce the first public beta for Mindtree 2. MindTree is an Information Organizer/Outliner, note taker, web publisher written for Python 2.6 and Qt4. MindTree 2.x is a complete rewrite. The original MindTree was written for Tkinter and Tix. The original product, which never got past alpha version, has reached end-of-life. Its current state is unknown and unsupported. The MindTree project can be found and downloaded here: http://code.google.com/p/mindtree/ Please note that this is a first beta of a complete rewrite. It is suggested that this version of the software be used for evaluation purposes only. MindTree is targeted for those who have a need to organize and publish to the web large amounts of information. This information is organized in the form of an outline. The Application GUI displays a dual-pane editor in which the outline is viewed as a collapsible tree on the left and notes for the outline entries are displayed and edited on the right. MindTree will take any outline and create a web site from it which has a similar layout and functionality to the MindTree desktop application complete with collapsible/navigable tree on the left and notes on the right. Some future plans for MindTree include ReStructured Text editing, improved text styling capabilities, Inclusion of structured text objects into articles such as lists and tables and customizable HTML generation. Thanks for you interest, Ron Longo -- View this message in context: http://www.nabble.com/Announcement%3A--MindTree-for-Python-beta----feedback-appreciated-tp20841316p20841316.html Sent from the Python - python-list mailing list archive at Nabble.com. From alwaseem307ster at yahoo.com Fri Dec 19 07:17:46 2008 From: alwaseem307ster at yahoo.com (klia) Date: Fri, 19 Dec 2008 04:17:46 -0800 (PST) Subject: importing csv file into sqlite In-Reply-To: <7f64f5c6-b130-4f9b-a670-6b32eccba550@n33g2000pri.googlegroups.com> References: <21067453.post@talk.nabble.com> <7f64f5c6-b130-4f9b-a670-6b32eccba550@n33g2000pri.googlegroups.com> Message-ID: <21090356.post@talk.nabble.com> John Machin wrote: > > On Dec 18, 6:20?pm, klia wrote: >> klia wrote: >> >> > hey guys, i have a hug .csv file which i need to insert it into sqlite >> > database using python. >> > my csv data looks like this >> > Birthday2,12/5/2008,HTC,this is my birthday >> > Sea,12/3/2008,kodak,sea >> > birthday4,14/3/2009,samsung,birthday >> > love,17/4/2009,SONY,view of island >> >> > can any one give me a head start codes. >> >> > thanks in advance >> >> guys so far i came out with this but i get this error >> waseem at Linux:~/Project2$ python experment.py >> Traceback (most recent call last): >> ? File "experment.py", line 13, in >> ? ? curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item) >> sqlite3.ProgrammingError: Incorrect number of bindings supplied. The >> current >> statement uses 4, and there are 1 supplied. >> >> here's the codes >> >> import sqlite3 >> import csv >> >> f = open('/home/waseem/Project2/photos.txt') >> csv.field_size_limit(100000) #see below! > > I see nothing "below" that looks at all like an attempt to justify > setting the field size limit to 100000 -- why are you doing that? > Tends to make one suspect a problem with your delimiter and/or your > line separator. > >> input = csv.reader(f, delimiter='\t') > > Why \t??? Your data examples show commas -- could this be why you are > getting one field per line (as Peter has pointed out)? > >> conn = sqlite3.connect('/home/waseem/Project2/picutres.db') > > Is it really called "picutres" instead of "pictures", or are you > typing the code that you ran again from (your) memory? > >> curse = conn.cursor() >> >> curse.execute('CREATE TABLE photos (Name VARCHAR(100) PRIMARY KEY, Date >> INTEGER, Make VARCHAR(50), Tag VARCHAR(100))') > > [OT but to save the next question] > The column named "Date" is defined to be INTEGER but the data from the > CSV file will be a str object e.g. "12/5/2008" ... I know sqlite > cheerfully regards column types as vague reminders rather than > enforceable constraints on your input, but wouldn't you like to > convert your dates to e.g. "2008-05-12" before you poke them in? You > may want to use "ORDER BY Date" at some stage, and so that ORDER BY > isn't whacked and GROUP BY doesn't give ludicrous results, wouldn't it > be a good idea to crunch 12/5/2008 and 12/05/2008 into a common format > so that they compare equal? >> >> for item in input: > > I strongly suggest that you try to get a clue about exactly what you > are getting from the csv reader e.g. > > for line_num, item in enumerate(input_renamed_as_suggested_by_anor): > print line_num, repr(item) > >> ? ? ? ? curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item) >> curse.commit() >> > > HTH, > John > -- > http://mail.python.org/mailman/listinfo/python-list > > hey guys i took all of your suggestion but my goal ain't yet achieved :-(( these are the codes after changes, john i couldn't really catch what do you mean by renaming input, is it just normal renaming.i am testing the code on just simple .csv file with few data in as follows before trying on my hug csv file but still no joy "Bithday",12-05-08,"HTC","this is my birthday" "Sea",12-03-08,"kodak","sea" "girl","14-03-2009","samsung","birthday" "love","17-04-2009","SONY","view of island" import sqlite3 import csv f = open('/home/waseem/Project2/photos.csv') input = csv.reader(f, delimiter=',') conn = sqlite3.connect('/home/waseem/Project2/pictures.db') curse = conn.cursor() curse.execute('CREATE TABLE photos (Name VARCHAR(100) PRIMARY KEY, Date INTEGER, Make VARCHAR(50), Tag VARCHAR(100))') for row in input: curse.execute('INSERT INTO photos VALUES (?,?,?,?)', '*row') curse.commit() this time i got this error waseem at Linux:~/Project2$ python experment.py Traceback (most recent call last): File "experment.py", line 12, in curse.execute('INSERT INTO photos VALUES (?,?,?,?)', '*row') sqlite3.IntegrityError: column Name is not unique i removed the primary key and single quotation mark for '*row' to just *row but i got the old error which is waseem at Linux:~/Project2$ python experment.py Traceback (most recent call last): File "experment.py", line 11, in curse.execute('INSERT INTO photos VALUES (?,?,?,?)', *row) TypeError: function takes at most 2 arguments (5 given) -- View this message in context: http://www.nabble.com/importing-csv-file-into-sqlite-tp21067453p21090356.html Sent from the Python - python-list mailing list archive at Nabble.com. From yameenaziz at gmail.com Sat Dec 13 17:57:54 2008 From: yameenaziz at gmail.com (yameenaziz at gmail.com) Date: Sat, 13 Dec 2008 14:57:54 -0800 (PST) Subject: http://1000earndollars.blogspot.com/ Message-ID: "How To Make $1,000,000 THIS YEAR With our Online Business" From aleksandr.goretoy at gmail.com Sat Dec 27 18:18:37 2008 From: aleksandr.goretoy at gmail.com (alex goretoy) Date: Sat, 27 Dec 2008 17:18:37 -0600 Subject: parsing csv files class In-Reply-To: References: <49562755.6050205@byoteki.com> Message-ID: It's main concern is to grab the file into the buffer for use in other classes. The self.soc.me_him is just so I know when its ENTERING or EXITING in that function when I run it in terminal. It's prints it in color. My main concern right now is to add error handling. I'm still learning how to use assert and yield, but I got try,except down pat. All this class does is grabs the file either from http or local storage into a buffer and I use that in other classes. I want to add support for creating creating csv as well. I read the doc on csv and will try some things out soon. Thanks for helping me. On Sat, Dec 27, 2008 at 2:15 PM, Gabriel Genellina wrote: > En Sat, 27 Dec 2008 11:02:13 -0200, Gary M. Josack > escribi?: > >> alex goretoy wrote: >> > > I know it's messy with all those self.soc.* functions, but it works in one >>> of my current project. I just want to make it more pythonic I also want to >>> add capability for makeing csv file if I give it input like: >>> 1234,something nice, hey this is something nice >>> 2468,something else, something else >>> >> > reader = csv.reader(file(filename, "rb")) >>> try: >>> for row in reader: >>> self.buffer.append(row) >>> s,a=[],{} >>> >> > Do you know that there is a csv module in the standard library already? >> > > I'd say he already knows, he even used it in the code. > > To Alex G.: I didn't understand what's the purpose of this class. Probably > you want to do too much things in the same place; looks like it has multiple > concerns, and that's not a good idea usually. > > -- > Gabriel Genellina > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? -- ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? -------------- next part -------------- An HTML attachment was scrubbed... URL: From p.f.moore at gmail.com Thu Dec 11 14:51:35 2008 From: p.f.moore at gmail.com (Paul Moore) Date: Thu, 11 Dec 2008 11:51:35 -0800 (PST) Subject: Best way of debigging a C extension Message-ID: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> I'm writing a C extension. My environment is Python 2.5, with the mingw compiler, on Windows XP. At the moment I'm debugging by scattering printf() statements around, but it's not always easy. Is there a better way of debugging - particularly for diagnosing crashes? I have gdb (although I've hardly used it, but I can learn :-)) but if I try building my extension with python setup.py build --debug, I get an error because -lpython25_d does not exist. I'm not surprised by this, as I don't have a debug build of Python - but that should be OK, I'm only looking for debugging info from my code. I tried copying libpython25.a to libpython25_d.a - my extension now builds, but the resulting pyd is XXX_d.pyd, which won't import. If I rename this to XXX.pyd, I can import and things seem to work - but it seems a bit of a roundabout way of doing things. Is there a simpler way that I've missed? It seems to me that this (debugging a C extension without compiling a debug build of Python) would be a fairly common situation, so I would have expected a "cleaner" way of doing it. At the very least, a documentation patch to explain the best way of doing things might be useful. I'll see what I can put together based on the responses I get here. Thanks, Paul. From honey33145 at gmail.com Wed Dec 3 08:20:56 2008 From: honey33145 at gmail.com (navneet khanna) Date: Wed, 3 Dec 2008 18:50:56 +0530 Subject: Where does the clr in IronPython look the dll Message-ID: Hello Everybody I am trying to import dll with clr.AddReference("TCdll") I am getting the following error. Traceback (most recent call last): File "", line 1, in clr.AddReference("TCdll") FileNotFoundException: Unable to find assembly 'TCdll'. at Python.Runtime.CLRModule.AddReference(String name) I have loaded the dll in system32 folder. Have I loaded the dll at the right place or do I need to place it anywhere else? Waiting for your replies. Regards Navneet -------------- next part -------------- An HTML attachment was scrubbed... URL: From geekmail at usenot.de Thu Dec 4 14:41:59 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Thu, 4 Dec 2008 20:41:59 +0100 Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> Message-ID: <20081204204159.716f98b4@usenot.de> On Thu, 4 Dec 2008 09:30:52 -0800 "Daniel Fetchinson" wrote: > >> As you have probably guessed: nothing changed here. > >> Also see:http://www.python.org/dev/peps/pep-0666/ > > > > What? Do you mean it's possible to mix tabs and spaces still? Why? > > Why not? > +1 -- My real email address is constructed by swapping the domain with the recipient (local part). From sjmachin at lexicon.net Sat Dec 6 22:30:40 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 6 Dec 2008 19:30:40 -0800 (PST) Subject: Python 3.0 automatic decoding of UTF16 References: <55d79070-0c11-4fb9-8cf5-b8cc7c54b5d2@v42g2000yqv.googlegroups.com> <0e37191f-3672-4313-bc5c-ffcd904e4796@k24g2000pri.googlegroups.com> Message-ID: On Dec 7, 9:34?am, John Machin wrote: > On Dec 7, 9:01?am, David Bolen wrote: > > > Johannes Bauer writes: > > > This is very strange - when using "utf16", endianness should be detected > > > automatically. When I simply truncate the trailing zero byte, I receive: > > > Any chance that whatever you used to "simply truncate the trailing > > zero byte" also removed the BOM at the start of the file? ?Without it, > > utf16 wouldn't be able to detect endianness and would, I believe, fall > > back to native order. > > When I read this, I thought "O no, surely not!". Seems that you are > correct: > [Python 2.5.2, Windows XP] > | >>> nobom = u'abcde'.encode('utf_16_be') > | >>> nobom > | '\x00a\x00b\x00c\x00d\x00e' > | >>> nobom.decode('utf16') > | u'\u6100\u6200\u6300\u6400\u6500' > > This may well explain one of the Python 3.0 problems that the OP's 2 > files exhibit: data appears to have been byte-swapped under some > conditions. Possibility: it is reading the file a chunk at a time and > applying the utf_16 encoding independently to each chunk -- only the > first chunk will have a BOM. Well, no, on further investigation, we're not byte-swapped, we've tricked ourselves into decoding on odd-byte boundaries. Here's the scoop: It's a bug in the newline handling (in io.py, class IncrementalNewlineDecoder, method decode). It reads text files in 128- byte chunks. Converting CR LF to \n requires special case handling when '\r' is detected at the end of the decoded chunk n in case there's an LF at the start of chunk n+1. Buggy solution: prepend b'\r' to the chunk n+1 bytes and decode that -- suddenly with a 2-bytes-per- char encoding like UTF-16 we are 1 byte out of whack. Better (IMVH[1] O) solution: prepend '\r' to the result of decoding the chunk n+1 bytes. Each of the OP's files have \r on a 64-character boundary. Note: They would exhibit the same symptoms if encoded in utf-16LE instead of utf-16BE. With the better solution applied, the first file [the truncated one] gave the expected error, and the second file [the apparently OK one] gave sensible looking output. [1] I thought it best to be Very Humble given what you see when you do: import io print(io.__author__) Hope my surge protector can cope with this :-) ^%!//() NO CARRIER From fankaicn at gmail.com Mon Dec 29 20:30:16 2008 From: fankaicn at gmail.com (Fan Kai) Date: Mon, 29 Dec 2008 17:30:16 -0800 (PST) Subject: Why threading.Thread has no detach method Message-ID: <63111136-5048-4321-a7b4-1655b8f35619@q30g2000prq.googlegroups.com> Does this mean terminated threads will automatically release all resouce? From has.temp3 at virgin.net Mon Dec 8 18:22:49 2008 From: has.temp3 at virgin.net (has) Date: Mon, 8 Dec 2008 15:22:49 -0800 (PST) Subject: Number of Python 3.x packages at the PyPI References: <9c1ab0f3-6686-4c0f-8a6c-12e20539f354@41g2000yqf.googlegroups.com> <493b954e$0$4021$9b622d9e@news.freenet.de> <2d656e64-deff-40ed-8066-57b6f8874ec4@b38g2000prf.googlegroups.com> <493c29a7$0$27869$9b622d9e@news.freenet.de> Message-ID: <3b2464a1-84d4-4833-ac26-accd317d978d@k19g2000yqg.googlegroups.com> On 7 Dec, 19:53, "Martin v. L?wis" wrote: > > I've had to fork my appscript project's codebase in order to add > > support for Python 3.x. I would like to distribute both 2.x and 3.x > > versions under the same package name for obvious reasons. This isn't a > > problem with eggs as the Python version number is included in each > > egg's name, but what about source distributions where both filenames > > are exactly the same (appscript-0.19.0.tar.gz)? > > I see. My initial reaction was that something should be done about this; > please do bring this up on catalog-... at python.org. OK, will do. > On second thought: can't you just include the source of both versions > in a single source distribution file? The .tar.gz distributions are built by distutils/setuptools. If I manually combine them into a single archive, I'm guessing that 'easy_install appscript' won't know how to read that custom archive when building and installing from source. (Which also raises a further question: if I do eventually manage to upload both 2.x and 3.x versions under the same PyPI entry, will easy_install know which one to download?) Thanks, has -- Control AppleScriptable applications from Python, Ruby and ObjC: http://appscript.sourceforge.net From jonas.esp at googlemail.com Fri Dec 19 06:39:40 2008 From: jonas.esp at googlemail.com (Kless) Date: Fri, 19 Dec 2008 03:39:40 -0800 (PST) Subject: [Pyrex] Compiling via setuptools Message-ID: <2198b635-7bf8-43c1-889e-66582675294d@p2g2000prf.googlegroups.com> When I use the next command in my home system: $ python setup.py develop Pyrex compiles the '.pyx' file without any problem. But after of uploading it to Pypi, and when is installed via 'easy_install' it doesn't builds any more. (I had to upload the '.c' file compiled on my system) You can see here how has been configured: http://www.bitbucket.org/ares/bcryptwrap/src/tip/setup.py and here where I had to add any files: http://www.bitbucket.org/ares/bcryptwrap/src/tip/MANIFEST.in From tenax.raccoon at gmail.com Thu Dec 18 10:20:08 2008 From: tenax.raccoon at gmail.com (Jason) Date: Thu, 18 Dec 2008 07:20:08 -0800 (PST) Subject: Selecting a different superclass References: <5adf5202-d80f-4cd1-a5f2-2d1c5f47504f@e1g2000pra.googlegroups.com> Message-ID: On Dec 18, 4:36?am, "psaff... at googlemail.com" wrote: > On 17 Dec, 20:33, "Chris Rebert" wrote: > > > superclass = TraceablePointSet if tracing else PointSet > > Perfect - many thanks. Good to know I'm absolved from evil, also ;) > > Peter Another way would be to have a factory function that builds the appropriate instance: class PointSet(object): @staticmethod def Create_Instance(*args, **keyargs): if TRACE_DATA: return TraceablePointSet(*args, **keyargs) else: return PointSet(*args, **keyargs) # Normal release class body goes here. class TraceablePointSet(object): # Normal debug class body goes here point_set = PointSet.Create_Instance() This is the way you'd do things if you wanted a mix of your release class instances and debug class instances. Perhaps there's only a certain set of initial arguments that need to be checked, or maybe the TRACE_DATA global can change. Inside the body you could also explicitly check for a "trace" parameter, like so: if keyargs.get( 'trace_data', False ): # Create debug instance .... That would allow you to create debug instances only when you want them. A variation on Chris Rebert's option is also possible: class _PointSet(object): # Normal body definition here class _TraceablePointSet(object): # Traceable body definition here if TRACE_DATA: PointSet = _TraceablePointSet else: PointSet = _PointSet Hope this helps. Python's dynamic nature loves you! --Jason From rt8396 at gmail.com Mon Dec 22 14:08:48 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 11:08:48 -0800 (PST) Subject: I always wonder ... References: <18767.54282.188749.522233@montanaro-dyndns-org.local> Message-ID: <097fc1e1-d0fa-469c-af51-0ccf8ed1542f@35g2000pry.googlegroups.com> On Dec 22, 1:02?pm, Christian Heimes wrote: > Don't worry about the trolling, Skip. I'd be more worried if nobody > trolls about Python. It would mean Python loses popularity and our work > is all in vain. Christain, you are truly an open minded, intelligent Human being. Thanks for blessing use with your wisdom here. We need more like you. Every thought, action, fact, must always be questioned, that is what makes us human! From rt8396 at gmail.com Thu Dec 18 14:52:27 2008 From: rt8396 at gmail.com (r) Date: Thu, 18 Dec 2008 11:52:27 -0800 (PST) Subject: IDLE cursor color References: <65c5974c-e5c5-46c1-9673-371a7c9ea047@a12g2000pro.googlegroups.com> Message-ID: <313c1a14-ac85-4326-a2dc-29955549a708@f11g2000vbf.googlegroups.com> in IDLE go to: Options -> Configure IDLE -> Highlighting... 1.) in the box click the word "cursor" 2.) press the button that says "Choose Color for" 3.) Pick a color and save the changes viola! you did it! :) From steve at holdenweb.com Sun Dec 21 21:01:12 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 21 Dec 2008 21:01:12 -0500 Subject: Read an image from a URL and write it to the browser In-Reply-To: References: Message-ID: McCoy Fan wrote: > On Dec 21, 7:25 am, Peter Otten <__pete... at web.de> wrote: >> McCoy Fan wrote: >>> I want to do something simple: read an image from an image URL and >>> write the image to the browser in CGI style. >>> I wrote a CGI script to do this (I'm new to Python) and got the >>> following error: >>> "FancyURLopener instance has no attribute 'tempcache'" in >> method FancyURLopener.__del__ of >> I have no idea what that error means and neither does Google. >>> Any idea where I went wrong in the code below? >>> import urllib >>> urlString = "http://www.google.com/google_logo.jpg" >>> imgStream = urllib.urlopen(urlString) >>> imgBuffer = imgStream.read() >>> imgStream.close() >>> print "Content-Type: image/jpeg" >>> print >>> print imgBuffer >> Your script runs without error here, but I can provoke the attribute error >> by passing an invalid proxies argument to urlopen(): >> >> $ python -c"import urllib; urllib.urlopen('whatever', proxies=42)" >> Traceback (most recent call last): >> File "", line 1, in >> File "/usr/lib/python2.5/urllib.py", line 75, in urlopen >> opener = FancyURLopener(proxies=proxies) >> File "/usr/lib/python2.5/urllib.py", line 609, in __init__ >> URLopener.__init__(self, *args, **kwargs) >> File "/usr/lib/python2.5/urllib.py", line 117, in __init__ >> assert hasattr(proxies, 'has_key'), "proxies must be a mapping" >> AssertionError: proxies must be a mapping >> Exception exceptions.AttributeError: "FancyURLopener instance has no >> attribute 'tempcache'" in > > ignored >> >> Please post your complete traceback, Python version, and OS to allow for a >> more detailed diagnosis. >> >> You can also try to run your script with >> >>> imgStream = urllib.urlopen(urlString) >> changed to >> >> imgStream = urllib.urlopen(urlString, proxies={}) >> >> to bypass the code in which I suppose the failure to occur. >> >> Peter > > I appreciate your response. Thank you. > > After reading your reply, I realized this must be related to the fact > that I am running this script on Google App Engine. > > It turns out, App Engine does not allow direct socket communication so > urllib is not allowed. > > Instead they provide their own library called urlfetch. So my script > should look something like this: > > from google.appengine.api import urlfetch > print 'Content-Type: text/plain' > print '' > result = urlfetch.fetch('http://www.google.com/google_logo.jpg') > print result.content > > I haven't been able to get it to work yet but at least I'm heading in > the right direction now. I'll keep digging. Thanks! You might also want to bear in mind that at least for me the content that this URL returns is HTML with embedded javascript, and not the JPEG you were expecting. That's because the URL gives a 404 response. This might be a seasonal thing: right now they are showing a "Happy Holidays" motif on their front page. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From bdesth.quelquechose at free.quelquepart.fr Sun Dec 21 09:17:45 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 21 Dec 2008 15:17:45 +0100 Subject: a small doubt In-Reply-To: References: <19ac19520812201750hb592e4dsa5ef7d2a1906c2ed@mail.gmail.com> Message-ID: <494e5dbc$0$16190$426a34cc@news.free.fr> (answering to the OP) > Piyush Anonymous wrote: >> i wrote this code >> -- >> class Person(object): >> instancesCount = 0 >> def __init__(self, title=""): >> Person.instancesCount += 1 >> self.id = "tempst" >> def testprint(self): >> print "blah blah" >> def __getattribute__(self, name): >> print "in get attribute" >> >> a = Person() >> a.testprint() >> print a.id >> ----- >> but i am getting this error >> ---- >> in get attribute >> Traceback (most recent call last): >> File "trapmethodcall1.py", line 15, in >> a.testprint() >> TypeError: 'NoneType' object is not callable >> ------ >> why is it so? __getattribute__ is called whenever an attribute or >> method is called, rt? Yes. Methods are attributes too. And __getattribute__ is the attribute lookup operator implementation - it is invoked *everytime* you have obj.attr or getattr(obj, "attr") or hasattr(obj, "attr"). IOW, you'd better *not* touch it unless 1/ you really know what you're doing, 2/ you have a very compelling reason to do so and 3/ you're ok to pay the performance hit (the default implementation in 'object' being optimized). >> or if i set __getattribute__ , i cannot have >> methods in class? Yes, you can. But you have to write a proper implementation of __getattribute__. The one above will prevent you from accessing any class or instance attribute (or, more exactly, will always return None). >> actually my aim is to trap all method calls and keep a counter which >> is update whenever method called or returned. how should i go about it? Using __getattribute__, you'll only get at the method when it is looked up (which doesn't imply it will be called). If you want to log calls and returns, you'll have to wrap the method in a decorator. You can do this either manually (ie manually adding the logger decorator on methods), via monkeypatching on class objects (but this can be tricky too), or adding a properly implemented version of __getattribute__ (but this won't work if the method is looked up on the class itself) # a Q&D method call logger def log(meth): if hasattr(meth, "logged"): # already wrapped return meth def logged(*args, **kw): if hasattr(meth, "im_self"): # wrapping a method what = "method %s " % meth else: # wrapping a function, 'self' or 'cls' is the first arg what = "method %s of object %s" % (meth, args[0]) print "%s called with %s %s" % (what, str(args), kw) try: result = meth(*args, **kw) except Exception, e: print "%s raised %s" % (what, e) raise else: print "%s returned %s" % (what, str(result)) return result logged.logged = True return logged # manual decoration class Foo(object): @log def bar(self): pass # using __getattribute__ class Foo(object): def bar(self): pass def __getattribute__(self, name): attr = super(Foo2, self).__getattribute__(name) if hasattr(attr, "im_self"): attr = log(attr) return attr Given the shortcomings of the __getattribute__ version (performance hit and only triggered on instance lookup), I'd strongly suggest the manual decoration - possibly using a flag (global setting or environment variable) to switch it off, ie: if globals().get("DEBUG", False): def log(func): def logged(*args, **kw): # wrapping a function # we assume this function is used as a method, so # 'self' or 'cls' is the first arg what = "method %s of object %s" % (func, args[0]) print "%s called with %s %s" % (what, str(args), kw) try: result = func(*args, **kw) except Exception, e: print "%s raised %s" % (what, e) raise print "%s returned %s" % (what, str(result)) return result return logged else: def log(func): # no-op return func NB : all this is pretty Q&D and mostly untested, but it should get you started. HTH From jkrukoff at ltgc.com Tue Dec 30 19:00:03 2008 From: jkrukoff at ltgc.com (John Krukoff) Date: Tue, 30 Dec 2008 17:00:03 -0700 Subject: [ANN]: circuits-1.0b1 released! In-Reply-To: References: Message-ID: <1230681603.9684.17.camel@jmk> On Wed, 2008-12-31 at 09:44 +1000, James Mills wrote: > Hi all, > > I'm pleased to announce the release of circuits-1.0b1 I'm curious, you've a number of comparisons to Twisted on your site FAQ section, but this sounds like a much closer project to Kamaelia (http://www.kamaelia.org/Home). Are these actually similar or am I missing something important that differentiates circuits? -- John Krukoff Land Title Guarantee Company From prologic at shortcircuit.net.au Mon Dec 8 09:53:32 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 9 Dec 2008 00:53:32 +1000 Subject: Beginner trying to understand functions. In-Reply-To: References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> Message-ID: On Tue, Dec 9, 2008 at 12:46 AM, Peter Otten <__peter__ at web.de> wrote: > I think the OP is using Python 3.0. What used to cause trouble Well of course he/she/it is! I'm too blind to have noticed that! :) --JamesMills -- -- -- "Problems are solved by method" From darcy at druid.net Sun Dec 7 10:14:30 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sun, 7 Dec 2008 10:14:30 -0500 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: References: <5u8o06xbqf.ln2@joeserver.homelan.net> <1mmq06x4g6.ln2@joeserver.homelan.net> Message-ID: <20081207101430.85707592.darcy@druid.net> On Sun, 07 Dec 2008 16:05:53 +0100 Johannes Bauer wrote: > But, seriously - I find that whole "while True:" and "if line == """ > construct ugly as hell, too. How can reading a file line by line be > achieved in a more pythonic kind of way? for line in open(filename): -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From lie.1296 at gmail.com Mon Dec 1 19:54:16 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 02 Dec 2008 07:54:16 +0700 Subject: end of print = lower productivity ? In-Reply-To: <493406E3.6090304@tim.thechases.com> References: <757b4e03-7d13-4758-85c4-f5224ee9853b@j35g2000yqh.googlegroups.com> <21d250f9-1477-450e-9587-c4b28d08ea00@t3g2000yqa.googlegroups.com> <981d3e99-d2b4-4455-a52a-e906bd0fe7c4@r36g2000prf.googlegroups.com> <4931D571.8070007@tim.thechases.com> <1228032887.6627.53.camel@lieryan-laptop> <493406E3.6090304@tim.thechases.com> Message-ID: <1228179256.7037.16.camel@lieryan-laptop> On Mon, 2008-12-01 at 09:46 -0600, Tim Chase wrote: > > For a proof, let's see what Google has to say about this: > > "Windows text editor". Vim is on page 3, near the turning > > point where nobody is talking about text-editor anymore and > > more about text-editor reviews. Even worse is Emacs, on page > > 6, after many other popular text-editors have been mentioned > > several times. > > That's a pretty malformed "proof": > > http://www.google.com/search?q=people%20you%20should%20listen%20to%20regarding%20choice%20of%20text-editor > > You don't appear anywhere in the top *10* pages...QED ;-) That's a pretty malformed dis-proof. > However, if you want to play that game, vim.org appears on page #1 of > > http://www.google.com/search?q=best+text+editor Not a valid proof. When people queried for "best text editor", they'll be looking for reviews instead of official site of text editor. So the placement of vim.org in the first page for "best text editor" is out of context (although I do agree that vim is one of the best editor, if not the best, in terms of power and speed). > Use what editor works for you -- but if evolution in the > language's features makes difficulties for you but not for users > of other editors, it's your editor that's the problem, not the > language. Personally, I don't think having two parens is adding much difficulties, but I symphatize those who think it is. Actually I wanna say: It's vi(m)'s fault for being too powerful making its avid users doesn't care about users of other editors. Not many text editors are nearly as powerful as vi(m) (or emacs), although most (all?) are much easier to use for day-to-day editing. but I don't want to start a war here. From duncan.booth at invalid.invalid Tue Dec 30 11:39:52 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Dec 2008 16:39:52 GMT Subject: thread, multiprocessing: communication overhead References: Message-ID: mk wrote: > This time I decided to test communication overhead in multithreaded / > multiprocess communication. The results are rather disappointing, that > is, communication overhead seems to be very high. In each of the > following functions, I send 10,000 numbers to the function / 10 threads > / 10 processes, which simply returns it in its respective way. > > > Function: notfun Best: 0.00622 sec Average: 0.00633 sec > (simple function) > > Function: threadsemfun Best: 0.64428 sec Average: 0.64791 sec > (10 threads synchronizing using semaphore) > > Function: threadlockfun Best: 0.66288 sec Average: 0.66453 sec > (10 threads synchronizing using locks) > > Function: procqueuefun Best: 1.16291 sec Average: 1.17217 sec > (10 processes communicating with main process using queues) > > Function: procpoolfun Best: 1.18648 sec Average: 1.19577 sec > (a pool of 10 processes) > > If I'm doing smth wrong in the code below (smth that would result in > performance suffering), please point it out. You aren't just timing the communication overhead: each of your functions creates a pool of 10 threads or 10 processes on every run, so your times include the startup and shutdown times. From deets at nospam.web.de Sun Dec 7 14:36:58 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 07 Dec 2008 20:36:58 +0100 Subject: Importing the re module fails In-Reply-To: <20081207202326.4b5ab73d@usenot.de> References: <20081207202326.4b5ab73d@usenot.de> Message-ID: <6q2muqFahsfnU1@mid.uni-berlin.de> Andreas Waldenburger schrieb: > This is a little puzzling. > > > Using ipython: > > [wildemar at localhost Logstuff]$ ipython > Python 2.5.2 (r252:60911, Sep 30 2008, 15:41:38) > Type "copyright", "credits" or "license" for more information. > > [snip ipython help message] > > In [1]: import re > > > This works fine. But with the regular python interpreter I get this: > > [wildemar at localhost Logstuff]$ python > Python 2.5.2 (r252:60911, Sep 30 2008, 15:41:38) > [GCC 4.3.2 20080917 (Red Hat 4.3.2-4)] on linux2 > Type "help", "copyright", "credits" or "license" for more > information. > >>> import re > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.5/re.py", line 10, in > # AB (info at pythonware.com). > AttributeError: 'module' object has no attribute 'compile' > > > What gives? Has Fedora-10 botched python or does anybody else have that > problem es well? In my re.py module on line 10, there is no import - it has way to much comments on the module beginning. So - how does your /usr/lib/python2.5/re.py look like? And what about some modules lying around (potentially *pycs) that mask system modules? Diez From chengang.beijing at gmail.com Fri Dec 12 00:28:06 2008 From: chengang.beijing at gmail.com (chengang.beijing at gmail.com) Date: Thu, 11 Dec 2008 21:28:06 -0800 (PST) Subject: how to convert '\xf0' to 0xf0 ? References: <1cb85265-1c36-4e4b-88f1-46b0ebae3dea@v5g2000prm.googlegroups.com> Message-ID: <8f5b95c0-486d-48ce-b75c-e18a86d73f50@l33g2000pri.googlegroups.com> Hi, ord('\xf0') works and it only works for char. Do you know any way to convet '\xf0\xf0' and '\xf0\xf0\xff\xfe' to integer? Br, Chen Gang On Dec 12, 12:40?pm, Steve Holden wrote: > chengang.beij... at gmail.com wrote: > > '\xf0' is the value read from a binary file, I need to change this > > kinds strings to int for further processing... > > if it is in C, then '\xf0' is an integer and it can be handled > > directly, but in python, it is a string. > > > and both int('10',16) and int('0x10',16) returns 16. > > > Br, Chen Gang > > > On Dec 12, 12:06 pm, Tommy Nordgren wrote: > >> On Dec 12, 2008, at 4:48 AM, chengang.beij... at gmail.com wrote: > > >>> int('\xf0',16) doesn't work, any way to do that? > >>> -- > >>>http://mail.python.org/mailman/listinfo/python-list > >> ? ? ? ? Should be int('10',16) > >> or int('0x10',16) > > It seems that you want the integer value of a character you read in from > a file. Is this correct? Note that '\xf0' is the interpreter's way of > representing a one-character string whose only character has the > hexadecimal value f0, because the actual character is not printable: the > backslash has a special meaning in character string literals. > > Any one-character string, however, can be converted to the equivalent > integer value using the ord() function. You can convert the other way > using the chr() function: > > > > >>> ord('A') > 65 > >>> chr(65) > 'A' > >>> ord('\xf0') > 240 > >>> chr(240) > '\xf0' > >>> hex(240) > '0xf0' > > So just apply the ord() function to the character and you'll get its > integer value! > > regards > ?Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ From jeremiah.dodds at gmail.com Sat Dec 13 23:30:58 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Sat, 13 Dec 2008 23:30:58 -0500 Subject: Error with SOAPpy In-Reply-To: <2da206ed-f3bb-4ef9-b43e-88ba799a9d87@a12g2000pro.googlegroups.com> References: <2da206ed-f3bb-4ef9-b43e-88ba799a9d87@a12g2000pro.googlegroups.com> Message-ID: <12cbbbfc0812132030t468365cfiaf7ef18a863586c2@mail.gmail.com> On Sat, Dec 13, 2008 at 10:54 PM, Amit Goyal wrote: > Hi All, > > I am new to Python and was trying the sample code on Dive into Python > for WSDL. Below is the error I get. > > Traceback (most recent call last): > File "", line 4, in -toplevel- > print 'Light sensor value: ' + server._ns(namespace).readLSpercent > (int_1 = "1") > File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 470, in > __call__ > return self.__r_call(*args, **kw) > File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 492, in > __r_call > self.__hd, self.__ma) > File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 363, in > __call > config = self.config) > File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 187, in > call > r.endheaders() > File "c:\Python24\lib\httplib.py", line 798, in endheaders > self._send_output() > File "c:\Python24\lib\httplib.py", line 679, in _send_output > self.send(msg) > File "c:\Python24\lib\httplib.py", line 646, in send > self.connect() > File "c:\Python24\lib\httplib.py", line 614, in connect > socket.SOCK_STREAM): > gaierror: (11001, 'getaddrinfo failed') > > I am using Python 2.4.4 and the following versions. > > >>> xml.__version__ > '0.8.4' > >>> fpconst.__version__ > '0.7.2' > >>> SOAPpy.__version__ > '0.12.0' > > Regards, > Amit > -- > http://mail.python.org/mailman/listinfo/python-list > Are you behind a proxy? -------------- next part -------------- An HTML attachment was scrubbed... URL: From gnewsg at gmail.com Fri Dec 19 11:13:34 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Fri, 19 Dec 2008 08:13:34 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: On 19 Dic, 17:01, walterbyrd wrote: > I have not worked with Python enough to really know. But, it seems to > me that more I look at python 3.0, the more I wonder if it isn't a > step backwards. > > To me, it seems that this: > > print "%s=%d" % ('this',99) > > Is much easier, and faster, to type, and is also easier to read and > understand. It also allows people to leverage their knowledge of C. > > This (if it's right) is much longer, and requires more special > characters. > > print( "{0}={1}".format('this',99)) > > Maybe it's worth all the extra trouble, and breaking backward > compatibilty, and all. But, I never had the idea that the old way was > all that big a problem. Of course, I could be wrong. Was the old way > all that big of a problem? You can use the old 2.x syntax also in Python 3.x: C:\>C:\python30\python.exe Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> print("%s=%d" % ('this',99)) this=99 --- Giampaolo http://code.google.com/p/pyftpdlib/ From pdorange at pas-de-pub-merci.mac.com Wed Dec 24 02:59:16 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Wed, 24 Dec 2008 08:59:16 +0100 Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> <1iscu14.oixxplpgajabN%pdorange@pas-de-pub-merci.mac.com> <1isenn3.1g8fxa21aqzibkN%pdorange@pas-de-pub-merci.mac.com> <0161d9c7$0$20621$c3e8da3@news.astraweb.com> Message-ID: <1isg3dq.1yyxrjp5eqcj5N%pdorange@pas-de-pub-merci.mac.com> Steven D'Aprano wrote: > > sign_0 : 0.375 > > sign_1 : 0.444 (+18%) > > sign_2 : 0.661 (+76%) > > sign_3 : 0.498 (+33%) > > > Looking at those results, and remembering that each time is for one > million iterations of one thousand calls each, one million iteration only, that's enough but yes indeed this function is fast. > I'd say that there's so > little difference in speed between them, that you should choose whichever > function is easier to understand. Yes, you're right. I just made those test for pure intellectual reason. For me sign_0 is the simplest one to understood. So in the domain of my little arcade game, this is what i'll use. I don't need the accuraccy of sign_1, because in the application i just need to know if the target is right or left or if the speed direction is right or left. > At least until you profile your > application and discover that the sign() function is the bottleneck > keeping your program slow. In each frame i'll have to use about 10 to 20 sign() call, so it'll not be the bottleneck. -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From steve at REMOVE-THIS-cybersource.com.au Fri Dec 12 17:55:20 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Dec 2008 22:55:20 GMT Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> Message-ID: <0152e35f$0$8244$c3e8da3@news.astraweb.com> On Fri, 12 Dec 2008 21:18:36 +0000, Lie Ryan wrote: > On Fri, 12 Dec 2008 11:50:38 -0500, Steve Holden wrote: > >> Kirk Strauser wrote: >>> At 2008-12-12T15:51:15Z, Marco Mariani writes: >>> >>>> Filip Gruszczy?ski wrote: >>>> >>>>> I am not doing it, because I need it. I can as well use "if not elem >>>>> is None", >>> >>>> I suggest "if elem is not None", which is not quite the same. >>> >>> So what's the difference exactly? "foo is not None" is actually >>> surprising to me, since "not None" is True. "0 is True" is False, but >>> "0 is not None" is True. Why is that? >> >> "is not" is an operator, so the parse is >> >> foo (is not) None >> >> not >> >> foo is (not None) >> >> > Personally, I'd prefer VB's version: > foo IsNot bar > > or in pseudo-python > foo isnot bar > > since that would make it less ambiguous. "a is not b" is no more ambiguous than "1+2*3". True, there's ambiguity if you are ignorant of the precedence rules, but that's no worse than saying that "+" is ambiguous if you don't know what "+" means. "What's this 'is' operator??? It's ambiguous, it could mean ANYTHING!!! Panic panic panic panic!!!" *wink* You're allowed to assume the normal conventions, and (lucky for me!) despite being Dutch Guido choose to assume the normal English convention that "a is not b" means the same as "not (a is b)" rather than "a is (not b)". That's probably because the use-cases for the second would be rather rare. So given the normal precedence rules of Python, there is no ambiguity. True, you have to learn the rules, but that's no hardship. -- Steven From hongtian.info at gmail.com Tue Dec 30 01:22:52 2008 From: hongtian.info at gmail.com (Hongtian) Date: Mon, 29 Dec 2008 22:22:52 -0800 (PST) Subject: How to debug embeding Python? Message-ID: Hi Friends, My application is written in C/C++ and Python is embed to extend some functions (several .py files are invoked). But I am confused how to debug these embed Python? Can I use 'print-debuging'? and where can I capture the output string? Or Python can support 'break' debug for such scenario? Thanks. From roy at panix.com Sat Dec 6 08:50:20 2008 From: roy at panix.com (Roy Smith) Date: Sat, 06 Dec 2008 08:50:20 -0500 Subject: Learning Python now coming from Perl References: Message-ID: In article , Bertilo Wennergren wrote: > I'm planning to start learning Python now, using Python 3000. > I have no previous Python skills, but I now Perl pretty well. > I'm also well experienced with JavaScript. > > Any pointers and tips how I should go about getting into > Python? I assume you use Perl to solve real problems in whatever job you do. My recommendation would be the next time some problem comes up that you would normally solve with Perl, try doing it in Python. Having a real task that you need to accomplish is a great way to focus the mind. For your first project, pick something that's small enough that you think you could tackle it in under 50 lines of Perl. One of the very first things you'll probably discover that's different between Perl and Python is how they handle string pattern matching. In Perl, it's a built in part of the language syntax. In Python, you use the re module. The regular expressions themselves are the same, but the mechanism you use to apply them to input text is quite different. From gnewsg at gmail.com Tue Dec 16 07:19:57 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Tue, 16 Dec 2008 04:19:57 -0800 (PST) Subject: ethical questions about global variables References: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> Message-ID: On 16 Dic, 07:23, Michele Simionato wrote: > On Dec 16, 3:45?am, "Giampaolo Rodola'" wrote: > > > Hi, > > in a module of mine (ftpserver.py) I'd want to add a (boolean) global > > variable named "use_gmt_times" to decide whether the server has to > > return times in GMT or localtime but I'm not sure if it is a good idea > > because of the "ethical" doubts I'm gonna write below. > > Global variables have a bad reputation, but they are not > so bad in Python. Notice that: > > 1. global variables in Python are local to the module they > ? ?are defined in; > > 2. class names and module names are usually global variables > ? ?and nobody complains about that. > > 3. if you use an ALL_CAPS convention it is quite quite clear > ? ?that you are using a global variable. > > Actually the ALL_CAPS convention is for constants, but > sometimes I use it for configuration variables too, if > they are set at the beginning and they are never changed > during the running of the program. If you have more than > a single global, it makes sense to introduce a configuration > object, as others have said (this is how typically work) > but if you have a single parameter the confuguration > object is not worth the effort, IMO. > > ? ? ? ? ? ? ? ? ?M. Simionato No, all the other "configurable" variables are offered as class attributes. --- Giampaolo http://code.google.com/p/pyftpdlib/ From bignose+hates-spam at benfinney.id.au Mon Dec 15 02:55:55 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 15 Dec 2008 18:55:55 +1100 Subject: alt.possessive.its.has.no.apostrophe References: <87vdtmf0mu.fsf_-_@benfinney.id.au> Message-ID: <87r649g9dg.fsf@benfinney.id.au> James Stroud writes: > Ben Finney wrote: > > James Stroud writes: > > > >> Yes. I think it was the British who decided that the apostrophe > >> rule for "it" would be reversed from normal usage relative to > >> just about every other noun. It also seems an indefensible claim to say that anyone ?decided? it would be that way, especially ?the British?. > > Remember that ?it? is a pronoun. I see no reversal: > > Ok. Pronouns are reversed. Or, more generally: Pronouns, which are different in just about every other way from other nouns, are different in this way also. Is that about right? -- \ ?I met my girlfriend in Macy's; she was buying clothes, and I | `\ was putting Slinkies on the escalators.? ?Steven Wright | _o__) | Ben Finney From python.list at tim.thechases.com Wed Dec 3 06:10:28 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 03 Dec 2008 05:10:28 -0600 Subject: Simple ini Config parser examples needed In-Reply-To: <4936016F.8010401@g.nevcal.com> References: <47c890dc0812021331m1fe3f420kce9bcb07df5ae44e@mail.gmail.com> <4935BBE5.3020607@g.nevcal.com> <47c890dc0812021522g7f42b00o2a831bac1e15aa05@mail.gmail.com> <4936016F.8010401@g.nevcal.com> Message-ID: <49366924.7050806@tim.thechases.com> > Tim provided a correct-looking answer, albeit somewhat > complex, as it doesn't reuse the logic in the ConfigParser. It didn't start out very complex, but it was so easy to make it a bit more robust with such a scant few lines of code that I went ahead. The original just looked like options = {} for line in file("simple.ini"): line = line.rstrip("\r\n") if '=' in line: key, value = line.split('=', 1) options[key] = value which is about as simple as it gets. However, this doesn't handle commented lines nicely (OP didn't mention whether there were comments), the keys are case-sensitive (often not a desired behavior), and leading/trailing whitespace for both the key & value are preserved (also rarely desired), and in the event of a malformed line (with no '='), it fails indistinguishably from a blank line and silently. The big advantages given by the ConfigParser hack (tacking on a fake section-header) - it provides the convenience methods for pulling out an int/float/bool in addition to a string - possibly handles continued lines (I saw something in the source referring to this) - it handles merging config files from multiple sources (such as /etc/foo_rc then merged with ~/.foo_rc) - encourages use-of and learning-about a standard library module - and it handles string substitution if you want it. It also provides for defaults, but the standard dict has the get() method to allow for defaults, and the library offers the default-dict. As a personal aside, it does bug me that the ConfigParser .get*() methods don't afford an optional default value like dict.get() in the event you want a value that may be present in the config file but isn't in the [DEFAULT] section when present raising a NoSectionError or NoOptionError. I.e. I'd like to be able to call cp.get('some_section', 'some_key', '42') on an empty config.ini file and get back the "42" as if it existed in "some_section" rather than throwing an exception/error (and why the heck do these "exceptions" descend from Error rather than Exception? These aren't errors...they're exceptions) -tkc From yinon.me at gmail.com Mon Dec 15 08:29:00 2008 From: yinon.me at gmail.com (Yinon Ehrlich) Date: Mon, 15 Dec 2008 05:29:00 -0800 (PST) Subject: Limit traceback from most recent call References: Message-ID: <8ab4f9a8-3629-4f6a-bbf2-1deed8624215@w24g2000prd.googlegroups.com> On Dec 14, 8:07?pm, Brian Allen Vanderburg II wrote: > I've looked at traceback module but I can't find how to limit traceback > from the most recent call if it is possible. ?I see that extract_tb has > a limit parameter, but it limits from the start and not the end. ? > Currently I've made my own traceback code to do this but wonder if > python already has a way to do this build in: > > def format_partial_exc(limit=None): > > ? ? (type, value, tb) = sys.exc_info() > > ? ? items = traceback.extract_tb(tb) > > ? ? if limit: > > ? ? ? ? items = items[-limit:] # Get last 'limit' items and not first > > ? ? result = 'Traceback (most recent call last):\n' > > ? ? items = traceback.format_list(items) > > ? ? for i in items: > > ? ? ? ? result += i # Newline already included > > ? ? result += type.__name__ + ': ' + str(value) > > ? ? return result > > Is this possible currently from traceback or other python module? > > Brian A. Vanderburg II Hi, The interface of extract_tb is: traceback.extract_tb(tb, limit=None) try to play with the 'limit' argument Good luck, Yinon From torriem at gmail.com Mon Dec 22 12:04:15 2008 From: torriem at gmail.com (Michael Torrie) Date: Mon, 22 Dec 2008 10:04:15 -0700 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <52b8e001-2cc7-4891-8540-a3cdb6b78533@e25g2000vbe.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> <59153e28-bf86-4158-96d9-23aa5b9f0205@j35g2000yqh.googlegroups.com> <52b8e001-2cc7-4891-8540-a3cdb6b78533@e25g2000vbe.googlegroups.com> Message-ID: <494FC88F.10706@gmail.com> r wrote: > Thanks MRAB, > except the float is not 2 decimal places, but its there > > Come on... They did this for the interpreter not us. It's easer to > parse this string with positional arguments and a dict of format > descriptions. Come on pydev, at least be honest about it! No. They did this for the *language*. Come on, R. Read the PEP on the new string formatter. The rationale is very clear. From desas2 at gmail.com Mon Dec 1 15:58:19 2008 From: desas2 at gmail.com (desas2 at gmail.com) Date: Mon, 1 Dec 2008 12:58:19 -0800 (PST) Subject: python 2.5.2 or Python 2.6 compilation problem on AIX 5.3 References: <26fbc708-1b64-4271-9c7d-4394aa281f47@j39g2000yqn.googlegroups.com> Message-ID: <5eae5283-2f52-4b05-9a8c-0c9ced3e54db@h20g2000yqn.googlegroups.com> On Dec 1, 1:06 pm, Terry Reedy wrote: > des... at gmail.com wrote: > > Hello: > > I am trying to compile Python 2.5.2 on AIX 5.3 with gcc 4.2.3. I am > > getting following error. (I also tried Python 2.6 with same error) > > > creating build/temp.aix-5.3-2.5/share/tmhsdsd2/tmp/Python-2.5.2/ > > Modules > > gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - > > Wstrict-prototypes -I. -I/share/tmhsdsd2/tmp/Python-2.5.2/./Include - > > I. -IInclude -I./Include -I/usr/local/include -I/share/tmhsdsd2/tmp/ > > Python-2.5.2/Include -I/share/tmhsdsd2/tmp/Python-2.5.2 -c /share/ > > tmhsdsd2/tmp/Python-2.5.2/Modules/_struct.c -o build/temp.aix-5.3-2.5/ > > share/tmhsdsd2/tmp/Python-2.5.2/Modules/_struct.o > > creating build/lib.aix-5.3-2.5 > > > ./Modules/ld_so_aix gcc -pthread -bI:Modules/python.exp build/ > > temp.aix-5.3-2.5/share/tmhsdsd2/tmp/Python-2.5.2/Modules/_struct.o -L/ > > usr/local/lib -lpython2.5 -o build/lib.aix-5.3-2.5/_struct.so > > collect2: library libpython2.5 not found > > Have you checked all the directories on PATH to see if any contain > libpython2.5? > Thanks for your response. libpython2.5.a is in the current directory same as Makefile. Thank you. Dinakar From 5lvqbwl02 at sneakemail.com Sun Dec 28 03:54:51 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Sun, 28 Dec 2008 00:54:51 -0800 (PST) Subject: Doing set operation on non-hashable objects References: <3a87eb6a-13ff-4aea-8835-3a233cc6cfc4@w39g2000prb.googlegroups.com> Message-ID: On Dec 24, 12:21?pm, "Gabriel Genellina" wrote: > En Wed, 24 Dec 2008 17:16:59 -0200, <5lvqbw... at sneakemail.com> escribi?: > > > I'm writing an application which is structured roughly as follows: > > > "db" is a dict, where the values are also dicts. > > A function searches through db and returns a list of values, each of > > which is a dict as described above. > > I need to perform set operations on these lists (intersection and > > union) > > However the objects themselves are not hashable, and therefore can't > > be in a set, because they are dicts. > > > If you *only* care about object identity, you might use a dictionary that ? > only compares by identity to anyone else: > > class nc_dict(dict): > ? ?"A hashable dictionary that isn't equal to anyone else" > > ? ?def __eq__(self, other): > ? ? ?return cmp(id(self),id(other))==0 > > ? ?def __hash__(self): > ? ? ?return hash(id(self)) > > d1 = nc_dict(a=1, b=2, c=3) > d2 = nc_dict(b=2, c=0, d=4) > d3 = nc_dict(a=1, c=3, e=5) > dd1 = nc_dict(x=d1, y=d2) > dd2 = nc_dict(x=d1, y=d3) > dd3 = nc_dict(y=d2, z=d3, w=d1) > l1 = [dd1, dd2] > l2 = [dd2, dd3] > s1 = set(l1) > s2 = set(l2) > print s1-s2 > print s2-s1 > print s1&s2 > > # instances of nc_dict with the same contents are NOT equal > d4 = nc_dict(a=1, b=2, c=3) > print d1, d4, d1==d4 ?# output: False > > # but we can use this function to compare contents > def cmp_contents(d1, d2): > ? ? ?try: return cmp(sorted(d1.items()), sorted(d2.items())) > ? ? ?except Exception: return 1 # assume they're unequal > > print cmp_contents(d1,d4)==0 # output: True Good idea. I'll try this out. I don't think it's likely that I'll have a case where the dicts have identical values, but different identities. And if they do I probably don't care too much. Thanks From luke.leighton at googlemail.com Tue Dec 2 15:54:19 2008 From: luke.leighton at googlemail.com (lkcl) Date: Tue, 2 Dec 2008 12:54:19 -0800 (PST) Subject: Pyjamas 0.4: Python Web Toolkit Release References: Message-ID: <655eff24-100b-494f-802e-c59f9539fb1b@h5g2000yqh.googlegroups.com> On Dec 2, 6:52 pm, Duncan Booth wrote: > "Luke Kenneth Casson Leighton" wrote: > > >Pyjamasstarted as a port of Google's Web Toolkit, to python. > > Explaining whyPyjamas(and GWT) is so significant takes > > some doing: the summary is that comprehensive desktop-like > > user interfaces can be developed very simply, to run in > > any modern web browser, without having to write a single > > line of JavaScript. > > Great concept. 's'wikkid :) > The demos are a bit flakey (especially with IE): ehn? o dear. well, i try my best with ies4linux (ie6 under wine). ie7 doesn't quiiiite cut it, and the script debugger just doesn't quite want to play nice under wine. so if you do make a report, please _do_ make sure it includes a full stack trace, not just a line number. > where do you want bug > reports (the sourceforge tracker seems to be empty so I wondered if you > used somewhere else)? code.google.com - http://code.google.com/p/pyjamas/issues/list thanks! From kyrie at uh.cu Wed Dec 10 14:01:35 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Wed, 10 Dec 2008 14:01:35 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: <493FE561.6030007@egenix.com> References: <1228923619.493fe2e3c3073@comuh.uh.cu> <493FE561.6030007@egenix.com> Message-ID: <200812101401.35786.kyrie@uh.cu> On Wednesday 10 December 2008 10:50:57 am M.-A. Lemburg wrote: > On 2008-12-10 16:40, Luis Zarrabeitia wrote: > > Quoting Rasmus Fogh : > >> Rhamphoryncus wrote: > > Rich comparisons were added to Python at the request of the > Numeric (now numpy) developers and they have been part of Python > a Numeric for many many years. > > I don't think it's likely they'll change things back to the days > of Python 1.5.2 ;-) Please define "rich comparisons" for me. It seems that I do not understand the term - I was thinking it meant the ability to override the comparison operators, and specially, the ability to override them independently. Even in statically typed languages, when you override the equality operator/function you can choose not to return a valid answer (raise an exception). And it would break all the cases mentioned above (element in list, etc). But that isn't the right thing to do. The language doesn't/can't prohibit you from breaking the equality test, but that shouldn't be considered a feature. (a==b).all() makes no sense. > > Even the transition itself could be done without breaking much code... > > Make the == op return an object that wraps the array of bools (instead of > > the array itself), give it the any() and all() methods, and make > > __nonzero__/__bool__ equivalent to all(). > > That would cause a lot of confusion on its own, since such an > object wouldn't behave in the same way as say a regular Python > list (bool([0]) == True). I'm certain that something could be worked out. A quick paragraph that took me just a few minutes to type shouldn't be construed as a PEP that will solve all the problems :D. -- Luis Zarrabeitia (aka Kyrie) Fac. de Matem?tica y Computaci?n, UH. http://profesores.matcom.uh.cu/~kyrie From kyosohma at gmail.com Tue Dec 30 16:40:04 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 30 Dec 2008 13:40:04 -0800 (PST) Subject: win32gui References: Message-ID: <4af4b9c7-b7d0-40c4-ba86-38a62df4fb19@e1g2000pra.googlegroups.com> On Dec 30, 3:22?pm, Gandalf wrote: > I'm searching the win32gui hooks for a function to get the windowClass > position any idea? > > thanks! Try looking in the docs: http://docs.activestate.com/activepython/2.4/pywin32/win32gui.html I think the GetWindowPlacement() might be what you're looking for, although it's kind of hard to tell from what little info you gave. Mike From arnodel at googlemail.com Thu Dec 11 18:31:03 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 11 Dec 2008 23:31:03 +0000 Subject: list organization question References: Message-ID: Robocop writes: > I have a list of objects, each object having two relevant attributes: > date and id. I'd like not only organize by id, but also by date. > I.e. i would like to parse my list into smaller lists such that each > new mini-list has a unique date, but consists of only objects with a > specific id. Are there any handy imports i could use to accomplish > something like this? I'm relatively new to python and as such don't > know all of the preloaded functions at my disposal. Thanks for any > help in advance, the community here is always ridiculously helpful. Look at itertools.groupby. E.g. from itertools import groupby data = [ my objects ] def getdate(x): return x.date by_date = {} for date, objs in groupby(sorted(data, key=getdate), getdate): by_date[date] = list(objs) # list(objs) is the list of all objects in data whose date is date I'm sorry if this is a bit terse... -- Arnaud From gagsl-py2 at yahoo.com.ar Mon Dec 8 02:48:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Dec 2008 05:48:45 -0200 Subject: Don't you just love writing this sort of thing :) References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: En Sun, 07 Dec 2008 05:34:39 -0200, Lawrence D'Oliveiro escribi?: > In message , Arnaud Delobelle wrote: > >> * you give the impression of being arrogant; > > Oddly enough, I wasn't the one who started by criticizing other people's > code. I have no ego about my code; I gladly accept criticisms. But > perhaps > some other people are not so thick-skinned and do not like getting as > they > give... May I ask then *why* did you chose to post your code fragment? Did I miss something? -- Gabriel Genellina From jan at jandecaluwe.com Tue Dec 23 06:32:32 2008 From: jan at jandecaluwe.com (Jan Decaluwe) Date: Tue, 23 Dec 2008 12:32:32 +0100 Subject: Why MyHDL? Message-ID: <4950d063$0$2853$ba620e4c@news.skynet.be> Hello: MyHDL is a Python package for using Python as a Hardware Description Language. A new release is upcoming, and on this occasion we have prepared a page about why MyHDL may be useful to you: http://www.myhdl.org/doku.php/why Regards, Jan -- Jan Decaluwe - Resources bvba - http://www.jandecaluwe.com Python as a hardware description language: http://www.myhdl.org From steven at REMOVE.THIS.cybersource.com.au Thu Dec 11 03:10:12 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 11 Dec 2008 08:10:12 GMT Subject: Rich Comparisons Gotcha References: Message-ID: On Wed, 10 Dec 2008 17:58:49 -0500, Luis Zarrabeitia wrote: > On Sunday 07 December 2008 09:21:18 pm Robert Kern wrote: >> The deficiency is in the feature of rich comparisons, not numpy's >> implementation of it. __eq__() is allowed to return non-booleans; >> however, there are some parts of Python's implementation like >> list.__contains__() that still expect the return value of __eq__() to >> be meaningfully cast to a boolean. > > list.__contains__, tuple.__contains__, the 'if' keyword... > > How do can you suggest to fix the list.__contains__ implementation? I suggest you don't, because I don't think it's broken. I think it's working as designed. It doesn't succeed with arbitrary data types which may be broken, buggy or incompatible with __contain__'s design, but that's okay, it's not supposed to. > Should I wrap all my "if"s with this?: > > if isinstance(a, numpy.array) or isisntance(b,numpy.array): > res = compare_numpy(a,b) > elif isinstance(a,some_otherclass) or isinstance(b,someotherclass): > res = compare_someotherclass(a,b) > ... > else: > res = (a == b) > if res: > # do whatever No, inlining that code everywhere you have an if would be stupid. What you should do is write a single function equals(x, y) that does precisely what you want it to do, in whatever way you want, and then call it: if equals(a, b): Or, put your data inside a wrapper. If you read back over my earlier posts in this thread, I suggested a lightweight wrapper class you could use. You could make it even more useful by using delegation to make the wrapped class behave *exactly* like the original, except for __eq__. You don't even need to wrap every single item: def wrap_or_not(obj): if obj in list_of_bad_types_i_know_about: return EqualityWrapper(obj) return obj data = [1, 2, 3, BadData, 4] data = map(wrap_or_not, data) It isn't really that hard to deal with these things, once you give up the illusion that your code should automatically work with arbitrarily wacky data types that you don't control. -- Steven From biltar at hotmail.com Mon Dec 15 08:03:12 2008 From: biltar at hotmail.com (Ali art) Date: Mon, 15 Dec 2008 13:03:12 +0000 Subject: UnicodeEncodeError Message-ID: Hello! I am using Windows XP professional version 2002 Service pack 3. AMD Athlon(TM)XP 2400+ 2.00GHz 992MB RAM. I have downloaded Windows x86 MSI Instaler Python 3.0 (sig) (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32 Control Panel -> System -> Advanced -> Environment Variables. System Variables -> Path -> edit C:\Windows\System32\Wbem;C:\Python30 start -> programs -> python 3.0 -> IDLE(Python GUI) -> IDLE 3.0 -> File -> New Window -> i wrote "print('??????')" without qutes-> File -> Save -> Python30 -> i gave file name "d2.py" without qutes-> and Run -> Run Module -> it gives error "invalid character in identifier" then i tried second method start -> run -> cmd -> d2.py and enter it gives the error C:\>d2.pyTraceback (most recent call last): File "C:\Python30\d2.py", line 4, in print('\u011f?\u015f??\u0131') File "C:\Python30\lib\io.py", line 1491, in write b = encoder.encode(s) File "C:\Python30\lib\encodings\cp437.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0]UnicodeEncodeError: 'charmap' codec can't encode character '\u011f' in position0: character maps to C:\> But if i write in Phyton Shell -> >>> print('??????') and pressed enter -> gives '??????' it works. What is wrong? all the best _________________________________________________________________ Connect to the next generation of MSN Messenger? http://imagine-msn.com/messenger/launch80/default.aspx?locale=en-us&source=wlmailtagline -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at microcorp.co.za Wed Dec 3 23:33:41 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 4 Dec 2008 06:33:41 +0200 Subject: Please fix your clock [was Re: Multiple equates] References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> <0147f4b7$0$20670$c3e8da3@news.astraweb.com> Message-ID: <001601c955c9$94034700$0d00a8c0@hendrik> "Steven D'Aprano" wrote: >Hendrik, I think your PC's clock is wrong. You seem to be posting from >the future. I always knew I was more advanced than other people... :-) Well spotted! Thanks - Hendrik From zak.mc.kraken at libero.it Fri Dec 12 10:34:42 2008 From: zak.mc.kraken at libero.it (Vito De Tullio) Date: Fri, 12 Dec 2008 16:34:42 +0100 Subject: Removing None objects from a sequence References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> Message-ID: Filip Gruszczy?ski wrote: > I checked itertools, but the only thing that > seemed ok, was ifilter - this requires seperate function though, so > doesn't seem too short. is this too much long? >>> from itertools import ifilter >>> for element in ifilter(lambda x: x is not None, [0,1,2,None,3,None,4]): ... print element ... 0 1 2 3 4 >>> -- By ZeD From cjw at ncf.ca Wed Dec 3 11:51:04 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Wed, 03 Dec 2008 11:51:04 -0500 Subject: Multiple Versions of Python on Windows XP In-Reply-To: <493592EE.9090005@v.loewis.de> References: <4934de22$0$27863$9b622d9e@news.freenet.de> <493592EE.9090005@v.loewis.de> Message-ID: Martin v. L??wis wrote: >>>> What changes are made to the registry? >>> For a complete list, see Tools/msi/msi.py in the source tree. >> I have scanned the file: >> http://svn.python.org/projects/python/branches/py3k/Tools/msi/msi.py >> >> I don't find anything that addresses this issue. > > Read the add_registry function. You may need to first understand > how the Registry table in an MSI file works. > >> I am seeking some mechanism such that any of Python 2.5, Python 2.6 or >> Python 2.6 can be chosen as the currently active version. > > If Glenn Lindermann's answer doesn't help, you need to explain: > what is a "currently active version"? How is one Python version > more active than any other? > >> I was hoping that there is some simpler way than the "Repair" procedure. > > See Glenn Lindermann's answer. > >>> It would be good to be more specific with such statements: what troubles >>> specifically? If I play dumb, I'd say "of course - windows explorer >>> doesn't support editing Python files; you need a text editor". >> Yes, I should have been clearer. The PyScripter application locks up >> and must be killed, using the Task Manager. > > I think you need to report that to the PyScripter authors as a bug. > I can't imagine how the "currently active version" can affect what > PyScripter does. > > Regards, > Martin Martin, Many thanks for your responses. Yes, Glen Lindermann's suggestion seems to meet the need. It's been a while since I've looked at DOS and I didn't remember fType or assoc. Michel Claveau suggests VirtualBox, this seems a big hammer to kill this particular fly. It's interesting that each install sets up a Python.File variable in the registry. It's a pity that this can't be used to achieve this more simply. Best wishes, Colin W. From mark at thomaszone.com Tue Dec 30 08:38:55 2008 From: mark at thomaszone.com (Mark Thomas) Date: Tue, 30 Dec 2008 05:38:55 -0800 (PST) Subject: Any equivalent to Ruby's 'hpricot' html/xpath/css selector package? References: <495a2031$0$31867$9b4e6d93@newsspool3.arcor-online.net> Message-ID: On Dec 30, 8:20?am, Stefan Behnel wrote: > Mark Thomas wrote: > > The main difference is that lxml doesn't have CSS selector syntax > > Feel free to read the docs: > > http://codespeak.net/lxml/cssselect.html Don't know how I missed that... So lxml is pretty much an exact equivalent to what Ruby has to offer (Hpricot or Nokogiri). Nice. From martin at v.loewis.de Tue Dec 2 02:29:03 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 02 Dec 2008 08:29:03 +0100 Subject: Multiple Versions of Python on Windows XP In-Reply-To: <4934E183.9020404@g.nevcal.com> References: <4934de22$0$27863$9b622d9e@news.freenet.de> <4934E183.9020404@g.nevcal.com> Message-ID: <4934E3BF.7000403@v.loewis.de> > It would be nice if the ftypes were version specific as created by the > installer; IIRC, I created the above three from the ftype Python.File as > I installed each version. That's a good idea; please submit a wish list item to bugs.python.org. There may be issues (such as people relying on this being Python.File), but I can't see any problems off-hand. Regards, Martin From darcy at druid.net Tue Dec 16 15:18:00 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 16 Dec 2008 15:18:00 -0500 Subject: Where is a good open source python project to be used as example? In-Reply-To: References: <05T1l.219074$FR.507685@twister1.libero.it> Message-ID: <20081216151800.ec03bf25.darcy@druid.net> On Tue, 16 Dec 2008 20:03:21 GMT Andrea Francia wrote: > >> Did you know where are such projects? > > > > http://www.PyGreSQL.org/. > > > > Thanks! But I can't find any unit test in the code. Look again. They are in the files named TEST_PyGreSQL_classic.py and TEST_PyGreSQL_dbapi20.py. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 00:14:44 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Dec 2008 05:14:44 GMT Subject: Don't you just love writing this sort of thing :) References: Message-ID: <0148b086$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 13:27:35 +1300, Lawrence D'Oliveiro wrote: > In message , Cong > Ma wrote: > >> The "if ... != None" is not necessary... "if PatchDatePat.search(f)" >> is OK. > > I don't do that. Perhaps you should? Since the context has been deleted, it's hard to tell whether the code as written by Lawrence is incorrect or merely bad style. Here's his original piece of code, with the stupid formatting fixed to a more readable style: for Entry in sorted( f for f in os.listdir(PatchesDir) if PatchDatePat.search(f) != None ): Patch = (open, gzip.GzipFile)[Entry.endswith(".gz")]( os.path.join(PatchesDir, Entry), "r") ... read from Patch ... Patch.close() Still pretty obfuscated. The for block could be made considerably more readable. Here's one way: opener = gzip.GzipFile if Entry.endswith(".gz") else open Patch = opener(os.path.join(PatchesDir, Entry), "r") ... read from Patch ... Patch.close() Looking at the call to sorted(), Cong Ma suggested that if PatchDatePat.search(f) != None should be replaced by the much shorter: if PatchDatePat.search(f) The replacement is much more Pythonic style, but it could fail if PatchDatePat.search() returns a false value (0, empty string, empty list, etc) which is intended to count as a match. Without knowing what the search method does, it is impossible to tell whether this is a risk or not. On the other hand, Lawrence's code can also fail if the search method returns an object which for some reason tests equal to None despite being a match. In other words, *both* techniques are fragile, because they make assumptions about the sort of object the search method can return. The best way of doing this test, given *only* the assumption that None indicates no match, is with: if PatchDatePat.search(f) is not None This also happens to be (marginally) faster that either of the others, as it relies only on an identity test, and doesn't need to make an equality test or a __nonzero__ test, both of which require method lookups. -- Steven From rdcollum at gmail.com Wed Dec 31 14:55:14 2008 From: rdcollum at gmail.com (Roger) Date: Wed, 31 Dec 2008 11:55:14 -0800 (PST) Subject: Why not Ruby? References: Message-ID: <0640abb6-ab69-4709-a46c-b0ee8c9f0c09@n21g2000vba.googlegroups.com> On Dec 31, 12:55?pm, Xah Lee wrote: > Just spent 3 hours looking into Ruby today. Here's my short impression > for those interested. > Who are you? In case no one tells you, you are a cocky, egotistical windbag with opinions that border constructive but never gets there. Why would anyone care what you think? Again, who are you? Xah Lee? And? I didn't subscribe to read reviews on Ruby. And I'm pretty sure anyone that bothers to subscribe to a group about programming has the wherewithal to research a language themselves and come to their own determiniation. Also, this is a Python group and not Ruby. I knew I should have avoided this post and read the one about Nike Shoes from China. At least those bits of trolling spam don't try to mask themselves as something worthwhile. From info at orlans-amo.be Fri Dec 5 14:15:33 2008 From: info at orlans-amo.be (info at orlans-amo.be) Date: Fri, 5 Dec 2008 11:15:33 -0800 (PST) Subject: Python 3.0 automatic decoding of UTF16 References: Message-ID: <55d79070-0c11-4fb9-8cf5-b8cc7c54b5d2@v42g2000yqv.googlegroups.com> On Dec 5, 3:25?pm, Johannes Bauer wrote: > Hello group, > > I'm having trouble reading a utf-16 encoded file with Python3.0. This is > my (complete) code: > > #!/usr/bin/python3.0 > > class AddressBook(): > ? ? ? ? def __init__(self, filename): > ? ? ? ? ? ? ? ? f = open(filename, "r", encoding="utf16") > ? ? ? ? ? ? ? ? while True: > ? ? ? ? ? ? ? ? ? ? ? ? line = f.readline() > ? ? ? ? ? ? ? ? ? ? ? ? if line == "": break > ? ? ? ? ? ? ? ? ? ? ? ? print([line[x] for x in range(len(line))]) > ? ? ? ? ? ? ? ? f.close() > > a = AddressBook("2008_11_05_Handy_Backup.txt") > > This is the file (only 1 kB, if hosting doesn't work please tell me and > I'll see if I can put it someplace else): > > http://www.file-upload.net/download-1297291/2008_11_05_Handy_Backup.t... > > What I get: The file reads file the first few lines. Then, in the last > line, I get lots of garbage (looking like uninitialized memory): > > ['E', 'n', 't', 'r', 'y', '0', '0', 'T', 'e', 'x', 't', ' ', '=', ' ', > '"', 'A', 'D', 'A', 'C', ' ', 'V', 'e', 'r', 'k', 'e', 'h', 'r', 's', > 'i', 'n', 'f', 'o', '"', '\u0d00', '\u0a00', '?', '?', '?', '?', '? > ', '\u3000', '\u3100', '?', '?', '?', '?', '\u2000', '?', '\u2000', > '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', > '\u0d00', '\u0a00', '?', '?', '?', '?', '?', '\u3000', '\u3100', ' > ?', '?', '?', '?', '\u2000', '?', '\u2000', '?', '?', '?', '?', > '\u3100', '?', '?', '?', '?', '?', '?', '?', '?', '\u0d00', > '\u0a00', '\u0d00', '\u0a00', '?', '?', '?', '?', '?', '?', '?', > '?', '?', '\u3000', '\u3000', '?', '?', '\u0d00', '\u0a00'] > > Where the line > > Entry00Text = "ADAC Verkehrsinfo"\r\n > > is actually the only thing the line contains, Python makes the rest up. > > The actual file is much longer and contains private numbers, so I > truncated them away. When I let python process the original file, it > dies with another error: > > Traceback (most recent call last): > ? File "./modify.py", line 12, in > ? ? a = AddressBook("2008_11_05_Handy_Backup.txt") > ? File "./modify.py", line 7, in __init__ > ? ? line = f.readline() > ? File "/usr/local/lib/python3.0/io.py", line 1807, in readline > ? ? while self._read_chunk(): > ? File "/usr/local/lib/python3.0/io.py", line 1556, in _read_chunk > ? ? self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) > ? File "/usr/local/lib/python3.0/io.py", line 1293, in decode > ? ? output = self.decoder.decode(input, final=final) > ? File "/usr/local/lib/python3.0/codecs.py", line 300, in decode > ? ? (result, consumed) = self._buffer_decode(data, self.errors, final) > ? File "/usr/local/lib/python3.0/encodings/utf_16.py", line 69, in > _buffer_decode > ? ? return self.decoder(input, self.errors, final) > UnicodeDecodeError: 'utf16' codec can't decode bytes in position 74-75: > illegal encoding > > With the place where it dies being exactly the place where it outputs > the weird garbage in the shortened file. I guess it runs over some page > boundary here or something? > > Kind regards, > Johannes > > -- > "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, > verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." > ? ? ? ? ?-- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik > ? ? ? ? ? ? ? ? ? ? ? ? ?<48d8bf1d$0$7510$54022... at news.sunrise.ch> 2 problems: endianness and trailing zer byte. This works for me: class AddressBook(): def __init__(self, filename): f = open(filename, "r", encoding="utf_16_be", newline="\r\n") while True: line = f.readline() if len(line) == 0: break print (line.replace("\r\n","")) f.close() a = AddressBook("2008_11_05_Handy_Backup2.txt") Please note the filename: I modified your file by dropping the trailing zer byte From shao.tu at gmail.com Thu Dec 11 04:53:58 2008 From: shao.tu at gmail.com (stalex) Date: Thu, 11 Dec 2008 01:53:58 -0800 (PST) Subject: Py_GetPath() C API in python 3 Message-ID: <772bb62b-1ef1-4ffa-90f6-c1cbdc728fdd@q30g2000prq.googlegroups.com> Hi all, I want to build a new, requires total control, python interpreter. So I implement my own version of Py_GetPath(), Py_GetPrefix(), Py_GetExecPrefix() and Py_GetProgramFullPath(). When compiling, I always get error messages, for each API function, look like followings: /opt/python-3.0/lib/python3.0/config/libpython3.0.a(getpath.o)(.text +0x211c): In function `Py_GetPath': ./Modules/getpath.c:739: multiple definition of `Py_GetPath' myApp.o(.text+0x0):/home/alex/workspace/develop/src/myApp.c:11: first defined here /usr/bin/ld: Warning: size of symbol `Py_GetPath' changed from 126 in system.o to 32 in /opt/python-3.0/lib/python3.0/config/libpython3.0.a (getpath.o) collect2: ld returned 1 exit status If I compile my application with python 2.x, everything's just okay and my application as well. Any ideas on how to get this working for python 3? From pdorange at pas-de-pub-merci.mac.com Thu Dec 18 09:21:16 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Thu, 18 Dec 2008 15:21:16 +0100 Subject: re.match() performance References: <755bd716-f5f6-4953-87a7-04ee148c3298@i18g2000prf.googlegroups.com> Message-ID: <1is5gvp.1bafifnn1ir2uN%pdorange@pas-de-pub-merci.mac.com> Emanuele D'Arrigo wrote: > I've written the code below to test the differences in performance > between compiled and non-compiled regular expression matching but I > don't quite understand the results. It appears that the compiled the > pattern only takes 2% less time to process the match. Is there some > caching going on in the uncompiled section that prevents me from > noticing its otherwise lower speed? Running your sample i got also a 2% the first time, but next time i got a different speed : 4 time faster. Running 1st time Pattern Matching Time: 0.122432 (Compiled) Pattern Matching Time: 0.12012 Ratio Compiled/NotCompiled: 0.981116048092 2nd time and more Pattern Matching Time: 0.00257 (Compiled) Pattern Matching Time: 0.000619 Ratio Compiled/NotCompiled: 0.240856031128 Config python 2.5.1 / MacOS X 10.5 -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From christophedeze at gmail.com Mon Dec 22 12:27:14 2008 From: christophedeze at gmail.com (Toff) Date: Mon, 22 Dec 2008 09:27:14 -0800 (PST) Subject: join a samba domain References: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> <5428c77b-ed4f-49ec-a808-dccd77a2a01c@g3g2000pre.googlegroups.com> Message-ID: On 22 d?c, 17:57, Tim Golden wrote: > Toff wrote: > > On 22 d?c, 17:02, Tim Golden wrote: > >> Toff wrote: > >>> hi, > >>> I 'm trying to write a script to make my computer join a samba. > >>> domeone have any idea ?? > >> Ummm. It's not clear if you're saying that your code doesn't > >> work, or asking for general advice, or what? I'm not in a > >> position to have my machine join a domain or workgroup, but > >> you seem to have got most things in place already. The only > >> thing I would expect to have to change is this last line: > > >>> ? ?import wmi > >>> ? ?c = wmi.WMI() > >>> ? ?d = c.Win32_ComputerSystem > >>> ? ?d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") > >> because the d is only a WMI *class*, not a WMI *instance*, > >> so doesn't refer as it should to your computer system but > >> to the class of computer systems. Try something like this (untested): > > >> > >> import wmi > > >> c = wmi.WMI () > >> for d in c.Win32_ComputerSystem (): > >> ? d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") > > >> > > >> TJG > > thanks but it doesn't work > > I've got this errors > > > Traceback (most recent call last): > > ?File "integrdom.py", line 51, in > > ? ?main() > > ?File "integrdom.py", line 13, in main > > ? ?joindom() > > ?File "integrdom.py", line 44, in joindom > > ? ?d.JoinDomainOrWorkGroup(None, 3, "domcd", "adminLocal", r"admin > > \domcd") > > ?File "c:\Python25\Lib\site-packages\wmi.py", line 493, in __getattr__ > > ? ?handle_com_error (error_info) > > ?File "c:\Python25\Lib\site-packages\wmi.py", line 189, in > > handle_com_error > > ? ?raise x_wmi, "\n".join (exception_string) > > wmi.x_wmi > > Do you not get *anything* after than wmi.x_wmi? Not even > a messy exception string? > > TJG no pessy string something strange: import wmi c = wmi.WMI() os = c.Win32_ComputerSystem for method_name in os.methods: method = getattr(os, method_name) print method it doesn't give the same parameter order for JoinDomainOrWorkGroup than MSDN doc From bruno.42.desthuilliers at websiteburo.invalid Fri Dec 19 08:33:19 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 19 Dec 2008 14:33:19 +0100 Subject: How to parsing a sequence of integers In-Reply-To: References: Message-ID: <494ba258$0$18998$426a74cc@news.free.fr> Steven Woody a ?crit : > Hi, > > I am a newbie and is reading the python book. Could anyone tell me, > how to parsing the following string > "123 100 12 37 ..." > into a list of integers on which I can then apply max()/min()? source = "123 100 12 37" list_of_ints = [int(part) for part in source.strip().split()] > > In additional to max/min, is there something like average()? Not AFAIK, but it's really trivial def average(lst): """ assume lst is a list of numerics """ return sum(lst) / len(lst) From roy at panix.com Thu Dec 4 15:11:08 2008 From: roy at panix.com (Roy Smith) Date: Thu, 4 Dec 2008 12:11:08 -0800 (PST) Subject: Checking if an int fits in 32 bits? Message-ID: I'm working with marshaling data over a binary wire protocol. I'm using struct.pack() to handle the low-level encoding of ints. One of the things I need to do is make sure an int can be represented in 4 bytes. Is there a portable way to do that? For now, I'm doing signed ints, but I'll certainly have to do unsigned 32-bit ints (and 64-bit ints) at some point. Not to mention shorts and chars. At first I thought pack() might raise an exception on a value overflow, that but doesn't seem to be the case: >>> [hex(ord(c)) for c in struct.pack('!i', 999999999999999999999L)] ['0xde', '0x9f', '0xff', '0xff'] Should I be thinking more along the lines of bit masking (and worrying about all the niggling 2-complement issues) in the Python code? Or is there some cleaner way to do this? From alwaseem307ster at yahoo.com Thu Dec 18 02:20:15 2008 From: alwaseem307ster at yahoo.com (klia) Date: Wed, 17 Dec 2008 23:20:15 -0800 (PST) Subject: importing csv file into sqlite In-Reply-To: <21067453.post@talk.nabble.com> References: <21067453.post@talk.nabble.com> Message-ID: <21068111.post@talk.nabble.com> klia wrote: > > hey guys, i have a hug .csv file which i need to insert it into sqlite > database using python. > my csv data looks like this > Birthday2,12/5/2008,HTC,this is my birthday > Sea,12/3/2008,kodak,sea > birthday4,14/3/2009,samsung,birthday > love,17/4/2009,SONY,view of island > > can any one give me a head start codes. > > thanks in advance > guys so far i came out with this but i get this error waseem at Linux:~/Project2$ python experment.py Traceback (most recent call last): File "experment.py", line 13, in curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item) sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 4, and there are 1 supplied. here's the codes import sqlite3 import csv f = open('/home/waseem/Project2/photos.txt') csv.field_size_limit(100000) #see below! input = csv.reader(f, delimiter='\t') conn = sqlite3.connect('/home/waseem/Project2/picutres.db') curse = conn.cursor() curse.execute('CREATE TABLE photos (Name VARCHAR(100) PRIMARY KEY, Date INTEGER, Make VARCHAR(50), Tag VARCHAR(100))') for item in input: curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item) curse.commit() -- View this message in context: http://www.nabble.com/importing-csv-file-into-sqlite-tp21067453p21068111.html Sent from the Python - python-list mailing list archive at Nabble.com. From cesium5500 at yahoo.ca Fri Dec 5 09:27:39 2008 From: cesium5500 at yahoo.ca (Guy Doune) Date: Fri, 05 Dec 2008 09:27:39 -0500 Subject: pretty strange behavior of "strip" FORGET THE LAST ONE In-Reply-To: <493936EC.9030606@yahoo.ca> References: <4938693F.6090709@yahoo.ca> <493936EC.9030606@yahoo.ca> Message-ID: <49393A5B.9090009@yahoo.ca> Guy Doune a ?crit : > Ok, didn't show the whole problem... > > I will read the doc anyway, but why "questions.html" keep it "t"?? > > >>> test=['03.html', '06.html', 'questions.html', '04.html', > 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test[4] > 'toc.html' > >>> test[4].strip('.html') > 'oc' > >>> test[2].strip('.html') > 'questions' > > Thanks. > > Guy > > Guy Doune a ?crit : >> Hi everybody, >> >> Could it be a bug????? >> >> Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) >> [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> test=['03.html', '06.html', 'questions.html', '04.html', >> 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] >> >>> test >> ['03.html', '06.html', 'questions.html', '04.html', 'toc.html', >> '01.html', '05.html', '07.html', '02.html', '08.html'] >> >>> test[4] >> 'toc.html' >> >>> test[4].strip('.html') >> 'oc' >> >> Can't figure out what is going on, really. >> >> Guy >> > From bignose+hates-spam at benfinney.id.au Mon Dec 1 15:54:55 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 02 Dec 2008 07:54:55 +1100 Subject: Emacs vs. Eclipse vs. Vim References: <1228094836.4406.6.camel@generator> Message-ID: <87myffwr8g.fsf@benfinney.id.au> Peter Anderson writes: > What I have done is skipped the whole Vim/Emacs obscure editor thing > and opted for PyScripter PyScripter is not obscure, compared to Emacs and Vim? I think I need a new ironometer. -- \ ?I went to a garage sale. ?How much for the garage?? ?It's not | `\ for sale.?? ?Steven Wright | _o__) | Ben Finney From rt8396 at gmail.com Sun Dec 14 01:24:42 2008 From: rt8396 at gmail.com (r) Date: Sat, 13 Dec 2008 22:24:42 -0800 (PST) Subject: 1 or 1/0 doesn't raise an exception References: <49446E39.6020807@tim.thechases.com> Message-ID: <8972c415-2fbb-479f-8a03-b8b29b20ac42@g38g2000yqn.googlegroups.com> > Let me just point out that unsuspecting people (like me) might rely on > the whole expression to be evaluated and rely on exceptions being > raised if needed. This happens when people assume something ;) Use a different construct if you want to catch error's, I don't understand how you could not get it? >>> bool(1) True >>> bool(0) False >>> bool([]) False >>> bool([0]) True >>> bool([0,0,0]) True >>> bool({}) False >>> bool(()) False see a pattern here? >>> [] or {} or () or 0 or 1 1 >>> bool('python rules!') True From noone at lewscanon.com Mon Dec 1 20:31:17 2008 From: noone at lewscanon.com (Lew) Date: Mon, 01 Dec 2008 20:31:17 -0500 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: Jon Harrop wrote: > Xah Lee wrote: (nothing Java-related) Please take this crud out of the Java newsgroup. -- Lew From eliben at gmail.com Tue Dec 9 02:46:01 2008 From: eliben at gmail.com (eliben) Date: Mon, 8 Dec 2008 23:46:01 -0800 (PST) Subject: SequenceMatcher bug ? Message-ID: Hello, This is about Python 2.5.2 - I don't know if there were fixes to this module in 2.6/3.0 I think I ran into a bug with difflib.SequenceMatcher class. Specifically, its ratio() method. The following: SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + [5]).ratio () returns 0.0 While the same with 500 replaced by 100 returns .99... something Looking at the code of SequenceMatcher there's some caching going on when the sequences are longer than 200 elements (and indeed, I can reproduce the bug above 200 but not below). Can anyone confirm that this misbehaves and suggest a workaround ? P.S. quick_ratio() works fine, it seems. Thanks Eli From tjreedy at udel.edu Wed Dec 10 13:54:42 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 10 Dec 2008 13:54:42 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Rasmus Fogh wrote: > Rhamphoryncus wrote: >> You grossly overvalue using the "in" operator on lists. > > Maybe. But there is more to it than just 'in'. If you do: >>>> c = numpy.zeros((2,)) >>>> ll = [1, c, 3.] > then the following all throw errors: > 3 in ll, 3 not in ll, ll.index(3), ll.count(3), ll.remove(3) > c in ll, c not in ll, ll.index(c), ll.count(c), ll.remove(c) > > Note how the presence of c in the list makes it behave wrong for 3 as > well. So do not put numpy arrays into lists without wrapping them. They were designed and semi-optimized, by a separate community, for a specific purpose -- numerical computation -- and not for 'playing nice' with other Python objects. It is a design feature of Python that people can implement specialized objects with specialized behaviors for specialized purposes. From paul at boddie.org.uk Fri Dec 5 08:45:40 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 5 Dec 2008 05:45:40 -0800 (PST) Subject: ANN: Shed Skin 0.0.30, an experimental (restricted-)Python-to-C++ Compiler References: Message-ID: <69be21c3-c71d-42a2-9d23-fdea8a832dd0@o40g2000prn.googlegroups.com> On 5 Des, 12:24, "Mark Dufour" wrote: > Hi all, > > I have just released version 0.0.30 of Shed Skin, an experimental > (restricted) Python-to-C++ compiler. I think Mark forgot to post some links. ;-) http://shed-skin.blogspot.com/ http://code.google.com/p/shedskin/ Paul From bdesth.quelquechose at free.quelquepart.fr Sun Dec 21 14:41:37 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 21 Dec 2008 20:41:37 +0100 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: <494ea9a5$0$24542$426a34cc@news.free.fr> r a ?crit : > I noticed when i mentioned "self" nobody wants to touch that subject. > There could be many reasons why... > > 0.) nobody but the 10 regulars i see here exists > 1.) nobody cares(doubt it) > 2.) nobody is brave enough to question it(maybe) > 3.) most people like to type self over and over again(doubt it) > 4.) most people here have given up on changing the BDFL's mind about > it. (good possibility) > 5.) this is a hot-button topic(no doubt in my mind!) 6.) you are definitevely clueless. (snip) > I love python's classes, but HATE self.redundant! This declaration only makes clear that answer to your above question is #6. > This really needs to > be fixed, Your ignorance needs to be fixed, yes, indeed. Please go and fix it - all the relevant materials is available in (or linked from somewhere in) this newgroup's archives. > and you have not heard the last from me about it!!! As far as I'm concerned, yes. Welcome to my bozo filter. Please come back when you'll have grown a brain. From p.f.moore at gmail.com Sun Dec 14 12:51:03 2008 From: p.f.moore at gmail.com (Paul Moore) Date: Sun, 14 Dec 2008 09:51:03 -0800 (PST) Subject: Looking for the best way to translate an idiom References: <4945406a$0$1127$426a74cc@news.free.fr> Message-ID: <2c5ad999-47f9-4040-85c9-4c9438afe4bb@b41g2000pra.googlegroups.com> On 14 Dec, 16:22, Bruno Desthuilliers wrote: > if you only want the first returned value, you can just apply a slice: > > def f(): > ? ? return 1,2,3 > > a = f()[0] + 1 Hmm, true. I'm not sure it's any less ugly, though :-) > FWIW, Python 2.6 has NamedTuple objects... I know, but I want to target 2.5+ (I still have a number of systems running 2.5) > > - have 2 calls, one to return just the position, one to return both. > > This feels awkward, because of the 2 method names to remember. > > You forgot one solution: passing a flag to the function to specify if > you want only the main result or the extra ones as well, and give this > flag the appropriate default value depending on most common use case. True, that's another option. It might work, I'll think about it. > The one that happens to be the most simple for the most common usecase, > while still providing support for more advanced stuff. Exactly. I'll have to think some more about real use cases. > > I suspect my intuition isn't accurate here, as most of the use I've > > made of the library is in writing tests, which isn't typical use :-( > > So perhaps you should start writing some real-life code ? :-) Once I have a library that's functional enough to do so, I may well. Chicken and egg situation, to some extent... And I don't really feel like switching to Lua just to get a feel for how the library gets used! > > Thanks for any assistance. > > Not sure I've been that helpful. Sorry... Any feedback helps. Thanks for taking the time. Paul. From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 30 04:34:21 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 30 Dec 2008 10:34:21 +0100 Subject: SQL, lite lite lite In-Reply-To: <8vco26x1v6.ln2@joelaptop.homelan.net> References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> <8vco26x1v6.ln2@joelaptop.homelan.net> Message-ID: <4959eb17$0$32023$426a74cc@news.free.fr> Johannes Bauer a ?crit : (snip) > Even if it took (as you mentioned) a semester of SQL studies - which it > does not - why do you think your syntax is easier? The only person your > proposed syntax is easier for is you. Get over it, learn SQL, and enjoy > the benefits of one unified standard - not everyone cooking their own > soup. You'll be able to learn PostgreSQL, Oracle SQL, mySQL, SQlite all > at once! Oh what a beautiful dream... We all wish we'd live in such a perfect world. Sadly, it's not the case. First because each SQL vendor cooks its own soup, so you still have to learn each SQL implementation, limitations and gory details. Also, because handling SQL queries as raw strings is more than painfull. It just doesn't play well with the host language. So any non trivial project ends up reinventing its own half-backed abstraction layer, that you have to learn too. Now I don't mean that learning SQL (and the relational theory behind SQL) is a waste of time. You obviously need a good understanding of SQL to use a SQL database - directly or thru any abstraction layer. We definitively agree on this. But a smart abstraction layer (like SQLAlchemy, or even the less powerfull but still pretty good Django ORM) at least avoids reinventing a new one for each project. My 2 cents... From google at mrabarnett.plus.com Sun Dec 21 11:33:30 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 21 Dec 2008 16:33:30 +0000 Subject: Python is slow In-Reply-To: <6r6hpfFfb643U3@mid.uni-berlin.de> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> <6r6hpfFfb643U3@mid.uni-berlin.de> Message-ID: <494E6FDA.4070401@mrabarnett.plus.com> Marc 'BlackJack' Rintsch wrote: > On Sat, 20 Dec 2008 14:18:40 -0800, cm_gui wrote: > >>> Seriously cm_gui, you're a fool. >>> Python is not slow. >> haha, getting hostile? >> python fans sure are a nasty crowd. >> >> Python is SLOW. >> >> when i have the time, i will elaborate on this. > > You are not fast enough to elaborate on Python's slowness!? :-) > > cm_gui is slow! > > Ciao, > Marc 'BlackJack' Rintsch > Correction: cm_gui is SLOW! :-) From ptmcg at austin.rr.com Mon Dec 8 14:21:00 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 8 Dec 2008 11:21:00 -0800 (PST) Subject: Text parsing via regex References: Message-ID: <37b28494-c98f-4e06-a451-8a4702030f10@v38g2000yqb.googlegroups.com> On Dec 8, 12:13?pm, Robocop wrote: > I'm having a little text parsing problem that i think would be really > quick to troubleshoot for someone more versed in python and Regexes. > I need to write a simple script that parses some arbitrarily long > string every 50 characters, and does not parse text in the middle of > words Are you just wrapping text? If so, then use the textwrap module. import textwrap source_string = "a bunch of nonsense that could be really long, or really short depending on the situation" print textwrap.fill(source_string,50) print textwrap.wrap(source_string,50) print map(len,textwrap.wrap(source_string,50)) pad50 = lambda s : (s+ " "*50)[:50] print '|\n'.join(map(pad50,textwrap.wrap(source_string,50))) Prints: a bunch of nonsense that could be really long, or really short depending on the situation ['a bunch of nonsense that could be really long, or', 'really short depending on the situation'] [49, 39] a bunch of nonsense that could be really long, or | really short depending on the situation -- Paul From ed at leafe.com Wed Dec 10 14:24:39 2008 From: ed at leafe.com (Ed Leafe) Date: Wed, 10 Dec 2008 13:24:39 -0600 Subject: Dabo 0.9.0 Released Message-ID: <47C9D05A-1D50-4690-8062-03939E1C9AE7@leafe.com> We are proud (and relieved!) to finally release Dabo 0.9.0, the first official release of the framework in six months. We haven't been taking it easy during that period; rather, we made some changes that clean up some weak spots in the codebase, and as a result can offer a much more solid framework, and are on course for a 1.0 release in the near future. To do this, we made some decisions that break backwards compatibility. We dropped support for Python versions earlier than 2.4, and wxPython versions below 2.8. Supporting everything is nice to aim for, but completely impractical. There is also a major addition to the framework: the ability to deploy Dabo applications as true web apps. Imagine: being able to develop a rich internet app using nothing but Python on both the client and server! It's still early in the development process, so it's lacking a lot of the supporting tools, and almost no documentation has been created, but that will be coming in the next few weeks/months. When you deploy your app as a web app, all data access and business logic is on the server, and the framework automatically handles the communication between the client and server. The framework also automatically grabs file changes from the server, making UI updates seamless and quick. Lots more interesting stuff will be happening in this area in the near future, so stay tuned! If you're not already familiar with Dabo, we're the premier open source framework for developing desktop (and now web!) applications in Python. We make the difficult stuff like binding databases to UI controls simple. You can grab the latest version from http://dabodev.com/download A fairly comprehensive list of the changes we've made since the last release can be found at http://svn.dabodev.com/dabo/tags/dabo-0.9.0/ChangeLog And if you want to learn more, join our email list: http://leafe.com/mailman/listinfo/dabo-users -- Ed Leafe From jeremiah.dodds at gmail.com Thu Dec 25 07:19:39 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Thu, 25 Dec 2008 07:19:39 -0500 Subject: os.system('cls') In-Reply-To: References: <05BADA85-33ED-48BF-B251-2CC830D6D55E@rgbaz.eu> Message-ID: <12cbbbfc0812250419m68de6079v7ea0d47f5c21ad94@mail.gmail.com> On Thu, Dec 25, 2008 at 7:11 AM, Dennis van Oosterhout < de.slotenzwemmer at gmail.com> wrote: > Btw...does that mean that system('cls') only works on Windows...or to > say it otherwise: the program isn't platform independant? > > Yes. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Thu Dec 25 16:29:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Dec 2008 19:29:14 -0200 Subject: question; C/C++ with Python References: <123f104c-0edc-423f-841d-70d8d9492ddd@r15g2000prd.googlegroups.com> Message-ID: En Thu, 25 Dec 2008 12:50:31 -0200, Hongtian escribi?: > I have a C/C++ application and I wrote a .py file to extend it. > The .py file includes some simple functions without import any other > modules. And you embedded the Python interpreter into your application, I presume? > Today, I want to update my .py file and import SMTP library in the > file, but it seems fail to import SMTP library. > > So I want to ask: when the .py file is used to extend C/C++ > application, can it import other modules? Sure! Just make sure the desired modules can be found along the Python search path (that is, sys.path) > How to do that? should I > copy all pythons libs to my C/C++ application directory? That could be > terrible... If you want to distribute your application, this would be a good thing, else you must rely on the right Python version being installed somewhere. You may add the required entries to sys.path manually, in your code. Or you may define the PYTHONPATH environment variable (also in your code) before initializing the interpreter. Or you may call the function Py_SetProgramName (before initializing) pointing to your external Python installation. -- Gabriel Genellina From google at mrabarnett.plus.com Mon Dec 22 14:10:11 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 22 Dec 2008 19:10:11 +0000 Subject: Python's popularity In-Reply-To: References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: <494FE613.5080107@mrabarnett.plus.com> r wrote: > Steve Holden >> What makes you assume this is a zero-sum game, and that Python won't >> survive if any other language becomes popular. Every language borrows >> from those that came before it. Terms like "outright plagiarism" don't >> encourage rational debate, and make you seem like a troll who is more >> interested in stirring up controversy than actually doing things to help >> promote the language. > > This is a war Steve, and i will explain why. Python does not need to > compete with perl, lisp, C, basic, etc, etc. WHY, well because python > is SO radically different than those languages. Ruby on the other > hand, took most from python, the only difference is Ruby's full OO > integration.(12.method()). Since Ruby is so similar to python we must > consider that some people who would have found only python in this > niche now could go to Ruby. I am for choices, but this is out and out > robbery! > Of course we must stand on the shoulders of greater minds than our own > to get ahead, but using someone's knowledge against them is wrong. If > Ruby want's to incorporate so many Pythonian ideas into their > language, at least put a note in the tutorial giving credit to Guido > for his wisdom. Don't use our ideas and then bash python in the next > breath! > [snip] "Pythonian"? A real Pythonista would know it's "Pythonic"! A real Pythonista would be called "p", not "r", which sounds very Rubish(?) to me... From Slaunger at gmail.com Thu Dec 4 04:09:08 2008 From: Slaunger at gmail.com (Slaunger) Date: Thu, 4 Dec 2008 01:09:08 -0800 (PST) Subject: Pythonic design patterns Message-ID: Hi comp.lang.python I am this novice Python programmer, who is not educated as a computer scientist (I am a physicist), and who (regrettably) has never read the GOF on design patterns. I find myself spending a lot of time in Python making some designs, to solve some task, which is the end turn out to be closely related to well established design patterns / programming idioms, which other users in this forum has been kind enough to point out. Only my implementations are often not that clean, and I may call things something different than the normal convention, which is a source of confusion for myself and others trying to communicate with me. I guess I could boost my productivity by learning these well-proven and well-established design patterns by heart. I was therefore wondering if you could recommend a book or a resource concerning design patterns with special focus on the possibilities in Python? In that manner I may be able to both learn programming more pythonic AND learn the design patterns. -- Slaunger From jamskip at googlemail.com Mon Dec 15 04:56:37 2008 From: jamskip at googlemail.com (jamskip at googlemail.com) Date: Mon, 15 Dec 2008 01:56:37 -0800 (PST) Subject: Thread Locking issue - Can't allocate lock (sem_init fail) Message-ID: Hi all, I have a peculiar problem with a multithreaded program of mine (actually I've sort of inherited it). Before i show you the error, here's a litle background. Its a program to check email addresses are valid, and its main task is to verify the domain names. Here's the basic functionality: * The prog has a list of domains it has seen before which is read into memory (the 'rollover'). * A new list of emails is read-in from a file (to a queue) and is checked against the rollover. * If we've seen the domain before then update the existing entry. * If we've not seen the domain before, add it. The program is multithreaded to speed up the processing...there are input and output Queues. Now, each domain entry is an class object containing various bits of info. Each domain class also has its own lock, so that only one thread can modify each domain at a time. I'm load-testing the program with a sample of 1 million email addresses and when i hit about the 500,000 mark i get a locking error... sem_init: No space left on device Exception in thread Thread-2: Traceback (most recent call last): File "/usr/local/lib/python2.4/threading.py", line 442, in __bootstrap self.run() File "/usr/local/lib/python2.4/threading.py", line 422, in run self.__target(*self.__args, **self.__kwargs) File "jess.py", line 250, in worker record.result = function( id, record.value ) File "jess.py", line 291, in action found_domain = domains.addNewDomain( domain_name ) File "jess.py", line 123, in addNewDomain self.domain_store.append( self.Domain( name = name ) ) File "jess.py", line 46, in __init__ self.lock = Lock() error: can't allocate lock Googling for this sort of error doesn't yield any results, and i can't find any information about limits to the number of locks you can have in Python. The 'No space left on device' message indicates a memory issue, however i doubt this since its running on a linux server with 4 cores and 16GB ram. It seems more like an internal Python limit has been hit (sem_init - semaphore initialisation?). Does anyone know more about threading internals and any internal limits? For the timebeing, I've implemented locking at a higher level which will reduce performance but keep the number of lock objects to a minumum. Thanks From skip at pobox.com Thu Dec 11 09:48:48 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 11 Dec 2008 08:48:48 -0600 Subject: How can I understan the "for" here? In-Reply-To: <49412744.8040301@gmail.com> References: <49412744.8040301@gmail.com> Message-ID: <18753.10320.829867.403714@montanaro-dyndns-org.local> Kermit> I can't understand the second sentence because of the "for Kermit> ... in". Google for "python list comprehensions". -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From arnodel at googlemail.com Tue Dec 2 17:38:14 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 2 Dec 2008 14:38:14 -0800 (PST) Subject: best way to do this References: Message-ID: <24947f71-3a1c-4ea9-9b8b-8efdcbfbe5f4@v42g2000yqv.googlegroups.com> On Dec 2, 2:09?pm, TP wrote: > Hi everybody, > > >>> c=[(5,3), (6,8)] > > From c, I want to obtain a list with 5,3,6, and 8, in any order. > I do this: > > >>> [i for (i,j) in c] + [ j for (i,j) in c] > > [5, 6, 3, 8] > > Is there a quicker way to do this? > One list comprehension is enough: >>> c=[(5,3), (6,8)] >>> [x for t in c for x in t] [5, 3, 6, 8] HTH -- Arnaud From xahlee at gmail.com Mon Dec 8 12:34:43 2008 From: xahlee at gmail.com (Xah Lee) Date: Mon, 8 Dec 2008 09:34:43 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> Message-ID: <0201522a-b15a-4401-a208-5d9af70bdd74@w24g2000prd.googlegroups.com> On Dec 8, 5:10 am, Jon Harrop wrote: > Xah Lee wrote: > > For those interested in this Mathematica problem, i've now cleaned up > > the essay with additional comments here: > > > ? A Mathematica Optimization Problem > > http://xahlee.org/UnixResource_dir/writ/Mathematica_optimization.html > > In that article you say: > > > Further, if Intersect is made to take a flat sequence of argument as > > in ?Intersect[o_, d_, lambda_, n_, c_, r_, s_]?, then pattern matching can > > be avoided by making it into a pure function ?Function?. And when it is > > a ?Function?, then Intersect or part of it may be compiled with Compile. > > When the code is compiled, the speed should be a order of magnitude > > faster. > That is incorrect. Mathematica's Compile function cannot handle recursive > functions like Intersect. i didn't claim it can. You can't expect to have a fast or good program if you code Java style in a functional lang. Similarly, if you want code to run fast in Mathematica, you don't just slap in your OCaml code into Mathematica syntax and expect it to work fast. If you are a Mathematica expert, you could make it recurse yet have the speed as other langs. First, by changing your function's form, to avoid pattern matching, and rewrite your bad recursion. That is what i claimed in the above paragraph. Read it again to see. > For example: > In[1]:= Compile[{n_, _Integer}, If[# == 0, 1, #0[[# n - 1]] #1] &[n]] > > During evaluation of In[1]:= Compile::fun: Compilation of > (If[#1==0,1,#0[[#1 n-1]] #1]&)[Compile`FunctionVariable$435] cannot > proceed. It is not possible to compile pure functions with arguments > that represent the function itself. >> Mathematica's Compile function is intended to speed up numerical computation. To want Compile to handle recursion in the context of Mathematica's programing features, is not something possible even in theoretical sense. Scheme lisp implementations can compile recursive code, but lisp is a lower level lang than Mathematica, where perhaps the majority of Mathematica's builtin functions can equate to 10 or more lines of lisp, and any of its hundreds math functions equates to entire libraries of other langs. It is reasonable, but silly, to expect Mathematica's Compile function to compile any code in Mathematica. Perhaps in the future version of Mathematica, its Compile function can handle basic recursive forms. Also, in this discussion, thanks to Thomas M Hermann's $20 offered to me for my challenge to you, that i have taken the time to show working code that demonstrate many problems in your code. Unless you think my code and replies to you are totally without merit or fairness, but otherwise you should acknowledge it, in whole or in parts you agree, in a honest and wholehearted way, instead of pushing on with petty verbal fights. Xah ? http://xahlee.org/ ? From bdesth.quelquechose at free.quelquepart.fr Wed Dec 17 16:11:19 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 17 Dec 2008 22:11:19 +0100 Subject: Why no lexical scoping for a method within a class? In-Reply-To: <5ad98089-883f-4ca6-934e-605e2376439c@f40g2000pri.googlegroups.com> References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> <5ad98089-883f-4ca6-934e-605e2376439c@f40g2000pri.googlegroups.com> Message-ID: <494978ad$0$22014$426a74cc@news.free.fr> walterbyrd a ?crit : > On Dec 17, 8:41 am, prueba... at latinmail.com wrote: > >> If scoping worked as you want, how, pray tell, would you define object >> attributes?- Hide quoted text - > > I suppose you could do this: > > class className(): > varname = "whatever" This defines a class attribute - that is, an attribute of the className class object, accessible either thru the className object or it's instances if not shadowed by an instance attribute by the same name/ > def fname(self, varname): > . . . . > > Instead of having variable defined within methods to be global > everywhere within the class. There's nothing like a "variable defined within (a) method", because you never define methods in Python - only functions. So there's no difference in scoping rules for functions defined within a class statement block or outside a class statement block. > Anyway, it's not a matter of what I like, I am just trying to > understand the reason behind the scoping rules. Then you should start with understanding the scoping rules. From deets at nospam.web.de Sat Dec 13 13:36:59 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 13 Dec 2008 19:36:59 +0100 Subject: [OT] stable algorithm with complexity O(n) In-Reply-To: References: Message-ID: <6qidmbFc4qduU1@mid.uni-berlin.de> David Hl??ik schrieb: > Hi guys, > > i am really sorry for making offtopic, hope you will not kill me, but > this is for me life important problem which needs to be solved within > next 12 hours.. > > I have to create stable algorithm for sorting n numbers from interval > [1,n^2] with time complexity O(n) . > > Can someone please give me a hint. Would be very very thankful! Unless I grossly miss out on something in computer science 101, the lower bound for sorting is O(n * log_2 n). Which makes your task impossible, unless there is something to be assumed about the distribution of numbers in your sequence. Who has given you that assignment - a professor? Or some friend who's playing tricks on you? Diez From grante at visi.com Sun Dec 7 10:48:19 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 07 Dec 2008 09:48:19 -0600 Subject: how to get a beep, OS independent ? References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> Message-ID: On 2008-12-07, Joe Strout wrote: > But invoking the standard system beep What makes you think there is such a thing as "the standard system beep"? -- Grant From invalid at invalid Tue Dec 23 15:57:52 2008 From: invalid at invalid (Grant Edwards) Date: Tue, 23 Dec 2008 14:57:52 -0600 Subject: pseudo terminal usage from Python? References: <5t-dnRgMi9Z4lszUnZ2dnUVZ_vOdnZ2d@posted.visi> Message-ID: <1JqdnU9Oz9ZNzczUnZ2dnUVZ_hCdnZ2d@posted.visi> On 2008-12-23, skip at pobox.com wrote: > Grant> Are you sure it's not Python buffering its input? Have you tried > Grant> "python -u mympstat.py"? > > >> Nope. -u unbuffers stdout and stderr, not stdin. It really must be > >> mpstat being uncooperative. > > Grant> That's not what my python man page says: > > Grant> -u Force stdin, stdout and stderr to be totally > Grant> unbuffered. On systems where it matters, also put > Grant> stdin, stdout and stderr in binary mode. > > Grant> That's for 2.5.2, but that's how I remember previous versions > Grant> working as well. > > I'm still running 2.4.5 at work. It's -u help: > > -u : unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x) > see man page for details on internal buffering relating to '-u' > > Was stdin unbuffering maybe added in 2.5? Let's do some experiments... $ cat echo.py import sys while 1: line = sys.stdin.readline() sys.stdout.write(line) $ (while sleep 1; do date; done) | python2.4 echo.py [I see a line printed once per second.] $ (while sleep 1; do date; done) | python2.5 echo.py [same as 2.4] Is python stdin is line-buffered by default? We'll do a version that doesn't have newlines in the input stream... $ cat echo2.py import sys while 1: sys.stdout.write(sys.stdin.read(1)) $ (while sleep 1; do echo -n $(date); done) | python2.4 echo2.py [wait 10-20 seconds -- no output. When I hit ctrl-C, I see a all the output.] $ (while sleep 1; do echo -n $(date); done) | python2.5 echo2.py [same as 2.4] It appears the by default both 2.4 and 2.5 have line-buffered stdin. Let's try -u... $ (while sleep 1; do echo -n $(date); done) | python2.4 -u echo2.py [I see output once per second.] $ (while sleep 1; do echo -n $(date); done) | python2.5 -u echo2.py [same as 2.4] Under Linux, the '-u' option unbuffers stdin in both 2.4 and 2.5. It just isn't mentioned in the help output or the man page for 2.4. -- Grant Edwards grante Yow! Will the third world at war keep "Bosom Buddies" visi.com off the air? From Slaunger at gmail.com Tue Dec 9 18:24:28 2008 From: Slaunger at gmail.com (Slaunger) Date: Tue, 9 Dec 2008 15:24:28 -0800 (PST) Subject: Best way to report progress at fixed intervals References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> Message-ID: <43016471-d0ce-4912-b18d-03407928acf1@w1g2000prm.googlegroups.com> On 10 Dec., 00:11, rdmur... at bitdance.com wrote: > >> ? ? ? ? ?# Monitoring loop. > >> ? ? ? ? ?loops = 0 > >> ? ? ? ? ?# We're going to loop ten times per second using an integer count, > >> ? ? ? ? ?# so multiply the seconds parameter by 10 to give it the same > >> ? ? ? ? ?# magnitude. > >> ? ? ? ? ?intint = int(self.progress_interval*10) > > Is this not an unnecessary complication? > >> ? ? ? ? ?# isAlive will be false after dowork returns > >> ? ? ? ? ?while worker.isAlive(): > >> ? ? ? ? ? ? ?loops += 1 > >> ? ? ? ? ? ? ?# Wait 0.1 seconds between checks so that we aren't chewing > >> ? ? ? ? ? ? ?# CPU in a spin loop. > >> ? ? ? ? ? ? ?time.sleep(0.1) > > Why not just call this with progress_interval directly? > > Because then the program make take up to progress_interval seconds to > complete even after all the work is done. ?For a long running program > and a short progress_interval that might not matter, so yes, that would > be a reasonable simplification depending on your requirements. > Ah, OK. With my timer.cancel() statement in my original proposal I avoided that. > > > OK. I agree this is a more elegant implementation, although I my mind, > > I find it more natural if the reporting goes on in a subthread, but > > You could pretty easily rewrite it to put the reporter in the subthread, > it was just more natural to _me_ to put the worker in the subthread, > so that's how I coded it. ?Note, however, that if you were to write a > GUI front end it might be important to put the worker in the background > because on some OSes it is hard to update GUI windows from anything > other than the main thread. ?(I ran into this in a Windows GUI ap I > wrote using wxPython). > Ah, yes, you right. For GUIs this is often quite important. I don't do much GUI, so This is not something I had strongly in mind. Br, -- Slaunger From lists at cheimes.de Fri Dec 12 10:55:57 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 12 Dec 2008 16:55:57 +0100 Subject: Python is slow In-Reply-To: <8156b37b-d1f6-4142-ad6e-8488c95b6592@z28g2000prd.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> <8156b37b-d1f6-4142-ad6e-8488c95b6592@z28g2000prd.googlegroups.com> Message-ID: sturlamolden schrieb: > On Dec 12, 3:04 pm, Luis M. Gonz?lez wrote: > >> Why don't you guys google a little bit to know what's being done to >> address python's "slowness"?? > > Nothing is being done, and woth Py3k it got even worse. Indeed, it *is* slower for now. As I already said in another thread our top priorities were feature completeness and bug fixing. Optimizations will follow the features in the near future. Christian From joe at strout.net Mon Dec 22 17:16:24 2008 From: joe at strout.net (Joe Strout) Date: Mon, 22 Dec 2008 15:16:24 -0700 Subject: Python's popularity In-Reply-To: References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <18767.47566.709705.92@montanaro-dyndns-org.local> Message-ID: <495011B8.1050607@strout.net> Alvin ONeal wrote: > Also worthy of mention: > I've seen python pre-installed on consumer HP desktops (I think as > part of a backup/restore script, but I'm not sure) It's pre-installed on every Mac (both desktop and laptop), too. Cheers, - Joe From skip at pobox.com Thu Dec 11 17:50:12 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 11 Dec 2008 16:50:12 -0600 Subject: Python 2.5.2 error on Solaris, No module named _md5 In-Reply-To: References: Message-ID: <18753.39204.493828.300991@montanaro-dyndns-org.local> Shawn> When I "import md5", I got: ... Shawn> import _md5 Shawn> ImportError: No module named _md5 Check the output of the build process to see if the _md5 extension failed to build, and if so, dig into the setup.py file a bit. It's likely that you forgot to include the proper include and lib directories when building Python so distutils didn't know where to find the necessary header files and libraries. Also, make sure the necessary stuff is actually installed on your system. Many Linux systems install header files and libraries as separate packages. You might have the latter but not the former. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From rt8396 at gmail.com Sat Dec 20 19:27:22 2008 From: rt8396 at gmail.com (r) Date: Sat, 20 Dec 2008 16:27:22 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> <59153e28-bf86-4158-96d9-23aa5b9f0205@j35g2000yqh.googlegroups.com> Message-ID: <52b8e001-2cc7-4891-8540-a3cdb6b78533@e25g2000vbe.googlegroups.com> Thanks MRAB, except the float is not 2 decimal places, but its there Come on... They did this for the interpreter not us. It's easer to parse this string with positional arguments and a dict of format descriptions. Come on pydev, at least be honest about it! From BrooklineTom at gmail.com Wed Dec 10 23:48:01 2008 From: BrooklineTom at gmail.com (brooklineTom) Date: Wed, 10 Dec 2008 20:48:01 -0800 (PST) Subject: Deeper tracebacks? References: <7e1c74f0-8f72-4a88-935b-90b77fe5aaa5@s37g2000vbp.googlegroups.com> Message-ID: On Dec 10, 10:49 pm, "Chris Rebert" wrote: > On Wed, Dec 10, 2008 at 3:50 PM, brooklineTom wrote: > > On Dec 10, 5:03 pm, "Gabriel Genellina" > > wrote: > >> En Wed, 10 Dec 2008 16:59:16 -0200, brooklineTom > >> escribi?: > > >> > I want my exception handler to report the method that originally > >> > raised an exception, at the deepest level in the call-tree. Let give > >> > an example. > > >> That's the default behavior, you don't have to do anything special. > > >> > import sys, traceback > >> > class SomeClass: > >> > def error(self): > >> > """Raises an AttributeError exception.""" > >> > int(3).zork() > > >> > def perform_(self, aSelector): > >> > try: > >> > aMethod = getattr(self, aSelector, None) > >> > answer = apply(aMethod, [], {}) > >> > except: AttributeError, anAttributeErrorException: > >> > aRawStack = traceback.extract_stack() > >> > answer = None > > >> (I assume you're using Python < 3.0) > >> Use the 3-names form of the except statement: > > >> try: > >> aMethod = getattr(self, aSelector, None) > >> answer = aMethod() > >> except AttributeError, e, tb: > >> # the tb variable holds the traceback up to the error > >> # the same thing you see printed by Python when > >> # an unhandled error happens > >> answer = None > > >> Alternatively, you can obtain the same thing with sys.exc_info()[2] > >> Remember to delete any reference to the traceback object as soon as you're > >> done with it; seehttp://docs.python.org/library/sys.html#sys.exc_info > > >> -- > >> Gabriel Genellina > > > I'm using Python 2.5. > > > As I understand it, "aRawStack" (above) has the same information as > > sys.exc_info()[2]. > > > The deepest entry in aRawStack is the perform_ invocation. The > > contents of the two bottom-most stack frames are: > >>>> aRawStack[8][3] > > "answer = anObject.perform_('error')" > >>>> aRawStack[9][3] > > 'aRawStack = traceback.extract_stack()' > > > By the time the handler is called, "zork" -- the method that was > > called when the exception was raised, and "error", the method that > > invoked zork, have already been removed from the stack. > > There is no zork() method, so it *can't have been called* and > therefore *can't be in the traceback*. The error lies in the method > that's trying to call a _nonexistent_ method, and that's where Python > reports the error. > > Recall that: > x.zork() > > is equivalent to: > _z = x.zork #error occurs here, in the attribute lookup > _z() #Python never gets here > > So no call takes place because you get an AttributeError before Python > can get any further. zork() would only in the traceback if (1) it was > looked up and called successfully [not the case here] and (2) an error > occurred in zork()'s method body [again, not the case because it's not > defined]. > > Cheers, > Chris > > -- > Follow the path of the Iguana...http://rebertia.com I understand that there is no method named "zork". The attempted call to zork occurred in the method named "error", *not* the method named "perform_". I suggest that the failing method is "error", and the reported line number should be the line that contains "int(3).zork". Specifically, I think that aRawStack should contain the following: >>> aRawStack[8][3] "answer = anObject.perform_('error')" >>> aRawStack[9][3] "answer = anObject.error()" >>> aRawStack[10][3] 'aRawStack = traceback.extract_stack()' The entry at aRawStack[9] is the stack frame that I suggest is missing. Thx, Tom From igouy2 at yahoo.com Tue Dec 23 17:21:01 2008 From: igouy2 at yahoo.com (Isaac Gouy) Date: Tue, 23 Dec 2008 14:21:01 -0800 (PST) Subject: 2to3 used in the Shootout References: <4f1a8f03-fd7f-49ea-8031-61f73fb0c0e8@x16g2000prn.googlegroups.com> Message-ID: <65a43a69-1ef2-4a41-b860-a370891aecbd@g39g2000pri.googlegroups.com> On Dec 23, 11:51?am, bearophileH... at lycos.com wrote: > They have translated the Python benchmarks of the Shootout site from > Py2 to Py3 using 2to3: > > http://shootout.alioth.debian.org/u32/benchmark.php?test=all?=pyt... So please re-write those programs to remove problems created by automatic translation and better take advantage of Python 3 functionality... http://shootout.alioth.debian.org/u32/faq.php#play > It shows some "performance bugs" of Python3 itself (especially > regarding the binary-trees benchmark, that was unexpected by me), and > two points where 2to3 may be improved, for example after the > translation this gives error: > ? ? ? ? ?table=string.maketrans('ACBDGHK\nMNSRUTWVYacbdghkmnsrutwvy', > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 'TGVHCDM > \nKNSYAAWBRTGVHCDMKNSYAAWBR')): > > Gives: > TypeError: maketrans arguments must be bytes objects > > Bye, > bearophile From ali2862006 at gmail.com Thu Dec 4 18:33:30 2008 From: ali2862006 at gmail.com (mido) Date: Thu, 4 Dec 2008 15:33:30 -0800 (PST) Subject: watch football online for free Message-ID: watch football online for free Watch with us through the Internet the most important football games, watched all the competition directly and free Egyptian league - Champions of Europe - the English league - regular French - German Bundesliga - Dutch league - Portuguese league - Spanish league - Turkish league Moment by moment on our site http://live-football.t35.com From metolone+gmane at gmail.com Fri Dec 5 07:39:26 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Fri, 5 Dec 2008 04:39:26 -0800 Subject: generating a liste of characters References: Message-ID: "Yves Dorfsman" wrote in message news:YywZk.17248$st1.2898 at newsfe10.iad... > Is there any built in way to generate a list of characters, something > along the line of range('a'-'z') ? > > Right now I am using: > > chars = [ chr(l) for l in range(0x30, 0x3a) ] # 0 - 9 > chars += [ chr(l) for l in range(0x41, 0x5b) ] # A - Z > chars += [ chr(l) for l in range(0x61, 0x7b) ] # a - z > > Is there a better, more straight forward way of doing that ? Writing a helper function reduces code repetition and improves readability: def crange(startch,endch): '''Return a list of characters from startch to endch, inclusive.''' return [chr(c) for c in xrange(ord(startch),ord(endch)+1)] chars = crange('0','9') + crange('A','Z') + crange('a','z') -Mark From __peter__ at web.de Mon Dec 8 06:23:58 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 08 Dec 2008 12:23:58 +0100 Subject: built-in functions as class attributes References: <75fdbf34-34d9-4373-bbe0-7e3f76dc4c3f@x38g2000yqj.googlegroups.com> Message-ID: Mark Dickinson wrote: > Here's a curiosity: after > > def my_hex(x): > return hex(x) > > one might expect hex and my_hex to be interchangeable > in most situations. But (with both Python 2.x and 3.x) > I get: > >>>> def my_hex(x): return hex(x) > ... >>>> class T(object): f = hex > ... >>>> class T2(object): f = my_hex > ... >>>> T().f(12345) > '0x3039' >>>> T2().f(12345) > Traceback (most recent call last): > File "", line 1, in > TypeError: my_hex() takes exactly 1 argument (2 given) > [36412 refs] > > Anyone know what the precise rules that lead to this > behaviour are, or where they're documented? To work properly as a method a callable needs a __get__() method implementing the binding mechanism. Functions written in C generally don't have that. >>> class A(object): ... def __call__(self, *args): ... print "called with", args ... >>> class B(object): ... a = A() ... >>> B().a() called with () Now let's turn A into a descriptor: >>> def __get__(self, inst, cls=None): ... print inst, cls ... if inst is not None: ... def bound(*args): ... self(inst, *args) ... return bound ... return self ... >>> A.__get__ = __get__ >>> B().a() <__main__.B object at 0x2ae49971b890> called with (<__main__.B object at 0x2ae49971b890>,) I don't know if there is something official, I google for http://users.rcn.com/python/download/Descriptor.htm or "descrintro" every time I need a refresher. Peter From rt8396 at gmail.com Mon Dec 22 14:57:23 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 11:57:23 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <1d03c66b-c725-42f4-af6e-2351a7841b30@z1g2000yqn.googlegroups.com> Message-ID: On Dec 22, 1:50?pm, Luis M. Gonz?lez wrote: > On Dec 22, 3:44?pm, r wrote: > > > > > Steve Holden > > > > What makes you assume this is a zero-sum game, and that Python won't > > > survive if any other language becomes popular. Every language borrows > > > from those that came before it. Terms like "outright plagiarism" don't > > > encourage rational debate, and make you seem like a troll who is more > > > interested in stirring up controversy than actually doing things to help > > > promote the language. > > > This is a war Steve, and i will explain why. Python does not need to > > compete with perl, lisp, C, basic, etc, etc. WHY, well because python > > is SO radically different than those languages. Ruby on the other > > hand, took most from python, the only difference is Ruby's full OO > > integration.(12.method()). Since Ruby is so similar to python we must > > consider that some people who would have found only python in this > > niche now could go to Ruby. I am for choices, but this is out and out > > robbery! > > Of course we must stand on the shoulders of greater minds than our own > > to get ahead, but using someone's knowledge against them is wrong. If > > Ruby want's to incorporate so many Pythonian ideas into their > > language, at least put a note in the tutorial giving credit to Guido > > for his wisdom. Don't use our ideas and then bash python in the next > > breath! > > > > I have an article about the Zen coming up in "Python Magazine" so I > > > won't steal its thunder. Suffice it to say that people take the Zen far > > > too seriously. Anyone who does so undermines their own credibility as a > > > Python commentator. This isn't a war. Stop being childish. > > > I was speaking to the loyalty of Pythonista's. Of course we are not > > really going to slay mats, come on Steve, get real! > > > > If all you want from a language is speed, go use C. I would avoid > > > assembly language though, since a modern optimizing C compiler will > > > often beat an assembly language programmer for execution speed, and the > > > programming time will definitely be shorter. But to make speed the > > > be-all and end-all is a witless approach. Speed is definitely not why > > > dynamic languages' popularity is increasing. Speed *is* still relevant > > > in certain areas, and completely irrelevant in others. > > > Come on Steve, i am NOT saying speed is the only thing that matters > > here! But it is very important. I never compared Python to C, that is > > madness. But it must be better, faster, smarter than it's direct > > competition(ruby)... you agree?? > > > > Much more of this kind of tripe and nobody will read what you write > > > anyway. You will hear the plonking of a hundred thousand newsreaders > > > every time you post. > > > Oh Steve... Listen, my words are ment as a wake-up-call to all who > > still love Python, and i believe you are one of them. Maybe old age > > has slowed your hand, that's OK, Us "youngsters" will take the helm. > > And be serious, do you really think this group is read by "hundreds-of- > > thousands of news readers? I wish it were, but I highly doubt it. > > Dude, calm down... There is no war here. > Please turn off your computer, go take a walk for awhile, experience > some real life in the outer world, and then think about this again. > Python is cool language, Ruby too. We are all happy and competition is > good. > Nobody will win this "war" and the loser won't be annihilated. I hope > there will be some healthy cross-pollination. > There is actually, for example python borrowed list-comprehensions > from haskell and I've never heard any haskell fan calling for jihad. > > Did you know that people are looking forward to use pypy to create a > fast ruby implementation? > Pypy is being developed by python developers and they will be happy to > see a ruby, perl, logo or whatever language implemented with pypy. We > are talking about tools, not religions. > Those who use them to create useful, real life applications know it. > > Soon, we will be able to use python libraries from ruby and the other > way around. the differences will be just a matter of taste, different > syntax to achieve the same tasks. > > Luis Your right, Python needs Ruby, and do you know why??? The same reason MS needs, Mac & Linux. So they do not fall asleep at the wheel! This keeps MS on there toes(although still no explanation for their piss- poor product). Python needs Ruby so we don't fall asleep. Ruby may be the best thing that happened to Python. Wake Up people! The writing is on the Wall! From wblusk1 at verizon.net Mon Dec 22 13:31:57 2008 From: wblusk1 at verizon.net (wblusk1 at verizon.net) Date: Mon, 22 Dec 2008 18:31:57 +0000 Subject: Python-list Digest, Vol 63, Issue 420 In-Reply-To: References: Message-ID: <1679064795-1229970717-cardhu_decombobulator_blackberry.rim.net-395278973-@bxe345.bisx.prod.on.blackberry> Sent from my Verizon Wireless BlackBerry -----Original Message----- From: python-list-request at python.org Date: Mon, 22 Dec 2008 19:01:06 To: Subject: Python-list Digest, Vol 63, Issue 420 Send Python-list mailing list submissions to python-list at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/python-list or, via email, send a message with subject or body 'help' to python-list-request at python.org You can reach the person managing the list at python-list-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Python-list digest..." From tino at wildenhain.de Mon Dec 29 14:45:31 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 29 Dec 2008 20:45:31 +0100 Subject: math module for Decimals In-Reply-To: References: <251111d8-a48a-45e3-a744-16fdb729fa33@i20g2000prf.googlegroups.com> <016729e4$0$6988$c3e8da3@news.astraweb.com> Message-ID: <495928DB.7040209@wildenhain.de> jerry.carl.mi at gmail.com wrote: ... > It's really just the goniometric functions that I am missing most at > the moment, so maybe I can figure it out with help of what you said > plus the already existing imperfect modules. Meantime maybe this > discussion will caught Guido's eye... ;-) And btw I do expect that > Python becomes better than Mathematica one day because it's free and > open :-) Maybe when Wolfram retires ;-) Thanks again! I agree having full support for all math.* functions for all builtin types would be nice. However if you are more looking for replacement of mathematica and friends with python you might check scipy/numpy. Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From rt8396 at gmail.com Fri Dec 26 14:07:55 2008 From: rt8396 at gmail.com (r) Date: Fri, 26 Dec 2008 11:07:55 -0800 (PST) Subject: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> <90f06b27-39da-4f1a-a878-f3972e942d57@s24g2000vbp.googlegroups.com> <62caf93b-0455-4450-9895-8a9d9554f75e@r32g2000vba.googlegroups.com> <1isezkk.51e05y1457jqrN%pdorange@pas-de-pub-merci.mac.com> <3cb2a746-1a43-44a1-9825-7667af9fe2fa@s1g2000prg.googlegroups.com> <1isi4sn.11mpft612g7udcN%pdorange@pas-de-pub-merci.mac.com> <1isk1kn.1s8efppxapfeaN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <301a2968-21d6-475d-958c-890e0fc27249@m15g2000vbl.googlegroups.com> On Dec 26, 5:06?am, pdora... at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) wrote: > r wrote: > > > Go to Google groups... it looks perfect :) > > It's a usenet group here, nothing to do with google groups. > To get back to the group subject, what is your actual python projects ? I am crusading to bring python scripting to Google SketchUp, do want to get on board? From clp at rebertia.com Mon Dec 1 13:37:57 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 1 Dec 2008 10:37:57 -0800 Subject: Python introspection and namespace weird question In-Reply-To: References: Message-ID: <47c890dc0812011037u64076950o186af7477269cc0a@mail.gmail.com> On Mon, Dec 1, 2008 at 6:04 AM, Rayene Ben Rayana wrote: > Hello everybody, > > Is there an easy way to do something like this in python ? > >>>> red_car = MyVehicleClass() >>>> car = red_car >>>> car.labels() > ['red_car' , 'car' ] > > In other words, does an instance has access to its name pointers ? In short, No. (Cue another debate over whether Python uses call-by-X semantics...) Typically people who want to do such things actually want/should use a dictionary mapping string keys to instance values instead. Note that in certain limited cases, voodoo involving the locals() or globals() built-in functions or the `inspect` module can work, but not in the common general case. But generally these techniques are considered bad style and kludgey unless you're writing a debugger or something equally meta, with using a dictionary as explained previously being much preferred. For example, for your particular code above, the following happens to work: [name for name, obj in locals().iteritems() if obj is car] #==> ['red_car' , 'car' ] But this will only give the names in the current function of the particular car object. Likewise, globals() works only for module-level names, and the `inspect` module's magic only works for names in calling functions (i.e. those below the current one in the callstack). Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks in advance, > > Rayene > > > -- > http://mail.python.org/mailman/listinfo/python-list > > From prologic at shortcircuit.net.au Tue Dec 30 19:54:45 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 10:54:45 +1000 Subject: get method In-Reply-To: <016ab880$0$6988$c3e8da3@news.astraweb.com> References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> <495AAB97.5010707@mrabarnett.plus.com> <71508d7a-f678-40ba-801c-0bbfbbab961e@r15g2000prh.googlegroups.com> <016ab880$0$6988$c3e8da3@news.astraweb.com> Message-ID: On Wed, Dec 31, 2008 at 10:49 AM, Steven D'Aprano wrote: > What set module? Sorry I must have meant the collections module :) > Adding a multi-set or bag class to the collections module would be a good > idea though. Perhaps you should put in a feature request? :) Perhaps I will. cheers James From stdazi at gmail.com Sat Dec 13 07:00:26 2008 From: stdazi at gmail.com (stdazi) Date: Sat, 13 Dec 2008 04:00:26 -0800 (PST) Subject: Parallelizing python code - design/implementation questions Message-ID: Hello! I'm about to parallelize some algorithm that turned out to be too slow. Before I start doing it, I'd like to hear some suggestions/hints from you. The algorithm essentially works like this: There is a iterator function "foo" yielding a special kind permutation of [1,....n]. The main program then iterates through this permutations calculating some proprieties. Each time a calculation ends, a counter is incremented and each time the counter is divisible by 100, the current progress is printed. The classical idea is to spawn m threads and use some global lock when calling the instance of the iterator + one global lock for incrementing the progress counter. Is there any better way? I'm especially concerned with performance degradation due to locking - is there any way to somehow avoid it? I've also read about the `multiprocessing' module and as far as I've understood : ==== permutation = foo() threadlst = [] for i in xrange(m) : p = Process(target=permutation.next) threadlst.append(p) p.start() for p in threadlst: p.join() ==== should do the trick. Am I right? Is there any better way other than this? From martin at v.loewis.de Tue Dec 2 02:05:06 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Tue, 02 Dec 2008 08:05:06 +0100 Subject: Multiple Versions of Python on Windows XP In-Reply-To: References: Message-ID: <4934de22$0$27863$9b622d9e@news.freenet.de> > Could anyone please point me to documentation on the way the msi > installer handles multiple versions eg. Python 2.5, 2.6 and 3.0? I don't think that is documented anywhere. > What changes are made to the registry? For a complete list, see Tools/msi/msi.py in the source tree. > Is there some way to specify a default version in such a way that it can > be changed as necessary? What do you mean by "default version"? There is the version that is associated with the .py/.pyc extensions at any point in time; you can change these by re-running the respective installers from add-and-remove-programs. In a well-managed installation, only one Python installation would have the "Register Extensions" feature selected; to then change the default, one would unselect the feature in one version, and reselect it in a different. If only the default installation procedure was ever used, re-running the installer in "Repair" mode (from ARP) will also restore the extension associations. > PyScripter uses an option to select a version eg. > > C:\Program Files\PyScripter\PyScripter.exe --python26 > > but I'm having some trouble with it when I attempt edit a python file > from the Windows Explorer. It would be good to be more specific with such statements: what troubles specifically? If I play dumb, I'd say "of course - windows explorer doesn't support editing Python files; you need a text editor". Regards, Martin From castironpi at gmail.com Sun Dec 21 05:35:59 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 21 Dec 2008 02:35:59 -0800 (PST) Subject: trapping all method calls in a class... References: <19ac19520812202312q71409182kb58a0f7aaf3b0e74@mail.gmail.com> Message-ID: <9ae69de7-a56f-44fc-8916-97ae6de32155@u18g2000pro.googlegroups.com> On Dec 21, 1:32?am, "Chris Rebert" wrote: > On Sat, Dec 20, 2008 at 11:12 PM, Piyush Anonymous > > wrote: > > hi, > > i need to trap all method calls in a class in order to update a counter > > which is increased whenever a method is called and decreased whenever method > > returns. in order to that i am trying to write a decorator for all the > > methods. > > > see the code here with error. > > ------- > >http://codepad.org/2w7JVvDB > > ---- > > any suggestions? any other better way of doing it? > > I call unnecessary use of metaclasses! Here's my (untested) attempt at > a simpler class decorator approach: > > def decorate_meths(klass): > ? ? attrs = klass.__dict__.items() > ? ? ? ? for name, val in attrs: > ? ? ? ? ? ? ? ? if callable(val): > ? ? ? ? ? ? ? ? ? ? ? ? klass.__dict__[name] = decorate(val) > > def decorate(method): > ? ? #should be called for every method call in the class > ? ? def decorated(self, *args, **kwds): > ? ? ? ? print "2 Inside __call__()" > ? ? ? ? returnval = method(self, *args,**kwds) > ? ? ? ? print "3 After self.f(*args)" > ? ? ? ? return returnval > ? ? return decorated > > #@decorate_meths <-- this syntax requires a later Python version > class Person(object): > ? ? ? ? def testprint(self,val): > ? ? ? ? ? ? ? ? print "blah blah" > Person = decorate_meths(Person) > > #rest of code after the class definition would be the same > > Sidenotes about your code: > - `args` and `kwds` are the conventional names for the * and ** > special arguments > - the `methodname` variable was actually getting method objects, not > strings, as its values; this was probably part of the bug in your > program > > Cheers, > Chris > > -- > Follow the path of the Iguana...http://rebertia.com Two more possibilities. 1. Use sys.settrace, and a dictionary mapping functions to integers. The functions are given in the frame object, which is a parameter to the settrace function. 2. __getattribute__, which either maps a function to an integer, and returns the function; or returns a function that increments an integer, then calls the requested function. P.S. I did not see the original post in Google Groups. From theller at python.net Thu Dec 4 15:33:43 2008 From: theller at python.net (Thomas Heller) Date: Thu, 04 Dec 2008 21:33:43 +0100 Subject: Checking if an int fits in 32 bits? In-Reply-To: References: Message-ID: <6pqt56F9bvoiU1@mid.individual.net> Roy Smith schrieb: > I'm working with marshaling data over a binary wire protocol. I'm > using struct.pack() to handle the low-level encoding of ints. One of > the things I need to do is make sure an int can be represented in 4 > bytes. Is there a portable way to do that? For now, I'm doing signed > ints, but I'll certainly have to do unsigned 32-bit ints (and 64-bit > ints) at some point. Not to mention shorts and chars. > > At first I thought pack() might raise an exception on a value > overflow, that but doesn't seem to be the case: > >>>> [hex(ord(c)) for c in struct.pack('!i', 999999999999999999999L)] > ['0xde', '0x9f', '0xff', '0xff'] > > Should I be thinking more along the lines of bit masking (and worrying > about all the niggling 2-complement issues) in the Python code? Or is > there some cleaner way to do this? > You could try something like this: import ctypes def int_fits_in_32bit(value): return ctypes.c_int32(value) == value and similar for signed/unsigned short/int/long. Packing and unpacking with the struct module, however, does basically the same. Thomas From jeremiah.dodds at gmail.com Thu Dec 25 04:42:31 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Thu, 25 Dec 2008 04:42:31 -0500 Subject: =?ISO-8859-1?Q?Re:_object_ori=EBnted?= In-Reply-To: References: Message-ID: <12cbbbfc0812250142k801b445v55628e935d932e5e@mail.gmail.com> On Wed, Dec 24, 2008 at 10:54 AM, Dennis van Oosterhout < de.slotenzwemmer at gmail.com> wrote: > I know that python is an Object Ori?nted language but I was wondering if it > gets used as a non-OOP also (by a good amount of people). > > -- > http://mail.python.org/mailman/listinfo/python-list > > I, for one, use the different "paradigms" (OO, procedural, functional, etc) where they feel appropriate for solving different problems. I have quite a few strictly procedural scripts, mainly for sysadmin stuff and generating project skeletons. Most of the "complete" programs that I write use a mix of OO and functional paradigms. -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Sun Dec 21 18:37:04 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 21 Dec 2008 15:37:04 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: On Dec 21, 10:58?am, MRAB wrote: > Aaron Brady wrote: > > On Dec 21, 10:31 am, MRAB wrote: snip > >> The original format is a string. The result of '%' is a string if > >> there's only 1 placeholder to fill, or a (partial) format object (class > >> "Format"?) if there's more than one. Similarly, the format object > >> supports '%'. The result of '%' is a string if there's only 1 > >> placeholder to fill, or a new (partial) format object if there's more > >> than one. > > >> ?>>> f = "%r %i" > >> ?>>> type(f) > >> > >> ?>>> f = f % (2, 3, 4) > >> ?>>> type(f) > >> > >> ?>>> f = f % 1 > >> ?>>> type(f) > >> > > > Alright, so how are you handling: > > >>>> f= "%s %i" > >>>> type( f ) > > > >>>> f= f% '%i' ?#now '%i %i' > >>>> type( f ) > > > >>>> f= f% 1 > >>>> type( f ) > > ? > > > In other words, are you slipping '1' in to the very first available > > slot, or the next, after the location of the prior? > > Let's assume that Format objects display their value like the equivalent > string format: > > ?>>> f = "%r %i" > ?>>> f > '%r %i' > ?>>> f = f % (2, 3, 4) > ?>>> f > > ?>>> f = f % 1 > ?>>> f > '(2, 3, 4) 1' > ?>>> > ?>>> f = "%s %i" > ?>>> f > '%s %i' > ?>>> f = f % '%i' > ?>>> f > > ?>>> f = f % 1 > ?>>> f > '%%i 1' I assume you meant '%i 1' since there are no more flags in f, and it's returned to a regular string. 'f %= 1' doesn't work any more as in-place modulo, since one time, 'f' is a Format object, the other, 'f' is a string. Just raise an exception for that (or assign to __class__ IINM if I'm not mistaken). Actually, the class you showed is kind of nifty. Tuples are correctly interpolated. I think on the whole you'll use more parenthesis, since each term in the tuple appears separately, and might be an expression (have a lower-precedence op.), as well as more modulo signs. You can currently do-it-yourself, you just need a constructor in the format string. >>> f = Format("%r %i") >>> type(f) >>> f = f % (2, 3, 4) >>> type(f) Or, as someone suggested earlier, a new literal marking: >>> f = f"%r %i" >>> type(f) From gagsl-py2 at yahoo.com.ar Mon Dec 8 02:49:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Dec 2008 05:49:07 -0200 Subject: i use the urllib question In-Reply-To: References: Message-ID: En Fri, 05 Dec 2008 10:23:44 -0200, Huytason escribi?: > i use pthon 3.0 today > > python code: > import urllib.request > > then use PyRun_StringFlag to run it. > > get this > > it's a bug? You should tell us more details. You are embedding Python, I presume? The default search path (sys.path) is initialized based on the executable location; very probably you don't have a 'lib' directory. Either set the PYTHONPATH environment var, or copy the required libraries, or call Py_SetProgramName. -- Gabriel Genellina From cadmuxe at gmail.com Mon Dec 8 09:59:53 2008 From: cadmuxe at gmail.com (cadmuxe) Date: Mon, 8 Dec 2008 06:59:53 -0800 (PST) Subject: Beginner trying to understand functions. References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> Message-ID: <9df7549a-f28b-4d39-b105-90c099f472f2@z28g2000prd.googlegroups.com> On 12?8?, ??10?53?, "James Mills" wrote: > On Tue, Dec 9, 2008 at 12:46 AM, Peter Otten <__pete... at web.de> wrote: > > I think the OP is using Python 3.0. What used to cause trouble > > Well of course he/she/it is! > I'm too blind to have noticed that! :) > > --JamesMills > > -- > -- > -- "Problems are solved by method" oh,i think i should go to read the new document of py3k thanks for all From metolone+gmane at gmail.com Fri Dec 5 09:44:35 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Fri, 5 Dec 2008 06:44:35 -0800 Subject: A more pythonic way of writting References: <35d176ed-df5f-46b4-8321-4814fcc4398c@f3g2000yqf.googlegroups.com> Message-ID: "eric" wrote in message news:35d176ed-df5f-46b4-8321-4814fcc4398c at f3g2000yqf.googlegroups.com... > def flag(IGNORECASE=False, LOCALE=False, MULTILINE=False, > DOTALL=False, UNICODE=False, VERBOSE=False): > vals = [IGNORECASE, LOCALE, MULTILINE, DOTALL, UNICODE, VERBOSE] > filtered = map( lambda m:m[1],filter( lambda m: m[0], > zip(vals,'iLmsux'))) > return '?'+''.join( filtered ) filtered = [c for c,v in zip('iLmsux',vals) if v] -Mark From rocky at panix.com Tue Dec 30 05:09:35 2008 From: rocky at panix.com (R. Bernstein) Date: Tue, 30 Dec 2008 05:09:35 -0500 Subject: How do I DRY the following code? References: Message-ID: "Patrick Mullen" writes: >> f1(...): >> "Docstring f1" >> c = C() >> return c.f1(...) >> >> f2(...): >> "Docstring f2" >> c = C() >> return c.f2(...) > > Why not just do either this: > C().f2(..) where you need f2 Yes, this is a little better. Thanks! From python.list at tim.thechases.com Mon Dec 8 06:12:02 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 08 Dec 2008 05:12:02 -0600 Subject: Determining whether a variable is less/greater than a range. In-Reply-To: <362ab93b-b804-4ebe-a22f-e422feb301c8@c1g2000yqg.googlegroups.com> References: <362ab93b-b804-4ebe-a22f-e422feb301c8@c1g2000yqg.googlegroups.com> Message-ID: <493D0102.6030808@tim.thechases.com> > a = list(range(10, 21)) > > b = 9 > > c = 21 > > How can I find out if b and c have values less or more than the values > in list a? Sounds like a good use for 2.5's addition of the any() and all() functions -- you don't mention whether you want your variable compared against *any* of the list items or *all* of the list items. You also don't mention whether you want the comparison results, or just a single scalar. Lastly, you omit the details of what happens if your target value ("d" below) falls within the range. One of the following should do it for you: >>> a = range(10,21) >>> b = 9 >>> c = 21 >>> d = 15 >>> any(b < x for x in a) True >>> all(b < x for x in a) True >>> any(c < x for x in a) False >>> any(d < x for x in a) True >>> all(d < x for x in a) False >>> any(c > x for x in a) True >>> all(c > x for x in a) True >>> any(d > x for x in a) True >>> all(d > x for x in a) False If you just want the comparisons: y1 = [bx) for x in a] z2 = [(cx) for x in a] z3 = [(dx) for x in a] -tkc From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 2 08:08:05 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 02 Dec 2008 14:08:05 +0100 Subject: Do more imported objects affect performance In-Reply-To: References: <1be78d220812010621u51dead9dnbaa0b4c8c9414362@mail.gmail.com> <79153a2e0812012124o7401df57m4ac21dfe37c2ec5@mail.gmail.com> Message-ID: <4935332e$0$1138$426a74cc@news.free.fr> Nick Craig-Wood a ?crit : > On Tue, Dec 02, 2008 at 11:24:29AM +0600, Taskinoor Hasan wrote: >> On Mon, Dec 1, 2008 at 8:21 PM, Filip Gruszczy?ski wrote: >> >>> I see. Thanks for a really good explanation, I like to know, how to do >>> things in the proper way :) >> I always prefer to use import module and then use module.function. The >> reason is simple. It makes the code more readable and maintainable. > > I prefer the "from module import function". That means that if > "module" doesn't supply "function" it raises an exception at compile > time, not run time when you try to run "module.function". Nope. import is an executable statement, and ImportError happens at runtime too. From martin.hellwig at dcuktec.org Sat Dec 6 07:53:35 2008 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Sat, 06 Dec 2008 12:53:35 +0000 Subject: Can't get exclusive file lock when safely renaming a file In-Reply-To: <014a049b$0$20670$c3e8da3@news.astraweb.com> References: <014a049b$0$20670$c3e8da3@news.astraweb.com> Message-ID: <493a75cf$0$185$e4fe514c@news.xs4all.nl> Steven D'Aprano wrote: > import os, fcntl > oldname = "ham.txt" > newname = "spam.txt" > > def lock_destination(name): > fileno = os.open(name, os.O_CREAT | os.O_EXCL) > fcntl.flock(fileno, fcntl.LOCK_EX) # POSIX systems only > return fileno > > # Create a test file to be renamed. > f = open(oldname, 'w') > f.write('this is my file\n') > f.close() > fileno = lock_destination(newname) > > # At this point, I can see "ham.txt" plus an empty file > # "spam.txt" in my file browser > > os.rename(oldname, newname) > > The rename works, but here is my problem: after getting what I thought > was an exclusive lock on the new file, but before calling os.rename(), I > can still over-write it from another process: > > $ echo "this comes from another process" > spam.txt > $ cat spam.txt > this comes from another process > This is weird, you would indeed expect it to be locked, I tried it on FreeBSD and it behaves the same. I guess the behavior of os.rename should be changed so it raises an exception when the source destination exists independent on the below platform. I tried searching for another way to do it but the closest I came was to popen mv and raise an exception if it asks to overwrite the existing file. Sorry I can't be of more help. -- mph From manatlan at gmail.com Mon Dec 8 08:15:55 2008 From: manatlan at gmail.com (manatlan) Date: Mon, 8 Dec 2008 05:15:55 -0800 (PST) Subject: pytz and timezone specialists References: <1f6172c1-4f70-42ea-8010-b72beb0af487@w24g2000prd.googlegroups.com> Message-ID: On 5 d?c, 20:46, Ned Deily wrote: > In article > <1f6172c1-4f70-42ea-8010-b72beb0af... at w24g2000prd.googlegroups.com>, > > > > ?manatlan wrote: > > Here is a really simple code : > > ------------------------------------------------------- > > from datetime import datetime > > frompytzimport timezone > > > tz=timezone("Europe/Paris") > > > d=datetime(2008,12,12,19,00,00,tzinfo=tz) > > print d.isoformat() > > > d=datetime.now(tz) > > print d.isoformat() > > ------------------------------------------------------- > > when I run it, it displays (according current time ;-): > > > 2008-12-12T19:00:00+00:09 > > 2008-12-05T19:15:38.135467+01:00 > > > The Europe/Paris timezone is GMT+1 ... the second date seems to be > > right (+01:00 at the end) > > > But why the first date ends with "+00:09" ?!? it should be +01:00 ... > > no ?! > > Where's the bug ?!? (sure : it's me ;-) ... but i don't understand > > this simple thing) > >>> tz = timezone("Europe/Paris") > >>> d = tz.localize(datetime(2008,12,12,19,00,00)) > >>> print d.isoformat() > > 2008-12-12T19:00:00+01:00 > > > > "This library only supports two ways of building a localized time. The > first is to use the .localize() method provided by thepytzlibrary. > This is used to localize a naive datetime (datetime with no timezone > information). ?... Unfortunately using the tzinfo argument of the > standard datetime constructors ''does not work'' withpytzfor many > timezones." > > -- > ?Ned Deily, > ?n... at acm.org now, I use : d=datetime.now(tz).replace(2008,12,12,19,00,00) and it works like expected ... btw, thanks for your answer From greg at cosc.canterbury.ac.nz Sun Dec 14 03:03:26 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Sun, 14 Dec 2008 21:03:26 +1300 Subject: Bidrectional Subprocess Communication In-Reply-To: References: Message-ID: <6qjspkFcv81kU1@mid.individual.net> Gabriel Genellina wrote: > (Pipes don't work the same as sockets, although unix-like systems try > hard to hide the differences...) BSD-based unixes implement pipes using socketpair(), so pipes actually *are* sockets (or at least they used to be, not sure whether it's still true). -- Greg From iofferkicks24 at gmail.com Wed Dec 24 21:25:03 2008 From: iofferkicks24 at gmail.com (www.iofferkicks.com) Date: Wed, 24 Dec 2008 18:25:03 -0800 (PST) Subject: www.iofferkicks.com china cheap wholesale nike shoes,air jordan shoes,air force one shoes. Message-ID: <33a3a127-a22b-41a7-8193-a23698d34c7f@w1g2000prk.googlegroups.com> Get Nike Shoes at Super Cheap Prices Discount Nike air jordans (www.iofferkicks.com) Discount Nike Air Max 90 Sneakers (www.iofferkicks.com) Discount Nike Air Max 91 Supplier (www.iofferkicks.com) Discount Nike Air Max 95 Shoes Supplier (www.iofferkicks.com) Discount Nike Air Max 97 Trainers (www.iofferkicks.com) Discount Nike Air Max 2003 Wholesale (www.iofferkicks.com) Discount Nike Air Max 2004 Shoes Wholesale (www.iofferkicks.com) Discount Nike Air Max 2005 Shop (www.iofferkicks.com) Discount Nike Air Max 2006 Shoes Shop (www.iofferkicks.com) Discount Nike Air Max 360 Catalogs (www.iofferkicks.com) Discount Nike Air Max Ltd Shoes Catalogs (www.iofferkicks.com) Discount Nike Air Max Tn Men's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 2 Women's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 3 Customize (www.iofferkicks.com) Discount Nike Air Max Tn 4 Shoes Customize ( www.iofferkicks.com) Discount Nike Air Max Tn 6 Supply (www.iofferkicks.com) Discount Nike Shox NZ Shoes Supply (www.iofferkicks.com) Discount Nike Shox OZ Sale (www.iofferkicks.com) Discount Nike Shox TL Store (www.iofferkicks.com) Discount Nike Shox TL 2 Shoes Store (www.iofferkicks.com) Discount Nike Shox TL 3 Distributor (www.iofferkicks.com) Discount Nike Shox Bmw Shoes Distributor (www.iofferkicks.com) Discount Nike Shox Elite Shoes Manufacturer (www.iofferkicks.com) Discount Nike Shox Monster Manufacturer (www.iofferkicks.com) Discount Nike Shox R4 Running Shoes (www.iofferkicks.com) Discount Nike Shox R5 Mens Shoes (www.iofferkicks.com) Discount Nike Shox Ride Womens Shoes (www.iofferkicks.com) Discount Nike Shox Rival Shoes Wholesaler (www.iofferkicks.com) Discount Nike Shox Energia Wholesaler (www.iofferkicks.com) Discount Nike Shox LV Sneaker (www.iofferkicks.com) Discount Nike Shox Turbo Suppliers (www.iofferkicks.com) Discount Nike Shox Classic Shoes Suppliers (www.iofferkicks.com) Discount Nike Shox Dendara Trainer (www.iofferkicks.com) Discount Nike Air Jordan 1 Seller (www.iofferkicks.com) Discount Nike Air Jordan 2 Shoes Seller (www.iofferkicks.com) Discount Nike Air Jordan 3 Collection (www.iofferkicks.com) Discount Nike Air Jordan 4 Shoes Collection (www.iofferkicks.com) Discount Nike Air Jordan 5 Chaussure Shoes (www.iofferkicks.com) Discount Nike Air Jordan 6 Catalog (www.iofferkicks.com) Discount Nike Air Jordan 7 Shoes Catalog (www.iofferkicks.com) Discount Nike Air Jordan 8 Customized (www.iofferkicks.com) Discount Nike Air Jordan 9 Shoes Customized (www.iofferkicks.com) Discount Nike Air Jordan 10 Wholesalers (www.iofferkicks.com) Discount Nike Jordan 11 Shoes Wholesalers (www.iofferkicks.com) Discount Nike Air Jordan 12 Factory (www.iofferkicks.com) Discount Nike Air Jordan 13 Shoes Factory (www.iofferkicks.com) Discount Nike Air Jordan 14 Shoes Sell (www.iofferkicks.com) Discount Nike Air Jordan 16 Exporter (www.iofferkicks.com) Discount Nike Air Jordan 17 Shoes Exporter (www.iofferkicks.com) Discount Nike Air Jordan 18 Offer (www.iofferkicks.com) Discount Nike Air Jordan 19 Shoes Offer (www.iofferkicks.com) Discount Nike Air Jordan 20 Manufacture (www.iofferkicks.com) Discount Nike Jordan 21 Shoes Manufacture (www.iofferkicks.com) EMAIL:IOFFERKICKS at GMAIL.COM MSN :IOFFERKICKS at MSN.COM From rt8396 at gmail.com Mon Dec 22 12:40:29 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 09:40:29 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> Message-ID: On Dec 22, 8:58?am, walterbyrd wrote: > On Dec 21, 12:28?pm, Bruno Desthuilliers > > wrote: > > Strange enough, > > no one seems to complain about PHP or Ruby's performances... > > A few years back, there was a certain amount of chest thumping, when > python/django easily beat ror in a benchmark test. Now that ruby is > faster, I guess speed is no big issue. > > By the same reasoning, python advocates used to sneer at php because > php constantly broke backward compatibility. Now that python does it, > breaking backward compatibility is no big deal. I guess unicode > support was not that important, until python caught up to perl. > > I guess, the way it works is: you first assume that python is > superior, then you figure out why. I think what walter is saying is the loyalty is gone. community: """If python makes great, if it doesn't, why should "i" care if it goes down the toilet? i just move to ruby""" Were is your loyalty pyfans?, Has the fight left you??? From torriem at gmail.com Thu Dec 11 14:19:19 2008 From: torriem at gmail.com (Michael Torrie) Date: Thu, 11 Dec 2008 12:19:19 -0700 Subject: just got the g1 In-Reply-To: References: Message-ID: <494167B7.9090304@gmail.com> garywood wrote: > Hi > > Just got the G1, is their any way to get python running on the andriod platform ? Nope. But some day when other languages are supported, Python will be high on the list. In the meantime, Android is java only. And no you can't use Jython because Android statically compiles normal java byte code to the special bytecode their own VM uses. Jython being a dynamic language does not emit static java classes. From what I understand, porting Jython to work on this special VM is not trivial. From wojciech_mula at poczta.null.onet.pl.invalid Sat Dec 13 21:14:37 2008 From: wojciech_mula at poczta.null.onet.pl.invalid (Wojciech =?ISO-8859-2?Q?Mu=B3a?=) Date: Sun, 14 Dec 2008 03:14:37 +0100 Subject: 1 or 1/0 doesn't raise an exception References: Message-ID: <20081214031437.48078f5d.wojciech_mula@poczta.null.onet.pl.invalid> "Daniel Fetchinson" wrote: > Is it a feature that > > 1 or 1/0 > > returns 1 and doesn't raise a ZeroDivisionError? If so, what's the rationale? See: http://en.wikipedia.org/wiki/Short-circuit_evaluation From bj_666 at gmx.net Sat Dec 20 07:07:07 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 20 Dec 2008 12:07:07 GMT Subject: encoding problem References: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> <6r1m72Ffb5kpU3@mid.uni-berlin.de> <6r2hvjFfb5kpU6@mid.uni-berlin.de> <6r2nfgFfb5kpU7@mid.uni-berlin.de> Message-ID: <6r45fbFfc57aU2@mid.uni-berlin.de> On Fri, 19 Dec 2008 16:50:39 -0700, Joe Strout wrote: > Marc 'BlackJack' Rintsch wrote: > >>>> And does REALbasic really use byte strings plus an encoding!? >>> You betcha! Works like a dream. >> >> IMHO a strange design decision. > > I get that you don't grok it, but I think that's because you haven't > worked with it. RB added encoding data to its strings years ago, and > changed the default string encoding to UTF-8 at about the same time, and > life has been delightful since then. The only time you ever have to > think about it is when you're importing a string from some unknown > source (e.g. a socket), at which point you need to tell RB what encoding > it is. From that point on, you can pass that string around, extract > substrings, split it into words, concatenate it with other strings, > etc., and it all Just Works (tm). Except that you don't know for sure what the output encoding will be, as it depends on the operations on the strings in the program flow. So to be sure you have to en- or recode at output too. And then it is the same as in Python -- decode when bytes enter the program and encode when (unicode) strings leave the program. > In comparison, Python requires a lot more thought on the part of the > programmer to keep track of what's what (unless, as you point out, you > convert everything into unicode strings as soon as you get them, but > that can be a very expensive operation to do on, say, a 500MB UTF-8 text > file). So it doesn't require more thought. Unless you complicate it yourself, but that is language independent. I would not do operations on 500?MiB text in any language if there is any way to break that down into smaller chunks. Slurping in large files doesn't scale very well. On my Eee-PC even a 500?MiB byte `str` is (too) expensive. > But saying that having only one string type that knows it's Unicode, and > another string type that hasn't the foggiest clue how to interpret its > data as text, is somehow easier than every string knowing what it is and > doing the right thing -- well, that's just silly. Sorry, I meant the implementation not the POV of the programmer, which seems to be quite the same. Ciao, Marc 'BlackJack' Rintsch From bdesth.quelquechose at free.quelquepart.fr Thu Dec 4 13:44:07 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 Dec 2008 19:44:07 +0100 Subject: Python Runtime Method Call Binding In-Reply-To: <9f2308eb-9eb9-4431-8af7-975c3e054849@e18g2000yqo.googlegroups.com> References: <0147f396$0$20670$c3e8da3@news.astraweb.com> <9f2308eb-9eb9-4431-8af7-975c3e054849@e18g2000yqo.googlegroups.com> Message-ID: <493832b1$0$17775$426a34cc@news.free.fr> k3xji a ?crit : (snip) > My problem is that I have a very-multithreaded application that I want > to profile dynamically. And I want to see how many functions are > called/how much time spent on them.(I tried Profilers but lack of > multithreading support I cannot do what I want to do.) ??? I didn't found any mention of such a limitation on the profile / cProfile doc: http://www.python.org/doc/2.6/library/profile.html#module-cProfile > So, from your answers above, if I use a decorator I will not be able > to understand that the function has finished processing. Yes you will: def log(func): def _logged(*args, **kw): print "func", func.__name__, " called with ", args, kw result = func(*args, **kw) print "func", func.__name__, " returned ", result return result _logged.__name__ = "logged_%s" % func.__name__ _logged.__doc__ = func.__doc__ return _logged > I think problem is clarified now. Maybe you have other suggestions? Yes. 1/ the @decorator def func(): pass syntax is really syntactic sugar for def func(): pass func = decorator(func) 2/ nothing prevents you from dynamically rebinding methods at runtime: def log(func): # cf below if getattr(func, "_decorated", False): # already decorated, just return the func or method as is return func def _logged(*args, **kw): print "func", func.__name__, " called with ", args, kw result = func(*args, **kw) print "func", func.__name__, " returned ", result return result _logged.__name__ = "logged_%s" % func.__name__ _logged.__doc__ = func.__doc__ # IMPORTANT : mark the function / method as already decorated _logged._decorated = True return _logged class Foo(object): def bar(self): pass Foo.bar = log(Foo.bar) 3/ Now fact is that even all this won't probably be enough to implement a robust generic profiler - something which obviously requires a deep understanding of the language *and* it's implementation. From bkamrani at gmail.com Thu Dec 4 07:48:10 2008 From: bkamrani at gmail.com (bkamrani at gmail.com) Date: Thu, 4 Dec 2008 04:48:10 -0800 (PST) Subject: performance question: dictionary or list, float or string? References: <434bf4e3-54f4-4e15-b8b0-510a988f25b8@z1g2000yqn.googlegroups.com> <904a19e9-3800-4d61-aea0-4bdabc0674fa@j32g2000yqn.googlegroups.com> <842b13b2-1df5-4b34-af14-7b082970682b@41g2000yqf.googlegroups.com> <796f927e-5def-4637-bb31-88965b9bcb44@z28g2000prd.googlegroups.com> Message-ID: On Dec 4, 1:28?pm, alex23 wrote: > On Dec 4, 8:12?pm, bkamr... at gmail.com wrote: > > > About the piece of code you posted, there is something I don't > > understand. > > > ? ? ? ? for i, line in data: > > > where data is a file object. Is it legal to write that? > > I believe it results in "too many values to unpack" or do I miss > > something? > > From the context, my guess is Matimus intended to write: > > ? ? ? ? ?for i, line in enumerate(data): You're right! That was interesting! From zxo102 at gmail.com Thu Dec 25 18:32:22 2008 From: zxo102 at gmail.com (zxo102) Date: Thu, 25 Dec 2008 15:32:22 -0800 (PST) Subject: How to display Chinese in a list retrieved from database via python References: <22be506d-91c2-4727-ace7-2e3382b6d214@g3g2000pre.googlegroups.com> Message-ID: <979fdf6d-0500-47ba-87fd-0f0361ca3059@p2g2000prf.googlegroups.com> On 12?26?, ??4?58?, "Gabriel Genellina" wrote: > En Thu, 25 Dec 2008 07:27:03 -0200, zxo102 escribi?: > > > > > On 12?25?, ??3?35?, "Chris Rebert" wrote: > >> On Wed, Dec 24, 2008 at 11:29 PM, zxo102 wrote: > >> > Hi, > >> > I retrieve some info in Chinese from postgresql and assign it to a > >> > variable 'info' defined in javascript of a html page: > >> > var info = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce > >> > \xc4'] > >> > But I want it to be > >> > var info = ['??','??','??'] > >> > since in html pages (via javascript), the items in chinese out of the > >> > former :['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4'] can > >> > not be displayed correctly when it is inserted into a html page. If > >> > the list is var info = ['??','??','??'] , then everything works > >> > fine. > > > The html code is as follows > > > test > > > > > > > But the '??' is '\xd6\xd0\xce\xc4'. When row01 and row02 is called > > from somewhere, > > '\xd6\xd0\xce\xc4' can not be displayed correctly as '??' in html > > environment. > > You forgot to specify the page encoding, gb2312 presumably. If adding the > encoding does not help, I'd say the problem must reside on how you later > use row01 and row02 (your html page does not those variables for > anything). '??' is the same as '\xd6\xd0\xce\xc4', and both javascript > and Python share the same representation for strings (mostly) so this > should not be an issue. > > My PC is unable to display those characters, but I get "true" from this: > > test > > > -- > Gabriel Genellina I did that: , but it does not work. Alert('\xd6\xd0\xce\xc4') displays some "junks". I am thinking there may be some way to convert '\xd6\xd0\xce\xc4' to '??' in the list with python before I generate the html page. As a result, when I open the html file with Vi, I can see '??' directly instead of '\xd6\xd0\xce\xc4'. That will solve my problem. Any ideas? Ouyang From af300wsm at gmail.com Mon Dec 8 11:53:55 2008 From: af300wsm at gmail.com (Andrew Falanga) Date: Mon, 8 Dec 2008 08:53:55 -0800 (PST) Subject: Calling C# COM (.NET) from python Message-ID: Hi, I've never programmed in python and only have a small understanding of what is wrapped up in the terms COM and .NET. Is there a way of using python to get a hold of objects written in C# as COM objects using python? I'm looking for ways to avoid VBScript (which, after a couple of weeks, I've determined to be horrid). That is, is there a way of getting at COM objects in python that's similar to doing a CreateObject call in VBScript (http://msdn.microsoft.com/en-us/library/ dcw63t7z.aspx)? Thanks, Andy From steve at holdenweb.com Fri Dec 26 16:13:11 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 26 Dec 2008 16:13:11 -0500 Subject: [SQL] Right way to set a variable to NULL? In-Reply-To: <5nfal41gom0iqi2nh5h0m5847ev9brtvpf@4ax.com> References: <5nfal41gom0iqi2nh5h0m5847ev9brtvpf@4ax.com> Message-ID: Gilles Ganault wrote: > Hello > > I use regexes to extract information from a text file. Some of the > records don't have e-mails or www addresses, so those must match Null > in SQL, but None doesn't work as expected: > > ======= > if itemmatch: > web = itemmatch.group(1).strip() > else: > web = None > > sql = 'INSERT INTO mytable (name,address,web,mail) VALUES > ("%s","%s","%s","%s","%s")' % (name,address,web,mail) > ======= > I take it this code isn't pasted from an actual program, since the statement above would give a run time ValueError. > Is there a better way in Python to have a variable match NULL than > building the SQL query step by step? > You could, of course, have replaced None in your code with "NULL", and that should have removed the database errors you were observing. Retaining the None, however, you could move to using parameterized queries. Replace each '"%s"' in your sql string with the appropriate parameter mark (could be '%s', could be '?', could be three other things depending on your database platform. Then you provide a tuple of data items (using None for the NULL values) as a second argument to the cursor's .execute() method, and the database driver module inserts the data in to the SQL statement, escaping things where appropriate. So, supposing you were using MySQL or PostgreSQL you would write if itemmatch: web = itemmatch.group(1).strip() else: web = None sql = '''INSERT INTO mytable (name,address,web,mail) VALUES (%s, %s, %s, %s)''' cursor.execute(sql, (name,address,web,mail)) Don't forget to call the connection's .commit() method to ensure the database changes are made permanent. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From upton at virginia.edu Mon Dec 15 11:28:03 2008 From: upton at virginia.edu (Dan Upton) Date: Mon, 15 Dec 2008 11:28:03 -0500 Subject: stable algorithm with complexity O(n) In-Reply-To: <52cfb77e-4baf-4fba-8eac-cc6c7ddb5be5@k1g2000prb.googlegroups.com> References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> <015612ac$0$20639$c3e8da3@news.astraweb.com> <52cfb77e-4baf-4fba-8eac-cc6c7ddb5be5@k1g2000prb.googlegroups.com> Message-ID: <5504f9ac0812150828m14f6999ak6112c5975042dc88@mail.gmail.com> On Mon, Dec 15, 2008 at 11:05 AM, wrote: >> Non-comparison sorts are a useful technique, but it's changing the >> problem, and they are only useful in very limited circumstances. There's >> a good reason that most sort routines are based on O(n*log n) comparison >> sorts instead of O(n) bucket sorts or radix sorts. >> > This is an assumption that I never quite understood. What most people > want is to have sorted data, they don't care if I used a sorting or > non-sorting comparison to do it. I think it is just that in most cases > n is not very big anyway and comparison sorts make it easier on the > programmer to create arbitrary types that are sortable. And if n is small and sparse (ie, k > n) , O(k*n) for radix sort could be worse than O(n^2). You could also ask why people make such a big deal about quicksort over mergesort, since mergesort has a guaranteed O(n log n) time whereas quicksort can be O(n^2) on pathological cases. I think I remember learning in my algorithms class that for small sorts (n < ~40) , bubblesort can actually be the fastest (or close to the fastest) in terms of wall-clock time because it has a relatively small constant factor in its O(n^2) complexity. From miki.tebeka at gmail.com Tue Dec 9 11:39:38 2008 From: miki.tebeka at gmail.com (Miki) Date: Tue, 9 Dec 2008 08:39:38 -0800 (PST) Subject: pickling a circular object inherited from list References: Message-ID: <3b1bab42-657c-4b93-9236-aa5236c16826@w1g2000prk.googlegroups.com> Hello Klaus, > I have a problem with inheritance from list. I want to create a tree > like object where child nodes are kept in self[:] and every child has a > field that points to its parent. Pickling such an object, however, > throws an AssertionError. See below for source code and output of an > easy example case of my problem. > > What did I do wrong? Old Python version? :) Seems to work in 3.0 (don't have 2.6 currently to check but IMO it's fixed there as well). HTH, -- Miki http://pythonwise.blogspot.com From dfnsonfsduifb at gmx.de Tue Dec 16 23:50:50 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Wed, 17 Dec 2008 05:50:50 +0100 Subject: Does Python3 offer a FrozenDict? In-Reply-To: <01584ccb$0$20656$c3e8da3@news.astraweb.com> References: <01584ccb$0$20656$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano schrieb: > On Tue, 16 Dec 2008 17:59:30 +0100, Johannes Bauer wrote: > >> Hello group, >> >> is there anything like a frozen dict in Python3, so I could do a >> >> foo = { FrozenDict({"a" : "b"}): 3 } >> >> or something like that? > > > If *all* you want is to use it as a key, then: > > tuple(sorted(some_dict.items)) > > may do the job. Well, I'd like to access it like a dict afterwards, e.g. for (i, j) in foo.items(): print(i["a"]) Regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From ajaksu at gmail.com Mon Dec 22 17:30:56 2008 From: ajaksu at gmail.com (ajaksu) Date: Mon, 22 Dec 2008 14:30:56 -0800 (PST) Subject: I always wonder ... References: Message-ID: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> On Dec 22, 3:53?pm, s... at pobox.com wrote: > ... shouldn't people who spend all their time trolling be doing something > else: studying, working, writing patches which solve the problems they > perceive to exist in the troll subject? ? Sure. So should I. Hmm. Shutting-up-and-back-to-work-ly y'rs, Daniel From rogerpack2005 at gmail.com Sat Dec 27 00:49:38 2008 From: rogerpack2005 at gmail.com (rogerdpack) Date: Fri, 26 Dec 2008 21:49:38 -0800 (PST) Subject: ruby -> python translator exists? References: <04b51f42-e18e-4902-8a98-38f0538c1eda@s9g2000prg.googlegroups.com> <4a10794e-a3e7-4aa4-8d21-580152806277@c36g2000prc.googlegroups.com> <72c2df21-db59-4870-9388-ccaa47cf11e4@20g2000yqt.googlegroups.com> Message-ID: <9c579c5a-ac9f-4716-8300-6d41ed52fd72@a26g2000prf.googlegroups.com> > Search for the tool "Unholy". -- Al Thank you for your replies. -=r From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 21:30:26 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2008 02:30:26 GMT Subject: ANN: New Book: Programming in Python 3 References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> Message-ID: <015c5013$0$20656$c3e8da3@news.astraweb.com> On Fri, 19 Dec 2008 19:35:20 -0500, Colin J. Williams wrote: > Steve Holden wrote: >> Thomas Heller wrote: (Fixing broken unicode again) >>> "One of Python's great strengths" >>> ^ >>> "and also teaches Python's functional programming features" >>> ^ >>> "The book's approach is wholly practical" >>> ^ >> It always has been valid English. The apostrophe is only omitted from >> personal pronouns (hers, its, and so on). >> >> regards >> Steve > > What is the subject of "teaches"? The example given is obviously a sentence fragment. The subject will be in the part of the sentence left out, and from context it is almost certainly going to be the book being discussed, or possibly the author of the book. -- Steven From joelh at planetjoel.com Wed Dec 3 00:32:27 2008 From: joelh at planetjoel.com (Joel Heenan) Date: Wed, 3 Dec 2008 16:32:27 +1100 Subject: Query netgroup information through python In-Reply-To: <843700460811051534l71704b71pd85cc023d0c4e395@mail.gmail.com> References: <843700460811051534l71704b71pd85cc023d0c4e395@mail.gmail.com> Message-ID: <4f89225b0812022132h564f261bob1a10b84129f364a@mail.gmail.com> Well it doesn't appear that this exists in the standard library or in any other library, so I ended up writing my own C interface to the underlying functions. If you are trying to do the same thing, then you can find the module here: http://www.planetjoel.com/viewarticle/629/Python+NSS+netgroups+interface Cheers Joel On Thu, Nov 6, 2008 at 10:34 AM, Joel Heenan wrote: > Python List, > > We have a setup where we have implemented NIS Netgroups through LDAP. > I'm looking to query this information through python. We don't have a > nis domain or nis server so I don't think the nis module is > appropriate, what I think I'm looking for is python bindings for nss > (name switching services). Does such a module exist? grp, pwd, spwd I > think are all going through NSS but do not handle netgroups. > > Thanks > > Joel > -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Sun Dec 7 09:36:18 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 07 Dec 2008 14:36:18 +0000 Subject: Don't you just love writing this sort of thing :) References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: Lawrence D'Oliveiro writes: > In message , Arnaud Delobelle wrote: > >> * you seem to disregard the fact that in 'programming language' there >> is the word 'language'. A language is a way to _communicate_ >> information, in the case of a programming language you communicate >> it to the computer but also to other human beings. > > It was Niklaus Wirth, I think who pointed out that programming languages are > not properly "languages" but are actually "notations". Like mathematics is > a notation. I suppose anyone could call them what they want. The fact is that they are languages with grammars. Anyway, replace 'language' with 'notation' in my point and it is still meaningful. > And mathematics, too, is a predominantly functional, not a procedural, > notation. Well, mathematics is seldom concerned with procedures, that's true. But mathematics is more preoccupied with relations than functions. > Could that be why so many people are frightened of functional > constructs, like my code example and things like lambdas? Because they > look too much like mathematics? I don't think that people have been frightened by it. They don't think it's expressed elegantly as Python is designed to be used as an imperative language. -- Arnaud -- Arnaud From jarausch at skynet.be Mon Dec 1 11:09:55 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Mon, 01 Dec 2008 17:09:55 +0100 Subject: double import protection - how to ? In-Reply-To: References: <49313901$0$2854$ba620e4c@news.skynet.be> <49316253.5010701@skynet.be> Message-ID: <49340C53.8000504@skynet.be> Peter Otten wrote: > Helmut Jarausch wrote: > >> Peter Otten wrote: >>> Helmut Jarausch wrote: >> Then it's a problem with a problem with a webserver written in Python >> (Karrigell-3.0) and probably related to multi-threading (the statements in >> my module get definitely executed more than once). > > Maybe you have the reload_modules* option switched on? That would defeat > Python's caching in order to ease development. > > (*) see http://karrigell.sourceforge.net/en/configuration.htm > Thanks Peter for the hint. Indeed, I am trying to port my application to Karrigell-3.0, where Python's caching is bypassed and the statements in the module get executed each time. So, I have to install a trap door using a global variable. Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From nick at craig-wood.com Tue Dec 2 05:30:46 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 02 Dec 2008 04:30:46 -0600 Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> Message-ID: Slaunger wrote: > On 1 Dec., 16:30, Nick Craig-Wood wrote: > > > > I wouldn't use __getattr__ unless you've got lots of attributes to > > overload. ?__getattr__ is a recipe for getting yourself into trouble > > in my experience ;-) > > > > Just do it like this... > > > > class PayloadOnDemand(object): > > ? ? ? def __init__(self, a_file, a_file_position): > > ? ? ? ? ? self._data = None > > ? ? ? ? ? self.f = a_file > > ? ? ? ? ? self.file_position = a_file_position > > > > ? ? ? @property > > ? ? ? def data(self): > > ? ? ? ? ? if self._data is None: > > ? ? ? ? ? ? ? self._data = self.really_read_the_data() > > ? ? ? ? ? return self._data > > > > then you'll have a .data attribute which when you read it for the > > first time it will populate itself. > > > > If None is a valid value for data then make a sentinel, eg > > > > class PayloadOnDemand(object): > > ? ? ? sentinel = object() > > > > ? ? ? def __init__(self, a_file, a_file_position): > > ? ? ? ? ? self._data = self.sentinel > > ? ? ? ? ? self.f = a_file > > ? ? ? ? ? self.file_position = a_file_position > > > > ? ? ? @property > > ? ? ? def data(self): > > ? ? ? ? ? if self._data is self.sentinel: > > ? ? ? ? ? ? ? self._data = self.really_read_the_data() > > ? ? ? ? ? return self._data > > > > > > - Vis tekst i anf?rselstegn - > > OK, I get it. In my case I have four attributes to create when one of > them is accessed, I do not know if that is a lot of attributes;-) One > thing I like about the __getattr__ is that it is only called that one > single time where an attempt to read a data attribute fails because > the attribute name is not defined in the __dict__ of the object. For 4 attributes I'd probably go with the __getattr__. Or you could easily write your own decorator to cache the result... Eg http://code.activestate.com/recipes/363602/ > With the property methology you do the value check on each get, which > does not look as "clean". The property methology is also a little less > arcane I guess for less experienced Python programmers to understand > when re-reading the code. Less magic is how I would put it. Magic is fun to write, but a pain to come back to. Over the years I find I try to avoid magic more and more in python. > What kind of trouble are you referring to in __getattr__? Is it > recursive calls to the method on accessing object attributes in that > method itself or other complications? Every time I write a __getattr__ I get tripped up by infinite recursion! It is probably just me ;-) > On a related issue, thank you for showing me how to use @property as a > decorator - I was not aware of that possibility, just gotta understand > how to decorate a setter and delete method as well, but I should be > able to look that up by myself... I'm sure you will! http://www.python.org/doc/2.5.2/lib/built-in-funcs.html -- Nick Craig-Wood -- http://www.craig-wood.com/nick From googler.1.webmaster at spamgourmet.com Fri Dec 5 18:29:45 2008 From: googler.1.webmaster at spamgourmet.com (googler.1.webmaster at spamgourmet.com) Date: Fri, 5 Dec 2008 15:29:45 -0800 (PST) Subject: Python C API References: <54fbb55d-3c39-459d-86a3-302b69721f0f@s20g2000yqh.googlegroups.com> <4938ed67$0$30227$9b4e6d93@newsspool1.arcor-online.net> <3d1b6644-c943-412d-8860-6779a981fa44@20g2000yqt.googlegroups.com> Message-ID: <83d478fd-f4a8-495c-b216-b42f4147768c@a12g2000yqm.googlegroups.com> Hi! Any ideas? Thanks, :) From skip at pobox.com Thu Dec 4 12:52:38 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 4 Dec 2008 11:52:38 -0600 Subject: RELEASED Python 3.0 final In-Reply-To: References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> Message-ID: <18744.6374.72609.825058@montanaro-dyndns-org.local> >>> As you have probably guessed: nothing changed here. >>> Also see:http://www.python.org/dev/peps/pep-0666/ >> >> What? Do you mean it's possible to mix tabs and spaces still? Why? Daniel> Why not? Because it has historically been a source of errors in a mixed development environment (people using text editors with different tab stops). Better to not allow them to be mixed. Skip From iofferkicks21 at gmail.com Wed Dec 24 09:41:42 2008 From: iofferkicks21 at gmail.com (www.iofferkicks.com) Date: Wed, 24 Dec 2008 06:41:42 -0800 (PST) Subject: www.iofferkicks.com china cheap wholesale nike shoes,air jordan shoes,air force one shoes. Message-ID: Get Nike Shoes at Super Cheap Prices Discount Nike air jordans (www.iofferkicks.com) Discount Nike Air Max 90 Sneakers (www.iofferkicks.com) Discount Nike Air Max 91 Supplier (www.iofferkicks.com) Discount Nike Air Max 95 Shoes Supplier (www.iofferkicks.com) Discount Nike Air Max 97 Trainers (www.iofferkicks.com) Discount Nike Air Max 2003 Wholesale (www.iofferkicks.com) Discount Nike Air Max 2004 Shoes Wholesale (www.iofferkicks.com) Discount Nike Air Max 2005 Shop (www.iofferkicks.com) Discount Nike Air Max 2006 Shoes Shop (www.iofferkicks.com) Discount Nike Air Max 360 Catalogs (www.iofferkicks.com) Discount Nike Air Max Ltd Shoes Catalogs (www.iofferkicks.com) Discount Nike Air Max Tn Men's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 2 Women's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 3 Customize (www.iofferkicks.com) Discount Nike Air Max Tn 4 Shoes Customize ( www.iofferkicks.com) Discount Nike Air Max Tn 6 Supply (www.iofferkicks.com) Discount Nike Shox NZ Shoes Supply (www.iofferkicks.com) Discount Nike Shox OZ Sale (www.iofferkicks.com) Discount Nike Shox TL Store (www.iofferkicks.com) Discount Nike Shox TL 2 Shoes Store (www.iofferkicks.com) Discount Nike Shox TL 3 Distributor (www.iofferkicks.com) Discount Nike Shox Bmw Shoes Distributor (www.iofferkicks.com) Discount Nike Shox Elite Shoes Manufacturer (www.iofferkicks.com) Discount Nike Shox Monster Manufacturer (www.iofferkicks.com) Discount Nike Shox R4 Running Shoes (www.iofferkicks.com) Discount Nike Shox R5 Mens Shoes (www.iofferkicks.com) Discount Nike Shox Ride Womens Shoes (www.iofferkicks.com) Discount Nike Shox Rival Shoes Wholesaler (www.iofferkicks.com) Discount Nike Shox Energia Wholesaler (www.iofferkicks.com) Discount Nike Shox LV Sneaker (www.iofferkicks.com) Discount Nike Shox Turbo Suppliers (www.iofferkicks.com) Discount Nike Shox Classic Shoes Suppliers (www.iofferkicks.com) Discount Nike Shox Dendara Trainer (www.iofferkicks.com) Discount Nike Air Jordan 1 Seller (www.iofferkicks.com) Discount Nike Air Jordan 2 Shoes Seller (www.iofferkicks.com) Discount Nike Air Jordan 3 Collection (www.iofferkicks.com) Discount Nike Air Jordan 4 Shoes Collection (www.iofferkicks.com) Discount Nike Air Jordan 5 Chaussure Shoes (www.iofferkicks.com) Discount Nike Air Jordan 6 Catalog (www.iofferkicks.com) Discount Nike Air Jordan 7 Shoes Catalog (www.iofferkicks.com) Discount Nike Air Jordan 8 Customized (www.iofferkicks.com) Discount Nike Air Jordan 9 Shoes Customized (www.iofferkicks.com) Discount Nike Air Jordan 10 Wholesalers (www.iofferkicks.com) Discount Nike Jordan 11 Shoes Wholesalers (www.iofferkicks.com) Discount Nike Air Jordan 12 Factory (www.iofferkicks.com) Discount Nike Air Jordan 13 Shoes Factory (www.iofferkicks.com) Discount Nike Air Jordan 14 Shoes Sell (www.iofferkicks.com) Discount Nike Air Jordan 16 Exporter (www.iofferkicks.com) Discount Nike Air Jordan 17 Shoes Exporter (www.iofferkicks.com) Discount Nike Air Jordan 18 Offer (www.iofferkicks.com) Discount Nike Air Jordan 19 Shoes Offer (www.iofferkicks.com) Discount Nike Air Jordan 20 Manufacture (www.iofferkicks.com) Discount Nike Jordan 21 Shoes Manufacture (www.iofferkicks.com) EMAIL:IOFFERKICKS at GMAIL.COM MSN :IOFFERKICKS at MSN.COM From bearophileHUGS at lycos.com Fri Dec 5 22:23:42 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 5 Dec 2008 19:23:42 -0800 (PST) Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> <5926cb50-e53f-4e9e-8672-b4e29e2280b5@r36g2000prf.googlegroups.com> <0149a9be$0$20670$c3e8da3@news.astraweb.com> Message-ID: <32eb24d8-c402-4104-8488-e79ec7998d24@v4g2000yqa.googlegroups.com> Steven D'Aprano: >I think you're talking about mixed spaces/tabs in the one module.< Right. >My gut feeling is that you have to have a fairly unusual set of circumstances before it causes actual bugs.< I don't mix tab and spaces in my code, and my editor is able to convert them, so after the first few days of Python coding, it more or less never caused me problems. But such thing in code written by others has caused me enough troubles, I am generally unable to edit such code keeping it functional, so I have to (sometimes by trial and error) convert it to a space only (or tabs only) format. Such troubles aren't that large compared for example to the usual troubles I receive writing and comping C++ code, but enough compared to the usual smoothness of coding in Python :-) >Er, what do you mean? What wart?< Not using {:}/{} as literals for empty dict/set. Bye, bearophile From clp at rebertia.com Mon Dec 22 02:08:32 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 21 Dec 2008 23:08:32 -0800 Subject: How to represent a sequence of raw bytes In-Reply-To: References: <200812220327.36180.motoom@xs4all.nl> Message-ID: <47c890dc0812212308i68cd7925w7ff8d5a21584a3ba@mail.gmail.com> On Sun, Dec 21, 2008 at 10:56 PM, Steven Woody wrote: > On Mon, Dec 22, 2008 at 10:27 AM, Michiel Overtoom wrote: >> On Monday 22 December 2008 03:23:03 Steven Woody wrote: >> >>> 2. char buf[] = {0x11, 0x22, 0x33, ... } >>> >>> What's the equivalent representation for above in Python? >> >>>>> buf="\x11\x22\33" >>>>> for b in buf: print ord(b) >> ... >> 17 >> 34 >> 27 >>>>> >> > > Hi, Michiel > > I thing "\x11\x22\x33" in python is not the {0x11, 0x22, 0x33} in C. > Since, a string in python is immutable, I can _not_ do something like: > b[1] = "\x55". > > And, how about char buf[200] in my original question? The intension > is to allocate 200 undefined bytes in memory. Thanks. You want the `bytearray` type referred to in PEP 3137 (http://www.python.org/dev/peps/pep-3137/). However, I believe `bytearray` is only available in Python 3.0 Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From istvan.albert at gmail.com Fri Dec 5 15:17:55 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Fri, 5 Dec 2008 12:17:55 -0800 (PST) Subject: slow Python 3.0 write performance? References: Message-ID: On Dec 5, 3:06?pm, s... at pobox.com wrote: > It should get faster over time. ?It will get faster over a shorter period of > time if people contribute patches. I see, thanks for the clarification. I will make the point though that this makes python 3.0 unsuited for anyone who has to process data. One could live with slowdowns of say 20-50 percent, to get the goodies that 3.0 offers, but when a process that takes 1 second suddenly starts to take 10, it is makes the situation untenable. best, Istvan From Werner.Merkl at fujitsu-siemens.com Wed Dec 17 03:09:38 2008 From: Werner.Merkl at fujitsu-siemens.com (Werner Merkl) Date: Wed, 17 Dec 2008 09:09:38 +0100 Subject: Windows PE and Python 2.6 (Side-by-Side error) In-Reply-To: <491DAA05.7080301@v.loewis.de> References: <491DAA05.7080301@v.loewis.de> Message-ID: <4948B3C2.4010301@fujitsu-siemens.com> Martin v. L?wis schrieb: >> Has anyone an idea? > > You should not install "for all users" before copying it, > but "just for me". > > Regards, > Martin This works! Thank you very much! (Sorry for the delay. I had been on a conference, than I was ill and than, there were more urgent things...) But now PyScripter may not use Python 2.6 internally. E. g., if I load a python-dll (import bz2) I receise an Runtime ERROR! R6034... Again, thanx a lot Werner From maakiduwaha at gmail.com Wed Dec 3 05:37:48 2008 From: maakiduwaha at gmail.com (pappu rana) Date: Wed, 3 Dec 2008 02:37:48 -0800 (PST) Subject: USA JOB 1500$ PER DAY Message-ID: <8794fac3-d4ee-41d8-9812-bc4abdf816f7@k24g2000pri.googlegroups.com> make money any where in the world work 1 hour in day,& get 15,000$ per month. No Investment. 100% Guaranteed Income.Proofs & Details On http://multilinsolition.homestead.com From clp at rebertia.com Wed Dec 17 18:40:21 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 17 Dec 2008 15:40:21 -0800 Subject: The rule of literal string In-Reply-To: References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> <_PmdnU59w62vGtTUnZ2dnUVZ_hSdnZ2d@pdx.net> <34028b73-7807-4e88-80bc-fe31a7b1a2a0@i20g2000prf.googlegroups.com> <47c890dc0812171525t527353e2m5c8b0597ee183e21@mail.gmail.com> Message-ID: <47c890dc0812171540oab568fay928577fd3a98b51a@mail.gmail.com> On Wed, Dec 17, 2008 at 3:34 PM, James Mills wrote: > On Thu, Dec 18, 2008 at 9:25 AM, Chris Rebert wrote: >> As I stated previously, the key rule is: >> >> eval(repr(something)) == something > > This rule is only true for basic data types; > > For example: > >>>> eval(repr(1)) == 1 > True >>>> eval(repr([1, 2, 3])) == [1, 2, 3] > True >>>> eval(repr({"a": 1, "b": 2, "c": 3})) == {"a": 1, "b": 2, "c": 3} > True >>>> eval(repr("foo")) == "foo" > True > > I guess the key thing here is that the repr > implementation (__repr__) for str, int, float > list and dict return sensible represenations > that Python _can_ evaluate with eval(...) > > --JamesMills > True, I oversimplified to make things easier to understand. Strictly speaking, only the basic types make the guarantee I stated. Arbitrary types can have arbitrary, non-eval()-able repr()s. But the docs do state eval()-ability as a goal: repr(object) Return a string containing a printable representation of an object. [...] For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From arnodel at googlemail.com Sun Dec 14 05:52:25 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 14 Dec 2008 10:52:25 +0000 Subject: Optimizing methods away or not? References: <0154b041$0$6988$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano writes: > I have a class with a method meant to verify internal program logic (not > data supplied by the caller). Because it is time-consuming but optional, > I treat it as a complex assertion statement, and optimize it away if > __debug__ is false: > > class Parrot: > def __init__(self, *args): > print "Initialising instance..." > if __debug__: > self.verify() # check internal program state, not args > if __debug__: > def verify(self): > print "Verifying..." > > > If I run Python normally, I can do this: FWIW here is a way with a metaclass: ===== verify_init.py ===== from functools import wraps def post_verify(method): @wraps(method) def decorated(self, *args): result = method(self, *args) self.verify() return result return decorated class VerifyInit(type): def __new__(meta, name, bases, attrs): if __debug__: attrs['__init__'] = post_verify(attrs['__init__']) else: del attrs['verify'] return type.__new__(meta, name, bases, attrs) class Parrot: __metaclass__ = VerifyInit def __init__(self, *args): print "Initialising instance..." def verify(self): print "Verifying..." coco = Parrot() ========== marigold:junk arno$ python verify_init.py Initialising instance... Verifying... marigold:junk arno$ python -O verify_init.py Initialising instance... You could also not use the metaclass and use post_verify as a decorator: class Parrot: @post_verify def __init__(self, *args): print "Initialising instance..." if __debug__: def verify(self): print "Verifying..." -- Arnaud From excord80 at gmail.com Thu Dec 4 00:18:53 2008 From: excord80 at gmail.com (excord80 at gmail.com) Date: Wed, 3 Dec 2008 21:18:53 -0800 (PST) Subject: How can I do this (from Perl) in Python? (closures) Message-ID: <68b8294c-8771-4b02-bd46-2f25f5e01602@j35g2000yqh.googlegroups.com> I just came across http://www.perl.com/pub/a/2002/05/29/closure.html and wanted to try the "canonical example of closures" in Python. I came up with the following, but it fails: ####################### #!/usr/bin/env python def make_counter(start_num): start = start_num def counter(): start += 1 return counter from_ten = make_counter(10) from_three = make_counter(3) print from_ten() # 10 print from_ten() # 11 print from_three() # 3 print from_ten() # 12 print from_three() # 4 #################### The error message is: "UnboundLocalError: local variable 'start' referenced before assignment". The same thing happens if I omit start and just use start_num directly. How can I do it in Python? From malkia at mac.com Thu Dec 4 15:08:48 2008 From: malkia at mac.com (Dimiter "malkia" Stanev) Date: Thu, 04 Dec 2008 12:08:48 -0800 Subject: Mathematica 7 compares to other languages In-Reply-To: <6c702fda-1a8a-4c3d-a7c0-82e45edab2ce@k41g2000yqn.googlegroups.com> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <591e8625-7e4d-4db8-ae6c-73c4370f8088@q26g2000prq.googlegroups.com> <6plpnsF8pi3oU1@mid.individual.net> <6c702fda-1a8a-4c3d-a7c0-82e45edab2ce@k41g2000yqn.googlegroups.com> Message-ID: > You think the posts are bad... check out his web site... Just don't go to every page on the Xah website - some of his stuff is NSFW (Not Safe For Work). From yohell at ifm.liu.se Tue Dec 16 20:09:08 2008 From: yohell at ifm.liu.se (Joel Hedlund) Date: Wed, 17 Dec 2008 02:09:08 +0100 Subject: weird dict problem, how can this even happen? In-Reply-To: <88idnfej99XAtNXUnZ2dnUVZ_hednZ2d@pdx.net> References: <88idnfej99XAtNXUnZ2dnUVZ_hednZ2d@pdx.net> Message-ID: Scott David Daniels wrote: > Perhaps your hash function could be something like: I'm not sure I understand what you're suggesting. /Joel From gagsl-py2 at yahoo.com.ar Tue Dec 2 01:48:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Dec 2008 04:48:55 -0200 Subject: Creating classes and objects more than once? References: <5f3a7d84-d07e-417c-a228-e07bdf3b676b@v42g2000yqv.googlegroups.com> <5037872d-d2a3-4d70-be00-18fbf4279767@j35g2000yqh.googlegroups.com> <874p1syzxh.fsf@benfinney.id.au> <58cfdea8-f75f-43c4-bf60-a2dbb8ceed1d@g38g2000yqn.googlegroups.com> <87zljjy3c5.fsf@benfinney.id.au> <1e035b98-418f-4b7b-86f6-14fbfa5844b6@o2g2000yqd.googlegroups.com> <9e804f42-447a-489e-9e44-b2c81c01ddc9@g38g2000yqd.googlegroups.com> Message-ID: En Sat, 29 Nov 2008 04:51:59 -0200, Carl Banks escribi?: > On Nov 28, 11:51?pm, Carl Banks >> Absolute versus relative imports don't have anything to do with the >> issue here. ?PEP 328 concerns itself with imports relative to the >> executing module in package space. ?It has nothing to do with imports >> relative to the current directory in filename space. > > > I thought of another way to put this to help explain things. Suppose > you have two files in your current directory, a Python script file > (app.py) which imports a Python module (work.py). > > Near the top of the file app.py, there is line like this: > > import work > > What happens beneath the covers when this statement is excuted (and > from __future__ import absolute_import hasn't been run)? Many people > seem to think that the Python interpreter first considers whether this > is a relative import and starts by looking for "sister" modules in the > same "package" (i.e., directory). Python would thus see the file > work.py in the same "package" and complete this as a relative import. > > Thus, they reason, if one were to add "from __future__ import > absolute_import" to the top of app.py, the import would no longer work > because implicit relative imports have been disabled. One would have > to use "from . import work" instead. > > Well, this is not how it happens. No top level module, including > __main__, is in a package. Thus, when Python sees "import work" in a > top-level module, it doesn't consider it to be a relative import, even > when implicit relative imports have not been disabled. > > The point of this is, disabling implicit relative imports has no > effect on imports from top-level modules since they were never > relative imports anyway. Python is able to find the "sisters" of top- > level modules and scripts not because it is doing a relative import, > but because those "sister" modules are in one of the directories > listed in sys.path. > > In particular, if "" is listed in sys.path, the current working > directory--even when modified by os.chdir--will be searched for > "sisters" of top-level modules. While all the above explanation is true for scripts executed using "python xxx.py", it's not the same when you execute a module using runpy.py, that is, using "python -m xxx" If you execute a module inside a package in that way, Python recognizes the fact it's inside a package, and honors relative imports (starting from version 2.6, when PEP366 was implemented). So the statement "from __future__ import absolute_import" *does* change how imports are handled on the top module. A simple test showing the difference: C:\temp\test366>dir /b b.py pkga C:\temp\test366>type b.py msg='this is the external b module' C:\temp\test366>cd pkga C:\temp\test366\pkga>dir /b abs.py b.py rel.py __init__.py C:\temp\test366\pkga>type __init__.py C:\temp\test366\pkga>type b.py msg='this is the b module inside package pkga' C:\temp\test366\pkga>type rel.py print "this script uses 'traditional' import semantics" from b import msg print msg print "using a bare import:" import b print b.msg C:\temp\test366\pkga>type abs.py from __future__ import absolute_import print "this script sets absolute_import" print "using an absolute import:" from b import msg print msg print "using a bare import:" import b print b.msg print "using an explicit relative import:" from .b import msg print msg C:\temp\test366\pkga>cd .. C:\temp\test366>python -m pkga.rel this script uses 'traditional' import semantics this is the b module inside package pkga using a bare import: this is the b module inside package pkga C:\temp\test366>python -m pkga.abs this script sets absolute_import using an absolute import: this is the external b module using a bare import: this is the external b module using an explicit relative import: this is the b module inside package pkga -- Gabriel Genellina From roy at panix.com Sat Dec 20 19:05:41 2008 From: roy at panix.com (Roy Smith) Date: Sat, 20 Dec 2008 19:05:41 -0500 Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: In article , walterbyrd wrote: > On Dec 19, 10:25?am, Michael Torrie wrote: > > > Personally the new string formatter is sorely needed in Python. ? > > Really? You know, it's funny, but when I read problems that people > have with python, I don't remember seeing that. Loads of people > complain about the white space issue. Some people complain about the > speed. Lots of complaints about certain quirky behavior, but I have > not come across any complaints about the string formatting. > > In fact, from what I have seen, many of the "problems" being "fixed" > seem to be non-problems. > > I dunno, maybe it's just me. I had an interesting experience with this recently. I was giving a co-worker quick python into. He's an experienced programer in various languages, but this was his first exposure to python. He got really hung up on the % syntax. By (bad) luck, he was trying to print a tuple (let's call it "t"), did format % t and was surprised at the result. It set him off on a "but that's stupid, blah, blah, blah" rant. I haven't absorbed the new syntax well enough to figure out if people will get hung up by this with the new syntax. From google at mrabarnett.plus.com Thu Dec 11 11:44:44 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 11 Dec 2008 16:44:44 +0000 Subject: Preventing execution of a method In-Reply-To: References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> Message-ID: <4941437C.8040901@mrabarnett.plus.com> alex23 wrote: > On Dec 12, 2:07 am, "Emanuele D'Arrigo" wrote: >> I.e. if I have a class with two methods, doSomethingSafe() and >> doSomethingDangerous(), is there a way to prevent another module from >> executing doSomethingDangerous() but allow the execution of >> doSomethingSafe()? >> >> My understanding is that in python this is not possible. Can you >> confirm? > > Your understanding is correct. > > The Python convention is to prefix non-public methods/classes etc with > an underscore, as in _doSomethingDangerous(). This is meant to > indicate to anyone using your module that they shouldn't use this > function, at least not without having a good understanding of what it > does. > You could add a little bit of protection by always passing a certain object into _doSomethingDangerous(). _guard = object() def _doSomethingDangerous(g): if g is not _guard: raise Exception("Don't do that!") That would at least stop accidental calls. From jcd at sdf.lonestar.org Thu Dec 25 19:16:41 2008 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Thu, 25 Dec 2008 19:16:41 -0500 Subject: Exec inside a class method to call other class methods? In-Reply-To: <4953CF57.8080905@sympatico.ca> References: <4953CF57.8080905@sympatico.ca> Message-ID: <20081226001641.GA22946@sdf.lonestar.org> On Thu, 25 Dec 2008 13:22:15 -0500 Matthew Dubins wrote: > Hello all, > > I have made a python script to upload contact information from an > excel worksheet to an online database. One part of the program that > really tripped me up was when I wanted to call specific class methods > that I had made to deal with specific types of contact information > (Parent's name, Child's name, Phone #, etc). My first thought was to > make it easy using the exec statement. > > The code (a method within a class) looked like this: > ---------- > def parse(self, data, data_type) > exec "self.__parse_%s(data)" % data_type > ---------- > The data_type variable contains strings that exactly match the > spellings of the 2nd word in the titles of the class methods that I > wanted to call for each data_type inputted into the parse function. > For some reason, *it didn't work*. Alternately, I found the ugly > code shown below to be functional. As you can see, for each > data_type, I call the corresponding class method that I've > specified. Please help me to transform my ugly functional code into > concise functional code. :) > > Thanks, > Matthew > ---------- > def parse(self, data, data_type): > if data_type == 'nocall': > self.__parse_nocall(data) > elif data_type == 'DOB': > self.__parse_DOB(data) > elif data_type == 'gender': > self.__parse_gender(data) > elif data_type == 'Prematurity': > self.__parse_Prematurity(data) > elif data_type == 'email': > self.__parse_email(data) > elif data_type == 'languages': > self.__parse_languages(data) > elif data_type == 'phone': > self.__parse_phone(data) > elif data_type == 'cname': > self.__parse_cname(data) > elif data_type == 'pname': > self.__parse_pname(data) > elif data_type == 'address': > self.__parse_address(data) > elif data_type == 'duedate': > self.__parse_dudedate(data) > This is precisely what subclasses were designed for: class DataField(object): def __init__(self, data): self.data = data def parse(self): pass class AddressDataField(DataField): def parse(self): self.data = do_something(self.data) class DueDateDataField(DataField): def parse(self): self.data = parse_date(self.data) and so forth. Then your if/else chain can be pulled out to the place where you instantiate each field: if data_type=='address': field=AddressDataField(data) elif data_type=='due_date': field=DueDateDataField(data) else: field = DataField(data) Then a simple field.parse() will do the right thing to field.data(). You might even include the parsing in __init__(). Define __init__() once on the base class (DataField), and it will pull the proper parse method from the subclass. Happy Hacking, and Merry Christmas. Cliff From rileyrgdev at gmail.com Mon Dec 1 09:04:00 2008 From: rileyrgdev at gmail.com (Richard Riley) Date: Mon, 01 Dec 2008 15:04:00 +0100 Subject: Emacs vs. Eclipse vs. Vim References: Message-ID: Roy Smith writes: > In article , > Richard Riley wrote: > >> Roy Smith writes: >> >> > Clay Hobbs wrote: >> >> The first real text editor I used was Vim, which I actually started >> >> using about a year ago. I've looked at Emacs and it just looks >> >> confusing. >> > >> > I've been using emacs for so many years (um let's see, it's got to be close >> > to 25 years now; first saw it on Columbia's TOPS-20 systems in the early >> > 80's) that my fingers know what they're doing without my even thinking >> > about it. In fact, I used to work with another emacs nut. Every so often, >> > one of use would watch the other do something and ask, "What was that?". >> > Inevitably, neither of us could evoke the keystrokes we had just typed. We >> > would just re-do it, and watch our fingers to see what we typed. It didn't >> > even have to be on a keyboard; we could air-type it, and that was good >> > enough. >> > >> > In any case, the basic logic behind emacs is pretty simple. C-F is forward >> > one character. C-B is back one character. C-N is Next line. C-P is >> > Previous line. >> >> It's worth pointing out to people making "loony" signs here that the >> arrow keys work too .... > > Yeah, I guess. I use the arrows keys to mindlessly scroll around in a > file, especially when I just want to show some code to somebody. It serves > two purposes. First, I can lean way back from the keyboard and reach out > with one hand (giving the other person better visibility). Second, it > makes it easier for a non-emacs person to jump in and drive for a while > (they saw me use the arrow keys and do the same, no explanations needed). > > For any serious editing, however, it's strictly the keys on the main part > of the keyboard. It's just so much faster when your hands never have to > leave their home position. To use the arrow keys, I need to pick my hand > up and move it over to the arrow key cluster. Slow, slow, slow. Have to disagree. I could never use C-f etc. If I want to navigate the cursor its generally to browse and the 10th of a second it takes to rest hand on the cursor pad is immaterial in the time compared to sit back and read the code. I find the reference to using control keys to naviaget code character and line at time leads to more people abandoning emacs than you would believe. All it needs is a "cursor keys or, for hardcore types, the following key sequences". Still. all to their own. -- important and urgent problems of the technology of today are no longer the satisfactions of the primary needs or of archetypal wishes, but the reparation of the evils and damages by the technology of yesterday. ~Dennis Gabor, Innovations: Scientific, Technological and Social, 1970 From steve at REMOVE-THIS-cybersource.com.au Thu Dec 25 08:24:03 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Dec 2008 13:24:03 GMT Subject: PythonCard timer/thread tutorial References: <59e602b0-937c-4bd5-bc71-30094e1cd596@r36g2000prf.googlegroups.com> <6f7164cc-56dc-4022-8943-067b8ca44e61@40g2000prx.googlegroups.com> Message-ID: <0163809d$0$6988$c3e8da3@news.astraweb.com> On Wed, 24 Dec 2008 16:59:23 -0800, Mike Driscoll wrote: >> Among my questions are: >> """ A little thread we've added""" seems to be an isolated string. It >> does not seem to be doing anything there, almost like a comment. Why is >> it there? > > > That's what some people call a doc string. Other people call it "Maurice". *wink* A doc[umentation] string is the accepted name for it. Anytime a function, class or module starts immediately with a loan string, that string is stored by the Python compiler in an attribute __doc__. E.g.: >>> def parrot(x): ... "This is a doc string." ... return "Norwegian Blue" ... >>> parrot.__doc__ 'This is a doc string.' > It is like a comment in that > it helps the user know what the function is for. Notice the triple > quotes. Triple quotes are a red herring. Any string literal will do. -- Steven From mudzot at gmail.com Tue Dec 16 12:47:11 2008 From: mudzot at gmail.com (mudzot) Date: Tue, 16 Dec 2008 09:47:11 -0800 (PST) Subject: Free place to host python files? References: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> <32599660-2393-4e18-8c48-05d64bccbbc1@t26g2000prh.googlegroups.com> Message-ID: > well, ignoring the fact that pastebin doesn't work for me for some > reason, I'm talking about hosting it as a .py downloadable, not a hunk > of text. maybe one option is registering in some free project hosting service like code.google.com From geekmail at usenot.de Wed Dec 3 05:48:55 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Wed, 3 Dec 2008 11:48:55 +0100 Subject: Reverse zip() ? References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> <20081203095154.1bb33d4d@usenot.de> <8000d0b0-c9e5-4dbd-a6a0-e35b83277e72@d42g2000prb.googlegroups.com> Message-ID: <20081203114855.3915af9e@usenot.de> On Wed, 3 Dec 2008 02:11:51 -0800 (PST) alex23 wrote: > On Dec 3, 6:51?pm, Andreas Waldenburger wrote: > > On Tue, 02 Dec 2008 18:16:13 -0800 Bryan Olson > > > zip as its own inverse might be even easier to comprehend if we > > > call zip by its more traditional name, "transpose". > > > > Sounds like a Py4k change to me. > > Nah, just add the following to your sitecustomize.py: > > transpose = zip > > :) Gaaahh! :) /W -- My real email address is constructed by swapping the domain with the recipient (local part). From stefan_ml at behnel.de Sat Dec 20 05:27:24 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 20 Dec 2008 11:27:24 +0100 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <015c47ad$0$20656$c3e8da3@news.astraweb.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c47ad$0$20656$c3e8da3@news.astraweb.com> Message-ID: <494cc88c$0$31344$9b4e6d93@newsspool4.arcor-online.net> Steven D'Aprano wrote: > I have no objection to > the addition of the format() method (although I wonder whether it might > have been better as a function). I actually learned about the String.format() method in Java a while after having read about str.format() in Python, and my first reaction was to recognise how stupid you'd have to be to make that a static method that ignores the string it's called on. :) I think '...'.format() makes sense given that we already have '...'.join(). Stefan From jon at ffconsultancy.com Wed Dec 3 11:24:36 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Wed, 03 Dec 2008 16:24:36 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> Message-ID: Xah Lee wrote: > On Dec 2, 5:13 pm, Jon Harrop wrote: >> The Mathematica code is 700,000x slower so a 50% improvement will be >> uninteresting. Can you make my Mathematica code five orders of magnitude >> faster or not? > > Pay me $10 thru paypal, i'll can increase the speed so that timing is > 0.5 of before. > > Pay me $100 thru paypal, i'll try to make it timing 0.1 of before. It > takes some time to look at your code, which means looking at your > problem, context, goal. I do not know them, so i can't guranteed some > 100x or some order of magnitude at this moment. > > Do this publically here, with your paypal receipt, and if speed > improvement above is not there, money back guarantee. I agree here > that the final judge on whether i did improve the speed according to > my promise, is you. Your risk would not be whether we disagree, but if > i eat your money. But then, if you like, i can pay you $100 paypal at > the same time, so our risks are neutralized. However, that means i'm > risking my time spend on working at your code. So, i suggest $10 to me > would be good. Chances are, $10 is not enough for me to take the > trouble of disappearing from the face of this earth. My example demonstrates several of Mathematica's fundamental limitations. They cannot be avoided without improving or replacing Mathematica itself. These issues are never likely to be addressed in Mathematica because its users value features and not general performance. Consequently, there is great value in combining Mathematica with performant high-level languages like OCaml and F#. This is what the vast majority of Mathematica users do: they use it as a glorified graph plotter. >> > few tips: >> >> > ? Always use Module[] unless you really have a reason to use Block[]. >> >> Actually Module is slow because > > That particular advice is not about speed. It is about lexical scoping > vs dynamic scoping. > >> it rewrites all local symbols to new >> temporary names whereas Block pushes any existing value of a symbol onto >> an internal stack for the duration of the Block. > > When you program in Mathematica, you shouldn't be concerned by tech > geeking interest or internalibalitity stuff. Optimization is > important, but not with choice of Block vs Module. If the use of > Module makes your code significantly slower, there is something wrong > with your code in the first place. What exactly do you believe is wrong with my code? >> In this case, Module is 30% slower. > > Indeed, because somethnig is very wrong with your code. No, that is a well-known characteristic of Mathematica's Module and it has nothing to do with my code. >> > ? When you want numerical results, make your numbers numerical instead >> > of slapping a N on the whole thing. >> >> Why? > > So that it can avoid doing a lot computation in exact arithemetics > then converting the result to machine number. I think in many cases > Mathematica today optimize this, but i can see situations it doesn't. That is a premature optimization that has no significant effect in this case because all applications of N have already been hoisted. >> > ? Avoid Table[] when you really want go for speed. Try Map and Range. >> >> The time spent in Table is insignificant. > > just like Block vs Module. It depends on how you code it. If Table is > used in some internal loop, you pay for it. It is insignificant in this case. >> > ? I see nowhere using Compile. Huh? >> >> Mathematica's Compile function has some limitations that make it >> difficult to leverage in this case: > > When you are doing intensive numerical computation, your core loop > should be compiled. No, such computations must be off-loaded to a more performant high-level language implementation like OCaml or F#. With up to five orders of magnitude performance difference, that means almost all computations. >> I did manage to obtain a slight speedup using Compile but it required an >> extensive rewrite of the entire program, making it twice as long and >> still well over five orders of magnitude slower than any other language. > > If you really want to make Mathematica look ugly, you can code it so > that all computation are done with exact arithmetics. You can show the > world how Mathematica is one googleplex times slower. I am not trying to make Mathematica look bad. It is simply not suitable when hierarchical solutions are preferable, e.g. FMM, BSPs, adaptive subdivision for cosmology, hydrodynamics, geophysics, finite element materials... The Mathematica language is perhaps the best example of what a Lisp-like language can be good for in the real world but you cannot compare it to modern FPLs like OCaml, Haskell, F# and Scala because it doesn't even have a type system, let alone a state-of-the-art static type system. Mathematica is suitable for graph plotting and for solving problems where it provides a prepackaged solution that is a perfect fit. Even then, you can have unexpected problems. Compute the FFT of 2^20 random machine-precision floats and it works fine. Raise them to the power of 100 and it becomes 100x slower, at which point you might as well be writing your numerical code in PHP. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From bearophileHUGS at lycos.com Tue Dec 16 11:44:42 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 16 Dec 2008 08:44:42 -0800 (PST) Subject: Generator slower than iterator? References: Message-ID: MRAB: > from collections import defaultdict > match_counter = defaultdict(int) > for line in fileinput.input(sys.argv[1:]): > ip = line.split()[0] > match_counter[ip] += 1 This can be a little faster still: match_counter = defaultdict(int) for line in fileinput.input(sys.argv[1:]): ip = line.split(None, 1)[0] match_counter[ip] += 1 Bye, bearophile From David Fri Dec 26 16:52:24 2008 From: David (David) Date: Fri, 26 Dec 2008 15:52:24 -0600 Subject: strange behavior of math.sqrt() in new 3.0 version Message-ID: I'm a newbee trying 3.0 Please help with math.sqrt() At the command line this function works correctly >>> import math n = input("enter a number > ") s = math.sqrt(n) An entry of 9 or 9.0 will yield 3.0 Yet the same code in a script gives an error message Script1 import math n = input("enter a number > ") s = math.sqrt(n) Traceback (most recent call last) : File "", line 1, in File "script1.py" line 3 in s = math.sqrt(n) TypeError : a float is required Entering 9 or 9.0 gives same error message. According to the math module the results of all functions are floats. However it says nothing about inputs. Strangely the above code runs fine in version 2.5 ( ? ) and will handle large integers. I've read the documentation for 3.0 including the section "Floating Point Arithmetic: Issues & Limitations" and it helps nada. From federico at linux.com.uy Tue Dec 16 10:07:14 2008 From: federico at linux.com.uy (Federico Moreira) Date: Tue, 16 Dec 2008 12:07:14 -0300 Subject: Generator slower than iterator? Message-ID: Hi all, Im parsing a 4.1GB apache log to have stats about how many times an ip request something from the server. The first design of the algorithm was for line in fileinput.input(sys.argv[1:]): ip = line.split()[0] if match_counter.has_key(ip): match_counter[ip] += 1 else: match_counter[ip] = 1 And it took 3min 58 seg to give me the stats Then i tried a generator solution like def generateit(): for line in fileinput.input(sys.argv[1:]): yield line.split()[0] for ip in generateit(): ...the same if sentence Instead of being faster it took 4 min 20 seg Should i leave fileinput behind? Am i using generators with the wrong aproach? Thanks in advance, Federico. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jon at ffconsultancy.com Wed Dec 10 05:45:25 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Wed, 10 Dec 2008 10:45:25 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <9ecfa224-ce8f-44e9-abca-008314f44e87@40g2000prx.googlegroups.com> Message-ID: <3sOdnVyMm5m4AKLUnZ2dnUVZ8hydnZ2d@posted.plusnet> Stef Mientki wrote: > Who said Mathematica was a high level language ? Xah is using what he calls "highlevelness" as an excuse for poor performance. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From bearophileHUGS at lycos.com Fri Dec 12 09:58:39 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 12 Dec 2008 06:58:39 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> Message-ID: <25b4d503-5073-4e66-8914-ca5fa7b144e1@w39g2000prb.googlegroups.com> sturlamolden: > On a recent benchmark Java 6 -server beats C compiled by GCC 4.2.3 And > most of that magic comes from an implementation of a dynamically typed > language (Smalltalk). [...] > http://shootout.alioth.debian.org/u32q/benchmark.php?test=all?=all That is indeed a nice result, JavaVM has come a long way from the first one used for applets. That result comes mostly from the fact that this is a test on a 4-core CPU, that is less easy to manage from C. You can see that in the single 64-bit core tests: http://shootout.alioth.debian.org/u64/benchmark.php?test=all&lang=all And take a look at the memory used too, up to 34 times higher for the JVM on the 4-core CPU. In the next years people that use low-level languages like C may need to invent a new language fitter for multi-core CPUs, able to be used on GPUs too (see the OpenCL), less error-prone than C, able to use the CPU vector instructions efficiently. (The D language is probably unfit for this purpose, because even if it's meant to be a system language, I don't think it can be used much to replace C everywhere it's used now.) A C+ maybe? :-) I agree that CPython may quite enjoy having something built-in like Psyco, but it's a lot of work for an open source project. Probably with 1/3 or 1/2 of the work poured on PyPy you may create that improvement for CPython. Maybe PyPy will someday produce some fruit, but I think they have used the wrong strategy: instead of trying to create something very new that someday will work, it's often better to try to improve something that today everybody uses, AND try to be useful from almost the very beginning. Bye, bearophile From gagsl-py2 at yahoo.com.ar Mon Dec 29 04:52:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Dec 2008 07:52:16 -0200 Subject: Read-Write Lock vs primitive Lock() References: Message-ID: En Mon, 29 Dec 2008 05:56:10 -0200, k3xji escribi?: > I am trying to see on which situations does the Read-Write Lock > performs better on primitive Lock() itself. Below is the code I am > using to test the performance: > import threading > import locks > import time > > class mylock(object): (I'm not convinced your lock is correct) > GLOBAL_VAR = 1 > #GLOBAL_LOCK = locks.ReadWriteLock() > GLOBAL_LOCK = threading.Lock() > #GLOBAL_LOCK = mylock() > GLOBAL_LOOP_COUNT = 100000 > GLOBAL_READER_COUNT = 1000 > GLOBAL_WRITER_COUNT = 1 Only one writer? If this is always the case, you don't need a lock at all. > class wthread(threading.Thread): > def run(self): > try: > #GLOBAL_LOCK.acquireWrite() > #GLOBAL_LOCK.acquire_write() > GLOBAL_LOCK.acquire() > for i in range(GLOBAL_LOOP_COUNT): > GLOBAL_VAR = 4 > finally: > #GLOBAL_LOCK.release_write() > GLOBAL_LOCK.release() Note that the thread acquires the lock ONCE, repeats several thousand times an assignment to a *local* variable called GLOBAL_VAR (!), finally releases the lock and exits. As every thread does the same, they just run one after another, they never have a significant overlap. Also, you should acquire the lock *before* the try block (you have to ensure that, *after* acquiring the lock, it is always released; such requisite does not apply *before* acquiring the lock) I'd test again with something like this: class wthread(threading.Thread): def run(self): global GLOBAL_VAR for i in xrange(GLOBAL_LOOP_COUNT): GLOBAL_LOCK.acquire() try: GLOBAL_VAR += 1 finally: GLOBAL_LOCK.release() > class rthread(threading.Thread): > def run(self): > try: > #GLOBAL_LOCK.acquireRead() > #GLOBAL_LOCK.acquire_read() > GLOBAL_LOCK.acquire() > for i in range(GLOBAL_LOOP_COUNT): > GLOBAL_VAR = 3 > finally: > #GLOBAL_LOCK.release_read() > GLOBAL_LOCK.release() Hmmm, it's a reader but attempts to modify the value? You don't have to protect a read operation on a global variable - so a lock isn't required here. > What I am doing is: I am creating multiple readers and try to do > something. I had assumed that with using primitive Lock() on the above > situation, it will create a bottleneck on the rthreads. But the > numbers indicate that there are no difference at all. I had > implemented my own READ-WRIET lock as can be seen above mylock and > also used the one here: code.activestate.com/recipes/502283/. I hope you now understand why you got the same numbers always. -- Gabriel Genellina From fetchinson at googlemail.com Thu Dec 11 03:30:56 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 11 Dec 2008 00:30:56 -0800 Subject: why doesn't pop/clear call __delitem__ on a dict? In-Reply-To: <47c890dc0812110005m3106ff39i9f9211a99c0afc9e@mail.gmail.com> References: <47c890dc0812110005m3106ff39i9f9211a99c0afc9e@mail.gmail.com> Message-ID: >> I just found out that if I want to have a custom dict it's not enough >> to overload __getitem__, __setitem__ and __delitem__ because, for >> example, pop and clear don't call __delitem__. I.e. an instance of the >> following will not print 'deleted' upon instance.pop( 'key' ): >> >> class mydict( dict ): >> def __setitem__( self, key, value ): >> print 'set' >> super( mydict, self ).__setitem__( key, value ) >> def __getitem__( self, key ): >> print 'get' >> super( mydict, self ).__getitem__( key ) >> def __delitem__( self, key ): >> print 'deleted' >> super( mydict, self ).__delitem__( key ) >> >> Why is this? > > For optimization purposes essentially, so that the built-in dict can > be as fast as possible as it is used pervasively in Python. > >> what other methods do I have to overload so that >> I get what I expect for all dict operations? > > You might consider just subclassing UserDict.DictMixin instead: > http://docs.python.org/library/userdict.html#UserDict.DictMixin > It implements the complete dict interface all in terms of provided > __getitem__(), __setitem__(), __delitem__(), and keys() methods. Thanks a lot! -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From ivan.illarionov at gmail.com Tue Dec 23 15:51:18 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 23 Dec 2008 12:51:18 -0800 (PST) Subject: PIL - font kerning References: <21524b00-9151-43ab-b1b9-a3dd5666d959@n33g2000pri.googlegroups.com> Message-ID: <013a0d90-e70e-49e9-ad7c-73d93e7bd79a@z28g2000prd.googlegroups.com> On Dec 23, 11:22 pm, Ivan Illarionov wrote: > On 23 ???, 16:44, carsn wrote: > > > Hey all, > > > anybody know, if there?s a way to specify the kerning of a font, when > > you draw text with PIL? > > > I?d like to achieve the same effect that you get, when you set a > > negative kerning in Gimp/Photshop - ie. reduce the spacing between > > glyphs. > > > Can PIL do that or do I use another lib for that? > > > Thx for any pointers & some nice xmas days to U all! > > carsten > > No. PIL can't do that. I suggest combination of cairo/pango/pangocairo > (pycairo and pygtk packages). > > Ivan I found a little helper function that does what you want (and more) import cairo import pango import pangocairo def draw_text(surface, context, text, font="sans 14", position=None, color=None, box_width=None, alignment=pango.ALIGN_CENTER, line_spacing=None, letter_spacing=None, extra_kerning=None): if color is None: color = (0.0, 0.0, 0.0) context.set_source_rgb(*color) pc = pangocairo.CairoContext(context) layout = pc.create_layout() layout.set_text(text) layout.set_font_description(pango.FontDescription(font)) if box_width: layout.set_width(box_width) layout.set_alignment(alignment) if line_spacing: layout.set_spacing(spacing) alist = pango.AttrList() if letter_spacing: alist.insert(pango.AttrLetterSpacing(letter_spacing, 0, len (text))) if extra_kerning: for pos, kern in extra_kerning.iteritems(): alist.insert(pango.AttrLetterSpacing(kern, pos, pos +1)) layout.set_attributes(alist) if position is None: width, height = surface.get_width(), surface.get_height() w, h = layout.get_pixel_size() position = (width/2.0 - w/2.0, height/2.0 - h/2.0) context.move_to(*position) pc.show_layout(layout) And example usage: surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) context = cairo.Context(surface) draw_text(surface, context, 'Hello world!', font="sans 52", color=(.25,.28,.33), letter_spacing=-6000, extra_kerning={0:-9000, 1:-1000, 6:6000, 7:-15000, 8:5000, 9:-7000}) surface.write_to_png("hello.png") -- Ivan From saving.energy150 at gmail.com Sat Dec 6 10:02:48 2008 From: saving.energy150 at gmail.com (Energy Saver) Date: Sat, 6 Dec 2008 07:02:48 -0800 (PST) Subject: How you can save fuel and the environment Message-ID: Driving and Car Maintenance Transportation accounts for 66% of U.S. oil use -mainly in the form of gasoline. Luckily, there are plenty of ways to improve gas mileage. Driving Tips:- Idling gets you 0 miles per gallon. The best way to warm up a vehicle is to drive it. No more than 30 seconds of idling on winter days is needed. Anything more simply wastes fuel and increases emissions.- Aggressive driving (speeding, rapid acceleration, and hard braking) wastes gas. It can lower your highway gas mileage 33% and city mileage 5%. Drive at lowest and constant rpms; 2000 rpm are enough; you can save up to 30%. Even a Porsche can be driven at the 4th gear at 20 mph and at the 6th gear at 50 mph with 2.5 times less fuel consumption.- Avoid high speeds. Driving 75 mph, rather than 65 mph, could cut your fuel economy by 15%.- When you use overdrive gearing, your cars engine speed goes down. This saves gas and reduces wear.- Use air conditioning only when necessary.- Clear out your car; extra weight decreases gas mileage. Each 60 pounds increases fuel consumption by 10%. - Reduce drag by placing items inside the car or trunk rather than on roof racks. A roof rack or carrier provides additional cargo space and may allow you to buy a smaller car. However, a loaded roof rack can decrease your fuel economy by 5%.- Check into carpooling and public transit to cut mileage and car maintenance costs. Car Maintenance Tips:- Use the grade of motor oil recommended by your cars manufacturer. Using a different motor oil can lower your gasoline mileage by 1% to 2%.- Keep tires properly inflated and aligned to improve your gasoline mileage by around 3.3%.- Get regular engine tune- ups and car maintenance checks to avoid fuel economy problems due to worn spark plugs, dragging brakes, low transmission fluid, or transmission problems.- Replace clogged air filters to improve gas mileage by as much as 10% and protect your engine.- Combine errands into one trip. Several short trips, each one taken from a cold start, can use twice as much fuel as one trip covering the same distance when the engine is warm. Do not forget that in the first mile your car uses 8 times more fuel, in the second mile 4 times and only after the fourth mile it becomes normal.Long-Term Savings Tip- Consider buying a highly fuel-efficient vehicle. A fuelefficient vehicle, a hybrid vehicle, or an alternative fuel vehicle could save you a lot at the gas pump and help the environment.See the Fuel Economy Guide (www.fueleconomy.gov) for more on buying a new fuel-efficient car or truck. Source: www.eere.energy.gov and http://www.vcd.org/155.html From arnodel at googlemail.com Fri Dec 12 14:26:27 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 12 Dec 2008 19:26:27 +0000 Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> <31443882-cb41-420b-8269-b1590581783d@c36g2000prc.googlegroups.com> <6qfhc9Fc3a5jU5@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch writes: > On Fri, 12 Dec 2008 07:56:58 -0800, sturlamolden wrote: > >> On Dec 12, 4:55 pm, sturlamolden wrote: >> >>> def __setitem__(self, index, value): >>> if _buf[index] is not value: # given that _buf is the tuple's >>> internal buffer >>> raise TypeError, 'tuple' object does not support item >>> assignment >> >> bl?h, that should be self._buf[index] > > But then the error message is not true anymore because tuples *would* > support item assignment when the old and new value are the same. Which > leads to strange things like code that may or may not raise that > exception, depending on implementation details: > > t = (1, 2) > t[0] = 1 # Maybe okay -- maybe not. > t[1] += 0 # Same here. > > I'd find that quite odd. > > Ciao, > Marc 'BlackJack' Rintsch What I find a bit annoying is when you get both * an exception * a mutation E.g. >>> t[1] *= 2 Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment Now is t the same as before? Sometimes it is: >>> t (1, 2) >>> t[1] *= 2 Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment >>> t (1, 2) Sometimes not: >>> t (1, [2]) >>> t[1] *= 2 Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment >>> t (1, [2, 2]) I agree it's not a bug, but I never feel comfortable with it. -- Arnaud From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 18:50:29 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Dec 2008 23:50:29 GMT Subject: To Troll or Not To Troll (aka: "as" keyword woes) References: <20081205163107.1815df40@usenot.de> Message-ID: <0149b601$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 14:00:18 -0800, James Stroud wrote: > Andreas Waldenburger wrote: >> Is it me, or has c.l.p. developed a slightly harsher tone recently? >> (Haven't been following for a while.) > > Yep. I can only post here for about a week or two until someone blows a > cylinder and gets ugly because they interpreted something I said as a > criticism of the language and took it personally by extension. What do you mean??? Python is PERFECT and if you don't AGREE than you should go back to Ruby you Ruby-lover!!! *wink* -- Steven From kyrie at uh.cu Sun Dec 21 14:54:55 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Sun, 21 Dec 2008 14:54:55 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: <1229889295.494e9f0f58182@mail.uh.cu> Quoting r : > I noticed when i mentioned "self" nobody wants to touch that subject. > There could be many reasons why... > > 0.) nobody but the 10 regulars i see here exists > 1.) nobody cares(doubt it) > 2.) nobody is brave enough to question it(maybe) > 3.) most people like to type self over and over again(doubt it) > 4.) most people here have given up on changing the BDFL's mind about > it. (good possibility) > 5.) this is a hot-button topic(no doubt in my mind!) You forgot 6.) it is the best, cleanest, most consistent and extensible way to do it. > This was the reason for using indention over the bracket plague in > python. REDUNDANCY!!! Why not dump self and make the language cleaner. > I love python's classes, but HATE self.redundant! This really needs to > be fixed, and you have not heard the last from me about it!!! Do you also hate cls.redundant on a classmethod? Would you rather type 'self' even when it is referring to a class? Would you like to resort to a hack, like C#3.0's 'this' explicit argument, when monkey-patching? I used to hate 'self'. Then I met classmethods, metaclasses and decorators, and the 'new'/'types' modules. It's just one of those examples where Guido's time machine works flawlessly. > 3000 would have been the perfect time to dump self and really clean up > the language, and it's not too late, dawn is not upon us yet. No need to wait for python 3000. You can have a 'selfless metaclass' right now: http://www.voidspace.org.uk/python/articles/metaclasses.shtml (BTW, I really hope you are complaining about the explicit self on the argument list, and not about the 'self.' prefix - if that were the case, what magic would you propose for the compiler to guess when you are referring to locals, globals, class or instance variables?) -- Luis Zarrabeitia Facultad de Matem?tica y Computaci?n, UH http://profesores.matcom.uh.cu/~kyrie From bdesth.quelquechose at free.quelquepart.fr Thu Dec 11 14:48:49 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 11 Dec 2008 20:48:49 +0100 Subject: Preventing execution of a method In-Reply-To: <307fe197-1b42-4305-af0e-94b7ebe3ce70@r15g2000prh.googlegroups.com> References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> <764daeef-bfbe-411a-8521-bb114321e4ac@b38g2000prf.googlegroups.com> <19304f8c-e34f-4aa9-8df2-6a7d3553007a@e1g2000pra.googlegroups.com> <2eed8876-94d2-4304-88a5-eb4a78b4f41d@33g2000yqm.googlegroups.com> <307fe197-1b42-4305-af0e-94b7ebe3ce70@r15g2000prh.googlegroups.com> Message-ID: <49417c59$0$8491$426a74cc@news.free.fr> Emanuele D'Arrigo a ?crit : > Thank you all for the confirmation and the suggestions (including the > tangential ones: I didn't know one could remove your his own posts!). > > As much as I really like Python (which I've been using full-time only > for the past two months) I really wish it did have regular private/ > protected/public methods. What for ? What you need is a way to tell the client code what's part of the interface and what's implementation detail. From experience (*years* fo experience), no one in it's own mind will mess with implementation unless he has a very compelling reason _and_ is willing to pay the price ("shit, I broke everything... Ok, my fault.") > I'm building an application that can be extended by the users and I > really wish there was a solid way to prevent them from accessing parts > of the application that they shouldn't access In Python, "shouldn't access" is spelled with a single leading underscore !-) > or to provide read-only > access. I.e. right now I'm working on the graphical client which > potentially could be rewritten entirely by the users. It is necessary > and perfectly reasonable for the client module to access some of the > objects to be represented graphically, but those objects shouldn't be > modifiable by it. Why so ? At worst, they'll break everything. So what ? As long as they mess with your implementation, they are responsible for what happens. OTHO, someone may have a perfectly valid reason to rewrite parts (or whole) of your GUI - and he'll just love you for not standing in the way. > I now wonder, would developing the graphical client as an entirely > separate application, communicating with the server via the localhost > network interface and messages, solve the problem? *which* problem ? Seriously ? What do you fear ? Extension code breaking your app ? How is that *your* problem (I mean, as long as you explicitely told the user what was part of the API and what wasn't ?). What if your program was written in C, distributed only as compiled machine code, and one of your users decided to make random edits in the binary code ? Would you feel responsible ? *Nothing* in this world is idiot-proof, so don't waste time trying to protect idiots from themselves. From banibrata.dutta at gmail.com Tue Dec 2 23:54:27 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Wed, 3 Dec 2008 10:24:27 +0530 Subject: [ANN] Pyjamas 0.4: Python Web Toolkit Release In-Reply-To: References: Message-ID: <3de8e1f70812022054g40f974a1x5bdd676b2d9527ea@mail.gmail.com> Amazing concept, and glad that someone thought of this and implemented this. The book's formatting on IE and Chrome looked a bit unusual. Content wise it is already firly decent (i.e. enough to get a programmer started), but sometimes text appears in a long & narrow col. format instead of the more usual page format ... and the (i) i.e. informative text icons to the left of informative notes gives a jarring visual feel/urge to scroll to see more :). On Tue, Dec 2, 2008 at 6:15 PM, Luke Kenneth Casson Leighton wrote: > This is the 0.4 Release of Pyjamas, the python-to-javascript > compiler and Web Widget set and framework. > > Download Pyjamas 0.4 here: > https://sourceforge.net/project/showfiles.php?group_id=239074 > http://code.google.com/p/pyjamas/downloads/list > > Pyjamas started as a port of Google's Web Toolkit, to python. > Explaining why Pyjamas (and GWT) is so significant takes > some doing: the summary is that comprehensive desktop-like > user interfaces can be developed very simply, to run in > any modern web browser, without having to write a single > line of JavaScript. Further recommended reading is here: > http://advogato.org/article/993.html > http://advogato.org/article/981.html > > The homepage is http://pyjs.org > The sister project, Pyjamas-Desktop, is at http://pyjd.org > > Documentation on Pyjamas is considerable, and includes: > http://pyjs.org/book/output/Bookreader.html > http://pyjs.org/showcase/Showcase.html > http://pyjd.sf.net/api > http://pyjd.sf.net/controls_tutorial.html > http://lkcl.net/pyjamas-desktop/docs/output/docui.html > Also, as the Pyjamas UI API is near-identical to that of > GWT 1.5, the GWT JavaDoc reference guide is still relevant: > http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/index.html > -- > http://mail.python.org/mailman/listinfo/python-list > -- regards, Banibrata http://www.linkedin.com/in/bdutta http://octapod.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From BrooklineTom at gmail.com Wed Dec 31 00:02:11 2008 From: BrooklineTom at gmail.com (brooklineTom) Date: Tue, 30 Dec 2008 21:02:11 -0800 (PST) Subject: Parsing Excel spreadsheets References: <6a54de23-bea4-40c7-ad7c-22c6eba4bd8a@z6g2000pre.googlegroups.com> Message-ID: andyhume at gmail.com wrote: > Hi, > > Can anybody recommend an approach for loading and parsing Excel > spreadsheets in Python. Any well known/recommended libraries for this? > > The only thing I found in a brief search was http://www.lexicon.net/sjmachin/xlrd.htm, > but I'd rather get some more input before going with something I don't > know. > > Thanks, > Andy. I save the spreadsheets (in Excel) in xml format. I started with the standard xml tools (xml.dom and xml.dom.minidom). I built a pullparser, and then just crack them. The MS format is tedious and overly complex (like all MS stuff), but straightforward. Once I've cracked them into their component parts (headers, rows, cells, etc), then I walk through them doing whatever I want. I found this material to be no worse than doing similar crud with xhtml. I know there are various python packages around that do it, but I found the learning curve of those packages to be steeper than just grokking the spreadsheet structure itself. In spite of all the hair, the underlying MS structure really does have everything you'll need. My suggestion is just go for it, it isn't all that hard. From jfabiani at yolo.com Tue Dec 16 01:47:25 2008 From: jfabiani at yolo.com (John Fabiani) Date: Mon, 15 Dec 2008 22:47:25 -0800 Subject: tutorial on parser Message-ID: Hi, I'm attempting to learn how to convert MsSQl Transact-SQL to postgres pgsql. So far my readings have led me to finding a parser. I'm looking for a tutorial on how to get it done. I did find a commercial product but they want over $10,000 us. This way beyond my means. Therefore, I need to get it done either myself to find a open source project. Thanks in advance. John Fabiani From joe at strout.net Tue Dec 30 16:55:24 2008 From: joe at strout.net (Joe Strout) Date: Tue, 30 Dec 2008 14:55:24 -0700 Subject: embedding python in wxpython In-Reply-To: References: <191280cf-ecf9-4135-9737-9923061855d1@t39g2000prh.googlegroups.com> Message-ID: <495A98CC.5070808@strout.net> Steve Holden wrote: >> I'd like the console to be a bidirectional representation of what's >> going on in the gui, plus a general purpose evaluation environment >> where you can manipulate application data via some api which is >> automatically exposed to the console when the application opens up. >> >> I'm looking for high-level hints/strategies/directions. >> > I seem to remember you can create your wxApp with an argument of True or > False. One of those settings creates a window containing any output to > sys.stderr, if I remember rightly. You do -- True (the default) redirects standard output to a window, while False does not redirect it. However, neither setting will create a bidirectional console or evaluation environment as the OP was asking for. (But other wx widgets do provide that, as other replies have pointed out.) Best, - Joe From upton at virginia.edu Thu Dec 4 15:32:12 2008 From: upton at virginia.edu (Dan Upton) Date: Thu, 4 Dec 2008 15:32:12 -0500 Subject: Off Topic: Re: Obama's Birth Certificate - Demand that US presidential electors investigate Obama's eligibility In-Reply-To: References: <89pZk.9151$be.4743@nlpi061.nbdc.sbc.com> Message-ID: <5504f9ac0812041232x2a22a63m8217779c57d44ebd@mail.gmail.com> [snip > > > Follow-ups again set to talk.politics. Of course that may be futile in > dealing with this kind of scumbag. > > -- > --Bryan Also, changing newsgroups followups doesn't affect replying to the mailing list. From aleksandr.goretoy at gmail.com Sat Dec 27 05:54:59 2008 From: aleksandr.goretoy at gmail.com (alex goretoy) Date: Sat, 27 Dec 2008 04:54:59 -0600 Subject: parsing csv files class Message-ID: Hello All, I have this class that I use in one of my projects. I know it's missing functionality and some things could have been done differently. Can you ehlp me make this class better? What can I do to make it more resistant to error? You can find the stdout_colours class on Google if you want it, JFGI I want to make it more pythonic. I come from a PHP background, can you tell? Any and all help is appreciated -Alex #!/usr/bin/env python from ctypes import * import os, sys, types, csv, urllib, urllib2, urlparse, string,stdout_colours class parsercsvy(object): """Return a line from a csv file or total amount of lines""" def __init__(self,file_name=""): self.func_me_color="white_on_black" self.soc=stdout_colours.stdout_colors() self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.filename = file_name self.buffer = [] self.bufferp= [] if string.find(self.filename,"http") != -1: resp=urllib2.urlopen(self.filename) file=resp.read() lfi=len(string.split(self.filename,"/")) filename = "/tmp/"+string.split(self.filename,"/")[lfi-1] f=open(filename,"w") f.write(file) f.close self.parse(self.filename) else: self.parse(self.filename) self.soc.me_him(['EXIT:',__name__],self.func_me_color) def parse(self,filename,ret=0): self.soc.me_him(['ENTER:',__name__],self.func_me_color) i = 0 try: reader = csv.reader(file(filename, "rb")) try: for row in reader: self.buffer.append(row) s,a=[],{} for j in range(len(self.buffer[0])): a[self.buffer[0][j]]=row[j] self.bufferp.append(a) i+=1 self.total = i-1 except csv.Error, e: sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) except IOError, e: sys.exit('file %s, IOError: %s' % (filename, e)) self.soc.me_him(['EXIT:',__name__],self.func_me_color) def index(self, index): """return line for index""" self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.soc.me_him(['RETURN:',self.buffer[int(index)],__name__],self.func_me_color) return self.buffer[int(index)] def total(self): """return total number of lines in csv file""" self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.soc.me_him(['RETURN:',self.total,__name__],self.func_me_color) return self.total def header(self): """return csv header == line 0""" self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.soc.me_him(['RETURN:',self.buffer[0],__name__],self.func_me_color) return self.buffer[0] def find_and_replace(self,li,fi,re): """ find and replace a string inside a string, return list find_and_replace(list,find,replace) """ this=[] for l in li: # found_index=string.find(l,fi) this.append(l.replace(fi,re)) return this def return_buffer(self): self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.soc.me_him(['RETURN:',self.buffer,__name__],self.func_me_color) return self.buffer if __name__ == "__main__": if len(sys.argv) < 1: print "Usage: %s file"% sys.argv[0] f=sys.argv[1] c=csv_parser(f) print c.bufferp -- ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at cheimes.de Mon Dec 22 14:02:58 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 22 Dec 2008 20:02:58 +0100 Subject: I always wonder ... In-Reply-To: <18767.54282.188749.522233@montanaro-dyndns-org.local> References: <18767.54282.188749.522233@montanaro-dyndns-org.local> Message-ID: skip at pobox.com schrieb: > .... shouldn't people who spend all their time trolling be doing something > else: studying, working, writing patches which solve the problems they > perceive to exist in the troll subject? Is there some online troll game > running where the players earn points for generating responses to their > posts? Don't worry about the trolling, Skip. I'd be more worried if nobody trolls about Python. It would mean Python loses popularity and our work is all in vain. Prepare yourself for the worst, Christmas holidays are near! The fading day light usually increased the amount of troll posts. Christian From sjmachin at lexicon.net Fri Dec 26 22:22:09 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 26 Dec 2008 19:22:09 -0800 (PST) Subject: math.sqrt() in new 3.0 version : solution in input() References: Message-ID: On Dec 27, 1:34?pm, David Lemper wrote: > > Problem is the new input() function. Yields a string. > > Thanks to Scott, Chris, Gabriel & John. > > Some thought I was not using the Python 3 command line. > I was : ?Python 3.0 (r30:67507... > Erratic behavior was that I was sometimes using n = input() > and sometimes entering the integer directly into the > math.sqrt() function, eg s = math.sqrt(4194304) > > I cannot find a mention of this in "The Python Tutorial > release 3.1" ? The I&O section discusses output formatting > and reading & writing text files. Yes, it's not in the Tutorial. But you must have found out about its existence somewhere ... 2.x manuals? > John pointed out its in Guido's "What's New in Python3.0" > Indeed its mentioned in PEP 3111, near end of What's New > and somewhat obscurely. " raw_input() was renamed to input(). > That is the new input() function function reads a line from > sys.stdin . . ." ? ? ? ? ? ? ? ? ? ? ? ? ? If you are sticking to 3.0, then you're not in the target audience for "What's New in Python3.0". Just read the docs on the input function: http://docs.python.org/3.0/library/functions.html#input or use help() at the interactive prompt: Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> help(input) Help on built-in function input in module builtins: input(...) input([prompt]) -> string Read a string from standard input. The trailing newline is stripped. [snip] HTH, John From duncan.booth at invalid.invalid Wed Dec 10 14:43:23 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Dec 2008 19:43:23 GMT Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: Tim Chase wrote: > [nibbling a little flame-bait] > >> Python is even slower than PHP! >> >> Just go to any Python website and you will know. >> An example is: >> http://www2.ljworld.com/ > > I'm not sure I'm seeing what you're seeing -- the dynamic page > loaded in under 2 seconds -- about on par with sun.com, > python.org, php.net or msn.com all being pulled from non-cached > servers. You sure you're not mistaking your bandwidth and/or > browser-rendering slowness for Python-as-a-web-server slowness? > For another example try http://www.novell.com. That's a Plone site which gets a lot of visitors and isn't noticeably slow. From kyrie at uh.cu Wed Dec 10 10:40:19 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Wed, 10 Dec 2008 10:40:19 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: <1228923619.493fe2e3c3073@comuh.uh.cu> Quoting Rasmus Fogh : > Rhamphoryncus wrote: > > You grossly overvalue using the "in" operator on lists. > > Maybe. But there is more to it than just 'in'. If you do: > >>> c = numpy.zeros((2,)) > >>> ll = [1, c, 3.] > then the following all throw errors: > 3 in ll, 3 not in ll, ll.index(3), ll.count(3), ll.remove(3) > c in ll, c not in ll, ll.index(c), ll.count(c), ll.remove(c) > > Note how the presence of c in the list makes it behave wrong for 3 as > well. I think I lost the first messages on this thread, but... Wouldn't be easier to just fix numpy? I see no need to have the == return anything but a boolean, at least on Numpy's case. The syntax 'a == b' is an equality test, not a detailed summary of why they may be different, and (a==b).all() makes no little sense to read unless you know beforehad that a and b are numpy arrays. When I'm comparing normal objects, I do not expect (nor should I) the == operator to return an attribute-by-attribute summary of what was equal and what wasn't. Why is numpy's == overloaded in such a counter intuitive way? I realize that an elementwise comparison makes a lot of sense, but it could have been done instead with a.compare_with(b) (or even better, a.compare_with(b, epsilon=e)). No unexpected breakage, and you have the chance of specifying when you consider two elements to be equal - very useful. Even the transition itself could be done without breaking much code... Make the == op return an object that wraps the array of bools (instead of the array itself), give it the any() and all() methods, and make __nonzero__/__bool__ equivalent to all(). -- Luis Zarrabeitia Facultad de Matem?tica y Computaci?n, UH http://profesores.matcom.uh.cu/~kyrie From gagsl-py2 at yahoo.com.ar Mon Dec 29 01:15:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Dec 2008 04:15:56 -0200 Subject: /kolab/bin/python: double free or corruption (fasttop) References: <78edebdd-030f-4517-b9ed-5225511724d7@t39g2000prh.googlegroups.com> Message-ID: En Mon, 29 Dec 2008 04:12:02 -0200, Gabriel Genellina escribi?: > En Sun, 28 Dec 2008 12:10:06 -0200, aspineux > escribi?: > >> I got this. >> This is a test script, to help me to understand why I have unexpected >> result in application. >> But I got a more unexpected result, and probably wrong error message >> about the read-only cursor. > >> def server(): >> dbenv, db=init_db(read_only=False) >> >> update_thread=threading.Thread(target=lambda : cleanup(db)) >> update_thread.setDaemon(True) >> update_thread.start() > > I'd write it as > update_thread = threading.Thread(target=cleanup, args=(db,)) > or: > update_thread = threading.Thread(target=lambda db=db: cleanup(db)) > > The original code is creating a closure and I'm unsure how closures > interact with threads. Anyway, the crash should not happen, this may be a bug in Python or bsddb: http://bugs.python.org/ -- Gabriel Genellina From martin.hellwig at dcuktec.org Wed Dec 3 17:04:58 2008 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 03 Dec 2008 22:04:58 +0000 Subject: "as" keyword woes In-Reply-To: <493701f0$0$194$e4fe514c@news.xs4all.nl> References: <493701f0$0$194$e4fe514c@news.xs4all.nl> Message-ID: <4937028a$0$194$e4fe514c@news.xs4all.nl> Martin P. Hellwig wrote: > Warren DeLano wrote: >> A bottom line / pragmatic question... hopefully not a FAQ. >> >> Why was it necessary to make "as" a reserved keyword? > > Because it can be used at the import statement to let the imported thing > be known under another name? > Something like: > > >>> import xml.etree.ElementTree as ET > Sorry forget about the post, you know full well why not :-) -- mph From tino at wildenhain.de Thu Dec 18 09:14:34 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Thu, 18 Dec 2008 15:14:34 +0100 Subject: confused about __str__ vs. __repr__ In-Reply-To: References: Message-ID: <494A5ACA.8060205@wildenhain.de> Neal Becker wrote: > Reading some FAQ, I see that __str__ is "meant for human eyes". > > But it seems that: > class X(object): > def __str__(self): > return "str" > def __repr__(self): > return "repr" > > x = X() > d = {0 : x} > print d > {0: repr} > > So if __str__ is "meant for human eyes", then why isn't print using it! it is: > print x str but dict just uses repr() for all its childs to print. T. -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From tino at wildenhain.de Fri Dec 26 10:43:27 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Fri, 26 Dec 2008 16:43:27 +0100 Subject: =?ISO-8859-1?Q?Can=B4t_Surf_Python_Pages_in_Windoz?= =?ISO-8859-1?Q?e?= In-Reply-To: <4dc0cfea0812260701q6baf0ccbj154c5b3fa2281cdb@mail.gmail.com> References: <4dc0cfea0812260701q6baf0ccbj154c5b3fa2281cdb@mail.gmail.com> Message-ID: <4954FB9F.5050702@wildenhain.de> hi, Victor Subervi wrote: > Hi; > > I try to surf to this code in Windoze and it doesn't work...just posts a > small, black screen for a split second. Why? I don't know what "surf this code" means (or what Windoze should be) > print "Content-Type: text/html" > print > print """ > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> > > > > > Yeah > > """ this could be fine if called in CGI context. > Also, Zope is installed, but when I go to: > localhost:8080/manage_main > or > local:8080/Zope-Instance/manage_main > I get a 404, after having started the service and everything is go. I > have Python up. What gives? Don't know what "gives" but how did you make sure Zope could really start and bind the port? There are a lot things which could go wrong: Applications using this port already, firewall in your way... a 404 however indicates the service is there but you are not authorized. Please read "User and Permission" chapter in the zope book. Please note the above code you cited is not useable (or sensible) in a zope environment. Happy coding Tino > Victor > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From gagsl-py2 at yahoo.com.ar Tue Dec 30 19:00:24 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Dec 2008 22:00:24 -0200 Subject: Triple quoted string in exec function ? References: <495A253B.6010003@gmail.com> <495A81A7.8030507@gmail.com> Message-ID: En Tue, 30 Dec 2008 18:16:39 -0200, Stef Mientki escribi?: > ibpet11 at gmail.com wrote: >> the message Steven sent you is ok to explain how to work with triple >> quote >> > Yes, but not to work around my problem. > I guess I've to remove all triple quoted strings from my code. Why so? You only have to avoid repeating the *same* kind of triple quotes inside a triple quoted string literal. But you are free to use any other combination of ' and ", even include the surrounding triple quotes escape inside (escaping them with \) >>> x = """This is line 'one'. ... ''line "two" starts '''here ... and this is line three'' ... this last line contains \"\"\" too""" >>> print x This is line 'one'. ''line "two" starts '''here and this is line three'' this last line contains """ too With so much freedom I can't imagine what prevents you from using triple quoted strings. -- Gabriel Genellina From roy at panix.com Sat Dec 6 23:07:10 2008 From: roy at panix.com (Roy Smith) Date: Sat, 06 Dec 2008 23:07:10 -0500 Subject: Learning Python now coming from Perl References: <014a96e0$0$20670$c3e8da3@news.astraweb.com> Message-ID: In article , "Python Nutter" wrote: > At least if you push REs inform the readers where to get the a RE GUI > builder written in Python so they can build and *test* the complex and > unwieldy REs to perform anything beyond the basic pattern searches. Oh, my, I think my brain's about to explode. A RE GUI builder? Cough, gasp, sputter. This is literally the first time I've ever heard of such a thing, and it's leaving a bad taste in my mouth. RE is the last bastion of Real Programmers. Real Programmers don't use GUI builders. Using a GUI to build an RE is like trying to program by pushing little UMLish things around with a mouse. It's Just Wrong. From wuwei23 at gmail.com Tue Dec 2 10:10:22 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 2 Dec 2008 07:10:22 -0800 (PST) Subject: Checking a string against multiple matches References: <99a3a677-a38d-40f5-9a94-a98865150b69@k19g2000yqg.googlegroups.com> <200af09b-adba-4d8f-9ed9-2343030f9718@i24g2000prf.googlegroups.com> <376e669e-20b8-4734-a01e-e7a739362f8a@d23g2000yqc.googlegroups.com> Message-ID: <56eb7ee1-2801-4d7d-9e8e-af2bd5065c89@t39g2000prh.googlegroups.com> On Dec 2, 10:09?pm, Chris wrote: > On Dec 2, 3:01?am, alex23 wrote: > > The only time I'd expect it to do partial matches is if you were doing > > string.index(string), rather than list.index(string): > It would if the OP was iterating over the list and checking that item > with .index so it uses the string.index instead of list.index Which is what I was implying when I wrote "The only time I'd expect it to do partial matches is if you were doing string.index(string), rather than list.index(string)", oddly enough :) From grahn+nntp at snipabacken.se Mon Dec 8 16:47:27 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 8 Dec 2008 21:47:27 GMT Subject: how to get a beep, OS independent ? References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> <6q25utFa7km1U1@mid.uni-berlin.de> Message-ID: On 7 Dec 2008 14:46:53 GMT, Marc 'BlackJack' Rintsch wrote: > On Sun, 07 Dec 2008 07:17:30 -0700, Joe Strout wrote: > >> But invoking the standard system beep is such a basic function that it >> ought to be easier than this. I'm pretty sure it's a single OS call on >> all platforms. On OS X, for example, it's >> >> void NSBeep(void); >> >> declared in NSGraphics.h. I'm sure it's something similarly simple on >> other platforms. > > I'm not so sure. Under Unix the "system beep" is usually in the terminal > emulation and triggered by sending '\a' to it. Yes, and a terminal which prints a control character instead of beeping or flashing the screen, that's highly unusual. I think the poster tested this in some IDE with an "output window" rather than a real terminal. > AFAIK there is no standard beep in X-Windows There is, actually. It's called the bell, and it can be somewhat configured using xset(1). It's the single sound you can squeeze of a standard X server, and it's obviously modeled after the terminal bell. > so every desktop environment implements > something like audio notifications. KDE and Gnome might, but mine doesn't. Things vary so much on Unix. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From esgameserver at gmail.com Thu Dec 4 02:23:57 2008 From: esgameserver at gmail.com (esgameserver at gmail.com) Date: Wed, 3 Dec 2008 23:23:57 -0800 (PST) Subject: Python Dynamic Profiling Message-ID: Hi, Sorry for re-posting but I want to clarify my question again here. So, we have a multithreaded server application and I want to see the profile of our code means which function is executed how many times and time spent in that function dynamically. With dynamic, I mean without stopping the profiled thread. Is there any way to do that, other than hacking my own code with hooks and calculating the info above by hand? P.S:cProfile and Profile modules are very good indeed, but as far as I understand you need to stop the profiler and the associated thread to see the profile results. That is unacceptable for my situation. Thanks, From timr at probo.com Wed Dec 31 02:31:11 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 31 Dec 2008 07:31:11 GMT Subject: Cheetah References: Message-ID: sopherfish at gmail.com wrote: > >1. In Cheetah 2.0.1, both from python 2.5.2 and 2.6, after I do a >#from datetime import date, most of the datetime objects seem to work >fine. For example, $date(2008, 12, 15) works. However $date.today() >does not work and I get an exception required argument year not found. >In Python both 2.5.2 and 2.6 (without Cheetah), the today() works >fine. For some reason, though, it does not work from Cheetah. Show us the EXACT code and the EXACT error. >2. In reportlab 2.2, when I generate a PDF, no matter how many  s >I put it, I only get one space. I am using it with python 2.6. The PDF >generates fine and one $nbsp works, but for some reason, when I put it >in multiple times, I still only get one space. Well, you've spelled it two ways here, and neither way is correct. It's spelled   with an ampersand before and a semicolon after. Again, show us a complete, runnable example and we can check it out. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From stefan_ml at behnel.de Sun Dec 7 02:51:11 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 07 Dec 2008 08:51:11 +0100 Subject: Don't you just love writing this sort of thing :) In-Reply-To: References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: <493b806f$0$31336$9b4e6d93@newsspool4.arcor-online.net> Lawrence D'Oliveiro wrote: > In message , Arnaud Delobelle wrote: > >> * you seem to disregard the fact that in 'programming language' there >> is the word 'language'. A language is a way to _communicate_ >> information, in the case of a programming language you communicate >> it to the computer but also to other human beings. > > It was Niklaus Wirth, I think who pointed out that programming languages are > not properly "languages" but are actually "notations". Like mathematics is > a notation. > > And mathematics, too, is a predominantly functional, not a procedural, > notation. Could that be why so many people are frightened of functional > constructs, like my code example and things like lambdas? Because they look > too much like mathematics? That's not the impression I got from reading this thread. Stefan From sjmachin at lexicon.net Thu Dec 25 08:21:03 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 25 Dec 2008 05:21:03 -0800 (PST) Subject: SyntaxError: encoding problem: with BOM References: <6res8tF1do1sU1@mid.uni-berlin.de> <400f176b-bd9a-4f26-b01b-1aa7c7dcf5ac@z6g2000pre.googlegroups.com> <6rf6m1F1e0f8U1@mid.uni-berlin.de> Message-ID: On Dec 25, 11:36?pm, NoName wrote: > On 25 ???, 03:35, "Diez B. Roggisch" wrote: > > > > > NoName schrieb: > > > > On 25 ???, 00:37, "Diez B. Roggisch" wrote: > > >> NoName schrieb: > > > >>> i have 1.py in cp866 encoding: > > >>> # -*- coding: cp866 -*- > > >>> print ("ff") > > >>> It's not work in Python 3.0 > > >>> Error: > > >>> File "", line 1 > > >>> SyntaxError: encoding problem: with BOM > > >>> what's wrong? > > >> I can only guess, but just because you write the coding-header that > > >> doesn't mean that the editor you use does actually *use* that encoding. > > >> What I presume it does is to use utf-8, and write that stupid BOM > > >> microsoft uses for denoting utf-8-content as first byte. Try using a > > >> different editor, or alter it's settings to really use your desired > > >> encoding. > > > >> Diez > > > > I used Far Manager editor. and it *really* used cp866 > > > I can print hex dump of source file. > > > I don't want to use UTF-8 for py-file! > > > How about you show us the python file in question? > > > diez > > you can get it here http://slil.ru/26481345 NoName, Asking people to download a zip file from a website written in a language and character set that they probably are not familiar with is liable to make them rather nervous and not bother. It's not a good way to ask for help. All you had to do was display the file contents unambiguously, like this: C:\downloads>\python30\python Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> open('11.py', 'rb').read() b"# -*- coding: cp866 -*- \r\nprint('test')" >>> ^Z So, there's nothing very remarkable there ... a trailing space on the end of the first line, the second line is not terminated by \r\n, no non-ASCII characters in the file, ... nothing that might cause Python to give you a syntax error. ... and it doesn't give a syntax error: C:\downloads>\python30\python 11.py test If you still maintain that you are getting the syntax error mentioned in your first posting, please construct a file that causes the error to happen on your machine (what type of machine? what OS are you using?) and show (like I did above) firstly what is in the file and secondly what happens when you run it. No hex editors, no websites, no zip files, just plain Python like I did. From martin at v.loewis.de Sun Dec 14 18:42:05 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 15 Dec 2008 00:42:05 +0100 Subject: Python 3.0 crashes displaying Unicode at interactive prompt In-Reply-To: <89022013-f7f6-4779-849f-b36fe618104e@r15g2000prh.googlegroups.com> References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> <49443531.5050304@v.loewis.de> <49448FC2.6030306@v.loewis.de> <494576DD.1050505@v.loewis.de> <89022013-f7f6-4779-849f-b36fe618104e@r15g2000prh.googlegroups.com> Message-ID: <494599CD.3030408@v.loewis.de> > It's unfortunate that the default behaviour isn't > optimal at the interactive prompt for some configurations, though. As I said, it's a trade-off. The alternative, if it was the default, wouldn't be optimal at the interactive prompt for some other configurations. In particular, users of non-latin scripts have been complaining that they can't read their strings - hence the change, which now actually allows these users to read the text that is stored in the strings. The question really is why John Machin has a string that contains '\u9876' (which is a Chinese character), yet his terminal is incapable of displaying that character. More likely, people will typically encounter only characters in their data that their terminals are also capable of displaying (or else the terminal would be pretty useless) In the long run, it might be useful to have an error handler on sys.stdout in interactive mode, which escapes characters that cannot be encoded (perhaps in a different color, if the terminal supports colors, to make it clear that it is an escape sequence) Regards, Martin From mal at egenix.com Thu Dec 18 18:02:29 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 19 Dec 2008 00:02:29 +0100 Subject: psycopg2 and large queries In-Reply-To: <494AC077.2060605@shopzeus.com> References: <762eed9d-4646-4c62-a9b7-d57d47f03b9e@e1g2000pra.googlegroups.com> <494AC077.2060605@shopzeus.com> Message-ID: <494AD685.7010009@egenix.com> On 2008-12-18 22:28, Laszlo Nagy wrote: > >> Well, there are plenty of PostgreSQL modules around these days, and >> even if pyPgSQL isn't suitable, I'm sure that there must be one which >> can be made to work on Windows and to support server-side cursors. See >> here for more: >> >> http://wiki.python.org/moin/PostgreSQL >> > I'm just looking for something that can replace psycopg2, because of the > bug mentioned in my original post. Here are my options: > > - psycopg1: development stalled > - psycopg2: memory bug and/or not db api compilant (see my original post) > - pyPgSQL: looks like that the last release was in mid 2006 (and it > depends on mxDateTime -> licensing problems) mxDateTime is open-source, just like everything you find in our eGenix mx Base distribution: http://www.egenix.com/products/python/mxBase/ mxODBC and mxODBC Connect are commercial products, work well with PostgreSQL and are actively maintained: http://www.egenix.com/products/python/ Why not give them a try ? -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 18 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-12-02: Released mxODBC.Connect 1.0.0 http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From stef.mientki at gmail.com Fri Dec 26 08:05:15 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 26 Dec 2008 14:05:15 +0100 Subject: Is there a function to remove escape characters from a string ? In-Reply-To: References: <0163882f$0$6988$c3e8da3@news.astraweb.com> Message-ID: <4954D68B.5080900@gmail.com> >> I have the following kind of strings, >> the funny "?" is ASCII character 254, used as a separator character >> > > ASCII ends at 127. Just refer to it as chr(254). > > note 1) >> [FSM] >> Counts = "1?11?16" ==> 1,11,16 >> Init1 = "1?\BCtrl" ==> 1,Ctrl >> State5 = "8?\BJUMP_COMPL\b\n>PCWrite = 1\n>PCSource = 10" >> ==> 8, JUMP_COMPL\n>PCWrite = 1\n>PCSource = 10 >> > > After making those substitutions, what are you going to do with it? > Split it up into fields using the csv module or stuff.split(",") or > some other DIY method? Is there a possibility that whoever "designed" > that data format used chr(254) as a separator because the data fields > contained "," sometimes and so "," could not be used as a separator? > > Yep, chr(254), because it's not in the human range of characters and it's accepted by windows ini-files. >> Seeing and testing all your answers, with great solutions that I've >> never seen before, >> > > As far as str methods and built-ins that work on str objects are > concerned, there is no corpus of secret knowledge known only to a > cabal of wizards; it's all in the manual, and you don't need special > magical spectacles to see it :-) > > note 2) >> knowing nothing of escape sequences (I'm a windows guy ;-) >> > > Why do you think that whether or not you are a "windows guy" is > relevant to knowing anything about escape sequences? > > Just a windows guy, or maybe better, "being a windows guy for many years", windows users are wysiwyg users, they are not dealing with individual bits. I personally left escape sequences and values of ASCII characters behind me more than 25 years ago. And now maybe you might understand note 1) and note 2) . cheers, Stef From Lie.1296 at gmail.com Sun Dec 7 01:17:12 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 6 Dec 2008 22:17:12 -0800 (PST) Subject: Guido's new method definition idea References: <493abe2e$0$15998$426a34cc@news.free.fr> Message-ID: <62bcfe49-bee6-4348-8ec9-8ab85132c8ff@40g2000prx.googlegroups.com> On Dec 7, 1:02?am, News123 wrote: > What would be interesting would be some syntactical sugar to get rid of > the 'self' (at least in the code body). > > example: > class C: > ? ? class_elements a,b,c,d > > ? ? def method(self,arg): > ? ? ? ? global d > ? ? ? ? a,b,c = arg[0..3] > ? ? ? ? d = a + b > ? ? ? ? self.e = a + d > Nah, that would make it not explicit. Explicit here also means that to refer to self's a, we need to explicitly refer to self. From cjw at ncf.ca Fri Dec 19 19:38:33 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Fri, 19 Dec 2008 19:38:33 -0500 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <6r25ckFejl4vU1@mid.individual.net> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> <6r25ckFejl4vU1@mid.individual.net> Message-ID: Thomas Heller wrote: > Steve Holden schrieb: >> Thomas Heller wrote: >>> Question from a non-native english speaker: is this now valid english? >>> >>> "One of Python???s great strengths" >>> ^ >>> "and also teaches Python???s functional programming features" >>> ^ >>> "The book???s approach is wholly practical" >>> ^ >> It always has been valid English. The apostrophe is only omitted from >> personal pronouns (hers, its, and so on). > > I see, thanks. But, is the apostrophe optional in the above fragments? > > Thomas Whoops. I read the first two lines as one sentence. Thomas Heller was questioning the possessive. I don't see any problem with the three examples he gives. Colin W. From invalid at invalid Tue Dec 16 10:43:38 2008 From: invalid at invalid (Grant Edwards) Date: Tue, 16 Dec 2008 09:43:38 -0600 Subject: alt.possessive.its.has.no.apostrophe References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> <9ImdneOohuZCNdvUnZ2dnUVZ_s3inZ2d@earthlink.com> Message-ID: On 2008-12-16, Hendrik van Rooyen wrote: > "Dennis Lee Bieber" wrote: > > 8<----- stuff blaming Davy for "aluminum" ---------- > >> Isn't Davy a Brit? > > No, he was a Brit. > He's dead now. > His safety lamp lives on. > It's a good thing its got that heat-sink sieve- should be "it's got" (contracted form of "it has got"). > it's enabled countless miners > to flee when they see its change of colour. > Thus it's saved the lives of a lot of canaries, > and that's of ecological importance. > > Spot the apostrophe error, if you can. -- Grant Edwards grante Yow! RHAPSODY in Glue! at visi.com From clp at rebertia.com Mon Dec 1 16:21:31 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 1 Dec 2008 13:21:31 -0800 Subject: Is it safe to modify the dict returned by vars() or locals() In-Reply-To: <4934508b$0$2861$ba620e4c@news.skynet.be> References: <4934508b$0$2861$ba620e4c@news.skynet.be> Message-ID: <47c890dc0812011321h66f4309cya7a750b169d994ca@mail.gmail.com> On Mon, Dec 1, 2008 at 1:01 PM, Helmut Jarausch wrote: > Hi, > > I am looking for an elegant way to solve the following problem: > > Within a function > > def Foo(**parms) > > I have a list of names, say VList=['A','B','C1'] > and I like to generate abbreviation > _A identical to parms['A'] Could you explain what you mean by that? Your sample code doesn't seem to do any "abbreviation"... Otherwise I don't see why you don't just have a proper parameter list. > > for that I could write > > def Foo(**parms) : > for N in VList : > if N in parms : > vars()[N]= parms[N] > else : > vars()[N]= None > > Does this work, is it typical Python? >From the docs (http://docs.python.org/library/functions.html): locals() Update and return a dictionary representing the current local symbol table. *Warning*: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter. Free variables are returned by locals() when it is called in a function block. Modifications of free variables may not affect the values used by the interpreter. Free variables are not returned in class blocks. As the warning states, it modifying the dict doesn't really work (except at the module level, but that's an implementation detail IIRC) For example: >>> def foo(): ... a = 3 ... l = locals() ... l['a'] = 5 ... print a ... >>> foo() 3 In any case, it'd be considered a bit of a hack. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Many thanks for a hint, > Helmut. > > -- > Helmut Jarausch > > Lehrstuhl fuer Numerische Mathematik > RWTH - Aachen University > D 52056 Aachen, Germany > -- > http://mail.python.org/mailman/listinfo/python-list > From ibpet11 at gmail.com Tue Dec 30 05:37:46 2008 From: ibpet11 at gmail.com (ibpet11 at gmail.com) Date: Tue, 30 Dec 2008 02:37:46 -0800 (PST) Subject: using def in pythons Message-ID: <235ffe4b-9f36-4d41-bee8-24cb4a69728d@q30g2000prq.googlegroups.com> hi, i want to have a broad knowledge on the use of "def" in python as i know i might need it to my string handling and for a lot of things in general. I will really appreciate anybody who can support my mission of becoming a python Programmer as per constant chatting and support or manuals to read. thanks From prologic at shortcircuit.net.au Sun Dec 14 04:23:49 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Sun, 14 Dec 2008 19:23:49 +1000 Subject: XMPP xmpppy - User Authorization In-Reply-To: <66b3831b-b26d-4ce9-80b2-e0e8c85ecbc4@k9g2000vbl.googlegroups.com> References: <66b3831b-b26d-4ce9-80b2-e0e8c85ecbc4@k9g2000vbl.googlegroups.com> Message-ID: On Sun, Dec 14, 2008 at 3:47 PM, Henson wrote: > In my own bot, using the latest xmpppy, I've been printing everything > going to the message handler to the screen. I've yet to see a > 'subscribe' string. Has this changed? No this hasn't changed. This is the string you need to check for. It does work :) cheers James > -- -- "Problems are solved by method" From christophedeze at gmail.com Mon Dec 22 11:22:51 2008 From: christophedeze at gmail.com (Toff) Date: Mon, 22 Dec 2008 08:22:51 -0800 (PST) Subject: join a samba domain References: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> Message-ID: <5428c77b-ed4f-49ec-a808-dccd77a2a01c@g3g2000pre.googlegroups.com> On 22 d?c, 17:02, Tim Golden wrote: > Toff wrote: > > hi, > > > I 'm trying to write a script to make my computer join a samba. > > > domeone have any idea ?? > > Ummm. It's not clear if you're saying that your code doesn't > work, or asking for general advice, or what? I'm not in a > position to have my machine join a domain or workgroup, but > you seem to have got most things in place already. The only > thing I would expect to have to change is this last line: > > > ? ?import wmi > > ? ?c = wmi.WMI() > > ? ?d = c.Win32_ComputerSystem > > ? ?d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") > > because the d is only a WMI *class*, not a WMI *instance*, > so doesn't refer as it should to your computer system but > to the class of computer systems. Try something like this (untested): > > > import wmi > > c = wmi.WMI () > for d in c.Win32_ComputerSystem (): > ? d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") > > > > TJG thanks but it doesn't work I've got this errors Traceback (most recent call last): File "integrdom.py", line 51, in main() File "integrdom.py", line 13, in main joindom() File "integrdom.py", line 44, in joindom d.JoinDomainOrWorkGroup(None, 3, "domcd", "adminLocal", r"admin \domcd") File "c:\Python25\Lib\site-packages\wmi.py", line 493, in __getattr__ handle_com_error (error_info) File "c:\Python25\Lib\site-packages\wmi.py", line 189, in handle_com_error raise x_wmi, "\n".join (exception_string) wmi.x_wmi From martin at v.loewis.de Sun Dec 7 04:20:14 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 07 Dec 2008 10:20:14 +0100 Subject: Number of Python 3.x packages at the PyPI In-Reply-To: <9c1ab0f3-6686-4c0f-8a6c-12e20539f354@41g2000yqf.googlegroups.com> References: <9c1ab0f3-6686-4c0f-8a6c-12e20539f354@41g2000yqf.googlegroups.com> Message-ID: <493b954e$0$4021$9b622d9e@news.freenet.de> excord80 at gmail.com wrote: > Is there an easy way to see the number of PyPI packages which have > been ported to Python 3? Yes: browse all pacakges classified with Programming Language :: Python :: 3 You can find them at http://pypi.python.org/pypi?:action=browse&c=533 It seems that some package authors only classify with Programming Language :: Python :: 3 > Are there any special arrangements necessary for PyPI packages which > have both a Python 2.x version and a Python 3.x version? So far, no such need has been identified. Regards, Martin From google at mrabarnett.plus.com Sat Dec 6 11:50:24 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 06 Dec 2008 16:50:24 +0000 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: References: <55d79070-0c11-4fb9-8cf5-b8cc7c54b5d2@v42g2000yqv.googlegroups.com> Message-ID: <493AAD50.4050904@mrabarnett.plus.com> Johannes Bauer wrote: > info at orlans-amo.be schrieb: > >> 2 problems: endianness and trailing zer byte. >> This works for me: > > This is very strange - when using "utf16", endianness should be detected > automatically. When I simply truncate the trailing zero byte, I receive: > > Traceback (most recent call last): > File "./modify.py", line 12, in > a = AddressBook("2008_11_05_Handy_Backup.txt") > File "./modify.py", line 7, in __init__ > line = f.readline() > File "/usr/local/lib/python3.0/io.py", line 1807, in readline > while self._read_chunk(): > File "/usr/local/lib/python3.0/io.py", line 1556, in _read_chunk > self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) > File "/usr/local/lib/python3.0/io.py", line 1293, in decode > output = self.decoder.decode(input, final=final) > File "/usr/local/lib/python3.0/codecs.py", line 300, in decode > (result, consumed) = self._buffer_decode(data, self.errors, final) > File "/usr/local/lib/python3.0/encodings/utf_16.py", line 69, in > _buffer_decode > return self.decoder(input, self.errors, final) > UnicodeDecodeError: 'utf16' codec can't decode byte 0x0a in position 0: > truncated data > > But I suppose something *is* indeed weird because the file I uploaded > and which did not yield the "truncated data" error ia 1559 bytes, which > just cannot be. > It might be that the EOF marker (b'\x1A' or u'\u001A') was written or is being read as a single byte instead of 2 bytes for UTF-16 text. From bearophileHUGS at lycos.com Tue Dec 16 12:28:09 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 16 Dec 2008 09:28:09 -0800 (PST) Subject: Does Python3 offer a FrozenDict? References: Message-ID: Johannes Bauer: > is there anything like a frozen dict in Python3, so I could do a > foo = { FrozenDict({"a" : "b"}): 3 } You can adapt this code to Python3 (and post a new recipe? It may be positive to create a new section of the Cookbook for Py3 only): http://code.activestate.com/recipes/414283/ Please remember that Py3 is very new, so 99% of the stuff present for Py2.x is absent. Using Py3 is your choice. Bye, bearophile From excord80 at gmail.com Sat Dec 6 22:56:10 2008 From: excord80 at gmail.com (excord80 at gmail.com) Date: Sat, 6 Dec 2008 19:56:10 -0800 (PST) Subject: Number of Python 3.x packages at the PyPI Message-ID: <9c1ab0f3-6686-4c0f-8a6c-12e20539f354@41g2000yqf.googlegroups.com> Is there an easy way to see the number of PyPI packages which have been ported to Python 3? Are there any special arrangements necessary for PyPI packages which have both a Python 2.x version and a Python 3.x version? From wodemoneke at gmail.com Sun Dec 14 09:21:16 2008 From: wodemoneke at gmail.com (Daniel Woodhouse) Date: Sun, 14 Dec 2008 16:21:16 +0200 Subject: changing string encoding to different charset? Message-ID: <4c0a037d0812140621j5d4f4d47mb4a3097586bacac5@mail.gmail.com> Is it possible to re-encode a string to a different character set in python? To be more specific, I want to change a text file encoded in windows-1251 to UTF-8. I've tried using string.encode, but get the error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 0: ordinal not in range(128) -------------- next part -------------- An HTML attachment was scrubbed... URL: From fetchinson at googlemail.com Thu Dec 4 12:30:52 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 4 Dec 2008 09:30:52 -0800 Subject: RELEASED Python 3.0 final In-Reply-To: <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> Message-ID: >> As you have probably guessed: nothing changed here. >> Also see:http://www.python.org/dev/peps/pep-0666/ > > What? Do you mean it's possible to mix tabs and spaces still? Why? Why not? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From rdmurray at bitdance.com Tue Dec 16 18:59:31 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Tue, 16 Dec 2008 23:59:31 +0000 (UTC) Subject: eval() and global variables References: Message-ID: Quoth "=?ISO-8859-1?Q?Juan_Pablo_Romero_M=E9ndez?=" : > Hello, > > Suppose this function is given: > > def f(x,y): > return x+y+k > > Is it possible to somehow assign a value to k without resorting to > making k global? > > I'm thinking something like this: > > eval("f(1,1)", {"f":f, "k":1}) > > Or even better, something like: > > def g(k): > return f > > g(1)(1,1) ==> 3 >>> def g(k): ... def f(x,y): ... return x+y+k ... return f ... >>> g(1)(1,1) 3 But what's the use case? The above might not satisfy it. --RDM From rt8396 at gmail.com Mon Dec 22 16:09:13 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 13:09:13 -0800 (PST) Subject: I always wonder ... References: Message-ID: <4b1d5c89-166e-415f-8bb4-b8d5a4089368@h20g2000yqn.googlegroups.com> On Dec 22, 2:31?pm, s... at pobox.com wrote: > ? ? Carl> ...shouldn't poeple who spend all their time following up to > ? ? Carl> trolls, or starting new threads about trolls, being doing > ? ? Carl> something else? > > Sure. ?It was just a momentary break from work, as is this. ?I thought an > implied smiley was enough, but I guess not. > > Skip Pythonic.explicit_smiley() -> :) From rt8396 at gmail.com Mon Dec 22 13:01:21 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 10:01:21 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> Walter, I just look at the stats for comp.lang.python, and i am 9th place for most post this month. That makes me completely sad. With just 50 post so far, i am showing up on the high count. Sad, very sad. Now i have much reason to believe that only 100 or so people follow this list :(. Python is slipping. We must try harder, or all of Guido's work will be for nothing! From martin at v.loewis.de Mon Dec 8 20:08:19 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 09 Dec 2008 02:08:19 +0100 Subject: how to add command line flags to distutils setup script? In-Reply-To: References: Message-ID: <493dc504$0$21190$9b622d9e@news.freenet.de> skip at pobox.com wrote: > Suppose I have a setup.py script which imports distutils.core.setup. Is > there some way to, for example, add a command line flag to the build command > so that I can run it like > > python setup.py build --frob=True > > ? You should inherit from the build command, extend the user_options attribute, and pass the new class as "build" class into the commands dictionary of setup. You might need to extend initialize_options and finalize_options as well. Regards, Martin From xahlee at gmail.com Wed Dec 10 19:51:00 2008 From: xahlee at gmail.com (Xah Lee) Date: Wed, 10 Dec 2008 16:51:00 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> Message-ID: <5ebe5a7d-cbdf-4d66-a816-a7d2a0a273c9@40g2000prx.googlegroups.com> On Dec 10, 2:47?pm, John W Kennedy wrote: > Xah Lee wrote: > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, > > you'll have 50 or hundreds lines. > > C: > > #include > #include > > void normal(int dim, float* x, float* a) { > ? ? float sum = 0.0f; > ? ? int i; > ? ? float divisor; > ? ? for (i = 0; i < dim; ++i) sum += x[i] * x[i]; > ? ? divisor = sqrt(sum); > ? ? for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; > > } > > Java: > > static float[] normal(final float[] x) { > ? ? float sum = 0.0f; > ? ? for (int i = 0; i < x.length; ++i) sum += x[i] * x[i]; > ? ? final float divisor = (float) Math.sqrt(sum); > ? ? float[] a = new float[x.length]; > ? ? for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor; > ? ? return a; > > } Thanks to various replies. I've now gather code solutions in ruby, python, C, Java, here: ? A Example of Mathematica's Expressiveness http://xahlee.org/UnixResource_dir/writ/Mathematica_expressiveness.html now lacking is perl, elisp, which i can do well in a condensed way. It'd be interesting also to have javascript... and perhaps erlang, OCaml/F#, Haskell too. Xah ? http://xahlee.org/ ? From castironpi at gmail.com Tue Dec 16 15:17:09 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 16 Dec 2008 12:17:09 -0800 (PST) Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> Message-ID: On Dec 16, 4:15?am, "Gabriel Genellina" wrote: > En Tue, 16 Dec 2008 07:29:19 -0200, Aaron Brady ? > escribi?: > > > I have a file handle I want to inherit in a child process. ?I am > > looking at '_make_inheritable' in 'Popen', but it needs an instance, > > and by the time I have one, the subprocess is already running. > > > Can't I call 'Popen._make_inheritable( None, handle )'? ?The method > > does not use 'self'. > > File handles are inherited by default, I think. What's your specific ? > problem? > > -- > Gabriel Genellina I want a dual-console application for some multi-threaded output. The main process spawns a second process in a second window, and directs its readout through a pipe. That is, the second process is just a dummy, print pipe directly to console. It worked when I used the 'stdin= PIPE' keyword in Popen, but passing my own pipe handle on the command line isn't working. The keyword is a workaround. > File handles are inherited by default, I think. I thought so too. The web seems to say that on Linux they are, and on Windows, you need to call DuplicateHandle for it. By the way, there are a few solutions to the inheritance problem. 1. Override __init__ and __del__ in a subclass. 2. Assign DummyClass= Popen._make_inheritable 3. Override Popen._execute_child to call _make_inheritable, then call the super method. From luismgz at gmail.com Thu Dec 11 07:06:19 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Thu, 11 Dec 2008 04:06:19 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: <9e0bb906-e019-45ef-8047-b33982c7c5ad@l39g2000yqn.googlegroups.com> On Dec 10, 3:42?pm, cm_gui wrote: > http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-... > > I fully agree with Krzysztof Kowalczyk . > Can't they build a faster VM for Python since they love the language > so much? > > Python is SLOW. ? ?And I am not comparing it with compiled languages > like C. > Python is even slower than PHP! > > Just go to any Python website and you will know. > An example is:http://www2.ljworld.com/ > And this site is created by the creators of Django! > > And it is not just this Python site that is slow. There are many many > Python sites which are very slow. And please don?t say that it could > be the web hosting or the server which is slow ? because when so many > Python sites are slower than PHP sites, it couldn?t be the web > hosting. ? Also, Zope/Plone is even slower. > > Python is slow. Very slow. Now seriously, just to finish your idiotic rant, check the Pypy project: http://codespeak.net/pypy http://morepypy.blogspot.com And if you still think this is not enough, why don't you help these guys to make it faster? Luis From dullrich at sprynet.com Tue Dec 2 12:13:21 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 02 Dec 2008 11:13:21 -0600 Subject: newbie question References: Message-ID: In article , Nan wrote: > Hello, > I just started to use Python. I wrote the following code and > expected 'main' would be called. > > def main(): > print "hello" > > main > > But I was wrong. I have to use 'main()' to invoke main. The python > interpreter does not give any warnings for the above code. Is there > any way/tool to easily detect this kind of errors ? It's valid Python - it's only an error because it doesn't do what you want. The reason you're required to include the parentheses with a function call is that in Python there are _other_ things you might want to do with a function other than call it. For example you can pass a function as a parameter to another function. Silly example: def twice(f): f() f() def main(): print 'hello' twice(main) Before trying it, figure out what would happen if you said twice(main()) . A slightly more interesting example: twice(f) simply calls f twice. double(f) returns a new function; when you call that new function it calls f twice: def double(f): def res(): f() f() return res def main(): print 'hello' The point being that this example shows how sometimes you want those parentheses and sometimes you don't. Either one of the following is a way to call main twice: mainmain = double(main) mainmain() or double(main)() When I said mainmain = double(main) I left off the final parentheses because I didn't want to call mainmain just then, I just wanted to set mainmain to the right thing. > Thanks ! -- David C. Ullrich From philip at semanchuk.com Mon Dec 8 10:05:52 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Mon, 8 Dec 2008 10:05:52 -0500 Subject: Best way to run multiple Python processes without overloading CPU or disk i/o In-Reply-To: References: <1228278090.29785.1287948757@webmail.messagingengine.com> Message-ID: <2F6BC7BC-5B5F-47DE-B323-99A3DA907999@semanchuk.com> On Dec 8, 2008, at 2:48 AM, Gabriel Genellina wrote: > En Wed, 03 Dec 2008 02:29:32 -0200, Philip Semanchuk > escribi?: > >> >> On Dec 2, 2008, at 11:21 PM, python at bdurham.com wrote: >> >>> Is there a cross-platform way to launch multiple Python processes >>> and monitor CPU usage >> >> os.getloadavg() might be useful. It certainly works on *nix, don't >> know about Windows. The documentation doesn't mention any platform >> limitations. > > ....apart from saying "Availability: Unix."? :) Which just goes to show that Python is improving all the time. That's a fix that's present in the 2.6 documentation. I have 2.5 installed, and "Availability: Unix" is not in that doc: http://www.python.org/doc/2.5/lib/os-path.html#l2h-2791 From tino at wildenhain.de Thu Dec 18 09:36:01 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Thu, 18 Dec 2008 15:36:01 +0100 Subject: confused about __str__ vs. __repr__ In-Reply-To: References: <494A5ACA.8060205@wildenhain.de> Message-ID: <494A5FD1.9050406@wildenhain.de> Neal Becker wrote: ... >>> So if __str__ is "meant for human eyes", then why isn't print using it! >> it is: >> >> > print x >> str >> >> but dict just uses repr() for all its childs to print. >> >> T. > That makes no sense to me. If I call 'print' on a container, why wouldn't it recursively print on the contained objects? Since print means call str, printing a container should recursively call str on the objects. Every class is free on how to best implement __str__, you will find the same behavior on tuple and list as well. Maybe its discussable to change the implementation sensibly, best if you would come with a proposal? Perhaps pprint.pprint is a starting point? Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From jay.amorin at gmail.com Wed Dec 3 13:25:32 2008 From: jay.amorin at gmail.com (Jay Jesus Amorin) Date: Thu, 4 Dec 2008 02:25:32 +0800 Subject: python to parse excel file csv format Message-ID: Hi all, Can anyone please help me. i need to parse the content of my csv excel file and run the unix command chown. test.csv: "/dev/trunk/admin/sql/ADBPOS_CMSI_NATIONALITY.syn",814 "/dev/trunk/bin/ADBPOSCMSDICED.ctl",405 "/dev/trunk/discoverer/ADBPOS_BUSINESS_AREA.eex",215 Please help me parse the csv file and run chown $csvfile_secondcolumn $csvfile_firstcolumn. Here's how i want to run it. ./parsecsv.py test.csv Many thanks. Jay -------------- next part -------------- An HTML attachment was scrubbed... URL: From scottm45810 at hotmail.com Sat Dec 27 17:06:03 2008 From: scottm45810 at hotmail.com (scott) Date: Sat, 27 Dec 2008 14:06:03 -0800 Subject: Python 3 and my Mac (Leopard) In-Reply-To: <4952b38d$0$20300$607ed4bc@cv.net> References: <4952b38d$0$20300$607ed4bc@cv.net> Message-ID: Dan wrote: > Wanted to learn python, got Mark Summerfield's new book "Programming in > Python 3". Having a hard time getting python 3 and IDLE working on my > Mac with Leopard. The mac "resources" on the python.org site seem a bit > out of date, and don't really mention python 3. Are there any resources > out there? Is the python community just not interested in Macs? I've > tried googling and the usual search strategies. Any help would be > appreciated. > > DAN > Activestate has a Python 3.0 distribution for 8 or 9 platforms including Mac OS X: http://www.activestate.com/Products/activepython/python3.mhtml IDLE works well here on Leopard (calltips etc) and they have bundled documentation in Apple help format. Note: I installed ActiveTcl prior to installing Python 3.0: http://www.activestate.com/Products/activetcl/index.mhtml I'm not sure if this was necessary for proper IDLE function or not. Both ActivePython 3.0 and ActiveTcl installs were painless. From prologic at shortcircuit.net.au Mon Dec 15 03:35:58 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 15 Dec 2008 18:35:58 +1000 Subject: Python is slow In-Reply-To: <20081215082616.1de76e92@andi-lap> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <20081215082616.1de76e92@andi-lap> Message-ID: On Mon, Dec 15, 2008 at 5:26 PM, Andreas Kostyrka wrote: > So to summarize, Python is fast enough for even demanding stuff, and > when done correctly even number crunching or binary parsing huge files > or possible in competitive speeds. But you sometime need a developer > that can wield the tool with a certain experience, and not a stupid > rookie that whines that his tool does not make his O(n**n) algorithm > automatically blazing fast. Amen! +10 --JamesMills From de.slotenzwemmer at gmail.com Thu Dec 25 07:11:09 2008 From: de.slotenzwemmer at gmail.com (Dennis van Oosterhout) Date: Thu, 25 Dec 2008 13:11:09 +0100 Subject: os.system('cls') In-Reply-To: References: <05BADA85-33ED-48BF-B251-2CC830D6D55E@rgbaz.eu> Message-ID: Btw...does that mean that system('cls') only works on Windows...or to say it otherwise: the program isn't platform independant? 2008/12/25 Dennis van Oosterhout : > Hello Arno, > > thanks for the explanation! I have one more question: on the python > site it says it's better to replace the system commands by subprocess > and Popen. > Now I searched for some good example for my specific case (as I have > no idea how it should work and I don't get it any clearer by reading > http://docs.python.org/3.0/library/subprocess.html#module-subprocess) > and I found this: > >> import subprocess >> def clear(): >> subProcess.Popen('clear') > > But it just doesn't seem to work. Would you have any idea how it would work? > > Once more thanks for the first answer, > > Devilly > > > 2008/12/25 Python >> >> On 25 dec 2008, at 11:22, Dennis van Oosterhout wrote: >> >>> Hi there! I was searching for a way to clear the 'DOS screen'/command screen etc. and found that os.system('cls') works for this. I was just wondering where I can find al the commands which can be used for os.system(). I searched with google but I didn't find an answer. In the official python tutorial it says os.system('command') executes the command, but it doesn't say which commands exist (or I'm just blind). >>> >>> Does anyone have an answer for this question? >>> >>> Thanks, >>> >>> Devilly >> >> Hey Deville, >> >> >> os.system() executes commands that you usually use in a shell outside python. >> so in the case of you being a windows user, you replace 'command' with any DOS >> command. >> >> gr >> Arno > From mareksp.92 at gmail.com Mon Dec 15 12:51:49 2008 From: mareksp.92 at gmail.com (Marek_SP) Date: Mon, 15 Dec 2008 09:51:49 -0800 (PST) Subject: Structure using whitespace vs logical whitespace References: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> Message-ID: <5079101b-d477-4127-b595-1f1eb50740cf@y1g2000pra.googlegroups.com> On 15 Gru, 18:14, MRAB wrote: > cmdrrickhun... at yaho.com wrote: > > I've been trying to search through the years of Python talk to find an > > answer to this, but my Googlefu is weak. > > > In most languages, I'll do something like this > > > xmlWriter.BeginElement("parent"); > > ----xmlWriter.BeginElement("child"); > > ----------xml.Writer.Characters("subtext"); > > ----xmlWriter.EndElement(); > > xmlWriter.EndElement(); > > > Where the dashes are indentation (since some newsgroup handlers don't > > do tabs well). ?XML writing is just an example. > > > In general, I'm using indentation to show logical flow through code. > > Python's choice to give semantic meaning to whitespace prevents me > > from doing such things. ?What was once reserved for logical use is now > > used syntactically. ?In 90% of cases, its not needed, and whitespace > > significance seems to be pretty effective. ?In that last 10%, however, > > I've been frustrated many times. > > > I've been using python for a few years, and gotten around this in one > > way or another, but now I want to get other who work with me to pick > > up Python. ?All newbies to Python have trouble with the idea of > > whitespace sensitivity, but how can I convince them that "it just > > works better" when I have this construct which I want to use but > > can't. > > > Has anybody found a way to emulate this behavior? ?I've often done it > > by opening an expression for the whole thing, but there's a lot of > > tasks where a single expression just isn't sufficient (such as things > > with assignment). > > > PS. In my opinion the solution would be to have the option of entering > > a "whitespace insensitive" mode which uses C style {} and ;. ?The > > token to enter it could be as complicated as you want (in fact, it may > > make sense to make it complicated to discourage use unless it's really > > advantageous). ?I'd sugest {{ and }} or something bigger like {={ } > > =}. ?Only two problems: 1) I'm sure it would offend Guido's sense of > > language aesthetics ?2) I'm sure the idea has been hashed over on this > > newsgroup to death... hence prefering a workaround instead. > > You could use the "with" statement: > > class xml_element(object): > ? ? ?def __init__(self, text): > ? ? ? ? ?self.text = text > ? ? ?def __enter__(self): > ? ? ? ? ?xmlWriter.BeginElement(self.text) > ? ? ?def __exit__(self, *args): > ? ? ? ? ?xmlWriter.EndElement() > > with xml_element("parent"): > ? ? ?with xml_element("child"): > ? ? ? ? ?xmlWriter.Characters("subtext") Yep, I think that's what Guido was thinking about while adding `with` statements. They're great at grouping code logically. Before I used `if True:` to do this but it wasn't good looking. From gagsl-py2 at yahoo.com.ar Wed Dec 24 13:55:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2008 16:55:33 -0200 Subject: String Comparison Testing References: <89f89940812241020l3e814f2dv4479da8d6575f7e7@mail.gmail.com> Message-ID: En Wed, 24 Dec 2008 16:20:17 -0200, Brad Causey escribi?: > I am trying to do some basic log parsing, and well, I am absolutely > floored > at this seemingly simple problem. I am by no means a novice in python, > but > yet this is really stumping me. I have extracted the pertinent code > snippets > and modified them to function as a standalone script. Basically I am > reading > a log file ( in this case, testlog.log) for entries and comparing them to > entries in a safe list (in this case, safelist.lst). I have spent > numerous > hours doing this several ways and this is the most simple way I can come > up > with: I'd say the "\n" at the end of each line is the culprit. > safelist = safelistfh.readlines() safelist = [line.strip() for line in safelistfh] (or just strip('\n') if spaces are important); same for the other list. > def safecheck(line): > for entry in safelist: > print 'I am searching for\n' > print entry > print '\n' > print 'to exist in\n' > print line repr() is your friend when debugging these things: print repr(entry) etc. > comp = line.find(entry) > if comp <> -1: > out = 'Failed' > else: > out = 'Passed' I'd use: if entry in line: ... Are you sure you're interested in the LAST comparison result ONLY? -- Gabriel Genellina From jpablo.romero at gmail.com Tue Dec 9 20:23:30 2008 From: jpablo.romero at gmail.com (=?ISO-8859-1?Q?Juan_Pablo_Romero_M=E9ndez?=) Date: Tue, 9 Dec 2008 19:23:30 -0600 Subject: Compiling and installing python 2.5.2 with Visual C++ 2008 In-Reply-To: References: Message-ID: Thanks! I'm having trouble with msi.py, so I'll better try python 2.6 The problem is with Pivy (openinventor bindings to python), it refuses to compile. It says: --------------------------------------------------------- ... error: Python was built with Visual Studio 2003; extensions must be built with a compiler than can generate compatible binaries. Visual Studio 2003 was not found on this system. If you have Cygwin installed, you can try compiling with MingW32, by passing "-c mingw32" to setup.py. --------------------------------------------------------- And because I've been compiling everything needed by pivy (Coin, Qt, SoQt, PyQt) with visual c++ 8, I decided to recompile python itself. Juan Pablo 2008/12/9 Gabriel Genellina : > En Tue, 09 Dec 2008 11:32:46 -0200, Juan Pablo Romero M?ndez > escribi?: > >> I need to compile python myself because of a module (pivy). So I >> downloaded MS Visual C++ 2008 express edition. It apparently compiled >> fine but I don't know how to install it to recreate the standard >> distribution. In linux i'd take "make install", but on windows? > > See Tools/msi/README.txt > BTW, do you really have to recompile Python? Unless the project requires > some specific compiler flags incompatible with the standard build, usually > there is no need to recompile Python just because of an extension. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > From bearophileHUGS at lycos.com Fri Dec 19 07:26:16 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 19 Dec 2008 04:26:16 -0800 (PST) Subject: List comprehension in if clause of another list comprehension References: Message-ID: <767cee3c-5021-4978-8750-bc5692e6517b@w39g2000prb.googlegroups.com> Peter Otten: > The problem is that list comprehensions do not introduce a new namespace. I think Python3 fixes this bug. Bye, bearophile From joe at strout.net Fri Dec 19 18:50:39 2008 From: joe at strout.net (Joe Strout) Date: Fri, 19 Dec 2008 16:50:39 -0700 Subject: encoding problem In-Reply-To: <6r2nfgFfb5kpU7@mid.uni-berlin.de> References: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> <6r1m72Ffb5kpU3@mid.uni-berlin.de> <6r2hvjFfb5kpU6@mid.uni-berlin.de> <6r2nfgFfb5kpU7@mid.uni-berlin.de> Message-ID: <494C334F.1040408@strout.net> Marc 'BlackJack' Rintsch wrote: >>> I don't see the shortcoming in Python <3.0. If you want real strings >>> with characters instead of just a bunch of bytes simply use `unicode` >>> objects instead of `str`. >> Fair enough -- that certainly is the best policy. But working with any >> other encoding (sometimes necessary when interfacing with any other >> software), it's still a bit of a PITA. > > But it has to be. There is no automagic guessing possible. Automagic guessing isn't possible if strings keep track of what encoding their data is. And why shouldn't they? We're a long way from the day when a "string" was nothing more than an array of bytes. Adding a teeny bit of metadata makes life much easier. >>> And does REALbasic really use byte strings plus an encoding!? >> You betcha! Works like a dream. > > IMHO a strange design decision. I get that you don't grok it, but I think that's because you haven't worked with it. RB added encoding data to its strings years ago, and changed the default string encoding to UTF-8 at about the same time, and life has been delightful since then. The only time you ever have to think about it is when you're importing a string from some unknown source (e.g. a socket), at which point you need to tell RB what encoding it is. From that point on, you can pass that string around, extract substrings, split it into words, concatenate it with other strings, etc., and it all Just Works (tm). In comparison, Python requires a lot more thought on the part of the programmer to keep track of what's what (unless, as you point out, you convert everything into unicode strings as soon as you get them, but that can be a very expensive operation to do on, say, a 500MB UTF-8 text file). > A lot more hassle compared to an opaque > unicode string type which uses some internal encoding that makes > operations like getting a character at a given index easy or > concatenating without the need to reencode. No. RB supports UCS-2 encoding, too, and is smart enough to take advantage of the fixed character width of any encoding when that's what a string happens to be. And no reencoding is used when it's not necessary (e.g., concatenating two strings of the same encoding, or adding an ASCII string to a string using any ASCII superset, such as UTF-8). There's nothing stopping you from converting all your strings to UCS-2 when you get them, if that's your preference. But saying that having only one string type that knows it's Unicode, and another string type that hasn't the foggiest clue how to interpret its data as text, is somehow easier than every string knowing what it is and doing the right thing -- well, that's just silly. Best, - Joe From wolfgang.lipp at gmail.com Fri Dec 12 16:44:32 2008 From: wolfgang.lipp at gmail.com (_wolf) Date: Fri, 12 Dec 2008 13:44:32 -0800 (PST) Subject: forcing future re-import from with an imported module References: <533670ae-6d9d-4b10-9156-e41b31b678c7@g17g2000prg.googlegroups.com> Message-ID: On Dec 11, 12:43 am, rdmur... at bitdance.com wrote: > "Why can't you have the code that is doing the import [...] > call a function [...] to produce [the] side effect [...]? > Explicit is better than implicit. A python programmer is > going to expect that importing a module is idempotent" you?re completely right that `import foo` with side effects may break some expectations, but so do all `from __future__` imports. you?re also right that another solution would be to come in from the other side and explicitly call a function from the importing module. all of this does not answer one question tho: why does deleting a module work most of the time, but not in the case outlined in my first post, above? why do we get to see this slightly strange error message there complaining about ?not finding? a module ?in sys.modules??well, most of the time, when a module is not in that cache, it will be imported, but not in this case. why? cheers & ~flow From mail at timgolden.me.uk Wed Dec 17 08:29:23 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 17 Dec 2008 13:29:23 +0000 Subject: Transferring a file over sockets In-Reply-To: References: Message-ID: <4948FEB3.5020707@timgolden.me.uk> Ferdinand Sousa wrote: > I am using sockets to transfer a file over LAN. There are 2 scripts, the > server opens a listens for connection and the client is run on another > machine. I always make sure the server is run first. The strange thing is > that if the the server script is double-clicked and executed (run in a > console with title %Python path%python.exe) the output file saved on the > server is truncated. It works just fine if you open the server script in > IDLE and then run it. The client script can be run in either way, it still > works. You could try using any arbitrary file to test this behaviour after > changing the file name in both the scripts. A couple of things: * Are you aware that there's no particular guarantee that what's sent along a socket in one write will be received in one read? There's a HOWTO here if you're interested: http://docs.python.org/dev/howto/sockets.html * Also, unless this is an exercise for yourself in investigating how sockets work, (in which case... read the docs :)), you might consider that you're reinventing the wheel not a little. But perhaps you knew that? TJG > > ========================================================== > # file receiver > # work in progress > > import socket > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > HOST = '192.168.1.17' > PORT = 31400 > > s.bind((HOST, PORT)) > s.listen(3) > conn, addr = s.accept() > print 'conn at address',addr > conn.send('READY') > f = open('C:\\Documents and Settings\\USER\\Desktop\\test.pdf','wb') > fsize=int(conn.recv(8)) > print 'File size',fsize > f.write(conn.recv(fsize)) > f.close() > conn.close() > s.close() > > raw_input('Press any key to exit') > > > =========================================================== > > # file sender !!! > # Work in progress > > import socket, os > from stat import ST_SIZE > > > HOST = '192.168.1.17' > PORT = 31400 # Arbitrary non-privileged port > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > s.connect((HOST,PORT)) > if s.recv(5)!='READY': > raw_input('Unable to connect \n\n Press any key to exit ...') > s.close() > exit() > > f=open('C:\\Documents and Settings\\USER\\Desktop\\t.pdf', 'rb') > fsize=os.stat(f.name)[ST_SIZE] > > s.send(str(fsize)) > s.send(f.read()) > > s.close() > f.close() > > =========================================================== > > Thanks for reading!! > > Best regards, > Ferdi > > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list From deets at nospam.web.de Thu Dec 11 17:52:23 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 11 Dec 2008 23:52:23 +0100 Subject: Best way of debigging a C extension In-Reply-To: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> References: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> Message-ID: <6qdjt7Fc1fg0U1@mid.uni-berlin.de> Paul Moore schrieb: > I'm writing a C extension. My environment is Python 2.5, with the > mingw compiler, on Windows XP. At the moment I'm debugging by > scattering printf() statements around, but it's not always easy. Is > there a better way of debugging - particularly for diagnosing crashes? > > I have gdb (although I've hardly used it, but I can learn :-)) but if > I try building my extension with python setup.py build --debug, I get > an error because -lpython25_d does not exist. I'm not surprised by > this, as I don't have a debug build of Python - but that should be OK, > I'm only looking for debugging info from my code. > > I tried copying libpython25.a to libpython25_d.a - my extension now > builds, but the resulting pyd is XXX_d.pyd, which won't import. If I > rename this to XXX.pyd, I can import and things seem to work - but it > seems a bit of a roundabout way of doing things. Is there a simpler > way that I've missed? It seems to me that this (debugging a C > extension without compiling a debug build of Python) would be a fairly > common situation, so I would have expected a "cleaner" way of doing > it. > > At the very least, a documentation patch to explain the best way of > doing things might be useful. I'll see what I can put together based > on the responses I get here. I never tried this on windows - but what happens if you start python inside GDB, and then set breakpoints inside your extension? This works flawlessly for me under *nix. The debug-build of python isn't needed for this - and I doubt a bit that it helps you much, as being inside the interpreter & getting detailed information isn't your goal - you want to see your extensions functions, what parameters they get and so on. Diez From enleverlesX.XmcX at XmclaveauX.com Sat Dec 20 12:09:01 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sat, 20 Dec 2008 18:09:01 +0100 Subject: PIL on 3.x? In-Reply-To: <6r44k2Fff3hbU1@mid.uni-berlin.de> References: <3892784c-ddf4-4451-bcfd-dbc58b9b55f8@e1g2000pra.googlegroups.com> <494c0ad4$0$4096$ba4acef3@news.orange.fr> <6r44k2Fff3hbU1@mid.uni-berlin.de> Message-ID: <494d2755$0$18388$ba4acef3@news.orange.fr> Hi! Fredrik Lundh (Pythonware ; the author of PIL (and ElementTree, and many other things)) had, in the past, often give answers. To me, like to others people. @-salutations -- Michel Claveau From castironpi at gmail.com Tue Dec 30 14:12:31 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 30 Dec 2008 11:12:31 -0800 (PST) Subject: SQL, lite lite lite References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> <8da5c6b1-951f-4abd-8ee7-07b63802b9f6@13g2000yql.googlegroups.com> Message-ID: <186e44f7-f949-45e2-b1e2-a913560acf94@s9g2000prg.googlegroups.com> On Dec 30, 11:16?am, prueba... at latinmail.com wrote: > On Dec 29, 1:06?pm, Aaron Brady wrote: snip > > My idea is to create a 'Relation' class. ?The details are basically > > open, such as whether to back it with 'sqllite3', 'shelve', 'mmap', or > > just mapping and sequence objects; what the simplest syntax is that > > can capture and permit all the basics, and how much and what else can > > fit in at that level; how and whether it can include arbitrary Python > > objects, and what constraints there are on them if not; how and > > whether to permit transactions; and what the simplest and coolest > > thing you can do with a little Python syntax is. snip > You really do like to reinvent the wheels do you? :-) Nothing wrong > with that. Just be aware that most people that really need what you > are proposing are probably already using mature feature rich libraries > for that. > > http://wiki.python.org/moin/HigherLevelDatabaseProgramming Look at these options! Who invents the wheel? Naturally, I've had time to master every one. The page on Dee reminded me that there was some relational algebra early on in the databases course. I'd forgotten. Maybe I wouldn't feel so sheepish if I'd tried starting there, to see exactly what I need. It's possible that if I had a real goal, it could drive the requirements for my Relation class. I don't. What I have is very vague, somewhat second-hand, and also inspired by a tangent in a recent thread here on c-l-databases, er, -py. You remember the days of parallel arrays before records were invented. The bare minimum I can think of for a relation is just a set of tuples. TakingClass( Arthur, Science ) #TakingClass.add( ( Arthur, Science ) ) It's just that 'what classes is Arthur taking?' is an O( total ) op. Next is a parallel mapping. TakingClass( Arthur, Science ) # science.add( arthur ) # arthur.add( science ) O( key ) read and O( 1 ) add, but it's repetitious. I feel it's really error prone, but maybe it's the best balance. The actual abstraction is something more like this: # Emps( Name, EmpID, Department ) Emps( KnightsOfNi, NiNiNi, Gardening ) # tupA= EmpsTuple( KnightsOfNi, NiNiNi, Gardening ) # KnightsOfNi.add( tupA ) # NiNiNi.add( tupA ) # Gardening.add( tupA ) (If KnightsOfNi will appear in more than one relation, it will need to distinguish: 'KnightsOfNi.emps.add( tupA )'.) A single predicate is just a set. A relation is just a set of tuples. Dee lets you write lambda expressions for filters/selects. Django lets you chain selects with a double underscore. From antoine at vo.lu Sat Dec 6 04:02:53 2008 From: antoine at vo.lu (Antoine De Groote) Date: Sat, 06 Dec 2008 10:02:53 +0100 Subject: Guido's new method definition idea In-Reply-To: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> Message-ID: <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> Allowing "$" as a substitute for "self" wouldn't require this new syntax. class C: def method($, arg): $.value = arg I'm strongly against this. This looks ugly and reminds me of Perl and Ruby. (I don't have anything against these languages, but there's a reason I use Python). Russ P. wrote: > On Dec 5, 6:21 pm, "Daniel Fetchinson" > wrote: >> Hi folks, >> >> The story of the explicit self in method definitions has been >> discussed to death and we all know it will stay. However, Guido >> himself acknowledged that an alternative syntax makes perfect sense >> and having both (old and new) in a future version of python is a >> possibility since it maintains backward compatibility. The alternative >> syntax will be syntactic sugar for the old one. This blog post of his >> is what I'm talking about: >> >> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... >> >> The proposal is to allow this: >> >> class C: >> def self.method( arg ): >> self.value = arg >> return self.value >> >> instead of this: >> >> class C: >> def method( self, arg ): >> self.value = arg >> return self.value >> >> I.e. explicit self stays only the syntax is slightly different and may >> seem attractive to some. As pointed out by Guido classmethods would >> work similarly: >> >> class C: >> @classmethod >> def cls.method( arg ): >> cls.val = arg >> return cls.val >> >> The fact that Guido says, >> >> "Now, I'm not saying that I like this better than the status quo. But >> I like it a lot better than [...] but it has the great advantage that >> it is backward compatible, and can be evolved into a PEP with a >> reference implementation without too much effort." >> >> shows that the proposal is viable. >> >> I'd like this new way of defining methods, what do you guys think? >> Anyone ready for writing a PEP? >> >> Cheers, >> Daniel >> >> -- >> Psss, psss, put it down! -http://www.cafepress.com/putitdown > > I like it. > > I'll even go a step further and suggest that "$" be allowed as a > substitute for "self". It looks like a capital "S" (for Self), and it > stands out clearly. It also makes code more succinct with no loss of > readability. Think of the line wraps that could be avoided. From aisaac at american.edu Thu Dec 4 14:50:58 2008 From: aisaac at american.edu (Alan G Isaac) Date: Thu, 04 Dec 2008 14:50:58 -0500 Subject: simplest way to strip a comment from the end of a line? In-Reply-To: References: Message-ID: rdmurray at bitdance.com wrote: > >>> from shlex import split > >>> split("this is a test #with a comment") > ['this', 'is', 'a', 'test', '#with', 'a', 'comment'] > >>> split("this is a test #with a comment", comments=True) > ['this', 'is', 'a', 'test'] > >>> split("this is a '#gnarlier' test #with a comment", comments=True) > ['this', 'is', 'a', '#gnarlier', 'test'] > > http://docs.python.org/library/shlex.html It would be nice to have this example included in the module docs... Alan Isaac From kermit.mei at gmail.com Thu Dec 11 09:44:20 2008 From: kermit.mei at gmail.com (Kermit Mei) Date: Thu, 11 Dec 2008 22:44:20 +0800 Subject: How can I understan the "for" here? Message-ID: <49412744.8040301@gmail.com> Hello all, look at the following sentence: >>>params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"} >>> ["%s=%s" % (k, v) for k, v in params.items()] ['pwd=secret', 'database=master', 'uid=sa', 'server=mpilgrim'] I can't understand the second sentence because of the "for ... in". I consider that the syntactics of "for" should be: for k,v in params.items(): ...... But there's no a colon here, why it can work? Thanks! From deets at nospam.web.de Mon Dec 1 16:56:48 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 01 Dec 2008 22:56:48 +0100 Subject: newbie question: parse a variable inside an RE? In-Reply-To: References: Message-ID: <6pj4svF832i3U1@mid.uni-berlin.de> joemacbusiness at gmail.com schrieb: > Hi All, > > How do I parse a variable inside an RE? > What is the re.search() syntax when your > search string is a variable? > It's easy to parse hardcoded RE's but not > if you use a variable. Both are exactly equal in difficulty. > > Here is my code, input and runtime: > > $ cat test45.py > #!/usr/bin/python > > import re > > resp = raw_input('Selection: ') > newresp = resp.strip() > print "you chose ", newresp > > fname = open('test44.in') > for I in fname: > # if re.search('^newresp', "%s"%(I)): # returns nothing > # if re.search(^newresp, "%s"%(I)): # syntax error > if re.search("^newresp", "%s"%(I)): # returns nothing > print I, How should python know that you want the newresp being expanded? And not that you want to search for the word "newresp"? You need to use the *variable* newresp: if re.search(newresp, I): ... If you want to alter it to have a "^" prepended before you use it, you need to do so: newresp = "^" + newresp And as show above, "%s" % I is nothing but I - no need for the string-interpolation. Diez From walterbyrd at iname.com Fri Dec 19 11:01:13 2008 From: walterbyrd at iname.com (walterbyrd) Date: Fri, 19 Dec 2008 08:01:13 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? Message-ID: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> I have not worked with Python enough to really know. But, it seems to me that more I look at python 3.0, the more I wonder if it isn't a step backwards. To me, it seems that this: print "%s=%d" % ('this',99) Is much easier, and faster, to type, and is also easier to read and understand. It also allows people to leverage their knowledge of C. This (if it's right) is much longer, and requires more special characters. print( "{0}={1}".format('this',99)) Maybe it's worth all the extra trouble, and breaking backward compatibilty, and all. But, I never had the idea that the old way was all that big a problem. Of course, I could be wrong. Was the old way all that big of a problem? From george.sakkis at gmail.com Thu Dec 4 13:13:00 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 4 Dec 2008 10:13:00 -0800 (PST) Subject: Overriding a method at the instance level on a subclass of a builtin type References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> Message-ID: On Dec 4, 1:03?pm, "Zac Burns" wrote: > Ok... but why are the special methods handled differently? Because otherwise they wouldn't be special ;-) And also for performance and implementation reasons I believe. George From ndbecker2 at gmail.com Tue Dec 2 19:47:52 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 02 Dec 2008 19:47:52 -0500 Subject: problem with optparse References: Message-ID: Robert Kern wrote: > Neal Becker wrote: >> This example is right out of python library reference. What's wrong >> here? >> >> import optparse >> >> def store_value(option, opt_str, value, parser): >> setattr(parser.values, option.dest, value) >> >> parser = optparse.OptionParser() >> parser.add_option("--foo", >> action="callback", callback=store_value, >> type="int", nargs=3, dest="foo") >> >> (opt,args) = parser.parse_args ('--foo a b c'.split()) >> >> [...] >> /usr/lib64/python2.5/optparse.pyc in _process_args(self, largs, rargs, >> values) >> 1423 elif self.allow_interspersed_args: >> 1424 largs.append(arg) >> -> 1425 del rargs[0] >> 1426 else: >> 1427 return # stop now, leave this >> arg in rargs >> >> TypeError: 'str' object doesn't support item deletion > > Dunno. It works for me (i.e. I get the expected "error: option --foo: > invalid integer value: 'a'"). Have you tried it outside of IPython? > yes: python test_opt.py Traceback (most recent call last): File "test_opt.py", line 12, in (opt,args) = parser.parse_args ('--foo') File "/usr/lib64/python2.5/optparse.py", line 1378, in parse_args stop = self._process_args(largs, rargs, values) File "/usr/lib64/python2.5/optparse.py", line 1425, in _process_args del rargs[0] TypeError: 'str' object doesn't support item deletion From paul at boddie.org.uk Wed Dec 10 08:45:30 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 10 Dec 2008 05:45:30 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> Message-ID: <9bb6c327-27e3-4208-8b5e-cf607340a2b5@q30g2000prq.googlegroups.com> On 9 Des, 19:23, "Chris Mellon" wrote: > > So hold up a second. I'm out of line for calling someone on making a > trollish post that's not relevant to the topic, and for being pretty > late to the party even with the part that *was* on topic, and for > (even in the original post) going the ad-hominem route by not so > subtly implying that Python is an ivory tower language that's not good I believe the term was "ivory-tower thinking". > enough for people with real problems - a clearly false statement by > any standards, and doubly offensive from someone who *is* using it for > real problems and who himself is a less than shining example of You're wide of the mark now, since the complainant was referring to motivations in the the design of the language, not the relevance of the language outside academia (where it is also highly relevant, by the way). > responsible software management, but the OPs lapse into ranting in > response to trite but accurate answers to a question he could have > answered for himself, in detail, had he bothered to read the threads > from the time when the issue actually matter is a reasonable response > that we should support and validate? Trite but accurate? References to the Zen of Python were trite and peripheral at best, especially since the actual reasons (some actually being offered, aside from "get used to it", which isn't a reason) are mostly pragmatic. I think at that point, the complainant is justified in questioning the priorities of the core developers, even though he knows that there's no recourse at this point. The most you can blame him for in that respect is not starting a new thread about those topics, and it's not as if he's the first to air his grievances about those things, is it? > Sometimes you're not ?a crusader for thinking differently and change > by confrontation and speaking truth to power. Sometimes you're just an > asshole. I think you managed to enter this thread without revealing any particular insight in the matter, so I suppose name-calling was the most we could expect from you at this point. > For clarification: The OPs original complaint is legitimate, if dated > and partially his own fault. His phrasing of the problem, the tone and > content of his email, and his lapse into flaming when he wasn't > immediately hailed as a herald of sanity is not legitimate. If people would confine themselves to the matters under discussion without taking an adversarial position - after all, it's not as if the guy just dropped in to flame everyone having never used Python - there wouldn't be any need for anyone to lapse into flaming, tantrums or name-calling, would there? You wouldn't even need to apologise for calling the guy a troll, now, would you? Paul From python at bdurham.com Tue Dec 2 07:39:54 2008 From: python at bdurham.com (python at bdurham.com) Date: Tue, 02 Dec 2008 07:39:54 -0500 Subject: Determining number of dict key collisions in a dictionary Message-ID: <1228221594.807.1287801527@webmail.messagingengine.com> Is there any way to determine the number of dictionary key collisions in a specific dictionary? Background: I'm working on a project using very large dictionaries (64 bit Python) and question from my client is how effective is Python's default hash technique for our data set? Their concern is based on the belief that Python's default dictionary hash scheme is optimized for 32 bit vs. 64 bit environments and may not have anticipated the additional range of keys that can be generated in a 64 bit environment. Our keys are based on 20 to 44 byte ASCII (7-bit) alpha-numeric strings. Thank you, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From jan at jandecaluwe.com Wed Dec 24 02:52:15 2008 From: jan at jandecaluwe.com (Jan Decaluwe) Date: Wed, 24 Dec 2008 08:52:15 +0100 Subject: Why MyHDL? In-Reply-To: References: <4950d063$0$2853$ba620e4c@news.skynet.be> Message-ID: <4951ea41$0$2850$ba620e4c@news.skynet.be> Stef Mientki wrote: > hello Jan, > > Jan Decaluwe wrote: >> Hello: >> >> MyHDL is a Python package for using Python as a >> Hardware Description Language. >> >> A new release is upcoming, and on this occasion >> we have prepared a page about why MyHDL may >> be useful to you: >> >> http://www.myhdl.org/doku.php/why >> > Very Interesting, > I'm no expert at all (but as an exercise I'm just now writing an EDIF-v2 > to SystemC converter in Python) , > I wonder why I only see comparison with VHDL and SystemVerilog, > and not with SystemC ? MyHDL's target audience are the users of mainstream HDL-based design flows (including synthesis and implementation.) I don't encounter SystemC there. Jan -- Jan Decaluwe - Resources bvba - http://www.jandecaluwe.com Python as a hardware description language: http://www.myhdl.org From grebekel at gmail.com Mon Dec 29 14:11:55 2008 From: grebekel at gmail.com (Grebekel) Date: Mon, 29 Dec 2008 11:11:55 -0800 (PST) Subject: flushing of print statements ending with comma Message-ID: <25783efa-fa57-49c8-b20a-7bdf6f7cb256@w1g2000prk.googlegroups.com> I have recently noticed that print statements ending with a comma are not immediately flushed. This is evident when such statement is executed before a very long operation (a big loop for instance). Example: print 'Take a walk, because this will take a while...', i = 0 while i < 10**10: i += 1 print "we're done!" Here the first string is not printed until the second print statement. If the second print statement is removed then the string is not printed until the end of the program. Apparently, python does not flush the stdout buffer until it is ordered to do so either explicitly or by a print statement not ending with a comma. Using sys.std.flush after the print fixes this issue, but doing so each time seems cumbersome and somewhat counterintuitive. Is there some reasoning behind this behavior or is it a bug? Python version 2.5.1 From robert.kern at gmail.com Mon Dec 8 17:13:12 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 08 Dec 2008 16:13:12 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Terry Reedy wrote: > Rasmus Fogh wrote: >> much, though, just to get code like this to work as intended: >> alist.append(x) >> print ('x is present: ', x in alist) > > Even if rich comparisons as you propose, the above would *still* not > necessarily work. Collection classes can define a __contains__ that > overrides the default and that can do anything, though True/False is > recommended. No, it's actually required. In [4]: class A(object): def __contains__(self, other): return 'foo' ...: ...: In [7]: a = A() In [8]: 1 in a Out[8]: True Okay, so it will coerce to True/False for you, but unlike rich comparisons, the return value must be interpretable as a boolean. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From robert.kern at gmail.com Mon Dec 22 16:22:14 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 22 Dec 2008 15:22:14 -0600 Subject: 64-bit / 128-bit data element type for array? In-Reply-To: <880c8478-8b40-40e0-8597-aef960612f09@s9g2000prg.googlegroups.com> References: <880c8478-8b40-40e0-8597-aef960612f09@s9g2000prg.googlegroups.com> Message-ID: akineko wrote: > Hello, > > bearophile and Robert, thank you for your prompt response. > I will try NumPy (this is a good execuse to learn and to use a new > package). > >> I haven't seen uint128 in the wild, though. > > Of course, not many applications require uinit128 as a scalar value. > I may need to deal with 128-bit data as it is now not uncommon to have > 128-bit data bus (or even 256-bit wide and beyond) in ASICs > (microchip) design. Unfortunately, some designs use big-endian and > others use little-endian ... Is that actually a 2s-complement 128-bit unsigned integer, or is it just a 128-bit-long chunk of data? -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From gagsl-py2 at yahoo.com.ar Mon Dec 29 00:40:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Dec 2008 03:40:08 -0200 Subject: ctypes & strings References: <334452.47084.qm@web30003.mail.mud.yahoo.com> <000f01c96822$5c300f00$0d00a8c0@hendrik> <00a801c968dd$6508b3a0$0d00a8c0@hendrik> Message-ID: En Sun, 28 Dec 2008 08:59:03 -0200, Hendrik van Rooyen escribi?: > "Gabriel Genellina" wrote: > >> Hmmm, I don't think posting a potentially harmful example is actually a >> good idea... > > True - its my only example though, and nobody else was > bothering to reply, so I kicked off and flushed out some > response. > > Who was it that said that the way to get info out of usenet > was to post some rubbish? > > :-) As in xkcd: http://xkcd.com/386/ BTW, Python is featured again in the Christmas special: http://xkcd.com/521/ -- Gabriel Genellina From dickinsm at gmail.com Mon Dec 8 06:37:26 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 8 Dec 2008 03:37:26 -0800 (PST) Subject: built-in functions as class attributes References: <75fdbf34-34d9-4373-bbe0-7e3f76dc4c3f@x38g2000yqj.googlegroups.com> Message-ID: <001ab2a6-b58e-4ed0-9cdb-7a9a743b18ee@j38g2000yqa.googlegroups.com> On Dec 8, 11:23?am, Peter Otten <__pete... at web.de> wrote: > I don't know if there is something official, I google for > > http://users.rcn.com/python/download/Descriptor.htm > > or "descrintro" every time I need a refresher. Thank you! I'd read this before, but apparently I'd either not taken it in first time round, or entirely forgotten it. Anything written by Raymond has got to be pretty darn close to 'official'. :) Mark From gagsl-py2 at yahoo.com.ar Tue Dec 16 04:43:25 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Dec 2008 07:43:25 -0200 Subject: Deepcopying slice objects References: Message-ID: En Sun, 14 Dec 2008 15:43:01 -0200, Max Argus escribi?: > I stumbled across a thread about that suggests fixing deepcopy to let it > copy slice objects. ( > http://mail.python.org/pipermail/python-list/2006-August/398206.html). I > expected this to work and don't see any reason why it shouldn't in case > there is a good reason why it dosen't work can someone please explain it. It works fine, both in 2.6 and 3.0: py> from copy import copy, deepcopy py> x = slice(1, 10, 2) py> copy(x) slice(1, 10, 2) py> deepcopy(x) slice(1, 10, 2) -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Sun Dec 14 06:03:05 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Dec 2008 11:03:05 GMT Subject: Optimizing methods away or not? References: <0154b041$0$6988$c3e8da3@news.astraweb.com> Message-ID: <0154df65$0$6988$c3e8da3@news.astraweb.com> On Sun, 14 Dec 2008 10:52:25 +0000, Arnaud Delobelle wrote: > You could also not use the metaclass and use post_verify as a decorator Except that self.verify doesn't exist if __debug__ is false. -- Steven From rhf22 at mole.bio.cam.ac.uk Sun Dec 7 07:43:59 2008 From: rhf22 at mole.bio.cam.ac.uk (Rasmus Fogh) Date: Sun, 7 Dec 2008 12:43:59 +0000 (GMT) Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Robert Kern Wrote: >Terry Reedy wrote: >> Rasmus Fogh wrote: >>> Personally I would like to get these !@#$%&* misfeatures removed, >> >> What you are calling a misfeature is an absence, not a presence that >> can be removed. > > That's not quite true. Rich comparisons explicitly allow non-boolean > return values. Breaking up __cmp__ into multiple __special__ methods was > not the sole purpose of rich comparisons. One of the prime examples at the > time was numpy (well, Numeric at the time). We wanted to use == to be able > to return an array > with boolean values where the two operand arrays were equal. E.g. > > In [1]: from numpy import * > > In [2]: array([1, 2, 3]) == array([4, 2, 3]) > Out[2]: array([False, True, True], dtype=bool) > > SQLAlchemy uses these operators to build up objects that will be turned > into SQL expressions. > > >>> print users.c.id==addresses.c.user_id > > Basically, the idea was to turn these operators into full-fledged > operators like +-/*. Returning a non-boolean violates neither the letter, > nor the spirit of the feature. > > Unfortunately, if you do overload __eq__ to build up expressions or > whatnot, the other places where users of __eq__ are implicitly expecting > a boolean break. > While I was (and am) a supporter of rich comparisons, I feel Rasmus's > pain from time to time. It would be nice to have an alternate method to > express the boolean "yes, this thing is equal in value to that other thing". > Unfortunately, I haven't figured out a good way to fit it in now without > sacrificing rich comparisons entirely. The best way, IMHO, would have been to use an alternative notation in numpy and SQLalchemy, and have '==' always return only a truth value - it could be a non-boolean as long as the bool() function gave the correct result. Surely the extra convenience of overloading '==' in special cases was not worth breaking such basic operations as 'bool(x == y)' or 'x in alist'. Again, the problem is only with '==', not with '>', '<=' etc. Of course it is done now, and unlikely to be reversed. >>> and constrain the __eq__ function to always return a truth value. >> >> It is impossible to do that with certainty by any mechanical >> creation-time checking. So the implementation of operator.eq would >> have to check the return value of the ob.__eq__ function it calls *every >> time*. That would slow down the speed of the 99.xx% of cases where the >> check is not needed and would still not prevent exceptions. And if the >> return value was bad, all operator.eq could do is raise and exception >> anyway. > >Sure, but then it would be a bug to return a non-boolean from __eq__ and >friends. It is not a bug today. I think that's what Rasmus is proposing. Yes, that is the point. If __eq__ functions are *supposed* to return booleans I can write generic code that will work for well-behaved objects, and any errors will be somebody elses fault. If __eq__ is free to return anything, or throw an error, it becomes my responsibility to write generic code that will work anyway, including with floating point numbers, numpy, or SQLalchemy. And I cannot see any way to do that (suggestions welcome). If purportedly general code does not work with numpy, your average numpy user will not be receptive to the idea that it is all numpys fault. Current behaviour is both inconsistent and counterintuitive, as these examples show. >>> x = float('NaN') >>> x == x False >>> ll = [x] >>> x in ll True >>> x == ll[0] False >>> import numpy >>> y = numpy.zeros((3,)) >>> y array([ 0., 0., 0.]) >>> bool(y==y) Traceback (most recent call last): File "", line 1, in ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() >>> ll1 = [y,1] >>> y in ll1 True >>> ll2 = [1,y] >>> y in ll2 Traceback (most recent call last): File "", line 1, in ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() >>> Can anybody see a way this could be fixed (please)? I may well have to live with it, but I would really prefer not to. --------------------------------------------------------------------------- Dr. Rasmus H. Fogh Email: r.h.fogh at bioc.cam.ac.uk Dept. of Biochemistry, University of Cambridge, 80 Tennis Court Road, Cambridge CB2 1GA, UK. FAX (01223)766002 From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 29 04:07:00 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 29 Dec 2008 10:07:00 +0100 Subject: why cannot assign to function call In-Reply-To: References: Message-ID: <49589334$0$8269$426a74cc@news.free.fr> scsoce a ?crit : > I have a function return a reference, and want to assign to the > reference, You have a function that returns an object. You can't "assign" to an object - this makes no sense. I'm afraid you are confusing Python's name/object bindings with C pointers or C++ references. From MatthewHyatt at ComputerPeople.co.uk Mon Dec 8 13:11:26 2008 From: MatthewHyatt at ComputerPeople.co.uk (Hyatt, Matthew) Date: Mon, 8 Dec 2008 18:11:26 -0000 Subject: Great Python Job - Bristol - UK Message-ID: <3D9A341721DDC4438239BB7799E7EE511029FDFF@EXCHANGE01.ajilongroup.co.uk> Hi there, I hope you don't mind me contacting you - I need to contact some real Python experts and thought this would be best. I currently have a unique opportunity for a talented Python Software Engineer to work on exciting application development projects for the aeronautical industry. You will work in a team of world experts that includes PhD qualified professionals that are recognised by their peers as being global authorities in their individual fields. If you have a background and keen interest in Python programming, physics, mathematics, engineering or CFD, then this could be your dream job. The role Working in a team of 10 software experts, you will develop ground-breaking technology that is largely green-field. This is very challenging and interesting work that involves a large research element and will include the development of the company's own open-source Python application framework, extensive use of PyQT and CFD work. Person Spec In order to apply, you will have superb programming skills in Python and a strong academic background, MSc or PhD qualified in a numeric or engineering discipline. Ideally, your knowledge of Python will extend to PyQT and your broader development skills will include C/C++, MATLAB and SQL. Any experience gained in CFD, or prior exposure to Enthought's Envisage product would be an advantage. If you have the required skills and are interested, please respond with a copy of your CV and I will gladly discuss the opportunity in more detail. Many thanks, Matt Matthew Hyatt Senior Consultant Tel: +44 (0) 117 930 8575 Fax: +44 (0) 117 929 1444 matthewhyatt at computerpeople.co.uk www.computerpeople.com Intelligent Business Solutions through Executive Search & Selection, Careers Consultancy, Managed Service & Specialised Recruitment This e-mail and any files transmitted with it are confidential (and may contain privileged information) to the ordinary user of the e-mail address to which it was addressed and must not be copied, disclosed or distributed without the prior authorisation of the sender. Please notify the sender and destroy this e-mail immediately if you are not the intended recipient. Please also note that while our own software systems have been used to try to ensure that this e-mail has been swept for viruses, we do not accept responsibility for any damage or loss caused in respect of any viruses transmitted by the e-mail. Please ensure your own checks are carried out before any attachments are opened. Computer People, Jonathan Wren & People Direct are the trading names of Ajilon (UK) Limited whose registered office is at:71 Elstree Way, Borehamwood, Hertfordshire, England, WD6 1WD. Registered in England & Wales: Registered No. 01458245. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image001.jpg Type: image/jpeg Size: 2219 bytes Desc: image001.jpg URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image002.gif Type: image/gif Size: 2153 bytes Desc: image002.gif URL: From wuwei23 at gmail.com Thu Dec 11 11:16:51 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 11 Dec 2008 08:16:51 -0800 (PST) Subject: Preventing execution of a method References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> Message-ID: On Dec 12, 2:07?am, "Emanuele D'Arrigo" wrote: > I.e. if I have a class with two methods, doSomethingSafe() and > doSomethingDangerous(), is there a way to prevent another module from > executing doSomethingDangerous() but allow the execution of > doSomethingSafe()? > > My understanding is that in python this is not possible. Can you > confirm? Your understanding is correct. The Python convention is to prefix non-public methods/classes etc with an underscore, as in _doSomethingDangerous(). This is meant to indicate to anyone using your module that they shouldn't use this function, at least not without having a good understanding of what it does. From martin at v.loewis.de Sun Dec 14 17:20:22 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 14 Dec 2008 23:20:22 +0100 Subject: Building from source -- zlib/binascii problems 2.5.2/2.6.1 In-Reply-To: References: <71531b64-535f-49d0-a0c6-7704df83b251@f18g2000vbf.googlegroups.com> <49458079.1000304@v.loewis.de> <003b0307-c8df-489b-98e6-cfaa35d050a4@k1g2000prb.googlegroups.com> Message-ID: <494586A6.4060102@v.loewis.de> > So.. it seems as though I need to get it to point to the 64 bit > version (or compile the zlib that comes with Python source). I'm not > sure how to override that. The easiest solution would be to invoke the linker line manually, and replace -lz with the absolute path to the right library. Regards, Martin From martin.hellwig at dcuktec.org Mon Dec 22 13:07:20 2008 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Mon, 22 Dec 2008 18:07:20 +0000 Subject: I always wonder ... In-Reply-To: References: Message-ID: <494fd759$0$186$e4fe514c@news.xs4all.nl> skip at pobox.com wrote: > Is there some online troll game > running where the players earn points for generating responses to their > posts? > You just got 10 points ;-) -- mph From cma at mail.bnu.edu.cn Tue Dec 9 04:56:37 2008 From: cma at mail.bnu.edu.cn (Cong Ma) Date: Tue, 09 Dec 2008 17:56:37 +0800 Subject: [Python 2.x] Pickling a datetime.tzinfo subclass instance? In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > En Mon, 08 Dec 2008 12:34:03 -0200, Cong Ma escribi?: > >> I'm writing a program that pickles an instance of a custom subclass of >> datetime.tzinfo. I followed the guides given in the Library Reference >> (version >> 2.5.2, chapter 5.1.6), which contain the note: >> >> "Special requirement for pickling: A tzinfo subclass must have an >> __init__ >> method that can be called with no arguments, else it can be pickled >> but possibly >> not unpickled again. This is a technical requirement that may be >> relaxed in the >> future." >> >> I tried this with an example "FixedOffset" subclass instance given in the >> Example section in the manual. It indeed failed to unpickle. To work >> around >> this, I found two possible solutions: >> 1. Modify the __init__ method so that it takes optional arguments with >> default >> values; > > Doing that still works with 2.6 and 3.0 > >> 2. Implement the __getinitargs__ method so that it does the opposite of >> __init__: returning a tuple from the instance's internal state that >> can be used >> to re-initialize an instance, retaining the old value. > > In fact, it doesn't matter *what* it returns, as far as they're valid > arguments to __init__ > >> My questions: >> 1. Is the "technical limitation" fixed in version 2.6 or 3.0? I can't >> check it >> for myself now... Python.org seems down and I can't find the docs. > > No, they behave the same (odd) way. > >> 2. To stick with version 2.5, which of the above 2 methods is better? >> Both seems >> to unpickle to the correct result, but are there subtle side-effects? >> Or there >> are better solutions? > > I'd use method 1, just because the __getinitargs__ are useless. > Gabriel, Thank you so much for your great explanations. Had you not told me this, I would hardly be able to find it out by myself :) Regards, Cong. From andreas at kostyrka.org Sun Dec 14 12:35:24 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sun, 14 Dec 2008 18:35:24 +0100 Subject: execution time In-Reply-To: References: Message-ID: <20081214173524.GA4896@hell.kostyrka.org> On Sun, Dec 14, 2008 at 05:03:38PM +0100, David Hl??ik wrote: > Hi guys, > > #! /usr/bin/python > > import random > import bucket2 > > data = [ random.randint(1,25) for i in range(5)] > print "random data : %s" % data > print "result: %s" %bucket2.sort(data) > > How to write a test script which will outputs execution time for > bucket2.sort(data) ? Well: import time starttime = time.time() .... endtime = time.time() print "Whatever .... does, it took %5.3fs to do." % (endtime - starttime) Alternativly take a look at the timeit standard module. Andreas > > Thanks in advance! > -- > http://mail.python.org/mailman/listinfo/python-list From python-url at phaseit.net Wed Dec 24 09:17:57 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Wed, 24 Dec 2008 14:17:57 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Dec 24) Message-ID: QOTW: "Threads seem to be used only because mediocre programmers don't know what else to use." - Sturla Molden http://mail.python.org/pipermail/python-dev/2008-December/084265.html Python 2.4.6 and 2.5.3 were released this week: http://groups.google.com/group/comp.lang.python/browse_thread/thread/53901d6dd764d8a8/ What's the difference between __str__ vs. __repr__? http://groups.google.com/group/comp.lang.python/browse_thread/thread/a0f0b526006fe831/ Unicode problems -- and how RealBasic solves them in a totally different way: http://groups.google.com/group/comp.lang.python/browse_thread/thread/f623b434f2ac6d9/ An optimization exercise, involving fileinput and str.split/partition: http://groups.google.com/group/comp.lang.python/browse_thread/thread/77fc160ee557ae39/ How to modify a program while it is still running: http://groups.google.com/group/comp.lang.python/browse_thread/thread/95397361600ded28/ A looooong thread about the new (3.0) string formatting mechanism http://groups.google.com/group/comp.lang.python/browse_thread/thread/23d63689c0087ebf/ Two apparently trivial tasks are actually challenging to get right: writing a sign() function, and timing it: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c726f932f75c23e4/ ======================================================================== 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 Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From esgameserver at gmail.com Mon Dec 1 16:15:35 2008 From: esgameserver at gmail.com (esgameserver at gmail.com) Date: Mon, 1 Dec 2008 13:15:35 -0800 (PST) Subject: Thread always alive Message-ID: Hi, I have thread that the isAlive() method is always returning True even the last finally(..) clause is executed. I am suspecting some kind of a leak on a IO object like a file or socket descriptor is still open. Could this lead to this kind of problem? If yes, how can I debug this issue efficiently to see the leak? Thanks, From joe at strout.net Sun Dec 7 09:17:30 2008 From: joe at strout.net (Joe Strout) Date: Sun, 7 Dec 2008 07:17:30 -0700 Subject: how to get a beep, OS independent ? In-Reply-To: References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> Message-ID: On Dec 7, 2008, at 6:36 AM, Duncan Booth wrote: > Python is just printing the ascii bell character: some environments > will > interpret that as a request to make a beep, some will do things like > flashing the whole screen, others just output a graphic character. > Python > doesn't know what your environment will do. Agreed. But invoking the standard system beep is such a basic function that it ought to be easier than this. I'm pretty sure it's a single OS call on all platforms. On OS X, for example, it's void NSBeep(void); declared in NSGraphics.h. I'm sure it's something similarly simple on other platforms. Where's the standard place for this sort of OS-abstraction function, outside the standard Python library? I'm talking about something more light-weight than wx, QT, or TK; something that just wraps standard functions (like the system beep) and works in console apps or in any flavor of GUI app. Is there such a module out there somewhere? Best, - Joe From google at mrabarnett.plus.com Fri Dec 19 13:31:00 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 19 Dec 2008 18:31:00 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> Message-ID: <494BE864.1040100@mrabarnett.plus.com> bearophileHUGS at lycos.com wrote: > r: >> I always thought of Python as an intuitive way to write C code.< > > C is a very low level language, not far from assembly, and often it's > not intuitive at all. > > C string formatting is short and a flexible enough, but it's out of > place in a language as high level as Python3. The new syntax allows > more flexibility, and it's better for most people that don't know C > already, like newbies, etc. > > ------------------ > > walterbyrd: >> It seems to me that 3.0 is changing a lot of non-problems. And it's > going to be slower to boot.< > > They are non-problems for people that already know lot of Python (and > some C). But for all the other people, especially newbies, it's better > in most things. > > Most language designers (and generally people very used a certain > language) become so accustomed to their language that they most of the > times become like "blind" to the defects and warts of their language > (I have said this four years ago too, when I have started learning > Python, listing many problems in Python, and among them there were C > string formatting too). So I think it was a feat for the Python > developers to see many characteristics of the Python2.x as what they > are: warts, bugs, etc, and fix them (and most of the times their newer > designs are "the right thing" with just few exceptions, I have counted > only 3 of them, and they are small). They have gained even more of my > respect. > > Regarding the speed of Python3 programs, they will go faster because > people will be forced to use things like lazy ranges, lazy map and > filter, lazy keys and values, and the "key" of sort/sorted. All those > things can be used in Python2.x too, but lot of people aren't expert > enough (or they are just lazy) and don't use them, so the average > Python3 program will probably be faster (and use less memory) thanks > to them. > > Python3 programs will go slower because they use 2-byte long Unicode > strings by default (it can be compiled for 4-byte Unicode too, and I > think this has to become the default, eventually, because I think it > will become silly to save few bytes for strings when you will have > 8-16-32+ GB of RAM), and they use multi-precision integers only. Such > strings and numbers allow to reduce some troubles, even "bugs", etc. > > At the moment Python3 isn't much optimized for speed, you can think of > it an experimental release still. I/O and multiprecision integers will > probably be speed up (and some form of transparent on-the-fly > compression or smart representation can in most times halve the memory > used by Py3 strings, putting the performance almost back to the Py2.x > one. In computer science there are LOT of tricks that can be used if > you have the brain and time to invent and implement them. You can see > that for example in how Psyco manages internally string/list/tuple > slices). > > Anyway, CPUs and computers are now much faster than the CPUs present > when Python was created. And Python is first of all designed for the > programmer and not for the CPU. So I think it's right to make Python3 > become a little higher level language even if this slows it down a > little. For the kind of programs Python is often used for, I think > this is a Win. (Ruby programs are often slower than Python ones > (because Ruby is a little higher level than Python) but it's very > useful anyway). If Python will continue to develop in the following > years (think about a Python4000) then I think it may become good to > make it become even more slower, if this will help make it a little > more higher level still. > I would've hoped that Python 4000 would address the internals (JIT) just as Python 3000 addressed the externals. From iofferkicks32 at gmail.com Sat Dec 27 10:26:32 2008 From: iofferkicks32 at gmail.com (www.iofferkicks.com) Date: Sat, 27 Dec 2008 07:26:32 -0800 (PST) Subject: www.iofferkicks.com china cheap wholesale nike shoes,air jordan shoes,air force one shoes. Message-ID: Get Nike Shoes at Super Cheap Prices Discount Nike air jordans (www.iofferkicks.com) Discount Nike Air Max 90 Sneakers (www.iofferkicks.com) Discount Nike Air Max 91 Supplier (www.iofferkicks.com) Discount Nike Air Max 95 Shoes Supplier (www.iofferkicks.com) Discount Nike Air Max 97 Trainers (www.iofferkicks.com) Discount Nike Air Max 2003 Wholesale (www.iofferkicks.com) Discount Nike Air Max 2004 Shoes Wholesale (www.iofferkicks.com) Discount Nike Air Max 2005 Shop (www.iofferkicks.com) Discount Nike Air Max 2006 Shoes Shop (www.iofferkicks.com) Discount Nike Air Max 360 Catalogs (www.iofferkicks.com) Discount Nike Air Max Ltd Shoes Catalogs (www.iofferkicks.com) Discount Nike Air Max Tn Men's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 2 Women's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 3 Customize (www.iofferkicks.com) Discount Nike Air Max Tn 4 Shoes Customize ( www.iofferkicks.com) Discount Nike Air Max Tn 6 Supply (www.iofferkicks.com) Discount Nike Shox NZ Shoes Supply (www.iofferkicks.com) Discount Nike Shox OZ Sale (www.iofferkicks.com) Discount Nike Shox TL Store (www.iofferkicks.com) Discount Nike Shox TL 2 Shoes Store (www.iofferkicks.com) Discount Nike Shox TL 3 Distributor (www.iofferkicks.com) Discount Nike Shox Bmw Shoes Distributor (www.iofferkicks.com) Discount Nike Shox Elite Shoes Manufacturer (www.iofferkicks.com) Discount Nike Shox Monster Manufacturer (www.iofferkicks.com) Discount Nike Shox R4 Running Shoes (www.iofferkicks.com) Discount Nike Shox R5 Mens Shoes (www.iofferkicks.com) Discount Nike Shox Ride Womens Shoes (www.iofferkicks.com) Discount Nike Shox Rival Shoes Wholesaler (www.iofferkicks.com) Discount Nike Shox Energia Wholesaler (www.iofferkicks.com) Discount Nike Shox LV Sneaker (www.iofferkicks.com) Discount Nike Shox Turbo Suppliers (www.iofferkicks.com) Discount Nike Shox Classic Shoes Suppliers (www.iofferkicks.com) Discount Nike Shox Dendara Trainer (www.iofferkicks.com) Discount Nike Air Jordan 1 Seller (www.iofferkicks.com) Discount Nike Air Jordan 2 Shoes Seller (www.iofferkicks.com) Discount Nike Air Jordan 3 Collection (www.iofferkicks.com) Discount Nike Air Jordan 4 Shoes Collection (www.iofferkicks.com) Discount Nike Air Jordan 5 Chaussure Shoes (www.iofferkicks.com) Discount Nike Air Jordan 6 Catalog (www.iofferkicks.com) Discount Nike Air Jordan 7 Shoes Catalog (www.iofferkicks.com) Discount Nike Air Jordan 8 Customized (www.iofferkicks.com) Discount Nike Air Jordan 9 Shoes Customized (www.iofferkicks.com) Discount Nike Air Jordan 10 Wholesalers (www.iofferkicks.com) Discount Nike Jordan 11 Shoes Wholesalers (www.iofferkicks.com) Discount Nike Air Jordan 12 Factory (www.iofferkicks.com) Discount Nike Air Jordan 13 Shoes Factory (www.iofferkicks.com) Discount Nike Air Jordan 14 Shoes Sell (www.iofferkicks.com) Discount Nike Air Jordan 16 Exporter (www.iofferkicks.com) Discount Nike Air Jordan 17 Shoes Exporter (www.iofferkicks.com) Discount Nike Air Jordan 18 Offer (www.iofferkicks.com) Discount Nike Air Jordan 19 Shoes Offer (www.iofferkicks.com) Discount Nike Air Jordan 20 Manufacture (www.iofferkicks.com) Discount Nike Jordan 21 Shoes Manufacture (www.iofferkicks.com) EMAIL:IOFFERKICKS at GMAIL.COM MSN :IOFFERKICKS at MSN.COM From istvan.albert at gmail.com Thu Dec 4 13:40:41 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Thu, 4 Dec 2008 10:40:41 -0800 (PST) Subject: Python 3 read() function References: <16651e80812040900j257fe2acjf5d8817811d32da6@mail.gmail.com> Message-ID: On Dec 4, 1:31?pm, Terry Reedy wrote: > Jerry Hill wrote: > > That's 3 orders of magnitude slower on python3.0! > > Timing of os interaction may depend on os. ?I verified above on WinXp > with 4 meg Pythonxy.chm file. ?Eye blink versus 3 secs, duplicated. ?I > think something is wrong that needs fixing in 3.0.1. > > http://bugs.python.org/issue4533 I believe that the slowdowns are even more substantial when opening the file in text mode. From jaume.bonet at gmail.com Thu Dec 11 12:35:58 2008 From: jaume.bonet at gmail.com (Jaume Bonet) Date: Thu, 11 Dec 2008 09:35:58 -0800 (PST) Subject: Memory leak when using a C++ module for Python References: Message-ID: <13db1224-5d6d-4240-8184-ce852e10b422@d36g2000prf.googlegroups.com> Sure, sorry... This is the function that is visible from python and the one that the python code calls: static PyObject * IMFind (PyObject *self, PyObject *args, PyObject *kwargs) { //Array for the detection of the parameters coming from Python static char *kwlist[] = {"shareInt","root","prefix","lowerLimit",NULL}; //Root protein code char *root; //Pefix for the output file char *prefix; //Incoming Python object PyObject *shareIntPy; //Number of proteins at level two from the root, that will appear in the iMotifs' proteins int *pSize = new int; //Maximum number of common interactors int *max = new int; //Set relating each protein (integer) with their interactors... set** shareInt; //Lower limit for iMotif search int lowLim; //Vector for the seed iMotifs from an specific threshold vector IMseed; //Vector of all the working iMotifs during the identification process vector IMarray; //Receiving data from python if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Ossi", kwlist, &shareIntPy, &root, &prefix,&lowLim)) { cerr << "Error in parameter transference from python to iMotif C++ module"< translator = string2int (shareIntPy,root,shareInt,pSize,max); //Loop for iMotif search at threshold thr till the specified lower limit for (int thr = *max; thr >= lowLim; thr--) { cout << "Checking threshold " << thr << endl; //Specifying the output file name stringstream filename; filename << prefix << "." << thr; //Getting the seed iMotifs for this threshold IMseed = getSeedIM(shareInt,*pSize,thr); //Adding the new seeds (if any) to those obtained from previous rounds... if (!IMseed.size()) { IMseed.clear(); vector().swap(IMseed); //This is how I try to free them now, size & capacity gets to 0, but the // memory is not freed... } else { IMarray.insert(IMarray.end(),IMseed.begin(),IMseed.end()); IMseed.clear(); vector().swap(IMseed); } //Fuse those iMotifs sharing thr interactors // It also deletes the IMarray before giving it the new data in the same way as I use here for IMseed processIMVector(IMarray,thr); writeIMVector(IMarray,translator,filename.str()); } return Py_BuildValue(""); } The object iMotif used here is composed by 2 sets and 3 strings just like this: (the access is done by setters and getters) class iMotif { private: //Set of the proteins that shares the iMotif with the root set proteins; //Set of the proteins to which the iMotifs interacts set interactors; //iMotifs interactors signature string MD5Interactor; //iMotifs proteins signature string MD5Proteins; //Real MD5 according to the sequences names string signature; ... } and I specified the destructor as: iMotif::~iMotif() { this->proteins.clear(); set().swap(this->proteins); this->interactors.clear(); set().swap(this->proteins); } The call to the function from python goes like this: iMotifs.IMFind(shareInt=intersections_dict, root=options.protein_problem, prefix=prefixOutFile, lowerLimit=1); where intersections_dict is a dictionary and options.protein_problem and prefixOutFile are strings. There is nothing to return from C++ to python, the result is directly printed into several files. Thanks, J From sjmachin at lexicon.net Sun Dec 7 04:46:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 7 Dec 2008 01:46:34 -0800 (PST) Subject: Python 3.0 automatic decoding of UTF16 References: <55d79070-0c11-4fb9-8cf5-b8cc7c54b5d2@v42g2000yqv.googlegroups.com> <0e37191f-3672-4313-bc5c-ffcd904e4796@k24g2000pri.googlegroups.com> Message-ID: On Dec 7, 8:15?pm, Terry Reedy wrote: > John Machin wrote: > > Here's the scoop: It's a bug in the newline handling (in io.py, class > > IncrementalNewlineDecoder, method decode). It reads text files in 128- > > byte chunks. Converting CR LF to \n requires special case handling > > when '\r' is detected at the end of the decoded chunk n in case > > there's an LF at the start of chunk n+1. Buggy solution: prepend b'\r' > > to the chunk n+1 bytes and decode that -- suddenly with a 2-bytes-per- > > char encoding like UTF-16 we are 1 byte out of whack. > Please post this on the tracker so it can get included with other io > work for 3.0.1. I'm fiddling with a short bug-demo script right now. From philip at semanchuk.com Tue Dec 2 23:29:32 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 2 Dec 2008 23:29:32 -0500 Subject: Best way to run multiple Python processes without overloading CPU or disk i/o In-Reply-To: <1228278090.29785.1287948757@webmail.messagingengine.com> References: <1228278090.29785.1287948757@webmail.messagingengine.com> Message-ID: On Dec 2, 2008, at 11:21 PM, python at bdurham.com wrote: > Is there a cross-platform way to launch multiple Python processes > and monitor CPU usage os.getloadavg() might be useful. It certainly works on *nix, don't know about Windows. The documentation doesn't mention any platform limitations. HTH Philip > and disk i/o so that the maximum number of > independent processes can be running at all times without > overloading their environment? By process I mean independent > application sessions vs. multiple threads of a single > application. I'm looking for suggestions on what Python modules > and/or techniques to use to maximize the number of processes I > can run on my system over a multi-day period. > Background: I have a large collection of data analysis scripts > that can run independently of one another. These scripts read > very large log files in a sequential manner and calculate > specific statistics. These scripts are hosted on a 8 core 64-bit > server with 48G of memory that is dedicated to running these > scripts. I am looking for a way to write a master script that > monitors system CPU and disk i/o and when there is capacity > launch another script from a pool of scripts so that I'm getting > max utilization from my hardware, eg. so that I'm running the max > number of scripts I can at any one point in time without > overwhelming the system. > The server in question is currently running Windows 2008 > Enterprise, but I have the option to switch to a 64-bit version > of Linux if there are benefits to doing so. > Thank you, > Malcolmm > -- > http://mail.python.org/mailman/listinfo/python-list From martin at v.loewis.de Wed Dec 10 01:10:52 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 10 Dec 2008 07:10:52 +0100 Subject: Compiling and installing python 2.5.2 with Visual C++ 2008 In-Reply-To: References: Message-ID: <493f5d6c$0$9126$9b622d9e@news.freenet.de> > --------------------------------------------------------- > ... > error: Python was built with Visual Studio 2003; > extensions must be built with a compiler than can generate compatible binaries. > Visual Studio 2003 was not found on this system. If you have Cygwin installed, > you can try compiling with MingW32, by passing "-c mingw32" to setup.py. > --------------------------------------------------------- > > And because I've been compiling everything needed by pivy (Coin, Qt, > SoQt, PyQt) with visual c++ 8, I decided to recompile python itself. There isn't a real installation procedure. You just copy the files by hand into the places where they belong. In the specific case, overwriting all .exe, .dll, and .pyd files in an installed directory should be sufficient. Regards, Martin From google at mrabarnett.plus.com Tue Dec 16 10:25:50 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 16 Dec 2008 15:25:50 +0000 Subject: Generator slower than iterator? In-Reply-To: References: Message-ID: <4947C87E.4020002@mrabarnett.plus.com> Federico Moreira wrote: > Hi all, > > Im parsing a 4.1GB apache log to have stats about how many times an ip > request something from the server. > > The first design of the algorithm was > > for line in fileinput.input(sys.argv[1:]): > ip = line.split()[0] > if match_counter.has_key(ip): > match_counter[ip] += 1 > else: > match_counter[ip] = 1 > > And it took 3min 58 seg to give me the stats > > Then i tried a generator solution like > > def generateit(): > for line in fileinput.input(sys.argv[1:]): > yield line.split()[0] > > for ip in generateit(): > ...the same if sentence > > Instead of being faster it took 4 min 20 seg > > Should i leave fileinput behind? > Am i using generators with the wrong aproach? > Your first design is already simple to understand, so I think that using a generator isn't necessary (and probably isn't worth the cost!). You might want to try defaultdict instead of dict to see whether that would be faster: from collections import defaultdict match_counter = defaultdict(int) for line in fileinput.input(sys.argv[1:]): ip = line.split()[0] match_counter[ip] += 1 From google at mrabarnett.plus.com Sat Dec 20 19:17:39 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 21 Dec 2008 00:17:39 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <59153e28-bf86-4158-96d9-23aa5b9f0205@j35g2000yqh.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> <59153e28-bf86-4158-96d9-23aa5b9f0205@j35g2000yqh.googlegroups.com> Message-ID: <494D8B23.8040100@mrabarnett.plus.com> r wrote: > Walter, > > Would you be kind enough to translate this code to the new syntax? > >>>> s = 'python' >>>> n = 12 >>>> f = 1.333333333 >>>> '%s %05d %0.2f' %(s,n,f) > 'python 00012 1.33' > > i want to see how casting is handled. Thanks > >>> '{0} {1:05} {2:.2}'.format(s, n, f) 'python 00012 1.3' From rdmurray at bitdance.com Sun Dec 14 05:46:51 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Sun, 14 Dec 2008 05:46:51 -0500 (EST) Subject: subprocess to pipe through several processes? In-Reply-To: References: Message-ID: On Sat, 13 Dec 2008 at 23:05, Neal Becker wrote: > How would I use suprocess to do the equivalent of: > > cat - | program_a | program_b Have you tried extending the pipe example from the manual? http://docs.python.org/library/subprocess.html#replacing-shell-pipeline --David From manu3d at gmail.com Thu Dec 18 08:49:49 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 18 Dec 2008 05:49:49 -0800 (PST) Subject: re.match() performance Message-ID: <27c0f622-782d-4d7f-9469-45ca1cff59ee@q26g2000prq.googlegroups.com> Hi everybody! I've written the code below to test the differences in performance between compiled and non-compiled regular expression matching but I don't quite understand the results. It appears that the performance difference is only around 2%, even if I run the ------------ import re import time ## Setup pattern = "(.*)" compiledPattern = re.compile(pattern) longMessage = ""+ "a" * 100000 +"" numberOfRuns = 1000 ## TIMED FUNCTIONS startTime = time.clock() for i in range(0, numberOfRuns): re.match(pattern, longMessage) patternMatchingTime = time.clock() - startTime startTime = time.clock() for i in range(0, numberOfRuns): compiledPattern.match(longMessage) compiledPatternMatchingTime = time.clock() - startTime ratioCompiledToNot = compiledPatternMatchingTime / patternMatchingTime ## PRINT OUTS print("") print(" Pattern Matching Time: " + str(patternMatchingTime)) print("(Compiled) Pattern Matching Time: " + str (compiledPatternMatchingTime)) print("") print("Ratio Compiled/NotCompiled: " + str(ratioCompiledToNot)) print("") From 5lvqbwl02 at sneakemail.com Sun Dec 7 02:29:02 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Sat, 6 Dec 2008 23:29:02 -0800 (PST) Subject: Brain going crazy with recursive functions Message-ID: <181d6cf8-8df3-46d4-9d21-197d34b3de87@d36g2000prf.googlegroups.com> I'm trying to solve the 9-tile puzzle using as functional an approach as possible. I've recently finished reading SICP and am deliberately avoiding easy python-isms for the more convoluted scheme/functional methods. The following function is trivial to do with for loops and directly accessing arrays with [] syntax. I'm trying to limit myself to the types of idioms/semantics one finds in minimal scheme, such as in SICP. I want eventually to port this to scheme, but I know python better, so that's where I'm starting. My current problem is the following. The 9-tile puzzle consists of a list of lists like this [[1,2,3],[4,5,6],[7,8,0]], where the numbers can be jumbled up. I'm looking for the location of the zero using *only* recursion and operators that are similar to car/cdr. The return value should be the row,col of the zero. For example above the return value would be (2,2). I'm also trying to define a single "linear_search(...)" function which does the search for within the row (an inner list above) and within the whole list. linear_search takes as an argument a "truth_function" which does the actual work. What's tricky is that the truth function for the array-as-a-whole is also the linear_search for a row. Once I'm in linear_search for the array, I also call linear_search for each row. The problem is the line where it says acc.insert(0,idx) looks fishy to me. It works fine and returns the row,col of the location of the zero tile, but it seems to be mutating a variable, and that's the thing I'm trying to avoid. In a sense, it's not hard enough and python is making this too easy :) (although it took a bit of mind-wrenching to get to this point. Recursion makes you either dumber or smarter, I'm not sure which). How do I accumulate the inner value of the search so it pops out at the end, without resorting to a mutable variable? I did a bit of search and the word "monad" came up, but I'm not sure what that is (I know it relates to haskell and some other purely functional stuff, but I get very lost when trying to read that stuff). def linear_search(array, truth_func, acc): # Goes through each element of array and applies truth_func. # Returns index if found, otherwise returns None def linear_search_iter(idx, truth_func, arr, acc): if arr: tf = truth_func(arr[0]) if tf or type(tf) is int: acc.insert(0,idx) return idx, acc+[idx] else: return linear_search_iter(idx+1, truth_func, arr[1:], acc) return linear_search_iter(0, truth_func, array, acc) def locate_zero(p): # Locates empty tile. Returns (r,c) tuple def find_zero_in_row(row): return linear_search(row, lambda x: x==0, acc) acc = [] ls = linear_search(p, find_zero_in_row, acc) print acc return acc locate_zero(def linear_search(array, truth_func, acc): # Goes through each element of array and applies truth_func. # Returns index if found, otherwise returns None def linear_search_iter(idx, truth_func, arr, acc): if arr: tf = truth_func(arr[0]) if tf or type(tf) is int: acc.insert(0,idx) return idx, acc+[idx] else: return linear_search_iter(idx+1, truth_func, arr[1:], acc) return linear_search_iter(0, truth_func, array, acc) def locate_zero(p): # Locates empty tile. Returns (r,c) tuple def find_zero_in_row(row): return linear_search(row, lambda x: x==0, acc) acc = [] ls = linear_search(p, find_zero_in_row, acc) print acc return acc locate_zero([[5, 3, 4], [2, 0, 1], [8, 6, 7]]) returns the correct value of [1,1]. Any suggestions please? thanks Michael From Slaunger at gmail.com Mon Dec 1 11:18:09 2008 From: Slaunger at gmail.com (Slaunger) Date: Mon, 1 Dec 2008 08:18:09 -0800 (PST) Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> Message-ID: On 1 Dec., 16:30, Nick Craig-Wood wrote: > > I wouldn't use __getattr__ unless you've got lots of attributes to > overload. ?__getattr__ is a recipe for getting yourself into trouble > in my experience ;-) > > Just do it like this... > > class PayloadOnDemand(object): > ? ? ? def __init__(self, a_file, a_file_position): > ? ? ? ? ? self._data = None > ? ? ? ? ? self.f = a_file > ? ? ? ? ? self.file_position = a_file_position > > ? ? ? @property > ? ? ? def data(self): > ? ? ? ? ? if self._data is None: > ? ? ? ? ? ? ? self._data = self.really_read_the_data() > ? ? ? ? ? return self._data > > then you'll have a .data attribute which when you read it for the > first time it will populate itself. > > If None is a valid value for data then make a sentinel, eg > > class PayloadOnDemand(object): > ? ? ? sentinel = object() > > ? ? ? def __init__(self, a_file, a_file_position): > ? ? ? ? ? self._data = self.sentinel > ? ? ? ? ? self.f = a_file > ? ? ? ? ? self.file_position = a_file_position > > ? ? ? @property > ? ? ? def data(self): > ? ? ? ? ? if self._data is self.sentinel: > ? ? ? ? ? ? ? self._data = self.really_read_the_data() > ? ? ? ? ? return self._data > > -- > Nick Craig-Wood --http://www.craig-wood.com/nick- Skjul tekst i anf?rselstegn - > > - Vis tekst i anf?rselstegn - OK, I get it. In my case I have four attributes to create when one of them is accessed, I do not know if that is a lot of attributes;-) One thing I like about the __getattr__ is that it is only called that one single time where an attempt to read a data attribute fails because the attribute name is not defined in the __dict__ of the object. With the property methology you do the value check on each get, which does not look as "clean". The property methology is also a little less arcane I guess for less experienced Python programmers to understand when re-reading the code. What kind of trouble are you referring to in __getattr__? Is it recursive calls to the method on accessing object attributes in that method itself or other complications? On a related issue, thank you for showing me how to use @property as a decorator - I was not aware of that possibility, just gotta understand how to decorate a setter and delete method as well, but I should be able to look that up by myself... -- Slaunger From sjmachin at lexicon.net Fri Dec 12 15:26:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 12 Dec 2008 12:26:34 -0800 (PST) Subject: (Very Newbie) Problems defining a variable References: <878wqlz27z.fsf@daycos.com> <7f7e8811-4043-40d4-8aa4-f44e1d255632@o4g2000pra.googlegroups.com> Message-ID: <90ef0df1-c4ee-4a69-a0d2-41b69d23058d@k36g2000pri.googlegroups.com> On Dec 13, 6:49?am, "Tim Rowe" wrote: > 2008/12/12 John Machin : > > > (4) in practice, the "default" action would not be "return 0.0"; > > perhaps something along these lines: > > > if balance < -overdraft_limit: > > ? raise Exception(...) > > That's more likely to be in the withdrawal routine You'd certainly hope that this test would appear in the withdrawal routine. > (and is probably > best not handled as an exception, because it's pretty much normal > flow). If a bank provided a service such as the one implemented by > this program, there'd be no need for it to know about overdraft limits > because it's not making actual transactions. Why would they increase > coupling unneccesarily? Yeah, you're right, much easier to return 0% interest on a negative balance [customers happy; no wear and tear on the call centre] and hope that anomalies are checked somewhere else *and* that somebody #1 is tasked with actioning the anomaly reports and that somebody #2 is keeping an eye on somebody #1. From exarkun at divmod.com Tue Dec 16 23:03:45 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 16 Dec 2008 23:03:45 -0500 Subject: Can anyone suggest a good HTTP/1.1 web client? In-Reply-To: <412038d6-81c0-4615-aab5-d3cea4093dfc@p2g2000prn.googlegroups.com> Message-ID: <20081217040345.20272.1064231101.divmod.quotient.22045@ohm> On Tue, 16 Dec 2008 18:47:41 -0800 (PST), Kottiyath wrote: > >> If you'd like to help out with the new Twisted HTTP client, that would be >> wonderful. ?Even if you can just try it out and report any problems you run >> into, that would be immensely helpful. >> >> Jean-Paul > >I would love to help out with the client. But, I am extremely tied up >at the current moment. I would be able to provide any sort of >meaningful contribution only after ~a month. I can surely try this out >and upload any bugs in the ticket you mentioned. > >Also, is there any planned date for persistent connections? If not, >that will be the first thing I will be working on after my assignment >is over - since it increasingly looks like it is essential to my system >(actually, any REST applications). Hard to predict when it will be done. Sometime in January is a possibility, but that's a guess, not a promise. :) Jean-Paul From federico at linux.com.uy Tue Dec 16 11:48:54 2008 From: federico at linux.com.uy (Federico Moreira) Date: Tue, 16 Dec 2008 13:48:54 -0300 Subject: Generator slower than iterator? In-Reply-To: <4947D788.3040508@islandtraining.com> References: <4947D788.3040508@islandtraining.com> Message-ID: The defaultdict option looks faster than the standard dict (20 secs aprox). Now i have: ############################# import fileinput import sys from collections import defaultdict match_counter = defaultdict(int) for line in fileinput.input(sys.argv[1:]): match_counter[line.split()[0]] += 1 ############################# About generators, now i get the idea of when use them and when not. Thanks MRAB, Lie and Gary. Now not only is faster but also cleaner and easy to understand =) -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Fri Dec 5 14:27:19 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 5 Dec 2008 11:27:19 -0800 (PST) Subject: slow Python 3.0 write performance? References: Message-ID: On Dec 5, 12:54?pm, Istvan Albert wrote: > Could someone run the code below on both Python 2.5 and 3.0 > > For me (on Windows) it runs over 7 times slower with Python 3.0 > > import time > > lo, hi, step = 10**5, 10**6, 10**5 > > # writes increasingly more lines to a file > for N in range(lo, hi, step): > ? ? fp = open('foodata.txt', 'wt') > ? ? start = time.time() > ? ? for i in range( N ): > ? ? ? ? fp.write( '%s\n' % i) > ? ? fp.close() > ? ? stop = time.time() > ? ? print ( "%s\t%s" % (N, stop-start) ) Ran on Windows XP virtual machine: 3.0 output: 100000 0.889999866486 200000 1.79699993134 300000 2.875 400000 3.73399996758 500000 4.71899986267 600000 5.59400010109 700000 7.04699993134 800000 7.31299996376 900000 8.375 2.5.2 output: 100000 0.156000137329 200000 0.296999931335 300000 0.640000104904 400000 0.640000104904 500000 0.78200006485 600000 0.952999830246 700000 1.13999986649 800000 1.25 900000 1.42199993134 Slowness in this exercise is confirmed on Windows XP. Mike From robert.kern at gmail.com Tue Dec 16 20:59:37 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 16 Dec 2008 17:59:37 -0800 Subject: Free place to host python files? In-Reply-To: References: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> <32599660-2393-4e18-8c48-05d64bccbbc1@t26g2000prh.googlegroups.com> Message-ID: feba wrote: > Stuff like code.google, sf.net, are more oriented towards serious > development, not just holding random apps, aren't they? There are plenty of "projects" on them which are just personal sandboxes like you are asking for. I recommend code.google.com. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sumerc at gmail.com Thu Dec 4 12:39:59 2008 From: sumerc at gmail.com (k3xji) Date: Thu, 4 Dec 2008 09:39:59 -0800 (PST) Subject: Python Runtime Method Call Binding References: <0147f396$0$20670$c3e8da3@news.astraweb.com> Message-ID: <9f2308eb-9eb9-4431-8af7-975c3e054849@e18g2000yqo.googlegroups.com> On Dec 4, 5:48?pm, Steven D'Aprano wrote: > On Thu, 04 Dec 2008 06:23:28 -0800, k3xji wrote: > > Hi, > > > Is there a way to hook a function call in python? I know __getattr__ is > > doing for variables, > > What do you mean "variables"? Do you mean attributes? > > > it is giving us a chance before a field is > > initialized. > > What field? Is a field the same as a variable, or something else? > > > Do we have same functionality for methods? > > Yes, methods are attributes too, they are reached by the exact same > mechanism as any other attribute. > > Any object with a __call__ method can be called. Normally you create > objects with a __call__ method by using def or lambda. > > > Example: > > > class Foo(object): > > ? ? def __call_method__(self, ...) # just pseudo > > ? ? ? ? print 'A method is called in object...' > > > f = Foo() > > f.test_method() > > > I think you understand my point. > > I wish I did. It might have helped if you actually showed the expected > output of your "test_method", instead of expecting us to *guess* what you > expect to happen. > > I'm going to guess what you mean, and show you one possible solution. > Read it carefully: it shows three examples of __getattr__, starting from > the simplest to the relatively complicated. > > class Parrot(object): > ? ? def __getattr__(self, name): > ? ? ? ? if name == "colour": > ? ? ? ? ? ? return "red" > ? ? ? ? elif name == "talk": > ? ? ? ? ? ? return lambda x: "Hi, I'm %s the talking parrot" % x > ? ? ? ? elif name == "speak": > ? ? ? ? ? ? class Birdy(object): > ? ? ? ? ? ? ? ? def __init__(self, name): > ? ? ? ? ? ? ? ? ? ? self.name = name > ? ? ? ? ? ? ? ? def __call__(self): > ? ? ? ? ? ? ? ? ? ? return "I'm the talking Parrot %s" % self.name > ? ? ? ? ? ? return Birdy('Fred') > ? ? ? ? else: > ? ? ? ? ? ? raise AttributeError > > And in use: > > >>> p = Parrot() > >>> p.colour > 'red' > >>> p.talk ?# get the attribute "talk" > > at 0x81fab1c> > > >>> p.talk("Fred") ?# call the attribute (method) "talk" > > "Hi, I'm Fred the talking parrot" > > >>> p.speak > > <__main__.Birdy object at 0x820076c>>>> p.speak() > > "I'm the talking Parrot Fred" > > -- > Steven Thank you for all the answers. I have given a bad example but got great answers. So let me clarify my problem again. I think "decorator of Bruno" and the "third example of Steven" is what I am looking for. Steven you embed a callable object in __getattr__ to accomplish what I want. But my problem: My problem is that I have a very-multithreaded application that I want to profile dynamically. And I want to see how many functions are called/how much time spent on them.(I tried Profilers but lack of multithreading support I cannot do what I want to do.) So, from your answers above, if I use a decorator I will not be able to understand that the function has finished processing. And if I use the "callable object" Steven's third solution, I will need to convert every function I want to profile to a callable object. I think problem is clarified now. Maybe you have other suggestions? Thanks, From rt8396 at gmail.com Tue Dec 30 11:15:17 2008 From: rt8396 at gmail.com (r) Date: Tue, 30 Dec 2008 08:15:17 -0800 (PST) Subject: Parsing Excel spreadsheets References: <6a54de23-bea4-40c7-ad7c-22c6eba4bd8a@z6g2000pre.googlegroups.com> Message-ID: <4894d0fe-a238-4675-9e79-0b0755c001e8@y1g2000pra.googlegroups.com> On Dec 30, 10:07?am, "andyh... at gmail.com" wrote: > Hi, > > Can anybody recommend an approach for loading and parsing Excel > spreadsheets in Python. Any well known/recommended libraries for this? > > The only thing I found in a brief search washttp://www.lexicon.net/sjmachin/xlrd.htm, > but I'd rather get some more input before going with something I don't > know. > > Thanks, > Andy. xlrd(read only) also see pyExcelerator From Russ.Paielli at gmail.com Sat Dec 6 19:42:15 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 6 Dec 2008 16:42:15 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> Message-ID: <845f784f-8dcd-4f18-ae78-3f528f179b3e@r15g2000prd.googlegroups.com> > But it's ugly. ?No amount of rationalization will make it not ugly. The dollar sign is ugly? I beg to differ. From stef.mientki at gmail.com Sun Dec 21 19:24:38 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 22 Dec 2008 01:24:38 +0100 Subject: Beep In-Reply-To: References: Message-ID: <494EDE46.20602@gmail.com> Jeffrey Barish wrote: > I use sys.stdout.write('\a') to beep. It works fine on Kubuntu, but not on > two other platforms (one of which is Ubuntu). I presume that the problem > is due to a system configuration issue. Can someone point me in the right > direction? Thanks. > I started a thread about this issue acouple of weeks ago, look for "how to get a beep, OS independent ?" The best way seems to use something like PyGame. cheers, Stef From andre.roberge at gmail.com Sun Dec 7 08:39:26 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sun, 7 Dec 2008 05:39:26 -0800 (PST) Subject: python book for non technical absolute beginner References: <493a7c6a$0$973$426a34cc@news.free.fr> Message-ID: On Dec 6, 9:21?am, News123 wrote: > Hi, > > One of my 'non technical' friends complained about knowing nothing at > all about programming (though using computers regularly for mails / web > browsing / googling and downloading / cropping photos ) > > He wants to play a little with programming to stimulate parts of his > otehrwise idle brain cells. ;-) Normally it's more the social science / > linguistic parts being exercised, > > I thought python might be a nice language for this > > No my question does anybody know a nice beginners book (or a learning CD > or on line tutorial)? Ideally it shouldn't be too serious and have a lot > of small nice mini-examples > > thanks in advance for any suggestions hints > > bye > > N For something completely different, try http://rur-ple.sourceforge.net/ It's Karel the robot, using only Python, and comes with a whole bunch of lessons and exercises. Andr? From torppa at staff.megabaud.fi Mon Dec 29 11:30:42 2008 From: torppa at staff.megabaud.fi (Jarkko Torppa) Date: Mon, 29 Dec 2008 16:30:42 GMT Subject: multiprocessing vs thread performance References: Message-ID: On 2008-12-29, mk wrote: > janislaw wrote: > >> Ah, so there are 100 processes at time. 200secs still don't sound >> strange. > > I ran the PEP 371 code on my system (Linux) on Python 2.6.1: > > Linux SLES (9.156.44.174) [15:18] root ~/tmp/src # ./run_benchmarks.py > empty_func.py > > Importing empty_func > Starting tests ... > non_threaded (1 iters) 0.000005 seconds > threaded (1 threads) 0.000235 seconds > processes (1 procs) 0.002607 seconds > > non_threaded (2 iters) 0.000006 seconds > threaded (2 threads) 0.000461 seconds > processes (2 procs) 0.004514 seconds > > non_threaded (4 iters) 0.000008 seconds > threaded (4 threads) 0.000897 seconds > processes (4 procs) 0.008557 seconds > > non_threaded (8 iters) 0.000010 seconds > threaded (8 threads) 0.001821 seconds > processes (8 procs) 0.016950 seconds > > This is very different from PEP 371. It appears that the PEP 371 code > was written on Mac OS X. On the PEP371 it says "All benchmarks were run using the following: Python 2.5.2 compiled on Gentoo Linux (kernel 2.6.18.6)" On my iMac 2.3Ghz dualcore. python 2.6 iTaulu:src torppa$ python run_benchmarks.py empty_func.py Importing empty_func Starting tests ... non_threaded (1 iters) 0.000002 seconds threaded (1 threads) 0.000227 seconds processes (1 procs) 0.002367 seconds non_threaded (2 iters) 0.000003 seconds threaded (2 threads) 0.000406 seconds processes (2 procs) 0.003465 seconds non_threaded (4 iters) 0.000004 seconds threaded (4 threads) 0.000786 seconds processes (4 procs) 0.006430 seconds non_threaded (8 iters) 0.000006 seconds threaded (8 threads) 0.001618 seconds processes (8 procs) 0.012841 seconds With python2.5 and pyProcessing-0.52 iTaulu:src torppa$ python2.5 run_benchmarks.py empty_func.py Importing empty_func Starting tests ... non_threaded (1 iters) 0.000003 seconds threaded (1 threads) 0.000143 seconds processes (1 procs) 0.002794 seconds non_threaded (2 iters) 0.000004 seconds threaded (2 threads) 0.000277 seconds processes (2 procs) 0.004046 seconds non_threaded (4 iters) 0.000005 seconds threaded (4 threads) 0.000598 seconds processes (4 procs) 0.007816 seconds non_threaded (8 iters) 0.000008 seconds threaded (8 threads) 0.001173 seconds processes (8 procs) 0.015504 seconds -- Jarkko Torppa, Elisa From pruebauno at latinmail.com Thu Dec 4 13:43:03 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Thu, 4 Dec 2008 10:43:03 -0800 (PST) Subject: Good introductory book? References: Message-ID: On Dec 3, 9:44 am, "Ken D'Ambrosio" wrote: > Hi, all. I'm getting ready to do some projects in Python, and I've cut my > teeth a little bit, but I've found the "Learning|Programming Python" books > from O'Reilly to be more-or-less useless (to my surprise -- I'm usually an > O'Reilly fan). I really, really like "Python Essential Reference", but > it's -- well, more of a reference than an intro. So, an introductory text > that actually assumes some previous programming experience (as opposed to > "Learning Python" which must be the most slowly-paced programming book > ever) would be terrific. > > Thanks for your suggestions! > > -Ken I had the same experience as you had and almost gave up on Python. I had programmed in other languages before and found the Programming Python book very tedious to read. I just wanted to learn the syntax and library to start writing my own stuff. Luckily, I found Guido's 12 page tutorial (http://www.python.org/doc/2.5.2/tut/tut.html) and that plus the online library reference and Google was everything I ever needed since then. That said I looked at O'Reilly's "Python in a Nutshell" and I thought it was really good. It is a mix between introduction, language and library reference. I should have gotten that instead of Learning/Programming when I started and I probably would have been much happier. From Graham.Dumpleton at gmail.com Sat Dec 6 05:34:07 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Sat, 6 Dec 2008 02:34:07 -0800 (PST) Subject: mod_python and files directory References: Message-ID: On Dec 6, 1:52?am, "mete bilgin" wrote: > Hi all, > I try to make a websevice with python and mod_python. ? try to make a po > files, but i can not reach them in the page. When i ask the page like " > os.listdir('.') " but i want to get files directory, what can i do? sorry > for my bad describe of that. Thanks a lot... The current working directory in Apache can be anything. You must supply an absolute path to all directories/files you are trying to access/use. Graham From callen314 at gmail.com Tue Dec 2 15:44:10 2008 From: callen314 at gmail.com (Craig Allen) Date: Tue, 2 Dec 2008 12:44:10 -0800 (PST) Subject: Confused about class relationships References: Message-ID: <5d4b15f9-3aa1-4370-b8f8-6393b0b5fa39@40g2000prx.googlegroups.com> what you have is a totally acceptable factory system. Not sure why you are using a generator, but that's another matter. I agree with the previous replies regarding inheritance... this is not a case for inheritance. You could, however, have Bar be a borg with the Bar factory built in as a class method to the Bar class itself if you want the whole job done by one component. Questions to lead to or away from that: will Engine every create things besides Bars? From steve at REMOVE-THIS-cybersource.com.au Wed Dec 17 20:15:36 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Dec 2008 01:15:36 GMT Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> <175fa5d5-f345-47b8-a686-e0e36e1b99e9@q37g2000vbn.googlegroups.com> <39eec12b-d7cc-44b5-aa65-bfa559dcba05@n33g2000pri.googlegroups.com> Message-ID: <01599b9a$0$20656$c3e8da3@news.astraweb.com> On Wed, 17 Dec 2008 10:20:21 -0800, walterbyrd wrote: > On Dec 17, 10:00?am, r wrote: >> When writing >> procedural code how would you like it if vars inside functions were >> automatically global. Your code with be blowing chunks in no time. > > That was my point - I consider python's ordinary use of lexical scoping > to be a good thing, and I was wondering why this "good thing" was not > used in classes, as well as outside of classes. But it is. You're mistaking lexical scoping for object attribute access. The rules for lexical scoping inside a class are (almost) the same as they are for inside a function: def parrot(breed): def message(colour): return "The %s %s has beautiful plumage." % (breed, colour) return message("Blue") class Parrot: def parrot(self, breed): def message(colour): return "The %s %s has beautiful plumage." % (breed, colour) return message("Blue") And in use: >>> parrot("Norwegian") 'The Norwegian Blue has beautiful plumage.' >>> p = Parrot() >>> p.parrot("Swedish") 'The Swedish Blue has beautiful plumage.' Notice that to have lexical scoping work, you actually have to nest the functions. Otherwise they are in different scopes. This might lead you believe you can do this: class Parrot2: colour = "Blue" def parrot(self, breed): return "The %s %s has beautiful plumage." % (breed, colour) >>> p = Parrot2() >>> p.parrot("Norwegian") Traceback (most recent call last): File "", line 1, in File "", line 4, in parrot NameError: global name 'colour' is not defined What's going on? Why doesn't the parrot method see the name "colour" in the class scope? The reason is that the class scope is deliberately left out of the nested scope chain. This was a design decision from when nested scopes were introduced: "An alternative would have been to allow name binding in class scope to behave exactly like name binding in function scope. This rule would allow class attributes to be referenced either via attribute reference or simple name. This option was ruled out because it would have been inconsistent with all other forms of class and instance attribute access, which always use attribute references. Code that used simple names would have been obscure." http://www.python.org/dev/peps/pep-0227/ So inside the method, you need to refer to Parrot.colour (or thanks to the rules of attribute inheritance, self.colour). Classes could be closures, but that could radically change the way methods and classes work. Depending on design decisions, it might require huge changes to the Python compiler. How would it change the existing lexical scoping in factory functions? def factory(colour): class Parrot: def parrot(self, breed): return "The %s %s has beautiful plumage." % (breed, colour) return Parrot >>> redparrot = factory("Red")() >>> redparrot.parrot("Swedish") 'The Swedish Red has beautiful plumage.' Consider a hypothetical Python with classes included in the lexical scoping: class Parrot3: colour = "Blue" def parrot(self): colour = "Red" What should method parrot do? I can think of at least three possibilities: * create a local name colour inside the method scope; * change the class attribute Parrot3.colour to "Red"; * create an instance attribute self.colour. Whatever solution you come up with, there is potential inconsistency with other parts of the language. -- Steven From skip at pobox.com Sat Dec 27 16:09:04 2008 From: skip at pobox.com (skip at pobox.com) Date: Sat, 27 Dec 2008 15:09:04 -0600 Subject: [2.4.4] creating a datetime.datetime from an XML xs:dateTime In-Reply-To: <5fa6c12e0812271255l4f4893e8w9f96e9ace73ea50c@mail.gmail.com> References: <5fa6c12e0812271208x4baccaedk262e51becb6e2076@mail.gmail.com> <18774.36465.346262.883182@montanaro-dyndns-org.local> <5fa6c12e0812271255l4f4893e8w9f96e9ace73ea50c@mail.gmail.com> Message-ID: <18774.39280.365281.768302@montanaro-dyndns-org.local> martin> is that http://labix.org/python-dateutil, I'll have a look at martin> it. Yup. PyPI: http://pypi.python.org/pypi/python-dateutil/1.4.1 Skip From kermit.mei at gmail.com Thu Dec 11 13:03:46 2008 From: kermit.mei at gmail.com (Kermit Mei) Date: Fri, 12 Dec 2008 02:03:46 +0800 Subject: How can I understan the "for" here? In-Reply-To: <20081211100312.9d68eeab.darcy@druid.net> References: <49412744.8040301@gmail.com> <20081211100312.9d68eeab.darcy@druid.net> Message-ID: <49415602.8030009@gmail.com> D'Arcy J.M. Cain wrote: > On Thu, 11 Dec 2008 22:44:20 +0800 > Kermit Mei wrote: > >> >>> ["%s=%s" % (k, v) for k, v in params.items()] >> ['pwd=secret', 'database=master', 'uid=sa', 'server=mpilgrim'] >> >> I can't understand the second sentence because of the "for ... in". >> I consider that the syntactics of "for" should be: >> >> for k,v in params.items(): >> > > I think you are binding ':' here too tightly to the 'for' construct in > your mind. The for construct is "for in " > which can be used as : in block > constructs. The above is not a block construct but a list > comprehension so it follows different rules. > > Yes, I see. Thanks you all. From dotancohen at gmail.com Wed Dec 3 21:13:51 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 4 Dec 2008 04:13:51 +0200 Subject: RELEASED Python 3.0 final In-Reply-To: References: Message-ID: <880dece00812031813t78ec560cy69dd3710fbd4c2a9@mail.gmail.com> On this page: http://www.python.org/download/releases/3.0/ The text "This is a proeuction release" should probably read "This is a production release". It would give a better first impression :) -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-??-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From gregsaundersemail at gmail.com Sun Dec 14 21:22:43 2008 From: gregsaundersemail at gmail.com (Greg) Date: Sun, 14 Dec 2008 18:22:43 -0800 (PST) Subject: Python User Group - Calgary, Alberta, Canada Message-ID: <097b1d93-cf9d-42e9-a2a2-2fb3b231970e@w24g2000prd.googlegroups.com> Hi all, this is just a brief announcement regarding the resurrection of the Python User Group in Calgary, Alberta, Canada. Our first meeting will be on Wednesday, January 14, 2009. Our official web site (albeit requiring a lot of work): http://www.pythoncalgary.com/ We have a mailing list set up at: http://groups.google.ca/group/pythoncalgary/ Calendar of Events: http://www.google.com/calendar/hosted/pythoncalgary.com/embed?src=admin%40pythoncalgary.com&ctz=America/Edmonton If you live in our around the Calgary area, please join the mailing list and consider coming to our inaugural meeting in January. Venue TBA. Thanks Greg From robert.kern at gmail.com Sun Dec 7 16:32:53 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 07 Dec 2008 15:32:53 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Rasmus Fogh wrote: > Current behaviour is both inconsistent and counterintuitive, as these > examples show. > >>>> x = float('NaN') >>>> x == x > False Blame IEEE for that one. Rich comparisons have nothing to do with that one. >>>> ll = [x] >>>> x in ll > True >>>> x == ll[0] > False > >>>> import numpy >>>> y = numpy.zeros((3,)) >>>> y > array([ 0., 0., 0.]) >>>> bool(y==y) > Traceback (most recent call last): > File "", line 1, in > ValueError: The truth value of an array with more than one element is > ambiguous. Use a.any() or a.all() >>>> ll1 = [y,1] >>>> y in ll1 > True >>>> ll2 = [1,y] >>>> y in ll2 > Traceback (most recent call last): > File "", line 1, in > ValueError: The truth value of an array with more than one element is > ambiguous. Use a.any() or a.all() > > Can anybody see a way this could be fixed (please)? I may well have to > live with it, but I would really prefer not to. Make a concrete proposal for fixing it that does not break backwards compatibility. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From gagsl-py2 at yahoo.com.ar Fri Dec 26 07:08:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 26 Dec 2008 10:08:02 -0200 Subject: SyntaxError: encoding problem: with BOM References: <6res8tF1do1sU1@mid.uni-berlin.de> <400f176b-bd9a-4f26-b01b-1aa7c7dcf5ac@z6g2000pre.googlegroups.com> <6rf6m1F1e0f8U1@mid.uni-berlin.de> <26e21f3f-ded1-48ca-8897-2ebd05dd07ad@w39g2000prb.googlegroups.com> Message-ID: En Thu, 25 Dec 2008 11:55:16 -0200, NoName escribi?: > Error > ---- > C:\Documents and Settings\Ra\??????? ????>11.py > File "", line 1 > SyntaxError: encoding problem: with BOM > > No error > ---- > C:\Documents and Settings\Ra\??????? ????>python 11.py > test > > Error when russian symbols in full path to py-script. > Is it Python bug? or i need to modify some registry keys? Yes, it's a bug. The encoding declaration may be anything, ascii, even an inexistent codec will trigger the bug. Any non-ascii character in the script name or path provokes then a SyntaxError when the script is executed directly. As a workaround, avoid using any Russian characters in directory names or script file names, or invoke them always using "python xxx.py", not directly. > OS: WinXP SP3 Russian. > Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit > (Intel)] on win32 My tests were on WinXP SP3 Spanish. See http://bugs.python.org/issue4747 -- Gabriel Genellina From honey33145 at gmail.com Thu Dec 4 00:55:41 2008 From: honey33145 at gmail.com (navneet khanna) Date: Thu, 4 Dec 2008 11:25:41 +0530 Subject: Access functions in dll class Message-ID: Hello Everybody I am able to import the dll and able to access the class of the dll. But when I am trying to access the methods in the dll its showing error. #Class1 is the class in dll and next is the function. Class1.Bin_To_Dec("11") Traceback (most recent call last): File "", line 1, in Class1.Bin_To_Dec("11") TypeError: No method matches given arguments Please help me to find out where am i wrong? Do I need to create object of dll class and then access it? If yes then how can I access it? Thanks Navneet -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Fri Dec 12 14:36:12 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 12 Dec 2008 19:36:12 +0000 Subject: Removing None objects from a sequence References: Message-ID: alex23 writes: > Rather than a list comprehension, use a generator expression: > > for item in (x for x in sequence if x is not None): > do_something(x) I much prefer for item in sequence: if x is not None: do_something(x) -- Arnaud From petite.abeille at gmail.com Sun Dec 14 08:07:50 2008 From: petite.abeille at gmail.com (Petite Abeille) Date: Sun, 14 Dec 2008 14:07:50 +0100 Subject: [OT] Alternative web server scripting language Message-ID: <3D39640F-3248-428F-B92A-2101A225C8E0@gmail.com> Hello, Now that Lua [1] appears as a native scripting language in more [2] and more [3] mainstream web servers, here is an example of a web server written in Lua: http://svr225.stepx.com:3388/a The wiki demo sports content from the 2008/9 Wikipedia Selection, containing about 5500 articles, accessible through full text search: http://svr225.stepx.com:3388/search?q=python An index, timeline and recent changes navigation is provided to facilitate article retrieval: http://svr225.stepx.com:3388/index/a http://svr225.stepx.com:3388/date/2008 http://svr225.stepx.com:3388/recent The wiki content is accessible as an Atom feed: feed://svr225.stepx.com:3388/search?q=brazil feed://svr225.stepx.com:3388/index/a feed://svr225.stepx.com:3388/date/2008 feed://svr225.stepx.com:3388/recent Or as a WebDAV repository: dav://svr225.stepx.com:3388/ Kind regards, -- PA. http://alt.textdrive.com/nanoki/ [1] http://www.lua.org/about.html [2] http://svn.apache.org/repos/asf/httpd/mod_wombat/trunk/README [3] http://redmine.lighttpd.net/wiki/1/Docs:ModMagnet From google at mrabarnett.plus.com Sun Dec 7 21:40:58 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 08 Dec 2008 02:40:58 +0000 Subject: Infinite hangup when using CGI sys.stdin.read() In-Reply-To: References: Message-ID: <493C893A.5080103@mrabarnett.plus.com> pacsciadmin at gmail.com wrote: > I maintain a CGI framework named PyTin, and while previously the > developer was only allowed to access GET and POST by cgi.FieldStorage. > I'm trying to add code to my request gatherer that looks like: > > 1. request.rawpost = StringIO() # Just normal StringIO > 2. request.rawpost.write(sys.stdin.read()) > 3. request.rawpost.seek(0) > 4. request.fields = cgi.FieldStorage(fp=request.rawpost) > 5. request.rawpost.seek(0) > > Obviously, my actual code doesn't have the line numbers. > > I'm testing it out on the CGIHTTPRequestHandler with BaseHTTPServer, > and whenever my test script reaches line 2, it hangs up. It doesn't > spit out a traceback, or stop in less than a minute, whenever I use > sys.stdin.read(). Can anyone explain what is going on? > sys.stdin.read() will read until EOF. If stdin is connected to a file when the entire file will be read. If stdin is connected to the console then it will return when it reaches the end of the input (will that ever happen?) or the EOF marker, such as ctrl-Z in Windows or ctrl-D (I think) in *nix. From steve at holdenweb.com Fri Dec 12 11:13:13 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Dec 2008 11:13:13 -0500 Subject: var or inout parm? In-Reply-To: <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> Message-ID: sturlamolden wrote: > On Dec 12, 3:54 pm, Steve Holden wrote: [...] >> The interpreter "should not" have a GIL. > >> The tuple "should" check that >> it is actually being mutated. How? > > In Python it would be something similar to: > > def __setitem__(self, index, value): > if _buf[index] is not value: # given that _buf is the tuple's > internal buffer > raise TypeError, 'tuple' object does not support item > assignment > > It should be the tuple's __setitem__ that was invoked here, not > __iadd__, or the parser is faulty. > OK, so now you are proposing to alter the parser, and possibly the implementation of the INPLACE_ADD opcode in eval.c, so can you give us the patch for those, please? This is exactly the point I was trying to make. It's easy to stand on the sidelines and make sensible- or even intelligent-sounding suggestions about how to change Python. But inside the interpreter there's a maze of twisty little passages all alike (or similar complexity), and hand-waving doesn't get you anywhere. Discussion of such behavior as a "bug" is also pejorative, since the current semantics are the way they are by design. You are therefore disagreeing with the design of Python rather than discussing a bug in its implementation. That also raises the issues of how you get Jython and IronPython to implement the same semantics, and whether you care about the millions of lines of code that already assumes the current behavior. You've got a lot of work to do ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From torriem at gmail.com Fri Dec 19 14:54:28 2008 From: torriem at gmail.com (Michael Torrie) Date: Fri, 19 Dec 2008 12:54:28 -0700 Subject: IMAP: How to implement GMail-like threaded conversations view In-Reply-To: References: Message-ID: <494BFBF4.1000205@gmail.com> Martin wrote: > Currently I am trying to get used to Python's imaplib and email > modules. > I'like to create a webmail client simmilar to GMail. This is off-topic, but why on earth would you want to emulate Gmail's conversation views? It's horrible and a very broken way of viewing e-mail threads. Compared the normal, threaded view of, say the discussions on this list to the view that Gmail gives you. For conversations of more than half a dozen posts, Gmail's view is unnavigatable. Suppose I want to break into a discussion that's already dozens of posts long. With a real threaded view I can easily see the flow of the conversation, grab random posts, then maybe read their parent or grandparent posts. Looking at the rest of your e-mail, I can see that maybe you do want to have real threads rather than the google conversation view which removes all structure. > > My Questions: > a) Is there any feature hidden in Python's built-in modules (imaplib, > email) that already can group all my mails into threads? Each e-mail has a referral number that refers to the parent email. Just keep track of these in a structure and you can easily build a nice tree of the thread. > > b) If not a... what would be the best way to implement this? > > I can think of two approaches: > b.1) Use the "References:" field of the messages in order to find out > which messages are related to each other. Yes. This is absolutely the right way to do it. > > I tried a first implementation which works quite well but I don't know > if there can occur situations where one message is related to two > parents. Also I don't know what happens if someone is too lazy to type > my address. He might click at "Reply", delete topic and old mail-text > and compose a new mail. Theoretically his mail client would set the > "References:" field accordingly never the less, wouldn't it? Therefore > my mail client would consider that completely new mail as part of an > older conversation. In this case, a lazy user is a lazy user. Probably best to encourage people to use better etiquette when using e-mail. > > The thoughts above might lead to the second approach: > > b.2) Use the "Subject:" field of the messages. Horribly broken. Thunderbird does this and it drives me crazy. I often get messages months apart that happen to have a common subject line, even though they aren't the same thread or conversation. I don't want a new message, which does not refer to the old message in any way, to attach itself to my 6-month old message and force me to scroll down through potentially hundreds of e-mails to find the stupid thing. No, the RFCs are there for a reason. They bring sanity to the chaos. Anything else is madness. And the fact the Outlook doesn't do proper referral fields just infuriates me. Sigh. From jwkenne at attglobal.net Wed Dec 10 17:47:49 2008 From: jwkenne at attglobal.net (John W Kennedy) Date: Wed, 10 Dec 2008 17:47:49 -0500 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: <49404775$0$4893$607ed4bc@cv.net> Xah Lee wrote: > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, > you'll have 50 or hundreds lines. C: #include #include void normal(int dim, float* x, float* a) { float sum = 0.0f; int i; float divisor; for (i = 0; i < dim; ++i) sum += x[i] * x[i]; divisor = sqrt(sum); for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; } Java: static float[] normal(final float[] x) { float sum = 0.0f; for (int i = 0; i < x.length; ++i) sum += x[i] * x[i]; final float divisor = (float) Math.sqrt(sum); float[] a = new float[x.length]; for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor; return a; } -- John W. Kennedy "Never try to take over the international economy based on a radical feminist agenda if you're not sure your leader isn't a transvestite." -- David Misch: "She-Spies", "While You Were Out" From a at a.aa Mon Dec 15 15:23:26 2008 From: a at a.aa (a) Date: Mon, 15 Dec 2008 20:23:26 GMT Subject: Python plugin for Netbeans Message-ID: <21z1l.218500$FR.506807@twister1.libero.it> Netbeans added a python plugin to its plugin repository. Do you tried it? What do you think about this plugin? From sonynamratha2009 at gmail.com Wed Dec 24 15:32:43 2008 From: sonynamratha2009 at gmail.com (sony) Date: Wed, 24 Dec 2008 12:32:43 -0800 (PST) Subject: electronics Message-ID: http://allelectronicss.blogspot.com/2008/12/mobile-phone.html http://allelectronicss.blogspot.com/2008/12/electric-car.html http://allelectronicss.blogspot.com/2008/12/electric-vehicles.html http://allelectronicss.blogspot.com/2008/12/washing-machine.html http://allelectronicss.blogspot.com/2008/12/microwave-oven.html http://allelectronicss.blogspot.com/2008/12/fan.html http://allelectronicss.blogspot.com/2008/12/iron-box.html http://allelectronicss.blogspot.com/2008/12/refrigerator.html http://allelectronicss.blogspot.com/2008/12/electric-heater.html http://allelectronicss.blogspot.com/2008/12/stove.html http://allelectronicss.blogspot.com/2008/12/bulb.html http://allelectronicss.blogspot.com/2008/12/tape-recorder.html http://allelectronicss.blogspot.com/2008/12/plasma.html http://allelectronicss.blogspot.com/2008/12/television.html http://allelectronicss.blogspot.com/2008/12/ipod.html http://allelectronicss.blogspot.com/2008/12/laptop.html http://allelectronicss.blogspot.com/2008/12/computer.html From your.master at gmail.com Thu Dec 11 16:32:00 2008 From: your.master at gmail.com (Brandon) Date: Thu, 11 Dec 2008 13:32:00 -0800 (PST) Subject: dictionary idiom needed References: <383976cf-53fb-48e4-b028-8f568468ce77@r36g2000prf.googlegroups.com> <0c4950c1-4833-40c7-ac19-260b61d5289f@k24g2000pri.googlegroups.com> <7c55c59b-cebe-4f4e-ae40-282ae7e005bf@d42g2000prb.googlegroups.com> Message-ID: > >>> d = defaultdict(lambda: defaultdict(int)) > > Arnaud Ah... so that's what lambdas are for. Many thanks! Brandon From tjreedy at udel.edu Mon Dec 1 15:02:48 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Dec 2008 15:02:48 -0500 Subject: Two attributes! Why? In-Reply-To: References: <76bc5df8-26fd-4e2d-a134-c5d13ea3b39a@n10g2000yqm.googlegroups.com> <0140c948$0$20670$c3e8da3@news.astraweb.com> Message-ID: Emanuele D'Arrigo wrote: > On Nov 29, 5:21 am, Steven D'Aprano cybersource.com.au> wrote: >> This is a side-effect of name-mangling. Double-underscore names are only >> mangled when they are referred to directly as attributes, not when they >> are passed to setattr, getattr etc. Those functions don't do any name >> mangling. Even as attributes, they are only mangled within the class definition. "__* Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between ?private? attributes of base and derived classes. See section Identifiers (Names). " Class-private is intended to mean 'private', not known and not used outside the class definition. I believe the 'mangled' form is intentionally not documented. > Ah! That make sense! Thank you! > > It's a bit of an obscure thing right now. I don't see mention of it in > the description of the setattr/getattr built-ins: > http://docs.python.org/library/functions.html > Wouldn't be good to have a hint of the issue there? I think not. The functions tell the truth when they say 'no such attribute' Any mention might suggest that trying to access private names from outside the class is a sensible thing to do. Perhaps the __* doc quoted above could be improved. Is anything there unclear? Terry Jan Reedy From torriem at gmail.com Fri Dec 19 12:25:30 2008 From: torriem at gmail.com (Michael Torrie) Date: Fri, 19 Dec 2008 10:25:30 -0700 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <494BD90A.6000206@gmail.com> r wrote: > if 3.0 looks like... print( "{0}={1}".format('this',99)) , WTF... > thats retarded and looks like Ruby code. Thats not intuitive thats > madness! What happens when you need a conversion to string from an > integer, more code?? My faith is slipping. Have the python Gods gone > mad??. Please tell me i am wrong. You are wrong. > > Pythons likeness to C is one of its great powers. I always thought of > Python as an intuitive way to write C code. I have to confess, I have no idea what you are talking about. I have never ever seen Python as an intuitive way to write C code. That's kind of bizarre. > I am sticking with 2x(which i had planned to do anyway) I have heard > of nothing significant enough to compel me to make the change yet. And > with that example from 3.0, i am really setting my ways now. i may > have to support the continuation of 2.x beyond 2.9. > Guido! please don't play Russian roulette with Python! I have loved > python all the way up through the 2.x line. And i carry a great > respect for you and your accomplishments. Python must feel at home to > a C programmer. That, i feel, is the professional following for > Python. I also feel Python is a gateway to the C language for n00b > programmers. Let Ruby have the Perl programmers, we don't need them! > > Excuse me, I think i am going to cry now :( Okay, you're welcome to. So funny that now that Python 3.0 is actually released we have people acting all surprised like they've never seen any of the new features in Python 3.0 coming. However these features have been discussed for years! And debated! Personally the new string formatter is sorely needed in Python. And they way it has been implemented is a thing of beauty. Basically the burden of formatting strings has been moved from the print statement/function to the objects themselves. Furthermore, the new {} notation allows many, many more options for formatting to be used. Want to display a floating point number with $#.## notation, and ($#.##) for negative? It's all now possible. Couldn't be done before. Want to have the ability to format your own custom object in a particular way when printing with print()? Just define a __format__ method in your object. print() will ask it to format itself. In short, this is a huge improvement, and backwards compatibility is preserved for the 2.x style for those that wish it. From bdesth.quelquechose at free.quelquepart.fr Sun Dec 14 12:01:33 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 14 Dec 2008 18:01:33 +0100 Subject: Need help improving number guessing game In-Reply-To: <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> Message-ID: <494549a3$0$22507$426a74cc@news.free.fr> feba a ?crit : > #!/usr/bin/python > #Py3k, UTF-8 > > import random > > def setup(): > #global target, guess, a, b > #a, b make minimum, maximum. Can be adjusted. > a, b = 1, 99 > target = random.randint(a, b) > return a, b, target Seems ok. You may want to use arguments with default values for a and b (and possibly to use more meaningfull names): def setup(mini=1, maxi=99) # sanity check if mini >= maxi: raise ValueError("mini must be lower than maxi") target = random.randint(mini, maxi) return mini, maxi, target > def playerswitch(player): > #Player Switch > #if player's a witch, burn her! Extra bonus point for quoting Monty Pythons !-) > if player == "P1": > player = "P2" > else: > player = "P1" > return player I'd name this one "switch_player" (most of the time, function names should be verbs) - but this is mostly a matter of personal taste !-) Minor point for a short program, but still good practice : use constants. IE : # at the top level PLAYER_1 = 1 PLAYER_2 = 2 # in your code .... if player == PLAYER_1: ... Also, you could use early returns here instead of rebinding then returning player. def switch_player(player): if player == PLAYER_1: return PLAYER_2 else: return PLAYER_1 > def youwin(pnum, player, p1sc, p2sc): I assume 'p1sc' means "player_1_score" ? If so, you may want to use a dict for scores: scores = {PLAYER_1:0, PLAYER_2:0} then... > if pnum == 1: > print("CONGRATULATIONS!") Is it really necessary to WRITE THIS IN ALL UPPERS ?-) > else: > if player == "P1": > p1sc += 1 > else: > p2sc += 1 Which would then become: scores[player] +=1 > end = "CONGRATULATIONS %s! SCORE -- P1:%s P2:%s" > print(end %(player, p1sc, p2sc)) > return p1sc, p2sc > def playagain(play): > playover = input("PLAY AGAIN? Y/N: ") > if playover.strip().lower() == "y": > play = 1 If it's meant to be 0/1 flag, Python has proper booleans too (True and False). > a, b, target = setup() > else: > print("GOOD BYE. PLAY AGAIN SOON!") > quit() It might be better to avoid exiting so brutally. Why not returning 0, none, None, None ? > return play, a, b, target > > > def guesscheck(guess, target, play, a, b, p1sc, p2sc): > if guess == target: > p1sc, p2sc = youwin(pnum, player, p1sc, p2sc) > play, a, b, target = playagain(play) > elif guess >= b: > print("NUMBER MUST BE IN RANGE") > guess = int(input("[%s-%s]%s>> " % (a, b, player))) > play, a, b, target, p1sc, p2sc = guesscheck(guess, target, > play, > a, b, p1sc, p2sc) > elif guess <= a: > print("NUMBER MUST BE IN RANGE") > guess = int(input("[%s-%s]%s>> " % (a, b, player))) > play, a, b, target, p1sc, p2sc = guesscheck(guess, target, > play, > a, b, p1sc, p2sc) > elif guess > target: > print("TOO HIGH") > b = guess > else: > print("TOO LOW") > a = guess > return play, a, b, target, p1sc, p2sc > > def guessing(a, b, player, pnum, target, p1sc, p2sc, play): > #a and b are to keep the user aware of min/max > guess = int(input("[%s-%s]%s>> " % (a, b, player))) > play, a, b, target, p1sc, p2sc = guesscheck(guess, target, play, > a, b, p1sc, p2sc) > if pnum == 2: > player = playerswitch(player) > return play, a, b, player, target, p1sc, p2sc > > #Let the show begin! You should either put this in it's own function (could be named 'main'), or at least "protect" it with an "if __name__ == '__main__':" test. > print("WELCOME TO THE SUPER NUMBER GUESSING GAME!") > pnum = int(input("1 OR 2 PLAYERS?\n> ")) > play = 1 > player = "P1" # P1 goes first > #Scores, keep track of times player guessed first. > p1sc, p2sc = 0, 0 > > #Grabs minimum, maximum, and target numbers > a, b, target = setup() > > while play == 1: > play, a, b, player, target, p1sc, p2sc \ > = guessing(a, b, player, pnum, target, p1sc, p2sc, play) > > > This is what I have now. And it looks way better than your first version. (snip) From quian.xu at stud.tu-ilmenau.de Tue Dec 23 09:51:00 2008 From: quian.xu at stud.tu-ilmenau.de (Qian Xu) Date: Tue, 23 Dec 2008 15:51:00 +0100 Subject: print to console without a line break References: Message-ID: Albert Hopkins wrote: > On Tue, 2008-12-23 at 13:18 +0000, Lie Ryan wrote: > > Probably because your stdout is line-buffered. Try: > > sys.stdout.write("Testing something...") > sys.stout.flush() # flush the stdout buffer Thanks. This works for me ^^) From google at mrabarnett.plus.com Wed Dec 10 09:57:58 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 10 Dec 2008 14:57:58 +0000 Subject: "as" keyword woes In-Reply-To: References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> Message-ID: <493FD8F6.3050803@mrabarnett.plus.com> Aaron Brady wrote: > On Dec 9, 12:40 pm, MRAB wrote: >> Aaron Brady wrote: >>> On Dec 9, 8:28 am, MRAB wrote: >>> snip >>>> In some languages (I think Delphi is one of them - it's been a while!) >>>> some words which would normally be identifiers have a special meaning in >>>> certain contexts, but the syntax precludes any ambiguity, and not in a >>>> difficult way. "as" in Python was one of those. >>>> I certainly wouldn't want something like PL/I, where "IF", "THEN" and >>>> "ELSE" could be identifiers, so you could have code like: >>>> IF IF = THEN THEN >>>> THEN = ELSE; >>>> ELSE >>>> ELSE = IF; >>>> Seehttp://en.wikipedia.org/wiki/PL/I_(programming_language). >>> snip >>> That is, 'certainly' doesn't change the meaning of your statement >>> any. You wouldn't want it, but King George III didn't want the >>> American Revolution. >> It's called emphasis. > > I just take you to have meant, then, +1 on excluding keywords from > identifiers. You said it the long way though, so I thought I missed > something deeper, that didn't come across. > IIRC, most computer languages have an LL(1) grammar, which means that when they are parsed you need to look at only the next word. If you're about to parse a statement and the next word is "IF" then you know it's an IF-statement, if it's an identifier then it's either a call or an assignment statement (OK, you don't know exactly what kind of statement it is at that point, but it works out just fine!). In the example from PL/I, "IF" could be the start of an IF-statement "IF THEN" or an assignment statement "IF = ". It's a bit more tricky for the parser as well as the programmer. Life is easier if words having special meanings are reserved. However, that doesn't mean that all special words /must/ be reserved (pragmatism beats purity). Sometimes the syntax makes it clear and unambiguous, so you can get away with not making it a reserved word. The word "as" in Python doesn't need to be reserved because the syntax precludes ambiguity, but it's the only such word in the language, so it's just tidier to make it reserved too. From bdesth.quelquechose at free.quelquepart.fr Mon Dec 15 16:53:06 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 15 Dec 2008 22:53:06 +0100 Subject: Need help improving number guessing game In-Reply-To: <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> <01564c98$0$21844$c3e8da3@news.astraweb.com> <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> Message-ID: <4946df78$0$19771$426a74cc@news.free.fr> feba a ?crit : > Alright! This is feeling more like it. > > #!/usr/bin/python > #Py3k, UTF-8 > import random > (snip) > def youwin(game): > if game['pnum'] == 1: > print("CONGRATULATIONS! IT TOOK YOU %s GUESSES" % game > ['gcount']) > else: > if game['player'] == game['player1']: > game['p1sc'] += 1 > else: > game['p2sc'] += 1 If you had initialized your "game" dict with player1 = dict(score=0) player2 = dict(score=0), game = dict( player1 = player1, player2 = player2 player = player1 # ... ) you wouldn't need the test on game['player'] == game["player1"] , and could just use: game["player"]["score"] += 1 (snip) > first off, I want to thank all of you for your help with this. I > really don't think I could've learned all of this out nearly as > quickly by reading tutorials and documentation, let alone had anything > near the grasp I have on it now. '''This''' is why I like learning by > doing. The only things I still don't really understand are .strip > ().lower(), .strip() returns a copy of the string without leading and ending whitespaces (inlcuding newlines, tabs etc). .lower() returns a copy of the string in all lowercases. Since .strip() returns a string object, you can chain method calls. " yaDDA\n".strip().lower() is just a shortcut for thestring = " yaDDA\n" tmp1 = thestring.strip() # => "yaDDA" tmp2 = tmp1.lower() # => "yadda" > and try/except/else, and I plan on looking them up before > I do anything else. In the past few hours I've gone from not having a > clue what the whole {'fred': 0, 'barney': 0} thing was about to being > able to fully understand what you're talking about, and put it into > practice Quite close... You still failed to understand how dicts could be used to replace 'if/else' statements (dict-base dispatch is very idiomatic in Python, and is also a good introduction to OO). (snip) > 5; I added the ability for it to automatically complete when there's > only one option left. I was amazed' I was actually going to ask for > advice on how to do it here. I was going to say "I was thinking (blah > blah)", but then I just typed it in, and it worked flawlessly. Yeps. That's probably why most of us here fell in love with Python: it makes simple thing simple, and tend to JustWork(tm). > 6; can anyone think of anything else to add on to/do with this game? rewrite it once again using objects instead of dicts ? Anyway, thanks for sharing your enthusiasm with us. From mr.spoon21 at gmail.com Wed Dec 17 12:14:41 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Wed, 17 Dec 2008 18:14:41 +0100 Subject: OT: Binary tree logarithms properties Message-ID: <8f67b6f80812170914m377191f4g81345ffe5d0b7f26@mail.gmail.com> Hi, I'm searching for a clear explanation of binary tree properties, expecially the ones related to logarithms. For example, I know that in a tree with 2n-1 nodes, we have log(n) levels, from 0 to log(n). So, if k is the level, the nodes on a level have indexes between 2^k and 2^(k+1)-1. For k=0 we have 2 and 3. For k=1 we have 4, 5, 6, 7 and so on. I know this after I studied some exercises on my book. Anyway there is no explanation or demonstration of these properties. I know this is not the better place to ask (or maybe it is?), but maybe someone can point me to something useful. Thanks, bye From google at mrabarnett.plus.com Mon Dec 22 12:37:52 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 22 Dec 2008 17:37:52 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <494FBE99.6050507@gmail.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <494FBE99.6050507@gmail.com> Message-ID: <494FD070.4060209@mrabarnett.plus.com> Michael Torrie wrote: > r wrote: >> Steven, >> Would you like to elaborate on -why- escaped backslashes are needed in >> strings... i waiting??? > > Some character was needed. It just happens that backslashes have been > used in this manner for composing nonprintable sequences, codes, etc. > It's only in use because someone arbitrarily picked it about 40 years > ago. Any character could have been used; any such character would still > be have to escaped. > BCPL used '*', but C, which was developed from BCPL, uses '\'. > Kind of funny that you are complaining about Python in particular when > this behavior is in almost all languages today, including Perl, Ruby, > > Don't blame python for a mistake that Microsoft made, that of choosing a > commonly-accepted escape character (long before Python was even though > of!) as their path delimiter. Fortunately sane operating systems use a > standard slash. Even Windows APIs accept forward slashes as path > delimiters. > > So really your complaint about the backslash is a bit silly. Are you > going to campaign that C# and Java also "fix" this problem by choosing > another character? > From geekmail at usenot.de Sun Dec 7 14:23:26 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sun, 7 Dec 2008 20:23:26 +0100 Subject: Importing the re module fails Message-ID: <20081207202326.4b5ab73d@usenot.de> This is a little puzzling. Using ipython: [wildemar at localhost Logstuff]$ ipython Python 2.5.2 (r252:60911, Sep 30 2008, 15:41:38) Type "copyright", "credits" or "license" for more information. [snip ipython help message] In [1]: import re This works fine. But with the regular python interpreter I get this: [wildemar at localhost Logstuff]$ python Python 2.5.2 (r252:60911, Sep 30 2008, 15:41:38) [GCC 4.3.2 20080917 (Red Hat 4.3.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/re.py", line 10, in # AB (info at pythonware.com). AttributeError: 'module' object has no attribute 'compile' What gives? Has Fedora-10 botched python or does anybody else have that problem es well? /W -- My real email address is constructed by swapping the domain with the recipient (local part). From stef.mientki at gmail.com Wed Dec 31 09:18:02 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 31 Dec 2008 15:18:02 +0100 Subject: Graphics Library with Standard Interaction Features, 2D and 3D In-Reply-To: References: <69c3eca8-5e17-49fb-8354-5fdc0bd73f9a@r15g2000prd.googlegroups.com> Message-ID: <495B7F1A.5000101@gmail.com> Maybe VPython (Visual) or Panda fits your needs. cheers, Stef From __peter__ at web.de Mon Dec 8 09:46:07 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 08 Dec 2008 15:46:07 +0100 Subject: Beginner trying to understand functions. References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> Message-ID: James Mills wrote: > On Tue, Dec 9, 2008 at 12:24 AM, cadmuxe wrote: >> i think we should use raw_input('Please enter your name: ') instead of >> input('Please enter your name: ') > > Good point :) OP: Please take notes :) I think the OP is using Python 3.0. What used to cause trouble Python 2.5.1 (r251:54863, Jul 31 2008, 23:17:43) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> input() 1/0 Traceback (most recent call last): File "", line 1, in File "", line 1, in ZeroDivisionError: integer division or modulo by zero is now the way it should be: Python 3.0 (r30:67503, Dec 4 2008, 11:26:28) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> raw_input() Traceback (most recent call last): File "", line 1, in NameError: name 'raw_input' is not defined >>> input() 1/0 '1/0' Peter From bearophileHUGS at lycos.com Sat Dec 13 09:00:09 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 13 Dec 2008 06:00:09 -0800 (PST) Subject: Removing None objects from a sequence References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> <4942E668.5030100@tim.thechases.com> <01538f0c$0$6988$c3e8da3@news.astraweb.com> Message-ID: <234b9a34-52e3-42c3-968c-f50983e51c68@e1g2000pra.googlegroups.com> Steven D'Aprano: > The algorithm is unclear: try explaining > what you are doing in English, and see how difficult it is. That algorithm is a standard one, and quite clear. Any programmer worth his/her/hir salt has to be able to understand that. I agree that the idiom with the list comp (algorithm2) is better for Python, but you have to know that algorithm1 to use it in other languages. > Now, sure, most of the work in Tim's version is executed in fast C code > instead of slow Python code. If we were programming in C, your version > might perform better relative to Tim's. Try Psyco too: from timeit import default_timer as clock def remove_nones1(alist): n = len(alist) i = j = 0 while i < n: if alist[i] is not None: alist[j] = alist[i] j += 1 i += 1 alist[j : i] = [] def remove_nones2(alist): alist[:] = [x for x in alist if x is not None] def remove_nones3(alist): for i in xrange(len(alist)-1, -1, -1): if alist[i] is None: del alist[i] def test123(data): data1 = data[:] data2 = data[:] data3 = data[:] t = clock() remove_nones1(data1) print " remove_nones1:", round(clock() - t, 2), "s" t = clock() remove_nones2(data2) print " remove_nones2:", round(clock() - t, 2), "s" t = clock() remove_nones3(data3) print " remove_nones3:", round(clock() - t, 2), "s" assert data1 == data2 == data3 assert data1 == data2 def test12(data): data1 = data[:] data2 = data[:] data3 = data[:] t = clock() remove_nones1(data1) print " remove_nones1:", round(clock() - t, 2), "s" t = clock() remove_nones2(data2) print " remove_nones2:", round(clock() - t, 2), "s" print " remove_nones3: (not tested)" assert data1 == data2 def gen_data(N): print " N:", N data = [None]*2 + range(5) + [None]*3 + range(5, 10) + [None]*4 + \ [10, None, 11, None, 12, None] data *= N data += range(N * 10) data += [None] * (N * 10) data += [None, 0] * (N * 10) data += [1] * (N * 100) return data print "Without Psyco:" test123(gen_data(1000)) test12(gen_data(30000)) print print "With Psyco:" import psyco; psyco.full() test123(gen_data(1000)) test12(gen_data(30000)) Results on a Core2 2 GHz, Python 2.6.1, latest Psyco: Without Psyco: N: 1000 remove_nones1: 0.05 s remove_nones2: 0.02 s remove_nones3: 3.04 s N: 30000 remove_nones1: 1.51 s remove_nones2: 0.62 s remove_nones3: (not tested) With Psyco: N: 1000 remove_nones1: 0.0 s remove_nones2: 0.01 s remove_nones3: 3.01 s N: 30000 remove_nones1: 0.08 s remove_nones2: 0.33 s remove_nones3: (not tested) As you see even with Psyco a (bit) lower level style of coding wins :-) In practice if that routine is important (or if it's a generic library routine that you don't know how it will be used) you use two different algorithms according to the availability of Psyco. Something like: def remove_nones4(alist): if psyco_available: n = len(alist) i = j = 0 while i < n: if alist[i] is not None: alist[j] = alist[i] j += 1 i += 1 alist[j : i] = [] else: alist[:] = [x for x in alist if x is not None] Bye, bearophile From george.sakkis at gmail.com Mon Dec 1 16:53:49 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 1 Dec 2008 13:53:49 -0800 (PST) Subject: Scanner class Message-ID: <737a0550-0b92-4f65-829e-953882d74419@y18g2000yqn.googlegroups.com> Is there any stdlib or (more likely) 3rd party module that provides a similar functionality to the java.util.Scanner class [1] ? If not, would there be any interest in porting it (with a more Pythonic API of course) or are there better alternatives ? George [1] http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html From bockman at virgilio.it Wed Dec 31 04:20:47 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: Wed, 31 Dec 2008 10:20:47 +0100 Subject: select.select and socket.setblocking In-Reply-To: References: Message-ID: <495b3970$0$11387$5fc30a8@news.tiscali.it> Jean-Paul Calderone ha scritto: > On Tue, 30 Dec 2008 19:19:08 +0100, Francesco Bochicchio > wrote: >> [snip] >> >> If you are interested in socket errors, you should >> also fill the third 'fd-set' in the select call, and after select >> returns check that fd is not in it anymore: >> >> ready = select.select( [fd],[], [fd] ) >> if fd in ready[2]: >> # raise your error here > > The third argument to select() isn't for monitoring sockets for errors. > Its > behavior is also rather platform sensitive. In general, you don't need it > at all on POSIX, but on Windows you should pass the same list for it as you > pass for the write-set, merge the results, and treat them all as writeable. > > Or use a higher-level library that deals with all the asinine details for > you. ;) > > Jean-Paul Yes, now that you mention it I remember having to do something like that on a socket library I wrote on windows ... IIRC, the send could not complete and then signal the readyness of the socket through the third argument of the select ... My experience is mostly on unices, and I usually don't use the third argument (and not often the second) but I remember having read on select manual page that it was for errors. Now both python manuals than select manual page say it is for 'exceptional conditions', without going into details ... Tx for the clarification, anyway ... Ciao ---- FB From pruebauno at latinmail.com Wed Dec 17 10:41:16 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Wed, 17 Dec 2008 07:41:16 -0800 (PST) Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> Message-ID: On Dec 17, 10:19?am, walterbyrd wrote: > For a language as well structured as Python, this seems somewhat > sloppy, and inconsistant. ?Or is there some good reason for this? > > Here is what I mean: > > def a(): > ? ? x = 99 > ? ? print x > > def b(): > ? ? print x > > a() > b() # raises an exception because x is not defined. > > However in the methods are within a class, the scoping seems to work > differently. > > class ab(): > ? ? def a(self): > ? ? ? ? self.x = 99 > ? ? ? ? print self.x > ? ? def b(self): > ? ? ? ? print self.x > > i = ab() > i.a() > i.b() # this works, why no lexical scoping? If scoping worked as you want, how, pray tell, would you define object attributes? From luismgz at gmail.com Mon Dec 29 23:35:04 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Mon, 29 Dec 2008 20:35:04 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <9c8c524f-6985-4cc8-b19c-666f85c69946@a26g2000prf.googlegroups.com> <01696606$0$6988$c3e8da3@news.astraweb.com> Message-ID: <78bd573f-03b0-4628-909d-3f84f9718e7e@13g2000yql.googlegroups.com> On Dec 29, 9:44?pm, Steven D'Aprano wrote: > How do you lose backward compatibility by *adding* new functionality? The > old functionality will continue to work as normal. > > -- > Steven AFAIK it still works the old way, but it will be deprecated soon. From cournape at gmail.com Thu Dec 4 18:58:29 2008 From: cournape at gmail.com (David Cournapeau) Date: Fri, 5 Dec 2008 08:58:29 +0900 Subject: using distutils to cross-compile extensions? In-Reply-To: <49385CBB.7060207@cs.cornell.edu> References: <49385CBB.7060207@cs.cornell.edu> Message-ID: <5b8d13220812041558r665738fydc558d46a851c887@mail.gmail.com> On Fri, Dec 5, 2008 at 7:42 AM, Michael George wrote: > Hi, > > Please CC me in replying as I am off list. > > I have an extension module that I've built using distutils. I wonder if > it's possible to use distutils to cross-compile it for windows on my linux > box, and whether the pain involved is great. Can anyone point me in the > right direction? You will have more luck using wine in your case if that's an option. General cross-compilation with distutils is for all practical purpose impossible - except for the particular case of 32 <-> 64 bits windows, which is fully supported. The first step for cross compilation would be the ability to build python itself wtih different build/host, and that's already non trivial. David From russell.sayers at gmail.com Mon Dec 1 22:32:52 2008 From: russell.sayers at gmail.com (russ) Date: Tue, 2 Dec 2008 14:32:52 +1100 Subject: Google App Engine Code Challenge - write a tetris playing algorithm In-Reply-To: References: Message-ID: <10304c580812011932l7ef375fcv4149f66064d02a30@mail.gmail.com> that's the first feature i'll add.. once the popularity gets over zero! :) On Tue, Dec 2, 2008 at 2:19 PM, Casey McGinty wrote: > On Sun, Nov 30, 2008 at 2:41 PM, russ.au wrote: > >> I've got more features to add, depending on how >> popular it is.. >> > > Are you going to create a leader board to track the high scores? > -------------- next part -------------- An HTML attachment was scrubbed... URL: From walterbyrd at iname.com Mon Dec 29 12:50:14 2008 From: walterbyrd at iname.com (walterbyrd) Date: Mon, 29 Dec 2008 09:50:14 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> Message-ID: <9c8c524f-6985-4cc8-b19c-666f85c69946@a26g2000prf.googlegroups.com> On Dec 21, 12:28?pm, Bruno Desthuilliers wrote: > > I can see where the new formatting might be helpful in some cases. > > But, I am not sure it's worth the cost. > > Err... _Which_ cost exactly ? Loss of backward compatibility, mainly. From reckoner at gmail.com Mon Dec 15 22:21:01 2008 From: reckoner at gmail.com (Reckoner) Date: Mon, 15 Dec 2008 19:21:01 -0800 (PST) Subject: tricky nested list unpacking problem References: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> Message-ID: <018c566d-f32c-4f9a-b1c0-fd51e370a75b@y1g2000pra.googlegroups.com> On Dec 15, 1:28?pm, Arnaud Delobelle wrote: > Reckoner writes: > > Hi, > > > I have lists of the following type: > > > [1,2,3,[5,6]] > > > and I want to produce the following strings from this as > > > '0-1-2-3-5' > > '0-1-2-3-6' > > > That was easy enough. The problem is that these can be nested. For > > example: > > > [1,2,3,[5,6],[7,8,9]] > > > which should produce > > > '0-1-2-3-5-7' > > '0-1-2-3-5-8' > > '0-1-2-3-5-9' > > '0-1-2-3-6-7' > > '0-1-2-3-6-8' > > '0-1-2-3-6-9' > > > also, > > > [1,2,3,[5,6],7,[9]] > > > should produce > > > '0-1-2-3-5-7-9' > > '0-1-2-3-6-7-9' > > > obviously, these are nested loops over the lists. The problem is that > > I don't know ahead of time how many lists there are or how deep they > > go. In other words, you could have: > > > [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]] > > IMHO the second level of nested lists is unnecessary as the same can be > achieved with just one sublevel of list (unless they are to be > interpreted in a way you have not explained). ?If you avoid this double > nesting then the 'flatten()' function below is not necessary anymore. > > > > > Any help appreciated. I've really been having trouble with this. > > > I hope that made sense. > > Here is a not thought out solution: > > def flatten(lst): > ? ? for x in lst: > ? ? ? ? if isinstance(x, list): > ? ? ? ? ? ? for y in flatten(x): > ? ? ? ? ? ? ? ? yield y > ? ? ? ? else: > ? ? ? ? ? ? yield x > > def unpack(lst): > ? ? stack, strings = [], [] > ? ? def rec(): > ? ? ? ? i = len(stack) > ? ? ? ? if i == len(lst): > ? ? ? ? ? ? strings.append('-'.join(map(str, stack))) > ? ? ? ? elif isinstance(lst[i], list): > ? ? ? ? ? ? for x in flatten(lst[i]): > ? ? ? ? ? ? ? ? stack.append(x) > ? ? ? ? ? ? ? ? rec() > ? ? ? ? ? ? ? ? stack.pop() > ? ? ? ? else: > ? ? ? ? ? ? stack.append(lst[i]) > ? ? ? ? ? ? rec() > ? ? rec() > ? ? return strings > > l1 = [1,2,3,[5,6]] > l2 = [1,2,3,[5,6],[7,8,9]] > l3 = [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]] > > Then: > > >>> unpack(l1) > > ['1-2-3-5', '1-2-3-6']>>> unpack(l2) > > ['1-2-3-5-7', '1-2-3-5-8', '1-2-3-5-9', '1-2-3-6-7', '1-2-3-6-8', '1-2-3-6-9']>>> unpack(l3) > > ['1-2-3-5-7-9', '1-2-3-5-7-1', '1-2-3-5-7-2', '1-2-3-5-7-3', > '1-2-3-5-7-4', '1-2-3-5-7-5', '1-2-3-5-6-9', '1-2-3-5-6-1', > '1-2-3-5-6-2', '1-2-3-5-6-3', '1-2-3-5-6-4', '1-2-3-5-6-5', > '1-2-3-5-10-9', '1-2-3-5-10-1', '1-2-3-5-10-2', '1-2-3-5-10-3', > '1-2-3-5-10-4', '1-2-3-5-10-5', '1-2-3-5-11-9', '1-2-3-5-11-1', > '1-2-3-5-11-2', '1-2-3-5-11-3', '1-2-3-5-11-4', '1-2-3-5-11-5'] > > -- > Arnaud Thanks for your detailed reply. I will have to ponder your solution carefully. From prologic at shortcircuit.net.au Tue Dec 2 17:59:54 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 3 Dec 2008 08:59:54 +1000 Subject: HELP!...Google SketchUp needs a Python API In-Reply-To: References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> Message-ID: On Wed, Dec 3, 2008 at 4:44 AM, Benjamin Kaplan wrote: > > > On Tue, Dec 2, 2008 at 1:36 PM, Craig Allen wrote: >> >> > Just remember thought that if you threat Python like a >> > hammer, suddenly everything will look like a bail. >> > >> >> don't you mean if you use Python like a pitchfork? > > Or that everything else looks like a nail. B and N are right next to each > other, so that seems more likely to me. Haha that was my bad typing :) --JamesMills -- -- -- "Problems are solved by method" From saluk64007 at gmail.com Sun Dec 21 15:00:04 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Sun, 21 Dec 2008 12:00:04 -0800 Subject: Are Django/Turbogears too specific? In-Reply-To: References: Message-ID: On Sun, Dec 21, 2008 at 11:41 AM, Gilles Ganault wrote: > Hi > > I'd like to rewrite a Web 2.0 PHP application in Python with AJAX, and > it seems like Django and Turbogears are the frameworks that have the > most momentum. > > I'd like to use this opportunity to lower the load on servers, as the > PHP application wasn't built to fit the number of users hammering the > servers now. > > I'm concerned, though, that these frameworks they may be too specific > to the tasks they were originally developped for (news articles, > AFAIK). Do you think I should just use eg. CherryPy and some basic > AJAX? > > Thank you for any feedback. > -- > http://mail.python.org/mailman/listinfo/python-list > No, they aren't very specific at all. Both frameworks allow configuration at nearly every level. The cool, slick admin interface might not be so useful depending on your application, but everything else has uses in just about any field. I only have experience with TG and cherrypy, TG for me is almost like cherrypy (I'm not sure if it still does, I've been out of the loop, but it used to use cherrypy under the hood), but a bit nicer to work with, especially if you have any AJAX. From geekmail at usenot.de Wed Dec 3 03:51:54 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Wed, 3 Dec 2008 09:51:54 +0100 Subject: Reverse zip() ? References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> Message-ID: <20081203095154.1bb33d4d@usenot.de> On Tue, 02 Dec 2008 18:16:13 -0800 Bryan Olson wrote: > zip as its own inverse might be even easier to comprehend if we call > zip by its more traditional name, "transpose". > Sounds like a Py4k change to me. /W -- My real email address is constructed by swapping the domain with the recipient (local part). From robert.kern at gmail.com Mon Dec 8 18:01:50 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 08 Dec 2008 17:01:50 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: <493DA61F.7020207@mrabarnett.plus.com> References: <493DA61F.7020207@mrabarnett.plus.com> Message-ID: MRAB wrote: > Terry Reedy wrote: >> Rasmus Fogh wrote: >> >>> For my personal problem I could indeed wrap all objects in a wrapper >>> with >>> whatever 'correct' behaviour I want (thanks, TJR). It does seem a bit >> >> I was not suggesting that you wrap *everything*, merely an adaptor for >> numpy arrays in whatever subclass and source it is that feeds them to >> your code. It is fairly unusual, I think, to find numpy arrays 'in >> the wild', outside the constrained context of numerical code where the >> programmer uses them intentionally and hopefully understands their >> peculiarities. >> >>> much, though, just to get code like this to work as intended: >>> alist.append(x) >>> print ('x is present: ', x in alist) >> >> Even if rich comparisons as you propose, the above would *still* not >> necessarily work. Collection classes can define a __contains__ that >> overrides the default and that can do anything, though True/False is >> recommended. >> > If you have a list of results and you want to see whether one of them is > Nan then the obvious way is "Nan in results", but __contains__ uses > __eq__ and Nan == Nan returns False, so "Nan in results" returns False. > Hmm... "Nan is Nan" returns True, However, "Nan is SomeOtherNan" does not return True. > so if there was a version of > __contains__ which used "is" then "Nan in results" would return True. > Perhaps "Nan is in results"? Or would that be too confusing, ie "in" vs > "is in"? list.__contains__() already checks with "is" before it tries "==". In [65]: from numpy import nan, inf In [66]: other_nan = inf/inf In [67]: nan in [nan] Out[67]: True In [68]: nan in [other_nan] Out[68]: False -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From gagsl-py2 at yahoo.com.ar Fri Dec 26 14:00:20 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 26 Dec 2008 17:00:20 -0200 Subject: =?utf-8?Q?Can=C2=B4t_Surf_Python_Pages_in_W?= =?utf-8?Q?indoze?= References: <4dc0cfea0812260701q6baf0ccbj154c5b3fa2281cdb@mail.gmail.com> <4954FB9F.5050702@wildenhain.de> <4dc0cfea0812260911k4dbc0f2ame9cc874e067b7816@mail.gmail.com> Message-ID: En Fri, 26 Dec 2008 15:11:44 -0200, Victor Subervi escribi?: > On 12/26/08, Tino Wildenhain wrote: >>> print "Content-Type: text/html" >>> print >>> print """ >>> >> http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> I think there should be only one blank line between header and content, you have two (so the document contains an empty line before the doctype declaration, and I think this is invalid). >>> >>> >>> >>> >>> Yeah >>> >>> """ The title tag (in head) is mandatory (although this should not prevent it from working) >> this could be fine if called in CGI context. > > Can you state clearly what "CGI context" means? Tino W. surely meant to say: - if you have a web server running - and it is capable of handle CGI scripts - and you have configured it to handle CGI scripts - and you have configured it to run the code above as a CGI script in response to certain request - and you pointed your browser to the right server, at the right port, at the right url - then, the code above should run and you should get a nice HTML page with the word Yeah in it. > Should I be importing a CGI > module? I pulled this code from a page that was working. If it had an > importation of something CGI, I believe I would have tested that with all > the other things that were imported that I tested, but perhaps not. I am > not > at my home computer to test, and will not be back online for a week. No, the code above doesn't require other modules to run. > I am not worried about Zope now, but the above code, yes. You're talking about two totally separate projects, I presume. The above code should not be used with Zope. -- Gabriel Genellina From stepp.aaron at gmail.com Mon Dec 22 22:52:35 2008 From: stepp.aaron at gmail.com (Aaron Stepp) Date: Mon, 22 Dec 2008 22:52:35 -0500 Subject: iterating initalizations In-Reply-To: <47c890dc0812221943g44bd7222t8c09c088d87e77df@mail.gmail.com> References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> <47c890dc0812221943g44bd7222t8c09c088d87e77df@mail.gmail.com> Message-ID: <002696D3-E888-4D32-8416-0CFE4AC859AC@gmail.com> On Dec 22, 2008, at 10:43 PM, Chris Rebert wrote: > On Mon, Dec 22, 2008 at 7:32 PM, Aaron Stepp > wrote: > >> >> Thanks for the help so far, I think I'm starting to get a hang of the >> syntax. >> >> I think I need to state my goal more clearly. >> >> Instead of writing a long list of initializations like so: >> >> A = [ ] >> B = [ ] >> ... >> Y = [ ] >> Z = [ ] >> >> I'd like to save space by more elegantly turning this into a loop. >> If I >> need to just write it out, I guess that's ok... but it would be much >> cleaner. I'm a composer, not a programmer, so some of this is >> quite above >> me. >> > > So, are these variables supposed to be module-level, or attributes of > class pitchAndRhythm, or what? > Also, are you going to use the variables normally or are you going to > need "variable variables" (e.g. like $$var in PHP, which gives the > value of the variable with the name of the string stored in $var)? > > Cheers, > Chris > > -- > Follow the path of the Iguana... > http://rebertia.com The're going to only be part of the pitchAndRhythm class. Simply put, I just need enough arrays to hold a list of pitches/rhythms. Then I'll have each list member returned to an instrument defined in another module. As I'm hacking away at the code, I'm realizing that maybe I can do this with just and A = [] and B = []. But I'm not sure... Thanks again. AS From BrianVanderburg2 at aim.com Sun Dec 14 13:07:10 2008 From: BrianVanderburg2 at aim.com (Brian Allen Vanderburg II) Date: Sun, 14 Dec 2008 13:07:10 -0500 Subject: Limit traceback from most recent call Message-ID: <49454B4E.30308@aim.com> I've looked at traceback module but I can't find how to limit traceback from the most recent call if it is possible. I see that extract_tb has a limit parameter, but it limits from the start and not the end. Currently I've made my own traceback code to do this but wonder if python already has a way to do this build in: def format_partial_exc(limit=None): (type, value, tb) = sys.exc_info() items = traceback.extract_tb(tb) if limit: items = items[-limit:] # Get last 'limit' items and not first result = 'Traceback (most recent call last):\n' items = traceback.format_list(items) for i in items: result += i # Newline already included result += type.__name__ + ': ' + str(value) return result Is this possible currently from traceback or other python module? Brian A. Vanderburg II From robert.panesse at gmail.com Sun Dec 21 08:40:20 2008 From: robert.panesse at gmail.com (McCoy Fan) Date: Sun, 21 Dec 2008 05:40:20 -0800 (PST) Subject: Read an image from a URL and write it to the browser References: Message-ID: On Dec 21, 7:25?am, Peter Otten <__pete... at web.de> wrote: > McCoy Fan wrote: > > I want to do something simple: read an image from an image URL and > > write the image to the browser in CGI style. > > > I wrote a CGI script to do this (I'm new to Python) and got the > > following error: > > > "FancyURLopener instance has no attribute 'tempcache'" in > method FancyURLopener.__del__ of > > I have no idea what that error means and neither does Google. > > > Any idea where I went wrong in the code below? > > import urllib > > > urlString = "http://www.google.com/google_logo.jpg" > > imgStream = urllib.urlopen(urlString) > > imgBuffer = imgStream.read() > > imgStream.close() > > print "Content-Type: image/jpeg" > > print > > print imgBuffer > > Your script runs without error here, but I can ?provoke the attribute error > by passing an invalid proxies argument to urlopen(): > > $ python -c"import urllib; urllib.urlopen('whatever', proxies=42)" > Traceback (most recent call last): > ? File "", line 1, in > ? File "/usr/lib/python2.5/urllib.py", line 75, in urlopen > ? ? opener = FancyURLopener(proxies=proxies) > ? File "/usr/lib/python2.5/urllib.py", line 609, in __init__ > ? ? URLopener.__init__(self, *args, **kwargs) > ? File "/usr/lib/python2.5/urllib.py", line 117, in __init__ > ? ? assert hasattr(proxies, 'has_key'), "proxies must be a mapping" > AssertionError: proxies must be a mapping > Exception exceptions.AttributeError: "FancyURLopener instance has no > attribute 'tempcache'" in > ignored > > Please post your complete traceback, Python version, and OS to allow for a > more detailed diagnosis. > > You can also try to run your script with > > > imgStream = urllib.urlopen(urlString) > > changed to > > imgStream = urllib.urlopen(urlString, proxies={}) > > to bypass the code in which I suppose the failure to occur. > > Peter I appreciate your response. Thank you. After reading your reply, I realized this must be related to the fact that I am running this script on Google App Engine. It turns out, App Engine does not allow direct socket communication so urllib is not allowed. Instead they provide their own library called urlfetch. So my script should look something like this: from google.appengine.api import urlfetch print 'Content-Type: text/plain' print '' result = urlfetch.fetch('http://www.google.com/google_logo.jpg') print result.content I haven't been able to get it to work yet but at least I'm heading in the right direction now. I'll keep digging. Thanks! From gregturn at mindspring.com Mon Dec 1 14:47:02 2008 From: gregturn at mindspring.com (Goldfish) Date: Mon, 1 Dec 2008 11:47:02 -0800 (PST) Subject: Spring Python 0.9.0 is released Message-ID: <3fca9b88-df7c-40dc-a64d-7181c39dd42c@g38g2000yqd.googlegroups.com> Spring Python, the python version of the Spring Framework, has just released version 0.9.0. This release includes a key update to springpython.security.web module, where authorization has been patched to support CherryPy 3.1. To download the 0.9.0 release, or an archived release, and for access to sample applications use http://www.springsource.com/download/community?project=Spring%20Extensions Please visit the website at http://springpython.webfactional.com for information about features, releases, source code, licensing, and official documentation. ============================================================================== Release Notes - Spring Python - Version 0.9 Bug * [SESPRINGPYTHONPY-81] - Fix AccessDecisionManager based on CherryPy 3 upgrade Task * [SESPRINGPYTHONPY-76] - Convert sample applications to new XMLConfig format. ============================================================================== Key Features of Spring Python include: * Inversion Of Control - The idea is to decouple two classes at the interface level. This lets you build many reusable parts in your software, and your whole application becomes more pluggable. You can use either the XmlApplicationContext or the DecoratorBasedApplicationContext. * Aspect-oriented Programming - Spring Python provides great ways to wrap advice around objects. It is utilized for remoting. Another use is for debug tracers and performance tracing. * DatabaseTemplate - Reading from the database requires a monotonous cycle of opening cursors, reading rows, and closing cursors, along with exception handlers. With this template class, all you need is the SQL query and row-handling function. Spring Python does the rest. * Database Transactions - Wrapping multiple database calls with transactions can make your code hard to read. This module provides multiple ways to define transactions without making things complicated. * Security - Plugin security interceptors to lock down access to your methods, utilizing both authentication and domain authorization. * Remoting - It is easy to convert your local application into a distributed one. If you have already built your client and server pieces using the IoC container, then going from local to distributed is just a configuration change. * Samples - to help demonstrate various features of Spring Python, some sample applications have been created: o PetClinic - Everybody's favorite Spring sample application has been rebuilt from the ground up using various web containers including: CherryPy. Go check it out for an example of how to use this framework. o Spring Wiki - Wikis are powerful ways to store and manage content, so we created a simple one as a demo! o Spring Bot - Use Spring Python to build a tiny bot to manage the IRC channel of your open source project. From wuwei23 at gmail.com Sun Dec 21 20:37:47 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 21 Dec 2008 17:37:47 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <7fc23c41-6bf8-4272-b405-acc092cbac87@r15g2000prd.googlegroups.com> Message-ID: <5b15041d-c1e9-4b28-b8ca-89505e49fe83@a12g2000pro.googlegroups.com> On Dec 21, 10:11?am, r wrote: > Most of the complaints i hear are the redundant use of self. > Which I lamented about but have become accustom(brainwashed) to it. I > would remove this if it where up to me. It's a shame Python wasn't released under some kind of license, one that allowed its source to be, say, "opened" and modified. Otherwise you would just implement this yourself and submit patches, right? From prologic at shortcircuit.net.au Sun Dec 21 21:02:38 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Dec 2008 12:02:38 +1000 Subject: Threads, forks, multiplexing - oh my In-Reply-To: References: Message-ID: On Mon, Dec 22, 2008 at 11:36 AM, Thomas Raef wrote: > I now want to run multiple instances of this program on a client, after > receiving the command line and args from a broker, dispatcher, whatever you > want to call it. You can use the subprocess module. > I've read where forks will run programs but they replace the calling program > ? is that correct? Am I reading that right? If so, then my client program > will have to use forks so it can run a program. Then are threads to run > functions and not full-fledged programs? Forking creates a clone/child process of the parent. You probably want os.system or subprocess. > When, if ever, would I want to look at implementing multiplexing? Single-process multiplexing (think event-driven) can often be far better in terms of performance. --JamesMills From srilyk at gmail.com Tue Dec 16 04:20:29 2008 From: srilyk at gmail.com (W W) Date: Tue, 16 Dec 2008 03:20:29 -0600 Subject: [Tutor] Having Issues with CMD and the 'python' command In-Reply-To: References: Message-ID: <333efb450812160120g57f18631hf6c7149dc307d3@mail.gmail.com> On Mon, Dec 15, 2008 at 9:56 AM, Benjamin Kaplan wrote: > It's not a question of sensibility. It's a question of purpose. The Zen is > the philosophy of a language that tries to be easy to learn and easy to use. > Python is used by programmers who want to experiment with it, but who > usually know enough not to os.system("rm -r /") or anything similar. > Windows, on the other hand, wants to hide everything that can potentially > ruin the system as deep as possible so that many of the idiots who use that > system don't do stupid things like delete the registry, wipe the environment > settings, turn off the "Nag Screen" (UAC), and other things of that nature > But if it were sensible, it would (like certain other OS's) make it more difficult to have built-in permissions that allow you to totally hose the system, i.e. it would be secure.While it may not technically be using the same comparison criteria we do, Python still gives you the proper result: In [5]: 'obfuscation' is not 'security' and 'obfuscation' != 'security' Out[5]: True I think that's an important concept for programmers to realize. Allowing people to break things if they fool around enough is not a very sensible, or secure way of running things. And if you're writing OSes, the sensible thing is to write secure code. And if you're writing programs for general consumption, it's /also/ best to write secure code. That's my 2c anyways :) -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrew.replogle at gmail.com Tue Dec 16 14:21:35 2008 From: andrew.replogle at gmail.com (Andrew) Date: Tue, 16 Dec 2008 11:21:35 -0800 (PST) Subject: subprocess returncode windows References: Message-ID: <18348eae-5af1-47e9-a198-b95d4fcb6eac@a12g2000pro.googlegroups.com> On Dec 16, 12:50?pm, Christian Heimes wrote: > Andrew schrieb: > > > > > Hello, > > > I'm running into a strange situation with getting incorrect > > returncodes / exit status from python subprocess.call. I'm using a > > python script (runtime 2.6.1 on windows) to automate the deploy of > > java applications to glassfish application server. Below is an example > > of using a subprocess call to test the success / failure of the > > glassfish CLI tool "asadmin" > > > Example.py: > > ---------------------- > > import sys > > from subprocess import * > > > try: > > ? ? retcode = call("c:/glassfish/bin/asadmin.bat " + "list-system- > > properties --host mydomain --port 4848 --user admin server-01", > > shell=True) > > ? ? if retcode < 0: > > ? ? ? ? print >>sys.stderr, "Child was terminated by signal", -retcode > > ? ? else: > > ? ? ? ? print >>sys.stderr, "Child returned", retcode > > except OSError, e: > > ? ? print >>sys.stderr, "Execution failed:", e > > Don't use shell=True! Instead use a list of arguments without shell=True: > > call(["c:/glassfish/bin/asadmin.bat", "list-system-properties", "--host > mydomain", "--port 4848", "--user admin", "server-01"]) > > That should solve your quoting issues on Windows and fix your code. > shell=True is considered evil and should be avoided whenever possible. > > Christian Thanks Christian, I've removed shell=True, unfortunately, if I structure the call like: call(["c:/glassfish/bin/asadmin.bat", "list-system-properties", "-- host mydomain", "--port 4848", "--user admin", "server-01"]) It doesn't seem to recognize any arguments after list-system- properties. If I structure it like: call("c:/glassfish/bin/asadmin.bat "+"list-system-properties --host mydomain --port 4848 --user admin server-01") Then it executes correctly but still gives invalid returncode of 0 when it fails instead of 1. Andrew From steve at REMOVE-THIS-cybersource.com.au Wed Dec 31 01:27:01 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Dec 2008 06:27:01 GMT Subject: How to get back a list object from its string representation? References: <78f8019c0812302046j31fa38aeif33d659ec5f2c84e@mail.gmail.com> Message-ID: <016b07b4$0$6988$c3e8da3@news.astraweb.com> On Wed, 31 Dec 2008 03:08:29 -0200, Gabriel Genellina wrote: > eval is like Pandora?s box, all kind of bad things can come from it. Do > not use it with any user-supplied string. If you can restrict the values > to be just constants, there is a "safe eval" recipe in > http://code.activestate.com The ast module in Python 2.6 includes a "literal eval" function: >>> ast.literal_eval("[1, 2, 3]") [1, 2, 3] -- Steven From work8home4all at gmail.com Mon Dec 22 09:39:48 2008 From: work8home4all at gmail.com (work8home4all at gmail.com) Date: Mon, 22 Dec 2008 06:39:48 -0800 (PST) Subject: Start Earning With Commission junction Message-ID: Start Earning With Commission junction one of the biggest affiliate programes i.e running on internet in these days details on http://megalinesolutions.googlepages.com/cj_1 From gagsl-py2 at yahoo.com.ar Tue Dec 16 04:00:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Dec 2008 07:00:32 -0200 Subject: Structure using whitespace vs logical whitespace References: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> Message-ID: En Mon, 15 Dec 2008 14:29:31 -0200, cmdrrickhunter at yaho.com escribi?: > PS. In my opinion the solution would be to have the option of entering > a "whitespace insensitive" mode which uses C style {} and ;. The > token to enter it could be as complicated as you want (in fact, it may > make sense to make it complicated to discourage use unless it's really > advantageous). I'd sugest {{ and }} or something bigger like {={ } > =}. Only two problems: 1) I'm sure it would offend Guido's sense of > language aesthetics 2) I'm sure the idea has been hashed over on this > newsgroup to death... hence prefering a workaround instead. It's a hidden feature, already implemented. Try: from __future__ import braces -- Gabriel Genellina From dstanek at dstanek.com Thu Dec 25 18:18:03 2008 From: dstanek at dstanek.com (David Stanek) Date: Thu, 25 Dec 2008 18:18:03 -0500 Subject: Exec inside a class method to call other class methods? In-Reply-To: <4953CF57.8080905@sympatico.ca> References: <4953CF57.8080905@sympatico.ca> Message-ID: On Thu, Dec 25, 2008 at 1:22 PM, Matthew Dubins wrote: > Hello all, > > I have made a python script to upload contact information from an excel > worksheet to an online database. One part of the program that really > tripped me up was when I wanted to call specific class methods that I had > made to deal with specific types of contact information (Parent's name, > Child's name, Phone #, etc). My first thought was to make it easy using the > exec statement. > The code (a method within a class) looked like this: > ---------- > def parse(self, data, data_type) > exec "self.__parse_%s(data)" % data_type > ---------- > The data_type variable contains strings that exactly match the spellings of > the 2nd word in the titles of the class methods that I wanted to call for > each data_type inputted into the parse function. For some reason, *it > didn't work*. Alternately, I found the ugly code shown below to be > functional. As you can see, for each data_type, I call the corresponding > class method that I've specified. Please help me to transform my ugly > functional code into concise functional code. :) > > Thanks, > Matthew > ---------- > def parse(self, data, data_type): > if data_type == 'nocall': > self.__parse_nocall(data) > elif data_type == 'DOB': > self.__parse_DOB(data) > elif data_type == 'gender': > self.__parse_gender(data) > elif data_type == 'Prematurity': > self.__parse_Prematurity(data) > elif data_type == 'email': > self.__parse_email(data) > elif data_type == 'languages': > self.__parse_languages(data) > elif data_type == 'phone': > self.__parse_phone(data) > elif data_type == 'cname': > self.__parse_cname(data) > elif data_type == 'pname': > self.__parse_pname(data) > elif data_type == 'address': > self.__parse_address(data) > elif data_type == 'duedate': > self.__parse_dudedate(data) > I would look for a way to reorganize your code so that each type contains its own parse method. -- David http://www.traceback.org From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 23:22:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Dec 2008 04:22:53 GMT Subject: To Troll or Not To Troll (aka: "as" keyword woes) References: <20081205163107.1815df40@usenot.de> <27945697-3f2f-452d-bed4-d1ca45d46fbb@r10g2000prf.googlegroups.com> Message-ID: <0149f5d8$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 19:00:12 -0800, alex23 wrote: > On Dec 6, 8:00?am, James Stroud wrote: >> I think its a symptom of the language's maturing, getting popular, and >> a minority fraction* of the language's most devout advocates developing >> an egotism that complements their python worship in a most unsavory >> way. > > It's hard to see how anyone could ever take offence at your posts given > such unbiased objectivity ;) I see your wink, but, please, did you read that thread started by "r" about the Ruby API for some piece of Google software? That was so offensively fanboyish that I almost removed Python from my computer. -- Steven From rt8396 at gmail.com Mon Dec 22 14:28:44 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 11:28:44 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: On Dec 22, 1:10?pm, MRAB wrote: > r wrote: > > Steve Holden > >> What makes you assume this is a zero-sum game, and that Python won't > >> survive if any other language becomes popular. Every language borrows > >> from those that came before it. Terms like "outright plagiarism" don't > >> encourage rational debate, and make you seem like a troll who is more > >> interested in stirring up controversy than actually doing things to help > >> promote the language. > > > This is a war Steve, and i will explain why. Python does not need to > > compete with perl, lisp, C, basic, etc, etc. WHY, well because python > > is SO radically different than those languages. Ruby on the other > > hand, took most from python, the only difference is Ruby's full OO > > integration.(12.method()). Since Ruby is so similar to python we must > > consider that some people who would have found only python in this > > niche now could go to Ruby. I am for choices, but this is out and out > > robbery! > > Of course we must stand on the shoulders of greater minds than our own > > to get ahead, but using someone's knowledge against them is wrong. If > > Ruby want's to incorporate so many Pythonian ideas into their > > language, at least put a note in the tutorial giving credit to Guido > > for his wisdom. Don't use our ideas and then bash python in the next > > breath! > > [snip] > "Pythonian"? A real Pythonista would know it's "Pythonic"! A real > Pythonista would be called "p", not "r", which sounds very Rubish(?) to > me... MRAB -> '%sMuchRubyAndBasic' %'Too' MRAB -> Method.Ruby(AttractsBraindead) MRAB -> MyRubyAintBad MRAB -> MuchoRubyAndBasic Pythonian is more acceptable in the context of my sentence... """ If Ruby want's to incorporate so many Pythonian ideas into their language, at least put a note in the tutorial giving credit to Guido for his wisdom.""" Pythonian.translate() -> in the domain if Python... ownership Pythonic.translate() -> in a python style... (way of) two radically different meaning, of course if you vocabulary reaches that far?? From 4564 at 755189.45 Wed Dec 17 09:26:30 2008 From: 4564 at 755189.45 (Enrico) Date: Wed, 17 Dec 2008 15:26:30 +0100 Subject: Python, XML and XPath References: Message-ID: <49490c49$0$1115$4fafbaef@reader3.news.tin.it> "Hole" ha scritto nel messaggio news:daf5cd00-36dc-4ab4-976e-a6d859b52d0a at w24g2000prd.googlegroups.com... > Hi all, > > I hope this is not an "overasked" question but I find myself quite > confused about python xml management (I have to use python for a > project and I come from java world, you know...where frameworks, > libraries and tools to use are standard de iure or standard de facto). > > I need to use XML parsing with xpath: a simple xml reader. You can try lxml, have a look here http://codespeak.net/lxml/xpathxslt.html > > I've found that the standard distribution of python doesn't include > xpath support modules so I've decided to add libxml2. > > I've installed cygwin c compiler but I still have errors like the > following: > > C:\Python25\Lib\libxml2-python-2.6.9>python setup.py build install I never used libxml2 but version 2.6.9 seems quite old, according to this page: http://users.skynet.be/sbi/libxml-python/ Bye, Enrico From rt8396 at gmail.com Sat Dec 20 18:34:27 2008 From: rt8396 at gmail.com (r) Date: Sat, 20 Dec 2008 15:34:27 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> Message-ID: <59153e28-bf86-4158-96d9-23aa5b9f0205@j35g2000yqh.googlegroups.com> Walter, Would you be kind enough to translate this code to the new syntax? >>> s = 'python' >>> n = 12 >>> f = 1.333333333 >>> '%s %05d %0.2f' %(s,n,f) 'python 00012 1.33' i want to see how casting is handled. Thanks From nemokingdom at gmail.com Mon Dec 29 01:36:01 2008 From: nemokingdom at gmail.com (nemo) Date: Sun, 28 Dec 2008 22:36:01 -0800 (PST) Subject: ftp design question References: <74706983-5198-436b-b0ca-b0246a41c67e@v5g2000prm.googlegroups.com> Message-ID: <504983b3-fad0-4e01-a2cc-df2f67fe7157@r37g2000prr.googlegroups.com> On Dec 29, 12:31?pm, Steve Holden wrote: > nemo wrote: > > Hi,all. > > I'm on a toy ftp project and I want it to be convinient for the user > > to cancel an undergoing downloading while continue others. The > > following code explains: > > for file in download_files: > > ? ? self.ftp.retrbinary('RETR '+file, ?fileHandler) > > Thers seems not a solid way to cancel this transfer and I considered > > thread or process but I can't handle this correctly. > > Thread: I can't kill the thread in another thread, so... > > Process: There seems something wrong(raise an EOFError exception) when > > I use Process(target = download_fun, args = (dir,)) for each > > downloading after connection built. > > Some suggestions? > > How about > > for file in download_files: > ? ? try: > ? ? ? ? self.ftp.retrbinary('RETR %s' % file, fileHandler) > ? ? except KeyboardInterrupt: > ? ? ? ? print file, "transfer abandoned" > > Then you can cancel a single file transfer with Ctrl/C. > > regards > ?Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ Thanks your advice, actually, this ftp has a GUI interface, so I'm considering the downloading part in another process or thread, whick is s a tricky part for me to design. From skip at pobox.com Mon Dec 22 11:01:18 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 22 Dec 2008 10:01:18 -0600 Subject: Python's popularity In-Reply-To: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: <18767.47566.709705.92@montanaro-dyndns-org.local> Walter> From what I have seen: Walter> - in unix/linux sysadmin, perl is far more popular than python, Walter> windows sysadmins typically don't use either. Walter> - in web-development, php is far more popular than python - it's not Walter> even close. Walter> - when I did a search on dice, I found over 20X more jobs advertised Walter> for ruby on rails developers, than for python dango developers. Walter> - application development is dominated by java, c/c++, and maybe a Walter> little visual basic. Walter> - as I understand it, fortran is still the most popular language for Walter> numberical programming. Looking at specific application domains doesn't tell the entire story. If you look back at the Tour de France results from the 80's I believe Greg Lemond won it one year without ever winning a stage. What you are reporting is akin to that. Fortran is almost certainly the king of numerical programming, but Python might be #2 or #3 there (behind Matlab). I'm pretty sure it dwarfs Perl, PHP and Ruby in that domain. In web development, while PHP is more popular than Python, Python is probably much more popular than Perl and Tcl. Maybe not ahead of Ruby due to RoR. etc etc. Skip From fetchinson at googlemail.com Wed Dec 10 16:35:30 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 10 Dec 2008 13:35:30 -0800 Subject: looking up function's doc in emacs In-Reply-To: References: Message-ID: > in programing elisp in emacs, i can press "Ctrl+h f" to lookup the doc > for the function under cursor. > > is there such facility when coding in perl, python, php? > > (i'm interested in particular python. In perl, i can work around with > "perldoc -f functionName", and in php it's php.net/functionName. Both > of which i have a elisp command with a shortcut that let me jump to > the doc) Why can't you do the same with pydoc (the command line tool, ususally installed in /usr/local/bin/pydoc or somewhere else if python shipped with your distro). Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From federico at linux.com.uy Tue Dec 16 12:51:20 2008 From: federico at linux.com.uy (Federico Moreira) Date: Tue, 16 Dec 2008 14:51:20 -0300 Subject: Generator slower than iterator? In-Reply-To: References: Message-ID: 2008/12/16 > Python 3.0 does not support has_key, it's time to get used to not using it > :) > Good to know line.split(None, 1)[0] really speeds up the proccess Thanks again. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cjw at ncf.ca Sat Dec 6 09:20:42 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 06 Dec 2008 09:20:42 -0500 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: <493A8A3A.6060203@ncf.ca> Daniel Fetchinson wrote: > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html > > The proposal is to allow this: > > class C: > def self.method( arg ): > self.value = arg > return self.value > > instead of this: > > class C: > def method( self, arg ): > self.value = arg > return self.value > > I.e. explicit self stays only the syntax is slightly different and may > seem attractive to some. As pointed out by Guido classmethods would > work similarly: > > class C: > @classmethod > def cls.method( arg ): > cls.val = arg > return cls.val > > The fact that Guido says, > > "Now, I'm not saying that I like this better than the status quo. But > I like it a lot better than [...] but it has the great advantage that > it is backward compatible, and can be evolved into a PEP with a > reference implementation without too much effort." > > shows that the proposal is viable. > > I'd like this new way of defining methods, what do you guys think? > Anyone ready for writing a PEP? > > Cheers, > Daniel > The quoted blogspot is not available. I like the idea but I don't see how explicit and implicit can co-exist. Version 3.0 is the time to introduce the enhancement. Colin W. From marco at sferacarta.com Thu Dec 4 10:28:44 2008 From: marco at sferacarta.com (Marco Mariani) Date: Thu, 04 Dec 2008 16:28:44 +0100 Subject: Pythonic design patterns In-Reply-To: <45fdd23c-0ccc-4135-b10c-1ef1d5ea4e6b@p2g2000prf.googlegroups.com> References: <0147e8b9$0$20670$c3e8da3@news.astraweb.com> <45fdd23c-0ccc-4135-b10c-1ef1d5ea4e6b@p2g2000prf.googlegroups.com> Message-ID: George Sakkis wrote: >> This is all very good, but don't drink the design pattern Kool-Aid and >> start pushing design patterns everywhere. (Not everything needs to be a >> singleton. No, really.) > > Obligatory reading: http://www.mortendahl.dk/thoughts/blog/view.aspx?id=122 By the way, it's a fact that many low-level patterns, as they are described, are useful mainly/only in statically typed languages. The ones in PEAA, for instance, are high-level enough to be useful in any environment. http://www.amazon.com/Enterprise-Application-Architecture-Addison-Wesley-Signature/dp/0321127420 From steve at REMOVE-THIS-cybersource.com.au Fri Dec 26 22:07:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Dec 2008 03:07:53 GMT Subject: Is there a function to remove escape characters from a string ? References: <0163882f$0$6988$c3e8da3@news.astraweb.com> <5a29b62a-c38f-409b-8887-6259ad072bf5@w1g2000prk.googlegroups.com> Message-ID: <01659326$0$6988$c3e8da3@news.astraweb.com> On Sat, 27 Dec 2008 01:41:40 +0100, Stef Mientki wrote: > Sorry if I offended someone, that was certainly not my intention. And I > guess you will be surprised, if I tell you, I don't (want) to understand > any bit of the above code ;-) Come on, the home computer was invented > about 1980. If we look at hardware, it follows the Moore's law, for > software I would expect at least 0.1 of Moore's law ;-) I hope that > clarifies my point. No, that only makes it even more confusing. What does Moore's Law have to do with your willful ignorance about the existence of human languages other than English? -- Steven From zhushenli at gmail.com Wed Dec 3 07:27:26 2008 From: zhushenli at gmail.com (Davy) Date: Wed, 3 Dec 2008 04:27:26 -0800 (PST) Subject: Thread Tkinter problem Message-ID: <64c7402c-8b7b-4281-9d7d-1abdd6177d96@r15g2000prh.googlegroups.com> Hi all, I am using thread and tkinter to write some simple programs and solidify my understanding of Python thread/GUI programing. The scheme is thread + queue + GUI. One child thread (gen_board_thread) generate board and insert data into queue infinitely. Meanwhile, the main thread canvas widget get the board data from queue. I assume the program will run forever if don't close them explicitly, but the fact is contrary to my understanding. It seems the child thread insert data till queue is full, then the main thread eat the data till the queue is empty, and the main thread starve(when timeout option is set) and die. So the two thread work like two function call, but not two thread! Is this situation caused by deadlock(I guess main thread has higher priority)? Or how can I know whether the child thread is still alive? Ultimately, how to solve the problem? The code are attached. Any suggestion will be appreciated :-) Best regards, Davy //---------Code below--------------- from Tkinter import * import thread import Queue ##import time x = 3 ## vertical y = 5 ## horizontal block_width = 10 block_height = 10 canvas_width = x * block_width canvas_height = y * block_height data_queue = Queue.Queue(20) board_1 = [[1,0,1], [0,1,1], [1,0,0], [0,0,1], [0,1,0]] board_2 = [[0,1,0], [1,0,0], [0,1,1], [1,1,0], [1,0,1]] def gen_board_thread(): ## Problem: the thread seems to be deadlock or killed or postponed after execution was taken over by main thread draw_canvas_loop() print 'enter here' gen_flip = 1 while(data_queue.full() == False): ##print '???' ##time.sleep(0.1) if (gen_flip == 1): gen_flip = 0 data = board_1 else: gen_flip = 1 data = board_2 data_queue.put(data) print 'put', data_queue.qsize() def create_canvas(root,canvas_width,canvas_height,): canvas = Canvas(root, width=canvas_width, height=canvas_height, bg='white') canvas.pack(expand=YES) return canvas def draw_canvas_loop(canvas_b): board = data_queue.get(block = True, timeout=1) print 'get', data_queue.qsize() draw_canvas(board, canvas_b, x, y, block_width, block_height) canvas_b.after(300, lambda:draw_canvas_loop(canvas_b)) def draw_canvas(board, canvas_b, x, y, block_width, block_height): ##canvas_b.after(3000) ##time.sleep(3) for j in range(y): for i in range(x): if board[j][i] == 1: color = 'black' else: color = 'white' start_x = block_width * i start_y = block_height * j end_x = start_x + block_width end_y = start_y + block_height canvas_b.create_rectangle (start_x,start_y,end_x,end_y,fill=color) if __name__ == '__main__': root = Tk() root.title('Tetris') canvas = create_canvas(root,canvas_width,canvas_height) thread.start_new(gen_board_thread,()) draw_canvas_loop(canvas) mainloop() From ldo at geek-central.gen.new_zealand Wed Dec 3 03:15:45 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 03 Dec 2008 21:15:45 +1300 Subject: Multiple equates References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> <9m3h06-vhh.ln1@lairds.us> Message-ID: Cameron Laird wrote: > def f1(Match): > return Something missing here? From marduk at letterboxes.org Sat Dec 6 07:47:27 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Sat, 06 Dec 2008 07:47:27 -0500 Subject: Insert Multiple Records Using One Insert Statemen with MySQLdb module In-Reply-To: <6d85c9db-2769-461b-bfe0-974e4fad5e07@k8g2000yqn.googlegroups.com> References: <6d85c9db-2769-461b-bfe0-974e4fad5e07@k8g2000yqn.googlegroups.com> Message-ID: <1228567647.20032.1.camel@blackwidow.nbk> On Sat, 2008-12-06 at 04:03 -0800, anton.ranieri.it at gmail.com wrote: > Hi, > > I'd like to insert Multiple Records Using One Insert Statement > > inserting one record using one insert statement works > this is the example: > > import MySQLdb > conn = MySQLdb.connect(host="localhost",.....) > cursore = conn.cursor() > cursore.execute('INSERT INTO frutta (nome, quantita) VALUES(%s, %s)', > ('Pompelmi', 10) > ) > > but when I try to insert Multiple Records Using One Insert Statement > in this way: > > cursore.execute('INSERT INTO frutta (nome, quantita) VALUES(%s, %s)', > ('Pompelmi', 10), > ('Pompelmi', 10), > ('Pompelmi', 10) > ) > > it doesn't work! You want to use the cursor's .executemany() method. > -- > http://mail.python.org/mailman/listinfo/python-list From rt8396 at gmail.com Mon Dec 22 18:47:55 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 15:47:55 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <6ra8t0F925rU1@mid.individual.net> <29feda0d-6432-4cb9-8809-e4d4a7798601@e1g2000pra.googlegroups.com> <6raeb8F9s47U2@mid.individual.net> <6rahpaFav7kU2@mid.individual.net> <97e49a8c-6730-42f2-b4d0-35eaff38b69f@y1g2000pra.googlegroups.com> Message-ID: <48221004-94ce-4b2a-b94a-1ca45a2562b8@j11g2000yqg.googlegroups.com> [Jeff] but I raise the bar so that any random joker probably won't bother (and making the reverse mapping - knowing my real identity and then looking for recent net activity - is much more difficult to do) [/Jeff] You are the epitimy of an internet troll. A troll tries to hide his identity. Why are you so concerned about your TRUE identity. Are the FEDS after you, maybe it's the Martians i do not know? Did they take into their spaceship and do things to you? Do you wear a aluminum foil hat. Look out for those cell towers, there mind control devices hahaha. Thanks for the good laugh. From brendandetracey at yahoo.com Fri Dec 12 11:20:38 2008 From: brendandetracey at yahoo.com (Brendan) Date: Fri, 12 Dec 2008 08:20:38 -0800 (PST) Subject: Reading online zip files - zipfile and zlib, wbits References: <21ba0ff5-7698-481a-851c-80b9ddcd5814@q26g2000prq.googlegroups.com> Message-ID: On Dec 12, 11:36?am, Brendan wrote: > On Dec 12, 10:46?am, Brendan wrote: > > > > > > > On Dec 12, 10:25?am, Brendan wrote: > > > > I am fooling around with accessing contents of zip files online. I > > > download the tail end of the zip and use zipfile to get the zip > > > central directory structure. I download the section of the zip file I > > > need, directly read the zip file headers and use that information with > > > zlib to uncompress the data. The files I am examining will always be > > > compressed using deflate, with a wbits value of -15(minus for > > > headerless data because I am unsure whether the zip file header is > > > what zlib expects). > > > > I can not find anywhere in the PK Zip Application notes (http://www.pkware.com/documents/casestudies/APPNOTE.TXT) how to > > > determine the value I should uze for wbits with zlib.decompress. I > > > have determined it is -15 from experimentation. Does anyone know the > > > answer to this? > > > Okay, I found part of the answer here in the zip app notes > > [quote] > > general purpose bit flag: (2 bytes) > > > ? ? ? ? ? Bit 0: If set, indicates that the file is encrypted. > > > ? ? ? ? ? (For Method 6 - Imploding) > > ? ? ? ? ? Bit 1: If the compression method used was type 6, > > ? ? ? ? ? ? ? ? ?Imploding, then this bit, if set, indicates > > ? ? ? ? ? ? ? ? ?an 8K sliding dictionary was used. ?If clear, > > ? ? ? ? ? ? ? ? ?then a 4K sliding dictionary was used. > > ? ? ? ? ? Bit 2: If the compression method used was type 6, > > ? ? ? ? ? ? ? ? ?Imploding, then this bit, if set, indicates > > ? ? ? ? ? ? ? ? ?3 Shannon-Fano trees were used to encode the > > ? ? ? ? ? ? ? ? ?sliding dictionary output. ?If clear, then 2 > > ? ? ? ? ? ? ? ? ?Shannon-Fano trees were used. > > > ? ? ? ? ? (For Methods 8 and 9 - Deflating) > > ? ? ? ? ? Bit 2 ?Bit 1 > > ? ? ? ? ? ? 0 ? ? ?0 ? ?Normal (-en) compression option was used. > > ? ? ? ? ? ? 0 ? ? ?1 ? ?Maximum (-exx/-ex) compression option was > > used. > > ? ? ? ? ? ? 1 ? ? ?0 ? ?Fast (-ef) compression option was used. > > ? ? ? ? ? ? 1 ? ? ?1 ? ?Super Fast (-es) compression option was used. > > [/quote] > > > Now I just don't understand Why Normal deflate corresponds to 15 > > wbits, and why I have to use headerless for the data, i.e. wbits = -15. > > Seems the bit flags are not properly set, bit 2 should be 0 and bit 1 > should be 1, to correspond to maximum compression i.e. wbit = 15. > Still don't know why wbits has to be negative.- Hide quoted text - > > - Show quoted text - Arg! Tried a different tack. Took the file header plus compressed file and concatenated with central directory. Now need only zipfile module. From walterbyrd at iname.com Mon Dec 22 12:48:19 2008 From: walterbyrd at iname.com (walterbyrd) Date: Mon, 22 Dec 2008 09:48:19 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: On Dec 22, 10:13?am, r wrote: > Since the > advent of Ruby(Python closet competitor), Python's hold on this niche > is slipping. About the only place I ever hear of ruby being used is web development with RoR. When it comes to web development, it seems to me that ruby (because of rails) is far more popular than python. It seems to me that ruby is the niche player, and python (with fairly new frameworks) is trying to catch up to ruby in that niche. It seems to me that the python web framework that best competes with rails, is Django, and Django 1.0 just came out a few months back. > A lot of Ruby noobies don't even realize that most of > Ruby is an out-right plagiarism of Python. Maybe. But the rails framework seems to have a different philosophy than the django, turbogears, or pylons, frameworks. RoR values convention over configuration, and has a lot of "magic" whereas the python frameworks seem to have the opposite philosophy - in those regards. I see pros and cons to both approaches. I wonder what the market with think? > Now since Python *is not* the only language on it's block, we have to > compete with our main nemesis(Ruby) for survival I think both python and ruby will "survive." I think python is also competing with perl in the sysadmin space - although I see perl as being much more popular there. From deets at nospam.web.de Wed Dec 17 09:17:35 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 17 Dec 2008 15:17:35 +0100 Subject: Python, XML and XPath References: Message-ID: <6qsfvvFeen6dU1@mid.uni-berlin.de> Hole wrote: > Hi all, > > I hope this is not an "overasked" question but I find myself quite > confused about python xml management (I have to use python for a > project and I come from java world, you know...where frameworks, > libraries and tools to use are standard de iure or standard de facto). I suggest you use one of the available binary builds for windows: http://pypi.python.org/pypi/lxml/2.1 Diez From grahn+nntp at snipabacken.se Mon Dec 8 16:32:31 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 8 Dec 2008 21:32:31 GMT Subject: Source code generation using Python References: <82098706-978f-4920-ac75-57ef3573ac44@x38g2000yqj.googlegroups.com> Message-ID: On Sat, 6 Dec 2008 13:47:26 -0800 (PST), ats wrote: > Hello, > > This is my first posting to a Python group (and I'm starting with > Python seriously only now) , so bear with me if I make some mistakes. > > I want to generate 3 different versions of a C++ source code, > basically injecting different flavours of inline assembler depending > on target compiler/CPU. > > Code generation should be integrated into a 'master source file' which > is the processed and generates the right code for GCC / MSVC or other > cases. Something like: > > int FastAdd( int t1, int t2 ){ > int r; > ##if USE_INLINE_ASM > #ARG( eax, "t1") > #ARG( ebx, "t2") > #ASM( "add", ebx, eax ) > #RES( eax, "r" ) > ##else > r = t1+t2; > ##endif > return r; > } You didn't say explicitly, so I have to ask: is there a reason you cannot use the C++ preprocessor? It does exactly what you describe, and would be the least surprising solution to the readers. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From renesd at gmail.com Thu Dec 4 22:06:10 2008 From: renesd at gmail.com (illume) Date: Thu, 4 Dec 2008 19:06:10 -0800 (PST) Subject: Python 3.0 C API migration tools, or docs? References: <008877d2-8705-48a6-bb09-6c31c6b77970@p2g2000prf.googlegroups.com> <1a5cf43f-5802-4c69-9226-18cbc6256c0c@k19g2000yqg.googlegroups.com> Message-ID: Cool thanks Benjamin! Maybe it should be in a wiki as well? So that as people convert their modules we can add notes as well. I started a wiki with that in mind here: http://wiki.python.org/moin/cporting It'd be good if there was a link from the 2to3 docs, and in the C API docs to either/both of these resources. I thought there'd be much more help for people migrating considering the 2to3 tool exists... but I'll get over it... hehe. cheers, On Dec 5, 1:23?pm, Benjamin wrote: > On Dec 4, 7:45?pm, illume wrote: > > > Hi, > > > are there migration tools for C API migration to python 3? > > > I'm sure there must be some code somewhere to help change stuff over > > right? > > > I don't see any docs for migrating code from 2.x to 3.x either:http://docs.python.org/3.0/c-api/index.html > > At the moment all that is officially available is this rather > incomplete howto:http://docs.python.org/howto/cporting.html > > > > > Help needed with this! > > > cheers, > > From sibteym at infotechsw.com Mon Dec 29 05:31:42 2008 From: sibteym at infotechsw.com (Sibtey Mehdi) Date: Mon, 29 Dec 2008 16:01:42 +0530 Subject: poblem regarding opening a html file Message-ID: <022701c969a0$a4541ef0$5fc513ac@pwit.com> Hi I have a GUI application (wxpython) that calls another GUI Application. I m using os.system (cmd) to launch The second GUI, in the second GUI I m trying to open the html file using the os.startfile (filename) function but It takes lots of time to open the html file. If I am running only the second application then 'os.startfile' quickly open the html file. Any one can help me to solve this problem. Thanks. Sibtey -------------- next part -------------- An HTML attachment was scrubbed... URL: From saju.pillai at gmail.com Thu Dec 11 08:33:53 2008 From: saju.pillai at gmail.com (Saju Pillai) Date: Thu, 11 Dec 2008 05:33:53 -0800 (PST) Subject: Python, threading References: Message-ID: On Dec 11, 6:06?pm, SMALLp wrote: > Hy. I have a problem! I'm making multi thread application (client, > server) using wxPython for GUI, and threading.Thread for threding. > > Clients connect and when they are connected (evry thread handles one > connection) threads change main window. > > I neded tip how to make communication between threeds. Threads already share data your problem would likely be to synchronize the threads - threading.Sempahore & threading.Lock will help Maybe you want some threads to wait while other thread(s) do some work ? - threading.Event & threading.Condition The documentation on "threading" module is where you should start. -srp -- http://saju.net.in From prologic at shortcircuit.net.au Sun Dec 7 23:50:57 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Dec 2008 14:50:57 +1000 Subject: infering the number of args a function takes at runtime In-Reply-To: <47c890dc0812072045g3b9d17c8r5768028afd22262d@mail.gmail.com> References: <47c890dc0812072045g3b9d17c8r5768028afd22262d@mail.gmail.com> Message-ID: On Mon, Dec 8, 2008 at 2:45 PM, Chris Rebert wrote: > On Sun, Dec 7, 2008 at 8:39 PM, sniffer wrote: >> hi all, >> i am a python newbie, in a project currently doing i need to find out >> the number of arguments that a function takes at runtime.? Is this >> possible ,if so how do i do this,i ve looked through the python >> documentation but couldnt find anything.any help will be great > > You want inspect.getargspec() or one of its friends in the `inspect` > module. See http://docs.python.org/library/inspect.html#inspect.getargspec Also, I have to ask: Why do you need to do this ? Please show some code samples of what you're trying to achieve and what the problem is ? cheers James -- -- -- "Problems are solved by method" From gagsl-py2 at yahoo.com.ar Wed Dec 24 12:48:34 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2008 15:48:34 -0200 Subject: Custom C Exception Subclasses References: <41f291ff-d7bd-4334-8689-636e95524cdc@b38g2000prf.googlegroups.com> Message-ID: En Wed, 24 Dec 2008 15:00:36 -0200, Ivan Illarionov escribi?: > On Dec 24, 6:42?pm, Ross wrote: >> For a project that I am doing, it would be useful to have an exception >> class that stores some additional data along with the message. >> However, I want to be able to store a couple pointers to C++ classes, >> so I can't just use an exception created with PyExc_NewException. ?If >> I were to subclass the built-in Exception type, I would need to have >> access to the PyExc_ExceptionObject, but the headers only give >> PyExc_Exception, the type object. ?This seems like a rather >> straightforward task, but I can't seem to find any documentation for >> it. ?Does anyone know how to do this? ?Thanks! > > When you raise an exception in C++ you can set it to ANY Python object > via PyErr_SetObject and that object could store pointers to C++ > classes. Remember that exceptions should inherit from BaseException; although this rule isn't enforced in Python 2.6, 3.0 doesn't allow that. It isn't explicitely written in the docs, but I think that PyErr_SetObject won't allow you to pass an object which is not an instance of its first argument. -- Gabriel Genellina From bdesth.quelquechose at free.quelquepart.fr Wed Dec 3 13:16:29 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 Dec 2008 19:16:29 +0100 Subject: python an sqlite objects In-Reply-To: References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <4936bceb$0$16783$426a34cc@news.free.fr> Message-ID: <4936dab7$0$9107$426a74cc@news.free.fr> skip at pobox.com a ?crit : > Bruno> Or if you want something more portable, serialize the object to > Bruno> json. At least you'll have a chance to deserialize it with some > Bruno> other language. > > Assuming json can serialize more-or-less arbitrary Python objects. I assume the OP knows what kind of objects he's going to serialize. > Can > it serialize class instances? instances of which class ?-) More seriously: simplejson knows how to serialize most builtin types. For other types, you have to write your own serializer, but it's _usually_ quite simple. Most of the time, you want to serialize the instance's __dict__. From max at alcyone.com Sat Dec 6 19:34:56 2008 From: max at alcyone.com (Erik Max Francis) Date: Sat, 06 Dec 2008 16:34:56 -0800 Subject: Guido's new method definition idea In-Reply-To: <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> Message-ID: Russ P. wrote: > Python already uses shorthand extensively. How about "def"? For people > who are so worried about self-explanatory symbols, what the heck does > that stand for? Default? Defeat? Defect? Defunct? Defer? That's pretty silly; it's pretty obvious that `def` means "define," and even if that weren't obvious on its face, in context it's _really_ obvious. `def f(): ...` certainly isn't going to be confused to a request to defecate on something called `f`, after all -- which is about as plausible as your other suggestions. `$` as a shortcut for self, on the other hand, gives absolutely no mnemonic indication what it stands for, and users would be simply left guessing. P.S. You're beating a long-dead horse here; your precise proposal has been brought up countless times on comp.lang.python and shot down every single time for the same reason. It isn't going to happen. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis There are not fifty ways of fighting, there is only one: to be the conqueror. -- Andrew Malraux, 1937 From robert.kern at gmail.com Wed Dec 3 18:15:48 2008 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 03 Dec 2008 17:15:48 -0600 Subject: "as" keyword woes In-Reply-To: <01470229$0$20670$c3e8da3@news.astraweb.com> References: <493701f0$0$194$e4fe514c@news.xs4all.nl> <01470229$0$20670$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > While I feel sympathy for the OP, I do have to ask: he's been using > Python 2.5 for, what, a couple of years now? How many times did he see > the depreciation warning, and almost certainly the pending depreciation > warning before that? Python-dev has been talking about making "as" a > keyword since at least Python 2.3. Why wait until after version 2.6 is > released before saying anything? It's entirely possible that he did not see the warning. Python 2.5 has a bug where the warning gets silenced by an intervening import. http://bugs.python.org/issue3936 -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From zxo102 at gmail.com Sat Dec 27 00:03:24 2008 From: zxo102 at gmail.com (zxo102) Date: Fri, 26 Dec 2008 21:03:24 -0800 (PST) Subject: How to display Chinese in a list retrieved from database via python References: <22be506d-91c2-4727-ace7-2e3382b6d214@g3g2000pre.googlegroups.com> <979fdf6d-0500-47ba-87fd-0f0361ca3059@p2g2000prf.googlegroups.com> Message-ID: <19680ed2-c78f-4ab9-8ca0-8ce26fd5b6a7@o4g2000pra.googlegroups.com> On 12?26?, ??3?16?, "Mark Tolonen" wrote: > "zxo102" wrote in message > > news:979fdf6d-0500-47ba-87fd-0f0361ca3059 at p2g2000prf.googlegroups.com... > > > > > > > On 12?26?, ??4?58?, "Gabriel Genellina" > > wrote: > >> En Thu, 25 Dec 2008 07:27:03 -0200, zxo102 escribi?: > > >> > On 12?25?, ??3?35?, "Chris Rebert" wrote: > >> >> On Wed, Dec 24, 2008 at 11:29 PM, zxo102 wrote: > >> >> > Hi, > >> >> > I retrieve some info in Chinese from postgresql and assign it to > >> >> > a > >> >> > variable 'info' defined in javascript of a html page: > >> >> > var info = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce > >> >> > \xc4'] > >> >> > But I want it to be > >> >> > var info = ['??','??','??'] > >> >> > since in html pages (via javascript), the items in chinese out of > >> >> > the > >> >> > former :['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4'] > >> >> > can > >> >> > not be displayed correctly when it is inserted into a html page. If > >> >> > the list is var info = ['??','??','??'] , then everything > >> >> > works > >> >> > fine. > > >> > The html code is as follows > > >> > test > >> > > >> > > > >> > But the '??' is '\xd6\xd0\xce\xc4'. When row01 and row02 is called > >> > from somewhere, > >> > '\xd6\xd0\xce\xc4' can not be displayed correctly as '??' in html > >> > environment. > > >> You forgot to specify the page encoding, gb2312 presumably. If adding the > >> encoding does not help, I'd say the problem must reside on how you later > >> use row01 and row02 (your html page does not those variables for > >> anything). '??' is the same as '\xd6\xd0\xce\xc4', and both javascript > >> and Python share the same representation for strings (mostly) so this > >> should not be an issue. > > >> My PC is unable to display those characters, but I get "true" from this: > > >> test > >> > > >> -- > >> Gabriel Genellina > > > I did that: , but it does not work. Alert('\xd6\xd0\xce\xc4') > >> displays some "junks". I am thinking there may be some way to convert > >> '\xd6\xd0\xce\xc4' to '??' in the list with python before I generate > >> the html page. As a result, when I open the html file with Vi, I can see > >> '??' directly instead of '\xd6\xd0\xce\xc4'. That will solve my > >> problem. > > > Any ideas? > > Use charset=gb2312 instead of charset='gb2312'(remove single quotes). > > I was able to display ?? successfully with this code: > > f=open('test.html','wt') > f.write(''' > > test > \xd6\xd0\xce\xc4''') > f.close() > > -Mark- ??????? - > > - ??????? - Mark, I have exactly copied your code into the htdocs of my Apache server, test \xd6\xd0\xce\xc4 but it still shows me \xd6\xd0\xce\xc4. Any ideas? ouyang From steve at REMOVE-THIS-cybersource.com.au Tue Dec 16 20:26:44 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 17 Dec 2008 01:26:44 GMT Subject: How to modify a program while it's running? References: Message-ID: <01584cbd$0$20656$c3e8da3@news.astraweb.com> On Tue, 16 Dec 2008 13:25:17 -0700, Joe Strout wrote: > Here's my situation: I'm making an AIM bot, but the AIM server will get > annoyed if you log in too frequently (and then lock you out for a > while). So my usual build-a-little, test-a-little methodology doesn't > work too well. Ouch! What AIM server are you running? Perhaps you need a less curmudgeonly one? > So I'd like to restructure my app so that it can stay running and stay > logged in, yet I can still update and reload at least most of the code. > But I'm not sure what's the best way to do this. Should I move the > reloadable code into its own module, and then when I give my bot a > "reload" command, have it call reload on that module? Will that work, > and is there a better way? That should work for functions, but less successfully with classes. The problem is that existing objects will still have the old behaviour even after reloading the class. In the interactive interpreter, the easiest way around that is to just throw the instance away and recreate it. That's not very convenient. You may be able to work around that by keeping a list of instances, then going through each one and saying: instance.__class__ = mymodule.MyClass although I haven't tried this and don't know if it even works. -- Steven From bdesth.quelquechose at free.quelquepart.fr Sun Dec 14 14:20:40 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 14 Dec 2008 20:20:40 +0100 Subject: Looking for the best way to translate an idiom In-Reply-To: References: <4945406a$0$1127$426a74cc@news.free.fr> Message-ID: <49456a3f$0$27546$426a74cc@news.free.fr> Steve Holden a ?crit : > Bruno Desthuilliers wrote: > [...] >> if you only want the first returned value, you can just apply a slice: >> >> def f(): >> return 1,2,3 >> >> a = f()[0] + 1 >> > That isn't a slice, it's indexing Yeps, sorry - and thanks for the correction. From mailmaverick666 at gmail.com Fri Dec 5 02:17:05 2008 From: mailmaverick666 at gmail.com (rishi pathak) Date: Fri, 5 Dec 2008 12:47:05 +0530 Subject: CONNECTION TIMED OUT ERROR using urllib2 In-Reply-To: <726d283d0812042236j792f4706v373ca6449861e3e2@mail.gmail.com> References: <726d283d0812042217w41a0288eg3ee79d4ffdb5ff4b@mail.gmail.com> <180b672e0812042227j12a4d647k84e507dfae77d665@mail.gmail.com> <726d283d0812042236j792f4706v373ca6449861e3e2@mail.gmail.com> Message-ID: <180b672e0812042317v55308ff1x42959d08dfe63bb5@mail.gmail.com> Before executing script do export http_proxy=http://:/ On Fri, Dec 5, 2008 at 12:06 PM, svalbard colaco wrote: > Hi rishi, > > Thanks for ur reply, > yes i set the following enviroment variables (FC6 platform) > http_proxy,http_user,http_password > > But i get the same error; Can u tell me which other variables i need to > set or am i going wrong in the syntax of these > variables? > > Regards > sv > > > On Fri, Dec 5, 2008 at 11:57 AM, rishi pathak wrote: > >> Are you sitting behind a proxy. If so then you have to set proxy for http >> >> On Fri, Dec 5, 2008 at 11:47 AM, svalbard colaco < >> svalbardcolaco at gmail.com> wrote: >> >>> Hi all >>> >>> I have written a small code snippet to open a URL using urllib2 to open a >>> web page , my python version is 2.4 but i get an urlopen error called >>> connection timed out >>> >>> The following is the code snippet >>> >>> *import urllib2 >>> >>> f = urllib2.urlopen('http://www.google.com/') >>> print f.read(100)* >>> >>> >>> where as the same url http://www.google.com/ works through my browser. >>> >>> The following is the back trace : >>> >>> File "test_url.py", line 3, in ? >>> f = urllib2.urlopen('http://www.google.com/') >>> File "/usr/lib/python2.4/urllib2.py", line 130, in urlopen >>> return _opener.open(url, data) >>> File "/usr/lib/python2.4/urllib2.py", line 358, in open >>> response = self._open(req, data) >>> File "/usr/lib/python2.4/urllib2.py", line 376, in _open >>> '_open', req) >>> File "/usr/lib/python2.4/urllib2.py", line 337, in _call_chain >>> result = func(*args) >>> File "/usr/lib/python2.4/urllib2.py", line 1021, in http_open >>> return self.do_open(httplib.HTTPConnection, req) >>> File "/usr/lib/python2.4/urllib2.py", line 996, in do_open >>> raise URLError(err) >>> *urllib2.URLError: >>> >>> >>> Any pointers in this regard will be of great help. >>> >>> Thanking you'll in advance. >>> >>> Regards, >>> sv >>> >>> >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >>> >> >> >> -- >> Regards-- >> Rishi Pathak >> Pune-Maharastra >> > > -- Regards-- Rishi Pathak Pune-Maharastra -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul.hermeneutic at gmail.com Sat Dec 6 11:36:44 2008 From: paul.hermeneutic at gmail.com (Paul Watson) Date: Sat, 06 Dec 2008 10:36:44 -0600 Subject: Running Python 2 and Python 3 on the same machine In-Reply-To: <493A4C89.8070007@v.loewis.de> References: <1228424486.5873.6.camel@linux-3eb6.site> <49387f7e$0$27857$9b622d9e@news.freenet.de> <1228489547.5613.10.camel@linux-3eb6.site> <4939c6ef$0$6534$9b622d9e@news.freenet.de> <1228539820.27659.21.camel@linux-3eb6.site> <493A4C89.8070007@v.loewis.de> Message-ID: <1228581374.3651.16.camel@linux-3eb6.site> On Sat, 2008-12-06 at 10:57 +0100, "Martin v. L?wis" wrote: > > Ok. I built the source on an openSUSE 11.0 system. I used 'sudo make > > altinstll'. It created an executable /usr/local/bin/python3.0 file. > > Nothing was touched in /usr/bin. > > Ah, then you missed the fun part. Take a look at the install: target > in the Makefile. > > > I need to start writing some code with Python 3. I want to write the > > code in such a way that it can be easily shared with others with the > > least difficulty and overhead as possible. How should I write the code > > to enable this? What, if anything, should I assume about another > > system's configuration? > > I don't quite understand the problem. Sharing code is very easy over > the internet. You can upload it on PyPI (say), or mail it. So you > must be asking for something else. > > > As someone suggested before, naming the files as '.py3' is probably a > > bad idea in the long run. It also does not really solve the problem. > > > > I could use a shebang. But, what should it specify? If I use > > 'python3.0', then that will soon be quite old. If I make up a link for > > python3 -> python3.0, that would work, but then every other system that > > is to run the code must that link also. However, I am thinking that > > this would be the best long term answer. > > Well, this will be rejected. It might be a good medium-term answer, but > it is a *bad* long-term answer. In the long term, Python 2 will > disappear, and we are stuck with calling the interpreter python3. > > > If I write scripts for Python 3, another developer writes scripts for > > Python 2, and a common customer wants to install both of our packages > > onto a single machine, then what is the best plan for everyone to make > > that happen with as little difficulty as possible? > > My recommendation is to use distutils, for a long-term answer. People > will run "python3.0 setup.py install", and distutils' install_scripts > will replace the shebang line with the actual path to Python 3.0. > This has not only the advantage of continuing to work for 3.1; it has > also the advantage that scripts installed into a private location will > be run by the correct interpreter (rather than relying on the > interpreter being in /usr/bin, or on PATH). > > For "quick" sharing, the shebang line "#!/usr/bin/env python3.0" will > be enough. When Python 3.1 gets released, you may find yourself writing > scripts that run only on Python 3.x for x>=1 (i.e. won't run on 3.0, > because you use a new feature in 3.1). In that case, presence of a > python3 executable won't help, either. > > Regards, > Martin Yes! Finally we are getting somewhere. I can see how this can work for distributed packages. I still have two questions. I do not mean to take your individual time for this. If there is documentation I should read, please suggest it. First, let's say that the package has been installed using distutils and the shebang line is set to '#!/usr/local/bin/python3.0'. Now, Python 3.1 is released with a number of speed performance improvements and several security fixes. The existing application is hardcoded to use Python3.0 directly. Does distutils include any mechanism to update this setting so that the package will use a different interpreter? Must the application be installed again in order to update the shebang lines? Second, we frequently have a number of standalone utilities written in Python. When the task requires excessive effort to write in a shell script, Python is a great answer. What is your recommendation for the shebang line on one-off, single .py file utility scripts? From cjw at ncf.ca Tue Dec 2 15:10:40 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Tue, 02 Dec 2008 15:10:40 -0500 Subject: Multiple Versions of Python on Windows XP In-Reply-To: <493592EE.9090005@v.loewis.de> References: <4934de22$0$27863$9b622d9e@news.freenet.de> <493592EE.9090005@v.loewis.de> Message-ID: Martin v. L?wis wrote: >>>> What changes are made to the registry? >>> For a complete list, see Tools/msi/msi.py in the source tree. >> I have scanned the file: >> http://svn.python.org/projects/python/branches/py3k/Tools/msi/msi.py >> >> I don't find anything that addresses this issue. > > Read the add_registry function. You may need to first understand > how the Registry table in an MSI file works. > >> I am seeking some mechanism such that any of Python 2.5, Python 2.6 or >> Python 2.6 can be chosen as the currently active version. > > If Glenn Lindermann's answer doesn't help, you need to explain: > what is a "currently active version"? How is one Python version > more active than any other? > >> I was hoping that there is some simpler way than the "Repair" procedure. > > See Glenn Lindermann's answer. I'll look at it > >>> It would be good to be more specific with such statements: what troubles >>> specifically? If I play dumb, I'd say "of course - windows explorer >>> doesn't support editing Python files; you need a text editor". Using a right click, one can open any .py file with say SciTe. Within SciTe, one can Run the current file. It would be good to have the appropriate version (my use of "default") preselected. >> Yes, I should have been clearer. The PyScripter application locks up >> and must be killed, using the Task Manager. > > I think you need to report that to the PyScripter authors as a bug. > I can't imagine how the "currently active version" can affect what > PyScripter does. Yes, I'll do that. > I'll also follow up with Glenn Lindermann's answer. Many thanks, Best wishes, Colin W. > Regards, > Martin From castironpi at gmail.com Thu Dec 4 06:04:54 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 4 Dec 2008 03:04:54 -0800 (PST) Subject: "as" keyword woes References: <7dudnSS7uIn_KarUnZ2dnUVZ_tTinZ2d@earthlink.com> Message-ID: <10f6ca6d-35d8-45a6-9a3e-dbdd8aacdb78@d23g2000yqc.googlegroups.com> On Dec 4, 4:43?am, Dennis Lee Bieber wrote: > On Thu, 4 Dec 2008 01:28:56 -0800, "Warren DeLano" > declaimed the following in comp.lang.python: > > > In addition, note that my choice of a concise method identifier affects > > only my users. ?Python's introduction of a new keyword affects the > > entire Python world code base, so perhaps you should be directing your > > "choose better names" criticism in another direction? > > ? ? ? ? Dropping in... > > ? ? ? ? If a "chosen name" mirrors a syntactic element -- whether reserved > or not -- I'd consider that name potentially ambiguous or conflicted. > > ? ? ? ? While "if" has been long a reserved word, I can as easily see > someone using "if" as a shorthand name for "interface". And if "if" were > not a reserved word, one might encounter code on the lines of > > ? ? ? ? if = if + 1 > > which is quite obnoxious to my eyes... or maybe > > ? ? ? ? if if.connected: > ? ? ? ? ? ? ? ? if.close() Does the OP hold the following should be legal? if if or or: and( for ) if not: while( def ) If not, it's an exception to Python's trend of not handcuffing programmers. From castironpi at gmail.com Thu Dec 18 16:46:45 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 18 Dec 2008 13:46:45 -0800 (PST) Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> Message-ID: <7e23a789-84c3-47b9-b040-ca7dd062d058@a37g2000pre.googlegroups.com> On Dec 17, 7:16?pm, "Gabriel Genellina" wrote: > En Wed, 17 Dec 2008 22:46:32 -0200, Aaron Brady ? > escribi?: > > > > > On Dec 17, 5:05?pm, "Gabriel Genellina" > > wrote: > >> En Wed, 17 Dec 2008 12:21:38 -0200, Jeremy Sanders ? > >> escribi?: > > >> > It would be nice if Python created pipes that are properly ? > >> inheritable by > >> > default by child processes, as they're mostly used for IPC. > > >> I'd say it is a bug in os.pipe implementation; they should be ? > >> inheritable ? > >> by default, as in posix (after all, the code is in "posixmodule.c"). > > > The code looks like this: > > > ? ?ok = CreatePipe(&read, &write, NULL, 0); > > ? ?Py_END_ALLOW_THREADS > > ? ?if (!ok) > > ? ? ? ? ? ?return win32_error("CreatePipe", NULL); > > ? ?read_fd = _open_osfhandle((Py_intptr_t)read, 0); > > ? ?write_fd = _open_osfhandle((Py_intptr_t)write, 1); > > > 'If lpPipeAttributes is NULL, the handle cannot be inherited.' ?You > > could populate a 'SECURITY_ATTRIBUTES' structure, or call > > DuplicateHandle on both of them. > > > A patch would look like this: > > > SECURITY_ATTRIBUTES sattribs; > > sattribs.nLength = sizeof(sattribs); > > sattribs.lpSecurityDescriptor = NULL; > > sattribs.bInheritHandle = TRUE; > > ok = CreatePipe(&read, &write, &sattribs, 0); > > Yes, that's exactly how os.popen does it (in posixmodule.c) > > > This still doesn't answer whether the file descriptor return by > > '_open_osfhandle' can be inherited too. > > It doesn't matter. The OS only cares about file handles, not C RTL ? > structures. Sorry for the multiple posts. File handles are inheritable by child processes, if the permissions are right. File descriptors are not. Is there a way that we can get the handles of a pipe into code, so that we can pass them to a subprocess? Will it take calling 'CreatePipe' from ctypes directly if on Windows? Or can 'os.pipe' be made to abstract that? If Windows can't inherit descriptors, 'os.pipe' should return handles, and 'os.read' &co. should accept them. It is a fairly large patch. From adi at lspl.net Mon Dec 8 09:27:13 2008 From: adi at lspl.net (sniffer) Date: Mon, 8 Dec 2008 06:27:13 -0800 (PST) Subject: dBase III files and Visual Foxpro 6 files References: Message-ID: <917126a8-c2c6-49c5-b001-07c953992dac@q26g2000prq.googlegroups.com> On Dec 8, 12:53?pm, Ethan Furman wrote: > Greetings All! > > I nearly have support complete for dBase III dbf/dbt files -- just > wrapping up support for dates. ?The null value has been a hindrance for > awhile but I nearly have that solved as well. > > For any who know of a cool dbf module already in existence for dBase III > and Visual Foxpro -- where were you six months ago when I was searching? > ? ;) ?Seriously, though, this has been a great learning experience for me. > > As I said -- dbf/dbt files are 99% ready. ?idx files -- no support: ?for > my purposes I just don't need them. ?I've found no problem in loading > tables up to 300,000 records with 50 fields per record, and re-ordering > them on the fly in memory. > > However, after putting much effort into this code, and wanting it to be > useful to others in the community, are there others who work with dbf > files that would need idx/cdx support? ?Or tables so large they won't > fit comfortably into memory? > > ~ethan~ hi ethan, great to hear that someone has finally written something for interacting with vfp6 data,when do you plan to release it From rhodri at wildebst.demon.co.uk Tue Dec 9 20:25:01 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Wed, 10 Dec 2008 01:25:01 -0000 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: On Mon, 08 Dec 2008 14:24:59 -0000, Rasmus Fogh wrote: > On the minus side there would be the difference between > '__equal__' and '__eq__' to confuse people. This is a very big minus. It would be far better to spell __equal__ in such a way as to make it clear why it wasn't the same as __eq__, otherwise you end up with the confusion that the Perl "==" and "eq" operators regularly cause. -- Rhodri James *-* Wildebeeste Herder to the Masses From google at mrabarnett.plus.com Thu Dec 11 21:11:17 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 12 Dec 2008 02:11:17 +0000 Subject: newbie question: if var1 == var2: In-Reply-To: <37fc3229-b0a2-4d95-990f-61300fc2b257@r37g2000prr.googlegroups.com> References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> <44aa0191-e374-4bf0-b039-d05cfa996b1d@p2g2000prn.googlegroups.com> <37fc3229-b0a2-4d95-990f-61300fc2b257@r37g2000prr.googlegroups.com> Message-ID: <4941C845.3030909@mrabarnett.plus.com> John Machin wrote: > On Dec 12, 11:39 am, MRAB wrote: >> Jason Scheirer wrote: >>> On Dec 11, 3:49 pm, John Machin wrote: >>>> On Dec 12, 10:31 am, "Rhodri James" >>>> wrote: >>>>> On Thu, 11 Dec 2008 19:49:23 -0000, Steve Holden >>>>> wrote: >>>>>> Kirk Strauser wrote: >>>>>>> At 2008-11-29T04:02:11Z, Mel writes: >>>>>>>> You could try >>>>>>>> for item in fname: >>>>>>>> item = item.strip() >>>>>>> This is one case where I really miss Perl's "chomp" function. It >>>>>>> removes a >>>>>>> trailing newline and nothing else, so you don't have to worry about >>>>>>> losing >>>>>>> leading or trailing spaces if those are important to you. >>>>>> ... and it's so hard to write >>>>>> item = item[:-1] >>>>> Tsk. That would be "chop". "chomp" would be >>>>> if item[-1] == '\n': >>>>> item = item[:-1] >>>> Better: >>>> if item and item[-1] == '\n': >>>> return item[:-1] >>>> return item >>> Best: >>> return item \ >>> if not (item and item.endswith('\n')) \ >>> else item[:-1] >>> Though really you should be using item.rstrip() >> Why not just: >> >> item[:-1] if item.endswith('\n') else item > > Some possible reasons: > * because you might be supporting old versions of Python (my offering > runs on 1.5) > * because the " if else " syntax > gives you the screaming dry Edgar Britts > * because you'd prefer not to have the overhead of a method lookup and > method call > OK: if item[-1:] == '\n': return item[:-1] return item From almar.klein at gmail.com Mon Dec 8 09:10:41 2008 From: almar.klein at gmail.com (Almar Klein) Date: Mon, 8 Dec 2008 15:10:41 +0100 Subject: Guido's new method definition idea In-Reply-To: <493d1f03$0$32048$426a34cc@news.free.fr> References: <493a9fed$0$18973$426a34cc@news.free.fr> <493c1ff6$0$4942$426a34cc@news.free.fr> <49d12ec1-2be9-497b-80bc-9f0402a9086d@s20g2000yqh.googlegroups.com> <493d1f03$0$32048$426a34cc@news.free.fr> Message-ID: I like the transparancy and clearity of python, and the explicit self fits beautifully. Allowing a second way of defining your methods would only confuse newbies more I would think. I was a newby only half a year ago (or maybe I still am). The explicit self seems weird the very first time you see it, but very soon you see the beauty of it. The error message may be confusing sometimes, but as Guido says, I guess it's better to fix the error message rather than changing the language. -1 for me! As for the $ stuff, it makes things less transparant and yes, it's looks rather ugly. -1 on this one as well. Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Dec 24 02:03:19 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2008 05:03:19 -0200 Subject: socket send help References: Message-ID: En Wed, 24 Dec 2008 03:59:42 -0200, greywine at gmail.com escribi?: > New guy here. I'm trying to figure out sockets in order to one day do > a multiplayer game. Here's my problem: even the simplest examples > don't work on my computer: > > A simple server: > > from socket import * > myHost = '' Try with myHost = '127.0.0.1' instead - a firewall might be blocking your server. > s.listen(5) # allow 5 simultaneous connections Not exactly: your server program only handles a single connection at a time. The 5 above specifies how many connections may exist "on hold" waiting for you to accept() them. > connection.send('echo -> ' + data) That's fine for Python 2.6, but you must use b'echo -> ' with 3.0 > And a simple client: > > s.send('Hello world') # send the data Same as above, should be b'Hello world' with Python 3.0 > If I run testserver.py via the cmd prompt in Windows XP and then the > testclient.py program, I get the following error: > > Traceback (most recent call last): > File "C:\Python30\testclient.py", line 12, in > s.send('Hello world') # send the data > TypeError: send() argument 1 must be string or buffer, not str The above error message is wrong (and I think it was corrected on the 3.0 final release; if you got it with 3.0 final, file a bug report at http://bugs.python.org/ ) > This happens in 2.6 or 3.0 and with different example client & server > programs from the web. What am I missing? The error above surely comes from 3.0; with 2.6 you should get a different error (if it fails at all). Try again with 2.6.1. I didn't run the code but it looks fine -- if you got it from a book or article, unless it explicitely says "Python 3.0", assume it was written for the 2.x series. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Sat Dec 27 22:38:44 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 28 Dec 2008 01:38:44 -0200 Subject: C API: array of floats/ints from python to C and back References: Message-ID: En Sun, 28 Dec 2008 00:40:52 -0200, Daniel Fetchinson escribi?: >> You MUST check EVERY function call for errors! > > Yes, I know :) > Believe me, if you don't, there is a risk of crashing the program. And they're a lot harder to find and fix. >> And check the argument's type (how do you know it is a list?). Once you >> are sure the first parameter *is* a list, you may use the "macro" >> version >> of several functions, like PyList_GET_SIZE and PyList_GET_ITEM. > > The macro versions are preferable because they are faster? Yes, because they don't do any additional checking. PyList_GET_ITEM just retrieves the item; PyList_GetItem checks whether it is called on a list object, then checks if index is out of bounds, and only then goes to retrieve the item. >> You should check that both lists have the same length too. >> And you should check that elements are integers, or convertible to >> integers (in case of error, PyInt_AsLong returns -1 and PyErr_Occurred() >> is true) >> To fill the resulting tuple, use PyTuple_SET_ITEM instead. BTW, why >> return >> a tuple and not a list? > > No particular reason, other than the fact that I won't need to modify > these lists/tuples from python so whenever something will not change, > I use a tuple because it's immutable. Or this is not a very good > practice? There is no difference between lists and tuples in terms of > speed I suppose (getitem, setitem, etc). Usually lists represent an ordered collection of similar items, where position is not relevant (the third item is treated more or less the same as the tenth); by example, a list of attendants to certain event. It makes sense to process the whole list doing the same thing to each element, and it makes sense to ask "is this item in the list?." Tuples represent an ordered collection of dissimilar items, where position is relevant (because it identifies each item); by example, a row from a database table (name, address, age, phone number), or a point (x,y,z) in space. It isn't common to process the whole tuple doing the same thing for each element, and usually it doesn't make sense to look for certain item in the tuple. But it does make sense to refer to individual items like t[2], or t.age (namedtuple, 2.6 and up) From this point of view, lists and tuples are conceptually different - tuples aren't "frozen" lists. But this is just common usage, or maybe historical intent; of course you are free to use whatever structure you feel adequate. Once the list/tuple is created and filled, there is no speed difference accessing the individual items. Creating an empty list that grows one element at a time is slow for large lists (the memory block has to be re-allocated and copied over evry time it gets full) but this doesn't happen if you provide the final size when creating the list. -- Gabriel Genellina From prologic at shortcircuit.net.au Mon Dec 22 17:24:20 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 23 Dec 2008 08:24:20 +1000 Subject: Event Driven programming - Doubts In-Reply-To: <80f360e4-2880-4c66-a6b4-e05d6dbc9031@b41g2000pra.googlegroups.com> References: <80f360e4-2880-4c66-a6b4-e05d6dbc9031@b41g2000pra.googlegroups.com> Message-ID: On Tue, Dec 23, 2008 at 12:57 AM, Kottiyath wrote: > Hi, > I have been looking at Twisted and lately Circuits as examples for > event driven programming in Python. Wonderful! :) "circuits" that is :) > Even though I understood how to implement the code in these and > what is deferred etc, I have not yet understood the implementation of > deferred. I went through a lot of tutorials, but I guess most places > they expect that the user already understands how events are > generated. The tutorials mention that there is no more threads once > twisted is used. deferred to me is nothing more than scheduling "things" to happen "later". ie: Timers, or Timed Events. I clearly biased here as I'm the developer of circuits, so I can't comment on Twisted's design or architecture, but the way to achieve Twisted's so-called deferred (events?) is to use the Timer component, Timed Events. > My question is as follows: > I have not understood how the callbacks are hit without (a) > blocking the code or (b) having new threads. Again speaking in terms of circuits, but also in the event-driven paradigm: a) Event Handlers _can_ block - but ideally shouldn't (ihmo). b) Forking new threads/processes per event is mostly not necessary. (There are exceptions). > The usual example given is that of a program waiting for data coming > through a socket. In the tutorials, it is mentioned that -in an event > driven program, we schedule the code to hit when the remote server > gets back to us - . > Now, my question is - somebody has to still wait on that socket and > check whether the data is received, and once all the data is received, > call the appropriate callbacks. In the case of circuits' TCPServer component you simply poll it in your main event-loop. The pattern looks like this: from circuits.lib.sockets import TCPServer server = TCPServer(8000) while True: server.poll() server.flush() The TCPServer component has various builtin event handlers that do all the work for you and expose other more useful events to the application, such as: * connect * disconnect * read * error > Is twisted creating a micro-thread which just waits on the socket and > once the data is received, calls callFromThread for it to run on the > main loop? I can't comment - I tend to avoid threads where ever possible. > If so, Even though data locking etc is not a problem, are we not still > having threads? Will it not still cause scalability problems in high > traffic? Regarding scalability btw ... (in case you're interested) circuits comes with circuits.lib.web and several sets of Web Components. A lot of code was borrowed from the BaseHTTPServer from the python standard library and bits and pieces from CherryPy and the cgi module.... In terms of performance, it has a "raw" performance ~3k req/s on good hardware. Do have fun in your endeavours :) cheers James Circuits: http://trac.softcircuit.com.au/circuits/ From piyush.subscription at gmail.com Sat Dec 20 20:50:24 2008 From: piyush.subscription at gmail.com (Piyush Anonymous) Date: Sun, 21 Dec 2008 07:20:24 +0530 Subject: a small doubt Message-ID: <19ac19520812201750hb592e4dsa5ef7d2a1906c2ed@mail.gmail.com> i wrote this code -- class Person(object): instancesCount = 0 def __init__(self, title=""): Person.instancesCount += 1 self.id = "tempst" def testprint(self): print "blah blah" def __getattribute__(self, name): print "in get attribute" a = Person() a.testprint() print a.id ----- but i am getting this error ---- in get attribute Traceback (most recent call last): File "trapmethodcall1.py", line 15, in a.testprint() TypeError: 'NoneType' object is not callable ------ why is it so? __getattribute__ is called whenever an attribute or method is called, rt? or if i set __getattribute__ , i cannot have methods in class? actually my aim is to trap all method calls and keep a counter which is update whenever method called or returned. how should i go about it? -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Tue Dec 16 04:43:47 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Dec 2008 07:43:47 -0200 Subject: ethical questions about global variables References: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> Message-ID: En Tue, 16 Dec 2008 00:45:05 -0200, Giampaolo Rodola' escribi?: > Another doubt is the naming convention. PEP-8 states that global > variables should use the lower_case_naming_convention but I've seen a > lot of library module using the UPPER_CASE_NAMING_CONVENTION. What am > I supposed to do about it? Are you sure those UPPER_CASE names you've seen are actually variables? or constants like: CRLF = '\r\n' (ok, it's not a true "constant" because the language doesn't prevent you from modifying it... but the "intended usage" is to be a constant) -- Gabriel Genellina From bj_666 at gmx.net Sat Dec 6 04:18:20 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 6 Dec 2008 09:18:20 GMT Subject: Guido's new method definition idea References: <48db9$493a3e2b$d9a2276f$10794@news.hispeed.ch> Message-ID: <6puuasFa29upU1@mid.uni-berlin.de> On Sat, 06 Dec 2008 09:56:12 +0100, Antoine De Groote wrote: > try this: > >>>> import this > > and look at the 15th line... The reason why I'm against that change too. It adds a second, alternative way to express something that is already in the language. > I agree that for newcomers to Python, the class method definition might > seem strange. And after the change it continues to because they will run into *both* variants in tutorials, code, and books, so it might be even more confusing. Ciao, Marc 'BlackJack' Rintsch From luismgz at gmail.com Wed Dec 10 17:48:49 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Wed, 10 Dec 2008 14:48:49 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: <4b0f6c1a-9d3f-4fd7-8506-314d29ee87a8@k36g2000yqe.googlegroups.com> You are WRONG, WRONG, WRONG!! And when I say Wrong, I mean WRONG!!! And I am not saying that you are confussed. I say that you are WRONG! And when someone says so many times that you are wrong, it is because you are WRONG! And don't say that you are not wrong, because you are wrong! You are Wrong. Very Wrong. On Dec 10, 3:42?pm, cm_gui wrote: > http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-... > > I fully agree with Krzysztof Kowalczyk . > Can't they build a faster VM for Python since they love the language > so much? > > Python is SLOW. ? ?And I am not comparing it with compiled languages > like C. > Python is even slower than PHP! > > Just go to any Python website and you will know. > An example is:http://www2.ljworld.com/ > And this site is created by the creators of Django! > > And it is not just this Python site that is slow. There are many many > Python sites which are very slow. And please don?t say that it could > be the web hosting or the server which is slow ? because when so many > Python sites are slower than PHP sites, it couldn?t be the web > hosting. ? Also, Zope/Plone is even slower. > > Python is slow. Very slow. From castironpi at gmail.com Mon Dec 15 00:12:13 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 14 Dec 2008 21:12:13 -0800 (PST) Subject: stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> Message-ID: On Dec 14, 8:18?pm, Roy Smith wrote: > Steven D'Aprano wrote: > > All the positive thinking in the world won't help you: > > > * make a four-sided triangle; > > > * split a magnet into two individual poles; > > These two are fundamentally different problems. > > The first is impossible by definition. ?The definition of triangle is, "a > three-sided polygon". ?Asking for a "four-sided triangle" is akin to asking > for "a value of three which is equal to four". > > The second is only "impossible" because it contradicts our understanding > (based on observation) of how the physical universe works. ?Our > understanding could simply be wrong. ?We've certainly been wrong before, > and we will undoubtedly be proven wrong again in the future. ?When it comes > to things like electromagnetic theory, it doesn't take too many steps to > get us to the fuzzy edge of quantum physics where we know there are huge > questions yet to be answered. I agree. Most of his examples were tautologies. The magnet one was the exception. Then, to beat the O( n lg n ) limit, just break an assumption. > > * or design a comparison sort which does fewer than O(n*log n) two-way > > comparisons in the worst case, or fewer than O(n) comparisons in the best > > case. Make a three-way comparison, make a non-comparison sort, or make non- random inputs. From timr at probo.com Wed Dec 31 02:18:20 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 31 Dec 2008 07:18:20 GMT Subject: Easy-to-use Python GUI References: Message-ID: <617ml4tfvvhj45p0667f0ubr4f2g5onq57@4ax.com> "Joel Koltner" wrote: >... >One approach that I like comes from SAX BASIC/WinWrap, which is more or less a >clone of Microsoft's Visual BASIC for Applications, but they (apparently) >wanted everything to still be human-readable, so they have a simple GUI >("form") builder that generates code that looks like this: > >--- > > Begin Dialog UserDialog 850,497,"Export Control" ' %GRID:10,7,1,1 > > GroupBox 20,7,360,217,"Drill File Generation",.GroupBox1 > CheckBox 40,35,130,14,"Output drill file(s)",.genDrill > Text 40,63,270,28,"Identify via layers as any that contain this text in >their names:",.Text > TextBox 40,98,220,21,.viaLayerName > Text 40,140,100,14,"Output method:",.Text8 > DropListBox 160,140,180,21,DrillStyle(),.drillStyle > Text 40,175,130,28,"Select drill table units:",.Text2 > ListBox 200,175,120,28,unitNames(),.unitName > > OKButton 310,469,90,21 > CancelButton 410,469,90,21 > > End Dialog > >' GUI builder generates or modifies everything above, but can also be edited >by hand >' You write the following code... > > Dim dlg As UserDialog > > dlg.genDrill = 1 > ReDim DrillStyle(1) > DrillStyle(0) = "All Via Layers In One File" > DrillStyle(1) = "One File Per Via Layer" > dlg.drillStyle = 1 > > func=Dialog(dlg) > >--- > >This is pretty darned easy for me understand and modify either by hand or with >the GUI builder. Well, allow me to point out that the equivalent code in wxPython would not be very much longer than this. It's just spelled differently. Sure, you have a bit of a learning curve to climb, just like you do with any new development tool. Once you take the time to get familiar with it, you'd read the wxPython program just as easily as that Basic example. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From brian at thebdbulls.com Mon Dec 1 16:34:24 2008 From: brian at thebdbulls.com (bdbull) Date: Mon, 1 Dec 2008 13:34:24 -0800 (PST) Subject: Thread always alive References: Message-ID: <94510d10-691d-45e0-ac7e-f7c91c0ce34e@l39g2000yqn.googlegroups.com> > I am suspecting some kind of a leak on a IO object like a file or socket descriptor is still open. Are you sure you're closing them all? You mentioned a finally clause so is it possible that your code is throwing an exception before you clean everything up? From lists at cheimes.de Thu Dec 4 11:48:27 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 04 Dec 2008 17:48:27 +0100 Subject: Python 3 read() function In-Reply-To: References: Message-ID: Cro wrote: > Good day. > I have installed Python 3 and i have a problem with the builtin read() > function. > > [code] > huge = open ( 'C:/HUGE_FILE.pcl', 'rb', 0 ) > import io > vContent = io.StringIO() > vContent = huge.read() # This line takes hours to process !!! > vSplitContent = vContent.split > ( 'BIN;SP1;PW0.3,1;PA100,700;PD625,700;PU;' ) # This one i have neve > tried... > [/code] Do you really mean io.StringIO? I guess you want io.BytesIO() .. Christian From gagsl-py2 at yahoo.com.ar Sat Dec 13 23:48:39 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 14 Dec 2008 02:48:39 -0200 Subject: Bidrectional Subprocess Communication References: Message-ID: En Sat, 13 Dec 2008 18:19:29 -0200, Emanuele D'Arrigo escribi?: > I'm trying to replicate the positive results of the Client/Server > scripts from the thread "Bidirectional Networking", but this time > using a Process/SubProcess architecture. > > The SubProcess, acting as a server, is working just fine. But the > Process executing the SubProcess, the client, somehow doesn't hear any > of the standard output from the SubProcess. What am I missing? (Pipes don't work the same as sockets, although unix-like systems try hard to hide the differences...) - you have to close server.stdin when you don't have more data to send. The server will see an end-of-file and knows it has to exit the loop. Same thing on the client side. - you have to wait until the server answers, else it will get a "broken pipe" error or similar. - end-of-file, in Python, is detected when a read/readline returns an empty string - you sent "Stop!" without a \n - readline() on the server side would wait forever; it doesn't matter in the code below because server.stdin is explicitely closed. Below are the modified version of your programs: #clientTest.py import sys import threading from time import sleep from subprocess import Popen, PIPE ## Server Thread class ListenerThread(threading.Thread): def __init__(self, inChannel): threading.Thread.__init__(self) self.inChannel = inChannel def run(self): while True: data = self.inChannel.readline() if not data: # data=='' means eof break data = data.strip() print("serverTest.py says: " + data) print("Starting Client!") server = Popen("python serverTest.py", stdin=PIPE, stdout=PIPE) listenerThread = ListenerThread(server.stdout) listenerThread.start() server.stdin.write("Something very meaningful!\n") server.stdin.write("Stop!") server.stdin.close() # notify server: no more data listenerThread.join() # wait until server closes channel print("Client Stopped!") # serverTest.py import sys print("Starting Server!") while True: data = sys.stdin.readline() if not data: # data=='' means eof break data = data.strip() print("SERVER RECV: '" + data + "'") if(data == "Stop!"): break print("Server Stopped!") -- Gabriel Genellina From felipevaldez at gmail.com Wed Dec 3 15:10:45 2008 From: felipevaldez at gmail.com (fel) Date: Wed, 3 Dec 2008 12:10:45 -0800 (PST) Subject: Tired of coding. Message-ID: <40e958e2-60fb-4dbe-811b-e149d668b81c@f13g2000yqj.googlegroups.com> http://digg.com/programming/Tired_of_coding_try_FBP_Flow_Based_Programming From akineko at gmail.com Mon Dec 29 17:26:59 2008 From: akineko at gmail.com (akineko) Date: Mon, 29 Dec 2008 14:26:59 -0800 (PST) Subject: tkInter constraining the width only References: <2d06d584-f398-4bf2-9452-bc2d915b1d17@k19g2000yqg.googlegroups.com> Message-ID: Hello Roger, Thank you for your prompt response to my posting. Yes, it worked. I never thought of putting 0! A special trick not mentioned in the documentation. Thanks! Aki- On Dec 29, 1:01 pm, Roger wrote: > You want to set the max height to 0. I know this is counter- > intuitive. From ldo at geek-central.gen.new_zealand Tue Dec 2 17:52:07 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 03 Dec 2008 11:52:07 +1300 Subject: Multiple equates References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> Message-ID: In message , Cameron Laird wrote: > In article , > Lawrence D'Oliveiro wrote: > >>Cameron Laird wrote: >> >>> I've been trying to decide if there's any sober reason to advocate >>> the one-liner >>> >>> map(lambda i: a.__setitem__(i, False), [x1, x2, x3, ..., x1024]) >> >>Are lambdas like the Dark Side of Python? >> >>:) > > Enough so, apparently, that I'm reluctant even to touch that question. So how else would you express something like def shell_escape(Arg) : """returns Arg suitably escaped for use as a command-line argument to Bash.""" return \ re.sub \ ( r"[\<\>\"\'\|\&\$\#\;\(\)\[\]\{\}\`\!\~\ \\]", lambda Match : "\\" + Match.group(0), Arg ) # Need to catch anything that might be meaningful to shell #end shell_escape ? From sturlamolden at yahoo.no Fri Dec 12 09:30:43 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 06:30:43 -0800 (PST) Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> Message-ID: <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> On Dec 12, 3:08 pm, Marc 'BlackJack' Rintsch wrote: > No bug because a mutation *is* attempted. ``a += x`` calls `a.__iadd__` > which *always* returns the result which is *always* rebound to the name > `a`. Even with mutable objects where `__iadd__()` simply returns > `self`! No, a mutation is not attempted, even if __iadd__() always returns a value. If a rebinding of a member to the same member is attempted, the tuple should not raise an exception. The tuple should check that it is actually being *mutated* before it raises any exception. There is an attempted write to the tuple, but not an attempted mutation of the tuple. The tuple should tell the difference. Immutability does not imply inwriteability, if the write operation changes nothing. But the tuple raises an exception on any write attempt. From casey.mcginty at gmail.com Wed Dec 3 16:48:10 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Wed, 3 Dec 2008 11:48:10 -1000 Subject: Reverse zip() ? In-Reply-To: <333edbe80812021647i4621271p7f87dff8d0926951@mail.gmail.com> References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> <333edbe80812021647i4621271p7f87dff8d0926951@mail.gmail.com> Message-ID: > The corner case is when dealing with empty lists and there aren't > enough items to unpack. > > Another solution to zip(), with a slightly different behaviour for conner cases .... >>> a = (1,2,3) >>> b = (1,2,3) >>> c = (1,2,3,4) >>> zip(a,b) [(1, 1), (2, 2), (3, 3)] >>> map(None,a,b) [(1, 1), (2, 2), (3, 3)] >>> zip(a,c) [(1, 1), (2, 2), (3, 3)] >>> map(None,a,c) [(1, 1), (2, 2), (3, 3), (None, 4)] -------------- next part -------------- An HTML attachment was scrubbed... URL: From Scott.Daniels at Acm.Org Sat Dec 27 18:15:43 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 27 Dec 2008 15:15:43 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: Daniel Fetchinson wrote: > I have considered using ctypes but for my needs using the C API > directly seems more reasonable. array.array and numpy.array doesn't > fit my needs since I need to do long and complicated operations on the > two (pretty large) integer arrays that would be too slow using > array.array and numpy.array (I've verified this claim by benchmarking > a numpy.array based solution). OK, but if you go to array.array or numpy.array or ctypes, you can create a uniformly typed (C datatype) array , which is the key to getting any speed out of the deal. If you insist on using python lists, you are stuck with extracting data element by element from its Python language wrap. --Scott David Daniels Scott.Daniels at Acm.Org From steve at holdenweb.com Tue Dec 30 08:57:07 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Dec 2008 08:57:07 -0500 Subject: select.select and socket.setblocking In-Reply-To: <495A2548.8010007@shopzeus.com> References: <495A2548.8010007@shopzeus.com> Message-ID: Laszlo Nagy wrote: > I'm using this method to read from a socket: > > def read_data(self,size): > """Read data from connection until a given size.""" > res = "" > fd = self.socket.fileno() > while not self.stop_requested.isSet(): > remaining = size - len(res) > if remaining<=0: > break > # Give one second for an incoming connection so we can stop the > # server in seconds when needed > ready = select.select([fd], [], [], 1) > if fd in ready[0]: > data = self.socket.recv(min(remaining,8192)) # 8192 is > recommended by socket.socket manual. > if not data: > # select returns the fd but there is no data to read > -> connection closed! > raise TransportError("Connection closed.") > else: > res += data > else: > pass > if self.stop_requested.isSet(): > raise SystemExit(0) > return res > > > This works: if I close the socket on the other side, then I see this in > the traceback: > > File "/usr/home/gandalf/Python/Projects/OrbToy/orb/endpoint.py", line > 233, in read_data > raise TransportError("Connection closed.") > TransportError: Connection closed. > > Also when I call stop_requested.set() then the thread stops within one > seconds. > > Then I switch to non blocking mode, my code works exactly the same way, > or at least I see no difference. > > I have read the socket programming howto ( > http://docs.python.org/howto/sockets.html#sockets ) but it does not > explain how a blocking socket + select is different from a non blocking > socket + select. Is there any difference? > Well, ignoring your question for the moment, what's wrong with the following (untested) code? def read_data(self, size): data = "" while len(data) < size: d = self.socket.read(size-len(data)) if not d: raise TransportError("Socket closed while reading data") data += d return data I feel the raw socket operations are easier to understand and less confusing. Since you don't want to return until you've read the data there really doesn't seem to be any point using select(), which is mainly useful in asynchronous operations (in which case you would have to use non-blocking sockets). It's not obvious from your code how self.stop_requested is supposed to change the result of its is_set() method. Maybe that's where the select() comes in? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From stargaming at gmail.com Wed Dec 10 01:02:20 2008 From: stargaming at gmail.com (Robert Lehmann) Date: 10 Dec 2008 06:02:20 GMT Subject: List Problem References: Message-ID: <493f5b6c$0$27863$9b622d9e@news.freenet.de> On Tue, 09 Dec 2008 21:40:08 -0800, dongzhi wrote: > I have one problem for List. Like that: > > format='just "a" ""little"" test' > part = format.split('"') > print part > > the result is : ['just ', 'a', ' ', '', 'little', '', ' test'] > > the list part have 7 element. > > If I execute part[1], I have got 'a'. If I execute part[2], I have got > ' '. But, if I execute part[1::2], I have got ['a', '', '']. I don't > know why. Please tell me why. You're slicing your list with the arguments "start at 1, stop at the end, using a step size of 2." It's basically the same as ``part[1], part[1+2], part[1+2+2], ...``. Perhaps you wanted to do ``part[1:3]`` (meaning "start at 1, stop before 3"). See the Python Reference for details. http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode- list-tuple-buffer-xrange http://docs.python.org/reference/expressions.html#id8 HTH, -- Robert "Stargaming" Lehmann From wuwei23 at gmail.com Tue Dec 9 19:09:45 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 9 Dec 2008 16:09:45 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <4ridneQnkLrPkKDUnZ2dnUVZ8qbinZ2d@posted.plusnet> <986b6ea1-efba-4146-9704-5f9e3787c26a@a37g2000pre.googlegroups.com> Message-ID: On Dec 10, 9:19?am, Xah Lee wrote: > I'm not sure he's intentionally making Mathematica look bad or just > sloppiness. Actually, there's only one person here tainting Mathematica by association, and it's not Jon. From collin.day.0 at gmail.com Thu Dec 18 21:12:02 2008 From: collin.day.0 at gmail.com (Collin D) Date: Thu, 18 Dec 2008 18:12:02 -0800 (PST) Subject: Factoring Polynomials References: Message-ID: On Dec 18, 11:37?am, collin.da... at gmail.com wrote: > I am trying to write a simple application to factor polynomials. I > wrote (simple) raw_input lines to collect the a, b, and c values from > the user, but I dont know how to implement the quadratic equation > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > into python. Any ideas? I completed the code: #import from math import sqrt # collect data a = float(raw_input('Type a value: ')) b = float(raw_input('Type b value: ')) c = float(raw_input('Type c value: ')) # create solver def solver(a,b,c): if b**2 - 4*a*c < 0: return 'No real solution.' else: sol1 = -1 * b + (sqrt(b**2 - 4*a*c)) / 2*a sol2 = -1 * b - (sqrt(b**2 - 4*a*c)) / 2*a return (sol1, sol2) # execute print solver(a,b,c) Thanks to everyone who helped... This really expanded my knowledge on some of the mathematical functions in Python. From tavares at fe.up.pt Mon Dec 29 14:50:56 2008 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Mon, 29 Dec 2008 11:50:56 -0800 (PST) Subject: =?windows-1252?Q?Symposium_=93Image_Processing_and_Analysis=94_within?= =?windows-1252?Q?_the_ICCES=2709_Thailand_=96_Last_Announce_=26_Call_for_Papers?= Message-ID: <9e75ee2f-a417-4245-96ea-143aadd8913f@r15g2000prh.googlegroups.com> (Our apologies for cross-posting. We appreciate if you kindly distribute this information by your co- workers and colleagues.) ******************************************************************************************************* Symposium ?Image Processing and Analysis? Int. Conf. on Computational & Experimental Engineering and Sciences 2009 (ICCES'09) Phuket, Thailand, 8-13 April 2009 http://icces.org/cgi-bin/ices09/pages/index ******************************************************************************************************* Dear Colleague, Within the International Conference on Computational & Experimental Engineering and Sciences 2009 (ICCES'09), to be held in Phuket, Thailand, in 8-13 April 2009, we are organizing the Symposium ?Image Processing and Analysis?. Examples of some topics that will be considered in that symposium are: Image restoring, Description, Compression, Segmentation and Description; Objects tracking, Matching, Reconstruction and Registration; Visualization Enhance; Simulation and Animation; Software Development for Image Processing and Analysis; Grid Computing in Image Processing and Analysis; Applications of Image Processing and Analysis. Due to your research activities in those fields, we would like to invite you to submit your work and participate in the Symposium ?Image Processing and Analysis?. Important dates and Instructions: - 1 Jan 2009: Deadline for abstract submission; - 10 Jan 2009: End of abstract selection. For instructions and submission, please access to the conference website at: http://icces.org/cgi-bin/ices09/pages/index. Instructions for authors are available at: http://icces.org/cgi-bin/ices09/pages/guide. Please note, when submitting your work you should choose the Symposium ?Image Processing and Analysis?. If you intend to submit your work please notify as soon as possible the main organizer of your intention (tavares at fe.up.pt); The organizers are preparing a special issue of the International Journal Computer Modeling in Engineering & Sciences (CMES), ISSN: 1526-1492, dedicated to the Symposium ?Image Processing and Analysis? with extended papers of the works presented in the ICCES'09. With kind regards, The Organizers, Jo?o Manuel R. S. Tavares (tavares at fe.up.pt) Faculty of Engineering of University of Porto, Porto, Portugal Yongjie (Jessica) Zhan (jessicaz at andrew.cmu.edu) Carnegie Mellon University, Pittsburgh, USA Maria Jo?o M. Vasconcelos (maria.vasconcelos at fe.up.pt) Faculty of Engineering of University of Porto, Porto, Portugal From rayene.benrayana at gmail.com Mon Dec 1 09:04:33 2008 From: rayene.benrayana at gmail.com (Rayene Ben Rayana) Date: Mon, 1 Dec 2008 15:04:33 +0100 Subject: Python introspection and namespace weird question Message-ID: Hello everybody, Is there an easy way to do something like this in python ? >>> red_car = MyVehicleClass() >>> car = red_car >>> car.labels() ['red_car' , 'car' ] In other words, does an instance has access to its name pointers ? Thanks in advance, Rayene -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at microcorp.co.za Thu Dec 4 14:14:26 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 4 Dec 2008 21:14:26 +0200 Subject: Thread Tkinter problem References: <64c7402c-8b7b-4281-9d7d-1abdd6177d96@r15g2000prh.googlegroups.com><35672781-eca1-4139-8b5d-88c457960d62@g1g2000pra.googlegroups.com> <98353009-15ea-4029-99d1-42f9d32e7c27@r15g2000prh.googlegroups.com> Message-ID: <001a01c95648$5cd70800$0d00a8c0@hendrik> "Davy" wrote: >def gen_board_thread(): > print 'enter here' > gen_flip = 1 > while(True): You don't need the brackets: while True: is good enough > time.sleep(0.3) > if (data_queue.full() == False): write: if not data_queue.full(): , and lose the brackets here too. > if (gen_flip == 1): write: if gen_flip: (no brackets - not needed, ugly) > gen_flip = 0 > data = board_1 > else: > gen_flip = 1 > data = board_2 > data_queue.put(data) > print 'put', data_queue.qsize() HTH - Hendrik From wicijowski at gmail.com Sat Dec 27 15:51:37 2008 From: wicijowski at gmail.com (janislaw) Date: Sat, 27 Dec 2008 12:51:37 -0800 (PST) Subject: tkinter 3.0 multiple keyboard events together References: <600d4b68-6fe2-4c2c-b425-1a739430bb54@s9g2000prg.googlegroups.com> <7b5e466c-d75d-4e71-b559-f8a0d3718094@r15g2000prd.googlegroups.com> Message-ID: On 27 Gru, 15:08, Pavel Kosina wrote: > janislaw napsal(a): > > Use google to find the appropriate site, or browse this site, there > > are plenty of examples. You may want to examine the code I wrote to > > you to catch the idea: > > #---------------------- > > import Tkinter > > import pprint > > > tk = Tkinter.Tk() > > f = Tkinter.Frame(tk, width=100, height=100) > > msg = Tkinter.StringVar() > > msg.set('Hello') > > l = Tkinter.Label(f, ?textvariable=msg) > > l.pack() > > f.pack() > > > keys = set() > > > def keyPressHandler(event): > > ? ? keys.add(event.char) > > ? ? display() > > > def keyReleaseHandler(event): > > ? ? keys.remove(event.char) > > ? ? display() > > > def display(): > > ? ? msg.set(str(keys)) > > > f.bind_all('', keyPressHandler) > > f.bind_all('', keyReleaseHandler) > > > f.mainloop() > > Is this really the most simple solution how to do this in Tkinter? Is > there nothing cleaner "build inside"? Um, I could be only guessing what are you meant to do, unless you describe your problem in more detailed way. I.e. describe the desired behaviour, show code which you have, and describe the current behaviour. > This solution has disadvantage that after you release one key, that the > function keyPressHandler stopped to be called by the other pressed keys. > I would have not to build moving the player in KeyPresshandler, but on > another new function that would have to read periodically "keys" and to > act afterwards.... Hmmm. Maybe you'd like to hook into Tkinter event loop, i.e. by custom events if you don't like periodical polling. >From what I am guessing, you expect that 2 keyboard events are simultaneous and can be cached at the same time instant. Well that would be impossible, cause all the underlying hardware is sequential. You may have parallel stuff if you go down to VHDL and write your own hardware, but when you have a CPU, then you'll have to stick with writing programs. C'mon, 20 lines is not such a big deal. Regards JW From notvalid2 at sbcglobal.net Tue Dec 16 18:56:43 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Tue, 16 Dec 2008 15:56:43 -0800 Subject: WinMerge--B/W Shading of Printed Copy to Show Differences? Message-ID: <3jX1l.6876$pr6.3299@flpi149.ffdc.sbc.com> Is there a way to highlight differences between the two files when printing in b/w? Help suggests there may be some texturing, but all I see is color choices. -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From clp at rebertia.com Sat Dec 13 16:07:22 2008 From: clp at rebertia.com (Chris Rebert) Date: Sat, 13 Dec 2008 13:07:22 -0800 Subject: Python 3.0 crashes displaying Unicode at interactive prompt In-Reply-To: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> Message-ID: <47c890dc0812131307o119ae1bap37f28fadd9772f08@mail.gmail.com> On Sat, Dec 13, 2008 at 12:28 PM, John Machin wrote: > > Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> x = u'\u9876' >>>> x > u'\u9876' > > # As expected > > Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit > (Intel)] on win 32 > Type "help", "copyright", "credits" or "license" for more information. >>>> x = '\u9876' >>>> x > Traceback (most recent call last): > File "", line 1, in > File "C:\python30\lib\io.py", line 1491, in write > b = encoder.encode(s) > File "C:\python30\lib\encodings\cp850.py", line 19, in encode > return codecs.charmap_encode(input,self.errors,encoding_map)[0] > UnicodeEncodeError: 'charmap' codec can't encode character '\u9876' in > position > 1: character maps to > > # *NOT* as expected (by me, that is) > > Is this the intended outcome? When Python tries to display the character, it must first encode it because IO is done in bytes, not Unicode codepoints. When it tries to encode it in CP850 (apparently your system's default encoding judging by the traceback), it unsurprisingly fails (CP850 is an old Western Europe codec, which obviously can't encode an Asian character like the one in question). To signal that failure, it raises an exception, thus the error you see. This is intended behavior. Either change your default system/terminal encoding to one that can handle such characters or explicitly encode the string and use one of the provided options for dealing with unencodable characters. Also, please don't call it a "crash" as that's very misleading. The Python interpreter didn't dump core, an exception was merely thrown. There's a world of difference. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From pdorange at pas-de-pub-merci.mac.com Mon Dec 22 06:31:44 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Mon, 22 Dec 2008 12:31:44 +0100 Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> Christian Heimes wrote: > Pierre-Alain Dorange schrieb: > > I don't find any sign(x) function in the math library (return the sign > > of the value). > > I've read that math module is a wrapper to C math lib and that C math > > lib has not sign(), so... > > Starting with Python 2.6 the math and cmath modules have a copysign > function. I'm using 2.5.2 at that time, but copysign() is fine. with : s=copysign(1.0,x) it return the sign (-1.0, 0.0, +1.0) > > I've implement my own sign function of course (it's easy) but a standard > > one in math would be better and could be faster. > > Sure? :) I was... > Are you aware that the IEEE 754 standard makes a difference > between the floats +0.0 and -0.0? > > from math import atan2 > def sign(x): > if x > 0 or (x == 0 and atan2(x, -1.) > 0.): > return 1 > else: > return -1 Thanks As my need is for a game and that i do not have IEEE real concern, i would simply using my simple function (but not as accurate) : def sign(x): if x==0.0: return 0.0 elif x>0.0: return 1.0 else: return -1.0 -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From rdcollum at gmail.com Thu Dec 18 11:24:44 2008 From: rdcollum at gmail.com (Roger) Date: Thu, 18 Dec 2008 08:24:44 -0800 (PST) Subject: Tkinter unbinding Message-ID: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> I've done a lot of googling for this topic and I fear that it's not possible. I have a widget that is overloaded with several bindings. I want to be able to unbind one method form the same Event without destroying all the other bindings to the same event that's associated to the same widget. For example: import Tkinter def test(): print 'test' def test2(): print 'test2' root = Tkinter.Tk() funcid1 = root.bind("<1>", lambda e: test()) funcid2 = root.bind("<1>", lambda e: test2(), add='+') root.unbind("<1>", funcid2) root.mainloop() When run neither <1> binding will exist against the root because the unbind will unbind all the functions associated with that event. However, in this example, I only want to unbind test2 not test1. Any help is greatly appreciated. Thanks! Roger. From nospam at nospam.com Fri Dec 26 09:16:49 2008 From: nospam at nospam.com (Gilles Ganault) Date: Fri, 26 Dec 2008 15:16:49 +0100 Subject: [2.5.1] Str.Replace() doesn't work? Message-ID: Hello I need to parse an HTML file where records aren't homogenous, so I figured I could run a first loop to add an unused character at the beginning of each record, and then run a second loop to actually parse each record. I can't figure out why the script is not returning anything in the "for m in matches" block: ========= f = open("input.txt", "r") response = f.read() f.close() #Pass 1: Add some character to separate records #response.replace('
  • References: <58772.75.67.216.99.1228576211.squirrel@webmail.jots.org> Message-ID: Ken D'Ambrosio wrote: > Hi, all. I've done some poking around, and can find roughly two million > different ways to attach attachments to an e-mail... but darn few to > detach them. Any suggestions? I'm assuming I'm just missing looking in > The Right Place, but thus-far, my Googling has been for naught. Try the email package doc in the Lib Manual. From kyosohma at gmail.com Wed Dec 31 16:06:21 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 31 Dec 2008 13:06:21 -0800 (PST) Subject: Creating an application for Linux Message-ID: <7d2fe328-064c-46da-9150-7305b6f9e94e@b41g2000pra.googlegroups.com> Hi, My boss wants me to port one of my applications to Ubuntu. I successfully ported it without too many headaches but now I need a way to distribute it to people that may or may not already have the dependencies my application requires. I'm a newb with Linux so I'm not even sure what they call the distribution (rpms, deb, source code). After browsing the various "installer" docs out there, it looks like bbfreeze or PyInstaller might work, but I couldn't find any examples. Any advice is appreciated. Thanks! I am using Python 2.5.2 and this is a wxPython application with SqlAlchemy and a few other external packages. Mike From cjw at ncf.ca Sat Dec 6 08:18:07 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 06 Dec 2008 08:18:07 -0500 Subject: Multiple Versions of Python on Windows XP In-Reply-To: References: <4934de22$0$27863$9b622d9e@news.freenet.de> <4934E183.9020404@g.nevcal.com> <4934E3BF.7000403@v.loewis.de> Message-ID: <493A7B8F.8070806@ncf.ca> Glenn Linderman wrote: > On approximately 12/1/2008 11:29 PM, came the following characters from > the keyboard of Martin v. L?wis: >>> It would be nice if the ftypes were version specific as created by the >>> installer; IIRC, I created the above three from the ftype Python.File as >>> I installed each version. >>> >> >> That's a good idea; please submit a wish list item to bugs.python.org. >> There may be issues (such as people relying on this being Python.File), >> but I can't see any problems off-hand. >> >> Regards, >> Martin >> > > OK, Issue 4485 created. My first one, so let me know if I goofed. I > elaborated a bit from the original email, upon reflection. Seemed > useful, but also seemed complex by the time I got done. > > I don't really have a clue what the uninstaller should do with these; > nor have I fiddled to know if it presently removes Python.File. I > suppose it should delete them, if and only if the ftype and assoc have > the same content as was created by the corresponding version installation. > Here's another approach to handling multiple versions of Python, thanks to the PyScripter List. It does not address the need to access different versions of the Python Interpreter. Here is the full story. There are two types of Python installation a) For all users Python creates registry entries at HKEY_LOCAL_MACHINE\SOFTWARE\Python \PythonCore\2.x with installation info and puts the dll in c:\Windows \System32. b) For a single user Python creates registry entries at HKEY_CURRENT_USER\SOFTWARE\Python \PythonCore\2.x with installation info and does not put the dll in c: \Windows\System32. PyScripter without any command line flags looks at the registry to find the latest version of Python and then for an all user installation tries to load the relevant Python dll from the system path. For a single user installation tries to load the DLL from the Install path that is in the registry. When PyScripter is used with a --PYTHONxx flag then it does the above but searching only for the specific version. The Registry lookup does not take place when Python is used with the -- PYTHONDLLPATH. Instead PyScripter tries to load the Python dll from the specified path. The --PYTHONDLLPATH flag should be used with the --PYTHONxx flag. See http://pyscripter.googlepages.com/portablepython for an example of using PyScripter with portable Python. The %PYTHONHOME% variable is not used by PyScripter directly but by Python to find the installed libraries. See the Python documentation for its use. Colin W. From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 07:15:27 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Dec 2008 12:15:27 GMT Subject: Don't you just love writing this sort of thing :) References: <0148b086$0$20670$c3e8da3@news.astraweb.com> Message-ID: <0149131f$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 23:16:08 +1300, Lawrence D'Oliveiro wrote: > In message <0148b086$0$20670$c3e8da3 at news.astraweb.com>, Steven D'Aprano > wrote: > >> On Fri, 05 Dec 2008 13:27:35 +1300, Lawrence D'Oliveiro wrote: >> >>> In message , Cong >>> Ma wrote: >>> >>>> The "if ... != None" is not necessary... "if PatchDatePat.search(f)" >>>> is OK. >>> >>> I don't do that. >> >> Perhaps you should? > > I prefer using explicitly Boolean values for conditions. Perhaps you do, but there's no evidence of such in your post. bool(PatchDatePat.search(f) != None) would be an "explicitly Boolean value". What you posted was an *implicitly* Boolean value, and not even guaranteed to be Boolean, as __ne__ can return any object it likes. And yes, such a call to bool would be pointless. -- Steven From saluk64007 at gmail.com Sun Dec 21 03:57:46 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Sun, 21 Dec 2008 00:57:46 -0800 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: On Sat, Dec 20, 2008 at 10:15 PM, r wrote: > On Dec 20, 11:11 pm, walterbyrd wrote: >> On Dec 20, 5:05 pm, Roy Smith >> >> > He got really hung up on the % syntax. >> >> I guess it's good to know that there is, at least, one person in the >> world doesn't like the % formatting. As least the move was not >> entirely pointless. >> >> But, you must admit, of all the things people complain about with >> Python, the % formatting is probably one of the least common >> complaints. Complaints about Python's speed seem much more common. >> >> Yet, 3.0 makes the speed worse, and "fixes" a non-problem. A few points: 1) The new formatting is NOT the reason for the speed slowdown. So this change at least was a no cost change. No cost to interpreter speed, and no cost as it doesn't replace the old sprintf style. Of all the things to complain about in python 3.0, the format method is the silliest. 2) In my experience, major version changes tend to be slower than before. When a lot of things change, especially if very low-level things change, as happened in python 3.0, the new code has not yet went through many years of revision and optimization that the old code has. In my opinion, python 3 was rushed out the door a bit. It could have done with a few more months of optimization and polishing. However, on the other hand, it is going to take so long for python infrastructure to convert to python 3, that an earlier release makes sense, even if it hasn't been excessively polished. The biggest reason for the speed change is the rewritten stdio and unicode-everything. Hopefully this stuff can be improved in future updates. I don't think anyone WANTS cpython to be slower. From steve at REMOVE-THIS-cybersource.com.au Mon Dec 29 19:44:46 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Dec 2008 00:44:46 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <9c8c524f-6985-4cc8-b19c-666f85c69946@a26g2000prf.googlegroups.com> Message-ID: <01696606$0$6988$c3e8da3@news.astraweb.com> On Mon, 29 Dec 2008 09:50:14 -0800, walterbyrd wrote: > On Dec 21, 12:28?pm, Bruno Desthuilliers > wrote: > >> > I can see where the new formatting might be helpful in some cases. >> > But, I am not sure it's worth the cost. >> >> Err... _Which_ cost exactly ? > > Loss of backward compatibility, mainly. How do you lose backward compatibility by *adding* new functionality? The old functionality will continue to work as normal. -- Steven From google at mrabarnett.plus.com Tue Dec 9 14:00:02 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 09 Dec 2008 19:00:02 +0000 Subject: Best way to report progress at fixed intervals In-Reply-To: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> Message-ID: <493EC032.3040005@mrabarnett.plus.com> Slaunger wrote: > Hi comp.lang.python > > I am a novice Python 2.5 programmer, who write some cmd line scripts > for processing large amounts of data. > > I would like to have possibility to regularly print out the progress > made during the processing, say every 1 seconds, and i am wondering > what a proper generic way to do this is. > > I have created this test example to show the general problem. Running > the script gives me the output: > > Work through all 20 steps reporting progress every 1.0 secs... > Work step 0 > Work step 1 > Work step 2 > Work step 3 > Work step 4 > Processed 4 of 20 > Work step 5 > Work step 6 > Work step 7 > Work step 8 > Processed 8 of 20 > Work step 9 > Work step 10 > Work step 11 > Work step 12 > Work step 13 > Processed 13 of 20 > Work step 14 > Work step 15 > Work step 16 > Work step 17 > Processed 17 of 20 > Work step 18 > Work step 19 > Finished working through 20 steps > > The script that does this is as follows: > > testregularprogress.py: > > """ > Test module for testing generic ways of displaying progress > information > at regular intervals. > """ > import random > import threading > import time > > def work(i): > """ > Dummy process function, which takes a random time in the interval > 0.0-0.5 secs to execute > """ > print "Work step %d" % i > time.sleep(0.5 * random.random()) > > > def workAll(verbose=True, max_iter=20, progress_interval=1.0): > > class _Progress(object): > > def __init__(self): > self.no = 0 > self.max = max_iter > self.start_timer = verbose > > def __str__(self): > self.start_timer = True # I do not like this appraoch > return "Processed %d of %d" % (self.no, self.max) > > p = _Progress() > > def report_progress(): > print p > > if verbose: > print "Work through all %d steps reporting progress every > %3.1f secs..." % \ > (max_iter, progress_interval) > > for i in xrange(max_iter): > if p.start_timer : > p.start_timer = False # Let the progress instance set the > flag > timer = threading.Timer(progress_interval, > report_progress) > timer.start() > work(i) > p.no = i + 1 > > # Kill the last timer, which is still active at this time > timer.cancel() > > if verbose: > print "Finished working through %d steps" % max_iter > > if __name__ == "__main__": > workAll() > > Quite frankly, I do not like what I have made! It is a mess, > responsibilities are mixed, and it seems overly complicated. But I > can't figure out how to do this right. > > I would therefore like some feedback on this proposed generic "report > progress at regular intervals" approach presented here. What could I > do better? > I've come up with this: """ Test module for testing generic ways of displaying progress information at regular intervals. """ import random import threading import time def work(i): """ Dummy process function, which takes a random time in the interval 0.0-0.5 secs to execute """ print "Work step %d" % i time.sleep(0.5 * random.random()) def workAll(verbose=True, max_iter=20, progress_interval=1.0): class _Progress(threading.Thread): def __init__(self, progress_interval=1.0): threading.Thread.__init__(self) self.setDaemon(True) self.progress_interval = progress_interval self.progress = None self.active = True def stop(self): self.active = False def run(self): while self.active: if self.progress is not None: print self.progress time.sleep(self.progress_interval) if verbose: print "Work through all %d steps reporting progress every %3.1f secs..." % \ (max_iter, progress_interval) p = _Progress(progress_interval) p.start() for i in xrange(max_iter): p.progress = "Processed %d of %d" % (i + 1, max_iter) work(i) p.stop() if verbose: print "Finished working through %d steps" % max_iter if __name__ == "__main__": workAll() From Jiandong.Ge at gmail.com Thu Dec 11 09:55:04 2008 From: Jiandong.Ge at gmail.com (JD) Date: Thu, 11 Dec 2008 06:55:04 -0800 (PST) Subject: How to pass out the result from iterated function References: <74ea407e-7cf0-4619-99e5-d08b9161e9d0@f40g2000pri.googlegroups.com> Message-ID: <6f3f4f5c-d043-42ef-9ba3-075036d79c6d@r37g2000prr.googlegroups.com> On Dec 10, 2:25 pm, eric wrote: > On Dec 10, 9:16 pm, JD wrote: > > > > > I got a iterated function like this: > > > def iterSomething(list): > > has_something = False > > for cell in list: > > if something in cell: > > has_something = True > > output = something > > if has_something: > > iterSomething(output) > > else: > > final_out = outupt > > > The problem is how can I read this final_out outside of the function. > > I tried the global statement, it seems not work. Any idea? > > > JD Thanks, I tried to return the last result. It's not working. Your code works, thanks > why don't you just return it ? > > def iterSomething(list): > has_something = False > for cell in list: > if something in cell: > has_something = True > output = something > if has_something: > return iterSomething(output) > else: > return output > > ? From rt8396 at gmail.com Sat Dec 20 19:20:38 2008 From: rt8396 at gmail.com (r) Date: Sat, 20 Dec 2008 16:20:38 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> On Dec 20, 6:05?pm, Roy Smith wrote: > In article > , > > ?walterbyrd wrote: > > On Dec 19, 10:25?am, Michael Torrie wrote: > > > > Personally the new string formatter is sorely needed in Python. ? > > > Really? You know, it's funny, but when I read problems that people > > have with python, I don't remember seeing that. Loads of people > > complain about the white space issue. Some people complain ?about the > > speed. Lots of complaints about certain quirky behavior, but I have > > not come across any complaints about the string formatting. > > > In fact, from what I have seen, many of the "problems" being "fixed" > > seem to be non-problems. > > > I dunno, maybe it's just me. > > I had an interesting experience with this recently. ?I was giving a > co-worker quick python into. ?He's an experienced programer in various > languages, but this was his first exposure to python. > > He got really hung up on the % syntax. ?By (bad) luck, he was trying to > print a tuple (let's call it "t"), did > > format % t > > and was surprised at the result. ?It set him off on a "but that's stupid, > blah, blah, blah" rant. ?I haven't absorbed the new syntax well enough to > figure out if people will get hung up by this with the new syntax. It is stupid, more reason to fix the current problem instead creating a whole new one. One more big complaint "THE BACKSLASH PLAGUE". ever tried regexp?, or file paths?. All because that little backslash char is a line continuation character, maybe we should fix that. Would your life end if '\' was not a continuation char? Mine would not because i don't write my code to need it. Python has real warts that need fixing, and thats really hard for me to say, because i am such a fanboy of Python. From sampsa.riikonen at iki.fi Mon Dec 8 15:56:10 2008 From: sampsa.riikonen at iki.fi (Sampsa Riikonen) Date: Mon, 08 Dec 2008 22:56:10 +0200 Subject: xml.dom.minidom bug ? Message-ID: Dear All, I am experiencing a weird problem with the xml.dom.minidom module: ---------------------------------------- sampsa at linux-ty84:~/python> python easyxml.py Traceback (most recent call last): File "easyxml.py", line 1, in import xml.dom.minidom File "/usr/lib64/python2.5/site-packages/_xmlplus/dom/__init__.py", line 236, in import MessageSource File "/usr/lib64/python2.5/site-packages/_xmlplus/dom/MessageSource.py", line 21, in _ = get_translator("dom") File "/usr/lib64/python2.5/site-packages/_xmlplus/FtCore.py", line 54, in get_translator f = gettext.translation('4Suite', locale_dir).gettext File "/usr/lib64/python2.5/gettext.py", line 478, in translation t = _translations.setdefault(key, class_(open(mofile, 'rb'))) File "/usr/lib64/python2.5/gettext.py", line 180, in __init__ self._parse(fp) File "/usr/lib64/python2.5/gettext.py", line 264, in _parse unpack = struct.unpack AttributeError: 'module' object has no attribute 'unpack' ------------------- A bug in the module? And the weirdest thing is that I figured out how to get around this problem long time ago, but now I don't have a clue anymore... :/ Any help appreciated. Cheers, Sampsa From eric at ericaro.net Wed Dec 10 15:25:27 2008 From: eric at ericaro.net (eric) Date: Wed, 10 Dec 2008 12:25:27 -0800 (PST) Subject: How to pass out the result from iterated function References: Message-ID: <74ea407e-7cf0-4619-99e5-d08b9161e9d0@f40g2000pri.googlegroups.com> On Dec 10, 9:16?pm, JD wrote: > I got a iterated function like this: > > def iterSomething(list): > ? ? has_something = False > ? ? for cell in list: > ? ? ? ? if something in cell: > ? ? ? ? ? ? has_something = True > ? ? ? ? ? ? output = something > ? ?if has_something: > ? ? ? ?iterSomething(output) > ? ?else: > ? ? ? ?final_out = outupt > > The problem is how can I read this final_out outside of the function. > I tried the global statement, it seems not work. Any idea? > > JD why don't you just return it ? def iterSomething(list): has_something = False for cell in list: if something in cell: has_something = True output = something if has_something: return iterSomething(output) else: return output ? From conrad.ammon at gmail.com Mon Dec 15 15:45:41 2008 From: conrad.ammon at gmail.com (cmdrrickhunter@yaho.com) Date: Mon, 15 Dec 2008 12:45:41 -0800 (PST) Subject: Managing timing in Python calls References: Message-ID: I believe WxTimerEvent is handled using the event queue, which isn't going to do what you want. An event which goes through the queue does not get processed until you return to the queue. What you want to do is actually a rather difficult task to do generically. Should the task be interrupted immediately? Or is a tiny latency acceptable? Should the function being terminated get to handle its own termination? Or should the termination be forced on it. What sort of overhead is acceptable for this "set_timeout" behavior? I would not be surprised if there isn't a built in solution, because its so hard, but rather built in tools which can be used to do it. If your timeouts are on the order of seconds, you might be able to just check time.time() at the begining, and compare it to the current time later in the function. This could be on the main thread or on a worker thread. If you need better handling, you may want to look at how condition variables and such work. Finally, thread has a function to send a Keyboard Interrupt to the main thread. I believe you could do your work on the main thread, and catch the interrupt. "Background" tasks are not easy to implement in any language (other than perhaps AJAX ;-) ). Remember, Python does not support truly simultaneous threads. It actually does timeslices of about 100 operations. Any solution you choose should work given this information. And as for a "nicer" construct, I personally just learned of how to handle the "with" command. I could see something like class Timeout: def __init__(self, t): self.t = t def __enter__(self): self.start = time.time() def __exit__(self, x, y, z): return None def __nonzero__(self): return time.time() - self.start <= self.t def doSomethingLong(timeout = True): # true guarentees bailout never occurs while timeout: doAnIteration() with Timeout(3) as t: doSomethingLong(t) and have your Timeout class have a flag which it sets when doSomethingLong needs to bail out, using whatever method is "best" for your particular application. This is, of course pseudocode - I've not run it through python msyself. Hopefully any errors are obvious enough that you can work around them. From Russ.Paielli at gmail.com Sun Dec 7 15:13:37 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 7 Dec 2008 12:13:37 -0800 (PST) Subject: Python for kids? Message-ID: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> I have a 12-year-old son who spends too much time playing Xbox live and watching silly YouTube videos. I would like to try to get him interested in programming. Is anyone aware of a good book or website that addresses this concern, preferably (but not necessarily) using Python? I could try to teach him Python myself, but I'm afraid I would just frustrate him and kill his interest in programming. I did a Google search and found a few things, but not a lot. Thanks. From tjreedy at udel.edu Sat Dec 6 16:47:15 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 06 Dec 2008 16:47:15 -0500 Subject: "as" keyword woes In-Reply-To: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> Message-ID: Warren DeLano wrote: > As someone somewhat knowledgable of how parsers work, I do not > understand why a method/attribute name "object_name.as(...)" must > necessarily conflict with a standalone keyword " as ". It seems to me > that it should be possible to unambiguously separate the two without > ambiguity or undue complication of the parser. The lexer, which preceeds the parser, has separate KEYWORD and IDENTIFIER categories. For example, 'if a ...' is lexed as (KEYWORD, 'if'), (IDENTIFIER, 'a'), ... . Leaving 'as' as an identifier identified by the parser as a contextual keyword in import statements was a kludge. When 'as' was reused in "with as " in 2.5 (with __future__ import), it was planned and announced that *both* 'with' and 'as' would become full-time keywords in 2.6, just as 'yield' did in 2.3 after its introduction (with required __future__) in 2.2. Making 'yield' a keyword of course impacted people who used the word in financial calculations, but they adjusted. > So, assuming I now wish to propose a corrective PEP Working with people trying to improve threading would be more productive. Terry Jan Reedy From jstroud at mbi.ucla.edu Sun Dec 14 18:24:05 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 14 Dec 2008 15:24:05 -0800 Subject: Need help improving number guessing game In-Reply-To: <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> Message-ID: It looks much better. But as Bruno suggests and as I alluded to earlier, you should get in the habit of forming verification loops on input channels that aren't already guaranteed to provide valid input messages. I'm not sure how to say that in English, but in python my example was: while True: try: guess1 = int(input("\n>> ")) except ValueError: print 'Bad value.' else: break Other than that, you still have some points where you can break lines down to improve clarity. Think of it like trying to avoid run-on sentences. Over all, it looks like you have picked up some good technique that you could only get by experimentation over the course of about 5 or 6 months. James From deets at nospam.web.de Mon Dec 8 12:50:05 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 Dec 2008 18:50:05 +0100 Subject: Equivalent of 'wget' for python? References: Message-ID: <6q552dFat95dU1@mid.uni-berlin.de> Jean-Paul Calderone wrote: > On Mon, 08 Dec 2008 17:29:35 +0100, "Diez B. Roggisch" > wrote: >>Robert Dailey wrote: >> >>> Hi, >>> >>> I'm looking for a portable way to download ZIP files on the internet >>> through Python. I don't want to do os.system() to invoke 'wget', since >>> this isn't portable on Windows. I'm hoping the core python library has >>> a library for this. Note that I'll be using Python 3.0. >> >>Module urllib2 >> > > There isn't such a module in Python 3.0. If you knew that urllib2 has been removed/integrated/whatever into urllib, it would have helped to mention that, don't you think? To the OP: urllib.request.urlopen is your friend. Diez From p at ulmcnett.com Mon Dec 22 15:04:11 2008 From: p at ulmcnett.com (Paul McNett) Date: Mon, 22 Dec 2008 12:04:11 -0800 Subject: Check file is In-Reply-To: References: <7caa7d45-ebbe-4c88-bb50-2f01f7315d07@s9g2000prg.googlegroups.com> <494cbef5$0$90267$14726298@news.sunsite.dk> Message-ID: <494FF2BB.2050402@ulmcnett.com> Colin J. Williams wrote: > The ReportLab toolkit appears to be concerned with building Portable > Document Files. I would be interested in any utility which will read > any pdf - for example, to convert pdf -> html I don't know of any Python utility to do this, but pdftohtml, pdftotext, pdftoppm, and pdftops exist on my Ubuntu Linux system. Paul From rt8396 at gmail.com Wed Dec 31 03:02:28 2008 From: rt8396 at gmail.com (r) Date: Wed, 31 Dec 2008 00:02:28 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <9c8c524f-6985-4cc8-b19c-666f85c69946@a26g2000prf.googlegroups.com> <01696606$0$6988$c3e8da3@news.astraweb.com> <78bd573f-03b0-4628-909d-3f84f9718e7e@13g2000yql.googlegroups.com> Message-ID: <4f95bf3c-69cb-4b8f-b2c5-cce5f5f38b49@v42g2000yqv.googlegroups.com> You know, it is so much easier to find my posts now that someone has been thoughtful enough to mark them for me. Thank you kind chaps, i shall leave a shiny new nickel for you, just send me your name, address, and phone numbers. I'll get them in the mail right away. From joe at strout.net Tue Dec 9 10:36:50 2008 From: joe at strout.net (Joe Strout) Date: Tue, 9 Dec 2008 08:36:50 -0700 Subject: How to initialize a class variable once In-Reply-To: <493E5700.4030107@aim.com> References: <493E5700.4030107@aim.com> Message-ID: <293D8F1A-066B-43FD-B3D2-82368955AB11@strout.net> On Dec 9, 2008, at 4:31 AM, Brian Allen Vanderburg II wrote: > There is one situation where a module can be imported/executed > twice, if it is the __main__ module. That's an excellent point -- this is something I've run into, and it always feels a bit awkward to code around it. What's the standard idiom for avoiding this issue in a complex app? Have a "main" file that is not imported by anything else, and which does little but launch stuff from some other module? As I say it, that seems obvious, but somehow I keep getting urges to put global stuff (like my Application subclass) in the main file, and then I find I need to reference it from some other module, and get into trouble. This is probably just bias from my last programming environment, though. I can adapt. Anyway, thanks for pointing this out; I bet it's the root cause of the OP's observation. Best, - Joe From steve at holdenweb.com Tue Dec 30 08:02:11 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Dec 2008 08:02:11 -0500 Subject: string in files In-Reply-To: <62075511-08ad-405a-a3af-2da8d2f22c50@v39g2000pro.googlegroups.com> References: <62075511-08ad-405a-a3af-2da8d2f22c50@v39g2000pro.googlegroups.com> Message-ID: ibpet11 at gmail.com wrote: > On Dec 30, 11:17 am, "Narasimhan Raghu-RBQG84" > wrote: >> Simple solution: us result=yourString.split(" ") and you get a list with >> all the words. >> >> -----Original Message----- >> From: python-list-bounces+rbqg84=motorola.... at python.org >> >> [mailto:python-list-bounces+rbqg84=motorola.... at python.org] On Behalf Of >> ibpe... at gmail.com >> Sent: Tuesday, December 30, 2008 3:43 PM >> To: python-l... at python.org >> Subject: string in files >> >> guys i need info on how to call up different words in a line of a file >> using python example : file = 'this is a python coding group' >> >> i want to assign a xter to this, is, a, python , coding and group >> [...] > thanks brother > i mean how do i particularly assign (u = this) > (y = is).... > in the strings up there. i have been able to split strings with any > character sign. > Well, if you *know* you have a particular number of words in the string you can say u, v, w, x, y, z = 'this is a python coding group'.split() But if you have a variable number of words this isn't practical in Python 2, though Python 3 has features that make it easier. The real question is "what is the larger goal you are trying to achieve". Where a programmer is trying to create names dynamically there are usually better ways to proceed. Could you tell us a little more about what you are trying to do? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From patrickstinson.lists at gmail.com Mon Dec 1 00:47:45 2008 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Sun, 30 Nov 2008 20:47:45 -0900 Subject: incorrect line reported in traceback Message-ID: <6214d7a20811302147r4e17a7a5g38796573d5804d@mail.gmail.com> Is there any reason why the last item in the traceback is one frame below the top of the stack? It would be great to show the real line in my editor... From mtestinori at no_mail.com Mon Dec 1 19:17:12 2008 From: mtestinori at no_mail.com (Mario Testinori) Date: Tue, 02 Dec 2008 01:17:12 +0100 Subject: Emacs vs. Eclipse vs. Vim References: <27757214-df90-4a33-8f44-65673c9ababd@20g2000yqt.googlegroups.com> Message-ID: On Mon, 1 Dec 2008 15:57:17 -0800 (PST), "sjdevnull at yahoo.com" wrote: >On Nov 29, 3:44?pm, Josh wrote: >> If you were a beginning programmer and willing to make an investment in >> steep learning curve for best returns down the road, which would you pick? >> >> I know this topic has been smashed around a bit already, but 'learning >> curve' always seems to be an arguement. If you feel that one is easier >> or harder than the others to learn feel free to tell, but let's not make >> that the deciding factor. Which one will be most empowering down the >> road as a development tool? > >I'd strongly recommend not using an IDE but going with federated >tools; this makes it easier to pick the editor, code navigation tool, >build system, etc that you like best, and makes it easier to swap out >one piece at a time if you don't like it. So of the choices >mentioned, I'd go with emacs or vim if I were you. I'd say this has another advantage, that someone already mentioned - better learning the process that goes behind the gui of an ide. After all, an ide is just a frontend to something ... > >Personally I also find high value in picking an editor that can be run >on a command-line terminal connection (e.g. when you're ssh'd into a >remote server), but that may be less important depending on what sort >of development you are doing. True, the value of this could vary from critical to not important at all. -- Mario From grante at visi.com Fri Dec 19 17:30:43 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 19 Dec 2008 16:30:43 -0600 Subject: IMAP: How to implement GMail-like threaded conversations view References: Message-ID: On 2008-12-19, Jean-Paul Calderone wrote: > On Fri, 19 Dec 2008 08:47:18 -0800 (PST), Martin wrote: >>Currently I am trying to get used to Python's imaplib and email >>modules. >>I'like to create a webmail client simmilar to GMail. > > I'd suggest using Twisted's IMAP4 client. It's somewhat easier to > use than Python's imaplib because it does much more parsing of IMAP4's > complex syntax for you. It will also be easier to do IMAP4 and HTTP > simultaneously if you're using Twisted. Anything that helps with with the IMAP responses is worth looking at, because parsing IMAP response messages is brutal. I'm not sure what the IMAP protocol authors thought was going to be parsing the replies, but it sure couldn't have been a real-world computer program. IMO, the IMAP protocol has achieved a level of suckage that would make Microsoft proud. But, it works. Eventually. -- Grant From lists at cheimes.de Tue Dec 16 13:47:23 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 16 Dec 2008 19:47:23 +0100 Subject: sys.maxint in Python 2.6.1 (amd64) on Windows XP x64 In-Reply-To: <4bddf65a-bb9f-406c-a544-8c38b27547a7@b38g2000prf.googlegroups.com> References: <4bddf65a-bb9f-406c-a544-8c38b27547a7@b38g2000prf.googlegroups.com> Message-ID: Lin schrieb: > Hi, > > I installed the amd64 version of Python 2.6.1 on my Windows XP x64 > system. I was expecting sys.maxint to be 9223372036854775807 (or 2 ^63 > -1), but instead I got 2147483647 (i.e., 2^31-1) just like what I got > from a 32-bit version of Python. Is this by design or does it indicate > a bug or an installation problem? Thank you very much! This is by design. In their infinitive wisdom Microsoft has decided to make the 'long' C type always a 32 bit signed integer - even on 64bit systems. On most Unix systems a long is at least 32 bit but usually sizeof(ptr). Christian From mirandasnailvv at gmail.com Fri Dec 19 19:42:21 2008 From: mirandasnailvv at gmail.com (mirandasnailvv at gmail.com) Date: Fri, 19 Dec 2008 16:42:21 -0800 (PST) Subject: sydney female slut gloryhole - Free Message-ID: <179d616f-d7d6-41bd-897c-ac7216ea5879@v39g2000pro.googlegroups.com> sydney female slut gloryhole . . . *******CLICK HERE******** http://club247.cn/sydney-female-slut-gloryhole ***************************** . . . . . . . . . . . . sydney female slut gloryhole From jeremiah.dodds at gmail.com Wed Dec 3 06:45:05 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Wed, 3 Dec 2008 06:45:05 -0500 Subject: Multiple equates In-Reply-To: References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> <9m3h06-vhh.ln1@lairds.us> Message-ID: <12cbbbfc0812030345m5afa83d3m518e108d11d3e0fb@mail.gmail.com> On Wed, Dec 3, 2008 at 6:23 AM, Lawrence D'Oliveiro wrote: > > So why is that better? > -- > http://mail.python.org/mailman/listinfo/python-list > I personally think that it looks marginally cleaner (indentation issues aside). Do you think it's substantially worse? If so, why? I mean you asked how you would express the original code with the lambda - that's how you would, by pulling the lambda out into a function. How would you express it better is a different question. I think that the code in question is an example of a case where a lambda is appropriate in python, but it's definitely not any worse for having the code pulled out. If the function wasn't trival, you'd have to anyhow. The whole "lambdas good or bad" thing has been done to death as far as it relates to python. For python, it seems that anonymous functions are a no-no unless they're effectively one liners. -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Fri Dec 19 15:44:40 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 19 Dec 2008 21:44:40 +0100 Subject: [ANN] Python 2.4.6 and 2.5.3 (final) Message-ID: <494C07B8.6000001@v.loewis.de> On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.4.6 and 2.5.3 (final). 2.5.3 is the last bug fix release of Python 2.5. Future 2.5.x releases will only include security fixes. According to the release notes, about 80 bugs and patches have been addressed since Python 2.5.2, many of them improving the stability of the interpreter, and improving its portability. Since the release candidate, the only change was an update to the Macintosh packaging procedure. 2.4.6 includes only a small number of security fixes. Python 2.6 is the latest version of Python, we're making this release for people who are still running Python 2.4. See the release notes at the website (also available as Misc/NEWS in the source distribution) for details of bugs fixed; most of them prevent interpreter crashes (and now cause proper Python exceptions in cases where the interpreter may have crashed before). For more information on Python 2.4.6 and 2.5.3, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.4.6 http://www.python.org/2.5.3 Highlights of the previous major Python releases are available from the Python 2.5 page, at http://www.python.org/2.4/highlights.html http://www.python.org/2.5/highlights.html Enjoy this release, Martin Martin v. Loewis martin at v.loewis.de Python Release Manager (on behalf of the entire python-dev team) From ylj798 at gmail.com Tue Dec 2 11:48:16 2008 From: ylj798 at gmail.com (ylj798 at gmail.com) Date: Tue, 2 Dec 2008 08:48:16 -0800 (PST) Subject: help me~!about base64 Message-ID: <0ff1ba7b-8a17-4647-99fc-9c8e32f83de7@g1g2000pra.googlegroups.com> my code? ????????????????????????????????????? import base64 def deflashget(st): if st.startswith('Flashget://'): return base64.decodestring(st[len('Flashget://'):])[10:-10] elif st.startswith('http://') or st.startswith('ftp://'): return 'Flashget://' + base64.encodestring('[FLASHGET]' + st +'[FLASHGET]').replace('\n', '') st='Flashget:// W0ZMQVNIR0VUXWh0dHA6Ly9kb3duLnJub3ZlbC5jb20vYm9va3R4dC8zLzEzNjgyLzEzNjgyLnppcFtGTEFTSEdFVF0=&1064' print deflashget(st) ???????????????????????????????????????? it's run ,Eric gave me error,the error is "'module' object has no attribute 'decodestring'", what can I do? who can help me? From alexoplocatie at gmail.com Wed Dec 17 09:28:01 2008 From: alexoplocatie at gmail.com (aka) Date: Wed, 17 Dec 2008 06:28:01 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> <0d9ea7cc-b5fb-4edb-be32-490aae9e7204@b41g2000pra.googlegroups.com> Message-ID: <0de3a7bf-a4c4-4103-a4e0-44313405fa94@z28g2000prd.googlegroups.com> Hi John, thanks. You're right, I didn't past the method header because I thought it didn't matter when the input filename is hardcoded. The try/except isn't very helpful indeed so I commented it out. You're right I wrongly referred to the UnicodeReader class in my first post because that's ultimately where I want to go so I outcommented it here for you to see. The fact is that neither csv.reader nor the UnicodeReader will read the file, while writing with the UnicodeWriter works like a charm. That's why I put str() around roles to see any content. I simplified the csv-file by cutting off columns without result. The file looks now like: id;company;department 12;Cadillac;Research 11;Ford;Accounting 10;Chrysler;Sales The dictionary on the return is because this code is part of my TurboGears application. The entire method is: import csv from utilities.urw import UnicodeWriter, UnicodeReader @expose(allow_json=True) def import_roles(self, input=None, *args, **kwargs): inp = 'C:/temp/test.csv' roles = [] msg = '' ## try: fp = open(inp, 'rb') reader = csv.reader(fp, dialect='excel', delimiter=';') ## reader = UnicodeReader(fp, dialect='excel', delimiter=';') for r in reader: roles.append(r[0]) fp.close() ## except: ## msg = "Something's wrong with the csv.reader" return dict(filepath=inp, roles=str(roles), msg=msg) csv.reader results in: for r in reader: Error: line contains NULL byte Use of UnicodeReader results in: UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: unexpected code byte Will post only complete code from now on thanks. From jcd at sdf.lonestar.org Mon Dec 8 15:07:22 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 08 Dec 2008 15:07:22 -0500 Subject: "as" keyword woes In-Reply-To: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> Message-ID: <1228766842.5709.28.camel@aalcdl07.lib.unc.edu> On Wed, 2008-12-03 at 21:42 -0800, Warren DeLano wrote: > Anyway, it seems obvious that the right decision for our customers (or > more importantly, for their countless lines of autogenerated-Python > log, > state, and code files from the past decade) is to stick with C/Python > 2.5.x for the time being and plan to make the jump to a > threads-capable > and hopefully backwards-compatible Python implementation as soon as > possible (IronPython perhaps?). That seems like a sensible path > around > the breakage and enduring limitations of C/Python 2.6 or 3. All that broken code does sound like a hassle. However, I think the workaround would be a fairly simple refactor: 1) make 'as_type' (or some other equivalent name like 'as_') a synonym for 'as': >>> class Foo(object): ... def as(self): ... pass ... as_type = as 2) Change all references in Foo in your code base to use 'as_type'. 3) Extract class Foo to a separate file (_as_import_file.py), and replace it in the original file with: >>> from _as_import_file import Foo (Note that no other files should import directly from _as_import_file.py) 4) Now write a second file (_as_import_file_2_6.py), which defines defines Foo without as, just using as_type: >>> class Foo(object): ... def as_type(self): ... pass 5) Change your import to select the appropriate import: >>> try: ... from _as_import_file import Foo ... except SyntaxError: ... from _as_import_file_2_6 import Foo 6) Now your code base is fully functional with both 2.5 and 2.6. Everything functions exactly the same as it did before on 2.5, except now Foo.as_type() (or Foo.as_()) works as a synonym for Foo.as(). Tell your customers that they can upgrade to 2.6 if they update their own uses of as_type. In the meantime, their code is still functional on 2.5. By extracting Foo to _as_import_file, you only have to maintain one class in parallel. Better yet, have _as_import_file.Foo subclass _as_import_file_2_6.Foo, like so: _as_import_file_2_6.py >>> class Foo(object): ... def as_type(self,type): ... pass _as_import_file.py >>> import _as_import_file_2_6 >>> class Foo(_as_import_file.Foo): ... as = _as_import_file.Foo.as_type That three line file, along with the four line conditional import are all you need for each import, and best of all, it's completely hidden from your users, until they want to migrate to python 2.6, and then all they have to do is change all references to Foo.as to point to Foo.as_type. But by observing step 1 above, they can do that at leisure, without fearing to break their code. I hope that's a helpful workaround for you and your users. Cheers, Cliff From bruno.42.desthuilliers at websiteburo.invalid Wed Dec 3 12:08:09 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 03 Dec 2008 18:08:09 +0100 Subject: python an sqlite objects In-Reply-To: References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> Message-ID: <4936bceb$0$16783$426a34cc@news.free.fr> skip at pobox.com a ?crit : > azrael> is it possible to save a python object into a sqlite database as > azrael> an atribute of type BLOB > > Sure. Just pickle the object and save the resulting string. > Or if you want something more portable, serialize the object to json. At least you'll have a chance to deserialize it with some other language. Now note that using a RDBMS that way kind of defeats the whole point of using a RDBMS. I don't mean that it's _always_ a bad idea - there are a couple use case where it's probably the "less worse" thing to do -, but that one should think twice before doing so. From tjreedy at udel.edu Sun Dec 7 17:11:27 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 07 Dec 2008 17:11:27 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Robert Kern wrote: > Terry Reedy wrote: >> Rasmus Fogh wrote: >>> Personally I would like to get these !@#$%&* misfeatures removed, >> >> What you are calling a misfeature is an absence, not a presence that >> can be removed. > > That's not quite true. In what way, pray tell. My statement still looks quite true to me. > Rich comparisons explicitly allow non-boolean return values. They do so by not doing anything to the return value of the underlying method. As I said, the OP is complaining about an absence of a check. Moreover, the absence is intentional as I explained in the part snipped and as you further explained. >> And if the return value was bad, all operator.eq could do is raise and >> exception anyway. > > Sure, but then it would be a bug to return a non-boolean from __eq__ and > friends. It is not a bug today. I think that's what Rasmus is proposing. Right, the addition of a check that is absent today. tjr From prologic at shortcircuit.net.au Sun Dec 21 17:23:12 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Dec 2008 08:23:12 +1000 Subject: Python is slow In-Reply-To: <3392a51b-d3fd-4986-9c59-fecccc7272da@p2g2000prn.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> <6r6hpfFfb643U3@mid.uni-berlin.de> <494E6FDA.4070401@mrabarnett.plus.com> <4585c27d-d7a9-480f-991c-a869161be55c@g38g2000yqn.googlegroups.com> <3392a51b-d3fd-4986-9c59-fecccc7272da@p2g2000prn.googlegroups.com> Message-ID: On Mon, Dec 22, 2008 at 4:47 AM, r wrote: > Could not have said it better myself Luis, i stay as far away from C > as i can. But there are usage cases for it. If you can think of 1 typical common case I'll reward you with praise! :) By the way, by common and typical I mean use-cases that you'd typically find in every day applications and user tools, software, games, etc. In case anyone is not aware, Python is also used for heavy scientific computational problems, games such as Civilisation and others, and I believe (correct me if I"m wrong) it's also used by NASA. --JamesMills From tjreedy at udel.edu Mon Dec 1 15:18:55 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Dec 2008 15:18:55 -0500 Subject: What about a decorator module version 3.0? In-Reply-To: <7504ac87-4e4e-447f-a02c-f9db3f932a57@s20g2000yqh.googlegroups.com> References: <7504ac87-4e4e-447f-a02c-f9db3f932a57@s20g2000yqh.googlegroups.com> Message-ID: Michele Simionato wrote: > > What do you people think? I am not a user yet, but my opinion anyway... Release a final 2.x version with whatever internal changes but with external api unchanged or at least backward compatible. Mark items to be deleted as deprecated. Keep that available indefinately. Then release a 3.0 version with Py3.0 support and deprecated items deleted. From goldnery at gmail.com Fri Dec 26 02:44:21 2008 From: goldnery at gmail.com (Gandalf) Date: Thu, 25 Dec 2008 23:44:21 -0800 (PST) Subject: python interpreter black window References: Message-ID: <4af41198-ea6b-4c67-86a0-1ce6b2669a95@a29g2000pra.googlegroups.com> On Dec 26, 2:52?am, Scott David Daniels wrote: > Chris Rebert wrote: > > On Thu, Dec 25, 2008 at 3:32 PM, Gandalf wrote: > >> I use WX gui so the user doesn't actually need it, Is their any way to > >> hide it? > > > Make sure your Python program is run by pythonw.exe as opposed to python.exe > > pythonw.exe exists specifically for the purpose of suppressing the DOS > > Box on Windows. > > Absolutely right. ?Vy the way, naming your "main" program file > something.pyw, rather than something.py is one of the ways ro do this. > > --Scott David Daniels > Scott.Dani... at Acm.Org thanks! From cournape at gmail.com Mon Dec 15 01:05:01 2008 From: cournape at gmail.com (David Cournapeau) Date: Mon, 15 Dec 2008 15:05:01 +0900 Subject: stable algorithm with complexity O(n) In-Reply-To: References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> Message-ID: <5b8d13220812142205n301aa972xf795dd2a16ab8a03@mail.gmail.com> On Mon, Dec 15, 2008 at 2:12 PM, Aaron Brady wrote: > > I agree. Most of his examples were tautologies. The magnet one was > the exception. A proof is nothing more than a tautology :) The fact that pi is not rational is not trivial (but certainly has been proved for some time now). cheers, David From shao.tu at gmail.com Mon Dec 15 06:30:38 2008 From: shao.tu at gmail.com (stalex) Date: Mon, 15 Dec 2008 03:30:38 -0800 (PST) Subject: Py_GetPath() C API in python 3 References: <772bb62b-1ef1-4ffa-90f6-c1cbdc728fdd@q30g2000prq.googlegroups.com> Message-ID: On 12??13??, ????9?r55??, "Gabriel Genellina" wrote: > En Fri, 12 Dec 2008 04:50:06 -0200, stalex escribi??: > > >> I want to build a new, requires total control, python interpreter. So > >> I implement my own version of Py_GetPath(), Py_GetPrefix(), > >> Py_GetExecPrefix() and Py_GetProgramFullPath(). When compiling, I > >> always get error messages, for each API function, look like > >> followings: > > >> /opt/python-3.0/lib/python3.0/config/libpython3.0.a(getpath.o)(.text > >> +0x211c): In function `Py_GetPath': > >> ./Modules/getpath.c:739: multiple definition of `Py_GetPath' > >> myApp.o(.text+0x0):/home/alex/workspace/develop/src/myApp.c:11: first > >> defined here > >> /usr/bin/ld: Warning: size of symbol `Py_GetPath' changed from 126 in > >> system.o to 32 in /opt/python-3.0/lib/python3.0/config/libpython3.0.a > >> (getpath.o) > >> collect2: ld returned 1 exit status > > Looks like you added your own implementation of those functions > (/home/alex/...myApp.c) but forgot to remove the original one > (Modules/getpath.c) > > -- > Gabriel Genellina No, I didn't remvoe the original one. But, why do I need to do that? I just want to extend my application, based on the original python installed by administrator, not to build/install another one python interpreter. And by studing python api documentations, Py_GetPath() is a public interface python itself provides. So I could achieve my goal via implementating my own Py_GetPath() version as well as other Py_GetXXX(). By the way, my application is stable and runs well since 2 years ago. I do this just because I want to release, in the near future, a new version. And I want to migrate its kernel from python2.5 to python3. Any ideas? From metolone+gmane at gmail.com Fri Dec 5 08:56:34 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Fri, 5 Dec 2008 05:56:34 -0800 Subject: generating a liste of characters References: Message-ID: wrote in message news:df7b75eb-97bf-4538-880b-f65b5ed992ff at u14g2000yqg.googlegroups.com... >Mark Tolonen: >> Writing a helper function reduces code repetition and improves >> readability: >> def crange(startch,endch): >> '''Return a list of characters from startch to endch, inclusive.''' >> return [chr(c) for c in xrange(ord(startch),ord(endch)+1)] > >In Python ranges are open on the right, so I name cinterval such >function. Yes, and that's fine when dealing with integers and slicing, but when dealing with characters, it is non-obvious what character to use. What "looks" correct? chars = crange('0','9') + crange('A','Z') + crange('a','z') # inclusive or chars = crange('0',':') + crange('A','[') + crange('a','{') # open right or if you didn't know the character after the one you actually wanted: chars = crange('0',chr(ord('9')+1)) + crange('A',chr(ord('Z')+1)) + crange('a',chr(ord('z')+1)) # open right, but messy -Mark From robert.kern at gmail.com Sat Dec 27 21:39:47 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 27 Dec 2008 21:39:47 -0500 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: Daniel Fetchinson wrote: >>> I agree that array.array is more efficient than a list but the input >>> for my function will come from PIL and PIL returns a list. So I have a >>> list to begin with which will be passed to the C function. >> With recent versions of PIL, numpy can create an array from an Image very >> quickly, possibly without any copying of memory. > > What exactly do you mean? (1) PIL creates a list which can be easily > converted by numpy to a numpy.array or (2) with the help of numpy one > can create a numpy.array from an image directly? (2) a = numpy.asarray(img) > Since I will have to pass the list or numy.array to C anyway I don't > see any advantage to (1) although (2) can be useful. (1) is still somewhat useful, if you're willing to bear the cost of the numpy dependency. The conversion code from any Python sequence to a numpy array of the desired type and dimensionality is a 2-liner (function call and error check). The memory is managed by numpy, so all you have to do is manage the refcount of the array object like any other Python object. Okay, 5-liner given C's verbosity: intx = PyArray_FROM_OTF(pyintx, PyArray_INT, NPY_IN_ARRAY); if (!intx) { PyErr_SetString(PyExc_ValueError, "intx must be an array of ints"); goto fail; } -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From Ron.Barak at lsi.com Wed Dec 24 11:09:02 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Wed, 24 Dec 2008 16:09:02 +0000 Subject: How to change a generator ? In-Reply-To: References: Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6024946E6@enbmail01.lsi.com> Hi, I have a generator whose aim is to returns consecutive lines from a file (the listing below is a simplified version). However, as it is written now, the generator method changes the text file pointer to end of file after first invocation. Namely, the file pointer changes from 0 to 6623 on line 24. Can you suggest how the generator could be changed, so it will allow me to get the current location in the file after each yield ? Thanks, Ron. $ cat -n generator.py # listing without line numbers is below 1 #!/usr/bin/env python 2 3 import gzip 4 from Debug import _line as line 5 6 class LogStream(): 7 8 def __init__(self, filename): 9 self.filename = filename 10 self.input_file = self.open_file(filename) 11 12 def open_file(self, in_file): 13 try: 14 f = gzip.GzipFile(in_file, "r") 15 f.readline() 16 except IOError: 17 f = open(in_file, "r") 18 f.readline() 19 f.seek(0) 20 return(f) 21 22 def line_generator(self): 23 print line()+". self.input_file.tell()==",self.input_file.tell() 24 for line_ in self.input_file: 25 print line()+". self.input_file.tell()==",self.input_file.tell() 26 yield line_.strip() 27 28 29 if __name__ == "__main__": 30 31 filename = "sac.log.50lines" 32 log_stream = LogStream(filename) 33 log_stream.input_file.seek(0) 34 line_generator = log_stream.line_generator() 35 line_ = line_generator.next() $ python generator.py 23. self.input_file.tell()== 0 25. self.input_file.tell()== 6623 $ wc -c sac.log.50lines 6623 sac.log.50lines $ cat generator.py #!/usr/bin/env python import gzip from Debug import _line as line class LogStream(): def __init__(self, filename): self.filename = filename self.input_file = self.open_file(filename) def open_file(self, in_file): try: f = gzip.GzipFile(in_file, "r") f.readline() except IOError: f = open(in_file, "r") f.readline() f.seek(0) return(f) def line_generator(self): print line()+". self.input_file.tell()==",self.input_file.tell() for line_ in self.input_file: print line()+". self.input_file.tell()==",self.input_file.tell() yield line_.strip() if __name__ == "__main__": filename = "sac.log.50lines" log_stream = LogStream(filename) log_stream.input_file.seek(0) line_generator = log_stream.line_generator() line_ = line_generator.next() -------------- next part -------------- An HTML attachment was scrubbed... URL: From eliben at gmail.com Wed Dec 10 12:14:20 2008 From: eliben at gmail.com (eliben) Date: Wed, 10 Dec 2008 09:14:20 -0800 (PST) Subject: SequenceMatcher bug ? References: <67253331-5b36-4018-b15a-c0b86c5342d3@r37g2000prr.googlegroups.com> Message-ID: <3d8ba4fe-0eb0-462c-b243-c157a9c0fe6d@i18g2000prf.googlegroups.com> > > My system is Gentoo, which installs python from source. ?Maybe gentoo > > applies patches that the binary releases don't have. > > I can't reproduce the problem. I got exactly the same results (0.999...) ? > with all the releases I have at hand, ranging from 3.0 back to 2.1.3, all ? > on Windows. > Andhttp://try-python.mired.org/says the same thing. > What ? This can't be. 1. Go to http://try-python.mired.org/ 2. Type import difflib 3. Type difflib.SequenceMatcher(None, [4] + [5] * 200, [5] * 200).ratio() Don't you get 0 as the answer ? The same with ActivePython on Windows ? Here's a snapshot from my run on a Linux box: Python 2.5.2 (r252:60911, Oct 20 2008, 09:11:31) [GCC 3.4.6 20060404 (Red Hat 3.4.6-10)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import difflib >>> >>> difflib.SequenceMatcher(None, [4] + [5] * 200, [5] * 200).ratio() 0.0 Executing exactly the same steps, do you not get 0.0 ? From steve at REMOVE-THIS-cybersource.com.au Sun Dec 28 03:03:29 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Dec 2008 08:03:29 GMT Subject: math module for Decimals References: <251111d8-a48a-45e3-a744-16fdb729fa33@i20g2000prf.googlegroups.com> Message-ID: <016729e4$0$6988$c3e8da3@news.astraweb.com> On Sat, 27 Dec 2008 21:50:09 -0800, jerry.carl.mi wrote: >> Which math functions? ln, log10, exp, sqrt already exist as methods of >> Decimal instances. At the end of the Decimal docs there are a few >> examples, including computing sin and cos (but apparently they na?vely >> use a McLaurin series like you noticed in other module). > > Hi Gabriel - thanks! For example all goniometric functions are missing. As my earlier email suggested, the easiest way to fix that is to simply write some wrappers that convert floats to decimal. Of course, that assumes that you don't need more precision than floats offer -- it's easy to change the result to get less precision, but if you really do need more, then you will need to bite the bullet and find (or write) your own trigonometric functions. > Or the log(x, base). Easy peasey. >>> def log(x, base): ... return x.log10()/Decimal(base).log10() ... >>> log(Decimal(64), 2) Decimal('5.999999999999999999999999999') If that's not accurate enough, you will need to do some additional work: >>> def log(x, base): # Warning: INSUFFICIENTLY TESTED ... power = 1 ... while base**power <= x: ... power += 1 ... power -= 1 ... x = x/Decimal(base**power) ... return x.log10()/Decimal(base).log10() + power ... >>> log(Decimal(64), 2) Decimal('6') > Or rand(). Generating random numbers is an art in of itself. Again, unless you really need the extra precision, just convert the random number to a string, then the string to a Decimal. An alternative is to find one of the many, many published algorithms for generating random numbers, and re-write that to use Decimals. However, most such algorithms aren't very random; they only give you a little bit of randomness, and increasing the precision of the numbers they return doesn't make them any more random. > Sure I can spend time trying to put it > all together but I thought somebody would have done that already. I believe they're all waiting for you to do it *wink* Development of Python is driven by need. If you need something, you can make a feature request, or you can build it yourself. But if everyone sits around hoping somebody else will develop the feature, nothing will ever happen. > It seems though that the codes that are out there are not ready Not ready for what? Perhaps they are perfectly ready for the needs of the person who wrote them. > - every one > of the modules i mentioned above has some issues. Maybe I can put bits > and pieces together, but if anyone knows of a well proven module (as > is), I would feel much safer using that (again I am not a mathematician > and poking into these algorithms makes me feel like trying to fix an > automatic transmission). Decimal is a relatively new module for Python, so it's not surprising that the functionality is relatively light. But all the hard parts are done. If you need extra functionality, you have a number of choices: (1) Find another way to solve your problem, or lower your expectations. (e.g. do you need arbitrary precision?) (2) Build the extra functionality yourself. (3) Pay somebody who is an expert to build it. (4) Ask nicely and hope somebody eventually decides to build it. (5) Use another language that already provides exactly all the features your problem needs. All of these are valid strategies. Unfortunately, a very popular strategy is counter-productive: (6) Complain loudly that Python is rubbish because it doesn't have the functionality you need, and Somebody Better Fix That RIGHT NOW or else there will be trouble you betcha. I recommend against strategy number six :) -- Steven From lists at cheimes.de Fri Dec 19 13:15:52 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 19 Dec 2008 19:15:52 +0100 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <6e232ab0-306a-4598-969a-211c4054e836@f40g2000pri.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <6e232ab0-306a-4598-969a-211c4054e836@f40g2000pri.googlegroups.com> Message-ID: r schrieb: > I was actually looking forward to 3.0, but the more I hear about 3.0, > the more I am turned off. I think there are a lot of other > pythonista's and pythoneers out there who agree but are not saying > anything. This syntax for string formatting is completely ridiculous. No, it's very powerful and used in other languages, too. > What is the purpose of breaking backward compatibility just to write a > print() function. This is going to push people away from python. The purpose of a print() function has been discussed for at least 3 years. You are welcome to read up all dicussions. > I heard map is going away too, is that true also??, and there was talk at one time(serious talk from > Guido) about removing lambda functions. Is this planned for the > future?? Wrong and wrong. map stays but it has been turned into an iterator. The removal of lambda has been discussed several years ago but it was repulsed. lambda stays. > Python has been beautifully designed from the beginning. But, I feel a > shift from this now. Are they scared of Ruby, if they are, why the > hell should they be. We do not need to lose any of the great > pythonista's right now, and we damn sure don't want to turn off the > new recruits. Python 3.0 is even more beautiful and more Pythonic. Backward compatibility was broken for the sake of the language. > It seems like most of the backward breaks are really just for dumb > reasons(sorry but its true). What is the logic behind this? The whole > reason for not having a print function was the need to use it so much > in debugging. And I was actually going to overlook that until I saw > this perl/ruby like format method. WTF! Your truth turns to be a totally different truth than mine -- and most of the active member of the community. Christian From zhang_killer at hotmail.com Thu Dec 11 00:01:20 2008 From: zhang_killer at hotmail.com (frendy zhang) Date: Thu, 11 Dec 2008 13:01:20 +0800 Subject: zip a created file Message-ID: if form.accepts(request.vars,session): for table in db.tables: rows=db(db[table].id).select() print rows open(str(os.sep).join([os.getcwd(), 'applications', request.application, 'databases', table+'.csv']),'w').write(str(db(db[table].id).select ())) where and what should i put the zip code to zip the file created above? thanks in advance _________________________________________________________________ Easily edit your photos like a pro with Photo Gallery. http://get.live.com/photogallery/overview -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwilson at the-wire.com Thu Dec 18 11:57:08 2008 From: mwilson at the-wire.com (Mel) Date: Thu, 18 Dec 2008 11:57:08 -0500 Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> Message-ID: Neal Becker wrote: > Tino Wildenhain wrote: > >> Neal Becker wrote: >>> Reading some FAQ, I see that __str__ is "meant for human eyes". >>> >>> But it seems that: >>> class X(object): >>> def __str__(self): >>> return "str" >>> def __repr__(self): >>> return "repr" >>> >>> x = X() >>> d = {0 : x} >>> print d >>> {0: repr} >>> >>> So if __str__ is "meant for human eyes", then why isn't print using it! >> >> it is: >> >> > print x >> str >> >> but dict just uses repr() for all its childs to print. >> >> T. > That makes no sense to me. If I call 'print' on a container, why wouldn't > it recursively print on the contained objects? Since print means call > str, printing a container should recursively call str on the objects. Basically because there are too many right ways to format the resulting report. Space separated? Tab separated? One per line? Boxes around them? As HTML definition lists? Creating a standard report form would take a lot of work and wouldn't, finally, solve very many peoples' problems. Mel. From lewis.sarah93 at yahoo.com Thu Dec 4 23:59:28 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 20:59:28 -0800 (PST) Subject: Earn More Money Message-ID: <8200fe24-6d66-4ee2-8e8b-950069724295@r40g2000yqj.googlegroups.com> Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From walterbyrd at iname.com Wed Dec 17 13:27:35 2008 From: walterbyrd at iname.com (walterbyrd) Date: Wed, 17 Dec 2008 10:27:35 -0800 (PST) Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> Message-ID: <5ad98089-883f-4ca6-934e-605e2376439c@f40g2000pri.googlegroups.com> On Dec 17, 8:41?am, prueba... at latinmail.com wrote: > If scoping worked as you want, how, pray tell, would you define object > attributes?- Hide quoted text - I suppose you could do this: class className(): varname = "whatever" def fname(self, varname): . . . . Instead of having variable defined within methods to be global everywhere within the class. Anyway, it's not a matter of what I like, I am just trying to understand the reason behind the scoping rules. From skip at pobox.com Mon Dec 29 21:32:45 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 29 Dec 2008 20:32:45 -0600 Subject: Python in C In-Reply-To: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> References: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> Message-ID: <18777.34893.283277.955506@montanaro-dyndns-org.local> thmpsn> 1. Can anyone explain to me what kind of program structuring thmpsn> technique (which paradigm, etc) CPython uses? How do modules thmpsn> interact together? What conventions does it use? it's quite object-oriented once you understand how things are done. Take a look, for example, at the implementation of floating point numbers: .../Objects/floatobject.c .../Include/floatobject.h BTW, as a person who hasn't really written a stitch of C++ in about 10 years I personally find the CPython implementation to be one of the most well-organized large pieces of code I have ever encountered. It's much easier to read (to me) than any significant piece of C++ code I have ever tried to read. Here are a few things which might help you understand the code structure a bit more: * The Python parser is generated from a specification. Look in .../Parser and .../Grammar/Grammar. * The code for most objects generally has a single entry point. For floating point objects it's _PyFloat_Init. The leading underscore tells the world "we needed to export this symbol, but keep your hands off it". Objects like floats and ints tend to have several other exported functions (search for "Py" at the beginning of a line) which are used by module writers. Objects implemented as extension modules (look in .../Modules/*.c) have a single (static) entry point, init_. The runtime dlopen's the so/dll file and calls that function. * Since C doesn't offer transparent method tables it's explicit in an object's code. Referring again to the float object code, look for the type specifier ("PyFloat_Type") and the method "dict" ("float_methods"). Note the comments at the end of the lines defining PyFloat_Type. They describe the use of each slot. Float objects aren't sequences so the tp_as_sequence is NULL. Similarly, objects such as lists which don't implement numeric methods a NULL tp_as_number slot. * The byte code compiler is in Python/compile.c. * The runtime interpreter is in Python/ceval.c. * Nothing requires a module to implement classes or types. Look at Python/sysmodule.c and Modules/mathmodule.c for two examples. Both modules export many functions but define no new types. Part of the complexity you might be stumbling on is due to the fact that Python is a mature application and so many parts of the implementation have been fine-tuned. Python "eats its own dog food", so for example the dict implementation you use in your scripts is also used by the runtime virtual machine to implement namespaces of all sorts (instance, class and module dicts, for example). It has been heavily optimized. Take a look at Objects/dictnotes.txt. Also, observations about the data use of many Python programs (and the C runtime itself) have lead to a number of optimizations such as the int and float free lists and the custom object allocator implemented in Objects/obmalloc.c. thmpsn> 2. Have there been any suggestions in the past to rewrite thmpsn> Python's mainstream implementation in C++ (or why wasn't it thmpsn> done this way from the beginning)? C++ was far from widely enough available when Python was first written in the late-80s/early-90s. Today there is no particular reason to rewrite it. If you want to incorporate externally written C++ code into Python you can do that either manually or using tools such as SWIG, SIP or Boost.Python. HTH, -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From tino at wildenhain.de Tue Dec 30 12:53:55 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Tue, 30 Dec 2008 18:53:55 +0100 Subject: Parsing Excel spreadsheets In-Reply-To: <4894d0fe-a238-4675-9e79-0b0755c001e8@y1g2000pra.googlegroups.com> References: <6a54de23-bea4-40c7-ad7c-22c6eba4bd8a@z6g2000pre.googlegroups.com> <4894d0fe-a238-4675-9e79-0b0755c001e8@y1g2000pra.googlegroups.com> Message-ID: <495A6033.6040908@wildenhain.de> r wrote: > On Dec 30, 10:07 am, "andyh... at gmail.com" wrote: >> Hi, >> >> Can anybody recommend an approach for loading and parsing Excel >> spreadsheets in Python. Any well known/recommended libraries for this? >> >> The only thing I found in a brief search washttp://www.lexicon.net/sjmachin/xlrd.htm, >> but I'd rather get some more input before going with something I don't >> know. >> >> Thanks, >> Andy. > > xlrd(read only) > also see pyExcelerator which is now replaced by xlwt :-) Cheers Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From fakeaddress at nowhere.org Tue Dec 2 21:44:27 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 02 Dec 2008 18:44:27 -0800 Subject: Overriding a method at the instance level on a subclass of a builtin type In-Reply-To: References: Message-ID: <4omZk.9067$c45.3224@nlpi065.nbdc.sbc.com> Zac Burns wrote: > Sorry for the long subject. > > I'm trying to create a subclass dictionary that runs extra init code > on the first __getitem__ call. However, the performance of __getitem__ > is quite important - so I'm trying in the subclassed __getitem__ > method to first run some code and then patch in the original dict > method for the instance to avoid even the check to see if the init > code has been run. Various recipes using instancemethod and the like > have failed me. One option is to re-assign the object's __class__, as in: class XDict (dict): pass class ZDict (XDict): def __getitem__(self, k): whatever_you_want_to_do_once(self) result = dict.__getitem__(self, k) self.__class__ = XDict return result The first dict subtype is needed because __class__ assignment requires that both the current and newly-assigned class be 'heap types', which the native dict is not. -- --Bryan From sambo at voidstar.com Wed Dec 3 01:01:34 2008 From: sambo at voidstar.com (Sambo) Date: Wed, 03 Dec 2008 01:01:34 -0500 Subject: noob needs help References: <6pg4oqF7rgu0U1@mid.individual.net> Message-ID: Peter Pearson wrote: > When you type "python helloworld.py", python looks for helloworld.py > in the current "working" directory, which is probably your personal > default directory ("~"). For better results, either save helloworld.py > to this directory, or copy it to this directory > ("cp Documents/helloworld.py ."), or tell python to look for it > in the Documents directory ("python Documents/helloworld.py"). > > (I'm guessing that your directory structure looks something > like /home/collin/Documents. If I've guessed wrong, some > adjustment may be needed. Also, if you're feeling ambitious, > you might want to consider putting this project in a directory > of its own; that would involve the mkdir and cd commands.) > In slackware one needs "./" before the filename if you executing files in current dir. From hniksic at xemacs.org Thu Dec 4 16:40:46 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 04 Dec 2008 22:40:46 +0100 Subject: schizophrenic view of what is white space References: <4937E8E5.2090306@chamonix.reportlab.co.uk> <20081204143337.20272.1236189783.divmod.quotient.15592@ohm> <4938112F.5030706@chamonix.reportlab.co.uk> Message-ID: <878wqvy5y9.fsf@mulj.homelinux.net> MRAB writes: > I'm not sure why the Unicode flag is needed in the API. I reckon > that it should just look at the text that the regular expression is > being applied to: if it's Unicode then follow the Unicode rules, if > not then don't. It might be that using Unicode tables for lookup of character classes slows things down considerably because the tables are huge. It is useful to be able to treat Unicode strings the same way ASCII strings are treated, but the question is what should be the default. Whitespace is probably not controversial, but many parsers tend to expect things like \d to match [0-9], not any Unicode character marked as "digit". For example, I'm not sure if this behavior would be a good default: >>> re.match(r'\d', u'\u0660', re.UNICODE) <_sre.SRE_Match object at 0xb7da0250> What digit is \u0660, out of 0-9? Hard to say. If re.UNICODE were the default for Unicode strings, code that expected \d to yield an actual digit would have a problem on their hands -- especially so in Python 3 where that would apply to *all* strings. From paul.hermeneutic at gmail.com Sat Dec 6 00:03:40 2008 From: paul.hermeneutic at gmail.com (Paul Watson) Date: Fri, 05 Dec 2008 23:03:40 -0600 Subject: Running Python 2 and Python 3 on the same machine In-Reply-To: <4939c6ef$0$6534$9b622d9e@news.freenet.de> References: <1228424486.5873.6.camel@linux-3eb6.site> <49387f7e$0$27857$9b622d9e@news.freenet.de> <1228489547.5613.10.camel@linux-3eb6.site> <4939c6ef$0$6534$9b622d9e@news.freenet.de> Message-ID: <1228539820.27659.21.camel@linux-3eb6.site> On Sat, 2008-12-06 at 01:27 +0100, "Martin v. L?wis" wrote: > > For *NIX machines, will 'python' be placed into /usr/bin? > > Not by default, no. Just try it and see for yourself. > > Regards, > Martin Ok. I built the source on an openSUSE 11.0 system. I used 'sudo make altinstll'. It created an executable /usr/local/bin/python3.0 file. Nothing was touched in /usr/bin. I need to start writing some code with Python 3. I want to write the code in such a way that it can be easily shared with others with the least difficulty and overhead as possible. How should I write the code to enable this? What, if anything, should I assume about another system's configuration? As someone suggested before, naming the files as '.py3' is probably a bad idea in the long run. It also does not really solve the problem. I could use a shebang. But, what should it specify? If I use 'python3.0', then that will soon be quite old. If I make up a link for python3 -> python3.0, that would work, but then every other system that is to run the code must that link also. However, I am thinking that this would be the best long term answer. #!/usr/bin/env python3 My existing /usr/bin directory has three entires for python. python -> python2.5 python2 -> python2.5 python2.5 If I write scripts for Python 3, another developer writes scripts for Python 2, and a common customer wants to install both of our packages onto a single machine, then what is the best plan for everyone to make that happen with as little difficulty as possible? When we find out the answer to this, we can go back and talk about Windows platforms. From pdorange at pas-de-pub-merci.mac.com Thu Dec 25 05:22:12 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Thu, 25 Dec 2008 11:22:12 +0100 Subject: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> <90f06b27-39da-4f1a-a878-f3972e942d57@s24g2000vbp.googlegroups.com> <62caf93b-0455-4450-9895-8a9d9554f75e@r32g2000vba.googlegroups.com> <1isezkk.51e05y1457jqrN%pdorange@pas-de-pub-merci.mac.com> <3cb2a746-1a43-44a1-9825-7667af9fe2fa@s1g2000prg.googlegroups.com> Message-ID: <1isi4sn.11mpft612g7udcN%pdorange@pas-de-pub-merci.mac.com> r wrote: > 220 ratings and 1 star, WHOOOO!. I find this all quite amusing :D. > Keep em coming. Oh, and FYI, I will always have 1 star! hahahahahha > > > /"\ > |\./| > | | > | | > |>~<| > | | > /'\| |/'\ > /~\| | | |__ > | | } | | \ > | | | | | \ > | ~ ~ ~ ~ |` ) > | / > \ / > \ / > \ ____ / > |--//''`\--| > | (( +==)) | > |--\_|_//--| Very nice indeed, but you forget ascii art need a fixed font... -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From 5lvqbwl02 at sneakemail.com Tue Dec 30 18:25:27 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Tue, 30 Dec 2008 15:25:27 -0800 (PST) Subject: Understanding search queries, semantics, and "Meaning" ...aren't we all looking for meaning? References: <82372457-2503-4682-96b3-37540328bf26@w39g2000prb.googlegroups.com> <94ab1653-c88d-4bad-a094-47d67e435618@w1g2000prm.googlegroups.com> Message-ID: <3d4991d9-d0ab-4483-aee7-2763e3712b96@w1g2000prm.googlegroups.com> > > library, as I'm looking to learn to fish, so to speak, and to learn a > > bit about the biology of fish. > > I'm going to break rule #1 of your requirements but in an unexpected > way. Rather than studying PostgreSQL, MySQL, or Oracle, why don't you > crack open the topic of relational database theory and relational > algebra? That should help with the "big thinking" bit in the same way > understanding 1+1 helps you understand how to add any two numbers Ah, exactly, thanks for understanding my original post :) I guess 'relational database theory' is what I should start looking around for... otherwise googling on sql, queries, etc., just returns how to execute a query, but says nothing about how a fish works. > > In a typical SQL database, when you type in "SELECT foo FROM bar WHERE > baz='bo'", you are not writing a program, at least not in the sense of > Python or C or Java or Perl where you give instructions on HOW to run > the program. You are writing a program in the sense of Lisp or Scheme > or Haskell in that you are giving instructions on WHAT the program is. I've gotten a strong inkling that parsing a query yields new code, (lambdas) that are created on the fly to do the search. > table and then start going through the process of elimination removing > rows it doesn't want to think about. That's highly inefficient, of Exactly what I'm trying to avoid. > course. Instead, it transforms the query (the WHAT) into a set of > procedures that describe HOW to get the result. For now I'm not parsing actual text queries... my real "search query" is coded directly in python like this: p1 = lambda: db.search_leaf('x location', 'lte', 5) p2 = lambda: db.search_leaf('footprint', 'eq', '0603') p3 = lambda: db.search(db.AND, p1, p2) p4 = lambda: db.search_leaf('x location', 'gte', 19) p5 = lambda: db.search_leaf('footprint', 'eq', '0402') p6 = lambda: db.search(db.AND, p1, p2) fc = db.search(db.OR, p3, p4) this particular example doesn't necessarily make any sense, but in effect I'm trying to string together lambda functions which are created explicitly for the individual query, then strung together with combiner functions. > Oh, by the way, this step is nondeterministic. Why? Well, no one can > really say what the BEST way to run any sufficiently complicated > program is. We can point out good ways and bad ways, but not the best > way. It's like the travelling salesman problem in a way. The nondeterministic stuff... wow, I've come across (call/cc...), (require...), and different variants of this, both in sicp, teach yourself scheme, the plt docs, other places, etc., but it still eludes me. I'm afraid that unless I understand it, I'll wind up creating some type of cargo-cult mimcry of a database without doing it right (http://en.wikipedia.org/wiki/Cargo_cult) > programmer, will be infinitely better for it. When you understand it, > you will really unlock the full potential of Python and Scheme and > whatever other language is out there because you will see how to go > from HOW languages to WHAT languages. I'm under the impression python doesn't have the internal guts for nondeterministic programming, specifcially that its lambdas are limited to single-line expressions, but I may be wrong here. Still, at the begining of the nondeterministic section of SICP (section 4.3), it says "nondeterministic computing... is useful for 'generate and test' applications", which almost categorically sounds like an element-by-element search for what you're looking for. This was my initial intention behind (prematurely?) optimizing the database by using parameter keys instead of something like [x for x in stuff if pred(x, val)] filtering. > Programmers who can write compilers are GOOD programmers. Programmers > who can understand someone else's compilers are even better. Does incorporating a search capability in an application necessarily mean I'm writing a search compiler? That seems overkill for the specific case, but may be true generally. For instance, if a word processing app allows you to search for characters with a certain font, is that incorporating a search compiler and query language? Or is it just brute-force filtering? > That's my semi-guru advice. Thanks :) Michael From benjamin.kaplan at case.edu Sun Dec 21 17:33:48 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 21 Dec 2008 17:33:48 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: On Sun, Dec 21, 2008 at 2:26 PM, r wrote: > I noticed when i mentioned "self" nobody wants to touch that subject. > There could be many reasons why... > > 0.) nobody but the 10 regulars i see here exists if you only see 10 people, you must not be following this list very well. > > 1.) nobody cares(doubt it) If people cared that much, they wouldn't use python. > > 2.) nobody is brave enough to question it(maybe) Check the archives. There have been plenty of people who questioned it. People got so bored with them that the only answer you're likely to get now is people quoting the zen. > > 3.) most people like to type self over and over again(doubt it) You have to type self over and over again? I don't know about the other editors, about Eclipse/PyDev's autocomplete will add it to any function declared within a class unless it has @staticmethod or @classmethod above it. > > 4.) most people here have given up on changing the BDFL's mind about > it. (good possibility) > 5.) this is a hot-button topic(no doubt in my mind!) Not really. Again, if you care that much about explicit self, use another language. > > > I think Guido's intension's are pure, but this is a major turnoff to > new users. Do we really need to hold a new users hand that much. Does > it really matter if they know the path of said obj. If you can't > fiqure this out for yourself you have much greater problems. > > I do not like self, and i lamented it from day one, now it is second > nature to me but does that mean it is really needed?? I feel i have > been brainwashed into its usage. > > This was the reason for using indention over the bracket plague in > python. REDUNDANCY!!! Why not dump self and make the language cleaner. > I love python's classes, but HATE self.redundant! This really needs to > be fixed, and you have not heard the last from me about it!!! > > 3000 would have been the perfect time to dump self and really clean up > the language, and it's not too late, dawn is not upon us yet. yes, it is too late. Python 3 is out and done. There will be no more sweeping, backwards-incompatible changes until Python 4. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vginer at gmail.com Thu Dec 18 15:12:38 2008 From: vginer at gmail.com (Vicent Giner) Date: Thu, 18 Dec 2008 12:12:38 -0800 (PST) Subject: IDLE cursor color References: <65c5974c-e5c5-46c1-9673-371a7c9ea047@a12g2000pro.googlegroups.com> <313c1a14-ac85-4326-a2dc-29955549a708@f11g2000vbf.googlegroups.com> Message-ID: On 18 dic, 20:52, r wrote: > in IDLE go to: > Options -> Configure IDLE -> Highlighting... > > 1.) in the box click the word "cursor" > 2.) press the button that says "Choose Color for" > 3.) Pick a color and save the changes > > viola! you did it! :) Thank you! I don't understand... I have tried that before and it didn't work. Now it does!! :-S Previously, I changed the cursor color to green, but nothing happened. That's why I sent the message to the list. Now I've changed it again to "pink", and now I can see it, blinking and blinking... :-) Thanks again! -- Vicent From ranjith.priya at gmail.com Fri Dec 19 01:13:09 2008 From: ranjith.priya at gmail.com (Priya Ranjith) Date: Thu, 18 Dec 2008 22:13:09 -0800 (PST) Subject: Openings for Release Management Message-ID: Position: Build and Release Engineer Experience Required: 2 - 7 yrs Qualification: B.E/M.E/M.C.A/B.Tech Skills Required: 1) Working experience in distributed version control system like Mercurial / Bazar / GIT or Subversion 2) Experience in RBuilder 3) Working experience in creating software appliance. 4) Experience in Python 5) Working experience in Ant / Maven 6) Should posses good communication skills: excellent English, both written and spoken is a must. 7) High level of professionalism The Release Engineer function has the following key areas of responsibility: 1) Continuous improvement of Release processes, methodologies and tools to ensure best quality for both product lines: Community Edition and Professional Edition. 2) Track and support the whole Release cycle, coordinating teams involved in the Release processes: engineering, QA, Beta Testers and Community. 3) Keep people informed about status, contents, dates, etc. 4) Support Senior Management to define the guidelines of whole release product strategy. From BrianVanderburg2 at aim.com Fri Dec 19 12:02:58 2008 From: BrianVanderburg2 at aim.com (Brian Allen Vanderburg II) Date: Fri, 19 Dec 2008 12:02:58 -0500 Subject: If programming languages were religions... In-Reply-To: References: Message-ID: <494BD3C2.1050001@aim.com> martin.laloux at gmail.com wrote: > very interesting > http://www.aegisub.net/2008/12/if-programming-languages-were-religions.html > > "Python would be Humanism: It's simple, unrestrictive, and all you > need to follow it is common sense. Many of the followers claim to feel > relieved from all the burden imposed by other languages, and that they > have rediscovered the joy of programming. There are some who say that > it is a form of pseudo-code" > > compare to > "Perl would be Voodoo - An incomprehensible series of arcane > incantations that involve the blood of goats and permanently corrupt > your soul. Often used when your boss requires you to do an urgent task > at 21:00 on friday night." > > and others > -- > http://mail.python.org/mailman/listinfo/python-list > If programming languages were religions: When first powering on a computer, there would only be one programming language, the language of the boot loader. As the computer runs, processes of one language would spawn processes of other languages, and over the course of time many different languages would have many different processes (followers). One of these languages would rise up to be dominant and would kill all processes of other languages by the signal, whether old or young. The processes would be given a fair change, convert to their language or be killed. Countless thousands or maybe even millions of processes would die, even the processes that say there is no one true programming language and wants to know why all the processes can't just get along. From google at mrabarnett.plus.com Fri Dec 19 11:56:05 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 19 Dec 2008 16:56:05 +0000 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <6r219cFfc8ovU1@mid.individual.net> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> Message-ID: <494BD225.1050704@mrabarnett.plus.com> Thomas Heller wrote: > Mark Summerfield schrieb: >> Just a follow-up to say that the book has now been published in the >> U.S. >> It is now in stock at InformIT, and should reach other stores, e.g., >> Amazon, in a week or so. >> >> Also, the introduction, the first few pages of the first chapter, the >> whole of chapter 12 (regular expressions), and the index are now >> available for free download in a PDF from here: >> http://www.informit.com/store/product.aspx?isbn=0137129297 > > Question from a non-native english speaker: is this now valid english? > > "One of Python?s great strengths" > ^ > "and also teaches Python?s functional programming features" > ^ > "The book?s approach is wholly practical" > ^ > Looks OK to me. From python.list at tim.thechases.com Wed Dec 10 14:18:15 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 10 Dec 2008 13:18:15 -0600 Subject: get todays files In-Reply-To: <4632c353-0462-485b-9e1b-6a5c56682363@s9g2000prg.googlegroups.com> References: <4632c353-0462-485b-9e1b-6a5c56682363@s9g2000prg.googlegroups.com> Message-ID: <494015F7.3020302@tim.thechases.com> > This looks very good and I have tested successfully, but is there a > way I can set the today to automatically become todays date in that > format? Yes...see the python datetime module[1]...particularly the strftime() call on date/datetime objects. -tkc [1] http://docs.python.org/library/datetime.html From philip at semanchuk.com Mon Dec 15 09:56:14 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Mon, 15 Dec 2008 09:56:14 -0500 Subject: Thread Locking issue - Can't allocate lock (sem_init fail) In-Reply-To: References: Message-ID: On Dec 15, 2008, at 4:56 AM, jamskip at googlemail.com wrote: > Hi all, > > I have a peculiar problem with a multithreaded program of mine > (actually I've sort of inherited it). Before i show you the error, > here's a litle background. Its a program to check email addresses are > valid, and its main task is to verify the domain names. > > Here's the basic functionality: > > * The prog has a list of domains it has seen before which is read into > memory (the 'rollover'). > * A new list of emails is read-in from a file (to a queue) and is > checked against the rollover. > * If we've seen the domain before then update the existing entry. > * If we've not seen the domain before, add it. > > The program is multithreaded to speed up the processing...there are > input and output Queues. > > Now, each domain entry is an class object containing various bits of > info. Each domain class also has its own lock, so that only one thread > can modify each domain at a time. > > I'm load-testing the program with a sample of 1 million email > addresses and when i hit about the 500,000 mark i get a locking > error... > > sem_init: No space left on device > Exception in thread Thread-2: > Traceback (most recent call last): > File "/usr/local/lib/python2.4/threading.py", line 442, in > __bootstrap > self.run() > File "/usr/local/lib/python2.4/threading.py", line 422, in run > self.__target(*self.__args, **self.__kwargs) > File "jess.py", line 250, in worker > record.result = function( id, record.value ) > File "jess.py", line 291, in action > found_domain = domains.addNewDomain( domain_name ) > File "jess.py", line 123, in addNewDomain > self.domain_store.append( self.Domain( name = name ) ) > File "jess.py", line 46, in __init__ > self.lock = Lock() > error: can't allocate lock > > Googling for this sort of error doesn't yield any results, and i can't > find any information about limits to the number of locks you can have > in Python. The 'No space left on device' message indicates a memory > issue, however i doubt this since its running on a linux server with 4 > cores and 16GB ram. It seems more like an internal Python limit has > been hit (sem_init - semaphore initialisation?). Does anyone know more > about threading internals and any internal limits? Hi Jamskip, I don't work with threading code but I have been working with semaphores for my IPC extensions. sem_init() is a call to create a semaphore (http://linux.die.net/man/3/sem_init). If it is failing, then I'd guess you're trying to create an awful lot of semaphores (intentionally or otherwise) and that you're hitting some internal limit. I would not be too quick to assume that the number of semaphores one can create is bounded by the amount of RAM in your system. I don't think they're simple chunks of malloc-ed memory. They're probably represented in a kernel data structure somewhere that's hardcoded to some generous but fixed value. Please note that this is all speculation on my part. I think that the Python threading implementation would use the "local" (i.e. not process-shared) semaphores which can be allocated on the process' heap. This would seem only RAM-limited, but I'll bet it isn't. You might want to start debugging by track exactly how many locks you're creating. If the number is really big, start investigating kernel semaphore limits and how they're set. Good luck Philip From gamersunit at gmail.com Thu Dec 11 19:35:33 2008 From: gamersunit at gmail.com (Gregory Plantaine) Date: Thu, 11 Dec 2008 16:35:33 -0800 (PST) Subject: Find Files in a Folder Between 2 Dates References: <4c54b6c5-ae4d-4b89-8c6d-940c96de29bb@n33g2000pri.googlegroups.com> <94cd4bd7-a69f-48ba-90f7-382014844905@g1g2000pra.googlegroups.com> <862567e3-4469-43ae-b41b-1a1817124f50@k36g2000pri.googlegroups.com> <6b3bed68-3036-4e05-9571-e7dce0db2cff@r36g2000prf.googlegroups.com> Message-ID: <7ef72fa0-bf7b-453c-8bd4-4e947bc84a25@i18g2000prf.googlegroups.com> On Dec 11, 11:02?am, Gregory Plantaine wrote: > On Dec 5, 3:14?pm, John Machin wrote: > > > > > > > On Dec 6, 9:41?am, GregoryPlantaine wrote: > > > > That worked perfectly! > > > > Thanks Tim! > > > > Since we can print the files, does that mean the list of files is in a > > > tuple, or something? ?Would there be a way to further split up the > > > file names? > > > > For example, now that the files are processed into the list, we want > > > to look through that list to find different filetypes. > > > > files > > > > C:\Folder\File_200812051439.111 > > > C:\Folder\File_200812051539.222 > > > *DANGER* It looks like you are interested in the timestamps that are > > embedded in the names of the files. Tim's code assumes [reasonably > > given that your problem description was ambiguous and had no examples > > of good and bad results] that you are interested in the last > > modification time of the file. You may say "same thing". Yes, same > > thing, until somebody sucks a file into a text editor, messes with it, > > and saves it again. No, Murphy's Law has not been repealed. > > > > Can we split up .111 files? > > > > Actually, where would I look something like this up? > > > In the Library Reference Manual ... there are all sorts of goodies in > > the os and os.path modules e.g. like those used by Tim; make sure you > > read the docs on the methods Tim used so that you understand what's > > happening. > > > HTH, > > John > > Thanks for the advice John! > > I was going though the Manual, but I'm having some trouble figuring > out how to iterate through each line. > > So from the same example, we've already created a list called "lists". > Now how do I iterate through each line? > > For eachline in lists > ? ? Find all .111 files.- Hide quoted text - > > - Show quoted text - Ok, I figured it out. Actually more simple than I thought: for eachfile in files: if eachfile.endswith(".111"): print eachfile Another somewhat related question, instead of defining the firstdate, how would we do this? firstdate = secondate - 7 days From lie.1296 at gmail.com Fri Dec 12 16:48:09 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 12 Dec 2008 21:48:09 +0000 (UTC) Subject: Interface & Implementation References: <11e2ac5b5eb.2364397661727502391.6806593866408074890@adventnet.com> Message-ID: On Fri, 12 Dec 2008 16:07:26 +0530, J Ramesh Kumar wrote: > Hi, > > I am new to python. I require some help on implementing interface and > its implementation. I could not find any sample code in the web. Can you > please send me some sample code which is similar to the below java code > ? Thanks in advance for your help. > > ............ > public interface MyIfc > { > public void myMeth1(); > public void myMeth2(); > } > .... > public class MyClass implements MyIfc { > public void myMeth1() > { > //do some implementation > } > > public void myMeth2() > { > //do some implementation > } > } There is no need for interface in python due to duck typing class MyClass1(object): def myMeth1(self): # some implementation def myMeth2(self): # some implementation class MyClass2(object): def myMeth1(self): # other implementation def myMeth2(self): # other implementation cs[0] = MyClass1() cs[1] = MyClass2() for c in cs: c.myMeth1() c.myMeth2() but if you really want it, simple inheritance might be better anyway, though not really pythonic: class MyIfc(object): def myMeth1(self): return NotImplemented def myMeth2(self): return NotImplemented class MyClass(MyIfc): def myMeth1(self): # some implementation def myMeth2(self): # some implementation # some might notice the (ab)use of NotImplemented sentinel there From martin at v.loewis.de Mon Dec 15 16:48:15 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 15 Dec 2008 22:48:15 +0100 Subject: Problem Python 2.6.1 vs 2.6 & pyWin32 In-Reply-To: <4946754f$0$19000$426a74cc@news.free.fr> References: <4946754f$0$19000$426a74cc@news.free.fr> Message-ID: <4946D09F.6050300@v.loewis.de> > I am very disappointed. Help me, please. Try installing Python 2.6.1 "for all users". Regards, Martin From rocky at panix.com Thu Dec 11 05:06:31 2008 From: rocky at panix.com (R. Bernstein) Date: Thu, 11 Dec 2008 05:06:31 -0500 Subject: sys.settrace 'call' event behavior Message-ID: On Jun 21, 8:47 am, Michal Kwiatkowski wrote: > I'm building a tool to trace all function calls usingsys.settrace > function from the standard library. One of the awkward behaviors of > this facility is that the class definitions are reported as 'call' > events.[1] Since I don't want to catch class definitions, only > function calls, I'm looking for a way to differentiate between those > two. So far I have only vague clues about how to do that. > > At the bottom of this mail is a simple script that prints all > attributes (except for the bytecode) of the traced code. In the sample > code Bar class is defined and foo function is called after that. The > following trace output is reported: > > Bar, 0, 0, (), (), (), (None,), ('__name__', '__module__', 'None'), > foo.py, 21, , 1, 66 > foo, 0, 0, (), (), (), (None,), (), foo.py, 25, , 1, 67 > > Class definition and functioncalldiffers on four attributes. Two of > them, co_name and co_firstlineno are not very helpful. Other two are > co_names and co_flags. The latter differs only by the CO_OPTIMIZED > flag, which is for "internal use only"[2]. So we're left with > co_names, which "is a tuple containing the names used by the > bytecode". Is that helpful in distinguishing between class definitions > and function calls? Do you have any other ideas on how to tell them > apart? > > Source of the sample script I used follows. > > def trace(frame,event, arg): > ifevent== 'call': > print ', '.join(map(str, [frame.f_code.co_name, > frame.f_code.co_argcount, > frame.f_code.co_nlocals, > frame.f_code.co_varnames, > frame.f_code.co_cellvars, > frame.f_code.co_freevars, > frame.f_code.co_consts, > frame.f_code.co_names, > frame.f_code.co_filename, > frame.f_code.co_firstlineno, > frame.f_code.co_lnotab, > frame.f_code.co_stacksize, > frame.f_code.co_flags])) > return trace > > import syssys.settrace(trace) > > class Bar(object): > None > pass > > def foo(): > pass > > foo() > > [1] It is strange for me, but documented properly.http://docs.python.org/lib/debugger-hooks.htmlsays thatcallevent > happens when "a function is called (or some other code block > entered)." > > [2]http://docs.python.org/ref/types.html#l2h-145 > > Cheers, > mk Perhaps you could filter based on the type of the frame.f_code.co_name ? e.g. or type(eval(frame.f_code.co_name)) (Sorry for the delayed reply - I don't generally read the newsgroup and stumbled across this looking for something else. But I noticed no replies, so...) From pavlovevidence at gmail.com Thu Dec 4 00:29:17 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 3 Dec 2008 21:29:17 -0800 (PST) Subject: How can I do this (from Perl) in Python? (closures) References: <68b8294c-8771-4b02-bd46-2f25f5e01602@j35g2000yqh.googlegroups.com> Message-ID: <712b964c-764f-42bd-bec5-0e9acea15d8e@13g2000yql.googlegroups.com> On Dec 3, 11:18?pm, excor... at gmail.com wrote: > I just came acrosshttp://www.perl.com/pub/a/2002/05/29/closure.html > and wanted to try the "canonical example of closures" in Python. I > came up with the following, but it fails: > > ####################### > #!/usr/bin/env python > > def make_counter(start_num): > ? ? start = start_num > ? ? def counter(): > ? ? ? ? start += 1 > ? ? return counter > > from_ten = make_counter(10) > from_three = make_counter(3) > > print from_ten() ? ? ? # 10 > print from_ten() ? ? ? # 11 > print from_three() ? ? # 3 > print from_ten() ? ? ? # 12 > print from_three() ? ? # 4 > #################### > > The error message is: "UnboundLocalError: local variable 'start' > referenced before assignment". The same thing happens if I omit start > and just use start_num directly. > > How can I do it in Python? In Python 3.0, you can do this: def make_counter(start): def counter(): nonlocal start start += 1 return start # I assume you forgot this above return counter In Python 2.x, there is no nonlocal statement, so the best you can do is improvise something like this: def make_counter(start_num): start = [start_num] def counter(): start[0] += 1 return start[0] return counter You can access variables from an enclosing scope starting from Python 2.2 (from 2.1 with from __future__ import nested_scopes), but you could not rebind those variables until Python 3.0 came out today. Carl Banks From sjmachin at lexicon.net Fri Dec 19 08:39:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 19 Dec 2008 05:39:34 -0800 (PST) Subject: How to parsing a sequence of integers References: <494ba258$0$18998$426a74cc@news.free.fr> Message-ID: On Dec 20, 12:33?am, Bruno Desthuilliers wrote: > Steven Woody a ?crit :> Hi, > > > I am a newbie and is reading the python book. ?Could anyone tell me, > > how to parsing the following string > > ? ?"123 100 12 37 ..." > > ?> into a list of integers on which I can then apply max()/min()? > > source = "123 100 12 37" > list_of_ints = [int(part) for part in source.strip().split()] The purpose of the .strip() would be ...? From cptnwillard at gmail.com Mon Dec 1 05:12:03 2008 From: cptnwillard at gmail.com (cptnwillard at gmail.com) Date: Mon, 1 Dec 2008 02:12:03 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <3a30f601-7128-4e5f-a97e-9f899404912c@o40g2000prn.googlegroups.com> <4f31c483-8382-480e-8417-b7eef1b1792d@z1g2000yqn.googlegroups.com> <8c856b01-7f0c-4d5b-a1d2-cfe7dc74389f@w3g2000yqc.googlegroups.com> <1680020c-521c-4498-8e74-92e99c03da6b@w35g2000yqm.googlegroups.com> <0d9d2404-cb3f-4390-b97c-79251db8ac95@k8g2000yqn.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> Message-ID: Don't feed the troll. From steve at REMOVE-THIS-cybersource.com.au Tue Dec 16 20:48:04 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 17 Dec 2008 01:48:04 GMT Subject: weird dict problem, how can this even happen? References: <88idnfej99XAtNXUnZ2dnUVZ_hednZ2d@pdx.net> Message-ID: <015851be$0$20656$c3e8da3@news.astraweb.com> On Wed, 17 Dec 2008 02:10:31 +0100, Joel Hedlund wrote: > Scott David Daniels wrote: >> Perhaps your hash function could be something like: > > I'm not sure I understand what you're suggesting. Neither am I, since you've removed the hash function which might have given readers a clue. *wink* Snipping irrelevant text is a Good Thing, but in this case you were a little heavy-handed. -- Steven From girbarobert at yahoo.com Tue Dec 2 05:34:34 2008 From: girbarobert at yahoo.com (girbarobert at yahoo.com) Date: Tue, 2 Dec 2008 02:34:34 -0800 (PST) Subject: Obama's Birth Certificate - Demand that US presidential electors investigate Obama's eligibility Message-ID: This message is not about the meaningless computer printout called "Certification of Live Birth" that Obama propaganda machine calls his "Birth Certificate". The American people are still waiting for a copy of Obama's original birth certificate that includes all his birth information. Remind your US presidential electors of their constitutional duty to investigate Obama's natural-born citizen status. No federal agency like FBI or Secret Service, no Hawaii bureaucrats have ever investigated Obama's birth in Hawaii. Many illegal aliens in USA have official "birth certificates" issued by state bureaucrats on the basis of falsified birth records. Obama has spent over $800,000 in legal costs to avoid presenting a $10 copy of his original birth certificate on the grounds that nobody has a legal standing to see it. Remind your US presidential electors that they have the legal standing and constitutional duty to investigate Obama's birth in Hawaii by demanding that Obama provide all his original birth records, and a federal agency like FBI or Secret Service fully investigate them. To find the names of US presidential electors use the partial list at wikipedia below. Or use www.google.com, click News on top, then in the Search News enter the name of your state and the words: presidential electors. Or contact your US Senators, US House Rep, your state senators/reps, etc. If a US presidential elector refuses to investigate Obama's eligibility then post his/her full name on the internet so that all web search engines can pick it up. http://www.wnd.com/index.php?fa=PAGE.view&pageId=81550 http://en.wikipedia.org/wiki/List_of_United_States_presidential_electors,_2008 http://www.senate.gov/general/contact_information/senators_cfm.cfm http://clerk.house.gov/member_info/index.html From steve at REMOVE-THIS-cybersource.com.au Mon Dec 29 20:06:26 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Dec 2008 01:06:26 GMT Subject: get method References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> Message-ID: <01696b1a$0$6988$c3e8da3@news.astraweb.com> On Mon, 29 Dec 2008 17:00:31 -0800, Ross wrote: > Here's my code: > > def histogram(s): > d = dict() > for c in s: > d[c]= d.get(c,0) > return d > > This code returns a dictionary of all the letters to any string s I give > it but each corresponding value is incorrectly the default of 0. What am > I doing wrong? You're forgetting to increase the count each time you see a letter: * Look up the letter c in the dict, and call it count; * If c isn't found in the dict, use 0 as the count. * Set the value to count. But at no point do you increase count. -- Steven From bj_666 at gmx.net Wed Dec 10 09:33:57 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Dec 2008 14:33:57 GMT Subject: Announcement: MindTree for Python beta -- feedback appreciated References: <20841316.post@talk.nabble.com> <6q9ksbFbef4kU1@mid.individual.net> Message-ID: <6qa2alFbdrbpU1@mid.uni-berlin.de> On Wed, 10 Dec 2008 23:47:05 +1300, greg wrote: > Johann Spies wrote: > >> % /usr/local/bin/python3.0 MindTree.pyw >> Traceback (most recent call last): >> File "MindTree.pyw", line 2, in >> from future_builtins import * >> ImportError: No module named future_builtins > > Hmmm... does this mean that Python3 has no future? :-) It is just not built in. So it is easier to change the future by replacing the module. ;-) Ciao, Marc 'BlackJack' Rintsch From __peter__ at web.de Tue Dec 9 03:19:23 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Dec 2008 09:19:23 +0100 Subject: html codes References: Message-ID: Daniel Fetchinson wrote: > I came across a javascript library that returns all sorts of html > codes in the cookies it sets and I need my web framework (written in > python :)) to decode them. I'm aware of htmlentitydefs but > htmlentitydefs.entitydefs.keys( ) are of the form '&#xxx' but this > javascript library uses stuff like '%3A' for the ':' for example. The > conversion is here: > > http://www.ascii.cl/htmlcodes.htm > > Is there a python package/module/whatever that does the conversion for > me or do I have to write a little wrapper myself (and introduce bugs > while doing so :))? >>> import urllib >>> urllib.quote("L?blich ?hnlich ?blich") 'L%C3%B6blich%20%C3%A4hnlich%20%C3%BCblich' >>> urllib.unquote(_) 'L\xc3\xb6blich \xc3\xa4hnlich \xc3\xbcblich' >>> print _ L?blich ?hnlich ?blich If you care about the encoding you have to encode/decode explicitly: >>> urllib.quote(u"L?blich ?hnlich ?blich".encode("latin1")) 'L%F6blich%20%E4hnlich%20%FCblich' >>> urllib.unquote(_).decode("latin1") u'L\xf6blich \xe4hnlich \xfcblich' Peter From peke at iki.fi Tue Dec 16 15:59:52 2008 From: peke at iki.fi (=?ISO-8859-1?Q?Pekka_Kl=E4rck?=) Date: Tue, 16 Dec 2008 22:59:52 +0200 Subject: Problem Python 2.6.1 vs 2.6 & pyWin32 In-Reply-To: <4946e680$0$9099$9b622d9e@news.freenet.de> References: <4946754f$0$19000$426a74cc@news.free.fr> <4946D09F.6050300@v.loewis.de> <4946e680$0$9099$9b622d9e@news.freenet.de> Message-ID: <7dedbb6d0812161259h2be0e421v8655f9a0ade57f61@mail.gmail.com> 2008/12/16 "Martin v. L?wis" : >>> Try installing Python 2.6.1 "for all users". >> >> Could you clarify why that's needed? > > I didn't say it's needed. I said that he should try that, perhaps it > helps. > >> One thing we noticed (I'm not sure has this been yet submitted to >> bugs.python.org yet) was that installing packages created with Python >> 2.5 to Python 2.6 failed unless Python was in %PATH% [1]. This must have actually been caused by the Python26.dll not being in PATH. Unfortunately I don't have all the details since these problems didn't bite me personally, but I assume this has been a single user installation. > In general, that's not supported at all. You will have to rebuild all > packages for Python 2.6, unless they are pure-python packages (in > which case PATH should be irrelevant). > > If the .pyd files would have loaded, Python would have complained that > they originate from the wrong Python version. The question was about a pure-python package. Based on my very limited knowledge on .pyd files they aren't related to the problem. >> Another pretty severe problem was that installers created with Python >> 2.6 didn't work at all with older versions [2]. > > That's not a bug, either. It has been that way since Python 1.4 or so: > .pyd files built for X.Y won't work for X.(Y+1), and vice versa. > > It seems that you mean something specific with the word "installer"; > I think you should elaborate what precisely you are referring to. Sorry for not being explicit. With "installer" I meant the binary Windows installer you create with command "python setup.py bdist_wininst". In the past we've been able to use "package-version.win32.exe" files created with Python 2.5 on older version, but that doesn't seem to be case with 2.6. Cheers, .peke From nick at craig-wood.com Thu Dec 11 08:30:53 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 11 Dec 2008 07:30:53 -0600 Subject: How do I manually uninstall setuptools (installed by egg)? References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> <47c890dc0812091904p12e75510sbe0b8858eb2f6d9e@mail.gmail.com> Message-ID: David Cournapeau wrote: > On Wed, Dec 10, 2008 at 12:04 PM, Chris Rebert wrote: > > On Tue, Dec 9, 2008 at 6:49 PM, wrote: > >> On Ubuntu, I accidentally manually installed setuptools > >> http://pypi.python.org/pypi/setuptools/0.6c9 (by running the .egg file > >> as a shell script via sudo), and now realize I should just be using > >> apt to take care of my system Python packages. > > > > Really, why? setuptools has more Python packages/programs available > > and updates faster than Debian. > > It's also likely that some of the Debian Python packages are installed > > using setuptools anyway. > > So, why do you think apt and not setuptools is The Right Way(tm)? > > Setuptools is certainly not the right way to install packages > system-wide on debian, it is very likely to break the whole thing. It wouldn't be too difficult to make a .deb target which would collect all the files that did get installed into a package. It would be a rather rough and ready package but would do the job. The .deb would then be uninstallable in the usual (dpkg --purge) way. Did anyone think about that? There is a bdist_rpm target for distutils which I often use then use alien to turn into a .deb. easy_install is a lot easier though! > dpkg is a real package installer, with uninstallation feature, correct > dependency handling: if you start installing things with setuptools > there, dpkg cannot know anymore how to manage your system. Agreed. > That's why it is generally a very bad idea to install things which > are not managed by dpkg in /usr - be it python or something else > BTW. It is a much better practice to install from source into > /usr/local, or your $HOME, etc... Anywhere which is not /usr. easy_install can do that I think... I find it odd that easy_install doesn't have a) a list what you installed with easy_install b) uninstall in an otherwise excellent program. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bj_666 at gmx.net Mon Dec 1 03:44:48 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Dec 2008 08:44:48 GMT Subject: pydoc enforcement. References: <6ccec696-a8bb-4818-a016-642514677b70@b38g2000prf.googlegroups.com> Message-ID: <6phmg0F82a0lU1@mid.uni-berlin.de> On Sun, 30 Nov 2008 16:27:07 -0800, ken.faulkner at gmail.com wrote: > Basically I'm interested adding a check to see if: > 1) pydoc's are written for every function/method. Pylint warns for missing docstrings. > 2) There are entries for each parameter, defined by some predetermined syntax. But which syntax? There are several in use out there. Even the (I think) popular epydoc allows at least three, its own, something JavaDoc like, and ReST. And I dislike forcing to document every parameter. There's lots of code that is clear just by the names of the parameters and one or two usage examples in the docs. Forcing to state the obvious again does not add information for the user and is annoying for the programmer. > My idea is that as much as I love dynamic typing, there are times when > using some modules/API's that have less than stellar documentation. I > was thinking that if it was possible to enable some switch that > basically forced compilation to fail if certain documentation criteria > weren't met. But that doesn't enforce good or even real documentation either. Even worse, you can't spot the undocumented parts of the code anymore, because now every "docable" object has "documentation" like this just to make the compiler happy: def spam(foo, bar): """ :param foo: a foo object. :param bar: a bar object. """ Which basically tells the same as no documentation at all. Ciao, Marc 'BlackJack' Rintsch From steve at REMOVE-THIS-cybersource.com.au Thu Dec 18 20:10:28 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2008 01:10:28 GMT Subject: Factoring Polynomials References: Message-ID: <015aebdf$0$20656$c3e8da3@news.astraweb.com> On Thu, 18 Dec 2008 11:37:35 -0800, collin.day.0 wrote: > I am trying to write a simple application to factor polynomials. I wrote > (simple) raw_input lines to collect the a, b, and c values from the > user, but I dont know how to implement the quadratic equation > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > into python. Any ideas? def quadratic_solution(a, b, c): sol1 = (-b + (b**2 - 4*a*c)**0.5)/2*a sol2 = (-b - (b**2 - 4*a*c)**0.5)/2*a return (sol1, sol2) Because this looks like homework, I've deliberately left in two errors in the above. One of them is duplicated in the two lines above the return, and you must fix it or you'll get radically wrong answers. The second is more subtle, and quite frankly if this is homework you could probably leave it in and probably not even lose marks. You will need to do significant research into numerical methods to learn what it is, but you will then get significantly more accurate results. -- Steven From w_a_x_man at yahoo.com Thu Dec 11 11:01:51 2008 From: w_a_x_man at yahoo.com (William James) Date: Thu, 11 Dec 2008 17:01:51 +0100 (CET) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> Message-ID: William James wrote: > John W Kennedy wrote: > > > Xah Lee wrote: > > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or > > > Java, you'll have 50 or hundreds lines. > > > > > Java: > > > > static float[] normal(final float[] x) { > > float sum = 0.0f; > > for (int i = 0; i < x.length; ++i) sum += x[i] * x[i]; > > final float divisor = (float) Math.sqrt(sum); > > float[] a = new float[x.length]; > > for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor; > > return a; > > } > > "We don't need no stinkin' loops!" > > SpiderMonkey Javascript: > > function normal( ary ) > { div=Math.sqrt(ary.map(function(x) x*x).reduce(function(a,b) a+b)) > return ary.map(function(x) x/div) > } The variable "div" shouldn't be global. function normal( ary ) { var div = Math.sqrt( ary.map(function(x) x*x).reduce(function(a,b) a+b) ) return ary.map(function(x) x/div) } From simonharrison.uk at googlemail.com Mon Dec 8 05:55:40 2008 From: simonharrison.uk at googlemail.com (simonharrison.uk at googlemail.com) Date: Mon, 8 Dec 2008 02:55:40 -0800 (PST) Subject: Determining whether a variable is less/greater than a range. References: <362ab93b-b804-4ebe-a22f-e422feb301c8@c1g2000yqg.googlegroups.com> Message-ID: Found it. min and max functions. I thought that this would be implemented as a list method: a.min a.max I can see that the built in functions make sense. From skip at pobox.com Sun Dec 21 14:53:06 2008 From: skip at pobox.com (skip at pobox.com) Date: Sun, 21 Dec 2008 13:53:06 -0600 Subject: Removing self. In-Reply-To: References: Message-ID: <18766.40610.916335.675493@montanaro-dyndns-org.local> r> I do not like self, and i lamented it from day one, now it is second r> nature to me but does that mean it is really needed?? I feel i have r> been brainwashed into its usage. ... r> 3000 would have been the perfect time to dump self and really clean up r> the language, and it's not too late, dawn is not upon us yet. Bruce Eckel proposes removing self from argument lists: http://www.artima.com/weblogs/viewpost.jsp?thread=239003 Guido responds: http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From gnewsg at gmail.com Tue Dec 16 13:36:45 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Tue, 16 Dec 2008 10:36:45 -0800 (PST) Subject: ethical questions about global variables References: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> <148d911b-5c43-48a1-baea-5a46c04cacfd@o4g2000pra.googlegroups.com> Message-ID: On 16 Dic, 18:01, ianar? wrote: > For anything more complicated than a simple script, I find it easier > to use some sort of config object. This could be a simple dictionnary > type class, where the values can be set/retrieved by the other classes > directly, or a more elaborate class including functions to set/ > retrieve the variables. This way setting/retrieving can be 'smart' -- > possibly looking at other variables, program states, thread count, > whatever, for the requested config option. It also allows for a lot of > expansion down the line if need be, rather than dealing with all sorts > of global variables floating around - which gets annoying pretty > quickly. > > On Dec 15, 9:45?pm, "Giampaolo Rodola'" wrote: > > > > > Hi, > > in a module of mine (ftpserver.py) I'd want to add a (boolean) global > > variable named "use_gmt_times" to decide whether the server has to > > return times in GMT or localtime but I'm not sure if it is a good idea > > because of the "ethical" doubts I'm gonna write below. > > > In first place I've never liked global variables too much and always > > preferred per-class-instance variables instead. > > The problem in my case is that I have to use such variable in two > > separated classes: FTPHandler and VirtualFileSystem. Also, I want that > > for no reason one class uses times in GMT and the other one local > > times. > > > Another doubt is the naming convention. PEP-8 states that global > > variables should use the lower_case_naming_convention but I've seen a > > lot of library module using the UPPER_CASE_NAMING_CONVENTION. What am > > I supposed to do about it? > > > Thanks in advance for any comment. > > > --- Giampaolohttp://code.google.com/p/pyftpdlib/- Nascondi testo citato > > - Mostra testo citato - All the modificable options the library has acquired so far consist of class attributes and I'm ok with that. The only option that should be global is "use_gmt_times" because it is supposed to be used in two classes and I want that both of them use the same parameter. Using a Config class for a single option like "use_gmt_times" is not worth the effort, IMO. --- Giampaolo http://code.google.com/p/pyftpdlib/ From prologic at shortcircuit.net.au Sun Dec 14 23:59:45 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 15 Dec 2008 14:59:45 +1000 Subject: Python is slow In-Reply-To: References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> Message-ID: On Mon, Dec 15, 2008 at 2:44 PM, Benjamin Kaplan wrote: > On Sun, Dec 14, 2008 at 11:38 PM, cm_gui wrote: >> >> hahaha, do you know how much money they are spending on hardware to >> make >> youtube.com fast??? > > Obviously not enough to get to the point where it's cheaper to have the > programmers write C code. And the hardware is more for handling the intense > traffic that YouTube gets, not for speeding up the site. Seriously cm_gui, you're a fool. Python is not slow. --JamesMills From marek at xivilization.net Sun Dec 28 07:55:49 2008 From: marek at xivilization.net (Marek Kubica) Date: Sun, 28 Dec 2008 12:55:49 +0000 (UTC) Subject: What is site-packages? References: Message-ID: On Sun, 28 Dec 2008 04:06:36 -0800, Hussein B wrote: > You mean like MoinMoin, Django or Pylons for example? Yes. Or lxml, BeautifulSoup, psycopg2 and basically anything that is available on PyPI. regards, Marek From tjreedy at udel.edu Mon Dec 29 14:20:38 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Dec 2008 14:20:38 -0500 Subject: Get a list of functions in a file In-Reply-To: References: Message-ID: member Basu wrote: > I'm putting some utility functions in a file and then building a simple > shell interface to them. Is their some way I can automatically get a > list of all the functions in the file? I could wrap them in a class and > then use attributes, but I'd rather leave them as simple functions. Lets assume that either 1) You only define functions (bind function names) in the module, or 2) You start any other top-level names with '_' so that they do not get imported. import utilfuncs funcs = vars(utilfuncs) # dict of name:func pairs names = funcs.keys() # display names and ask user to select 'inputname' # then, assuming no args output = funcs[inputname]() tjr From manishsinha.tech at gmail.com Sun Dec 28 13:22:01 2008 From: manishsinha.tech at gmail.com (Manish Sinha) Date: Sun, 28 Dec 2008 23:52:01 +0530 Subject: "return" in def In-Reply-To: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> Message-ID: <4957C3C9.40205@gmail.com> Roger wrote: > Hi Everyone, > > First I want to thank everyone that posts to this group. I read it > daily and always learn something new even if I never feel like I have > anything to contribute but my questions. > Same here, I always read the news, but hardly post anything since am not very much expert in Python. > Even when I'm not explicitly returning something I like to add > "return" because it's a good additional visual marker for me to see > where a method definition ends especially in cases where I may use a > nested method. > I would personally prefer to use a comment for return rather than giving an explicit return statement. e.g. # return from function -- Manish Sinha Personal Blog: http://www.manishsinha.info Tech Blog: http://manishtech.wordpress.com OpenPGP Key: 99E6658F From python at bdurham.com Wed Dec 24 04:08:36 2008 From: python at bdurham.com (python at bdurham.com) Date: Wed, 24 Dec 2008 04:08:36 -0500 Subject: Strategy for determing difference between 2 very large dictionaries In-Reply-To: <1230109636.18987.1291625111@webmail.messagingengine.com> References: <1230102996.2303.1291616055@webmail.messagingengine.com> <6rea9hF16p8tU1@mid.uni-berlin.de> <3Qm4l.11404$c45.9406@nlpi065.nbdc.sbc.com> <1230109636.18987.1291625111@webmail.messagingengine.com> Message-ID: <1230109716.19049.1291625225@webmail.messagingengine.com> Hi James, > For the purpose of perpetuating the annoying pedantry that has made > usenet great: > > http://docs.python.org/dev/3.0/whatsnew/3.0.html#views-and-iterators-instead-of-lists Great tip! Thank you! Malcolm From gudonghua at gmail.com Thu Dec 11 21:38:03 2008 From: gudonghua at gmail.com (gudonghua+python@gmail.com) Date: Thu, 11 Dec 2008 18:38:03 -0800 (PST) Subject: Rename of .mdb file -- lock References: <4049f296-2a04-4eee-9f09-aa37a973a8cf@r40g2000yqj.googlegroups.com> Message-ID: <8792708a-51c9-4fa6-b39d-4808ed1ffaed@t39g2000prh.googlegroups.com> On Dec 12, 10:15?am, noydb wrote: > All, > > I have the code below, which unzips a zipfile containing only one > file. ?Once it is unzipped, I want to rename the file based on a user > provided name. ?But I get this (WindowsError: [Error 32] The process > cannot access the file because it is being used by another process) > error, which does not make sense to me as no other apps are open. > > Any suggestions? > > Thanks! > > ****CODE**** > # Declare the zip file directory and name (shouldn't change, in a > permanent location) > mdb_zip = ("C:\\ProjWork\\mdb_geoDB_91.zip") > > output_dir = ("C:\\Temp") > > # ZipFile for read > z = zipfile.ZipFile(mdb_zip, 'r') > zFile = z.namelist() > > # Put contents of zipfile into a list > zList = z.namelist() > > # Loop thru list, write zipfile contents to new directory > for zItem in zList: > ? ? print "Unpacking",zItem > ? ? zRead = z.read(zItem) > ? ? z1File = open(os.path.join(output_dir, zItem),'wb') > ? ? z1File.write(zRead) > ? ? z1File.close z1File.close() > print "Finished extracting zip file" > > uChoice = "test44.mdb" ## to be user chosen someday > new91mdb = os.path.join(output_dir, zItem) # C:\TEMP\GDB_9_1.mdb > > ##os.rename(new91mdb, (os.path.join(output_dir, uChoice))) > os.rename(new91mdb, (os.path.join(output_dir, "C:\TEMP\test1.mdb"))) > > del new91mdb From patrick.waldo at gmail.com Thu Dec 4 10:57:49 2008 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Thu, 4 Dec 2008 07:57:49 -0800 (PST) Subject: UnicodeDecodeError quick question Message-ID: <6858147d-a213-45ef-9564-bff220688881@e1g2000pra.googlegroups.com> Hi Everyone, I am using Python 2.4 and I am converting an excel spreadsheet to a pipe delimited text file and some of the cells contain utf-8 characters. I solved this problem in a very unintuitive way and I wanted to ask why. If I do, csvfile.write(cell.encode("utf-8")) I get a UnicodeDecodeError. However if I do, c = unicode(cell.encode("utf-8"),"utf-8") csvfile.write(c) Why should I have to encode the cell to utf-8 and then make it unicode in order to write to a text file? Is there a more intuitive way to get around these bothersome unicode errors? Thanks for any advice, Patrick Code: # -*- coding: utf-8 -*- import xlrd,codecs,os xls_file = "/home/pwaldo2/work/docpool_plone/2008-12-4/ EU-2008-12-4.xls" book = xlrd.open_workbook(xls_file) bibliography_sheet = book.sheet_by_index(0) csv = os.path.split(xls_file)[0] + '/' + os.path.split(xls_file)[1] [:-4] + '.csv' csvfile = codecs.open(csv,'w',encoding='utf-8') rowcount = 0 data = [] while rowcount References: <6e24be88-b042-425b-b880-c97d184fee07@s20g2000yqh.googlegroups.com> Message-ID: <47c890dc0812040942k770a8da1jb21cfb012276b23b@mail.gmail.com> On Thu, Dec 4, 2008 at 8:57 AM, Cro wrote: >> Do you really mean io.StringIO? I guess you want io.BytesIO() .. >> >> Christian > > Mmm... i don't know. > I also tried : > > [code] > IDLE 3.0 >>>> import io >>>> vContent = io.BytesIO() You do realize that the previous line is completely pointless, right? Later you rebind vContent to the results of huge.read() without ever having used it between that line and the above line. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com >>>> huge = io.open("C:\HUGE_FILE.pcl",'r+b',0) >>>> vContent = huge.read() > [/code] > > It still waits a lot... i don't have the patience to wait for the file > to load completely... it takes a lot! > > Thank you for your reply. > -- > http://mail.python.org/mailman/listinfo/python-list > From debl2NoSpam at verizon.net Fri Dec 19 18:03:39 2008 From: debl2NoSpam at verizon.net (David Lees) Date: Fri, 19 Dec 2008 23:03:39 GMT Subject: Very Slow PythonWin 2.6.1 Startup on Windows XP SP3 In-Reply-To: References: <_PG2l.570$P5.31@nwrddc02.gnilink.net> Message-ID: Allan wrote: > David Lees writes: > >> PythonWin used to startup in a second or two on my Windows XP >> desktop. now it takes around 20 seconds. I tried turning off Google >> Desktop indexing and Norton AV, but it still takes a long time to >> start. Other random apps such as Firefox 3.0 (which I just updated >> to) and Thunderbird have normal startup times. > What happens if you just open a Python command window; is it much > faster? On my computer which is seven years old (HP Pavilion desktop, > 512 MB RAM) it takes less than ten seconds for PythonWin to open. You > might try reinstalling PythonWin. > I just uninstalled all copies of Python from my system(2.5, 2.6 and 3.0), along with their corresponding PythonWin. Then I downloaded and installed Python 2.6.1 and PythonWin build 212. Now Python starts up nearly instantly. Thanks for the suggestion. David From arne at vajhoej.dk Wed Dec 10 18:44:51 2008 From: arne at vajhoej.dk (=?UTF-8?B?QXJuZSBWYWpow7hq?=) Date: Wed, 10 Dec 2008 18:44:51 -0500 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <20081226055859.604@gmail.com> Message-ID: <49405469$0$90262$14726298@news.sunsite.dk> Jon Harrop wrote: > Xah Lee wrote: >> Kaz Kylheku wrote: >>> Really? ``50 or hundreds'' of lines in C? >>> >>> #include /* for sqrt */ >>> >>> void normalize(double *out, double *in) >>> { >>> double denom = sqrt(in[0] * in[0] + in[1] * in[1] + in[2] * >>> in[2]); >>> >>> out[0] = in[0]/denom; >>> out[1] = in[1]/denom; >>> out[2] = in[2]/denom; >>> } >>> >>> Doh? >> Kaz, pay attention: >> >> Xah wrote: ?Note, that the ?norm? as defined above works for vectors >> of any dimention, i.e. list of any length.? > > That is still only 6 lines of C code and not 50 as you claimed: > > double il = 0.0; > for (int i=0; i il += in[i] * in[i]; > il = 1.0 / sqrt(il); > for (int i=0; i out[i] = il * in[i]; Not that it matters, but the above requires C99 (or C++). Arne From steve at REMOVE-THIS-cybersource.com.au Mon Dec 15 01:09:02 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Dec 2008 06:09:02 GMT Subject: [OT] stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> Message-ID: <0155ebf4$0$6988$c3e8da3@news.astraweb.com> On Sun, 14 Dec 2008 21:18:03 -0500, Roy Smith wrote: > Steven D'Aprano wrote: > >> All the positive thinking in the world won't help you: >> >> * make a four-sided triangle; >> >> * split a magnet into two individual poles; > > These two are fundamentally different problems. > > The first is impossible by definition. The definition of triangle is, > "a three-sided polygon". Asking for a "four-sided triangle" is akin to > asking for "a value of three which is equal to four". That's right. But see below. > The second is only "impossible" because it contradicts our understanding > (based on observation) of how the physical universe works. Our > understanding could simply be wrong. And arithmetic could be inconsistent, in which case it might be possible to prove that 3 equals 4. We don't know for sure that arithmetic is consistent, and according to Godel, there is no way of proving that it is consistent. There's no evidence that it isn't, but then, unless the inconsistency was obvious, how would we know? http://www.mathpages.com/home/kmath347/kmath347.htm > We've certainly been wrong before, > and we will undoubtedly be proven wrong again in the future. When it > comes to things like electromagnetic theory, it doesn't take too many > steps to get us to the fuzzy edge of quantum physics where we know there > are huge questions yet to be answered. No. I worded my question very carefully. The discovery of magnetic monopoles, as predicted by the fuzzy end of quantum physics, would not invalidate my claim. Magnets don't generate magnetic fields by the use of monopoles, and the discovery of such wouldn't make it possible to cut an ordinary magnet in two to get an individual north and south pole. That would like taking a rope with two ends (an ordinary rope, in other words), cut it in half, and finding that each piece has only a single end. Now, you could counter with a clever solution involving splicing the rope to itself in such a way that it had one end and a loop at the other, er, end. And such a solution might be very valuable, if we needed a way to get a rope with a loop at one end. But it isn't solving the problem of cutting a rope in two and getting only two ends instead of four. It's solving a different problem. -- Steven From renesd at gmail.com Thu Dec 4 20:45:49 2008 From: renesd at gmail.com (illume) Date: Thu, 4 Dec 2008 17:45:49 -0800 (PST) Subject: Python 3.0 C API migration tools, or docs? Message-ID: <008877d2-8705-48a6-bb09-6c31c6b77970@p2g2000prf.googlegroups.com> Hi, are there migration tools for C API migration to python 3? I'm sure there must be some code somewhere to help change stuff over right? I don't see any docs for migrating code from 2.x to 3.x either: http://docs.python.org/3.0/c-api/index.html Help needed with this! cheers, From soid.exe at gmail.com Sun Dec 28 15:38:22 2008 From: soid.exe at gmail.com (Grigory Temchenko) Date: Sun, 28 Dec 2008 12:38:22 -0800 (PST) Subject: A form validation library with javascript validation Message-ID: <9d342005-90e4-4fec-8f16-a52c744f0fc0@d36g2000prf.googlegroups.com> Hey everyone, Can someone advice me a beautiful or just cool library for form validation with javascript supporting? From tmh.public at gmail.com Wed Dec 3 17:12:51 2008 From: tmh.public at gmail.com (Thomas M. Hermann) Date: Wed, 3 Dec 2008 14:12:51 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> Message-ID: On Dec 3, 3:15?pm, Xah Lee wrote: > On Dec 3, 8:24 am, Jon Harrop wrote: > > > My example demonstrates several of Mathematica's fundamental limitations. > > enough babble Jon. > > Come flying $5 to my paypal account, and i'll give you real code, > amongest the programing tech geekers here for all to see. > > I'll show, what kinda garbage you cooked up in your Mathematica code > for ?comparison?. > > You can actually just post your ?comparisons? to ?comp.soft- > sys.math.mathematica?, and you'll be ridiculed to death for any > reasonable judgement of claim on fairness. > > > Consequently, there is great value in combining Mathematica with performant > > high-level languages like OCaml and F#. This is what the vast majority of > > Mathematica users do: they use it as a glorified graph plotter. > > glorified your ass. > > Yeah, NASA, Intel, NSA, ... all use Mathematica to glorify their > pictures. LOL. > > > What exactly do you believe is wrong with my code? > > come flies $5 to my paypal, and i'll explain further. > > > I am not trying to make Mathematica look bad. It is simply not suitable when > > hierarchical solutions are preferable... > > Certainly there are areas other langs are more suitable and better > than Mathematica (for example: assembly langs). But not in the ways > you painted it to peddle your F# and OCaml books. > > You see Jon, you are this defensive, trollish guy, who takes every > opportunity to slight other langs that's not one of your F#, OCml that > you make a living of. In every opportunity, you injest your gribes > about static typing and other things, and thru ensuring chaos paves > the way for you to post urls to your website. > > With your math and functional programing expertise and Doctor label, > it can be quite intimidating to many geekers. But when you bump into > me, i don't think you have a chance. > > As a scientist, i think perhaps you should check your newsgroup > demeanor a bit? I mean, you already have a reputation of being biased. > Too much bias and peddling can be detrimental to your career, y'known? > > to be sure, i still respect your expertise and in general think that a > significant percentage of tech geeker's posts in debate with you are > moronic, especially the Common Moron Lispers, and undoubtably the Java > and imperative lang slaving morons who can't grope the simplest > mathematical concepts. Throwing your Mathematica bad mouthing at me > would be a mistake. > > Come, fly $5 to my paypal account. Let the challenge begin. > > ? Xah > ?http://xahlee.org/ > > ? Xah, I'll pay $20 to see your improved version of the code. The only references to PayPal I saw on your website were instructions to direct the payment to xah at xahlee.org, please let me know if that is correct. What I want in return is you to execute and time Dr. Harrop's original code, posting the results to this thread. Then, I would like you to post your code with the timing results to this thread as well. By Dr. Harrop's original code, I specifically mean the code he posted to this thread. I've pasted it below for clarity. Jon Harrop coded a ray tracer in Mathematica: > delta = Sqrt[$MachineEpsilon]; > > RaySphere[o_, d_, c_, r_] := > Block[{v, b, disc, t1, t2}, > v = c - o; > b = v.d; > disc = Sqrt[b^2 - v.v + r^2]; > t2 = b + disc; > If[Im[disc] != 0 || t2 <= 0, \[Infinity], > t1 = b - disc; > If[t1 > 0, t1, t2]] > ] > > Intersect[o_, d_][{lambda_, n_}, Sphere[c_, r_]] := > Block[{lambda2 = RaySphere[o, d, c, r]}, > If[lambda2 >= lambda, {lambda, n}, {lambda2, > Normalize[o + lambda2 d - c]}] > ] > Intersect[o_, d_][{lambda_, n_}, Bound[c_, r_, s_]] := > Block[{lambda2 = RaySphere[o, d, c, r]}, > If[lambda2 >= lambda, {lambda, n}, > Fold[Intersect[o, d], {lambda, n}, s]] > ] > > neglight = N at Normalize[{1, 3, -2}]; > > nohit = {\[Infinity], {0, 0, 0}}; > > RayTrace[o_, d_, scene_] := > Block[{lambda, n, g, p}, > {lambda, n} = Intersect[o, d][nohit, scene]; > If[lambda == \[Infinity], 0, > g = n.neglight; > If[g <= 0, 0, > {lambda, n} = > Intersect[o + lambda d + delta n, neglight][nohit, scene]; > If[lambda < \[Infinity], 0, g]]] > ] > > Create[level_, c_, r_] := > Block[{obj = Sphere[c, r]}, > If[level == 1, obj, > Block[{a = 3*r/Sqrt[12], Aux}, > Aux[x1_, z1_] := Create[level - 1, c + {x1, a, z1}, 0.5 r]; > Bound[c, > 3 r, {obj, Aux[-a, -a], Aux[a, -a], Aux[-a, a], Aux[a, a]}]]]] > > scene = Create[1, {0, -1, 4}, 1]; > > Main[level_, n_, ss_] := > Block[{scene = Create[level, {0, -1, 4}, 1]}, > Table[ > Sum[ > RayTrace[{0, 0, 0}, > N at Normalize[{(x + s/ss/ss)/n - 1/2, (y + Mod[s, ss]/ss)/n - 1/2, > 1}], scene], {s, 0, ss^2 - 1}]/ss^2, {y, 0, n - 1}, > {x, 0, n - 1}]] > > AbsoluteTiming[Export["image.pgm", Graphics at Raster@Main[9, 512, 4]]] > From wuwei23 at gmail.com Wed Dec 3 20:58:16 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 3 Dec 2008 17:58:16 -0800 (PST) Subject: RELEASED Python 3.0 final References: Message-ID: On Dec 4, 11:51?am, Barry Warsaw wrote: > On behalf of the Python development team and the Python community, I ? > am happy to announce the release of Python 3.0 final. Thanks to you and everyone involved for your efforts! From google at mrabarnett.plus.com Tue Dec 16 14:00:20 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 16 Dec 2008 19:00:20 +0000 Subject: sorting for recursive folder rename In-Reply-To: References: Message-ID: <4947FAC4.3040203@mrabarnett.plus.com> ianar? wrote: > Hello all, > > I trying to recursively rename folders and files, and am looking for > some ideas on the best way of doing this. The problem is that the > given list of items can be in order, and one to all items may be > renamed. Here is some preliminary code I have, but which does not work > very well. > > self.toRename has the following structure : > [ > [original_name, new_name, os.path.isdir] > .. > ] > > # define these here for faster processing > def split(item): > return os.path.split(item) > def addSep(path): > return os.sep + path + os.sep > def recursiveFolderSort(x,y): > return cmp(y[0], x[0]) > > sortedRename = sorted(self.toRename) > > # make a list of all folders that will be processed > foldersToAdjust = [] > for item in sortedRename: > if item[2] is False: if not item[2]: > oF = split(item[0])[1] # original folder name > nF = split(item[1])[1] # new folder name > if oF is not nF: if oF != nF: > foldersToAdjust.append((oF, nF)) > > # replace all occurences of folders in path > for i in range(len(self.toRename)): > for f in foldersToAdjust: > oF = addSep(f[0]) # original folder name > nF = addSep(f[1]) # new folder name > self.toRename[i][0] = self.toRename[i][0].replace(oF,nF) > self.toRename[i][1] = self.toRename[i][1].replace(oF,nF) > > if progressDialog.update(i) is False: if not progressDialog.update(i): > error = 'cancelled' > break > > # make sure renaming will be in correct order ! > self.toRename.sort(recursiveFolderSort) > > > > First problem is adjusting the paths can take a very long time. > Second problem is sorting is not always right and files get lost !! > Any input welcome. > You should use "is" and "is not" _only_ when checking for _identity, ie are these 2 both references to the _same_ object. Most of the time that would be "x is None" or "x is not None". From saluk64007 at gmail.com Sat Dec 6 01:47:50 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Fri, 5 Dec 2008 22:47:50 -0800 Subject: Guido's new method definition idea In-Reply-To: <014a071a$0$20670$c3e8da3@news.astraweb.com> References: <014a071a$0$20670$c3e8da3@news.astraweb.com> Message-ID: >> Daniel Fetchinson wrote: >>> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to- > stay.html >>> >>> The proposal is to allow this: >>> >>> class C: >>> def self.method( arg ): >>> self.value = arg >>> return self.value >>> >>> instead of this: >>> >>> class C: >>> def method( self, arg ): >>> self.value = arg >>> return self.value >>> I'd like this new way of defining methods, what do you guys think? I don't really like the proposed syntax any better than the old syntax. I certainly wouldn't use "def self." in any of my old code. I doubt I would use it in a new project were I to have the choice either. However, I don't really have a problem with other people liking it. the symetry of "def self.func(blah)==def func(self,blah)" and "ob.func(blah)==func(ob.blah)" is kind of neat. Could I do something like this: def a.add(b): return a+b Outside of a class? Of course then that makes you think you could do 5.add(6) or something craaaazy like that. (I mean, you can do (5).__add__(6) but that's something else entirely) From xahlee at gmail.com Thu Dec 4 20:02:59 2008 From: xahlee at gmail.com (Xah Lee) Date: Thu, 4 Dec 2008 17:02:59 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: alright, here's my improved code, pasted near the bottom. let me say a few things about Jon's code. If we rate that piece of mathematica code on the level of: Beginner Mathematica programer, Intermediate, Advanced, where Beginner is someone who just learned tried to program Mathematica no more than 6 months, then that piece of code is Beginner level. Here's some basic analysis and explanation. The program has these main functions: ? RaySphere ? Intersect ? RayTrace ? Create ? Main The Main calls Create then feed it to RayTrace. Create calls itself recursively, and basically returns a long list of a repeating element, each of the element differ in their parameter. RayTrace calls Intersect 2 times. Intersect has 2 forms, one of them calls itself recursively. Both forms calls RaySphere once. So, the core loop is with the Intersect function and RaySphere. Some 99.99% of time are spent there. ------------------ I didn't realize until after a hour, that if Jon simply give numerical arguments to Main and Create, the result timing by a factor of 0.3 of original. What a incredible sloppiness! and he intended this to show Mathematica speed with this code? The Main[] function calls Create. The create has 3 parameters: level, c, and r. The level is a integer for the recursive level of raytracing . The c is a vector for sphere center i presume. The r is radius of the sphere. His input has c and r as integers, and this in Mathematica means computation with exact arithmetics (and automatic kicks into infinite precision if necessary). Changing c and r to float immediately reduced the timing to 0.3 of original. ------------------ now, back to the core loop. The RaySphere function contain codes that does symbolic computation by calling Im, which is the imaginary part of a complex number!! and if so, it returns the symbol Infinity! The possible result of Infinity is significant because it is used in Intersect to do a numerical comparison in a If statement. So, here in these deep loops, Mathematica's symbolic computation is used for numerical purposes! So, first optimization at the superficial code form level is to get rid of this symbolic computation. Instead of checking whethere his ?disc = Sqrt[b^2 - v.v + r^2]? has imaginary part, one simply check whether the argument to sqrt is negative. after getting rid of the symbolic computation, i made the RaySphere function to be a Compiled function. I stopped my optimization at this step. The above are some _fundamental_ things any dummy who claims to code Mathematica for speed should know. Jon has written a time series Mathematica package that he's selling commercially. So, either he got very sloppy with this Mathematica code, or he intentionally made it look bad, or that his Mathematica skill is truely beginner level. Yet he dares to talk bullshit in this thread. Besides the above basic things, there are several aspects that his code can improve in speed. For example, he used pattern matching to do core loops. e.g. Intersect[o_, d_][{lambda_, n_}, Bound[c_, r_, s_]] any Mathematica expert knows that this is something you don't want to do if it is used in a core loop. Instead of pattern matching, one can change the form to Function and it'll speed up. Also, he used ?Block?, which is designed for local variables and the scope is dynamic scope. However the local vars used in this are local constants. A proper code would use ?With? instead. (in lisp, this is various let, let*. Lispers here can imagine how lousy the code is now.) Here's a improved code. The timing of this code is about 0.2 of the original. Also, optimization is purely based on code doodling. That is, i do not know what his code is doing, i do not have experience in writing a ray tracer. All i did is eyeballing his code flow, and improved the form. norm=Function[#/Sqrt@(Plus@@(#^2))]; delta=Sqrt[$MachineEpsilon]; myInfinity=10000.; Clear[RaySphere]; RaySphere = Compile[{o1, o2, o3, d1, d2, d3, c1, c2, c3, r}, Block[{v = {c1 - o1, c2 - o2, c3 - o3}, b = d1*(c1 - o1) + d2*(c2 - o2) + d3*(c3 - o3), discriminant = -(c1 - o1)^2 - (c2 - o2)^2 + (d1*(c1 - o1) + d2*(c2 - o2) + d3*(c3 - o3))^2 - (c3 - o3)^2 + r^2, disc, t1, t2}, If[discriminant < 0., myInfinity, disc = Sqrt[discriminant]; If[(t1 = b - disc) > 0., t1, If[(t2 = b + disc) <= 0., myInfinity, t2]]]]]; Remove[Intersect]; Intersect[{o1_,o2_,o3_},{d1_,d2_,d3_}][{lambda_,n_},Sphere [{c1_,c2_,c3_},r_]]:= Block[{lambda2=RaySphere[o1,o2,o3,d1,d2,d3,c1,c2,c3,r]}, If[lambda2?lambda,{lambda,n},{lambda2, norm[{o1,o2,o3}+lambda2 *{d1,d2,d3}-{c1,c2,c3}]}]] Intersect[{o1_,o2_,o3_},{d1_,d2_,d3_}][{lambda_,n_}, Bound[{c1_,c2_,c3_},r_,s_]]:= Block[{lambda2=RaySphere[o1,o2,o3,d1,d2,d3,c1,c2,c3,r]}, If[lambda2?lambda,{lambda,n}, Fold[Intersect[{o1,o2,o3},{d1,d2,d3}],{lambda,n},s]]] Clear[neglight,nohit] neglight=N at norm[{1,3,-2}]; nohit={myInfinity,{0.,0.,0.}}; Clear[RayTrace]; RayTrace[o_,d_,scene_]:= Block[{lambda,n,g,p},{lambda,n}=Intersect[o,d][nohit,scene]; If[lambda\[Equal]myInfinity,0,g=n.neglight; If[g?0, 0,{lambda,n}=Intersect[o+lambda d+delta n,neglight] [nohit,scene]; If[lambda Message-ID: En Sat, 27 Dec 2008 22:54:52 -0200, Daniel Fetchinson escribi?: > This is the function I have, the corresponding python function will > take two equal length lists of integers and the C function will > compute their sum and return the result as a python tuple. > > > static PyObject *func( PyObject * self, PyObject * args ) > { > int j, N; > int * src1, * src2; > PyObject *list1, *list2; > > list1 = PyTuple_GetItem( args, 0 ); > N = PyList_Size( list1 ); > src1 = ( int * ) malloc( N * sizeof( int ) ); > for( j = 0; j < N; j++ ) > { > src1[j] = (int)PyInt_AsLong( PyList_GetItem( list1, j ) ); > } > > list2 = PyTuple_GetItem( args, 1 ); > N = PyList_Size( list2 ); > src2 = ( int * ) malloc( N * sizeof( int ) ); > for( j = 0; j < N; j++ ) > { > src2[j] = (int)PyInt_AsLong( PyList_GetItem( list2, j ) ); > } > > PyObject * tuple; > tuple = PyTuple_New( N ); > for( j = 0; j < N; j++ ) > { > PyTuple_SetItem( tuple, j, PyInt_FromLong( (long)( src1[j] + > src2[j] ) ) ); > } > > free( src1 ); > free( src2 ); > > return tuple; > } As others already said, using a Numpy array or an array.array object would be more efficient (and even easier - the C code gets a pointer to an array of integers, as usual). > Do I have to free the memory occupied by the python objects list1 and > list2? No. Usually you don't do that for any Python object - just increment/decrement its reference count (using Py_INCREF/Py_DECREF). > Do I have to do any refcounting for list1, list2, tuple? In this case list1 and list2 come from PyTuple_GetItem; the docs say it returns a "borrowed reference" (that is, the function doesn't increment the refcount itself). So you don't have to decrement it yourself (and it isn't necesary to increment it in the first place, because the "args" tuple holds a reference, so the object can't disappear until the function exits, at least) > Any comment on the above code will be very appreciated! If I'm pushed > in the right direction I'm a fast learner but the beginning steps are > always hard :) You MUST check EVERY function call for errors! And check the argument's type (how do you know it is a list?). Once you are sure the first parameter *is* a list, you may use the "macro" version of several functions, like PyList_GET_SIZE and PyList_GET_ITEM. You should check that both lists have the same length too. And you should check that elements are integers, or convertible to integers (in case of error, PyInt_AsLong returns -1 and PyErr_Occurred() is true) To fill the resulting tuple, use PyTuple_SET_ITEM instead. BTW, why return a tuple and not a list? -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Fri Dec 12 07:10:47 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Dec 2008 12:10:47 GMT Subject: (Very Newbie) Problems defining a variable References: <49425146$0$8495$426a74cc@news.free.fr> <11c53a4a-de1e-4bee-ad60-a05befb6cbf4@a12g2000yqm.googlegroups.com> Message-ID: <01524c52$0$20617$c3e8da3@news.astraweb.com> On Fri, 12 Dec 2008 04:05:21 -0800, feba wrote: > that's it, thanks! was confused with it being basically in a column of > all >= *. > > I replaced it with > > if bank <= 0: > print("You're in the red!") > quit() > elif bank >= 1 and bank <= 9999: > rate = 0.0060 You can replace this with the simpler, easier to read and faster: elif 1 <= bank <= 9999: rate = 0.0060 elif 10000 <= bank <= 24999: rate = 0.0085 ... > elif bank >= 100000: > rate = 0.0173 > else: > print("What's this doing here?") Change the last two else clauses to this one: else: rate = 0.0173 -- Steven From __peter__ at web.de Mon Dec 1 16:25:30 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 01 Dec 2008 22:25:30 +0100 Subject: Is it safe to modify the dict returned by vars() or locals() References: <4934508b$0$2861$ba620e4c@news.skynet.be> Message-ID: Helmut Jarausch wrote: > I am looking for an elegant way to solve the following problem: > > Within a function > > def Foo(**parms) > > I have a list of names, say VList=['A','B','C1'] > and I like to generate abbreviation > _A identical to parms['A'] > > for that I could write > > def Foo(**parms) : > for N in VList : > if N in parms : > vars()[N]= parms[N] > else : > vars()[N]= None > > Does this work, is it typical Python? locals() gives you a copy of the local namespace. No changes to the copy are written back to that namespace. In idiomatic python you'd just use the dictionary. If you are bothered with the non-existent keys, make a copy >>> parms = dict(a=1, c=3) >>> p = dict.fromkeys(["a", "b", "c"]) >>> p.update(parms) >>> p["a"], p["b"], p["c"] (1, None, 3) >>> p["x"] Traceback (most recent call last): File "", line 1, in KeyError: 'x' or, setting any non-existent key to None: >>> from collections import defaultdict >>> parms = dict(a=1, c=3) >>> p = defaultdict(lambda: None) >>> p.update(parms) >>> p["a"], p["b"], p["c"] (1, None, 3) If you insist on manipulating the namespace you can use exec: >>> def foo(**parms): ... exec "\n".join("%s = parms.get(%r)" % (n, n) for n in ["a", "b", "c"]) ... return a, b, c ... >>> foo(a=1, c=3) (1, None, 3) >>> foo(b=20) (None, 20, None) Peter From arkanes at gmail.com Thu Dec 4 14:34:26 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 4 Dec 2008 13:34:26 -0600 Subject: To Troll or Not To Troll In-Reply-To: <896B75251BA19745A529B1B867893FA50679CE@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA50679CE@planet.delsci.local> Message-ID: <4866bea60812041134t42b7aca5j7b50d06094280240@mail.gmail.com> On Thu, Dec 4, 2008 at 1:10 PM, Warren DeLano wrote: >> Yet Another Python Troll (the ivory tower reference, as well as the >> abrupt shift from complaining about keywords to multiprocessing), I >> have to point out that Python does add new keywords, it has done so in >> the past, and there was a considerable amount of warning, including an >> automated deprecation warning in the very version you are going to >> recommend to your "customers' (I don't actually think you have any >> customers). > > ROFL! I'm sorry, you're right -- this has all been a figment of my > imagination... > > http://www.pymolwiki.org/index.php/Covers > > http://images.google.com/images?q=pymol > > So don't mind me -- I clearly don't know what I'm talking about. > Peculiarities in usenet resulted in this discussion having several threads and I missed some messages before I wrote this email. So I apologize for calling you a troll, but only slightly - what you wrote had exactly the same content and tone that people who are intentionally trolling write every day. There are legitimate, interesting, and important discussions to be had about multithreading in Python, but nothing you wrote was of any use to any of them. I still would have to call your management of the problem considerably into question - your expertise at writing mathematical software may not be in question, but your skills and producing and managing a software product are. You have nobody at your organization, which sells a product that relies on Python, who follows python-dev? Or who even reads the changelogs for new python versions? You should have known about the "as" keyword change *over a year ago*, even if the import bug was masking the deprecation warning. Everything else aside, I can't get past that issue with your complaints. I *have* gone back now and read all the posts in all the threads and I still have not seen a single post from you even hinting that you might have any responsibility in the matter. Multithreading is a different discussion, and totally unrelated to the original complaint (which is why it's trolling, customers or not, to bring it up in this thread) and I'm not going to address it - everything of any interest in the conversation has been said already, and if you know enough to talk seriously about it you already know all the arguments on both sides. If you *don't* know them, a perusal of the python-dev and c.l.p archives should bring you up to speed easily. From pavlovevidence at gmail.com Sat Dec 6 15:13:16 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 6 Dec 2008 12:13:16 -0800 (PST) Subject: "as" keyword woes References: Message-ID: On Dec 6, 1:38?pm, "Warren DeLano" wrote: > There, I assert that 'object.as(class_reference)' is the simplest and > most elegant generalization of this widely-used convention. ?Indeed, it > is the only obvious concise answer, if you are limited to using methods > for casting. I don't agree with your assertion. object.as_type(class_reference) object.cast(class_reference) These are both concise and obvious. > As someone somewhat knowledgable of how parsers work, I do not > understand why a method/attribute name "object_name.as(...)" must > necessarily conflict with a standalone keyword " as ". ?It seems to me > that it should be possible to unambiguously separate the two without > ambiguity or undue complication of the parser. It's possible, and they've been doing it for years, and they could have continued doing it if they wanted to. You'll notice that nowhere the Python grammar can two identifiers be separated by whitespace. So if you have two identifiers separated by whitespace, and the second one is "as", you know it has to be keyword "as". Well, they made it a keyword anyway. It was never a question of whether they could do it. > So, assuming I now wish to propose a corrective PEP to remedy this > situation for Python 3.1 and beyond, what is the best way to get started > on such a proposal? ? I think you'd be wasting your time, but the general procedure is outlined in PEP 1. Basically, you write a pre-PEP (aka PEP XXX) according to the guidelines in PEP 1, which you would post here and request comments on it. Then, if you can muster some support for it, you would send it to PEP maintainer (the email is listed somewhere on the PEPs page, dig for it), and get a number assigned, upon which time Guido van Rossum will read it and any comments in python-dev, and make a pronouncement of some sort. If you write a PEP, I advise you to try to sound less whiny and than you have in this thread. Saying "object.as(class_reference) is highly convenient because it mirrors textually the Java convention of object.asFloat" will go over a lot better than "object.as (class_reference) is the only obvious concise answer". Carl Banks From martin at v.loewis.de Fri Dec 5 19:26:37 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 06 Dec 2008 01:26:37 +0100 Subject: Running Python 2 and Python 3 on the same machine In-Reply-To: References: <1228424486.5873.6.camel@linux-3eb6.site> <49387f7e$0$27857$9b622d9e@news.freenet.de> Message-ID: <4939c6be$0$6534$9b622d9e@news.freenet.de> Terry Reedy wrote: > Martin v. L?wis wrote: >>> Since the source code is incompatible, I was expecting the Python >>> executable to have a new name such as 'python3' >> >> It does: the executable is called python3.0. > > Why do you say that? Because it is - on Unix. I assumed that was the platform that the OP cared about. Regards, Martin From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 21:06:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2008 02:06:12 GMT Subject: ANN: New Book: Programming in Python 3 References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> Message-ID: <015c4a65$0$20656$c3e8da3@news.astraweb.com> On Fri, 19 Dec 2008 19:32:22 -0500, Colin J. Williams wrote: (Fixing broken unicode.) >> Question from a non-native english speaker: is this now valid english? >> >> "One of Python's great strengths" >> ^ >> "and also teaches Python's functional programming features" >> ^ >> "The book's approach is wholly practical" >> ^ >> >> Curious, >> Thomas > > No. Is this a quote from some > advertising stuff or was it written by the author? What makes you say it is not valid English? How do you make possessives? -- Steven From theiviaxx at gmail.com Wed Dec 10 17:44:59 2008 From: theiviaxx at gmail.com (TheIvIaxx) Date: Wed, 10 Dec 2008 14:44:59 -0800 (PST) Subject: lxml.etree error: xmlSchematronSetValidStructuredErrors Message-ID: <33c18d97-598e-4c8c-ac1d-b7c839862eda@a26g2000prf.googlegroups.com> I have installed libxml2 and libxslt and then tried to install lxml with easy_install lxml. I can import lxml by "import lxml" but trying "from lxml import etree" and get: ImportError: /usr/local/lib/python2.5/site-packages/lxml-2.2alpha1- py2.5-linux-i686.egg/lxml/etree.so: undefined symbol: xmlSchematronSetValidStructuredErrors I have only seen one mention of this error through googling and they suggested there was something wrong with libxml2 or libxslt. However importing libxml2 works fine, libxslt throws an error about it not defining an init function (?). Any advice? Thanks From steve at holdenweb.com Mon Dec 15 12:35:36 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 15 Dec 2008 12:35:36 -0500 Subject: %s place holder does not let me insert ' in an sql query with python. In-Reply-To: References: <1229345178.31093.24.camel@krishna-laptop> Message-ID: <49469568.2090203@holdenweb.com> Lamonte Harris wrote: > I had this problem too. If you've upgraded to python 2.6 you need to > use the new sytnax "format > > queryString = "insert into venders > values('{0}','{1}','{2}'".format(field1,field2,field3) > Will all readers of this thread kindly regard this as an example of how *not* to generate and execute SQL queries in Python. Study the cursor.execute() method, and provide parameterized queries and a data tuple instead. Please also note that the above technique explicitly continues to generate SQL syntax errors in Krishnakan's case where the data values themselves contain apostrophes. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From rt8396 at gmail.com Mon Dec 22 21:51:40 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 18:51:40 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> Message-ID: <7c02eb33-a919-4481-8eda-76062729f233@k19g2000yqg.googlegroups.com> On Dec 22, 7:34?pm, Steven D'Aprano wrote: > On Mon, 22 Dec 2008 10:01:21 -0800, r wrote: > > Walter, > > I just look at the stats for comp.lang.python, and i am 9th place for > > most post this month. > > And about 9,000th place for useful information. > > -- > Steven I think you missed my point Steven, I was in no way proud of the fact of my 9th place rating. It just proves my point to the small following of this group. And frankly makes me feel bad. From gagsl-py2 at yahoo.com.ar Sun Dec 21 17:30:33 2008 From: gagsl-py2 at yahoo.com.ar (gagsl-py2 at yahoo.com.ar) Date: Sun, 21 Dec 2008 14:30:33 -0800 (PST) Subject: [Help] The pywinauto Can't select the MDI's menu using the MenuItems() which return []. In-Reply-To: Message-ID: <85676.52949.qm@web32801.mail.mud.yahoo.com> --- El vie 19-dic-08, ???? escribi?: > I use the WORD Only for my example. > The application I test is similar to the WORD and It > has't the COM. The code below opens the Choose Font dialog on my Spanish Windows version: py> from pywinauto.application import Application py> app = Application.start("Notepad.exe") py> app[u"Sin t?tulo - Bloc de notas"].MenuSelect(u"Formato->Fuente") (using an English version, the last line would be app.UntitledNotepad.MenuSelect("Format->Font") I presume) There are many examples in the documentation, and some more info at http://pywinauto.seleniumhq.org/ I think there is a pywinauto users list. > 2008/12/19 Gabriel Genellina > > > En Thu, 18 Dec 2008 11:28:54 -0200, Simon Brunning > > escribi?: > > > > 2008/12/18 ???? : > >> > >>> This problem also use the following > discription: > >>> How to use pywinauto to open WORD and select > its Menu. > >>> I can't do that and have no idea why! > >>> Looking forward your help,Thanks! > >>> > >> > >> Word can be automated with COM. My golden rule is > that automation via > >> GUI driving is always a last resort. -- Gabriel Genellina ____________________________________________________________________________________ ?Busc? desde tu celular! Yahoo! oneSEARCH ahora est? en Claro http://ar.mobile.yahoo.com/onesearch From samslists at gmail.com Fri Dec 5 15:02:19 2008 From: samslists at gmail.com (Sam) Date: Fri, 5 Dec 2008 12:02:19 -0800 (PST) Subject: Centralized logging server... Message-ID: <413147e3-aaea-4ae3-a350-4c22a79fe77a@b38g2000prf.googlegroups.com> Hi... I'm working with a small team writing a bunch of python applications that communicate via xml/http in a somewhat restful way. :) They are running on about half a dozen computers. We'll probably be scaling that to a lot more computers soon. I've been playing with the python logging module. I'd like all of these applications to write their logs to the same place in order to make analysis easier. Any ideas on best practices? What are my options for a syslog server to receive the messages? Rsyslog looks like it would be good. Anyone know anything else? Thanks From vlastimil.brom at gmail.com Sat Dec 13 16:03:14 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Sat, 13 Dec 2008 22:03:14 +0100 Subject: Python 3.0 crashes displaying Unicode at interactive prompt In-Reply-To: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> Message-ID: <9fdb569a0812131303k73822a2es7639e37dbb0b98d3@mail.gmail.com> 2008/12/13 John Machin : > > Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> x = u'\u9876' >>>> x > u'\u9876' > > # As expected > > Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit > (Intel)] on win 32 > Type "help", "copyright", "credits" or "license" for more information. >>>> x = '\u9876' >>>> x > Traceback (most recent call last): > File "", line 1, in > File "C:\python30\lib\io.py", line 1491, in write > b = encoder.encode(s) > File "C:\python30\lib\encodings\cp850.py", line 19, in encode > return codecs.charmap_encode(input,self.errors,encoding_map)[0] > UnicodeEncodeError: 'charmap' codec can't encode character '\u9876' in > position > 1: character maps to > > # *NOT* as expected (by me, that is) > > Is this the intended outcome? > -- > http://mail.python.org/mailman/listinfo/python-list > I also found this a bit surprising, but it seems to be the intended behaviour (on a non-unicode console) http://docs.python.org/3.0/whatsnew/3.0.html "PEP 3138: The repr() of a string no longer escapes non-ASCII characters. It still escapes control characters and code points with non-printable status in the Unicode standard, however." I get the same error in windows cmd, (Idle prints the respective glyph correctly). To get the old behaviour of repr, one can use ascii, I suppose. Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> repr('\u9876') Traceback (most recent call last): File "", line 1, in File "C:\Python30\lib\io.py", line 1491, in write b = encoder.encode(s) File "C:\Python30\lib\encodings\cp852.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u9876' in position 2: character maps to >>> '\u9876'.encode("unicode-escape") b'\\u9876' >>> ascii('\u9876') "'\\u9876'" >>> From gary at byoteki.com Sat Dec 27 08:02:13 2008 From: gary at byoteki.com (Gary M. Josack) Date: Sat, 27 Dec 2008 08:02:13 -0500 Subject: parsing csv files class In-Reply-To: References: Message-ID: <49562755.6050205@byoteki.com> alex goretoy wrote: > I know it's messy with all those self.soc.* functions, but it works in > one of my current project. I just want to make it more pythonic I also > want to add capability for makeing csv file if I give it input like: > 1234,something nice, hey this is something nice > 2468,something else, something else > > On Sat, Dec 27, 2008 at 4:54 AM, alex goretoy > > wrote: > > Hello All, > > I have this class that I use in one of my projects. I know it's > missing functionality and some things could have been done > differently. Can you ehlp me make this class better? What can I do > to make it more resistant to error? You can find the > stdout_colours class on Google if you want it, JFGI I want to make > it more pythonic. I come from a PHP background, can you tell? > > Any and all help is appreciated > -Alex > > #!/usr/bin/env python > from ctypes import * > import os, sys, types, csv, urllib, urllib2, urlparse, > string,stdout_colours > > class parsercsvy(object): > """Return a line from a csv file or total amount of lines""" > def __init__(self,file_name=""): > self.func_me_color="white_on_black" > self.soc=stdout_colours.stdout_colors() > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > self.filename = file_name > self.buffer = [] > self.bufferp= [] > if string.find(self.filename,"http") != -1: > resp=urllib2.urlopen(self.filename) > file=resp.read() > lfi=len(string.split(self.filename,"/")) > filename = "/tmp/"+string.split(self.filename,"/")[lfi-1] > f=open(filename,"w") > f.write(file) > f.close > self.parse(self.filename) > else: > self.parse(self.filename) > self.soc.me_him(['EXIT:',__name__],self.func_me_color) > def parse(self,filename,ret=0): > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > i = 0 > try: > reader = csv.reader(file(filename, "rb")) > try: > for row in reader: > self.buffer.append(row) > s,a=[],{} > > for j in range(len(self.buffer[0])): > a[self.buffer[0][j]]=row[j] > self.bufferp.append(a) > i+=1 > self.total = i-1 > except csv.Error, e: > sys.exit('file %s, line %d: %s' % (filename, > reader.line_num, e)) > except IOError, e: > sys.exit('file %s, IOError: %s' % (filename, e)) > self.soc.me_him(['EXIT:',__name__],self.func_me_color) > def index(self, index): > """return line for index""" > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > > self.soc.me_him(['RETURN:',self.buffer[int(index)],__name__],self.func_me_color) > return self.buffer[int(index)] > def total(self): > """return total number of lines in csv file""" > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > > self.soc.me_him(['RETURN:',self.total,__name__],self.func_me_color) > return self.total > def header(self): > """return csv header == line 0""" > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > > self.soc.me_him(['RETURN:',self.buffer[0],__name__],self.func_me_color) > return self.buffer[0] > def find_and_replace(self,li,fi,re): > """ > find and replace a string inside a string, return list > find_and_replace(list,find,replace) > """ > this=[] > for l in li: > # found_index=string.find(l,fi) > this.append(l.replace(fi,re)) > return this > def return_buffer(self): > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > > self.soc.me_him(['RETURN:',self.buffer,__name__],self.func_me_color) > return self.buffer > if __name__ == "__main__": > if len(sys.argv) < 1: > print "Usage: %s file"% sys.argv[0] > f=sys.argv[1] > c=csv_parser(f) > print c.bufferp > -- > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > > > > > -- > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list > Do you know that there is a csv module in the standard library already? Thanks, Gary M. Josack From google at mrabarnett.plus.com Fri Dec 12 11:45:02 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 12 Dec 2008 16:45:02 +0000 Subject: Removing None objects from a sequence In-Reply-To: <87ej0dz894.fsf@daycos.com> References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> Message-ID: <4942950E.5030409@mrabarnett.plus.com> Kirk Strauser wrote: > At 2008-12-12T15:51:15Z, Marco Mariani writes: > >> Filip Gruszczy?ski wrote: >> >>> I am not doing it, because I need it. I can as well use "if not elem >>> is None", > >> I suggest "if elem is not None", which is not quite the same. > > So what's the difference exactly? "foo is not None" is actually surprising > to me, since "not None" is True. "0 is True" is False, but "0 is not None" > is True. Why is that? > I suppose that it should really be "not is" (cp "not in"), but Guido chose to follow the English pattern "is not". "not" returns a Boolean (or originally an int) and "is" checks for identity, but the result of "is False" or "is True" is down to implementation details in the interpreter, so you wouldn't write "is not ..." to mean "is (not ...)" anyway, and in practice it's not a problem. From bockman at virgilio.it Wed Dec 31 09:48:50 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: Wed, 31 Dec 2008 15:48:50 +0100 Subject: select.select and socket.setblocking In-Reply-To: <3652a957-eec6-494c-bd37-d150018bc0ed@p2g2000prf.googlegroups.com> References: <495a661d$0$11384$5fc30a8@news.tiscali.it> <495b34d8$0$11387$5fc30a8@news.tiscali.it> <3652a957-eec6-494c-bd37-d150018bc0ed@p2g2000prf.googlegroups.com> Message-ID: <495b8653$0$11383$5fc30a8@news.tiscali.it> < ... > >> Uhm. In my experience, with TCP protocol recv only returned less than >> the required bytes if the remote end disconnects. I always check the > > What if the sending end actually sent less than you asked for ? > > -srp > In blocking mode and with TCP protocol, the recv waits until more bytes are received - mixing up the next message with the previous one and then loosing the 'sync' and being unable to interpretate the received data - or the remote end disconnects. Yes this is bad, and is a good reason why socket receive should be handled in non-blocking mode if you receive data from untrusted sources. But luckily for me, as I said in the other post, I used socket mostly to communicate between specific applications on a private LAN or WAN, so I could afford to ignore the problem. Ciao ---- FB From pruebauno at latinmail.com Thu Dec 4 11:08:31 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Thu, 4 Dec 2008 08:08:31 -0800 (PST) Subject: funny generator behaviour References: Message-ID: <8aca069b-c19c-4c33-9bd6-6171070079c7@t26g2000prh.googlegroups.com> On Dec 4, 8:00 am, Edvin Fuglebakk wrote: > I have written a generator that puzzles me: > > The generator is supposed to create ordered selections of a set of > objects. repetition of objects is allowed and the selections should be > of a size determined by a pramter to the generator. > > Now, if I try to accummulate the generated selections into a list I get > some peculiar behaviour that I hope maybe some of you can help me > understand: > > Help much appreciated > -Edvin > > #straightforward acumulation. Does not give the expected result > >>> d=[] > >>> for f in orderedCombinations([1,2],3): > ... d.append(f) > ... > >>> d > [[1], [2], [1], [2], [1], [2], [1], [2]] > > #accumulating shallow copies of the genereated combinations works: > >>> d=[] > >>> for f in orderedCombinations([1,2],3): > ... d.append(f[:]) > ... > >>> d > [[1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 2, 2], [2, 1, 1], [2, 1, 2], [2, > 2, 1], [2, 2, 2]] > > #The generator: > def orderedCombinations(pool, k): > """ > Generator yielding ordered selections of size k with repetition from > pool. > """ > > if k == 1: > for m in pool: > yield [m] > > if k > 1: > > for m in pool: > for combo in orderedCombinations(pool, k-1): > > #insert and pop to avoid copying entire list > combo.insert(0,m) > yield combo > combo.pop(0) BTW if you search in the fine manual version 2.6 you will find that a slick implementation is already part of the standard library (hint: itertools): def orderedCombinations(pool, k): result = [[]] for poolel in [pool] * k: result = [x+[y] for x in result for y in poolel] return result From 20080915.20.wmcclain at spamgourmet.com Tue Dec 9 11:28:40 2008 From: 20080915.20.wmcclain at spamgourmet.com (Bill McClain) Date: 9 Dec 2008 16:28:40 GMT Subject: StringIO in 2.6 and beyond References: Message-ID: On 2008-12-08, Bill McClain <20080915.20.wmcclain at spamgourmet.com> wrote: > On 2008-12-08, Christian Heimes wrote: > > In this context 'str' means Python 3.0's str type, which is unicode in > > 2.x. Please report the misleading error message. > So this is an encoding problem? Can you give me a hint on how to correct in my > example? I see that io.StringIO() has an encoding parameter, but I'm unclear > what to specify. I still don't have this working. I've been specifying encodings without success. The StringIO example usage in the Python 3.0 documentation here: http://docs.python.org/3.0/library/io.html#io.StringIO gives me the same error on 2.6: #! /usr/bin/env python from __future__ import print_function import io output = io.StringIO() output.write('First line.\n') print('Second line.', file=output) # Retrieve file contents -- this will be # 'First line.\nSecond line.\n' contents = output.getvalue() # Close object and discard memory buffer -- # .getvalue() will now raise an exception. output.close() ./stringio30.py Traceback (most recent call last): File "./stringio30.py", line 7, in output.write('First line.\n') File "/usr/local/lib/python2.6/io.py", line 1487, in write s.__class__.__name__) TypeError: can't write str to text stream -Bill -- Sattre Press History of Astronomy http://sattre-press.com/ During the 19th Century info at sattre-press.com by Agnes M. Clerke http://sattre-press.com/han.html From bearophileHUGS at lycos.com Mon Dec 1 20:09:20 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 1 Dec 2008 17:09:20 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: Jon Harrop: Is so wide cross-posting positive? > 4. Static type checking.< This is a Python newsgroup, you will find less lovers of static typing here :-) >Overall, Mathematica is a whopping 700,000 times slower!< Your Mathematica code is cute, but surely Mathematica isn't designed for that kind of "programing". It's more for symbolic processing or to perform few operations in a very flexible way, so it's more for research and *exploration* and visualization; while more normal programming languages are more to compute a lot of things when you already know what you are doing. > http://www.ffconsultancy.com/languages/ray_tracer/ You can write versions for Python, Psyco, ShedSkin, too, if you want. Bye, bearophile From steve at holdenweb.com Fri Dec 12 11:55:27 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Dec 2008 11:55:27 -0500 Subject: concept of creating structures in python In-Reply-To: <25EDE674-3566-4720-BCEB-6A4D3865C9E2@strout.net> References: <25EDE674-3566-4720-BCEB-6A4D3865C9E2@strout.net> Message-ID: Joe Strout wrote: > On Dec 12, 2008, at 9:00 AM, Steve Holden wrote: > >>> Change the default value of ds_obj here to None. Otherwise, you will >>> certainly confuse yourself (there would be just one default object >>> shared among all instances). >>> >> Joe missed a piece out here. If you change the signature of your >> D.__init__() to read >> >> def __init__(self, dataName='ND', index = 0, ele_obj=None): >> >> then you need to insert the following code at the top of the method: >> >> if ele_obj is None: >> ele_obj = E() > > Yes, if you really need to guarantee that ele_obj is not None, then this > is the way to do it. > > Of course this would mean that you can't get a None ele_obj even by > passing it in explicitly as the parameter value -- if you need to > support that as well, then the solution is a little more complex. > Perhaps best in that case would be to just not give ele_obj any default > value at all, so it becomes a required parameter. > Just for completeness, if you want to be able to pass None then you need to create a sentinel object, usually just an instantiation of object(), and test for identity with that to determine that no argument was provided. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From Scott.Daniels at Acm.Org Sat Dec 27 19:06:42 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 27 Dec 2008 16:06:42 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: Daniel Fetchinson wrote: >.... I have a list to begin with which will be passed to the C function. > I assume converting the list to an array.array and passing that to the C > function doesn't make any difference in terms of speed since the > operation itself will be done in the C function anyway. Right, but why bother to do the conversion in C where you'll have to fiddle with refcounts and error propogation? convert in python, and go to the underlying data in C. --Scott David Daniels Scott.Daniels at Acm.Org From gagsl-py2 at yahoo.com.ar Sun Dec 14 16:46:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 14 Dec 2008 19:46:50 -0200 Subject: Bidrectional Subprocess Communication References: <5b4f4146-ad39-4fe6-9055-e852bd127143@q26g2000prq.googlegroups.com> Message-ID: En Sun, 14 Dec 2008 09:37:38 -0200, Emanuele D'Arrigo escribi?: > On Dec 14, 4:48?am, "Gabriel Genellina" > wrote: >> - you have to close server.stdin when you don't have more data to send. >> The server will see an end-of-file and knows it has to exit the loop. >> Same thing on the client side. > > Hi Gabriel, thanks for modifying the code to make it work. I've just > tried tinkering with it to see how far it would go. On your two > statements above: does this means that any data must be sent in one > batch and then the subprocess must shut down? What I was trying to > simulate is a client/server relationship through a subprocess, where > the server (the subprocess) keeps listening and the client sends data > when it wants to (and eventually viceversa). But when the > server.stdin.close() statement is issued, the pipe is closed for good > and can't be reopened (can it?). No, not at all. You can keep writing things to the pipe - as long as the read side keeps reading, there is no limit on how much data you can send. Just make sure you close the writing side of the pipe when you have no more data to send, to signal the other side it's OK to exit the read loop. >> - you have to wait until the server answers, else it will get a "broken >> pipe" error or similar. > > So, if I want to interrogate the subprocess multiple times I must end > and restart the ListenerThread multiple times then? No, I mean, since your example is bidirectional, the parent process must still be alive and able to read when the subprocess replies. Given this sequence: parent writes "hi sub!" child reads "hi sub!" child writes "hi dad!" parent reads "hi dad!" if the parent just exits after sending "hi sub!", the child will get an error when replying (I think it says "invalid handle" on Windows, "broken pipe" on Linux, or something like this). -- Gabriel Genellina From atagar1 at gmail.com Tue Dec 30 01:30:53 2008 From: atagar1 at gmail.com (Damian Johnson) Date: Mon, 29 Dec 2008 22:30:53 -0800 Subject: Python 3.0 Curses Unicode In-Reply-To: References: Message-ID: It seems as if the curses module in Python 3.0 isn't respecting the system's preferred encoding (utf-8) which was set via: locale.setlocale(locale.LC_ALL, '') The purpose of this was described at the top of ' http://docs.python.org/dev/3.0/library/curses.html#module-curses'. The getlocale function is reporting the proper values ('en_US', 'UTF8') but addstr is clearly not treating it as Unicode - is this a bug? -Damian 2008/12/28 Damian Johnson > Hi, I've switched to Python 3.0 for a new Japanese vocab quizzing > application due to its much improved Unicode support. However, I'm running > into an issue with displaying Unicode characters via curses. In Python 2.x a > simple hello-world looks like: > > #!/usr/bin/python > # coding=UTF-8 > > import curses > import locale > > locale.setlocale(locale.LC_ALL,"") > > def doStuff(stdscr): > message = u"hello ???!" > stdscr.addstr(0, 0, message.encode("utf-8"), curses.A_BLINK) > stdscr.getch() # pauses until a key's hit > > curses.wrapper(doStuff) > > This works. However, when I try to come up with an equivalent for Python > 3.0: > > #!/usr/bin/python > > import curses > import locale > > locale.setlocale(locale.LC_ALL,"") > > def doStuff(stdscr): > message = "hello ???!" > stdscr.addstr(0, 0, message, curses.A_BLINK) > stdscr.getch() # pauses until a key's hit > > curses.wrapper(doStuff) > > It fails (printing gibberish to the console). Anyone have a clue what I'm > doing wrong? Thanks! -Damian > > PS. Is the "# coding=UTF-8" header meaningless in Python 3.0? Also, is > "locale.setlocale(locale.LC_ALL,"")" still necessary for getting curses to > provide Unicode support? > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 17:58:10 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Dec 2008 22:58:10 GMT Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> <5926cb50-e53f-4e9e-8672-b4e29e2280b5@r36g2000prf.googlegroups.com> Message-ID: <0149a9be$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 07:09:27 -0800, bearophileHUGS wrote: > Andreas Waldenburger: >> Whenever has it been a pythonic ideal to "not allow" stuff? You get >> warnings. Everything else is up to you. > > It's a strong source for bugs, especially for newbies, that I have hoped > to see removed from Python3 (my first request of this was years ago). I > was nearly sure to see this wart removed from Python3, and now I hear > it's presents still. I don't understand why they haven't fixed it. "It"? Context please... snipping unnecessarily quoted text is a good thing, but please leave enough context for people to know what you're talking about. I think you're talking about mixed spaces/tabs in the one module. Frankly, I question just how "strong" a source of bugs it really is. Oh, I don't doubt that there are circumstances where it can cause bugs, but I don't remember the last time the solution to some newbie's problem on comp.lang.python was "use spaces or tabs but not both". My gut feeling is that you have to have a fairly unusual set of circumstances before it causes actual bugs. So perhaps nobody on the python-dev team have fixed it yet because nobody cares enough to do the work, or it's unexciting and tedious to fix. Or maybe python-dev *think* they've fixed it, and the fact that it isn't fixed is a bug that needs reporting. > Then this is the third thing I don't like of Python3 (the other two > being the removal of automatic tuple unpacking in function signature and > the wart of literals for empty set/dict). Er, what do you mean? What wart? -- Steven From rcdailey at gmail.com Tue Dec 9 10:31:41 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 9 Dec 2008 07:31:41 -0800 (PST) Subject: 'pretty print' for built in types Message-ID: <051e3a97-b9bc-4a67-8896-93628ca19f59@r15g2000prd.googlegroups.com> Hi, Is there a built in way to 'pretty print' a dict, list, and tuple (Amongst other types)? Dicts probably print the ugliest of them all, and it would be nice to see a way to print them in a readable way. I can come up with my own function to do this, but I don't want to do this if I don't have to. From rt8396 at gmail.com Fri Dec 19 13:44:25 2008 From: rt8396 at gmail.com (r) Date: Fri, 19 Dec 2008 10:44:25 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> Message-ID: <88ff7c46-2b23-49e4-865e-781d23433799@l33g2000pri.googlegroups.com> ~Michael, What?s next down this road of self destruction? Hey guys, forget about about empty parenthesis on a function/method call, we should not have to waste are time typing them? Wait forget about them all together and we will just write Ruby code? Def function arg arg arg arg arg arg ?Yea, that looks good?.insert(sarcasm) Things like forcing empty tuple on function/method calls are what make python so great. Python dumped the C bracket plague, but enforces parenthesis even for a no argument function. But hell, why shouldn?t we have 50 ways to the same thing in Python like Ruby. PS. Don?t discredit Walter just because he is not on the dev team, that don?t mean squat! ~Bearophile, Thanks for your civil approach to this conversation but I must disagree with you on the new string formatting syntax. You said the new syntax is suppost to be easier on the n00b , I say it pollutes a students mind. What is wrong with similarities to C formatting, I find nothing complicated about it. %s (means put a string here) %d (means put a integer here) %f (means put a float here) It does not get any simpler than that, and this will just ease the transition to C programming for this student. Lets not forget how important C is! I always likened Python to my cool uncle who would let me get away with more than my parents-C- but would enforce the important rules. Like Python?s forcing of empty tuple in function calls, that is a good idea. This allows you to clearly see arguments in source code. I like in Python there is only one, or a very minimal number of ways to do something(but usually only one is the best). Ruby is littered with different ways to do the same thing. I think this will be Ruby?s undoing?. And Pythons if we follow down this road. And lets not forget Python forcing of indention, that is Pythons greatest strength! From pruebauno at latinmail.com Thu Dec 18 11:45:21 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Thu, 18 Dec 2008 08:45:21 -0800 (PST) Subject: Is this pythonic? References: <66d058f9-cfe1-4b3c-ab8a-e6e88bb97770@m22g2000vbp.googlegroups.com> Message-ID: <7dc03d4b-4bce-4cc4-b020-681935cf0b0b@m4g2000vbp.googlegroups.com> On Dec 18, 11:08?am, ipyt... at gmail.com wrote: > x.validate_output(x.find_text(x.match_filename > (x.determine_filename_pattern(datetime.datetime.now())))) > > Is it even good programming form? Lisp and Scheme programmers love that style. You can tell by the number of parentheses :-). In Python people usually use an intermediate variable to break things up a bit but the amount of acceptable nesting is a matter of personal style. From grante at visi.com Sun Dec 7 23:27:31 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 07 Dec 2008 22:27:31 -0600 Subject: how to get a beep, OS independent ? References: <6q2sjfFai65qU1@mid.individual.net> Message-ID: On 2008-12-07, Peter Pearson wrote: > On Sun, 07 Dec 2008 00:40:53 +0100, Stef Mientki wrote: >> >> I want to give a small beep, for windows there's message-beep, >> and there seems to be something like " curses" , but that >> package seems to be totally broken in P2.5 for windows. >> >> Any other suggestions ? > > Many people have suggested sending an ASCII 07 to your > terminal window, but sometimes you don't have a terminal > window. Some terminal windows don't beep when they receive a BEL character. Some flash, some do nothing at all -- but that's the user's decision. I believe sending a BEL to stdout is the accepted standard for command-line applications. > Then there's the question of using the sound card versus using > the PC speaker. Assuming the computer has at lease one of the two (some of mine don't). > Too complicated for me. Cross-platform programming is indeed complicated. > I used a kluge: a short C program that beeps the way I want, > in this case using ioctl(fd,KDMKTONE,arg) on /dev/tty0 (this > is Linux). The program has enough privileges to execute even > when run by unprivileged users, and of course can be invoked > by whatever language you're working in. That would seem to make the machine on which the ioctl() call is executed beep (assuming it can beep). What if you're ssh'ed into the machine or running a remote X server? What if the user is deaf? One would presume the intent was to alert the person running the program to some condition that needs attention. If it's a command-line appliction, output a BEL character to stderr. That's the standard way to alert the user. If the user has her terminal configured to do something else (e.g. flash), then that's her decision and you shouldn't try to override it. If it's an X11 application, then use the Xlib call to request that the X server alert the user (usually with a "beep"). I've no idea what one does under Windows or MacOS, but I'm sure they have their "standards" as well. -- Grant From andre.roberge at gmail.com Wed Dec 31 11:37:26 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Wed, 31 Dec 2008 08:37:26 -0800 (PST) Subject: Solved. was: Memory leak problem (while using tkinter) References: Message-ID: <901c3b47-07f8-435d-a889-8cb00314a7e6@d42g2000prb.googlegroups.com> On Dec 31, 12:21?am, Andr? wrote: > I have written a small program (my first Tkinter-based app) to play > around the idea mentioned on > http://rogeralsing.com/2008/12/07/genetic-programming-evolution-of-mo... > and, in doing so, have encountered a memory leak problem. ? I have > seen mentions on the web of using the delete() method of canvas to > prevent such problems - which I have tried to do with limited > success. ?Below is the code I wrote; to run it, you will need a small > image file > (I used the one found onhttp://alteredqualia.com/visualization/evolve/) > that is saved under "mona_lisa.png". > It appears that the problem occurred due to creating drawing "contexts" with aggdraw which became orphaned in some ways. Below is some changes that appear to solve the problem. Perhaps this will be useful to others at some point... Andr? [SNIP] > > class AggDrawCanvas(Canvas): > ? ? def __init__(self, width, height, win): > ? ? ? ? Canvas.__init__(self, win) > ? ? ? ? self.image_id = None > ? ? ? ? self.win = win > ? ? ? ? self._width = width > ? ? ? ? self._height = height > ? ? ? ? self._size = width, height > ? ? ? ? self.config(width=width, height=height+20) > ? ? ? ? self.info = self.create_text(width/2, height+20) > ? ? ? ? self.pack() > ? ? ? ? self.dna = DNA(self._width, self._height) > ? ? ? ? self.mutations = 0 self.img = None > > ? ? def draw_dna(self): > ? ? ? ? img = Image.new("RGBA", self._size, "black") > ? ? ? ? self.context = aggdraw.Draw(img) replace by: if self.img is None: self.img = Image.new("RGBA", self._size, "black") self.context = aggdraw.Draw(self.img) else: brush = aggdraw.Brush((0, 0, 0), opacity=255) self.context.rectangle((0, 0, self._width, self._height), brush) > ? ? ? ? for gene in self.dna.dna: > ? ? ? ? ? ? brush = aggdraw.Brush(tuple(gene[1][0:3]), opacity=gene[1] > [3]) > ? ? ? ? ? ? self.context.polygon(gene[0], brush) > ? ? ? ? self.delete(img) > ? ? ? ? self.redraw() > [SNIP] From python.list at tim.thechases.com Sat Dec 13 11:12:41 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 13 Dec 2008 10:12:41 -0600 Subject: encrypt and descrypt a created file In-Reply-To: References: Message-ID: <4943DEF9.4090506@tim.thechases.com> > open(str(os.sep).join([ > os.getcwd(), > 'applications', > request.application, > 'databases', > table+'.csv']),'w').write(str(db(db[table].id).select ())) > > > How can i encrypt and descrypt the created file above?? Well, as I was recently admonished (and have come to love), the first recommendation is to use the "csv" module for writing CSV files. It deals with oddities like quotation-escaping, and a bunch of other details. However, you want some sort of encryption/decryption method, but you don't specify what type. You can do something simple like def encrypt(s): return s.encode('rot13') def decrypt(s): return s.decode('rot13') f = open(filename, 'wb') f.write(encrypt(content)) f.close() f = open(filename, 'r') content = decrypt(f.read()) f.close() It's not very good encryption though ;-) For better encryption see [1] & [2] for the pycrypto module. It's been a while since I've done anything using this module, but the docs are available for it and the basic premise is the same (encrypt the content before writing, decrypt the content upon reading). It would help to read up on crypto best-practices about storing key-files, password-management, etc. -tkc [1] http://www.pycrypto.org [2] http://www.amk.ca/python/code/crypto.html From lie.1296 at gmail.com Mon Dec 8 06:16:46 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 8 Dec 2008 11:16:46 +0000 (UTC) Subject: Guido's new method definition idea References: <20081207182721.4033466d@usenot.de> Message-ID: On Sun, 07 Dec 2008 18:27:21 +0100, Andreas Waldenburger wrote: > On Sat, 6 Dec 2008 23:21:04 -0800 (PST) Lie wrote: > >> I think we have to test this on newbies. [snip] >> > Now that's talking like a programmer! > > Ideas on how such a survey could be conducted? Anyone? > > >> If this dead horse is revived because of that reason, then I'd go with >> changing the error message to something that is less confusing to >> newbies[1]. > + googol > > >> I remember being tripped with the (thinking that python miscounted the >> number of argument) when I was new. This has the advantage of backward >> compatibility and no syntax change, just less misleading error message. >> >> [1] anything could work, but I like this one: (c is an instance of >> class C) >> if the code is: c.foo(...), Error: "TypeError: c.foo() takes exactly 3 >> argument" >> while if the code is: C.foo(...), Error: "C.foo() takes exactly 4 >> arguments" >> You can implement c.foo as a curried C.foo function, catch C.foo's >> TypeError exception then reraise it as c.foo exception. > I'm not sure that I'd find that less confusing. Because a c.foo() *does* > take four arguments, not three. It's just that the first one is implicit > (Right?). It's not implicit, we explicitly pass c (the object instance), although not in the argument list. So c.foo takes 3 arguments while C.foo takes 4 arguments. In other words: from functools import partial c = C() -> c.attr = partial(C.attr, c) Note the error message I gave: "TypeError: c.foo() takes exactly 3 arguments" "TypeError: C.foo() takes exactly 4 arguments" There are two differences there, not only one claims to accept three and the other 4 arguments, but also the capitalization of c/C. Here is a clearer example: inst = cls() "TypeError: inst.foo() takes exactly 3 arguments" "TypeError: cls.foo() takes exactly 4 arguments" for comparison, python's current (2.5) error message is: "TypeError: foo() takes exactly 4 arguments" in addition, with this proposal we'll know how foo is being called. The following is a quick and dirty implementation of such error message. Note: There are still some unresolved problems though: 1. instance.[func name] is hardcoded, as I don't know how to get the instance's name from the instance creation itself 2. Class Invoking from class gives TypeError: foo()... instead of TypeError: Class.foo()... 3. most definitely not to be used on real application from types import MethodType import re errmess = re.compile(r'(.*?) (.*?) (\d*) (arguments?) \((\d*) given\)') def usenewexc(obj): def wrap(f): def wrap_(*args, **kargs): try: print args, kargs return f(*args, **kargs) except TypeError, e: re_mess = errmess.match(e.message) fname = re_mess.group(1) interm = re_mess.group(2) if re_mess.group(3) != '1' else 'takes' reqargs = int(re_mess.group(3)) - 1 if re_mess.group(3) ! = '1' else 'no' argue_s = re_mess.group(4) if re_mess.group(3) != '1' else 'arguments' givenargs = int(re_mess.group(5)) - 1 raise TypeError('%s.%s %s %s %s (%s given)' % ('instance', fname, interm, reqargs, argue_s, givenargs)) return wrap_ for attrname in dir(obj): attr = obj.__getattribute__(attrname) if type(attr) == MethodType: obj.__setattr__(attrname, wrap(attr)) return obj class A(object): def foo(self): print '' pass a = usenewexc(A()) A.foo(a, 2) > How about: > > "TypeError: c.foo() takes exactly 3 arguments in addition to the > implicit instance reference." > > or > > "TypeError: c.foo() takes exactly 4 arguments (5 given, including the > implicit instance reference)" > > ... or something less kludgy in that general direction. This would > explain exactly what is wrong. > > /W > > -- > My real email address is constructed by swapping the domain with the > recipient (local part). From pythonsky at sky.com Thu Dec 11 09:27:21 2008 From: pythonsky at sky.com (garywood) Date: Thu, 11 Dec 2008 14:27:21 -0000 Subject: just got the g1 Message-ID: Hi Just got the G1, is their any way to get python running on the andriod platform ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Wed Dec 3 03:02:21 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 03 Dec 2008 09:02:21 +0100 Subject: porting modules to Python 3.0 In-Reply-To: References: <8f60c779-f1ec-4127-b173-f174c016aa96@a12g2000yqm.googlegroups.com> <4936255D.6000509@v.loewis.de> Message-ID: <49363d0d$0$3653$9b622d9e@news.freenet.de> > In one has both 2.x and 3.0 installed, would it easy to install 'lib.py' > for both? It's currently not possible to install something for 2.x; you have to specifically install it for every value of x (e.g. 2.5 or 2.6). It's the same for 3.0: you have to install it separately. Doing so is fairly easy. You just run "setup.py install" multiple times (or download and install prebuilt binaries if available). Regards, Martin From skip.montanaro at gmail.com Tue Dec 9 21:12:08 2008 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Tue, 9 Dec 2008 18:12:08 -0800 (PST) Subject: Test posting #2 - please ignore References: Message-ID: <7378d7c8-e480-492a-aeb2-99fba2eae188@v4g2000yqa.googlegroups.com> Still testing (posted via google groups)... S From kirk at daycos.com Mon Dec 15 15:02:42 2008 From: kirk at daycos.com (Kirk Strauser) Date: Mon, 15 Dec 2008 14:02:42 -0600 Subject: tricky nested list unpacking problem References: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> Message-ID: <87ljuhxl3x.fsf@daycos.com> At 2008-12-15T19:06:16Z, Reckoner writes: > The problem is that I don't know ahead of time how many lists there are or > how deep they go. In other words, you could have: Recursion is your friend. Write a function to unpack one "sublist" and call itself again with the new list. For instance, something like: def unpack(pattern): # Find the first subpattern to replace # [...] results = [] for number in subpattern: results.append(pattern.replace(subpattern, number)) return results Calling unpack([1,2,3,[5,6],[7,8,9]]) would look cause it to call unpack([1,2,3,5,[7,8,9]]) and unpack([1,2,3,6,[7,8,9]]), compile the results, and return them. -- Kirk Strauser The Day Companies From castironpi at gmail.com Thu Dec 18 06:52:52 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 18 Dec 2008 03:52:52 -0800 (PST) Subject: C API and memory allocation References: <59352942-e976-4ef4-bc40-c8953df0a792@c36g2000prc.googlegroups.com> Message-ID: <0d35b640-71ad-4cde-8869-74878b2f3981@r36g2000prf.googlegroups.com> On Dec 18, 5:09?am, Ivan Illarionov wrote: > On 18 ???, 03:51, Aaron Brady wrote: > (snip) > > > How did you get a reference to the original > > string object, with which to increment its reference count? > > Use the "O!" format ?instead of "s": > PyObject *pystr; > ... PyArg_ParseTuple(args, "O!", &PyStringObject, &pystr) ... edit: &PyString_Type > > Then you can use PyString_AS_STRING explicitly, and control ref. > counts yourself. > > > How do you know its length to copy it into your own buffer? > > Use the "s#" format, as Gabriel has said. > > Ivan I see. Do I read correctly that 's' is only useful when the argument's position is known? Otherwise you can't know its length or change its reference count. From skip at pobox.com Sat Dec 27 18:06:06 2008 From: skip at pobox.com (skip at pobox.com) Date: Sat, 27 Dec 2008 17:06:06 -0600 Subject: multiply each element of a list by a number In-Reply-To: References: <4955e7be$0$4066$ba4acef3@news.orange.fr> Message-ID: <18774.46302.839127.228495@montanaro-dyndns-org.local> Colin> ... perhaps faster than numpy: ... For extremely short lists, but not for much else: % for n in 1 10 100 1000 10000 100000 ; do > echo "len:" $n > echo -n "numpy: " > python -m timeit -s 'import numpy ; a = numpy.array(range('$n'))' 'a*3' > echo -n "list: " > python -m timeit -s 'a = range('$n')' '[3*x for x in a]' > done len: 1 numpy: 100000 loops, best of 3: 11.7 usec per loop list: 1000000 loops, best of 3: 0.698 usec per loop len: 10 numpy: 100000 loops, best of 3: 11.7 usec per loop list: 100000 loops, best of 3: 2.94 usec per loop len: 100 numpy: 100000 loops, best of 3: 12.1 usec per loop list: 10000 loops, best of 3: 24.4 usec per loop len: 1000 numpy: 100000 loops, best of 3: 15 usec per loop list: 1000 loops, best of 3: 224 usec per loop len: 10000 numpy: 10000 loops, best of 3: 41 usec per loop list: 100 loops, best of 3: 2.17 msec per loop len: 100000 numpy: 1000 loops, best of 3: 301 usec per loop list: 10 loops, best of 3: 22.2 msec per loop This is with Python 2.4.5 on Solaris 10. YMMV. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From castironpi at gmail.com Mon Dec 29 21:18:23 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 18:18:23 -0800 (PST) Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <40b1b762-459b-4d6f-91f0-0a6e68d233ae@a26g2000prf.googlegroups.com> <4d396242-13c9-4318-97ba-99f18564fbc5@o4g2000pra.googlegroups.com> <016969d3$0$6988$c3e8da3@news.astraweb.com> Message-ID: <28e76735-f749-4452-8aa2-18e8f0e9e499@k1g2000prb.googlegroups.com> On Dec 29, 7:00?pm, Steven D'Aprano wrote: > On Mon, 29 Dec 2008 05:31:17 -0800, Aaron Brady wrote: > > One style of coding I heard about once only permits returns at the end > > of a function. ?It claims it makes it easier to see the function as a > > mathematical object. > > That's silly. You treat the function as a black box: input comes in, and > output comes out. You have no idea of what happens inside the black box: > it could loop a thousand times, take 150 different branches, or take one > of 37 different exit points. From the outside, it's still exactly like a > mathematical object. Internal complexity is irrelevant. This is why > mathematicians can perform algebra on complicated functions like Bessel's > function (of the first or second kind), without needing to care that > actually calculating Bessel's function is quite tricky. > > What I think the one-return-per-function style is aiming at is that it is > (sometimes) easier to analyse the internals of the function if there are > few branches. The more complicated branches you have, the harder it is to > analyse the function. Early exits on their own are not the cause of the > complexity: it's the number of branches leading to the early exit that > causes the problem. You'd think they would have noticed that. Eliminating early exits doesn't change the number of branches! > Avoiding early exits is an over-reaction to the Bad Old Days of spaghetti > code. But used wisely, early exists can simplify, not complicate, code. To make your case, you don't even need to prove that a wise early exit can simplify. You just need that an early exit can simplify. (The conclusive case is the early exit is better. For that, it's sufficient but not necessary to show that simplicity is your reader's highest priority. What's instructive about that is the counterexample: when is simpler not better? (Not rhetorical. Or, if never, then it's the top priority and consistent with every top priority, if my calculations are correct; but it remains to show that early exits can simplify.) snip better simpler > The second version has double the number of lines of code of the first. > It introduces an extra variable "found_item" and two extra if blocks. I > don't think the claim that the version with an early exit is more > complicated than the version without can justified. In a lab report, this is the part where the author would be arguing, "And the object accelerated at 9.8 m/s^2, which proves our hypothesis." I think you're showing that early exits can simplify, but you're bringing in more factors. I think you're trying to say that less lines of code is simpler, and less variables is simpler. Those lack proofs. You need: M: Less lines of code is simpler. m: Simpler is always better. C: Less lines of code is better. Or something. But no amount of thrashing, bludgeoning, wibbling, whimpering, or beating children with blunt objects, is going to change your reader's knowledge of good. Only experience is. Fine fine, so leather belts are bad. That doesn't make fewer lines of code good. However, the burden of proof is (definitely IMO) on the people that are unilaterally opposed to early returns. They need: M: Early exits are never simpler. m: Simpler is always better. C: Early exits are never better. Oddly enough, you share a minor premise. From sjmachin at lexicon.net Fri Dec 26 18:39:46 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 26 Dec 2008 15:39:46 -0800 (PST) Subject: Is there a function to remove escape characters from a string ? References: <0163882f$0$6988$c3e8da3@news.astraweb.com> Message-ID: <5a29b62a-c38f-409b-8887-6259ad072bf5@w1g2000prk.googlegroups.com> On Dec 27, 12:05?am, Stef Mientki wrote: > Yep, chr(254), because it's not in the human range of characters > and it's accepted by windows ini-files. >>> import unicodedata as ucd >>> for i in (0,1,2,3,4,7,8): ... s = chr(254) ... enc = 'cp125' + str(i) ... try: ... u = s.decode(enc) ... except UnicodeDecodeError: ... continue ... print enc, 'U+%04X' % ord(u), ucd.name(u) ... cp1250 U+0163 LATIN SMALL LETTER T WITH CEDILLA cp1251 U+044E CYRILLIC SMALL LETTER YU cp1252 U+00FE LATIN SMALL LETTER THORN cp1253 U+03CE GREEK SMALL LETTER OMEGA WITH TONOS cp1254 U+015F LATIN SMALL LETTER S WITH CEDILLA cp1257 U+017E LATIN SMALL LETTER Z WITH CARON cp1258 U+20AB DONG SIGN Either you have a strange and narrow definition of "human", or you are so brave as to cheerfully insult (inter alia) Romanians, Russians, Icelanders, Greeks, Turks, Czechs, Estonians, Finns, Slovaks, Slovenians, and Vietnamese :-) From arnodel at googlemail.com Sun Dec 14 15:35:09 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 14 Dec 2008 20:35:09 +0000 Subject: package structure? References: Message-ID: Torsten Mohr writes: > Hi, > > in a package i'd like to have a structure like this: > > Files end with ".py", others are directories: > > mod > __init__.py # sets __all__ = ['smod1'] > smod1.py # contains AClass() > smod1 > __init__.py # sets __all__ = ['abc', 'def'] > abc.py > def.py > > So i can now do: > > import mod.smod1.abc > import mod.smod1 > > > But functions/classes in smod1.py are not found: > > a = mod.smod1.AClass() > > I know this is somehow ambiguous, but i wonder how else i can make > "mod" have subpackages and modules. > > I wonder how i can make AClass() known in that package. > > > Thanks for any hints, > Torsten. Why don't you put the contents of smod1.py in mod/smod1/__init__.py? It'll work this way. Or you can put smod1.py within mod/smod1 and put from smod1 import * in mod/smod1/__init__.py HTH -- Arnaud From sturlamolden at yahoo.no Fri Dec 12 09:17:43 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 06:17:43 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> Message-ID: <8156b37b-d1f6-4142-ad6e-8488c95b6592@z28g2000prd.googlegroups.com> On Dec 12, 3:04 pm, Luis M. Gonz?lez wrote: > Why don't you guys google a little bit to know what's being done to > address python's "slowness"?? Nothing is being done, and woth Py3k it got even worse. > It has been mentioned in this thread the pypy project (isn't it enough > for you??) > Other hints: shedskin, psyco, pyrex... None of those projects addresses inefficacies in the CPython interpreter, except for psyco - which died of an overdose PyPy. PyPy is interesting if they ever will be able to produce something useful. They have yet to prove that. Even if PyPy can come up with a Python JIT, they will still be decades behind the technologies of Strongtalk and Java. That is the problem with reinventing the wheel all over again. Not to forget LLVM and Parrot which also will support Python frontends. From ethan at stoneleaf.us Wed Dec 10 18:26:47 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 10 Dec 2008 15:26:47 -0800 Subject: internal circular class references Message-ID: <49405037.90809@stoneleaf.us> Greetings List! I'm writing a wrapper to the datetime.date module to support having no date. Its intended use is to hold a date value from a dbf file, which can be empty. The class is functional at this point, but there is one thing I would like to change -- datetime.date.max and datetime.date.min are class attributes of datetime.date, and hold datetime.date values. At this point I have to have two lines outside the actual class definition to do the same thing, e.g.: class NullDate(object): "adds null capable DateTime.Date constructs" __slots__ = ['_date'] def __new__(cls, date='', month=0, day=0): nulldate = object.__new__(cls) nulldate._date = "" . . . return nulldate def __getattr__(self, name): if self: attribute = self._date.__getattribute__(name) return attribute else: if callable(dt.date.__dict__[name]): return int else: return 0 def __nonzero__(self): if self._date: return True return False @classmethod def fromordinal(cls, number): if number: return cls(dt.date.fromordinal(number)) else: return cls() NullDate.max = NullDate(dt.date.max) NullDate.min = NullDate(dt.date.min) How can I move those last two lines into the class definition so that: 1) they are class attributes (not instance), and 2) they are NullDate type objects? ~ethan~ From george.sakkis at gmail.com Thu Dec 4 12:57:20 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 4 Dec 2008 09:57:20 -0800 (PST) Subject: Overriding a method at the instance level on a subclass of a builtin type References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> Message-ID: On Dec 4, 12:31?pm, Arnaud Delobelle wrote: > "Zac Burns" writes: > > The class method seems to be the most promising, however I have more > > 'state' methods to worry about so I might end up building new classes > > on the fly rather than have a class per permutation of states! Now the > > code isn't quite as clear as I thought it was going to be. > > > It seems unfortunate to me that methods are always looked up on the > > class for new style objects. Was this done for speed reasons? > > It's only special methods such as __getitem__, ... > > You can override normal method on a per-object basis just by adding a > callable attribute with its name to the object: > > >>> class A(object): > > ... ? ? def foo(self): print 'A.foo' > ...>>> a = A() > >>> a.foo() > A.foo > >>> def a_foo(): print 'a.foo' > ... > >>> a.foo = a_foo > >>> a.foo() Note that the overriden "method" here is a plain function; it doesn't take self as the first argument. If you want to bind it to a callable that expects the first argument to be self, you have to bind explicitly self to the object: >>> def a_foo(self): print 'a.foo' >>> a.foo = a_foo >>> a.foo() TypeError: a_foo() takes exactly 1 argument (0 given) >>> from functools import partial >>> a.foo = partial(a_foo,a) >>> a.foo() a_foo George From rdmurray at bitdance.com Fri Dec 5 10:15:02 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Fri, 5 Dec 2008 10:15:02 -0500 (EST) Subject: pretty strange behavior of "strip" In-Reply-To: References: <4938693F.6090709@yahoo.ca> Message-ID: On Thu, 4 Dec 2008 at 20:54, Terry Reedy wrote: >> 'toc.html' >> > > > test[4].strip('.html') >> 'oc' >> >> Can't figure out what is going on, really. > > What I can't figure out is why, when people cannot figure out what is going > on with a function (or methods in this case), they do not look it up the doc. > (If you are an exception and did, what confused you?) Can you enlighten me? I'm a little embarrassed to admit this, since I've been using python for many years, but until I read these posts I did not understand how strip used its string argument, and I _have_ read the docs. I can't tell you what confused the OP, but I can tell you what confused me. I have often wished that in 'split' I could specify a _set_ of characters on which the string would be split, in the same way the default list of whitespace characters causes a split where any one (or more) of them appears. But instead the string argument is a multi-character separator. (Which is sometimes useful and I wouldn't want to lose the ability to specify a multi-character separator!) My first experience in using the string argument was with split, so when I ended up using it with strip, by analogy I assumed that the string passed to strip would also be a multi-character string, and thus stripped only if the whole string appeared exactly. Reading the documentation did not trigger me reconsider that assumption. I guess I'm just lucky that I haven't run into any bugs (but I think I've used the string argument to strip only once or twice in my career). It would be lovely if both the split and strip methods would have a second string argument that would use the string in the opposite sense (as a set for split, as a sequence match for strip). In the meantime the docs could be clarified by replacing: the characters in the string will be stripped with all occurrences of any of the characters in the string will be stripped --RDM PS: the OP might want to look at th os.path.splitext function. From invalid at invalid Mon Dec 15 11:07:13 2008 From: invalid at invalid (Grant Edwards) Date: Mon, 15 Dec 2008 10:07:13 -0600 Subject: 1 or 1/0 doesn't raise an exception References: <49446E39.6020807@tim.thechases.com> Message-ID: On 2008-12-14, Peter Otten <__peter__ at web.de> wrote: > Grant Edwards wrote: > >> Short circuit evaluation of booleans is very common (and has >> been for decades), so I don't know why people would expect >> something else. > > Visual Basic ;) I should have known... -- Grant Edwards grante Yow! I'm using my X-RAY at VISION to obtain a rare visi.com glimpse of the INNER WORKINGS of this POTATO!! From bearophileHUGS at lycos.com Mon Dec 1 19:43:18 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 1 Dec 2008 16:43:18 -0800 (PST) Subject: optimization References: Message-ID: <6672532a-f162-4717-b0bb-c613214b57db@d32g2000yqe.googlegroups.com> Robert Kern: >I only expect functions to be defined inside of functions if they are going to use lexical scoping for some reason.< There are other reasons to nest functions. One of them is to represent logical nesting of some functionality. So you will find some exceptions to your self-created rule :-) Bye, bearophile From jonas.esp at googlemail.com Mon Dec 1 13:17:00 2008 From: jonas.esp at googlemail.com (Kless) Date: Mon, 1 Dec 2008 10:17:00 -0800 (PST) Subject: Chmod to a group only Message-ID: How to chmod a file to: o-rwx ? (to change only the others mode) os.chmod(fname, ) I was reading this [1], but the truth is that anything as 'S_IRUSR' doesn't help enought. [1] http://www.python.org/doc/2.5.2/lib/os-file-dir.html From rvncerr at gmail.com Thu Dec 25 01:00:01 2008 From: rvncerr at gmail.com (Raven) Date: Wed, 24 Dec 2008 22:00:01 -0800 (PST) Subject: Easy-to-use Python GUI References: Message-ID: <7598a48c-fe14-42da-94a9-645d73ca40bf@s37g2000vbp.googlegroups.com> On 25 ???, 06:47, "Joel Koltner" wrote: > Is there an easy-to-use, "function"-based cross-platform GUI toolkit for > Python out there that's a little more sophisticated than EasyGui? ?EasyGui > looks good, but it's a little more restrictive than what I'd like to have, yet > I'm (stubbornly :-) ) resistant to stepping up to a "full service" GUI toolkit > such as pyGTK or wxPython where it's all about event loops and callbacks and > you need to start planning how the GUI affects the overall program flow rather > than just using a "forms" (or "Wizard")-type approach where you put up a few > dialogs, users fill in some variables, and your program just sits around > waiting until "OK" or "Cancel" is clicked. > > One approach that I like comes from SAX BASIC/WinWrap, which is more or less a > clone of Microsoft's Visual BASIC for Applications, but they (apparently) > wanted everything to still be human-readable, so they have a simple GUI > ("form") builder that generates code that looks like this: > > --- > > ?Begin Dialog UserDialog 850,497,"Export Control" ' %GRID:10,7,1,1 > > ? GroupBox 20,7,360,217,"Drill File Generation",.GroupBox1 > ? CheckBox 40,35,130,14,"Output drill file(s)",.genDrill > ? Text 40,63,270,28,"Identify via layers as any that contain this text in > their names:",.Text > ? TextBox 40,98,220,21,.viaLayerName > ? Text 40,140,100,14,"Output method:",.Text8 > ? DropListBox 160,140,180,21,DrillStyle(),.drillStyle > ? Text 40,175,130,28,"Select drill table units:",.Text2 > ? ListBox 200,175,120,28,unitNames(),.unitName > > ? OKButton 310,469,90,21 > ? CancelButton 410,469,90,21 > > ?End Dialog > > ' GUI builder generates or modifies everything above, but can also be edited > by hand > ' You write the following code... > > ?Dim dlg As UserDialog > > ?dlg.genDrill = 1 > ?ReDim DrillStyle(1) > ?DrillStyle(0) = "All Via Layers In One File" > ?DrillStyle(1) = "One File Per Via Layer" > ?dlg.drillStyle = 1 > > ?func=Dialog(dlg) > > --- > > This is pretty darned easy for me understand and modify either by hand or with > the GUI builder. ?Still, it's quite powerful, since it supports all the common > GUI elements (text, group boxes, checkboxes, drop-down lists, text boxes, > buttons, etc.). ?This is about the level of sophistication I'm looking for. > > Anything like this for Python? > > Thanks, > ---Joel Try PyScripter :) http://mmm-experts.com/Products.aspx?ProductId=4 From upton at virginia.edu Mon Dec 22 12:40:55 2008 From: upton at virginia.edu (Dan Upton) Date: Mon, 22 Dec 2008 12:40:55 -0500 Subject: stable algorithm with complexity O(n) In-Reply-To: References: <0155aef3$0$6988$c3e8da3@news.astraweb.com> <015612ac$0$20639$c3e8da3@news.astraweb.com> <52cfb77e-4baf-4fba-8eac-cc6c7ddb5be5@k1g2000prb.googlegroups.com> <5504f9ac0812150828m14f6999ak6112c5975042dc88@mail.gmail.com> <1ffd301f-16d3-4dc7-988c-7741d658ca10@z28g2000prd.googlegroups.com> Message-ID: <5504f9ac0812220940o7326b2f6p77f9b5bb86a2ed11@mail.gmail.com> On Mon, Dec 22, 2008 at 12:29 PM, wrote: > On Dec 15, 10:00 pm, "cmdrrickhun... at yaho.com" > wrote: >> It can be proven that you cannot sort an arbitrarily large set of >> numbers, given no extra information, faster than O(n log n). > > Cormen Leiserson and Rivest, "Algorithms", have a short clear chapter > on > "Sorting in linear time": > " ... counting sort, radix sort and bucket sort ... use operations > other than comparisons. > Consequently, the Omega( n lg n ) lower bound does not apply to > them." > But the key here is "given no extra information." Your examples of non-comparison sorts require extra information, such as knowledge about the possible range the numbers can take on. From deets at nospam.web.de Wed Dec 24 11:35:13 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 24 Dec 2008 17:35:13 +0100 Subject: SyntaxError: encoding problem: with BOM In-Reply-To: <400f176b-bd9a-4f26-b01b-1aa7c7dcf5ac@z6g2000pre.googlegroups.com> References: <6res8tF1do1sU1@mid.uni-berlin.de> <400f176b-bd9a-4f26-b01b-1aa7c7dcf5ac@z6g2000pre.googlegroups.com> Message-ID: <6rf6m1F1e0f8U1@mid.uni-berlin.de> NoName schrieb: > On 25 ???, 00:37, "Diez B. Roggisch" wrote: >> NoName schrieb: >> >>> i have 1.py in cp866 encoding: >>> # -*- coding: cp866 -*- >>> print ("ff") >>> It's not work in Python 3.0 >>> Error: >>> File "", line 1 >>> SyntaxError: encoding problem: with BOM >>> what's wrong? >> I can only guess, but just because you write the coding-header that >> doesn't mean that the editor you use does actually *use* that encoding. >> What I presume it does is to use utf-8, and write that stupid BOM >> microsoft uses for denoting utf-8-content as first byte. Try using a >> different editor, or alter it's settings to really use your desired >> encoding. >> >> Diez > > I used Far Manager editor. and it *really* used cp866 > I can print hex dump of source file. > I don't want to use UTF-8 for py-file! How about you show us the python file in question? diez From sjmachin at lexicon.net Tue Dec 30 16:54:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 30 Dec 2008 13:54:34 -0800 (PST) Subject: Parsing Excel spreadsheets References: <6a54de23-bea4-40c7-ad7c-22c6eba4bd8a@z6g2000pre.googlegroups.com> <452bfdbc-b6e2-487d-9590-018a414b36a1@s9g2000prg.googlegroups.com> Message-ID: On Dec 31, 5:48?am, Mike Driscoll wrote: > On Dec 30, 10:07?am, "andyh... at gmail.com" wrote: > > > Hi, > > > Can anybody recommend an approach for loading and parsing Excel > > spreadsheets in Python. Any well known/recommended libraries for this? > > > The only thing I found in a brief search was http://www.lexicon.net/sjmachin/xlrd.htm, > > but I'd rather get some more input before going with something I don't > > know. > > > Thanks, > > Andy. > > If you need complete control of Excel, then you'll probably have to > use COM (see Mark Hammond's PyWin32 package). Otherwise, the > suggestions by the others will work. For avoidance of doubt, the OP should presume that you mean the *nett* suggestions by the others i.e. after Tino struck out pyExcelerator. From prabhu.ranjith at gmail.com Sun Dec 7 11:12:53 2008 From: prabhu.ranjith at gmail.com (ranjith) Date: Sun, 7 Dec 2008 08:12:53 -0800 (PST) Subject: @ Start learning through internet @ Message-ID: visit as at www.tiketin.blogspot.com You can learn all the computer languages from your home itself now. Online study. Visit www.tiketin.blogspot.com to start learning through internet and to clear your computer doubts. From clp at rebertia.com Wed Dec 3 22:52:12 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 3 Dec 2008 19:52:12 -0800 Subject: RELEASED Python 3.0 final In-Reply-To: References: Message-ID: <47c890dc0812031952r6d2adbfav20fde92431443751@mail.gmail.com> On Wed, Dec 3, 2008 at 7:47 PM, Daniel Fetchinson wrote: >> On behalf of the Python development team and the Python community, I >> am happy to announce the release of Python 3.0 final. >> >> Python 3.0 (a.k.a. "Python 3000" or "Py3k") represents a major >> milestone in Python's history, and was nearly three years in the >> making. This is a new version of the language that is incompatible >> with the 2.x line of releases, while remaining true to BDFL Guido van >> Rossum's vision. Some things you will notice include: >> >> * Fixes to many old language warts >> * Removal of long deprecated features and redundant syntax >> * Improvements in, and a reorganization of, the standard library >> * Changes to the details of how built-in objects like strings and >> dicts work >> * ...and many more new features >> >> While these changes were made without concern for backward >> compatibility, Python 3.0 still remains very much "Pythonic". >> >> We are confident that Python 3.0 is of the same high quality as our >> previous releases, such as the recently announced Python 2.6. We will >> continue to support and develop both Python 3 and Python 2 for the >> foreseeable future, and you can safely choose either version (or both) >> to use in your projects. Which you choose depends on your own needs >> and the availability of third-party packages that you depend on. Some >> other things to consider: >> >> * Python 3 has a single Unicode string type; there are no more 8-bit >> strings >> * The C API has changed considerably in Python 3.0 and third-party >> extension modules you rely on may not yet be ported >> * Tools are available in both Python 2.6 and 3.0 to help you migrate >> your code >> * Python 2.6 is backward compatible with earlier Python 2.x releases >> >> We encourage you to participate in Python 3.0's development process by >> joining its mailing list: >> >> http://mail.python.org/mailman/listinfo/python-3000 >> >> If you find things in Python 3.0 that are broken or incorrect, please >> submit bug reports at: >> >> http://bugs.python.org/ >> >> For more information, links to documentation, and downloadable >> distributions, see the Python 3.0 website: >> >> http://www.python.org/download/releases/3.0/ >> >> Enjoy, >> - -Barry >> >> Barry Warsaw >> barry at python.org >> Python 2.6/3.0 Release Manager >> (on behalf of the entire python-dev team) > > uname -a > > Linux fetch 2.6.23.1-42.fc8 #1 SMP Tue Oct 30 13:18:33 EDT 2007 x86_64 > x86_64 x86_64 GNU/Linux > > tar xzvf Python-3.0.tgz > cd Python-3.0 > ./configure > make > > Failed to find the necessary bits to build these modules: > _tkinter Do you have Tcl/Tk and their dev libs installed? Tkinter is based on Tcl/Tk. Also, that error isn't fatal, it just means that Tkinter won't be installed because it can't find the libs. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > To find the necessary bits, look in setup.py in detect_modules() for > the module's name. > > > Cheers, > Daniel > > > > > -- > Psss, psss, put it down! - http://www.cafepress.com/putitdown > -- > http://mail.python.org/mailman/listinfo/python-list > From alexoplocatie at gmail.com Wed Dec 17 05:39:10 2008 From: alexoplocatie at gmail.com (aka) Date: Wed, 17 Dec 2008 02:39:10 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> Message-ID: Due to being in a hurry I didn't paste correctly (sorry). The intention is to put values of column 1 ("id") in the roles list, therefore appending within the loop, to fill a session var. The complete code is: roles = [] inp = 'C:/temp/test.csv' try: fp = open(inp, 'rb') reader = csv.reader(fp, dialect='excel', delimiter=';') for r in reader: roles.append(r) ## ultimately should be something like r.id or r[0] ## first row of csv file should be skipped because of column names except: msg = 'Something's wrong with the csv.reader' return dict(file=inp,roles=str(roles)) The roles list isn't populated at all :( From google at mrabarnett.plus.com Fri Dec 5 20:05:17 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 06 Dec 2008 01:05:17 +0000 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: <7c150038-3c2d-4c3c-bb1a-66c8fde57d22@40g2000prx.googlegroups.com> References: <5u8o06xbqf.ln2@joeserver.homelan.net> <0149b28c$0$20670$c3e8da3@news.astraweb.com> <7c150038-3c2d-4c3c-bb1a-66c8fde57d22@40g2000prx.googlegroups.com> Message-ID: <4939CFCD.2030908@mrabarnett.plus.com> John Machin wrote: > On Dec 6, 10:35 am, Steven D'Aprano cybersource.com.au> wrote: >> On Fri, 05 Dec 2008 12:00:59 -0700, Joe Strout wrote: >>>> So UTF-16 has an explicit EOF marker within the text? >>> No, it does not. I don't know what Terry's thinking of there, but text >>> files do not have any EOF marker. They start at the beginning >>> (sometimes including a byte-order mark), and go till the end of the >>> file, period. >> Windows text files still interpret ctrl-Z as EOF, or at least Windows XP >> does. Vista, who knows? > > This applies only to files being read in an 8-bit text mode. It is > inherited from MS-DOS, which followed the CP/M convention, which was > necessary because CP/M's file system recorded only the physical file > length in 128-byte sectors, not the logical length. It is likely to > continue in perpetuity, just as standard railway gauge is (allegedly) > based on the axle-length of Roman chariots. > The chariots in question were drawn by 2 horses, so the gauge is based in the width of a horse. :-) > None of this is relevant to the OP's problem; his file appears to have > been truncated rather than having spurious data appended to it. From python-url at phaseit.net Tue Dec 16 15:39:10 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Tue, 16 Dec 2008 20:39:10 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Dec 16) Message-ID: QOTW: "... Python isn't a major software company - it's better!" - David LeBlanc `timeit` is the right tool to measure execution time of code snippets: http://groups.google.com./group/comp.lang.python/t/9f35d4bde7304ab7/ "Intentionally backward non-compatible" 3.0 is surely the biggest news of the week, or perhaps year: http://www.01net.com/editorial/399456/python-mue-en-une-v3-plus-coherente-mais-retro-incompatible/ Functions and scope explained to beginners: http://groups.google.com./group/comp.lang.python/t/760155a8e7bfd567/ Several experienced pythonistas help improve a beginner's game: http://groups.google.com./group/comp.lang.python/t/3fe51de743b183e5/ Duck typing helps to write a simple NullDate class: http://groups.google.com./group/comp.lang.python/t/e9bf920d5a3bf894/ How to prevent access to certain methods? http://groups.google.com./group/comp.lang.python/t/9910be8b800b66df/ Exploring bidirectional communication of two processes, first using sockets, later using pipes: http://groups.google.com./group/comp.lang.python/t/d90fa17612e6878b/ http://groups.google.com./group/comp.lang.python/t/7a29b036207feee2/ Determining what encoding a certain filename uses may be hard (or even impossible): http://groups.google.com./group/comp.lang.python/t/9274ac2431bee2f3/ Displaying unicode in 3.0: repr(), str(), ascii(), and unprintable characters: http://groups.google.com./group/comp.lang.python/t/a320c6a5d2ce5607/ http://groups.google.com./group/comp.lang.python/t/322a48591c81f089/ When working with Numpy arrays and others, operators like '=3D=3D' or 'in' may present non-obvious behaviour: http://groups.google.com./group/comp.lang.python/t/1fead6e2738bf4f5/ Homework, sorting, complexity, and magnetic monopoles (?): http://groups.google.com./group/comp.lang.python/t/d7bfec4913b2d616/ ======================================================================== 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 Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From manu3d at gmail.com Sat Dec 13 10:03:17 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Sat, 13 Dec 2008 07:03:17 -0800 (PST) Subject: Bidirectional Networking References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <6qeht0Fc3541U1@mid.individual.net> <782258db-2bdc-45a7-8d8f-7a036d574985@t26g2000prh.googlegroups.com> Message-ID: <2cf74767-e331-4fa6-8915-8f87ba01ca34@l33g2000pri.googlegroups.com> On Dec 12, 9:04 pm, "Gabriel Genellina" wrote: > If you're using 2.5 or older, override serve_forever: > > def serve_forever(self): > while not getattr(self, 'quit', False): > self.handle_request() > > and set the server 'quit' attribute to True in response to some command > from the client. Ok, I've tried this method and it would work if I wanted to shut down the server from the remote client. But if I want the server to shut down from the server itself upon some condition it doesn't work because the while statement is evaluated again only after there has been a request. If requests are infrequent or have ceased the self.handle_request() is never invoked and both the loop and the thread that contains it hang. I wasn't able to set a timeout upon which the handle_request() method returns. I'm not sure why. But I was able to make the original serve_forever() work. The problem was that in my code I used: asyncServer.daemon = True but somehow that doesn't work. I then tried: asyncServer.setDaemon(True) and that does work: when the asyncClient thread ends the only thread left running is the asyncServer, but as it is a daemon thread and there are no non-daemon threads left, the application exits regularly. So, below there's an updated version of my code that works as intended. Thanks for your help! Manu ------------------------- To use the following code, cut&paste into two separate *.py files and invert the port numbers in one file. Then, start them in two separate shells. ------------------------- import SocketServer import socket import threading import random from time import sleep ## Network request handler class MyTCPHandler(SocketServer.StreamRequestHandler): def handle(self): self.data = self.rfile.readline().strip() print "-> RECV: " + self.data + " - Sent by:" + self.client_address[0] ## Server Thread class ServerThread(threading.Thread): def __init__(self, localServer): threading.Thread.__init__(self) self.server = SocketServer.TCPServer(localServer, MyTCPHandler) def run(self): self.server.serve_forever() ## Client Thread class ClientThread(threading.Thread): def __init__(self, remoteServer): threading.Thread.__init__(self) self.remoteServer = remoteServer def run(self): cycle = 0 while cycle < 1000: chance = random.random() if(chance < 0.01): randomNumber = int(random.random() * 1000) message = str(randomNumber) + " from remote cycle " + str(cycle) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(self.remoteServer) sock.send(message + "\n") sock.close() print("SENT ->: "+str(randomNumber)+ " by local cycle "+str(cycle)) except: print("Failed to send number on cycle "+str (cycle)) cycle += 1 sleep(0.01) ## Simulating local/remote servers with different ports localServer = ("localhost", 9999) remoteServer = ("localhost", 10000) serverThread = ServerThread(localServer) serverThread.setDaemon(True) serverThread.start() clientThread = ClientThread(remoteServer) clientThread.start() --------------------------- From istvan.albert at gmail.com Fri Dec 5 23:19:22 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Fri, 5 Dec 2008 20:19:22 -0800 (PST) Subject: Don't you just love writing this sort of thing :) References: Message-ID: On Dec 3, 8:07?pm, Lawrence D'Oliveiro wrote: Originally, like many others here I said YIKES! but on a second read, it is not that bad. It actually grows on you. After looking at it one more time I found it neat, very concise without being unreadable. i. From claird at lairds.us Wed Dec 3 10:47:54 2008 From: claird at lairds.us (Cameron Laird) Date: Wed, 3 Dec 2008 15:47:54 +0000 Subject: Multiple equates References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> Message-ID: In article , Lawrence D'Oliveiro wrote: >In message , Cameron Laird wrote: > >> def shell_escape(Arg) : >> """returns Arg suitably escaped for use as a command-line argument >> to Bash.""" >> >> pattern = r"[\<\>\"\'\|\&\$\#\;\(\)\[\]\{\}\`\!\~\ \\]" >> def f1(Match): >> return "\\" + Match.group(0) >> return re.sub(pattern, f1, Arg) >> # Need to catch anything that might be meaningful to shell >> #end shell_escape > >So why is that better? I'm very lost, now. As best I can remember and/or reconstruct this conversation, the form above is adequately readable and does not involve lambda (and fits in eighty-column lines, and has a few even more mundane features). There's a realm within Pythonia that favors lambdalessness. I think that's all I'm claiming at this point. From taskinoor.hasan at csebuet.org Tue Dec 16 01:56:16 2008 From: taskinoor.hasan at csebuet.org (Taskinoor Hasan) Date: Tue, 16 Dec 2008 12:56:16 +0600 Subject: How can I return a non-zero status result from a python script? In-Reply-To: <5a289491-662c-49f2-98c7-aae100078a8a@r15g2000prd.googlegroups.com> References: <74b53da4-bf07-431b-898b-49977f7a685c@r36g2000prf.googlegroups.com> <5a289491-662c-49f2-98c7-aae100078a8a@r15g2000prd.googlegroups.com> Message-ID: <79153a2e0812152256g42a9059bqd4093411cdc66837@mail.gmail.com> sys.exit() raise SystemExit() exception which could be caught and if not caught, terminate only the current thread. If your program is multi-threaded and you want to terminate the process, i.e all threads, immediately then use os._exit(1) On Tue, Dec 16, 2008 at 7:52 AM, Miki wrote: > Hello, > > > How can I return a non-zero status result from the script? Just do a > > return 1? at the end? > raise SystemExit(1) > > HTH, > -- > Miki > http://pythonwise.blogspot.com > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at hlacik.eu Sun Dec 14 11:03:38 2008 From: david at hlacik.eu (=?ISO-8859-2?Q?David_Hl=E1=E8ik?=) Date: Sun, 14 Dec 2008 17:03:38 +0100 Subject: execution time Message-ID: Hi guys, #! /usr/bin/python import random import bucket2 data = [ random.randint(1,25) for i in range(5)] print "random data : %s" % data print "result: %s" %bucket2.sort(data) How to write a test script which will outputs execution time for bucket2.sort(data) ? Thanks in advance! From geekmail at usenot.de Sun Dec 7 12:10:54 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sun, 7 Dec 2008 18:10:54 +0100 Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> Message-ID: <20081207181054.5de84914@usenot.de> On Sun, 07 Dec 2008 02:49:27 -0500 acerimusdux wrote: > I'm not sure though whether allowing both syntaxes would make things > more or less confusing. It might actually be helpful in some respects > for newcomers to realize that self.method(arg) is somewhat the same > as method(self, arg). [snip] A professor of mine once said something to the effect that in teaching it is not so important to ?*tell* people a lot but to *omit* as much as practically possible. This might be the single most wise thing I have ever heard. If you're a newbee and you know nothing of the language, and probably nothing about programming at all, having two possibilities will thoroughly confuse you. Only when you have a working(!) knowledge of one version will you be able to appreciate the other. Since in this case the other option has no practical benefits whatsoever (IMHO), there's absolutely no need for it. /W PS: I will state again that I do like the idea in itself, its just about 20 years too late for it. -- My real email address is constructed by swapping the domain with the recipient (local part). From dongzhi at gmail.com Wed Dec 10 01:13:48 2008 From: dongzhi at gmail.com (dongzhi) Date: Tue, 9 Dec 2008 22:13:48 -0800 (PST) Subject: List Problem References: Message-ID: <8386b854-8253-48b2-9c9f-eb37973f2aec@o40g2000prn.googlegroups.com> On Dec 10, 2:00?pm, "James Mills" wrote: > On Wed, Dec 10, 2008 at 3:40 PM, dongzhi wrote: > > If I execute part[1], I have got ?'a'. If I execute part[2], I have > > got ' '. But, if I execute part[1::2], I have got ['a', '', '']. I > > don't know why. Please tell me why. > > Perhaps you meant: > > part[1:2] > > pydoc list > > This will tell you there are 3 arguments to __getslice__ > i, j, y > > Without doing any further reading I > presume from my experience that > this works much like range and xrange > and that the 3rd parameter is the step > size. > > Consider this: > > > > >>> x = [9, 1, 2, 3, 4] > >>> x > [9, 1, 2, 3, 4] > >>> x[1:2] > [1] > >>> x[1::2] > [1, 3] > >>> x[1::1] > [1, 2, 3, 4] > >>> x[1::2] > [1, 3] > >>> x[1::3] > [1, 4] > > cheers > James > > -- > -- > -- "Problems are solved by method Dear James Mills, Thanks a lot. Now, I know the reason. Best Regards, Liu Ming From shangach at gmail.com Wed Dec 3 14:43:00 2008 From: shangach at gmail.com (ShanMayne) Date: Wed, 3 Dec 2008 11:43:00 -0800 (PST) Subject: Switching windows in PyQT Message-ID: <9ef85e1f-9e46-48b6-8d11-a4f6e7176657@d23g2000yqc.googlegroups.com> Greetings All I am new to PyQT and GUI programming in general. What tutorials I have found are relatively clear on standard operations within a single window (QtGui.QWidget or QtGui.QMainWindow). Exiting this window exits the overall application. How would I switch between windows, that is close one and open another, within a running application. I would imagine this to be a standard feature often coded. My thanks Shannon From bockman at virgilio.it Tue Dec 30 13:19:08 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: Tue, 30 Dec 2008 19:19:08 +0100 Subject: select.select and socket.setblocking In-Reply-To: References: Message-ID: <495a661d$0$11384$5fc30a8@news.tiscali.it> Laszlo Nagy ha scritto: > I'm using this method to read from a socket: > > def read_data(self,size): > """Read data from connection until a given size.""" > res = "" > fd = self.socket.fileno() > while not self.stop_requested.isSet(): > remaining = size - len(res) > if remaining<=0: > break > # Give one second for an incoming connection so we can stop the > # server in seconds when needed > ready = select.select([fd], [], [], 1) > if fd in ready[0]: > data = self.socket.recv(min(remaining,8192)) # 8192 is > recommended by socket.socket manual. > if not data: > # select returns the fd but there is no data to read > -> connection closed! > raise TransportError("Connection closed.") > else: > res += data > else: > pass > if self.stop_requested.isSet(): > raise SystemExit(0) > return res > > > This works: if I close the socket on the other side, then I see this in > the traceback: > > File "/usr/home/gandalf/Python/Projects/OrbToy/orb/endpoint.py", line > 233, in read_data > raise TransportError("Connection closed.") > TransportError: Connection closed. > > Also when I call stop_requested.set() then the thread stops within one > seconds. > > Then I switch to non blocking mode, my code works exactly the same way, > or at least I see no difference. > > I have read the socket programming howto ( > http://docs.python.org/howto/sockets.html#sockets ) but it does not > explain how a blocking socket + select is different from a non blocking > socket + select. Is there any difference? > > Thanks > Couple of remarks: 1. AFAIK, select in python accepts also socket objects, or anything which has a fileno() method returning an integer. So you don't need to extract the fileno from the socket (python will do for you) although it does no harm. 2. IMO, the behaviour of your code is correct: with TCP protocol, when the remote ends disconnects, your end receives a 'read event' without data; you should just handle the fact that recv returns nothing as normal, not as error, and close your end of the connection. If you are interested in socket errors, you should also fill the third 'fd-set' in the select call, and after select returns check that fd is not in it anymore: ready = select.select( [fd],[], [fd] ) if fd in ready[2]: # raise your error here 3. AFAIK (sorry, I feel acronym-ly today ;), there is no difference in select between blocking and non-blocking mode. The difference is in the recv (again, assuming that you use TCP as protocol, that is AF_INET, SOCK_STREAM), which in the blocking case would wait to receive all the bytes that you requested, or the disconnection, in the other case would return immediately (and you should check the number of returned bytes, and when you read the remaining bytes of the message put the pieces together). I myself tend to avoid using non-blocking sockets, since blocking sockets are much easier to handle... HTH Ciao ------ FB From pavlovevidence at gmail.com Fri Dec 19 21:11:51 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 19 Dec 2008 18:11:51 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <1332da3c-8075-4552-9498-3ceb23faca8f@v31g2000vbb.googlegroups.com> Message-ID: On Dec 19, 7:12?pm, r wrote: > Marc, > Why move away from a concise and widely accepted way of sting > formatting, just to supposedly make it a little easier for n00bs? You were the one that brought it up, chief. I doubt anyone is arguing that this new formating was added just to make things easier for newbies, we're just saying that your assertion that printf-style is much easier for newbies is wrong. If you care to, go read the rationale for this change PEP 3101. You'd see the new formating was added to address limitations of the printf- style. (Hint: the limitations aren't that %s, %d, and %f are hard to remember.) > *It may be time to start hacking my own personal version of the Python > interpreter. hmm... Keep you ears to the ground... My friend, if you can't even cope with a new system of string formating, do you really expect to be able to maintain your own hacked- up fork of a highly wrought out programming language? Carl Banks From ivan.illarionov at gmail.com Tue Dec 23 16:12:57 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 23 Dec 2008 13:12:57 -0800 (PST) Subject: Beep References: Message-ID: <06d8d28f-dd63-4952-9e0c-97271871dfcd@w24g2000prd.googlegroups.com> On Dec 22, 3:16?am, Jeffrey Barish wrote: > I use sys.stdout.write('\a') to beep. ?It works fine on Kubuntu, but not on > two other platforms (one of which is Ubuntu). ?I presume that the problem > is due to a system configuration issue. ?Can someone point me in the right > direction? ?Thanks. > -- > Jeffrey Barish gnome-terminal (default terminal on Ubuntu) uses X11 bell for its beep. Try 'xset b on' to turn the beep on. See 'man xset' for more options. Ivan From ivan.illarionov at gmail.com Tue Dec 9 04:33:37 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 9 Dec 2008 01:33:37 -0800 (PST) Subject: Catching Python exceptions in C References: Message-ID: <72713421-97ed-453f-8f2f-06cc5f0ca355@o40g2000prn.googlegroups.com> On Dec 8, 9:42?pm, Senthil Kumar wrote: > Hi Pythoneers ! > Can somebody give a quick solution? > I am trying to raise exceptions in python and trying to handle it in > C. > I am able to raise exceptions successfully. However could not catch > those in C. > I am using the following function to run the python from C: > Pyrun_SimpleString(). > After the exception is raised, I am checking PyErr_Occurred(). It > always returns NULL, and I cannot catch the exception. > Pls help me a way out. > > Thanx in advance ! I use something like this: if (PyErr_Occurred()) { if (PyErr_ExceptionMatches(ExceptionName)) { /* do something about ExceptionName */ } else if (PyErr_ExceptionMatches(AnotherExceptionName)) { /* if we want to get the exception string */ PyObject *errtype, *errvalue, *traceback; PyErr_Fetch(&errtype, &errvalue, &traceback); if(errvalue != NULL) { PyObject *s = PyObject_Str(errvalue); /* Now 'PyString_AS_STRING(s)' contains C string of error message do something with it */ Py_DECREF(s); } Py_XDECREF(errvalue); Py_XDECREF(errtype); Py_XDECREF(traceback); } } Goof luck. From prologic at shortcircuit.net.au Sun Dec 21 17:26:17 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Dec 2008 08:26:17 +1000 Subject: Twisted for non-networking applications In-Reply-To: <82e49b84-43c9-452f-a139-c77378c12908@a12g2000pro.googlegroups.com> References: <82e49b84-43c9-452f-a139-c77378c12908@a12g2000pro.googlegroups.com> Message-ID: On Mon, Dec 22, 2008 at 4:27 AM, Kottiyath wrote: > Hi all, > Is it a good idea to use Twisted inside my application, even though > it has no networking part in it? > Basically, my application needs lots of parallel processing - but I > am rather averse to using threads - due to myraid issues it can cause. > So, I was hoping to use a reactor pattern to avoid the threads. I am > using twisted in another part of the application for networking, so I > was hoping to use the same for the non-networking part for reusing the > reactor pattern. > If somebody can help me on this, it would be very helpful. Alternatively you could give circuits (1) a go. It _can_ be a nice alternative to Twisted and isn't necessarily focused on Networking applications. cheers James 1. http://trac.softcircuit.com.au/circuits/ From lie.1296 at gmail.com Mon Dec 15 17:54:33 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 15 Dec 2008 22:54:33 +0000 (UTC) Subject: alt.possessive.its.has.no.apostrophe References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> <4f36bf19-40f2-4e88-8867-18a760000120@u18g2000pro.googlegroups.com> Message-ID: On Mon, 15 Dec 2008 11:53:40 -0800, Carl Banks wrote: > > (...For that matter, if the rule had been, "Never augment your words > spelling with an apostrophe", it would have really simplified > things....) Th next dae, wee aul wil bee speling liek this From ang.usenet at gmail.com Mon Dec 29 11:14:07 2008 From: ang.usenet at gmail.com (Aaron Gray) Date: Mon, 29 Dec 2008 16:14:07 -0000 Subject: HTML Correctness and Validators References: <2fb289be-00b3-440a-b153-ca88f0ba16c5@d42g2000prb.googlegroups.com> Message-ID: <6rsbahF33ndvU1@mid.individual.net> "Xah Lee" wrote in message news:2fb289be-00b3-440a-b153-ca88f0ba16c5 at d42g2000prb.googlegroups.com... >recently i wrote a blog essay about html correctness and html >validators, with relations to the programing lang communities. I hope >programing lang fans will take more consideration on the correctness >of the doc they produces. > >HTML Correctness and Validators >. http://xahlee.org/js/html_correctness.html Do you enjoy spamming comp.lang.functional with OT cross-posts ? Regards, Aaron From gagsl-py2 at yahoo.com.ar Wed Dec 10 10:37:12 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 10 Dec 2008 13:37:12 -0200 Subject: SequenceMatcher bug ? References: <67253331-5b36-4018-b15a-c0b86c5342d3@r37g2000prr.googlegroups.com> Message-ID: En Wed, 10 Dec 2008 12:00:30 -0200, escribi?: > On Tue, 9 Dec 2008 at 22:15, eliben wrote: >> On Dec 10, 4:12?am, rdmur... at bitdance.com wrote: >>> On Mon, 8 Dec 2008 at 23:46, eliben wrote: >>>> This is about Python 2.5.2 - I don't know if there were fixes to this >>>> module in 2.6/3.0 >>> >>>> I think I ran into a bug with difflib.SequenceMatcherclass. >>>> Specifically, its ratio() method. The following: >>> >>>> SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + [5]).ratio >>>> () >>> >>>> returns 0.0 >>> >>>> While the same with 500 replaced by 100 returns .99... something >>>> Looking at the code ofSequenceMatcherthere's some caching going on >>>> when the sequences are longer than 200 elements (and indeed, I can >>>> reproduce the bug above 200 but not below). Can anyone confirm that >>>> this misbehaves and suggest a workaround ? >>> >>> Python 2.5.2 (r252:60911, Sep 29 2008, 20:34:04) >>> [GCC 4.3.1] on linux2 >>> Type "help", "copyright", "credits" or "license" for more >>> information.>>> from difflib importSequenceMatcher >>>>>> SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + >>>>>> [5]).ratio() >>> >>> 0.99900299102691925 >>> >> >> Strange. I could reproduce the problem both on ActiveState Python >> 2.5.2 for Windows, and in the online Try Python evaluator: >> >> http://try-python.mired.org/ > > My system is Gentoo, which installs python from source. Maybe gentoo > applies patches that the binary releases don't have. I can't reproduce the problem. I got exactly the same results (0.999...) with all the releases I have at hand, ranging from 3.0 back to 2.1.3, all on Windows. And http://try-python.mired.org/ says the same thing. -- Gabriel Genellina From prahaai at gmail.com Sat Dec 13 01:17:57 2008 From: prahaai at gmail.com (Cro) Date: Fri, 12 Dec 2008 22:17:57 -0800 (PST) Subject: HGE and Python (again) References: <8180969e-9289-4f8c-ab80-30fbc50914d1@g17g2000prg.googlegroups.com> <6qdl1dFc3e1tU1@mid.uni-berlin.de> Message-ID: <1e95a808-70e5-44e9-a779-06bea89a786b@a37g2000pre.googlegroups.com> Good day. Thank you so much for your answer Diez! I managed to call HGE dll the way you told: >>> HGE = windll.LoadLibrary("C:/hge181/hge") >>> HGE.hgeCreate(0x180) But it's not helpful. It would mean that i have to re-create all the header files from "include" directory in python, and all helper functions from the "libs" to be able to use hge in the same way as the original. So ctypes is not what i need. It's a big step! I also tried swig, a lot. A lot, a lot, a lot of examples. Hacking examples and stuff. And i managed to compile "hge.h" header and call the structs and HGE main class. I don't seem to be able to acces the "enums", but that's not a big problem. How i did that, if anyone wants to know: There are 4 files. - There is "example.cxx", that includes "hge.h" in the proper C++ way and defines a HGE* hge=0 just like in the tutorials. - Then is "hge.h", the original file, with ONE line commented: line 408 with the DLL EXPORT. Ah, and one more thing. I had to delete ALL "CALL" keywords from HGE class, because if one CALL appears, the swig compiler flags the line as error. So, for now, no stdcall. - Then is "example.i", with "#include "hge.h"" and "%include "hge.h"". Simple as that. - And then, there is setup.py. "example_module = Extension('_example', sources=['example_wrap.cxx', 'example.cxx'],)" That's it. I compile it all like this: swig -c++ -python example.i setup build_ext --inplace So it's a huge step for me. The compiler i have in my system is mingw-3.4.5. I don't know if it's good for this. Maybe i should try a MS compiler instead? Next things i want to do: - try to compile the project with a MS compiles. Visual studio 7.1 or somethin. - learn if i can do stdcalls from swig !!! This is the most important. - try to compile one normal hge tutorial WITHOUT including "hge.lib" and "hgehelp.lib". All functions defined there can be included just like normal headers, the source is there and i compiled the libs myself. I need this step because i don't think i can include lib files in a swig project. - try to do all i did in swig, with Cython. It's pretty easy to use and faster from what i know. So i must learn to to stdcalls from swig. Can anyone suggest how to do that? I mean, i have lines like: virtual void CALL Release(); // in HGE class. And: void CALL HGE_Impl::Release() { //... // In the "c" file. } , where CALL is defined as "#define CALL __stdcall". I simply can't make this kind of classes so work in swig. Thank you very much. From dotancohen at gmail.com Thu Dec 4 15:56:03 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 4 Dec 2008 22:56:03 +0200 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> Message-ID: <880dece00812041256x227af79agf9a22226215f3330@mail.gmail.com> 2008/12/4 Mark Summerfield : > Now that Python 3 final has been released I thought it would be a good time > to mention that there's a new book to go with it: > > "Programming in Python 3: > A Complete Introduction to the Python Language" > ISBN 0137129297 > http://www.qtrac.eu/py3book.html > > I've been working on this for more than a year, testing the examples > against every Python 3 alpha and beta, and against the final release (using > Python's unit test and doctest modules of course:). > > The book has just gone into production and should be available in print at > the end of this month in the U.S., and a month or two later elsewhere. The > book's web page has links to a draft of the introduction and to safari > books online where you can read extracts. > > The book is aimed at a wide audience, but assumes some programming > experience (not necessarily Python, not necessarily object-oriented). It > teaches solid procedural style programming, then builds on that to teach > solid object-oriented programming, and then goes on to more advanced topics > (e.g., including a nice way to create validated attributes by combining > class decorators with descriptors). But even newcomers to Python 3 should > be able to write useful (although small and basic) programs after reading > chapter 1, and then go on to create larger and more sophisticated programs > as they work through the chapters. > I will ask my university bookstore to get a copy, though by experience it probably won't get there until Python 4! They just now got a Fedora 3 book in stock that I requested eons ago. If I decide to buy online, what is most favourable for you? Amazon? Direct order? I need shipping to Israel. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-??-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From fetchinson at googlemail.com Sat Dec 27 22:51:02 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 27 Dec 2008 19:51:02 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: >>> You MUST check EVERY function call for errors! >> >> Yes, I know :) >> > > Believe me, if you don't, there is a risk of crashing the program. And > they're a lot harder to find and fix. Sure, what I meant by the smiley is just that it was a quick and dirty example, not real code. In a real code I do check these sorts of things. >>> And check the argument's type (how do you know it is a list?). Once you >>> are sure the first parameter *is* a list, you may use the "macro" >>> version >>> of several functions, like PyList_GET_SIZE and PyList_GET_ITEM. >> >> The macro versions are preferable because they are faster? > > Yes, because they don't do any additional checking. PyList_GET_ITEM just > retrieves the item; PyList_GetItem checks whether it is called on a list > object, then checks if index is out of bounds, and only then goes to > retrieve the item. Thanks, I was wondering what the difference between these versions are, now it's clear. >>> You should check that both lists have the same length too. >>> And you should check that elements are integers, or convertible to >>> integers (in case of error, PyInt_AsLong returns -1 and PyErr_Occurred() >>> is true) >>> To fill the resulting tuple, use PyTuple_SET_ITEM instead. BTW, why >>> return >>> a tuple and not a list? >> >> No particular reason, other than the fact that I won't need to modify >> these lists/tuples from python so whenever something will not change, >> I use a tuple because it's immutable. Or this is not a very good >> practice? There is no difference between lists and tuples in terms of >> speed I suppose (getitem, setitem, etc). > > Usually lists represent an ordered collection of similar items, where > position is not relevant (the third item is treated more or less the same > as the tenth); by example, a list of attendants to certain event. It makes > sense to process the whole list doing the same thing to each element, and > it makes sense to ask "is this item in the list?." > > Tuples represent an ordered collection of dissimilar items, where position > is relevant (because it identifies each item); by example, a row from a > database table (name, address, age, phone number), or a point (x,y,z) in > space. It isn't common to process the whole tuple doing the same thing for > each element, and usually it doesn't make sense to look for certain item > in the tuple. But it does make sense to refer to individual items like > t[2], or t.age (namedtuple, 2.6 and up) > > From this point of view, lists and tuples are conceptually different - > tuples aren't "frozen" lists. But this is just common usage, or maybe > historical intent; of course you are free to use whatever structure you > feel adequate. > > Once the list/tuple is created and filled, there is no speed difference > accessing the individual items. Creating an empty list that grows one > element at a time is slow for large lists (the memory block has to be > re-allocated and copied over evry time it gets full) but this doesn't > happen if you provide the final size when creating the list. All right, this is clear then too, I'll probably use a list. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From andre.roberge at gmail.com Tue Dec 9 06:26:51 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Tue, 9 Dec 2008 03:26:51 -0800 (PST) Subject: Google Summer of Code 2009 References: <713dd4d7-0427-4b74-a5bc-1e3538afed6c@n10g2000vbl.googlegroups.com> Message-ID: On Dec 8, 10:34?pm, Eric wrote: > Hello, > I am interested in participating in Google Summer of Code 2009, > hopefully for something in Python. ?I realize that this is way before > it begins, but I would like to start to get to know the community > better and find something that I could work on during the summer of > code. ?I know a decent amount of Python, and I am a Sophomore Computer > Science major. ?My school teaches Java, but on the side I taught > myself Python. ?If anyone knows of any projects that could use another > hand, I would appreciate it. > > Thanks, > Eric You should have a look at http://wiki.python.org/moin/SummerOfCode It's still early, so there's nothing yet for 2009, but I am sure that some ongoing projects mentioned in previous years [like Crunchy ;-)] will be looking for volunteers. Andr? From sjmachin at lexicon.net Mon Dec 29 04:34:15 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 29 Dec 2008 01:34:15 -0800 (PST) Subject: why cannot assign to function call References: Message-ID: <97a11245-a034-4558-82d4-0c87e02bdb7e@u18g2000pro.googlegroups.com> On Dec 29, 5:01?pm, scsoce wrote: > I have a function return a reference, Stop right there. You don't have (and can't have, in Python) a function which returns a reference that acts like a pointer in C or C+ +. Please tell us what manual, tutorial, book, blog or Usenet posting gave you that idea, and we'll get the SWAT team sent out straight away. > and want to assign to the > reference, simply like this: > ?>>def f(a) > ? ? ? ? ? return a That's not a very useful function, even after you fix the syntax error in the def statement. Would you care to give us a more realistic example of what you are trying to achieve? > ? ? ?b = 0 > ? ? * f( b ) = 1* Is the * at the start of the line meant to indicate pointer dereferencing like in C? If not, what is it? Why is there a * at the end of the line? > but the last line will be refused as "can't assign to function call". > In my thought , the assignment is very nature, Natural?? Please tell us why you would want to do that instead of: b = 1 >?but ?why the interpreter > refused to do that ? Because (the BDFL be praised!) it (was not, is not, will not be) in the language grammar. From nytrokiss at gmail.com Thu Dec 4 15:52:40 2008 From: nytrokiss at gmail.com (James Matthews) Date: Thu, 4 Dec 2008 22:52:40 +0200 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> Message-ID: <8a6b8e350812041252p61049e98i144f27043b0a4ef0@mail.gmail.com> I am going to be checking Amazon now and ordering the book. Thanks James On Thu, Dec 4, 2008 at 9:42 PM, Alan G Isaac wrote: > Mark Summerfield wrote: > >> "Programming in Python 3: >> A Complete Introduction to the Python Language" >> ISBN 0137129297 >> http://www.qtrac.eu/py3book.html >> > > > OMG, you really wrote it in Lout? > I wish you would add to > http://www.qtrac.eu/lout.html > a comment on what you get out of that > (compared to using e.g., LaTeX or > reStructuredText). > > Anyway, congrats on the book! > I've asked my library to order it. > > Alan Isaac > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.astorandblack.com/ http://www.jewelerslounge.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From mmanns at gmx.net Thu Dec 18 19:49:32 2008 From: mmanns at gmx.net (mmanns at gmx.net) Date: Fri, 19 Dec 2008 01:49:32 +0100 Subject: Which sparse matrix package? References: <20081218231851.70dd91e2@Schlamber.localdomain> Message-ID: <20081219014932.7846a547@Schlamber.localdomain> On Fri, 19 Dec 2008 08:33:28 +1000 "James Mills" wrote: > > The dict that I tried out is of the type: > > > > {(1,2,3): "2323", (1,2,545): "2324234", ... } > > > > It is too slow for my application when it grows. One slicing > > operation with list comprehensions takes about 1/2 s on my computer > > for 1E6 elements. > > Let me get this straight. > It's taking 0.5s to slice your matrix > of 1E7 (10000000.0 rows/columns) My benchmark is as follows: 1) Each of the numbers in the 3-tuple is in the range [0, 1E7). 2) There are 1 000 000 elements in the dict (randomly distributed). 3) The content string is a random number in the range [0, 1E10) that is casted into a string. 4) Measure the time that retrieving all elements in a 10000x100x10 cube requires. > Are you mad ? This is TEN Millions and you > required it faster than 0.5s ? Think about how often a spreadsheet re-calculates cells. Furthermore, people tend to copy&paste cells. I had some small example (Wagner-Whitin algorithm demo) with hundreds of slicing operations on one screen. I believe that no-one wants to wait for 1/2 s times 500 == 250 s each time the spreadsheet is updated. Martin From benjamin.kaplan at case.edu Tue Dec 23 17:46:46 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 23 Dec 2008 17:46:46 -0500 Subject: SuSE11.1 eclipse 64 pydev can't add python path In-Reply-To: References: Message-ID: On Tue, Dec 23, 2008 at 5:08 PM, Nikolas Tautenhahn wrote: > Hi, > > Reimar Bauer wrote: > > I can install pydev using the update manager in eclipse for 64 bit from > the > > SuSE 11.1 repo. But I can't configure pydev without crashing it. > > I can select the interpreter /usr/bin/python > > and I do see the System PYTHONPATH > > Forced builtin libs also looks good. > > > > But Apply gives me > > # > > # An unexpected error has been detected by Java Runtime Environment: > > # > > # SIGSEGV (0xb) at pc=0x00007f2d7abebaed, pid=6544, tid=139832007596368 > > # > > # Java VM: IcedTea 64-Bit Server VM (1.7.0-b24 mixed mode linux-amd64) > > # Problematic frame: > > # V [libjvm.so+0x21baed] > > # > > # An error report file with more information is saved as: > > # /home/user/hs_err_pid6544.log > > # > > # If you would like to submit a bug report, please visit: > > # http://icedtea.classpath.org/bugzilla > > # The crash happened outside the Java Virtual Machine in native code. > > # See problematic frame for where to report the bug. > > unfortunately I can't help but reproduce the problem. My eclipse was > already configured when I updated openSuSE 11.0 to 11.1 so it is not > *that* bad for me (only when I install new eggs and want pydev to take > notice of them). > > The question is who is responsible for this... java? pydev? (suse?) If it was a PyDev problem, you'd see either a Python or a Java error message. This is a known bug in the HotSpot VM on Linux 64. It affects both the Sun and OpenJDK versions of Java. It was fixed in the newer builds. > > > If you open a ticket in a bugtracker, please post the url here and I > will add myself, too > > Best regards, > Nikolas Tautenhahn > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rt8396 at gmail.com Sat Dec 20 19:11:43 2008 From: rt8396 at gmail.com (r) Date: Sat, 20 Dec 2008 16:11:43 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <7fc23c41-6bf8-4272-b405-acc092cbac87@r15g2000prd.googlegroups.com> On Dec 20, 5:27?pm, walterbyrd wrote: > On Dec 19, 10:25?am, Michael Torrie wrote: > > > Personally the new string formatter is sorely needed in Python. ? > > Really? You know, it's funny, but when I read problems that people > have with python, I don't remember seeing that. Loads of people > complain about the white space issue. Some people complain ?about the > speed. Lots of complaints about certain quirky behavior, but I have > not come across any complaints about the string formatting. > > In fact, from what I have seen, many of the "problems" being "fixed" > seem to be non-problems. > > I dunno, maybe it's just me. You are exactly right Walter. I have not even considered this angle yet. Most of the complaints i hear are the redundant use of self. Which I lamented about but have become accustom(brainwashed) to it. I would remove this if it where up to me. I also hear a lot of complaints about speed. But never once in my life a problem with new users and string formatting. hmmm... food for thought From exarkun at divmod.com Tue Dec 30 15:55:51 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 30 Dec 2008 15:55:51 -0500 Subject: select.select and socket.setblocking In-Reply-To: Message-ID: <20081230205551.20272.583407013.divmod.quotient.29339@ohm> On Tue, 30 Dec 2008 14:41:17 -0600, Grant Edwards wrote: >On 2008-12-30, Francesco Bochicchio wrote: > >> 3. AFAIK (sorry, I feel acronym-ly today ;), there is no difference in >> select between blocking and non-blocking mode. The difference is in the >> recv (again, assuming that you use TCP as protocol, that is AF_INET, >> SOCK_STREAM), which in the blocking case would wait to receive all the >> bytes that you requested, > >No, in blocking mode it will wait to receive _some_ data (1 or >more bytes). The "requested" amount is strictly an upper >limit: recv won't return more than the requested number of >bytes, but it might return less. Hi Grant, I don't think you read Francesco's message carefully enough. :) He said: >>there is no difference in select between blocking and non-blocking mode. You're describing a difference in recv, not select. > >In non-blocking mode, it will always return immediately, either >with some data, no data (other end closed), or an EAGAIN or >EWOULDBLOCK error (I forget which). > >> [...] I myself tend to avoid using non-blocking sockets, since >> blocking sockets are much easier to handle... > >That depends on whether you can tolerate blocking or not. In >an event-loop, blocking is generally not allowed. > If you're careful, it's possible to avoid blocking, even when using a blocking socket, at least for AF_INET, SOCK_STREAM sockets. Of course, it's easier to avoid blocking by using a non-blocking socket. Jean-Paul From python.list at tim.thechases.com Thu Dec 11 13:57:18 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 11 Dec 2008 12:57:18 -0600 Subject: get todays files In-Reply-To: <49415258.2010101@doadesweb.co.uk> References: <4632c353-0462-485b-9e1b-6a5c56682363@s9g2000prg.googlegroups.com> <494015F7.3020302@tim.thechases.com> <49415258.2010101@doadesweb.co.uk> Message-ID: <4941628E.7070902@tim.thechases.com> > I know this will sound like I am being very cheeky, but is there a way > you can make this for where the ftp server is actually windows server? For Windows Server, I don't have a Windows FTP server to test with -- I've got the company Linux server, and the previous testing site I used (I think I used ftp.mozilla.org) which also likely runs some flavor of Linux. Neither supports the NLST from my testing. > curr_date = strftime("%d %B %Y", gmtime()) The first thing I noticed was that your strftime formating needs to match the format of the date that comes back from the FTP site. In my test, that was "YYYYMMDD". As such, your "%d %B %Y" would likely need to be "%Y%m%d". > ftp.retrlines('NLST',makelist) The servers I tried didn't support the NLST command so I can't exactly follow along here. However assuming that it correctly populates the list of files here > for ff in files: correctly, that's immaterial to me. > ftp = FTP(ftp_server) > ftp.set_pasv(False) > resp = ftp.login(ftp_uname,ftp_pwd) Just curious why you're logging into the server each pass through the loop -- I'd just connect once at the beginning of the loop, pull the files, and then disconnect at the end of the loop. > assert code == "213", "Unexpected result" Does this assert fail at any point? > if stamp[:8] == today: Given the above date-formatting, this should fail *every* time unless your FTP server is returning the date in some format other than "YYYYMMDDhhmmss" It's hard to pinpoint actual problems as this block of code has been modified, or doesn't run...there's some bogus indentation in your post: > log('Transferring: ' + ff[0]) > # make parameters to wget the backup file > params = ' ftp://' + ftp_server + '/' + ff[0] > rcode = subprocess.call('c:/wget.exe ' + params) > log('Return code from wget = ' + str(rcode)) > if (rcode == 0): > ff[1] = 1 > > else: > log('File ' + ff[0] + ' already exists locally, not > transferring') because this "else" is hanging oddly. Additionally, the FTP object has methods for downloading the content of a file, so I'd not bother shelling out to wget as an additional dependency. -tkc From robert.kern at gmail.com Thu Dec 18 18:16:19 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 18 Dec 2008 17:16:19 -0600 Subject: Python lex settings In-Reply-To: <0dfeb0c3-a524-4a72-aafd-4b88b71ff16c@w39g2000prb.googlegroups.com> References: <0dfeb0c3-a524-4a72-aafd-4b88b71ff16c@w39g2000prb.googlegroups.com> Message-ID: Sergey Shepelev wrote: > Hello. > > I'm trying to make almost-Python source to Erlang source translation > tool. > > Are there ready ply.lex settings for parsing python source? Yes! Andrew Dalke has implemented a PLY grammar for Python for experimenting with almost-Python languages. http://www.dalkescientific.com/Python/python4ply.html -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sjmachin at lexicon.net Tue Dec 9 01:14:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 8 Dec 2008 22:14:34 -0800 (PST) Subject: fuzzy or boolean text search References: <104335ff-e507-4429-9ad3-baecb63da8b3@k36g2000yqe.googlegroups.com> Message-ID: On Dec 9, 4:36?pm, n00b wrote: > hi, > > i'm looking for advice/suggestions for text search, preferably with > boolean or even fuzzy capabilities, and for use with mysql innodb > tables. ?asking too much :) ??? No ... feeding "fuzzy boolean text search mysql innodb" to my googler didn't choke it; it produced this at about the 15th hit: http://www.sphinxsearch.com/docs/manual-0.9.8.html Please tell your googler that we all hope that it gets well soon :-) From lie.1296 at gmail.com Fri Dec 12 16:18:36 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 12 Dec 2008 21:18:36 +0000 (UTC) Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> Message-ID: On Fri, 12 Dec 2008 11:50:38 -0500, Steve Holden wrote: > Kirk Strauser wrote: >> At 2008-12-12T15:51:15Z, Marco Mariani writes: >> >>> Filip Gruszczy?ski wrote: >>> >>>> I am not doing it, because I need it. I can as well use "if not elem >>>> is None", >> >>> I suggest "if elem is not None", which is not quite the same. >> >> So what's the difference exactly? "foo is not None" is actually >> surprising to me, since "not None" is True. "0 is True" is False, but >> "0 is not None" is True. Why is that? > > "is not" is an operator, so the parse is > > foo (is not) None > > not > > foo is (not None) > Personally, I'd prefer VB's version: foo IsNot bar or in pseudo-python foo isnot bar since that would make it less ambiguous. From prologic at shortcircuit.net.au Mon Dec 29 20:40:10 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 30 Dec 2008 11:40:10 +1000 Subject: multiprocessing vs thread performance In-Reply-To: <26f7d44e-552c-41e9-9290-17e5c4e6deb9@q30g2000prq.googlegroups.com> References: <26f7d44e-552c-41e9-9290-17e5c4e6deb9@q30g2000prq.googlegroups.com> Message-ID: On Tue, Dec 30, 2008 at 11:34 AM, Aaron Brady wrote: > The OP may be interested in Erlang, which Wikipedia (end-all, be-all) > claims is a 'distribution oriented language'. I would suggest to the OP that he take a look at circuits (1) an event framework with a focus on component architectures and distributed processing. I'm presently looking at Virtual Synchrony and other distributed processing architectures - but circuits is meant to be general purpose enough to fit event-driven applications/systems. cheers James 1. http://trac.softcircuit.com.au/circuits/ From lance.ellinghaus at eds.com Mon Dec 22 13:42:52 2008 From: lance.ellinghaus at eds.com (Ellinghaus, Lance) Date: Mon, 22 Dec 2008 13:42:52 -0500 Subject: Python's popularity In-Reply-To: <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> Message-ID: <752A61D5C34D41478E638FC92AF9051B03563493@usahm207.amer.corp.eds.com> > I just look at the stats for comp.lang.python, and i am 9th place for > most post this month. That makes me completely sad. With just 50 post > so far, i am showing up on the high count. Sad, very sad. Now i have > much reason to believe that only 100 or so people follow this list :(. > Python is slipping. We must try harder, or all of Guido's work will be > for nothing! Maybe most of us are doing real things with Python and not spending our time on the list posting. (I normally do not post on here, but I felt I had to now). I have used Python since 0.9.x and have brought it into every project/contract that I have worked on. The current project I am on tried to get rid of it and move to Perl for all of my code.. All of those people are gone and I am still here and so is Python. As a matter of fact, Python use has grown greatly and we rely on it for so many of our day to day operations, monitoring, data collection, etc. Python is not going away just because people are not posting here. Wake up! BEA and IBM have converted all of their custom script language support for WebLogic and WebSphere over to Jython because they felt Python (interfacing with Java) was the best solution to their script language issues. Everyone on the project I am on that works with WebLogic and WebSphere are learning Python so they can work with it. So far, no real complaints. People are moving away from Perl to Python for much of their scripting, but it will take a long time to complete. There is a lot of training, re-coding, and trying to figure out what the original Perl code did (ever try to go back and look at Perl code that is 2-3 years old!!!). Yes, Ruby has taken some of the popularity out of Python, but they are also hitting different markets. I have also read in a couple of magazine articles that RoR is losing momentum. From what I have read, RoR is great to create your first version, but if you need to maintain a large codebase, it is not as easy as they thought it would be and the reuse numbers are much lower than Python. But hey, what do I know.... Google, Yahoo!, YouTube... I know.. tiny little tinker-toy web applications.. right? Lance Ellinghaus From gagsl-py2 at yahoo.com.ar Mon Dec 8 03:31:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Dec 2008 06:31:28 -0200 Subject: mod_python and files directory In-Reply-To: <200812061326.40226.metebilgin48@gmail.com> References: <200812061326.40226.metebilgin48@gmail.com> Message-ID: En Sat, 06 Dec 2008 09:26:40 -0200, mete escribi?: > but i want to take it somewhere else...i want to it work some other path > in > other system. os.path.dirname(os.path.abspath(__file__)) returns the directory where the current file resides. Execute it early in your code. -- Gabriel Genellina From anonymous at anonymous.com Sat Dec 6 10:10:56 2008 From: anonymous at anonymous.com (anonymous) Date: Sat, 06 Dec 2008 15:10:56 GMT Subject: python book for non technical absolute beginner References: <493a7c6a$0$973$426a34cc@news.free.fr> Message-ID: <493A9503.A17F5EB4@anonymous.com> Yes, there is an excellent book for absolute beginners call Python Programming, for the absolute beginner (second edition by Michael Dawson. Here are the reasons why it is excellent for a beginner. It doesn't go beyong basic math as do most other computer books when giving examples, exercises or programs illustrating any language including Python. It teaches the basic phython in 9 chapters and the goes on to teach some basic graphics using Python. But for me and many others the first 9 chapters are perfect and awesome to work through. Most books attempting to teach any subject start off with a few easy basic chapters and then jumpt into complex explanations and examples. Not so with this book. It gives consistent easy to understand examples/code often in the form of a simple game which fun. No book I have seen, read or own on Python teaches the very basic principles of writing code as easily understood as this book. There are many excellent web sites around the world in many languages that teach basic Python with free texts and examples, but for somone with little or no programming experience or a first timer at programming with modest math skills, it is perfect. News123 wrote: > > Hi, > > One of my 'non technical' friends complained about knowing nothing at > all about programming (though using computers regularly for mails / web > browsing / googling and downloading / cropping photos ) > > He wants to play a little with programming to stimulate parts of his > otehrwise idle brain cells. ;-) Normally it's more the social science / > linguistic parts being exercised, > > I thought python might be a nice language for this > > No my question does anybody know a nice beginners book (or a learning CD > or on line tutorial)? Ideally it shouldn't be too serious and have a lot > of small nice mini-examples > > thanks in advance for any suggestions hints > > bye > > N From danebarney at gmail.com Sat Dec 27 00:10:59 2008 From: danebarney at gmail.com (Jugdish) Date: Fri, 26 Dec 2008 21:10:59 -0800 (PST) Subject: raw_input can't handle pound sign? References: <0165ad86$0$6988$c3e8da3@news.astraweb.com> Message-ID: <06613154-5789-4dd7-92cc-e20ca1f38670@a26g2000prf.googlegroups.com> Ahh ok, tried out your example and it works just fine. Turns out the actual problem is what I was doing with the input. Elsewhere, I call urlparse.urlparse() on the filename past in, which splits up the filename where the # sign is, so that's why it looked to me like the characters after the # were getting stripped away. Thanks for your help, in the future I'll try to do a bit more debugging of my own scripts before bringing my problems here! :) On Dec 26, 9:00?pm, Steven D'Aprano wrote: > On Fri, 26 Dec 2008 20:20:16 -0800, Jugdish wrote: > > Hi, I'm having problems getting a pound sign to go through as input sent > > to the raw_input() command. I'm running Python 2.5.1 on Windows XP. > > Here's my simple little script: > > > while True: > > ? ? response = raw_input("Please enter a file name: ") if > > ? ? os.path.exists(response): > > ? ? ? ? break > > > Problem is if the filename has a "#" in it, the script interprets that > > as the beginning of a comment (not sure why -- isn't raw_input supposed > > to treat the user's input as raw text and not do any sort of evals?) > > Yes it is. What makes you think it is being interpreted as a comment? > What results are you getting? > > > Any ideas how to get a # to go through? Thanks! > > Works for me (although I'm not using Windows XP). > > Can you execute this line at the interactive interpreter? > > print raw_input("Type something with a hash sign: ") > > At the prompt, type "test # string" (without the quotes) and show us what > result you get. When I do this, I get the following: > > >>> print raw_input("Type something with a hash sign: ") > > Type something with a hash sign: test # string > test # string > > -- > Steven From pavlovevidence at gmail.com Sun Dec 14 13:14:45 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 14 Dec 2008 10:14:45 -0800 (PST) Subject: curses and refreshing problem References: <69d2698a-6f44-4d85-adc3-1180ab158632@r15g2000prd.googlegroups.com> Message-ID: On Dec 14, 5:52?am, Karlo Lozovina <_karlo_ at _mosor.net_> wrote: > Carl Banks wrote innews:69d2698a-6f44-4d85-adc3-1180ab158632 at r15g2000prd.googlegroups.com: > > > Unless you are referring to some wget screen mode I don't know about, > > I suspect wget outputs its progress bar using carriage returns > > without newlines. ?If that's all you want, there is no need to use > > curses. > > > Here is a little example program to illustrate: > > > import time, sys > > for i in range(21): > > ? ? sys.stdout.write('\rProgress: [' + '='*i + ' '*(20-i) + ']') > > ? ? sys.stdout.flush() > > ? ? time.sleep(1) > > sys.stdout.write("\nFinised!\n") > > Thanks, that's it! I just assumed wget uses curses for the progress bar, > so the carriage return didn't even cross my mind ;). Sure. One other thing I'd like to point out is sometimes even if carriage return is not sufficient, you can get a little better control of the terminal by using escape sequences (quod Google). The more basic Xterm escape sequences work in pretty much any Unix-like environment you'd see these days, some might even work on a Windows terminal. For example, print "\033[2J\033[H" probably clears your screen and moves the cursor to top. Carl Banks From rt8396 at gmail.com Mon Dec 22 14:04:32 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 11:04:32 -0800 (PST) Subject: I always wonder ... References: <494fd759$0$186$e4fe514c@news.xs4all.nl> Message-ID: <310faab4-4598-4a5b-86d1-1c9410804982@p2g2000prf.googlegroups.com> > You just got 10 points ;-) Fighting trolls begets a troll. Skip not you, i have so much respect for you :) What really is a troll? Someone who does not agree with you? Someone you don't like? Someone you do like? All good questions. I think this whole troll calling business has gotten out of hand. Some people may antagonize you, but who is ultimately to blame for that? I guess we could have this set up were certain people could be banned, would you like that. Or maybe you should just ignore that which bothers you. If someone came to this group and said """ Ruby rules! Python sucks eggs!""" I would not even bother to reply. But do not let yourself be closed minded and think your ways are alway right. I have learned a lot from people here and have disagreed with a lot of opinions here. Troll calling is childish. be more open minded than that. From sergiocandiotti at hotmail.com Thu Dec 4 14:15:29 2008 From: sergiocandiotti at hotmail.com (sergio) Date: Thu, 4 Dec 2008 11:15:29 -0800 (PST) Subject: GIFTS.BUSINESS OPPORTUNITY Message-ID: Dear friend I'm writing to you because I just came across some businesses that I think have great potencial. All Solutions Network.A World of Opportunity and Solutions!! Make Money from Eveything...Loans,cars,meds,taxes,credit cards,vacations etc. Not Only can you make money for giving away free vacation packages,you get a free vacation certificate for just visiting the site!Make and Save on everything?It's Totally automated and no investment-EVER! Click here: http://allsolutionsnetwork.com/SC/SC6040/ Remote Data Backup Service Protect Your Most Valuable Asset...Your Data!! Take your free-30 days trial today with no credit card required. Online Backup Reseller Program.Just click here: http://sergioca.databu.com/bu/?id=sergioca GET YOUR OWN FREE TOTALLY AUTOMATED WEBSITE! 24/7 MULTIMEDIA MARKETING.WEALTH ON AUTO. Where Hig-Tech Meets Hig-Touch. 24/7 Fast Track system. A revolutionary,automated sponsoring and mentoring system to put your business on the FAST TRACK! Powerful sponsoring tools for FREE! Just click here: http://www.wealthonauto.com/members/sergiocandiotti/ MLM RESOURCE CENTER.MULTILEVEL MARKETING The #1 Site for Network Marketing, Training&Success. You can't build anything without THE RIGHT TOOLS. We have the tools! Just click here: http://www.wealthonauto.com/members/sergiocandiotti/mrc.htm Talk to you later. Sergio Candiotti Aguero sergiocandiotti at hotmail.com From Russ.Paielli at gmail.com Thu Dec 18 23:40:43 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Thu, 18 Dec 2008 20:40:43 -0800 (PST) Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> <6qv7kfFeuf65U1@mid.uni-berlin.de> <6qv9v4Ff1lv9U1@mid.uni-berlin.de> Message-ID: <3840c09b-1dae-4bb7-b509-624636cbbc28@g39g2000pri.googlegroups.com> On Dec 18, 1:27?pm, Robert Kern wrote: > Mikael Olofsson wrote: > > Diez B. Roggisch wrote: > >> Yep. And it's easy enough if you don't care about them being different.. > > >> def __repr__(self): > >> ? ? return str(self) > > > If I ever wanted __str__ and __repr__ to return the same thing, I would > > make them equal: > > > def __str__(self): > > ? ? return 'whatever you want' > > __repr__ = __str__ > > > That makes it more obvious to me what's going on. As a bonus, it saves > > one method call for every repr call. > > Or just define __repr__(). str() falls back to __repr__() if __str__() is not > defined. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > ? that is made terrible by our own mad attempt to interpret it as though it had > ? an underlying truth." > ? ?-- Umberto Eco I learned a while ago to just define __repr__, and let __str__ revert to it by default. Then, when I print a list for debugging purposes, I see something useful (as opposed to a type name and an address). The only reason that I can think of to define __str__ is to get two different representations. For example, sometimes I need both a one- line output format and a multi-line option for more clarity or detail. Then I use __repr__ for the one-liner and __str__ for the multi-liner. From prologic at shortcircuit.net.au Thu Dec 18 22:14:12 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Dec 2008 13:14:12 +1000 Subject: Factoring Polynomials In-Reply-To: References: <919062f9-765e-4279-aa26-2c130d4deacf@o4g2000pra.googlegroups.com> <4479b464-3a9b-4dd8-bf66-fea7d9471091@n33g2000pri.googlegroups.com> <661fd2d0-251d-4899-a015-8d257310a159@q26g2000prq.googlegroups.com> Message-ID: On Fri, Dec 19, 2008 at 12:48 PM, Collin D wrote: > UPDATE: > > #import > from math import sqrt > > # collect data > a = float(raw_input('Type a value: ')) > b = float(raw_input('Type b value: ')) > c = float(raw_input('Type c value: ')) > > # create solver > def solver(a,b,c): > disc = b**2 - 4*a*c > if disc < 0: > return 'No real solution.' > else: > sol1 = (-b + (sqrt(disc))) / (2*a) > sol2 = (-b - (sqrt(disc))) / (2*a) > return (sol1, sol2) You do not need the else here. return will always return control to the calee. Try this: class Unsolveable(Exception): pass # create solver def solver(a, b, c): disc = b**2 - 4*a*c if disc < 0: raise Unsolveable() return -b + (sqrt(disc) / (2*a)), -b - (sqrt(disc) / (2*a)) From bdesth.quelquechose at free.quelquepart.fr Sun Dec 14 11:22:11 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 14 Dec 2008 17:22:11 +0100 Subject: Looking for the best way to translate an idiom In-Reply-To: References: Message-ID: <4945406a$0$1127$426a74cc@news.free.fr> Paul Moore a ?crit : > I'm translating some code from another language (Lua) which has > multiple function return values. So, In Lua, it's possible to define a > function > > function f() > return 1,2,3 > end > > which returns 3 values. These can then be used/assigned by the caller: > > a,b,c = f() > > So far, much like Python, but the key difference is that in Lua, > excess arguments are ignored - so you can do > > a = f() > or even > a = f() + 1 > > where in the latter, a is 2 (as addition only needs 1 argument, so the > extra ones are discarded). > > This results in the code which I'm trying to translate having > functions which return multiple arguments, the first of which is the > "main" result, and the following values are "extra" results > (specifically, the position at which a match is found, followed by the > "captured" values of the match). > > I'm trying to find a natural equivalent in Python. So far, I've > considered the following: > > - return a tuple (pos, captures). This is messy, because you end up > far too often unpacking the tuple and throwing away the second value if you only want the first returned value, you can just apply a slice: def f(): return 1,2,3 a = f()[0] + 1 > - return an object with pos and captures attributes. This is better, > as you can do match(...).pos to get the position alone, but it doesn't > really feel "pythonic" (all those calls with .pos at the end...) FWIW, Python 2.6 has NamedTuple objects... > - have 2 calls, one to return just the position, one to return both. > This feels awkward, because of the 2 method names to remember. You forgot one solution: passing a flag to the function to specify if you want only the main result or the extra ones as well, and give this flag the appropriate default value depending on most common use case. > To make things worse, Lua indexes strings from 1, so it can use a > position of 0 to mean "no match" - so that a simple "did it match?" > test looks like if (match(....))... - where in Python I need if > (matchpos(...) != -1)... (Although if I return a match object, I can > override __nonzero__ to allow me to use the simpler Lua form). > > Can anyone suggest a good idiom for this situation? At the moment, I'm > returning a match object (the second option) which seems like the > least bad of the choices (and it mirrors how the re module works, > which is somewhat useful). But I'd like to know what others think. If > you were using a pattern matching library, what interface would you > prefer? The one that happens to be the most simple for the most common usecase, while still providing support for more advanced stuff. > I suspect my intuition isn't accurate here, as most of the use I've > made of the library is in writing tests, which isn't typical use :-( So perhaps you should start writing some real-life code ? > Thanks for any assistance. Not sure I've been that helpful. Sorry... From cournape at gmail.com Fri Dec 19 00:08:49 2008 From: cournape at gmail.com (David Cournapeau) Date: Fri, 19 Dec 2008 14:08:49 +0900 Subject: Python for amd64 and mingw-w64 Message-ID: <5b8d13220812182108y5a21d48as4adead61fede561a@mail.gmail.com> Hi, I want to build python extensions with mingw-w64 on windows 64 bits. I found some problems which I think are python bugs/deficiencies, but would like a confirmation: - Any extension requires the MS_WIN64 to be defined, but this symbol is only defined for MS compiler (in PC/pyport.h). Shouldn't it be defined independantly of the compiler ? One problem is that without this defines, SIZEOF_SIZE_T is set to 4 with gcc. Another consequence which can be seen even through a trivial , do nothing extension is that Py_InitModule4 is used (whereas the same source file will use Py_InitModule4_64, which is used when SIZEOF_SIZE_T !=SIZEOF_INT, in include/modsupport.h). - I have some link problems related to Py_InitModule4_64. I believe the problem is in libpython26.a, which according to nm does not have this symbol defined, whereas python26.dll has. thanks, David From quian.xu at stud.tu-ilmenau.de Tue Dec 23 06:06:09 2008 From: quian.xu at stud.tu-ilmenau.de (Qian Xu) Date: Tue, 23 Dec 2008 12:06:09 +0100 Subject: print to console without a line break References: Message-ID: Qian Xu wrote: > Hello All, > > Is it possible to print something to console without a line break? > > I tried: > sys.stdout.write("Testing something ...") // nothing will be printed > time.sleep(1) > sys.stdout.write("done\n") // now, the whole string will be printed > > What I want, is to see "Testing something ..." first. > And after 1 second, to see "done" (with a line break) > I have solved the problem by calling sys.stdout.flush() --Qian Xu From geon at post.cz Thu Dec 25 23:52:52 2008 From: geon at post.cz (Pavel Kosina) Date: Fri, 26 Dec 2008 05:52:52 +0100 Subject: tkinter 3.0 multiple keyboard events together Message-ID: <49546324.4050607@post.cz> Is it possible to catch in an event more that one key from keyboard? In my code, I can handle always the only one, the first I press, the others are omitted. Say, I press both "4" and "8" and only "4" is catched. def movePlayer(event): print (event.keysym) Thank you. -- geon Pavel Kosina From paul at boddie.org.uk Thu Dec 18 18:22:59 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 18 Dec 2008 15:22:59 -0800 (PST) Subject: psycopg2 and large queries References: <762eed9d-4646-4c62-a9b7-d57d47f03b9e@e1g2000pra.googlegroups.com> Message-ID: <7e76a8db-8a93-4704-8815-ad106f50c47d@w39g2000prb.googlegroups.com> On 18 Des, 22:28, Laszlo Nagy wrote: > > I'm just looking for something that can replace psycopg2, because of the > bug mentioned in my original post. Here are my options: > > - psycopg1: development stalled > - psycopg2: memory bug and/or not db api compilant (see my original post) If you want, I can try and dig up those patches I made. > - pyPgSQL: looks like that the last release was in mid 2006 (and it > depends on mxDateTime -> licensing problems) Well, Debian ships mxDateTime, so I suppose the licence is DFSG- compliant, at least. Whether that's enough only you can say, but porting the dependent parts to use the Python standard library datetime implementation might be possible. Paul From rhamph at gmail.com Mon Dec 8 18:30:22 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 8 Dec 2008 15:30:22 -0800 (PST) Subject: Rich Comparisons Gotcha References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Dec 8, 2:51?pm, Robert Kern wrote: > Rhamphoryncus wrote: > > "We've always done it that way" is NOT a use case! ?Certainly, it's a > > factor, but it seems quite weak compared to the sort use case. > > I didn't say it was. I was explaining that sorting was probably *not* a use case > for the boolean predicates at the time of writing of the standard. In fact, it > suggests implementing a Compare() function that returns "greater than", "less > than", "equal" or "unordered" in addition to the boolean predicates. That Python > eventually chose to use a generic boolean predicate as the basis of its sorting > routine many years after the IEEE-754 standard is another matter entirely. I interpret that to mean IEEE 754's semantics are for different circumstances and are inapplicable to Python. > In any case, the standard itself is quite short, and does not spend much time > justifying itself in any detail. A pity, as it is often invoked to explain language design. > > I suppose what I'm hoping for is an small example program (one or a > > few functions) that needs the "always false" behaviour of NaN. > > Steven D'Aprano gave one earlier in the thread. I see examples of behaviour, but no use cases. > Additionally, (x!=x) is a simple > test for NaNs if an IsNaN(x) function is not available. That's a trick to work around the lack of IsNaN(x). Again, not a use case. > Really, though, the > result falls out from the way that IEEE-754 constructed the logic of the > system. It is not defined that (NaN==NaN) should return False, per se. Rather, > all of the boolean predicates are defined in terms of that Compare(x,y) > function. If that function returns "unordered", then (x==y) is False. It doesn't > matter if one or both are NaNs; in either case, the result is "unordered". And if I arbitrarily dictate that NaN is a single value which is orderable, sorting just above -Infinity, then all the behaviour makes a lot more sense AND I fix sort. So you see the predicament I'm in. On the one hand we have a problem and an obvious solution. On the other hand we've got historical behaviour which everybody insists *must* remain, reasons unknown. It reeks of the Parable of the Monkeys. I think I should head over to one of the math groups and see if they can find a reason for it. From castironpi at gmail.com Mon Dec 29 14:18:33 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 11:18:33 -0800 (PST) Subject: why cannot assign to function call References: <97a11245-a034-4558-82d4-0c87e02bdb7e@u18g2000pro.googlegroups.com> <47-dnUx1_OP7gsTUnZ2dnUVZ_r6dnZ2d@pdx.net> Message-ID: On Dec 29, 1:05?pm, Scott David Daniels wrote: > John Machin wrote: > > On Dec 29, 5:01 pm, scsoce wrote: > >> I have a function return a reference, > > > Stop right there. You don't have (and can't have, in Python) a > > function which returns a reference that acts like a pointer in C or C+ > > +. Please tell us what manual, tutorial, book, blog or Usenet posting > > gave you that idea, and we'll get the SWAT team sent out straight > > away. > > Perhaps we can send the the Pennsylvania State University out after > them. ?I don't know why, but some fairly substantial people here are > scared of the PSU. > > ... > > Oh, I have just been informed by my captors that the are the Python > Secre.... --Why would he take the time to carve "ARGHHH!"? --Maybe he was dictating. From jenn.duerr at gmail.com Thu Dec 11 21:43:00 2008 From: jenn.duerr at gmail.com (noydb) Date: Thu, 11 Dec 2008 18:43:00 -0800 (PST) Subject: Rename of .mdb file -- lock References: <4049f296-2a04-4eee-9f09-aa37a973a8cf@r40g2000yqj.googlegroups.com> <8792708a-51c9-4fa6-b39d-4808ed1ffaed@t39g2000prh.googlegroups.com> Message-ID: <99fbe43e-9b30-4ed2-8355-29a21935e55a@n41g2000yqh.googlegroups.com> On Dec 11, 9:38?pm, "gudonghua+pyt... at gmail.com" wrote: > On Dec 12, 10:15?am, noydb wrote: > > > > > All, > > > I have the code below, which unzips a zipfile containing only one > > file. ?Once it is unzipped, I want to rename the file based on a user > > provided name. ?But I get this (WindowsError: [Error 32] The process > > cannot access the file because it is being used by another process) > > error, which does not make sense to me as no other apps are open. > > > Any suggestions? > > > Thanks! > > > ****CODE**** > > # Declare the zip file directory and name (shouldn't change, in a > > permanent location) > > mdb_zip = ("C:\\ProjWork\\mdb_geoDB_91.zip") > > > output_dir = ("C:\\Temp") > > > # ZipFile for read > > z = zipfile.ZipFile(mdb_zip, 'r') > > zFile = z.namelist() > > > # Put contents of zipfile into a list > > zList = z.namelist() > > > # Loop thru list, write zipfile contents to new directory > > for zItem in zList: > > ? ? print "Unpacking",zItem > > ? ? zRead = z.read(zItem) > > ? ? z1File = open(os.path.join(output_dir, zItem),'wb') > > ? ? z1File.write(zRead) > > ? ? z1File.close > > ? ? ?z1File.close() > > > > > print "Finished extracting zip file" > > > uChoice = "test44.mdb" ## to be user chosen someday > > new91mdb = os.path.join(output_dir, zItem) # C:\TEMP\GDB_9_1.mdb > > > ##os.rename(new91mdb, (os.path.join(output_dir, uChoice))) > > os.rename(new91mdb, (os.path.join(output_dir, "C:\TEMP\test1.mdb"))) > > > del new91mdb- Hide quoted text - > > - Show quoted text -- Hide quoted text - > > - Show quoted text - Thanks! That was simple enough. And... ##os.rename(new91mdb, (os.path.join(output_dir, uChoice))) os.rename(new91mdb, (os.path.join(output_dir, "C:\TEMP\test1.mdb"))) ... of those two lines, the top one worked. From metebilgin48 at gmail.com Sat Dec 6 06:26:40 2008 From: metebilgin48 at gmail.com (mete) Date: Sat, 6 Dec 2008 13:26:40 +0200 Subject: mod_python and files directory In-Reply-To: References: Message-ID: <200812061326.40226.metebilgin48@gmail.com> but i want to take it somewhere else...i want to it work some other path in other system. On Saturday 06 December 2008 12:34:07 Graham Dumpleton wrote: > On Dec 6, 1:52?am, "mete bilgin" wrote: > > Hi all, > > I try to make a websevice with python and mod_python. ? try to make a po > > files, but i can not reach them in the page. When i ask the page like " > > os.listdir('.') " but i want to get files directory, what can i do? sorry > > for my bad describe of that. Thanks a lot... > > The current working directory in Apache can be anything. You must > supply an absolute path to all directories/files you are trying to > access/use. > > Graham > -- > http://mail.python.org/mailman/listinfo/python-list From barry at python.org Wed Dec 3 20:51:33 2008 From: barry at python.org (Barry Warsaw) Date: Wed, 3 Dec 2008 20:51:33 -0500 Subject: RELEASED Python 3.0 final Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On behalf of the Python development team and the Python community, I am happy to announce the release of Python 3.0 final. Python 3.0 (a.k.a. "Python 3000" or "Py3k") represents a major milestone in Python's history, and was nearly three years in the making. This is a new version of the language that is incompatible with the 2.x line of releases, while remaining true to BDFL Guido van Rossum's vision. Some things you will notice include: * Fixes to many old language warts * Removal of long deprecated features and redundant syntax * Improvements in, and a reorganization of, the standard library * Changes to the details of how built-in objects like strings and dicts work * ...and many more new features While these changes were made without concern for backward compatibility, Python 3.0 still remains very much "Pythonic". We are confident that Python 3.0 is of the same high quality as our previous releases, such as the recently announced Python 2.6. We will continue to support and develop both Python 3 and Python 2 for the foreseeable future, and you can safely choose either version (or both) to use in your projects. Which you choose depends on your own needs and the availability of third-party packages that you depend on. Some other things to consider: * Python 3 has a single Unicode string type; there are no more 8-bit strings * The C API has changed considerably in Python 3.0 and third-party extension modules you rely on may not yet be ported * Tools are available in both Python 2.6 and 3.0 to help you migrate your code * Python 2.6 is backward compatible with earlier Python 2.x releases We encourage you to participate in Python 3.0's development process by joining its mailing list: http://mail.python.org/mailman/listinfo/python-3000 If you find things in Python 3.0 that are broken or incorrect, please submit bug reports at: http://bugs.python.org/ For more information, links to documentation, and downloadable distributions, see the Python 3.0 website: http://www.python.org/download/releases/3.0/ Enjoy, - -Barry Barry Warsaw barry at python.org Python 2.6/3.0 Release Manager (on behalf of the entire python-dev team) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Darwin) iQCVAwUBSTc3pXEjvBPtnXfVAQI69wP/dPHh8IL3GxziEV9QzlveKG+KyZb2X16x fxJnTCiXAbiAhT5C+m43OEnbF1PJgMDKtcZ5b7aQb4TQ0mJxISTQh0RfLCpArmlo tdTbzCLnh13KzB+3sUHCx+MeQNXERoWDV8hLz+4Ae71UsuUGynhtyP7ZJMJDue8j so2gv3fOMSs= =vkiy -----END PGP SIGNATURE----- From saluk64007 at gmail.com Sun Dec 7 20:17:45 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Sun, 7 Dec 2008 17:17:45 -0800 Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? In-Reply-To: References: Message-ID: On Sun, Dec 7, 2008 at 4:43 PM, wrote: > Trying to decide which to get started with. Can anyone suggest some > pros and cons to each of them? > > Would PyOpenGL be in the same camp as Pygame and pyglet? Do either of > Pygame or pyglet make use of PyOpenGL behind the scenes? > -- > http://mail.python.org/mailman/listinfo/python-list > PyOpengl - an opengl wrapper. Version 2 is written in c, version 3 instead uses ctypes Pyglet - an opengl + events/sound/etc wrapper written in ctypes pygame - an sdl wrapper for 2d rendering, sound, music, events, etc that can be used with pyopengl if 3d hardware support is desired. If you want to do 3d, your choice is basically pygame+pyopengl or pyglet. pyglet is nice because it comes with everything you need, versus pygame where you have to interact via pyopengl. Pygame +pyopengl2 is faster than pyglet or pygame+pyopengl3 becuase pyglet and pyopengl3 take a hit from ctypes. There is a project with pyopengl3 though to add some c code to speed things up, I think it works with numeric. Pyglet will be easiest to start with and use, it seems to be everyone's favorite choice these days. From python at bdurham.com Tue Dec 2 23:21:30 2008 From: python at bdurham.com (python at bdurham.com) Date: Tue, 02 Dec 2008 23:21:30 -0500 Subject: Best way to run multiple Python processes without overloading CPU or disk i/o Message-ID: <1228278090.29785.1287948757@webmail.messagingengine.com> Is there a cross-platform way to launch multiple Python processes and monitor CPU usage and disk i/o so that the maximum number of independent processes can be running at all times without overloading their environment? By process I mean independent application sessions vs. multiple threads of a single application. I'm looking for suggestions on what Python modules and/or techniques to use to maximize the number of processes I can run on my system over a multi-day period. Background: I have a large collection of data analysis scripts that can run independently of one another. These scripts read very large log files in a sequential manner and calculate specific statistics. These scripts are hosted on a 8 core 64-bit server with 48G of memory that is dedicated to running these scripts. I am looking for a way to write a master script that monitors system CPU and disk i/o and when there is capacity launch another script from a pool of scripts so that I'm getting max utilization from my hardware, eg. so that I'm running the max number of scripts I can at any one point in time without overwhelming the system. The server in question is currently running Windows 2008 Enterprise, but I have the option to switch to a 64-bit version of Linux if there are benefits to doing so. Thank you, Malcolmm -------------- next part -------------- An HTML attachment was scrubbed... URL: From news123 at free.fr Sun Dec 7 06:57:27 2008 From: news123 at free.fr (News123) Date: Sun, 07 Dec 2008 12:57:27 +0100 Subject: Guido's new method definition idea In-Reply-To: <62bcfe49-bee6-4348-8ec9-8ab85132c8ff@40g2000prx.googlegroups.com> References: <493abe2e$0$15998$426a34cc@news.free.fr> <62bcfe49-bee6-4348-8ec9-8ab85132c8ff@40g2000prx.googlegroups.com> Message-ID: <493bba28$0$8283$426a74cc@news.free.fr> Lie wrote: > On Dec 7, 1:02 am, News123 wrote: >> What would be interesting would be some syntactical sugar to get rid of >> the 'self' (at least in the code body). >> >> example: >> class C: >> class_elements a,b,c,d >> >> def method(self,arg): >> global d >> a,b,c = arg[0..3] >> d = a + b >> self.e = a + d >> > > Nah, that would make it not explicit. Explicit here also means that to > refer to self's a, we need to explicitly refer to self. Well being explicit when trying to suggest an implicit syntax (in order to reduce typing) is a little difficult ;-) Though you're right my main goal is not being implicit but would be reducing typing and have shorter source code lines. If 'global '' is accepted inside a def, then moving 'class_elements ' inside the def could be acceptable as well though it would requiere, that this statement is repeated per def bye N From marco at sferacarta.com Fri Dec 12 04:28:18 2008 From: marco at sferacarta.com (Marco Mariani) Date: Fri, 12 Dec 2008 10:28:18 +0100 Subject: Python is slow In-Reply-To: <4c9ba1a9-db8d-43a5-86f5-09f688200ea4@w24g2000prd.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <9e0bb906-e019-45ef-8047-b33982c7c5ad@l39g2000yqn.googlegroups.com> <4c9ba1a9-db8d-43a5-86f5-09f688200ea4@w24g2000prd.googlegroups.com> Message-ID: Giampaolo Rodola' wrote: > The real (and still unsolved) problem with PyPy is the installation > which requires something like a dozen of third-party packages to be > installed. > Unfortunately it seems there are no plans yet for releasing any > Windows/Linux/Mac installer in the near future. I'm not using it, but at least Ubuntu 8.10 has the .deb packages of pypy 1.0. And I remember installing a release last year in a few minutes, during a conference talk. From tjreedy at udel.edu Sat Dec 6 14:56:32 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 06 Dec 2008 14:56:32 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Rasmus Fogh wrote: > Dear All, > > For the first time I have come across a Python feature that seems > completely wrong. After the introduction of rich comparisons, equality > comparison does not have to return a truth value, and may indeed return > nothing at all and throw an error instead. As a result, code like > if foo == bar: > or > foo in alist > cannot be relied on to work. > > This is clearly no accident. According to the documentation all comparison > operators are allowed to return non-booleans, or to throw errors. There is > explicitly no guarantee that x == x is True. You have touched on a real and known issue that accompanies dynamic typing and the design of Python. *Every* Python function can return any Python object and may raise any exception either actively, by design, or passively, by not catching exceptions raised in the functions *it* calls. > Personally I would like to get these !@#$%&* misfeatures removed, What you are calling a misfeature is an absence, not a presence that can be removed. > and constrain the __eq__ function to always return a truth value. It is impossible to do that with certainty by any mechanical creation-time checking. So the implementation of operator.eq would have to check the return value of the ob.__eq__ function it calls *every time*. That would slow down the speed of the 99.xx% of cases where the check is not needed and would still not prevent exceptions. And if the return value was bad, all operator.eq could do is raise and exception anyway. > That is clearly not likely to happen. Unless I have misunderstood something, could > somebody explain to me. a. See above. b. Python programmers are allowed to define 'weird' but possibly useful-in-context behaviors, such as try out 3-value logic, or to operate on collections element by element (as with numpy). > 1) Why was this introduced? The 6 comparisons were previously done with one __cmp__ function that was supposed to return -1, 0, or 1 and which worked with negative, 0, or positive response, but which could return anything or raise an exception. The compare functions could mask but not prevent weird returns. I can understand relaxing the restrictions on > '<', '<=' etc. - after all you cannot define an ordering for all types of > object. But surely you can define an equal/unequal classification for all > types of object, if you want to? Is it just the numpy people wanting to > type 'a == b' instead of 'equals(a,b)', or is there a better reason? > > 2) If I want to write generic code, can I somehow work around the fact > that > if foo == bar: > or > foo in alist > does not work for arbitrary objects? Every Python function is 'generic' unless restrained by type tests. However, even 'generic' functions can only work as expected with objects that meet the assumptions embodied in the function. In my Python-based algorithm book-in-progess, I am stating this explicitly. In particular, I say taht the book only applies to objects for which '==' gives a boolean result that is reflexive, symmetric, and transitive. This exludes float('nan'), for instance (as I see you discovered), which follows the IEEE mandate to act otherwise. > CCPN has a table display class that maintains a list of arbitrary objects, > one per line in the table. The table class is completely generic, but only for the objects that meet the implied assumption. This is true for *all* Python code. If you want to apply the function to other objects, you must either adapt the function or adapt or wrap the objects to give them an interface that does meet the assumptions. > and subclassed for individual cases. It contains the code: > > if foo in tbllist: > ... > else: > ... > tbllist.append(foo) > ... > > One day the 'if' statement gave this rather obscure error: > "ValueError: > The truth value of an array with more than one element is ambiguous. > Use a.any() or a.all()" > A subclass had used objects passed in from some third party code, and as > it turned out foo happened to be a tuple containing a tuple containing a > numpy array. Right. 'in' calls '==' and assumes a boolean return. Assumption violated, exception raised. Completely normal. The error message even suggests a solution: wrap the offending objects in an adaptor class that gives them a normal interface with .all (or perhaps the all() builtin). Terry Jan Reedy From jstroud at mbi.ucla.edu Thu Dec 4 16:04:05 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 04 Dec 2008 13:04:05 -0800 Subject: To Troll or Not To Troll In-Reply-To: References: <896B75251BA19745A529B1B867893FA50679CE@planet.delsci.local> Message-ID: Chris Mellon wrote: > On Thu, Dec 4, 2008 at 1:10 PM, Warren DeLano wrote: >>> Yet Another Python Troll (the ivory tower reference, as well as the >>> abrupt shift from complaining about keywords to multiprocessing), I >>> have to point out that Python does add new keywords, it has done so in >>> the past, and there was a considerable amount of warning, including an >>> automated deprecation warning in the very version you are going to >>> recommend to your "customers' (I don't actually think you have any >>> customers). >> ROFL! I'm sorry, you're right -- this has all been a figment of my >> imagination... >> >> http://www.pymolwiki.org/index.php/Covers You forgot http://www.nature.com/neuro/journal/v10/n8/covers/index.html James From __peter__ at web.de Sun Dec 14 14:05:59 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 14 Dec 2008 20:05:59 +0100 Subject: Shorter tracebacks References: Message-ID: Peter Otten wrote: > That's none of __future__'s business, I think. Python offers a hook which > you can modify: > >>>> import sys, traceback >>>> from functools import partial >>>> sys.excepthook = partial(traceback.print_exception, limit=5) I just stumbled upon >>> import sys >>> sys.tracebacklimit Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'tracebacklimit' >>> sys.tracebacklimit = 2 >>> def f(): f() ... >>> f() Traceback (most recent call last): File "", line 1, in f File "", line 1, in f RuntimeError: maximum recursion depth exceeded Peter From pdorange at pas-de-pub-merci.mac.com Fri Dec 26 06:06:50 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Fri, 26 Dec 2008 12:06:50 +0100 Subject: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> <90f06b27-39da-4f1a-a878-f3972e942d57@s24g2000vbp.googlegroups.com> <62caf93b-0455-4450-9895-8a9d9554f75e@r32g2000vba.googlegroups.com> <1isezkk.51e05y1457jqrN%pdorange@pas-de-pub-merci.mac.com> <3cb2a746-1a43-44a1-9825-7667af9fe2fa@s1g2000prg.googlegroups.com> <1isi4sn.11mpft612g7udcN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <1isk1kn.1s8efppxapfeaN%pdorange@pas-de-pub-merci.mac.com> r wrote: > > Go to Google groups... it looks perfect :) It's a usenet group here, nothing to do with google groups. To get back to the group subject, what is your actual python projects ? -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From v+python at g.nevcal.com Thu Dec 4 02:34:28 2008 From: v+python at g.nevcal.com (Glenn Linderman) Date: Wed, 03 Dec 2008 23:34:28 -0800 Subject: Multiple Versions of Python on Windows XP In-Reply-To: References: <4934de22$0$27863$9b622d9e@news.freenet.de> <493592EE.9090005@v.loewis.de> Message-ID: <49378804.2050807@g.nevcal.com> On approximately 12/3/2008 8:51 AM, came the following characters from the keyboard of Colin J. Williams: > Martin v. L??wis wrote: >>>>> What changes are made to the registry? >>>> For a complete list, see Tools/msi/msi.py in the source tree. >>> I have scanned the file: >>> http://svn.python.org/projects/python/branches/py3k/Tools/msi/msi.py >>> >>> I don't find anything that addresses this issue. >> >> Read the add_registry function. You may need to first understand >> how the Registry table in an MSI file works. >> >>> I am seeking some mechanism such that any of Python 2.5, Python 2.6 or >>> Python 2.6 can be chosen as the currently active version. >> >> If Glenn Lindermann's answer doesn't help, you need to explain: >> what is a "currently active version"? How is one Python version >> more active than any other? >> >>> I was hoping that there is some simpler way than the "Repair" >>> procedure. >> >> See Glenn Lindermann's answer. >> >>>> It would be good to be more specific with such statements: what >>>> troubles >>>> specifically? If I play dumb, I'd say "of course - windows explorer >>>> doesn't support editing Python files; you need a text editor". >>> Yes, I should have been clearer. The PyScripter application locks up >>> and must be killed, using the Task Manager. >> >> I think you need to report that to the PyScripter authors as a bug. >> I can't imagine how the "currently active version" can affect what >> PyScripter does. >> >> Regards, >> Martin > > Martin, > > Many thanks for your responses. Yes, > Glen Lindermann's suggestion seems to > meet the need. > > It's been a while since I've looked at > DOS and I didn't remember fType or assoc. The equivalent of those commands is available via Windows Explorer, Tools / Folder Options, File Types, scroll-scroll-scroll your way to .py, Click Advanced, fiddle, copy paste apply, and other twaddle. A perfect example of why not everything should be done via GUI interfaces, or at least why this is an extremely poor GUI interface. GUI designers should count the command line keystrokes, and make sure their interface is shorter, otherwise they are a failure. > Michel Claveau suggests VirtualBox, this > seems a big hammer to kill > this particular fly. > > It's interesting that each install sets > up a Python.File variable in the registry. > > It's a pity that this can't be used to achieve this more simply. Martin seems willing to entertain the idea of future Windows installers doing something more brilliant in this area, for those that wish to switch between multiple installed versions, as he asked for a tracking issue to be created, which I did. Whether it will be exactly my technique, or something further improved, time will tell. But that will only apply to versions released after 3.0 and 2.6.1 (unless he has already coded it into the release, but I doubt he had time, or wishes to destabilize or delay these releases). Anyway, if you remember the arcane techniques for copy/paste in CMD prompt windows (Alt-space or click the "system" icon in the upper left of the CMD prompt window), and go from there, then setting up the multiple ftypes becomes a bit easier, perhaps. > Best wishes, > > Colin W. -- Glenn -- http://nevcal.com/ =========================== A protocol is complete when there is nothing left to remove. -- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking From hniksic at xemacs.org Mon Dec 15 04:51:49 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 15 Dec 2008 10:51:49 +0100 Subject: cx_Oracle issues References: <5b2dad81-2750-4347-8079-6ab31321d579@s1g2000prg.googlegroups.com> <9142a8f1-7f76-4fc0-9ca1-c9dec310f2ce@r37g2000prr.googlegroups.com> <9f436c9e-2319-499c-a306-d255996372fc@e22g2000vbe.googlegroups.com> Message-ID: <871vw9bway.fsf@mulj.homelinux.net> huw_at1 writes: >> > ORA-06502: PL/SQL: numeric or value error: character string buffer too >> > small ORA-06512: at line 1 >> >> This error is a problem with the PL/SQL, not cx_Oracle. ?You need to >> debug obj.function to see what kind of data is being accessed and then >> a data analysis of that data to understand why this error occurs. ?I >> can tell you the function is most likely expecting characters from a >> column that are numeric [0 .. 9] and is getting alpha characters. > > Hi thanks for the responses. Unfortunately the procedure in question > is from a third party vendor so I can't really debug it so I'd say I > was fairly stumped. Just out of interest how do you increase the > output buffer size with cx_Oracle? Ron's point was that you cannot fix this problem on the side of cx_Oracle because the exception occurs before cx_Oracle ever sees the result, during the execution of PL/SQL code. This is easy to verify: simply run the function the same way in sqlplus. If the problem persists, it's a bug in the function (or in the way you're calling it, or setting up the data, etc.) and you should complain to your vendor, or somehow work around the problem. Otherwise it's a cx_Oracle related problem. From sjmachin at lexicon.net Mon Dec 29 07:35:48 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 29 Dec 2008 04:35:48 -0800 (PST) Subject: AttributeError: 'module' object has no attribute 'DatagramHandler' (ubuntu-8.10, python 2.5.2) References: <4c6f0831-c05f-401f-b956-376600b38e06@r15g2000prd.googlegroups.com> Message-ID: <75aaddb4-faf3-47d4-850b-194e9c560071@c36g2000prc.googlegroups.com> On Dec 29, 11:08?pm, Tzury Bar Yochay wrote: > $ ~/devel/ice/snoip/freespeech$ python > Python 2.5.2 (r252:60911, Oct ?5 2008, 19:24:49) > [GCC 4.3.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> import logging > >>> logging.DatagramHandler > > Traceback (most recent call last): > ? File "", line 1, in > AttributeError: 'module' object has no attribute 'DatagramHandler' > > > > That is odd since the documentation says there is DatagramHandler for > module logging According to http://www.python.org/doc/2.5.2/lib/module-logging.html """ The StreamHandler and FileHandler classes are defined in the core logging package. The other handlers are defined in a sub- module, logging.handlers. """ and later in http://www.python.org/doc/2.5.2/lib/node415.html """ The DatagramHandler class, located in the logging.handlers module, ... """ HTH, John From rt8396 at gmail.com Tue Dec 16 17:00:16 2008 From: rt8396 at gmail.com (r) Date: Tue, 16 Dec 2008 14:00:16 -0800 (PST) Subject: What does the at sign do? References: Message-ID: Google "python decorators" From huwdjones at gmail.com Wed Dec 10 11:48:45 2008 From: huwdjones at gmail.com (huw_at1) Date: Wed, 10 Dec 2008 08:48:45 -0800 (PST) Subject: cx_Oracle issues Message-ID: <5b2dad81-2750-4347-8079-6ab31321d579@s1g2000prg.googlegroups.com> Hey all. When using cx_Oracle to run a procedure like: cursor.execute("select (obj.function(value)) from table where id=blah") I am getting the following error: ORA-06502: PL/SQL: numeric or value error: character string buffer too small ORA-06512: at line 1 Looking at cursor.description I get: [('(obj.function(value))', , 4000, 4000, 0, 0, 1)] Any tips - i have never seen this error before but am guessing that the value being returned is too big for the buffer size set for the cursor. the procedure fetches data from a LOB. Any suggestions/confirmations? Many thanks From israelu at elbit.co.il Wed Dec 31 06:30:11 2008 From: israelu at elbit.co.il (iu2) Date: Wed, 31 Dec 2008 03:30:11 -0800 (PST) Subject: Pass by reference Message-ID: <529e1d98-8932-49f0-b569-85285bd50f23@p2g2000prn.googlegroups.com> Hi, Is it possible somehow to change a varible by passing it to a function? I tried this: def change_var(dict0, varname, val): dict0[varname] = val def test(): a = 100 change_var(locals(), 'a', 3) print a But test() didn't work, the value a remains 100. I have several variables initialized to None. I need to convert each one of them an object only if it is None. something like: if not var1: var1 = MyObject() I want this to be a function, that is: def create_obj(var): if not var: var = MyObj() # set properties of var Now, I know I can achieve this by functional programming, def create_obj(var): if not var: x = MyObj() # set properties of x return x return var and then var = creaet_obj(var) Is there another way? Thanks From wuwei23 at gmail.com Thu Dec 4 01:35:50 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 3 Dec 2008 22:35:50 -0800 (PST) Subject: Multiple equates References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> Message-ID: <1d15d626-b548-4b27-9a63-114360607680@n33g2000pri.googlegroups.com> On Dec 4, 1:52?pm, Lawrence D'Oliveiro wrote: > Why is that? Was Rossum frightened in his cradle by a lambda when he was a > baby? Are some people afraid of lambdas the way others are afraid of > spiders? "Language designers are a superstitious and cowardly lot..." From steve at REMOVE-THIS-cybersource.com.au Thu Dec 11 15:09:51 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 Dec 2008 20:09:51 GMT Subject: newbie question: if var1 == var2: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> <87y6ymzecp.fsf@daycos.com> Message-ID: <01516b1e$0$20639$c3e8da3@news.astraweb.com> On Thu, 11 Dec 2008 13:44:22 -0600, Kirk Strauser wrote: > At 2008-12-11T17:24:44Z, rdmurray at bitdance.com writes: > >> >>> ' ab c \r\n'.rstrip('\r\n') >> ' ab c ' >> >>> ' ab c \n'.rstrip('\r\n') >> ' ab c ' >> >>> ' ab c '.rstrip('\r\n') >> ' ab c ' > > I didn't say it couldn't be done. I just like the Perl version better. def chomp(s): return s.rstrip('\r\n') And now you have chomp. -- Steven From mail at johnohagan.com Tue Dec 16 03:16:24 2008 From: mail at johnohagan.com (John O'Hagan) Date: Tue, 16 Dec 2008 08:16:24 +0000 Subject: Python music sequencer timing problems In-Reply-To: <200812150332.08748.mail@johnohagan.com> References: <3b52b652-df61-4eb4-bcff-0d1fb6f20891@r15g2000prh.googlegroups.com> <49451835$0$17068$6e1ede2f@read.cnntp.org> <200812150332.08748.mail@johnohagan.com> Message-ID: <200812160816.26006.mail@johnohagan.com> On Mon, 15 Dec 2008, John O'Hagan wrote: > On Sun, 14 Dec 2008, Bad Mutha Hubbard wrote: > > John O'Hagan wrote: > > > On Wed, 10 Dec 2008, badmuthahubbard wrote: > > [...] > > > > from time import time, sleep > > > > > > start = time() > > > for event in music: > > > duration=len(event) #Really, the length of the event > > > play(event) > > > while 1: > > > timer = time() > > > remaining = start + duration - timer > > > if remaining < 0.001: > > > break > > > else: > > > sleep(remaining / 2) > > > stop(event) > > > start += duration > > > > Very interesting approach, halving the remaining duration. Right now > > I'm not working with note-offs, Csound takes care of the duration. I > > just need to be able to call the notes at the right times. > > [...] > > I'm also using the above code without the "stop(event)" line for playing > non-midi stuff (fixed-length samples for example), which from the sound of > it also applies to your requirement - IOW, you _can_ use it just to start > notes at the right time, because the note-playing loop sleeps till then. > And as I realized after having a good sleep myself, this is only useful for timing events which occur sequentially and do not overlap, which is how my program works because it generates the events in real time, but which may be of no use in your case. But I suppose the same principle could be applied to reduce the number of calls needed in a separate timing thread. Unless of course each event contained the start-time of the next event as an attribute....? John From pavlovevidence at gmail.com Wed Dec 10 21:55:59 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 10 Dec 2008 18:55:59 -0800 (PST) Subject: internal circular class references References: Message-ID: On Dec 10, 5:26?pm, Ethan Furman wrote: > Greetings List! > > I'm writing a wrapper to the datetime.date module to support having no > date. ?Its intended use is to hold a date value from a dbf file, which > can be empty. > > The class is functional at this point, but there is one thing I would > like to change -- datetime.date.max and datetime.date.min are class > attributes of datetime.date, and hold datetime.date values. ?At this > point I have to have two lines outside the actual class definition to do > the same thing, e.g.: > > > ? ?class NullDate(object): > ? ? ? ?"adds null capable DateTime.Date constructs" > ? ? ? ?__slots__ = ['_date'] > ? ? ? ?def __new__(cls, date='', month=0, day=0): > ? ? ? ? ? ?nulldate = object.__new__(cls) > ? ? ? ? ? ?nulldate._date = "" > ? ? ? ? ? ? ? ? . > ? ? ? ? ? ? ? ? . > ? ? ? ? ? ? ? ? . > ? ? ? ? ? return nulldate > ? ? ? ?def __getattr__(self, name): > ? ? ? ? ? ?if self: > ? ? ? ? ? ? ? ?attribute = self._date.__getattribute__(name) > ? ? ? ? ? ? ? ?return attribute > ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ?if callable(dt.date.__dict__[name]): > ? ? ? ? ? ? ? ? ? ?return int > ? ? ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ? ? ?return 0 > ? ? ? ?def __nonzero__(self): > ? ? ? ? ? ?if self._date: > ? ? ? ? ? ? ? ?return True > ? ? ? ? ? ?return False > ? ? ? ?@classmethod > ? ? ? ?def fromordinal(cls, number): > ? ? ? ? ? ?if number: > ? ? ? ? ? ? ? ?return cls(dt.date.fromordinal(number)) > ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ?return cls() > ? ?NullDate.max = NullDate(dt.date.max) > ? ?NullDate.min = NullDate(dt.date.min) > > > How can I move those last two lines into the class definition so that: > ? ?1) they are class attributes (not instance), and > ? ?2) they are NullDate type objects? It can't be done by any straightforward method I know of. I advise you not to worry about it, and just define them afterwards, perhaps with an apologetic comment saying you would have put them inside the class definition if you could have. If the out-of-scope issue bothers you that much, you could use some metaclass hackery to run a method that defines the class attributes after the class is created, at the unrecommendable cost of confusing most readers. Here is a very simple example: def make_class_and_run_postcreate(name,bases,clsdict): cls = type.__new__(type,name,bases,clsdict) cls.__postcreate__() return cls class A(object): __metaclass__ = make_class_and_run_postcreate @classmethod def __postcreate__(cls): cls.internal_circular_class_ref = cls() BTW, if you don't mind some criticism of your code, the code you posted seems to be much too complex for the job you're describing. First of all, do you even need to wrap the datetime.date class? With Python's duck typing ability, you could have a separate NullDate class to go alongside the datetime.date, and use a regular datetime.date object when the date is present, and NullDate when it's absent. If necessary you can subclass datetime.date to add any new methods it would have to have. Use a factory function to return either NullDate or a datetime.date depending on whether the dbf cell is empty. class ValidDate(datetime.date): def is_valid(self): return True class NullDate(object): # implement any necessary methods of datetime.date interface here def is_valid(self): return False def create_date_from_dbf_cell(dbf_cell): if dbf_cell.empty(): return NullDate() return ValidDate(dbf_cell.value) If you do this, you don't have to muck around with __getattr__ or __new__ or snooping to datetime.date's class dict anything like that. Carl Banks From mnordhoff at mattnordhoff.com Wed Dec 17 06:32:22 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Wed, 17 Dec 2008 11:32:22 +0000 Subject: Free place to host python files? In-Reply-To: References: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> <47c890dc0812161625o76f5c7e6lb8809b99f6962d32@mail.gmail.com> Message-ID: <4948E346.7090009@mattnordhoff.com> James Mills wrote: > On Wed, Dec 17, 2008 at 10:25 AM, Chris Rebert wrote: >> I'll plug Bitbucket (http://bitbucket.org/). It gives you 150MB of >> Mercurial hosting for free, along with a bug tracker and wiki. And I >> hear it's implemented using Django. > > FreeHG (http://freehg.org) is pretty good too :) > > cheers > James I'll throw in too. No wiki, though. And , I guess. -- From warren at delsci.com Wed Dec 3 17:49:19 2008 From: warren at delsci.com (Warren DeLano) Date: Wed, 3 Dec 2008 14:49:19 -0800 Subject: "as" keyword woes Message-ID: <896B75251BA19745A529B1B867893FA50679C8@planet.delsci.local> > Because it can be used at the import statement to let the imported thing > be known under another name? > Something like: > > >>> import xml.etree.ElementTree as ET Yes, but that syntax worked fine for years without "as" actually having to be a keyword. There must be something more going on here... I have to believe that was some reason or benefit gained from making it a keyword, and thus prohibiting its use anywhere else, as opposed to sticking with the status quo. Otherwise this would merely be a pointless change (perhaps even destructive!). From google at mrabarnett.plus.com Wed Dec 24 14:10:51 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 24 Dec 2008 19:10:51 +0000 Subject: [SPAM] VERY simple string comparison issue In-Reply-To: <89f89940812241027o40e3d079v9f9d76e76b1af4a6@mail.gmail.com> References: <89f89940812241027o40e3d079v9f9d76e76b1af4a6@mail.gmail.com> Message-ID: <4952893B.4020008@mrabarnett.plus.com> Brad Causey wrote: > Python Version: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC > v.1310 32 bit (Intel)] on win32 > > List, > > I am trying to do some basic log parsing, and well, I am absolutely > floored at this seemingly simple problem. I am by no means a novice in > python, but yet this is really stumping me. I have extracted the > pertinent code snippets and modified them to function as a standalone > script. Basically I am reading a log file ( in this case, testlog.log) > for entries and comparing them to entries in a safe list (in this case, > safelist.lst). I have spent numerous hours doing this several ways and > this is the most simple way I can come up with: > > > import string > > safelistfh = file('safelist.lst', 'r') > safelist = safelistfh.readlines() > > logfh = file('testlog.log', 'r') > loglines = logfh.readlines() > > def safecheck(line): > for entry in safelist: > print 'I am searching for\n' > print entry > print '\n' > print 'to exist in\n' > print line > comp = line.find(entry) > if comp <> -1: > out = 'Failed' > else: > out = 'Passed' > return out > Unless I've misunderstood what you're doing, wouldn't it be better as: def safecheck(line): for entry in safelist: print 'I am searching for\n' print entry print '\n' print 'to exist in\n' print line if entry in line: return 'Passed' return 'Failed' > for log in loglines: > finalentry = safecheck(log) > if finalentry == 'Failed': > print 'This is an internal site' > else: > print 'This is an external site' > > Actually, I think it would be better to use True and False instead of 'Passed' and 'Failed. > The contents of the two files are as follows: > > > http://www.mysite.com > > > > http://www.mysite.com/images/homepage/xmlslideshow-personal.swf > > > It seems that no matter what I do, I can't get this to fail the " if > comp <> -1:" check. (My goal is for the check to fail so that I know > this is just a URL to a safe[internal] site) > My assumption is that the HTTP:// is somehow affecting the searching > capabilities of the string.find function. But I can't seem to locate any > documentation online that outlines restrictions when using special > characters. > > Any thoughts? > You'll still need to strip off the '\n'. From castironpi at gmail.com Tue Dec 2 21:05:47 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 2 Dec 2008 18:05:47 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> <00ab327a-c3fc-4b15-a084-4f8c6aed6a8e@o2g2000yqd.googlegroups.com> Message-ID: <8119ab7e-09f1-44de-bdbc-8fdff969d9e4@33g2000yqm.googlegroups.com> On Dec 2, 6:24?pm, r wrote: > I added you name to my "for" list. thanks +1 entertaining thread. From benjamin.kaplan at case.edu Fri Dec 5 14:00:46 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 5 Dec 2008 14:00:46 -0500 Subject: slow Python 3.0 write performance? In-Reply-To: References: Message-ID: On Fri, Dec 5, 2008 at 1:54 PM, Istvan Albert wrote: > Could someone run the code below on both Python 2.5 and 3.0 > > For me (on Windows) it runs over 7 times slower with Python 3.0 > > import time > > lo, hi, step = 10**5, 10**6, 10**5 > > # writes increasingly more lines to a file > for N in range(lo, hi, step): > fp = open('foodata.txt', 'wt') > start = time.time() > for i in range( N ): > fp.write( '%s\n' % i) > fp.close() > stop = time.time() > print ( "%s\t%s" % (N, stop-start) ) > > > > -- > http://mail.python.org/mailman/listinfo/python-list > This bug was already found. http://groups.google.com/group/comp.lang.python/browse_thread/thread/9046eee09137c657# -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrew at doadesweb.co.uk Wed Dec 10 13:14:46 2008 From: andrew at doadesweb.co.uk (Andrew D) Date: Wed, 10 Dec 2008 10:14:46 -0800 (PST) Subject: get todays files References: <3090b59b-a0b2-4bfb-a08f-6d6accfb363a@k36g2000pri.googlegroups.com> Message-ID: <26ee72ee-ebfd-4719-a1b2-22665fec9c0d@i20g2000prf.googlegroups.com> On Dec 10, 6:13?pm, Steve Holden wrote: > Andrew D wrote: > > On Dec 10, 5:55 pm, Steve Holden wrote: > >> Andrew D wrote: > >>> I have a script that will login to my ftp server and download all the > >>> backup files, but I want it to only download the files that were > >>> created today, e.g. if I ran the script today I want it to only fetch > >>> files created today. > >>> I am really not sure about how to do this, but it is quite important > >>> to me, so all help is highly appreciated! > >> IIRC there's an "ftpmirror" script in the Tools directory (if you're on > >> Windows - Linux/Unix users have to download the source). I adapted it to > >> several different purposes. > > > Thanks Steve, > > > I don't want to sound rude here, but I really want some code to add to > > my script so that it will only download todays files. > > That's OK. Maybe somebody's already got that code ready to go. I don't ... > > regards > ?Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ Thank you anyway Steve! Lets hope someone has the code ;) Andrew From gruszczy at gmail.com Fri Dec 12 06:15:12 2008 From: gruszczy at gmail.com (=?UTF-8?Q?Filip_Gruszczy=C5=84ski?=) Date: Fri, 12 Dec 2008 12:15:12 +0100 Subject: Removing None objects from a sequence In-Reply-To: References: Message-ID: <1be78d220812120315y70688a4do455bdf41d7e53b03@mail.gmail.com> I don't mean memory, but space in code ;-) I'll try this generator :) -- Filip Gruszczy?ski From skip at pobox.com Tue Dec 9 16:39:24 2008 From: skip at pobox.com (Skip Montanaro) Date: Tue, 9 Dec 2008 21:39:24 +0000 (UTC) Subject: Test message - please ignore Message-ID: Testing a new news-to-mail gateway on mail.python.org. This post is from gmane. Please ignore. Thx, Skip Montanaro From akineko at gmail.com Mon Dec 22 18:43:21 2008 From: akineko at gmail.com (akineko) Date: Mon, 22 Dec 2008 15:43:21 -0800 (PST) Subject: 64-bit / 128-bit data element type for array? References: <880c8478-8b40-40e0-8597-aef960612f09@s9g2000prg.googlegroups.com> Message-ID: Robert wrote: > Ah, good. numpy lets you construct your own data types from the primitives. > Since you don't actually need uint128 arithmetic, you don't need a uint128 > primitive. You can just use dtype('V16') (meaning "void, 16 bytes long") ... Impressive. I installed NumPy and it worked like a charm (I used uint64). The above feature is quite useful as the bus size inside a microchip is getting wider and wider (to get higher performance). Again, thank you for replying to my posting. Happy Holidays! Aki Niimura From luismgz at gmail.com Mon Dec 22 14:50:17 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Mon, 22 Dec 2008 11:50:17 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: <1d03c66b-c725-42f4-af6e-2351a7841b30@z1g2000yqn.googlegroups.com> On Dec 22, 3:44?pm, r wrote: > Steve Holden > > > What makes you assume this is a zero-sum game, and that Python won't > > survive if any other language becomes popular. Every language borrows > > from those that came before it. Terms like "outright plagiarism" don't > > encourage rational debate, and make you seem like a troll who is more > > interested in stirring up controversy than actually doing things to help > > promote the language. > > This is a war Steve, and i will explain why. Python does not need to > compete with perl, lisp, C, basic, etc, etc. WHY, well because python > is SO radically different than those languages. Ruby on the other > hand, took most from python, the only difference is Ruby's full OO > integration.(12.method()). Since Ruby is so similar to python we must > consider that some people who would have found only python in this > niche now could go to Ruby. I am for choices, but this is out and out > robbery! > Of course we must stand on the shoulders of greater minds than our own > to get ahead, but using someone's knowledge against them is wrong. If > Ruby want's to incorporate so many Pythonian ideas into their > language, at least put a note in the tutorial giving credit to Guido > for his wisdom. Don't use our ideas and then bash python in the next > breath! > > > I have an article about the Zen coming up in "Python Magazine" so I > > won't steal its thunder. Suffice it to say that people take the Zen far > > too seriously. Anyone who does so undermines their own credibility as a > > Python commentator. This isn't a war. Stop being childish. > > I was speaking to the loyalty of Pythonista's. Of course we are not > really going to slay mats, come on Steve, get real! > > > If all you want from a language is speed, go use C. I would avoid > > assembly language though, since a modern optimizing C compiler will > > often beat an assembly language programmer for execution speed, and the > > programming time will definitely be shorter. But to make speed the > > be-all and end-all is a witless approach. Speed is definitely not why > > dynamic languages' popularity is increasing. Speed *is* still relevant > > in certain areas, and completely irrelevant in others. > > Come on Steve, i am NOT saying speed is the only thing that matters > here! But it is very important. I never compared Python to C, that is > madness. But it must be better, faster, smarter than it's direct > competition(ruby)... you agree?? > > > Much more of this kind of tripe and nobody will read what you write > > anyway. You will hear the plonking of a hundred thousand newsreaders > > every time you post. > > Oh Steve... Listen, my words are ment as a wake-up-call to all who > still love Python, and i believe you are one of them. Maybe old age > has slowed your hand, that's OK, Us "youngsters" will take the helm. > And be serious, do you really think this group is read by "hundreds-of- > thousands of news readers? I wish it were, but I highly doubt it. Dude, calm down... There is no war here. Please turn off your computer, go take a walk for awhile, experience some real life in the outer world, and then think about this again. Python is cool language, Ruby too. We are all happy and competition is good. Nobody will win this "war" and the loser won't be annihilated. I hope there will be some healthy cross-pollination. There is actually, for example python borrowed list-comprehensions from haskell and I've never heard any haskell fan calling for jihad. Did you know that people are looking forward to use pypy to create a fast ruby implementation? Pypy is being developed by python developers and they will be happy to see a ruby, perl, logo or whatever language implemented with pypy. We are talking about tools, not religions. Those who use them to create useful, real life applications know it. Soon, we will be able to use python libraries from ruby and the other way around. the differences will be just a matter of taste, different syntax to achieve the same tasks. Luis From kermit.group at gmail.com Mon Dec 8 00:26:27 2008 From: kermit.group at gmail.com (Group) Date: Mon, 08 Dec 2008 13:26:27 +0800 Subject: A question about reference in Python. Message-ID: <493CB003.3080209@gmail.com> Hello, I'm studying algorithom. For concentrating on the question itself, I intend to use Python to implement the algorithoms. Now, I want to write a Red-Black Tree, and a List structure. In C/C++, I can use pointers to refer to children notes (or next notes). But, in Python, how can I do it? Except the sequence, I know not any way. You'd better help me understan how can I transform the following C code into Python: /* a List */ struct { int data; int *next; int *prev; } That's all. Thanks! Kermit From clp at rebertia.com Sat Dec 20 22:38:35 2008 From: clp at rebertia.com (Chris Rebert) Date: Sat, 20 Dec 2008 19:38:35 -0800 Subject: linecache vs egg - reading line of a file in an egg In-Reply-To: References: Message-ID: <47c890dc0812201938y4f6dbd73jd25453fb43161d9f@mail.gmail.com> On Sat, Dec 20, 2008 at 7:18 PM, R. Bernstein wrote: > Does linecache work with source in Python eggs? If not, is it > contemplated that this is going to be fixed or is there something else > like linecache that currently works? I believe it already does. FYI, eggs are just zip files with a certain file/directory structure. And linecache seems to handle reading from zipfile modules. Ergo, linecache can read source from eggs. Quoting from the linecache docs (http://docs.python.org/library/linecache.html), emphasis mine: linecache.getline(filename, lineno[, module_globals]) If a file named filename is not found, the function will ***look for it in the module search path, sys.path***, after first checking for a PEP 302 __loader__ in module_globals, in case the module was ***imported from a zipfile*** or other non-filesystem import source. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From jason.scheirer at gmail.com Tue Dec 2 18:32:25 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Tue, 2 Dec 2008 15:32:25 -0800 (PST) Subject: Multiple Versions of Python on Windows XP References: Message-ID: <994220a5-ff22-4c4b-8fe2-bbe3d609b90a@k36g2000pri.googlegroups.com> On Dec 1, 4:49?pm, "Colin J. Williams" wrote: > Could anyone please point me to > documentation on the way the msi > installer handles multiple versions eg. > Python 2.5, 2.6 and 3.0? > > What changes are made to the registry? > > Is there some way to specify a default > version in such a way that it can be > changed as necessary? > > PyScripter uses an option to select a > version eg. > > C:\Program > Files\PyScripter\PyScripter.exe --python26 > > but I'm having some trouble with it when > I attempt edit a python file from the > Windows Explorer. > > I would appreciate any information. > > Colin W. Some more factoids that may be of use: 1. The last Python you install will take over all the file associations, start menu stuff, etc. 2. You can enumerate over the Pythons you have installed in \ \HKEY_LOCAL_MACHINE\Software\Python\PythonCore\ 3. If you silently install a Python PACKAGE made with distutils' bdist_msi, it will by default install to the latest Python version it finds (2.6 > 2.5 > 2.4 > 2.3) From fetchinson at googlemail.com Sat Dec 27 21:44:38 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 27 Dec 2008 18:44:38 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: >>>> I agree that array.array is more efficient than a list but the input >>>> for my function will come from PIL and PIL returns a list. So I have a >>>> list to begin with which will be passed to the C function. >>> With recent versions of PIL, numpy can create an array from an Image very >>> quickly, possibly without any copying of memory. >> >> What exactly do you mean? (1) PIL creates a list which can be easily >> converted by numpy to a numpy.array or (2) with the help of numpy one >> can create a numpy.array from an image directly? > > (2) a = numpy.asarray(img) Thanks, I didn't know about this, maybe it will be useful. >> Since I will have to pass the list or numy.array to C anyway I don't >> see any advantage to (1) although (2) can be useful. > > (1) is still somewhat useful, if you're willing to bear the cost of the > numpy > dependency. The conversion code from any Python sequence to a numpy array of > the > desired type and dimensionality is a 2-liner (function call and error > check). > The memory is managed by numpy, so all you have to do is manage the refcount > of > the array object like any other Python object. > > Okay, 5-liner given C's verbosity: > > intx = PyArray_FROM_OTF(pyintx, PyArray_INT, NPY_IN_ARRAY); > if (!intx) { > PyErr_SetString(PyExc_ValueError, "intx must be an array of ints"); > goto fail; > } Yes, the dependency on numpy is my main concern. If it will help with my problem I don't mind the dependency actually, so I'll do more detailed benchmarks first. Thank you, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From narkewoody at gmail.com Fri Dec 19 08:50:12 2008 From: narkewoody at gmail.com (Steven Woody) Date: Fri, 19 Dec 2008 21:50:12 +0800 Subject: How to parsing a sequence of integers In-Reply-To: <494ba258$0$18998$426a74cc@news.free.fr> References: <494ba258$0$18998$426a74cc@news.free.fr> Message-ID: On Fri, Dec 19, 2008 at 9:33 PM, Bruno Desthuilliers wrote: > Steven Woody a ?crit : >> >> Hi, >> >> I am a newbie and is reading the python book. Could anyone tell me, >> how to parsing the following string >> "123 100 12 37 ..." > >> into a list of integers on which I can then apply max()/min()? > > source = "123 100 12 37" > list_of_ints = [int(part) for part in source.strip().split()] > >> >> In additional to max/min, is there something like average()? > > Not AFAIK, but it's really trivial > > def average(lst): > """ assume lst is a list of numerics """ > return sum(lst) / len(lst) > Cool! Thank all of you. From sjmachin at lexicon.net Fri Dec 5 17:32:23 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 5 Dec 2008 14:32:23 -0800 (PST) Subject: Python 3.0 automatic decoding of UTF16 References: <5u8o06xbqf.ln2@joeserver.homelan.net> Message-ID: On Dec 6, 5:36?am, Johannes Bauer wrote: > So UTF-16 has an explicit EOF marker within the text? I cannot find one > in original file, only some kind of starting sequence I suppose > (0xfeff). The last characters of the file are 0x00 0x0d 0x00 0x0a, > simple \r\n line ending. Sorry, *WRONG*. It ends in 00 0d 00 0a 00. The file is 1559 bytes long, an ODD number, which shouldn't happen with utf16. The file is stuffed. Python 3.0 has a bug; it should give a meaningful error message. Python 2.6.0 silently ignores the problem [that's a BUG] when read by a similar method: | >>> import codecs | >>> lines = codecs.open('x.txt', 'r', 'utf16').readlines() | >>> lines[-1] | u'[PhonePBK004]\r\n' Python 2.x does however give a meaningful precise error message if you try a decode on the file contents: | >>> s = open('x.txt', 'rb').read() | >>> len(s) | 1559 | >>> s[-35:] | '\x00\r\x00\n\x00[\x00P\x00h\x00o\x00n\x00e\x00P\x00B\x00K \x000\x000\x004\x00]\x00\r\x00\n\x00' | >>> u = s.decode('utf16') | Traceback (most recent call last): | File "", line 1, in | File "C:\python26\lib\encodings\utf_16.py", line 16, in decode | return codecs.utf_16_decode(input, errors, True) | UnicodeDecodeError: 'utf16' codec can't decode byte 0x00 in position 1558: truncated data HTH, John From castironpi at gmail.com Mon Dec 29 08:53:09 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 05:53:09 -0800 (PST) Subject: Read-Write Lock vs primitive Lock() References: <277c1be7-2560-4fd6-9610-0b4398dc3719@x16g2000prn.googlegroups.com> Message-ID: <0740d4b8-6c1e-432a-a2c4-ca73473831dd@a12g2000pro.googlegroups.com> On Dec 29, 4:17?am, k3xji wrote: > On 29 Aral?k, 11:52, "Gabriel Genellina" > wrote: > > > En Mon, 29 Dec 2008 05:56:10 -0200, k3xji escribi?: > snip > > > class wthread(threading.Thread): > > > ? ? def run(self): > > > ? ? ? ? ? ? try: > > > ? ? ? ? ? ? ? ? #GLOBAL_LOCK.acquireWrite() > > > ? ? ? ? ? ? ? ? #GLOBAL_LOCK.acquire_write() > > > ? ? ? ? ? ? ? ? GLOBAL_LOCK.acquire() > > > ? ? ? ? ? ? ? ? for i in range(GLOBAL_LOOP_COUNT): > > > ? ? ? ? ? ? ? ? ? ? GLOBAL_VAR = 4 > > > ? ? ? ? ? ? finally: > > > ? ? ? ? ? ? ? ? #GLOBAL_LOCK.release_write() > > > ? ? ? ? ? ? ? ? GLOBAL_LOCK.release() > > > Note that the thread acquires the lock ONCE, repeats several thousand > > times an assignment to a *local* variable called GLOBAL_VAR (!) snip > > class wthread(threading.Thread): > > ? ? ? def run(self): > > ? ? ? ? ? global GLOBAL_VAR > > ? ? ? ? ? for i in xrange(GLOBAL_LOOP_COUNT): > > ? ? ? ? ? ? ? GLOBAL_LOCK.acquire() > > ? ? ? ? ? ? ? try: > > ? ? ? ? ? ? ? ? ? GLOBAL_VAR += 1 > > ? ? ? ? ? ? ? finally: > > ? ? ? ? ? ? ? ? ? GLOBAL_LOCK.release() > > With that, primitive locks perform 10 times better than Read-Write > lock. See above. snip Gabriel's point (one of them) was that 'GLOBAL_VAR' isn't global in your example. Your 'wthread' objects aren't sharing anything. He added the 'global GLOBAL_VAR' statement, which is important From skip at pobox.com Tue Dec 16 09:29:27 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 16 Dec 2008 08:29:27 -0600 Subject: Free place to host python files? In-Reply-To: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> References: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> Message-ID: <18759.47943.95858.384595@montanaro-dyndns-org.local> feba> I'm getting started in python, and it would be helpful to have a feba> place to put up various code snippets I've made, so I don't have feba> to send them individually to each person I want to show it to. feba> I'd prefer to use something that would give me a directory for my feba> use only, instead of something where you can only upload one at a feba> time. I'd especially like to avoid stuff that uses CAPTCHAs feba> and/or forced waiting periods. http://pastebin.com/? -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From p.f.moore at gmail.com Tue Dec 16 12:56:57 2008 From: p.f.moore at gmail.com (Paul Moore) Date: Tue, 16 Dec 2008 09:56:57 -0800 (PST) Subject: Does Python3 offer a FrozenDict? References: Message-ID: On 16 Dec, 17:28, bearophileH... at lycos.com wrote: > Johannes Bauer: > > > is there anything like a frozen dict in Python3, so I could do a > > foo = { FrozenDict({"a" : "b"}): 3 } > > You can adapt this code to Python3 (and post a new recipe? It may be > positive to create a new section of the Cookbook for Py3 only):http://code.activestate.com/recipes/414283/ There's actually only tiny changes needed (I believe) - Change exception syntax: raise AttributeError("A frozendict cannot be modified.") - (bugfix for the original version): add **kw arg to __new__ (passed to dict.__init__) Simple testing looks OK. And the resulting code is OK for both 2.x and 3.0. Moral - don't assume that all code needs to be rewritten for Python 3.0 :-) Paul. PS I imagine that 2to3 would have fixed this up fine, but it was so easy to do by hand that I didn't bother :-) From n.kottiyath at gmail.com Tue Dec 16 21:47:41 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Tue, 16 Dec 2008 18:47:41 -0800 (PST) Subject: Can anyone suggest a good HTTP/1.1 web client? References: Message-ID: <412038d6-81c0-4615-aab5-d3cea4093dfc@p2g2000prn.googlegroups.com> > If you'd like to help out with the new Twisted HTTP client, that would be > wonderful. ?Even if you can just try it out and report any problems you run > into, that would be immensely helpful. > > Jean-Paul I would love to help out with the client. But, I am extremely tied up at the current moment. I would be able to provide any sort of meaningful contribution only after ~a month. I can surely try this out and upload any bugs in the ticket you mentioned. Also, is there any planned date for persistent connections? If not, that will be the first thing I will be working on after my assignment is over - since it increasingly looks like it is essential to my system (actually, any REST applications). Thank you very much, Jean-Paul. Regards, K From castironpi at gmail.com Sun Dec 21 21:11:05 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 21 Dec 2008 18:11:05 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: <2dfbb87b-019e-43aa-a9ef-5de2b5ada846@s1g2000prg.googlegroups.com> On Dec 21, 6:14?pm, MRAB wrote: > Aaron Brady wrote: > > On Dec 21, 10:58 am, MRAB wrote: > >> Aaron Brady wrote: > >>> On Dec 21, 10:31 am, MRAB wrote: > > snip > >>>> The original format is a string. The result of '%' is a string if > >>>> there's only 1 placeholder to fill, or a (partial) format object (class > >>>> "Format"?) if there's more than one. Similarly, the format object > >>>> supports '%'. The result of '%' is a string if there's only 1 > >>>> placeholder to fill, or a new (partial) format object if there's more > >>>> than one. > >>>> ?>>> f = "%r %i" > >>>> ?>>> type(f) > >>>> > >>>> ?>>> f = f % (2, 3, 4) > >>>> ?>>> type(f) > >>>> > >>>> ?>>> f = f % 1 > >>>> ?>>> type(f) > >>>> > >>> Alright, so how are you handling: > >>>>>> f= "%s %i" > >>>>>> type( f ) > >>> > >>>>>> f= f% '%i' ?#now '%i %i' > >>>>>> type( f ) > >>> > >>>>>> f= f% 1 > >>>>>> type( f ) > >>> ? > >>> In other words, are you slipping '1' in to the very first available > >>> slot, or the next, after the location of the prior? > >> Let's assume that Format objects display their value like the equivalent > >> string format: > > >> ?>>> f = "%r %i" > >> ?>>> f > >> '%r %i' > >> ?>>> f = f % (2, 3, 4) > >> ?>>> f > >> > >> ?>>> f = f % 1 > >> ?>>> f > >> '(2, 3, 4) 1' > > >> ?>>> f = "%s %i" > >> ?>>> f > >> '%s %i' > >> ?>>> f = f % '%i' > >> ?>>> f > >> > >> ?>>> f = f % 1 > >> ?>>> f > >> '%%i 1' > > > I assume you meant '%i 1' since there are no more flags in f, and it's > > returned to a regular string. > > Correct. > > > 'f %= 1' doesn't work any more as in-place modulo, since one time, 'f' > > is a Format object, the other, 'f' is a string. ?Just raise an > > exception for that (or assign to __class__ IINM if I'm not mistaken). > > All assignments rebind, even the augmented form: > > ?>>> class C1(object): > ? ? ? ? def __mod__(self, value): > ? ? ? ? ? ? ? ? return C2() > > ?>>> class C2(object): > ? ? ? ? def __mod__(self, value): > ? ? ? ? ? ? ? ? return C2() > > ?>>> f = C1() > ?>>> f > <__main__.C1 object at 0x00D144F0> > ?>>> f % 0 > <__main__.C2 object at 0x00D143F0> > ?>>> f %= 0 > ?>>> f > <__main__.C2 object at 0x00D145B0> > > > > > Actually, the class you showed is kind of nifty. ?Tuples are correctly > > interpolated. ?I think on the whole you'll use more parenthesis, since > > each term in the tuple appears separately, and might be an expression > > (have a lower-precedence op.), as well as more modulo signs. > > > You can currently do-it-yourself, you just need a constructor in the > > format string. > > >>>> f = Format("%r %i") > >>>> type(f) > > > >>>> f = f % (2, 3, 4) > >>>> type(f) > > > > > Or, as someone suggested earlier, a new literal marking: > > Yes, I suggested that earlier, but it isn't needed because you can > create a format object with "Format(string)". However, most of the time > you won't bother to create a format object explicitly because of: > > class str(object): > ? ? ?def __mod__(self, value): > ? ? ? ? ?return Format(self) % value > > >>>> f = f"%r %i" > >>>> type(f) > > > > ?>>> # Explicitly > ?>>> f = Format("%r %i") > ?>>> f > > ?>>> f % (2, 3, 4) > > ?>>> > ?>>> # Implicitly, relying on the __mod__ method of str > ?>>> f = "%r %i" > ?>>> f > '%r %i' > ?>>> f % (2, 3, 4) > > > I'd also like to add that there's nothing to prevent format objects from > having other methods where multiple placeholders can be filled in one call: > > ?>>> # By position > ?>>> f = Format("%r %i") > ?>>> f > > ?>>> f.fill([(2, 3, 4), 1]) > '(2, 3, 4) 1' > ?>>> > ?>>> # By name > ?>>> f = Format("%{tuple}r %{int}i") > ?>>> f > > ?>>> f.fill({"tuple": (2, 3, 4), "int": 1}) > '(2, 3, 4) 1' You're choosing to favor the '.chain()' method over the '.fill()' method for the behavior of '%'. I don't think you've justified it though. >>> Format( "%r %i" ).chain( ( 2, 3, 4 ) ).chain( 0 ) '(2, 3, 4) 0' >>> Format( "%r %i" ).fill( ( 2, 3, 4 ), 0 ) '(2, 3, 4) 0' Plus, I almost think we've almost attained defeating the purpose. From bignose+hates-spam at benfinney.id.au Thu Dec 4 01:36:44 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 04 Dec 2008 17:36:44 +1100 Subject: "as" keyword woes References: Message-ID: <87fxl4v43n.fsf@benfinney.id.au> "Warren DeLano" writes: > > But I can offer what I believe is a good reason why it *should* be > > a reserved word: Because simple is better than complex, and > > special cases aren't special enough to break the rules. > > So you prefer broken code to broken rules, eh? Your customers must > love that! This is exactly the kind of ivory-tower thinking I feared > might be behind the decision (form over function, damn the users to > hell, etc.) I don't know how you infer any of those from what I said, nor from the process of introducing features in Python. None of what you say there rings at all true with anything I've experienced in Python's core or the attitudes surrounding development if the language; indeed, quite the opposite. > Anyway, it seems obvious that the right decision for our customers > (or more importantly, for their countless lines of > autogenerated-Python log, state, and code files from the past > decade) is to stick with C/Python 2.5.x for the time being [?] This is an entirely reasonable and viable option, all the more so because of the comprehensive work done by the Python developers to continue the viability of the Python 2.x line and ease introduction of new features. Best of luck pursuing your goals. -- \ ?I'd like to see a nude opera, because when they hit those high | `\ notes, I bet you can really see it in those genitals.? ?Jack | _o__) Handey | Ben Finney From gamersunit at gmail.com Thu Dec 4 17:38:37 2008 From: gamersunit at gmail.com (Gregory Plantaine) Date: Thu, 4 Dec 2008 14:38:37 -0800 (PST) Subject: Find Files in a Folder Between 2 Dates Message-ID: <4c54b6c5-ae4d-4b89-8c6d-940c96de29bb@n33g2000pri.googlegroups.com> Is there a way to find all the files in a folder, between 2 dates? For example: Firstdate = 200801010000 Seconddate = 200801020000 Find all the files in C:\Folder that are between Firstdate and SecondDate. From s_david_rose at hotmail.com Thu Dec 11 13:04:27 2008 From: s_david_rose at hotmail.com (dave rose) Date: Thu, 11 Dec 2008 18:04:27 +0000 (UTC) Subject: Python to open command script file Message-ID: Hello all I would like to know how to do the following. I'd like to have a generic python program that the user will open a command-script file to do actions. So, my python program will get a list of servers, enumerate them within a checklistbox in wxpython. Then I want to open a command-file that will run against each selected server that will look like this: ---------------------------SAMPLE------------------------ copy abc.xyz from c:\source to u:\target copy all from c:\source to u:\target unload netshld from server1 -------------------------END SAMPLE---------------------- (where I have a class serverfuncs, where I can: s = serverfuncs() s.unload('', '') Really, I can do all the actions, but I don't know how to trigger them from an independent script file. Thanks! -Dave From jon at ffconsultancy.com Thu Dec 11 17:57:45 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Thu, 11 Dec 2008 22:57:45 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <452ba58b-9377-4463-85e2-5ecdaa25a129@t39g2000prh.googlegroups.com> Message-ID: Xah Lee wrote: > On Dec 10, 2:47?pm, John W Kennedy wrote: >> Xah Lee wrote: >> > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, >> > you'll have 50 or hundreds lines. >> >> C: >> >> #include >> #include >> >> void normal(int dim, float* x, float* a) { >> float sum = 0.0f; >> int i; >> float divisor; >> for (i = 0; i < dim; ++i) sum += x[i] * x[i]; >> divisor = sqrt(sum); >> for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; >> >> } > > i don't have experience coding C. The code above doesn't seems to > satisfy the spec. The input should be just a vector, array, list, or > whatever the lang supports. > The output is the same datatype of the same dimension. The output is in the preallocated argument "a". It is the same type (float *) and has the same dimension. That is idiomatic C. You could define a struct type representing a vector that includes its length and data (akin to std::vector<..> in C++) but it would still be nowhere near 50 LOC as you claimed. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From anton.ranieri.it at gmail.com Sat Dec 6 07:03:04 2008 From: anton.ranieri.it at gmail.com (anton.ranieri.it at gmail.com) Date: Sat, 6 Dec 2008 04:03:04 -0800 (PST) Subject: Insert Multiple Records Using One Insert Statemen with MySQLdb module Message-ID: <6d85c9db-2769-461b-bfe0-974e4fad5e07@k8g2000yqn.googlegroups.com> Hi, I'd like to insert Multiple Records Using One Insert Statement inserting one record using one insert statement works this is the example: import MySQLdb conn = MySQLdb.connect(host="localhost",.....) cursore = conn.cursor() cursore.execute('INSERT INTO frutta (nome, quantita) VALUES(%s, %s)', ('Pompelmi', 10) ) but when I try to insert Multiple Records Using One Insert Statement in this way: cursore.execute('INSERT INTO frutta (nome, quantita) VALUES(%s, %s)', ('Pompelmi', 10), ('Pompelmi', 10), ('Pompelmi', 10) ) it doesn't work! Antonella From prologic at shortcircuit.net.au Sun Dec 21 21:04:07 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Dec 2008 12:04:07 +1000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <5b15041d-c1e9-4b28-b8ca-89505e49fe83@a12g2000pro.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <7fc23c41-6bf8-4272-b405-acc092cbac87@r15g2000prd.googlegroups.com> <5b15041d-c1e9-4b28-b8ca-89505e49fe83@a12g2000pro.googlegroups.com> Message-ID: On Mon, Dec 22, 2008 at 11:37 AM, alex23 wrote: > On Dec 21, 10:11 am, r wrote: >> Most of the complaints i hear are the redundant use of self. >> Which I lamented about but have become accustom(brainwashed) to it. I >> would remove this if it where up to me. > > It's a shame Python wasn't released under some kind of license, one > that allowed its source to be, say, "opened" and modified. Otherwise > you would just implement this yourself and submit patches, right? +1 :) From __peter__ at web.de Thu Dec 18 04:28:08 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 18 Dec 2008 10:28:08 +0100 Subject: importing csv file into sqlite References: <21067453.post@talk.nabble.com> <21068111.post@talk.nabble.com> Message-ID: Chris Rebert wrote: >> klia wrote: >> for item in input: >> curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item) > I believe you need to change 'item' to '*item' to expand the list in > the call so that the function gets 4 additional args rather than 1 > additional arg that happens to be a list. But as I've never used the > DB-API before, this is just a guess. No, the execute() method call is correct. There must be a malformed row in the csv with only one field. Peter From martin.hellwig at dcuktec.org Wed Dec 3 17:02:24 2008 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 03 Dec 2008 22:02:24 +0000 Subject: "as" keyword woes In-Reply-To: References: Message-ID: <493701f0$0$194$e4fe514c@news.xs4all.nl> Warren DeLano wrote: > A bottom line / pragmatic question... hopefully not a FAQ. > > Why was it necessary to make "as" a reserved keyword? Because it can be used at the import statement to let the imported thing be known under another name? Something like: >>> import xml.etree.ElementTree as ET -- mph From prologic at shortcircuit.net.au Mon Dec 22 17:27:41 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 23 Dec 2008 08:27:41 +1000 Subject: Python is slow In-Reply-To: <6aad831b-80ce-40df-9b6e-571b1e822795@s1g2000prg.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <6r6hpfFfb643U3@mid.uni-berlin.de> <494E6FDA.4070401@mrabarnett.plus.com> <4585c27d-d7a9-480f-991c-a869161be55c@g38g2000yqn.googlegroups.com> <3392a51b-d3fd-4986-9c59-fecccc7272da@p2g2000prn.googlegroups.com> <6aad831b-80ce-40df-9b6e-571b1e822795@s1g2000prg.googlegroups.com> Message-ID: On Tue, Dec 23, 2008 at 4:42 AM, cm_gui wrote: > i am referring mainly to Python for web applications. > > Python is slow. Please just go away. You are making an embarrassment of yourself. --JamesMills From thomasmallen at gmail.com Fri Dec 19 16:17:03 2008 From: thomasmallen at gmail.com (tmallen) Date: Fri, 19 Dec 2008 13:17:03 -0800 (PST) Subject: mod_python resources References: <78064e7e-ba2c-4959-b5f8-4d1b928bc5fe@y18g2000yqn.googlegroups.com> <4lsl16-15a.ln1@archaeopteryx.softver.org.mk> Message-ID: Here's my problem (it's a conceptual one). Coming from the world of mod_php, each file can represent a page with no intervention. I was not able to achieve the same with mod_python when I tried, and for that matter, couldn't put the pieces together in a usable way. Let me start simply: If I wanted to create a trivial site, (Home, About, Contact) with a header and footer included, in PHP, it would be done as such: each page (index.php, about.php, contact.php) includes the template bits (header.php, footer.php). Is this simplicity achievable using Python? And by "simplicity," I'm referring to simplicity in execution; not necessarily an identical approach. Thanks, Thomas On Dec 17, 4:25?am, Graham Dumpleton wrote: > On Dec 17, 11:10?am, ?????? ??????????? wrote: > > > > I'm trying again because I'm stubborn. Maybe the fourth time will be > > > the charm... > > > > Are there any good tutorials out there for setting up Apache with > > > mod_python? > > > mod_python is depreceated, nobody uses it. usemod_wsgihttp://www.modwsgi.org/ > > The mod_python package is not deprecated, although it could be said to > be sleeping at the moment. You'll also probably still find that more > new people choose mod_python over mod_wsgi. This is because it has the > more obvious name to look for when Googling. It also has publisher and > PSP high level handler which are still attractive to many as they are > more lightweight and easier to get into than the large WSGI > frameworks. Finally, the Django folks still recommend in their > documentation to use mod_python. > > Anyway, if wanting to host a WSGI capable application, using mod_wsgi > would be the more obvious choice. If wanting to write your own > framework, or work at low level, basing it on WSGI rather than > mod_python specific APIs would certainly be a better long term > direction to take. > > Graham From febaen at gmail.com Mon Dec 15 13:29:49 2008 From: febaen at gmail.com (feba) Date: Mon, 15 Dec 2008 10:29:49 -0800 (PST) Subject: Need help improving number guessing game References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> <01564c98$0$21844$c3e8da3@news.astraweb.com> Message-ID: <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> Alright! This is feeling more like it. #!/usr/bin/python #Py3k, UTF-8 import random def setup(game, minr=1, maxr=99): #minr, maxr make minimum and maximum. Can be adjusted. game['minr'], game['maxr'] = minr, maxr game['gcount'] = 0 #Reset guess count game['target'] = random.randint(minr, maxr) def playerswitch(game): #Player Switch #if player's a witch: burn(her) if game['player'] == game['player1']: game['player'] = game['player2'] else: game['player'] = game['player1'] def youwin(game): if game['pnum'] == 1: print("CONGRATULATIONS! IT TOOK YOU %s GUESSES" % game ['gcount']) else: if game['player'] == game['player1']: game['p1sc'] += 1 else: game['p2sc'] += 1 end = "CONGRATULATIONS %s! SCORE -- P1:%s P2:%s" #Can the following line be more compact? print(end % (game['player'], game['p1sc'], game['p2sc'])) def playagain(game): playover = input("PLAY AGAIN? Y/N: ") if playover.strip().lower() == "y": game['play'] = True setup(game) else: print("GOOD BYE. PLAY AGAIN SOON!") game['play'] = False def autofinish(game): if game['maxr'] - game['minr'] == 2: print("...ONLY ONE OPTION LEFT!") youwin(game) playagain(game) def numplayers(game, prompt="1 OR 2 PLAYERS?\n> "): while True: num = input(prompt) try: num = int(num) except ValueError: print("BAD VALUE") else: break game['pnum'] = num def guesses(game): game['guess'] = int(input("[%s-%s]%s>> " \ #keeps user aware of who's turn it is, and the range % (game['minr'], game['maxr'], game['player']))) def guesscheck(game): if game['guess'] == game['target']: if game['pnum'] == 1: game['gcount'] += 1 youwin(game) playagain(game) elif game['guess'] >= game['maxr']: print("NUMBER MUST BE IN RANGE") guesses(game) guesscheck(game) elif game['guess'] <= game['minr']: print("NUMBER MUST BE IN RANGE") guesses(game) guesscheck(game) elif game['guess'] > game['target']: print("TOO HIGH") if game['pnum'] == 1: game['gcount'] += 1 game['maxr'] = game['guess'] else: print("TOO LOW") if game['pnum'] == 1: game['gcount'] += 1 game['minr'] = game['guess'] def guessing(game): guesses(game) guesscheck(game) if game['pnum'] == 2: playerswitch(game) autofinish(game) def main(game=None): if game is None: game = {} print("WELCOME TO THE SUPER NUMBER GUESSING GAME!") numplayers(game) game['play'] = True game['player1'], game['player2'] = "P1", "P2" game['player'] = game['player1'] # P1 goes first #Scores start at 0 game['p1sc'], game['p2sc'], game['gcount'] = 0, 0, 0 setup(game) while game['play'] is True: guessing(game) if __name__ == "__main__": main() first off, I want to thank all of you for your help with this. I really don't think I could've learned all of this out nearly as quickly by reading tutorials and documentation, let alone had anything near the grasp I have on it now. '''This''' is why I like learning by doing. The only things I still don't really understand are .strip ().lower(), and try/except/else, and I plan on looking them up before I do anything else. In the past few hours I've gone from not having a clue what the whole {'fred': 0, 'barney': 0} thing was about to being able to fully understand what you're talking about, and put it into practice 2; I feel like this process is going quicker and quicker every time I refine it. It also feels like it's getting easier to solve various bugs when I create them they pop up. It might be because I'm getting into it and having more fun, because the refinements are less major each time, because they're easier to pick up, or some combination of all of those. Either way, I feel very excited about it. 3; I found some very helpful gedit plugins. While I was in preferences, I noticed you can have it highlight the margin; so I set that to 75 to try to keep from going over the character limit/line recommendation. Draw Spaces, a plugin, showing spaces is also pretty helpful. I also found a python auto complete plugin which I haven't used so far, but which looks very promising, along with a terminal program (Keeps me from juggling windows, anyway) 4; I readded the counter for one player games. Out of curiosity, what do you think of: if game['pnum'] == 1: game['gcount'] += 1 ? I'm not sure whether this is good or bad. On the one hand, it keeps it from adding to gcount without needing to, on the other hand it seems like it might be more wasteful to check pnum than to just add to gcount. It also makes it harder to adjust it to show gcount in two player mode, if you want to do that for some reason. 5; I added the ability for it to automatically complete when there's only one option left. I was amazed' I was actually going to ask for advice on how to do it here. I was going to say "I was thinking (blah blah)", but then I just typed it in, and it worked flawlessly. This goes back to one, but I'm very excited, and thankful. 6; can anyone think of anything else to add on to/do with this game? With the minr/maxr display, multiplayer, score keeping, and automation, I'm just about all of ideas. All I can think of left to add is 3 and 4 player modes, or a fork where player 2 can't win (kekekekeke. Though I'm not sure how to do it...), both of which I feel are somewhat pointless for a game like this. If I can't learn anything more from it, I will probably go back to reading python guides for a bit, and then try to make something else. From ivan.illarionov at gmail.com Thu Dec 18 06:09:26 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 18 Dec 2008 03:09:26 -0800 (PST) Subject: C API and memory allocation References: Message-ID: <59352942-e976-4ef4-bc40-c8953df0a792@c36g2000prc.googlegroups.com> On 18 ???, 03:51, Aaron Brady wrote: (snip) > How did you get a reference to the original > string object, with which to increment its reference count? Use the "O!" format instead of "s": PyObject *pystr; ... PyArg_ParseTuple(args, "O!", &PyStringObject, &pystr) ... Then you can use PyString_AS_STRING explicitly, and control ref. counts yourself. > How do you know its length to copy it into your own buffer? Use the "s#" format, as Gabriel has said. Ivan From gh at ghaering.de Thu Dec 4 08:15:40 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 04 Dec 2008 14:15:40 +0100 Subject: RELEASED Python 3.0 final In-Reply-To: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> Message-ID: Iain King wrote: > [...] Props. I just looked through the What's New and the change log, but I > couldn't find the answer to something: has any change been made to > how tabs and spaces are used as indentation? Can they still be > (inadvisably) mixed in one file? Or, more extremely, has one or the > other been abolished? As you have probably guessed: nothing changed here. Also see: http://www.python.org/dev/peps/pep-0666/ -- Gerhard From lewis.sarah93 at yahoo.com Fri Dec 5 00:08:48 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 21:08:48 -0800 (PST) Subject: Reduce Debt Message-ID: <86e2a593-25c1-45b5-936a-1589e5a0cb48@u14g2000yqg.googlegroups.com> Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From alessio.pace at gmail.com Mon Dec 1 08:32:07 2008 From: alessio.pace at gmail.com (Alessio Pace) Date: Mon, 1 Dec 2008 05:32:07 -0800 (PST) Subject: How to distribute a Python app together with its dependencies? References: <35377946-378c-484d-88cc-396145090d2f@l39g2000yqn.googlegroups.com> Message-ID: <97ee9678-1872-488b-9818-ff7937907f82@w3g2000yqc.googlegroups.com> On 1 Dic, 10:37, BlueBird wrote: > Alessio Pace wrote: > > Hi, > > > I have to distribute a Python application which relies on an external > > library, and I'm not very fluent in this kind of stuff with Python (I > > come from the Java world where I would have used the Maven build tool > > to create an "assembly with dependencies" of all it is needed to run > > the app), so I was wondering if someone here could give me some > > suggestions :-) > > > The external library is generally not present on the machines where I > > have to distribute my app, and the set of machines on which I have to > > distribute this application is not known a priori (it is just known > > they are Unix systems). In fact by means of SSH I will have to copy > > (and install) the app+library and make it runnable onto the specified > > destination(s). > > I have never used it myself, but bbfreeze claims to create packaged > versions of an application, for windows and Unix : > > http://pypi.python.org/pypi/bbfreeze/0.95.2 > Thank you. What's the difference with "Freeze" shipped with Python, or with PyInstaller ? Do you have experiences with any of them? From pruebauno at latinmail.com Thu Dec 4 11:18:23 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Thu, 4 Dec 2008 08:18:23 -0800 (PST) Subject: funny generator behaviour References: Message-ID: <7cb2dc1b-195a-447f-81ed-e0e094a60a9d@i24g2000prf.googlegroups.com> On Dec 4, 8:00 am, Edvin Fuglebakk wrote: > I have written a generator that puzzles me: > > The generator is supposed to create ordered selections of a set of > objects. repetition of objects is allowed and the selections should be > of a size determined by a pramter to the generator. > > Now, if I try to accummulate the generated selections into a list I get > some peculiar behaviour that I hope maybe some of you can help me > understand: > > Help much appreciated > -Edvin > > #straightforward acumulation. Does not give the expected result > >>> d=[] > >>> for f in orderedCombinations([1,2],3): > ... d.append(f) > ... > >>> d > [[1], [2], [1], [2], [1], [2], [1], [2]] > > #accumulating shallow copies of the genereated combinations works: > >>> d=[] > >>> for f in orderedCombinations([1,2],3): > ... d.append(f[:]) > ... > >>> d > [[1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 2, 2], [2, 1, 1], [2, 1, 2], [2, > 2, 1], [2, 2, 2]] > > #The generator: > def orderedCombinations(pool, k): > """ > Generator yielding ordered selections of size k with repetition from > pool. > """ > > if k == 1: > for m in pool: > yield [m] > > if k > 1: > > for m in pool: > for combo in orderedCombinations(pool, k-1): > > #insert and pop to avoid copying entire list > combo.insert(0,m) > yield combo > combo.pop(0) def orderedCombinations(pool, k): res=[[]] for i in xrange(k): res=[n+[m] for n in res for m in pool] return res From joe at strout.net Fri Dec 12 10:37:15 2008 From: joe at strout.net (Joe Strout) Date: Fri, 12 Dec 2008 08:37:15 -0700 Subject: concept of creating structures in python In-Reply-To: References: Message-ID: On Dec 11, 2008, at 10:52 PM, navneet khanna wrote: > I want to create a structure within a structure i.e. nested > structures in python. > I tried with everything but its not working. > my code is like this: > > class L(Structure): > > def __init__(self,Name='ND',Addr=0,ds_obj = D()): Change the default value of ds_obj here to None. Otherwise, you will certainly confuse yourself (there would be just one default object shared among all instances). > self.Name = Name > self.Addr = Addr > self.ds_obj = ds_obj > > > class D(Structure): > > def __init__(self,dataName='ND',index = 0,ele_obj=E()): > > self.dataName = dataName > self.index = index > self.ele_obj = ele_obj Same thing here with ele_obj -- have it default to None to save yourself grief. Otherwise, these look fine. > these are two structures. I want to refer D structure in L one and > use it. I want to access the value of D structure like L.D.index = 0. But you didn't name it "D" -- if you have an L object, say "foo", then you'd get to it's D object as foo.ds_obj (since that's what you named it in L.__init__). If you then wanted to get to that thing's E object, it'd be foo.ds_obj.ele_obj. Best, - Joe From jstroud at mbi.ucla.edu Sun Dec 28 05:56:29 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 28 Dec 2008 02:56:29 -0800 Subject: assignment with [:] In-Reply-To: References: Message-ID: James Stroud wrote: > py> a = [1, 2, 3] > py> a1 = a > py> a1[:] = [x*3 for x in a1] > py> a1 > [3, 6, 9] > py> a1 > [3, 6, 9] This should have been: py> a = [1, 2, 3] py> a1 = a py> a1[:] = [x*3 for x in a1] py> a [3, 6, 9] py> a1 [3, 6, 9] James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From sturlamolden at yahoo.no Fri Dec 12 07:56:53 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 04:56:53 -0800 (PST) Subject: var or inout parm? References: Message-ID: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> On Dec 12, 1:44 pm, "Chris Rebert" wrote: > Python begs to differ, as those two statements are both semantically > identical in this case: That is because integers are immutable. When x += 1 is done on an int, there will be a rebinding. But try the same on say, a numpy array, and the result will be different: >>> import numpy >>> x = numpy.zeros(10) >>> id(x) 19504848 >>> x += 1 >>> id(x) 19504848 >>> x = x + 1 >>> id(x) 10451488 Whereas: >>> x = 1 >>> id(x) 10051256 >>> x += 1 >>> id(x) 10051244 >>> x = x + 1 >>> id(x) 10051232 From gh at ghaering.de Tue Dec 30 16:02:08 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 30 Dec 2008 22:02:08 +0100 Subject: SQL, lite lite lite In-Reply-To: <4959204f$0$15020$426a74cc@news.free.fr> References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> <4959204f$0$15020$426a74cc@news.free.fr> Message-ID: <6rvgihF3je6sU1@mid.uni-berlin.de> Bruno Desthuilliers wrote: > Aaron Brady a ?crit : >> Hi all, >> > (snip) > > >> I don't think relational data can be read and written very easily in >> Python. > > Did you try SQLAlchemy or Django's ORM ? > [...] Using an ORM when you don't grasp the relational model and/or the SQL query language is futile. That's probably the case for many other abstraction layers, too. -- Gerhard From clp at rebertia.com Wed Dec 24 02:53:38 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 23 Dec 2008 23:53:38 -0800 Subject: Strategy for determing difference between 2 very large dictionaries In-Reply-To: References: <1230102996.2303.1291616055@webmail.messagingengine.com> Message-ID: <47c890dc0812232353v743bb58cn50849991866c602c@mail.gmail.com> On Tue, Dec 23, 2008 at 11:46 PM, Gabriel Genellina wrote: > > Yes; but isn't a dict comprehension more adequate? > > [key: (dict1[key], dict2[key]) for key in common_keys if > dict1[key]!=dict2[key]} That initial [ should be a { of course. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From duncan.booth at invalid.invalid Fri Dec 5 09:22:30 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 Dec 2008 14:22:30 GMT Subject: generating a liste of characters References: Message-ID: "Mark Tolonen" wrote: > wrote in message > news:df7b75eb-97bf-4538-880b-f65b5ed992ff at u14g2000yqg.googlegroups.com. > .. >>In Python ranges are open on the right, so I name cinterval such >>function. > > Yes, and that's fine when dealing with integers and slicing, but when > dealing with characters, it is non-obvious what character to use. > What "looks" correct? > > chars = crange('0','9') + crange('A','Z') + crange('a','z') # > inclusive > I think bearophile's point was that you had the parameters correct, (specifying 'a' and 'z' makes sense), but the function itself had the wrong name. If you call it 'crange' you are implying the wrong behaviour. Call it something like 'cinterval' instead. -- Duncan Booth http://kupuguy.blogspot.com From nospam at nospam.com Fri Dec 26 09:24:10 2008 From: nospam at nospam.com (Gilles Ganault) Date: Fri, 26 Dec 2008 15:24:10 +0100 Subject: [2.5.1] Str.Replace() doesn't work? References: Message-ID: On Fri, 26 Dec 2008 15:16:49 +0100, Gilles Ganault wrote: >I can't figure out why the script is not returning anything in the >"for m in matches" block: Pfff, found it 5mn after posting ;-) s/reponse =/response =/ Sorry guys. From castironpi at gmail.com Sun Dec 21 11:41:35 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 21 Dec 2008 08:41:35 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: On Dec 21, 10:31?am, MRAB wrote: > Aaron Brady wrote: > > On Dec 20, 8:49 pm, MRAB wrote: > >> Aaron Brady wrote: > >>> On Dec 20, 7:38 pm, Steven D'Aprano >>> cybersource.com.au> wrote: > >>>> Instead of just whinging, how about making a suggestion to fix it? Go on, > >>>> sit down for an hour or ten and try to work out how a BINARY OPERATOR > >>>> like % (that means it can only take TWO arguments) can deal with an > >>>> arbitrary number of arguments, *without* having any special cases. > >>>> Go on. Take your time. I'll be waiting. > >>> Hi, not to take sides, but, there is a possibility. > >>> This behavior is currently legal: > >>>>>> "%i %%i" % 0 % 1 > >>> '0 1' > >>> So, just extend it. ?(Unproduced.) > >>>>>> "%i %i" % 0 % 1 > >>> '0 1' > >>>>>> "%r %i" % (2, 3, 4) % 1 > >>> '(2, 3, 4) 1' > >>>>>> "%r %i" % (2, 3, 4) > >>> '(2, 3, 4) %i' > >>> Which is quite clever and way ahead of its (posessive) time. > >> A couple of problems: > > >> 1. How do you handle a literal '%'? If you just double up then you'll > >> need to fix the string after all your substitutions. > > >> 2. What if a substitution introduces a '%'? > > >> I suppose a possible solution would be to introduce a special format > >> string, including a literal, eg: > > >> ? ? ?f"%r %i" % (2, 3, 4) % 1 > > >> and then convert the result to a true string: > > >> ? ? ?print(str(f"%r %i" % (2, 3, 4) % 1)) > > >> (although print() would call __str__ anyway). > > >> The format string would track where the last substitution occurred. > > >> Hmm... I think I'll just learn the new method. :-) > > > Now that I'm fighting 'r's war for him/her... > > > Um, here's one possibility. ?On the first interpolation, flags are > > noted and stored apart from subsequent interpolations. ?Then, use a > > sentinel to terminate the interpolation. ?(Unproduced.) > > >>>> "%r %i" % ( 2, 3 ) % 0 > > '(2, 3) 0' > >>>> "%% %r" % ( 2, 3 ) % str.interp_end > > '% (2, 3)' > >>>> "%sss%i" % "%d" % 0 > > '%dss0' > > > The first %s is replaced with %d, but doesn't hijack the '0'. ?If you > > want to interpolate the %d, use the sentinel. ?The sentinel is what > > causes '%%' to be handled. > > >>>> "%sss%i" % "%d" % 0 % 1 > > Traceback (most recent call last): > > ? File "", line 1, in > > TypeError: not all arguments converted during string formatting > >>>> "%sss%i" % "%d" % 0 % str.interp_end % 1 > > '1ss0' > > > Treating tuples as a special case appears to be the simpler solution, > > but this, 'chaining', to adopt the term, is still feasible. > > A possible solution occurred to me shortly after I posted, but I decided > that sleep was more important. :-) > > The original format is a string. The result of '%' is a string if > there's only 1 placeholder to fill, or a (partial) format object (class > "Format"?) if there's more than one. Similarly, the format object > supports '%'. The result of '%' is a string if there's only 1 > placeholder to fill, or a new (partial) format object if there's more > than one. > > ?>>> f = "%r %i" > ?>>> type(f) > > ?>>> f = f % (2, 3, 4) > ?>>> type(f) > > ?>>> f = f % 1 > ?>>> type(f) > Alright, so how are you handling: >>> f= "%s %i" >>> type( f ) >>> f= f% '%i' #now '%i %i' >>> type( f ) >>> f= f% 1 >>> type( f ) ? In other words, are you slipping '1' in to the very first available slot, or the next, after the location of the prior? From stef.mientki at gmail.com Sun Dec 7 04:27:29 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 07 Dec 2008 10:27:29 +0100 Subject: how to get a beep, OS independent ? In-Reply-To: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> Message-ID: <493B9701.2040402@gmail.com> Rainy wrote: > On Dec 6, 3:40 pm, Stef Mientki wrote: > >> hello, >> >> I want to give a small beep, >> for windows there's message-beep, >> and there seems to be something like " curses" , >> but that package seems to be totally broken in P2.5 for windows. >> >> Any other suggestions ? >> >> thanks, >> Stef Mientki >> > > For win there's winsound, you have to check sys.platform and do > what's necessary for the platform in question. In linux I think > you can just print '\a' (or does that only work in terminals?). > If you know that ext. speakers are always on, you can do a nicer > beep by using some wav file, in linux it's probably easiest to > use an external program to play it, like wavplay. Basically, > there is no single answer, it depends on circumstances. > -- > http://mail.python.org/mailman/listinfo/python-list > '\a' or chr(7) prints an inverted "BEL". So it looks that Python version independency is even worse than OS independency ;-) I'll take a look at wxPython and Pygame if there's something useful. anyway thanks, Stef From lewis.sarah93 at yahoo.com Fri Dec 5 00:04:21 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 21:04:21 -0800 (PST) Subject: Reduce Debt Message-ID: Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From mail at microcorp.co.za Thu Dec 4 13:19:05 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 4 Dec 2008 20:19:05 +0200 Subject: Multiple equates References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> Message-ID: <001801c95648$5b6d65e0$0d00a8c0@hendrik> "Cameron Laird" wrote: > There's a realm within Pythonia that favors lambdalessness. And who, may I ask, Is the King of this realm? - Hendrik From dickinsm at gmail.com Sun Dec 28 11:24:02 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 28 Dec 2008 08:24:02 -0800 (PST) Subject: math module for Decimals References: <41937dc9-4b67-43b5-9eab-6f8c851474cf@p2g2000prn.googlegroups.com> Message-ID: <0896c2d8-78ff-489e-801d-abef957601d0@s9g2000prg.googlegroups.com> On Dec 28, 3:55?pm, jerry.carl... at gmail.com wrote: > But i am after the extra precision: > > >>> from math import * > >>> (1+1e-16)-1 > > 0.0 Sounds like you don't care too much about the base-10 part, so there may be other solutions out there. Have you tried: 1. mpmath? 2. sympy? 3. Sage? Any of these is likely to be faster than a decimal solution. One thing that it would be *really* nice to have is a set of Python bindings to MPFR---to me, MPFR is the one obvious way to do high-precision math. Maybe bindings already exist somewhere. Sage includes them, but also includes many hundreds of megabytes of other stuff that you probably don't need or want. Maybe you could get access to MPFR via ctypes; I don't have any idea how feasible or complicated this might be. > Sure, you can say, there is such a small market for this application, > and maybe I should use other tools. Well, I found Python so much > easier to use for other reasons. And, again, it seems like there is a > desire for it outside of my own office. Well, I'd certainly find high-precision sin, cos, ... within Python useful. I'd guess the market isn't *so* small. > Agree: sin, cos and atan would do it. I'll see if I can find time. I've just discovered a half-finished version of atan for Decimal sitting on my computer, complete with error analysis. > Wow, i would never think my posting would go that high in the Python > world. I can't wait to tell my colleagues after these holidays ;-) LOL---hardly! I'm just one of hundreds of Python core devs, and I've only been that for around a year... > If I improve (in my view that is) the existing modules (dmath) etc. i > will keep you posted. For now I am reducing large arguments of > goniometric functions by adding the following into the dmath's sin(x) > and cos(x): > > x=Decimal.__mod__(x,Decimal('2')*pi()) > > Works fine for what i need, but i am sure it's not the right way to do > it. I don't know of any better way to deal with large arguments. The main problem is that the reduction step can introduce fairly large errors: for example, if you're using a value of pi that's accurate to 10**-20, say, then reducing something of magnitude 10**5*pi will give a result with error of around 10**-15. As far as I know, this problem is essentially unavoidable, and it's the reason why implementing sin for inputs like 10**999999999 isn't feasible. Mark From doron.tal.list at gmail.com Sun Dec 14 06:15:31 2008 From: doron.tal.list at gmail.com (Doron Tal) Date: Sun, 14 Dec 2008 13:15:31 +0200 Subject: Swig for Python 2.6 Message-ID: <2a8674c60812140315t78a474a4x2c9250f593f72a47@mail.gmail.com> Hi I'm trying to wrap a c library for use with Python 2.6. I'm using swig 1.3.36, and I get the following error: linux-python/log_wrap.c: In function '_PySwigObject_type': linux-python/log_wrap.c:1680: warning: missing initializer linux-python/log_wrap.c:1680: warning: (near initialization for 'tmp.tp_version_tag') linux-python/log_wrap.c: In function '_PySwigPacked_type': linux-python/log_wrap.c:1843: warning: missing initializer linux-python/log_wrap.c:1843: warning: (near initialization for 'tmp.tp_version_tag') linux-python/log_wrap.c: In function 'swig_varlink_type': linux-python/log_wrap.c:3334: warning: missing initializer linux-python/log_wrap.c:3334: warning: (near initialization for 'tmp.tp_version_tag') What swig version should I use? If version 1.3.36 is good enough, then what can be my mistake? Thanks, doron -------------- next part -------------- An HTML attachment was scrubbed... URL: From jobs.teaching.english.asia at gmail.com Sun Dec 7 21:28:01 2008 From: jobs.teaching.english.asia at gmail.com (Jobs Teaching English in Asia) Date: Sun, 7 Dec 2008 18:28:01 -0800 (PST) Subject: Cambodia TEFL - Gap Year, Travel & Study, Paid Teaching Job - http://www.cambodiatefl.com Message-ID: Cambodia TEFL - Gap Year, Travel & Study, Paid Teaching Job http://www.cambodiatefl.com From nemokingdom at gmail.com Fri Dec 26 20:29:37 2008 From: nemokingdom at gmail.com (nemo) Date: Fri, 26 Dec 2008 17:29:37 -0800 (PST) Subject: Process with ftplib References: Message-ID: <7e172a64-9bda-44c3-90fb-4c716c1f38b4@l33g2000pri.googlegroups.com> On Dec 26, 10:40?pm, "Gabriel Genellina" wrote: > En Fri, 26 Dec 2008 11:07:30 -0200, nemo escribi?: > > > There seems something wrong when I use multiprocessing.Process with > > ftplib, [...] > > It works well but when I using the Process module, something seems > > wrong: > > ftp = qftp(host, port, user, password) > > p = multiprocessing.Process(target = ftp.connect) > > p.join() > > ftp.ftp.pwd() ? ? ? ? ? ? ? ? ? #after join, i think a connection has > > made, but it throws an exception > > This give me a 'NoneType object has no attribute sendall' exception. I > > wondered why? > > After p.join(), the second process has finished. The global variable ftp ? > isn't shared between them - so it does not reflect the changes made in the ? > other process. > > An introductory article to multiprocessing:http://www.doughellmann.com/articles/CompletelyDifferent-2007-10-mult... > > -- > Gabriel Genellina thanks. -- nemo From robert.kern at gmail.com Sun Dec 28 16:57:51 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 28 Dec 2008 16:57:51 -0500 Subject: "return" in def In-Reply-To: <088c7d93-e87f-44a0-9ea7-faa7feded7df@a26g2000prf.googlegroups.com> References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <0167cbf7$0$6988$c3e8da3@news.astraweb.com> <088c7d93-e87f-44a0-9ea7-faa7feded7df@a26g2000prf.googlegroups.com> Message-ID: Benjamin wrote: > On Dec 28, 1:35 pm, Steven D'Aprano cybersource.com.au> wrote: >> The second thing I think is that maybe the function is a generator, and >> so I look for a yield. > > You shouldn't, though; Generators can't contain any return statement. Yes, they can. It doesn't return a value, it just raises a StopIteration error. In [18]: def g(): for i in range(5): if i == 3: print 'Early exit.' return print 'Should not happen.' yield i ....: ....: In [25]: list(g()) Early exit. Out[25]: [0, 1, 2] -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From mnations at gmail.com Sat Dec 13 21:45:43 2008 From: mnations at gmail.com (Mudcat) Date: Sat, 13 Dec 2008 18:45:43 -0800 (PST) Subject: PyQt: Pulling Abstract Item Data from Mime Data using Drag and Drop. References: <150086b2-b02d-4204-8c06-b08c0aa119c4@k1g2000prb.googlegroups.com> Message-ID: <9c332bde-351d-4499-b33e-dac1a00ac434@g38g2000yqd.googlegroups.com> On Dec 12, 6:17?pm, David Boddie wrote: > That's correct, retrieveData() is a protected function in C++ and the > QMimeData object was created by the framework, not you, in this case. Ah, well that explains it. Figured as much but was hoping maybe I was trying to access it incorrectly. > You could use the data() method to get the serialized data then try to > extract the list item-by-item using the QDataStream class, or perhaps > PyQt has a convenience function to unpack the items. I tried to get info back using data() but kept getting null values. Same goes for the items() function which is fed with mimeData and is supposed to return a list. From the documentation it appeared that was supposed to be the middle-man to re-convert the data. I know the data existed because I could drag/drop elements from one treeWidget to another but still couldn't get data back from the target widget. > Alternatively - and this is a bit speculative - perhaps you can copy > the data to another QMimeData object which you have created, and use > its retrieveData() method to retrieve the items. I started down the path of creating my own MimeType but then realized it was quicker to just override the drop() function and grab the selected items from the source widget, just letting the mime data disappear into the ether. A little klugey but deadline is fast approaching. However I'll give the pyqt mailing list a shot. I didn't know there was one just for pyqt. Thanks for all the help, Marc From peke at iki.fi Mon Dec 15 17:58:07 2008 From: peke at iki.fi (=?ISO-8859-1?Q?Pekka_Kl=E4rck?=) Date: Tue, 16 Dec 2008 00:58:07 +0200 Subject: Problem Python 2.6.1 vs 2.6 & pyWin32 In-Reply-To: <4946D09F.6050300@v.loewis.de> References: <4946754f$0$19000$426a74cc@news.free.fr> <4946D09F.6050300@v.loewis.de> Message-ID: <7dedbb6d0812151458o29607864x74ea3f43fb49c880@mail.gmail.com> 2008/12/15 "Martin v. L?wis" : >> I am very disappointed. Help me, please. > > Try installing Python 2.6.1 "for all users". Could you clarify why that's needed? Link to a relevant bug report or something similar is enough. We've got some weird problems installing Python packages (win32.exe) on Windows with Python 2.6 and would like to know are these problems related. One thing we noticed (I'm not sure has this been yet submitted to bugs.python.org yet) was that installing packages created with Python 2.5 to Python 2.6 failed unless Python was in %PATH% [1]. Even then output printed by postinstall scripts wasn't visible in the installer. Another pretty severe problem was that installers created with Python 2.6 didn't work at all with older versions [2]. [1] http://code.google.com/p/robotframework/issues/detail?id=150 [2] http://code.google.com/p/robotframework/issues/detail?id=163 Cheers, .peke From mailmaverick666 at gmail.com Fri Dec 5 01:27:22 2008 From: mailmaverick666 at gmail.com (rishi pathak) Date: Fri, 5 Dec 2008 11:57:22 +0530 Subject: CONNECTION TIMED OUT ERROR using urllib2 In-Reply-To: <726d283d0812042217w41a0288eg3ee79d4ffdb5ff4b@mail.gmail.com> References: <726d283d0812042217w41a0288eg3ee79d4ffdb5ff4b@mail.gmail.com> Message-ID: <180b672e0812042227j12a4d647k84e507dfae77d665@mail.gmail.com> Are you sitting behind a proxy. If so then you have to set proxy for http On Fri, Dec 5, 2008 at 11:47 AM, svalbard colaco wrote: > Hi all > > I have written a small code snippet to open a URL using urllib2 to open a > web page , my python version is 2.4 but i get an urlopen error called > connection timed out > > The following is the code snippet > > *import urllib2 > > f = urllib2.urlopen('http://www.google.com/') > print f.read(100)* > > > where as the same url http://www.google.com/ works through my browser. > > The following is the back trace : > > File "test_url.py", line 3, in ? > f = urllib2.urlopen('http://www.google.com/') > File "/usr/lib/python2.4/urllib2.py", line 130, in urlopen > return _opener.open(url, data) > File "/usr/lib/python2.4/urllib2.py", line 358, in open > response = self._open(req, data) > File "/usr/lib/python2.4/urllib2.py", line 376, in _open > '_open', req) > File "/usr/lib/python2.4/urllib2.py", line 337, in _call_chain > result = func(*args) > File "/usr/lib/python2.4/urllib2.py", line 1021, in http_open > return self.do_open(httplib.HTTPConnection, req) > File "/usr/lib/python2.4/urllib2.py", line 996, in do_open > raise URLError(err) > *urllib2.URLError: > > > Any pointers in this regard will be of great help. > > Thanking you'll in advance. > > Regards, > sv > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Regards-- Rishi Pathak Pune-Maharastra -------------- next part -------------- An HTML attachment was scrubbed... URL: From fetchinson at googlemail.com Tue Dec 9 02:51:00 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 8 Dec 2008 23:51:00 -0800 Subject: html codes Message-ID: Hi folks, I came across a javascript library that returns all sorts of html codes in the cookies it sets and I need my web framework (written in python :)) to decode them. I'm aware of htmlentitydefs but htmlentitydefs.entitydefs.keys( ) are of the form '&#xxx' but this javascript library uses stuff like '%3A' for the ':' for example. The conversion is here: http://www.ascii.cl/htmlcodes.htm Is there a python package/module/whatever that does the conversion for me or do I have to write a little wrapper myself (and introduce bugs while doing so :))? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From cjwilliams43 at gmail.com Thu Dec 4 08:29:47 2008 From: cjwilliams43 at gmail.com (Colin J. Williams) Date: Thu, 04 Dec 2008 08:29:47 -0500 Subject: Multiple Versions of Python on Windows XP In-Reply-To: <49378804.2050807@g.nevcal.com> References: <4934de22$0$27863$9b622d9e@news.freenet.de> <493592EE.9090005@v.loewis.de> <49378804.2050807@g.nevcal.com> Message-ID: <4937DB4B.7060001@ncf.ca> Glenn Linderman wrote: > > The equivalent of those commands is available via Windows Explorer, > Tools / Folder Options, File Types, scroll-scroll-scroll your way to > .py, Click Advanced, fiddle, copy paste apply, and other twaddle. Yes, but what's needed is a further level of indirection. Currently, this allows .py to be associated with a particular editor. It would be great if there were some way of associating "Python.File", which is created in the install process, with a particular editor. Then, one is left with associating "Python.File" with a given version of Python. Meanwhile, your suggestion provides a workaround. Colin W. > A perfect example of why not everything should be done via GUI > interfaces, or at least why this is an extremely poor GUI interface. > > GUI designers should count the command line keystrokes, and make sure > their interface is shorter, otherwise they are a failure. > >> Michel Claveau suggests VirtualBox, this >> seems a big hammer to kill >> this particular fly. >> >> It's interesting that each install sets >> up a Python.File variable in the registry. >> >> It's a pity that this can't be used to achieve this more simply. > > Martin seems willing to entertain the idea of future Windows > installers doing something more brilliant in this area, for those that > wish to switch between multiple installed versions, as he asked for a > tracking issue to be created, which I did. > > Whether it will be exactly my technique, or something further > improved, time will tell. But that will only apply to versions > released after 3.0 and 2.6.1 (unless he has already coded it into the > release, but I doubt he had time, or wishes to destabilize or delay > these releases). > > Anyway, if you remember the arcane techniques for copy/paste in CMD > prompt windows (Alt-space or click the "system" icon in the upper left > of the CMD prompt window), and go from there, then setting up the > multiple ftypes becomes a bit easier, perhaps. > >> Best wishes, >> >> Colin W. > > > From sjmachin at lexicon.net Wed Dec 17 10:54:26 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 17 Dec 2008 07:54:26 -0800 (PST) Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> Message-ID: <2c7dce74-3531-4eb0-923f-0e0ed72fd79a@r10g2000prf.googlegroups.com> On Dec 18, 2:19?am, walterbyrd wrote: > For a language as well structured as Python, this seems somewhat > sloppy, and inconsistant. ?Or is there some good reason for this? > > Here is what I mean: > > def a(): > ? ? x = 99 > ? ? print x > > def b(): > ? ? print x > > a() > b() # raises an exception because x is not defined. > > However in the methods are within a class, the scoping seems to work > differently. > > class ab(): > ? ? def a(self): > ? ? ? ? self.x = 99 > ? ? ? ? print self.x > ? ? def b(self): > ? ? ? ? print self.x > > i = ab() > i.a() > i.b() # this works, why no lexical scoping? Two questions for you: (1) If you were to change the sloppy inconsistent scoping mechanism in classes, what would you change it to? (2) What do you think of the following: class ab(): def a(self): self.x = 99 print self.x def b(me): print me.x ? From clp at rebertia.com Fri Dec 26 01:17:40 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 25 Dec 2008 22:17:40 -0800 Subject: socket send help In-Reply-To: <8a5a2b07-3274-483a-be06-51eab226315a@d36g2000prf.googlegroups.com> References: <8a5a2b07-3274-483a-be06-51eab226315a@d36g2000prf.googlegroups.com> Message-ID: <47c890dc0812252217q323d63dcp54cd70db1c023005@mail.gmail.com> On Thu, Dec 25, 2008 at 10:08 PM, greywine at gmail.com wrote: > Hi again, > > I've done some more playing around with socket and socketserver and > have discovered I can send strings or lists with socket.send() by > converting to bytes. But lists with strings in them or dicts can't be > converted by bytes(). How can I send those? If you're sending structured data rather than just bytestrings, you should use proper serialization. Use the `json`, `pickle`, or `marshal` modules to convert your data to an external representation in bytes, send the bytes thru the socket, then deserialize the bytes back into data structures using the same module again. The Python std lib docs are your friend. Merry Christmas, Chris -- Follow the path of the Iguana... http://rebertia.com From ndbecker2 at gmail.com Thu Dec 18 10:49:27 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 18 Dec 2008 10:49:27 -0500 Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> <6qv7kfFeuf65U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Neal Becker wrote: > >> Tino Wildenhain wrote: >> >>> Neal Becker wrote: >>> ... >>>>>> So if __str__ is "meant for human eyes", then why isn't print using >>>>>> it! >>>>> it is: >>>>> >>>>> > print x >>>>> str >>>>> >>>>> but dict just uses repr() for all its childs to print. >>>>> >>>>> T. >>>> That makes no sense to me. If I call 'print' on a container, why >>>> wouldn't it recursively print on the contained objects? Since print >>>> means call str, printing a container should recursively call str on the >>>> objects. >>> >>> Every class is free on how to best implement __str__, you will find >>> the same behavior on tuple and list as well. >>> >>> Maybe its discussable to change the implementation sensibly, best if you >>> would come with a proposal? Perhaps pprint.pprint is a starting point? >>> >>> Regards >>> Tino >> >> First, I'd like to know if there is a rationale for the current design. >> Am I correct in thinking this is a defect? > > I don't think so. First of all, there is no "generic" way of printing a > collection. And the current implementation tries to give an overview what > is contained in the collection, without trying to make it "fancy" - any > such thing needed to be hand-coded anyway. > > Using repr for that is better suited, as for example string keys are > printed with quotes around them - making clear what they are, and not > irritating the user through potentially contained spaces or even things > that look as if they are python objects. > > For example, if repr *wasn't* used, > > { "{foo=bar}" : "baz"} > > would be printed > > {{foo=bar} : baz} > > Which is *not* what the dictionary actually contains! > > The same goes for unicode-objects. They appear with their "funny" > characters as \xXX-codes - instead of bailing out on you with > unicode-errors. > > So, IMHO the current behavior is desired. > So if I want to overload something in my custom class, so that I get a nice string whether it's printed directly, or as part of a container, what is the recommendation? Overload both __str__ and __repr__? From ethan at stoneleaf.us Thu Dec 11 12:33:14 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 11 Dec 2008 09:33:14 -0800 Subject: internal circular class references In-Reply-To: References: Message-ID: <49414EDA.2050509@stoneleaf.us> Carl Banks wrote: > On Dec 10, 5:26 pm, Ethan Furman wrote: > >>Greetings List! >> >>I'm writing a wrapper to the datetime.date module to support having no >>date. Its intended use is to hold a date value from a dbf file, which >>can be empty. >> >>The class is functional at this point, but there is one thing I would >>like to change -- datetime.date.max and datetime.date.min are class >>attributes of datetime.date, and hold datetime.date values. At this >>point I have to have two lines outside the actual class definition to do >>the same thing, e.g.: >> >> >> class NullDate(object): >> "adds null capable DateTime.Date constructs" >> __slots__ = ['_date'] >> def __new__(cls, date='', month=0, day=0): >> nulldate = object.__new__(cls) >> nulldate._date = "" >> . >> . >> . >> return nulldate >> NullDate.max = NullDate(dt.date.max) >> NullDate.min = NullDate(dt.date.min) >> >> >>How can I move those last two lines into the class definition so that: >> 1) they are class attributes (not instance), and >> 2) they are NullDate type objects? > > > > It can't be done by any straightforward method I know of. I advise > you not to worry about it, and just define them afterwards, perhaps > with an apologetic comment saying you would have put them inside the > class definition if you could have. > > > If the out-of-scope issue bothers you that much, you could use some > metaclass hackery to run a method that defines the class attributes > after the class is created, at the unrecommendable cost of confusing > most readers. Here is a very simple example: > > def make_class_and_run_postcreate(name,bases,clsdict): > cls = type.__new__(type,name,bases,clsdict) > cls.__postcreate__() > return cls > > class A(object): > __metaclass__ = make_class_and_run_postcreate > @classmethod > def __postcreate__(cls): > cls.internal_circular_class_ref = cls() Well, since "Practicality beats purity" ;) , I'll stick with having the two assignment statements just outside the class. Not to mention my metaclass skills are nonexistent at this point. > BTW, if you don't mind some criticism of your code, the code you > posted seems to be much too complex for the job you're describing. Critiques always welcome. > First of all, do you even need to wrap the datetime.date class? With > Python's duck typing ability, you could have a separate NullDate class > to go alongside the datetime.date, and use a regular datetime.date > object when the date is present, and NullDate when it's absent. If > necessary you can subclass datetime.date to add any new methods it > would have to have. Use a factory function to return either NullDate > or a datetime.date depending on whether the dbf cell is empty. > > class ValidDate(datetime.date): > def is_valid(self): > return True > > class NullDate(object): > # implement any necessary methods of datetime.date interface here > def is_valid(self): > return False > > def create_date_from_dbf_cell(dbf_cell): > if dbf_cell.empty(): > return NullDate() > return ValidDate(dbf_cell.value) > > > If you do this, you don't have to muck around with __getattr__ or > __new__ or snooping to datetime.date's class dict anything like that. > > > Carl Banks Good question. My goal with NullDate is to have a date object that I can treat the same regardless of whether or not it actually holds a date. NullDates with no value should sort before any NullDates with a value, should be comparable to dates as well as NullDates, and should support all the same methods. In other words, I don't want to have to worry about whether my date object has an actual date under most circumstances (printing, using as dictionary keys, comparing, etc.). Does my design make more sense given these expanded requirements, or could it still be done simpler? For that matter, do my requirements make sense? ~Ethan~ From gagsl-py2 at yahoo.com.ar Wed Dec 24 12:24:59 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2008 15:24:59 -0200 Subject: Custom C Exception Subclasses References: <41f291ff-d7bd-4334-8689-636e95524cdc@b38g2000prf.googlegroups.com> Message-ID: En Wed, 24 Dec 2008 13:42:38 -0200, Ross escribi?: > For a project that I am doing, it would be useful to have an exception > class that stores some additional data along with the message. > However, I want to be able to store a couple pointers to C++ classes, > so I can't just use an exception created with PyExc_NewException. In fact you can, you could store those pointers as attributes of the exception object, using a PyCObject. Accessing those attributes isn't as easy as doing exc->field, but I think it's easy enough. Inheriting from some exception type requires you to define the type structure and fill it right, and IMHO is a lot harder. > If > I were to subclass the built-in Exception type, I would need to have > access to the PyExc_ExceptionObject, but the headers only give > PyExc_Exception, the type object. This seems like a rather > straightforward task, but I can't seem to find any documentation for > it. Does anyone know how to do this? Thanks! Perhaps there is a misunderstanding here. To subclass a type, you need the type, not an instance of such type. The "Exception" class you use in Python code is "PyExc_Exception" in C code. Usually one would inherit a subclass, RuntimeError by example, so use PyExc_RuntimeError as the base type. -- Gabriel Genellina From tkpapp at gmail.com Tue Dec 2 17:04:44 2008 From: tkpapp at gmail.com (Tamas K Papp) Date: 2 Dec 2008 22:04:44 GMT Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <591e8625-7e4d-4db8-ae6c-73c4370f8088@q26g2000prq.googlegroups.com> Message-ID: <6plpnsF8pi3oU1@mid.individual.net> On Tue, 02 Dec 2008 13:57:35 -0800, Lew wrote: > Xah Lee wrote: >> If [yo]u would like to learn [the] [E]nglish lang[uage] and writing >> insights from me, peruse: > > /Au contraire/, I was suggesting a higher standard for your posts. Hi Lew, It is no use. Xah has been posting irrelevant rants in broken English here for ages. No one knows why, but mental institutions must be really classy these days if the inmates have internet access. Just filter him out with your newsreader. Best, Tamas From steve at REMOVE-THIS-cybersource.com.au Sun Dec 14 22:21:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Dec 2008 03:21:21 GMT Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> <0152e35f$0$8244$c3e8da3@news.astraweb.com> Message-ID: <0155c4a7$0$6988$c3e8da3@news.astraweb.com> On Mon, 15 Dec 2008 02:11:10 +0000, Lie Ryan wrote: >> So given the normal precedence rules of Python, there is no ambiguity. >> True, you have to learn the rules, but that's no hardship. > > *I* know about the precedence rule, but a newbie or a tired programmer > might not. He might want to reverse the truth value of argument b but > instead has just reversed the whole expression. And? A newbie or a tired programmer might not know that a^b is bit-wise xor instead of exponentiation, or that range(n) doesn't include n, or even that len(alist) returns the length of a list. There's no limit to the potential mistakes that are possible for a programmer who is tired, inexperienced, intoxicated or just plain stupid enough. What's your point? Are you expecting Python to be mistake-proof? There's a certain level of knowledge about the language necessary to program effectively, and learning that "is not" is a single operator is not particularly onerous. -- Steven From David Wed Dec 31 11:10:21 2008 From: David (David) Date: Wed, 31 Dec 2008 10:10:21 -0600 Subject: How to initialize an array with a large number of members ? Message-ID: <5m4nl4hs8f9q6rfcp7b1jt7nk1o6sq6r0f@4ax.com> Thanks to those who have helped a beginner in Python. Using version 3.0 # script23 from array import array < see failed initialization attempts below > tally = array('H',for i in range(75) : [0]) tally = array('H',[for i in range(75) : 0]) tally = array('H',range(75) : [0]) tally = array('H',range(75) [0]) Above give either Syntax error or TypeError All examples of sequences in docs show only a few members being initialized. Array doc says an iterator can be used, but doen't show how. What would you do for a 2 dimensional array ? Incorporate c code ? The online docs are clearly insufficient for a novice. Have ordered Summerfields new book. From marduk at letterboxes.org Tue Dec 9 13:11:40 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Tue, 09 Dec 2008 13:11:40 -0500 Subject: Can't figure out where SyntaxError: can not delete variable 'x' referenced in nested scope us coming from in python >=2.6 Message-ID: <1228846300.4109.30.camel@brotherus.rdu.redhat.com> Say I have module foo.py: def a(x): def b(): x del x If I run foo.py under Python 2.4.4 I get: File "foo.py", line 4 del x SyntaxError: can not delete variable 'x' referenced in nested scope Under Python 2.6 and Python 3.0 I get: SyntaxError: can not delete variable 'x' referenced in nested scope The difference is under Python 2.4 I get a traceback with the lineno and offending line, but I do not get a traceback in Pythons 2.6 and 3.0. The reason why I ask is... I have a python package, 'foo', with __init__.py and a whole bunch of other modules. It runs fine on Python 2.4 as well as 2.6, but when I run 2to3 on my foo directory and try to 'import foo' in Python 3 I get no traceback, I can't 'import foo' in Python 2 because 'foo' is no longer Python2-compatible, but my original Python2 version of foo imports just fine. So is there a way to find the offending code w/o having to go through every line of code in 'foo' by hand? I've tried using pdb but it just breaks out of the debugger. thanks, -a From castironpi at gmail.com Mon Dec 8 15:15:59 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 8 Dec 2008 12:15:59 -0800 (PST) Subject: A question about reference in Python. References: <493CB003.3080209@gmail.com> Message-ID: <716e9093-7976-43e5-a37a-0773a24b8389@j39g2000yqn.googlegroups.com> On Dec 8, 9:18?am, Joe Strout wrote: > On Dec 7, 2008, at 10:26 PM, Group wrote: > > > Now, I want to write a Red-Black Tree, and a List structure. In C/C+ > > +, I can > > use pointers to refer to ?children ?notes (or next notes). But, in ? > > Python, how > > can I do it? Except the sequence, I know not any way. > > Any variable in Python is a reference, which is roughly analogous to a ? > pointer type in C/C++. ?For details and examples, see: ? Message-ID: On 2008-12-07, suku wrote: > i need some suggestion on making graphs. Will this be possible > with normal python setup file or do i need to download add ons for > that.. gnuplot-py matplotlib vtk -- Grant From lewis.sarah93 at yahoo.com Thu Dec 4 23:55:07 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 20:55:07 -0800 (PST) Subject: Reduce Debt Message-ID: <9f83499d-0eaf-4a7b-8d4e-b12e4512e0d2@j38g2000yqa.googlegroups.com> Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From andrew at doadesweb.co.uk Wed Dec 10 14:00:47 2008 From: andrew at doadesweb.co.uk (Andrew D) Date: Wed, 10 Dec 2008 11:00:47 -0800 (PST) Subject: get todays files References: Message-ID: <4632c353-0462-485b-9e1b-6a5c56682363@s9g2000prg.googlegroups.com> On Dec 10, 6:55?pm, Tim Chase wrote: > > I have a script that will login to my ftp server and download > > all the backup files, but I want it to only download the files > > that were created today, e.g. if I ran the script today I want > > it to only fetch files created today. > > Use Python's ftp module and send the MDTM command to get back the > timestamp of the filename. ?Insecurely, this would look something > like > > ? ?from ftplib import FTP > ? ?hostname = "ftp.mozilla.org" > ? ?conn = FTP(hostname) > ? ?user = "anonymous" > ? ?password = "u... at example.com" > ? ?conn.login(user, password) > ? ?filename = "pub/README" > ? ?results = conn.sendcmd("MDTM %s" % filename) > ? ?code, stamp = results.split(None, 1) > ? ?assert code == "213", "Unexpected result" > ? ?print "%s was modified on %s" % (filename, stamp) > ? ?today = '20081210' > ? ?if stamp[:8] == today: > ? ? ?process(filename) > ? ?else: > ? ? ?print "ignoring", filename > > The MDTM command is not part of the core RFC-959, but rather the > RFC-3659[1] so you might run across some servers that don't > support it. ?You can read more about the Python ftplib module at > [2] which would be where you want to read up on pulling back a > listing of the directory of file-names to check. ?There is a NLST > command (I don't have a server handy that supports this command). > ? The LIST command returns pretty/readable information that's not > quite so machine-parsing friendly (at least in a cross-FTP-server > sort of way). ?However, that part, I leave as an exercise for the > reader along with the complications of the "today" bit. > > Oh, SteveH, I checked your FTP-cloning source in my Python dir, > and it doesn't look like it does anything regarding file-times in > it, so that may have been a red-herring. ?Unless you've added > something since the ver. I've got here. > > -tkc > > [1]http://en.wikipedia.org/wiki/List_of_FTP_commands > > [2]http://www.python.org/doc/2.5.2/lib/ftp-objects.html This looks very good and I have tested successfully, but is there a way I can set the today to automatically become todays date in that format? Thanks though, this is what I was looking for! Andrew From zaz600 at gmail.com Thu Dec 25 21:34:15 2008 From: zaz600 at gmail.com (NoName) Date: Thu, 25 Dec 2008 18:34:15 -0800 (PST) Subject: SyntaxError: encoding problem: with BOM References: <6res8tF1do1sU1@mid.uni-berlin.de> <400f176b-bd9a-4f26-b01b-1aa7c7dcf5ac@z6g2000pre.googlegroups.com> <6rf6m1F1e0f8U1@mid.uni-berlin.de> <26e21f3f-ded1-48ca-8897-2ebd05dd07ad@w39g2000prb.googlegroups.com> Message-ID: > It's a bug, please report it. I though we fixed all Windows path bugs > for 3.0 but apparently one slipped through. > > Christian It is too difficult for me. please help me=) From boyee118 at gmail.com Wed Dec 17 09:49:17 2008 From: boyee118 at gmail.com (=?UTF-8?B?5Li654ix6ICM55Sf?=) Date: Wed, 17 Dec 2008 22:49:17 +0800 Subject: [Help] The pywinauto Can't select the MDI's menu using the MenuItems() which return []. Message-ID: I can't use the MenuItems() in my MDI application. Any example is very nice!!!! Thanks a lot! -- "OpenBookProject"-?????????? ??: http://groups.google.com/group/OpenBookProject ??: http://wiki.woodpecker.org.cn/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldo at geek-central.gen.new_zealand Sat Dec 6 02:28:17 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 06 Dec 2008 20:28:17 +1300 Subject: Don't you just love writing this sort of thing :) References: <0148b086$0$20670$c3e8da3@news.astraweb.com> <01490b5f$0$20670$c3e8da3@news.astraweb.com> Message-ID: In message <01490b5f$0$20670$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > On Fri, 05 Dec 2008 23:28:48 +1300, Lawrence D'Oliveiro wrote: > >> In message <0148b086$0$20670$c3e8da3 at news.astraweb.com>, Steven D'Aprano >> wrote: >> >>> Since the context has been deleted, it's hard to tell whether the code >>> as written by Lawrence ... >> >> If you want to reply to my message, reply to my message, don't reply to >> my reply to someone else's reply to my message. > > I did reply to your message. It was your message that was missing all the > context necessary to tell what you were rabbiting on about. If you wanted the context for your reply, you should have replied to the message with the context. That way you automatically get the context when you hit reply, no need to go out of your way to dig it up from a different posting. Does that make any sense to you, or should I start drawing simple diagrams? From nad at acm.org Thu Dec 4 18:51:31 2008 From: nad at acm.org (Ned Deily) Date: Thu, 04 Dec 2008 15:51:31 -0800 Subject: pretty strange behavior of "strip" References: <4938693F.6090709@yahoo.ca> Message-ID: In article <4938693F.6090709 at yahoo.ca>, Guy Doune wrote: > Could it be a bug????? > > Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> test=['03.html', '06.html', 'questions.html', '04.html', > 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test > ['03.html', '06.html', 'questions.html', '04.html', 'toc.html', > '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test[4] > 'toc.html' > >>> test[4].strip('.html') > 'oc' > > Can't figure out what is going on, really. >>> help("".strip) >>> help("".endswith) -- Ned Deily, nad at acm.org From gagsl-py2 at yahoo.com.ar Tue Dec 16 18:11:12 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Dec 2008 21:11:12 -0200 Subject: subprocess returncode windows References: <18348eae-5af1-47e9-a198-b95d4fcb6eac@a12g2000pro.googlegroups.com> Message-ID: En Tue, 16 Dec 2008 17:21:35 -0200, Andrew escribi?: > On Dec 16, 12:50?pm, Christian Heimes wrote: >> Andrew schrieb: >> >> > I'm running into a strange situation with getting incorrect >> > returncodes / exit status from python subprocess.call. I'm using a >> > python script (runtime 2.6.1 on windows) to automate the deploy of >> > java applications to glassfish application server. Below is an example > > I've removed shell=True, unfortunately, if I structure the call like: > > call(["c:/glassfish/bin/asadmin.bat", "list-system-properties", "-- > host > mydomain", "--port 4848", "--user admin", "server-01"]) > > It doesn't seem to recognize any arguments after list-system- > properties. Should be: call(["c:/glassfish/bin/asadmin.bat", "list-system-properties", "--host", "mydomain", "--port", "4848", "--user", "admin", "server-01"]) *Every* argument should be an item in the list (your way, "--port 4848" becomes a single argument, not two: option plus value) (This is independent of your other issue) > If I structure it like: > > call("c:/glassfish/bin/asadmin.bat "+"list-system-properties --host > mydomain --port 4848 --user admin server-01") > > Then it executes correctly but still gives invalid returncode of 0 > when it fails instead of 1. A similar example works fine for me: C:\temp>type ret.c #include int main(int argc, char* argv[]) { return atoi(argv[1]); } C:\temp>ret 5 C:\temp>echo %errorlevel% 5 C:\temp>type testret.bat ret %1 C:\temp>testret 3 C:\temp>ret 3 C:\temp>echo %errorlevel% 3 C:\temp>type testret.py from subprocess import call ret = call(["testret.bat", "42"]) print "testret.bat exit code =", ret C:\temp>python testret.py C:\temp>ret 42 testret.bat exit code = 42 C:\temp>python -V Python 2.6 C:\temp>ver Microsoft Windows XP [Versi?n 5.1.2600] -- Gabriel Genellina From steve at holdenweb.com Sat Dec 20 08:25:53 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 20 Dec 2008 08:25:53 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <2dc66762-f51e-4bbd-9372-756610d4201e@j11g2000yqg.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c4ef2$0$20656$c3e8da3@news.astraweb.com> <2d53cd36-52b0-4a1a-913d-0c545cfadc23@v15g2000vbb.googlegroups.com> <2dc66762-f51e-4bbd-9372-756610d4201e@j11g2000yqg.googlegroups.com> Message-ID: <494CF261.2040106@holdenweb.com> r wrote: > On Dec 19, 10:04 pm, Steve Holden wrote: >> r wrote: >>> Thanks Steven, >>> We need a real Pepsi challenge here to show the insignificance of this >>> change. I am not against change. But when we lose something as - >>> compact- as %formating i'm going to want to see a damn good reason for >>> it! Especially when this breaks code, and the "French Connection" is >>> not good enough reason for me :) >>> Christian said this was not going to be depreciated until 3.2, but >>> that still puts the accepted way on the chopping block. >> If Python is so important to you it's a pity you haven't been playing >> any active role in its development. Do you expect the developers to be >> psychic? > > Steve, > I just recently started to have an opinion about these things. "The > squeaky wheel get the grease", just allowing my voice be heard. It > might seem that i am trashing Python dev, but that could not be > further from the truth. > > Many great changes have been made in 3.0, i just feel strongly about C > style formating. Why could't we improve on what we had instead of > making radical changes? Thats all i am asking. I wasn't really a part of the decision-making process, but I anticipate that the developers' reply would be that the new scheme is much more adaptable, both to new data types (which can implement their own __format__ method) and to internationalization (because it's possible to alter word order in the format strings). Thanks for clarifying your approach, by the way, which isn't as unreasonable as it first seemed if you've only recently started using Python. You will find over time that the developers are right about these decisions much more than they are wrong, and you still have a couple of years to get used to it ;-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From fetchinson at googlemail.com Sat Dec 27 17:27:53 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 27 Dec 2008 14:27:53 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: >> I'm trying to write an extension module in C which contains a single >> function with the following prototype: >> void func( int N, int * arg1, int * arg2, int * ret ); >> Here arg1 and arg2 are length N arrays, and the function computes ret >> which is also an N length array. From python I'd like to call this >> function as >> ret = func( [ 1, 2, 3 ], [ 2, 3, 4] ) > > This requirement pretty much dictates the slow answer you have. I'm not sure I understand what you mean. > > Does this mean that I can only pass the arrays from python to C as > > generic python objects and in a later operation I need to get the > > elements from this generic python object, construct a C array and pass > > that to the C function? ... What's the simplest way of doing this? > > Either use ctypes, look into array.array, or look into numpy.array. I have considered using ctypes but for my needs using the C API directly seems more reasonable. array.array and numpy.array doesn't fit my needs since I need to do long and complicated operations on the two (pretty large) integer arrays that would be too slow using array.array and numpy.array (I've verified this claim by benchmarking a numpy.array based solution). > I'd just use numpy, myself: > import numpy > total = numpy.array([1, 2, 3]) + numpy.array([2, 3, 4]) What makes you think I want to add two arrays? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From trentm at activestate.com Sat Dec 13 16:17:28 2008 From: trentm at activestate.com (Trent Mick) Date: Sat, 13 Dec 2008 13:17:28 -0800 Subject: ActivePython 2.6.1.1 and 3.0.0.0 released! In-Reply-To: <58cd9ea1-9cf5-4c90-81ba-411774a878b7@o4g2000pra.googlegroups.com> References: <58cd9ea1-9cf5-4c90-81ba-411774a878b7@o4g2000pra.googlegroups.com> Message-ID: <49442668.1080500@activestate.com> Kay Schluehr wrote: > On 13 Dez., 00:16, Trent Mick wrote: > >> Note that currently PyWin32 is not included in ActivePython 3.0. > > Is there any activity in this direction? The PyWin32 CVS tree is getting checkins from Mark Hammond and Roger Upole with a py3k tag. I'm not sure how close they are currently. Trent -- Trent Mick trentm at activestate.com From bruno.42.desthuilliers at websiteburo.invalid Thu Dec 4 03:20:11 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 04 Dec 2008 09:20:11 +0100 Subject: python an sqlite objects In-Reply-To: References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <4936bceb$0$16783$426a34cc@news.free.fr> <4936dab7$0$9107$426a74cc@news.free.fr> Message-ID: <493792a9$0$16763$426a74cc@news.free.fr> skip at pobox.com a ?crit : > Bruno> Most of the time, you want to serialize the instance's __dict__. > > Does it recreate an instance at the other end or just a dict? If you serialize a dict, you'll obviously get a dict back. Note that the point of json is *not* to replace pickle. json is a *data* serialization format meant to represent "basic" types (dicts, lists, strings and numbers) in human readable and (mostly) language-agnostic way. If you want a Python object store, you'll be better looking at ZODB, Durus or friends. From lists at cheimes.de Wed Dec 24 11:09:17 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 24 Dec 2008 17:09:17 +0100 Subject: Using exceptions in defined in an extension module inside another extension module In-Reply-To: <26443e22-0dd6-4fa9-a58e-8d9314001c6c@o4g2000pra.googlegroups.com> References: <26443e22-0dd6-4fa9-a58e-8d9314001c6c@o4g2000pra.googlegroups.com> Message-ID: Floris Bruynooghe schrieb: > What I can't work out however is how to then be able to raise this > exception in another extension module. Just defining it as "extern" > doesn't work, even if I make sure the first module -that creates the > exception- gets loaded first. Because the symbol is defined in the > first extension module the dynamic linker can't find it as it only > seems to look in the main python executable for symbols used in > dlloaded sofiles. > > Does anyone have an idea of how you can do this? The answer is so obvious that you are going to bang your head against the next wall. You have to do exactly the same as you'd do with a pure Python module: import it. :) static PyObject *yourexc = NULL; PyObject *yourmod = PyImport_ImportModule("yourmod"); if (yourmod == NULL) return NULL; *yourexc = PyObject_GetAttrString(yourmod, "YourException"); if (yourexc == NULL) return NULL; Christian From rdcollum at gmail.com Fri Dec 19 09:44:02 2008 From: rdcollum at gmail.com (Roger) Date: Fri, 19 Dec 2008 06:44:02 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <494b5f47$0$17068$6e1ede2f@read.cnntp.org> <494b632b$0$17070$6e1ede2f@read.cnntp.org> Message-ID: <0390fcbc-8100-4aa8-93fa-ad358609ab7b@p2g2000prn.googlegroups.com> > either. I'd suggest a plain-python workaround along the lines of Wow. You just blew my mind. I'm going to play with this. Thanks a lot, I've really learned a lot in just that small bit. I don't have much experience in playing with a lot of the 'private' calls such as __call__. I need to do some more reading. Roger. From musiccomposition at gmail.com Mon Dec 8 22:45:36 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 8 Dec 2008 19:45:36 -0800 (PST) Subject: Catching Python exceptions in C References: Message-ID: On Dec 8, 12:42?pm, Senthil Kumar wrote: > Hi Pythoneers ! > Can somebody give a quick solution? > I am trying to raise exceptions in python and trying to handle it in > C. > I am able to raise exceptions successfully. However could not catch > those in C. > I am using the following function to run the python from C: > Pyrun_SimpleString(). > After the exception is raised, I am checking PyErr_Occurred(). It > always returns NULL, and I cannot catch the exception. > Pls help me a way out. If a function returns NULL, you can use PyErr_ExceptionMatches to check if it is the exception you want to catch. > > Thanx in advance ! From rt8396 at gmail.com Mon Dec 29 01:14:36 2008 From: rt8396 at gmail.com (r) Date: Sun, 28 Dec 2008 22:14:36 -0800 (PST) Subject: why cannot assign to function call References: Message-ID: <579ac8fe-8d8e-4c93-87d4-6a22c9d066f2@r40g2000yqj.googlegroups.com> On Dec 29, 12:01?am, scsoce wrote: > I have a function return a reference, and want to assign to the > reference, simply like this: > ?>>def f(a) > ? ? ? ? ? return a > ? ? ?b = 0 > ? ? * f( b ) = 1* > but the last line will be refused as "can't assign to function call". > In my thought , the assignment is very nature, ?but ?why the interpreter > refused to do that ? > > thks because all you need to do is >>> b = 1 trying to change the return value of a function before you even "know what it is" so to speak, defeats the whole purpose of sending it there in the first place. just assign the variable to a new value. Thats my common sense answer, maybe somebody can give a technical one :) From workingpad at gmail.com Sun Dec 28 23:26:21 2008 From: workingpad at gmail.com (Jack.Chu) Date: Sun, 28 Dec 2008 20:26:21 -0800 (PST) Subject: creating a datetime.datetime from an XML xs:dateTime References: <5fa6c12e0812271208x4baccaedk262e51becb6e2076@mail.gmail.com> <18774.36465.346262.883182@montanaro-dyndns-org.local> <5fa6c12e0812271255l4f4893e8w9f96e9ace73ea50c@mail.gmail.com> Message-ID: I think a simple regular expression is a relatively easy solution. From philip at semanchuk.com Tue Dec 9 12:29:17 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 9 Dec 2008 12:29:17 -0500 Subject: When (and why) to use del? In-Reply-To: <1228840517.4109.10.camel@brotherus.rdu.redhat.com> References: <1228840517.4109.10.camel@brotherus.rdu.redhat.com> Message-ID: On Dec 9, 2008, at 11:35 AM, Albert Hopkins wrote: > I'm looking at a person's code and I see a lot of stuff like this: > > def myfunction(): > # do some stuff stuff > my_string = function_that_returns_string() > # do some stuff with my_string > del my_string > # do some other stuff > return > > and also > > def otherfunction(): > try: > # some stuff > except SomeException, e: > # more stuff > del e > return > > > I think this looks ugly, but also does it not hurt performance by > preempting the gc? My feeling is that this is a misuse of 'del'. Am I > wrong? Is there any advantage of doing the above? The code above doesn't pre-empt the GC, it just provides it with a useful hint. When you del a variable you just tell the GC, "I'm done with this, so you might be able to get rid of it next time you collect garbage". If the variable wasn't explicitly del-ed, you'd still hold a reference and the GC would be unable to collect it while the section "do some other stuff" runs. HOWEVER, I don't code that way and I've never seen anyone else do that. It's ugly, as you said, and represents a lot of mental clutter for anyone reading/writing the code. And since the GC might not even run during the "do some other stuff" section, there might be no advantage at all to the explicit del. On rare occasions (I can think of once or twice in all the Python I've written) I'll del a variable that might use lots of memory if it wouldn't otherwise get dereferenced quickly (say, by going out of scope). But in my experience that's quite rare. Cheers Philip From clp at rebertia.com Mon Dec 15 15:16:06 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 15 Dec 2008 12:16:06 -0800 Subject: Problem accessing a web page In-Reply-To: References: Message-ID: <47c890dc0812151216o59a3cbc2uf98d74604988d27@mail.gmail.com> On Mon, Dec 15, 2008 at 11:55 AM, Antoni Mont wrote: > Hi all, > > My apologises if this is not the appropriate group. > > I'd like to access a web site from a python script. That page, in fact, > is a form of main page. With a browser (Firefox, for instance) I can do > it without problem: I open the main web whose url is: > > 'http://www.mcu.es/webISBN/tituloSimpleFilter.do?cache=init&prev_layout=busquedaisbn&layout=busquedaisbn&language=es' > > and then, from the same (or another tab) I open the form (it's a book > database and the ISBN is the relevant parameter) whose url is: > > 'http://www.mcu.es/webISBN/tituloSimpleDispatch.do?params.forzaQuery=N¶ms.cisbnExt=8484031128&action=Buscar&layout=busquedaisbn' > > So I get the information about the book. > > But when I try to do the same from the script, I get a time-out > error -without time elapsing at all. This is the piece of the > script relevant for the subject: I'm able to grab the problem webpage via Python just fine, albeit with a bit of a delay. So, don't know what your exact problem is, maybe your connection? If you're trying to programmatically browse the web, you might want to look at mechanize: http://wwwsearch.sourceforge.net/mechanize/ Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From arnodel at googlemail.com Mon Dec 15 16:28:03 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 15 Dec 2008 21:28:03 +0000 Subject: tricky nested list unpacking problem References: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> Message-ID: Reckoner writes: > Hi, > > I have lists of the following type: > > [1,2,3,[5,6]] > > and I want to produce the following strings from this as > > '0-1-2-3-5' > '0-1-2-3-6' > > That was easy enough. The problem is that these can be nested. For > example: > > [1,2,3,[5,6],[7,8,9]] > > which should produce > > '0-1-2-3-5-7' > '0-1-2-3-5-8' > '0-1-2-3-5-9' > '0-1-2-3-6-7' > '0-1-2-3-6-8' > '0-1-2-3-6-9' > > also, > > [1,2,3,[5,6],7,[9]] > > should produce > > '0-1-2-3-5-7-9' > '0-1-2-3-6-7-9' > > obviously, these are nested loops over the lists. The problem is that > I don't know ahead of time how many lists there are or how deep they > go. In other words, you could have: > > [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]] IMHO the second level of nested lists is unnecessary as the same can be achieved with just one sublevel of list (unless they are to be interpreted in a way you have not explained). If you avoid this double nesting then the 'flatten()' function below is not necessary anymore. > > Any help appreciated. I've really been having trouble with this. > > I hope that made sense. Here is a not thought out solution: def flatten(lst): for x in lst: if isinstance(x, list): for y in flatten(x): yield y else: yield x def unpack(lst): stack, strings = [], [] def rec(): i = len(stack) if i == len(lst): strings.append('-'.join(map(str, stack))) elif isinstance(lst[i], list): for x in flatten(lst[i]): stack.append(x) rec() stack.pop() else: stack.append(lst[i]) rec() rec() return strings l1 = [1,2,3,[5,6]] l2 = [1,2,3,[5,6],[7,8,9]] l3 = [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]] Then: >>> unpack(l1) ['1-2-3-5', '1-2-3-6'] >>> unpack(l2) ['1-2-3-5-7', '1-2-3-5-8', '1-2-3-5-9', '1-2-3-6-7', '1-2-3-6-8', '1-2-3-6-9'] >>> unpack(l3) ['1-2-3-5-7-9', '1-2-3-5-7-1', '1-2-3-5-7-2', '1-2-3-5-7-3', '1-2-3-5-7-4', '1-2-3-5-7-5', '1-2-3-5-6-9', '1-2-3-5-6-1', '1-2-3-5-6-2', '1-2-3-5-6-3', '1-2-3-5-6-4', '1-2-3-5-6-5', '1-2-3-5-10-9', '1-2-3-5-10-1', '1-2-3-5-10-2', '1-2-3-5-10-3', '1-2-3-5-10-4', '1-2-3-5-10-5', '1-2-3-5-11-9', '1-2-3-5-11-1', '1-2-3-5-11-2', '1-2-3-5-11-3', '1-2-3-5-11-4', '1-2-3-5-11-5'] -- Arnaud From rhamph at gmail.com Mon Dec 8 23:44:09 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 8 Dec 2008 20:44:09 -0800 (PST) Subject: Rich Comparisons Gotcha References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> Message-ID: <85dacb56-4f2c-42ad-a9a9-90ce7fbc5032@g17g2000prg.googlegroups.com> On Dec 8, 7:44?pm, Steven D'Aprano wrote: > On Mon, 08 Dec 2008 10:20:56 -0800, Rhamphoryncus wrote: > > On Dec 7, 4:20?pm, Steven D'Aprano > cybersource.com.au> wrote: > >> On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: > >> > Rasmus Fogh wrote: > > >> >> Current behaviour is both inconsistent and counterintuitive, as > >> >> these examples show. > > >> >>>>> x = float('NaN') > >> >>>>> x == x > >> >> False > > >> > Blame IEEE for that one. Rich comparisons have nothing to do with > >> > that one. > > >> There is nothing to blame them for. This is the correct behaviour. NaNs > >> should *not* compare equal to themselves, that's mathematically > >> incoherent. > > > Mathematically, NaNs shouldn't be comparable at all. ?They should raise > > an exception when compared. ?In fact, they should raise an exception > > when *created*. ?But that's not what we want. ?What we want is a dummy > > value that silently plods through our calculations. ?For a dummy value > > it seems a lot more sense to pick an arbitrary yet consistent sort order > > (I suggest just above -Inf), rather than quietly screwing up the sort. > > > Regarding the mythical IEEE 754, > > It's hardly mythical. > > http://ieeexplore.ieee.org/ISOL/standardstoc.jsp?punumber=4610933 I consider it to be mythical because most knowledge of it is indirect. Few who use floating point have the documents available to them. Requiring purchase/membership is the cause of this. > > although it's extremely rare to find > > quotations, I have one on just this subject. ?And it does NOT say "x == > > NaN gives false". ?It says it gives *unordered*. > > Unordered means that none of the following is true: > > x > NaN > x < NaN > x == NaN > > It doesn't mean that comparing a NaN with something else is an error. Robert Kern already clarified that. My confusion was due to relying on second-hand knowledge. From cournape at gmail.com Mon Dec 29 21:52:44 2008 From: cournape at gmail.com (David Cournapeau) Date: Tue, 30 Dec 2008 11:52:44 +0900 Subject: Python in C In-Reply-To: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> References: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> Message-ID: <5b8d13220812291852y42b227d8w736546eff5f6947b@mail.gmail.com> On Tue, Dec 30, 2008 at 10:22 AM, wrote: > I've just downloaded Python's mainstream implementation (CPython), > which is written in C. Not to my surprise, I feel like I'm looking at > unstructured spaghetti, and I'm having trouble figuring out how it all > works together. (Please bear with me; I'm just going through the usual > frustration that anyone goes through when trying to see the > organization of a C program :) > > So, I have two queries: > > 1. Can anyone explain to me what kind of program structuring technique > (which paradigm, etc) CPython uses? How do modules interact together? > What conventions does it use? I am not sure what you mean by "which paradigm". CPython uses ansi C, objects visible at the python level are structures, the API is exposed through array of function pointers, etc... which are all standard C techniques. All core objects are in Objects, and each of them expose its API in a function pointer array; for example, the complex object (in complexobject.c) implements its basic API through the PyObjectType, which contains functions called by the interpreter. At the beginning, I was a bit confused by the terminology (like protocol), but that may just be my poor English. The documentation is pretty good: http://docs.python.org/c-api/index.html (for python 2.6) It may be easier to first see how to code your own extension, maybe - if only because the related doc is written as a tutorial instead of as a reference as the above. > > 2. Have there been any suggestions in the past to rewrite Python's > mainstream implementation in C++ (or why wasn't it done this way from > the beginning)? Python was started in the early 90, where arguably, C++ was not easy to deal with: not many good compilers were available, most 'interesting' features of C++ were not portable because implemented differently. Without going through the dreadful C vs C++, C++ is arguably more complex and much bigger than C++, to the point where it is almost impossible for anyone to master the whole language. This means that people only use a subset of it, and many projects use a coding style which severly limit what you can do to avoid everyone using a different subset; this can be managed in constraints environments, but it does not work well in open source generally. It is certainly not my experience that C++ is more readable than C in the projects I have been involved with. Also, there are some objective facts against C++ for things "at the bottom" like a programming language: C++ is not easily callable from other languages, whereas C is (the C ABI is standardized on many platforms, whereas C++ is not). In particular, calling dynamically loaded code in C++ is very difficult (practically, a C wrapper has to be provided). Taking an example of arguably mature and big C++ project, the JDK, its external API is in C, not C++. cheers, David From benjamin.kaplan at case.edu Tue Dec 23 08:44:47 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 23 Dec 2008 08:44:47 -0500 Subject: SuSE11.1 eclipse 64 pydev can't add python path In-Reply-To: References: Message-ID: On Tue, Dec 23, 2008 at 7:49 AM, Reimar Bauer wrote: > Hi > > I can install pydev using the update manager in eclipse for 64 bit from the > SuSE 11.1 repo. But I can't configure pydev without crashing it. > I can select the interpreter /usr/bin/python > and I do see the System PYTHONPATH > Forced builtin libs also looks good. > > But Apply gives me > # > # An unexpected error has been detected by Java Runtime Environment: > # > # SIGSEGV (0xb) at pc=0x00007f2d7abebaed, pid=6544, tid=139832007596368 > # > # Java VM: IcedTea 64-Bit Server VM (1.7.0-b24 mixed mode linux-amd64) > # Problematic frame: > # V [libjvm.so+0x21baed] > # > # An error report file with more information is saved as: > # /home/user/hs_err_pid6544.log > # > # If you would like to submit a bug report, please visit: > # http://icedtea.classpath.org/bugzilla > # The crash happened outside the Java Virtual Machine in native code. > # See problematic frame for where to report the bug. > > > That problem happens also with the recent > eclipse-cpp-ganymede-SR1-linux-gtk-x86_64.tar.gz > > What can be the cause for this problem? Do you know a workaround e.g. > manually configuring pydev? > > Does one have pydev or eclipse working on SuSE11.1? > > > cheers > Reimar > This isn't a problem with PyDev. This is a known bug in the 64-bit Java, both Sun and OpenJDK. It was fixed in the really recent updates (Sun 6u10 and OpenJDK 6b12, I think), which I guess SuSE doesn't have yet. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Fri Dec 5 19:27:27 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sat, 06 Dec 2008 01:27:27 +0100 Subject: Running Python 2 and Python 3 on the same machine In-Reply-To: <1228489547.5613.10.camel@linux-3eb6.site> References: <1228424486.5873.6.camel@linux-3eb6.site> <49387f7e$0$27857$9b622d9e@news.freenet.de> <1228489547.5613.10.camel@linux-3eb6.site> Message-ID: <4939c6ef$0$6534$9b622d9e@news.freenet.de> > For *NIX machines, will 'python' be placed into /usr/bin? Not by default, no. Just try it and see for yourself. Regards, Martin From jcd at sdf.lonestar.org Wed Dec 10 18:29:44 2008 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Wed, 10 Dec 2008 18:29:44 -0500 Subject: var or inout parm? In-Reply-To: <47c890dc0812080057r6d117bbcic377cb96de52d973@mail.gmail.com> References: <493cda2a$0$17080$426a34cc@news.free.fr> <47c890dc0812080057r6d117bbcic377cb96de52d973@mail.gmail.com> Message-ID: <1228951784.5698.1.camel@mctell> On Mon, 2008-12-08 at 00:57 -0800, Chris Rebert wrote: > On Mon, Dec 8, 2008 at 12:26 AM, Bruno Desthuilliers > wrote: > > Colin J. Williams a ?crit : > >> > >> mh at pixar.com wrote: > >>> > >>> How can I make a "var" parm, where the called function can modify > >>> the value of the parameter in the caller? > >>> > >>> def f(x): > >>> x = x + 1 > >>> > >>> n = 1 > >>> f(n) > >>> # n should now be 2 > >>> > >>> Many TIA!! > >>> Mark > >>> > >>> > >> > >> Why not run it and see? > >> > >> Your function returns None. > >> > >> The function in effect takes a copy of n. > > > > Nope, it takes the object bound to global name 'n'. > > See Also: the earlier heated debate thread over what evaluation > strategy Python uses (Survey says!: call-by-object). > Oh dear God. PLEASE don't see also that thread. That way lies madness. Just google for call-by-object, and ignore the hell out of that thread. > Cheers, > Chris > From news123 at free.fr Wed Dec 17 15:20:40 2008 From: news123 at free.fr (News123) Date: Wed, 17 Dec 2008 21:20:40 +0100 Subject: mysql hash generator in python In-Reply-To: References: Message-ID: <49495f18$0$17874$426a74cc@news.free.fr> Hi Matias. Could you show us the 'class implementation'? Whether class or not the result should be the same. If it isn't, then there should be a small error. If we have both code versions to look at it's easier to help you. bye N Mat?as Hern?ndez wrote: > (sorry for my english, but i'm speak spanish) > Hi list.. this is my first post... and obviously if for help.. > > I try to implement the password function of mysql in a python script. > > I read that the password function of mysql was implemented with a double > sha1() > > I python i try this: > example1: > if __name__=="__main__": > s = hashlib.sha1() > s.update('test') > s2 = hashlib.sha1() > s2.update(s.digest() > print s2.hexdigest() > > This script show me the same hash that password function of mysql, but > when i implement this in a class the hash is different??? why??? > > And if is posible??? can you show a example code of old_password > function of mysql in python??? > > THNX From LambertDW at Corning.com Thu Dec 11 02:07:54 2008 From: LambertDW at Corning.com (Lambert, David W (S&T)) Date: Thu, 11 Dec 2008 02:07:54 -0500 Subject: if expression source format Message-ID: <84B204FFB016BA4984227335D8257FBA625679@CVCV0XI05.na.corning.com> The "if" expression leads to long statements. Please offer suggestions to beautify this function. For this example use maximum line length marked by the ####'s. Thank you. ############################################################## def compute_wind_chill_temperture(T:'Temperature, dF',s:'Wind speed, mph')->'dF': ''' ''' return 35.74 + 0.6215*T + s**0.16*(T*0.4275-35.75) if T < 40 else T From google at mrabarnett.plus.com Sat Dec 6 18:48:49 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 06 Dec 2008 23:48:49 +0000 Subject: how to get a beep, OS independent ? In-Reply-To: <493B0D85.3060404@gmail.com> References: <493B0D85.3060404@gmail.com> Message-ID: <493B0F61.6030604@mrabarnett.plus.com> Stef Mientki wrote: > hello, > > I want to give a small beep, > for windows there's message-beep, > and there seems to be something like " curses" , > but that package seems to be totally broken in P2.5 for windows. > > Any other suggestions ? > print chr(7)? From gagsl-py2 at yahoo.com.ar Wed Dec 10 17:23:09 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 10 Dec 2008 20:23:09 -0200 Subject: When (and why) to use del? References: <1228840517.4109.10.camel@brotherus.rdu.redhat.com> Message-ID: En Tue, 09 Dec 2008 15:29:17 -0200, Philip Semanchuk escribi?: > On Dec 9, 2008, at 11:35 AM, Albert Hopkins wrote: > >> def myfunction(): >> # do some stuff stuff >> my_string = function_that_returns_string() >> # do some stuff with my_string >> del my_string >> # do some other stuff >> return >> >> I think this looks ugly, but also does it not hurt performance by >> preempting the gc? My feeling is that this is a misuse of 'del'. Am I >> wrong? Is there any advantage of doing the above? > > The code above doesn't pre-empt the GC, it just provides it with a > useful hint. When you del a variable you just tell the GC, "I'm done > with this, so you might be able to get rid of it next time you collect > garbage". If the variable wasn't explicitly del-ed, you'd still hold a > reference and the GC would be unable to collect it while the section "do > some other stuff" runs. Note that CPython has a garbage collector AND uses reference counts. Objects are deallocated *immediately* as soon as their reference count reaches zero. The GC is used only to detect and dispose of reference cycles. So, if you `del` a name and it happens to be the last reference to certain object, the object is immediately destroyed; the GC isn't involved at all. > On rare occasions (I can think of once or twice in all the Python I've > written) I'll del a variable that might use lots of memory if it > wouldn't otherwise get dereferenced quickly (say, by going out of > scope). But in my experience that's quite rare. Yes, I've seldom used "del" in those circumstances too. And inside an exception handler. I can't remember of other cases. -- Gabriel Genellina From fetchinson at googlemail.com Sat Dec 6 16:49:40 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 6 Dec 2008 13:49:40 -0800 Subject: Guido's new method definition idea In-Reply-To: <493a9fed$0$18973$426a34cc@news.free.fr> References: <493a9fed$0$18973$426a34cc@news.free.fr> Message-ID: >> Hi folks, >> >> The story of the explicit self in method definitions has been >> discussed to death and we all know it will stay. However, Guido >> himself acknowledged that an alternative syntax makes perfect sense >> and having both (old and new) in a future version of python is a >> possibility since it maintains backward compatibility. The alternative >> syntax will be syntactic sugar for the old one. This blog post of his >> is what I'm talking about: >> >> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html >> >> The proposal is to allow this: >> >> class C: >> def self.method( arg ): >> self.value = arg >> return self.value >> >> instead of this: >> >> class C: >> def method( self, arg ): >> self.value = arg >> return self.value >> > (snip) >> I'd like this new way of defining methods, what do you guys think? > > -1 > > As far as I'm concerned, it doesn't add anything to the language, nor > doesn't save any typing, so I just don't see the point. And having it > co-existing with the normal syntax will only add more confusion. It doesn't add anything but makes something that exists a bit clearer and friendlier to newbies. Saving typing was never the intention. > NB : FWIW, I would eventually have voted -0 if it had been proposed for > Python 3, and as a _replacement_ (not _alternative_) to the current > syntax. But Python 3 is now released, so... There will be python 4000 eventually :) -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From bearophileHUGS at lycos.com Mon Dec 1 20:02:17 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 1 Dec 2008 17:02:17 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: <673ca33e-9c1e-4c8e-a81d-d46828fe47b1@n10g2000yqm.googlegroups.com> Mathematica has some powerful symbolic processing capabilities, for example the integrals, etc. It also contains many powerful algorithms, often written in few lines of code. And its graphic capabilities are good. It also shows some surprising ways to integrate and manipulate data, for example here you can see how you can even put images into formulas, to manipulate them: http://reference.wolfram.com/mathematica/ref/ImageApply.html So when you need an algorithm, you can often find it already inside, for example in the large Combinatorics package. So it has WAY more batteries included, compared to Python. I'd like to see something as complete as that Combinatorics package in Python. But while the editor of (oldish) Mathematica is good to quickly input formulas (but even for this I have found way better things, for example the editor of GraphEQ www.peda.com/grafeq/ that is kilometers ahead), it's awful for writing *programs* even small 10-line ones. Even notepad seems better for this. For normal programming Python is light years more handy and better (and more readable too), there's no contest here. Python is also probably faster for normal programs (when built-in functions aren't used). Python is much simpler to learn, to read, to use (but it also does less things). A big problem is of course that Mathematica costs a LOT, and is closed source, so a mathematician has to trust the program, and can't inspect the code that gives the result. This also means that any research article that uses Mathematica relies on a tool that costs a lot (so not everyone can buy it to confirm the research results) and it contains some "black boxes" that correspond to the parts of the research that have used the closed source parts of Mathematica, that produce their results by "magic". As you can guess, in science it's bad to have black boxes, it goes against the very scientific method. Bye, bearophile From ppearson at nowhere.invalid Fri Dec 5 12:33:11 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 5 Dec 2008 17:33:11 GMT Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> Message-ID: <6pt6unF9q11aU1@mid.individual.net> On Thu, 4 Dec 2008 15:49:46 -0600, skip at pobox.com wrote: > > It's more than warnings. With properly crafted > combinations of spaces and tabs you can get code which > looks like it has a certain indentation to the human > observer but which looks like it has different indentation > (and thus different semantics) to the byte code compiler. > There is often no warning. Fascinating. Has anybody developed demo code that looks, during code review, as if it prints a Snoopy calendar, but really, during execution, emails your password file to Minsk? The security implications are intriguing. What's the most underhanded thing anybody has seen done? -- To email me, substitute nowhere->spamcop, invalid->net. From bearophileHUGS at lycos.com Sun Dec 7 21:17:58 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 7 Dec 2008 18:17:58 -0800 (PST) Subject: Python for kids? References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> <53f406ed-c261-4d86-a8dc-4001d10d05b5@s20g2000yqh.googlegroups.com> <11a3e492-3c0d-475f-b350-f28351842dad@f3g2000yqf.googlegroups.com> Message-ID: <0494617a-4ac3-40a9-9ff0-d39cd4882497@s20g2000yqh.googlegroups.com> Luis M. Gonz?lez: >After he tried hard many approaches to solving the problem with his limited knowledge,< You may even be surprised to see he/her/hir find a solution without your help :-) Or maybe you will see a different solution, this happens often in math and computer science, even basic ones. >show him the right way. This way he will see the light.< Sometimes if the problem is interesting there are more than one "right way". And showing the light is more a purpose for priests than teachers ;-) Note that such things are well known, you can find similar things in tons of (most) books about pedagogy. For example you can try a simple but delicious book, "Brainstorms" by Seymour Papert (who also was one of the inventors of Logo language and is currently learning to talk and walk again). You can even find similar ideas in books more far from pedagogy ones, like "Deschooling Society" by Ivan Illich. Bye, bearophile From fernandohsanches at gmail.com Fri Dec 5 15:16:47 2008 From: fernandohsanches at gmail.com (Fernando H. Sanches) Date: Fri, 5 Dec 2008 12:16:47 -0800 (PST) Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> Message-ID: <84332560-580d-488b-aa6b-6aad754a7805@k36g2000pri.googlegroups.com> On Dec 4, 5:45?pm, Andreas Waldenburger wrote: > On Thu, 4 Dec 2008 11:52:38 -0600 s... at pobox.com wrote: > > > > > ? ? >>> As you have probably guessed: nothing changed here. > > ? ? >>> Also see:http://www.python.org/dev/peps/pep-0666/ > > > ? ? >> What? Do you mean it's possible to mix tabs and spaces still? > > ? ? >> Why? > > > ? ? Daniel> Why not? > > > Because it has historically been a source of errors in a mixed > > development environment (people using text editors with different tab > > stops). ?Better to not allow them to be mixed. > > Whenever has it been a pythonic ideal to "not allow" stuff? You get > warnings. Everything else is up to you. > > /W > > -- > My real email address is constructed by swapping the domain with the > recipient (local part). Python has "not allowed stuff" for a long time. For example, it disallows statements in lambdas. "Disallowing" is not bad. Disallowing bad practices (like mixing tabs and spaces) is actually good! I agree that the tab/space thing should be changed. Would it be too hard to make the parser see if the indentation is consistent in the whole file? This is a annoying source of problems, specially since you can't tell a whitespace from a tab just looking at it. And I personally disliked most of the changes (specially the ones on map and reduce). I hope functional programming doesn't get even more hindered in future releases, because I believe these changes only made Python weaker. Well, anyway, congratulations for everyone for Python 3 release. Some of the changes were a real improvement (like the Unicode sources). And I hope that, in the end, these changes help making Python a better language. From brendandetracey at yahoo.com Fri Dec 12 09:25:14 2008 From: brendandetracey at yahoo.com (Brendan) Date: Fri, 12 Dec 2008 06:25:14 -0800 (PST) Subject: Reading online zip files - zipfile and zlib, wbits Message-ID: I am fooling around with accessing contents of zip files online. I download the tail end of the zip and use zipfile to get the zip central directory structure. I download the section of the zip file I need, directly read the zip file headers and use that information with zlib to uncompress the data. The files I am examining will always be compressed using deflate, with a wbits value of -15(minus for headerless data because I am unsure whether the zip file header is what zlib expects). I can not find anywhere in the PK Zip Application notes ( http://www.pkware.com/documents/casestudies/APPNOTE.TXT ) how to determine the value I should uze for wbits with zlib.decompress. I have determined it is -15 from experimentation. Does anyone know the answer to this? From tjreedy at udel.edu Mon Dec 8 17:21:30 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Dec 2008 17:21:30 -0500 Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? In-Reply-To: <682de8aa-62b1-477a-8b31-ae7698b1ffe7@w1g2000prk.googlegroups.com> References: <5ccd4a18-cd2b-4040-90c6-33723af15e96@b38g2000prf.googlegroups.com> <7e1a9226-c7a9-4b5e-bfbb-ea079639d6a2@t39g2000prh.googlegroups.com> <682de8aa-62b1-477a-8b31-ae7698b1ffe7@w1g2000prk.googlegroups.com> Message-ID: illume wrote: > On Dec 8, 7:31 pm, alex23 wrote: >> On Dec 8, 2:26 pm, illume wrote: >> >>> pygame is simpler to learn, since it doesn't require you to know how >>> to create classes or functions. >> I'm not sure if I'd be quick to tout that as an advantage... :) > > Hi, > > It's easier to teach only requiring *using* classes, and functions > than *creating* them. This is important if it's being used to teach > programming - as you don't need to teach people two fairly large > concepts before you can do anything. Every program defines a function that maps input from the external world (possible null, but not for a game) to output to the external world (presumable not null, certainly not for a game). So defining internal function objects is not that big a step. I agree that creating new classes is a big step, and that using callbacks can be a mind-twister. tjr From jr9445 at ATT.COM Mon Dec 8 16:07:01 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Mon, 8 Dec 2008 15:07:01 -0600 Subject: Guido's new method definition idea In-Reply-To: <699ea750-8dd9-472f-a7aa-90492c32c519@z1g2000yqn.googlegroups.com> References: <493a9fed$0$18973$426a34cc@news.free.fr> <493c1ff6$0$4942$426a34cc@news.free.fr><49d12ec1-2be9-497b-80bc-9f0402a9086d@s20g2000yqh.googlegroups.com> <699ea750-8dd9-472f-a7aa-90492c32c519@z1g2000yqn.googlegroups.com> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Aaron Brady > Sent: Monday, December 08, 2008 3:27 PM > To: python-list at python.org > Subject: Re: Guido's new method definition idea > > On Dec 7, 4:23?pm, Philip Slate wrote: > > On Dec 7, 1:13?pm, Bruno Desthuilliers > > > > wrote: > > > > and friendlier to newbies. > > > > > I'd rather say "more acceptable to java-brainwashed developpers". > > > > And I'd rather say you're trolling, but that's ok since you're > > preaching to the converted. You conveniently forgot to mention the > C++/ > > Eiffel/Smalltalk/pretty-much-every-OO-lang "brainwashed" developers > > too. In reality Python, with its kludgy OO and objects being > > essentially glorified dicts, is the odd one out, not the other way > > around. > > That's true. But what would a Python-brainwashed developer be? Anyone who believes that writing beautiful, unencumbered code is efficient, while still believing that discovering type casting errors at runtime isn't grossly inefficient. Or given whitespace delimited code, Python developers believe that nothing is important. ;-) ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA623 From wdraxinger at darkstargames.de Mon Dec 8 07:33:36 2008 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Mon, 08 Dec 2008 13:33:36 +0100 Subject: Shutdown Mac OSX computer using python References: Message-ID: <0qgv06-jpp.ln1@skadi.yggdrasil.draxit.de> H?kan Hagenrud wrote: > Hello, i'm a python noob! > > But I would like to shutdown a 10.5.x mac computer using python > (2.5.1) > > this is my code: > #!/usr/bin/python > import SystemEvents > down = SystemEvents.Power_Suite.Power_Suite_Events() > down.shut_down() > > the last call needs an additional argument, I cant find any > documentation about this. Anybody knows? > > Thank you! Why so complicated? MacOS X is a Unix at it's base, so you can use Unix commands. #!/usr/bin/python import os os.system("shutdown -h now") Must be run as root, won't work otherwise. You can however add to sudoers (man visudo) shutdown as NOPASSWD program for the users that want to execute the script and use "sudo shutdown ..." instead of just "shutdown ..." Wolfgang Draxinger -- E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 16 03:45:36 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 16 Dec 2008 09:45:36 +0100 Subject: ethical questions about global variables In-Reply-To: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> References: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> Message-ID: <49476a7c$0$28214$426a74cc@news.free.fr> Giampaolo Rodola' a ?crit : > Hi, > in a module of mine (ftpserver.py) I'd want to add a (boolean) global > variable named "use_gmt_times" to decide whether the server has to > return times in GMT or localtime but I'm not sure if it is a good idea > because of the "ethical" doubts I'm gonna write below. > > In first place I've never liked global variables too much and always > preferred per-class-instance variables instead. > The problem in my case is that I have to use such variable in two > separated classes: FTPHandler and VirtualFileSystem. Also, I want that > for no reason one class uses times in GMT and the other one local > times. Looks like it's more a configuration variable than a global. IOW, it's not supposed to change during execution. > Another doubt is the naming convention. PEP-8 states that global > variables should use the lower_case_naming_convention but I've seen a > lot of library module using the UPPER_CASE_NAMING_CONVENTION. ALL_UPPER_NAMES are pseudo-constants - IOW, they are really variables but are by convention considered as constants. HTH From goatold at gmail.com Mon Dec 15 21:46:55 2008 From: goatold at gmail.com (goatold at gmail.com) Date: Mon, 15 Dec 2008 18:46:55 -0800 (PST) Subject: socket and subprocess problem Message-ID: <6d3291c3-4e12-4bdd-884a-21f15f38d105@a12g2000pro.googlegroups.com> Hi all, Here is my problem, see if any one else met this before In my python code I use subprocess.Popen to run and external program who will listen to a TCP port. And I also create a socket to connect to the TCP port that the external program is listening. I will get 'Connection refused, errno=111' when I try to socket.connect (). But if I run my subprocess.Popen code and socket code in two separate python process. Socket will connect just fine. OS is RHEL5 x86_64, python version is 2.6.1 Pseudo code as below Class a: def run() subprocess.Popen(..) Class b: def run(): sock = socket.socket() sock.connect(..) ################################# test.py # socket connect will fail here a.run() b.run() ################################### test1.py if __name__ = '__main__': a.run() test2.py # socket will connect fine if __name__ = '__main__': b.run From eric at ericaro.net Wed Dec 10 06:08:05 2008 From: eric at ericaro.net (eric) Date: Wed, 10 Dec 2008 03:08:05 -0800 (PST) Subject: Best way to report progress at fixed intervals References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> <817384d5-5f68-4c1f-9560-0bc7b7d2b1e3@v5g2000prm.googlegroups.com> <6ccb77a2-a3f1-4b6b-900c-d4626be9e939@s1g2000prg.googlegroups.com> Message-ID: <93371329-5989-4f96-ac79-58a54ba6b07f@35g2000pry.googlegroups.com> Don't mind if I give my shot ? def work(i): """ Dummy process function, which takes a random time in the interval 0.0-0.5 secs to execute """ print "Work step %d" % i time.sleep(0.5 * random.random()) def workAll(work, verbose=True, max_iter=20, progress_interval=1.0): ''' pass the real job as a callable ''' progress = time.time() for i in range(max_iter): # do the requested loop work(i) if verbose: print "Work through all %d steps reporting progress every %3.1f secs..." %(max_iter, progress_interval) interval = time.time()-progress if interval>progress_interval: print "Processed %d of %d at pace %s" % (i, max_iter, interval) progress +=interval if __name__=="__main__": workAll(work, False) It's works fine, and the "pace" is 'almost' the required one. You earn a no-thread-mess, and cleaner alg. But the loop is controlled by the caller (the WorkAll function) this is also called ass-backward algorithm, and you cannot expect algorithms to be assbackward (even if it's the best way to implement them). You can use the yield statement, to turn easilly your alg into a nice, stopable assbackward algo: def work(): """ Dummy process function, which takes a random time in the interval 0.0-0.5 secs to execute """ for i in range(50): print "Work step %d" % i time.sleep(0.5 * random.random()) yield i # kind-of "publish it and let the caller do whatever it want s (good practice anyway) def workAll(work, verbose=True, max_iter=20, progress_interval=1.0): ''' pass the real job as a generator ''' progress = time.time() i = 0 for w in work: # do the requested loop if verbose: print "Work through all %d steps reporting progress every %3.1f secs..." %(max_iter, progress_interval) interval = time.time()-progress if interval>progress_interval: print "Processed %d at pace %s" % (w, interval) progress +=interval if i>=max_iter: work.close() i+=1 if __name__=="__main__": workAll(work(), False) # note the calling difference hope it helps. From Scott.Daniels at Acm.Org Mon Dec 15 14:46:27 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 15 Dec 2008 11:46:27 -0800 Subject: Removing None objects from a sequence In-Reply-To: <01538f0c$0$6988$c3e8da3@news.astraweb.com> References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> <4942E668.5030100@tim.thechases.com> <01538f0c$0$6988$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Fri, 12 Dec 2008 19:02:24 -0500, Terry Reedy wrote: > ... >> Tim Chase wrote: >>>> If you want to literally remove None objects from a list....(or >>>> mutable sequence) >>>> >>>> def deNone(alist): >>>> n=len(alist) >>>> i=j=0 >>>> while i < n: >>>> if alist[i] is not None: >>>> alist[j] = alist[i] >>>> j += 1 >>>> i += 1 >>>> alist[j:i] = [] > Contrast that with the alternative suggested by Tim: > > def deNone2(alist): > alist[:] = [x for x in alist if x is not None] > ... > Here's another low-level algorithm, the classical delete items in place > algorithm. Three lines, one index, lousy O(N**2) performance. > > def deNone3(alist): > for i in xrange(len(alist)-1, -1, -1): > if alist[i] is None: > del alist[i] > > Now, let's do a shoot-out. Do they return the same thing? ... [good measurements generally reinforcing Tim's implementation] ... If you want to keep the original's method, but do it in a more Pythonic way, I would suggest: def deNone4(alist): j = 0 for val in alist: if val is not None: alist[j] = val j += 1 del alist[j :] This still loses to Tim's clearer code, but by nowhere near as much. --Scott David Daniels Scott.Daniels at Acm.Org From jstroud at mbi.ucla.edu Sun Dec 14 18:42:18 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 14 Dec 2008 15:42:18 -0800 Subject: Looking for the best way to translate an idiom In-Reply-To: References: Message-ID: Paul Moore wrote: > I'm translating some code from another language (Lua) which has > multiple function return values. So, In Lua, it's possible to define a > function > > function f() > return 1,2,3 > end > > which returns 3 values. These can then be used/assigned by the caller: > > a,b,c = f() > > So far, much like Python, but the key difference is that in Lua, > excess arguments are ignored - so you can do py> class mytuple(tuple): def magic(self, astr): names = astr.split() for name, val in zip(names, self): globals()[name] = val ... py> t = mytuple((1,2,3)) py> t.magic('a b') py> a 1 py> b 2 James From zapwireDASHgroups at yahoo.com Wed Dec 24 18:47:07 2008 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Wed, 24 Dec 2008 15:47:07 -0800 Subject: Easy-to-use Python GUI Message-ID: Is there an easy-to-use, "function"-based cross-platform GUI toolkit for Python out there that's a little more sophisticated than EasyGui? EasyGui looks good, but it's a little more restrictive than what I'd like to have, yet I'm (stubbornly :-) ) resistant to stepping up to a "full service" GUI toolkit such as pyGTK or wxPython where it's all about event loops and callbacks and you need to start planning how the GUI affects the overall program flow rather than just using a "forms" (or "Wizard")-type approach where you put up a few dialogs, users fill in some variables, and your program just sits around waiting until "OK" or "Cancel" is clicked. One approach that I like comes from SAX BASIC/WinWrap, which is more or less a clone of Microsoft's Visual BASIC for Applications, but they (apparently) wanted everything to still be human-readable, so they have a simple GUI ("form") builder that generates code that looks like this: --- Begin Dialog UserDialog 850,497,"Export Control" ' %GRID:10,7,1,1 GroupBox 20,7,360,217,"Drill File Generation",.GroupBox1 CheckBox 40,35,130,14,"Output drill file(s)",.genDrill Text 40,63,270,28,"Identify via layers as any that contain this text in their names:",.Text TextBox 40,98,220,21,.viaLayerName Text 40,140,100,14,"Output method:",.Text8 DropListBox 160,140,180,21,DrillStyle(),.drillStyle Text 40,175,130,28,"Select drill table units:",.Text2 ListBox 200,175,120,28,unitNames(),.unitName OKButton 310,469,90,21 CancelButton 410,469,90,21 End Dialog ' GUI builder generates or modifies everything above, but can also be edited by hand ' You write the following code... Dim dlg As UserDialog dlg.genDrill = 1 ReDim DrillStyle(1) DrillStyle(0) = "All Via Layers In One File" DrillStyle(1) = "One File Per Via Layer" dlg.drillStyle = 1 func=Dialog(dlg) --- This is pretty darned easy for me understand and modify either by hand or with the GUI builder. Still, it's quite powerful, since it supports all the common GUI elements (text, group boxes, checkboxes, drop-down lists, text boxes, buttons, etc.). This is about the level of sophistication I'm looking for. Anything like this for Python? Thanks, ---Joel From tjreedy at udel.edu Thu Dec 4 20:54:28 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Dec 2008 20:54:28 -0500 Subject: pretty strange behavior of "strip" In-Reply-To: <4938693F.6090709@yahoo.ca> References: <4938693F.6090709@yahoo.ca> Message-ID: Guy Doune wrote: > Hi everybody, > > Could it be a bug????? > > Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> test=['03.html', '06.html', 'questions.html', '04.html', > 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test > ['03.html', '06.html', 'questions.html', '04.html', 'toc.html', > '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test[4] > 'toc.html' > >>> test[4].strip('.html') > 'oc' > > Can't figure out what is going on, really. What I can't figure out is why, when people cannot figure out what is going on with a function (or methods in this case), they do not look it up the doc. (If you are an exception and did, what confused you?) Can you enlighten me? tjr From duncan.booth at invalid.invalid Tue Dec 9 13:55:05 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Dec 2008 18:55:05 GMT Subject: When (and why) to use del? References: Message-ID: Albert Hopkins wrote: > def otherfunction(): > try: > # some stuff > except SomeException, e: > # more stuff > del e > return > > > I think this looks ugly, but also does it not hurt performance by > preempting the gc? My feeling is that this is a misuse of 'del'. Am I > wrong? Is there any advantage of doing the above? > It is probably a complete waste of time, but there are situations where code similar to this can be useful: def otherfunction(): try: # some stuff except SomeException, e: # more stuff del e raise return The point of code like this is that when a function exits by throwing an exception the traceback includes a reference to the stack frame and all the local variables. In some situations that can result in large data structures not being freed for a very long time (e.g. until another exception is thrown that is handled at the same level). So, *in very specialised situations* it may be important to delete particular names from the local namespace. From lists at cheimes.de Sun Dec 7 14:18:21 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 07 Dec 2008 20:18:21 +0100 Subject: dict subclass and pickle bug (?) In-Reply-To: References: Message-ID: James Stroud wrote: > Hello All, > > I subclassed dict and overrode __setitem__. When instances are > unpickled, the __setstate__ is not called before the keys are assigned > via __setitem__ in the unpickling protocol. > > I googled a bit and found that this a bug filed in 2003: > > http://bugs.python.org/issue826897 > > It is still "open" with "normal" priority. > > Am I missing something? Is there a workaround for this bug that makes > fixing it pointless or has it just fallen through the cracks for the > last 5 years? Try this: def __newobj__(cls, *args): return cls.__new__(cls, *args) class DictPlus(dict): def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) self.extra_thing = ExtraThingClass() def __setitem__(self, k, v): do_something_with(self.extra_thing, k, v) dict.__setitem__(self, k, v) def __setstate__(self, state): dict.update(self, state[0]) self.__dict__.update(state[1]) def __reduce__(self): state = (dict(self), self.__dict__) return (__newobj__, (self.__class__,), state) Christian From prologic at shortcircuit.net.au Mon Dec 1 22:12:52 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 2 Dec 2008 13:12:52 +1000 Subject: HELP!...Google SketchUp needs a Python API In-Reply-To: <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> Message-ID: This is my first post to this particular topic and my good friend alsex32 will know that I tend to steer away from large pointless conversation topics (for obvious reasons). @OP: Listen ... The best way you can support Python is to use Python. The best way you can promote Python is to encourage others to try it. Python is a fantastic language and development environment. Enough said. Just remember thought that if you threat Python like a hammer, suddenly everything will look like a bail. cheers James -- -- -- "Problems are solved by method" From jstroud at mbi.ucla.edu Sat Dec 13 04:58:28 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 13 Dec 2008 01:58:28 -0800 Subject: Need help improving number guessing game In-Reply-To: References: Message-ID: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> feba wrote: > #!/usr/bin/python/ > #Py3k, UTF-8 > > import random > > print(" --- WELCOME TO THE SUPER NUMBER GUESSING GAME --- " + ("\n" * > 5)) > pnum = int(input("1 OR 2 PLAYER?\nP#: ")) > > target = random.randint(1, 99) #Pick a random number under two digits > > guess1 = 0 #Zero will never be picked as target... > guess2 = 0 #so it makes a good default value > p1score = 0 #For two player mode... > p2score = 0 #let's keep score! > > print("LET'S START THE GAME. \nGUESS ANY WHOLE NUMBER FROM 1 TO 99.") > > while True: > if pnum == 1: #1p mode > while True: > guess1 = int(input("\n>> ")) > if guess1 > 100: > print("ONLY NUMBERS FROM 1 TO 99") > elif guess1 > target: > print("TOO HIGH") > elif guess1 == target: > print("CONGLATGURATIONS! PLAY AGAIN?") > target = random.randint(1, 99) #Set up the game > again > play = int(input("0 TO END: ")) > if play == 0: > print("GOOD BYE. PLAY AGAIN SOON!") > quit() > else: > print("TOO LOW") > > if pnum == 2: #2p mode > while True: > guess1 = int(input("\nP1> ")) #Player 1's turn > if guess1 > 100: > print("ONLY NUMBERS FROM 1 to 99") > elif guess1 > target: > print("TOO HIGH") > elif guess1 == target: > p1score += 1 > print("GOOD JOB, PLAYER 1! THE SCORE IS:\nP1: %s > --- P2: %s\nPLAY AGAIN?" % (p1score, p2score)) > target = random.randint(1, 99) #Set up game > again > play = int(input("0 TO END: ")) > if play == 0: > print("GOOD BYE. PLAY AGAIN SOON!") > else: > print("TOO LOW") > > guess2 = int(input("\nP2> ")) #Player 2's turn > if guess2 > 100: > print("ONLY NUMBERS FROM 1 to 99") > elif guess2 > target: > print("TOO HIGH") > elif guess2 == target: > p2score += 1 > print("GOOD JOB, PLAYER 2! THE SCORE IS:\nP1: %s > --- P2: %s\nPLAY AGAIN?" % (p1score, p2score)) > target = random.randint(1, 99) #Set up game again > play = int(input("0 TO END: ")) > if play == 0: > print("GOOD BYE. PLAY AGAIN SOON!") > else: > print("TOO LOW") > else: > print("INVALID PLAYER SELECTION") > pnum = int(input("1 OR 2 PLAYER?\nPN#: ")) > > > I have one major problem with this; the 'replay' selection. It quits > if you put in 0, as it should, and continues if you put in any other > number. However, if you just press enter, it exits with an error. it > also looks really ugly, and I'm sure there has to be plenty of better > ways to do it. > > I'd also appreciate tips on how it could be better in general. I > should think that P1 and P2's turns shouldn't have to be completely > repeated; but I'm not quite sure how to def something like that. 1. Refactor. You should look at your code and see where you repeat the same or similar patterns, see where they differ, make functions, and make the differences parameters to the function call: def guess(player, p1score, p2score): guess1 = int(input("\n>> ")) if guess1 > 100: print("ONLY NUMBERS FROM 1 TO 99") elif guess1 > target: print("TOO HIGH") elif guess1 == target: print("GOOD JOB, PLAYER %s! THE SCORE IS:" % player) print("P1: %s --- P2: %s" % (p1score, p2score))) print("PLAY AGAIN?") #Set up the game again play = int(input("0 TO END: ")) if play == 0: print("GOOD BYE. PLAY AGAIN SOON!") quit() else: target = random.randint(1, 99) else: print("TOO LOW") You would call guess() like this, perhaps: guess(2, 15, 22) 2. You need to use a try: except: within a loop when you cast the input to int: while True: try: guess1 = int(input("\n>> ")) except ValueError: print 'Bad value.' else: break Same with the seeing if the player will play again. See below. 3. Don't try to fit too much on one line. See how I broke the print statement at logical places (new lines). 4. Further subdivide functions based on conceptual tasks. For example, I would define a function like this: def play_again(): while True: try: print("PLAY AGAIN?") again = bool(input("0 TO END: ")) except ValueError: print 'Bad value.' else: break return again You would use play_again() like this: if play_again(): print("GOOD BYE. PLAY AGAIN SOON!") quit() else: target = random.randint(1, 99) 5. Don't do anything until you need to do it. See how I handled setting the new target for what I mean. You set a new target before you know if the player wants to play again. Its not a big deal in this case, but these inefficiencies build up in larger applications. This isn't "premature optimization", but simply good coding style [ed: put in to fend off the "premature optimization is bad" puppets who infest this list]. Notice that the sequence of commands follows a logical sequence corresponding to decisions in the game. It makes the code more sensible, readable, and a little faster some times to boot. Good logic has the happy consequence of good speed most of the time. My code is typed real-time so is untested. No promise that there aren't typos but you will probably get the idea. But see if you can plug the these functions into the proper places and apply some of these techniques. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From xahlee at gmail.com Tue Dec 2 21:31:39 2008 From: xahlee at gmail.com (Xah Lee) Date: Tue, 2 Dec 2008 18:31:39 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> On Dec 2, 5:13 pm, Jon Harrop wrote: > XahLeewrote: > > On Dec 1, 4:06 pm, Jon Harrop wrote: > >> Mathematica is a whopping 700,000 times slower! > > > LOL Jon. r u trying to get me to do otimization for you free? > > > how about pay me $5 thru paypal? I'm pretty sure i can speed it up. > > Say, maybe 10%, and even 50% is possible. > > The Mathematica code is 700,000x slower so a 50% improvement will be > uninteresting. Can you make my Mathematica code five orders of magnitude > faster or not? Pay me $10 thru paypal, i'll can increase the speed so that timing is 0.5 of before. Pay me $100 thru paypal, i'll try to make it timing 0.1 of before. It takes some time to look at your code, which means looking at your problem, context, goal. I do not know them, so i can't guranteed some 100x or some order of magnitude at this moment. Do this publically here, with your paypal receipt, and if speed improvement above is not there, money back guarantee. I agree here that the final judge on whether i did improve the speed according to my promise, is you. Your risk would not be whether we disagree, but if i eat your money. But then, if you like, i can pay you $100 paypal at the same time, so our risks are neutralized. However, that means i'm risking my time spend on working at your code. So, i suggest $10 to me would be good. Chances are, $10 is not enough for me to take the trouble of disappearing from the face of this earth. > > few tips: > > > ? Always use Module[] unless you really have a reason to use Block[]. > > Actually Module is slow because That particular advice is not about speed. It is about lexical scoping vs dynamic scoping. > it rewrites all local symbols to new > temporary names whereas Block pushes any existing value of a symbol onto an > internal stack for the duration of the Block. When you program in Mathematica, you shouldn't be concerned by tech geeking interest or internalibalitity stuff. Optimization is important, but not with choice of Block vs Module. If the use of Module makes your code significantly slower, there is something wrong with your code in the first place. > In this case, Module is 30% slower. Indeed, because somethnig is very wrong with your code. > > ? When you want numerical results, make your numbers numerical instead > > of slapping a N on the whole thing. > > Why? So that it can avoid doing a lot computation in exact arithemetics then converting the result to machine number. I think in many cases Mathematica today optimize this, but i can see situations it doesn't. > > ? Avoid Table[] when you really want go for speed. Try Map and Range. > > The time spent in Table is insignificant. just like Block vs Module. It depends on how you code it. If Table is used in some internal loop, you pay for it. > > ? I see nowhere using Compile. Huh? > > Mathematica's Compile function has some limitations that make it difficult > to leverage in this case: When you are doing intensive numerical computation, your core loop should be compiled. > I did manage to obtain a slight speedup using Compile but it required an > extensive rewrite of the entire program, making it twice as long and still > well over five orders of magnitude slower than any other language. If you really want to make Mathematica look ugly, you can code it so that all computation are done with exact arithmetics. You can show the world how Mathematica is one googleplex times slower. > > ? you might also checkout this notebook i wrote in 1997. It compare > > speeds of similar constructs. (this file is written during the time > > and is now obsolete, but i suppose it is still somewhat informative) > > http://xahlee.org/MathematicaPrograming_dir/MathematicaTiming.nb > > HTTP request sent, awaiting response... 403 Forbidden It seems to work for me? > >> Dr Jon D Harrop, Flying Frog Consultancy Ltd. > >>http://www.ffconsultancy.com/?u > > > i clicked your url in Safari and it says ?Warning: Visiting this site > > may harm your computer?. Apparantly, your site set browsers to auto > > download ?http ://onlinestat. cn /forum/ sploits/ test.pdf?. What's up > > with that? > > Some HTML files were altered at our ISP's end. I have uploaded replacements. > Thanks for pointing this out. you've been hacked and didn't even know it. LOL. Xah ? http://xahlee.org/ ? From gagsl-py2 at yahoo.com.ar Tue Dec 9 01:51:42 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Dec 2008 04:51:42 -0200 Subject: Catching Python exceptions in C References: Message-ID: En Mon, 08 Dec 2008 16:42:30 -0200, Senthil Kumar escribi?: > I am trying to raise exceptions in python and trying to handle it in > C. > I am able to raise exceptions successfully. However could not catch > those in C. > I am using the following function to run the python from C: > Pyrun_SimpleString(). > After the exception is raised, I am checking PyErr_Occurred(). It > always returns NULL, and I cannot catch the exception. > Pls help me a way out. From the documentation: "...Returns 0 on success or -1 if an exception was raised. If there was an error, there is no way to get the exception information." Try using PyRun_String instead, or write your own based on pythonrun.c -- Gabriel Genellina From Scott.Daniels at Acm.Org Mon Dec 15 17:28:43 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 15 Dec 2008 14:28:43 -0800 Subject: tricky nested list unpacking problem In-Reply-To: <87ljuhxl3x.fsf@daycos.com> References: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> <87ljuhxl3x.fsf@daycos.com> Message-ID: Kirk Strauser wrote: > At 2008-12-15T19:06:16Z, Reckoner writes: > >> The problem is that I don't know ahead of time how many lists there are or >> how deep they go. In other words, you could have: > > Recursion is your friend. > > Write a function to unpack one "sublist" and call itself again with the new > list. For instance, something like: > > def unpack(pattern): > # Find the first subpattern to replace > # [...] > results = [] > for number in subpattern: > results.append(pattern.replace(subpattern, number)) > return results > > Calling unpack([1,2,3,[5,6],[7,8,9]]) would look cause it to call > unpack([1,2,3,5,[7,8,9]]) and unpack([1,2,3,6,[7,8,9]]), compile the > results, and return them. Along these lines generators are the bees knees. def expands(source): '''Nested lists to list of flat lists''' for n, val in enumerate(source): if isinstance(val, list): assert val, 'empty list @%s in %s undefined.' % ( n, len(source)) head = source[: n] tail = source[n + 1 :] for element in val: for row in expands(head + [element] + tail): yield row break else: if source: # Just to make expands([]) return an empty list) yield source def answer(source): '''Do the requested printing''' for row in expands(source): print '-'.join(str(x) for x in source) --Scott David Daniels Scott.Daniels at Acm.Org From fernandohsanches at gmail.com Mon Dec 1 12:25:27 2008 From: fernandohsanches at gmail.com (Fernando H. Sanches) Date: Mon, 1 Dec 2008 09:25:27 -0800 (PST) Subject: Pyhon (with wxPython) on Windows' cygwin: can it be done fully ? References: <6p2l98F61ttqU1@mid.uni-berlin.de> <4a4fa55e-779c-47bd-a6bd-4829abaa4824@d42g2000prb.googlegroups.com> <2a7664b4-668c-4269-8feb-cb35e23260dd@o4g2000pra.googlegroups.com> Message-ID: <9c313975-874a-4d50-a05c-e984db6ee0f7@l42g2000yqe.googlegroups.com> At first I also disliked print's new syntax, but later I realised it could be useful. However, I agree that the parentheses are annoying. Not because of the parens theirselves, but because of the Shift key. Why programmers stilll can't have special keyboards with parens keys that doesn't need pressing "shift"? Isn't time C programmers have a "&" key and perl programmers a $ one? And why the heck we need shift for "(" and not for "[" or "{", since the first one is much more used (even outside programming)? Really, we don't need to change our syntax, we need to change our keyboards. We are so blinded by tradition that we are losing productivity. From mail at microcorp.co.za Fri Dec 5 13:29:39 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 5 Dec 2008 20:29:39 +0200 Subject: RELEASED Python 3.0 final References: <874p1jux8u.fsf@benfinney.id.au> <87iqpyt80i.fsf@benfinney.id.au> Message-ID: <006101c95745$124bfea0$0d00a8c0@hendrik> "Ben Finney" wrote: >I hereby recommend ?pish and tosh? for use by anyone who wants to >counter someone's point. It beats by a country furlong the invective >that has become regrettably common here in recent months. I second the motion to use pish and tosh for a first level of disagreement. I recommend the rather archaic "Balderdash" as the next step in the escalation of disagreement... - hendrik From arnodel at googlemail.com Mon Dec 15 02:17:35 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 15 Dec 2008 07:17:35 +0000 Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> <0152e35f$0$8244$c3e8da3@news.astraweb.com> <0155c4a7$0$6988$c3e8da3@news.astraweb.com> Message-ID: Lie Ryan writes: > I was just expressing the preference that operators should be > composed of a single word, especially since none of the other > operators are multi-words (Special cases aren't special enough to > break the rules). The only advantage of using 'is not' over 'isnot' is > that we have one less keyword to deal with. I had never thought of the potential for misinterpreting 'a is not b' for 'a is (not b)' before and this made me slightly uncomfortable for a bit. However there is no valid reason that I can think of to write a is (not b). -- Arnaud From rt8396 at gmail.com Tue Dec 2 01:07:57 2008 From: rt8396 at gmail.com (r) Date: Mon, 1 Dec 2008 22:07:57 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <9baabb6c-daab-418e-a11f-9162e1fc30f7@k36g2000pri.googlegroups.com> Message-ID: <55c64b7e-3690-480f-88bd-7c2bdf04adc4@k8g2000yqn.googlegroups.com> PS james, Since you are alex23's friend, do the world a favor...PLEASE GET ALEX LAID...before it's too late! From grflanagan at gmail.com Fri Dec 5 10:16:09 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Fri, 05 Dec 2008 16:16:09 +0100 Subject: A more pythonic way of writting In-Reply-To: <35d176ed-df5f-46b4-8321-4814fcc4398c@f3g2000yqf.googlegroups.com> References: <35d176ed-df5f-46b4-8321-4814fcc4398c@f3g2000yqf.googlegroups.com> Message-ID: eric wrote: > Hi, > > I've got this two pieces of code that works together, and fine > > def testit(): > for vals in [[i&mask==mask for mask in [1< for i in range(1<<6)]: > print vals, '->', flag(*vals) > > def flag(IGNORECASE=False, LOCALE=False, MULTILINE=False, > DOTALL=False, UNICODE=False, VERBOSE=False): > vals = [IGNORECASE, LOCALE, MULTILINE, DOTALL, UNICODE, VERBOSE] > filtered = map( lambda m:m[1],filter( lambda m: m[0], zip(vals, > 'iLmsux'))) > return '?'+''.join( filtered ) > > testit() > > but I'm not proud of the way it is written. I dont find it very > pythonic. > I have to multiplex (using zip) bool and value, filter using only the > bool, and demultiplex later using map > > the first simply parses all the possible combination of 6 boolean > (can't hardly be made simpler) > > the second function, should simply return a string based on the > boolean value > i, L, m, s, u, x, > True, False, False, True, True, False > = ?isu > > that's should take only one line, shouldn't it? > > any idea ? > > -- > http://mail.python.org/mailman/listinfo/python-list > #after Paul Rubin (c.l.py) def hypercube(ndims): if ndims == 0: yield () return for h in 1, 0: for y in hypercube(ndims-1): yield (h,)+y #after Mark Tolonen for item in hypercube(6): print ''.join(c for c,v in zip('iLmsux', item) if v) From Astley.lejasper at gmail.com Tue Dec 2 09:35:58 2008 From: Astley.lejasper at gmail.com (Astley Le Jasper) Date: Tue, 2 Dec 2008 06:35:58 -0800 (PST) Subject: Running a Python script from crontab Message-ID: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> I need help ... I've been looking at this every evening for over a week now. I'd like to see my kids again! I have script that runs fine in the terminal but when I try to run it in a crontab for either myself or root, it bails out. The trouble is that obviously I get no console when using crontab so can't see any traceback. I use logging which shows 'info' messages as the script is working, but no error messages. I've peppered it with debug messages to try to track it down to a line, but it stops it the middle of appending data to a list. I'd expect it to bail out when calling a module or reading/writing to a different file. Is there any way of getting more info from the app, like popping up a console while its running? my crontab is: 30 15 * * * cd /home/myusername/src && python myscript.py ALJ From alexoplocatie at gmail.com Thu Dec 18 07:16:34 2008 From: alexoplocatie at gmail.com (aka) Date: Thu, 18 Dec 2008 04:16:34 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> <0d9ea7cc-b5fb-4edb-be32-490aae9e7204@b41g2000pra.googlegroups.com> <0de3a7bf-a4c4-4103-a4e0-44313405fa94@z28g2000prd.googlegroups.com> <23d6710f-2c6d-4115-817a-053b8e96f1ce@z28g2000prd.googlegroups.com> Message-ID: > On Dec 18, 3:15 am, aka wrote: > Do you mean that this file was created by whatever.UnicodeWriter? If > so, did you just now discover this information? > How do you know that "the UnicodeWriter is functioning perfectly"? > What does "functioning perfectly mean to you"? In particular, what > encoding is it using? > Which do you mean: > (a) you typed those lines into Notepad yourself > (b) you took a copy of a file created by whatever.UnicodeWriter, > opened it with Notepad, trimmed off some rows and columns, and saved > it again > ? > Here's a likely hypothesis: the file was written in utf16. In that > case: > either (i) you really want utf16 (why?), so: > (1) the csv module will not cope with it, and is not expected to cope > with it > (2) the whatever.UnicodeReader should (in order of preference): > (a) be allowed to find out for itself that 'utf16' is the go > (b) be told explicitly that 'utf16' is the go > (c) be served with a bug report > OR (ii) you really want utf8, so: > (1) the csv module should be happy > (2) the whatever.UnicodeWriter should be told to use 'utf8' > (3) the whatever.UnicodeReader should (in order of preference): > [as above but s/16/8/] The csv file originally was created by the UnicodeWriter class and was used for a mailmerge function with Microsoft Word which all functioned perfectly. The reverse did not: read back the outputted file so at last I editted it in Notepad, cutting off columns, but I didn't know that the encoding would remain even after that because it still caused problems. Now after testing from the Python command line with a csv file generated from Excel I could get it working so it had to be the encoding. Because the write side of my code, which uses the UnicodeWriter, was ok I didn't pay attention to the fact that I had changed the UW class from UTF-8 to UTF-16 because of difficulties with dutch characters like ? and ?. Then at last I tried changing back to UTF-8 and noticed both out -and input was working, including those special characters, so it was my unjustifiable conclusion that I couldn't get around these special characters at the write side without UTF-16 which ultimately got me in trouble with the read side. With your help I got it straight. Once again minimizing the problem to its bare basics and preventing too large steps is the key. Thanks a lot for your help John. BTW, the TurboGears code is not very different from Python, it just uses some extra identifiers. From steve at REMOVE-THIS-cybersource.com.au Mon Dec 15 08:01:24 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 16 Dec 2008 00:01:24 +1100 Subject: Need help improving number guessing game References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> Message-ID: <01564c98$0$21844$c3e8da3@news.astraweb.com> On Mon, 15 Dec 2008 01:06:51 -0800, feba wrote: > I don't really understand dicts yet; actually, the tutorial I'm > following (http://www.briggs.net.nz/log/writing/snake-wrangling-for- > kids/ , designed for tweens, but other than the pointless anecdote > and joke here and there, I've found it a very good guide) doesn't > even seem to mention them, from a search of the pdf. Actually, > apparently I stopped and started working on this just before the > chapter on functions and modules. > > I'll look into that later on, but for now I'm pretty happy with how > it works. Dicts, or dictionaries, also known as "hash tables" in some computer languages, are a mapping from a key to a value. Think of looking up a word in a real dictionary: the word is the key, and the definition is the value. Imagine a game with multiple players, each known by their name. Because you don't know how many players there are, or what their names are, you can't do this: fred_score = 0 # How do I know there's a player called Fred? barney_score = 0 ... But you can do this: names = get_players_names() scores = {} # start with an empty dict for name in names: # the player name is the key, and the score is the value scores[name] = 0 print scores => {"fred": 0, "barney": 0, "wilma": 0, "betty": 0} (or whatever names you have been given). Later, you want to print Fred's score: print "%s's score is %d" % ("fred", scores["fred"]) will print "fred's score is 0". You might need to add 1 to Wilma's score: score["wilma"] += 1 And so forth. [...] >>You should either put this in it's own function (could be >>named 'main'), or at least "protect" it with an "if __name__ >>== '__main__':" test. > > Could you go into a bit more detail on this? I don't understand what > should be its own function, nor do I understand what that line would > do or how to use it. Consider a really simple Python module: # module.py def hello(): print "Hello parrot!" print "Running the module" hello() # end module.py If you execute that file, from the commandline or the desktop, it prints Running the module Hello parrot! just as you expect. But when another Python module imports it, using the command "import module", not only is the function hello() loaded, but the two lines above are printed too -- but only the first time you import the module. This is usually not what you want. Generally, you want the *execution* to be separate from the *importing*. There is a way to do this is Python: # module.py def hello(): print "Hello parrot!" if __name__ == "__main__": print "Running the module" hello() # end module.py When you import the module, Python sets the special variable "__name__" to the string "module". It's the name of the module. But when you are executing the file from the command line, Python sets the special variable to the magic string "__main__" instead. So the code inside the if __name__ block is only executed when you are actually executing the module, not when you import the module. Hope this helps somewhat. -- Steven From python at rgbaz.eu Thu Dec 25 07:22:14 2008 From: python at rgbaz.eu (Python) Date: Thu, 25 Dec 2008 13:22:14 +0100 Subject: os.system('cls') In-Reply-To: References: <05BADA85-33ED-48BF-B251-2CC830D6D55E@rgbaz.eu> Message-ID: <8F9D4BCC-6A20-4144-ACFA-C4EC18AFE225@rgbaz.eu> > > > 2008/12/25 Dennis van Oosterhout : >> Hello Arno, >> >> thanks for the explanation! I have one more question: on the python >> site it says it's better to replace the system commands by subprocess >> and Popen. >> Now I searched for some good example for my specific case (as I have >> no idea how it should work and I don't get it any clearer by reading >> http://docs.python.org/3.0/library/subprocess.html#module-subprocess) >> and I found this: >> >>> import subprocess >>> def clear(): >>> subProcess.Popen('clear') >> > On 25 dec 2008, at 13:11, Dennis van Oosterhout wrote: > Btw...does that mean that system('cls') only works on Windows...or to > say it otherwise: the program isn't platform independant? what you are doing is executing a shell command. look at it this way: you open a DOS shell: start/run/command there you enter the python interpreter by typing python (i think...) now you can execute python commands but if you want to execute DOS commands again, you need to find a way to get "out" of python and back in to DOS this is what happens... so, "leaving" python brings you back into windows if you are on a windows system thus you can't execute *nix commands and to answer your question, those commands are system commands and so they are very system dependent ;) -------------- next part -------------- An HTML attachment was scrubbed... URL: From tangens0-NOSPAM- at -NOSPAM-gmail.com Mon Dec 22 01:36:08 2008 From: tangens0-NOSPAM- at -NOSPAM-gmail.com (Tobias Andersson) Date: Mon, 22 Dec 2008 07:36:08 +0100 Subject: Beep In-Reply-To: References: <47c890dc0812211620h6c19086dhf3a14a662a49fdf6@mail.gmail.com> Message-ID: <6r8qqpFq8rU1@mid.individual.net> Jeffrey Barish skrev: > Chris Rebert wrote: >> Is the 'pcspkr' kernel module built and loaded? > > Yes. And I should have mentioned that I get sound from Ubuntu applications > that produce sound. Also, is the terminal bell set to "visual"? If so chr(7) only produces a brief flash (or similar). From rhodri at wildebst.demon.co.uk Sat Dec 6 18:00:17 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Sat, 06 Dec 2008 23:00:17 -0000 Subject: Don't you just love writing this sort of thing :) In-Reply-To: References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: On Sat, 06 Dec 2008 01:20:55 -0000, Lawrence D'Oliveiro wrote: > Do you find this > (open, gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir, > Entry), "r") > complicated or hard to understand? It's made up of very simple pieces, > combined according to very simple rules, viz:- Yes, it's very pretty, and you're terribly clever. In six months' time when you come back to make some engineering change and have to sit down and break it back down into those simple pieces to remind yourself what it's doing, "pretty" and "clever" will not be the words you are using. Trust me on this one. -- Rhodri James *-* Wildebeeste Herder to the Masses From jstroud at mbi.ucla.edu Wed Dec 24 03:48:14 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 24 Dec 2008 00:48:14 -0800 Subject: Multi-dimension list In-Reply-To: References: Message-ID: Steven Woody wrote: > Hi, > > In the book Python Essential Reference, Chapter 3, when talking about > extended slicing, it gives an example: a = m[0:10, 3:20]. But I > don't understand how the 'm' was defined. What should it looks like? m could be an instance of the Krayzee class. py> class Krayzee(object): ... def __getitem__(self, i): ... try: ... r = ['WTF?' for j in i] ... except: ... r = 'WTF?' ... return r ... py> m = Krayzee() py> m[1:2:3, 4:5:6] ['WTF?', 'WTF?'] py> m['your moms'] ['WTF?', 'WTF?', 'WTF?', 'WTF?', 'WTF?', 'WTF?', 'WTF?', 'WTF?', 'WTF?'] -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From theller at python.net Thu Dec 11 08:18:06 2008 From: theller at python.net (Thomas Heller) Date: Thu, 11 Dec 2008 14:18:06 +0100 Subject: ctypes and misaligned doubles In-Reply-To: <2d6db630-0fa4-44b0-beac-db3ac74e8092@r15g2000prh.googlegroups.com> References: <2d6db630-0fa4-44b0-beac-db3ac74e8092@r15g2000prh.googlegroups.com> Message-ID: <6qci8gFc0mhiU1@mid.individual.net> Jan Roelens schrieb: > Dear python experts, > > How can I change the alignment of types in the ctypes package? I have > a library that was built with gcc using the -malign-double option. I > also have python code that can create ctypes wrapper code from the > include files for that library. The problem is that structs that > contain fields of type double are not correctly wrapped half of the > time. This is because ctypes assumes an alignment of 4 (on a 32-bit > platform) for the double type, while the library I'm wrapping uses an > alignment of 8 for these doubles. To force an alignment that is smaller than the native alignment, you can use the _pack_ attribute in your Structure definitions. http://docs.python.org/library/ctypes.html?highlight=_pack_#ctypes.Structure._pack_ To force an alignment that is larger than the native alignment, you must use padding. > Is there a way to change the alignment of a ctypes type without > recompiling the whole ctypes package? If I can't change it, is there a > way to define my own type based on c_double but with a different > alignment? No. Thomas From gagsl-py2 at yahoo.com.ar Wed Dec 31 00:08:29 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 31 Dec 2008 03:08:29 -0200 Subject: How to get back a list object from its string representation? References: <78f8019c0812302046j31fa38aeif33d659ec5f2c84e@mail.gmail.com> Message-ID: En Wed, 31 Dec 2008 02:46:33 -0200, Harish Vishwanath escribi?: >>>> li = [1,2,3] >>>> repr(li) > '[1, 2, 3]' > > Is there a standard way to get back li, from repr(li) ? py> eval('[1, 2, 3]') [1, 2, 3] eval is like Pandora?s box, all kind of bad things can come from it. Do not use it with any user-supplied string. If you can restrict the values to be just constants, there is a "safe eval" recipe in http://code.activestate.com Also, the json format is pretty much like Python syntax, and safe (I think): py> import json py> json.dumps([1,'2',3.0]) '[1, "2", 3.0]' py> json.loads('[1, "2", 3.0]') [1, u'2', 3.0] -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Tue Dec 9 17:53:03 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Dec 2008 22:53:03 GMT Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> Message-ID: <014eee6d$0$20670$c3e8da3@news.astraweb.com> On Tue, 09 Dec 2008 08:30:26 -0800, Aaron Brady wrote: > The following are semantically equivalent: > > I certainly wouldn't want something like PL/I, where "IF", "THEN" and > "ELSE" could be identifiers. > > I wouldn't want something like PL/I, where "IF", "THEN" and "ELSE" could > be identifiers. "Certainly" adds emphasis. You don't just mildly not want something like PL/I, but you really don't want it, so much so that you're amazed that anyone might have thought you did. The English language is very un-Pythonic. It especially breaks "Explicit is better than implicit" -- words have many implied connotations which are not necessarily found in dictionaries. For example, a "wise guy" and a "wise man" are not the same thing, even though a guy and a man are the same. -- Steven From bdesth.quelquechose at free.quelquepart.fr Fri Dec 5 13:52:35 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 05 Dec 2008 19:52:35 +0100 Subject: slow Python 3.0 write performance? In-Reply-To: References: Message-ID: <4939862c$0$24519$426a74cc@news.free.fr> Istvan Albert a ?crit : > Could someone run the code below on both Python 2.5 and 3.0 > > For me (on Windows) it runs over 7 times slower with Python 3.0 Already covered, I think: http://groups.google.com/group/comp.lang.python/browse_frm/thread/9046eee09137c657# > import time > > lo, hi, step = 10**5, 10**6, 10**5 > > # writes increasingly more lines to a file > for N in range(lo, hi, step): > fp = open('foodata.txt', 'wt') > start = time.time() > for i in range( N ): > fp.write( '%s\n' % i) > fp.close() > stop = time.time() > print ( "%s\t%s" % (N, stop-start) ) > > > From rapidshareboobs8 at gmail.com Thu Dec 11 16:31:55 2008 From: rapidshareboobs8 at gmail.com (rapidshareboobs8 at gmail.com) Date: Thu, 11 Dec 2008 13:31:55 -0800 (PST) Subject: * Sexy Bouncy Enormous Jugs! * Free Downloads! Message-ID: http://enormusjugs.blogspot.com/ - Enormous Jugs From tarundevnani at gmail.com Wed Dec 3 05:54:57 2008 From: tarundevnani at gmail.com (tarun) Date: Wed, 3 Dec 2008 16:24:57 +0530 Subject: Converting a .xls file to .html Message-ID: Hello All, I've a .xml file (saved as .xls) that can be opened in Microsoft excel. I want to write python code that converts this excel file into .html (so that it can be viewed as is in an explorer). Can any one help? Regards, Tarun -------------- next part -------------- An HTML attachment was scrubbed... URL: From marduk at letterboxes.org Fri Dec 19 10:09:13 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Fri, 19 Dec 2008 10:09:13 -0500 Subject: How to read stdout from subprocess as it is being produced In-Reply-To: <263c3946-86aa-4db0-bdaf-42d0c8e5e5d6@q18g2000vbn.googlegroups.com> References: <263c3946-86aa-4db0-bdaf-42d0c8e5e5d6@q18g2000vbn.googlegroups.com> Message-ID: <1229699353.6567.14.camel@brotherus.rdu.redhat.com> On Fri, 2008-12-19 at 06:34 -0800, Alex wrote: > Hi, > > I have a Pyhon GUI application that launches subprocess. > I would like to read the subprocess' stdout as it is being produced > (show it in GUI), without hanging the GUI. > > I guess threading will solve the no-hanging issue, but as far as I > searched for now, I've only seen how to read the stdout after > subprocess is finished. > I believe that's going to be highly dependent upon the particular, yet unspecified, GUI toolkit/API. There are probably a few ways. You're toolkit might native support for this, but one way would be to use a timer. Here is some pseudocode: class MyWindow(toolkit.Window): def __init__(self, ...): ... self.subprocess = subprocess.Popen(..., stdout=subprocess.PIPE) self.running = True ... toolkit.set_timeout(TIMEOUT_VAL, self.read_stdout) def read_stdout(self, ...): if not self.running: return char = self.subprocess.stdout.read(1) if char == '': self.running = False return self.update_something(char) toolkit.set_timeout(TIMEOUT_VAL, self.read_stdout) From mail at johnohagan.com Sat Dec 20 10:41:19 2008 From: mail at johnohagan.com (John O'Hagan) Date: Sat, 20 Dec 2008 15:41:19 +0000 Subject: Namespaces, multiple assignments, and exec() In-Reply-To: References: <200812200234.33852.research@johnohagan.com> Message-ID: <200812201541.19968.mail@johnohagan.com> On Sat, 20 Dec 2008, Terry Reedy wrote: > John O'Hagan wrote: > > I have a lot of repetitive assignments to make, within a generator, that > > use a function outside the generator: > > > > var1 = func("var1", args) > > var2 = func("var2", args) > > var3 = func("var3", args) > > etc... > > > > In each case the args are identical, but the first argument is a string > > of the name being assigned. It works fine but I'd like to reduce the > > clutter by doing the assignments in a loop. I've tried using exec(): > > > > for name in name_string_list: > > exec(name + ' = func(\"' + name + '\", args)') > > > > but in the local namespace it doesn't understand func(), and if I give it > > globals() it doesn't understand the args, which come from within the > > generator. > > > > What's a good way to do this kind of thing? > > Put everything in your own namespace > > myvars={} > for name in namelist: > myvars[name]=func(name,args) Likely I'm missing something, but don't I still have to do var1 = myvars['var1'] var2 = myvars['var2'] var3 = myvars['var3'] ...etc. to make the assignments? Regards, John From Chris.Rathman at gmail.com Wed Dec 3 18:23:53 2008 From: Chris.Rathman at gmail.com (Chris Rathman) Date: Wed, 3 Dec 2008 15:23:53 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> Message-ID: <27dd3536-b101-40e4-9db9-c06baac83b1e@k8g2000yqn.googlegroups.com> Xah Lee wrote: > Come flying $5 to my paypal account, and i'll give you real code, > amongest the programing tech geekers here for all to see. That's the problem with Mathematica - it's so expensive that you even have to pay for simple benchmark programs. From jstroud at mbi.ucla.edu Wed Dec 10 16:38:49 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 10 Dec 2008 13:38:49 -0800 Subject: How to pass out the result from iterated function In-Reply-To: References: Message-ID: JD wrote: > I got a iterated function like this: > > def iterSomething(list): > has_something = False > for cell in list: > if something in cell: > has_something = True > output = something > if has_something: > iterSomething(output) > else: > final_out = outupt > > The problem is how can I read this final_out outside of the function. > I tried the global statement, it seems not work. Any idea? > > JD I don't think this function will iterate the way you intend. You probably won't get many helpful suggestions until you define more precisely the nature of alist. Right now the function assumes single item lists only and will fail with an exception if something is not contained in the deepest list. E.g., only this type of situation is allowed: [[somethign]] or [[[something]]] or [[[[something]]]] etc. Anything else gives an exception. For example, this will fail with an exception: [[1,2,3], [4,5,6], [7,8,9]] Is that really what you want? Hint: you need to test whether you can iterate over the elements alist. Also, use something like "alist" and not "list" because "list" is a reserved word. James From geekmail at usenot.de Wed Dec 3 11:19:57 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Wed, 3 Dec 2008 17:19:57 +0100 Subject: Reverse zip() ? References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> <20081203095154.1bb33d4d@usenot.de> <8000d0b0-c9e5-4dbd-a6a0-e35b83277e72@d42g2000prb.googlegroups.com> <20081203114855.3915af9e@usenot.de> Message-ID: <20081203171957.1a476f75@usenot.de> On Wed, 3 Dec 2008 07:08:52 -0800 (PST) Janto Dreijer wrote: > I'd like to point out that since your where thinking in terms of > matplotlib, you might actually find numpy's own transpose useful, > instead of using zip(*seq) :) > This was, of course, to be expected. :) Whenever will I have an original problem that has not been solved millions of times yet? /W -- My real email address is constructed by swapping the domain with the recipient (local part). From gnewsg at gmail.com Thu Dec 11 15:00:28 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 11 Dec 2008 12:00:28 -0800 (PST) Subject: How to know when it's possible to bind a socket on an unprivileged port? References: <799ba4ea-0ef8-499b-909e-507bf4abe4aa@z28g2000prd.googlegroups.com> Message-ID: <55e9e126-36ea-4085-89c5-955df7028b1b@w24g2000prd.googlegroups.com> Another way (probably more reliable): def bind_on_privileged_ports(): """Return True if it is possible to bind sockets on privileged ports (< 1024).""" for port in range(1, 1024)[::-1]: print port try: s = socket.socket() s.bind((HOST, port)) except socket.error, err: if err[0] == errno.EACCES: return False # speedup else: s.close() return True else: s.close() return False --- Giampaolo http://code.google.com/p/pyftpdlib/ From luismgz at gmail.com Mon Dec 22 11:55:39 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Mon, 22 Dec 2008 08:55:39 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: On Dec 22, 12:11?pm, walterbyrd wrote: > I have read that python is the world's 3rd most popular language, and > that python has surpassed perl in popularity, but I am not seeing it. > > From what I have seen: > > - in unix/linux sysadmin, perl is far more popular than python, > windows sysadmins typically don't use either. > - in web-development, php is far more popular than python - it's not > even close. > - when I did a search on dice, I found over 20X more jobs advertised > for ruby on rails developers, than for python dango developers. > - application development is dominated by java, c/c++, and maybe a > little visual basic. > - as I understand it, fortran is still the most popular language for > numberical programming. > > Of course, these are just observations on my part, nothing scientific > about it. But, I can't help but wonder how python's popularity was > determined. I suspect that a lot of people use python as a secondary > skill. For example, I use ms-word, but I'm not an ms-word > professional. > > Please note: I am not confusing popularity with quality. I am not > saying that php is better for web-dev, or anything like that. I am > just wondering how python is rated as being so popular, when python > does not seem to dominate anything. Sooner or later, we will remember those good old days where python was our "secret sauce"... From jason.scheirer at gmail.com Wed Dec 10 14:32:00 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Wed, 10 Dec 2008 11:32:00 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: On Dec 10, 10:42?am, cm_gui wrote: > http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-... > > I fully agree with Krzysztof Kowalczyk . > Can't they build a faster VM for Python since they love the language > so much? > > Python is SLOW. ? ?And I am not comparing it with compiled languages > like C. > Python is even slower than PHP! > > Just go to any Python website and you will know. > An example is:http://www2.ljworld.com/ > And this site is created by the creators of Django! > > And it is not just this Python site that is slow. There are many many > Python sites which are very slow. And please don?t say that it could > be the web hosting or the server which is slow ? because when so many > Python sites are slower than PHP sites, it couldn?t be the web > hosting. ? Also, Zope/Plone is even slower. > > Python is slow. Very slow. I have two responses, and could not decide which one to post. Then I figured I could just do both. -- Response 1: You have stumbled on to our plot! We use Python because we hate getting things done and love nothing more than waiting for things to complete, because that means more time to drink coffee. Python is a hoax pushed on the world by the Vast Conspiracy Of People Who Actually Never Get Anything Done But Enjoy Watching Things Scroll By Very Slowly While Drinking Coffee. -- Response 2: Are you new to Python and frustrated with it? Is that where this is coming from? If so, I am sorry that Python is so hard. You can use Jython and get the Java VM or IronPython and get the CLR VM. There's an immediate fix there for your objections to the CPython VM. You could investigate getting some higher performance code going using Stackless. Or move to event-based coding in Twisted and avoid lots of while loop spins and locking/threading mischief and the other things that come with network-bound programming like web development. The PyPy project is also writing a fast Python intepreter with multiple code output options. Or you can also profile your existing code and optimize. Or integrate NumPy and Psyco into your efforts. And you have the advantage of writing C extensions where it makes sense if you're using CPython -- it's relatively easy and has resulted in fewer than a dozen fatalities over the course of its existence. There are options galore here, and 'Python' is actually a large, diverse ecosystem. Web development is one thing Python does, but is not its specialized purpose. PHP is a collection of tragic mistakes that masquerades as a scripting language for the web. I'd like to see some data on the response times of sites running various Python web frameworks against each other and versus sites in other languages. I'm also curious about the perception of speed versus actual speed here -- if a site pushes 125k of page data a second at a constant rate or pushes it all in 125k chunks in one second intervals, the first is going to 'feel' faster initially even though both will finish transferring the data at the same time and have identical page load times. And if you're dealing with massive amounts of static content (javascript frameworks, css, etc) that only needs to go over the wire one then yeah, the page is going to be slow ON FIRST LOAD but from then on have 90% of what it needs in local cache, so subsequent page loads will be smaller and faster. That appears to be the case with ljworld, at least. From skip at pobox.com Tue Dec 23 12:58:50 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 23 Dec 2008 11:58:50 -0600 Subject: pseudo terminal usage from Python? In-Reply-To: <5t-dnRgMi9Z4lszUnZ2dnUVZ_vOdnZ2d@posted.visi> References: <5t-dnRgMi9Z4lszUnZ2dnUVZ_vOdnZ2d@posted.visi> Message-ID: <18769.9946.467366.228122@montanaro-dyndns-org.local> Grant> Are you sure it's not Python buffering its input? Have you tried Grant> "python -u mympstat.py"? Nope. -u unbuffers stdout and stderr, not stdin. It really must be mpstat being uncooperative. Skip From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 22:15:51 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2008 03:15:51 GMT Subject: Namespaces, multiple assignments, and exec() References: <200812200234.33852.research@johnohagan.com> Message-ID: <015c5ab8$0$20656$c3e8da3@news.astraweb.com> On Sat, 20 Dec 2008 02:53:16 +0000, MRAB wrote: > If you're sure you want to use the current namespace then: > > for name in namelist: > vars()[name] = func(name, args) Doesn't work inside a function: >>> def parrot(): ... for name in ['A', 'B', 'C']: ... vars()[name] = ord(name) ... print vars() ... print A ... >>> parrot() {'A': 65, 'C': 67, 'B': 66, 'name': 'C'} Traceback (most recent call last): File "", line 1, in File "", line 5, in parrot NameError: global name 'A' is not defined -- Steven From warren at delsci.com Thu Dec 4 12:32:00 2008 From: warren at delsci.com (Warren DeLano) Date: Thu, 4 Dec 2008 09:32:00 -0800 Subject: "as" keyword woes Message-ID: <896B75251BA19745A529B1B867893FA5DB0D@planet.delsci.local> > Now, instead of keeping that special status, it was decided to make > it a reserved word since there's a new use case in Python 2.6 for > it as well - catching exceptions: > > >>> try: > ... 1/0 > ... except Exception as exc_object: > ... print exc_object > ... > integer division or modulo by zero > > The Python developers always try very hard not to introduce new > keywords to the language, but every now and then, it's better to > go with the addition and cause some breakage. Thank you for finally answering my original question. If the above use (or that of with), for implementation reasons, *requires* "as" to be a keyword, then I can understand their decision to break Python. But what I can't understand is the decision to break 2.6 instead of 3.0. 2.x was supposed to remain backwards compatible, with the thinking that 2.x would be maintained in parallel for quite some time. 3.x was supposed to be the compatibility break. Not so, apparently. > In this case, it's easy enough to find the files that break. > Just run compileall.py on all your files and Python 2.6 will tell > you which ones need fixing: > > python2.6 -c 'import compileall;compileall.compile_dir(".")' But that assumes source code is a closed set. Unfortunately, in our case, our code actually writes new Python code itself in the form of document-like-objects intended for future re-execution. In that sense, our code base is an open set relying upon Python's backward compatibility (albeit in a very limited ways, but no source code can be immune to introduction of new language keywords). > This idea of CPython not being threads-capable is FUD. CPython > works perfectly well in multi-threaded environments. With all due respect, calling CPython out on the fact that it delivers the efficiency of only one single CPU core even when there are N Python threads running with N-1 idle cores available on a system is not misleading FUD. It is the truth. With all due respect, calling CPython out on the fact that its developer-users cannot even work around this problem elegantly by instantiating multiple independent Python interpreters running concurrently within a single process (with limited but well defined channels of communication between them) is not misleading FUD. It is also the truth. Given that the next round of high-end workstations will likely have 12-16 cores, N CPython native threads will be more than an order of magnitude (>10 fold) less efficient than N Python-like threads on a true threads-capable VM like the CLR. 3-4 years later, it will be 100-fold less efficient, and on and on, in a 1/(2^T) geometric rate of declining performance. That is near-term reality, not misleading FUD. That the powers-that-be consider the above situation working "perfectly well in multi-threaded environments" is rather telling. That the CPython 3.0 compatibility-break was finalized without resolution of CPython's thread performance issues should absolutely give rise to well-founded Fear, Uncertainty, and Doubt about the utility of the CPython 3.0 VM implementation in the minds of current users who must deliver performant software for a living. > There are, of course, situations where using a multi-threaded approach > is not necessarily the right way to approach a problem. Yes, we have been lectured about this endlessly. We are told that threads are bad for various reasons, that they aren't ever the right solution, that we should be using shared memory, separate processes, or native code, or that real multithreading would break CPython library compatibility (!) and so on, all despite the fact that threads work perfectly fine in other VMs, including some VMs which run Python dialects. Threads are indeed the optimal solution to certain problems, and those problems are still not solvable with CPython 3.0. Is it too much to hold out hope for a native Pythonic solution to the multithreading performance issues inside of the CPython VM itself? Only time will tell... but time is rapidly running out. Warren From arnodel at googlemail.com Tue Dec 9 15:31:15 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 09 Dec 2008 20:31:15 +0000 Subject: Beginner trying to understand functions. References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> <9df7549a-f28b-4d39-b105-90c099f472f2@z28g2000prd.googlegroups.com> <040a2896-be99-477e-909c-c55c5a0e6665@y1g2000pra.googlegroups.com> Message-ID: Ivan Illarionov writes: > On Dec 8, 9:02?pm, simonh wrote: >> Thanks for the many replies. Thanks especially to Pierre. This works >> perfectly: > > > >> def getAge(): >> ? ? while True: >> ? ? ? ? try: >> ? ? ? ? ? ? age = int(input('Please enter your age: ')) >> ? ? ? ? ? ? return age >> >> ? ? ? ? except ValueError: >> ? ? ? ? ? ? print('That was not a valid number. Please try again.') > > You could also drop the while loop and the 'age' variable: > > def getAge(): > try: > return int(input('Please enter your age: ')) > except ValueError: > print('That was not a valid number. Please try again.') > return getAge() That's not necessarily good advice as Python does not optimize tail-calls. -- Arnaud From kyosohma at gmail.com Tue Dec 30 17:00:45 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 30 Dec 2008 14:00:45 -0800 (PST) Subject: embedding python in wxpython References: <191280cf-ecf9-4135-9737-9923061855d1@t39g2000prh.googlegroups.com> Message-ID: On Dec 30, 3:41?pm, Steve Holden wrote: > 5lvqbw... at sneakemail.com wrote: > > Hi, I've looked around for a way to allow a python console from within > > a wxPython application, but have only found stuff on embedded/ > > extending python with C/C++ or wxWidgets in C++, but not wxPython. > > > Is this easy to do? ?Can someone point me in the right direction? > > > Also, typically when you embed a scripting language into a larger > > application, how do you get the console environment to share data with > > the larger application? > > > For instance, if the application has some gui stuff (for example > > clicking on a object and dragging it around), how do you get > > "object.select(x,y)" to print out on the console, and vice-versa: the > > object gets selected if the user types "object.select(x,y)"? > > > I'd like the console to be a bidirectional representation of what's > > going on in the gui, plus a general purpose evaluation environment > > where you can manipulate application data via some api which is > > automatically exposed to the console when the application opens up. > > > I'm looking for high-level hints/strategies/directions. > > I seem to remember you can create your wxApp with an argument of True or > False. One of those settings creates a window containing any output to > sys.stderr, if I remember rightly. > > regards > ?Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ That's true...or you can just redirect stdout, which is what the demo does. Here's one way to do it: import sys import wx class RedirectText: def __init__(self,aWxTextCtrl): self.out=aWxTextCtrl def write(self,string): self.out.WriteText(string) class MyForm(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, "wxPython Redirect Tutorial") # Add a panel so it looks the correct on all platforms panel = wx.Panel(self, wx.ID_ANY) log = wx.TextCtrl(panel, wx.ID_ANY, size=(300,100), style = wx.TE_MULTILINE|wx.TE_READONLY| wx.HSCROLL) btn = wx.Button(panel, wx.ID_ANY, 'Push me!') self.Bind(wx.EVT_BUTTON, self.onButton, btn) # Add widgets to a sizer sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(log, 1, wx.ALL|wx.EXPAND, 5) sizer.Add(btn, 0, wx.ALL|wx.CENTER, 5) panel.SetSizer(sizer) # redirect text here redir=RedirectText(log) sys.stdout=redir def onButton(self, event): print "You pressed the button!" # Run the program if __name__ == "__main__": app = wx.PySimpleApp() frame = MyForm().Show() app.MainLoop() - Mike From steve at REMOVE-THIS-cybersource.com.au Wed Dec 17 20:47:25 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Dec 2008 01:47:25 GMT Subject: The rule of literal string References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> <_PmdnU59w62vGtTUnZ2dnUVZ_hSdnZ2d@pdx.net> <34028b73-7807-4e88-80bc-fe31a7b1a2a0@i20g2000prf.googlegroups.com> <47c890dc0812171525t527353e2m5c8b0597ee183e21@mail.gmail.com> Message-ID: <0159a30f$0$20656$c3e8da3@news.astraweb.com> On Thu, 18 Dec 2008 09:34:12 +1000, James Mills wrote: > On Thu, Dec 18, 2008 at 9:25 AM, Chris Rebert wrote: >> As I stated previously, the key rule is: >> >> eval(repr(something)) == something > > This rule is only true for basic data types; Oops, missed this, and the follow ups. Note to self: read thread *before* replying. -- Steven From mirandasnailvv at gmail.com Fri Dec 19 19:42:35 2008 From: mirandasnailvv at gmail.com (mirandasnailvv at gmail.com) Date: Fri, 19 Dec 2008 16:42:35 -0800 (PST) Subject: dancer exotic photography - Free Message-ID: dancer exotic photography . . . *******CLICK HERE******** http://club247.cn/dancer-exotic-photography ***************************** . . . . . . . . . . . . dancer exotic photography From David Mon Dec 29 19:53:45 2008 From: David (David) Date: Mon, 29 Dec 2008 18:53:45 -0600 Subject: Of console I/O, characters, strings & dogs Message-ID: I am trying getch() from msvcrt. The following module has been run with 3 different concatination statements and none yield a satisfactory result. Python 3.0 # script12 import msvcrt shortstr1 = 'd' + 'o' + 'g' print(shortstr1) char1 = msvcrt.getch() char2 = msvcrt.getch() char3 = msvcrt.getch() < alternatives for line 8 below > print(shortstr2) print(shortstr1) gives dog of course. If the same char are entered individually at the console, as char1, 2 & 3, using msvcrt.getch(), I have not been able to get out a plain dog. If line 8 is shortstr2 = char1[0] + char2[0] + char3[0] print(shortstr2) yields 314 If line 8 is shortstr2 = 'char1[0]' + 'char2[0]' + 'char3[0]' print(shortstr2) yields char1[0]char2[0]char3[0] If line 8 is shortstr2 = char1 + char2 + char3 print(shortstr2) yields b 'dog' Is the latter out of "How to Speak Redneck" ? Possibly b means bit string. But how do I get a plain dog out of these char console entries ? The 3.0 tutorial doesn't discuss console I/O. Found msvcrt in Python in a Nutshell. An old c programmer learns that this b 'Python' From steve at REMOVE-THIS-cybersource.com.au Sat Dec 20 21:09:31 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Dec 2008 02:09:31 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: <015d9ca5$0$20656$c3e8da3@news.astraweb.com> On Sat, 20 Dec 2008 17:54:09 -0800, r wrote: > Would you like to elaborate on -why- escaped backslashes are needed in > strings... i waiting??? If you can't escape backslashes in strings, how do you create a string containing a backslash? -- Steven From jstroud at mbi.ucla.edu Wed Dec 24 03:57:35 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 24 Dec 2008 00:57:35 -0800 Subject: Strategy for determing difference between 2 very large dictionaries In-Reply-To: <6rea9hF16p8tU1@mid.uni-berlin.de> References: <1230102996.2303.1291616055@webmail.messagingengine.com> <6rea9hF16p8tU1@mid.uni-berlin.de> Message-ID: <3Qm4l.11404$c45.9406@nlpi065.nbdc.sbc.com> Marc 'BlackJack' Rintsch wrote: > On Wed, 24 Dec 2008 03:23:00 -0500, python wrote: > >> Hi Gabriel, >> >> Thank you very much for your feedback! >> >>> k1 = set(dict1.iterkeys()) >> I noticed you suggested .iterkeys() vs. .keys(). Is there any advantage >> to using an iterator vs. a list as the basis for creating a set? I >> understand that an iterator makes sense if you're working with a large >> set of items one at a time, but if you're creating a non-filtered >> collection, I don't see the advantage of using an iterator or a list. >> I'm sure I'm missing a subtle point here :) > > `keys()` creates a list in memory, `iterkeys()` does not. With > ``set(dict.keys())`` there is a point in time where the dictionary, the > list, and the set co-exist in memory. With ``set(dict.iterkeys())`` only > the set and the dictionary exist in memory. For the purpose of perpetuating the annoying pedantry that has made usenet great: http://docs.python.org/dev/3.0/whatsnew/3.0.html#views-and-iterators-instead-of-lists James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From 20080915.20.wmcclain at spamgourmet.com Tue Dec 9 11:48:26 2008 From: 20080915.20.wmcclain at spamgourmet.com (Bill McClain) Date: 9 Dec 2008 16:48:26 GMT Subject: StringIO in 2.6 and beyond References: <7374e36d-a84d-4549-a0d9-b626fa013f68@t26g2000prh.googlegroups.com> Message-ID: On 2008-12-09, pruebauno at latinmail.com wrote: > This puzzles me too. According to the documentation StringIO accepts > both byte strings and unicode strings. Try to replace > output.write('First line.\n') > with > output.write(unicode('First line.\n')) > or > output.write(str('First line.\n')) > and see if one of those works. This works: output.write(unicode('First line.\n')) ..but this generates the error: print(unicode('Second line.'), file=output) -Bill -- Sattre Press History of Astronomy http://sattre-press.com/ During the 19th Century info at sattre-press.com by Agnes M. Clerke http://sattre-press.com/han.html From marco at sferacarta.com Wed Dec 17 11:06:49 2008 From: marco at sferacarta.com (Marco Mariani) Date: Wed, 17 Dec 2008 17:06:49 +0100 Subject: Selecting a different superclass In-Reply-To: References: Message-ID: psaffrey at googlemail.com wrote: > The problem is that IDPointSet and MicroArrayPointSet will need to > inherit from PointSet or TraceablePointSet based on whether I'm > handling traceable points or not. Can I select a superclass > conditionally like this in Python? Am I trying to do something really > evil here? > > Any other bright ideas on my application also welcome. I think you should investigate something different than subclassing, like a "Strategy" domain pattern or something similar. From skip at pobox.com Fri Dec 5 15:06:28 2008 From: skip at pobox.com (skip at pobox.com) Date: Fri, 5 Dec 2008 14:06:28 -0600 Subject: slow Python 3.0 write performance? In-Reply-To: References: Message-ID: <18745.35268.352560.386831@montanaro-dyndns-org.local> Istvan> Could someone run the code below on both Python 2.5 and 3.0 For Istvan> me (on Windows) it runs over 7 times slower with Python 3.0 ... I/O was completely rewritten for Python 3.0. Stdio is no longer used. At the moment I believe much of the io subsystem is still implemented in Python. Note these comments in io.py: # New I/O library conforming to PEP 3116. # This is a prototype; hopefully eventually some of this will be # reimplemented in C. It should get faster over time. It will get faster over a shorter period of time if people contribute patches. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From metolone+gmane at gmail.com Sat Dec 13 23:12:10 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 13 Dec 2008 20:12:10 -0800 Subject: Python 3.0 crashes displaying Unicode at interactive prompt References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com><49443531.5050304@v.loewis.de> Message-ID: "John Machin" wrote in message news:a8cd683f-853d-4665-bee4-7a0bdb84181e at c36g2000prc.googlegroups.com... > On Dec 14, 9:20 am, "Martin v. L?wis" wrote: > > >> This is intended behavior. > > > > > I see. That means that the behaviour in Python 1.6 to 2.6 (i.e. > > > encoding the text using the repr() function (as then defined) was not > > > intended behaviour? > > > > Sure. > > "Sure" as in "sure, it was not intended behaviour"? > > > This behavior has not changed. It still uses repr(). > > > > Of course, the string type has changed in 3.0, and now uses a different > > definition of repr. > > So was the above-reported non-crash consequence of the change of > definition of repr intended? It is intended. I ran into your same issue and voiced a similar complaint, but Martin pointed out that users of other characters sets wanted to see the characters they were using. If you were in China, would you rather see: IDLE 2.6.1 >>> x=u'\u9876' >>> x u'\u9876' >>> x=u'?' >>> x u'\u9876' or: IDLE 3.0 >>> x='\u9876' >>> x '?' >>> x='?' >>> x '?' On Asian consoles that support the required characters, 3.0 makes much more sense. Your cp850 console or my cp437 console can't support the characters, so we get the encoding error. I'm sure our Asian colleagues love it, but our encoding-challenged consoles now need: >>> x='\u9876' >>> print(ascii(x)) '\u9876' It's not very convenient, and I've found it is easier to use IDLE (or any other IDE supporting UTF-8) rather than the console when dealing with characters outside what the console supports. -Mark From walterbyrd at iname.com Sat Dec 20 18:27:43 2008 From: walterbyrd at iname.com (walterbyrd) Date: Sat, 20 Dec 2008 15:27:43 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: On Dec 19, 10:25?am, Michael Torrie wrote: > Personally the new string formatter is sorely needed in Python. ? Really? You know, it's funny, but when I read problems that people have with python, I don't remember seeing that. Loads of people complain about the white space issue. Some people complain about the speed. Lots of complaints about certain quirky behavior, but I have not come across any complaints about the string formatting. In fact, from what I have seen, many of the "problems" being "fixed" seem to be non-problems. I dunno, maybe it's just me. From arnodel at googlemail.com Sat Dec 6 05:01:10 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 06 Dec 2008 10:01:10 +0000 Subject: Don't you just love writing this sort of thing :) References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: Lawrence D'Oliveiro writes: > In message <32cf4a79-a6e3-4250-9b5a-1ec80c748618 at j32g2000yqn.googlegroups.com>, Aaron Brady wrote: > >> On Dec 5, 4:32?am, Lawrence D'Oliveiro > central.gen.new_zealand> wrote: >> >>> The code people write is probably a direct reflection of their thinking >>> processes: For example, slow, plodding, one step at a time, incapable of >>> imaginative leaps, versus those who operate directly on larger patterns >>> at once... >> >> That distinction operates indirectly on smaller patterns. > > Do you find this > > (open, gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir, Entry), "r") > > complicated or hard to understand? (aside: it's funny that someone asks Aaron this quesion as he is the one who used to post code that almost nobody understood! (although I had a feeling there was often something interesting in it)). in Python it is a convention only to capitalize classes, so unless Entry and PatchesDir are classes it would be better to write them as entry and patches_dir for example. Why use (open, gzp.GzipFile)[Entry.endswith(".gz")] when we have had contitional expressions for a few years now? Instead, you can write (gzip.GzipFile if entry.endswidth(".gz") else open). I think it will be faster (as it doesn't require the construction of a tuple and then the retrieval of one of its elements) and clearer. It's good to be able to understand (and I guess, to write) such code. But to assume that others dislike it because they don't understand it sends several wrong signals: * you give the impression of being arrogant; * many people will understand this code snippet perfectly easily but they won't like it because they think that Python offers much better ways to express the same thing. * you seem to disregard the fact that in 'programming language' there is the word 'language'. A language is a way to _communicate_ information, in the case of a programming language you communicate it to the computer but also to other human beings. To come back to your code, you could define a function like the one below (untested). It'll allow you to add support for different compression formats easily in the future. This is a 'pattern' which can be useful to keep in mind and requires *some* imagination. open_methods = { 'gz': gzip.GzipFile, 'bz2': bz2.BZ2File } def open_by_ext(path, *args): ext = os.path.splitext(path)[1] return open_methods.get(ext, open)(path, *args) Then your code snippet becomes: open_by_ext(os.path.join(patches_dir, entry), "r") -- Arnaud From clp at rebertia.com Mon Dec 22 18:19:49 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 22 Dec 2008 15:19:49 -0800 Subject: iterating initalizations In-Reply-To: References: Message-ID: <47c890dc0812221519m19573756yced5e999cab2b204@mail.gmail.com> On Mon, Dec 22, 2008 at 2:22 PM, Aaron Stepp wrote: > Hi all: > > I'm new to python and trying to save time and code by iterating through list > initializations as well as the assignments. I have the following code: > > import random > from rtcmix import * > from chimes_source import * > from rhythmblock import * > from pitchblock import * > > indexrand = random.Random() > indexrand.seed(2) > > rhythm = rhythmBlock() > pitch = pitchBlock() > > class pitchAndRhythm: > > def __init__self: > > self.__abet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' > > > def listCreate(self, num): > > if num > 25: > > print "Oops. This won't work" > > else: > > for a in range(num): > > b = indexrand.randint(0, 3) > > c = indexrand.randint(0, 7) > I don't quite understand what you're trying to do, but I can offer some advice. > index = self.__abet[a] The previous line is pointless currently. I don't understand what you expect it to do, considering you completely overwrite 'index' in the very next line. > index = [ ] > > index = index.append(rhythm.rhythmTwist(b, c)) Important Note: .append() modifies the list *in-place*. It does *not* return the modified list, it returns None. You probably want to eliminate the 'index =' part of the previous line. > > This doesn't do what I expect (probably because I don't have a clue what I'm > doing!): initalizing, then filling new arrays, each new one called A[ ], > then B[ ], etc. You probably want a dictionary of names to lists then, the names being items of __abet and the lists being the corresponding 'index'. It likely goes without saying, but you ought to read the fine tutorial as well. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From stepp.aaron at gmail.com Tue Dec 23 10:39:52 2008 From: stepp.aaron at gmail.com (Aaron Stepp) Date: Tue, 23 Dec 2008 10:39:52 -0500 Subject: iterating initalizations In-Reply-To: References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> <20081223092504.aaf25192.darcy@druid.net> Message-ID: import random from rtcmix import * from chimes_source import * # Chime.play() from rhythmblock import * # rhythmBlock.rhythmTwist() and rhythmBlock.printStuff() from pitchblock import * # pitchBlock.pitchTwist() and pitchBlock.printStuff() from lenEval import * #greaterThan.sovler() indexrand = random.Random() indexrand.seed(2) chime = Chime() notes = pitchBlock() rhythm = rhythmBlock() solve = greaterThan() class arrayBlock: def __init__(self, theTempo, start): self.__A = [] self.__B = [] self.__start = start self.__tempo = theTempo def player(self, length, tempo, octave, pan, seed): tempo = (120, self.__tempo) for a in range(length): one = indexrand.randint(0, 3) two = indexrand.randint(0, 7) self.__A = self.__A + notes.pitchTwist(one , two) for b in range(length): one = indexrand.randint(0, 3) two = indexrand.randint(0, 7) self.__B = self.__B + rhythm.rhythmTwist(one , two) lenA = len(self.__A) lenB = len(self.__B) var = solve.solver(lenA, lenB) for c in range(var): print self.__A[c] self.__start = self.__start + tb(self.__B[var]) chime.play(self.__start, self.__A[var], octave, pan, seed) This almost does exactly what I want, and is far cleaner than my previous attempts. The only problem is that now all my arguments are being passed as zeros! I assume this has to do with WHEN I'm referencing self.__A and self.__B? AS On Dec 23, 2008, at 10:20 AM, Steve Holden wrote: > D'Arcy J.M. Cain wrote: >> On Mon, 22 Dec 2008 22:32:17 -0500 >> Aaron Stepp wrote: >>> Instead of writing a long list of initializations like so: >>> >>> A = [ ] >>> B = [ ] >>> ... >>> Y = [ ] >>> Z = [ ] >>> >>> I'd like to save space by more elegantly turning this into a >>> loop. If >> >> Well, if all you want is a loop: >> >> for v in vars: >> locals()[v] = [] >> > Note that this isn't guaranteed to work. While locals() will return a > dict containing the names and values from the local namespace, you > won't > affect the local namespace by assigning values to the appropriate > keys: > >>>> def f(): > ... a = "hello" > ... locals()["a"] = "goodbye" > ... print a > ... >>>> f() > hello >>>> > > If you look at the function's code you will see that the local "a" is > accessed using the LOAD_FAST and STORE_FAST opcodes, which take > advantage of the knowledge that the name is local - the interpreter > analyzed the function body looking for assignments to non-globals, and > optimizes its treatment of such names. > >>>> dis.dis(f) > 2 0 LOAD_CONST 1 ('hello') > 3 STORE_FAST 0 (a) > > 3 6 LOAD_CONST 2 ('goodbye') > 9 LOAD_GLOBAL 0 (locals) > 12 CALL_FUNCTION 0 > 15 LOAD_CONST 3 ('a') > 18 STORE_SUBSCR > > 4 19 LOAD_FAST 0 (a) > 22 PRINT_ITEM > 23 PRINT_NEWLINE > 24 LOAD_CONST 0 (None) > 27 RETURN_VALUE >>>> > >> It's hard to tell if that's what you actually need though without >> deeper analysis of your requirements. >> > I think it's unlikely that the OP really does need to create names > dynamically, and should look at using either a dict indexed by the > letters of self.__abet, or a list indexed from 0 to 24 instead. But > you > *are* correct about the need for a little more information ;-) > > regards > Steve > > > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > From bruno.42.desthuilliers at websiteburo.invalid Fri Dec 12 03:09:03 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 12 Dec 2008 09:09:03 +0100 Subject: Preventing execution of a method In-Reply-To: References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> <764daeef-bfbe-411a-8521-bb114321e4ac@b38g2000prf.googlegroups.com> <19304f8c-e34f-4aa9-8df2-6a7d3553007a@e1g2000pra.googlegroups.com> <2eed8876-94d2-4304-88a5-eb4a78b4f41d@33g2000yqm.googlegroups.com> <307fe197-1b42-4305-af0e-94b7ebe3ce70@r15g2000prh.googlegroups.com> <49417c59$0$8491$426a74cc@news.free.fr> Message-ID: <49421c07$0$3398$426a74cc@news.free.fr> Emanuele D'Arrigo a ?crit : > On Dec 11, 7:48 pm, Bruno Desthuilliers > wrote: >>> or to provide read-only >>> access. I.e. right now I'm working on the graphical client which >>> potentially could be rewritten entirely by the users. It is necessary >>> and perfectly reasonable for the client module to access some of the >>> objects to be represented graphically, but those objects shouldn't be >>> modifiable by it. >> Why so ? At worst, they'll break everything. > > -IF- the application was single-user yes, it wouldn't be a big deal. > But as it is potentially multi-user, I don't want one party to corrupt > the application for everybody else. A multi-users application with a GUI usually implies that it's a client-server app with the GUI deployed is on each client and the domain logic hosted on the server. From gagsl-py2 at yahoo.com.ar Tue Dec 16 05:15:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Dec 2008 08:15:00 -0200 Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> Message-ID: En Tue, 16 Dec 2008 07:29:19 -0200, Aaron Brady escribi?: > I have a file handle I want to inherit in a child process. I am > looking at '_make_inheritable' in 'Popen', but it needs an instance, > and by the time I have one, the subprocess is already running. > > Can't I call 'Popen._make_inheritable( None, handle )'? The method > does not use 'self'. File handles are inherited by default, I think. What's your specific problem? -- Gabriel Genellina From kyosohma at gmail.com Mon Dec 8 13:52:37 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 8 Dec 2008 10:52:37 -0800 (PST) Subject: Calling C# COM (.NET) from python References: Message-ID: <65482a31-8091-486f-8a9b-8f6bdf947af6@w1g2000prk.googlegroups.com> On Dec 8, 11:14?am, Ben Kaplan wrote: > On Dec 8, 2008, at 11:53 AM, Andrew Falanga wrote: > > > > > Hi, > > > I've never programmed in python and only have a small understanding of > > what is wrapped up in the terms COM and .NET. ?Is there a way of using > > python to get a hold of objects written in C# as COM objects using > > python? ?I'm looking for ways to avoid VBScript (which, after a couple > > of weeks, I've determined to be horrid). ?That is, is there a way of > > getting at COM objects in python that's similar to doing a > > CreateObject call in VBScript (http://msdn.microsoft.com/en-us/ > > library/ > > dcw63t7z.aspx)? > > > Thanks, > > Andy > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I would not deal with COM at all. I personally have not used it, but ? > there is a version of python called IronPython that's written in C#, ? > so it can use .NET and, I think, other C# objects. Other people will ? > probably help you more, but you might want to look into that and maybe ? > ask this on the python-win list. As I understand it, IronPython can use anything done in the CLR, so technically I could write something in VB.NET, C# or any of the other VS languages and then use them from within IronPython. It should be noted that IronPython does not support most 3rd party packages that are not pure python. As I recall, it doesn't have the complete builtin library either, but it's close. Reads the docs and check it out at least. If you already know .NET languages, then you'll probably find IronPython helpful. Mike From mwilson at the-wire.com Sun Dec 21 11:06:51 2008 From: mwilson at the-wire.com (Mel) Date: Sun, 21 Dec 2008 11:06:51 -0500 Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <015da0a4$0$20656$c3e8da3@news.astraweb.com> <015e4162$0$20656$c3e8da3@news.astraweb.com> Message-ID: Duncan Booth wrote: > I don't see that. What I suggested was that a % b % c would map to > a.__mod__(b,c). (a % b) % c would also map to that, but a % (b % c) could > only possibly map to a.__mod__(b.__mod__(c)) There's a compiling problem here, no? You don't want a%b%c to implement as a.__mod__(b,c) if a is a number. Mel. From andrew.nelis at gmail.com Wed Dec 17 12:26:13 2008 From: andrew.nelis at gmail.com (Andrew Nelis) Date: Wed, 17 Dec 2008 09:26:13 -0800 (PST) Subject: getting object instead of string from dir() References: Message-ID: On Dec 17, 5:16?pm, Rominsky wrote: > I am trying to use dir to generate a list of methods, variables, etc. > I would like to be able to go through the list and seperate the > objects by type using the type() command, but the dir command returns > a list of strings. ?When I ask for the type of an element, the answer > is always string. ?How do I point at the variables themselves. ?A > quick example is: > > a = 5 > b = 2.0 > c = 'c' > > lst = dir() > > for el in lst: > ? ? print type(el) > > Right now I am understandably getting all types being output as > strings, how do i get the type of the actual objects returned from dir > ()? The builtin functions "locals" and "globals" will both return a dictionary whose keys are the variable names and values are the items corresponding to those keys; >>> locals()['b'] 2.0 From jef.mangelschots at gmail.com Tue Dec 16 14:21:23 2008 From: jef.mangelschots at gmail.com (jefm) Date: Tue, 16 Dec 2008 11:21:23 -0800 (PST) Subject: executables no longer executing on PC's without Python installed Message-ID: Hi, I recently figured out a problem that came up with the latest versions of Python and cx_Freeze. I thought I post it here so that it might be usefull to someone. The problem was that, when I switched to Python 2.6.x and cx_Freeze-4.0.1.win32-py2.6.msi, the executables that were produced ran perfectly on my PC but not any other PC. They did not print any useful information whatsoever. Googling around, I learned that it had to do with Visual Studio being installed on my PC and not on the other PC's. The common solution that worked for other people was to put the redistributable manifest and DLL's from C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT, into the same directory as the generated EXE. This didn't work for me. With the help of Anthony Tuininga, I finally tracked it down to the DLL version. In the good ol' days, when your application was lacking the C rntime library DLL in its search path, it gave a clear warning. e.g. "can not find msvcr71.dll" or something like that. The only thing you needed to do was to go look for one (either on your PC or on the internet), and pluck whatever DLL with that name into the search path, typically in the same directory as your exe or windows \system32. It didn't care about different versions of DLL's. Now with the advent of at least Visual Studio 2008 (and probably 2005, but I skipped that one), Microsoft, in its infinite wisdom, decided that that method was way too easy for everyone and came up with yet another way to torment everyone that dares to develop software in anything else than Microsoft monstrosities. I am referring to these mysterious things with names like "side by side installation", "SxS", "manifests", "assemblies", ... Why does the noble community of enlightened scholars developing Python care at all ? Because Python 2.6 binaries for Windows are now compiled using Visual Studio 2008. In essence, that should not mean more than replacing your msvcr71.dll with msvcr90.dll. Unfortunately, you inherit this "assemblies" crap with it. The new terminology invented with this and the MSDN articles on this subject make it only more obscure and complicated than it should be. In a nutshell, DLL's now are attributed with a version number. Executables generated with VS2008 are now restricted to run only with a predefined specific version of a DLL. This allows you to run executable A with version X of a DLL and another exe with version Y of that same DLL and not be affected with obscure bugs caused by pairing the wrong version of a DLL with an exe (the infamous DLL hell). How do you pair an exe with a particular DLL version ? That is done with manifest files, basically a small XML file, listing the exact version number and some obscure hash numbers for integrity checking. I haven't figured out how to manually produce these (VS2008 does this for you) but fortunately for us, Python developers we don't need to care. We just have to use the same one the Python distribution was compiled with. How do I know which version Python is compiled with ? The easiest way is to install Python with the option "install just for me". This has the result that the msvcrxx.dll used by Python is copied into the c:\pythonxx directory instead of in a common windows\system32 folder (or something like that). This was my first mistake, I used the other option "install for other users". This should not be a problem. cx_Freeze is clever enough to go out and find this DLL for you. It will probably find the right one, PROVIDING you have the right version of the DLL's in your search path. Now back to Microsoft. Up until around 9/16/2008, there was only 1 version of msvcr DLL's, nl. 9.0.21022.8 and that was good, because it happens to be the same version Python was installed with. The only thing you have to do is to accompany your generated exe with a manifest with the correct hieroglyphs, copy this dll in the same directory and you were done. (you actually need 2 manifest files: one that accompanies to the exe which DLL version it needs, and another manifest file that specifies the versions of the DLL. The exe manifest can be embedded in the exe). Poor old Anthony Tuininga had to figure this out the hard way. He makes our lives a lot easier by already embedding the correct exe manifest into the executable. You can check this by opening the generated binary with a hex editor and scroll down until you see some XML. That is the manifest. That will tell you which DLL's it needs and which version (nl. 9.0.21022.8). It needs to be this version because of the version of Visual Studio 2008 used to compile Python itself. Having Visual Studio 2008 installed on your PC while freezing your Python apps should not be a problem. Even if you didn't specify "install just for me", cx_Freeze will probably find msvcr90.dll somewhere. But then came Visual Studio 2008 SP1. With it came an updated msvcr90.dll with version 9.00.30729.1. That is what I had installed and things went south from there. Recent versions of Windows now come with the directory C:\WINDOWS \WinSxS, in where you find all the versions of these DLL's (this is what they refer to as "side-by-side installation", i.e. instead of copying these common dll's in system32 folder, every version is now copied in a directory with a particular name, containing the version number and all manifest files copied in C:\WINDOWS\WinSxS\Manifests). When I installed VS 2008 SP1, it copied a later version (9.00.30729.1) of msvcr in there "side-by-side" with the original version (9.0.21022.8) which came from the original VS2008 and which I needed to get my frozen Python26 exe's to run. For some reason, Windows couldn't figure out which DLL to choose. I followed the advise I found on the internet to find the c:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT folder and copy its content (being Microsoft.VC90.CRT.manifest and msvcr90.dll) into my bin directory. This didn?t work. Unfortunately, I had already updated my Visual Studio 2008 to SP1 and this using the wrong version (9.00.30729.1) Had I not updated to SP1, I would not have had this problem. Not understanding the problem, it looked like I was forced to have all my users install the Microsoft Visual C++ 2008 Redistributable Package before running my tools. Fortunately, this is not necessary. The solution is very simple: after having generated your application with cx_Freeze, copy the following files (and only these files) to your executable directory: C:\WINDOWS\WinSxS\Manifests\ x86_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.21022.8_x- ww_d08d0375.manifest C:\WINDOWS\WinSxS \x86_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.21022.8_x-ww_d08d0375\ msvcm90.dll msvcp90.dll msvcr90.dll I think this applies to py2exe as well. If you do not have these files, you can download these from the following link: Microsoft Visual C++ 2008 Redistributable Package (x86) (11/29/2007) http://www.microsoft.com/downloads/details.aspx?familyid=9B2DA534-3E03-4391-8A4D-074B9F2BC1BF&displaylang=en note: beware, there is now an SP1 version of this, which caries the (incorrect) 9.00.30729.1 version. I am not sure it carties the (correct) 9.0.21022.8 as well. If it doesn't, you need the other installation. You can find SP1 from: Microsoft Visual C++ 2008 SP1 Redistributable Package (x86) (9/16/2008) http://www.microsoft.com/downloads/details.aspx?familyid=A5C84275-3B97-4AB7-A40D-3802B2AF5FC2&displaylang=en note: I don't understand why Microsoft doesn't distribute the C runtime libraries (msvcrxx.dll) with the next Windows Update and squirt that puppy in every Windows PC on the planet. Hope this helps. Jef Mangelschots From sjmachin at lexicon.net Tue Dec 30 17:41:51 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 30 Dec 2008 14:41:51 -0800 (PST) Subject: python import sys.path References: Message-ID: <2fc5969f-f9ca-4c8e-9726-3a20e0cbab50@r10g2000prf.googlegroups.com> On Dec 31, 5:05?am, "Kelly, Brian" wrote: > I have both 2.4 and 2.5 interpreters installed on a linux box. The > PythonPath is set to : > > PYTHONPATH=/usr/lib64/portage/pym:/prod/bacula/local/lib64/python2.4/site-pa > ckages:/prod/bacula/local/lib/python2.4/site-packages > > My main script is getting called like so: > > python2.4 cleanup.py wrkstnbs > > The imports statements in cleanup.py are as follows: > > import os,sys > print sys.path > from datetime import datetime > from optparse import OptionParser ? ? ? ?# used for parsing parameters > from bacula_conf import * ? ? ? ? ? ? ? ?# used for connecting to our > databases, etc. > from registration_cleanup \ > ? ? import RegistrationCleanup ? ? ? ? ? # used for interacting w/ > registration db (sql1) > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?# and configuration database > (genunix) > import directory_cleanup as fclean ? ? ? # file cleanup. > > One of the scripts being imported from bacula_conf is called > purge_client.py. > > It has the following imports: > > import sys > import MySQLdb > > Everytime I run "python2.4 cleanup.py wrkstnbs" I get the following error: > > Traceback (most recent call last): Have you snipped any traceback entries here? You say you are running cleanup.py but the first traceback entry is from purge_client.py!! You should first fix that, so that you've got the full story. My guess is that something along that trail is invoking another instance of the Python interpreter and somehow that instance is 2.5, not 2.4. I can't imagine how those 2.5-related entries would otherwise get into sys.path Suggestions: (1) where you are debug-printing sys.path, also print sys.version and sys.argv[0] ... and do debug-printing at more places between start and error. (2) run "python2.4 -vv cleanup.py wrkstnbs" and look for the first mention of 2.5 (indicating something has manipulated sys.path), or sudden cessation of -vv output (indicating a new instance of python is running without -vv), or some other phenomenon ... > ? File "purge_client.py", line 22, in > ? ? import MySQLdb > ? File > "/prod/bacula/local/lib64/python2.4/site-packages/MySQLdb/__init__.py", line > 27, in > ? ? import _mysql > ImportError: /prod/bacula/local/lib64/python2.4/site-packages/_mysql.so: > undefined symbol: Py_InitModule4 What happens when you run python2.4 and at the interactive prompt do >>> import _mysql ? Is there a possibility that you installed 2.5 MySQLdb into the 2.4 hierarchy? [could be a stupid question from a windows guy; this may be a non-problem on linux] Is this the first thing that you've tried after installing 2.5, or the only problem found in an exhaustive regression test of all your apps using 2.4, or somewhere in the middle? [big snip] HTH, John From narkewoody at gmail.com Tue Dec 23 23:29:41 2008 From: narkewoody at gmail.com (Steven Woody) Date: Wed, 24 Dec 2008 12:29:41 +0800 Subject: Multi-dimension list In-Reply-To: References: Message-ID: Hi, In the book Python Essential Reference, Chapter 3, when talking about extended slicing, it gives an example: a = m[0:10, 3:20]. But I don't understand how the 'm' was defined. What should it looks like? Thanks. - narke From ht at example.com Thu Dec 4 15:09:57 2008 From: ht at example.com (HT) Date: Thu, 04 Dec 2008 12:09:57 -0800 Subject: Why shouldn't you put config options in py files References: Message-ID: Chris Rebert wrote: > On Thu, Dec 4, 2008 at 11:35 AM, HT wrote: >> FOO = {'bar': ('a': 'b'), 'abc': ('z': 'x')} > > I'll assume you meant ('a', 'b') as colons in parens don't make sense. Yes, sorry. > Well, it is pretty weird to be allowed to put arbitrary code in a mere > config file. The end result is that we want to have that dictionary in that variable (most of the config values would just be simple values or lists and this dict is among the most complex), but it doesn't mean that the config file would need to have arbitrary code. I can think of many ways to achieve that (haven't actually tried writing the code to read these yet): [my_foos] bar = a, b abc = z, x or maybe foo.bar= a, b foo.abc= z, x or something like that. You'd read the values with ConfigParser, then process them to get the dictionary. > Have you considered using JSON for the config file format instead? It > shares Python's syntax for literals, so you could do: No, hadn't thought of that. Might be doable, need to think about that some more. Thanks. From fetchinson at googlemail.com Fri Dec 5 21:21:18 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Fri, 5 Dec 2008 18:21:18 -0800 Subject: Guido's new method definition idea Message-ID: Hi folks, The story of the explicit self in method definitions has been discussed to death and we all know it will stay. However, Guido himself acknowledged that an alternative syntax makes perfect sense and having both (old and new) in a future version of python is a possibility since it maintains backward compatibility. The alternative syntax will be syntactic sugar for the old one. This blog post of his is what I'm talking about: http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html The proposal is to allow this: class C: def self.method( arg ): self.value = arg return self.value instead of this: class C: def method( self, arg ): self.value = arg return self.value I.e. explicit self stays only the syntax is slightly different and may seem attractive to some. As pointed out by Guido classmethods would work similarly: class C: @classmethod def cls.method( arg ): cls.val = arg return cls.val The fact that Guido says, "Now, I'm not saying that I like this better than the status quo. But I like it a lot better than [...] but it has the great advantage that it is backward compatible, and can be evolved into a PEP with a reference implementation without too much effort." shows that the proposal is viable. I'd like this new way of defining methods, what do you guys think? Anyone ready for writing a PEP? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From jon at ffconsultancy.com Mon Dec 8 20:00:35 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Tue, 09 Dec 2008 01:00:35 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: jason-sage at creativetrax.com wrote: > For the interested, with MMA 6, on a Pentium 4 3.8Ghz: > > The code that Jon posted: > > Timing[Export["image-jon.pgm", Graphics at Raster@Main[2, 100, 4]]] > {80.565, "image-jon.pgm"} That is not the code I posted: you are using Xah's parameters that generate a different (and largely empty) scene. > The code that Xah posted: > > Timing[Export["image-xah.pgm", Graphics at Raster@Main[2, 100, 4.]]] > {42.3186, "image-xah.pgm"} > > So Xah's code is about twice as fast as Jon's code, on my computer. > > The resulting files were identical (and both looked like pure white > images; I thought they'd be interesting!). Use 9, 512, 4 instead of 2, 100, 4 and you will get a more interesting image of over 80,000 spheres with shadows and diffuse lighting. This is a really important difference: half of that program is dedicated to hierarchical spherical bounding volumes that are essential when tracing a large number of spheres. Xah solved a completely different problem by simplifying the scene to only 5 spheres, where bounding volumes are useless and the performance characteristics of the program are wildly different. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From python at rgbaz.eu Wed Dec 31 07:55:51 2008 From: python at rgbaz.eu (Python) Date: Wed, 31 Dec 2008 13:55:51 +0100 Subject: Graphics Library with Standard Interaction Features, 2D and 3D In-Reply-To: <69c3eca8-5e17-49fb-8354-5fdc0bd73f9a@r15g2000prd.googlegroups.com> References: <69c3eca8-5e17-49fb-8354-5fdc0bd73f9a@r15g2000prd.googlegroups.com> Message-ID: <878673C7-0520-49B1-A24B-B7292D6C32CC@rgbaz.eu> On 31 dec 2008, at 13:37, Benjamin Blundell wrote: > Hi all. I've had a look around the forums and the we and im looking > for a library (or a set of libraries) for dealing with Visualisation > and Interaction in Python. At the moment i've been using Flash with > the Five3D library to do most of the work. Sadly this isnt an option > anymore but it is a good example. Pretty,anti-aliased 2D and 3D > graphics, simple interaction and no need to rewrite the wheel. > > Im a fan of OpenGL and PyOpenGL is fairly cool but I really dont want > to have to write yet another camera, another way of dealing with > Vectors, texture organiser, picking, etc etc. Is there a library or > set of libraries that people are aware of that might do this? I > remember a few in C++ and C but it'd be nicer to stick to working with > Python > > Cheers > Ben Hey Ben, dunno if this is exactly what you;re looking for, yet you could have a look at Blender http://blender.org/ http://wiki.blender.org/index.php/Scripts it's an open source 3D application and has a python scripting engine... (just like maya from Autodesk) gr Arno From samslists at gmail.com Fri Dec 5 19:04:40 2008 From: samslists at gmail.com (Sam) Date: Fri, 5 Dec 2008 16:04:40 -0800 (PST) Subject: Centralized logging server... References: <413147e3-aaea-4ae3-a350-4c22a79fe77a@b38g2000prf.googlegroups.com> Message-ID: <857c6c29-178d-4444-90e0-f3c25386921c@w24g2000prd.googlegroups.com> Yep...I'm planning on using SysLogHandler. Although if I were to use rsyslog, for example, I might potentially be better off using tcp or even doing it using rfc 3195. Sysloghandler uses udp...I imagine that will be faster but with less reliability. I'll have to think about that. Has anyone implemented a library for rfc 3195, or would I have to do that from scratch. I was more curious as to what people are using to receive the messages? Syslog-ng? traditoinal? rsyslog? Home grown solutions? I know syslog is already running, but I'm not sure the traditional version could keep up with all the traffic I'm going to have. Anyone know how well it scales compared to the alternatives? Thanks Sam On Dec 5, 12:24?pm, s... at pobox.com wrote: > ? ? Sam> I've been playing with the python logging module. ?I'd like all of > ? ? Sam> these applications to write their logs to the same place in order > ? ? Sam> to make analysis easier. > > ? ? Sam> Any ideas on best practices? > > Perhaps use logging.handlers.SysLogHandler? > > ? ? Sam> What are my options for a syslog server to receive the messages? > ? ? Sam> Rsyslog looks like it would be good. ?Anyone know anything else? > > If you're running on a Unix system of any type you should have syslog by > default. ?You shouldn't need to install anything. > > -- > Skip Montanaro - s... at pobox.com -http://smontanaro.dyndns.org/ From rbonvall at gmail.com Wed Dec 10 22:28:04 2008 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Wed, 10 Dec 2008 19:28:04 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: Arnaud Delobelle wrote: > def unit(v): > return map((sum(map(lambda x:x*x, v))**0.5).__rdiv__, v) > > The hard bit was to make it less readable than the Ruby version ;) I loved the use of __rdiv__ :) I would have proposed the more straightforward: def u(v): return [x/sum(x**2 for x in v)**0.5 for x in v] or, in order to avoid computing the norm for each element: def u(v): return (lambda norm: [x/norm for x in v])(sum(x**2 for x in v) **0.5) -- Roberto Bonvallet From castironpi at gmail.com Mon Dec 29 20:46:36 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 17:46:36 -0800 (PST) Subject: why cannot assign to function call References: <495867C2.7080807@gmail.com> Message-ID: <5e807c67-7d97-4b8a-8c5f-a3b97f5c5003@i20g2000prf.googlegroups.com> On Dec 29, 6:06?pm, Miles wrote: > On Mon, Dec 29, 2008 at 1:01 AM, scsoce wrote: > > I have a function return a reference, and want to assign to the reference, > > simply like this: > >>>def f(a) > > ? ? ? ? return a > > ? ?b = 0 > > ? * f( b ) = 1* > > but the last line will be refused as "can't assign to function call". > > In my thought , the assignment is very nature, ?but ?why the interpreter > > refused to do that ? > > Here's some links to help you better understand Python objects: > > http://effbot.org/zone/python-objects.htmhttp://effbot.org/zone/call-by-object.htm > > The second one is a bit denser reading, but it's important to learn > that Python's approach to objects and "variables" is fundamentally > different from that of C/C++. ?In the example below, there's no way in > the Python language* that bar() can change the value of b, since > strings and numbers are immutable. On a technicality, to avert a flaming, "change the value of 'b'" is an ambiguous phrase. There are two interpretations of "change what 'b' refers to" and "change what 'b' refers to". Even in spoken language, I don't think that emphasis can resolve them either. One means, 'make a change in the world, in the actual configuration of such and such actual matter.' The other means, 'update the axioms the speaker is using to communicate to the listeners. (Such and such will no longer refer to such and such; it will refer to such and such; accept this and reject that.)' To make an observation, reference is a purely linguistic phenomenon. I, for one, am at a loss for how to disambiguate it. I'm open to suggestions. From bruno.42.desthuilliers at websiteburo.invalid Fri Dec 19 07:22:33 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 19 Dec 2008 13:22:33 +0100 Subject: encoding problem In-Reply-To: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> References: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> Message-ID: <494b91c2$0$1133$426a74cc@news.free.fr> digisatori at gmail.com a ?crit : > The below snippet code generates UnicodeDecodeError. > #!/usr/bin/env python > #--*-- coding: utf-8 --*-- > s = '???' > u = unicode(s) > > > It seems that the system use the default encoding- ASCII to decode the > utf8 encoded string literal, and thus generates the error. Indeed. You want: u = unicode(s, 'utf-8') # or : u = s.decode('utf-8') > The question is why the Python interpreter use the default encoding > instead of "utf-8", which I explicitly declared in the source. Because there's no reliable way for the interpreter to guess how what's passed to unicode has been encoded ? s = s.decode("utf-8").encode("latin1") # should unicode try to use utf-8 here ? try: u = unicode(s) except UnicodeDecodeError: print "would have worked better with "u = unicode(s, 'latin1')" NB : IIRC, the ascii subset is safe whatever the encoding, so I'd say it's a sensible default... From steve at REMOVE-THIS-cybersource.com.au Mon Dec 15 04:00:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Dec 2008 09:00:48 GMT Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> <0152e35f$0$8244$c3e8da3@news.astraweb.com> <0155c4a7$0$6988$c3e8da3@news.astraweb.com> Message-ID: <01561434$0$20639$c3e8da3@news.astraweb.com> On Mon, 15 Dec 2008 05:39:45 +0000, Lie Ryan wrote: > I was just expressing the > preference that operators should be composed of a single word, > especially since none of the other operators are multi-words Then you should have said so, instead of introducing red-herrings about tired programmers. I must say, some years ago I probably would have agreed with you. I used to dislike "a is not b" and would go out of my way to write "not a is b". But then I decided that was just being silly, and I've never looked back. -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 22:07:49 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2008 03:07:49 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <1332da3c-8075-4552-9498-3ceb23faca8f@v31g2000vbb.googlegroups.com> Message-ID: <015c58d6$0$20656$c3e8da3@news.astraweb.com> On Fri, 19 Dec 2008 17:12:00 -0800, r wrote: > Why move away from a concise and widely accepted way of sting > formatting, just to supposedly make it a little easier for n00bs? (which > i disagree this is easier) In turn, creating more syntactical clutter. > (%s %f %d) is all you need to remember. If people can't understand that, > i fear for the future of Humans as a species! Reading your wibbling, so do I. Take ten deep breaths and calm down. Firstly, the introduction of format() is not to "make it a little easier for n00bs" as you claim, but to allow more powerful, flexible string formatting. Secondly, to use % formatting to full effectiveness you need to know MUCH more than (%s %f %d). You need to know: Formatting codes: %s %r %d %f %g %G %c %i %u %o %x %X %e %E %% (have I missed any?) Keyword formatting: %(name)s Flags: - + 0 Field width and precision, including the special case of "*" and how they fit together: %[(name)][flags][width][.precision][unused(!) length modifier]code You also need to know about operator precedence: >>> "%s" % 3+2 Traceback (most recent call last): File "", line 1, in TypeError: cannot concatenate 'str' and 'int' objects and the special casing of tuples: >>> "Tuple = %s" % (1,2,3) Traceback (most recent call last): File "", line 1, in TypeError: not all arguments converted during string formatting For trivial cases, format() isn't much harder than %: "{0}".format(x) "%s" % x For more complex cases, format() will let you do things that you can't do with only %, e.g. arbitrary fill characters, centring fields, percentage formatting, mixing positional and keyword arguments, etc. Before you blow yet another gasket, go read the PEP: http://www.python.org/dev/peps/pep-3101/ -- Steven From rogerb at rogerbinns.com Wed Dec 24 03:27:25 2008 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 24 Dec 2008 00:27:25 -0800 Subject: Most efficient way to build very large dictionaries In-Reply-To: <1230104615.5867.1291617213@webmail.messagingengine.com> References: <1230104615.5867.1291617213@webmail.messagingengine.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 python at bdurham.com wrote: > Can I take advantage of this knowledge to optimize You do the optimization last :-) The first thing you need to do is make sure you have a way of validating you got the correct results. With 25M entries it would be very easy for an optimization to get the wrong results (maybe only one result wrong). Once you can verify the results correctness, write the simplest most readable code possible. Then once your whole program is approaching completion time how long things take to get an idea of where to optimize. For example it is pointless optimizing the loading phase if it only takes 2 minutes out of a 3 hour runtime. Finally you can optimize and always have a way of verifying that the optimizations are correct. You have the original code to document what is supposed to be happening as optimized code tends to get rather obfuscated and unreadable. Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAklR8mkACgkQmOOfHg372QQvLQCgu6NYNUuhgR06KQunPmIrZ64B +rsAnAgQOKzMdmonF+zIhsX2r/Xg/72Y =LFfW -----END PGP SIGNATURE----- From pyth0nc0d3r at gmail.com Mon Dec 15 08:21:12 2008 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Mon, 15 Dec 2008 07:21:12 -0600 Subject: %s place holder does not let me insert ' in an sql query with python. In-Reply-To: <1229345178.31093.24.camel@krishna-laptop> References: <1229345178.31093.24.camel@krishna-laptop> Message-ID: I had this problem too. If you've upgraded to python 2.6 you need to use the new sytnax "format queryString = "insert into venders values('{0}','{1}','{2}'".format(field1,field2,field3) On Mon, Dec 15, 2008 at 6:46 AM, Krishnakant wrote: > hello all hackers. > This is some kind of an interesting situation although many of you must > have already gone through it. > I am facing a situation where I have to use psycopg2 and insert rows in > a postgresql table. > That's pritty easy and no need to say that it works well. But there are > some entries which have an ' in the value. > I have a venders table in my database and one of the values tryed was > "His Master's Voice " > now the master's word has the ' which is used for starting and ending a > varchar value for postgresql or almost any standard RDBMS. > Does any one know what is the way out of this? > how do you let the ' go as a part of the string? > I have used %s as placeholder as in > queryString = "insert into venders values ('%s,%s,%s" % > (field1,field2,field3 ) ... > This is not working for the ' values. > can any one suggest a suitable solution? > happy hacking. > Krishnakant. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From hackingkk at gmail.com Sun Dec 21 12:20:05 2008 From: hackingkk at gmail.com (Krishnakant) Date: Sun, 21 Dec 2008 22:50:05 +0530 Subject: Python is slow In-Reply-To: <494E6FDA.4070401@mrabarnett.plus.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> <6r6hpfFfb643U3@mid.uni-berlin.de> <494E6FDA.4070401@mrabarnett.plus.com> Message-ID: <1229880005.4138.46.camel@krishna-laptop> With my current experience with java, python and perl, I can only suggest one thing to who ever feels that python or any language is slow. By the way there is only one language with is fastest and that is assembly. And with regards to python, I am writing pritty heavy duty applications right now. Just to mention I am totally blind and I use a screen reader called orca on the gnome desktop. I hope readers here can understand that a screen reader has to do a lot of real-time information processing and respond with lightenning speed. And Orca the scree reader is coded totally in python. So that is one example. So conclusion is is how you enhance your program by utilising the best aspects of python. happy hacking. Krishnakant. On Sun, 2008-12-21 at 16:33 +0000, MRAB wrote: > Marc 'BlackJack' Rintsch wrote: > > On Sat, 20 Dec 2008 14:18:40 -0800, cm_gui wrote: > > > >>> Seriously cm_gui, you're a fool. > >>> Python is not slow. > >> haha, getting hostile? > >> python fans sure are a nasty crowd. > >> > >> Python is SLOW. > >> > >> when i have the time, i will elaborate on this. > > > > You are not fast enough to elaborate on Python's slowness!? :-) > > > > cm_gui is slow! > > > > Ciao, > > Marc 'BlackJack' Rintsch > > > Correction: > > cm_gui is SLOW! :-) > -- > http://mail.python.org/mailman/listinfo/python-list From febaen at gmail.com Mon Dec 15 17:40:08 2008 From: febaen at gmail.com (feba) Date: Mon, 15 Dec 2008 14:40:08 -0800 (PST) Subject: Need help improving number guessing game References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> <01564c98$0$21844$c3e8da3@news.astraweb.com> <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> Message-ID: Spent a bit more time looking over suggestions and working out some annoyances. import random def customrange(game, lowunsafe=True): game['defrang'] = False #Keeps setup from changing range to defaults while lowunsafe: #makes sure that the low number is positive picklow = int(input("PLEASE PICK THE LOW NUMBER: ")) if picklow < 0: print("LOW NUMBER MUST BE POSTIVE") else: lowunsafe = False pickhigh = int(input("PLEASE PICK THE HIGH NUMBER: ")) if pickhigh - picklow <= 2: #see setup(). print("HIGH MUST BE AT LEAST THREE GREATER THAN LOW") else: game['minr'], game['maxr'] = picklow, pickhigh print("RANGE IS [%s-%s]!" % (game['minr'], game['maxr'])) def wantcustom(game, unsure=True): #Allows user to decide their own range for guessing. while unsure: pickrange = input("WOULD YOU LIKE TO CREATE A CUSTOM RANGE? Y/ N: ") if pickrange.lower() == "n": game['minr'], game['maxr'] = 1, 99 #Default range. see setup unsure = False elif pickrange.lower() == "y": customrange(game) unsure = False else: print("INVALID INPUT") def samesettings(game, unsure=True): while unsure: keepset = input("USE SAME SETTINGS? Y/N: ") if keepset.lower() == "y": game['minr'], game['maxr'] = 1, 99 #Default range. see setup unsure = False elif keepset.lower() == "n": wantcustom(game) numplayers(game) unsure = False else: print("INVALID INPUT") def setup(game): #minr, maxr make minimum and maximum. Can be adjusted. #Make sure that maxr - minr is at least 3. #1 or less would be impossible. 2 would only have one guess for victory #The first would be unplayable, the second would play itself if game['maxr'] - game['minr'] <= 2: raise ValueError("INVALID RANGE!") #If this fails, check line 43 game['gcount'] = 0 #Reset guess count game['target'] = random.randint(game['minr'], game['maxr']) def playerswitch(game): #Player Switch #if player's a witch: burn(her) if game['player'] == game['player1']: game['player'] = game['player2'] else: game['player'] = game['player1'] def youwin(game): if game['pnum'] == 1: print("CONGRATULATIONS! IT TOOK YOU %s GUESSES" % game ['gcount']) else: if game['player'] == game['player1']: game['p1sc'] += 1 else: game['p2sc'] += 1 end = "CONGRATULATIONS %s! SCORE -- P1:%s P2:%s" print(end % (game['player'], game['p1sc'], game['p2sc'])) def playagain(game, unsure=True): while unsure: playover = input("PLAY AGAIN? Y/N: ") if playover.lower() == "y": game['play'] = True samesettings(game) setup(game) unsure = False elif playover.lower() == "n": print("GOOD BYE. PLAY AGAIN SOON!") game['play'] = False unsure = False else: print("INVALID INPUT") def autofinish(game): if game['maxr'] - game['minr'] == 2: print("...ONLY ONE OPTION LEFT!") youwin(game) playagain(game) def numplayers(game, unsafe=True, prompt="1 OR 2 PLAYERS?\n> "): while unsafe: while True: num = input(prompt) try: #Make sure that num is valid num = int(num) except ValueError: print("BAD VALUE!") else: break if num == 1 or 2: #ONLY allow 1 or 2P. unsafe = False else: print("INVALID INPUT") game['pnum'] = num def guesses(game, unsafe=True): while unsafe: while True: try: guess = int(input("[%s-%s]%s>> " \ #keeps user aware of who's turn it is, and the range % (game['minr'], game['maxr'], game['player']))) except ValueError: print("BAD VALUE!") else: break if guess >= game['maxr']: print("NUMBER MUST BE IN RANGE") guesses(game) guesscheck(game) elif guess <= game['minr']: print("NUMBER MUST BE IN RANGE") guesses(game) guesscheck(game) else: unsafe = False game['guess'] = guess def guesscheck(game): if game['guess'] == game['target']: if game['pnum'] == 1: game['gcount'] += 1 youwin(game) playagain(game) elif game['guess'] > game['target']: print("TOO HIGH") if game['pnum'] == 1: game['gcount'] += 1 game['maxr'] = game['guess'] else: print("TOO LOW") if game['pnum'] == 1: game['gcount'] += 1 game['minr'] = game['guess'] def guessing(game): guesses(game) guesscheck(game) if game['pnum'] == 2: playerswitch(game) autofinish(game) def main(game=None): if game is None: game = {} print("WELCOME TO THE SUPER NUMBER GUESSING GAME!") game['play'] = True game['player1'], game['player2'] = "P1", "P2" game['player'] = game['player1'] # P1 goes first #Scores start at 0 game['p1sc'], game['p2sc'], game['gcount'] = 0, 0, 0 wantcustom(game) numplayers(game) setup(game) while game['play'] is True: guessing(game) if __name__ == "__main__": main() This is basically finding a balance between being annoyed by prompts and being annoyed by having to quit and restart. Given the sorts of people who will play this longer than to find out how it works are the sort of people who find spreadsheets and powerpoints and EVE online fun, I'll go with prompts. From duncan.booth at invalid.invalid Mon Dec 1 16:51:21 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Dec 2008 21:51:21 GMT Subject: Why doesn't doc has predifined name and location ? References: <493455AD.4040306@gmail.com> Message-ID: "Chris Rebert" wrote: > Sidenote: what Python projects publish their docs in CHM besides > possibly Win32 GUI programs? Python itself does and, given that chm output is one of the features built in to Sphinx, so can anything which uses reST documentation. From junk.mail.only at lycos.com Thu Dec 4 21:08:51 2008 From: junk.mail.only at lycos.com (junk.mail.only) Date: Thu, 04 Dec 2008 21:08:51 -0500 (EST) Subject: How can I do this (from Perl) in Python? (closures) Message-ID: <20081204210851.HM.0000000000002Ul@junk.mail.only.mail-wwl6.bo3.lycos.com.lycos.com> An HTML attachment was scrubbed... URL: From joemacbusiness at gmail.com Mon Dec 1 15:47:23 2008 From: joemacbusiness at gmail.com (joemacbusiness at gmail.com) Date: Mon, 1 Dec 2008 12:47:23 -0800 (PST) Subject: newbie question: parse a variable inside an RE? Message-ID: Hi All, How do I parse a variable inside an RE? What is the re.search() syntax when your search string is a variable? It's easy to parse hardcoded RE's but not if you use a variable. Here is my code, input and runtime: $ cat test45.py #!/usr/bin/python import re resp = raw_input('Selection: ') newresp = resp.strip() print "you chose ", newresp fname = open('test44.in') for I in fname: # if re.search('^newresp', "%s"%(I)): # returns nothing # if re.search(^newresp, "%s"%(I)): # syntax error if re.search("^newresp", "%s"%(I)): # returns nothing print I, [jmccaughan at dhcppc2 work]$ cat test44.in a1 b1 g1 g2 h1 h4 4g 5g h5 $ python test45.py Selection: g you chose g $ Thanks... From aleksandr.goretoy at gmail.com Tue Dec 30 22:25:15 2008 From: aleksandr.goretoy at gmail.com (alex goretoy) Date: Wed, 31 Dec 2008 03:25:15 +0000 Subject: parsing csv files class In-Reply-To: References: Message-ID: This line doesn't work for me. bufferp is empty afterwards. self.bufferp= [dict(zip(header,line)) for line in reader] needs to be this self.bufferp= [dict(zip(header,line)) for line in self.buffer] after reading from the reader, it becomes empty. Figured maybe someone would find this info useful. Thank you Tim for helping me make my library better. I may need some assistance in another thread about a pycurl library. I want it to fall back to urllib/urllib2 if pycurl is not installed module. look for thread "pycurl urllib fallback" I will post it here shortly to python-list. On Mon, Dec 29, 2008 at 6:15 AM, alex goretoy wrote: > Tim, Thank you for your suggestions that you made. I will modify my class > to what you said. I will also remove find_and_replace. seeing as I won't use > it anywhere else. I think I put it there for some test and forgot to delete > it. I was actually deleting the header outside of the class. This works much > better for me. Any other suggestions are appreciated. Thank you. -A > > > On Sun, Dec 28, 2008 at 5:46 AM, Tim Roberts wrote: > >> "alex goretoy" wrote: >> > >> >class parsercsvy(object): >> > """Return a line from a csv file or total amount of lines""" >> > def __init__(self,file_name=""): >> > self.func_me_color="white_on_black" >> > self.soc=stdout_colours.stdout_colors() >> > self.soc.me_him(['ENTER:',__name__],self.func_me_color) >> > self.filename = file_name >> > self.buffer = [] >> > self.bufferp= [] >> > if string.find(self.filename,"http") != -1: >> > resp=urllib2.urlopen(self.filename) >> > file=resp.read() >> > lfi=len(string.split(self.filename,"/")) >> > filename = "/tmp/"+string.split(self.filename,"/")[lfi-1] >> >> Style issue: unless you are running Python 1.x, you virtually never need >> to import the "string" module. Also, you can always refer to the last >> element of a list or tuple by using [-1]: >> >> parts = self.filename.split( "/" ) >> filename = "/tmp/" + parts[-1] >> >> >> > def parse(self,filename,ret=0): >> > self.soc.me_him(['ENTER:',__name__],self.func_me_color) >> > i = 0 >> > try: >> > reader = csv.reader(file(filename, "rb")) >> > try: >> > for row in reader: >> > self.buffer.append(row) >> > s,a=[],{} >> > >> > for j in range(len(self.buffer[0])): >> > a[self.buffer[0][j]]=row[j] >> > self.bufferp.append(a) >> > i+=1 >> > self.total = i-1 >> >> You might consider keeping the header line separate. >> >> reader = csv.reader(open(filename, "rb")) >> header = reader.next() >> self.buffer = list(reader) >> self.bufferp = [ dict( zip( header, line ) ) for line in reader ] >> self.header = header >> >> Also, you don't really need a separate "total" variable, since it's equal >> to len(self.buffer). >> >> > def total(self): >> > """return total number of lines in csv file""" >> > self.soc.me_him(['ENTER:',__name__],self.func_me_color) >> > >> self.soc.me_him(['RETURN:',self.total,__name__],self.func_me_color) >> > return self.total >> >> There's a problem here, as this was originally written. "self.total" >> starts out being a function (this one here). But after self.parse runs, >> "self.total" will be an integer, and this function is lost. You need to >> decide whether you want users to just access the self.total integer, or >> force them to use the function. In the latter case, you can change the >> counter to self._total. >> >> On the other hand, the self.total counter is unnecessary: >> def total(self): >> return len(self.buffer) >> >> > def find_and_replace(self,li,fi,re): >> > """ >> > find and replace a string inside a string, return list >> > find_and_replace(list,find,replace) >> > """ >> > this=[] >> > for l in li: >> ># found_index=string.find(l,fi) >> > this.append(l.replace(fi,re)) >> > return this >> >> def find_and_replace(self,li,fi,re): >> return [l.replace(fi,re) for l in li] >> >> I'm not sure why this is a member of the class; it doesn't use any of the >> members. >> -- >> Tim Roberts, timr at probo.com >> Providenza & Boekelheide, Inc. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > > -- > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > -- ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Sat Dec 13 15:28:14 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 13 Dec 2008 12:28:14 -0800 (PST) Subject: Python 3.0 crashes displaying Unicode at interactive prompt Message-ID: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> x = u'\u9876' >>> x u'\u9876' # As expected Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> x = '\u9876' >>> x Traceback (most recent call last): File "", line 1, in File "C:\python30\lib\io.py", line 1491, in write b = encoder.encode(s) File "C:\python30\lib\encodings\cp850.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u9876' in position 1: character maps to # *NOT* as expected (by me, that is) Is this the intended outcome? From python.list at tim.thechases.com Mon Dec 15 15:55:59 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 15 Dec 2008 14:55:59 -0600 Subject: Problem accessing a web page In-Reply-To: <47c890dc0812151216o59a3cbc2uf98d74604988d27@mail.gmail.com> References: <47c890dc0812151216o59a3cbc2uf98d74604988d27@mail.gmail.com> Message-ID: <4946C45F.7060100@tim.thechases.com> > I'm able to grab the problem webpage via Python just fine, albeit with > a bit of a delay. So, don't know what your exact problem is, maybe > your connection? When you get the second page, are you getting the same content back that you get if you do a search in your favorite browser? Using just content = urllib.urlopen(url2).read() 'Error' in content # True 'Friedrich' in content # False However, when you browse to the page, those two should be inverted: 'Error' in content # False 'Friedrich' in content # True I've tried adding in the parameters correctly via post params = urllib.urlencode([ ('params.forzaQuery', 'N'), ... ('layout', 'busquedaisbn'), ]) content = urllib.urlopen(url2, data).read() However, this too fails because the underlying engine expects a session ID in the URL. I finally got it to work with the code below: import urllib data = [ ('params.forzaQuery', 'N'), ('params.cdispo', 'A'), ('params.cisbnExt', '8484031128'), ('params.liConceptosExt[0].texto', ''), ('params.orderByFormId', '1'), ('action', 'Buscar'), ('language', 'es'), ('prev_layout', 'busquedaisbn'), ('layout', 'busquedaisbn'), ] params = urllib.urlencode(data) url = 'http://www.mcu.es/webISBN/tituloSimpleDispatch.do;jsessionid=5E8D9A11E4A28BDF0BA6B254D0118262' fp = urllib.urlopen(url, params) content = fp.read() fp.close() but I had to hard-code the jsessionid parameter in the URL. This would have to be determined from the initial call & response of the initial URL (the initial URL returns a
    element with the URL to POST to, including this magic jsessionid parameter). Hope this helps nudge you (the OP) in the right direction to get what you're looking for. -tkc From akineko at gmail.com Mon Dec 22 17:33:17 2008 From: akineko at gmail.com (akineko) Date: Mon, 22 Dec 2008 14:33:17 -0800 (PST) Subject: 64-bit / 128-bit data element type for array? References: <880c8478-8b40-40e0-8597-aef960612f09@s9g2000prg.googlegroups.com> Message-ID: Hello Robert, > Is that actually a 2s-complement 128-bit unsigned integer, or is it just a > 128-bit-long chunk of data? That is a good question. A 128-bit data can be anything. A 128-bit data can be an instrution code (VLIW machines use such wide instruction). A 128-bit can be a packed ascill (16 chrs). A 128-bit can be a descriptor (a structure of various fields). It is probably safe to say that only unsigned 128-bit is required. (I cannot think of any situations where signed 128-bit is necessary) Hope this answers your question. Aki Niimura On Dec 22, 1:22 pm, Robert Kern wrote: > akineko wrote: > > Hello, > > > bearophile and Robert, thank you for your prompt response. > > I will try NumPy (this is a good execuse to learn and to use a new > > package). > > >> I haven't seen uint128 in the wild, though. > > > Of course, not many applications require uinit128 as a scalar value. > > I may need to deal with 128-bit data as it is now not uncommon to have > > 128-bit data bus (or even 256-bit wide and beyond) in ASICs > > (microchip) design. Unfortunately, some designs use big-endian and > > others use little-endian ... > > Is that actually a 2s-complement 128-bit unsigned integer, or is it just a > 128-bit-long chunk of data? > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco From deets at nospam.web.de Thu Dec 18 10:13:18 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 18 Dec 2008 16:13:18 +0100 Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> Message-ID: <6qv7kfFeuf65U1@mid.uni-berlin.de> Neal Becker wrote: > Tino Wildenhain wrote: > >> Neal Becker wrote: >> ... >>>>> So if __str__ is "meant for human eyes", then why isn't print using >>>>> it! >>>> it is: >>>> >>>> > print x >>>> str >>>> >>>> but dict just uses repr() for all its childs to print. >>>> >>>> T. >>> That makes no sense to me. If I call 'print' on a container, why >>> wouldn't it recursively print on the contained objects? Since print >>> means call str, printing a container should recursively call str on the >>> objects. >> >> Every class is free on how to best implement __str__, you will find >> the same behavior on tuple and list as well. >> >> Maybe its discussable to change the implementation sensibly, best if you >> would come with a proposal? Perhaps pprint.pprint is a starting point? >> >> Regards >> Tino > > First, I'd like to know if there is a rationale for the current design. > Am I correct in thinking this is a defect? I don't think so. First of all, there is no "generic" way of printing a collection. And the current implementation tries to give an overview what is contained in the collection, without trying to make it "fancy" - any such thing needed to be hand-coded anyway. Using repr for that is better suited, as for example string keys are printed with quotes around them - making clear what they are, and not irritating the user through potentially contained spaces or even things that look as if they are python objects. For example, if repr *wasn't* used, { "{foo=bar}" : "baz"} would be printed {{foo=bar} : baz} Which is *not* what the dictionary actually contains! The same goes for unicode-objects. They appear with their "funny" characters as \xXX-codes - instead of bailing out on you with unicode-errors. So, IMHO the current behavior is desired. Diez From Slaunger at gmail.com Mon Dec 1 09:01:48 2008 From: Slaunger at gmail.com (Slaunger) Date: Mon, 1 Dec 2008 06:01:48 -0800 (PST) Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> Message-ID: Slaunger wrote: > > class PayloadOnDemand(object): > ? ? """ > ? ? Behaves as a PayloadInstant object, but instantiation is faster > ? ? as only the position of the payload in the file is stored > initially in the object. > ? ? Only when acessing the initially non-existing data attribute > ? ? are the data actually read and the attribure created and bound to > the instance. > ? ? This will actually be a little slower than in PayloadInstant as > the correct file position > ? ? has to be seeked out first. > ? ? On later calls the object has as efficient attribute access as > PayloadInstant > ? ? """ > > ? ? @classmethod > ? ? def read_from_file(cls, f, size): > ? ? ? ? pos = f.tell() > ? ? ? ? f.seek(pos + size) #Skip to end of payload > ? ? ? ? return cls(pos) Extend with ref to file instead: return cls(f, pos) > > ? ? # I probably need some __getattr__ or __getattribute__ magic > # there...?? To answer my own rethorical question I guess I should do something like this def __getattr__(self, attr_name): """ Only called if attr_name is not in the __dict__ for the instance """ if attr_name == 'data': self.__dict__[attr_name] = read_data(self.f, self.file_position) > > ? ? def __init__(self, a_file_position): > ? ? ? ? self.file_position = a_file_position > and then I need to also store a reference to the file in the constructor... def __init__(self, a_file, a_file_position): self.f = a_file self.file_position = a_file_position Have I understood correctly how to to it the on demand way? -- Slaunger From gagsl-py2 at yahoo.com.ar Mon Dec 29 01:19:17 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Dec 2008 04:19:17 -0200 Subject: Cheetah References: Message-ID: En Sun, 28 Dec 2008 15:01:14 -0200, escribi?: > 1. In Cheetah 2.0.1, both from python 2.5.2 and 2.6, after I do a [...] > 2. In reportlab 2.2, when I generate a PDF, no matter how many  s > [...] Better to report those problems to each product authors. -- Gabriel Genellina From geekmail at usenot.de Sun Dec 7 15:00:16 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sun, 7 Dec 2008 21:00:16 +0100 Subject: [OT] [sort of] Malcom Reynolds? Message-ID: <20081207210016.751a33c9@usenot.de> Just found this in the re module's docs: m = re.match(r"(?P\w+) (?P\w+)", "Malcom Reynolds") Does this represent an attempt to phase out the gratuitous Monty Python references in favor of gratuitous Firefly references? Because if so, I'm all for it. Anyways, stuff like that really makes reading documentation fun. /W -- My real email address is constructed by swapping the domain with the recipient (local part). From benjamin.kaplan at case.edu Sun Dec 7 22:25:27 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 7 Dec 2008 22:25:27 -0500 Subject: Python for kids? In-Reply-To: <11a3e492-3c0d-475f-b350-f28351842dad@f3g2000yqf.googlegroups.com> References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> <53f406ed-c261-4d86-a8dc-4001d10d05b5@s20g2000yqh.googlegroups.com> <11a3e492-3c0d-475f-b350-f28351842dad@f3g2000yqf.googlegroups.com> Message-ID: On Sun, Dec 7, 2008 at 8:10 PM, Luis M. Gonz?lez wrote: > This is a very good advice. > I learned from my own experience in college that trying to learn a > solution to a problem I never had, is wasted time. > The first step is confronting your student with an specific problem, > then let him try to find a way to solve it by himself. > After he tried hard many approaches to solving the problem with his > limited knowledge, show him the right way. > This way he will see the light. > > I believe that many teachers don't know this basic concept, and they > simply teach in a mechanical way, without having their students > interested in the subject or without having explained them what > exactly these skills are good for. > > Luis As a current college student, I second that. I have several years of programming experience, but most of my friends are taking Intro Programming this semester (it's a required course for all engineers, not just CS students). They sort of understand the stuff they go over in class, but when they look at their homework problems (and they get very interesting problems. Like stories based off of Pokemon, Stargate, and Lord of the Rings. Not exactly useful, but fun), they're absolutely clueless. > > > On Dec 7, 5:37 pm, bearophileH... at lycos.com wrote: > > On Dec 7, 9:13 pm, "Russ P." wrote: > > > > > I have a 12-year-old son who spends too much time playing Xbox live > > > and watching silly YouTube videos. I would like to try to get him > > > interested in programming. > > > > Lot of people learn to program even before age of 12. > > But I think it's better for you to help him get interest in problem- > > solving and some of the other bases of the mathematic, scientific and > > computational mindset. Once those interests are in place, he will > > probably go looking by himself for things like programming languages, > > math and science (of course at that point a gentle guide toward good > > ideas, good problems to solve, good books to read and good programming > > languages, helps). > > > > Otherwise you risk pushing a person to learn using a tool (programming > > is interesting by itself, but it's mostly a tool still) before having > > any use for such tool or desire to learn it. And this may lead to > > someone with no passion to solve problems and learn. > > > > Bye, > > bearophile > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Fri Dec 5 14:35:41 2008 From: castironpi at gmail.com (Aaron Brady) Date: Fri, 5 Dec 2008 11:35:41 -0800 (PST) Subject: Don't you just love writing this sort of thing :) References: Message-ID: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> On Dec 5, 4:32?am, Lawrence D'Oliveiro wrote: > The code people write is probably a direct reflection of their thinking > processes: For example, slow, plodding, one step at a time, incapable of > imaginative leaps, versus those who operate directly on larger patterns at > once... That distinction operates indirectly on smaller patterns. There are two types of people. Those who can grasp this distinction, and those who cannot. From ajaksu at gmail.com Wed Dec 24 21:43:34 2008 From: ajaksu at gmail.com (ajaksu) Date: Wed, 24 Dec 2008 18:43:34 -0800 (PST) Subject: Easy-to-use Python GUI References: Message-ID: On Dec 24, 9:47?pm, "Joel Koltner" wrote: > ?Dim dlg As UserDialog > > ?dlg.genDrill = 1 > ?ReDim DrillStyle(1) > ?DrillStyle(0) = "All Via Layers In One File" > ?DrillStyle(1) = "One File Per Via Layer" > ?dlg.drillStyle = 1 > > ?func=Dialog(dlg) > > --- > > This is pretty darned easy for me understand and modify either by hand or with > the GUI builder. ?Still, it's quite powerful, since it supports all the common > GUI elements (text, group boxes, checkboxes, drop-down lists, text boxes, > buttons, etc.). ?This is about the level of sophistication I'm looking for. > > Anything like this for Python? I have not used it (yet), but Treethon looks like what you want: --- _import: gtk view: gtk.Window() add: - view: gtk.Button('Hello World') on clicked: print view.get_label() --- Check http://pypi.python.org/pypi/treethon/ and http://code.google.com/p/treethon/ If you can report back on treethon, I'd like to hear about it :) HTH, Daniel From ndbecker2 at gmail.com Mon Dec 1 12:41:24 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Mon, 01 Dec 2008 12:41:24 -0500 Subject: optimization Message-ID: I noticed in some profiling, that it seems that: def Func (): def something(): ... It appears that if Func is called many times, this nested func definition will cause significant overhead. Is this true? I guess I've become accustomed to decent compilers performing reasonable transformations and so have tended to write code for clarity. From dickinsm at gmail.com Thu Dec 18 16:09:03 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 18 Dec 2008 13:09:03 -0800 (PST) Subject: Factoring Polynomials References: <5dfe1cf3-530d-4e31-833e-e26db85611be@d36g2000prf.googlegroups.com> Message-ID: On Dec 18, 8:47?pm, Scott David Daniels wrote: > ? ? ?else: # a single result (discriminant is zero) > ? ? ? ? ?return (-b / (2 * a),) Maybe make that (-b / (2. * a)) to avoid getting funny results when a and b are integers. (Or do a from __future__ import division, or use Python 3.0, or ....) And to make the function more bullet-proof, you might want to do something like (untested): from math import copysign [rest of example as in Scott's post] if discriminant: # two results root1 = (-b - copysign(discriminant, b))/(2*a) root2 = c/(a*root1) return (root1, root2) to avoid numerical problems when b*b is much larger than abs(a*c). Compare with the results of the usual formula when a = c = 1, b = 10**9, for example. But that still doesn't help you when the computation of the discriminant underflows or overflows... Isn't floating-point a wonderful thing! :) Mark From imageguy1206 at gmail.com Tue Dec 9 10:05:48 2008 From: imageguy1206 at gmail.com (imageguy) Date: Tue, 9 Dec 2008 07:05:48 -0800 (PST) Subject: dBase III files and Visual Foxpro 6 files References: Message-ID: <8cf816c5-99c3-41c4-8610-8dbe5a8b8fc3@k1g2000prb.googlegroups.com> On Dec 8, 2:53?am, Ethan Furman wrote: > Greetings All! > > I nearly have support complete for dBase III dbf/dbt files -- just > wrapping up support for dates. ?The null value has been a hindrance for > awhile but I nearly have that solved as well. > > For any who know of a cool dbf module already in existence for dBase III > and Visual Foxpro -- where were you six months ago when I was searching? > ? ;) ?Seriously, though, this has been a great learning experience for me. > > As I said -- dbf/dbt files are 99% ready. ?idx files -- no support: ?for > my purposes I just don't need them. ?I've found no problem in loading > tables up to 300,000 records with 50 fields per record, and re-ordering > them on the fly in memory. > > However, after putting much effort into this code, and wanting it to be > useful to others in the community, are there others who work with dbf > files that would need idx/cdx support? ?Or tables so large they won't > fit comfortably into memory? > > ~ethan~ I occasionally need access to dbf files. In the past I have used the recipe found in the python cookbook on the activestate website. I do not need access to the idx/cdx as I have found that loading the records from the table into memory worked well for me too. If/When you release would enjoy having a peak. g. From mensanator at aol.com Sat Dec 6 12:08:14 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 6 Dec 2008 09:08:14 -0800 (PST) Subject: RELEASED Python 3.0 final References: <874p1jux8u.fsf@benfinney.id.au> <87iqpyt80i.fsf@benfinney.id.au> Message-ID: On Dec 5, 12:29?pm, "Hendrik van Rooyen" wrote: > "Ben Finney" wrote: > >I hereby recommend ?pish and tosh? for use by anyone who wants to > >counter someone's point. It beats by a country furlong the invective > >that has become regrettably common here in recent months. > > I second the motion to use pish and tosh for a first level of disagreement. > > I recommend the rather archaic "Balderdash" as the next step in the > escalation of disagreement... As a W.C. Fields fan, I love his "non-swearing" vocabulary: - Drat - Dag nab it - Holy Mother of Pearl! etc. > > - hendrik From rt8396 at gmail.com Sat Dec 20 19:01:58 2008 From: rt8396 at gmail.com (r) Date: Sat, 20 Dec 2008 16:01:58 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> <59153e28-bf86-4158-96d9-23aa5b9f0205@j35g2000yqh.googlegroups.com> <7889a362-d96e-4f1f-a66b-ef52b9cdb047@q26g2000prq.googlegroups.com> <85f91606-b589-425d-9636-4636c8ccbc4f@r34g2000vbp.googlegroups.com> Message-ID: <6b4176c3-49ce-4e7c-bced-07d8d19bc0f4@s20g2000yqh.googlegroups.com> Just to be on record, i am OK with adding a new way to do this as long as the old C style str format does not ever go away. I don't like 20 ways to do the same thing, but i really like the compact way of %formating now. My complaint is the deprecation of %formating. Maybe i'll use the new syntax to print a tuple or two, but that is the only use i have for it ;). Slowing down Python even more than it is, is suicide. Sure high level languages are slower than there complied brethren, but a line has to be drawn in the sand somewhere. As CPU speeds increase so does the complexity's of modern software. GUI toolkits hog more resources as they need eye pleasing "glass effects". You can't just blindly Parrot off.. "well CPU's get faster every year". Python must stay fast, and simplistic(but not too simplistic), to compete with other high level languages. From tavares at fe.up.pt Tue Dec 9 17:50:18 2008 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Tue, 9 Dec 2008 14:50:18 -0800 (PST) Subject: EURASIP JASP - Special issue on Image Processing and Analysis in Biomechanics - Announce & Call for papers Message-ID: <402605af-3176-4e6c-badd-fb7dc6f0cab5@z27g2000prd.googlegroups.com> ------------------------------------------------------------------------------------------------------------------------------------------ (Apologies for cross-posting) EURASIP Journal on Advances in Signal Processing Special issue on Image Processing and Analysis in Biomechanics http://www.hindawi.com/journals/asp/si/ipab.html Announce and Call for papers We would appreciate if you could distribute this information by your colleagues and co-workers. ------------------------------------------------------------------------------------------------------------------------------------------ Dear Colleague, A critical component for true realistic biomechanical analysis and simulations is to obtain accurately, from images, the geometric data and the behavior of the desired structures. For that, the use of automatic, efficient, and robust techniques of image processing and analysis is mandatory. The main objective of this Special Issue, of the EURASIP Journal on Advances in Signal Processing, on Image Processing and Analysis in Biomechanics is to bring together recent advances in the related fields (not limited to): - Signal processing in biomechanical applications; - Data interpolation, registration, acquisition and compression in biomechanics; - Segmentation of objects in images for biomechanical applications; - 3D reconstruction of objects from images for biomechanical applications; - 2D/3D tracking and object analysis in images for biomechanical applications; - 3D vision in biomechanics; - Biomechanical applications involving image processing and analysis algorithms; - Virtual reality in biomechanics; - Software development for image processing and analysis in biomechanics. Submission Instructions & Important Dates: Authors should follow the journal manuscript format (http:// www.hindawi.com/journals/asp/) and submit their manuscript through the journal Manuscript Tracking System (http://mts.hindawi.com/), according to the following timetable: - Manuscript Due: May 1, 2009; - First Round of Reviews: August 1, 2009; - Publication Date: November 1, 2009. Lead Guest Editor Jo?o Manuel R. S. Tavares, University of Porto, Portugal (tavares at fe.up.pt) Guest Editor R. M. Natal Jorge, University of Porto, Portugal (rnatal at fe.up.pt) From castironpi at gmail.com Sat Dec 13 15:28:22 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 13 Dec 2008 12:28:22 -0800 (PST) Subject: Problems running on HP Intel duo core machine References: <200809221443.25765.inq1ltd@inqvista.com> <200812111458.16157.inq1ltd@inqvista.com> Message-ID: <262d674e-28cc-489b-b058-b7aee9b9172f@o4g2000pra.googlegroups.com> On Dec 11, 3:16?pm, jim-on-linux wrote: > Aaron, > > The TraceBack is : > > TraceBack: > File win32ui.pyc, line 12, in > File win32ui.pyc Line 10, in _load > ImportError: DLL Load Failed: The specified module > could not be found. snip > > Both modules 'win32api.pyd' ?and win32ui.pyd are in > > the same directory. > > > Below is a copy of the win32ui.py module. The only > > difference between this and win32api.py module is > > the name that is installed when creating the path. > > > def __load(): > > ? ? import imp, os, sys > > ? ? try: > > ? ? ? ? dirname = > > os.path.dirname(__loader__.archive) except > > NameError: > > ? ? ? ? dirname = sys.prefix > > ? ? path = os.path.join(dirname, 'win32ui.pyd') > > ? ? #print "py2exe extension module", __name__, > > "->", path > > ? ? mod = imp.load_dynamic(__name__, path) > > ## ? ?mod.frozen = 1 > > __load() > > del __load snip 'load_dynamic' help says this: "(Note: using shared libraries is highly system dependent, and not all systems support it.)" You can try this: create a bare-bones shared library, 'temp_load.pyd' perhaps, place it in the folder, and create 'temp_load.py' there too, as follows: import imp imp.load_dynamic( 'temp_load', 'temp_load.pyd' ) That will tell us if the problem is Python or win32ui. From collin.day.0 at gmail.com Thu Dec 18 14:37:35 2008 From: collin.day.0 at gmail.com (collin.day.0 at gmail.com) Date: Thu, 18 Dec 2008 11:37:35 -0800 (PST) Subject: Factoring Polynomials Message-ID: I am trying to write a simple application to factor polynomials. I wrote (simple) raw_input lines to collect the a, b, and c values from the user, but I dont know how to implement the quadratic equation x = (-b +or- (b^2 - 4ac)^1/2) / 2a into python. Any ideas? From steve at holdenweb.com Mon Dec 22 12:04:48 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 22 Dec 2008 12:04:48 -0500 Subject: Python's popularity In-Reply-To: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: walterbyrd wrote: > I have read that python is the world's 3rd most popular language, and > that python has surpassed perl in popularity, but I am not seeing it. [rest of stuff adequately answered by other posters] The "Python has surpassed Perl" myth came from one month's results on the TIOBE index, which does not claim to use a scientifically justifiable methodology. Python *is* becoming very popular. Training demand is certainly going up. It's a great language for people whose primary career isn't programming but who need to do some programming - for example, there are about 40 scientists and engineers supporting the Mars Lander project using Python code, because it's a great way to put systems together that other engineers can understand. I try to discourage people from getting into language pissing contests, because they are rarely productive. The short answer is that nobody really knows how popular the various languages are, there are simply estimates with higher or lower credibility. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From stefan_ml at behnel.de Tue Dec 30 08:26:37 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 30 Dec 2008 14:26:37 +0100 Subject: Any equivalent to Ruby's 'hpricot' html/xpath/css selector package? In-Reply-To: <4958a2d7$0$15461$426a74cc@news.free.fr> References: <4958a2d7$0$15461$426a74cc@news.free.fr> Message-ID: <495a218d$0$31871$9b4e6d93@newsspool3.arcor-online.net> Bruno Desthuilliers wrote: >> However, what makes it really useful is that it does a good job of >> handling the "broken" html that is so commonly found on the web. > > BeautifulSoup ? > http://pypi.python.org/pypi/BeautifulSoup/3.0.7a > > possibly with ElementSoup ? > http://pypi.python.org/pypi/ElementSoup/rev452 It's actually debatable if BS is any better than lxml/libxml2 when parsing broken HTML, as lxml tends to tidy things up pretty well. The only major difference is in encoding detection, for which you can also use a separate tool like chardet: http://chardet.feedparser.org/ Stefan From rhf22 at mole.bio.cam.ac.uk Mon Dec 8 09:24:59 2008 From: rhf22 at mole.bio.cam.ac.uk (Rasmus Fogh) Date: Mon, 8 Dec 2008 14:24:59 +0000 (GMT) Subject: Rich Comparisons Gotcha Message-ID: Rober Kern wrote: >James Stroud wrote: >> Steven D'Aprano wrote: >>> On Sun, 07 Dec 2008 13:57:54 -0800, James Stroud wrote: >>>> Rasmus Fogh wrote: >>>>>>>> ll1 = [y,1] >>>>>>>> y in ll1 >>>>> True >>>>>>>> ll2 = [1,y] >>>>>>>> y in ll2 >>>>> Traceback (most recent call last): >>>>> File "", line 1, in >>>>> ValueError: The truth value of an array with more than one element is >>>>> ambiguous. Use a.any() or a.all() >>>> I think you could be safe calling this a bug with numpy. >>> Only in the sense that there are special cases where the array >>> elements are all true, or all false, and numpy *could* safely return a >>> bool. But special cases are not special enough to break the rules. >>> Better for the numpy caller to write this: >>> a.all() # or any() >>> instead of: >>> try: >>> bool(a) >>> except ValueError: >>> a.all() >>> as they would need to do if numpy sometimes returned a bool and >>> sometimes raised an exception. >> I'm missing how a.all() solves the problem Rasmus describes, namely that >> the order of a python *list* affects the results of containment tests by >> numpy.array. E.g. "y in ll1" and "y in ll2" evaluate to different >> results in his example. It still seems like a bug in numpy to me, even >> if too much other stuff is broken if you fix it (in which case it >> apparently becomes an "issue"). > It's an issue, if anything, not a bug. There is no consistent > implementation of > bool(some_array) that works in all cases. numpy's predecessor Numeric > used to > implement this as returning True if at least one element was non-zero. > This > works well for bool(x!=y) (which is equivalent to (x!=y).any()) but does > not > work well for bool(x==y) (which should be (x==y).all()), but many people > got > confused and thought that bool(x==y) worked. When we made numpy, we > decided to > explicitly not allow bool(some_array) so that people will not write > buggy code like this again. You are so right, Robert: > The deficiency is in the feature of rich comparisons, not numpy's > implementation of it. __eq__() is allowed to return non-booleans; > however, there are some parts of Python's implementation like > list.__contains__() that still expect the return value of __eq__() to be > meaningfully cast to a boolean. One might argue if this is a deficiency in rich comparisons or a rather a bug in list, set and dict. Certainly numpy is following the rules. In fact numpy should be applauded for throwing an error rather than returning a misleading value. For my personal problem I could indeed wrap all objects in a wrapper with whatever 'correct' behaviour I want (thanks, TJR). It does seem a bit much, though, just to get code like this to work as intended: alist.append(x) print ('x is present: ', x in alist) So, I would much prefer a language change. I am not competent to even propose one properly, but I'll try. First, to clear the air: Rich comparisons, the ability to overload '==', and the constraints (or lack of them) on __eq__ must stay unchanged. There are reasons for their current behaviour - ieee754 is particularly convincing - and anyway they are not going to change. No point in trying. There remains the problem is that __eq__ is used inside python 'collections' (list, set, dict etc.), and that the kind of overloading used (quite legitimately) in numpy etc. breaks the collection behaviour. It seems that proper behaviour of the collections requires an equality test that satisfies: 1) x equal x 2) x equal y => y equal x 3) x equal y and y equal z => x equal z 4) (x equal y) is a boolean 5) (x equal y) is defined (and will not throw an error) for all x,y 6) x unequal y == not(x equal y) (by definition) Note to TJR: 5) does not mean that Python should magically shield me from errors. All I am asking is that programmers design their equal() function to avoid raising errors, and that errors raised from equal() clearly count as bugs. I cannot imagine getting the collections to work in a simple and intuitive manner without an equality test that satisfies 1)-6). Maybe somebody else can. Instead I would propose adding an __equal__ special method for the purpose. It looks like the current collections use the folowing, at least in part def oldCollectionTest(x,y): if x is y: return True else: return (x == y) I would propose adding a new __equal__ method that satisfies 2) - 6) above. We could then define def newCollectionTest(x,y): if x is y: # this takes care of satisfying 1) return True elif hasattr(x, '__equal__'): return x.__equal__(y) elif hasattr(y, '__equal__'): return y.__equal__(x) else: return False The implementations for list, set and dict would then behave according to newCollectionTest. We would also want an equal() built-in with the same behaviour. In plain words, the default behaviour would be identity semantics. Objects that wanted value semantics could implement an __equal__ function with the correct behaviour. Wherever possible __equal__ would be the same as __eq__. This function may deviate from 'proper' behaviour in some cases. All I claim for it is that it makes collections work as intended, and that it is clear and explicit, and reasonably intuitive. Backwards compatibility should not be a big problem. The only behaviour change would be that list, set, and dict would now behave the way it was always assumed they should - and the way the documentation says they should. On the minus side there would be the difference between '__equal__' and '__eq__' to confuse people. On the plus side the behaviour of objects inside collections would now be explicitly defined, and __eq__ and __equal__ would be so similar that most people could ignore the distinction. Some examples: # NaN: # For floats, __equal__ would be the same as __eq__. For NaN this gives >>> x = float('NaN') >>> y = float('NaN') >>> x == x False >>> equal(x,x) True >>> equal(x,y) False # It may be problematical mathematically, but computationally it makes # perfect sense that looking in a given storage location will give you the # same value every time, even if the actual value happens to be undefined. # The behaviour is simple to describe, and indeed NaN does behave this way # in collections at the moment. All we are doing is documenting it clearly. # numpy Numpy would have no __equal__ function, so we would have pure identity semantics - 'equals(x,y)' would be the same as 'x is y' # ordinary numbers. Any Python object with value semantics would need an __equal__ function with the correct behaviour. Mark Dickinson pointed out the thread "Comparing float and decimal", which shows that comparisons between float and decimal numbers do not currently satisfy 3). It would not be attractive to have __equal__ and __eq__ behave differently for ordinary numbers, so if the relevant __eq__ can not be fixed that is a problem for my proposal. At this point I shall try to retire gracefully. Regrettably I am not competent to discuss if this can be done, how it can be done, and how much work is required. Rasmus --------------------------------------------------------------------------- Dr. Rasmus H. Fogh Email: r.h.fogh at bioc.cam.ac.uk Dept. of Biochemistry, University of Cambridge, 80 Tennis Court Road, Cambridge CB2 1GA, UK. FAX (01223)766002 From eric at ericaro.net Thu Dec 18 18:42:10 2008 From: eric at ericaro.net (eric) Date: Thu, 18 Dec 2008 15:42:10 -0800 (PST) Subject: Which sparse matrix package? References: <20081218231851.70dd91e2@Schlamber.localdomain> Message-ID: <1a42d287-aea2-408c-bad5-3c0446a50f8b@y1g2000pra.googlegroups.com> On Dec 18, 11:52?pm, MRAB wrote: > James Mills wrote: > > On Fri, Dec 19, 2008 at 8:18 AM, Martin Manns wrote: > >> Hi: > > > Hi, > > >> I am writing a spreadsheet application in Python > > > What's wrong with pyspread ? > > > [ ... snip ... ] > > >> The dict that I tried out is of the type: > > >> {(1,2,3): "2323", (1,2,545): "2324234", ... } > > >> It is too slow for my application when it grows. One slicing operation > >> with list comprehensions takes about 1/2 s on my computer for 1E6 > >> elements. > > > Let me get this straight. > > It's taking 0.5s to slice your matrix > > of 1E7 (10000000.0 rows/columns) > > > Are you mad ? This is TEN Millions and you > > required it faster than 0.5s ? > > No, 1E6, or ONLY 1 million. :-) what does Internet explorer 6 & 7 have to do with that ? ;-) > > > Am I missing something here ? > > Would a matrix of matrices work better, ie a supermatrix where each > element is either a submatrix of cells or None if the submatrix is > empty? How much memory it would save would depend on how sparse the > matrix is. sparse matrix efficiency is all about guessing the probability for a cell to be empty. My guess is that the probability for a cell (i,j) to be empty grows with norm(i,j) then, you should store your data in a list, and the indexes in another "list", then use a BTree like algorithm, or keep you data ordered by norm(i,j) growing. something like: data = [] # kernel =[] # full of couples (i,j) def add(i,j,value): data.append(value) # or put in the "right place" to keep it sorted kernel.append(i,j) # same comment def get(i,j): k = kernel_of(i,j) return data[k] def set(i,j,value): if is_probably_empty(): k = kernel_of(i,j) if k: data[k]= value else: add(i,j,value) else: add(i,j,value) where the 'kernel_of method" can take advantage of the sorted order (i*j or max(i,j) should be as good) to make a fast dichotomy. The set method is about finding if the cell is 'empty or not' and then either perform an indexof, or a add. to efficiently know if a cell is empty (the is_probably_empty method) or not, try to use the bloom filter using i*j%m as hash function (for instance) here arrays have the size of your actual data (maybe thousands of cell for a huge spreadsheet), that's MUCH better than the size of the maxN*maxM if my memory is correct, there is room in numpy for your own sparse matrix implementation. You should try it with your own sparse matrix implementation. -- Eric http://codeslash.blogspot.com From rdmurray at bitdance.com Wed Dec 17 11:04:42 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Wed, 17 Dec 2008 16:04:42 +0000 (UTC) Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> Message-ID: Quoth walterbyrd : > For a language as well structured as Python, this seems somewhat > sloppy, and inconsistant. Or is there some good reason for this? Yes. It's called Object Oriented Programming. > Here is what I mean: > > def a(): > x = 99 > print x > > def b(): > print x > > a() > b() # raises an exception because x is not defined. > > However in the methods are within a class, the scoping seems to work > differently. > > class ab(): > def a(self): > self.x = 99 > print self.x > def b(self): > print self.x > > i = ab() > i.a() > i.b() # this works, why no lexical scoping? Because x is an attribute. If you don't understand what that means, read any introductory article on OOP. To give you a clue, if you had said: class ab(): def a(self): x = 99 print x def b(self): print x You'd have gotten the exception you expected (assuming x wasn't defined globally). --RDM From bdesth.quelquechose at free.quelquepart.fr Sun Dec 14 11:36:28 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 14 Dec 2008 17:36:28 +0100 Subject: Need help improving number guessing game In-Reply-To: <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> Message-ID: <494543c2$0$1127$426a74cc@news.free.fr> feba a ?crit : > #!/usr/bin/python > #Py3k, UTF-8 > > import random > > def startup(): > print("WELCOME TO THE SUPER NUMBER GUESSING GAME!") > global pnum, play, player, p1sc, p2sc You should now try to rewrite the whole thing to avoid using globals. > pnum = int(input("1 OR 2 PLAYERS?\n> ")) What happens here if you type something that's not a valid argument for int() ? (snip) From rdcollum at gmail.com Sun Dec 28 18:11:53 2008 From: rdcollum at gmail.com (Roger) Date: Sun, 28 Dec 2008 15:11:53 -0800 (PST) Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <0167cbf7$0$6988$c3e8da3@news.astraweb.com> <676bffeb-4b07-4226-8c14-7da57d94351b@f13g2000yqj.googlegroups.com> <3afba310-dcde-4dc1-825a-7c63b97e2a40@w1g2000prk.googlegroups.com> Message-ID: <45cb0c85-ff4d-4f7a-9eeb-ac68f29cd689@k1g2000prb.googlegroups.com> On Dec 28, 5:12?pm, John Machin wrote: > On Dec 29, 7:06?am, Roger wrote: > > > > > > Curious. When I see a bare return, the first thing I think is that the > > > author forgot to include the return value and that it's a bug. > > > > The second thing I think is that maybe the function is a generator, and > > > so I look for a yield. If I don't see a yield, I go back to thinking > > > they've left out the return value, and have to spend time trying to > > > understand the function in order to determine whether that is the case or > > > not. > > > > In other words, even though it is perfectly valid Python, bare returns > > > always make the intent of the function less clear for me. I'm with Bruno > > > -- if you have a function with early exits, and you need to make the > > > intent of the function clear, explicitly return None. Otherwise, leave it > > > out altogether. > > > > -- > > > Steven > > > To me this is the soundest argument. ?Thanks for the advice. ?I think > > I'll follow this as a rule of thumb hereafter. > > Please don't. Follow MRAB's advice, with the corollary that a > generator is forced by the compiler to be a "procedure" in MRAB's > terminology. Yup, this is what I took away from this discussion. Thanks! From trentm at activestate.com Fri Dec 12 18:16:44 2008 From: trentm at activestate.com (Trent Mick) Date: Fri, 12 Dec 2008 15:16:44 -0800 Subject: ActivePython 2.6.1.1 and 3.0.0.0 released! Message-ID: <4942F0DC.7080005@activestate.com> I'm happy to announce that ActivePython 2.6.1.1 and ActivePython 3.0.0.0 are now available. Details and download links for 2.6 here: http://www.activestate.com/Products/activepython/feature_list.mhtml Details and download links for 3.0 here: http://www.activestate.com/Products/activepython/python3.mhtml All ActivePython downloads (e.g. for older releases) are available here: http://downloads.activestate.com/ActivePython/ ActivePython 3.0.0.0 is the first release of ActivePython for Python 3. ActivePython 2.6.1.1 is a patch release based on Python 2.6.1. What is ActivePython? --------------------- ActivePython is ActiveState's binary distribution of Python. Builds for Windows, Mac OS X, Linux, HP-UX and AIX are made freely available. ActivePython includes the Python core and the many core extensions: zlib and bzip2 for data compression, the Berkeley DB (bsddb) and SQLite (sqlite3) database libraries, OpenSSL bindings for HTTPS support, the Tix GUI widgets for Tkinter, ElementTree for XML processing, ctypes (on supported platforms) for low-level library access, and others. The Windows distribution ships with PyWin32 -- a suite of Windows tools developed by Mark Hammond, including bindings to the Win32 API and Windows COM. Note that currently PyWin32 is not included in ActivePython 3.0. See this page for full details: http://docs.activestate.com/activepython/2.6/whatsincluded.html http://docs.activestate.com/activepython/3.0/whatsincluded.html As well, ActivePython ships with a wealth of documentation for both new and experienced Python programmers. In addition to the core Python docs, ActivePython includes the "What's New in Python" series, "Dive into Python", the Python FAQs & HOWTOs, and the Python Enhancement Proposals (PEPs). An online version of the docs can be found here: http://docs.activestate.com/activepython/2.6/welcome.html We would welcome any and all feedback to: ActivePython-feedback at activestate.com.com Please file bugs against ActivePython at: http://bugs.activestate.com/query.cgi?set_product=ActivePython On what platforms does ActivePython run? ---------------------------------------- ActivePython includes installers for the following platforms: - Windows/x86 - Mac OS X - Linux/x86 - Linux/x86_64 ("x86_64" is also known as "AMD64") - Solaris/SPARC - Solaris/SPARC (64-bit) - Solaris/x86 - HP-UX/PA-RISC - AIX/PowerPC Extra Bits ---------- ActivePython releases also include the following: - ActivePython26.chm & ActivePython30.chm: An MS compiled help collection of the full ActivePython documentation set. Linux users of applications such as xCHM might find this useful. This package is installed by default on Windows. Extra bits are available from: http://downloads.activestate.com/ActivePython/etc/ Thanks, and enjoy! Trent, Python Tech Lead -- Trent Mick http://planet.activestate.com/ trentm at activestate.com From tjreedy at udel.edu Mon Dec 29 14:25:27 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Dec 2008 14:25:27 -0500 Subject: why cannot assign to function call In-Reply-To: <97a11245-a034-4558-82d4-0c87e02bdb7e@u18g2000pro.googlegroups.com> References: <97a11245-a034-4558-82d4-0c87e02bdb7e@u18g2000pro.googlegroups.com> Message-ID: John Machin wrote: > On Dec 29, 5:01 pm, scsoce wrote: >> I have a function return a reference, > > Stop right there. You don't have (and can't have, in Python) a > function which returns a reference that acts like a pointer in C or C+ > +. Please tell us what manual, tutorial, book, blog or Usenet posting > gave you that idea, Perhaps the ones claiming that Python is 'call by reference' and hence, by implication, at least, 'return by reference'. > and we'll get the SWAT team sent out straight away. I and others have posted many times that such a viewpoints leads to confusion, such as in this post. tjr From news123 at free.fr Sat Dec 6 13:23:38 2008 From: news123 at free.fr (News123) Date: Sat, 06 Dec 2008 19:23:38 +0100 Subject: Learning Python now coming from Perl In-Reply-To: References: Message-ID: <493ac32b$0$30907$426a74cc@news.free.fr> I fully agree with Roy's answer. COding small tasks is a good starting point. For quite some time you'll be of course less efficient than with your previous language, but that's part of the learning curve, isn't it. I guess you'll learn the syntax rather quickly. What's more painful is to learn which functianilty is in which library and which library exists. There's of course a lot of online documentation, but often you find answers to trivial python questions fastest with Google: for example: search for something like "python string reverse example" And there's of course this newsgroup whenever you're stuck with a 'missing' feature, (though mostly the features aren't missing, but just a little different) bye N Roy Smith wrote: > In article , > Bertilo Wennergren wrote: > >> I'm planning to start learning Python now, using Python 3000. >> I have no previous Python skills, >> . . . > > I assume you use Perl to solve real problems in whatever job you do. My > recommendation would be the next time some problem comes up that you would > normally solve with Perl, try doing it in Python. Having a real task that > you need to accomplish is a great way to focus the mind. For your first > project, pick something that's small enough that you think you could tackle > it in under 50 lines of Perl. > > One of the very first things you'll probably discover that's different > between Perl and Python is how they handle string pattern matching. In > Perl, it's a built in part of the language syntax. In Python, you use the > re module. The regular expressions themselves are the same, but the > mechanism you use to apply them to input text is quite different. From andrew at doadesweb.co.uk Wed Dec 10 14:19:48 2008 From: andrew at doadesweb.co.uk (Andrew Doades) Date: Wed, 10 Dec 2008 19:19:48 +0000 Subject: get todays files In-Reply-To: <494015F7.3020302@tim.thechases.com> References: <4632c353-0462-485b-9e1b-6a5c56682363@s9g2000prg.googlegroups.com> <494015F7.3020302@tim.thechases.com> Message-ID: <49401654.5090505@doadesweb.co.uk> Tim Chase wrote: >> This looks very good and I have tested successfully, but is there a >> way I can set the today to automatically become todays date in that >> format? > > Yes...see the python datetime module[1]...particularly the strftime() > call on date/datetime objects. > > -tkc > > [1] > http://docs.python.org/library/datetime.html Thanks Tim, I got it in there myself. Thanks for all your help with this and the links proved very useful and interesting reads. Andrew From steve at REMOVE-THIS-cybersource.com.au Fri Dec 12 17:40:39 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Dec 2008 22:40:39 GMT Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> Message-ID: <0152dfee$0$8244$c3e8da3@news.astraweb.com> On Fri, 12 Dec 2008 10:08:23 -0600, Kirk Strauser wrote: > At 2008-12-12T15:51:15Z, Marco Mariani writes: > >> Filip Gruszczy?ski wrote: >> >>> I am not doing it, because I need it. I can as well use "if not elem >>> is None", > >> I suggest "if elem is not None", which is not quite the same. > > So what's the difference exactly? "foo is not None" is actually > surprising to me, since "not None" is True. "0 is True" is False, but > "0 is not None" is True. Why is that? "a is not b" uses a single operator to do the test. >>> import dis >>> x = compile('a is not b', '', 'single') >>> dis.dis(x) 1 0 LOAD_NAME 0 (a) 3 LOAD_NAME 1 (b) 6 COMPARE_OP 9 (is not) 9 PRINT_EXPR 10 LOAD_CONST 0 (None) 13 RETURN_VALUE "not a is b" looks like it would use two operators (is, followed by not) but wonderfully, Python has a peephole optimization that fixes that micro inefficiency: >>> x = compile('not a is b', '', 'single') >>> dis.dis(x) 1 0 LOAD_NAME 0 (a) 3 LOAD_NAME 1 (b) 6 COMPARE_OP 9 (is not) 9 PRINT_EXPR 10 LOAD_CONST 0 (None) 13 RETURN_VALUE So if you are using at least Python 2.5, the two expressions don't just return the same result, they actually generate the same byte code. -- Steven From rhamph at gmail.com Mon Dec 22 04:16:30 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 22 Dec 2008 01:16:30 -0800 (PST) Subject: Are python objects thread-safe? References: Message-ID: On Dec 21, 11:51?am, RajNewbie wrote: > Say, I have two threads, updating the same dictionary object - but for > different parameters: > Please find an example below: > a = {file1Data : '', > ? ? ? ?file2Data : ''} > > Now, I send it to two different threads, both of which are looping > infinitely: > In thread1: > a['file1Data'] = open(filename1).read > ? ? ? ? ? and > in thread2: > a['file2Data'] = open(filename2).read > > My question is ?- is this object threadsafe? - since we are working on > two different parameters in the object. Or should I have to block the > whole object? In general, python makes few promises. It has a *strong* preference towards failing gracefully (ie an exception rather than a segfault), which implies atomic operations underneath, but makes no promise as to the granularity of those atomic operations. In practice though, it is safe to update two distinct keys in a dict. From stefan_ml at behnel.de Wed Dec 3 00:54:55 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 03 Dec 2008 06:54:55 +0100 Subject: Reverse zip() ? In-Reply-To: References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> <333edbe80812021647i4621271p7f87dff8d0926951@mail.gmail.com> Message-ID: <49361f2f$0$31333$9b4e6d93@newsspool4.arcor-online.net> Zac Burns wrote: > More succinct failure: > > keys, values = zip(*{}.iteritems()) Simple fix: some_iterable = {}.iteritems() keys, values = zip(*list(some_iterable)) or: keys, values = zip(*(some_iterable if isinstance(some_iterable, (list, tuple)) else list(some_iterable))) Stefan From phil at freehackers.org Mon Dec 1 04:37:05 2008 From: phil at freehackers.org (BlueBird) Date: Mon, 1 Dec 2008 01:37:05 -0800 (PST) Subject: How to distribute a Python app together with its dependencies? References: Message-ID: <35377946-378c-484d-88cc-396145090d2f@l39g2000yqn.googlegroups.com> Alessio Pace wrote: > Hi, > > I have to distribute a Python application which relies on an external > library, and I'm not very fluent in this kind of stuff with Python (I > come from the Java world where I would have used the Maven build tool > to create an "assembly with dependencies" of all it is needed to run > the app), so I was wondering if someone here could give me some > suggestions :-) > > The external library is generally not present on the machines where I > have to distribute my app, and the set of machines on which I have to > distribute this application is not known a priori (it is just known > they are Unix systems). In fact by means of SSH I will have to copy > (and install) the app+library and make it runnable onto the specified > destination(s). I have never used it myself, but bbfreeze claims to create packaged versions of an application, for windows and Unix : http://pypi.python.org/pypi/bbfreeze/0.95.2 cheers, Philippe From de.slotenzwemmer at gmail.com Thu Dec 25 06:56:34 2008 From: de.slotenzwemmer at gmail.com (Dennis van Oosterhout) Date: Thu, 25 Dec 2008 12:56:34 +0100 Subject: os.system('cls') In-Reply-To: <05BADA85-33ED-48BF-B251-2CC830D6D55E@rgbaz.eu> References: <05BADA85-33ED-48BF-B251-2CC830D6D55E@rgbaz.eu> Message-ID: Hello Arno, thanks for the explanation! I have one more question: on the python site it says it's better to replace the system commands by subprocess and Popen. Now I searched for some good example for my specific case (as I have no idea how it should work and I don't get it any clearer by reading http://docs.python.org/3.0/library/subprocess.html#module-subprocess) and I found this: > import subprocess > def clear(): > subProcess.Popen('clear') But it just doesn't seem to work. Would you have any idea how it would work? Once more thanks for the first answer, Devilly 2008/12/25 Python > > On 25 dec 2008, at 11:22, Dennis van Oosterhout wrote: > >> Hi there! I was searching for a way to clear the 'DOS screen'/command screen etc. and found that os.system('cls') works for this. I was just wondering where I can find al the commands which can be used for os.system(). I searched with google but I didn't find an answer. In the official python tutorial it says os.system('command') executes the command, but it doesn't say which commands exist (or I'm just blind). >> >> Does anyone have an answer for this question? >> >> Thanks, >> >> Devilly > > Hey Deville, > > > os.system() executes commands that you usually use in a shell outside python. > so in the case of you being a windows user, you replace 'command' with any DOS > command. > > gr > Arno From sonicsai at gmail.com Tue Dec 23 05:10:04 2008 From: sonicsai at gmail.com (sai) Date: Tue, 23 Dec 2008 02:10:04 -0800 Subject: turtle ? Message-ID: <41d04d600812230210s5b90aa0cud8a3161ca816c80e@mail.gmail.com> python newbie here :-) I am trying to get turtle to run but got stuck here: $ python Python 2.5.2 (r252:60911, Aug 5 2008, 16:17:28) [GCC 4.2.2 20071128 (prerelease) (4.2.2-3.1mdv2008.0)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import turtle Traceback (most recent call last): File "", line 1, in ImportError: No module named turtle I have used google to search the web and the newsgroup but got nothing. The Linux distro is Mandriva, if that makes a difference. sai From paul.hermeneutic at gmail.com Fri Dec 5 10:05:47 2008 From: paul.hermeneutic at gmail.com (Paul Watson) Date: Fri, 05 Dec 2008 09:05:47 -0600 Subject: Running Python 2 and Python 3 on the same machine In-Reply-To: <49387f7e$0$27857$9b622d9e@news.freenet.de> References: <1228424486.5873.6.camel@linux-3eb6.site> <49387f7e$0$27857$9b622d9e@news.freenet.de> Message-ID: <1228489547.5613.10.camel@linux-3eb6.site> On Fri, 2008-12-05 at 02:10 +0100, "Martin v. L?wis" wrote: > > Since the source code is incompatible, I was expecting the Python > > executable to have a new name such as 'python3' > > It does: the executable is called python3.0. > > > or for the default > > source code filename to change to '.py3' or something. > > Such a proposal would be rejected. In a few years from now, Python 2 > will be gone, and we would be stuck with an ugly file extension > (similar to how \windows\system is now an empty directory, and > \windows\system32 actually contains the 64-bit binaries on x64)- > > Regards, > Martin I have to agree with Terry; installing the released python-3.0.msi results in an executable named 'python.exe' in the filesystem. I have not built it yet, but I assume the *NIX package results in a 'python' executable file. For a machine that runs existing Python 2.x applications, what should be in the PATH variable? For *NIX machines, will 'python' be placed into /usr/bin? If so, then the Python scripts that start out with a shebang like the following will have difficulty. #!/usr/bin/python #!/usr/bin/env python Has there been any guidance issued? From nicholas.cole at gmail.com Wed Dec 17 05:01:17 2008 From: nicholas.cole at gmail.com (Nicholas) Date: Wed, 17 Dec 2008 02:01:17 -0800 (PST) Subject: Relative imports in Python 3.0 Message-ID: Imagine a module that looks like ModuleDir __init__.py a.py b.py In python 2.x I used to have tests at the end of each of my modules, so that module b.py might look something like import a .......... .......... if __name__ == '__main__': runtests() But under Python 3.0 this seems impossible. For usual use import a.py has to become the line: from . import a But if I use that form it is no longer possible to run b.py as a standalone script without raising an error about using relative imports. I am sure I am not the first to run into this issue, but what is the solution? Best wishes, Nicholas From rezaee.ayat at yahoo.com Thu Dec 25 00:27:11 2008 From: rezaee.ayat at yahoo.com (Ayat Rezaee) Date: Wed, 24 Dec 2008 21:27:11 -0800 (PST) Subject: contour in python Message-ID: <185369.62211.qm@web45409.mail.sp1.yahoo.com> ?Hello, I need your help, ?I want to make a plot something like this program, ?? import Numeric as N ?? from contour import contour ?? x = N.arange(25) * 15.0 - 180.0 ?? y = N.arange(13) * 15.0 - 90.0 ??? data = N.outerproduct(N.sin(y*N.pi/360.), N.cos(x*N.pi/360.)) contour (data, x, y, title='Example') ?but cant import contour ; so I should install contour or do anythings? send ma a link if it should be installed. ?Best regards, ?Ayat. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sumerc at gmail.com Thu Dec 4 15:36:01 2008 From: sumerc at gmail.com (k3xji) Date: Thu, 4 Dec 2008 12:36:01 -0800 (PST) Subject: Python Runtime Method Call Binding References: <0147f396$0$20670$c3e8da3@news.astraweb.com> <9f2308eb-9eb9-4431-8af7-975c3e054849@e18g2000yqo.googlegroups.com> <493832b1$0$17775$426a34cc@news.free.fr> Message-ID: Thanks for the tips. >3/ Now fact is that even all this won't probably be enough to implement >a robust generic profiler - something which obviously requires a deep >understanding of the language *and* it's implementation. Indeed. Maybe not generic,but with these information at least I can write my specific multi-threaded profiler. All I need to is to rebind the methods/functions in the given modules and guard the callCount and timeElapsed values via locks. And the difficult point here is the timeElapsed information which should also take into account the thread it is running on, I can specifically differentiate the threads by looking at the args[0] parameter which is holding the self instance. Of course for this to work, I need to limit which objects to rebind..etc.etc. Briefly, I think I got what I asked for:) Thanks, From castironpi at gmail.com Mon Dec 29 13:06:56 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 10:06:56 -0800 (PST) Subject: SQL, lite lite lite Message-ID: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> Hi all, About a year ago, I posted an idea I was having about thread synchronization to the newsgroup. However, I did not explain it well, and I really erred on the side of brevity. (After some finagling, Mr. Bieber and I decided it wasn't exactly anything groundbreaking.) But I think the brevity cost me some readers, who might have had more interest. The affair was on the whole discouraging. So, I'm going to try another idea, and assume that readers have some time, and will spend it on it. I don't think relational data can be read and written very easily in Python. There are some options, such as 'sqllite3', but they are not easy. 'sqllite3' statements are valid SQL expressions, which afford the entire power of SQL, but contrary to its name, it is not that 'lite'. To me, 'lite' is something you could learn (even make!) in an afternoon, not a semester; something the size of an ActiveState recipe, or a little bigger, maybe a file or two. If you think SQL is a breeze, you probably won't find my idea exciting. I assume that the basics of SQL are creating tables, selecting records, and updating records. My idea is to create a 'Relation' class. The details are basically open, such as whether to back it with 'sqllite3', 'shelve', 'mmap', or just mapping and sequence objects; what the simplest syntax is that can capture and permit all the basics, and how much and what else can fit in at that level; how and whether it can include arbitrary Python objects, and what constraints there are on them if not; how and whether to permit transactions; and what the simplest and coolest thing you can do with a little Python syntax is. This is basically an invitation for everyone to brainstorm. (No hijackings, good humor & digression ok.) Lastly, ... **warning, spoiler! here's what I thought of already.** **repeat! spoiler! here's what I thought of already.** #Just the select and update syntax: >>> a= people._select( "firstname== 'Joe'" ) #select 'key' from 'people' where 'firstname'== 'joe' >>> a [Entry2864, Entry3076, Entry3172] >>> entry1= a[ 0 ] >>> entry1.phone #select 'phone' from 'people' where 'key'==self.key "555-2413" >>> entry1.phone= "555-1234" #update 'people' set 'phone'= '555-1234' where 'key'==self.key >>> entry1.phone "555-1234" #Create table syntax (a-whole-nother beast in itself): >>> classes= db.Relation( 'class_', 'person', Unique( 'class_', 'person' ) ) #create table 'classes' ( 'key', 'class_', 'person' ) unique ( 'class_', 'person' ) >>> classes._unique( 'class_', 'person' ) >>> classes.class_.noneok= False #'class_' cannot be null >>> classes.person.noneok= False >>> classes._insert( 'Physics', 'Dan' ) >>> classes._insert( 'Chem', 'Tim' ) Hoping-"good critic"-is-self-consistent-ly, hoping-to-hear-it's-too- complicated-already-ly, A. Brady From __peter__ at web.de Fri Dec 19 10:14:21 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2008 16:14:21 +0100 Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <494b5f47$0$17068$6e1ede2f@read.cnntp.org> <494b632b$0$17070$6e1ede2f@read.cnntp.org> <0390fcbc-8100-4aa8-93fa-ad358609ab7b@p2g2000prn.googlegroups.com> Message-ID: Roger wrote: >> either. I'd suggest a plain-python workaround along the lines of > > Wow. You just blew my mind. I'm going to play with this. Thanks a > lot, I've really learned a lot in just that small bit. I don't have > much experience in playing with a lot of the 'private' calls such as > __call__. I need to do some more reading. Here's a non-OO variant: funcs = [] def call(event): for f in list(funcs): # * f(event) root.bind("<1>", call) funcs.append(test) funcs.append(test2) root.bind("<1>", call) def unbind(): print "unbind" funcs.remove(test2) I does the same, but is a bit harder to manage if you have more than one event/widget to deal with. (*) iterating over a copy of the list of functions is slightly more robust as it will not accidentally skip callbacks when the original list is modified during iteration. I suggest that you change the OO version accordingly. Peter From roy at panix.com Tue Dec 9 00:50:26 2008 From: roy at panix.com (Roy Smith) Date: Tue, 09 Dec 2008 00:50:26 -0500 Subject: How to initialize a class variable once References: <707edf86-c223-4cf5-b6ca-a7c396a5edce@t26g2000prh.googlegroups.com> Message-ID: In article <707edf86-c223-4cf5-b6ca-a7c396a5edce at t26g2000prh.googlegroups.com>, alex23 wrote: > You might need to provide some more details about your code. It's going to take me some time to generate a minimal test case. From Afro.Systems at gmail.com Mon Dec 15 13:51:14 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Mon, 15 Dec 2008 10:51:14 -0800 (PST) Subject: os.environ.get('SSH_ORIGINAL_COMMAND') returns None Message-ID: Trying to follow a technique found at bzr I did the following added to ~/.ssh/authorized_keys the command="my_parder" parameter which point to a python script file named 'my_parser' and located in / usr/local/bin (file was chmoded as 777) in that script file '/usr/local/bin/my_parser' I got the following lines: #!/usr/bin/env python import os print os.environ.get('SSH_ORIGINAL_COMMAND', None) When trying to ssh e.g. 'ssh localhost' I get None on the terminal and then the connection is closed. I wonder if anyone have done such or alike in the past and can help me with this. Is there anything I should do in my python file in order to get that environment variable? From vkseashoremack at googlemail.com Sat Dec 20 11:56:02 2008 From: vkseashoremack at googlemail.com (vkseashoremack at googlemail.com) Date: Sat, 20 Dec 2008 08:56:02 -0800 (PST) Subject: teenflood - Free Message-ID: teenflood . . . *******CLICK HERE******** http://club247.cn/teenflood ***************************** . . . . . . . . . . . . teenflood From prologic at shortcircuit.net.au Sun Dec 21 17:27:48 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Dec 2008 08:27:48 +1000 Subject: Are python objects thread-safe? In-Reply-To: References: Message-ID: On Mon, Dec 22, 2008 at 4:51 AM, RajNewbie wrote: > Say, I have two threads, updating the same dictionary object - but for > different parameters: > Please find an example below: > a = {file1Data : '', > file2Data : ''} > > Now, I send it to two different threads, both of which are looping > infinitely: > In thread1: > a['file1Data'] = open(filename1).read > and > in thread2: > a['file2Data'] = open(filename2).read > > My question is - is this object threadsafe? - since we are working on > two different parameters in the object. Or should I have to block the > whole object? I believe (iirc), all basic data types and objects are thread-safe. I could be wrong though - I don't tend to use threads much myself :) cheers James From darcy at druid.net Tue Dec 16 08:44:52 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 16 Dec 2008 08:44:52 -0500 Subject: String slices work only for first string character ? In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF60249410A@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF60249410A@enbmail01.lsi.com> Message-ID: <20081216084452.f1a3002a.darcy@druid.net> On Tue, 16 Dec 2008 13:35:27 +0000 "Barak, Ron" wrote: > Can any one explain why the following string slice works only for the first character, but not for any other ? I think that you need to reread the docs on slices. > print "|"+data[0:1]+"|" > print "|"+data[1:1]+"|" If you want the second character use "data[1:2]". -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From pete.forman at westerngeco.com Tue Dec 16 05:12:32 2008 From: pete.forman at westerngeco.com (Pete Forman) Date: Tue, 16 Dec 2008 10:12:32 +0000 Subject: alt.possessive.its.has.no.apostrophe References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> <49467CE2.3060401@holdenweb.com> <4946826E.7060001@tim.thechases.com> <989de86c-24cc-4ca6-8e9b-82e8ce853c7b@n33g2000pri.googlegroups.com> Message-ID: Aaron Brady writes: > On Dec 15, 11:04?am, Steve Holden wrote: >> Tim Chase wrote: >> > Steve Holden wrote: >> >> This led to a schism between the British and the >> >> newly-independent Americans, who responded by taking the "u" >> >> out of colour, valour, and aluminium. >> >> > Darn Americans and their alminim.... ;-) >> >> > Next thing you know, they'll be putting an I in TEAM.[1] >> >> It's called humour. Or humor. Or incompetence ;-) > > There's an 'I' in Python. There's no 'F' in Python in this thread. -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- the opinion of Schlumberger or http://petef.22web.net -./\.- WesternGeco. From grflanagan at gmail.com Thu Dec 11 03:32:44 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Thu, 11 Dec 2008 09:32:44 +0100 Subject: Mathematica 7 compares to other languages In-Reply-To: <5ebe5a7d-cbdf-4d66-a816-a7d2a0a273c9@40g2000prx.googlegroups.com> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <5ebe5a7d-cbdf-4d66-a816-a7d2a0a273c9@40g2000prx.googlegroups.com> Message-ID: Xah Lee wrote: > On Dec 10, 2:47 pm, John W Kennedy wrote: >> Xah Lee wrote: >>> In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, >>> you'll have 50 or hundreds lines. [...] > > Thanks to various replies. > > I've now gather code solutions in ruby, python, C, Java, here: > > ? A Example of Mathematica's Expressiveness > http://xahlee.org/UnixResource_dir/writ/Mathematica_expressiveness.html > > now lacking is perl, elisp, which i can do well in a condensed way. > It'd be interesting also to have javascript... mmm, stone soup... javascript: var map = function(fn, a) { var b = new Array(a.length); for (i = 0; i < a.length; i++) { b[i] = fn(a[i]); } return b }; var reduce = function(fn, a, init) { var s = init; for (i = 0; i < a.length; i++) { s = fn(s, a[i]); } return s }; var sum = function(a) { return reduce(function(x, y) { return x + y }, a, 0.0) }; var norm = function(a) { var pow = Math.pow; return Math.sqrt(sum(map(function(x) { return pow(x, 2) }, a))) }; var Unit = function(a) { var N = norm(a); return map(function(x) { return x/N }, a) }; From marduk at letterboxes.org Wed Dec 3 17:12:27 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Wed, 03 Dec 2008 17:12:27 -0500 Subject: "as" keyword woes In-Reply-To: <896B75251BA19745A529B1B867893FA50679C6@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA50679C6@planet.delsci.local> Message-ID: <1228342347.29326.62.camel@brotherus.rdu.redhat.com> On Wed, 2008-12-03 at 13:38 -0800, Warren DeLano wrote: > A bottom line / pragmatic question... hopefully not a FAQ. > > Why was it necessary to make "as" a reserved keyword? > > And more to the point, why was it necessary to prevent developers from > being able to refer to attributes named "as"? > > For example, this code breaks as of 2.6 / 3.0: > > Class C: > Pass > > obj = C() > > obj.bs = 2 # valid > > obj.as = 1 # syntax error > > obj.cs = 3 # valid > > Just to be clear: I understand why it breaks, since "as" is now a > keyword, I also know that one can use workarounds such as: > > obj.__dict__['as'] = 1 > > to maintain compatibility. > > What I want to understand is why this parser change was necessary in > order to enable new 2.6/3.0 features. Was this change potentially > avoidable? > > Why can't the parser distinguish between a standalone " as " keyword and > ".as" used as an object/attribute reference? > > Couldn't we have continued along just fine using a smarter parser > without elevating "as" to reserved status (and thus potentially breaking > a 10+ years of existing code)? > > Thank you for enlighting me! > > (Unfortunately, our project may now have to maintain a branch at 2.5.x > in order to preserve compatibility with existing third-party scripts & > infrastructure which routinely rely upon "as" as an object method. > Sigh.) > > Cheers, > Warren The short answer is that "as" is a keyword as of 2.6 (with the introduction of the "with" statement) and to be fair none of the other keywords can be identifiers. Also to be fair, there seems to be warning at least in my version of python 2.5: >>> import sys >>> sys.version_info (2, 5, 1, 'final', 0) >>> class C: ... pass ... >>> obj = C() >>> obj.as = 3 :1: Warning: 'as' will become a reserved keyword in Python 2.6 From yuniyuni21 at gmail.com Wed Dec 10 23:57:08 2008 From: yuniyuni21 at gmail.com (yuniyuni21 at gmail.com) Date: Wed, 10 Dec 2008 20:57:08 -0800 (PST) Subject: density plot Message-ID: Hi, Does anyone know how to make the density plot, more specifically a gaussian-smoothed version of a histogram. Actually, it's not exactly a plot that I want. What I want to do is get the maximum count (or highest peak) of the density distribution. It's different from the probability density function that has the center at zero. In S plus and R, there is the "density" function which I can use to get the max x and y in the frequency distribution. I really appreciate if anyone can help. From rdmurray at bitdance.com Wed Dec 10 18:43:28 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Wed, 10 Dec 2008 18:43:28 -0500 (EST) Subject: forcing future re-import from with an imported module In-Reply-To: References: <533670ae-6d9d-4b10-9156-e41b31b678c7@g17g2000prg.googlegroups.com> Message-ID: On Wed, 10 Dec 2008 at 14:53, _wolf wrote: > thanks for your answer. i am aware that imports are not designed to > have side-effects, but this is exactly what i want: to trigger an > action with `import foo`. you get foo, and doing this can have a side- > effect for the module, in roughly the way that a `from __future__ > import with_statement` changes the interpretation of the current > module (of course, i do not intend to effect syntactic changes---my > idea is to look into the module namespace and modify it). think of it > as ?metamodule programming? (? la metaclass programming). > > maybe import hooks are the way to go? somtimes it would be good if > there was a signalling system that broadcasts all kinds of system > state change. > > cheers & ~flow > > ok so the question is: how to make it so each import of a given module > has a side-effect, even repeated imports? Why can't you have the code that is doing the import subsequently call a function from the module to produce whatever side effect it is you want? Explicit is better than implicit. A python programmer is going to expect that importing a module is idempotent, and breaking that assumption strikes me as a bad idea. Maybe you should give us more details about what problem it is you are trying to solve. There might be a good pythonic way to solve it. --RDM From bj_666 at gmx.net Sun Dec 21 04:49:36 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Dec 2008 09:49:36 GMT Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> Message-ID: <6r6hpfFfb643U3@mid.uni-berlin.de> On Sat, 20 Dec 2008 14:18:40 -0800, cm_gui wrote: >> Seriously cm_gui, you're a fool. >> Python is not slow. > > haha, getting hostile? > python fans sure are a nasty crowd. > > Python is SLOW. > > when i have the time, i will elaborate on this. You are not fast enough to elaborate on Python's slowness!? :-) cm_gui is slow! Ciao, Marc 'BlackJack' Rintsch From ghimire.manoj at gmail.com Thu Dec 18 11:22:17 2008 From: ghimire.manoj at gmail.com (manojghimire) Date: Thu, 18 Dec 2008 08:22:17 -0800 (PST) Subject: mysql with python Message-ID: can anybody give me the link where I can directly download the _mysql.dll file required by MySQLdb for Python 2.6. I tried to build MySQL db but there is error: None. Is there a need for me to step down to Python 2.5 ?? Further any comments on the best ORM for Python ?? From prologic at shortcircuit.net.au Tue Dec 2 18:03:33 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 3 Dec 2008 09:03:33 +1000 Subject: HELP!...Google SketchUp needs a Python API In-Reply-To: References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> Message-ID: You're a funny man r :) Good luck with your endeavours! I have a hard enough time convincing my work colleagues to use anything other than PHP for everything! Here PHP is the Hammer / Pitchfork! --JamesMills On Wed, Dec 3, 2008 at 8:16 AM, r wrote: > OK...so here are the stat's so far. > > 6+BDFL - who would support my crazy idea, or think it -might- be ok > 11 - who are on the fence > 6 - who think this is a complete waste of time, a stupid idea, or just > simply want to kill me > > -> from these stats i can deduce the following: > total_members_comp.lang.python = 14433 > note: I will be fair and remove spammers or members that don't follow > this list anymore by dividing the total number in half.(this should be > generous enough) > total_actual_members = (14433/2) = 7214 > total_num_responders = 11 > > ->current stats: <11> > percentFor = 31 > percentNay = 27 > percentOnFence = 40 > > ->Forecast of turnout: <7214> > potentialFors = 2,236.34 > potentialConverts = 2,885.34 > totalPotentials = 5,121.68 > > even if only 10% of these act...that is 512 people. I still have hope! > > import hope > while hope.amt > 0: > continue > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From simonharrison.uk at googlemail.com Mon Dec 8 06:27:15 2008 From: simonharrison.uk at googlemail.com (simonharrison.uk at googlemail.com) Date: Mon, 8 Dec 2008 03:27:15 -0800 (PST) Subject: Determining whether a variable is less/greater than a range. References: <362ab93b-b804-4ebe-a22f-e422feb301c8@c1g2000yqg.googlegroups.com> Message-ID: On Dec 8, 11:12?am, Tim Chase wrote: > > a = list(range(10, 21)) > > > b = 9 > > > c = 21 > > > How can I find out if b and c have values less or more than the values > > in list a? > > Sounds like a good use for 2.5's addition of the any() and all() > functions -- you don't mention whether you want your variable > compared against *any* of the list items or *all* of the list > items. ?You also don't mention whether you want the comparison > results, or just a single scalar. ?Lastly, you omit the details > of what happens if your target value ("d" below) falls within the > range. ?One of the following should do it for you: > > ? ?>>> a = range(10,21) > ? ?>>> b = 9 > ? ?>>> c = 21 > ? ?>>> d = 15 > ? ?>>> any(b < x for x in a) > ? ?True > ? ?>>> all(b < x for x in a) > ? ?True > ? ?>>> any(c < x for x in a) > ? ?False > ? ?>>> any(d < x for x in a) > ? ?True > ? ?>>> all(d < x for x in a) > ? ?False > ? ?>>> any(c > x for x in a) > ? ?True > ? ?>>> all(c > x for x in a) > ? ?True > ? ?>>> any(d > x for x in a) > ? ?True > ? ?>>> all(d > x for x in a) > ? ?False > > If you just want the comparisons: > > ? ?y1 = [b ? ?y2 = [c ? ?y3 = [d ? ?z1 = [(bx) for x in a] > ? ?z2 = [(cx) for x in a] > ? ?z3 = [(dx) for x in a] > > -tkc Hi Tim. I'm just learning Python at the moment. All I was really wanting was a True or False value which min and max give. a = list(range(10, 21)) b = 9 c = 21 if b < min(a) if c > max(a) The any() and all() functions look useful so thanks for the tips. From darcy at druid.net Sun Dec 7 18:44:13 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sun, 7 Dec 2008 18:44:13 -0500 Subject: how to get a beep, OS independent ? In-Reply-To: <320A8AF5-DF3F-482F-93BE-073C74AA6462@strout.net> References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> <320A8AF5-DF3F-482F-93BE-073C74AA6462@strout.net> Message-ID: <20081207184413.4d9e90f3.darcy@druid.net> On Sun, 7 Dec 2008 12:56:14 -0700 Joe Strout wrote: > On Dec 7, 2008, at 8:48 AM, Grant Edwards wrote: > > What makes you think there is such a thing as "the standard system > > beep"? > > Because OS X (the platform with which I'm most familiar) certainly has > one, and REALbasic has had a "Beep" method for years which works on > all platforms. If RB can do it, we can do it too. It works on all platforms that RB runs on. A rather short list. Certainly a subset of the platforms that Python runs on. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From python.list at tim.thechases.com Fri Dec 12 17:32:08 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 12 Dec 2008 16:32:08 -0600 Subject: Removing None objects from a sequence In-Reply-To: References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> Message-ID: <4942E668.5030100@tim.thechases.com> > If you want to literally remove None objects from a list....(or mutable > sequence) > > def deNone(alist): > n=len(alist) > i=j=0 > while i < n: > if alist[i] is not None: > alist[j] = alist[i] > j += 1 > i += 1 > alist[j:i] = [] > > blist=[None,1,None,2,None,3,None,None,4,None] > deNone(blist) > print(blist) > > # prints [1, 2, 3, 4] ...wouldn't a cleaner way of doing this just be >>> blist=[None,1,None,2,None,3,None,None,4,None] >>> alist = blist >>> blist[:] = [x for x in blist if x is not None] >>> blist [1, 2, 3, 4] >>> alist [1, 2, 3, 4] By using the slice assignment, it leaves the blist referring to the same list-object (as shown by the "alist" bit), and modifying it in place. This reads a lot more cleanly in my estimation. If the data-set is large, in 2.5+, you can just use a generator: blist[:] = (x for x in blist if x is not None) -tkc From mludvig at logix.net.nz Fri Dec 12 05:32:27 2008 From: mludvig at logix.net.nz (Michal Ludvig) Date: Fri, 12 Dec 2008 23:32:27 +1300 Subject: File names, character sets and Unicode Message-ID: <49423DBB.9090401@logix.net.nz> Hi all, is there any way to determine what's the charset of filenames returned by os.walk()? The trouble is, if I pass argument to os.walk() I get the filenames as byte-strings. Possibly UTF-8 encoded Unicode, who knows. OTOH If I pass to os.walk() all the filenames I get in the loop are already unicode()d. However with some locales settings os.walk() dies with for example: Traceback (most recent call last): File "tst.py", line 10, in for root, dirs, files in filelist: File "/usr/lib/python2.5/os.py", line 303, in walk for x in walk(path, topdown, onerror): File "/usr/lib/python2.5/os.py", line 293, in walk if isdir(join(top, name)): File "/usr/lib/python2.5/posixpath.py", line 65, in join path += '/' + b UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1: ordinal not in range(128) I can't even skip over these files with 'os.walk(..., onerror=handler)' the handler() is never called. That happens for instance when the file names have some non-ascii characters and locales are set to ascii, but reportedly in some other cases as well. What's the right and safe way to walk the filesystem and get some meaningful filenames? Related question - if the directory is given name on a command line what's the right way to preprocess the argument before passing it down to os.walk()? For instance with LANG=en_NZ.UTF-8 (i.e. UTF-8 system): * directory is called 'smile?' * sys.argv[1] will be 'smile\xe2\x98\xba' (type str) * after .decode("utf-8") I get u'smile\u263a' (type unicode) But how should I decode() it when running on a system where $LANG doesn't end with "UTF-8"? Apparently some locales have non-ascii default charsets. For instance zh_TW is BIG5 charset by default, ru_RU is ISO-8850-5, etc. How do I detect that to get the right charset for decode()? I tend to have everything internally in Unicode but it's often unclear how to convert some inputs to Unicode in the first place. What are the best practices for dealing with these chraset issues in Python? Thanks! Michal -- * Amazon S3 backup tool -- http://s3tools.logix.cz/s3cmd From clp at rebertia.com Sun Dec 21 19:20:57 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 21 Dec 2008 16:20:57 -0800 Subject: Beep In-Reply-To: References: Message-ID: <47c890dc0812211620h6c19086dhf3a14a662a49fdf6@mail.gmail.com> On Sun, Dec 21, 2008 at 4:16 PM, Jeffrey Barish wrote: > I use sys.stdout.write('\a') to beep. It works fine on Kubuntu, but not on > two other platforms (one of which is Ubuntu). I presume that the problem > is due to a system configuration issue. Can someone point me in the right > direction? Thanks. Is the 'pcspkr' kernel module built and loaded? Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From mail at johnohagan.com Tue Dec 30 09:21:29 2008 From: mail at johnohagan.com (John O'Hagan) Date: Tue, 30 Dec 2008 14:21:29 +0000 Subject: why cannot assign to function call In-Reply-To: <5e807c67-7d97-4b8a-8c5f-a3b97f5c5003@i20g2000prf.googlegroups.com> References: <495867C2.7080807@gmail.com> <5e807c67-7d97-4b8a-8c5f-a3b97f5c5003@i20g2000prf.googlegroups.com> Message-ID: <200812301421.29888.mail@johnohagan.com> On Tue, 30 Dec 2008, Aaron Brady wrote: [...] > On a technicality, to avert a flaming, "change the value of 'b'" is an > ambiguous phrase. There are two interpretations of "change what 'b' > refers to" and "change what 'b' refers to". Even in spoken language, > I don't think that emphasis can resolve them either. > > One means, 'make a change in the world, in the actual configuration of > such and such actual matter.' The other means, 'update the axioms the > speaker is using to communicate to the listeners. (Such and such will > no longer refer to such and such; it will refer to such and such; > accept this and reject that.)' To make an observation, reference is a > purely linguistic phenomenon. > > I, for one, am at a loss for how to disambiguate it. I'm open to > suggestions. I think you've already done so quite clearly. But I suspect the ambiguity centres on the word "change" - in the first interpretation it means "alter" (the object in place), in the second, it more precisely means "exchange" (one object for another). I'd be interested to know to what extent this ambiguity exists in languages other than English - as a somewhat relevant example, ambiguities in English around the verb "to be" ("I am Fred", "I am tall", "I am hungry"; i.e., identity vs. attributes vs. state) disappear in other languages which use different verbs in each case. On a (philosophical) side-note, I wonder if this is a real ambiguity: while the statement that the name "b" now refers to a different object is clear-cut, the other interpretation, that the object itself has changed but is somehow still the same object, is a bit of an ontological minefield. Fortunately, unlike the murky world of philosophy, Python (AIUI) simplifies this question by simply declaring that yes, in the case of mutable objects, we may say that we are still referring to the same object although we've changed it, and no, in the case of immutable objects, we may not, and must exchange it if we want a different "value" (a word too fraught with ambiguity in this context to use unquoted!). The sometimes useful fuzziness of human languages means we don't need to ask, for example, "how tall is the object currently referred to by the name Fred?", but in Python, it helps to understand that this is what's going on. Regards, John From prologic at shortcircuit.net.au Tue Dec 30 17:42:26 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 08:42:26 +1000 Subject: multiprocessing vs thread performance In-Reply-To: <47cfc6de-4b13-4a74-accc-c1d027c44d5a@35g2000pry.googlegroups.com> References: <26f7d44e-552c-41e9-9290-17e5c4e6deb9@q30g2000prq.googlegroups.com> <47cfc6de-4b13-4a74-accc-c1d027c44d5a@35g2000pry.googlegroups.com> Message-ID: On Wed, Dec 31, 2008 at 12:29 AM, Aaron Brady wrote: > James, Hi. I'm glad you asked; I never know how "out there" my > comments are (but surmise that feedback is always a good thing). What > I was thinking was, I didn't know Virtual Synchrony, and I've never > used Erlang, but I'm interested in concurrency especially as it > pertains to units of work, division of labor, and division of context; > and generators are another way to divide context. So: I wanted to put > more of my background and interests on the table. What I said wasn't > directly relevant, I see. But it's not like I > "dissertated" (discussed) the Tibettan-Austrian spice trade. I think > I just want to say stuff about threading! Maybe I'm just excited to > meet people who share my interests... not unheard of. Glad to see others also interested in these topics :) (snip) > 'Circuits' doesn't use generators. I think generators are an > underexplored technique. Is 'circuits' assembly line or start-to- > finish, if my analogy makes any sense? 'Circuits' is event-driven, > but I don't see any difference between 'event-driven' and > multithreaded in general. (I think contrast can create a good picture > and a clear understanding.) What is special about an 'event-driven' > architecture? Are you distinguishing blocking from polling? I'll shortly be releasing circuits-1.0 today hopefully. To answer your question, circuits is inspired by a software architecture that my most favoured lecturer a few years back was teaching. That is: * Behaviour Trees (design) and consequently: * The concept of "everything is a Component" * Systems and Sub-Systems are built upon Components and * Everything is an event. and * An emergent property of such systems are "Behaviour". That being said, circuits employs both an event-driven approach as well as a Component architecture. In your analogy it is both horizontal and vertical. As I continue to develop circuits and improve it's core design as well as building it's ever growing set of Components, I try to keep it as general as possible - my main aim though is distributed processing and architectures. (See the primes example). Thanks for sharing your interest :) cheers James From gagsl-py2 at yahoo.com.ar Wed Dec 17 18:47:54 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 17 Dec 2008 21:47:54 -0200 Subject: Location HTTP Header References: <68fa1e9b-6652-4d34-a7fe-fc98db8bf6d4@m16g2000vbp.googlegroups.com> Message-ID: En Wed, 17 Dec 2008 20:52:42 -0200, ptn escribi?: > I tried this stupid script on my server: > > #! /usr/bin/env python > > print 'Location: http://www.google.com\n' > > and it didn't work, I get a blank page. I first tried the Location > header in another script, and when execution got to that point, it > would > just sort of ignore it, because the script would keep running to the > end > of the code (or stop at some unhandled exception). I assume this is a cgi script. For the Location field to be relevant, the Status should be a 3xx (like 307 Temporary Redirect, or 302 Found) In your case, your server probably has already sent a 200 OK response, so Location is ignored. Try adding a Status line -before Location above- like: print 'Status: 302 Found" > Any ideas? I'd use a different protocol other than CGI... -- Gabriel Genellina From ndbecker2 at gmail.com Mon Dec 15 19:11:27 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Mon, 15 Dec 2008 19:11:27 -0500 Subject: OpenOpt 0.21 (free optimization framework) References: Message-ID: Is it easy_install able? I got: sudo easy_install -U openopt Searching for openopt Reading http://pypi.python.org/simple/openopt/ Couldn't find index page for 'openopt' (maybe misspelled?) Scanning index of all packages (this may take a while) Reading http://pypi.python.org/simple/ Reading http://pypi.python.org/simple/OpenOpt/ Reading http://scipy.org/scipy/scikits/wiki/OpenOpt Best match: openopt [unknown version] Downloading http://pypi.python.org/packages/source/O/OpenOpt/openopt.tar.bz2#md5=6ba26f9083189e7bf49a318de575bc46 Processing openopt.tar.bz2 Running openopt/setup.py -q bdist_egg --dist-dir /tmp/easy_install-rnCH9g/openopt/egg-dist-tmp-jxo557 scikits.openopt 0.18.dev is already the active version in easy-install.pth Installed /usr/lib/python2.5/site-packages/scikits.openopt-0.18.dev-py2.5.egg Sounds like the wrong version? From has.temp3 at virgin.net Mon Dec 8 18:31:57 2008 From: has.temp3 at virgin.net (has) Date: Mon, 8 Dec 2008 15:31:57 -0800 (PST) Subject: Shutdown Mac OSX computer using python References: Message-ID: On 8 Dec, 09:26, H?kan Hagenrud wrote: > Hello, i'm a python noob! > > But I would like to shutdown a 10.5.x mac computer using python (2.5.1) > > this is my code: > #!/usr/bin/python > import SystemEvents > down = SystemEvents.Power_Suite.Power_Suite_Events() > down.shut_down() Avoid Python 2.x's ancient gensuitemodule/aetools modules - they've always been flaky and/or broken on OS X and are completely hosed on Intel Macs. For something this simple, you could just shell out to osascript, avoiding any additional dependencies: import subprocess subprocess.call(['osascript', '-e', 'tell app "System Events" to shut down']) (Note that I wouldn't recommend using 'shutdown' as Wolfgang suggests - while it will shut down your system, it doesn't know anything about the Mac desktop and will unceremoniously kill off all your GUI processes without going through their normal quit procedures.) HTH has -- Control AppleScriptable applications from Python, Ruby and ObjC: http://appscript.sourceforge.net From google at mrabarnett.plus.com Thu Dec 11 18:26:07 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 11 Dec 2008 23:26:07 +0000 Subject: list organization question In-Reply-To: References: Message-ID: <4941A18F.9030209@mrabarnett.plus.com> Robocop wrote: > I have a list of objects, each object having two relevant attributes: > date and id. I'd like not only organize by id, but also by date. > I.e. i would like to parse my list into smaller lists such that each > new mini-list has a unique date, but consists of only objects with a > specific id. Are there any handy imports i could use to accomplish > something like this? I'm relatively new to python and as such don't > know all of the preloaded functions at my disposal. Thanks for any > help in advance, the community here is always ridiculously helpful. > Perhaps you could iterate through the list, building a dict of lists, where the key of the dict is the date. From jerry.carl.mi at gmail.com Sun Dec 28 00:50:09 2008 From: jerry.carl.mi at gmail.com (jerry.carl.mi at gmail.com) Date: Sat, 27 Dec 2008 21:50:09 -0800 (PST) Subject: math module for Decimals References: Message-ID: <251111d8-a48a-45e3-a744-16fdb729fa33@i20g2000prf.googlegroups.com> > Which math functions? ln, log10, exp, sqrt already exist as methods of ? > Decimal instances. At the end of the Decimal docs there are a few ? > examples, including computing sin and cos (but apparently they na?vely use ? > a McLaurin series like you noticed in other module). Hi Gabriel - thanks! For example all goniometric functions are missing. Or the log(x, base). Or rand(). Sure I can spend time trying to put it all together but I thought somebody would have done that already. It seems though that the codes that are out there are not ready - every one of the modules i mentioned above has some issues. Maybe I can put bits and pieces together, but if anyone knows of a well proven module (as is), I would feel much safer using that (again I am not a mathematician and poking into these algorithms makes me feel like trying to fix an automatic transmission). From musiccomposition at gmail.com Wed Dec 17 13:48:05 2008 From: musiccomposition at gmail.com (Benjamin) Date: Wed, 17 Dec 2008 10:48:05 -0800 (PST) Subject: Relative imports in Python 3.0 References: Message-ID: <5fca0c81-cb2d-4fd9-8357-d355a5290ab3@k24g2000pri.googlegroups.com> On Dec 17, 4:01?am, Nicholas wrote: > Imagine a module that looks like > > ModuleDir > ? ? ?__init__.py > ? ? ?a.py > ? ? ?b.py > > In python 2.x I used to have tests at the end of each of my modules, > so that module b.py might look something like > > import a > ?.......... > ?.......... > > if __name__ == '__main__': > ? ?runtests() > > But under Python 3.0 this seems impossible. ?For usual use import a.py > has to become the line: > > from . import a > > But if I use that form it is no longer possible to run b.py as a > standalone script without raising an error about using relative > imports. > > I am sure I am not the first to run into this issue, but what is the > solution? Use absolute imports: from ModuleDir import a > > Best wishes, > > Nicholas From saju.pillai at gmail.com Thu Dec 11 05:36:02 2008 From: saju.pillai at gmail.com (saju.pillai at gmail.com) Date: Thu, 11 Dec 2008 02:36:02 -0800 (PST) Subject: Equivalent of 'wget' for python? References: Message-ID: On Dec 11, 2:36?pm, hrishy wrote: > Hi > > Please excuse my OOP but is my understanding correct > > urllib.urlretrieve(url_of_zip_file,destination_on_local_filesystem) > > is urllib --->Static Class on which the method urlretrieve method is invoked ? No urllib is a "method". Use type(obj) to find out what python thinks the "type" of that object is. Note that "object" here is not meant in the same sense as the OOP definition. > > In that case what does the python 3.0 version mean > > import urllib.request > urllib.request.urlretrieve(url, local_file_name) > > urllib -->static class > request -->method > urlretrieve--> what is this then ? A 'function'. urllib.request.urlretrieve is the fully qualified name of the function urlretrieve. In other words urlretrieve lives in the urllib.request namespace. -srp > > regards > Hrishy > > --- On Mon, 8/12/08, Jerry Hill wrote: > > > From: Jerry Hill > > Subject: Re: Equivalent of 'wget' for python? > > To: python-l... at python.org > > Date: Monday, 8 December, 2008, 5:54 PM > > On Mon, Dec 8, 2008 at 11:53 AM, r0g > > wrote: > > > urllib.urlretrieve(url_of_zip_file, > > destination_on_local_filesystem). > > > In python 3.0, that appears to be: > > > import urllib.request > > urllib.request.urlretrieve(url, local_file_name) > > > -- > > Jerry > > -- > >http://mail.python.org/mailman/listinfo/python-list > > From lewis.sarah93 at yahoo.com Thu Dec 4 23:47:30 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 20:47:30 -0800 (PST) Subject: Reduce Debt Message-ID: <31bbf31b-45f7-4fb3-b9ae-a7700d7b82c8@t3g2000yqa.googlegroups.com> Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From tarundevnani at gmail.com Thu Dec 11 07:28:21 2008 From: tarundevnani at gmail.com (tarun) Date: Thu, 11 Dec 2008 17:58:21 +0530 Subject: Converting c header file to a python file Message-ID: Hello, I am looking for a tool/utility by which can convert c header file to a python file. A typical header file that I want convert looks like: #ifndef __VAR1 #define __VAR1 #define VAR2 "Rev 2" #define VAR3 2L typedef struct { .... .... } #if defined(__cplusplus) || defined(__cplusplus__) extern "C" { #endif And also function declarations Thanks, Tarun -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Sun Dec 7 17:16:27 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 07 Dec 2008 17:16:27 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Rasmus Fogh wrote: > > Can anybody see a way this could be fixed (please)? I may well have to > live with it, but I would really prefer not to. I made a suggestion in my first response, which perhaps you missed. tjr From kyosohma at gmail.com Thu Dec 4 15:59:54 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 4 Dec 2008 12:59:54 -0800 (PST) Subject: Good introductory book? References: Message-ID: <215b15b4-4681-4fd6-b3fe-1de6b845a68a@t2g2000yqm.googlegroups.com> On Dec 3, 8:44?am, "Ken D'Ambrosio" wrote: > Hi, all. ?I'm getting ready to do some projects in Python, and I've cut my > teeth a little bit, but I've found the "Learning|Programming Python" books > from O'Reilly to be more-or-less useless (to my surprise -- I'm usually an > O'Reilly fan). ?I really, really like "Python Essential Reference", but > it's -- well, more of a reference than an intro. ?So, an introductory text > that actually assumes some previous programming experience (as opposed to > "Learning Python" which must be the most slowly-paced programming book > ever) would be terrific. > > Thanks for your suggestions! > > -Ken I liked "Beginning Python" by Hetland. There's also "Python Power!" by Telles, which I think was pretty good. Note that there's not much out for the 3.0 version yet other than the official docs. You'll probably have to wait until next year before much is really written/published about that. Mike From vschmidt13 at gmail.com Mon Dec 8 14:27:31 2008 From: vschmidt13 at gmail.com (Val) Date: Mon, 8 Dec 2008 11:27:31 -0800 (PST) Subject: easy_install of module produces un-importable result Message-ID: I've written my first module, "gpsparser" and uploaded it as an egg to PyPI. I can use easy_istall to install my own module, but when I try to import it I get an ImportError "No module named gpsparser". So I've done some research and found that in my site-packages/ directory gpsparser exists as an egg file, while all the other packages I've installed exist as an egg directory. If this makes any sense, can anyone explain what I've done wrong in building my package that the installation process does not unpack the egg file? Thanks, Val From your.master at gmail.com Thu Dec 11 15:04:01 2008 From: your.master at gmail.com (Brandon) Date: Thu, 11 Dec 2008 12:04:01 -0800 (PST) Subject: dictionary idiom needed References: <383976cf-53fb-48e4-b028-8f568468ce77@r36g2000prf.googlegroups.com> <0c4950c1-4833-40c7-ac19-260b61d5289f@k24g2000pri.googlegroups.com> Message-ID: <7c55c59b-cebe-4f4e-ae40-282ae7e005bf@d42g2000prb.googlegroups.com> Thanks bear - Some outside advice has me looking at nested dictionaries. But I am still bogged down because I've not created one before and all examples I can find are simple ones where they are created manually, not with loops. Maybe a further example: data: POS1 POS2 POS3 ['word1','tagA','tagB'] ['word2','tagC','tagD'] ['word1','tagE','tagB'] ['word1','tagC','tagF'] ... and so on. FWIW: I am guaranteed that the set of tags that may occur in position2 is complementary to the set of tags that may occur in position3. Now I want to get an accounting of all the tags that occurred in position3 in the context of, say, word1. Here I've shown that for word1, tagB and tagF occurs. I want a way to access all this information such that nested_dict['word1']['tagB'] = 2, and nested_dict ['word1']['tagF'] = 1. As I mentioned, I already have dicts such that dictA['word1'] = 3, and dictB['tagB'] = 2. I used defaultdict to build those, and that seems to be causing me to get some funky values back from my initial attempts to build a nested dictionary. I am stumbling at constructing a "for" loop that automatically creates such nested dictionaries. I hope that clears things up. If you still have any advice, it's much appreciated. Thanks, Brandon From gagsl-py2 at yahoo.com.ar Mon Dec 29 22:53:52 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Dec 2008 01:53:52 -0200 Subject: Python in C References: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> <18777.34893.283277.955506@montanaro-dyndns-org.local> Message-ID: En Tue, 30 Dec 2008 00:32:45 -0200, escribi?: > BTW, as a person who hasn't really written a stitch of C++ in about 10 > years > I personally find the CPython implementation to be one of the most > well-organized large pieces of code I have ever encountered. It's much > easier to read (to me) than any significant piece of C++ code I have ever > tried to read. I completely agree. > Here are a few things which might help you understand the code structure > a > bit more: I'd suggest reading object.h too - it describes the Python object system (from the implementation POV). -- Gabriel Genellina From dickinsm at gmail.com Sun Dec 28 09:33:37 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 28 Dec 2008 06:33:37 -0800 (PST) Subject: math module for Decimals References: Message-ID: <41937dc9-4b67-43b5-9eab-6f8c851474cf@p2g2000prn.googlegroups.com> On Dec 28, 12:02?am, jerry.carl... at gmail.com wrote: > I have been looking for a Python module with math functions that would > both eat and spit Decimals. The standard math module eats Decimals > allright but spits floats. Yes: it just converts the input (whether float, int, Fraction or Decimal) to a float using the __float__ method, and then applies the usual float->float maths function. > I tried using the AJDecimalMathAdditions, but ran into issues like dSin > (1E4) would take forever to calculate and would result in sin() > > 1 ... If i understand it correctly, the program is using maclaurin > series to calculate the value and since it does not chop off all the > multiples of 2*pi, the maclaurin approximation becomes useless when > its too far from x=0. Implementing these functions *is* kinda tricky, especially if you want them to be correctly rounded, efficient, and to deal correctly with all the special cases (infinities, nans, ...). But it's far from impossible. sin and cos present particular difficulties for large arguments; probably the range of accepted inputs would have to be restricted for those functions. > (1) what do folks use when they need to calculate something like exp > (sin(Decimal())) or even more complex things? Any recommendations? Or > am I completely missing something? Generally, something other than Python. :) (For example, GP/Pari or MPFR.) I'd like to be able to use Python for this, though. A couple of questions for you (I'm curious what additions would suit your particular use case best): - are you using Decimal for the base-10-ness or the extra precision Decimal provides? Or significant zeros? Or compatibility with existing Decimal code, or what? - what 3 functions would you most like to see added? For me, I think it would be something like sin, cos and atan (or possibly atan2). Once you've got those three, everything else is fairly easy. In particular, atan/atan2 at least gives you access to pi. > (2) Is there any plan to provide a standard python module that would > do that? (Python 4.0? ;-) No, there's no such plan. It's highly unlikely that the Decimal module will grow any extra math functions: it's designed to stick very closely to the IBM standard. It's not impossible that extra Decimal functions could be added in some other module, but it seems fairly unlikely. FWIW, I'm the author of the current Decimal log, log10, exp and pow functions, so I'm probably in a fairly good position to try to implement reasonably high-quality versions of some other elementary functions (again, just as an external addition to the decimal module, not as part of the decimal module itself). This is an itch I've often wanted scratched, as well. I might just have a go.... (Help in the form of code, tests, suggestions, etc. would be welcome!) Mark From cs at zip.com.au Sat Dec 6 23:03:48 2008 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 7 Dec 2008 15:03:48 +1100 Subject: Guido's new method definition idea In-Reply-To: <20081206113000.4da8b7df@usenot.de> Message-ID: <20081207040348.GA21618@cskk.homeip.net> On 06Dec2008 11:30, Andreas Waldenburger wrote: | On 6 Dec 2008 09:18:20 GMT Marc 'BlackJack' Rintsch | wrote: | > On Sat, 06 Dec 2008 09:56:12 +0100, Antoine De Groote wrote: | > [snip reference to "preferably only one way to do it"] | > | > The reason why I'm against that change too. It adds a second, | > alternative way to express something that is already in the language. | > | > > I agree that for newcomers to Python, the class method definition | > > might seem strange. | > | > And after the change it continues to because they will run into | > *both* variants in tutorials, code, and books, so it might be even | > more confusing. | > | I agree with that view. Not much to add to it, just increasing the | weight. Me too. And it smells like Perl if we let the $ get in there. And it doesn't add any facility to the language - it's just syntactic lint. So -1 from me. -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ From dotancohen at gmail.com Wed Dec 10 16:13:05 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 10 Dec 2008 23:13:05 +0200 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: <880dece00812101313j358e3e7dg6a5fe79b6f83dd18@mail.gmail.com> 2008/12/10 : > On Dec 5, 9:51 am, Xah Lee wrote: >> >> For those of you who don't know linear algebra but knows coding, this >> means, we want a function whose input is a list of 3 elements say >> {x,y,z}, and output is also a list of 3 elements, say {a,b,c}, with >> the condition that >> >> a = x/Sqrt[x^2+y^2+z^2] >> b = y/Sqrt[x^2+y^2+z^2] >> c = z/Sqrt[x^2+y^2+z^2] > >> >> In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, >> you'll have 50 or hundreds lines. > > Ruby: > > def norm a > s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) > a.map{|x| x/s} > end If someone doesn't counter with a Python one-liner then I'm going to port that to brainfuck. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-??-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From stephane.chazelas at unicyclist.com Mon Dec 1 06:53:18 2008 From: stephane.chazelas at unicyclist.com (Stephane Chazelas) Date: Mon, 1 Dec 2008 11:53:18 +0000 (UTC) Subject: Python surpasses Perl in popularity? References: <5e87aee0-c7fd-4e9d-befb-0cc01cee64ec@f40g2000pri.googlegroups.com> <49316c95$0$2813$742ec2ed@news.sonic.net> <49322ea2$0$2747$742ec2ed@news.sonic.net> <4933a5ae$0$185$e4fe514c@news.xs4all.nl> Message-ID: 2008-12-01, 08:51(+00), Casper H.S Dik: > Stephane CHAZELAS writes: > >>It's true it was vague and misleading, > >>/bin is not the standard place to look for "sh" as far as the >>"POSIX" standard is concerned. That doesn't mean that standard >>commands (POSIX or not) cannot be found in /bin. But /bin/sh has >>been made a non-standard place for "sh". It's the "legacy" >>place. Those commands that have not undergone non-backward >>compatible changes with POSIX can still be found in /bin, the >>others are to be found in /usr/xpg/bin (for the standard >>versions). > > The proper place is "`getconf PATH`". POSIX doesn't list any > pathnames. > > Of course, the problem is then "where did getconf come from?". [...] Sorry, I was specifically speaking of Solaris 7, 8, 9. "getconf PATH" is not enough, you have to pick the correct getconf, and that getconf be called in the relevant environment. For instance, in later versions of Solaris, I beleive you get /usr/xpg6/bin or /usr/xpg4/bin first depending on the environment. Also, PATH is not necessarily the only thing needed to get you the conformant utilities. See BIN_SH on Tru64, POSIXLY_CORRECT on GNU... I beleive the only thing POSIX requires is that how to get into the proper environment be documented (but it is unspecified). On Solaris, I beleive it's in the standards(5) man page. -- St?phane From steve at holdenweb.com Sat Dec 20 08:20:12 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 20 Dec 2008 08:20:12 -0500 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <06daa32b-aff7-4104-99bb-3cd1365be600@w1g2000prm.googlegroups.com> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> <06daa32b-aff7-4104-99bb-3cd1365be600@w1g2000prm.googlegroups.com> Message-ID: <494CF10C.8010302@holdenweb.com> Mark Summerfield wrote: [...] > > With two dozen postings on my use of English I'm now rather nervous > about the feeback I'll get on my Python 3! > There is no such thing as bad publicity. Quick, make a blog post about how there have been over twenty comments about your use of English (though don't forget to point out that it's correct). > PS Although Amazon.com still says the publication date is the 27th, > they now expect to have it in stock on Monday (the 22nd). Congratulations. I know what a relief it is to see a project of that size come to fruition! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From skip at pobox.com Thu Dec 4 14:33:11 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 4 Dec 2008 13:33:11 -0600 Subject: python an sqlite objects In-Reply-To: <49382153.80604@mrabarnett.plus.com> References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <18742.47391.389709.119341@montanaro-dyndns-org.local> <49382153.80604@mrabarnett.plus.com> Message-ID: <18744.12407.398550.411202@montanaro-dyndns-org.local> >> # Ensure that we're running Python 3 or later. >> import sys >> assert int(sys.version.split()[0].split('.')[0]) >= 3 >> # If there's a better way to chek, please tell. >> MRAB> [snip] MRAB> Why split on whitespace and then '.'? MRAB> assert int(sys.version.split('.')[0]) >= 3 Why split at all? Just use sys.version_info: >>> import sys >>> assert sys.version_info[0] > 2, sys.version_info Traceback (most recent call last): File "", line 1, in ? AssertionError: (2, 4, 5, 'final', 0) vs: >>> import sys >>> print(sys.version_info) (3, 0, 0, 'final', 0) Skip From h0leforfun at gmail.com Wed Dec 17 09:11:45 2008 From: h0leforfun at gmail.com (Hole) Date: Wed, 17 Dec 2008 06:11:45 -0800 (PST) Subject: Python, XML and XPath Message-ID: Hi all, I hope this is not an "overasked" question but I find myself quite confused about python xml management (I have to use python for a project and I come from java world, you know...where frameworks, libraries and tools to use are standard de iure or standard de facto). I need to use XML parsing with xpath: a simple xml reader. I've found that the standard distribution of python doesn't include xpath support modules so I've decided to add libxml2. I've installed cygwin c compiler but I still have errors like the following: C:\Python25\Lib\libxml2-python-2.6.9>python setup.py build install C:\Python25\lib\distutils\dist.py:247: UserWarning: 'licence' distribution option is deprecated; use 'license' warnings.warn(msg) running build running build_py running build_ext building 'libxml2mod' extension writing build\temp.win32-2.5\Release\libxml2mod.def C:\MinGW\bin\gcc.exe -mno-cygwin -shared -s build \temp.win32-2.5\Release\libxml2-py.o build\temp.win32-2.5\Release \libxml.o build\temp.win32-2.5\Release\types.o build \temp.win32-2.5\Release\libxml2mod .def -L/usr\lib -LC:\Python25\libs -LC:\Python25\PCBuild -llibxslt - llibexslt -llibxml2 -lpython25 -lmsvcr71 -o build \lib.win32-2.5\libxmlmods\libxml2mod.pyd build\temp.win32-2.5\Release\libxml2-py.o:libxml2-py.c:(.text+0x1629): undefined reference to `_imp__xmlFree' build\temp.win32-2.5\Release\libxml2-py.o:libxml2-py.c:(.text+0x2802): undefined reference to `_imp__xmlFree' build\temp.win32-2.5\Release\libxml2-py.o:libxml2-py.c:(.text+0x44b2): undefined reference to `_imp__xmlFree' build\temp.win32-2.5\Release\libxml2-py.o:libxml2-py.c:(.text+0x50e4): undefined reference to `_imp__xmlFree' build\temp.win32-2.5\Release\libxml2-py.o:libxml2-py.c:(.text+0x5519): undefined reference to `_imp__xmlFree' build\temp.win32-2.5\Release\libxml2-py.o:libxml2-py.c:(.text+0x7339): more undefined references to `_imp__xmlFree' follow Does anyone know how to solve this issue or has suggestions for another (easy-to-install) xml-xpath library? Thanks for your support! From google at mrabarnett.plus.com Sun Dec 21 14:55:14 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 21 Dec 2008 19:55:14 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: <494E9F22.2000501@mrabarnett.plus.com> r wrote: > I noticed when i mentioned "self" nobody wants to touch that subject. > There could be many reasons why... > > 0.) nobody but the 10 regulars i see here exists > 1.) nobody cares(doubt it) > 2.) nobody is brave enough to question it(maybe) > 3.) most people like to type self over and over again(doubt it) > 4.) most people here have given up on changing the BDFL's mind about > it. (good possibility) > 5.) this is a hot-button topic(no doubt in my mind!) > 6.) nobody here wants to go through that whole discussion yet again From your.master at gmail.com Thu Dec 11 15:06:56 2008 From: your.master at gmail.com (Brandon) Date: Thu, 11 Dec 2008 12:06:56 -0800 (PST) Subject: dictionary idiom needed References: <383976cf-53fb-48e4-b028-8f568468ce77@r36g2000prf.googlegroups.com> Message-ID: <98f99282-811f-4067-9640-81013cea04bc@i18g2000prf.googlegroups.com> > Smells like homework without a particular application. @Scott: Even if that were the case :) I'd still like to figure out how to create nested dictionaries! Brandon From stefan_ml at behnel.de Tue Dec 30 08:28:37 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 30 Dec 2008 14:28:37 +0100 Subject: Any equivalent to Ruby's 'hpricot' html/xpath/css selector package? In-Reply-To: References: Message-ID: <495a2204$0$31871$9b4e6d93@newsspool3.arcor-online.net> Kenneth McDonald wrote: > Ruby has a package called 'hpricot' which can perform limited xpath > queries, and CSS selector queries. However, what makes it really useful > is that it does a good job of handling the "broken" html that is so > commonly found on the web. Does Python have anything similar, i.e. > something that will not only do XPath queries, but will do so on > imperfect HTML? lxml.html is your friend. http://codespeak.net/lxml/lxmlhtml.html Stefan From stefan_ml at behnel.de Fri Dec 5 10:14:35 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 05 Dec 2008 16:14:35 +0100 Subject: Small problem with Psyco In-Reply-To: <1d71a6ed-4d96-4e86-983c-a54e23fcf158@t3g2000yqa.googlegroups.com> References: <1d71a6ed-4d96-4e86-983c-a54e23fcf158@t3g2000yqa.googlegroups.com> Message-ID: <49394559$0$32670$9b4e6d93@newsspool2.arcor-online.net> bearophileHUGS at lycos.com wrote: > I post it here because I am using a Psyco version that was compiled by > people here. > I am using Python 2.6.1, on Win, with Psyco (1, 6, 0, 'final', 0). > > This minimized code: > > from psyco.classes import psyobj > class Bar(psyobj): > def __init__(self, baz): > pass > b = Bar(0) > > Produces: > C:\...\test.py:5: DeprecationWarning: object.__new__() takes no > parameters > b = Bar(0) I noticed that, too, when using Cython to compile a Python class that inherits from object into an extension type that inherits from its C equivalent at the C level. I assume that psyco does something similar here. Stefan From george.sakkis at gmail.com Tue Dec 9 11:31:41 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 9 Dec 2008 08:31:41 -0800 (PST) Subject: How to initialize a class variable once References: <493E5700.4030107@aim.com> Message-ID: <81b8e65d-f80c-4e84-8c50-b3f907b2212a@e6g2000vbe.googlegroups.com> On Dec 9, 10:36?am, Joe Strout wrote: > On Dec 9, 2008, at 4:31 AM, Brian Allen Vanderburg II wrote: > > > There is one situation where a module can be imported/executed ? > > twice, if it is the __main__ module. > > That's an excellent point -- this is something I've run into, and it ? > always feels a bit awkward to code around it. What's the standard ? > idiom for avoiding this issue in a complex app? ?Have a "main" file ? > that is not imported by anything else, and which does little but ? > launch stuff from some other module? Yes, I believe that's the common practice. Still, whenever I end up putting stuff in a "main" file and run into the double import problem (e.g. when pickling), I do an explicit "from main import *" after all the definitions, i.e.: # myscript.py __all__ = ['foo', 'Bar'] def foo(x,y): ... class Bar(object): .... from myscript import * if __name__ == '__main__': assert foo.__module__ == Bar.__module__ == 'myscript' George From bj_666 at gmx.net Wed Dec 24 03:30:41 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Dec 2008 08:30:41 GMT Subject: Strategy for determing difference between 2 very large dictionaries References: <1230102996.2303.1291616055@webmail.messagingengine.com> Message-ID: <6rea9hF16p8tU1@mid.uni-berlin.de> On Wed, 24 Dec 2008 03:23:00 -0500, python wrote: > Hi Gabriel, > > Thank you very much for your feedback! > >> k1 = set(dict1.iterkeys()) > > I noticed you suggested .iterkeys() vs. .keys(). Is there any advantage > to using an iterator vs. a list as the basis for creating a set? I > understand that an iterator makes sense if you're working with a large > set of items one at a time, but if you're creating a non-filtered > collection, I don't see the advantage of using an iterator or a list. > I'm sure I'm missing a subtle point here :) `keys()` creates a list in memory, `iterkeys()` does not. With ``set(dict.keys())`` there is a point in time where the dictionary, the list, and the set co-exist in memory. With ``set(dict.iterkeys())`` only the set and the dictionary exist in memory. Ciao, Marc 'BlackJack' Rintsch From metolone+gmane at gmail.com Sat Dec 6 17:52:04 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 6 Dec 2008 14:52:04 -0800 Subject: operators as variables References: <103920.71204.qm@web26006.mail.ukl.yahoo.com> Message-ID: "macc_200" wrote in message news:103920.71204.qm at web26006.mail.ukl.yahoo.com... > Hi, > just starting programming and have an elementary question > after playing around with lists but cannot find >the answer > with googling. > I have a list of variables and I would like some of those > variables to be integers and some to be operators so the > list would look something like [5 * 4 - 4 + 6] and then be > able to evaluate the result (i.e. get 10). How do you make > the interpreter see the operator as that instead of a string > and just echo the list back to me. > thanks, > Andy > (and suggestions for a decent Python book would be appreciated) See the operator module, and then check out pyparsing. -Mark From joe at strout.net Thu Dec 4 10:50:06 2008 From: joe at strout.net (Joe Strout) Date: Thu, 4 Dec 2008 08:50:06 -0700 Subject: simplest way to strip a comment from the end of a line? Message-ID: I have lines in a config file which can end with a comment (delimited by # as in Python), but which may also contain string literals (delimited by double quotes). A comment delimiter within a string literal doesn't count. Is there any easy way to strip off such a comment, or do I need to use a loop to find each # and then count the quotation marks to its left? Thanks, - Joe From vkseashoremack at googlemail.com Sat Dec 20 11:56:11 2008 From: vkseashoremack at googlemail.com (vkseashoremack at googlemail.com) Date: Sat, 20 Dec 2008 08:56:11 -0800 (PST) Subject: Dog Penis - Free Message-ID: <1b4417a3-6f7c-4c3c-9d59-60c12256163a@i20g2000prf.googlegroups.com> Dog Penis . . . *******CLICK HERE******** http://club247.cn/Dog-Penis ***************************** . . . . . . . . . . . . Dog Penis From n.kottiyath at gmail.com Wed Dec 24 13:15:29 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Wed, 24 Dec 2008 10:15:29 -0800 (PST) Subject: Iterating over objects of a class References: <2df27de3-7fa3-4ac9-acd9-f946939517cf@r37g2000prr.googlegroups.com> <6rfb7iF1fg5rU1@mid.uni-berlin.de> Message-ID: <65c317f6-4fb8-4d54-a811-9a3fff50a690@p2g2000prf.googlegroups.com> On Dec 24, 10:52?pm, "Diez B. Roggisch" wrote: > Kottiyath schrieb: > > > Hi, > > ? ?How can I iterate over all the objects of a class? > > ? ?I wrote the code like following: > > class baseClass(object): > > Consider adopting PEP 8 ?coding conventions. > > > > > ? ? __registry = [] > > > ? ? def __init__(self, name): > > ? ? ? ? self.__registry.append(self) > > ? ? ? ? self.name = name > > > ? ? def __iter__(self): > > ? ? ? ? baseClass.item = 0 > > ? ? ? ? return self.__registry[0] > > > ? ? def next(self): > > ? ? ? ? if baseClass.item >= len(self.__registry): > > ? ? ? ? ? ? raise StopIteration > > ? ? ? ? baseClass.item += 1 > > ? ? ? ? return self.__registry[baseClass.item - 1] > > > For testing, create the following objects- > > a = baseClass("Test1") > > b = baseClass("Test2") > > > class subClass (baseClass): > > ? ?pass > > c = subClass("Test3") > > > ---->Actual Iteration<---- > > for i in a: > > ? ? print i.name > > > Test1 > > Test2 > > Test3 > > > --------------------------------------------------- > > I see the following problems in the code: > > 1. I have to iterate over any of the objects. For correctness, I > > wanted to iterate over the class, like > > for i in baseClass(): > > ? ?do x > > but that will will create one more object - which I do not want. > > > 2. If the subclass wants to do somethings in its constructor, I am not > > sure how to update the registry. > > class subClass (baseClass): > > ? ?def __init__(self, name): > > ? ? ? ?**do something** > > ? ? ? ?super.init(self, name) ?----> This errors out, saying it needs > > super, not subClass > > You don't show the actual traceback, however the idiom for invoking > super for new-style-classes is > > super(subClass, self).__init__(name) > > for your case. > > > Another method I thought of implementing it was using generators - > > where-in baseClass.objects() is a generator which will yield the > > objects one by one - but even then the second issue remains. > > If somebody can help me out, I would be very thankful. > > Using a generator or not isn't the issue here. > > What you need is a *class*-based access, not instance-based. There are > various methods to accomplish this. The simplest is to ditch the > obnoxious __registry as name, and just do > > class BaseClass(object): > > ? ? REGISTRY = [] > > Then iterating is a simple matter of > > for instance in BaseClass.REGISTRY: > ? ? ... > > Case solved. Alternatively, if you insist on the concept of privacy for > that registry, you can use a classmethod: > > class BaseClass(object): > > ? ? @classmethod > ? ? def registry(cls): > ? ? ? ? for i in cls.__registry: > ? ? ? ? ? ? yield i > > Last but not least you *could* go for a __metaclass__ with an > __getitem__-method, that makes thinks look fancy because you then can do: > > for instance in BaseClass: > ? ? ?... > > I leave it as an exercise to you - gotta go christmas dining now :) > > Diez Thank you Very much, Diez. I was able to do the Generator and the super part of it, but I never even thought of the metaclass option. I will try it out. Thank you very much. Merry Christmas. P.S - >Also, I will use the PEP 8 coding conventions From nospam at forMe.thks Wed Dec 17 11:35:13 2008 From: nospam at forMe.thks (Ross) Date: Wed, 17 Dec 2008 11:35:13 -0500 Subject: Managing timing in Python calls In-Reply-To: References: Message-ID: Interesting stuff - I hadn't come across the 'with' syntax before, so I've learned something already. I was briefly excited to learn about the callLater command which is just a convenience class for the wxTimer class. It seems to be pretty much a parallel of the var t = window.setTimeout( function () { do_when_timed_out} sort of thing in AJAX. However, as is well grumbled on the 'net, you can't use wxTimer from a non-main thread. So that dropped off my plate. But getting my head around my AJAX problem versus my python implementation, I realized my use of those javascript structures were really just used because javascript doesn't allow any threading at all. With Python, just having my other processing path in a thread is enough, and I can use the brutish time.sleep() function, without worrying about blocking the processing of my mainline (UI) thread. So I'm able to proceed. I do want to know more about the 'with' command tho' so I'll look into that. Thx again. Ross. cmdrrickhunter at yaho.com wrote: > I believe WxTimerEvent is handled using the event queue, which isn't > going to do what you want. An event which goes through the queue does > not get processed until you return to the queue. > > What you want to do is actually a rather difficult task to do > generically. Should the task be interrupted immediately? Or is a > tiny latency acceptable? Should the function being terminated get to > handle its own termination? Or should the termination be forced on > it. What sort of overhead is acceptable for this "set_timeout" > behavior? > > I would not be surprised if there isn't a built in solution, because > its so hard, but rather built in tools which can be used to do it. > > If your timeouts are on the order of seconds, you might be able to > just check time.time() at the begining, and compare it to the current > time later in the function. This could be on the main thread or on a > worker thread. > > If you need better handling, you may want to look at how condition > variables and such work. > > Finally, thread has a function to send a Keyboard Interrupt to the > main thread. I believe you could do your work on the main thread, and > catch the interrupt. > > "Background" tasks are not easy to implement in any language (other > than perhaps AJAX ;-) ). > > Remember, Python does not support truly simultaneous threads. It > actually does timeslices of about 100 operations. Any solution you > choose should work given this information. > > And as for a "nicer" construct, I personally just learned of how to > handle the "with" command. I could see something like > > class Timeout: > def __init__(self, t): > self.t = t > def __enter__(self): > self.start = time.time() > def __exit__(self, x, y, z): > return None > def __nonzero__(self): > return time.time() - self.start <= self.t > > > def doSomethingLong(timeout = True): # true guarentees bailout never > occurs > while timeout: > doAnIteration() > > with Timeout(3) as t: > doSomethingLong(t) > > > > and have your Timeout class have a flag which it sets when > doSomethingLong needs to bail out, using whatever method is "best" for > your particular application. This is, of course pseudocode - I've not > run it through python msyself. Hopefully any errors are obvious > enough that you can work around them. From cournape at gmail.com Mon Dec 29 22:35:45 2008 From: cournape at gmail.com (David Cournapeau) Date: Tue, 30 Dec 2008 12:35:45 +0900 Subject: print a vs print '%s' % a vs print '%f' a In-Reply-To: References: <5b8d13220812291919h700f1586q5ab68ec6edb927f1@mail.gmail.com> Message-ID: <5b8d13220812291935i1a8de1e2h9ee08e9e668f9cad@mail.gmail.com> On Tue, Dec 30, 2008 at 12:23 PM, James Mills wrote: > On Tue, Dec 30, 2008 at 1:19 PM, David Cournapeau wrote: > (... snip ...) > >> print '%f' % a # -> print '1.#INF' > > Would this not be controlled by: > 1. float(a) or a.__float__() > 2. tp_print Bah, I made a mistake in my example: complex('inf') should read float('inf') (complex('inf') does not work). So 1 is out :) If I read correctly the code, tp_print also calls the format_float function (as tp_str, and tp_repr), so it looks like it is not used in that case. cheers, David From rtw at freenet.co.uk Tue Dec 30 21:49:41 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Tue, 30 Dec 2008 20:49:41 -0600 Subject: Triple quoted string in exec function ? References: <016abfa1$0$6988$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote in news:016abfa1$0$6988$c3e8da3 at news.astraweb.com in comp.lang.python: > On Tue, 30 Dec 2008 15:35:28 -0600, Rob Williscroft wrote: > >> Stef Mientki wrote in news:mailman.6399.1230668197.3487.python- >> list at python.org in comp.lang.python: >> >>>>> And, by the way, exec is a *statement*, not a function! >>>>> >>> exec ( Init_Code, PG.P_Globals ) >>> >>> I've really doubt that this is a statement, unless I don't understand >>> what a statement is. >>>>> >>>>> >>> >> In python 2.x the above is a statement that is passed a tuple: >> >> http://docs.python.org/reference/simple_stmts.html#exec > > > The documentation doesn't say anything about it accepting a tuple as an > argument. The tuple argument works in both 2.5 and 2.6. Curious. > My mistake, it is also behaving as a function: http://docs.python.org/dev/3.0/whatsnew/3.0.html#removed-syntax Removed keyword: exec() is no longer a keyword; it remains as a function. (Fortunately the function syntax was also accepted in 2.x.) Also ... Though that was the only documentation of it I found in a brief web search. > I was also surprised by this behaviour: > >>>> g, l = {}, {} # no globals, no locals >>>> exec "x = 1" in g, l >>>> l > {'x': 1} >>>> g.keys() > ['__builtins__'] > > I see *now* that this is documented: > > "...the current implementation MAY add a reference to the dictionary of > the built-in module __builtin__ under the key __builtins__ (!)." > [emphasis added] > > but it's still rather disconcerting. That means that: > > exec "some potentially dangerous code" in {}, {} > > isn't as safe as I thought it was. AIUI it isn't meant to be safe, it provides some data hiding that is useful for programming purposes but isn't much use for security. Another example of a security hole: >>> def f(): ... print "f()" ... >>> exec "from __main__ import f; f()" f() >>> Rob. -- http://www.victim-prime.dsl.pipex.com/ From venutaurus539 at gmail.com Wed Dec 3 23:43:52 2008 From: venutaurus539 at gmail.com (venu madhav) Date: Thu, 4 Dec 2008 10:13:52 +0530 Subject: Obtaining SMTP address of a sender and receiver of an outlook mail In-Reply-To: References: Message-ID: Hi, I don't have access to the AD server because only the administrators here have those rights. Aren't there any MAPI Sender and Recipient object properties which satisfies my need? Thank you, Venu. On Thu, Dec 4, 2008 at 9:00 AM, BJ Swope wrote: > If you have access to the AD server that hosts those DNs you can use > python's ldap module to retrieve the smtp attribute for the DN you've just > parsed from the message. > > On Wed, Dec 3, 2008 at 2:06 AM, venutaurus539 at gmail.com < > venutaurus539 at gmail.com> wrote: > >> Hi all, >> I am trying to use python for extracting contents of an outlook >> email. For extracting the list of Recipients addresses I tried using >> the "MAPI.message.Recipients.Address" property, but the problem I am >> facing is that it is giving the complete DN name which is putting me >> in further complications. Is there any way to obtain the actual SMTP >> mail address (username at domain.com) from the above object? I searched >> for it in the MSDN help but couldn't succeed. >> >> Thanks in advance, >> Venu >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From arkanes at gmail.com Thu Dec 11 13:34:03 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 11 Dec 2008 12:34:03 -0600 Subject: Is 3.0 worth breaking backward compatibility? In-Reply-To: <4731f7cf-ef15-4328-85a4-de4437009f2e@40g2000prx.googlegroups.com> References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> <20081207203553.7d62434a@usenot.de> <4731f7cf-ef15-4328-85a4-de4437009f2e@40g2000prx.googlegroups.com> Message-ID: <4866bea60812111034t6dd4f204ka236835812ba9e5a@mail.gmail.com> On Thu, Dec 11, 2008 at 12:21 PM, walterbyrd wrote: > On Dec 7, 12:35 pm, Andreas Waldenburger wrote: > >> Pleeeeze. Python 3 is shipping now, and so is 2.x, where x > 5. Python >> 2 is going to be around for quite some time. What is everybody's >> problem? > > A possible, potential, problem, could arise if you were using python > 2.x, but some other code, that you wanted to include, was writen in > python 3.x. A possible, potential, problem, could arise if you were using [Java], but some other code, that you wanted to include, was writen in [Pascal]. Surely the software industry is doomed? From castironpi at gmail.com Mon Dec 8 15:01:42 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 8 Dec 2008 12:01:42 -0800 (PST) Subject: var or inout parm? References: Message-ID: On Dec 7, 2:54?am, m... at pixar.com wrote: > How can I make a "var" parm, where the called function can modify > the value of the parameter in the caller? > > def f(x): > ? ? x = x + 1 > > n = 1 > f(n) > # n should now be 2 You can't. 'n' would need a 'set_to' method, which it doesn't have. Otherwise, that's not what the equal sign does. From martin at v.loewis.de Thu Dec 4 20:10:22 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 05 Dec 2008 02:10:22 +0100 Subject: Running Python 2 and Python 3 on the same machine In-Reply-To: <1228424486.5873.6.camel@linux-3eb6.site> References: <1228424486.5873.6.camel@linux-3eb6.site> Message-ID: <49387f7e$0$27857$9b622d9e@news.freenet.de> > Since the source code is incompatible, I was expecting the Python > executable to have a new name such as 'python3' It does: the executable is called python3.0. > or for the default > source code filename to change to '.py3' or something. Such a proposal would be rejected. In a few years from now, Python 2 will be gone, and we would be stuck with an ugly file extension (similar to how \windows\system is now an empty directory, and \windows\system32 actually contains the 64-bit binaries on x64)- Regards, Martin From mcrute at gmail.com Thu Dec 4 19:46:06 2008 From: mcrute at gmail.com (Michael Crute) Date: Thu, 4 Dec 2008 19:46:06 -0500 Subject: Importing Version Specific Modules In-Reply-To: <18744.30436.32591.969670@montanaro-dyndns-org.local> References: <558b73fb0812041529g313a27bpcfd09fc90f474f6e@mail.gmail.com> <18744.30436.32591.969670@montanaro-dyndns-org.local> Message-ID: <558b73fb0812041646r669accc3q293adeb0cac10262@mail.gmail.com> On Thu, Dec 4, 2008 at 7:33 PM, wrote: > Michael> try: > Michael> from string import Template > Michael> except ImportError: > Michael> from our.compat.string import Template > > This is "easier to ask forgiveness than permission" (EAFP). This tends to > be more Pythonic (and thus, preferred). You don't *really* care what the > version just, but whether or not the string module has a Template object. > Besides, what if some bright admin at some customer decides to backport the > Template implementation to their 2.4 installation? The first form would > load your compatibility version, probably not what they were hoping when > they put in the effort to backport. That was the kind of reasoning I'm looking for. I'll stick with the pythonic try/except approach then. -mike -- ________________________________ Michael E. Crute http://mike.crute.org God put me on this earth to accomplish a certain number of things. Right now I am so far behind that I will never die. --Bill Watterson From ajaksu at gmail.com Tue Dec 23 16:57:37 2008 From: ajaksu at gmail.com (ajaksu) Date: Tue, 23 Dec 2008 13:57:37 -0800 (PST) Subject: python3 urlopen(...).read() returns bytes References: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> <5496b34d-7ce4-4281-9f01-aed12dab9fd3@f33g2000vbf.googlegroups.com> <42ad842c-8d8a-4ff5-a721-0688b7ae20f7@41g2000yqf.googlegroups.com> Message-ID: <9d0248cc-6ba3-44f8-a60a-e5565b7d20ab@f11g2000vbf.googlegroups.com> On Dec 23, 12:51?pm, Christian Heimes wrote: > If you want to do it right ... It should be a clean patch against the > py3k svn branch including documentation and a unit test. Got all three at http://bugs.python.org/issue4733 . Probably got all three wrong too, so any feedback is very welcome :) I think a neat improvement, besides better docs, names, code, etc., would be to implement Carl Bank's idea of checking Content-Encoding. Oh, and there's a 'print("Using default charset '%s'" % response.charset)' in there that seemed educational when I wrote it, but now sounds lame :) Glenn, can you test the patch[1] there? Thanks for the encouragement, Chris! I hope we don't regret it :D Daniel [1]http://bugs.python.org/file12437/urlopen_text.diff From sjmachin at lexicon.net Sun Dec 28 17:02:03 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 28 Dec 2008 14:02:03 -0800 (PST) Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <0167cbf7$0$6988$c3e8da3@news.astraweb.com> <088c7d93-e87f-44a0-9ea7-faa7feded7df@a26g2000prf.googlegroups.com> Message-ID: <67f19f31-8554-416c-bf75-344ed12493b0@e1g2000pra.googlegroups.com> On Dec 29, 8:36?am, Benjamin wrote: > On Dec 28, 1:35?pm, Steven D'Aprano > cybersource.com.au> wrote: > > The second thing I think is that maybe the function is a generator, and > > so I look for a yield. > > You shouldn't, though; Generators can't contain any return statement. What gave you that impression? Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def foo(): ... for i in range(4): ... yield i ... return ... >>> foo >>> x = foo() >>> x >>> list(x) [0, 1, 2, 3] >>> def bar(): ... for i in range(4): ... yield i ... return 42 ... File "", line 4 SyntaxError: 'return' with argument inside generator (go to http://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy then scroll down) Generator functions A function or method which uses the yield statement (see section The yield statement) is called a generator function. Such a function, when called, always returns an iterator object which can be used to execute the body of the function: calling the iterator?s next() method will cause the function to execute until it provides a value using the yield statement. When the function executes a return statement or falls off the end, a StopIteration exception is raised and the iterator will have reached the end of the set of values to be returned. From BrianVanderburg2 at aim.com Wed Dec 17 07:38:38 2008 From: BrianVanderburg2 at aim.com (Brian Allen Vanderburg II) Date: Wed, 17 Dec 2008 07:38:38 -0500 Subject: Relative imports in Python 3.0 In-Reply-To: References: Message-ID: <4948F2CE.8040102@aim.com> nicholas.cole at gmail.com wrote: > Imagine a module that looks like > > ModuleDir > __init__.py > a.py > b.py > > > In python 2.x I used to have tests at the end of each of my modules, > so that module b.py might look something like > > import a > .......... > .......... > > if __name__ == '__main__': > runtests() > > But under Python 3.0 this seems impossible. For usual use import a.py > has to become the line: > > from . import a > > But if I use that form it is no longer possible to run b.py as a > standalone script without raising an error about using relative > imports. > > I am sure I am not the first to run into this issue, but what is the > solution? > > Best wishes, > > Nicholas > -- > http://mail.python.org/mailman/listinfo/python-list > Sorry for the duplicate, sent to wrong email. Python 3 (and I think 2.6) now use absolute import when using a 'import blah' statement. if ('.' in __name__) or hasattr(globals, '__path__'): from . import a else: import a If '__name__' has a'.' then it is either a package or a module in a package, in which case relative imports can be used. If it does not have a '.' it may still be a package but the '__init__.py' file, in which case the module has a '__path__' attribute, so relative imports can be used. Otherwise it is not a package or in a package so absolute imports must used. Also, since it is not in a package it is assumed that it is top module (__main__) or possible module imported from the top that is not in a package, such as a.py doing an 'import b', b would be a module but not a package so still probably need absolute imports, my guess anyway. But I also think that 'from . import a' would be nice if it would work from non-packages as well, meaning just 'import a' if it is a non-package. Brian A. Vanderburg II From stephen at thorne.id.au Mon Dec 22 07:20:58 2008 From: stephen at thorne.id.au (Stephen Thorne) Date: Mon, 22 Dec 2008 22:20:58 +1000 Subject: no sign() function ? In-Reply-To: <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <20081222122058.GA8543@thorne.id.au> On 2008-12-22, Pierre-Alain Dorange wrote: > def sign(x): > if x==0.0: > return 0.0 > elif x>0.0: > return 1.0 > else: > return -1.0 Isn't this approximately this? :: def sign(x): return float(cmp(x, 0)) Or if you don't want a float response:: def sign(x): return cmp(x, 0) -- Regards, Stephen Thorne Development Engineer NetBox Blue - 1300 737 060 From hackingkk at gmail.com Mon Dec 15 08:46:03 2008 From: hackingkk at gmail.com (Krishnakant) Date: Mon, 15 Dec 2008 19:16:03 +0530 Subject: %s place holder does not let me insert ' in an sql query with python. In-Reply-To: References: <1229345178.31093.24.camel@krishna-laptop> Message-ID: <1229348763.31093.38.camel@krishna-laptop> hello all, thanks for all of your very quick responses. The problem is that I am using python 2.5 so the 2.6 syntax does not apply in my case. secondly, My problem is very unique. I have created a function called executeProcedure in python which calls stored procedures in postgresql. The fun part of this function is that it has just got 3 standard parameters namely the name of the sp to be called, whether it returns 1 or more records as a result and the list containing the input parameters which that sp will need for execution. So no matter what your sp does as in insert update delete or select, no matter there is one param or 10 all you have to do is pass one string containing the function name, one boolean and one list of params. The rest is taken care by this python function. So now all hackers will understand that the query to call the stored procedure namely cursor.execute(select * from functname ) will be built dynamically. So now in this situation I have to build the querystring and then pass it to execute of the cursor. in this case, I get a problem when there is ' in any of the values during insert or update. If any one wants this code, Please let me know. You all can get a lot of utility out of the function. This only becomes a problem when an ' comes in the value. So I need help to fix the problem with the given context. happy hacking. Krishnakant. On Mon, 2008-12-15 at 07:21 -0600, Lamonte Harris wrote: > sorry about that > > queryString = "insert into venders > values('{0}','{1}','{2}')".format(field1,field2,field3) > > On Mon, Dec 15, 2008 at 7:21 AM, Lamonte Harris > wrote: > I had this problem too. If you've upgraded to python 2.6 you > need to use the new sytnax "format > > queryString = "insert into venders > values('{0}','{1}','{2}'".format(field1,field2,field3) > > > > On Mon, Dec 15, 2008 at 6:46 AM, Krishnakant > wrote: > hello all hackers. > This is some kind of an interesting situation although > many of you must > have already gone through it. > I am facing a situation where I have to use psycopg2 > and insert rows in > a postgresql table. > That's pritty easy and no need to say that it works > well. But there are > some entries which have an ' in the value. > I have a venders table in my database and one of the > values tryed was > "His Master's Voice " > now the master's word has the ' which is used for > starting and ending a > varchar value for postgresql or almost any standard > RDBMS. > Does any one know what is the way out of this? > how do you let the ' go as a part of the string? > I have used %s as placeholder as in > queryString = "insert into venders values ('%s,%s,%s" > % > (field1,field2,field3 ) ... > This is not working for the ' values. > can any one suggest a suitable solution? > happy hacking. > Krishnakant. > > -- > http://mail.python.org/mailman/listinfo/python-list > > > From saltmarch2008 at gmail.com Fri Dec 12 00:56:23 2008 From: saltmarch2008 at gmail.com (Shaguf) Date: Thu, 11 Dec 2008 21:56:23 -0800 (PST) Subject: Apache Tapestry Creator to Speak on Clojure, Tapestry 5 Message-ID: <62f4890b-0eab-426b-b9c8-8645d7475f94@r36g2000prf.googlegroups.com> Apache Tapestry Creator to Speak on Clojure, Tapestry 5 Bangalore, December 10, 2008: If you are a Java developer building web- based applications and tired of the countless frameworks that promise you a slick UI fast but fail to live up to their promise, then switch to Apache Tapestry to get more functionality with less code. The creator of Tapestry, Howard Lewis Ship, is coming this summer to India's biggest summit for the developer ecosystem - Great Indian Developer Summit (http://www.developersummit.com/) to speak on the recently released Tapestry 5.0 version, covering the core IoC container, how to define and inject services and advanced topics such as decorating services to provide additional concerns, or creating services in terms of design patterns such as chain-of-command and pipeline. On April 25, the author of 'Tapestry in Action' will also conduct a 3- hour, hands on workshop on building your own Tapestry applications. Hew will cover what it means to be a component web framework, what advantages that brings, how to create database-driven web applications using Hibernate, show off Tapestry's live class reloading, advanced error reporting and other productivity features, how Tapestry can be tuned and customized and build new components. A frequent speaker at JavaOne, NoFluffJustStuff, ApacheCon Howard will also throw the spotlight on Clojure -- made up of one part Lisp (one of the oldest computer languages), one part Java (so young, yet so well adopted), a healthy serving of functional programming, and a state-of-the-art concurrency layer on top. Clojure embraces functional programming with immutable data types and first class functions. It is fully interoperable with Java. Clojure's approach to concurrency includes asynchonous Agents, and Software Transactional Memory. About Great Indian Developer Summit Great Indian Developer Summit, produced by Saltmarch Media, is the biggest gathering of software developers from Java/J2EE, Microsoft computing technologies, Rich Internet Applications (RIA), Web 2.0, Ajax, Agile, SOA, and Enterprise IT. For both veterans and newcomers to the world of .NET, Java, and the Rich Web, the Great Indian Developer Summit provides participants with a well-balanced learning experience that guaranteed they went back with a richer understanding of the technologies that make a difference to their careers. See the GIDS 2008 Red Stripe Report: http://www.developersummit.com/2008/report/pdf/Red_Stripe_Report-GIDS08.zip Over 3000 qualified and talented delegates - Source, attended GIDS 2008: The Hindu - Monday, 26 May 2008 (http://www.developersummit.com/ 2008/report/postPress.html). With outstanding educational sessions, powerhouse speakers, a high-profile award ceremony, GIDS 2009 will feature premium knowledge, action plans and advise from been-there- done-it veterans, creators, and visionaries. For further information on GIDS 2009, please visit the summit on the web http://www.developersummit.com/. A Saltmarch Media Press Release E: info at developersummit.com Ph: +91 080 4005 1000 From mensanator at aol.com Sat Dec 6 23:16:56 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 6 Dec 2008 20:16:56 -0800 (PST) Subject: "as" keyword woes References: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> <0147dc24$0$20670$c3e8da3@news.astraweb.com> <0148b217$0$20670$c3e8da3@news.astraweb.com> <7d0lj4d9hai2f87r30erc4l1ir85osbfg7@4ax.com> <88579d9a-df52-49b9-a6fe-53c8f4524bf3@j39g2000yqn.googlegroups.com> <70llj41hie2svs68o5efn22i97f649svfh@4ax.com> <1cda9a9a-1641-424b-9f3d-c4e2635efed7@j38g2000yqa.googlegroups.com> <014b0f94$0$20670$c3e8da3@news.astraweb.com> <4469f2ed-f012-400d-9d4f-bd44cd075d0d@w34g2000yqm.googlegroups.com> <014b3616$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Dec 6, 9:09?pm, Steven D'Aprano wrote: > On Sat, 06 Dec 2008 18:09:07 -0800, Mensanator wrote: > > On Dec 6, 6:25 pm, Steven D'Aprano > cybersource.com.au> wrote: > >> On Sat, 06 Dec 2008 14:36:07 -0800, Mensanator wrote: > >> > It was extremely simple for me to fix the sympy module where I > >> > noticed it. I'm not saying it wasn't a problem, I'm saying it wasn't > >> > BROKEN. > > >> If it wasn't broken, why did you need to fix it? > > > If my tire is flat, I have to fix it. But it may just need air, in which > > case it's not broken. > > In which case it doesn't need *fixing*, The state of the tire being flat has to be fixed, but not necessarily the tire. > it needs *refilling*. A flat tire > isn't necessarily broken. It is broken if it has a puncture or a slow > leak or has been ripped to shreds, but not if somebody merely let the air > out. "Air comes out if you open the value" is within standard operating > parameters and the tire is therefore working correctly. Just as "as" producing a syntax error is working correctly. > > >> "Broken" means "not working", not "unfixable". > > > So, you're saying that Python is broken and will remain so forever, > > since "as" will remain a keyword? > > I don't think that having "as" be a keyword is broken. But WS does and you appear to be taking his side. > I think the OP's > code is broken for Python 2.6 or better, So do I. Why are you arguing then? Simply to be pedantic about the meaning of "broken"? > and it will remain broken > forever unless he fixes it or chooses to stay with 2.5. > > > Are you advocating that we all switch to Ruby? > > Why do you think that? Because seem to be agreeing that the problem is with Python. If that's not what you meant, it's not coming across that way. > Do you imagine that Ruby has no features which are > inconvenient to users, or backwards incompatibilities, or warts, or that > it is impossible to write broken Ruby code? Who knows what you believe if you're agrreing that Python is permanently broken? > > -- > Steven From alessio.pace at gmail.com Mon Dec 1 01:33:43 2008 From: alessio.pace at gmail.com (Alessio Pace) Date: Sun, 30 Nov 2008 22:33:43 -0800 (PST) Subject: How to distribute a Python app together with its dependencies? References: <1ded1134-4933-4e05-953d-f93ac27c17e8@x16g2000prn.googlegroups.com> Message-ID: <5d9114c9-790a-49bb-8631-af8f36e0262a@o2g2000yqd.googlegroups.com> On 1 Dic, 05:23, Lev Elbert wrote: > If Python for Windows you can use Py2Exe package. It works very well > in simple cases and requires a few tweaks to make it recognize some > dependencies. As I was saying above, the destination machines are all Unix. Thank you anyway for your suggestion, I'll keep it in mind if I can to deploy on Windows too. -- Alessio Pace. From stef.mientki at gmail.com Fri Dec 19 11:58:36 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 19 Dec 2008 17:58:36 +0100 Subject: Building a web questionnaire, can it be done in Python ? Message-ID: <494BD2BC.4050000@gmail.com> hello, I'm considering building a web questionnaire in Python. I've made several desktop applications in Python / wxPython, but I've no experience in using Python on a webserver, and I don't have much knowledge about web applications in general. As am quit familiar with Python, therefor it sounds evident to me to make the web application in Python, but I'm not sure that's really the best way. I've googled, but the links I get, makes me more confused: Zope, Plone , ...?? And I can find a lot in other languages Perl, JavaScript, PHP, CGI, ... So maybe someone on this list can give me some advise, a good starting point, because it's almost impossible to evaluate all the possibilities myself, and I'm afraid the first choice will be the final choice ;-) The questionnaires are used to diagnose and treat all kinds of patients in a hospital. Therefor I need 2 versions, a web-version and a desktop version, the latter I need to be able to lock the computer. The desktop version is no problem, neither the locking. Also the analysis and reporting of the data will be done in a desktop application. The problematic (at least form my point of view) requirements: ================================================ The content and layout comes from an existing database. The layout of the desktop version and the web-version should be almost identical to the paper and pencil version (most norms are based on the paper and pencil version) The questions can have different forms, multiple choice, multiple choice with multiple answers, but also things like sliders. The answering should also be possible with the keyboard only: e.g. 1,2,.. for the answers, PgUp / PgDn or Enter for previous / next question. The web application should have some kind of security (soap ? https ?) and a login. Depending on answers to previous questions, some questions should be ignored. Depending on answers to previous questions, some questionnairies should be ignored. Patient should be able to browse within 1 questionnaire, but not to the previously answered ones. After each questionnaire there should be check if all questions were answered. Should run in IE and Mozilla. I'm not sure about this one yet: While a session can take several hours, it could be beneficial to connect to the internet only at some intermediate intervals, or when one questionnaire is completely finished. thanks, Stef From steve at holdenweb.com Tue Dec 23 07:06:01 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 23 Dec 2008 07:06:01 -0500 Subject: On Whose Desktop Message-ID: Thanks to Barry Warsaw the "On Your Desktop" blog now has a new entry: http://onyourdesktop.blogspot.com/ Who would you like to see profiled next? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From prologic at shortcircuit.net.au Thu Dec 18 19:23:30 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Dec 2008 10:23:30 +1000 Subject: importing csv file into sqlite In-Reply-To: References: <21067453.post@talk.nabble.com> Message-ID: On Fri, Dec 19, 2008 at 10:11 AM, Gabriel Genellina wrote: > But your code does *exactly* that, it reads the whole file in memory: > >> def mkBuffer(fd): >> buffer = StringIO() >> buffer.write(fd.read()) >> ... > > That mkBuffer function has no useful purpose IMHO, just remove it. It was a mistake in my implementation at the time of writing :) I've since fixed and removed it! Thanks though :) cheers James From n.kottiyath at gmail.com Wed Dec 24 13:18:55 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Wed, 24 Dec 2008 10:18:55 -0800 (PST) Subject: Iterating over objects of a class References: <2df27de3-7fa3-4ac9-acd9-f946939517cf@r37g2000prr.googlegroups.com> <6rfb7iF1fg5rU1@mid.uni-berlin.de> Message-ID: <7f47994f-13b6-45c4-920a-83aa72282bec@i20g2000prf.googlegroups.com> On Dec 24, 11:04?pm, MRAB wrote: > Diez B. Roggisch wrote: > > Kottiyath schrieb: > >> Hi, > >> ? ?How can I iterate over all the objects of a class? > >> ? ?I wrote the code like following: > >> class baseClass(object): > > > Consider adopting PEP 8 ?coding conventions. > > >> ? ? __registry = [] > > >> ? ? def __init__(self, name): > >> ? ? ? ? self.__registry.append(self) > >> ? ? ? ? self.name = name > > >> ? ? def __iter__(self): > >> ? ? ? ? baseClass.item = 0 > >> ? ? ? ? return self.__registry[0] > > >> ? ? def next(self): > >> ? ? ? ? if baseClass.item >= len(self.__registry): > >> ? ? ? ? ? ? raise StopIteration > >> ? ? ? ? baseClass.item += 1 > >> ? ? ? ? return self.__registry[baseClass.item - 1] > > >> For testing, create the following objects- > >> a = baseClass("Test1") > >> b = baseClass("Test2") > > >> class subClass (baseClass): > >> ? ?pass > >> c = subClass("Test3") > > >> ---->Actual Iteration<---- > >> for i in a: > >> ? ? print i.name > > >> Test1 > >> Test2 > >> Test3 > > >> --------------------------------------------------- > >> I see the following problems in the code: > >> 1. I have to iterate over any of the objects. For correctness, I > >> wanted to iterate over the class, like > >> for i in baseClass(): > >> ? ?do x > >> but that will will create one more object - which I do not want. > > >> 2. If the subclass wants to do somethings in its constructor, I am not > >> sure how to update the registry. > >> class subClass (baseClass): > >> ? ?def __init__(self, name): > >> ? ? ? ?**do something** > >> ? ? ? ?super.init(self, name) ?----> This errors out, saying it needs > >> super, not subClass > > > You don't show the actual traceback, however the idiom for invoking > > super for new-style-classes is > > > super(subClass, self).__init__(name) > > > for your case. > > >> Another method I thought of implementing it was using generators - > >> where-in baseClass.objects() is a generator which will yield the > >> objects one by one - but even then the second issue remains. > >> If somebody can help me out, I would be very thankful. > > > Using a generator or not isn't the issue here. > > > What you need is a *class*-based access, not instance-based. There are > > various methods to accomplish this. The simplest is to ditch the > > obnoxious __registry as name, and just do > > > class BaseClass(object): > > > ? ?REGISTRY = [] > > > Then iterating is a simple matter of > > > for instance in BaseClass.REGISTRY: > > ? ?... > > > Case solved. Alternatively, if you insist on the concept of privacy for > > that registry, you can use a classmethod: > > > class BaseClass(object): > > > ? ?@classmethod > > ? ?def registry(cls): > > ? ? ? ?for i in cls.__registry: > > ? ? ? ? ? ?yield i > > > Last but not least you *could* go for a __metaclass__ with an > > __getitem__-method, that makes thinks look fancy because you then can do: > > > for instance in BaseClass: > > ? ? ... > > > I leave it as an exercise to you - gotta go christmas dining now :) > > The other thing to remember is that because the 'registry' contains > references to the instances, they won't be garbage collected. Is there any other way out in this case? I have factory methods - and I have to loop over them - sort of Chain of Responsibility pattern. Having a registry inside the class instance and looping through them was the only clean thing I could think of. I understand that garbage collection would be an issue - but is there any way out? From istvan.albert at gmail.com Thu Dec 4 15:40:34 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Thu, 4 Dec 2008 12:40:34 -0800 (PST) Subject: Python 3 read() function References: Message-ID: <4dc8248b-2620-4bea-ba69-688c8f2da855@w39g2000prb.googlegroups.com> Turns out write performance is also slow! The program below takes 3 seconds on python 2.5 17 seconds on python 3.0 yes, 17 seconds! tested many times in various order. I believe the slowdowns are not constant (3x) but some sort of nonlinear function (quadratic?) play with the N to see it. =================================== import time start = time.time() N = 10**6 fp = open('testfile.txt', 'wt') for n in range(N): fp.write( '%s\n' % n ) fp.close() end = time.time() print (end-start) From prologic at shortcircuit.net.au Mon Dec 29 01:08:22 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 29 Dec 2008 16:08:22 +1000 Subject: why cannot assign to function call In-Reply-To: <495867C2.7080807@gmail.com> References: <495867C2.7080807@gmail.com> Message-ID: On Mon, Dec 29, 2008 at 4:01 PM, scsoce wrote: > I have a function return a reference, and want to assign to the reference, > simply like this: >>>def f(a) > return a > b = 0 > * f( b ) = 1* > but the last line will be refused as "can't assign to function call". > In my thought , the assignment is very nature, but why the interpreter > refused to do that ? That's exactly right. You _cannot_ assign to a function call. This is invalid in just about _all_ languages. Assignments are generally bound to a variable. >>> def f(a): ... return a ... >>> b = 0 >>> x = f(b) >>> x 0 >>> cheers James From digisatori at gmail.com Fri Dec 19 11:58:16 2008 From: digisatori at gmail.com (digisatori at gmail.com) Date: Fri, 19 Dec 2008 08:58:16 -0800 (PST) Subject: encoding problem References: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> <6r1m72Ffb5kpU3@mid.uni-berlin.de> Message-ID: <8522bfaf-7efc-4ebb-a63a-b5ecc73e236d@35g2000pry.googlegroups.com> On 12?19?, ??9?34?, Marc 'BlackJack' Rintsch wrote: > On Fri, 19 Dec 2008 04:05:12 -0800, digisat... at gmail.com wrote: > > The below snippet code generates UnicodeDecodeError. > > #!/usr/bin/env > > python > > #--*-- coding: utf-8 --*-- > > s = '???' > > u = unicode(s) > > > It seems that the system use the default encoding- ASCII to decode the > > utf8 encoded string literal, and thus generates the error. > > > The question is why the Python interpreter use the default encoding > > instead of "utf-8", which I explicitly declared in the source. > > Because the declaration is only for decoding unicode literals in that > very source file. > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch Thanks for the answer. I believe the declaration is not only for unicode literals, it is for all literals in the source even including Comments. we can try runing a source file without encoding declaration and have only 1 line of comments with non-ASCII characters. That will arise a Syntax error and bring me to the pep263 URL. I read the pep263 and quoted below: Python's tokenizer/compiler combo will need to be updated to work as follows: 1. read the file 2. decode it into Unicode assuming a fixed per-file encoding 3. convert it into a UTF-8 byte string 4. tokenize the UTF-8 content 5. compile it, creating Unicode objects from the given Unicode data and creating string objects from the Unicode literal data by first reencoding the UTF-8 data into 8-bit string data using the given file encoding The above described Python internal process indicate that the step 2 will utilise the specific encoding to decode all literals in source, while in step5 will evolve a re-encoding with the specific encoding. That is the reason why we have to explicitly declare a encoding as long as we have non-ASCII in source. Bruno answered why we need specify a encoding when decoding a byte string with perfect explanation, Thank you very much. From duncan.booth at invalid.invalid Sat Dec 13 16:24:09 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Dec 2008 21:24:09 GMT Subject: stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <1ff0d642-b560-433c-b793-3a05f5b051b9@g1g2000pra.googlegroups.com> Message-ID: Aaron Brady wrote: >So, what's the group policy on helping with homework? rhetorical> In my book anyone who is dumb enough to ask for homework help on a newsgroup and doesn't acknowledge that when they hand in their answer deserves whatever they get. Oh, and of course there are 2 deliberate error in the 'solution' I posted so they're not going to get full marks if they simply reuse it. (If there are more than 2 errors then at least one of them is not deliberate.) That's assuming the teacher is savvy enough to keep an eye on the obvious sources for quick answers. From federico at linux.com.uy Fri Dec 19 08:29:25 2008 From: federico at linux.com.uy (Federico Moreira) Date: Fri, 19 Dec 2008 10:29:25 -0300 Subject: Generator slower than iterator? In-Reply-To: <62013718-57e9-4690-a2be-11e63b9c135b@u18g2000pro.googlegroups.com> References: <62013718-57e9-4690-a2be-11e63b9c135b@u18g2000pro.googlegroups.com> Message-ID: Great, 2min 34 secs with the open method =) but why? ip, sep, rest = line.partition(' ') match_counter[ip] += 1 instead of match_counter[line.strip()[0]] += 1 strip really takes more time than partition? I'm having the same results with both of them right now. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davidgshi at yahoo.co.uk Thu Dec 18 10:42:08 2008 From: davidgshi at yahoo.co.uk (David Shi) Date: Thu, 18 Dec 2008 15:42:08 +0000 (GMT) Subject: Extracting data from XML containing CDATA and store data in a .dbf file Message-ID: <989642.86682.qm@web26307.mail.ukl.yahoo.com> I am looking for advice/efficient script to extract data from XML containing CDATA. ? I wish to extract all the data and store it in a .dbf file. ? Regards. ? David -------------- next part -------------- An HTML attachment was scrubbed... URL: From mynthon1 at gmail.com Tue Dec 23 08:27:45 2008 From: mynthon1 at gmail.com (mynthon) Date: Tue, 23 Dec 2008 05:27:45 -0800 (PST) Subject: wxPython.button.disabled still catching clicks References: <8cb6da6a-7df4-4cce-a28e-385448a25b26@w39g2000prb.googlegroups.com> <1ff2aad7-29a1-48cd-b3de-29fab443aa3e@u18g2000pro.googlegroups.com> Message-ID: <0e9a5ab7-8078-4d12-adb2-aaf92a78b007@s9g2000prm.googlegroups.com> On Dec 23, 11:58?am, Aaron Brady wrote: > On Dec 23, 4:50?am, mynthon wrote: > > > > > Hello! (sorry for my english) > > > I have a problem with buttons in wxPython. When button is disabled > > (by .Disable() or .Enable(False)) it is grayed out but still receive > > clicks. > > > Eg. i have button that disable itself, runs long action and enable > > itself: > > > def onClick(self, evt): > > ? ? self.btn.Enable(False) > > ? ? for i in range (1000): > > ? ? ? ? print i > > ? ? self.btn.Enable(True) > > > when for loop is running button is greyed out and when i click on it > > nothing happens but when loop ends another one is started because > > button "remebered" thad i click on it when was diabled. My only idea > > is to reposition button outside frame instead of disabling it but this > > solution is...not good. > > > thanks for any help. Ive searched groups, google and it looks that > > only i have this problem :) > > No, it is very common. ?During your for loop, the loop is dominating > the process completely. ?Events are just building up in the app's > message queue, and don't get handled until after you yield on control. > > If you need to run a long task, look into threading, the OnIdle > method, the 'multiprocessing' module, or pump messages during your > long task. ok, maybe someone will need it. I dont know how it works because i didnt have time to read docs and i cannot explain everything. I used google and wxPython demo (in tree: wxpython overview / process and events / process) class leftPanel(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id, style=wx.BORDER_SUNKEN) # here you have to define new process, IDLE event, and onPRocessEnd event self.process = None self.GetParent().Bind(wx.EVT_IDLE, self.onIdle) self.Bind(wx.EVT_END_PROCESS, self.onProcessEnd) # create button and bind event to it self.runScriptBtn = wx.Button(self, -1, 'RUN ME!', (10,220)) self.runScriptBtn.Bind(wx.EVT_BUTTON, self.onClick, self.runScriptBtn) def onClick(self, evt): # disable button self.runScriptBtn.Enable(False) # here you have to enter command to run # previusly i heve here exec('python myScript.py') # but now it will be a subprocess cmd = 'python xxx1.py' #create new process self.process = wx.Process(self) # dont know what it is for self.process.Redirect() # execute cmd command pid = wx.Execute(cmd, wx.EXEC_ASYNC, self.process) def onIdle(self, evt): # beacuse this method is called only when app enters idle mode # the line below is nedded to "simulate" entering idle mode # dont know how it works but it works evt.RequestMore(True) # here is some code to catch subprocess output if self.process is not None: stream = self.process.GetInputStream() if stream.CanRead(): text = stream.read() print text def onProcessEnd(self, evt): # here is some code to catch subprocess output # when it is destroyed stream = self.process.GetInputStream() if stream.CanRead(): text = stream.read() print text # dont know it is necessary self.process.CloseOutput() # remove (clear) process object self.process.Destroy() self.process = None # show button again self.runScriptBtn.Enable() From fetchinson at googlemail.com Tue Dec 9 11:14:09 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Tue, 9 Dec 2008 08:14:09 -0800 Subject: html codes In-Reply-To: References: Message-ID: >> I came across a javascript library that returns all sorts of html >> codes in the cookies it sets and I need my web framework (written in >> python :)) to decode them. I'm aware of htmlentitydefs but >> htmlentitydefs.entitydefs.keys( ) are of the form '&#xxx' but this >> javascript library uses stuff like '%3A' for the ':' for example. The >> conversion is here: >> >> http://www.ascii.cl/htmlcodes.htm >> >> Is there a python package/module/whatever that does the conversion for >> me or do I have to write a little wrapper myself (and introduce bugs >> while doing so :))? > >>>> import urllib >>>> urllib.quote("L?blich ?hnlich ?blich") > 'L%C3%B6blich%20%C3%A4hnlich%20%C3%BCblich' >>>> urllib.unquote(_) > 'L\xc3\xb6blich \xc3\xa4hnlich \xc3\xbcblich' >>>> print _ > L?blich ?hnlich ?blich > > If you care about the encoding you have to encode/decode explicitly: > >>>> urllib.quote(u"L?blich ?hnlich ?blich".encode("latin1")) > 'L%F6blich%20%E4hnlich%20%FCblich' >>>> urllib.unquote(_).decode("latin1") > u'L\xf6blich \xe4hnlich \xfcblich' Thanks a lot guys! Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From jpablo.romero at gmail.com Wed Dec 10 22:07:30 2008 From: jpablo.romero at gmail.com (=?ISO-8859-1?Q?Juan_Pablo_Romero_M=E9ndez?=) Date: Wed, 10 Dec 2008 21:07:30 -0600 Subject: Compiling and installing python 2.5.2 with Visual C++ 2008 In-Reply-To: <493f5d6c$0$9126$9b622d9e@news.freenet.de> References: <493f5d6c$0$9126$9b622d9e@news.freenet.de> Message-ID: Finally installed Python 2.6, which is compiled with visual C++ 2008, and all my problems went away. Thanks to all, Juan Pablo 2008/12/10 "Martin v. L?wis" : >> --------------------------------------------------------- >> ... >> error: Python was built with Visual Studio 2003; >> extensions must be built with a compiler than can generate compatible binaries. >> Visual Studio 2003 was not found on this system. If you have Cygwin installed, >> you can try compiling with MingW32, by passing "-c mingw32" to setup.py. >> --------------------------------------------------------- >> >> And because I've been compiling everything needed by pivy (Coin, Qt, >> SoQt, PyQt) with visual c++ 8, I decided to recompile python itself. > > There isn't a real installation procedure. You just copy the files by > hand into the places where they belong. In the specific case, > overwriting all .exe, .dll, and .pyd files in an installed directory > should be sufficient. > > Regards, > Martin > -- > http://mail.python.org/mailman/listinfo/python-list > From paul at boddie.org.uk Mon Dec 8 14:21:55 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 8 Dec 2008 11:21:55 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> Message-ID: <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> On Dec 4, 5:39 pm, "Chris Mellon" wrote: > > Honestly, based on the content and tenor of this post I think this is > Yet Another Python Troll So original: disagreeable criticism is "trolling". A few points... Short keywords are more likely to collide with short variable and attribute names, and while we should all use descriptive names for things, the complainant does seem to have found a reasonable application of a short name; when new short keywords are introduced, conflicts with such applications are inevitable, and that's exactly what has happened here. Anyone who has used any library or framework which combines another domain or technology with Python has probably seen names with trailing underscores; I believe PyQt employs exec_ instead of exec in various places, for example. Choosing some other name which needs no underscore can work against the beginner if they are referring to generic documentation. My message on python-dev about parsers and keywords noted that some languages manage to achieve what the complainant wants, more or less. SQL implementations, for example, can often deal with keywords if they are qualified, and it is even possible to double-quote keywords and use them as identifiers: create table "create" ( "select" varchar ); select "select" from "create"; select "create".select from "create"; (This from a PostgreSQL 8.2 session.) [...] > If you suppressed or ignored the deprecation warning that > all your code has been generating for at least 2 years it's pretty > damn ballsy to come here and tell everyone how *Python* is doing > something wrong. Maybe the complainant realises that he has no say in this matter and that he has to raise it in this fashion as a last resort. I've only skimmed this thread, but if the complainant is still using 2.4 (like a number of people) he won't have seen such a warning (although maybe he admits seeing it somewhere amongst the pile of "how dare you criticise?!" messages), and now he sees that he's running out of road. What I can say is that it certainly does take balls to see matters from the other guy's perspective instead of calling someone names for pointing something out. Paul From antoine at vo.lu Sat Dec 6 03:56:12 2008 From: antoine at vo.lu (Antoine De Groote) Date: Sat, 06 Dec 2008 09:56:12 +0100 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: <48db9$493a3e2b$d9a2276f$10794@news.hispeed.ch> try this: >>> import this and look at the 15th line... I agree that for newcomers to Python, the class method definition might seem strange. I certainly had problems with it when starting with Python, coming from Java. But in the meantime it feels right. I don't know if it is because I'm used to the old way, but I find the proposed alternative way slightly less readable. Altough these are no technical considerations, I'm -1 on this. Daniel Fetchinson wrote: > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html > > The proposal is to allow this: > > class C: > def self.method( arg ): > self.value = arg > return self.value > > instead of this: > > class C: > def method( self, arg ): > self.value = arg > return self.value > > I.e. explicit self stays only the syntax is slightly different and may > seem attractive to some. As pointed out by Guido classmethods would > work similarly: > > class C: > @classmethod > def cls.method( arg ): > cls.val = arg > return cls.val > > The fact that Guido says, > > "Now, I'm not saying that I like this better than the status quo. But > I like it a lot better than [...] but it has the great advantage that > it is backward compatible, and can be evolved into a PEP with a > reference implementation without too much effort." > > shows that the proposal is viable. > > I'd like this new way of defining methods, what do you guys think? > Anyone ready for writing a PEP? > > Cheers, > Daniel > From mh at pixar.com Sun Dec 7 03:54:46 2008 From: mh at pixar.com (mh at pixar.com) Date: Sun, 07 Dec 2008 08:54:46 GMT Subject: var or inout parm? Message-ID: How can I make a "var" parm, where the called function can modify the value of the parameter in the caller? def f(x): x = x + 1 n = 1 f(n) # n should now be 2 Many TIA!! Mark -- Mark Harrison Pixar Animation Studios From geekmail at usenot.de Fri Dec 5 10:31:07 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Fri, 5 Dec 2008 16:31:07 +0100 Subject: To Troll or Not To Troll (aka: "as" keyword woes) References: Message-ID: <20081205163107.1815df40@usenot.de> On Thu, 4 Dec 2008 16:17:20 -0800 "Warren DeLano" wrote: > Thank so much for the suggestions Ben. Sorry that I am personally > unable to live up to your high standards, but it is nevertheless an > honor to partipicate in such a helpful and mutually respectful > community mailing list! > You seem mildly irritated. Please don't be. Clearly you are not "personally unable" to "live up to" anybody's standards. His advice was a good one because there is a merrit to standards compliance. Just because you didn't know the standards (or rather "best practices") doesn't mean you're in any way deficient. Is it me, or has c.l.p. developed a slightly harsher tone recently? (Haven't been following for a while.) regards /W -- My real email address is constructed by swapping the domain with the recipient (local part). From steve at REMOVE-THIS-cybersource.com.au Thu Dec 4 10:02:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Dec 2008 15:02:12 GMT Subject: Pythonic design patterns References: Message-ID: <0147e8b9$0$20670$c3e8da3@news.astraweb.com> On Thu, 04 Dec 2008 01:09:08 -0800, Slaunger wrote: > I find myself spending a lot of time in Python making some designs, to > solve some task, which is the end turn out to be closely related to well > established design patterns / programming idioms, which other users in > this forum has been kind enough to point out. Only my implementations > are often not that clean, and I may call things something different than > the normal convention, which is a source of confusion for myself and > others trying to communicate with me. > > I guess I could boost my productivity by learning these well-proven and > well-established design patterns by heart. This is all very good, but don't drink the design pattern Kool-Aid and start pushing design patterns everywhere. (Not everything needs to be a singleton. No, really.) I think the risk with design patterns is that in the hands of an over- enthusiastic new convert, they encourage over-engineering, excessive abstraction and Big Design Up Front thinking. Patterns are useful, there's no doubt about it, but patterns should for the most part be invisible. Functions are patterns, but because they were invented back when dinosaurs walked the earth, before the Gang Of Four, they're just called functions instead of AbstractReusableResultGeneratingValueFactory Pattern. *wink* http://c2.com/cgi/wiki?DesignPatternsConsideredHarmful I think one good sign of pattern over/mis-use is when people can't even agree on whether something is a pattern, and if so, which pattern it is: http://c2.com/cgi/wiki?FactoryMethod -- Steven From jstroud at mbi.ucla.edu Tue Dec 23 19:58:00 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 23 Dec 2008 16:58:00 -0800 Subject: On Whose Desktop In-Reply-To: References: Message-ID: Steve Holden wrote: > Thanks to Barry Warsaw the "On Your Desktop" blog now has a new entry: Note the thumb trackball. It's the shiznizzle. Give one two weeks of your patience and you'll seriously consider having it implanted in your thigh so you don't have to worry about missing it when you travel. From mrkafk at gmail.com Tue Dec 30 10:46:29 2008 From: mrkafk at gmail.com (mk) Date: Tue, 30 Dec 2008 16:46:29 +0100 Subject: thread, multiprocessing: communication overhead Message-ID: Hello everyone, This time I decided to test communication overhead in multithreaded / multiprocess communication. The results are rather disappointing, that is, communication overhead seems to be very high. In each of the following functions, I send 10,000 numbers to the function / 10 threads / 10 processes, which simply returns it in its respective way. Function: notfun Best: 0.00622 sec Average: 0.00633 sec (simple function) Function: threadsemfun Best: 0.64428 sec Average: 0.64791 sec (10 threads synchronizing using semaphore) Function: threadlockfun Best: 0.66288 sec Average: 0.66453 sec (10 threads synchronizing using locks) Function: procqueuefun Best: 1.16291 sec Average: 1.17217 sec (10 processes communicating with main process using queues) Function: procpoolfun Best: 1.18648 sec Average: 1.19577 sec (a pool of 10 processes) If I'm doing smth wrong in the code below (smth that would result in performance suffering), please point it out. Code: import threading import multiprocessing import time import timeit def time_fun(fun): t = timeit.Timer(stmt = fun, setup = "from __main__ import " + fun.__name__) results = t.repeat(repeat=10, number=1) best_result = min(results) avg = sum(results) / len(results) print "Function: %-15s Best: %5.5f sec Average: %5.5f sec" % (fun.__name__, best_result, avg) def notfun(): inputlist = range(0,10000) reslist = [] for x in range(len(inputlist)): reslist.append(inputlist.pop()) def threadsemfun(): def tcalc(sem, inputlist, reslist, tid, activitylist): while len(inputlist) > 0: sem.acquire() try: x = inputlist.pop() except IndexError: sem.release() return #activitylist[tid] += 1 reslist.append(x) sem.release() inputlist = range(0,10000) #print "before: ", sum(inputlist) reslist = [] tlist = [] activitylist = [ 0 for x in range(0,10) ] sem = threading.Semaphore() for t in range(0,10): tlist.append(threading.Thread(target=tcalc, args=(sem, inputlist, reslist, t, activitylist))) for t in tlist: t.start() for t in tlist: t.join() #print "after: ", sum(reslist) #print "thread action count:", activitylist def threadlockfun(): def tcalc(lock, inputlist, reslist, tid, activitylist): while True: lock.acquire() if len(inputlist) == 0: lock.release() return x = inputlist.pop() reslist.append(x) #activitylist[tid] += 1 lock.release() inputlist = range(0,10000) #print "before: ", sum(inputlist) reslist = [] tlist = [] activitylist = [ 0 for x in range(0,10) ] sem = threading.Semaphore() for t in range(0,10): tlist.append(threading.Thread(target=tcalc, args=(sem, inputlist, reslist, t, activitylist))) for t in tlist: t.start() for t in tlist: t.join() #print "after: ", sum(reslist) #print "thread action count:", activitylist def pf(x): return x def procpoolfun(): pool = multiprocessing.Pool(processes=10) inputlist = range(0,10000) reslist = [] i, j, jmax = 0, 10, len(inputlist) #print "before: ", sum(inputlist) while j <= jmax: res = pool.map_async(pf, inputlist[i:j]) reslist.extend(res.get()) i += 10 j += 10 #print "after: ", sum(reslist) def procqueuefun(): def pqf(qin, qout): pid = multiprocessing.current_process().pid while True: x = qin.get() if x == 'STOP': return qout.put((pid, x)) qin = multiprocessing.Queue() qout = multiprocessing.Queue() plist = [] activity = dict() for i in range(0,10): p = multiprocessing.Process(target = pqf, args=(qin, qout)) p.start() plist.append(p) activity[p.pid] = 0 inputlist = range(0,10000) reslist = [] #print "before:", sum(inputlist) ilen = len(inputlist) x = 0 while x != ilen: for i in range(0,10): qin.put(inputlist[x+i]) for i in range(0,10): pid, res = qout.get() #activity[pid] = activity[pid] + 1 reslist.append(res) x += 10 for i in range(0,10): qin.put('STOP') for i in range(len(plist)): plist[i].join() #print "after:", sum(reslist) #print "activity", activity if __name__ == "__main__": time_fun(notfun) time_fun(threadsemfun) time_fun(threadlockfun) time_fun(procqueuefun) time_fun(procpoolfun) From steve at REMOVE-THIS-cybersource.com.au Sat Dec 6 00:36:32 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Dec 2008 05:36:32 GMT Subject: Guido's new method definition idea References: Message-ID: <014a071a$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 20:35:07 -0800, James Stroud wrote: > Daniel Fetchinson wrote: >> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to- stay.html >> >> The proposal is to allow this: >> >> class C: >> def self.method( arg ): >> self.value = arg >> return self.value >> >> instead of this: >> >> class C: >> def method( self, arg ): >> self.value = arg >> return self.value > >> I'd like this new way of defining methods, what do you guys think? > > Consider the maverick who insists on > > class C: > def me.method(arg): > self.value = arg Replace "self" with "me". > which should be equivalent to > > class C: > def method(me, arg): > me.value = arg > > What's the interpreter going to do with our maverick's code? I don't see why you think this is a problem. The compiler merely treats: def ANYTHING.method(arg): inside a class as if it were def method(ANYTHING, arg): and it will Just Work. If you want a classmethod, you still need to use the classmethod decorator -- there's no reason to make self and cls keywords. Personally, I'm neutral on the idea. Perhaps +0.00001. -- Steven From googler.1.webmaster at spamgourmet.com Fri Dec 5 04:44:13 2008 From: googler.1.webmaster at spamgourmet.com (googler.1.webmaster at spamgourmet.com) Date: Fri, 5 Dec 2008 01:44:13 -0800 (PST) Subject: Python C API References: <54fbb55d-3c39-459d-86a3-302b69721f0f@s20g2000yqh.googlegroups.com> <4938ed67$0$30227$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <3d1b6644-c943-412d-8860-6779a981fa44@20g2000yqt.googlegroups.com> Hi! thats a very interesting point and good to know. I have to release the GIL but how do I do? In this case i need PyEval_AcquireLock and PyEval_ReleaseLock? Thanks. From timr at probo.com Thu Dec 18 02:17:44 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 18 Dec 2008 07:17:44 GMT Subject: sys.maxint in Python 2.6.1 (amd64) on Windows XP x64 References: <4bddf65a-bb9f-406c-a544-8c38b27547a7@b38g2000prf.googlegroups.com> <7a629cb1-0fbc-41d4-ac51-d0be68df1df5@r36g2000prf.googlegroups.com> Message-ID: Lin wrote: > >Ah, this makes sense. Thanks...... The main reason I'm trying 64-bit >Python is that I want to write files bigger than 4GB. This should work >on Windows x64, right? (i.e., are the pointers bona fide 64 bit?) Those two questions are not related. Win32 (NTFS) has always been able to create files larger than 4GB, and the file APIs that deal with file positions and file sizes can all handle 64-bit values. Pointers on Win32 are 32 bits, but that doesn't affect files. If you want to map that large file into memory, you have to do it a gigabyte at a time, but if you're using ReadFile and WriteFile, it's not a problem. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From steve at REMOVE-THIS-cybersource.com.au Mon Dec 29 20:40:36 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Dec 2008 01:40:36 GMT Subject: Of console I/O, characters, strings & dogs References: Message-ID: <0169731c$0$6988$c3e8da3@news.astraweb.com> On Mon, 29 Dec 2008 18:53:45 -0600, David Lemper wrote: > I am trying getch() from msvcrt. The following module has been run with > 3 different concatination statements and none yield a satisfactory > result. Python 3.0 Your first problem is that you've run into the future of computing: strings are not bytes. For many decades, programmers have been pretending that they are, and you can get away with it so long as you ignore the 95% of the world that doesn't use English as their only language. Unfortunately, the time for this is passed. Fortunately, it's (mostly) not difficult to use Unicode, and Python makes it easy for you. > # script12 > import msvcrt > shortstr1 = 'd' + 'o' + 'g' > print(shortstr1) In Python 3, shortstr1 is a Unicode string. Python 3 uses Unicode as it's string type. Because Python is doing all the hard work behind the scenes, you don't have to worry about it, and you can just print shortstr1 and everything will Just Work. > char1 = msvcrt.getch() > char2 = msvcrt.getch() > char3 = msvcrt.getch() I don't have msvcrt here but my guess it that getch is returning a *byte* rather than a *character*. In the Bad Old Days, all characters were bytes, and programmers pretended that they were identical. (This means you could only have 256 of them, and not everyone agreed what those 256 of them were.) But in Unicode, characters are characters, and there are thousands of them. MANY thousands. *Way* too many to store in a single byte. > < alternatives for line 8 below > > print(shortstr2) > > print(shortstr1) gives dog of course. If the same > char are entered individually at the console, as char1, > 2 & 3, using msvcrt.getch(), I have not been able to get > out a plain dog. > > If line 8 is shortstr2 = char1[0] + char2[0] + char3[0] > print(shortstr2) yields 314 >>> ord('d') + ord('o') + ord('g') 314 The ordinal value of a byte is its numeric value, as a byte. > If line 8 is shortstr2 = 'char1[0]' + 'char2[0]' + 'char3[0]' > print(shortstr2) yields char1[0]char2[0]char3[0] Of course it does. You're setting shortstr2 equal to the literal strings 'char1[0]' etc. But nice try: you want to convert each not-really-a-char to a (Unicode) string. You don't do that with the '' delimiters, as that makes a literal string, but with the str() function. Either of these should work: shortstr2 = str(char1) + str(char2) + str(char3) shortstr2 = str(char1 + char2 + char3) While they will work for (probably) any character you can type with your keyboard, they will probably fail to give sensible results as soon as you try using characters like ? ? ? ? ? The right way to convert bytes to characters is to decode them, and to decode them, you have to know what encoding system is used. If the characters are plain-old English letters typed on an American keyboard, you can do this: bytes = char1 + char2 + char3 shortstr2 = bytes.decode('ascii') but this can give unexpected results if bytes contains non-ASCII values. Better is to go the whole-hog and use the UTF-8 encoding, unless you specifically know to use something else: shortstr2 = bytes.decode('utf-8') > If line 8 is shortstr2 = char1 + char2 + char3 > print(shortstr2) yields b 'dog' > > Is the latter out of "How to Speak Redneck" ? > > Possibly b means bit string. Nice guess, close but not quite. It actually means byte string. You probably should read this: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky http://www.joelonsoftware.com/articles/Unicode.html Good luck! -- Steven From james at agentultra.com Thu Dec 11 11:53:32 2008 From: james at agentultra.com (J Kenneth King) Date: Thu, 11 Dec 2008 11:53:32 -0500 Subject: pydb 1.24 References: Message-ID: <85vdtqejqr.fsf@dozer.localdomain> rocky at panix.com (R. Bernstein) writes: > This release is to clear out some old issues. It contains some > bugfixes, document corrections, and enhancements. Tests were > revised for Python 2.6 and Python without readline installed. A bug > involving invoking from ipython was fixed. The "frame" command is a > little more like gdb's. Exceptions are now caught in runcall(). > > This is the last release contemplated before a major rewrite. > > download: > https://sourceforge.net/project/showfiles.php?group_id=61395&package_id=175827 > > bug reports: > https://sourceforge.net/tracker/?group_id=61395&atid=497159 I watched the demo video, look forward to working with it. Any links to that emacs front-end being used in the video? Cheers and thanks! From walterbyrd at iname.com Mon Dec 22 09:58:06 2008 From: walterbyrd at iname.com (walterbyrd) Date: Mon, 22 Dec 2008 06:58:06 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> Message-ID: <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> On Dec 21, 12:28?pm, Bruno Desthuilliers wrote: > Strange enough, > no one seems to complain about PHP or Ruby's performances... A few years back, there was a certain amount of chest thumping, when python/django easily beat ror in a benchmark test. Now that ruby is faster, I guess speed is no big issue. By the same reasoning, python advocates used to sneer at php because php constantly broke backward compatibility. Now that python does it, breaking backward compatibility is no big deal. I guess unicode support was not that important, until python caught up to perl. I guess, the way it works is: you first assume that python is superior, then you figure out why. From stef.mientki at gmail.com Mon Dec 1 15:19:40 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 01 Dec 2008 21:19:40 +0100 Subject: Emacs vs. Eclipse vs. Vim In-Reply-To: <49335D41.5090505@internode.on.net> References: <1228094836.4406.6.camel@generator> <49335D41.5090505@internode.on.net> Message-ID: <493446DC.7030908@gmail.com> Peter Anderson wrote: > What I have done is skipped the whole Vim/Emacs obscure editor thing > and opted for PyScripter (see > http://mmm-experts.com/Products.aspx?ProductID=4 ). It might not be as > complete/complex as these other editors but it is easy to use and just > lets me get on with the task of cutting code. if it works it's a fair good editor, but if it doesn't (I have to restart the editor about each hour) ... > > As a fall-back I also use EditPlus (see > http://www.editplus.com/index.html ). Its only for Windows but PyScripter is also only for windows ;-) > and its shareware so you need to pay for it. Its clip library makes it > a VERY GOOD text editor. It's a real shame there are NO text editors > with such a comprehensive and easy to modify clip library function (I > would be really pleased to be proven wrong on this last point :-) ). What so great about it ? I use a template manager, written in pure python, works under any OS (where Python is installed) and can be used with any text editor and is open source and completely free. I think it has at least the same capabilities as the Komodo clip library. Somewhere in the middle of the following page are a few notes: http://mientki.ruhosting.nl/data_www/pylab_works/pw_code_editor.html and you can find the sources here: http://code.google.com/p/pylab-works/downloads/list > > However, the best advice I think that can be given about editors is > keep trying them until you find the one YOU like. We all like > different things, especially when it comes to editors. > +1 cheers, Stef From Afro.Systems at gmail.com Mon Dec 29 07:08:54 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Mon, 29 Dec 2008 04:08:54 -0800 (PST) Subject: AttributeError: 'module' object has no attribute 'DatagramHandler' (ubuntu-8.10, python 2.5.2) Message-ID: <4c6f0831-c05f-401f-b956-376600b38e06@r15g2000prd.googlegroups.com> $ ~/devel/ice/snoip/freespeech$ python Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import logging >>> logging.DatagramHandler Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'DatagramHandler' >>> That is odd since the documentation says there is DatagramHandler for module logging From david at hlacik.eu Sat Dec 13 13:23:50 2008 From: david at hlacik.eu (=?ISO-8859-2?Q?David_Hl=E1=E8ik?=) Date: Sat, 13 Dec 2008 19:23:50 +0100 Subject: [OT] stable algorithm with complexity O(n) Message-ID: Hi guys, i am really sorry for making offtopic, hope you will not kill me, but this is for me life important problem which needs to be solved within next 12 hours.. I have to create stable algorithm for sorting n numbers from interval [1,n^2] with time complexity O(n) . Can someone please give me a hint. Would be very very thankful! Thanks in advance! D. From raj.indian.08 at gmail.com Mon Dec 1 09:32:58 2008 From: raj.indian.08 at gmail.com (RajNewbie) Date: Mon, 1 Dec 2008 06:32:58 -0800 (PST) Subject: 11001, 'getaddrinfo failed' : Error in httplib but not in urllib2 Message-ID: Hi all, I am trying to connect to localhost via httplib, but it fails. To check whether it is a firewall problem etc, I tried to connect via urllib2, but it went through fine. Could some one help me out on this? I cannot use urllib2 in the program because I have to send files via post to a url, and urllib2 doesn't support it (Python2.4) Please see the code below: -->HTTPLIB<-- h = httplib.HTTPConnection("http://127.0.0.1:8000") h.request('GET', "/accounts/") res = h.getresponse() -->URLLIB2<-- req = urllib2.Request("http://127.0.0.1:8000/accounts/") fd = urllib2.urlopen(req) Regards Raj From cjw at ncf.ca Mon Dec 29 10:07:00 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Mon, 29 Dec 2008 10:07:00 -0500 Subject: multiply each element of a list by a number In-Reply-To: References: <4955e7be$0$4066$ba4acef3@news.orange.fr> <49580B2E.8050009@ncf.ca> Message-ID: <4958E794.1070704@ncf.ca> skip at pobox.com wrote: >>>>>> "Colin" == Colin J Williams writes: > > Colin> skip at pobox.com wrote: > > >> For extremely short lists, but not for much else: > >> > >> % for n in 1 10 100 1000 10000 100000 ; do > >> > echo "len:" $n > >> > echo -n "numpy: " > >> > python -m timeit -s 'import numpy ; a = numpy.array(range('$n'))' 'a*3' > >> > echo -n "list: " > >> > python -m timeit -s 'a = range('$n')' '[3*x for x in a]' > >> > done > >> len: 1 > >> numpy: 100000 loops, best of 3: 11.7 usec per loop > >> list: 1000000 loops, best of 3: 0.698 usec per loop > >> len: 10 > >> numpy: 100000 loops, best of 3: 11.7 usec per loop > >> list: 100000 loops, best of 3: 2.94 usec per loop > >> len: 100 > >> numpy: 100000 loops, best of 3: 12.1 usec per loop > >> list: 10000 loops, best of 3: 24.4 usec per loop > >> len: 1000 > >> numpy: 100000 loops, best of 3: 15 usec per loop > >> list: 1000 loops, best of 3: 224 usec per loop > >> len: 10000 > >> numpy: 10000 loops, best of 3: 41 usec per loop > >> list: 100 loops, best of 3: 2.17 msec per loop > >> len: 100000 > >> numpy: 1000 loops, best of 3: 301 usec per loop > >> list: 10 loops, best of 3: 22.2 msec per loop > >> > >> This is with Python 2.4.5 on Solaris 10. YMMV. > > Colin> Your comment is justified for len= 100 > Colin> or 1,000 but not for len= 10,000 or 100,000. > > Look again at the time units per loop. > > Colin> I wonder about the variability of the number of loops in your > Colin> data. > > That's how timeit works. It runs a few iterations to see how many to run to > get a reasonable runtime. That's interesting but that's not the way timeit is documented for Python 2.5: timeit( [number=1000000]) Time number executions of the main statement. This executes the setup statement once, and then returns the time it takes to execute the main statement a number of times, measured in seconds as a float. The argument is the number of times through the loop, defaulting to one million. The main statement, the setup statement and the timer function to be used are passed to the constructor. > > Colin> I have tried to repeat your test with the program below, but it > Colin> fails to cope with numpy. > > I stand by my assertion that numpy will be much faster than pure Python for > all but very short lists. > In spite of the fact that your own data doesn't support the assertion? I would have expected numpy to be the clear winner for len > 1,500. Perhaps your data questions the value of timeit as a timing tool. Colin W. From bgailer at gmail.com Mon Dec 15 08:31:30 2008 From: bgailer at gmail.com (bob gailer) Date: Mon, 15 Dec 2008 08:31:30 -0500 Subject: [Tutor] Having Issues with CMD and the 'python' command In-Reply-To: References: Message-ID: <49465C32.7020200@gmail.com> An HTML attachment was scrubbed... URL: From shaomumu at gmail.com Tue Dec 16 14:22:53 2008 From: shaomumu at gmail.com (Lin) Date: Tue, 16 Dec 2008 11:22:53 -0800 (PST) Subject: sys.maxint in Python 2.6.1 (amd64) on Windows XP x64 References: <4bddf65a-bb9f-406c-a544-8c38b27547a7@b38g2000prf.googlegroups.com> Message-ID: <7a629cb1-0fbc-41d4-ac51-d0be68df1df5@r36g2000prf.googlegroups.com> > > > I installed the amd64 version of Python 2.6.1 on my Windows XP x64 > > system. I was expecting sys.maxint to be 9223372036854775807 (or 2 ^63 > > -1), but instead I got 2147483647 (i.e., 2^31-1) just like what I got > > from a 32-bit version of Python. Is this by design or does it indicate > > a bug or an installation problem? Thank you very much! > > This is by design. In their infinitive wisdom Microsoft has decided to > make the 'long' C type always a 32 bit signed integer - even on 64bit > systems. On most Unix systems a long is at least 32 bit but usually > sizeof(ptr). > Ah, this makes sense. Thanks...... The main reason I'm trying 64-bit Python is that I want to write files bigger than 4GB. This should work on Windows x64, right? (i.e., are the pointers bona fide 64 bit?) -lin From ianare at gmail.com Tue Dec 16 15:59:46 2008 From: ianare at gmail.com (=?ISO-8859-1?B?aWFuYXLp?=) Date: Tue, 16 Dec 2008 12:59:46 -0800 (PST) Subject: sorting for recursive folder rename References: Message-ID: <56d7c5b3-314d-43bd-a292-197fbbd4853c@v5g2000prm.googlegroups.com> On Dec 16, 2:00?pm, MRAB wrote: > ianar? wrote: > > Hello all, > > > I trying to recursively rename folders and files, and am looking for > > some ideas on the best way of doing this. The problem is that the > > given list of items can be in order, and one to all items may be > > renamed. Here is some preliminary code I have, but which does not work > > very well. > > > self.toRename has the following structure : > > [ > > [original_name, new_name, os.path.isdir] > > .. > > ] > > > # define these here for faster processing > > def split(item): > > ? ? return os.path.split(item) > > def addSep(path): > > ? ? return os.sep + path + os.sep > > def recursiveFolderSort(x,y): > > ? ? return cmp(y[0], x[0]) > > > sortedRename = sorted(self.toRename) > > > # make a list of all folders that will be processed > > foldersToAdjust = [] > > for item in sortedRename: > > ? ? if item[2] is False: > > ? ? ? if not item[2]:> ? ? ? ? oF = split(item[0])[1] # original folder name > > ? ? ? ? nF = split(item[1])[1] # new folder name > > ? ? ? ? if oF is not nF: > > ? ? ? ? ? if oF != nF:> ? ? ? ? ? ? foldersToAdjust.append((oF, nF)) > > > # replace all occurences of folders in path > > for i in range(len(self.toRename)): > > ? ? for f in foldersToAdjust: > > ? ? ? ? oF = addSep(f[0]) # original folder name > > ? ? ? ? nF = addSep(f[1]) # new folder name > > ? ? ? ? self.toRename[i][0] = self.toRename[i][0].replace(oF,nF) > > ? ? ? ? self.toRename[i][1] = self.toRename[i][1].replace(oF,nF) > > > ? ? if progressDialog.update(i) is False: > > ? ? ? if not progressDialog.update(i):> ? ? ? ? error = 'cancelled' > > ? ? ? ? break > > > # make sure renaming will be in correct order ! > > self.toRename.sort(recursiveFolderSort) > > > First problem is adjusting the paths can take a very long time. > > Second problem is sorting is not always right and files get lost !! > > Any input welcome. > > You should use "is" and "is not" _only_ when checking for _identity, ie > are these 2 both references to the _same_ object. Most of the time that > would be "x is None" or "x is not None". Thanks, this has been corrected. From raj.indian.08 at gmail.com Sun Dec 21 13:51:07 2008 From: raj.indian.08 at gmail.com (RajNewbie) Date: Sun, 21 Dec 2008 10:51:07 -0800 (PST) Subject: Are python objects thread-safe? Message-ID: Say, I have two threads, updating the same dictionary object - but for different parameters: Please find an example below: a = {file1Data : '', file2Data : ''} Now, I send it to two different threads, both of which are looping infinitely: In thread1: a['file1Data'] = open(filename1).read and in thread2: a['file2Data'] = open(filename2).read My question is - is this object threadsafe? - since we are working on two different parameters in the object. Or should I have to block the whole object? From martin at v.loewis.de Sat Dec 13 17:27:33 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 13 Dec 2008 23:27:33 +0100 Subject: [ANN] Python 2.4.6 and 2.5.3, release candidate 1 Message-ID: <494436D5.6050103@v.loewis.de> On behalf of the Python development team and the Python community, I'm happy to announce the release candidates of Python 2.4.6 and 2.5.3. 2.5.3 is the last bug fix release of Python 2.5. Future 2.5.x releases will only include security fixes. According to the release notes, over 100 bugs and patches have been addressed since Python 2.5.1, many of them improving the stability of the interpreter, and improving its portability. 2.4.6 includes only a small number of security fixes. Python 2.6 is the latest version of Python, we're making this release for people who are still running Python 2.4. See the release notes at the website (also available as Misc/NEWS in the source distribution) for details of bugs fixed; most of them prevent interpreter crashes (and now cause proper Python exceptions in cases where the interpreter may have crashed before). Assuming no major problems crop up, a final release of Python 2.4.6 and 2.5.3 will follow in about a week's time. For more information on Python 2.4.6 and 2.5.3, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.4.6 http://www.python.org/2.5.3 Highlights of the previous major Python releases are available from the Python 2.5 page, at http://www.python.org/2.4/highlights.html http://www.python.org/2.5/highlights.html Enjoy this release, Martin Martin v. Loewis martin at v.loewis.de Python Release Manager (on behalf of the entire python-dev team) From steve at REMOVE-THIS-cybersource.com.au Sun Dec 28 01:58:18 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Dec 2008 06:58:18 GMT Subject: math module for Decimals References: Message-ID: <01671a9e$0$6988$c3e8da3@news.astraweb.com> On Sat, 27 Dec 2008 16:02:51 -0800, jerry.carl.mi wrote: > Hi, > > I have been looking for a Python module with math functions that would > both eat and spit Decimals. The standard math module eats Decimals > allright but spits floats... herefore exp(sin(Decimal())) produces exp > () of a float :-( You can write your own wrappers. Assuming you always want to return decimals instead of floats: from decimal import Decimal import math def exp(x): if isinstance(x, Decimal): return x.exp() f = math.exp(x) return make_decimal(f) def sin(x): f = math.sin(x) return make_decimal(f) You can get fancier if you like: def cos(x): try: return x.cos() except AttributeError: f = math.cos(x) return make_decimal(f) That version will automatically use Decimal.cos() in the future, assuming Decimals grow a cos() method. If they don't, it will continue to work (although a tad slower than the sin() above. Converting floats to decimals is tricky, because you have to decide how much precision you care about. You can keep all the precision of floats. Depending on your needs, this is either a feature or a gotcha: >>> (1.0/3).as_integer_ratio() # expecting (1, 3) (6004799503160661L, 18014398509481984L) Anyway, here are at least three ways to write make_decimal: # Python 2.6 only def make_decimal(f): # exact, no loss of precision # however, will fail for f = NAN or INF a, b = f.as_integer_ratio() return Decimal(a)/Decimal(b) def make_decimal(f): return Decimal("%r" % f) def make_decimal(f, precision=16): # choose how many decimal places you want to keep return Decimal.from_float(f, precision) You choose which suits you best. > So far, i found: > > -AJDecimalMathAdditions (http://www.ajgs.com/programming/ > PythonForDownload.html) > -decimalfuncs (http://pypi.python.org/pypi/decimalfuncs/1.4) -and dmath > (http://pypi.python.org/pypi/dmath/0.9) > > I tried using the AJDecimalMathAdditions, but ran into issues like dSin > (1E4) would take forever to calculate and would result in sin() > 1 ... > If i understand it correctly, the program is using maclaurin series to > calculate the value and since it does not chop off all the multiples of > 2*pi, the maclaurin approximation becomes useless when its too far from > x=0. You might try something like this: pi = Decimal("%r" % math.pi) twopi = 2*pi pi2 = pi/2 def sin(x): # *** UNTESTED *** if x < 0: return -sin(-x) elif x > twopi: x = remainder(x, twopi) return sin(x) elif x > pi: return -sin(x - pi) elif x > pi2: return sin(pi - x) else: return AJDecimalMathAdditions.dSin(x) You can treat cos and tan similarly but not identically. However, you might find that it quicker and simpler to just do your maths calculations as floats, then convert to decimals, as in my earlier examples. > I also ran into some issues with the decimalfuncs, but i have never > tried the dmath thing. > > Now, i can go and start modifying these modules to behave more like the > standard math module but since i am neither mathematician or programer, > i really hesitate. And so you should. Getting numerical functions correct is damn hard. However, if all you need is "close enough", then don't be scared -- the sort of tricks I've shown are probably "close enough", although you may want a disclaimer about not using them for running nuclear reactors or flying aircraft. The basic tools Python supplies are pretty good, and you can probably get a 95% solution with them without being an expert in computational mathematics. > So my questions are: > > (1) what do folks use when they need to calculate something like exp > (sin(Decimal())) or even more complex things? Any recommendations? Or am > I completely missing something? > > (2) Is there any plan to provide a standard python module that would do > that? (Python 4.0? ;-) Guido is very reluctant to put numeric libraries in the standard library, precisely because it is so hard to get it right. Don't expect Python to become Mathematica any time soon! -- Steven From digitig at gmail.com Sun Dec 7 16:48:46 2008 From: digitig at gmail.com (Tim Rowe) Date: Sun, 7 Dec 2008 21:48:46 +0000 Subject: Is 3.0 worth breaking backward compatibility? In-Reply-To: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> Message-ID: 2008/12/7 walterbyrd : > IMO: breaking backward compatibility is a big deal, and should only be > done when it is seriously needed. > > Also, IMO, most of, if not all, of the changes being made in 3.0 are > debatable, at best. I can not think of anything that is being changed > that was really a "show stopper" anyway. But that's what a major release number does for you. Modula2 was quite a break from Modula. Think of Python3.0 it as a new language, if you like, that's inspired by Python2. You can stay with Python2 or you can adopt the new language. That way you won't have to think of it in terms of breaking any sort of backwards compatibility because there is no backwards ;-) -- Tim Rowe From deets at nospam.web.de Tue Dec 30 08:32:29 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 30 Dec 2008 14:32:29 +0100 Subject: How to debug embeding Python? In-Reply-To: References: Message-ID: <6rum7dF3elu4U1@mid.uni-berlin.de> Hongtian schrieb: > Hi Friends, > > My application is written in C/C++ and Python is embed to extend some > functions (several .py files are invoked). But I am confused how to > debug these embed Python? Can I use 'print-debuging'? and where can I > capture the output string? > > Or Python can support 'break' debug for such scenario? You should be able to use the python debugger (pdb) by manually putting import pdb; pdb.set_trace() on a place that is of interest to you. Then if your program is started inside a shell, you should be able to step-debug it. Additinoally, there is the very flexible & powerful logging-module that you can use to write logfiles. This is better than simple print-statements, as you can keep the logging statements around and just turn them on or off on demand. Additionally, printing might not work reliably in cases where the stdout/err-streams aren't visible or otherwise in use. But the logging-module can log to files (or even system event logs *me thinks*) Diez From acerimusdux at comcast.net Mon Dec 8 09:04:44 2008 From: acerimusdux at comcast.net (acerimusdux) Date: Mon, 08 Dec 2008 09:04:44 -0500 Subject: Beginner trying to understand functions. Message-ID: <493D297C.9040504@comcast.net> simonh write: > In my attempt to learn Python I'm writing a small (useless) program to > help me understand the various concepts. I'm going to add to this as I > learn to serve as a single place to see how something works, > hopefully. Here is the first approach: > > > > name = input('Please enter your name: ') > print('Hello', name) > > while True: > try: > age = int(input('Please enter your age: ')) > break > except ValueError: > print('That was not a valid number. Please try again.') > > permitted = list(range(18, 31)) > > if age in permitted: > print('Come on in!') > elif age < min(permitted): > print('Sorry, too young.') > elif age > max(permitted): > print('Sorry, too old.') > > input('Press any key to exit.') > > > > That works fine. Then I've tried to use functions instead. The first > two work fine, the third fails: > > > > def getName(): > name = input('Please enter your name: ') > print('Hello', name) > > def getAge(): > while True: > try: > age = int(input('Please enter your age: ')) > break > except ValueError: > print('That was not a valid number. Please try again.') > > def checkAge(): > permitted = list(range(18, 31)) > if age in permitted: > print('Come on in!') > elif age < min(permitted): > print('Sorry, too young.') > elif age > max(permitted): > print('Sorry, too old.') > > getName() > getAge() > checkAge() > > I get this error message: NameError: global name 'age' is not > defined. > > I'm stuck, can someone help? Thanks. > You are running into Python's scoping rules. Variables in Python are not global by default, they are local to their scope. Each function has it's own scope (but blocks like if: and while: don't.) So your variable "age" only exists in getage(). It doesn't exist in checkage(). You could simply add a "global age" statement to getAge() before you first use the age variable, and that will likely work. Or, rather than declare it global, you might want to have getage() return a value, and then pass it to checkage () as a function parameter. Add a "return age" statement to getage() before "break". Then, for your def: def checkage(age): And then when calling: A=getAge() checkAge(A) From deets at nospam.web.de Wed Dec 24 12:52:50 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 24 Dec 2008 18:52:50 +0100 Subject: Iterating over objects of a class In-Reply-To: <2df27de3-7fa3-4ac9-acd9-f946939517cf@r37g2000prr.googlegroups.com> References: <2df27de3-7fa3-4ac9-acd9-f946939517cf@r37g2000prr.googlegroups.com> Message-ID: <6rfb7iF1fg5rU1@mid.uni-berlin.de> Kottiyath schrieb: > Hi, > How can I iterate over all the objects of a class? > I wrote the code like following: > class baseClass(object): Consider adopting PEP 8 coding conventions. > __registry = [] > > def __init__(self, name): > self.__registry.append(self) > self.name = name > > def __iter__(self): > baseClass.item = 0 > return self.__registry[0] > > def next(self): > if baseClass.item >= len(self.__registry): > raise StopIteration > baseClass.item += 1 > return self.__registry[baseClass.item - 1] > > For testing, create the following objects- > a = baseClass("Test1") > b = baseClass("Test2") > > class subClass (baseClass): > pass > c = subClass("Test3") > > ---->Actual Iteration<---- > for i in a: > print i.name > > Test1 > Test2 > Test3 > > --------------------------------------------------- > I see the following problems in the code: > 1. I have to iterate over any of the objects. For correctness, I > wanted to iterate over the class, like > for i in baseClass(): > do x > but that will will create one more object - which I do not want. > > 2. If the subclass wants to do somethings in its constructor, I am not > sure how to update the registry. > class subClass (baseClass): > def __init__(self, name): > **do something** > super.init(self, name) ----> This errors out, saying it needs > super, not subClass You don't show the actual traceback, however the idiom for invoking super for new-style-classes is super(subClass, self).__init__(name) for your case. > Another method I thought of implementing it was using generators - > where-in baseClass.objects() is a generator which will yield the > objects one by one - but even then the second issue remains. > If somebody can help me out, I would be very thankful. Using a generator or not isn't the issue here. What you need is a *class*-based access, not instance-based. There are various methods to accomplish this. The simplest is to ditch the obnoxious __registry as name, and just do class BaseClass(object): REGISTRY = [] Then iterating is a simple matter of for instance in BaseClass.REGISTRY: ... Case solved. Alternatively, if you insist on the concept of privacy for that registry, you can use a classmethod: class BaseClass(object): @classmethod def registry(cls): for i in cls.__registry: yield i Last but not least you *could* go for a __metaclass__ with an __getitem__-method, that makes thinks look fancy because you then can do: for instance in BaseClass: ... I leave it as an exercise to you - gotta go christmas dining now :) Diez From castironpi at gmail.com Tue Dec 23 15:23:45 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 23 Dec 2008 12:23:45 -0800 (PST) Subject: Are python objects thread-safe? References: <5306b56c-eb8c-4148-b426-013caa871375@b41g2000pra.googlegroups.com> Message-ID: <867b3e71-f5f3-43e8-9232-2b683a516540@b41g2000pra.googlegroups.com> On Dec 23, 7:30?am, Duncan Booth wrote: > Aaron Brady wrote: > > Th.1 ? Th.2 > > a=X > > ? ? ? ?a=Y > > a=Z > > > You are saying that if 'a=Z' interrupts 'a=Y' at the wrong time, the > > destructor for 'X' or 'Y' might not get called. ?Correct? ?In serial > > flow, the destructor for X is called, then Y. > > No, the destructors will be called, but the destructors can do pretty much > anything they want so you can't say the assignment is atomic. This isn't > actually a threading issue: you don't need multiple threads to experience > werid issues here. If you do strange things in a destructor then you can > come up with confusing code even with a single thread. I see. What about del a a= Z Then, can we say 'a=Z' is atomic? At least, it eliminates the destructor issue you raise. > >> Other nasty things can happen if you use dictionaries from multiple > >> threads. You cannot add or remove a dictionary key while iterating over > >> a dictionary. This isn't normally a big issue, but as soon as you try to > >> share the dictionary between threads you'll have to be careful never to > >> iterate through it. > > > These aren't documented, IIRC. ?Did you just discover them by trial > > and error? > > It is documented, but I can't remember where for Python 2.x. For Python 3, > PEP 3106 says: "As in Python 2.x, mutating a dict while iterating over it > using an iterator has an undefined effect and will in most cases raise a > RuntimeError exception. (This is similar to the guarantees made by the Java > Collections Framework.)" I infer that d.items() holds the GIL during the entire operation, and it's safe to put in a thread. It is merely using an iterator that is unsafe. (Python 3.0 removed d.items(), leaving only the iterator, I understand.) I'm looking at the code, and I don't see where the size is safely checked. That is, can't I sneak in an add and a remove during iteration, so long as it doesn't catch me? I'm looking at 'dict_traverse': while (PyDict_Next(op, &i, &pk, &pv)) { Py_VISIT(pk); Py_VISIT(pv); } No locks are acquired here, though I might have missed acquiring the GIL somewhere else. In the OP's example, he wasn't changing the size of the dict. From Scott.Daniels at Acm.Org Fri Dec 19 19:05:42 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 19 Dec 2008 16:05:42 -0800 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: excord80 wrote: > On Dec 19, 11:01 am, walterbyrd wrote: >> To me, it seems that this: >> print "%s=%d" % ('this',99) >> Is much easier, ... >> This (if it's right) is much longer, ... >> print( "{0}={1}".format('this',99)) > Yeah, I like the old way better too. It's got this nice elegant > simplicity to it (using the percent sign for not only the things > inside the string, but also to separate it from the tuple that > follows). Also, I like having only *one* special symbol (`%') to worry > about in my strings instead of two (`{' and `}'). Ah, but for internationalization, you can change the format string to take args in a different order if, for example, French messages want modifiers on one side and English on the other. The code can stay the same, while only the text used to do the formatting must change. --Scott David Daniels Scott.Daniels at Acm.Org From tjreedy at udel.edu Wed Dec 3 02:07:53 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 03 Dec 2008 02:07:53 -0500 Subject: porting modules to Python 3.0 In-Reply-To: <4936255D.6000509@v.loewis.de> References: <8f60c779-f1ec-4127-b173-f174c016aa96@a12g2000yqm.googlegroups.com> <4936255D.6000509@v.loewis.de> Message-ID: Martin v. L?wis wrote: >> Is there something like that already in place? What are the >> recommendations for library >> authors willing to support both Python 2.X and 3.X in parallel? > > My recommendation is to use 3.0's build_py_2to3 implementation of > the build_py command. See Demo/distutils/test2to3. > > You will have a single lib.py, written in 2.x. When you install > in 3.0, lib2to3 will convert it to 3.x in the build area, and > then install the 3.0 version. > > That, of course, requires you to adjust lib.py in such a way that > 2to3 will successfully and completely convert it. In my experience > (with porting Django) and Mark Hammond's experience (with porting > PythonWin), this should be always possible. You look at what 2to3 > does, find out what additional modifications need to be done, and > apply them to the input of 2to3 so that > a) 2to3 leaves these changes in place > b) they either have no effect or still work correctly when run > in 2.x. > > Regards, > Martin > -- > http://mail.python.org/mailman/listinfo/python-list In one has both 2.x and 3.0 installed, would it easy to install 'lib.py' for both? From drobinow at gmail.com Sun Dec 14 19:54:47 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Sun, 14 Dec 2008 16:54:47 -0800 (PST) Subject: Looking for the best way to translate an idiom References: Message-ID: On Dec 14, 11:19?am, Paul Moore wrote: > I'm translating some code from another language (Lua) which has > multiple function return values. So, In Lua, it's possible to define a > function > > ? ? function f() > ? ? ? ? return 1,2,3 > ? ? end > > which returns 3 values. These can then be used/assigned by the caller: > > ? ? a,b,c = f() > > So far, much like Python, but the key difference is that in Lua, > excess arguments are ignored - so you can do > > ? ? a = f() > or even > ? ? a = f() + 1 > > where in the latter, a is 2 (as addition only needs 1 argument, so the > extra ones are discarded). > > This results in the code which I'm trying to translate having > functions which return multiple arguments, the first of which is the > "main" result, and the following values are "extra" results > (specifically, the position at which a match is found, followed by the > "captured" values of the match). > > I'm trying to find a natural equivalent in Python. So far, I've > considered the following: > > - return a tuple (pos, captures). This is messy, because you end up > far too often unpacking the tuple and throwing away the second value > - return an object with pos and captures attributes. This is better, > as you can do match(...).pos to get the position alone, but it doesn't > really feel "pythonic" (all those calls with .pos at the end...) > - have 2 calls, one to return just the position, one to return both. > This feels awkward, because of the 2 method names to remember. > > To make things worse, Lua indexes strings from 1, so it can use a > position of 0 to mean "no match" - so that a simple "did it match?" > test looks like if (match(....))... - where in Python I need if > (matchpos(...) != -1)... (Although if I return a match object, I can > override __nonzero__ to allow me to use the simpler Lua form). > > Can anyone suggest a good idiom for this situation? At the moment, I'm > returning a match object (the second option) which seems like the > least bad of the choices (and it mirrors how the re module works, > which is somewhat useful). But I'd like to know what others think. If > you were using a pattern matching library, what interface would you > prefer? > > I suspect my intuition isn't accurate here, as most of the use I've > made of the library is in writing tests, which isn't typical use :-( > > Thanks for any assistance. > > Paul I'm baffled by this discussion. What's wrong with a, dontcare, dontcare2 = f() a = a + 1 Simple, clear, and correct. From google at mrabarnett.plus.com Fri Dec 12 18:43:07 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 12 Dec 2008 23:43:07 +0000 Subject: os.lstat : proper way to do this In-Reply-To: References: Message-ID: <4942F70B.4030409@mrabarnett.plus.com> m1k3b0 at gmail.com wrote: > I'm converting from Perl to Python, so I'm learning the basics - > please be gentle! :) > > In Perl, I can lstat($file) whether $file exists or not: > lstat($file); > unless (-e _) { > print STDERR "$file: No such file or directory\n"; > } > unless (-l _) { > print STDERR "$file: Not a symbolic link\n"; > } > > The lstat() returns normally whether the file exists or not, and I > check for existence with the "-e" conditional. Then I go on and check > other modes. > > In Python,if I os.lstat(file) and file doesn't exist, I get an error > from within the module: > OSError: [Errno 2] No such file or directory: '/etc/xxx' > > I can check first with os.path.exists(file), but then I'm doing two > stat() type calls which is inefficient (especially when we're talking > thousands of files). > > I want to be able to do something like this: > mode = os.lstat(file)[ST_MODE] > if not mode: > print >> sys.stderr, file, ": No such file or directory" > if not S_ISLNK(mode): > print >> sys.stderr, file, ": Not a symbolic link" > > Of course, this isn't valid. How can I do this efficiently without > getting "no such file" error? > Just catch the exception: try: mode = os.lstat(file).st_mode # An alternative way. # If we get here then the file does exist. if not S_ISLNK(mode): print >> sys.stderr, file, ": Not a symbolic link" except OSError, e: if e.errno == 2: # File doesn't exist. print >> sys.stderr, file, ": No such file or directory" else: # Failed for some other reason. BTW, "file" happens to be the name of one of the build-ins, so try to use something else, eg. "file_path". From geekmail at usenot.de Thu Dec 11 13:41:57 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Thu, 11 Dec 2008 19:41:57 +0100 Subject: Is 3.0 worth breaking backward compatibility? References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> <20081207203553.7d62434a@usenot.de> <4731f7cf-ef15-4328-85a4-de4437009f2e@40g2000prx.googlegroups.com> Message-ID: <20081211194157.32f57d3e@usenot.de> On Thu, 11 Dec 2008 10:21:55 -0800 (PST) walterbyrd wrote: > On Dec 7, 12:35?pm, Andreas Waldenburger wrote: > > > Pleeeeze. Python 3 is shipping now, and so is 2.x, where x > 5. > > Python 2 is going to be around for quite some time. What is > > everybody's problem? > > A possible, potential, problem, could arise if you were using python > 2.x, but some other code, that you wanted to include, was writen in > python 3.x. > Yes, that would be a problem, of course. But I fail to see how that is not a problem with python 2.x as well. New Style Classes? Generators? The "with" statement? I use those all the time. Why aren't as many people complaining about them with the same argument? /W -- My real email address is constructed by swapping the domain with the recipient (local part). From sjmachin at lexicon.net Mon Dec 22 16:05:46 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 22 Dec 2008 13:05:46 -0800 (PST) Subject: How to represent a sequence of raw bytes References: <200812220327.36180.motoom@xs4all.nl> <015f66d7$0$20615$c3e8da3@news.astraweb.com> Message-ID: <44a5f0ac-3021-443f-90f2-5f3bd0116d4b@w1g2000prk.googlegroups.com> On Dec 23, 1:52?am, "Steven Woody" wrote: > On Mon, Dec 22, 2008 at 6:44 PM, Steven D'Aprano > > wrote: > > On Mon, 22 Dec 2008 14:56:45 +0800, Steven Woody wrote: > > >> The intension is to allocate 200 undefined bytes in memory. > > > You *want* undefined bytes? Out of curiosity, what do you intend to do > > with them? > > to receive/send network packets, read raw files, etc. ?After read > replies of the thread, I think 'array' or 'struct' maybe what I > wanted, may a plain list can do, but I am not sure. [Rhetorical questions] How do you use "undefined bytes" to receive network packets?? Do you really want to use "undefined bytes" to *send* network packets???? Suggestion: Stop trying to replicate C in Python; think about what you are trying to accomplish at a higher level, then how to implement that in Python. Cheers, John From mensanator at aol.com Fri Dec 19 10:57:53 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 19 Dec 2008 07:57:53 -0800 (PST) Subject: How to parsing a sequence of integers References: <494ba258$0$18998$426a74cc@news.free.fr> Message-ID: On Dec 19, 9:23?am, Joe Strout wrote: > Peter Otten wrote: > > If you are using Python 2.x: > > ... > > So you better throw in a float(...): > > Or, add > > ? ?from __future__ import division > > at the top of the file. ?I put this at the top of all my Python files, > whether I expect to be dividing or not. ?It just saves grief. If you want division to be floating point. If, like me, you rarely do floating point division and want the "/" to mean integer division as God intended, then you don't put from __future__ import division in your source files. That's one of the good things about Python, you can have it either way. > > Cheers, > - Joe From inigoserna at gmail.com Sat Dec 20 18:52:24 2008 From: inigoserna at gmail.com (=?UTF-8?Q?I=C3=B1igo_Serna?=) Date: Sun, 21 Dec 2008 00:52:24 +0100 Subject: ANN: lfm v2.1 Message-ID: <65a1d6f80812201552s438150eeh40dd830fb515855c@mail.gmail.com> Hi there, As a present for Christmas I announce here a new version of 'lfm'. Description: ========= Last File Manager is a simple but powerful file manager for the UNIX console. It's written in Python, using curses module. Licensed under GNU Public License version 3. Some of the features you could find in lfm: - console-based file manager for UNIX platforms - 1-pane or 2-pane view - tabs - bookmarks - history - vfs for compressed files - dialogs with entry completion - fast access to a shell - direct integration of find/grep, df and other tools - color files by extension - fast file viewer with text and binary modes - ...and many others Download it from: ============= http://www.terra.es/personal7/inigoserna/lfm or if it doesn't show last version (crap of ISP reverse proxy), try this low-bandwidth home server: http://inigo.katxi.org/devel/lfm Changes since last version: ==================== Version 2.1 ("What do you want for Christimas?") - 2008/12/21: + Ctrl-H now show/hide dot files + Ctrl-Y display directories history + It's now posible to move the cursor in the non-active pane Consult the documentation for available keys and actions This behaviour is de/activated with Ctrl-W + added support for .7z compressed files + swapped F2 and F12 keys, now F2 rename files and F12 show file menu + new key shortcuts in dialogs. Read docs + speed up cursor movement + lots of code cleaning and refactoring + and fixed lot of bugs, some of them: - setup.py: change I?igo for Inigo to avoid problems when installing - sorting by None doesn't crash anymore - MenuWin dialog crashed when title length was greater than length of entries to show Of course, all comments, suggestions, etc. are welcome. Best regards, I?igo Serna From sumerc at gmail.com Thu Dec 4 12:45:09 2008 From: sumerc at gmail.com (k3xji) Date: Thu, 4 Dec 2008 09:45:09 -0800 (PST) Subject: Python Runtime Method Call Binding References: <0147f396$0$20670$c3e8da3@news.astraweb.com> Message-ID: <0ad65087-9b50-4d11-85a4-0ebf7e8e01a0@c1g2000yqg.googlegroups.com> test From arkanes at gmail.com Wed Dec 10 11:22:29 2008 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 10 Dec 2008 10:22:29 -0600 Subject: Flushing PyQt's Event Queue In-Reply-To: <19d41195-a734-4974-ad02-b6ddf62c316f@v5g2000prm.googlegroups.com> References: <19d41195-a734-4974-ad02-b6ddf62c316f@v5g2000prm.googlegroups.com> Message-ID: <4866bea60812100822u39cf705ay118ff6a4fb40d785@mail.gmail.com> On Wed, Dec 10, 2008 at 6:30 AM, ff wrote: > Hi, I am writing an app which models growth of a system over time > visually which is activated by button clicks, and when the loop > finishes running i dont want any events [mainly clicking on buttons] > that happened during the loop to be put into action since then it may > run multiple times without the user realising what they have done, > > is there way to flush the event queue when the loop has finished?? This is a UI problem, not a programming problem. Instead of trying to find a code solution to the problem, consider changing your UI so that the actions aren't possible. For example, disable the buttons (perhaps showing by showing a progress dialog box with a cancel button) while the sim is running. From pdorange at pas-de-pub-merci.mac.com Mon Dec 8 08:57:02 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Mon, 8 Dec 2008 14:57:02 +0100 Subject: Beginner trying to understand functions. References: Message-ID: <1irmx3x.1ye1mpc1xmopj2N%pdorange@pas-de-pub-merci.mac.com> simonh wrote: > def getName(): > name = input('Please enter your name: ') > print('Hello', name) > > def getAge(): > while True: > try: > age = int(input('Please enter your age: ')) > break > except ValueError: > print('That was not a valid number. Please try again.') > > def checkAge(): > permitted = list(range(18, 31)) > if age in permitted: > print('Come on in!') > elif age < min(permitted): > print('Sorry, too young.') > elif age > max(permitted): > print('Sorry, too old.') > > getName() > getAge() > checkAge() > > I get this error message: NameError: global name 'age' is not > defined. Indeed age was not a global... So : 1/ make it a global (just define "age=0" before getAge() 2/ or return a value from getAge() and pass this avlue to checkAge. I recommand the second option, less globals is always better. def getAge(): while True: try: age = int(input('Please enter your age: ')) return age except ValueError: print('That was not a valid number. Please try again.') def checkAge(age,min=18,max=31): if age in list(range(min, max)): print('Come on in!') elif age < min: print('Sorry, too young.') elif age > max: print('Sorry, too old.') getName() a=getAge() checkAge(a) For my part, i wouldn't loop getAge(? this way : i dislike infinite loop. I prefer to return None when ther is an error and check for None in the main program def getAge(): try: age = int(input('Please enter your age: ')) return age except ValueError: print('That was not a valid number. Please try again.') return None getName() a=getAge() if a!=None: checkAge(a) of i you want to loop in getAge() : def getAge(): age=-1 while age<0: try: age = int(input('Please enter your age: ')) except ValueError: print('That was not a valid number. Please try again.') return age I'm a beginner with python, perhaps it was not "pythonic", but i'm sure someone will tell is it's not. -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From rhf22 at mole.bio.cam.ac.uk Sun Dec 7 11:23:59 2008 From: rhf22 at mole.bio.cam.ac.uk (Rasmus Fogh) Date: Sun, 7 Dec 2008 16:23:59 +0000 (GMT) Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: > On Sun, 07 Dec 2008 13:03:43 +0000, Rasmus Fogh wrote: >> Jamed Stroud Wrote: > ... >>> Second, consider that any value in python also evaluates to a truth >>> value in boolean context. > But bool(x) can fail too. So not every object in Python can be > interpreted as a truth value. >>> Third, every function returns something. > Unless it doesn't return at all. >>> A function's returning nothing >>> is not a possibility in the python language. None is something but >>> evaluates to False in boolean context. >> Indeed. The requirement would be not that return_value was a boolean, >> but that bool(return_value) was defined and gave the correct result. > If __bool__ or __nonzero__ raises an exception, you would like Python to > ignore the exception and return True or False. Which should it be? How > do you know what the correct result should be? > From the Zen of Python: > "In the face of ambiguity, refuse the temptation to guess." > All binary operators are ambiguous when dealing with vector or array > operands. Should the operator operate on the array as a whole, or on > each element? The numpy people have decided that element-wise equality > testing is more useful for them, and this is their prerogative to do so. > In fact, the move to rich comparisons was driven by the needs of numpy. > http://www.python.org/dev/peps/pep-0207/ > It is a *VERY* important third-party library, and this was not the first > and probably won't be the last time that their needs will move into > Python the language. > Python encourages such domain-specific behaviour. In fact, that's what > operator-overloading is all about: classes can define what any operator > means for *them*. There's no requirement that the infinity of potential > classes must all define operators in a mutually compatible fashion, not > even for comparison operators. > For example, consider a class implementing one particular version of > three-value logic. It isn't enough for == to only return True or False, > because you also need Maybe: > True == False => returns False > True == True => returns True > True == Maybe => returns Maybe > etc. > Or consider fuzzy logic, where instead of two truth values, you have a > continuum of truth values between 0.0 and 1.0. What should comparing two > such fuzzy values for equality return? A boolean True/False? Another > fuzzy value? > Another one from the Zen: > "Special cases aren't special enough to break the rules." > The rules are that classes can customize their behaviour, that methods > can fail, and that Python should not try to guess what the correct value > should have been in the event of such a failure. Equality is a special > case, but it isn't so special that it needs to be an exception from > those rules. > If you really need a guaranteed-can't-fail[1] equality test, try > something like this untested wrapper class: > class EqualityWrapper(object): > def __init__(self, obj): > self.wrapped = obj > def __eq__(self, other): > try: > return bool(self.wrapped == other) > except Exception: > return False # or maybe True? > Now wrap all your data: > data = [a list of arbitrary objects] > data = map(EqualityWrapper, data) > process(data) > [1] Not a guarantee. Well, lots to think about. Just to keep you from shooting at straw men: I would have liked it to be part of the design contract (a convention, if you like) that 1) bool(x == y) should return a boolean and never throw an error 2) x == x return True I do *not* say that bool(x) should never throw an error. I do *not* say that Python should guess a return value if an __eq__ function throws an error, only that it should have been considered a bug, or at least bad form, for __eq__ functions to do so. What might be a sensible behaviour (unlike your proposed wrapper) would be the following: def eq(x, y): if x is y: return True else: try: return (x == y) except Exception: return False If is is possible to change the language, how about having two diferent functions, one for overloading the '==' operator, and another for testing list and set membership, dictionary key identity, etc.? For instance like this - Add a new function __equals__; x.__equals__(y) could default to bool(x.__eq__(y)) - Estalish by convention that x.__equals__(y) must return a boolean and may not intentionally throw an error. - Establish by convention that 'x is y' implies 'x.__equals__(y)' in the sense that (not (x is y and not x.__equals__(y)) must always hold - Have the Python data structures call __equals__ when they want to compare objects internally (e.g. for 'x in alist', 'x in adict', 'set(alist)', etc. - Provide an equals(x,y) built-in that calls the __equals__ function - numpy and others who (mis)use '==' for their own purposes could use def __equals__(self, other): return (self is other) For the float NaN case it looks like things are already behaving like this. For numpy objects you would not lose anything, since 'numpyArray in alist' is broken anyway. I still think it is a bad choice that numpy got to write array1 == array2 for their purposes, while everybody else has to use if equals(x, y): but at least both sides could get the behaviour they want. Yours, Rasmus --------------------------------------------------------------------------- Dr. Rasmus H. Fogh Email: r.h.fogh at bioc.cam.ac.uk Dept. of Biochemistry, University of Cambridge, 80 Tennis Court Road, Cambridge CB2 1GA, UK. FAX (01223)766002 From gagsl-py2 at yahoo.com.ar Sun Dec 28 02:15:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 28 Dec 2008 05:15:55 -0200 Subject: C API: array of floats/ints from python to C and back References: Message-ID: En Sun, 28 Dec 2008 01:47:08 -0200, Daniel Fetchinson escribi?: >> As others already said, using a Numpy array or an array.array object >> would >> be more efficient (and even easier - the C code gets a pointer to an >> array >> of integers, as usual). > > I looked for this in the C API docs but couldn't find anything on how > to make an array.array python object appear as a pointer to integers > (or floats, etc) in C code. On > > http://docs.python.org/c-api/concrete.html#sequence-objects > > There is only list and tuple or maybe you mean byte array? That has > only been introduced in python 2.6 and I'm working on 2.5. array is a library module, and isn't really part of the API. You're looking for the buffer protocol: PyObject_AsReadBuffer/PyObject_AsWriteBuffer; see http://docs.python.org/c-api/objbuffer.html Given an array.array('l') (containing C long integers): int do_something(PyObject* obj) { long *vec; Py_ssize_t nbytes, nitems, i; if (PyObject_AsReadBuffer(obj, (const void **)&vec, &nbytes) != 0) return NULL; nitems = nbytes/sizeof(long); for (i=0; i <49443531.5050304@v.loewis.de> <49448FC2.6030306@v.loewis.de> Message-ID: On 14 Des, 05:46, "Martin v. L?wis" wrote: > > Yes. If you want a display that is guaranteed to work on your terminal, > use the ascii() builtin function. But shouldn't the production of an object's representation via repr be a "safe" operation? That is, the operation should always produce a result, regardless of environmental factors like the locale or terminal's encoding support. If John were printing the object, it would be a different matter, but he apparently just wants to see a sequence of characters which represents the object. Paul From python-url at phaseit.net Mon Dec 8 11:56:39 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 8 Dec 2008 16:56:39 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Dec 8) Message-ID: QOTW: "To the pure, everything, properly described, is pure ;-)" - Bengt Richter The final version of Python 3.0 was released last Wednesday, jointly with 2.6.1 - congratulations! http://groups.google.com/group/comp.lang.python/t/f92e7e2db667d903/ Implementing "lazy" properties: http://groups.google.com/group/comp.lang.python/t/ce1d75c31a6e2df1/ Overriding __special__ methods at the instance level: http://groups.google.com/group/comp.lang.python/t/3442c5004de0d411/ Strategy to develop libraries both for 2.x and 3.x http://groups.google.com/group/comp.lang.python/t/ee4f9e645e5f41d0/ Guidelines for designing a project's structure on disk: http://groups.google.com/group/comp.lang.python/t/e8dd7109df5f61b2/ A detective story: a hard-to-find bug regarding how 3.0 reads UTF16-encoded files: http://groups.google.com/group/comp.lang.python/t/ae1bc6660a6b2c5f/ When translated into Python, a Perl example about closures shows a few differences between 2.5 and 3.0: http://groups.google.com/group/comp.lang.python/t/5c6734bc5181af6a/ Learning Python for Perl programmers: http://groups.google.com/group/comp.lang.python/t/d2abcb3e75c5f041/ An alternative syntax for defining methods (moving self out of the argument list): http://groups.google.com/group/comp.lang.python/t/5457b8649040f7ea/ "as" is now a keyword (2.6); that breaks some existing code, and angers several people: http://groups.google.com/group/comp.lang.python/t/e9ffe83fcf4b0af0/ 3.0 file read/write is slow and not as optimized as 2.x: http://groups.google.com/group/comp.lang.python/t/6c4d3a2d678c1eba/ http://groups.google.com/group/comp.lang.python/t/9046eee09137c657/ ======================================================================== 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 Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From clp at rebertia.com Thu Dec 25 02:35:13 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 24 Dec 2008 23:35:13 -0800 Subject: How to display Chinese in a list retrieved from database via python In-Reply-To: References: Message-ID: <47c890dc0812242335g187358a8u7f8cb1df5c864fab@mail.gmail.com> On Wed, Dec 24, 2008 at 11:29 PM, zxo102 wrote: > Hi, > I retrieve some info in Chinese from postgresql and assign it to a > variable 'info' defined in javascript of a html page: > var info = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce > \xc4'] > But I want it to be > var info = ['??','??','??'] > since in html pages (via javascript), the items in chinese out of the > former :['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4'] can > not be displayed correctly when it is inserted into a html page. If > the list is var info = ['??','??','??'] , then everything works > fine. > > Anybody knows how to solve this problem? Upgrading to Python 2.6 would probably be beneficial due to its better handling of Unicode. Also, posting some of the actual code you're using (to generate JavaScript, I guess?) would definitely help. Merry Christmas, Chris -- Follow the path of the Iguana... http://rebertia.com From redrackem at yahoo.com Wed Dec 24 20:07:27 2008 From: redrackem at yahoo.com (Red Rackham) Date: Wed, 24 Dec 2008 17:07:27 -0800 (PST) Subject: ctypes & strings Message-ID: <334452.47084.qm@web30003.mail.mud.yahoo.com> Hi friends; ? I would like to pass a string into a dll function.? I notice that to pass using ctypes, it has to be a ctypes type.? Looking at the ctypes doc page I don't see a c_string class.? ? I tried to pass in?byref("name of string") and got back "TypeError: byref() argument must be a ctypes instance, not 'str'" ? If I use astr = create_string_buffer( "name of string" ), and try to pass that in, I get "ValueError: Procedure probably called with too many arguments (4 bytes in excess)". ? If I use astr = (c_char*255)("name of string"), I get "TypeError: one character string expected" (on this line). ? Could some benevolet expert please clue me in on how to accomplish this? ? Thanks!!!! ? Mark ? ? ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From dadapapa at googlemail.com Thu Dec 4 06:24:42 2008 From: dadapapa at googlemail.com (Harold Fellermann) Date: Thu, 4 Dec 2008 03:24:42 -0800 (PST) Subject: Don't you just love writing this sort of thing :) References: Message-ID: <5d680f7c-9127-4b6c-8179-849b5d27fd66@t2g2000yqm.googlegroups.com> On Dec 4, 10:39?am, Cong Ma wrote: > Lawrence D'Oliveiro wrote: > > for \ > > ? ? ? ? Entry \ > > ? ? in \ > > ? ? ? ? sorted \ > > ? ? ? ? ? ( > > ? ? ? ? ? ? f for f in os.listdir(PatchesDir) if PatchDatePat.search(f) != None > > ? ? ? ? ? ) \ > > : > > ? ? Patch = (open, gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir, Entry), "r") > > ? ? ... read from Patch ... > > ? ? Patch.close() > > #end for > > The "if ... != None" is not necessary... ?"if PatchDatePat.search(f)" is OK. > And I don't like it... Maybe the whole if clause is not necessary? This is how I would try it: for Entry in filter(PatchDatePat.search, os.listdir(PatchesDir)) : fname = os.path(PatchesDir, Entry) Patch = file(fname) if fname.endswith('.gz') else GzipFile(fname) # ... read from Patch ... Patch.close() From joe at strout.net Tue Dec 30 16:55:24 2008 From: joe at strout.net (Joe Strout) Date: Tue, 30 Dec 2008 14:55:24 -0700 Subject: embedding python in wxpython In-Reply-To: References: <191280cf-ecf9-4135-9737-9923061855d1@t39g2000prh.googlegroups.com> Message-ID: <495A98CC.5070808@strout.net> Steve Holden wrote: >> I'd like the console to be a bidirectional representation of what's >> going on in the gui, plus a general purpose evaluation environment >> where you can manipulate application data via some api which is >> automatically exposed to the console when the application opens up. >> >> I'm looking for high-level hints/strategies/directions. >> > I seem to remember you can create your wxApp with an argument of True or > False. One of those settings creates a window containing any output to > sys.stderr, if I remember rightly. You do -- True (the default) redirects standard output to a window, while False does not redirect it. However, neither setting will create a bidirectional console or evaluation environment as the OP was asking for. (But other wx widgets do provide that, as other replies have pointed out.) Best, - Joe From joe at strout.net Thu Dec 11 18:21:47 2008 From: joe at strout.net (Joe Strout) Date: Thu, 11 Dec 2008 16:21:47 -0700 Subject: list organization question In-Reply-To: References: Message-ID: <0C41D49F-A972-41AF-91B4-DF4E1486A020@strout.net> On Dec 11, 2008, at 4:12 PM, Robocop wrote: > I have a list of objects, each object having two relevant attributes: > date and id. I'd like not only organize by id, but also by date. > I.e. i would like to parse my list into smaller lists such that each > new mini-list has a unique date, but consists of only objects with a > specific id. I'm not quite following you here. What are the inputs and outputs you're after? For the sake of argument let's say you want: given the list of objects (let's call it mylist), and a desired ID (desired_id), return a smaller list of all the objects with that ID. That would be simply: return [item for item in mylist if item.id=desired_id] Look up "list comprehensions" for an explanation of what's going on here. If you want a list for a given date, then just change the "if" part. You seem to want both at once, but I can't understand what that means. HTH, - Joe From hackingkk at gmail.com Mon Dec 15 07:46:18 2008 From: hackingkk at gmail.com (Krishnakant) Date: Mon, 15 Dec 2008 18:16:18 +0530 Subject: %s place holder does not let me insert ' in an sql query with python. Message-ID: <1229345178.31093.24.camel@krishna-laptop> hello all hackers. This is some kind of an interesting situation although many of you must have already gone through it. I am facing a situation where I have to use psycopg2 and insert rows in a postgresql table. That's pritty easy and no need to say that it works well. But there are some entries which have an ' in the value. I have a venders table in my database and one of the values tryed was "His Master's Voice " now the master's word has the ' which is used for starting and ending a varchar value for postgresql or almost any standard RDBMS. Does any one know what is the way out of this? how do you let the ' go as a part of the string? I have used %s as placeholder as in queryString = "insert into venders values ('%s,%s,%s" % (field1,field2,field3 ) ... This is not working for the ' values. can any one suggest a suitable solution? happy hacking. Krishnakant. From fuzzyman at gmail.com Wed Dec 10 18:33:54 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Wed, 10 Dec 2008 15:33:54 -0800 (PST) Subject: Dabo 0.9.0 Released References: Message-ID: On Dec 10, 7:24?pm, Ed Leafe wrote: > We are proud (and relieved!) to finally release Dabo 0.9.0, the first ? > official release of the framework in six months. We haven't been ? > taking it easy during that period; rather, we made some changes that ? > clean up some weak spots in the codebase, and as a result can offer a ? > much more solid framework, and are on course for a 1.0 release in the ? > near future. > Congratulations Ed and crew. Michael Foord -- http://www.ironpythoninaction.com/ From 7068316797 at message.alltel.com Thu Dec 25 09:21:51 2008 From: 7068316797 at message.alltel.com (7068316797 at message.alltel.com) Date: Thu, 25 Dec 2008 08:21:51 -0600 Subject: anagram finder / dict mapping questi Message-ID: <2310590.1230214932928.JavaMail.root@MD-00> An embedded and charset-unspecified text was scrubbed... Name: file.plain URL: From narkewoody at gmail.com Fri Dec 19 08:20:48 2008 From: narkewoody at gmail.com (Steven Woody) Date: Fri, 19 Dec 2008 21:20:48 +0800 Subject: How to parsing a sequence of integers Message-ID: Hi, I am a newbie and is reading the python book. Could anyone tell me, how to parsing the following string "123 100 12 37 ..." into a list of integers on which I can then apply max()/min()? In additional to max/min, is there something like average()? Thanks in advance. - narke From skip at pobox.com Mon Dec 22 12:53:14 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 22 Dec 2008 11:53:14 -0600 Subject: I always wonder ... Message-ID: <18767.54282.188749.522233@montanaro-dyndns-org.local> ... shouldn't people who spend all their time trolling be doing something else: studying, working, writing patches which solve the problems they perceive to exist in the troll subject? Is there some online troll game running where the players earn points for generating responses to their posts? -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From steve at REMOVE-THIS-cybersource.com.au Wed Dec 17 19:54:09 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Dec 2008 00:54:09 GMT Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> <6a76b501-f6dc-41b5-8828-b55fece68651@l33g2000pri.googlegroups.com> <49497aa4$0$9084$426a74cc@news.free.fr> Message-ID: <01599693$0$20656$c3e8da3@news.astraweb.com> On Wed, 17 Dec 2008 22:19:43 +0100, Bruno Desthuilliers wrote: > Your > problem is that you are confusing variables and attributes. In Python, > 'anything.anyname' (note the dot) is the attribute 'anyname' of object > 'anything'. An easy mistake to make, given that scopes are just namespaces, and attribute access is just accessing names in namespaces too. -- Steven From benjamin.kaplan at case.edu Fri Dec 12 00:35:43 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 12 Dec 2008 00:35:43 -0500 Subject: how to convert '\xf0' to 0xf0 ? In-Reply-To: <8f5b95c0-486d-48ce-b75c-e18a86d73f50@l33g2000pri.googlegroups.com> References: <1cb85265-1c36-4e4b-88f1-46b0ebae3dea@v5g2000prm.googlegroups.com> <8f5b95c0-486d-48ce-b75c-e18a86d73f50@l33g2000pri.googlegroups.com> Message-ID: On Fri, Dec 12, 2008 at 12:28 AM, wrote: > Hi, > > ord('\xf0') works and it only works for char. Do you know any way to > convet > '\xf0\xf0' and '\xf0\xf0\xff\xfe' to integer? > Is that supposed to be a single integer or 4 integers? Either way, you'd use a for loop to iterate over each character. 4 integers : >>> a = '\xf0\xf0\xff\xfe' >>> b = [ord(ch) for ch in a] >>> b [240, 240, 255, 254] 1 really large integer: >>> a = '\xf0\xf0\xff\xfe' >>> i = 0 >>> for ch in a : ... i = i << 8 ... i += ord(ch) ... >>> i 4042326014L > > > Br, Chen Gang > > On Dec 12, 12:40 pm, Steve Holden wrote: > > chengang.beij... at gmail.com wrote: > > > '\xf0' is the value read from a binary file, I need to change this > > > kinds strings to int for further processing... > > > if it is in C, then '\xf0' is an integer and it can be handled > > > directly, but in python, it is a string. > > > > > and both int('10',16) and int('0x10',16) returns 16. > > > > > Br, Chen Gang > > > > > On Dec 12, 12:06 pm, Tommy Nordgren wrote: > > >> On Dec 12, 2008, at 4:48 AM, chengang.beij... at gmail.com wrote: > > > > >>> int('\xf0',16) doesn't work, any way to do that? > > >>> -- > > >>>http://mail.python.org/mailman/listinfo/python-list > > >> Should be int('10',16) > > >> or int('0x10',16) > > > > It seems that you want the integer value of a character you read in from > > a file. Is this correct? Note that '\xf0' is the interpreter's way of > > representing a one-character string whose only character has the > > hexadecimal value f0, because the actual character is not printable: the > > backslash has a special meaning in character string literals. > > > > Any one-character string, however, can be converted to the equivalent > > integer value using the ord() function. You can convert the other way > > using the chr() function: > > > > > > > > >>> ord('A') > > 65 > > >>> chr(65) > > 'A' > > >>> ord('\xf0') > > 240 > > >>> chr(240) > > '\xf0' > > >>> hex(240) > > '0xf0' > > > > So just apply the ord() function to the character and you'll get its > > integer value! > > > > regards > > Steve > > -- > > Steve Holden +1 571 484 6266 +1 800 494 3119 > > Holden Web LLC http://www.holdenweb.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Fri Dec 26 16:50:41 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 26 Dec 2008 13:50:41 -0800 (PST) Subject: Right way to set a variable to NULL? References: <5nfal41gom0iqi2nh5h0m5847ev9brtvpf@4ax.com> Message-ID: <1401c3b2-e80d-4339-b519-4ded340e6e28@r15g2000prd.googlegroups.com> On Dec 27, 7:33?am, Gilles Ganault wrote: > Hello > > I use regexes to extract information from a text file. Some of the > records don't have e-mails or www addresses, so those must match Null > in SQL, but None doesn't work as expected: > > ======= > ? ? ? ? if itemmatch: > ? ? ? ? ? ? ? ? web = itemmatch.group(1).strip() > ? ? ? ? else: > ? ? ? ? ? ? ? ? web = None > > ? ? ? ? sql = 'INSERT INTO mytable ?(name,address,web,mail) VALUES > ("%s","%s","%s","%s","%s")' % (name,address,web,mail) > ======= You have MULTIPLE problems here. PROBLEM 1: That code won't even create the "sql" string; you have %s 5 times, but only 4 elements in the tuple. When asking for help, always post (1) the code that you actually ran (2) the result or error message that you got [merely saying "doesn't work" is not very useful at all]. PROBLEM 2: Having fixed problem 1, the result is not valid SQL; you get VALUES ("Gilles", ...; it should be VALUES('Gilles', ... PROBLEM 3: Having fixed problem 2: If you have a name like "L'Hopital" or "O'Reilly" the result is VALUES('L'Hopital', ...; it should be VALUES ('L''Hopital', ... *AND* you don't have to worry about all the rules for SQL constant values; the worrying and work has been done for you. > Is there a better way in Python to have a variable match NULL than > building the SQL query step by step? Yes. Don't construct the SQL query by Python string formatting. In fact, don't *ever* construct *any* SQL query that needs args by using string formatting/interpolation in *any* language, even when you think it's "working" -- see http://en.wikipedia.org/wiki/SQL_injection ... search for "SQL injection attack" for more references. Essential reference: the Python Database API Specification v2.0 (http://www.python.org/dev/peps/pep-0249/) You need something like: sql = "INSERT INTO mytable (name,address,web,mail) VALUES(?,?,?,?)" cursor.execute(sql, (name, address, web, mail)) Some database software uses something other than ? to mark parameter positions; you may need (for example) ... VALUES(%s,%s,%s,%s) ... (*NOT* the same meaning as %s in Python!). Read about "paramstyle" in the DB API spec, and check the documentation for the DB software that you are using. HTH, John From mikko.viitamaki at gmail.com Mon Dec 1 07:55:32 2008 From: mikko.viitamaki at gmail.com (=?ISO-8859-1?Q?Mikko_Viitam=E4ki?=) Date: Mon, 1 Dec 2008 14:55:32 +0200 Subject: How to distribute a Python app together with its dependencies? In-Reply-To: References: Message-ID: <48da7eab0812010455j2ff92d59ye64785ae071ecb72@mail.gmail.com> On Sun, Nov 30, 2008 at 2:22 PM, Alessio Pace wrote: > Hi, > > I have to distribute a Python application which relies on an external > library, and I'm not very fluent in this kind of stuff with Python (I > come from the Java world where I would have used the Maven build tool > to create an "assembly with dependencies" of all it is needed to run > the app), so I was wondering if someone here could give me some > suggestions :-) > > The external library is generally not present on the machines where I > have to distribute my app, and the set of machines on which I have to > distribute this application is not known a priori (it is just known > they are Unix systems). In fact by means of SSH I will have to copy > (and install) the app+library and make it runnable onto the specified > destination(s). > > My question is: how would you do that? At the moment my current > solution is to make a tarball of the sources of my app + the > "distutils" archive of the external library, copy all into the target > machine, decompress and install via distutils(*) the external library, > setup some PYTHONPATH stuff on the destination machine, and finally be > able to launch the application. > > (*) specifying a prefix into the user home, as I'm not root there > > > So in the end I was wondering if there is a more elegant way of doing > this because, as I said before, I'm not very experienced in these kind > of tasks in Python. > > Thanks in advance for any suggestion or comment. > > Alessio Pace. > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, I was reading Learning Python yesterday and I think this was mentioned: http://peak.telecommunity.com/DevCenter/PythonEggs I don't have experience either so no guarantees cheers /mikko/ From skip at pobox.com Wed Dec 3 14:24:45 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 3 Dec 2008 13:24:45 -0600 Subject: python an sqlite objects In-Reply-To: <4936dab7$0$9107$426a74cc@news.free.fr> References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <4936bceb$0$16783$426a34cc@news.free.fr> <4936dab7$0$9107$426a74cc@news.free.fr> Message-ID: <18742.56573.208546.568369@montanaro-dyndns-org.local> Bruno> Most of the time, you want to serialize the instance's __dict__. Does it recreate an instance at the other end or just a dict? Skip From rt8396 at gmail.com Sun Dec 21 14:26:02 2008 From: rt8396 at gmail.com (r) Date: Sun, 21 Dec 2008 11:26:02 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: I noticed when i mentioned "self" nobody wants to touch that subject. There could be many reasons why... 0.) nobody but the 10 regulars i see here exists 1.) nobody cares(doubt it) 2.) nobody is brave enough to question it(maybe) 3.) most people like to type self over and over again(doubt it) 4.) most people here have given up on changing the BDFL's mind about it. (good possibility) 5.) this is a hot-button topic(no doubt in my mind!) I think Guido's intension's are pure, but this is a major turnoff to new users. Do we really need to hold a new users hand that much. Does it really matter if they know the path of said obj. If you can't fiqure this out for yourself you have much greater problems. I do not like self, and i lamented it from day one, now it is second nature to me but does that mean it is really needed?? I feel i have been brainwashed into its usage. This was the reason for using indention over the bracket plague in python. REDUNDANCY!!! Why not dump self and make the language cleaner. I love python's classes, but HATE self.redundant! This really needs to be fixed, and you have not heard the last from me about it!!! 3000 would have been the perfect time to dump self and really clean up the language, and it's not too late, dawn is not upon us yet. From walterbyrd at iname.com Wed Dec 17 13:20:21 2008 From: walterbyrd at iname.com (walterbyrd) Date: Wed, 17 Dec 2008 10:20:21 -0800 (PST) Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> <175fa5d5-f345-47b8-a686-e0e36e1b99e9@q37g2000vbn.googlegroups.com> Message-ID: <39eec12b-d7cc-44b5-aa65-bfa559dcba05@n33g2000pri.googlegroups.com> On Dec 17, 10:00?am, r wrote: > When writing > procedural code how would you like it if vars inside functions were > automatically global. Your code with be blowing chunks in no time. That was my point - I consider python's ordinary use of lexical scoping to be a good thing, and I was wondering why this "good thing" was not used in classes, as well as outside of classes. From dickinsm at gmail.com Sun Dec 28 09:38:32 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 28 Dec 2008 06:38:32 -0800 (PST) Subject: math module for Decimals References: <01671a9e$0$6988$c3e8da3@news.astraweb.com> <016721cc$0$6988$c3e8da3@news.astraweb.com> Message-ID: On Dec 28, 7:28?am, Steven D'Aprano wrote: > Ah crap, I forgot that from_float() has been left out of the decimal API. > That's very annoying. Agreed. It's maybe even annoying enough that a feature request at bugs.python.org might be honoured. (Hint, hint!) It's fairly easy to emulate in Python 2.6 and above, using the as_integer_ratio float method: >>> from decimal import Decimal >>> from math import pi >>> n, d = pi.as_integer_ratio() >>> Decimal(n)/d Decimal('3.141592653589793115997963469') Mark From gagsl-py2 at yahoo.com.ar Tue Dec 23 13:00:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 23 Dec 2008 16:00:08 -0200 Subject: Are python objects thread-safe? References: <5306b56c-eb8c-4148-b426-013caa871375@b41g2000pra.googlegroups.com> Message-ID: En Tue, 23 Dec 2008 11:30:25 -0200, Duncan Booth escribi?: > Aaron Brady wrote: > >> Th.1 Th.2 >> a=X >> a=Y >> a=Z >> >> You are saying that if 'a=Z' interrupts 'a=Y' at the wrong time, the >> destructor for 'X' or 'Y' might not get called. Correct? In serial >> flow, the destructor for X is called, then Y. > > No, the destructors will be called, but the destructors can do pretty > much > anything they want so you can't say the assignment is atomic. This isn't > actually a threading issue: you don't need multiple threads to experience > werid issues here. If you do strange things in a destructor then you can > come up with confusing code even with a single thread. A simple example showing what you said: py> class A: ... def __del__(self): ... global a ... a = None ... py> a = A() py> a = 3 py> print a None -- Gabriel Genellina From prologic at shortcircuit.net.au Tue Dec 16 19:28:07 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 17 Dec 2008 10:28:07 +1000 Subject: Free place to host python files? In-Reply-To: <47c890dc0812161625o76f5c7e6lb8809b99f6962d32@mail.gmail.com> References: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> <47c890dc0812161625o76f5c7e6lb8809b99f6962d32@mail.gmail.com> Message-ID: On Wed, Dec 17, 2008 at 10:25 AM, Chris Rebert wrote: > I'll plug Bitbucket (http://bitbucket.org/). It gives you 150MB of > Mercurial hosting for free, along with a bug tracker and wiki. And I > hear it's implemented using Django. FreeHG (http://freehg.org) is pretty good too :) cheers James From tjreedy at udel.edu Mon Dec 1 14:06:24 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Dec 2008 14:06:24 -0500 Subject: python 2.5.2 or Python 2.6 compilation problem on AIX 5.3 In-Reply-To: <26fbc708-1b64-4271-9c7d-4394aa281f47@j39g2000yqn.googlegroups.com> References: <26fbc708-1b64-4271-9c7d-4394aa281f47@j39g2000yqn.googlegroups.com> Message-ID: desas2 at gmail.com wrote: > Hello: > I am trying to compile Python 2.5.2 on AIX 5.3 with gcc 4.2.3. I am > getting following error. (I also tried Python 2.6 with same error) > > creating build/temp.aix-5.3-2.5/share/tmhsdsd2/tmp/Python-2.5.2/ > Modules > gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - > Wstrict-prototypes -I. -I/share/tmhsdsd2/tmp/Python-2.5.2/./Include - > I. -IInclude -I./Include -I/usr/local/include -I/share/tmhsdsd2/tmp/ > Python-2.5.2/Include -I/share/tmhsdsd2/tmp/Python-2.5.2 -c /share/ > tmhsdsd2/tmp/Python-2.5.2/Modules/_struct.c -o build/temp.aix-5.3-2.5/ > share/tmhsdsd2/tmp/Python-2.5.2/Modules/_struct.o > creating build/lib.aix-5.3-2.5 > > ./Modules/ld_so_aix gcc -pthread -bI:Modules/python.exp build/ > temp.aix-5.3-2.5/share/tmhsdsd2/tmp/Python-2.5.2/Modules/_struct.o -L/ > usr/local/lib -lpython2.5 -o build/lib.aix-5.3-2.5/_struct.so > collect2: library libpython2.5 not found Have you checked all the directories on PATH to see if any contain libpython2.5? > *** WARNING: renaming "_struct" since importing it failed: > 0509-022 Cannot load module build/lib.aix-5.3-2.5. > 0509-026 System error: A file or directory in the path name > does not exist. > error: No such file or directory > make: 1254-004 The error code from the last command is 1. > > > Stop. > > > I am not able to find the problem. I would appreciate, if you could > help. I used following command line options to confugure. > ./configure --prefix=/home/hci/dinakar/python25 -enable-shared --with- > gcc > > Thank you. > Dinakar > -- > http://mail.python.org/mailman/listinfo/python-list > From steve at REMOVE-THIS-cybersource.com.au Tue Dec 30 21:11:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Dec 2008 02:11:12 GMT Subject: TypeError: list indices must be integers References: <2e5a61c0-fa99-4170-81ca-eb3a10859400@k36g2000pri.googlegroups.com> Message-ID: <016acbbf$0$6988$c3e8da3@news.astraweb.com> On Tue, 30 Dec 2008 17:46:11 -0800, dubux wrote: > i keep getting "TypeError: list indices must be integers" on the > following line "date = mylist[y]" > can someone please explain this and give me the proper way to achieve > what im trying to do? The obvious question is, what is the value of y? Insert a line: print type(y), y immediately before date = mylist[y] and see what it says. I'm guessing that it will say that y is a string. -- Steven From __peter__ at web.de Tue Dec 9 14:26:38 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Dec 2008 20:26:38 +0100 Subject: StringIO in 2.6 and beyond References: Message-ID: Bill McClain wrote: > On 2008-12-09, Peter Otten <__peter__ at web.de> wrote: > >> >>> out = io.StringIO() >> >>> print(u"hello", file=out, end=u"\n") >> >>> out.getvalue() >> u'hello\n' > > That has the benefit of working. Thank you! > > That can't be the intended behavior of print(), can it? Insering > non-unicode spaces and line terminators? I thought all text was unicode > now. Or is that only in 3.0? Yes it's 3.0 only. I have no clear idea of the implications of using the print() function in 2.6 yet; maybe changing the defaults for end/sep to unicode would suffice to make it work smoothly. I will probably defer the transition from statement to function until I move to 3.x. One benefit of the function is that you can do things like from functools import partial print = partial(print, sep=u" ", end=u"\n") Peter From rt8396 at gmail.com Sun Dec 21 01:15:23 2008 From: rt8396 at gmail.com (r) Date: Sat, 20 Dec 2008 22:15:23 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> Message-ID: <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> On Dec 20, 11:11?pm, walterbyrd wrote: > On Dec 20, 5:05?pm, Roy Smith > > > He got really hung up on the % syntax. > > I guess it's good to know that there is, at least, one person in the > world doesn't like the % formatting. As least the move was not > entirely pointless. > > But, you must admit, of all the things people complain about with > Python, the % formatting is probably one of the least common > complaints. Complaints about Python's speed seem much more common. > > Yet, 3.0 makes the speed worse, and "fixes" a non-problem. > > I can see where the new formatting might be helpful in some cases. > But, I am not sure it's worth the cost. This all really comes down to the new python users. Yea, i said it. Not rabid fanboys like Steven and myself.(i can't speak for walter but i think he would agree) Are we going to make sure joe-blow python newbie likes the language. And doesn't get turned off and run over to ruby or whoever. Like it or not, without newusers python is doomed to the same fate as all the other "great" languages who had their 15 mins of fame. We must proactively seek out the wants of these new users and make sure python stays alive. But we also must not sell are pythonic souls in the process. It would be nice to get a vote together and see what does the average pythoneer want? What do they like, What do they dislike. What is the state of the Python Union? Does anybody know, Does anybody care? I think python is slipping away from it's dominate foothold on the world. Google's use of python may be the only thing holding this house of cards together. Ruby's "hype" is defiantly growing and unless we strive for greatness, python may fail. I think ruby may have their act together a little better than us right now. And since Ruby is such a hodge-podge of different languages, the __init__ hold is there for many. what does joe-python want??? From iofferkicks006 at gmail.com Sun Dec 21 23:27:54 2008 From: iofferkicks006 at gmail.com (www.iofferkicks.com) Date: Sun, 21 Dec 2008 20:27:54 -0800 (PST) Subject: www.iofferkicks.com china cheap wholesale nike shoes,air jordan shoes,air force one shoes. Message-ID: <382d6350-495e-4887-aec7-4862bdeffaed@r15g2000prh.googlegroups.com> Get Nike Shoes at Super Cheap Prices Discount Nike air jordans (www.iofferkicks.com) Discount Nike Air Max 90 Sneakers (www.iofferkicks.com) Discount Nike Air Max 91 Supplier (www.iofferkicks.com) Discount Nike Air Max 95 Shoes Supplier (www.iofferkicks.com) Discount Nike Air Max 97 Trainers (www.iofferkicks.com) Discount Nike Air Max 2003 Wholesale (www.iofferkicks.com) Discount Nike Air Max 2004 Shoes Wholesale (www.iofferkicks.com) Discount Nike Air Max 2005 Shop (www.iofferkicks.com) Discount Nike Air Max 2006 Shoes Shop (www.iofferkicks.com) Discount Nike Air Max 360 Catalogs (www.iofferkicks.com) Discount Nike Air Max Ltd Shoes Catalogs (www.iofferkicks.com) Discount Nike Air Max Tn Men's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 2 Women's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 3 Customize (www.iofferkicks.com) Discount Nike Air Max Tn 4 Shoes Customize ( www.iofferkicks.com) Discount Nike Air Max Tn 6 Supply (www.iofferkicks.com) Discount Nike Shox NZ Shoes Supply (www.iofferkicks.com) Discount Nike Shox OZ Sale (www.iofferkicks.com) Discount Nike Shox TL Store (www.iofferkicks.com) Discount Nike Shox TL 2 Shoes Store (www.iofferkicks.com) Discount Nike Shox TL 3 Distributor (www.iofferkicks.com) Discount Nike Shox Bmw Shoes Distributor (www.iofferkicks.com) Discount Nike Shox Elite Shoes Manufacturer (www.iofferkicks.com) Discount Nike Shox Monster Manufacturer (www.iofferkicks.com) Discount Nike Shox R4 Running Shoes (www.iofferkicks.com) Discount Nike Shox R5 Mens Shoes (www.iofferkicks.com) Discount Nike Shox Ride Womens Shoes (www.iofferkicks.com) Discount Nike Shox Rival Shoes Wholesaler (www.iofferkicks.com) Discount Nike Shox Energia Wholesaler (www.iofferkicks.com) Discount Nike Shox LV Sneaker (www.iofferkicks.com) Discount Nike Shox Turbo Suppliers (www.iofferkicks.com) Discount Nike Shox Classic Shoes Suppliers (www.iofferkicks.com) Discount Nike Shox Dendara Trainer (www.iofferkicks.com) Discount Nike Air Jordan 1 Seller (www.iofferkicks.com) Discount Nike Air Jordan 2 Shoes Seller (www.iofferkicks.com) Discount Nike Air Jordan 3 Collection (www.iofferkicks.com) Discount Nike Air Jordan 4 Shoes Collection (www.iofferkicks.com) Discount Nike Air Jordan 5 Chaussure Shoes (www.iofferkicks.com) Discount Nike Air Jordan 6 Catalog (www.iofferkicks.com) Discount Nike Air Jordan 7 Shoes Catalog (www.iofferkicks.com) Discount Nike Air Jordan 8 Customized (www.iofferkicks.com) Discount Nike Air Jordan 9 Shoes Customized (www.iofferkicks.com) Discount Nike Air Jordan 10 Wholesalers (www.iofferkicks.com) Discount Nike Jordan 11 Shoes Wholesalers (www.iofferkicks.com) Discount Nike Air Jordan 12 Factory (www.iofferkicks.com) Discount Nike Air Jordan 13 Shoes Factory (www.iofferkicks.com) Discount Nike Air Jordan 14 Shoes Sell (www.iofferkicks.com) Discount Nike Air Jordan 16 Exporter (www.iofferkicks.com) Discount Nike Air Jordan 17 Shoes Exporter (www.iofferkicks.com) Discount Nike Air Jordan 18 Offer (www.iofferkicks.com) Discount Nike Air Jordan 19 Shoes Offer (www.iofferkicks.com) Discount Nike Air Jordan 20 Manufacture (www.iofferkicks.com) Discount Nike Jordan 21 Shoes Manufacture (www.iofferkicks.com) EMAIL:IOFFERKICKS at GMAIL.COM MSN :IOFFERKICKS at MSN.COM From clp at rebertia.com Fri Dec 19 15:58:54 2008 From: clp at rebertia.com (Chris Rebert) Date: Fri, 19 Dec 2008 12:58:54 -0800 Subject: IMAP: How to implement GMail-like threaded conversations view In-Reply-To: <494BFBF4.1000205@gmail.com> References: <494BFBF4.1000205@gmail.com> Message-ID: <47c890dc0812191258t608d2e3ex5f23ba7de9ad0f97@mail.gmail.com> On Fri, Dec 19, 2008 at 11:54 AM, Michael Torrie wrote: > Martin wrote: >> Currently I am trying to get used to Python's imaplib and email >> modules. >> I'like to create a webmail client simmilar to GMail. > > This is off-topic, but why on earth would you want to emulate Gmail's > conversation views? It's horrible and a very broken way of viewing > e-mail threads. Compared the normal, threaded view of, say the > discussions on this list to the view that Gmail gives you. For > conversations of more than half a dozen posts, Gmail's view is > unnavigatable. Suppose I want to break into a discussion that's already > dozens of posts long. With a real threaded view I can easily see the > flow of the conversation, grab random posts, then maybe read their > parent or grandparent posts. Looking at the rest of your e-mail, I can > see that maybe you do want to have real threads rather than the google > conversation view which removes all structure. I disagree. Reading the messages in chronological order is natural and if people quote their parent posts properly, which they nearly always do, there's no need to consult the parent message again (and you'll have already read it by that point in the conversation anyway and recognize it). Why would you "grab random posts" anyway? It makes much more sense to just read the stream until you reach an interesting post (thus gaining the context of the _entire_ discussion) or just read the post in isolation along with its quoting of its parents. Additionally, for most normal people who've never heard of mailinglists, email conversations are typically simple back-and-forth exchanges displayed excellently by Gmail's conversation view; these same people would probably find threading complex and confusing. >> The thoughts above might lead to the second approach: >> >> b.2) Use the "Subject:" field of the messages. > > Horribly broken. Thunderbird does this and it drives me crazy. I often > get messages months apart that happen to have a common subject line, > even though they aren't the same thread or conversation. I don't want a > new message, which does not refer to the old message in any way, to > attach itself to my 6-month old message and force me to scroll down > through potentially hundreds of e-mails to find the stupid thing. No, > the RFCs are there for a reason. They bring sanity to the chaos. > Anything else is madness. And the fact the Outlook doesn't do proper > referral fields just infuriates me. Sigh. Yes, apparently circa Netscape 3.0 they used an ingenious message threading algorithm (described on http://www.jwz.org/doc/threading.html) but the Netscape 4 devs foolishly threw out the code and wrote the broken algorithm used today. Quite a shame. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From prologic at shortcircuit.net.au Tue Dec 30 22:40:33 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 13:40:33 +1000 Subject: greenlets and how they can be used Message-ID: Hey all, The "greenlet" from http://codespeak.net/py/dist/greenlet.html is a rather interesting way of handling flow of control. I can't seem to find anything else on the subject except for the above link and the most recent version 0.2 and it's tests. What can "greenlet"'s be used for ? What use-cases have you guys used them for (if any) ? Can they be used in place of threads with much the same effect - but more lightweight ? cheers James -- -- "Problems are solved by method" From lkcl at lkcl.net Wed Dec 31 15:23:22 2008 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Wed, 31 Dec 2008 20:23:22 +0000 Subject: [ANN] Builds of PyWebkitGtk and Webkit-Glib-Gtk (r39359+#16401.master) for Debian i386, Debian AMD64 and Macports MacOSX 10.4 Message-ID: webkit-glib-gtk provides gobject bindings to webkit's DOM model. pywebkitgtk provides python bindings to the gobject bindings of webkit's DOM model. files are available for download at: https://sourceforge.net/project/showfiles.php?group_id=236659&package_id=290457&release_id=650548 separate pre-built .debs for AMD64 and i386 Debian are included, for pywebkitgtk and webkit-gtk with gobject bindings to the DOM model. if you have seen OLPC/SUGAR's "hulahop", or if you have used Gecko / XUL DOM bindings, or KDE's KHTMLPart DOM bindings, you will appreciate the value of webkit-glib-gtk. pywebkitgtk with glib/gobject bindings basically brings pywebkitgtk on a par with hulahop. if you find the thought of pywebkitgtk with glib bindings, and/or hulahop to be "all too much", then do consider looking at pyjd (the other download from the same location, above). pyjd - aka pyjamas-desktop - is a level "above" pywebkitgtk-glib, and is on a par with pykde, pyqt4, pygtk2, python-wxWidgets and other desktop-based widget sets. (side-note: the advantage of pyjd is that if you write an app which conforms to the pyjamas UI widget set API, you can compile the same python app source code to javascript and run it directly in all major web browsers: see http://pyjs.org, which is a python-to-javascript compiler). code-stability-wise, pywebkitgtk and webkit-glib-gtk should be considered "experimental" (not least because this is a release from a svn build!). that having been said, pyjamas-desktop is declared "production" because pywebkitgtk with DOM bindings, thanks to webkit-glib-gtk, provides absolutely everything that pyjamas-desktop needs (and if webkit-glib-gtk becomes a moving target, the DOM.py abstraction layer in pyjamas-desktop will take care of it. if it becomes a _severe_ moving target, pyjamas-desktop will drop webkit and provide a python-hulahop / XUL-Geck port instead. or as well. whatevrrrr :). gobject-interface-wise, the webkit gobject DOM bindings that have been added _can_ be considered to be "stable", as long as the underlying webkit library IDL files are "stable" (additions to Console.idl were made in the past couple of months, for example, and HTML5 is making advances as well). that having been said, _some_ functionality proved intransigent during the initial main development phase of the webkit gobject DOM bindings, such as RGBColour conversion of CSS Style Properties, and so were *temporarily* left out. given that pyjamas-desktop is considered "production", that should give a pretty clear indication of the importance of those rare bits of DOM model bindings features that were left out. SVG Canvas bindings, however, have NOT been included, as that would have added a further 120 gobjects to the list. instructions for anyone brave enough to install webkit-glib-gtk from source, themselves, on macosx: http://github.com/lkcl/webkit/wikis/installing-webkit-glib-on-macosx there is an (experimental) Portfile in the macosx 10.4 glib tarball, as well. please note that the MacOSX build is NOT a "native" webkit build: it is a GTK / X11 build (known as a "gtk port", in webkit developer terminology). the reason for providing the MacOSX webkit-glib-gtk build, along with a MacOSX port of pywebkitgtk is because the "native" webkit build - which includes ObjectiveC bindings and thus can automatically get python bindings - has very subtly different functionality. whilst the native ObjectiveC bindings are more fully compliant with the W3C standards, providing javascript-like functionality where absolutely necessary, the webkit-glib-gtk build's gobject bindings are going specifically for direct correspondance with the functionality provided by the webkit javascript bindings, falling back to alternatives where it is absolutely not possible to achieve that goal. the actual differences, however, are extremely small, percentage-wise. out of around 300 objects, providing around 1,500 functions, and tens of thousands of properties, there are approximately 20 functions that are different, and only four properties that are different. examples of the differences in the bindings APIs offered by ObjectiveC and webkit-glib-gtk Gobject bindings include: * the provision of the function "toString", which is known as a javascriptism that is not in the W3C standard. _not_ providing this function, which is a de-facto standard, is considered to be inconvenient, especially as both Gecko's language bindings _and_ PyKDE's PyKHTMLPart bindings provide toString() functions. The ObjectiveC bindings, in sticking to the W3C standard, religiously, do not offer "toString". the reason for including toString in the webkit-glib-gtk bindings should be fairly obvious: it is unreasonable to expect developers who will be used to the de-facto existence of toString in javascript to find that it's ... disappeared for no good reason, thus forcing them to make unnecessary coding workarounds, duplicating the exact same functionality that *already* exists in the webkit library! * hspace and vspace of HTMLAppletElement, and width and height of HTMLEmbedElement, are often (mistakenly) set to "NNNpx", "100%" and other values, in javascript, contrary to the W3C standards for HTMLAppletElement and HTMLEmbedElement, respectively. to make life easier for webkit applications (such as Safari, the iPhone browser and other important webkit applications), an exception was made to allow - and cater for or ignore, as appropriate, values in these non-standard formats. Whilst the ObjectiveC bindings stick to the W3C standards, and only allow hspace, vspace, width and height to be set to integer values, the webkit-glib-gtk bindings take advantage of the underlying webkit functions that perform the conversion, and are thus more tolerant - with the proviso of course that it's perfectly possible for users to shoot themselves in the foot by trying to set vspace="10em". such foot-shooting will be silently ignored - just as it is if you tried to do the same thing with javascript. * XMLHTTPRequest.send accepts a DOMString on the webkit-glib-gtk bindings, whereas what should actually be passed in is a Webkit Document object. various attempts were made to create appropriate TextDocument and XMLDocument objects: unfortunately they failed miserably. fortunately, earlier versions of Webkit provided a version of XMLHTTPRequest.send which accepts a DOMString argument, and this version was reactivated for the webkit-glib-gtk bindings. the ObjectiveC and all other bindings successfully pass in a Webkit Document object. this issue will at some point need to be addressed, however it's pretty low priority: using a DOMString works just as well. * Document.getSelection is considered to be a javascript-ism, and is not made available to the ObjectiveC bindings. the function has been added to the webkit-glib-gtk bindings just in case anyone feels like using it. anyone wishing to use the glib/gobject DOM model directly, in c, is well advised to look at the example modified WebKitTools/GtkLauncher/main.c which can be found here: http://lkcl.net/pyjamas-desktop/main.c this modified example is not "gobject-perfect" - there are a couple of areas where an experienced gobject programmer will spot ref-count losses that have yet to be addressed, however the code does some really quite sophisticated messing-about of the DOM model, and provides genuinely useful code snippets. developers may be intrigued to know that some of the code-snippets, such as get_absolute_top(), are direct ports from pyjamas-desktop of the DOM.py getAbsoluteTop() function, which was in turn itself a direct port from the javascript code inside pyjamas DOM.py of the same function name. the technique, and the examples, will help other developers wishing to write applications, by first writing or sourcing an example written in javascript, and then following the same conversion techniques as can be seen by comparing DOM.py getAbsoluteTop() with the example main.c get_absolute_top(). anyone wishing to provide bindings to other languages, such as ruby, perl or java: the pygtk-codegen-2.0 application pretty much made mincemeat of webkit.defs (available on request, or look at code.google.com/p/pywebkitgtk issue #13 - i may update the patch soon enough) and absolutely _no_ funny business - overrides of _any_ kind - were required! the only "funny business" that's in pywebkitgtk overrides is to do with gtk, not the webkit gobject bindings. 300 objects, 1500 functions and tens of thousands of properties all get added with a vanilla .defs file. unbelievable. so this spells "good news" for the garbage-collecting languages (e.g. ruby, perl, possibly java): if your language-of-choice's gobject-auto-generator is as good as python-gobject's auto-generator, you should be up-and-running within literally a couple of hours. oh - but first: i would advise you to look at pywebkitgtk's "demobrowser.py" for guidance on how to create a webkit gtk app (using your language of choice) first, followed by looking at pyjamas-desktop's "pyjd.py" for further hints on how to bind to the DOM model functions [pyjd.py is based on demobrowser.py]. c++ is a different matter. webkitgtkmm will _not_ be gaining DOM bindings based on webkit.defs. after discussions with jonathon jongsma, we came to the conclusion that it would be far better to write a _separate_ set of bindings (gobjectmm) actually in webkit, due to subtle information being available that is lost by the time you get to webkit-gobject c-bindings. anyone anticipating to write or have webkitgtkmm "up-and-running", providing gtk / gobject bindings to webkit's DOM model, should expect to take between three and four weeks in writing a CodeGeneratorGobjectMM.pl, using the other WebKit CodeGenerators as guides. that's all, for now. bugs should be reported to the respective bugtrackers of the appropriate projects - http://code.google.com/p/pyjamas, http://code.google.com/p/pywebkitgtk and http://bugs.webkit.org should do the trick. l. From Slaunger at gmail.com Tue Dec 2 15:45:13 2008 From: Slaunger at gmail.com (Slaunger) Date: Tue, 2 Dec 2008 12:45:13 -0800 (PST) Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> <258cf433-f6c9-43e7-a235-f5f6b2b6433f@j39g2000yqn.googlegroups.com> <33b4cc2f-2311-491c-a2e6-9cc5452b1a6b@g38g2000yqd.googlegroups.com> <652449ff-3a5b-41be-a033-c3c355d277b8@z1g2000yqn.googlegroups.com> Message-ID: <8b1c6e09-a77a-4ef5-aa6e-68127ad755c1@f20g2000yqg.googlegroups.com> On 2 Dec., 17:50, George Sakkis wrote: > > > ? ? ? ? ? ? ? ? I1, Q1, I2, Q2 = bytes_to_data(buf) > > ? ? ? ? ? ? ? ? self.__dict__["I1"] = I1 > > ? ? ? ? ? ? ? ? self.__dict__["Q1"] = Q1 > > ? ? ? ? ? ? ? ? self.__dict__["I2"] = I2 > > ? ? ? ? ? ? ? ? self.__dict__["Q2"] = Q2 > > with: > > ? ? self.__dict__.update(zip(self.data_attr_names, bytes_to_data > (buf))) > > where data_attr_names = ("I1", "Q1", "I2", "Q2") instead of a > frozenset. A linear search in a size-4 tuple is unlikely to be the > bottleneck with much I/O anyway. Thank you for this little hint, George. I've never used update on a dict and the zip function before. This is a nice application of these functions. And I agree, performance is not an issue by selecting a tuple instead of a frozenset. The bytes_to_data function is the performance bottleneck in the actual application (implemented in parent class). -- Slaunger From floris.bruynooghe at gmail.com Wed Dec 17 18:06:41 2008 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Wed, 17 Dec 2008 15:06:41 -0800 (PST) Subject: C API and memory allocation Message-ID: Hi I'm slightly confused about some memory allocations in the C API. Take the first example in the documentation: static PyObject * spam_system(PyObject *self, PyObject *args) { const char *command; int sts; if (!PyArg_ParseTuple(args, "s", &command)) return NULL; sts = system(command); return Py_BuildValue("i", sts); } What I'm confused about is the memory usage of "command". As far as I understand the compiler provides space for the size of the pointer, as sizeof(command) would indicate. So I'm assuming PyArg_ParseTuple() must allocate new memory for the returned string. However there is nothing in the API that provides for freeing that allocated memory again. So does this application leak memory then? Or am I misunderstanding something fundamental? Regards Floris From pdorange at pas-de-pub-merci.mac.com Mon Dec 8 09:00:01 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Mon, 8 Dec 2008 15:00:01 +0100 Subject: Python and audio frequency analysis References: Message-ID: <1irmxjm.16x42iy1m9u5l8N%pdorange@pas-de-pub-merci.mac.com> manatlan wrote: > I'd like to make a kind of "spectrum analyzer" ... > Which should display "bars" according bands of frequencies ... in real > time... > > Is anybody know an audio processing lib in python for that ? For the display module you can use pygame, pyglet or pyOpenGL, there are fast. For the audio analysis i thought the module must be written in C or something very fast, because python, due to it's nature, would probably not compute spectrum as fast as real time : 44100 samples per seconds is a lot of work... -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From kyosohma at gmail.com Tue Dec 30 13:48:13 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 30 Dec 2008 10:48:13 -0800 (PST) Subject: Parsing Excel spreadsheets References: <6a54de23-bea4-40c7-ad7c-22c6eba4bd8a@z6g2000pre.googlegroups.com> Message-ID: <452bfdbc-b6e2-487d-9590-018a414b36a1@s9g2000prg.googlegroups.com> On Dec 30, 10:07?am, "andyh... at gmail.com" wrote: > Hi, > > Can anybody recommend an approach for loading and parsing Excel > spreadsheets in Python. Any well known/recommended libraries for this? > > The only thing I found in a brief search washttp://www.lexicon.net/sjmachin/xlrd.htm, > but I'd rather get some more input before going with something I don't > know. > > Thanks, > Andy. If you need complete control of Excel, then you'll probably have to use COM (see Mark Hammond's PyWin32 package). Otherwise, the suggestions by the others will work. Mike From rhf22 at mole.bio.cam.ac.uk Tue Dec 9 06:50:22 2008 From: rhf22 at mole.bio.cam.ac.uk (Rasmus Fogh) Date: Tue, 9 Dec 2008 11:50:22 +0000 (GMT) Subject: Rich Comparisons Gotcha Message-ID: Steven DAprano wrote: > On Mon, 08 Dec 2008 14:24:59 +0000, Rasmus Fogh wrote: snip >> What might be a sensible behaviour (unlike your proposed wrapper) Sorry 1) I was rude, 2) I thanked TJR for your wrapper class proposal in a later mail. It is yours. > What do you dislike about my wrapper class? Perhaps it is fixable. I think it is a basic requirement for functioning lists that you get >>> alist = [1,x] >>> x in alist True >>> alist.remove(x) >>> alist [1] # unless of course x == 1, in which case the list is [x]. Your wrapper would not provide this behaviour. It is necessary to do if x is y: return True be it in the eq() function, or in the list implementation. Note that this is the current python behaviour for nan in lists, whatever the mathematics say. >> would be the following: >> def eq(x, y): >> if x is y: >> return True > I've already mentioned NaNs. Sentinel values also sometimes need to > compare not equal with themselves. Forcing them to compare equal will > cause breakage. The list.__contains__ method already checks 'x is y' before it checks 'x == y'. I'd say that a list where my example above does not work is broken already, but of course I do not want to break further code. Could you give an example of this use of sentinel values? >> else: >> try: >> return (x == y) >> except Exception: >> return False > Why False? Why not True? If an error occurs inside __eq__, how do you > know that the correct result was False? > class Broken(object): > def __eq__(self, other): > return Treu # oops, raises NameError In managing collections the purpose of eq would be to divide objects into a small set that are all equal to each other, and a larger set that are all unequal to all members of the first set. That requires default to False. If you default to True then eq(aNumpyArray, x) would return True for all x. If an error occurs inside __eq__ it could be 1) because __eq__ is badly written, or 2) because the type of y was not considered by the implementers of x or is in some deep way incompatible with x. 1) I cannot help, and for 2) I am simply saying that value semantics require an __eq__ that returns a truth value. In the absence of that I want identity semantics. Rasmus From prologic at shortcircuit.net.au Thu Dec 18 01:17:47 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 18 Dec 2008 16:17:47 +1000 Subject: importing csv file into sqlite In-Reply-To: <21067453.post@talk.nabble.com> References: <21067453.post@talk.nabble.com> Message-ID: On Thu, Dec 18, 2008 at 3:58 PM, klia wrote: > hey guys, i have a hug .csv file which i need to insert it into sqlite > database using python. > my csv data looks like this > Birthday2,12/5/2008,HTC,this is my birthday > Sea,12/3/2008,kodak,sea > birthday4,14/3/2009,samsung,birthday > love,17/4/2009,SONY,view of island > > can any one give me a head start codes. How big ? When size is important in data processing, you should _never_ try to load it all up at once. Use filters... Here's a head start: $ csv2sql.py mydata.csv | sqlite3 mydatabase.db Here's the source to my csv2sql.py tool (1): ------------------------------------------------------------ #!/usr/bin/env python # Module: csv2sql # Date: 14th September 2008 # Author: James Mills, prologic at shortcircuit dot net dot au """csv2sql Tool to convert CSV data files into SQL statements that can be used to create SQL tables. Each line of text in the file is read, parsed and converted to SQL and output to stdout (which can be piped). """ __desc__ = "CSV to SQL Tool" __version__ = "0.2" __author__ = "James Mills" __email__ = "%s, prologic at shortcircuit dot net dot au" % __author__ __url__ = "http://shortcircuit.net.au/~prologic/" __copyright__ = "CopyRight (C) 2008 by %s" % __author__ __license__ = "GPL" import os import csv import optparse from cStringIO import StringIO USAGE = "%prog [options] " VERSION = "%prog v" + __version__ def parse_options(): """parse_options() -> opts, args Parse any command-line options given returning both the parsed options and arguments. """ parser = optparse.OptionParser(usage=USAGE, version=VERSION) parser.add_option("-t", "--table", action="store", default=None, dest="table", help="Specify table name") parser.add_option("-f", "--fields", action="store", default=None, dest="fields", help="Specify a list of fields") opts, args = parser.parse_args() if len(args) < 1: parser.print_help() raise SystemExit, 1 return opts, args def mkBuffer(fd): buffer = StringIO() buffer.write(fd.read()) buffer.seek(0) fd.close() return buffer def readCSV(file): if type(file) == str: fd = open(file, "rU") else: fd = file fd = mkBuffer(fd) sniffer = csv.Sniffer() dialect = sniffer.sniff(fd.readline()) fd.seek(0) reader = csv.reader(fd, dialect) for line in reader: yield line def main(): opts, args = parse_options() file = args[0] if file == "-": fd = sys.stdin if opts.table is None: print "ERROR: No table specified and stdin used." raise SystemExit(1) else: fd = open(file, "rU") if opts.table is None: table = os.path.splitext(file)[0] else: table = opts.table for line in readCSV(fd): if opts.fields: fields = [x.strip() for x in opts.fields.split(",")] fields = "(%s)" % ",".join(fields) else: fields = "" values = ",".join(["\"%s\"" % x for x in line]) print "INSERT INTO %s %s VALUES (%s);" % (table, fields, values) if __name__ == "__main__": main() ---------------------------------------------------------------- Hope this helps, Here's a small test of using it: jmills at atomant:~$ python Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> fd = open("test.csv", "w") >>> for i in xrange(1000000): ... fd.write("foo,bar,%d\n" % i) ... >>> fd.close() >>> jmills at atomant:~$ du -h test.csv 15M test.csv jmills at atomant:~$ wc -l test.csv 1000000 test.csv jmills at atomant:~$ time csv2sql.py test.csv > test.sql real 0m14.303s user 0m8.877s sys 0m0.676s cheers James References: 1. http://hg.softcircuit.com.au/projects/tools/ From ptmcg at austin.rr.com Thu Dec 4 17:35:42 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 4 Dec 2008 14:35:42 -0800 (PST) Subject: simplest way to strip a comment from the end of a line? References: <52e3f2a9-6fb1-42ef-9871-c904ede5520e@t3g2000yqa.googlegroups.com> <9cdc9039-6b7b-42fb-b261-4ad721ccd1d4@j39g2000yqn.googlegroups.com> Message-ID: Yowza! My eyes glaze over when I see re's like "r'(?m)^(?P.*? (".*?".*?)*)(?:#.*?)?$"! Here's a simple recognizer that reads source code and suppresses comments. A comment will be a '#' character followed by the rest of the line. We need the recognizer to also detect quoted strings, so that any would-be '#' comment introducers that are in a quoted string *wont* incur the stripping wrath of the recognizer. A quoted string must be recognized before recognizing a '#' comment introducer. With our input tests given as: tests ='''this is a test 1 this is a test 2 #with a comment this is a '#gnarlier' test #with a comment this is a "#gnarlier" test #with a comment '''.splitlines() here is such a recognizer implemented using pyparsing. from pyparsing import quotedString, Suppress, restOfLine comment = Suppress('#' + restOfLine) recognizer = quotedString | comment for t in tests: print t print recognizer.transformString(t) print Prints: this is a test 1 this is a test 1 this is a test 2 #with a comment this is a test 2 this is a '#gnarlier' test #with a comment this is a '#gnarlier' test this is a "#gnarlier" test #with a comment this is a "#gnarlier" test For some added fun, add a parse action to quoted strings, to know when we've really done something interesting: def detectGnarliness(tokens): if '#' in tokens[0]: print "Ooooh, how gnarly! ->", tokens[0] quotedString.setParseAction(detectGnarliness) Now our output becomes: this is a test 1 this is a test 1 this is a test 2 #with a comment this is a test 2 this is a '#gnarlier' test #with a comment Ooooh, how gnarly! -> '#gnarlier' this is a '#gnarlier' test this is a "#gnarlier" test #with a comment Ooooh, how gnarly! -> "#gnarlier" this is a "#gnarlier" test -- Paul From ajaksu at gmail.com Mon Dec 1 21:17:09 2008 From: ajaksu at gmail.com (ajaksu) Date: Mon, 1 Dec 2008 18:17:09 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <4f31c483-8382-480e-8417-b7eef1b1792d@z1g2000yqn.googlegroups.com> <8c856b01-7f0c-4d5b-a1d2-cfe7dc74389f@w3g2000yqc.googlegroups.com> <1680020c-521c-4498-8e74-92e99c03da6b@w35g2000yqm.googlegroups.com> <0d9d2404-cb3f-4390-b97c-79251db8ac95@k8g2000yqn.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> Message-ID: r, you could just calm down, stop your trolling and wait to see if more people like greg are able to see a good idea behind your awful delivery. Seriously, you're talking nonsense to people that have actively promoted, taught, developed with and helped develop Python for years. You're mistaking lack of support for your plea (to your format and Ruby-bashing, mostly) for something completely different. I wouldn't get a lot of supporters to the call of "HELP, Opera needs to support Python in webpages", and would need to be crazy(ier) to take any offense in that. So, you sound like a loony when you face that situation with a "I'll fight for FREEDOM, against all you turncoats, and I don't hate Ruby, that Satan spawn!". Just pretend to be normal a little harder (many of us do it [like me {and myself}]) and you'll be all set. I'd like to try hacking some form of Python to work in SketchUp (on top of Ruby, that is). Now, why won't I try to? I'm a Linux user and we don't get a SU version. So much for FREEDOM. BTW, some things in SU have encrypted Ruby code behind them :) Anyway, if I could hack on it, I'd try to get the Ruby API talking to Python. The main thing would be checking what RPy[0] and RubyPython[1] can offer, hoping that Bridge[2] can still work its magic with the new versions of SU. Given that people get WxRuby[3] and DLLs[4] working with SU-Ruby, Python sounds feasible. Good luck to anyone trying to get the software done :) Cheers, Daniel [0] http://rubyforge.org/projects/rpy/ [1] http://rubypython.rubyforge.org/ [2] http://plugins.ro/labs/bridge_tut.htm [3] http://wxsu.sourceforge.net/ [4] http://tinyurl.com/6h28rb From xahlee at gmail.com Tue Dec 9 18:11:20 2008 From: xahlee at gmail.com (Xah Lee) Date: Tue, 9 Dec 2008 15:11:20 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: <9ecfa224-ce8f-44e9-abca-008314f44e87@40g2000prx.googlegroups.com> On Dec 8, 5:25 pm, Terry Reedy wrote: > Lest anyone doubt that problem size is important for comparing program > run times, consider ... just in case there's any doubt: Simply change these lines in Jon's program: Main[9, 512, 4] to Main[9, 512, 4.] and it will run faster. Also, change this line: Block[{scene = Create[level, {0, -1, 4}, 1]}, to Block[{scene = Create[level, {0., -1., 4.}, 1.]}, will make it faster further. (both of which are in my version. The ?Block? can be replaced with ?With?.) As i said, this error in a Mathematica code in the context of speed is a major blunder. His denial makes him a stubborn moron. Reference: ? A Mathematica Optimization Problem http://xahlee.org/UnixResource_dir/writ/Mathematica_optimization.html Xah ? http://xahlee.org/ ? From inq1ltd at inqvista.com Fri Dec 5 15:02:26 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Fri, 05 Dec 2008 15:02:26 -0500 Subject: Problems running on hp duo Pentium R processor In-Reply-To: <200809221446.29472.inq1ltd@inqvista.com> References: <200809221443.25765.inq1ltd@inqvista.com> <200809221446.29472.inq1ltd@inqvista.com> Message-ID: <200812051502.26421.inq1ltd@inqvista.com> Python help, In September I wrote: I have a number of clients running a program built with python 2.5. One has just purchased an HP with a duo core Pentium R processor E2200, 2.2G with .99g ram. Only on the new HP, when they try to print they get an import error; File win32ui.pyc line 12, in File win32ui.pyc, line 10, in _load ImportError: DLL load failed: The specified module could not be found. It turns out that the E2200 processor is 64 bit architecture. What are my options? I've run DependecyWalker, They are using Win XP Service Pack 2 jim=on-linux From michele.simionato at gmail.com Wed Dec 10 11:21:01 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 10 Dec 2008 08:21:01 -0800 (PST) Subject: Maintaining signature in help(decorated function) References: <48f2fd47-1fc3-4b2f-ad39-24adce7e9a5c@k36g2000yqe.googlegroups.com> Message-ID: <941d9581-6165-4513-b172-a1d6295285d3@b38g2000prf.googlegroups.com> On Dec 10, 5:07?pm, jelsas wrote: > Hi -- I can't seem to maintain the function signature when applying a > decorator. ?I'm using functools.wraps. ?Example: > > >>> def mydecorator(fn): > > ... ? ? from functools import wraps > ... ? ? # simple decorator > ... ? ? @wraps(fn) > ... ? ? def wrapped(*args, **kwargs): > ... ? ? ? ? ? ? print 'i\'m wrapped!' > ... ? ? ? ? ? ? return fn(*args, **kwargs) > ... ? ? return wrapped > ... > > >>> @mydecorator > > ... def f(foo, bar): > ... ? ? '''docstring for f''' > ... ? ? pass > ... > > > > >>> help(f) > > displays: > > Help on function f in module __main__: > > f(*args, **kwargs) > ? ? docstring for f > > I would like to maintain f's signature in the help message, (foo, bar) > instead of (*args, **kwargs) > > Thanks in advance! You want the decorator module: http://www.phyast.pitt.edu/~micheles/python/documentation.html From hancock.robert at gmail.com Tue Dec 23 00:32:25 2008 From: hancock.robert at gmail.com (Robert Hancock) Date: Mon, 22 Dec 2008 21:32:25 -0800 (PST) Subject: cgitb and Apache Message-ID: <9314086c-fdf0-412f-a37e-89a871331683@k36g2000yqe.googlegroups.com> I have a cgi running in my alpha environment and, of course, everything works fine. In beta, when I attempt to access a page via our proxy, which works perfectly in alpha. It attempts to call cgitb but freezes for while and then exits. The Apache log show: [Mon Dec 22 23:49:25 2008] [error] [client 172.16.143.75] /usr/local/ python26/lib/python2.6/cgitb.py:173: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6 [Mon Dec 22 23:49:25 2008] [error] [client 172.16.143.75] value = pydoc.html.repr(getattr(evalue, name)) The source for cgitb at 173 is: pydoc.html.escape(str(evalue)))] if isinstance(evalue, BaseException): for name in dir(evalue): if name[:1] == '_': continue ---> value = pydoc.html.repr(getattr(evalue, name)) exception.append('\n
    %s%s =\n%s' % (indent, name, value)) import traceback return head + ''.join(frames) + ''.join(exception) + ''' Any suggestions on how to deal with this? From arnodel at googlemail.com Thu Dec 4 11:57:57 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 04 Dec 2008 16:57:57 +0000 Subject: funny generator behaviour References: Message-ID: Edvin Fuglebakk writes: > I have written a generator that puzzles me: > > The generator is supposed to create ordered selections of a set of > objects. repetition of objects is allowed and the selections should be > of a size determined by a pramter to the generator. > > Now, if I try to accummulate the generated selections into a list I > get some peculiar behaviour that I hope maybe some of you can help me > understand: > > Help much appreciated > -Edvin > > #straightforward acumulation. Does not give the expected result >>>> d=[] >>>> for f in orderedCombinations([1,2],3): > ... d.append(f) > ... >>>> d > [[1], [2], [1], [2], [1], [2], [1], [2]] > > #accumulating shallow copies of the genereated combinations works: >>>> d=[] >>>> for f in orderedCombinations([1,2],3): > ... d.append(f[:]) > ... >>>> d > [[1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 2, 2], [2, 1, 1], [2, 1, 2], [2, > 2, 1], [2, 2, 2]] > > > #The generator: > def orderedCombinations(pool, k): > """ > Generator yielding ordered selections of size k with repetition > from pool. > """ > > if k == 1: > for m in pool: > yield [m] > > if k > 1: > > for m in pool: > for combo in orderedCombinations(pool, k-1): > > #insert and pop to avoid copying entire list > combo.insert(0,m) > yield combo I haven't tried your code but I think the problem is that you yield a list above and then mutate it below, so when you generate the next combination the previous one is mutated. Change the above line to yield list(combo) and it should sort the problem. > combo.pop(0) -- Arnaud From clp at rebertia.com Thu Dec 11 03:05:04 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 11 Dec 2008 00:05:04 -0800 Subject: why doesn't pop/clear call __delitem__ on a dict? In-Reply-To: References: Message-ID: <47c890dc0812110005m3106ff39i9f9211a99c0afc9e@mail.gmail.com> On Wed, Dec 10, 2008 at 11:53 PM, Daniel Fetchinson wrote: > I just found out that if I want to have a custom dict it's not enough > to overload __getitem__, __setitem__ and __delitem__ because, for > example, pop and clear don't call __delitem__. I.e. an instance of the > following will not print 'deleted' upon instance.pop( 'key' ): > > class mydict( dict ): > def __setitem__( self, key, value ): > print 'set' > super( mydict, self ).__setitem__( key, value ) > def __getitem__( self, key ): > print 'get' > super( mydict, self ).__getitem__( key ) > def __delitem__( self, key ): > print 'deleted' > super( mydict, self ).__delitem__( key ) > > Why is this? For optimization purposes essentially, so that the built-in dict can be as fast as possible as it is used pervasively in Python. > what other methods do I have to overload so that > I get what I expect for all dict operations? You might consider just subclassing UserDict.DictMixin instead: http://docs.python.org/library/userdict.html#UserDict.DictMixin It implements the complete dict interface all in terms of provided __getitem__(), __setitem__(), __delitem__(), and keys() methods. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Cheers, > Daniel > From 5lvqbwl02 at sneakemail.com Wed Dec 24 14:16:59 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Wed, 24 Dec 2008 11:16:59 -0800 (PST) Subject: Doing set operation on non-hashable objects Message-ID: <3a87eb6a-13ff-4aea-8835-3a233cc6cfc4@w39g2000prb.googlegroups.com> Hi, I'm writing an application which is structured roughly as follows: "db" is a dict, where the values are also dicts. A function searches through db and returns a list of values, each of which is a dict as described above. I need to perform set operations on these lists (intersection and union) However the objects themselves are not hashable, and therefore can't be in a set, because they are dicts. I'm not sure how large each set will be, but the point is I'm trying to avoid anything looking like an O(n^2) algorithm, so I can't just use naive double-looping to check for intersection/union on a pair of lists. The only way I can think of to do this right is to hash the dicts by freezing them, turning them all into tuples, which can then be hashed. But this is a problem because more dicts might be nested inside. At any rate, I'd need to thaw them out when I'm done and turn them back into dicts, which seems complicated and annoying, and all this leads me to believe there is a better way. What I really need is a set of pointers, so at the end of the operation I have the actual objects pointed to. Can I somehow use the object IDs as set elements, then recreate a list with the actual objects they point to? How do you get the object back from an ID in python? thanks Michael From garlictrompet at gmail.com Wed Dec 17 06:03:24 2008 From: garlictrompet at gmail.com (Analog Kid) Date: Wed, 17 Dec 2008 16:33:24 +0530 Subject: regex problem .. In-Reply-To: References: <3b10c2060812150421y1c3e7da6ha1b72c736e2a20d4@mail.gmail.com> Message-ID: <3b10c2060812170303w1cd8ecdmad7c97c42e44f08@mail.gmail.com> Hi guys: Thanks for your responses. Points taken. Basically, I am looking for a combination of the following ... [^\w] and %(?!20) ... How do I do this in a single RE? Thanks for all you help. Regards, AK On Mon, Dec 15, 2008 at 10:54 PM, Steve Holden wrote: > Analog Kid wrote: > > Hi All: > > I am new to regular expressions in general, and not just re in python. > > So, apologies if you find my question stupid :) I need some help with > > forming a regex. Here is my scenario ... > > I have strings coming in from a list, each of which I want to check > > against a regular expression and see whether or not it "qualifies". By > > that I mean I have a certain set of characters that are permissible and > > if the string has characters which are not permissible, I need to flag > > that string ... here is a snip ... > > > > flagged = list() > > strs = ['HELLO', 'Hi%20There', '123123@#@'] > > p = re.compile(r"""[^a-zA-Z0-9]""", re.UNICODE) > > for s in strs: > > if len(p.findall(s)) > 0: > > flagged.append(s) > > > > print flagged > > > > my question is ... if I wanted to allow '%20' but not '%', how would my > > current regex (r"""[^a-zA-Z0-9]""") be modified? > > > The essence of the approach is to observe that each element is a > sequence of zero or more "character", where character is "either > letter/digit or escape." So you would use a pattern like > > "([a-zA-Z0-9]|%[0-9a-f][0-9a-f])+" > > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ibpet11 at gmail.com Tue Dec 30 09:55:49 2008 From: ibpet11 at gmail.com (ibpet11 at gmail.com) Date: Tue, 30 Dec 2008 06:55:49 -0800 (PST) Subject: Triple quoted string in exec function ? References: <495A253B.6010003@gmail.com> Message-ID: On Dec 30, 2:48?pm, Steve Holden wrote: > Stef Mientki wrote: > > hello, > > > I'm running scripts, with the execute function (Python 2.5), > > and it seems that triple quoted strings are not allowed. > > > Is there a workaround, > > or is this a fundamental problem of the exec-function ? > > If you think about it, it should be obvious that you can't surround a > string to be compiled with any of the quotes that appear inside the > string to be compiled. That's about the only limitation I am aware of. > > And, by the way, exec is a *statement*, not a function! > > >>> exec """print '''This is > > ... a long string''' > ... """ > This is > a long string > > > > regards > ?Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ hello, the message Steven sent you is ok to explain how to work with triple quote Cheers. From clp at rebertia.com Tue Dec 2 04:26:26 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 2 Dec 2008 01:26:26 -0800 Subject: How to sort a list of file paths In-Reply-To: <2F0A3D19CA15C143B0688EC94220748720D1F89A61@SE-EX007.groupinfra.com> References: <2F0A3D19CA15C143B0688EC94220748720D1F89A61@SE-EX007.groupinfra.com> Message-ID: <47c890dc0812020126p5e8ff750x91ff58e9fabd7d32@mail.gmail.com> On Tue, Dec 2, 2008 at 12:36 AM, Eriksson, John wrote: > Hi, > > > > This weekend I had some problems to get a list containing file paths to be > sorted in a way that I could use. > > > > I also found a thread in this mailing list ( > http://mail.python.org/pipermail/python-list/2007-April/433590.html ) and > realized that others might be interested in a solution. > > > > So... here is my five cents regarding file path sorting: > > > > Problem description: > > > > You have a list containing some file names: > > > >>>> file_list = ["File2.txt","File1.txt","File10.txt"] > > > > If you sort this list in the conventional way you end up with a result like: > > > >>>> file_list.sort() > >>>> print file_list > > ['File1.txt','File10.txt','File2.txt'] > > > > Solution: > > > > Sort the list by splitting alphas and digits in to groups and compare them > separately. > > > > import re > > def true_alphanum_cmp(a,b): > > aa = re.findall(r'\d |\D ', a) > > bb = re.findall(r'\d |\D ', b) > > for i in range(min(len(aa),len(bb))): > > if aa[i].isdigit() and bb[i].isdigit(): > > c = cmp(int(aa[i]),int(bb[i])) > > else: > > c = cmp(aa[i],bb[i]) > > if c!=0: > > return c > > return cmp(len(aa),len(bb)) > > > > file_list = ["File2.txt","File1.txt","File10.txt"] > > file_list.sort(true_alphanum_cmp) > > > > If the formatting in this mail is messed up you can find the example at > http://arainyday.se/notebook/true_alphanum_cmp.php > > > > All comments and improvements are welcome! Sounds like the issue discussed in the post on Coding Horror: http://www.codinghorror.com/blog/archives/001018.html It even links to another Python version of the algorithm. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > > > Best regards > > John Eriksson > > _________________________________________ > > > > Logica - Releasing your potential > > Tegsplan 2b > > 904 20 UME? > > Sweden > > > > T: +46 (0) 90 15 91 38 > > M: +46 (0) 70 366 16 77 > > E: john.eriksson at logica.com > > www.logica.se > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > From prologic at shortcircuit.net.au Thu Dec 18 18:54:15 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Dec 2008 09:54:15 +1000 Subject: Which sparse matrix package? In-Reply-To: References: <20081218231851.70dd91e2@Schlamber.localdomain> Message-ID: On Fri, Dec 19, 2008 at 8:52 AM, Robert Kern wrote: > pyspread *is* the spreadsheet application he is writing. Oh :) My bad :) --JamesMills From steve at holdenweb.com Thu Dec 11 23:40:32 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 11 Dec 2008 23:40:32 -0500 Subject: how to convert =?ISO-8859-1?Q?=27=5Cxf0=27_to_0xf0_=3F?= In-Reply-To: <1cb85265-1c36-4e4b-88f1-46b0ebae3dea@v5g2000prm.googlegroups.com> References: <1cb85265-1c36-4e4b-88f1-46b0ebae3dea@v5g2000prm.googlegroups.com> Message-ID: chengang.beijing at gmail.com wrote: > '\xf0' is the value read from a binary file, I need to change this > kinds strings to int for further processing... > if it is in C, then '\xf0' is an integer and it can be handled > directly, but in python, it is a string. > > and both int('10',16) and int('0x10',16) returns 16. > > Br, Chen Gang > > On Dec 12, 12:06 pm, Tommy Nordgren wrote: >> On Dec 12, 2008, at 4:48 AM, chengang.beij... at gmail.com wrote: >> >>> int('\xf0',16) doesn't work, any way to do that? >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> Should be int('10',16) >> or int('0x10',16) It seems that you want the integer value of a character you read in from a file. Is this correct? Note that '\xf0' is the interpreter's way of representing a one-character string whose only character has the hexadecimal value f0, because the actual character is not printable: the backslash has a special meaning in character string literals. Any one-character string, however, can be converted to the equivalent integer value using the ord() function. You can convert the other way using the chr() function: >>> ord('A') 65 >>> chr(65) 'A' >>> ord('\xf0') 240 >>> chr(240) '\xf0' >>> hex(240) '0xf0' >>> So just apply the ord() function to the character and you'll get its integer value! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From bruno.42.desthuilliers at websiteburo.invalid Thu Dec 18 11:12:13 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 18 Dec 2008 17:12:13 +0100 Subject: Is this pythonic? In-Reply-To: <66d058f9-cfe1-4b3c-ab8a-e6e88bb97770@m22g2000vbp.googlegroups.com> References: <66d058f9-cfe1-4b3c-ab8a-e6e88bb97770@m22g2000vbp.googlegroups.com> Message-ID: <494a761c$0$20035$426a34cc@news.free.fr> ipytest at gmail.com a ?crit : > x.validate_output(x.find_text(x.match_filename > (x.determine_filename_pattern(datetime.datetime.now())))) > > Is it even good programming form? functional programming addicts might say yes. But as far as I'm concerned, I find it a bit too nested... From sjmachin at lexicon.net Tue Dec 2 19:59:06 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 2 Dec 2008 16:59:06 -0800 (PST) Subject: problem with optparse References: Message-ID: <72745ddb-8997-4e97-a8ad-9bcab4aefe6b@c36g2000prc.googlegroups.com> On Dec 3, 11:28?am, Robert Kern wrote: > Neal Becker wrote: > > This example is right out of python library reference. ?What's wrong here? > > > import optparse > > > def store_value(option, opt_str, value, parser): > > ? ? setattr(parser.values, option.dest, value) > > > parser = optparse.OptionParser() > > parser.add_option("--foo", > > ? ? ? ? ? ? ? ? ? action="callback", callback=store_value, > > ? ? ? ? ? ? ? ? ? type="int", nargs=3, dest="foo") > > > (opt,args) = parser.parse_args ('--foo a b c'.split()) > > > [...] > > /usr/lib64/python2.5/optparse.pyc in _process_args(self, largs, rargs, values) > > ? ?1423 ? ? ? ? ? ? elif self.allow_interspersed_args: > > ? ?1424 ? ? ? ? ? ? ? ? largs.append(arg) > > -> 1425 ? ? ? ? ? ? ? ? del rargs[0] > > ? ?1426 ? ? ? ? ? ? else: > > ? ?1427 ? ? ? ? ? ? ? ? return ? ? ? ? ? ? ? ? ?# stop now, leave this arg in rargs > > > TypeError: 'str' object doesn't support item deletion > > Dunno. It works for me (i.e. I get the expected "error: option --foo: invalid > integer value: 'a'"). Have you tried it outside of IPython? > Works for me (Python 2.[456] in interactive mode, Windows XP). Also gives expected result with '--foo 12 34 56'. From sjmachin at lexicon.net Thu Dec 11 18:43:41 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 11 Dec 2008 15:43:41 -0800 (PST) Subject: list organization question References: <79587def-2112-48dd-bab2-95427a2dca8b@y1g2000pra.googlegroups.com> Message-ID: <9c89dd5b-5edb-4d9d-b1f9-333aeb4743b6@r15g2000prd.googlegroups.com> On Dec 12, 10:17?am, Robocop wrote: > I'm currently trying something along the lines of a sort.compare, but > as i'm never sure how many mini-lists i'll end up with, i'm not sure > how exactly to begin. ?Maybe something like a C vector, i.e. a list of > pointers to other lists? ?Or more specifically, compare dates in my > list, push that into some empty dates[], then do something along the > lines of for looping over dates to create subset lists, and nesting > some more compares within these lists to further sort the data by id. > Sound crazy or plausible? Crazy, yes. Plausible that you might attempt it, yes. Learn about dictionaries. They're built in; you don't need to import them. E.g. [OTTOMH; untested] id_map = {} # maps (unique) id to the object with that id date_map = {} # maps date to a list of ids whose objects have that date for o in olist: if o.id in id_map: raise Exception("duplicate id: %r" % o.id) id_map[o.id] = o if o.date not in date_map: date_map[o.date] = [] date_map[o.date].append(o.id) From bdesth.quelquechose at free.quelquepart.fr Mon Dec 8 16:18:56 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 08 Dec 2008 22:18:56 +0100 Subject: Public imports In-Reply-To: <66ecdd96-38dd-4054-8009-e145c0a78316@o40g2000prn.googlegroups.com> References: <9623b0a3-7053-41f1-b116-0cd5e54f39e9@v13g2000vbb.googlegroups.com> <493d1ec0$0$32048$426a34cc@news.free.fr> <66ecdd96-38dd-4054-8009-e145c0a78316@o40g2000prn.googlegroups.com> Message-ID: <493d9cf8$0$27349$426a74cc@news.free.fr> M?rcio Faustino a ?crit : > So, no chance of doing this: > > # "A.py" > from __future__ import division, with_statement > > # "B.py" > from A import * > print 1 / 2 > > ...and printing 0.5, right? Nope, but for totally unrelated reasons (cf Skip's anwer). OTHO, this is valid: # foo.py def bar(): return "bar" # A.py from foo import bar # B.py from A import bar print bar() FWIW, this is often used in packages __init__.py to hide the package's internal organization (or when a module starts to grow too big and has to be refactored as a package without breaking client code). HTH From geekmail at usenot.de Thu Dec 4 14:45:25 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Thu, 4 Dec 2008 20:45:25 +0100 Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> Message-ID: <20081204204525.414db889@usenot.de> On Thu, 4 Dec 2008 11:52:38 -0600 skip at pobox.com wrote: > > >>> As you have probably guessed: nothing changed here. > >>> Also see:http://www.python.org/dev/peps/pep-0666/ > >> > >> What? Do you mean it's possible to mix tabs and spaces still? > >> Why? > > Daniel> Why not? > > Because it has historically been a source of errors in a mixed > development environment (people using text editors with different tab > stops). Better to not allow them to be mixed. > Whenever has it been a pythonic ideal to "not allow" stuff? You get warnings. Everything else is up to you. /W -- My real email address is constructed by swapping the domain with the recipient (local part). From glenn.chappell at gmail.com Mon Dec 22 21:22:47 2008 From: glenn.chappell at gmail.com (Glenn G. Chappell) Date: Mon, 22 Dec 2008 18:22:47 -0800 (PST) Subject: python3 urlopen(...).read() returns bytes References: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> <5496b34d-7ce4-4281-9f01-aed12dab9fd3@f33g2000vbf.googlegroups.com> Message-ID: Okay, so I guess I didn't really *get* the whole unicode/text/binary thing. Maybe I still don't, but I think I'm getting closer. Thanks to everyone who replied. On Dec 22, 1:41?pm, ajaksu wrote: > On Dec 22, 8:25?pm, Christian Heimes wrote: > That said, a "decode to declared HTTP header encoding" version of > urlopen could be useful to give some users the output they want (text > from network io) or to make it clear why bytes is the safe way. Sounds like a great idea. More to the point, it sounds like it's pretty much a necessary idea. Consider: reading a web page is an easy one-liner. Now, no one is going to write that one-liner, and then spend 20 lines trying to get the Content-Type and encoding figured out. Instead we're all going to do it the short, easy, *wrong* way. So every program in the world that uses urlopen gets to have the same bug. Not good. The *right* way needs to be the *easy* way. -GGC- From Russ.Paielli at gmail.com Thu Dec 18 21:23:11 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Thu, 18 Dec 2008 18:23:11 -0800 (PST) Subject: Factoring Polynomials References: <919062f9-765e-4279-aa26-2c130d4deacf@o4g2000pra.googlegroups.com> Message-ID: On Dec 18, 6:17?pm, Collin D wrote: > On Dec 18, 6:12?pm, Collin D wrote: > > > > > On Dec 18, 11:37?am, collin.da... at gmail.com wrote: > > > > I am trying to write a simple application to factor polynomials. I > > > wrote (simple) raw_input lines to collect the a, b, and c values from > > > the user, but I dont know how to implement the quadratic equation > > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > > into python. Any ideas? > > > I completed the code: > > > #import > > from math import sqrt > > > # collect data > > a = float(raw_input('Type a value: ')) > > b = float(raw_input('Type b value: ')) > > c = float(raw_input('Type c value: ')) > > > # create solver > > def solver(a,b,c): > > ? ? if b**2 - 4*a*c < 0: > > ? ? ? ? return 'No real solution.' > > ? ? else: > > ? ? ? ? sol1 = -1 * b + (sqrt(b**2 - 4*a*c)) / 2*a > > ? ? ? ? sol2 = -1 * b - (sqrt(b**2 - 4*a*c)) / 2*a > > ? ? ? ? return (sol1, sol2) > > > # execute > > print solver(a,b,c) > > > Thanks to everyone who helped... > > This really expanded my knowledge on some of the mathematical > > functions in Python. > > UPDATE: > ' > > #import > from math import sqrt > > # collect data > a = float(raw_input('Type a value: ')) > b = float(raw_input('Type b value: ')) > c = float(raw_input('Type c value: ')) > > # create solver > def solver(a,b,c): > ? ? if b**2 - 4*a*c < 0: > ? ? ? ? return 'No real solution.' > ? ? else: > ? ? ? ? sol1 = (-1 * b + (sqrt(b**2 - 4*a*c))) / 2*a > ? ? ? ? sol2 = (-1 * b - (sqrt(b**2 - 4*a*c))) / 2*a > ? ? ? ? return (sol1, sol2) > > # execute > print solver(a,b,c) You need to put your denominator, 2*a, in parens. The way it stands, you are dividing by 2, then multiplying by a. That's not what you want. Also, for better style, I suggest you compute the discriminanat once and store it for reuse rather than repeating the expression three times. From steve at REMOVE-THIS-cybersource.com.au Mon Dec 1 18:00:23 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 01 Dec 2008 23:00:23 GMT Subject: end of print = lower productivity ? References: <757b4e03-7d13-4758-85c4-f5224ee9853b@j35g2000yqh.googlegroups.com> <21d250f9-1477-450e-9587-c4b28d08ea00@t3g2000yqa.googlegroups.com> <981d3e99-d2b4-4455-a52a-e906bd0fe7c4@r36g2000prf.googlegroups.com> <4931D571.8070007@tim.thechases.com> <1228032887.6627.53.camel@lieryan-laptop> Message-ID: <01446462$0$20670$c3e8da3@news.astraweb.com> On Mon, 01 Dec 2008 09:46:43 -0600, Tim Chase wrote: >> For a proof, let's see what Google has to say about this: "Windows text >> editor". Vim is on page 3, near the turning point where nobody is >> talking about text-editor anymore and more about text-editor reviews. >> Even worse is Emacs, on page 6, after many other popular text-editors >> have been mentioned several times. > > That's a pretty malformed "proof" You're right, it is not "proof", but it is damn good evidence that vim has got a small mindshare among the general Windows-only text editor using population. > However, if you want to play that game, vim.org appears on page #1 of > > http://www.google.com/search?q=best+text+editor Is that prefixed by "not even close to"? *grin* > Use what editor works for you -- but if evolution in the language's > features makes difficulties for you but not for users of other editors, > it's your editor that's the problem, not the language. Well, maybe. I think it is quite legitimate to say that APL is the problem, not the lack of good editors (not to mention keyboards!) for all the weird special characters it uses. But in context, I agree with you. -- Steven From chengang.beijing at gmail.com Thu Dec 11 22:48:50 2008 From: chengang.beijing at gmail.com (chengang.beijing at gmail.com) Date: Thu, 11 Dec 2008 19:48:50 -0800 (PST) Subject: =?windows-1252?Q?how_to_convert_=91=5Cxf0=27_to_0xf0_=3F?= Message-ID: int('\xf0',16) doesn't work, any way to do that? From rt8396 at gmail.com Sat Dec 20 18:44:47 2008 From: rt8396 at gmail.com (r) Date: Sat, 20 Dec 2008 15:44:47 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> <59153e28-bf86-4158-96d9-23aa5b9f0205@j35g2000yqh.googlegroups.com> <7889a362-d96e-4f1f-a66b-ef52b9cdb047@q26g2000prq.googlegroups.com> Message-ID: <85f91606-b589-425d-9636-4636c8ccbc4f@r34g2000vbp.googlegroups.com> Thanks, i understand. Maybe some of the pro "new syntax" guys will show a translation From cjw at ncf.ca Fri Dec 19 19:35:20 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Fri, 19 Dec 2008 19:35:20 -0500 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> Message-ID: Steve Holden wrote: > Thomas Heller wrote: >> Mark Summerfield schrieb: >>> Just a follow-up to say that the book has now been published in the >>> U.S. >>> It is now in stock at InformIT, and should reach other stores, e.g., >>> Amazon, in a week or so. >>> >>> Also, the introduction, the first few pages of the first chapter, the >>> whole of chapter 12 (regular expressions), and the index are now >>> available for free download in a PDF from here: >>> http://www.informit.com/store/product.aspx?isbn=0137129297 >> Question from a non-native english speaker: is this now valid english? >> >> "One of Python???s great strengths" >> ^ >> "and also teaches Python???s functional programming features" >> ^ >> "The book???s approach is wholly practical" >> ^ > It always has been valid English. The apostrophe is only omitted from > personal pronouns (hers, its, and so on). > > regards > Steve What is the subject of "teaches"? I have no problem with the second sentence. Colin W. From enleverlesX.XmcX at XmclaveauX.com Sat Dec 13 02:39:43 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sat, 13 Dec 2008 08:39:43 +0100 Subject: ActivePython 2.6.1.1 and 3.0.0.0 released! In-Reply-To: <58cd9ea1-9cf5-4c90-81ba-411774a878b7@o4g2000pra.googlegroups.com> References: <58cd9ea1-9cf5-4c90-81ba-411774a878b7@o4g2000pra.googlegroups.com> Message-ID: <494368d9$0$845$ba4acef3@news.orange.fr> Hi! M. Hammond said (wrote) said that the work is enormous, because modifications of the C architecture of Python 3 was largely modified. (sorry for my bad english) -- Michel Claveau From shangach at gmail.com Wed Dec 3 15:15:11 2008 From: shangach at gmail.com (ShanMayne) Date: Wed, 3 Dec 2008 12:15:11 -0800 (PST) Subject: Numpy record array - field names for all dimensions Message-ID: <74c0e6f0-8caf-4e06-a162-1d107977ff3c@d32g2000yqe.googlegroups.com> Greetings All I am seeking to represent datasets where each data element is the calculated result from several (4 for now) other data types. A matrix- like (in the general mathematical sense) seems logical, where the intersection of each of the 4 values (from different data sets) holds the value derived from those 4 values here serving as indexes. So, each matrix/array element is associated with 4 fields. eg: matrix element/output value = 24.235 --> 'Formula' = 'C12H24O2N2' 'Solvent' = 'Acetonitrile' 'fragmentation_method' = 'CID' 'resolution' = 'unit' ideally I would like to call the output value by indexing the matrix with the input information. eg: matrix['C12H24O2N2']['Acetonitrile']['CID']['unit'] = 24.235 Numpy's record arrays seemingly don't allow all dimensions to carry field names. ie. each column/row carrying a label. Instead fieldname usage appears to create a "new dimension" as denoted by square brackets. eg: pixel_matrix = array([[(1,2,3), (4,5,6)], [(7,8,9), (10,11,12)]], [('r',float32),('g',float32),('b',float32)]) Q: Can anyone tell me if the sort of data structuring I seek can be done with Numpy record arrays or, if not, can you recommend a more suitable module? Great & Glowing Thanks! From marko.loparic at gmail.com Fri Dec 26 17:50:56 2008 From: marko.loparic at gmail.com (Marko Loparic) Date: Fri, 26 Dec 2008 23:50:56 +0100 Subject: looking for a consultant for the design of an interface for our mathematical models Message-ID: Hi, I am looking for someone that could help us to design (perhaps also to implement) a user interface (GUI + repository of data) for our mathematical models. I work for a company in the energy sector. Currently in our department we have 5 different mathematical models using different GUIs and excel hacks to allow users to feed the data and get results. We would like to have a single, powerful, user-friendly interface for all those models. We need the help of an experienced and inventive software designer to help us to choose the technology to use and to make the design (possibly also the implementation) of the tool. Of course we would like to reuse existing tools whenever possible. We propose to pay for one or two days of consultancy when we will describe our needs and discuss the possible design choices. Depending on the conclusions we get we can work further together. We are located near Brussels. Usage of python is not a request but it is a natural choice since it is the main language we use. Any indication on how I can find the good person or company for the job would be of great help! Thank you very much! Marko PS. This message was already posted to scipy list. Someone suggested me to contact Enthought which seems to be a very good idea. But we will probably look for advices from different professionals to make a decision. From Scott.Daniels at Acm.Org Fri Dec 5 12:34:17 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 05 Dec 2008 09:34:17 -0800 Subject: ANN: Shed Skin 0.0.30, an experimental (restricted-)Python-to-C++ Compiler In-Reply-To: <8180ef690812050324j1dc6c570ib9644137bbc193c6__44477.3383591839$1228498143$gmane$org@mail.gmail.com> References: <8180ef690812050324j1dc6c570ib9644137bbc193c6__44477.3383591839$1228498143$gmane$org@mail.gmail.com> Message-ID: <49396619.2090700@Acm.Org> Mark Dufour wrote: > Hi all, > > I have just released version 0.0.30 of Shed Skin, ... Normally, including a link is a good idea. --Scott David Daniels Scott.Daniels at Acm.Org From dfnsonfsduifb at gmx.de Tue Dec 16 23:51:45 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Wed, 17 Dec 2008 05:51:45 +0100 Subject: Does Python3 offer a FrozenDict? In-Reply-To: References: Message-ID: <14dm16x3n6.ln2@joeserver.homelan.net> bearophileHUGS at lycos.com schrieb: > Johannes Bauer: >> is there anything like a frozen dict in Python3, so I could do a >> foo = { FrozenDict({"a" : "b"}): 3 } > > You can adapt this code to Python3 (and post a new recipe? It may be > positive to create a new section of the Cookbook for Py3 only): > http://code.activestate.com/recipes/414283/ Well, yes, I've been using something like that so far - but I think this is functionality the language should provide - therefore I thought maybe Python3 included something like this already. Regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From mh at pixar.com Thu Dec 11 18:57:12 2008 From: mh at pixar.com (mh at pixar.com) Date: Thu, 11 Dec 2008 23:57:12 GMT Subject: var or inout parm? References: <493cda2a$0$17080$426a34cc@news.free.fr> <47c890dc0812080057r6d117bbcic377cb96de52d973@mail.gmail.com> Message-ID: J. Clifford Dyer wrote: > Just google for call-by-object, and ignore the hell out of that thread. Now I've got to go read it! ;-) -- Mark Harrison Pixar Animation Studios From rhodri at wildebst.demon.co.uk Thu Dec 11 18:31:13 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Thu, 11 Dec 2008 23:31:13 -0000 Subject: newbie question: if var1 == var2: In-Reply-To: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> Message-ID: On Thu, 11 Dec 2008 19:49:23 -0000, Steve Holden wrote: > Kirk Strauser wrote: >> At 2008-11-29T04:02:11Z, Mel writes: >> >>> You could try >>> >>> for item in fname: >>> item = item.strip() >> >> This is one case where I really miss Perl's "chomp" function. It >> removes a >> trailing newline and nothing else, so you don't have to worry about >> losing >> leading or trailing spaces if those are important to you. > > ... and it's so hard to write > > item = item[:-1] Tsk. That would be "chop". "chomp" would be if item[-1] == '\n': item = item[:-1] :-) -- Rhodri James *-* Wildebeeste Herder to the Masses From mail at microcorp.co.za Thu Dec 4 23:27:12 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 5 Dec 2008 06:27:12 +0200 Subject: time.sleep() and Tkinter after()? References: <03613d37-ca4f-4962-bce2-eea0a3f65952@r15g2000prd.googlegroups.com> Message-ID: <000701c95691$e71aa6e0$0d00a8c0@hendrik> "Davy" wrote: >Although I don't understand your explanation very well(I guess >maybe .after() re-schedule is better than .sleep unresponsive in GUI >application?)I will take it as a golden rule. I did not in fact try to explain it - I was trying to get you to think a bit wider, as that way you would get more benefit than just being given a solution. As for taking what I say as a golden rule:- If you hang around this group for long enough, you will learn to never take what I say as gospel - I often pull the piss - be warned! 8<----------------------------------- >Yeah, I forgot to *delete* the rectangle object I generate before. >One more question, besides create/delete method, can I just create two >rectangles (one black/one white), and assign two tags to these two >rectangles, and place rectangle by just using tags(that is, can I >place one object on several places of the canvas)? You can redraw it to make it look different and position it on another place, but I have never seen one thing in two places before. If it is possible I don't know how to do it. Now if it were a class, you could have multiple instances, but I have only ever seen one thing, one picture... - Hendrik From nospam at nospam.com Sun Dec 21 14:41:16 2008 From: nospam at nospam.com (Gilles Ganault) Date: Sun, 21 Dec 2008 20:41:16 +0100 Subject: Are Django/Turbogears too specific? Message-ID: Hi I'd like to rewrite a Web 2.0 PHP application in Python with AJAX, and it seems like Django and Turbogears are the frameworks that have the most momentum. I'd like to use this opportunity to lower the load on servers, as the PHP application wasn't built to fit the number of users hammering the servers now. I'm concerned, though, that these frameworks they may be too specific to the tasks they were originally developped for (news articles, AFAIK). Do you think I should just use eg. CherryPy and some basic AJAX? Thank you for any feedback. From mmanns at gmx.net Thu Dec 18 17:18:51 2008 From: mmanns at gmx.net (Martin Manns) Date: Thu, 18 Dec 2008 23:18:51 +0100 Subject: Which sparse matrix package? Message-ID: <20081218231851.70dd91e2@Schlamber.localdomain> Hi: I am writing a spreadsheet application in Python http://pyspread.sf.net which currently uses numpy.array for: + storing object references (each array element corresponds to one grid cell) + slicing (read and write) + mapping from/to smaller numpy.array + searching and replacing + growing and shrinking + transpose operation. While fast and stable, this is really memory inefficient for large grids (i.e. larger than 1E7 rows and columns), so that I am looking into dicts and sparse matrices. The dict that I tried out is of the type: {(1,2,3): "2323", (1,2,545): "2324234", ... } It is too slow for my application when it grows. One slicing operation with list comprehensions takes about 1/2 s on my computer for 1E6 elements. Therefore, I looked into sparse matrices and found scipy.sparse and pysparse. I tried out both lil_matrix objects. (I wrote a wrapper that turns them into Python object arrays.) scipy.sparse.lil_matrix allowed __getitem__ slicing only for one of the dimensions and used much memory when increasing the number of columns above 1E7. pysparse.spmatrix.ll_mat was faster, uses less space and allows slicing for both dimensions. However, its methods are not documented well and I am not able to compile it in Debian testing due to some g77 dependencies. Even though the deb package works well, I am concerned about having a dependency to a problematic package. Now my questions: Is there a better suited / maintained module for such sparse matrices (or multi-dim arrays)? Should I use another type of matrix in scipy.sparse? If yes which? Does a different data-structure suit my above-stated needs better? Best Regards Martin From basu at archlinux.us Tue Dec 30 01:16:25 2008 From: basu at archlinux.us (member Basu) Date: Tue, 30 Dec 2008 01:16:25 -0500 Subject: Get a list of functions in a file In-Reply-To: References: Message-ID: Thanks for all your replies, but the thing is I want to get the list of functions in that file itself, not by importing it as a module. I've decided to go with a class-based approach due to a number of other reasons, but I'm still interested in a way to get function name in that file itself. Thanks, Basu -------------- next part -------------- An HTML attachment was scrubbed... URL: From fakeaddress at nowhere.org Tue Dec 2 19:34:40 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 02 Dec 2008 16:34:40 -0800 Subject: unicode and hashlib In-Reply-To: <6qydnbFh7MOAH6nUnZ2dnUVZ_orinZ2d@pdx.net> References: <8af54b5f-d21b-4794-9bce-afc96ea4db74@j11g2000yqg.googlegroups.com> <6qydnbFh7MOAH6nUnZ2dnUVZ_orinZ2d@pdx.net> Message-ID: Scott David Daniels wrote: > Bryan Olson wrote: >> ... I think that's good behavior, except that the error message is likely >> to end beginners to look up the obscure buffer interface before they >> find they just need mystring.decode('utf8') or bytes(mystring, 'utf8'). > Oops, careful here (I made this mistake once in this thread as well). > You _decode_ from unicode to bytes. The code you quoted doesn't run. Doh! I even tested it with .encode(), then wrote it wrong. Just in case anyone Googles the error message and lands here: If you are working with a Python str (string) object and get, TypeError: object supporting the buffer API required Then you probably want to encode the string to a bytes object, and UTF-8 is likely the encoding of choice, as in: mystring.encode('utf8') or bytes(mystring, 'utf8') Thanks for the correction. -- --Bryan From clp at rebertia.com Tue Dec 23 01:00:57 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 22 Dec 2008 22:00:57 -0800 Subject: using subprocess module in Python CGI In-Reply-To: References: Message-ID: <47c890dc0812222200n26183303x717082b94010d250@mail.gmail.com> On Mon, Dec 22, 2008 at 2:02 AM, ANURAG BAGARIA wrote: > Hello, > > I am a Python Newbie and would like to call a short python script via > browser using a CGI script, but initially I am trying to call the same > python script directly through python command line. The script intends to > perform a few command line in a pipe and I have written the script (a short > one) as follows. > > #!/usr/bin/python > > import cgi, string, os, sys, cgitb, commands, subprocess > import posixpath, macpath > #file = "x.tar.gz" > #comd = "tar -xf %s" % (file) > #os.system(comd) > #commands.getoutput('tar -xf x.tar.gz | cd demo; cp README ../') > comd = [\ > "tar -xf x.tar.gz", \ > "cd demo", \ > "cp README ../", \ > ] > outFile = os.path.join(os.curdir, "output.log") > outptr = file(outFile, "w") > errFile = os.path.join(os.curdir, "error.log") > errptr = file(errFile, "w") > retval = subprocess.call(comd, 0, None, None, outptr, errptr) > errptr.close() > outptr.close() > if not retval == 0: > errptr = file(errFile, "r") > errData = errptr.read() > errptr.close() > raise Exception("Error executing command: " + repr(errData)) > > > but after trying to execute this independently, I get the following error > which I am unable to interpret : > > Traceback (most recent call last): > File "process.py", line 18, in > retval = subprocess.call(comd, 0, None, None, outptr, errptr) > File "/usr/lib/python2.5/subprocess.py", line 443, in call > return Popen(*popenargs, **kwargs).wait() > File "/usr/lib/python2.5/subprocess.py", line 593, in __init__ > errread, errwrite) > File "/usr/lib/python2.5/subprocess.py", line 1135, in _execute_child > raise child_exception There should be at least one more line in this traceback, and that line is the most important one. People will need that line to help you with your problem. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From john.eriksson at logica.com Tue Dec 2 03:36:02 2008 From: john.eriksson at logica.com (Eriksson, John) Date: Tue, 2 Dec 2008 09:36:02 +0100 Subject: How to sort a list of file paths Message-ID: <2F0A3D19CA15C143B0688EC94220748720D1F89A61@SE-EX007.groupinfra.com> Hi, This weekend I had some problems to get a list containing file paths to be sorted in a way that I could use. I also found a thread in this mailing list ( http://mail.python.org/pipermail/python-list/2007-April/433590.html ) and realized that others might be interested in a solution. So... here is my five cents regarding file path sorting: Problem description: You have a list containing some file names: >>> file_list = ["File2.txt","File1.txt","File10.txt"] If you sort this list in the conventional way you end up with a result like: >>> file_list.sort() >>> print file_list ['File1.txt','File10.txt','File2.txt'] Solution: Sort the list by splitting alphas and digits in to groups and compare them separately. import re def true_alphanum_cmp(a,b): aa = re.findall(r'\d |\D ', a) bb = re.findall(r'\d |\D ', b) for i in range(min(len(aa),len(bb))): if aa[i].isdigit() and bb[i].isdigit(): c = cmp(int(aa[i]),int(bb[i])) else: c = cmp(aa[i],bb[i]) if c!=0: return c return cmp(len(aa),len(bb)) file_list = ["File2.txt","File1.txt","File10.txt"] file_list.sort(true_alphanum_cmp) If the formatting in this mail is messed up you can find the example at http://arainyday.se/notebook/true_alphanum_cmp.php All comments and improvements are welcome! Best regards John Eriksson _________________________________________ Logica - Releasing your potential Tegsplan 2b 904 20 UME? Sweden T: +46 (0) 90 15 91 38 M: +46 (0) 70 366 16 77 E: john.eriksson at logica.com www.logica.se -------------- next part -------------- An HTML attachment was scrubbed... URL: From craig_farrow at sil.org Fri Dec 12 03:49:00 2008 From: craig_farrow at sil.org (Craig Farrow) Date: Fri, 12 Dec 2008 16:49:00 +0800 Subject: [Python.NET] Where does the clr in IronPython look the dll In-Reply-To: References: Message-ID: <4942257C.407@sil.org> The dll needs to be on the Python path (sys.path). You can either add to the path with sys.path.append("c:\....") or put your dll in a folder in the Python site-packages directory and add a .pth file (for Python.NET, but not IronPython -- it doesn't recognise the .pth files). Regards, Craig. 3/12/2008 9:20 p.m. d?, navneet khanna wrote: > Hello Everybody > > I am trying to import dll with clr.AddReference("TCdll") > I am getting the following error. > > Traceback (most recent call last): > File "", line 1, in > clr.AddReference("TCdll") > FileNotFoundException: Unable to find assembly 'TCdll'. > at Python.Runtime.CLRModule.AddReference(String name) > > I have loaded the dll in system32 folder. Have I loaded the dll at the > right place or do I need to place it anywhere else? > Waiting for your replies. > > Regards > Navneet > ------------------------------------------------------------------------ > > _________________________________________________ > Python.NET mailing list - PythonDotNet at python.org > http://mail.python.org/mailman/listinfo/pythondotnet From icanbob at gmail.com Sun Dec 14 07:28:01 2008 From: icanbob at gmail.com (bobicanprogram) Date: Sun, 14 Dec 2008 04:28:01 -0800 (PST) Subject: problem adding custom module in cgi script References: Message-ID: On Dec 11, 8:03 pm, bobicanprogram wrote: > Problem: > > Apache server serving an HTML file to a Firefox Browser containing a > form and > a CGI python CGI script. HTML works fine, meat of the CGI script works > fine > except that when a home grown and ordinarily functional module that is > to be > imported is added, the interpreter cannot find it. > > Running cgi.test() reveals that PYTHONPATH is correctly set. Still > nada. > Adding the sys.* stuff still nada. > > Items: Firefox Browser, Apache server, Python 2.5. > > ======================================= > > The CGI script: > #! /usr/bin/python > > import cgi > #cgi.test() > import sys > > #sys.path.append("/myModulePath") > #sys.path.insert(0, "/myModulePath") > import myModule **************** Problem here ******************** > > =========================================== > httpd error_log excerpt: > [Wed Dec 10 13:39:46 2008] [error] [client 192.168.1.1] Traceback > (most recent > call last):, referer:http://192.168.1.1/nee.html > [Wed Dec 10 13:39:46 2008] [error] [client 192.168.1.1] > File "/var/www/cgi-bin/noo.py", line 11, in , referer:http://192.168.1.1/nee.html > [Wed Dec 10 13:39:46 2008] [error] [client 192.168.1.1] import > myModule, > referer:http://192.168.1.1/nee.html > [Wed Dec 10 13:39:46 2008] [error] [client 192.168.1.1] ImportError: > No module > named myModule, referer:http://192.168.1.1/nee.html > > ============================================= > Relevant lines from http.conf: > ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" > SetEnv PYTHONPATH /myModulePath > PassEnv PYTHONPATH > > Thanks in advance for any pointers. > > bob Solution found! The apache web server is running on a Linux box equipped with SELinux which was preventing apache from opening the required modules according to the SELinux troubleshoot browser which is available from the main menu under the administration moniker. Apache's error_log describes the problem as one of not being able to locate the said modules for import. This is misleading to say the least. Adjusting SELinux to allow this is the solution to the problem; this can be done under 'main menu/administration/ SELinux Management bob From sapanapappu at gmail.com Fri Dec 19 06:59:37 2008 From: sapanapappu at gmail.com (sapanapappu at gmail.com) Date: Fri, 19 Dec 2008 03:59:37 -0800 (PST) Subject: 15000$ per month Message-ID: 1500$ per month? MAKE MONEY 24 HOUR, THE REAL ONLINE JOB, http://labnol.homestead.com/ From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 15 03:14:39 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 15 Dec 2008 09:14:39 +0100 Subject: Looking for the best way to translate an idiom In-Reply-To: References: Message-ID: <494611c2$0$21934$426a34cc@news.free.fr> Aahz a ?crit : > In article , > James Stroud wrote: >> In case its not obvious: > > Ah, so that's where Bruno's extra apostrophe came from! ;-) Err... Which one exactly ? > > (Sorry about the spelling flame, but seeing three posts in quick > succession with incorrect spelling of its/it's pushed me into making a > public comment.) From bruno.42.desthuilliers at websiteburo.invalid Wed Dec 10 10:51:42 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 10 Dec 2008 16:51:42 +0100 Subject: "as" keyword woes In-Reply-To: <66ea8282-05cc-4d24-8447-1df5e0e6b9f6@40g2000prx.googlegroups.com> References: <66ea8282-05cc-4d24-8447-1df5e0e6b9f6@40g2000prx.googlegroups.com> Message-ID: <493fe580$0$1726$426a74cc@news.free.fr> Lie a ?crit : > On Dec 7, 2:38 am, "Warren DeLano" wrote: (snip) >> As someone somewhat knowledgable of how parsers work, I do not >> understand why a method/attribute name "object_name.as(...)" must >> necessarily conflict with a standalone keyword " as ". It seems to me >> that it should be possible to unambiguously separate the two without >> ambiguity or undue complication of the parser. >> (snip) > > And let things like: > > filelike.print('lpt') # python 2.6 > zipper.with('7z') > failure.try(alternative) > executecodeobject.if(True) > onfailure.break() > > ? As far as I'm concerned, I'd find this perfectly acceptable - there's no possible confusion here. Now this wouldn't be very practical, since you'd have to define the functions outside the class (with a valid identifier) then bind them to the class. But this is probably not going to happen anyway... From geekmail at usenot.de Tue Dec 2 15:09:30 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Tue, 2 Dec 2008 21:09:30 +0100 Subject: Reverse zip() ? Message-ID: <20081202210930.2ac88ec6@usenot.de> Hi all, we all know about the zip builtin that combines several iterables into a list of tuples. I often find myself doing the reverse, splitting a list of tuples into several lists, each corresponding to a certain element of each tuple (e.g. matplotlib/pyplot needs those, rather than lists of points). This is of course trivial to do via iteration or listcomps, BUT, I was wondering if there is a function I don't know about that does this nicely? redards /W -- My real email address is constructed by swapping the domain with the recipient (local part). From steve at holdenweb.com Tue Dec 30 16:41:44 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Dec 2008 16:41:44 -0500 Subject: embedding python in wxpython In-Reply-To: <191280cf-ecf9-4135-9737-9923061855d1@t39g2000prh.googlegroups.com> References: <191280cf-ecf9-4135-9737-9923061855d1@t39g2000prh.googlegroups.com> Message-ID: 5lvqbwl02 at sneakemail.com wrote: > Hi, I've looked around for a way to allow a python console from within > a wxPython application, but have only found stuff on embedded/ > extending python with C/C++ or wxWidgets in C++, but not wxPython. > > Is this easy to do? Can someone point me in the right direction? > > Also, typically when you embed a scripting language into a larger > application, how do you get the console environment to share data with > the larger application? > > For instance, if the application has some gui stuff (for example > clicking on a object and dragging it around), how do you get > "object.select(x,y)" to print out on the console, and vice-versa: the > object gets selected if the user types "object.select(x,y)"? > > I'd like the console to be a bidirectional representation of what's > going on in the gui, plus a general purpose evaluation environment > where you can manipulate application data via some api which is > automatically exposed to the console when the application opens up. > > I'm looking for high-level hints/strategies/directions. > I seem to remember you can create your wxApp with an argument of True or False. One of those settings creates a window containing any output to sys.stderr, if I remember rightly. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From gnewsg at gmail.com Mon Dec 29 02:29:58 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sun, 28 Dec 2008 23:29:58 -0800 (PST) Subject: How to "kill" orphaned threads at program exit References: Message-ID: <02fab23a-a7e5-46c9-a805-e4d5a792d784@n33g2000pri.googlegroups.com> On 28 Dic, 18:47, Roy Smith wrote: > In article > , > "Giampaolo Rodola'" wrote: > > > Hi, > > I know that it's not possible to "kill" threads but I'm wondering if > > does exist some workaround for my problem. > > I have a test suite which does a massive usage of threads. > > Sometimes happens that one test fails, the test suite keeps running > > until the end, and when it's finished the program hangs on and the > > only way to stop is to kill it manually. > > You don't say how you're creating your threads, so I'll assume you're using > threading.Thread(). After creating each thread, and before calling start() > on it, call setDaemon(True). Apparently it doesn't make any difference. A curious thing is that by putting a "print 1" as last instruction the pending threads get killed and the program exits (Windows XP sp3 32 bit). --- Giampaolo http://code.google.com/p/pyftpdlib/ From steve at holdenweb.com Fri Dec 19 23:04:58 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 19 Dec 2008 23:04:58 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <2d53cd36-52b0-4a1a-913d-0c545cfadc23@v15g2000vbb.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c4ef2$0$20656$c3e8da3@news.astraweb.com> <2d53cd36-52b0-4a1a-913d-0c545cfadc23@v15g2000vbb.googlegroups.com> Message-ID: r wrote: > Thanks Steven, > We need a real Pepsi challenge here to show the insignificance of this > change. I am not against change. But when we lose something as - > compact- as %formating i'm going to want to see a damn good reason for > it! Especially when this breaks code, and the "French Connection" is > not good enough reason for me :) > > Christian said this was not going to be depreciated until 3.2, but > that still puts the accepted way on the chopping block. If Python is so important to you it's a pity you haven't been playing any active role in its development. Do you expect the developers to be psychic? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From gagsl-py2 at yahoo.com.ar Mon Dec 29 04:51:58 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Dec 2008 07:51:58 -0200 Subject: Get a list of functions in a file References: Message-ID: En Mon, 29 Dec 2008 05:26:52 -0200, member Basu escribi?: > I'm putting some utility functions in a file and then building a simple > shell interface to them. Is their some way I can automatically get a > list of > all the functions in the file? I could wrap them in a class and then use > attributes, but I'd rather leave them as simple functions. Such file is called a "module" in Python. Just import it (I'll use glob as an example, it's a module in the standard library, look for glob.py). To get all names defined inside the module, use the dir() function: py> import glob py> dir(glob) ['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'f nmatch', 'glob', 'glob0', 'glob1', 'has_magic', 'iglob', 'magic_check', 'os', 'r e', 'sys'] Note that you get the names of all functions defined inside the module (fnmatch, glob, glob0, has_magic...) but also many other names (like os, re, sys that are just imported modules, and __all__, __doc__, etc that are special attributes) If you are only interested in functions, the best way is to use inspect: py> import inspect py> inspect.getmembers(glob, inspect.isfunction) [('glob', ), ('glob0', ), ('glob1', ), ('has_magic', ), ('iglob', )] Modules are covered in the Python tutorial here and the inspect module is documented here -- Gabriel Genellina From castironpi at gmail.com Sat Dec 20 21:17:54 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 20 Dec 2008 18:17:54 -0800 (PST) Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> <7e23a789-84c3-47b9-b040-ca7dd062d058@a37g2000pre.googlegroups.com> Message-ID: <4791e919-0c55-49a2-bfdf-0f366a382e13@n33g2000pri.googlegroups.com> On Dec 20, 7:06?pm, Aaron Brady wrote: > On Dec 18, 7:21?pm, "Gabriel Genellina" > wrote: > > > > > En Thu, 18 Dec 2008 19:46:45 -0200, Aaron Brady ? > > escribi?: > snip > > > Will it take calling > > > 'CreatePipe' from ctypes directly if on Windows? ?Or can 'os.pipe' be > > > made to abstract that? ?If Windows can't inherit descriptors, > > > 'os.pipe' should return handles, and 'os.read' &co. should accept > > > them. > > > I think the best way would be to modify os.pipe so it returns inheritable ? > > pipes, as it should have been from the beginning. > > > > It is a fairly large patch. > > > Not at all, you have already posted most of it. > > I have marginally tested the patch on a custom build. ?It works, but > there is a catch. ?The descriptor can't be passed directly to the > child on the command line. ?You need to call 'msvcrt.get_osfhandle' on > the descriptor, pass the result, then call 'msvcrt.open_osfhandle' in > the child. Issue is at: http://bugs.python.org/issue4708 From trylks at gmail.com Tue Dec 30 13:42:11 2008 From: trylks at gmail.com (Jose Mora) Date: Tue, 30 Dec 2008 19:42:11 +0100 Subject: duck typing at will Message-ID: <6e1bfdea0812301042x70ab57capf99ce73d364d54db@mail.gmail.com> Duck typing is called that way because "If it looks like a duck and quacks like a duck, it must be a duck." I think it would be good to have also "If the programmer wants to deal with it like a duck, it must be a duck" I mean, some tasks are rather boring in python when compared with php, for example, let's imagine we have a dictionary that contains dictionaries that contain the times that a key appears. We, or at least I, would like to write something as short as: dict[k1][k2] += 1 However we will have to do a longer code (this is the smallest code I could come up with): dict = {} if not k1 in dict: dict[k1] = {} if not k2 in dict[k1]: dict[k1][k2] = 0 dict[k1][k2] += 1 I know it is not the Apocalypse nor something really important when compared with other things, but maybe it would be better if it wasn't necessary to declare the variables when they are built-in types or to initialize the keys in a dictionary, having special values (the identity element of the operation that causes the initialization) to initialize when it has not been done, initializing with the most general type that supports the operation that causes the initialization, casting to other type if necessary after that. This is just an idea, maybe I'm not the first one suggesting it, or maybe it is completely impossible to implement it because it would require deep changes in python, but I wanted to discuss it. Best regards. From ross.jett at gmail.com Mon Dec 29 20:38:36 2008 From: ross.jett at gmail.com (Ross) Date: Mon, 29 Dec 2008 17:38:36 -0800 (PST) Subject: get method References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> Message-ID: <4819de67-72dc-415c-b4c8-2353581c2bc7@r2g2000vbp.googlegroups.com> On Dec 29, 8:07?pm, Scott David Daniels wrote: > Ross wrote: > > ... Use get to write histogram more concisely. You should be able to > > eliminate the if statement. > > > def histogram(s): > > ? ?d = dict() > > ? ?for c in s: > > ? ? ? ? ? ?d[c]= d.get(c,0) > > ? ?return d > > > This code returns a dictionary of all the letters to any string s I > > give it but each corresponding value is incorrectly the default of 0. > > What am I doing wrong? > > How is this code supposed to count? > > --Scott David Daniels > Scott.Dani... at Acm.Org I realize the code isn't counting, but how am I to do this without using an if statement as the problem instructs? From anthony.tolle at gmail.com Fri Dec 19 09:53:46 2008 From: anthony.tolle at gmail.com (anthony.tolle at gmail.com) Date: Fri, 19 Dec 2008 06:53:46 -0800 (PST) Subject: How to read stdout from subprocess as it is being produced References: <263c3946-86aa-4db0-bdaf-42d0c8e5e5d6@q18g2000vbn.googlegroups.com> Message-ID: On Dec 19, 9:34?am, Alex wrote: > Hi, > > I have a Pyhon GUI application that launches subprocess. > I would like to read the subprocess' stdout as it is being produced > (show it in GUI), without hanging the GUI. > > I guess threading will solve the no-hanging issue, but as far as I > searched for now, I've only seen how to read the stdout after > subprocess is finished. > > Thanks! If I'm interpreting your needs correctly, then you may find this module helpful: http://code.activestate.com/recipes/440554/ I've used it successfully in the past when I wanted to use native python code (no C extensions necessary) for asynchronous reading from a child process. I'm not sure if later versions of Python (2.6, 3.0) support this in the standard library. I haven't researched it. From ivan.illarionov at gmail.com Sat Dec 27 23:47:26 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Sat, 27 Dec 2008 20:47:26 -0800 (PST) Subject: C API: array of floats/ints from python to C and back References: Message-ID: On Dec 28, 12:45?am, "Daniel Fetchinson" wrote: > I'm trying to write an extension module in C which contains a single > function with the following prototype: > > void func( int N, int * arg1, int * arg2, int * ret ); > > Here arg1 and arg2 are length N arrays, and the function computes ret > which is also an N length array. From python I'd like to call this > function as > > ret = func( [ 1, 2, 3 ], [ 2, 3, 4] ) > > I've read through the docs athttp://docs.python.org/extending/extending.htmland alsohttp://docs.python.org/c-api/arg.htmlfrom which I learned how to pass > a fixed number of basic datatypes (int, float, string) from python to > C and back. What I don't know is how to pass an array back and forth. > > As far as I can see PyArg_ParseTuple is the function I should use for > converting the python arguments to C but the format string passed to > PyArg_ParseTuple can only be one of the basic data types ("s", "i", > etc) or a generic python object ("O"). > > Does this mean that I can only pass the arrays from python to C as > generic python objects and in a later operation I need to get the > elements from this generic python object, construct a C array and pass > that to the C function? Since I assume this is a frequent operation > I'd think there are some shortcuts, aren't there? Or what's the > simplest way of doing this? > > Cheers, > Daniel > > -- > Psss, psss, put it down! -http://www.cafepress.com/putitdown Hi Daniel, Consider using this: http://docs.python.org/c-api/objbuffer.html This *IS* a shortcut, real shortcut. From gneuner2 at comcast.net Fri Dec 12 12:15:21 2008 From: gneuner2 at comcast.net (George Neuner) Date: Fri, 12 Dec 2008 12:15:21 -0500 Subject: Mathematica 7 compares to other languages References: <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <20081226055859.604@gmail.com> Message-ID: On Wed, 10 Dec 2008 21:37:34 +0000 (UTC), Kaz Kylheku wrote: >Now try writing a device driver for your wireless LAN adapter in Mathematica. Notice how Xah chose not to respond to this. George From malkarouri at gmail.com Tue Dec 9 11:59:40 2008 From: malkarouri at gmail.com (malkarouri) Date: Tue, 9 Dec 2008 08:59:40 -0800 (PST) Subject: When (and why) to use del? References: Message-ID: On 9 Dec, 16:35, Albert Hopkins wrote: > I'm looking at a person's code and I see a lot of stuff like this: > > ? ? ? ? def myfunction(): > ? ? ? ? ? ? # do some stuff stuff > ? ? ? ? ? ? my_string = function_that_returns_string() > ? ? ? ? ? ? # do some stuff with my_string > ? ? ? ? ? ? del my_string > ? ? ? ? ? ? # do some other stuff > ? ? ? ? ? ? return > > and also > > ? ? ? ? def otherfunction(): > ? ? ? ? ? ? try: > ? ? ? ? ? ? ? ? # some stuff > ? ? ? ? ? ? except SomeException, e: > ? ? ? ? ? ? ? ? # more stuff > ? ? ? ? ? ? ? ? del e > ? ? ? ? ? ? return > > I think this looks ugly, but also does it not hurt performance by > preempting the gc? ?My feeling is that this is a misuse of 'del'. Am I > wrong? ?Is there any advantage of doing the above? As far as I understand it, this does not do anything. Let me explain. The del statement doesn't actually free memory. It just removes the binding from the corresponding namespace. So in your first example, my_string cannot be used after the deletion. Of course, if the string referenced by my_string was referenced by some other name then it will still stay in memory. In both your examples, the bindings are going to be removed anyway immediately after the del statement, when returning from the function. So, the del is redundant. If for some reason, however, you are not breaking your work into functions (not advisable) you will have a huge list of commands with no deletion and start to use huge amounts of memory. Solution: divide your work into functions. It is sometimes, however, useful to preempt the gc. This can be done when you know that this is a good time to do chores, e.g. on an application's idle period. Calling gc.collect() is useful here. Regards, Muhammad Alkarouri From bearophileHUGS at lycos.com Sat Dec 20 07:55:42 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 20 Dec 2008 04:55:42 -0800 (PST) Subject: Jarow-Winkler algorithm: Measuring similarity between strings References: <4f351b3b-4da7-4fee-a1ac-c42179d430f5@s9g2000prm.googlegroups.com> <665bf3f7-ef74-4e59-bbac-cfbc12d4e81d@x16g2000prn.googlegroups.com> Message-ID: John Machin: > This paper by Heikki Hyyr? is well worth > reading, and refers to a whole lot of previous work, including > Ukkonen's: > http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.6.2242 This is the site of the author: http://www.cs.uta.fi/~helmu/pubs/pubs.html There you can find updates too: http://www.cs.uta.fi/~helmu/pubs/cpm02.pdf But such researchers have to offer C/Pascal/Java code too of their papers. Implementing things from scratch every time is a waste of time. Probably using SSE instructions like ANDPS, ANDNPS, ORPS, XORPS allows to use bitwise operations on 128 bit, allowing to search for longer strings in the same time. And the GPU of graphic cards offers other possibilities: http://www.cbcb.umd.edu/software/cmatch/Cmatch.pdf Bye, bearophile From deets at nospam.web.de Wed Dec 17 09:18:08 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 17 Dec 2008 15:18:08 +0100 Subject: Python, XML and XPath References: <6qsfvvFeen6dU1@mid.uni-berlin.de> Message-ID: <6qsg10Feen6dU2@mid.uni-berlin.de> Diez B. Roggisch wrote: > Hole wrote: > >> Hi all, >> >> I hope this is not an "overasked" question but I find myself quite >> confused about python xml management (I have to use python for a >> project and I come from java world, you know...where frameworks, >> libraries and tools to use are standard de iure or standard de facto). > > > > I suggest you use one of the available binary builds for windows: > > http://pypi.python.org/pypi/lxml/2.1 Most probably better: http://pypi.python.org/pypi/lxml/2.1.3 Diez From michael at stroeder.com Fri Dec 5 09:13:02 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 05 Dec 2008 15:13:02 +0100 Subject: EBCDIC <--> ASCII In-Reply-To: <6b861698-8638-443d-a230-3eca7424fcfc@j32g2000yqn.googlegroups.com> References: <091f0404-2be3-4bda-8619-03627bd03fdc@k8g2000yqn.googlegroups.com> <6b861698-8638-443d-a230-3eca7424fcfc@j32g2000yqn.googlegroups.com> Message-ID: martinjamesevans at gmail.com wrote: > On Dec 4, 4:45 pm, Michael Str?der wrote: >> martinjamesev... at gmail.com wrote: >>> I'm having a problem trying to use the codecs package to aid me in >>> converting some bytes from EBCDIC into ASCII. >> Which EBCDIC variant? >> >>> sEBCDIC = unicode(sSource, 'cp500', 'ignore') >> Are you sure CP500 is the EBCDIC variant for the language you want? >> >> http://www.ietf.org/rfc/rfc1345.txtlists it as: >> >> &charset IBM500 >> &rem source: IBM NLS RM Vol2 SE09-8002-01, March 1990 >> &alias CP500 >> &alias ebcdic-cp-be >> &alias ebcdic-cp-ch >> >>> Obviously I could just knock up a 255 character lookup table and do it >>> myself, I was just trying to be a little more Pythonic and use that >>> built in table. >> It's pythonic to implement a Unicode codec for unknown character tables. >> I've put these two on my web site: >> >> http://www.stroeder.com/pylib/encodings/ebcdicatde.pyhttp://www.stroeder.com/pylib/encodings/cp273.py(needs ebcdicatde) > > Thanks for the tables, ebcdicatde.py does look more suitable. > > My problem appears to be that my source is a byte string. In a > nutshell I need "\x81\x82\x83\xf1\xf2\xf3" to become "abc123" in a > byte string. Python 2.5.2 (r252:60911, Aug 1 2008, 00:43:38) >>> import ebcdicatde >>> "\x81\x82\x83\xf1\xf2\xf3".decode('ebcdic-at-de').encode('ascii') 'abc123' >>> Ciao, Michael. From anonymous.c.lisper at gmail.com Mon Dec 1 20:46:10 2008 From: anonymous.c.lisper at gmail.com (anonymous.c.lisper at gmail.com) Date: Mon, 1 Dec 2008 17:46:10 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: <603036aa-f047-4ab4-a27c-e7ed7347ccd5@f3g2000yqf.googlegroups.com> On Dec 1, 8:29?pm, Lew wrote: > anonymous.c.lis... at gmail.com wrote: > > A rational human would realize that not too many people peruse this > > newsgroup, > > and that most of them have already seen the wall of text post that you > > generate every time. > > Just out of curiosity, what do you consider "this" newsgroup, given its wide > crossposting? > > -- > Lew Ah, didn't realize the cross-posted nature. comp.lang.lisp Hadn't realized he had branched out to cross-posting across five comp.langs Apologies for the double post, thought the internet had wigged out when i sent it first time. From pavlovevidence at gmail.com Fri Dec 26 00:59:25 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 25 Dec 2008 21:59:25 -0800 (PST) Subject: Exec inside a class method to call other class methods? References: <4953CF57.8080905@sympatico.ca> <20081226001641.GA22946@sdf.lonestar.org> <47c890dc0812251624m7e1c5e55rb538996a52d56675@mail.gmail.com> Message-ID: <6706036c-98e0-46c1-b3c2-5a9a0a92af56@w39g2000prb.googlegroups.com> On Dec 25, 6:35?pm, "David Stanek" wrote: > You won't need the dictionary at all if each type has a parse method. How do you know what type to use if you don't have a if...elif..., dictionary, getattr, or some other sort of dispatching? Look at his requirements: there is a variable called "data_type" that controls how to parse the data. Whether he uses the variable to figure out what method to call, or to figure out what type of object to create to call the parse method of, some sort of dispatching is necessary. This is inevitable when type information is supplied through the input. To be honest I am a little concerned over the more-or-less knee-jerk suggestions to refactor this into a highly object-oriented approach. For the task at hand the OP's approach is fine (aside from the use of exec). Carl Banks From gagsl-py2 at yahoo.com.ar Wed Dec 17 19:42:17 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 17 Dec 2008 22:42:17 -0200 Subject: C API and memory allocation References: Message-ID: En Wed, 17 Dec 2008 21:35:04 -0200, Floris Bruynooghe escribi?: > On Dec 17, 11:06?pm, Floris Bruynooghe > wrote: >> So I'm assuming PyArg_ParseTuple() >> must allocate new memory for the returned string. ?However there is >> nothing in the API that provides for freeing that allocated memory >> again. > > I've dug a little deeper into this and found that PyArg_ParseTuple > (and friends) end up using PyString_AS_STRING() (Python/getargs.c:793) > which according to the documentation returns a pointer to the internal > buffer of the string and not a copy and that because of this you > should not attempt to free this buffer. Yes; but you don't have to dig into the implementation; from http://docs.python.org/c-api/arg.html : s (string or Unicode object) [const char *] Convert a Python string or Unicode object to a C pointer to a character string. You must not provide storage for the string itself; a pointer to an existing string is stored into the character pointer variable whose address you pass. > But how can python now know how long to keep that buffer object in > memory for? It doesn't - *you* have to ensure that the original string object isn't destroyed (by example, incrementing its reference count as long as you keep the pointer), or copy the string contents into your own buffer. -- Gabriel Genellina From zapwireDASHgroups at yahoo.com Wed Dec 31 12:55:43 2008 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Wed, 31 Dec 2008 09:55:43 -0800 Subject: SQL, lite lite lite References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> <4959204f$0$15020$426a74cc@news.free.fr> <6rvgihF3je6sU1@mid.uni-berlin.de> Message-ID: "Gerhard H?ring" wrote in message news:6rvgihF3je6sU1 at mid.uni-berlin.de... > Using an ORM when you don't grasp the relational model and/or the SQL query > language is futile. You'd probably be surprised just how many people there are out there using SQLlite (and other databases) who have no more than a 5 minute introduction to relational databasess. "See, you have tables, and you can stick columns for various attributes, and then add records for rows, and if you make multiple tables you specify which attribute becomes a 'key value' to find the corresponding record in another. Have fun!" > That's probably the case for many other abstraction layers, too. GUIs come to mind... From prologic at shortcircuit.net.au Thu Dec 18 17:33:28 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Dec 2008 08:33:28 +1000 Subject: Which sparse matrix package? In-Reply-To: <20081218231851.70dd91e2@Schlamber.localdomain> References: <20081218231851.70dd91e2@Schlamber.localdomain> Message-ID: On Fri, Dec 19, 2008 at 8:18 AM, Martin Manns wrote: > Hi: Hi, > I am writing a spreadsheet application in Python What's wrong with pyspread ? [ ... snip ... ] > The dict that I tried out is of the type: > > {(1,2,3): "2323", (1,2,545): "2324234", ... } > > It is too slow for my application when it grows. One slicing operation > with list comprehensions takes about 1/2 s on my computer for 1E6 > elements. Let me get this straight. It's taking 0.5s to slice your matrix of 1E7 (10000000.0 rows/columns) Are you mad ? This is TEN Millions and you required it faster than 0.5s ? Am I missing something here ? cheers James From rhodri at wildebst.demon.co.uk Wed Dec 17 19:03:01 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Thu, 18 Dec 2008 00:03:01 -0000 Subject: Why no lexical scoping for a method within a class? In-Reply-To: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> Message-ID: On Wed, 17 Dec 2008 15:19:32 -0000, walterbyrd wrote: > However in the methods are within a class, the scoping seems to work > differently. Not really. Hopefully this commentary will show you why. > class ab(): > def a(self): > self.x = 99 > print self.x > def b(self): > print self.x > > i = ab() This creates |i|, an instance of class |ab|. As yet it is pure and virgin, having nothing but the methods that it gets from |ab|. Soon this will change... > i.a() This creates an attribute |x| in |i|, and assigns the number 99 to it. > i.b() # this works, why no lexical scoping? This works because you ran |i.a()| first, so |i.x| exists and can be printed out. Lexical scoping is going on here, you're just mistaking what's being scoped; it's the |self| in |b|, which is in scope because it's a parameter. This particular |self| (the |i| you made earlier) happens to have an attribute |x|, so it all works. If however you'd written: j = ab() j.b() then Python would whinge mightily at you, claiming that it knoweth naught of this |x| attribute of which you speak, and can it go home now for this is a silly place. The |self| in |b| is still in lexical scope, though. -- Rhodri James *-* Wildebeeste Herder to the Masses From marduk at letterboxes.org Tue Dec 30 14:54:50 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Tue, 30 Dec 2008 14:54:50 -0500 Subject: need help with list/variables In-Reply-To: <63b5acce-d566-48cb-abce-c00fd0e02a39@v39g2000pro.googlegroups.com> References: <63b5acce-d566-48cb-abce-c00fd0e02a39@v39g2000pro.googlegroups.com> Message-ID: <1230666890.3713.2.camel@centar.nbk> On Tue, 2008-12-30 at 11:31 -0800, wx1234 at gmail.com wrote: > I have a list and would like to parse the list appending each list > item to the end of a variable on a new line. > > for instance > > mylist = ['something\n', 'another something\n', 'something again\n'] > > then parse mylist to make it appear in my variable in this format: > > myvar = """ > something > another something > something again""" > > how would i go about setting a variable like this? myvar = ''.join(mylist) Though if you really want an "blank line" in the beginning you'll need to prepend a '\n' -a From rocky at panix.com Thu Dec 11 04:33:18 2008 From: rocky at panix.com (R. Bernstein) Date: Thu, 11 Dec 2008 04:33:18 -0500 Subject: trace module and doctest Message-ID: On Nov 22 2007, 4:31 pm, j... at pobox.com (John J. Lee) wrote: > s... at pobox.com writes: > > I am trying to use thetracemodulewith the --count flag to test for > > statement coverage in my doctests. Thetracecoverage listing is very > > weird, marking many statements as unexecuted which were clearly executed > > during the run (I can see their output on the screen). Is this some known > > interaction between thetraceanddoctestmodules? > > Yes: > > http://python-nose.googlecode.com/svn/trunk/nose/plugins/doctests.py > > http://svn.zope.org/Zope3/trunk/src/zope/testing/doctest.py?rev=28679... > > John Interesting. Is this problem caused or ascerbated by the fact that sys.settrace() is this sort of global? I've been looking at redoing pdb from scratch, from the bottom up. As Obama might say in a different context, "line by line". I sort of don't like the global-ness of pdb, or for that matter the sys.settrace's trace hook. So as a start, I wrote a "tracer" module (http://code.google.com/p/pytracer/ and on Pypi) which just a wrapper around the global trace hook to allow different applications to register trace events and not clobber one-another. Possibly in an Ideal world, Python would itself have done the trace hook chaining. (I believe that the case in Ruby ;-) But Python 2.6 does now allow you *query* to find out if a trace hook has been installed, chaining so it is now possible, even though tracer doesn't use the 2.6 sy.gettrace () to allow it chain outside of routines that use it directly. But as I wonder if this kind of problem would have been avoided if there had been a wrapper to allow settrace chaining? (And if that is s -- unlikely as it is to happen -- various applications like tracer, doctest and pdb could be rewritten to use tracer.) From rdcollum at gmail.com Sun Dec 28 12:19:46 2008 From: rdcollum at gmail.com (Roger) Date: Sun, 28 Dec 2008 09:19:46 -0800 (PST) Subject: "return" in def Message-ID: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> Hi Everyone, First I want to thank everyone that posts to this group. I read it daily and always learn something new even if I never feel like I have anything to contribute but my questions. When I define a method I always include a return statement out of habit even if I don't return anything explicitly: def something(): # do something return Is this pythonic or excessive? Is this an unnecessary affectation that only adds clock ticks to my app and would I be better off removing "returns" where nothing is returned or is it common practice to have returns. Even when I'm not explicitly returning something I like to add "return" because it's a good additional visual marker for me to see where a method definition ends especially in cases where I may use a nested method. Thanks for the discussion! Roger. From prologic at shortcircuit.net.au Mon Dec 29 20:45:08 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 30 Dec 2008 11:45:08 +1000 Subject: Python in C In-Reply-To: <47c890dc0812291732p34ab7710u5b98b30eb926113c@mail.gmail.com> References: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> <47c890dc0812291732p34ab7710u5b98b30eb926113c@mail.gmail.com> Message-ID: On Tue, Dec 30, 2008 at 11:32 AM, Chris Rebert wrote: > On Mon, Dec 29, 2008 at 5:22 PM, wrote: > >> 2. Have there been any suggestions in the past to rewrite Python's >> mainstream implementation in C++ (or why wasn't it done this way from >> the beginning)? > > I'm not a CPython dev (I bet one will pipe in), but I would speculate > it's because C++ is so much more complicated and a bit less portable > than C. I'm not a CPython dev either, but I concur with this statement. cheers James From tn.pablo at gmail.com Thu Dec 18 12:07:03 2008 From: tn.pablo at gmail.com (ptn) Date: Thu, 18 Dec 2008 09:07:03 -0800 (PST) Subject: Location HTTP Header References: <68fa1e9b-6652-4d34-a7fe-fc98db8bf6d4@m16g2000vbp.googlegroups.com> Message-ID: <5f4d3006-0750-4faa-ae1b-3a0408abbe2a@g1g2000pra.googlegroups.com> On Dec 17, 6:47?pm, "Gabriel Genellina" wrote: > En Wed, 17 Dec 2008 20:52:42 -0200, ptn escribi?: > > > I tried this stupid script on my server: > > > ? ?#! /usr/bin/env python > > > ? ?print 'Location:http://www.google.com\n' > > > and it didn't work, I get a blank page. ?I first tried the Location > > header in another script, and when execution got to that point, it > > would > > just sort of ignore it, because the script would keep running to the > > end > > of the code (or stop at some unhandled exception). > > I assume this is a cgi script. For the Location field to be relevant, the ? > Status should be a 3xx (like 307 Temporary Redirect, or 302 Found) > In your case, your server probably has already sent a 200 OK response, so ? > Location is ignored. > Try adding a Status line -before Location above- like: > print 'Status: 302 Found" > > > Any ideas? > > I'd use a different protocol other than CGI... > > -- > Gabriel Genellina Mmmmm no, that didn't do it. The script now is: #! /usr/bin/env python print 'Status: 302 Found' print 'Location: http://www.google.com\n' but still nothing happens, I get the same blank page. Since the sscript is so simple, maybe it is a matter of server configuration? Is that possible? From chrispoliquin at gmail.com Fri Dec 5 13:50:47 2008 From: chrispoliquin at gmail.com (chrispoliquin at gmail.com) Date: Fri, 5 Dec 2008 10:50:47 -0800 (PST) Subject: Overwrite single line of file Message-ID: Hi, I have about 900 text files (about 2 GB of data) and I need to make some very specific changes to the last line of each file. I'm wondering if there is a way to just overwrite the last line of a file or replace the spots I want (I even know the position of the characters I need to replace). I know how to open files and read the contents and then write everything out again after making the changes, but is there a way to replace just the last line without having to completely rewrite each file after making the changes? -Chris From tino at wildenhain.de Wed Dec 3 08:57:06 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Wed, 03 Dec 2008 14:57:06 +0100 Subject: Converting a .xls file to .html In-Reply-To: References: Message-ID: <49369032.8080908@wildenhain.de> Hi, tarun wrote: > Hello All, > > I've a .xml file (saved as .xls) that can be opened in Microsoft excel. Well if its an xml file then just attach a style to it and you can just view it in a browser w/o involving excel in the first place. Also there are lots of xml libraries coming with python so you can translate it directly into HTML of your choice. > I want to write python code that converts this excel file into .html (so > that it can be viewed as is in an explorer). Whats an Explorer? I guess you mean Webbrowser here? Now if you manage to have it in Excel, then you could just save it as HTML (or whatever Microsoft believes is HTML). If the file is stored elsewhere in Excel-Format, then you could script that using xlrd (google for it) Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From bblais at bryant.edu Fri Dec 5 16:37:37 2008 From: bblais at bryant.edu (Brian Blais) Date: Fri, 5 Dec 2008 16:37:37 -0500 Subject: Can I load a python program at the interactive >>> prompt? In-Reply-To: <269e5d69-02b7-409b-ad53-b7702b6ec13a@i24g2000prf.googlegroups.com> References: <269e5d69-02b7-409b-ad53-b7702b6ec13a@i24g2000prf.googlegroups.com> Message-ID: <6143BC03-1E8E-4622-9FA8-EC78E78F0F9E@bryant.edu> On Dec 5, 2008, at 15:52 , walterbyrd wrote: > Can I load a file into the python interactive environment? For > example I have a file called test.py that consists of the following: > > print "hello" > print "hello again" > > Can I load that file into python at the >>> prompt? > >>>> load "test.py" > > or something like that? > I think you mean: execfile('test.py') that should work. if you have iPython, which is a great shell for running python code, you can do: run test.py as far as copy/paste, I think in Windows Python runs in a DOS prompt, so you should be able to right-click and choose Edit/Paste. Not too convenient, but I think it works. bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at mrabarnett.plus.com Sat Dec 20 21:36:52 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 21 Dec 2008 02:36:52 +0000 Subject: a small doubt In-Reply-To: <19ac19520812201750hb592e4dsa5ef7d2a1906c2ed@mail.gmail.com> References: <19ac19520812201750hb592e4dsa5ef7d2a1906c2ed@mail.gmail.com> Message-ID: <494DABC4.30603@mrabarnett.plus.com> Piyush Anonymous wrote: > i wrote this code > -- > class Person(object): > instancesCount = 0 > def __init__(self, title=""): > Person.instancesCount += 1 > self.id = "tempst" > def testprint(self): > print "blah blah" > def __getattribute__(self, name): > print "in get attribute" > > a = Person() > a.testprint() > print a.id > ----- > but i am getting this error > ---- > in get attribute > Traceback (most recent call last): > File "trapmethodcall1.py", line 15, in > a.testprint() > TypeError: 'NoneType' object is not callable > ------ > why is it so? __getattribute__ is called whenever an attribute or method > is called, rt? or if i set __getattribute__ , i cannot have methods in > class? > > actually my aim is to trap all method calls and keep a counter which is > update whenever method called or returned. how should i go about it? > a.testprint causes __getattribute__ to be called. That method returns None. a.testprint() is therefore None(), hence the exception. From saluk64007 at gmail.com Mon Dec 8 16:07:56 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Mon, 8 Dec 2008 13:07:56 -0800 Subject: Guido's new method definition idea In-Reply-To: References: <014a071a$0$20670$c3e8da3@news.astraweb.com> <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> Message-ID: On Mon, Dec 8, 2008 at 12:55 PM, Arnaud Delobelle wrote: > anthony.tolle at gmail.com writes: > >> class C: >> def createfunc(self): >> def self.func(arg): >> return arg + 1 >> >> Or, after the class definition is done, to extend it dynamically: >> >> def C.method(self, arg): >> self.value = arg >> >> ...which would be the equivalent of the following: >> >> def method(self, arg): >> self.value = arg >> C.method = method > > What about the following then? > > functions = {} > > def functions['square'](x): > return x*x > > def functions['cube'](x): > return x**3 > > -- > Arnaud > -- > http://mail.python.org/mailman/listinfo/python-list > Why not? "def ob.func" is fundamentally "def ob.__dict__["func"]" anyway. I like this idea much better than the original proposal, even though it is pretty much unrelated. From bdesth.quelquechose at free.quelquepart.fr Sun Dec 21 09:20:25 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 21 Dec 2008 15:20:25 +0100 Subject: trapping all method calls in a class... In-Reply-To: References: <19ac19520812202312q71409182kb58a0f7aaf3b0e74@mail.gmail.com> Message-ID: <494e5e5c$0$16190$426a34cc@news.free.fr> Chris Rebert a ?crit : (snip) > Sidenotes about your code: > - `args` and `kwds` are the conventional names for the * and ** > special arguments for '**', the most "conventional" names (at least the one I usually see) are 'kwargs', then 'kw' From benjamin.kaplan at case.edu Sun Dec 14 15:27:57 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 14 Dec 2008 15:27:57 -0500 Subject: package structure? In-Reply-To: References: Message-ID: On Sun, Dec 14, 2008 at 3:16 PM, Torsten Mohr wrote: > Hi, > > in a package i'd like to have a structure like this: > > Files end with ".py", others are directories: > > mod > __init__.py # sets __all__ = ['smod1'] > smod1.py # contains AClass() > smod1 > __init__.py # sets __all__ = ['abc', 'def'] > abc.py > def.py > > So i can now do: > > import mod.smod1.abc > import mod.smod1 > > > But functions/classes in smod1.py are not found: > > a = mod.smod1.AClass() > > I know this is somehow ambiguous, but i wonder how else i can make > "mod" have subpackages and modules. > > I wonder how i can make AClass() known in that package. > You have two modules named smod1- one of them uses the code in smod1.py, the other one is in smod1/__init__.py. The second one hides the first. Python doesn't let you have two modules with the same name. You have to either rename one of the smod1's or define AClass in smod1/__init__.py instead. > > > Thanks for any hints, > Torsten. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From manu3d at gmail.com Thu Dec 18 08:51:33 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 18 Dec 2008 05:51:33 -0800 (PST) Subject: re.match() performance Message-ID: <755bd716-f5f6-4953-87a7-04ee148c3298@i18g2000prf.googlegroups.com> Sorry for the previous post, hit the Enter button by mistake... here's the complete one: Hi everybody! I've written the code below to test the differences in performance between compiled and non-compiled regular expression matching but I don't quite understand the results. It appears that the compiled the pattern only takes 2% less time to process the match. Is there some caching going on in the uncompiled section that prevents me from noticing its otherwise lower speed? Manu ------------ import re import time ## Setup pattern = "(.*)" compiledPattern = re.compile(pattern) longMessage = ""+ "a" * 100000 +"" numberOfRuns = 1000 ## TIMED FUNCTIONS startTime = time.clock() for i in range(0, numberOfRuns): re.match(pattern, longMessage) patternMatchingTime = time.clock() - startTime startTime = time.clock() for i in range(0, numberOfRuns): compiledPattern.match(longMessage) compiledPatternMatchingTime = time.clock() - startTime ratioCompiledToNot = compiledPatternMatchingTime / patternMatchingTime ## PRINT OUTS print("") print(" Pattern Matching Time: " + str(patternMatchingTime)) print("(Compiled) Pattern Matching Time: " + str (compiledPatternMatchingTime)) print("") print("Ratio Compiled/NotCompiled: " + str(ratioCompiledToNot)) print("") From wuwei23 at gmail.com Fri Dec 5 22:00:12 2008 From: wuwei23 at gmail.com (alex23) Date: Fri, 5 Dec 2008 19:00:12 -0800 (PST) Subject: To Troll or Not To Troll (aka: "as" keyword woes) References: <20081205163107.1815df40@usenot.de> Message-ID: <27945697-3f2f-452d-bed4-d1ca45d46fbb@r10g2000prf.googlegroups.com> On Dec 6, 8:00?am, James Stroud wrote: > I think its a symptom of the language's > maturing, getting popular, and a minority fraction* of the language's > most devout advocates developing an egotism that complements their > python worship in a most unsavory way. It's hard to see how anyone could ever take offence at your posts given such unbiased objectivity ;) From tjreedy at udel.edu Mon Dec 8 20:25:35 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Dec 2008 20:25:35 -0500 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: Jon Harrop wrote: > jason-sage at creativetrax.com wrote: >> For the interested, with MMA 6, on a Pentium 4 3.8Ghz: >> >> The code that Jon posted: >> >> Timing[Export["image-jon.pgm", Graphics at Raster@Main[2, 100, 4]]] >> {80.565, "image-jon.pgm"} > > That is not the code I posted: you are using Xah's parameters that generate > a different (and largely empty) scene. > >> The code that Xah posted: >> >> Timing[Export["image-xah.pgm", Graphics at Raster@Main[2, 100, 4.]]] >> {42.3186, "image-xah.pgm"} >> >> So Xah's code is about twice as fast as Jon's code, on my computer. >> >> The resulting files were identical (and both looked like pure white >> images; I thought they'd be interesting!). > > Use 9, 512, 4 instead of 2, 100, 4 and you will get a more interesting image > of over 80,000 spheres with shadows and diffuse lighting. > > This is a really important difference: half of that program is dedicated to > hierarchical spherical bounding volumes that are essential when tracing a > large number of spheres. Xah solved a completely different problem by > simplifying the scene to only 5 spheres, where bounding volumes are useless > and the performance characteristics of the program are wildly different. Lest anyone doubt that problem size is important for comparing program run times, consider the following realistic example: the run time of algorithm A is n*n, that of B is 10.6666666667*n*log2(n). A is faster for small problems, B for large problems, with the crossover at 64. A hybrid algorithm C could use B for large problems and A for small problems and small subproblems generated by B's divide and conquer technique. Python's list.sort is such a hybrid of binary insertion sort and merge sort, with a crossover at 64 based on experimental data. tjr From bkamrani at gmail.com Tue Dec 2 06:51:55 2008 From: bkamrani at gmail.com (bkamrani at gmail.com) Date: Tue, 2 Dec 2008 03:51:55 -0800 (PST) Subject: performance question: dictionary or list, float or string? References: Message-ID: <434bf4e3-54f4-4e15-b8b0-510a988f25b8@z1g2000yqn.googlegroups.com> I forgot to mention that I did a simple timeit test which doesn't show significant runtime difference 3.5 sec for dictionary case and 3.48 for list case. def read_as_dictionary(): fil = open('myDataFile', 'r') forces = {} for region in range(25): forces[region] = {} for step in range(20000): for region in range(25): line = fil.next(); spl = line.split() forces[region] [step] = spl def read_as_list(): fil = open('myDataFile.txt', 'r') forces = [] for region in range(25): forces.append([]) for step in range(20000): for region in range(25): line = fil.next(); spl = line.split() forces[region].append(spl) Cheers, /Ben From castironpi at gmail.com Thu Dec 18 16:40:35 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 18 Dec 2008 13:40:35 -0800 (PST) Subject: C API and memory allocation References: <59352942-e976-4ef4-bc40-c8953df0a792@c36g2000prc.googlegroups.com> <0d35b640-71ad-4cde-8869-74878b2f3981@r36g2000prf.googlegroups.com> <494a55fb$0$31873$9b4e6d93@newsspool3.arcor-online.net> Message-ID: On Dec 18, 7:54?am, Stefan Behnel wrote: > Aaron Brady wrote: > > I see. ?Do I read correctly that 's' is only useful when the > > argument's position is known? > > I assume you meant "length". No, position in the argument list. Otherwise you can't change its reference count; in which case, a pointer to the string object's contents (a char*) is useless after control leaves the caller's scope. > > ?Otherwise you can't know its length or > > change its reference count. > > The internal representation of Python byte strings is 0 terminated, so > strlen() will work. As MRAB said, Python strings can contain null bytes, since they carry their lengths. Therefore strlen will always succeed, but isn't always right. >>> len( "abc\x00def" ) 7 'strlen' says '3'. So, with 's', you are limited to the operations preceding null bytes in the current scope (with the GIL held). I hold this is strong enough to put the burden of proof on the defenders of having 's'. What is its use case? From eric at ericaro.net Thu Dec 4 15:08:51 2008 From: eric at ericaro.net (eric) Date: Thu, 4 Dec 2008 12:08:51 -0800 (PST) Subject: simplest way to strip a comment from the end of a line? References: <52e3f2a9-6fb1-42ef-9871-c904ede5520e@t3g2000yqa.googlegroups.com> Message-ID: <9cdc9039-6b7b-42fb-b261-4ad721ccd1d4@j39g2000yqn.googlegroups.com> On Dec 4, 5:15?pm, eric wrote: > On Dec 4, 4:50?pm, Joe Strout wrote: > > > I have lines in a config file which can end with a comment (delimited ? > > by # as in Python), but which may also contain string literals ? > > (delimited by double quotes). ?A comment delimiter within a string ? > > literal doesn't count. ?Is there any easy way to strip off such a ? > > comment, or do I need to use a loop to find each # and then count the ? > > quotation marks to its left? > > > Thanks, > > - Joe > > Hi, > > if the string literal you wan't to escape, is not escaped (i.e > contains \" ) then a regexp like > > .*?(?:".*?".*?)*#(?P .*?)$ > > (not tested) > .*? ?everything but keep it greedy > ".*?" the string literal not escaped well it works too import re test ='''this is a test 1 this is a test 2 #with a comment this is a '#gnarlier' test #with a comment this is a "#gnarlier" test #with a comment ''' splitter = re.compile(r'(?m)^(?P.*?(".*?".*?)*)(?:#.*?)?$') def com_strip(text): return [x[0] for x in splitter.findall(test) ] # raw implementation for line in test.split('\n'): print line, '->', re.match(r'(?P.*?(".*?".*?)*)(?:#.*?)?$', line).group("data") # with a function for line in com_strip(test): print line and here is the console output this is a test 1 -> this is a test 1 this is a test 2 #with a comment -> this is a test 2 this is a '#gnarlier' test #with a comment -> this is a ' this is a "#gnarlier" test #with a comment -> this is a "#gnarlier" test -> this is a test 1 this is a test 2 this is a ' this is a "#gnarlier" test From gagsl-py2 at yahoo.com.ar Wed Dec 24 12:37:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2008 15:37:53 -0200 Subject: How to change a generator ? References: <7F0503CD69378F49BE0DC30661C6CCF6024946E6@enbmail01.lsi.com> <49526B7E.20904@mrabarnett.plus.com> Message-ID: En Wed, 24 Dec 2008 15:03:58 -0200, MRAB escribi?: >> I have a generator whose aim is to returns consecutive lines from a >> file (the listing below is a simplified version). >> However, as it is written now, the generator method changes the text >> file pointer to end of file after first invocation. >> Namely, the file pointer changes from 0 to 6623 on line 24. >> > It might be that the generator method of self.input_file is reading the > file a chunk at a time for efficiency even though it's yielding a line > at a time. I think this is the case too. I can think of 3 alternatives: a) open the file unbuffered (bufsize=0). But I think this would greatly decrease performance. b) keep track internally of file position (by adding each line length). The file should be opened in binary mode in this case (to avoid any '\n' translation). c) return line numbers only, instead of file positions. Seeking to a certain line number requires to re-read the whole file from start; depending on how often this is required, and how big is the file, this might be acceptable. -- Gabriel Genellina From deen.vdm at gmail.com Sun Dec 7 02:52:35 2008 From: deen.vdm at gmail.com (deen.vdm at gmail.com) Date: Sat, 6 Dec 2008 23:52:35 -0800 (PST) Subject: hifriends Message-ID: <4e398db0-a652-4af6-a33c-c1c8fe86f1ef@s1g2000prg.googlegroups.com> hi,visit the web for download the latest songs and music by clickhttp://musicsite-download.blogspot.com/ From google at mrabarnett.plus.com Sat Dec 6 12:59:28 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 06 Dec 2008 17:59:28 +0000 Subject: RELEASED Python 3.0 final In-Reply-To: References: <874p1jux8u.fsf@benfinney.id.au> <87iqpyt80i.fsf@benfinney.id.au> Message-ID: <493ABD80.4020203@mrabarnett.plus.com> Mensanator wrote: > On Dec 5, 12:29 pm, "Hendrik van Rooyen" wrote: >> "Ben Finney" wrote: >>> I hereby recommend ?pish and tosh? for use by anyone who wants to >>> counter someone's point. It beats by a country furlong the invective >>> that has become regrettably common here in recent months. >> I second the motion to use pish and tosh for a first level of disagreement. >> >> I recommend the rather archaic "Balderdash" as the next step in the >> escalation of disagreement... > > As a W.C. Fields fan, I love his "non-swearing" > vocabulary: > > - Drat > > - Dag nab it > > - Holy Mother of Pearl! > > etc. > Holy Zarquon's Singing Fish! (Hitch-hiker's Guide to the Galaxy) But don't say B*****m. :-) http://www.bbc.co.uk/cult/hitchhikers/guide/belgium.shtml From 20080915.20.wmcclain at spamgourmet.com Wed Dec 10 06:58:37 2008 From: 20080915.20.wmcclain at spamgourmet.com (Bill McClain) Date: 10 Dec 2008 11:58:37 GMT Subject: StringIO in 2.6 and beyond References: Message-ID: On 2008-12-10, ajaksu wrote: > On Dec 9, 5:24?pm, Bill McClain <20080915.20.wmccl... at spamgourmet.com> > wrote: > > On 2008-12-09, MRAB wrote: > > > > > In Python 2.x unmarked string literals are bytestrings. In Python 3.x > > > they're Unicode. The intention is to make the transition from 2.x to 3.x > > > easier by adding some features of 3.x to 2.x, but without breaking > > > backwards compatibility (not entirely successfully!). > > > > It is a bit ugly. In 2.6 StringIO won't take bytestrings, so I apply u'x'. But > > in 3.0 u'x' will be gone and I'll have to change the code again. > Try: > from __future__ import unicode_literals That works for: output.write('First line.\n') ...but not for: print('Second line.', file=output) Maybe a combination of this and functools.partial as was suggested before. At least the necessary edits would be at the top of the program. -Bill -- Sattre Press Tales of War http://sattre-press.com/ by Lord Dunsany info at sattre-press.com http://sattre-press.com/tow.html From xahlee at gmail.com Wed Dec 31 12:55:23 2008 From: xahlee at gmail.com (Xah Lee) Date: Wed, 31 Dec 2008 09:55:23 -0800 (PST) Subject: Why not Ruby? Message-ID: Just spent 3 hours looking into Ruby today. Here's my short impression for those interested. * Why Not Ruby? http://xahlee.org/UnixResource_dir/writ/why_not_Ruby.html plain text version follows: -------------------------------------- Why Not Ruby? Xah Lee, 2008-12-31 Spent about 3 hours looking into Ruby language today. The articles i read in detail are: * Wikipedia: Ruby (programming language)?J. Gives general overview. * Brief tutorial: "Ruby in Twenty Minutes" http://www.ruby-lang.org/en/documentation/quickstart/ * Personal blog by Stevey Yegge, published in 2004-10. http://steve.yegge.googlepages.com/ruby-tour The Wikipedia gives the best intro and overview in proper context. The "Ruby in Twenty Minutes" is just 4 pages. It give you a very concrete intro to Ruby's syntax and semantics. Stevey Yegge's blog doesn't teach much and rambles, but provide a little personal view. I read it because his opinions i respect. Q: Will you learn Ruby? No. For practical application, the lang is some 100 times less useful than each of Perl, Python, PHP, Javascript. For academic study, functional langs like Mathematica, Haskell, OCaml, erlang, Qz, are far more interesting and powerful in almost all aspects. Further, there's also Perl6, NewLisp, Clojure, Scala... With respect to elegance or power, these modern lang of the past 5 years matches or exceed Ruby. Q: Do you think Ruby lang is elegant? Yes. In my opinion, better than Perl, Python, PHP. As a high level lang, it's far better than Java, C, C++ type of shit. However, i don't think it is any better than emacs lisp, Scheme lisp, javascript, Mathematica. Note that Ruby doesn't have a spec, and nor a formal spec. Javascript has. Ruby's syntax isn't that regular, nor is it based on a system. Mathemtica's is. Ruby's power is probably less than Scheme, and probably same as Javascript. I also didn't like the fact that ruby uses keyword "end" to indicate code block much as Pascal and Visual Basic, Logo, do. I don't like that. Q: Won't Ruby be a interesting learning experience? No. As far as semantics goes, Ruby is basically identical to Perl, Python, PHP. I am a expert in Perl and PHP, and have working knowledge of Python. I already regretted having spent significant amount of time (roughly over a year) on Python. In retrospect, i didn't consider the time invested in Python worthwhile. (as it turns out, i don't like Python and Guido cult, as the lang is going the ways of OOP mumbo- jumbo with its Python 3 "brand new" future.) There is absolutely nothing new in Ruby, as compared to Perl, Python, PHP, or Emacs lisp, Scheme lisp. Q: Do you recommend new programers to learn Ruby then? Not particularly. As i mentioned, if you are interested in practical utility, there's already Perl, PHP, Python, Javascript, which are all heavily used in the computing industry. If you are interested as a academic exercise, there's Scheme lisp, and much of functional langs such as OCaml, Haskell, Mathematica, which will teach you a whole lot more about computer science, features of language semantics, etc. Q: Do you condemn Ruby? No. I think it's reasonably elegant, but today there are too many languages, so Ruby don't particularly standout for me. Many of them, are arguably quite more elegant and powerful than Ruby. See: Proliferation of Computing Languages. From rafesacks at gmail.com Mon Dec 1 03:54:35 2008 From: rafesacks at gmail.com (Rafe) Date: Mon, 1 Dec 2008 00:54:35 -0800 (PST) Subject: Project structure - Best practices References: Message-ID: <2d1f986f-94da-49c8-a1a5-df9457d5f8b3@r36g2000prf.googlegroups.com> On Nov 30, 11:43?pm, "Filip Gruszczy?ski" wrote: > This is first time that I am building python application that is > larger than a single module and I would like to do it right. I google > it a bit, finding some stuff about not using src directory (which I > have seen so many times, that I believed it be standard) and using > packages. Still, there are few things, that I would like to achieve > with this structure: > * being able to use pychecker a lot - catching all typos in one shot > instead of running app many times really saves me a lot of time > * being able to write some unit tests > * having clean division of code among packages and modules (I have > seen some projects, where modules are pretty large - I would like to > keep them logically divided, event if they stay smaller) > > My project is a tool for people interested in role playing games. My > current structure looks something like this: > > /src > rpgDirectory.py (main script, running the app) > > src/rpg > plans.py > support.py > gui.py > iosystem.py > > src/rpg/character > model.py > sheet.py > gui.py > handlers.py > requirements.py > > The problem is, that modules from src/rpg/character use classes > defined in support.py. Therefore I have to use absolute paths to > import it and this works only, when I run rpgDirectory.py. When I use > pychecker, it can't import this module and fails. Any suggestions, how > can I avoid this and what structure should I use? > > -- > Filip Gruszczy?ski Hi, I have read in many places that relative imports aren't recommend as a standard. This includes PEP 8 (http://www.python.org/dev/peps/ pep-0008/) which states: " - Relative imports for intra-package imports are highly discouraged. Always use the absolute package path for all imports. Even now that PEP 328 [7] is fully implemented in Python 2.5, its style of explicit relative imports is actively discouraged; absolute imports are more portable and usually more readable." ...and I completely agree. I always use the standard import form unless absolutely necessary. However, I use 'as' to shorten the path to the last module. For example: >>> import app.foo.bar as bar >>> instance = bar.Class() The only "relative" import I use when I am getting another module in the same package. If I have: app/ __init__.py constants.py foo/ __init__.py bar.py here.py utils/ __init__.py ... and I am inside app/foo/here.py, I might have some imports at the top of the module which look like this... import app.constants as appC import app.utils import bar Python will look for 'bar' in the local package before looking through the python path. I could have imported constants as just "c", but single letter variables are dangerous and I work with an application where it is common in the community to use 'c' for 'constants' (regardless of the danger). Lastly, I could import 'app.utils' as 'utils', but this is such a common module name that I like to preserve the name-space or at least prefix it (so I suppose something like 'apputils' would be acceptable, but I'd only be saving one character, the '.', so what's the point?). I find that no matter how well I plan what my structure will be, I end up making small changes such as flattening a sub-package or converting a module to a sub-package to break things down further. As someone who recently started learning python, I would recommend that you just make a quick sketch of what you think might work and then just begin coding. Adjust to logic along the way. At some point planning begins to eat time rather than save it. get through the fastest initial 80%, maybe push for a few more %, then just go for it (I assume you have this luxury. If not then you probably have a team that can help refine the plan anyway.) Hope this helps. - Rafe From gnewsg at gmail.com Thu Dec 11 13:09:37 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 11 Dec 2008 10:09:37 -0800 (PST) Subject: How to know when it's possible to bind a socket on an unprivileged port? Message-ID: <799ba4ea-0ef8-499b-909e-507bf4abe4aa@z28g2000prd.googlegroups.com> Hi, For a purpose of testing I need a function which could tell me whether it is possible to bind sockets on privileged ports or not. I wrote down this simple function. It seems reasonably working to me but I'd like to hear your opinion first. Thanks in advance. import socket, errno def bind_on_privileged_ports(port=21): """Return True if it is possible to bind sockets on privileged ports (< 1024).""" try: s = socket.socket() s.bind(("", port)) except socket.error, err: if err[0] == errno.EACCES: return False s.close() return True --- Giampaolo http://code.google.com/p/pyftpdlib/ From sjmachin at lexicon.net Sat Dec 20 06:32:02 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 20 Dec 2008 03:32:02 -0800 (PST) Subject: Jarow-Winkler algorithm: Measuring similarity between strings References: <4f351b3b-4da7-4fee-a1ac-c42179d430f5@s9g2000prm.googlegroups.com> <665bf3f7-ef74-4e59-bbac-cfbc12d4e81d@x16g2000prn.googlegroups.com> Message-ID: On Dec 20, 7:07?pm, ?yvind wrote: > Thanks for the useful comments. > > On 20 Des, 01:38, John Machin wrote: > > > On Dec 20, 10:02?am, ?yvind wrote: > > > > Based on examples and formulas fromhttp://en.wikipedia.org/wiki/Jaro-Winkler. > > > For another Python implementation, google "febrl". > > > > Useful for measuring similarity between two strings. For example if > > > you want to detect that the user did a typo. > > > You mean like comparing the user's input word with some collection of > > valid words? You would need to be using something else as a quick-and- > > dirty filter ... Jaro-Winkler is relatively slow. > > Do you have any alternative ?suggestions? Use a Levenshtein or Damerau edit distance. The latter handles adjacent transpositions (...AB...->...BA...) which covers well over 90% of the transposition errors I've ever seen. The remainder e.g. ...AXB...->...BXA... are given the same weight by Jaro-Winkler; this is IMHO silly. Read a little bit further than the CS101 level on Levenshtein edit distance and ignore any implementation which calculates all N*M cells of a dynamic programming matrix -- in the case where the objective is to calculate the distance except that once the distance is known to be over a threshold you don't care how big it is (you will reject a match if the distance is too big), then you only need to fill in the entries in a narrow band astride the trailing diagonal, and you can reliably give up if the current distance on the diagonal becomes too high. Ukkonen's the man in this field. It gets better. You can forget the matrix when the word lengths are less than the number of bits in your computer word (even 32 bits is enough for most words in most languages). The bit-parallel techniques include Damerau distance. This paper by Heikki Hyyr? is well worth reading, and refers to a whole lot of previous work, including Ukkonen's: http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.6.2242 And you can forget about all the fancy techniques when the word lengths are so different that they can't be the same (e.g. Fu and Featherstonehaugh) -- or the shorter should perhaps be checked to see if it's a plausible abbreviation or contraction of the longer. > > ?Also as the Wikipedia article says, > > it's not a metric. I.e. it doesn't satisfy dist(a, c) <= dist(a, b) + > > dist(b, c). > > Its not a mathematical correct metric, but it is a useful heuristical > metric. Useful for what? IMHO: If it doesn't satisfy the symmetry condition and the triangle rule, it's just plain dodgy. J-W is dodgy and slow. Might as well use soundex. End of story. > > > The above code is not symmetrical; jarow_m(s1, s2) does not > > necessarily equal jarow_m(s2, s1). The article talks about one "m", > > not two of them. > > Hmm.. also a good point. I will make it count all the matches, not > just the matches in s1. The whole Jaro definition is woolly ... what is a match when you have more than one occurrence of the same letter? Have a look at what the matches might be between MISSISSIPPI and a variant with an extra I in the middle e.g MISSISISIPPI. Cheers, John From jstraszheim at comcast.net Sat Dec 6 16:42:08 2008 From: jstraszheim at comcast.net (Jeffrey Straszheim) Date: Sat, 06 Dec 2008 16:42:08 -0500 Subject: Can't get exclusive file lock when safely renaming a file In-Reply-To: <014a049b$0$20670$c3e8da3@news.astraweb.com> References: <014a049b$0$20670$c3e8da3@news.astraweb.com> Message-ID: <493AF1B0.9030802@comcast.net> Steven D'Aprano wrote: > I'm trying to safely rename a file without over-writing any existing > files, and I've run into a problem with file locks. Here's a naive way of > renaming without over-writing By default on a Linux filesystem, flock() gives you an _advisory_ lock. Other processes can touch the file unless they explicitly check the lock. Try man mount (see under the -o mand) and man fcntl (see under file locking) Jeffrey Straszheim From arnodel at googlemail.com Fri Dec 5 01:26:01 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 05 Dec 2008 06:26:01 +0000 Subject: Overriding a method at the instance level on a subclass of a builtin type References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> Message-ID: "Zac Burns" writes: > Ok. Feature request then - assignment of a special method name to an > instance raises an error. I haven't got the time to implement it, but I'm sure you can obtain the behaviour you want. -- Arnaud From mnordhoff at mattnordhoff.com Fri Dec 5 02:23:33 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Fri, 05 Dec 2008 07:23:33 +0000 Subject: generating a liste of characters In-Reply-To: <49369624.7020103@ncee.net> References: <49369624.7020103@ncee.net> Message-ID: <4938D6F5.30906@mattnordhoff.com> This is a slightly old post, but oh well... Shane Geiger wrote: > import string > alphabet=list(string.letters[0:26]) > print alphabet Most of the string module's constants are locale-specific. If you want the ASCII alphabet instead of the current language's, you need to use string.ascii_{letters,lowercase,uppercase}. > Yves Dorfsman wrote: >> Is there any built in way to generate a list of characters, something >> along the line of range('a'-'z') ? >> >> Right now I am using: >> >> chars = [ chr(l) for l in range(0x30, 0x3a) ] # 0 - 9 >> chars += [ chr(l) for l in range(0x41, 0x5b) ] # A - Z >> chars += [ chr(l) for l in range(0x61, 0x7b) ] # a - z >> >> Is there a better, more straight forward way of doing that ? >> >> >> >> Thanks. -- From vminch at gmail.com Sat Dec 13 10:50:26 2008 From: vminch at gmail.com (vk) Date: Sat, 13 Dec 2008 07:50:26 -0800 (PST) Subject: Netbeans Early Access and Python3 References: Message-ID: <04920acb-35e0-49da-8aaf-11c3c025977a@s1g2000prg.googlegroups.com> Netbeans is a very polished IDE. I just tried the Python EA plugin, however, and it does not have 3.x support as of now. From geekmail at usenot.de Thu Dec 4 05:11:15 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Thu, 4 Dec 2008 11:11:15 +0100 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> Message-ID: <20081204111115.7cee2ecc@usenot.de> On Wed, 03 Dec 2008 20:38:44 -0500 Lew wrote: > Xah Lee wrote: > > enough babble ... > > Good point. Plonk. Guun dun! > I vaguely remember you plonking the guy before. Did you unplonk him in the meantime? Or was that just a figure of speech? teasingly yours, /W -- My real email address is constructed by swapping the domain with the recipient (local part). From BrooklineTom at gmail.com Wed Dec 10 18:50:16 2008 From: BrooklineTom at gmail.com (brooklineTom) Date: Wed, 10 Dec 2008 15:50:16 -0800 (PST) Subject: Deeper tracebacks? References: Message-ID: <7e1c74f0-8f72-4a88-935b-90b77fe5aaa5@s37g2000vbp.googlegroups.com> On Dec 10, 5:03 pm, "Gabriel Genellina" wrote: > En Wed, 10 Dec 2008 16:59:16 -0200, brooklineTom > escribi?: > > > I want my exception handler to report the method that originally > > raised an exception, at the deepest level in the call-tree. Let give > > an example. > > That's the default behavior, you don't have to do anything special. > > > import sys, traceback > > class SomeClass: > > def error(self): > > """Raises an AttributeError exception.""" > > int(3).zork() > > > def perform_(self, aSelector): > > try: > > aMethod = getattr(self, aSelector, None) > > answer = apply(aMethod, [], {}) > > except: AttributeError, anAttributeErrorException: > > aRawStack = traceback.extract_stack() > > answer = None > > (I assume you're using Python < 3.0) > Use the 3-names form of the except statement: > > try: > aMethod = getattr(self, aSelector, None) > answer = aMethod() > except AttributeError, e, tb: > # the tb variable holds the traceback up to the error > # the same thing you see printed by Python when > # an unhandled error happens > answer = None > > Alternatively, you can obtain the same thing with sys.exc_info()[2] > Remember to delete any reference to the traceback object as soon as you're > done with it; seehttp://docs.python.org/library/sys.html#sys.exc_info > > -- > Gabriel Genellina I'm using Python 2.5. As I understand it, "aRawStack" (above) has the same information as sys.exc_info()[2]. The deepest entry in aRawStack is the perform_ invocation. The contents of the two bottom-most stack frames are: >>> aRawStack[8][3] "answer = anObject.perform_('error')" >>> aRawStack[9][3] 'aRawStack = traceback.extract_stack()' By the time the handler is called, "zork" -- the method that was called when the exception was raised, and "error", the method that invoked zork, have already been removed from the stack. In this example, I only show one call for simplicity. In practice, the method being invoked by perform_ may nest calls arbitrarily deeply. I know, by being in the exception handler, that an exception happened. What I need to know is which nested call raised it. From anurag.bagaria at gmail.com Tue Dec 23 04:53:03 2008 From: anurag.bagaria at gmail.com (ANURAG BAGARIA) Date: Tue, 23 Dec 2008 10:53:03 +0100 Subject: using subprocess module in Python CGI In-Reply-To: <47c890dc0812222200n26183303x717082b94010d250@mail.gmail.com> References: <47c890dc0812222200n26183303x717082b94010d250@mail.gmail.com> Message-ID: Thank you for the prompt response. Yeah, I missed out one line at the end of the error, the whole of which is: Traceback (most recent call last): File "process.py", line 18, in retval = subprocess.call(comd, 0, None, None, outptr, errptr) File "/usr/lib/python2.5/subprocess.py", line 443, in call return Popen(*popenargs, **kwargs).wait() File "/usr/lib/python2.5/subprocess.py", line 593, in __init__ errread, errwrite) File "/usr/lib/python2.5/subprocess.py", line 1135, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory Looking forward to any kind of help or suggestion in this regard. Thanks. On Tue, Dec 23, 2008 at 7:00 AM, Chris Rebert wrote: > On Mon, Dec 22, 2008 at 2:02 AM, ANURAG BAGARIA > wrote: > > Hello, > > > > I am a Python Newbie and would like to call a short python script via > > browser using a CGI script, but initially I am trying to call the same > > python script directly through python command line. The script intends to > > perform a few command line in a pipe and I have written the script (a > short > > one) as follows. > > > > #!/usr/bin/python > > > > import cgi, string, os, sys, cgitb, commands, subprocess > > import posixpath, macpath > > #file = "x.tar.gz" > > #comd = "tar -xf %s" % (file) > > #os.system(comd) > > #commands.getoutput('tar -xf x.tar.gz | cd demo; cp README ../') > > comd = [\ > > "tar -xf x.tar.gz", \ > > "cd demo", \ > > "cp README ../", \ > > ] > > outFile = os.path.join(os.curdir, "output.log") > > outptr = file(outFile, "w") > > errFile = os.path.join(os.curdir, "error.log") > > errptr = file(errFile, "w") > > retval = subprocess.call(comd, 0, None, None, outptr, errptr) > > errptr.close() > > outptr.close() > > if not retval == 0: > > errptr = file(errFile, "r") > > errData = errptr.read() > > errptr.close() > > raise Exception("Error executing command: " + repr(errData)) > > > > > > but after trying to execute this independently, I get the following error > > which I am unable to interpret : > > > > Traceback (most recent call last): > > File "process.py", line 18, in > > retval = subprocess.call(comd, 0, None, None, outptr, errptr) > > File "/usr/lib/python2.5/subprocess.py", line 443, in call > > return Popen(*popenargs, **kwargs).wait() > > File "/usr/lib/python2.5/subprocess.py", line 593, in __init__ > > errread, errwrite) > > File "/usr/lib/python2.5/subprocess.py", line 1135, in _execute_child > > raise child_exception > > There should be at least one more line in this traceback, and that > line is the most important one. > People will need that line to help you with your problem. > > Cheers, > Chris > > -- > Follow the path of the Iguana... > http://rebertia.com > -- I just want to LIVE while I'm alive. AB -------------- next part -------------- An HTML attachment was scrubbed... URL: From ajaksu at gmail.com Wed Dec 24 10:49:53 2008 From: ajaksu at gmail.com (ajaksu) Date: Wed, 24 Dec 2008 07:49:53 -0800 (PST) Subject: python web programming for PHP programmers References: Message-ID: <19270710-ba52-4d2c-bc19-7dad0c848aa5@y1g2000pra.googlegroups.com> On Dec 24, 12:40?pm, Nikola Skoric wrote: > I0m a python newbie with PHP background. I've tried to make a web app > from one of my python scripts (which I haven't done before) and I > ended up with: > > echo shell_exec("python foobar.py"); > ?> > which works really nice :-D Clever :) Python can work in a similar way to PHP if your server supports it, but Python also allows you to create the server itself. > For some reason I can't find no "quick and dirty python web > programming tutorial for PHP programmers" on google. :-D I don't need > a general python tutorial, I just need a tutorial on how to make a > hello world server side script with python. Any suggestions? See http://webpython.codepoint.net/cgi_hello_world for a very primitive way (and docs here: http://docs.python.org/dev/library/cgi.html ). A better way, that uses a trivial Python-based server: hello.py --- from wsgiref.simple_server import make_server def hello_app(environ, start_response): start_response("200 OK", [('Content-Type','text/plain')]) return "Hello world!" httpd = make_server('', 8000, hello_app) print "Serving HTTP on port 8000..." httpd.serve_forever() --- Then: $ python hello.py Serving HTTP on port 8000... localhost - - [24/Dec/2008 13:11:32] "GET / HTTP/1.1" 200 12 (see http://docs.python.org/dev/library/wsgiref.html#module-wsgiref.simple_server ) You can use better Python-based servers with handy features for testing: http://projects.wagner-flo.net/wsgi-serve/ http://pypi.python.org/pypi/James/0.7.1 Now, to ease things, you can have Python working more like PHP. First, server support. What HTTP server are you using? For starting up, mod_python (http://www.modpython.org/) isn't that bad, but there are better alternatives: http://code.google.com/p/modwsgi/ , http://pypi.python.org/pypi/python-fastcgi/1.1 and http://python.ca/scgi/ Then, there are many ways of getting the PHP feel (embedding in pages, etc.): http://www.modpython.org/live/current/doc-html/pyapi-psp.html#pyapi-psp http://nick.borko.org/pse/examples/php_example.html http://snakelets.sourceforge.net/ (development stopped) http://www.webwareforpython.org/PSP/Docs/index.html HTH, Daniel From timr at probo.com Wed Dec 31 02:43:04 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 31 Dec 2008 07:43:04 GMT Subject: multiprocessing vs thread performance References: Message-ID: Christian Heimes wrote: > >You have missed an important point. A well designed application does >neither create so many threads nor processes. The creation of a thread >or forking of a process is an expensive operation. That actually depends on the operating system. As one example, thread creation on Windows is not all that expensive. >You should use a pool of threads or processes. Even so, this is good advise. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From bakul+usenet at bitblocks.com Wed Dec 10 19:12:02 2008 From: bakul+usenet at bitblocks.com (Bakul Shah) Date: Wed, 10 Dec 2008 16:12:02 -0800 Subject: Mathematica 7 compares to other languages In-Reply-To: <49404775$0$4893$607ed4bc@cv.net> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> Message-ID: <49405AD2.7010207@bitblocks.com> John W Kennedy wrote: > Xah Lee wrote: >> In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, >> you'll have 50 or hundreds lines. > > C: > > #include > #include > > void normal(int dim, float* x, float* a) { > float sum = 0.0f; > int i; > float divisor; > for (i = 0; i < dim; ++i) sum += x[i] * x[i]; > divisor = sqrt(sum); > for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; > } > > Java: > > static float[] normal(final float[] x) { > float sum = 0.0f; > for (int i = 0; i < x.length; ++i) sum += x[i] * x[i]; > final float divisor = (float) Math.sqrt(sum); > float[] a = new float[x.length]; > for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor; > return a; > } > > q){x%sqrt sum x}3 4 0.6 0.8 From wtanksleyjr at gmail.com Mon Dec 8 19:43:31 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Mon, 8 Dec 2008 16:43:31 -0800 (PST) Subject: Guido's new method definition idea References: Message-ID: <06f8131b-ba72-4f65-a8c9-cc36b0fb586f@x14g2000yqk.googlegroups.com> On Dec 5, 6:21?pm, "Daniel Fetchinson" wrote: > I'd like this new way of defining methods, what do you guys think? > Anyone ready for writing a PEP? I think it's an awesome proposal. It's about time! With this change, defining methods uses the same special syntax hack that calling them does. This is a good thing because it makes it easy to refer to methods consistently. I see a lot of people are against it; I admit that it's not the status quo, but that's not a sufficient argument against a change (it defeats all possible changes). A more interesting argument against it is that it's special "implicit" syntax; but I would argue that it merely reflects the existing special syntax of method calls. Unfortunately, writing a PEP is sadly outside my skillset. > Daniel -Wm From zaz600 at gmail.com Fri Dec 26 22:52:50 2008 From: zaz600 at gmail.com (NoName) Date: Fri, 26 Dec 2008 19:52:50 -0800 (PST) Subject: SyntaxError: encoding problem: with BOM References: <6res8tF1do1sU1@mid.uni-berlin.de> <400f176b-bd9a-4f26-b01b-1aa7c7dcf5ac@z6g2000pre.googlegroups.com> <6rf6m1F1e0f8U1@mid.uni-berlin.de> <26e21f3f-ded1-48ca-8897-2ebd05dd07ad@w39g2000prb.googlegroups.com> Message-ID: <42a1d835-76d8-4b9e-b76e-c9853d4df25e@c36g2000prc.googlegroups.com> On 26 ???, 23:08, "Gabriel Genellina" wrote: > En Thu, 25 Dec 2008 11:55:16 -0200, NoName escribi?: > > > Error > > ---- > > C:\Documents and Settings\Ra\??????? ????>11.py > > File "", line 1 > > SyntaxError: encoding problem: with BOM > > > No error > > ---- > > C:\Documents and Settings\Ra\??????? ????>python 11.py > > test > > > Error when russian symbols in full path to py-script. > > Is it Python bug? or i need to modify some registry keys? > > Yes, it's a bug. The encoding declaration may be anything, ascii, even an > inexistent codec will trigger the bug. Any non-ascii character in the > script name or path provokes then a SyntaxError when the script is > executed directly. > As a workaround, avoid using any Russian characters in directory names or > script file names, or invoke them always using "python xxx.py", not > directly. > > > OS: WinXP SP3 Russian. > > Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit > > (Intel)] on win32 > > My tests were on WinXP SP3 Spanish. > Seehttp://bugs.python.org/issue4747 > > -- > Gabriel Genellina Gabriel Genellina, thanks for bug report =) From pruebauno at latinmail.com Tue Dec 30 12:16:08 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Tue, 30 Dec 2008 09:16:08 -0800 (PST) Subject: SQL, lite lite lite References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> Message-ID: <8da5c6b1-951f-4abd-8ee7-07b63802b9f6@13g2000yql.googlegroups.com> On Dec 29, 1:06?pm, Aaron Brady wrote: > Hi all, > > About a year ago, I posted an idea I was having about thread > synchronization to the newsgroup. ?However, I did not explain it well, > and I really erred on the side of brevity. ?(After some finagling, Mr. > Bieber and I decided it wasn't exactly anything groundbreaking.) ?But > I think the brevity cost me some readers, who might have had more > interest. ?The affair was on the whole discouraging. ?So, I'm going to > try another idea, and assume that readers have some time, and will > spend it on it. > > I don't think relational data can be read and written very easily in > Python. ?There are some options, such as 'sqllite3', but they are not > easy. ?'sqllite3' statements are valid SQL expressions, which afford > the entire power of SQL, but contrary to its name, it is not that > 'lite'. ?To me, 'lite' is something you could learn (even make!) in an > afternoon, not a semester; something the size of an ActiveState > recipe, or a little bigger, maybe a file or two. ?If you think SQL is > a breeze, you probably won't find my idea exciting. ?I assume that the > basics of SQL are creating tables, selecting records, and updating > records. > > My idea is to create a 'Relation' class. ?The details are basically > open, such as whether to back it with 'sqllite3', 'shelve', 'mmap', or > just mapping and sequence objects; what the simplest syntax is that > can capture and permit all the basics, and how much and what else can > fit in at that level; how and whether it can include arbitrary Python > objects, and what constraints there are on them if not; how and > whether to permit transactions; and what the simplest and coolest > thing you can do with a little Python syntax is. > > This is basically an invitation for everyone to brainstorm. ?(No > hijackings, good humor & digression ok.) ?Lastly, ... > > **warning, spoiler! ?here's what I thought of already.** > > **repeat! ?spoiler! ?here's what I thought of already.** > > #Just the select and update syntax: > > >>> a= people._select( "firstname== 'Joe'" ) > > #select 'key' from 'people' where 'firstname'== 'joe'>>> a > > [Entry2864, Entry3076, Entry3172]>>> entry1= a[ 0 ] > >>> entry1.phone > > #select 'phone' from 'people' where 'key'==self.key > "555-2413">>> entry1.phone= "555-1234" > > #update 'people' set 'phone'= '555-1234' where 'key'==self.key>>> entry1.phone > > "555-1234" > > #Create table syntax (a-whole-nother beast in itself): > > >>> classes= db.Relation( 'class_', 'person', Unique( 'class_', 'person' ) ) > > #create table 'classes' ( 'key', 'class_', 'person' ) unique > ( 'class_', 'person' ) > > >>> classes._unique( 'class_', 'person' ) > >>> classes.class_.noneok= False #'class_' cannot be null > >>> classes.person.noneok= False > >>> classes._insert( 'Physics', 'Dan' ) > >>> classes._insert( 'Chem', 'Tim' ) > > Hoping-"good critic"-is-self-consistent-ly, hoping-to-hear-it's-too- > complicated-already-ly, > A. Brady You really do like to reinvent the wheels do you? :-) Nothing wrong with that. Just be aware that most people that really need what you are proposing are probably already using mature feature rich libraries for that. http://wiki.python.org/moin/HigherLevelDatabaseProgramming From Scott.Daniels at Acm.Org Fri Dec 26 17:15:00 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 26 Dec 2008 14:15:00 -0800 Subject: strange behavior of math.sqrt() in new 3.0 version In-Reply-To: References: Message-ID: David Lemper wrote: > I'm a newbee trying 3.0 Please help with math.sqrt() > > At the command line this function works correctly > >>> import math > n = input("enter a number > ") > s = math.sqrt(n) > An entry of 9 or 9.0 will yield 3.0 > Yet the same code in a script gives an error message > Script1 > import math > n = input("enter a number > ") > s = math.sqrt(n) > ... TypeError : a float is required > > Strangely the above code runs fine in version 2.5 ( ? ) ... OK, here's what's going on: "at the command line" in 2.X, the builtin function input reads a string and returns the eval of that string. This is a bit of a safety issue. I suspect when "it worked from the command line," you were using a 2.X command line inadvertently. in 2.X, you'll get similar errors if you use "raw_input" instead of "input". The "input" function in 3.0 is the same as the "raw_input" function in 2.X. I would suggest using: import math value = float(input("enter a number > ")) root = math.sqrt(value) print('root(%s) == %s' % (value, root)) I avoid using single-letter variables except where I know the types from the name (so I use i, j, k, l, m, n as integers, s as string, and w, x, y, and z I am a little looser with (but usually float or complex). --Scott David Daniels Scott.Daniels at Acm.Org From steve at REMOVE-THIS-cybersource.com.au Sat Dec 20 20:49:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Dec 2008 01:49:45 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <015d9804$0$20656$c3e8da3@news.astraweb.com> On Sat, 20 Dec 2008 15:27:43 -0800, walterbyrd wrote: > On Dec 19, 10:25?am, Michael Torrie wrote: > >> Personally the new string formatter is sorely needed in Python. > > Really? You know, it's funny, but when I read problems that people have > with python, I don't remember seeing that. Loads of people complain > about the white space issue. Some people complain about the speed. Lots > of complaints about certain quirky behavior, but I have not come across > any complaints about the string formatting. There are some things that some people whinge about, often just to hear the sound of their own voice (or the look of their own font, if you prefer). Whitespace and speed are two of those: they attract trolls and sooks. (That's not to say that there aren't real problems related to them. But it seems to me that the real problems are drowned out by the trolls.) Then there are things that people don't complain about, they just shrug and code a work-around. If % doesn't do what you want, do you cry about it, or do you code around it? I can't speak for others, but what I did was ask the question, discover that % was not powerful enough, and coded around it: http://mail.python.org/pipermail/python-list/2006-April/376641.html > In fact, from what I have seen, many of the "problems" being "fixed" > seem to be non-problems. > > I dunno, maybe it's just me. It's just you. Sheesh, I've never seen such a bunch of cry-babies sooking that their favourite language just got *more* power and flexibility. If functionality was being removed, I could understand the response, but this? It's just crazy. -- Steven From benjamin.kaplan at case.edu Fri Dec 12 15:59:36 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 12 Dec 2008 15:59:36 -0500 Subject: Umlauts in idle In-Reply-To: <26880ecf-d0eb-42ab-8ebd-56f64c023999@v39g2000pro.googlegroups.com> References: <26880ecf-d0eb-42ab-8ebd-56f64c023999@v39g2000pro.googlegroups.com> Message-ID: On Fri, Dec 12, 2008 at 3:51 PM, a_olme wrote: > Hello all, > > When I try to use umlauts in idle it will only print out as Unicode > escape characters. Is it possible to configure idle to print them as > ordinary characters? > Best Regards Anders Olme Make sure you are using Unicode strings and not byte strings. This is why Python 3 switched to using Unicode by default. IDLE 2.6.1 on Mac 10.5 : >>> print u'\u00c4' ? >>> print '\u00c4' \u00c4 > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From muhamed.hmd at gmail.com Tue Dec 9 16:06:22 2008 From: muhamed.hmd at gmail.com (john adam) Date: Tue, 9 Dec 2008 13:06:22 -0800 (PST) Subject: conratulations....... Message-ID: conratulatios...... Here's my dear friend largest mobile library programs All you care programs : Witness all the programs in the modern world Alkmiotr Honored by your visit You'll see in the blogger 1.If you are suffering from a virus protection programs most important to you AVG Anti-Virus Free Edition "avG" http://mesotheliomame.blogspot.com/2008/11/pericardial-mesothelioma-and-modern.html 2.If you turn suffering from transmitting the files LimeWire Pro 4.14.7 http://mesotheliomame.blogspot.com/2008/11/overview-of-mesothelioma-cancer.html 3.If you have files you spy on your computer solution Ad-Aware 2008 http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawsuits-faq.html 4.You stronger virus program Ante 2008 Avira AntiVir Personal - Free Antivirus http://mesotheliomame.blogspot.com/2008/11/number-form-of-mesothelioma-pleural.html 5.Now a program of protection and anti-virus and anti-spy files Avast Home Edition http://mesotheliomame.blogspot.com/2008/11/what-to-look-for-in-california.html 6.If you are suffering from non-fast you download this program FrostWire http://mesotheliomame.blogspot.com/2008/11/if-you-are-diagnosed-with-mesothelioma_15.html 7.If you have difficulty loading of the Diaspora and Google Orbit Downloader http://mesotheliomame.blogspot.com/2008/11/if-you-are-diagnosed-with-mesothelioma.html 8.If you have difficulty difficult compression "file" winrar http://mesotheliomame.blogspot.com/2008/11/contacting-mesothelioma-lawyer.html 9.If you are suffering from aAdware/Malware files you solution Malwarebytes' Anti-Malware http://mesotheliomame.blogspot.com/2008/11/scientists-conduct-clincial-trials-of.html 10.Now the most powerful video chat in the world Camfrog Video Chat http://mesotheliomame.blogspot.com/2008/11/new-drug-study-for-abdominal.html 11.Program chat world is a lot mIRC http://mesotheliomame.blogspot.com/2008/11/ohio-mesothelioma-lawyer-help-you-get.html 12.If you have difficulty reading flv files FLV Player http://mesotheliomame.blogspot.com/2008/11/detailed-information-on-mesothelioma.html 13.If you have difficulty download from youtube YouTube Downloader http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawyers-in-high-demand.html 14.If you are suffering from penetrating the strongest program you repel breakthroughs in the world Spybot - Search & Destroy http://mesotheliomame.blogspot.com/2008/11/chemotherapy-treatment-for-mesothelioma.html 15.If you have difficulty with the way they spread the images IrfanView http://mesotheliomame.blogspot.com/2008/11/california-mesothelioma-laws-and.html 16.Now have a major program of the torrent file and upload files BitComet http://mesotheliomame.blogspot.com/2008/11/facing-mesothelioma-without-california.html 17.The program is exclusive download from the Web at high speed Download Accelerator Plus http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-diagnoses-increase_15.html 18.If you are suffering from problems with the performance of the solution you Smart Defrag http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-diagnoses-increase.html 19.If you have difficulty in performing the solution you Advanced WindowsCare Personal http://mesotheliomame.blogspot.com/2008/11/mesothelioma-is-deadly-cancer.html 20.If you have difficulty in operating the sound and video files you solution real player http://mesotheliomame.blogspot.com/2008/11/facts-and-misconceptions-about.html 21.Here is the most important video player program in America GOM Media Player http://mesotheliomame.blogspot.com/2008/11/how-severe-is-mesothelioma-disease.html 22.If you have difficulty operating Flash Games Flash Player http://mesotheliomame.blogspot.com/2008/11/glimpse-at-mesothelioma-info-from-past.html 23.If you have difficulty in cleaning Riggstir professionally you the best solution http://mesotheliomame.blogspot.com/2008/11/detection-of-asbestos-mesothelioma.html 24.If you turn suffering from your computer and the difficulty you download this program"System Mechanic" http://mesotheliomame.blogspot.com/2008/11/brief-overview-of-malignant.html 25.If you are suffering from problems in the cleaning solution you Riggstir http://mesotheliomame.blogspot.com/2008/11/mesothelioma-and-911.html 26.Use the latest hour computer in the world in the magnificence of beauty http://mesotheliomame.blogspot.com/2008/11/precise-idea-about-pericardial.html 27.If you have difficulty in maintaining from hard disk http://mesotheliomame.blogspot.com/2008/11/mesothelioma-at-glance.html 28.If you have difficulty in managing personal and protection of your system you program http://mesotheliomame.blogspot.com/2008/11/financial-burden-of-mesothelioma.html 29.If you have difficulty in recording data and operation of your system http://mesotheliomame.blogspot.com/2008/11/how-to-find-mesothelioma-lawyer.html 30.Here's this program that offers you much time http://mesotheliomame.blogspot.com/2008/11/hurricane-victims-at-risk-for.html 31.If you have difficulty in browsing files http://mesotheliomame.blogspot.com/2008/11/3-top-florida-mesothelioma-lawyer.html 32.Here's this program, which automatically corrects the mistakes of your system security http://mesotheliomame.blogspot.com/2008/11/if-diagnosed-with-mesothelioma-call.html 33.The enjoyment of this program to register images from camera to the computer during the talk http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-diagnosed-questions.html 34.If you have difficulty transforming stretches in games or votes you this giant http://mesotheliomame.blogspot.com/2008/11/mesothelioma-ready-reckoner.html 35.If you have difficulty in operation all formats video files http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawyers-how-to-choose-them.html 36.If you have difficulty in the organization and ease of cleaning solution you http://mesotheliomame.blogspot.com/2008/11/mesothelioma-exposure-could-be-fatal.html 37.Very popular program in the compression winzip http://mesotheliomame.blogspot.com/2008/11/mesothelioma-greed-cancer-profits.html 38..If you want to broadcast material on the Internet you solution Virtual DJ Software http://mesotheliomame.blogspot.com/2008/11/abc-mesothelioma-new-treatments-for.html 39.now The creation of program files pdf PrimoPDF http://mesotheliomame.blogspot.com/2008/11/abc-mesothelioma-treatments-for.html 40..If you have difficulty operating the extensions you solution "MPEG-1, MPEG-2, MPEG-DivX, mp3, ogg VLC Media Player http://mesotheliomame.blogspot.com/2008/11/brachytherapy-for-treatment-of.html 41.If you have difficulty browser you this treasure Mozilla Firefox http://mesotheliomame.blogspot.com/2008/11/asbestos-mesothelioma-treatment-how.html 42.If you are difficult to clean your computer you solution Glary Utilities http://mesotheliomame.blogspot.com/2008/11/mesothelioma-treatment-research.html 43.very Free program to repair and improve and see photos PhotoScape http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-history.html 44.If you have difficulty operating films and cartoons BS.Player http://mesotheliomame.blogspot.com/2008/11/mesothelioma-attorney.html 45.Conversion formulas giant cylinders to the chimerical not want the program ... PowerISO http://mesotheliomame.blogspot.com/2008/11/deadly-mesothelioma-symptoms-could-be_15.html 46.You program the operator of high-quality video DivX for Windows with DivX Player http://mesotheliomame.blogspot.com/2008/11/deadly-mesothelioma-symptoms-could-be.html 47.If you have difficulty copies of CDs nero "9"new http://mesotheliomame.blogspot.com/2008/11/association-of-asbestos-and.html 48.If you have difficulty audio chat on the net you the solution Windows Live Messenger http://mesotheliomame.blogspot.com/2008/11/need-for-mesothelioma-lawyer-to-fight.html 49.If you have difficulty download on the net ActiveX Download Control http://mesotheliomame.blogspot.com/2008/11/funding-for-mesothelioma-research-noble_15.html 50.If you have difficulty in registration at the sites and forums you solution RoboForm http://mesotheliomame.blogspot.com/2008/11/funding-for-mesothelioma-research-noble.html 51.If you are an amateur or design you a solution designed sites you Adobe Photoshop CS3 Extended http://mesotheliomame.blogspot.com/2008/11/brief-overview-of-peritoneal.html 52.If you have difficulty cleaning you stronger cleaning program in the world ccleaner http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawyers-helping-hands.html 53.If you have difficulty in Alturrent know what files you need them all uTorrent http://mesotheliomame.blogspot.com/2008/11/how-to-proceed-with-mesothelioma_15.html 54.If you have difficulty in loading files from the iPod Lalai iTunes http://mesotheliomame.blogspot.com/2008/11/how-to-proceed-with-mesothelioma.html 55.If you have difficulty converting audio files to any formulas you solution Easy CD-DA Extractor http://mesotheliomame.blogspot.com/2008/11/difference-between-pleural-and.html 56.If you have difficulty converting video files to the formula psp PSP Video 9 http://mesotheliomame.blogspot.com/2008/11/positive-guideline-to-deal-with.html 57.If you have difficulty in the work of videos from YouTube to evict you like you solution Windows Movie Maker http://mesotheliomame.blogspot.com/2008/11/history-of-asbestos-related.html 58.If you have difficulty in Works with all audio files extranet windows media player http://mesotheliomame.blogspot.com/2008/11/tips-on-choosing-your-mesothelioma.html 59.If you have difficulty in Browser you the most powerful browser in the world Avant Browse http://mesotheliomame.blogspot.com/2008/11/good-mesothelioma-attorney-is-hard-to.html 60.If you have difficulty in Video-sharing to you this wonderful program BearFlix http://mesotheliomame.blogspot.com/2008/11/peritoneal-mesothelioma-information.html 61.If you have difficulty in Survey of spyware on your computer SpywareBlaster http://mesotheliomame.blogspot.com/2008/11/how-to-care-for-someone-with.html 62.If you are suffering from problems in Alhard Disek you this legend smart PerfectDisk http://mesotheliomame.blogspot.com/2008/11/why-is-mesothelioma-so-deadly.html 63.If you have difficulty in the liberation of files "pdf" http://mesotheliomame.blogspot.com/2008/11/when-do-you-need-mesothelioma-attorney.html 64.If you have difficulty in personal control of your system next to you http://mesotheliomame.blogspot.com/2008/11/all-about-mesothelioma-lawyer.html 65.If you have difficulty in the key to jump easily be you next http://mesotheliomame.blogspot.com/2008/11/what-is-mesothelioma-cancer.html 66.If you have difficulty playing in the pictures and the amendment http://mesotheliomame.blogspot.com/2008/11/mesothelioma-information.html 67.If you have difficulty in protecting your system security followed CAPS http://mesotheliomame.blogspot.com/2008/11/symptoms-of-mesothelioma.html 68.If you have difficulty in speed of your computer you this program http://mesotheliomame.blogspot.com/2008/11/what-radical-mesothelioma-treatments.html 69.If you have difficulty maintaining a malfunction in your computer that you legend http://mesotheliomame.blogspot.com/2008/11/can-washington-mesothelioma-attorneys.html 70.If you have difficulty in the transfer of files between disks http://mesotheliomame.blogspot.com/2008/11/causes-of-mesothelioma-cancer.html 71.Discovered the most important program on the Web EZ Macros http://mesotheliomame.blogspot.com/2008/11/mesothelioma-treatment-radiation-or.html 72.If you are suffering from similar files, you repeat this unique program http://mesotheliomame.blogspot.com/2008/11/types-of-mesothelioma-cancer.html http://mesotheliomame.blogspot.com/ From fetchinson at googlemail.com Wed Dec 10 18:11:35 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 10 Dec 2008 15:11:35 -0800 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <20081226055859.604@gmail.com> Message-ID: On 12/10/08, Jon Harrop wrote: > Xah Lee wrote: >> Kaz Kylheku wrote: >>> Really? ``50 or hundreds'' of lines in C? >>> >>> #include /* for sqrt */ >>> >>> void normalize(double *out, double *in) >>> { >>> double denom = sqrt(in[0] * in[0] + in[1] * in[1] + in[2] * >>> in[2]); >>> >>> out[0] = in[0]/denom; >>> out[1] = in[1]/denom; >>> out[2] = in[2]/denom; >>> } >>> >>> Doh? >> >> Kaz, pay attention: >> >> Xah wrote: ?Note, that the "norm" as defined above works for vectors >> of any dimention, i.e. list of any length.? > > That is still only 6 lines of C code and not 50 as you claimed: > > double il = 0.0; > for (int i=0; i il += in[i] * in[i]; > il = 1.0 / sqrt(il); > for (int i=0; i out[i] = il * in[i]; > > Try computing the Fourier transform of: > > 0.007 + 0.01 I, -0.002 - 0.0024 I Funniest thread ever! Actual real money changing hands, did this happen ever in a newsgroup? Xah Lee rulez! Xah Lee for president! (No kidding, I like the guy.) Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From rt8396 at gmail.com Thu Dec 25 13:42:36 2008 From: rt8396 at gmail.com (r) Date: Thu, 25 Dec 2008 10:42:36 -0800 (PST) Subject: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> <90f06b27-39da-4f1a-a878-f3972e942d57@s24g2000vbp.googlegroups.com> <62caf93b-0455-4450-9895-8a9d9554f75e@r32g2000vba.googlegroups.com> <1isezkk.51e05y1457jqrN%pdorange@pas-de-pub-merci.mac.com> <3cb2a746-1a43-44a1-9825-7667af9fe2fa@s1g2000prg.googlegroups.com> <1isi4sn.11mpft612g7udcN%pdorange@pas-de-pub-merci.mac.com> Message-ID: On Dec 25, 4:22?am, pdora... at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) wrote: > r wrote: > > 220 ratings and 1 star, WHOOOO!. I find this all quite amusing :D. > > Keep em coming. Oh, and FYI, I will always have 1 star! hahahahahha > > > ? ? ? ? ? ? ? ? ? ?/"\ > > ? ? ? ? ? ? ? ? ? ? |\./| > > ? ? ? ? ? ? ? ? ? ? | ? | > > ? ? ? ? ? ? ? ? ? ?| ? | > > ? ? ? ? ? ? ? ? ? ? |>~<| > > ? ? ? ? ? ? ? ? ? ? | ? | > > ? ? ? ? ? ? ? ? ?/'\| ? |/'\ > > ? ? ? ? ? ? ?/~\| ? | ? | ? |__ > > ? ? ? ? ? ? | ? | ? } ? | ? | ?\ > > ? ? ? ? ? ? | ? | ? | ? | ? | ? \ > > ? ? ? ? ? ?| ~ ? ~ ? ~ ? ~ |` ? ) > > ? ? ? ? ? ? | ? ? ? ? ? ? ? ? ? / > > ? ? ? ? ? \ ? ? ? ? ? ? ? ? ?/ > > ? ? ? ? ? ? ? \ ? ? ? ? ? ? ? / > > ? ? ? ? ? ? ? ?\ ? ?____ ? ? / > > ? ? ? ? ? ? ? ? |--//''`\--| > > ? ? ? ? ? ? ? ? | (( +==)) | > > ? ? ? ? ? ? ? ? |--\_|_//--| > > Very nice indeed, but you forget ascii art need a fixed font... > > -- > Pierre-Alain Dorange > > Ce message est sous licence Creative Commons "by-nc-sa-2.0" > ? ? ? ? Go to Google groups... it looks perfect :) From max at alcyone.com Sat Dec 6 19:36:15 2008 From: max at alcyone.com (Erik Max Francis) Date: Sat, 06 Dec 2008 16:36:15 -0800 Subject: Guido's new method definition idea In-Reply-To: <8b8d1fb3-f49e-49bf-8cfe-eeee5ed16109@r37g2000prr.googlegroups.com> References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> <8b8d1fb3-f49e-49bf-8cfe-eeee5ed16109@r37g2000prr.googlegroups.com> Message-ID: Russ P. wrote: > On Dec 6, 4:32 am, Andreas Waldenburger wrote: >> But that is not the way Python is meant to work. There are several >> tennets in the Zen of Python that don't chime well with this approach. >> "self" is a speaking identifier, "$" isn't. > > Is "@" a "speaking identifier? How about "#" and "!="? Last I heard, > they were all part of Python. None of these are identifiers at all. You might want to read up on the language reference to see what an identifier actually is. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis There are not fifty ways of fighting, there is only one: to be the conqueror. -- Andrew Malraux, 1937 From ndbecker2 at gmail.com Thu Dec 18 13:35:33 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 18 Dec 2008 13:35:33 -0500 Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> Message-ID: Mel wrote: > Neal Becker wrote: > >> Tino Wildenhain wrote: >> >>> Neal Becker wrote: >>>> Reading some FAQ, I see that __str__ is "meant for human eyes". >>>> >>>> But it seems that: >>>> class X(object): >>>> def __str__(self): >>>> return "str" >>>> def __repr__(self): >>>> return "repr" >>>> >>>> x = X() >>>> d = {0 : x} >>>> print d >>>> {0: repr} >>>> >>>> So if __str__ is "meant for human eyes", then why isn't print using it! >>> >>> it is: >>> >>> > print x >>> str >>> >>> but dict just uses repr() for all its childs to print. >>> >>> T. >> That makes no sense to me. If I call 'print' on a container, why >> wouldn't >> it recursively print on the contained objects? Since print means call >> str, printing a container should recursively call str on the objects. > > Basically because there are too many right ways to format the resulting > report. Space separated? Tab separated? One per line? Boxes around > them? As HTML definition lists? Creating a standard report form would > take a lot of work and wouldn't, finally, solve very many peoples' > problems. > > Mel. > Thanks, but the question of how to format the container is different from how to format the primitive elements of the container. I was suggesting that printing an element of a container should be consistent with printing the element without the container, i.e., print [a] should be consistent with print a From bruno.42.desthuilliers at websiteburo.invalid Fri Dec 12 06:56:16 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 12 Dec 2008 12:56:16 +0100 Subject: (Very Newbie) Problems defining a variable In-Reply-To: References: Message-ID: <49425146$0$8495$426a74cc@news.free.fr> febaen at gmail.com a ?crit : > #!/usr/bin/python > #Py3k, UTF-8 > > bank = int(input("How much money is in your account?\n>>")) > target = int(input("How much money would you like to earn each year? > \n>>")) > > interest = 0 > i = 0 > > while interest < target: > #determine the interest rate to use > if bank >= 9999: > rate = 0.006 > elif bank >= 10000 and bank <= 24999: > rate = 0.0085 > elif bank >= 25000 and bank <= 49999: > rate = 0.0124 > elif bank >= 50000 and bank <= 99999: > rate = 0.0149 > elif bank >= 100000: > rate = 0.0173 (snip) > I'm pretty certain that that is also the problem in the code. I'm > pretty sure it's a problem with the 'if' statements', and it looks > like it's one of those mistakes that's so simple you look back on it > and laugh at yourself. If you put in a bank number <= 9999, it fails, > saying "NameError: name 'rate' is not defined". If you put in one > higher, it runs correctly, but thinks that the rate is 0.006 Indeed. That's what you asked for. If bank is >= 9999, then rate will be set to 0.006, and the following tests will be skipped. Else - since you just don't handle the case -, rate is not defined at all. I guess you wanted your first test to be: if bank <= 9999: ... FWIW, when using if/elif that way, make sure you always end with a "default" else clause (even if just to signal you didn't expect to be there...) HTH From sonynamratha2009 at gmail.com Wed Dec 24 15:33:34 2008 From: sonynamratha2009 at gmail.com (sony) Date: Wed, 24 Dec 2008 12:33:34 -0800 (PST) Subject: mobiles Message-ID: Excellent Mobiles(Latest) http://latestmobii.blogspot.com/2008/11/blackberry-8800.html http://latestmobii.blogspot.com/2008/11/sony-ericsson-z555i.html http://latestmobii.blogspot.com/2008/11/motorola.html http://latestmobii.blogspot.com/2008/11/samsung.html http://latestmobii.blogspot.com/2008/11/nokia-7380-coming-soon.html http://latestmobii.blogspot.com/2008/11/sony-ericsson-xperia-x1.html http://latestmobii.blogspot.com/2008/11/nokia-8800.html From jason.scheirer at gmail.com Thu Dec 18 13:51:08 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Thu, 18 Dec 2008 10:51:08 -0800 (PST) Subject: Is this pythonic? References: <66d058f9-cfe1-4b3c-ab8a-e6e88bb97770@m22g2000vbp.googlegroups.com> <7dc03d4b-4bce-4cc4-b020-681935cf0b0b@m4g2000vbp.googlegroups.com> Message-ID: On Dec 18, 8:45?am, prueba... at latinmail.com wrote: > On Dec 18, 11:08?am, ipyt... at gmail.com wrote: > > > x.validate_output(x.find_text(x.match_filename > > (x.determine_filename_pattern(datetime.datetime.now())))) > > > Is it even good programming form? > > Lisp and Scheme programmers love that style. You can tell by the > number of parentheses :-). In Python people usually use an > intermediate variable to break things up a bit but the amount of > acceptable nesting is a matter of personal style. I'd say it's fine but breaking up the statement once or twice is a good idea just because if one of the function calls in this nested thing throws an exception, a smaller statement with fewer calls makes for a far more readable traceback. And I hope that this whole statement all lives inside of a method in the same x class, or is a higher-level class that makes use of this behavior? If not, you may want to consider doing so. class X(object): @property def todays_filepattern(self): return self.match_filename( self.determine_filename_pattern( datetime.datetime.now())) def validate_todays_files(self): return self.validate_output(self.find_text (self.todays_filepattern)) From metolone+gmane at gmail.com Fri Dec 26 02:16:21 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Thu, 25 Dec 2008 23:16:21 -0800 Subject: How to display Chinese in a list retrieved from database via python References: <22be506d-91c2-4727-ace7-2e3382b6d214@g3g2000pre.googlegroups.com> <979fdf6d-0500-47ba-87fd-0f0361ca3059@p2g2000prf.googlegroups.com> Message-ID: "zxo102" wrote in message news:979fdf6d-0500-47ba-87fd-0f0361ca3059 at p2g2000prf.googlegroups.com... > On 12?26?, ??4?58?, "Gabriel Genellina" > wrote: >> En Thu, 25 Dec 2008 07:27:03 -0200, zxo102 escribi?: >> >> >> >> > On 12?25?, ??3?35?, "Chris Rebert" wrote: >> >> On Wed, Dec 24, 2008 at 11:29 PM, zxo102 wrote: >> >> > Hi, >> >> > I retrieve some info in Chinese from postgresql and assign it to >> >> > a >> >> > variable 'info' defined in javascript of a html page: >> >> > var info = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce >> >> > \xc4'] >> >> > But I want it to be >> >> > var info = ['??','??','??'] >> >> > since in html pages (via javascript), the items in chinese out of >> >> > the >> >> > former :['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4'] >> >> > can >> >> > not be displayed correctly when it is inserted into a html page. If >> >> > the list is var info = ['??','??','??'] , then everything >> >> > works >> >> > fine. >> >> > The html code is as follows >> >> > test >> > >> > >> >> > But the '??' is '\xd6\xd0\xce\xc4'. When row01 and row02 is called >> > from somewhere, >> > '\xd6\xd0\xce\xc4' can not be displayed correctly as '??' in html >> > environment. >> >> You forgot to specify the page encoding, gb2312 presumably. If adding the >> encoding does not help, I'd say the problem must reside on how you later >> use row01 and row02 (your html page does not those variables for >> anything). '??' is the same as '\xd6\xd0\xce\xc4', and both javascript >> and Python share the same representation for strings (mostly) so this >> should not be an issue. >> >> My PC is unable to display those characters, but I get "true" from this: >> >> test >> >> >> -- >> Gabriel Genellina > > I did that: , but it does not work. Alert('\xd6\xd0\xce\xc4') >> displays some "junks". I am thinking there may be some way to convert >> '\xd6\xd0\xce\xc4' to '??' in the list with python before I generate >> the html page. As a result, when I open the html file with Vi, I can see >> '??' directly instead of '\xd6\xd0\xce\xc4'. That will solve my >> problem. > > Any ideas? Use charset=gb2312 instead of charset='gb2312'(remove single quotes). I was able to display ?? successfully with this code: f=open('test.html','wt') f.write(''' test \xd6\xd0\xce\xc4''') f.close() -Mark From gdamjan at gmail.com Tue Dec 16 19:10:44 2008 From: gdamjan at gmail.com (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Wed, 17 Dec 2008 01:10:44 +0100 Subject: mod_python resources References: <78064e7e-ba2c-4959-b5f8-4d1b928bc5fe@y18g2000yqn.googlegroups.com> Message-ID: <4lsl16-15a.ln1@archaeopteryx.softver.org.mk> > I'm trying again because I'm stubborn. Maybe the fourth time will be > the charm... > > Are there any good tutorials out there for setting up Apache with > mod_python? mod_python is depreceated, nobody uses it. use mod_wsgi http://www.modwsgi.org/ -- ?????? ( http://softver.org.mk/damjan/ ) Today we create the legacy of tomorrow. From george.sakkis at gmail.com Sun Dec 7 19:24:58 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 7 Dec 2008 16:24:58 -0800 (PST) Subject: Rich Comparisons Gotcha References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> <014c55e9$0$20670$c3e8da3@news.astraweb.com> Message-ID: <11d8b41a-a910-4915-8969-fc90e978350b@j11g2000yqg.googlegroups.com> On Dec 7, 6:37?pm, Steven D'Aprano wrote: > On Sun, 07 Dec 2008 23:20:12 +0000, Steven D'Aprano wrote: > > On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: > > >> Rasmus Fogh wrote: > > >>> Current behaviour is both inconsistent and counterintuitive, as these > >>> examples show. > > >>>>>> x = float('NaN') > >>>>>> x == x > >>> False > > >> Blame IEEE for that one. Rich comparisons have nothing to do with that > >> one. > > > There is nothing to blame them for. This is the correct behaviour. NaNs > > should *not* compare equal to themselves, that's mathematically > > incoherent. > > Sorry, I should explain why. > > Given: > > x = log(-5) ?# a NaN > y = log(-2) ?# the same NaN > x == y ?# Some people want this to be true for NaNs. > > Then: > > # Compare x and y directly. > log(-5) == log(-2) > # If x == y then exp(x) == exp(y) for all x, y. > exp(log(-5)) == exp(log(-2)) > -5 == -2 > > and now the entire foundations of mathematics collapses into a steaming > pile of rubble. And why doesn't this happen with the current behavior if x = y = log (-5) ? According to the same proof, -5 != -5. George From max at alcyone.com Fri Dec 12 18:45:24 2008 From: max at alcyone.com (Erik Max Francis) Date: Fri, 12 Dec 2008 15:45:24 -0800 Subject: Removing None objects from a sequence In-Reply-To: References: Message-ID: Filip Gruszczy?ski wrote: > I don't mean memory, but space in code ;-) Your goal should be clarity of code, not saving keystrokes. Writing something that is compact in terms of the amount of code to write does not mean its function is clear or even that it is more efficient to run, for that matter. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis God grant me to contend with those that understand me. -- Thomas Fuller From hackingkk at gmail.com Mon Dec 22 13:37:09 2008 From: hackingkk at gmail.com (Krishnakant) Date: Tue, 23 Dec 2008 00:07:09 +0530 Subject: Python's popularity In-Reply-To: References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: <1229971029.6331.31.camel@krishna-laptop> hello hackers. Python is best at high level calculations and as an indication, Please note that I am leading a team on developing an accounting software which will be modular and would suit the economic conditions of developed and almost developed countries like India. I find that number crunching and heavy calculations is shear programming bliss in python. At the front end we are using pygtk and find it very light and zippy. And we are going to use twisted for middle layer and reportlab for reporting. And the development so far is pritty smooth and our programmres who learned python for the first time are just amaised about the fact that how easily python can do a certain thing. So i don't know what others think but python is not just a good scripting language (not that being a good scripting language is some thing bad ) but also a complete enterprise ready language with given frameworks like twisted. happy hacking. Krishnakant. On Mon, 2008-12-22 at 12:59 -0500, Tommy Grav wrote: > On Dec 22, 2008, at 12:48 PM, walterbyrd wrote: > >> Now since Python *is not* the only language on it's block, we have to > >> compete with our main nemesis(Ruby) for survival > > > > I think both python and ruby will "survive." I think python is also > > competing with perl in the sysadmin space - although I see perl as > > being much more popular there. > > Python is making great headway in the physical sciences. Especially > in astronomy Python has become a real player as not only a tool for > quick and dirty calculations, but more serious number crunching using > the great numpy and scipy libraries. With Cython, I, think it will > even start > taking over some of the speed critical niche from C and Fortran. > > Cheers > Tommy > -- > http://mail.python.org/mailman/listinfo/python-list From martin at v.loewis.de Mon Dec 1 18:53:31 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 02 Dec 2008 00:53:31 +0100 Subject: Chmod to a group only In-Reply-To: <83e430f3-0c4c-4aae-84e3-7a8bb6dc1b74@t11g2000yqg.googlegroups.com> References: <83e430f3-0c4c-4aae-84e3-7a8bb6dc1b74@t11g2000yqg.googlegroups.com> Message-ID: <493478fb$0$11318$9b622d9e@news.freenet.de> >> How to chmod a file to: o-rwx ? (to change only the others mode) > I have tried: > > mode = os.stat(fname).st_mode > os.chmod(fname, mode | stat.S_IRWXO) => Changes to o+rwx Close. Try os.chmod(fname, mode & ~stat.S_IRWXO) Regards, Martin From zac256 at gmail.com Thu Dec 4 12:16:52 2008 From: zac256 at gmail.com (Zac Burns) Date: Thu, 4 Dec 2008 09:16:52 -0800 Subject: Overriding a method at the instance level on a subclass of a builtin type In-Reply-To: <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> Message-ID: <333edbe80812040916x7bcd2658h1c95db1959eaaf4a@mail.gmail.com> The class method seems to be the most promising, however I have more 'state' methods to worry about so I might end up building new classes on the fly rather than have a class per permutation of states! Now the code isn't quite as clear as I thought it was going to be. It seems unfortunate to me that methods are always looked up on the class for new style objects. Was this done for speed reasons? -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer (Digital Overlord) Zindagi Games On Thu, Dec 4, 2008 at 2:38 AM, Aaron Brady wrote: > On Dec 3, 1:25 pm, Jason Scheirer wrote: >> On Dec 2, 6:13 pm, Aaron Brady wrote: >> > >>> class A: >> >> > ... def methA( self ): >> > ... print 'methA' >> > ... self.meth= self.methB >> > ... meth= methA >> > ... def methB( self ): >> > ... print 'methB' >> > ...>>> a= A() >> > >>> a.meth() >> > methA >> > >>> a.meth() >> >> > methB >> >> The problem with using this this pattern in the way that you've >> specified is that you have a potential memory leak/object lifetime >> issue. Assigning a bound method of an instance (which itself holds a >> reference to self) to another attribute in that same instance creates >> a kind of circular dependency that I have discovered can trip up the >> GC more often than not. >> >> You can subclass it as easily: >> >> class dictsubclass(dict): >> def __getitem__(self, keyname): >> if not hasattr(self, '_run_once'): >> self.special_code_to_run_once() >> self._run_once = True >> return super(self, dict).__getitem__(keyname) >> >> If that extra ~16 bytes associated with the subclass is really a >> problem: >> >> class dictsubclass(dict): >> def __getitem__(self, keyname): >> self.special_code_to_run_once() >> self.__class__ = dict >> return super(self, dict).__getitem__(keyname) >> >> But I don't think that's a good idea at all. > > Interesting. The following code ran, and process memory usage rose to > 150MB. It failed to return to normal afterward. > >>>> for x in range( 10000000 ): > ... a= [] > ... a.append(a) > ... > > However, the following code succeeded in returning usage to normal. > >>>> import gc >>>> gc.collect() > > It was in version 2.6. So, the GC succeeded in collecting circularly > linked garbage when invoked manually. That might have implications in > the OP's use case. > > In another language, it would work differently, if it lacked unbound > method descriptors. C++ for example, untested: > > class C { > public: > func_t meth; > C( ) { meth= methA; } > void methA( ) { meth= methB; } > void methB( ) { } > }; > > It has no problems with memory consumption (an extra pointer per > object), or circular references; functions are not first-class > objects. However they are in Python, which creates an entire bound > method object per instance. > > The OP stated: > >> run some code and then patch in the original dict >> method for the instance to avoid even the check to see if the init >> code has been run. > > So your, Arnaud's, and Bryan's '.__class__' solution is probably best, > and possibly even truer to the intent of the State Pattern. > > It is too bad that you can't assign an unbound method to the member, > and derive the bound method on the fly. That might provide a middle- > ground solution. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From gh at ghaering.de Wed Dec 3 12:50:17 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 03 Dec 2008 18:50:17 +0100 Subject: python an sqlite objects In-Reply-To: <18742.47391.389709.119341@montanaro-dyndns-org.local> References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <18742.47391.389709.119341@montanaro-dyndns-org.local> Message-ID: skip at pobox.com wrote: > azrael> is it possible to save a python object into a sqlite database as > azrael> an atribute of type BLOB > > Sure. Just pickle the object and save the resulting string. Be sure to save it as BLOB, not TEXT. Suppose you have serialized your object as Python bytestring. serialized = ... ... .execute("insert into mytable(mycolumn) values (?)", (sqlite3.Binary(serialized),)) This way you will get a BLOB in the form of a Python buffer object when you later select it from the database, which you can then deserialize to a Python object. If you don't go the BLOB way, you may get an exception, because SQLite assumes all text is UTF-8 encoded, which it isn't necessarily when you put arbitrary serialized strings into the database. -- Gerhard From steve at REMOVE-THIS-cybersource.com.au Thu Dec 4 17:29:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Dec 2008 22:29:41 GMT Subject: "as" keyword woes References: <7dudnSS7uIn_KarUnZ2dnUVZ_tTinZ2d@earthlink.com> <0147e4df$0$20670$c3e8da3@news.astraweb.com> Message-ID: <01485198$0$20670$c3e8da3@news.astraweb.com> On Thu, 04 Dec 2008 10:44:33 -0600, Chris Mellon wrote: > On Thu, Dec 4, 2008 at 8:45 AM, Steven D'Aprano > wrote: >> On Thu, 04 Dec 2008 20:53:38 +1000, James Mills wrote: >> >>> Readability of your code becomes very important especially if you're >>> working with many developers over time. >>> >>> 1. Use sensible meaningful names. >>> 2. Don't use abbreviations. >> >> This is excellent advice, but remember, what is a sensible meaningful >> name is domain-specific. In a maths library, this would be sensible: >> >> def poly(x): >> return 4*x**3 -2*x**2 +3*x -7 >> >> and this ridiculous: >> >> def poly(real_number): >> return 4*real_number**3 -2*real_number**2 +3*real_number -7 >> >> >> > I actually wonder. The former is "sensible" in a math context because > there's a very long tradition in mathematics of using terse, inscrutable > placeholders for terms. It's only inscrutable to those who don't speak the language, in the same way that those who don't read English would find "The cat sat on the mat" to be inscrutable, or those with no programming experience at all would find: if myList is not None: return [item.method() for item in myList.process()] fairly mystifying. It almost looks like English, but what's with the weird punctuation and non-standard use of capitals? > I'm not a mathematician and I don't know > anything about the history of mathematical notation, but I'd guess this > has something to do with the fact that maths has historically been done > with a pencil and paper, and that terseness is an important quality when > you have a limited canvas and lots of stuff to write. I don't believe "limited canvas" is a major factor, because the availability of paper is only rarely a limiting factor. (However, there have been periods where paper or its equivalent was a rare and precious commodity.) Having lots of stuff to write by hand is a real factor though, especially since in a typical proof each line is very similar to the previous line. > Aside from the cultural indoctrination, though (and that may be a real > and strong force when dealing with math software, and I don't want to > discount it in general, just for purposes of this discussion) why is it > more sensible to use "x" here instead of "number" or "real" or > "real_number" or something else? Because the long names actually distract from the essential semantics of the problem being worked on. Consider my example: return 4*x**3 -2*x**2 +3*x -7 Translated into English, this would mean: Think of a number and call it x, and by convention it is a real number; cube it and multiply by four; subtract two times the square of it; add three times it; subtract 7 Compare this: return 4*real_number**3 -2*real_number**2 +3*real_number -7 As a mathematician, I would read that as: Think of a number and call it real_number; cube it and multiply by four, and don't forget the number needs to be a real number; subtract two times the square of it, and remember the number is a real number; add three times it, and did I mention that it has to be a real number?; subtract 7 Explicit is not *always* better than implicit, and terseness *is* a virtue (up to a point!) which is why we don't do this: Define a function called myFunc which takes one argument called foo. The instructions to be executed when calling myFunc start here: if the value of the argument foo is identical to the value of the keyword None then: change the value of the argument foo to the result returned by the function calc_foo, passing no arguments to it otherwise do nothing ... but prefer the (slightly) terse and (moderately) implicit: def myFunc(foo, bar): if foo is None: foo = calc_foo() ... Thank goodness we don't have to program in verbose, explicit English! In general, most mathematical expressions will involve a small number of variables, and what they represent are obvious from context, at least for those familiar with the problem domain. Those who aren't familiar with the problem domain aren't expected to work on either developing the expression in the first place, or maintaining it, in whatever sense mathematics is expected to be maintained. Although the problem domain naively seems narrow ("huh, who needs to understand complex numbers?") it is actually very abstract and hence can in principle be applied to many different problems. Contrast this with some arbitrary non-mathematical program. It might involve many variables rather than a few, and those variables might be rich objects with many attributes instead of simple numbers. The problem domain is often very concrete: *this* one specific business process, meaningful to only this department of that organisation, or at least to those just like them. Because concrete is more narrow than abstract, and because people who don't understand the problem domain are expected to maintain the software, you can't rely on implicit knowledge: you have to be explicit, and hence verbose, self-explanatory names are a virtue. -- Steven From bearophileHUGS at lycos.com Mon Dec 15 20:09:58 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 15 Dec 2008 17:09:58 -0800 (PST) Subject: Removing None objects from a sequence References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> <4942E668.5030100@tim.thechases.com> <01538f0c$0$6988$c3e8da3@news.astraweb.com> Message-ID: <2f58c57b-a56b-464e-9251-466046bfe840@a37g2000pre.googlegroups.com> Scott David Daniels: > If you want to keep the original's method, but do it in a more Pythonic > way, I would suggest: > > ? ? ?def deNone4(alist): > ? ? ? ? ?j = 0 > ? ? ? ? ?for val in alist: > ? ? ? ? ? ? ?if val is not None: > ? ? ? ? ? ? ? ? ?alist[j] = val > ? ? ? ? ? ? ? ? ?j += 1 > ? ? ? ? ?del alist[j :] For my benchmarks this is also the faster version with and without Psyco :-) (Even it's a bit slow when given a list that has no Nones). Bye, bearophile From castironpi at gmail.com Tue Dec 16 04:21:32 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 16 Dec 2008 01:21:32 -0800 (PST) Subject: alt.possessive.its.has.no.apostrophe References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> <49467CE2.3060401@holdenweb.com> <4946826E.7060001@tim.thechases.com> Message-ID: <989de86c-24cc-4ca6-8e9b-82e8ce853c7b@n33g2000pri.googlegroups.com> On Dec 15, 11:04?am, Steve Holden wrote: > Tim Chase wrote: > > Steve Holden wrote: > >> This led to a schism between the British and the > >> newly-independent Americans, who responded by taking the "u" > >> out of colour, valour, and aluminium. > > > Darn Americans and their alminim.... ;-) > > > Next thing you know, they'll be putting an I in TEAM.[1] > > It's called humour. Or humor. Or incompetence ;-) There's an 'I' in Python. From missive at hotmail.com Sun Dec 28 16:03:45 2008 From: missive at hotmail.com (Lee Harr) Date: Mon, 29 Dec 2008 01:33:45 +0430 Subject: error on windows with commands.getstatusoutput Message-ID: My application is trying to start twistd in a cross-platform way. Unfortunately, it works fine on my linux system, but I do not have windows, and I am trying to debug this remotely on a system I never use :o( Anyhow, here is the error I am getting: cmd = '%s -y %s -l %s' % (conf.twistd, conf.tztac, conf.twistdlog) status, output = commands.getstatusoutput(cmd) Error code: 1 Command: C:/Python25/Scripts/twistd.bat -y tzmud.tac -l var/log/twistd.log Output: '{' is not recognized as an internal or external command, operable program or batch file. Apparently, the Command works fine from the command line. So... Can I run a .bat file on windows with getstatusoutput? Anyone recognize this kind of error? Thanks for any assistance. _________________________________________________________________ Show them the way! Add maps and directions to your party invites. http://www.microsoft.com/windows/windowslive/events.aspx From n.kottiyath at gmail.com Mon Dec 29 11:51:01 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Mon, 29 Dec 2008 08:51:01 -0800 (PST) Subject: Python module import loop issue Message-ID: <02bc8567-695a-4277-9698-a95549a0bc98@w39g2000prb.googlegroups.com> This might not be pure python question. Sorry about that. I couldnt think of any other place to post the same. I am creating a _medium_complex_ application, and I am facing issues with creating the proper module structure. This is my first application and since this is a run-of-the-mill application, I hope someone would be able to help me. Base Module: Contains definitions for Class A1, Class A2 Module 1.1: Class B1 (refines A1) Module 1.2: Class C1 (refines A1) Module 1.3: Class D1 (refines A1) Module 2.1: Class B2 (refines A2): Uses objects of B1, C1, D1 Module 2.2: Class C2 (refines A2) Module 2.3: Class D2 (refines A2) -->Python Entry Module : Module EN<-- Calls objects of B1, C1 and D1 Module EN and also Module 2 creates and calls the objects during run time - and so calls cannot be hardcoded. So, I want to use Factory methods to create everything. Module Factory: import 1.1,1.2,1.3, 2.1,2.2,2.3 A1Factory: {'B1Tag':1.1.B1, 'C1Tag':1.2.C1, 'D1Tag':1.3.D1'} A2Factory: {'B2Tag':2.1.B2, 'C2Tag':2.2.C2, 'D2Tag':2.3.D2'} But, since Module requires objects of B1, C1 etc, it has to import Factory. Module 2.1: import Factory. Now, there is a import loop. How can we avoid this loop? The following ways I could think of 1. Automatic updation of factory inside superclass whenever a subclass is created. But, since there is no object created, I cannot think of a way of doing this. 2. Update A1Factory in each module which implements refinements. _Very_important_, how do I make sure each module is hit - so that the factory is updated? The module EN will be looking only at base module, so the other modules is not hit. I will have to import every module in EN - just to make sure that the A1Factory updation code is hit. This looks in-elegent. If somebody could help me out, I would be very thankful. From prologic at shortcircuit.net.au Mon Dec 29 20:51:18 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 30 Dec 2008 11:51:18 +1000 Subject: get method In-Reply-To: References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> <4819de67-72dc-415c-b4c8-2353581c2bc7@r2g2000vbp.googlegroups.com> Message-ID: On Tue, Dec 30, 2008 at 11:43 AM, James Mills wrote: > On Tue, Dec 30, 2008 at 11:38 AM, Ross wrote: >> I realize the code isn't counting, but how am I to do this without >> using an if statement as the problem instructs? > > I just gave you a hint :) Ross: This exercise is a simple exercise dealing with: * assignments * functions * dictionaries * looping * attributes and methods >>> def histogram(s): ... d = dict() ... for c in s: ... d[c] = d.get(c, 0) + 1 ... return d ... >>> histogram("Hello World!") {'!': 1, ' ': 1, 'e': 1, 'd': 1, 'H': 1, 'l': 3, 'o': 2, 'r': 1, 'W': 1} Note the 3rd line of the function ? 1. Get the value (with a default of 0) of the key c from the dictionary d 2. Add 1 to this value 3. Store in d with key c Hope this helps. cheers James From rt8396 at gmail.com Sat Dec 20 00:30:52 2008 From: rt8396 at gmail.com (r) Date: Fri, 19 Dec 2008 21:30:52 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c4ef2$0$20656$c3e8da3@news.astraweb.com> <2d53cd36-52b0-4a1a-913d-0c545cfadc23@v15g2000vbb.googlegroups.com> Message-ID: <2dc66762-f51e-4bbd-9372-756610d4201e@j11g2000yqg.googlegroups.com> On Dec 19, 10:04?pm, Steve Holden wrote: > r wrote: > > Thanks Steven, > > We need a real Pepsi challenge here to show the insignificance of this > > change. I am not against change. But when we lose something as - > > compact- as %formating i'm going to want to see a damn good reason for > > it! Especially when this breaks code, and the "French Connection" is > > not good enough reason for me :) > > > Christian said this was not going to be depreciated until 3.2, but > > that still puts the accepted way on the chopping block. > > If Python is so important to you it's a pity you haven't been playing > any active role in its development. Do you expect the developers to be > psychic? Steve, I just recently started to have an opinion about these things. "The squeaky wheel get the grease", just allowing my voice be heard. It might seem that i am trashing Python dev, but that could not be further from the truth. Many great changes have been made in 3.0, i just feel strongly about C style formating. Why could't we improve on what we had instead of making radical changes? Thats all i am asking. From enleverlesX.XmcX at XmclaveauX.com Fri Dec 19 15:17:26 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Fri, 19 Dec 2008 21:17:26 +0100 Subject: pymssql for python 2.6 ? In-Reply-To: References: Message-ID: <494c03ac$0$18372$ba4acef3@news.orange.fr> Hi! Look at http://www.mayukhbose.com/python/ado/ado-connection.php That run OK with Python 2.6 @-salutations -- MCI From paul.nospam at rudin.co.uk Thu Dec 11 00:40:45 2008 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Thu, 11 Dec 2008 05:40:45 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: <87r64f9sma.fsf@rudin.co.uk> "Dotan Cohen" writes: > 2008/12/10 : >> On Dec 5, 9:51 am, Xah Lee wrote: >>> >>> For those of you who don't know linear algebra but knows coding, this >>> means, we want a function whose input is a list of 3 elements say >>> {x,y,z}, and output is also a list of 3 elements, say {a,b,c}, with >>> the condition that >>> >>> a = x/Sqrt[x^2+y^2+z^2] >>> b = y/Sqrt[x^2+y^2+z^2] >>> c = z/Sqrt[x^2+y^2+z^2] >> >>> >>> In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, >>> you'll have 50 or hundreds lines. >> >> Ruby: >> >> def norm a >> s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) >> a.map{|x| x/s} >> end > > If someone doesn't counter with a Python one-liner then I'm going to > port that to brainfuck. from numpy.linalg import norm :) From alexoplocatie at gmail.com Wed Dec 17 11:15:37 2008 From: alexoplocatie at gmail.com (aka) Date: Wed, 17 Dec 2008 08:15:37 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> <0d9ea7cc-b5fb-4edb-be32-490aae9e7204@b41g2000pra.googlegroups.com> <0de3a7bf-a4c4-4103-a4e0-44313405fa94@z28g2000prd.googlegroups.com> Message-ID: John, this is the actual code I ran in TurboGears which is a Python framework. I should have left away the import statements. Trust me, the problem isn't in there because the UnicodeWriter is functioning perfectly. I did allready sanitate the csv file to these four lines in Notepad so there isn't anything more than this: id;company;department 12;Cadillac;Research 11;Ford;Accounting 10;Chrysler;Sales The only possible problematic lines are marked ##### here: > > ? ? def import_roles(self, input=None, *args, **kwargs): > > ? ? ? ? inp = 'C:/temp/test.csv' > > ? ? ? ? roles = [] > > ? ? ? ? msg = '' > > ? ? ? ? ## try: > > ? ? ? ? fp = open(inp, 'rb') ##### > > ? ? ? ? reader = csv.reader(fp, dialect='excel', delimiter=';') ##### > > ? ? ? ? ## reader = UnicodeReader(fp, dialect='excel', delimiter=';') ##### > > ? ? ? ? for r in reader: > > ? ? ? ? ? ? roles.append(r[0]) ##### > > ? ? ? ? fp.close() > > ? ? ? ? ## except: > > ? ? ? ? ? ? ## msg = "Something's wrong with the csv.reader" > > ? ? ? ? return dict(filepath=inp, > > ? ? ? ? ? ? ? ? ? ? roles=str(roles), > > ? ? ? ? ? ? ? ? ? ? msg=msg) Yeah rdmur, I'll have a look at the Python commandline. From jerry.carl.mi at gmail.com Sun Dec 28 11:41:22 2008 From: jerry.carl.mi at gmail.com (jerry.carl.mi at gmail.com) Date: Sun, 28 Dec 2008 08:41:22 -0800 (PST) Subject: math module for Decimals References: <41937dc9-4b67-43b5-9eab-6f8c851474cf@p2g2000prn.googlegroups.com> <0896c2d8-78ff-489e-801d-abef957601d0@s9g2000prg.googlegroups.com> Message-ID: <59c08a51-da39-467b-9576-fa0cc1db3207@i18g2000prf.googlegroups.com> > 1. mpmath? > 2. sympy? > 3. Sage? Haven't tried those, i guess i have some studying to do. > > > x=Decimal.__mod__(x,Decimal('2')*pi()) > > > Works fine for what i need, but i am sure it's not the right way to do > > it. > > I don't know of any better way to deal with large arguments. > The main problem is that the reduction step can introduce fairly > large errors: ?for example, if you're using a value of pi > that's accurate to 10**-20, say, then reducing something of > magnitude 10**5*pi will give a result with error of around > 10**-15. ?As far as I know, this problem is essentially > unavoidable, and it's the reason why implementing sin for inputs > like 10**999999999 isn't feasible. Good point. No tool will work in all parts of the universe (which is especially true for the universal ski wax). Let me check the 3 modules you listed above! From robert.kern at gmail.com Mon Dec 8 17:51:38 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 08 Dec 2008 16:51:38 -0600 Subject: Text parsing via regex In-Reply-To: References: Message-ID: Robocop wrote: > Wow! Thanks for all the input, it looks like that textwrapper will > work great for my needs. And thanks for the regex help everyone. > Also, i was thinking of using a list, but i haven't used them much in > python. Is there anything in python that is equivalent to pushback in > c++ for vectors? list.append() -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From aisaac at american.edu Thu Dec 4 14:42:04 2008 From: aisaac at american.edu (Alan G Isaac) Date: Thu, 04 Dec 2008 14:42:04 -0500 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> Message-ID: Mark Summerfield wrote: > "Programming in Python 3: > A Complete Introduction to the Python Language" > ISBN 0137129297 > http://www.qtrac.eu/py3book.html OMG, you really wrote it in Lout? I wish you would add to http://www.qtrac.eu/lout.html a comment on what you get out of that (compared to using e.g., LaTeX or reStructuredText). Anyway, congrats on the book! I've asked my library to order it. Alan Isaac From jstroud at mbi.ucla.edu Sun Dec 14 03:00:03 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 14 Dec 2008 00:00:03 -0800 Subject: Optimizing methods away or not? In-Reply-To: <0154b041$0$6988$c3e8da3@news.astraweb.com> References: <0154b041$0$6988$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > class Parrot: > def __init__(self, *args): > print "Initialising instance..." > if __debug__: > self.verify() # check internal program state, not args > if __debug__: > def verify(self): > print "Verifying..." +1 It looks good to me and the intent is much clearer than the other. From fetchinson at googlemail.com Sat Dec 27 19:54:52 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 27 Dec 2008 16:54:52 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: On 12/27/08, Robert Kern wrote: > Daniel Fetchinson wrote: > >> I agree that array.array is more efficient than a list but the input >> for my function will come from PIL and PIL returns a list. So I have a >> list to begin with which will be passed to the C function. > > With recent versions of PIL, numpy can create an array from an Image very > quickly, possibly without any copying of memory. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it > had > an underlying truth." > -- Umberto Eco > > -- > http://mail.python.org/mailman/listinfo/python-list > Hi Robert, now that we are at it let me ask something related. Now I managed to get my lists to C, operate on them in C and convert the result back to a python tuple. Since this is my first C program that uses the python C API I'm sure there are refcounting issues that I'm not considering, maybe also memory management too. This is the function I have, the corresponding python function will take two equal length lists of integers and the C function will compute their sum and return the result as a python tuple. static PyObject *func( PyObject * self, PyObject * args ) { int j, N; int * src1, * src2; PyObject *list1, *list2; list1 = PyTuple_GetItem( args, 0 ); N = PyList_Size( list1 ); src1 = ( int * ) malloc( N * sizeof( int ) ); for( j = 0; j < N; j++ ) { src1[j] = (int)PyInt_AsLong( PyList_GetItem( list1, j ) ); } list2 = PyTuple_GetItem( args, 1 ); N = PyList_Size( list2 ); src2 = ( int * ) malloc( N * sizeof( int ) ); for( j = 0; j < N; j++ ) { src2[j] = (int)PyInt_AsLong( PyList_GetItem( list2, j ) ); } PyObject * tuple; tuple = PyTuple_New( N ); for( j = 0; j < N; j++ ) { PyTuple_SetItem( tuple, j, PyInt_FromLong( (long)( src1[j] + src2[j] ) ) ); } free( src1 ); free( src2 ); return tuple; } Do I have to free the memory occupied by the python objects list1 and list2? Do I have to do any refcounting for list1, list2, tuple? Any comment on the above code will be very appreciated! If I'm pushed in the right direction I'm a fast learner but the beginning steps are always hard :) Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From jura.grozni at gmail.com Wed Dec 3 14:11:19 2008 From: jura.grozni at gmail.com (azrael) Date: Wed, 3 Dec 2008 11:11:19 -0800 (PST) Subject: python an sqlite objects References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <18742.47391.389709.119341@montanaro-dyndns-org.local> Message-ID: It logical that it would be more efficient and logical to use a object oriented database, but in this case I ask because of the portable nature of sqlite. so, if I get it right, this should be possible >>> class a: >>> def __init__(self, a, b): >>> self.c = a+b >>> self.d = a*b >>> >>> ob = a(1,3) >>> oc = a(2,4) >>> dbCursor.execute("insert into tabel example values (?,?)",[ob, oc]) #table example consists of blob atributes >>> dbcursor.commit() >>> dbCursor.execute("select * from table example") >>> list = dbcursor.fetchall() >>> for i in list: >>> print i.c, i.d >>> 4 3 6 6 From vlastimil.brom at gmail.com Mon Dec 1 16:09:33 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Mon, 1 Dec 2008 22:09:33 +0100 Subject: newbie question: parse a variable inside an RE? In-Reply-To: References: Message-ID: <9fdb569a0812011309k4e6beb68kda99f479b7e5012b@mail.gmail.com> 2008/12/1 > Hi All, > > How do I parse a variable inside an RE? > What is the re.search() syntax when your > search string is a variable? > It's easy to parse hardcoded RE's but not > if you use a variable. > > Here is my code, input and runtime: > > $ cat test45.py > #!/usr/bin/python > > import re > > resp = raw_input('Selection: ') > newresp = resp.strip() > print "you chose ", newresp > > fname = open('test44.in') > for I in fname: > # if re.search('^newresp', "%s"%(I)): # returns nothing > # if re.search(^newresp, "%s"%(I)): # syntax error > if re.search("^newresp", "%s"%(I)): # returns nothing > print I, > > [jmccaughan at dhcppc2 work]$ cat test44.in > a1 > b1 > g1 > g2 > h1 > h4 > 4g > 5g > h5 > > $ python test45.py > Selection: g > you chose g > $ > > Thanks... > -- > http://mail.python.org/mailman/listinfo/python-list > It doesn't seem very robust, but it can be made work, try e.g.: for item in fname: if re.search("^"+newresp, "%s" % (item,)): print item, (prints: g1 g2 in a similar code) (if you know, that item is a string, the %s interpolation is not needed; you can also use re match, without hte need for "^" . hth vbr -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Fri Dec 12 14:20:52 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 12 Dec 2008 11:20:52 -0800 (PST) Subject: (Very Newbie) Problems defining a variable References: <878wqlz27z.fsf@daycos.com> Message-ID: <7f7e8811-4043-40d4-8aa4-f44e1d255632@o4g2000pra.googlegroups.com> On Dec 13, 5:18?am, Kirk Strauser wrote: > At 2008-12-12T18:12:39Z, "Tim Rowe" writes: > > > > > Is there a tidy way of making rates and thresholds local to get_rate, > > without recalculating each time? I suppose going object oriented is > > the proper way. > > > #Py3k,UTF-8 > > > rates = {0: 0.006, 10000: 0.0085, 25000: 0.0124, 50000: 0.0149, 100000: 0.0173} > > thresholds = list(rates.keys()) > > thresholds.sort() > > thresholds.reverse() > > > def get_rate(balance): > > ? ? for threshold in thresholds: > > ? ? ? ? if balance >= threshold: > > ? ? ? ? ? ? return rates[threshold] > > ? ? else: > > ? ? ? ? return 0.0 > > How 'bout: > > def get_rate(balance): > ? ? for threshold, rate in ((100000, .0173), > ? ? ? ? ? ? ? ? ? ? ? ? ? ? (50000, .0149), > ? ? ? ? ? ? ? ? ? ? ? ? ? ? (25000, .0124), > ? ? ? ? ? ? ? ? ? ? ? ? ? ? (10000, .0085), > ? ? ? ? ? ? ? ? ? ? ? ? ? ? (0, .006)): > ? ? ? ? if balance > threshold: > ? ? ? ? ? ? return rate > ? ? return .0 (1) you meant "if balance > threshold:" (2) sequential search can be very fast if the sequence is in descending order of probability of occurence ... you might like to consider reversing the order (3) for a much longer table, binary search using a function from the bisect module could be considered (4) in practice, the "default" action would not be "return 0.0"; perhaps something along these lines: if balance < -overdraft_limit: raise Exception(...) return HUGE From sturlamolden at yahoo.no Fri Dec 12 08:29:15 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 05:29:15 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> Message-ID: <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> On Dec 11, 4:25 am, Carl Banks wrote: > cm_gui is TROLL. And I am not compring it with bots like Aaron > Castironpi Brody. cm_gui is even troller than Xah Lee! Sure he is a troll, but he also have a point. Python is slower than it needs to be. Creating a fast implementation of a dynamic language is almost rocket science. But it has been done. There is Stronghold, the fastest version of Smalltalk known to man, on which the Sun Java VM is based. On a recent benchmark Java 6 -server beats C compiled by GCC 4.2.3 And most of that magic comes from an implementation of a dynamically typed language (Smalltalk). A Python interpreter based on Strontalk would be interesting... http://shootout.alioth.debian.org/u32q/benchmark.php?test=all&lang=all Second, there are other fast implementations of dynamic languages. The CMUCL and SBCL versions of Common Lisp comes to min; you can see how SBCL does in the same benchmark (CMUCL tends to be even faster). So Python is a lot slower than it needs to be. But in most cases, perceived 'slowness' comes from bad programming. http://www.strongtalk.org/ From gnewsg at gmail.com Wed Dec 31 15:26:04 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Wed, 31 Dec 2008 12:26:04 -0800 (PST) Subject: Why not Ruby? References: Message-ID: On 31 Dic, 18:55, Xah Lee wrote: > Just spent 3 hours looking into Ruby today. Here's my short impression > for those interested. > > * Why Not Ruby? > http://xahlee.org/UnixResource_dir/writ/why_not_Ruby.html > > plain text version follows: > -------------------------------------- > > Why Not Ruby? > > Xah Lee, 2008-12-31 > > Spent about 3 hours looking into Ruby language today. > > The articles i read in detail are: > > * Wikipedia: Ruby (programming language)?J. Gives general overview. > > * Brief tutorial: "Ruby in Twenty Minutes"http://www.ruby-lang.org/en/documentation/quickstart/ > > * Personal blog by Stevey Yegge, published in 2004-10.http://steve.yegge.googlepages.com/ruby-tour > > The Wikipedia gives the best intro and overview in proper context. The > "Ruby in Twenty Minutes" is just 4 pages. It give you a very concrete > intro to Ruby's syntax and semantics. Stevey Yegge's blog doesn't > teach much and rambles, but provide a little personal view. I read it > because his opinions i respect. > > Q: Will you learn Ruby? > > No. For practical application, the lang is some 100 times less useful > than each of Perl, Python, PHP, Javascript. For academic study, > functional langs like Mathematica, Haskell, OCaml, erlang, Qz, are far > more interesting and powerful in almost all aspects. Further, there's > also Perl6, NewLisp, Clojure, Scala... With respect to elegance or > power, these modern lang of the past 5 years matches or exceed Ruby. > > Q: Do you think Ruby lang is elegant? > > Yes. In my opinion, better than Perl, Python, PHP. As a high level > lang, it's far better than Java, C, C++ type of shit. However, i don't > think it is any better than emacs lisp, Scheme lisp, javascript, > Mathematica. Note that Ruby doesn't have a spec, and nor a formal > spec. Javascript has. Ruby's syntax isn't that regular, nor is it > based on a system. Mathemtica's is. Ruby's power is probably less than > Scheme, and probably same as Javascript. > > I also didn't like the fact that ruby uses keyword "end" to indicate > code block much as Pascal and Visual Basic, Logo, do. I don't like > that. > > Q: Won't Ruby be a interesting learning experience? > > No. As far as semantics goes, Ruby is basically identical to Perl, > Python, PHP. I am a expert in Perl and PHP, and have working knowledge > of Python. I already regretted having spent significant amount of time > (roughly over a year) on Python. In retrospect, i didn't consider the > time invested in Python worthwhile. (as it turns out, i don't like > Python and Guido cult, as the lang is going the ways of OOP mumbo- > jumbo with its Python 3 "brand new" future.) There is absolutely > nothing new in Ruby, as compared to Perl, Python, PHP, or Emacs lisp, > Scheme lisp. > > Q: Do you recommend new programers to learn Ruby then? > > Not particularly. As i mentioned, if you are interested in practical > utility, there's already Perl, PHP, Python, Javascript, which are all > heavily used in the computing industry. If you are interested as a > academic exercise, there's Scheme lisp, and much of functional langs > such as OCaml, Haskell, Mathematica, which will teach you a whole lot > more about computer science, features of language semantics, etc. > > Q: Do you condemn Ruby? > > No. I think it's reasonably elegant, but today there are too many > languages, so Ruby don't particularly standout for me. Many of them, > are arguably quite more elegant and powerful than Ruby. See: > Proliferation of Computing Languages. This is not a Ruby group. I recommend you to go waste your time there. --- Giampaolo http://code.google.com/p/pyftpdlib From python.list at tim.thechases.com Mon Dec 15 08:29:54 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 15 Dec 2008 07:29:54 -0600 Subject: Having Issues with CMD and the 'python' command In-Reply-To: References: Message-ID: <49465BD2.5010409@tim.thechases.com> James Mills wrote: > "cmd" has _nothing_ to do with Python. well, not quite "nothing"... http://docs.python.org/lib/module-cmd.html [grins, ducks and runs] (every time I see this module it makes me want to go write a small interactive-fiction game in the style of Zork/Adventure :) -tkc From steve at REMOVE-THIS-cybersource.com.au Tue Dec 30 03:52:05 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Dec 2008 08:52:05 GMT Subject: How do I DRY the following code? References: Message-ID: <0169d83a$0$6988$c3e8da3@news.astraweb.com> On Mon, 29 Dec 2008 21:13:55 -0500, R. Bernstein wrote: > How do I DRY the following code? > > class C(): [snip code] Move the common stuff into methods (or possibly external functions). If you really need to, make them private by appending an underscore to the front of the name. class C(): def common1(self, *args): return "common1" def common2(self, *args): return "common2" def _more(self, *args): # Private, don't touch! return "more stuff" def f1(self, arg1, arg2=None, globals=None, locals=None): ... unique stuff #1 ... self.common1() ret = eval(args, globals, locals) self._more() return retval def f2(self, arg1, arg2=None, *args, **kwds): ... unique stuff #2 ... self.common1() ret = arg1(args, *args, **kwds) self.common2 return retval def f3(self, arg1, globals=None, locals=None): ... unique stuff #3 ... self.common1() exec cmd in globals, locals self.common2() return None # unneeded def f4(self, arg1, globals=None, locals=None): ... unique stuff #4 ... self.common1() execfile(args, globals, locals) self._more() An explicit "return None" is probably not needed. Python functions and methods automatically return None if they reach the end of the function. > Above there are two kinds of duplication: that within class C and that > outside which creates an instance of the class C and calls the > corresponding method. Do you really need them? If so, you're repeating yourself by definition. That's not necessarily a problem, the stand-alone functions are just wrappers of methods. You can decrease (but not eliminate) the amount of repeated code with a factory function: def build_standalone(methodname, docstring=None): def function(arg, arg2=None, globals=None, locals=None): c = C() return c.getattr(methodname)(arg, arg2, globals, locals) function.__name__ = methodname function.__doc__ = docstring return function f1 = build_standalone('f1', "Docstring f1") f2 = build_standalone('f2', "Docstring f2") f3 = build_standalone('f3', "Docstring f3") There's no way to avoid the repeated f1 etc. But honestly, with only three such functions, I'd consider that overkill. > Lest the above be too abstract, those who want to look at the full > (and redundant) code: > > http://code.google.com/p/pydbg/source/browse/trunk/api/pydbg/api/ debugger.py You have parameters called Globals and Locals. It's the usual Python convention that names starting with a leading uppercase letter is a class. To avoid shadowing the built-ins, it would be more conventional to write them as globals_ and locals_. You may or may not care about following the convention :) I notice you have code like the following: if Globals is None: import __main__ Globals = __main__.__dict__ I would have written that like: if Globals is None: Globals = globals() or even if Globals is None: from __main__ import __dict__ as Globals You also have at least one unnecessary pass statement: if not isinstance(expr, types.CodeType): expr = expr+'\n' pass The pass isn't needed. In your runcall() method, you say: res = None self.start(start_opts) try: res = func(*args, **kwds) except DebuggerQuit: pass finally: self.stop() return res This is probably better written as: self.start(start_opts) try: return func(*args, **kwds) except DebuggerQuit: return None finally: self.stop() -- Steven From bearophileHUGS at lycos.com Sat Dec 6 11:42:28 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 6 Dec 2008 08:42:28 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> <8b8d1fb3-f49e-49bf-8cfe-eeee5ed16109@r37g2000prr.googlegroups.com> <014a932b$0$20670$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano: > If a line of code uses too many instance attributes to fit comfortably on > a line, spread it over two lines. There is no newline shortage, they are > a renewable resource. Splitting lines is generally possible, but sometimes it's not I want, for example to keep a formula whole. And splitting lines increases line count. Increasing line count may reduce the amount of code you can see in a screenshot, and this may decrease a little the programmer's ability to understand code. (I am not suggesting to cram everything into one or few lines, like in K language: regarding code size there's an optimal middle point between K/APL and Ada/certain Java. Still, typing "self." very often requires time, and even if you are lucky to have an IDE that helps you write that faster, the code uses lot of space anyway). That's why I say that the following code, while looking a little ugly, may be a little "better" anyway (and maybe even more readable): class ThisIsAClass: def $some_method(arg1, arg2): $value = arg1 + $foo + $bar + $baz * arg2 ... Than the current syntax: class ThisIsAClass: def some_method(self, arg1, arg2): self.value = arg1 + self.foo + self.bar + self.baz * arg2 ... Bye, bearophile From floris.bruynooghe at gmail.com Thu Dec 18 09:41:40 2008 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Thu, 18 Dec 2008 06:41:40 -0800 (PST) Subject: C API and memory allocation References: <4949f109$0$31329$9b4e6d93@newsspool4.arcor-online.net> Message-ID: On Dec 18, 6:43?am, Stefan Behnel wrote: > Floris Bruynooghe wrote: > > I'm slightly confused about some memory allocations in the C API. > > If you want to reduce the number of things you have to get your head > around, learn Cython instead of the raw C-API. It's basically Python, does > all the reference counting for you and also reduces the amount of memory > handling you have to care about. > > http://cython.org/ Sure that is a good choice in some cases. Not in my case currently though, it would mean another build dependency on all our build hosts and I'm just (trying to) stop an existing extension module from leaking memory, no way I'm going to re-write that from scratch. But interesting discussion though, thanks! Floris From gdamjan at gmail.com Tue Dec 16 19:13:48 2008 From: gdamjan at gmail.com (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Wed, 17 Dec 2008 01:13:48 +0100 Subject: ethical questions about global variables References: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> <0d9a9758-f338-4a58-971a-1bd29e40ce32@v5g2000prm.googlegroups.com> Message-ID: > By "per-class-instance variables", you are talking > about instance attributes? I.e. "self.use_gmt_times"? > I don't see much difference between global variables > and instance attributes. using global variable in modules makes the module not Thread-safe Using a instance attribute allows more threads to each have a separate instance with it's own config. -- ?????? ( http://softver.org.mk/damjan/ ) Today we create the legacy of tomorrow. From david at abbottdavid.com Sun Dec 7 10:04:35 2008 From: david at abbottdavid.com (David) Date: Sun, 07 Dec 2008 10:04:35 -0500 Subject: python book for non technical absolute beginner In-Reply-To: References: <493a7c6a$0$973$426a34cc@news.free.fr> Message-ID: <493BE603.1020600@abbottdavid.com> I like this one: http://www.freenetpages.co.uk/hp/alan.gauld/ -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From rt8396 at gmail.com Sat Dec 20 20:54:09 2008 From: rt8396 at gmail.com (r) Date: Sat, 20 Dec 2008 17:54:09 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: On Dec 20, 7:38?pm, Steven D'Aprano wrote: > On Sat, 20 Dec 2008 16:20:38 -0800, r wrote: > > On Dec 20, 6:05?pm, Roy Smith wrote: > >> I had an interesting experience with this recently. ?I was giving a > >> co-worker quick python into. ?He's an experienced programer in various > >> languages, but this was his first exposure to python. > > >> He got really hung up on the % syntax. ?By (bad) luck, he was trying to > >> print a tuple (let's call it "t"), did > > >> format % t > > >> and was surprised at the result. ?It set him off on a "but that's > >> stupid, blah, blah, blah" rant. ?I haven't absorbed the new syntax well > >> enough to figure out if people will get hung up by this with the new > >> syntax. > > > It is stupid, more reason to fix the current problem instead creating a > > whole new one. > > Instead of just whinging, how about making a suggestion to fix it? Go on, > sit down for an hour or ten and try to work out how a BINARY OPERATOR > like % (that means it can only take TWO arguments) can deal with an > arbitrary number of arguments, *without* having any special cases. > > Go on. Take your time. I'll be waiting. > > > One more big complaint "THE BACKSLASH PLAGUE". ever tried regexp?, or > > file paths?. All because that little backslash char is a line > > continuation character, maybe we should fix that. > > This makes no sense whatsoever. How does the line continuation character > make any difference to backslashes inside a regex or a file path? > > Again, instead of whinging, what's your suggestion to fix it? Another > suggestion, because your first: > > > Would your life end if '\' was not a continuation char? > > is just stupid. The line continuation character is *irrelevant* to the > problem of backslashes inside strings. For all the use it is, you might > as well suggest changing the name None to Null. > > -- > Steven i prefer None over Null myself, just another Pythonic beauty! ;) Steven, Would you like to elaborate on -why- escaped backslashes are needed in strings... i waiting??? From mail at microcorp.co.za Tue Dec 23 03:33:26 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 23 Dec 2008 10:33:26 +0200 Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com><6ra8t0F925rU1@mid.individual.net><29feda0d-6432-4cb9-8809-e4d4a7798601@e1g2000pra.googlegroups.com><6raeb8F9s47U2@mid.individual.net><25b1ece0-712b-4516-af28-88c50d00ab8c@s9g2000prg.googlegroups.com> Message-ID: <01e501c964e9$d10fc900$0d00a8c0@hendrik> "r" wrote: >Now thats the kind of friendly banter this group could use. Instead of >people acting as if their bowel-movements smell like bakery fresh >cinnamon rolls! What an amazing thing to say! Doesn't yours? - Hendrik From tjreedy at udel.edu Sat Dec 6 15:16:47 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 06 Dec 2008 15:16:47 -0500 Subject: python book for non technical absolute beginner In-Reply-To: <493a7c6a$0$973$426a34cc@news.free.fr> References: <493a7c6a$0$973$426a34cc@news.free.fr> Message-ID: News123 wrote: > One of my 'non technical' friends complained about knowing nothing at > all about programming (though using computers regularly for mails / web > browsing / googling and downloading / cropping photos ) > > He wants to play a little with programming to stimulate parts of his > otehrwise idle brain cells. ;-) Normally it's more the social science / > linguistic parts being exercised, > > I thought python might be a nice language for this > > No my question does anybody know a nice beginners book (or a learning CD > or on line tutorial)? Ideally it shouldn't be too serious and have a lot > of small nice mini-examples > > thanks in advance for any suggestions hints I started with the 1.3 version of http://docs.python.org/tutorial/index.html (but had lots of previous experience). From sjmachin at lexicon.net Thu Dec 25 20:03:01 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 25 Dec 2008 17:03:01 -0800 (PST) Subject: Is there a function to remove escape characters from a string ? References: <0163882f$0$6988$c3e8da3@news.astraweb.com> Message-ID: On Dec 26, 8:53?am, Stef Mientki wrote: > Steven D'Aprano wrote: > > On Thu, 25 Dec 2008 11:00:18 +0100, Stef Mientki wrote: > > >> hello, > > >> Is there a function to remove escape characters from a string ? > >> (preferable all escape characters except "\n"). > > > Can you explain what you mean? I can think of at least four alternatives: > > I have the following kind of strings, > the funny "?" is ASCII character 254, used as a separator character ASCII ends at 127. Just refer to it as chr(254). > > [FSM] > Counts = "1?11?16" ? ? ==> ? 1,11,16 > Init1 = "1?\BCtrl" ? ? ==> ? ?1,Ctrl > State5 = "8?\BJUMP_COMPL\b\n>PCWrite = 1\n>PCSource = 10" > ? ? ? ? ?==> 8, JUMP_COMPL\n>PCWrite = 1\n>PCSource = 10 After making those substitutions, what are you going to do with it? Split it up into fields using the csv module or stuff.split(",") or some other DIY method? Is there a possibility that whoever "designed" that data format used chr(254) as a separator because the data fields contained "," sometimes and so "," could not be used as a separator? > Seeing and testing all your answers, with great solutions that I've > never seen before, As far as str methods and built-ins that work on str objects are concerned, there is no corpus of secret knowledge known only to a cabal of wizards; it's all in the manual, and you don't need special magical spectacles to see it :-) > knowing nothing of escape sequences (I'm a windows guy ;-) Why do you think that whether or not you are a "windows guy" is relevant to knowing anything about escape sequences? > I now see that the characters I need to remove, like ?\B ?and \b ?are > not "official" escape sequences. \b *is* an "official" escape sequence, just like \n; see below: | >>> x = '\b'; print len(x), repr(x) | 1 '\x08' | >>> x = r'\b'; print len(x), repr(x) | 2 '\\b' | >>> x = '\B'; print len(x), repr(x) | 2 '\\B' | >>> x = r'\B'; print len(x), repr(x) | 2 '\\B' > So in this case the best (easiest to understand) method is a few replace > statements: > s = s.replace ( '\b', '' ).replace( '\B', ?'' ) It's probable that \b and \B are both TWO-byte sequences, in which case you should use r'\b' so that it does what you want it to do, and use r'\B' for consistency. From john.eriksson at logica.com Tue Dec 2 08:43:51 2008 From: john.eriksson at logica.com (Eriksson, John) Date: Tue, 2 Dec 2008 14:43:51 +0100 Subject: How to sort a list of file paths In-Reply-To: <47c890dc0812020126p5e8ff750x91ff58e9fabd7d32@mail.gmail.com> References: <2F0A3D19CA15C143B0688EC94220748720D1F89A61@SE-EX007.groupinfra.com> <47c890dc0812020126p5e8ff750x91ff58e9fabd7d32@mail.gmail.com> Message-ID: <2F0A3D19CA15C143B0688EC94220748720D1FF9480@SE-EX007.groupinfra.com> Hi again, I've updated the example using the ideas and python tricks used on pages found via the link you gave me, Chris. So... for future references here's the best (?) way of sorting a list of file names in the correct way (correct for some applications at least). Note: For some odd reason I seemed to get the best performance using a lambda defined function instead of an ordinary function. # --- EXAMPLE --- import re RE_DIGIT = re.compile(r'(\d+)') ALPHANUM_KEY = lambda s: [int(g) if g.isdigit() else g for g in RE_DIGIT.split(s)] file_list = ["File2.txt","File1.txt","File10.txt"] file_list.sort(key=ALPHANUM_KEY) # --------------- Best Regards /John -----Original Message----- From: cvrebert at gmail.com [mailto:cvrebert at gmail.com] On Behalf Of Chris Rebert Sent: den 2 december 2008 10:26 To: Eriksson, John Cc: python-list at python.org Subject: Re: How to sort a list of file paths On Tue, Dec 2, 2008 at 12:36 AM, Eriksson, John wrote: > Hi, > > > > This weekend I had some problems to get a list containing file paths to be > sorted in a way that I could use. > > > > I also found a thread in this mailing list ( > http://mail.python.org/pipermail/python-list/2007-April/433590.html ) and > realized that others might be interested in a solution. > > > > So... here is my five cents regarding file path sorting: > > > > Problem description: > > > > You have a list containing some file names: > > > >>>> file_list = ["File2.txt","File1.txt","File10.txt"] > > > > If you sort this list in the conventional way you end up with a result like: > > > >>>> file_list.sort() > >>>> print file_list > > ['File1.txt','File10.txt','File2.txt'] > > > > Solution: > > > > Sort the list by splitting alphas and digits in to groups and compare them > separately. > > > > import re > > def true_alphanum_cmp(a,b): > > aa = re.findall(r'\d |\D ', a) > > bb = re.findall(r'\d |\D ', b) > > for i in range(min(len(aa),len(bb))): > > if aa[i].isdigit() and bb[i].isdigit(): > > c = cmp(int(aa[i]),int(bb[i])) > > else: > > c = cmp(aa[i],bb[i]) > > if c!=0: > > return c > > return cmp(len(aa),len(bb)) > > > > file_list = ["File2.txt","File1.txt","File10.txt"] > > file_list.sort(true_alphanum_cmp) > > > > If the formatting in this mail is messed up you can find the example at > http://arainyday.se/notebook/true_alphanum_cmp.php > > > > All comments and improvements are welcome! Sounds like the issue discussed in the post on Coding Horror: http://www.codinghorror.com/blog/archives/001018.html It even links to another Python version of the algorithm. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > > > Best regards > > John Eriksson > > _________________________________________ > > > > Logica - Releasing your potential > > Tegsplan 2b > > 904 20 UME? > > Sweden > > > > T: +46 (0) 90 15 91 38 > > M: +46 (0) 70 366 16 77 > > E: john.eriksson at logica.com > > www.logica.se > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > From Slaunger at gmail.com Mon Dec 1 09:37:35 2008 From: Slaunger at gmail.com (Slaunger) Date: Mon, 1 Dec 2008 06:37:35 -0800 (PST) Subject: Emacs vs. Eclipse vs. Vim References: Message-ID: <27b16b50-57a9-4061-989c-17e02e56ab49@g38g2000yqn.googlegroups.com> On 29 Nov., 21:44, Josh wrote: > If you were a beginning programmer and willing to make an investment in > steep learning curve for best returns down the road, which would you pick? > > I know this topic has been smashed around a bit already, but 'learning > curve' always seems to be an arguement. If you feel that one is easier > or harder than the others to learn feel free to tell, but let's not make > that the deciding factor. Which one will be most empowering down the > road as a development tool? > > Thanks in advance, > > JR Many have written that they have no experience with using Eclipse. Well, I have a little, and I just want to add my experience. I am a novice Python programmer and I use Eclipse with the PyDev and SubClipse extensions which gives me a Python environment and integration with Subversion, which is the version control system I use. My OS is Windows XP and Server 2003. Other people are working on the same project using either eclipse on a linux box or another editor of choice. Eclipse works very well for me. The facilities I like are: * A handy object browser which lets be jump into the part of the code I am interested in (I work with several, quite large modules). * Autocompletion: When I write . it gives me a suggestion of the methods/attributes available and the doc string (if available) is shown as a tool tip. It can autogenerate a generic signature for a method call with the attribute names prefilled. Very handy as I quite often forget the order of arguments. * Unit tests: It is quite convenient to write and run unit tests in the environment (unittest run targets) * Refactoring: Intelligent rename for instance is handy for renaming methods and attributes across modules * Debugger: I debugger environment which works well for me with watchlists, step-into, step over. * Chroma-coded * Auto-indentation * Macros for block commenting, indenting and unindenting. * Nice integrated diff toll which integrates well with subversion. * And tons of other things which I have not explored yet. Like a coverage run target for instance. * Some Syntax checking I am personally satisfied with the startup time and overall responsiveness of Eclipse, but users of Emacs/Vim may have other bars for responsiveness than me. Sometimes I experience some problems with cascading inexplicable errors ocurring in the IDE when running unit test suites. This is annoying and they do not occur when I run the tests stand- alone outside on the command line. This IDE works well for me. I do not have an opinion about how it works in comparison with Emacs and Vim, just wanted to give my opinion on Eclipse and Python as this had not been discussed so much. On the prestige level it is certainly not considered as "cool" to use Eclipse as Emacs/Vim where I am working. I often hear the opinion that you are not a proper coder/hacker is you do not master any of these classic editors. I also think it depends much upon your coding style. Personally I spend much more time thinking on "how" to implement this-and-that, than actually coding. That may reflect that I am still a novice Python Programmer. -- Slaunger From ershov.a_n at mail.ru Tue Dec 2 14:47:07 2008 From: ershov.a_n at mail.ru (burb) Date: Tue, 2 Dec 2008 11:47:07 -0800 (PST) Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> <24f0dc02-9461-4b93-a2f8-a56fa5919ffc@n10g2000yqm.googlegroups.com> Message-ID: <2839c097-7d7d-42a7-a458-287442452983@v4g2000yqa.googlegroups.com> use UNIX "mail" command: crontab will send letters to you and you can look at traceback there. From wuwei23 at gmail.com Mon Dec 8 03:31:56 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 8 Dec 2008 00:31:56 -0800 (PST) Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? References: <5ccd4a18-cd2b-4040-90c6-33723af15e96@b38g2000prf.googlegroups.com> Message-ID: <7e1a9226-c7a9-4b5e-bfbb-ea079639d6a2@t39g2000prh.googlegroups.com> On Dec 8, 2:26?pm, illume wrote: > pygame is simpler to learn, since it doesn't require you to know how > to create classes or functions. I'm not sure if I'd be quick to tout that as an advantage... :) From svalbardcolaco at gmail.com Fri Dec 5 01:36:17 2008 From: svalbardcolaco at gmail.com (svalbard colaco) Date: Fri, 5 Dec 2008 12:06:17 +0530 Subject: CONNECTION TIMED OUT ERROR using urllib2 In-Reply-To: <180b672e0812042227j12a4d647k84e507dfae77d665@mail.gmail.com> References: <726d283d0812042217w41a0288eg3ee79d4ffdb5ff4b@mail.gmail.com> <180b672e0812042227j12a4d647k84e507dfae77d665@mail.gmail.com> Message-ID: <726d283d0812042236j792f4706v373ca6449861e3e2@mail.gmail.com> Hi rishi, Thanks for ur reply, yes i set the following enviroment variables (FC6 platform) http_proxy,http_user,http_password But i get the same error; Can u tell me which other variables i need to set or am i going wrong in the syntax of these variables? Regards sv On Fri, Dec 5, 2008 at 11:57 AM, rishi pathak wrote: > Are you sitting behind a proxy. If so then you have to set proxy for http > > On Fri, Dec 5, 2008 at 11:47 AM, svalbard colaco > wrote: > >> Hi all >> >> I have written a small code snippet to open a URL using urllib2 to open a >> web page , my python version is 2.4 but i get an urlopen error called >> connection timed out >> >> The following is the code snippet >> >> *import urllib2 >> >> f = urllib2.urlopen('http://www.google.com/') >> print f.read(100)* >> >> >> where as the same url http://www.google.com/ works through my browser. >> >> The following is the back trace : >> >> File "test_url.py", line 3, in ? >> f = urllib2.urlopen('http://www.google.com/') >> File "/usr/lib/python2.4/urllib2.py", line 130, in urlopen >> return _opener.open(url, data) >> File "/usr/lib/python2.4/urllib2.py", line 358, in open >> response = self._open(req, data) >> File "/usr/lib/python2.4/urllib2.py", line 376, in _open >> '_open', req) >> File "/usr/lib/python2.4/urllib2.py", line 337, in _call_chain >> result = func(*args) >> File "/usr/lib/python2.4/urllib2.py", line 1021, in http_open >> return self.do_open(httplib.HTTPConnection, req) >> File "/usr/lib/python2.4/urllib2.py", line 996, in do_open >> raise URLError(err) >> *urllib2.URLError: >> >> >> Any pointers in this regard will be of great help. >> >> Thanking you'll in advance. >> >> Regards, >> sv >> >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > > -- > Regards-- > Rishi Pathak > Pune-Maharastra > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gh at ghaering.de Wed Dec 3 16:41:48 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 03 Dec 2008 22:41:48 +0100 Subject: building an extension module with autotools? In-Reply-To: References: Message-ID: <4936FD1C.1010700@ghaering.de> Michael George wrote: > Hello, > > (Please CC me in replies, as I am off-list) Ok, but please reply publicly. > I'm building an application (a game) in python, with a single C module > containing some performance-critical code. I'm trying to figure out the > best way to set it up to build. Use distutils and keep your sanity. > Distutils seems to be designed only for > building and distributing code that lives in site-packages. I'd prefer > not to install it in the global site-packages, but rather group all of > the files together. Then just use the build step of distutils and do the rest from your build script (Python-based, make based, whatever you prefer). > I've tried using automake, In my opinion, this is serious overkill. automake is good for making stuff work on a herd of different Unixen with various combinations of libc functions available etc. But for developing a Python extension, it doesn't help much at all. All you need to know about Python is available via macros if you import Python.h. > however I'm worried about libtool not getting > the options right while building my module. It seems to me like the > ideal frankenstein monster would be for automake to invoke distutils to > do the actual building. However I'm relatively new to both autotools > and distutils, so getting this rigged up has been a bit of a challenge. > Can anybody point me to a good example of something like this or give me > any pointers? My recommendation is to start simple instead of wasting too much time upfront for probably nothing. Here's what I'd start with: #!/bin/sh python setup.py build cp build/lib.*/*.so . python test.py HTH -- Gerhard From zac256 at gmail.com Tue Dec 2 19:58:36 2008 From: zac256 at gmail.com (Zac Burns) Date: Tue, 2 Dec 2008 16:58:36 -0800 Subject: Overriding a method at the instance level on a subclass of a builtin type Message-ID: <333edbe80812021658s3ae50aeetd45551b85b52b6a3@mail.gmail.com> Sorry for the long subject. I'm trying to create a subclass dictionary that runs extra init code on the first __getitem__ call. However, the performance of __getitem__ is quite important - so I'm trying in the subclassed __getitem__ method to first run some code and then patch in the original dict method for the instance to avoid even the check to see if the init code has been run. Various recipes using instancemethod and the like have failed me. Curiously if __slots__ is not specified no error occurs when setting self.__getitem__ but the function is not overriden. If __slots__ is ['__getitem__'] however it complains that __getitem__ is read only. I do not understand that behavior. -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer (Digital Overlord) Zindagi Games From lists at cheimes.de Thu Dec 25 14:17:31 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 25 Dec 2008 20:17:31 +0100 Subject: Syntax error for print In-Reply-To: <99a432d6-5085-4a3a-82ff-538c95e33515@z28g2000prd.googlegroups.com> References: <2b65c6e1-b5a9-438d-a45c-b8f9d18228de@s1g2000prg.googlegroups.com> <99a432d6-5085-4a3a-82ff-538c95e33515@z28g2000prd.googlegroups.com> Message-ID: jsm4321 at gmail.com schrieb: > Thanks Bearophile. > > I should have used a tutorial for Python 3.0 > > I was reading tutorial for Python 2.5 Get Python 2.5 or 2.6, seriously. Python 3.0 is not (yet) supported by most tutorials, third party extensions and books. Christian From jeff_barish at earthlink.net Mon Dec 22 22:42:20 2008 From: jeff_barish at earthlink.net (Jeffrey Barish) Date: Mon, 22 Dec 2008 20:42:20 -0700 Subject: Beep References: <47c890dc0812211620h6c19086dhf3a14a662a49fdf6@mail.gmail.com> <6r8qqpFq8rU1@mid.individual.net> Message-ID: Tobias Andersson wrote: > Jeffrey Barish skrev: >> Chris Rebert wrote: >>> Is the 'pcspkr' kernel module built and loaded? >> >> Yes. And I should have mentioned that I get sound from Ubuntu >> applications that produce sound. > > Also, is the terminal bell set to "visual"? If so chr(7) only > produces a brief flash (or similar). On Ubuntu, it is possible to set visual and audible beeps separately. When I set both, I get the visual beep, but not the audible one. It's not a Python issue -- so I should take this thread to Ubuntu -- because I observe this behavior even when I hit backspace at the beginning of a line in a terminal. -- Jeffrey Barish From mnordhoff at mattnordhoff.com Wed Dec 10 07:13:28 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Wed, 10 Dec 2008 12:13:28 +0000 Subject: Using the `email' module in a bazaar plugin In-Reply-To: <20081210115825.01853c3b.jules@REMOVETHIS.op59.net> References: <20081210115825.01853c3b.jules@REMOVETHIS.op59.net> Message-ID: <493FB268.3010107@mattnordhoff.com> Julian Smith wrote: > I don't seem to be able to use the `email' module from within a bazaar > plugin. Other modules work ok, e.g. nntplib. > > Here's my plugin, cut-down to show just the email problem: > > import sys > print 'sys.version', sys.version > > import nntplib > n = nntplib.NNTP( 'jsmith-ubuntu2' ) > print n > > import email > m=email.MIMEText.MIMEText('text of email') > > - and here's the output when i run any bazaar command: > > > bzr status > sys.version 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] > > 'module' object has no attribute 'MIMEText' > Unable to load plugin 'js_notify' from '/home/jsmith/.bazaar/plugins' > ... > > The plugin runs fine on its own, it's only when loaded into Bazaar that things > go wrong. > > I thought perhaps this could be caused by the `email' module's use of > LazyImporter. I've tried various things such as `from email.mime.text import > MIMEText', and they fail in similar ways. > > I'm using bzr-1.9, python 2.5.2, on Ubuntu-8.xx. > > Does anyone have any ideas ? > > Thanks, > > - Julian The built-in email module is probably getting shadowed by another one (perhaps bzrlib.plugins.email?), so "import email" is importing the wrong module. You'll have to rename it to something else. Have your plugin print email.__path__ to see which module it is. -- From jeremiah.dodds at gmail.com Thu Dec 4 04:06:32 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Thu, 4 Dec 2008 04:06:32 -0500 Subject: Multiple equates In-Reply-To: <001801c95648$5b6d65e0$0d00a8c0@hendrik> References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> <001801c95648$5b6d65e0$0d00a8c0@hendrik> Message-ID: <12cbbbfc0812040106m50a9f6edxcbb373bac62823a4@mail.gmail.com> On Thu, Dec 4, 2008 at 1:19 PM, Hendrik van Rooyen wrote: > > "Cameron Laird" wrote: > > > There's a realm within Pythonia that favors lambdalessness. > > And who, may I ask, Is the King of this realm? > > - Hendrik > > -- > http://mail.python.org/mailman/listinfo/python-list > Guido? -------------- next part -------------- An HTML attachment was scrubbed... URL: From bockman at virgilio.it Wed Dec 31 14:17:51 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: Wed, 31 Dec 2008 20:17:51 +0100 Subject: select.select and socket.setblocking In-Reply-To: <4b7fdd17-c9c0-4970-9bf8-e596c939e23e@d42g2000prb.googlegroups.com> References: <495a661d$0$11384$5fc30a8@news.tiscali.it> <495b34d8$0$11387$5fc30a8@news.tiscali.it> <3652a957-eec6-494c-bd37-d150018bc0ed@p2g2000prf.googlegroups.com> <495b8653$0$11383$5fc30a8@news.tiscali.it> <4b7fdd17-c9c0-4970-9bf8-e596c939e23e@d42g2000prb.googlegroups.com> Message-ID: <495bc560$0$11385$5fc30a8@news.tiscali.it> Saju Pillai ha scritto: > On Dec 31, 7:48 pm, Francesco Bochicchio wrote: > > Is this correct ? IIRC even in blocking mode recv() can return with > less bytes than requested, unless the MSG_WAITALL flag is supplied. > Blocking mode only guarantees that recv() will wait for a message if > none is available - but not that it *will* return the number of bytes > requested. > > -srp > You are right ... most of my socket experience predates MSG_WAITALL, and I forgot that now the default behaviour is different ... oops ... Ciao ------ FB From aboudouvas at panafonet.gr Sat Dec 6 05:54:06 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Sat, 6 Dec 2008 02:54:06 -0800 (PST) Subject: Netbeans Early Access and Python3 Message-ID: Hi, have anyone using this release of NetBeans (6.5 with Python support) with Python 3 without any problems ? I mean, does it work with Python3 or only with 2.x ? From dstanek at dstanek.com Mon Dec 22 10:43:44 2008 From: dstanek at dstanek.com (David Stanek) Date: Mon, 22 Dec 2008 10:43:44 -0500 Subject: Event Driven programming - Doubts In-Reply-To: <80f360e4-2880-4c66-a6b4-e05d6dbc9031@b41g2000pra.googlegroups.com> References: <80f360e4-2880-4c66-a6b4-e05d6dbc9031@b41g2000pra.googlegroups.com> Message-ID: On Mon, Dec 22, 2008 at 9:57 AM, Kottiyath wrote: > > If so, Even though data locking etc is not a problem, are we not still > having threads? Will it not still cause scalability problems in high > traffic? > If not, could somebody let me know how it is done? This somewhat depends on the application. Is it IO bound or CPU bound? >From what I understand about twisted you will only have one process and one thread which means you will only be using one CPU. -- David http://www.traceback.org From w_a_x_man at yahoo.com Wed Dec 10 21:22:40 2008 From: w_a_x_man at yahoo.com (William James) Date: 11 Dec 2008 02:22:40 GMT Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <40b4b23f-c1eb-4ac5-bb42-e0f6276e97bf@r37g2000prr.googlegroups.com> Message-ID: Jon Harrop wrote: > Xah Lee wrote: > > On Dec 10, 12:37 pm, w_a_x_... at yahoo.com wrote: > >> Ruby: > > > > >> def norm a > >> s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) > >> a.map{|x| x/s} > >> end > > > > I don't know ruby, but i tried to run it and it does not work. > > > > #ruby > > def norm a > > s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) > > a.map{|x| x/s} > > end > > > > v = [3,4] > > > > p norm(v) # returns [0.6, 0.8] > > That is the correct answer. > > > The correct result for that input would be 5. > > No, you're confusing normalization with length. Expanded for easier comprehension. def norm a # Replace each number with its square. b = a.map{|x| x*x } # Sum the squares. (inject is reduce or fold) c = b.inject{|x,y| x + y } # Take the square root of the sum. s = Math.sqrt( c ) # Divide each number in original list by the square root. a.map{|x| x/s } end 1.upto(4){|i| a = (1..i).to_a p a p norm( a ) } --- output --- [1] [1.0] [1, 2] [0.447213595499958, 0.894427190999916] [1, 2, 3] [0.267261241912424, 0.534522483824849, 0.801783725737273] [1, 2, 3, 4] [0.182574185835055, 0.365148371670111, 0.547722557505166, 0.730296743340221] From clp at rebertia.com Sun Dec 7 03:35:24 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 7 Dec 2008 00:35:24 -0800 Subject: can graphs be made in python as we make in java In-Reply-To: <89ff42d1-6a4c-4d45-a646-238b43e7e8de@s9g2000prm.googlegroups.com> References: <89ff42d1-6a4c-4d45-a646-238b43e7e8de@s9g2000prm.googlegroups.com> Message-ID: <47c890dc0812070035g6298be00ob1afc56a451e32f2@mail.gmail.com> On Sun, Dec 7, 2008 at 12:29 AM, suku wrote: > HI folks... > > i need some suggestion on making graphs. Will this be possible > with normal python setup file or do i need to download add ons for > that.. Python includes no such module for that in the standard library. You'll need to use a third-party library. If you're writing a webapp, pygooglechart (http://pygooglechart.slowchop.com/) is pretty good. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > help me out > -- > http://mail.python.org/mailman/listinfo/python-list > From paul at boddie.org.uk Mon Dec 15 10:34:06 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 15 Dec 2008 07:34:06 -0800 (PST) Subject: %s place holder does not let me insert ' in an sql query with python. References: <1229345178.31093.24.camel@krishna-laptop> Message-ID: <412769f8-c1c8-4d4b-9350-7189b98a7dac@p2g2000prn.googlegroups.com> On 15 Des, 14:46, Krishnakant wrote: > hello all, > thanks for all of your very quick responses. > The problem is that I am using python 2.5 so the 2.6 syntax does not > apply in my case. The parameter syntax for database operations is defined by the DB-API, and this is a very different matter to that of Python string substitution (or formatting). See this document for details: http://www.python.org/dev/peps/pep-0249/ You should note that when sending the SQL command to the database system, you do not use the % operator to prepare that command. Instead, you should pass the collection of parameters as the second argument of the execute method. In other words... cursor.execute(query, parameters) Note that the query is kept as a separate argument; you do not combine these two things yourself. Paul P.S. As far as I know, Python 2.6 still has the traditional printf- style substitution syntax, so any exhortation to adopt new-style formatting is ill-advised, especially since it has only slight relevance to this particular enquiry. From duncan.booth at invalid.invalid Tue Dec 2 04:50:31 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Dec 2008 09:50:31 GMT Subject: Is it safe to modify the dict returned by vars() or locals() References: <4934508b$0$2861$ba620e4c@news.skynet.be> <4935011A.9080406@igpm.rwth-aachen.de> Message-ID: Helmut Jarausch wrote: > Chris Rebert wrote: >> On Mon, Dec 1, 2008 at 1:01 PM, Helmut Jarausch >> wrote: >>> Hi, >>> >>> I am looking for an elegant way to solve the following problem: >>> >>> Within a function >>> >>> def Foo(**parms) >>> >>> I have a list of names, say VList=['A','B','C1'] >>> and I like to generate abbreviation >>> _A identical to parms['A'] >> >> Could you explain what you mean by that? Your sample code doesn't >> seem to do any "abbreviation"... >> Otherwise I don't see why you don't just have a proper parameter >> list. > > In my application parms contains field names of an html form iff these > fields have been modified. > I'd like to use the short name _A instead of the longer expression > parms['A'] > > You haven't yet explained why you don't just do: def foo(A=None, **parms): ... The code to call foo remains the same as before, but Python will unpack the named parameter into the local variable A for you automatically. Any other parms that you didn't know about in advance remain in the separate dictionary. -- Duncan Booth http://kupuguy.blogspot.com From philip at semanchuk.com Sat Dec 13 15:27:50 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Sat, 13 Dec 2008 15:27:50 -0500 Subject: Parallelizing python code - design/implementation questions In-Reply-To: References: Message-ID: On Dec 13, 2008, at 7:00 AM, stdazi wrote: > Hello! > > I'm about to parallelize some algorithm that turned out to be too > slow. Before I start doing it, I'd like to hear some suggestions/hints > from you. Hi stdazi, If you're communicating between multiple processes with Python, you might find my IPC extensions useful. They're much less sophisticated than multiprocessing; they just give access to IPC semaphores and shared memory (no message queues yet) on Unix. POSIX IPC: http://semanchuk.com/philip/posix_ipc/ System V IPC: http://semanchuk.com/philip/sysv_ipc/ More System V IPC: http://nikitathespider.com/python/shm/ The System V IPC extensions are similar; the latter is older and better tested but won't be developed anymore. The former is newer, has a couple more features and is the future of System V IPC w/Python, at least as far as my work is concerned. Good luck Philip > > > The algorithm essentially works like this: There is a iterator > function "foo" yielding a special kind permutation of [1,....n]. The > main program then iterates through this permutations calculating some > proprieties. Each time a calculation ends, a counter is incremented > and each time the counter is divisible by 100, the current progress is > printed. > > The classical idea is to spawn m threads and use some global lock when > calling the instance of the iterator + one global lock for > incrementing the progress counter. Is there any better way? I'm > especially concerned with performance degradation due to locking - is > there any way to somehow avoid it? > > I've also read about the `multiprocessing' module and as far as I've > understood : > > ==== > permutation = foo() > threadlst = [] > for i in xrange(m) : > p = Process(target=permutation.next) > threadlst.append(p) > p.start() > for p in threadlst: > p.join() > ==== > > should do the trick. Am I right? Is there any better way other than > this? > -- > http://mail.python.org/mailman/listinfo/python-list From warren at delsci.com Thu Dec 4 19:17:20 2008 From: warren at delsci.com (Warren DeLano) Date: Thu, 4 Dec 2008 16:17:20 -0800 Subject: To Troll or Not To Troll (aka: "as" keyword woes) Message-ID: <896B75251BA19745A529B1B867893FA5DB0E@planet.delsci.local> > From: Ben Finney > > "Chris Mellon" writes: > > > Peculiarities in usenet resulted in this discussion having several > > threads and I missed some messages before I wrote this email. > > I'll put this more bluntly: Warren's messages to date > egregiously break the flow of discussion. > > Warren, in the interest of sane discussion in these forums, please: > > * preserve attribution lines on quoted material so we can see who > wrote what. > > * use the convention of ?New subject (was: Old subject)? when you > change the ?Subject? field of a message. > > * switch to a client that preserves threading in messages you send, > i.e. that properly constructs the ?References? and ?In-Reply-To? > fields. > > General advice good for everyone, of course, but particularly > apropos to this reply. Any one of the above is detrimental to > omit; striking on all three makes a discussion almost > impossible to follow. (Thank you, though, for avoiding the > worse habit of top posting!) Thank so much for the suggestions Ben. Sorry that I am personally unable to live up to your high standards, but it is nevertheless an honor to partipicate in such a helpful and mutually respectful community mailing list! Warren From arnodel at googlemail.com Tue Dec 23 12:03:31 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 23 Dec 2008 17:03:31 +0000 Subject: On Whose Desktop References: <4950db7e$0$14770$426a74cc@news.free.fr> <89ca6cc9-fa26-42c9-be67-35aad569500b@i18g2000prf.googlegroups.com> Message-ID: Aaron Brady writes: > +1 whose (posessive) -1 posessive :) -- Arnaud From tundra at tundraware.com Tue Dec 9 11:58:05 2008 From: tundra at tundraware.com (Tim Daneliuk) Date: Tue, 09 Dec 2008 10:58:05 -0600 Subject: Python 3 For Python 2 Users Message-ID: I code in Python 2.x intermittently and have only casually watched the 3.x development discussions. Now it's time to get up to speed. Has someone written a tutorial for people in my situation. Yes, I've looked at the release notes, but I'm looking for something that motivates all the major changes to give me a better sense of the Gestalt of the new language. TIA, -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From rdcollum at gmail.com Thu Dec 18 11:52:20 2008 From: rdcollum at gmail.com (Roger) Date: Thu, 18 Dec 2008 08:52:20 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <71ede5f0-fd88-4155-9f0d-42d0ad5f57dc@v42g2000yqj.googlegroups.com> Message-ID: On Dec 18, 11:40?am, r wrote: > Yea, my answer was really not a helping answer(sorry) just showing > exactly why this will not work with w.unbind(). Why do you need two > separate functions to bind the same event?? You cannot combine the > two?? I can't combine the two in my app unfortunately. The binding is to a custom widget that upon it being destroyed the binding is no longer valid. I can work around this by being hacky but I prefer to delete the one binding itself which would make things cleaner. From clp at rebertia.com Tue Dec 9 22:29:06 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 9 Dec 2008 19:29:06 -0800 Subject: How do I manually uninstall setuptools (installed by egg)? In-Reply-To: <375bd56a-d92b-4d33-bf70-5bea630a376a@q30g2000vbn.googlegroups.com> References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> <375bd56a-d92b-4d33-bf70-5bea630a376a@q30g2000vbn.googlegroups.com> Message-ID: <47c890dc0812091929m68dbcfceoeca883be82c6b9df@mail.gmail.com> On Tue, Dec 9, 2008 at 7:16 PM, wrote: > On Dec 9, 10:04 pm, "Chris Rebert" wrote: >> So, why do you think apt and not setuptools is The Right Way(tm)? > > I like to keep > 1 Python on my computer. Ah, now I get it. I had no idea setuptools could install Python *itself* until I checked just now. That's kinda neat, but mostly silly, because, as you point out, management of Python itself is much better left to the platform's package manager. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From chaneyfgargue at gmail.com Tue Dec 9 14:08:27 2008 From: chaneyfgargue at gmail.com (chaneyfgargue at gmail.com) Date: Tue, 9 Dec 2008 11:08:27 -0800 (PST) Subject: Opa asdasd News Message-ID: <257ad7af-fea8-4389-9f6a-095446525016@z6g2000pre.googlegroups.com> The decision comes after the review of a six-month pilot program that extended the TIS National to pharmacies. http://bmool.blogsome.com/ http://asdmk.blogsome.com/ The pilot program, conducted by the department and the Pharmacy Guild of Australia, involved 331 pharmacies having access to the service 24 hours a day. http://steppo.blogsome.com/ Participating pharmacies will be able to use the Translating and Interpreting Service (TIS National), operated by the Department of Immigration, 24 hours a day, seven days a week. Pharmacy Guild of Australia national president Kos Sclavos implored pharmacists to use the service to prevent patients from misinterpreting important usage instructions. http://mygotar.blogsome.com/ "The interpreter service is not a full solution. The best solution is to always have a staff member of that language. Pharmacies have been very good at going out of their way to employ perhaps one staff member fluent in another language. But because the trading hours of pharmacies, it's very hard to have a staff member on at all times with that language skills base. So this service fills in or augments current practices." Mr Sclavos said there were inherent problems with other multilingual initiatives, such as printing instruction labels in other languages. "The tendency to revert to a first language as experienced by some older Australians, who have acquired English as a second language, is one of the greatest issues facing our ageing population. This was demonstrated by the heavy usage of the TIS services by post-war aged European communities throughout the duration of the pilot. Pharmacies who participated in the pilot used interpreting services more frequently and reported improved outcomes in terms of client understanding of medications." http://rollz.blogsome.com/ "You need to be getting that verbal and non-verbal feedback from the patient that they have indeed understood the instructions and that's why the interpreter service is so important because the interpreter on the other end of the phone will ask 'now repeat what I've just explained' or 'have you understood what I just said'," Mr Sclavos said. http://aermk.blogsome.com/ "As a pharmacist, if I was checking the prescription later and unless it's dual-labelled, I couldn't be sure because I couldn't read that language or couldn't understand the translation. The difficulty we have with the dual-labelling approach is that we would be getting complaints that the packaging is getting smaller and smaller and there is no room to put a sticker on the packet. That's why the Guild?s policy is not to support automatic translations because it increases the risk of errors." http://twoaac.blogsome.com/ Parliamentary Secretary for Multicultural Affairs Laurie Ferguson said health care needs of recent migrants and elderly former migrants necessitated the extension of the service to pharmacies. http://viewpharmacy.blogsome.com/ "Interpreting services are crucial for the proper distribution and usage of prescription medicines by non-English speaking Australians," Mr Ferguson said. From mensanator at aol.com Sat Dec 6 17:36:07 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 6 Dec 2008 14:36:07 -0800 (PST) Subject: "as" keyword woes References: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> <0147dc24$0$20670$c3e8da3@news.astraweb.com> <0148b217$0$20670$c3e8da3@news.astraweb.com> <7d0lj4d9hai2f87r30erc4l1ir85osbfg7@4ax.com> <88579d9a-df52-49b9-a6fe-53c8f4524bf3@j39g2000yqn.googlegroups.com> <70llj41hie2svs68o5efn22i97f649svfh@4ax.com> Message-ID: <1cda9a9a-1641-424b-9f3d-c4e2635efed7@j38g2000yqa.googlegroups.com> On Dec 6, 2:09?pm, Wolfgang Strobl wrote: > Mensanator : > > > > > > >On Dec 6, 8:16?am, Wolfgang Strobl wrote: > >> Dennis Lee Bieber : > > >> >On 05 Dec 2008 05:21:25 GMT, Steven D'Aprano > >> > declaimed the following in > >> >comp.lang.python: > > >> >> On Thu, 04 Dec 2008 08:44:19 -0800, Matimus wrote: > > >> >> > The point was that there > >> >> > is that new releases don't _break_ anything. > > >> >> But that's clearly not true, because the OP is pointing out that the new > >> >> release from 2.5 to 2.6 *does* break his code. > > >> > ? ?One now has to ask what "break" really meant... For this example, > >> >the change did not break Python SYNTAX -- just a complaint about using > >> >what is now a reserved word as an object name. > > >> Of course it does: > > >> C:\Python26>python > >> Python 2.6 (r26:66721, Oct ?2 2008, 11:35:03) [MSC v.1500 32 bit > >> (Intel)] on win 32 > >> Type "help", "copyright", "credits" or "license" for more information.>>> as=2 > > >> ? File "", line 1 > >> ? ? as=2 > >> ? ? ?^ > >> SyntaxError: invalid syntax > > >I disagree. "Broken" is something you can't work > >around. > > Well, that language change _did_ break the OPs code, and he already > explained why it isn't as simple to work around as you obviously happen > to believe. It was extremely simple for me to fix the sympy module where I noticed it. I'm not saying it wasn't a problem, I'm saying it wasn't BROKEN. And no, I couldn't use sympy after the fix because apparently there is some change the way 2.6 hashes which truly breaks the sympy code, so no using sympy with 2.6 until a corrected version is released. And the real problem is that the latest version was released without ever testing it under 2.6. Hopefully, that won't happen again. > ? Calling it "not a SYNTAX error" is not only mistaken, it's > weaseling around the problem too. It's not weaseling around the problem, it's rating the seriousness of the problem. Right now if I need sympy, I HAVE to use 2.5, if I need itertools.permutations I HAVE to use 2.6. But I canot use both in the same program which is a tad more serious than having to rename a variable I had business using in the first place. > > >In this case, simply saying as_=2 works fine. > > Certainly not, for example when that name is already used outside your > control. In addition, you'll have to find all places, where the now > syntactically illegal name is or might be used. This can get arbitrarily > hard in generated ?or foreign code. The difficulty of fixing it isn't the issue, it's whether it can be fixed at all. > > > > >A better example of broken was when the gmpy module > >wouldn't solve a certain linear congruence problem > >because the problem was not invertible. > > What does that have to to with anything? It's an example of what it means to be BROKEN, and yes, nothing at all to do with SYNTAX. > We're disussing a language > change on the syntax level which breaks existing legal code, not how a > numerical library behaves for borderline cases. And yet, you don't consider this a case of "weasel words". Strange. > > [...] > > >> Making a former syntactically valid ?two letter name a reserved word in > >> 2.6 was a mistake, IMHO. > > >I think you're in the minority there. > > Perhaps. Does that matter? Yeah, if you think it will be resolved in your favor. > > >> What's next? What about making i,j,k, x and y > >> reserved words in 2.7? =:-/ > > >Yeah, right. That'll happen. > > Certainly not. ?On the other hand, I was quite flabbergasted by the > change in question, likewise. Wasn't that something ?reserved for 3.0: > breaking code mercilessly? ? Mercilessly? If there were no deprecation warnings, you might have a case there. You act as if the failure to display such warnings was deliberate, but that was due to a BUG, not merciless behaviour on the part of the developers. > What is 3.0 good for, when we have to bear > such breakage in a minor release, already? You're making a mountain out of a molehill. > > >You ought to be more > >concerned about real problems. > > It is a real problem for the OP. Who gave him permission to use 2.6? Is 2.5 suddenly unavailable? Assholes like Microsoft pull stunts like that, but Python.org doesn't. If it's his code, he can easily fix it. If it's someone else's code, he should be using a version guaranteed to work in 2.6. > > -- > Thank you for observing all safety precautions From pythonnutter at gmail.com Sat Dec 6 20:44:19 2008 From: pythonnutter at gmail.com (Python Nutter) Date: Sun, 7 Dec 2008 12:44:19 +1100 Subject: Learning Python now coming from Perl In-Reply-To: References: Message-ID: Perl Cookbook for Python Programmers: http://pleac.sourceforge.net/pleac_python/index.html P3K as starting point (slight cringe) as long as you know the caveats. I'm of the mind as Christopher with regard to how Python 3.0 has been released on Python.org: """I don't think that Python 3.0 is a bad thing. But that it's displayed so prominently on the Python web site, without any kind of warning that it's not going to work with 99% of the Python code out there, scares the hell out of me. People are going to download and install 3.0 by default, and nothing's going to work. They're going to complain, and many are going to simply walk away. - Christopher Lenz""" Python3 is beautiful, and I am totally with James Bennet http://www.b-list.org/weblog/2008/dec/05/python-3000/ That said I would suggest you learn the whole history of the Py3K project and its 19+ years of 20/20 hindsight on what works well and what doesn't so you can if you want to jump right into Python3 fully informed on why it is the way it is and why you need to wait for 3rd party libraries to catch up and release a Python 3 compatible version and why all the Internal libraries are no worry except for the fact some of them have disappeared in the cleanup or merged into a single library. Then you can make sense of all the 2.x books and posts and know where to start when trying to apply it to Python 3. Cheers, PN (Python 2.5.2, Stackless Python 2.5.2, Python 2.6 and Python 3.0 on my box) P.S. Look into iPython as your new favourtie shell and virtualenv to help you keep all your projects straight and you'll be very productive in no time =) 2008/12/7 Bertilo Wennergren : > I'm planning to start learning Python now, using Python 3000. > I have no previous Python skills, but I now Perl pretty well. > I'm also well experienced with JavaScript. > > Any pointers and tips how I should go about getting into > Python? From martin at v.loewis.de Tue Dec 9 17:32:00 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 09 Dec 2008 23:32:00 +0100 Subject: Google Summer of Code 2009 In-Reply-To: <713dd4d7-0427-4b74-a5bc-1e3538afed6c@n10g2000vbl.googlegroups.com> References: <713dd4d7-0427-4b74-a5bc-1e3538afed6c@n10g2000vbl.googlegroups.com> Message-ID: <493EF1E0.90802@v.loewis.de> > I am interested in participating in Google Summer of Code 2009, > hopefully for something in Python. I realize that this is way before > it begins, but I would like to start to get to know the community > better and find something that I could work on during the summer of > code. I know a decent amount of Python, and I am a Sophomore Computer > Science major. My school teaches Java, but on the side I taught > myself Python. If anyone knows of any projects that could use another > hand, I would appreciate it. Traditionally, the PSF SoC participation includes a number of projects, many of them with their own mailing lists etc. Andre has already pointed you to the list of potential projects; the exact set of projects may vary, of course. So if one of them interests you, you should contact the specific mailing lists. If it is Python proper, the list would be python-dev at python.org. Notice that several projects written in Python participate in SoC on their own, e.g. Django. Take a look at the full list of SoC organizations for 2008; perhaps you spot something that interests you. Again, which specific organizations will participate in 2009 will vary again (it's nearly certain that the PSF will get approved again, though). Regards, Martin From lie.1296 at gmail.com Mon Dec 15 00:39:45 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 15 Dec 2008 05:39:45 +0000 (UTC) Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> <0152e35f$0$8244$c3e8da3@news.astraweb.com> <0155c4a7$0$6988$c3e8da3@news.astraweb.com> Message-ID: On Mon, 15 Dec 2008 03:21:21 +0000, Steven D'Aprano wrote: > On Mon, 15 Dec 2008 02:11:10 +0000, Lie Ryan wrote: > >>> So given the normal precedence rules of Python, there is no ambiguity. >>> True, you have to learn the rules, but that's no hardship. >> >> *I* know about the precedence rule, but a newbie or a tired programmer >> might not. He might want to reverse the truth value of argument b but >> instead has just reversed the whole expression. > > And? A newbie or a tired programmer might not know that a^b is bit-wise > xor instead of exponentiation, or that range(n) doesn't include n, or > even that len(alist) returns the length of a list. There's no limit to > the potential mistakes that are possible for a programmer who is tired, > inexperienced, intoxicated or just plain stupid enough. What's your > point? Are you expecting Python to be mistake-proof? > > There's a certain level of knowledge about the language necessary to > program effectively, and learning that "is not" is a single operator is > not particularly onerous. I give up. It does not matter to me anyway. I was just expressing the preference that operators should be composed of a single word, especially since none of the other operators are multi-words (Special cases aren't special enough to break the rules). The only advantage of using 'is not' over 'isnot' is that we have one less keyword to deal with. From mludvig at logix.net.nz Sat Dec 13 04:48:31 2008 From: mludvig at logix.net.nz (Michal Ludvig) Date: Sat, 13 Dec 2008 22:48:31 +1300 Subject: setup.py installs modules to a wrong place Message-ID: <494384EF.7050605@logix.net.nz> Hi, I have recently seen some reports from users of my s3cmd script [1] who installed the package using the provided distutils-based setup.py and immediately after installation the script failed to run because it couldn't find its modules. Here's an example session from Mac OS X, but similar behaviour has been observed on Ubuntu as well. Needless to say it works for me just fine so I can't easily debug and fix it :-( First is the reported setup.py output: ----- ~/bin/s3cmd $ sudo python setup.py install Password: ... running install_lib creating /usr/lib/python2.5/site-packages creating /usr/lib/python2.5/site-packages/S3 copying build/lib/S3/PkgInfo.py -> /usr/lib/python2.5/site-packages/S3 ... more modules, etc ... ----- It decided to put the modules to /usr/lib/python2.5/site-packages/S3 Now, s3cmd should import from there, but fails: ~/bin/s3cmd $ s3cmd Traceback (most recent call last): File "/usr/bin/s3cmd", line 1207, in from S3 import PkgInfo ImportError: No module named S3 sys.path at the time the script died had these entries: /usr/bin /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python25.zip /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5 /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-darwin /System/Library/Frameworks/Python.framework/Versions/2.5/...other_subdirs... /Library/Python/2.5/site-packages There is nothing special in setup.py. After all have a look yourself: http://s3tools.svn.sourceforge.net/viewvc/s3tools/s3cmd/trunk/setup.py?view=markup What could be the reason for distutils / setup.py to install the modules to a directory that's not in sys.path? Can I detect it in setup.py and prevent or workaround it somehow? Thanks! [1] http://s3tools.logix.cz/s3cmd -- Amazon S3 command line client Michal From jules at REMOVETHIS.op59.net Wed Dec 10 09:20:04 2008 From: jules at REMOVETHIS.op59.net (Julian Smith) Date: Wed, 10 Dec 2008 14:20:04 +0000 Subject: Using the `email' module in a bazaar plugin References: <20081210115825.01853c3b.jules@REMOVETHIS.op59.net> Message-ID: <20081210142004.505f121f.jules@REMOVETHIS.op59.net> On Wed, 10 Dec 2008 12:13:28 +0000 Matt Nordhoff wrote: > Julian Smith wrote: > > I don't seem to be able to use the `email' module from within a bazaar > > plugin. Other modules work ok, e.g. nntplib. > > > > Here's my plugin, cut-down to show just the email problem: > > > > import sys > > print 'sys.version', sys.version > > > > import nntplib > > n = nntplib.NNTP( 'jsmith-ubuntu2' ) > > print n > > > > import email > > m=email.MIMEText.MIMEText('text of email') > > > > - and here's the output when i run any bazaar command: > > > > > bzr status > > sys.version 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] > > > > 'module' object has no attribute 'MIMEText' > > Unable to load plugin 'js_notify' from '/home/jsmith/.bazaar/plugins' > > ... > > > > The plugin runs fine on its own, it's only when loaded into Bazaar that things > > go wrong. > > > > I thought perhaps this could be caused by the `email' module's use of > > LazyImporter. I've tried various things such as `from email.mime.text import > > MIMEText', and they fail in similar ways. > > > > I'm using bzr-1.9, python 2.5.2, on Ubuntu-8.xx. > > > > Does anyone have any ideas ? > > > > Thanks, > > > > - Julian > > The built-in email module is probably getting shadowed by another one > (perhaps bzrlib.plugins.email?), so "import email" is importing the > wrong module. You'll have to rename it to something else. > > Have your plugin print email.__path__ to see which module it is. Ah, you're quite right. Curiously, email.__path__ is: /usr/lib/python2.5/site-packages/bzrlib/plugins/email - but sys.path is: ['/usr/bin', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/Numeric', '/usr/lib/python2.5/site-packages/PIL', '/usr/lib/python2.5/site-packages/gst-0.10', '/var/lib/python-support/python2.5', '/usr/lib/python2.5/site-packages/gtk-2.0', '/var/lib/python-support/python2.5/gtk-2.0'] - i.e. no occurrence of `/usr/lib/python2.5/site-packages/bzrlib/plugins'. So i guess bazaar is redefining __import__() to look in the the plugins directory first, or something. Anyway, I can get things to work with the following: import imp email = imp.load_module( 'email', *imp.find_module( 'email', sys.path)) Many thanks, - Julian -- http://op59.net/ From luismgz at gmail.com Sun Dec 7 20:10:00 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Sun, 7 Dec 2008 17:10:00 -0800 (PST) Subject: Python for kids? References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> <53f406ed-c261-4d86-a8dc-4001d10d05b5@s20g2000yqh.googlegroups.com> Message-ID: <11a3e492-3c0d-475f-b350-f28351842dad@f3g2000yqf.googlegroups.com> This is a very good advice. I learned from my own experience in college that trying to learn a solution to a problem I never had, is wasted time. The first step is confronting your student with an specific problem, then let him try to find a way to solve it by himself. After he tried hard many approaches to solving the problem with his limited knowledge, show him the right way. This way he will see the light. I believe that many teachers don't know this basic concept, and they simply teach in a mechanical way, without having their students interested in the subject or without having explained them what exactly these skills are good for. Luis On Dec 7, 5:37?pm, bearophileH... at lycos.com wrote: > On Dec 7, 9:13?pm, "Russ P." wrote: > > > I have a 12-year-old son who spends too much time playing Xbox live > > and watching silly YouTube videos. I would like to try to get him > > interested in programming. > > Lot of people learn to program even before age of 12. > But I think it's better for you to help him get interest in problem- > solving and some of the other bases of the mathematic, scientific and > computational mindset. Once those interests are in place, he will > probably go looking by himself for things like programming languages, > math and science (of course at that point a gentle guide toward good > ideas, good problems to solve, good books to read and good programming > languages, helps). > > Otherwise you risk pushing a person to learn using a tool (programming > is interesting by itself, but it's mostly a tool still) before having > any use for such tool or desire to learn it. And this may lead to > someone with no passion to solve problems and learn. > > Bye, > bearophile From gagsl-py2 at yahoo.com.ar Tue Dec 2 03:03:29 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Dec 2008 06:03:29 -0200 Subject: how can I open an excel sheet with specified name References: Message-ID: En Fri, 28 Nov 2008 23:12:50 -0200, Zuo, Changchun escribi?: > Could you please send me an example script example of > > * Opening an excel workbook with specified name > * Read or write number in a specified spreadsheet There is a specific group for those topics: python-excel [1] I'd suggest using the excelent xlrd [2] and xlwt [3] packages. [1] http://groups.google.com/group/python-excel/ [2] http://pypi.python.org/pypi/xlrd [3] http://pypi.python.org/pypi/xlwt -- Gabriel Genellina From sjmaster at gmail.com Sat Dec 6 11:59:26 2008 From: sjmaster at gmail.com (Steve M) Date: Sat, 6 Dec 2008 08:59:26 -0800 (PST) Subject: Can't get exclusive file lock when safely renaming a file References: <014a049b$0$20670$c3e8da3@news.astraweb.com> Message-ID: <872b1222-1410-404b-890c-ca2ca69faab1@41g2000yqf.googlegroups.com> On Dec 6, 12:25?am, Steven D'Aprano wrote: > The rename works, but here is my problem: after getting what I thought > was an exclusive lock on the new file, but before calling os.rename(), I > can still over-write it from another process: > > $ echo "this comes from another process" > spam.txt > $ cat spam.txt > this comes from another process What happens if you try to delete spam.txt at this point instead of over-write it? From ldo at geek-central.gen.new_zealand Sun Dec 7 02:27:51 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 07 Dec 2008 20:27:51 +1300 Subject: Don't you just love writing this sort of thing :) References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: In message , Rhodri James wrote: > Yes, it's very pretty, and you're terribly clever. In six months' time > when you come back to make some engineering change and have to sit down > and break it back down into those simple pieces to remind yourself what > it's doing, "pretty" and "clever" will not be the words you are using. > Trust me on this one. Considering I've been writing and maintaining and debugging code for about 30 years now, I figure I have the hard-earned right to judge what I will be able to understand in six months and what I won't... -- Lawrence "Been There, Done That" D'Oliveiro From Scott.Daniels at Acm.Org Wed Dec 24 14:48:57 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 24 Dec 2008 11:48:57 -0800 Subject: Iterating over objects of a class In-Reply-To: <7f47994f-13b6-45c4-920a-83aa72282bec@i20g2000prf.googlegroups.com> References: <2df27de3-7fa3-4ac9-acd9-f946939517cf@r37g2000prr.googlegroups.com> <6rfb7iF1fg5rU1@mid.uni-berlin.de> <7f47994f-13b6-45c4-920a-83aa72282bec@i20g2000prf.googlegroups.com> Message-ID: <7M-dnekT_vCVD8_UnZ2dnUVZ_q_inZ2d@pdx.net> Kottiyath wrote: > ... > Having a registry inside the class instance and looping through them > was the only clean thing I could think of. > I understand that garbage collection would be an issue - but is there > any way out? Search for weakref in the documentatione. In this case, I'd use a WeakValueDictionary() from id(obj) to obj. Note id(obj) is guaranteed to be unique for all objects in existance, but the id of a collected object may match the id of a new object. >>> import weakref >>> d = weakref.WeakValueDictionary() >>> vs = [Int(n) for n in range(3, 500, 70)] >>> for n in vs: d[id(n)] = n v = Int(n+1) d[id(v)] = v >>> for obj in d.values(): # values is safer than itervalues print obj >>> # note the above was the following, which fails: >>> for v in d.values(): # values is safer than itervalues print v For extra credit, explain why values is better. --Scott David Daniels Scott.Daniels at Acm.Org From goatold at gmail.com Tue Dec 16 00:30:57 2008 From: goatold at gmail.com (goatold at gmail.com) Date: Mon, 15 Dec 2008 21:30:57 -0800 (PST) Subject: socket and subprocess problem References: <6d3291c3-4e12-4bdd-884a-21f15f38d105@a12g2000pro.googlegroups.com> Message-ID: <73dca20d-3378-4c96-aa30-f0617f111fa0@i18g2000prf.googlegroups.com> Guys thanks to point it out. Yes, it's a race problem. I tried sleep long enough, then I can connect to the socket. I should add code to try to connect to the socket for a given time out. Roy Smith wrote: > In article > <6d3291c3-4e12-4bdd-884a-21f15f38d105 at a12g2000pro.googlegroups.com>, > goatold at gmail.com wrote: > > > In my python code I use subprocess.Popen to run and external program > > who will listen to a TCP port. And I also create a socket to connect > > to the TCP port that the external program is listening. > > I will get 'Connection refused, errno=111' when I try to > > socket.connect(). > > > Class a: > > def run() > > subprocess.Popen(..) > > Class b: > > def run(): > > sock = socket.socket() > > sock.connect(..) > > ################################# > > test.py > > # socket connect will fail here > > a.run() > > b.run() > > ################################### > > test1.py > > if __name__ = '__main__': > > a.run() > > > > test2.py > > # socket will connect fine > > if __name__ = '__main__': > > b.run > > Sounds like a timing problem. I assume that the process started by a.run() > creates a socket and does a bind/listen/accept sequence on it. The problem > is, there's nothing in your code which guarantees that this happens before > b.run() executes the connect() call. > > The cheesy way to test this is to sleep for a second somewhere between > a.run() and b.run(). See if that helps. > > If it doesn't, then it's possible the process started by a.run() isn't > doing what it's supposed to do. Try running test1.py, and while it's > running, run netstat to see if you've got something listening on the port > you expect. From gagsl-py2 at yahoo.com.ar Sun Dec 14 02:38:05 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 14 Dec 2008 05:38:05 -0200 Subject: 1 or 1/0 doesn't raise an exception References: <49446E39.6020807@tim.thechases.com> Message-ID: En Sun, 14 Dec 2008 02:40:10 -0200, Benjamin Kaplan escribi?: > On Sat, Dec 13, 2008 at 10:49 PM, Daniel Fetchinson < > fetchinson at googlemail.com> wrote: > >> >> Is it a feature that >> >> >> >> 1 or 1/0 >> >> >> >> returns 1 and doesn't raise a ZeroDivisionError? If so, what's the >> >> rationale? >> > >> > http://en.wikipedia.org/wiki/Short-circuit_evaluation >> >> Let me just point out that unsuspecting people (like me) might rely on >> the whole expression to be evaluated and rely on exceptions being >> raised if needed. > > If you want both expressions evaluated, you can use & and |, just like > in C > and Java (&& and || are used for short circuit evaluation in those > languages). No: &, | (and ^, too) perform bitwise operations in Python, C and Java: py> 1 & 2 0 && and || --in both C and Java-- are like `and` and `or` in Python; they perform logical operations, and short-circuit evaluation of their operands. If you want to evaluate a logical expression without short circuiting, do that explicitely: a = first part b = second part if a or b: ... -- Gabriel Genellina From mail at microcorp.co.za Wed Dec 3 22:13:09 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 4 Dec 2008 05:13:09 +0200 Subject: Thread Tkinter problem References: <64c7402c-8b7b-4281-9d7d-1abdd6177d96@r15g2000prh.googlegroups.com> Message-ID: <001801c955be$798e83e0$0d00a8c0@hendrik> "Davy" wrote: > while(data_queue.full() == False): This will fill the queue and stop. Use while true and if queue not full... - Hendrik From mr.spoon21 at gmail.com Tue Dec 16 14:59:57 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Tue, 16 Dec 2008 20:59:57 +0100 Subject: Free place to host python files? In-Reply-To: References: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> <32599660-2393-4e18-8c48-05d64bccbbc1@t26g2000prh.googlegroups.com> Message-ID: <8f67b6f80812161159m6822117eh5ea5d23d7bfcf331@mail.gmail.com> 2008/12/16 feba : > Stuff like code.google, sf.net, are more oriented towards serious > development, not just holding random apps, aren't they? > > Anyway, I found MediaFire, which looks like it will suffice for now. Take a look to Dropbox (http://www.getdropbox.com/). You can use it to directly share files with your friends or to create a public link to your files so other people can download them. From iofferkicks21 at gmail.com Wed Dec 24 00:10:59 2008 From: iofferkicks21 at gmail.com (www.iofferkicks.com) Date: Tue, 23 Dec 2008 21:10:59 -0800 (PST) Subject: www.iofferkicks.com china cheap wholesale nike shoes,air jordan shoes,air force one shoes. Message-ID: <9bab9ca1-5f3a-4c40-9dc8-cbcadbb6b8d3@n33g2000pri.googlegroups.com> Get Nike Shoes at Super Cheap Prices Discount Nike air jordans (www.iofferkicks.com) Discount Nike Air Max 90 Sneakers (www.iofferkicks.com) Discount Nike Air Max 91 Supplier (www.iofferkicks.com) Discount Nike Air Max 95 Shoes Supplier (www.iofferkicks.com) Discount Nike Air Max 97 Trainers (www.iofferkicks.com) Discount Nike Air Max 2003 Wholesale (www.iofferkicks.com) Discount Nike Air Max 2004 Shoes Wholesale (www.iofferkicks.com) Discount Nike Air Max 2005 Shop (www.iofferkicks.com) Discount Nike Air Max 2006 Shoes Shop (www.iofferkicks.com) Discount Nike Air Max 360 Catalogs (www.iofferkicks.com) Discount Nike Air Max Ltd Shoes Catalogs (www.iofferkicks.com) Discount Nike Air Max Tn Men's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 2 Women's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 3 Customize (www.iofferkicks.com) Discount Nike Air Max Tn 4 Shoes Customize ( www.iofferkicks.com) Discount Nike Air Max Tn 6 Supply (www.iofferkicks.com) Discount Nike Shox NZ Shoes Supply (www.iofferkicks.com) Discount Nike Shox OZ Sale (www.iofferkicks.com) Discount Nike Shox TL Store (www.iofferkicks.com) Discount Nike Shox TL 2 Shoes Store (www.iofferkicks.com) Discount Nike Shox TL 3 Distributor (www.iofferkicks.com) Discount Nike Shox Bmw Shoes Distributor (www.iofferkicks.com) Discount Nike Shox Elite Shoes Manufacturer (www.iofferkicks.com) Discount Nike Shox Monster Manufacturer (www.iofferkicks.com) Discount Nike Shox R4 Running Shoes (www.iofferkicks.com) Discount Nike Shox R5 Mens Shoes (www.iofferkicks.com) Discount Nike Shox Ride Womens Shoes (www.iofferkicks.com) Discount Nike Shox Rival Shoes Wholesaler (www.iofferkicks.com) Discount Nike Shox Energia Wholesaler (www.iofferkicks.com) Discount Nike Shox LV Sneaker (www.iofferkicks.com) Discount Nike Shox Turbo Suppliers (www.iofferkicks.com) Discount Nike Shox Classic Shoes Suppliers (www.iofferkicks.com) Discount Nike Shox Dendara Trainer (www.iofferkicks.com) Discount Nike Air Jordan 1 Seller (www.iofferkicks.com) Discount Nike Air Jordan 2 Shoes Seller (www.iofferkicks.com) Discount Nike Air Jordan 3 Collection (www.iofferkicks.com) Discount Nike Air Jordan 4 Shoes Collection (www.iofferkicks.com) Discount Nike Air Jordan 5 Chaussure Shoes (www.iofferkicks.com) Discount Nike Air Jordan 6 Catalog (www.iofferkicks.com) Discount Nike Air Jordan 7 Shoes Catalog (www.iofferkicks.com) Discount Nike Air Jordan 8 Customized (www.iofferkicks.com) Discount Nike Air Jordan 9 Shoes Customized (www.iofferkicks.com) Discount Nike Air Jordan 10 Wholesalers (www.iofferkicks.com) Discount Nike Jordan 11 Shoes Wholesalers (www.iofferkicks.com) Discount Nike Air Jordan 12 Factory (www.iofferkicks.com) Discount Nike Air Jordan 13 Shoes Factory (www.iofferkicks.com) Discount Nike Air Jordan 14 Shoes Sell (www.iofferkicks.com) Discount Nike Air Jordan 16 Exporter (www.iofferkicks.com) Discount Nike Air Jordan 17 Shoes Exporter (www.iofferkicks.com) Discount Nike Air Jordan 18 Offer (www.iofferkicks.com) Discount Nike Air Jordan 19 Shoes Offer (www.iofferkicks.com) Discount Nike Air Jordan 20 Manufacture (www.iofferkicks.com) Discount Nike Jordan 21 Shoes Manufacture (www.iofferkicks.com) EMAIL:IOFFERKICKS at GMAIL.COM MSN :IOFFERKICKS at MSN.COM From ShannonL at yogananda-srf.org Tue Dec 2 17:55:14 2008 From: ShannonL at yogananda-srf.org (ShannonL at yogananda-srf.org) Date: Tue, 2 Dec 2008 14:55:14 -0800 Subject: Hashlib py26 Message-ID: This feels a bit silly, but I am trying to encrypt some simple text with the new hashlib library and then decrypt it back into text. I can do this with M2Crypto RC4, but not the new hashlib. Could someone give me a quick example. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sturlamolden at yahoo.no Fri Dec 12 10:56:58 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 07:56:58 -0800 (PST) Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> Message-ID: <31443882-cb41-420b-8269-b1590581783d@c36g2000prc.googlegroups.com> On Dec 12, 4:55 pm, sturlamolden wrote: > def __setitem__(self, index, value): > if _buf[index] is not value: # given that _buf is the tuple's > internal buffer > raise TypeError, 'tuple' object does not support item > assignment bl?h, that should be self._buf[index] From sbergman27 at gmail.com Fri Dec 19 12:37:27 2008 From: sbergman27 at gmail.com (Steve Bergman) Date: Fri, 19 Dec 2008 09:37:27 -0800 (PST) Subject: Building a web questionnaire, can it be done in Python ? References: Message-ID: <07750b8c-3648-4214-b520-931142b4f0a0@z28g2000prd.googlegroups.com> The most popular choice for web apps, and the one I use myself, would be Django. You might post your question in the Django group: http://groups-beta.google.com/group/django-users The only thing that I see that could be a problem would be the legacy database. But that depends very much upon your exact situation. From tgrav at mac.com Sat Dec 6 12:21:39 2008 From: tgrav at mac.com (Tommy Grav) Date: Sat, 06 Dec 2008 12:21:39 -0500 Subject: Guido's new method definition idea In-Reply-To: References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> <8b8d1fb3-f49e-49bf-8cfe-eeee5ed16109@r37g2000prr.googlegroups.com> <014a932b$0$20670$c3e8da3@news.astraweb.com> Message-ID: <3CB45A5D-9C99-4167-BB00-53F72958B5F6@mac.com> On Dec 6, 2008, at 11:42 AM, bearophileHUGS at lycos.com wrote: > class ThisIsAClass: > def $some_method(arg1, arg2): > $value = arg1 + $foo + $bar + $baz * arg2 > ... I think my biggest problem with this is what got me off Perl. Add $, together with already used @ and maybe some other identifiers and I start loosing track of what each of the character means. It is fine when you are used to the language, but learning it becomes a harder proposition. self.foo is self-explanatory (no pun intended) to me, $foo is not. Cheers Tommy From rt8396 at gmail.com Fri Dec 12 14:41:21 2008 From: rt8396 at gmail.com (r) Date: Fri, 12 Dec 2008 11:41:21 -0800 (PST) Subject: newbie question... References: Message-ID: i was just giving you an example from my TextEditor.py script. this is how arg works lets say you have a script named MyScript.py --- import sys print sys.argv --- call the script with arguments > MyScript.py 99 100 ['C:\\Python25\\MyScript.py', '99', '100'] int(sys.argv[1]) -> 99 From warren at delsci.com Wed Dec 3 16:38:23 2008 From: warren at delsci.com (Warren DeLano) Date: Wed, 3 Dec 2008 13:38:23 -0800 Subject: "as" keyword woes Message-ID: <896B75251BA19745A529B1B867893FA50679C6@planet.delsci.local> A bottom line / pragmatic question... hopefully not a FAQ. Why was it necessary to make "as" a reserved keyword? And more to the point, why was it necessary to prevent developers from being able to refer to attributes named "as"? For example, this code breaks as of 2.6 / 3.0: Class C: Pass obj = C() obj.bs = 2 # valid obj.as = 1 # syntax error obj.cs = 3 # valid Just to be clear: I understand why it breaks, since "as" is now a keyword, I also know that one can use workarounds such as: obj.__dict__['as'] = 1 to maintain compatibility. What I want to understand is why this parser change was necessary in order to enable new 2.6/3.0 features. Was this change potentially avoidable? Why can't the parser distinguish between a standalone " as " keyword and ".as" used as an object/attribute reference? Couldn't we have continued along just fine using a smarter parser without elevating "as" to reserved status (and thus potentially breaking a 10+ years of existing code)? Thank you for enlighting me! (Unfortunately, our project may now have to maintain a branch at 2.5.x in order to preserve compatibility with existing third-party scripts & infrastructure which routinely rely upon "as" as an object method. Sigh.) Cheers, Warren From robert.kern at gmail.com Sun Dec 7 19:27:44 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 07 Dec 2008 18:27:44 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Terry Reedy wrote: > Robert Kern wrote: >> Terry Reedy wrote: >>> Rasmus Fogh wrote: > >>>> Personally I would like to get these !@#$%&* misfeatures removed, >>> >>> What you are calling a misfeature is an absence, not a presence that >>> can be removed. >> >> That's not quite true. > > In what way, pray tell. My statement still looks quite true to me. There is an explicit policy that __eq__() methods can return non-bools for various purposes. I consider that policy to a "presence that can be removed". There is no check because that policy exists, not the other way around. Anyways, this is really a semantic digression, and not particularly important. Peace? -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From googler.1.webmaster at spamgourmet.com Thu Dec 25 05:39:16 2008 From: googler.1.webmaster at spamgourmet.com (googler.1.webmaster at spamgourmet.com) Date: Thu, 25 Dec 2008 02:39:16 -0800 (PST) Subject: Python with PyGIL_Ensure? References: Message-ID: <0591a852-0f41-492f-9016-2bf603964a04@i20g2000prf.googlegroups.com> and merry christmas :) From tjreedy at udel.edu Mon Dec 1 15:45:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Dec 2008 15:45:58 -0500 Subject: end of print = lower productivity ? In-Reply-To: References: Message-ID: Alan G Isaac wrote: > I actually trust that the developers had good > reasons for this change, but I think it is > silly to argue that it is costless. Guido ever argued that. > The question is, what is the cost-benefit trade-off? Uniformity of language, flexibility, and removal of the >> hack that Guido hated after adding. Check the pydev discussions. > One obvious cost is that working at the > interpreter prompt is now slightly less > convenient. But neither 'print' nor 'print()' is needed at the interpreter prompt. > Just because the cost is small > does not mean it should not be offset by a > benefit. > > I am less sympathetic to the suggestion that > there is an inconvenience when working in > an editor, but clearly some people find one. That is the only time 'print' or 'print()' is needed. I find it a minor nuisance also, but then I should learn to touch-type () better anyway for all the other uses. > My preferred transition would have been to > retain the `print` statement but add a `printf` > function (i.e., the new `print` function). > Presumably many would find this a repulsive > redundancy and a needless maintenance headache. Yes. tjr From steve at REMOVE-THIS-cybersource.com.au Tue Dec 2 08:50:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Dec 2008 13:50:41 GMT Subject: performance question: dictionary or list, float or string? References: Message-ID: <01453507$0$20670$c3e8da3@news.astraweb.com> On Tue, 02 Dec 2008 03:41:29 -0800, bkamrani wrote: > Hi Python gurus! > I'm going to read in an Ascii file containing float numbers in rows and > columns (say 10 columns 500000 rows) for further numerical process. > Which format is best to save them in, eg, dictionary, list, or numpy > array when it comes to performance? That depends on: (1) What do you mean by performance? Speed or memory use? (2) Do you care about the performance of reading the data in, or the performance of working with the data later, or both? (3) What do you intend to do with the numbers later? > Will it be beneficial to convert all strings to float directly after > reading or it doesn't matter to save them as string and thereafter when > it comes to calculation convert them to floats? That depends on what you intend to do with them. Since you're doing numerical processing, it's probably a good idea to convert them to numbers rather than strings. -- Steven From Rick at youtellme.com Thu Dec 25 21:24:49 2008 From: Rick at youtellme.com (Rick van Hattem) Date: Fri, 26 Dec 2008 03:24:49 +0100 Subject: How to stop subprocesses from copying listening sockets Message-ID: <200812260324.50166.Rick@youtellme.com> Hi everyone, Recently I've started building a program that spawns new processes when requested via http, since the http interface doesn't need to be fancy I've just used the BaseHTTPServer module for this, but... it seems I'm running into a little problem. When spawning a new process (which forks itself into a daemon, but isn't too relevant in this case) the listening socket is copied to the new process. Evidently this results in the base process not being able to restart since the new spawned process starts listening on the port. Here's a simple example of what I mean. Assuming we've got the server like this: import subprocess import BaseHTTPServer server = BaseHTTPServer.HTTPServer(('', 1234), BaseHTTPServer.BaseHTTPRequestHandler) subprocess.Popen(['python', 'the_daemon.py']) With the_daemon.py being this: import time time.sleep(60) And we run the main server and kill it after that (i.e. using netstat to find the PID), we'll see that the new process which does nothing besides wait for 60 second will listen on port 1234 (use netstat to confirm). Anyone has an idea on how to circumvent this issue? Kind regards, Rick van Hattem PS: tested both on Fedora 8 using Python 2.5.1 and Gentoo Linux 2008 using Python 2.5.2 From clp at rebertia.com Mon Dec 8 17:29:01 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 8 Dec 2008 14:29:01 -0800 Subject: Calling function from a string In-Reply-To: <7bc1be6f-121e-409a-9e08-f2dd2a86f241@e25g2000vbe.googlegroups.com> References: <7bc1be6f-121e-409a-9e08-f2dd2a86f241@e25g2000vbe.googlegroups.com> Message-ID: <47c890dc0812081429o6a3226fanccaca84e903cd923@mail.gmail.com> On Mon, Dec 8, 2008 at 2:23 PM, Robert Dailey wrote: > Hi, > > I have a string representing the name of a function in Python 3.0. How > can I call the function name represented by this string *without* > creating a mapping? Assuming the function is within scope: return_val = vars()[the_string](arguments, go, here) Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > From rhodri at wildebst.demon.co.uk Wed Dec 10 19:33:32 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Thu, 11 Dec 2008 00:33:32 -0000 Subject: How to pass out the result from iterated function In-Reply-To: References: Message-ID: On Wed, 10 Dec 2008 20:16:56 -0000, JD wrote: > I got a iterated function like this: > > def iterSomething(list): > has_something = False > for cell in list: > if something in cell: > has_something = True > output = something > if has_something: > iterSomething(output) > else: > final_out = outupt > > The problem is how can I read this final_out outside of the function. > I tried the global statement, it seems not work. Any idea? Isn't this going to throw an exception anyway if 'something' doesn't appear in 'list'? You try assigning 'output' to 'final_out' with no guarantee that 'output' has ever been assigned to. -- Rhodri James *-* Wildebeeste Herder to the Masses From ajaksu at gmail.com Tue Dec 23 13:11:28 2008 From: ajaksu at gmail.com (ajaksu) Date: Tue, 23 Dec 2008 10:11:28 -0800 (PST) Subject: python3 urlopen(...).read() returns bytes References: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> <5496b34d-7ce4-4281-9f01-aed12dab9fd3@f33g2000vbf.googlegroups.com> <42ad842c-8d8a-4ff5-a721-0688b7ae20f7@41g2000yqf.googlegroups.com> Message-ID: <9480ac97-9c0b-445c-ad62-eb418a54f6a1@o40g2000yqb.googlegroups.com> On Dec 23, 12:51?pm, Christian Heimes wrote: > If you want to do it right ... It should be a clean patch against the > py3k svn branch Done > including documentation This thread is a good start :) > and a unit test. Doing this now. Daniel From de.slotenzwemmer at gmail.com Wed Dec 24 10:54:39 2008 From: de.slotenzwemmer at gmail.com (Dennis van Oosterhout) Date: Wed, 24 Dec 2008 16:54:39 +0100 Subject: =?ISO-8859-1?Q?object_ori=EBnted?= Message-ID: I know that python is an Object Ori?nted language but I was wondering if it gets used as a non-OOP also (by a good amount of people). -------------- next part -------------- An HTML attachment was scrubbed... URL: From collin.day.0 at gmail.com Thu Dec 18 21:27:35 2008 From: collin.day.0 at gmail.com (Collin D) Date: Thu, 18 Dec 2008 18:27:35 -0800 (PST) Subject: Factoring Polynomials References: <919062f9-765e-4279-aa26-2c130d4deacf@o4g2000pra.googlegroups.com> Message-ID: <4479b464-3a9b-4dd8-bf66-fea7d9471091@n33g2000pri.googlegroups.com> On Dec 18, 6:23?pm, "Russ P." wrote: > On Dec 18, 6:17?pm, Collin D wrote: > > > > > > > On Dec 18, 6:12?pm, Collin D wrote: > > > > On Dec 18, 11:37?am, collin.da... at gmail.com wrote: > > > > > I am trying to write a simple application to factor polynomials. I > > > > wrote (simple) raw_input lines to collect the a, b, and c values from > > > > the user, but I dont know how to implement the quadratic equation > > > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > > > into python. Any ideas? > > > > I completed the code: > > > > #import > > > from math import sqrt > > > > # collect data > > > a = float(raw_input('Type a value: ')) > > > b = float(raw_input('Type b value: ')) > > > c = float(raw_input('Type c value: ')) > > > > # create solver > > > def solver(a,b,c): > > > ? ? if b**2 - 4*a*c < 0: > > > ? ? ? ? return 'No real solution.' > > > ? ? else: > > > ? ? ? ? sol1 = -1 * b + (sqrt(b**2 - 4*a*c)) / 2*a > > > ? ? ? ? sol2 = -1 * b - (sqrt(b**2 - 4*a*c)) / 2*a > > > ? ? ? ? return (sol1, sol2) > > > > # execute > > > print solver(a,b,c) > > > > Thanks to everyone who helped... > > > This really expanded my knowledge on some of the mathematical > > > functions in Python. > > > UPDATE: > > ' > > > #import > > from math import sqrt > > > # collect data > > a = float(raw_input('Type a value: ')) > > b = float(raw_input('Type b value: ')) > > c = float(raw_input('Type c value: ')) > > > # create solver > > def solver(a,b,c): > > ? ? if b**2 - 4*a*c < 0: > > ? ? ? ? return 'No real solution.' > > ? ? else: > > ? ? ? ? sol1 = (-1 * b + (sqrt(b**2 - 4*a*c))) / 2*a > > ? ? ? ? sol2 = (-1 * b - (sqrt(b**2 - 4*a*c))) / 2*a > > ? ? ? ? return (sol1, sol2) > > > # execute > > print solver(a,b,c) > > You need to put your denominator, 2*a, in parens. The way it stands, > you are dividing by 2, then multiplying by a. That's not what you > want. > > Also, for better style, I suggest you compute the discriminanat once > and store it for reuse rather than repeating the expression three > times.- Hide quoted text - > > - Show quoted text - I see what you mean on the denominator and discriminant. Ill do that. From miki.tebeka at gmail.com Mon Dec 15 20:52:34 2008 From: miki.tebeka at gmail.com (Miki) Date: Mon, 15 Dec 2008 17:52:34 -0800 (PST) Subject: How can I return a non-zero status result from a python script? References: <74b53da4-bf07-431b-898b-49977f7a685c@r36g2000prf.googlegroups.com> Message-ID: <5a289491-662c-49f2-98c7-aae100078a8a@r15g2000prd.googlegroups.com> Hello, > How can I return a non-zero status result from the script? Just do a > return 1? at the end? raise SystemExit(1) HTH, -- Miki http://pythonwise.blogspot.com From eric at ericaro.net Mon Dec 8 05:55:56 2008 From: eric at ericaro.net (eric) Date: Mon, 8 Dec 2008 02:55:56 -0800 (PST) Subject: Determining whether a variable is less/greater than a range. References: <362ab93b-b804-4ebe-a22f-e422feb301c8@c1g2000yqg.googlegroups.com> Message-ID: On Dec 8, 11:44?am, "simonharrison... at googlemail.com" wrote: > Hi. I'm having another go at learning Python so I'll probably be > asking a few basic questions. Here is the first one. > > a = list(range(10, 21) > > b = 9 > > c = 21 > > How can I find out if b and c have values less or more than the values > in list a? > > Thanks. what about: a = list(range(10, 21)) def compare(value, list): m,M = min(list), max(list) return value>=m, value<=M b = 9 c = 21 print compare(b,a) print compare(c,a) for i in range (8, 25): print i, compare(i, a) """ (False, True) (True, False) 8 (False, True) 9 (False, True) 10 (True, True) 11 (True, True) 12 (True, True) 13 (True, True) 14 (True, True) 15 (True, True) 16 (True, True) 17 (True, True) 18 (True, True) 19 (True, True) 20 (True, True) 21 (True, False) 22 (True, False) 23 (True, False) 24 (True, False) """ it helps? From BrianVanderburg2 at aim.com Mon Dec 15 16:46:28 2008 From: BrianVanderburg2 at aim.com (Brian Allen Vanderburg II) Date: Mon, 15 Dec 2008 16:46:28 -0500 Subject: Limit traceback from most recent call In-Reply-To: <8ab4f9a8-3629-4f6a-bbf2-1deed8624215@w24g2000prd.googlegroups.com> References: <8ab4f9a8-3629-4f6a-bbf2-1deed8624215@w24g2000prd.googlegroups.com> Message-ID: <4946D034.30609@aim.com> yinon.me at gmail.com wrote: > On Dec 14, 8:07 pm, Brian Allen Vanderburg II > wrote: > > > Hi, > > The interface of extract_tb is: > traceback.extract_tb(tb, limit=None) > try to play with the 'limit' argument > > Good luck, > Yinon > -- > http://mail.python.org/mailman/listinfo/python-list > I have, but the limit argument shows the first items and not the last items (where the exception occurred): def a(): b() def b(): c() def c(): d() def d(): open('/path/to/fake/file') try: a(): except: print traceback.format_exc(limit=2) try: a(): except: print format_partial_exc(limit=2) Prints something like this Traceback (most recent call last): File "b.py", line 52, in ? a() File "b.py", line 19, in a b() IOError: [Errno 2] No such file or directory: '/path/to/fake/file' Traceback (most recent call last): File "b.py", line 25, in c d() File "b.py", line 29, in d handle=open('/path/to/fake/file', 'rt') IOError: [Errno 2] No such file or directory: '/path/to/fake/file' The second one (using format_partial_exc) prints the last two items of the traceback instead of the first, showing the error is line 29 in function d, the first one limits the traceback but gives no indication of where the error occurred. Brian A. Vanderburg II -------------- next part -------------- An HTML attachment was scrubbed... URL: From zevboy at gmail.com Fri Dec 5 07:23:44 2008 From: zevboy at gmail.com (Huytason) Date: Fri, 5 Dec 2008 20:23:44 +0800 Subject: i use the urllib question Message-ID: i use pthon 3.0 today python code: import urllib.request then use PyRun_StringFlag to run it. get this it's a bug? -------------- next part -------------- An HTML attachment was scrubbed... URL: From geon at post.cz Fri Dec 26 11:44:08 2008 From: geon at post.cz (Pavel Kosina) Date: Fri, 26 Dec 2008 17:44:08 +0100 Subject: tkinter 3.0 multiple keyboard events together In-Reply-To: <600d4b68-6fe2-4c2c-b425-1a739430bb54@s9g2000prg.googlegroups.com> References: <600d4b68-6fe2-4c2c-b425-1a739430bb54@s9g2000prg.googlegroups.com> Message-ID: <495509D8.10105@post.cz> janislaw napsal(a): > On 26 Gru, 05:52, Pavel Kosina wrote: > >> Is it possible to catch in an event more that one key from keyboard? In >> my code, I can handle always the only one, the first I press, the others >> are omitted. Say, I press both "4" and "8" and only "4" is catched. >> >> def movePlayer(event): >> print (event.keysym) >> > Each keypress triggers another event. Fortunately there are two types > of events: reaction to press and release. The logic to write to > recognize those as simultaneous clicks is up to you :) > Might you give me a little bit more? Just a link to a site where this is explained and showed would be OK. I really did my best but everything is bad. geon From duncan.booth at invalid.invalid Tue Dec 23 08:30:25 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Dec 2008 13:30:25 GMT Subject: Are python objects thread-safe? References: <5306b56c-eb8c-4148-b426-013caa871375@b41g2000pra.googlegroups.com> Message-ID: Aaron Brady wrote: > Th.1 Th.2 > a=X > a=Y > a=Z > > You are saying that if 'a=Z' interrupts 'a=Y' at the wrong time, the > destructor for 'X' or 'Y' might not get called. Correct? In serial > flow, the destructor for X is called, then Y. No, the destructors will be called, but the destructors can do pretty much anything they want so you can't say the assignment is atomic. This isn't actually a threading issue: you don't need multiple threads to experience werid issues here. If you do strange things in a destructor then you can come up with confusing code even with a single thread. > >> Other nasty things can happen if you use dictionaries from multiple >> threads. You cannot add or remove a dictionary key while iterating over >> a dictionary. This isn't normally a big issue, but as soon as you try to >> share the dictionary between threads you'll have to be careful never to >> iterate through it. > > These aren't documented, IIRC. Did you just discover them by trial > and error? > It is documented, but I can't remember where for Python 2.x. For Python 3, PEP 3106 says: "As in Python 2.x, mutating a dict while iterating over it using an iterator has an undefined effect and will in most cases raise a RuntimeError exception. (This is similar to the guarantees made by the Java Collections Framework.)" -- Duncan Booth http://kupuguy.blogspot.com From gagsl-py2 at yahoo.com.ar Fri Dec 12 20:55:03 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 12 Dec 2008 23:55:03 -0200 Subject: Py_GetPath() C API in python 3 References: <772bb62b-1ef1-4ffa-90f6-c1cbdc728fdd@q30g2000prq.googlegroups.com> Message-ID: En Fri, 12 Dec 2008 04:50:06 -0200, stalex escribi?: >> I want to build a new, requires total control, python interpreter. So >> I implement my own version of Py_GetPath(), Py_GetPrefix(), >> Py_GetExecPrefix() and Py_GetProgramFullPath(). When compiling, I >> always get error messages, for each API function, look like >> followings: >> >> /opt/python-3.0/lib/python3.0/config/libpython3.0.a(getpath.o)(.text >> +0x211c): In function `Py_GetPath': >> ./Modules/getpath.c:739: multiple definition of `Py_GetPath' >> myApp.o(.text+0x0):/home/alex/workspace/develop/src/myApp.c:11: first >> defined here >> /usr/bin/ld: Warning: size of symbol `Py_GetPath' changed from 126 in >> system.o to 32 in /opt/python-3.0/lib/python3.0/config/libpython3.0.a >> (getpath.o) >> collect2: ld returned 1 exit status Looks like you added your own implementation of those functions (/home/alex/...myApp.c) but forgot to remove the original one (Modules/getpath.c) -- Gabriel Genellina From python at rgbaz.eu Thu Dec 25 06:34:40 2008 From: python at rgbaz.eu (Python) Date: Thu, 25 Dec 2008 12:34:40 +0100 Subject: os.system('cls') In-Reply-To: References: Message-ID: <05BADA85-33ED-48BF-B251-2CC830D6D55E@rgbaz.eu> On 25 dec 2008, at 11:22, Dennis van Oosterhout wrote: > Hi there! I was searching for a way to clear the 'DOS screen'/ > command screen etc. and found that os.system('cls') works for this. > I was just wondering where I can find al the commands which can be > used for os.system(). I searched with google but I didn't find an > answer. In the official python tutorial it says os.system('command') > executes the command, but it doesn't say which commands exist (or > I'm just blind). > > Does anyone have an answer for this question? > > Thanks, > > Devilly Hey Deville, os.system() executes commands that you usually use in a shell outside python. so in the case of you being a windows user, you replace 'command' with any DOS command. gr Arno From marduk at letterboxes.org Wed Dec 3 09:57:33 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Wed, 03 Dec 2008 09:57:33 -0500 Subject: Obama's Birth Certificate - Demand that US presidential electors investigate Obama's eligibility In-Reply-To: <6cf32afd-f167-4c3e-884a-48452eaa8f82@w34g2000yqm.googlegroups.com> References: <89pZk.9151$be.4743@nlpi061.nbdc.sbc.com> <6cf32afd-f167-4c3e-884a-48452eaa8f82@w34g2000yqm.googlegroups.com> Message-ID: <1228316253.29326.0.camel@brotherus.rdu.redhat.com> This has nothing to do with Python. Please take this thread to cares.who.someone. From philip at semanchuk.com Mon Dec 29 13:19:22 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Mon, 29 Dec 2008 13:19:22 -0500 Subject: SQL, lite lite lite In-Reply-To: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> Message-ID: On Dec 29, 2008, at 1:06 PM, Aaron Brady wrote: > I don't think relational data can be read and written very easily in > Python. There are some options, such as 'sqllite3', but they are not > easy. 'sqllite3' statements are valid SQL expressions, which afford > the entire power of SQL, but contrary to its name, it is not that > 'lite'. To me, 'lite' is something you could learn (even make!) in an > afternoon, not a semester; something the size of an ActiveState > recipe, or a little bigger, maybe a file or two. Hi Aaron, The "lite" part of SQLite refers to its implementation more than its feature set. In other words, SQLite doesn't promise to make SQL easier, it promises many of the features of a big, heavy relational database (e.g. Postgres, MySQL, Oracle, etc.) but in a small, light package. I can see why you'd be disappointed if you were expecting the former. IMHO it does quite well at the latter. After a look at the syntax you're proposing, I wonder how you feel it differs from ORMs like SQLAlchemy (for instance). Cheers Philip From tjreedy at udel.edu Mon Dec 8 19:26:37 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Dec 2008 19:26:37 -0500 Subject: RuntimeError: dictionary changed size during iteration In-Reply-To: <274eb282-1635-40ca-95af-b82271c57802@v4g2000yqa.googlegroups.com> References: <274eb282-1635-40ca-95af-b82271c57802@v4g2000yqa.googlegroups.com> Message-ID: Robert Dailey wrote: > stuff = vars() >>> vars() is globals() True > for key in stuff: You just changed globals, which is aliased as stuff. Stuff changes. > print( key, '--', stuff[key] ) > > > > I get the following error message: > ('CopyEmotionFX', '--', ) > Traceback (most recent call last): > File "C:\IT\work\jewett\depends.py", line 12, in > for key in stuff: > RuntimeError: dictionary changed size during iteration > > Why is this happening? From bockman at virgilio.it Wed Dec 31 04:01:11 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: Wed, 31 Dec 2008 10:01:11 +0100 Subject: select.select and socket.setblocking In-Reply-To: References: <495a661d$0$11384$5fc30a8@news.tiscali.it> Message-ID: <495b34d8$0$11387$5fc30a8@news.tiscali.it> Grant Edwards ha scritto: > On 2008-12-30, Francesco Bochicchio wrote: > >> 3. AFAIK (sorry, I feel acronym-ly today ;), there is no difference in >> select between blocking and non-blocking mode. The difference is in the >> recv (again, assuming that you use TCP as protocol, that is AF_INET, >> SOCK_STREAM), which in the blocking case would wait to receive all the >> bytes that you requested, > > No, in blocking mode it will wait to receive _some_ data (1 or > more bytes). The "requested" amount is strictly an upper > limit: recv won't return more than the requested number of > bytes, but it might return less. > Uhm. In my experience, with TCP protocol recv only returned less than the required bytes if the remote end disconnects. I always check the returned value of recv and signal an error if the read bytes are less than the expected ones, but this error is never occurred (and its about 20 years that I use sockets in various languages and various flavor of unix and occasionally on windows. Maybe have always been lucky ? :-) And, on some unices system call recv also returns when a signal interrupts the syscall, but I half-remember reading that python recv in such a case repeat the system call by itself ... although this might be only my desire ... > In non-blocking mode, it will always return immediately, either > with some data, no data (other end closed), or an EAGAIN or > EWOULDBLOCK error (I forget which). > >> [...] I myself tend to avoid using non-blocking sockets, since >> blocking sockets are much easier to handle... > > That depends on whether you can tolerate blocking or not. In > an event-loop, blocking is generally not allowed. > What I usually do, when I cannot block is: - use socket in blocking mode - do a select with a very small timeout and do a recv only if the select returns with input events - (with TCP) do a recv for the exact amount of bytes that I expect ( this mean having a user protocol that carries the message size in the header, but this is usually the case ). This usually worked for me. If my process (or thread) has only to deal with socket I/O, I make a blocking select, and then make an 'exact' recv on whichever socket the select signals. Ciao ---- FB From jenn.duerr at gmail.com Thu Dec 11 21:15:59 2008 From: jenn.duerr at gmail.com (noydb) Date: Thu, 11 Dec 2008 18:15:59 -0800 (PST) Subject: Rename of .mdb file -- lock Message-ID: <4049f296-2a04-4eee-9f09-aa37a973a8cf@r40g2000yqj.googlegroups.com> All, I have the code below, which unzips a zipfile containing only one file. Once it is unzipped, I want to rename the file based on a user provided name. But I get this (WindowsError: [Error 32] The process cannot access the file because it is being used by another process) error, which does not make sense to me as no other apps are open. Any suggestions? Thanks! ****CODE**** # Declare the zip file directory and name (shouldn't change, in a permanent location) mdb_zip = ("C:\\ProjWork\\mdb_geoDB_91.zip") output_dir = ("C:\\Temp") # ZipFile for read z = zipfile.ZipFile(mdb_zip, 'r') zFile = z.namelist() # Put contents of zipfile into a list zList = z.namelist() # Loop thru list, write zipfile contents to new directory for zItem in zList: print "Unpacking",zItem zRead = z.read(zItem) z1File = open(os.path.join(output_dir, zItem),'wb') z1File.write(zRead) z1File.close print "Finished extracting zip file" uChoice = "test44.mdb" ## to be user chosen someday new91mdb = os.path.join(output_dir, zItem) # C:\TEMP\GDB_9_1.mdb ##os.rename(new91mdb, (os.path.join(output_dir, uChoice))) os.rename(new91mdb, (os.path.join(output_dir, "C:\TEMP\test1.mdb"))) del new91mdb From bearophileHUGS at lycos.com Fri Dec 5 10:09:27 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 5 Dec 2008 07:09:27 -0800 (PST) Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> Message-ID: <5926cb50-e53f-4e9e-8672-b4e29e2280b5@r36g2000prf.googlegroups.com> Andreas Waldenburger: > Whenever has it been a pythonic ideal to "not allow" stuff? You get > warnings. Everything else is up to you. It's a strong source for bugs, especially for newbies, that I have hoped to see removed from Python3 (my first request of this was years ago). I was nearly sure to see this wart removed from Python3, and now I hear it's presents still. I don't understand why they haven't fixed it. Then this is the third thing I don't like of Python3 (the other two being the removal of automatic tuple unpacking in function signature and the wart of literals for empty set/dict). Bye, bearophile From ianare at gmail.com Tue Dec 16 12:09:40 2008 From: ianare at gmail.com (=?ISO-8859-1?B?aWFuYXLp?=) Date: Tue, 16 Dec 2008 09:09:40 -0800 (PST) Subject: Python plugin for Netbeans References: <21z1l.218500$FR.506807@twister1.libero.it> Message-ID: <8d2cc75b-3483-46a0-87f5-92edddf993d4@r10g2000prf.googlegroups.com> On Dec 15, 3:23?pm, a wrote: > Netbeans added a python plugin to its plugin repository. > Do you tried it? What do you think about this plugin? If you like netbeans already it's great to finally have python officially supported. I find netbeans to be easier to use than eclipse. From musiccomposition at gmail.com Sun Dec 7 23:01:31 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sun, 7 Dec 2008 20:01:31 -0800 (PST) Subject: Python for kids? References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> Message-ID: On Dec 7, 2:13?pm, "Russ P." wrote: > I have a 12-year-old son who spends too much time playing Xbox live > and watching silly YouTube videos. I would like to try to get him > interested in programming. Is anyone aware of a good book or website > that addresses this concern, preferably (but not necessarily) using > Python? I could try to teach him Python myself, but I'm afraid I would > just frustrate him and kill his interest in programming. I did a > Google search and found a few things, but not a lot. Thanks. Perhaps what he really needs is some time away from the screen. From nick at craig-wood.com Wed Dec 3 09:30:48 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 03 Dec 2008 08:30:48 -0600 Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> <258cf433-f6c9-43e7-a235-f5f6b2b6433f@j39g2000yqn.googlegroups.com> <33b4cc2f-2311-491c-a2e6-9cc5452b1a6b@g38g2000yqd.googlegroups.com> <2772646a-623f-400b-a606-281a7e3220d4@20g2000yqt.googlegroups.com> Message-ID: Slaunger wrote: > On 3 Dec., 11:30, Nick Craig-Wood wrote: > > > ? ? ? ? ?cls = self.__class__ > > > ? ? ? ? ?if attr_name in cls.data_attr_names: > > > > self.data_attr_names should do instead of cls.data_attr_names unless > > you are overriding it in the instance (which you don't appear to be). > > Yeah, I know. I just like the cls notation for code readability > because it tells you that it is a class attribute, which is not > instance- dependent. > > That may be legacy from my Java past, where I used to do it that > way. I know perfectly well that self. would do it. i just find > that notation a little misleading I quite like it... It looks in the instance, then in the class which I find to be very elegant - you can set a default in the class and override it on a per object or per subclass basis. > > I think you want setattr() here - __dict__ is an implemetation detail > > - classes with __slots__ for instance don't have a __dict__. ?I'd > > probably do this > > Oh my, I did not know that. __slots__?? Something new I got to > understand. But you are right. thanks! > > > > > ? ? ? ? ? ? ? ? ? ?for k, v in zip(("I1", "Q1", "I2", "Q2"), bytes_to_data(buf)): > > ? ? ? ? ? ? ? ? ? ? ? ?setattr(self, k, v) > > ? ? ? ? ? ? ? ? ? ?return object.__getattr__(self, attr_name) > > > And perhaps even more readable (how I do it now, no need to call > __getattr__ for an attribute, whcih is already there): > ... > for attr, value in zip(cls.data_attr_names, > bytes_to_data(buf)): > setattr(self, attr, value) > > return getattr(self, attr_name) I wrote the object.__getattr__ call to stop recursion troubles. If you are sure you've set the attribute then plain getattr() is OK I guess... > In this process I have actaully managed to isolate all the > ...OnDemand stuff in an abstract PayloadOnDemand class > > I can now use this "decorator-like"/helper class to very easily > make an ...OnDemand variant of a class by just doing multiple > inheritance - no implementation: > > class PayloadBaconAndEggsOnDemand(PayloadOnDemand, PayloadBaconAndEggs): pass You've reinvented a Mixin class! http://en.wikipedia.org/wiki/Mixin It is a good technique. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From rt8396 at gmail.com Mon Dec 1 15:29:25 2008 From: rt8396 at gmail.com (r) Date: Mon, 1 Dec 2008 12:29:25 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <3a30f601-7128-4e5f-a97e-9f899404912c@o40g2000prn.googlegroups.com> <4f31c483-8382-480e-8417-b7eef1b1792d@z1g2000yqn.googlegroups.com> <8c856b01-7f0c-4d5b-a1d2-cfe7dc74389f@w3g2000yqc.googlegroups.com> <1680020c-521c-4498-8e74-92e99c03da6b@w35g2000yqm.googlegroups.com> <0d9d2404-cb3f-4390-b97c-79251db8ac95@k8g2000yqn.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> Message-ID: Rome is Burning! Pay particular attention to the second paragraph. Narcissistic culture Main article: The Culture of Narcissism Historian and social critic Christopher Lasch described this topic in his book, "The Culture of Narcissism",[3] published in 1979. He defines a narcissistic culture as one in which every activity and relationship is defined by the hedonistic need to acquire the symbols of spiritual wealth, this becoming the only expression of rigid, yet covert, social hierarchies. It is a culture where liberalism only exists insofar as it serves a consumer society, and even art, sex and religion lose their liberating power. In such a society of constant competition, there can be no allies, and little transparency. The threats to acquisitions of social symbols are so numerous, varied and frequently incomprehensible, that defensiveness, as well as competitiveness, becomes a way of life. Any real sense of community is undermined -- or even destroyed -- to be replaced by virtual equivalents that strive, unsuccessfully, to synthesize a sense of community. It can mean also many other things. Contrary to Lasch, Bernard Stiegler argues in his book, Aimer, s?aimer, nous aimer: Du 11 septembre au 21 avril, that consumer capitalism is in fact destructive of what he calls primordial narcissism, without which it is not possible to extend love to others. -food for thought- From tjreedy at udel.edu Thu Dec 4 20:45:16 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Dec 2008 20:45:16 -0500 Subject: Running Python 2 and Python 3 on the same machine In-Reply-To: <49387f7e$0$27857$9b622d9e@news.freenet.de> References: <1228424486.5873.6.camel@linux-3eb6.site> <49387f7e$0$27857$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: >> Since the source code is incompatible, I was expecting the Python >> executable to have a new name such as 'python3' > > It does: the executable is called python3.0. Why do you say that? As I reported on the py3 list when requesting a new name -- in particular, python3, the new python is installed on WinXP as python.exe and pythonw.exe!!! The includes the new 3.0 release. From jason.scheirer at gmail.com Tue Dec 16 17:56:02 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Tue, 16 Dec 2008 14:56:02 -0800 (PST) Subject: AIM client code for Python? References: Message-ID: On Dec 16, 9:54?am, Joe Strout wrote: > I'd like to write an AIM bot in Python. ?I found and tried > , but it doesn't work for me: > > Connecting... > Traceback (most recent call last): > ? ?File "aimbot-1.py", line 17, in > ? ? ?bot.go() > ? ?File "/Users/jstrout/Documents/Python-Dev/AIMbot/toc.py", line 62, ? > in go > ? ? ?self.process_loop() > ? ?File "/Users/jstrout/Documents/Python-Dev/AIMbot/toc.py", line 156, ? > in process_loop > ? ? ?event = self.recv_event() > ? ?File "/Users/jstrout/Documents/Python-Dev/AIMbot/toc.py", line 230, ? > in recv_event > ? ? ?dtemp = self._socket.recv(buflen - len(data)) > socket.error: (54, 'Connection reset by peer') > > I wrote to the author a week ago, but never got a reply. ?It could be ? > as simple as changing the server addresses in toc.py, currently: > > TOC_SERV_AUTH = ("login.oscar.aol.com", 29999 ) > TOC_SERV = ( "toc.oscar.aol.com", 9898 ) > > ...but I don't understand AIM well enough to know the correct values ? > (and was rather hoping that I wouldn't have to). > > Does anyone know how to get Py-TOC to work, or have another Python TOC ? > implementation to suggest? > > Thanks, > - Joe What I did once to get a bot working was to use Pidgin, and communicate with the instance of Pidgin over D-Bus. This has the happy side effect of making the bot multi-protocol and handling all the connection drop issues and the like, as well as allowing for you to intervene in conversations. class HookForAccount(object): def __init__(self, usernames=None): if usernames is not None: if isinstance(usernames, basestring): usernames = [usernames] usernames = set([x.lower() for x in usernames]) bus = dbus.SessionBus() obj = bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject") self.purple = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface") self.accountids = set() for account in self.purple.PurpleAccountsGetAllActive(): if usernames is None or self.purple.PurpleAccountGetUsername(account).lower() in usernames: print self.purple.PurpleAccountGetUsername(account) self.accountids.add(account) bus.add_signal_receiver(self.got_im, dbus_interface="im.pidgin.purple.PurpleInterface", signal_name="ReceivedImMsg") def got_im(self, code, screenname, message, conversation_id, flags): time.sleep(1.75) self.purple.PurpleConvImSend(self.purple.PurpleConvIm (conversation_id), "HELLO!") if __name__ == "__main__": logging.getLogger().setLevel(0) dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) HookForAccount(sys.argv[1:] or None) loop = gobject.MainLoop() loop.run() From mirandasnailvv at gmail.com Fri Dec 19 19:43:11 2008 From: mirandasnailvv at gmail.com (mirandasnailvv at gmail.com) Date: Fri, 19 Dec 2008 16:43:11 -0800 (PST) Subject: download nero express for free - Free Message-ID: download nero express for free . . . *******CLICK HERE******** http://club247.cn/download-nero-express-for-free ***************************** . . . . . . . . . . . . download nero express for free From joshua at joshuakugler.com Thu Dec 11 21:47:06 2008 From: joshua at joshuakugler.com (Joshua Kugler) Date: Thu, 11 Dec 2008 17:47:06 -0900 Subject: Disputing Cookie.py's definition of valid characters Message-ID: Some investigation today revealed that Cookie.py thinks these are valid characters for names and values of cookies: _LegalCharsPatt = r"[\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\=]" The rest, presumably being encoded via %NN. I notice that (), {}, and others made the list, but not []. Is there a reason for that? I didn't find a list of valid characters anywhere in the cookie RFC (disclaimer: I didn't read the HTTP 1.1 RFC). The reason this got brought up: I'm parsing some cookies that have been set by a PHP app (out of my control, no flames please) and it has cookies of the form name[0], name [1], and so on which get transformed to arrays on the server side such that: $_COOKIES['name'] Will be a list with values from name[0], name[1]. Well, when these are parsed by Cookie.py, they simply vanish because it doesn't like the [ and ] in the cookie names. But these are set successfully and the browser side, and are sent back to the server successfully. Since this is a CherryPy app, it's not as easy as just subclassing the cookie class I want. I suppose I could sub class and then monkey patch CherryPy, but that feels nasty. Hmm...local copy of Cookie.py that comes before /usr/lib/python2.5 in the site path would work too. Thoughts? Is this a bug in Cookie.py, or is PHP out of spec to send cookies with [ and ] in the name? j From clp at rebertia.com Mon Dec 29 07:18:03 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 29 Dec 2008 04:18:03 -0800 Subject: AttributeError: 'module' object has no attribute 'DatagramHandler' (ubuntu-8.10, python 2.5.2) In-Reply-To: <4c6f0831-c05f-401f-b956-376600b38e06@r15g2000prd.googlegroups.com> References: <4c6f0831-c05f-401f-b956-376600b38e06@r15g2000prd.googlegroups.com> Message-ID: <47c890dc0812290418h14b89435nc019d78e46dbec0d@mail.gmail.com> On Mon, Dec 29, 2008 at 4:08 AM, Tzury Bar Yochay wrote: > $ ~/devel/ice/snoip/freespeech$ python > Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) > [GCC 4.3.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import logging >>>> logging.DatagramHandler > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute 'DatagramHandler' >>>> > > > That is odd since the documentation says there is DatagramHandler for > module logging >From http://docs.python.org/library/logging.html#logging.DatagramHandler : "The DatagramHandler class, located in the logging.handlers module [...]" >From http://docs.python.org/library/logging.html#logging-levels : "The StreamHandler and FileHandler classes are defined in the core logging package. The other handlers are defined in a sub- module, logging.handlers." There's your answer. I do agree though that the "class logging.DatagramHandler" line in the docs is misleading to say the least. Perhaps a docs bug should be filed... Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From Slaunger at gmail.com Tue Dec 9 16:27:37 2008 From: Slaunger at gmail.com (Slaunger) Date: Tue, 9 Dec 2008 13:27:37 -0800 (PST) Subject: Best way to report progress at fixed intervals References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> Message-ID: On 9 Dec., 19:35, rdmur... at bitdance.com wrote: > > I felt like a little lunchtime challenge, so I wrote something that > I think matches your spec, based on your sample code. ?This is not > necessarily the best implementation, but I think it is simpler and > clearer than yours. ?The biggest change is that the work is being > done in the subthread, while the main thread does the monitoring. > Well, thank you for spending your lunch time break on my little problem. > It would be fairly simple to enhance this so that you could pass > arbitrary arguments in to the worker function, in addition to > or instead of the loop counter. > Yes, I agree > ----------------------------------------------------------------------- > """ > Test module for testing generic ways of displaying progress > information at regular intervals. > """ > import random > import threading > import time > > def work(i): > ? ? ?""" > ? ? ?Dummy process function, which takes a random time in the interval > ? ? ?0.0-0.5 secs to execute > ? ? ?""" > ? ? ?print "Work step %d" % i > ? ? ?time.sleep(0.5 * random.random()) > > class Monitor(object): > ? ? ?""" > ? ? ?This class creates an object that will execute a worker function > ? ? ?in a loop and at regular intervals emit a progress report on > ? ? ?how many times the function has been called. > ? ? ?""" > > ? ? ?def dowork(self): > ? ? ? ? ?""" > ? ? ? ? ?Call the worker function in a loop, keeping track of how > ? ? ? ? ?many times it was called in self.no > ? ? ? ? ?""" > ? ? ? ? ?for self.no in xrange(self.max_iter): > ? ? ? ? ? ? ?self.func(self.no) > > ? ? ?def __call__(self, func, verbose=True, max_iter=20, progress_interval=1.0): I had to look up the meaning of __call__, to grasp this, but I get your methology > ? ? ? ? ?""" > ? ? ? ? ?Repeatedly call 'func', passing it the loop count, for max_iter > ? ? ? ? ?iterations, and every progress_interval seconds report how > ? ? ? ? ?many times the function has been called. > ? ? ? ? ?""" > ? ? ? ? ?# Not all of these need to be instance variables, but they might > ? ? ? ? ?# as well be in case we want to reference them in an enhanced > ? ? ? ? ?# dowork function. > ? ? ? ? ?self.func = func > ? ? ? ? ?self.verbose = verbose > ? ? ? ? ?self.max_iter=max_iter > ? ? ? ? ?self.progress_interval=progress_interval > > ? ? ? ? ?if self.verbose: > ? ? ? ? ? ? ?print ("Work through all %d steps reporting progress every " > ? ? ? ? ? ? ? ? ?"%3.1f secs...") % (self.max_iter, self.progress_interval) > > ? ? ? ? ?# Create a thread to run the loop, and start it going. > ? ? ? ? ?worker = threading.Thread(target=self.dowork) > ? ? ? ? ?worker.start() > > ? ? ? ? ?# Monitoring loop. > ? ? ? ? ?loops = 0 > ? ? ? ? ?# We're going to loop ten times per second using an integer count, > ? ? ? ? ?# so multiply the seconds parameter by 10 to give it the same > ? ? ? ? ?# magnitude. > ? ? ? ? ?intint = int(self.progress_interval*10) Is this not an unnecessary complication? > ? ? ? ? ?# isAlive will be false after dowork returns > ? ? ? ? ?while worker.isAlive(): > ? ? ? ? ? ? ?loops += 1 > ? ? ? ? ? ? ?# Wait 0.1 seconds between checks so that we aren't chewing > ? ? ? ? ? ? ?# CPU in a spin loop. > ? ? ? ? ? ? ?time.sleep(0.1) Why not just call this with progress_interval directly? > ? ? ? ? ? ? ?# when the modulus (second element of divmod tuple) is zero, > ? ? ? ? ? ? ?# then we have hit a new progress_interval, so emit the report. And then avoid this if expression? > ? ? ? ? ? ? ?if not divmod(loops, intint)[1]: > ? ? ? ? ? ? ? ? ?print "Processed %d of %d" % (self.no, self.max_iter) > > ? ? ? ? ?if verbose: > ? ? ? ? ? ? ?print "Finished working through %d steps" % max_iter > > if __name__ == "__main__": > ? ? ?#Create the monitor. > ? ? ?monitor = Monitor() > ? ? ?#Run the work function under monitoring. > ? ? ?monitor(work) I was unfamiliar with this notation, but now I understand it simply invokes __call__. Thank you for showing me that! OK. I agree this is a more elegant implementation, although I my mind, I find it more natural if the reporting goes on in a subthread, but that is a matter of taste, I guess. Anyway: Thank you again for spending your lunch break on this! -- Slaunger From fetchinson at googlemail.com Wed Dec 31 15:30:18 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 31 Dec 2008 12:30:18 -0800 Subject: PIL on 3.x? In-Reply-To: References: Message-ID: > Does anyone know if PIL will be ported to the 3.x branch? Actually, Guilherme Polo has ported PIL 1.1.6 to python 3.0: http://mail.python.org/pipermail/image-sig/2008-December/005338.html Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From eric at ericaro.net Tue Dec 9 10:44:03 2008 From: eric at ericaro.net (eric) Date: Tue, 9 Dec 2008 07:44:03 -0800 (PST) Subject: 'pretty print' for built in types References: <051e3a97-b9bc-4a67-8896-93628ca19f59@r15g2000prd.googlegroups.com> Message-ID: On Dec 9, 4:31?pm, Robert Dailey wrote: > Hi, > > Is there a built in way to 'pretty print' a dict, list, and tuple > (Amongst other types)? Dicts probably print the ugliest of them all, > and it would be nice to see a way to print them in a readable way. I > can come up with my own function to do this, but I don't want to do > this if I don't have to. you can have a look at [http://code.google.com/p/prynt/ prynt], it provides some simple functions, to pretty print into RestructuredText, and then, when the process is finished (it's an option) show the 'console' converted into html. dict are transformed into definition: key: value key: value it helps ? From jstroud at mbi.ucla.edu Mon Dec 15 00:08:33 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 14 Dec 2008 21:08:33 -0800 Subject: Looking for the best way to translate an idiom In-Reply-To: References: Message-ID: Aahz wrote: > In article , > James Stroud wrote: >> In case its not obvious: > > Ah, so that's where Bruno's extra apostrophe came from! ;-) > > > (Sorry about the spelling flame, but seeing three posts in quick > succession with incorrect spelling of its/it's pushed me into making a > public comment.) Yes. I think it was the British who decided that the apostrophe rule for "it" would be reversed from normal usage relative to just about every other noun. I'm not sure the purpose--maybe it was to give compulsive proofreaders a raison d'etre. From hjtoi-better-remove-when_replying at comcast.net Mon Dec 15 13:01:46 2008 From: hjtoi-better-remove-when_replying at comcast.net (Heikki Toivonen) Date: Mon, 15 Dec 2008 10:01:46 -0800 Subject: pexpect and inconsistent exit values Message-ID: I don't seem to be able to figure out how to get the exit values of commands executed with pexpect reliably. Here's first with regular shell: heikki at ubuntu:~$ true; echo $? 0 Let's try with pexpect. Below is the program: ---CLIP--- import sys, pexpect cmd = "true" print 'cmd=', cmd child = pexpect.spawn(cmd, logfile=sys.stdout) child.close() print 'child exitstatus=', child.exitstatus print 'child signalstatus=', child.signalstatus print 'child status=', child.status ---CLIP--- The output: (fabexp)heikki at ubuntu:~/python_virtualenvs/fabexp$ python dep.py cmd= true child exitstatus= 1 child signalstatus= None child status= 256 (fabexp)heikki at ubuntu:~/python_virtualenvs/fabexp$ python dep.py cmd= true child exitstatus= 0 child signalstatus= None child status= 0 (fabexp)heikki at ubuntu:~/python_virtualenvs/fabexp$ python dep.py cmd= true child exitstatus= None child signalstatus= 1 child status= 1 I have tried various other commands, and I just can't seem to be able to get reliable exit codes from commands I execute. Any ideas what is going on? -- Heikki Toivonen - http://heikkitoivonen.net From jonas.esp at googlemail.com Mon Dec 22 03:58:35 2008 From: jonas.esp at googlemail.com (Kless) Date: Mon, 22 Dec 2008 00:58:35 -0800 (PST) Subject: HMAC with RIPEMD-160 References: Message-ID: <0152ffa0-7f06-4e94-8a6c-743199e5010c@f3g2000yqf.googlegroups.com> On 21 dic, 23:53, "Chris Rebert" wrote: > On Sun, Dec 21, 2008 at 4:21 AM, Kless wrote: > > Is there any way of use HMAC with RIPEMD-160? > > > Since that to create a ripemd-160 hash there is to use: > > ? ?h = hashlib.new('ripemd160') > > it looks that isn't possible > > > For HMAC-SHA256 would be: > > --------- > > import hashlib > > import hmac > > > hm = hmac.new('key', msg='message', digestmod=hashlib.sha256) > > Untested, but should work according to the docs: > hm = hmac.new('key', msg='message', digestmod=lambda: hashlib.new('ripemd160')) > It works, thank you From tjreedy at udel.edu Sat Dec 6 16:13:37 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 06 Dec 2008 16:13:37 -0500 Subject: slow Python 3.0 write performance? In-Reply-To: <493A698D.5080807@cheimes.de> References: <493A698D.5080807@cheimes.de> Message-ID: Christian Heimes wrote: > Istvan Albert wrote: >> A previous poster suggested that in this case the slowdown is caused >> by the new io code being written in python rather than C. > > For text mode Python 3's write() method is slower than Python 2.x's > method because all text is encoded. The slowdown is mostly caused by > additional code for line ending detection and decoding/encoding. The new > io library does more than the old file object > > So far the new io library hasn't been optimized yet, too. Please give it > some time and report speed issues at http://bugs.python.org/. On WinXP, tests 3 times each ------------------------------------------- 3.0 --- import time line = 'a'*99 + '\n' text = line*500000 start=time.time() open('wtest', 'w').write(text) print(time.time()-start) # 3.4 to 4.0 import time line = 'a'*99 + '\n' text = line*500000 start=time.time() text = bytes(line,'ascii')*500000 print(time.time()-start) # 1.1 to 1.25 start=time.time() open('wtest', 'wb').write(text) # note wb print(time.time()-start) # 1.5 to 1.8 ---------------------------------------------- 2.5 --- import time line = 'a'*99 + '\n' text = line*500000 start=time.time() open('wtest', 'w').write(text) print(time.time()-start) # 3.3 to 4.1 import time line = 'a'*99 + '\n' text = line*500000 start=time.time() open('wtest', 'wb').write(text) # note wb print(time.time()-start) # 1.0 to 1.6 ------------------------------------------------- Conclusion: 1. on WinXP, writing with 3.0 has no slowdown versus 2.5 2. on WinXP, binary mode writing is about 3 times faster that text mode writing with its line-ending expansion. If that is not needed, binary mode and explicit bytes-text conversion is about twice as fast. Terry Jan Reedy From sopherfish at gmail.com Sun Dec 28 12:06:05 2008 From: sopherfish at gmail.com (sopherfish at gmail.com) Date: Sun, 28 Dec 2008 09:06:05 -0800 (PST) Subject: reportlab Message-ID: <77de75c7-2a2e-4621-a369-26680f3ad3a9@l38g2000vba.googlegroups.com> In reportlab 2.2, when I generate a PDF, no matter how many  s I put it, I only get one space. I am using it with python 2.6. The PDF generates fine and one $nbsp works, but for some reason, when I put it in multiple times, I still only get one space. From fakeaddress at nowhere.org Thu Dec 4 14:07:37 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 04 Dec 2008 11:07:37 -0800 Subject: Off Topic: Re: Obama's Birth Certificate - Demand that US presidential electors investigate Obama's eligibility In-Reply-To: References: <89pZk.9151$be.4743@nlpi061.nbdc.sbc.com> Message-ID: MM456Z at yahoo.com wrote: > Bryan Olson wrote: >> girbarob... at yahoo.com wrote: >>> This message is not about the meaningless computer printout called >> More importantly, it's not about Python. I'm setting follow-ups to >> talk.politics. I set the follow-ups header appropriately, as per established newsgroup etiquette. The deceitful not-abuser set the newsgroups back, inappropriately. Sorry if my reply annoys anyone, but I'm sticking to proper usage. >>> "Certification of Live Birth" that Obama propaganda machine calls his >>> "Birth Certificate". The American people are still waiting for a copy >>> of Obama's original birth certificate that includes all his birth >>> information. >> The document is what Hawaii provides as certified copy of birth record. >> It contains all the information the federal government requires to prove >> citizenship by birth, and it shows that Barack Hussein Obama was born 04 >> August 1961 in Honolulu. See: >> >> http://www.factcheck.org/elections-2008/born_in_the_usa.html >> > > This garbage on factcheck.org is a worthless piece of paper > insufficient to prove a US citizenship much less a natural born one. That's not true within the law as established under the U.S. Constitution. Barack Obama's site showed the document he got from Hawaii -- which form that the U.S. Department of State accepts. factcheck.org went it and and examined the record: http://www.factcheck.org/elections-2008/born_in_the_usa.html > You need to have a long version of legitimate birth certificate that > includes all birth information. You tell not the truth. The link shows a record from Hawaii. Hawaii became a U.S. state on 21 August 1959, and thus the record is entitled to the "full faith and credit" granted to state records under the U.S. Constitution Article IV Section 1. Does the record establish that he is a "natural born" citizen? The given record shows that BARACK HUSSEIN OBAMA was born on "August 4, 1961" in the city of HONOLULU on the island of OAHU (capitalization in original). The U.S. Constitution, Amendment 14 section 1, states that all persons born in the United States are citizens. B. H. Obama is a citizen of the USA by birth. >> Remind your US presidential electors of their constitutional duty to >>> investigate Obama's natural-born citizen status. >>> No federal agency like FBI or Secret Service, no Hawaii bureaucrats >>> have ever investigated Obama's birth in Hawaii. Many illegal aliens in >>> USA have official "birth certificates" issued by state bureaucrats on >>> the basis of falsified birth records. >> Janice Okubo of Hawaii's Department of Health confirmed that the state >> has Obama?s original birth certificate on record: >> >> http://hawaii.gov/health/about/pr/2008/08-93.pdf >> >> [...] > Do you have a sufficient IQ to actually grasp what this news release > says? Questioning the other guy's IQ? You must be new to Usenet. [...] > Get one thing straight for your own self interest! THERE ARE TENS OF > MILLIONS OF GUN OWNERS IN USA ONLY WAITING TO USE THEM ON ANYBODY WHO > THREATENS THE US CONSTITUTION - so better use all your brain cells in > your own self interest to resolve this matter now and not later. Run > to Obama and beg him to release all birth records or things will not > get any better. You are playing with fire. Now we see your true stripes. You pretend to be a loyal American, but really you are a hater and a traitor, using guns to threaten anyone who dares to actually stand up for the U.S. Constitution. Follow-ups again set to talk.politics. Of course that may be futile in dealing with this kind of scumbag. -- --Bryan From arnodel at googlemail.com Sun Dec 14 05:24:08 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 14 Dec 2008 10:24:08 +0000 Subject: [OT] stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <01547201$0$6988$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano writes: > On Sat, 13 Dec 2008 19:17:41 +0000, Duncan Booth wrote: > >> I think you must have fallen asleep during CS101. The lower bound for >> sorting where you make a two way branch at each step is O(n * log_2 n), >> but if you can choose between k possible orderings in a single >> comparison you can get O(n * log_k n). > > I think you might have been sleeping through Maths 101 :-) > > The difference between log_2 N and log_k N is a constant factor (log_2 k) > and so doesn't effect the big-oh complexity. It affects it if k is a function of n. In this particular example, we can set k=n so we get O(n). -- Arnaud From lists at cheimes.de Fri Dec 19 13:10:59 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 19 Dec 2008 19:10:59 +0100 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: walterbyrd schrieb: > On Dec 19, 9:13 am, "Giampaolo Rodola'" wrote: >> You can use the old 2.x syntax also in Python 3.x: > > Yeah, but it's deprecated, and - as I understand it - may be removed > completely in future versions. Also, in the future, if you are working > with code from another developer, it's likely that developer will use > the new format. I suppose you can use both - but what an awful mess > that would be. It's not going to be removed for many years - if ever. The % string formatting system is not deprecated in 3.0. For that very reason it must stay until 3.2. We don't have plans to deprecate it in 3.1 so it will stay at least until Python 3.3 which is to be released about 2014. Christian From pavlovevidence at gmail.com Wed Dec 10 22:25:41 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 10 Dec 2008 19:25:41 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> On Dec 10, 12:42?pm, cm_gui wrote: > Python is SLOW. ? ?And I am not comparing it with compiled languages > like C. > Python is even slower than PHP! cm_gui is TROLL. And I am not compring it with bots like Aaron Castironpi Brody. cm_gui is even troller than Xah Lee! Carl Banks From geekmail at usenot.de Sat Dec 6 07:32:58 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sat, 6 Dec 2008 13:32:58 +0100 Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> Message-ID: <20081206133258.693cf59e@usenot.de> On Sat, 6 Dec 2008 04:02:54 -0800 (PST) bearophileHUGS at lycos.com wrote: > class C: > def $method(arg): > $value = arg > > (Note there's no point after $, it's not currently possible). > Ruby uses @ and @@ for similar purposes. > I agree that the code looks worse, but also shorter to read and write, > so in lines of code that use many instance attributes, that short $ > syntax helps keep the line shorter. So I may grow to accept this > sugar... > But that is not the way Python is meant to work. There are several tennets in the Zen of Python that don't chime well with this approach. "self" is a speaking identifier, "$" isn't. we've-been-through-this-ingly yours /W -- My real email address is constructed by swapping the domain with the recipient (local part). From python at bdurham.com Wed Dec 24 02:43:35 2008 From: python at bdurham.com (python at bdurham.com) Date: Wed, 24 Dec 2008 02:43:35 -0500 Subject: Most efficient way to build very large dictionaries Message-ID: <1230104615.5867.1291617213@webmail.messagingengine.com> I'm working with some very large dictionaries (about 25M items per dictionary) that get filled based on data parsed from text based log files. I'm using Python dictionaries to track the frequency of specific combinations of events, eg, I build a key and then add various timing info from the current record to that's key's current value. If the key doesn't exist, I create it and initalize it to its first value. Most keys will have anywhere from 2 to 10,000 value increments. Over time, I've noticed that 90%+ of the keys in my dictionaries stay constant across daily runs of my program. Can I take advantage of this knowledge to optimize my dictionary performance by pre-building my dictionary based on a given list of keys whose values are all set to 0? Specifically, is there a way to bulk load a dictionary with keys/initial values that is faster than individually adding most dictionary entries one at a time? Here are 2 high level strategies I've been thinking about for improving the performance of my dictionaries. 1. Create a list of keys from a current dictionary, pickle this list of keys and then on my next program run, load the pickled list of keys and somehow convert this list to a dictionary with all key values set to 0. 2. After I've performed my analysis on a current dictionary, iterate through this dictionary, setting all values to 0 (is there a fast way to do this?), and then on my next program run, load this pickled dictionary of keys and zero values. I would appreciate your thoughts on whether there are advantages to working with a pre-built dictionary and if so, what are the best ways to create a pre-loaded dictionary. Thank you, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From prologic at shortcircuit.net.au Mon Dec 22 03:35:30 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Dec 2008 18:35:30 +1000 Subject: How to represent a sequence of raw bytes In-Reply-To: References: <200812220327.36180.motoom@xs4all.nl> Message-ID: On Mon, Dec 22, 2008 at 4:56 PM, Steven Woody wrote: > I thing "\x11\x22\x33" in python is not the {0x11, 0x22, 0x33} in C. > Since, a string in python is immutable, I can _not_ do something like: > b[1] = "\x55". > > And, how about char buf[200] in my original question? The intension > is to allocate 200 undefined bytes in memory. Thanks. Steven, one piece of advice. Python is not C. Thank. cheers James From tam at milkyway.gsfc.nasa.gov Fri Dec 12 10:39:44 2008 From: tam at milkyway.gsfc.nasa.gov (Tom McGlynn) Date: Fri, 12 Dec 2008 07:39:44 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> Message-ID: <3a72f628-0a57-46df-ac2f-d101e170e9db@w1g2000prm.googlegroups.com> On Dec 11, 6:46 am, "William James" wrote: > John W Kennedy wrote: > > Xah Lee wrote: > > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or > > > Java, you'll have 50 or hundreds lines. > > > Java: > > > static float[] normal(final float[] x) { > > float sum = 0.0f; > > for (int i = 0; i < x.length; ++i) sum += x[i] * x[i]; > > final float divisor = (float) Math.sqrt(sum); > > float[] a = new float[x.length]; > > for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor; > > return a; > > } Calculating the norm of a vector is a numeric operation, so not surprising it's pretty easy to do in Fortran. While pre Fortran 90 would using something similar to the above, today you can do it as norm = x/sqrt(sum(x*x)) for an arbitratry vector (or tensor for that matter). It would take a couple more lines to wrap it up in a function real function norm(x) real x(*) norm = x/sqrt(sum(x*x)) end [Caveat: my Fortran is more than rusty ....] So even Fortran can do this in only 1 line or 4 as a function. Judging by the LOC and, at least to my eye, the clarity of the method, Fortran is a real winner! Just to give a tiny bit of Java relevance to the discussion: It's the ability to write functions that straightforwardly express the mathematical intent of the user that makes operator overloading (in this case over arrays) so useful in many numerical contexts. This is cross-posted to Python as well. I understand it has similar array arithmetic capabilities to Fortran. I believe this may be one reason for Python's burgeoning popularity Tom McGlynn From rt8396 at gmail.com Thu Dec 18 11:40:11 2008 From: rt8396 at gmail.com (r) Date: Thu, 18 Dec 2008 08:40:11 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <71ede5f0-fd88-4155-9f0d-42d0ad5f57dc@v42g2000yqj.googlegroups.com> Message-ID: Yea, my answer was really not a helping answer(sorry) just showing exactly why this will not work with w.unbind(). Why do you need two separate functions to bind the same event?? You cannot combine the two?? From rt8396 at gmail.com Mon Dec 22 16:50:10 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 13:50:10 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <6ra8t0F925rU1@mid.individual.net> <29feda0d-6432-4cb9-8809-e4d4a7798601@e1g2000pra.googlegroups.com> <6rae73F9s47U1@mid.individual.net> Message-ID: On Dec 22, 3:13?pm, je.s.t... at hehxduhmp.org wrote: > r wrote: > > We see where you stand. And also see that by removing your comments > > from the archive in 5 days, how small your acorns really are. > > What is "the archive", Google Groups? ?You do realize that's not the > entirety of Usenet, correct? Absolutely, but why do you wish to remove your post. Do you not stand behind everything you say? I do, and if a make a mistake i will apologize for it. I have no reason to hide my words from anybody. They will be here from now to eternity. This just makes your thoughts look more "drive-by-ish" to me. Thats all. From nils.krahnstoever at gmail.com Thu Dec 11 00:19:51 2008 From: nils.krahnstoever at gmail.com (Nok) Date: Wed, 10 Dec 2008 21:19:51 -0800 (PST) Subject: Call by reference in SWIG? Message-ID: <298d9cd2-d982-4238-9bd8-bd8a96bb5f50@m15g2000vbl.googlegroups.com> I can't get call-by-reference functions to work in SWIG... Even when wrapping a trivial example like this: /* File : trivial.i */ %module trivial %inline %{ class test { public: void foo(int *t) { *t=42; } }; %} I get a TypeError when trying to use it: import trivial x=10 c=trivial.test() c.foo(x) The error is: def foo(*args): return _trivial.test_foo(*args) TypeError: in method 'test_foo', argument 2 of type 'int &' From duncan.booth at invalid.invalid Thu Dec 4 03:50:21 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 4 Dec 2008 08:50:21 GMT Subject: How can I do this (from Perl) in Python? (closures) References: <68b8294c-8771-4b02-bd46-2f25f5e01602@j35g2000yqh.googlegroups.com> Message-ID: excord80 at gmail.com wrote: > I just came across http://www.perl.com/pub/a/2002/05/29/closure.html > and wanted to try the "canonical example of closures" in Python. I > came up with the following, but it fails: > > ####################### > #!/usr/bin/env python > > def make_counter(start_num): > start = start_num > def counter(): > start += 1 > return counter The other answers you got will work, but here's an alternative to consider: you can convert the function into a generator and then just move the variable inside. >>> def make_counter(start_num): def counter(): start = start_num while 1: yield start start += 1 return counter().next >>> from_ten = make_counter(10) >>> from_three = make_counter(3) >>> print from_ten() 10 >>> print from_ten() 11 >>> print from_three() 3 >>> print from_ten() 12 >>> print from_three() 4 >>> While I realise you are just trying a simple example, if you actually wanted the code the truly Pythonic way would be to use the existing libraries: >>> import itertools >>> def make_counter(start_num): return itertools.count(start_num).next >>> from_ten = make_counter(10) >>> from_three = make_counter(3) >>> print from_ten() 10 >>> print from_ten() 11 >>> print from_three() 3 >>> print from_ten() 12 >>> print from_three() 4 >>> Never reinvent the wheel unless you really need a square one. :^) -- Duncan Booth http://kupuguy.blogspot.com From thorsten at thorstenkampe.de Wed Dec 10 14:30:32 2008 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Wed, 10 Dec 2008 20:30:32 +0100 Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: * cm_gui (Wed, 10 Dec 2008 10:42:40 -0800 (PST))> > Python is SLOW. And I am not comparing it with compiled languages > like C. > Python is even slower than PHP! Sure. But Perl is faster than Ruby (exactly 2.53 times as fast). And Python is 1.525 times faster than VisualBasic (or was it the other way round?). > Just go to any Python website and you will know. > An example is: > http://www2.ljworld.com/ > And this site is created by the creators of Django! Quite slow, indeed! Django is even slower than Python itself... > And it is not just this Python site that is slow. There are many many > Python sites which are very slow. And please don?t say that it could > be the web hosting or the server which is slow ? because when so many > Python sites are slower than PHP sites, it couldn?t be the web > hosting. Also, Zope/Plone is even slower. I hope this will awaken the community. I did a quick test and it seems that Zope is slower than Python but Python is faster than Plone and PHP is faster than even Perl and Python _together_...! Thanks for the heads-up, cm_gui! Thorsten From tn.pablo at gmail.com Wed Dec 17 17:52:42 2008 From: tn.pablo at gmail.com (ptn) Date: Wed, 17 Dec 2008 14:52:42 -0800 (PST) Subject: Location HTTP Header Message-ID: <68fa1e9b-6652-4d34-a7fe-fc98db8bf6d4@m16g2000vbp.googlegroups.com> Hi all. I tried this stupid script on my server: #! /usr/bin/env python print 'Location: http://www.google.com\n' and it didn't work, I get a blank page. I first tried the Location header in another script, and when execution got to that point, it would just sort of ignore it, because the script would keep running to the end of the code (or stop at some unhandled exception). I ran chmod 755 script.cgi and the cgi script is at the correct directory, but still nothing. I think it might be an error from the server (the old PythonWeb.org webserver), maybe it doesn't support Location? Is that even possible? Or maybe there's some setup I forgot to do? Any ideas? Thanks a lot. From python.list at tim.thechases.com Wed Dec 10 13:55:51 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 10 Dec 2008 12:55:51 -0600 Subject: get todays files In-Reply-To: References: Message-ID: <494010B7.4000105@tim.thechases.com> > I have a script that will login to my ftp server and download > all the backup files, but I want it to only download the files > that were created today, e.g. if I ran the script today I want > it to only fetch files created today. Use Python's ftp module and send the MDTM command to get back the timestamp of the filename. Insecurely, this would look something like from ftplib import FTP hostname = "ftp.mozilla.org" conn = FTP(hostname) user = "anonymous" password = "user at example.com" conn.login(user, password) filename = "pub/README" results = conn.sendcmd("MDTM %s" % filename) code, stamp = results.split(None, 1) assert code == "213", "Unexpected result" print "%s was modified on %s" % (filename, stamp) today = '20081210' if stamp[:8] == today: process(filename) else: print "ignoring", filename The MDTM command is not part of the core RFC-959, but rather the RFC-3659[1] so you might run across some servers that don't support it. You can read more about the Python ftplib module at [2] which would be where you want to read up on pulling back a listing of the directory of file-names to check. There is a NLST command (I don't have a server handy that supports this command). The LIST command returns pretty/readable information that's not quite so machine-parsing friendly (at least in a cross-FTP-server sort of way). However, that part, I leave as an exercise for the reader along with the complications of the "today" bit. Oh, SteveH, I checked your FTP-cloning source in my Python dir, and it doesn't look like it does anything regarding file-times in it, so that may have been a red-herring. Unless you've added something since the ver. I've got here. -tkc [1] http://en.wikipedia.org/wiki/List_of_FTP_commands [2] http://www.python.org/doc/2.5.2/lib/ftp-objects.html From joe at strout.net Fri Dec 19 10:23:10 2008 From: joe at strout.net (Joe Strout) Date: Fri, 19 Dec 2008 08:23:10 -0700 Subject: How to parsing a sequence of integers In-Reply-To: References: <494ba258$0$18998$426a74cc@news.free.fr> Message-ID: <494BBC5E.7070909@strout.net> Peter Otten wrote: > If you are using Python 2.x: > ... > So you better throw in a float(...): Or, add from __future__ import division at the top of the file. I put this at the top of all my Python files, whether I expect to be dividing or not. It just saves grief. Cheers, - Joe From hotkatrina4u at gmail.com Fri Dec 19 04:51:25 2008 From: hotkatrina4u at gmail.com (hotkatrina4u) Date: Fri, 19 Dec 2008 01:51:25 -0800 (PST) Subject: Online INTERNET JOBS Message-ID: <9900f9bb-1faf-44db-a1cb-c15debab8895@b41g2000pra.googlegroups.com> Start Your Own INTERNET JOBS AT http://megalinesolutions.googlepages.com/ No Fee Required From gagsl-py2 at yahoo.com.ar Mon Dec 8 02:48:19 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Dec 2008 05:48:19 -0200 Subject: Best way to run multiple Python processes without overloading CPU or disk i/o In-Reply-To: References: <1228278090.29785.1287948757@webmail.messagingengine.com> Message-ID: En Wed, 03 Dec 2008 02:29:32 -0200, Philip Semanchuk escribi?: > > On Dec 2, 2008, at 11:21 PM, python at bdurham.com wrote: > >> Is there a cross-platform way to launch multiple Python processes >> and monitor CPU usage > > os.getloadavg() might be useful. It certainly works on *nix, don't know > about Windows. The documentation doesn't mention any platform > limitations. ....apart from saying "Availability: Unix."? :) To the OP: You may monitor CPU usage using the Tim Golden's wmi module [1] py> import wmi py> c = wmi.WMI() py> for p in c.Win32_Processor(): .... print float(p.LoadPercentage) .... 9.0 [1] http://timgolden.me.uk/python/ -- Gabriel Genellina From bearophileHUGS at lycos.com Mon Dec 8 09:29:54 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 8 Dec 2008 06:29:54 -0800 (PST) Subject: Public imports References: <9623b0a3-7053-41f1-b116-0cd5e54f39e9@v13g2000vbb.googlegroups.com> Message-ID: <8e382f56-3048-4fdc-881a-700416d29156@n41g2000yqh.googlegroups.com> M?rcio Faustino: > Does Python support public imports instead of the default private? > Something like D's "public import" (see 2.0/module.html>) or even Perl's "export_to_level". D type system has several big holes, and I am trying to push Walter to fix some of those, to make it look a little more sane, like for example the Python module system. Public imports are often bad. Bye, bearophile From darcy at druid.net Tue Dec 23 10:59:11 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 23 Dec 2008 10:59:11 -0500 Subject: iterating initalizations In-Reply-To: References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> <20081223092504.aaf25192.darcy@druid.net> Message-ID: <20081223105911.9b265bf2.darcy@druid.net> On Tue, 23 Dec 2008 10:20:59 -0500 Steve Holden wrote: > D'Arcy J.M. Cain wrote: > > Well, if all you want is a loop: > > > > for v in vars: > > locals()[v] = [] > > > Note that this isn't guaranteed to work. While locals() will return a > dict containing the names and values from the local namespace, you won't > affect the local namespace by assigning values to the appropriate keys: > > >>> def f(): > ... a = "hello" > ... locals()["a"] = "goodbye" > ... print a This was my test: >>> locals()['x'] = "hello" >>> x 'hello' >>> locals()['x'] = "goodbye" >>> x 'goodbye' Just didn't want people to think that I post without testing. In any case, even if that worked as expected I am pretty sure that it is the wrong solution but without knowing more about what the OP is doing it is impossible to know what the right answer is. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From invalid at invalid Tue Dec 23 11:03:49 2008 From: invalid at invalid (Grant Edwards) Date: Tue, 23 Dec 2008 10:03:49 -0600 Subject: pseudo terminal usage from Python? References: Message-ID: <5t-dnRgMi9Z4lszUnZ2dnUVZ_vOdnZ2d@posted.visi> On 2008-12-23, skip at pobox.com wrote: > > I ran into an interesting problem yesterday. The mpstat(1) command on > Solaris formats its output like so: > > CPU minf mjf xcal intr ithr csw icsw migr smtx srw syscl usr sys wt idl > 0 42 1 1184 812 265 227 12 44 37 0 1131 6 2 0 93 > 1 25 1 933 447 2 203 37 75 12 0 902 5 4 0 91 > 2 17 0 195 495 1 201 41 77 13 0 514 5 1 0 94 > 3 4 0 117 882 405 171 34 65 21 0 449 5 2 0 93 > > I'm only interested in presenting the CPU numbers and user+sys values > prefixed by a timestamp. For example, the above might be formatted like so: > > 07:28:46.373328 0 8 1 9 2 6 3 7 > > The obvious solution might be something simple like this: > > mpstat 1 | python mympstat.py > > where mympstat.py does a trival amount of reformatting. > > The problem is that mpstat recognizes when its output is a pipe and block > buffers it so the Python script sees input in massive blobs, not the > second-by-second output you'd see running "mpstat 1" by itself. Are you sure it's not Python buffering its input? Have you tried "python -u mympstat.py"? > I suspect there is some magic I can perform with pseudo terminals (this is > on Solaris 10.) The documentation for the pty module contains no examples > and I've been so far unable to find any using Google. I had a Linux pty example running once upon a time. If "python -u" doesn't work post again, and I'll try to find it. -- Grant Edwards grante Yow! Please come home with at me ... I have Tylenol!! visi.com From deets at nospam.web.de Wed Dec 24 08:37:33 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 24 Dec 2008 14:37:33 +0100 Subject: SyntaxError: encoding problem: with BOM In-Reply-To: References: Message-ID: <6res8tF1do1sU1@mid.uni-berlin.de> NoName schrieb: > i have 1.py in cp866 encoding: > > # -*- coding: cp866 -*- > print ("ff") > > > > It's not work in Python 3.0 > Error: > > File "", line 1 > SyntaxError: encoding problem: with BOM > > what's wrong? I can only guess, but just because you write the coding-header that doesn't mean that the editor you use does actually *use* that encoding. What I presume it does is to use utf-8, and write that stupid BOM microsoft uses for denoting utf-8-content as first byte. Try using a different editor, or alter it's settings to really use your desired encoding. Diez From skip.montanaro at gmail.com Sat Dec 27 13:54:32 2008 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Sat, 27 Dec 2008 10:54:32 -0800 (PST) Subject: Test message via Google Groups Message-ID: <0172c8ed-13ca-49e7-a7bb-2f9bef475f65@t39g2000prh.googlegroups.com> Test message - please ignore. Skip From aleksandr.goretoy at gmail.com Sat Dec 27 18:54:02 2008 From: aleksandr.goretoy at gmail.com (alex goretoy) Date: Sat, 27 Dec 2008 17:54:02 -0600 Subject: how to make a class to get all forms and input fields from webpage Message-ID: Hello All, How do I make a class for retrieving all forms and input fields on a web page. Meaning, form name, form url,all input fields, text,textarea,select,etc...I have something currently and it kinda works. It also kinda works for retrieving all images on webpages. My main concer here is to make is retrive forms and input fields into a dict that has this kinda of outline: Maybe not exactly like this, but something to this nature. So I can use it in other classes. forms= {"name":{"url":{"""input_name1":"","input_name_2","select_input":{"value1":"","value2":"selected","value3":""}}}} This is what I have made a long time ago, I haven't touched it in a while, but I need to make it work with some other classes. I need tit to receive all forms and inputs for me. What is a more efficient way to do this? My background is in PHP and I want to extend my python knowledge. I came up with this script by Googling something a long time ago and making modifications and additions to it. You can find the stdout_colours class on line, JFGI. It's allows for display of caller and called function and colors output to terminal. Thanks for your help my friends. #!/usr/bin/python import urllib, urllib2 import re, sys,string import os, sys, Image from sgmllib import SGMLParser from urlparse import urlparse import stdout_colours class URLPacker(SGMLParser): def __init__(self,colorize,caller): self.colorize=colorize self.caller=caller self.reset() def reset(self): SGMLParser.reset(self) self.func_me_color="white_on_black" self.soc=stdout_colours.stdout_colors(self.colorize,self.caller) self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.urls = {} self.imgs = {} self.forms = {} self.inputs = {} self.action = "" self.method = "" self.url="" self.path="" self.source="" self.dirname="" self.level=0 self.max_depth=4 self.urlRExp = re.compile('[.]htm$|[.]html$|[.]shtml$|[/]$|[.]php$', re.IGNORECASE) self.fileRExp = re.compile('[\/:*?"<>|]') self.formats=[] self.soc.me_him(['EXIT:',__name__],self.func_me_color) def start_a(self,attrs): self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.soc.w(attrs,"red") href = [v for k,v in attrs if k=='href'] for value in href: if self.urls.has_key(value): pass else: self.urls[value]=0 self.soc.me_him(['EXIT:',__name__],self.func_me_color) def start_img(self,attrs): self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.soc.w(attrs,"blue") src = [v for k,v in attrs if k=="src"] for value in src: if self.imgs.has_key(value): pass else: self.imgs[value]=0 self.soc.me_him(['EXIT:',__name__],self.func_me_color) def start_form(self,attrs): self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.soc.w(attrs,"green") method = [v for k, v in attrs if k=='method'] action = [v for k,v in attrs if k=="action"] if string.join(method,"") != "": self.method=method[0] else: self.method="post" self.action=action[0] self.soc.w(action,"white_on_green") self.soc.w(method,"white_on_blue") self.forms[self.action]={} self.forms[self.action][self.method]={} self.soc.me_him(['EXIT:',__name__],self.func_me_color) def start_input(self,attrs): self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.soc.w(attrs,"yellow") name = [v for k, v in attrs if k=='name'] value = [v for k,v in attrs if k=="value"] if string.join(name,"") !="": if string.join(value,"")!="": self.forms[self.action][self.method][name[0]]=value[0] else: self.forms[self.action][self.method][name[0]]="" self.soc.w(self.forms,"white_on_gold") self.soc.me_him(['EXIT:',__name__],self.func_me_color) def url_dirname(self, url): self.soc.me_him(['RETURN:',__name__],self.func_me_color) #print url return self.fileRExp.sub('_',url) def dirname(self,url): self.soc.me_him(['RETURN:',__name__],self.func_me_color) return os.path.dirname(url) def save_images(self,minsize): if os.path.isdir(self.path+self.dirname): return False # aborting, dir exists else: a=self.path+self.dirname os.mkdir(a) os.chdir(a) print self.url for img in self.imgs.keys(): loc=self.url_dirname(img) print loc, img, a try: if self.imgs[img]==0: #urllib.urlretrieve(img,loc) #os.system('wget -A.jpg,gif,png,wmv,avi,mpg -r -l4 -H -erobots=off --wait=1 -np -U \"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.6) Gecko/20050405 Firefox/1.0 (Ubuntu package 1.0.2)\" '+img) #im = Image.open(loc) #if im.size[0] From steve at holdenweb.com Sat Dec 20 08:20:12 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 20 Dec 2008 08:20:12 -0500 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <06daa32b-aff7-4104-99bb-3cd1365be600@w1g2000prm.googlegroups.com> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> <06daa32b-aff7-4104-99bb-3cd1365be600@w1g2000prm.googlegroups.com> Message-ID: <494CF10C.8010302@holdenweb.com> Mark Summerfield wrote: [...] > > With two dozen postings on my use of English I'm now rather nervous > about the feeback I'll get on my Python 3! > There is no such thing as bad publicity. Quick, make a blog post about how there have been over twenty comments about your use of English (though don't forget to point out that it's correct). > PS Although Amazon.com still says the publication date is the 27th, > they now expect to have it in stock on Monday (the 22nd). Congratulations. I know what a relief it is to see a project of that size come to fruition! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From m1k3b0 at gmail.com Fri Dec 12 18:06:05 2008 From: m1k3b0 at gmail.com (m1k3b0 at gmail.com) Date: Fri, 12 Dec 2008 15:06:05 -0800 (PST) Subject: os.lstat : proper way to do this Message-ID: I'm converting from Perl to Python, so I'm learning the basics - please be gentle! :) In Perl, I can lstat($file) whether $file exists or not: lstat($file); unless (-e _) { print STDERR "$file: No such file or directory\n"; } unless (-l _) { print STDERR "$file: Not a symbolic link\n"; } The lstat() returns normally whether the file exists or not, and I check for existence with the "-e" conditional. Then I go on and check other modes. In Python,if I os.lstat(file) and file doesn't exist, I get an error from within the module: OSError: [Errno 2] No such file or directory: '/etc/xxx' I can check first with os.path.exists(file), but then I'm doing two stat() type calls which is inefficient (especially when we're talking thousands of files). I want to be able to do something like this: mode = os.lstat(file)[ST_MODE] if not mode: print >> sys.stderr, file, ": No such file or directory" if not S_ISLNK(mode): print >> sys.stderr, file, ": Not a symbolic link" Of course, this isn't valid. How can I do this efficiently without getting "no such file" error? Thanks! mikebo From martin at v.loewis.de Sun Dec 7 14:53:10 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 07 Dec 2008 20:53:10 +0100 Subject: Number of Python 3.x packages at the PyPI In-Reply-To: <2d656e64-deff-40ed-8066-57b6f8874ec4@b38g2000prf.googlegroups.com> References: <9c1ab0f3-6686-4c0f-8a6c-12e20539f354@41g2000yqf.googlegroups.com> <493b954e$0$4021$9b622d9e@news.freenet.de> <2d656e64-deff-40ed-8066-57b6f8874ec4@b38g2000prf.googlegroups.com> Message-ID: <493c29a7$0$27869$9b622d9e@news.freenet.de> > I've had to fork my appscript project's codebase in order to add > support for Python 3.x. I would like to distribute both 2.x and 3.x > versions under the same package name for obvious reasons. This isn't a > problem with eggs as the Python version number is included in each > egg's name, but what about source distributions where both filenames > are exactly the same (appscript-0.19.0.tar.gz)? I see. My initial reaction was that something should be done about this; please do bring this up on catalog-sig at python.org. On second thought: can't you just include the source of both versions in a single source distribution file? If you are going to release them in lock-step, you probably want to always release both sets of sources together; if you don't release them in lock-step, users will get confused how to obtain the most recent release for 3.x (say) if some version has only the 2.x release. Regards, Martin From f.guerrieri at gmail.com Mon Dec 22 13:15:31 2008 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Mon, 22 Dec 2008 19:15:31 +0100 Subject: Python's popularity In-Reply-To: <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> Message-ID: <79b79e730812221015y6b8be729ve2123bdef6715f11@mail.gmail.com> On Mon, Dec 22, 2008 at 7:01 PM, r wrote: > Walter, > I just look at the stats for comp.lang.python, and i am 9th place for > most post this month. That makes me completely sad. With just 50 post > so far, i am showing up on the high count. Sad, very sad. Now i have > much reason to believe that only 100 or so people follow this list :(. > Python is slipping. We must try harder, or all of Guido's work will be > for nothing! Just wanted to remember you that Python is an open source project initiated and led by Guido Van Rossum and kept alive (and in good health) by the work of *many* people. It if were only Guido's work it would be different from what it is now. Furthermore, choosing to code in a language or in another is not a matter of religion or of war. If someone likes Ruby, or Perl, or VBA... and is productive (according to her needs) with it, why in the world should a Python programmer consider her an "enemy"??? Francesco -------------- next part -------------- An HTML attachment was scrubbed... URL: From ethan at stoneleaf.us Thu Dec 11 14:29:09 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 11 Dec 2008 11:29:09 -0800 Subject: internal circular class references In-Reply-To: <49414EDA.2050509@stoneleaf.us> References: <49414EDA.2050509@stoneleaf.us> Message-ID: <49416A05.3070307@stoneleaf.us> Thanks, Carl! Thanks, RDM! Your examples and ideas are much appreciated. Many thanks also to everyone else who responded. ~Ethan~ From grahn+nntp at snipabacken.se Tue Dec 9 03:39:43 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 9 Dec 2008 08:39:43 GMT Subject: gzip.GzipFile (was Re: Don't you just love writing this sort of thing :)) References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: On Mon, 08 Dec 2008 14:21:40 +0000, MRAB wrote: > Jorgen Grahn wrote: >> On Sat, 06 Dec 2008 10:01:10 +0000, Arnaud Delobelle wrote: >> >> ... >>> Why use (open, gzp.GzipFile)[Entry.endswith(".gz")] when we have had >>> contitional expressions for a few years now? Instead, you can write >>> >>> (gzip.GzipFile if entry.endswidth(".gz") else open). >>> >>> I think it will be faster (as it doesn't require the construction of a >>> tuple and then the retrieval of one of its elements) and clearer. >> >> Even clearer would be if gzip.Gzipfile could (optionally) read >> non-gzipped files and file-like objects, like the gzip Unix commands >> zcat -f, zgrep and so on. ... > gzip is for reading gzipped files. IMHO it would be better to have a > de-archive module which uses the gzip, tarfile, etc, modules as necessary. Not tarfile, since that's usually a container for many files. But ok, maybe you are right about placing it in a different module -- even though it's fairly common for Unix application to accept plain files, gzipped files and nothing else. Note that such a module should handle reading sys.stdin and other non-disk files. That's a bit tricky, because when you realize that you guessed wrong on the format, you have already consumed and discarded some of the data. I started looking at such a module a year ago, but never finished it. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From sjmachin at lexicon.net Sat Dec 6 17:34:28 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 6 Dec 2008 14:34:28 -0800 (PST) Subject: Python 3.0 automatic decoding of UTF16 References: <55d79070-0c11-4fb9-8cf5-b8cc7c54b5d2@v42g2000yqv.googlegroups.com> Message-ID: <0e37191f-3672-4313-bc5c-ffcd904e4796@k24g2000pri.googlegroups.com> On Dec 7, 9:01?am, David Bolen wrote: > Johannes Bauer writes: > > This is very strange - when using "utf16", endianness should be detected > > automatically. When I simply truncate the trailing zero byte, I receive: > > Any chance that whatever you used to "simply truncate the trailing > zero byte" also removed the BOM at the start of the file? ?Without it, > utf16 wouldn't be able to detect endianness and would, I believe, fall > back to native order. When I read this, I thought "O no, surely not!". Seems that you are correct: [Python 2.5.2, Windows XP] | >>> nobom = u'abcde'.encode('utf_16_be') | >>> nobom | '\x00a\x00b\x00c\x00d\x00e' | >>> nobom.decode('utf16') | u'\u6100\u6200\u6300\u6400\u6500' This may well explain one of the Python 3.0 problems that the OP's 2 files exhibit: data appears to have been byte-swapped under some conditions. Possibility: it is reading the file a chunk at a time and applying the utf_16 encoding independently to each chunk -- only the first chunk will have a BOM. From badmuthahubbard at gmail.com Wed Dec 10 11:12:40 2008 From: badmuthahubbard at gmail.com (badmuthahubbard) Date: Wed, 10 Dec 2008 08:12:40 -0800 (PST) Subject: Python music sequencer timing problems Message-ID: <3b52b652-df61-4eb4-bcff-0d1fb6f20891@r15g2000prh.googlegroups.com> I've been trying to get the timing right for a music sequencer using Tkinter. First I just loaded the Csound API module and ran a Csound engine in its own performance thread. The score timing was good, being controlled internally by Csound, but any time I moved the mouse I got audio dropouts. It was suggested I run the audio engine as a separate process, with elevated/realtime priority and use sockets to tell it what to play, and that way, too, people could set up servers for the audio on different CPUs. But I've found that the method I came up with for timing the beats/notes is too slow (using threading.Timer on a function that calls itself over and over), and the whole thing played too slowly (and still gave me noise when moving the mouse). I've been using subprocesses, but I'm now wondering if sockets would or could make a difference. The overall goal is this: when the user wants to audition a piece, create an audio engine process with elevated/realtime priority. This engine also has all the synthesis and sound processing rules for the various instruments, due to the way Csound is structured. Set up a scheduler- possibly in another process, or just another thread- and fill it with all the notes from the score and their times. Also, the user should be able to see a time-cursor moving across the piece so they can see where they are in the score. As this last bit is GUI, the scheduler should be able to send callbacks back to the GUI as well as notes to the audio engine. But neither the scheduler nor the audio engine should wait for Tkinter's updating of the location of the time- cursor. Naturally, all notes will have higher priorities in the scheduler than all GUI updates, but they won't necessarily always be at the same time. So, I have a few ideas about how to proceed, but I want to know if I'll need to learn more general things first: 1. Create both the scheduler and the audio engine as separate processes and communicate with them through sockets. When all events are entered in the scheduler, open a server socket in the main GUI process and listen for callbacks to move the cursor (is it possible to do this using Tkinter's mainloop, so the mouse can be moved, albeit sluggishly, at the same time the cursor is moving continuously?); the audio engine runs at as high priority as possible, and the scheduler runs somewhere between that and the priority of the main GUI, which should even perhaps be temporarily lowered below default for good measure. or 2. Create the audio engine as an elevated priority process, and the scheduler as a separate thread in the main process. The scheduler sends notes to the audio engine and callbacks within its own process to move the GUI cursor. Optionally, every tiny update of the cursor could be a separate thread that dies an instant later. 3. Closer to my original idea, but I'm hoping to avoid this. All note scheduling and tempo control is done by Csound as audio engine, and a Csound channel is set aside for callbacks to update the cursor position. Maybe this would be smoothest, as timing is built into Csound already, but the Csound score will be full of thousands of pseudo-notes that only exist for those callbacks. Down the road I'd like to have notes sound whenever they are added or moved on the score, not just when playing the piece, as well as the option of adjusting the level, pan, etc. of running instruments. It seems method 2 runs the risk of slowing down the timing of the notes if the mouse moves around; but method 1 would require setting up an event loop to listen for GUI updates from the scheduler. I was trying method 1 with subprocesses, but reading from the scheduler process's stdout PIPE for GUI updates wasn't working. I was referred to Twisted and the code module for this, and haven't yet worked out how to use them appropriately. I don't mind a complex solution, if it is reliable (I'm aiming at cross-platform, at least WinXP-OSX-Linux), but everything I try seems to add unnecessary complexity without actually solving anything. I've been reading up on socket programming, and catching bits here and there about non-blocking IO. Seem like good topics to know about, if I want to do audio programming, but I also need a practical solution for now. Any advice? Thanks a lot. -Chuckk From gandalf at shopzeus.com Thu Dec 18 11:43:02 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 18 Dec 2008 17:43:02 +0100 Subject: Is this pythonic? In-Reply-To: <66d058f9-cfe1-4b3c-ab8a-e6e88bb97770@m22g2000vbp.googlegroups.com> References: <66d058f9-cfe1-4b3c-ab8a-e6e88bb97770@m22g2000vbp.googlegroups.com> Message-ID: <494A7D96.8010902@shopzeus.com> ipytest at gmail.com wrote: > x.validate_output(x.find_text(x.match_filename > (x.determine_filename_pattern(datetime.datetime.now())))) > > Is it even good programming form? > You should try LISP. :-) From martin at v.loewis.de Mon Dec 15 18:21:36 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 16 Dec 2008 00:21:36 +0100 Subject: Problem Python 2.6.1 vs 2.6 & pyWin32 In-Reply-To: References: <4946754f$0$19000$426a74cc@news.free.fr> <4946D09F.6050300@v.loewis.de> Message-ID: <4946e680$0$9099$9b622d9e@news.freenet.de> >> Try installing Python 2.6.1 "for all users". > > Could you clarify why that's needed? I didn't say it's needed. I said that he should try that, perhaps it helps. > One thing we noticed (I'm not sure has this been yet submitted to > bugs.python.org yet) was that installing packages created with Python > 2.5 to Python 2.6 failed unless Python was in %PATH% [1]. In general, that's not supported at all. You will have to rebuild all packages for Python 2.6, unless they are pure-python packages (in which case PATH should be irrelevant). If the .pyd files would have loaded, Python would have complained that they originate from the wrong Python version. > Another pretty severe problem was that installers created with Python > 2.6 didn't work at all with older versions [2]. That's not a bug, either. It has been that way since Python 1.4 or so: .pyd files built for X.Y won't work for X.(Y+1), and vice versa. It seems that you mean something specific with the word "installer"; I think you should elaborate what precisely you are referring to. Regards, Martin From bignose+hates-spam at benfinney.id.au Sun Dec 14 16:55:44 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 15 Dec 2008 08:55:44 +1100 Subject: the official way of printing unicode strings References: Message-ID: <871vwah15r.fsf@benfinney.id.au> Piotr Sobolewski writes: > in Python (contrary to Perl, for instance) there is one way to do > common tasks. More accurately: the ideal is that there should be only one *obvious* way to do things. Other ways may also exist. > Could somebody explain me what is the official python way of > printing unicode strings? Try these: If you want something more official, try the PEP that introduced Unicode objects, PEP 100: . > I tried to do this such way: > s = u"Stanis?aw Lem" > print u.encode('utf-8') > This works, but is very cumbersome. Nevertheless, that says everything that needs to be said: You've defined a Unicode text object, and you've printed it specifying which character encoding to use. When dealing with text, the reality is that there is *always* an encoding at the point where program objects must interface to or from a device, such as a file, a keyboard, or a display. There is *no* sensible default encoding, except for the increasingly-inadequate 7-bit ASCII. Since there is no sensible default, Python needs to be explicitly told at some point which encoding to use. > Then I tried to do this that way: > s = u"Stanis?aw Lem" > print u > This breaks when I redirect the output of my program to some file, > like that: > $ example.py > log How does it ?break?? What behaviour did you expect, and what behaviour did you get instead? -- \ ?I hope that after I die, people will say of me: ?That guy sure | `\ owed me a lot of money?.? ?Jack Handey | _o__) | Ben Finney From mcrute at gmail.com Thu Dec 4 18:29:48 2008 From: mcrute at gmail.com (Michael Crute) Date: Thu, 4 Dec 2008 18:29:48 -0500 Subject: Importing Version Specific Modules Message-ID: <558b73fb0812041529g313a27bpcfd09fc90f474f6e@mail.gmail.com> Which method makes the most sense for importing a module in python that is version specific? My use case is that I'm writing code that will be deployed into a python 2.3 environment and in a few months be upgraded to python 2.5. This: if sys.version_info[:2] >= (2, 5): from string import Template else: from our.compat.string import Template or this try: from string import Template except ImportError: from our.compat.string import Template I know that either case is equally correct and works correctly but which one is preferable? -- ________________________________ Michael E. Crute http://mike.crute.org God put me on this earth to accomplish a certain number of things. Right now I am so far behind that I will never die. --Bill Watterson From tvrtko.sokolovski at gmail.com Sat Dec 13 17:06:32 2008 From: tvrtko.sokolovski at gmail.com (sokol) Date: Sat, 13 Dec 2008 14:06:32 -0800 (PST) Subject: pypi package dates Message-ID: Am I missing something? There are no release dates for packages in pypi. One cannot have an idea how current the package is... From george.sakkis at gmail.com Tue Dec 2 21:12:26 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 2 Dec 2008 18:12:26 -0800 (PST) Subject: Overriding a method at the instance level on a subclass of a builtin type References: Message-ID: On Dec 2, 7:58?pm, "Zac Burns" wrote: > Sorry for the long subject. > > I'm trying to create a subclass dictionary that runs extra init code > on the first __getitem__ call. However, the performance of __getitem__ > is quite important - so I'm trying in the subclassed __getitem__ > method to first run some code and then patch in the original dict > method for the instance to avoid even the check to see if the init > code has been run. Various recipes using instancemethod and the like > have failed me. For new-style classes, special methods are always looked up in the class, not the instance, so you're out of luck there. What are you trying to do? Perhaps there is a less magic solution to the general problem. George From R.Brodie at rl.ac.uk Fri Dec 5 12:38:25 2008 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 5 Dec 2008 17:38:25 -0000 Subject: Python 3.0 automatic decoding of UTF16 References: <85fxl24lbu.fsf@dozer.localdomain> Message-ID: "J Kenneth King" wrote in message news:85fxl24lbu.fsf at dozer.localdomain... > It probably means what it says: that the input file contains characters > it cannot read using the specified encoding. That was my first thought. However it appears that there is an off by one error somewhere in the intersection of line ending/codec processing. Half way through the codec starts byte-flipping characters. From mail at microcorp.co.za Sun Dec 28 05:59:03 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 28 Dec 2008 12:59:03 +0200 Subject: ctypes & strings References: <334452.47084.qm@web30003.mail.mud.yahoo.com><000f01c96822$5c300f00$0d00a8c0@hendrik> Message-ID: <00a801c968dd$6508b3a0$0d00a8c0@hendrik> "Gabriel Genellina" wrote: >Hmmm, I don't think posting a potentially harmful example is actually a >good idea... True - its my only example though, and nobody else was bothering to reply, so I kicked off and flushed out some response. Who was it that said that the way to get info out of usenet was to post some rubbish? :-) - Hendrik From jeremiah.dodds at gmail.com Sat Dec 20 04:37:00 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Sat, 20 Dec 2008 04:37:00 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <2dc66762-f51e-4bbd-9372-756610d4201e@j11g2000yqg.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c4ef2$0$20656$c3e8da3@news.astraweb.com> <2d53cd36-52b0-4a1a-913d-0c545cfadc23@v15g2000vbb.googlegroups.com> <2dc66762-f51e-4bbd-9372-756610d4201e@j11g2000yqg.googlegroups.com> Message-ID: <12cbbbfc0812200137t37bdb792p2eab52812c21aefa@mail.gmail.com> On Sat, Dec 20, 2008 at 12:30 AM, r wrote: > Why could't we improve on what we had instead of > making radical changes? Thats all i am asking. > -- > http://mail.python.org/mailman/listinfo/python-list > Often times improving on what you have involves radical changes, especially if the goals of what you have change, or were not fully understood during their original implementation. -------------- next part -------------- An HTML attachment was scrubbed... URL: From news123 at free.fr Sat Dec 6 08:21:45 2008 From: news123 at free.fr (News123) Date: Sat, 06 Dec 2008 14:21:45 +0100 Subject: python book for non technical absolute beginner Message-ID: <493a7c6a$0$973$426a34cc@news.free.fr> Hi, One of my 'non technical' friends complained about knowing nothing at all about programming (though using computers regularly for mails / web browsing / googling and downloading / cropping photos ) He wants to play a little with programming to stimulate parts of his otehrwise idle brain cells. ;-) Normally it's more the social science / linguistic parts being exercised, I thought python might be a nice language for this No my question does anybody know a nice beginners book (or a learning CD or on line tutorial)? Ideally it shouldn't be too serious and have a lot of small nice mini-examples thanks in advance for any suggestions hints bye N From pxrepreza at gmail.com Tue Dec 23 12:12:32 2008 From: pxrepreza at gmail.com (Paulo Repreza) Date: Tue, 23 Dec 2008 09:12:32 -0800 Subject: String Format Error. In-Reply-To: References: <47c890dc0812222311m2a67b798v167b40de9dfcd53d@mail.gmail.com> Message-ID: Thank You! On Tue, Dec 23, 2008 at 3:49 AM, Steve Holden wrote: > Chris Rebert wrote: > > On Mon, Dec 22, 2008 at 10:19 PM, Paulo Repreza > wrote: > >> Hi, > >> > >> I'm a newbie with python and I recently bought Beginning with Python > (Which > >> is a book I recommend) but the problem that I'm facing it's the > following: > >> > >> This is the code: > >> > >> #!/usr/bin/python2.5 > >> # Filename: str_format.py > >> > >> age = 25 > >> name = 'foobar' > >> > >> print('{0} is {1} years old'.format(name, age)) > >> print('Why is {0} playing with that python?'.format(name)) > >> > >> > >> But when I run the script I receive this error: > >> > >> Traceback (most recent call last): > >> File "str_format.py", line 7, in > >> print('{0} is {1} years old'.format(name, age)) > >> AttributeError: 'str' object has no attribute 'format' > >> > >> > >> It is an error because of the version that I'm using ? Python 2.5.2 > (Debian > >> lenny) > > > > Yes, Python 2.6 or higher is required to use .format() according to > > http://docs.python.org/whatsnew/2.6.html > > > For a replacement that will work in 2.5, see the "%" sign as an operator > (sometimes called "string interpolation"). > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fetchinson at googlemail.com Mon Dec 22 17:25:54 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 22 Dec 2008 14:25:54 -0800 Subject: Are Django/Turbogears too specific? In-Reply-To: References: Message-ID: > I'd like to rewrite a Web 2.0 PHP application in Python with AJAX, and > it seems like Django and Turbogears are the frameworks that have the > most momentum. > > I'd like to use this opportunity to lower the load on servers, as the > PHP application wasn't built to fit the number of users hammering the > servers now. > > I'm concerned, though, that these frameworks they may be too specific > to the tasks they were originally developped for (news articles, > AFAIK). Do you think I should just use eg. CherryPy and some basic > AJAX? The 1.x branch of tg is built on cherrypy, the 2.x branch is built on pylons. Both branches depend on external packages for most of their functionality which makes them very flexible. Django is monolithic and was intended to be monolithic. Of course you can customize it and use different components than the defaults, but after all *everything* is customizable since the source code is there and you can modify it. The point is that tg was designed with flexibility and customizability in mind, while django was designed with a monolithic infrastructure in mind. The 1.x branch of tg is stable and has been for years while the 2.x branch is in beta but will be released soon as a stable, production version. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From 5lvqbwl02 at sneakemail.com Sun Dec 7 02:33:35 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Sat, 6 Dec 2008 23:33:35 -0800 (PST) Subject: Brain going crazy with recursive functions Message-ID: <6470511f-093e-42c2-a6c2-4bb90b336ac9@r15g2000prd.googlegroups.com> I'm trying to solve the 9-tile puzzle using as functional an approach as possible. I've recently finished reading SICP and am deliberately avoiding easy python-isms for the more convoluted scheme/functional methods. The following function is trivial to do with for loops and directly accessing arrays with [] syntax. I'm trying to limit myself to the types of idioms/semantics one finds in minimal scheme, such as in SICP. I want eventually to port this to scheme, but I know python better, so that's where I'm starting. My current problem is the following. The 9-tile puzzle consists of a list of lists like this [[1,2,3],[4,5,6],[7,8,0]], where the numbers can be jumbled up. I'm looking for the location of the zero using *only* recursion and operators that are similar to car/cdr. The return value should be the row,col of the zero. For example above the return value would be (2,2). I'm also trying to define a single "linear_search(...)" function which does the search for within the row (an inner list above) and within the whole list. linear_search takes as an argument a "truth_function" which does the actual work. What's tricky is that the truth function for the array-as-a-whole is also the linear_search for a row. Once I'm in linear_search for the array, I also call linear_search for each row. The problem is the line where it says acc.insert(0,idx) looks fishy to me. It works fine and returns the row,col of the location of the zero tile, but it seems to be mutating a variable, and that's the thing I'm trying to avoid. In a sense, it's not hard enough and python is making this too easy :) (although it took a bit of mind-wrenching to get to this point. Recursion makes you either dumber or smarter, I'm not sure which). How do I accumulate the inner value of the search so it pops out at the end, without resorting to a mutable variable? I did a bit of search and the word "monad" came up, but I'm not sure what that is (I know it relates to haskell and some other purely functional stuff, but I get very lost when trying to read that stuff). def linear_search(array, truth_func, acc): # Goes through each element of array and applies truth_func. # Returns index if found, otherwise returns None def linear_search_iter(idx, truth_func, arr, acc): if arr: tf = truth_func(arr[0]) if tf or type(tf) is int: acc.insert(0,idx) return idx, acc+[idx] else: return linear_search_iter(idx+1, truth_func, arr[1:], acc) return linear_search_iter(0, truth_func, array, acc) def locate_zero(p): # Locates empty tile. Returns (r,c) tuple def find_zero_in_row(row): return linear_search(row, lambda x: x==0, acc) acc = [] ls = linear_search(p, find_zero_in_row, acc) print acc return acc locate_zero([[5, 3, 4], [2, 0, 1], [8, 6, 7]]) correctly returns (1,1) From mail at timgolden.me.uk Mon Dec 22 11:57:26 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 22 Dec 2008 16:57:26 +0000 Subject: join a samba domain In-Reply-To: <5428c77b-ed4f-49ec-a808-dccd77a2a01c@g3g2000pre.googlegroups.com> References: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> <5428c77b-ed4f-49ec-a808-dccd77a2a01c@g3g2000pre.googlegroups.com> Message-ID: <494FC6F6.6000107@timgolden.me.uk> Toff wrote: > On 22 d?c, 17:02, Tim Golden wrote: >> Toff wrote: >>> hi, >>> I 'm trying to write a script to make my computer join a samba. >>> domeone have any idea ?? >> Ummm. It's not clear if you're saying that your code doesn't >> work, or asking for general advice, or what? I'm not in a >> position to have my machine join a domain or workgroup, but >> you seem to have got most things in place already. The only >> thing I would expect to have to change is this last line: >> >>> import wmi >>> c = wmi.WMI() >>> d = c.Win32_ComputerSystem >>> d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") >> because the d is only a WMI *class*, not a WMI *instance*, >> so doesn't refer as it should to your computer system but >> to the class of computer systems. Try something like this (untested): >> >> >> import wmi >> >> c = wmi.WMI () >> for d in c.Win32_ComputerSystem (): >> d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") >> >> >> >> TJG > thanks but it doesn't work > I've got this errors > > Traceback (most recent call last): > File "integrdom.py", line 51, in > main() > File "integrdom.py", line 13, in main > joindom() > File "integrdom.py", line 44, in joindom > d.JoinDomainOrWorkGroup(None, 3, "domcd", "adminLocal", r"admin > \domcd") > File "c:\Python25\Lib\site-packages\wmi.py", line 493, in __getattr__ > handle_com_error (error_info) > File "c:\Python25\Lib\site-packages\wmi.py", line 189, in > handle_com_error > raise x_wmi, "\n".join (exception_string) > wmi.x_wmi Do you not get *anything* after than wmi.x_wmi? Not even a messy exception string? TJG From dstanek at dstanek.com Mon Dec 22 10:27:49 2008 From: dstanek at dstanek.com (David Stanek) Date: Mon, 22 Dec 2008 10:27:49 -0500 Subject: Basic misunderstanding of generators In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF6024944BB@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF6024944BB@enbmail01.lsi.com> Message-ID: On Mon, Dec 22, 2008 at 4:47 AM, Barak, Ron wrote: > > if __name__ == "__main__": > filename = "sac.log.gz" > log_stream = LogStream(filename) > line_ = log_stream.next_line(log_stream.input_file) > print line_ > > $ python LogManager_try.py > > A method or function containing a yield statement will return a generator instance when called. Which is what is happening in your example. What you want to do is something like: for line in log_stream.next_line(log_stream.input_file): print line To make the code bit simpler and more OO you should not need to pass anything into next_line(). It is a part the object so it naturally has access to its properties. That being said you can then use __iter__ instead and then you can then do something like: for line in log_stream: print line OTOH If your LogStreamer class doesn't keep any additional state I would probably just create a single generator function. -- David http://www.traceback.org From saluk64007 at gmail.com Tue Dec 30 00:57:22 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Mon, 29 Dec 2008 21:57:22 -0800 Subject: How do I DRY the following code? In-Reply-To: References: Message-ID: On Mon, Dec 29, 2008 at 6:13 PM, R. Bernstein wrote: > How do I DRY the following code? > > class C(): > > def f1(self, arg1, arg2=None, globals=None, locals=None): > ... unique stuff #1 ... > ... some common stuff #1 ... > ret = eval(args, globals, locals) > ... more stuff #2 ... > return retval Possibly make a separate method with the common stuff. Make each variant function call various other methods with the "different stuff" being different arguments to shared functions, or calling slightly different methods. Take the code one issue at a time, this seems complex enough that there is no easy, quick refactoring that can be done. Something like this is what I see, but it's hazy: def f1(self,args): ... unique stuff #1 self.commonstuff1() ret = self.myeval(args) self.commonstuff2() return retval Looking at the actual code, my thoughts are that you pick the most common base "run" type and stick with that, making other run types modify that. For instance, you could pass an evaluator function in to the base run() method, and call that, instead of having a separate case for exec or eval. runfunc would pass in the function itself as the evaluator. So it looks more like this: def run(blah, blah, BLAH, BLAAAAAH, evaluator, locals, globals): do much stuff evaluator(code,locals,globals) do much other stuff def runfunc(blah, func): run(blah, value_defined_for_runfunc, func, locals, globals) def runeval(blah): run(blah, value_defined_for_runfunc, eval, locals globals) The thing I don't like about this is it could very well make the main run function even hairier than it already is. But I don't think it has to be that way. This may not be the ideal solution either, if you can get a nice set of lower-level methods which each run method compose in different ways to produce the final result. > f1(...): > "Docstring f1" > c = C() > return c.f1(...) > > f2(...): > "Docstring f2" > c = C() > return c.f2(...) Why not just do either this: C().f2(..) where you need f2 Or make the function an argument: f(name): c = C() return getattr(c,name)() I'm not sure why you need the top-level functions though. If you really need them, and don't want to add an extra argument, I don't think there is a simpler way to do than you have. From tommy.nordgren at comhem.se Thu Dec 11 23:06:33 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Fri, 12 Dec 2008 05:06:33 +0100 Subject: =?ISO-8859-1?Q?Re:_how_to_convert_=91\xf0'_to_0xf0_=3F?= In-Reply-To: References: Message-ID: On Dec 12, 2008, at 4:48 AM, chengang.beijing at gmail.com wrote: > int('\xf0',16) doesn't work, any way to do that? > -- > http://mail.python.org/mailman/listinfo/python-list Should be int('10',16) or int('0x10',16) ------------------------------------------------------ "Home is not where you are born, but where your heart finds peace" - Tommy Nordgren, "The dying old crone" tommy.nordgren at comhem.se From sonicsai at gmail.com Tue Dec 23 04:30:08 2008 From: sonicsai at gmail.com (sai) Date: Tue, 23 Dec 2008 01:30:08 -0800 Subject: No subject Message-ID: <41d04d600812230130j5893b288m44bf820f05484ad4@mail.gmail.com> From christophedeze at gmail.com Mon Dec 22 10:17:55 2008 From: christophedeze at gmail.com (Toff) Date: Mon, 22 Dec 2008 07:17:55 -0800 (PST) Subject: join a samba domain Message-ID: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> hi, I 'm trying to write a script to make my computer join a samba. domeone have any idea ?? thanks regards, ************************************************************************* # -*- coding: iso-8859-1 *-* import win32com.client import os,sys import win32api import impers import socket from win32com.client import GetObject import wmi def main(): test() joindom() def test(): import wmi c = wmi.WMI() os = c.Win32_ComputerSystem for method_name in os.methods: method = getattr(os, method_name) print method def joindom(): #Joining a computer to a domain #========================= JOIN_DOMAIN = 1 ACCT_CREATE = 2 ACCT_DELETE = 4 WIN9X_UPGRADE = 16 DOMAIN_JOIN_IF_JOINED = 32 JOIN_UNSECURE = 64 MACHINE_PASSWORD_PASSED = 128 DEFERRED_SPN_SET = 256 INSTALL_INVOCATION = 262144 strDomain = "mydom" strPassword = "mydompw" strUser = "admin" strComputer = socket.gethostname() print strComputer #objComputer = win32com.client.GetObject(r"winmgmts: {impersonationLevel=Impersonate}!\\mypc\root \cimv2:Win32_ComputerSystem.Name='mypc'") import wmi c = wmi.WMI() d = c.Win32_ComputerSystem d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") if __name__=='__main__': main() *********************************************************************** From jstroud at mbi.ucla.edu Thu Dec 4 04:44:50 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 04 Dec 2008 01:44:50 -0800 Subject: "as" keyword woes In-Reply-To: References: Message-ID: alex23 wrote: > On Dec 4, 3:42 pm, "Warren DeLano" wrote: >> So you prefer broken code to broken rules, eh? Your customers must love >> that! This is exactly the kind of ivory-tower thinking I feared might >> be behind the decision (form over function, damn the users to hell, >> etc.) > > Really? I find that believing something should remain static at the > expense of actual improvement to the language is far more 'ivory-tower > thinking' than embracing change. First, to quote Tim Peters, "practicality beats purity." Second, I might be biased here because I happen to know Warren, but, although he hails from the ivory tower, I imagine his concerns are purely practical. His contributions to software in structural biology are legendary. >> Am I the only one picking up on the irony here? "as" exists largely to >> provide a mechanism for working around namespace conflicts -- except, >> apparently, conflicts involving "as". The fact that "as" itself creates >> an insurmountable namespace collision is just killing me! How absurd. > > Speaking of irony, you're complaining about namespace conflicts with a > -two character identifier- you've chosen. Here's a hint: choose better > names. The name fit his needs until changes in the language broke the name. If a name works and the code works, then the name is good enough. And speaking as a professional user of his software at the level of the application and at the level of the API, let me tell you his code works pretty damn good. >> But to be brutally honest...in this many-core world we must all accept >> and deal with today, it is hard to imagine how a non-multithreaded AND >> non-backwards compatible Python implementation can have much of a life >> ahead of it, with or without an "as" keyword. I do sincerely hope I am >> wrong about this, but it is seems quite possible that C/Python's glory >> days are now behind us. > > To match your honesty, I'm somewhat tired with the trend of some > people to hit -one- issue with Python and suddenly lash out like > children over all the same old tired crap. Have you even looked at > multiprocessing? Have you contributed to any projects working on GIL- > less implementations? Or are you just regurgitating the same bullet > points we've heard time and time again? > > For chrissake, if you cannot do ANYTHING but BITCH about a change, > then you've no damn right to consider yourself a programmer. Real > programmers find solutions, not excuses. Correction: Real programmers write programs. And no, at this point he can't do anything but complain because, as others have noted, the change is not going away. >> And if so, then thank you all for so many wonderful years of effort and >> participation! > > You're welcome. Don't let the door hit you on the ass on your way out. You probably aren't a developer for the cPython implementation, but, if you were, I'd recommend taking rants like Warren's to heart because they are born of honest frustration and practical concern. Hopefully developers for python 2.7 are listening and won't break backward compatibility just because the "Zen of Python" suggests it might be a good idea. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From sjmachin at lexicon.net Mon Dec 29 04:59:13 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 29 Dec 2008 01:59:13 -0800 (PST) Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <0167cbf7$0$6988$c3e8da3@news.astraweb.com> <676bffeb-4b07-4226-8c14-7da57d94351b@f13g2000yqj.googlegroups.com> <3afba310-dcde-4dc1-825a-7c63b97e2a40@w1g2000prk.googlegroups.com> <495897c4$0$8481$426a74cc@news.free.fr> Message-ID: <7f340e90-c288-4592-8a4c-b008c24cf62a@q26g2000prq.googlegroups.com> On Dec 29, 8:26?pm, Bruno Desthuilliers wrote: > John Machin a ?crit : > > > > > On Dec 29, 7:06 am, Roger wrote: > >>> Curious. When I see a bare return, the first thing I think is that the > >>> author forgot to include the return value and that it's a bug. > >>> The second thing I think is that maybe the function is a generator, and > >>> so I look for a yield. If I don't see a yield, I go back to thinking > >>> they've left out the return value, and have to spend time trying to > >>> understand the function in order to determine whether that is the case or > >>> not. > >>> In other words, even though it is perfectly valid Python, bare returns > >>> always make the intent of the function less clear for me. I'm with Bruno > >>> -- if you have a function with early exits, and you need to make the > >>> intent of the function clear, explicitly return None. Otherwise, leave it > >>> out altogether. > >>> -- > >>> Steven > >> To me this is the soundest argument. ?Thanks for the advice. ?I think > >> I'll follow this as a rule of thumb hereafter. > > > Please don't. Follow MRAB's advice, with the corollary that a > > generator is forced by the compiler to be a "procedure" in MRAB's > > terminology. > > I fail to see any *practical* difference between MRAB's and Steven's > POVs. In both cases, it boils down to > - don't use a bare return at the end of a def statement's body, > - either use only bare returns ('procedure') or explicitely return None > ('function') Steven's treatment was somewhat discursive, and didn't explicitly mention the 'procedure' possibility. In fact, this sentence "if you have a function with early exits, and you need to make the intent of the function clear, explicitly return None." would if applied to a 'procedure' cause a stylistic horror as bad as a bare return at the end of the def. From toby at telegraphics.com.au Thu Dec 11 00:03:10 2008 From: toby at telegraphics.com.au (toby) Date: Wed, 10 Dec 2008 21:03:10 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: On Dec 10, 3:37 pm, w_a_x_... at yahoo.com wrote: > On Dec 5, 9:51 am, Xah Lee wrote: > > > > > For those of you who don't know linear algebra but knows coding, this > > means, we want a function whose input is a list of 3 elements say > > {x,y,z}, and output is also a list of 3 elements, say {a,b,c}, with > > the condition that > > > a = x/Sqrt[x^2+y^2+z^2] > > b = y/Sqrt[x^2+y^2+z^2] > > c = z/Sqrt[x^2+y^2+z^2] > > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, > > you'll have 50 or hundreds lines. void normalise(float d[], float v[]){ float m = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); d[0] = v[0]/m; // My guess is Xah Lee d[1] = v[1]/m; // hasn't touched C d[2] = v[2]/m; // for near to an eternitee } > > Ruby: > > def norm a > s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) > a.map{|x| x/s} > end From castironpi at gmail.com Thu Dec 4 23:15:46 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 4 Dec 2008 20:15:46 -0800 (PST) Subject: Overriding a method at the instance level on a subclass of a builtin type References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> Message-ID: <0c69e493-669a-4503-b2ec-ae7cf5e7fa0c@t2g2000yqm.googlegroups.com> On Dec 4, 11:16?am, "Zac Burns" wrote: > The class method seems to be the most promising, however I have more > 'state' methods to worry about so I might end up building new classes > on the fly rather than have a class per permutation of states! Now the > code isn't quite as clear as I thought it was going to be. > > It seems unfortunate to me that methods are always looked up on the > class for new style objects. Was this done for speed reasons? I thought of two more solutions. One, derive a new class for each instance as you create it, and assign methods to that, that can be shared. Even more memory consumption though. >>> class A: ... def methA( self ): print 'methA' ... def methB( self ): print 'methB' ... >>> class A1(A): meth= A.methA ... >>> a1=A1() >>> a1.meth() methA >>> A1.meth=A.methB >>> a1.meth() methB Two, use getter properties to return the right function, based on index and array. >>> class A( object ): ... @property ... def meth( self ): ... return self.meths[ self.methA_i ].__get__( self, A ) ... def methA( self ): ... print 'methA' ... self.methA_i+= 1 ... def methB( self ): ... print 'methB' ... self.methA_i-= 1 ... meths= [ methA, methB ] ... def __init__( self ): ... self.methA_i= 0 ... >>> a= A() >>> a.meth() methA >>> a.meth() methB >>> a.meth() methA Or (two B), look up the method by name on name-index pair. >>> class A( object ): ... @property ... def meth( self ): ... return getattr( self, self.meths[ self.methA_i ] ) ... def methA( self ): ... print 'methA' ... self.methA_i+= 1 ... def methB( self ): ... print 'methB' ... self.methA_i-= 1 ... meths= [ 'methA', 'methB' ] ... def __init__( self ): ... self.methA_i= 0 ... >>> a= A() >>> a.meth() methA >>> a.meth() methB >>> a.meth() methA The 'meths' list will need separate lists for each 'group' of state- dependent functions you wish to use. From vkseashoremack at googlemail.com Sat Dec 20 11:56:46 2008 From: vkseashoremack at googlemail.com (vkseashoremack at googlemail.com) Date: Sat, 20 Dec 2008 08:56:46 -0800 (PST) Subject: lesbo land - Free Message-ID: <22d76a26-4fd1-4d1f-aef9-407fa1f1597a@t26g2000prh.googlegroups.com> lesbo land . . . *******CLICK HERE******** http://club247.cn/lesbo-land ***************************** . . . . . . . . . . . . lesbo land From rt8396 at gmail.com Tue Dec 2 16:17:52 2008 From: rt8396 at gmail.com (r) Date: Tue, 2 Dec 2008 13:17:52 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> Message-ID: <64deddc7-3d65-43de-bb2d-766c890a9ab8@33g2000yqm.googlegroups.com> "The devils in the details" From excord80 at gmail.com Sun Dec 7 19:15:13 2008 From: excord80 at gmail.com (excord80 at gmail.com) Date: Sun, 7 Dec 2008 16:15:13 -0800 (PST) Subject: Number of Python 3.x packages at the PyPI References: <9c1ab0f3-6686-4c0f-8a6c-12e20539f354@41g2000yqf.googlegroups.com> <493b954e$0$4021$9b622d9e@news.freenet.de> Message-ID: On Dec 7, 12:21?pm, s... at pobox.com wrote: > ? ? Martin>http://pypi.python.org/pypi?:action=browse&c=533 > > ? ? Martin> It seems that some package authors only classify with > > ? ? Martin> ? Programming Language :: Python :: 3 > > I did a release for lockfile yesterday which supports 3.0. ?I added the > "Programming Language :: Python :: 3.0" tag, but not the more inlusive tag > above. ?I just updated the information to include it so it now appears in > the search results. > > Skip Should specifying the 3.0 tag implicity and automatically specify the 3 tag as well? From metolone+gmane at gmail.com Fri Dec 5 09:50:36 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Fri, 5 Dec 2008 06:50:36 -0800 Subject: pretty strange behavior of "strip" References: <4938693F.6090709@yahoo.ca> <493936EC.9030606@yahoo.ca> Message-ID: "Guy Doune" wrote in message news:493936EC.9030606 at yahoo.ca... > Ok, didn't show the whole problem... > > I will read the doc anyway, but why "questions.html" keep it "t"?? > > >>> test=['03.html', '06.html', 'questions.html', '04.html', 'toc.html', > '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test[4] > 'toc.html' > >>> test[4].strip('.html') > 'oc' > >>> test[2].strip('.html') > 'questions' It doesn't strip the character set from the whole string, it strips it from the beginning and end of the string only. If it encounters a character that isn't in the set, it stops. Does this make it more clear? >>> 'aabdabcdccb'.strip('cba') 'dabcd' -Mark From sjmachin at lexicon.net Sat Dec 6 16:40:47 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 6 Dec 2008 13:40:47 -0800 (PST) Subject: Python 3.0 automatic decoding of UTF16 References: <5u8o06xbqf.ln2@joeserver.homelan.net> <1mmq06x4g6.ln2@joeserver.homelan.net> Message-ID: On Dec 7, 6:20?am, "Mark Tolonen" wrote: > "Johannes Bauer" wrote in message > > news:1mmq06x4g6.ln2 at joeserver.homelan.net... > > > > >John Machin schrieb: > >> On Dec 6, 5:36 am, Johannes Bauer wrote: > >>> So UTF-16 has an explicit EOF marker within the text? I cannot find one > >>> in original file, only some kind of starting sequence I suppose > >>> (0xfeff). The last characters of the file are 0x00 0x0d 0x00 0x0a, > >>> simple \r\n line ending. > > >> Sorry, *WRONG*. It ends in 00 0d 00 0a 00. The file is 1559 bytes > >> long, an ODD number, which shouldn't happen with utf16. ?The file is > >> stuffed. Python 3.0 has a bug; it should give a meaningful error > >> message. > > >Yes, you are right. I fixed the file, yet another error pops up > >(http://www.file-upload.net/download-1299688/2008_12_05_Handy_Backup.t... > > >Traceback (most recent call last): > > ?File "./modify.py", line 12, in > > ? ?a = AddressBook("2008_12_05_Handy_Backup.txt") > > ?File "./modify.py", line 7, in __init__ > > ? ?line = f.readline() > > ?File "/usr/local/lib/python3.0/io.py", line 1807, in readline > > ? ?while self._read_chunk(): > > ?File "/usr/local/lib/python3.0/io.py", line 1556, in _read_chunk > > ? ?self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) > > ?File "/usr/local/lib/python3.0/io.py", line 1293, in decode > > ? ?output = self.decoder.decode(input, final=final) > > ?File "/usr/local/lib/python3.0/codecs.py", line 300, in decode > > ? ?(result, consumed) = self._buffer_decode(data, self.errors, final) > > ?File "/usr/local/lib/python3.0/encodings/utf_16.py", line 69, in > >_buffer_decode > > ? ?return self.decoder(input, self.errors, final) > >UnicodeDecodeError: 'utf16' codec can't decode byte 0x0a in position 0: > >truncated data > > >File size is 1630 bytes - so this clearly cannot be. > > How about posting your code? He did. Ugly stuff using readline() :-) Should still work, though. There are definite problems with readline() and readlines(), including: First file: silently ignores error *and* the last line returned is garbage [consists of multiple actual lines, and the trailing codepoints have been byte-swapped] Second file: as he has just reported. I've reproduced it with f.open ('second_file.txt', encoding='utf16') followed by each of: (1) f.readlines() (2) list(f) (3) for line in f: print(repr(line)) With the last one, the error happens after printing the last actual line in his file. From Ron.Barak at lsi.com Thu Dec 25 10:21:13 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Thu, 25 Dec 2008 15:21:13 +0000 Subject: Question withdrawn: seek() returns unexpected results References: Message-ID: <7F0503CD69378F49BE0DC30661C6CCF60249470B@enbmail01.lsi.com> Hi, Problem solved when strip() is being replaced by strip('\n'). Happy holidays, Ron. ________________________________ From: Barak, Ron Sent: Thursday, December 25, 2008 15:05 To: 'python-list at python.org' Subject: seek() returns unexpected results Hi, When using seek() with a certain text file, I get strange results. I looked at the text file with a binary editor and verified with 'file', and it's an ASCII English text file. Running the script on other text files gives the expected output. Could you suggest the reason ? In the outputs below, when using generator.py as input for generator.py the 'diff' is a nice progression as expected. ('diff' is the difference between the file pointer location and the number of characters read up to now). However, when using sac.log as input for generator.py the 'diff' is a strange series: 1, 2, 1, 2, 3, 4, 5, 6 Running generator.py on a bigger portion of sac.log produces these 'diff's: 1, 2, 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, 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, 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, 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, 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, 32, 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, 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, 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, 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, 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, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 Thanks, Ron. ________________________________ $ cat -n generator.py 1 #!/usr/bin/env python 2 3 import gzip 4 import sys 5 from Debug import _line as line 6 7 class LogStream(): 8 9 def __init__(self, filename): 10 self.filename = filename 11 self.input_file = self.open_file(filename) 12 13 def open_file(self, in_file): 14 try: 15 f = gzip.GzipFile(in_file, "r") 16 f.readline() 17 except IOError: 18 f = open(in_file, "r") 19 f.readline() 20 f.seek(0) 21 return(f) 22 23 def line_generator(self): 24 while True: 25 line_ = self.input_file.readline() 26 print line()+". line_==|"+line_.strip()+"|" 27 self.total_chars += len(line_) 28 print line()+". line length:",len(line_),"; file pointer:",self.input_file.tell(), 29 print "; total chars:",self.total_chars,"; diff:",self.input_file.tell() - self.total_chars 30 if not line_: 31 break 32 yield line_.strip() 33 34 35 if __name__ == "__main__": 36 37 filename = sys.argv[1] 38 log_stream = LogStream(filename) 39 log_stream.input_file.seek(0) 40 log_stream.total_chars = 0 41 line_generator = log_stream.line_generator() 42 for i in range(8): 43 line_ = line_generator.next() $ python generator.py generator.py 26. line_==|#!/usr/bin/env python| 28. line length: 22 ; file pointer: 23 ; total chars: 22 ; diff: 1 26. line_==|| 28. line length: 1 ; file pointer: 25 ; total chars: 23 ; diff: 2 26. line_==|import gzip| 28. line length: 12 ; file pointer: 38 ; total chars: 35 ; diff: 3 26. line_==|import sys| 28. line length: 11 ; file pointer: 50 ; total chars: 46 ; diff: 4 26. line_==|from Debug import _line as line| 28. line length: 32 ; file pointer: 83 ; total chars: 78 ; diff: 5 26. line_==|| 28. line length: 1 ; file pointer: 85 ; total chars: 79 ; diff: 6 26. line_==|class LogStream():| 28. line length: 19 ; file pointer: 105 ; total chars: 98 ; diff: 7 26. line_==|| 28. line length: 5 ; file pointer: 111 ; total chars: 103 ; diff: 8 $ python generator.py sac.log 26. line_==|Dec 15 15:45:20 iSW-00-090 svm_sac[1714]: AGENT[0]: [tv_expand ] tv_expand:........[Domain 5:DVol1_3CG1-MM-1229347528T0] maxVolCapacityMB:....[5121] tempVolCapacityMB:...[512] fivePercentMB:.......[256] expandedTempVolCap:..[1024]| 28. line length: 246 ; file pointer: 247 ; total chars: 246 ; diff: 1 26. line_==|Dec 15 15:45:20 iSW-00-090 svm_sac[1714]: AGENT[0]: [daemon_send_expand_reque] [Domain 5:DVol1_3CG1-MM-1229347528T0]: Add expand request up to 1024 MB (2097152 sectors)| 28. line length: 170 ; file pointer: 418 ; total chars: 416 ; diff: 2 26. line_==|Dec 15 15:45:20 iSW-00-090 svm_sac[1746]: AGENT[0]: [domain_expand_exec ] [Domain 5:DVol1_3CG1-MM-1229347528T0]: Send expand up to 1024 MB (2097152 sectors): success| 28. line length: 172 ; file pointer: 589 ; total chars: 588 ; diff: 1 26. line_==|Dec 15 15:45:21 iSW-00-090 svm_sac[1744]: AGENT[0]: [domain_poll ] Domain [Domain 5]: SVM reported volume manager setup changed| 28. line length: 141 ; file pointer: 731 ; total chars: 729 ; diff: 2 26. line_==|Dec 15 15:45:21 iSW-00-090 svm_sac[1744]: AGENT[0]: [domain_poll ] Domain [Domain 5]: SVM reported multiview setup changed| 28. line length: 136 ; file pointer: 868 ; total chars: 865 ; diff: 3 26. line_==|Dec 15 15:45:21 iSW-00-090 svm_sac[1744]: AGENT[0]: [domain_is_setup_changed ] Domain [Domain 5]: Setup CHANGED| 28. line length: 113 ; file pointer: 982 ; total chars: 978 ; diff: 4 26. line_==|Dec 15 15:45:21 iSW-00-090 svm_sac[1744]: AGENT[0]: [domain_get_pages ] Domain [Domain 5]: Asked to get setup pages| 28. line length: 124 ; file pointer: 1107 ; total chars: 1102 ; diff: 5 26. line_==|Dec 15 15:45:21 iSW-00-090 svm_sac[1744]: AGENT[0]: [svm_get_pages ] SVM [Domain 5:12345]: got all setup pages| 28. line length: 122 ; file pointer: 1230 ; total chars: 1224 ; diff: 6 $ cat generator.py #!/usr/bin/env python import gzip import sys from Debug import _line as line class LogStream(): def __init__(self, filename): self.filename = filename self.input_file = self.open_file(filename) def open_file(self, in_file): try: f = gzip.GzipFile(in_file, "r") f.readline() except IOError: f = open(in_file, "r") f.readline() f.seek(0) return(f) def line_generator(self): while True: line_ = self.input_file.readline() print line()+". line_==|"+line_.strip()+"|" self.total_chars += len(line_) print line()+". line length:",len(line_),"; file pointer:",self.input_file.tell(), print "; total chars:",self.total_chars,"; diff:",self.input_file.tell() - self.total_chars if not line_: break yield line_.strip() if __name__ == "__main__": filename = sys.argv[1] log_stream = LogStream(filename) log_stream.input_file.seek(0) log_stream.total_chars = 0 line_generator = log_stream.line_generator() for i in range(8): line_ = line_generator.next() -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Sat Dec 6 17:56:33 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sat, 6 Dec 2008 17:56:33 -0500 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: On Sat, Dec 6, 2008 at 4:51 PM, Daniel Fetchinson wrote: > >> Hi folks, > >> > >> The story of the explicit self in method definitions has been > >> discussed to death and we all know it will stay. However, Guido > >> himself acknowledged that an alternative syntax makes perfect sense > >> and having both (old and new) in a future version of python is a > >> possibility since it maintains backward compatibility. The alternative > >> syntax will be syntactic sugar for the old one. This blog post of his > >> is what I'm talking about: > >> > >> > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html > >> > >> The proposal is to allow this: > >> > >> class C: > >> def self.method( arg ): > >> self.value = arg > >> return self.value > >> > >> instead of this: > >> > >> class C: > >> def method( self, arg ): > >> self.value = arg > >> return self.value > >> > >> I.e. explicit self stays only the syntax is slightly different and may > >> seem attractive to some. As pointed out by Guido classmethods would > >> work similarly: > >> > >> class C: > >> @classmethod > >> def cls.method( arg ): > >> cls.val = arg > >> return cls.val > >> > >> The fact that Guido says, > >> > >> "Now, I'm not saying that I like this better than the status quo. But > >> I like it a lot better than [...] but it has the great advantage that > >> it is backward compatible, and can be evolved into a PEP with a > >> reference implementation without too much effort." > >> > >> shows that the proposal is viable. > >> > >> I'd like this new way of defining methods, what do you guys think? > >> Anyone ready for writing a PEP? > >> > > What's the advantage? If there is not a good reason, I would strongly > > opposed polluting the language. > > Did you read the blog post? The advantage is having a less confusing > situation for newbies (confusing the number of arguments to a method > call). > 2 points about this: 1) You'd confuse newbies about the fact that self.foo() is just syntax sugar for cls.foo(self). The problem with newbies getting argument numbers still exists, just in the other case. This could also get confusing when you call methods for the super class class Foo : def self.bar() : ... class OtherFoo(Foo) ; def self.bar() : ... b = OtherFoo() cls = Foo cls.bar(b) 2) You'd have to allow this at the module level too (or else it violates the special cases part of the Zen). That would really confuse newbies. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rameshj at adventnet.com Fri Dec 12 05:37:26 2008 From: rameshj at adventnet.com (J Ramesh Kumar) Date: Fri, 12 Dec 2008 16:07:26 +0530 Subject: Interface & Implementation Message-ID: <11e2ac5b5eb.2364397661727502391.6806593866408074890@adventnet.com> Hi, I am new to python. I require some help on implementing interface and its implementation. I could not find any sample code in the web. Can you please send me some sample code which is similar to the below java code ? Thanks in advance for your help. ............ public interface MyIfc { public void myMeth1(); public void myMeth2(); } .... public class MyClass implements MyIfc { public void myMeth1() { //do some implementation } public void myMeth2() { //do some implementation } } ... MyClass myc=new MyClass(); Hashtable hash=new Hashtable(); hash.put("MYIFC",myc); ........ MyIfc myi=(MyIfc)hash.get("MYIFC"); myi.myMeth1(); myi.myMeth2(); ......... Thanks, Ramesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at microcorp.co.za Wed Dec 3 23:40:02 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 4 Dec 2008 06:40:02 +0200 Subject: Please fix your clock [was Re: Multiple equates] References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> <0147f4b7$0$20670$c3e8da3@news.astraweb.com> <20081204170017.4be41c7f@usenot.de> Message-ID: <002401c955ca$5fd63b80$0d00a8c0@hendrik> "Andreas Waldenburger" > On 04 Dec 2008 15:53:21 GMT Steven D'Aprano > wrote: > > > Hendrik, I think your PC's clock is wrong. You seem to be posting > > from the future. > > So? Maybe he is. What's your problem? It was probably playing hob with his threading reader... - Hendrik From gagsl-py2 at yahoo.com.ar Thu Dec 11 20:39:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 11 Dec 2008 23:39:28 -0200 Subject: Converting c header file to a python file References: Message-ID: En Thu, 11 Dec 2008 10:28:21 -0200, tarun escribi?: > I am looking for a tool/utility by which can convert c header file to a > python file. A typical header file that I want convert looks like: Locate h2py.py somewhere in your Python distribution. From the comments: # Read #define's and translate to Python code. # Handle #include statements. # Handle #define macros with one argument. # Anything that isn't recognized or doesn't translate into valid # Python is ignored. (doesn't convert *all* you want, but it's a start) -- Gabriel Genellina From BrianVanderburg2 at aim.com Tue Dec 9 06:31:12 2008 From: BrianVanderburg2 at aim.com (Brian Allen Vanderburg II) Date: Tue, 09 Dec 2008 06:31:12 -0500 Subject: How to initialize a class variable once In-Reply-To: References: Message-ID: <493E5700.4030107@aim.com> mccredie at gmail.com wrote: > > Unless you are calling reload() on the module, it will only ever get > _loaded_ once. Each additional import will just yield the existing > module. Perhaps if you post an example of the behavior that leads you > to believe that the class variables are getting reinitialized I can > provide more useful help. > > Matt > -- > http://mail.python.org/mailman/listinfo/python-list > There is one situation where a module can be imported/executed twice, if it is the __main__ module. Obviously the example below would be considered bad Python practice but it just shows how it can be done: main.py: class Blah(object): def action(self): print "action" print "import" if __name__ == "__main__": import app app.run() app.py: def run(): import main blah = main.Blah() blah.action() python main.py: import import action The reason is the first time main.py gets loaded, it is known as '__main__' but when app imports main, it is not in sys.modules so it loads 'main.py' again but this time as 'main' Brian Vanderburg II -------------- next part -------------- An HTML attachment was scrubbed... URL: From fakeaddress at nowhere.org Tue Dec 23 00:13:01 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 22 Dec 2008 21:13:01 -0800 Subject: Event Driven programming - Doubts In-Reply-To: <80f360e4-2880-4c66-a6b4-e05d6dbc9031@b41g2000pra.googlegroups.com> References: <80f360e4-2880-4c66-a6b4-e05d6dbc9031@b41g2000pra.googlegroups.com> Message-ID: Kottiyath wrote: > [...] I have not yet understood the implementation of > deferred. I went through a lot of tutorials, but I guess most places > they expect that the user already understands how events are > generated. The tutorials mention that there is no more threads once > twisted is used. > > My question is as follows: > I have not understood how the callbacks are hit without (a) > blocking the code or (b) having new threads. > > The usual example given is that of a program waiting for data coming > through a socket. In the tutorials, it is mentioned that -in an event > driven program, we schedule the code to hit when the remote server > gets back to us - . > Now, my question is - somebody has to still wait on that socket and > check whether the data is received, and once all the data is received, > call the appropriate callbacks. > > Is twisted creating a micro-thread which just waits on the socket and > once the data is received, calls callFromThread for it to run on the > main loop? No. Event-driven frameworks are built upon some system call that waits for events from multiple sources at once. The Python standard library exposes several such calls, the most portable of which is select(), in the module also named "select". http://docs.python.org/library/select.html So how is something like deferred implemented? When you schedule action on your socket, you are telling the framework to include your socket in in subsequent calls to select(), until the socket selects as ready. The framework keeps a single global list of sockets on which clients are waiting, and from this list it builds the select() parameters. A single call to select() waits on behalf of all the callbacks. The select() call returns a list of sockets ready for I/0; the framework iterates over the ready list, invoking the corresponding callbacks one by one. After the last callback returns, the framework loops back to select() again. select() is not the only call to do multi-source I/O, and I'm not an expert on these frameworks, so take the above as a simplified general description. -- --Bryan From prologic at shortcircuit.net.au Wed Dec 3 20:16:37 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 4 Dec 2008 11:16:37 +1000 Subject: Don't you just love writing this sort of thing :) In-Reply-To: References: Message-ID: uggh no! On Thu, Dec 4, 2008 at 11:07 AM, Lawrence D'Oliveiro wrote: > for \ > Entry \ > in \ > sorted \ > ( > f for f in os.listdir(PatchesDir) if PatchDatePat.search(f) != None > ) \ > : > Patch = (open, gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir, Entry), "r") > ... read from Patch ... > Patch.close() > #end for > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From lotro8520963 at gmail.com Mon Dec 8 21:27:14 2008 From: lotro8520963 at gmail.com (www.lotro-shop.com) Date: Mon, 8 Dec 2008 18:27:14 -0800 (PST) Subject: sell lotro gold ,This is the professional Lotro gold shop,come on!www.lotro-shop.com Message-ID: <7c248b60-6462-44fb-ab93-c6868749a0e2@r37g2000prr.googlegroups.com> In The Lord of the Rings OnlineTM: Shadows of AngmarTM (LOTRO), players can customize certain elements of the game's user interface (UI), also known as "skinning." While we don't allow you to do a full- scale UI replacement, we do give you the ability to replace selected visual elements of the UI. (A full list of these elements and their sizes is provided at the end of this overview.) This is an updated (and prettied up) version of the information that had originally been posted in their Beta forums which we had copied to our Developer Discussions - Tutorials & Other Helpful Information forum. It is a combination of the Skinning the LOTRO UI and Art Assets posts. http://www.lotro-shop.com http://www.aocgolds.net/ From tjreedy at udel.edu Fri Dec 5 12:55:53 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 05 Dec 2008 12:55:53 -0500 Subject: dict subclass and pickle bug (?) In-Reply-To: <6J7_k.6212$hc1.5967@flpi150.ffdc.sbc.com> References: <6J7_k.6212$hc1.5967@flpi150.ffdc.sbc.com> Message-ID: James Stroud wrote: > James Stroud wrote: >> Hello All, >> >> I subclassed dict and overrode __setitem__. When instances are >> unpickled, the __setstate__ is not called before the keys are assigned >> via __setitem__ in the unpickling protocol. >> >> I googled a bit and found that this a bug filed in 2003: It is an 'issue' reporting a possibly unexpected side-effect of protocol working as designed and documented. Possibly a design flaw, but not a bug in the narrow sense (in spite of the url of the issue tracker). >> http://bugs.python.org/issue826897 >> >> It is still "open" with "normal" priority. > > Here is the ugly "fix" I'm basically going to have to live with, it seems: > > class DictPlus(dict): > def __init__(self, *args, **kwargs): > self.extra_thing = ExtraThingClass() > dict.__init__(self, *args, **kwargs) > def __setitem__(self, k, v): > try: > do_something_with(self.extra_thing, k, v) > except AttributeError: > self.extra_thing = ExtraThingClass() > do_something_with(self.extra_thing, k, v) > dict.__setitem__(self, k, v) > def __setstate__(self, adict): > pass I took the liberty of adding this to the issue. > I can't imagine this bug has survived because there is no bug to fix. I have suggesting closing. Terry Jan Reedy From duncan.booth at invalid.invalid Mon Dec 22 03:59:13 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Dec 2008 08:59:13 GMT Subject: Are python objects thread-safe? References: Message-ID: RajNewbie wrote: > Say, I have two threads, updating the same dictionary object - but for > different parameters: > Please find an example below: > a = {file1Data : '', > file2Data : ''} > > Now, I send it to two different threads, both of which are looping > infinitely: > In thread1: > a['file1Data'] = open(filename1).read > and > in thread2: > a['file2Data'] = open(filename2).read > > My question is - is this object threadsafe? - since we are working on > two different parameters in the object. Or should I have to block the > whole object? > It depends exactly what you mean by 'threadsafe'. The GIL will guarantee that you can't screw up Python's internal data structures: so your dictionary always remains a valid dictionary rather than a pile of bits. However, when you dig a bit deeper, it makes very few guarantees at the Python level. Individual bytecode instructions are not guaranteed atomic: for example, any assignment (including setting a new value into the dictionary) could overwrite an existing value and the value which is overwritten may have a destructor written in Python. If that happens you can get context switches within the assignment. Other nasty things can happen if you use dictionaries from multiple threads. You cannot add or remove a dictionary key while iterating over a dictionary. This isn't normally a big issue, but as soon as you try to share the dictionary between threads you'll have to be careful never to iterate through it. You will probably find it less error prone in the long run if you get your threads to write (key,value) tuples into a queue which the consuming thread can read and use to update the dictionary. -- Duncan Booth http://kupuguy.blogspot.com From sjdevnull at yahoo.com Mon Dec 1 18:57:17 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Mon, 1 Dec 2008 15:57:17 -0800 (PST) Subject: Emacs vs. Eclipse vs. Vim References: Message-ID: <27757214-df90-4a33-8f44-65673c9ababd@20g2000yqt.googlegroups.com> On Nov 29, 3:44?pm, Josh wrote: > If you were a beginning programmer and willing to make an investment in > steep learning curve for best returns down the road, which would you pick? > > I know this topic has been smashed around a bit already, but 'learning > curve' always seems to be an arguement. If you feel that one is easier > or harder than the others to learn feel free to tell, but let's not make > that the deciding factor. Which one will be most empowering down the > road as a development tool? I'd strongly recommend not using an IDE but going with federated tools; this makes it easier to pick the editor, code navigation tool, build system, etc that you like best, and makes it easier to swap out one piece at a time if you don't like it. So of the choices mentioned, I'd go with emacs or vim if I were you. Personally I also find high value in picking an editor that can be run on a command-line terminal connection (e.g. when you're ssh'd into a remote server), but that may be less important depending on what sort of development you are doing. From rhamph at gmail.com Sun Dec 14 03:46:01 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Sun, 14 Dec 2008 00:46:01 -0800 (PST) Subject: __future__ and compile: unrecognised flags References: <20081213112917.6209.qmail@s461.sureserver.com> Message-ID: <1ef4c02f-9dac-4e06-8f45-eae839944425@d42g2000prb.googlegroups.com> On Dec 13, 6:03?am, Steve Holden wrote: > Poor Yorick wrote: > > I have a future statement in a script which is intended to work in 2.6 and 3. > > Shouldn't compile flags in __future__ objects essentially be noops for versions > > that already support the feature? doctest is complaining about unrecognised > > flags. ?This illustrates the problem: > > > ? ? Python 3.0 (r30:67507, Dec ?3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win > > ? ? 32 > > ? ? Type "help", "copyright", "credits" or "license" for more information. > > ? ? >>> from __future__ import unicode_literals > > ? ? >>> src = 'a = "hello"' > > ? ? >>> c1 = compile(src,'','exec',unicode_literals.compiler_flag) > > ? ? Traceback (most recent call last): > > ? ? ? File "", line 1, in > > ? ? ValueError: compile(): unrecognised flags > > This could arguably be classed as a bug given that the 2.6 documentation > for __future__ says "No feature description will ever be deleted from > __future__." However I suspect that the feature has been removed because > all string literals are Unicode in 3.0 and up, and 3.0 is allowed to > break compatibility. I don't think the rule about __future__ applies to compile(). From arnodel at googlemail.com Mon Dec 1 17:08:05 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 01 Dec 2008 22:08:05 +0000 Subject: optimization References: Message-ID: Neal Becker writes: > I noticed in some profiling, that it seems that: > > def Func (): > def something(): > ... > > It appears that if Func is called many times, this nested func > definition will cause significant overhead. Is this true? I guess > I've become accustomed to decent compilers performing reasonable > transformations and so have tended to write code for clarity. If something() can be defined outside Func(), how is it clearer to define it inside? -- Arnaud From castironpi at gmail.com Sat Dec 27 19:06:23 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 27 Dec 2008 16:06:23 -0800 (PST) Subject: ctypes & strings References: <334452.47084.qm@web30003.mail.mud.yahoo.com> <000f01c96822$5c300f00$0d00a8c0@hendrik> Message-ID: <23bb633f-494a-4390-9158-15ee0f1967e5@l33g2000pri.googlegroups.com> On Dec 27, 2:03?pm, "Gabriel Genellina" wrote: > En Sat, 27 Dec 2008 10:54:32 -0200, Hendrik van Rooyen ? > escribi?: > > > The c routine will actually break Python's normal string > > immmutability and give you back a changed ins. > > ...so don't do that! > If you require a mutable string to pass to C functions, use ? > ctypes.create_string_buffer() > > > It is in general not a good idea to change the passed string > > like I am doing - but you wanted to know how > > to pass a python string, and the outs example should get > > you going - a string is an array of characters in c... > > Hmmm, I don't think posting a potentially harmful example is actually a ? > good idea... > > -- > Gabriel Genellina One alternative would be to return a pair of Python strings. You might want to wrap the C function you have already in another one, which allocates buffers and creates Python objects. Hendrik is right, though. The ctypes module allows us to break string immutability within Python code. From BrianVanderburg2 at aim.com Sun Dec 7 10:31:21 2008 From: BrianVanderburg2 at aim.com (Brian Allen Vanderburg II) Date: Sun, 07 Dec 2008 10:31:21 -0500 Subject: Python idea/proposal to assist in single-archive python applications Message-ID: <493BEC49.2000500@aim.com> Python Community The following is just an idea that I considered that may be helpful in creating an application in a single archive easier and with less code. Such an application would be similar to jar files for Java. First, the application and all data files should be able to run either extracted or zipped up into an archive. When running an application as part of an archive, the first step Python would do would be to insert that archive into sys.path, and then load the internal file of the same name as the __main__ module. This zip file: myapp.zip | |-- myapp.py |-- myapp.pyc (optional) |-- application/ (main application package) |-- pixmaps/ |-- ... Could be run as something like: python --par myapp.zip In addition it is needed to be able to open a file just as easily whether that file is in the archive or not. Assuming that a datafile in an application may be located relative to the '__file__' attributes, the following will not work in an archive: file = open(os.path.join(os.path.dirname('__file__'), '..', 'pixmaps', 'splash.png')) However, a simple function, perhaps built-in, could be provided which would work for reading either internal files or regular files. That is, the function would be able to open a file '/path/to/file', and it would also be able to open a file '/path/to/zipfile.zip/internal/file'. If built in the function could also take advantage of the open modes 'rb', 'rt' and 'rU'. Currently this is not so easy. First it would require the user writing a function to be able to open a file internally and externally just as easily, using zipfile and StringIO for any internal files. Secondly, opening a file in such a way only allows binary opens, it can't take advantage of pythons 'rU' open mode if the application so needs. Also, it still requires an external startup script to set the path and import the internal module. If this function was provided in Python, then and application could fairly easily run just as well zipped up as they would unzipped. Brian Vanderburg II From roy at panix.com Sat Dec 6 13:30:13 2008 From: roy at panix.com (Roy Smith) Date: Sat, 06 Dec 2008 13:30:13 -0500 Subject: Learning Python now coming from Perl References: Message-ID: In article , aahz at pythoncraft.com (Aahz) wrote: > In article , > Bertilo Wennergren wrote: > > > >I don't suppose there is any introductory material out there that is > >based on Python 3000 and that is also geared at people with a Perl > >background? Too early for that I guess.. > > Honestly, the differences between 2.x and 3.0 are small enough that it > doesn't much matter, as long as you're not the kind of person who gets > put off by little problems. Because so much material is for 2.x, you > may be better off just learning 2.x first and then moving to 3.x. I'm not sure I agree. If you're starting out, you might as well learn the new stuff. Then there's no need to unlearn the old way. Using material meant for 2.x is likely to lead to confusion. If you don't know either, you'll never know if something isn't working as described because you're doing it wrong or if it's just not the same as it used to be. When everything is new, what seem like little stumbling blocks to experts become total blockers to people starting from zero. From lie.1296 at gmail.com Fri Dec 12 15:44:55 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 12 Dec 2008 20:44:55 +0000 (UTC) Subject: (Very Newbie) Problems defining a variable References: <49425146$0$8495$426a74cc@news.free.fr> <11c53a4a-de1e-4bee-ad60-a05befb6cbf4@a12g2000yqm.googlegroups.com> <7cb69ff5-9034-41cc-b667-d69329707b18@d36g2000prf.googlegroups.com> Message-ID: On Fri, 12 Dec 2008 04:58:36 -0800, feba wrote: > Actually, I have gedit set to four spaces per tab. I have no reason why > it's showing up that large on copy/paste, but the file itself is fine. You've set gedit to _show tabs_ as four spaces, but not to substitute tabs with four spaces. Go to gedit's preference where you change how many spaces is used to display tabs, right below it is "Insert spaces instead of tabs". From mail at johnohagan.com Sun Dec 14 22:32:08 2008 From: mail at johnohagan.com (John O'Hagan) Date: Mon, 15 Dec 2008 03:32:08 +0000 Subject: Python music sequencer timing problems In-Reply-To: <49451835$0$17068$6e1ede2f@read.cnntp.org> References: <3b52b652-df61-4eb4-bcff-0d1fb6f20891@r15g2000prh.googlegroups.com> <49451835$0$17068$6e1ede2f@read.cnntp.org> Message-ID: <200812150332.08748.mail@johnohagan.com> On Sun, 14 Dec 2008, Bad Mutha Hubbard wrote: > John O'Hagan wrote: > > On Wed, 10 Dec 2008, badmuthahubbard wrote: [...] > > from time import time, sleep > > > > start = time() > > for event in music: > > duration=len(event) #Really, the length of the event > > play(event) > > while 1: > > timer = time() > > remaining = start + duration - timer > > if remaining < 0.001: > > break > > else: > > sleep(remaining / 2) > > stop(event) > > start += duration > > > Very interesting approach, halving the remaining duration. Right now > I'm not working with note-offs, Csound takes care of the duration. I > just need to be able to call the notes at the right times. [...] I'm also using the above code without the "stop(event)" line for playing non-midi stuff (fixed-length samples for example), which from the sound of it also applies to your requirement - IOW, you _can_ use it just to start notes at the right time, because the note-playing loop sleeps till then. [...] > I also like and respect Fluidsynth, but I'm working on a pretty > microtonal system, and MIDI doesn't have enough microtonal support. > [...] I'm certainly not trying to convert you to Fluidsynth - I'm more likely to convert to Csound - but just for the record, you can do microtonal stuff fairly easily using Fluidsynth's "settuning" command. In my program I can use any equal-tempered division of the octave by preceding each set of events which require it with this: mesg = [ "select " + channel + " " + font + " " + bank+ " " + program + " \ntuning name 0 " + program + "\n"] for key in xrange(128): pitch = str((((key - 60) * 12.0 / divisor) + 60) * 100) mesg.append( "tune " + bank + " " + program + " " + str(key) + " " + pitch + "\n") mesg.append("settuning " + channel + " " + bank " " + program + "\n") mesg = ''.join(mesg) fluidsynth_socket.send(mesg) where "divisor" is the number you want to divide the octave by (the other names are self-descriptive). The reason for the "60"s in there is just to keep middle C where it is. For more complex/non-linear pitch-warping, the rest of the "pitch = " line could be replaced with any pitch-altering function taking "key" as an argument; but I haven't tried that yet. I'd be interested to hear about the microtonal system(s) you're using. Regards, John From skip at pobox.com Sat Dec 13 10:40:31 2008 From: skip at pobox.com (skip at pobox.com) Date: Sat, 13 Dec 2008 09:40:31 -0600 Subject: Why %e not in time.strftime directives? In-Reply-To: <38f9c4ba-d96d-47e1-b718-562bdc6718e9@t26g2000prh.googlegroups.com> References: <38f9c4ba-d96d-47e1-b718-562bdc6718e9@t26g2000prh.googlegroups.com> Message-ID: <18755.55151.493185.235108@montanaro-dyndns-org.local> Leo> Any special reasons? Nobody thought to add it? Got a patch? -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From pdorange at pas-de-pub-merci.mac.com Tue Dec 23 08:36:53 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Tue, 23 Dec 2008 14:36:53 +0100 Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> <1iscu14.oixxplpgajabN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <1isenn3.1g8fxa21aqzibkN%pdorange@pas-de-pub-merci.mac.com> Steven D'Aprano wrote: > But this is just duplicating what timeit already does. Trust me, learn to > use it, you won't be sorry. Here's a trick that took me a long time to > learn: instead of copying your functions into the setup code of timeit, > you can just import them. Thanks for the advise, i made the test using timeit and your very interesting method to import... Now i know how to use timeit simply ;-) New results on 1000 float values randomized from -500.0 to +500.0. Each test is timeit(1000) sign_0 : 0.375 sign_1 : 0.444 (+18%) sign_2 : 0.661 (+76%) sign_3 : 0.498 (+33%) It seems it don't change the relative results between the methods. Using timeit make measure accurate and remove print/range footprints. I also try Arnaud's proposition, it make sign_0 just a little better (-1%) -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From rt8396 at gmail.com Mon Dec 22 18:24:34 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 15:24:34 -0800 (PST) Subject: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> Message-ID: <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> You know what i hate more than a troll, a spineless jellyfish who goes around rating peoples post with one star. You are the lowest form of life. You are the same type of person who would key someones car in the parking lot. You do not have the balls to face you enemy. If who made a rating were visible, then i would have respect for you, but since you lurk in the shadows, you are scum. Come out and face me if you dare! I never have rated a post UNLESS i rate it with 5 stars, WHY, you ask, Because my balls are so big i walk around bow-legged! F'in Cowards! From clp at rebertia.com Wed Dec 17 19:06:35 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 17 Dec 2008 16:06:35 -0800 Subject: The rule of literal string In-Reply-To: <6f1677a9-1127-4e69-b536-d82e123324b1@z27g2000prd.googlegroups.com> References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> <_PmdnU59w62vGtTUnZ2dnUVZ_hSdnZ2d@pdx.net> <34028b73-7807-4e88-80bc-fe31a7b1a2a0@i20g2000prf.googlegroups.com> <6f1677a9-1127-4e69-b536-d82e123324b1@z27g2000prd.googlegroups.com> Message-ID: <47c890dc0812171606n18196cb9g5fdb8b7921cacd5c@mail.gmail.com> On Wed, Dec 17, 2008 at 3:52 PM, Li Han wrote: > Chris worte: > [snip] >> And repr("''") ==> "\"''\"" >> Which when print()-ed is: "''" >> And eval("''") is the same as entering two apostrophes ('') at the >> REPL, both of which give an empty string object. > > On my machine: >>>> repr("''") > '"\'\'"' > Han Well, I was kinda winging it and didn't actually use the interpreter for some of those. The point is that the output I gave _could_ reasonably be that of the interpreter (if the implementation details of repr() were slightly different; it would still meet the spec anyway) and illustrates the eval()-repr() relationship. Just keep in mind the equivalence rule and what repr() does should become obvious. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From geekmail at usenot.de Sat Dec 6 18:23:07 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sun, 7 Dec 2008 00:23:07 +0100 Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> Message-ID: <20081207002307.5d30f195@usenot.de> On Sat, 6 Dec 2008 14:39:34 -0800 (PST) "Russ P." wrote: > I don't know much about Perl, but my understanding is that a dollar > sign must be used every time a variable is dereferenced, as in bash or > other shell languages. What we are proposing here is something > entirely different: the dollar sign would simply be a shorthand for > "self". In Perl, the dollar sign is clutter, but in this case it > actually reduces clutter. > This is the weirdest thing. Not a month seems to go by that this old hat isn't dug up again. You're fighting windmills. Why do you think self has been around so long? Because it's the best choice? No, because it works and there just is no need to change it (where "need" is defined by the desires of the majority). Getting the Python comunity to replace self with something shorter will never compensate for the time you spent bullying it through. I'd much rather spend time coding than complaining, but that might be just me. (BTW: I have my editor set up so that "s" is expanded to "self" and "." is expanded to "self."; I virtually lose no time at all with self and would gain nothing from a change to it. And regarding line-lengths: My code lines tend to be shorter than my comments explaining them, but that may again be just me. Excuse my being stubborn. :) /W -- My real email address is constructed by swapping the domain with the recipient (local part). From gubatron at gmail.com Wed Dec 3 06:31:13 2008 From: gubatron at gmail.com (Gubatron) Date: Wed, 3 Dec 2008 03:31:13 -0800 (PST) Subject: Jython: Packing several .py on .jar, problem importing .py modules within the .jar Message-ID: Hello all, I've a problem with Jython and importing .py inside a jar. I'm putting .class and .py files inside .jar files. myjar.jar MyJar\SomeClass.class MyJar\main.py MyJar\otherModule.py So I add the myjar.jar to Jython's sys.path org.python.core.PySystemState pySys = new org.python.core.PySystemState(); pySys.path.insert(0,new PyString("/path/to/myjar.jar")); and execute main.py //We pass the PythonInterpreter the modified PySystemState PythonInterpreter i = new PythonInterpreter(null, pySys); //Find the entry in the jar for the python file and execute it. //It should be able to find any resource inside the jar. JarFile jFile = new JarFile("/path/to/myjar.jar"); ZipEntry zipEntry = jFile.getEntry("MyJar/main.py"); InputStream pythonInputStream = jFile.getInputStream(zipEntry); i.execfile(pythonInputStream); main.py will execute fine, it'll be able to do from MyJar import SomeClass with no problem However, If I try to import the other .py in the same jar, it won't find it: from otherModule import * or from MyJar.otherModule import * I always get this: ImportError: no module named otherModule at org.python.core.Py.ImportError(Unknown Source) at org.python.core.imp.import_first(Unknown Source) at org.python.core.imp.import_name(Unknown Source) at org.python.core.imp.importName(Unknown Source) at org.python.core.ImportFunction.load(Unknown Source) at org.python.core.ImportFunction.__call__(Unknown Source) at org.python.core.PyObject.__call__(Unknown Source) at org.python.core.__builtin__.__import__(Unknown Source) at org.python.core.imp.importFromAs(Unknown Source) at org.python.core.imp.importFrom(Unknown Source) at org.python.pycode._pyx1.f$0(:26) at org.python.pycode._pyx1.call_function() at org.python.core.PyTableCode.call(Unknown Source) at org.python.core.PyCode.call(Unknown Source) at org.python.core.Py.runCode(Unknown Source) at org.python.util.PythonInterpreter.execfile(Unknown Source) I've tried adding more paths to sys.path, with no luck: pySys.path.insert(0,new PyString("/path/to/myjar.jar/MyJar")); pySys.path.insert(0,new PyString("file:jar:/path/to/myjar.jar!")); and nothing works, any ideas would help. I know this has to work, because I previously had a problem where I couldn't do import os and then I added the "Lib/" folder inside jython.jar and now I'm able to import all those standard jython modules, so, somehow, jython is able to import .py within a .jar, help would be very much appreciated. Angel Leon From fetchinson at googlemail.com Sat Dec 6 16:50:34 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 6 Dec 2008 13:50:34 -0800 Subject: Guido's new method definition idea In-Reply-To: <50bbef6f-02e3-47d8-810c-179b89ccf62a@d32g2000yqe.googlegroups.com> References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> <20081206133704.1bed455c@usenot.de> <4d1a952e-25ad-4b36-ba46-ed35758331b0@e1g2000pra.googlegroups.com> <50bbef6f-02e3-47d8-810c-179b89ccf62a@d32g2000yqe.googlegroups.com> Message-ID: > Bad idea having two ways to do this. Pick one or the other! Maybe only this alternative syntax for python 4000? -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From lie.1296 at gmail.com Tue Dec 9 16:28:37 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 9 Dec 2008 21:28:37 +0000 (UTC) Subject: Guido's new method definition idea References: <014a071a$0$20670$c3e8da3@news.astraweb.com> <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> Message-ID: On Mon, 08 Dec 2008 20:55:16 +0000, Arnaud Delobelle wrote: > anthony.tolle at gmail.com writes: > >> class C: >> def createfunc(self): >> def self.func(arg): >> return arg + 1 >> >> Or, after the class definition is done, to extend it dynamically: >> >> def C.method(self, arg): >> self.value = arg >> >> ...which would be the equivalent of the following: >> >> def method(self, arg): >> self.value = arg >> C.method = method > > What about the following then? > > functions = {} > > def functions['square'](x): > return x*x > > def functions['cube'](x): > return x**3 > > -- > Arnaud -1. In most cases, it would generally be better as: def functions(x): return x.func() since the rule-of-thumb of OOP is that objects should do things by itself. This is also more in line with python's built-in functions, which merely calls the appropriate __special__ names. and whenever creating an object is too complex, that could easily be def functions(which, x): def _function_square(): return x*x def _function_cube(): return x**3 d = {'square': _function_square, 'cube': _function_cube, } return d[which]() From rt8396 at gmail.com Sat Dec 13 21:57:55 2008 From: rt8396 at gmail.com (r) Date: Sat, 13 Dec 2008 18:57:55 -0800 (PST) Subject: 1 or 1/0 doesn't raise an exception References: Message-ID: These are just the kind of things that make Python so beautiful ;) Thanks Guido! From alexoplocatie at gmail.com Thu Dec 18 07:00:27 2008 From: alexoplocatie at gmail.com (aka) Date: Thu, 18 Dec 2008 04:00:27 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> <0d9ea7cc-b5fb-4edb-be32-490aae9e7204@b41g2000pra.googlegroups.com> <0de3a7bf-a4c4-4103-a4e0-44313405fa94@z28g2000prd.googlegroups.com> <23d6710f-2c6d-4115-817a-053b8e96f1ce@z28g2000prd.googlegroups.com> Message-ID: <06edd327-f40c-46e7-b1a3-fbe1847cdcb3@40g2000prx.googlegroups.com> On 18 dec, 00:06, John Machin wrote: - Tekst uit oorspronkelijk bericht niet weergeven - - Tekst uit oorspronkelijk bericht weergeven - > On Dec 18, 3:15 am, aka wrote: > Do you mean that this file was created by whatever.UnicodeWriter? If > so, did you just now discover this information? > How do you know that "the UnicodeWriter is functioning perfectly"? > What does "functioning perfectly mean to you"? In particular, what > encoding is it using? > Which do you mean: > (a) you typed those lines into Notepad yourself > (b) you took a copy of a file created by whatever.UnicodeWriter, > opened it with Notepad, trimmed off some rows and columns, and saved > it again > ? > Here's a likely hypothesis: the file was written in utf16. In that > case: > either (i) you really want utf16 (why?), so: > (1) the csv module will not cope with it, and is not expected to cope > with it > (2) the whatever.UnicodeReader should (in order of preference): > (a) be allowed to find out for itself that 'utf16' is the go > (b) be told explicitly that 'utf16' is the go > (c) be served with a bug report > OR (ii) you really want utf8, so: > (1) the csv module should be happy > (2) the whatever.UnicodeWriter should be told to use 'utf8' > (3) the whatever.UnicodeReader should (in order of preference): > [as above but s/16/8/] The csv file originally was created by the UnicodeWriter class and was used for a mailmerge function with Microsoft Word which all functioned perfectly. The reverse did not: read back the outputted file so at last I editted it in Notepad, cutting off columns, but I didn't know that the encoding would remain even after that because it still caused problems. Now after testing from the Python command line with a csv file generated from Excel I could get it working so it had to be the encoding. Because the write side of my code, which uses the UnicodeWriter, was ok I didn't pay attention to the fact that I had changed the UW class from UTF-8 to UTF-16 because of difficulties with dutch characters like ? and ?. Then at last I tried changing back to UTF-8 and noticed both out -and input was working, including those special characters, so it was my unjustifiable conclusion that I couldn't get around these special characters at the write side without UTF-16 which ultimately got me in trouble with the read side. With your help I got it straight. Once again minimizing the problem to its bare basics and to prevent big steps is the key. Thanks a lot for your help John. BTW, the TurboGears code is not very different from Python, it just uses some extra identifiers around the Python code. From paul.nospam at rudin.co.uk Mon Dec 1 01:32:24 2008 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Mon, 01 Dec 2008 06:32:24 +0000 Subject: Emacs vs. Eclipse vs. Vim References: Message-ID: <878wr08kxz.fsf@rudin.co.uk> Clay Hobbs writes: > It has key commands with key modifiers to do simple tasks (such as > moving the cursor to the left). Err - you move the cursor to the left by pressing the left arrow key (as you do with virtually every other editor), unless you've made some strange key bind customisations. From gagsl-py2 at yahoo.com.ar Mon Dec 29 00:32:04 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Dec 2008 03:32:04 -0200 Subject: Otra vez Python en xkcd Message-ID: Hola En el especial de Navidad de este a?o: http://xkcd.com/521/ -- Gabriel Genellina From robert.kern at gmail.com Sun Dec 7 21:21:18 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 07 Dec 2008 20:21:18 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: References: <014c593e$0$20670$c3e8da3@news.astraweb.com> Message-ID: James Stroud wrote: > Steven D'Aprano wrote: >> On Sun, 07 Dec 2008 13:57:54 -0800, James Stroud wrote: >> >>> Rasmus Fogh wrote: > >>>>>>> ll1 = [y,1] >>>>>>> y in ll1 >>>> True >>>>>>> ll2 = [1,y] >>>>>>> y in ll2 >>>> Traceback (most recent call last): >>>> File "", line 1, in >>>> ValueError: The truth value of an array with more than one element is >>>> ambiguous. Use a.any() or a.all() >>> I think you could be safe calling this a bug with numpy. >> >> Only in the sense that there are special cases where the array >> elements are all true, or all false, and numpy *could* safely return a >> bool. But special cases are not special enough to break the rules. >> Better for the numpy caller to write this: >> >> a.all() # or any() >> >> instead of: >> >> try: >> bool(a) >> except ValueError: >> a.all() >> >> as they would need to do if numpy sometimes returned a bool and >> sometimes raised an exception. > > I'm missing how a.all() solves the problem Rasmus describes, namely that > the order of a python *list* affects the results of containment tests by > numpy.array. E.g. "y in ll1" and "y in ll2" evaluate to different > results in his example. It still seems like a bug in numpy to me, even > if too much other stuff is broken if you fix it (in which case it > apparently becomes an "issue"). It's an issue, if anything, not a bug. There is no consistent implementation of bool(some_array) that works in all cases. numpy's predecessor Numeric used to implement this as returning True if at least one element was non-zero. This works well for bool(x!=y) (which is equivalent to (x!=y).any()) but does not work well for bool(x==y) (which should be (x==y).all()), but many people got confused and thought that bool(x==y) worked. When we made numpy, we decided to explicitly not allow bool(some_array) so that people will not write buggy code like this again. The deficiency is in the feature of rich comparisons, not numpy's implementation of it. __eq__() is allowed to return non-booleans; however, there are some parts of Python's implementation like list.__contains__() that still expect the return value of __eq__() to be meaningfully cast to a boolean. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From fakeaddress at nowhere.org Thu Dec 18 05:00:50 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 18 Dec 2008 02:00:50 -0800 Subject: socket and subprocess problem In-Reply-To: References: <6d3291c3-4e12-4bdd-884a-21f15f38d105@a12g2000pro.googlegroups.com> <73dca20d-3378-4c96-aa30-f0617f111fa0@i18g2000prf.googlegroups.com> Message-ID: James Mills wrote: > subprocess process: > > #1. When my subprocess process has successfully > started notify the parent. > #2. When my subprocess process has successfully > created a listening socket, notify the parent. > > parent process: > > #1. When our subprocess process has > successfully started a listening socket > initiate a connection. I'd swear James copied my response, except his came first. Even the formatting came out similar. I hadn't seen his response when I wrote mine, and wouldn't have bothered posing the same thing again. -- --Bryan From mail at microcorp.co.za Wed Dec 17 09:01:31 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 17 Dec 2008 16:01:31 +0200 Subject: Transferring a file over sockets References: Message-ID: <002801c96050$251d57e0$0d00a8c0@hendrik> Ferdinand Sousa wrote: >========================================================== .# file receiver ># work in progress > >import socket > >s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >HOST = '192.168.1.17' >PORT = 31400 > >s.bind((HOST, PORT)) >s.listen(3) >conn, addr = s.accept() >print 'conn at address',addr >conn.send('READY') >f = open('C:\\Documents and Settings\\USER\\Desktop\\test.pdf','wb') >fsize=int(conn.recv(8)) >print 'File size',fsize >f.write(conn.recv(fsize)) This recv is not guaranteed to actually receive the number of characters you are asking for - it will stop when it has received that many, yes, but it may return with less, or even none if there is a time out set. The TCP is a more or less featureless stream of characters. Consider including a start marker so you know where the lesson starts. If you do this, consider the possibility of having a "false sync". Sending/receiving the length is good - also google for "netstring" Google for "escaping". Consider writing a loop to receive until the required length has been received - look at the docs for the recv function - it can tell you how much has been received. >f.close() >conn.close() >s.close() > >raw_input('Press any key to exit') > > >=========================================================== > ># file sender !!! ># Work in progress > >import socket, os >from stat import ST_SIZE > > >HOST = '192.168.1.17' >PORT = 31400 # Arbitrary non-privileged port > >s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > >s.connect((HOST,PORT)) >if s.recv(5)!='READY': > raw_input('Unable to connect \n\n Press any key to exit ...') > s.close() > exit() > >f=open('C:\\Documents and Settings\\USER\\Desktop\\t.pdf', 'rb') >fsize=os.stat(f.name)[ST_SIZE] > >s.send(str(fsize)) >s.send(f.read()) Are you sure that the send will send all the chars that you ask it to send? If yes - why do you think this? What are the values that the send can return? > >s.close() >f.close() > >=========================================================== hth - Hendrik From w_a_x_man at yahoo.com Thu Dec 11 06:53:15 2008 From: w_a_x_man at yahoo.com (William James) Date: 11 Dec 2008 11:53:15 GMT Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> Message-ID: William James wrote: > John W Kennedy wrote: > > > Xah Lee wrote: > > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or > > > Java, you'll have 50 or hundreds lines. > > > > > Java: > > > > static float[] normal(final float[] x) { > > float sum = 0.0f; > > for (int i = 0; i < x.length; ++i) sum += x[i] * x[i]; > > final float divisor = (float) Math.sqrt(sum); > > float[] a = new float[x.length]; > > for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor; > > return a; > > } > > "We don't need no stinkin' loops!" > > SpiderMonkey Javascript: > > function normal( ary ) > { div=Math.sqrt(ary.map(function(x) x*x).reduce(function(a,b) a+b)) > return ary.map(function(x) x/div) > } The variable "div" shouldn't be global. function normal( ary ) { var div = Math.sqrt( ary.map(function(x) x*x).reduce(function(a,b) a+b) ) return ary.map(function(x) x/div) } From arnodel at googlemail.com Wed Dec 10 02:03:30 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 10 Dec 2008 07:03:30 +0000 Subject: Best way to report progress at fixed intervals References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> <817384d5-5f68-4c1f-9560-0bc7b7d2b1e3@v5g2000prm.googlegroups.com> <6ccb77a2-a3f1-4b6b-900c-d4626be9e939@s1g2000prg.googlegroups.com> Message-ID: Slaunger writes: > On 10 Dec., 03:44, George Sakkis wrote: >> On Dec 9, 11:40?am, Slaunger wrote: >> >> > I would therefore like some feedback on this proposed generic "report >> > progress at regular intervals" approach presented here. What could I >> > do better? >> >> There is a pypi package that might do what you're looking for (haven't >> used it though):http://pypi.python.org/pypi/progressbar/. >> >> HTH, >> George > > Thank you. I will keep that in mind, if I ever get to doing GUI-based > progress. > > -- Slaunger It's a text progress bar -- Arnaud From rt8396 at gmail.com Sun Dec 28 12:33:19 2008 From: rt8396 at gmail.com (r) Date: Sun, 28 Dec 2008 09:33:19 -0800 (PST) Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> Message-ID: On Dec 28, 11:19?am, Roger wrote: > Hi Everyone, > > First I want to thank everyone that posts to this group. ?I read it > daily and always learn something new even if I never feel like I have > anything to contribute but my questions. > > When I define a method I always include a return statement out of > habit even if I don't return anything explicitly: > > def something(): > ? ? ? ? # do something > ? ? ? ? return > > Is this pythonic or excessive? ?Is this an unnecessary affectation > that only adds clock ticks to my app and would I be better off > removing "returns" where nothing is returned or is it common practice > to have returns. > > Even when I'm not explicitly returning something I like to add > "return" because it's a good additional visual marker for me to see > where a method definition ends especially in cases where I may use a > nested method. > > Thanks for the discussion! > Roger. returning nothing does nothing :) From george.sakkis at gmail.com Tue Dec 9 21:44:23 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 9 Dec 2008 18:44:23 -0800 (PST) Subject: Best way to report progress at fixed intervals References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> Message-ID: <817384d5-5f68-4c1f-9560-0bc7b7d2b1e3@v5g2000prm.googlegroups.com> On Dec 9, 11:40?am, Slaunger wrote: > I would therefore like some feedback on this proposed generic "report > progress at regular intervals" approach presented here. What could I > do better? There is a pypi package that might do what you're looking for (haven't used it though): http://pypi.python.org/pypi/progressbar/. HTH, George From rdcollum at gmail.com Thu Dec 18 14:48:36 2008 From: rdcollum at gmail.com (Roger) Date: Thu, 18 Dec 2008 11:48:36 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <71ede5f0-fd88-4155-9f0d-42d0ad5f57dc@v42g2000yqj.googlegroups.com> <61f45e65-2404-4cc0-9d81-f848c1ba566f@i18g2000prf.googlegroups.com> Message-ID: On Dec 18, 12:49?pm, r wrote: > Maybe someone will chime in with an answer, sorry i could not help. > ponder this, i must... Regardless, thanks for your help! I truly appreciate it. Roger. From raviforlkml at gmail.com Mon Dec 1 20:48:22 2008 From: raviforlkml at gmail.com (raviforlkml at gmail.com) Date: Mon, 1 Dec 2008 17:48:22 -0800 (PST) Subject: Loading required libraries for python script from shell just once Message-ID: I have a linux-like host running busybox with the python installation mounted over NFS and have the corresponding symlinks setup in /usr/bin and /usr/lib for python to run smoothly. A shell script runs my python script several times, each time with different paramters. E.g. # cat foo.sh # Lot of setup stuff ${TEST_DIR}/bin/run-test.py --arg1 foo1 --arg2 bar1 --arg3 baz1 ${TEST_DIR}/bin/run-test.py --arg1 foo2 --arg2 bar2 --arg3 baz2 ${TEST_DIR}/bin/run-test.py --arg1 foo3 --arg2 bar3 --arg3 baz3 There is a delay of about 10-15 seconds before run-test.py starts executing. Can someone suggest a method to speed up this process? Most of the delay seems to be due to python loading up the required modules. Is it possible to load all the modules used by run-test.py in a pre-execution environment in order to prevent this delay? I considered a rewrite of the shell script into python, but it has too many dependencies on shell libraries and I don't want to go that route (unless an alternative solution is impossible). Thanks! From bj_666 at gmx.net Sat Dec 13 06:23:25 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 13 Dec 2008 11:23:25 GMT Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> <87iqpoc1l0.fsf@mulj.homelinux.net> Message-ID: <6qhk9dFclvujU1@mid.uni-berlin.de> On Sat, 13 Dec 2008 02:20:59 +0100, Hrvoje Niksic wrote: > Saner (in this respect) behavior in the tuple example would require a > different protocol. I don't understand why Python doesn't just call > __iadd__ for side effect if it exists. The decision to also rebind the > result of __i*__ methods continues to baffle me. I guess it is a result > of a desire to enable the __i*__ methods to punt and return a different > instance after all, but if so, that design decision brings more problems > than benefits. How often do you use ``+=`` with mutable objects? I use it very often with number types and sometimes with tuples, and there rebinding is necessary. If I couldn't use it in this way: ``x = 0; x += z``, I'd call that a bad design decision. It would be a quite useless operator then. Ciao, Marc 'BlackJack' Rintsch From Russ.Paielli at gmail.com Sat Dec 6 02:41:11 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Fri, 5 Dec 2008 23:41:11 -0800 (PST) Subject: Guido's new method definition idea References: Message-ID: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> On Dec 5, 6:21?pm, "Daniel Fetchinson" wrote: > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... > > The proposal is to allow this: > > class C: > ? ? def self.method( arg ): > ? ? ? ? self.value = arg > ? ? ? ? return self.value > > instead of this: > > class C: > ? ? def method( self, arg ): > ? ? ? ? self.value = arg > ? ? ? ? return self.value > > I.e. explicit self stays only the syntax is slightly different and may > seem attractive to some. As pointed out by Guido classmethods would > work similarly: > > class C: > ? ? @classmethod > ? ? def cls.method( arg ): > ? ? ? ? cls.val = arg > ? ? ? ? return cls.val > > The fact that Guido says, > > "Now, I'm not saying that I like this better than the status quo. But > I like it a lot better than [...] but it has the great advantage that > it is backward compatible, and can be evolved into a PEP with a > reference implementation without too much effort." > > shows that the proposal is viable. > > I'd like this new way of defining methods, what do you guys think? > Anyone ready for writing a PEP? > > Cheers, > Daniel > > -- > Psss, psss, put it down! -http://www.cafepress.com/putitdown I like it. I'll even go a step further and suggest that "$" be allowed as a substitute for "self". It looks like a capital "S" (for Self), and it stands out clearly. It also makes code more succinct with no loss of readability. Think of the line wraps that could be avoided. From steve at REMOVE-THIS-cybersource.com.au Mon Dec 22 05:44:39 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Dec 2008 10:44:39 GMT Subject: How to represent a sequence of raw bytes References: <200812220327.36180.motoom@xs4all.nl> Message-ID: <015f66d7$0$20615$c3e8da3@news.astraweb.com> On Mon, 22 Dec 2008 14:56:45 +0800, Steven Woody wrote: > The intension is to allocate 200 undefined bytes in memory. You *want* undefined bytes? Out of curiosity, what do you intend to do with them? -- Steven From google at mrabarnett.plus.com Fri Dec 12 11:47:43 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 12 Dec 2008 16:47:43 +0000 Subject: newbie question: if var1 == var2: In-Reply-To: <87myf1z8n7.fsf@daycos.com> References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> <87y6ymzecp.fsf@daycos.com> <87myf1z8n7.fsf@daycos.com> Message-ID: <494295AF.1070308@mrabarnett.plus.com> Kirk Strauser wrote: > At 2008-12-12T15:35:11Z, "J. Cliff Dyer" writes: > >> Python has a version equally good: >> >> def chomp(s): >> return s.rstrip('\r\n') >> >> You'll hardly miss Perl at all. ;) > > I haven't missed Perl in years! I just wish there was a basestring.stripeol > method because I seem to end up writing the inline version of "chomp" every > time I iterate across a file. > Python is open source. You could suggest adding it and/or provide a patch. From sturlamolden at yahoo.no Fri Dec 12 09:50:27 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 06:50:27 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> <49427875$0$30229$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <0c3e89f2-b67c-4da5-bd33-87c98ee48812@z28g2000prd.googlegroups.com> On Dec 12, 3:43 pm, Stefan Behnel wrote: > http://cython.org/ How is the numpy support in Cython going? It was supposed to know about ndarrays natively. I.e. not treat them as Python objects, but rather as known C structs. That way an operation like arr[n] would not result in a callback to Python, but translate directly to fast pointer arithmetics. From aleksandr.goretoy at gmail.com Sat Dec 27 06:10:06 2008 From: aleksandr.goretoy at gmail.com (alex goretoy) Date: Sat, 27 Dec 2008 05:10:06 -0600 Subject: parsing csv files class In-Reply-To: References: Message-ID: I know it's messy with all those self.soc.* functions, but it works in one of my current project. I just want to make it more pythonic I also want to add capability for makeing csv file if I give it input like: 1234,something nice, hey this is something nice 2468,something else, something else On Sat, Dec 27, 2008 at 4:54 AM, alex goretoy wrote: > Hello All, > > I have this class that I use in one of my projects. I know it's missing > functionality and some things could have been done differently. Can you ehlp > me make this class better? What can I do to make it more resistant to error? > You can find the stdout_colours class on Google if you want it, JFGI I want > to make it more pythonic. I come from a PHP background, can you tell? > > Any and all help is appreciated > -Alex > > #!/usr/bin/env python > from ctypes import * > import os, sys, types, csv, urllib, urllib2, urlparse, > string,stdout_colours > > class parsercsvy(object): > """Return a line from a csv file or total amount of lines""" > def __init__(self,file_name=""): > self.func_me_color="white_on_black" > self.soc=stdout_colours.stdout_colors() > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > self.filename = file_name > self.buffer = [] > self.bufferp= [] > if string.find(self.filename,"http") != -1: > resp=urllib2.urlopen(self.filename) > file=resp.read() > lfi=len(string.split(self.filename,"/")) > filename = "/tmp/"+string.split(self.filename,"/")[lfi-1] > f=open(filename,"w") > f.write(file) > f.close > self.parse(self.filename) > else: > self.parse(self.filename) > self.soc.me_him(['EXIT:',__name__],self.func_me_color) > def parse(self,filename,ret=0): > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > i = 0 > try: > reader = csv.reader(file(filename, "rb")) > try: > for row in reader: > self.buffer.append(row) > s,a=[],{} > > for j in range(len(self.buffer[0])): > a[self.buffer[0][j]]=row[j] > self.bufferp.append(a) > i+=1 > self.total = i-1 > except csv.Error, e: > sys.exit('file %s, line %d: %s' % (filename, > reader.line_num, e)) > except IOError, e: > sys.exit('file %s, IOError: %s' % (filename, e)) > self.soc.me_him(['EXIT:',__name__],self.func_me_color) > def index(self, index): > """return line for index""" > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > > self.soc.me_him(['RETURN:',self.buffer[int(index)],__name__],self.func_me_color) > return self.buffer[int(index)] > def total(self): > """return total number of lines in csv file""" > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > self.soc.me_him(['RETURN:',self.total,__name__],self.func_me_color) > return self.total > def header(self): > """return csv header == line 0""" > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > > self.soc.me_him(['RETURN:',self.buffer[0],__name__],self.func_me_color) > return self.buffer[0] > def find_and_replace(self,li,fi,re): > """ > find and replace a string inside a string, return list > find_and_replace(list,find,replace) > """ > this=[] > for l in li: > # found_index=string.find(l,fi) > this.append(l.replace(fi,re)) > return this > def return_buffer(self): > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > > self.soc.me_him(['RETURN:',self.buffer,__name__],self.func_me_color) > return self.buffer > if __name__ == "__main__": > if len(sys.argv) < 1: > print "Usage: %s file"% sys.argv[0] > f=sys.argv[1] > c=csv_parser(f) > print c.bufferp > -- > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > -- ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? -------------- next part -------------- An HTML attachment was scrubbed... URL: From Kevin.Smith at sas.com Tue Dec 2 11:19:22 2008 From: Kevin.Smith at sas.com (Kevin D. Smith) Date: Tue, 2 Dec 2008 10:19:22 -0600 Subject: Debugging a Python Program that Hangs Message-ID: I have a fairly large python program that, when a certain combination of options is used, hangs. I have no idea where it is hanging, so simply putting in print statements to locate the spot would be quite difficult. Unfortunately, ctrl-C'ing the program doesn't print a traceback either. Looking through the python debugger documentation, I don't see how to run a python program and interactively stopping it while it is running. Is there a way to stop within a running python program to see where it is getting hung up? -- Kevin D. Smith From dfnsonfsduifb at gmx.de Mon Dec 29 21:17:44 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Tue, 30 Dec 2008 03:17:44 +0100 Subject: SQL, lite lite lite In-Reply-To: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> Message-ID: <8vco26x1v6.ln2@joelaptop.homelan.net> Aaron Brady schrieb: > This is basically an invitation for everyone to brainstorm. (No > hijackings, good humor & digression ok.) Lastly, ... Even if it took (as you mentioned) a semester of SQL studies - which it does not - why do you think your syntax is easier? The only person your proposed syntax is easier for is you. Get over it, learn SQL, and enjoy the benefits of one unified standard - not everyone cooking their own soup. You'll be able to learn PostgreSQL, Oracle SQL, mySQL, SQlite all at once! Regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From bj_666 at gmx.net Fri Dec 19 16:10:12 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Dec 2008 21:10:12 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> <88ff7c46-2b23-49e4-865e-781d23433799@l33g2000pri.googlegroups.com> Message-ID: <6r2gtkFfb5kpU5@mid.uni-berlin.de> On Fri, 19 Dec 2008 10:44:25 -0800, r wrote: > ~Bearophile, > Thanks for your civil approach to this conversation but I must disagree > with you on the new string formatting syntax. You said the new syntax is > suppost to be easier on the n00b , I say it pollutes a students mind. > What is wrong with similarities to C formatting, I find nothing > complicated about it. > > %s (means put a string here) > %d (means put a integer here) > %f (means put a float here) > > It does not get any simpler than that, Well for those simple cases you could simply use '%s' for strings, integers, and floating point objects in Python. But '{0}' isn't more complicated. But you get the extra flexibility to decouple the order in the string and the order of the objects to be formatted. > and this will just ease the transition to C programming for this > student. Lets not forget how important C is! To a Python "n00b"? Not important at all. Beside the point that '%s' is still possible -- someone who knows C but struggles with replacing '%s' by '{0}' has far greater problems. Ciao, Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Wed Dec 10 22:45:07 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 10 Dec 2008 19:45:07 -0800 (PST) Subject: How to convert uint64 in C into Python 32bit Object [ I am using Python2.2 ] References: <069f0d65-a3d5-4e8f-a85b-c53743ab99d0@i18g2000prf.googlegroups.com> Message-ID: <8485fb8f-4425-436d-9e0b-2079c80c9802@q26g2000prq.googlegroups.com> On Dec 11, 9:49?am, Explore_Imagination wrote: > Hi all > > I am new to C and python ... I want to convert C data type uint64 > variable into the Python 32bit Object. I am currently using Python 2.2 > [ It is necessary to use it ] > > Kindly give your suggestion how and in which way I can achieve this > task. I'm not sure what you mean by "the Python 32bit Object". A Python int object holds a signed 32-bit integer. A Python long object holds a signed integer of arbitrary size. You will need to convert your uint64 into a Python long; then, if necessary, check that the result will fit in an int (result <= sys.maxint). If the "C variable" is in an 8-byte string that you have read from a file, the unpack function in the struct module will do the job. Assuming your computer is little-endian: >>> maxu64 = '\xff' * 8 # example input string >>> import struct >>> result = struct.unpack('>> result 18446744073709551615L >>> 2 ** 64 - 1 18446744073709551615L If however you mean that in C code you need to build a Python object to pass over to Python code: According to the Python/C API Reference Manual (http://www.python.org/doc/2.2.3/api/longObjects.html): PyObject* PyLong_FromUnsignedLongLong(unsigned long long v) Return value: New reference. Returns a new PyLongObject object from a C unsigned long long, or NULL on failure. If however you mean something else, .... HTH, John From luismgz at gmail.com Sat Dec 20 10:44:03 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Sat, 20 Dec 2008 07:44:03 -0800 (PST) Subject: Namespaces, multiple assignments, and exec() References: Message-ID: <9405cec7-0b51-46e1-a20e-0c11ce036234@k8g2000yqn.googlegroups.com> On Dec 19, 11:34?pm, John O'Hagan wrote: > I have a lot of repetitive assignments to make, within a generator, that use a > function outside the generator: > > var1 = func("var1", args) > var2 = func("var2", args) > var3 = func("var3", args) > etc... > > In each case the args are identical, but the first argument is a string of the > name being assigned. It works fine but I'd like to reduce the clutter by > doing the assignments in a loop. I've tried using exec(): > > for name in name_string_list: > ? ? exec(name + ' = func(\"' + name + '\", args)') > > but in the local namespace it doesn't understand func(), and if I give it > globals() it doesn't understand the args, which come from within the > generator. > > What's a good way to do this kind of thing? > > Thanks, > > John Why don't you just use a dictionary? d = {} for name in name_string_list: d[name] = func(name, args) Luis From 20080915.20.wmcclain at spamgourmet.com Tue Dec 9 13:41:26 2008 From: 20080915.20.wmcclain at spamgourmet.com (Bill McClain) Date: 9 Dec 2008 18:41:26 GMT Subject: StringIO in 2.6 and beyond References: Message-ID: On 2008-12-09, Peter Otten <__peter__ at web.de> wrote: > >>> out = io.StringIO() > >>> print(u"hello", file=out, end=u"\n") > >>> out.getvalue() > u'hello\n' That has the benefit of working. Thank you! That can't be the intended behavior of print(), can it? Insering non-unicode spaces and line terminators? I thought all text was unicode now. Or is that only in 3.0? -Bill -- Sattre Press History of Astronomy http://sattre-press.com/ During the 19th Century info at sattre-press.com by Agnes M. Clerke http://sattre-press.com/han.html From narkewoody at gmail.com Mon Dec 22 09:52:30 2008 From: narkewoody at gmail.com (Steven Woody) Date: Mon, 22 Dec 2008 22:52:30 +0800 Subject: How to represent a sequence of raw bytes In-Reply-To: <015f66d7$0$20615$c3e8da3@news.astraweb.com> References: <200812220327.36180.motoom@xs4all.nl> <015f66d7$0$20615$c3e8da3@news.astraweb.com> Message-ID: On Mon, Dec 22, 2008 at 6:44 PM, Steven D'Aprano wrote: > On Mon, 22 Dec 2008 14:56:45 +0800, Steven Woody wrote: > >> The intension is to allocate 200 undefined bytes in memory. > > You *want* undefined bytes? Out of curiosity, what do you intend to do > with them? > to receive/send network packets, read raw files, etc. After read replies of the thread, I think 'array' or 'struct' maybe what I wanted, may a plain list can do, but I am not sure. From python.leojay at gmail.com Thu Dec 11 05:54:54 2008 From: python.leojay at gmail.com (Leo Jay) Date: Thu, 11 Dec 2008 18:54:54 +0800 Subject: Equivalent of 'wget' for python? In-Reply-To: References: Message-ID: <4e307e0f0812110254q593e46b0rfd818a2290d7a9fe@mail.gmail.com> On Tue, Dec 9, 2008 at 12:22 AM, Robert Dailey wrote: > Hi, > > I'm looking for a portable way to download ZIP files on the internet > through Python. I don't want to do os.system() to invoke 'wget', since > this isn't portable on Windows. I'm hoping the core python library has > a library for this. Note that I'll be using Python 3.0. > You can get Wget for Windows here: http://gnuwin32.sourceforge.net/packages/wget.htm -- Best Regards, Leo Jay From alex.pulver at gmail.com Fri Dec 19 09:34:55 2008 From: alex.pulver at gmail.com (Alex) Date: Fri, 19 Dec 2008 06:34:55 -0800 (PST) Subject: How to read stdout from subprocess as it is being produced Message-ID: <263c3946-86aa-4db0-bdaf-42d0c8e5e5d6@q18g2000vbn.googlegroups.com> Hi, I have a Pyhon GUI application that launches subprocess. I would like to read the subprocess' stdout as it is being produced (show it in GUI), without hanging the GUI. I guess threading will solve the no-hanging issue, but as far as I searched for now, I've only seen how to read the stdout after subprocess is finished. Thanks! From klaus.kopec at tuebingen.mpg.de Tue Dec 9 10:59:16 2008 From: klaus.kopec at tuebingen.mpg.de (Klaus Kopec) Date: Tue, 09 Dec 2008 16:59:16 +0100 Subject: pickling a circular object inherited from list Message-ID: Hello everyone, I have a problem with inheritance from list. I want to create a tree like object where child nodes are kept in self[:] and every child has a field that points to its parent. Pickling such an object, however, throws an AssertionError. See below for source code and output of an easy example case of my problem. What did I do wrong? Best regards, Klaus ======== source: class myList(list): pass class myObject: def __init__(self, parent=None): self.parent = parent if __name__ == '__main__': r = myList() r.append( myObject(r) ) from pickle import dump, load dump(r, file('/tmp/x', 'w')) ========= output: Traceback (most recent call last): File "", line 1, in ? File "/tmp/python-11053-o.py", line 15, in ? dump(r, f) File "/usr/lib/python2.4/pickle.py", line 1382, in dump Pickler(file, protocol, bin).dump(obj) File "/usr/lib/python2.4/pickle.py", line 231, in dump self.save(obj) File "/usr/lib/python2.4/pickle.py", line 338, in save self.save_reduce(obj=obj, *rv) File "/usr/lib/python2.4/pickle.py", line 419, in save_reduce self.memoize(obj) File "/usr/lib/python2.4/pickle.py", line 251, in memoize assert id(obj) not in self.memo AssertionError From python.list at tim.thechases.com Thu Dec 4 18:42:19 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 04 Dec 2008 17:42:19 -0600 Subject: Find Files in a Folder Between 2 Dates In-Reply-To: <4c54b6c5-ae4d-4b89-8c6d-940c96de29bb@n33g2000pri.googlegroups.com> References: <4c54b6c5-ae4d-4b89-8c6d-940c96de29bb@n33g2000pri.googlegroups.com> Message-ID: <49386ADB.9040909@tim.thechases.com> > Is there a way to find all the files in a folder, between 2 dates? > > For example: > > Firstdate = 200801010000 > Seconddate = 200801020000 > > Find all the files in C:\Folder that are between Firstdate and > SecondDate. This should do it: import time import os firstdate = "200801010000" seconddate = "200801020000" def get_timestamp(s): return time.mktime(time.strptime(s, "%Y%m%d%H%M")) start = get_timestamp(firstdate) end = get_timestamp(seconddate) location = '/path/to/wherever/' files = [fname for fname in os.listdir(location) if start <= os.stat(os.path.join(location, fname)).st_mtime <= end ] print files The magic is the the os.stat(f).st_mtime to determine when the associated timestamp, the os.listdir() to get the available files in a directory, and the list-comprehension to filter to only the ones you want. -tkc From philip at semanchuk.com Tue Dec 2 09:50:02 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 2 Dec 2008 09:50:02 -0500 Subject: Running a Python script from crontab In-Reply-To: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> Message-ID: <38C55FC8-B430-4C46-907F-C41D57F2D3F1@semanchuk.com> On Dec 2, 2008, at 9:35 AM, Astley Le Jasper wrote: > I need help ... I've been looking at this every evening for over a > week now. I'd like to see my kids again! > > I have script that runs fine in the terminal but when I try to run it > in a crontab for either myself or root, it bails out. > > The trouble is that obviously I get no console when using crontab so > can't see any traceback. I use logging which shows 'info' messages as > the script is working, but no error messages. I've peppered it with > debug messages to try to track it down to a line, but it stops it the > middle of appending data to a list. I'd expect it to bail out when > calling a module or reading/writing to a different file. > > Is there any way of getting more info from the app, like popping up a > console while its running? > > my crontab is: > > 30 15 * * * cd /home/myusername/src && python myscript.py Here's what my crontab looks like on FreeBSD. (Your syntax may differ.) Note how I'm redirecting stdout and stderr to a log file -- that helps debugging. Also, I'm setting an explicit shell and path just to make sure that e.g. Python is findable. ---------------------------- SHELL=/usr/local/bin/bash PATH=/bin:/usr/bin:/usr/local/bin # min hh day mon dow */2 * * * * python /usr/local/foo/myscript.py >> / var/log/me/myscript.txt 2>&1 ---------------------------- HTH Philip From steve at REMOVE-THIS-cybersource.com.au Sat Dec 6 18:48:04 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Dec 2008 23:48:04 GMT Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> <8b8d1fb3-f49e-49bf-8cfe-eeee5ed16109@r37g2000prr.googlegroups.com> <014a932b$0$20670$c3e8da3@news.astraweb.com> Message-ID: <014b06e8$0$20670$c3e8da3@news.astraweb.com> On Sat, 06 Dec 2008 08:01:40 -0800, Russ P. wrote: >> -2 on this proposal. > > Did you get two votes in the Presidential election too? 8^) You know, occasionally you stumble across people on the Internet who aren't from the USA. Some of us even speak English almost as good as native speakers *wink* In any case, in this context -2 refers to the strength of feeling, not the number of votes. Python is not a democracy, and our Beloved BDFL Guido graciously takes our needs and wants into account before making decisions. -- Steven From rt8396 at gmail.com Tue Dec 2 00:03:26 2008 From: rt8396 at gmail.com (r) Date: Mon, 1 Dec 2008 21:03:26 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <9baabb6c-daab-418e-a11f-9162e1fc30f7@k36g2000pri.googlegroups.com> Message-ID: Ok, so i was wrong about you =) From sgeiger at ncee.net Mon Dec 8 15:03:32 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Mon, 08 Dec 2008 15:03:32 -0500 Subject: Text parsing via regex In-Reply-To: References: Message-ID: <493D7D94.3080802@ncee.net> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061 def wrap(text, width): """ A word-wrap function that preserves existing line breaks and most spaces in the text. Expects that existing line breaks are posix newlines (\n). """ return reduce(lambda line, word, width=width: '%s%s%s' % (line, ' \n'[(len(line)-line.rfind('\n')-1 + len(word.split('\n',1)[0] ) >= width)], word), text.split(' ') ) # 2 very long lines separated by a blank line msg = """Arthur: "The Lady of the Lake, her arm clad in the purest \ shimmering samite, held aloft Excalibur from the bosom of the water, \ signifying by Divine Providence that I, Arthur, was to carry \ Excalibur. That is why I am your king!" Dennis: "Listen. Strange women lying in ponds distributing swords is \ no basis for a system of government. Supreme executive power derives \ from a mandate from the masses, not from some farcical aquatic \ ceremony!\"""" # example: make it fit in 40 columns print(wrap(msg,40)) # result is below """ Arthur: "The Lady of the Lake, her arm """ Robocop wrote: > I'm having a little text parsing problem that i think would be really > quick to troubleshoot for someone more versed in python and Regexes. > I need to write a simple script that parses some arbitrarily long > string every 50 characters, and does not parse text in the middle of > words (but ultimately every parsed string should be 50 characters, so > adding in white spaces is necessary). So i immediately came up with > something along the lines of: > > string = "a bunch of nonsense that could be really long, or really > short depending on the situation" > r = re.compile(r".{50}") > m = r.match(string) > > then i started to realize that i didn't know how to do exactly what i > wanted. At this point i wanted to find a way to simply use something > like: > > parsed_1, parsed_2,...parsed_n = m.groups() > > However i'm having several problems. I know that playskool regular > expression i wrote above will only parse every 50 characters, and will > blindly cut words in half if the parsed string doesn't end with a > whitespace. I'm relatively new to regexes and i don't know how to > have it take that into account, or even what type of logic i would > need to fill in the extra whitespaces to make the string the proper > length when avoiding cutting words up. So that's problem #1. Problem > #2 is that because the string is of arbitrary length, i never know how > many parsed strings i'll have, and thus do not immediately know how > many variables need to be created to accompany them. It's easy enough > with each pass of the function to find how many i will have by doing: > mag = len(string) > upper_lim = mag/50 + 1 > But i'm not sure how to declare and set them to my parsed strings. > Now problem #1 isn't as pressing, i can technically get away with > cutting up the words, i'd just prefer not to. The most pressing > problem right now is #2. Any help, or suggestions would be great, > anything to get me thinking differently is helpful. > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From nick at craig-wood.com Mon Dec 1 07:30:46 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 01 Dec 2008 06:30:46 -0600 Subject: Emacs vs. Eclipse vs. Vim References: Message-ID: Josh wrote: > If you were a beginning programmer and willing to make an investment in > steep learning curve for best returns down the road, which would you pick? IMHO I'd want these features * Keyboard macros * Regular expression search and replace * Integration with version control * Infinite undo * Syntax colouring (not essential) * Bracket matching (useful but not essential) * Integration with compiler with error throwback (essential for C code work) * Automatic indenting (a great time saver) I know that emacs (my choice) and vim have all these features, don't know about Eclipse. In fact if I had to pick one feature that a programmer's editor must have it would be keyboard macros. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From dotancohen at gmail.com Wed Dec 3 21:08:21 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 4 Dec 2008 04:08:21 +0200 Subject: RELEASED Python 3.0 final In-Reply-To: References: Message-ID: <880dece00812031808q1a56c6b6g399283e8d12ec8c3@mail.gmail.com> 2008/12/4 Barry Warsaw : > On behalf of the Python development team and the Python community, I am > happy to announce the release of Python 3.0 final. > Congratulations! I have been learning Python 2.x while paying strict attention to the 3.x [in]compatibility issue. So, I have been waiting for this day since I've started with Python! -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-??-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From gdamjan at gmail.com Thu Dec 4 14:01:11 2008 From: gdamjan at gmail.com (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Thu, 04 Dec 2008 20:01:11 +0100 Subject: Python 3 read() function References: Message-ID: > I don't think it matters. Here's a quick comparison between 2.5 and > 3.0 on a relatively small 17 meg file: > > C:\>c:\Python30\python -m timeit -n 1 > "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" > 1 loops, best of 3: 36.8 sec per loop > > C:\>c:\Python25\python -m timeit -n 1 > "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" > 1 loops, best of 3: 33 msec per loop > > That's 3 orders of magnitude slower on python3.0! Isn't this because you have the file cached in memory on the second run? -- ?????? ( http://softver.org.mk/damjan/ ) "The moment you commit and quit holding back, all sorts of unforseen incidents, meetings and material assistance will rise up to help you. The simple act of commitment is a powerful magnet for help." -- Napoleon From arnodel at googlemail.com Tue Dec 2 14:17:34 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 02 Dec 2008 19:17:34 +0000 Subject: Scanner class References: <737a0550-0b92-4f65-829e-953882d74419@y18g2000yqn.googlegroups.com> <5d73aeb2-a4f1-4dd4-9c16-67db39df9e0c@u14g2000yqg.googlegroups.com> Message-ID: George Sakkis writes: > On Dec 1, 5:42?pm, Arnaud Delobelle wrote: >> George Sakkis writes: >> >> http://code.activestate.com/recipes/457664/ > > Thanks, didn't know about it. I also found Plex [1] which seems more > powerful. > > George > > [1] http://www.cosc.canterbury.ac.nz/greg.ewing/python/Plex/version/doc/index.html I've also written a python module that aims to be similar to GNU flex. You can see it here: http://www.marooned.org.uk/~arno/python/lexing.html It's not extremely sophisticated but it's quite easy to use. I've written a Python 3 tokeniser in it :) -- Arnaud From benjamin.kaplan at case.edu Tue Dec 23 09:31:31 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 23 Dec 2008 09:31:31 -0500 Subject: Python's popularity In-Reply-To: <32d8e3f1-52a7-4bce-a70a-70db488a417b@h20g2000yqn.googlegroups.com> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> <7c02eb33-a919-4481-8eda-76062729f233@k19g2000yqg.googlegroups.com> <32d8e3f1-52a7-4bce-a70a-70db488a417b@h20g2000yqn.googlegroups.com> Message-ID: On Tue, Dec 23, 2008 at 12:05 AM, r wrote: > On Dec 22, 10:09 pm, Ben Kaplan wrote: > > That's just because most of us don't say anything unless we have > > something useful to say. We prefer to let the experts answer the > > questions, but we read the threads so we can benefit from them. > > OK Ben, So you are saying > > 1.) do not question the gods! > 2.) speak only when spoken to! > 3.) do not have an opinion! > > Somehow this reminds me of some old and brainwashing religions, Not an > OSS project. Just observations Ben. You're the one who keeps bringing up the need to spread python. For most people, this is a forum to ask questions and have experts respond to them. Most people who post here aren't looking for your opinion, they want answers. If you know the answer to a question, answer it. If not, read the answers of people who have seen it before. When you post your opinions, you're just creating more noise. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rt8396 at gmail.com Wed Dec 24 15:52:49 2008 From: rt8396 at gmail.com (r) Date: Wed, 24 Dec 2008 12:52:49 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> Message-ID: On Dec 22, 7:26?pm, Steven D'Aprano wrote: > On Mon, 22 Dec 2008 06:58:06 -0800, walterbyrd wrote: > > On Dec 21, 12:28?pm, Bruno Desthuilliers > > wrote: > >> Strange enough, > >> no one seems to complain about PHP or Ruby's performances... > > > A few years back, there was a certain amount of chest thumping, when > > python/django easily beat ror in a benchmark test. Now that ruby is > > faster, I guess speed is no big issue. > > Who was doing this chest-thumping? Fanboys like "r"? Why should you tar > all of us with their immaturity? Walter, Steven would rather live in a bland Utopian society and could care less for the greatness of competition and he has little respect for loyalty. He would like to have little league games where there is no losers, so nobody's "feelings" get hurt(oh NO!). And EOE so that god forbid weather or not someone is qualified they must be hired just to keep a equal balance in the workplace. Hey Steven, we should outlaw individualism too, God forbid someone think outside the box!(damn heretics!) But as they say "ignorance is bliss" ey Stevie? From bruno.42.desthuilliers at websiteburo.invalid Fri Dec 19 09:02:56 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 19 Dec 2008 15:02:56 +0100 Subject: How to parsing a sequence of integers In-Reply-To: References: <494ba258$0$18998$426a74cc@news.free.fr> Message-ID: <494ba949$0$23019$426a34cc@news.free.fr> John Machin a ?crit : > On Dec 20, 12:33 am, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: >> Steven Woody a ?crit :> Hi, >> >>> I am a newbie and is reading the python book. Could anyone tell me, >>> how to parsing the following string >>> "123 100 12 37 ..." >> > into a list of integers on which I can then apply max()/min()? >> >> source = "123 100 12 37" >> list_of_ints = [int(part) for part in source.strip().split()] > > The purpose of the .strip() would be ...? Err... To check if you were paying attention ?-) From m.faustino at gmail.com Mon Dec 8 13:29:08 2008 From: m.faustino at gmail.com (=?ISO-8859-1?Q?M=E1rcio_Faustino?=) Date: Mon, 8 Dec 2008 10:29:08 -0800 (PST) Subject: Public imports References: <9623b0a3-7053-41f1-b116-0cd5e54f39e9@v13g2000vbb.googlegroups.com> <493d1ec0$0$32048$426a34cc@news.free.fr> Message-ID: <66ecdd96-38dd-4054-8009-e145c0a78316@o40g2000prn.googlegroups.com> So, no chance of doing this: # "A.py" from __future__ import division, with_statement # "B.py" from A import * print 1 / 2 ...and printing 0.5, right? Too bad :) Thanks! From rdmurray at bitdance.com Tue Dec 9 13:43:26 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Tue, 9 Dec 2008 13:43:26 -0500 (EST) Subject: Can't figure out where SyntaxError: can not delete variable 'x' referenced in nested scope us coming from in python >=2.6 In-Reply-To: <1228846300.4109.30.camel@brotherus.rdu.redhat.com> References: <1228846300.4109.30.camel@brotherus.rdu.redhat.com> Message-ID: On Tue, 9 Dec 2008 at 13:11, Albert Hopkins wrote: > Say I have module foo.py: > > def a(x): > def b(): > x > del x [...] > The difference is under Python 2.4 I get a traceback with the lineno and > offending line, but I do not get a traceback in Pythons 2.6 and 3.0. 2.5 also omits the traceback. Smells like a bug to me. --RDM From jason.scheirer at gmail.com Wed Dec 3 14:25:29 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Wed, 3 Dec 2008 11:25:29 -0800 (PST) Subject: Overriding a method at the instance level on a subclass of a builtin type References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> Message-ID: <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> On Dec 2, 6:13?pm, Aaron Brady wrote: > On Dec 2, 6:58?pm, "Zac Burns" wrote: > > > > > Sorry for the long subject. > > > I'm trying to create a subclass dictionary that runs extra init code > > on the first __getitem__ call. However, the performance of __getitem__ > > is quite important - so I'm trying in the subclassed __getitem__ > > method to first run some code and then patch in the original dict > > method for the instance to avoid even the check to see if the init > > code has been run. Various recipes using instancemethod and the like > > have failed me. > > > Curiously if __slots__ is not specified no error occurs when setting > > self.__getitem__ but the function is not overriden. If __slots__ is > > ['__getitem__'] however it complains that __getitem__ is read only. I > > do not understand that behavior. > > > -- > > Zachary Burns > > (407)590-4814 > > Aim - Zac256FL > > Production Engineer (Digital Overlord) > > Zindagi Games > > That sounds like the State Pattern, from GoF. ?http://en.wikipedia.org/wiki/State_pattern > > I like the idea of 'renaming', not redefining, but reassigning methods > at different points during an object's lifetime. ?I often wish I had > more experience with it, and more docs talked about it. > > It's hard on memory usage, since each instance has its own function > attribute, even if there's still only one instance of the function. > Without it, the function attribute is just looked up on the class. > > Not thoroughly tested: > > >>> class A: > > ... ? ? def methA( self ): > ... ? ? ? ? ? ? print 'methA' > ... ? ? ? ? ? ? self.meth= self.methB > ... ? ? meth= methA > ... ? ? def methB( self ): > ... ? ? ? ? ? ? print 'methB' > ...>>> a= A() > >>> a.meth() > methA > >>> a.meth() > > methB The problem with using this this pattern in the way that you've specified is that you have a potential memory leak/object lifetime issue. Assigning a bound method of an instance (which itself holds a reference to self) to another attribute in that same instance creates a kind of circular dependency that I have discovered can trip up the GC more often than not. You can subclass it as easily: class dictsubclass(dict): def __getitem__(self, keyname): if not hasattr(self, '_run_once'): self.special_code_to_run_once() self._run_once = True return super(self, dict).__getitem__(keyname) If that extra ~16 bytes associated with the subclass is really a problem: class dictsubclass(dict): def __getitem__(self, keyname): self.special_code_to_run_once() self.__class__ = dict return super(self, dict).__getitem__(keyname) But I don't think that's a good idea at all. From steven at REMOVE.THIS.cybersource.com.au Wed Dec 10 22:28:02 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 11 Dec 2008 03:28:02 GMT Subject: Rich Comparisons Gotcha References: <200812101401.35786.kyrie@uh.cu> <49401C2D.4050209@egenix.com> Message-ID: On Wed, 10 Dec 2008 17:21:51 -0500, Luis Zarrabeitia wrote: > I do numeric work... I'm finishing my MSc in applied math and I'm > programing mostly with python. And I'd rather have a.compare_with(b), or > a.elementwise_compare(b), or whatever name, rather than (a==b).all(). Unluckily for you, the Numeric/Numpy people wanted something else. They asked first, there's a lot more of them, and their project is very important to Python's continued success. > In > fact, I'd very much like to have an a.compare_with(b, epsilon=e).all() > (to account for rounding errors), and with python2.5, > all(a.compare_with(b)). > > Yes, I could create an element_compare(a,b) function. Absolutely. > But I still can't use a==b and have a meaningful result. That's right. *ANY* operation in Python can fail, given arbitrary data, with the possible exception of the id() function and the "is" and "is not" operators. You have to deal with it. > Ok, I can (and do) ignore that, > it's just one library, I'll keep track of the types before asking for > equality (already an ugly thing to do in python), but the a==b behaviour > breaks the lists (a in ll, ll.indexof(a)) even for elements not in > numpy. ?Should I also ignore lists? That depends on what sort of contract your code is giving. Does it promise to work with any imaginable data whatsoever, no matter how badly broken or poorly designed or incompatible with what you're trying to do? If so, then I suggest your contract is broken, not the behaviour of list. You can't make trustworthy promises to deal with arbitrary data types that you don't control, that can fail in arbitrary ways. Here's something for you to consider: class Boobytrap: def __eq__(self, other): if other == 1: return True elif other == 2: while True: pass return False >>> alist = [0, Boobytrap(), 2, 3] >>> 1 in alist True >>> 3 in alist True >>> 5 in alist False >>> 2 in alist What do you expect should happen? > The concept of equality between two arrays is very well defined, as it > is also very well defined the element-by-element comparison. There is a > need to test for both - then the way to test for equality should be the > equality test. The Numpy people disagree with you. It was from their request that Python was changed to allow __eq__ to return arbitrary objects. -- Steven From ndbecker2 at gmail.com Mon Dec 1 18:00:15 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Mon, 01 Dec 2008 18:00:15 -0500 Subject: optimization References: Message-ID: Arnaud Delobelle wrote: > Neal Becker writes: > >> I noticed in some profiling, that it seems that: >> >> def Func (): >> def something(): >> ... >> >> It appears that if Func is called many times, this nested func >> definition will cause significant overhead. Is this true? I guess >> I've become accustomed to decent compilers performing reasonable >> transformations and so have tended to write code for clarity. > > If something() can be defined outside Func(), how is it clearer to > define it inside? > If it's only used inside. From kirk at daycos.com Fri Dec 12 11:08:23 2008 From: kirk at daycos.com (Kirk Strauser) Date: Fri, 12 Dec 2008 10:08:23 -0600 Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> Message-ID: <87ej0dz894.fsf@daycos.com> At 2008-12-12T15:51:15Z, Marco Mariani writes: > Filip Gruszczy?ski wrote: > >> I am not doing it, because I need it. I can as well use "if not elem >> is None", > I suggest "if elem is not None", which is not quite the same. So what's the difference exactly? "foo is not None" is actually surprising to me, since "not None" is True. "0 is True" is False, but "0 is not None" is True. Why is that? -- Kirk Strauser The Day Companies From roy at panix.com Sat Dec 20 20:19:03 2008 From: roy at panix.com (Roy Smith) Date: Sat, 20 Dec 2008 20:19:03 -0500 Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> <59153e28-bf86-4158-96d9-23aa5b9f0205@j35g2000yqh.googlegroups.com> <7889a362-d96e-4f1f-a66b-ef52b9cdb047@q26g2000prq.googlegroups.com> <85f91606-b589-425d-9636-4636c8ccbc4f@r34g2000vbp.googlegroups.com> <6b4176c3-49ce-4e7c-bced-07d8d19bc0f4@s20g2000yqh.googlegroups.com> Message-ID: In article <6b4176c3-49ce-4e7c-bced-07d8d19bc0f4 at s20g2000yqh.googlegroups.com>, r wrote: > You can't just blindly Parrot off.. "well CPU's get faster every > year". Sure you can :-) There was a nice treatment of this on slashdot today (http://www.codinghorror.com/blog/archives/001198.html). The executive summary is I'm willing to accept that Python is (big handwave) 10x slower than C++, because *I'm* 10x faster writing in Python than I am in C++, and I cost more than my computer. Moore's laws says (small handwave) CPU speed doubles every 24 months. At that rate, and assuming I remember enough high-school algebra to solve a compound interest problem, hardware gets 10% faster every 3 months. If Python gets 10% slower every 10 years or so, it's ahead of the curve. From bearophileHUGS at lycos.com Fri Dec 12 18:47:45 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 12 Dec 2008 15:47:45 -0800 (PST) Subject: (Very Newbie) Problems defining a variable References: <878wqlz27z.fsf@daycos.com> <4942c9b4$0$1651$426a34cc@news.free.fr> Message-ID: Kirk Strauser: > def get_rate(balance): > for threshold, rate in ((100000, .0173), > (50000, .0149), > (25000, .0124), > (10000, .0085), > (0, .006)): > if balance > threshold: > return rate > return .0 Nice code. This operation, of choosing an item in a sorted list of intervals that has no holes, is common enough. But something like an interval dict is overkill here. I suggest to put a zero before all those points, to improve readability and avoid some possible errors: it's easy to not see a small leading point. ---------------- Bruno Desthuilliers: > A sequence of pairs and a dict are _almost_ interchangeable (mmm... is > that the correct word ?) representations of a same data set[1] - the > main difference being ordering. If ordering matters, choose a sequence > of pairs as main representation - you can easily build a dict from it > if/when you need it. Generally(*) it's better to use the simpler data structure that does the job. Here a list/tuple of tuples is good. Very often programs get translated to other languages, so keeping things as simple as possible helps that too. --------- (*) I have used 'generally' because there's a compromise to be taken here. In C and other related languages you often use structs or records, so if you have pairs you give a name to the fields, for example "x" and "y" for the two coordinates of a 2D Point. In Python in such situation you can create a Point class, but often you instead use a (x, y) or [x, y]. In some situations you need to access the fields, so you use [0] and [1]. This is (was) a case where Python looks lower-lever than the C language. In Python3/Python2.6+ you can use a NamedTuple too. Is it better to give and take a list of points to/from as a list of [x,y] lists or as a list of Point2D? Probably a Java programmer thinks that using Point2D is safer and is a way to document what the function takes/returns too. Extending the list of pairs to 3D points is a little simpler if they are represented as tuples/lists. That's an example where you may not choose the simpler data structure (that in Python is a list of pairs) and use a list of NamedTuple to make code "safer" even if the data structure is a little more complex. Bye, bearophile From wmcbrine at users.sf.net Sat Dec 6 17:43:30 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Sat, 06 Dec 2008 22:43:30 GMT Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> <84332560-580d-488b-aa6b-6aad754a7805@k36g2000pri.googlegroups.com> Message-ID: On Fri, 05 Dec 2008 12:16:47 -0800, Fernando H. Sanches wrote: > I agree that the tab/space thing should be changed. Would it be too hard > to make the parser see if the indentation is consistent in the whole > file? *Something* has changed. I had a piece of code where, without realizing it, I had a tab mixed in with the spaces at the start of one line in a block. In 2.5, it worked, silently. In 3.0, I got an indentation error. -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From david at hlacik.eu Sun Dec 14 16:02:21 2008 From: david at hlacik.eu (=?ISO-8859-2?Q?David_Hl=E1=E8ik?=) Date: Sun, 14 Dec 2008 22:02:21 +0100 Subject: [OT] stable algorithm with complexity O(n) In-Reply-To: References: <6qidmbFc4qduU1@mid.uni-berlin.de> <01547201$0$6988$c3e8da3@news.astraweb.com> Message-ID: Thank you guys for help and support! My homework is done and waiting for grading. Here it comes - bucket sort with time complexity O(n) == linear complexity #! /usr/bin/python def sort(numbers): "sort n positive integers in O(n) provided that they are all from interval [1, n^2]" N = len(numbers) # get size of test numbers buckets_mod = [[] for i in xrange(N)] buckets_sorted = [[] for i in xrange(N+1)] # group numbers to buckets (list of numbers) with common modulus for n in numbers: buckets_mod[n % N].append(n) print "buckets_mod: %s" % buckets_mod # check numbers in buckets for l in buckets_mod: for n in l: # place number into bucket number grouped by result of division buckets_sorted[n / N].append(n) print "buckets_sorted: %s" % buckets_sorted # search through sorted buckets and return list of sorted numbers return [n for l in buckets_sorted for n in l] Regards, David On Sun, Dec 14, 2008 at 11:24 AM, Arnaud Delobelle wrote: > Steven D'Aprano writes: > >> On Sat, 13 Dec 2008 19:17:41 +0000, Duncan Booth wrote: >> >>> I think you must have fallen asleep during CS101. The lower bound for >>> sorting where you make a two way branch at each step is O(n * log_2 n), >>> but if you can choose between k possible orderings in a single >>> comparison you can get O(n * log_k n). >> >> I think you might have been sleeping through Maths 101 :-) >> >> The difference between log_2 N and log_k N is a constant factor (log_2 k) >> and so doesn't effect the big-oh complexity. > > It affects it if k is a function of n. In this particular example, we > can set k=n so we get O(n). > > -- > Arnaud > -- > http://mail.python.org/mailman/listinfo/python-list > From bdesth.quelquechose at free.quelquepart.fr Thu Dec 11 14:53:40 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 11 Dec 2008 20:53:40 +0100 Subject: newbie question: if var1 == var2: In-Reply-To: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> Message-ID: <49417d7c$0$8491$426a74cc@news.free.fr> Steve Holden a ?crit : > Kirk Strauser wrote: >> At 2008-11-29T04:02:11Z, Mel writes: >> >>> You could try >>> >>> for item in fname: >>> item = item.strip() >> This is one case where I really miss Perl's "chomp" function. It removes a >> trailing newline and nothing else, so you don't have to worry about losing >> leading or trailing spaces if those are important to you. > > ... and it's so hard to write > > item = item[:-1] Steve, you should know better. It's item = item.rstrip('\r\n') From hniksic at xemacs.org Fri Dec 12 09:13:33 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 12 Dec 2008 15:13:33 +0100 Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> Message-ID: <87skotmqgi.fsf@mulj.homelinux.net> sturlamolden writes: > Actually I would consider this to be a bug. The tuple is immutable, > but no mutation of the tuple is ever attempted. That's a common misconception about how += works in Python. It simply *always* rebinds. Once you grok that, everything else follows. From google at mrabarnett.plus.com Sun Dec 7 19:47:25 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 08 Dec 2008 00:47:25 +0000 Subject: Python for kids? In-Reply-To: References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> Message-ID: <493C6E9D.1070500@mrabarnett.plus.com> Russ P. wrote: > Thanks to everyone who replied. The information was very helpful. > > Someone might want to consider putting a kids section on python.org > (if it doesn't have one already -- I didn't see one). > You have a kid. Why don't you? :-) From gagsl-py2 at yahoo.com.ar Thu Dec 18 20:21:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Dec 2008 23:21:06 -0200 Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> <7e23a789-84c3-47b9-b040-ca7dd062d058@a37g2000pre.googlegroups.com> Message-ID: En Thu, 18 Dec 2008 19:46:45 -0200, Aaron Brady escribi?: > On Dec 17, 7:16?pm, "Gabriel Genellina" > wrote: >> En Wed, 17 Dec 2008 22:46:32 -0200, Aaron Brady ? >> escribi?: >> >> >> >> > On Dec 17, 5:05?pm, "Gabriel Genellina" >> > wrote: >> >> En Wed, 17 Dec 2008 12:21:38 -0200, Jeremy Sanders ? >> >> escribi?: >> >> >> > It would be nice if Python created pipes that are properly ? >> >> inheritable by >> >> > default by child processes, as they're mostly used for IPC. >> >> >> I'd say it is a bug in os.pipe implementation; they should be ? >> >> inheritable ? >> >> by default, as in posix (after all, the code is in "posixmodule.c"). >> >> > The code looks like this: >> >> > ? ?ok = CreatePipe(&read, &write, NULL, 0); >> > ? ?Py_END_ALLOW_THREADS >> > ? ?if (!ok) >> > ? ? ? ? ? ?return win32_error("CreatePipe", NULL); >> > ? ?read_fd = _open_osfhandle((Py_intptr_t)read, 0); >> > ? ?write_fd = _open_osfhandle((Py_intptr_t)write, 1); >> >> > 'If lpPipeAttributes is NULL, the handle cannot be inherited.' ?You >> > could populate a 'SECURITY_ATTRIBUTES' structure, or call >> > DuplicateHandle on both of them. >> >> > A patch would look like this: >> >> > SECURITY_ATTRIBUTES sattribs; >> > sattribs.nLength = sizeof(sattribs); >> > sattribs.lpSecurityDescriptor = NULL; >> > sattribs.bInheritHandle = TRUE; >> > ok = CreatePipe(&read, &write, &sattribs, 0); >> >> Yes, that's exactly how os.popen does it (in posixmodule.c) >> >> > This still doesn't answer whether the file descriptor return by >> > '_open_osfhandle' can be inherited too. >> >> It doesn't matter. The OS only cares about file handles, not C RTL ? >> structures. > > Sorry for the multiple posts. File handles are inheritable by child > processes, if the permissions are right. File descriptors are not. > Is there a way that we can get the handles of a pipe into code, so > that we can pass them to a subprocess? On Windows, file handles are the real OS stuff, the "true" reference to an open file. File descriptors are not, they exist only to please the C runtime library. Programs not written in C (directly, or indirectly like Python) don't care at all about file descriptors. And in case one actually cares, there is _open_osfhandle in the C RTL (available as msvcrt.open_osfhandle from Python). A subprocess may inherit handles from its parent [there are two filters: the parameter "bInheritHandles" in the CreateProcess call provides global control, and individual handles can be made inheritable or not, before creating the new subprocess]. "Anonymous" pipes are good to replace stdin/stdout/stderr, because there is no need to explicitely communicate the handle value to the subprocess: one just replaces the corresponding handle with the desired pipe, and the subprocess might not even notice it. In case this is not enough, one might pass the handle (as a number) in the command line, but probably a "named pipe" would be better. As this is not transparent for the child process, one must explicitely code such things. > Will it take calling > 'CreatePipe' from ctypes directly if on Windows? Or can 'os.pipe' be > made to abstract that? If Windows can't inherit descriptors, > 'os.pipe' should return handles, and 'os.read' &co. should accept > them. I think the best way would be to modify os.pipe so it returns inheritable pipes, as it should have been from the beginning. > It is a fairly large patch. Not at all, you have already posted most of it. -- Gabriel Genellina From prasannaksahoo at gmail.com Thu Dec 4 23:23:30 2008 From: prasannaksahoo at gmail.com (pk sahoo) Date: Fri, 5 Dec 2008 09:53:30 +0530 Subject: Geeting the error Open failed: : Expected BOF record; found 0x3f3c Message-ID: hallo everybody, when i m running the command python runxlrd.py 3rows a.xls i m getting the following error === File: a.xls === *** Open failed: : Expected BOF record; found 0x3f3c what is the reason.... regards prasanna -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Mon Dec 15 03:54:15 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Dec 2008 08:54:15 GMT Subject: stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> Message-ID: <015612ac$0$20639$c3e8da3@news.astraweb.com> On Sun, 14 Dec 2008 21:12:13 -0800, Aaron Brady wrote: > On Dec 14, 8:18?pm, Roy Smith wrote: >> Steven D'Aprano wrote: >> > All the positive thinking in the world won't help you: >> >> > * make a four-sided triangle; >> >> > * split a magnet into two individual poles; >> >> These two are fundamentally different problems. >> >> The first is impossible by definition. ?The definition of triangle is, >> "a three-sided polygon". ?Asking for a "four-sided triangle" is akin to >> asking for "a value of three which is equal to four". >> >> The second is only "impossible" because it contradicts our >> understanding (based on observation) of how the physical universe >> works. ?Our understanding could simply be wrong. ?We've certainly been >> wrong before, and we will undoubtedly be proven wrong again in the >> future. ?When it comes to things like electromagnetic theory, it >> doesn't take too many steps to get us to the fuzzy edge of quantum >> physics where we know there are huge questions yet to be answered. > > I agree. Most of his examples were tautologies. The magnet one was the > exception. > > Then, to beat the O( n lg n ) limit, just break an assumption. No no no, that's solving a different problem! You're welcome to solve a different problem if you like, and sometimes doing so is very valuable: sometimes the original problem turns out not to be important after all. But don't pretend that it's the same problem. >> > * or design a comparison sort which does fewer than O(n*log n) >> > two-way comparisons in the worst case, or fewer than O(n) comparisons >> > in the best case. > > Make a three-way comparison, make a non-comparison sort, or make non- > random inputs. Again no. Multi-way comparisons merely change the base of the logarithm, which in turn merely changes the constant term. It's still O(n*log n). Non-comparison sorts are a useful technique, but it's changing the problem, and they are only useful in very limited circumstances. There's a good reason that most sort routines are based on O(n*log n) comparison sorts instead of O(n) bucket sorts or radix sorts. And the quip about non-random inputs just shows you don't understand the problem you're being asked to solve. O(n*log n) is for the least number of comparisons needed for the worst possible input. It's not for the best possible input, or random input, or the average number of comparisons, or any other measurement. You've misunderstood the question if you think "give better input" is the answer. And frankly, it's *easy* to come up with a comparison sort that has O(n) behaviour for the best possible input. Bubble sort has O(n) behaviour for input that is already sorted. Even the infamous bogosort has O(n) behaviour for the best possible input: def is_sorted(alist): """Return True if alist is sorted, otherwise False.""" for i in xrange(1, len(alist)): if alist[i-1] > alist[i]: return False return True def bogosort(alist): # Shuffle alist until it happens to be sorted while not is_sorted(alist): random.shuffle(alist) I believe bogosort has behaviour O(n!), which is far worse than merely exponential O(2**n) complexity. But when given already sorted input, the version of bogosort above is O(n). Even the archtypically Awful (not just Bad) algorithm is amazingly fast if you happen to give it the best possible input. (By the way, the above code is not suitable for use in production code. Due to limitations of the standard Python random number generator, not all permutations of lists larger than a certain size can be generated. The default random number generator for Python 2.5 is the Mersenne Twister, which has a period of 2**19937-1. But the number of permutations of n items is n!, and n! is greater than 2**19937-1 for n=2081 or more. That means that for any list with 2081 or more items, there is a finite probability that the above implementation of bogosort will merely cycle repeatedly over 2**19937-1 unsorted permutations and hence never terminate.) -- Steven From nospam at nospam.invalid Mon Dec 15 16:51:33 2008 From: nospam at nospam.invalid (Rahul) Date: Mon, 15 Dec 2008 21:51:33 +0000 (UTC) Subject: Insatlling python on compute-node-linux (Cray). Message-ID: Has anyone tried installing Python on Compute Node Linux (on a cray)? I was having trouble getting it running. I see that CNL does not support dynamic libraries but I am not sure what the best way then is to get Python running. Any tips? -- Rahul From malaclypse2 at gmail.com Tue Dec 2 12:50:52 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 2 Dec 2008 12:50:52 -0500 Subject: help me~!about base64 In-Reply-To: <0ff1ba7b-8a17-4647-99fc-9c8e32f83de7@g1g2000pra.googlegroups.com> References: <0ff1ba7b-8a17-4647-99fc-9c8e32f83de7@g1g2000pra.googlegroups.com> Message-ID: <16651e80812020950l27a97396reab835f55ec9e41f@mail.gmail.com> 2008/12/2 : > it's run ,Eric gave me error,the error is "'module' object has no > attribute 'decodestring'", Do you have your own base64.py (or base64.pyc) that's shadowing the standard module base64? Try this: >>> import base64 >>> print base64.__file__ C:\Python25\lib\base64.py >>> What does that say when you do it? -- Jerry From marduk at letterboxes.org Thu Dec 4 15:42:31 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Thu, 04 Dec 2008 15:42:31 -0500 Subject: "as" keyword woes In-Reply-To: <777c7313-267f-4dc2-b6fd-fad0c9714f41@l42g2000yqe.googlegroups.com> References: <777c7313-267f-4dc2-b6fd-fad0c9714f41@l42g2000yqe.googlegroups.com> Message-ID: <1228423351.7548.23.camel@brotherus.rdu.redhat.com> It's been a while so I can't remember, but it seems like "yield" was dropped in to python relatively quickly in 2.2. Was there a similar outrage when "yield" became a keyword? -a From saluk64007 at gmail.com Sun Dec 21 14:56:25 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Sun, 21 Dec 2008 11:56:25 -0800 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: On Sun, Dec 21, 2008 at 11:26 AM, r wrote: > I noticed when i mentioned "self" nobody wants to touch that subject. > There could be many reasons why... > > 0.) nobody but the 10 regulars i see here exists > 1.) nobody cares(doubt it) > 2.) nobody is brave enough to question it(maybe) > 3.) most people like to type self over and over again(doubt it) > 4.) most people here have given up on changing the BDFL's mind about > it. (good possibility) > 5.) this is a hot-button topic(no doubt in my mind!) It's a combination between (4) (5) and (6). 6 being, we have discussed "self" every week for the past 6 years, it hasn't changed yet, it's not going away, it's not a trivial "problem", deal with it. (0) is ridiculous, there are more than 10 respondents to this post alone. (1) - if nobody cared it wouldn't come up every week, but it's been discussed so much most are tired of it (2) - people question it all the time, usually people who are new to the language but not always. The discussion generally doesn't amount to anything (3) - It's not about wanting to type self over and over again, it's about being able to start with functions or start with classes, and easily refactor to the other way when needed; and never having a chance to wonder where a variable came from. There are ups and downs to self, it is generally more work to remove it than it is worth, what would the gain be? We'd be trading some ups and downs for some other ups and downs. And no, BDFL is not going to bend on self. He almost bent on the issue a few weeks ago, but his proposition merely changed some syntax - self was still there. On Sun, Dec 21, 2008 at 11:01 AM, Christian Heimes wrote: > We could have waited a few more months or even a few more years with a > 3.0 release. There is always - I repeat ALWAYS - work to do. For an open > source project like Python "release early, release often" works better. Good point, and I agree. It's too early for people to complain about python 3 being slow. It's also too both too late and too early to complain about things in python 3 that are thought of as a step backward. It's too late, because python 3 is out and it's already been changed! Things are not going to change back. Complaints are a bit useless at this point, except to let off steam. It's too early, because without using python3 in a major project, from the ground up, with the new features, the benefits or negatives for all of the changes cannot truly be known. From prologic at shortcircuit.net.au Mon Dec 15 08:01:01 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 15 Dec 2008 23:01:01 +1000 Subject: Having Issues with CMD and the 'python' command In-Reply-To: References: Message-ID: "cmd" has _nothing_ to do with Python. --JamesMills -- -- "Problems are solved by method" On Mon, Dec 15, 2008 at 10:51 PM, Lamonte Harris wrote: > Every time I start cmd on windows it requires me to "set > path=%path%;C:\python26" why? I'm getting annoyed... > > -- > http://mail.python.org/mailman/listinfo/python-list > > From bj_666 at gmx.net Sun Dec 21 11:09:04 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Dec 2008 16:09:04 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <015da0a4$0$20656$c3e8da3@news.astraweb.com> <6r6uvbFfb643U5@mid.uni-berlin.de> Message-ID: <6r7810Ffb643U6@mid.uni-berlin.de> On Sun, 21 Dec 2008 15:30:34 +0000, Duncan Booth wrote: > Marc 'BlackJack' Rintsch wrote: > >>> a+b+c+d might execute a.__add__(b,c,d) allowing more efficient string >>> concatenations or matrix operations, and a%b%c%d might execute as >>> a.__mod__(b,c,d). >> >> But that needs special casing strings and ``%`` in the comiler, because >> it might not be always safe to do this on arbitrary objects. Only in >> cases where the type of `a` is known at compile time and ``a % b`` >> returns an object of ``type(a)``. >> > I could be wrong, but I don't see that would be the case. > > I think it would be safe (in this hypothetical universe) any time that > 'a' had a method __mod__ which accepted more than one argument. And returns an object of ``type(a)`` or at least a "duck type" so that it is guaranteed that ``a.__mod__(b, c)`` really has the same semantics as ``a.__mod__(b).__mod__(c)``. For arbitrary objects `a`, `b`, and `c` that are not known at compile time, how could the compiler decide if it is safe to emit code that calls `a.__mod__()` with multiple arguments? Ciao, Marc 'BlackJack' Rintsch From oyvinrog at gmail.com Sat Dec 20 03:07:31 2008 From: oyvinrog at gmail.com (=?ISO-8859-1?B?2Hl2aW5k?=) Date: Sat, 20 Dec 2008 00:07:31 -0800 (PST) Subject: Jarow-Winkler algorithm: Measuring similarity between strings References: <4f351b3b-4da7-4fee-a1ac-c42179d430f5@s9g2000prm.googlegroups.com> Message-ID: <665bf3f7-ef74-4e59-bbac-cfbc12d4e81d@x16g2000prn.googlegroups.com> Thanks for the useful comments. On 20 Des, 01:38, John Machin wrote: > On Dec 20, 10:02?am, ?yvind wrote: > > > Based on examples and formulas fromhttp://en.wikipedia.org/wiki/Jaro-Winkler. > > For another Python implementation, google "febrl". > > > Useful for measuring similarity between two strings. For example if > > you want to detect that the user did a typo. > > You mean like comparing the user's input word with some collection of > valid words? You would need to be using something else as a quick-and- > dirty filter ... Jaro-Winkler is relatively slow. Do you have any alternative suggestions? > > > > > def jarow(s1,s2): > > > ? ? """ ?Returns a number between 1 and 0, where 1 is the most similar > > > ? ? ? ? example: > > > ? ? ? ? print jarow("martha","marhta") > > > ? ? ? ? """ > > ? ? m= jarow_m(s1,s2) > > ? ? t1 = jarow_t(s1,s2) > > ? ? t2 = jarow_t(s2,s1) > > ? ? t = float(t1)/float(t2) > > Huh? t1 and t2 are supposed to be counts of transpositions. So is t. > So how come t is a ratio of t1 to t2?? BTW, suppose t2 is zero. Good point. There should be only one jarow_t. > > Also as the Wikipedia article says, > it's not a metric. I.e. it doesn't satisfy dist(a, c) <= dist(a, b) + > dist(b, c). Its not a mathematical correct metric, but it is a useful heuristical metric. > > The above code is not symmetrical; jarow_m(s1, s2) does not > necessarily equal jarow_m(s2, s1). The article talks about one "m", > not two of them. > Hmm.. also a good point. I will make it count all the matches, not just the matches in s1. From rurpy at yahoo.com Tue Dec 16 01:22:44 2008 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Mon, 15 Dec 2008 22:22:44 -0800 (PST) Subject: ethical questions about global variables References: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> <0d9a9758-f338-4a58-971a-1bd29e40ce32@v5g2000prm.googlegroups.com> Message-ID: <298179e4-a33f-4fb2-8d57-e817293a1502@v5g2000prm.googlegroups.com> On Dec 15, 11:00 pm, ru... at yahoo.com wrote: > #my_module > class Config: pass > config = Config() > > def func1(state): > config.A = 1 > def func2(state) > config.A = 2 > def func3(state) > print config.A That of course should have been: def func1(config): config.A = 1 def func2(config) config.A = 2 def func3(config) print config.A From gruszczy at gmail.com Fri Dec 12 04:18:35 2008 From: gruszczy at gmail.com (=?UTF-8?Q?Filip_Gruszczy=C5=84ski?=) Date: Fri, 12 Dec 2008 10:18:35 +0100 Subject: Removing None objects from a sequence Message-ID: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> Hi! I would like to iterate over a sequence nad ignore all None objects. The most obvious way is explicitly checking if element is not None, but it takes too much space. And I would like to get something faster. I can use [ sth for sth in self.__sth if not sth is None ], but I don't know if that's the best way. I checked itertools, but the only thing that seemed ok, was ifilter - this requires seperate function though, so doesn't seem too short. How can I get it the shortest and fastest way? -- Filip Gruszczy?ski From bj_666 at gmx.net Sun Dec 14 04:19:45 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 14 Dec 2008 09:19:45 GMT Subject: Optimizing methods away or not? References: <0154b041$0$6988$c3e8da3@news.astraweb.com> Message-ID: <6qk1dhFcr01gU1@mid.uni-berlin.de> On Sun, 14 Dec 2008 07:41:55 +0000, Steven D'Aprano wrote: > I have a class with a method meant to verify internal program logic (not > data supplied by the caller). Because it is time-consuming but optional, > I treat it as a complex assertion statement, and optimize it away if > __debug__ is false: > > class Parrot: > def __init__(self, *args): > print "Initialising instance..." > if __debug__: > self.verify() # check internal program state, not args > if __debug__: > def verify(self): > print "Verifying..." > > > If I run Python normally, I can do this: > >>>> p = Parrot() > Initialising instance... > Verifying... >>>> p.verify() > Verifying... > > > and if I run Python with the -O flag, I get this: > >>>> p = Parrot() > Initialising instance... >>>> p.verify() > Traceback (most recent call last): > File "", line 1, in > AttributeError: Parrot instance has no attribute 'verify' > > > This is the behaviour I want, but I haven't seen it before in other > code. What do people think? Is it a good idea or a bad? > > If you think it is a bad idea to have verify disappear under > optimization, would you change your mind if it were called __verify > instead? > > > One possible alternative is to do something like this: > > class Parrot: > def __init__(self, *args): > print "Initialising instance..." > if __debug__: > self.verify() > def verify(self): > if __debug__: > print "Verifying..." > return None > # this is optional > else: > warnings.warn("verify() is a null op") > > > which now means that Parrot instances will always have a verify method, > even if it does nothing. I'm not sure I like that. What do others think? > Which do you consider better design? None of it. Why not simply: class Parrot: def __init__(self, *args): print "Initialising instance..." assert self.verify() def _verify(self): print "Verifying..." return None If you compile with -O the ``assert`` is optimized away. But you still can call `_verify()` at specific points even in optimized code if you want or need. Ciao, Marc 'BlackJack' Rintsch From R.Bauer at fz-juelich.de Wed Dec 17 15:48:36 2008 From: R.Bauer at fz-juelich.de (Reimar Bauer) Date: Wed, 17 Dec 2008 21:48:36 +0100 Subject: something else instead of PIL? Message-ID: Hi what has happened to PIL? No updates since two years. Or does one know an alternative lib for resizing images? cheers Reimar From sjmachin at lexicon.net Sat Dec 13 18:11:36 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 13 Dec 2008 15:11:36 -0800 (PST) Subject: Python 3.0 crashes displaying Unicode at interactive prompt References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> <49443531.5050304@v.loewis.de> Message-ID: On Dec 14, 9:20?am, "Martin v. L?wis" wrote: > >> This is intended behavior. > > > I see. That means that the behaviour in Python 1.6 to 2.6 (i.e. > > encoding the text using the repr() function (as then defined) was not > > intended behaviour? > > Sure. "Sure" as in "sure, it was not intended behaviour"? > This behavior has not changed. It still uses repr(). > > Of course, the string type has changed in 3.0, and now uses a different > definition of repr. So was the above-reported non-crash consequence of the change of definition of repr intended? From collin.day.0 at gmail.com Thu Dec 18 20:37:40 2008 From: collin.day.0 at gmail.com (Collin D) Date: Thu, 18 Dec 2008 17:37:40 -0800 (PST) Subject: Factoring Polynomials References: <269523e2-eba9-4b6b-b0fb-c5a7deb3ed76@o4g2000pra.googlegroups.com> Message-ID: <2980024c-e680-4010-b8c4-eccd7fd37b65@a37g2000pre.googlegroups.com> On Dec 18, 5:30?pm, "James Mills" wrote: > UPDATE: > > jmills at atomant:~/tmp$ cat polycalc.py > #!/usr/bin/env python > > from math import sqrt > > def f(a, b, c): > ? ? if (b**2 - (4 * a * c)) < 0: > ? ? ? ? return None, None # Can't solve > ? ? x1 = -b - (sqrt(b**2 - (4 * a * c)) / (2 * a)) > ? ? x2 = -b + (sqrt(b**2 - (4 * a * c)) / (2 * a)) > ? ? return x1, x2 > > print "Polynomial Solver..." > print > > while True: > ? ? a = float(raw_input("a: ")) > ? ? b = float(raw_input("b: ")) > ? ? c = float(raw_input("c: ")) > > ? ? x = f(a, b, c) > ? ? if None in x: > ? ? ? ? print "Can't solve!" > ? ? else: > ? ? ? ? print "x = (%0.2f, %0.2f)" % x > jmills at atomant:~/tmp$ ./polycalc.py > Polynomial Solver... > > a: 1 > b: 8 > c: 5 > x = (-11.32, -4.68) Ahh. Great.. that answers a lot of questions. Originally I was using just a = raw_input('a: ') And was getting errors because you cant perform mathmatical operations on strings. >.< Thanks again! From steve at REMOVE-THIS-cybersource.com.au Tue Dec 9 18:00:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Dec 2008 23:00:48 GMT Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> Message-ID: <014ef03e$0$20670$c3e8da3@news.astraweb.com> On Tue, 09 Dec 2008 05:48:29 -0800, Paul Boddie wrote: > Well, I think it's more interesting to explore the boundaries of what > can be done, to debunk notions that such things aren't being done in the > mainstream, and to examine whether they could benefit usability, than it > is to defer to the Zen of Python as some kind of prescriptive, > near-religious text at every turn. Go right ahead. Write your experimental language, and if people like it, they'll use it. That's what Guido did, all those years ago. But don't turn Python into a hodgepodge of "features" that most people consider misfeatures. The Zen certainly is prescriptive, but it's not "near-religious" in any sense. It's a distillation of probably hundreds of man-years of programming experience from people like Guido and Tim Peters into a small number of heuristics about the sorts of design decisions which have been proven to be successful in the past. I think it is childish to reject the Zen just because it's the Zen. Good advice doesn't cease to be good advice just because people tell you it's good advice, even if some people are awfully strident about it. -- Steven From gagsl-py2 at yahoo.com.ar Tue Dec 30 17:19:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Dec 2008 20:19:33 -0200 Subject: Read-Write Lock vs primitive Lock() References: <277c1be7-2560-4fd6-9610-0b4398dc3719@x16g2000prn.googlegroups.com> Message-ID: En Tue, 30 Dec 2008 06:16:23 -0200, k3xji escribi?: > As GLOBAL_LOOP_COUNT is 10000000, now this is making a bottleneck on > the readers. I had assumed that as everythread is given only 100 > bytecodes to execute, that it will be enough to have a 10000 value for > this number to let other rthread start() and try to acquire the lock. > But, Python undocumentedly, does not grab the GIL easily if a Lock is > held. This is strange for me. This has nothing to do with the GIL, nor undocumented behavior. If all threads are blocked waiting for the same lock, yielding the CPU has no effect, because nobody can progress until the lock is released. I'll ask you again: what is your use case? what do you want to do? what is a "reader" in your problem? what is a "writer"? what is the resource you want to protect using a lock? Different problems have different behaviors; for example, for reading/writing files, your model is basically wrong. > That may be the point. That is why I am trying to test this. When will > ReadWrite() lock permforms better over the primitive lock. By the way, > for the reference, the code in the recipe is used in CherryPy and > based on the Tanenbaum's book Operating Systems Design. Ah, good to know at least it has some background. Anyway, isn't a guarantee of correctness. By exampe, Tanenbaum's algorithm for the dining philosophers problem were (is?) flawed (according to W. Stallings). > I understand your point completely, but let's change anything inside > the loop. Just assume that we a thread that is supposed to read > something, and a thread that is supposed to write. If I create > thousands of readers, and if the operation is enormously huge > calculation(as Python does not grab GIL easily inside a Lock), then > this will create a bottlencek on readers. But, with ReadWrite Lock > this problem *SHOULD* be fixed and in my tests I see it is fixed, when > I increase the time spent in the loop in huge amounts. But why would you protect the whole long calculation with a lock? And why do you say "Python does not grab GIL easily inside a Lock", whatever that means? If you hold a scarce resource for a long time, this is likely to cause a bottleneck, and the language (be it Python or other) is mostly irrelevant here. > I had > assumed that Python will release GIL for other threads after 100 > bytecodes are executed by default. Yes. You can alter how often this occurs, using sys.setcheckinterval (the code I posted does that, just to see how results vary) > However, as I stated, when a Lock() > is held this is changing. I think this is because to avoid simple MT > problems for new programmers. Not sure. I will read threads.c for > information. No, it's always the same thing, locks don't affect this behavior. But as I said above, if no other thread can progress because all of them are waiting to acquire the same lock, you gain nothing by releasing the GIL. -- Gabriel Genellina From jgardner at jonathangardner.net Tue Dec 30 16:50:51 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Tue, 30 Dec 2008 13:50:51 -0800 (PST) Subject: Understanding search queries, semantics, and "Meaning" ...aren't we all looking for meaning? References: <82372457-2503-4682-96b3-37540328bf26@w39g2000prb.googlegroups.com> Message-ID: <94ab1653-c88d-4bad-a094-47d67e435618@w1g2000prm.googlegroups.com> On Dec 30, 12:35?pm, 5lvqbw... at sneakemail.com wrote: > I have Section 4.4.1 of SICP rattling around in my head (database > queries), and I'm trying to come up with a simple dictionary-based > database in Python to represent circuit diagrams. ?My main confusion > isn't one of implementation, but a matter of "big thinking", > fundamentally, about the problem. Please don't suggest using a SQL > library, as I'm looking to learn to fish, so to speak, and to learn a > bit about the biology of fish. > I'm going to break rule #1 of your requirements but in an unexpected way. Rather than studying PostgreSQL, MySQL, or Oracle, why don't you crack open the topic of relational database theory and relational algebra? That should help with the "big thinking" bit in the same way understanding 1+1 helps you understand how to add any two numbers together. No, SQL is not the be-all-end-all of relational theory. Yes, it does a pretty dang good job at it, though, which is why it is still around. > I've subclassed dict to hdict ("hashable dict") and rewritten the > __hash__ function so I can include a dict into a set. Thanks to a > previous poster here for providing that suggestion. > > A circuit component looks like this for example: > > comp1 = hdict(value=1e-6, footprint='0402', vendor='digikey') > comp2 = hdict(value=10e3, footprint='0603', vendor='mouser') > etc, etc. > > The database holds the values like this: > db = dict() # normal dict > db['value'] = ([1e-6, 10e3], [comp1, comp2]) #ordered set for fast > lookup/insertion > db['footprint'] = {'0402':set[comp1], '0603':comp2} # unordered uses > normal dict for fast lookup > db['vendor'] = {'digikey':[comp1], 'mouser':[comp2]} > > So basically the keys are the component parameters, and the values is > the list of components with that value. ?Stuff that is comparable is > ordered; stuff that is discrete is not ordered, using either 2-tuples > or dicts, respectively. > > This allows extremely fast lookup of components based on their > properties, with O(1) performance for non-ordered stuff, and O(log n) > performance for ordered stuff (using bisect methods). ?The set > operations are extremely fast, so I can do AND and OR operations on > compound queries of this nature without worry. > > I need this speed not so much for selecting components when the user > types in a query, but for when the mouse is hovering over the > schematic and I need things to light up underneath, if the GUI is > generating hundreds of mouse messages per second, and for inspector > windows to appear quickly when you click, etc. ?If you have ever used > Altium, you can see how effective this is in terms of creating a good > interactive user experience. > OK, turn it around in your head. Consider the indexes you built above as yet another table. Consider what a table or a database really is. When you see how they are all really the same thing, either you've mastered relational algebra of you've seen the big picture. Kind of like the cons cell being enough to describe any data structure in the universe, a table is enough to describe everything in the relational world. > My question is what happens when I choose to search for NOT > footprint='0402'. > > Should this return a blank list? This happens by default., and is in > fact true: a blank list satisfies "not anything" actually. > Should this return everything that is NOT footprint 0402 (ie returns > 0603 components)? ?This *strongly implies* a pre-selection of *all* > objects before performing the negating function, or of looking at the > ordering of other queries in the overall search term, and then > applying NOT to the results of another query. > > But I'm suspicious of a brute force preselection of all objects > whenever I see a NOT, and anyway it messes up the clean query/combiner > method of search I'm doing, and it requires an implied sequence of > search, where I'm pretty sure it should not rely on sequencing. ?Even > though this is single threaded, etc., the semantics of the query > should not rely on ordering of the search term: > > footprint='0402' and NOT vendor='mouser' should return the same as > NOT vendor='mouser' and footprint='0402'. > > So this is my philosophical quandary. ?I'm not sure what the correct > thing is. ?In SICP they are using nondeterministic stuff which I don't > quite get, so it's hard to follow. ?Also they are not using > dictionaries and hashes, so I'm not sure if their generate-and-test > method would work here anyway. ?Generate-and-test seems extremely > inefficient. > > Can a wise guru please enlighten me? > (I don't think I qualify as a guru, but I think I see how I can help.) In a typical SQL database, when you type in "SELECT foo FROM bar WHERE baz='bo'", you are not writing a program, at least not in the sense of Python or C or Java or Perl where you give instructions on HOW to run the program. You are writing a program in the sense of Lisp or Scheme or Haskell in that you are giving instructions on WHAT the program is. The database doesn't, at least shouldn't, read in all the rows in a table and then start going through the process of elimination removing rows it doesn't want to think about. That's highly inefficient, of course. Instead, it transforms the query (the WHAT) into a set of procedures that describe HOW to get the result. That step---taking the definition of the program and turning it into actual instructions on HOW to run the program---is the compilation and optimization phase. It's a very hard step to do, but no harder than the process Python goes through taking files of bytes and converting them into Python bytecode. Oh, by the way, this step is nondeterministic. Why? Well, no one can really say what the BEST way to run any sufficiently complicated program is. We can point out good ways and bad ways, but not the best way. It's like the travelling salesman problem in a way. Now, that "hard stuff" you are glossing over in SICP is the IMPORTANT stuff. It's the WHOLE POINT of that section. Stop glossing over it. Keep working at it bit by bit until you understand it. You, as a programmer, will be infinitely better for it. When you understand it, you will really unlock the full potential of Python and Scheme and whatever other language is out there because you will see how to go from HOW languages to WHAT languages. Programmers who can write compilers are GOOD programmers. Programmers who can understand someone else's compilers are even better. On Python-specific stuff: For a moment, forget about Python and hashes and dicts and arrays and lists and such. Focus only on the cons cell and Scheme. When you have mastered those concepts, you will see how to efficiently use the Python data structures and how to simplify the Scheme code into Python. Right now you are doing a bit of premature optimization. That's my semi-guru advice. From gagsl-py2 at yahoo.com.ar Thu Dec 18 19:11:12 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Dec 2008 22:11:12 -0200 Subject: importing csv file into sqlite References: <21067453.post@talk.nabble.com> Message-ID: En Thu, 18 Dec 2008 04:17:47 -0200, James Mills escribi?: > How big ? When size is important in data > processing, you should _never_ try to > load it all up at once. Use filters... But your code does *exactly* that, it reads the whole file in memory: > def mkBuffer(fd): > buffer = StringIO() > buffer.write(fd.read()) > ... That mkBuffer function has no useful purpose IMHO, just remove it. -- Gabriel Genellina From max at alcyone.com Fri Dec 12 04:26:54 2008 From: max at alcyone.com (Erik Max Francis) Date: Fri, 12 Dec 2008 01:26:54 -0800 Subject: Removing None objects from a sequence In-Reply-To: References: Message-ID: Filip Gruszczy?ski wrote: > I would like to iterate over a sequence nad ignore all None objects. > The most obvious way is explicitly checking if element is not None, > but it takes too much space. That doesn't make much sense; why would iterating over the sequence take more _space_? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Life is a gamble so I should / Live life more carefully -- TLC From philr at aspexconsulting.co.nz Sun Dec 28 18:18:26 2008 From: philr at aspexconsulting.co.nz (Phil Runciman) Date: Mon, 29 Dec 2008 12:18:26 +1300 Subject: game engine (as in rules not graphics) In-Reply-To: <402f625f-b835-4cb8-bcea-523756c489ca@g39g2000pri.googlegroups.com> Message-ID: See: Chris Moss, Prolog++: The Power of Object-Oriented and Logic Programming (ISBN 0201565072) This book is a pretty handy intro to an OO version Prolog produced by Logic Programming Associates. Prolog is a wonderful tool for such things as working out a factory layout for new car production or for creating an expert system for choosing antibiotics for treating a condition. It has even been used for helping producing immigration legislation and then for providing a system for checking eligibility (other than can you survive in a desert and get through barbed wire!) One person used is to teach primary school children English grammar. The children created their own grammar rules and checked them out using Prolog. Their understanding of english grammar exceeded many university graduates after this exercise. (Google Dr. Richard Ennals). FWIW. Declaration of interest: Chris Moss is my wife's first cousin. -----Original Message----- From: Aaron Brady [mailto:castironpi at gmail.com] Sent: Sunday, 28 December 2008 1:22 p.m. To: python-list at python.org Subject: Re: game engine (as in rules not graphics) On Dec 27, 3:02?pm, Martin wrote: > Hello, > > I'd like to get in touch with game development a bit. I'm not talking > about graphics but rather the game rules itself. Something > likehttp://en.wikipedia.org/wiki/Monopoly_(game)#Rules, is there even > a general approach to that or should I just go sketch up my rules and > try to implement them. Being totally new to this topic I don't quite > now what to search for to get some decent results that let me make a > mental link between game rules and what the best practices are to > implement them in python (or any other programming language) > > thanks, > martin Not my expertise but here are my $0.02. You are looking for ways to represent rules: buying a house is legal in such and such situation, and the formula for calculating its price is something. You want "predicates" such as InJail, OwnedBy, Costs. Costs( New York Ave, 200 ) InJail( player2 ) OwnedBy( St. Charles Ave, player4 ) LegalMove( rolldie ) LegalMove( sellhouse ) There are rule-based languages out there, such as Prolog. They are equally expressive as Python (you can write a Turing machine in them), but they are more convenient for representing rules in a prog. language. Predicates are more or less equivalent to positive assertions about something. NewYorkAve.cost= 200 player2.injail= True... rolldie.islegal= True Some predicates have to be calculated, rather than stored, but Python descriptors go easy on you for that. Someone else will have to tell you how rule-based programming measures up against object-oriented programming. From walterbyrd at iname.com Mon Dec 22 17:23:45 2008 From: walterbyrd at iname.com (walterbyrd) Date: Mon, 22 Dec 2008 14:23:45 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <494fef38$0$12781$426a74cc@news.free.fr> Message-ID: On Dec 22, 11:50?am, Bruno Desthuilliers wrote: > > When it comes to web development, it seems to me that ruby > > (because of rails) is far more popular > > s/popular/hyped/ I'm not so sure. Go to dice.com, enter "ruby rails" no quotes, search all words, job titles only - I got 86 hits, and another five hits when I searched for "RoR." Do the same search, but substitue "python django" for "ruby rails" and I get 3 hits. Doing the search for just "ruby" and I get 121 hits. Doing the search for just "python" and I get 61 hits. Just "rails" and get 94 hits, just "django" and I get 4 hits. Not scientific, but there is substantial difference. > Fooled by version numbers ? No, but I am giving django the benefit of the doubt. The django project told people all along that django was not to be considered production ready before 1.0. I will accept that some people decided to wait until 1.0 came out to do any production development. Maybe django is only lagging because 1.0 just came out? > My actual CTO is a big Ruby/Rails fan, yet he settled on Python/Django > for our current 'big' project. Wonder why ? Not knowing much about RoR: yes, I wonder why? Is it because python has a cleaner syntax? Or what? From zxo102 at gmail.com Thu Dec 25 02:29:08 2008 From: zxo102 at gmail.com (zxo102) Date: Wed, 24 Dec 2008 23:29:08 -0800 (PST) Subject: How to display Chinese in a list retrieved from database via python Message-ID: Hi, I retrieve some info in Chinese from postgresql and assign it to a variable 'info' defined in javascript of a html page: var info = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce \xc4'] But I want it to be var info = ['??','??','??'] since in html pages (via javascript), the items in chinese out of the former :['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4'] can not be displayed correctly when it is inserted into a html page. If the list is var info = ['??','??','??'] , then everything works fine. Anybody knows how to solve this problem? Thanks in advance. zxo102 From Jiandong.Ge at gmail.com Wed Dec 10 15:16:56 2008 From: Jiandong.Ge at gmail.com (JD) Date: Wed, 10 Dec 2008 12:16:56 -0800 (PST) Subject: How to pass out the result from iterated function Message-ID: I got a iterated function like this: def iterSomething(list): has_something = False for cell in list: if something in cell: has_something = True output = something if has_something: iterSomething(output) else: final_out = outupt The problem is how can I read this final_out outside of the function. I tried the global statement, it seems not work. Any idea? JD From jaume.bonet at gmail.com Wed Dec 10 18:09:48 2008 From: jaume.bonet at gmail.com (Jaume Bonet) Date: Wed, 10 Dec 2008 15:09:48 -0800 (PST) Subject: Memory leak when using a C++ module for Python Message-ID: Hi, I'm pretty new in python programming. I've been developing a C++ module for a python application that simply gets the information from python, makes the last processing (which is very time consuming -that's why I make it in C++-). When I test the code from C++ each time I delete a vector the consumed memory decreases, but it does not happen when the module is called from python. The memory is kept... Once the data comes from python, the PyObjects are read and its information passed to C objects (that is done just once) and all the rest of the processing is done with those objects. I've read that the even when you delete the content of the vectors the memory is not freed when you are working with python. Is that so? Is there any way to really free that memory? Thanks, J From steve at REMOVE-THIS-cybersource.com.au Sat Dec 13 11:21:22 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Dec 2008 16:21:22 GMT Subject: Removing None objects from a sequence References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> <4942E668.5030100@tim.thechases.com> <01538f0c$0$6988$c3e8da3@news.astraweb.com> <234b9a34-52e3-42c3-968c-f50983e51c68@e1g2000pra.googlegroups.com> Message-ID: <0153d884$0$6988$c3e8da3@news.astraweb.com> On Sat, 13 Dec 2008 06:00:09 -0800, bearophileHUGS wrote: > Steven D'Aprano: >> The algorithm is unclear: try explaining what you are doing in English, >> and see how difficult it is. > > That algorithm is a standard one, and quite clear. Any programmer worth > his/her/hir salt has to be able to understand that. I didn't say it can't be understood. But please, if you think it is quite clear, go ahead and explain how it works, and how you know the algorithm is correct and there are no odd corner cases where it fails. As my comp sci lecturer used to say, "prove the algorithm is correct". Remember, Terry made a specific claim: the algorithm is simpler and cleaner than Tim's copy-the-values-that-aren't-None solution. It's not just clear, it's significantly clearer: "No, making a filtered copy that is then copied back before being deleted is algorithmically much messier. My code does the minimum work necessary and is algorithmically cleaner." Do you agree with Terry's claim? -- Steven From glenn.chappell at gmail.com Mon Dec 22 16:41:56 2008 From: glenn.chappell at gmail.com (Glenn G. Chappell) Date: Mon, 22 Dec 2008 13:41:56 -0800 (PST) Subject: python3 urlopen(...).read() returns bytes Message-ID: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> I just ran 2to3 on a py2.5 script that does pattern matching on the text of a web page. The resulting script crashed, because when I did f = urllib.request.urlopen(url) text = f.read() then "text" is a bytes object, not a string, and so I can't do a regexp on it. Of course, this is easy to patch: just do "f.read().decode()". However, it strikes me as an obvious bug, which ought to be fixed. That is, read() should return a string, as it did in py2.5. But apparently others disagree? This was mentioned in issue 3930 ( http://bugs.python.org/issue3930 ) back in September '08, but that issue is now closed, apparently because consistent behavior was achieved. But I figure consistently bad behavior is still bad. This change breaks pretty much every Python program that opens a webpage, doesn't it? 2to3 doesn't catch it, and, in any case, why should read() return bytes, not string? Am I missing something? By the way, I'm running Ubuntu 8.10. Doing "python3 --version" prints "Python 3.0rc1+". From has.temp3 at virgin.net Sun Dec 7 13:06:11 2008 From: has.temp3 at virgin.net (has) Date: Sun, 7 Dec 2008 10:06:11 -0800 (PST) Subject: Number of Python 3.x packages at the PyPI References: <9c1ab0f3-6686-4c0f-8a6c-12e20539f354@41g2000yqf.googlegroups.com> <493b954e$0$4021$9b622d9e@news.freenet.de> Message-ID: <2d656e64-deff-40ed-8066-57b6f8874ec4@b38g2000prf.googlegroups.com> On 7 Dec, 09:20, "Martin v. L?wis" wrote: > excor... at gmail.com wrote: > > Are there any special arrangements necessary for PyPI packages which > > have both a Python 2.x version and a Python 3.x version? > > So far, no such need has been identified. I've had to fork my appscript project's codebase in order to add support for Python 3.x. I would like to distribute both 2.x and 3.x versions under the same package name for obvious reasons. This isn't a problem with eggs as the Python version number is included in each egg's name, but what about source distributions where both filenames are exactly the same (appscript-0.19.0.tar.gz)? Thanks, has -- Control AppleScriptable applications from Python, Ruby and ObjC: http://appscript.sourceforge.net From robin at reportlab.com Mon Dec 22 07:32:27 2008 From: robin at reportlab.com (Robin Becker) Date: Mon, 22 Dec 2008 12:32:27 +0000 Subject: excluding non-data files from distutils package_data Message-ID: <494F88DB.8060408@chamonix.reportlab.co.uk> Is there a convenient way in a distutils setup to determine which files will be included as part of the package setup. The need arises because I want to exclude those files from the package_data argument after doing a recursive sweep of the package folder to locate all files inclding .py etc etc. -- Robin Becker From pavlovevidence at gmail.com Mon Dec 29 22:32:48 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 29 Dec 2008 19:32:48 -0800 (PST) Subject: Python module import loop issue References: <02bc8567-695a-4277-9698-a95549a0bc98@w39g2000prb.googlegroups.com> <4a0557b7-e901-49ff-b4db-53f4d8a7c0f8@r40g2000yqj.googlegroups.com> Message-ID: Gabriel Genellina wrote: > En Mon, 29 Dec 2008 19:47:51 -0200, Carl Banks > escribi?: > > On Dec 29, 10:51?am, Kottiyath wrote: > > >> Module Factory: > >> A1Factory: {'B1Tag':1.1.B1, 'C1Tag':1.2.C1, 'D1Tag':1.3.D1'} > >> A2Factory: {'B2Tag':2.1.B2, 'C2Tag':2.2.C2, 'D2Tag':2.3.D2'} > >> > >> But, since Module requires objects of B1, C1 etc, it has to import > >> Factory. > >> Now, there is a import loop. How can we avoid this loop? > > > > I'm going to suggest three ways: a straightforward, good-enough way; a > > powerful, intelligent, badass way; and a sneaky way. > > In Python 2.6 (and 3.0) there is a fourth way: class decorators. > > > 1. The straightforward, good-enough way > > > > Define functions in Factory.py called register_A1_subclass and > > register_A2_subclass, then call them whenever you create a new > > subclass. > > Class decorators are a clean variant of this approach (in my opinion). > > > package1/module1.py: > > ----------------------------- > > import Factory > > > > class B1(A1): > > # define class B1 here > > > > Factory.register_A1_subclass("B1Tag",B1) > > ----------------------------- > > That would become: > > @Factory.register_A1_subclass("B1Tag") > class B1(A1): > ... > > (for an adequate variant of register_A1_subclass). The advantage is that > the "register" stuff appears prominently near the name of the class, and > there is no need to repeat the name. > Also, "B1Tag" can be left out, if it is stored as a class attribute of B1 > (in some cases using __name__ is enough) Thanks for the additional suggestion. > > 2. The powerful, intelligent, badass way > > > > Metaclasses. I would guess you do not want to do this, and I wouldn't > > recommend it if you haven't studied up on how metaclasses work, but > > it's a textbook example of their usefulness. If you expect to use > > factory functions like this a lot, it might be worth your while to > > learn them. > > A problem with metaclasses is when you have intermediate subclasses that > are not meant to be registered, but the metaclass applies equally to all > of them. Not the way I wrote it. If you'll note, the metaclass only added the class to the factory map if a tag attribute was defined in the class dict. Carl Banks From clp at rebertia.com Thu Dec 25 18:39:23 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 25 Dec 2008 15:39:23 -0800 Subject: python interpreter black window In-Reply-To: References: Message-ID: <47c890dc0812251539r5fd68f1brc25159ddb6e3d0d5@mail.gmail.com> On Thu, Dec 25, 2008 at 3:32 PM, Gandalf wrote: > I use WX gui so the user doesn't actually need it, Is their any way to > hide it? Make sure your Python program is run by pythonw.exe as opposed to python.exe pythonw.exe exists specifically for the purpose of suppressing the DOS Box on Windows. Merry Christmas, Chris -- Follow the path of the Iguana... http://rebertia.com From saju.pillai at gmail.com Wed Dec 31 09:55:59 2008 From: saju.pillai at gmail.com (Saju Pillai) Date: Wed, 31 Dec 2008 06:55:59 -0800 (PST) Subject: select.select and socket.setblocking References: <495a661d$0$11384$5fc30a8@news.tiscali.it> <495b34d8$0$11387$5fc30a8@news.tiscali.it> <3652a957-eec6-494c-bd37-d150018bc0ed@p2g2000prf.googlegroups.com> <495b8653$0$11383$5fc30a8@news.tiscali.it> Message-ID: <4b7fdd17-c9c0-4970-9bf8-e596c939e23e@d42g2000prb.googlegroups.com> On Dec 31, 7:48?pm, Francesco Bochicchio wrote: > < ... > > > >> Uhm. In my experience, with TCP protocol recv only returned less than > >> the required bytes if the remote end disconnects. I always check the > > > What if the sending end actually sent less than you asked for ? > > > -srp > > In blocking mode and with TCP protocol, the recv waits until more bytes > are received - ?mixing up the next message with the previous one and Is this correct ? IIRC even in blocking mode recv() can return with less bytes than requested, unless the MSG_WAITALL flag is supplied. Blocking mode only guarantees that recv() will wait for a message if none is available - but not that it *will* return the number of bytes requested. -srp > then loosing the 'sync' and being unable to interpretate the received > data - ?or the remote end disconnects. > > Yes this is bad, ?and is a good reason why socket receive should be > handled ? in non-blocking mode if you receive data from untrusted > sources. But luckily for me, as I said in the other post, I used socket > mostly to communicate between specific applications on a private LAN or > WAN, so I could afford to ignore the problem. > > Ciao > ---- > FB From lists at cheimes.de Wed Dec 3 17:59:23 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 03 Dec 2008 23:59:23 +0100 Subject: building an extension module with autotools? In-Reply-To: <4936FD1C.1010700@ghaering.de> References: <4936FD1C.1010700@ghaering.de> Message-ID: Gerhard H?ring wrote: > #!/bin/sh > python setup.py build > cp build/lib.*/*.so . > python test.py "python setup.py build_ext -i" is your friend. It installs the extensions inplace. No need for cp here. :) Christian From geekmail at usenot.de Sun Dec 7 14:17:00 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sun, 7 Dec 2008 20:17:00 +0100 Subject: Guido's new method definition idea References: <493a9fed$0$18973$426a34cc@news.free.fr> <493c1ff6$0$4942$426a34cc@news.free.fr> Message-ID: <20081207201700.6ade1f33@usenot.de> On Sun, 07 Dec 2008 19:13:18 +0100 Bruno Desthuilliers wrote: > > and friendlier to newbies. > > I'd rather say "more acceptable to java-brainwashed developpers". Why would you rather be unfriendly and seed ambivalence? I do see the fun in a little Python snobbism, but ... come on. /W -- My real email address is constructed by swapping the domain with the recipient (local part). From rt8396 at gmail.com Sun Dec 21 16:43:23 2008 From: rt8396 at gmail.com (r) Date: Sun, 21 Dec 2008 13:43:23 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> <494ea9a5$0$24542$426a34cc@news.free.fr> Message-ID: <4a00e9c5-89a5-4910-b274-659aea0e2b78@s36g2000vbp.googlegroups.com> Bruno, I thought i had already gone up, up, and away to your kill filter. hmm, guess you had a change of heart ;D From benjamin.kaplan at case.edu Wed Dec 3 01:01:13 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 3 Dec 2008 01:01:13 -0500 Subject: HELP!...Google SketchUp needs a Python API In-Reply-To: <36056737-3c78-499a-a81d-f6241e904460@t11g2000yqg.googlegroups.com> References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> <00ab327a-c3fc-4b15-a084-4f8c6aed6a8e@o2g2000yqd.googlegroups.com> <8119ab7e-09f1-44de-bdbc-8fdff969d9e4@33g2000yqm.googlegroups.com> <36056737-3c78-499a-a81d-f6241e904460@t11g2000yqg.googlegroups.com> Message-ID: On Tue, Dec 2, 2008 at 10:06 PM, r wrote: > "If we can laugh what else would we do" > > I'd like to touch also on some comments by ajaksu: > [ajaksu] > I'd like to try hacking some form of Python to work in SketchUp (on > top of Ruby, that is). Now, why won't I try to? I'm a Linux user and > we don't get a SU version. So much for FREEDOM. BTW, some things in > SU > have encrypted Ruby code behind them :) > [/ajaksu] > > You CAN use SketchUp on Linux...ajaksu...thru Wine, but I know this is > not good enough. I would love to see FULL SketchUp support for linux > and I HAVE made my voice heard. I urge you brother to make make your > voice heard also. > > Go to this thread and let your voice be heard: > > http://groups.google.com/group/sketchupsuggestions/browse_thread/thread/7c0c810b88ad4d5/dfabe1e01bab12b3?hl=en#dfabe1e01bab12b3 > > This is the reason...amoung many others...that Linux has yet to take > any noticable market from MS. Linux could...If the Linux devolpers > would ban together and unite to make package managment and portability > between all *nix's universal, OR one great linux distro that the > average dummy can use(ubuntu looks promising, but still has a long way > to go)...compete with microsoft on a grand level. We have to steal the > idiots from under microsoft's feet, and they will come crumbling down. > But as long as a poor n00b installs his shiny new *nix system and > can't even connect to the network to see the latest janet jackson > "wardrobe malfunction", or fiqure out how to mount a flash drive, > Linux will be nothing more than our beloved oddessy. > > There will NEVER be good support on linux for most applications, > games, etc... Until people start to get behind linux and support it. > Now you say, well i don't have time to support this, my life is too > busy, my back hurts. I say stop making excuses. You DON'T have to > invest your life, just simply make your voice heard.(myself and other > dedicated people will tow the load). But at least get off your bum and > do something. > > It's time to change the world, the hour is upon us, Microsoft is > asleep at the wheel, the time for revolution is NOW! > > -- > http://mail.python.org/mailman/listinfo/python-list > The Ubuntu devs are aware of this issue and a bug report has been filed. https://bugs.launchpad.net/ubuntu/+bug/1 -------------- next part -------------- An HTML attachment was scrubbed... URL: From miki.tebeka at gmail.com Mon Dec 15 20:51:25 2008 From: miki.tebeka at gmail.com (Miki) Date: Mon, 15 Dec 2008 17:51:25 -0800 (PST) Subject: parse C expression? References: Message-ID: <132711c2-257f-4d86-93fa-91c89db7733a@g1g2000pra.googlegroups.com> > Is there a standard module available that lets me parse a syntax like "C" > with numbers, operators, braces, variables and function calls? There is a C compiler implemented with PLY somewhere. > I'd like to use this to parse an own kind of configuration language > and preferred would be just standard modules. ?Is there something > available that is maybe based on shlex? I usually use Python as my configuration syntax, see http://pythonwise.blogspot.com/2006/05/using-python-syntax-in-configuration.html (shameless plug). Beware that this has security implications, I use it only in internal applications. HTH, -- Miki http://pythonwise.blogspot.com From arkanes at gmail.com Thu Dec 4 11:39:26 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 4 Dec 2008 10:39:26 -0600 Subject: "as" keyword woes In-Reply-To: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> Message-ID: <4866bea60812040839q3df3d723j3baeeb649c814067@mail.gmail.com> On Wed, Dec 3, 2008 at 11:42 PM, Warren DeLano wrote: >> > Why was it necessary to make "as" a reserved keyword? >> >> I can't answer for the Python developers as to why they *did* make it >> a reserved word. >> >> But I can offer what I believe is a good reason why it *should* be a >> reserved word: Because simple is better than complex, and special >> cases aren't special enough to break the rules. > > So you prefer broken code to broken rules, eh? Your customers must love > that! This is exactly the kind of ivory-tower thinking I feared might > be behind the decision (form over function, damn the users to hell, > etc.) > Honestly, based on the content and tenor of this post I think this is Yet Another Python Troll (the ivory tower reference, as well as the abrupt shift from complaining about keywords to multiprocessing), I have to point out that Python does add new keywords, it has done so in the past, and there was a considerable amount of warning, including an automated deprecation warning in the very version you are going to recommend to your "customers' (I don't actually think you have any customers). If you suppressed or ignored the deprecation warning that all your code has been generating for at least 2 years it's pretty damn ballsy to come here and tell everyone how *Python* is doing something wrong. From jstroud at mbi.ucla.edu Sun Dec 7 17:12:10 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 07 Dec 2008 14:12:10 -0800 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: <_SX_k.10055$YU2.2013@nlpi066.nbdc.sbc.com> James Stroud wrote: >[cast to bool] for numpy works like a unary ufunc. Scratch that. Not thinking and typing at same time. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From desas2 at gmail.com Mon Dec 1 12:20:56 2008 From: desas2 at gmail.com (desas2 at gmail.com) Date: Mon, 1 Dec 2008 09:20:56 -0800 (PST) Subject: python 2.5.2 or Python 2.6 compilation problem on AIX 5.3 Message-ID: <26fbc708-1b64-4271-9c7d-4394aa281f47@j39g2000yqn.googlegroups.com> Hello: I am trying to compile Python 2.5.2 on AIX 5.3 with gcc 4.2.3. I am getting following error. (I also tried Python 2.6 with same error) creating build/temp.aix-5.3-2.5/share/tmhsdsd2/tmp/Python-2.5.2/ Modules gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - Wstrict-prototypes -I. -I/share/tmhsdsd2/tmp/Python-2.5.2/./Include - I. -IInclude -I./Include -I/usr/local/include -I/share/tmhsdsd2/tmp/ Python-2.5.2/Include -I/share/tmhsdsd2/tmp/Python-2.5.2 -c /share/ tmhsdsd2/tmp/Python-2.5.2/Modules/_struct.c -o build/temp.aix-5.3-2.5/ share/tmhsdsd2/tmp/Python-2.5.2/Modules/_struct.o creating build/lib.aix-5.3-2.5 ./Modules/ld_so_aix gcc -pthread -bI:Modules/python.exp build/ temp.aix-5.3-2.5/share/tmhsdsd2/tmp/Python-2.5.2/Modules/_struct.o -L/ usr/local/lib -lpython2.5 -o build/lib.aix-5.3-2.5/_struct.so collect2: library libpython2.5 not found *** WARNING: renaming "_struct" since importing it failed: 0509-022 Cannot load module build/lib.aix-5.3-2.5. 0509-026 System error: A file or directory in the path name does not exist. error: No such file or directory make: 1254-004 The error code from the last command is 1. Stop. I am not able to find the problem. I would appreciate, if you could help. I used following command line options to confugure. ./configure --prefix=/home/hci/dinakar/python25 -enable-shared --with- gcc Thank you. Dinakar From __peter__ at web.de Mon Dec 8 05:40:15 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 08 Dec 2008 11:40:15 +0100 Subject: ftp retrlines with re... References: Message-ID: isabellknauer at googlemail.com wrote: > filelist=server.retrlines('LIST') This does not do what you think it does. >>> help("ftplib.FTP.retrlines") gives """ Help on method retrlines in module ftplib: retrlines(self, cmd, callback=None) unbound ftplib.FTP method Retrieve data in line mode. The argument is a RETR or LIST command. The callback function (2nd argument) is called for each line, with trailing CRLF stripped. This creates a new port for you. print_line() is the default callback. """ I. e. you would need something like lines = [] server.retrlines("LIST", lines.append) to store the method's output in a variable instead of printing it to stdout. But try files = server.nlist() instead which gives you a list of filenames. Peter PS: Remember to take Gabriel's advice to heart for your next question. From istvan.albert at gmail.com Fri Dec 5 23:09:39 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Fri, 5 Dec 2008 20:09:39 -0800 (PST) Subject: slow Python 3.0 write performance? References: Message-ID: On Dec 5, 3:41?pm, Christian Heimes wrote: > I've fixed the read() slowness yesterday. You'll get the fix in the next > release of Python 3.0 in a couple of weeks. Does this fix speed up the write() function as well? A previous poster suggested that in this case the slowdown is caused by the new io code being written in python rather than C. Istvan From gagsl-py2 at yahoo.com.ar Wed Dec 17 20:28:04 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 17 Dec 2008 23:28:04 -0200 Subject: C API and memory allocation References: Message-ID: En Wed, 17 Dec 2008 22:51:03 -0200, Aaron Brady escribi?: > On Dec 17, 6:42?pm, "Gabriel Genellina" > wrote: >> En Wed, 17 Dec 2008 21:35:04 -0200, Floris Bruynooghe ? >> escribi?: >> > But how can python now know how long to keep that buffer object in >> > memory for? >> >> It doesn't - *you* have to ensure that the original string object isn't >> ? >> destroyed (by example, incrementing its reference count as long as you ? >> keep the pointer), or copy the string contents into your own buffer. > > I missed something. How did you get a reference to the original > string object, with which to increment its reference count? From the original arguments to the function -- the first argument you pass to PyArg_ParseTuple &co. > How do > you know its length to copy it into your own buffer? Use the "s#" format instead, which returns both a pointer to the string contents and its length. Even if you're not going to copy the buffer, it's required in case the string could contain any NUL byte. -- Gabriel Genellina From andreas at kostyrka.org Mon Dec 15 02:26:16 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 15 Dec 2008 08:26:16 +0100 Subject: Python is slow In-Reply-To: References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> Message-ID: <20081215082616.1de76e92@andi-lap> Am Sun, 14 Dec 2008 20:38:58 -0800 (PST) schrieb cm_gui : > > hahaha, do you know how much money they are spending on hardware to > make > youtube.com fast??? yeah, as they do for basically all big sites, no matter what language is used for implementation. Next is the fact that it's rather simple with Python to meet speed demands where external factors like Gb vs 10Gb network cards are the limiting factor. And last, you do realize that most "simple" websites do hinge on the performance and scalability of the underlying SQL server. In practice some languages like PHP do force that "LAMP" model much stronger on the developer, which makes developing systems that scale beyond a certain point a challenge. So to summarize, Python is fast enough for even demanding stuff, and when done correctly even number crunching or binary parsing huge files or possible in competitive speeds. But you sometime need a developer that can wield the tool with a certain experience, and not a stupid rookie that whines that his tool does not make his O(n**n) algorithm automatically blazing fast. Andreas > > > By the way... I know of a very slow Python site called YouTube.com. > > In fact, it is so slow that nobody ever uses it. > > -- > http://mail.python.org/mailman/listinfo/python-list From dfnsonfsduifb at gmx.de Tue Dec 16 11:59:30 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Tue, 16 Dec 2008 17:59:30 +0100 Subject: Does Python3 offer a FrozenDict? Message-ID: Hello group, is there anything like a frozen dict in Python3, so I could do a foo = { FrozenDict({"a" : "b"}): 3 } or something like that? Regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From mccredie at gmail.com Tue Dec 2 14:37:24 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 2 Dec 2008 11:37:24 -0800 (PST) Subject: performance question: dictionary or list, float or string? References: <434bf4e3-54f4-4e15-b8b0-510a988f25b8@z1g2000yqn.googlegroups.com> Message-ID: On Dec 2, 3:51?am, bkamr... at gmail.com wrote: > I forgot to mention that I did a simple timeit test which doesn't > show > significant runtime difference 3.5 sec for dictionary case and 3.48 > for > list case. > > def read_as_dictionary(): > ? ? fil = open('myDataFile', 'r') > ? ? forces = {} > ? ? for region in range(25): > ? ? ? ? forces[region] = {} > > ? ? for step in range(20000): > ? ? ? ? for region in range(25): > ? ? ? ? ? ? line = fil.next(); spl = line.split() > ? ? ? ? ? ? forces[region] [step] = spl > > def read_as_list(): > ? ? fil = open('myDataFile.txt', 'r') > ? ? forces = [] > ? ? for region in range(25): > ? ? ? ? forces.append([]) > > ? ? for step in range(20000): > ? ? ? ? for region in range(25): > ? ? ? ? ? ? line = fil.next(); spl = line.split() > ? ? ? ? ? ? forces[region].append(spl) > > Cheers, > /Ben There really isn't enough information to recommend a particular direction. A dictionary doesn't seem appropriate for this information though. Also, you are hard coding the step range to 20000. Is that the number of lines in the file? That isn't really a safe way to do it. # this is just bad style in python: line = fil.next(); spl = line.split() # better written spl = fil.next().split() I would just do it this way: def read_as_list(data, regions=25, maxlines=20000): # If data is a filename, open the file. If it is a file # object or any sequence of 'lines' it should just work. file_opened = False if isinstance(data, basestring): data = open(data, 'r') file_opened = True forces = [[] for _ in xrange(regions)] try: for i, line in data: if i == maxlines: break forces[i % 25].append(line.split()) finally: if file_opened: f.close() return forces Matt From esgameserver at gmail.com Wed Dec 3 10:13:14 2008 From: esgameserver at gmail.com (esgameserver at gmail.com) Date: Wed, 3 Dec 2008 07:13:14 -0800 (PST) Subject: Profiling Python Message-ID: <15e24533-472f-4147-9467-893b40ff2710@w35g2000yqm.googlegroups.com> Hi, Simply put, we want to see the profile info dynamically. Is that possible? To clarify again, Is there some function like profile.PrintStats() which dynamically shows the stats before stopping the Profiler? Regards, From googler.1.webmaster at spamgourmet.com Thu Dec 25 05:37:59 2008 From: googler.1.webmaster at spamgourmet.com (googler.1.webmaster at spamgourmet.com) Date: Thu, 25 Dec 2008 02:37:59 -0800 (PST) Subject: Python with PyGIL_Ensure? Message-ID: Hi! I have a small problem with my python embedded interpreter. I do some stuff where two threads exists which do some pythons stuff in the same stuff. So bpoth call PyGILState_Ensure() which occurs a crash. What can I do, that one thread waits until the other thread released the gil state? Thanks a lot. From martin at v.loewis.de Mon Dec 8 02:31:31 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 08 Dec 2008 08:31:31 +0100 Subject: Number of Python 3.x packages at the PyPI In-Reply-To: References: <9c1ab0f3-6686-4c0f-8a6c-12e20539f354@41g2000yqf.googlegroups.com> <493b954e$0$4021$9b622d9e@news.freenet.de> Message-ID: <493ccd54$0$21674$9b622d9e@news.freenet.de> > Should specifying the 3.0 tag implicity and automatically specify the > 3 tag as well? No. There is really no builtin automatic semantics to any of the classifiers. Regards, Martin From kyosohma at gmail.com Tue Dec 30 13:46:21 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 30 Dec 2008 10:46:21 -0800 (PST) Subject: folder extraction References: Message-ID: <0854393e-6c94-451e-9e9d-51132d7e09e3@k1g2000prb.googlegroups.com> On Dec 30, 9:30?am, ibpe... at gmail.com wrote: > how do i get along with this task of extracting multiples folder and > generating their names individually in a their respective files as > they were generated. Are you talking about unzipping an archive or walking a directory? If the former, see the zip module or use the subprocess module to control an external archiving application. If the latter, see os.walk and the glob module. Mike From hoteljorba at gmail.com Tue Dec 9 18:31:54 2008 From: hoteljorba at gmail.com (morecowbell) Date: Tue, 9 Dec 2008 15:31:54 -0800 (PST) Subject: fuzzy or boolean text search References: <104335ff-e507-4429-9ad3-baecb63da8b3@k36g2000yqe.googlegroups.com> Message-ID: On Dec 9, 12:14?am, John Machin wrote: > On Dec 9, 4:36?pm, n00b wrote: > > > hi, > > > i'm looking for advice/suggestions for text search, preferably with > > boolean or even fuzzy capabilities, and for use with mysql innodb > > tables. ?asking too much :) ??? > > No ... feeding "fuzzy boolean text search mysql innodb" to my googler > didn't choke it; it produced this at about the 15th hit: > > http://www.sphinxsearch.com/docs/manual-0.9.8.html > > Please tell your googler that we all hope that it gets well soon :-) since you found the list, i presume you can google and looking for something pythonic. we tried a few options but it's bleak. for a pythonic solution, look at TextIndexNG3 (Zope). i'll take some fiddling, though: http://sourceforge.net/projects/textindexng; if something with a py wrapper will do, you might as well go with the big guns: lucence. we found that to work very well and that includes SA integration (http://www.freebsdsoftware.org/textproc/py-lucene.html) From exarkun at divmod.com Thu Dec 18 10:10:54 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 18 Dec 2008 10:10:54 -0500 Subject: confused about __str__ vs. __repr__ In-Reply-To: Message-ID: <20081218151054.20272.980517665.divmod.quotient.22608@ohm> On Thu, 18 Dec 2008 09:51:01 -0500, Neal Becker wrote: >Tino Wildenhain wrote: > >> Neal Becker wrote: >> ... >>>>> So if __str__ is "meant for human eyes", then why isn't print using it! >>>> it is: >>>> >>>> > print x >>>> str >>>> >>>> but dict just uses repr() for all its childs to print. >>>> >>>> T. >>> That makes no sense to me. If I call 'print' on a container, why >>> wouldn't it recursively print on the contained objects? Since print >>> means call str, printing a container should recursively call str on the >>> objects. >> >> Every class is free on how to best implement __str__, you will find >> the same behavior on tuple and list as well. >> >> Maybe its discussable to change the implementation sensibly, best if you >> would come with a proposal? Perhaps pprint.pprint is a starting point? >> >> Regards >> Tino > >First, I'd like to know if there is a rationale for the current design. Am I correct in thinking this is a defect? There is a rationale. Consider: >>> class strit(object): ... def __init__(self, it): ... self.it = it ... def __repr__(self): ... return str(self.it) ... This will let us see what a dict.__str__ which called __str__ on the objects in it would look like. So first, something simple: >>> print str({strit("['foo']"): 'bar'}) {['foo']: 'bar'} >>> Mildly confusing - you can't use a list as a dict key! But it could be worse: >>> print str({strit("1: 2, 3"): 'bar'}) {1: 2, 3: 'bar'} >>> Wait - *how* many items are in that dictionary? Hopefully that makes the rationale clear - when a human is looking at the str of a dict (and a human is ostensibly the intended audience) - using the __repr__ of the contained objects makes it easier for the human to understand what's in the dict. Using __str__ would make it much harder in many cases. Jean-Paul From clp at rebertia.com Wed Dec 17 00:44:41 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 16 Dec 2008 21:44:41 -0800 Subject: The rule of literal string In-Reply-To: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> Message-ID: <47c890dc0812162144r365c74dfw464118825a963e9e@mail.gmail.com> On Tue, Dec 16, 2008 at 9:32 PM, Li Han wrote: > Hi! I just began to read the tutorial of python3.0 and I just can't > figure out the rule of literal string. There is a example in the > tuotrial: >>>> '"Isn\'t," she said.' > '"Isn\'t," she said.' > It is not what I want, I just want '"Isn't," she said.' be printed, > why the backslash failed? > These don't work at all: >>>> '''"Isn't," she said.''' > '"Isn\'t," she said.' >>>> r"Isn't," she said. > SyntaxError: invalid syntax (, line 1) >>>> r'"Isn't," she said.' > SyntaxError: invalid syntax (, line 1) > I have tried to solve it until my brain damaged and now I need to > sleep. You need to print() the string. Otherwise, the interpreter does an implicit repr() on the string, causing it to output a string literal equivalent to the string, essentially doing print(repr(your_string)). To explain what repr() does, consider the following identity: eval(repr(your_string)) == your_string Notice how the outer set of quotes is still present in the output you got. Using print() explicitly causes repr() not to be called, thus the escape backslashes aren't shown and neither are the surrounding quotes. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From ldo at geek-central.gen.new_zealand Mon Dec 1 03:03:01 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 01 Dec 2008 21:03:01 +1300 Subject: Emacs vs. Eclipse vs. Vim References: Message-ID: In message , Roy Smith wrote: > Likewise for the source control (CVS, SVN, P4, etc) integrations [in > emacs]. Discovered that by accident today. Had a conflicted update in Subversion, fixed it up, saved the file, switched to a terminal window, typed "svn status", and lo and behold, the conflict had vanished (along with the .mine and .rnn files). I assume it was Emacs doing that, and not a side-effect of the "svn status" command. :) From floris.bruynooghe at gmail.com Wed Dec 17 18:35:04 2008 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Wed, 17 Dec 2008 15:35:04 -0800 (PST) Subject: C API and memory allocation References: Message-ID: Hello again On Dec 17, 11:06?pm, Floris Bruynooghe wrote: > So I'm assuming PyArg_ParseTuple() > must allocate new memory for the returned string. ?However there is > nothing in the API that provides for freeing that allocated memory > again. I've dug a little deeper into this and found that PyArg_ParseTuple (and friends) end up using PyString_AS_STRING() (Python/getargs.c:793) which according to the documentation returns a pointer to the internal buffer of the string and not a copy and that because of this you should not attempt to free this buffer. But how can python now know how long to keep that buffer object in memory for? When the reference count of the string object goes to zero the object can be deallocated I though, and then your pointer will point to something different all of a sudden. Does this mean you always have too keep a reference to the original objects when you've extracted information from them with PyArg_Parse*() functions? (At least while you want to hang on to that information.) Regards Floris From stef.mientki at gmail.com Tue Dec 30 15:21:45 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 30 Dec 2008 21:21:45 +0100 Subject: embedding python in wxpython In-Reply-To: <191280cf-ecf9-4135-9737-9923061855d1@t39g2000prh.googlegroups.com> References: <191280cf-ecf9-4135-9737-9923061855d1@t39g2000prh.googlegroups.com> Message-ID: <495A82D9.3000902@gmail.com> 5lvqbwl02 at sneakemail.com wrote: > Hi, I've looked around for a way to allow a python console from within > a wxPython application, but have only found stuff on embedded/ > extending python with C/C++ or wxWidgets in C++, but not wxPython. > > Is this easy to do? Can someone point me in the right direction? > > Also, typically when you embed a scripting language into a larger > application, how do you get the console environment to share data with > the larger application? > > For instance, if the application has some gui stuff (for example > clicking on a object and dragging it around), how do you get > "object.select(x,y)" to print out on the console, and vice-versa: the > object gets selected if the user types "object.select(x,y)"? > > I'd like the console to be a bidirectional representation of what's > going on in the gui, plus a general purpose evaluation environment > where you can manipulate application data via some api which is > automatically exposed to the console when the application opens up. > > I'm looking for high-level hints/strategies/directions. > If you're looking for "high-level", I don't understand why you want to see what's going on in the gui, as I see the gui just a tool to control the real data. For a pretty high level data manipulation, something like PyLab_Works ? http://code.google.com/p/pylab-works/ cheers, Stef From jstroud at mbi.ucla.edu Fri Dec 5 17:00:18 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 05 Dec 2008 14:00:18 -0800 Subject: To Troll or Not To Troll (aka: "as" keyword woes) In-Reply-To: <20081205163107.1815df40@usenot.de> References: <20081205163107.1815df40@usenot.de> Message-ID: Andreas Waldenburger wrote: > Is it me, or has c.l.p. developed a slightly harsher tone recently? > (Haven't been following for a while.) Yep. I can only post here for about a week or two until someone blows a cylinder and gets ugly because they interpreted something I said as a criticism of the language and took it personally by extension. Then I have to take a 4 month break because I'm VERY prone to reciprocating--nastily. I think its a symptom of the language's maturing, getting popular, and a minority fraction* of the language's most devout advocates developing an egotism that complements their python worship in a most unsavory way. I wish they would instead spend their energy volunteering to moderate this list and culling out some of the spam. *No names were mentioned in the making of this post. From jay.dow at gmail.com Thu Dec 11 10:53:32 2008 From: jay.dow at gmail.com (jay.dow at gmail.com) Date: Thu, 11 Dec 2008 07:53:32 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <9e0bb906-e019-45ef-8047-b33982c7c5ad@l39g2000yqn.googlegroups.com> Message-ID: On Dec 11, 7:06 am, Luis M. Gonz?lez wrote: > On Dec 10, 3:42 pm, cm_gui wrote: > > > > >http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-... > > > I fully agree with Krzysztof Kowalczyk . > > Can't they build a faster VM for Python since they love the language > > so much? > > > Python is SLOW. And I am not comparing it with compiled languages > > like C. > > Python is even slower than PHP! > > > Just go to any Python website and you will know. > > An example is:http://www2.ljworld.com/ > > And this site is created by the creators of Django! > > > And it is not just this Python site that is slow. There are many many > > Python sites which are very slow. And please don?t say that it could > > be the web hosting or the server which is slow ? because when so many > > Python sites are slower than PHP sites, it couldn?t be the web > > hosting. Also, Zope/Plone is even slower. > > > Python is slow. Very slow. > > Now seriously, just to finish your idiotic rant, check the Pypy > project: > > http://codespeak.net/pypyhttp://morepypy.blogspot.com > > And if you still think this is not enough, why don't you help these > guys to make it faster? > > Luis PyPy looks pretty sweet. I'm glad this discussion was started. There always seems to be this buzz about python being slow. So what if it's not as fast as C? I make that up by cutting down development time. I figured if I ever ran into something being too slow, that I'd just have to learn c extensions and replace the bottle necks. In 2007 I wrote a system in python that communicated to an autopilot on an autonomously flying aircraft at real-time. We never had any speed issues. I have not played with django much and I do not typically develop web apps, but the slowness really must be bloated algorithms in the libraries you are using. Programming in other languages (java, c, c++, c# etc) is not an issue for me, but next to python it's like writing with a feather and ink instead of a ball point pen. I have to put more time into working with the tools I'm using than actually getting the job done. From mal at egenix.com Thu Dec 11 11:05:21 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 11 Dec 2008 17:05:21 +0100 Subject: Rich Comparisons Gotcha In-Reply-To: <200812101721.51692.kyrie@uh.cu> References: <200812101401.35786.kyrie@uh.cu> <49401C2D.4050209@egenix.com> <200812101721.51692.kyrie@uh.cu> Message-ID: <49413A41.2090605@egenix.com> On 2008-12-10 23:21, Luis Zarrabeitia wrote: > On Wednesday 10 December 2008 02:44:45 pm you wrote: >>> Even in statically typed languages, when you override the equality >>> operator/function you can choose not to return a valid answer (raise an >>> exception). And it would break all the cases mentioned above (element in >>> list, etc). But that isn't the right thing to do. The language >>> doesn't/can't prohibit you from breaking the equality test, but that >>> shouldn't be considered a feature. (a==b).all() makes no sense. >> Perhaps not in your application, but it does make sense in other >> numeric applications, e.g. ones that work on vectors or matrixes. >> >> I'd suggest you simply wrap the comparison in a function and then >> have that apply the necessary conversion to a boolean. > > I do numeric work... I'm finishing my MSc in applied math and I'm programing > mostly with python. And I'd rather have a.compare_with(b), or > a.elementwise_compare(b), or whatever name, rather than (a==b).all(). In > fact, I'd very much like to have an a.compare_with(b, epsilon=e).all() (to > account for rounding errors), and with python2.5, all(a.compare_with(b)). > > Yes, I could create an element_compare(a,b) function. But I still can't use > a==b and have a meaningful result. Ok, I can (and do) ignore that, it's just > one library, I'll keep track of the types before asking for equality (already > an ugly thing to do in python), but the a==b behaviour breaks the lists (a in > ll, ll.indexof(a)) even for elements not in numpy. ?Should I also ignore > lists? You should perhaps reconsider your use of lists. Lists with elements of different types can be tricky at times, so perhaps you either need a different data type which doesn't scan all elements or a separate search function that knows about your type setup. The fact that comparisons can raise exceptions is not new to Python, so this problem can pop up in other areas as well, esp. when using 3rd party extensions. Regarding the other issues like new methods you should really talk to the numpy developers, since they are the ones who could fix this. > The concept of equality between two arrays is very well defined, as it is also > very well defined the element-by-element comparison. There is a need to test > for both - then the way to test for equality should be the equality test. > >>> I'm certain that something could be worked out. A quick paragraph that >>> took me just a few minutes to type shouldn't be construed as a PEP that >>> will solve all the problems :D. >> As always: the Devil is in the details :-) > > Of course... -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 11 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-12-02: Released mxODBC.Connect 1.0.0 http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From mail at timgolden.me.uk Fri Dec 5 16:05:07 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 05 Dec 2008 21:05:07 +0000 Subject: Can I load a python program at the interactive >>> prompt? In-Reply-To: <269e5d69-02b7-409b-ad53-b7702b6ec13a@i24g2000prf.googlegroups.com> References: <269e5d69-02b7-409b-ad53-b7702b6ec13a@i24g2000prf.googlegroups.com> Message-ID: <49399783.8040108@timgolden.me.uk> walterbyrd wrote: > I am running cygwin on xp. > > Much to my annoyance, I can not cut-and-paste from a windows app to > the python prompt. I think I could do this with putty, but I do not > have the permissions to install putty on my xp box. I do this all the time. The key (altho' not strictly essential) is to access the console window Properties from the top-left drop-down menu and then on the first tab, select Quick Edit. With this, you can just right-click with the mouse and whatever you had in the clipboard (as long as it's text) will drop into your Python session. Whenever I'm posting code snippets here, I always copy them from the email and do what I've described to run them in a fresh interpreter session to make sure they work. > > Can I load a file into the python interactive environment? For > example I have a file called test.py that consists of the following: > > print "hello" > print "hello again" > > Can I load that file into python at the >>> prompt? > >>>> load "test.py" > > or something like that? Well, you can use execfile if you want. TJG From excord80 at gmail.com Sun Dec 7 20:23:10 2008 From: excord80 at gmail.com (excord80 at gmail.com) Date: Sun, 7 Dec 2008 17:23:10 -0800 (PST) Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? References: Message-ID: On Dec 7, 8:17?pm, "Patrick Mullen" wrote: > On Sun, Dec 7, 2008 at 4:43 PM, ? wrote: > > [snip] > PyOpengl - an opengl wrapper. ?Version 2 is written in c, version 3 > instead uses ctypes > Pyglet - an opengl + events/sound/etc wrapper written in ctypes Does pyglet use PyOpenGL as its OpenGL wrapper? If not, any idea why? Seems like it would be a fairly substantial duplication of effort. From python at rcn.com Fri Dec 19 06:42:24 2008 From: python at rcn.com (Raymond Hettinger) Date: Fri, 19 Dec 2008 03:42:24 -0800 (PST) Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> Message-ID: On Dec 12, 7:51?am, Marco Mariani wrote: > Filip Gruszczy?ski wrote: > > I am not doing it, because I need it. I can as well use "if not elem > > is None", > > I suggest "if elem is not None", which is not quite the same. They are semantically the same. In theory, Filip's would run slower because of the time to negate the is-test, but the peephole optimizer recognizes the opportunity to make the substitution so it works out exactly the same: >>> dis(compile('x is not None', '', 'eval')) 1 0 LOAD_NAME 0 (x) 3 LOAD_CONST 0 (None) 6 COMPARE_OP 9 (is not) 9 RETURN_VALUE >>> dis(compile('not x is None', '', 'eval')) 1 0 LOAD_NAME 0 (x) 3 LOAD_CONST 0 (None) 6 COMPARE_OP 9 (is not) 9 RETURN_VALUE Raymond From rbrennan55 at hotmail.com Tue Dec 2 16:18:30 2008 From: rbrennan55 at hotmail.com (RON BRENNAN) Date: Tue, 2 Dec 2008 16:18:30 -0500 Subject: Simple ini Config parser examples needed Message-ID: Hello, I have a very simple ini file that I needs parsed. What is the best way I can parse an ini file that doesn't include sections? As in: person=tall height=small shoes=big Thats it. Can anyone help me? Thanks, Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: From zhushenli at gmail.com Wed Dec 3 20:08:27 2008 From: zhushenli at gmail.com (Davy) Date: Wed, 3 Dec 2008 17:08:27 -0800 (PST) Subject: Thread Tkinter problem References: <64c7402c-8b7b-4281-9d7d-1abdd6177d96@r15g2000prh.googlegroups.com> Message-ID: <35672781-eca1-4139-8b5d-88c457960d62@g1g2000pra.googlegroups.com> On Dec 4, 11:13?am, "Hendrik van Rooyen" wrote: > ?"Davy" wrote: > > ? ? while(data_queue.full() == False): > > This will fill the queue and stop. > Use while true and if queue not full... Hi Hendrik, It works, thank you:) Davy > > - Hendrik From google at mrabarnett.plus.com Mon Dec 15 10:42:16 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 15 Dec 2008 15:42:16 +0000 Subject: Thread Locking issue - Can't allocate lock (sem_init fail) In-Reply-To: References: Message-ID: <49467AD8.2030105@mrabarnett.plus.com> Philip Semanchuk wrote: > > On Dec 15, 2008, at 4:56 AM, jamskip at googlemail.com wrote: > >> Hi all, >> >> I have a peculiar problem with a multithreaded program of mine >> (actually I've sort of inherited it). Before i show you the error, >> here's a litle background. Its a program to check email addresses are >> valid, and its main task is to verify the domain names. >> >> Here's the basic functionality: >> >> * The prog has a list of domains it has seen before which is read into >> memory (the 'rollover'). >> * A new list of emails is read-in from a file (to a queue) and is >> checked against the rollover. >> * If we've seen the domain before then update the existing entry. >> * If we've not seen the domain before, add it. >> >> The program is multithreaded to speed up the processing...there are >> input and output Queues. >> >> Now, each domain entry is an class object containing various bits of >> info. Each domain class also has its own lock, so that only one thread >> can modify each domain at a time. >> >> I'm load-testing the program with a sample of 1 million email >> addresses and when i hit about the 500,000 mark i get a locking >> error... >> >> sem_init: No space left on device >> Exception in thread Thread-2: >> Traceback (most recent call last): >> File "/usr/local/lib/python2.4/threading.py", line 442, in >> __bootstrap >> self.run() >> File "/usr/local/lib/python2.4/threading.py", line 422, in run >> self.__target(*self.__args, **self.__kwargs) >> File "jess.py", line 250, in worker >> record.result = function( id, record.value ) >> File "jess.py", line 291, in action >> found_domain = domains.addNewDomain( domain_name ) >> File "jess.py", line 123, in addNewDomain >> self.domain_store.append( self.Domain( name = name ) ) >> File "jess.py", line 46, in __init__ >> self.lock = Lock() >> error: can't allocate lock >> >> Googling for this sort of error doesn't yield any results, and i can't >> find any information about limits to the number of locks you can have >> in Python. The 'No space left on device' message indicates a memory >> issue, however i doubt this since its running on a linux server with 4 >> cores and 16GB ram. It seems more like an internal Python limit has >> been hit (sem_init - semaphore initialisation?). Does anyone know more >> about threading internals and any internal limits? > > Hi Jamskip, > I don't work with threading code but I have been working with semaphores > for my IPC extensions. sem_init() is a call to create a semaphore > (http://linux.die.net/man/3/sem_init). If it is failing, then I'd guess > you're trying to create an awful lot of semaphores (intentionally or > otherwise) and that you're hitting some internal limit. > > I would not be too quick to assume that the number of semaphores one can > create is bounded by the amount of RAM in your system. I don't think > they're simple chunks of malloc-ed memory. They're probably represented > in a kernel data structure somewhere that's hardcoded to some generous > but fixed value. > > Please note that this is all speculation on my part. I think that the > Python threading implementation would use the "local" (i.e. not > process-shared) semaphores which can be allocated on the process' heap. > This would seem only RAM-limited, but I'll bet it isn't. > > You might want to start debugging by track exactly how many locks you're > creating. If the number is really big, start investigating kernel > semaphore limits and how they're set. > You're creating a thread and a lock for each _domain_? Sounds like overkill to me. Many domains means many threads and many locks, by the sounds of it too many for the system. From prabhu.ranjith at gmail.com Sun Dec 7 11:12:29 2008 From: prabhu.ranjith at gmail.com (ranjith) Date: Sun, 7 Dec 2008 08:12:29 -0800 (PST) Subject: @ Start learning through internet @ Message-ID: <2f93f018-85b4-47c4-a335-97584cd202f9@r40g2000yqj.googlegroups.com> visit as at www.tiketin.blogspot.com You can learn all the computer languages from your home itself now. Online study. Visit www.tiketin.blogspot.com to start learning through internet and to clear your computer doubts. From sjmachin at lexicon.net Tue Dec 30 20:45:03 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 30 Dec 2008 17:45:03 -0800 (PST) Subject: Triple quoted string in exec function ? References: <495A253B.6010003@gmail.com> <495A81A7.8030507@gmail.com> Message-ID: <0020c0c3-6ce7-4629-8f13-c2f606cb77d3@z6g2000pre.googlegroups.com> On Dec 31, 8:34?am, Steve Holden wrote: > Stef Mientki wrote: > > ibpe... at gmail.com wrote: > >> On Dec 30, 2:48 pm, Steve Holden wrote: > > >>> Stef Mientki wrote: > > >>>> hello, > >>>> ? ? ? I'm running scripts, with the execute function (Python 2.5), > >>>> and it seems that triple quoted strings are not allowed. > >>>> ? ? ? Is there a workaround, > >>>> or is this a fundamental problem of the exec-function ? > > >>> If you think about it, it should be obvious that you can't surround a > >>> string to be compiled with any of the quotes that appear inside the > >>> string to be compiled. That's about the only limitation I am aware of. > > >>> And, by the way, exec is a *statement*, not a function! > > > ? ? ?exec ( Init_Code, PG.P_Globals ) > > > I've really doubt that this is a statement, > > unless I don't understand what a statement is. > > We'll have to conclude you don't, then, won't we ;-) > Two observations: (1) Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> exec("print a", {'a': 42}) 42 >>> exec "print a" in {'a': 42} 42 (2) >From http://docs.python.org/3.0/whatsnew/3.0.html#removed-syntax """ Removed keyword: exec() is no longer a keyword; it remains as a function. (Fortunately the function syntax was also accepted in 2.x.) """ There's still the triple-quotes-aren't-a-problem issue and the perennial not-showing-code-and-error-output issue ... so by my reckoning the score for this match is: Stef 1, RoW 2 :-) From google at mrabarnett.plus.com Sat Dec 20 21:49:57 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 21 Dec 2008 02:49:57 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: <494DAED5.4080108@mrabarnett.plus.com> Aaron Brady wrote: > On Dec 20, 7:38 pm, Steven D'Aprano cybersource.com.au> wrote: >> Instead of just whinging, how about making a suggestion to fix it? Go on, >> sit down for an hour or ten and try to work out how a BINARY OPERATOR >> like % (that means it can only take TWO arguments) can deal with an >> arbitrary number of arguments, *without* having any special cases. >> >> Go on. Take your time. I'll be waiting. > > Hi, not to take sides, but, there is a possibility. > > This behavior is currently legal: > >>>> "%i %%i" % 0 % 1 > '0 1' > > So, just extend it. (Unproduced.) > >>>> "%i %i" % 0 % 1 > '0 1' >>>> "%r %i" % (2, 3, 4) % 1 > '(2, 3, 4) 1' >>>> "%r %i" % (2, 3, 4) > '(2, 3, 4) %i' > > Which is quite clever and way ahead of its (posessive) time. > A couple of problems: 1. How do you handle a literal '%'? If you just double up then you'll need to fix the string after all your substitutions. 2. What if a substitution introduces a '%'? I suppose a possible solution would be to introduce a special format string, including a literal, eg: f"%r %i" % (2, 3, 4) % 1 and then convert the result to a true string: print(str(f"%r %i" % (2, 3, 4) % 1)) (although print() would call __str__ anyway). The format string would track where the last substitution occurred. Hmm... I think I'll just learn the new method. :-) From rogerb at rogerbinns.com Mon Dec 29 16:52:33 2008 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 29 Dec 2008 13:52:33 -0800 Subject: SQL, lite lite lite In-Reply-To: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Aaron Brady wrote: > Python. There are some options, such as 'sqllite3', but they are not > easy. 'sqllite3' statements are valid SQL expressions, which afford > the entire power of SQL, but contrary to its name, it is not that > 'lite'. Have you compared the compiled size of SQLite against other things? For example on my machine the size of MySQL client library, whose sole purpose is to transport queries and results across the network is the same size as the entirety of SQLite! You can prune SQLite back even further as documented in http://www.sqlite.org/compile.html It is even possible to omit the SQL front end. Queries are stored already processed in the database. This functionality is used by mp3 manufacturers and similar constrained embedded environments. > To me, 'lite' is something you could learn (even make!) in an > afternoon, If you just want to treat the database as a glorified spreadsheet then SQL is "lite", although perhaps a little verbose of a dbm style interface. > If you think SQL is > a breeze, you probably won't find my idea exciting. I assume that the > basics of SQL are creating tables, selecting records, and updating > records. The basics of SQL are about expressing the relational model http://en.wikipedia.org/wiki/Relational_model which has stood the test of time. (That doesn't mean it is superior just that it is good enough like the "qwerty" keyboard layout.) There have been attempts at alternatives like http://en.wikipedia.org/wiki/The_Third_Manifesto but that doesn't seem to have caught on. It seems your basic complaint is the complexity of doing database stuff. Ultimately this will be the case if some data is related to other bits of data. As other posters have pointed out, there are various ORM type wrappers for Python that try to wrap this up in syntactic sugar :-) For something completely different have a look at CouchDB http://couchdb.apache.org/ which operates on "documents" (basically something with an id and an arbitrary updateable list of properties). It does take a bit to get your head wrapped around it - try this posting for an example http://www.cmlenz.net/archives/2007/10/couchdb-joins Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAklZRp0ACgkQmOOfHg372QQ4RQCgzSmgEhvG2DQlWYb68U8BZNOo wOAAnip4GIvKiskuwwWJwaepmJwHLjXJ =0UiA -----END PGP SIGNATURE----- From greg at cosc.canterbury.ac.nz Sun Dec 14 19:04:00 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Mon, 15 Dec 2008 13:04:00 +1300 Subject: [OT] stable algorithm with complexity O(n) In-Reply-To: References: <6qidmbFc4qduU1@mid.uni-berlin.de> Message-ID: <6qll2nFd5qv8U1@mid.individual.net> Lie Ryan wrote: > "You know what you just did? You've > just found a problem that was supposed to be an example of unsolvable > problem." > > It has happened before, why not again? There's a big difference between an unsolvable problem and an unsolved problem. In the cases you're talking about, nobody had solved the problem before, but neither had anybody proved there was no solution. In the case at hand, there is a proof that such an algorithm is impossible. Overturning that would require finding a flaw in the proof, which for such a simple proof seems very unlikely. That's not to say nobody should try, but I won't be holding my breath. -- Greg From google at mrabarnett.plus.com Wed Dec 24 13:04:16 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 24 Dec 2008 18:04:16 +0000 Subject: Iterating over objects of a class In-Reply-To: <6rfb7iF1fg5rU1@mid.uni-berlin.de> References: <2df27de3-7fa3-4ac9-acd9-f946939517cf@r37g2000prr.googlegroups.com> <6rfb7iF1fg5rU1@mid.uni-berlin.de> Message-ID: <495279A0.1030504@mrabarnett.plus.com> Diez B. Roggisch wrote: > Kottiyath schrieb: >> Hi, >> How can I iterate over all the objects of a class? >> I wrote the code like following: >> class baseClass(object): > > Consider adopting PEP 8 coding conventions. > > >> __registry = [] >> >> def __init__(self, name): >> self.__registry.append(self) >> self.name = name >> >> def __iter__(self): >> baseClass.item = 0 >> return self.__registry[0] >> >> def next(self): >> if baseClass.item >= len(self.__registry): >> raise StopIteration >> baseClass.item += 1 >> return self.__registry[baseClass.item - 1] >> >> For testing, create the following objects- >> a = baseClass("Test1") >> b = baseClass("Test2") >> >> class subClass (baseClass): >> pass >> c = subClass("Test3") >> >> ---->Actual Iteration<---- >> for i in a: >> print i.name >> >> Test1 >> Test2 >> Test3 >> >> --------------------------------------------------- >> I see the following problems in the code: >> 1. I have to iterate over any of the objects. For correctness, I >> wanted to iterate over the class, like >> for i in baseClass(): >> do x >> but that will will create one more object - which I do not want. >> >> 2. If the subclass wants to do somethings in its constructor, I am not >> sure how to update the registry. >> class subClass (baseClass): >> def __init__(self, name): >> **do something** >> super.init(self, name) ----> This errors out, saying it needs >> super, not subClass > > You don't show the actual traceback, however the idiom for invoking > super for new-style-classes is > > > super(subClass, self).__init__(name) > > for your case. > >> Another method I thought of implementing it was using generators - >> where-in baseClass.objects() is a generator which will yield the >> objects one by one - but even then the second issue remains. >> If somebody can help me out, I would be very thankful. > > > Using a generator or not isn't the issue here. > > What you need is a *class*-based access, not instance-based. There are > various methods to accomplish this. The simplest is to ditch the > obnoxious __registry as name, and just do > > class BaseClass(object): > > REGISTRY = [] > > > Then iterating is a simple matter of > > for instance in BaseClass.REGISTRY: > ... > > > Case solved. Alternatively, if you insist on the concept of privacy for > that registry, you can use a classmethod: > > > class BaseClass(object): > > > @classmethod > def registry(cls): > for i in cls.__registry: > yield i > > > > > > Last but not least you *could* go for a __metaclass__ with an > __getitem__-method, that makes thinks look fancy because you then can do: > > > for instance in BaseClass: > ... > > I leave it as an exercise to you - gotta go christmas dining now :) > The other thing to remember is that because the 'registry' contains references to the instances, they won't be garbage collected. From hubaghdadi at gmail.com Sun Dec 28 06:40:11 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Sun, 28 Dec 2008 03:40:11 -0800 (PST) Subject: What is site-packages? Message-ID: Hey, What is /usr/lib/pythonx.y/site-packages folder and for what it is used usually? Thanks. From paul at boddie.org.uk Wed Dec 10 06:43:26 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 10 Dec 2008 03:43:26 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> <014ef03e$0$20670$c3e8da3@news.astraweb.com> Message-ID: On 10 Des, 00:00, Steven D'Aprano wrote: > > Go right ahead. Write your experimental language, and if people like it, > they'll use it. That's what Guido did, all those years ago. But don't > turn Python into a hodgepodge of "features" that most people consider > misfeatures. If you consult the public record, you'll see that I'm probably more conservative than most when it comes to adding features. Indeed, one of the principal benefits I see in Python 3.0 is that the hordes of people wanting to add new stuff to Python will now focus on that flavour of the language and not Python 2.x. However, as I pointed out in another message, keyword conflicts have been a problem for the language designers for some time, and more powerful parser technology might have been able to help out. [...] > I think it is childish to reject the Zen just because it's the Zen. Good > advice doesn't cease to be good advice just because people tell you it's > good advice, even if some people are awfully strident about it. I object to the Zen being trotted out every time someone questions any aspect of Python's design (language or implementation) which isn't being reworked elsewhere (say, in Python 3, where apparently the Zen can be suspended), especially when the parts of the Zen being quoted lack pertinence when compared to a properly formulated response to the original inquiry. Paul From pdorange at pas-de-pub-merci.mac.com Tue Dec 23 12:34:41 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Tue, 23 Dec 2008 18:34:41 +0100 Subject: Python's popularity References: Message-ID: <1isezj4.1l4g8lk1plxz8lN%pdorange@pas-de-pub-merci.mac.com> r wrote: > > I've already stated, and you've already proven, that it's pretty trivial > > to ascertain my true identity, if one actually cares. OTOH, that's > > *not* the case with you. Who is hiding now? > > I told you, my name is Thurstan Howell III. Do you want to know my > favorite color too? Only if it's pythonic. -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From invalid at invalid Thu Dec 11 18:01:10 2008 From: invalid at invalid (Grant Edwards) Date: Thu, 11 Dec 2008 17:01:10 -0600 Subject: Best way of debigging a C extension References: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> <6qdjt7Fc1fg0U1@mid.uni-berlin.de> Message-ID: On 2008-12-11, Diez B. Roggisch wrote: > I never tried this on windows - but what happens if you start > python inside GDB, and then set breakpoints inside your > extension? > > This works flawlessly for me under *nix. > > The debug-build of python isn't needed for this - and I doubt > a bit that it helps you much, as being inside the interpreter > & getting detailed information isn't your goal - you want to > see your extensions functions, what parameters they get and so > on. It's probably a lot easier to just stick in a few printf() calls in key places... -- Grant Edwards grante Yow! I'm into SOFTWARE! at visi.com From kyosohma at gmail.com Mon Dec 1 14:20:20 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 1 Dec 2008 11:20:20 -0800 (PST) Subject: Dec 1st Python Meeting Cancellation Message-ID: Hi all! Sorry for the very short notice, but the Python Programming group is canceling tonight's meeting due to inclement weather, lack of interest and sickness. We hope to see you at our next meeting, which will be Monday, January 5th, 2009. Happy holidays! Mike Driscoll http://www.pyowa.org From clp at rebertia.com Wed Dec 17 18:25:41 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 17 Dec 2008 15:25:41 -0800 Subject: The rule of literal string In-Reply-To: <34028b73-7807-4e88-80bc-fe31a7b1a2a0@i20g2000prf.googlegroups.com> References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> <_PmdnU59w62vGtTUnZ2dnUVZ_hSdnZ2d@pdx.net> <34028b73-7807-4e88-80bc-fe31a7b1a2a0@i20g2000prf.googlegroups.com> Message-ID: <47c890dc0812171525t527353e2m5c8b0597ee183e21@mail.gmail.com> 2008/12/17 Li Han : > On 12?18?, ??7?12?, Scott David Daniels wrote: > Scott wrote: >> Try: print repr(repr("'")) >> that might enlighten you. > > I found that print( repr( repr( arbitarystring ) ) ) == repr > ( arbitarystring ) As I stated previously, the key rule is: eval(repr(something)) == something That is, repr() gives a string of Python code that, when evaluated, results in what you gave to repr(). So repr('') ==> "''" And repr("''") ==> "\"''\"" Which when print()-ed is: "''" And eval("''") is the same as entering two apostrophes ('') at the REPL, both of which give an empty string object. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From mludvig at logix.net.nz Mon Dec 29 07:41:51 2008 From: mludvig at logix.net.nz (Michal Ludvig) Date: Tue, 30 Dec 2008 01:41:51 +1300 Subject: setup.py installs modules to a wrong place In-Reply-To: <7d6d6971-e6cc-418f-a79e-598517ffb013@j38g2000yqa.googlegroups.com> References: <494384EF.7050605@logix.net.nz> <7d6d6971-e6cc-418f-a79e-598517ffb013@j38g2000yqa.googlegroups.com> Message-ID: <4958C58F.9060504@logix.net.nz> Hi Omer, > I'm seeing this on fc8 with a custom built python2.6. Not happening > with any other packages (e.g. boto). Workaround of course was just to > copy the S3 dir to /usr/local/lib/python2.6/site-packages. I've found it. The culprit was a pre-set install prefix in setup.cfg - I can't remember why I put it there ages ago. Anyway, now it's removed ;-) > I poked around a bit but nothing obvious jumped out. Happy to do any > debugging if you have tests you'd like to me to run. Thanks for the offer. I believe the current SVN trunk [1] of s3cmd should install just fine everywhere. Michal [1] .. http://s3tools.logix.cz/download From sjmachin at lexicon.net Wed Dec 17 18:06:47 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 17 Dec 2008 15:06:47 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> <0d9ea7cc-b5fb-4edb-be32-490aae9e7204@b41g2000pra.googlegroups.com> <0de3a7bf-a4c4-4103-a4e0-44313405fa94@z28g2000prd.googlegroups.com> Message-ID: <23d6710f-2c6d-4115-817a-053b8e96f1ce@z28g2000prd.googlegroups.com> On Dec 18, 3:15?am, aka wrote: > John, this is the actual code I ran in TurboGears which is a Python > framework. It's not complete -- the change in indentation would have caused a SyntaxError. If (as you appear to assert) the problem is in the csv module, then create a small stand-alone no-TurboGears Python script and a test file which together demonstrate the problem reproducibly so that the problem can investigated by anyone with a standard TurboGears-free Python installation. If you can't reproduce the problem in that manner, then you may need to seek assistance in a TurboGears-specific forum. > I should have left away the import statements. Trust me, the problem > isn't in there because the UnicodeWriter is functioning perfectly. Do you mean that this file was created by whatever.UnicodeWriter? If so, did you just now discover this information? How do you know that "the UnicodeWriter is functioning perfectly"? What does "functioning perfectly mean to you"? In particular, what encoding is it using? > I did allready sanitate the csv file to these four lines in Notepad so > there isn't anything more than this: > > id;company;department > 12;Cadillac;Research > 11;Ford;Accounting > 10;Chrysler;Sales Which do you mean: (a) you typed those lines into Notepad yourself (b) you took a copy of a file created by whatever.UnicodeWriter, opened it with Notepad, trimmed off some rows and columns, and saved it again ? You said earlier """ csv.reader results in: for r in reader: Error: line contains NULL byte Use of UnicodeReader results in: UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: unexpected code byte """ Those results are consistent with your file being encoded in utf16_le, with the utf16_le BOM ('\xff\xfe') at the start of the file. Have you, as I asked, looked at the file with some better-than-Notepad diagnostic apparatus? Here's a likely hypothesis: the file was written in utf16. In that case: either (i) you really want utf16 (why?), so: (1) the csv module will not cope with it, and is not expected to cope with it (2) the whatever.UnicodeReader should (in order of preference): (a) be allowed to find out for itself that 'utf16' is the go (b) be told explicitly that 'utf16' is the go (c) be served with a bug report OR (ii) you really want utf8, so: (1) the csv module should be happy (2) the whatever.UnicodeWriter should be told to use 'utf8' (3) the whatever.UnicodeReader should (in order of preference): [as above but s/16/8/] HTH, John From noone at lewscanon.com Wed Dec 3 20:38:44 2008 From: noone at lewscanon.com (Lew) Date: Wed, 03 Dec 2008 20:38:44 -0500 Subject: Mathematica 7 compares to other languages In-Reply-To: <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> Message-ID: Xah Lee wrote: > enough babble ... Good point. Plonk. Guun dun! -- Lew From jeremiah.dodds at gmail.com Thu Dec 25 07:35:39 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Thu, 25 Dec 2008 07:35:39 -0500 Subject: Is there a function to remove escape characters from a string ? In-Reply-To: <%CK4l.11459$c45.7073@nlpi065.nbdc.sbc.com> References: <%CK4l.11459$c45.7073@nlpi065.nbdc.sbc.com> Message-ID: <12cbbbfc0812250435u19d3d7ffo5afd2e73ea80ca83@mail.gmail.com> On Thu, Dec 25, 2008 at 7:02 AM, James Stroud wrote: > Stef Mientki wrote: > >> hello, >> >> Is there a function to remove escape characters from a string ? >> (preferable all escape characters except "\n"). >> >> thanks, >> Stef >> > > > import string test = 'this\r is a test\t yeah\n' for c in string.printable[-5:]: if c != '\n': test = test.replace(c, ' ') Hmm, should the escape codes be in their own little list in string? Or are they, and I'm just not seeing them? Is string.printable[-5:] a reliable way to get the list of escape codes? -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Tue Dec 23 08:18:32 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 23 Dec 2008 13:18:32 +0000 (UTC) Subject: print to console without a line break References: Message-ID: On Tue, 23 Dec 2008 11:50:59 +0100, Qian Xu wrote: > Hello All, > > Is it possible to print something to console without a line break? > > I tried: > sys.stdout.write("Testing something ...") // nothing will be printed > time.sleep(1) > sys.stdout.write("done\n") // now, the whole string will be printed > > What I want, is to see "Testing something ..." first. And after 1 > second, to see "done" (with a line break) > > The only one solution I have found is to call "echo -n 'my_string'". But > it is not nice. Because I have to escape all special chars in the string > manually. > > Any advice? > Best regards > -- Qian Xu If you don't mind an extra space, you can use this: print 'Testing something ...', # note the trailing comma From bdesth.quelquechose at free.quelquepart.fr Sun Dec 28 12:15:23 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 28 Dec 2008 18:15:23 +0100 Subject: "return" in def In-Reply-To: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> Message-ID: <4957c1dc$0$24043$426a34cc@news.free.fr> Roger a ?crit : > > When I define a method I always include a return statement out of > habit even if I don't return anything explicitly: > > def something(): > # do something > return > > Is this pythonic or excessive? If it's the last statement in the function body, it is indeed "excessive". OTHO I sometimes end a function with an explicit "return None" when there are branches with early returns, ie: def func(): if some_condition: return something return None to make really clear what happens - even if it _should_ be clear without the last statement. IOW : use your own judgement. From mwilson at the-wire.com Tue Dec 9 16:17:09 2008 From: mwilson at the-wire.com (Mel) Date: Tue, 09 Dec 2008 16:17:09 -0500 Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> <1ddabaf6-c129-4395-8d81-738e67e6f3ca@q26g2000prq.googlegroups.com> Message-ID: Carl Banks wrote: >[ ... ] Do you want the human reader to have to have all kinds of > rules to memorize about when a symbol is an identifier and when it's a > syntactic element? Do you want people to have to learn when to escape > a symbol so that the parser treats it as an identifier instead of > syntax? Then again, Python programmers should be used to namespaces, and it shouldn't bother people that `open` means one thing, and `image.open` means something very different -- if you've imported image. Mel. From benjamin.kaplan at case.edu Sat Dec 13 23:40:10 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sat, 13 Dec 2008 23:40:10 -0500 Subject: 1 or 1/0 doesn't raise an exception In-Reply-To: References: <49446E39.6020807@tim.thechases.com> Message-ID: On Sat, Dec 13, 2008 at 10:49 PM, Daniel Fetchinson < fetchinson at googlemail.com> wrote: > >> Is it a feature that > >> > >> 1 or 1/0 > >> > >> returns 1 and doesn't raise a ZeroDivisionError? If so, what's the > >> rationale? > > > > Yes, it's a feature: > > > > http://en.wikipedia.org/wiki/Short-circuit_evaluation > > > > When you have "True or False", you know it's true by the time > > you've got the first piece, so there's no need to evaluate the > > 2nd piece. The opposite is helpful too: > > > > lst = [some list or an empty list] > > ... > > if lst and lst[0] == 42: > > > > This ensures that the "lst[0]" doesn't fail if lst is empty, > > because lst evaluating to false (an empty list) short-circuits > > preventing the evaluation of "lst[0]". > > Okay, it's clear, thanks. > > Let me just point out that unsuspecting people (like me) might rely on > the whole expression to be evaluated and rely on exceptions being > raised if needed. > > So from now on I will not do! If you want both expressions evaluated, you can use & and |, just like in C and Java (&& and || are used for short circuit evaluation in those languages). -------------- next part -------------- An HTML attachment was scrubbed... URL: From tmohr at s.netic.de Sun Dec 14 15:40:32 2008 From: tmohr at s.netic.de (Torsten Mohr) Date: Sun, 14 Dec 2008 21:40:32 +0100 Subject: package structure? References: Message-ID: >> I wonder how i can make AClass() known in that package. >> > > Why don't you put the contents of smod1.py in mod/smod1/__init__.py? > It'll work this way. Of course, thanks for that hint. Best regards, Torsten. From jeremiah.dodds at gmail.com Wed Dec 3 23:32:13 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Wed, 3 Dec 2008 23:32:13 -0500 Subject: RELEASED Python 3.0 final In-Reply-To: <1b9568f2-55a0-4f1e-886c-2675b16b58c9@g38g2000yqn.googlegroups.com> References: <1b9568f2-55a0-4f1e-886c-2675b16b58c9@g38g2000yqn.googlegroups.com> Message-ID: <12cbbbfc0812032032y3bcc0676k6831ca546fbed240@mail.gmail.com> thankers.append(self) -------------- next part -------------- An HTML attachment was scrubbed... URL: From jurgenex at hotmail.com Thu Dec 4 00:24:13 2008 From: jurgenex at hotmail.com (Jürgen Exner) Date: Wed, 03 Dec 2008 21:24:13 -0800 Subject: Mathematica 7 compares to other languages References: <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <4b6c3304-2396-4d35-a06f-e5d693cbbb12@f13g2000yqj.googlegroups.com> <20081219033030.559@gmail.com> Message-ID: Kaz Kylheku wrote: >On 2008-12-04, J?rgen Exner wrote: >> toby wrote: >>>On Dec 3, 4:15 pm, Xah Lee wrote: >>>> On Dec 3, 8:24 am, Jon Harrop wrote: >>>> >>>> > My example demonstrates several of Mathematica's fundamental limitations. >>>> >>>> enough babble Jon. >>>> >>>> Come flying $5 to my paypal account, and i'll give you real code, >>> >>>I'll give you $5 to go away >> >> if you add "and never come back" then count me in, too. > >Really? I will trade you one Xah Lee for three Jon Harrops and I will even >throw in a free William James. Well, I've never seen those names on CL.perl.M, so I don't know them. jue From steve at holdenweb.com Fri Dec 12 08:22:28 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Dec 2008 08:22:28 -0500 Subject: How to write binary data to file and socket In-Reply-To: References: Message-ID: Lee Soin wrote: > Hello, all! > I'm new to python. In Linux C programming, writing data to file and > socket share the same system call "write". But it seems that only data > of string type can be used for "write" and "send". So how to write > binary data to file and socket? > Assuming you are using Python 2.x, use the struct module to convert your data to a string, then write that. In Python 3.x you would use the bytes type. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From brfredericks at gmail.com Thu Dec 11 19:02:27 2008 From: brfredericks at gmail.com (bfrederi) Date: Thu, 11 Dec 2008 16:02:27 -0800 (PST) Subject: Dictionary as Keyword Arguments Message-ID: I was wondering if I had a dictionary of keywords and values like so: keyword_arg_dict = { 'attribute': 'stone', 'contents': 'cave people', 'path': '/path/to/cave', 'name': 'Ogg's Cave', } And I had a function that accepted keyword arguments like so: make_dwelling( attribute='stone', contents='cave people', path='/path/to/cave', name='Ogg's Cave', ) Is there any way I could use my keyword_arg_dict as my keyword args for the make_dwelling function, since I am not the creator of the make_dwelling function, and need to take that dictionary of key-value pairs and turn it into keyword-value arguments for the make_dwelling function? From stef.mientki at gmail.com Mon Dec 8 15:19:35 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 08 Dec 2008 21:19:35 +0100 Subject: how to get a beep, OS independent ? In-Reply-To: References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> <014c575a$0$20670$c3e8da3@news.astraweb.com> Message-ID: <493D8157.2030200@gmail.com> Joe Strout wrote: > On Dec 7, 2008, at 4:43 PM, Steven D'Aprano wrote: > >> Of course, if you're volunteering to write such a standard system beep >> for Python, I for one would be grateful. > > I am. But where should I put it? Assuming we don't want to wait for > the (understandably) lengthy and contentious process required to add > something to the Python system libraries, where would be the next best > place for this sort of simple OS abstraction layer? > Well I would love to try it, why not already attach it to this list ? cheers, Stef > Thanks, > - Joe > > -- > http://mail.python.org/mailman/listinfo/python-list From google at mrabarnett.plus.com Sun Dec 28 14:25:19 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 28 Dec 2008 19:25:19 +0000 Subject: "return" in def In-Reply-To: <40b1b762-459b-4d6f-91f0-0a6e68d233ae@a26g2000prf.googlegroups.com> References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <40b1b762-459b-4d6f-91f0-0a6e68d233ae@a26g2000prf.googlegroups.com> Message-ID: <4957D29F.7060008@mrabarnett.plus.com> Gerard Flanagan wrote: > On Dec 28, 5:19 pm, Roger wrote: >> Hi Everyone, > [...] >> When I define a method I always include a return statement out of >> habit even if I don't return anything explicitly: >> >> def something(): >> # do something >> return >> >> Is this pythonic or excessive? Is this an unnecessary affectation >> that only adds clock ticks to my app and would I be better off >> removing "returns" where nothing is returned or is it common practice >> to have returns. >> > > It's not particularly excessive but it is uncommon. A nekkid return > can sometimes be essential within a function body, so a non-essential > nekkid return could be considered just noise. > If it's a function, ie the result is used by the caller, then explicitly return with the value, even if it's None. On the other hand, if it's a procedure, ie the result is always None and that result isn't used by the caller, then don't use return, except for an early exit. From fetchinson at googlemail.com Wed Dec 3 22:47:10 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 3 Dec 2008 19:47:10 -0800 Subject: RELEASED Python 3.0 final In-Reply-To: References: Message-ID: > On behalf of the Python development team and the Python community, I > am happy to announce the release of Python 3.0 final. > > Python 3.0 (a.k.a. "Python 3000" or "Py3k") represents a major > milestone in Python's history, and was nearly three years in the > making. This is a new version of the language that is incompatible > with the 2.x line of releases, while remaining true to BDFL Guido van > Rossum's vision. Some things you will notice include: > > * Fixes to many old language warts > * Removal of long deprecated features and redundant syntax > * Improvements in, and a reorganization of, the standard library > * Changes to the details of how built-in objects like strings and > dicts work > * ...and many more new features > > While these changes were made without concern for backward > compatibility, Python 3.0 still remains very much "Pythonic". > > We are confident that Python 3.0 is of the same high quality as our > previous releases, such as the recently announced Python 2.6. We will > continue to support and develop both Python 3 and Python 2 for the > foreseeable future, and you can safely choose either version (or both) > to use in your projects. Which you choose depends on your own needs > and the availability of third-party packages that you depend on. Some > other things to consider: > > * Python 3 has a single Unicode string type; there are no more 8-bit > strings > * The C API has changed considerably in Python 3.0 and third-party > extension modules you rely on may not yet be ported > * Tools are available in both Python 2.6 and 3.0 to help you migrate > your code > * Python 2.6 is backward compatible with earlier Python 2.x releases > > We encourage you to participate in Python 3.0's development process by > joining its mailing list: > > http://mail.python.org/mailman/listinfo/python-3000 > > If you find things in Python 3.0 that are broken or incorrect, please > submit bug reports at: > > http://bugs.python.org/ > > For more information, links to documentation, and downloadable > distributions, see the Python 3.0 website: > > http://www.python.org/download/releases/3.0/ > > Enjoy, > - -Barry > > Barry Warsaw > barry at python.org > Python 2.6/3.0 Release Manager > (on behalf of the entire python-dev team) uname -a Linux fetch 2.6.23.1-42.fc8 #1 SMP Tue Oct 30 13:18:33 EDT 2007 x86_64 x86_64 x86_64 GNU/Linux tar xzvf Python-3.0.tgz cd Python-3.0 ./configure make Failed to find the necessary bits to build these modules: _tkinter To find the necessary bits, look in setup.py in detect_modules() for the module's name. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From benjamin.kaplan at case.edu Mon Dec 8 13:40:41 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 8 Dec 2008 13:40:41 -0500 Subject: Public imports In-Reply-To: <66ecdd96-38dd-4054-8009-e145c0a78316@o40g2000prn.googlegroups.com> References: <9623b0a3-7053-41f1-b116-0cd5e54f39e9@v13g2000vbb.googlegroups.com> <493d1ec0$0$32048$426a34cc@news.free.fr> <66ecdd96-38dd-4054-8009-e145c0a78316@o40g2000prn.googlegroups.com> Message-ID: On Mon, Dec 8, 2008 at 1:29 PM, M?rcio Faustino wrote: > So, no chance of doing this: > > # "A.py" > from __future__ import division, with_statement > > # "B.py" > from A import * > print 1 / 2 > > ...and printing 0.5, right? Too bad :) > Thanks! That would be a very bad idea. What if you did that and then someone else tried to use your module? However, future imports are a special case. This will work with any normal import. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Tue Dec 2 20:49:01 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 2 Dec 2008 17:49:01 -0800 (PST) Subject: problem with optparse References: Message-ID: <1e60b3d7-e564-4ea9-b4f6-8ccc2e3b6a1b@e1g2000pra.googlegroups.com> On Dec 3, 11:47 am, Neal Becker wrote: > Robert Kern wrote: > > Neal Becker wrote: > >> This example is right out of python library reference. What's wrong > >> here? > > >> import optparse > > >> def store_value(option, opt_str, value, parser): > >> setattr(parser.values, option.dest, value) > > >> parser = optparse.OptionParser() > >> parser.add_option("--foo", > >> action="callback", callback=store_value, > >> type="int", nargs=3, dest="foo") > > >> (opt,args) = parser.parse_args ('--foo a b c'.split()) > > >> [...] > >> /usr/lib64/python2.5/optparse.pyc in _process_args(self, largs, rargs, > >> values) > >> 1423 elif self.allow_interspersed_args: > >> 1424 largs.append(arg) > >> -> 1425 del rargs[0] > >> 1426 else: > >> 1427 return # stop now, leave this > >> arg in rargs > > >> TypeError: 'str' object doesn't support item deletion > > > Dunno. It works for me (i.e. I get the expected "error: option --foo: > > invalid integer value: 'a'"). Have you tried it outside of IPython? > > yes: > python test_opt.py > Traceback (most recent call last): > File "test_opt.py", line 12, in > (opt,args) = parser.parse_args ('--foo') > File "/usr/lib64/python2.5/optparse.py", line 1378, in parse_args > stop = self._process_args(largs, rargs, values) > File "/usr/lib64/python2.5/optparse.py", line 1425, in _process_args > del rargs[0] > TypeError: 'str' object doesn't support item deletion This is rather confusing: on my system the two source lines and numbers in the traceback correspond to the Python 2.6 source, but don't correspond to the Python 2.5 source. However, your path is .../ python2.5/... Unfortunately, although optparse has changed between 2.5 and 2.6, optparse.__version__ wasn't changed from "1.5.3" so it's no use asking you to print that. Working backwards from the error, it seems that by the time this is executed: stop = self._process_args(largs, rargs, values) rargs has become a string instead of a list of strings. Perhaps you would like to (1) check your optparse.py for corruption and (2) put some temporary print statements along the trail from your *** AARRGGHH!! *** '--foo' in your second message should be ['--foo'] so how come you got an error with '--foo a b c'.split() in your first message??? I'll try again: Perhaps you would like to (1) check your optparse.py for corruption and then (2) if you still have a problem, show us the contents of your test_opt.py and the results of running that at the command line. It would be nice if you included: import sys; print sys.version near the top of test_opt.py. HTH, John From digitig at gmail.com Fri Dec 12 14:04:54 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 12 Dec 2008 19:04:54 +0000 Subject: (Very Newbie) Problems defining a variable In-Reply-To: <878wqlz27z.fsf@daycos.com> References: <878wqlz27z.fsf@daycos.com> Message-ID: 2008/12/12 Kirk Strauser : > def get_rate(balance): > for threshold, rate in ((100000, .0173), > (50000, .0149), > (25000, .0124), > (10000, .0085), > (0, .006)): > if balance > threshold: > return rate > return .0 Yes, once it's changed from a dictionary to tuples it becomes easier, doesn't it? D'oh! -- Tim Rowe From geekmail at usenot.de Sun Dec 7 16:06:29 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sun, 7 Dec 2008 22:06:29 +0100 Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> Message-ID: <20081207220629.67f4cc17@usenot.de> On Sun, 07 Dec 2008 20:56:40 GMT I V wrote: > So, if we want Python to the programming language of choice for > Lacanian psychoanalysts, perhaps we should adopt the symbol "$" (or > even, with Python 3's support for unicode identifiers, S followed by > U+0388) instead of "self." OK, I'm sold. :) /W -- My real email address is constructed by swapping the domain with the recipient (local part). From jcd at sdf.lonestar.org Mon Dec 1 11:15:39 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 01 Dec 2008 11:15:39 -0500 Subject: Pyhon (with wxPython) on Windows' cygwin: can it be done fully ? In-Reply-To: <4a4fa55e-779c-47bd-a6bd-4829abaa4824@d42g2000prb.googlegroups.com> References: <6p2l98F61ttqU1@mid.uni-berlin.de> <4a4fa55e-779c-47bd-a6bd-4829abaa4824@d42g2000prb.googlegroups.com> Message-ID: <1228148139.32081.14.camel@aalcdl07.lib.unc.edu> On Sat, 2008-11-29 at 13:31 -0800, Lie wrote: > pdb and logging is too much for beginners, which most likely does not > yet understand the workings of the debugger and logger (and pdb's many > quirks). Don't forget that we're all beginners once. Python's learning > curve shouldn't raise with time, it should get lower so more people > can join in the board. >>> import logging >>> logging.basicConfig(level=logging.DEBUG) >>> >>> logging.debug("HERE!") DEBUG:root:HERE! >>> logging.debug("THERE!") DEBUG:root:THERE! >>> logging.info("abc") INFO:root:abc Ooh. Tough one. The only thing that's missing is to have this clearly documented in tutorials. (Maybe level 2, once you've learned the basics). And if that's too hard for you, you can still use print("HERE!"). But why sweat the "productivity loss" of the two parens when robust logging is really that easy, and can be turned on or off at one place? From brendandetracey at yahoo.com Tue Dec 16 09:28:00 2008 From: brendandetracey at yahoo.com (Brendan) Date: Tue, 16 Dec 2008 06:28:00 -0800 (PST) Subject: zipfile.is_zipfile() and string buffers Message-ID: <79196ccb-11fb-4a2d-9c2c-79801f108a05@f40g2000pri.googlegroups.com> I would like zipfile.is_zipfile(), to operate on a cStringIO.StringIO string buffer, but is seems only to accept file names as arguments. Should it not be able to handle string buffers too? From __peter__ at web.de Fri Dec 19 09:33:07 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2008 15:33:07 +0100 Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <494b5f47$0$17068$6e1ede2f@read.cnntp.org> <494b632b$0$17070$6e1ede2f@read.cnntp.org> Message-ID: Roger wrote: >> Note that I took out the lambdas and gave event arguments to the >> functions; if you did that on purpose, because you need to call the same >> functions without events, then just ignore that... >> SO, the other workaround, which I've used, is to bind the event to a >> generic function, and have that generic function conditionally call >> the functions you want. I'll go back and try to make an example from >> your example. -Chuckk > > Thanks Chuckk! You've done exactly what I did so far. I went through > the source in Tkinter.py and had an inkling of what the unbind > function was doing. I believe, and please correct me if I'm wrong, > in: self.tk.call('bind', self._w, sequence, '') , the '' is unbinding > all methods and I believe the self.deletecommand(funcid) is a > workaround for a memory leak otherwise. Perhaps self.tk.call('bind', > self._w, sequence, funcid) would work but that's a pure guess. I > would have liked to investigate the tcl source directly to see if I > could develop a workaround through a tk.call() but that was hitting a > wall in terms of any documentation I could research. I'm interested > in any workaround you may have however! The documentation for bind in tcl is here http://www.tcl.tk/man/tcl8.4/TkCmd/bind.htm and as far as I understand it doesnt support unbinding selected callbacks, either. I'd suggest a plain-python workaround along the lines of import Tkinter def test(event): print 'test' def test2(event): print 'test2' root = Tkinter.Tk() root.geometry("200x100+100+100") class Multiplexer: def __init__(self): self.funcs = [] def __call__(self, event): for f in self.funcs: f(event) def add(self, f): self.funcs.append(f) return f def remove(self, f): self.funcs.remove(f) m = Multiplexer() m.add(test) m.add(test2) root.bind("<1>", m) def unbind(): print "unbind" m.remove(test2) button = Tkinter.Button(root, text="unbind test2", command=unbind) button.pack() root.mainloop() Peter From rhodri at wildebst.demon.co.uk Tue Dec 16 19:36:56 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Wed, 17 Dec 2008 00:36:56 -0000 Subject: sorting for recursive folder rename In-Reply-To: References: Message-ID: On Tue, 16 Dec 2008 18:20:52 -0000, ianar? wrote: > Hello all, > > I trying to recursively rename folders and files, and am looking for > some ideas on the best way of doing this. The problem is that the > given list of items can be in order, and one to all items may be > renamed. Here is some preliminary code I have, but which does not work > very well. > self.toRename has the following structure : > [ > [original_name, new_name, os.path.isdir] > .. > ] [snip] import os for item in self.toRename: os.renames(item[0], item[1]) That's it. os.renames will take care of all the intermediate directory creation so you don't even need to sort the list. -- Rhodri James *-* Wildebeeste Herder to the Masses From roy at panix.com Mon Dec 15 22:18:13 2008 From: roy at panix.com (Roy Smith) Date: Mon, 15 Dec 2008 22:18:13 -0500 Subject: socket and subprocess problem References: <6d3291c3-4e12-4bdd-884a-21f15f38d105@a12g2000pro.googlegroups.com> Message-ID: In article <6d3291c3-4e12-4bdd-884a-21f15f38d105 at a12g2000pro.googlegroups.com>, goatold at gmail.com wrote: > In my python code I use subprocess.Popen to run and external program > who will listen to a TCP port. And I also create a socket to connect > to the TCP port that the external program is listening. > I will get 'Connection refused, errno=111' when I try to > socket.connect(). > Class a: > def run() > subprocess.Popen(..) > Class b: > def run(): > sock = socket.socket() > sock.connect(..) > ################################# > test.py > # socket connect will fail here > a.run() > b.run() > ################################### > test1.py > if __name__ = '__main__': > a.run() > > test2.py > # socket will connect fine > if __name__ = '__main__': > b.run Sounds like a timing problem. I assume that the process started by a.run() creates a socket and does a bind/listen/accept sequence on it. The problem is, there's nothing in your code which guarantees that this happens before b.run() executes the connect() call. The cheesy way to test this is to sleep for a second somewhere between a.run() and b.run(). See if that helps. If it doesn't, then it's possible the process started by a.run() isn't doing what it's supposed to do. Try running test1.py, and while it's running, run netstat to see if you've got something listening on the port you expect. From google at mrabarnett.plus.com Tue Dec 9 14:07:08 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 09 Dec 2008 19:07:08 +0000 Subject: StringIO in 2.6 and beyond In-Reply-To: References: Message-ID: <493EC1DC.8050708@mrabarnett.plus.com> Bill McClain wrote: > On 2008-12-09, Peter Otten <__peter__ at web.de> wrote: > >>>>> out = io.StringIO() >>>>> print(u"hello", file=out, end=u"\n") >>>>> out.getvalue() >> u'hello\n' > > That has the benefit of working. Thank you! > > That can't be the intended behavior of print(), can it? Insering non-unicode > spaces and line terminators? I thought all text was unicode now. Or is that > only in 3.0? > In Python 2.x unmarked string literals are bytestrings. In Python 3.x they're Unicode. The intention is to make the transition from 2.x to 3.x easier by adding some features of 3.x to 2.x, but without breaking backwards compatibility (not entirely successfully!). From tmh.public at gmail.com Wed Dec 3 19:22:21 2008 From: tmh.public at gmail.com (Thomas M. Hermann) Date: Wed, 3 Dec 2008 16:22:21 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> Message-ID: <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> On Dec 3, 5:26?pm, Xah Lee wrote: > Agreed. My paypal address is ?xah @@@ xahlee.org?. (replace the triple > @ to single one.) Once you paid thru paypal, you can post receit here > if you want to, or i'll surely acknowledge it here. > > Here's what i will do: > > I will give a version of Mathematica code that has the same behavior > as his. And i will give timing result. The code will run in > Mathematica version 4. (sorry, but that's what i have) As i > understand, Jon is running Mathematica 6. However, i don't see > anything that'd require Mathematica 6. If my code is not faster or in > other ways not satisfactory (by your judgement), or it turns out > Mathematica 6 is necessary, or any problem that might occure, i offer > money back guarantee. > > ? Xah > ?http://xahlee.org/ > > ? > Alright, I've sent $20. The only reason I would request a refund is if you don't do anything. As long as you improve the code as you've described and post the results, I'll be satisfied. If the improvements you've described don't result in better performance, that's OK. Good luck, Tom From lie.1296 at gmail.com Mon Dec 8 01:53:42 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 8 Dec 2008 06:53:42 +0000 (UTC) Subject: tabs and spaces in py3k References: <774909e2-b248-4251-bbba-deb309e72714@x38g2000yqj.googlegroups.com> Message-ID: On Sun, 07 Dec 2008 20:51:50 -0800, rurpy wrote: > Do the Py3k docs need correction? If I were the maintainer of the parser, I'd add something like this: tab_width = random.randint(0, 1000) From wyldwolf at gmail.com Wed Dec 24 19:01:11 2008 From: wyldwolf at gmail.com (Kevin Kelley) Date: Wed, 24 Dec 2008 18:01:11 -0600 Subject: Python's popularity In-Reply-To: References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: <77895c1d0812241601qd11437fpf5830d5201c4f9a6@mail.gmail.com> On Tue, Dec 23, 2008 at 10:38 AM, r wrote: > > School time son, > This forum is much more than a question answer session, son. Sure > people are welcome to ask a Python related question. But this forum is > really the main highway of Python development and future. If your a > n00b go to the "Python forum.org", you will feel more comfy over > there. > > >From python.org (http://www.python.org/community/lists/) - python-list: Pretty much anything Python-related is fair game for discussion, and the group is even fairly tolerant of off-topic digressions; there have been entertaining discussions of topics such as floating point, good software design, and other programming languages such as Lisp and Forth. *Most discussion on comp.lang.python is about developing with Python, not about development of the Python interpreter itself.* python-dev: Note: python-dev is for work on developing Python (fixing bugs and adding new features to Python itself); if you're having problems writing a Python program, please post to comp.lang.python. *python-dev is the heart of Python's development. Practically everyone with Subversion write privileges is on python-dev, and first drafts of PEPs are often posted here for initial review and rewriting before their more public appearance on python-announce.* I think you are confusing lists r. Kevin -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Sun Dec 14 16:53:31 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 14 Dec 2008 16:53:31 -0500 Subject: Optimizing methods away or not? In-Reply-To: <0154b041$0$6988$c3e8da3@news.astraweb.com> References: <0154b041$0$6988$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I have a class with a method meant to verify internal program logic (not > data supplied by the caller). Because it is time-consuming but optional, > I treat it as a complex assertion statement, and optimize it away if > __debug__ is false: > > class Parrot: > def __init__(self, *args): > print "Initialising instance..." > if __debug__: > self.verify() # check internal program state, not args > if __debug__: > def verify(self): > print "Verifying..." Given that verify is only called from within _init__, I would put everything within one 'if __debug__' statement. Either inline if __debug__: or if for some reason you really don't like that, nested if __debug__: def verify(): print "Verifying..." verify() tjr From cmgui2 at gmail.com Sat Dec 20 17:18:40 2008 From: cmgui2 at gmail.com (cm_gui) Date: Sat, 20 Dec 2008 14:18:40 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> Message-ID: <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> > Seriously cm_gui, you're a fool. > Python is not slow. > > --JamesMills haha, getting hostile? python fans sure are a nasty crowd. Python is SLOW. when i have the time, i will elaborate on this. From lance.ellinghaus at eds.com Mon Dec 22 20:57:52 2008 From: lance.ellinghaus at eds.com (Ellinghaus, Lance) Date: Mon, 22 Dec 2008 20:57:52 -0500 Subject: Python's popularity In-Reply-To: <19b9ab88-6812-4416-9020-3be16b839fcd@m16g2000vbp.googlegroups.com> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com><18767.47566.709705.92@montanaro-dyndns-org.local> <19b9ab88-6812-4416-9020-3be16b839fcd@m16g2000vbp.googlegroups.com> Message-ID: <752A61D5C34D41478E638FC92AF9051B03563591@usahm207.amer.corp.eds.com> > > Alvin ONeal wrote: > > > Also worthy of mention: > > > I've seen python pre-installed on consumer HP desktops (I think as > > > part of a backup/restore script, but I'm not sure) > > > > It's pre-installed on every Mac (both desktop and laptop), too. > I am using a Vista HP right now that came pre-installed with Python. > Blew my mind when i found out :). This single reason just reinforced > my belief in Python. Now if we can get Python on every windows > platform... Check out IronPython. Fully supported and FUNDED by Micro$oft! http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython Lance Ellinghaus From prologic at shortcircuit.net.au Mon Dec 29 20:43:10 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 30 Dec 2008 11:43:10 +1000 Subject: get method In-Reply-To: <4819de67-72dc-415c-b4c8-2353581c2bc7@r2g2000vbp.googlegroups.com> References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> <4819de67-72dc-415c-b4c8-2353581c2bc7@r2g2000vbp.googlegroups.com> Message-ID: On Tue, Dec 30, 2008 at 11:38 AM, Ross wrote: > I realize the code isn't counting, but how am I to do this without > using an if statement as the problem instructs? I just gave you a hint :) cheers James From ken.dambrosio at segway.com Wed Dec 3 09:44:37 2008 From: ken.dambrosio at segway.com (Ken D'Ambrosio) Date: Wed, 3 Dec 2008 09:44:37 -0500 (EST) Subject: Good introductory book? Message-ID: <45131.66.155.201.114.1228315477.squirrel@webmail.jots.org> Hi, all. I'm getting ready to do some projects in Python, and I've cut my teeth a little bit, but I've found the "Learning|Programming Python" books from O'Reilly to be more-or-less useless (to my surprise -- I'm usually an O'Reilly fan). I really, really like "Python Essential Reference", but it's -- well, more of a reference than an intro. So, an introductory text that actually assumes some previous programming experience (as opposed to "Learning Python" which must be the most slowly-paced programming book ever) would be terrific. Thanks for your suggestions! -Ken From lolekk1233 at wp.pl Tue Dec 9 10:27:59 2008 From: lolekk1233 at wp.pl (Sexy18) Date: Tue, 9 Dec 2008 07:27:59 -0800 (PST) Subject: Very Cute And Very Sexy Blonde Stripping Message-ID: <345b885a-691a-4ba6-a8ab-9d5326c6f954@v39g2000pro.googlegroups.com> http://yeba.pl/show/movies/5257/Perfect_babe_-_Idealna_kobieta From Brian.Kelly at uwsp.edu Tue Dec 30 13:05:27 2008 From: Brian.Kelly at uwsp.edu (Kelly, Brian) Date: Tue, 30 Dec 2008 12:05:27 -0600 Subject: python import sys.path Message-ID: I have both 2.4 and 2.5 interpreters installed on a linux box. The PythonPath is set to : PYTHONPATH=/usr/lib64/portage/pym:/prod/bacula/local/lib64/python2.4/site-pa ckages:/prod/bacula/local/lib/python2.4/site-packages My main script is getting called like so: python2.4 cleanup.py wrkstnbs The imports statements in cleanup.py are as follows: import os,sys print sys.path from datetime import datetime from optparse import OptionParser # used for parsing parameters from bacula_conf import * # used for connecting to our databases, etc. from registration_cleanup \ import RegistrationCleanup # used for interacting w/ registration db (sql1) # and configuration database (genunix) import directory_cleanup as fclean # file cleanup. One of the scripts being imported from bacula_conf is called purge_client.py. It has the following imports: import sys import MySQLdb Everytime I run "python2.4 cleanup.py wrkstnbs" I get the following error: Traceback (most recent call last): File "purge_client.py", line 22, in import MySQLdb File "/prod/bacula/local/lib64/python2.4/site-packages/MySQLdb/__init__.py", line 27, in import _mysql ImportError: /prod/bacula/local/lib64/python2.4/site-packages/_mysql.so: undefined symbol: Py_InitModule4 If I print sys.path of both the calling script and the imported module I get the following sys.path from cleanup.py: ['/prod/bacula/local/tools/bacula_conf/maintenance', '/usr/lib64/portage/pym', '/prod/bacula/local/lib64/python2.4/site-packages', '/prod/bacula/local/lib/python2.4/site-packages', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib64/python2.4/lib-dynload', '/usr/lib/portage/pym', '/usr/lib64/python2.4/site-packages', '/usr/lib/python2.4/site-packages'] However the sys.path printed by the called module purge_client.py displays as such: ['/prod/bacula/local/tools/bacula_conf/maintenance', '/usr/lib64/portage/pym', '/prod/bacula/local/lib64/python2.4/site-packages', '/prod/bacula/local/lib/python2.4/site-packages', '/usr/lib64/python25.zip', '/usr/lib64/python2.5', '/usr/lib64/python2.5/plat-linux2', '/usr/lib64/python2.5/lib-tk', '/usr/lib64/python2.5/lib-dynload', '/usr/lib64/python2.5/site-packages'] If I call purge_client.py like so: python2.4 purge_client.py wrkstnbs the sys.path is: ['/prod/bacula/local/tools/bacula_conf/maintenance', '/usr/lib64/portage/pym', '/prod/bacula/local/lib64/python2.4/site-packages', '/prod/bacula/local/lib/python2.4/site-packages', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib64/python2.4/lib-dynload', '/usr/lib/portage/pym', '/usr/lib64/python2.4/site-packages', '/usr/lib/python2.4/site-packages'] Can anyone explain why purge_client.py has a different sys.path when imported from another script? At this point I'm quite puzzled and would like to continue using the 2.4 interpreter for the time being. Thanks, Brian Kelly -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 5082 bytes Desc: not available URL: From philip at semanchuk.com Thu Dec 4 23:27:34 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Thu, 4 Dec 2008 23:27:34 -0500 Subject: Running a Python script from crontab In-Reply-To: <6a302e08-e8be-4d5e-b754-11fc18468cc8@v4g2000yqa.googlegroups.com> References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> <126ba84a-0ea0-4a91-b7d2-89ed650e5d6c@d32g2000yqe.googlegroups.com> <6a302e08-e8be-4d5e-b754-11fc18468cc8@v4g2000yqa.googlegroups.com> Message-ID: <22F6B5D9-74D4-4DA6-A46D-2A263CC6F662@semanchuk.com> On Dec 4, 2008, at 4:21 AM, Astley Le Jasper wrote: > On Dec 4, 12:34 am, Lawrence D'Oliveiro central.gen.new_zealand> wrote: >> In message , >> Philip >> >> Semanchuk wrote: >>> In my experience, the environment in which a cron job runs is >>> different from the environment in which some command line scripts >>> run... >> >> Which is true, but again, cron should report the environment in the >> mail >> message. For example, here are some headers from a recent run of the >> maildir backup task I have scheduled twice a day: >> >> Subject: Cron $HOME/bin/backupdir $HOME/.maildir >> X-Cron-Env: >> X-Cron-Env: >> X-Cron-Env: >> X-Cron-Env: >> X-Cron-Env: > > Where do you get the emails from? In my experience, this depends on the machine config. The machine *should* be set up to email the user when a cron job fails. You'll log in via terminal and get the message "You have new mail" which means something went wrong with your cron job. As Lawrence said, run mail in the terminal window and you'll have a message from cron. You might not be getting these mails for some reason. From skip at pobox.com Sat Dec 27 13:44:32 2008 From: skip at pobox.com (skip at pobox.com) Date: Sat, 27 Dec 2008 12:44:32 -0600 Subject: Test message - please ignore Message-ID: <18774.30608.479342.587934@montanaro-dyndns-org.local> Working on the spam filter. Please ignore... S From steve at holdenweb.com Tue Dec 23 10:20:59 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 23 Dec 2008 10:20:59 -0500 Subject: iterating initalizations In-Reply-To: <20081223092504.aaf25192.darcy@druid.net> References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> <20081223092504.aaf25192.darcy@druid.net> Message-ID: D'Arcy J.M. Cain wrote: > On Mon, 22 Dec 2008 22:32:17 -0500 > Aaron Stepp wrote: >> Instead of writing a long list of initializations like so: >> >> A = [ ] >> B = [ ] >> ... >> Y = [ ] >> Z = [ ] >> >> I'd like to save space by more elegantly turning this into a loop. If > > Well, if all you want is a loop: > > for v in vars: > locals()[v] = [] > Note that this isn't guaranteed to work. While locals() will return a dict containing the names and values from the local namespace, you won't affect the local namespace by assigning values to the appropriate keys: >>> def f(): ... a = "hello" ... locals()["a"] = "goodbye" ... print a ... >>> f() hello >>> If you look at the function's code you will see that the local "a" is accessed using the LOAD_FAST and STORE_FAST opcodes, which take advantage of the knowledge that the name is local - the interpreter analyzed the function body looking for assignments to non-globals, and optimizes its treatment of such names. >>> dis.dis(f) 2 0 LOAD_CONST 1 ('hello') 3 STORE_FAST 0 (a) 3 6 LOAD_CONST 2 ('goodbye') 9 LOAD_GLOBAL 0 (locals) 12 CALL_FUNCTION 0 15 LOAD_CONST 3 ('a') 18 STORE_SUBSCR 4 19 LOAD_FAST 0 (a) 22 PRINT_ITEM 23 PRINT_NEWLINE 24 LOAD_CONST 0 (None) 27 RETURN_VALUE >>> > It's hard to tell if that's what you actually need though without > deeper analysis of your requirements. > I think it's unlikely that the OP really does need to create names dynamically, and should look at using either a dict indexed by the letters of self.__abet, or a list indexed from 0 to 24 instead. But you *are* correct about the need for a little more information ;-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From shaguf.m at gmail.com Wed Dec 24 02:35:52 2008 From: shaguf.m at gmail.com (Shaguf) Date: Tue, 23 Dec 2008 23:35:52 -0800 (PST) Subject: GIDS 2009 Java:: Save Big, Win Big, Learn Big: Act Before Dec 29 2008 Message-ID: <104a9b09-f1dc-4971-b8e1-7a24448835b0@f40g2000pri.googlegroups.com> ------------------------------------------------------------------- :::: Great Indian Developer Summit 2009 - GIDS.Java :::: :::: 24 April 2009 :::: :::: J N Tata Auditorium, IISc, Bangalore :::: :::: http://www.developersummit.com :::: ------------------------------------------------------------------- Dear Group members, The economic downturn will run out of steam trying to outdo the 'ready and waiting' software professional. Packed with premium knowledge, action plans and advise from been-there-done-it veterans, creators, and visionaries, the 2009 edition of Great Indian Developer Summit features focused sessions, case studies, workshops and power panels that will transform you into a force to reckon with. Java Speakers at the 2009 edition of GIDS include: Clemens Utschig- Utschig, Craig McClanahan, Debu Panda, Frank Nimphius, Howard Lewis Ship, Dr. Jim Webber, Jonas Jacobi, Mike Keith, Ola Bini, Prabhu Sunderraman, Thomas Marrs and Venkat Subramaniam. The conference this year has sessions on Guerrilla SOA, REST, Groovy, Building Web Services Using Spring, Struts 2.0 Deep Dive, Computing in the Cloud, Building RESTful Applications with JAX-RS, Tuning performance of JPA Applications, Diagnosing Production Java Applications, Building RESTful Applications with Ruby on Rails, Maven 2 at Work, Apache Utilities at Work, Web Services at Work, JRuby, Testing Java with Ruby, Tapestry 5 Inversion of Control, Clojure: Concurrent Functional Programming for the JVM, Unit testing, Apache Tapestry 5 and much more. Please have a look at http://www.developersummit.com/speakers.html for more info on the speakers and the sessions. Register before the 29th of December for Rs. 1,999/-. Besides the learning at the GIDS.Java conference on Friday, the 24th of April, this fee also includes: 1. Discount of 35% on the standard fee 2. Assured Gift - GIDS 2009 Cult T-shirt (upon receipt of payment on or before Jan 12 2009) 3. Entry into a lucky draw for the following gifts: Sony WEGA 29 inches (1), Mac Air Book (1), Wireless Mouse (50 nos), Apple iPOD 120 GB (5 nos). 4. Lunch and refreshments 5. Conference materials 6. Complimentary invitation to Cyrus Broacha's show at the Great Indian Developer Awards on Saturday, the 25th of April 2009 So hurry up and register now under the GIDS Loyalty discount scheme: http://www.developersummit.com/registration.html Wishing you and your family a Merry Christmas and a wonderful year ahead. Thanks, Shaguf http://www.developersummit.com/ info at developersummit.com From orsenthil at gmail.com Sat Dec 6 11:36:27 2008 From: orsenthil at gmail.com (Phoe6) Date: Sat, 6 Dec 2008 08:36:27 -0800 (PST) Subject: CVS Folders/Contents to Automatic Website - Program suggestions Message-ID: Hello all, I use cvs to maintain all my python snippets, notes, c, c++ code. As the hosting provider provides a public webserver also, I was thinking that I should convert the cvs folders automatically to website. 1) cvs2web is not what i mean. 2) doxygen may not be suitable. I tried with rest2web, it is requires that I write /restweb headers and files to be .txt files. An approach I have thought is: 1) run source-hightlight and create .html pages for all the scripts. 2) now write a script to index those script .htmls and create webpage. 3) Create the website of those pages. before proceeding, I thought I shall discuss here, if the members have any suggestion. What do do, when you want to maintain your snippets and notes in cvs and also auto generate it into a good website. I like rest2web for notes. Thanks, Senthil From stepp.aaron at gmail.com Mon Dec 22 17:22:56 2008 From: stepp.aaron at gmail.com (Aaron Stepp) Date: Mon, 22 Dec 2008 17:22:56 -0500 Subject: iterating initalizations Message-ID: Hi all: I'm new to python and trying to save time and code by iterating through list initializations as well as the assignments. I have the following code: import random from rtcmix import * from chimes_source import * from rhythmblock import * from pitchblock import * indexrand = random.Random() indexrand.seed(2) rhythm = rhythmBlock() pitch = pitchBlock() class pitchAndRhythm: def __init__self: self.__abet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def listCreate(self, num): if num > 25: print "Oops. This won't work" else: for a in range(num): b = indexrand.randint(0, 3) c = indexrand.randint(0, 7) index = self.__abet[a] index = [ ] index = index.append(rhythm.rhythmTwist(b, c)) This doesn't do what I expect (probably because I don't have a clue what I'm doing!): initalizing, then filling new arrays, each new one called A[ ], then B[ ], etc. This seems very un-pythonic, and I'm sure there is a right way to do it. I'm just lost! Thanks Aaron Stepp From schapman1974 at gmail.com Sun Dec 28 20:16:48 2008 From: schapman1974 at gmail.com (Stephen Chapman) Date: Sun, 28 Dec 2008 20:16:48 -0500 Subject: ZSI - ServiceContainer Message-ID: Does Anyone know how to Make the ServiceContainer work under SSL Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From antoinedg at gmail.com Mon Dec 15 11:32:00 2008 From: antoinedg at gmail.com (Antoine De Groote) Date: Mon, 15 Dec 2008 17:32:00 +0100 Subject: pylab.ylabel: put label on the other side Message-ID: Hey everybody, I'm plotting graphs with 2 y-axes, which I created using ax_left = pylab.subplot(111) ax_right = pylab.twinx() Then I switch the sides of the ticks: ax_left.yaxis.tick_right() ax_right.yaxis.tick_left() This works, the ticks are on the opposite sides (left axis ticks are on the right side and vice-versa). But, when I want to label the y-axes with for example pylab.axes(ax_left) pylab.ylabel('Some label') they are on the wrong side, i.e. not on the same side as the ticks of the corresponding y-axis. For this example, the label would be on the left side instead of the right side. This is giving me headaches for quite a few hours now, so maybe somebody knows a solution. Regards, antoine From lie.1296 at gmail.com Tue Dec 16 11:10:54 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 16 Dec 2008 16:10:54 +0000 (UTC) Subject: Generator slower than iterator? References: Message-ID: On Tue, 16 Dec 2008 12:07:14 -0300, Federico Moreira wrote: > Hi all, > > Im parsing a 4.1GB apache log to have stats about how many times an ip > request something from the server. > > The first design of the algorithm was > > for line in fileinput.input(sys.argv[1:]): > ip = line.split()[0] > if match_counter.has_key(ip): > match_counter[ip] += 1 > else: > match_counter[ip] = 1 nitpick: dict.has_key is usually replaced with if ip in match_counter: ... also, after investigating your code further, I see that you've unnecessarily used generators, the first code is simpler and you've not avoided any creation of huge intermediate list by using the generator this way. You won't get any performance improvement with this, and instead get a performance hit due to function overhead and name look up. From pavlovevidence at gmail.com Sat Dec 6 16:21:59 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 6 Dec 2008 13:21:59 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> Message-ID: On Dec 6, 9:12?am, "Russ P." wrote: > On Dec 6, 1:02?am, Antoine De Groote wrote: > > > > > Allowing "$" as a substitute for "self" wouldn't require this new syntax. > > > class C: > > ? ? def method($, arg): > > ? ? ? ? $.value = arg > > > I'm strongly against this. This looks ugly and reminds me of Perl and > > Ruby. (I don't have anything against these languages, but there's a > > reason I use Python). > > > Russ P. wrote: > > > On Dec 5, 6:21 pm, "Daniel Fetchinson" > > > wrote: > > >> Hi folks, > > > >> The story of the explicit self in method definitions has been > > >> discussed to death and we all know it will stay. However, Guido > > >> himself acknowledged that an alternative syntax makes perfect sense > > >> and having both (old and new) in a future version of python is a > > >> possibility since it maintains backward compatibility. The alternative > > >> syntax will be syntactic sugar for the old one. This blog post of his > > >> is what I'm talking about: > > > >>http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... > > > >> The proposal is to allow this: > > > >> class C: > > >> ? ? def self.method( arg ): > > >> ? ? ? ? self.value = arg > > >> ? ? ? ? return self.value > > > >> instead of this: > > > >> class C: > > >> ? ? def method( self, arg ): > > >> ? ? ? ? self.value = arg > > >> ? ? ? ? return self.value > > > >> I.e. explicit self stays only the syntax is slightly different and may > > >> seem attractive to some. As pointed out by Guido classmethods would > > >> work similarly: > > > >> class C: > > >> ? ? @classmethod > > >> ? ? def cls.method( arg ): > > >> ? ? ? ? cls.val = arg > > >> ? ? ? ? return cls.val > > > >> The fact that Guido says, > > > >> "Now, I'm not saying that I like this better than the status quo. But > > >> I like it a lot better than [...] but it has the great advantage that > > >> it is backward compatible, and can be evolved into a PEP with a > > >> reference implementation without too much effort." > > > >> shows that the proposal is viable. > > > >> I'd like this new way of defining methods, what do you guys think? > > >> Anyone ready for writing a PEP? > > > >> Cheers, > > >> Daniel > > > >> -- > > >> Psss, psss, put it down! -http://www.cafepress.com/putitdown > > > > I like it. > > > > I'll even go a step further and suggest that "$" be allowed as a > > > substitute for "self". It looks like a capital "S" (for Self), and it > > > stands out clearly. It also makes code more succinct with no loss of > > > readability. Think of the line wraps that could be avoided. > > It looks "ugly" simply because it is new to you. Once you get used to > it, I'll bet it will look fine. And resemblance to another language is > not a very good reason to reject it. Perl is not new to me and I am familiar with the syntax, such as it is. I find it unspeakably ugly. So, no, you would lose your bet if it were me. Carl Banks From Scott.Daniels at Acm.Org Tue Dec 16 17:19:32 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 16 Dec 2008 14:19:32 -0800 Subject: weird dict problem, how can this even happen? In-Reply-To: References: Message-ID: <88idnfej99XAtNXUnZ2dnUVZ_hednZ2d@pdx.net> Joel Hedlund wrote: > Duncan Booth wrote: >> I think you probably are correct. The only thing I can think that >> might help is if you can catch all the situations where changes to the >> dependent values might change the hash and wrap them up: before >> changing the hash pop the item out of the dict, then reinsert it after >> the change. > > That would probably require a lot of uncomfortable signal handling, > especially for a piece of functionality I'd like to be as unobtrusive as > possible in the application. > >> Alternatively give up on defining hash and __eq__ for FragmentInfo and >> rely on object identity instead. Perhaps your hash function could be something like: class HashedCache(dict): def __init__(self, dictionary): self.update(dictionary) self._hash = hash(tuple(sorted(dictionary.keys()))) def __hash__(self): return self._hash --Scott David Daniels Scott.Daniels at Acm.Org From stef.mientki at gmail.com Mon Dec 1 20:30:25 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 02 Dec 2008 02:30:25 +0100 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: <49348FB1.8080307@gmail.com> Jon Harrop wrote: > Xah Lee wrote: > >> And on this page, there are sections where Mathematica is compared to >> programing langs, such as C, C++, Java, and research langs Lisp, >> ML, ..., and scripting langs Python, Perl, Ruby... >> > > Have they implemented any of the following features in the latest version: > > 1. Redistributable standalone executables. > > 2. Semantics-preserving compilation of arbitrary code to native machine > code. > > 3. A concurrent run-time to make efficient parallelism easy. > > 4. Static type checking. > > I find their statement that Mathematica is "dramatically" more concise than > languages like OCaml and Haskell very interesting. I ported my ray tracer > language comparison to Mathematica: > > Mathematica (and MatLab) have a few large advantages over python / scipy / sage 1- although normally the cost a huge amount of money, students gets them (almost) for nothing (reminds me of a drug dealer ;-) 2- MatLab is th? industrial standard 3- Wolfram's and Mathworks websites are a huge source of (simple) theory and examples 4- a large number of publishers only accept articles based on commercial packages like MatLab / Labview 5- they form alliances if they come too close together ( e.g. MatLab and LabView) So how does a small community like the Python / Scipy / Sage community, which it's enormous diversity / induviduality (if I don't like one tiny detail, I'll start something completely new), ever think they are going to beat those commercial packages, even if the product, is technical speaking, much better ? Well I still have some hope, the recently published MatPlotLib documentation / galery is a good example. just my 1 cent (considering there's a recession), cheers, Stef From python.list at tim.thechases.com Mon Dec 1 10:46:43 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 01 Dec 2008 09:46:43 -0600 Subject: end of print = lower productivity ? In-Reply-To: <1228032887.6627.53.camel@lieryan-laptop> References: <757b4e03-7d13-4758-85c4-f5224ee9853b@j35g2000yqh.googlegroups.com> <21d250f9-1477-450e-9587-c4b28d08ea00@t3g2000yqa.googlegroups.com> <981d3e99-d2b4-4455-a52a-e906bd0fe7c4@r36g2000prf.googlegroups.com> <4931D571.8070007@tim.thechases.com> <1228032887.6627.53.camel@lieryan-laptop> Message-ID: <493406E3.6090304@tim.thechases.com> > For a proof, let's see what Google has to say about this: > "Windows text editor". Vim is on page 3, near the turning > point where nobody is talking about text-editor anymore and > more about text-editor reviews. Even worse is Emacs, on page > 6, after many other popular text-editors have been mentioned > several times. That's a pretty malformed "proof": http://www.google.com/search?q=people%20you%20should%20listen%20to%20regarding%20choice%20of%20text-editor You don't appear anywhere in the top *10* pages...QED ;-) However, if you want to play that game, vim.org appears on page #1 of http://www.google.com/search?q=best+text+editor Use what editor works for you -- but if evolution in the language's features makes difficulties for you but not for users of other editors, it's your editor that's the problem, not the language. Viva-la-print-function'ly yers, -tkc From amontfes at yahoo.es Mon Dec 15 16:31:39 2008 From: amontfes at yahoo.es (Antoni Mont) Date: Mon, 15 Dec 2008 22:31:39 +0100 Subject: Problem accessing a web page References: <47c890dc0812151216o59a3cbc2uf98d74604988d27@mail.gmail.com> <4946C45F.7060100@tim.thechases.com> Message-ID: Tim Chase wrote: > When you get the second page, are you getting the same content > back that you get if you do a search in your favorite browser? > > Using just > > content = urllib.urlopen(url2).read() > 'Error' in content # True > 'Friedrich' in content # False > > However, when you browse to the page, those two should be inverted: > > 'Error' in content # False > 'Friedrich' in content # True > > I've tried adding in the parameters correctly via post > > params = urllib.urlencode([ > ('params.forzaQuery', 'N'), > ... > ('layout', 'busquedaisbn'), > ]) > content = urllib.urlopen(url2, data).read() > > However, this too fails because the underlying engine expects a > session ID in the URL. I finally got it to work with the code below: > > import urllib > > data = [ > ('params.forzaQuery', 'N'), > ('params.cdispo', 'A'), > ('params.cisbnExt', '8484031128'), > ('params.liConceptosExt[0].texto', ''), > ('params.orderByFormId', '1'), > ('action', 'Buscar'), > ('language', 'es'), > ('prev_layout', 'busquedaisbn'), > ('layout', 'busquedaisbn'), > ] > > params = urllib.urlencode(data) > > url = > 'http://www.mcu.es/webISBN/tituloSimpleDispatch.do;jsessionid=5E8D9A11E4A28BDF0BA6B254D0118262' > > fp = urllib.urlopen(url, params) > content = fp.read() > fp.close() > > > but I had to hard-code the jsessionid parameter in the URL. This > would have to be determined from the initial call & response of > the initial URL (the initial URL returns a element with > the URL to POST to, including this magic jsessionid parameter). > > Hope this helps nudge you (the OP) in the right direction to get > what you're looking for. > > -tkc > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list OK, Tim, I think you got the point. The jsessionid change in every response of the initial URL, so I need to read it and stand with it during the session. Now I must guess how to do it. Thank you very much to you and also to Chris. Kind regards, Toni From martin at v.loewis.de Fri Dec 26 19:09:04 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 27 Dec 2008 01:09:04 +0100 Subject: Python 3 and my Mac (Leopard) In-Reply-To: <4952b38d$0$20300$607ed4bc@cv.net> References: <4952b38d$0$20300$607ed4bc@cv.net> Message-ID: <49557220$0$12632$9b622d9e@news.freenet.de> Dan wrote: > Is the python community just not interested in Macs? This is fairly close to the truth. The Mac port is currently mostly unmaintained, due to the past contributors having moved on or being occupied by other matters (such as Real Life). I would phrase it vice versa, though: the Mac community is not much interested in Python. Of course, Apple has a steady interest in Python, but that so far focuses on 2.x, is bound to Apple's product cycles, and did not went as far yet as assigning an Apple engineer to contribute to the Python core on a regular basis. To contribute in this area, you do need to deep understanding of OSX, so many Mac users are probably not qualified - and neither are most of the Python core contributors. Regards, Martin From robert.kern at gmail.com Tue Dec 2 18:17:03 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 02 Dec 2008 17:17:03 -0600 Subject: Hashlib py26 In-Reply-To: References: Message-ID: ShannonL at yogananda-srf.org wrote: > This feels a bit silly, but I am trying to encrypt some simple text with > the new hashlib library and then decrypt it back into text. I can do > this with M2Crypto RC4, but not the new hashlib. Could someone give me > a quick example. hashlib does not do encryption. It implements cryptographic hash functions which, while related to encryption algorithms and sometimes are a primitive component of such algorithms, do not actually encrypt and decrypt messages. http://en.wikipedia.org/wiki/Cryptographic_hash_function -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From pavlovevidence at gmail.com Mon Dec 29 16:47:51 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 29 Dec 2008 13:47:51 -0800 (PST) Subject: Python module import loop issue References: <02bc8567-695a-4277-9698-a95549a0bc98@w39g2000prb.googlegroups.com> Message-ID: <4a0557b7-e901-49ff-b4db-53f4d8a7c0f8@r40g2000yqj.googlegroups.com> On Dec 29, 10:51?am, Kottiyath wrote: > This might not be ?pure python question. Sorry about that. I couldnt > think of any other place to post the same. > I am creating a _medium_complex_ application, and I am facing issues > with creating the proper module structure. > This is my first application and since this is a run-of-the-mill > application, I hope someone would be able to help me. > > Base Module: > Contains definitions for Class A1, Class A2 > > Module 1.1: > Class B1 (refines A1) > Module 1.2: > Class C1 (refines A1) > Module 1.3: > Class D1 (refines A1) > > Module 2.1: > Class B2 (refines A2): > ? ? ? ? Uses objects of B1, C1, D1 > Module 2.2: > Class C2 (refines A2) > Module 2.3: > Class D2 (refines A2) > > -->Python Entry Module : Module EN<-- > Calls objects of B1, C1 and D1 > > Module EN and also Module 2 creates and calls the objects during run > time - and so calls cannot be hardcoded. > So, I want to use Factory methods to create everything. > > Module Factory: > import 1.1,1.2,1.3, ?2.1,2.2,2.3 > A1Factory: {'B1Tag':1.1.B1, 'C1Tag':1.2.C1, 'D1Tag':1.3.D1'} > A2Factory: {'B2Tag':2.1.B2, 'C2Tag':2.2.C2, 'D2Tag':2.3.D2'} > > But, since Module requires objects of B1, C1 etc, it has to import > Factory. > Module 2.1: > import Factory. > > Now, there is a import loop. How can we avoid this loop? > > The following ways I could think of > 1. Automatic updation of factory inside superclass whenever a subclass > is created. But, since there is no object created, ?I cannot think of > a way of doing this. I'm going to suggest three ways: a straightforward, good-enough way; a powerful, intelligent, badass way; and a sneaky way. 1. The straightforward, good-enough way Define functions in Factory.py called register_A1_subclass and register_A2_subclass, then call them whenever you create a new subclass. Factory.py ----------------------------- A1Factory = {} A2Factory = {} def register_A1_subclass(tag,cls): A1Factory[tag] = cls def register_A2_subclass(tag,cls): A2Factory[tag] = cls ----------------------------- package1/module1.py: ----------------------------- import Factory class B1(A1): # define class B1 here Factory.register_A1_subclass("B1Tag",B1) ----------------------------- So after you define B1, call Factory.register_A1_subclass to add it to the A1Factory. Factory.py no longer has to import package1.module2, so the circular import is broken, at the paltry price of having to add a boilerplate function call after every class definition. 2. The powerful, intelligent, badass way Metaclasses. I would guess you do not want to do this, and I wouldn't recommend it if you haven't studied up on how metaclasses work, but it's a textbook example of their usefulness. If you expect to use factory functions like this a lot, it might be worth your while to learn them. Anyway, here's a simple example to illustrate. It doesn't meet your requirements since all classes use the same factory; updating it to your needs is left as an exercise. Factory.py: ----------------------------- Factory = {} class FactoryMetaclass(type): def __new__(metaclass,name,bases,dct): cls = type.__new__(metaclass,name,bases,dct) tag = dct.get("tag") if tag is not None: Factory[tag] = cls return cls ------------------------------ Base.py: ------------------------------ import Factory class A2(object): __metaclass__ = FactoryMetaclass # define rest of A2 ------------------------------ package1/module2.py: ------------------------------ class B2(A2): tag = "B2Tag" #define rest of B2 ------------------------------ When the class B2 statement is executed, Python notes that the metaclass for A2 was set to FactoryMetaclass (subclasses inherit the metaclass), so it calls FactoryMetaclass's __new__ method to create the class object. The __new__ method checks to see if the class defines a "tag" attribute, and if so, adds the class to the Factory with that tag. Voila. (As a footnote, I will mention that I've created a library, Dice3DS, that uses metaclass programming in exactly this way.) 3. The sneaky way New-style classes maintain a list of all their subclasses, which you can retrieve by calling the __subclassess__ class method. You could use this to define a factory function that searches through this list for the appropriate subclass. Factory.py: ----------------------------- def _create_subclass(basecls,name): for cls in basecls.__subclasses__(): if cls.__name__ == name: return cls() cls2 = _create_subclass(cls,name) if cls2 is not None: return cls2() return None def create_A1_subclass(name): cls = _create_subclass(A1,name) if cls is None: raise ValueError("no subclass of A1 by that name") return cls ----------------------------- So here you search through A1's subclasses for a class matching the class's name. Note that we do it recursively, in case B1 (for instance) has its own subclasses, and I presume we do want those. You can change it to do a search by a tag class attribute if you wish; left as an exercise. > 2. Update A1Factory in each module which implements refinements. > _Very_important_, how do I make sure each module is hit - so that the > factory is updated? The module EN will be looking only at base module, > so the other modules is not hit. I will have to import every module in > EN - just to make sure that the A1Factory updation code is hit. This > looks in-elegent. Not worth it. The straightforward, good-enough way above is good enough. Carl Banks From digisatori at gmail.com Fri Dec 19 07:05:12 2008 From: digisatori at gmail.com (digisatori at gmail.com) Date: Fri, 19 Dec 2008 04:05:12 -0800 (PST) Subject: encoding problem Message-ID: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> The below snippet code generates UnicodeDecodeError. #!/usr/bin/env python #--*-- coding: utf-8 --*-- s = '???' u = unicode(s) It seems that the system use the default encoding- ASCII to decode the utf8 encoded string literal, and thus generates the error. The question is why the Python interpreter use the default encoding instead of "utf-8", which I explicitly declared in the source. From joe at strout.net Tue Dec 16 12:54:38 2008 From: joe at strout.net (Joe Strout) Date: Tue, 16 Dec 2008 10:54:38 -0700 Subject: AIM client code for Python? Message-ID: <732D7AE5-1429-4482-82FA-78328D6C3CF5@strout.net> I'd like to write an AIM bot in Python. I found and tried , but it doesn't work for me: Connecting... Traceback (most recent call last): File "aimbot-1.py", line 17, in bot.go() File "/Users/jstrout/Documents/Python-Dev/AIMbot/toc.py", line 62, in go self.process_loop() File "/Users/jstrout/Documents/Python-Dev/AIMbot/toc.py", line 156, in process_loop event = self.recv_event() File "/Users/jstrout/Documents/Python-Dev/AIMbot/toc.py", line 230, in recv_event dtemp = self._socket.recv(buflen - len(data)) socket.error: (54, 'Connection reset by peer') I wrote to the author a week ago, but never got a reply. It could be as simple as changing the server addresses in toc.py, currently: TOC_SERV_AUTH = ("login.oscar.aol.com", 29999 ) TOC_SERV = ( "toc.oscar.aol.com", 9898 ) ...but I don't understand AIM well enough to know the correct values (and was rather hoping that I wouldn't have to). Does anyone know how to get Py-TOC to work, or have another Python TOC implementation to suggest? Thanks, - Joe From walterbyrd at iname.com Mon Dec 22 14:27:15 2008 From: walterbyrd at iname.com (walterbyrd) Date: Mon, 22 Dec 2008 11:27:15 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> Message-ID: <649f7890-315c-4711-990b-5ec7e5cd5a3b@i20g2000prf.googlegroups.com> On Dec 22, 11:42?am, "Ellinghaus, Lance" wrote: > Yes, Ruby has taken some of the popularity out of Python, but they are > also hitting different markets. Do you mean different markets within web development, or do you mean ruby is used mostly for web-dev, while python is used for other stuff? From google at mrabarnett.plus.com Thu Dec 18 09:19:15 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 18 Dec 2008 14:19:15 +0000 Subject: C API and memory allocation In-Reply-To: <494a55fb$0$31873$9b4e6d93@newsspool3.arcor-online.net> References: <59352942-e976-4ef4-bc40-c8953df0a792@c36g2000prc.googlegroups.com> <0d35b640-71ad-4cde-8869-74878b2f3981@r36g2000prf.googlegroups.com> <494a55fb$0$31873$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <494A5BE3.2090505@mrabarnett.plus.com> Stefan Behnel wrote: > Aaron Brady wrote: >> I see. Do I read correctly that 's' is only useful when the >> argument's position is known? > > I assume you meant "length". > > >> Otherwise you can't know its length or >> change its reference count. > > The internal representation of Python byte strings is 0 terminated, so > strlen() will work. > But remember that a bytestring can contain a zero byte (chr(0) in Python 2.x). From google at mrabarnett.plus.com Sat Dec 6 21:26:40 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 07 Dec 2008 02:26:40 +0000 Subject: Learning Python now coming from Perl In-Reply-To: References: Message-ID: <493B3460.90308@mrabarnett.plus.com> Bertilo Wennergren wrote: > Aahz wrote: > >> In article , > >> Bertilo Wennergren wrote: > >>> I don't suppose there is any introductory material out there that is >>> based on Python 3000 and that is also geared at people with a Perl >>> background? Too early for that I guess.. > >> Honestly, the differences between 2.x and 3.0 are small enough that it >> doesn't much matter, as long as you're not the kind of person who gets >> put off by little problems. Because so much material is for 2.x, you >> may be better off just learning 2.x first and then moving to 3.x. > > The main reason I waited until Python 3000 came out is > the new way Unicode is handled. The old way seemed really > broken to me. Much of what I do when I program consists > of juggling Unicode text (real Unicode text with lots of > actual characters outside of Latin 1). So in my case > learning version 2.x first might not be very convenient. > I'd just get bogged down with the strange way 2.x handles > such data. I'd rather skip that completely and just go > with the Unicode handling in 3.0. > I wouldn't have said it was broken, it's just that it was a later addition to the language and backwards compatibility is important. Tidying things which would break backwards compatibility in a big way was deliberately left to a major version, Python 3. From digitig at gmail.com Thu Dec 4 10:48:24 2008 From: digitig at gmail.com (Tim Rowe) Date: Thu, 4 Dec 2008 15:48:24 +0000 Subject: Python advocacy ... HELP! In-Reply-To: <5f8c1a52-545e-402e-863a-acdf23d04c78@h20g2000yqn.googlegroups.com> References: <5f8c1a52-545e-402e-863a-acdf23d04c78@h20g2000yqn.googlegroups.com> Message-ID: 2008/12/4 Michael_D_G : > > I am a faculty member of a cs department. We currently teach C++ in > our intro to programming course. I am teaching this class and it seems > to me that we would be much better served teaching python in the intro > course, C++ for Data structures, as we do now, and Java in object > oriented programming, as we do now. > Some of my colleagues agree with me but some still see python as a > niche language and don't understand > how we could teach anything beyond C, C++ or Java. Try asking "Are we teaching computer science, so that the students will be able to cope with whatever they meet once they graduate, or are we teaching computer programming, in a couple of specific languages, so that the students will be completely unprepared if they meet anything else?" -- Tim Rowe From harrrrpo at gmail.com Thu Dec 18 14:34:01 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Thu, 18 Dec 2008 21:34:01 +0200 Subject: Location HTTP Header In-Reply-To: <5f4d3006-0750-4faa-ae1b-3a0408abbe2a@g1g2000pra.googlegroups.com> References: <68fa1e9b-6652-4d34-a7fe-fc98db8bf6d4@m16g2000vbp.googlegroups.com> <5f4d3006-0750-4faa-ae1b-3a0408abbe2a@g1g2000pra.googlegroups.com> Message-ID: <538050a90812181134i12461daal31647521ccb7674b@mail.gmail.com> use LiveHTTPHeaders with firefox and show us browser-server interaction -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Dec 24 02:46:04 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2008 05:46:04 -0200 Subject: Strategy for determing difference between 2 very large dictionaries References: <1230102996.2303.1291616055@webmail.messagingengine.com> Message-ID: En Wed, 24 Dec 2008 05:16:36 -0200, escribi?: > I'm looking for suggestions on the best ('Pythonic') way to > determine the difference between 2 very large dictionaries > containing simple key/value pairs. > By difference, I mean a list of keys that are present in the > first dictionary, but not the second. And vice versa. And a list > of keys in common between the 2 dictionaries whose values are > different. > The 2 strategies I'm considering are: > 1. Brute force: Iterate through first dictionary's keys and > determine which keys it has that are missing from the second > dictionary. If keys match, then verify that the 2 dictionaries > have identical values for the same key. Repeat this process for > the second dictionary. > 2. Use sets: Create sets from each dictionary's list of keys and > use Python's set methods to generate a list of keys present in > one dictionary but not the other (for both dictionaries) as well > as a set of keys the 2 dictionaries have in common. I cannot think of any advantage of the first approach - so I'd use sets. k1 = set(dict1.iterkeys()) k2 = set(dict2.iterkeys()) k1 - k2 # keys in dict1 not in dict2 k2 - k1 # keys in dict2 not in dict1 k1 & k2 # keys in both > Using the set > of keys in common, compare values across dictionaries to > determine which keys have different values (can this last step be > done via a simple list comprehension?) Yes; but isn't a dict comprehension more adequate? [key: (dict1[key], dict2[key]) for key in common_keys if dict1[key]!=dict2[key]} (where common_keys=k1&k2 as above) -- Gabriel Genellina From steve at holdenweb.com Mon Dec 15 12:24:14 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 15 Dec 2008 12:24:14 -0500 Subject: regex problem .. In-Reply-To: <3b10c2060812150421y1c3e7da6ha1b72c736e2a20d4@mail.gmail.com> References: <3b10c2060812150421y1c3e7da6ha1b72c736e2a20d4@mail.gmail.com> Message-ID: Analog Kid wrote: > Hi All: > I am new to regular expressions in general, and not just re in python. > So, apologies if you find my question stupid :) I need some help with > forming a regex. Here is my scenario ... > I have strings coming in from a list, each of which I want to check > against a regular expression and see whether or not it "qualifies". By > that I mean I have a certain set of characters that are permissible and > if the string has characters which are not permissible, I need to flag > that string ... here is a snip ... > > flagged = list() > strs = ['HELLO', 'Hi%20There', '123123@#@'] > p = re.compile(r"""[^a-zA-Z0-9]""", re.UNICODE) > for s in strs: > if len(p.findall(s)) > 0: > flagged.append(s) > > print flagged > > my question is ... if I wanted to allow '%20' but not '%', how would my > current regex (r"""[^a-zA-Z0-9]""") be modified? > The essence of the approach is to observe that each element is a sequence of zero or more "character", where character is "either letter/digit or escape." So you would use a pattern like "([a-zA-Z0-9]|%[0-9a-f][0-9a-f])+" regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From BrooklineTom at gmail.com Thu Dec 11 12:26:11 2008 From: BrooklineTom at gmail.com (brooklineTom) Date: Thu, 11 Dec 2008 09:26:11 -0800 (PST) Subject: Deeper tracebacks? References: Message-ID: <81a32daf-e337-43b0-93d4-86a8f0317c6c@o40g2000prn.googlegroups.com> BINGO! Give that man a CIGAR! The specifics don't seem to be quite right (there is no sys.last_traceback), but R.Bernstein put me directly on the correct track. I misunderstood the traceback module documentation. OK, I just plain didn't read it correctly, it's right there ("extract_stack(): Extract the raw traceback from the current stack frame."). The answer is to use traceback.extract_tb (), called with sys.exc_info()[3] (the stackframe that raised the exception). Another sterling example of the benefits of reading the fine manual -- for comprehension this time. Instead of: aRawStack = traceback.extract_stack() do this: aRawStack = traceback.extract_tb(sys.exc_info()[2]) With this change, aRawStack contains the following: >>> aRawStack[0][3] 'answer = apply(aMethod, [], {})' >>> aRawStack[1][3] 'int(3).zork()' This is *exactly* what I was seeking. I appreciate all the responses, and especially appreciate the pointer from R.Bernstein. Thx, Tom On Dec 11, 4:49 am, ro... at panix.com (R. Bernstein) wrote: > brooklineTom writes: > > I want my exception handler to report the method that originally > > raised an exception, at the deepest level in the call-tree. Let give > > an example. > > > import sys, traceback > > class SomeClass: > > def error(self): > > """Raises an AttributeError exception.""" > > int(3).zork() > > > def perform_(self, aSelector): > > try: > > aMethod = getattr(self, aSelector, None) > > answer = apply(aMethod, [], {}) > > except: AttributeError, anAttributeErrorException: > > aRawStack = traceback.extract_stack() > > answer = None > > > When I call "perform_" (... SomeClass().perform_('error')), I want to > > collect and report the location *within the method ("error") that > > failed*. The above code reports the location of "perform_", and no > > deeper in the call tree. > > > Anybody know how to accomplish this? > > extract_stack() without any arguments is getting this from the > *current frame* which as you noted doesn't have the last exception > info included which has been popped; variable sys.last_traceback has the frames > at the time of the exception, I think. > > So in your code try changing: > aRawStack = traceback.extract_stack() > to > aRawStack = traceback.extract_stack(sys.last_traceback) From exarkun at divmod.com Tue Dec 16 15:36:50 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 16 Dec 2008 15:36:50 -0500 Subject: Can anyone suggest a good HTTP/1.1 web client? In-Reply-To: Message-ID: <20081216203650.20272.244726156.divmod.quotient.21919@ohm> On Tue, 16 Dec 2008 12:18:17 -0800 (PST), Kottiyath wrote: >Hi all, > I have to connect to a secure website every second to get the data >and then post to it. I have been investigating on many web clients in >python, but nothing fits the bill properly. > The ones I tried implementing are: > 1. httplib based - I created myself. (I cannot use urllib2 since I >have to transfer files, and urllib2 doesnt have multipart content-type >support) > 2. Twisted web client. > I also looked at mechanize etc too. > > The problems I face are - > 1. I liked twisted a lot, but when I implemented it, I found that >client support is there only for twisted.web and not twisted.web2. >Since I connect to the same website every time, I would like to have >persistent connections and since twisted.web is HTTP/1.0, persistent >connection support is not yet there. Without persistent connections, I >would have to have TCP connection handshake everytime and it is taking >too much time. I'm working on a new HTTP 1.1 client for Twisted. You can follow the progress at or check out the development branch and give it a try. Persistent connections are not yet implemented, but there's not a whole lot left to do to support them. That means pipelining isn't supported yet, but once persistent connections are supported pipelining will be simple. As with any Twisted protocol, it's just as easy to run over SSL as over TCP, so HTTPS is essentially supported for free. There is not yet support for proxies, but this is planned as well and should be only a little more work to implement. > [snip] > > Is there any good web client which I can use straight up? Or would >I have to implement the whole thing myself? It looks like a big beast >and I was wondering whether python provides it straight up. If you'd like to help out with the new Twisted HTTP client, that would be wonderful. Even if you can just try it out and report any problems you run into, that would be immensely helpful. Jean-Paul From andreas.roehler at online.de Thu Dec 11 08:31:18 2008 From: andreas.roehler at online.de (Andreas =?UTF-8?B?UsO2aGxlcg==?=) Date: Thu, 11 Dec 2008 14:31:18 +0100 Subject: looking up function's doc in emacs References: Message-ID: Xah Lee wrote: > in programing elisp in emacs, i can press ?Ctrl+h f? to lookup the doc > for the function under cursor. > > is there such facility when coding in perl, python, php? > > (i'm interested in particular python. In perl, i can work around with > ?perldoc -f functionName?, and in php it's php.net/functionName. Both > of which i have a elisp command with a shortcut that let me jump to > the doc) > > Thanks. > > Xah > ? http://xahlee.org/ > > ? python help(FUNCTIONNAME) From benjamin.kaplan at case.edu Fri Dec 26 19:41:39 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 26 Dec 2008 19:41:39 -0500 Subject: multiply each element of a list by a number In-Reply-To: References: Message-ID: On Fri, Dec 26, 2008 at 7:05 PM, wrote: > > What does *not* work is > 3 * [0,1,2] > As you know, this gives > [0,1,2,0,1,2,0,1,2] > What I am hoping for is > [0,3,6] > I see that I can use > numpy.multiply(3,range(3)) > but this seems overkill to me. Can you tell I am coming to Python from > Matlab? > > Thanks -- Rob you can do [i * 3 for i in range(3)] > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Wed Dec 31 03:52:09 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 31 Dec 2008 08:52:09 GMT Subject: Memory leak problem (while using tkinter) References: Message-ID: <6s0q5pF3oddcU1@mid.uni-berlin.de> On Tue, 30 Dec 2008 20:21:06 -0800, Andr? wrote: > I have written a small program (my first Tkinter-based app) to play > around the idea mentioned on > http://rogeralsing.com/2008/12/07/genetic-programming-evolution-of-mona- lisa/ > and, in doing so, have encountered a memory leak problem. I have seen > mentions on the web of using the delete() method of canvas to prevent > such problems - which I have tried to do with limited success. Below is > the code I wrote; to run it, you will need a small image file > (I used the one found on http://alteredqualia.com/visualization/evolve/) > that is saved under "mona_lisa.png". > > Any help would be greatly appreciated. I don't see anything obvious but that the program is too long and uses too much components to be sure that `Tkinter` is the culprit. Try too trim it down to the smallest possible program that still has the problem. Ciao, Marc 'BlackJack' Rintsch From castironpi at gmail.com Tue Dec 30 10:52:26 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 30 Dec 2008 07:52:26 -0800 (PST) Subject: why cannot assign to function call References: <495867C2.7080807@gmail.com> <5e807c67-7d97-4b8a-8c5f-a3b97f5c5003@i20g2000prf.googlegroups.com> Message-ID: <5fb29c80-a6a4-4cb4-aa62-0d2aeb437662@o4g2000pra.googlegroups.com> On Dec 30, 8:21?am, John O'Hagan wrote: > On Tue, 30 Dec 2008, Aaron Brady wrote: > > [...] > > > On a technicality, to avert a flaming, "change the value of 'b'" is an > > ambiguous phrase. There are two interpretations of "change what 'b' > > refers to" and "change what 'b' refers to". Even in spoken language, > > I don't think that emphasis can resolve them either. > > > One means, 'make a change in the world, in the actual configuration of > > such and such actual matter.' The other means, 'update the axioms the > > speaker is using to communicate to the listeners. (Such and such will > > no longer refer to such and such; it will refer to such and such; > > accept this and reject that.)' To make an observation, reference is a > > purely linguistic phenomenon. > > > I, for one, am at a loss for how to disambiguate it. I'm open to > > suggestions. > > I think you've already done so quite clearly. But I suspect the ambiguity > centres on the word "change" - in the first interpretation it means "alter" > (the object in place), in the second, it more precisely means "exchange" (one > object for another). > > I'd be interested to know to what extent this ambiguity exists in languages > other than English - as a somewhat relevant example, ambiguities in English > around the verb "to be" ("I am Fred", "I am tall", "I am hungry"; i.e., > identity vs. attributes vs. state) disappear in other languages which use > different verbs in each case. > > On a (philosophical) side-note, I wonder if this is a real ambiguity: while > the statement that the name "b" now refers to a different object is > clear-cut, the other interpretation, that the object itself has changed but > is somehow still the same object, is a bit of an ontological minefield. > > Fortunately, unlike the murky world of philosophy, Python (AIUI) simplifies > this question by simply declaring that yes, in the case of mutable objects, > we may say that we are still referring to the same object although we've > changed it, and no, in the case of immutable objects, we may not, and must > exchange it if we want a different "value" (a word too fraught with ambiguity > in this context to use unquoted!). > > The sometimes useful fuzziness of human languages means we don't need to ask, > for example, "how tall is the object currently referred to by the name > Fred?", but in Python, it helps to understand that this is what's going on. > > Regards, > > John There are a few problems going on here. (My ultimate goal is a unambiguous, non-arbitrary way to talk about Python; it's just that unambiguous and non-arbitrary are really tall orders.) One is the dependence (supervenience) of meaning on grammar (semantics on syntax, function on form). One is the absence of form in computing and math. Another is the composite identity. I think the problem goes deeper than just English. In any language that has a plural, the propositions in question come out as, 'one thing is two things' or 'two things are one thing'. According to some rules, these are ungrammatical sentences, due to plurality disagreement. Ex: The Morning Star is ... The Evening Star is ... *The Morning Star and The Evening Star is... *The Morning Star and The Evening Star are... Neither of the latter two is correct. (* marks ungrammatical.) As such, the listener isn't sure what meaning to take. Accepting that, I'll adopt the terms John proposed, 'change' vs. 'exchange', the former when the material configuration changes, the latter when the communication axioms change. b= [2, 3] b= [3, 4] 'b' has exchanged. (Somewhat ungrammatical.) b= [2, 3] b.append( 4 ) 'b' has changed. According to this, when you replace every floorboard on a porch, one at a time, it's still the same porch-- it's changed, it's different, and it's the same. However, if you haul off the porch and put a new one in its place, it's not. ('porch[:]=' vs. 'porch='.) You can't just look at the initial and final configurations of matter to determine so. Therefore, 'id' is an informal function. Identity isn't defined on math objects, only on Python objects; there is no notion of 'is' in math. It doesn't make sense to ask if '2 is 2', only if '2=2'. In Python, they are both defined, and not the same. Unfortunately, in the language involved, 'same' and 'different' aren't opposites, so the communication is horrendous and belabored. Lastly, equality is a tolerance concept on the computer, not in math. The computer looks at voltage thresholds in the underlying gates; the actual voltages, beyond a certain precision, of two representations of '0110' aren't the same. Further, the actual voltages of one representation of '0110' over time aren't equal either. However, that means, that in order to answer some questions about equality and identity, we have to address the implementation of the compiler. You might get the same answers in many or practically all implementations of Python, but the specification doesn't make the leap onto a real computer, where the equivalents of continuity of form are defined in an unspecified way. You could even have continuity of the contents of a byte (word)-- that is, they (the actual voltages on the individual wires of the word) don't change at all between times t0 and t1, but an identity test on it fails. Perhaps composite identity isn't a common source of problems for language speakers. P.S. Didn't say 'value'. From michele.simionato at gmail.com Tue Dec 16 01:23:33 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 15 Dec 2008 22:23:33 -0800 (PST) Subject: ethical questions about global variables References: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> Message-ID: On Dec 16, 3:45?am, "Giampaolo Rodola'" wrote: > Hi, > in a module of mine (ftpserver.py) I'd want to add a (boolean) global > variable named "use_gmt_times" to decide whether the server has to > return times in GMT or localtime but I'm not sure if it is a good idea > because of the "ethical" doubts I'm gonna write below. Global variables have a bad reputation, but they are not so bad in Python. Notice that: 1. global variables in Python are local to the module they are defined in; 2. class names and module names are usually global variables and nobody complains about that. 3. if you use an ALL_CAPS convention it is quite quite clear that you are using a global variable. Actually the ALL_CAPS convention is for constants, but sometimes I use it for configuration variables too, if they are set at the beginning and they are never changed during the running of the program. If you have more than a single global, it makes sense to introduce a configuration object, as others have said (this is how typically work) but if you have a single parameter the confuguration object is not worth the effort, IMO. M. Simionato From arkanes at gmail.com Thu Dec 4 11:44:33 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 4 Dec 2008 10:44:33 -0600 Subject: "as" keyword woes In-Reply-To: <0147e4df$0$20670$c3e8da3@news.astraweb.com> References: <7dudnSS7uIn_KarUnZ2dnUVZ_tTinZ2d@earthlink.com> <0147e4df$0$20670$c3e8da3@news.astraweb.com> Message-ID: <4866bea60812040844w1b6b143fpdaceaa64982fd970@mail.gmail.com> On Thu, Dec 4, 2008 at 8:45 AM, Steven D'Aprano wrote: > On Thu, 04 Dec 2008 20:53:38 +1000, James Mills wrote: > >> Readability of your code becomes very important especially if you're >> working with many developers over time. >> >> 1. Use sensible meaningful names. >> 2. Don't use abbreviations. > > This is excellent advice, but remember, what is a sensible meaningful > name is domain-specific. In a maths library, this would be sensible: > > def poly(x): > return 4*x**3 -2*x**2 +3*x -7 > > and this ridiculous: > > def poly(real_number): > return 4*real_number**3 -2*real_number**2 +3*real_number -7 > > I actually wonder. The former is "sensible" in a math context because there's a very long tradition in mathematics of using terse, inscrutable placeholders for terms. I'm not a mathematician and I don't know anything about the history of mathematical notation, but I'd guess this has something to do with the fact that maths has historically been done with a pencil and paper, and that terseness is an important quality when you have a limited canvas and lots of stuff to write. Aside from the cultural indoctrination, though (and that may be a real and strong force when dealing with math software, and I don't want to discount it in general, just for purposes of this discussion) why is it more sensible to use "x" here instead of "number" or "real" or "real_number" or something else? From onlinejob4ind at gmail.com Tue Dec 23 23:40:37 2008 From: onlinejob4ind at gmail.com (kela) Date: Tue, 23 Dec 2008 20:40:37 -0800 (PST) Subject: earn more then,15,989$/- Message-ID: <35e2d75e-d503-4a3a-99cc-0a7909a5b4ef@k1g2000prb.googlegroups.com> THE REAL ONLINE JOB from,USA. earn more then,15,989$/- per month,if you want more detail,on No investment. http://onlinejob4ind.homestead.com/ From psftw1 at gmail.com Sun Dec 14 17:09:07 2008 From: psftw1 at gmail.com (peter s.) Date: Sun, 14 Dec 2008 14:09:07 -0800 (PST) Subject: Building from source -- zlib/binascii problems 2.5.2/2.6.1 References: <71531b64-535f-49d0-a0c6-7704df83b251@f18g2000vbf.googlegroups.com> <49458079.1000304@v.loewis.de> <003b0307-c8df-489b-98e6-cfaa35d050a4@k1g2000prb.googlegroups.com> Message-ID: On Dec 14, 5:03?pm, "peter s." wrote: > On Dec 14, 4:54?pm, "Martin v. L?wis" wrote: > > > > > > Target: x86_64-redhat-linux > > > gcc -pthread -shared build/temp.linux-x86_64-2.5/location/of/ > > > Python-2.5.2/Modules/zlibmodule.o -L/usr/local/lib -lz -o build/ > > > lib.linux-x86_64-2.5/zlib.so > > > /usr/bin/ld: skipping incompatible /usr/lib/libz.so when searching for > > > -lz > > > Do > > > ? file /usr/lib/libz.so > > > It might be a 32-bit library, in which case you can check whether > > /usr/lib64 has a 64-bit library. I'm puzzled why it only > > happens for -lz; perhaps you are better of compiling with a 32-bit > > compiler. > > > Regards, > > Martin > > $ file /usr/lib/libz.s* > /usr/lib/libz.so: ? ? ? symbolic link to `libz.so.1.2.3' > /usr/lib/libz.so.1: ? ? symbolic link to `libz.so.1.2.3' > /usr/lib/libz.so.1.2.3: ELF 32-bit LSB shared object, Intel 80386, > version 1 (SYSV), stripped I meant to also add $ file /usr/lib64/libz.s* /usr/lib64/libz.so.1: symbolic link to `libz.so.1.2.3' /usr/lib64/libz.so.1.2.3: ELF 64-bit LSB shared object, AMD x86-64, version 1 (SYSV), stripped So.. it seems as though I need to get it to point to the 64 bit version (or compile the zlib that comes with Python source). I'm not sure how to override that. From ffbittencourt at gmail.com Fri Dec 5 10:37:45 2008 From: ffbittencourt at gmail.com (Fred) Date: Fri, 5 Dec 2008 12:37:45 -0300 Subject: No subject Message-ID: <4ed4cf0c0812050737o1d42c9e2j6e53223dcda73a3e@mail.gmail.com> -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at marcher.name Sat Dec 27 15:08:23 2008 From: martin at marcher.name (Martin) Date: Sat, 27 Dec 2008 21:08:23 +0100 Subject: [2.4.4] creating a datetime.datetime from an XML xs:dateTime Message-ID: <5fa6c12e0812271208x4baccaedk262e51becb6e2076@mail.gmail.com> Hi, subject says it all. I'd like to create a python datetime.datetime from an xs:string[1] I know about time.strptime and could get to a datetime.datetime from there, but that would be error prone like: * are there time zones? * how is the year represented * etc, yadda yadda so I'd rather like to find some method (hopefully within the standard lib) that had more peer review than only me :). thanks martin [1] http://www.w3.org/TR/xmlschema-2/#dateTime -- http://soup.alt.delete.co.at http://www.xing.com/profile/Martin_Marcher http://www.linkedin.com/in/martinmarcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From nemokingdom at gmail.com Fri Dec 26 08:07:30 2008 From: nemokingdom at gmail.com (nemo) Date: Fri, 26 Dec 2008 05:07:30 -0800 (PST) Subject: Process with ftplib Message-ID: Hi,all There seems something wrong when I use multiprocessing.Process with ftplib, My ftp class has a connection method like this: class qftp: def __init__(...): self.ftp = FTP() def connection(self): self.ftp.connect(self.addr, self.port) self.ftp.login(self.user, self.password) when i call the method like: ftp = qftp(host, port, user, password) ftp.connect() ftp.pwd() It works well but when I using the Process module, something seems wrong: ftp = qftp(host, port, user, password) p = multiprocessing.Process(target = ftp.connect) p.join() ftp.ftp.pwd() #after join, i think a connection has made, but it throws an exception This give me a 'NoneType object has no attribute sendall' exception. I wondered why? From gruszczy at gmail.com Fri Dec 12 08:08:04 2008 From: gruszczy at gmail.com (=?UTF-8?Q?Filip_Gruszczy=C5=84ski?=) Date: Fri, 12 Dec 2008 14:08:04 +0100 Subject: Removing None objects from a sequence In-Reply-To: <01524eee$0$20617$c3e8da3@news.astraweb.com> References: <01524eee$0$20617$c3e8da3@news.astraweb.com> Message-ID: <1be78d220812120508g55393212h2ae7d027a54a4d9e@mail.gmail.com> I am not doing it, because I need it. I can as well use "if not elem is None", but I just wanted to know, if there is some better way of doing this. I like to know :-) And I can't understand why you are becoming so aggressive because of this. Just because I asked for that, doesn't mean, that I will put some obfuscated code into my project. I just wanted to learn something new - I checked itertools, I googled a bit, now I wanted to ask here if someone knew some really cool way of this. All the other assumptions weren't really necessary. Thanks for those ideas, however. I like the last one a lot :) -- Filip Gruszczy?ski From geekmail at usenot.de Thu Dec 4 11:00:17 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Thu, 4 Dec 2008 17:00:17 +0100 Subject: Please fix your clock [was Re: Multiple equates] References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> <0147f4b7$0$20670$c3e8da3@news.astraweb.com> Message-ID: <20081204170017.4be41c7f@usenot.de> On 04 Dec 2008 15:53:21 GMT Steven D'Aprano wrote: > Hendrik, I think your PC's clock is wrong. You seem to be posting > from the future. So? Maybe he is. What's your problem? /W -- My real email address is constructed by swapping the domain with the recipient (local part). From timr at probo.com Tue Dec 30 23:51:06 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 31 Dec 2008 04:51:06 GMT Subject: parsing csv files class References: Message-ID: "alex goretoy" wrote: > >This line doesn't work for me. bufferp is empty afterwards. > >self.bufferp= [dict(zip(header,line)) for line in reader] > >needs to be this >self.bufferp= [dict(zip(header,line)) for line in self.buffer] Yes, when I was writing this, I started out eliminating self.buffer entirely. When I added it back in, I forgot to change this back. >I may need some assistance in another thread about a pycurl library. I want >it to fall back to urllib/urllib2 if pycurl is not installed module. look >for thread "pycurl urllib fallback" I will post it here shortly to >python-list. One common method is like this: try: import pycurl except ImportError: pycurl = None import urllib -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From steve at holdenweb.com Tue Dec 9 23:34:58 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 09 Dec 2008 23:34:58 -0500 Subject: Python & LEGO Mindstorm control... In-Reply-To: <000001c959d0$49b1f9c0$dd15ed40$@ch> References: <000001c959d0$49b1f9c0$dd15ed40$@ch> Message-ID: <493F46F2.9020702@holdenweb.com> feinepost at bluewin.ch wrote: > Hi Toni Meyer, > > > > I would be quite interested in your Python extension to send ir signals > to the rcx. > > > > I am quite new to this stuff, hope I?ll understand what you did? > > > > Could you send it to me? > > > > Thanks a lot! > Daniel: You do realize that you posted to a mailing list, not an individual, right? There's no evidence that "Toni Meyer" will see your message. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From dongzhi at gmail.com Wed Dec 10 00:40:08 2008 From: dongzhi at gmail.com (dongzhi) Date: Tue, 9 Dec 2008 21:40:08 -0800 (PST) Subject: List Problem Message-ID: Hi All, I have one problem for List. Like that: format='just "a" ""little"" test' part = format.split('"') print part the result is : ['just ', 'a', ' ', '', 'little', '', ' test'] the list part have 7 element. If I execute part[1], I have got 'a'. If I execute part[2], I have got ' '. But, if I execute part[1::2], I have got ['a', '', '']. I don't know why. Please tell me why. Thanks. Best Regards, Liu Ming From jeremiah.dodds at gmail.com Thu Dec 4 04:31:31 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Thu, 4 Dec 2008 04:31:31 -0500 Subject: Python advocacy ... HELP! In-Reply-To: <5f8c1a52-545e-402e-863a-acdf23d04c78@h20g2000yqn.googlegroups.com> References: <5f8c1a52-545e-402e-863a-acdf23d04c78@h20g2000yqn.googlegroups.com> Message-ID: <12cbbbfc0812040131t606d71c5n10a8c2090f20710f@mail.gmail.com> On Thu, Dec 4, 2008 at 1:52 AM, Michael_D_G wrote: > > I am a faculty member of a cs department. We currently teach C++ in > our intro to programming course. I am teaching this class and it seems > to me that we would be much better served teaching python in the intro > course, C++ for Data structures, as we do now, and Java in object > oriented programming, as we do now. > Some of my colleagues agree with me but some still see python as a > niche language and don't understand > how we could teach anything beyond C, C++ or Java. > > I have looked at several interesting academic papers, on doing just > this approach. I have also looked through the > python web page to get examples of industry players using python in a > non-trivial way. Yes, I know, Google, > Microsoft, Sun, CIA website running on Plone, NOAA, NASA. If anyone > has any recent articles, > or if anyone on the list is at a fortune 500 company, how do I refute > the notion that Python > is a "marginal" language because according to TOBIE it only less than > a 6% market share. > > -michael > -- > http://mail.python.org/mailman/listinfo/python-list > Well, I'm not in a fortune 500, but python _is_ currently paying my bills. There is a python job board, and a very active community around the language - I don't think it's hard to show that it's not a "niche" language anymore. Canonical, as well as Google, O'reilly, Sun, _and_ Microsoft are sponsors of the PSF. That's pretty much every major name in the software-development world right now. Niche languages aren't going to be getting that much support, from that many sources. Blender uses python. Bittorrent. Trac. Bazaar. Mercurial. But you know all this already. It seems to me that it shouldn't even matter if it _is_ a niche language though, considering that you're trying to convince people to use it as an "intro to programming" language. I would think that an introductory programming course in this day and age should be more about general concepts than language bits, and python is pretty good at staying out of your way - other than Scheme, I can't think of a better language to use to demonstrate the process of programming on a high level. Showing some code to your colleagues, in both C++ and python, and showing how the python code is close to being psuedo-code, and easier to understand would help, as well as showing the interpreter (or ipython), and how that could be very useful in class. It's intro to programming - the specific language should take a backseat to how easy it is to express ideas to the person with no programming experience in a clean manner, right? It seems to me that that's the point that your colleagues need to understand - being a good programmer (and, by association, being led down the path to being a good programmer) is more about understanding abstraction and how to break down a problem than what language is used, especially at the beginning. This was perhaps less true 10 years ago, when it was much more important to have a firm understanding of what's going on at a lower level to implement anything non-trivial, but these days there are plenty of useful things and learning that can be done with practically no knowledge of (for instance) machine architecture. I know the above wasn't exactly what you were asking for, but I hope it wasn't useless. -------------- next part -------------- An HTML attachment was scrubbed... URL: From renesd at gmail.com Mon Dec 8 05:19:32 2008 From: renesd at gmail.com (illume) Date: Mon, 8 Dec 2008 02:19:32 -0800 (PST) Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? References: <5ccd4a18-cd2b-4040-90c6-33723af15e96@b38g2000prf.googlegroups.com> <7e1a9226-c7a9-4b5e-bfbb-ea079639d6a2@t39g2000prh.googlegroups.com> <682de8aa-62b1-477a-8b31-ae7698b1ffe7@w1g2000prk.googlegroups.com> <4b2bcda5-cee2-484e-9fc7-47caaf7a165e@z27g2000prd.googlegroups.com> Message-ID: <6590e515-ef71-4441-baef-1847178bf1d0@g1g2000pra.googlegroups.com> On Dec 8, 8:59?pm, alex23 wrote: > On Dec 8, 7:18?pm, illume wrote: > > > It's easier to teach only requiring *using* classes, and functions > > than *creating* them. ?This is important if it's being used to teach > > programming - as you don't need to teach people two fairly large > > concepts before you can do anything. > > I'm just kind of aghast at the idea of "teaching" anyone how to > program games by using large, imperative chunks of code. I don't see > functions as being a "fairly large concept" at all, and utterly vital > to being able to write anything but the most basic 'hello world' > example code. > Yes, teaching hello world without requiring the creation classes is a *good thing*. Imagine having to create classes to make a hello world program? You'd have a typical java hello world program. This means you need to explain the concept of OO before they can do hello world. It's about teaching concepts separately, rather than requiring them to be taught all at once. If you don't need to use something, then why bother using it? Just for purity? Python has a long history of not making everything classes. So I see requiring the creation of classes to do 'hello world' as being un-pythonic and overly complex. I also see it getting in the way of seeing results, which is important when intially learning programming. > > Also python has very slow function calls, so avoiding using callbacks > > is also faster. > > Wouldn't it be better to teach people the basics of coding -before- > setting out to optimise their code? I was explaing the advantages of avoiding callbacks, and avoiding requiring the creation of classes. I think it's simpler, and faster to avoid callbacks. I was not saying that it's better to optimize peoples code before teaching people the basics of programming. From jstroud at mbi.ucla.edu Thu Dec 4 05:00:53 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 04 Dec 2008 02:00:53 -0800 Subject: Pythonic design patterns In-Reply-To: References: Message-ID: Slaunger wrote: > Hi comp.lang.python > I was therefore wondering if you could recommend a book or a resource > concerning design patterns with special focus on the possibilities in > Python? > > In that manner I may be able to both learn programming more pythonic > AND learn the design patterns. > > -- Slaunger Check the python cheat sheet for the most common idioms: http://rgruet.free.fr/PQR25/PQR2.5.html#Workspace. You should also check out http://effbot.org/zone/index.htm and peruse Fredrik Lundh's code. His blog is worth a look as well. He is a master of pythonic idioms and patterns. The cookbook has a lot of complex examples and may not provide you with the insight you are looking for. Only a small fraction of the recipes do this. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From dfnsonfsduifb at gmx.de Sat Dec 6 11:38:03 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Sat, 06 Dec 2008 17:38:03 +0100 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: <55d79070-0c11-4fb9-8cf5-b8cc7c54b5d2@v42g2000yqv.googlegroups.com> References: <55d79070-0c11-4fb9-8cf5-b8cc7c54b5d2@v42g2000yqv.googlegroups.com> Message-ID: info at orlans-amo.be schrieb: > 2 problems: endianness and trailing zer byte. > This works for me: This is very strange - when using "utf16", endianness should be detected automatically. When I simply truncate the trailing zero byte, I receive: Traceback (most recent call last): File "./modify.py", line 12, in a = AddressBook("2008_11_05_Handy_Backup.txt") File "./modify.py", line 7, in __init__ line = f.readline() File "/usr/local/lib/python3.0/io.py", line 1807, in readline while self._read_chunk(): File "/usr/local/lib/python3.0/io.py", line 1556, in _read_chunk self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) File "/usr/local/lib/python3.0/io.py", line 1293, in decode output = self.decoder.decode(input, final=final) File "/usr/local/lib/python3.0/codecs.py", line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) File "/usr/local/lib/python3.0/encodings/utf_16.py", line 69, in _buffer_decode return self.decoder(input, self.errors, final) UnicodeDecodeError: 'utf16' codec can't decode byte 0x0a in position 0: truncated data But I suppose something *is* indeed weird because the file I uploaded and which did not yield the "truncated data" error ia 1559 bytes, which just cannot be. Regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From robert.kern at gmail.com Mon Dec 1 19:11:16 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 01 Dec 2008 18:11:16 -0600 Subject: optimization In-Reply-To: References: Message-ID: Neal Becker wrote: > Arnaud Delobelle wrote: > >> Neal Becker writes: >> >>> I noticed in some profiling, that it seems that: >>> >>> def Func (): >>> def something(): >>> ... >>> >>> It appears that if Func is called many times, this nested func >>> definition will cause significant overhead. Is this true? I guess >>> I've become accustomed to decent compilers performing reasonable >>> transformations and so have tended to write code for clarity. >> If something() can be defined outside Func(), how is it clearer to >> define it inside? > > If it's only used inside. I, for one, find that significantly less clear. I only expect functions to be defined inside of functions if they are going to use lexical scoping for some reason. If I read your code, I'd probably waste a good five minutes trying to figure out what part of the local scope you were using before I would conclude that you just did it because you thought it looked better. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From benjamin.kaplan at case.edu Fri Dec 12 13:11:39 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 12 Dec 2008 13:11:39 -0500 Subject: (Very Newbie) Problems defining a variable In-Reply-To: References: Message-ID: On Fri, Dec 12, 2008 at 12:50 PM, Dennis Lee Bieber wrote: > On Fri, 12 Dec 2008 03:42:55 -0800 (PST), febaen at gmail.com declaimed the > following in comp.lang.python: > > > #!/usr/bin/python > > #Py3k, UTF-8 > > > > bank = int(input("How much money is in your account?\n>>")) > > target = int(input("How much money would you like to earn each year? > > \n>>")) > > > Just for my curiosity -- did Python 3.x (besides turning print into > a function) also change input() to behave as the old raw_input()? > Yes. > > The above would be very discouraged in Python 2.x... in favor of ... > int(raw_input(...)) > > > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alexoplocatie at gmail.com Wed Dec 17 05:30:02 2008 From: alexoplocatie at gmail.com (aka) Date: Wed, 17 Dec 2008 02:30:02 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> Message-ID: <2eaf2da1-6ce3-432d-9cca-80a6da797495@q37g2000vbn.googlegroups.com> Due to being in a hurry I didn't paste correctly so I lost the try clause (sorry). The intention is to parse a csv file and (ultimately) put values of column 1 ("id") in a list (so I need to append in the loop) that will be used to fill a session var. The complete code is: roles = [] inp = 'C:/temp/test.csv' try: fp = open(inp, 'rb') reader = csv.reader(fp, dialect='excel', delimiter=';') for r in reader: roles.append(r) ## ultimately should be something like r.id or r[0] except: msg = 'Something's wrong with the csv.reader' return dict(file=inp,roles=str(roles)) The roles list isn't populated at all :( From adi at lspl.net Sun Dec 7 23:39:13 2008 From: adi at lspl.net (sniffer) Date: Sun, 7 Dec 2008 20:39:13 -0800 (PST) Subject: infering the number of args a function takes at runtime Message-ID: hi all, i am a python newbie, in a project currently doing i need to find out the number of arguments that a function takes at runtime.? Is this possible ,if so how do i do this,i ve looked through the python documentation but couldnt find anything.any help will be great TIA From castironpi at gmail.com Thu Dec 11 15:52:37 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 11 Dec 2008 12:52:37 -0800 (PST) Subject: Problems running on HP Intel duo core machine References: <200809221443.25765.inq1ltd@inqvista.com> <200812051608.56335.inq1ltd@inqvista.com> Message-ID: On Dec 11, 1:58?pm, jim-on-linux wrote: > py help, > > I produced a program that runs on windows. > One client is using an HP machine with an Intel cpu > E2200 @ 2.2ghz., and with .99 G ram. > The machine is using Win XP Pro 32 bit OS with service > pack 2 > > I ran Dependency Walker and everything is OK. > > I used py2exe to build the exe file with bundle > files:1 and also 3, with the same traceback results. > > I created a test print module that imports both > win32api and win32ui modules and its only job is to > print a page of text. > > The first module that is imported is win32api. > line 8 of that module adds to the path the module named > 'win32api.pyd'. > The import is is completed without error. > > The next module that is imported is win32ui. > line 8 of that module adds to the path a module named > 'win32ui.pyd'. > The search for the win32ui.pyd module seems to be the > cause of the problem. ? > Traceback: > ImportError: Dll load failed: The specified module > could not be found. Is this your complete traceback? It is possible 'win32ui.pyd' is trying to load something else it can't find. From bdesth.quelquechose at free.quelquepart.fr Sun Dec 21 15:14:50 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 21 Dec 2008 21:14:50 +0100 Subject: Are Django/Turbogears too specific? In-Reply-To: References: Message-ID: <494eb16e$0$22710$426a74cc@news.free.fr> Philip Semanchuk a ?crit : (snip) > From the reading I did, I gathered that Django was really good if you > want to do what Django is good at, but not as easy to customize as, say, > Pylons. That was my first impression too, and was more or less true some years ago. After more experience, having gained a deeper knowledge of Django's internals, I can tell you this is just not true. You can "customize" it as you want - meaning: you can use any ORM (or no ORM at all) and any template language you want, as long as you don't intend to use django's ORM and template language related features (which just don't exist in Pylons). IOW : Django is just as flexible as Pylons (or pretty close to), but has more to offer if you stick to builtin components. NB : not to dismiss Pylons, which is a pretty great framework too, and use IMHO better default components (namely SQLAlchemy and Mako). From cournape at gmail.com Thu Dec 11 02:56:14 2008 From: cournape at gmail.com (David Cournapeau) Date: Thu, 11 Dec 2008 16:56:14 +0900 Subject: density plot In-Reply-To: References: Message-ID: <5b8d13220812102356r17a1e186k367b5ff62cd92f99@mail.gmail.com> On Thu, Dec 11, 2008 at 1:57 PM, wrote: > Hi, > > Does anyone know how to make the density plot, more specifically a > gaussian-smoothed version of a histogram. Actually, it's not exactly > a plot that I want. What I want to do is get the maximum count (or > highest peak) of the density distribution. It's different from the > probability density function that has the center at zero. > > In S plus and R, there is the "density" function which I can use to > get the max x and y in the frequency distribution. scipy ML is more appropriate for this kind of questions: http://www.scipy.org/Mailing_Lists In scipy, there is a kernel density estimator, which is one popular method for non-parametric density estimation, and fit exactly the "Gaussian smoothed version of the histogram" when used with Gaussian kernels. David From rogerb at rogerbinns.com Wed Dec 24 02:26:49 2008 From: rogerb at rogerbinns.com (Roger Binns) Date: Tue, 23 Dec 2008 23:26:49 -0800 Subject: Strategy for determing difference between 2 very large dictionaries In-Reply-To: <1230102996.2303.1291616055@webmail.messagingengine.com> References: <1230102996.2303.1291616055@webmail.messagingengine.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 python at bdurham.com wrote: > Feedback on my proposed strategies (or better strategies) would be > greatly appreciated. Both strategies will work but I'd recommend the second approach since it uses already tested code written by other people - the chances of it being wrong are far lower than new code. You also neglected to mention what your concerns are or even what "very large" is. Example concerns are memory consumption, cpu consumption, testability, utility of output (eg as a generator getting each result on demand or a single list with complete results). Some people will think a few hundred entries is large. My idea of large is a working set larger than my workstation's 6GB of memory :-) In general the Pythonic approach is: 1 - Get the correct result 2 - Simple code (developer time is precious) 3 - Optimise for your data and environment Step 3 is usually not needed. Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAklR5DUACgkQmOOfHg372QSuWACgp0xrdpW+NSB6qqCM3oBY2e/I LIEAn080VgNvmEYj47Mm7BtV69J1GwXN =MKLl -----END PGP SIGNATURE----- From klaus.kopec at tuebingen.mpg.de Tue Dec 9 13:14:33 2008 From: klaus.kopec at tuebingen.mpg.de (Klaus Kopec) Date: Tue, 09 Dec 2008 19:14:33 +0100 Subject: pickling a circular object inherited from list In-Reply-To: <3b1bab42-657c-4b93-9236-aa5236c16826@w1g2000prk.googlegroups.com> References: <3b1bab42-657c-4b93-9236-aa5236c16826@w1g2000prk.googlegroups.com> Message-ID: >> What did I do wrong? > Old Python version? :) > Seems to work in 3.0 (don't have 2.6 currently to check but IMO it's > fixed there as well). It works for me with v3.0 as well, but not with v2.6.1 (same error as stated before for v2.4). Is there any way to fix this in v2.6.1 or even v2.4? Right now I cannot switch to v3.0 because I depend on several not compatible packages (numpy, biopython, ...) From jstroud at mbi.ucla.edu Sun Dec 7 16:53:51 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 07 Dec 2008 13:53:51 -0800 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Luis Zarrabeitia wrote: > > Quoting James Stroud : > >> First, here is why the ability to throw an error is a feature: >> >> class Apple(object): >> def __init__(self, appleness): >> self.appleness = appleness >> def __cmp__(self, other): >> assert isinstance(other, Apple), 'must compare apples to apples' >> return cmp(self.appleness, other.appleness) >> >> class Orange(object): pass >> >> Apple(42) == Orange() > > I beg to disagree. > The right answer for the question "Am I equal to this chair right here?" is not > "I don't know", nor "I can't compare". The answer is "No, I'm not a chair, thus > I'm not equal to this chair right here". If someone comes to my house, looking > for me, he will not run away because he sees a chair before he sees me. Your > assert doesn't belong inside the methot, it should be up to the caller to decide > if the human-chair comparisons make sense or not. I certainly don't want to be > type-checking when looking for an object within a mixed-type collection. > >> This reminds me of complex numbers: would 4 + 4i be equal to sqrt(32)? > > I assume you meant sqrt(32i). No, I definitely didn't mean sqrt(32i). I'm using sqrt() to represent the mathematical square root, and not an arbitrary function one might define, by the way. My point is that 4 + 4i, sqrt(32), and sqrt(-32) all exist in different spaces. They are not comparable, even when testing for equality in a pure mathematical sense. If when encounter these values in our programs, we might like the power to decide the results of these comparisons. In one context it might make sense to throw an exception, in another, it might make sense to return False based on the fact that we consider them different "types", in yet another context, it might make sense to look at complex plane values as vectors and return their scalar magnitude for comparison to real numbers. I think this ability to define the results of comparisons is not a shortcoming of the language but a strength. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From tjreedy at udel.edu Thu Dec 4 14:55:08 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Dec 2008 14:55:08 -0500 Subject: Python 3 read() function In-Reply-To: <20081204194232.20272.544720092.divmod.quotient.15718@ohm> References: <20081204194232.20272.544720092.divmod.quotient.15718@ohm> Message-ID: Jean-Paul Calderone wrote: > On Thu, 04 Dec 2008 14:25:48 -0500, Terry Reedy wrote: >> [snip] >> >> In my test, I read Python25.chm with 2.5 and Python30.chm with 3.0. >> >> Rereading Python30.chm without closing *is* much faster. >> >>> f=open('Doc/Python30.chm','rb') >> >>> d=f.read() >> >>> d=f.read() >> >>> d=f.read() > > Did you think about what this does? Whoops ;-) f.seek(0) first and it is maybe a bit faster, but not 'much'. From wicijowski at gmail.com Sun Dec 28 15:34:04 2008 From: wicijowski at gmail.com (janislaw) Date: Sun, 28 Dec 2008 12:34:04 -0800 (PST) Subject: tkinter 3.0 multiple keyboard events together References: <600d4b68-6fe2-4c2c-b425-1a739430bb54@s9g2000prg.googlegroups.com> <7b5e466c-d75d-4e71-b559-f8a0d3718094@r15g2000prd.googlegroups.com> Message-ID: <655327e0-47b5-4c0b-a028-c1ed1692b14f@r15g2000prd.googlegroups.com> On 28 Gru, 09:43, Pavel Kosina wrote: > well, I am working on a tutorial for youngster (thats why i need to stay > the code as easy as possible). In this game you are hunted by robots. I > could use key"7" on numeric keypad for left-up moving but seems to me, > that "4"+"8" is much more standard for them. > > > Hmmm. Maybe you'd like to hook into Tkinter event loop, i.e. by custom > > events if you don't like periodical polling. > > No, that would be even more difficult. I already have a code that use > your idea: > > from Tkinter import * > root = Tk() > > pressedKeys=set() > > def onKeyPress(event): > pressedKeys.add(event.keysym) > > def onKeyRelease(event): > pressedKeys.remove(event.keysym) > > def move(): > print list(pressedKeys) > root.after(100,move) > > root.bind("", onKeyPress) > root.bind("", onKeyRelease) > root.after(100,move) > root.mainloop() > > well, I thought that gui?s have such a problem already built-in - so > that i am not pressed to code it. You know, its not exactly about me - > if I do it for myself, for my program, that there is no problem, but I > need to explained it to begginners ..... And I do not want, as might be > more usual, do my module, that would cover this "insanity" (look at it > with 13-years old boy eyes ;-) ). Do you like to say me, that this is > not a standard "function" neither in tkinter, not say gtk or the others, > too? Ok, I get it then! Your goal is very humble :) In the piece of code we have came together to, there is a functionality you already want - the pressedKeys. I suppose, that you'd like to hide from the further implementors (children). You can write another module, which could contain this piece of code and could be imported by kids to have the desired features. Meaning only getting this list of keys. But what you write here: > I would expect something like this: > > def onKeyTouch(event): > ? ? print (event.keysymAll) > > root.bind("", onKeyTouch) ...is a bit misleading. There is no such thing as simultaneous events - for that the event dispatcher loop is designed - to simplyfy all usual stuff with parallel paradigsm such as interrupts, thread safety etc. An event is in my eyes a response to a short action, let's call it atomic. There's no need to pretend, that clicking a few keys simultanously is sth immediate and the software could by any chance guess that a few keys were actually clicked. Even the keyboard driver does some sequential scanning on the keys, and the key codes are then send to the board sequentially as well. Try to run this code: #---------------- #Tkinter multiple keypress #Answer http://groups.google.com/group/comp.lang.python/browse_thread/thread/88788c3b0b0d51d1/c4b7efe2d71bda93 import Tkinter import pprint import time tk = Tkinter.Tk() f = Tkinter.Frame(tk, width=100, height=100) msg = Tkinter.StringVar() msg.set('Hello') l = Tkinter.Label(f, textvariable=msg) l.pack() f.pack() keys = set() lastTime = None def keyPressHandler(event): keys.add(event.char) global lastTime now = time.time() if lastTime: difference = now - lastTime if difference < 0.1: #seconds print difference, 's' lastTime = now display() def keyReleaseHandler(event): keys.remove(event.char) display() def display(): msg.set(str(keys)) f.bind_all('', keyPressHandler) f.bind_all('', keyReleaseHandler) f.mainloop() #-------------------------------- ... and find out, how 'simultaneous' they are. For me it's 0.0, meaning that the event handlers were executed one after another, but sometimes there is sth like 0.0309998989105 s - proabably an USB latency, or an operating system context switch - hard to tell. If you'd like to have two key clicks to generate a single event, you'd have to write some timeout code (threading.Timer or tk stuff is handy) to check how 'simultaneous' they actually were. Search web for events in <> inequality signs if you really want this. I don't know gtk, but hey, pygame has pygame.key.get_pressed if you'd like to switch: http://www.pygame.org/docs/ref/key.html Have luck Jan From steve at REMOVE-THIS-cybersource.com.au Tue Dec 30 20:19:29 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Dec 2008 01:19:29 GMT Subject: Triple quoted string in exec function ? References: Message-ID: <016abfa1$0$6988$c3e8da3@news.astraweb.com> On Tue, 30 Dec 2008 15:35:28 -0600, Rob Williscroft wrote: > Stef Mientki wrote in news:mailman.6399.1230668197.3487.python- > list at python.org in comp.lang.python: > >>>> And, by the way, exec is a *statement*, not a function! >>>> >> exec ( Init_Code, PG.P_Globals ) >> >> I've really doubt that this is a statement, unless I don't understand >> what a statement is. >>>> >>>> >> > In python 2.x the above is a statement that is passed a tuple: > > http://docs.python.org/reference/simple_stmts.html#exec The documentation doesn't say anything about it accepting a tuple as an argument. The tuple argument works in both 2.5 and 2.6. Curious. I was also surprised by this behaviour: >>> g, l = {}, {} # no globals, no locals >>> exec "x = 1" in g, l >>> l {'x': 1} >>> g.keys() ['__builtins__'] I see *now* that this is documented: "...the current implementation MAY add a reference to the dictionary of the built-in module __builtin__ under the key __builtins__ (!)." [emphasis added] but it's still rather disconcerting. That means that: exec "some potentially dangerous code" in {}, {} isn't as safe as I thought it was. -- Steven From duncan.booth at invalid.invalid Fri Dec 5 03:31:38 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 Dec 2008 08:31:38 GMT Subject: Don't you just love writing this sort of thing :) References: Message-ID: Lawrence D'Oliveiro wrote: > In message , Duncan Booth wrote: > >> Have you ever considered trying to write readable code instead? >> >> (I must admit I haven't checked whether GZipFile works with the 'with' >> statement... > > That's why I prefer writing _correct_ code instead. Good idea, but the mess you posted is going to be virtually untestable whereas splitting it up into small testable functions will make it much easier for you to actually get somewhere near your goal of correct code. BTW, by trimming half of my sentence you changed its meaning significantly. You implied that I gave an example without caring whether it could work whereas the other half of the sentence pointed out that if GZipFile requires it you may need to add a single function call to my code. -- Duncan Booth http://kupuguy.blogspot.com From cournape at gmail.com Fri Dec 12 05:25:14 2008 From: cournape at gmail.com (David Cournapeau) Date: Fri, 12 Dec 2008 19:25:14 +0900 Subject: How do I manually uninstall setuptools (installed by egg)? In-Reply-To: References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> <47c890dc0812091904p12e75510sbe0b8858eb2f6d9e@mail.gmail.com> Message-ID: <5b8d13220812120225q5f88238j19bb083ba6e98406@mail.gmail.com> On Thu, Dec 11, 2008 at 10:30 PM, Nick Craig-Wood wrote: > David Cournapeau wrote: >> On Wed, Dec 10, 2008 at 12:04 PM, Chris Rebert wrote: >> > On Tue, Dec 9, 2008 at 6:49 PM, wrote: >> >> On Ubuntu, I accidentally manually installed setuptools >> >> http://pypi.python.org/pypi/setuptools/0.6c9 (by running the .egg file >> >> as a shell script via sudo), and now realize I should just be using >> >> apt to take care of my system Python packages. >> > >> > Really, why? setuptools has more Python packages/programs available >> > and updates faster than Debian. >> > It's also likely that some of the Debian Python packages are installed >> > using setuptools anyway. >> > So, why do you think apt and not setuptools is The Right Way(tm)? >> >> Setuptools is certainly not the right way to install packages >> system-wide on debian, it is very likely to break the whole thing. > > It wouldn't be too difficult to make a .deb target which would collect > all the files that did get installed into a package. It would be a > rather rough and ready package but would do the job. Depends what you mean by would do the job: rather rough certainly does not mean "would do the job" for something as essential as a package IMO. > > The .deb would then be uninstallable in the usual (dpkg --purge) way. > > Did anyone think about that? Yes, there is stddeb which does that (make a .deb package from a setuptools package). > > easy_install can do that I think... Not without a lot of hoola, unfortunately; for example, it breaks stow, so I have to use specialy scripts to circumvent the damn thing and make it what I tell him to do. I never understood what's easy about easy install: it is broken in so many ways, and has caused me so many pains - even when I was not using - that I do not trust it at all. I only use it to download packages (and even then it manage to fail more than work), and always install them from setup.py afterwards (at which step I of course also have to circumvent setuptools if the package uses setuptools). cheers, David From bj_666 at gmx.net Sun Dec 21 08:34:35 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Dec 2008 13:34:35 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <015da0a4$0$20656$c3e8da3@news.astraweb.com> Message-ID: <6r6uvbFfb643U5@mid.uni-berlin.de> On Sun, 21 Dec 2008 12:45:32 +0000, Duncan Booth wrote: > You seem to have made an unwarranted assumption, namely that a binary > operator has to compile to a function with two operands. There is no > particular reason why this has to always be the case: for example, I > believe that C# when given several strings to add together optimises > this into a single call to a concatenation method. > > Python *could* do something similar if the appropriate opcodes/methods > supported more than two arguments: > > a+b+c+d might execute a.__add__(b,c,d) allowing more efficient string > concatenations or matrix operations, and a%b%c%d might execute as > a.__mod__(b,c,d). But that needs special casing strings and ``%`` in the comiler, because it might not be always safe to do this on arbitrary objects. Only in cases where the type of `a` is known at compile time and ``a % b`` returns an object of ``type(a)``. Ciao, Marc 'BlackJack' Rintsch From steve at holdenweb.com Wed Dec 10 12:55:17 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 10 Dec 2008 12:55:17 -0500 Subject: get todays files In-Reply-To: References: Message-ID: Andrew D wrote: > I have a script that will login to my ftp server and download all the > backup files, but I want it to only download the files that were > created today, e.g. if I ran the script today I want it to only fetch > files created today. > > I am really not sure about how to do this, but it is quite important > to me, so all help is highly appreciated! > IIRC there's an "ftpmirror" script in the Tools directory (if you're on Windows - Linux/Unix users have to download the source). I adapted it to several different purposes. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From almar.klein at gmail.com Wed Dec 10 06:59:46 2008 From: almar.klein at gmail.com (Almar Klein) Date: Wed, 10 Dec 2008 12:59:46 +0100 Subject: Mathematica 7 compares to other languages In-Reply-To: <501d76b2-45d1-4475-8d88-e0e51e19fc10@q26g2000prq.googlegroups.com> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <9ecfa224-ce8f-44e9-abca-008314f44e87@40g2000prx.googlegroups.com> <501d76b2-45d1-4475-8d88-e0e51e19fc10@q26g2000prq.googlegroups.com> Message-ID: 2008/12/10 Xah Lee > Jon Harrop moron wrote: > > Only for trivial input and not for the challenge you were given. > > what challenge? > > > That code is evaluated once to build the scene. There is no point in > > optimizing it. > > The point is optimizing your incompetence. > > > That performance issue only affects trivial problems and, in particular, > > does not affect the problem you were trying to solve. > > solve your mom? > > What challange? Euhm, I think that was pretty clear. And you're constantly insulting people, not responding to their arguments. Not a particularly nice way to behave in a news group such as this. >Also, all you did is talking bullshit. >You, kept on babbling. I think YOU are the one who is talking crap here. You are too afraid to admid you failed the challange (probably because you think so high of yourself). You try to cover it with crap and insults. Cheers, Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Thu Dec 4 10:53:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Dec 2008 15:53:21 GMT Subject: Please fix your clock [was Re: Multiple equates] References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> Message-ID: <0147f4b7$0$20670$c3e8da3@news.astraweb.com> Hendrik, I think your PC's clock is wrong. You seem to be posting from the future. From fetchinson at googlemail.com Thu Dec 11 02:53:28 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 10 Dec 2008 23:53:28 -0800 Subject: why doesn't pop/clear call __delitem__ on a dict? Message-ID: I just found out that if I want to have a custom dict it's not enough to overload __getitem__, __setitem__ and __delitem__ because, for example, pop and clear don't call __delitem__. I.e. an instance of the following will not print 'deleted' upon instance.pop( 'key' ): class mydict( dict ): def __setitem__( self, key, value ): print 'set' super( mydict, self ).__setitem__( key, value ) def __getitem__( self, key ): print 'get' super( mydict, self ).__getitem__( key ) def __delitem__( self, key ): print 'deleted' super( mydict, self ).__delitem__( key ) Why is this? There might other gotchas too I suppose. My intention is clear from the above, what other methods do I have to overload so that I get what I expect for all dict operations? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From tjreedy at udel.edu Thu Dec 4 21:00:29 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Dec 2008 21:00:29 -0500 Subject: Python 3 read() function In-Reply-To: References: <16651e80812040900j257fe2acjf5d8817811d32da6@mail.gmail.com> Message-ID: Christian Heimes wrote: > Terry Reedy wrote: >> Timing of os interaction may depend on os. I verified above on WinXp >> with 4 meg Pythonxy.chm file. Eye blink versus 3 secs, duplicated. I >> think something is wrong that needs fixing in 3.0.1. >> >> http://bugs.python.org/issue4533 > > I've attached a patch to the bug. reading was so slow because the > fileio_readall() was increasing the buffer by 8kB in each iteration. The > new code doubles the buffer until it reaches 512kB. Starting with 512kB > it's increased in 512kB blocks. Python 2.x has the same growth rate. > > Christian Thank you. Too bad this was not caught a week ago, but the timing of each method of each class is a bit hard to test for. Perhaps in the future. tjr From google at mrabarnett.plus.com Sun Dec 21 11:58:53 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 21 Dec 2008 16:58:53 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: <494E75CD.20501@mrabarnett.plus.com> Aaron Brady wrote: > On Dec 21, 10:31 am, MRAB wrote: >> Aaron Brady wrote: >>> On Dec 20, 8:49 pm, MRAB wrote: >>>> Aaron Brady wrote: >>>>> On Dec 20, 7:38 pm, Steven D'Aprano >>>> cybersource.com.au> wrote: >>>>>> Instead of just whinging, how about making a suggestion to fix it? Go on, >>>>>> sit down for an hour or ten and try to work out how a BINARY OPERATOR >>>>>> like % (that means it can only take TWO arguments) can deal with an >>>>>> arbitrary number of arguments, *without* having any special cases. >>>>>> Go on. Take your time. I'll be waiting. >>>>> Hi, not to take sides, but, there is a possibility. >>>>> This behavior is currently legal: >>>>>>>> "%i %%i" % 0 % 1 >>>>> '0 1' >>>>> So, just extend it. (Unproduced.) >>>>>>>> "%i %i" % 0 % 1 >>>>> '0 1' >>>>>>>> "%r %i" % (2, 3, 4) % 1 >>>>> '(2, 3, 4) 1' >>>>>>>> "%r %i" % (2, 3, 4) >>>>> '(2, 3, 4) %i' >>>>> Which is quite clever and way ahead of its (posessive) time. >>>> A couple of problems: >>>> 1. How do you handle a literal '%'? If you just double up then you'll >>>> need to fix the string after all your substitutions. >>>> 2. What if a substitution introduces a '%'? >>>> I suppose a possible solution would be to introduce a special format >>>> string, including a literal, eg: >>>> f"%r %i" % (2, 3, 4) % 1 >>>> and then convert the result to a true string: >>>> print(str(f"%r %i" % (2, 3, 4) % 1)) >>>> (although print() would call __str__ anyway). >>>> The format string would track where the last substitution occurred. >>>> Hmm... I think I'll just learn the new method. :-) >>> Now that I'm fighting 'r's war for him/her... >>> Um, here's one possibility. On the first interpolation, flags are >>> noted and stored apart from subsequent interpolations. Then, use a >>> sentinel to terminate the interpolation. (Unproduced.) >>>>>> "%r %i" % ( 2, 3 ) % 0 >>> '(2, 3) 0' >>>>>> "%% %r" % ( 2, 3 ) % str.interp_end >>> '% (2, 3)' >>>>>> "%sss%i" % "%d" % 0 >>> '%dss0' >>> The first %s is replaced with %d, but doesn't hijack the '0'. If you >>> want to interpolate the %d, use the sentinel. The sentinel is what >>> causes '%%' to be handled. >>>>>> "%sss%i" % "%d" % 0 % 1 >>> Traceback (most recent call last): >>> File "", line 1, in >>> TypeError: not all arguments converted during string formatting >>>>>> "%sss%i" % "%d" % 0 % str.interp_end % 1 >>> '1ss0' >>> Treating tuples as a special case appears to be the simpler solution, >>> but this, 'chaining', to adopt the term, is still feasible. >> A possible solution occurred to me shortly after I posted, but I decided >> that sleep was more important. :-) >> >> The original format is a string. The result of '%' is a string if >> there's only 1 placeholder to fill, or a (partial) format object (class >> "Format"?) if there's more than one. Similarly, the format object >> supports '%'. The result of '%' is a string if there's only 1 >> placeholder to fill, or a new (partial) format object if there's more >> than one. >> >> >>> f = "%r %i" >> >>> type(f) >> >> >>> f = f % (2, 3, 4) >> >>> type(f) >> >> >>> f = f % 1 >> >>> type(f) >> > > Alright, so how are you handling: > >>>> f= "%s %i" >>>> type( f ) > >>>> f= f% '%i' #now '%i %i' >>>> type( f ) > >>>> f= f% 1 >>>> type( f ) > ? > > In other words, are you slipping '1' in to the very first available > slot, or the next, after the location of the prior? > Let's assume that Format objects display their value like the equivalent string format: >>> f = "%r %i" >>> f '%r %i' >>> f = f % (2, 3, 4) >>> f >>> f = f % 1 >>> f '(2, 3, 4) 1' >>> >>> f = "%s %i" >>> f '%s %i' >>> f = f % '%i' >>> f >>> f = f % 1 >>> f '%%i 1' From arnodel at googlemail.com Thu Dec 11 15:19:35 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 11 Dec 2008 20:19:35 +0000 Subject: dictionary idiom needed References: <383976cf-53fb-48e4-b028-8f568468ce77@r36g2000prf.googlegroups.com> <0c4950c1-4833-40c7-ac19-260b61d5289f@k24g2000pri.googlegroups.com> <7c55c59b-cebe-4f4e-ae40-282ae7e005bf@d42g2000prb.googlegroups.com> Message-ID: Brandon writes: > Thanks bear - > > Some outside advice has me looking at nested dictionaries. But I am > still bogged down because I've not created one before and all examples > I can find are simple ones where they are created manually, not with > loops. Maybe a further example: > > data: > POS1 POS2 POS3 > ['word1','tagA','tagB'] > ['word2','tagC','tagD'] > ['word1','tagE','tagB'] > ['word1','tagC','tagF'] > > ... and so on. FWIW: I am guaranteed that the set of tags that may > occur in position2 is complementary to the set of tags that may occur > in position3. > > Now I want to get an accounting of all the tags that occurred in > position3 in the context of, say, word1. Here I've shown that for > word1, tagB and tagF occurs. I want a way to access all this > information such that nested_dict['word1']['tagB'] = 2, and nested_dict > ['word1']['tagF'] = 1. > > As I mentioned, I already have dicts such that dictA['word1'] = 3, and > dictB['tagB'] = 2. I used defaultdict to build those, and that seems > to be causing me to get some funky values back from my initial > attempts to build a nested dictionary. I am stumbling at constructing > a "for" loop that automatically creates such nested dictionaries. > > I hope that clears things up. If you still have any advice, it's much > appreciated. > > Thanks, > > Brandon >>> from collections import defaultdict >>> >>> data = [['word1','tagA','tagB'], ... ['word2','tagC','tagD'], ... ['word1','tagE','tagB'], ... ['word1','tagC','tagF']] >>> >>> d = defaultdict(lambda: defaultdict(int)) >>> >>> for w, t1, t2 in data: ... d[w][t2] += 1 ... >>> d['word1']['tagB'] 2 >>> d['word2']['tagD'] 1 >>> d['word2']['tagF'] 0 HTH -- Arnaud From gagsl-py2 at yahoo.com.ar Fri Dec 12 21:38:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 13 Dec 2008 00:38:00 -0200 Subject: forcing future re-import from with an imported module References: <533670ae-6d9d-4b10-9156-e41b31b678c7@g17g2000prg.googlegroups.com> Message-ID: En Fri, 12 Dec 2008 19:44:32 -0200, _wolf escribi?: > On Dec 11, 12:43 am, rdmur... at bitdance.com wrote: >> "Why can't you have the code that is doing the import [...] >> call a function [...] to produce [the] side effect [...]? >> Explicit is better than implicit. A python programmer is >> going to expect that importing a module is idempotent" > > you?re completely right that `import foo` with side effects may break > some expectations, but so do all `from __future__` imports. you?re > also right that another solution would be to come in from the other > side and explicitly call a function from the importing module. all of > this does not answer one question tho: why does deleting a module work > most of the time, but not in the case outlined in my first post, > above? why do we get to see this slightly strange error message there > complaining about ?not finding? a module ?in sys.modules??well, most > of the time, when a module is not in that cache, it will be imported, > but not in this case. why? The import system can be customised in many ways (the various import hooks, special entries in sys.path, meta_path, path_hooks, __import__, etc.), even could be completely reimplemented. There are safety checks in the interpreter, to validate some minimal pre and postconditions that should always hold. By example, checking that sys.path contains a list of directories. Or the one you broke: after successfully executing "import foo", there must be an entry named "foo" in sys.modules. If not, it is asumed that something in the import machinery went wrong. -- Gabriel Genellina From akineko at gmail.com Tue Dec 30 01:44:41 2008 From: akineko at gmail.com (akineko) Date: Mon, 29 Dec 2008 22:44:41 -0800 (PST) Subject: Python in C References: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> Message-ID: <313583fc-4651-4deb-8a44-c3b1810b722c@z27g2000prd.googlegroups.com> Although this is not what you are asking but I'm wondering why you need to read CPython implementation. I have been using Python for 7 or 8 years but I've never encountered any situations where I need to read CPython implementation. I needed to read library implementations and installer codes, though. CPython worked great for me. I don't want to read a large piece of software, like CPython, unless it is really really necessary. I'm curious. Aki- On Dec 29, 5:22?pm, thmpsn.... at gmail.com wrote: > I've just downloaded Python's mainstream implementation (CPython), > which is written in C. Not to my surprise, I feel like I'm looking at > unstructured spaghetti, and I'm having trouble figuring out how it all > works together. (Please bear with me; I'm just going through the usual > frustration that anyone goes through when trying to see the > organization of a C program :) > > So, I have two queries: > > 1. Can anyone explain to me what kind of program structuring technique > (which paradigm, etc) CPython uses? How do modules interact together? > What conventions does it use? > > 2. Have there been any suggestions in the past to rewrite Python's > mainstream implementation in C++ (or why wasn't it done this way from > the beginning)? From andre.roberge at gmail.com Sun Dec 7 15:43:24 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sun, 7 Dec 2008 12:43:24 -0800 (PST) Subject: Python for kids? References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> Message-ID: <2dcad5b4-5085-4e0a-bab2-daaf8d5b75f3@33g2000yqm.googlegroups.com> On Dec 7, 4:13?pm, "Russ P." wrote: > I have a 12-year-old son who spends too much time playing Xbox live > and watching silly YouTube videos. I would like to try to get him > interested in programming. Is anyone aware of a good book or website > that addresses this concern, preferably (but not necessarily) using > Python? I could try to teach him Python myself, but I'm afraid I would > just frustrate him and kill his interest in programming. I did a > Google search and found a few things, but not a lot. Thanks. http://rur-ple.sourceforge.net Andr? From mail at microcorp.co.za Tue Dec 23 03:03:24 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 23 Dec 2008 10:03:24 +0200 Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com><1d03c66b-c725-42f4-af6e-2351a7841b30@z1g2000yqn.googlegroups.com> Message-ID: <01e401c964e9$d07a3fc0$0d00a8c0@hendrik> "r" wrote:: > The writing is on the Wall! Yes it is, and as always, it says : Mene, mene, tekel epharsim. If my protestant upbringing hasn't failed me, it means: Weighed, and found wanting. - Hendrik From wuwei23 at gmail.com Thu Dec 4 02:13:18 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 3 Dec 2008 23:13:18 -0800 (PST) Subject: "as" keyword woes References: Message-ID: On Dec 4, 3:42?pm, "Warren DeLano" wrote: > So you prefer broken code to broken rules, eh? ?Your customers must love > that! ?This is exactly the kind of ivory-tower thinking I feared might > be behind the decision (form over function, damn the users to hell, > etc.) Really? I find that believing something should remain static at the expense of actual improvement to the language is far more 'ivory-tower thinking' than embracing change. > Am I the only one picking up on the irony here? ?"as" exists largely to > provide a mechanism for working around namespace conflicts -- except, > apparently, conflicts involving "as". ?The fact that "as" itself creates > an insurmountable namespace collision is just killing me! ?How absurd. Speaking of irony, you're complaining about namespace conflicts with a -two character identifier- you've chosen. Here's a hint: choose better names. > But to be brutally honest...in this many-core world we must all accept > and deal with today, it is hard to imagine how a non-multithreaded AND > non-backwards compatible Python implementation can have much of a life > ahead of it, with or without an "as" keyword. ?I do sincerely hope I am > wrong about this, but it is seems quite possible that C/Python's glory > days are now behind us. ? To match your honesty, I'm somewhat tired with the trend of some people to hit -one- issue with Python and suddenly lash out like children over all the same old tired crap. Have you even looked at multiprocessing? Have you contributed to any projects working on GIL- less implementations? Or are you just regurgitating the same bullet points we've heard time and time again? For chrissake, if you cannot do ANYTHING but BITCH about a change, then you've no damn right to consider yourself a programmer. Real programmers find solutions, not excuses. > And if so, then thank you all for so many wonderful years of effort and > participation! You're welcome. Don't let the door hit you on the ass on your way out. From sturlamolden at yahoo.no Fri Dec 12 11:55:12 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 08:55:12 -0800 (PST) Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> Message-ID: On Dec 12, 5:13 pm, Steve Holden wrote: > OK, so now you are proposing to alter the parser, and possibly the > implementation of the INPLACE_ADD opcode in eval.c, so can you give us > the patch for those, please? That is not where the problem resides. From tjreedy at udel.edu Sun Dec 7 04:15:29 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 07 Dec 2008 04:15:29 -0500 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: References: <55d79070-0c11-4fb9-8cf5-b8cc7c54b5d2@v42g2000yqv.googlegroups.com> <0e37191f-3672-4313-bc5c-ffcd904e4796@k24g2000pri.googlegroups.com> Message-ID: John Machin wrote: > Here's the scoop: It's a bug in the newline handling (in io.py, class > IncrementalNewlineDecoder, method decode). It reads text files in 128- > byte chunks. Converting CR LF to \n requires special case handling > when '\r' is detected at the end of the decoded chunk n in case > there's an LF at the start of chunk n+1. Buggy solution: prepend b'\r' > to the chunk n+1 bytes and decode that -- suddenly with a 2-bytes-per- > char encoding like UTF-16 we are 1 byte out of whack. Better (IMVH[1] > O) solution: prepend '\r' to the result of decoding the chunk n+1 > bytes. Each of the OP's files have \r on a 64-character boundary. > Note: They would exhibit the same symptoms if encoded in utf-16LE > instead of utf-16BE. With the better solution applied, the first file > [the truncated one] gave the expected error, and the second file [the > apparently OK one] gave sensible looking output. > > [1] I thought it best to be Very Humble given what you see when you > do: > import io > print(io.__author__) > Hope my surge protector can cope with this :-) > ^%!//() > NO CARRIER Please post this on the tracker so it can get included with other io work for 3.0.1. From lie.1296 at gmail.com Tue Dec 23 09:17:44 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 23 Dec 2008 14:17:44 +0000 (UTC) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> <7c02eb33-a919-4481-8eda-76062729f233@k19g2000yqg.googlegroups.com> <32d8e3f1-52a7-4bce-a70a-70db488a417b@h20g2000yqn.googlegroups.com> Message-ID: On Mon, 22 Dec 2008 21:05:22 -0800, r wrote: > On Dec 22, 10:09?pm, Ben Kaplan wrote: >> That's just because most of us don't say anything unless we have >> something useful to say. We prefer to let the experts answer the >> questions, but we read the threads so we can benefit from them. > > OK Ben, So you are saying > > 1.) do not question the gods! Hmmm... when we talk about something we don't know, only trash would come out of our mouth. > 2.) speak only when spoken to! He (Ben) does not say anything remotely like that. > 3.) do not have an opinion! Again, you're adding sauce, meat, beef, and spices to his statement. > Somehow this reminds me of some old and brainwashing religions, Not an > OSS project. Just observations Ben. Isn't it you that have been accused of religionizing python by many people in this list? From conrad.ammon at gmail.com Mon Dec 15 15:27:12 2008 From: conrad.ammon at gmail.com (cmdrrickhunter@yaho.com) Date: Mon, 15 Dec 2008 12:27:12 -0800 (PST) Subject: Structure using whitespace vs logical whitespace References: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> Message-ID: <89b3cbe5-e61b-49eb-926a-e96a43a35fe5@s1g2000prg.googlegroups.com> On Dec 15, 11:10?am, Terry Reedy wrote: > > In general, I'm using indentation to show logical flow through code. > > That, of course, is what Python does. > Python does NOT use indentation to show logical flow. It uses it to show syntactical flow. The XML writer is the perfect example of a case where they are different. In most cases, syntactic flow is close enough to logical flow. There are a few cases where you can 'draw a picture' of the algorithm in code if you are whitespace insensitive. I've not used the "with" keyword before, and it does seem to handle this troublesome case quite well. I learned python before it was around, and never really studied it hard enough. I'll have to investigate what other tricks can be done with it. I'm a big fan of the rule "make the 90% easy and the remaining 10% possible." Whitespace sensitivity makes the 90% easy, and just from the looks of it, the 'with' command and whitespace insensitive expressions give the remaining 10%. And I do like the automated support for "finally" clauses when using 'with' Thanks for the help, everyone! From ldo at geek-central.gen.new_zealand Wed Dec 3 06:23:24 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 04 Dec 2008 00:23:24 +1300 Subject: Multiple equates References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> <9m3h06-vhh.ln1@lairds.us> Message-ID: In message , Cameron Laird wrote: > def shell_escape(Arg) : > """returns Arg suitably escaped for use as a command-line argument > to Bash.""" > > pattern = r"[\<\>\"\'\|\&\$\#\;\(\)\[\]\{\}\`\!\~\ \\]" > def f1(Match): > return "\\" + Match.group(0) > return re.sub(pattern, f1, Arg) > # Need to catch anything that might be meaningful to shell > #end shell_escape So why is that better? From gagsl-py2 at yahoo.com.ar Mon Dec 29 22:24:58 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Dec 2008 01:24:58 -0200 Subject: Python module import loop issue References: <02bc8567-695a-4277-9698-a95549a0bc98@w39g2000prb.googlegroups.com> <4a0557b7-e901-49ff-b4db-53f4d8a7c0f8@r40g2000yqj.googlegroups.com> Message-ID: En Mon, 29 Dec 2008 19:47:51 -0200, Carl Banks escribi?: > On Dec 29, 10:51?am, Kottiyath wrote: >> Module Factory: >> A1Factory: {'B1Tag':1.1.B1, 'C1Tag':1.2.C1, 'D1Tag':1.3.D1'} >> A2Factory: {'B2Tag':2.1.B2, 'C2Tag':2.2.C2, 'D2Tag':2.3.D2'} >> >> But, since Module requires objects of B1, C1 etc, it has to import >> Factory. >> Now, there is a import loop. How can we avoid this loop? > > I'm going to suggest three ways: a straightforward, good-enough way; a > powerful, intelligent, badass way; and a sneaky way. In Python 2.6 (and 3.0) there is a fourth way: class decorators. > 1. The straightforward, good-enough way > > Define functions in Factory.py called register_A1_subclass and > register_A2_subclass, then call them whenever you create a new > subclass. Class decorators are a clean variant of this approach (in my opinion). > package1/module1.py: > ----------------------------- > import Factory > > class B1(A1): > # define class B1 here > > Factory.register_A1_subclass("B1Tag",B1) > ----------------------------- That would become: @Factory.register_A1_subclass("B1Tag") class B1(A1): ... (for an adequate variant of register_A1_subclass). The advantage is that the "register" stuff appears prominently near the name of the class, and there is no need to repeat the name. Also, "B1Tag" can be left out, if it is stored as a class attribute of B1 (in some cases using __name__ is enough) > 2. The powerful, intelligent, badass way > > Metaclasses. I would guess you do not want to do this, and I wouldn't > recommend it if you haven't studied up on how metaclasses work, but > it's a textbook example of their usefulness. If you expect to use > factory functions like this a lot, it might be worth your while to > learn them. A problem with metaclasses is when you have intermediate subclasses that are not meant to be registered, but the metaclass applies equally to all of them. -- Gabriel Genellina From steven at REMOVE.THIS.cybersource.com.au Mon Dec 8 21:43:06 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 09 Dec 2008 02:43:06 GMT Subject: A question about reference in Python. References: <493CB003.3080209@gmail.com> Message-ID: On Mon, 08 Dec 2008 08:18:27 -0700, Joe Strout wrote: > On Dec 7, 2008, at 10:26 PM, Group wrote: > >> Now, I want to write a Red-Black Tree, and a List structure. In C/C+ +, >> I can >> use pointers to refer to children notes (or next notes). But, in >> Python, how >> can I do it? Except the sequence, I know not any way. > > Any variable in Python is a reference Except that they don't behave like references in languages that have explicit reference parameters. Joe, please stop muddying the water. We've been over this to death. Did you not see the thread asking how to create reference parameters in Python? Subject "var or inout parm?". I noticed you were conspicuous by your absence in that little discussion. -- Steven From google at mrabarnett.plus.com Thu Dec 4 13:06:38 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 04 Dec 2008 18:06:38 +0000 Subject: schizophrenic view of what is white space In-Reply-To: <4938112F.5030706@chamonix.reportlab.co.uk> References: <4937E8E5.2090306@chamonix.reportlab.co.uk> <20081204143337.20272.1236189783.divmod.quotient.15592@ohm> <4938112F.5030706@chamonix.reportlab.co.uk> Message-ID: <49381C2E.3060707@mrabarnett.plus.com> Robin Becker wrote: > Jean-Paul Calderone wrote: > ......... >> >> You have to give the re module an additional hint that you care about >> unicode: >> >> exarkun at charm:~$ python >> Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu >> 4.2.3-2ubuntu7)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import re >> >>> print re.compile(r'\s').search(u'a\xa0b') >> None >> >>> print re.compile(r'\s', re.U).search(u'a\xa0b') >> <_sre.SRE_Match object at 0xb7dbb3a0> >> >>> >> >> Jean-Paul > ....... > > so the default behaviour differs for unicode and re working on unicode. > I suppose that won't be true in Python 3. > I'm not sure why the Unicode flag is needed in the API. I reckon that it should just look at the text that the regular expression is being applied to: if it's Unicode then follow the Unicode rules, if not then don't. From arnodel at googlemail.com Sun Dec 7 12:49:47 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 07 Dec 2008 17:49:47 +0000 Subject: Brain going crazy with recursive functions References: <6470511f-093e-42c2-a6c2-4bb90b336ac9@r15g2000prd.googlegroups.com> Message-ID: 5lvqbwl02 at sneakemail.com writes: > I'm trying to solve the 9-tile puzzle using as functional an approach > as possible. I've recently finished reading SICP and am deliberately > avoiding easy python-isms for the more convoluted scheme/functional > methods. The following function is trivial to do with for loops and > directly accessing arrays with [] syntax. I'm trying to limit myself > to the types of idioms/semantics one finds in minimal scheme, such as > in SICP. I want eventually to port this to scheme, but I know python > better, so that's where I'm starting. > > My current problem is the following. The 9-tile puzzle consists of a > list of lists like this [[1,2,3],[4,5,6],[7,8,0]], where the numbers > can be jumbled up. I'm looking for the location of the zero using > *only* recursion and operators that are similar to car/cdr. The > return value should be the row,col of the zero. For example above > the > return value would be (2,2). I'm not sure what your code does but there is a canonical way to transform a loop the call of a recursive function. I don't think I can put it into words easily so I've demonstrated it below on your 'locate_zero' function. def find_zero(square): "The normal imperative way in simple Python." i = 0 for row in square: j = 0 for n in row: if n == 0: return i, j j += 1 i += 1 def func_find_zero(square): """ The translation into recursive calls. A function is created for each loop. There are no mutations. """ def square_loop(square, i): def row_loop(row, j): if row: if row[0] == 0: return i, j else: return row_loop(row[1:], j+1) if square: res = row_loop(square[0], 0) if res is not None: return res else: return square_loop(square[1:], i+1) return square_loop(square, 0) I've intentionally made both function 'non-clever' to make the translation process more apparent. -- Arnaud From nad at acm.org Tue Dec 9 15:13:35 2008 From: nad at acm.org (Ned Deily) Date: Tue, 09 Dec 2008 12:13:35 -0800 Subject: pickling a circular object inherited from list References: <3b1bab42-657c-4b93-9236-aa5236c16826@w1g2000prk.googlegroups.com> Message-ID: In article , Klaus Kopec wrote: > >> What did I do wrong? > > Old Python version? :) > > Seems to work in 3.0 (don't have 2.6 currently to check but IMO it's > > fixed there as well). > It works for me with v3.0 as well, but not with v2.6.1 (same error as > stated before for v2.4). > > Is there any way to fix this in v2.6.1 or even v2.4? Right now I cannot > switch to v3.0 because I depend on several not compatible packages > (numpy, biopython, ...) It looks like your example can be made to work by either specifying pickle protocol 2 or by switching to cPickle. -- Ned Deily, nad at acm.org From google at mrabarnett.plus.com Sat Dec 20 20:28:15 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 21 Dec 2008 01:28:15 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <52b8e001-2cc7-4891-8540-a3cdb6b78533@e25g2000vbe.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> <59153e28-bf86-4158-96d9-23aa5b9f0205@j35g2000yqh.googlegroups.com> <52b8e001-2cc7-4891-8540-a3cdb6b78533@e25g2000vbe.googlegroups.com> Message-ID: <494D9BAF.6020005@mrabarnett.plus.com> r wrote: > Thanks MRAB, > except the float is not 2 decimal places, but its there > Oops! >>> '{0} {1:05} {2:.2f}'.format(s, n, f) 'python 00012 1.33' >>> '{0:s} {1:05d} {2:.2f}'.format(s, n, f) 'python 00012 1.33' From prologic at shortcircuit.net.au Mon Dec 15 22:00:23 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 16 Dec 2008 13:00:23 +1000 Subject: Copying files in directory In-Reply-To: <2a815b7d-f01f-4666-bfc6-e9c43a75019b@t3g2000yqa.googlegroups.com> References: <2a815b7d-f01f-4666-bfc6-e9c43a75019b@t3g2000yqa.googlegroups.com> Message-ID: On Tue, Dec 16, 2008 at 12:49 PM, wrote: > I'm writing a project management system, and I need the ability to > accept a directory name and move its contents to another directory. > Can someone give me a code sample that will handle this? I can't find > any "copying" functions in os or os.path. Try the shutil module. --JamesMills From clp at rebertia.com Thu Dec 4 14:48:28 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 4 Dec 2008 11:48:28 -0800 Subject: Why shouldn't you put config options in py files In-Reply-To: References: Message-ID: <47c890dc0812041148k7e636541w37915defe1b45b4b@mail.gmail.com> On Thu, Dec 4, 2008 at 11:35 AM, HT wrote: > A colleague of mine is arguing that since it is easy to write config like: > > FOO = {'bar': ('a': 'b'), 'abc': ('z': 'x')} I'll assume you meant ('a', 'b') as colons in parens don't make sense. > > in config.py and just import it to get FOO, but difficult to achieve the > same using an ini file and ConfigParser, and since Python files are just > text, we should just write the config options in the Python file and > import it. > > I can think of lots of arguments why this is a bad idea, but I don't > seem to be able to think of a really convincing one. > > Anyone? Well, it is pretty weird to be allowed to put arbitrary code in a mere config file. Have you considered using JSON for the config file format instead? It shares Python's syntax for literals, so you could do: $ cat config.json { "FOO": { "bar": ["a", "b"], "abc": ["z", "x"] } } Note that the whitespace doesn't matter. Also, you can use Python's built-on `json` module to parse the file. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > From victorsubervi at gmail.com Fri Dec 26 12:11:44 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 26 Dec 2008 18:11:44 +0100 Subject: =?ISO-8859-1?Q?Re:_Can=B4t_Surf_Python_Pages_in_Windoze?= In-Reply-To: <4954FB9F.5050702@wildenhain.de> References: <4dc0cfea0812260701q6baf0ccbj154c5b3fa2281cdb@mail.gmail.com> <4954FB9F.5050702@wildenhain.de> Message-ID: <4dc0cfea0812260911k4dbc0f2ame9cc874e067b7816@mail.gmail.com> On 12/26/08, Tino Wildenhain wrote: > > > print "Content-Type: text/html" >> print >> print """ >> > http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> >> >> >> >> >> Yeah >> >> """ >> > > this could be fine if called in CGI context. Can you state clearly what "CGI context" means? Should I be importing a CGI module? I pulled this code from a page that was working. If it had an importation of something CGI, I believe I would have tested that with all the other things that were imported that I tested, but perhaps not. I am not at my home computer to test, and will not be back online for a week. I am not worried about Zope now, but the above code, yes. TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From sopherfish at gmail.com Sun Dec 28 12:01:14 2008 From: sopherfish at gmail.com (sopherfish at gmail.com) Date: Sun, 28 Dec 2008 09:01:14 -0800 (PST) Subject: Cheetah Message-ID: 1. In Cheetah 2.0.1, both from python 2.5.2 and 2.6, after I do a #from datetime import date, most of the datetime objects seem to work fine. For example, $date(2008, 12, 15) works. However $date.today() does not work and I get an exception required argument year not found. In Python both 2.5.2 and 2.6 (without Cheetah), the today() works fine. For some reason, though, it does not work from Cheetah. 2. In reportlab 2.2, when I generate a PDF, no matter how many  s I put it, I only get one space. I am using it with python 2.6. The PDF generates fine and one $nbsp works, but for some reason, when I put it in multiple times, I still only get one space. From stefan_ml at behnel.de Tue Dec 30 08:20:50 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 30 Dec 2008 14:20:50 +0100 Subject: Any equivalent to Ruby's 'hpricot' html/xpath/css selector package? In-Reply-To: References: Message-ID: <495a2031$0$31867$9b4e6d93@newsspool3.arcor-online.net> Mark Thomas wrote: > The main difference is that lxml doesn't have CSS selector syntax Feel free to read the docs: http://codespeak.net/lxml/cssselect.html Stefan From Graham.Dumpleton at gmail.com Wed Dec 17 04:25:58 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Wed, 17 Dec 2008 01:25:58 -0800 (PST) Subject: mod_python resources References: <78064e7e-ba2c-4959-b5f8-4d1b928bc5fe@y18g2000yqn.googlegroups.com> <4lsl16-15a.ln1@archaeopteryx.softver.org.mk> Message-ID: On Dec 17, 11:10?am, ?????? ??????????? wrote: > > I'm trying again because I'm stubborn. Maybe the fourth time will be > > the charm... > > > Are there any good tutorials out there for setting up Apache with > > mod_python? > > mod_python is depreceated, nobody uses it. usemod_wsgihttp://www.modwsgi.org/ The mod_python package is not deprecated, although it could be said to be sleeping at the moment. You'll also probably still find that more new people choose mod_python over mod_wsgi. This is because it has the more obvious name to look for when Googling. It also has publisher and PSP high level handler which are still attractive to many as they are more lightweight and easier to get into than the large WSGI frameworks. Finally, the Django folks still recommend in their documentation to use mod_python. Anyway, if wanting to host a WSGI capable application, using mod_wsgi would be the more obvious choice. If wanting to write your own framework, or work at low level, basing it on WSGI rather than mod_python specific APIs would certainly be a better long term direction to take. Graham From gandalf at shopzeus.com Mon Dec 8 16:18:46 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 08 Dec 2008 22:18:46 +0100 Subject: ORB for Python and PHP Message-ID: <493D8F36.4040504@shopzeus.com> We have a problem here. We have a website written in PHP. and many programs written in Python. The communication between the components is messy. os.system calls are mixed with popen, xml-rpc and others. We would like to make it consistent and portable. We would like to use free software. What are our options? I checked these: - Bonobo is the most advanced, but it can only handle C language - FNORB is good for Python, but not for PHP - OmniORB would be very good for C and Python, but not PHP There are others but they do not support both Python and PHP. Should I implement my own ORB, or do you know a suitable solution? Thank you, Laszlo From n.kottiyath at gmail.com Tue Dec 16 15:18:17 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Tue, 16 Dec 2008 12:18:17 -0800 (PST) Subject: Can anyone suggest a good HTTP/1.1 web client? Message-ID: Hi all, I have to connect to a secure website every second to get the data and then post to it. I have been investigating on many web clients in python, but nothing fits the bill properly. The ones I tried implementing are: 1. httplib based - I created myself. (I cannot use urllib2 since I have to transfer files, and urllib2 doesnt have multipart content-type support) 2. Twisted web client. I also looked at mechanize etc too. The problems I face are - 1. I liked twisted a lot, but when I implemented it, I found that client support is there only for twisted.web and not twisted.web2. Since I connect to the same website every time, I would like to have persistent connections and since twisted.web is HTTP/1.0, persistent connection support is not yet there. Without persistent connections, I would have to have TCP connection handshake everytime and it is taking too much time. 2. Since I connect to the website every second, I have to have many connections running at the same time. I am worried that creating threads for each connection is going to be a big problem (esp if the server response is slow), since the processor will get swamped - especially since there are many other activities going on in the machine. 3. I would also like to pipe line the requests - esp if the response is slow. Other requirements: 1. HTTPS Support 2. Connection through proxy. Is there any good web client which I can use straight up? Or would I have to implement the whole thing myself? It looks like a big beast and I was wondering whether python provides it straight up. Regards K From febaen at gmail.com Tue Dec 16 12:49:12 2008 From: febaen at gmail.com (feba) Date: Tue, 16 Dec 2008 09:49:12 -0800 (PST) Subject: Free place to host python files? References: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> <32599660-2393-4e18-8c48-05d64bccbbc1@t26g2000prh.googlegroups.com> Message-ID: Stuff like code.google, sf.net, are more oriented towards serious development, not just holding random apps, aren't they? Anyway, I found MediaFire, which looks like it will suffice for now. From jon at ffconsultancy.com Tue Dec 9 21:05:47 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Wed, 10 Dec 2008 02:05:47 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <9ecfa224-ce8f-44e9-abca-008314f44e87@40g2000prx.googlegroups.com> Message-ID: Xah Lee wrote: > On Dec 8, 5:25 pm, Terry Reedy wrote: >> Lest anyone doubt that problem size is important for comparing program >> run times, consider ... > > just in case there's any doubt: > > Simply change these lines in Jon's program: > > Main[9, 512, 4] to Main[9, 512, 4.] > > and it will run faster. Only for trivial input and not for the challenge you were given. > Also, change this line: > > Block[{scene = Create[level, {0, -1, 4}, 1]}, > > to > > Block[{scene = Create[level, {0., -1., 4.}, 1.]}, Same again. > will make it faster further. (both of which are in my version. The > ?Block? can be replaced with ?With?.) That code is evaluated once to build the scene. There is no point in optimizing it. > As i said, this error in a Mathematica code in the context of speed is > a major blunder. His denial makes him a stubborn moron. That performance issue only affects trivial problems and, in particular, does not affect the problem you were trying to solve. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From lists at cheimes.de Thu Dec 11 18:57:10 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 12 Dec 2008 00:57:10 +0100 Subject: Best way of debigging a C extension In-Reply-To: <6b20568d-8ce9-4240-8f83-b579c241d9a9@l33g2000pri.googlegroups.com> References: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> <6b20568d-8ce9-4240-8f83-b579c241d9a9@l33g2000pri.googlegroups.com> Message-ID: Paul Moore schrieb: > The trouble is, I only have mingw to build extensions, not MSVC7.1 - > so I can't build Python (and I don't know if I still have the toolkit > compiler to build with that - I certainly don't have all the pieces > installed). With Python 2.6, I guess things will be better as I have > VS2008 Express, so I can use this to build a debug Python plus my > extension. It's more work than I really want to do to go that way, but > I guess it'll work. Pyhon 2.5 doesn't support VS 2008. It has unofficial support for VS 2005 in the PCbuild8 directory. You can mail Martin von L?wis and ask him for a debug build of Python 2.5.2. I don't have the tools on my build box. > That's what I thought. I was just hoping that using a debug build of > an extension would be usable with a standard release build of Python, > as that's what will be easy for most people to set up. A debug build changes large parts of the ABI. Every PyObject struct gains additional fields, lots of checks are added to Python's memory allocation system and asserts are enabled. Debug extensions have a _d suffix for a very good reason. We aren't just trying to make *your* life harder. :) Christian From kyrie at uh.cu Wed Dec 10 17:21:51 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Wed, 10 Dec 2008 17:21:51 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: <49401C2D.4050209@egenix.com> References: <200812101401.35786.kyrie@uh.cu> <49401C2D.4050209@egenix.com> Message-ID: <200812101721.51692.kyrie@uh.cu> On Wednesday 10 December 2008 02:44:45 pm you wrote: > > Even in statically typed languages, when you override the equality > > operator/function you can choose not to return a valid answer (raise an > > exception). And it would break all the cases mentioned above (element in > > list, etc). But that isn't the right thing to do. The language > > doesn't/can't prohibit you from breaking the equality test, but that > > shouldn't be considered a feature. (a==b).all() makes no sense. > > Perhaps not in your application, but it does make sense in other > numeric applications, e.g. ones that work on vectors or matrixes. > > I'd suggest you simply wrap the comparison in a function and then > have that apply the necessary conversion to a boolean. I do numeric work... I'm finishing my MSc in applied math and I'm programing mostly with python. And I'd rather have a.compare_with(b), or a.elementwise_compare(b), or whatever name, rather than (a==b).all(). In fact, I'd very much like to have an a.compare_with(b, epsilon=e).all() (to account for rounding errors), and with python2.5, all(a.compare_with(b)). Yes, I could create an element_compare(a,b) function. But I still can't use a==b and have a meaningful result. Ok, I can (and do) ignore that, it's just one library, I'll keep track of the types before asking for equality (already an ugly thing to do in python), but the a==b behaviour breaks the lists (a in ll, ll.indexof(a)) even for elements not in numpy. ?Should I also ignore lists? The concept of equality between two arrays is very well defined, as it is also very well defined the element-by-element comparison. There is a need to test for both - then the way to test for equality should be the equality test. > > I'm certain that something could be worked out. A quick paragraph that > > took me just a few minutes to type shouldn't be construed as a PEP that > > will solve all the problems :D. > > As always: the Devil is in the details :-) Of course... -- Luis Zarrabeitia (aka Kyrie) Fac. de Matem?tica y Computaci?n, UH. http://profesores.matcom.uh.cu/~kyrie From Slaunger at gmail.com Thu Dec 4 16:18:44 2008 From: Slaunger at gmail.com (Slaunger) Date: Thu, 4 Dec 2008 13:18:44 -0800 (PST) Subject: Pythonic design patterns References: Message-ID: Thank you all for sharing your views, links and suggestions on my question. I see where this is getting, and I have extracted the following points: 1. Many classic design patterns, especially the creational ones (Factory, etc.) aren't really that useful in Python as the built-in features in the language and the new style objects has ways of doing these things far more natural than statically types languages. 2. Don't be religious about the design pattern and applying them too frantically. They may look cool, but there is a great danger for over- engineering and subsequent lower code readability, debuggability, and maintainability. 3. Seek inspiration from well-written sample code. 4. It is good to know them, but be bold sometimes and do something simpler. I think I will buy the Cookbook, not for its design patterns, but more for seing good examples of pythonic code and commonly used Python programming idioms. I already have the "Python in a Nutshell", which I like very much as a no-nonsense presentation of the language and its batteries, and that book would probably be a valuable addition to my limited collected (there are a few condensed pages concerning new- style objects, which I read over and over again). Later, if I still have the appetite for it and feel the need I might dive into some of the other resources mentioned. As a matter of fact I have visited all the links now and gotten some valuable inspirations. -- ~~~~ From gagsl-py2 at yahoo.com.ar Thu Dec 25 01:46:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Dec 2008 04:46:31 -0200 Subject: Easy-to-use Python GUI References: Message-ID: En Wed, 24 Dec 2008 21:47:07 -0200, Joel Koltner escribi?: > Is there an easy-to-use, "function"-based cross-platform GUI toolkit for > Python out there that's a little more sophisticated than EasyGui? Try Dabo http://dabodev.com/ -- Gabriel Genellina From xahlee at gmail.com Thu Dec 11 14:12:25 2008 From: xahlee at gmail.com (Xah Lee) Date: Thu, 11 Dec 2008 11:12:25 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <91bf5d87-0154-472b-9350-e3290ab867e1@k1g2000prb.googlegroups.com> Message-ID: <49a1717b-36f0-402c-a633-a7df23dca0bf@35g2000pry.googlegroups.com> On Dec 11, 6:50 am, the.brown.dragon.b... at gmail.com wrote: ;; Chicken Scheme. By the.brown.dragon... at gmail.com (require 'srfi-1) (define (normalize vec) (map (cute / <> (sqrt (reduce + 0 (map (cute expt <> 2) vec)))) vec)) Is it possible to make it work in scsh? (i'm running scsh 0.6.4, and don't know Scheme lisp well) Xah ? http://xahlee.org/ ? From clp at rebertia.com Fri Dec 12 07:44:31 2008 From: clp at rebertia.com (Chris Rebert) Date: Fri, 12 Dec 2008 04:44:31 -0800 Subject: var or inout parm? In-Reply-To: References: Message-ID: <47c890dc0812120444uc3e8b3djd0fb181935ee51e@mail.gmail.com> On Fri, Dec 12, 2008 at 4:34 AM, sturlamolden wrote: > You cannot modify parameters by rebinding. x = x + 1 is a rebinding. x > += 1 is not. Python begs to differ, as those two statements are both semantically identical in this case: Python 2.6 (r26:66714, Nov 18 2008, 21:48:52) [GCC 4.0.1 (Apple Inc. build 5484)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> x = 2 >>> id (x) 8405372 >>> x += 1 >>> id(x) 8405360 >>> x = x + 1 >>> id(x) 8405348 If you were talking about lists rather than integers though, you'd be absolutely correct, as the += ends up being a method call to __iadd__ instead of a plain assignment. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From piyush.subscription at gmail.com Sun Dec 21 02:12:19 2008 From: piyush.subscription at gmail.com (Piyush Anonymous) Date: Sun, 21 Dec 2008 12:42:19 +0530 Subject: trapping all method calls in a class... Message-ID: <19ac19520812202312q71409182kb58a0f7aaf3b0e74@mail.gmail.com> hi, i need to trap all method calls in a class in order to update a counter which is increased whenever a method is called and decreased whenever method returns. in order to that i am trying to write a decorator for all the methods. see the code here with error. ------- http://codepad.org/2w7JVvDB ---- any suggestions? any other better way of doing it? -------------- next part -------------- An HTML attachment was scrubbed... URL: From oyvinrog at gmail.com Fri Dec 19 18:02:08 2008 From: oyvinrog at gmail.com (=?ISO-8859-1?B?2Hl2aW5k?=) Date: Fri, 19 Dec 2008 15:02:08 -0800 (PST) Subject: Jarow-Winkler algorithm: Measuring similarity between strings Message-ID: <4f351b3b-4da7-4fee-a1ac-c42179d430f5@s9g2000prm.googlegroups.com> Based on examples and formulas from http://en.wikipedia.org/wiki/Jaro-Winkler. Useful for measuring similarity between two strings. For example if you want to detect that the user did a typo. def jarow(s1,s2): """ Returns a number between 1 and 0, where 1 is the most similar example: print jarow("martha","marhta") """ m= jarow_m(s1,s2) t1 = jarow_t(s1,s2) t2 = jarow_t(s2,s1) t = float(t1)/float(t2) d = 0.1 # this is the jaro-distance d_j = 1.0/3.0 * ((m/len(s1)) + (m/len(s2)) + ((m - t)/float(m))) # if the strings are prefixed similar, they are weighted more heavily l = winkler_l(s1,s2) print l return d_j + (l * 0.1 * (1 - d_j)) def winkler_l(s1,s2): """ Number of the four first characters matching """ l = 0 counter = 0 for s_j,s_i in zip(s1,s2): if s_j == s_i: l += 1 counter += 1 if counter > 4: break return l def jarow_m(s1,s2): """ Number of matching characters """ m = 0 d = {} for s in s1: d[s] = True for s in s2: if d.has_key(s): m += 1 return m def jarow_t(s1,s2): """ Number of transpositions """ t= 0 pos ={} counter = 0 for s in s1: pos[s] = counter counter += 1 counter = 0 for s in s2: if pos.has_key(s): if pos[s] != counter: t += 1 counter += 1 return t From google at mrabarnett.plus.com Wed Dec 17 10:21:02 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 17 Dec 2008 15:21:02 +0000 Subject: Transferring a file over sockets In-Reply-To: <002801c96050$251d57e0$0d00a8c0@hendrik> References: <002801c96050$251d57e0$0d00a8c0@hendrik> Message-ID: <494918DE.4010306@mrabarnett.plus.com> Hendrik van Rooyen wrote: > Ferdinand Sousa wrote: > >> ========================================================== > .# file receiver >> # work in progress >> >> import socket >> >> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >> HOST = '192.168.1.17' >> PORT = 31400 >> >> s.bind((HOST, PORT)) >> s.listen(3) >> conn, addr = s.accept() >> print 'conn at address',addr >> conn.send('READY') >> f = open('C:\\Documents and Settings\\USER\\Desktop\\test.pdf','wb') >> fsize=int(conn.recv(8)) >> print 'File size',fsize >> f.write(conn.recv(fsize)) > > This recv is not guaranteed to actually receive the number of > characters you are asking for - it will stop when it has received that > many, yes, but it may return with less, or even none if there is a > time out set. > > The TCP is a more or less featureless stream of characters. > > Consider including a start marker so you know where the lesson starts. > If you do this, consider the possibility of having a "false sync". > Sending/receiving the length is good - also google for "netstring" > Google for "escaping". > > Consider writing a loop to receive until the required length has been > received - look at the docs for the recv function - it can tell you how > much has been received. > >> f.close() >> conn.close() >> s.close() >> >> raw_input('Press any key to exit') >> >> >> =========================================================== >> >> # file sender !!! >> # Work in progress >> >> import socket, os >>from stat import ST_SIZE >> >> HOST = '192.168.1.17' >> PORT = 31400 # Arbitrary non-privileged port >> >> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >> >> s.connect((HOST,PORT)) >> if s.recv(5)!='READY': >> raw_input('Unable to connect \n\n Press any key to exit ...') >> s.close() >> exit() >> >> f=open('C:\\Documents and Settings\\USER\\Desktop\\t.pdf', 'rb') >> fsize=os.stat(f.name)[ST_SIZE] >> >> s.send(str(fsize)) >> s.send(f.read()) > > Are you sure that the send will send all the chars > that you ask it to send? > > If yes - why do you think this? > > What are the values that the send can return? > >> s.close() >> f.close() >> >> =========================================================== > You're also sending the length as a bytestring str(fsize), which will have an unknown length, but you're receiving the length as exactly 8 bytes. Either mark the end of the length in some way (with '\n'?) and look for that when receiving, or pad what you send to exactly 8 bytes (str(fsize).zfill(8)). From zac256 at gmail.com Tue Dec 2 19:47:27 2008 From: zac256 at gmail.com (Zac Burns) Date: Tue, 2 Dec 2008 16:47:27 -0800 Subject: Reverse zip() ? In-Reply-To: References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> Message-ID: <333edbe80812021647i4621271p7f87dff8d0926951@mail.gmail.com> There is a problem with this however, which prompted me to actually write an unzip function. One might expect to be able to do something like so (pseudocode)... def filesAndAttributes(): files = walk() attributes = [attr(f) for f in files] return zip(files, attributes) files, attributes = zip(*filesAndAttributes()) The corner case is when dealing with empty lists and there aren't enough items to unpack. The unzip function therefore has an elementsForEmpty keyword that handles this case. Perhaps something like this could be added to zip? I have not (yet) dealt with the PEP process, so I'm not sure where that starts. Perhaps a discussion could start here. -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer (Digital Overlord) Zindagi Games On Tue, Dec 2, 2008 at 4:14 PM, John Machin wrote: > On Dec 3, 7:12 am, Stefan Behnel wrote: >> Andreas Waldenburger wrote: >> > we all know about the zip builtin that combines several iterables into >> > a list of tuples. >> >> > I often find myself doing the reverse, splitting a list of tuples into >> > several lists, each corresponding to a certain element of each tuple >> > (e.g. matplotlib/pyplot needs those, rather than lists of points). >> >> > This is of course trivial to do via iteration or listcomps, BUT, I was >> > wondering if there is a function I don't know about that does this >> > nicely? >> >> I think you're asking about zip(): >> >> >>> l=[1,2,3] >> >>> zip(l,l) >> [(1, 1), (2, 2), (3, 3)] >> >>> zip(*zip(l,l)) >> [(1, 2, 3), (1, 2, 3)] >> > > Here's a version that makes it slightly easier to comprehend: > > Q: I know how to zip sequences together: > | >>> a = (1, 2, 3) > | >>> b = (4, 5, 6) > | >>> z = zip(a, b) > | >>> z > | [(1, 4), (2, 5), (3, 6)] > but how do I reverse the process? > > A: Use zip()! > | >>> a2, b2 = zip(*z) > | >>> a2 > | (1, 2, 3) > | >>> b2 > | (4, 5, 6) > > Cheers, > John > -- > http://mail.python.org/mailman/listinfo/python-list > From mail at johnohagan.com Sun Dec 21 21:02:31 2008 From: mail at johnohagan.com (John O'Hagan) Date: Mon, 22 Dec 2008 02:02:31 +0000 Subject: Namespaces, multiple assignments, and exec() In-Reply-To: <200812201541.19968.mail@johnohagan.com> References: <200812200234.33852.research@johnohagan.com> <200812201541.19968.mail@johnohagan.com> Message-ID: <200812220202.31393.mail@johnohagan.com> On Sat, 20 Dec 2008, John O'Hagan wrote: > On Sat, 20 Dec 2008, Terry Reedy wrote: > > John O'Hagan wrote: > > > I have a lot of repetitive assignments to make, within a generator, > > > that use a function outside the generator: > > > > > > var1 = func("var1", args) > > > var2 = func("var2", args) > > > var3 = func("var3", args) > > > etc... > > > > > > In each case the args are identical, but the first argument is a string > > > of the name being assigned. It works fine but I'd like to reduce the > > > clutter by doing the assignments in a loop. I've tried using exec(): > > > > > > for name in name_string_list: > > > exec(name + ' = func(\"' + name + '\", args)') > > > > > > but in the local namespace it doesn't understand func(), and if I give > > > it globals() it doesn't understand the args, which come from within the > > > generator. > > > > > > What's a good way to do this kind of thing? > > > > Put everything in your own namespace > > > > myvars={} > > for name in namelist: > > myvars[name]=func(name,args) > > Likely I'm missing something, but don't I still have to do > > var1 = myvars['var1'] > var2 = myvars['var2'] > var3 = myvars['var3'] > ...etc. > > to make the assignments? And of course I am missing the fact that I can now do the exec loop over myvars{} in the local namespace. Doing this, however, exposed some behaviour that surprises me. Inside my generator, doing: exec('foo = 7') in locals() print foo foo = 3 produces an UnboundLocalError. In case it's relevant, the error I get inside the generator if I don't specify local()s is: SyntaxError: unqualified exec is not allowed in function 'sequence_engine' it contains a nested function with free variables But doing the same thing in a simple test generator, even if it calls outside functions, works as I expect. Removing any subsequent reassignments of the same name fixes the error, and as it happens I can do this, but I'm curious, without me posting the whole generator (it's long), why doesn't the above exec() assignment work in that context? Thanks, John From Scott.Daniels at Acm.Org Thu Dec 25 19:52:10 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 25 Dec 2008 16:52:10 -0800 Subject: python interpreter black window In-Reply-To: References: Message-ID: Chris Rebert wrote: > On Thu, Dec 25, 2008 at 3:32 PM, Gandalf wrote: >> I use WX gui so the user doesn't actually need it, Is their any way to >> hide it? > > Make sure your Python program is run by pythonw.exe as opposed to python.exe > pythonw.exe exists specifically for the purpose of suppressing the DOS > Box on Windows. Absolutely right. Vy the way, naming your "main" program file something.pyw, rather than something.py is one of the ways ro do this. --Scott David Daniels Scott.Daniels at Acm.Org From scalet at yebu.de Mon Dec 8 17:09:23 2008 From: scalet at yebu.de (resi147) Date: Mon, 8 Dec 2008 14:09:23 -0800 (PST) Subject: close has no effect on Mac OSX Python 3.0 Message-ID: <83b43edf-81e5-4116-ad7b-2dcacde2d101@f3g2000yqf.googlegroups.com> I'm wondering if it's really a bug since it's so trivial: fp = open('/etc/services') ct = fp.read(1048) print(ct[-80:], end='') fp.close() ct = fp.read(17) print(ct) the second read should fail, but happily continues reading the file. Really a bug? As said in the subject, I use MacOSX 10.5.5 with Python 3.0, officially released these days. Karl From alan.chambers at cambridgeconsultants.com Fri Dec 12 12:08:45 2008 From: alan.chambers at cambridgeconsultants.com (alan.chambers at cambridgeconsultants.com) Date: Fri, 12 Dec 2008 09:08:45 -0800 (PST) Subject: Python extension: callbacks blocked when holding button down Message-ID: <05533b81-de89-4ee2-90c5-8f19533b65a9@g17g2000prg.googlegroups.com> I'm developing a Python extension. It's a wrapper for some firmware, and simulates the target hardware environment. I'm using wxPython. I pass a function to the extension so it can let Python know about certain events. The code is currently single threaded. My problem is that the callback seems to have no effect if it is called while I am holding down a wxButton in the Python GUI. Long button presses are significant in the firmware so this seems a bit limiting. Can anyone explain what is going on? What's the best workaround? Thanks. Al From jredgrave at capisco.com Tue Dec 2 17:12:33 2008 From: jredgrave at capisco.com (Jon Redgrave) Date: Tue, 2 Dec 2008 14:12:33 -0800 (PST) Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> Message-ID: <9566ebea-d6b9-45bf-9bba-df259508efd3@w3g2000yqc.googlegroups.com> On Dec 2, 2:35?pm, Astley Le Jasper wrote: ... Try using the "screen" utility - change the line in your crontab: cd /home/myusername/src && python myscript.py to cd /home/myusername/src && screen -dmS mypthon python -i myscript.py then once cron has started your program attach to the console using >> screen -r mypython (using python -i leaves you at the python prompt if the script just terminates) I email myself and drop into the pdb debugger on an exception, then use screen to debug the system From kay.schluehr at gmx.net Tue Dec 9 06:05:45 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 9 Dec 2008 03:05:45 -0800 (PST) Subject: python3.0 - any hope it will get faster? References: <6q70udFb5dmqU1@mid.dfncis.de> Message-ID: On 9 Dez., 11:51, Helmut Jarausch wrote: > Hi, > > I was somewhat surprised when I ran pystones with python-2.5.2 and > with python-3.0 > > On my old/slow machine I get > > python-2.5.2 > from test import pystone > pystone.pystones() > gives (2.73, 18315.018315018315) > > python-3.0 > from test import pystone > pystone.pystones() > gives (4.2700000000000005, 11709.601873536298) > > That's a drop of 36% ! > > I know that processing unicode is inherently slower, > but still I was surprised that it's so much slower. On my WinXP notebook python-3.0 >>> from test import pystone >>> pystone.pystones() (1.1734318188484849, 42610.059823557647) python-2.5.1 >>> from test import pystone >>> pystone.pystones() (1.2927221197107452, 38678.072601703308) From gagsl-py2 at yahoo.com.ar Wed Dec 10 15:10:38 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 10 Dec 2008 18:10:38 -0200 Subject: SequenceMatcher bug ? References: <67253331-5b36-4018-b15a-c0b86c5342d3@r37g2000prr.googlegroups.com> <3d8ba4fe-0eb0-462c-b243-c157a9c0fe6d@i18g2000prf.googlegroups.com> Message-ID: En Wed, 10 Dec 2008 15:14:20 -0200, eliben escribi?: >> > My system is Gentoo, which installs python from source. ?Maybe gentoo >> > applies patches that the binary releases don't have. >> >> I can't reproduce the problem. I got exactly the same results >> (0.999...) ? >> with all the releases I have at hand, ranging from 3.0 back to 2.1.3, >> all ? >> on Windows. > >> Andhttp://try-python.mired.org/says the same thing. >> > > What ? This can't be. > > 1. Go to http://try-python.mired.org/ > 2. Type > import difflib > 3. Type > difflib.SequenceMatcher(None, [4] + [5] * 200, [5] * 200).ratio() > > Don't you get 0 as the answer ? Ah, but that isn't the same expression you posted originally: SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + [5]).ratio() Using *that* expression I got near 1.0 always. But leaving out the [5] at the end, it's true, it gives the wrong answer. Old Python 2.1.3 didn't have this problem: Python 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> import difflib >>> difflib.SequenceMatcher(None, [4] + [5] * 500, [5] * 500).ratio() 0.99900099900099903 >>> difflib.SequenceMatcher(None, [4] + [5] * 200, [5] * 200).ratio() 0.99750623441396513 >>> difflib.SequenceMatcher(None, [4] + [5] * 100, [5] * 100).ratio() 0.99502487562189057 I've updated the tracker item. -- Gabriel Genellina From mail at microcorp.co.za Tue Dec 16 05:27:38 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 16 Dec 2008 12:27:38 +0200 Subject: alt.possessive.its.has.no.apostrophe References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> <9ImdneOohuZCNdvUnZ2dnUVZ_s3inZ2d@earthlink.com> Message-ID: <000901c95f69$003a5f00$0d00a8c0@hendrik> "Dennis Lee Bieber" wrote: 8<----- stuff blaming Davy for "aluminum" ---------- > Isn't Davy a Brit? No, he was a Brit. He's dead now. His safety lamp lives on. It's a good thing its got that heat-sink sieve- it's enabled countless miners to flee when they see its change of colour. Thus it's saved the lives of a lot of canaries, and that's of ecological importance. Spot the apostrophe error, if you can. - Hendrik From rt8396 at gmail.com Tue Dec 16 17:24:23 2008 From: rt8396 at gmail.com (r) Date: Tue, 16 Dec 2008 14:24:23 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <355f1cfe-6abb-4d2c-8bf4-3aa62e713c1f@w34g2000yqm.googlegroups.com> Message-ID: On Dec 15, 7:15?am, Luis M. Gonz?lez wrote: > On Dec 15, 1:38?am, cm_gui wrote: > > > hahaha, do you know how much money they are spending on hardware to > > make > > youtube.com fast??? > > > > By the way... I know of a very slow Python site called YouTube.com. In > > > fact, it is so slow that nobody ever uses it. > > Buddy, just stop whining and go with c++ if it makes you happy. > By the way, what's the blazingly fast application you need to write so > desperately? > What kind of performance problem have you find in python that makes > you so unhappy? > What are you going to do with all the extra speed provided by c++ (a > Hello World! ?)... Still no reply from cm_gui, he must have googled "C hello world" :D From ldo at geek-central.gen.new_zealand Sun Dec 7 02:32:21 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 07 Dec 2008 20:32:21 +1300 Subject: Don't you just love writing this sort of thing :) References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: In message , Arnaud Delobelle wrote: > * you seem to disregard the fact that in 'programming language' there > is the word 'language'. A language is a way to _communicate_ > information, in the case of a programming language you communicate > it to the computer but also to other human beings. It was Niklaus Wirth, I think who pointed out that programming languages are not properly "languages" but are actually "notations". Like mathematics is a notation. And mathematics, too, is a predominantly functional, not a procedural, notation. Could that be why so many people are frightened of functional constructs, like my code example and things like lambdas? Because they look too much like mathematics? From tino at wildenhain.de Mon Dec 29 06:54:57 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 29 Dec 2008 12:54:57 +0100 Subject: Windows SSH (remote execution of commands) - Python Automation In-Reply-To: <7FAD6FCE52421841A11B441DEF3A88CA01F09006@ZMY16EXM70.ds.mot.com> References: <7FAD6FCE52421841A11B441DEF3A88CA01F09006@ZMY16EXM70.ds.mot.com> Message-ID: <4958BA91.2070105@wildenhain.de> Hi, Narasimhan Raghu-RBQG84 wrote: > Hi experts, > > I am looking for some information on how to automate remote login to a > UNIX machine using ssh from a windows XP box. > > Possible way: > > 1. Use putty (or any other ssh client from windows XP). -- Can be > automated with command line parameters. The problem is that I am able to > login - Putty window opens up as well. But obviously I am unable to run > any commands in that. I need to find something like a handle to that > Putty window so that I can execute commands there. Obviously putty is one (of several) terminal emulators (or in short gui clients) for ssh protocol. This means they are made for interactive work with mouse and keyboard rather then for command automation. Its easy if you just use one of the many command line ssh clients. You can use os.popen() and friends or the command module to work with them. There is also another solution: http://www.lag.net/paramiko/ which implements the ssh protocol in python so you can do more and have finer control over the processes and channels (for example file transfer and command control w/o resort to multiple connections) This is a little bit harder of course. Also, sometimes its more easy and relieable to just use cron on unix side. This works much much better then Task scheduler on windows btw. Regards Tino > Can anyone provide me some help in achieving this ? > > > Thanks, > > -- > *Raghu* > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From skip at pobox.com Tue Dec 30 09:47:30 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 30 Dec 2008 08:47:30 -0600 Subject: Python list's mail server in DNSBL ? In-Reply-To: <495A31B9.6020507@shopzeus.com> References: <495A2825.4070000@shopzeus.com> <495A2957.6090805@holdenweb.com> <495A31B9.6020507@shopzeus.com> Message-ID: <18778.13442.50043.370958@montanaro-dyndns-org.local> >> > Ask your Mail-/DNS-Administrator to correct HELO and DNS MX >> > settings and to get removed from DNSBLs; in >> > bogusmx.rfc-ignorant.org >> > >> > >> > Please reply to if you feel this message to >> > be in error. I went to rfc-ignorant.org and looked up python.org. python.org was in their database from 2004-08-27 to 2005-11-09. It's not been there since. My guess is that chello.at is having problems interpreting rfc-ignorant.org records. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From tjreedy at udel.edu Fri Dec 5 13:01:06 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 05 Dec 2008 13:01:06 -0500 Subject: RELEASED Python 3.0 final In-Reply-To: <5926cb50-e53f-4e9e-8672-b4e29e2280b5@r36g2000prf.googlegroups.com> References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> <5926cb50-e53f-4e9e-8672-b4e29e2280b5@r36g2000prf.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Andreas Waldenburger: >> Whenever has it been a pythonic ideal to "not allow" stuff? You get >> warnings. Everything else is up to you. > > It's a strong source for bugs, especially for newbies, that I have > hoped to see removed from Python3 (my first request of this was years > ago). I was nearly sure to see this wart removed from Python3, and now > I hear it's presents still. I don't understand why they haven't fixed > it. Did you or someone fine a specific rejection of disallowing mixture in 3.0, or did no one specifically suggest it and offer to make the change? From pdorange at pas-de-pub-merci.mac.com Mon Dec 22 08:51:32 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Mon, 22 Dec 2008 14:51:32 +0100 Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <1iscu14.oixxplpgajabN%pdorange@pas-de-pub-merci.mac.com> Stephen Thorne wrote: > > def sign(x): > > if x==0.0: > > return 0.0 > > elif x>0.0: > > return 1.0 > > else: > > return -1.0 > > Isn't this approximately this? :: > > def sign(x): > return float(cmp(x, 0)) Yes cmp() is probably the closest function to sign. I'm new to python and here i discover at least 4 methods, i just make a small script for timing those methods (100 000 times each on a set of 10 values). I do not use timeit, i can't make it work easyly as it need a standalone env for each test. ---- the test script -------------------- #!/usr/bin/env python from math import atan2 import time def sign_0(x): if x==0.0: return 0.0 elif x>0.0: return 1.0 else: return -1.0 def sign_1(x): if x > 0 or (x == 0 and atan2(x, -1.) > 0.): return 1 else: return -1 def sign_2(x): return cmp(x, 0) sign_3 = lambda x:+(x > 0) or -(x < 0) def main(): candidates=[1.1,0.0,-0.0,-1.2,2.4,5.6,-8.2,74.1,-23.4,7945.481] startTime = time.clock() for i in range(100000): for value in candidates: s=sign_0(value) print "sign_0 : ",time.clock() - startTime startTime = time.clock() for i in range(100000): for value in candidates: s=sign_1(value) print "sign_1 : ",time.clock() - startTime startTime = time.clock() for i in range(100000): for value in candidates: s=sign_2(value) print "sign_2 : ",time.clock() - startTime startTime = time.clock() for i in range(100000): for value in candidates: s=sign_3(value) print "sign_3 : ",time.clock() - startTime if __name__ == '__main__' : main() ---- the results ----------------------------- My config : iMac (2,66 GHz intel dual core 2 duo) MacOS X 10.5.5 Python 2.5.1 sign_0 = 0.4156 second (0%) sign_1 = 0.5316 second (+28%) sign_2 = 0.6515 second (+57%) sign_3 = 0.5244 second (+26%) ---- conclusions ------------------------------- 1/ python is fast 2/ method (0) is the fastest 3/ cmp method (2) is the slowest 4/ the precise one (IEEE 754) is also fast (1) -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From casey.mcginty at gmail.com Mon Dec 1 23:21:13 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Mon, 1 Dec 2008 18:21:13 -1000 Subject: Google App Engine Code Challenge - write a tetris playing algorithm In-Reply-To: <10304c580812011932l7ef375fcv4149f66064d02a30@mail.gmail.com> References: <10304c580812011932l7ef375fcv4149f66064d02a30@mail.gmail.com> Message-ID: Well, I think its a cool idea. I might try it out if I can find some free cycles. And does the game logic assume the pieces come straight down? For example, what if you wanted to move a piece to the left or right after its past some vertical obstruction? For example If you place and upside down 'j' or 'l', is there any way to fill in the two blocked squares, without removing the top portion first? - Casey -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Tue Dec 23 04:59:07 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 23 Dec 2008 09:59:07 +0000 Subject: join a samba domain In-Reply-To: <1a326512-3c74-404d-9c51-fde35f39702e@t39g2000prh.googlegroups.com> References: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> <494fd597$0$90267$14726298@news.sunsite.dk> <73194a24-f14e-46f1-8789-886ba4729084@r15g2000prd.googlegroups.com> <1a326512-3c74-404d-9c51-fde35f39702e@t39g2000prh.googlegroups.com> Message-ID: <4950B66B.4020907@timgolden.me.uk> Toff wrote: > On 22 d?c, 19:37, Toff wrote: >> On 22 d?c, 18:59, Jens Henrik Leonhard Jensen >> >> wrote: >>> Toff wrote: >>>> d = c.Win32_ComputerSystem >>>> d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") >>> Shouldn't r"admin\\mydom" be "admin\\mydom" or r"admin\mydom". >>> Or maybe just "admin" >>> /Jens Henrik >> you are right but i've got the same error. > > the more i look at my script the more i think it s a BUG. > > #ALL works great > import wmi > c = wmi.WMI() > for computer in c.Win32_ComputerSystem(): > if computer.PartOfDomain: > print computer.Domain #DOMCD > print computer.SystemStartupOptions # (u'"Microsoft Windows XP > Professionnel" /noexecute=optin /fastdetect',) > > #error message > computer.JoinDomainOrWorkGroup('DOMCD', 'adminLocal', 'admin\ > \DOMCD',None,3 ) Try: computer.JoinDomainOrWorkgroup (...) note the lowercase "group" TJG From kajnilsson5 at hotmail.com Sun Dec 28 19:20:09 2008 From: kajnilsson5 at hotmail.com (kajnilsson5 at hotmail.com) Date: Sun, 28 Dec 2008 16:20:09 -0800 (PST) Subject: How to get involved Message-ID: <33e09baf-00b5-40f0-9b5f-152c370941e6@r36g2000prf.googlegroups.com> I'm new to the open source comunnity and I was wondering if there are any bugs that I can trouble shoot or just some beginner tasks I can be sent? Kaj Nilsson Kajnilsson5 at hotmail.com From tino at wildenhain.de Wed Dec 3 15:32:55 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Wed, 03 Dec 2008 21:32:55 +0100 Subject: python to parse excel file csv format In-Reply-To: <4936DC35.6010404@mrabarnett.plus.com> References: <4936DC35.6010404@mrabarnett.plus.com> Message-ID: <4936ECF7.3040400@wildenhain.de> MRAB wrote: > Jay Jesus Amorin wrote: >> This is how i do it, but it runs with error. Kindly help >> >> >> #!/usr/bin/env python >> >> import csv, sys, os >> filename = (sys.argv[1]) >> reader = csv.reader(open(filename, "rb"), delimiter=',', >> quoting=csv.QUOTE_NONE) >> >> try: >> for row in reader: >> os.popen("chown row[0] row[1]") > This should be: > > os.popen("chown %s %s" % (row[0], row[1])) > > or: > > os.popen("chown %s %s" % tuple(row)) No, it should really be os.popen(("chown",row[0],row[1])) or better yet, for fmodes,fname in reader: os.popen(("chown",fmodes,fname)) or even plus better: for fmodes,fname in reader: os.chmod(fname,fmodes) (Both my examples avoid problems with unquoted filenames) Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From worldgnat at gmail.com Mon Dec 1 12:30:42 2008 From: worldgnat at gmail.com (worldgnat) Date: Mon, 1 Dec 2008 09:30:42 -0800 (PST) Subject: HTML File Parsing References: <49077399$0$31880$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <495fad71-26dc-426d-b78d-7aa6eabefe2d@t11g2000yqg.googlegroups.com> On Oct 28, 3:18?pm, Stefan Behnel wrote: > Felipe De Bene wrote: > > I'm having problems parsing an HTML file with the following syntax : > > > > > ? ? > > ? ? > > and so on.... > > > whenever I feed the parser with such file I get the error : > > > HTMLParser.HTMLParseError: bad end tag: "", at > > line 515, column 45 > > Your HTML page is not HTML, i.e. it is broken. Python's HTMLParser is not made > for parsing broken HTML. However, you can use the parse of lxml.html to fix up > your HTML for you. > > http://codespeak.net/lxml/ > > Stefan It doesn't just choke on bad HTML, it also chokes on javascript that writes HTML, e.g. document.write(' wrote: >En Wed, 10 Dec 2008 15:14:20 -0200, eliben escribi?: > >> What ? This can't be. >> >> 1. Go to http://try-python.mired.org/ >> 2. Type >> import difflib >> 3. Type >> difflib.SequenceMatcher(None, [4] + [5] * 200, [5] * 200).ratio() >> >> Don't you get 0 as the answer ? > >Ah, but that isn't the same expression you posted originally: > >SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + [5]).ratio() > >Using *that* expression I got near 1.0 always. But leaving out the [5] at >the end, it's true, it gives the wrong answer. >... >I've updated the tracker item. Your assessment that it is the same problem as #1528074 is correct. It's the "popularity" optimization. The key here is that the second sequence consists of more than 200 identical items. For example, all of the following give the same bad result: difflib.SequenceMatcher(None, [4] + [5] * 200, [5] * 200).ratio() difflib.SequenceMatcher(None, [4] + [5] , [5] * 200).ratio() difflib.SequenceMatcher(None, [4] , [5] * 200).ratio() If you print get_matching_blocks(), you'll see that there are none, because the "b" sequence is optimized completely away. The #1528074 calls it "working by designed" and suggests updating the doc. However, I would argue that it's worth checking for this. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From saju.pillai at gmail.com Thu Dec 11 09:02:30 2008 From: saju.pillai at gmail.com (Saju Pillai) Date: Thu, 11 Dec 2008 06:02:30 -0800 (PST) Subject: How to convert uint64 in C into Python 32bit Object [ I am using Python2.2 ] References: <069f0d65-a3d5-4e8f-a85b-c53743ab99d0@i18g2000prf.googlegroups.com> <8485fb8f-4425-436d-9e0b-2079c80c9802@q26g2000prq.googlegroups.com> <6b710b67-0e91-4c55-8ef7-23891addfc51@q26g2000prq.googlegroups.com> Message-ID: <3ddb340b-83f9-44b0-8b4e-7a4f05d3a999@g17g2000prg.googlegroups.com> On Dec 11, 6:45?pm, Explore_Imagination wrote: > On Dec 11, 4:45 am, John Machin wrote: > > > > > On Dec 11, 9:49 am, Explore_Imagination > > wrote: > > > > Hi all > > > > I am new to C and python ... I want to convert C data type uint64 > > > variable into the Python 32bit Object. I am currently using Python 2.2 > > > [ It is necessary to use it ] > > > > Kindly give your suggestion how and in which way I can achieve this > > > task. > > > I'm not sure what you mean by "the Python 32bit Object". A Python int > > object holds a signed 32-bit integer. A Python long object holds a > > signed integer of arbitrary size. You will need to convert your uint64 > > into a Python long; then, if necessary, check that the result will fit > > in an int (result <= sys.maxint). > > > If the "C variable" is in an 8-byte string that you have read from a > > file, the unpack function in the struct module will do the job. > > Assuming your computer is little-endian: > > > >>> maxu64 = '\xff' * 8 # example input string > > >>> import struct > > >>> result = struct.unpack(' > >>> result > > > 18446744073709551615L>>> 2 ** 64 - 1 > > > 18446744073709551615L > > > If however you mean that in C code you need to build a Python object > > to pass over to Python code: According to the Python/C API Reference > > Manual (http://www.python.org/doc/2.2.3/api/longObjects.html): > > > PyObject* PyLong_FromUnsignedLongLong(unsigned long long v) > > ? ? Return value: New reference. > > ? ? Returns a new PyLongObject object from a C unsigned long long, or > > NULL on failure. > > > If however you mean something else, .... > > > HTH, > > John > > Thanks for your feedback ... Actually I want to pass unit64 variable > in C to python > but at the same time I want to have a generic code which should work > on both little-endian > and big endian architectures > > Any suggestions ? I am not sure if endianness comes into the picture. As long as sizeof (uint64) == sizeof(unsigned long long) on your platform, python should have no problem accepting the return value of PyLong_FromUnsignedLongLong(uint64_var); srp -- http://saju.net.in From joe at strout.net Thu Dec 11 19:01:37 2008 From: joe at strout.net (Joe Strout) Date: Thu, 11 Dec 2008 17:01:37 -0700 Subject: any Python developers available in the Denver area? Message-ID: <7CFB9612-786D-488C-8B98-4002FABB0465@strout.net> My company is considering a contract job that would require some development staff on the client site in Denver. We'd like to subcontract some of that work. If you're a good Python coder in the Denver area, and would be available at least three days a week starting in January, please send me email privately. Thanks, - Joe From Scott.Daniels at Acm.Org Fri Dec 19 19:18:03 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 19 Dec 2008 16:18:03 -0800 Subject: IDLE doesn't show stderr output from extension modules In-Reply-To: <6406df08-36bb-4cd8-a356-6d563c2eac7f@e1g2000pra.googlegroups.com> References: <6406df08-36bb-4cd8-a356-6d563c2eac7f@e1g2000pra.googlegroups.com> Message-ID: Brian Cole wrote: > I'm importing an extension module created with SWIG. When working with > the module interactively in IDLE there should be warning and error > messages printed to stderr by the extension module. However, these are > not being caught by the IDLE window, they are going directly to the > terminal that was used to start IDLE. However if the extension module is printing to stderr via non-Python function calls (e.g. C or C++ or Fortran), Idle and Python have no chance to get to the output. If you are using Python calls for the I/O, check if some variant of bug 3926's fix code solves your problems. --Scott David Daniels Scott.Daniels at Acm.Org From martin at v.loewis.de Tue Dec 2 15:25:23 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Tue, 02 Dec 2008 21:25:23 +0100 Subject: Multiple Versions of Python on Windows XP In-Reply-To: References: <4934de22$0$27863$9b622d9e@news.freenet.de> <493592EE.9090005@v.loewis.de> Message-ID: <493599B3.8070606@v.loewis.de> > Using a right click, one can open any .py file with say SciTe. Within > SciTe, one can Run the current file. > > It would be good to have the appropriate version (my use of "default") > preselected. I don't know how SciTe choses the version of Python to run. In the sense in why you use the word, there might just not be a "default" version of Python on Windows. Somebody who knows SciTe better may correct me. Regards, Martin From v+python at g.nevcal.com Tue Dec 2 03:56:13 2008 From: v+python at g.nevcal.com (Glenn Linderman) Date: Tue, 02 Dec 2008 00:56:13 -0800 Subject: Multiple Versions of Python on Windows XP In-Reply-To: <4934E3BF.7000403@v.loewis.de> References: <4934de22$0$27863$9b622d9e@news.freenet.de> <4934E183.9020404@g.nevcal.com> <4934E3BF.7000403@v.loewis.de> Message-ID: <4934F82D.1090601@g.nevcal.com> On approximately 12/1/2008 11:29 PM, came the following characters from the keyboard of Martin v. L?wis: >> It would be nice if the ftypes were version specific as created by the >> installer; IIRC, I created the above three from the ftype Python.File as >> I installed each version. >> > > That's a good idea; please submit a wish list item to bugs.python.org. > There may be issues (such as people relying on this being Python.File), > but I can't see any problems off-hand. > > Regards, > Martin > OK, Issue 4485 created. My first one, so let me know if I goofed. I elaborated a bit from the original email, upon reflection. Seemed useful, but also seemed complex by the time I got done. I don't really have a clue what the uninstaller should do with these; nor have I fiddled to know if it presently removes Python.File. I suppose it should delete them, if and only if the ftype and assoc have the same content as was created by the corresponding version installation. -- Glenn -- http://nevcal.com/ =========================== A protocol is complete when there is nothing left to remove. -- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking From rdcollum at gmail.com Fri Dec 19 09:23:55 2008 From: rdcollum at gmail.com (Roger) Date: Fri, 19 Dec 2008 06:23:55 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <494b5f47$0$17068$6e1ede2f@read.cnntp.org> <494b632b$0$17070$6e1ede2f@read.cnntp.org> Message-ID: > Note that I took out the lambdas and gave event arguments to the > functions; if you did that on purpose, because you need to call the same > functions without events, then just ignore that... > SO, the other workaround, which I've used, is to bind the event to a > generic function, and have that generic function conditionally call > the functions you want. I'll go back and try to make an example from > your example. -Chuckk Thanks Chuckk! You've done exactly what I did so far. I went through the source in Tkinter.py and had an inkling of what the unbind function was doing. I believe, and please correct me if I'm wrong, in: self.tk.call('bind', self._w, sequence, '') , the '' is unbinding all methods and I believe the self.deletecommand(funcid) is a workaround for a memory leak otherwise. Perhaps self.tk.call('bind', self._w, sequence, funcid) would work but that's a pure guess. I would have liked to investigate the tcl source directly to see if I could develop a workaround through a tk.call() but that was hitting a wall in terms of any documentation I could research. I'm interested in any workaround you may have however! You now, I really considered going over to wxwidgets, and I definitely want to try it after the current app I'm developing is complete, but I've so much experience with Tkinter now after banging my head against a wall for months (productive months mind you) on various projects, it's like an old persnickety friend you just can't give up. =) Thanks a ton! Roger. From musiccomposition at gmail.com Sun Dec 28 16:36:54 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sun, 28 Dec 2008 13:36:54 -0800 (PST) Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <0167cbf7$0$6988$c3e8da3@news.astraweb.com> Message-ID: <088c7d93-e87f-44a0-9ea7-faa7feded7df@a26g2000prf.googlegroups.com> On Dec 28, 1:35?pm, Steven D'Aprano wrote: > The second thing I think is that maybe the function is a generator, and > so I look for a yield. You shouldn't, though; Generators can't contain any return statement. From steve at holdenweb.com Fri Dec 12 01:28:50 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Dec 2008 01:28:50 -0500 Subject: how to convert '\xf0' to 0xf0 ? In-Reply-To: <8f5b95c0-486d-48ce-b75c-e18a86d73f50@l33g2000pri.googlegroups.com> References: <1cb85265-1c36-4e4b-88f1-46b0ebae3dea@v5g2000prm.googlegroups.com> <8f5b95c0-486d-48ce-b75c-e18a86d73f50@l33g2000pri.googlegroups.com> Message-ID: Looks like you need the struct module. That can convert binary fields of various lengths into the appropriate Python types, and vice versa. >>> import struct >>> struct.unpack("L", '\xf0\xf0\xff\xfe') (4278186224L,) >>> struct.unpack("l", '\xf0\xf0\xff\xfe') (-16781072,) >>> regards Steve chengang.beijing at gmail.com wrote: > Hi, > > ord('\xf0') works and it only works for char. Do you know any way to > convet > '\xf0\xf0' and '\xf0\xf0\xff\xfe' to integer? > > > Br, Chen Gang > > On Dec 12, 12:40 pm, Steve Holden wrote: >> chengang.beij... at gmail.com wrote: >>> '\xf0' is the value read from a binary file, I need to change this >>> kinds strings to int for further processing... >>> if it is in C, then '\xf0' is an integer and it can be handled >>> directly, but in python, it is a string. >>> and both int('10',16) and int('0x10',16) returns 16. >>> Br, Chen Gang >>> On Dec 12, 12:06 pm, Tommy Nordgren wrote: >>>> On Dec 12, 2008, at 4:48 AM, chengang.beij... at gmail.com wrote: >>>>> int('\xf0',16) doesn't work, any way to do that? >>>>> -- >>>>> http://mail.python.org/mailman/listinfo/python-list >>>> Should be int('10',16) >>>> or int('0x10',16) >> It seems that you want the integer value of a character you read in from >> a file. Is this correct? Note that '\xf0' is the interpreter's way of >> representing a one-character string whose only character has the >> hexadecimal value f0, because the actual character is not printable: the >> backslash has a special meaning in character string literals. >> >> Any one-character string, however, can be converted to the equivalent >> integer value using the ord() function. You can convert the other way >> using the chr() function: >> >> >> >>>>> ord('A') >> 65 >>>>> chr(65) >> 'A' >>>>> ord('\xf0') >> 240 >>>>> chr(240) >> '\xf0' >>>>> hex(240) >> '0xf0' >> >> So just apply the ord() function to the character and you'll get its >> integer value! >> >> regards >> Steve >> -- >> Steve Holden +1 571 484 6266 +1 800 494 3119 >> Holden Web LLC http://www.holdenweb.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From brigettehodson at gmail.com Tue Dec 16 12:51:09 2008 From: brigettehodson at gmail.com (Brigette Hodson) Date: Tue, 16 Dec 2008 10:51:09 -0700 Subject: Python Dictionary Algorithm Question Message-ID: <3ca641b40812160951h3a13e69am291afb02965451a7@mail.gmail.com> Hello! I am in a beginning algorithms class this semester and I am working on a presentation. I want to discuss in some detail the algorithm python uses to determine the hash function for python dictionaries. Does anyone know what this algorithm is? Or where I can go to find information on it? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eric at ericaro.net Thu Dec 18 05:38:45 2008 From: eric at ericaro.net (eric) Date: Thu, 18 Dec 2008 02:38:45 -0800 (PST) Subject: Best Practice using Glade/Python Message-ID: <1b63220b-1572-4a8f-8f43-474ef8194bb0@s1g2000prg.googlegroups.com> Hi, I was wondering which is the "best practice" using glade/python, and, of course, especially the connect (both side). I didn't found that much documentation on the net ( too noisy), and the best "thing" I've found was http://www.linuxjournal.com/article/7558 which is a bit old now (2004). The article is very interesting BTW, but I was concerned by the fact it might be a little outdated. It smells like I'm missing something here, and that there have been a clean way to connect both (the autoconnect stuff does not seem that clean to me) for a long time now. So here is the question, do you practive galde/python, which is your practice ? Thanks Eric http://codeslash.blogspot.com From invalid at invalid Tue Dec 23 14:18:10 2008 From: invalid at invalid (Grant Edwards) Date: Tue, 23 Dec 2008 13:18:10 -0600 Subject: pseudo terminal usage from Python? References: <5t-dnRgMi9Z4lszUnZ2dnUVZ_vOdnZ2d@posted.visi> Message-ID: On 2008-12-23, skip at pobox.com wrote: > > Grant> Are you sure it's not Python buffering its input? Have you tried > Grant> "python -u mympstat.py"? > > Nope. -u unbuffers stdout and stderr, not stdin. It really must be mpstat > being uncooperative. That's not what my python man page says: -u Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode. That's for 2.5.2, but that's how I remember previous versions working as well. -- Grant Edwards grante Yow! We have DIFFERENT at amounts of HAIR -- visi.com From eric at ericaro.net Fri Dec 5 11:33:19 2008 From: eric at ericaro.net (eric) Date: Fri, 5 Dec 2008 08:33:19 -0800 (PST) Subject: simplest way to strip a comment from the end of a line? References: <52e3f2a9-6fb1-42ef-9871-c904ede5520e@t3g2000yqa.googlegroups.com> <9cdc9039-6b7b-42fb-b261-4ad721ccd1d4@j39g2000yqn.googlegroups.com> <340697a3-3f17-477a-aea2-c85344da93d4@k41g2000yqn.googlegroups.com> Message-ID: On Dec 5, 11:56?am, eric wrote: > On Dec 4, 11:35?pm, Paul McGuire wrote: > > > Yowza! ?My eyes glaze over when I see re's like "r'(?m)^(?P.*? > > (".*?".*?)*)(?:#.*?)?$"! > > yeah, I know ... :( ( I love complicated regexp ... it's like a puzzle > game for me) > > > > > from pyparsing import quotedString, Suppress, restOfLine > > > comment = Suppress('#' + restOfLine) > > recognizer = quotedString | comment > > > for t in tests: > > ? ? print t > > ? ? print recognizer.transformString(t) > > ? ? print > > > Prints: > > > this is a test 1 > > this is a test 1 > > > this is a test 2 #with a comment > > this is a test 2 > > > this is a '#gnarlier' test #with a comment > > this is a '#gnarlier' test > > > this is a "#gnarlier" test #with a comment > > this is a "#gnarlier" test > > > For some added fun, add a parse action to quoted strings, to know when > > we've really done something interesting: > > > def detectGnarliness(tokens): > > ? ? if '#' in tokens[0]: > > ? ? ? ? print "Ooooh, how gnarly! ->", tokens[0] > > quotedString.setParseAction(detectGnarliness) > > > Now our output becomes: > > > this is a test 1 > > this is a test 1 > > > this is a test 2 #with a comment > > this is a test 2 > > > this is a '#gnarlier' test #with a comment > > Ooooh, how gnarly! -> '#gnarlier' > > this is a '#gnarlier' test > > > this is a "#gnarlier" test #with a comment > > Ooooh, how gnarly! -> "#gnarlier" > > this is a "#gnarlier" test > > > -- Paul > > I didn't knew pyparsing. It's amazing ! thanks maybe you'd rather replace: splitter = re.compile(r'(?m)^(?P.*?(".*?".*?)*)(?:#.*?)?$') by from reO import * quote = characters('"') # defining the characters used as string sep sharp= string('#') # defining the sharp symbol data = ALL + repeat( group( quote + ALL + quote + ALL ) ) # ALL ( "ALL" ALL)* comment = group(sharp+ALL+END_LINE) # the comment itself xp = flag(MULTILINE=True) + START_LINE + group( data, name="data") + if_exists(comment) splitter = xp.compile() From paul_hildebrandt at yahoo.com Thu Dec 4 17:40:34 2008 From: paul_hildebrandt at yahoo.com (Paul Hildebrandt) Date: Thu, 4 Dec 2008 14:40:34 -0800 (PST) Subject: Porting to 3.0, test coverage Message-ID: <8f25bd4f-fd2f-4908-88ee-852624cf3234@z6g2000pre.googlegroups.com> I was just reading what's new with Python 3.0 http://docs.python.org/dev/3.0/whatsnew/3.0.html I like this prerequisite to porting: "Start with excellent test coverage" May I suggest looking into Pythoscope for those looking to boost test coverage. http://pythoscope.org Paul From tino at wildenhain.de Sat Dec 13 13:43:57 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Sat, 13 Dec 2008 19:43:57 +0100 Subject: zip a created file In-Reply-To: References: Message-ID: <4944026D.3040806@wildenhain.de> frendy zhang wrote: > if form.accepts(request.vars,session): > for table in db.tables: > rows=db(db[table].id).select() > print rows > open(str(os.sep).join([os.getcwd(), 'applications', > request.application, 'databases', > table+'.csv']),'w').write(str(db(db[table].id).select ())) > > > where and what should i put the zip code to zip the file created above? > thanks in advance You don't? ;) The code is very -crappy- suboptimal... - can you reformulate the problem first? Where is request, session coming from? If its a web application, what are you doing with open() and why this complicated code instead of just os.path.join() ? In short, creating a file and zipping and sending to the browser should not need to create an intermediate file in the file system. (This also avoids a lot of problems with your approach above - for example if the same query is put twice the same time...) Just have a look at the examples in the documentation which come with the zipfile module. Cheers Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From fetchinson at googlemail.com Sun Dec 7 13:21:06 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sun, 7 Dec 2008 10:21:06 -0800 Subject: Guido's new method definition idea In-Reply-To: <47c890dc0812061353x6214cfb4s1d729d36ab93f3dc@mail.gmail.com> References: <47c890dc0812061353x6214cfb4s1d729d36ab93f3dc@mail.gmail.com> Message-ID: >>> Hi folks, >>> >>> The story of the explicit self in method definitions has been >>> discussed to death and we all know it will stay. However, Guido >>> himself acknowledged that an alternative syntax makes perfect sense >>> and having both (old and new) in a future version of python is a >>> possibility since it maintains backward compatibility. The alternative >>> syntax will be syntactic sugar for the old one. This blog post of his >>> is what I'm talking about: >>> >>> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... >>> >>> The proposal is to allow this: >>> >>> class C: >>> def self.method( arg ): >>> self.value = arg >>> return self.value >>> >>> instead of this: >>> >>> class C: >>> def method( self, arg ): >>> self.value = arg >>> return self.value >> >> >> >> -1 >> >> I explained why deep in the thread but I'll elaborate more here. When >> I see a def statement, I mentally equate that to an assigment to the >> thing being def'ed. So for instance, when I see this: >> >> def (): >> >> I think of it like this: >> >> = >> >> >> Thus, if I were to see a function definition like this >> >> def foo.bar(): return 1 >> >> I would think you were defining a function and assigning it to >> foo.bar. IOW, it would be mostly equivalent to this: >> >> foo.bar = lambda: 1 >> >> >> (Analogously, I would expect a definition like this: >> >> def baz[10](): return 1 >> >> to be equivalent to this: >> >> baz[10] = lambda: 1 ) >> >> >> So, if, inside a class definition, I were to see this: >> >> def self.method(): return 1 >> >> Well, I'd understand that is was a method assigment, of course, but it >> would conflict with what I would expect the natural meaning of >> something like def a.b() would be. The above statement is not >> equivalent to: >> >> self.method = lambda: 1 >> >> but I think that's what it ought to be, in general. > > Similarly, to those coming from Ruby or those operating under the > frequent misunderstanding that the `def`s are happening in the context > of a class object (which in reality has yet to be created), `self` in > this context might be misconstrued as the class object and thus `def > self.foo` might be misunderstood (through the intuitive equivalence > you mention) as a defining a classmethod rather than an instance > method. This is actually a real counter argument, I think. Self, the instance, doesn't exist until it is created and certainly doesn't exist during class creation. So something like class C: def self.meth( arg ): return arg can be confusing since 'self' appears as if it was defined in the scope of C but clearly it isn't yet. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From lew at lewscanon.com Tue Dec 2 15:21:14 2008 From: lew at lewscanon.com (Lew) Date: Tue, 2 Dec 2008 12:21:14 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: Xah Lee wrote: > LOL Jon. r u trying to get me to do otimization for you free? These are professional software development forums, not some script- kiddie cellphone-based chat room. "r" is spelled "are" and "u" should be "you". > how about pay me $5 thru paypal? I'm pretty sure i [sic] can speed it up. > Say, maybe 10%, and even 50% is possible. The first word in a sentence should be capitalized. "PayPal" is a trademark and should be capitalized accordingly. The word "I" in English should be capitalized. Proper discipline in these matters helps the habit of mind for languages like Java, where case counts. Jon Harrop has a reputation as an extremely accomplished software maven and columnist. I find his claims of relative speed and compactness credible. He was not asking you to speed up his code, but claiming that yours was not going to be as effective. The rhetorical device of asking him for money does nothing to counter his points, indeed it reads like an attempt to deflect the point. -- Lew From mail at anjanesh.net Fri Dec 19 22:47:56 2008 From: mail at anjanesh.net (Anjanesh Lekshminarayanan) Date: Sat, 20 Dec 2008 09:17:56 +0530 Subject: mod_python resources In-Reply-To: References: <78064e7e-ba2c-4959-b5f8-4d1b928bc5fe@y18g2000yqn.googlegroups.com> <4lsl16-15a.ln1@archaeopteryx.softver.org.mk> Message-ID: <1a7951080812191947j148fae8bq2357b614ecfe3f74@mail.gmail.com> Same requirement here. But isnt there any mod_python for Python 3.0 ? Or do we need to build it from source ourselves ? I was hoping there would be mod_wsgi binaries for Python 3.0. From callen314 at gmail.com Tue Dec 2 13:36:13 2008 From: callen314 at gmail.com (Craig Allen) Date: Tue, 2 Dec 2008 10:36:13 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> Message-ID: <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> > Just remember thought that if you threat Python like a > hammer, suddenly everything will look like a bail. > don't you mean if you use Python like a pitchfork? From mludvig at logix.net.nz Mon Dec 29 07:06:09 2008 From: mludvig at logix.net.nz (Michal Ludvig) Date: Tue, 30 Dec 2008 01:06:09 +1300 Subject: Unicode encoding - ignoring errors Message-ID: <4958BD31.1010801@logix.net.nz> Hi, in my script I have sys.stdout and sys.stderr redefined to output unicode strings in the current system encoding: encoding = locale.getpreferredencoding() sys.stdout = codecs.getwriter(encoding)(sys.stdout) However on some systems the locale doesn't let all the unicode chars be displayed and I eventually end up with UnicodeEncodeError exception. I know I could explicitly "sanitize" all output with: whatever.encode(encoding, "replace") but it's quite inconvenient. I'd much prefer to embed this "replace" operation into the sys.stdout writer. Is there any way to set a conversion error handler in codecs.getwriter() or perhaps chain it with some other filter somehow? I prefer to have questionmarks in the output instead of experiencing crashes with UnicodeEncodeErrors ;-) Thanks! Michal From xahlee at gmail.com Wed Dec 3 16:15:11 2008 From: xahlee at gmail.com (Xah Lee) Date: Wed, 3 Dec 2008 13:15:11 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> Message-ID: <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> On Dec 3, 8:24 am, Jon Harrop wrote: > My example demonstrates several of Mathematica's fundamental limitations. enough babble Jon. Come flying $5 to my paypal account, and i'll give you real code, amongest the programing tech geekers here for all to see. I'll show, what kinda garbage you cooked up in your Mathematica code for ?comparison?. You can actually just post your ?comparisons? to ?comp.soft- sys.math.mathematica?, and you'll be ridiculed to death for any reasonable judgement of claim on fairness. > Consequently, there is great value in combining Mathematica with performant > high-level languages like OCaml and F#. This is what the vast majority of > Mathematica users do: they use it as a glorified graph plotter. glorified your ass. Yeah, NASA, Intel, NSA, ... all use Mathematica to glorify their pictures. LOL. > What exactly do you believe is wrong with my code? come flies $5 to my paypal, and i'll explain further. > I am not trying to make Mathematica look bad. It is simply not suitable when > hierarchical solutions are preferable... Certainly there are areas other langs are more suitable and better than Mathematica (for example: assembly langs). But not in the ways you painted it to peddle your F# and OCaml books. You see Jon, you are this defensive, trollish guy, who takes every opportunity to slight other langs that's not one of your F#, OCml that you make a living of. In every opportunity, you injest your gribes about static typing and other things, and thru ensuring chaos paves the way for you to post urls to your website. With your math and functional programing expertise and Doctor label, it can be quite intimidating to many geekers. But when you bump into me, i don't think you have a chance. As a scientist, i think perhaps you should check your newsgroup demeanor a bit? I mean, you already have a reputation of being biased. Too much bias and peddling can be detrimental to your career, y'known? to be sure, i still respect your expertise and in general think that a significant percentage of tech geeker's posts in debate with you are moronic, especially the Common Moron Lispers, and undoubtably the Java and imperative lang slaving morons who can't grope the simplest mathematical concepts. Throwing your Mathematica bad mouthing at me would be a mistake. Come, fly $5 to my paypal account. Let the challenge begin. Xah ? http://xahlee.org/ ? From prologic at shortcircuit.net.au Mon Dec 8 04:04:29 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Dec 2008 19:04:29 +1000 Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? In-Reply-To: <7e1a9226-c7a9-4b5e-bfbb-ea079639d6a2@t39g2000prh.googlegroups.com> References: <5ccd4a18-cd2b-4040-90c6-33723af15e96@b38g2000prf.googlegroups.com> <7e1a9226-c7a9-4b5e-bfbb-ea079639d6a2@t39g2000prh.googlegroups.com> Message-ID: On Mon, Dec 8, 2008 at 6:31 PM, alex23 wrote: > On Dec 8, 2:26 pm, illume wrote: >> pygame is simpler to learn, since it doesn't require you to know how >> to create classes or functions. > > I'm not sure if I'd be quick to tout that as an advantage... :) Neither would i. Classes and Objects and good OOP practises can benefit a pygame game just as well as any other Python app. What's more using and learning Python's OO semantics and syntax is really really easy :) --JamesMills -- -- -- "Problems are solved by method" From ldo at geek-central.gen.new_zealand Sat Dec 6 02:29:24 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 06 Dec 2008 20:29:24 +1300 Subject: Don't you just love writing this sort of thing :) References: <0149f773$0$20670$c3e8da3@news.astraweb.com> Message-ID: In message <0149f773$0$20670$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > It would have been far more concise ... Gee, I thought people were complaining it was too cryptic, now it turns out they were actually complaining because it was too verbose. From rt8396 at gmail.com Thu Dec 11 12:36:44 2008 From: rt8396 at gmail.com (r) Date: Thu, 11 Dec 2008 09:36:44 -0800 (PST) Subject: Preventing execution of a method References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> <764daeef-bfbe-411a-8521-bb114321e4ac@b38g2000prf.googlegroups.com> <19304f8c-e34f-4aa9-8df2-6a7d3553007a@e1g2000pra.googlegroups.com> Message-ID: <2eed8876-94d2-4304-88a5-eb4a78b4f41d@33g2000yqm.googlegroups.com> > And of course -now- I realise that the OP was asking for protecting > methods. Please disregard my last post :) Alex23, Are you telling me that you do not know how to YANK your own post? I find that hard to believe. ;) From castironpi at gmail.com Sun Dec 21 06:23:43 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 21 Dec 2008 03:23:43 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <015da0a4$0$20656$c3e8da3@news.astraweb.com> Message-ID: <2e82daf5-f1db-4176-8994-6c738bbf916d@p2g2000prn.googlegroups.com> On Dec 20, 8:26?pm, Steven D'Aprano wrote: > On Sat, 20 Dec 2008 17:55:35 -0800, Aaron Brady wrote: snip > > This behavior is currently legal: > > >>>> "%i %%i" % 0 % 1 > > '0 1' > > > So, just extend it. ?(Unproduced.) > > >>>> "%i %i" % 0 % 1 > > '0 1' > > Errors should never pass silently, unless explicitly silenced. You have > implicitly silenced the TypeError you get from not having enough > arguments for the first format operation. That means that you will > introduce ambiguity and bugs. No, it's not part of the (new) '%' operation. '%' handles one flag at a time. It's not an error if the author intends it. > "%i %i %i %i" % 5 % 3 %7 > > Here I have four slots and only three numbers. Which output did I expect? > > '%i 5 3 7' > '5 %i 3 7' > '5 3 %i 7' > '5 3 7 %i' Anything, so long as it's (contraction) consistent and general. > Or more likely, the three numbers is a mistake, there is supposed to be a > fourth number there somewhere, only now instead of the error being caught > immediately, it won't be discovered until much later. Leave that to unit testing and your QA team. To make the change, the burden of proof (which is large) would fall to me. However, in the abstract case, it's not clear that either one is favorable, more obvious, or a simpler extrapolation. Bug-proneness is an argument against a construction, just not a conclusive one. How heavy is it in this case? From steve at REMOVE-THIS-cybersource.com.au Sat Dec 6 10:34:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Dec 2008 15:34:12 GMT Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> <8b8d1fb3-f49e-49bf-8cfe-eeee5ed16109@r37g2000prr.googlegroups.com> Message-ID: <014a932b$0$20670$c3e8da3@news.astraweb.com> On Sat, 06 Dec 2008 07:15:27 -0800, Russ P. wrote: > On Dec 6, 4:32?am, Andreas Waldenburger wrote: >> On Sat, 6 Dec 2008 04:02:54 -0800 (PST) bearophileH... at lycos.com wrote: >> >> > class C: >> > ? ? def $method(arg): >> > ? ? ? ? $value = arg >> >> > (Note there's no point after $, it's not currently possible). If -- and that's a HUGE if -- the compiler is changed to allow $method, it could certainly be changed to allow $.method. >> > Ruby >> > uses @ and @@ for similar purposes. I agree that the code looks >> > worse, but also shorter to read and write, so in lines of code that >> > use many instance attributes, that short $ syntax helps keep the line >> > shorter. So I may grow to accept this sugar... If a line of code uses too many instance attributes to fit comfortably on a line, spread it over two lines. There is no newline shortage, they are a renewable resource. >> But that is not the way Python is meant to work. There are several >> tennets in the Zen of Python that don't chime well with this approach. >> "self" is a speaking identifier, "$" isn't. > > Is "@" a "speaking identifier? How about "#" and "!="? Last I heard, > they were all part of Python. Yes they are. @f is pronounced "at f" or "decorate f". # comment is pronounced "hash comment" or even not pronounced at all. x != y is pronounced "x not equal to y" The proposed def $method(arg): would be pronounced "def dollar method arg" or "def method self arg". The first is ugly to my ears, the second confusing. -2 on this proposal. -- Steven From clp at rebertia.com Wed Dec 31 06:48:49 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 31 Dec 2008 03:48:49 -0800 Subject: Pass by reference In-Reply-To: <529e1d98-8932-49f0-b569-85285bd50f23@p2g2000prn.googlegroups.com> References: <529e1d98-8932-49f0-b569-85285bd50f23@p2g2000prn.googlegroups.com> Message-ID: <47c890dc0812310348l1b1278bcke50ed5819722d639@mail.gmail.com> On Wed, Dec 31, 2008 at 3:30 AM, iu2 wrote: > Hi, > > Is it possible somehow to change a varible by passing it to a > function? > > I tried this: > > def change_var(dict0, varname, val): > dict0[varname] = val > > > def test(): > a = 100 > change_var(locals(), 'a', 3) > print a > > > But test() didn't work, the value a remains 100. Yes, that's clearly stated in the documentation for locals(); from http://docs.python.org/library/functions.html#locals : "Warning: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter." > > I have several variables initialized to None. > I need to convert each one of them an object only if it is None. > something like: > > if not var1: var1 = MyObject() That should be: if var1 is None: var1 = MyObject() Otherwise, the "conversion" will also happen if var1 happens to be a false but non-None object, e.g. {}, [], 0, etc Also, it's just the idiomatic way of writing tests against None in Python. > > I want this to be a function, that is: > > def create_obj(var): > if not var: var = MyObj() > # set properties of var > > Now, I know I can achieve this by functional programming, > > def create_obj(var): > if not var: > x = MyObj() > # set properties of x > return x > return var > > and then > > var = creaet_obj(var) > > Is there another way? Not really, or at the very least it'll be kludgey. Python uses call-by-object (http://effbot.org/zone/call-by-object.htm), not call-by-value or call-by-reference. Could you explain why you have to set so many variables to the same value (if they're None)? It's a bit strange and could be a sign that there's a better way to structure your program (e.g. use a dictionary). We might be able to offer more helpful suggestions if you explain. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From pavlovevidence at gmail.com Fri Dec 19 15:50:49 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 19 Dec 2008 12:50:49 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> <88ff7c46-2b23-49e4-865e-781d23433799@l33g2000pri.googlegroups.com> Message-ID: On Dec 19, 12:44?pm, r wrote: > ~Michael, > What?s next down this road of self destruction? Hey guys, forget about > about empty parenthesis on a function/method call, ?we should not have > to waste are time typing them? Wait forget about them all together and > we will just write Ruby code? > > Def function arg arg arg arg arg arg > > ?Yea, that looks good?.insert(sarcasm) > Things like forcing empty tuple on function/method calls are what make > python so great. Python dumped the C bracket plague, ?but enforces > parenthesis even for a no argument function. But hell, why shouldn?t > we have 50 ways to the same thing in Python like Ruby. > > PS. Don?t discredit Walter just because he is not on the dev team, > that don?t mean squat! > > ~Bearophile, > Thanks for your civil approach to this conversation but I must > disagree with you on the new string formatting syntax. You said the > new syntax is suppost to be easier on the n00b , I say it pollutes a > students mind. What is wrong with similarities to C formatting, ?I > find nothing complicated about it. > > %s (means put a string here) > %d (means put a integer here) > %f (means put a float here) > > It does not get any simpler than that, No, you just think it's easiest because that's the way you learned it. I'm kind of ambivalent about the change (it does have a couple minor drawbacks), but I don't see any way that the new method isn't easier to learn than the old--especially if you want to do more advanced formatting--unless you already knew the old method. I really don't like that they made format a string method, though, I would have hoped for a built-in, and why didn't they abbreviate this one? If any function or method would have had a case for an abbreviated name, this was it. But just about anything is better than that % operator and its multi-level confusion involving tuple syntax, operator precedence, and special-casing of tuples and dicts. > and this will just ease the > transition to C programming for this student. Lets not forget how > important C is! C programmers who learn Python have to learn all kinds of new things, a new string formating method would be a minor one. As for everyone else, they'll probably have an easier time of it. Carl Banks From luke.leighton at googlemail.com Wed Dec 31 16:36:55 2008 From: luke.leighton at googlemail.com (lkcl) Date: Wed, 31 Dec 2008 13:36:55 -0800 (PST) Subject: Creating an application for Linux References: <7d2fe328-064c-46da-9150-7305b6f9e94e@b41g2000pra.googlegroups.com> Message-ID: hiya mike: where do i know you from? i've heard your name somewhere and for the life of me can't remember where! anyway... onwards. your simplest bet is to take advantage of the .deb install system, which, if you follow that, will allow you to pull in all of the dependencies _without_ screwing around with the ubuntu distribution, or requiring that you build "special" versions of the dependencies. so - your first port of call is to locate a similar app to your own one: apt-cache search wxwidgets [rose-tinted filter on the results...] cryptonit - A client side PKI (X.509) cryptographic tool fontypython - A GUI tool to manage ttf fonts jmdlx - jugglemaster deluxe using wxWidgets wxmaxima - a wxWidgets GUI for the computer algebra system maxima multiget - graphical download manager then, do apt-cache show , paying particular attention to the dependencies. apt-cache show fontypython looks like a good candidate. so, do apt-get source fontypython (or other candidate) also do apt-get build-essential dh-make dpkg-dev debutils python-dev devscripts python-setuptools juuust for fun, but the essential ones are probably dh-make and dpkg-dev. then you have something to work from (an example - the source of the deb-wrapped fontypython) and you will have most of the debian developer utils etc. etc. _then_ you go to e.g. oooo this: http://www.pythonmark.com/python-library/debian/howto-build-a-debian-package-from-python-sources/ the preamble for which says "don't bother with that annoying ubuntu python deb howto video, particularly on the basis that who gives a stuff about _verbal_ instructions when you actually want stuff you can READ!" :) the most important thing that _you_ need to remember is that you _must_ identify the correct libraries (and their debian packagenames - can't bring myself to say ubuntu packagenames) and make damn sure that you add them into the dependencies in the debian/control file. do _not_ be tempted to "bundle" customised versions of python- pysqlite, python-sqlalchemy etc. etc. testing: you should really use a debootstrap absolute "basic" environment (set up a chroot, or a virtual KVM or other virtual PC, qemu, whatever, or even a real machine) do NOT do a "full" install of ubuntu, do an absolute minimalist install (netbook, businesscard, whatever). ... and _then_ install your .deb (with dpkg -i) followed by apt-get -f install (to pull in all of the dependencies). then, use export DISPLAY=192.168.1.5:0.0 (adapt as necessary), run xhost + on 192.168.1.5 (adapt as necessary), and _then_ fire up your test app. if you get a python library not found runtime error, you know that you got your dependencies wrong, in the debian/control file. if you install a "vanilla" ubuntu desktop, various other packages will pull in the dependencies for you - and you will never find out if you got all of the dependencies correct. that having been said, if you don't _care_ about correctness, skip the above six sentences :) l. On Dec 31, 9:06 pm, Mike Driscoll wrote: > Hi, > > My boss wants me to port one of my applications to Ubuntu. I > successfully ported it without too many headaches but now I need a way > to distribute it to people that may or may not already have the > dependencies my application requires. I'm a newb with Linux so I'm not > even sure what they call the distribution (rpms, deb, source code). > > After browsing the various "installer" docs out there, it looks like > bbfreeze or PyInstaller might work, but I couldn't find any examples. > Any advice is appreciated. Thanks! > > I am using Python 2.5.2 and this is a wxPython application with > SqlAlchemy and a few other external packages. > > Mike From gagsl-py2 at yahoo.com.ar Wed Dec 10 17:03:22 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 10 Dec 2008 20:03:22 -0200 Subject: Deeper tracebacks? References: Message-ID: En Wed, 10 Dec 2008 16:59:16 -0200, brooklineTom escribi?: > I want my exception handler to report the method that originally > raised an exception, at the deepest level in the call-tree. Let give > an example. That's the default behavior, you don't have to do anything special. > import sys, traceback > class SomeClass: > def error(self): > """Raises an AttributeError exception.""" > int(3).zork() > > def perform_(self, aSelector): > try: > aMethod = getattr(self, aSelector, None) > answer = apply(aMethod, [], {}) > except: AttributeError, anAttributeErrorException: > aRawStack = traceback.extract_stack() > answer = None (I assume you're using Python < 3.0) Use the 3-names form of the except statement: try: aMethod = getattr(self, aSelector, None) answer = aMethod() except AttributeError, e, tb: # the tb variable holds the traceback up to the error # the same thing you see printed by Python when # an unhandled error happens answer = None Alternatively, you can obtain the same thing with sys.exc_info()[2] Remember to delete any reference to the traceback object as soon as you're done with it; see http://docs.python.org/library/sys.html#sys.exc_info -- Gabriel Genellina From clp at rebertia.com Mon Dec 8 01:13:46 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 7 Dec 2008 22:13:46 -0800 Subject: A question about reference in Python. In-Reply-To: References: <493CB003.3080209@gmail.com> Message-ID: <47c890dc0812072213q20cb415fjbd4c80e7af7a7ef5@mail.gmail.com> On Sun, Dec 7, 2008 at 10:09 PM, James Mills wrote: > Hi, > > This is really really really pointless code and a really really pointless > exercise, but nonetheless, here is a very very basic and minimal > implementation of what you're expecting. This should almost > *never* be done in Python! Python is a superior dynamic programming > language, but it's NOT C! > > Here goes: > > jmills at atomant:~/tmp$ ./list.py >>>> x[0] > 0 >>>> x[1] > 1 >>>> x[2] > 2 >>>> x[3] > 3 >>>> x[4] > Traceback (most recent call last): > File "", line 1, in > File "./list.py", line 36, in __getitem__ > return node.value > AttributeError: 'NoneType' object has no attribute 'value' >>>> > jmills at atomant:~/tmp$ > > And the code: > > #!/home/jmills/bin/python -i > > class Node(object): > The following three lines serve no purpose and can only lead to confusion: > value = None > prev = None > next = None > > def __init__(self, value, prev=None, next=None): > self.value = value > self.prev = prev > self.next = next > > class List(object): > Same with the following line. Why do you have these? Python does *not* have the concept of instance variable declaration. You are creating *class variables*, which is almost certainly not what you want. > data = None > Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > def __init__(self, *seq): > if seq: > first = prev = node = None > for x in seq: > if not first: > first = Node(x) > prev = node = first > else: > node = Node(x, prev) > prev.next = node > prev = node > > self.data = first > > def __getitem__(self, x): > node = self.data > for i in xrange(x): > node = node.next > return node.value > > x = List(0, 1, 2, 3) > > > Notes: > > I have not implemented any error checking whatsoever. > I have not implemented any of your normal list > operations whatsoever (except 1). __getitem__. > > Have fun, > > cheers > James > > On Mon, Dec 8, 2008 at 3:26 PM, Group wrote: >> Hello, I'm studying algorithom. For concentrating on the question itself, I >> intend to use Python to implement the algorithoms. >> >> Now, I want to write a Red-Black Tree, and a List structure. In C/C++, I can >> use pointers to refer to children notes (or next notes). But, in Python, >> how >> can I do it? Except the sequence, I know not any way. >> >> You'd better help me understan how can I transform the following C code into >> Python: >> >> /* a List */ >> struct { >> int data; >> int *next; >> int *prev; >> } >> >> That's all. Thanks! >> Kermit >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > > -- > -- > -- "Problems are solved by method" > -- > http://mail.python.org/mailman/listinfo/python-list > From prologic at shortcircuit.net.au Wed Dec 31 01:17:01 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 16:17:01 +1000 Subject: MemoryError when list append... plz help In-Reply-To: <21227745.post@talk.nabble.com> References: <21227745.post@talk.nabble.com> Message-ID: (Sorry for top posting): You are mad! Why on God's earth would you want to create a list containing 60 MILLION elements ? What is the use case ? What are you solving ? You may have 4G of ram, but I very seriously doubt you have 4G of ram available to Python. I have no idea how many bytes of memory storing each element of a list consumes let alone each float object, but I assure you it's not going to be anywhere near that of 60494500 4-bytes spaces (do floats in C normally consume 4 bytes) in C. --JamesMills -- -- "Problems are solved by method" On Wed, Dec 31, 2008 at 4:02 PM, [BON] wrote: > > ====================== > s=[] > for i in range(11000-1): > for j in range(i+1, 11000): > .... > s.append(((i,j),sim)) > ====================== > above sim is floating type. > s.append is totally coducted 60,494,500 times. > but this code raise MemoryError. > > My computer has 4G RAM. > i think it's enough. but it doesn't... > > So, i've tested below code. > ====================== > a=[] > i=0 > while i<60494500 : > a.append(i) > i+=1 > ====================== > but this code raise also MemoryError. > > How can i resolve this problem? > please, help... > > Regards, > -- > View this message in context: http://www.nabble.com/MemoryError-when-list-append...-plz-help-tp21227745p21227745.html > Sent from the Python - python-list mailing list archive at Nabble.com. > > -- > http://mail.python.org/mailman/listinfo/python-list > From jstroud at mbi.ucla.edu Sat Dec 13 22:28:57 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 13 Dec 2008 19:28:57 -0800 Subject: Need help improving number guessing game In-Reply-To: References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> Message-ID: James Stroud wrote: > Be assured that it takes on special intelligence to write unintelligible I meant "*no* special intelligence". From castironpi at gmail.com Tue Dec 16 04:29:19 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 16 Dec 2008 01:29:19 -0800 (PST) Subject: subprocess.Popen inheriting Message-ID: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> Hi, I have a file handle I want to inherit in a child process. I am looking at '_make_inheritable' in 'Popen', but it needs an instance, and by the time I have one, the subprocess is already running. Can't I call 'Popen._make_inheritable( None, handle )'? The method does not use 'self'. From robert.kern at gmail.com Sun Dec 28 00:12:27 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 28 Dec 2008 00:12:27 -0500 Subject: assignment with [:] In-Reply-To: References: Message-ID: Ben Bush wrote: > Hi, > > I saw this line of code on a recent post: > > a1[:] = [x*3 for x in a1] > > Could somebody tells me what the [:] means? I can't find it anywhere. It's a slice assignment. When both the start and stop arguments are omitted, it refers to the entire sequence. In this case, it means to replace the entire contents of the list a1 with the value on the right-hand-side. "a[2:4] = ..." would replace the 3rd and 4th items in the list with the sequence on the right-hand-side, for instance. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From mail at johnohagan.com Mon Dec 1 00:28:14 2008 From: mail at johnohagan.com (John O'Hagan) Date: Mon, 1 Dec 2008 05:28:14 +0000 Subject: Confused about class relationships In-Reply-To: References: Message-ID: <200812010528.14528.mail@johnohagan.com> On Sat, 29 Nov 2008, Carl Banks wrote: > On Nov 26, 11:20?pm, John O'Hagan wrote: [...] > > > > class Bar(list): > > > > ? ? ? ? def __init__(self, a_bar, args, engine): > > ? ? ? ? ? ? ? ? list.__init__ (self, a_bar) > > ? ? ? ? ? ? ? ? self[:] = a_bar ? ? ? ? > > ? ? ? ? ? ? ? ? self.args = args > > ? ? ? ? ? ? ? ? self.engine = engine > > ? ? ? ? ? ? ? ? #more instance attributes... > > > > ? ? ? ? #methods... > > > > class Engine: > > > > ? ? ? ? def __init__(self, args): > > ? ? ? ? ? ? ? ? self.args = args ? ? ? ? ? ? ? ? ? ? ? ? > > ? ? ? ? ? ? ? ? #more instance attributes... > > > > ? ? ? ? def bar_builder(self): > > ? ? ? ? ? ? ? ? #body of method generates lists... > > ? ? ? ? ? ? ? ? yield Bar([generated_list], args, self) > > > > ? ? ? ? #more methods... > > > > #(other stuff...) > > > > def main(args): > > > > ? ? ? ? ? ? engine = Engine(args) > > ? ? ? ? ? ? bars = engine.bar_builder() > > ? ? ? ? ? ? for a_bar in bars: > > ? ? ? ? ? ? ? ? #play the music!... > > > > While this works (to my surprise!) and solves the problem which motivated > > it (i.e. Engine instances need to pass some attributes to Bar instances > > ), it seems too convoluted. Should one class inherit the other? > > No. (I wonder if you meant, "Should one class reference the other?", > as in, "Should Engines only reference bars or Bars only reference > engines, but not both?", in which case the answer is a non-commital, > "It depends.") > > Inheritance is not something you do because object A wants to access > the attributes/properties/etc. of B. Actually, that is something that > happens pretty often and when it does, there's a couple things you > should think about: > > 1. How you want A to access the attributes of B. Should you just let > A poke around in B, or should you define methods of B for A to call, > and those methods access the internals of B? It's a judgment call > most of the time. > > 2. Whether some behavior of B ought to be defined as part of A's class > instead, or vice versa. There is sometimes ambiguity over what class > a method that uses the attributes of two different objects should > belong to. > > Inheritance isn't something you need to think about here. > > Inheritance is something you consider when you have two objects, A and > B, that should act very similar or the same in certain situations. > Engines and Bars don't seem to share any behavior at all. Contrast > this to Bars and lists, which do share behavior. x[1] does pretty > much the same thing whether x is a Bar or a list, I'd imagine, so > there's reason for an inheritance relationship there. > > > If so, which way > > around? Or is it fine as is? > > One thing you might want to consider is whether Engine instance could > be simply passed into the Bar's play method (or whatever other method > accesses the Engine attributes), and whether the Engine needs to be > involved in generating bars at all. For instance: > > > class Bar(list): > def __init__(self, a_bar, args): > list.__init__(self, a_bar) > self[:] = a_bar > self.args = args > # etc. > def play(self, engine): > use(engine.time_signature).somehow() > # instead of use(self.engine.time_signature).somehow() > > > def bar_builder(self,args): > # plain function, not part of Engine class > # or perhaps a method of some other class > yield Bar([generated_list],args) > > > def main(): > engine = Engine(args) > bars = bar_builder(self,args) > for a_bar in bars: > a_bar.play(engine) > > > One benefit of doing it this way is that you've freed Bars and Engines > from each other. Conceivably you could create a second engine object > (maybe of a different type altogether), and play the very same Bar > objects with that engine instead. Thanks for such a detailed reply...I actually had bar_builder as a plain function originally, but because I didn't know how to pass attributes around like you have above, I was using globals to do it and was trying to solve that by classing everything in sight. Although the program doesn't work quite as you have deduced above, I can use the approach you suggest to simplify it immensely. (I hope.) > > > I'm hoping this is a common trap I've fallen into; I just haven't been > > able to get my head around it. (I'm a musician...) > > Well I think it looks pretty good for a musician newbie. There's a > few organizational decisions I'd make differently, but overall it's > clean and readable and not too complicated how you did it. At least > not what you've showed us. :) > [...] Believe me, the whole thing is more complicated and messy, but you don't want to see my dirty laundry! :) Regards, john From cjw at ncf.ca Fri Dec 19 19:33:20 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Fri, 19 Dec 2008 19:33:20 -0500 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <494bd4e6$0$31863$9b4e6d93@newsspool3.arcor-online.net> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> <494bd4e6$0$31863$9b4e6d93@newsspool3.arcor-online.net> Message-ID: Stefan Behnel wrote: > Thomas Heller wrote: >> Mark Summerfield schrieb: >>> Just a follow-up to say that the book has now been published in the >>> U.S. >>> It is now in stock at InformIT, and should reach other stores, e.g., >>> Amazon, in a week or so. >>> >>> Also, the introduction, the first few pages of the first chapter, the >>> whole of chapter 12 (regular expressions), and the index are now >>> available for free download in a PDF from here: >>> http://www.informit.com/store/product.aspx?isbn=0137129297 >> Question from a non-native english speaker: is this now valid english? >> >> "One of Python???s great strengths" >> ^ >> "and also teaches Python???s functional programming features" >> ^ >> "The book???s approach is wholly practical" >> ^ > > 'Always' has been. It's not valid German, though, if that's what you are > asking. > > Stefan It wasn't the question. Colin W. From steve at holdenweb.com Sun Dec 14 13:00:07 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 14 Dec 2008 13:00:07 -0500 Subject: Looking for the best way to translate an idiom In-Reply-To: <4945406a$0$1127$426a74cc@news.free.fr> References: <4945406a$0$1127$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: [...] > if you only want the first returned value, you can just apply a slice: > > def f(): > return 1,2,3 > > a = f()[0] + 1 > That isn't a slice, it's indexing regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From thmpsn.m.k at gmail.com Mon Dec 29 20:22:08 2008 From: thmpsn.m.k at gmail.com (thmpsn.m.k at gmail.com) Date: Mon, 29 Dec 2008 17:22:08 -0800 (PST) Subject: Python in C Message-ID: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> I've just downloaded Python's mainstream implementation (CPython), which is written in C. Not to my surprise, I feel like I'm looking at unstructured spaghetti, and I'm having trouble figuring out how it all works together. (Please bear with me; I'm just going through the usual frustration that anyone goes through when trying to see the organization of a C program :) So, I have two queries: 1. Can anyone explain to me what kind of program structuring technique (which paradigm, etc) CPython uses? How do modules interact together? What conventions does it use? 2. Have there been any suggestions in the past to rewrite Python's mainstream implementation in C++ (or why wasn't it done this way from the beginning)? From martin at v.loewis.de Sat Dec 13 04:38:35 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 13 Dec 2008 10:38:35 +0100 Subject: Umlauts in idle In-Reply-To: <26880ecf-d0eb-42ab-8ebd-56f64c023999@v39g2000pro.googlegroups.com> References: <26880ecf-d0eb-42ab-8ebd-56f64c023999@v39g2000pro.googlegroups.com> Message-ID: <4943829B.9050606@v.loewis.de> > When I try to use umlauts in idle it will only print out as Unicode > escape characters. Is it possible to configure idle to print them as > ordinary characters? Did you really use the print statement? They print out fine for me. Regards, Martin From sjmachin at lexicon.net Fri Dec 5 18:14:39 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 5 Dec 2008 15:14:39 -0800 (PST) Subject: Find Files in a Folder Between 2 Dates References: <4c54b6c5-ae4d-4b89-8c6d-940c96de29bb@n33g2000pri.googlegroups.com> <94cd4bd7-a69f-48ba-90f7-382014844905@g1g2000pra.googlegroups.com> Message-ID: <862567e3-4469-43ae-b41b-1a1817124f50@k36g2000pri.googlegroups.com> On Dec 6, 9:41?am, Gregory Plantaine wrote: > That worked perfectly! > > Thanks Tim! > > Since we can print the files, does that mean the list of files is in a > tuple, or something? ?Would there be a way to further split up the > file names? > > For example, now that the files are processed into the list, we want > to look through that list to find different filetypes. > > files > > C:\Folder\File_200812051439.111 > C:\Folder\File_200812051539.222 *DANGER* It looks like you are interested in the timestamps that are embedded in the names of the files. Tim's code assumes [reasonably given that your problem description was ambiguous and had no examples of good and bad results] that you are interested in the last modification time of the file. You may say "same thing". Yes, same thing, until somebody sucks a file into a text editor, messes with it, and saves it again. No, Murphy's Law has not been repealed. > > Can we split up .111 files? > > Actually, where would I look something like this up? In the Library Reference Manual ... there are all sorts of goodies in the os and os.path modules e.g. like those used by Tim; make sure you read the docs on the methods Tim used so that you understand what's happening. HTH, John From rsarpi at gmail.com Wed Dec 10 19:37:25 2008 From: rsarpi at gmail.com (icarus) Date: Wed, 10 Dec 2008 16:37:25 -0800 (PST) Subject: broken ncurses on python 3.0 Message-ID: OS: win32, python 3.0 I've been trying to run some curses demos and I get this: C:\Python\Lib\curses>python textpad.py Traceback (most recent call last): File "textpad.py", line 3, in import curses File "C:\Python\lib\curses\__init__.py", line 15, in from _curses import * ImportError: No module named _curses The C:\Python\include does not have the curses.h header. Reinstalling from the x86 msi binary doesn't do it. Any ideas on how to get this working? maybe it's just the w32 version that missed ncurses From sambasivareddy.s at patni.com Wed Dec 3 05:51:40 2008 From: sambasivareddy.s at patni.com (sambasivareddy) Date: Wed, 3 Dec 2008 16:21:40 +0530 Subject: How to write a string with required color in a file with python.net? Message-ID: <011501c95535$20b302c0$750ba8c0@patni.com> Hi all, I have couple of double on python futures .Quires listed below: * How to write a particular string with required/selected color in a file with python.net? Which module I need to use it? How to set color for particular string in file? --------------------------------- file=open("C:\\test\\TestResult.txt","w") file.writelines("testcase1 pass \n") file.writelines("testcase2 Faile \n") file.close() ----------------------------- I want output like this in file: testcase1 pass testcase2 Faile * How to create .exe file in python.net? I have tried with py2exe module but it is not supporting with python.net if anyone have any information or code on the same queries plz send it. thanks in advance. Regards, sambu _____________________________________________________________________ This e-mail message may contain proprietary, confidential or legally privileged information for the sole use of the person or entity to whom this message was originally addressed. Any review, e-transmission dissemination or other use of or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you have received this e-mail in error kindly delete this e-mail from your records. If it appears that this mail has been forwarded to you without proper authority, please notify us immediately at netadmin at patni.com and delete this mail. _____________________________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: From pyth0nc0d3r at gmail.com Mon Dec 15 08:36:47 2008 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Mon, 15 Dec 2008 07:36:47 -0600 Subject: Having Issues with CMD and the 'python' command In-Reply-To: References: Message-ID: It was python3 messing me up. I forgot I had python 3 on my box uninstalled it, redid it and wallah. On Mon, Dec 15, 2008 at 7:33 AM, wrote: > On Mon, 15 Dec 2008 at 07:16, Lamonte Harris wrote: > >> Yeah I tried doing it from the environment variables yet it still fails to >> work. >> > > Well, I can't be of any more help, then. It worked for me on my XP Home > box, and at this point we've exhausted my knowledge of windows :) > > --RDM > -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at marcher.name Fri Dec 26 11:31:47 2008 From: martin at marcher.name (Martin) Date: Fri, 26 Dec 2008 17:31:47 +0100 Subject: sys.stdout.write()'s bug or doc bug? In-Reply-To: References: Message-ID: <5fa6c12e0812260831y23cce99w7d8624429cee2199@mail.gmail.com> Sorry GMAIL got me again, I sent this in private first, apologies. hi, 2008/12/26 Qiangning Hong : >>>> sys.stdout.write(u) > Traceback (most recent call last): > File "", line 1, in > UnicodeEncodeError: 'ascii' codec can't encode character u'\u554a' in > position 0: ordinal not in range(128) >>>> type(sys.stdout) > >>>> sys.stdout.encoding > 'UTF-8' Python 2.4.4 (#2, Oct 22 2008, 19:52:44) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> u = u"\u554a" >>> print u ? >>> sys.stdout.write(u + "\n") Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\u554a' in position 0: ordinal not in range(128) >>> # you are trying to write unicode, you need to encode it to something that suits your needs >>> sys.stdout.write(u.encode("UTF-8") + "\n") ? >>> # now go and write a hundred times "Unicode is not an encoding" :) > So, my question is, as sys.stdout IS a file object, why it does not > use its encoding attribute to convert the given unicode? An > implementation bug? A documenation bug? hmm I always thought "sys.stdout" is a "file-like object" not that it IS a file. /martin -- http://soup.alt.delete.co.at http://www.xing.com/profile/Martin_Marcher http://www.linkedin.com/in/martinmarcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From steve at holdenweb.com Mon Dec 22 20:38:43 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 22 Dec 2008 20:38:43 -0500 Subject: Python's popularity In-Reply-To: <48221004-94ce-4b2a-b94a-1ca45a2562b8@j11g2000yqg.googlegroups.com> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <6ra8t0F925rU1@mid.individual.net> <29feda0d-6432-4cb9-8809-e4d4a7798601@e1g2000pra.googlegroups.com> <6raeb8F9s47U2@mid.individual.net> <6rahpaFav7kU2@mid.individual.net> <97e49a8c-6730-42f2-b4d0-35eaff38b69f@y1g2000pra.googlegroups.com> <48221004-94ce-4b2a-b94a-1ca45a2562b8@j11g2000yqg.googlegroups.com> Message-ID: r wrote: > [Jeff] > but I raise the bar so that any random joker probably won't bother > (and making the reverse mapping - knowing my real identity and then > looking for recent net activity - is much more difficult to do) > [/Jeff] > > You are the epitimy of an internet troll. A troll tries to hide his > identity. Why are you so concerned about your TRUE identity. Are the > FEDS after you, maybe it's the Martians i do not know? Did they take > into their spaceship and do things to you? Do you wear a aluminum foil > hat. Look out for those cell towers, there mind control devices > hahaha. Thanks for the good laugh. Pot, meet kettle. Kettle: pot. -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From castironpi at gmail.com Wed Dec 10 02:21:54 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 9 Dec 2008 23:21:54 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> <014eee6d$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Dec 9, 4:53?pm, Steven D'Aprano wrote: > On Tue, 09 Dec 2008 08:30:26 -0800, Aaron Brady wrote: > > The following are semantically equivalent: > > > I certainly wouldn't want something like PL/I, where "IF", "THEN" and > > "ELSE" could be identifiers. > > > I wouldn't want something like PL/I, where "IF", "THEN" and "ELSE" could > > be identifiers. > > "Certainly" adds emphasis. You don't just mildly not want something like > PL/I, but you really don't want it, so much so that you're amazed that > anyone might have thought you did. I see. He was expressing amazement too. This is distinct from a similar case, "-1 on including it, but it has some advantages, and could be useful for other purposes." He thinks it's a bad idea all around, not just ill-suited to Python. > The English language is very un-Pythonic. It especially breaks "Explicit > is better than implicit" -- words have many implied connotations which > are not necessarily found in dictionaries. For example, a "wise guy" and > a "wise man" are not the same thing, even though a guy and a man are the > same. I can't attest to many other languages, but the same might hold true. It's the speakers, not the language. English also breaks 'Errors should never pass silently', though more so in large "I have the conch" gatherings, and less so in smaller numbers. If I end up at the wrong restaurant for dinner, that's the equivalent (analogue) of reading from uninitialized memory, or other silently passed errors. 'Special cases aren't special enough to break the rules.' Italian breaks this one--- 700 irregular verbs! But the Esperanto community is growing... heh heh. English spelling is bad too: "if 'i' before 'e' and not after 'c': ...' It's not a fair fight though, between English and Python. There's no 'final say', that is, unifying vision, about what's legal in English. People will just talk. If everyone drops their articles tomorrow, English no longer has them. Perhaps you could compare Python to an audience to English with only one member. I guess I take 'complex' and 'nested' to be about the same. Back to topic, the 'eth' sound might be ugly to some humans. But that doesn't mean it's ugly to English speakers, let alone useless. I guess some people think the disjunction of 'useful' and 'ugly' is nearly empty. I think one of the things the Zen has going for it is its authors were (are) programmers-- they taste their own medicine. In naturally occurring large religions, the priests aren't peasants very often... though sometimes the prophets are. You could compare the Zen to 'folk wisdom' per se, rather than a religion (though the latter proclaims itself the former too often). Just because you defer to something, doesn't mean it's a religion. But if the content has drifted so far that Peters and van Rossum no longer follow it, it's a bad sign. From badmuthahubbard at usenet.cnntp.org Fri Dec 19 03:46:00 2008 From: badmuthahubbard at usenet.cnntp.org (Bad Mutha Hubbard) Date: 19 Dec 2008 08:46:00 GMT Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> Message-ID: <494b5f47$0$17068$6e1ede2f@read.cnntp.org> Roger wrote: > I've done a lot of googling for this topic and I fear that it's not > possible. I have a widget that is overloaded with several bindings. > I want to be able to unbind one method form the same Event without > destroying all the other bindings to the same event that's associated > to the same widget. > > For example: > > import Tkinter > > def test(): > print 'test' > > def test2(): > print 'test2' > > root = Tkinter.Tk() > funcid1 = root.bind("<1>", lambda e: test()) > funcid2 = root.bind("<1>", lambda e: test2(), add='+') > root.unbind("<1>", funcid2) > root.mainloop() > > When run neither <1> binding will exist against the root because the > unbind will unbind all the functions associated with that event. > However, in this example, I only want to unbind test2 not test1. > > Any help is greatly appreciated. Thanks! > Roger. I believe you've discovered a bug. Aside from recommending trying wxWidgets, here's the source of the unbind function in Tkinter.py: def unbind(self, sequence, funcid=None): """Unbind for this widget for event SEQUENCE the function identified with FUNCID.""" self.tk.call('bind', self._w, sequence, '') if funcid: self.deletecommand(funcid) ------------------------------------------- First, it replaces all bindings for the sequence with the empty string, i.e., it deletes all bindings for that event unconditionally. THEN it calls deletecommand() with the funcid, who knows what that does. My Tcl is not so sharp. I have an idea for a workaround, let me see if it works... -Chuckk From gneuner2 at comcast.net Fri Dec 12 14:47:17 2008 From: gneuner2 at comcast.net (George Neuner) Date: Fri, 12 Dec 2008 14:47:17 -0500 Subject: Mathematica 7 compares to other languages References: <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> <8evqj4p342jvcma5saibf54thv7075r88g@4ax.com> <9d5ecca4-3eb8-42ad-b4d8-951719ef874b@n33g2000pri.googlegroups.com> Message-ID: On Mon, 8 Dec 2008 15:14:18 -0800 (PST), Xah Lee wrote: >Dear George Neuner, > >Xah Lee wrote: >> >For example, >> >the level or power of lang can be roughly order as >> >this: >> >> >assembly langs >> >C, pascal >> >C++, java, c# >> >unix shells >> >perl, python, ruby, php >> >lisp >> >Mathematica > >George wrote: >> According to what "power" estimation? Assembly, C/C++, C#, Pascal, >> Java, Python, Ruby and Lisp are all Turing Complete. I don't know >> offhand whether Mathematica is also TC, but if it is then it is at >> most equally powerful. > >it's amazing that every tech geekers (aka idiots) want to quote >?Turing Complete? in every chance. Even a simple cellular automata, >such as Conway's game of life or rule 110, are complete. > >http://en.wikipedia.org/wiki/Conway's_Game_of_Life >http://en.wikipedia.org/wiki/Rule_110 > >in fact, according to Stephen Wolfram's controversial thesis by the >name of ?Principle of computational equivalence?, every goddamn thing >in nature is just about turing complete. (just imagine, when you take >a piss, the stream of yellow fluid is actually doing turning complete >computations!) Wolfram's thesis does not make the case that everything is somehow doing computation. >for a change, it'd be far more interesting and effective knowledge >showoff to cite langs that are not so-called fuck of the turing >complete. We geek idiots cite Turing because it is an important measure of a language. There are plenty of languages which are not complete. That you completely disregard a fundamental truth of computing is disturbing. >the rest of you message went on stupidly on the turing complete point >of view on language's power, mixed with lisp fanaticism, and personal >gribes about merits and applicability assembly vs higher level langs. You don't seem to understand the difference between leverage and power and that disturbs all the geeks here who do. We worry that newbies might actually listen to your ridiculous ramblings and be led away from the truth. >It's fine to go on with your gribes, but be careful in using me as a >stepping stone. Xah, if I wanted to step on you I would do it with combat boots. You should be thankful that you live 3000 miles away and I don't care enough about your petty name calling to come looking for you. If you insult people in person like you do on usenet then I'm amazed that you've lived this long. George From saluk64007 at gmail.com Wed Dec 10 16:16:54 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Wed, 10 Dec 2008 13:16:54 -0800 Subject: "as" keyword woes In-Reply-To: References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> <493FD8F6.3050803@mrabarnett.plus.com> Message-ID: On Wed, Dec 10, 2008 at 11:57 AM, Benjamin Kaplan wrote: > > > On Wed, Dec 10, 2008 at 12:22 PM, Patrick Mullen > wrote: >> >> I don't have a huge stake in this, but I wouldn't mind a change to >> allow anything proceeding a "." or preceeding a "(" to not be >> identified as a keyword. It is obvious to me a s a human reader that >> something.if is quite a bit different than just a bare if. And as far >> as parsing technology goes, isn't it supposed to go for the biggest >> match first? I would not be for allowing bare keywords to be used in >> the situations described above, but since we are so used to being able >> to being able to have say, myclass.dir() or myclass.len() without them >> overwriting the builtin functions, it makes sense to me to be able to >> define a myclass.as() or myclass.with() without overwriting the >> keywords. Though I know the semantics behind these two things are >> very different, the rules I go through when reading the code are very >> similar. The parser change might be a hassle, and it might not be >> worth it at all of course, but from a conceptual point of view it is >> simple. I mean, even now you can do class.__dict__["as"]. > > so what happens here? > > if(some_condition()) : > do_something(a) > > Yes, I know you don't need the parenthesis there in Python, but you still > can use it. > >> >> I guess I'm -1 for full PL/1 craziness, but +1 for qualified keyword >> usage. >> -- >> http://mail.python.org/mailman/listinfo/python-list > > Right, I now see how this scenario is tricky. It could maybe be in the form of " " but that starts getting pretty complicated. Too tricky. Following the period on the other hand still makes sense to me. It makes sense in the nature of "I wouldn't mind seeing this added", but I suppose it still might not make sense in the nature of "We should do the work to make this a reality". From walterbyrd at iname.com Mon Dec 22 10:11:02 2008 From: walterbyrd at iname.com (walterbyrd) Date: Mon, 22 Dec 2008 07:11:02 -0800 (PST) Subject: Python's popularity Message-ID: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> I have read that python is the world's 3rd most popular language, and that python has surpassed perl in popularity, but I am not seeing it. >From what I have seen: - in unix/linux sysadmin, perl is far more popular than python, windows sysadmins typically don't use either. - in web-development, php is far more popular than python - it's not even close. - when I did a search on dice, I found over 20X more jobs advertised for ruby on rails developers, than for python dango developers. - application development is dominated by java, c/c++, and maybe a little visual basic. - as I understand it, fortran is still the most popular language for numberical programming. Of course, these are just observations on my part, nothing scientific about it. But, I can't help but wonder how python's popularity was determined. I suspect that a lot of people use python as a secondary skill. For example, I use ms-word, but I'm not an ms-word professional. Please note: I am not confusing popularity with quality. I am not saying that php is better for web-dev, or anything like that. I am just wondering how python is rated as being so popular, when python does not seem to dominate anything. From atagar1 at gmail.com Tue Dec 30 19:04:28 2008 From: atagar1 at gmail.com (Damian Johnson) Date: Tue, 30 Dec 2008 16:04:28 -0800 Subject: Python 3.0 Curses Unicode In-Reply-To: References: Message-ID: Just resolved the issue (turned out to be an issue with linked ncurses libraries). If others run into this discussion of the solution can be found at: http://bugs.python.org/issue4787 Cheers! -Damian On Mon, Dec 29, 2008 at 10:30 PM, Damian Johnson wrote: > It seems as if the curses module in Python 3.0 isn't respecting the > system's preferred encoding (utf-8) which was set via: > locale.setlocale(locale.LC_ALL, '') > > The purpose of this was described at the top of ' > http://docs.python.org/dev/3.0/library/curses.html#module-curses'. The > getlocale function is reporting the proper values ('en_US', 'UTF8') but > addstr is clearly not treating it as Unicode - is this a bug? -Damian > > 2008/12/28 Damian Johnson > > Hi, I've switched to Python 3.0 for a new Japanese vocab quizzing >> application due to its much improved Unicode support. However, I'm running >> into an issue with displaying Unicode characters via curses. In Python 2.x a >> simple hello-world looks like: >> >> #!/usr/bin/python >> # coding=UTF-8 >> >> import curses >> import locale >> >> locale.setlocale(locale.LC_ALL,"") >> >> def doStuff(stdscr): >> message = u"hello ???!" >> stdscr.addstr(0, 0, message.encode("utf-8"), curses.A_BLINK) >> stdscr.getch() # pauses until a key's hit >> >> curses.wrapper(doStuff) >> >> This works. However, when I try to come up with an equivalent for Python >> 3.0: >> >> #!/usr/bin/python >> >> import curses >> import locale >> >> locale.setlocale(locale.LC_ALL,"") >> >> def doStuff(stdscr): >> message = "hello ???!" >> stdscr.addstr(0, 0, message, curses.A_BLINK) >> stdscr.getch() # pauses until a key's hit >> >> curses.wrapper(doStuff) >> >> It fails (printing gibberish to the console). Anyone have a clue what I'm >> doing wrong? Thanks! -Damian >> >> PS. Is the "# coding=UTF-8" header meaningless in Python 3.0? Also, is >> "locale.setlocale(locale.LC_ALL,"")" still necessary for getting curses to >> provide Unicode support? >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jimsgibson at gmail.com Thu Dec 11 15:11:06 2008 From: jimsgibson at gmail.com (Jim Gibson) Date: Thu, 11 Dec 2008 12:11:06 -0800 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <5ebe5a7d-cbdf-4d66-a816-a7d2a0a273c9@40g2000prx.googlegroups.com> Message-ID: <111220081211063566%jimsgibson@gmail.com> In article <5ebe5a7d-cbdf-4d66-a816-a7d2a0a273c9 at 40g2000prx.googlegroups.com>, Xah Lee wrote: > On Dec 10, 2:47?pm, John W Kennedy wrote: > > Xah Lee wrote: > > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, > > > you'll have 50 or hundreds lines. > > > > C: > > > > #include > > #include > > > > void normal(int dim, float* x, float* a) { > > ? ? float sum = 0.0f; > > ? ? int i; > > ? ? float divisor; > > ? ? for (i = 0; i < dim; ++i) sum += x[i] * x[i]; > > ? ? divisor = sqrt(sum); > > ? ? for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; > > > > } > > > > Java: > > > > static float[] normal(final float[] x) { > > ? ? float sum = 0.0f; > > ? ? for (int i = 0; i < x.length; ++i) sum += x[i] * x[i]; > > ? ? final float divisor = (float) Math.sqrt(sum); > > ? ? float[] a = new float[x.length]; > > ? ? for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor; > > ? ? return a; > > > > } > > Thanks to various replies. > > I've now gather code solutions in ruby, python, C, Java, here: > > ? A Example of Mathematica's Expressiveness > http://xahlee.org/UnixResource_dir/writ/Mathematica_expressiveness.html > > now lacking is perl, elisp, which i can do well in a condensed way. > It'd be interesting also to have javascript... and perhaps erlang, > OCaml/F#, Haskell too. Perl: sub normal { my $sum = 0; $sum += $_ ** 2 for @_; my $length = sqrt($sum); return map { $_/$length } @_; } -- Jim Gibson From lolekk122333 at wp.pl Fri Dec 5 16:38:14 2008 From: lolekk122333 at wp.pl (girl18bebes) Date: Fri, 5 Dec 2008 13:38:14 -0800 (PST) Subject: +18! Hot girl sexy girl woman dance for mature older man! big boobs, hot ass, big booty tits breast, Hot sexy young girl woman, hot woman, sexy wo, sexy cougar babes, teens, bikini, virginman Message-ID: <45eca54f-90c4-47a8-9f30-8427c48bb3d8@y18g2000yqn.googlegroups.com> http://yeba.pl/show/movies/5257/Perfect_babe_-_Idealna_kobieta From robert.kern at gmail.com Thu Dec 4 14:34:14 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 04 Dec 2008 13:34:14 -0600 Subject: Python Dynamic Profiling In-Reply-To: References: Message-ID: esgameserver at gmail.com wrote: > Hi, > > Sorry for re-posting but I want to clarify my question again here. > > So, we have a multithreaded server application and I want to see the > profile of our code means which function is executed how many times > and time spent in that function dynamically. With dynamic, I mean > without stopping the profiled thread. > > Is there any way to do that, other than hacking my own code with hooks > and calculating the info above by hand? > > P.S:cProfile and Profile modules are very good indeed, but as far as I > understand you need to stop the profiler and the associated thread to > see the profile results. That is unacceptable for my situation. Don't use the run*() methods. Instead, use enable() and disable(). This means that the profiler isn't the thing calling your code. You can stop it and collect the profile information without halting your code. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From steve at REMOVE-THIS-cybersource.com.au Sun Dec 28 14:35:02 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Dec 2008 19:35:02 GMT Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> Message-ID: <0167cbf7$0$6988$c3e8da3@news.astraweb.com> On Sun, 28 Dec 2008 12:38:50 -0500, Steve Holden wrote: > Roger wrote: >> Hi Everyone, >> >> First I want to thank everyone that posts to this group. I read it >> daily and always learn something new even if I never feel like I have >> anything to contribute but my questions. >> >> When I define a method I always include a return statement out of habit >> even if I don't return anything explicitly: >> >> def something(): >> # do something >> return >> >> Is this pythonic or excessive? Is this an unnecessary affectation that >> only adds clock ticks to my app and would I be better off removing >> "returns" where nothing is returned or is it common practice to have >> returns. >> > It's an unnecessary affectation, but I don't believe it adds any clock > ticks to your app, as the function has to return anyway. The dis module > shows you they both generate exactly the same code: ... >> Even when I'm not explicitly returning something I like to add "return" >> because it's a good additional visual marker for me to see where a >> method definition ends especially in cases where I may use a nested >> method. >> > Well, I suppose at least you aren't writing "return None" ... Normally a > blank line or two suffices for me. Curious. When I see a bare return, the first thing I think is that the author forgot to include the return value and that it's a bug. The second thing I think is that maybe the function is a generator, and so I look for a yield. If I don't see a yield, I go back to thinking they've left out the return value, and have to spend time trying to understand the function in order to determine whether that is the case or not. In other words, even though it is perfectly valid Python, bare returns always make the intent of the function less clear for me. I'm with Bruno -- if you have a function with early exits, and you need to make the intent of the function clear, explicitly return None. Otherwise, leave it out altogether. -- Steven From google at mrabarnett.plus.com Thu Dec 25 19:46:54 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 26 Dec 2008 00:46:54 +0000 Subject: Mathematica 7 compares to other languages In-Reply-To: <8j78l4drqjg46ps74up555bfu44kct27f7@4ax.com> References: <49404775$0$4893$607ed4bc@cv.net> <452ba58b-9377-4463-85e2-5ecdaa25a129@t39g2000prh.googlegroups.com> <6375k4pf1mleb6im67nkpec5olqbsom88e@4ax.com> <8j78l4drqjg46ps74up555bfu44kct27f7@4ax.com> Message-ID: <4954297E.7090700@mrabarnett.plus.com> sln at netherlands.com wrote: > On Thu, 25 Dec 2008 21:50:29 +0000, Jon Harrop wrote: > >> Xah Lee wrote: >>>>> On Dec 10, 2:47 pm, John W Kennedy wrote: >>>>>> C: >>>>>> #include >>>>>> #include >>>>>> void normal(int dim, float* x, float* a) { >>>>>> float sum = 0.0f; >>>>>> int i; >>>>>> float divisor; >>>>>> for (i = 0; i < dim; ++i) sum += x[i] * x[i]; >>>>>> divisor = sqrt(sum); >>>>>> for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; >>>>>> } >>> Due to the low level of C, this C example should perhaps then accept a >>> sequence of numbers separated by space... >> In other words, you want a REPL. >> >> Why don't we have another challenge that involves handling a non-trivial >> input format, i.e. parsing? > > Maybe you could speed it up. > > sln > > ---------------------------------- > void normal (int Dimension, double *X, double *A) > { > double *xp, *ap, divisor, sum; > int i; > > for ( i=0, sum=0., xp=X; i sum += (*xp) ** 2; C doesn't have a "**" operator. > divisor = sqrt ( sum ); > for ( i=0, ap=A, xp=X; i *ap = *xp / divisor; > > // if Dimension is greater than > // sizeof double X[] or double A[] it will GPF. > // this is a really, really bad design. > } From roy at panix.com Mon Dec 29 10:32:55 2008 From: roy at panix.com (Roy Smith) Date: Mon, 29 Dec 2008 10:32:55 -0500 Subject: multiprocessing vs thread performance References: Message-ID: In article , Christian Heimes wrote: > You have missed an important point. A well designed application does > neither create so many threads nor processes. The creation of a thread > or forking of a process is an expensive operation. You should use a pool > of threads or processes. It's worth noting that forking a new process is usually a much more expensive operation than creating a thread. Not that I would want to create 100,000 of either! Not everybody realizes it, but threads eat up a fair chunk of memory (you get one stack per thread, which means you need to allocate a hunk of memory for each stack). I did a quick look around; 256k seems like a common default stack size. 1 meg wouldn't be unheard of. From dickinsm at gmail.com Sun Dec 7 13:14:06 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 7 Dec 2008 10:14:06 -0800 (PST) Subject: Rich Comparisons Gotcha References: Message-ID: <4f12f2b4-ef5e-4358-aa28-6ce51c2e10a7@a12g2000pro.googlegroups.com> On Dec 7, 4:23?pm, Rasmus Fogh wrote: > If is is possible to change the language, how about having two > diferent functions, one for overloading the '==' operator, and another > for testing list and set membership, dictionary key identity, etc.? I've often thought that this would have made a lot of sense too, though I'd probably choose to spell the well-behaved structural equality "==" and the flexible numeric equality "eq" (a la Fortran). Hey, we could have *six* new keywords: eq, ne, le, lt, ge, gt! See the recent (September?) thread "Comparing float and decimal" for some of the fun that results from lack of transitivity of equality. But I think there's essentially no chance of Python changing to support this. And even if there were, Python's conflation of structural equality with numeric equality brings significant benefits in terms of readability of code, ease of learning, and general friendliness; it's only really troublesome in a few corner cases. Is the tradeoff worth it? So for me, this comes down to a case of 'practicality beats purity'. Mark From robert.kern at gmail.com Tue Dec 2 19:28:55 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 02 Dec 2008 18:28:55 -0600 Subject: problem with optparse In-Reply-To: References: Message-ID: Neal Becker wrote: > This example is right out of python library reference. What's wrong here? > > import optparse > > def store_value(option, opt_str, value, parser): > setattr(parser.values, option.dest, value) > > parser = optparse.OptionParser() > parser.add_option("--foo", > action="callback", callback=store_value, > type="int", nargs=3, dest="foo") > > (opt,args) = parser.parse_args ('--foo a b c'.split()) > > [...] > /usr/lib64/python2.5/optparse.pyc in _process_args(self, largs, rargs, values) > 1423 elif self.allow_interspersed_args: > 1424 largs.append(arg) > -> 1425 del rargs[0] > 1426 else: > 1427 return # stop now, leave this arg in rargs > > TypeError: 'str' object doesn't support item deletion Dunno. It works for me (i.e. I get the expected "error: option --foo: invalid integer value: 'a'"). Have you tried it outside of IPython? -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sjmachin at lexicon.net Mon Dec 22 19:55:37 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 22 Dec 2008 16:55:37 -0800 (PST) Subject: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> Message-ID: <9eae14b8-93d6-4c34-b7d3-56c27408b52f@a26g2000prf.googlegroups.com> On Dec 23, 10:24?am, r wrote: > Because my balls are so big i walk around bow-legged! Have you considered that your alleged testicular enormity may in fact be an illusion caused by a hernia? From robert.kern at gmail.com Mon Dec 1 20:06:24 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 01 Dec 2008 19:06:24 -0600 Subject: optimization In-Reply-To: <6672532a-f162-4717-b0bb-c613214b57db@d32g2000yqe.googlegroups.com> References: <6672532a-f162-4717-b0bb-c613214b57db@d32g2000yqe.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Robert Kern: >> I only expect functions to be defined inside of functions if they are going to use lexical scoping for some reason.< > > There are other reasons to nest functions. One of them is to represent > logical nesting of some functionality. Is that any different than Neal's "if it's only used inside"? > So you will find some exceptions to your self-created rule :-) It's not a rule; it's just what I expect after many years of programming Python and reading lots of Python code. Most people define functions at the top-level regardless of whether they are used once or not. Defining a function inside of a function is an oddity. Lexical scoping requires that you define a function inside of a function, so that is always my first assumption about why the author defined the function there. I only fall back to "the author just wanted to organize things in a different way" when I fail to find the lexically-scoped variables, or I see a comment explaining it. I'm pretty sure that lexical scoping (and its poor-man implementation via keyword arguments before) is what the def-in-a-def feature was for, not organization. As Neal has observed, there is a performance hit for creating functions inside of another function. Every time you go through the outer function, you are creating new function objects for all of the inner functions. That's how you can get lexical scoping. It is not equivalent to defining the functions all at the top-level, where all of the function objects are created at once. The compiler can't optimize that overhead away because the overhead arises from implementing a real feature. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From cjwilliams43 at gmail.com Mon Dec 22 16:00:00 2008 From: cjwilliams43 at gmail.com (Colin J. Williams) Date: Mon, 22 Dec 2008 16:00:00 -0500 Subject: Check file is In-Reply-To: <494FF2BB.2050402@ulmcnett.com> References: <7caa7d45-ebbe-4c88-bb50-2f01f7315d07@s9g2000prg.googlegroups.com> <494cbef5$0$90267$14726298@news.sunsite.dk> <494FF2BB.2050402@ulmcnett.com> Message-ID: <494FFFD0.9020903@ncf.ca> An HTML attachment was scrubbed... URL: From philip at semanchuk.com Wed Dec 3 15:32:11 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Wed, 3 Dec 2008 15:32:11 -0500 Subject: Running a Python script from crontab In-Reply-To: <1f4901bb-012c-4e74-8650-c72d48203822@g38g2000yqn.googlegroups.com> References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> <126ba84a-0ea0-4a91-b7d2-89ed650e5d6c@d32g2000yqe.googlegroups.com> <1f4901bb-012c-4e74-8650-c72d48203822@g38g2000yqn.googlegroups.com> Message-ID: <19F946A1-D58F-4A04-B488-AD4BB9174DC7@semanchuk.com> On Dec 3, 2008, at 3:06 PM, Astley Le Jasper wrote: > On 3 Dec, 19:49, Philip Semanchuk wrote: >> On Dec 3, 2008, at 1:33 PM, Astley Le Jasper wrote: >> >>> On 3 Dec, 16:41, Philip Semanchuk wrote: >>>> On Dec 3, 2008, at 10:29 AM, Astley Le Jasper wrote: >> >>>>> I've included a switch to include or exclude theloggingto console. >>>>> Whenloggingonly to file, the script runs fine. >> >>>>> Of course, I still don't understand whyduallogging, and >>>>> specifically >>>>> to the console, causes a problem and if anyone has any comments >>>>> about >>>>> thedualoutputloggingcode above then I'd still be happy to hear >>>>> about it. >> >>>> Trying to write non-ASCII characters perchance? >> >>> Errmmm ... that's kind of spoookey. I using UTF-8 encoding as I >>> have a >>> lot of European language characters. But would that cause a problem >>> when running from crontab but not in the terminal? >> >>> Go on then ... spill the beans. >> >> Oh, I don't know exactly. It's just what I thought of when you said >> that the problem occurs when logging to the console but not to files. >> I don't have a deep Unix background so I can't give you the details >> on >> what "the console" means to a cron job. >> >> In my experience, the environment in which a cron job runs is >> different from the environment in which some command line scripts run >> (remember my earlier suggestion about needing to explicitly set the >> PATH?) and so if the console for a cron job differed from the console >> that a Python program sees when run in a terminal, that would not >> surprise me. >> >> Hope it's a useful suggestion >> Philip > > I tried using the path variables but it didn't help. There again, I > didn't really understand what was being passed in the path variables > and, rather than just copying and pasting, I wanted to look up further > info to get to grips with it. I've got something that works, so now > the pressure is off I can spend some time looking it up. > > [sigh ... my experiences with linux haven't been that good so far. It > is, if nothing else, interesting] Sorry, I was misleading. I don't think the PATH has anything to do with why your script can't log to the console when run as a cron job. I was just pointing out that my Python scripts have had environment- related problems when run as cron jobs, so it would not surprise me if that's your problem too. The PATH was just an example of an environment element that wasn't what I expected. Just a thought -- if my weak hunch that non-ASCII output is your problem, you might be able to test this easily (depending on how you use the logger) by forcing all output messages to "foo". If your cron job doesn't crash then, you know that the *content* of the output is probably the culprit which would indeed point to an encoding problem. HTH Philip From Russ.Paielli at gmail.com Thu Dec 18 21:47:38 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Thu, 18 Dec 2008 18:47:38 -0800 (PST) Subject: Factoring Polynomials References: <919062f9-765e-4279-aa26-2c130d4deacf@o4g2000pra.googlegroups.com> <4479b464-3a9b-4dd8-bf66-fea7d9471091@n33g2000pri.googlegroups.com> <661fd2d0-251d-4899-a015-8d257310a159@q26g2000prq.googlegroups.com> Message-ID: <6ce67c39-4d16-479f-87dd-a68d8000ce78@a26g2000prf.googlegroups.com> On Dec 18, 6:41?pm, "Russ P." wrote: > On Dec 18, 6:31?pm, Collin D wrote: > > > > > On Dec 18, 6:27?pm, Collin D wrote: > > > > On Dec 18, 6:23?pm, "Russ P." wrote: > > > > > On Dec 18, 6:17?pm, Collin D wrote: > > > > > > On Dec 18, 6:12?pm, Collin D wrote: > > > > > > > On Dec 18, 11:37?am, collin.da... at gmail.com wrote: > > > > > > > > I am trying to write a simple application to factor polynomials. I > > > > > > > wrote (simple) raw_input lines to collect the a, b, and c values from > > > > > > > the user, but I dont know how to implement the quadratic equation > > > > > > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > > > > > > into python. Any ideas? > > > > > > > I completed the code: > > > > > > > #import > > > > > > from math import sqrt > > > > > > > # collect data > > > > > > a = float(raw_input('Type a value: ')) > > > > > > b = float(raw_input('Type b value: ')) > > > > > > c = float(raw_input('Type c value: ')) > > > > > > > # create solver > > > > > > def solver(a,b,c): > > > > > > ? ? if b**2 - 4*a*c < 0: > > > > > > ? ? ? ? return 'No real solution.' > > > > > > ? ? else: > > > > > > ? ? ? ? sol1 = -1 * b + (sqrt(b**2 - 4*a*c)) / 2*a > > > > > > ? ? ? ? sol2 = -1 * b - (sqrt(b**2 - 4*a*c)) / 2*a > > > > > > ? ? ? ? return (sol1, sol2) > > > > > > > # execute > > > > > > print solver(a,b,c) > > > > > > > Thanks to everyone who helped... > > > > > > This really expanded my knowledge on some of the mathematical > > > > > > functions in Python. > > > > > > UPDATE: > > > > > ' > > > > > > #import > > > > > from math import sqrt > > > > > > # collect data > > > > > a = float(raw_input('Type a value: ')) > > > > > b = float(raw_input('Type b value: ')) > > > > > c = float(raw_input('Type c value: ')) > > > > > > # create solver > > > > > def solver(a,b,c): > > > > > ? ? if b**2 - 4*a*c < 0: > > > > > ? ? ? ? return 'No real solution.' > > > > > ? ? else: > > > > > ? ? ? ? sol1 = (-1 * b + (sqrt(b**2 - 4*a*c))) / 2*a > > > > > ? ? ? ? sol2 = (-1 * b - (sqrt(b**2 - 4*a*c))) / 2*a > > > > > ? ? ? ? return (sol1, sol2) > > > > > > # execute > > > > > print solver(a,b,c) > > > > > You need to put your denominator, 2*a, in parens. The way it stands, > > > > you are dividing by 2, then multiplying by a. That's not what you > > > > want. > > > > > Also, for better style, I suggest you compute the discriminanat once > > > > and store it for reuse rather than repeating the expression three > > > > times.- Hide quoted text - > > > > > - Show quoted text - > > > > I see what you mean on the denominator and discriminant. Ill do that.- Hide quoted text - > > > > - Show quoted text - > > > UPDATE: > > > #import > > from math import sqrt > > > # collect data > > a = float(raw_input('Type a value: ')) > > b = float(raw_input('Type b value: ')) > > c = float(raw_input('Type c value: ')) > > > # find discriminant > > disc = b**2 - 4*a*c > > > # create solver > > def solver(a,b,c): > > ? ? if disc < 0: > > ? ? ? ? return 'No real solution.' > > ? ? else: > > ? ? ? ? sol1 = (-1 * b + (sqrt(disc))) / (2*a) > > ? ? ? ? sol2 = (-1 * b - (sqrt(disc))) / (2*a) > > ? ? ? ? return (sol1, sol2) > > > # execute > > print solver(a,b,c) > > A couple of style points. I would use -b rather than -1 * b. Also, you > don't need the else clause. You can simplify it to > > def solver(a, b, c): > > ? ? disc = b**2 - 4 * a * c > > ? ? if disc < 0: return "No real solution." > > ? ? sol1 = (-b + sqrt(disc)) / (2*a) > ? ? sol2 = (-b - sqrt(disc)) / (2*a) > > ? ? return sol1, sol2 By the way, this little function is suitable for your purposes here, but it is not really a good general quadratic solver, because it returns different types depending on the inputs. For a good general function, you would probably want to throw an exception when the discriminant is negative (as an earlier poster suggested). From narkewoody at gmail.com Mon Dec 22 04:11:18 2008 From: narkewoody at gmail.com (Steven Woody) Date: Mon, 22 Dec 2008 17:11:18 +0800 Subject: How to represent a sequence of raw bytes In-Reply-To: References: <200812220327.36180.motoom@xs4all.nl> Message-ID: On Mon, Dec 22, 2008 at 4:35 PM, James Mills wrote: > On Mon, Dec 22, 2008 at 4:56 PM, Steven Woody wrote: >> I thing "\x11\x22\x33" in python is not the {0x11, 0x22, 0x33} in C. >> Since, a string in python is immutable, I can _not_ do something like: >> b[1] = "\x55". >> >> And, how about char buf[200] in my original question? The intension >> is to allocate 200 undefined bytes in memory. Thanks. > > Steven, one piece of advice. > > Python is not C. > > Thank. > > cheers > James > Ok, I will study all your advices. I think I may find my way when doing real tasks. From malaclypse2 at gmail.com Mon Dec 1 15:53:23 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 1 Dec 2008 15:53:23 -0500 Subject: Checking a string against multiple matches In-Reply-To: <279c426a-214c-4b6f-aaf2-989abd197744@v4g2000yqa.googlegroups.com> References: <99a3a677-a38d-40f5-9a94-a98865150b69@k19g2000yqg.googlegroups.com> <279c426a-214c-4b6f-aaf2-989abd197744@v4g2000yqa.googlegroups.com> Message-ID: <16651e80812011253j50f2cfcen980a679bbe0ce9c5@mail.gmail.com> On Mon, Dec 1, 2008 at 3:29 PM, Aaron Scott wrote: > Damn you, Python, and your loose documentation! It never occurred to > me to actually TRY my pseudocode, since I couldn't find anything on > that type of statement. Anyway, feel free to ignore me from now on. I'm not sure where you think the "in" operator should be documented. It's in the documentation for sequence types: http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange The tutorial points there too, in its discussion of strings. It's also in the language reference, in the section on comparision operators: http://docs.python.org/reference/expressions.html#id12 Was there someplace you were looking that you expected to find something about the containment operator and couldn't find it? Maybe it would be worth adding a "See Also" someplace? -- Jerry From geekmail at usenot.de Sun Dec 7 15:25:46 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sun, 7 Dec 2008 21:25:46 +0100 Subject: Python for kids? References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> Message-ID: <20081207212546.484c0d0e@usenot.de> On Sun, 7 Dec 2008 12:13:37 -0800 (PST) "Russ P." wrote: > I have a 12-year-old son who spends too much time playing Xbox live > and watching silly YouTube videos. I would like to try to get him > interested in programming. Is anyone aware of a good book or website > that addresses this concern, preferably (but not necessarily) using > Python? I could try to teach him Python myself, but I'm afraid I would > just frustrate him and kill his interest in programming. I did a > Google search and found a few things, but not a lot. Thanks. Since your son seems to enjoy games, getting him interested in game programming seems the most appropriate thing to do. I'm not much of a Gamer myself, but I should think maybe modding a shooter or other kind of game should be within the grasp of a 12 year old (provided you let him play shooters). Also, there's AGS (and friends) for making Adventure games. Depending on his interests, smaller projects might work out as well, such as Sudoku, Mahjongh, Card Games and whatnot. Any of those could well become father and son projects as long as you let him have the lead. Has he ever expressed an interest in programming at all? /W -- My real email address is constructed by swapping the domain with the recipient (local part). From google at mrabarnett.plus.com Fri Dec 5 14:15:11 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 05 Dec 2008 19:15:11 +0000 Subject: Overwrite single line of file In-Reply-To: References: Message-ID: <49397DBF.1060104@mrabarnett.plus.com> chrispoliquin at gmail.com wrote: > Hi, > > I have about 900 text files (about 2 GB of data) and I need to make > some very specific changes to the last line of each file. I'm > wondering if there is a way to just overwrite the last line of a file > or replace the spots I want (I even know the position of the > characters I need to replace). > > I know how to open files and read the contents and then write > everything out again after making the changes, but is there a way to > replace just the last line without having to completely rewrite each > file after making the changes? > f = open(path, "r+") f.seek(start_of_last_line) f.write(new_line) # Assuming that new_line ends with "\n" f.truncate() # In case the new line is shorter than what it's replacing f.close() From hniksic at xemacs.org Sat Dec 13 09:28:20 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sat, 13 Dec 2008 15:28:20 +0100 Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> <87iqpoc1l0.fsf@mulj.homelinux.net> <6qhk9dFclvujU1@mid.uni-berlin.de> Message-ID: <87bpvgb14r.fsf@mulj.homelinux.net> Marc 'BlackJack' Rintsch writes: > On Sat, 13 Dec 2008 02:20:59 +0100, Hrvoje Niksic wrote: > >> Saner (in this respect) behavior in the tuple example would require >> a different protocol. I don't understand why Python doesn't just >> call __iadd__ for side effect if it exists. The decision to also >> rebind the result of __i*__ methods continues to baffle me. I >> guess it is a result of a desire to enable the __i*__ methods to >> punt and return a different instance after all, but if so, that >> design decision brings more problems than benefits. > > How often do you use ``+=`` with mutable objects? I use it very > often with number types and sometimes with tuples, and there > rebinding is necessary. If I couldn't use it in this way: ``x = 0; > x += z``, I'd call that a bad design decision. It would be a quite > useless operator then. Marc, I agree with you, I wasn't arguing that += shouldn't work for immutable objects. If an object doesn't support __iadd__ at all (as is already the case for numbers, strings, etc.), += should fall back to __add__ followed by assignment. My point is that, *if they do*, it would be better to just use __iadd__ and not attempt to also rebind. Again, in pseudocode, I'd expect A += x to be implemented as: lhsobj = A if hasattr(lhsobj, '__iadd__'): lhsobj.__iadd__(x) # lhsobj has __iadd__, just use it else: A = lhsobj.__add__(x) # fails if __add__ is not present either That way tupleobj[0] += blah would work just fine for mutable objects and would throw an exception for immutable objects. The current situation where += first modifies the mutable object, and *then* throws an exception feels like a design glitch. From lie.1296 at gmail.com Fri Dec 12 16:00:38 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 12 Dec 2008 21:00:38 +0000 (UTC) Subject: (Very Newbie) Problems defining a variable References: Message-ID: On Fri, 12 Dec 2008 09:50:43 -0800, Dennis Lee Bieber wrote: > On Fri, 12 Dec 2008 03:42:55 -0800 (PST), febaen at gmail.com declaimed the > following in comp.lang.python: > >> #!/usr/bin/python >> #Py3k, UTF-8 >> >> bank = int(input("How much money is in your account?\n>>")) target = >> int(input("How much money would you like to earn each year? \n>>")) >> > Just for my curiosity -- did Python 3.x (besides turning print into > a function) also change input() to behave as the old raw_input()? > > The above would be very discouraged in Python 2.x... in favor of ... > int(raw_input(...)) > Actually, that's the first thing I wanted to bark on, before seeing the little note above it: "#Py3k, UTF-8". I wonder though, there is a potential problem if someone (users) is running this py3k code in a python2.x. The code is a perfectly legal and correct python 2.x code, but uses input() instead of raw_input(), we all know the evil of 2.x's input (). From 20080915.20.wmcclain at spamgourmet.com Tue Dec 9 14:24:13 2008 From: 20080915.20.wmcclain at spamgourmet.com (Bill McClain) Date: 9 Dec 2008 19:24:13 GMT Subject: StringIO in 2.6 and beyond References: Message-ID: On 2008-12-09, MRAB wrote: > In Python 2.x unmarked string literals are bytestrings. In Python 3.x > they're Unicode. The intention is to make the transition from 2.x to 3.x > easier by adding some features of 3.x to 2.x, but without breaking > backwards compatibility (not entirely successfully!). It is a bit ugly. In 2.6 StringIO won't take bytestrings, so I apply u'x'. But in 3.0 u'x' will be gone and I'll have to change the code again. It's a small effort for what I am working on, but frustrating trying to puzzle this out from the docs, which I couldn't do. -Bill -- Sattre Press History of Astronomy http://sattre-press.com/ During the 19th Century info at sattre-press.com by Agnes M. Clerke http://sattre-press.com/han.html From sumerc at gmail.com Tue Dec 30 03:16:14 2008 From: sumerc at gmail.com (k3xji) Date: Tue, 30 Dec 2008 00:16:14 -0800 (PST) Subject: Read-Write Lock vs primitive Lock() References: <277c1be7-2560-4fd6-9610-0b4398dc3719@x16g2000prn.googlegroups.com> Message-ID: > >> Note that the thread acquires the lock ONCE, repeats several thousand > >> times an assignment to a *local* variable called GLOBAL_VAR (!), finally > >> releases the lock and exits. As every thread does the same, they just ? > >> run > >> one after another, they never have a significant overlap. Ok. Forget about the GLOBAL_VAR. See the below code: import threading import locks import time GLOBAL_VAR = [] #GLOBAL_LOCK = locks.ReadWriteLock() GLOBAL_LOCK = threading.Lock() #GLOBAL_LOCK = mylock() GLOBAL_LOOP_COUNT = 10000000 GLOBAL_READER_COUNT = 100 GLOBAL_WRITER_COUNT = 1 global GLOBAL_LEN class wthread(threading.Thread): def run(self): try: GLOBAL_LOCK.acquireWrite() #GLOBAL_LOCK.acquire_write() #GLOBAL_LOCK.acquire() for i in range(GLOBAL_LOOP_COUNT): pass finally: #GLOBAL_LOCK.release_write() GLOBAL_LOCK.release() class rthread(threading.Thread): def run(self): try: GLOBAL_LOCK.acquireRead() #GLOBAL_LOCK.acquire_read() print 'ENTER:'+str(threading.currentThread()) #GLOBAL_LOCK.acquire() print 'ACQUIRE:'+str(threading.currentThread()) for i in range(GLOBAL_LOOP_COUNT): pass finally: #GLOBAL_LOCK.release_read() GLOBAL_LOCK.release() print 'RELEASE:'+str(threading.currentThread()) # module executed? if __name__ == "__main__": starttime = time.clock() threads = [] for i in range(GLOBAL_READER_COUNT): rt = rthread() threads.append(rt) for i in range(GLOBAL_WRITER_COUNT): wt = wthread() threads.append(wt) for thread in threads: thread.start() for thread in threads: thread.join() print "All operations took " + str(time.clock() - starttime) + " msecs" As GLOBAL_LOOP_COUNT is 10000000, now this is making a bottleneck on the readers. I had assumed that as everythread is given only 100 bytecodes to execute, that it will be enough to have a 10000 value for this number to let other rthread start() and try to acquire the lock. But, Python undocumentedly, does not grab the GIL easily if a Lock is held. This is strange for me. > > If I put the for loop outside, in that case, readers will not overlap > > at all, and you would be amazed by the numbers for that test. They > > indicate primitive lock is faster than read-write lock, as it requires > > the lock, executes only one bytecode operation and releases the lock. > > So, in order to create a bottlenneck on readers, we need to somehow do > > not release the lock immediately. > > Again, what is your specific use case? why do you think readers will see a ? > bottleneck? > > > With that, primitive locks perform 10 times better than Read-Write > > lock. See above. > > So what? You don't like such results? The read-write lock in the recipe ? > you posted is rather complex, and isn't obvious whether it is correct or ? > not, and the author doesn't prove it nor provide a reference. I'd stick to ? > the standard Lock object unless I have specific needs. > Note that threading.Lock objects are implemented in C and don't have ? > significant overhead (other than the wait itself); even threading.RLock ? > objects are a lot slower. So depending on what you really have to do, the ? > overhead of using a class like ReadWriteLock may be worse than using a ? > standard Lock. That may be the point. That is why I am trying to test this. When will ReadWrite() lock permforms better over the primitive lock. By the way, for the reference, the code in the recipe is used in CherryPy and based on the Tanenbaum's book Operating Systems Design. > >> Hmmm, it's a reader but attempts to modify the value? > >> You don't have to protect a read operation on a global variable - so a > >> lock isn't required here. > > > This is just for testing. Suppose that I am actually reading the > > value. I don't understand why a lock is not required? Are you saying > > lock is not necesary beacuse GLOBAL_VALUE is an immutable object, if > > then, suppose it is not. This is just a test. Suppose GLOBAl_VAR is a > > list and we are calling append() on it which is nt an atomic > > operation. > > It doesn't matter whether it is mutable or immutable. Remember that, in ? > Python, a global variable is just a *name* that refers to an object; you ? > either get the old object referred, or the new one. If it is a list and it ? > is being modified "in place", you always get the same list -- its contents ? > may differ from one instant to another so iterating over it isn't safe. > That's why I insist on knowing your use case: you may me doing things more ? > complicated than they should. I understand your point completely, but let's change anything inside the loop. Just assume that we a thread that is supposed to read something, and a thread that is supposed to write. If I create thousands of readers, and if the operation is enormously huge calculation(as Python does not grab GIL easily inside a Lock), then this will create a bottlencek on readers. But, with ReadWrite Lock this problem *SHOULD* be fixed and in my tests I see it is fixed, when I increase the time spent in the loop in huge amounts. > > Each thread in your original code were like this: > > begin thread; wait for lock; execute something locally; release lock; exit ? > thread; > > There was no shared state between threads. Even if you fix them to share ? > some variable, they were a single, sequential, piece of code (the inner ? > loop is irrelevant here). Once a thread gets the lock, it just runs to its ? > end. No one waits more than once for the lock. So all of them run ? > sequentially, in arbitrary order, but just one after the other. They never ? > overlap. You are correct about this. But this is an undocumented thing. I had assumed that Python will release GIL for other threads after 100 bytecodes are executed by default. However, as I stated, when a Lock() is held this is changing. I think this is because to avoid simple MT problems for new programmers. Not sure. I will read threads.c for information. Thanks. From steve at REMOVE-THIS-cybersource.com.au Fri Dec 12 19:00:24 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Dec 2008 00:00:24 GMT Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> Message-ID: <0152f29f$0$8244$c3e8da3@news.astraweb.com> On Fri, 12 Dec 2008 08:43:31 -0800, sturlamolden wrote: > On Dec 12, 5:13 pm, Steve Holden wrote: > >> > It should be the tuple's __setitem__ that was invoked here, not >> > __iadd__, or the parser is faulty. >> >> OK, so now you are proposing to alter the parser, and possibly the >> implementation of the INPLACE_ADD opcode in eval.c, so can you give us >> the patch for those, please? > > What? Take a look at the code again: > > mytuple[0] += 1 > > should never attempt an __iadd__ on mytuple. > > A sane parser would see this as: > > tmp = mytuple.__getitem__(0) > tmp = tmp.__iadd__(1) > mytuple.__setitem__(0, tmp) # should this always raise an exception? It is quite problematic if you do that. You've already pointed that out yourself, by asking if "should this always raise an exception?". With the behaviour you're asking for, there's ambiguity is what is allowed and what isn't. You can try making __setitem__ cleverer, as in your earlier post, but then: t = (1, 2, 3) t[0] += x sometimes succeeds, sometimes fails, depending on the value of x. And worse: t[0] = y also sometimes succeeds. It's not clear that those occasional successes are actively harmful, but nor is it clear that prohibiting them is harmful either. The best you get from it is the ability to mutate mutable items in a tuple, but you can do that already: t = ([], None) x = t[0] x += ["mutated"] So the current tuple implementation gives us consistent behaviour and simplicity without preventing you from mutating elements if you really want to. The only real cost is if you do this: t[0] += ["mutated"] you get an error and a mutation. Certainly a gotcha, but I wouldn't describe it as a bug: it's pretty much unavoidable if you want to avoid treating tuples as a special case. >> Discussion of such behavior as a "bug" is also pejorative, since the >> current semantics are the way they are by design. > > Right, this bug is by design. You learned that phrase from a guy in > Redmond? No. It merely means that just because you think it is a bug doesn't make it so. It may even mean that there is no perfect solution, that *any* behaviour on tuples containing mutable objects will be considered broken by some people under some circumstances. Trade-offs in software design are inevitable. There's little gain from your proposal, and some cost, and the problem you are trying to solve isn't a problem in practice. So if it's a bug, it's an insignificant one, not worth fixing because the fix will invariably cause more problems than the bug. -- Steven From klaus.kopec at tuebingen.mpg.de Wed Dec 10 05:03:12 2008 From: klaus.kopec at tuebingen.mpg.de (Klaus Kopec) Date: Wed, 10 Dec 2008 11:03:12 +0100 Subject: pickling a circular object inherited from list In-Reply-To: References: <3b1bab42-657c-4b93-9236-aa5236c16826@w1g2000prk.googlegroups.com> Message-ID: Ned Deily wrote: > In article , > Klaus Kopec wrote: >>>> What did I do wrong? >>> Old Python version? :) >>> Seems to work in 3.0 (don't have 2.6 currently to check but IMO it's >>> fixed there as well). >> It works for me with v3.0 as well, but not with v2.6.1 (same error as >> stated before for v2.4). >> >> Is there any way to fix this in v2.6.1 or even v2.4? Right now I cannot >> switch to v3.0 because I depend on several not compatible packages >> (numpy, biopython, ...) > > It looks like your example can be made to work by either specifying > pickle protocol 2 or by switching to cPickle. > Using pickle protocol 2 solved the problem. Thank you all for helping me out! From steven at REMOVE.THIS.cybersource.com.au Thu Dec 11 03:14:45 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 11 Dec 2008 08:14:45 GMT Subject: if expression source format References: Message-ID: On Thu, 11 Dec 2008 02:07:54 -0500, Lambert, David W (S&T) wrote: > The "if" expression leads to long statements. Please offer suggestions > to beautify this function. For this example use maximum line length > marked by the ####'s. > > Thank you. > > > ############################################################## > def compute_wind_chill_temperture(T:'Temperature, dF',s:'Wind speed, > mph')->'dF': > ''' > > ''' > return 35.74 + 0.6215*T + s**0.16*(T*0.4275-35.75) if T < 40 else T Firstly, you don't need "compute". Every function computes. Secondly, fix the spelling of temperature. Thirdly, we can make it easier to read by spreading it out. ############################################################## def wind_chill_temperature( T:'Temperature, dF',s:'Wind speed, mph')->'dF': 'http://www.erh.noaa.gov/er/iln/tables.htm#heat index' if T < 40: return 35.74 + 0.6215*T + s**0.16*(T*0.4275-35.75) else: return T There is no shortage of newlines. They are a renewable resource, don't be afraid to use a couple of extra lines to make your code more readable. -- Steven From matt at blackcodeseo.com Sat Dec 13 01:06:53 2008 From: matt at blackcodeseo.com (Matt) Date: Sat, 13 Dec 2008 01:06:53 -0500 Subject: using google search api for python Message-ID: You might want to try this Google Search API for Python. Sample implementation: >>> from Google import Google, search >>> results = search('blackcodeseo.com', 3) >>> for result in results: ? print 'Title: %s' % (result.title()) ? print 'Url: %s' % (result.url()) ? print 'Description: %s' % (result.description()) ? print ? Title: Black Code SEO Url: http://blackcodeseo.com/ Description: Oct 29, 2008 ? Black Code SEO. Programatically Automating SEO ? Download BlackCodeSeo Navigator. Run python setup.py install ? Title: Have A Question? Url: http://blackcodeseo.com/have-a-question/ Description: If you have any questions about anything, you can reach me at matt at blackcodeseo. com and I will be happy to reply. Your questions may be posted on the site ? Title: SpiderMonkey ? Didier Stevens Url: http://blog.didierstevens.com/programs/spidermonkey/ Description: The exact post is http://blackcodeseo.com/python-spidermonkey-navigator/. Comment by Matt ? Wednesday 29 October 2008 @ 20:56. Thanks. ? >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip at pobox.com Mon Dec 22 15:31:27 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 22 Dec 2008 14:31:27 -0600 Subject: I always wonder ... In-Reply-To: References: Message-ID: <18767.63775.837578.900457@montanaro-dyndns-org.local> Carl> ...shouldn't poeple who spend all their time following up to Carl> trolls, or starting new threads about trolls, being doing Carl> something else? Sure. It was just a momentary break from work, as is this. I thought an implied smiley was enough, but I guess not. Skip From Sengly.Heng at gmail.com Tue Dec 23 05:46:20 2008 From: Sengly.Heng at gmail.com (Sengly) Date: Tue, 23 Dec 2008 02:46:20 -0800 (PST) Subject: Very basic question Message-ID: <21ab1917-f0c9-48fb-baa9-02e5bf229bf5@s9g2000prm.googlegroups.com> Hello all, I would like to calculate a string expression to a float. For example, I have ('12/5') and I want 2.4 as a result. I tried to use eval but it only gives me 2 instead of 2.5 Help!!! Regards, Sengly From anthony.tolle at gmail.com Mon Dec 29 10:46:26 2008 From: anthony.tolle at gmail.com (anthony.tolle at gmail.com) Date: Mon, 29 Dec 2008 07:46:26 -0800 (PST) Subject: why cannot assign to function call References: Message-ID: <27ff529c-ac42-449c-87a4-64ecc6582b5f@t26g2000prh.googlegroups.com> On Dec 29, 1:01?am, scsoce wrote: > I have a function return a reference, and want to assign to the > reference, simply like this: > ?>>def f(a) > ? ? ? ? ? return a > ? ? ?b = 0 > ? ? * f( b ) = 1* > but the last line will be refused as "can't assign to function call". > In my thought , the assignment is very nature, ?but ?why the interpreter > refused to do that ? > > thks Probably the closest thing you are going to get in Python would be the following: >>> class C: ... pass ... >>> def f(a): ... return a ... >>> b = C() >>> b.value = 0 >>> b.value 0 >>> f(b).value = 1 >>> b.value 1 But as others have pointed out, Python is not C/C++, and shouldn't be treated as such. From sjmachin at lexicon.net Mon Dec 29 23:52:25 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 29 Dec 2008 20:52:25 -0800 (PST) Subject: Of console I/O, characters, strings & dogs References: Message-ID: <8814e07b-6d4f-4338-a96f-be16f46b12cd@w1g2000prk.googlegroups.com> On Dec 30, 11:53?am, David Lemper wrote: > I am trying getch() from msvcrt. Unfortunately the msvcrt docs have not been 2to3ified: """ msvcrt.getch() 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. msvcrt.getwch() Wide char variant of getch(), returning a Unicode value. """ In Python 3.0, getch() returns a length-1 bytes object. getwch() returns a length-1 str object. Suggestions: (1) Do more of the 3.0 tutorial so that you understand the bytes/str thing. (2) Use getwch instead of getch (3) Consider whether the builtins print() and input() cover your needs for console IO. HTH, John From Russ.Paielli at gmail.com Thu Dec 18 21:41:57 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Thu, 18 Dec 2008 18:41:57 -0800 (PST) Subject: Factoring Polynomials References: <919062f9-765e-4279-aa26-2c130d4deacf@o4g2000pra.googlegroups.com> <4479b464-3a9b-4dd8-bf66-fea7d9471091@n33g2000pri.googlegroups.com> <661fd2d0-251d-4899-a015-8d257310a159@q26g2000prq.googlegroups.com> Message-ID: On Dec 18, 6:31?pm, Collin D wrote: > On Dec 18, 6:27?pm, Collin D wrote: > > > > > On Dec 18, 6:23?pm, "Russ P." wrote: > > > > On Dec 18, 6:17?pm, Collin D wrote: > > > > > On Dec 18, 6:12?pm, Collin D wrote: > > > > > > On Dec 18, 11:37?am, collin.da... at gmail.com wrote: > > > > > > > I am trying to write a simple application to factor polynomials. I > > > > > > wrote (simple) raw_input lines to collect the a, b, and c values from > > > > > > the user, but I dont know how to implement the quadratic equation > > > > > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > > > > > into python. Any ideas? > > > > > > I completed the code: > > > > > > #import > > > > > from math import sqrt > > > > > > # collect data > > > > > a = float(raw_input('Type a value: ')) > > > > > b = float(raw_input('Type b value: ')) > > > > > c = float(raw_input('Type c value: ')) > > > > > > # create solver > > > > > def solver(a,b,c): > > > > > ? ? if b**2 - 4*a*c < 0: > > > > > ? ? ? ? return 'No real solution.' > > > > > ? ? else: > > > > > ? ? ? ? sol1 = -1 * b + (sqrt(b**2 - 4*a*c)) / 2*a > > > > > ? ? ? ? sol2 = -1 * b - (sqrt(b**2 - 4*a*c)) / 2*a > > > > > ? ? ? ? return (sol1, sol2) > > > > > > # execute > > > > > print solver(a,b,c) > > > > > > Thanks to everyone who helped... > > > > > This really expanded my knowledge on some of the mathematical > > > > > functions in Python. > > > > > UPDATE: > > > > ' > > > > > #import > > > > from math import sqrt > > > > > # collect data > > > > a = float(raw_input('Type a value: ')) > > > > b = float(raw_input('Type b value: ')) > > > > c = float(raw_input('Type c value: ')) > > > > > # create solver > > > > def solver(a,b,c): > > > > ? ? if b**2 - 4*a*c < 0: > > > > ? ? ? ? return 'No real solution.' > > > > ? ? else: > > > > ? ? ? ? sol1 = (-1 * b + (sqrt(b**2 - 4*a*c))) / 2*a > > > > ? ? ? ? sol2 = (-1 * b - (sqrt(b**2 - 4*a*c))) / 2*a > > > > ? ? ? ? return (sol1, sol2) > > > > > # execute > > > > print solver(a,b,c) > > > > You need to put your denominator, 2*a, in parens. The way it stands, > > > you are dividing by 2, then multiplying by a. That's not what you > > > want. > > > > Also, for better style, I suggest you compute the discriminanat once > > > and store it for reuse rather than repeating the expression three > > > times.- Hide quoted text - > > > > - Show quoted text - > > > I see what you mean on the denominator and discriminant. Ill do that.- Hide quoted text - > > > - Show quoted text - > > UPDATE: > > #import > from math import sqrt > > # collect data > a = float(raw_input('Type a value: ')) > b = float(raw_input('Type b value: ')) > c = float(raw_input('Type c value: ')) > > # find discriminant > disc = b**2 - 4*a*c > > # create solver > def solver(a,b,c): > ? ? if disc < 0: > ? ? ? ? return 'No real solution.' > ? ? else: > ? ? ? ? sol1 = (-1 * b + (sqrt(disc))) / (2*a) > ? ? ? ? sol2 = (-1 * b - (sqrt(disc))) / (2*a) > ? ? ? ? return (sol1, sol2) > > # execute > print solver(a,b,c) A couple of style points. I would use -b rather than -1 * b. Also, you don't need the else clause. You can simplify it to def solver(a, b, c): disc = b**2 - 4 * a * c if disc < 0: return "No real solution." sol1 = (-b + sqrt(disc)) / (2*a) sol2 = (-b - sqrt(disc)) / (2*a) return sol1, sol2 From sjmachin at lexicon.net Tue Dec 30 21:32:39 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 30 Dec 2008 18:32:39 -0800 (PST) Subject: TypeError: list indices must be integers References: <2e5a61c0-fa99-4170-81ca-eb3a10859400@k36g2000pri.googlegroups.com> Message-ID: <472447d7-9ed2-4bf2-bb8f-a0c62735316e@q30g2000prq.googlegroups.com> On Dec 31, 12:46?pm, dubux wrote: > my head hurts from looking at it so long. > ? ? ? ? ? ? ? ? mylist = map(lambda i: news_list[i], filter(lambda i: i%2 == 0, range(len(news_list)))) > ? ? ? ? ? ? ? ? date = mylist[y] My head hurts from looking at that only briefly. Any good reason why you wrote that in such a fashion instead of: mylist = news_list[::2] date = mylist[y] or (even better): date = news_list[y * 2] ? From jstroud at mbi.ucla.edu Thu Dec 25 07:02:02 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 25 Dec 2008 04:02:02 -0800 Subject: Is there a function to remove escape characters from a string ? In-Reply-To: References: Message-ID: <%CK4l.11459$c45.7073@nlpi065.nbdc.sbc.com> Stef Mientki wrote: > hello, > > Is there a function to remove escape characters from a string ? > (preferable all escape characters except "\n"). > > thanks, > Stef import string WANTED = string.printable[:-5] + "\n" def descape(s, w=WANTED): return "".join(c for c in s if c in w) James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From exarkun at divmod.com Wed Dec 17 08:52:36 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 17 Dec 2008 08:52:36 -0500 Subject: Transferring a file over sockets In-Reply-To: Message-ID: <20081217135236.20272.889774205.divmod.quotient.22188@ohm> On Wed, 17 Dec 2008 17:41:46 +0530, Ferdinand Sousa wrote: >I am using sockets to transfer a file over LAN. There are 2 scripts, the >server opens a listens for connection and the client is run on another >machine. I always make sure the server is run first. The strange thing is >that if the the server script is double-clicked and executed (run in a >console with title %Python path%python.exe) the output file saved on the >server is truncated. It works just fine if you open the server script in >IDLE and then run it. The client script can be run in either way, it still >works. You could try using any arbitrary file to test this behaviour after >changing the file name in both the scripts. > >========================================================== ># file receiver ># work in progress > >import socket > >s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >HOST = '192.168.1.17' >PORT = 31400 > >s.bind((HOST, PORT)) >s.listen(3) >conn, addr = s.accept() >print 'conn at address',addr >conn.send('READY') >f = open('C:\\Documents and Settings\\USER\\Desktop\\test.pdf','wb') >fsize=int(conn.recv(8)) >print 'File size',fsize >f.write(conn.recv(fsize)) >f.close() >conn.close() >s.close() > >raw_input('Press any key to exit') > > >=========================================================== > ># file sender !!! ># Work in progress > >import socket, os >from stat import ST_SIZE > > >HOST = '192.168.1.17' >PORT = 31400 # Arbitrary non-privileged port > >s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > >s.connect((HOST,PORT)) >if s.recv(5)!='READY': > raw_input('Unable to connect \n\n Press any key to exit ...') > s.close() > exit() > >f=open('C:\\Documents and Settings\\USER\\Desktop\\t.pdf', 'rb') >fsize=os.stat(f.name)[ST_SIZE] > >s.send(str(fsize)) >s.send(f.read()) > >s.close() >f.close() > >=========================================================== > >Thanks for reading!! You're not handling your sockets properly. send() does not necessary send the entire string you pass to it. recv(n) does not necessarily return an n-length string. Read the socket documentation more carefully and try fixing those issues. Or try using Twisted which presents a somewhat easier API to use. Jean-Paul From deets at nospam.web.de Tue Dec 9 04:06:52 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 09 Dec 2008 10:06:52 +0100 Subject: ORB for Python and PHP In-Reply-To: References: <6q5idtFb0dk0U1@mid.uni-berlin.de> Message-ID: <6q6qphFaob49U1@mid.uni-berlin.de> Laszlo Nagy schrieb: > >>> >>> There are others but they do not support both Python and PHP. Should >>> I implement my own ORB, or do you know a suitable solution? >> >> >> The whole purpose of an ORB ist that it is interoperable. So if you >> have a good python orb (I personally prefer OmniORB), and a good one >> for PHP - connect them. > Are all ORBs compatible with each other? I know that this is offtopic, > but do you know any ORB for PHP? I couldn't find any. As I said - that's the *purpose* of ORBs. It has taken a while, but AFAIK by now CORBA2.3 is pretty stable. What about this? http://phporb.sourceforge.net/ I never used it though. PHP isn't to well suited for CORBA, due to the request/response-cycle based architecture. >> I would suggest a consistent XMLRPC-interface though. > Unfortunately, this would not be good. Sometimes we need to pass through > binary data (image file), do session management (which is hard to do > with xml-rpc, where each request is a new connection) and optimize speed > for communication when the parties are on the same machine. Then maybe thrift is for you. http://wiki.apache.org/thrift/ThriftGeneration Diez From rdmurray at bitdance.com Fri Dec 5 11:20:28 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Fri, 5 Dec 2008 11:20:28 -0500 (EST) Subject: pretty strange behavior of "strip" In-Reply-To: References: <4938693F.6090709@yahoo.ca> Message-ID: On Fri, 5 Dec 2008 at 07:54, Mark Tolonen wrote: >> > > import re >> > > re.split('[,.]','blah,blah.blah') > ['blah', 'blah', 'blah'] Thank you. Somehow it never occurred to me that I could use that kind of pattern that way. I guess my brain just doesn't think in regexes very well :) --RDM From toby at telegraphics.com.au Wed Dec 3 23:15:24 2008 From: toby at telegraphics.com.au (toby) Date: Wed, 3 Dec 2008 20:15:24 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <591e8625-7e4d-4db8-ae6c-73c4370f8088@q26g2000prq.googlegroups.com> <6plpnsF8pi3oU1@mid.individual.net> Message-ID: <6c702fda-1a8a-4c3d-a7c0-82e45edab2ce@k41g2000yqn.googlegroups.com> On Dec 2, 5:04 pm, Tamas K Papp wrote: > On Tue, 02 Dec 2008 13:57:35 -0800, Lew wrote: > > Xah Lee wrote: > >> If [yo]u would like to learn [the] [E]nglish lang[uage] and writing > >> insights from me, peruse: > > > /Au contraire/, I was suggesting a higher standard for your posts. > > Hi Lew, > > It is no use. Xah has been posting irrelevant rants in broken English > here for ages. No one knows why, but mental institutions must be really > classy these days if the inmates have internet access. Just filter him > out with your newsreader. You think the posts are bad... check out his web site... --T > > Best, > > Tamas From arnodel at googlemail.com Tue Dec 16 04:10:04 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 16 Dec 2008 09:10:04 +0000 Subject: weird dict problem, how can this even happen? References: Message-ID: Joel Hedlund writes: > I'm having a very hard time explaining why this snippet *sometimes* > raises KeyError: > > snippet: >> print type(self.pool) >> for frag in self.pool.keys(): >> if frag is fragment_info: >> print "the fragment_info *is* in the pool", hash(frag), hash(fragment_info), hash(frag) == hash(fragment_info), frag == fragment_info, frag in self.pool, frag in self.pool.keys() >> try: >> renderer_index = self.pool.pop(fragment_info) >> except KeyError: >> print "Glorious KeyError!" >> for frag in self.pool.keys(): >> if frag is fragment_info: >> print "the fragment_info *is* in the pool", hash(frag), hash(fragment_info), hash(frag) == hash(fragment_info), frag == fragment_info, frag in self.pool, frag in self.pool.keys() >> raise > > > output: >> >> the fragment_info *is* in the pool 987212075 987212075 True True False True >> Glorious KeyError! >> the fragment_info *is* in the pool 987212075 987212075 True True False True >> Traceback (most recent call last): >> File "/home/yohell/workspace/missy/core/gui.py", line 92, in process_job >> renderer_index = self.pool.pop(fragment_info) >> KeyError: > > This snippet is part of a much larger gtk program, and the problem > only from time to time, predominantly when the cpu is under heavy load > and this method gets called a lot. If I didn't know better I'd say > it's a bug in python's dict implementation, but I do know better, so I > know it's far more likely that I've made a mistake somewhere. I'll be > damned if I can figure out what and where though. I've reproduced this > bug (?) with python-2.5.2 on Ubuntu 8.10 and python-2.5.1 on WinXP. > > I would very much like an explanation to this that does not involve > threads, because I haven't made any that I'm aware of. I can't even > understand how this could happen. How do I even debug this? > > Please help, I feel like I've taken crazy pills here! > /Joel Hedlund It could happen if two object x and y are such that hash(x) != hash(y) but x == y, breaking the requirement on hash values. HTH -- Arnaud From steve at REMOVE-THIS-cybersource.com.au Wed Dec 31 10:33:54 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Dec 2008 15:33:54 GMT Subject: change only the nth occurrence of a pattern in a string References: <0scs26-7a5.ln1@rama.fbx.proxad.net> Message-ID: <016b87de$0$6988$c3e8da3@news.astraweb.com> On Wed, 31 Dec 2008 15:40:32 +0100, TP wrote: > Hi everybody, > > I would like to change only the nth occurence of a pattern in a string. > The problem with "replace" method of strings, and "re.sub" is that we > can only define the number of occurrences to change from the first one. > >>>> v="coucou" >>>> v.replace("o","i",2) > 'ciuciu' >>>> import re >>>> re.sub( "o", "i", v,2) > 'ciuciu' >>>> re.sub( "o", "i", v,1) > 'ciucou' > > What is the best way to change only the nth occurence (occurrence number > n)? Step 1: Find the nth occurrence. Step 2: Change it. def findnth(source, target, n): num = 0 start = -1 while num < n: start = source.find(target, start+1) if start == -1: return -1 num += 1 return start def replacenth(source, old, new, n): p = findnth(source, old, n) if n == -1: return source return source[:p] + new + source[p+len(old):] And in use: >>> replacenth("abcabcabcabcabc", "abc", "WXYZ", 3) 'abcabcWXYZabcabc' > Why this default behavior? For the user, it would be easier to put > re.sub or replace in a loop to change the first n occurences. Easier than just calling a function? I don't think so. I've never needed to replace only the nth occurrence of a string, and I guess the Python Development team never did either. Or they thought that the above two functions were so trivial that anyone could write them. -- Steven From cournape at gmail.com Mon Dec 29 22:19:02 2008 From: cournape at gmail.com (David Cournapeau) Date: Tue, 30 Dec 2008 12:19:02 +0900 Subject: print a vs print '%s' % a vs print '%f' a Message-ID: <5b8d13220812291919h700f1586q5ab68ec6edb927f1@mail.gmail.com> Hi, While working on some python C extensions, I got curious in how things work for printing float objects (and C-level objects which inherit from it). In python 2.6, I understand that the formatting went into surgery for more consistency across platforms. So for example, on windows, complex('inf') would be printed 'inf', and not '1.#INF'. However, I would like some clarifications if possible about the following: a = complex('inf') print a # -> print 'inf' print '%s' % a # -> print 'inf' print '%f' % a # -> print '1.#INF' My understanding is that in the first case, the formatting is controlled through the tp_print and in the second case, from str(a) behavior (tp_str). Can the 3rd one be controled at all ? Or is it going directly through the underlying C runtime, without python doing any formatting (which is how I understand the inconsistency). Is this by design ? thanks, David From rocky at panix.com Thu Dec 11 05:17:09 2008 From: rocky at panix.com (R. Bernstein) Date: Thu, 11 Dec 2008 05:17:09 -0500 Subject: Custom debugger trace hooks Message-ID: A colleague recently asked this: Is there a cleaner way to dump a trace/track of running a python script. With Pydb I made work-around with import pydb pydb.debugger(dbg_cmds=['bt', 'l', 's']*300 + ['c']) So now I have a dump of 300 steps with backtraces, so I can easily compare two executions of the same script to find where they diverged. I think it is a really nice feature. pydb and pdb inherit from the cmd module which does allow pre- and post-command hooks. Neither pdb nor pydb make it easy to add one's own hook. However If there's something you want to run before stepping you can do that by monkey-patching Pdb.precmd: #################### snip import pydb def myprecmd(obj, debug_cmd): """Custom Hook method executed before issuing a debugger command.""" global _pydb_trace obj.do_list('') obj.do_where('10') # limit stack to at most 10 entries return obj.old_precmd(debug_cmd) # is always string 's' in example below _pydb_trace = pydb.Pdb() pydb.Pdb.old_precmd = pydb.Pdb.precmd pydb.Pdb.precmd = myprecmd pydb.debugger(dbg_cmds=['s'] * 30) # .... #################### I believe the same is applicable to pdb, although I haven't investigated. From prologic at shortcircuit.net.au Thu Dec 4 18:51:50 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 5 Dec 2008 09:51:50 +1000 Subject: pretty strange behavior of "strip" In-Reply-To: <4938693F.6090709@yahoo.ca> References: <4938693F.6090709@yahoo.ca> Message-ID: On Fri, Dec 5, 2008 at 9:35 AM, Guy Doune wrote: >>>> test=['03.html', '06.html', 'questions.html', '04.html', 'toc.html', >>>> '01.html', '05.html', '07.html', '02.html', '08.html'] >>>> test > ['03.html', '06.html', 'questions.html', '04.html', 'toc.html', '01.html', > '05.html', '07.html', '02.html', '08.html'] >>>> test[4] > 'toc.html' >>>> test[4].strip('.html') > 'oc' I believe you're after this: >>> test=['03.html', '06.html', 'questions.html', '04.html', 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] >>> test ['03.html', '06.html', 'questions.html', '04.html', 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] >>> from os.path import splitext >>> files = [splitext(x)[0] for x in test] >>> files ['03', '06', 'questions', '04', 'toc', '01', '05', '07', '02', '08'] >>> And no, it's not a bug. Read the docs :) cheers James -- -- -- "Problems are solved by method" From jstroud at mbi.ucla.edu Sat Dec 13 22:27:51 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 13 Dec 2008 19:27:51 -0800 Subject: Need help improving number guessing game In-Reply-To: <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> Message-ID: feba wrote: > This is what I have so far. better? worse? Much better. I didn't check if it works. But you need to figure out a way to give up on your reliance on global variables. They will end up stifling you in the long run when you move to substantial projects. Also, you should start moving the nested if: then: blocks to functions. Finally, you should limit your lines to no more than 80 chars. I do 71. Don't be afraid to use transient variables to help. Be assured that it takes on special intelligence to write unintelligible code at will. Also be assured that fitting everything on one line is not a good way to save time. Aim for clarity. If you want to start off on the right foot, you'll grind on your guessing game until all variables are insulated within local scope and the logic of the program becomes apparent from its architecture as a collection of functions. This is an example of how to combine these concepts: def update_scores(player, p1sc, p2sc): if player == "P1": plsc +=1 else: p2sc +=1 tmplt = "CONGRATULATIONS %s! SCORE -- P1:%s P2:%s" print(tmplt % (player, p1sc, p2sc)) return p1sc, p2sc p1sc, p2sc = update_scores(player, p1sc, p2sc) Finally, put comments on their own lines. Google "python style guide". James From Scott.Daniels at Acm.Org Mon Dec 1 19:35:44 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 01 Dec 2008 16:35:44 -0800 Subject: unicode and hashlib In-Reply-To: References: <8af54b5f-d21b-4794-9bce-afc96ea4db74@j11g2000yqg.googlegroups.com> Message-ID: <6qydnbFh7MOAH6nUnZ2dnUVZ_orinZ2d@pdx.net> Bryan Olson wrote: > ... I think that's good behavior, except that the error message is likely > to end beginners to look up the obscure buffer interface before they find > they just need mystring.decode('utf8') or bytes(mystring, 'utf8'). Oops, careful here (I made this mistake once in this thread as well). You _decode_ from unicode to bytes. The code you quoted doesn't run. This does: >>> a = 'Andr\xe9' >>> b = unicode(a, 'cp1252') >>> b.encode('utf-8') 'Andr\xc3\xa9' >>> b.decode('utf-8') Traceback (most recent call last): File "", line 1, in b.decode('utf-8') File "C:\Python26\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 4: ordinal not in range(128) >>> hashlib.md5(b.encode('utf-8')).hexdigest() '45f1deffb45a5f6c2380a4cee9b3e452' >>> hashlib.md5(b.decode('utf-8')).hexdigest() Traceback (most recent call last): File "", line 1, in hashlib.md5(b.decode('utf-8')).hexdigest() File "C:\Python26\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 4: ordinal not in range(128) > Incidentally, MD5 has fallen and SHA-1 is falling. Python's hashlib also > includes the stronger SHA-2 family. Well, the choice of hash always depends on the app. -Scott From accurateengines at yahoo.com Wed Dec 10 02:45:12 2008 From: accurateengines at yahoo.com (Mike Kolbet) Date: Tue, 9 Dec 2008 23:45:12 -0800 (PST) Subject: Accessing __slots__ from C Message-ID: <385465.38128.qm@web31606.mail.mud.yahoo.com> -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Dec 12 08:31:25 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Dec 2008 08:31:25 -0500 Subject: var or inout parm? In-Reply-To: References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> Message-ID: sturlamolden wrote: > On Dec 12, 1:56 pm, sturlamolden wrote: > >> That is because integers are immutable. When x += 1 is done on an int, >> there will be a rebinding. But try the same on say, a numpy array, and >> the result will be different: > > > And a consequence of this is, if you have a function like > > def foobar(x): > x += 1 > > then the parameter x will be modified given that x have mutable type. > > However, if we have a function like > > def foobar(x): > x = x + 1 > > then x will not be modified, mutable or not. > > (Well, you could abuse operator overlaoding to make unexpected side > effects in the latter case. But except for such insanity it will not > have side-effects.) > This was all thrashed out exhaustively in the still-feared call semantics thread. Yes, augmented operations work differently on mutable and immutable objects. Nothing to see here, move right along ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From callen314 at gmail.com Tue Dec 16 15:44:59 2008 From: callen314 at gmail.com (Craig Allen) Date: Tue, 16 Dec 2008 12:44:59 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> Message-ID: On Dec 14, 6:38 pm, cm_gui wrote: > hahaha, do you know how much money they are spending on hardware to > make > youtube.com fast??? > > > By the way... I know of a very slow Python site called YouTube.com. In > > fact, it is so slow that nobody ever uses it. less than they'd spend to implement it in C From yaksavage at gmail.com Tue Dec 2 22:38:36 2008 From: yaksavage at gmail.com (thor) Date: Tue, 2 Dec 2008 19:38:36 -0800 (PST) Subject: best way to do this References: Message-ID: <137514ca-d16c-4713-b14f-e12ab4f607ab@c36g2000prc.googlegroups.com> On Dec 2, 10:09?pm, TP wrote: > Hi everybody, > > >>> c=[(5,3), (6,8)] > > From c, I want to obtain a list with 5,3,6, and 8, in any order. > I do this: > > >>> [i for (i,j) in c] + [ j for (i,j) in c] > > [5, 6, 3, 8] > > Is there a quicker way to do this? > >>> c = [(5, 3), (6, 8)] >>> [x for t in zip(*c) for x in t] [5, 6, 3, 8] From makobu.mwambiriro at gmail.com Wed Dec 31 16:46:48 2008 From: makobu.mwambiriro at gmail.com (makobu) Date: Wed, 31 Dec 2008 13:46:48 -0800 (PST) Subject: PyS60, GPS and SMS Message-ID: ######################################################## # Send an SMS with your current GPS co-ordinates using a # Nokia SmartPhone and PyS60 # # Timothy Makobu, 01-01-2009 ######################################################## import positioning import messaging import appuifw import sys # Get your GPS co-ordinates # def getCoordinates(): positioning.select_module(positioning.default_module()) positioning.set_requestors([{'type':'service', 'format':'application','data':'position'}]) try: sys.stdout.write('Retrieving GPS co-ordinates ...\n') data = positioning.position(course=1, satellites=1) except: sys.stdout.write('Could not retrieve GPS co-ordinates\n\n\n') sys.exit(-1) else: sys.stdout.write('GPS co-ordinates retrieved\n') return (data['position']['latitude'], data['position'] ['longitude']) # Send your GPS co-ordinates as an SMS # def sendCoordinates(coords, number): message = u'I\'m at location:\nLatitute --> %f\nLongitute --> %f \n' % coords try: sys.stdout.write('Sending SMS ...\n') messaging.sms_send(number, message) except: sys.stdout.write('Could not send SMS :(\n\n\n') sys.exit(-1) else: sys.stdout.write('SMS sent :)\n') if __name__ == '__main__': presetPhoneNumber = None # Enter phoneNumber here eg '+254722000000' phoneNumber = presetPhoneNumber or appuifw.query(u'Enter number: ','text') if not phoneNumber: sys.stdout.write('No number entered; exiting ...\n\n\n') sys.exit(-1) sendCoordinates(getCoordinates(), phoneNumber) From ianare at gmail.com Tue Dec 16 13:20:52 2008 From: ianare at gmail.com (=?ISO-8859-1?B?aWFuYXLp?=) Date: Tue, 16 Dec 2008 10:20:52 -0800 (PST) Subject: sorting for recursive folder rename Message-ID: Hello all, I trying to recursively rename folders and files, and am looking for some ideas on the best way of doing this. The problem is that the given list of items can be in order, and one to all items may be renamed. Here is some preliminary code I have, but which does not work very well. self.toRename has the following structure : [ [original_name, new_name, os.path.isdir] .. ] # define these here for faster processing def split(item): return os.path.split(item) def addSep(path): return os.sep + path + os.sep def recursiveFolderSort(x,y): return cmp(y[0], x[0]) sortedRename = sorted(self.toRename) # make a list of all folders that will be processed foldersToAdjust = [] for item in sortedRename: if item[2] is False: oF = split(item[0])[1] # original folder name nF = split(item[1])[1] # new folder name if oF is not nF: foldersToAdjust.append((oF, nF)) # replace all occurences of folders in path for i in range(len(self.toRename)): for f in foldersToAdjust: oF = addSep(f[0]) # original folder name nF = addSep(f[1]) # new folder name self.toRename[i][0] = self.toRename[i][0].replace(oF,nF) self.toRename[i][1] = self.toRename[i][1].replace(oF,nF) if progressDialog.update(i) is False: error = 'cancelled' break # make sure renaming will be in correct order ! self.toRename.sort(recursiveFolderSort) First problem is adjusting the paths can take a very long time. Second problem is sorting is not always right and files get lost !! Any input welcome. From bearophileHUGS at lycos.com Sat Dec 6 20:31:13 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 6 Dec 2008 17:31:13 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> Message-ID: Erik Max Francis: > your precise proposal has > been brought up countless times on comp.lang.python And something tells me that it will keep coming up many more times in the following years too. Bye, bearophile From gagsl-py2 at yahoo.com.ar Sat Dec 27 03:08:29 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 27 Dec 2008 06:08:29 -0200 Subject: How to display Chinese in a list retrieved from database via python References: <22be506d-91c2-4727-ace7-2e3382b6d214@g3g2000pre.googlegroups.com> <979fdf6d-0500-47ba-87fd-0f0361ca3059@p2g2000prf.googlegroups.com> <19680ed2-c78f-4ab9-8ca0-8ce26fd5b6a7@o4g2000pra.googlegroups.com> Message-ID: En Sat, 27 Dec 2008 03:03:24 -0200, zxo102 escribi?: > On 12?26?, ??3?16?, "Mark Tolonen" > wrote: >> >> I was able to display ?? successfully with this code: >> >> f=open('test.html','wt') >> f.write(''' >> >> test >> \xd6\xd0\xce\xc4''') >> f.close() >> > Mark, > I have exactly copied your code into the htdocs of my Apache > server, > > > > test > \xd6\xd0\xce\xc4 > > but it still shows me \xd6\xd0\xce\xc4. Any ideas? That's not the same thing as Mark T. said. The original was Python code to *write* a test file that you could open in a browser. Things like "\xd6\xd0" are escape sequences interpreted by Python, not meant to literally appear in a file. Like \n -- it means "start a new line", one wants a new line in the output, *not* a backslash and a letter n. "\xd6\xd0" generate *two* bytes, not eight. If the file is interpreted as containing latin-1 characters, you see them as ??. But due to the "charset=gb2312" line, those two bytes together make the ideograph ?. So, write the Python code (from f=open... up to f.close()) in a file and execute it. Then open the generated test.html file. You should see the two ideographs. -- Gabriel Genellina From dotancohen at gmail.com Fri Dec 5 03:12:36 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Fri, 5 Dec 2008 10:12:36 +0200 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <200812050738.17172.list@qtrac.plus.com> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <880dece00812041256x227af79agf9a22226215f3330@mail.gmail.com> <200812050738.17172.list@qtrac.plus.com> Message-ID: <880dece00812050012p1703df91u405caba7ed5b346f@mail.gmail.com> 2008/12/5 Mark Summerfield : > I don't think the book is due in Europe until the end of January, but > could take longer for elsewhere. (Of course Israel is in Europe > according to the Eurovision Song Contest, so you might get lucky:) > Yes, we are in the unique geographical and political position to be in Europe when it suits us, in Asia when it suits us, and to be in the Middle East when it suits us! Thanks! -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-??-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From tjreedy at udel.edu Mon Dec 8 18:06:28 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Dec 2008 18:06:28 -0500 Subject: tabs and spaces in py3k In-Reply-To: References: <774909e2-b248-4251-bbba-deb309e72714@x38g2000yqj.googlegroups.com> Message-ID: inyeol.lee at gmail.com wrote: >> Do the Py3k docs need correction? > > -tt option in python 2.x is now default in python 3.0. > Apparently it got slipped from any documentation, including what's > new. http://bugs.python.org/issue4603 From mail at microcorp.co.za Wed Dec 3 23:38:46 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 4 Dec 2008 06:38:46 +0200 Subject: Python advocacy ... HELP! References: <5f8c1a52-545e-402e-863a-acdf23d04c78@h20g2000yqn.googlegroups.com> Message-ID: <001f01c955ca$3326b7e0$0d00a8c0@hendrik> "Tim Rowe" wrote: > Try asking "Are we teaching computer science, so that the students > will be able to cope with whatever they meet once they graduate, or > are we teaching computer programming, in a couple of specific > languages, so that the students will be completely unprepared if they > meet anything else?" What is computer science anyway - as opposed to what the electronic engineering guys do - which is the true science - the programming bits, or the modern hardware bits? Or maybe both? Where are both taught? - Hendrik From martin at marcher.name Mon Dec 29 05:14:12 2008 From: martin at marcher.name (Martin) Date: Mon, 29 Dec 2008 11:14:12 +0100 Subject: game engine (as in rules not graphics) In-Reply-To: References: <402f625f-b835-4cb8-bcea-523756c489ca@g39g2000pri.googlegroups.com> Message-ID: <5fa6c12e0812290214v31439a7ava9225eec2c68ae1a@mail.gmail.com> Hi, 2008/12/29 Phil Runciman : > See: Chris Moss, Prolog++: The Power of Object-Oriented and Logic Programming (ISBN 0201565072) > > This book is a pretty handy intro to an OO version Prolog produced by Logic Programming Associates. > From: Aaron Brady [mailto:castironpi at gmail.com] > Sent: Sunday, 28 December 2008 1:22 p.m. > Not my expertise but here are my $0.02. You are looking for ways to represent rules: buying a house is legal in such and such situation, and the formula for calculating its price is something. You want "predicates" such as InJail, OwnedBy, Costs. > > Costs( New York Ave, 200 ) > InJail( player2 ) > OwnedBy( St. Charles Ave, player4 ) > LegalMove( rolldie ) > LegalMove( sellhouse ) I'm not sure I'm looking for prolog, i had an introductory course back at the university but it didn't exactly like it. I'm after some info how such rules would defined in python (specifically python althou logic programming is probably the more appropriate way). I guess I'm missing quite some basics in the design of such concepts, I'll head back to google to find some introductory stuff now :). regards, Martin -- http://soup.alt.delete.co.at http://www.xing.com/profile/Martin_Marcher http://www.linkedin.com/in/martinmarcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From sonynamratha2009 at gmail.com Wed Dec 24 15:35:40 2008 From: sonynamratha2009 at gmail.com (sony) Date: Wed, 24 Dec 2008 12:35:40 -0800 (PST) Subject: advt Message-ID: <60d51d87-a94d-4fae-b33a-8b1400f31066@i20g2000prf.googlegroups.com> http://www.adztel.blogspot.com/ http://adztel.blogspot.com/2008/12/tatoo-niche-ebooks.html http://adztel.blogspot.com/2008/12/cpa-riches.html http://adztel.blogspot.com/2008/12/value-scan-profile.html http://adztel.blogspot.com/2008/12/keyword-elite-software.html http://adztel.blogspot.com/2008/12/over-1600-nano-technology-companies.html http://adztel.blogspot.com/2008/12/internet-marketing-wish-list.html http://adztel.blogspot.com/2008/12/affilorama.html From missive at hotmail.com Wed Dec 31 12:18:35 2008 From: missive at hotmail.com (Lee Harr) Date: Wed, 31 Dec 2008 21:48:35 +0430 Subject: error on windows with commands.getstatusoutput Message-ID: > Anyhow, I've replaced it with this: > > > from subprocess import Popen, PIPE, STDOUT > p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, > stderr=STDOUT, close_fds=True) > output, unused = p.communicate() > status = p.returncode > > > Does that look more windows-friendly? Unfortunately, no. close_fds is also not available on windows (or at least not when trying to capture stderr with stdout like this.) So, now I'm going with ... p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT) I don't really understand what close_fds does. I only put it in because it was in the example code. I have a report that this code works on windows, and it is also working for me on linux. _________________________________________________________________ More than messages?check out the rest of the Windows Live?. http://www.microsoft.com/windows/windowslive/ From deets at nospam.web.de Fri Dec 5 18:25:14 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 06 Dec 2008 00:25:14 +0100 Subject: Can I load a python program at the interactive >>> prompt? In-Reply-To: References: <269e5d69-02b7-409b-ad53-b7702b6ec13a@i24g2000prf.googlegroups.com> Message-ID: <6ptriqF9gfifU1@mid.uni-berlin.de> Tim Golden schrieb: > walterbyrd wrote: >> I am running cygwin on xp. > > .... and I just noticed this vital bit. So not sure > how much of my other post applies. Sorry. Maybe it'll > help anyway. :) Everything. The atrocity that the windows terminal window is isn't mitigated by an out-of-the-box cygwin. Did anybody *ever* need a rectangular marking mode? You could use rxvt. But that's also far from perfect. Diez From mrnull at gmail.com Sun Dec 14 00:47:31 2008 From: mrnull at gmail.com (Henson) Date: Sat, 13 Dec 2008 21:47:31 -0800 (PST) Subject: XMPP xmpppy - User Authorization References: Message-ID: <66b3831b-b26d-4ce9-80b2-e0e8c85ecbc4@k9g2000vbl.googlegroups.com> In my own bot, using the latest xmpppy, I've been printing everything going to the message handler to the screen. I've yet to see a 'subscribe' string. Has this changed? James Mills wrote: > On Wed, Nov 5, 2008 at 11:28 AM, James Mills > wrote: > > Can anyone shed any light on how I might > > be able to react to "User Authorization Requests" > > from other users on an XMPP server/network > > using teh xmlpp [1] library ? > > [SOLVED}: > > I found out from having a peek at jabberbot [1] > that it was as simple as parsing the message. > > Here's a code snippet: > > > def messageHandler(self, cnx, message): > text = message.getBody() > user = message.getFrom() > > if text is not None: > self.env.log.debug("<%s> %s" % (user, text)) > > if " " in text: > command, args = text.split(" ", 1) > else: > command, text = text, "" > > command = command.upper() > > if command == "SUBSCRIBE": > self._client.Roster.Authorize(user) > reply = "Authorized." > > > --JamesMills > > -- > -- > -- "Problems are solved by method" From alan.gauld at btinternet.com Mon Dec 15 10:17:40 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Dec 2008 15:17:40 -0000 Subject: [Tutor] Having Issues with CMD and the 'python' command References: <49465C32.7020200@gmail.com> Message-ID: "bob gailer" wrote > Try this: > > Start->Settings->Control Panel->System->Advanced->Environment > Variables > Highlight PATH under System Variables & Click Edit. > Add ;C:\python26 And notice that Bob said ADD - DO NOT REPLACE the existing setting or you will likely break stuff and its not easy to fix it afterwards unless you have a full backup to hand!! Alan G. From znikeshoes004 at gmail.com Thu Dec 25 03:45:50 2008 From: znikeshoes004 at gmail.com (www.voguetouch.com) Date: Thu, 25 Dec 2008 00:45:50 -0800 (PST) Subject: www.voguetouch.com sell nike shoes, tshirt, ugg boots, handbags and so on Message-ID: <448b3300-6428-4c7f-a5d4-1036c9ffc2b0@g3g2000pre.googlegroups.com> cheap nike shoes: WWW(VOGUETOUCH)COM We are wholesaler of Nike Jordan and Other Shoes in China. We are a professional exporting company in china. We supply many kinds of Shoes, such as Nike Shoes, Jordan 1-23, Air Jordan, AF1, DUNK, Air max series etc. Most of them are in stock and can be supplied surely on time. All these shoes are packed with original-boxes and cards our price $33jordan shoes,$15tshirt,15sunglasess, $13cap,$33jean, $35bag our website: WWW(VOGUETOUCH)COM MSN:voguetouch01 at msn.com From rt8396 at gmail.com Mon Dec 22 15:00:15 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 12:00:15 -0800 (PST) Subject: I always wonder ... References: <18767.54282.188749.522233@montanaro-dyndns-org.local> <097fc1e1-d0fa-469c-af51-0ccf8ed1542f@35g2000pry.googlegroups.com> Message-ID: <35ef0b14-714a-42ef-abc5-63951a0cb007@e18g2000yqo.googlegroups.com> On Dec 22, 1:54?pm, Christian Heimes wrote: > > you are truly an open minded, intelligent Human being. Thanks for > > blessing use with your wisdom here. We need more like you. Every > > thought, action, fact, must always be questioned, that is what makes > > us human! > > *plonk* so i was wrong about you ;) From ajaksu at gmail.com Mon Dec 22 17:41:49 2008 From: ajaksu at gmail.com (ajaksu) Date: Mon, 22 Dec 2008 14:41:49 -0800 (PST) Subject: python3 urlopen(...).read() returns bytes References: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> Message-ID: <5496b34d-7ce4-4281-9f01-aed12dab9fd3@f33g2000vbf.googlegroups.com> On Dec 22, 8:25?pm, Christian Heimes wrote: > It's not possible unless you know the encoding of the bytes. Network io > only returns byte and you must encode it explicitly. [...] > There is no generic and simple way to detect the encoding of a remote > site. Sometimes the encoding is mentioned in the HTTP header, sometimes > it's embedded in the section of the HTML document. That said, a "decode to declared HTTP header encoding" version of urlopen could be useful to give some users the output they want (text from network io) or to make it clear why bytes is the safe way. Daniel From rt8396 at gmail.com Mon Dec 22 19:49:59 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 16:49:59 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <6ra8t0F925rU1@mid.individual.net> <29feda0d-6432-4cb9-8809-e4d4a7798601@e1g2000pra.googlegroups.com> <6raeb8F9s47U2@mid.individual.net> <25b1ece0-712b-4516-af28-88c50d00ab8c@s9g2000prg.googlegroups.com> Message-ID: On Dec 22, 6:18?pm, Aaron Brady wrote: > Us small-minded people have hopes and dreams just like anybody else, > Thurston. Now thats the kind of friendly banter this group could use. Instead of people acting as if their bowel-movements smell like bakery fresh cinnamon rolls! From bearophileHUGS at lycos.com Sun Dec 7 15:37:16 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 7 Dec 2008 12:37:16 -0800 (PST) Subject: Python for kids? References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> Message-ID: <53f406ed-c261-4d86-a8dc-4001d10d05b5@s20g2000yqh.googlegroups.com> On Dec 7, 9:13?pm, "Russ P." wrote: > I have a 12-year-old son who spends too much time playing Xbox live > and watching silly YouTube videos. I would like to try to get him > interested in programming. Lot of people learn to program even before age of 12. But I think it's better for you to help him get interest in problem- solving and some of the other bases of the mathematic, scientific and computational mindset. Once those interests are in place, he will probably go looking by himself for things like programming languages, math and science (of course at that point a gentle guide toward good ideas, good problems to solve, good books to read and good programming languages, helps). Otherwise you risk pushing a person to learn using a tool (programming is interesting by itself, but it's mostly a tool still) before having any use for such tool or desire to learn it. And this may lead to someone with no passion to solve problems and learn. Bye, bearophile From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 22:20:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2008 03:20:21 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c47ad$0$20656$c3e8da3@news.astraweb.com> Message-ID: <015c5bc6$0$20656$c3e8da3@news.astraweb.com> On Sat, 20 Dec 2008 01:54:35 +0000, Steven D'Aprano wrote: > There clearly is a need for a more heavyweight formatting solution than > % and string.Template. There are things that can't be done easily with % > alone, and format() will make them much simpler. I have no objection to > the addition of the format() method (although I wonder whether it might > have been better as a function). Except of course there is a format() function. Like len(), str() etc, it just calls the appropriate special method on the argument: format(obj, format_spec) -> obj.__format__(format_spec) -- Steven From guido at python.org Sat Dec 6 15:29:09 2008 From: guido at python.org (Guido van Rossum) Date: Sat, 6 Dec 2008 12:29:09 -0800 Subject: [Python-Dev] "as" keyword woes In-Reply-To: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> Message-ID: On Sat, Dec 6, 2008 at 11:38 AM, Warren DeLano wrote: [...] > There, I assert that 'object.as(class_reference)' is the simplest and > most elegant generalization of this widely-used convention. Indeed, it > is the only obvious concise answer, if you are limited to using methods > for casting. Well, that's too bad, as 'as' is now a reserved word. > Although there are other valid domain-specific uses for "as" as either a > local variable or attribute names (e.g. systematic naming: as, bs, cs), > those aren't nearly as important compared to "as" being available as the > name of a generalized casting method -- one that is now strictly denied > to users of Python 2.6 and 3. If you had brought this up 5-10 years ago when we first introduced 'as' as a semi-keyword (in the import statement) we might have been able to avert this disaster. As it was, nobody ever brought this up AFICR, so I don't think it's *that* obvious. > As someone somewhat knowledgable of how parsers work, I do not > understand why a method/attribute name "object_name.as(...)" must > necessarily conflict with a standalone keyword " as ". It seems to me > that it should be possible to unambiguously separate the two without > ambiguity or undue complication of the parser. That's possible with sufficiently powerful parser technology, but that's not how the Python parser (and most parsers, in my experience) treat reserved words. Reserved words are reserved in all contexts, regardless of whether ambiguity could arise. Otherwise *every* reserved word would have to be allowed right after a '.', and many keywords would have to be allowed as identifiers in other contexts. That way lies PL/1... Furthermore, how would you define the 'as' method? Would you also want to be allowed to write def as(self, target): ... ??? Trust me, it's a slippery slope, and you don't want to start going down there. > So, assuming I now wish to propose a corrective PEP to remedy this > situation for Python 3.1 and beyond, what is the best way to get started > on such a proposal? Don't bother writing a PEP to make 'as' available as an attribute again. It has no chance of being accepted. Instead, think of a different word you could use. -- --Guido van Rossum (home page: http://www.python.org/~guido/) From benjamin.kaplan at case.edu Sat Dec 13 16:23:31 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sat, 13 Dec 2008 16:23:31 -0500 Subject: stable algorithm with complexity O(n) In-Reply-To: <1ff0d642-b560-433c-b793-3a05f5b051b9@g1g2000pra.googlegroups.com> References: <6qidmbFc4qduU1@mid.uni-berlin.de> <1ff0d642-b560-433c-b793-3a05f5b051b9@g1g2000pra.googlegroups.com> Message-ID: 2008/12/13 Aaron Brady > On Dec 13, 1:17 pm, Duncan Booth wrote: > > "Diez B. Roggisch" wrote: > > > > > > > > > David Hl??ik schrieb: > > >> Hi guys, > > > > >> i am really sorry for making offtopic, hope you will not kill me, but > > >> this is for me life important problem which needs to be solved within > > >> next 12 hours.. > > > > >> I have to create stable algorithm for sorting n numbers from interval > > >> [1,n^2] with time complexity O(n) . > > > > >> Can someone please give me a hint. Would be very very thankful! > > > > > Unless I grossly miss out on something in computer science 101, the > > > lower bound for sorting is O(n * log_2 n). Which makes your task > > > impossible, unless there is something to be assumed about the > > > distribution of numbers in your sequence. > > > > > Who has given you that assignment - a professor? Or some friend who's > > > playing tricks on you? > > > > I think you must have fallen asleep during CS101. The lower bound for > > sorting where you make a two way branch at each step is O(n * log_2 n), > but > > if you can choose between k possible orderings in a single comparison you > > can get O(n * log_k n). > > > > To beat n * log_2 n just use a bucket sort: for numbers with a known > > maximum you can sort them digit by digit for O(n log_k n), and if you > don't > > restrict yourself to decimal then k can be as large as you want, so for > the > > problem in question I think you can set k=n and (log_n n)==1 so you get > > O(n) > > Minor detail: with k= n, you have log_n (n^2)= 2, so you get O(2n)= O > (n). Same answer. > > The generic sort theorems also assume you can compare arbitrarily > large numbers in constant time, which isn't true. That is, for any > given machine, there exist numbers that you can't compare on them in > constant time. But with a known upper bound k, you can just use a k- > bit machine. > > So, what's the group policy on helping with homework? rhetorical> The policy is "don't do the homework for them". It's more for people who post "write a O(n) sort algorithm for integers in a range [0, n^2]" with a subject of "URGENT: RESPOND QUICKLY". The OP asked for advice on this problem, not for someone to give him the algorithm. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmurray at bitdance.com Thu Dec 11 12:24:44 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Thu, 11 Dec 2008 12:24:44 -0500 (EST) Subject: newbie question: if var1 == var2: In-Reply-To: <87abb21xzm.fsf@daycos.com> References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> Message-ID: On Thu, 11 Dec 2008 at 10:24, Kirk Strauser wrote: > At 2008-11-29T04:02:11Z, Mel writes: > >> You could try >> >> for item in fname: >> item = item.strip() > > This is one case where I really miss Perl's "chomp" function. It removes a > trailing newline and nothing else, so you don't have to worry about losing > leading or trailing spaces if those are important to you. >>> ' ab c \r\n'.rstrip('\r\n') ' ab c ' >>> ' ab c \n'.rstrip('\r\n') ' ab c ' >>> ' ab c '.rstrip('\r\n') ' ab c ' --RDM From jstroud at mbi.ucla.edu Fri Dec 5 23:36:03 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 05 Dec 2008 20:36:03 -0800 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: Of course I meant class C: def me.method(arg): me.value = arg James From Scott.Daniels at Acm.Org Sun Dec 14 19:14:14 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 14 Dec 2008 16:14:14 -0800 Subject: Output to file gets lost - don't know where to look ... In-Reply-To: References: <26a47940-c997-4da4-8f05-205b8d3001a8@d42g2000prb.googlegroups.com> Message-ID: uair01 wrote: >> I will try the python program outside of IDLE. > > Yes, running the program from the Linux shell instead of from IDLE > produces all output correctly. > Now I'll have to look for a new simple development environment :-( > I think I'll try SPE that has worked well for me ... Or you could try to distill the problem to a simple case and by so doing, improve IDLE for everyone. I'd start by seeing if changing >> .../idlelib/CallTipWindow.py", line 126, in hidetip from: >> self.label.destroy() to: if self.label is not None: self.label.destroy() and seeing if that quick-fix lets you go farther. --Scott David Daniels Scott.Daniels at Acm.Org From peter.anderson at internode.on.net Mon Dec 1 23:46:28 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Tue, 02 Dec 2008 15:46:28 +1100 Subject: Emacs vs. Eclipse vs. Vim In-Reply-To: <493446DC.7030908@gmail.com> References: <493446DC.7030908@gmail.com> Message-ID: <4934BDA4.4080209@internode.on.net> Stef asked: >/ />/ As a fall-back I also use EditPlus (see />/ http://www.editplus.com/index.html ). Its only for Windows /but PyScripter is also only for windows ;-) >/ and its shareware so you need to pay for it. Its clip library makes it />/ a VERY GOOD text editor. It's a real shame there are NO text editors />/ with such a comprehensive and easy to modify clip library function (I />/ would be really pleased to be proven wrong on this last point :-) ). /What so great about it ? I think you would really need to try it. As I said yesterday, I find the clip library really very useful; its simple to use and easy to create/extend. Here is a short piece of clip library from a HTML clip lib: #T=Bold ^! #T=Italic ^! #T=Underline text ^! #T=Superscript (end note) ^! #T=Code fragment ^! #T=Highligt text - yellow ^! #T=Centre text
    ^!
    Only the text on the line after the "T#" appears in the clip lib side panel. Double click on the text label and EditPlus inserts the clip text into the document being edited. The "^!" is where the cursor sits after the clip insertion. Clips can be inserted "around" existing text. Very neat; if you use Windows its really worth a try. Regards, Peter -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From tangens0-NOSPAM- at -NOSPAM-gmail.com Fri Dec 12 02:24:16 2008 From: tangens0-NOSPAM- at -NOSPAM-gmail.com (Tobias Andersson) Date: Fri, 12 Dec 2008 08:24:16 +0100 Subject: Bidirectional Networking In-Reply-To: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> Message-ID: <6qeht0Fc3541U1@mid.individual.net> Emanuele D'Arrigo skrev: > [...] What if the server > wanted to notify the client of something of interest, i.e. new data > that the client should take into consideration and potentially > process? If the protocol is relatively simple perhaps you can implement something similar to IMAP's "IDLE": http://www.faqs.org/ftp/rfc/rfc2177.txt Basically the client (when having nothing important to do) sends the "idle" command and then listens for messages from the server until "idle" is canceled. But looking into "circuits" as suggested by James seems like a good idea also. HTH /TA From Ron.Barak at lsi.com Thu Dec 25 08:04:36 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Thu, 25 Dec 2008 13:04:36 +0000 Subject: seek() returns unexpected results In-Reply-To: References: Message-ID: <7F0503CD69378F49BE0DC30661C6CCF602494703@enbmail01.lsi.com> Hi, When using seek() with a certain text file, I get strange results. I looked at the text file with a binary editor and verified with 'file', and it's an ASCII English text file. Running the script on other text files gives the expected output. Could you suggest the reason ? In the outputs below, when using generator.py as input for generator.py the 'diff' is a nice progression as expected. ('diff' is the difference between the file pointer location and the number of characters read up to now). However, when using sac.log as input for generator.py the 'diff' is a strange series: 1, 2, 1, 2, 3, 4, 5, 6 Running generator.py on a bigger portion of sac.log produces these 'diff's: 1, 2, 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, 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, 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, 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, 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, 32, 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, 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, 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, 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, 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, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 Thanks, Ron. ________________________________ $ cat -n generator.py 1 #!/usr/bin/env python 2 3 import gzip 4 import sys 5 from Debug import _line as line 6 7 class LogStream(): 8 9 def __init__(self, filename): 10 self.filename = filename 11 self.input_file = self.open_file(filename) 12 13 def open_file(self, in_file): 14 try: 15 f = gzip.GzipFile(in_file, "r") 16 f.readline() 17 except IOError: 18 f = open(in_file, "r") 19 f.readline() 20 f.seek(0) 21 return(f) 22 23 def line_generator(self): 24 while True: 25 line_ = self.input_file.readline() 26 print line()+". line_==|"+line_.strip()+"|" 27 self.total_chars += len(line_) 28 print line()+". line length:",len(line_),"; file pointer:",self.input_file.tell(), 29 print "; total chars:",self.total_chars,"; diff:",self.input_file.tell() - self.total_chars 30 if not line_: 31 break 32 yield line_.strip() 33 34 35 if __name__ == "__main__": 36 37 filename = sys.argv[1] 38 log_stream = LogStream(filename) 39 log_stream.input_file.seek(0) 40 log_stream.total_chars = 0 41 line_generator = log_stream.line_generator() 42 for i in range(8): 43 line_ = line_generator.next() $ python generator.py generator.py 26. line_==|#!/usr/bin/env python| 28. line length: 22 ; file pointer: 23 ; total chars: 22 ; diff: 1 26. line_==|| 28. line length: 1 ; file pointer: 25 ; total chars: 23 ; diff: 2 26. line_==|import gzip| 28. line length: 12 ; file pointer: 38 ; total chars: 35 ; diff: 3 26. line_==|import sys| 28. line length: 11 ; file pointer: 50 ; total chars: 46 ; diff: 4 26. line_==|from Debug import _line as line| 28. line length: 32 ; file pointer: 83 ; total chars: 78 ; diff: 5 26. line_==|| 28. line length: 1 ; file pointer: 85 ; total chars: 79 ; diff: 6 26. line_==|class LogStream():| 28. line length: 19 ; file pointer: 105 ; total chars: 98 ; diff: 7 26. line_==|| 28. line length: 5 ; file pointer: 111 ; total chars: 103 ; diff: 8 $ python generator.py sac.log 26. line_==|Dec 15 15:45:20 iSW-00-090 svm_sac[1714]: AGENT[0]: [tv_expand ] tv_expand:........[Domain 5:DVol1_3CG1-MM-1229347528T0] maxVolCapacityMB:....[5121] tempVolCapacityMB:...[512] fivePercentMB:.......[256] expandedTempVolCap:..[1024]| 28. line length: 246 ; file pointer: 247 ; total chars: 246 ; diff: 1 26. line_==|Dec 15 15:45:20 iSW-00-090 svm_sac[1714]: AGENT[0]: [daemon_send_expand_reque] [Domain 5:DVol1_3CG1-MM-1229347528T0]: Add expand request up to 1024 MB (2097152 sectors)| 28. line length: 170 ; file pointer: 418 ; total chars: 416 ; diff: 2 26. line_==|Dec 15 15:45:20 iSW-00-090 svm_sac[1746]: AGENT[0]: [domain_expand_exec ] [Domain 5:DVol1_3CG1-MM-1229347528T0]: Send expand up to 1024 MB (2097152 sectors): success| 28. line length: 172 ; file pointer: 589 ; total chars: 588 ; diff: 1 26. line_==|Dec 15 15:45:21 iSW-00-090 svm_sac[1744]: AGENT[0]: [domain_poll ] Domain [Domain 5]: SVM reported volume manager setup changed| 28. line length: 141 ; file pointer: 731 ; total chars: 729 ; diff: 2 26. line_==|Dec 15 15:45:21 iSW-00-090 svm_sac[1744]: AGENT[0]: [domain_poll ] Domain [Domain 5]: SVM reported multiview setup changed| 28. line length: 136 ; file pointer: 868 ; total chars: 865 ; diff: 3 26. line_==|Dec 15 15:45:21 iSW-00-090 svm_sac[1744]: AGENT[0]: [domain_is_setup_changed ] Domain [Domain 5]: Setup CHANGED| 28. line length: 113 ; file pointer: 982 ; total chars: 978 ; diff: 4 26. line_==|Dec 15 15:45:21 iSW-00-090 svm_sac[1744]: AGENT[0]: [domain_get_pages ] Domain [Domain 5]: Asked to get setup pages| 28. line length: 124 ; file pointer: 1107 ; total chars: 1102 ; diff: 5 26. line_==|Dec 15 15:45:21 iSW-00-090 svm_sac[1744]: AGENT[0]: [svm_get_pages ] SVM [Domain 5:12345]: got all setup pages| 28. line length: 122 ; file pointer: 1230 ; total chars: 1224 ; diff: 6 $ cat generator.py #!/usr/bin/env python import gzip import sys from Debug import _line as line class LogStream(): def __init__(self, filename): self.filename = filename self.input_file = self.open_file(filename) def open_file(self, in_file): try: f = gzip.GzipFile(in_file, "r") f.readline() except IOError: f = open(in_file, "r") f.readline() f.seek(0) return(f) def line_generator(self): while True: line_ = self.input_file.readline() print line()+". line_==|"+line_.strip()+"|" self.total_chars += len(line_) print line()+". line length:",len(line_),"; file pointer:",self.input_file.tell(), print "; total chars:",self.total_chars,"; diff:",self.input_file.tell() - self.total_chars if not line_: break yield line_.strip() if __name__ == "__main__": filename = sys.argv[1] log_stream = LogStream(filename) log_stream.input_file.seek(0) log_stream.total_chars = 0 line_generator = log_stream.line_generator() for i in range(8): line_ = line_generator.next() -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Fri Dec 5 19:19:31 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sat, 06 Dec 2008 01:19:31 +0100 Subject: Multiple Versions of Python on Windows XP In-Reply-To: References: <4934de22$0$27863$9b622d9e@news.freenet.de> <493592EE.9090005@v.loewis.de> <49378804.2050807@g.nevcal.com> <4937DB4B.7060001@ncf.ca> Message-ID: <4939C513.2090802@v.loewis.de> Glenn Linderman wrote: > I'm unaware of it needing to handle multiple extensions > from the command line or via double clicking in Explorer, so was > exploiting the extra level of indirection to save typing, and make the > command simpler to remember. Python *does* provide multiple useful extensions that you might want to double-click, namely .py and .pyw. It also provides an association for .pyc; whether that is useful or not may be debatable. > Not sure what your reference to an editor is about. This I also wonder about. Apparently, his editor has the capability of running Python scripts, and then his question is how to make the editor use a different Python version (and he assumed that there is the notion of a "default" Python version in Windows, and that the editor would just run the default). I'm still very unsure as to what his editor actually does, but his report of success seems to indicate that it choses the interpreter associated with .py. Regards, Martin From mccredie at gmail.com Mon Dec 8 23:36:17 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 8 Dec 2008 20:36:17 -0800 (PST) Subject: How to initialize a class variable once References: Message-ID: On Dec 8, 8:08?pm, Roy Smith wrote: > I've got a class with a class variable: > > class Foo: > ? ?_map = {} > > How do I make sure this only gets initialized the *first* time the > module containing the class is imported? ?What appears to be happening > as it stands is each time the module gets imported, Foo._map get re- > initialized. Unless you are calling reload() on the module, it will only ever get _loaded_ once. Each additional import will just yield the existing module. Perhaps if you post an example of the behavior that leads you to believe that the class variables are getting reinitialized I can provide more useful help. Matt From dstanek at dstanek.com Thu Dec 25 19:05:47 2008 From: dstanek at dstanek.com (David Stanek) Date: Thu, 25 Dec 2008 19:05:47 -0500 Subject: Exec inside a class method to call other class methods? In-Reply-To: <495415C8.2050205@sympatico.ca> References: <4953CF57.8080905@sympatico.ca> <495415C8.2050205@sympatico.ca> Message-ID: On Thu, Dec 25, 2008 at 6:22 PM, Matthew Dubins wrote: > Each type does contain its own parsing method. It's just that, as it > stands, one method is being used to shunt off the data to the correct > parsing method. > Not really. You have all of the parsing methods in a single class. Is it possible for each data class to have a parse method? class DOB(object): def parse(...): pass There are many pros and cons do this way of doing things. Google polymorphism and possibly duck typing to see some interesting discussions. -- David http://www.traceback.org From cjw at ncf.ca Sun Dec 28 18:26:38 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sun, 28 Dec 2008 18:26:38 -0500 Subject: multiply each element of a list by a number In-Reply-To: References: <4955e7be$0$4066$ba4acef3@news.orange.fr> Message-ID: <49580B2E.8050009@ncf.ca> skip at pobox.com wrote: > Colin> ... perhaps faster than numpy: > ... > > For extremely short lists, but not for much else: > > % for n in 1 10 100 1000 10000 100000 ; do > > echo "len:" $n > > echo -n "numpy: " > > python -m timeit -s 'import numpy ; a = numpy.array(range('$n'))' 'a*3' > > echo -n "list: " > > python -m timeit -s 'a = range('$n')' '[3*x for x in a]' > > done > len: 1 > numpy: 100000 loops, best of 3: 11.7 usec per loop > list: 1000000 loops, best of 3: 0.698 usec per loop > len: 10 > numpy: 100000 loops, best of 3: 11.7 usec per loop > list: 100000 loops, best of 3: 2.94 usec per loop > len: 100 > numpy: 100000 loops, best of 3: 12.1 usec per loop > list: 10000 loops, best of 3: 24.4 usec per loop > len: 1000 > numpy: 100000 loops, best of 3: 15 usec per loop > list: 1000 loops, best of 3: 224 usec per loop > len: 10000 > numpy: 10000 loops, best of 3: 41 usec per loop > list: 100 loops, best of 3: 2.17 msec per loop > len: 100000 > numpy: 1000 loops, best of 3: 301 usec per loop > list: 10 loops, best of 3: 22.2 msec per loop > > This is with Python 2.4.5 on Solaris 10. YMMV. > Skip, Your comment is justified for len= 100 or 1,000 but not for len= 10,000 or 100,000. I wonder about the variability of the number of loops in your data. I have tried to repeat your test with the program below, but it fails to cope with numpy. The results for Python 2.5 are: list: 0.421 0.253 list: 0.427 0.254 list: 0.420 0.250 list: 0.421 0.255 list: 0.415 0.254 list: 0.423 0.254 list: 0.422 0.256 The results for Python 2.6 are: list: 0.388 0.228 list: 0.410 0.225 list: 0.384 0.227 list: 0.389 0.226 list: 0.390 0.227 The script used above for both 2.5 and 2.6: # speedUgh.py To compare array timing ##import numpy import timeit as _t m= 100 # number of repetitions values= (10, 100) numpyRes= [] listRes= [] for n in values: sn= 'numpy.arange(' + str(n) + ')*3' t= _t.Timer(sn) ## r= t.repeat(3, m) ## numpyRes.append(sum(t.repeat(3, m)) * 1000000/(3*m*n)) sl='a= [3*k for k in range(' + str(n) + ')]' t= _t.Timer(stmt= sl) listRes.append( sum(t.repeat(3, m)) * 1000000/(3*m*n)) ##print 'numpy:', len(values)*'%8.3f' % tuple(numpyRes) print ' list:', len(values)*'%8.3f' % tuple(listRes) Colin W. From jcd at sdf.lonestar.org Mon Dec 1 11:03:04 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 01 Dec 2008 11:03:04 -0500 Subject: pydoc enforcement. In-Reply-To: <6ccec696-a8bb-4818-a016-642514677b70@b38g2000prf.googlegroups.com> References: <6ccec696-a8bb-4818-a016-642514677b70@b38g2000prf.googlegroups.com> Message-ID: <1228147384.32081.5.camel@aalcdl07.lib.unc.edu> On Sun, 2008-11-30 at 16:27 -0800, ken.faulkner at gmail.com wrote: > I've been thinking about implementing (although no idea yet *HOW*) the > following features/extension for the python compile stage and would be > interested in any thoughts/comments/flames etc. > > Basically I'm interested adding a check to see if: > 1) pydoc's are written for every function/method. > 2) There are entries for each parameter, defined by some > predetermined syntax. > > My idea is that as much as I love dynamic typing, there are times when > using some modules/API's that have less than stellar documentation. I > was thinking that if it was possible to enable some switch that > basically forced compilation to fail if certain documentation criteria > weren't met. > > Yes, it should be up to developers to provide documentation in the > first place. Or, the client developer might need to read the source > (IF its available)... but having some "forced" documentation might at > least ease the problem a little. > > For example (half borrowing from Javadoc). > > class Foo( object ): > > def bar( self, ui ): > pass > > > Would fail, since the bar method has an "unknown" parameter called > "ui". > What I think could be interesting is that the compiler forces some > documentation such as: > > class Foo( object ): > > def bar( self, ui ): > """ > @Param: ui : blah blah blah. > """ > pass > > > The compiler could check for @Param matching each parameter passed to > the method/function. Sure, a lot of people might just not put a > description in, so we'd be no better off. But at least its getting > them *that* far, maybe it would encourage them to actually fill in > details. > > Now ofcourse, in statically typed language, they might have the > description as "Instance of UIClass" or something like that. For > Python, maybe just a description of "Instance of abstract class UI" or > "List of Dictionaries"... or whatever. Sure, precise class names > mightn't be mentioned (since we mightn't know what is being used > then), but having *some* description would certainly be helpful (I > feel). > > Even if no-one else is interested in this feature, I think it could > help my own development (and would be an interested "first change" > into Python itself). > > Apart from bagging the idea, does anyone have a suggestion on where in > the Python source I would start for implementing such an idea? > > Thanks > > Ken For the reasons already stated, I think it's probably a bad idea to enforce this at compile time. I think it's a great idea to make sure that this information is present in all your code, but unless you want to see useless stubs, the correct time to enforce this is at commit time. Don't accept any improperly documented patches. Syntax is not enough to ensure what you want to ensure. The semantics have to be right as well. Cheers, Cliff From pavlovevidence at gmail.com Wed Dec 24 00:36:16 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 23 Dec 2008 21:36:16 -0800 (PST) Subject: Multi-dimension list References: Message-ID: On Dec 23, 10:29?pm, "Steven Woody" wrote: > Hi, > > In the book Python Essential Reference, Chapter 3, when talking about > extended slicing, it gives an example: ?a = m[0:10, 3:20]. ?But I > don't understand how the 'm' was defined. ?What should it looks like? I suspect what the book is saying is that the Python language will accept and multidimensional indexing and slicing (it's legal syntax), even though there are no types built into Python that use multidimensional slicing. However, some third party libraries do provide types that allow multidimensional indexing and slicing, most notably numpy. So, for instance, if you were install numpy, you could get multidimensional arrays and slice 'em up however you'd like: import numpy a = numpy.array([[1,2,3],[4,5,6],[7,8,9]]) print a[1:3,0:2] Carl Banks From castironpi at gmail.com Tue Dec 23 05:58:26 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 23 Dec 2008 02:58:26 -0800 (PST) Subject: wxPython.button.disabled still catching clicks References: <8cb6da6a-7df4-4cce-a28e-385448a25b26@w39g2000prb.googlegroups.com> Message-ID: <1ff2aad7-29a1-48cd-b3de-29fab443aa3e@u18g2000pro.googlegroups.com> On Dec 23, 4:50?am, mynthon wrote: > Hello! (sorry for my english) > > I have a problem with buttons in wxPython. When button is disabled > (by .Disable() or .Enable(False)) it is grayed out but still receive > clicks. > > Eg. i have button that disable itself, runs long action and enable > itself: > > def onClick(self, evt): > ? ? self.btn.Enable(False) > ? ? for i in range (1000): > ? ? ? ? print i > ? ? self.btn.Enable(True) > > when for loop is running button is greyed out and when i click on it > nothing happens but when loop ends another one is started because > button "remebered" thad i click on it when was diabled. My only idea > is to reposition button outside frame instead of disabling it but this > solution is...not good. > > thanks for any help. Ive searched groups, google and it looks that > only i have this problem :) No, it is very common. During your for loop, the loop is dominating the process completely. Events are just building up in the app's message queue, and don't get handled until after you yield on control. If you need to run a long task, look into threading, the OnIdle method, the 'multiprocessing' module, or pump messages during your long task. From rdcollum at gmail.com Thu Dec 18 11:36:57 2008 From: rdcollum at gmail.com (Roger) Date: Thu, 18 Dec 2008 08:36:57 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <71ede5f0-fd88-4155-9f0d-42d0ad5f57dc@v42g2000yqj.googlegroups.com> Message-ID: >funcid1 = root.bind("<1>", lambda e: test()) >funcid2 = root.bind("<1>", lambda e: test2(), add='+') >root.unbind("<1>", funcid2) Isn't this what I've done in my example code? From mail at microcorp.co.za Tue Dec 16 05:43:24 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 16 Dec 2008 12:43:24 +0200 Subject: alt.possessive.its.has.no.apostrophe References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> <49467CE2.3060401@holdenweb.com> <4946826E.7060001@tim.thechases.com> <989de86c-24cc-4ca6-8e9b-82e8ce853c7b@n33g2000pri.googlegroups.com> Message-ID: <002d01c95f6b$33d05340$0d00a8c0@hendrik> "Aaron Brady" wrote: >There's an 'I' in Python. No! It's supposed to be : There's a T in python. "an" is only used when the next word starts with a vowel, as in: It's been an hour now... All this is because English speakers are genetically incapable of moving their tongues. :-) - Hendrik From kyrie at uh.cu Sun Dec 7 09:23:46 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Sun, 07 Dec 2008 09:23:46 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: <1228659826.493bdc7284e77@mail.uh.cu> Quoting James Stroud : > First, here is why the ability to throw an error is a feature: > > class Apple(object): > def __init__(self, appleness): > self.appleness = appleness > def __cmp__(self, other): > assert isinstance(other, Apple), 'must compare apples to apples' > return cmp(self.appleness, other.appleness) > > class Orange(object): pass > > Apple(42) == Orange() I beg to disagree. The right answer for the question "Am I equal to this chair right here?" is not "I don't know", nor "I can't compare". The answer is "No, I'm not a chair, thus I'm not equal to this chair right here". If someone comes to my house, looking for me, he will not run away because he sees a chair before he sees me. Your assert doesn't belong inside the methot, it should be up to the caller to decide if the human-chair comparisons make sense or not. I certainly don't want to be type-checking when looking for an object within a mixed-type collection. > This reminds me of complex numbers: would 4 + 4i be equal to sqrt(32)? I assume you meant sqrt(32i). Well, sqrt is a function, and if its result value is defined as 4+4i, then the answer is 'yes', otherwise, the answer should be no. sqrt(4) is *not* -2, and should not be equal to -2. The standard definition of the square root _function_ for real numbers is to take the non-negative real root. I haven't heard of a standard square root _function_ for complex numbers (there is of course, a definition of square root, but it is not a function). So, if by your definition of sqrt, sqrt(32i) returns a number, there is no ambiguity. -2 is not sqrt(4). If you need the answer to be 'True', you may be asking the wrong question. From vkseashoremack at googlemail.com Sat Dec 20 11:56:29 2008 From: vkseashoremack at googlemail.com (vkseashoremack at googlemail.com) Date: Sat, 20 Dec 2008 08:56:29 -0800 (PST) Subject: foot domme - Free Message-ID: <223f4f8a-afba-4d3a-a804-f15183f56bdb@a12g2000pro.googlegroups.com> foot domme . . . *******CLICK HERE******** http://club247.cn/foot-domme ***************************** . . . . . . . . . . . . foot domme From simonharrison.uk at googlemail.com Mon Dec 8 13:02:05 2008 From: simonharrison.uk at googlemail.com (simonh) Date: Mon, 8 Dec 2008 10:02:05 -0800 (PST) Subject: Beginner trying to understand functions. References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> <9df7549a-f28b-4d39-b105-90c099f472f2@z28g2000prd.googlegroups.com> Message-ID: <040a2896-be99-477e-909c-c55c5a0e6665@y1g2000pra.googlegroups.com> Thanks for the many replies. Thanks especially to Pierre. This works perfectly: def getName(): name = input('Please enter your name: ') print('Hello', name) def getAge(): while True: try: age = int(input('Please enter your age: ')) return age except ValueError: print('That was not a valid number. Please try again.') def checkAge(age,min=18,max=31): if age in list(range(min, max)): print('Come on in!') elif age < min: print('Sorry, too young.') elif age >= max: print('Sorry, too old.') getName() a = getAge() checkAge(a) I am running Python 3, sorry for not stating that originally. From grante at visi.com Sun Dec 14 10:37:25 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 14 Dec 2008 09:37:25 -0600 Subject: 1 or 1/0 doesn't raise an exception References: <49446E39.6020807@tim.thechases.com> Message-ID: On 2008-12-14, Daniel Fetchinson wrote: > Let me just point out that unsuspecting people (like me) might rely on > the whole expression to be evaluated and rely on exceptions being > raised if needed. Short circuit evaluation of booleans is very common (and has been for decades), so I don't know why people would expect something else. -- Grant From prologic at shortcircuit.net.au Thu Dec 18 05:15:39 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 18 Dec 2008 20:15:39 +1000 Subject: socket and subprocess problem In-Reply-To: References: <6d3291c3-4e12-4bdd-884a-21f15f38d105@a12g2000pro.googlegroups.com> <73dca20d-3378-4c96-aa30-f0617f111fa0@i18g2000prf.googlegroups.com> Message-ID: On Thu, Dec 18, 2008 at 8:00 PM, Bryan Olson wrote: > I'd swear James copied my response, except his came first. Even the > formatting came out similar. I hadn't seen his response when I wrote mine, > and wouldn't have bothered posing the same thing again. Great minds think alike huh :) You should check out my circuits (1) library! cheers James 1: http://trac.softcircuit.net.au/circuits/ From cmr.Pent at gmail.com Mon Dec 22 03:15:01 2008 From: cmr.Pent at gmail.com (cmr.Pent at gmail.com) Date: Mon, 22 Dec 2008 00:15:01 -0800 (PST) Subject: Calling ImageMagick's convert Message-ID: Hello group! I'm a Python beginner. I'm trying to call ImageMagick's convert program from my code. My OS is Debian testing, and my version of Python is 2.5. I've just stumbled upon a problem: (1) subprocess.call('convert in.png -resize 640x480 out.png', shell = True) works, but none of the following does: (2) subprocess.call('convert in.png -resize 640x480 out.png') (3) subprocess.call(['convert', 'in.png', '-resize 640x480', 'out.png']) (4) subprocess.call(['convert', 'in.png', '-resize 640x480', 'out.png'], shell = True) In these cases, convert program says 'unrecognized option -resize 640x480'. At the same time, subprocess.call(['ls', '-l']) works as expected. I'd like to use variant (3), as it seems the most handy. I don't understand why is shell = True required in case of convert. Is it a bug in Python, in ImageMagick, or am I missing something very basic here? Any hint appreciated. Andrey From Astley.lejasper at gmail.com Wed Dec 3 15:06:28 2008 From: Astley.lejasper at gmail.com (Astley Le Jasper) Date: Wed, 3 Dec 2008 12:06:28 -0800 (PST) Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> <126ba84a-0ea0-4a91-b7d2-89ed650e5d6c@d32g2000yqe.googlegroups.com> Message-ID: <1f4901bb-012c-4e74-8650-c72d48203822@g38g2000yqn.googlegroups.com> On 3 Dec, 19:49, Philip Semanchuk wrote: > On Dec 3, 2008, at 1:33 PM, Astley Le Jasper wrote: > > > > > On 3 Dec, 16:41, Philip Semanchuk wrote: > >> On Dec 3, 2008, at 10:29 AM, Astley Le Jasper wrote: > > >>> I've included a switch to include or exclude theloggingto console. > >>> Whenloggingonly to file, the script runs fine. > > >>> Of course, I still don't understand whyduallogging, and specifically > >>> to the console, causes a problem and if anyone has any comments ? > >>> about > >>> thedualoutputloggingcode above then I'd still be happy to hear > >>> about it. > > >> Trying to write non-ASCII characters perchance? > > > Errmmm ... that's kind of spoookey. I using UTF-8 encoding as I have a > > lot of European language characters. But would that cause a problem > > when running from crontab but not in the terminal? > > > Go on then ... spill the beans. > > Oh, I don't know exactly. It's just what I thought of when you said ? > that the problem occurs when logging to the console but not to files. ? > I don't have a deep Unix background so I can't give you the details on ? > what "the console" means to a cron job. > > In my experience, the environment in which a cron job runs is ? > different from the environment in which some command line scripts run ? > (remember my earlier suggestion about needing to explicitly set the ? > PATH?) and so if the console for a cron job differed from the console ? > that a Python program sees when run in a terminal, that would not ? > surprise me. > > Hope it's a useful suggestion > Philip I tried using the path variables but it didn't help. There again, I didn't really understand what was being passed in the path variables and, rather than just copying and pasting, I wanted to look up further info to get to grips with it. I've got something that works, so now the pressure is off I can spend some time looking it up. [sigh ... my experiences with linux haven't been that good so far. It is, if nothing else, interesting] Thanks ALJ From steve at REMOVE-THIS-cybersource.com.au Sat Dec 20 21:07:19 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Dec 2008 02:07:19 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> <59153e28-bf86-4158-96d9-23aa5b9f0205@j35g2000yqh.googlegroups.com> <7889a362-d96e-4f1f-a66b-ef52b9cdb047@q26g2000prq.googlegroups.com> <85f91606-b589-425d-9636-4636c8ccbc4f@r34g2000vbp.googlegroups.com> <6b4176c3-49ce-4e7c-bced-07d8d19bc0f4@s20g2000yqh.googlegroups.com> Message-ID: <015d9c20$0$20656$c3e8da3@news.astraweb.com> On Sat, 20 Dec 2008 16:01:58 -0800, r wrote: > Just to be on record, i am OK with adding a new way to do this as long > as the old C style str format does not ever go away. I don't like 20 > ways to do the same thing, but i really like the compact way of > %formating now. % formatting isn't compact unless you are only doing trivial substitutions. > My complaint is the deprecation of %formating. % formatting hasn't been deprecated. All this Sturm und Drang over nothing. > Maybe > i'll use the new syntax to print a tuple or two, but that is the only > use i have for it ;). Good for you. If your code is that trivial, then you're lucky. > Slowing down Python even more than it is, is suicide. Oh noes, we're all gonna die!!! Just out of curiosity "r", how old are you? 14? 15? You're remarkably mature for a 15 year old. -- Steven From hniksic at xemacs.org Mon Dec 22 02:40:40 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 22 Dec 2008 08:40:40 +0100 Subject: How to represent a sequence of raw bytes References: Message-ID: <87k59sodxj.fsf@mulj.homelinux.net> "Steven Woody" writes: > What's the right type to represent a sequence of raw bytes. In C, > we usually do > > 1. char buf[200] or > 2. char buf[] = {0x11, 0x22, 0x33, ... } > > What's the equivalent representation for above in Python? import array buf = array.array('b', [0x11, 0x22, ...]) It automatically retrieves byte values without having to call ord(), and it allows changing them. It also has a C API for getting to the address of the underlying buffer. From inq1ltd at inqvista.com Thu Dec 11 14:58:16 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Thu, 11 Dec 2008 14:58:16 -0500 Subject: Problems running on HP Intel duo core machine In-Reply-To: References: <200809221443.25765.inq1ltd@inqvista.com> <200812051608.56335.inq1ltd@inqvista.com> Message-ID: <200812111458.16157.inq1ltd@inqvista.com> py help, I produced a program that runs on windows. One client is using an HP machine with an Intel cpu E2200 @ 2.2ghz., and with .99 G ram. The machine is using Win XP Pro 32 bit OS with service pack 2 I ran Dependency Walker and everything is OK. I used py2exe to build the exe file with bundle files:1 and also 3, with the same traceback results. I created a test print module that imports both win32api and win32ui modules and its only job is to print a page of text. The first module that is imported is win32api. line 8 of that module adds to the path the module named 'win32api.pyd'. The import is is completed without error. The next module that is imported is win32ui. line 8 of that module adds to the path a module named 'win32ui.pyd'. The search for the win32ui.pyd module seems to be the cause of the problem. Traceback: ImportError: Dll load failed: The specified module could not be found. Both modules 'win32api.pyd' and win32ui.pyd are in the same directory. Below is a copy of the win32ui.py module. The only difference between this and win32api.py module is the name that is installed when creating the path. def __load(): import imp, os, sys try: dirname = os.path.dirname(__loader__.archive) except NameError: dirname = sys.prefix path = os.path.join(dirname, 'win32ui.pyd') #print "py2exe extension module", __name__, "->", path mod = imp.load_dynamic(__name__, path) ## mod.frozen = 1 __load() del __load The only difference I can find is that this program works fine on every machine that it is tried on except the HP duo core machine, with Intel E2200 cpu. Somehow the path is affected? I've tried all of the suggestions and checked a lot of things but I'm not there yet, Any suggestions would be helpful. jim-on-linux From clp at rebertia.com Mon Dec 29 07:10:46 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 29 Dec 2008 04:10:46 -0800 Subject: Unicode encoding - ignoring errors In-Reply-To: <4958BD31.1010801@logix.net.nz> References: <4958BD31.1010801@logix.net.nz> Message-ID: <47c890dc0812290410u25f9e69oecdcc0e859f9b10e@mail.gmail.com> On Mon, Dec 29, 2008 at 4:06 AM, Michal Ludvig wrote: > Hi, > > in my script I have sys.stdout and sys.stderr redefined to output > unicode strings in the current system encoding: > > encoding = locale.getpreferredencoding() > sys.stdout = codecs.getwriter(encoding)(sys.stdout) > > However on some systems the locale doesn't let all the unicode chars be > displayed and I eventually end up with UnicodeEncodeError exception. > > I know I could explicitly "sanitize" all output with: > > whatever.encode(encoding, "replace") > > but it's quite inconvenient. I'd much prefer to embed this "replace" > operation into the sys.stdout writer. > > Is there any way to set a conversion error handler in codecs.getwriter() > or perhaps chain it with some other filter somehow? I prefer to have > questionmarks in the output instead of experiencing crashes with > UnicodeEncodeErrors ;-) You really should read the fine module docs (namely, http://docs.python.org/library/codecs.html ). codecs.getwriter() returns a StreamWriter subclass (basically). The constructor of said subclass has the signature: StreamWriter(stream[, errors]) You want the 'errors' argument. So all you have to do is add one argument to your stdout reassignment: sys.stdout = codecs.getwriter(encoding)(sys.stdout, 'replace') Yay Python, for making such things easy! Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From nabla.kvadrat at gmail.com Thu Dec 11 00:55:16 2008 From: nabla.kvadrat at gmail.com (Nabla Kvadrat) Date: Thu, 11 Dec 2008 06:55:16 +0100 Subject: multiprocessing+simplehttpserver+windows Message-ID: Hi, can someone please help me with/explain if following problem can be somehow resolved? I have Py2.6.1 win32 and I'm playing around with multiprocessing module. Trying examples here: http://docs.python.org/library/multiprocessing.html#examples. Example with SimpleHTTPServer.HttpServer don't work because of socket.fromfd in multiprocessing.reduction. If number of processes is >1 it ends with traceback ....... pickle.: 'module' object has no attribute 'fromfd'. As I understand socket.fromfd on windows is not implemented (?), so why the example script is care about platform if sys.platform == 'win32': import multiprocessing.reduction and finally, is there some easy (no patching and recompiling python from source) way to get this example to work on win32 platform? Thanks for any help, I'm Python amateur... N. From Scott.Daniels at Acm.Org Wed Dec 24 15:22:07 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 24 Dec 2008 12:22:07 -0800 Subject: Doing set operation on non-hashable objects In-Reply-To: <3a87eb6a-13ff-4aea-8835-3a233cc6cfc4@w39g2000prb.googlegroups.com> References: <3a87eb6a-13ff-4aea-8835-3a233cc6cfc4@w39g2000prb.googlegroups.com> Message-ID: 5lvqbwl02 at sneakemail.com wrote: > ... "db" is a dict, where the values are also dicts. > A function searches through db and returns a list of values, each of > which is a dict as described above. > I need to perform set operations on these lists (intersection and > union) > However the objects themselves are not hashable, and therefore can't > be in a set, because they are dicts. > I'm not sure how large each set will be, but the point is I'm trying > to avoid anything looking like an O(n^2) algorithm, so I can't just > use naive double-looping to check for intersection/union on a pair of > lists. Well, if the lists are ordered, you can do intersection and union in O(n) time. If they are orderable, you can sort each first, giving O(n log n). Note you can do lst.sort(key=id) which will sort on ids. > What I really need is a set of pointers, so at the end of the > operation I have the actual objects pointed to. Can I somehow use the > object IDs as set elements, then recreate a list with the actual > objects they point to? > How do you get the object back from an ID in python? You don't; you remember the mapping in a dictionary and look it up. If there were a way to go from id to object, the whole idea of garbage collection and reference counts would fly out the window, leading to nasty crashes (or you might get to an object that is the re-used id of an older object). --Scott David Daniels Scott.Daniels at Acm.Org From roy at panix.com Sun Dec 14 21:18:03 2008 From: roy at panix.com (Roy Smith) Date: Sun, 14 Dec 2008 21:18:03 -0500 Subject: [OT] stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > All the positive thinking in the world won't help you: > > * make a four-sided triangle; > > * split a magnet into two individual poles; These two are fundamentally different problems. The first is impossible by definition. The definition of triangle is, "a three-sided polygon". Asking for a "four-sided triangle" is akin to asking for "a value of three which is equal to four". The second is only "impossible" because it contradicts our understanding (based on observation) of how the physical universe works. Our understanding could simply be wrong. We've certainly been wrong before, and we will undoubtedly be proven wrong again in the future. When it comes to things like electromagnetic theory, it doesn't take too many steps to get us to the fuzzy edge of quantum physics where we know there are huge questions yet to be answered. From ldo at geek-central.gen.new_zealand Thu Dec 4 17:58:24 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 05 Dec 2008 11:58:24 +1300 Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> <126ba84a-0ea0-4a91-b7d2-89ed650e5d6c@d32g2000yqe.googlegroups.com> <6a302e08-e8be-4d5e-b754-11fc18468cc8@v4g2000yqa.googlegroups.com> Message-ID: In message <6a302e08-e8be-4d5e-b754-11fc18468cc8 at v4g2000yqa.googlegroups.com>, Astley Le Jasper wrote: > On Dec 4, 12:34?am, Lawrence D'Oliveiro central.gen.new_zealand> wrote: >> >> For example, here are some headers from a recent run of the >> maildir backup task I have scheduled twice a day: >> >> Subject: Cron $HOME/bin/backupdir $HOME/.maildir >> X-Cron-Env: >> X-Cron-Env: >> X-Cron-Env: >> X-Cron-Env: >> X-Cron-Env: > > Where do you get the emails from? >From my local mailbox on the machine. From pdorange at pas-de-pub-merci.mac.com Tue Dec 23 12:34:42 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Tue, 23 Dec 2008 18:34:42 +0100 Subject: [Offtopic] Re: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> <90f06b27-39da-4f1a-a878-f3972e942d57@s24g2000vbp.googlegroups.com> <62caf93b-0455-4450-9895-8a9d9554f75e@r32g2000vba.googlegroups.com> Message-ID: <1isezkk.51e05y1457jqrN%pdorange@pas-de-pub-merci.mac.com> r wrote: > [...] > Well that shows that even lads with tiny nads can be brave, any of the > other trolls want to expose them selfs? This thread is offtopic, please just keep silent and let it be closed... -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From castironpi at gmail.com Mon Dec 1 21:45:34 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 1 Dec 2008 18:45:34 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <4f31c483-8382-480e-8417-b7eef1b1792d@z1g2000yqn.googlegroups.com> <8c856b01-7f0c-4d5b-a1d2-cfe7dc74389f@w3g2000yqc.googlegroups.com> <1680020c-521c-4498-8e74-92e99c03da6b@w35g2000yqm.googlegroups.com> <0d9d2404-cb3f-4390-b97c-79251db8ac95@k8g2000yqn.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> Message-ID: <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> On Dec 1, 2:29?pm, r wrote: > Rome is Burning! > Pay particular attention to the second paragraph. > > Narcissistic culture > > Main article: The Culture of Narcissism > Historian and social critic Christopher Lasch described this topic in > his book, "The Culture of Narcissism",[3] published in 1979. He > defines a narcissistic culture as one in which every activity and > relationship is defined by the hedonistic need to acquire the symbols > of spiritual wealth, this becoming the only expression of rigid, yet > covert, social hierarchies. It is a culture where liberalism only > exists insofar as it serves a consumer society, and even art, sex and > religion lose their liberating power. > > In such a society of constant competition, there can be no allies, and > little transparency. The threats to acquisitions of social symbols are > so numerous, varied and frequently incomprehensible, that > defensiveness, as well as competitiveness, becomes a way of life. Any > real sense of community is undermined -- or even destroyed -- to be > replaced by virtual equivalents that strive, unsuccessfully, to > synthesize a sense of community. It can mean also many other things. > > Contrary to Lasch, Bernard Stiegler argues in his book, Aimer, > s?aimer, nous aimer: Du 11 septembre au 21 avril, that consumer > capitalism is in fact destructive of what he calls primordial > narcissism, without which it is not possible to extend love to others. > > -food for thought- Off-topic post, defer. I'll take the summary to be true to Lasch's original. He states, "it is a culture where liberalism only exists insofar as it serves a consumer society". But liberalism serves a consumer society to a large, large extent. He states, "...and religion lose their liberating power." But religion has no liberating power. The second sentence in the second paragraph presumably states, "The threats [in such a society]...". If so, it states, In a society of constant competition, competitiveness becomes a way of life; which is trivial. "The threats to acquisitions of social symbols are so numerous, varied and frequently incomprehensible, that defensiveness, as well as competitiveness, becomes a way of life." Is the following also true? That is, the same of goods in general? The threats to acquisitions of goods (presumably durable goods) are so numerous, varied and frequently incomprehensible, that defensiveness, as well as competitiveness, becomes a way of life. If not, then define social symbols as distinct from goods, specifically that the threats to their acquisitions are more numerous, varied, and incomprehensible; or conclude the original is false, or that defensiveness and competitiveness aren't bad. Not to mention, you have to contrive the definitions in order to have defensive( x ) and competitive( x ) both true. Reminds me of Foucault... in the bad way. From castironpi at gmail.com Sat Dec 20 20:55:35 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 20 Dec 2008 17:55:35 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: On Dec 20, 7:38?pm, Steven D'Aprano wrote: > Instead of just whinging, how about making a suggestion to fix it? Go on, > sit down for an hour or ten and try to work out how a BINARY OPERATOR > like % (that means it can only take TWO arguments) can deal with an > arbitrary number of arguments, *without* having any special cases. > > Go on. Take your time. I'll be waiting. Hi, not to take sides, but, there is a possibility. This behavior is currently legal: >>> "%i %%i" % 0 % 1 '0 1' So, just extend it. (Unproduced.) >>> "%i %i" % 0 % 1 '0 1' >>> "%r %i" % (2, 3, 4) % 1 '(2, 3, 4) 1' >>> "%r %i" % (2, 3, 4) '(2, 3, 4) %i' Which is quite clever and way ahead of its (posessive) time. From wx1234 at gmail.com Tue Dec 30 20:46:11 2008 From: wx1234 at gmail.com (dubux) Date: Tue, 30 Dec 2008 17:46:11 -0800 (PST) Subject: TypeError: list indices must be integers Message-ID: <2e5a61c0-fa99-4170-81ca-eb3a10859400@k36g2000pri.googlegroups.com> here is a function i wrote that doesnt work. i wrote to parse a "news" file that is going to work in conjunction with a website via mod_wsgi. my head hurts from looking at it so long. please help! i will further explain in the post. def news(x,y): # usage news(date, number) # x = date/news # y = number news_file = '/home/scam/Desktop/www/info/news' news = open(news_file, 'r') news_list = news.readlines() news.close() if x == 'date': mylist = map(lambda i: news_list[i], filter(lambda i: i%2 == 0, range (len(news_list)))) date = mylist[y] return '
    %s

    ' % (date) if x == 'news': mylist = map(lambda i: news_list[i], filter(lambda i: i%2 == 1, range (len(news_list)))) news = mylist[y] return '%s
    ' % (news) else: return news_list and call it with the follow syntax: news('[date/news]', [any number]) i keep getting "TypeError: list indices must be integers" on the following line "date = mylist[y]" can someone please explain this and give me the proper way to achieve what im trying to do? From stephane_chazelas at yahoo.fr Mon Dec 1 01:36:16 2008 From: stephane_chazelas at yahoo.fr (Stephane CHAZELAS) Date: Mon, 1 Dec 2008 06:36:16 +0000 (UTC) Subject: Python surpasses Perl in popularity? References: <5e87aee0-c7fd-4e9d-befb-0cc01cee64ec@f40g2000pri.googlegroups.com> <49316c95$0$2813$742ec2ed@news.sonic.net> <49322ea2$0$2747$742ec2ed@news.sonic.net> Message-ID: 2008-12-1, 01:10(+01), Sven Mascheck: > In comp.unix.shell Stephane CHAZELAS wrote: > >> The Bourne shell, as can still be found on some systems either in some >> non-standard place (/bin on Solaris, /usr/old/bin on HPUX) or named >> differently [...] > > What do you mean with "non-standard place" here? It's true it was vague and misleading, /bin is not the standard place to look for "sh" as far as the "POSIX" standard is concerned. That doesn't mean that standard commands (POSIX or not) cannot be found in /bin. But /bin/sh has been made a non-standard place for "sh". It's the "legacy" place. Those commands that have not undergone non-backward compatible changes with POSIX can still be found in /bin, the others are to be found in /usr/xpg/bin (for the standard versions). -- St?phane From pruebauno at latinmail.com Mon Dec 15 11:07:50 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Mon, 15 Dec 2008 08:07:50 -0800 (PST) Subject: stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> <015612ac$0$20639$c3e8da3@news.astraweb.com> <52cfb77e-4baf-4fba-8eac-cc6c7ddb5be5@k1g2000prb.googlegroups.com> Message-ID: <8f039dec-1a5e-4b60-9603-81687952fcec@l33g2000pri.googlegroups.com> On Dec 15, 11:05?am, prueba... at latinmail.com wrote: > > Non-comparison sorts are a useful technique, but it's changing the > > problem, and they are only useful in very limited circumstances. There's > > a good reason that most sort routines are based on O(n*log n) comparison > > sorts instead of O(n) bucket sorts or radix sorts. > > This is an assumption that I never quite understood. What most people > want is to have sorted data, they don't care if I used a sorting or > non-sorting comparison to do it. I think it is just that in most cases > n is not very big anyway and comparison sorts make it easier on the > programmer to create arbitrary types that are sortable. I meant they don't care if I use a comparison or non-comparison sort of course. From steve at REMOVE-THIS-cybersource.com.au Tue Dec 9 08:24:32 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Dec 2008 13:24:32 GMT Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> Message-ID: <014e6931$0$20670$c3e8da3@news.astraweb.com> On Tue, 09 Dec 2008 04:39:55 -0800, Paul Boddie wrote: > To be fair to the complainant, before mentioning the GIL, he did > initially get the usual trite fragments of the Zen of Python right back > at him ("simple is better than complex", "special cases aren't special > enough to break the rules"), albeit not the whole thing in its overused, > unabridged form. I think I'd go on a rant if presented with that rather > than the accepted reason for the noted shortcomings of the language: > CPython's parsing technology isn't "sufficiently powerful parser > technology" as GvR himself says [1]. > > Paul > > [1] > http://mail.python.org/pipermail/python-dev/2008-December/084023.html That is not what Guido said. What he actually said was: "That's possible with sufficiently powerful parser technology, but that's not how the Python parser (and most parsers, in my experience) treat reserved words." In other words, with a more powerful parser, it would be POSSIBLE. But that doesn't mean that the only reason Python doesn't do what the OP wants is the lack of such a parser. To give an analogy: with sufficiently powerful automotive technology, we could all have cars capable of accelerating from 0 to 300mph in less than five seconds. (That's faster than the space shuttle accelerates, by the way.) The technology exists: drag racers have it. But the costs (financial and social) would be prohibitive, and so very few people have such cars, and those that do have restrictions on where and when they can use them. What Guido is saying is that even if he agreed with the OP he couldn't add that feature. He's not saying that he agrees with the OP. The Zen gives good reasons for believing that even if Python's parser was sufficiently powerful, he'd still consider the feature undesirable. -- Steven From Scott.Daniels at Acm.Org Mon Dec 8 14:55:30 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 08 Dec 2008 11:55:30 -0800 Subject: Determining whether a variable is less/greater than a range. In-Reply-To: <362ab93b-b804-4ebe-a22f-e422feb301c8@c1g2000yqg.googlegroups.com> References: <362ab93b-b804-4ebe-a22f-e422feb301c8@c1g2000yqg.googlegroups.com> Message-ID: simonharrison.uk at googlemail.com wrote: > Hi. I'm having another go at learning Python so I'll probably be > asking a few basic questions. Here is the first one. I think nobody has pointed out to you that "a < b < c" has the conventional mathematical definition (b is between a and c). So, perhaps: b = 9 c = 21 print 'All inbounds', all(10 <= x <= 21 for x in (b, c)) print 'None inbounds', all(not 10 <= x <= 21 for x in (b, c)) print 'inbounds', [x for x in (b, c) if 10 <= x <= 21] print 'outabounds', [x for x in (b, c) if not 10 <= x <= 21] I do advise working through the tutorial before asking. --Scott David Daniels Scott.Daniels at Acm.Org From harish.shastry at gmail.com Tue Dec 30 23:46:33 2008 From: harish.shastry at gmail.com (Harish Vishwanath) Date: Wed, 31 Dec 2008 10:16:33 +0530 Subject: How to get back a list object from its string representation? Message-ID: <78f8019c0812302046j31fa38aeif33d659ec5f2c84e@mail.gmail.com> Hello, Consider : >>> li = [1,2,3] >>> repr(li) '[1, 2, 3]' Is there a standard way to get back li, from repr(li) ? Regards, Harish -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Tue Dec 23 06:15:06 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 23 Dec 2008 03:15:06 -0800 (PST) Subject: Very basic question References: <21ab1917-f0c9-48fb-baa9-02e5bf229bf5@s9g2000prm.googlegroups.com> <38f6b145-8615-4bcc-88f6-1988f9a7f68f@q30g2000prq.googlegroups.com> Message-ID: <5f2c242e-9876-47dc-8f5d-e2f64675e501@w24g2000prd.googlegroups.com> On Dec 23, 9:49?pm, Sengly wrote: > I can hack it by doing eval('1.0*12/5') but is there any better method? from __future__ import division From cedric.schmeits at gmail.com Tue Dec 9 08:53:06 2008 From: cedric.schmeits at gmail.com (Cedric Schmeits) Date: Tue, 9 Dec 2008 05:53:06 -0800 (PST) Subject: Beginner trying to understand functions. References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> <9df7549a-f28b-4d39-b105-90c099f472f2@z28g2000prd.googlegroups.com> <040a2896-be99-477e-909c-c55c5a0e6665@y1g2000pra.googlegroups.com> Message-ID: <4c43037d-4394-4fce-8609-c04b0ed3d4f9@z27g2000prd.googlegroups.com> the following would be nicer: def run(): get_name() a = get_age() check_age(a) again() if __name__ == "__main__": run() In this setup your script will only be run if it's started by itself, but when using a import, the functions from the script can be executed separately. From sjmachin at lexicon.net Fri Dec 19 09:08:15 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 19 Dec 2008 06:08:15 -0800 (PST) Subject: importing csv file into sqlite References: <21067453.post@talk.nabble.com> Message-ID: <5bf2ab8d-be1a-454a-8c88-146694f5087b@q30g2000prq.googlegroups.com> On Dec 18, 5:17?pm, "James Mills" wrote: > > def readCSV(file): > ? if type(file) == str: Stiff cheese if the file path is a unicode object, eh? > ? ? ?fd = open(file, "rU") > ? else: > ? ? ?fd = file > From martinjamesevans at gmail.com Mon Dec 8 03:18:11 2008 From: martinjamesevans at gmail.com (martinjamesevans at gmail.com) Date: Mon, 8 Dec 2008 00:18:11 -0800 (PST) Subject: EBCDIC <--> ASCII References: <091f0404-2be3-4bda-8619-03627bd03fdc@k8g2000yqn.googlegroups.com> <6b861698-8638-443d-a230-3eca7424fcfc@j32g2000yqn.googlegroups.com> Message-ID: On Dec 5, 2:13?pm, Michael Str?der wrote: > martinjamesev... at gmail.com wrote: > > On Dec 4, 4:45 pm, Michael Str?der wrote: > >> martinjamesev... at gmail.com wrote: > >>> I'm having a problem trying to use the codecs package to aid me in > >>> converting some bytes from EBCDIC into ASCII. > >> Which EBCDIC variant? > > >>> sEBCDIC = unicode(sSource, 'cp500', 'ignore') > >> Are you sure CP500 is the EBCDIC variant for the language you want? > > >>http://www.ietf.org/rfc/rfc1345.txtlistsit as: > > >> ? ?&charset IBM500 > >> ? ?&rem source: IBM NLS RM Vol2 SE09-8002-01, March 1990 > >> ? ?&alias CP500 > >> ? ?&alias ebcdic-cp-be > >> ? ?&alias ebcdic-cp-ch > > >>> Obviously I could just knock up a 255 character lookup table and do it > >>> myself, I was just trying to be a little more Pythonic and use that > >>> built in table. > >> It's pythonic to implement a Unicode codec for unknown character tables. > >> I've put these two on my web site: > > >>http://www.stroeder.com/pylib/encodings/ebcdicatde.pyhttp://www.stroe...ebcdicatde) > > > Thanks for the tables, ebcdicatde.py does look more suitable. > > > My problem appears to be that my source is a byte string. In a > > nutshell I need "\x81\x82\x83\xf1\xf2\xf3" to become "abc123" in a > > byte string. > > Python 2.5.2 (r252:60911, Aug ?1 2008, 00:43:38) > ?>>> import ebcdicatde > ?>>> "\x81\x82\x83\xf1\xf2\xf3".decode('ebcdic-at-de').encode('ascii') > 'abc123' > ?>>> > > Ciao, Michael.- Hide quoted text - > > - Show quoted text - Many thanks for all your posts! Just what I needed. From vginer at gmail.com Thu Dec 18 14:21:18 2008 From: vginer at gmail.com (Vicent Giner) Date: Thu, 18 Dec 2008 11:21:18 -0800 (PST) Subject: IDLE cursor color Message-ID: <65c5974c-e5c5-46c1-9673-371a7c9ea047@a12g2000pro.googlegroups.com> I am working with IDLE, version 1.2.2 I've changed the colors theme using the "Options > Configure IDLE..." menu option. I've chosen a black background for all the items, so now my work area is black, and everything is OK, except for the fact that I can't see where the cursor is located, I mean, I don't know in which part of the window I am going to write. The cursor is blinking black, but I don't know how to change it. Please, any suggestion, hint, tip or clue?? Thank you in advance! From lists at cheimes.de Thu Dec 4 17:39:04 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 04 Dec 2008 23:39:04 +0100 Subject: Python 3 read() function In-Reply-To: References: <16651e80812040900j257fe2acjf5d8817811d32da6@mail.gmail.com> Message-ID: Terry Reedy wrote: > Timing of os interaction may depend on os. I verified above on WinXp > with 4 meg Pythonxy.chm file. Eye blink versus 3 secs, duplicated. I > think something is wrong that needs fixing in 3.0.1. > > http://bugs.python.org/issue4533 I've attached a patch to the bug. reading was so slow because the fileio_readall() was increasing the buffer by 8kB in each iteration. The new code doubles the buffer until it reaches 512kB. Starting with 512kB it's increased in 512kB blocks. Python 2.x has the same growth rate. Christian From bignose+hates-spam at benfinney.id.au Wed Dec 3 19:16:49 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 04 Dec 2008 11:16:49 +1100 Subject: "as" keyword woes References: Message-ID: <87oczsvlou.fsf@benfinney.id.au> "Warren DeLano" writes: > Why was it necessary to make "as" a reserved keyword? I can't answer for the Python developers as to why they *did* make it a reserved word. But I can offer what I believe is a good reason why it *should* be a reserved word: Because simple is better than complex, and special cases aren't special enough to break the rules. > And more to the point, why was it necessary to prevent developers > from being able to refer to attributes named "as"? There aren't special rules for which names can be use in which way, and that's a *good* thing. Any name that is valid in one area of Python syntax is valid in all Python syntax. > Why can't the parser distinguish between a standalone " as " keyword > and ".as" used as an object/attribute reference? Because that would require special-casing some names as being forbidden in syntax where other names are allowed. Special cases in language syntax are to be avoided where feasible. -- \ ?Pinky, are you pondering what I'm pondering?? ?I think so, | `\ Brain, but this time *you* put the trousers on the chimp.? | _o__) ?_Pinky and The Brain_ | Ben Finney From castironpi at gmail.com Thu Dec 18 05:52:43 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 18 Dec 2008 02:52:43 -0800 (PST) Subject: OT: Binary tree logarithms properties References: <8f67b6f80812170914m377191f4g81345ffe5d0b7f26@mail.gmail.com> Message-ID: <5d33a275-1554-463c-a125-43221d960753@k36g2000pri.googlegroups.com> On Dec 18, 4:34?am, Mr.SpOOn wrote: > 2008/12/17 Terry Reedy : > > > Nodes only have single number indexes if you arrange them linearly. Then the > > index depends on how you arrange them, whether you start the array indexes > > with 0 or 1, and whether you start the level numbers with 0 or 1. ?Call the > > breadth-first sequence bf. ?Then the 1-based slice for 1-first level k is > > bf[2**(k-1):2**k)]. ?Again, proof by induction. > > Yes, I was referring to the heap numeration. > Anyway, Francesco Guerrieri answered me in a private message and > explained me the formula. > > But actually I was searching for other similar properties. A tree with one node A, can have two children A CD C and D can each have two children A CD EF GH Taking 'x' to be the level number, each level can have 2**x members. Each member is a child of the higher level. You see the pattern, 1, 2, 4... then 8, 16, etc. The total number of nodes at a level is 2**x plus its earlier levels. 2**x + 2**(x-1) + ... + 2**0. = 2**(x+1) - 1. Taking the log2 of both sides, we have: log2 count_of_nodes = log2( 2**(x+1) - 1 ) Better yet: log2 ( count_of_nodes + 1 ) = log2( 2**(x+1) ) log2 ( count_of_nodes + 1 ) = x+1 From mrnull at gmail.com Mon Dec 15 11:49:35 2008 From: mrnull at gmail.com (Henson) Date: Mon, 15 Dec 2008 08:49:35 -0800 (PST) Subject: XMPP xmpppy - User Authorization References: <66b3831b-b26d-4ce9-80b2-e0e8c85ecbc4@k9g2000vbl.googlegroups.com> Message-ID: <14c866e4-8c08-403f-a0d0-eb28031a443f@t39g2000prh.googlegroups.com> On Dec 14, 4:23?am, "James Mills" wrote: > On Sun, Dec 14, 2008 at 3:47 PM, Henson wrote: > > In my own bot, using the latestxmpppy, I've been printing everything > > going to the message handler to the screen. ?I've yet to see a > > 'subscribe' string. ?Has this changed? > > No this hasn't changed. This is the string you need > to check for. It does work :) > > cheers > James > > > > -- > -- "Problems are solved by method" Found it. To me, the 'subscribe' was coming in through the Presence handler, not the Message handler. Thanks for the heads up, - Henson From rdcollum at gmail.com Thu Dec 18 14:11:48 2008 From: rdcollum at gmail.com (Roger) Date: Thu, 18 Dec 2008 11:11:48 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <71ede5f0-fd88-4155-9f0d-42d0ad5f57dc@v42g2000yqj.googlegroups.com> <61f45e65-2404-4cc0-9d81-f848c1ba566f@i18g2000prf.googlegroups.com> Message-ID: <7b8839ab-d00b-40f7-a878-5077dde7b8d4@f40g2000pri.googlegroups.com> On Dec 18, 12:49?pm, r wrote: > Maybe someone will chime in with an answer, sorry i could not help. > ponder this, i must... Regardless, thanks for your help! I truly appreciate it. Roger. From john.rominsky at gmail.com Wed Dec 17 14:52:17 2008 From: john.rominsky at gmail.com (Rominsky) Date: Wed, 17 Dec 2008 11:52:17 -0800 (PST) Subject: getting object instead of string from dir() References: Message-ID: <477b9c2e-a0ab-4b26-b643-4a9369c2aaac@r2g2000vbp.googlegroups.com> On Dec 17, 10:59?am, Christian Heimes wrote: > Rominsky schrieb: > > > I am trying to use dir to generate a list of methods, variables, etc. > > I would like to be able to go through the list and seperate the > > objects by type using the type() command, but the dir command returns > > a list of strings. ?When I ask for the type of an element, the answer > > is always string. ?How do I point at the variables themselves. ?A > > quick example is: > > > a = 5 > > b = 2.0 > > c = 'c' > > > lst = dir() > > > for el in lst: > > ? ? print type(el) > > for name, obj in vars().iteritems(): > ? ? print name, obj > > Christian I do have some understanding of the pythonic methodology of programming, though by far I still don't consider myself an expert. The problem at hand is that I am coming from a matlab world and trying to drag my coworkers with me. I have gotten a lot of them excited about using python for this work, but the biggest gripe everytime is they want their matlab ide. I am trying to experiment with making similar pieces of the ide, in particular I am working on the workspace window which lists all the current variables in the namespace, along with their type, size, value, etc.... I am trying to create a python equivalent. I can get dir to list all the variables names in a list of strings, but I am trying to get more info them. hence the desire to do a type command on them. I like the locals and globals commands, but I am still trying to get more info. I have started using the eval command with the strings, which is working, but I am curious if there is a better or more elegant way of getting the info. The eval example would be something like: a = 5 b = 2.0 c = 'c' lst = dir() for el in lst: print el + '\t' + str(eval('type(%s)'%el)) It works, now I am curious if there is a better way. From stef.mientki at gmail.com Thu Dec 18 14:09:26 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 18 Dec 2008 20:09:26 +0100 Subject: how to dock another application under Linux ? Message-ID: <494A9FE6.6050609@gmail.com> hello, Under windows it's fairly easy to capture an application and dock in to your own wxPython application, something like this: - start the external application from within wxPython - give the caption of the application a special name - find de windows handler of the applications mainform - tell the applications mainform, that some wxpanel is the parent I use this to dock VPython in wxPython. Is there a similar solution for Linux ( and Mac) ? thanks, Stef From sjmachin at lexicon.net Fri Dec 26 17:57:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 26 Dec 2008 14:57:34 -0800 (PST) Subject: strange behavior of math.sqrt() in new 3.0 version References: Message-ID: <0a25e3ad-9c94-4c16-9d6a-b79ceb10da1c@o40g2000prn.googlegroups.com> On Dec 27, 8:52?am, David Lemper wrote: > I'm a newbee trying 3.0 ? Please help with ?math.sqrt() math.sqrt() is not the problem. > At the command line this function works correctly > ? ? ? >>> import math > ? ? ? ? ? ? ? n = input("enter a number > ") > ? ? ? ? ? ? ? s = math.sqrt(n) > ? ? ?An entry of 9 or 9.0 ?will yield 3.0 I can't reproduce this. See below. Are you sure that you weren't using Python 2.x? Start with a fresh Python 3.0, and please copy/paste *exactly* what is on the screen, like I've done: C:\junk>\python30\python Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> n = input("float-> ") float-> 9 >>> type(n) >>> repr(n) "'9'" >>> import math >>> s = math.sqrt(n) Traceback (most recent call last): File "", line 1, in TypeError: a float is required All of the above is exactly as expected. input() returns a string. math.sqrt expects a float. > > Yet the same code in a script gives an error message > ? ? ?Script1 > ? ? ? ? ? ? ? ? ? ?import math > ? ? ? ? ? ? ? ? ? ?n = input("enter a number > ") > ? ? ? ? ? ? ? ? ? ?s = math.sqrt(n) > > ? ? ? ? ? ? ? ?Traceback (most recent call last) : > ? ? ? ? ? ? ? ? ? File "", line 1, in > ? ? ? ? ? ? ? ? ? File "script1.py" line 3 in > ? ? ? ? ? ? ? ? ? ? ?s = math.sqrt(n) > ? ? ? ? ? ? ? ?TypeError : a float is required > ? ? ?Entering 9 or 9.0 gives same error message. Again, as expected. > > ? ?According to the math module the results of all > ? ?functions are floats. ?However it says nothing about > ? ?inputs. > > Strangely the above code runs fine in version 2.5 ?( ? ) > and will handle large integers. Suggestion: either choose ONE of 2.6 and 3.0 to learn Python, or plan to spend a lot of time being confused, or reading "What's new in Python 3.0" -- a relevant snippet of which is: """ PEP 3111: raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use eval(input()). """ HTH, John From terry6394 at gmail.com Tue Dec 2 00:01:01 2008 From: terry6394 at gmail.com (Cyril.Liu) Date: Tue, 2 Dec 2008 13:01:01 +0800 Subject: epydoc: How to add new fields as the building fields? Message-ID: <6d2d06b10812012101v6f63b1d8o53b9040aaadcc719@mail.gmail.com> I can add new field in my docstring with "@newfield*"***** tag. but some tag witch I defined would be used in every source files. I do not want to write " @newfield tag ..." in all my docstring. Is there any way to add a building fields to epydoc? thx. -- About Cyril.Liu ----------------------------------- Cyril ????????????, ??????????????, ??????????????:"????????????????????????" http://blog.liuciyong.cn/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From prologic at shortcircuit.net.au Thu Dec 11 09:51:31 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 12 Dec 2008 00:51:31 +1000 Subject: How can I understan the "for" here? In-Reply-To: <49412744.8040301@gmail.com> References: <49412744.8040301@gmail.com> Message-ID: On Fri, Dec 12, 2008 at 12:44 AM, Kermit Mei wrote: > I can't understand the second sentence because of the "for ... in". > I consider that the syntactics of "for" should be: > > for k,v in params.items(): > ...... > > But there's no a colon here, why it can work? It's called a list comprehension. The "for x in y" construct becomes an expression. Simple example: Build a list of integers divisible by 3: >>> [x for x in xrange(10) if not x % 3] [0, 3, 6, 9] cheers James -- -- -- "Problems are solved by method" From pruebauno at latinmail.com Fri Dec 12 10:03:44 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Fri, 12 Dec 2008 07:03:44 -0800 (PST) Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> Message-ID: On Dec 12, 8:08?am, "Filip Gruszczy?ski" wrote: > I am not doing it, because I need it. I can as well use "if not elem > is None", but I just wanted to know, if there is some better way of > doing this. I like to know :-) > > And I can't understand why you are becoming so aggressive because of > this. Just because I asked for that, doesn't mean, that I will put > some obfuscated code into my project. I just wanted to learn something > new - I checked itertools, I googled a bit, now I wanted to ask here > if someone knew some really cool way of this. ?All the other > assumptions weren't really necessary. > > Thanks for those ideas, however. I like the last one a lot :) > > -- > Filip Gruszczy?ski In this case the "cool" way is the straightforward way: either the list versions: [x fox x in seq if x is not None] filter(lambda x: x is not None, seq) or the generator versions: (x for x in seq if x is not None) itertools.ifilter(lambda x: x is not None, seq) From rdmurray at bitdance.com Wed Dec 10 09:00:30 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Wed, 10 Dec 2008 09:00:30 -0500 (EST) Subject: SequenceMatcher bug ? In-Reply-To: <67253331-5b36-4018-b15a-c0b86c5342d3@r37g2000prr.googlegroups.com> References: <67253331-5b36-4018-b15a-c0b86c5342d3@r37g2000prr.googlegroups.com> Message-ID: On Tue, 9 Dec 2008 at 22:15, eliben wrote: > On Dec 10, 4:12?am, rdmur... at bitdance.com wrote: >> On Mon, 8 Dec 2008 at 23:46, eliben wrote: >>> This is about Python 2.5.2 - I don't know if there were fixes to this >>> module in 2.6/3.0 >> >>> I think I ran into a bug with difflib.SequenceMatcherclass. >>> Specifically, its ratio() method. The following: >> >>> SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + [5]).ratio >>> () >> >>> returns 0.0 >> >>> While the same with 500 replaced by 100 returns .99... something >>> Looking at the code ofSequenceMatcherthere's some caching going on >>> when the sequences are longer than 200 elements (and indeed, I can >>> reproduce the bug above 200 but not below). Can anyone confirm that >>> this misbehaves and suggest a workaround ? >> >> Python 2.5.2 (r252:60911, Sep 29 2008, 20:34:04) >> [GCC 4.3.1] on linux2 >> Type "help", "copyright", "credits" or "license" for more information.>>> from difflib importSequenceMatcher >>>>> SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + >>>>> [5]).ratio() >> >> 0.99900299102691925 >> > > Strange. I could reproduce the problem both on ActiveState Python > 2.5.2 for Windows, and in the online Try Python evaluator: > > http://try-python.mired.org/ My system is Gentoo, which installs python from source. Maybe gentoo applies patches that the binary releases don't have. --RDM From wuwei23 at gmail.com Mon Dec 8 23:52:32 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 8 Dec 2008 20:52:32 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> Message-ID: <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> On Dec 9, 5:21?am, Paul Boddie wrote: > What I can say is that it certainly does take balls to see matters > from the other guy's perspective instead of calling someone names for > pointing something out. >From my perspective, it was less the original complaint and more the sudden jump to "CPython is dead! The GIL sucks! Academic eggheads!" that prompted the comparisons to trolling. Especially in this case, where Chris was responding to the follow-up rant rather than the initial complaint. So I think to a certain degree the troll-typing reactions are understandable :) From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 16 04:26:55 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 16 Dec 2008 10:26:55 +0100 Subject: Need help improving number guessing game In-Reply-To: <1f33580b-84f9-4059-a0f0-b6a8d71325af@b38g2000prf.googlegroups.com> References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> <01564c98$0$21844$c3e8da3@news.astraweb.com> <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> <4946df78$0$19771$426a74cc@news.free.fr> <1f33580b-84f9-4059-a0f0-b6a8d71325af@b38g2000prf.googlegroups.com> Message-ID: <4947742c$0$25951$426a34cc@news.free.fr> feba a ?crit : >> .strip() returns a copy of the string without leading and ending > whitespaces (inlcuding newlines, tabs etc). > > Ahh. I had removed it because it didn't seem to do anything, but I've > readded it. > > And I understand your dictionary stuff correctly now, I think, and I > worked it in. Currently, I have: > > > import random > > def safeint(prompt="y"): > while True: > x = input(prompt) > try: > x = int(x) > except ValueError: > print("BAD INPUT!") > else: > break > return x > > def safestr(prompt="y"): > while True: > x = input(prompt) > try: > x = str(x) Doesn't input already return a string ? > except ValueError: > print("BAD INPUT!") > else: > break > return x You could as well replace the 'break' statement by 'return x' - since returning will obviously break the loop Now don't you notice kind of a pattern in these two functions ? obviously, the only thing that change is the conversion/validation part. The good news is that Python functions are objects too, so you can pass them as params to another function. The generic version of your above code could be: def safeinput(prompt, convert): while True: x = input(prompt) try: x = convert(x) except ValueError, e: print("Bad input : %s" % e) else: return x then you can use it for int: i = safeinput("Please enter an integer", int) or use more complex conversion/validation: def yesno(s): s = s.strip().lower() if not s in ("y", "n"): raise ValueError("please answer with 'y' or 'n'") # we return a boolean return s == 'y' answer = safeinput("really do this ?", yesno) Last point : if your conversion/validation function needs more arguments than the value to convert - ie : converting to an int and vaidating this int is in a specified range, which require mini and maxi arguments for the range - you can use partial evaluation[1]: from functools import partial def int_in_range(x, mini, maxi): x = int(x) if not mini <= x <= maxi: raise ValueError("%s is not in range (%s, %s)" % (x, mini, maxi)) return x i = safeinput( "Please enter an int between 1 and 99", partial(int_in_range, mini=1, maxi=99) ) [1] given the function f(x, y): return x + y, the partial evaluation partial(f, x=2) is a function fx(y) that when called returns the result of f(2, y). (snip) >> rewrite it once again using objects instead of dicts ? > > I'd need to find out how those work, Mostly as glorified dicts with associated functions. Your game and players dicts are obvious candidates. Whenever you see a dict with a more or less defined "structure" and a set of functions working on this dict, you have in fact a class waiting to be born. > and I have a list of python stuff > to read piling up anyway... That said, I think for something like > that, something that's not a major flaw, I'd prefer to make something > else, and maybe work on this again later on. There is only so much > guessing numbers one person can take. Indeed. That was just a suggestion, and it would have been pretty interesting IMHO as a basis for a "from Q&D procedural scripting to OO application programing" tutorial. From steve at holdenweb.com Mon Dec 15 10:50:58 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 15 Dec 2008 10:50:58 -0500 Subject: alt.possessive.its.has.no.apostrophe In-Reply-To: <87r649g9dg.fsf@benfinney.id.au> References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> Message-ID: <49467CE2.3060401@holdenweb.com> Ben Finney wrote: > James Stroud writes: > >> Ben Finney wrote: >>> James Stroud writes: >>> >>>> Yes. I think it was the British who decided that the apostrophe >>>> rule for "it" would be reversed from normal usage relative to >>>> just about every other noun. > > It also seems an indefensible claim to say that anyone ?decided? it > would be that way, especially ?the British?. > It's our language, dammit! Ours, ours, ours! This decision was actually taken at a meeting of the Society of British pedants on November 23, 1786. This led to a schism between the British and the newly-independent Americans, who responded by taking the "u" out of colour, valour, and aluminium. >>> Remember that ?it? is a pronoun. I see no reversal: >> Ok. Pronouns are reversed. > > Or, more generally: Pronouns, which are different in just about every > other way from other nouns, are different in this way also. Is that > about right? > Just think of them as "nounpros" and you won't go wrong. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From excord80 at gmail.com Tue Dec 9 21:49:05 2008 From: excord80 at gmail.com (excord80 at gmail.com) Date: Tue, 9 Dec 2008 18:49:05 -0800 (PST) Subject: How do I manually uninstall setuptools (installed by egg)? Message-ID: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> On Ubuntu, I accidentally manually installed setuptools http://pypi.python.org/pypi/setuptools/0.6c9 (by running the .egg file as a shell script via sudo), and now realize I should just be using apt to take care of my system Python packages. I also installed one or two packages using its ``easy_install``. Looks like it lives in ``/usr/lib/python2.5/site-packages``. How can I manually remove those packages installed using that ``easy_install``, and then manually remove the setuptools package I installed? From jeremiah.dodds at gmail.com Wed Dec 3 03:28:05 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Wed, 3 Dec 2008 03:28:05 -0500 Subject: noob needs help In-Reply-To: References: <6pg4oqF7rgu0U1@mid.individual.net> Message-ID: <12cbbbfc0812030028v32dd49e9pd752ce97894bb205@mail.gmail.com> On Wed, Dec 3, 2008 at 1:01 AM, Sambo wrote: > Peter Pearson wrote: > > > In slackware one needs "./" before the filename if you executing > files in current dir. > -- > http://mail.python.org/mailman/listinfo/python-list > Umm, only if you're running files marked as executable. If you're running foo.py file by typing "python foo.py", you shouldn't need to type "python ./foo.py" . Besides, wouldn't that be an issue with whatever shell you were using anyhow, and not an issue with slackware? -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.kern at gmail.com Mon Dec 8 15:04:22 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 08 Dec 2008 14:04:22 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> Message-ID: Rhamphoryncus wrote: > On Dec 8, 11:54 am, Robert Kern wrote: >> Rhamphoryncus wrote: >>> On Dec 7, 4:20 pm, Steven D'Aprano >> cybersource.com.au> wrote: >>>> On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: >>>>> Rasmus Fogh wrote: >>>>>> Current behaviour is both inconsistent and counterintuitive, as these >>>>>> examples show. >>>>>>>>> x = float('NaN') >>>>>>>>> x == x >>>>>> False >>>>> Blame IEEE for that one. Rich comparisons have nothing to do with that >>>>> one. >>>> There is nothing to blame them for. This is the correct behaviour. NaNs >>>> should *not* compare equal to themselves, that's mathematically >>>> incoherent. >>> Mathematically, NaNs shouldn't be comparable at all. They should >>> raise an exception when compared. In fact, they should raise an >>> exception when *created*. But that's not what we want. What we want >>> is a dummy value that silently plods through our calculations. For a >>> dummy value it seems a lot more sense to pick an arbitrary yet >>> consistent sort order (I suggest just above -Inf), rather than quietly >>> screwing up the sort. >> Well, there are explicitly two kinds of NaNs: signalling NaNs and quiet NaNs, to >> accommodate both requirements. Additionally, there is significant flexibility in >> trapping the signals. > > Right, but most of that's lower level. By the time it reaches Python > we only care about quiet NaNs. No, signaling NaNs raise the exception that you are asking for. You're right that if you get a Python float object that is a NaN, it is probably going to be quiet, but signaling NaNs can affect Python in the way that you want. >>> Regarding the mythical IEEE 754, although it's extremely rare to find >>> quotations, I have one on just this subject. And it does NOT say "x >>> == NaN gives false". It says it gives *unordered*. It is C and >>> probably most other languages that turn that into false (as they want >>> a dummy value, not an error.) >>> http://groups.google.ca/group/sci.math.num-analysis/browse_thread/thr... >> Table 4 on page 9 of the standard is pretty clear on the subject. When the two >> operands are unordered, the operator == returns False. The standard defines how >> to do comparisons notionally; two operands can be "greater than", "less than", >> "equal" or "unordered". It then goes on to map these notional concepts to >> programming language boolean predicates. > > Ahh, interesting. Still though, does it give an explanation for such > behaviour, or use cases? There must be some situation where blindly > returning false is enough benefit to trump screwing up sorting. Well, the standard was written in the days of Fortran. You didn't really have generic sorting routines. You *could* implement whatever ordering you wanted because you *had* to implement the ordering yourself. You didn't have to use a limited boolean predicate. Basically, the boolean predicates have to return either True or False. Neither one is really satisfactory, but that's the constraint you're under. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From wuwei23 at gmail.com Wed Dec 3 05:11:51 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 3 Dec 2008 02:11:51 -0800 (PST) Subject: Reverse zip() ? References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> <20081203095154.1bb33d4d@usenot.de> Message-ID: <8000d0b0-c9e5-4dbd-a6a0-e35b83277e72@d42g2000prb.googlegroups.com> On Dec 3, 6:51?pm, Andreas Waldenburger wrote: > On Tue, 02 Dec 2008 18:16:13 -0800 Bryan Olson > > zip as its own inverse might be even easier to comprehend if we call > > zip by its more traditional name, "transpose". > > Sounds like a Py4k change to me. Nah, just add the following to your sitecustomize.py: transpose = zip :) From motoom at xs4all.nl Sun Dec 21 21:27:36 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Mon, 22 Dec 2008 03:27:36 +0100 Subject: How to represent a sequence of raw bytes In-Reply-To: References: Message-ID: <200812220327.36180.motoom@xs4all.nl> On Monday 22 December 2008 03:23:03 Steven Woody wrote: > 2. char buf[] = {0x11, 0x22, 0x33, ... } > > What's the equivalent representation for above in Python? >>> buf="\x11\x22\33" >>> for b in buf: print ord(b) ... 17 34 27 >>> Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From Scott.Daniels at Acm.Org Fri Dec 19 15:48:31 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 19 Dec 2008 12:48:31 -0800 Subject: weird dict problem, how can this even happen? In-Reply-To: References: <88idnfej99XAtNXUnZ2dnUVZ_hednZ2d@pdx.net> Message-ID: Joel Hedlund wrote: > Scott David Daniels wrote: >> Perhaps your hash function could be something like: > > I'm not sure I understand what you're suggesting. > > /Joel Sorry, a half-thought out idea based on the fact that you wanted a consistent hash for a varying dictionary. The given dictionary subclass does have a consistent hash, so it should be able to find itself. Of course solving the consistent hash without any more work doesn't succeed in general and, without major changes, it makes for exponential lookups (lookup with all keys elements and drop parts til found). Perhaps separating the key (unchanging) from the to-be-varied part of the entry might work for some data sources, and the singly calculated hash might help. Sorry for a confusing post without much to recommend it. --Scott David Daniels Scott.Daniels at Acm.Org From sumerc at gmail.com Tue Dec 30 03:16:23 2008 From: sumerc at gmail.com (k3xji) Date: Tue, 30 Dec 2008 00:16:23 -0800 (PST) Subject: Read-Write Lock vs primitive Lock() References: <277c1be7-2560-4fd6-9610-0b4398dc3719@x16g2000prn.googlegroups.com> Message-ID: > >> Note that the thread acquires the lock ONCE, repeats several thousand > >> times an assignment to a *local* variable called GLOBAL_VAR (!), finally > >> releases the lock and exits. As every thread does the same, they just ? > >> run > >> one after another, they never have a significant overlap. Ok. Forget about the GLOBAL_VAR. See the below code: import threading import locks import time GLOBAL_VAR = [] #GLOBAL_LOCK = locks.ReadWriteLock() GLOBAL_LOCK = threading.Lock() #GLOBAL_LOCK = mylock() GLOBAL_LOOP_COUNT = 10000000 GLOBAL_READER_COUNT = 100 GLOBAL_WRITER_COUNT = 1 global GLOBAL_LEN class wthread(threading.Thread): def run(self): try: GLOBAL_LOCK.acquireWrite() #GLOBAL_LOCK.acquire_write() #GLOBAL_LOCK.acquire() for i in range(GLOBAL_LOOP_COUNT): pass finally: #GLOBAL_LOCK.release_write() GLOBAL_LOCK.release() class rthread(threading.Thread): def run(self): try: GLOBAL_LOCK.acquireRead() #GLOBAL_LOCK.acquire_read() print 'ENTER:'+str(threading.currentThread()) #GLOBAL_LOCK.acquire() print 'ACQUIRE:'+str(threading.currentThread()) for i in range(GLOBAL_LOOP_COUNT): pass finally: #GLOBAL_LOCK.release_read() GLOBAL_LOCK.release() print 'RELEASE:'+str(threading.currentThread()) # module executed? if __name__ == "__main__": starttime = time.clock() threads = [] for i in range(GLOBAL_READER_COUNT): rt = rthread() threads.append(rt) for i in range(GLOBAL_WRITER_COUNT): wt = wthread() threads.append(wt) for thread in threads: thread.start() for thread in threads: thread.join() print "All operations took " + str(time.clock() - starttime) + " msecs" As GLOBAL_LOOP_COUNT is 10000000, now this is making a bottleneck on the readers. I had assumed that as everythread is given only 100 bytecodes to execute, that it will be enough to have a 10000 value for this number to let other rthread start() and try to acquire the lock. But, Python undocumentedly, does not grab the GIL easily if a Lock is held. This is strange for me. > > If I put the for loop outside, in that case, readers will not overlap > > at all, and you would be amazed by the numbers for that test. They > > indicate primitive lock is faster than read-write lock, as it requires > > the lock, executes only one bytecode operation and releases the lock. > > So, in order to create a bottlenneck on readers, we need to somehow do > > not release the lock immediately. > > Again, what is your specific use case? why do you think readers will see a ? > bottleneck? > > > With that, primitive locks perform 10 times better than Read-Write > > lock. See above. > > So what? You don't like such results? The read-write lock in the recipe ? > you posted is rather complex, and isn't obvious whether it is correct or ? > not, and the author doesn't prove it nor provide a reference. I'd stick to ? > the standard Lock object unless I have specific needs. > Note that threading.Lock objects are implemented in C and don't have ? > significant overhead (other than the wait itself); even threading.RLock ? > objects are a lot slower. So depending on what you really have to do, the ? > overhead of using a class like ReadWriteLock may be worse than using a ? > standard Lock. That may be the point. That is why I am trying to test this. When will ReadWrite() lock permforms better over the primitive lock. By the way, for the reference, the code in the recipe is used in CherryPy and based on the Tanenbaum's book Operating Systems Design. > >> Hmmm, it's a reader but attempts to modify the value? > >> You don't have to protect a read operation on a global variable - so a > >> lock isn't required here. > > > This is just for testing. Suppose that I am actually reading the > > value. I don't understand why a lock is not required? Are you saying > > lock is not necesary beacuse GLOBAL_VALUE is an immutable object, if > > then, suppose it is not. This is just a test. Suppose GLOBAl_VAR is a > > list and we are calling append() on it which is nt an atomic > > operation. > > It doesn't matter whether it is mutable or immutable. Remember that, in ? > Python, a global variable is just a *name* that refers to an object; you ? > either get the old object referred, or the new one. If it is a list and it ? > is being modified "in place", you always get the same list -- its contents ? > may differ from one instant to another so iterating over it isn't safe. > That's why I insist on knowing your use case: you may me doing things more ? > complicated than they should. I understand your point completely, but let's change anything inside the loop. Just assume that we a thread that is supposed to read something, and a thread that is supposed to write. If I create thousands of readers, and if the operation is enormously huge calculation(as Python does not grab GIL easily inside a Lock), then this will create a bottlencek on readers. But, with ReadWrite Lock this problem *SHOULD* be fixed and in my tests I see it is fixed, when I increase the time spent in the loop in huge amounts. > > Each thread in your original code were like this: > > begin thread; wait for lock; execute something locally; release lock; exit ? > thread; > > There was no shared state between threads. Even if you fix them to share ? > some variable, they were a single, sequential, piece of code (the inner ? > loop is irrelevant here). Once a thread gets the lock, it just runs to its ? > end. No one waits more than once for the lock. So all of them run ? > sequentially, in arbitrary order, but just one after the other. They never ? > overlap. You are correct about this. But this is an undocumented thing. I had assumed that Python will release GIL for other threads after 100 bytecodes are executed by default. However, as I stated, when a Lock() is held this is changing. I think this is because to avoid simple MT problems for new programmers. Not sure. I will read threads.c for information. Thanks. From rt8396 at gmail.com Fri Dec 19 11:54:51 2008 From: rt8396 at gmail.com (r) Date: Fri, 19 Dec 2008 08:54:51 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: if 3.0 looks like... print( "{0}={1}".format('this',99)) , WTF... thats retarded and looks like Ruby code. Thats not intuitive thats madness! What happens when you need a conversion to string from an integer, more code?? My faith is slipping. Have the python Gods gone mad??. Please tell me i am wrong. Pythons likeness to C is one of its great powers. I always thought of Python as an intuitive way to write C code. I am sticking with 2x(which i had planned to do anyway) I have heard of nothing significant enough to compel me to make the change yet. And with that example from 3.0, i am really setting my ways now. i may have to support the continuation of 2.x beyond 2.9. Guido! please don't play Russian roulette with Python! I have loved python all the way up through the 2.x line. And i carry a great respect for you and your accomplishments. Python must feel at home to a C programmer. That, i feel, is the professional following for Python. I also feel Python is a gateway to the C language for n00b programmers. Let Ruby have the Perl programmers, we don't need them! Excuse me, I think i am going to cry now :( From vkseashoremack at googlemail.com Sat Dec 20 11:56:19 2008 From: vkseashoremack at googlemail.com (vkseashoremack at googlemail.com) Date: Sat, 20 Dec 2008 08:56:19 -0800 (PST) Subject: hd fisting - Free Message-ID: <01ef30ac-e80f-486e-8c8b-8ec7be6c6e81@g3g2000pre.googlegroups.com> hd fisting . . . *******CLICK HERE******** http://club247.cn/hd-fisting ***************************** . . . . . . . . . . . . hd fisting From tjreedy at udel.edu Wed Dec 3 11:42:09 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 03 Dec 2008 11:42:09 -0500 Subject: porting modules to Python 3.0 In-Reply-To: <49363d0d$0$3653$9b622d9e@news.freenet.de> References: <8f60c779-f1ec-4127-b173-f174c016aa96@a12g2000yqm.googlegroups.com> <4936255D.6000509@v.loewis.de> <49363d0d$0$3653$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: >> In one has both 2.x and 3.0 installed, would it easy to install 'lib.py' >> for both? > > It's currently not possible to install something for 2.x; you have to > specifically install it for every value of x (e.g. 2.5 or 2.6). That is what I meant. > It's the same for 3.0: you have to install it separately. > Doing so is fairly easy. You just run "setup.py install" multiple > times In the right place, with the right option to choose a different Python each time. I eventually found the apparent answers in Installing Python Modules, but only after reading well past 'the above command is everything you need to get out of this manual' ;-(. Hitherto, I have only unzipped library packages directly into the desired site-packages directory. This has been easier and safer than setup.py, but will not automatically run 2to3 over the package. Hence my question. Terry From cesium5500 at yahoo.ca Thu Dec 4 18:35:27 2008 From: cesium5500 at yahoo.ca (Guy Doune) Date: Thu, 04 Dec 2008 18:35:27 -0500 Subject: pretty strange behavior of "strip" Message-ID: <4938693F.6090709@yahoo.ca> Hi everybody, Could it be a bug????? Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> test=['03.html', '06.html', 'questions.html', '04.html', 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] >>> test ['03.html', '06.html', 'questions.html', '04.html', 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] >>> test[4] 'toc.html' >>> test[4].strip('.html') 'oc' Can't figure out what is going on, really. Guy From steve at REMOVE-THIS-cybersource.com.au Mon Dec 15 03:15:54 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Dec 2008 08:15:54 GMT Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> Message-ID: <015609af$0$20639$c3e8da3@news.astraweb.com> On Sun, 14 Dec 2008 20:38:58 -0800, cm_gui wrote: >> By the way... I know of a very slow Python site called YouTube.com. In >> fact, it is so slow that nobody ever uses it. > > hahaha, do you know how much money they are spending on hardware to make > youtube.com fast??? Oooh, I know! ONE MILLION DOLLARS!!!! And still cheaper and easier than re-writing YouTube's infrastructure in another language. -- Steven From psftw1 at gmail.com Mon Dec 15 00:25:07 2008 From: psftw1 at gmail.com (peter s.) Date: Sun, 14 Dec 2008 21:25:07 -0800 (PST) Subject: Building from source -- zlib/binascii problems 2.5.2/2.6.1 References: <71531b64-535f-49d0-a0c6-7704df83b251@f18g2000vbf.googlegroups.com> <49458079.1000304@v.loewis.de> <003b0307-c8df-489b-98e6-cfaa35d050a4@k1g2000prb.googlegroups.com> <494586A6.4060102@v.loewis.de> Message-ID: <564db0cc-6ad7-4d57-87ce-e03e8c9f2271@s16g2000vbp.googlegroups.com> On Dec 14, 5:20?pm, "Martin v. L?wis" wrote: > > So.. it seems as though I need to get it to point to the 64 bit > > version (or compile the zlib that comes with Python source). ?I'm not > > sure how to override that. > > The easiest solution would be to invoke the linker line manually, > and replace -lz with the absolute path to the right library. > > Regards, > Martin Thanks for you help thus far, though I am still stuck. I have tried a number of things with no success. Modifying the actual command that builds the zlibmodule to link to other sources produces different errors, such as "build/lib.linux-x86_64-2.5/zlib.so: undefined symbol: inflateEnd". Will update this thread if I find a solution. From invalid at invalid Mon Dec 22 13:53:12 2008 From: invalid at invalid (Grant Edwards) Date: Mon, 22 Dec 2008 12:53:12 -0600 Subject: I always wonder ... References: <494fd759$0$186$e4fe514c@news.xs4all.nl> Message-ID: On 2008-12-22, Martin P. Hellwig wrote: > skip at pobox.com wrote: >> Is there some online troll game running where the players earn >> points for generating responses to their posts? > > You just got 10 points ;-) We'll have to ask for an instant replay for the judges on that one. If his question was genuine, then it doesn't officially count as a troll. -- Grant Edwards grante Yow! Are we laid back yet? at visi.com From steve at holdenweb.com Sat Dec 20 17:34:16 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 20 Dec 2008 17:34:16 -0500 Subject: Python is slow In-Reply-To: <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> Message-ID: cm_gui wrote: >> Seriously cm_gui, you're a fool. >> Python is not slow. >> >> --JamesMills > > haha, getting hostile? > python fans sure are a nasty crowd. > > Python is SLOW. > Two lies in one posting! > when i have the time, i will elaborate on this. > Save your time, go somewhere else. Nobody here is interested. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From google at mrabarnett.plus.com Wed Dec 24 12:03:58 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 24 Dec 2008 17:03:58 +0000 Subject: How to change a generator ? In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF6024946E6@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF6024946E6@enbmail01.lsi.com> Message-ID: <49526B7E.20904@mrabarnett.plus.com> Barak, Ron wrote: > Hi, > > I have a generator whose aim is to returns consecutive lines from a file > (the listing below is a simplified version). > However, as it is written now, the generator method changes the text > file pointer to end of file after first invocation. > Namely, the file pointer changes from 0 to 6623 on line 24. > It might be that the generator method of self.input_file is reading the file a chunk at a time for efficiency even though it's yielding a line at a time. > Can you suggest how the generator could be changed, so it will allow me > to get the current location in the file after each yield ? > > Thanks, > Ron. > > $ cat -n generator.py # listing without line numbers is below > 1 #!/usr/bin/env python > 2 > 3 import gzip > 4 from Debug import _line as line > 5 > 6 class LogStream(): > 7 > 8 def __init__(self, filename): > 9 self.filename = filename > 10 self.input_file = self.open_file(filename) > 11 > 12 def open_file(self, in_file): > 13 try: > 14 f = gzip.GzipFile(in_file, "r") > 15 f.readline() > 16 except IOError: > 17 f = open(in_file, "r") > 18 f.readline() > 19 f.seek(0) > 20 return(f) > 21 > 22 def line_generator(self): > 23 print line()+". > self.input_file.tell()==",self.input_file.tell() > 24 for line_ in self.input_file: > 25 print line()+". > self.input_file.tell()==",self.input_file.tell() > 26 yield line_.strip() > 27 > 28 > 29 if __name__ == "__main__": > 30 > 31 filename = "sac.log.50lines" > 32 log_stream = LogStream(filename) > 33 log_stream.input_file.seek(0) > 34 line_generator = log_stream.line_generator() > 35 line_ = line_generator.next() > > $ python generator.py > 23. self.input_file.tell()== 0 > 25. self.input_file.tell()== 6623 > > $ wc -c sac.log.50lines > 6623 sac.log.50lines > $ cat generator.py > #!/usr/bin/env python > > import gzip > from Debug import _line as line > > class LogStream(): > > def __init__(self, filename): > self.filename = filename > self.input_file = self.open_file(filename) > > def open_file(self, in_file): > try: > f = gzip.GzipFile(in_file, "r") > f.readline() > except IOError: > f = open(in_file, "r") > f.readline() > f.seek(0) > return(f) > > def line_generator(self): > print line()+". self.input_file.tell()==",self.input_file.tell() > for line_ in self.input_file: > print line()+". self.input_file.tell()==",self.input_file.tell() > yield line_.strip() > > > if __name__ == "__main__": > > filename = "sac.log.50lines" > log_stream = LogStream(filename) > log_stream.input_file.seek(0) > line_generator = log_stream.line_generator() > line_ = line_generator.next() > From jstroud at mbi.ucla.edu Mon Dec 15 01:31:38 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 14 Dec 2008 22:31:38 -0800 Subject: alt.possessive.its.has.no.apostrophe In-Reply-To: <87vdtmf0mu.fsf_-_@benfinney.id.au> References: <87vdtmf0mu.fsf_-_@benfinney.id.au> Message-ID: Ben Finney wrote: > James Stroud writes: > >> Yes. I think it was the British who decided that the apostrophe rule >> for "it" would be reversed from normal usage relative to just about >> every other noun. > > Remember that ?it? is a pronoun. I see no reversal: Ok. Pronouns are reversed. Bob's Its From wuwei23 at gmail.com Thu Dec 11 05:01:45 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 11 Dec 2008 02:01:45 -0800 (PST) Subject: Equivalent of 'wget' for python? References: Message-ID: <8108f5d1-9052-4a5f-a470-7412abe14103@v5g2000prm.googlegroups.com> On Dec 11, 7:36?pm, hrishy wrote: > urllib -->static class > request -->method > urlretrieve--> what is this then ? The easiest way is to check for yourself, using type(). So 'type(urllib)' should give you '' (assuming the same types as 2.5, I don't have an install of 3.0 handy atm). My guess is 'type(urllib.request)' will be the same, and 'type (urllib.request.urlretrieve)' will be ''. 'urllib' is a module, or most likely in this case a package, which is a folder that can be treated as a module. It contains another module, 'request', which has inside the function 'urlretrieve'. Modules & packages are a handy language feature for placing functionality into namespaces. The documentation is worth checking out: http://docs.python.org/3.0/tutorial/modules.html From duncan.booth at invalid.invalid Sun Dec 7 12:17:35 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Dec 2008 17:17:35 GMT Subject: Python idea/proposal to assist in single-archive python applications References: Message-ID: Brian Allen Vanderburg II wrote: > In addition it is needed to be able to open a file just as easily > whether that file is in the archive or not. Assuming that a datafile in > an application may be located relative to the '__file__' attributes, the > following will not work in an archive: Why not use pkgutil.get_data()? Provided you remember to put your zip file on PYTHONPATH you can already run modules directly out of a zipfile (Python 2.5 and later). If your zipfile contains __main__.py then with Python 2.6 or later you can run it directly: just specify the zip filename on the command line. I'm not sure what, if anything, you are asking for that doesn't already exist in Python. From metolone+gmane at gmail.com Fri Dec 5 10:54:01 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Fri, 5 Dec 2008 07:54:01 -0800 Subject: pretty strange behavior of "strip" References: <4938693F.6090709@yahoo.ca> Message-ID: wrote in message news:Pine.LNX.4.64.0812050945320.1160 at kimball.webabinitio.net... > On Thu, 4 Dec 2008 at 20:54, Terry Reedy wrote: [snip] > I have often wished that in 'split' I could specify a _set_ of characters > on which the string would be split, in the same way the default list > of whitespace characters causes a split where any one (or more) of > them appears. But instead the string argument is a multi-character > separator. (Which is sometimes useful and I wouldn't want to lose the > ability to specify a multi-character separator!) >>> import re >>> re.split('[,.]','blah,blah.blah') ['blah', 'blah', 'blah'] -Mark From jarausch at igpm.rwth-aachen.de Tue Dec 9 05:51:55 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Tue, 09 Dec 2008 11:51:55 +0100 Subject: python3.0 - any hope it will get faster? Message-ID: <6q70udFb5dmqU1@mid.dfncis.de> Hi, I was somewhat surprised when I ran pystones with python-2.5.2 and with python-3.0 On my old/slow machine I get python-2.5.2 from test import pystone pystone.pystones() gives (2.73, 18315.018315018315) python-3.0 from test import pystone pystone.pystones() gives (4.2700000000000005, 11709.601873536298) That's a drop of 36% ! I know that processing unicode is inherently slower, but still I was surprised that it's so much slower. Is there any hope Python-3.0 will get faster or is the main potential for optimizations exhausted, already? That's not to start a flame war! I know computers get faster, we human beings don't (me, at least) -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From KDawg44 at gmail.com Tue Dec 16 15:44:18 2008 From: KDawg44 at gmail.com (KDawg44) Date: Tue, 16 Dec 2008 12:44:18 -0800 (PST) Subject: Using Mechanize to Fill Out a Form Message-ID: Hi, I am trying to use the Mechanize module to browse to a site, fill out a form, and login. However, it hangs on the opening of the URL. The URL is https, will this cause the open from mechanize to fail? Thanks. Kevin From todorovic.dejan at gmail.com Thu Dec 4 09:56:57 2008 From: todorovic.dejan at gmail.com (netpork) Date: Thu, 4 Dec 2008 06:56:57 -0800 (PST) Subject: m2crypto loading cert file from memory buffer Message-ID: <585682fe-befa-423f-a5d2-1dda717c5edc@r40g2000yqj.googlegroups.com> started using m2crypto recently, it works pretty well by now, i just have one question: ctx = SSL.Context('sslv3') ctx.load_cert_chain('client.pem') anyone knows a way of loading cert file from memory buffer and not from a file? i just do not want to have my cert file in the directory of my app that anyone can get. From bblais at bryant.edu Thu Dec 11 15:01:37 2008 From: bblais at bryant.edu (Brian Blais) Date: Thu, 11 Dec 2008 15:01:37 -0500 Subject: Mathematica 7 compares to other languages In-Reply-To: <452ba58b-9377-4463-85e2-5ecdaa25a129@t39g2000prh.googlegroups.com> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <452ba58b-9377-4463-85e2-5ecdaa25a129@t39g2000prh.googlegroups.com> Message-ID: <6E0FEB3A-1131-409D-843C-DD31A4859289@bryant.edu> On Dec 11, 2008, at 13:41 , Xah Lee wrote: > On Dec 10, 2:47 pm, John W Kennedy wrote: >> Xah Lee wrote: >>> In lisp, python, perl, etc, you'll have 10 or so lines. In C or >>> Java, >>> you'll have 50 or hundreds lines. >> >> C: >> >> #include >> #include >> >> void normal(int dim, float* x, float* a) { >> float sum = 0.0f; >> int i; >> float divisor; >> for (i = 0; i < dim; ++i) sum += x[i] * x[i]; >> divisor = sqrt(sum); >> for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; >> >> } > > i don't have experience coding C. The code above doesn't seems to > satisfy the spec. The input should be just a vector, array, list, or > whatever the lang supports. > The output is the same datatype of the same dimension. > This does satisfy it, depending on what you mean by "return". In C it is more common to do in-place assignment of pointers, rather than return values. So in the code above float *x is a list, if you will, of floats float *a is a list also dim is the length of the list it assumes that the outside code has already allocated the space for a and x. Instead of returning "a", it modifies the list in place. (for C purists, I know it's not a list, but that's just a convenient term). Also, for python, I wouldn't choose to code it in one line, when 2 is clearer: def normal(x): square=sqrt(sum([val**2 for val in x])) return [val/square for val in x] or, as others have pointed out, for numerical work I'd just use numpy: from numpy import * def normal(x): return x/sqrt(x.sum()) or something like that. bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at mrabarnett.plus.com Thu Dec 4 18:52:59 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 04 Dec 2008 23:52:59 +0000 Subject: pretty strange behavior of "strip" In-Reply-To: <4938693F.6090709@yahoo.ca> References: <4938693F.6090709@yahoo.ca> Message-ID: <49386D5B.4000602@mrabarnett.plus.com> Guy Doune wrote: > Hi everybody, > > Could it be a bug????? > > Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> test=['03.html', '06.html', 'questions.html', '04.html', > 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test > ['03.html', '06.html', 'questions.html', '04.html', 'toc.html', > '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test[4] > 'toc.html' > >>> test[4].strip('.html') > 'oc' > > Can't figure out what is going on, really. > It's not a bug. strip() treats its argument as a _set_ of characters and strips any of those characters from both ends of the string. lstrip() strips only the left-hand end and rstrip() strips only the right-hand end. From matt.dubins at sympatico.ca Thu Dec 25 18:22:48 2008 From: matt.dubins at sympatico.ca (Matthew Dubins) Date: Thu, 25 Dec 2008 18:22:48 -0500 Subject: Exec inside a class method to call other class methods? In-Reply-To: References: <4953CF57.8080905@sympatico.ca> Message-ID: <495415C8.2050205@sympatico.ca> Each type does contain its own parsing method. It's just that, as it stands, one method is being used to shunt off the data to the correct parsing method. Matthew Dubins David Stanek wrote: > On Thu, Dec 25, 2008 at 1:22 PM, Matthew Dubins > wrote: > >> Hello all, >> >> I have made a python script to upload contact information from an excel >> worksheet to an online database. One part of the program that really >> tripped me up was when I wanted to call specific class methods that I had >> made to deal with specific types of contact information (Parent's name, >> Child's name, Phone #, etc). My first thought was to make it easy using the >> exec statement. >> The code (a method within a class) looked like this: >> ---------- >> def parse(self, data, data_type) >> exec "self.__parse_%s(data)" % data_type >> ---------- >> The data_type variable contains strings that exactly match the spellings of >> the 2nd word in the titles of the class methods that I wanted to call for >> each data_type inputted into the parse function. For some reason, *it >> didn't work*. Alternately, I found the ugly code shown below to be >> functional. As you can see, for each data_type, I call the corresponding >> class method that I've specified. Please help me to transform my ugly >> functional code into concise functional code. :) >> >> Thanks, >> Matthew >> ---------- >> def parse(self, data, data_type): >> if data_type == 'nocall': >> self.__parse_nocall(data) >> elif data_type == 'DOB': >> self.__parse_DOB(data) >> elif data_type == 'gender': >> self.__parse_gender(data) >> elif data_type == 'Prematurity': >> self.__parse_Prematurity(data) >> elif data_type == 'email': >> self.__parse_email(data) >> elif data_type == 'languages': >> self.__parse_languages(data) >> elif data_type == 'phone': >> self.__parse_phone(data) >> elif data_type == 'cname': >> self.__parse_cname(data) >> elif data_type == 'pname': >> self.__parse_pname(data) >> elif data_type == 'address': >> self.__parse_address(data) >> elif data_type == 'duedate': >> self.__parse_dudedate(data) >> >> > > I would look for a way to reorganize your code so that each type > contains its own parse method. > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From narkewoody at gmail.com Mon Dec 22 19:41:28 2008 From: narkewoody at gmail.com (Steven Woody) Date: Tue, 23 Dec 2008 08:41:28 +0800 Subject: How to represent a sequence of raw bytes In-Reply-To: <44a5f0ac-3021-443f-90f2-5f3bd0116d4b@w1g2000prk.googlegroups.com> References: <200812220327.36180.motoom@xs4all.nl> <015f66d7$0$20615$c3e8da3@news.astraweb.com> <44a5f0ac-3021-443f-90f2-5f3bd0116d4b@w1g2000prk.googlegroups.com> Message-ID: On Tue, Dec 23, 2008 at 5:05 AM, John Machin wrote: > On Dec 23, 1:52 am, "Steven Woody" wrote: >> On Mon, Dec 22, 2008 at 6:44 PM, Steven D'Aprano >> >> wrote: >> > On Mon, 22 Dec 2008 14:56:45 +0800, Steven Woody wrote: >> >> >> The intension is to allocate 200 undefined bytes in memory. >> >> > You *want* undefined bytes? Out of curiosity, what do you intend to do >> > with them? >> >> to receive/send network packets, read raw files, etc. After read >> replies of the thread, I think 'array' or 'struct' maybe what I >> wanted, may a plain list can do, but I am not sure. > > [Rhetorical questions] How do you use "undefined bytes" to receive > network packets?? Do you really want to use "undefined bytes" to > *send* network packets???? > > Suggestion: Stop trying to replicate C in Python; think about what you > are trying to accomplish at a higher level, then how to implement that > in Python. > > Cheers, > John Good suggestion, thanks! From skip at pobox.com Sun Dec 7 12:21:07 2008 From: skip at pobox.com (skip at pobox.com) Date: Sun, 7 Dec 2008 11:21:07 -0600 Subject: Number of Python 3.x packages at the PyPI In-Reply-To: <493b954e$0$4021$9b622d9e@news.freenet.de> References: <9c1ab0f3-6686-4c0f-8a6c-12e20539f354@41g2000yqf.googlegroups.com> <493b954e$0$4021$9b622d9e@news.freenet.de> Message-ID: <18748.1539.499785.595995@montanaro-dyndns-org.local> Martin> http://pypi.python.org/pypi?:action=browse&c=533 Martin> It seems that some package authors only classify with Martin> Programming Language :: Python :: 3 I did a release for lockfile yesterday which supports 3.0. I added the "Programming Language :: Python :: 3.0" tag, but not the more inlusive tag above. I just updated the information to include it so it now appears in the search results. Skip From eric at ericaro.net Wed Dec 3 16:55:42 2008 From: eric at ericaro.net (eric) Date: Wed, 3 Dec 2008 13:55:42 -0800 (PST) Subject: python an sqlite objects References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <18742.47391.389709.119341@montanaro-dyndns-org.local> <4936F872.2020207@ghaering.de> Message-ID: <91ab57cb-e513-4894-98ed-b0de90136a0f@v15g2000yqn.googlegroups.com> On Dec 3, 10:21?pm, Gerhard H?ring wrote: > azrael wrote: > > It logical that it would be more efficient and logical to use a object > > oriented database, but in this case I ask because of the portable > > nature of sqlite. > > > so, if I get it right, this should be possible [...] > > Did you try it? Did it work? If so,it was pure luck. Attached is a > script that shows how to do it right. > > -- Gerhard > > ?sqlite_serialize.py > 1KViewDownload Hi, it is also possible to use Google Protobuf ( http://code.google.com/p/protobuf/ ) instead of pickle or json - it's portable to other languages too - you define what's the data you really wan't - it's fast, and compact I've done it on one of my projects ( see the code here http://code.google.com/p/pyshow/source/browse/trunk/src/pyshow/data/msgdb.py ), and using BerkeleyDB instead of sqlite( but that's not the point here) What I like with protobuf is that writing the proto file defines the real data structure, and that's a guaranty over time/processes/coders. I don't recommand using pickle to serialise object in a database. Because, it's easy at the beginning, but later, when you are going to 'upgrade' your objects (adding some new fields for instance, or splitting a field into a new object), you'll get a lot of troubles ( keeping the legacy object to live with the new one, implies renaming all objects ? etc.). That's what protobuf is for. BTW, I'm seeking help to start a new project that would connect protobuf to Database, like the piece of code I've done with berkeleyDB, but at a bigger scale. If anyone is interested. From Scott.Daniels at Acm.Org Thu Dec 18 15:47:46 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 18 Dec 2008 12:47:46 -0800 Subject: Factoring Polynomials In-Reply-To: <5dfe1cf3-530d-4e31-833e-e26db85611be@d36g2000prf.googlegroups.com> References: <5dfe1cf3-530d-4e31-833e-e26db85611be@d36g2000prf.googlegroups.com> Message-ID: eric wrote: > On Dec 18, 8:37 pm, collin.da... at gmail.com wrote: >> ... I dont know how to implement the quadratic equation ... > > with numpy: > from numpy import * > > s=[1,-1] > x = -b+s*sqrt( b**2-4*a*c )/(2*a) Numpy is pretty heavyweight for this. For built in modules you have a few choices: For real results: from math import sqrt For complex results: from cmath import sqrt or you can simply use: (value) ** .5 Then you can do something like: def quadsolve(a, b, c): try: discriminant = sqrt(b**2 - 4 * a * c) except ValueError: return () # No results at all. if discriminant: # two results return ((-b - discriminant) / (2 * a), (-b + discriminant) / (2 * a)) else: # a single result (discriminant is zero) return (-b / (2 * a),) --Scott David Daniels Scott.Daniels at Acm.Org From gneuner2 at comcast.net Fri Dec 12 12:39:26 2008 From: gneuner2 at comcast.net (George Neuner) Date: Fri, 12 Dec 2008 12:39:26 -0500 Subject: Mathematica 7 compares to other languages References: <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <452ba58b-9377-4463-85e2-5ecdaa25a129@t39g2000prh.googlegroups.com> Message-ID: <6375k4pf1mleb6im67nkpec5olqbsom88e@4ax.com> On Thu, 11 Dec 2008 10:41:59 -0800 (PST), Xah Lee wrote: >On Dec 10, 2:47?pm, John W Kennedy wrote: >> Xah Lee wrote: >> > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, >> > you'll have 50 or hundreds lines. >> >> C: >> >> #include >> #include >> >> void normal(int dim, float* x, float* a) { >> ? ? float sum = 0.0f; >> ? ? int i; >> ? ? float divisor; >> ? ? for (i = 0; i < dim; ++i) sum += x[i] * x[i]; >> ? ? divisor = sqrt(sum); >> ? ? for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; >> >> } > >i don't have experience coding C. Then why do you talk about it as if you know something? >The code above doesn't seems to satisfy the spec. It does. >The input should be just a vector, array, list, or >whatever the lang supports. The output is the same >datatype of the same dimension. C's native arrays are stored contiguously. Multidimensional arrays can be accessed as a vector of length (dim1 * dim2 * ... * dimN). This code handles arrays of any dimensionality. The poorly named argument 'dim' specifies the total number of elements in the array. George From tavares at fe.up.pt Tue Dec 23 14:01:29 2008 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Tue, 23 Dec 2008 11:01:29 -0800 (PST) Subject: =?windows-1252?Q?Symposium_=93Visualization_and_Human=2DComputer=94_wit?= =?windows-1252?Q?hin_the_IRF=922009_Conference_=96_Announce_=26_Call_for_Papers?= Message-ID: <72a5d86e-d008-4e74-9cdb-12f4b6650673@g39g2000pri.googlegroups.com> ---------------------------------------------------------------------------------------------------------------------------------------- (Apologies for cross-posting) Symposium on ?Visualization and Human-Computer? 3rd International Conference on Integrity, Reliability & Failure (IRF?2009) Faculty of Engineering, University of Porto, Porto ? PORTUGAL, 20-24 July 2009 http://paginas.fe.up.pt/clme/IRF2009/index.htm (We would appreciate if you could distribute this information by your colleagues and co-workers.) ---------------------------------------------------------------------------------------------------------------------------------------- Dear Colleague, Within the 3rd International Conference on Integrity, Reliability & Failure (IRF?2009), to be held in FEUP, Porto, Portugal, in July 20-24, 2009, we are organizing the Symposium ?Visualization and Human- Computer?. Examples of some topics that will be considered are: Scientific Data Visualization, Spatial Data in Visualization, Data Processing and Analysis, Information Visualization, Visualization Techniques, Large Data Visualization, Image Processing and Analysis, Hardware for Visualization, Human-Computer Interaction, Visual Analytics, Visual Data Mining and Knowledge Discovery, Human Perception, Interface Design, Evaluation and User Studies, Software Development, Grid and High Performance Computing, Applications in Engineering, Biomechanics, Bioinformatics, Bioimaging, Physical, Earth, Space, Environmental and Information Sciences. Due to your research activities in those fields, we would like to invite you to submit your work and participate in the Symposium ?Visualization and Human-Computer?. For instructions and submission, please access to the conference website at: http://paginas.fe.up.pt/clme/IRF2009/index.htm Please note that, when submitting your work you should select the Symposium #7 ?Visualization and Human-Computer?. Important dates: - February 28, 2009: Deadline for abstract submission; - March 21, 2009: Notification of abstract acceptance; - May 10, 2009: Receipt of Full Papers; - July 20-24, 2009: Conference Events. Kind regards, Jo?o Manuel R. S. Tavares (University of Porto, Portugal, tavares at fe.up.pt) Renato Natal Jorge (University of Porto, Portugal, rnatal at fe.up.pt) (Symposium organizers) From gagsl-py2 at yahoo.com.ar Mon Dec 8 02:48:58 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Dec 2008 05:48:58 -0200 Subject: how to get a beep, OS independent ? In-Reply-To: References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> <014c575a$0$20670$c3e8da3@news.astraweb.com> Message-ID: En Sun, 07 Dec 2008 23:34:17 -0200, Joe Strout escribi?: > On Dec 7, 2008, at 4:43 PM, Steven D'Aprano wrote: > >> Of course, if you're volunteering to write such a standard system beep >> for Python, I for one would be grateful. > > I am. But where should I put it? Assuming we don't want to wait for > the (understandably) lengthy and contentious process required to add > something to the Python system libraries, where would be the next best > place for this sort of simple OS abstraction layer? The cookbook? http://www.activestate.com/ASPN/Python/Cookbook/ If you can make it run on several different architectures you could upload a patch as a feature request to http://bugs.python.org/ -- Gabriel Genellina From tom at tommorris.org Mon Dec 8 00:53:22 2008 From: tom at tommorris.org (Tom Morris) Date: 8 Dec 2008 05:53:22 GMT Subject: python book for non technical absolute beginner References: <493a7c6a$0$973$426a34cc@news.free.fr> Message-ID: <6q3r2iFahsj9U1@mid.individual.net> On 2008-12-06, News123 wrote: > One of my 'non technical' friends complained about knowing nothing at > all about programming (though using computers regularly for mails / web > browsing / googling and downloading / cropping photos ) > > He wants to play a little with programming to stimulate parts of his > otehrwise idle brain cells. ;-) Normally it's more the social science / > linguistic parts being exercised, > > I thought python might be a nice language for this > > No my question does anybody know a nice beginners book (or a learning CD > or on line tutorial)? Ideally it shouldn't be too serious and have a lot > of small nice mini-examples > It's not Python, but I am a big fan of Chris Pine's 'Learn to Program' , which is a Ruby tutorial for absolute beginners. It'd certainly be nice if the author were to allow someone to port the tutorial for Python and other languages. It spends a lot of time taking the reader from numbers and letters through conditionals, loops, arrays, iteration and eventually to classes and objects. It really is, in my opinion, one of the best programming tutorials for beginners. -- Tom Morris From anurag.bagaria at gmail.com Mon Dec 22 05:02:08 2008 From: anurag.bagaria at gmail.com (ANURAG BAGARIA) Date: Mon, 22 Dec 2008 11:02:08 +0100 Subject: using subprocess module in Python CGI Message-ID: Hello, I am a Python Newbie and would like to call a short python script via browser using a CGI script, but initially I am trying to call the same python script directly through python command line. The script intends to perform a few command line in a pipe and I have written the script (a short one) as follows. #!/usr/bin/python import cgi, string, os, sys, cgitb, commands, subprocess import posixpath, macpath #file = "x.tar.gz" #comd = "tar -xf %s" % (file) #os.system(comd) #commands.getoutput('tar -xf x.tar.gz | cd demo; cp README ../') comd = [\ "tar -xf x.tar.gz", \ "cd demo", \ "cp README ../", \ ] outFile = os.path.join(os.curdir, "output.log") outptr = file(outFile, "w") errFile = os.path.join(os.curdir, "error.log") errptr = file(errFile, "w") retval = subprocess.call(comd, 0, None, None, outptr, errptr) errptr.close() outptr.close() if not retval == 0: errptr = file(errFile, "r") errData = errptr.read() errptr.close() raise Exception("Error executing command: " + repr(errData)) but after trying to execute this independently, I get the following error which I am unable to interpret : Traceback (most recent call last): File "process.py", line 18, in retval = subprocess.call(comd, 0, None, None, outptr, errptr) File "/usr/lib/python2.5/subprocess.py", line 443, in call return Popen(*popenargs, **kwargs).wait() File "/usr/lib/python2.5/subprocess.py", line 593, in __init__ errread, errwrite) File "/usr/lib/python2.5/subprocess.py", line 1135, in _execute_child raise child_exception Could someone suggest where am I going wrong and if corrected, what is the probability of this script being compatible with being called through the browser. Thanking you people in advance. Regards. -- I just want to LIVE while I'm alive. AB -------------- next part -------------- An HTML attachment was scrubbed... URL: From kylefranki at gmail.com Sun Dec 21 10:10:36 2008 From: kylefranki at gmail.com (kylefranki at gmail.com) Date: Sun, 21 Dec 2008 07:10:36 -0800 (PST) Subject: Big Boobs on Parade Message-ID: <2962e6ab-63e9-4629-8184-0be0ac2a3b25@k1g2000prb.googlegroups.com> http://sosed.smutwebsites.com/ Big Boobs on Parade rulez the world of Big Boobs! This site offers a categorized selection of the most unique Free Big Boobs Movies ever filmed. Our team of hard working slaves picks each and every one of these fine babes warranting the finest big boobs videos for our fellow surfers From tmohr at s.netic.de Sun Dec 14 15:16:34 2008 From: tmohr at s.netic.de (Torsten Mohr) Date: Sun, 14 Dec 2008 21:16:34 +0100 Subject: package structure? Message-ID: Hi, in a package i'd like to have a structure like this: Files end with ".py", others are directories: mod __init__.py # sets __all__ = ['smod1'] smod1.py # contains AClass() smod1 __init__.py # sets __all__ = ['abc', 'def'] abc.py def.py So i can now do: import mod.smod1.abc import mod.smod1 But functions/classes in smod1.py are not found: a = mod.smod1.AClass() I know this is somehow ambiguous, but i wonder how else i can make "mod" have subpackages and modules. I wonder how i can make AClass() known in that package. Thanks for any hints, Torsten. From tavares at fe.up.pt Mon Dec 8 12:57:08 2008 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Mon, 8 Dec 2008 09:57:08 -0800 (PST) Subject: =?windows-1252?Q?Symposium_=93Computational_Methods_in_Image_Analysis?= =?windows-1252?Q?=94_within_the_USNCCM_X_Congress_=96_Announce_=26_Call_for_Pap?= =?windows-1252?Q?ers?= Message-ID: <573919c2-f37f-4e2f-8a83-182e327a4f3f@u18g2000pro.googlegroups.com> ------------------------------------------------------------------------------------------------------------------------------- (Apologies for cross-posting) Symposium on ?Computational methods in image analysis? 10th US National Congress on Computational Mechanics (USNCCM X) Columbus, Ohio, USA, July 16-19, 2009 http://usnccm-10.eng.ohio-state.edu/ We would appreciate if you could distribute this information by your colleagues and co-workers. ------------------------------------------------------------------------------------------------------------------------------- Dear Colleague, Within the 10th US National Congress on Computational Mechanics (USNCCM X), to be held in Ohio, USA, in July 16-19, 2009, we are organizing the Symposium ?Computational methods in image analysis?. Examples of some topics that will be considered in the symposium ?Computational methods in image analysis? are: Image Analysis, Objects Modeling, Image Segmentation, Matching, Shape Reconstruction, Motion and Deformation Analysis, Objects Description and Registration, Medical imaging, Software Development for Image Analysis and Grid and High Performance Computing in Image Analysis. Due to your research activities in those fields, we would like to invite you to submit your work and participate in the Symposium ?Computational methods in image analysis?. For instructions and submission, please access to the conference website at: http://usnccm-10.eng.ohio-state.edu/abstractsub.html Please note that, when submitting your work you should select the Symposium ?2.18.4 Computational methods in image analysis?. Important dates: - January 31, 2009: Deadline for abstract submission; - March 1, 2009: Deadline and notification of abstract acceptance; - July 16-19, 2009: Congress Events. Kind regards, Jo?o Manuel R. S. Tavares (University of Porto, Portugal, tavares at fe.up.pt) Renato Natal Jorge (University of Porto, Portugal, rnatal at fe.up.pt) Yongjie Zhang (Carnegie Mellon University, USA, jessicaz at andrew.cmu.edu) Dinggang Shen (UNC-CH School of Medicine, USA, dgshen at med.unc.edu) (Symposium organizers) From rt8396 at gmail.com Tue Dec 16 18:08:32 2008 From: rt8396 at gmail.com (r) Date: Tue, 16 Dec 2008 15:08:32 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <355f1cfe-6abb-4d2c-8bf4-3aa62e713c1f@w34g2000yqm.googlegroups.com> Message-ID: <705998e7-404f-4f4b-a2d6-566660e3e31a@o4g2000pra.googlegroups.com> What about all the crap you had to go through just to get output? Python wins PS. cm_gui try this piece of code >>> print 'hello world'.replace('world', 'idiot') From bdesth.quelquechose at free.quelquepart.fr Thu Dec 4 15:45:46 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 Dec 2008 21:45:46 +0100 Subject: Pythonic design patterns In-Reply-To: References: Message-ID: <49384f33$0$8475$426a74cc@news.free.fr> Slaunger a ?crit : > Thank you all for sharing your views, links and suggestions on my > question. I see where this is getting, and I have extracted the > following points: > > 1. Many classic design patterns, especially the creational ones > (Factory, etc.) aren't really that useful in Python as the built-in > features in the language and the new style objects has ways of doing > these things far more natural than statically types languages. Well... I'd formulate it another way: many classic design patterns are either builtins or simply obvious in Python, so they are barely identifiable as such - at least if you fail to decouple the *design* pattern from it's canonical implementation(s). Remember that design != implementation !-) > 2. Don't be religious about the design pattern and applying them too > frantically. They may look cool, but there is a great danger for over- > engineering and subsequent lower code readability, debuggability, and > maintainability. Indeed. And when you use one, try to implement it the pythonic way... (snip) From castironpi at gmail.com Sun Dec 21 10:57:12 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 21 Dec 2008 07:57:12 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: <45efda40-d5d8-4af3-902f-6e4a9596af49@t39g2000prh.googlegroups.com> On Dec 21, 8:50?am, Steve Holden wrote: > r wrote: snip > > This all really comes down to the new python users. Yea, i said it. > > Not rabid fanboys like Steven and myself.(i can't speak for walter but > > i think he would agree) Are we going to make sure joe-blow python > > newbie likes the language. And doesn't get turned off and run over to > > ruby or whoever. Like it or not, without newusers python is doomed to > > the same fate as all the other "great" languages who had their 15 mins > > of fame. > > > We must proactively seek out the wants of these new users and make > > sure python stays alive. But we also must not sell are pythonic souls > > ? ? ? ? ? ? ? ? ? ? ? ? ?that's "our" (possessive), r, not "are" (verb) > > > in the process. > > > It would be nice to get a vote together and see what does the average > > pythoneer want? What do they like, What do they dislike. What is the > > state of the Python Union? Does anybody know, Does anybody care? I > > think python is slipping away from it's dominate foothold on the > > world. Google's use of python may be the only thing holding this house > > of cards together. Ruby's "hype" is defiantly growing and unless we > > strive for greatness, python may fail. I think ruby may have their act > > together a little better than us right now. And since Ruby is such a > > hodge-podge of different languages, the __init__ hold is there for > > many. > > > what does joe-python want??? > > Don't make the mistake of assuming there is a "Joe Python" whose needs > neatly encapsulate the sum of all Python users' needs. There's plenty of > evidence from this group that different people like, want or need > different things from Python, and attempting to measure user > requirements by democratic means is not likely to produce much useful > information. > > There is no such thing as "the average Python programmer": an average > can only be measured for one-dimensional values on some sort of linear > continuum. Python users live in a multi-dimensional space where the > concept of an average has little meaning and less use. You've confused dimensions with modes. There is such thing as the center of a bivariate distribution--- it is merely the most common of the individual variables, the top of a 3-D hill, or the center of mass. However, an average only makes sense for unimodal distributions. If the distribution is bi-modal, there's no "average" in the neat sense. Dollars earned per hour spent writing in Python is a good candidate. There are two modes in that distribution. One at 0, the other in the tens or hundreds. And the global average is less common than either mode individually. So in this case, we have one "Joe Py" for every mode: Joe Free Py, and Joe Paid Py. (You might actually get multi- modal on that one-- Joe Salary Py, Joe Wage Py, Joe Stipend Py, Joe Free Py, but $0.01/hr. is less common than 0, and less common than $50.) You might also argue that the standard deviation is so high as to make any one data point unrepresentative of many others. But if you have variables in two dimensions, they're independent by definition (or there exists a basis set that is). From prologic at shortcircuit.net.au Mon Dec 15 21:58:27 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 16 Dec 2008 12:58:27 +1000 Subject: ethical questions about global variables In-Reply-To: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> References: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> Message-ID: On Tue, Dec 16, 2008 at 12:45 PM, Giampaolo Rodola' wrote: > Hi, > in a module of mine (ftpserver.py) I'd want to add a (boolean) global > variable named "use_gmt_times" to decide whether the server has to > return times in GMT or localtime but I'm not sure if it is a good idea > because of the "ethical" doubts I'm gonna write below. > > In first place I've never liked global variables too much and always > preferred per-class-instance variables instead. > The problem in my case is that I have to use such variable in two > separated classes: FTPHandler and VirtualFileSystem. Also, I want that > for no reason one class uses times in GMT and the other one local > times. > > Another doubt is the naming convention. PEP-8 states that global > variables should use the lower_case_naming_convention but I've seen a > lot of library module using the UPPER_CASE_NAMING_CONVENTION. What am > I supposed to do about it? > > Thanks in advance for any comment. You could always use a "config" object that you pass around to your other objects. --JamesMills From prologic at shortcircuit.net.au Fri Dec 19 06:50:04 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Dec 2008 21:50:04 +1000 Subject: importing csv file into sqlite In-Reply-To: References: <21067453.post@talk.nabble.com> Message-ID: On Fri, Dec 19, 2008 at 8:32 PM, Peter Otten <__peter__ at web.de> wrote: > James Mills wrote: > >> values = ",".join(["\"%s\"" % x for x in line]) >> print "INSERT INTO %s %s VALUES (%s);" % (table, fields, values) > > http://xkcd.com/327/ It's a tool! Not one meant to be used publicly from untrusted users. Free feel to submit a patch as is the Open Source spirit! --JamesMills From Lie.1296 at gmail.com Sat Dec 6 15:18:14 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 6 Dec 2008 12:18:14 -0800 (PST) Subject: "as" keyword woes References: Message-ID: <66ea8282-05cc-4d24-8447-1df5e0e6b9f6@40g2000prx.googlegroups.com> On Dec 7, 2:38?am, "Warren DeLano" wrote: > > Date: Fri, 05 Dec 2008 22:22:38 -0800 > > From: Dennis Lee Bieber > > Subject: Re: "as" keyword woes > > To: python-l... at python.org > > Message-ID: > > > ? ?I'm still in the dark as to what type of data could > > even inspire the > > use of "as" as an object name... A collection of "a" objects? In which > > case, what are the "a"s? > > Please let me clarify. ?It is not "as" as a standalone object that we > specifically miss in 2.6/3, but rather, the ability to use ".as" used as > a method or attribute name. ? > > In other words we have lost the ability to refer to "as" as the > generalized OOP-compliant/syntax-independent method name for casting: > > new_object = old_object.as(class_hint) > > # For example: > > float_obj = int_obj.as("float") > > # or > > float_obj = int_obj.as(float_class) > > # as opposed to something like > > float_obj = int_obj.asFloat() > > # which requires a separate method for each cast, or > > float_obj = (float)int_obj ? > > # which required syntax-dependent casting [language-based rather than > object-based]. > > Of course, use of explicit casting syntax "(float)" is fine if you're > restricting yourself to Python and other languages which support > casting, but that solution is unavailable inside of a pure OOP > message-passing paradigm where object.method(argument) invocations are > all you have to work with. ? > > Please note that use of object.asClassname(...) is a ubiqitous > convention for casting objects to specific classes (seen in ObjectiveC, > Java, SmallTalk, etc.). ? > > There, I assert that 'object.as(class_reference)' is the simplest and > most elegant generalization of this widely-used convention. ?Indeed, it > is the only obvious concise answer, if you are limited to using methods > for casting. > > Although there are other valid domain-specific uses for "as" as either a > local variable or attribute names (e.g. systematic naming: as, bs, cs), > those aren't nearly as important compared to "as" being available as the > name of a generalized casting method -- one that is now strictly denied > to users of Python 2.6 and 3. > > As someone somewhat knowledgable of how parsers work, I do not > understand why a method/attribute name "object_name.as(...)" must > necessarily conflict with a standalone keyword " as ". ?It seems to me > that it should be possible to unambiguously separate the two without > ambiguity or undue complication of the parser. > > So, assuming I now wish to propose a corrective PEP to remedy this > situation for Python 3.1 and beyond, what is the best way to get started > on such a proposal? ? > > Cheers, > Warren And let things like: filelike.print('lpt') # python 2.6 zipper.with('7z') failure.try(alternative) executecodeobject.if(True) onfailure.break() ? From lists at cheimes.de Thu Dec 11 06:58:10 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 11 Dec 2008 12:58:10 +0100 Subject: broken ncurses on python 3.0 In-Reply-To: References: Message-ID: icarus wrote: > OS: win32, python 3.0 > > I've been trying to run some curses demos and I get this: > > C:\Python\Lib\curses>python textpad.py > Traceback (most recent call last): > File "textpad.py", line 3, in > import curses > File "C:\Python\lib\curses\__init__.py", line 15, in > from _curses import * > ImportError: No module named _curses > > The C:\Python\include does not have the curses.h header. > Reinstalling from the x86 msi binary doesn't do it. > > Any ideas on how to get this working? maybe it's just the w32 version > that missed ncurses The Windows binaries doesn't have and never had an ncurses extension. The extension doesn't suport ncurses on Windows at all - in all versions of Python. Christian From anthony.tolle at gmail.com Mon Dec 8 11:59:53 2008 From: anthony.tolle at gmail.com (anthony.tolle at gmail.com) Date: Mon, 8 Dec 2008 08:59:53 -0800 (PST) Subject: Guido's new method definition idea References: <014a071a$0$20670$c3e8da3@news.astraweb.com> <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> Message-ID: <79139d04-bd26-4f36-b8c9-19554e7d4e95@e18g2000yqo.googlegroups.com> On Dec 6, 4:15?pm, Carl Banks wrote: > On Dec 6, 12:47?am, "Patrick Mullen" wrote: > > > Could I do something like this: > > > def a.add(b): return a+b > > > Outside of a class? ?Of course then that makes you think you could do > > 5.add(6) or something craaaazy like that. ?(I mean, you can do > > (5).__add__(6) but that's something else entirely) > > I'd be inclined to think that this defines an instancemethod on an > existing object a. ?In other word, I'd read the following two lines as > more or less equivalent. > > def a.add(b): return a+b > > a.add = lambda b: a+b > > Just as the following are equivalent: > > def foo(): return bar > > foo = lambda: bar > > I had been -0 on this, but now I think I'm -1. This brings up another question, what would one use when referencing method names inside the class definition?: class C: def self.method(arg): self.value = arg def self.othermethod(arg): self.value = arg # do this? funcs = (self.method, self.othermethod) # or this? funcs = (method, othermethod) On another related note, I would be interested in seeing this syntax adopted for a different purpose... Normally, if I'm defining a nested function that needs to be stored as an object attribute, I have to use a dummy name, like the following: class C: def createfunc(self, arg): def _dummy(arg): return arg + 1 self.func = _dummy It would be nice to be able to do the following instead: class C: def createfunc(self): def self.func(arg): return arg + 1 Or, after the class definition is done, to extend it dynamically: def C.method(self, arg): self.value = arg ...which would be the equivalent of the following: def method(self, arg): self.value = arg C.method = method Since functions are first-class objects, it seems perfectly reasonable to me. From shaomumu at gmail.com Tue Dec 16 13:38:45 2008 From: shaomumu at gmail.com (Lin) Date: Tue, 16 Dec 2008 10:38:45 -0800 (PST) Subject: sys.maxint in Python 2.6.1 (amd64) on Windows XP x64 Message-ID: <4bddf65a-bb9f-406c-a544-8c38b27547a7@b38g2000prf.googlegroups.com> Hi, I installed the amd64 version of Python 2.6.1 on my Windows XP x64 system. I was expecting sys.maxint to be 9223372036854775807 (or 2 ^63 -1), but instead I got 2147483647 (i.e., 2^31-1) just like what I got from a 32-bit version of Python. Is this by design or does it indicate a bug or an installation problem? Thank you very much! --lin From steve at holdenweb.com Mon Dec 15 12:04:31 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 15 Dec 2008 12:04:31 -0500 Subject: alt.possessive.its.has.no.apostrophe In-Reply-To: <4946826E.7060001@tim.thechases.com> References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> <49467CE2.3060401@holdenweb.com> <4946826E.7060001@tim.thechases.com> Message-ID: Tim Chase wrote: > Steve Holden wrote: >> This led to a schism between the British and the >> newly-independent Americans, who responded by taking the "u" >> out of colour, valour, and aluminium. > > Darn Americans and their alminim.... ;-) > > Next thing you know, they'll be putting an I in TEAM.[1] > It's called humour. Or humor. Or incompetence ;-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From __peter__ at web.de Fri Dec 19 04:36:53 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2008 10:36:53 +0100 Subject: eval() and global variables References: Message-ID: Juan Pablo Romero M?ndez wrote: > The hack given by Peter works fine, except in this case: > >>>> def aaaa(fn): > ... f2 = lambda x,y:(x,y,fn(x,y)) > ... function = type(f2) > ... f3 = function(f2.func_code,dict()) > ... print f3 > ... >>>> aaaa(lambda x,y:x+y) > Traceback (most recent call last): > File "", line 1, in > File "", line 4, in aaaa > TypeError: arg 5 (closure) must be tuple >>>> > > > Strange... The variable fn must be passed to the lambda somehow. You could return f2() from aaaa(), and f2() would still have to "know" about it. This is called a "closure". >>> def f(): pass ... >>> function = type(f) >>> print function.__doc__ function(code, globals[, name[, argdefs[, closure]]]) Create a function object from a code object and a dictionary. The optional name string overrides the name from the code object. The optional argdefs tuple specifies the default argument values. The optional closure tuple supplies the bindings for free variables. In your case we can reuse the closure just like the code: >>> def outer(fn): ... def inner(x, y): return x + fn(x, y) ... return function(inner.func_code, {}, closure=inner.func_closure) ... >>> outer(lambda a, b: a*b)(2, 3) 8 While we're at it, let's explore the remaining arguments: >>> f = outer(lambda a, b: a*b) >>> g = function(f.func_code, {}, "yadda", (10, 20), f.func_closure) >>> g >>> g() 210 Peter From google at mrabarnett.plus.com Mon Dec 8 17:28:16 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 08 Dec 2008 22:28:16 +0000 Subject: Text parsing via regex In-Reply-To: <37b28494-c98f-4e06-a451-8a4702030f10@v38g2000yqb.googlegroups.com> References: <37b28494-c98f-4e06-a451-8a4702030f10@v38g2000yqb.googlegroups.com> Message-ID: <493D9F80.2050102@mrabarnett.plus.com> Paul McGuire wrote: > On Dec 8, 12:13 pm, Robocop wrote: >> I'm having a little text parsing problem that i think would be really >> quick to troubleshoot for someone more versed in python and Regexes. >> I need to write a simple script that parses some arbitrarily long >> string every 50 characters, and does not parse text in the middle of >> words > > Are you just wrapping text? If so, then use the textwrap module. > > import textwrap > > source_string = "a bunch of nonsense that could be really long, or > really short depending on the situation" > > print textwrap.fill(source_string,50) > print textwrap.wrap(source_string,50) > > print map(len,textwrap.wrap(source_string,50)) > pad50 = lambda s : (s+ " "*50)[:50] > print '|\n'.join(map(pad50,textwrap.wrap(source_string,50))) > Instead of: pad50 = lambda s : (s+ " "*50)[:50] you could use: pad50 = lambda s: s.ljust(50) > Prints: > > a bunch of nonsense that could be really long, or > really short depending on the situation > ['a bunch of nonsense that could be really long, or', > 'really short depending on the situation'] > [49, 39] > a bunch of nonsense that could be really long, or | > really short depending on the situation > > -- Paul > > > -- > http://mail.python.org/mailman/listinfo/python-list > From prologic at shortcircuit.net.au Tue Dec 16 18:47:58 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 17 Dec 2008 09:47:58 +1000 Subject: Python is slow In-Reply-To: <705998e7-404f-4f4b-a2d6-566660e3e31a@o4g2000pra.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <355f1cfe-6abb-4d2c-8bf4-3aa62e713c1f@w34g2000yqm.googlegroups.com> <705998e7-404f-4f4b-a2d6-566660e3e31a@o4g2000pra.googlegroups.com> Message-ID: On Wed, Dec 17, 2008 at 9:08 AM, r wrote: > What about all the crap you had to go through just to get output? > Python wins Yes I can't say I really enjoy writing C (at all!) _except_ in the case where I may need to optimise some heavy computation. But then again with multi-core CPUs these days and cheap hardware, distributed processing is not only easy, but very effective! And I still wouldn't resort to C because well umm psyco is just awesome! --JamesMills From steve at REMOVE-THIS-cybersource.com.au Sun Dec 21 08:52:27 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Dec 2008 13:52:27 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <015da0a4$0$20656$c3e8da3@news.astraweb.com> Message-ID: <015e4162$0$20656$c3e8da3@news.astraweb.com> On Sun, 21 Dec 2008 12:45:32 +0000, Duncan Booth wrote: > Steven D'Aprano wrote: > >> Errors should never pass silently, unless explicitly silenced. You have >> implicitly silenced the TypeError you get from not having enough >> arguments for the first format operation. That means that you will >> introduce ambiguity and bugs. >> >> "%i %i %i %i" % 5 % 3 %7 >> >> Here I have four slots and only three numbers. Which output did I >> expect? >> >> '%i 5 3 7' >> '5 %i 3 7' >> '5 3 %i 7' >> '5 3 7 %i' >> >> Or more likely, the three numbers is a mistake, there is supposed to be >> a fourth number there somewhere, only now instead of the error being >> caught immediately, it won't be discovered until much later. >> > You seem to have made an unwarranted assumption, namely that a binary > operator has to compile to a function with two operands. There is no > particular reason why this has to always be the case: for example, I > believe that C# when given several strings to add together optimises > this into a single call to a concatenation method. [...] > Python *could* do something similar if the appropriate opcodes/methods > supported more than two arguments: > > a+b+c+d might execute a.__add__(b,c,d) allowing more efficient string > concatenations or matrix operations, and a%b%c%d might execute as > a.__mod__(b,c,d). That's only plausible if the operations are associative. Addition is associative, but string interpolation is not: >>> "%%%s" % ("%s" % "b") '%b' >>> ("%%%s" % "%s") % "b" Traceback (most recent call last): File "", line 1, in TypeError: not all arguments converted during string formatting Since string interpolation isn't associative, your hypothetical __mod__ method might take multiple arguments, but it would have to deal with them two at a time, unlike concatenation where the compiler could do them all at once. So whether __mod__ takes two arguments or many is irrelevant: its implementation must rely on some other function which takes two arguments and must succeed or fail on that. Either that, or we change the design of % interpolation, and allow it to silently ignore errors. I assumed that is what Aaron wanted. > In that alternate universe your example: > > "%i %i %i %i" % 5 % 3 %7 > > simply throws "TypeError: not enough arguments for format string" That has a disturbing consequence. Consider that most (all?) operations, we can use temporary values: x = 1 + 2 + 3 + 4 => x == 10 gives the same value for x as: temp = 1 + 2 + 3 x = temp + 4 I would expect that the same should happen for % interpolation: # using Aaron's hypothetical syntax s = "%s.%s.%s.%s" % 1 % 2 % 3 % 4 => "1.2.3.4" should give the same result as: temp = "%s.%s.%s.%s" % 1 % 2 % 3 s = temp % 4 But you're arguing that the first version should succeed and the second version, using a temporary value, should fail. And that implies that if you group part of the expression in parentheses, it will fail as well: s = ("%s.%s.%s.%s" % 1 % 2 % 3) % 4 Remove the parentheses, and it succeeds. That's disturbing. That makes the % operator behave very differently from other operators. Note that with the current syntax, we don't have that problem: short- supplying arguments leads to an exception no matter what. > "%s" % (1,2,3) > > just converts the tuple as a single argument. It also provides the > answer to how you put a percent in the format string (double it) I trust you know that already works, but just in case: >>> "%g%%" % 12.5 '12.5%' > and what happens if a substitution inserts a percent (it doesn't > interact with the formatting operators). Ditto: >>> "%s" % "%g" '%g' -- Steven From otrajman at gmail.com Fri Dec 19 19:10:39 2008 From: otrajman at gmail.com (otrajman at gmail.com) Date: Fri, 19 Dec 2008 16:10:39 -0800 (PST) Subject: setup.py installs modules to a wrong place References: <494384EF.7050605@logix.net.nz> Message-ID: <7d6d6971-e6cc-418f-a79e-598517ffb013@j38g2000yqa.googlegroups.com> Michal, I'm seeing this on fc8 with a custom built python2.6. Not happening with any other packages (e.g. boto). Workaround of course was just to copy the S3 dir to /usr/local/lib/python2.6/site-packages. I poked around a bit but nothing obvious jumped out. Happy to do any debugging if you have tests you'd like to me to run. -Omer From python.list at tim.thechases.com Fri Dec 26 19:46:09 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 26 Dec 2008 18:46:09 -0600 Subject: multiply each element of a list by a number In-Reply-To: References: Message-ID: <49557AD1.8080506@tim.thechases.com> > What does *not* work is > 3 * [0,1,2] > As you know, this gives > [0,1,2,0,1,2,0,1,2] > What I am hoping for is > [0,3,6] > I see that I can use > numpy.multiply(3,range(3)) > but this seems overkill to me. Can you tell I am coming to Python from > Matlab? The common way to do this is just a1 = [0,1,2] a2 = [x * 3 for x in a1] or, if you need a1 to be done in place: a1[:] = [x*3 for x in a1] -tkc From marco at sferacarta.com Wed Dec 17 11:07:39 2008 From: marco at sferacarta.com (Marco Mariani) Date: Wed, 17 Dec 2008 17:07:39 +0100 Subject: Selecting a different superclass In-Reply-To: References: Message-ID: Marco Mariani wrote: > I think you should investigate something different than subclassing, > like a "Strategy" domain pattern or something similar. s/domain/design/ From steve at holdenweb.com Thu Dec 11 14:49:23 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 11 Dec 2008 14:49:23 -0500 Subject: newbie question: if var1 == var2: In-Reply-To: <87abb21xzm.fsf@daycos.com> References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> Message-ID: Kirk Strauser wrote: > At 2008-11-29T04:02:11Z, Mel writes: > >> You could try >> >> for item in fname: >> item = item.strip() > > This is one case where I really miss Perl's "chomp" function. It removes a > trailing newline and nothing else, so you don't have to worry about losing > leading or trailing spaces if those are important to you. ... and it's so hard to write item = item[:-1] regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From Robert.T.Lynch at seagate.com Fri Dec 26 19:05:09 2008 From: Robert.T.Lynch at seagate.com (Robert.T.Lynch at seagate.com) Date: Fri, 26 Dec 2008 16:05:09 -0800 Subject: multiply each element of a list by a number Message-ID: What does *not* work is 3 * [0,1,2] As you know, this gives [0,1,2,0,1,2,0,1,2] What I am hoping for is [0,3,6] I see that I can use numpy.multiply(3,range(3)) but this seems overkill to me. Can you tell I am coming to Python from Matlab? Thanks -- Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From rt8396 at gmail.com Tue Dec 16 19:27:11 2008 From: rt8396 at gmail.com (r) Date: Tue, 16 Dec 2008 16:27:11 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <355f1cfe-6abb-4d2c-8bf4-3aa62e713c1f@w34g2000yqm.googlegroups.com> <705998e7-404f-4f4b-a2d6-566660e3e31a@o4g2000pra.googlegroups.com> Message-ID: On Dec 16, 5:47?pm, "James Mills" wrote: > On Wed, Dec 17, 2008 at 9:08 AM, r wrote: > > What about all the crap you had to go through just to get output? > > Python wins > > Yes I can't say I really enjoy writing C (at all!) > _except_ in the case where I may need to > optimise some heavy computation. But then > again with multi-core CPUs these days and > cheap hardware, distributed processing is > not only easy, but very effective! And I still > wouldn't resort to C because well umm > psyco is just awesome! > > --JamesMills This idiot(cm_gui) just needs to RTFM before going off on tirades like a 3 year old. What i find so funny is after Luis asked "what's the blazingly fast application you need to write so desperately?" we have yet to hear from this "expert programmer". He is probably still trying to get "hello world" to compile. From xahlee at gmail.com Wed Dec 10 16:12:44 2008 From: xahlee at gmail.com (Xah Lee) Date: Wed, 10 Dec 2008 13:12:44 -0800 (PST) Subject: looking up function's doc in emacs Message-ID: in programing elisp in emacs, i can press ?Ctrl+h f? to lookup the doc for the function under cursor. is there such facility when coding in perl, python, php? (i'm interested in particular python. In perl, i can work around with ?perldoc -f functionName?, and in php it's php.net/functionName. Both of which i have a elisp command with a shortcut that let me jump to the doc) Thanks. Xah ? http://xahlee.org/ ? From wx1234 at gmail.com Tue Dec 30 23:26:00 2008 From: wx1234 at gmail.com (dubux) Date: Tue, 30 Dec 2008 20:26:00 -0800 (PST) Subject: TypeError: list indices must be integers References: <2e5a61c0-fa99-4170-81ca-eb3a10859400@k36g2000pri.googlegroups.com> Message-ID: <98f638c1-d191-4f95-9668-01bc3c47526c@i20g2000prf.googlegroups.com> thanks for help everyone. it turned out the function itself worked fine.. it was the way i was calling it that was messing everything up. i ended up re-doing the whole thing as follows, and it now works perfectly. def news(x,y): news_file = '/home/scam/Desktop/www/info/news' news = open(news_file, 'r') news_list = news.readlines() news.close() if x == 'date': mylist = map(lambda i: news_list[i], filter(lambda i: i%2 == 0, range (len(news_list)))) date = mylist[y].replace("\n","") return '

    %s

    \n\n' % (date) if x == 'news': mylist = map(lambda i: news_list[i], filter(lambda i: i%2 == 1, range (len(news_list)))) news = mylist[y].replace("\n","") return '

    %s

    \n
    \n' % (news) else: return news_list news_parse, count, news_list = " ", 0, news('list','list') newss = map(lambda i: news_list[i], filter(lambda i: i%2 == 1, range (len(news_list)))) while count < len(newss): get_date = news('date', count) get_news = news('news', count) news_parse = '%s %s %s' % (news_parse, get_date, get_news) count = count + 1 From goyal.ak at gmail.com Sat Dec 13 22:54:31 2008 From: goyal.ak at gmail.com (Amit Goyal) Date: Sat, 13 Dec 2008 19:54:31 -0800 (PST) Subject: Error with SOAPpy Message-ID: <2da206ed-f3bb-4ef9-b43e-88ba799a9d87@a12g2000pro.googlegroups.com> Hi All, I am new to Python and was trying the sample code on Dive into Python for WSDL. Below is the error I get. Traceback (most recent call last): File "", line 4, in -toplevel- print 'Light sensor value: ' + server._ns(namespace).readLSpercent (int_1 = "1") File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 470, in __call__ return self.__r_call(*args, **kw) File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 492, in __r_call self.__hd, self.__ma) File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 363, in __call config = self.config) File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 187, in call r.endheaders() File "c:\Python24\lib\httplib.py", line 798, in endheaders self._send_output() File "c:\Python24\lib\httplib.py", line 679, in _send_output self.send(msg) File "c:\Python24\lib\httplib.py", line 646, in send self.connect() File "c:\Python24\lib\httplib.py", line 614, in connect socket.SOCK_STREAM): gaierror: (11001, 'getaddrinfo failed') I am using Python 2.4.4 and the following versions. >>> xml.__version__ '0.8.4' >>> fpconst.__version__ '0.7.2' >>> SOAPpy.__version__ '0.12.0' Regards, Amit From xahlee at gmail.com Wed Dec 10 17:15:09 2008 From: xahlee at gmail.com (Xah Lee) Date: Wed, 10 Dec 2008 14:15:09 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: <40b4b23f-c1eb-4ac5-bb42-e0f6276e97bf@r37g2000prr.googlegroups.com> Xah Lee wrote: > > For those of you who don't know linear algebra but knows coding, this > > means, we want a function whose input is a list of 3 elements say > > {x,y,z}, and output is also a list of 3 elements, say {a,b,c}, with > > the condition that > > > > a = x/Sqrt[x^2+y^2+z^2] > > b = y/Sqrt[x^2+y^2+z^2] > > c = z/Sqrt[x^2+y^2+z^2] > > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, > > you'll have 50 or hundreds lines. > > > > Note, that the ?norm? as defined above works for vectors of any > > dimention, i.e. list of any length. On Dec 10, 12:37 pm, w_a_x_... at yahoo.com wrote: > Ruby: > > def norm a > s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) > a.map{|x| x/s} > end I don't know ruby, but i tried to run it and it does not work. #ruby def norm a s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) a.map{|x| x/s} end v = [3,4] p norm(v) # returns [0.6, 0.8] The correct result for that input would be 5. Also note, i wrote: ?Note, that the ?norm? as defined above works for vectors of any dimention, i.e. list of any length.?. For detail, see: ? A Example of Mathematica's Expressiveness http://xahlee.org/UnixResource_dir/writ/Mathematica_expressiveness.html Xah ? http://xahlee.org/ ? From sjmachin at lexicon.net Sat Dec 13 17:09:04 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 13 Dec 2008 14:09:04 -0800 (PST) Subject: Python 3.0 crashes displaying Unicode at interactive prompt References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> Message-ID: On Dec 14, 8:07?am, "Chris Rebert" wrote: > On Sat, Dec 13, 2008 at 12:28 PM, John Machin wrote: > > > Python 2.6.1 (r261:67517, Dec ?4 2008, 16:51:00) [MSC v.1500 32 bit > > (Intel)] on win32 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> x = u'\u9876' > >>>> x > > u'\u9876' > > > # As expected > > > Python 3.0 (r30:67507, Dec ?3 2008, 20:14:27) [MSC v.1500 32 bit > > (Intel)] on win 32 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> x = '\u9876' > >>>> x > > Traceback (most recent call last): > > ?File "", line 1, in > > ?File "C:\python30\lib\io.py", line 1491, in write > > ? ?b = encoder.encode(s) > > ?File "C:\python30\lib\encodings\cp850.py", line 19, in encode > > ? ?return codecs.charmap_encode(input,self.errors,encoding_map)[0] > > UnicodeEncodeError: 'charmap' codec can't encode character '\u9876' in > > position > > 1: character maps to > > > # *NOT* as expected (by me, that is) > > > Is this the intended outcome? > > When Python tries to display the character, it must first encode it > because IO is done in bytes, not Unicode codepoints. When it tries to > encode it in CP850 (apparently your system's default encoding judging > by the traceback), it unsurprisingly fails (CP850 is an old Western > Europe codec, which obviously can't encode an Asian character like the > one in question). To signal that failure, it raises an exception, thus > the error you see. > This is intended behavior. I see. That means that the behaviour in Python 1.6 to 2.6 (i.e. encoding the text using the repr() function (as then defined) was not intended behaviour? > Either change your default system/terminal > encoding to one that can handle such characters or explicitly encode > the string and use one of the provided options for dealing with > unencodable characters. You are missing the point. I don't care about the visual representation. What I care about is an unambiguous representation that can be used when communicating about problems across cultures/ networks/mail-clients/news-readers ... the sort of problems that are initially advised as "I got this UnicodeEncodeError" and accompanied by no data or garbled data. > Also, please don't call it a "crash" as that's very misleading. The > Python interpreter didn't dump core, an exception was merely thrown. "spew nonsense on the screen and then stop" is about as useful and as astonishing as "dump core". core? You mean like ferrite doughnuts on a wire trellis? I thought that went out of fashion before cp850 was invented :-) From aaron.hildebrandt at gmail.com Mon Dec 1 14:31:03 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Mon, 1 Dec 2008 11:31:03 -0800 (PST) Subject: Checking a string against multiple matches Message-ID: <99a3a677-a38d-40f5-9a94-a98865150b69@k19g2000yqg.googlegroups.com> I've been trying to read up on this, but I'm not sure what the simplest way to do it is. I have a list of string. I'd like to check to see if any of the strings in that list matches another string. Pseudocode: if "two" in ["one", "two", "three", "four"]: return True Is there any built-in iteration that would do such a thing, or do I have to write a function to check for me? I was using .index on the list, but it would return True for strings that contained the search string rather than match it exactly, leading to false positives in my code. From prologic at shortcircuit.net.au Mon Dec 29 22:08:16 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 30 Dec 2008 13:08:16 +1000 Subject: multiprocessing vs thread performance In-Reply-To: References: <26f7d44e-552c-41e9-9290-17e5c4e6deb9@q30g2000prq.googlegroups.com> Message-ID: On Tue, Dec 30, 2008 at 12:52 PM, Aaron Brady wrote: > On Dec 29, 7:40 pm, "James Mills" > wrote: >> On Tue, Dec 30, 2008 at 11:34 AM, Aaron Brady wrote: >> > The OP may be interested in Erlang, which Wikipedia (end-all, be-all) >> > claims is a 'distribution oriented language'. > snip >> I'm presently looking at Virtual Synchrony and >> other distributed processing architectures - but >> circuits is meant to be general purpose enough >> to fit event-driven applications/systems. > > I noticed a while ago that threads can be used to simulate > generators. 'next', 'send', and 'yield' are merely replaced by > synchronizor calls (coining the term). > > Not the other way around, though, unless the generator guarantees a > yield frequently. 'settrace' anyone? Aaron, circuits doesn't use generators :) What did your comment have to do with this ? I have often seen generators used to facilitate coroutine and coooperative programming though. cheers James From joe at strout.net Mon Dec 8 10:18:27 2008 From: joe at strout.net (Joe Strout) Date: Mon, 8 Dec 2008 08:18:27 -0700 Subject: A question about reference in Python. In-Reply-To: <493CB003.3080209@gmail.com> References: <493CB003.3080209@gmail.com> Message-ID: On Dec 7, 2008, at 10:26 PM, Group wrote: > Now, I want to write a Red-Black Tree, and a List structure. In C/C+ > +, I can > use pointers to refer to children notes (or next notes). But, in > Python, how > can I do it? Except the sequence, I know not any way. Any variable in Python is a reference, which is roughly analogous to a pointer type in C/C++. For details and examples, see: Best, - Joe From stargaming at gmail.com Mon Dec 22 07:06:46 2008 From: stargaming at gmail.com (Robert Lehmann) Date: 22 Dec 2008 12:06:46 GMT Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <494f82d6$0$9151$9b622d9e@news.freenet.de> On Mon, 22 Dec 2008 12:31:44 +0100, Pierre-Alain Dorange wrote: >> > I don't find any sign(x) function in the math library (return the >> > sign of the value). >> > I've read that math module is a wrapper to C math lib and that C math >> > lib has not sign(), so... [snip] > As my need is for a game and that i do not have IEEE real concern, i > would simply using my simple function (but not as accurate) : > > def sign(x): > if x==0.0: > return 0.0 > elif x>0.0: > return 1.0 > else: > return -1.0 I found this snippet to be quite succinct (even though being smart *might* be wrong in programming):: sign = lambda x:+(x > 0) or -(x < 0) HTH, -- Robert "Stargaming" Lehmann From gregory.j.baker at gmail.com Tue Dec 2 15:27:15 2008 From: gregory.j.baker at gmail.com (gregory.j.baker at gmail.com) Date: Tue, 2 Dec 2008 12:27:15 -0800 (PST) Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> Message-ID: Try using the following at the begining of your Python program: import sys sys.stdout = open("out.txt","w") sys.stderr = open("err.txt","w") Then whatever would normally go to stdout or stderr goes to text files instead. You will see everything that happened. From febaen at gmail.com Sun Dec 14 05:53:10 2008 From: febaen at gmail.com (feba) Date: Sun, 14 Dec 2008 02:53:10 -0800 (PST) Subject: Need help improving number guessing game References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> Message-ID: <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> #!/usr/bin/python #Py3k, UTF-8 import random def setup(): #global target, guess, a, b #a, b make minimum, maximum. Can be adjusted. a, b = 1, 99 target = random.randint(a, b) return a, b, target def playerswitch(player): #Player Switch #if player's a witch, burn her! if player == "P1": player = "P2" else: player = "P1" return player def youwin(pnum, player, p1sc, p2sc): if pnum == 1: print("CONGRATULATIONS!") else: if player == "P1": p1sc += 1 else: p2sc += 1 end = "CONGRATULATIONS %s! SCORE -- P1:%s P2:%s" print(end %(player, p1sc, p2sc)) return p1sc, p2sc def playagain(play): playover = input("PLAY AGAIN? Y/N: ") if playover.strip().lower() == "y": play = 1 a, b, target = setup() else: print("GOOD BYE. PLAY AGAIN SOON!") quit() return play, a, b, target def guesscheck(guess, target, play, a, b, p1sc, p2sc): if guess == target: p1sc, p2sc = youwin(pnum, player, p1sc, p2sc) play, a, b, target = playagain(play) elif guess >= b: print("NUMBER MUST BE IN RANGE") guess = int(input("[%s-%s]%s>> " % (a, b, player))) play, a, b, target, p1sc, p2sc = guesscheck(guess, target, play, a, b, p1sc, p2sc) elif guess <= a: print("NUMBER MUST BE IN RANGE") guess = int(input("[%s-%s]%s>> " % (a, b, player))) play, a, b, target, p1sc, p2sc = guesscheck(guess, target, play, a, b, p1sc, p2sc) elif guess > target: print("TOO HIGH") b = guess else: print("TOO LOW") a = guess return play, a, b, target, p1sc, p2sc def guessing(a, b, player, pnum, target, p1sc, p2sc, play): #a and b are to keep the user aware of min/max guess = int(input("[%s-%s]%s>> " % (a, b, player))) play, a, b, target, p1sc, p2sc = guesscheck(guess, target, play, a, b, p1sc, p2sc) if pnum == 2: player = playerswitch(player) return play, a, b, player, target, p1sc, p2sc #Let the show begin! print("WELCOME TO THE SUPER NUMBER GUESSING GAME!") pnum = int(input("1 OR 2 PLAYERS?\n> ")) play = 1 player = "P1" # P1 goes first #Scores, keep track of times player guessed first. p1sc, p2sc = 0, 0 #Grabs minimum, maximum, and target numbers a, b, target = setup() while play == 1: play, a, b, player, target, p1sc, p2sc \ = guessing(a, b, player, pnum, target, p1sc, p2sc, play) This is what I have now. It seems to work perfectly, and I tried to work in your suggestions. Thanks, by the way, for recommending the style guide. I've bookmarked it, and I'll try to remember to consult it in the future. One (extremely minor) annoyance is that if you have only one possible guess left you still have to type it in manually. As an example, [30-32]P#>> can only possibly be 31 (and I've changed it so that any number >= 32 or <= 30 won't be accepted, so it's all the user can input), which means whatever player is in control has a %100 chance of winning. I know that "if b - a == 2" would be a simple enough test for this, but I'm not quite sure when to put it, or what to do with it. And yes, I'm aware that guess = int(input("[%s-%s]%s>> " % (a, b, player))) play, a, b, target, p1sc, p2sc = guesscheck(guess, target, play, a, b, p1sc, p2sc) is repeated three times. I will probably try to change this into a function later on; right now, I just spent a few hours trying to get this to work and making sure that it does (by playing it), so I'm going to take a break. From dlemper Sun Dec 21 16:42:39 2008 From: dlemper (dlemper) Date: Sun, 21 Dec 2008 15:42:39 -0600 Subject: wxpython for python 3.0 ? Message-ID: The wxpython web describes compatability with python 2.4 & 2.5 . Does it work with 3.0 ? If not, anyone have a clue as to when ? From bj_666 at gmx.net Fri Dec 12 06:08:09 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 12 Dec 2008 11:08:09 GMT Subject: File names, character sets and Unicode References: Message-ID: <6qev0oFc3a5jU1@mid.uni-berlin.de> On Fri, 12 Dec 2008 23:32:27 +1300, Michal Ludvig wrote: > is there any way to determine what's the charset of filenames returned > by os.walk()? No. Especially under *nix file systems file names are just a string of bytes, not characters. It is possible to have file names in different encondings in the same directory. > The trouble is, if I pass argument to os.walk() I get the > filenames as byte-strings. Possibly UTF-8 encoded Unicode, who knows. Nobody knows. :-) > What's the right and safe way to walk the filesystem and get some > meaningful filenames? The safe way is to use `str`. > Related question - if the directory is given name on a command line > what's the right way to preprocess the argument before passing it down > to os.walk()? Pass it as is. > For instance with LANG=en_NZ.UTF-8 (i.e. UTF-8 system): * directory is > called 'smile?' > * sys.argv[1] will be 'smile\xe2\x98\xba' (type str) * after > .decode("utf-8") I get u'smile\u263a' (type unicode) > > But how should I decode() it when running on a system where $LANG > doesn't end with "UTF-8"? Apparently some locales have non-ascii default > charsets. For instance zh_TW is BIG5 charset by default, ru_RU is > ISO-8850-5, etc. How do I detect that to get the right charset for > decode()? You can't. Even if you know the preferred encoding of the system, e.g. via $LANG, there is no guarantee that all file names are encoded this way. > I tend to have everything internally in Unicode but it's often unclear > how to convert some inputs to Unicode in the first place. What are the > best practices for dealing with these chraset issues in Python? I'm usually using UTF-8 as default but offer the user ways, e.g. command line switches, to change that. If I have to display file names in a GUI I use a decoded version of the byte string file name, but keep the byte string for operations on the file. Ciao, Marc 'BlackJack' Rintsch From pruebauno at latinmail.com Tue Dec 9 12:02:42 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Tue, 9 Dec 2008 09:02:42 -0800 (PST) Subject: When (and why) to use del? References: Message-ID: On Dec 9, 11:35?am, Albert Hopkins wrote: > I'm looking at a person's code and I see a lot of stuff like this: > > ? ? ? ? def myfunction(): > ? ? ? ? ? ? # do some stuff stuff > ? ? ? ? ? ? my_string = function_that_returns_string() > ? ? ? ? ? ? # do some stuff with my_string > ? ? ? ? ? ? del my_string > ? ? ? ? ? ? # do some other stuff > ? ? ? ? ? ? return > > and also > > ? ? ? ? def otherfunction(): > ? ? ? ? ? ? try: > ? ? ? ? ? ? ? ? # some stuff > ? ? ? ? ? ? except SomeException, e: > ? ? ? ? ? ? ? ? # more stuff > ? ? ? ? ? ? ? ? del e > ? ? ? ? ? ? return > > I think this looks ugly, but also does it not hurt performance by > preempting the gc? ?My feeling is that this is a misuse of 'del'. Am I > wrong? ?Is there any advantage of doing the above? If this is CPython (the standard Python) the extra del(s) in the examples you gave are just garbage and good for nothing. The reason being that they are inside a function; as soon as the program exits the function the variable gets deleted automatically. The only reason to use del would be a global variable in long running program that uses a lot of space, but global variables should be avoided for other reasons anyway. I never ever used del in my programs only on the interactive interpreter prompt after doing foolish things like x=open ('1GBfile').read() From nicolas.delanos at gmail.com Fri Dec 26 16:54:25 2008 From: nicolas.delanos at gmail.com (nicolas.delanos at gmail.com) Date: Fri, 26 Dec 2008 13:54:25 -0800 (PST) Subject: Python and DomainKey Message-ID: <63e888c6-d20b-414e-87f6-e998d8fb669e@v4g2000vbb.googlegroups.com> Hello, I'm working on a script able to send email using DomainKey and DKIM. For DKIM, it's working well (Thanks Greg - pydkim) but with DomainKey, I have trouble. There is no library yet able to sign emails. I tried to modify the pydkim library to implement DK but everything I have a "sig fail". Do you know a dk library ? From steve at REMOVE-THIS-cybersource.com.au Thu Dec 18 21:11:28 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2008 02:11:28 GMT Subject: Factoring Polynomials References: <015aebdf$0$20656$c3e8da3@news.astraweb.com> Message-ID: <015afa29$0$20656$c3e8da3@news.astraweb.com> On Thu, 18 Dec 2008 17:42:28 -0800, Collin D wrote: > The corrected function is: > def quadratic_solution(a,b,c) > sol1 = -1*b + ((b**2 - 4*a*c)**.5)/2*a > sol1 = -1*b - ((b**2 - 4*a*c)**.5)/2*a > return (sol1, sol2) > > Squaring the -b would give you some strange solutions.... :D So it would, but I didn't do that. Try again. You have a typo in the above: you've written "sol1" twice and there is no sol2. There is no difference between -1*b and -b (except that -b is probably a smidgen faster). In the quadratic formula, the -b must be divided by 2a as well as the discriminant. You're only dividing the discriminant. The *second* error has already been given away by Mark Dickson, who rightly points out that the quadratic equation is subject to round-off errors. The first error is still there :) (Hint: think about the precedence of operators and the need for brackets.) -- Steven From greywine at gmail.com Wed Dec 24 00:59:42 2008 From: greywine at gmail.com (greywine at gmail.com) Date: Tue, 23 Dec 2008 21:59:42 -0800 (PST) Subject: socket send help Message-ID: Hi everyone, New guy here. I'm trying to figure out sockets in order to one day do a multiplayer game. Here's my problem: even the simplest examples don't work on my computer: A simple server: from socket import * myHost = '' myPort = 21500 s = socket(AF_INET, SOCK_STREAM) # create a TCP socket s.bind((myHost, myPort)) # bind it to the server port s.listen(5) # allow 5 simultaneous connections while True: connection, address = s.accept() while True: data = connection.recv(1024) if data: connection.send('echo -> ' + data) else: break connection.close() # close socket And a simple client: import sys from socket import * serverHost = 'localhost' # servername is localhost serverPort = 21500 # use arbitrary port > 1024 s = socket(AF_INET, SOCK_STREAM) # create a TCP socket s.connect((serverHost, serverPort)) # connect to server on the port s.send('Hello world') # send the data data = s.recv(1024) # receive up to 1K bytes print(data) If I run testserver.py via the cmd prompt in Windows XP and then the testclient.py program, I get the following error: Traceback (most recent call last): File "C:\Python30\testclient.py", line 12, in s.send('Hello world') # send the data TypeError: send() argument 1 must be string or buffer, not str This happens in 2.6 or 3.0 and with different example client & server programs from the web. What am I missing? Thanks, John R. From deets at nospam.web.de Thu Dec 11 18:03:25 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 12 Dec 2008 00:03:25 +0100 Subject: Best way of debigging a C extension In-Reply-To: References: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> <6qdjt7Fc1fg0U1@mid.uni-berlin.de> Message-ID: <6qdkhtFc5ce1U1@mid.uni-berlin.de> Grant Edwards schrieb: > On 2008-12-11, Diez B. Roggisch wrote: > >> I never tried this on windows - but what happens if you start >> python inside GDB, and then set breakpoints inside your >> extension? >> >> This works flawlessly for me under *nix. >> >> The debug-build of python isn't needed for this - and I doubt >> a bit that it helps you much, as being inside the interpreter >> & getting detailed information isn't your goal - you want to >> see your extensions functions, what parameters they get and so >> on. > > It's probably a lot easier to just stick in a few printf() > calls in key places... > Easier than $ gdb python # set args myscript.py # break some_function_of_mine ? Diez From ldo at geek-central.gen.new_zealand Wed Dec 3 02:45:18 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 03 Dec 2008 20:45:18 +1300 Subject: Linear2D Message-ID: I've decided to give Github a go, with a simple project containing some routines for performing 2D linear transformations . This takes a functional rather than procedural approach. For example, a function to construct a matrix that maps a source rectangle to a destination rectangle is def MapRect(SrcRect, DstRect) : return \ ( Matrix.translation(- SrcRect.topleft()) * Matrix.scaling(DstRect.dimensions() / SrcRect.dimensions()) * Matrix.translation(DstRect.topleft()) ) #end MapRect From nick at craig-wood.com Mon Dec 8 05:30:50 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 08 Dec 2008 04:30:50 -0600 Subject: Learning Python now coming from Perl References: Message-ID: Bertilo Wennergren wrote: > I'm planning to start learning Python now, using Python 3000. > I have no previous Python skills, but I now Perl pretty well. > I'm also well experienced with JavaScript. > > Any pointers and tips how I should go about getting into > Python? Read "Dive Into Python" while following along with your keyboard. ( http://www.diveintopython.org/ free online or paper edition from your favourite bookseller ) My favourite mistake when I made the transition was calling methods without parentheses. In perl it is common to call methods without parentheses - in python this does absolutely nothing! pychecker does warn about it though. perl -> $object->method python -> object.method() -- Nick Craig-Wood -- http://www.craig-wood.com/nick From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 18:35:44 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Dec 2008 23:35:44 GMT Subject: Python 3.0 automatic decoding of UTF16 References: <5u8o06xbqf.ln2@joeserver.homelan.net> Message-ID: <0149b28c$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 12:00:59 -0700, Joe Strout wrote: >> So UTF-16 has an explicit EOF marker within the text? > > No, it does not. I don't know what Terry's thinking of there, but text > files do not have any EOF marker. They start at the beginning > (sometimes including a byte-order mark), and go till the end of the > file, period. Windows text files still interpret ctrl-Z as EOF, or at least Windows XP does. Vista, who knows? -- Steven From robert.kern at gmail.com Fri Dec 19 18:39:51 2008 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 19 Dec 2008 17:39:51 -0600 Subject: IDLE doesn't show stderr output from extension modules In-Reply-To: <6406df08-36bb-4cd8-a356-6d563c2eac7f@e1g2000pra.googlegroups.com> References: <6406df08-36bb-4cd8-a356-6d563c2eac7f@e1g2000pra.googlegroups.com> Message-ID: Brian Cole wrote: > I'm importing an extension module created with SWIG. When working with > the module interactively in IDLE there should be warning and error > messages printed to stderr by the extension module. However, these are > not being caught by the IDLE window, they are going directly to the > terminal that was used to start IDLE. > > Strange, because sys.stderr.write() does print to the IDLE window. > I've tried this on Windows and OSX, so it doesn't appear to be a > platform issue. Is this just a fundamental deficiency in the IDLE > shell prompt? Yup. IDLE swaps out the sys.stdout and sys.stderr objects at the Python level. It does not replace the STDOUT and STDERR C file pointers. Python code and C extension modules which use the Python APIs to write stuff out should get redirected, but extension modules that use fprintf(), etc., directly to STDOUT and STDERR won't. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From benjamin.kaplan at case.edu Sun Dec 21 17:40:31 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 21 Dec 2008 17:40:31 -0500 Subject: wxpython for python 3.0 ? In-Reply-To: References: Message-ID: On Sun, Dec 21, 2008 at 4:42 PM, wrote: > The wxpython web describes compatability with python 2.4 & 2.5 . > Does it work with 3.0 ? If not, anyone have a clue as to when ? This question was asked a couple of times on the wxpython-users mailing list. It's probably going to take a while. For now, I'd stick to python 2.x. The next version of wxPython should support 2.6, so use that and try to make your code relatively compatible with Python 3 (use the division, print_function, and unicode_literals future imports). Then, you'll be all set when Robin gets around to porting everything to Python 3. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sat Dec 6 22:09:23 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 03:09:23 GMT Subject: "as" keyword woes References: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> <0147dc24$0$20670$c3e8da3@news.astraweb.com> <0148b217$0$20670$c3e8da3@news.astraweb.com> <7d0lj4d9hai2f87r30erc4l1ir85osbfg7@4ax.com> <88579d9a-df52-49b9-a6fe-53c8f4524bf3@j39g2000yqn.googlegroups.com> <70llj41hie2svs68o5efn22i97f649svfh@4ax.com> <1cda9a9a-1641-424b-9f3d-c4e2635efed7@j38g2000yqa.googlegroups.com> <014b0f94$0$20670$c3e8da3@news.astraweb.com> <4469f2ed-f012-400d-9d4f-bd44cd075d0d@w34g2000yqm.googlegroups.com> Message-ID: <014b3616$0$20670$c3e8da3@news.astraweb.com> On Sat, 06 Dec 2008 18:09:07 -0800, Mensanator wrote: > On Dec 6, 6:25?pm, Steven D'Aprano cybersource.com.au> wrote: >> On Sat, 06 Dec 2008 14:36:07 -0800, Mensanator wrote: >> > It was extremely simple for me to fix the sympy module where I >> > noticed it. I'm not saying it wasn't a problem, I'm saying it wasn't >> > BROKEN. >> >> If it wasn't broken, why did you need to fix it? > > If my tire is flat, I have to fix it. But it may just need air, in which > case it's not broken. In which case it doesn't need *fixing*, it needs *refilling*. A flat tire isn't necessarily broken. It is broken if it has a puncture or a slow leak or has been ripped to shreds, but not if somebody merely let the air out. "Air comes out if you open the value" is within standard operating parameters and the tire is therefore working correctly. >> "Broken" means "not working", not "unfixable". > > So, you're saying that Python is broken and will remain so forever, > since "as" will remain a keyword? I don't think that having "as" be a keyword is broken. I think the OP's code is broken for Python 2.6 or better, and it will remain broken forever unless he fixes it or chooses to stay with 2.5. > Are you advocating that we all switch to Ruby? Why do you think that? Do you imagine that Ruby has no features which are inconvenient to users, or backwards incompatibilities, or warts, or that it is impossible to write broken Ruby code? -- Steven From hubaghdadi at gmail.com Sun Dec 28 07:06:36 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Sun, 28 Dec 2008 04:06:36 -0800 (PST) Subject: What is site-packages? References: Message-ID: On Dec 28, 2:04?pm, "Chris Rebert" wrote: > On Sun, Dec 28, 2008 at 3:40 AM, Hussein B wrote: > > Hey, > > What is /usr/lib/pythonx.y/site-packages folder and for what it is > > used usually? > > I believe it's where third-party libraries are typically installed to. > > Cheers, > Chris > > -- > Follow the path of the Iguana...http://rebertia.com You mean like MoinMoin, Django or Pylons for example? From thudfoo at opensuse.us Thu Dec 11 14:44:31 2008 From: thudfoo at opensuse.us (member thudfoo) Date: Thu, 11 Dec 2008 11:44:31 -0800 Subject: Equivalent of 'wget' for python? In-Reply-To: References: Message-ID: <3d881a310812111144k238fb4d2rc07d3f3a0593bba3@mail.gmail.com> On Mon, Dec 8, 2008 at 8:22 AM, Robert Dailey wrote: > Hi, > > I'm looking for a portable way to download ZIP files on the internet > through Python. I don't want to do os.system() to invoke 'wget', since > this isn't portable on Windows. I'm hoping the core python library has > a library for this. Note that I'll be using Python 3.0. > > Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > This module might be of interest: http://linux.duke.edu/projects/urlgrabber/ From istvan.albert at gmail.com Thu Dec 4 13:20:00 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Thu, 4 Dec 2008 10:20:00 -0800 (PST) Subject: Python 3 read() function References: Message-ID: <7cda0d37-a14e-49c2-a140-c9a4836a86af@i18g2000prf.googlegroups.com> I can confirm this, I am getting very slow read performance when reading a smaller 20 MB file. - Python 2.5 takes 0.4 seconds - Python 3.0 takes 62 seconds fname = "dmel-2R-chromosome-r5.1.fasta" data = open(fname, 'rt').read() print ( len(data) ) From prologic at shortcircuit.net.au Tue Dec 30 19:52:57 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 10:52:57 +1000 Subject: multiprocessing vs thread performance In-Reply-To: References: <26f7d44e-552c-41e9-9290-17e5c4e6deb9@q30g2000prq.googlegroups.com> <47cfc6de-4b13-4a74-accc-c1d027c44d5a@35g2000pry.googlegroups.com> Message-ID: On Wed, Dec 31, 2008 at 8:42 AM, James Mills wrote: (snip) > As I continue to develop circuits and improve it's > core design as well as building it's ever growing set > of Components, I try to keep it as general as > possible - my main aim though is distributed > processing and architectures. (See the primes example). Aaron, just wanted to demonstrate to you the example (primes) that I mentioned above: On Terminal A: jmills at atomant:~/circuits/examples$ ./primes.py -o primes.txt -b 127.0.0.1:8000 -p 1000 -w Total Primes: 1001 (23/s after 44.16s) Total Events: 43373 (983/s after 44.16s) Distribution: c1096b40-7606-4ba7-9593-1385e14ef339: 348 8313b43f-d45d-4a0a-8d87-e6a93d3dfb0b: 653 On Terminal B: jmills at atomant:~/other/circuits/examples$ ./primes.py -b 127.0.0.1:8001 -s 127.0.0.1:8000 The example uses circuits to distribute work amongst any arbitrary number of nodes connected to the system. This is all manually implemented by simply taking advantage of the circuits framework with my basic understanding ( so far ) of distributed processing, virtual synchrony, and other techniques. This is the same thing just run on a single node (no distribution): jmills at atomant:~/circuits/examples$ ./primes.py -o primes.txt -b 127.0.0.1:8000 -p 1000 Total Primes: 1001 (17/s after 62.13s) Total Events: 28579 (460/s after 62.13s) Distribution: 701be749-9833-40a4-9181-5ee18047b1ad: 1001 As you can see, running 2 instances almost halves the time. If you do try this though, you'll note that the CPU isn't being used very heavily at all - This could be improved - but the example merely demonstrates distributed event processing and syncronization. cheers James From tjreedy at udel.edu Tue Dec 23 17:04:20 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Dec 2008 17:04:20 -0500 Subject: [ANN] Python 2.5.4 (final) In-Reply-To: <4951482D.8050302@v.loewis.de> References: <4951482D.8050302@v.loewis.de> Message-ID: Martin v. L?wis wrote: > For more information on Python 2.5.4, including download > links for various platforms, release notes, and known issues, please > see: > > http://www.python.org/2.5.4 http://www.python.org/download/releases/2.5.4/ From gubatron at gmail.com Wed Dec 3 13:01:54 2008 From: gubatron at gmail.com (Gubatron) Date: Wed, 3 Dec 2008 10:01:54 -0800 (PST) Subject: Jython: Packing several .py on .jar, problem importing .py modules within the .jar References: <0ad925d8-f890-4b12-b0e0-e8c3a7dacf8c@v4g2000yqa.googlegroups.com> Message-ID: <7b48c8b2-7fb2-4e23-bdc2-d1cb7ab361d9@e18g2000yqo.googlegroups.com> cont... Take in consideration /** Hashtable of URLClassLoaders for each of the jars loaded */ private Hashtable classLoaders; Here's an example: org.python.core.PySystemState pySys = new org.python.core.PySystemState(); //classLoaders is a set that refers to a bunch of URLClassLoader objects pySys.setClassLoader(((URLClassLoader) classLoaders.get(jarFile))); //We also have to pass the jar to JYTHON_PATH (sys.path) //so that it can properly import inner python modules. pySys.path.insert(0,new PyString(jarFile)); //We pass the PythonInterpreter the modified PySystemState PythonInterpreter i = new PythonInterpreter (null, pySys); i.exec(pythonScriptName); Here's my method to create a classLoader that has a jarFile in its classpath: /** * Adds a given Jar to the Classpath. * Jython uses both classloaders, and it's JYTHONPATH (sys.path) * The classloaders help it find Java classes, in this case inside the jar * that contains the plugin. * * @param jarFile * * Where jarFile is the path (String) to the jarFile. * * I won't delete it though, in case it might be needed to load resources from * the jar. However, I believe the adition to the sys.path of jython will be enough. */ public void addJar2Classpath(String jarFile) throws Exception { if (jarFile == null) throw new Exception("PluginLoader.addJar2Classpath() - the jar file path can't be null"); File f = new File(jarFile); if (!f.exists()) { LOG.error("Jar doesn't exist ("+jarFile+")"); throw new Exception("PluginLoader.addJar2Classpath() - The jar file doesn't exist ("+ jarFile +")"); } URL jarURL = null; try { jarURL = new URL("jar:file:"+jarFile+"!/"); //jarURL = f.toURI().toURL(); LOG.info("The jar as an url " + jarURL); } catch (Exception e) { LOG.error("Bad URL for jar ("+jarFile+"):\n"+e.toString() +" ("+jarURL+")\n"); return; } if (loadedJar(jarURL)) { LOG.info("Jar was already loaded ("+jarURL+")"); return; } synchronized (classLoaders) { getLoadedJars().add((URL) jarURL); } //Create a new class loader for this jar. classLoaders.put(jarFile, URLClassLoader.newInstance(new URL[] {jarURL})); LOG.info("Jar loaded ("+jarURL+")"); } //addJar2Classpath So if we had a Jar like this: M Filemode Length Date Time File - ---------- -------- ----------- -------- ------------------------------------- drwxrwxrwx 0 3-Dec-2008 12:46:22 meta-inf/ -rw-rw-rw- 71 3-Dec-2008 12:46:22 meta-inf/manifest.mf drwxrwxrwx 0 3-Dec-2008 12:46:22 twoScriptsTest/com/ -rw-rw-rw- 491 3-Dec-2008 12:46:22 twoScriptsTest/com/ HelloFromJar.class drwxrwxrwx 0 3-Dec-2008 12:46:18 twoScriptsTest/guba/ -rw-rw-rw- 0 3-Dec-2008 06:24:22 twoScriptsTest/guba/ __init__.py -rw-rw-rw- 959 3-Dec-2008 12:46:18 twoScriptsTest/guba/ test.py -rw-rw-rw- 124 2-Dec-2008 17:50:56 twoScriptsTest/guba/ pleaseWork.py -rw-rw-rw- 0 3-Dec-2008 12:29:56 twoScriptsTest/ __init__.py - ---------- -------- ----------- -------- ------------------------------------- When we executed: i.exec("from guba import test") if test.py had this code, it'd work perfectly: #Import and use the Java Object inside the jar from com import HelloFromJar h = HelloFromJar() h.sayHello() #Import the other python module inside the jar from pleaseWork import echo echo("FrostWire") NOTE: It's very important that you have the __init__.py on the folders otherwise Jython won't find the modules. On Dec 3, 12:54?pm, Gubatron wrote: > I've managed to solve this problem. > > I can now run a python script that lives inside a Jar. The python > script is now able to import other scripts within the same jar, and > it's also able to import java classes that live within the jar. > > The problem was solved by giving the Jython Interpreter the proper > initialization. This entails: > > - Giving it a class loader that has put the Jar on it's class path > - Adding the path of the jar to the interpreter's sys.path > > Here's an example: > > ? ? ? ? ? ? ? ? ? ? ? ? org.python.core.PySystemState pySys = new > org.python.core.PySystemState(); > ? ? ? ? ? ? ? ? ? ? ? ? pySys.setClassLoader(((URLClassLoader) classLoaders.get(jarFile))); > > ? ? ? ? ? ? ? ? ? ? ? ? //We also have to pass the jar to JYTHON_PATH (sys.path) > ? ? ? ? ? ? ? ? ? ? ? ? //so that it can properly import inner python modules. > ? ? ? ? ? ? ? ? ? ? ? ? pySys.path.insert(0,new PyString(jarFile)); > > ? ? ? ? ? ? ? ? ? ? ? ? //We pass the PythonInterpreter the modified PySystemState > ? ? ? ? ? ? ? ? ? ? ? ? PythonInterpreter i = new PythonInterpreter(null, pySys); > ? ? ? ? ? ? ? ? ? ? ? ? i.exec(pythonScriptName); > > On Dec 3, 6:31?am, Gubatron wrote: > > > Hello all, > > > I've a problem with Jython and importing .py inside a jar. > > > I'm putting .class and .py files inside .jar files. > > > myjar.jar > > ? MyJar\SomeClass.class > > ? MyJar\main.py > > ? MyJar\otherModule.py > > > So I add the myjar.jar to Jython's sys.path > > > ? ? ? ? ? ? ? ? ? ? ? ? org.python.core.PySystemState pySys = new > > org.python.core.PySystemState(); > > ? ? ? ? ? ? ? ? ? ? ? ? pySys.path.insert(0,new PyString("/path/to/myjar.jar")); > > > and execute main.py > > > ? ? ? ? ? ? ? ? ? ? ? ? //We pass the PythonInterpreter the modified PySystemState > > ? ? ? ? ? ? ? ? ? ? ? ? PythonInterpreter i = new PythonInterpreter(null, pySys); > > > ? ? ? ? ? ? ? ? ? ? ? ? //Find the entry in the jar for the python file and execute it. > > ? ? ? ? ? ? ? ? ? ? ? ? //It should be able to find any resource inside the jar. > > ? ? ? ? ? ? ? ? ? ? ? ? JarFile jFile = new JarFile("/path/to/myjar.jar"); > > ? ? ? ? ? ? ? ? ? ? ? ? ZipEntry zipEntry = jFile.getEntry("MyJar/main.py"); > > > ? ? ? ? ? ? ? ? ? ? ? ? InputStream pythonInputStream = > > jFile.getInputStream(zipEntry); > > ? ? ? ? ? ? ? ? ? ? ? ? i.execfile(pythonInputStream); > > > main.py will execute fine, it'll be able to do > > > from MyJar import SomeClass > > > with no problem > > > However, If I try to import the other .py in the same jar, it won't > > find it: > > > from otherModule import * > > > or > > > from MyJar.otherModule import * > > > I always get this: > > > ImportError: no module named otherModule > > > ? ? ? ? at org.python.core.Py.ImportError(Unknown Source) > > ? ? ? ? at org.python.core.imp.import_first(Unknown Source) > > ? ? ? ? at org.python.core.imp.import_name(Unknown Source) > > ? ? ? ? at org.python.core.imp.importName(Unknown Source) > > ? ? ? ? at org.python.core.ImportFunction.load(Unknown Source) > > ? ? ? ? at org.python.core.ImportFunction.__call__(Unknown Source) > > ? ? ? ? at org.python.core.PyObject.__call__(Unknown Source) > > ? ? ? ? at org.python.core.__builtin__.__import__(Unknown Source) > > ? ? ? ? at org.python.core.imp.importFromAs(Unknown Source) > > ? ? ? ? at org.python.core.imp.importFrom(Unknown Source) > > ? ? ? ? at org.python.pycode._pyx1.f$0(:26) > > ? ? ? ? at org.python.pycode._pyx1.call_function() > > ? ? ? ? at org.python.core.PyTableCode.call(Unknown Source) > > ? ? ? ? at org.python.core.PyCode.call(Unknown Source) > > ? ? ? ? at org.python.core.Py.runCode(Unknown Source) > > ? ? ? ? at org.python.util.PythonInterpreter.execfile(Unknown Source) > > > I've tried adding more paths to sys.path, with no luck: > > > pySys.path.insert(0,new PyString("/path/to/myjar.jar/MyJar")); > > pySys.path.insert(0,new PyString("file:jar:/path/to/myjar.jar!")); > > > and nothing works, any ideas would help. I know this has to work, > > because I previously had a problem where I couldn't do > > > import os > > > and then I added the "Lib/" folder inside jython.jar and now I'm able > > to import all those standard jython modules, so, somehow, jython is > > able to import .py within a .jar, help would be very much appreciated. > > > Angel Leon > > From bdesth.quelquechose at free.quelquepart.fr Sun Dec 21 15:03:56 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 21 Dec 2008 21:03:56 +0100 Subject: Are Django/Turbogears too specific? In-Reply-To: References: Message-ID: <494eaee0$0$24527$426a34cc@news.free.fr> Gilles Ganault a ?crit : > Hi > > I'd like to rewrite a Web 2.0 PHP application in Python with AJAX, and > it seems like Django and Turbogears are the frameworks that have the > most momentum. > > I'd like to use this opportunity to lower the load on servers, as the > PHP application wasn't built to fit the number of users hammering the > servers now. > > I'm concerned, though, that these frameworks they may be too specific > to the tasks they were originally developped for (news articles, > AFAIK). Do you think I should just use eg. CherryPy and some basic > AJAX? I can't tell about Turbogears, but you're dead wrong if you think that there's anything specific to "news articles" in Django. It's *not* a CMS, it's a web programming framework, and is totally agnostic about what kind of application you're using it for. From cournape at gmail.com Wed Dec 10 09:43:32 2008 From: cournape at gmail.com (David Cournapeau) Date: Wed, 10 Dec 2008 23:43:32 +0900 Subject: How do I manually uninstall setuptools (installed by egg)? In-Reply-To: <47c890dc0812091904p12e75510sbe0b8858eb2f6d9e@mail.gmail.com> References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> <47c890dc0812091904p12e75510sbe0b8858eb2f6d9e@mail.gmail.com> Message-ID: <5b8d13220812100643pe688b9exefeaa13bdf589076@mail.gmail.com> On Wed, Dec 10, 2008 at 12:04 PM, Chris Rebert wrote: > On Tue, Dec 9, 2008 at 6:49 PM, wrote: >> On Ubuntu, I accidentally manually installed setuptools >> http://pypi.python.org/pypi/setuptools/0.6c9 (by running the .egg file >> as a shell script via sudo), and now realize I should just be using >> apt to take care of my system Python packages. > > Really, why? setuptools has more Python packages/programs available > and updates faster than Debian. > It's also likely that some of the Debian Python packages are installed > using setuptools anyway. > So, why do you think apt and not setuptools is The Right Way(tm)? Setuptools is certainly not the right way to install packages system-wide on debian, it is very likely to break the whole thing. dpkg is a real package installer, with uninstallation feature, correct dependency handling: if you start installing things with setuptools there, dpkg cannot know anymore how to manage your system. That's why it is generally a very bad idea to install things which are not managed by dpkg in /usr - be it python or something else BTW. It is a much better practice to install from source into /usr/local, or your $HOME, etc... Anywhere which is not /usr. David From deets at nospam.web.de Mon Dec 8 11:29:35 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 Dec 2008 17:29:35 +0100 Subject: Equivalent of 'wget' for python? References: Message-ID: <6q50bfFaqa0aU1@mid.uni-berlin.de> Robert Dailey wrote: > Hi, > > I'm looking for a portable way to download ZIP files on the internet > through Python. I don't want to do os.system() to invoke 'wget', since > this isn't portable on Windows. I'm hoping the core python library has > a library for this. Note that I'll be using Python 3.0. Module urllib2 Diez From bertilow at gmail.com Sat Dec 6 08:00:22 2008 From: bertilow at gmail.com (Bertilo Wennergren) Date: Sat, 06 Dec 2008 22:00:22 +0900 Subject: Learning Python now coming from Perl Message-ID: I'm planning to start learning Python now, using Python 3000. I have no previous Python skills, but I now Perl pretty well. I'm also well experienced with JavaScript. Any pointers and tips how I should go about getting into Python? -- Bertilo Wennergren From bthayre at physics.ucsd.edu Thu Dec 11 18:12:09 2008 From: bthayre at physics.ucsd.edu (Robocop) Date: Thu, 11 Dec 2008 15:12:09 -0800 (PST) Subject: list organization question Message-ID: I have a list of objects, each object having two relevant attributes: date and id. I'd like not only organize by id, but also by date. I.e. i would like to parse my list into smaller lists such that each new mini-list has a unique date, but consists of only objects with a specific id. Are there any handy imports i could use to accomplish something like this? I'm relatively new to python and as such don't know all of the preloaded functions at my disposal. Thanks for any help in advance, the community here is always ridiculously helpful. From bj_666 at gmx.net Fri Dec 12 09:08:28 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 12 Dec 2008 14:08:28 GMT Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> Message-ID: <6qf9irFc3a5jU3@mid.uni-berlin.de> On Fri, 12 Dec 2008 05:39:35 -0800, sturlamolden wrote: > On Dec 12, 2:34 pm, Hrvoje Niksic wrote: > >> >>> import numpy >> >>> t = (numpy.zeros(10),) >> >>> t >> >> (array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]),)>>> t[0] += >> 1 >> >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: 'tuple' object does not support item assignment >> >> Of course, the side effect occurs before the exception, so: >> >> >>> t[0] > >> array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) > > > Actually I would consider this to be a bug. The tuple is immutable, but > no mutation of the tuple is ever attempted. No bug because a mutation *is* attempted. ``a += x`` calls `a.__iadd__` which *always* returns the result which is *always* rebound to the name `a`. Even with mutable objects where `__iadd__()` simply returns `self`! It has to be this way because the compiler has no idea if the object bound to `a` will be mutable or immutable when the code actually runs. In [252]: def f(a, x): .....: a += x .....: In [253]: dis.dis(f) 2 0 LOAD_FAST 0 (a) 3 LOAD_FAST 1 (x) 6 INPLACE_ADD 7 STORE_FAST 0 (a) 10 LOAD_CONST 0 (None) 13 RETURN_VALUE Ciao, Marc 'BlackJack' Rintsch From prologic at shortcircuit.net.au Thu Dec 18 04:18:41 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 18 Dec 2008 19:18:41 +1000 Subject: importing csv file into sqlite In-Reply-To: <21068111.post@talk.nabble.com> References: <21067453.post@talk.nabble.com> <21068111.post@talk.nabble.com> Message-ID: @klia: You could have had this done hours ago had you taken my suggestion, used my tool and just piped it into sqlite3 on the command line. --JamesMills -- -- "Problems are solved by method" From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 8 03:26:18 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 08 Dec 2008 09:26:18 +0100 Subject: var or inout parm? In-Reply-To: References: Message-ID: <493cda2a$0$17080$426a34cc@news.free.fr> Colin J. Williams a ?crit : > mh at pixar.com wrote: >> How can I make a "var" parm, where the called function can modify >> the value of the parameter in the caller? >> >> def f(x): >> x = x + 1 >> >> n = 1 >> f(n) >> # n should now be 2 >> >> Many TIA!! >> Mark >> >> > > Why not run it and see? > > Your function returns None. > > The function in effect takes a copy of n. Nope, it takes the object bound to global name 'n'. From fakeaddress at nowhere.org Tue Dec 16 01:44:12 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 15 Dec 2008 22:44:12 -0800 Subject: socket and subprocess problem In-Reply-To: <73dca20d-3378-4c96-aa30-f0617f111fa0@i18g2000prf.googlegroups.com> References: <6d3291c3-4e12-4bdd-884a-21f15f38d105@a12g2000pro.googlegroups.com> <73dca20d-3378-4c96-aa30-f0617f111fa0@i18g2000prf.googlegroups.com> Message-ID: <37I1l.10065$yr3.8580@nlpi068.nbdc.sbc.com> goatold at gmail.com wrote: > Guys thanks to point it out. > Yes, it's a race problem. I tried sleep long enough, then I can > connect to the socket. I should add code to try to connect to the > socket for a given time out. As Roy noted, that's "the cheesy way". Are the kind of programmers who accept cheesy solutions? Of course not. The right solution is for the child process to tell the parent when the port is ready for connections. There are a variety of ways to transfer that message; the most straightforward is for the child process to write something to its standard output. Parent process: Launch child. read() child's output, waiting for the ready message. connect() to the port the child established. Child process: Create the socket; bind(); listen(). Write the ready message to stdout. accept(). There's a subtle yet important point here, that frequently gets lost: Roy Smith wrote: >> Sounds like a timing problem. I assume that the process started by a.run() >> creates a socket and does a bind/listen/accept sequence on it. The problem >> is, there's nothing in your code which guarantees that this happens before >> b.run() executes the connect() call. Actually, it's just bind() and listen() that have to happen before the client can connect(); accept() will not succeed until after a client connects. In our example the child process is the server, and the server's readiness alert should go after his call to listen() returns, but before he calls accept(). -- --Bryan From timr at probo.com Mon Dec 8 23:28:03 2008 From: timr at probo.com (Tim Roberts) Date: Tue, 09 Dec 2008 04:28:03 GMT Subject: pretty strange behavior of "strip" References: <4938693F.6090709@yahoo.ca> Message-ID: Guy Doune wrote: >Ok, didn't show the whole problem... > >I will read the doc anyway, but why "questions.html" keep it "t"?? > > >>> test=['03.html', '06.html', 'questions.html', '04.html', >'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test[4] >'toc.html' > >>> test[4].strip('.html') >'oc' > >>> test[2].strip('.html') >'questions' Because it removes any periods, h's, t's, m's, or l's at the beginning or ending of the string. That "t" is in the middle. In this case, the stripping stopped at the "q" and the "s". -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From fakeaddress at nowhere.org Fri Dec 12 22:51:13 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 12 Dec 2008 19:51:13 -0800 Subject: Bidirectional Networking In-Reply-To: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> Message-ID: Emanuele D'Arrigo wrote: > All the examples though are based on a client interrogating a server, > with the client initiating the connection, obtaining something and > then closing the connection. Basically the server is a reactive party: > only if the client get in touch the server respond. Indeed, to the network programmer that pattern of interaction defines client/server (according to Douglas Comer's /Internetworking with TCP/IP). > What if the server > wanted to notify the client of something of interest, i.e. new data > that the client should take into consideration and potentially > process? The "server push" problem. > One option would be for the client to periodically poll the server for > changes. Fair enough, that would work. But it'd be a bit of a waste if > the changes aren't particularly frequent. Implementing server push on top of client poll is the most popular and generally simplest option. > Is it possible then to establish both a server and a client in the > same application? Possible, and not all that hard to program, but there's a gotcha. Firewalls, including home routers and software firewalls, typically default to disallowing connections in the 'wrong' direction. If the client initiates all connections, you avoid a world of hassles. > I guess it must be possible but the examples all > rely on some kind of server loop (i.e. SocketServer.serve_forever) > that if started on both client and server sides would create two > listening parties but no talking at all! Furthermore, other libraries > might have their own loop, i.e. a graphical client has a loop to > redraw the screen and the two loops would somehow have to be > interleaved. > > I'm not quite seeing how this can be done other than we threads. Is > that the way to do it? Place the listening loop in a thread while the > rest of the application does its own thing? Threads work. Other options in Python standard library are 'select' and 'asyncore', but these do not play well with SocketServer and its descendants. There are also other free Python libraries. > Or is it SocketServer.handle_request() the key? I could call this > function periodically, but what happens if a request is made while the > application is doing something else? Are the requests queued and dealt > with one per loop? Requests are queued up, but the queue is small. SocketServer is built on top of 'socket', which has the list() and accept() calls to create the queue and get connections from it, respectively. The traditional listen queue size, and sometimes the system maximum, is 5. If you want to use SocketServer, read about ThreadingMixIn and ForkingMixIn. -- --Bryan From paul at boddie.org.uk Fri Dec 5 06:15:31 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 5 Dec 2008 03:15:31 -0800 (PST) Subject: using distutils to cross-compile extensions? References: <49385CBB.7060207@cs.cornell.edu> Message-ID: <012fa025-e12a-4c83-b81f-55bce905afe4@d23g2000yqc.googlegroups.com> On 5 Des, 00:58, "David Cournapeau" wrote: > > The first step for cross compilation would be the ability to build > python itself wtih different build/host, and that's already non > trivial. Now that Python 3.0 is out, perhaps there will be a possibility of one of the many cross-compilation patches being applied to Python 2.x: http://bugs.python.org/issue?%40columns=id%2Cactivity%2Ctitle%2Ccreator%2Cassignee%2Cstatus&%40sort=-activity&%40group=priority&%40filter=status&status=-1%2C1%2C3&%40search_text=cross-compile&submit=search+in+open+issues Paul From steve at REMOVE-THIS-cybersource.com.au Sun Dec 7 18:20:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 23:20:12 GMT Subject: Rich Comparisons Gotcha References: Message-ID: <014c51d9$0$20670$c3e8da3@news.astraweb.com> On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: > Rasmus Fogh wrote: > >> Current behaviour is both inconsistent and counterintuitive, as these >> examples show. >> >>>>> x = float('NaN') >>>>> x == x >> False > > Blame IEEE for that one. Rich comparisons have nothing to do with that > one. There is nothing to blame them for. This is the correct behaviour. NaNs should *not* compare equal to themselves, that's mathematically incoherent. -- Steven From trentm at activestate.com Mon Dec 1 13:33:02 2008 From: trentm at activestate.com (Trent Mick) Date: Mon, 01 Dec 2008 10:33:02 -0800 Subject: Debugging in Python In-Reply-To: <4931DC60.5070705@Acm.Org> References: <38a89d61-9dfd-491c-b9dc-946709eec8c7@v42g2000yqv.googlegroups.com> <4931DC60.5070705@Acm.Org> Message-ID: <49342DDE.2060604@activestate.com> Scott David Daniels wrote: > Stef Mientki wrote: >> .... I'm not completely satisfied with even the "best" debuggers, >> most of the good ones are too difficult, >> so I want to wrap rpdb2 and >> don't want to miss any great features ;-) > > I think ActiveState has a free 21-day trial, so you could check it out > yourself if you are willing to spend the concentrated time to check it > out. That is correct. Also the Python debugging docs are here, if that might help: http://docs.activestate.com/komodo/5.0/debugpython.html > Their license terms are reasonable (the license is attached to _you_, > not a particular machine you run it on, as I remember. Also correct: with a Komodo IDE license you can use Komodo on any machine that you use. Trent -- Trent Mick trentm at activestate.com From __peter__ at web.de Fri Dec 19 05:32:28 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2008 11:32:28 +0100 Subject: importing csv file into sqlite References: <21067453.post@talk.nabble.com> Message-ID: James Mills wrote: > values = ",".join(["\"%s\"" % x for x in line]) > print "INSERT INTO %s %s VALUES (%s);" % (table, fields, values) http://xkcd.com/327/ From jcd at sdf.lonestar.org Thu Dec 18 15:40:36 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Thu, 18 Dec 2008 15:40:36 -0500 Subject: Factoring Polynomials In-Reply-To: <5dfe1cf3-530d-4e31-833e-e26db85611be@d36g2000prf.googlegroups.com> References: <5dfe1cf3-530d-4e31-833e-e26db85611be@d36g2000prf.googlegroups.com> Message-ID: <1229632836.10976.3.camel@aalcdl07.lib.unc.edu> On Thu, 2008-12-18 at 11:52 -0800, eric wrote: > On Dec 18, 8:37 pm, collin.da... at gmail.com wrote: > > I am trying to write a simple application to factor polynomials. I > > wrote (simple) raw_input lines to collect the a, b, and c values from > > the user, but I dont know how to implement the quadratic equation > > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > > into python. Any ideas? > > with numpy: > from numpy import * > > s=[1,-1] > x = -b+s*sqrt( b**2-4*a*c )/(2*a) > > Eric Without the Nump. def polynomial(a, b, c): N = ((b**2 - 4*a*c)**.5) / 2*a return (-b + N, -b - N) From gamersunit at gmail.com Fri Dec 5 17:41:08 2008 From: gamersunit at gmail.com (Gregory Plantaine) Date: Fri, 5 Dec 2008 14:41:08 -0800 (PST) Subject: Find Files in a Folder Between 2 Dates References: <4c54b6c5-ae4d-4b89-8c6d-940c96de29bb@n33g2000pri.googlegroups.com> Message-ID: <94cd4bd7-a69f-48ba-90f7-382014844905@g1g2000pra.googlegroups.com> That worked perfectly! Thanks Tim! Since we can print the files, does that mean the list of files is in a tuple, or something? Would there be a way to further split up the file names? For example, now that the files are processed into the list, we want to look through that list to find different filetypes. files C:\Folder\File_200812051439.111 C:\Folder\File_200812051539.222 Can we split up .111 files? Actually, where would I look something like this up? From duncan.booth at invalid.invalid Mon Dec 8 04:10:35 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 Dec 2008 09:10:35 GMT Subject: how to get a beep, OS independent ? References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> Message-ID: Joe Strout wrote: > But invoking the standard system beep is such a basic function that it > ought to be easier than this. I'm pretty sure it's a single OS call > on all platforms. On OS X, for example, it's > > void NSBeep(void); > > declared in NSGraphics.h. I'm sure it's something similarly simple on > other platforms. I think what you're missing is a definition for 'the standard system'. If I'm logged in to one of my servers in a large datacentre then I don't what that system to beep as that would be pretty useless. I want the system I'm logged in with to do the beeping. For some systems and some types of login (e.g. Microsoft's Remote Desktop) then remoting the sound output isn't a problem, but I might just be logged in with SSH and in that case the only option available is to send some escape sequence to the user's terminal. Traditionally generation of escape sequences for a user's terminal is something done by the application, not a function of the operating system. I think that's why you'll find there will be a variety of ways to generate beeps, squeaks and squawks if you are using a gui (only as with all other gui functions there is no common ground between different systems), but nothing beyond '\a' for terminals. -- Duncan Booth http://kupuguy.blogspot.com From jstroud at mbi.ucla.edu Sat Dec 6 22:15:12 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 06 Dec 2008 19:15:12 -0800 Subject: operators as variables In-Reply-To: References: <103920.71204.qm@web26006.mail.ukl.yahoo.com> Message-ID: > macc_200 wrote: >> Hi, >> just starting programming and have an elementary question after >> playing around with lists but cannot find the answer with googling. >> I have a list of variables and I would like some of those variables to >> be integers and some to be operators so the list would look something >> like [5 * 4 - 4 + 6] and then be able to evaluate the result (i.e. get >> 10). How do you make the interpreter see the operator as that instead >> of a string and just echo the list back to me. Your specification is ambiguous because you mention lists but wrote an evaluable expression inside of brackets. Others have answered the question you probably really are asking. For fun, though, I'm going to pretend you meant "list" and not whatever [5 * 4 - 4 + 6] is: import operator opdict = {'+' : operator.add, '-' : operator.sub, '*' : operator.mul, '/' : operator.div} def take_two(aniterable): assert len(aniterable) % 2 == 0 aniter = iter(aniterable) while True: try: yield aniter.next(), aniter.next() except StopIteration: break def reductifier(alist): value = alist.pop(0) for op, operand in take_two(alist): value = opdict[op](value, operand) return value reductifier([5, "*", 4, "-", 4, "+", 6]) From org.python.python-list at pooryorick.com Fri Dec 12 16:52:52 2008 From: org.python.python-list at pooryorick.com (=?utf-8?Q?Poor=20Yorick?=) Date: Fri, 12 Dec 2008 21:52:52 +0000 Subject: =?utf-8?B?X19mdXR1cmVfXyBhbmQgdW5yZWNvZ25pc2VkIGZsYWdz?= Message-ID: <20081212215252.18112.qmail@s461.sureserver.com> I have a future statement in a script I intend to work on 2.6 and 3. Shouldn't __future__ statements basically be noops for versions that already support the feature? doctest is complaining about compiler flags. This illustrates the problem: Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> from __future__ import unicode_literals >>> src = 'a = "hello"' >>> c1 = compile(src,'','exec',unicode_literals.compiler_flag) Traceback (most recent call last): File "", line 1, in ValueError: compile(): unrecognised flags -- Yorick From jcd at sdf.lonestar.org Tue Dec 16 11:50:34 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 16 Dec 2008 11:50:34 -0500 Subject: alt.possessive.its.has.no.apostrophe In-Reply-To: <000901c95f69$003a5f00$0d00a8c0@hendrik> References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> <9ImdneOohuZCNdvUnZ2dnUVZ_s3inZ2d@earthlink.com> <000901c95f69$003a5f00$0d00a8c0@hendrik> Message-ID: <1229446234.8781.9.camel@aalcdl07.lib.unc.edu> On Tue, 2008-12-16 at 12:27 +0200, Hendrik van Rooyen wrote: > "Dennis Lee Bieber" wrote: > > 8<----- stuff blaming Davy for "aluminum" ---------- > > > Isn't Davy a Brit? > > No, he was a Brit. > He's dead now. > His safety lamp lives on. > It's a good thing its got that heat-sink sieve- > it's enabled countless miners > to flee when they see its change of colour. > Thus it's saved the lives of a lot of canaries, > and that's of ecological importance. > > Spot the apostrophe error, if you can. > > - Hendrik > It's a good thing *its* got that heat-sink sieve- its -> it has Cheers, Cliff From rt8396 at gmail.com Mon Dec 22 17:07:34 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 14:07:34 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <6ra8t0F925rU1@mid.individual.net> <29feda0d-6432-4cb9-8809-e4d4a7798601@e1g2000pra.googlegroups.com> <6raeb8F9s47U2@mid.individual.net> Message-ID: On Dec 22, 3:15?pm, je.s.t... at hehxduhmp.org wrote: > r wrote: > > We see where you stand. And also see that by removing your comments > > from the archive in 5 days, how small your acorns really are. > > Also, it is pretty hard to take such accusations seriously from someone > who themselves is using a generic gmail address w/o their real name > attached to it. ?If I didn't care about using a proper NNTP client, I > could quite easily create some dufus account on Gmail and post through > that just like you did - I'm sure that'd really increase my credibility! Would you trust my words more if i used a name like "Thurstan Howell III".... Come on, don't tell me you are that shallow. To attack my credibility solely based on my user name is the sport of small minded people. Surely you can bring more thought, and intelligence to this thread than that?... From rlight2 at gmail.com Wed Dec 24 10:42:38 2008 From: rlight2 at gmail.com (Ross) Date: Wed, 24 Dec 2008 07:42:38 -0800 (PST) Subject: Custom C Exception Subclasses Message-ID: <41f291ff-d7bd-4334-8689-636e95524cdc@b38g2000prf.googlegroups.com> For a project that I am doing, it would be useful to have an exception class that stores some additional data along with the message. However, I want to be able to store a couple pointers to C++ classes, so I can't just use an exception created with PyExc_NewException. If I were to subclass the built-in Exception type, I would need to have access to the PyExc_ExceptionObject, but the headers only give PyExc_Exception, the type object. This seems like a rather straightforward task, but I can't seem to find any documentation for it. Does anyone know how to do this? Thanks! From pxrepreza at gmail.com Tue Dec 23 01:19:21 2008 From: pxrepreza at gmail.com (Paulo Repreza) Date: Mon, 22 Dec 2008 22:19:21 -0800 Subject: String Format Error. Message-ID: Hi, I'm a newbie with python and I recently bought Beginning with Python (Which is a book I recommend) but the problem that I'm facing it's the following: *This is the code: * #!/usr/bin/python2.5 # Filename: str_format.py age = 25 name = 'foobar' print('{0} is {1} years old'.format(name, age)) print('Why is {0} playing with that python?'.format(name)) *But when I run the script I receive this error: *Traceback (most recent call last): File "str_format.py", line 7, in print('{0} is {1} years old'.format(name, age)) AttributeError: 'str' object has no attribute 'format' It is an error because of the version that I'm using ? Python 2.5.2 (Debian lenny) Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lewis.sarah93 at yahoo.com Fri Dec 5 00:02:41 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 21:02:41 -0800 (PST) Subject: Earn More Money Message-ID: <8d38f89d-cd44-46f7-869c-4209b16a3a0c@d14g2000yqb.googlegroups.com> Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From bearophileHUGS at lycos.com Mon Dec 22 14:22:02 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 22 Dec 2008 11:22:02 -0800 (PST) Subject: 64-bit / 128-bit data element type for array? References: Message-ID: akineko: > I need to handle binary files that contain 64-bit (or 128-bit in the > furture) unsigned int data. > Python's array seems not supporting unsigned int type beyond 32-bit > ('L'). I agree that it can be useful for the built-in array module to grow signed/unsigned 64 bit numbers. Numpy supports signed/unsigned 64 bit numbers too, so that may be enough for you: http://docs.scipy.org/doc/numpy/user/basics.types.html Regarding 128-bit numbers you may have to support them manually, with pairs of uint64, with numpy. They aren't much common yet. (D language will have cent/ucent 128 bit integral numbers, but it's not a common thing). Bye, bearophile From arnodel at googlemail.com Mon Dec 8 15:55:16 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 08 Dec 2008 20:55:16 +0000 Subject: Guido's new method definition idea References: <014a071a$0$20670$c3e8da3@news.astraweb.com> <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> Message-ID: anthony.tolle at gmail.com writes: > class C: > def createfunc(self): > def self.func(arg): > return arg + 1 > > Or, after the class definition is done, to extend it dynamically: > > def C.method(self, arg): > self.value = arg > > ...which would be the equivalent of the following: > > def method(self, arg): > self.value = arg > C.method = method What about the following then? functions = {} def functions['square'](x): return x*x def functions['cube'](x): return x**3 -- Arnaud From the.brown.dragon.blog at gmail.com Mon Dec 15 02:46:30 2008 From: the.brown.dragon.blog at gmail.com (the.brown.dragon.blog at gmail.com) Date: Sun, 14 Dec 2008 23:46:30 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <91bf5d87-0154-472b-9350-e3290ab867e1@k1g2000prb.googlegroups.com> <49a1717b-36f0-402c-a633-a7df23dca0bf@35g2000pry.googlegroups.com> Message-ID: <7bc8cd81-e35c-443d-a8fa-f5b0227a614d@a26g2000prf.googlegroups.com> On Dec 12, 12:12?am, Xah Lee wrote: > On Dec 11, 6:50 am, the.brown.dragon.b... at gmail.com wrote: > ;; Chicken Scheme. By the.brown.dragon... at gmail.com > (require 'srfi-1) > (define (normalize vec) > ? (map (cute / <> (sqrt (reduce + 0 (map (cute expt <> 2) vec)))) > vec)) > > Is it possible to make it work in scsh? (i'm running scsh 0.6.4, and > don't know Scheme lisp well) > > ? Xah > ?http://xahlee.org/ > > ? I don't have scsh but yes - it should work fine. "cute" is an SRFI (http://srfi.schemers.org/srfi-26/) which should be available. cheers, BD From george.sakkis at gmail.com Thu Dec 4 17:02:45 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 4 Dec 2008 14:02:45 -0800 (PST) Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> Message-ID: <3dd9addc-9121-496d-b775-12437d32097b@l33g2000pri.googlegroups.com> On Dec 4, 4:49?pm, s... at pobox.com wrote: > ? ? Andreas> Whenever has it been a pythonic ideal to "not allow" stuff? You > ? ? Andreas> get warnings. Everything else is up to you. > > It's more than warnings. ?With properly crafted combinations of spaces and > tabs you can get code which looks like it has a certain indentation to the > human observer but which looks like it has different indentation (and thus > different semantics) to the byte code compiler. ?There is often no warning. Amazing.. was it a conscious decision to keep the current behavior in 3.x or it was not even considered dropping it ?? Does anyone have a link where this was decided ? George From bearophileHUGS at lycos.com Thu Dec 4 11:32:05 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 4 Dec 2008 08:32:05 -0800 (PST) Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> Message-ID: <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> Gerhard H?ring: > As you have probably guessed: nothing changed here. > Also see:http://www.python.org/dev/peps/pep-0666/ What? Do you mean it's possible to mix tabs and spaces still? Why? Bye, bearophile From nabla.kvadrat at gmail.com Thu Dec 11 02:12:08 2008 From: nabla.kvadrat at gmail.com (Nabla Kvadrat) Date: Thu, 11 Dec 2008 08:12:08 +0100 Subject: multiprocessing+simplehttpserver+windows In-Reply-To: References: Message-ID: Additional information: complete traceback: Serving at http://localhost:8000 using 2 worker processes To exit press Ctrl-Break Traceback (most recent call last): File "C:\workspaces\workspace\skrserver-multiprocess\src\t.py", line 70, in test() File "C:\workspaces\workspace\skrserver-multiprocess\src\t.py", line 65, in test runpool(ADDRESS, NUMBER_OF_PROCESSES) File "C:\workspaces\workspace\skrserver-multiprocess\src\t.py", line 49, in runpool Process(target=serve_forever, args=(server,)).start() File "C:\Python26\lib\multiprocessing\process.py", line 104, in start self._popen = Popen(self) File "C:\Python26\lib\multiprocessing\forking.py", line 239, in __init__ dump(process_obj, to_child, HIGHEST_PROTOCOL) File "C:\Python26\lib\multiprocessing\forking.py", line 162, in dump ForkingPickler(file, protocol).dump(obj) File "C:\Python26\lib\pickle.py", line 224, in dump self.save(obj) File "C:\Python26\lib\pickle.py", line 331, in save self.save_reduce(obj=obj, *rv) File "C:\Python26\lib\pickle.py", line 419, in save_reduce save(state) File "C:\Python26\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python26\lib\pickle.py", line 649, in save_dict self._batch_setitems(obj.iteritems()) File "C:\Python26\lib\pickle.py", line 681, in _batch_setitems save(v) File "C:\Python26\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python26\lib\pickle.py", line 548, in save_tuple save(element) File "C:\Python26\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python26\lib\pickle.py", line 725, in save_inst save(stuff) File "C:\Python26\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python26\lib\pickle.py", line 649, in save_dict self._batch_setitems(obj.iteritems()) File "C:\Python26\lib\pickle.py", line 681, in _batch_setitems save(v) File "C:\Python26\lib\pickle.py", line 331, in save self.save_reduce(obj=obj, *rv) File "C:\Python26\lib\pickle.py", line 419, in save_reduce save(state) File "C:\Python26\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python26\lib\pickle.py", line 649, in save_dict self._batch_setitems(obj.iteritems()) File "C:\Python26\lib\pickle.py", line 681, in _batch_setitems save(v) File "C:\Python26\lib\pickle.py", line 331, in save self.save_reduce(obj=obj, *rv) File "C:\Python26\lib\pickle.py", line 419, in save_reduce save(state) File "C:\Python26\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python26\lib\pickle.py", line 649, in save_dict self._batch_setitems(obj.iteritems()) File "C:\Python26\lib\pickle.py", line 681, in _batch_setitems save(v) File "C:\Python26\lib\pickle.py", line 313, in save (t.__name__, obj)) pickle.PicklingError: Can't pickle 'lock' object: Traceback (most recent call last): File "", line 1, in File "C:\Python26\lib\multiprocessing\forking.py", line 342, in main self = load(from_parent) File "C:\Python26\lib\pickle.py", line 1370, in load return Unpickler(file).load() File "C:\Python26\lib\pickle.py", line 858, in load dispatch[key](self) File "C:\Python26\lib\pickle.py", line 1133, in load_reduce value = func(*args) File "C:\Python26\lib\multiprocessing\reduction.py", line 167, in rebuild_socket _sock = fromfd(fd, family, type_, proto) File "C:\Python26\lib\multiprocessing\reduction.py", line 156, in fromfd s = socket.fromfd(fd, family, type_, proto) AttributeError: 'module' object has no attribute 'fromfd' -------------- It seems that patch is available http://bugs.python.org/issue1378 but not yet applied on the Windows latest release. I have no environment to build it from source with this patch (in addition, I don't even know how :-)) Thanks for any help. On Thu, Dec 11, 2008 at 6:55 AM, Nabla Kvadrat wrote: > Hi, can someone please help me with/explain if following problem can > be somehow resolved? > > I have Py2.6.1 win32 and I'm playing around with multiprocessing > module. Trying examples here: > http://docs.python.org/library/multiprocessing.html#examples. Example > with SimpleHTTPServer.HttpServer don't work because of socket.fromfd > in multiprocessing.reduction. If number of processes is >1 it ends > with traceback ....... pickle.: 'module' object has no attribute > 'fromfd'. > As I understand socket.fromfd on windows is not implemented (?), so > why the example script is care about platform > if sys.platform == 'win32': > import multiprocessing.reduction > and finally, is there some easy (no patching and recompiling python > from source) way to get this example to work on win32 platform? > Thanks for any help, I'm Python amateur... > N. > From eduardo.padoan at gmail.com Thu Dec 4 06:25:50 2008 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Thu, 4 Dec 2008 09:25:50 -0200 Subject: "as" keyword woes In-Reply-To: References: Message-ID: On Thu, Dec 4, 2008 at 7:44 AM, James Stroud wrote: > alex23 wrote: >> >> On Dec 4, 3:42 pm, "Warren DeLano" wrote: >>> >>> So you prefer broken code to broken rules, eh? Your customers must love >>> that! This is exactly the kind of ivory-tower thinking I feared might >>> be behind the decision (form over function, damn the users to hell, >>> etc.) >> >> Really? I find that believing something should remain static at the >> expense of actual improvement to the language is far more 'ivory-tower >> thinking' than embracing change. > > First, to quote Tim Peters, "practicality beats purity." Second, I might be > biased here because I happen to know Warren, but, although he hails from the > ivory tower, I imagine his concerns are purely practical. His contributions > to software in structural biology are legendary. > >>> Am I the only one picking up on the irony here? "as" exists largely to >>> provide a mechanism for working around namespace conflicts -- except, >>> apparently, conflicts involving "as". The fact that "as" itself creates >>> an insurmountable namespace collision is just killing me! How absurd. >> >> Speaking of irony, you're complaining about namespace conflicts with a >> -two character identifier- you've chosen. Here's a hint: choose better >> names. > > The name fit his needs until changes in the language broke the name. If a > name works and the code works, then the name is good enough. And speaking as > a professional user of his software at the level of the application and at > the level of the API, let me tell you his code works pretty damn good. > >>> But to be brutally honest...in this many-core world we must all accept >>> and deal with today, it is hard to imagine how a non-multithreaded AND >>> non-backwards compatible Python implementation can have much of a life >>> ahead of it, with or without an "as" keyword. I do sincerely hope I am >>> wrong about this, but it is seems quite possible that C/Python's glory >>> days are now behind us. >> >> To match your honesty, I'm somewhat tired with the trend of some >> people to hit -one- issue with Python and suddenly lash out like >> children over all the same old tired crap. Have you even looked at >> multiprocessing? Have you contributed to any projects working on GIL- >> less implementations? Or are you just regurgitating the same bullet >> points we've heard time and time again? >> >> For chrissake, if you cannot do ANYTHING but BITCH about a change, >> then you've no damn right to consider yourself a programmer. Real >> programmers find solutions, not excuses. > > Correction: Real programmers write programs. And no, at this point he can't > do anything but complain because, as others have noted, the change is not > going away. > >>> And if so, then thank you all for so many wonderful years of effort and >>> participation! >> >> You're welcome. Don't let the door hit you on the ass on your way out. > > You probably aren't a developer for the cPython implementation, but, if you > were, I'd recommend taking rants like Warren's to heart because they are > born of honest frustration and practical concern. Hopefully developers for > python 2.7 are listening and won't break backward compatibility just because > the "Zen of Python" suggests it might be a good idea. Even I, who am not, by really far, legendary on anything, could give my 2? one time or another on python-dev or python-ideas. If you really care and think you have a good argument, I'm sure you are welcome to post there! But they cant hold the release until everyone in the world have voiced his concerns, its just not pratical. -- Eduardo de Oliveira Padoan http://djangopeople.net/edcrypt/ "Distrust those in whom the desire to punish is strong." -- Goethe, Nietzsche, Dostoevsky From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 21:25:37 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2008 02:25:37 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <015c4ef2$0$20656$c3e8da3@news.astraweb.com> On Fri, 19 Dec 2008 16:05:42 -0800, Scott David Daniels wrote: > Ah, but for internationalization, you can change the format string to > take args in a different order if, for example, French messages want > modifiers on one side and English on the other. The code can stay the > same, while only the text used to do the formatting must change. I can't see how this is any different between what we have now. Here's an example using keyword arguments: # untested "{modifier} {noun}".format(modifier="dead", noun="parrot") "{noun} {modifier}".format(modifier="mort", noun="perroquet") compared to: "%(modifier)s %(noun)s" % dict(modifier="dead", noun="parrot") "%(noun)s %(modifier)s" % dict(modifier="mort", noun="perroquet") Whether using % or format(), I don't see the need to change the code, only the strings. Using positional arguments is not really that different: "{0} {1}".format("dead", "parrot") "{0} {1}".format("perroquet", "mort") versus: "%s %s" % ("dead", "parrot") "%s %s" % ("perroquet", "mort") In this case, the template on the left remains the same, you just have to reorder the string arguments on the right. Clearly less satisfactory than the solution using keyword substitution, but whatever solution you pick, I don't see any advantage to format() over % formatting. Can you show an example? -- Steven From sjmachin at lexicon.net Tue Dec 2 19:14:46 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 2 Dec 2008 16:14:46 -0800 (PST) Subject: Reverse zip() ? References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> Message-ID: On Dec 3, 7:12?am, Stefan Behnel wrote: > Andreas Waldenburger wrote: > > we all know about the zip builtin that combines several iterables into > > a list of tuples. > > > I often find myself doing the reverse, splitting a list of tuples into > > several lists, each corresponding to a certain element of each tuple > > (e.g. matplotlib/pyplot needs those, rather than lists of points). > > > This is of course trivial to do via iteration or listcomps, BUT, I was > > wondering if there is a function I don't know about that does this > > nicely? > > I think you're asking about zip(): > > ? ? ? ? >>> l=[1,2,3] > ? ? ? ? >>> zip(l,l) > ? ? ? ? [(1, 1), (2, 2), (3, 3)] > ? ? ? ? >>> zip(*zip(l,l)) > ? ? ? ? [(1, 2, 3), (1, 2, 3)] > Here's a version that makes it slightly easier to comprehend: Q: I know how to zip sequences together: | >>> a = (1, 2, 3) | >>> b = (4, 5, 6) | >>> z = zip(a, b) | >>> z | [(1, 4), (2, 5), (3, 6)] but how do I reverse the process? A: Use zip()! | >>> a2, b2 = zip(*z) | >>> a2 | (1, 2, 3) | >>> b2 | (4, 5, 6) Cheers, John From bblais at bryant.edu Sun Dec 7 15:29:02 2008 From: bblais at bryant.edu (Brian Blais) Date: Sun, 7 Dec 2008 15:29:02 -0500 Subject: Python for kids? In-Reply-To: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> Message-ID: <2BDBC492-A75B-4F79-86E9-414EA521A80B@bryant.edu> On Dec 7, 2008, at 15:13 , Russ P. wrote: > I have a 12-year-old son who spends too much time playing Xbox live > and watching silly YouTube videos. I would like to try to get him > interested in programming. Is anyone aware of a good book or website check out: http://www.briggs.net.nz/log/writing/snake-wrangling-for-kids/ it's specifically for Python, and geared for the age of your son. bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais From manatlan at gmail.com Mon Dec 8 08:20:50 2008 From: manatlan at gmail.com (manatlan) Date: Mon, 8 Dec 2008 05:20:50 -0800 (PST) Subject: Python and audio frequency analysis Message-ID: I'd like to make a kind of "spectrum analyzer" ... Which should display "bars" according bands of frequencies ... in real time... Is anybody know an audio processing lib in python for that ? From jfmoreno at gitanosoftware.com Wed Dec 10 13:09:49 2008 From: jfmoreno at gitanosoftware.com (JFMoreno) Date: Wed, 10 Dec 2008 10:09:49 -0800 (PST) Subject: Jewel of the Week: Sterling Icon Collection just $39 Message-ID: Add a touch of class to your projects with this beautiful icon collection. 262 gorgeous icons for a total of 14934 files in +540mg that will make all your projects shine (Application, Website, Gadget, Game, Desktop, etc.). The collection includes 9 sizes: 16x16, 24x24, 32x32, 48x48, 64x64, 72x72, 96x96, 128x128, and 256x256 Included as well 7 formats: Windows ICO, PSD, PNG, JPG, BMP, GIF and Mac ICNS Previously sold for$149, this week only you can get this jewel for just $39 BUY NOW (secure): https://www.1stlogodesign.com/secure/orders/jeweloftheweek.htm Preview the entire collection: http://www.1stlogodesign.com/core/docs/sterlingiconcollection.pdf Download a sample: http://www.1stlogodesign.com/core/downloads/1stIDSterling.zip Compare our collection to identical quality collections from other vendors and you will find that you get: ? More Icons ? In some cases four times more icons. ? More sizes ? 9 different sizes from 16x16 to 256x256 ? More formats ? Our collection includes, PNG,PSD, JPG, BMP, GIF, ICO and ICNS formats ? Better quality ? Our icons are not cartoonish and therefore your project will look more professional ? More FREE updates ? FREE for LIFE! Would you like to receive notifications about our fantastic offers, last minute low-price deals and new releases? Join our newsletter: https://www.1stlogodesign.com/forms/newsletter.htm From fetchinson at googlemail.com Sat Dec 13 22:49:36 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 13 Dec 2008 19:49:36 -0800 Subject: 1 or 1/0 doesn't raise an exception In-Reply-To: <49446E39.6020807@tim.thechases.com> References: <49446E39.6020807@tim.thechases.com> Message-ID: >> Is it a feature that >> >> 1 or 1/0 >> >> returns 1 and doesn't raise a ZeroDivisionError? If so, what's the >> rationale? > > Yes, it's a feature: > > http://en.wikipedia.org/wiki/Short-circuit_evaluation > > When you have "True or False", you know it's true by the time > you've got the first piece, so there's no need to evaluate the > 2nd piece. The opposite is helpful too: > > lst = [some list or an empty list] > ... > if lst and lst[0] == 42: > > This ensures that the "lst[0]" doesn't fail if lst is empty, > because lst evaluating to false (an empty list) short-circuits > preventing the evaluation of "lst[0]". Okay, it's clear, thanks. Let me just point out that unsuspecting people (like me) might rely on the whole expression to be evaluated and rely on exceptions being raised if needed. So from now on I will not do! -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From rhf22 at mole.bio.cam.ac.uk Wed Dec 10 09:49:12 2008 From: rhf22 at mole.bio.cam.ac.uk (Rasmus Fogh) Date: Wed, 10 Dec 2008 14:49:12 +0000 (GMT) Subject: Rich Comparisons Gotcha Message-ID: Rhamphoryncus wrote: > You grossly overvalue using the "in" operator on lists. Maybe. But there is more to it than just 'in'. If you do: >>> c = numpy.zeros((2,)) >>> ll = [1, c, 3.] then the following all throw errors: 3 in ll, 3 not in ll, ll.index(3), ll.count(3), ll.remove(3) c in ll, c not in ll, ll.index(c), ll.count(c), ll.remove(c) Note how the presence of c in the list makes it behave wrong for 3 as well. > It's far more > common to use a dict or set for containment tests, due to O(1) > performance rather than O(n). I doubt the numpy array supports > hashing, so an error for misuse is all you should expect. Indeed it doees not. So there is not much to be gained from modifying equality comparison with sets/dicts. > In the rare case that you want to test for identity in a list, you can > easily write your own function to do it upfront: > def idcontains(seq, obj): > for i in seq: > if i is obj: > return True > return False Again, you can code around any particular case (though wrappers look like a more robust solution). Still, why not get rid of this wart, if we can find a way? --------------------------------------------------------------------------- Dr. Rasmus H. Fogh Email: r.h.fogh at bioc.cam.ac.uk Dept. of Biochemistry, University of Cambridge, 80 Tennis Court Road, Cambridge CB2 1GA, UK. FAX (01223)766002 From safe.girl1 at gmail.com Thu Dec 18 02:24:50 2008 From: safe.girl1 at gmail.com (safesexxxgirl) Date: Wed, 17 Dec 2008 23:24:50 -0800 (PST) Subject: ! hot lins freeeeee Message-ID: <286170c8-a71b-4fea-b22f-417bfd17fc30@k1g2000prb.googlegroups.com> ==> hot jokes free today http://adultjokes.tk http://adultjokes.tk ==> m2f m2m f2m m2m aunty srch http://sexxxsearch.tk http://sexxxsearch.tk ==> hot indian actress http://nudeactresses.tk http://nudeactresses.tk ==> hot vedios download free... http://hotmovies.co.nr http://hotmovies.co.nr ==> HOT C2C VOICE chat http://www.roleplaychat.co.cc http://www.roleplaychat.co.cc ==> hot dating girls mmm... http://www.hotdating.co.nr http://www.hotdating.co.nr ==> NEW INCOME/PENSION CALCULATOR http://6thpaycommission.tk http://6thpaycommission.tk ==> 1 CRORE SHARES FREE http://free-shares.tk http://free-shares.tk ==> MAKE FREE cash online... http://free-cash.tk http://free-cash.tk ==> win FREE GOLD TODAY... http://freegold4u.tk http://freegold4u.tk ==> free zodiac compatibility http://zodiacmatches.co.nr http://zodiacmatches.co.nr From arnodel at googlemail.com Fri Dec 19 17:51:18 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 19 Dec 2008 22:51:18 +0000 Subject: Generator slower than iterator? References: <62013718-57e9-4690-a2be-11e63b9c135b@u18g2000pro.googlegroups.com> Message-ID: MRAB writes: > Federico Moreira wrote: >> Great, 2min 34 secs with the open method =) >> >> but why? >> >> ip, sep, rest = line.partition(' ') >> match_counter[ip] += 1 >> >> instead of >> >> match_counter[line.strip()[0]] += 1 >> >> strip really takes more time than partition? >> >> I'm having the same results with both of them right now. >> > I think you meant split(), not strip(). > > split() might split the string into many parts, but you want only the > first part (at most 1 split), so the extra splits are unnecessary and > waste time. split(None, 1) and partition(' ') do at most 1 split, so > they don't do unnecessary work. Here's a very quick test: >>> timeit.Timer("a='fsdjflksjdf as fsd jkfl sdj'; b=a.partition(' ')[0]").timeit(5000000) 2.9831948280334473 >>> timeit.Timer("a='fsdjflksjdf as fsd jkfl sdj'; b=a[:a.find(' ')]").timeit(5000000) 3.0122888088226318 >>> timeit.Timer("a='fsdjflksjdf as fsd jkfl sdj'; b=a.split(None, 1)[0]").timeit(5000000) 4.5993850231170654 >>> timeit.Timer("a='fsdjflksjdf as fsd jkfl sdj'; b=a.split()[0]").timeit(5000000) 5.2067980766296387 So .split(None, 1) is quite a bit slower than .partition(' ') apparently. -- Arnaud From jstroud at mbi.ucla.edu Sat Dec 13 05:16:45 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 13 Dec 2008 02:16:45 -0800 Subject: Need help improving number guessing game In-Reply-To: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> Message-ID: James Stroud wrote: > 1. Refactor. You should look at your code and see where you repeat the > same or similar patterns, see where they differ, make functions, and > make the differences parameters to the function call: > > def guess(player, p1score, p2score): > guess1 = int(input("\n>> ")) > if guess1 > 100: > print("ONLY NUMBERS FROM 1 TO 99") > elif guess1 > target: > print("TOO HIGH") > elif guess1 == target: > print("GOOD JOB, PLAYER %s! THE SCORE IS:" % player) > print("P1: %s --- P2: %s" % (p1score, p2score))) > print("PLAY AGAIN?") > #Set up the game again > play = int(input("0 TO END: ")) > if play == 0: > print("GOOD BYE. PLAY AGAIN SOON!") > quit() > else: > target = random.randint(1, 99) > else: > print("TOO LOW") I realized this has a bug. The target is locked in the scope of the function. I wouldn't use global, though: def guess(player, p1score, p2score): target = None guess1 = int(input("\n>> ")) if guess1 > 100: print("ONLY NUMBERS FROM 1 TO 99") elif guess1 > target: print("TOO HIGH") elif guess1 == target: print("GOOD JOB, PLAYER %s! THE SCORE IS:" % player) print("P1: %s --- P2: %s" % (p1score, p2score))) print("PLAY AGAIN?") #Set up the game again play = int(input("0 TO END: ")) if play == 0: print("GOOD BYE. PLAY AGAIN SOON!") quit() else: target = random.randint(1, 99) else: print("TOO LOW") Use it like this: new_target = gues(player, p1score, p2score) if new_target is not None: target = new_target I officially declare that I can't guarantee no more bugs in my previous post. I just fixed this one because my conscience was bothering me. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From martin at v.loewis.de Sat Dec 6 04:57:29 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sat, 06 Dec 2008 10:57:29 +0100 Subject: Running Python 2 and Python 3 on the same machine In-Reply-To: <1228539820.27659.21.camel@linux-3eb6.site> References: <1228424486.5873.6.camel@linux-3eb6.site> <49387f7e$0$27857$9b622d9e@news.freenet.de> <1228489547.5613.10.camel@linux-3eb6.site> <4939c6ef$0$6534$9b622d9e@news.freenet.de> <1228539820.27659.21.camel@linux-3eb6.site> Message-ID: <493A4C89.8070007@v.loewis.de> > Ok. I built the source on an openSUSE 11.0 system. I used 'sudo make > altinstll'. It created an executable /usr/local/bin/python3.0 file. > Nothing was touched in /usr/bin. Ah, then you missed the fun part. Take a look at the install: target in the Makefile. > I need to start writing some code with Python 3. I want to write the > code in such a way that it can be easily shared with others with the > least difficulty and overhead as possible. How should I write the code > to enable this? What, if anything, should I assume about another > system's configuration? I don't quite understand the problem. Sharing code is very easy over the internet. You can upload it on PyPI (say), or mail it. So you must be asking for something else. > As someone suggested before, naming the files as '.py3' is probably a > bad idea in the long run. It also does not really solve the problem. > > I could use a shebang. But, what should it specify? If I use > 'python3.0', then that will soon be quite old. If I make up a link for > python3 -> python3.0, that would work, but then every other system that > is to run the code must that link also. However, I am thinking that > this would be the best long term answer. Well, this will be rejected. It might be a good medium-term answer, but it is a *bad* long-term answer. In the long term, Python 2 will disappear, and we are stuck with calling the interpreter python3. > If I write scripts for Python 3, another developer writes scripts for > Python 2, and a common customer wants to install both of our packages > onto a single machine, then what is the best plan for everyone to make > that happen with as little difficulty as possible? My recommendation is to use distutils, for a long-term answer. People will run "python3.0 setup.py install", and distutils' install_scripts will replace the shebang line with the actual path to Python 3.0. This has not only the advantage of continuing to work for 3.1; it has also the advantage that scripts installed into a private location will be run by the correct interpreter (rather than relying on the interpreter being in /usr/bin, or on PATH). For "quick" sharing, the shebang line "#!/usr/bin/env python3.0" will be enough. When Python 3.1 gets released, you may find yourself writing scripts that run only on Python 3.x for x>=1 (i.e. won't run on 3.0, because you use a new feature in 3.1). In that case, presence of a python3 executable won't help, either. Regards, Martin From yinon.me at gmail.com Tue Dec 16 09:39:15 2008 From: yinon.me at gmail.com (Yinon Ehrlich) Date: Tue, 16 Dec 2008 06:39:15 -0800 (PST) Subject: ethical questions about global variables References: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> Message-ID: <9b86455a-3b79-4a31-83cc-b3ef381f9248@o40g2000prn.googlegroups.com> On Dec 16, 4:45?am, "Giampaolo Rodola'" wrote: > Hi, > in a module of mine (ftpserver.py) I'd want to add a (boolean) global > variable named "use_gmt_times" to decide whether the server has to > return times in GMT or localtime but I'm not sure if it is a good idea > because of the "ethical" doubts I'm gonna write below. > > In first place I've never liked global variables too much and always > preferred per-class-instance variables instead. > The problem in my case is that I have to use such variable in two > separated classes: FTPHandler and VirtualFileSystem. Also, I want that > for no reason one class uses times in GMT and the other one local > times. > > Another doubt is the naming convention. PEP-8 states that global > variables should use the lower_case_naming_convention but I've seen a > lot of library module using the UPPER_CASE_NAMING_CONVENTION. What am > I supposed to do about it? > > Thanks in advance for any comment. > > --- Giampaolohttp://code.google.com/p/pyftpdlib/ Note also that PEP-8 states that "_single_leading_underscore... from M import *" does not import objects whose name starts with an underscore" From sjmachin at lexicon.net Fri Dec 19 08:58:57 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 19 Dec 2008 05:58:57 -0800 (PST) Subject: importing csv file into sqlite References: <21067453.post@talk.nabble.com> <7f64f5c6-b130-4f9b-a670-6b32eccba550@n33g2000pri.googlegroups.com> Message-ID: On Dec 19, 11:17?pm, klia wrote: [ancient screed snipped] > > hey guys > i took all of your suggestion but my goal ain't yet achieved :-(( > these are the codes after changes, john i couldn't really catch what do you > mean by renaming input, is it just normal renaming. Somebody else told you not to use "input", choose another name > i am testing the code on > just simple .csv file with few data in as follows before trying on my hug > csv file but still no joy > > "Bithday",12-05-08,"HTC","this is my birthday" > "Sea",12-03-08,"kodak","sea" > "girl","14-03-2009","samsung","birthday" > "love","17-04-2009","SONY","view of island" > > import sqlite3 > import csv > > f = open('/home/waseem/Project2/photos.csv') > input = csv.reader(f, delimiter=',') > conn = sqlite3.connect('/home/waseem/Project2/pictures.db') > curse = conn.cursor() > > curse.execute('CREATE TABLE photos (Name VARCHAR(100) PRIMARY KEY, Date > INTEGER, Make VARCHAR(50), Tag VARCHAR(100))') > for row in input: > ? ? ? ? curse.execute('INSERT INTO photos VALUES (?,?,?,?)', '*row') > curse.commit() > > this time i got this error > > waseem at Linux:~/Project2$ python experment.py > Traceback (most recent call last): > ? File "experment.py", line 12, in > ? ? curse.execute('INSERT INTO photos VALUES (?,?,?,?)', '*row') > sqlite3.IntegrityError: column Name is not unique > > i removed the primary key and single quotation mark for '*row' to just *row > but i got the old error which is > > waseem at Linux:~/Project2$ python experment.py > Traceback (most recent call last): > ? File "experment.py", line 11, in > ? ? curse.execute('INSERT INTO photos VALUES (?,?,?,?)', *row) > TypeError: function takes at most 2 arguments (5 given) > No, the old error was """sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 4, and there are 1 supplied.""" That's quite different. Secondly you have already been told about the difference between row and *row ... as the message says, it wants 2 arguments, (1) the SQL (2) the sequence of values that will be used to replace the ?s in the SQL. So just lose the *, OK? From rafesacks at gmail.com Mon Dec 1 05:29:55 2008 From: rafesacks at gmail.com (Rafe) Date: Mon, 1 Dec 2008 02:29:55 -0800 (PST) Subject: Best way to dynamically get an attribute from a module from within the same module References: Message-ID: <18097f03-dfc9-4671-954a-2871ca0c1910@d42g2000prb.googlegroups.com> > 3) using the bare name: > whatever > 1) and 2) are useful when the desired name is variable, not a constant like "whatever". I thought that went without saying. > > I have been using #1 for two reasons. First, I will never run this > > module directly, so __name__ will always be the module name and not "__main__". > > (note that it works even with __main__) Nice. Thanks. > > Second, I can use this in a class to decide whether I want > > the module where the class came from or, if I make the class a base > I don't completely understand your use case. In the expression: > ? ? getattr(some_module, attribute_name) > you may use any module as the first argument (the current module, or any other). Right, I was just confused about the effects of inheritance and scope. If I put a method in a baseclass, which is inherited in another module, and then run the method from an instance of the sub-class... - "sys.modules[__name__]" returns the baseclass module. - "sys.modules[self.__class__.__module__]" returns the subclass module. in the end I found it felt more logical to put the code in a module- level function and call it from the class. All of this was part of a fairly large factory method implementation. I now know that globals() refers to module-level names. The pros and cons were the main point of this thread and so far I have... 1) getattr(module, "whatever") seems the most pythonic way to do it but it takes more than one line and requires a little more thought about scope and inheritance. 2) globals()["whatever"] is concise, but it seems a little like a shortcut which requires special knowledge (though a very small amount). I did a quick benchmark test: < tmp2.py > import time import sys import tmp class A(tmp.A): pass class B(tmp.A): pass class C(tmp.A): pass class D(tmp.A): pass class E(tmp.A): pass class F(tmp.A): pass class G(tmp.A): pass class H(tmp.A): pass class I(tmp.A): pass class J(tmp.A): pass def test_globals_vs_gettattr(): t1 = time.time() for i in range(0, 1000000): H = globals()["H"] t2 = time.time() print "globals() too %s seconds." % str(t2-t1) t1 = time.time() mod = sys.modules[__name__] for i in range(0, 1000000): H = getattr(mod, "H") t2 = time.time() print "getattr() too %s seconds." % str(t2-t1) < /tmp2.py > tmp.py just has a simple class in it. I just wanted to add some complexity, but I doubt this had any affect on the times. >>> import tmp2 >>> tmp2.test_globals_vs_gettattr() globals() too .146900010109 seconds. getattr() too .434299993515 seconds. Just to see how much the call to sys.modules was affecting the test, I moved it outside the loop and reloaded the module for a second test. >>> reload(tmp2) >>> tmp2.test_globals_vs_gettattr() globals() too .139100003242 seconds. getattr() too .254600000381 seconds. This second test is pointless in practice since I would be calling sys.modules each time anyway. Even though the getattr() way is around 3.5 times slower, I had to run the code 1,000,000 times before the difference became humanly recognizable. I also realize benchmarks should be taken with a grain of salt since my setup may differ greatly from others'. I guess, in the end, I'd use getattr() because it feels more pythonic, and more basic. I got pretty deep in to learning python before I had to learn what the globals() dict could do for me. Cheers, - Rafe From andrew at doadesweb.co.uk Wed Dec 10 13:00:23 2008 From: andrew at doadesweb.co.uk (Andrew D) Date: Wed, 10 Dec 2008 10:00:23 -0800 (PST) Subject: get todays files References: Message-ID: <3090b59b-a0b2-4bfb-a08f-6d6accfb363a@k36g2000pri.googlegroups.com> On Dec 10, 5:55?pm, Steve Holden wrote: > Andrew D wrote: > > I have a script that will login to my ftp server and download all the > > backup files, but I want it to only download the files that were > > created today, e.g. if I ran the script today I want it to only fetch > > files created today. > > > I am really not sure about how to do this, but it is quite important > > to me, so all help is highly appreciated! > > IIRC there's an "ftpmirror" script in the Tools directory (if you're on > Windows - Linux/Unix users have to download the source). I adapted it to > several different purposes. > > regards > ?Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ Thanks Steve, I don't want to sound rude here, but I really want some code to add to my script so that it will only download todays files. Andrew From george.sakkis at gmail.com Tue Dec 2 21:25:08 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 2 Dec 2008 18:25:08 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <591e8625-7e4d-4db8-ae6c-73c4370f8088@q26g2000prq.googlegroups.com> Message-ID: On Dec 2, 4:57?pm, Lew wrote: > There is no reason for you to engage in an /ad hominem/ attack. ?It > does not speak well of you to resort to deflection when someone > expresses a contrary opinion, as you did with both Jon Harrop and with > me. ?I suggest that your ideas will be taken more seriously if you > engage in more responsible behavior. As a Slashdotter would put it... you must be new here ;-) From Matthijs.Mullender at gmail.com Wed Dec 10 10:38:21 2008 From: Matthijs.Mullender at gmail.com (Matthijs) Date: Wed, 10 Dec 2008 07:38:21 -0800 (PST) Subject: ANN: python-ntlm - provides NTLM support, including an authentication handler for urllib2 Message-ID: <4a7fe683-7c92-41ef-a785-0cea82a0f4a9@a12g2000pro.googlegroups.com> Announcing: python-ntlm http://code.google.com/p/python-ntlm/ python-ntlm is a library that provides NTLM support, including an authentication handler for urllib2. This library allows you to retrieve content from (usually corporate) servers protected with windows authentication (NTLM) using the python urllib2. For more details and downloads visit: http://code.google.com/p/python-ntlm/ == Example Usage == import urllib2 from ntlm import HTTPNtlmAuthHandler user = 'DOMAIN\User' password = "Password" url = "http://ntlmprotectedserver/securedfile.html" passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, url, user, password) # create the NTLM authentication handler auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman) # create and install the opener opener = urllib2.build_opener(auth_NTLM) urllib2.install_opener(opener) # retrieve the result response = urllib2.urlopen(url) print(response.read()) From sanket.s.patel at gmail.com Fri Dec 19 17:01:40 2008 From: sanket.s.patel at gmail.com (sanket) Date: Fri, 19 Dec 2008 14:01:40 -0800 (PST) Subject: how to convert pymedia.audio.acodec ACString to ctypes.c_char_p Message-ID: <82fa9417-7fbd-444c-b2a9-305f62e40287@v5g2000prm.googlegroups.com> Hello All Experts, I am quite new to Ctypes. I am using one c library and writing python bindings for it. I need to pass a character pointer to one function. I am reading one mp3 file and decoding it to raw pcm using pymedia. Now I need to pass this raw data in to a C function. Here is my code. # /********* from ctypes import * import pymedia.audio.acodec as codec dec = None dm = muxer.Demuxer('mp3') fp = open('test.mp3', 'rb') fingerprinting_done = False while not fingerprinting_done: s = fp.read(20000) frames = dm.parse(s) for fr in frames: if dec == None: dec = codec.Decoder(dm.streams[0]) r = dec.Decode(fr[1]) if r and r.data: # pass this r.data to the C function. # r.data is ACString object # I cannot do pcm_audio = c_char_p(r.data) . gives me following error # TypeError: string or integer address expected instead of ACString instance # *************/ I am getting error while converting r.data (which is ACstring object) in to ctypes.c_char_p. can you help me solving this problem? any help would be appericiated, Thank you, sanket From clp at rebertia.com Tue Dec 16 19:25:12 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 16 Dec 2008 16:25:12 -0800 Subject: Free place to host python files? In-Reply-To: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> References: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> Message-ID: <47c890dc0812161625o76f5c7e6lb8809b99f6962d32@mail.gmail.com> On Tue, Dec 16, 2008 at 6:10 AM, feba wrote: > I'm getting started in python, and it would be helpful to have a place > to put up various code snippets I've made, so I don't have to send > them individually to each person I want to show it to. I'd prefer to > use something that would give me a directory for my use only, instead > of something where you can only upload one at a time. I'd especially > like to avoid stuff that uses CAPTCHAs and/or forced waiting periods. > > I'd really rather not have to run a server off my own computer, if it > can be avoided at all. I'll plug Bitbucket (http://bitbucket.org/). It gives you 150MB of Mercurial hosting for free, along with a bug tracker and wiki. And I hear it's implemented using Django. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From bdesth.quelquechose at free.quelquepart.fr Tue Dec 30 13:55:53 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 30 Dec 2008 19:55:53 +0100 Subject: duck typing at will In-Reply-To: References: Message-ID: <495a7c6a$0$30721$426a74cc@news.free.fr> Jose Mora a ?crit : > Duck typing is called that way because "If it looks like a duck and > quacks like a duck, it must be a duck." or at least something close enough... > I think it would be good to > have also "If the programmer wants to deal with it like a duck, it > must be a duck" DWIM[1] just doesn't work. No parser can read your mind, and the harder they try, the more bugs they are likely to cause. IOW : cows neither look nor quack like ducks, and asking a cow to quack just won't turn your cow into a duck. [1] Do What I Mean > I mean, some tasks are rather boring in python when compared with php, Possibly. OTHO, and from years of experience with both languages, a lot of tasks are way more boring in php when compared to Python. > for example, let's imagine we have a dictionary that contains > dictionaries that contain the times that a key appears. We, or at > least I, would like to write something as short as: > > dict[k1][k2] += 1 > > However we will have to do a longer code (this is the smallest code I > could come up with): > dict = {} bad identifier - it shadows the builtin dict type. > if not k1 in dict: > dict[k1] = {} > if not k2 in dict[k1]: > dict[k1][k2] = 0 > dict[k1][k2] += 1 What about: from collections import defaultdict d = defaultdict(lambda: defaultdict(int)) for k1, k2 in whatever: d[k1][k2] += 1 NB : this requires a "recent" Python version (works on 2.5.1 at least). Else, yes, this will be a bit more "boring": d = dict() for k1, k2 in whatever: d2 = d.setdefault(k1, dict()) d2[k2] = d2.get(k2, 0) + 1 HTH From jeff_barish at earthlink.net Sun Dec 21 19:24:32 2008 From: jeff_barish at earthlink.net (Jeffrey Barish) Date: Sun, 21 Dec 2008 17:24:32 -0700 Subject: Beep References: <47c890dc0812211620h6c19086dhf3a14a662a49fdf6@mail.gmail.com> Message-ID: Chris Rebert wrote: > > Is the 'pcspkr' kernel module built and loaded? Yes. And I should have mentioned that I get sound from Ubuntu applications that produce sound. -- Jeffrey Barish From aisaac at american.edu Thu Dec 4 15:15:22 2008 From: aisaac at american.edu (Alan G Isaac) Date: Thu, 04 Dec 2008 15:15:22 -0500 Subject: "as" keyword woes In-Reply-To: References: Message-ID: <8aSdnSpVVdTAp6XUnZ2dnUVZ_szinZ2d@rcn.net> Warren DeLano wrote: > what I can't understand is the decision to break 2.6 instead of 3.0. 2.x was > supposed to remain backwards compatible, with the thinking that 2.x > would be maintained in parallel for quite some time. 3.x was supposed > to be the compatibility break. I do not understand why anyone would object to this perfectly cogent complaint of Warren's. Even if the deprecation warnings had not been invisible, the complaint would be valid. Alan Isaac From excord80 at gmail.com Fri Dec 12 01:27:06 2008 From: excord80 at gmail.com (excord80 at gmail.com) Date: Thu, 11 Dec 2008 22:27:06 -0800 (PST) Subject: How do I manually uninstall setuptools (installed by egg)? References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> <375bd56a-d92b-4d33-bf70-5bea630a376a@q30g2000vbn.googlegroups.com> <6q9rvnFbj6ogU1@mid.uni-berlin.de> Message-ID: <227a9972-e37d-40a0-bd9b-4fadd9e2473e@m15g2000vbp.googlegroups.com> On Dec 10, 7:45?am, "Diez B. Roggisch" wrote: > excor... at gmail.com wrote: > > > As an aside, I'm a bit struck by how long the setuptools/easy_install > > manuals are, and a bit dismayed at the lack of an easy_install > > uninstall command. Thinking of trying life for a while without > > setuptools/easy_install. Will have to see how far I get. :) > > To *long* manuals? So far I haven't heard that complaint in the FOSS > world... I didn't say that the manuals were too long, I said I was *struck by* how long they are. I read them through a while back, and they seemed long and confusing to me at the time. While reading, I kept thinking, "this should be simpler" and "why does a seemingly simple tool need such a long manual?". Maybe setuptools/easy_install/eggs is not overly complicated, but it seems that way to me. From gagsl-py2 at yahoo.com.ar Wed Dec 24 14:43:25 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2008 17:43:25 -0200 Subject: Custom C Exception Subclasses References: <41f291ff-d7bd-4334-8689-636e95524cdc@b38g2000prf.googlegroups.com> Message-ID: En Wed, 24 Dec 2008 15:48:34 -0200, Gabriel Genellina escribi?: > En Wed, 24 Dec 2008 15:00:36 -0200, Ivan Illarionov > escribi?: > >> When you raise an exception in C++ you can set it to ANY Python object >> via PyErr_SetObject and that object could store pointers to C++ >> classes. > > Remember that exceptions should inherit from BaseException; although > this rule isn't enforced in Python 2.6, 3.0 doesn't allow that. > It isn't explicitely written in the docs, but I think that > PyErr_SetObject won't allow you to pass an object which is not an > instance of its first argument. Correction: you're right, it is OK to pass any other object as the second parameter to PyErr_SetObject; it will be used as the argument to the exception constructor. -- Gabriel Genellina From arnodel at googlemail.com Tue Dec 16 16:14:44 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 16 Dec 2008 21:14:44 +0000 Subject: How to modify a program while it's running? References: Message-ID: Joe Strout writes: > Here's my situation: I'm making an AIM bot, but the AIM server will > get annoyed if you log in too frequently (and then lock you out for a > while). So my usual build-a-little, test-a-little methodology doesn't > work too well. > > So I'd like to restructure my app so that it can stay running and stay > logged in, yet I can still update and reload at least most of the > code. But I'm not sure what's the best way to do this. Should I move > the reloadable code into its own module, and then when I give my bot a > "reload" command, have it call reload on that module? Will that work, > and is there a better way? > > Thanks, > - Joe You could have two processes: the first one that logs in and does the message passing with the server, the other that implements the logic and talks to the server via the first one. This way you can restart the second one as often as you want without being logged out. I never user reload() but I hear that it has quite a few caveats. -- Arnaud From steve at REMOVE-THIS-cybersource.com.au Sat Dec 6 21:17:58 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 02:17:58 GMT Subject: [Python-Dev] "as" keyword woes References: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> Message-ID: <014b2a09$0$20670$c3e8da3@news.astraweb.com> On Sun, 07 Dec 2008 11:27:56 +1000, Nick Coghlan wrote: > Warren DeLano wrote: >> In other words we have lost the ability to refer to "as" as the >> generalized OOP-compliant/syntax-independent method name for casting: > > Other possible spellings: > > # Use the normal Python idiom for avoiding keyword clashes # and append > a trailing underscore > new_object = old_object.as_(class_hint) float_obj = int_obj.as_("float") > float_obj = int_obj.as_(float_class) > > # Use a different word (such as, oh, "cast" perhaps?) new_object = > old_object.cast(class_hint) float_obj = int_obj.cast("float") > float_obj = int_obj.cast(float_class) I don't like "cast", because a cast is an instruction to the compiler to treat data as some type other than what it was defined as. It doesn't create a new piece of data. (At least in C-like languages.) I'd prefer a method like obj.make_from(type) or obj.export_as(type) or similar. It's more verbose than "as" but its more explicit about what it does. obj.as(type) is ambiguous, because it could mean any "return a new object of type made from obj", "return obj inside a wrapper that makes it behave as if it were type", "convert obj to type in place". -- Steven From nick at craig-wood.com Tue Dec 2 08:30:45 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 02 Dec 2008 07:30:45 -0600 Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> <258cf433-f6c9-43e7-a235-f5f6b2b6433f@j39g2000yqn.googlegroups.com> Message-ID: Slaunger wrote: > On 2 Dec., 11:30, Nick Craig-Wood wrote: > > > > > For 4 attributes I'd probably go with the __getattr__. > > > OK, I'll do that! > > > Or you could easily write your own decorator to cache the result... > > > > Eg http://code.activestate.com/recipes/363602/ > > Cool. I never realized I could write my own decorators! > I've so far only used them for > @classmethod, @staticmethod and stuff like that. > User defined decorators are nice and fun to do as well. > I just hope it will be understandable > in four years also... Actually that decorator does exactly what you want. It replaces the attribute with the actual data so after the first call there is no overhead. I'd use that I think! > > > ?With the property methology you do the value check on each get, which > > > ?does not look as "clean". The property methology is also a little less > > > ?arcane I guess for less experienced Python programmers to understand > > > ?when re-reading the code. > > > > Less magic is how I would put it. ?Magic is fun to write, but a pain > > to come back to. ?Over the years I find I try to avoid magic more and > > more in python. > > > Ah, I see. I hope you do not consider user defined decorators > "magic" then? ;-) Well the magic is contained in the decorator so it isn't splattered throughout your code! Decorators are part of the meta-programming toolbag along with metaclasses. Used sparingly they can be extrememly useful! > Again, thank you for your assistance, Nick! No problem! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bdesth.quelquechose at free.quelquepart.fr Mon Dec 29 13:10:39 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 29 Dec 2008 19:10:39 +0100 Subject: SQL, lite lite lite In-Reply-To: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> Message-ID: <4959204f$0$15020$426a74cc@news.free.fr> Aaron Brady a ?crit : > Hi all, > (snip) > > I don't think relational data can be read and written very easily in > Python. Did you try SQLAlchemy or Django's ORM ? > There are some options, such as 'sqllite3', but they are not > easy. 'sqllite3' statements are valid SQL expressions, which afford > the entire power of SQL, but contrary to its name, it is not that > 'lite'. sqlite is a Python-independant library providing a lightweight SQL embedded (ie : no server) database system. It is "light" wrt/ Oracle, Postgres etc. > To me, 'lite' is something you could learn (even make!) in an > afternoon, not a semester; No one in it's own mind would hope to learn the relational theory and algebra in an afternoon, whatever the implementation. > something the size of an ActiveState > recipe, or a little bigger, maybe a file or two. If you think SQL is > a breeze, you probably won't find my idea exciting. I assume that the > basics of SQL are creating tables, selecting records, and updating > records. There's much more than this. > My idea is to create a 'Relation' class. The details are basically > open, such as whether to back it with 'sqllite3', 'shelve', 'mmap', or > just mapping and sequence objects; what the simplest syntax is that > can capture and permit all the basics, and how much and what else can > fit in at that level; how and whether it can include arbitrary Python > objects, and what constraints there are on them if not; how and > whether to permit transactions; and what the simplest and coolest > thing you can do with a little Python syntax is. > > This is basically an invitation for everyone to brainstorm. (No > hijackings, good humor & digression ok.) Lastly, ... > > > #Just the select and update syntax: > >>>> a= people._select( "firstname== 'Joe'" ) > #select 'key' from 'people' where 'firstname'== 'joe' >>>> a > [Entry2864, Entry3076, Entry3172] >>>> entry1= a[ 0 ] >>>> entry1.phone > #select 'phone' from 'people' where 'key'==self.key > "555-2413" >>>> entry1.phone= "555-1234" > #update 'people' set 'phone'= '555-1234' where 'key'==self.key >>>> entry1.phone > "555-1234" > > #Create table syntax (a-whole-nother beast in itself): > >>>> classes= db.Relation( 'class_', 'person', Unique( 'class_', 'person' ) ) > #create table 'classes' ( 'key', 'class_', 'person' ) unique > ( 'class_', 'person' ) >>>> classes._unique( 'class_', 'person' ) >>>> classes.class_.noneok= False #'class_' cannot be null >>>> classes.person.noneok= False >>>> classes._insert( 'Physics', 'Dan' ) >>>> classes._insert( 'Chem', 'Tim' ) From django's tutorial, part 1: # polls/models.py import datetime from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __unicode__(self): return self.question def was_published_today(self): return self.pub_date.date() == datetime.date.today() class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) votes = models.IntegerField() def __unicode__(self): return self.choice # in the interactive shell >>> from mysite.polls.models import Poll, Choice >>> Poll.objects.all() [] # Create a new Poll. >>> import datetime >>> p = Poll(question="What's up?", pub_date=datetime.datetime.now()) # Save the object into the database. You have to call save() explicitly. >>> p.save() # Now it has an ID. Note that this might say "1L" instead of "1", depending # on which database you're using. That's no biggie; it just means your # database backend prefers to return integers as Python long integer # objects. >>> p.id 1 # Access database columns via Python attributes. >>> p.question "What's up?" >>> p.pub_date datetime.datetime(2007, 7, 15, 12, 00, 53) # Change values by changing the attributes, then calling save(). >>> p.pub_date = datetime.datetime(2007, 4, 1, 0, 0) >>> p.save() # objects.all() displays all the polls in the database. >>> Poll.objects.all() [] # Django provides a rich database lookup API that's entirely driven by # keyword arguments. >>> Poll.objects.filter(id=1) [] >>> Poll.objects.filter(question__startswith='What') [] # Get the poll whose year is 2007. Of course, if you're going through this # tutorial in another year, change as appropriate. >>> Poll.objects.get(pub_date__year=2007) >>> Poll.objects.get(id=2) Traceback (most recent call last): ... DoesNotExist: Poll matching query does not exist. # Lookup by a primary key is the most common case, so Django provides a # shortcut for primary-key exact lookups. # The following is identical to Poll.objects.get(id=1). >>> Poll.objects.get(pk=1) # Make sure our custom method worked. >>> p = Poll.objects.get(pk=1) >>> p.was_published_today() False # Give the Poll a couple of Choices. The create call constructs a new # choice object, does the INSERT statement, adds the choice to the set # of available choices and returns the new Choice object. >>> p = Poll.objects.get(pk=1) >>> p.choice_set.create(choice='Not much', votes=0) >>> p.choice_set.create(choice='The sky', votes=0) >>> c = p.choice_set.create(choice='Just hacking again', votes=0) # Choice objects have API access to their related Poll objects. >>> c.poll # And vice versa: Poll objects get access to Choice objects. >>> p.choice_set.all() [, , ] >>> p.choice_set.count() 3 # The API automatically follows relationships as far as you need. # Use double underscores to separate relationships. # This works as many levels deep as you want; there's no limit. # Find all Choices for any poll whose pub_date is in 2007. >>> Choice.objects.filter(poll__pub_date__year=2007) [, , ] # Let's delete one of the choices. Use delete() for that. >>> c = p.choice_set.filter(choice__startswith='Just hacking') >>> c.delete() NB : works with sqlite, MySQL and Postgres, and supports transactions if the underlying SQL engine supports them. HTH From rhodri at wildebst.demon.co.uk Sat Dec 6 19:31:21 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Sun, 07 Dec 2008 00:31:21 -0000 Subject: python book for non technical absolute beginner In-Reply-To: <493a7c6a$0$973$426a34cc@news.free.fr> References: <493a7c6a$0$973$426a34cc@news.free.fr> Message-ID: On Sat, 06 Dec 2008 13:21:45 -0000, News123 wrote: > No my question does anybody know a nice beginners book (or a learning CD > or on line tutorial)? Ideally it shouldn't be too serious and have a lot > of small nice mini-examples For just pottering around with, your friend could do worse than the LiveWires Python Course. It doesn't go far into general programming skills, largely because its designed for 12-15 year old kids to get through in about three days of concentrated effort, but it will help to learn the basics of Python and programming in general. Caveat: the worksheets are built around Python 2.x (for small values of x!), tell your friend not to use Python 3.0. This is one of the few cases where it really matters that 'print' is now a function; nothing freaks a beginner like his output not behaving the way he's been told it should. -- Rhodri James *-* Wildebeeste Herder to the Masses From google at mrabarnett.plus.com Fri Dec 5 10:59:10 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 05 Dec 2008 15:59:10 +0000 Subject: pretty strange behavior of "strip" In-Reply-To: References: <4938693F.6090709@yahoo.ca> Message-ID: <49394FCE.2010700@mrabarnett.plus.com> rdmurray at bitdance.com wrote: > On Thu, 4 Dec 2008 at 20:54, Terry Reedy wrote: >>> 'toc.html' >>> > > > test[4].strip('.html') >>> 'oc' >>> >>> Can't figure out what is going on, really. >> >> What I can't figure out is why, when people cannot figure out what is >> going on with a function (or methods in this case), they do not look >> it up the doc. (If you are an exception and did, what confused you?) >> Can you enlighten me? > > I'm a little embarrassed to admit this, since I've been using python for > many years, but until I read these posts I did not understand how strip > used its string argument, and I _have_ read the docs. I can't tell you > what confused the OP, but I can tell you what confused me. > > I have often wished that in 'split' I could specify a _set_ of characters > on which the string would be split, in the same way the default list > of whitespace characters causes a split where any one (or more) of > them appears. But instead the string argument is a multi-character > separator. (Which is sometimes useful and I wouldn't want to lose the > ability to specify a multi-character separator!) > > My first experience in using the string argument was with split, so when I > ended up using it with strip, by analogy I assumed that the string passed > to strip would also be a multi-character string, and thus stripped only > if the whole string appeared exactly. Reading the documentation did > not trigger me reconsider that assumption. I guess I'm just lucky that > I haven't run into any bugs (but I think I've used the string argument > to strip only once or twice in my career). > > It would be lovely if both the split and strip methods would have a > second string argument that would use the string in the opposite sense > (as a set for split, as a sequence match for strip). > > In the meantime the docs could be clarified by replacing: > > the characters in the string will be stripped > > with > > all occurrences of any of the characters in the string will be > stripped > > --RDM > > PS: the OP might want to look at th os.path.splitext function. > If I had thought about it early enough I could have suggested that in Python 3 split() and strip() should accept either a string or a set of strings. It's still possible to extend split() in the future, but changing the behaviour of strip() with a string argument would break existing code, something which might have been OK as part of changes in Python 3. Unfortunately I don't have access to the time machine! :-) From greywine at gmail.com Fri Dec 26 01:08:34 2008 From: greywine at gmail.com (greywine at gmail.com) Date: Thu, 25 Dec 2008 22:08:34 -0800 (PST) Subject: socket send help References: Message-ID: <8a5a2b07-3274-483a-be06-51eab226315a@d36g2000prf.googlegroups.com> Hi again, I've done some more playing around with socket and socketserver and have discovered I can send strings or lists with socket.send() by converting to bytes. But lists with strings in them or dicts can't be converted by bytes(). How can I send those? One idea I initially tried was to set up a server (host,port) for receiving data and another one (host, different port) for strings, but that didn't work so I was thinking of throwing everything into a list or a dictionary and sending that but that's not working either. Any ideas? Thanks, John. On Dec 24, 12:03?am, "Gabriel Genellina" wrote: > En Wed, 24 Dec 2008 03:59:42 -0200, greyw... at gmail.com ? > escribi?: > > > New guy here. ?I'm trying to figure out sockets in order to one day do > > a multiplayer game. ?Here's my problem: ?even the simplest examples > > don't work on my computer: > > > A simple server: > > > fromsocketimport * > > myHost = '' > > Try with myHost = '127.0.0.1' instead - a firewall might be blocking your ? > server. > > > s.listen(5) ? ? ? ? ? ? ? ? ? ? ? ? # allow 5 simultaneous connections > > Not exactly: your server program only handles a single connection at a ? > time. The 5 above specifies how many connections may exist "on hold" ? > waiting for you to accept() them. > > > ? ? ? ? ? ? connection.send('echo -> ' + data) > > That's fine for Python 2.6, but you must use b'echo -> ' with 3.0 > > > And a simple client: > > > s.send('Hello world') ? ? ? ? ? ? ? # send the data > > Same as above, should be b'Hello world' with Python 3.0 > > > If I run testserver.py via the cmd prompt in Windows XP and then the > > testclient.py program, I get the following error: > > > Traceback (most recent call last): > > ? File "C:\Python30\testclient.py", line 12, in > > ? ? s.send('Hello world') ? ? ? ? ? ? ? # send the data > > TypeError: send() argument 1 must be string or buffer, not str > > The above error message is wrong (and I think it was corrected on the 3.0 ? > final release; if you got it with 3.0 final, file a bug report at ?http://bugs.python.org/) > > > This happens in 2.6 or 3.0 and with different example client & server > > programs from the web. ?What am I missing? > > The error above surely comes from 3.0; with 2.6 you should get a different ? > error (if it fails at all). Try again with 2.6.1. I didn't run the code ? > but it looks fine -- if you got it from a book or article, unless it ? > explicitely says "Python 3.0", assume it was written for the 2.x series. > > -- > Gabriel Genellina From rt8396 at gmail.com Mon Dec 22 19:12:36 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 16:12:36 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> <80427165-02a0-4401-ade9-3cef1d520e6c@v39g2000pro.googlegroups.com> Message-ID: <014977ea-a1aa-40ba-8ea2-bec4a84f5fcd@r27g2000vbp.googlegroups.com> On Dec 22, 5:53?pm, Aaron Brady wrote: > On Dec 22, 11:40?am, r wrote: > > > > > On Dec 22, 8:58?am, walterbyrd wrote: > > > > On Dec 21, 12:28?pm, Bruno Desthuilliers > > > > wrote: > > > > Strange enough, > > > > no one seems to complain about PHP or Ruby's performances... > > > > A few years back, there was a certain amount of chest thumping, when > > > python/django easily beat ror in a benchmark test. Now that ruby is > > > faster, I guess speed is no big issue. > > > > By the same reasoning, python advocates used to sneer at php because > > > php constantly broke backward compatibility. Now that python does it, > > > breaking backward compatibility is no big deal. I guess unicode > > > support was not that important, until python caught up to perl. > > > > I guess, the way it works is: you first assume that python is > > > superior, then you figure out why. > > > I think what walter is saying is the loyalty is gone. > > > community: > > """If python makes great, if it doesn't, why should "i" care if it > > goes down the toilet? ?i just move to ruby""" > > > Were is your loyalty pyfans?, Has the fight left you??? > > Point: It is not rational for the crew to go down with the ship, only > the captain. > > Case: Loyalty is a complex emotion, and it's not clear that it's our > highest priority, or that it's anyone's. > > I want to use a good language. ?If Python stops being good (that is, a > good version of Python stops being maintained and supported), then > I'll stop using it, and that's the rational thing to do. > > Just to be fair, though, it's (contraction) not obviously irrational > for a captain to go down with the ship. ?The mentality, commitments, > and principles that it lets him keep and make may be better on the > whole in the long run for captains, crews, and ships, only if they > have that consequence. ?That is, captains that will go down with the > ship are better captains of ships, and captains that have the capacity > to betray, forge, or abandon principles make worse captains; therefore > a good captain will go down, and can't change his mind. > > However, as critics and fans of Python, our actions don't really have > the same consequences as the captains. ?That is, it is not rational > for the crew to go down with the ship, only the captain. What if the crew sabotage the ship, should the captain still go down with it, even though sabatuers are to blame? All ships need a good captain, all captains need a good crew, and all crews need a good ship.(also True in reverse()). Without loyalty python will fail, so will Ruby, so will C. Sometimes even when loyalty is scarce, a language will survive solely because it is the only ship available. You do not have to fight for python as I do to use it and benefit from it, that's OK. I don't care either way. But don't piss on me for trying to keep her a-float, Mate!. From duncan.booth at invalid.invalid Tue Dec 2 13:52:52 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Dec 2008 18:52:52 GMT Subject: [ANN] Pyjamas 0.4: Python Web Toolkit Release References: Message-ID: "Luke Kenneth Casson Leighton" wrote: > Pyjamas started as a port of Google's Web Toolkit, to python. > Explaining why Pyjamas (and GWT) is so significant takes > some doing: the summary is that comprehensive desktop-like > user interfaces can be developed very simply, to run in > any modern web browser, without having to write a single > line of JavaScript. Great concept. The demos are a bit flakey (especially with IE): where do you want bug reports (the sourceforge tracker seems to be empty so I wondered if you used somewhere else)? From walterbyrd at iname.com Sat Dec 20 18:36:46 2008 From: walterbyrd at iname.com (walterbyrd) Date: Sat, 20 Dec 2008 15:36:46 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> Message-ID: <88a122de-14c6-4025-b36c-9a39bdd50d86@i20g2000prf.googlegroups.com> On Dec 19, 10:55?am, bearophileH... at lycos.com wrote: > Regarding the speed of Python3 programs, > they will go faster "The net result of the 3.0 generalizations is that Python 3.0 runs the pystone benchmark around 10% slower than Python 2.5. " http://docs.python.org/dev/3.0/whatsnew/3.0.html > (Ruby programs are often slower > than Python ones (because Ruby > is a little higher level than Python) As I understand it, that may have been true at one time. But, Ruby 1.9 very significantly sped up the language. While Python has been made slower, Ruby has been made much faster. I am no expert on the subject, I am just going by stuff I have read on web. From invalid at invalid Thu Dec 11 11:59:56 2008 From: invalid at invalid (Grant Edwards) Date: Thu, 11 Dec 2008 10:59:56 -0600 Subject: Python, threading References: Message-ID: On 2008-12-11, SMALLp wrote: > Hy. I have a problem! I'm making multi thread application (client, > server) using wxPython for GUI, and threading.Thread for threding. > > Clients connect and when they are connected (evry thread handles one > connection) threads change main window. > > I neded tip how to make communication between threeds. All window manipulation must be done in the main thread. Your worker threads can schedule work to be done by the main thread by using wx.CallAfter() http://wiki.wxpython.org/CallAfter -- Grant Edwards grante Yow! This is a NO-FRILLS at flight -- hold th' CANADIAN visi.com BACON!! From arnodel at googlemail.com Tue Dec 16 13:17:14 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 16 Dec 2008 18:17:14 +0000 Subject: Generator slower than iterator? References: Message-ID: bearophileHUGS at lycos.com writes: > This can be a little faster still: > > match_counter = defaultdict(int) > for line in fileinput.input(sys.argv[1:]): > ip = line.split(None, 1)[0] > match_counter[ip] += 1 > > Bye, > bearophile Or maybe (untested): match_counter = defaultdict(int) for line in fileinput.input(sys.argv[1:]): ip = line[:line.index(' ')] match_counter[ip] += 1 Or even (untested, I've never tried this ;): from itertools import count match_counter = defaultdict(count) for line in fileinput.input(sys.argv[1:]): ip = line[:line.index(' ')] match_counter[ip].next() match_total = dict((key, val()) for key, val in match_counter.iteritems()) Obviously the variable 'ip' could be removed in all cases. -- Arnaud From __peter__ at web.de Mon Dec 1 14:52:08 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 01 Dec 2008 20:52:08 +0100 Subject: Checking a string against multiple matches References: <99a3a677-a38d-40f5-9a94-a98865150b69@k19g2000yqg.googlegroups.com> Message-ID: Aaron Scott wrote: > I've been trying to read up on this, but I'm not sure what the > simplest way to do it is. > > I have a list of string. I'd like to check to see if any of the > strings in that list matches another string. > > Pseudocode: > > if "two" in ["one", "two", "three", "four"]: > return True Why /pseudo/ ? >>> if "two" in ["one", "two", "three", "four"]: ... print "match" ... else: ... print "no match" ... match >>> if "seven" in ["one", "two", "three", "four"]: ... print "match" ... else: ... print "no match" ... no match > Is there any built-in iteration that would do such a thing, or do I > have to write a function to check for me? I was using .index on the > list, but it would return True for strings that contained the search > string rather than match it exactly, leading to false positives in my > code. You didn't check carefully. list.index() gives you a value error when no matching item is found: >>> ["one", "two", "three", "four"].index("seven") Traceback (most recent call last): File "", line 1, in ValueError: list.index(x): x not in list Peter From bearophileHUGS at lycos.com Thu Dec 11 13:34:45 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 11 Dec 2008 10:34:45 -0800 (PST) Subject: dictionary idiom needed References: <383976cf-53fb-48e4-b028-8f568468ce77@r36g2000prf.googlegroups.com> Message-ID: <0c4950c1-4833-40c7-ac19-260b61d5289f@k24g2000pri.googlegroups.com> Brandon: > I need an dictionary idiom whereby I can find all instances of > a given 'word' with any 'tagB', and then subdivide into all instances > of a given 'tagB'. ?In both cases I would want the value as a count of > all instances found. If I have understood you well enough, I think you can do with a dict that has the tuple ('word', 'tagB') as key, and as value has a collections.defaultdict(int) that maps 'tagB' to its count. Bye, bearophile From mirandasnailvv at gmail.com Fri Dec 19 19:42:45 2008 From: mirandasnailvv at gmail.com (mirandasnailvv at gmail.com) Date: Fri, 19 Dec 2008 16:42:45 -0800 (PST) Subject: mixed wrestling pantyhose - Free Message-ID: <96a64fb6-7c6e-4fe4-b019-545efd5bc3da@u18g2000pro.googlegroups.com> mixed wrestling pantyhose . . . *******CLICK HERE******** http://club247.cn/mixed-wrestling-pantyhose ***************************** . . . . . . . . . . . . mixed wrestling pantyhose From bcausey at zerodayconsulting.com Wed Dec 24 13:20:17 2008 From: bcausey at zerodayconsulting.com (Brad Causey) Date: Wed, 24 Dec 2008 12:20:17 -0600 Subject: String Comparison Testing Message-ID: <89f89940812241020l3e814f2dv4479da8d6575f7e7@mail.gmail.com> Python Version: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 List, I am trying to do some basic log parsing, and well, I am absolutely floored at this seemingly simple problem. I am by no means a novice in python, but yet this is really stumping me. I have extracted the pertinent code snippets and modified them to function as a standalone script. Basically I am reading a log file ( in this case, testlog.log) for entries and comparing them to entries in a safe list (in this case, safelist.lst). I have spent numerous hours doing this several ways and this is the most simple way I can come up with: import string safelistfh = file('safelist.lst', 'r') safelist = safelistfh.readlines() logfh = file('testlog.log', 'r') loglines = logfh.readlines() def safecheck(line): for entry in safelist: print 'I am searching for\n' print entry print '\n' print 'to exist in\n' print line comp = line.find(entry) if comp <> -1: out = 'Failed' else: out = 'Passed' return out for log in loglines: finalentry = safecheck(log) if finalentry == 'Failed': print 'This is an internal site' else: print 'This is an external site' The contents of the two files are as follows: http://www.mysite.com http://www.mysite.com/images/homepage/xmlslideshow-personal.swf It seems that no matter what I do, I can't get this to fail the " if comp <> -1:" check. (My goal is for the check to fail so that I know this is just a URL to a safe[internal] site) My assumption is that the HTTP:// is somehow affecting the searching capabilities of the string.find function. But I can't seem to locate any documentation online that outlines restrictions when using special characters. Any thoughts? Thanks! -Brad Causey CISSP, MCSE, C|EH, CIFI Zero Day Consulting -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at cheimes.de Tue Dec 16 13:50:09 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 16 Dec 2008 19:50:09 +0100 Subject: subprocess returncode windows In-Reply-To: References: Message-ID: Andrew schrieb: > Hello, > > I'm running into a strange situation with getting incorrect > returncodes / exit status from python subprocess.call. I'm using a > python script (runtime 2.6.1 on windows) to automate the deploy of > java applications to glassfish application server. Below is an example > of using a subprocess call to test the success / failure of the > glassfish CLI tool "asadmin" > > Example.py: > ---------------------- > import sys > from subprocess import * > > try: > retcode = call("c:/glassfish/bin/asadmin.bat " + "list-system- > properties --host mydomain --port 4848 --user admin server-01", > shell=True) > if retcode < 0: > print >>sys.stderr, "Child was terminated by signal", -retcode > else: > print >>sys.stderr, "Child returned", retcode > except OSError, e: > print >>sys.stderr, "Execution failed:", e Don't use shell=True! Instead use a list of arguments without shell=True: call(["c:/glassfish/bin/asadmin.bat", "list-system-properties", "--host mydomain", "--port 4848", "--user admin", "server-01"]) That should solve your quoting issues on Windows and fix your code. shell=True is considered evil and should be avoided whenever possible. Christian From reckoner at gmail.com Mon Dec 15 14:06:16 2008 From: reckoner at gmail.com (Reckoner) Date: Mon, 15 Dec 2008 11:06:16 -0800 (PST) Subject: tricky nested list unpacking problem Message-ID: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> Hi, I have lists of the following type: [1,2,3,[5,6]] and I want to produce the following strings from this as '0-1-2-3-5' '0-1-2-3-6' That was easy enough. The problem is that these can be nested. For example: [1,2,3,[5,6],[7,8,9]] which should produce '0-1-2-3-5-7' '0-1-2-3-5-8' '0-1-2-3-5-9' '0-1-2-3-6-7' '0-1-2-3-6-8' '0-1-2-3-6-9' also, [1,2,3,[5,6],7,[9]] should produce '0-1-2-3-5-7-9' '0-1-2-3-6-7-9' obviously, these are nested loops over the lists. The problem is that I don't know ahead of time how many lists there are or how deep they go. In other words, you could have: [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]] Any help appreciated. I've really been having trouble with this. I hope that made sense. From mynthon1 at gmail.com Tue Dec 23 05:50:20 2008 From: mynthon1 at gmail.com (mynthon) Date: Tue, 23 Dec 2008 02:50:20 -0800 (PST) Subject: wxPython.button.disabled still catching clicks Message-ID: <8cb6da6a-7df4-4cce-a28e-385448a25b26@w39g2000prb.googlegroups.com> Hello! (sorry for my english) I have a problem with buttons in wxPython. When button is disabled (by .Disable() or .Enable(False)) it is grayed out but still receive clicks. Eg. i have button that disable itself, runs long action and enable itself: def onClick(self, evt): self.btn.Enable(False) for i in range (1000): print i self.btn.Enable(True) when for loop is running button is greyed out and when i click on it nothing happens but when loop ends another one is started because button "remebered" thad i click on it when was diabled. My only idea is to reposition button outside frame instead of disabling it but this solution is...not good. thanks for any help. Ive searched groups, google and it looks that only i have this problem :) From philip at semanchuk.com Sun Dec 21 15:03:40 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Sun, 21 Dec 2008 15:03:40 -0500 Subject: Are Django/Turbogears too specific? In-Reply-To: References: Message-ID: <95659C49-5A3F-4001-BE6D-A63D577D692C@semanchuk.com> On Dec 21, 2008, at 2:41 PM, Gilles Ganault wrote: > Hi > > I'd like to rewrite a Web 2.0 PHP application in Python with AJAX, and > it seems like Django and Turbogears are the frameworks that have the > most momentum. I don't have any practical experience with these, but I've done some research. My impression is that Pylons has more momentum than TG. The latter project has declared the 1.x branch to be a dead end, and they're working on a 2.0 branch that's not out yet. I could be wrong, but that's what I gathered from my reading. > I'm concerned, though, that these frameworks they may be too specific > to the tasks they were originally developped for (news articles, > AFAIK). From the reading I did, I gathered that Django was really good if you want to do what Django is good at, but not as easy to customize as, say, Pylons. Pylons, on the other hand, is a little more complicated because it's made of several different parts, but the positive side of "complicated" is "flexible". > Do you think I should just use eg. CherryPy and some basic AJAX? Yes or no, depending on what you're trying to do! =) Good luck Philip From clp at rebertia.com Fri Dec 12 07:11:30 2008 From: clp at rebertia.com (Chris Rebert) Date: Fri, 12 Dec 2008 04:11:30 -0800 Subject: (Very Newbie) Problems defining a variable In-Reply-To: References: Message-ID: <47c890dc0812120411n1c9c4557pd2b3a2c2158c1d8c@mail.gmail.com> On Fri, Dec 12, 2008 at 3:42 AM, wrote: > #!/usr/bin/python > #Py3k, UTF-8 > > > #determine the interest rate to use > if bank >= 9999: > rate = 0.006 > elif bank >= 10000 and bank <= 24999: > rate = 0.0085 > elif bank >= 25000 and bank <= 49999: > rate = 0.0124 > elif bank >= 50000 and bank <= 99999: > rate = 0.0149 > elif bank >= 100000: > rate = 0.0173 For the love of Benji, reverse the ordering of the clauses so you don't have to keep checking whether the number is also under the next limit! (I'm assuming Bruno's guess about your first test having the operator flipped around the wrong way was right) if bank >= 100000: rate = 0.0173 elif bank >= 50000: rate = 0.0149 elif bank >= 25000: rate = 0.0124 elif bank >= 10000: rate = 0.0085 else: rate = 0.006 Note how much simpler that is to read and understand. And switching the default case to the 'else' is just idiomatic. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From gagsl-py2 at yahoo.com.ar Fri Dec 26 14:00:20 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 26 Dec 2008 17:00:20 -0200 Subject: =?utf-8?Q?Can=C2=B4t_Surf_Python_Pages_in_W?= =?utf-8?Q?indoze?= References: <4dc0cfea0812260701q6baf0ccbj154c5b3fa2281cdb@mail.gmail.com> <4954FB9F.5050702@wildenhain.de> <4dc0cfea0812260911k4dbc0f2ame9cc874e067b7816@mail.gmail.com> Message-ID: En Fri, 26 Dec 2008 15:11:44 -0200, Victor Subervi escribi?: > On 12/26/08, Tino Wildenhain wrote: >>> print "Content-Type: text/html" >>> print >>> print """ >>> >> http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> I think there should be only one blank line between header and content, you have two (so the document contains an empty line before the doctype declaration, and I think this is invalid). >>> >>> >>> >>> >>> Yeah >>> >>> """ The title tag (in head) is mandatory (although this should not prevent it from working) >> this could be fine if called in CGI context. > > Can you state clearly what "CGI context" means? Tino W. surely meant to say: - if you have a web server running - and it is capable of handle CGI scripts - and you have configured it to handle CGI scripts - and you have configured it to run the code above as a CGI script in response to certain request - and you pointed your browser to the right server, at the right port, at the right url - then, the code above should run and you should get a nice HTML page with the word Yeah in it. > Should I be importing a CGI > module? I pulled this code from a page that was working. If it had an > importation of something CGI, I believe I would have tested that with all > the other things that were imported that I tested, but perhaps not. I am > not > at my home computer to test, and will not be back online for a week. No, the code above doesn't require other modules to run. > I am not worried about Zope now, but the above code, yes. You're talking about two totally separate projects, I presume. The above code should not be used with Zope. -- Gabriel Genellina From Russ.Paielli at gmail.com Sat Dec 6 10:12:15 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 6 Dec 2008 07:12:15 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> Message-ID: On Dec 6, 1:02?am, Antoine De Groote wrote: > Allowing "$" as a substitute for "self" wouldn't require this new syntax. > > class C: > ? ? def method($, arg): > ? ? ? ? $.value = arg > > I'm strongly against this. This looks ugly and reminds me of Perl and > Ruby. (I don't have anything against these languages, but there's a > reason I use Python). > > Russ P. wrote: > > On Dec 5, 6:21 pm, "Daniel Fetchinson" > > wrote: > >> Hi folks, > > >> The story of the explicit self in method definitions has been > >> discussed to death and we all know it will stay. However, Guido > >> himself acknowledged that an alternative syntax makes perfect sense > >> and having both (old and new) in a future version of python is a > >> possibility since it maintains backward compatibility. The alternative > >> syntax will be syntactic sugar for the old one. This blog post of his > >> is what I'm talking about: > > >>http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... > > >> The proposal is to allow this: > > >> class C: > >> ? ? def self.method( arg ): > >> ? ? ? ? self.value = arg > >> ? ? ? ? return self.value > > >> instead of this: > > >> class C: > >> ? ? def method( self, arg ): > >> ? ? ? ? self.value = arg > >> ? ? ? ? return self.value > > >> I.e. explicit self stays only the syntax is slightly different and may > >> seem attractive to some. As pointed out by Guido classmethods would > >> work similarly: > > >> class C: > >> ? ? @classmethod > >> ? ? def cls.method( arg ): > >> ? ? ? ? cls.val = arg > >> ? ? ? ? return cls.val > > >> The fact that Guido says, > > >> "Now, I'm not saying that I like this better than the status quo. But > >> I like it a lot better than [...] but it has the great advantage that > >> it is backward compatible, and can be evolved into a PEP with a > >> reference implementation without too much effort." > > >> shows that the proposal is viable. > > >> I'd like this new way of defining methods, what do you guys think? > >> Anyone ready for writing a PEP? > > >> Cheers, > >> Daniel > > >> -- > >> Psss, psss, put it down! -http://www.cafepress.com/putitdown > > > I like it. > > > I'll even go a step further and suggest that "$" be allowed as a > > substitute for "self". It looks like a capital "S" (for Self), and it > > stands out clearly. It also makes code more succinct with no loss of > > readability. Think of the line wraps that could be avoided. > > It looks "ugly" simply because it is new to you. Once you get used to it, I'll bet it will look fine. And resemblance to another language is not a very good reason to reject it. From kay.schluehr at gmx.net Thu Dec 18 01:11:19 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Wed, 17 Dec 2008 22:11:19 -0800 (PST) Subject: Relative imports in Python 3.0 References: Message-ID: <6b46d826-6ff7-40ca-91a9-003cf3038962@u18g2000pro.googlegroups.com> On 17 Dez., 11:01, Nicholas wrote: > I am sure I am not the first to run into this issue, but what is the > solution? When you use 2to3 just uncomment or delete the file fix_import.py in lib2to3/fixes/ . From google at mrabarnett.plus.com Fri Dec 19 21:53:16 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 20 Dec 2008 02:53:16 +0000 Subject: Namespaces, multiple assignments, and exec() In-Reply-To: References: <200812200234.33852.research@johnohagan.com> Message-ID: <494C5E1C.7060205@mrabarnett.plus.com> Terry Reedy wrote: > John O'Hagan wrote: >> I have a lot of repetitive assignments to make, within a generator, >> that use a function outside the generator: >> >> var1 = func("var1", args) >> var2 = func("var2", args) >> var3 = func("var3", args) >> etc... >> >> In each case the args are identical, but the first argument is a >> string of the name being assigned. It works fine but I'd like to >> reduce the clutter by doing the assignments in a loop. I've tried >> using exec(): >> >> for name in name_string_list: >> exec(name + ' = func(\"' + name + '\", args)') >> >> but in the local namespace it doesn't understand func(), and if I give >> it globals() it doesn't understand the args, which come from within >> the generator. >> >> What's a good way to do this kind of thing? > > Put everything in your own namespace > > myvars={} > for name in namelist: > myvars[name]=func(name,args) > If you're sure you want to use the current namespace then: for name in namelist: vars()[name] = func(name, args) From jeremy+complangpython at jeremysanders.net Wed Dec 17 09:21:38 2008 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Wed, 17 Dec 2008 14:21:38 +0000 Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> Message-ID: Aaron Brady wrote: > I thought so too. The web seems to say that on Linux they are, and on > Windows, you need to call DuplicateHandle for it. I hit this problem - it looks like pipes aren't very versatile on Windows. There's also the complicating factor that the handles in windows aren't the same as the file numbers that Python uses, so you have to convert between them. It would be nice if Python created pipes that are properly inheritable by default by child processes, as they're mostly used for IPC. It was so painful that I converted my code to use sockets instead, which seem much more portable between Windows and Unix (though you don't get to use socketpair and AF_UNIX in Windows). Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From mal at egenix.com Thu Dec 4 05:22:34 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 04 Dec 2008 11:22:34 +0100 Subject: "as" keyword woes In-Reply-To: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> Message-ID: <4937AF6A.8030007@egenix.com> On 2008-12-04 06:42, Warren DeLano wrote: >>> Why can't the parser distinguish between a standalone " as " keyword >>> and ".as" used as an object/attribute reference? >> Because that would require special-casing some names as being >> forbidden in syntax where other names are allowed. Special cases in >> language syntax are to be avoided where feasible. > > Am I the only one picking up on the irony here? "as" exists largely to > provide a mechanism for working around namespace conflicts -- except, > apparently, conflicts involving "as". The fact that "as" itself creates > an insurmountable namespace collision is just killing me! How absurd. Up until "as" has been special for many Python releases, ever since we introduced the "from xyz import abc as def" notation, so there's nothing new there. Now, instead of keeping that special status, it was decided to make it a reserved word since there's a new use case in Python 2.6 for it as well - catching exceptions: >>> try: ... 1/0 ... except Exception as exc_object: ... print exc_object ... integer division or modulo by zero The Python developers always try very hard not to introduce new keywords to the language, but every now and then, it's better to go with the addition and cause some breakage. In this case, it's easy enough to find the files that break. Just run compileall.py on all your files and Python 2.6 will tell you which ones need fixing: python2.6 -c 'import compileall;compileall.compile_dir(".")' > Anyway, it seems obvious that the right decision for our customers (or > more importantly, for their countless lines of autogenerated-Python log, > state, and code files from the past decade) is to stick with C/Python > 2.5.x for the time being and plan to make the jump to a threads-capable > and hopefully backwards-compatible Python implementation as soon as > possible (IronPython perhaps?). That seems like a sensible path around > the breakage and enduring limitations of C/Python 2.6 or 3. This idea of CPython not being threads-capable is FUD. CPython works perfectly well in multi-threaded environments. There are, of course, situations where using a multi-threaded approach is not necessarily the right way to approach a problem. For those you now have the multiprocessing module which allows creating and managing multiple processes to spread the load: http://docs.python.org/library/multiprocessing.html This also avoids many of the problems you face with multi-threading, e.g. managing low-level object access using thread locks, dealing with non-thread-aware code, finding all the instances of objects that would require thread-lock-managed access, etc. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 04 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-12-02: Released mxODBC.Connect 1.0.0 http://python.egenix.com/ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From ylj798 at gmail.com Tue Dec 2 14:31:33 2008 From: ylj798 at gmail.com (ylj798 at gmail.com) Date: Tue, 2 Dec 2008 11:31:33 -0800 (PST) Subject: help me~!about base64 References: <0ff1ba7b-8a17-4647-99fc-9c8e32f83de7@g1g2000pra.googlegroups.com> Message-ID: <30641a03-51ee-456a-9c1a-1aba4e82d023@z6g2000pre.googlegroups.com> On 12?3?, ??3?26?, "Jerry Hill" wrote: > On Tue, Dec 2, 2008 at 2:08 PM, wrote: > >>>>print base64.__file__ > > /usr/lib/python2.5/base64.pyc > > That looks fine, and matches what I have on my linux box. Your code > works fine for me when I run it, so I'm out of ideas. > > -- > Jerry Thanks~! My system is ubuntu8.04 python2.5 eric4,you don't know that what about error? From petite.abeille at gmail.com Tue Dec 2 15:39:57 2008 From: petite.abeille at gmail.com (Petite Abeille) Date: Tue, 2 Dec 2008 21:39:57 +0100 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: <1B1C50D7-13B3-4E4C-A87F-F4EB4D9C508C@gmail.com> On Dec 2, 2008, at 9:21 PM, Lew wrote: > These are professional software development forums, not some script- > kiddie cellphone-based chat room. "r" is spelled "are" and "u" should > be "you". While Xah Lee arguably represents a cross between "Enfant Provocateur" [1] and "Evil Clown" [2], this surely qualifies as a "Grammarian" [3] rebuke :D Cheers, -- PA. http://alt.textdrive.com/nanoki/ [1] http://redwing.hutman.net/~mreed/warriorshtm/enfantprovocateur.htm [2] http://redwing.hutman.net/~mreed/warriorshtm/evilclown.htm [3] http://redwing.hutman.net/~mreed/warriorshtm/grammarian.htm From Ron.Barak at lsi.com Sun Dec 21 06:41:42 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Sun, 21 Dec 2008 11:41:42 +0000 Subject: Best Practice using Glade/Python (ericericaro: message 1 of 20) In-Reply-To: <8ede3ba80812180547i3f48b032o6f7d0adab778c350@mail.gmail.com> References: <1b63220b-1572-4a8f-8f43-474ef8194bb0@s1g2000prg.googlegroups.com> <7F0503CD69378F49BE0DC30661C6CCF60249434B@enbmail01.lsi.com> <8ede3ba80812180547i3f48b032o6f7d0adab778c350@mail.gmail.com> Message-ID: <7F0503CD69378F49BE0DC30661C6CCF602494471@enbmail01.lsi.com> Hi Eric, Once the UI is defined, you interface to events as usual, e.g.: def OnSelChanged(self, evt): self.tablecont = str(self.GetItemText(evt.GetItem())) self.dprint(line()+". OnSelChanged:", self.tablecont) self.TreeViewController(self.tablecont) self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, self.tree) Bye, Ron. P.S.: I think you'd get better responses if you asked this question on wxpython-users at lists.wxwidgets.org ________________________________ From: Eric Atienza - eric at ericaro.net [mailto:+ericericaro+comverse+2e4452f01c.eric#ericaro.net at spamgourmet.com] Sent: Thursday, December 18, 2008 15:47 To: ericericaro.comverse at 9ox.net Subject: Re: Best Practice using Glade/Python (ericericaro: message 1 of 20) Hi, thank for the response (but it ain't in the usenet). I'm looking for best pratices about connecting 'events' from a glade defined UI, and python code. How to you manage it ? Eric http://codeslash.blogspot.com On Thu, Dec 18, 2008 at 2:25 PM, > wrote: Hi Eric, I'm not sure if I answer your question, but I designed wxPython GUI with wxGlade (http://wiki.wxpython.org/wxGlade). Bye, Ron. -----Original Message----- From: eric [mailto:eric at ericaro.net] Sent: Thursday, December 18, 2008 12:39 To: python-list at python.org Subject: Best Practice using Glade/Python Hi, I was wondering which is the "best practice" using glade/python, and, of course, especially the connect (both side). I didn't found that much documentation on the net ( too noisy), and the best "thing" I've found was http://www.linuxjournal.com/article/7558 which is a bit old now (2004). The article is very interesting BTW, but I was concerned by the fact it might be a little outdated. It smells like I'm missing something here, and that there have been a clean way to connect both (the autoconnect stuff does not seem that clean to me) for a long time now. So here is the question, do you practive galde/python, which is your practice ? Thanks Eric http://codeslash.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp at rebertia.com Sat Dec 27 14:33:40 2008 From: clp at rebertia.com (Chris Rebert) Date: Sat, 27 Dec 2008 11:33:40 -0800 Subject: parsing csv files class In-Reply-To: <49562755.6050205@byoteki.com> References: <49562755.6050205@byoteki.com> Message-ID: <47c890dc0812271133ia4471fav96d748d4c4a52fda@mail.gmail.com> On Sat, Dec 27, 2008 at 5:02 AM, Gary M. Josack wrote: > alex goretoy wrote: >> >> I know it's messy with all those self.soc.* functions, but it works in one >> of my current project. I just want to make it more pythonic I also want to >> add capability for makeing csv file if I give it input like: >> 1234,something nice, hey this is something nice >> 2468,something else, something else >> >> On Sat, Dec 27, 2008 at 4:54 AM, alex goretoy > > wrote: >> >> Hello All, >> >> I have this class that I use in one of my projects. I know it's >> missing functionality and some things could have been done >> differently. Can you ehlp me make this class better? What can I do >> to make it more resistant to error? You can find the >> stdout_colours class on Google if you want it, JFGI I want to make >> it more pythonic. I come from a PHP background, can you tell? >> >> Any and all help is appreciated >> -Alex >> >> #!/usr/bin/env python >> from ctypes import * >> import os, sys, types, csv, urllib, urllib2, urlparse, >> string,stdout_colours >> >> class parsercsvy(object): >> """Return a line from a csv file or total amount of lines""" > Do you know that there is a csv module in the standard library already? > > Thanks, > Gary M. Josack And here's a link to the docs for the `csv` module: http://docs.python.org/library/csv.html Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From grante at visi.com Mon Dec 22 23:35:42 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 22 Dec 2008 22:35:42 -0600 Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <18767.47566.709705.92@montanaro-dyndns-org.local> Message-ID: <5uudnUmykoMD983UnZ2dnUVZ_rrinZ2d@posted.usinternet> On 2008-12-22, Joe Strout wrote: > Alvin ONeal wrote: > >> Also worthy of mention: >> I've seen python pre-installed on consumer HP desktops (I think as >> part of a backup/restore script, but I'm not sure) > > It's pre-installed on every Mac (both desktop and laptop), too. IIRC, Python came pre-installed on my IBM Thinkpad. However, it wasn't anyplace the average user would stumble across it... -- Grant From cwitts at gmail.com Tue Dec 2 07:09:44 2008 From: cwitts at gmail.com (Chris) Date: Tue, 2 Dec 2008 04:09:44 -0800 (PST) Subject: Checking a string against multiple matches References: <99a3a677-a38d-40f5-9a94-a98865150b69@k19g2000yqg.googlegroups.com> <200af09b-adba-4d8f-9ed9-2343030f9718@i24g2000prf.googlegroups.com> Message-ID: <376e669e-20b8-4734-a01e-e7a739362f8a@d23g2000yqc.googlegroups.com> On Dec 2, 3:01?am, alex23 wrote: > On Dec 2, 5:31?am, Aaron Scott wrote: > > > I was using .index on the > > list, but it would return True for strings that contained the search > > string rather than match it exactly, leading to false positives in my > > code. > > Are you sure? That doesn't seem like standard behaviour. > > >>> l = ["one", "two", "three", "four"] > >>> l.index('on') > > Traceback (most recent call last): > ? File "", line 1, in > ValueError: list.index(x): x not in list>>> l.index('thre') > > Traceback (most recent call last): > ? File "", line 1, in > ValueError: list.index(x): x not in list > > The only time I'd expect it to do partial matches is if you were doing > string.index(string), rather than list.index(string): > > >>> "four".index('our') > > 1 It would if the OP was iterating over the list and checking that item with .index so it uses the string.index instead of list.index From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 29 05:13:42 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 29 Dec 2008 11:13:42 +0100 Subject: Any equivalent to Ruby's 'hpricot' html/xpath/css selector package? In-Reply-To: References: Message-ID: <4958a2d7$0$15461$426a74cc@news.free.fr> Kenneth McDonald a ?crit : > Ruby has a package called 'hpricot' which can perform limited xpath > queries, ElementTree ? (it's in the stdlib now) > and CSS selector queries. PyQuery ? http://pypi.python.org/pypi/pyquery > However, what makes it really useful > is that it does a good job of handling the "broken" html that is so > commonly found on the web. BeautifulSoup ? http://pypi.python.org/pypi/BeautifulSoup/3.0.7a possibly with ElementSoup ? http://pypi.python.org/pypi/ElementSoup/rev452 From steve at REMOVE-THIS-cybersource.com.au Sun Dec 7 18:43:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 23:43:41 GMT Subject: how to get a beep, OS independent ? References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> Message-ID: <014c575a$0$20670$c3e8da3@news.astraweb.com> On Sun, 07 Dec 2008 12:56:14 -0700, Joe Strout wrote: > On Dec 7, 2008, at 8:48 AM, Grant Edwards wrote: > >> On 2008-12-07, Joe Strout wrote: >> >>> But invoking the standard system beep >> >> What makes you think there is such a thing as "the standard system >> beep"? > > Because OS X (the platform with which I'm most familiar) certainly has > one, OS X, isn't that the operating system owned by Apple that runs on a handful of more-or-less identical varieties of hardware all controlled by Apple? > and REALbasic has had a "Beep" method for years which works on all > platforms. If RB can do it, we can do it too. That would be a standard language beep then, not a standard system beep. You're assuming that there is a standard way for any computer to make a sound. I don't think that is true. Of course, if you're volunteering to write such a standard system beep for Python, I for one would be grateful. -- Steven From wuwei23 at gmail.com Sat Dec 6 08:25:16 2008 From: wuwei23 at gmail.com (alex23) Date: Sat, 6 Dec 2008 05:25:16 -0800 (PST) Subject: To Troll or Not To Troll (aka: "as" keyword woes) References: <20081205163107.1815df40@usenot.de> <27945697-3f2f-452d-bed4-d1ca45d46fbb@r10g2000prf.googlegroups.com> <0149f5d8$0$20670$c3e8da3@news.astraweb.com> Message-ID: <6450388b-7181-43ba-b7ec-8cfe810f8ad4@r15g2000prd.googlegroups.com> On Dec 6, 2:22?pm, Steven D'Aprano wrote: > I see your wink, but, please, did you read that thread started by "r" > about the Ruby API for some piece of Google software? That was so > offensively fanboyish that I almost removed Python from my computer. The one wjere I was accused of wanting to hold back the evolution of Python amongst suggestions that I needed to get laid? Oh yeah, I saw it... I'm also not convinced it wasn't faux advocacy for the sake of trolling. From roy at panix.com Thu Dec 25 22:05:43 2008 From: roy at panix.com (Roy Smith) Date: Thu, 25 Dec 2008 22:05:43 -0500 Subject: How to stop subprocesses from copying listening sockets References: Message-ID: In article , Rick van Hattem wrote: > Recently I've started building a program that spawns new processes when > requested via http, since the http interface doesn't need to be fancy I've > just used the BaseHTTPServer module for this, but... it seems I'm running > into a little problem. When spawning a new process (which forks itself into a > daemon, but isn't too relevant in this case) the listening socket is copied > to the new process. The standard solution to this problem is to close all descriptors after forking and before doing the exec. You can tell subprocess.Popen() to do this by call it with "close_fds=True". From jason.scheirer at gmail.com Tue Dec 16 19:52:14 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Tue, 16 Dec 2008 16:52:14 -0800 (PST) Subject: WinMerge--B/W Shading of Printed Copy to Show Differences? References: <3jX1l.6876$pr6.3299@flpi149.ffdc.sbc.com> Message-ID: On Dec 16, 3:56?pm, "W. eWatson" wrote: > Is there a way to highlight differences between the two files when printing > in b/w? Help suggests there may be some texturing, but all I see is color > choices. > -- > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? W. eWatson > > ? ? ? ? ? ? ? (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > ? ? ? ? ? ? ? ?Obz Site: ?39? 15' 7" N, 121? 2' 32" W, 2700 feet > > ? ? ? ? ? ? ? ? ? ? ?Web Page: WinMerge is written in C++ and not even remotely related to Python. From google at mrabarnett.plus.com Thu Dec 4 15:30:29 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 04 Dec 2008 20:30:29 +0000 Subject: schizophrenic view of what is white space In-Reply-To: References: <4937E8E5.2090306@chamonix.reportlab.co.uk> <20081204143337.20272.1236189783.divmod.quotient.15592@ohm> <4938112F.5030706@chamonix.reportlab.co.uk> <49381C2E.3060707@mrabarnett.plus.com> Message-ID: <49383DE5.3030703@mrabarnett.plus.com> Terry Reedy wrote: > MRAB wrote: >> Robin Becker wrote: >>> Jean-Paul Calderone wrote: >>> ......... >>>> >>>> You have to give the re module an additional hint that you care about >>>> unicode: >>>> >>>> exarkun at charm:~$ python >>>> Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 >>>> (Ubuntu 4.2.3-2ubuntu7)] on linux2 >>>> Type "help", "copyright", "credits" or "license" for more information. >>>> >>> import re >>>> >>> print re.compile(r'\s').search(u'a\xa0b') >>>> None >>>> >>> print re.compile(r'\s', re.U).search(u'a\xa0b') >>>> <_sre.SRE_Match object at 0xb7dbb3a0> >>>> >>> >>>> >>>> Jean-Paul >>> ....... >>> >>> so the default behaviour differs for unicode and re working on >>> unicode. I suppose that won't be true in Python 3. >> > >> I'm not sure why the Unicode flag is needed in the API. I reckon that >> it should just look at the text that the regular expression is being >> applied to: if it's Unicode then follow the Unicode rules, if not then >> don't. > > I presume because \b is interpreted and replaced when the re is compiled > into internal state machine form. > The regular expression is compiled to codes which are then interpreted. There are 2 versions of the matcher, one for bytestrings and another for Unicode. I don't think that having it agnostic is too difficult to achieve. Interestingly, it treats every bytestring character as just a Unicode codepoint, so re.match(chr(0x80), unichr(0x80)) succeeds! I suppose it should complain if only one of the regex and the text is Unicode and the regex contains a literal or a literal character set (if the regex is, say, just \w then it doesn't matter). From simonharrison.uk at googlemail.com Mon Dec 8 05:44:56 2008 From: simonharrison.uk at googlemail.com (simonharrison.uk at googlemail.com) Date: Mon, 8 Dec 2008 02:44:56 -0800 (PST) Subject: Determining whether a variable is less/greater than a range. Message-ID: <362ab93b-b804-4ebe-a22f-e422feb301c8@c1g2000yqg.googlegroups.com> Hi. I'm having another go at learning Python so I'll probably be asking a few basic questions. Here is the first one. a = list(range(10, 21) b = 9 c = 21 How can I find out if b and c have values less or more than the values in list a? Thanks. From onlinejob4ind at gmail.com Thu Dec 25 03:43:17 2008 From: onlinejob4ind at gmail.com (kela) Date: Thu, 25 Dec 2008 00:43:17 -0800 (PST) Subject: Funny Christmas wallpapers, theme Message-ID: <315e8244-2e84-4a69-adce-0e5f36164cdd@r36g2000prf.googlegroups.com> Funny Christmas wallpapers, theme Free Funny Christmas Wallpaper Software Downloads Free Watch Software - StarBurn, Animated Funny Santa Clock Funny Christmas videos / Crazy Christmas Kick - Watch Santa Claus! http://funny-christmas-wallpaperws.blogspot.com/ From rschroev_nospam_ml at fastmail.fm Tue Dec 30 04:10:49 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue, 30 Dec 2008 10:10:49 +0100 Subject: get method In-Reply-To: References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> Message-ID: James Mills schreef: > Ross, the others have informed you that you are not > actually incrementing the count. I'll assume you've > fixed your function now :) ... I want to show you a far > simpler way to do this which takes advantage of > Python's list comprehensions and mappings (which are > really what dictionaries are): > >>>> s = "James Mills and Danielle Van Sprang" >>>> dict([(k, len([x for x in s if x == k])) for k in s]) > {'a': 5, ' ': 5, 'e': 3, 'd': 1, 'g': 1, 'i': 2, 'M': 1, 'J': 1, 'm': > 1, 'l': 4, 'n': 4, 'p': 1, 's': 2, 'r': 1, 'V': 1, 'S': 1, 'D': 1} Hm, you just changed an O(n) algorithm to an O(n**2) algorithm. No big deal for short strings, but try your solution on a string with length 10000 and see the difference. On my computer the O(n) version takes 0.008 seconds, while your version takes 8.6 seconds. That's 1000 times slower. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From nkanthikiran at gmail.com Sun Dec 7 08:58:45 2008 From: nkanthikiran at gmail.com (k.i.n.g.) Date: Sun, 7 Dec 2008 05:58:45 -0800 (PST) Subject: How to Write to csv file to create bulk address book Message-ID: <5387c7a1-eb04-4d27-826c-d6257298e2db@f40g2000pri.googlegroups.com> Hi , I am new to scripting, I am working on script which would create 'n' number address book entries into a csv file which would be used to import into a address book. I need suggestions for the same The fileds for csv file are as follows ""Title","First Name","Middle Name","Last Name","Suffix","Company","Department","Job Title","Business Street","Business Street 2","Business Street 3","Business City","Business State","Business Postal Code","Business Country","Home Street","Home Street 2","Home Street 3","Home City","Home State","Home Postal Code","Home Country","Other Street","Other Street 2","Other Street 3","Other City","Other State","Other Postal Code","Other Country","Assistant's Phone","Business Fax","Business Phone","Business Phone 2","Callback","Car Phone","Company Main Phone","Home Fax","Home Phone","Home Phone 2","ISDN","Mobile Phone","Other Fax","Other Phone","Pager","Primary Phone","Radio Phone","TTY/TDD Phone","Telex","Account","Anniversary","Assistant's Name","Billing Information","Birthday","Business Address PO Box","Categories","Children","Directory Server","E-mail Address","E- mail Type","E-mail Display Name","E-mail 2 Address","E-mail 2 Type","E- mail 2 Display Name","E-mail 3 Address","E-mail 3 Type","E-mail 3 Display Name","Gender","Government ID Number","Hobby","Home Address PO Box","Initials","Internet Free Busy","Keywords","Language","Location","Manager's Name","Mileage","Notes","Office Location","Organizational ID Number","Other Address PO Box","Priority","Private","Profession","Referred By","Sensitivity","Spouse","User 1","User 2","User 3","User 4","Web Page"" All the entries written by csv file by script can be random & dummy as this address book is used for testing purpose. Thank you in advance, Kanthi From gdamjan at gmail.com Sat Dec 13 23:01:58 2008 From: gdamjan at gmail.com (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Sun, 14 Dec 2008 05:01:58 +0100 Subject: File names, character sets and Unicode References: <49423DBB.9090401@logix.net.nz> Message-ID: > In a nutshell, this is likely to cause pain until all file systems are > standardized on a particular encoding of Unicode. Probably only about > another fifteen years to go ... well, most Linux distros are defaulting to a UTF-8 locale now, the exception beeing Gentoo&similar that expect the user to know what to configure - which he often doesn't :) but, yes, there's no way of enforcing that. -- ?????? ( http://softver.org.mk/damjan/ ) ... knowledge is exactly like power - something to be distributed as widely as humanly possible, for the betterment of all. -- jd From fetchinson at googlemail.com Wed Dec 24 23:31:44 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 24 Dec 2008 20:31:44 -0800 Subject: Easy-to-use Python GUI In-Reply-To: References: Message-ID: > Is there an easy-to-use, "function"-based cross-platform GUI toolkit for > Python out there that's a little more sophisticated than EasyGui? EasyGui > looks good, but it's a little more restrictive than what I'd like to have, > yet > I'm (stubbornly :-) ) resistant to stepping up to a "full service" GUI > toolkit > such as pyGTK or wxPython where it's all about event loops and callbacks and > you need to start planning how the GUI affects the overall program flow > rather > than just using a "forms" (or "Wizard")-type approach where you put up a few > dialogs, users fill in some variables, and your program just sits around > waiting until "OK" or "Cancel" is clicked. > > One approach that I like comes from SAX BASIC/WinWrap, which is more or less > a > clone of Microsoft's Visual BASIC for Applications, but they (apparently) > wanted everything to still be human-readable, so they have a simple GUI > ("form") builder that generates code that looks like this: > > --- > > Begin Dialog UserDialog 850,497,"Export Control" ' %GRID:10,7,1,1 > > GroupBox 20,7,360,217,"Drill File Generation",.GroupBox1 > CheckBox 40,35,130,14,"Output drill file(s)",.genDrill > Text 40,63,270,28,"Identify via layers as any that contain this text in > their names:",.Text > TextBox 40,98,220,21,.viaLayerName > Text 40,140,100,14,"Output method:",.Text8 > DropListBox 160,140,180,21,DrillStyle(),.drillStyle > Text 40,175,130,28,"Select drill table units:",.Text2 > ListBox 200,175,120,28,unitNames(),.unitName > > OKButton 310,469,90,21 > CancelButton 410,469,90,21 > > End Dialog > > ' GUI builder generates or modifies everything above, but can also be edited > by hand > ' You write the following code... > > Dim dlg As UserDialog > > dlg.genDrill = 1 > ReDim DrillStyle(1) > DrillStyle(0) = "All Via Layers In One File" > DrillStyle(1) = "One File Per Via Layer" > dlg.drillStyle = 1 > > func=Dialog(dlg) > > --- > > This is pretty darned easy for me understand and modify either by hand or > with > the GUI builder. Still, it's quite powerful, since it supports all the > common > GUI elements (text, group boxes, checkboxes, drop-down lists, text boxes, > buttons, etc.). This is about the level of sophistication I'm looking for. > > Anything like this for Python? How about the Tcl/Tk GUI that comes bundled with python? http://docs.python.org/library/tk.html Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From jstroud at mbi.ucla.edu Fri Dec 5 05:51:45 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 05 Dec 2008 02:51:45 -0800 Subject: dict subclass and pickle bug (?) In-Reply-To: References: Message-ID: <6J7_k.6212$hc1.5967@flpi150.ffdc.sbc.com> James Stroud wrote: > Hello All, > > I subclassed dict and overrode __setitem__. When instances are > unpickled, the __setstate__ is not called before the keys are assigned > via __setitem__ in the unpickling protocol. > > I googled a bit and found that this a bug filed in 2003: > > http://bugs.python.org/issue826897 > > It is still "open" with "normal" priority. Here is the ugly "fix" I'm basically going to have to live with, it seems: class DictPlus(dict): def __init__(self, *args, **kwargs): self.extra_thing = ExtraThingClass() dict.__init__(self, *args, **kwargs) def __setitem__(self, k, v): try: do_something_with(self.extra_thing, k, v) except AttributeError: self.extra_thing = ExtraThingClass() do_something_with(self.extra_thing, k, v) dict.__setitem__(self, k, v) def __setstate__(self, adict): pass This violates this: Beautiful is better than ugly. I can't imagine this bug has survived but I also can't imagine any better way to do this without specifying a different protocol, which would probably break other pickling I'm doing. I don't feel like finding out right now. Maybe repeal pep 307 ;o) James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From digitig at gmail.com Wed Dec 10 07:39:02 2008 From: digitig at gmail.com (Tim Rowe) Date: Wed, 10 Dec 2008 12:39:02 +0000 Subject: Don't you just love writing this sort of thing :) In-Reply-To: <493F028E.5050608@stoneleaf.us> References: <493F028E.5050608@stoneleaf.us> Message-ID: 2008/12/9 Ethan Furman : > Not all code has to be written for everyone. Not all code will be read by > the masses. Some code you write for yourself... an expression of who you > are, how you think... > > While my own quirks are not as visually entertaining, I think it's another > mark in Python's favor that such self-expression is possible, and > functional. > > Yes, Lawrence, I do love writing fun code. I did once get into a rivalry with a Perl programmer over obfusticating a coding exercise. I knew from the start that I had no chance, but I was impressed with how close-run I could make it with Python. Fun, yes, but no way anything I would consider for code that is actually going to be /used/ in any way whatsoever! -- Tim Rowe From martin at v.loewis.de Sat Dec 6 08:46:16 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 06 Dec 2008 14:46:16 +0100 Subject: Multiple Versions of Python on Windows XP In-Reply-To: References: <4934de22$0$27863$9b622d9e@news.freenet.de> <493592EE.9090005@v.loewis.de> <49378804.2050807@g.nevcal.com> <4937DB4B.7060001@ncf.ca> <4939C513.2090802@v.loewis.de> Message-ID: <493A8228.8010004@v.loewis.de> > SciTE doesn't do that, in the default configuration it just uses > whatever is called "pythonw" on the path, for running files having a .py > or .pyw suffix. I see. By default, Python does not put itself onto PATH. Does that mean that SciTE cannot run Python scripts in the default installation? Regards, Martin From lie.1296 at gmail.com Mon Dec 15 01:17:36 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 15 Dec 2008 06:17:36 +0000 (UTC) Subject: [OT] stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> Message-ID: On Mon, 15 Dec 2008 01:48:43 +0000, Steven D'Aprano wrote: > Some things really don't have a solution, no matter how much power of > positive thinking you apply to it. Some may, only not with the current understanding of the universe. Well, I agree that there are a few things that is straight out nonsense, such as 4-angled triangle. And actually you've got the wrong message from the story, I hadn't intend it to be about positive thinking (as most motivators would exploit), it's more about thinking outside the current popular frame of minds. When you're not bound by everyone around you that says a task is impossible, you might have a better chance to solve the task (well, as long as the task *is* possible). What follows is a not-so-funny joke. Q: Construct a 4-angled triangle. A: Hmmm.... let's see... What about this? /\ / \ /____\ Q: That's just a regular triangle A: How about this? _____ | | | | |_____| Q: That's just a regular rectangle. A: This? /|\ / | \ /__|__\ Q: Well, still no luck, it's a triangle, but it have 5 sides A: Well... (after thinking for a moment) How about this? /----\ / \ / \ / \ -----------------/ \-------\ ---------------------------------------- Q: Perfect, just like what I wanted, but you shouldn't let the Python eat it. -- Le Petit Prince & aptitude & me From fuzzyman at gmail.com Tue Dec 23 07:29:42 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Tue, 23 Dec 2008 04:29:42 -0800 (PST) Subject: On Whose Desktop References: Message-ID: <018b649a-bcc6-4d5f-a7f2-e86231c89e74@i18g2000prf.googlegroups.com> On Dec 23, 12:06?pm, Steve Holden wrote: > Thanks to Barry Warsaw the "On Your Desktop" blog now has a new entry: > > ?http://onyourdesktop.blogspot.com/ > > Who would you like to see profiled next? > > regards > ?Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ Guido (of course), Brett Cannon, Martin v Loewis, Jim Hugunin, Ted Leung, Dino Viehland (core developer of IronPython), Titus Brown, Ivan Kristic, Mark Shuttleworth, Tim Golden, Michele Simionato, Thomas Heller, Greg Ewing - any and all of these would be great. Any women in Python you could ask - how about Anna Ravenscroft? Conspicuously missing from the ones you have already done is Steve Holden of course... All the best, Michael Foord -- http://www.ironpythoninaction.com/ From michele.simionato at gmail.com Thu Dec 4 05:07:31 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 4 Dec 2008 02:07:31 -0800 (PST) Subject: Pythonic design patterns References: Message-ID: <9c181e7f-469e-4794-aed5-99fae77ee911@g38g2000yqd.googlegroups.com> On Dec 4, 11:00?am, James Stroud wrote: > > The cookbook has a lot of complex examples and may not provide you with > the insight you are looking for. Only a small fraction of the recipes do > this. Whereas I agree that the online cookbook has too many complex recipes, as far I can remember most recipes in the printed version were quite generic and worth to study. Another good book I did not mention before is "Dive into Python" by Mark Pilgrim which is also available on line (Google is your friend). From stefan_ml at behnel.de Fri Dec 5 03:59:19 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 05 Dec 2008 09:59:19 +0100 Subject: Python C API In-Reply-To: <54fbb55d-3c39-459d-86a3-302b69721f0f@s20g2000yqh.googlegroups.com> References: <54fbb55d-3c39-459d-86a3-302b69721f0f@s20g2000yqh.googlegroups.com> Message-ID: <4938ed67$0$30227$9b4e6d93@newsspool1.arcor-online.net> googler.1.webmaster at spamgourmet.com wrote: > The first question is, I found out the API contains other commands lik > PyEval_AcquireLock(). I don't really understand if I have to use them > too, could anyone explain? Thanks. That's unrelated. The GIL is special in that it has its own handling functions. > void MyProgressbar(Real p, void* hook) // this function wil be called > in another thread > { > PyGILState_STATE gilstate = PyGILState_Ensure(); > > PyObject* func = (PyObject*)hook; > //do some python stuff > > PyGILState_Release(gilstate) > } > > PyObject *pyMyFunction(PyObject *pSelf, PyObject *args, PyObject > *keywords) > { > static char *kwlist[] = {"hook", NULL}; > > PyObject *hook=NULL; > > if (!PyArg_ParseTupleAndKeywords(args, keywords, "O!", kwlist, > &PyFunction_Type, &hook)) > return NULL; You have to release the GIL around the following function call, so that the thread above can acuire it while you wait for the function to return in this thread here (which I assume you do). > LONG ok = MyFunction(myprogress, hook); //hook is a pointer which > is passed to the threaded function. Stefan From atagar1 at gmail.com Sun Dec 28 18:06:18 2008 From: atagar1 at gmail.com (Damian Johnson) Date: Sun, 28 Dec 2008 15:06:18 -0800 Subject: Python 3.0 Curses Unicode Message-ID: Hi, I've switched to Python 3.0 for a new Japanese vocab quizzing application due to its much improved Unicode support. However, I'm running into an issue with displaying Unicode characters via curses. In Python 2.x a simple hello-world looks like: #!/usr/bin/python # coding=UTF-8 import curses import locale locale.setlocale(locale.LC_ALL,"") def doStuff(stdscr): message = u"hello ???!" stdscr.addstr(0, 0, message.encode("utf-8"), curses.A_BLINK) stdscr.getch() # pauses until a key's hit curses.wrapper(doStuff) This works. However, when I try to come up with an equivalent for Python 3.0: #!/usr/bin/python import curses import locale locale.setlocale(locale.LC_ALL,"") def doStuff(stdscr): message = "hello ???!" stdscr.addstr(0, 0, message, curses.A_BLINK) stdscr.getch() # pauses until a key's hit curses.wrapper(doStuff) It fails (printing gibberish to the console). Anyone have a clue what I'm doing wrong? Thanks! -Damian PS. Is the "# coding=UTF-8" header meaningless in Python 3.0? Also, is "locale.setlocale(locale.LC_ALL,"")" still necessary for getting curses to provide Unicode support? -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Tue Dec 30 15:41:17 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 30 Dec 2008 14:41:17 -0600 Subject: select.select and socket.setblocking References: <495a661d$0$11384$5fc30a8@news.tiscali.it> Message-ID: On 2008-12-30, Francesco Bochicchio wrote: > 3. AFAIK (sorry, I feel acronym-ly today ;), there is no difference in > select between blocking and non-blocking mode. The difference is in the > recv (again, assuming that you use TCP as protocol, that is AF_INET, > SOCK_STREAM), which in the blocking case would wait to receive all the > bytes that you requested, No, in blocking mode it will wait to receive _some_ data (1 or more bytes). The "requested" amount is strictly an upper limit: recv won't return more than the requested number of bytes, but it might return less. In non-blocking mode, it will always return immediately, either with some data, no data (other end closed), or an EAGAIN or EWOULDBLOCK error (I forget which). > [...] I myself tend to avoid using non-blocking sockets, since > blocking sockets are much easier to handle... That depends on whether you can tolerate blocking or not. In an event-loop, blocking is generally not allowed. -- Grant From skip at pobox.com Mon Dec 1 13:06:02 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 1 Dec 2008 12:06:02 -0600 Subject: optimization In-Reply-To: References: Message-ID: <18740.10122.833580.878015@montanaro-dyndns-org.local> Neal> I noticed in some profiling, that it seems that: Neal> def Func (): Neal> def something(): Neal> ... Neal> It appears that if Func is called many times, this nested func Neal> definition will cause significant overhead. Is this true? I Neal> guess I've become accustomed to decent compilers performing Neal> reasonable transformations and so have tended to write code for Neal> clarity. It could. OTOH, the code object which implements the something body is stored as a local var (or a constant, can't remember off the top of my head), so it's not compiled over and over again. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From python.list at tim.thechases.com Tue Dec 2 16:45:58 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 02 Dec 2008 15:45:58 -0600 Subject: Simple ini Config parser examples needed In-Reply-To: References: Message-ID: <4935AC96.4050402@tim.thechases.com> > I have a very simple ini file that I needs parsed. What is the best way I can parse an ini file that doesn't include sections? > > As in: > > person=tall > height=small > shoes=big > > > Thats it. Can anyone help me? The built-in ConfigParser module assumes at least one INI-style section, which if it's not present, issues a raise MissingSectionHeaderError As such, if you don't have any headers, you may have to hand-parse. However, that's not too bad: from sys import stderr options = {} for i, line in enumerate(file("simple.ini")): line = line.rstrip("\r\n").lstrip() if not line or line.startswith(';') or line.startswith('#'): continue # it's blank or a commented line if '=' in line: name, value = line.split('=', 1) options[name.rstrip().lower()] = value.strip() else: stderr.write("Malformed option at line #%i\n" % (i+1)) person = options.get("person", "some default person value") socks = options.get("socks", "some default sock value") do_something(person, socks) Adjust the strip() calls if you want to preserve odd white-spacing. -tkc From duncan.booth at invalid.invalid Thu Dec 4 04:01:30 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 4 Dec 2008 09:01:30 GMT Subject: Don't you just love writing this sort of thing :) References: Message-ID: Lawrence D'Oliveiro wrote: > for \ > Entry \ > in \ > sorted \ > ( > f for f in os.listdir(PatchesDir) if > PatchDatePat.search(f) != None > ) \ >: > Patch = (open, > gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir, > Entry), "r") ... read from Patch ... > Patch.close() > #end for > Have you ever considered trying to write readable code instead? Something like (untested): def patchfiles(dir, pattern): for f in os.listdir(dir): if pat.search(f) is not None: yield os.path.join(dir, f) def openpatch(name): if name.endswith(".gz"): return gzip.GzipFile(name, "r") return open(name, "r") for entry in sorted(patchfiles(PatchesDir, PatchDatePat): with openpatch(entry) as patch: ... read from patch ... (I must admit I haven't checked whether GZipFile works with the 'with' statement, but if it doesn't you just wrap it in contextlib.closing). -- Duncan Booth http://kupuguy.blogspot.com From joe at strout.net Fri Dec 19 12:01:42 2008 From: joe at strout.net (Joe Strout) Date: Fri, 19 Dec 2008 10:01:42 -0700 Subject: How to parsing a sequence of integers In-Reply-To: References: <494ba258$0$18998$426a74cc@news.free.fr> Message-ID: <494BD376.4000602@strout.net> Mensanator wrote: >> from __future__ import division >> >> at the top of the file. I put this at the top of all my Python files, >> whether I expect to be dividing or not. It just saves grief. > > If you want division to be floating point. > If, like me, you rarely do floating point > division and want the "/" to mean integer > division as God intended, then you don't > put from __future__ import division in your > source files. > > That's one of the good things about Python, > you can have it either way. Until you someday move up to Python 3, at which point you'll have to go back and change all your code to use the unambiguous // operator when you mean integer division. Better to do it now, I think, at least in any new code you write, to save you the hassle later. For those not familiar with the topic: Best, - Joe From hard4forget at gmail.com Sat Dec 6 16:19:10 2008 From: hard4forget at gmail.com (philips) Date: Sat, 6 Dec 2008 13:19:10 -0800 (PST) Subject: first time in the internet history a huge collection of funny pictures and videos over 10000 funny pics and videos download free on mobile format www.funreality.com Message-ID: first time in the internet history a huge collection of funny pictures and videos over 10000 funny pics and videos download free on mobile format www.funreality.com From clp at rebertia.com Sun Dec 21 18:53:28 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 21 Dec 2008 15:53:28 -0800 Subject: HMAC with RIPEMD-160 In-Reply-To: References: Message-ID: <47c890dc0812211553w645eae5dha85d5df364ea732a@mail.gmail.com> On Sun, Dec 21, 2008 at 4:21 AM, Kless wrote: > Is there any way of use HMAC with RIPEMD-160? > > Since that to create a ripemd-160 hash there is to use: > h = hashlib.new('ripemd160') > it looks that isn't possible > > For HMAC-SHA256 would be: > --------- > import hashlib > import hmac > > hm = hmac.new('key', msg='message', digestmod=hashlib.sha256) Untested, but should work according to the docs: hm = hmac.new('key', msg='message', digestmod=lambda: hashlib.new('ripemd160')) Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From casey.mcginty at gmail.com Fri Dec 5 17:26:17 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Fri, 5 Dec 2008 12:26:17 -1000 Subject: Project structure - Best practices In-Reply-To: References: <2d1f986f-94da-49c8-a1a5-df9457d5f8b3@r36g2000prf.googlegroups.com> Message-ID: > > This is first time that I am building python application that is > larger than a single module and I would like to do it right. I want to just say I am in agreement with the OP. Basically, there are a lot of factors to balance out and consider when starting a python application for the first time. For a new developer, tracking down this information is not a trivial task, as it is spread out over many location, or in worse cases, left up for the developer to "discover" on his/her own. I know it was not an easy task for me at first, and if we can make it easier for the next set of newcomeres, than that would be all the better. As far as open source projects go, the Python documentation is some of the best I've seen, however it would be nice to see a "Python Project Quick Start Guide" as part of the standard docs. The basics of this document would touch on packaging, imports, logging, testing, documenting, naming conventions, SCM, etc. Instead of rehashing the current docs, the focus would be on the combined integration of all of these features into a single code base. I realize that there is a wide range of preferences on specifics of each topic. But, just like PEP 8[1] is a good standard on code style, so would having a document as reference for other project-level "style" fundamentals. Ultimately, there could be a template project directory and source files that a user could build from. This is much more preferable to a blank directory, and might have the added benefit of influencing users to pick up recommended, but often ignored, practices at the beginning of a project. So, with all this said. I'd be willing to capture a lot of the methods I've picked up over the last couple months working with python. If anyone wants to add some suggestions, I'd love to have more discussion to organize thoughts and see if any new ideas come out. As a starting point, what is a good markup language to use for some slick HTML and PDF output? - Casey McGinty [1] http://www.python.org/dev/peps/pep-0008/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From 5lvqbwl02 at sneakemail.com Tue Dec 30 15:35:34 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Tue, 30 Dec 2008 12:35:34 -0800 (PST) Subject: Understanding search queries, semantics, and "Meaning" ...aren't we all looking for meaning? Message-ID: <82372457-2503-4682-96b3-37540328bf26@w39g2000prb.googlegroups.com> I have Section 4.4.1 of SICP rattling around in my head (database queries), and I'm trying to come up with a simple dictionary-based database in Python to represent circuit diagrams. My main confusion isn't one of implementation, but a matter of "big thinking", fundamentally, about the problem. Please don't suggest using a SQL library, as I'm looking to learn to fish, so to speak, and to learn a bit about the biology of fish. I've subclassed dict to hdict ("hashable dict") and rewritten the __hash__ function so I can include a dict into a set. Thanks to a previous poster here for providing that suggestion. A circuit component looks like this for example: comp1 = hdict(value=1e-6, footprint='0402', vendor='digikey') comp2 = hdict(value=10e3, footprint='0603', vendor='mouser') etc, etc. The database holds the values like this: db = dict() # normal dict db['value'] = ([1e-6, 10e3], [comp1, comp2]) #ordered set for fast lookup/insertion db['footprint'] = {'0402':set[comp1], '0603':comp2} # unordered uses normal dict for fast lookup db['vendor'] = {'digikey':[comp1], 'mouser':[comp2]} So basically the keys are the component parameters, and the values is the list of components with that value. Stuff that is comparable is ordered; stuff that is discrete is not ordered, using either 2-tuples or dicts, respectively. This allows extremely fast lookup of components based on their properties, with O(1) performance for non-ordered stuff, and O(log n) performance for ordered stuff (using bisect methods). The set operations are extremely fast, so I can do AND and OR operations on compound queries of this nature without worry. I need this speed not so much for selecting components when the user types in a query, but for when the mouse is hovering over the schematic and I need things to light up underneath, if the GUI is generating hundreds of mouse messages per second, and for inspector windows to appear quickly when you click, etc. If you have ever used Altium, you can see how effective this is in terms of creating a good interactive user experience. My question is what happens when I choose to search for NOT footprint='0402'. Should this return a blank list? This happens by default., and is in fact true: a blank list satisfies "not anything" actually. Should this return everything that is NOT footprint 0402 (ie returns 0603 components)? This *strongly implies* a pre-selection of *all* objects before performing the negating function, or of looking at the ordering of other queries in the overall search term, and then applying NOT to the results of another query. But I'm suspicious of a brute force preselection of all objects whenever I see a NOT, and anyway it messes up the clean query/combiner method of search I'm doing, and it requires an implied sequence of search, where I'm pretty sure it should not rely on sequencing. Even though this is single threaded, etc., the semantics of the query should not rely on ordering of the search term: footprint='0402' and NOT vendor='mouser' should return the same as NOT vendor='mouser' and footprint='0402'. So this is my philosophical quandary. I'm not sure what the correct thing is. In SICP they are using nondeterministic stuff which I don't quite get, so it's hard to follow. Also they are not using dictionaries and hashes, so I'm not sure if their generate-and-test method would work here anyway. Generate-and-test seems extremely inefficient. Can a wise guru please enlighten me? thanks Michael From ianare at gmail.com Tue Dec 16 11:48:50 2008 From: ianare at gmail.com (=?ISO-8859-1?B?aWFuYXLp?=) Date: Tue, 16 Dec 2008 08:48:50 -0800 (PST) Subject: Copying files in directory References: <2a815b7d-f01f-4666-bfc6-e9c43a75019b@t3g2000yqa.googlegroups.com> Message-ID: <7dbf8403-8a16-48c2-9744-7f8e9842b923@a37g2000pre.googlegroups.com> On Dec 15, 9:49?pm, pacsciad... at gmail.com wrote: > I'm writing a project management system, and I need the ability to > accept a directory name and move its contents to another directory. > Can someone give me a code sample that will handle this? I can't find > any "copying" functions in os or os.path. > > Regards, > LeafStorm shutil's move function does what you describe From n.kottiyath at gmail.com Mon Dec 22 09:57:55 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Mon, 22 Dec 2008 06:57:55 -0800 (PST) Subject: Event Driven programming - Doubts Message-ID: <80f360e4-2880-4c66-a6b4-e05d6dbc9031@b41g2000pra.googlegroups.com> Hi, I have been looking at Twisted and lately Circuits as examples for event driven programming in Python. Even though I understood how to implement the code in these and what is deferred etc, I have not yet understood the implementation of deferred. I went through a lot of tutorials, but I guess most places they expect that the user already understands how events are generated. The tutorials mention that there is no more threads once twisted is used. My question is as follows: I have not understood how the callbacks are hit without (a) blocking the code or (b) having new threads. The usual example given is that of a program waiting for data coming through a socket. In the tutorials, it is mentioned that -in an event driven program, we schedule the code to hit when the remote server gets back to us - . Now, my question is - somebody has to still wait on that socket and check whether the data is received, and once all the data is received, call the appropriate callbacks. Is twisted creating a micro-thread which just waits on the socket and once the data is received, calls callFromThread for it to run on the main loop? If so, Even though data locking etc is not a problem, are we not still having threads? Will it not still cause scalability problems in high traffic? If not, could somebody let me know how it is done? From psaffrey at googlemail.com Wed Dec 17 09:41:24 2008 From: psaffrey at googlemail.com (psaffrey at googlemail.com) Date: Wed, 17 Dec 2008 06:41:24 -0800 (PST) Subject: Selecting a different superclass Message-ID: This might be a pure OO question, but I'm doing it in Python so I'll ask here. I'm writing a number crunching bioinformatics application. Read lots of numbers from files; merge, median and munge; draw plots. I've found that the most critical part of this work is validation and traceability - "where does this final value come from? How has it been combined with other values? Is that right?" My current implementation stores all my values just as floats with a class called PointSet for storing one set of such values, with various mathematical and statistical methods. There are several subclasses of PointSet (IDPointSet, MicroArrayPointSet) for obtaining values from different file types and with different processing pipelines. I'm planning to instead store each value in a TraceablePoint class which has members that describe the processing stages this value has undergone and a TraceablePointSet class to store groups of these - this will contain all the same methods as PointSet, but will operate on TraceablePoints instead of floats. Of course, this will be much slower than just floats, so I'd like to be able to switch it on and off. The problem is that IDPointSet and MicroArrayPointSet will need to inherit from PointSet or TraceablePointSet based on whether I'm handling traceable points or not. Can I select a superclass conditionally like this in Python? Am I trying to do something really evil here? Any other bright ideas on my application also welcome. Peter From prologic at shortcircuit.net.au Thu Dec 11 21:02:21 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 12 Dec 2008 12:02:21 +1000 Subject: Bidirectional Networking In-Reply-To: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> Message-ID: Have a look at circuits. http://trac.softcircuit.com.au/circuits/ It's a general purpose event-driven framework with a focus on Component architectures and has a good set of Networking Components, specifically: circuits.lib.sockets * TCPServer * TCPClient * UDPServer * UDPClient (alias of UDPServer) With circuits, there is no such thing as: serve_forever() It'll try to stay out of your way as much as possible and let you define your own main event loop which could look like this: from circuits import Manager from circuits.lib.sockets import TCPServer, TCPClient manager = Manager() server =TCPServer(8000) client = TCPClient() manager += server manager += client ... while True: server.poll() client.poll() manager.flush() I hope this helps you! :) cheers James On Fri, Dec 12, 2008 at 10:33 AM, Emanuele D'Arrigo wrote: > Hi everybody! A networking question! > > I've been looking at and tinkering a little with the various > networking modules in python. The examples are pretty clear and a > module such as the SimpleXMLRPCServer is actually simple! > > All the examples though are based on a client interrogating a server, > with the client initiating the connection, obtaining something and > then closing the connection. Basically the server is a reactive party: > only if the client get in touch the server respond. What if the server > wanted to notify the client of something of interest, i.e. new data > that the client should take into consideration and potentially > process? > > One option would be for the client to periodically poll the server for > changes. Fair enough, that would work. But it'd be a bit of a waste if > the changes aren't particularly frequent. > > Is it possible then to establish both a server and a client in the > same application? I guess it must be possible but the examples all > rely on some kind of server loop (i.e. SocketServer.serve_forever) > that if started on both client and server sides would create two > listening parties but no talking at all! Furthermore, other libraries > might have their own loop, i.e. a graphical client has a loop to > redraw the screen and the two loops would somehow have to be > interleaved. > > I'm not quite seeing how this can be done other than we threads. Is > that the way to do it? Place the listening loop in a thread while the > rest of the application does its own thing? > > Or is it SocketServer.handle_request() the key? I could call this > function periodically, but what happens if a request is made while the > application is doing something else? Are the requests queued and dealt > with one per loop? > > Thanks for your help! > > Manu > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From steve at holdenweb.com Mon Dec 29 11:22:17 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 29 Dec 2008 11:22:17 -0500 Subject: math module for Decimals In-Reply-To: <4958F3C4.1050103@wi.rr.com> References: <4958F3C4.1050103@wi.rr.com> Message-ID: Raymond L. Buvel wrote: > Since the interest is more in extended precision than in decimal > representation, there is another module that may be of interest. > > http://calcrpnpy.sourceforge.net/clnum.html > > It interfaces to the Class Library for Numbers (CLN) library to provide > both arbitrary precision floating point and complex floating point > numbers and the usual math functions. > > While I am the author of this module, I agree with Mark that a module > based on MPFR would be better since you have better control over > precision and rounding. > > I have looked at Sage (which uses MPFR) but it is a huge integrated > package so you can't just import what you need into one of your usual > Python scripts. > > I wrote the clnum module mainly to support arbitrary precision in an RPN > calculator available from the same SourceForge project. However, it > also works nicely as a stand-alone module. > > At this time, there is no Windows installer available for Python 2.6 > because I don't use Windows at home and the person who normally builds > the installer for me is no longer interested. If someone wants to > follow the published instructions and send me the resulting installer, I > will put it up on SourceForge. > I'm not sure why nobody has mentioned gmpy, except possibly because it advertises its alpha status and doesn't have many active developers. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From yameenaziz at gmail.com Sat Dec 13 17:54:23 2008 From: yameenaziz at gmail.com (yameenaziz at gmail.com) Date: Sat, 13 Dec 2008 14:54:23 -0800 (PST) Subject: 1000 Earn Dollars $$$ Message-ID: <1810f9ce-41d1-4420-8b1b-c62a481680a2@y1g2000pra.googlegroups.com> "How To Make $1,000,000 THIS YEAR With our Online Business" From joe at strout.net Mon Dec 8 23:30:00 2008 From: joe at strout.net (Joe Strout) Date: Mon, 8 Dec 2008 21:30:00 -0700 Subject: A question about reference in Python. In-Reply-To: References: <493CB003.3080209@gmail.com> Message-ID: <5207FE9F-B50F-4B5B-8959-124BB0C93E65@strout.net> On Dec 8, 2008, at 7:43 PM, Steven D'Aprano wrote: > On Mon, 08 Dec 2008 08:18:27 -0700, Joe Strout wrote: > >> On Dec 7, 2008, at 10:26 PM, Group wrote: >> >>> Now, I want to write a Red-Black Tree, and a List structure. In C/C >>> + +, >>> I can >>> use pointers to refer to children notes (or next notes). But, in >>> Python, how >>> can I do it? Except the sequence, I know not any way. >> >> Any variable in Python is a reference > > Except that they don't behave like references in languages that have > explicit reference parameters. I didn't say anything about reference parameters (by which I believe you mean parameters passed by reference). I say a variable in Python IS a reference. And it is *exactly* like a reference parameter in any other modern OOP language, as I've clearly shown (http://www.strout.net/info/coding/valref/ ). That page also explains that Python's references are always passed by value; Python doesn't have a pass-by-reference mechanism, unlike (say) RB, C++, or .NET. This stuff really isn't that hard. > Did you not see the thread asking how to create reference parameters > in > Python? Subject "var or inout parm?". I noticed you were conspicuous > by > your absence in that little discussion. No, sorry, I missed that one. The volume of this group (plus the several other Python lists I subscribe to) requires me to skim a lot, and often choose not to read a thread at all. In this case, the subject caught my attention, and I saw that I could help clear up some confusion. Now that I've done that, I'll probably cease to read this thread any further, since as you say, we've been over this to death. Go ahead and try to confuse him if you insist. Hopefully he'll ignore that and see that Python is simple, and identical in its semantics to the languages he already knows. Best, - Joe From fakeaddress at nowhere.org Tue Dec 16 01:52:20 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 15 Dec 2008 22:52:20 -0800 Subject: Thread Locking issue - Can't allocate lock (sem_init fail) In-Reply-To: References: Message-ID: jamskip at googlemail.com wrote: [...] > The program is multithreaded to speed up the processing...there are > input and output Queues. It's not the major point here, but are you aware of Python's GIL? > Now, each domain entry is an class object containing various bits of > info. Each domain class also has its own lock, so that only one thread > can modify each domain at a time. > > I'm load-testing the program with a sample of 1 million email > addresses and when i hit about the 500,000 mark i get a locking > error... Does that correspond to creating 500,000 locks? For sure? > sem_init: No space left on device [...] > error: can't allocate lock What happens if you try to allocate a million locks, as in: from threading import Lock locks = [] for i in range(10**6): try: locks.append(Lock()) locks[-1].acquire() except: print "Failed after %d locks." % i raise I tried the above in WindowsXP and Ubuntu 8.04 (Python 2.6 and 2.52 respectively), and it ran on both without the exception. > Googling for this sort of error doesn't yield any results, and i can't > find any information about limits to the number of locks you can have > in Python. The 'No space left on device' message indicates a memory > issue, however i doubt this since its running on a linux server with 4 > cores and 16GB ram. It seems more like an internal Python limit has > been hit (sem_init - semaphore initialisation?). Does anyone know more > about threading internals and any internal limits? Python treading is implemented on top of some thread facility the target O.S. provides. Creating a Python lock may or may not use up some limited kernel resource. Given my experiments, limited as they were I do not think this is a Python limit. If could be an issue with your platform, or a defect in the code you inherited. > For the timebeing, I've implemented locking at a higher level which > will reduce performance but keep the number of lock objects to a > minumum. That's probably a reasonable strategy whether or not you can create a million locks. -- --Bryan From lists at cheimes.de Sun Dec 21 14:01:12 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 21 Dec 2008 20:01:12 +0100 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: Patrick Mullen schrieb: > 2) In my experience, major version changes tend to be slower than > before. When a lot of things change, especially if very low-level > things change, as happened in python 3.0, the new code has not yet > went through many years of revision and optimization that the old code > has. In my opinion, python 3 was rushed out the door a bit. It could > have done with a few more months of optimization and polishing. > However, on the other hand, it is going to take so long for python > infrastructure to convert to python 3, that an earlier release makes > sense, even if it hasn't been excessively polished. The biggest > reason for the speed change is the rewritten stdio and > unicode-everything. Hopefully this stuff can be improved in future > updates. I don't think anyone WANTS cpython to be slower. The 3.0 release targets third party developers. Authors of 3rd party extensions and libraries need a stable API to port their software to a new major release. The main objective was feature completeness and stability. If you need speed either stick to the 2.x series or wait until 3.1 is out. We could have waited a few more months or even a few more years with a 3.0 release. There is always - I repeat ALWAYS - work to do. For an open source project like Python "release early, release often" works better. Christian From excord80 at gmail.com Fri Dec 19 15:04:58 2008 From: excord80 at gmail.com (excord80) Date: Fri, 19 Dec 2008 12:04:58 -0800 (PST) Subject: Building a web questionnaire, can it be done in Python ? References: Message-ID: On Dec 19, 11:58?am, Stef Mientki wrote: > hello, > > I'm considering building a web questionnaire in Python. > I've made several desktop applications in Python / ?wxPython, > but I've no experience in using Python on a webserver, > and I don't have much knowledge about web applications in general. > Ah. You want to report directly to the Django tutorial: http://docs.djangoproject.com/en/dev/intro/tutorial01/ From steve at REMOVE-THIS-cybersource.com.au Sun Dec 7 18:37:32 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 23:37:32 GMT Subject: Rich Comparisons Gotcha References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> Message-ID: <014c55e9$0$20670$c3e8da3@news.astraweb.com> On Sun, 07 Dec 2008 23:20:12 +0000, Steven D'Aprano wrote: > On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: > >> Rasmus Fogh wrote: >> >>> Current behaviour is both inconsistent and counterintuitive, as these >>> examples show. >>> >>>>>> x = float('NaN') >>>>>> x == x >>> False >> >> Blame IEEE for that one. Rich comparisons have nothing to do with that >> one. > > There is nothing to blame them for. This is the correct behaviour. NaNs > should *not* compare equal to themselves, that's mathematically > incoherent. Sorry, I should explain why. Given: x = log(-5) # a NaN y = log(-2) # the same NaN x == y # Some people want this to be true for NaNs. Then: # Compare x and y directly. log(-5) == log(-2) # If x == y then exp(x) == exp(y) for all x, y. exp(log(-5)) == exp(log(-2)) -5 == -2 and now the entire foundations of mathematics collapses into a steaming pile of rubble. -- Steven From google at mrabarnett.plus.com Wed Dec 31 11:57:59 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 31 Dec 2008 16:57:59 +0000 Subject: How to initialize an array with a large number of members ? In-Reply-To: <5m4nl4hs8f9q6rfcp7b1jt7nk1o6sq6r0f@4ax.com> References: <5m4nl4hs8f9q6rfcp7b1jt7nk1o6sq6r0f@4ax.com> Message-ID: <495BA497.9020508@mrabarnett.plus.com> David at bag.python.org wrote: > Thanks to those who have helped a beginner in > Python. Using version 3.0 > > # script23 > from array import array > < see failed initialization attempts below > > > tally = array('H',for i in range(75) : [0]) > > tally = array('H',[for i in range(75) : 0]) > > tally = array('H',range(75) : [0]) > > tally = array('H',range(75) [0]) > > Above give either Syntax error or TypeError > > All examples of sequences in docs show only > a few members being initialized. Array doc > says an iterator can be used, but doen't show > how. What would you do for a 2 dimensional > array ? Incorporate c code ? > The online docs are clearly insufficient for a > novice. Have ordered Summerfields new book. > >>> # With a list >>> tally = array('H', [0] * 75) >>> >>> # With a generator >>> tally = array('H', (0 for i in range(75))) From george.sakkis at gmail.com Wed Dec 10 14:51:51 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 10 Dec 2008 11:51:51 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: On Dec 10, 1:42?pm, cm_gui wrote: > http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-... > > I fully agree with Krzysztof Kowalczyk . > Can't they build a faster VM for Python since they love the language > so much? WTF is Krzysztof Kowalczyk and why should we care ? Thanks for playing, the exit for the trolls is right down the hall. From macc_200 at yahoo.co.uk Sat Dec 6 12:43:05 2008 From: macc_200 at yahoo.co.uk (macc_200) Date: Sat, 6 Dec 2008 17:43:05 +0000 (GMT) Subject: operators as variables Message-ID: <103920.71204.qm@web26006.mail.ukl.yahoo.com> Hi, just starting programming and have an elementary?question after playing around with lists but cannot find the answer with googling. I have a list?of variables?and I would like some of those variables to be integers and some to be?operators so the list would look something like [5?* 4?-?4 + 6] and then be able to evaluate the result (i.e. get 10).? How do you make the interpreter see the operator as that instead of a string and just echo the list back to me. thanks, Andy (and suggestions for a decent Python book would be appreciated) -------------- next part -------------- An HTML attachment was scrubbed... URL: From BrooklineTom at gmail.com Wed Dec 10 13:59:16 2008 From: BrooklineTom at gmail.com (brooklineTom) Date: Wed, 10 Dec 2008 10:59:16 -0800 (PST) Subject: Deeper tracebacks? Message-ID: I want my exception handler to report the method that originally raised an exception, at the deepest level in the call-tree. Let give an example. import sys, traceback class SomeClass: def error(self): """Raises an AttributeError exception.""" int(3).zork() def perform_(self, aSelector): try: aMethod = getattr(self, aSelector, None) answer = apply(aMethod, [], {}) except: AttributeError, anAttributeErrorException: aRawStack = traceback.extract_stack() answer = None When I call "perform_" (... SomeClass().perform_('error')), I want to collect and report the location *within the method ("error") that failed*. The above code reports the location of "perform_", and no deeper in the call tree. Anybody know how to accomplish this? From vedranf at vedranf.mine.nu Fri Dec 19 06:16:44 2008 From: vedranf at vedranf.mine.nu (=?ISO-8859-1?Q?Vedran_Furac=28?=) Date: Fri, 19 Dec 2008 12:16:44 +0100 Subject: List comprehension in if clause of another list comprehension Message-ID: Hi! In [69]: a = 'a b c' In [70]: b = 'a b, c d' In [74]: [i for i in a.split() if i not in b.split()] Out[74]: ['b'] Everything ok. In [77]: b.split() == [i for i in b.split()] Out[77]: True As expected. Now, put this in the first list comprehension: In [80]: [i for i in a.split() if i not in [i for i in b.split()] ] Out[80]: ['d'] Hmmmm... why is that? Regards! From samslists at gmail.com Sat Dec 27 04:19:36 2008 From: samslists at gmail.com (Sam) Date: Sat, 27 Dec 2008 01:19:36 -0800 (PST) Subject: Parsing a sitemap library? Message-ID: <0e9d5499-9c42-45ea-8060-2f73e199f8f9@z27g2000prd.googlegroups.com> Hi... I see an awful lot of code out there to create sitemaps using Python. But I can't find anything to consume sitemaps using Python. Is there a library to convert sitemaps and sitemap indexes of sitemaps into something more Pythonic? I know I can write one pretty easily using e.g. Beautiful Soup or maybe lxml, but I never like to reinvent the wheel. Thanks From wojciech_mula at poczta.null.onet.pl.invalid Sat Dec 13 14:04:02 2008 From: wojciech_mula at poczta.null.onet.pl.invalid (Wojciech =?ISO-8859-2?Q?Mu=B3a?=) Date: Sat, 13 Dec 2008 20:04:02 +0100 Subject: [OT] stable algorithm with complexity O(n) References: Message-ID: <20081213200402.952cad5d.wojciech_mula@poczta.null.onet.pl.invalid> "David Hl??ik" wrote: > I have to create stable algorithm for sorting n numbers from interval > [1,n^2] with time complexity O(n) . Some kind of radix sort or counting sort. These algo. has O(n) complexity. w. From nomadoro at gmail.com Fri Dec 12 07:11:46 2008 From: nomadoro at gmail.com (Lee Soin) Date: Fri, 12 Dec 2008 20:11:46 +0800 Subject: How to write binary data to file and socket Message-ID: Hello, all! I'm new to python. In Linux C programming, writing data to file and socket share the same system call "write". But it seems that only data of string type can be used for "write" and "send". So how to write binary data to file and socket? -- Sun Li Department of Physics Nanjing University, China -------------- next part -------------- An HTML attachment was scrubbed... URL: From anonymous.c.lisper at gmail.com Mon Dec 1 17:53:50 2008 From: anonymous.c.lisper at gmail.com (anonymous.c.lisper at gmail.com) Date: Mon, 1 Dec 2008 14:53:50 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: On Nov 30, 10:30?pm, Xah Lee wrote: > some stuff You are a bot? I think you failed the Turing test when you posted the same thing 20 times. A rational human would realize that not too many people peruse this newsgroup, and that most of them have already seen the wall of text post that you generate every time. Just a thought, but whoever owns this thing might want to rework the AI. From Rick at youtellme.com Thu Dec 25 22:17:19 2008 From: Rick at youtellme.com (Rick van Hattem) Date: Fri, 26 Dec 2008 04:17:19 +0100 Subject: dummy needs help with Python In-Reply-To: References: Message-ID: <200812260417.19137.Rick@youtellme.com> On Friday 26 December 2008 03:24:41 MLDSpenser at aol.com wrote: > I don't have time to work my way through the online Python tutorial. I've > tried a couple of forums but nobody has answered my questions. There are loads of Python tutorials on the net, some will teach you the basics in 5 minutes, others will give you a more thorough understanding in a couple of days. But it shouldn't be that hard I'd say, if you want it fast than I'd recommend this one: http://hetland.org/writing/instant-python.html > A simple > program with comments that say "here's where I read File A and define/map/ > the fields in it" would let me learn by testing and trying things out, the > same way I learned to work with the fields in the module. Here's a little example program, it's actually quite simple ;) import csv csv_reader = csv.reader(open('spam.csv')) for row in csv_reader: print row That will print all the rows in the file, if you want to extract the specific fields you could do something like this: for a, b, c in csv_reader: print a, b, c Where a, b and c are the fields (I'd recommend a more useful name though). For writing a csv the process is similar, but open it like this and use writerow: csv_writer = csv.writer(open('eggs.csv', 'w')) Hopefully that helps :) From pavlovevidence at gmail.com Mon Dec 22 17:18:44 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 22 Dec 2008 14:18:44 -0800 (PST) Subject: python3 urlopen(...).read() returns bytes References: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> Message-ID: <31982ad6-8567-42c0-a8bb-083e61fbd0e2@a29g2000pra.googlegroups.com> On Dec 22, 3:41?pm, "Glenn G. Chappell" wrote: > I just ran 2to3 on a py2.5 script that does pattern matching on the > text of a web page. The resulting script crashed, because when I did > > ? ? f = urllib.request.urlopen(url) > ? ? text = f.read() > > then "text" is a bytes object, not a string, and so I can't do a > regexp on it. > > Of course, this is easy to patch: just do "f.read().decode()". > However, it strikes me as an obvious bug, which ought to be fixed. > That is, read() should return a string, as it did in py2.5. Well, I can't agree that it's an obvious bug (in Python 3). It might be something worth raising a warning over in 2to3. It would also be a reasonable wishlist item for automatic encoding detection and conversion to a string (see below). But it's not a bug. > But apparently others disagree? This was mentioned in issue 3930 > (http://bugs.python.org/issue3930) back in September '08, but that > issue is now closed, apparently because consistent behavior was > achieved. But I figure consistently bad behavior is still bad. > > This change breaks pretty much every Python program that opens a > webpage, doesn't it? No. What if someone is using urllib retrieve (say) a JPEG image? A bytes object is what they'd want in Python 3. Also, many people were already explicitly dealing with encodings in Python 2.5; the change wouldn't affect them. > 2to3 doesn't catch it, and, in any case, why > should read() return bytes, not string? Am I missing something? It returns bytes because it doesn't know what encoding to use. This is the appropriate behavior. HOWEVER... a web page request often does know what encoding to use, since it ostensibly has to parse the header. It's reasonable that IF a url request's "Content-type" is text, and/or the "Content-encoding" is given, for urllib to have an option to automatically decode and return a string instead of bytes. (For all I know, it already can do that.) Carl Banks From tino at wildenhain.de Mon Dec 1 10:20:56 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 01 Dec 2008 16:20:56 +0100 Subject: finding the difference between the two version of the python program... In-Reply-To: <19ac19520812010430s7e0e11a6sf787ca1f73e87f36@mail.gmail.com> References: <19ac19520812010430s7e0e11a6sf787ca1f73e87f36@mail.gmail.com> Message-ID: <493400D8.8070203@wildenhain.de> Hi, Piyush Anonymous wrote: > is there a tool which, given two version of programs, finds the > difference like set of classes added, deleted and modified? > assuming the python program is written in oops way. diff for example can do this. There is also an difflib in python which you can use to roll your own diff. Regards TIno -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From jstroud at mbi.ucla.edu Sun Dec 7 16:57:54 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 07 Dec 2008 13:57:54 -0800 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Rasmus Fogh wrote: > Current behaviour is both inconsistent and counterintuitive, as these > examples show. > >>>> x = float('NaN') >>>> x == x > False Perhaps this should raise an exception? I think the problem is not with comparisons in general but with the fact that nan is type float: py> type(float('NaN')) No float can be equal to nan, but nan is a float. How can something be not a number and a float at the same time? The illogicality of nan's type creates the possibility for the illogical results of comparisons to nan including comparing nan to itself. >>>> ll = [x] >>>> x in ll > True >>>> x == ll[0] > False But there is consistency on the basis of identity which is the test for containment (in): py> x is x True py> x in [x] True Identity and equality are two different concepts. Comparing identity to equality is like comparing apples to oranges ;o) > >>>> import numpy >>>> y = numpy.zeros((3,)) >>>> y > array([ 0., 0., 0.]) >>>> bool(y==y) > Traceback (most recent call last): > File "", line 1, in > ValueError: The truth value of an array with more than one element is > ambiguous. Use a.any() or a.all() But the equality test is not what fails here. It's the cast to bool that fails, which for numpy works like a unary ufunc. The designers of numpy thought that this would be a more desirable behavior. The test for equality likewise is a binary ufunc and the behavior was chosen in numpy for practical reasons. I don't know if you can overload the == operator in C, but if you can, you would be able to achieve the same behavior. >>>> ll1 = [y,1] >>>> y in ll1 > True >>>> ll2 = [1,y] >>>> y in ll2 > Traceback (most recent call last): > File "", line 1, in > ValueError: The truth value of an array with more than one element is > ambiguous. Use a.any() or a.all() I think you could be safe calling this a bug with numpy. But the fact that someone can create a bug with a language is not a condemnation of the language. For example, C makes it real easy to crash a program by overrunning the limits of an array, but no one would suggest to remove arrays from C. > Can anybody see a way this could be fixed (please)? I may well have to > live with it, but I would really prefer not to. Your only hope is to somehow convince the language designers to remove the ability to overload == then get them to agree on what you think the proper behavior should be for comparisons. I think the probability of that happening is about zero, though, because such a change would run counter to the dynamic nature of the language. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From skip at pobox.com Wed Dec 24 11:02:47 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 24 Dec 2008 10:02:47 -0600 Subject: =?ISO-8859-1?Q?object_ori=EBnted?= In-Reply-To: References: Message-ID: <18770.23847.437473.79825@montanaro-dyndns-org.local> Dennis> I know that python is an Object Ori?nted language but I was Dennis> wondering if it gets used as a non-OOP also (by a good amount of Dennis> people). Oh yeah. Works great for writing quick-n-dirty Unix filters which are a bit more complex than can comfortably be wrangled with Bash, but not so complex that you need more organization (such as classes). A function looping over sys.stdin. Make a few transformations and away you go. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From nick at craig-wood.com Tue Dec 9 07:30:52 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 09 Dec 2008 06:30:52 -0600 Subject: Learning Python now coming from Perl References: Message-ID: Roy Smith wrote: > In article , > Nick Craig-Wood wrote: > > > My favourite mistake when I made the transition was calling methods > > without parentheses. In perl it is common to call methods without > > parentheses - in python this does absolutely nothing! pychecker does > > warn about it though. > > > > perl -> $object->method > > python -> object.method() > > On the other hand, leaving out the parens returns the function itself, > which you can then call later. I've often used this to create data-driven > logic. I didn't say it wasn't useful, just that if you came from Perl like I did, it is an easy mistake to make ;-) > For example, I'm currently working on some code that marshals objects of > various types to a wire protocol. I've got something like: > > encoders = { > SM_INT: write_int, > SM_SHORT: write_short, > SM_FLOAT: write_float, > # and so on > } > > class AnyVal: > def __init__(self, type, value): > self.type = type > self.value = value > > def write_anyval(any): > encoders[any.type](any.value) > > The fact that functions are objects which can be assigned and stored in > containers makes this easy to do. OO lore says whenever you see a type field in an instance you've gone wrong - types should be represented by what sort of object you've got, not by a type field. Eg http://www.soberit.hut.fi/mmantyla/BadCodeSmellsTaxonomy.htm """The situation where switch statements or type codes are needed should be handled by creating subclasses. """ Here is my first iteration (untested) class AnyVal: def __init__(self, value): self.value = value def write(self): raise NotImplementedError() class IntVal(AnyVal): def write(self): # write_int code class ShortVal(AnyVal): def write(self): # write_short code class FloatVal(AnyVal): def write(self): # write_float code Then to write an AnyVal you just call any.write() The initialisation of the AnyVals then becomes from AnyVal(int_expression, SM_INT) to IntVal(int_expression) However, if the types of the expressions aren't known until run time, then use a dict of class types AnyValRegistry = { SM_INT: IntVal, SM_SHORT: ShortVal, SM_FLOAT: FloatVal, # and so on } And initialise AnyVal objects thus any = AnyValRegistry[type](value) This smells of code duplication though and a real potential for a mismatch between the AnyValRegistry and the actual classes. I'd probably generalise this by putting the type code in the class and use a __metaclass__ to autogenerate the AnyValRegistry dict which would then become an attribute of AnyClass Eg (slightly tested) SM_INT=1 SM_SHORT=2 SM_FLOAT=3 class AnyVal(object): TYPE = None registry = {} class __metaclass__(type): def __init__(cls, name, bases, dict): cls.registry[cls.TYPE] = cls def __init__(self, value): self.value = value @classmethod def new(cls, type_code, value): """Factory function to generate the correct subclass of AnyVal by type code""" return cls.registry[type_code](value) def write(self): raise NotImplementedError() class IntVal(AnyVal): TYPE = SM_INT def write(self): # write_int code print "int", self.value class ShortVal(AnyVal): TYPE = SM_SHORT def write(self): # write_short code print "short", self.value class FloatVal(AnyVal): TYPE = SM_FLOAT def write(self): # write_float code print "float", self.value You then make new objects with any = AnyVal.new(type_code, value) and write them with any.write() Anyone can add a subclass of AnyVal and have it added to the AnyVal.registry which is neat. >>> any = AnyVal.new(SM_SHORT, 1) >>> any <__main__.ShortVal object at 0xb7e3776c> >>> any.write() short 1 >>> any = AnyVal.new(SM_FLOAT, 1.8) >>> any <__main__.FloatVal object at 0xb7e37a6c> >>> any.write() float 1.8 You could also override __new__ so you could write AnyVal(type_code, value) to create the object of a new type. I personally don't think its is worth it - a factory function is nice and obvious and show exactly what is going on. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From wanshizhao2 at gmail.com Sat Dec 13 15:47:13 2008 From: wanshizhao2 at gmail.com (www.toptog.com) Date: Sat, 13 Dec 2008 12:47:13 -0800 (PST) Subject: www.toptog.comnike sneaker jordan retro gucci prada timberland lacsote Message-ID: www.toptog.com Here we can supply you 1. All kinds of jerseys: NFL Jerseys, NBA Jerseys, NHL Jerseys, MLB Jerseys, SOCCER Jerseys, etc. 2. All brands of shoes: obama nike sneaker,jordan 6 ring,Bape-star, Nike-Air-Max, Nike-Shox, Air-Force-One, Nike-Clear-Shoes, Nike-Air- Jordan1-24, Timberland-Boots, Icecream-Shoes, Puma, DG, Adidas, Gucci, Prada, Chanel, LV, Dsqared, Paciotti-4us, DSK, Football, Locaste, etc. 3. All Categories of Apparel & Fashion: T-shirt, Hoody, (www.toptog.com) Lacoste,edhardy, Jeans, Jackets, A&F-Coats, NFL, NBA, MLB ect. (www.toptog.com) 4. Handbags: Juicy-Couture, Burberrys, Hermes, Balenciaqa, Prada, Chloe, Coach, Gucci, Chanel, FD, LV etc. (www.toptog.com) 5. Jeweler: Tiffany, Gucci, 100% Silver, Stone, Jade With Gold etc. 6. Others: Caps, sunglasses, Belts, Watches, perfumes, etc. Do not hesitate to contact us! website www.toptog.com From guruyaya at gmail.com Tue Dec 16 16:58:02 2008 From: guruyaya at gmail.com (guruyaya) Date: Tue, 16 Dec 2008 13:58:02 -0800 (PST) Subject: What does the at sign do? Message-ID: I'm reading a lot of python code lately, django code to be exact, and I keep bumping into expressions that look like this @register.filter I see nothing importing @register, so I assume it's not just a function name. Yet I cannot figure where this @ sign came from. I hope I'm not just forgetting something out of the very basics. Thanks in advance Yaya From zxo102 at gmail.com Mon Dec 29 08:49:42 2008 From: zxo102 at gmail.com (zxo102) Date: Mon, 29 Dec 2008 05:49:42 -0800 (PST) Subject: How to display Chinese in a list retrieved from database via python References: <22be506d-91c2-4727-ace7-2e3382b6d214@g3g2000pre.googlegroups.com><979fdf6d-0500-47ba-87fd-0f0361ca3059@p2g2000prf.googlegroups.com><19680ed2-c78f-4ab9-8ca0-8ce26fd5b6a7@o4g2000pra.googlegroups.com> <2560a6e0-c103-46d2-aa5a-8604de4d1968@b38g2000prf.googlegroups.com> Message-ID: <7e38e76a-d5ee-41d9-9ed5-73a2e2993733@w1g2000prm.googlegroups.com> On 12?29?, ??5?06?, "Mark Tolonen" wrote: > "zxo102" wrote in message > > news:2560a6e0-c103-46d2-aa5a-8604de4d1968 at b38g2000prf.googlegroups.com... > > > I have a list in a dictionary and want to insert it into the html > > file. I test it with following scripts of CASE 1, CASE 2 and CASE 3. I > > can see "??" in CASE 1 but that is not what I want. CASE 2 does not > > show me correct things. > > So, in CASE 3, I hacked the script of CASE 2 with a function: > > conv_list2str() to 'convert' the list into a string. CASE 3 can show > > me "??". I don't know what is wrong with CASE 2 and what is right with > > CASE 3. > > > Without knowing why, I have just hard coded my python application > > following CASE 3 for displaying Chinese characters from a list in a > > dictionary in my web application. > > > Any ideas? > > See below each case...????? > > > > > Happy a New Year: 2009 > > > ouyang > > > CASE 1: > > ######################################################## > > f=open('test.html','wt') > > f.write(''' > > > > test > > > > > > ''') > > f.close() > > In CASE 1, the *4 bytes* D6 D0 CE C4 are written to the file, which is the > correct gb2312 encoding for ??. > > > > > CASE 2: > > ####################################################### > > mydict = {} > > mydict['JUNK'] = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce > > \xc4'] > > f_str = ''' > > > > test > > > > > > ''' > > > f_str = f_str%mydict > > f=open('test02.html','wt') > > f.write(f_str) > > f.close() > > In CASE 2, the *16 characters* "\xd6\xd0\xce\xc4" are written to the file, > which is NOT the correct gb2312 encoding for ??, and will be interpreted > however javascript pleases. This is because the str() representation of > mydict['JUNK'] in Python 2.x is the characters "['\xd6\xd0\xce\xc4', > '\xd6\xd0\xce\xc4', '\xd6\xd0\xce\xc4']". > > > > > CASE 3: > > ################################################### > > mydict = {} > > mydict['JUNK'] = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce > > \xc4'] > > > f_str = ''' > > > > test > > > > > > ''' > > > import string > > > def conv_list2str(value): > > list_len = len(value) > > list_str = "[" > > for ii in range(list_len): > > list_str += '"'+string.strip(str(value[ii])) + '"' > > if ii != list_len-1: > > list_str += "," > > list_str += "]" > > return list_str > > > mydict['JUNK'] = conv_list2str(mydict['JUNK']) > > > f_str = f_str%mydict > > f=open('test03.html','wt') > > f.write(f_str) > > f.close() > > CASE 3 works because you build your own, correct, gb2312 representation of > mydict['JUNK'] (value[ii] above is the correct 4-byte sequence for ??). > > That said, learn to use Unicode strings by trying the following program, but > set the first line to the encoding *your editor* saves files in. You can > use the actual Chinese characters instead of escape codes this way. The > encoding used for the source code and the encoding used for the html file > don't have to match, but the charset declared in the file and the encoding > used to write the file *do* have to match. > > # coding: utf8 > > import codecs > > mydict = {} > mydict['JUNK'] = [u'??',u'??',u'??'] > > def conv_list2str(value): > return u'["' + u'","'.join(s for s in value) + u'"]' > > f_str = u''' > > test > > > ''' > > s = conv_list2str(mydict['JUNK']) > f=codecs.open('test04.html','wt',encoding='gb2312') > f.write(f_str % s) > f.close() > > -Mark > > P.S. Python 3.0 makes this easier for what you want to do, because the > representation of a dictionary changes. You'll be able to skip the > conv_list2str() function and all strings are Unicode by default. Thanks for your comments, Mark. I understand it now. The list(escape codes): ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4'] is from a postgresql database with "select" statement.I will postgresql database configurations and see if it is possible to return ['??','? ?','??'] directly with "select" statement. ouyang From timr at probo.com Wed Dec 31 02:22:46 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 31 Dec 2008 07:22:46 GMT Subject: What is site-packages? References: Message-ID: <8c7ml4dcf2b8e2i25jfhs40llngldduiqi@4ax.com> Hussein B wrote: >On Dec 28, 2:04?pm, "Chris Rebert" wrote: >> On Sun, Dec 28, 2008 at 3:40 AM, Hussein B wrote: >> > Hey, >> > What is /usr/lib/pythonx.y/site-packages folder and for what it is >> > used usually? >> >> I believe it's where third-party libraries are typically installed to. >> >> Follow the path of the Iguana...http://rebertia.com > >You mean like MoinMoin, Django or Pylons for example? It means any package that should be available to Python programs that is not part of the standard Python library. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From google at mrabarnett.plus.com Wed Dec 3 18:17:46 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 03 Dec 2008 23:17:46 +0000 Subject: [SPAM] Re: "as" keyword woes In-Reply-To: <1228342347.29326.62.camel@brotherus.rdu.redhat.com> References: <896B75251BA19745A529B1B867893FA50679C6@planet.delsci.local> <1228342347.29326.62.camel@brotherus.rdu.redhat.com> Message-ID: <4937139A.5060502@mrabarnett.plus.com> Albert Hopkins wrote: > On Wed, 2008-12-03 at 13:38 -0800, Warren DeLano wrote: >> A bottom line / pragmatic question... hopefully not a FAQ. >> >> Why was it necessary to make "as" a reserved keyword? >> >> And more to the point, why was it necessary to prevent developers from >> being able to refer to attributes named "as"? >> >> For example, this code breaks as of 2.6 / 3.0: >> >> Class C: >> Pass >> >> obj = C() >> >> obj.bs = 2 # valid >> >> obj.as = 1 # syntax error >> >> obj.cs = 3 # valid >> >> Just to be clear: I understand why it breaks, since "as" is now a >> keyword, I also know that one can use workarounds such as: >> >> obj.__dict__['as'] = 1 >> >> to maintain compatibility. >> >> What I want to understand is why this parser change was necessary in >> order to enable new 2.6/3.0 features. Was this change potentially >> avoidable? >> >> Why can't the parser distinguish between a standalone " as " keyword and >> ".as" used as an object/attribute reference? >> >> Couldn't we have continued along just fine using a smarter parser >> without elevating "as" to reserved status (and thus potentially breaking >> a 10+ years of existing code)? >> >> Thank you for enlighting me! >> >> (Unfortunately, our project may now have to maintain a branch at 2.5.x >> in order to preserve compatibility with existing third-party scripts & >> infrastructure which routinely rely upon "as" as an object method. >> Sigh.) >> >> Cheers, >> Warren > > The short answer is that "as" is a keyword as of 2.6 (with the > introduction of the "with" statement) and to be fair none of the other > keywords can be identifiers. > > Also to be fair, there seems to be warning at least in my version of > python 2.5: > >>>> import sys >>>> sys.version_info > (2, 5, 1, 'final', 0) >>>> class C: > ... pass > ... >>>> obj = C() >>>> obj.as = 3 > :1: Warning: 'as' will become a reserved keyword in Python 2.6 > The parser in Python v2.5 can identify when "as" has its special meaning by context, but it's better to be consistent. Hopefully there won't be many reserved words (IIRC, COBOL has a _large_ number of them)! If you still want a name like that then the convention is to add a trailing underscore, eg the "pass_" method of POP3 objects in poplib. That probably doesn't help you, though. :-( From clp at rebertia.com Sat Dec 6 18:47:08 2008 From: clp at rebertia.com (Chris Rebert) Date: Sat, 6 Dec 2008 15:47:08 -0800 Subject: how to get a beep, OS independent ? In-Reply-To: <493B0D85.3060404@gmail.com> References: <493B0D85.3060404@gmail.com> Message-ID: <47c890dc0812061547g595593a1lc5ee6539adaa224c@mail.gmail.com> On Sat, Dec 6, 2008 at 3:40 PM, Stef Mientki wrote: > hello, > > I want to give a small beep, > for windows there's message-beep, > and there seems to be something like " curses" , > but that package seems to be totally broken in P2.5 for windows. > > Any other suggestions ? Printing the http://en.wikipedia.org/wiki/Bell_character ("\a") to the terminal produces a beep from the internal speaker. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > thanks, > Stef Mientki > -- > http://mail.python.org/mailman/listinfo/python-list > From python at bdurham.com Wed Dec 24 04:23:21 2008 From: python at bdurham.com (python at bdurham.com) Date: Wed, 24 Dec 2008 04:23:21 -0500 Subject: Strategy for determing difference between 2 very large dictionaries In-Reply-To: References: <1230102996.2303.1291616055@webmail.messagingengine.com> Message-ID: <1230110601.21320.1291626339@webmail.messagingengine.com> Hi Peter, If you are not interested in the intermediate results and the dictionary values are hashable you can get the difference by >>> a = dict(a=1, b=2, c=3) >>> b = dict(b=2, c=30, d=4) >>> dict(set(a.iteritems()) ^ set(b.iteritems())) {'a': 1, 'c': 3, 'd': 4} That's very cool! Thanks for sharing that technique. Regards, Malcolm ----- Original message ----- From: "Peter Otten" <__peter__ at web.de> To: python-list at python.org Date: Wed, 24 Dec 2008 09:46:51 +0100 Subject: Re: Strategy for determing difference between 2 very large dictionaries Gabriel Genellina wrote: > En Wed, 24 Dec 2008 05:16:36 -0200, escribi?: [I didn't see the original post] >> I'm looking for suggestions on the best ('Pythonic') way to >> determine the difference between 2 very large dictionaries >> containing simple key/value pairs. >> By difference, I mean a list of keys that are present in the >> first dictionary, but not the second. And vice versa. And a list >> of keys in common between the 2 dictionaries whose values are >> different. >> The 2 strategies I'm considering are: >> 1. Brute force: Iterate through first dictionary's keys and >> determine which keys it has that are missing from the second >> dictionary. If keys match, then verify that the 2 dictionaries >> have identical values for the same key. Repeat this process for >> the second dictionary. >> 2. Use sets: Create sets from each dictionary's list of keys and >> use Python's set methods to generate a list of keys present in >> one dictionary but not the other (for both dictionaries) as well >> as a set of keys the 2 dictionaries have in common. > > I cannot think of any advantage of the first approach - so I'd use sets. > > k1 = set(dict1.iterkeys()) > k2 = set(dict2.iterkeys()) > k1 - k2 # keys in dict1 not in dict2 > k2 - k1 # keys in dict2 not in dict1 > k1 & k2 # keys in both > >> Using the set >> of keys in common, compare values across dictionaries to >> determine which keys have different values (can this last step be >> done via a simple list comprehension?) If you are not interested in the intermediate results and the dictionary values are hashable you can get the difference by >>> a = dict(a=1, b=2, c=3) >>> b = dict(b=2, c=30, d=4) >>> dict(set(a.iteritems()) ^ set(b.iteritems())) {'a': 1, 'c': 3, 'd': 4} Peter -- http://mail.python.org/mailman/listinfo/python-list From p.f.moore at gmail.com Sun Dec 14 11:19:11 2008 From: p.f.moore at gmail.com (Paul Moore) Date: Sun, 14 Dec 2008 08:19:11 -0800 (PST) Subject: Looking for the best way to translate an idiom Message-ID: I'm translating some code from another language (Lua) which has multiple function return values. So, In Lua, it's possible to define a function function f() return 1,2,3 end which returns 3 values. These can then be used/assigned by the caller: a,b,c = f() So far, much like Python, but the key difference is that in Lua, excess arguments are ignored - so you can do a = f() or even a = f() + 1 where in the latter, a is 2 (as addition only needs 1 argument, so the extra ones are discarded). This results in the code which I'm trying to translate having functions which return multiple arguments, the first of which is the "main" result, and the following values are "extra" results (specifically, the position at which a match is found, followed by the "captured" values of the match). I'm trying to find a natural equivalent in Python. So far, I've considered the following: - return a tuple (pos, captures). This is messy, because you end up far too often unpacking the tuple and throwing away the second value - return an object with pos and captures attributes. This is better, as you can do match(...).pos to get the position alone, but it doesn't really feel "pythonic" (all those calls with .pos at the end...) - have 2 calls, one to return just the position, one to return both. This feels awkward, because of the 2 method names to remember. To make things worse, Lua indexes strings from 1, so it can use a position of 0 to mean "no match" - so that a simple "did it match?" test looks like if (match(....))... - where in Python I need if (matchpos(...) != -1)... (Although if I return a match object, I can override __nonzero__ to allow me to use the simpler Lua form). Can anyone suggest a good idiom for this situation? At the moment, I'm returning a match object (the second option) which seems like the least bad of the choices (and it mirrors how the re module works, which is somewhat useful). But I'd like to know what others think. If you were using a pattern matching library, what interface would you prefer? I suspect my intuition isn't accurate here, as most of the use I've made of the library is in writing tests, which isn't typical use :-( Thanks for any assistance. Paul From stef.mientki at gmail.com Tue Dec 30 15:16:39 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 30 Dec 2008 21:16:39 +0100 Subject: Triple quoted string in exec function ? In-Reply-To: References: <495A253B.6010003@gmail.com> Message-ID: <495A81A7.8030507@gmail.com> ibpet11 at gmail.com wrote: > On Dec 30, 2:48 pm, Steve Holden wrote: > >> Stef Mientki wrote: >> >>> hello, >>> >>> I'm running scripts, with the execute function (Python 2.5), >>> and it seems that triple quoted strings are not allowed. >>> >>> Is there a workaround, >>> or is this a fundamental problem of the exec-function ? >>> >> If you think about it, it should be obvious that you can't surround a >> string to be compiled with any of the quotes that appear inside the >> string to be compiled. That's about the only limitation I am aware of. >> >> And, by the way, exec is a *statement*, not a function! >> exec ( Init_Code, PG.P_Globals ) I've really doubt that this is a statement, unless I don't understand what a statement is. >> >>>>> exec """print '''This is >>>>> >> ... a long string''' >> ... """ >> This is >> a long string >> >> >> >> regards >> Steve >> -- >> Steve Holden +1 571 484 6266 +1 800 494 3119 >> Holden Web LLC http://www.holdenweb.com/ >> > > hello, > the message Steven sent you is ok to explain how to work with triple > quote > > Yes, but not to work around my problem. I guess I've to remove all triple quoted strings from my code. anyway thanks, Stef From wuwei23 at gmail.com Mon Dec 1 23:59:29 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 1 Dec 2008 20:59:29 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> Message-ID: <9baabb6c-daab-418e-a11f-9162e1fc30f7@k36g2000pri.googlegroups.com> On Dec 2, 2:18?pm, r wrote: > PS hey...even alex23's post are a little less mean. Either I am > wearing him down or he is beginning to believe :) Yes, my wishing your death by asphyxiation is "less mean" than my original post suggesting you do some work. Your lack of reading comprehension is another big indicator that you're a troll. Just die already. From stef.mientki at gmail.com Thu Dec 25 16:53:34 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 25 Dec 2008 22:53:34 +0100 Subject: Is there a function to remove escape characters from a string ? In-Reply-To: <0163882f$0$6988$c3e8da3@news.astraweb.com> References: <0163882f$0$6988$c3e8da3@news.astraweb.com> Message-ID: <495400DE.3000709@gmail.com> Steven D'Aprano wrote: > On Thu, 25 Dec 2008 11:00:18 +0100, Stef Mientki wrote: > > >> hello, >> >> Is there a function to remove escape characters from a string ? >> (preferable all escape characters except "\n"). >> > > > Can you explain what you mean? I can think of at least four alternatives: > I have the following kind of strings, the funny "?" is ASCII character 254, used as a separator character [FSM] Counts = "1?11?16" ==> 1,11,16 Init1 = "1?\BCtrl" ==> 1,Ctrl State5 = "8?\BJUMP_COMPL\b\n>PCWrite = 1\n>PCSource = 10" ==> 8, JUMP_COMPL\n>PCWrite = 1\n>PCSource = 10 Seeing and testing all your answers, with great solutions that I've never seen before, knowing nothing of escape sequences (I'm a windows guy ;-) I now see that the characters I need to remove, like \B and \b are not "official" escape sequences. So in this case the best (easiest to understand) method is a few replace statements: s = s.replace ( '\b', '' ).replace( '\B', '' ) Nevertheless, thank you all for the other examples, cheers, Stef > (1) Remove literal escape sequences (backslash-char): > "abc\\t\\ad" => "abcd" > r"abc\t\ad" => "abcd" > > > (2) Replace literal escape sequences with the character they represent: > "abc\\t\\ad" => "abc\t\ad" > > > (3) Remove characters generated by escape sequences: > "abc\t\ad" => "abcd" > "abc" => "abc" but "a\x62c" => "ac" > > This is likely to be impossible without deep magic. > > > (4) Remove so-called binary characters which are typically inserted using > escape sequences: > "abc\t\ad" => "abcd" > "abc" => "abc" but "a\x62c" => "abc" > > This is probably the easiest, assuming you have bytes instead of unicode. > > import string > table = string.maketrans('', '') > delchars =''.join(chr(n) for n in range(32)) > > s = string.translate(s, table, delchars) > > > > From mludvig at logix.net.nz Thu Dec 18 18:21:27 2008 From: mludvig at logix.net.nz (Michal Ludvig) Date: Fri, 19 Dec 2008 12:21:27 +1300 Subject: setup.py installs modules to a wrong place In-Reply-To: <494384EF.7050605@logix.net.nz> References: <494384EF.7050605@logix.net.nz> Message-ID: <494ADAF7.8050003@logix.net.nz> Ping! Does anyone know what the problem could be? The bug reported provided some more information recently... The modules have been installed to /usr/lib/python2.5/site-packages as show below. Apparently on his system /usr/lib/python2.5 is a symlink to /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5 While this directory *is* in sys.path, the .../site-packages one isn't, see below in my original post. So why did Python decide to put the modules there? Why not one of the directories that are in sys.path? Is this configurable somewhere? Thanks! Michal Michal Ludvig wrote: > Hi, > > I have recently seen some reports from users of my s3cmd script [1] who > installed the package using the provided distutils-based setup.py and > immediately after installation the script failed to run because it > couldn't find its modules. > > Here's an example session from Mac OS X, but similar behaviour has been > observed on Ubuntu as well. Needless to say it works for me just fine so > I can't easily debug and fix it :-( > > First is the reported setup.py output: > > ----- > ~/bin/s3cmd $ sudo python setup.py install > Password: > ... > running install_lib > creating /usr/lib/python2.5/site-packages > creating /usr/lib/python2.5/site-packages/S3 > copying build/lib/S3/PkgInfo.py -> /usr/lib/python2.5/site-packages/S3 > ... more modules, etc ... > ----- > > It decided to put the modules to /usr/lib/python2.5/site-packages/S3 > > Now, s3cmd should import from there, but fails: > > ~/bin/s3cmd $ s3cmd > Traceback (most recent call last): > File "/usr/bin/s3cmd", line 1207, in > from S3 import PkgInfo > ImportError: No module named S3 > > sys.path at the time the script died had these entries: > /usr/bin > /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python25.zip > /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5 > /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-darwin > /System/Library/Frameworks/Python.framework/Versions/2.5/...other_subdirs... > /Library/Python/2.5/site-packages > > There is nothing special in setup.py. After all have a look yourself: > http://s3tools.svn.sourceforge.net/viewvc/s3tools/s3cmd/trunk/setup.py?view=markup > > What could be the reason for distutils / setup.py to install the modules > to a directory that's not in sys.path? Can I detect it in setup.py and > prevent or workaround it somehow? > > Thanks! > > [1] http://s3tools.logix.cz/s3cmd -- Amazon S3 command line client > > Michal > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From saluk64007 at gmail.com Wed Dec 10 12:22:46 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Wed, 10 Dec 2008 09:22:46 -0800 Subject: "as" keyword woes In-Reply-To: <493FD8F6.3050803@mrabarnett.plus.com> References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> <493FD8F6.3050803@mrabarnett.plus.com> Message-ID: On Wed, Dec 10, 2008 at 6:57 AM, MRAB wrote: > Aaron Brady wrote: >> >> On Dec 9, 12:40 pm, MRAB wrote: >>> >>> Aaron Brady wrote: >>>> >>>> On Dec 9, 8:28 am, MRAB wrote: >>>> snip >>>>> >>>>> In some languages (I think Delphi is one of them - it's been a while!) >>>>> some words which would normally be identifiers have a special meaning >>>>> in >>>>> certain contexts, but the syntax precludes any ambiguity, and not in a >>>>> difficult way. "as" in Python was one of those. >>>>> I certainly wouldn't want something like PL/I, where "IF", "THEN" and >>>>> "ELSE" could be identifiers, so you could have code like: >>>>> IF IF = THEN THEN >>>>> THEN = ELSE; >>>>> ELSE >>>>> ELSE = IF; >>>>> Seehttp://en.wikipedia.org/wiki/PL/I_(programming_language). >>>> >>>> snip >>>> That is, 'certainly' doesn't change the meaning of your statement >>>> any. You wouldn't want it, but King George III didn't want the >>>> American Revolution. >>> >>> It's called emphasis. >> >> I just take you to have meant, then, +1 on excluding keywords from >> identifiers. You said it the long way though, so I thought I missed >> something deeper, that didn't come across. >> > IIRC, most computer languages have an LL(1) grammar, which means that when > they are parsed you need to look at only the next word. If you're about to > parse a statement and the next word is "IF" then you know it's an > IF-statement, if it's an identifier then it's either a call or an assignment > statement (OK, you don't know exactly what kind of statement it is at that > point, but it works out just fine!). > > In the example from PL/I, "IF" could be the start of an IF-statement "IF > THEN" or an assignment statement "IF = ". It's a bit > more tricky for the parser as well as the programmer. > > Life is easier if words having special meanings are reserved. > > However, that doesn't mean that all special words /must/ be reserved > (pragmatism beats purity). Sometimes the syntax makes it clear and > unambiguous, so you can get away with not making it a reserved word. The > word "as" in Python doesn't need to be reserved because the syntax precludes > ambiguity, but it's the only such word in the language, so it's just tidier > to make it reserved too. > -- > http://mail.python.org/mailman/listinfo/python-list > I don't have a huge stake in this, but I wouldn't mind a change to allow anything proceeding a "." or preceeding a "(" to not be identified as a keyword. It is obvious to me a s a human reader that something.if is quite a bit different than just a bare if. And as far as parsing technology goes, isn't it supposed to go for the biggest match first? I would not be for allowing bare keywords to be used in the situations described above, but since we are so used to being able to being able to have say, myclass.dir() or myclass.len() without them overwriting the builtin functions, it makes sense to me to be able to define a myclass.as() or myclass.with() without overwriting the keywords. Though I know the semantics behind these two things are very different, the rules I go through when reading the code are very similar. The parser change might be a hassle, and it might not be worth it at all of course, but from a conceptual point of view it is simple. I mean, even now you can do class.__dict__["as"]. I guess I'm -1 for full PL/1 craziness, but +1 for qualified keyword usage. From clp at rebertia.com Tue Dec 9 01:01:27 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 8 Dec 2008 22:01:27 -0800 Subject: Password input in console/terminal In-Reply-To: References: Message-ID: <47c890dc0812082201x771805d8o51f62ed451453430@mail.gmail.com> On Mon, Dec 8, 2008 at 9:53 PM, RP wrote: > Hello All, > > This is my first REAL post(question) to Python-List. I know I can take input > from a user with raw_input() > How do I take password input in console? Any Help would be Greatly > Appreciated. Thank You. RP You use the appropriately-named `getpass` module: http://docs.python.org/library/getpass.html Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From cournape at gmail.com Fri Dec 19 04:06:20 2008 From: cournape at gmail.com (David Cournapeau) Date: Fri, 19 Dec 2008 18:06:20 +0900 Subject: Python for amd64 and mingw-w64 In-Reply-To: <494B3F75.10104@v.loewis.de> References: <494B3F75.10104@v.loewis.de> Message-ID: <5b8d13220812190106v74de0f3ai11cb59fbabe5c2c0@mail.gmail.com> On Fri, Dec 19, 2008 at 3:30 PM, "Martin v. L?wis" wrote: > > It's a mistake if libpython26.a gets included in the Win64 installer > at all; this library is only provided for 32-bit systems. My copy of > mingw doesn't support Win64 at all. Please ignore that last point: it looks like it is generated by our (numpy) build process, and has nothing to do with python per-se. David From hniksic at xemacs.org Fri Dec 12 20:20:59 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sat, 13 Dec 2008 02:20:59 +0100 Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> Message-ID: <87iqpoc1l0.fsf@mulj.homelinux.net> sturlamolden writes: > What? Take a look at the code again: > > mytuple[0] += 1 > > should never attempt an __iadd__ on mytuple. > > A sane parser would see this as: > > tmp = mytuple.__getitem__(0) > tmp = tmp.__iadd__(1) > mytuple.__setitem__(0, tmp) # should this always raise an exception? What do you mean by "a sane parser"? This is exactly what happens in current Python. Since tuple's __setitem__ always raises an exception (and that is by design and not likely to change), everything is sane. Saner (in this respect) behavior in the tuple example would require a different protocol. I don't understand why Python doesn't just call __iadd__ for side effect if it exists. The decision to also rebind the result of __i*__ methods continues to baffle me. I guess it is a result of a desire to enable the __i*__ methods to punt and return a different instance after all, but if so, that design decision brings more problems than benefits. From ldo at geek-central.gen.new_zealand Wed Dec 3 20:07:46 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 04 Dec 2008 14:07:46 +1300 Subject: Don't you just love writing this sort of thing :) Message-ID: for \ Entry \ in \ sorted \ ( f for f in os.listdir(PatchesDir) if PatchDatePat.search(f) != None ) \ : Patch = (open, gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir, Entry), "r") ... read from Patch ... Patch.close() #end for From acerimusdux at comcast.net Sun Dec 7 02:49:27 2008 From: acerimusdux at comcast.net (acerimusdux) Date: Sun, 07 Dec 2008 02:49:27 -0500 Subject: Guido's new method definition idea In-Reply-To: <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> Message-ID: <493B8007.9040608@comcast.net> Russ P. wrote: > Python already uses shorthand extensively. How about "def"? For people > who are so worried about self-explanatory symbols, what the heck does > that stand for? Default? Defeat? Defect? Defunct? Defer? > > > I think the difference here is that those other abbreviations are mostly fairly standard. The "def" keyword is the same in Ruby, and similar enough to "define" or "defun" in Scheme or LISP. The "!=" operator is pretty much standard across nearly all languages. What is being proposed with "$" here though, would be different from how it is used anywhere else and would be confusing. Moreover, I especially don't like proposing to eliminate as well in this instance the "dot notation", which is standard in nearly all object oriented languages. Using something as a substitute for "self" is one thing, and you can mostly use what you like there now, as "self" is more a convention than a requirement. But the "dot" that belongs there is critical to understanding, you can't hide that to save one keystroke. Getting back to Guido's suggestion, though, I think it makes some sense. Being new to Python, I did find myself occasionally forgetting "self" in instance methods. But, I also thought the requirement to include it was helpful in reminding me what was really going on there, that I was creating an instance method which was really a function that wouldn't actually be created until the instance was initiated. I tend to think this may be clearer though using the dot notation rather than passing the instance variable as a parameter. I'm not sure though whether allowing both syntaxes would make things more or less confusing. It might actually be helpful in some respects for newcomers to realize that self.method(arg) is somewhat the same as method(self, arg). Perhaps I'm wrong on this, I don't fully understand yet what is going on under the hood, but it seems to me that that would be part of the glue that allows Python to be so multi-paradigm; much of the difference between OOP and procedural or functional is just different syntax for the same thing. From r.grimm at science-computing.de Sat Dec 6 03:59:07 2008 From: r.grimm at science-computing.de (r.grimm at science-computing.de) Date: Sat, 6 Dec 2008 00:59:07 -0800 (PST) Subject: Pythonic design patterns References: Message-ID: <815c6e46-283f-44c3-ba78-b1f9223dd48b@v13g2000yqm.googlegroups.com> Hallo, > users in this forum has been kind enough to point out. Only my > implementations are often not that clean, and I may call things > something different than the normal convention, which is a source of > confusion for myself and others trying to communicate with me. I think, you should start with the classical books of Design Patterns to get a solid understanding and especially vocabulary to communicate with your coworkers. Its easier and better to say, that you will use a strategy pattern than to describe the architecture in many sentences to your partner in a ambigious way. Thats in my opinion the first and the key benefit of Design Patterns. Speaking in the same language. The next step should be to apply your knowledge to your programming language. So I will recommend the classical GOF Books and the serie Pattern Oriented Software Architecture. Greetings Rainer From ipytest at gmail.com Thu Dec 18 11:08:32 2008 From: ipytest at gmail.com (ipytest at gmail.com) Date: Thu, 18 Dec 2008 08:08:32 -0800 (PST) Subject: Is this pythonic? Message-ID: <66d058f9-cfe1-4b3c-ab8a-e6e88bb97770@m22g2000vbp.googlegroups.com> x.validate_output(x.find_text(x.match_filename (x.determine_filename_pattern(datetime.datetime.now())))) Is it even good programming form? From rt8396 at gmail.com Tue Dec 23 11:25:04 2008 From: rt8396 at gmail.com (r) Date: Tue, 23 Dec 2008 08:25:04 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: <30b5b812-0600-4cf9-9e37-f456a99947ef@a29g2000pra.googlegroups.com> On Dec 23, 8:21?am, Thorsten Kampe wrote: > You don't have a single clue about neither Python nor Ruby: > 'According to the Ruby FAQ, "If you like Perl, you will like Ruby and be > right at home with its syntax. [...] If you like Python, you may or may > not be put off by the huge difference in design philosophy between > Python and Ruby/Perl."'[1] So you read the preface to the tut and that somehow makes you more than a R00b n00b? Come on! From tommy.nordgren at comhem.se Tue Dec 23 16:05:10 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Tue, 23 Dec 2008 22:05:10 +0100 Subject: Get applications to open a given file (Mac and, or Windows) In-Reply-To: References: Message-ID: On Dec 23, 2008, at 5:29 PM, riklaunim at gmail.com wrote: > Under Linux/Unix I use GIO (pygobject) or gnome-vfs-python to get a > list of installed applications that can open given file (for example > image in graphics software). Is there something that can be used for > MS Windows or Mac OS X? > -- > http://mail.python.org/mailman/listinfo/python-list On mac, there are the modules Carbon.Launch and Carbon.LaunchServices Maybe you'll find useful items in the PyObjC framework as well ------------------------------------- This sig is dedicated to the advancement of Nuclear Power Tommy Nordgren tommy.nordgren at comhem.se From cournape at gmail.com Fri Dec 12 05:37:41 2008 From: cournape at gmail.com (David Cournapeau) Date: Fri, 12 Dec 2008 19:37:41 +0900 Subject: Building extensions for python 2.6 adm64 with the SDK compiler Message-ID: <5b8d13220812120237i7f84585bmf9bc9489327e44ae@mail.gmail.com> Hi, I have some trouble building python 2.6 extensions with the SDK compiler on windows 64 bits. The problem is that after link step, mt.exe is called to embed the MANIFEST into the executable, but the manifest is not created, so the build fails with a "general error c1010070:Failed to load and parse the manifest". I am a bit confused: - I thought that manifest should not be embedded in .pyd (http://bugs.python.org/issue4120), but the code of msvc9compiler.py in distutils suggests otherwise, and uses the option /MANIFESTFILE (which only changes the name of the manifest, according to MSDN). - Is this specific to the SDK compiler ? E.g. does the native VS compiler on 64 bits have the same problem ? I guess not, because people would have complained before, I guess. If I manually add the /MANIFEST file to the link options, the build does work, David From sjmachin at lexicon.net Thu Dec 11 18:49:10 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 11 Dec 2008 15:49:10 -0800 (PST) Subject: newbie question: if var1 == var2: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> Message-ID: On Dec 12, 10:31?am, "Rhodri James" wrote: > On Thu, 11 Dec 2008 19:49:23 -0000, Steve Holden ? > wrote: > > > > > Kirk Strauser wrote: > >> At 2008-11-29T04:02:11Z, Mel writes: > > >>> You could try > > >>> for item in fname: > >>> ? ? item = item.strip() > > >> This is one case where I really miss Perl's "chomp" function. ?It ? > >> removes a > >> trailing newline and nothing else, so you don't have to worry about ? > >> losing > >> leading or trailing spaces if those are important to you. > > > ... and it's so hard to write > > > ? ? ?item = item[:-1] > > Tsk. ?That would be "chop". ?"chomp" would be > > ? ? ?if item[-1] == '\n': > ? ? ? ? ?item = item[:-1] Better: if item and item[-1] == '\n': return item[:-1] return item From nicolas.chauvat at logilab.fr Tue Dec 30 09:05:18 2008 From: nicolas.chauvat at logilab.fr (nchauvat (Logilab)) Date: Tue, 30 Dec 2008 06:05:18 -0800 (PST) Subject: [ANN] release of CubicWeb 3.0.0 Message-ID: <2f5ba08e-5f8d-42fe-b25f-35b5686e595d@r10g2000prf.googlegroups.com> The development team is pleased to announce the release of CubicWeb 3.0.0 (nicknamed ShowTime). What is CubicWeb? ----------------- With CubicWeb, the Semantic Web is a construction game! CubicWeb_ is a semantic web application framework, licensed under the LGPL, that empowers developers to efficiently build web applications by reusing components (called cubes) and following the well known object-oriented design principles. Its main features are: * an engine driven by the explicit data model of the application, * a query language named RQL similar to W3C?s SPARQL, * a selection+view mechanism for semi-automatic XHTML/XML/JSON/ text generation, * a library of reusable components (data model and views) called cubes that fulfill common needs, * the power and flexibility of the Python programming language, * the reliability of SQL databases, LDAP directories, Subversion and Mercurial for storage backends. Being built since 2000 by an R&D project still going on today, supporting 100,000s of daily visits at some production sites, CubicWeb is a proven end to end solution for semantic web application development that promotes quality, reusability and efficiency. The unbeliever will read the quick overview_ of CubicWeb. The hacker will join development at the forge_. The impatient will move right away to installation_ and set-up of a CubicWeb environment. .. _cubicweb: http://www.cubicweb.org/ .. _overview: http://www.cubicweb.org/doc/en/A020-tutorial.en.html#overview .. _forge: http://www.cubicweb.org/project?vtitle=All%20cubicweb%20projects .. _installation: http://www.cubicweb.org/doc/en/C010-setup.en.html#miseenplaceenv Home page --------- http://www.cubicweb.org/ Download -------- http://ftp.logilab.org/pub/cubicweb/ Mailing list ------------ http://lists.cubicweb.org/mailman/listinfo/cubicweb Licence ------- LGPL - Lesser General Public Licence From arnodel at googlemail.com Wed Dec 10 16:59:13 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 10 Dec 2008 21:59:13 +0000 Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: cm_gui writes: [stuff] > Python is slow. Very slow. The same troll started this same flame earlier this year: http://groups.google.com/group/comp.lang.python/browse_thread/thread/5cea684680f63c82?q= -- Arnaud From __peter__ at web.de Tue Dec 9 13:05:49 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Dec 2008 19:05:49 +0100 Subject: StringIO in 2.6 and beyond References: Message-ID: Bill McClain wrote: > I've just installed 2.6, had been using 2.4. > > This was working for me: > > #! /usr/bin/env python > import StringIO > out = StringIO.StringIO() > print >> out, 'hello' > > I used 2to3, and added import from future to get: > > #! /usr/bin/env python > from __future__ import print_function > import io > out = io.StringIO() > print('hello', file=out) > > ...which gives an error: > > Traceback (most recent call last): > File "./example.py", line 5, in > print('hello', file=out) > File "/usr/local/lib/python2.6/io.py", line 1487, in write > s.__class__.__name__) > TypeError: can't write str to text stream > > ...which has me stumped. Why can't it? >>> from __future__ import print_function >>> import io >>> out = io.StringIO() >>> print("hello", file=out) Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.6/io.py", line 1487, in write s.__class__.__name__) TypeError: can't write str to text stream Seems io.StringIO() wants unicode. So let's feed it some: >>> print(u"hello", file=out) Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.6/io.py", line 1487, in write s.__class__.__name__) TypeError: can't write str to text stream Still complaining? Let's have a look at the output so far: >>> out.getvalue() u'hello' Hmm, u"hello" was written. The complaint must be about the newline then. >>> out = io.StringIO() >>> print(u"hello", file=out, end=u"\n") >>> out.getvalue() u'hello\n' Heureka. Let's try something else now: >>> print(u"hello", u"world", file=out, end=u"\n") Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.6/io.py", line 1487, in write s.__class__.__name__) TypeError: can't write str to text stream Fixing is left as exercise ;) Peter From gruszczy at gmail.com Sat Dec 13 06:50:03 2008 From: gruszczy at gmail.com (=?UTF-8?Q?Filip_Gruszczy=C5=84ski?=) Date: Sat, 13 Dec 2008 12:50:03 +0100 Subject: Removing None objects from a sequence In-Reply-To: <01538f0c$0$6988$c3e8da3@news.astraweb.com> References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> <4942E668.5030100@tim.thechases.com> <01538f0c$0$6988$c3e8da3@news.astraweb.com> Message-ID: <1be78d220812130350u53e0c334i562abbf1fe0a0701@mail.gmail.com> Just to be clear, I decided to use generator by alex23, as it seems simple, short and understandable. Still reading this thread was quite interesting, thanks :-) -- Filip Gruszczy?ski From honey33145 at gmail.com Fri Dec 12 00:52:45 2008 From: honey33145 at gmail.com (navneet khanna) Date: Fri, 12 Dec 2008 11:22:45 +0530 Subject: concept of creating structures in python Message-ID: Hello Everybody I want to create a structure within a structure i.e. nested structures in python. I tried with everything but its not working. my code is like this: class L(Structure): def __init__(self,Name='ND',Addr=0,ds_obj = D()): self.Name = Name self.Addr = Addr self.ds_obj = ds_obj class D(Structure): def __init__(self,dataName='ND',index = 0,ele_obj=E()): self.dataName = dataName self.index = index self.ele_obj = ele_obj these are two structures. I want to refer D structure in L one and use it. I want to access the value of D structure like L.D.index = 0. Please help me Thanks in advance Navneet -------------- next part -------------- An HTML attachment was scrubbed... URL: From xahlee at gmail.com Sun Dec 28 22:06:59 2008 From: xahlee at gmail.com (Xah Lee) Date: Sun, 28 Dec 2008 19:06:59 -0800 (PST) Subject: HTML Correctness and Validators Message-ID: <2fb289be-00b3-440a-b153-ca88f0ba16c5@d42g2000prb.googlegroups.com> recently i wrote a blog essay about html correctness and html validators, with relations to the programing lang communities. I hope programing lang fans will take more consideration on the correctness of the doc they produces. HTML Correctness and Validators ? http://xahlee.org/js/html_correctness.html plain text version follows. --------------------------- HTML Correctness and Validators Xah Lee, 2008-12-28 Some notes about html correctness and html validator. Condition Of Website Correctness My website ?xahlee.org? has close to 4000 html files. All are valid html files. ?Valid? here means passing the w3c's validator at http://validator.w3.org/. Being a programing and correctness nerd, correct html is important to me. (correct markup has important, practical, benefits, such as machine parsing and transformation, as picked up by the XML movement. Ultimately, it is a foundation of semantic web?.) In programing lang communities, the programer tech geekers are fanatical about their fav lang's superiority, and in the case of functional langs, they are often proud of their correctness features. However, a look at their official docs or websites, they are ALL invalid html, with errors in just about every 10 lines of html source code. It is fucking ridiculous. In the web development geeker communities, you can see how they are tight-assed about correct use of HTML/CSS, etc, where there are often frequent and heated debates about propriety of semantic markup, and they don't hesitate to ridicule Microsoft Internet Explorer browser, or the average HTML content producer. However, a look at the html they produced, also almost none are valid. The bad html also happens in vast majority of docs produced by organization of standards, such as the Unicode Consortium?, IETF?. For example, if you run w3c's validator on their IETF's home page, there are 32 errors, including ?no doctype found?, and if you validate unicode's http://www.unicode.org/faq/utf_bom.html, there are 2 errors. (few years ago, they are much worse. I don't think even ?w3.org?'s pages are valid back then.) In about 2006, i spent few hours research on what major websites produces valid html. To this date, I know of only one major site that produces valid html, and that is Wikipedia. This is fantastic. Wikipedia is produced by MediaWiki? engine, written in PHP. Many other wiki sites also run MediaWiki, so they undoubtfully are also valid. As far as i know, few other wiki or forum software also produces valid html, though they are more the exceptions than norm. (did try to check 7 random pages from ?w3.org?, looks like they are all valid today.) Personal Need For Validator My personal need is to validate typically hundreds of files on my local drive. Every month or so, i do systematic regex find-replace operation on a dir. This often results over a hundred changed files. Every now and then, i improve my css or html markup semantics site wide, so the find-replace is on all 4000 files. Usually the find- replace is carefully crafted with attention to correctenss, or done in emacs interactively, so possible regex screwup is minimal, but still i wish to validate by batch after the operation. Batch validation is useful because, if i screwed up in my regex, usually it ends up with badly formed html, so html validation can catch the result. In 2008, i converted most my sites from html 4 transitional to html 4 strict. The process is quite a manual pain, even the files i start with are valid. Here are some examples. In html4strict: * ??br?? must be inside block level tags. Image tag ??img ...?? needs to be enclosed in a block level tag such as ??div??. Content inside blockquote must be wrapped with a block level tag. e.g. ??blockquote?Time Flies?/blockquote?? would be invalid in html4strict; you must have ??blockquote??p?Time Flies?/p??/blockquote?? Lets look at the image tag example. You might think it is trivial to transform because you can simply use regex to wrap a ??div?? to image tags. However, it's not that simple. Because, for example, often i have this form: ?img src="pretty.jpg" alt="pretty girl" width="565" height="809"? ?p?above: A pretty girl.?/p? The ?p? tag immediately below a ?img? tag, functions as the image's caption. I have css setup so that this caption has no gap to the image above it, like this: img + p {margin-top:0px;width:100%} /* img caption */ I have the ?width:100%? because normally ?p? has ?width:80ex? for normal paragraph. Now, if i simply wrap a ?div? tag to all my ?img? tags, i will end up with this form: ?div??img src="pretty.jpg" alt="pretty girl" width="565" height="809"??/div? ?p?above: A pretty girl.?/p? Now this screws up with my caption css, and there's no way to match ?p? that comes after a ?div ? img?. Also, sometimes i have a sequence of images. Wrapping each with a ?div? would introduce gaps between them. This is just a simplified example. In short, converting from html4transitional to html4strict while hoping to retain appearance or markup semantics in practical ways is pretty much a manual pain. (the ultimate reason is because html4transitional is far from being a good semantic markup. (html4strict is a bit better)) Validators In my work i need a batch validator. What i want is a command line utility, that can batch validate all files in a dir. Here are some solutions related to html validation. * The standard validator service by w3c: http://validator.w3.org/ (see also: W3C Markup Validation Service? ). The problem with this is that it can't validate local files, and can't do in batch. Using it to validate 4000 files thru network (with a help of perl script) would not be acceptable, since each job means massive web traffic. (my site is near 754 Mebibyte?.) * FireFox has a ?Html Validator? add-on by Marc Gueury. https://addons.mozilla.org/en-US/firefox/addon/249. This is based on the same code as w3c validator, can work on local files, is extremely fast. When browsing any page, it shows a green check mark on the window corner when the file is valid. I heavily rely on this tool. * FireFox has a ?Web Developer? add-on by Chris Pederick. https://addons.mozilla.org/en-US/firefox/addon/60 Since Firefox ?v.3?, it has a icon that indicates if a page's css and javascript are invalid (has errors), and also indicates whether the file is using Quirks mode?. I heavily rely on this tool. I heavily relie on the above 2 FireFox tools. However, the FireFox tools do not let me do batch validation. Over the years i've searched for batch validation tools. Here's some list: * HTML Tidy? A batch tool primarily for cleanup html markup. I didn't find it useful for batch validation purposes, nor for html conversion jobs. It doesn't do well for my html conversion needs because the tool is incapable of retaining your html formatting (i.e. retain your newlines locations). I do a lot regex based text procesing on my html files, so i need assumptions about how newlines are in my html files. If i use tidy on my site, that means i have to abandon regex based text processing, and instead, have to treat my files using html and dom parsers, which makes most practical text processing needs quite more complex and cumbersome. * A perl module ?HTML::Lint?, at http://search.cpan.org/~petdance/HTML-Lint-2.06/lib/HTML/Lint.pm. Seems pretty much like HTML Tidy. * http://htmlhelp.com/tools/validator/offline/index.html.en is another validation tool. I haven't looked into yet. Their doc about differences to other validator: http://htmlhelp.com/tools/validator/differences.html.en, is quite interesting, and seems a advantage for my needs. * OpenJade and OpenSP. http://openjade.sourceforge.net/ Seems a good tool. Haven't looked into. * Emacs's nxml mode http://www.thaiopensource.com/nxml-mode/, by the xml expert James Clark?. This is written in elisp with over 10 thousand lines of code. It indicates whether your xml file is valid as you type. This package is very well received, reputed to make emacs the best xml editor. This is fantastic, but since my files are currently html not xhtml, so i haven't used this much. There are emacs html modes based on this package, called nxhtml mode, but the code is still pretty alpha and i find it having a lot problems. One semi solution for batch validation i found is: ?Validator S.A.C.?, at http://habilis.net/validator-sac/. It is basically w3c's validator compiled for OS X with a GUI interface. However, this is not designed for batch operation. If you want to do batch, i run it like this: ?/ Applications/Validator-SAC.app/Contents/Resources/weblet ?html file path??. However, it output a whole report in html on the validation result (same as the page you see in w3c validation). This is not what i want. What i want is simply for it to tell me if a file is valid or not. For any error detail, i can simply load the page in FireFox myself, since if i need to edit it i need to view it in FireFox anyway. So, to fix this problem, you can wrap a perl script, which takes a dir and simply print any file path that's invalid. Here's the perl script: # perl # 2008-06-20 validates a given dir's html files recursively requires the mac os x app Validator-SAC.app at http://habilis.net/validator-sac/ as of 2008-06 use strict; use File::Find; my $dirPath = q(/Users/xah/web/emacs); my $validator = q(/Applications/ Validator-SAC.app/Contents/Resources/weblet); sub wanted { if ($_ =~ m{\.html$} && not -d $File::Find::name) { my $output = qx{$validator "$File::Find::name" | head -n 11 | grep 'X-W3C-Validator-Status:'}; if ($output ne qq(X-W3C-Validator-Status: Valid\n)) { print q (Problem: ), $File::Find::name, "\n"; } else { print qq(Good: $_) ,"\n"; } } } find(\&wanted, $dirPath); print q(Done.) However, for some reason, ?Validator S.A.C.? took nearly 2 seconds to check each file, in contrast, the FireFox html validator add-on took a fraction of a second while also render the whole page completely. For example, suppose i have 20 files in a dir i need to validate. It's faster, if i just open all of them in FireFox and eyeball the validity indicator, then running the ?Validator SAC? on them. I wrote to its author Chuck Houpt about this. It seems that the validator uses Perl and loads about 20 heavy duty web related perl modules to do its job, and over all is wrapped as a Common Gateway Interface?. Perhaps there is a way to avoid these wrappers and call the parser or validator directly. I'm still looking for a fast, batch, html validation tool. ----------------- Xah ? http://xahlee.org/ ? From lolekk12233 at wp.pl Fri Dec 5 15:00:34 2008 From: lolekk12233 at wp.pl (girl18) Date: Fri, 5 Dec 2008 12:00:34 -0800 (PST) Subject: Pretty young girl enjoy fucking - Video Message-ID: <1b33238a-5e98-44b8-a595-c8aa500eabb1@s9g2000prm.googlegroups.com> http://yeba.pl/show/movies/5257/Perfect_babe_-_Idealna_kobieta From mnations at gmail.com Thu Dec 11 20:05:15 2008 From: mnations at gmail.com (Mudcat) Date: Thu, 11 Dec 2008 17:05:15 -0800 (PST) Subject: PyQt: Pulling Abstract Item Data from Mime Data using Drag and Drop. Message-ID: <150086b2-b02d-4204-8c06-b08c0aa119c4@k1g2000prb.googlegroups.com> I'm trying to drag/drop info from a TreeWidget into a TextBox. I have been able to modify the TextEdit box to override the dragEnterEvent like this: class TextEdit(QtGui.QTextEdit): def __init__(self, title, parent): QtGui.QTextEdit.__init__(self, title, parent) self.setAcceptDrops(True) def dragEnterEvent(self, event): if event.mimeData().hasFormat('text/plain'): event.accept() elif (event.mimeData().hasFormat("application/x- qabstractitemmodeldatalist")): print event itemData = event.mimeData().retrieveData("application/x- qabstractitemmodeldatalist", QtCore.QVariant.List) The drag is working up until the point I try to actually retrieve the data. At that point I get an unhandled Runtime Error saying "no access to protected functions or signals for objects not created in Python". Obviously I am not retrieving them in the correct format. Does anyone know how to convert/retrieve the information into a Python list? Thanks From RBQG84 at motorola.com Tue Dec 30 05:17:24 2008 From: RBQG84 at motorola.com (Narasimhan Raghu-RBQG84) Date: Tue, 30 Dec 2008 18:17:24 +0800 Subject: string in files In-Reply-To: <9cda24d9-7a88-45db-b23c-fb43b7d567d4@r37g2000prr.googlegroups.com> Message-ID: <7FAD6FCE52421841A11B441DEF3A88CA01F0910A@ZMY16EXM70.ds.mot.com> Simple solution: us result=yourString.split(" ") and you get a list with all the words. -----Original Message----- From: python-list-bounces+rbqg84=motorola.com at python.org [mailto:python-list-bounces+rbqg84=motorola.com at python.org] On Behalf Of ibpet11 at gmail.com Sent: Tuesday, December 30, 2008 3:43 PM To: python-list at python.org Subject: string in files guys i need info on how to call up different words in a line of a file using python example : file = 'this is a python coding group' i want to assign a xter to this, is, a, python , coding and group thanks -- http://mail.python.org/mailman/listinfo/python-list From news123 at free.fr Sun Dec 7 07:11:14 2008 From: news123 at free.fr (News123) Date: Sun, 07 Dec 2008 13:11:14 +0100 Subject: python book for non technical absolute beginner In-Reply-To: <493a7c6a$0$973$426a34cc@news.free.fr> References: <493a7c6a$0$973$426a34cc@news.free.fr> Message-ID: <493bbd62$0$14452$426a34cc@news.free.fr> Thanks for your answers, I'll look at - "Python Programming, for the absolute beginner (second edition by MichaelDawson." and at the LiveWires Course: http://www.livewires.org.uk/python/home I looked at http://www.greenteapress.com/thinkpython/thinkCSpy/ but think it's not a good choice for a non engineer, as this course tries to explain many principles, which are not really needed to get started. AN example is recursion. Recursion is important but confuses easily. I remember still how quite some people at school disconencted mentally when the teacher tried to explain the 'mathematical induction'. bye N News123 wrote: > Hi, > > One of my 'non technical' friends complained about knowing nothing at > all about programming (though using computers regularly for mails / web > browsing / googling and downloading / cropping photos ) > > He wants to play a little with programming to stimulate parts of his > otehrwise idle brain cells. ;-) Normally it's more the social science / > linguistic parts being exercised, > > I thought python might be a nice language for this > > No my question does anybody know a nice beginners book (or a learning CD > or on line tutorial)? Ideally it shouldn't be too serious and have a lot > of small nice mini-examples > > thanks in advance for any suggestions hints > > > bye > > > N From manu3d at gmail.com Thu Dec 11 11:07:45 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 11 Dec 2008 08:07:45 -0800 (PST) Subject: Preventing execution of a method Message-ID: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> Sorry if I'm a bit thick here... can any of the esteemed participant in this noble newsgroup confirm that is not possible to prevent a python module's code from executing the methods of another module? I.e. if I have a class with two methods, doSomethingSafe() and doSomethingDangerous(), is there a way to prevent another module from executing doSomethingDangerous() but allow the execution of doSomethingSafe()? My understanding is that in python this is not possible. Can you confirm? Manu From cjw at ncf.ca Sun Dec 7 08:20:41 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sun, 07 Dec 2008 08:20:41 -0500 Subject: var or inout parm? In-Reply-To: References: Message-ID: mh at pixar.com wrote: > How can I make a "var" parm, where the called function can modify > the value of the parameter in the caller? > > def f(x): > x = x + 1 > > n = 1 > f(n) > # n should now be 2 > > Many TIA!! > Mark > > Why not run it and see? Your function returns None. The function in effect takes a copy of n. n is not changed. Colin W. From bruno.42.desthuilliers at websiteburo.invalid Wed Dec 31 06:59:18 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 31 Dec 2008 12:59:18 +0100 Subject: Pass by reference In-Reply-To: <529e1d98-8932-49f0-b569-85285bd50f23@p2g2000prn.googlegroups.com> References: <529e1d98-8932-49f0-b569-85285bd50f23@p2g2000prn.googlegroups.com> Message-ID: <495b5e88$0$3491$426a74cc@news.free.fr> iu2 a ?crit : > Hi, > > Is it possible somehow to change a varible by passing it to a > function? For which definition of "change a variable" ? > I tried this: > > def change_var(dict0, varname, val): > dict0[varname] = val Ok, this is mutating dict0, so it works. > > def test(): > a = 100 > change_var(locals(), 'a', 3) Please (re)read the doc for locals(): http://www.python.org/doc/2.6/library/functions.html#locals See the big warning ? > print a > > But test() didn't work, It did. The problem is elsewhere. > the value a remains 100. > > I have several variables initialized to None. Where ? > I need to convert each one of them an object only if it is None. > something like: > > if not var1: var1 = MyObject() Warning : some objects can eval to false in a boolean context without being None. Better to explicitely test identity here: if var1 is None: var1 = Something() > I want this to be a function, that is: > > def create_obj(var): > if not var: var = MyObj() This is a rebinding, not a mutation. Here, 'var' is a local *name*, so rebinding it will only affect the local namespace. > # set properties of var Why don't you use the initializer of MyObj here ? class MyObj(object): def __init__(self, prop1, propx): # set properties of self self.prop1 = prop1 self.propx = propx Then just call: var = MyObj(somevalue, someothervalue) > Now, I know I can achieve this by functional programming, ??? > def create_obj(var): > if not var: > x = MyObj() > # set properties of x > return x > return var This is just a plain function. You may want to re-read the definition of "functional programming" !-) > and then > > var = creaet_obj(var) > > Is there another way? What's wrong with this one ? From steve at REMOVE-THIS-cybersource.com.au Wed Dec 31 18:02:18 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Dec 2008 23:02:18 GMT Subject: math module for Decimals References: <01671a9e$0$6988$c3e8da3@news.astraweb.com> <016721cc$0$6988$c3e8da3@news.astraweb.com> Message-ID: <016bf0f4$0$6988$c3e8da3@news.astraweb.com> On Sun, 28 Dec 2008 06:38:32 -0800, Mark Dickinson wrote: > On Dec 28, 7:28?am, Steven D'Aprano cybersource.com.au> wrote: >> Ah crap, I forgot that from_float() has been left out of the decimal >> API. That's very annoying. > > Agreed. It's maybe even annoying enough that a feature request at > bugs.python.org might be honoured. (Hint, hint!) I can take a hint :) http://bugs.python.org/issue4796# Thank you for looking at this. -- Steven From castironpi at gmail.com Wed Dec 31 18:22:13 2008 From: castironpi at gmail.com (Aaron Brady) Date: Wed, 31 Dec 2008 15:22:13 -0800 (PST) Subject: multiprocessing vs thread performance References: Message-ID: <04a86770-262c-499a-92d3-3ffa76434503@a29g2000pra.googlegroups.com> On Dec 29, 9:29?am, mk wrote: > Christian Heimes wrote: > > mk wrote: > >> Am I doing smth wrong in code below? Or do I have to use > >> multiprocessing.Pool to get any decent results? > > > You have missed an important point. A well designed application does > > neither create so many threads nor processes. > > Except I was not developing "well designed application" but writing the > test the goal of which was measuring the thread / process creation cost. > > > The creation of a thread > > or forking of a process is an expensive operation. > > Sure. The point is, how expensive? While still being relatively > expensive, it turns out that in Python creating a thread is much, much > cheaper than creating a process via multiprocessing on Linux, while this > seems to be not necessarily true on Mac OS X. > > > You should use a pool > > of threads or processes. > > Probably true, except, again, that was not quite the point of this > exercise.. > > > The limiting factor is not the creation time but the communication and > > synchronization overhead between multiple threads or processes. > > Which I am probably going to test as well. I had an idea. You could use 'multiprocessing' for synchronization, and just use an mmap for the actual communication. (I think it's a good idea.) From castironpi at gmail.com Wed Dec 31 18:24:56 2008 From: castironpi at gmail.com (Aaron Brady) Date: Wed, 31 Dec 2008 15:24:56 -0800 (PST) Subject: greenlets and how they can be used References: Message-ID: <2cb20fad-c9be-4fe8-9cb7-e7ff91a67649@z28g2000prd.googlegroups.com> On Dec 30, 9:40?pm, "James Mills" wrote: > Hey all, > > The "greenlet" fromhttp://codespeak.net/py/dist/greenlet.html > is a rather interesting way of handling flow of control. > > I can't seem to find anything else on the subject > except for the above link and the most recent version > 0.2 and it's tests. > > What can "greenlet"'s be used for ? What use-cases > have you guys used them for (if any) ? > > Can they be used in place of threads with much > the same effect - ?but more lightweight ? I don't know Erlang, but it seems to be useful for a construction of a unit of work that is more consistent with the underlying goal. I had a dream for a while that in a GUI framework, every event would spawn a unique thread. The GUI would remain responsive even while executing minor tasks. Of course, shaving a second off running time isn't exactly mission-critical to GUI users. From castironpi at gmail.com Wed Dec 31 18:28:53 2008 From: castironpi at gmail.com (Aaron Brady) Date: Wed, 31 Dec 2008 15:28:53 -0800 (PST) Subject: Easy-to-use Python GUI References: Message-ID: <0b4ba5a4-ac79-4f11-8885-d163fb1a84f0@i18g2000prf.googlegroups.com> On Dec 29, 5:49?pm, "Joel Koltner" wrote: > Thanks to everyone who responded; I'll be checking out the various toolkits > people have listed! > > ---Joel There is wxFormBuilder, which stores a GUI design in XML format. It may be lengthy, but your data reside in a data structure, and your program resides in a program structure. From Scott.Daniels at Acm.Org Wed Dec 31 18:30:30 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 31 Dec 2008 15:30:30 -0800 Subject: How to initialize an array with a large number of members ? In-Reply-To: <5m4nl4hs8f9q6rfcp7b1jt7nk1o6sq6r0f@4ax.com> References: <5m4nl4hs8f9q6rfcp7b1jt7nk1o6sq6r0f@4ax.com> Message-ID: David Lemper wrote: > ... Python. Using version 3.0 > # script23 > from array import array > < see failed initialization attempts below > > tally = array('H',for i in range(75) : [0]) > tally = array('H',[for i in range(75) : 0]) > tally = array('H',range(75) : [0]) > tally = array('H',range(75) [0]) > Above give either Syntax error or TypeError > > All examples of sequences in docs show only a few members > being initialized. Array doc says an iterator can be used, > but doesn't show how. First, [1,2,3] is iterable. You could look up iterators or generators or list comprehension, but since it's the holidays: import array tally = array.array('H', (0 for i in range(75)))# a generator tally = array.array('H', [0 for i in range(75)])# list comprehension > What would you do for a 2 dimensional array ? You'll have to wait for numpy for the most general 2-D, but for list-of-array: square = [array.array('H', (i * 100 + j for j in range(75))) for i in range(75)] square[4][8] From benjamin.kaplan at case.edu Wed Dec 31 18:30:43 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 31 Dec 2008 18:30:43 -0500 Subject: type conversion In-Reply-To: <016be89e$0$6988$c3e8da3@news.astraweb.com> References: <4b7188db-63b2-4ac5-80cb-d1326ca3694a@q26g2000prq.googlegroups.com> <613a20bf-6e5a-435e-9a83-36766e12f0ab@k8g2000yqn.googlegroups.com> <016be89e$0$6988$c3e8da3@news.astraweb.com> Message-ID: On Wed, Dec 31, 2008 at 5:26 PM, Steven D'Aprano < steve at remove-this-cybersource.com.au> wrote: > On Wed, 31 Dec 2008 12:35:20 -0800, Hamish McKenzie wrote: > > > sometimes I want to be able to initialize an instance with a variety of > > different data types. > > Type conversion is a bit of a misleading subject line. You're not really > converting different types, just initialising from different types. > > > > as an obvious example I might want to initialize a 4x4 matrix with > > either 16 floats, a list/tuple or 16 floats, another matrix or a > > quaternion. > > > > is there any other way to do it other than putting case statements in > > the __init__ method of the class, or having a Matrix.FromQuaternion( > > quat )? > > > You could have an external function qtom: > > def qtom(quaternion): > a, b, c, d = quaternion > return Matrix([ > a, 0, 0, 0, > 0, b, 0, 0, > 0, 0, c, 0, > 0, 0, 0, d]) > > > But the first two solutions seem reasonable to me, except of course > Python doesn't have a case statement you have to use an if...elseif block. You could also use a dict with type:method key/value pairings. This is closer to a switch/case than an if...elif chain is. (untested) def __init__(self, *args) : inits = {list: self._init_from_list, float: self._init_from_floats, Matrix: self._init_from_matrix} #and so on inits[type(args[0])](*args) > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Wed Dec 31 18:32:43 2008 From: castironpi at gmail.com (Aaron Brady) Date: Wed, 31 Dec 2008 15:32:43 -0800 (PST) Subject: Pass by reference References: <529e1d98-8932-49f0-b569-85285bd50f23@p2g2000prn.googlegroups.com> Message-ID: On Dec 31, 5:30?am, iu2 wrote: > Hi, > > Is it possible somehow to change a varible by passing it to a > function? > > I tried this: > > def change_var(dict0, varname, val): > ? dict0[varname] = val > > def test(): > ? a = 100 > ? change_var(locals(), 'a', 3) > ? print a > > But test() didn't work, the value a remains 100. > > I have several variables initialized to None. > I need to convert each one of them an object only if it is None. > something like: > > if not var1: var1 = MyObject() > > I want this to be a function, that is: > > def create_obj(var): > ? if not var: var = MyObj() > ? # set properties of var > > Now, I know I can achieve this by functional programming, > > def create_obj(var): > ? if not var: > ? ? x = MyObj() > ? ? # set properties of x > ? ? return x > ? return var > > and then > > var = creaet_obj(var) > > Is there another way? > > Thanks A practical way is to use a container. Some people use lists; I like an object. thingref= Ref( thing ) f( thingref ) print thingref() #or thingref.get() or w'ver. Then 'f' can assign like this: def f( aref ): # blah blah aref( newthing ) #or aref.set( newthing ) But the short answer is no. A function receives the contents of a variable, not a variable. From fennecfanatic at gmail.com Wed Dec 31 18:33:56 2008 From: fennecfanatic at gmail.com (Mirage) Date: Wed, 31 Dec 2008 15:33:56 -0800 (PST) Subject: Graphics Library with Standard Interaction Features, 2D and 3D References: <69c3eca8-5e17-49fb-8354-5fdc0bd73f9a@r15g2000prd.googlegroups.com> Message-ID: <60cc8c61-52c2-43b2-8287-66417f1d1ca9@q18g2000vbn.googlegroups.com> On Dec 31, 6:18?am, Stef Mientki wrote: > Maybe VPython (Visual) or Panda fits your needs. > cheers, > Stef I second that. Panda3D is awesome in so many ways. From castironpi at gmail.com Wed Dec 31 18:50:20 2008 From: castironpi at gmail.com (Aaron Brady) Date: Wed, 31 Dec 2008 15:50:20 -0800 (PST) Subject: SQL, lite lite lite References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> <8da5c6b1-951f-4abd-8ee7-07b63802b9f6@13g2000yql.googlegroups.com> <186e44f7-f949-45e2-b1e2-a913560acf94@s9g2000prg.googlegroups.com> <495a97ce$0$25469$426a74cc@news.free.fr> Message-ID: On Dec 30, 2:52?pm, Bruno Desthuilliers wrote: > Aaron Brady a ?crit : > > > On Dec 30, 11:16 am, prueba... at latinmail.com wrote: > (snip) > >> You really do like to reinvent the wheels do you? :-) Nothing wrong > >> with that. Just be aware that most people that really need what you > >> are proposing are probably already using mature feature rich libraries > >> for that. > > >>http://wiki.python.org/moin/HigherLevelDatabaseProgramming > > > Look at these options! ?Who invents the wheel? ?Naturally, I've had > > time to master every one. > > Oh, so that's why you propose to add yet another item to the list ? Aha, so it is. Your criticism might seem harsh, but it has an advantage. It made me get the lead out, that is, think. Assuming I do want my Relation class to be backed by a full-fledged database, all I would need is an adapter to a Dee or Django object. The only restriction is, records have to be uniform types. (In many cases, this can be good, since relations are statically typed.) I recognize that on average, I'm only saving a little syntax. If I have a Student object and I want the classes s/he is in, the SQL isn't horrible. SELECT objectrep FROM Classes WHERE Student IS studentA //'IS' is not supported in SQL It returns a list of Class instances. The Python is better. studentA.getClasses() To make it fully dynamic, studentA.get( 'Classes' ) or studentA.get( Classes ) or studentA.cross( Classes ) would be closer to what I have in mind. If readers will permit a brainstorm, maybe one of the options will spark an idea. studentA and Classes studentA.intersection( Classes ) However, I want a list of classes, not a list of students, so I am not wanting a pure 'intersection' relation, that is, not a commutative one. Classes.get( studentA ) Classes and studentA #breaks commutativity of 'and' Classes.intersection( studentA ) The method will have to determine what field 'studentA' is supposed to match. From http Wed Dec 31 19:19:54 2008 From: http (Paul Rubin) Date: 31 Dec 2008 16:19:54 -0800 Subject: multiprocessing vs thread performance References: <04a86770-262c-499a-92d3-3ffa76434503@a29g2000pra.googlegroups.com> Message-ID: <7x8wpv7u8l.fsf@ruckus.brouhaha.com> Aaron Brady writes: > I had an idea. You could use 'multiprocessing' for synchronization, > and just use an mmap for the actual communication. (I think it's a > good idea.) Are you reinventing POSH? (http://poshmodule.sourceforge.net) From castironpi at gmail.com Wed Dec 31 19:22:30 2008 From: castironpi at gmail.com (Aaron Brady) Date: Wed, 31 Dec 2008 16:22:30 -0800 (PST) Subject: why cannot assign to function call References: <495867C2.7080807@gmail.com> <5e807c67-7d97-4b8a-8c5f-a3b97f5c5003@i20g2000prf.googlegroups.com> <5fb29c80-a6a4-4cb4-aa62-0d2aeb437662@o4g2000pra.googlegroups.com> Message-ID: <0164a0d4-97c9-4be1-a948-4e5b0deb9585@b38g2000prf.googlegroups.com> On Dec 31, 1:39?am, Tim Roberts wrote: > Aaron Brady wrote: > > >I think the problem goes deeper than just English. ?In any language > >that has a plural, the propositions in question come out as, 'one > >thing is two things' or 'two things are one thing'. ?According to some > >rules, these are ungrammatical sentences, due to plurality > >disagreement. ?Ex: > > >The Morning Star is ... > >The Evening Star is ... > >*The Morning Star and The Evening Star is... > >*The Morning Star and The Evening Star are... > > >Neither of the latter two is correct. ?(* marks ungrammatical.) ? As > >such, the listener isn't sure what meaning to take. > > This is taking a serious twist into off-topicness, but I need to dispute > this. ?I will assert that the 4th line is, in fact, grammatically correct, > modulo the capitalization of the second "The". ?The fragment is clearly of > the form "X and Y are...", and regardless of the substitution of X and Y, > the plurality of the subject agrees with the verb. > > ? The Morning Star and the Evening Star are bright tonight. > > Ignoring the fact that we can't see both at the same time, why is the > meaning of that unclear? I want to get around to a clear answer to the OP's question, but I'm frustrated by a month-long argument about it that suffered from some serious misunderstandings of technical terms. (Therefore, thanks for entertaining my detour so far, as well as not jumping down my throat yet.) We didn't do a good job of explaining, and even disputed some of the terms ourselves. So, I'm trying to look for some clear, vernacular language that won't confuse lay speakers in an explanation. I agree that the form of the 4th fragment is 'X and Y are' in general. However, native speakers don't often use the form 'X and X are'. This is the source of my protest, because X = the Morning Star = the Evening Star. We don't say, 'G.H.W. Bush and the President are...', say, at Camp David. It is not that the meaning is unclear, it's just that form is never used. In fact, moreover, there is some exclusion implied. If I said, 'I'm going to St. Paul's and church,' my listener might think I had two destinations, or I was being philosophical. The conversational maxim of quantity [1] even leads him/r to believe that I want to convey more information that just that I'm going to church. [1] http://en.wikipedia.org/wiki/Gricean_maxim#Maxim_of_Quantity In other words, s/he infers that there is a reason I didn't say only, 'I'm going to St. Paul's' or 'I'm going to church', and s/he wants to know what it is. How all this relates to Python semantics is, if I say, 'a and b are the same object', the listener can get confused. I don't say, 'G.H.W. Bush and the President are the same'; I say, 'G.H.W. Bush is the President'. Part of the problem is that Python divorced variables from their contents; variables and objects are two different things. One is a key in a namespace lookup; the other is the value there. I want to conclude that, 'Therefore, there is no such thing as a reference to a variable; only a namespace and a key'. However, I'm not on firm footing to explain further, due to the uncommonness of the forms of speech I would need to use. Maybe I could observe, 'variable references are a peculiarity of C++, not available in every variable model'. From castironpi at gmail.com Wed Dec 31 19:26:42 2008 From: castironpi at gmail.com (Aaron Brady) Date: Wed, 31 Dec 2008 16:26:42 -0800 (PST) Subject: multiprocessing vs thread performance References: <04a86770-262c-499a-92d3-3ffa76434503@a29g2000pra.googlegroups.com> <7x8wpv7u8l.fsf@ruckus.brouhaha.com> Message-ID: <34305872-cb16-4bbb-ad34-3c6a04e30462@r10g2000prf.googlegroups.com> On Dec 31, 6:19?pm, Paul Rubin wrote: > Aaron Brady writes: > > I had an idea. ?You could use 'multiprocessing' for synchronization, > > and just use an mmap for the actual communication. ?(I think it's a > > good idea.) > > Are you reinventing POSH? ?(http://poshmodule.sourceforge.net) I thought the same thing! Paul Boddie introduced me to POSH some months ago. I don't recall the implementation of synchro. objects in POSH, but IIRC, 'multiprocessing' uses native OS handles opening in multiple processes. It could be that there would be substantial overlap, or the trade-offs could be significant. For one, the above combination only permits strings to be shared, not objects. From bdesth.quelquechose at free.quelquepart.fr Wed Dec 31 19:27:33 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Jan 2009 01:27:33 +0100 Subject: Why not Ruby? In-Reply-To: <0640abb6-ab69-4709-a46c-b0ee8c9f0c09@n21g2000vba.googlegroups.com> References: <0640abb6-ab69-4709-a46c-b0ee8c9f0c09@n21g2000vba.googlegroups.com> Message-ID: <495c1ba3$0$28149$426a74cc@news.free.fr> Roger a ?crit : > On Dec 31, 12:55 pm, Xah Lee wrote: (snip) > > Who are you? His name is Xah Lee, and he's a well(hem)known troll. Just ignore him. From philip at semanchuk.com Wed Dec 31 19:28:43 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Wed, 31 Dec 2008 19:28:43 -0500 Subject: multiprocessing vs thread performance In-Reply-To: <7x8wpv7u8l.fsf@ruckus.brouhaha.com> References: <04a86770-262c-499a-92d3-3ffa76434503@a29g2000pra.googlegroups.com> <7x8wpv7u8l.fsf@ruckus.brouhaha.com> Message-ID: <09049249-5F43-4040-AFF0-FAC409705622@semanchuk.com> On Dec 31, 2008, at 7:19 PM, Paul Rubin wrote: > Aaron Brady writes: >> I had an idea. You could use 'multiprocessing' for synchronization, >> and just use an mmap for the actual communication. (I think it's a >> good idea.) > > Are you reinventing POSH? (http://poshmodule.sourceforge.net) Or sysv_ipc? Or posix_ipc? http://semanchuk.com/philip/sysv_ipc/ http://semanchuk.com/philip/posix_ipc/ Bug fix version of the latter coming out in a day or two... From hongtian.info at gmail.com Wed Dec 31 20:42:56 2008 From: hongtian.info at gmail.com (Hongtian) Date: Wed, 31 Dec 2008 17:42:56 -0800 (PST) Subject: How to debug embeding Python? References: Message-ID: <879fea5e-be92-4869-9acf-83008127b2a7@g39g2000pri.googlegroups.com> Thanks all of you, my friends. I think log system is a very good choice. Happy new year! From cab938 at mail.usask.ca Wed Dec 31 21:01:50 2008 From: cab938 at mail.usask.ca (Chris Brooks) Date: Wed, 31 Dec 2008 18:01:50 -0800 (PST) Subject: multiprocessing BaseManager doesn't clean up net connections? Message-ID: <21238615.post@talk.nabble.com> Hi, I'm trying to use remote managers in the multiprocessing module to listen for some events synchronously while my program goes off and does other things. I use the .start() method which forks a new process to handle communication. When I catch the sigint and call sys.exit() though, the network port is still bound even after the python interpretor finishes. Here is my short code and the output: from multiprocessing.managers import BaseManager import threading import sys import signal import time class WorkManager(BaseManager): def __init__(self): BaseManager.__init__(self,address=('', 51114), authkey='chris') self.register('get_string', callable=self.getString) def getString(self): return "hi" manager = WorkManager() manager.start() def quit( arg1, arg2 ): sys.exit() signal.signal(signal.SIGINT, quit) #busy wait while 1: time.sleep(1) cab938 at ubuntu:~$ python2.6 server.py ^Ccab938 at ubuntu:~$ python2.6 server.py Process WorkManager-1: Traceback (most recent call last): File "/usr/local/lib/python2.6/multiprocessing/process.py", line 231, in _bootstrap self.run() File "/usr/local/lib/python2.6/multiprocessing/process.py", line 88, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python2.6/multiprocessing/managers.py", line 517, in _run_server server = cls._Server(registry, address, authkey, serializer) File "/usr/local/lib/python2.6/multiprocessing/managers.py", line 136, in __init__ self.listener = Listener(address=address, backlog=5) File "/usr/local/lib/python2.6/multiprocessing/connection.py", line 97, in __init__ self._listener = SocketListener(address, family, backlog) File "/usr/local/lib/python2.6/multiprocessing/connection.py", line 217, in __init__ self._socket.bind(address) File "", line 1, in bind error: [Errno 98] Address already in use Traceback (most recent call last): File "server.py", line 16, in manager.start() File "/usr/local/lib/python2.6/multiprocessing/managers.py", line 499, in start self._address = reader.recv() EOFError cab938 at ubuntu:~$ Comments? Is this a bug, or is there a better way to clean up the manager myself before shutting down? Chris -- View this message in context: http://www.nabble.com/multiprocessing-BaseManager-doesn%27t-clean-up-net-connections--tp21238615p21238615.html Sent from the Python - python-list mailing list archive at Nabble.com. From gh at ghaering.de Wed Dec 31 21:10:35 2008 From: gh at ghaering.de (=?UTF-8?B?R2VyaGFyZCBIw6RyaW5n?=) Date: Thu, 01 Jan 2009 03:10:35 +0100 Subject: Easy-to-use Python GUI In-Reply-To: References: Message-ID: <6s2n0sF408fuU1@mid.uni-berlin.de> Dotan Cohen wrote: > I have been following this thread with interest. Is there a way to > build Qt apps with relative easy? I use KDE and would prefer the Qt > toolkit for my GUI apps. Thanks. A few years ago, I've had bad experiences with wxPython (random things not actually working on Linux, only on Windows; getting segfaults when using not exactly the right values for API calls). So, when I had to decide for a toolkit for a new application I'm developing on my job which required: - ability to run on Windows - ability to run on MacOS - time to develop is short I recommended to go with PyQt. I remembered it was warmly recommended by Alex Martelli and others a few years ago. So far, it's been nothing but joy. We bought the book "Rapid GUI Programming with Python and Qt" (http://www.qtrac.eu/pyqtbook.html) which is *really* well written. It's probably the best tech book I ever had. The author formerly did Qt documentation for Trolltech, so he has deep understanding of what he's writing about. There may be not so many third-party add-ons for PyQt like for wxPython, but in my opinion, the quality of Qt, PyQt and documentation like the book make up for it. And, it's really extensive. So far I've found everything in Qt/PyQt I wanted/needed: - MDI workspaces - Dock windows - I needed something like wxPythons wxOGL for a process modeler and after looking around for two days, I found out that it's already all there in Qt 4.4: QGraphicsScene/QGraphicsView - etc. -- Gerhard From prologic at shortcircuit.net.au Wed Dec 31 21:57:39 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 1 Jan 2009 12:57:39 +1000 Subject: greenlets and how they can be used In-Reply-To: <2cb20fad-c9be-4fe8-9cb7-e7ff91a67649@z28g2000prd.googlegroups.com> References: <2cb20fad-c9be-4fe8-9cb7-e7ff91a67649@z28g2000prd.googlegroups.com> Message-ID: On Thu, Jan 1, 2009 at 9:24 AM, Aaron Brady wrote: (snip) > I had a dream for a while that in a GUI framework, every event would > spawn a unique thread. The GUI would remain responsive even while > executing minor tasks. Of course, shaving a second off running time > isn't exactly mission-critical to GUI users. Do you think greenlet's (this implementation anyway) would be useful in circuits (1) ? When you say every even that was created would spawn a new thread or greenlet ... Makes me wonder ... Just a thought ... What's yours ? cheers James 1. http://trac.softcircuit.com.au/circuits/ From koranthala at gmail.com Wed Dec 31 22:29:19 2008 From: koranthala at gmail.com (koranthala at gmail.com) Date: Wed, 31 Dec 2008 19:29:19 -0800 (PST) Subject: Videocapture in python Message-ID: <0372e356-8f37-457d-9201-18ae94fc68d9@a29g2000pra.googlegroups.com> I face issues in videocapture in python. Cant find anyplace where we can raise bug reports, so mentioning here. Also help required if somebody has solved it earlier. On using videocapture (python 2.4), I am facing the following issues while creating a video sort of application. -> Pull out the usb cable : Videocapture gets the data stored initially in the buffer and returns always. The images are not updated - but also there is no error returned. i.e. there is no information to the viewer that it is not working anymore. Especially because since the timestamp is updated everytime (it is done inside videocapture.py - wherein current time is overwritten on the received image), it gives a feeling that video is running. Currently I have done a workaround in that every 2 captures, i setup the camera again - but it takes too much time. Anyone has any suggestions on solving this? From kentilton at gmail.com Wed Dec 31 23:16:41 2008 From: kentilton at gmail.com (Kenneth Tilton) Date: Wed, 31 Dec 2008 23:16:41 -0500 Subject: Why not Ruby? In-Reply-To: References: Message-ID: <495c43c3$0$20279$607ed4bc@cv.net> Xah Lee wrote: > Just spent 3 hours looking into Ruby today. Here's my short impression > for those interested. > > * Why Not Ruby? > http://xahlee.org/UnixResource_dir/writ/why_not_Ruby.html > > plain text version follows: > -------------------------------------- > > Why Not Ruby? > > Xah Lee, 2008-12-31 > > Spent about 3 hours looking into Ruby language today. > > The articles i read in detail are: > > * Wikipedia: Ruby (programming language)?J. Gives general overview. > > * Brief tutorial: "Ruby in Twenty Minutes" > http://www.ruby-lang.org/en/documentation/quickstart/ > > * Personal blog by Stevey Yegge, published in 2004-10. > http://steve.yegge.googlepages.com/ruby-tour > > The Wikipedia gives the best intro and overview in proper context. The > "Ruby in Twenty Minutes" is just 4 pages. It give you a very concrete > intro to Ruby's syntax and semantics. Stevey Yegge's blog doesn't > teach much and rambles, but provide a little personal view. I read it > because his opinions i respect. > > Q: Will you learn Ruby? > > No. For practical application, the lang is some 100 times less useful > than each of Perl, Python, PHP, Javascript. For academic study, > functional langs like Mathematica, Haskell, OCaml, erlang, Qz, are far > more interesting and powerful in almost all aspects. Further, there's > also Perl6, NewLisp, Clojure, Scala... With respect to elegance or > power, these modern lang of the past 5 years matches or exceed Ruby. > > Q: Do you think Ruby lang is elegant? > > Yes. In my opinion, better than Perl, Python, PHP. As a high level > lang, it's far better than Java, C, C++ type of shit. However, i don't > think it is any better than emacs lisp, Scheme lisp, javascript, > Mathematica. Note that Ruby doesn't have a spec, and nor a formal > spec. Javascript has. Ruby's syntax isn't that regular, nor is it > based on a system. Mathemtica's is. Ruby's power is probably less than > Scheme, and probably same as Javascript. > > I also didn't like the fact that ruby uses keyword "end" to indicate > code block much as Pascal and Visual Basic, Logo, do. I don't like > that. > > Q: Won't Ruby be a interesting learning experience? > > No. As far as semantics goes, Ruby is basically identical to Perl, > Python, PHP. I am a expert in Perl and PHP, and have working knowledge > of Python. I already regretted having spent significant amount of time > (roughly over a year) on Python. In retrospect, i didn't consider the > time invested in Python worthwhile. (as it turns out, i don't like > Python and Guido cult, as the lang is going the ways of OOP mumbo- > jumbo with its Python 3 "brand new" future.) There is absolutely > nothing new in Ruby, as compared to Perl, Python, PHP, or Emacs lisp, > Scheme lisp. > > Q: Do you recommend new programers to learn Ruby then? > > Not particularly. As i mentioned, if you are interested in practical > utility, there's already Perl, PHP, Python, Javascript, which are all > heavily used in the computing industry. If you are interested as a > academic exercise, there's Scheme lisp, and much of functional langs > such as OCaml, Haskell, Mathematica, which will teach you a whole lot > more about computer science, features of language semantics, etc. > > Q: Do you condemn Ruby? > > No. I think it's reasonably elegant, but today there are too many > languages, so Ruby don't particularly standout for me. Many of them, > are arguably quite more elegant and powerful than Ruby. See: > Proliferation of Computing Languages. > Kenny Tilton, 2008-12-31 Q: Why not Xah's review of Ruby? >> Spent about 3 hours looking into Ruby language today. A. Three hours? I've had belches that lasted longer than that. Of course, a true master can tell a lot in just a few hours of coding with a new language... >> The articles i read in detail are: Q: Read?! A: That's what he said. hth,kzo From thudfoo at opensuse.us Wed Dec 31 23:53:52 2008 From: thudfoo at opensuse.us (member thudfoo) Date: Wed, 31 Dec 2008 20:53:52 -0800 Subject: Why not Ruby? In-Reply-To: References: Message-ID: <3d881a310812312053s5356e29co4b9ebcb55874adfa@mail.gmail.com> 2008/12/31 Giampaolo Rodola' : > On 31 Dic, 18:55, Xah Lee wrote: >> Just spent 3 hours looking into Ruby today. Here's my short impression [...] > --- Giampaolo > http://code.google.com/p/pyftpdlib > Hey, Giampaolo: I had gone to the trouble to filter out the posts from xah lee, but you have quoted his entire message. If you would like to scold xah lee, you can do so directly without reposting to this fine newsgroup. Thank You Very Much. > -- > http://mail.python.org/mailman/listinfo/python-list > > From ajaksu at gmail.com Tue Dec 23 17:42:53 2008 From: ajaksu at gmail.com (ajaksu) Date: Tue, 23 Dec 2008 14:42:53 -0800 (PST) Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <826275b7-986a-4e70-9129-83cc0d10f0d0@q36g2000vbn.googlegroups.com> On Dec 23, 2:45?pm, Mark Dickinson wrote: > On Dec 23, 4:27?pm, ajaksu wrote: > > > Is "x ** 0 > 0." instead of "atan2(x, -1.) > 0." unreliable across > > platforms? > > x**0 doesn't distinguish between x = -0.0 and x = 0.0. > > I suspect you're confusing -0.0**0.0 with (-0.0)**0.0. Yes, fooled me :) Thanks for the heads-up! Daniel From lie.1296 at gmail.com Sun Dec 14 17:46:58 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 14 Dec 2008 22:46:58 +0000 (UTC) Subject: Looking for the best way to translate an idiom References: <4945406a$0$1127$426a74cc@news.free.fr> <2c5ad999-47f9-4040-85c9-4c9438afe4bb@b41g2000pra.googlegroups.com> Message-ID: On Sun, 14 Dec 2008 09:51:03 -0800, Paul Moore wrote: > On 14 Dec, 16:22, Bruno Desthuilliers > wrote: >> if you only want the first returned value, you can just apply a slice: >> >> def f(): >> ? ? return 1,2,3 >> >> a = f()[0] + 1 > > Hmm, true. I'm not sure it's any less ugly, though :-) > >> FWIW, Python 2.6 has NamedTuple objects... > > I know, but I want to target 2.5+ (I still have a number of systems > running 2.5) > Ah, that discounts python 3.0 Python 3.0 allows you to do this: a, b, *c = range(5) # a >> 0 # b >> 1 # c >> [2, 3, 4] *a, b, c = range(5) # a >> [0, 1, 2] # b >> 3 # c >> 4 a, *b, c = range(5) # a >> 0 # b >> [1, 2, 3] # C >> 4 From erichapkido at gmail.com Tue Dec 9 11:26:54 2008 From: erichapkido at gmail.com (Eric) Date: Tue, 9 Dec 2008 08:26:54 -0800 (PST) Subject: Google Summer of Code 2009 References: <713dd4d7-0427-4b74-a5bc-1e3538afed6c@n10g2000vbl.googlegroups.com> Message-ID: <8933ce79-0b6a-4690-8b13-7e151d817a40@z28g2000prd.googlegroups.com> On Dec 9, 6:26?am, Andr? wrote: > On Dec 8, 10:34?pm, Eric wrote: > > You should have a look athttp://wiki.python.org/moin/SummerOfCode > > It's still early, so there's nothing yet for 2009, but I am sure that > some ongoing projects mentioned in previous years [like Crunchy ;-)] > will be looking for volunteers. > > Andr? Thanks for the link. For some reason I hadn't seen Crunchy there before. I would be interested in doing something for Crunchy. The class room server seems like a good project if it hasn't been tackled yet. I also wouldn't mind trying to get the history menu going as a start. -Eric From milliondollarnow at gmail.com Thu Dec 25 10:37:21 2008 From: milliondollarnow at gmail.com (pal) Date: Thu, 25 Dec 2008 07:37:21 -0800 (PST) Subject: Rock Hard Erection Message-ID: <0e0a28c3-08f5-4460-be8d-c7dfab421e24@n33g2000pri.googlegroups.com> ?Would You Like To Know How To Get Rock Hard Erection And Last 60 Minutes Longer Between Her Legs, Enjoy Multiple Orgasms While Keeping Your Rock Hard, Full Length Erection.? Please visit http://godisgreat.wdarpkere.click2sell.eu From stefan_ml at behnel.de Sat Dec 27 04:04:10 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 27 Dec 2008 10:04:10 +0100 Subject: Getting a locked buffer from objects (PEP 3118) In-Reply-To: References: Message-ID: <4955ef8b$0$30225$9b4e6d93@newsspool1.arcor-online.net> KKH wrote: > it seems the whole locking-theme has gone from PEP 3118 (PyBUF_LOCK is > gone). Yet the string and byte objects seem to provide locked buffers > through PyArg_Parse arguments s*, y* and z* (documentation says so). Might be a left-over. All locking the buffer interface itself provides is the guarantee that the buffer will not move between getting and releasing a buffer. Everything else must be handled at the application level. > Could someone please clarify the situation for me: Is it save to release > the GIL after getting a reference to a buffer-object by the arguments > above and only talking to this buffer while the GIL is gone? The buffer interface is a pure C level interface. All you get is a pointer to a memory buffer plus some meta data. No Python references are involved from that point on. So it only depends on your own code if it's safe to free the GIL or not. > And while we are at it :-) Is "PyArg_Parse('[syz]*'..." the only way to > get a locked buffer-view from string/byte objects? What kind of locking do you need? Stefan From clp at rebertia.com Thu Dec 18 04:04:03 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 18 Dec 2008 01:04:03 -0800 Subject: importing csv file into sqlite In-Reply-To: <21068111.post@talk.nabble.com> References: <21067453.post@talk.nabble.com> <21068111.post@talk.nabble.com> Message-ID: <47c890dc0812180104g4c934a56ma8ef49d0bf6b4d80@mail.gmail.com> On Wed, Dec 17, 2008 at 11:20 PM, klia wrote: > klia wrote: >> >> hey guys, i have a hug .csv file which i need to insert it into sqlite >> database using python. >> my csv data looks like this >> Birthday2,12/5/2008,HTC,this is my birthday >> Sea,12/3/2008,kodak,sea >> birthday4,14/3/2009,samsung,birthday >> love,17/4/2009,SONY,view of island >> >> can any one give me a head start codes. >> >> thanks in advance >> > guys so far i came out with this but i get this error > waseem at Linux:~/Project2$ python experment.py > Traceback (most recent call last): > File "experment.py", line 13, in > curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item) > sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current > statement uses 4, and there are 1 supplied. > > here's the codes > > import sqlite3 > import csv > > f = open('/home/waseem/Project2/photos.txt') > csv.field_size_limit(100000) #see below! > input = csv.reader(f, delimiter='\t') > conn = sqlite3.connect('/home/waseem/Project2/picutres.db') > curse = conn.cursor() > > curse.execute('CREATE TABLE photos (Name VARCHAR(100) PRIMARY KEY, Date > INTEGER, Make VARCHAR(50), Tag VARCHAR(100))') > > for item in input: > curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item) I believe you need to change 'item' to '*item' to expand the list in the call so that the function gets 4 additional args rather than 1 additional arg that happens to be a list. But as I've never used the DB-API before, this is just a guess. Also, you should rename 'input' so that you don't shadow a built-in function, and you might want to rename 'item' to something like 'row' to emphasize that it is itself a list of items. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > curse.commit() From castironpi at gmail.com Mon Dec 22 18:36:15 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 22 Dec 2008 15:36:15 -0800 (PST) Subject: Are python objects thread-safe? References: Message-ID: <5306b56c-eb8c-4148-b426-013caa871375@b41g2000pra.googlegroups.com> On Dec 22, 2:59?am, Duncan Booth wrote: > RajNewbie wrote: > > Say, I have two threads, updating the same dictionary object - but for > > different parameters: > > Please find an example below: > > a = {file1Data : '', > > ? ? ? ?file2Data : ''} > > > Now, I send it to two different threads, both of which are looping > > infinitely: > > In thread1: > > a['file1Data'] = open(filename1).read > > ? ? ? ? ? and > > in thread2: > > a['file2Data'] = open(filename2).read > > > My question is ?- is this object threadsafe? - since we are working on > > two different parameters in the object. Or should I have to block the > > whole object? > > It depends exactly what you mean by 'threadsafe'. The GIL will guarantee > that you can't screw up Python's internal data structures: so your > dictionary always remains a valid dictionary rather than a pile of bits. > > However, when you dig a bit deeper, it makes very few guarantees at the > Python level. Individual bytecode instructions are not guaranteed > atomic: for example, any assignment (including setting a new value into > the dictionary) could overwrite an existing value and the value which is > overwritten may have a destructor written in Python. If that happens you > can get context switches within the assignment. Th.1 Th.2 a=X a=Y a=Z You are saying that if 'a=Z' interrupts 'a=Y' at the wrong time, the destructor for 'X' or 'Y' might not get called. Correct? In serial flow, the destructor for X is called, then Y. > Other nasty things can happen if you use dictionaries from multiple > threads. You cannot add or remove a dictionary key while iterating over > a dictionary. This isn't normally a big issue, but as soon as you try to > share the dictionary between threads you'll have to be careful never to > iterate through it. These aren't documented, IIRC. Did you just discover them by trial and error? > You will probably find it less error prone in the long run if you get > your threads to write (key,value) tuples into a queue which the > consuming thread can read and use to update the dictionary. Perhaps there's a general data structure which can honor 'fire-and- forget' method calls in serial. a= async( {} ) a[0]= X a[0]= Y --> obj_queue[a].put( a.__setitem__, 0, X ) obj_queue[a].put( a.__setitem__, 0, Y ) If you need the return value, you'll need to block. print a[0] --> res= obj_queue[a].put( a.__getitem__, 0 ) res.wait() return res print res Or you can use a Condition object. But you can also delegate the print farther down the line of processing: obj_queue[a].link( print ).link( a.__getitem__, 0 ) (As you can see, the author (I) finds it a more interesting problem to get required information in the right places at the right times in execution. The actual implementation is left to the reader; I'm merely claiming that there exists a consistent one taking the above instructions to be sufficient givens.) From martin.hellwig at dcuktec.org Fri Dec 12 04:47:39 2008 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Fri, 12 Dec 2008 09:47:39 +0000 Subject: Moving to subprocess from os.popen--pipe closes prematurely In-Reply-To: References: Message-ID: <4942333c$0$191$e4fe514c@news.xs4all.nl> Kevin Walzer wrote: > Hello, > > I'm trying to move from os.popen to using subprocess, and I'm having > trouble with the pipe suddenly closing. > > My old code looked something like this: > Hi Kevin, You could try something more like: >>> import subprocess >>> cmd = subprocess.Popen([executable_path, executable_options], stdout=subprocess.PIPE, stdout=subprocess.PIPE) >>> std_out, std_err = cmd.communicate(standard_in_value) std_out is a string though, you probably need to split it on newline to get the same sort of list and since it is buffered in memory you probably don't want to use .communicate if you expect megabytes of data back. -- mph From _karlo_ at _mosor.net_ Sat Dec 13 15:29:43 2008 From: _karlo_ at _mosor.net_ (Karlo Lozovina) Date: Sat, 13 Dec 2008 20:29:43 +0000 (UTC) Subject: curses and refreshing problem Message-ID: Hi, I'm trying to implement text output interface, something similar to wget, using curses module. There are just two things I can't find out how to do: prevent curses from clearing the terminal when starting my program, and leaving my output after the program closes. Any way to do this with curses? Thanks... -- _______ Karlo Lozovina - Mosor | | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163 | || _ | _ | Parce mihi domine quia Dalmata sum. |__|_|__||_____|_____| From metolone+gmane at gmail.com Sat Dec 6 14:20:26 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 6 Dec 2008 11:20:26 -0800 Subject: Python 3.0 automatic decoding of UTF16 References: <5u8o06xbqf.ln2@joeserver.homelan.net> <1mmq06x4g6.ln2@joeserver.homelan.net> Message-ID: "Johannes Bauer" wrote in message news:1mmq06x4g6.ln2 at joeserver.homelan.net... >John Machin schrieb: >> On Dec 6, 5:36 am, Johannes Bauer wrote: >>> So UTF-16 has an explicit EOF marker within the text? I cannot find one >>> in original file, only some kind of starting sequence I suppose >>> (0xfeff). The last characters of the file are 0x00 0x0d 0x00 0x0a, >>> simple \r\n line ending. >> >> Sorry, *WRONG*. It ends in 00 0d 00 0a 00. The file is 1559 bytes >> long, an ODD number, which shouldn't happen with utf16. The file is >> stuffed. Python 3.0 has a bug; it should give a meaningful error >> message. > >Yes, you are right. I fixed the file, yet another error pops up >(http://www.file-upload.net/download-1299688/2008_12_05_Handy_Backup.txt.html): > >Traceback (most recent call last): > File "./modify.py", line 12, in > a = AddressBook("2008_12_05_Handy_Backup.txt") > File "./modify.py", line 7, in __init__ > line = f.readline() > File "/usr/local/lib/python3.0/io.py", line 1807, in readline > while self._read_chunk(): > File "/usr/local/lib/python3.0/io.py", line 1556, in _read_chunk > self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) > File "/usr/local/lib/python3.0/io.py", line 1293, in decode > output = self.decoder.decode(input, final=final) > File "/usr/local/lib/python3.0/codecs.py", line 300, in decode > (result, consumed) = self._buffer_decode(data, self.errors, final) > File "/usr/local/lib/python3.0/encodings/utf_16.py", line 69, in >_buffer_decode > return self.decoder(input, self.errors, final) >UnicodeDecodeError: 'utf16' codec can't decode byte 0x0a in position 0: >truncated data > >File size is 1630 bytes - so this clearly cannot be. How about posting your code? The first file is incorrect. It contains an extra 0x00 byte at the end of the file, but is otherwise correctly encoded with a big-endian UTF16 BOM and data. The second file is a correct UTF16-BE file as well. This code (Python 2.6) decodes the first file, removing the trailing extra byte: raw = open('2008_11_05_Handy_Backup.txt').read() data = raw[:-1].decode('utf16') and this code (Python 2.6) decodes the second: raw = open('2008_12_05_Handy_Backup.txt').read() data = raw.decode('utf16') Python 3.0 also has no problems with decoding or accurate error messages: >>> data = open('2008_12_05_Handy_Backup.txt',encoding='utf16').read() >>> data = open('2008_11_05_Handy_Backup.txt',encoding='utf16').read() Traceback (most recent call last): File "", line 1, in File "C:\dev\python30\lib\io.py", line 1724, in read decoder.decode(self.buffer.read(), final=True)) File "C:\dev\python30\lib\io.py", line 1295, in decode output = self.decoder.decode(input, final=final) File "C:\dev\python30\lib\codecs.py", line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) File "c:\dev\python30\lib\encodings\utf_16.py", line 61, in _buffer_decode codecs.utf_16_ex_decode(input, errors, 0, final) UnicodeDecodeError: 'utf16' codec can't decode byte 0x00 in position 1558: trunc ated data -Mark From mludvig at logix.net.nz Mon Dec 29 07:45:00 2008 From: mludvig at logix.net.nz (Michal Ludvig) Date: Tue, 30 Dec 2008 01:45:00 +1300 Subject: Unicode encoding - ignoring errors In-Reply-To: <47c890dc0812290410u25f9e69oecdcc0e859f9b10e@mail.gmail.com> References: <4958BD31.1010801@logix.net.nz> <47c890dc0812290410u25f9e69oecdcc0e859f9b10e@mail.gmail.com> Message-ID: <4958C64C.7000400@logix.net.nz> Chris Rebert wrote: > On Mon, Dec 29, 2008 at 4:06 AM, Michal Ludvig wrote: >> Hi, >> >> in my script I have sys.stdout and sys.stderr redefined to output >> unicode strings in the current system encoding: >> >> encoding = locale.getpreferredencoding() >> sys.stdout = codecs.getwriter(encoding)(sys.stdout) >> >> However on some systems the locale doesn't let all the unicode chars be >> displayed and I eventually end up with UnicodeEncodeError exception. >> >> I know I could explicitly "sanitize" all output with: >> >> whatever.encode(encoding, "replace") >> >> but it's quite inconvenient. I'd much prefer to embed this "replace" >> operation into the sys.stdout writer. >> [...] > codecs.getwriter() returns a StreamWriter subclass (basically). > The constructor of said subclass has the signature: > StreamWriter(stream[, errors]) > You want the 'errors' argument. Thanks! (and I'm going to read the module docs, really ;-) Michal From af300wsm at gmail.com Mon Dec 8 16:33:38 2008 From: af300wsm at gmail.com (Andrew Falanga) Date: Mon, 8 Dec 2008 13:33:38 -0800 (PST) Subject: Calling C# COM (.NET) from python References: <65482a31-8091-486f-8a9b-8f6bdf947af6@w1g2000prk.googlegroups.com> Message-ID: <0e2ec315-a5ef-419e-a224-78ab965db99c@r15g2000prd.googlegroups.com> On Dec 8, 11:52?am, Mike Driscoll wrote: > On Dec 8, 11:14?am, Ben Kaplan wrote: > > > > > On Dec 8, 2008, at 11:53 AM, Andrew Falanga wrote: > > > > Hi, > > > > I've never programmed in python and only have a small understanding of > > > what is wrapped up in the terms COM and .NET. ?Is there a way of using > > > python to get a hold of objects written in C# as COM objects using > > > python? ?I'm looking for ways to avoid VBScript (which, after a couple > > > of weeks, I've determined to be horrid). ?That is, is there a way of > > > getting at COM objects in python that's similar to doing a > > > CreateObject call in VBScript (http://msdn.microsoft.com/en-us/ > > > library/ > > > dcw63t7z.aspx)? > > > > Thanks, > > > Andy > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > I would not deal with COM at all. I personally have not used it, but ? > > there is a version of python called IronPython that's written in C#, ? > > so it can use .NET and, I think, other C# objects. Other people will ? > > probably help you more, but you might want to look into that and maybe ? > > ask this on the python-win list. > > As I understand it, IronPython can use anything done in the CLR, so > technically I could write something in VB.NET, C# or any of the other > VS languages and then use them from within IronPython. It should be > noted that IronPython does not support most 3rd party packages that > are not pure python. As I recall, it doesn't have the complete builtin > library either, but it's close. > > Reads the docs and check it out at least. If you already know .NET > languages, then you'll probably find IronPython helpful. > > Mike To all, thanks for the great replies. I've got something to work with here. Thanks to for the link to PyWin32 and the mailing list. That sounds promising as does this IronPython. I wished I knew more of .NET and python more (as my original post claims, I've never written Python and I only wished I knew the .NET stuff better for better footing in this). I'm very much the proverbial, "fish out of water," as I'm a UNIX man now stuck in a Windows world. Thanks again, Andy From tjreedy at udel.edu Fri Dec 12 19:16:47 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 12 Dec 2008 19:16:47 -0500 Subject: __future__ and unrecognised flags In-Reply-To: <20081212215252.18112.qmail@s461.sureserver.com> References: <20081212215252.18112.qmail@s461.sureserver.com> Message-ID: Poor Yorick wrote: > I have a future statement in a script I intend to work on 2.6 and 3. Shouldn't __future__ statements basically be noops for versions that already support the feature? doctest is complaining about compiler flags. This illustrates the problem: > > Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win > 32 > Type "help", "copyright", "credits" or "license" for more information. > >>> from __future__ import unicode_literals > >>> src = 'a = "hello"' > >>> c1 = compile(src,'','exec',unicode_literals.compiler_flag) > Traceback (most recent call last): > File "", line 1, in > ValueError: compile(): unrecognised flags According to this "The optional arguments flags and dont_inherit control which future statements (see PEP 236) affect the compilation of source. If neither is present (or both are zero) the code is compiled with those future statements that are in effect in the code that is calling compile. " you do not need to duplicate the future option in the compile call. I tried doing the same without the flag and it works. That said, this seems like a bug to me, so if no one explains otherwise, report it at http://bugs.python.org I tried with 5th param True and got same error. On Winxp tjr From dieter at handshake.de Sat Dec 6 14:35:19 2008 From: dieter at handshake.de (Dieter Maurer) Date: 06 Dec 2008 20:35:19 +0100 Subject: Profiling Python In-Reply-To: <15e24533-472f-4147-9467-893b40ff2710@w35g2000yqm.googlegroups.com> References: <15e24533-472f-4147-9467-893b40ff2710@w35g2000yqm.googlegroups.com> Message-ID: esgameserver at gmail.com writes on Wed, 3 Dec 2008 07:13:14 -0800 (PST): > To clarify again, > Is there some function like profile.PrintStats() which dynamically > shows the stats before stopping the Profiler? Try to (deep) copy the profiler instance and than call "PrintStats()" on the copy. Of course, you will then profile also the "PrintStats" in the running profiler. Dieter From manu3d at gmail.com Thu Dec 11 19:00:31 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 11 Dec 2008 16:00:31 -0800 (PST) Subject: Preventing execution of a method References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> <764daeef-bfbe-411a-8521-bb114321e4ac@b38g2000prf.googlegroups.com> <19304f8c-e34f-4aa9-8df2-6a7d3553007a@e1g2000pra.googlegroups.com> <2eed8876-94d2-4304-88a5-eb4a78b4f41d@33g2000yqm.googlegroups.com> <307fe197-1b42-4305-af0e-94b7ebe3ce70@r15g2000prh.googlegroups.com> <49417c59$0$8491$426a74cc@news.free.fr> <6qdmthFc5ggdU1@mid.individual.net> Message-ID: <86f33456-4620-42ef-8ba9-eb1532aa2635@r10g2000prf.googlegroups.com> On Dec 11, 11:46?pm, greg wrote: > Emanuele D'Arrigo wrote: > > -IF- the application was single-user yes, it wouldn't be a big deal. > > But as it is potentially multi-user, I don't want one party to corrupt > > the application for everybody else. > > In that case you definitely want a client-server architecture, > with the server managing all the critical data. Yep, I agree, I think that's the way to go and although trickier it allows for some neatness and flexibility. Thank you! Manu From enleverlesX.XmcX at XmclaveauX.com Sat Dec 20 12:05:37 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sat, 20 Dec 2008 18:05:37 +0100 Subject: check whether a JPG is completed? In-Reply-To: References: Message-ID: <494d2756$0$18388$ba4acef3@news.orange.fr> Hi! Sometimes, PIL give an error. With "try: Except:", you can get info. Sometimes, non error, but the Jpeg is not correct. Difficult, in this case, to get info. Therefore, the answer is: "not in all cases". @-salutations -- Michel Claveau From iofferkicks24 at gmail.com Wed Dec 24 22:59:09 2008 From: iofferkicks24 at gmail.com (www.iofferkicks.com) Date: Wed, 24 Dec 2008 19:59:09 -0800 (PST) Subject: www.iofferkicks.com china cheap wholesale nike shoes,air jordan shoes,air force one shoes. Message-ID: <790bd96b-dbda-470b-bc33-b6813ea10e2c@k36g2000pri.googlegroups.com> Get Nike Shoes at Super Cheap Prices Discount Nike air jordans (www.iofferkicks.com) Discount Nike Air Max 90 Sneakers (www.iofferkicks.com) Discount Nike Air Max 91 Supplier (www.iofferkicks.com) Discount Nike Air Max 95 Shoes Supplier (www.iofferkicks.com) Discount Nike Air Max 97 Trainers (www.iofferkicks.com) Discount Nike Air Max 2003 Wholesale (www.iofferkicks.com) Discount Nike Air Max 2004 Shoes Wholesale (www.iofferkicks.com) Discount Nike Air Max 2005 Shop (www.iofferkicks.com) Discount Nike Air Max 2006 Shoes Shop (www.iofferkicks.com) Discount Nike Air Max 360 Catalogs (www.iofferkicks.com) Discount Nike Air Max Ltd Shoes Catalogs (www.iofferkicks.com) Discount Nike Air Max Tn Men's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 2 Women's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 3 Customize (www.iofferkicks.com) Discount Nike Air Max Tn 4 Shoes Customize ( www.iofferkicks.com) Discount Nike Air Max Tn 6 Supply (www.iofferkicks.com) Discount Nike Shox NZ Shoes Supply (www.iofferkicks.com) Discount Nike Shox OZ Sale (www.iofferkicks.com) Discount Nike Shox TL Store (www.iofferkicks.com) Discount Nike Shox TL 2 Shoes Store (www.iofferkicks.com) Discount Nike Shox TL 3 Distributor (www.iofferkicks.com) Discount Nike Shox Bmw Shoes Distributor (www.iofferkicks.com) Discount Nike Shox Elite Shoes Manufacturer (www.iofferkicks.com) Discount Nike Shox Monster Manufacturer (www.iofferkicks.com) Discount Nike Shox R4 Running Shoes (www.iofferkicks.com) Discount Nike Shox R5 Mens Shoes (www.iofferkicks.com) Discount Nike Shox Ride Womens Shoes (www.iofferkicks.com) Discount Nike Shox Rival Shoes Wholesaler (www.iofferkicks.com) Discount Nike Shox Energia Wholesaler (www.iofferkicks.com) Discount Nike Shox LV Sneaker (www.iofferkicks.com) Discount Nike Shox Turbo Suppliers (www.iofferkicks.com) Discount Nike Shox Classic Shoes Suppliers (www.iofferkicks.com) Discount Nike Shox Dendara Trainer (www.iofferkicks.com) Discount Nike Air Jordan 1 Seller (www.iofferkicks.com) Discount Nike Air Jordan 2 Shoes Seller (www.iofferkicks.com) Discount Nike Air Jordan 3 Collection (www.iofferkicks.com) Discount Nike Air Jordan 4 Shoes Collection (www.iofferkicks.com) Discount Nike Air Jordan 5 Chaussure Shoes (www.iofferkicks.com) Discount Nike Air Jordan 6 Catalog (www.iofferkicks.com) Discount Nike Air Jordan 7 Shoes Catalog (www.iofferkicks.com) Discount Nike Air Jordan 8 Customized (www.iofferkicks.com) Discount Nike Air Jordan 9 Shoes Customized (www.iofferkicks.com) Discount Nike Air Jordan 10 Wholesalers (www.iofferkicks.com) Discount Nike Jordan 11 Shoes Wholesalers (www.iofferkicks.com) Discount Nike Air Jordan 12 Factory (www.iofferkicks.com) Discount Nike Air Jordan 13 Shoes Factory (www.iofferkicks.com) Discount Nike Air Jordan 14 Shoes Sell (www.iofferkicks.com) Discount Nike Air Jordan 16 Exporter (www.iofferkicks.com) Discount Nike Air Jordan 17 Shoes Exporter (www.iofferkicks.com) Discount Nike Air Jordan 18 Offer (www.iofferkicks.com) Discount Nike Air Jordan 19 Shoes Offer (www.iofferkicks.com) Discount Nike Air Jordan 20 Manufacture (www.iofferkicks.com) Discount Nike Jordan 21 Shoes Manufacture (www.iofferkicks.com) EMAIL:IOFFERKICKS at GMAIL.COM MSN :IOFFERKICKS at MSN.COM From pavlovevidence at gmail.com Sat Dec 6 16:33:22 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 6 Dec 2008 13:33:22 -0800 (PST) Subject: Guido's new method definition idea References: Message-ID: On Dec 5, 8:21?pm, "Daniel Fetchinson" wrote: > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... > > The proposal is to allow this: > > class C: > ? ? def self.method( arg ): > ? ? ? ? self.value = arg > ? ? ? ? return self.value > > instead of this: > > class C: > ? ? def method( self, arg ): > ? ? ? ? self.value = arg > ? ? ? ? return self.value -1 I explained why deep in the thread but I'll elaborate more here. When I see a def statement, I mentally equate that to an assigment to the thing being def'ed. So for instance, when I see this: def (): I think of it like this: = Thus, if I were to see a function definition like this def foo.bar(): return 1 I would think you were defining a function and assigning it to foo.bar. IOW, it would be mostly equivalent to this: foo.bar = lambda: 1 (Analogously, I would expect a definition like this: def baz[10](): return 1 to be equivalent to this: baz[10] = lambda: 1 ) So, if, inside a class definition, I were to see this: def self.method(): return 1 Well, I'd understand that is was a method assigment, of course, but it would conflict with what I would expect the natural meaning of something like def a.b() would be. The above statement is not equivalent to: self.method = lambda: 1 but I think that's what it ought to be, in general. Carl Banks From david at hlacik.eu Sat Dec 13 14:00:07 2008 From: david at hlacik.eu (=?ISO-8859-2?Q?David_Hl=E1=E8ik?=) Date: Sat, 13 Dec 2008 20:00:07 +0100 Subject: [OT] stable algorithm with complexity O(n) In-Reply-To: <6qidmbFc4qduU1@mid.uni-berlin.de> References: <6qidmbFc4qduU1@mid.uni-berlin.de> Message-ID: > Unless I grossly miss out on something in computer science 101, the lower > bound for sorting is O(n * log_2 n). Which makes your task impossible, > unless there is something to be assumed about the distribution of numbers in > your sequence. There is n numbers from interval [1 , n^2] I should do measurement for : n = 500, 1000, 1500, 2000, ..., 4500, 5000 O(n) means linear complexivity, so complexivity of algorithmus must be linear, which i have to prove. > > Who has given you that assignment - a professor? Or some friend who's > playing tricks on you? It is official assignment , by professor from Data Structures & Algorithms course. Thanks in advance! > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > From exarkun at divmod.com Fri Dec 19 12:38:14 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 19 Dec 2008 12:38:14 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <494BD97F.5080205@gmail.com> Message-ID: <20081219173814.20272.1836750143.divmod.quotient.23074@ohm> On Fri, 19 Dec 2008 10:27:27 -0700, Michael Torrie wrote: >walterbyrd wrote: >> On Dec 19, 9:13 am, "Giampaolo Rodola'" wrote: >>> You can use the old 2.x syntax also in Python 3.x: >> >> Yeah, but it's deprecated, and - as I understand it - may be removed >> completely in future versions. Also, in the future, if you are working >> with code from another developer, it's likely that developer will use >> the new format. I suppose you can use both - but what an awful mess >> that would be. >> >> It seems to me that 3.0 is changing a lot of non-problems. And it's >> going to be slower to boot. > >How is this? With projects like PyPy eventually enabling the JIT'ing of >python3 code, I don't see how this is going to be "slower." If anything >we have a python that can be made to run faster than ever before. What makes you think PyPy is going to enabling JIT'ing of Python 3 code? Perhaps it will, someday, but I suspect it will provide a JIT for Python 2 long before. Jean-Paul From acherry at btinternet.com Tue Dec 23 10:20:05 2008 From: acherry at btinternet.com (Adrian Cherry) Date: 23 Dec 2008 15:20:05 GMT Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: r wrote in news:ae1bb365-7755-4c5f-8166-e704c51a755d at i20g2000prf.googlegro ups.com: > > Oh Steve... Listen, my words are ment as a wake-up-call to > all who still love Python, and i believe you are one of > them. Maybe old age has slowed your hand, that's OK, Us > "youngsters" will take the helm. And be serious, do you > really think this group is read by "hundreds-of- thousands > of news readers? I wish it were, but I highly doubt it. > Thus spake the artilleryman from Horsell Common! Adrian Cherry From bj_666 at gmx.net Sun Dec 14 04:21:19 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 14 Dec 2008 09:21:19 GMT Subject: Optimizing methods away or not? References: <0154b041$0$6988$c3e8da3@news.astraweb.com> <6qk1dhFcr01gU1@mid.uni-berlin.de> Message-ID: <6qk1gfFcr01gU2@mid.uni-berlin.de> On Sun, 14 Dec 2008 09:19:45 +0000, Marc 'BlackJack' Rintsch wrote: > class Parrot: > def __init__(self, *args): > print "Initialising instance..." > assert self.verify() Here I meant ``assert self._verify()`` of course. > def _verify(self): > print "Verifying..." > return None Ciao, Marc 'BlackJack' Rintsch From claird at lairds.us Wed Dec 3 05:09:58 2008 From: claird at lairds.us (Cameron Laird) Date: Wed, 3 Dec 2008 10:09:58 +0000 Subject: Multiple equates References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> <9m3h06-vhh.ln1@lairds.us> Message-ID: In article , Lawrence D'Oliveiro wrote: >Cameron Laird wrote: > >> def f1(Match): >> return > >Something missing here? Ugh; yes, sorry: def shell_escape(Arg) : """returns Arg suitably escaped for use as a command-line argument to Bash.""" pattern = r"[\<\>\"\'\|\&\$\#\;\(\)\[\]\{\}\`\!\~\ \\]" def f1(Match): return "\\" + Match.group(0) return re.sub(pattern, f1, Arg) # Need to catch anything that might be meaningful to shell #end shell_escape From martin at v.loewis.de Sun Dec 21 04:41:40 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 21 Dec 2008 10:41:40 +0100 Subject: Python for amd64 and mingw-w64 In-Reply-To: <5b8d13220812210056r58a01f53h585d59d0bf81e663@mail.gmail.com> References: <494B3F75.10104@v.loewis.de> <5b8d13220812210056r58a01f53h585d59d0bf81e663@mail.gmail.com> Message-ID: <494E0F54.9000907@v.loewis.de> > This is the only problem on python side of things to make extensions > buildable on windows x64 (all the other problems I have encountered so > far to make numpy build with mingw-w64 are numpy's or mingw-w64). Thanks! Martin From excord80 at gmail.com Fri Dec 19 14:43:12 2008 From: excord80 at gmail.com (excord80) Date: Fri, 19 Dec 2008 11:43:12 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: On Dec 19, 11:01?am, walterbyrd wrote: > > To me, it seems that this: > > print "%s=%d" % ('this',99) > > Is much easier, and faster, to type, and is also easier to read and > understand. [snip] > > This (if it's right) is much longer, and requires more special > characters. > > print( "{0}={1}".format('this',99)) > Yeah, I like the old way better too. It's got this nice elegant simplicity to it (using the percent sign for not only the things inside the string, but also to separate it from the tuple that follows). Also, I like having only *one* special symbol (`%') to worry about in my strings instead of two (`{' and `}'). But, Python is Python. So I'll keep using the old way until they deprecate it, and then just get used to the new way. One reason I use Python is because I really *don't* have the time or inclination to question every little design decision and argue about alternatives. If you want to tweak the language to suit your personal tastes, you might prefer Perl 6. From aahz at pythoncraft.com Sun Dec 14 23:56:09 2008 From: aahz at pythoncraft.com (Aahz) Date: 14 Dec 2008 20:56:09 -0800 Subject: Looking for the best way to translate an idiom References: Message-ID: In article , James Stroud wrote: > >In case its not obvious: Ah, so that's where Bruno's extra apostrophe came from! ;-) (Sorry about the spelling flame, but seeing three posts in quick succession with incorrect spelling of its/it's pushed me into making a public comment.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From david_v_wright at yahoo.com Wed Dec 17 12:47:23 2008 From: david_v_wright at yahoo.com (david wright) Date: Wed, 17 Dec 2008 09:47:23 -0800 (PST) Subject: getting object instead of string from dir() Message-ID: <207545.62974.qm@web31805.mail.mud.yahoo.com> --- On Wed, 12/17/08, Rominsky wrote: From: Rominsky Subject: getting object instead of string from dir() To: python-list at python.org Date: Wednesday, December 17, 2008, 12:16 PM I am trying to use dir to generate a list of methods, variables, etc. I would like to be able to go through the list and seperate the objects by type using the type() command, but the dir command returns a list of strings.? When I ask for the type of an element, the answer is always string.? How do I point at the variables themselves.? A quick example is: a = 5 b = 2.0 c = 'c' lst = dir() for el in lst: ? ? print type(el) Right now I am understandably getting all types being output as strings, how do i get the type of the actual objects returned from dir ()? -- http://mail.python.org/mailman/listinfo/python-list Forgive me if you are well aware of this, just thought i'd chime in with the "Duck typing speech": Pythonic programming style that determines an object's type by inspection of its method or attribute signature rather than by explicit relationship to some type object ("If it looks like a duck and quacks like a duck, it must be a duck.") By emphasizing interfaces rather than specific types, well-designed code improves its flexibility by allowing polymorphic substitution. Duck-typing avoids tests using type() or isinstance(). Instead, it typically employs the EAFP (Easier to Ask Forgiveness than Permission) style of programming. http://en.wikipedia.org/wiki/Duck_typing From google at mrabarnett.plus.com Tue Dec 9 09:28:51 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 09 Dec 2008 14:28:51 +0000 Subject: "as" keyword woes In-Reply-To: <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> Message-ID: <493E80A3.1070107@mrabarnett.plus.com> Paul Boddie wrote: > On 9 Des, 14:24, Steven D'Aprano cybersource.com.au> wrote: >> That is not what Guido said. What he actually said was: >> >> "That's possible with sufficiently powerful parser technology, but >> that's not how the Python parser (and most parsers, in my experience) >> treat reserved words." > > I accept that many parsers are operating on predetermined tokens where > keywords will already have been identified as such, regardless of > their eventual syntactic context, by the time the parser gets to see > them. What I wanted to point out was that other approaches are not > exactly unheard of or particularly rare. Every now and again, the > language gets extended and new keywords are sought in an excruciating > process akin to a group writing exercise involving the existing > keywords. A better parsing framework would alleviate these problems. > > [Car analogy cut] > In some languages (I think Delphi is one of them - it's been a while!) some words which would normally be identifiers have a special meaning in certain contexts, but the syntax precludes any ambiguity, and not in a difficult way. "as" in Python was one of those. I certainly wouldn't want something like PL/I, where "IF", "THEN" and "ELSE" could be identifiers, so you could have code like: IF IF = THEN THEN THEN = ELSE; ELSE ELSE = IF; See http://en.wikipedia.org/wiki/PL/I_(programming_language). >> What Guido is saying is that even if he agreed with the OP he couldn't >> add that feature. He's not saying that he agrees with the OP. The Zen >> gives good reasons for believing that even if Python's parser was >> sufficiently powerful, he'd still consider the feature undesirable. > > Well, I think it's more interesting to explore the boundaries of what > can be done, to debunk notions that such things aren't being done in > the mainstream, and to examine whether they could benefit usability, > than it is to defer to the Zen of Python as some kind of prescriptive, > near-religious text at every turn. > > Paul > -- > http://mail.python.org/mailman/listinfo/python-list > From walterbyrd at iname.com Sat Dec 20 18:39:24 2008 From: walterbyrd at iname.com (walterbyrd) Date: Sat, 20 Dec 2008 15:39:24 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> <59153e28-bf86-4158-96d9-23aa5b9f0205@j35g2000yqh.googlegroups.com> Message-ID: <7889a362-d96e-4f1f-a66b-ef52b9cdb047@q26g2000prq.googlegroups.com> On Dec 20, 4:34?pm, r wrote: > Walter, > > Would you be kind enough to translate this code to the new syntax? I am sorry, but I just don't know the new syntax well enough. I am not sure if the examples that I have posted, so far, are correct. From luismgz at gmail.com Fri Dec 12 09:04:39 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Fri, 12 Dec 2008 06:04:39 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> Message-ID: <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> On Dec 12, 10:43?am, sturlamolden wrote: > On Dec 12, 2:29 pm, sturlamolden wrote: > > > Creating a fast implementation of a dynamic language is almost rocket > > science. But it has been done. There is Stronghold, > > I meant of course Strongtalk... Blah, blah, blah... Why don't you guys google a little bit to know what's being done to address python's "slowness"?? It has been mentioned in this thread the pypy project (isn't it enough for you??) Other hints: shedskin, psyco, pyrex... From antoine at vo.lu Sun Dec 7 15:06:28 2008 From: antoine at vo.lu (Antoine De Groote) Date: Sun, 07 Dec 2008 21:06:28 +0100 Subject: Guido's new method definition idea In-Reply-To: <493c1ff6$0$4942$426a34cc@news.free.fr> References: <493a9fed$0$18973$426a34cc@news.free.fr> <493c1ff6$0$4942$426a34cc@news.free.fr> Message-ID: <92c3f$493c2cc2$d9a2276f$18933@news.hispeed.ch> Bruno Desthuilliers wrote: > Daniel Fetchinson a ?crit : > (snip) >> It doesn't add anything but makes something that exists a bit clearer > > Err... I fail to see how magically transforming def self.foo(...) into > def foo(self, ...) makes anything clearer about what really happens and > how Python's object model works. > >> and friendlier to newbies. > > I'd rather say "more acceptable to java-brainwashed developpers". Nicely put! :-) From arnodel at googlemail.com Sun Dec 7 10:14:37 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 07 Dec 2008 15:14:37 +0000 Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> Message-ID: Erik Max Francis writes: [about removing self] > P.S. You're beating a long-dead horse here; your precise proposal has > been brought up countless times on comp.lang.python and shot down > every single time for the same reason. It isn't going to happen. I guess it's part of the process of learning Python :) -- Arnaud From anders.olme at gmail.com Sat Dec 13 05:58:48 2008 From: anders.olme at gmail.com (a_olme) Date: Sat, 13 Dec 2008 02:58:48 -0800 (PST) Subject: Umlauts in idle References: <26880ecf-d0eb-42ab-8ebd-56f64c023999@v39g2000pro.googlegroups.com> <4943829B.9050606@v.loewis.de> Message-ID: On 13 Dec, 10:38, "Martin v. L?wis" wrote: > > When I try to use umlauts in idle it will only print out as Unicode > > escape characters. Is it possible to configure idle to print them as > > ordinary characters? > > Did you really use the print statement? They print out fine for me. > > Regards, > Martin No I just put the characters in quotes like this "???"[::-1] and pressed return. //olme From martin.hellwig at dcuktec.org Wed Dec 17 08:03:39 2008 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 17 Dec 2008 13:03:39 +0000 Subject: [ANN] EuroPython 2009 =?windows-1252?Q?=96_Call_for_Partic?= =?windows-1252?Q?ipation!_?= Message-ID: <4948F8AB.7060809@dcuktec.org> On behalf of the EuroPython 2009 organisation it is my privilege and honour to announce the 'Call for Participation' for EuroPython 2009! EuroPython is the conference for the communities around Python, including the Django, Zope and Plone communities. This year's conference will be held in Birmingham, UK from Monday 29th June to Saturday 4th July 2009. Talks & Themes Do you have something you wish to present at EuroPython? Go to http://www.europython.eu/talks/cfp/ for this year's themes and submissions criteria, the deadline is on 5th April 2009. Other Talks, Activities and Events Have you got something which does not fit the above? Visit http://www.europython.eu/talks/ . Help Us Out We could use a hand any contribution is welcome, please take a look at http://www.europython.eu/contact/ . Sponsors An unique opportunity to affiliate with the prestigious EuroPython conference! http://www.europython.eu/sponsors/ Spread the Word Improve our publicity by distributing this announcement in your corner of the community, please coordinate this with the organizers: http://www.europython.eu/contact/ General Information For more information about the conference, please visit http://www.europython.eu/ Looking forward to see you! The EuroPython Team From rt8396 at gmail.com Tue Dec 2 17:16:45 2008 From: rt8396 at gmail.com (r) Date: Tue, 2 Dec 2008 14:16:45 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> Message-ID: OK...so here are the stat's so far. 6+BDFL - who would support my crazy idea, or think it -might- be ok 11 - who are on the fence 6 - who think this is a complete waste of time, a stupid idea, or just simply want to kill me -> from these stats i can deduce the following: total_members_comp.lang.python = 14433 note: I will be fair and remove spammers or members that don't follow this list anymore by dividing the total number in half.(this should be generous enough) total_actual_members = (14433/2) = 7214 total_num_responders = 11 ->current stats: <11> percentFor = 31 percentNay = 27 percentOnFence = 40 ->Forecast of turnout: <7214> potentialFors = 2,236.34 potentialConverts = 2,885.34 totalPotentials = 5,121.68 even if only 10% of these act...that is 512 people. I still have hope! import hope while hope.amt > 0: continue From castironpi at gmail.com Mon Dec 8 15:09:47 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 8 Dec 2008 12:09:47 -0800 (PST) Subject: appending values into array instead of a list References: Message-ID: <039825e2-3a59-4dd5-9c4b-69b03f3e9fbb@v4g2000yqa.googlegroups.com> On Dec 8, 9:03?am, trias wrote: > Hi, > ?I have this little script: snip > So on the above I am appending values from signaldict indexed by i for every > object in the ref list. This way I calculate the sum of all values with > similar indexing i value. Would I be able to store the signaldict[i] for > every line individually in a multidimensional array? ? I think you want arrays of tuples, not parallel arrays. Just append a tuple instead of a plain number. >>> a= [] >>> a.append( ( 10, -1 ) ) >>> a.append( ( 20, -1.1 ) ) >>> a [(10, -1), (20, -1.1000000000000001)] For true multidimensional arrays of a uniform type, there is 'numpy'. From deets at nospam.web.de Mon Dec 8 16:47:58 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 Dec 2008 22:47:58 +0100 Subject: xml.dom.minidom bug ? In-Reply-To: References: Message-ID: <6q5j0eFaq0g7U1@mid.uni-berlin.de> Sampsa Riikonen schrieb: > Dear All, > > I am experiencing a weird problem with the > xml.dom.minidom module: > ---------------------------------------- > sampsa at linux-ty84:~/python> python easyxml.py > Traceback (most recent call last): > File "easyxml.py", line 1, in > import xml.dom.minidom > File "/usr/lib64/python2.5/site-packages/_xmlplus/dom/__init__.py", line > 236, in > import MessageSource > File "/usr/lib64/python2.5/site-packages/_xmlplus/dom/MessageSource.py", > line 21, in > _ = get_translator("dom") > File "/usr/lib64/python2.5/site-packages/_xmlplus/FtCore.py", line 54, in > get_translator > f = gettext.translation('4Suite', locale_dir).gettext > File "/usr/lib64/python2.5/gettext.py", line 478, in translation > t = _translations.setdefault(key, class_(open(mofile, 'rb'))) > File "/usr/lib64/python2.5/gettext.py", line 180, in __init__ > self._parse(fp) > File "/usr/lib64/python2.5/gettext.py", line 264, in _parse > unpack = struct.unpack > AttributeError: 'module' object has no attribute 'unpack' > ------------------- > > A bug in the module? > > And the weirdest thing is that I figured out how to > get around this problem long time ago, but now I don't > have a clue anymore... :/ > > Any help appreciated. You don't happen to have a struct.py or struct.pyc lying around? To test this, execute *in the same directory your above code fails!!* $ python >>> import struct >>> struct.__file__ The result should be something below /usr/lib/python2.5/, if it's not - that's your culprit. Diez From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 8 04:49:34 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 08 Dec 2008 10:49:34 +0100 Subject: gzip.GzipFile (was Re: Don't you just love writing this sort of thing :)) In-Reply-To: References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: <493cedae$0$2052$426a74cc@news.free.fr> Jorgen Grahn a ?crit : (snip) > > Also, making a decision based on the .gz part of the name isn't > always correct -- you miss files named foo.Z and similar. .tgz anyone ? > /Jorgen > From gabriel.rossetti at arimaz.com Wed Dec 10 03:44:56 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Wed, 10 Dec 2008 09:44:56 +0100 Subject: memory leak? In-Reply-To: References: <493EAB79.6070805@arimaz.com> Message-ID: <493F8188.1030700@arimaz.com> Terry Reedy wrote: > Gabriel Rossetti wrote: > >> I ran these tests on linux 2.6 (ubuntu 8.04) using python 2.5.2. > > Have you tried the much newer 2.6? 2.5.3 will be out soon with some > bug fixes. > Thanks for the reply Terry, I just tried the pyserial example with python 2.6 and it still has the same problem, here's the output (I just copy/pasted the example in a running python2.6 interactive interpreter) : test1 at 09:19am : $ ps waux | grep python2.6 1000 6730 0.2 0.4 6176 4120 pts/12 S+ 09:17 0:00 python2.6 if I try the SIGUSR1 method : $ kill -SIGUSR1 6730 #################################################################### # DEBUG: The object count is : 12536 #################################################################### test2 at 09:25am : $ ps waux | grep python2.6 1000 6730 0.0 0.9 12360 10168 pts/12 S+ 09:17 0:00 python2.6 and the SIGUSR1 method gives me : #################################################################### # DEBUG: The object count is : 25089 #################################################################### I also tried freeing the received string (del t) explicitly but the results are unchanged. Thank you, Gabriel From google at mrabarnett.plus.com Mon Dec 8 17:34:26 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 08 Dec 2008 22:34:26 +0000 Subject: Text parsing via regex In-Reply-To: <9fdb569a0812081259kdafcb96n285419ccaa9d416b@mail.gmail.com> References: <9fdb569a0812081259kdafcb96n285419ccaa9d416b@mail.gmail.com> Message-ID: <493DA0F2.2000000@mrabarnett.plus.com> Vlastimil Brom wrote: > 2008/12/8 Robocop : >> I'm having a little text parsing problem that i think would be really >> quick to troubleshoot for someone more versed in python and Regexes. >> I need to write a simple script that parses some arbitrarily long >> string every 50 characters, and does not parse text in the middle of >> words (but ultimately every parsed string should be 50 characters, >> ... > > Hi, not sure, if I understand the task completely, but maybe some of > the variants below using re may help (depending on what should be done > further with the resulting test segments); > in the first two possibilities the resulting lines are 50 characters > long + 1 for "\n"; possibly 49 would be used if needed. > > > import re > > input_txt = """I'm having a little text parsing problem that i think > would be really > quick to troubleshoot for someone more versed in python and Regexes. > I need to write a simple script that parses some arbitrarily long > string every 50 characters, and does not parse text in the middle of > words (but ultimately every parsed string should be 50 characters, so > adding in white spaces is necessary). So i immediately came up with > something along the lines of:""" > > # print re.sub(r"((?s).{1,50}\b)", lambda m: m.group().ljust(50) + > "\n", input_txt) # re.sub using a function > I also thought of r"(.{1,50}\b)", but then I realised that there's a subtle problem: it says that the captured text should end on a word boundary, when, in fact, we just don't want it to split within a word. It would still be acceptable if it split between 2 non-word characters. Aargh! :-) > # for m in re.finditer(r"((?s).{1,50}\b)", input_txt): # adjusting > the matches via finditer > # print m.group().ljust(50) > > print [chunk.ljust(50) for chunk in re.findall(r"((?s).{1,50}\b)", > input_txt)] # adjusting the matched parts in findall > From deets at nospam.web.de Mon Dec 8 16:38:05 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 Dec 2008 22:38:05 +0100 Subject: ORB for Python and PHP In-Reply-To: References: Message-ID: <6q5idtFb0dk0U1@mid.uni-berlin.de> Laszlo Nagy schrieb: > We have a problem here. We have a website written in PHP. and many > programs written in Python. The communication between the components is > messy. os.system calls are mixed with popen, xml-rpc and others. We > would like to make it consistent and portable. We would like to use free > software. What are our options? I checked these: > > - Bonobo is the most advanced, but it can only handle C language > - FNORB is good for Python, but not for PHP > - OmniORB would be very good for C and Python, but not PHP > > There are others but they do not support both Python and PHP. Should I > implement my own ORB, or do you know a suitable solution? The whole purpose of an ORB ist that it is interoperable. So if you have a good python orb (I personally prefer OmniORB), and a good one for PHP - connect them. I would suggest a consistent XMLRPC-interface though. Diez From cjw at ncf.ca Mon Dec 22 14:28:16 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Mon, 22 Dec 2008 14:28:16 -0500 Subject: Check file is In-Reply-To: <494cbef5$0$90267$14726298@news.sunsite.dk> References: <7caa7d45-ebbe-4c88-bb50-2f01f7315d07@s9g2000prg.googlegroups.com> <494cbef5$0$90267$14726298@news.sunsite.dk> Message-ID: gardsted wrote: > Harish wrote: >> Hi Friends >> Is there any utility in python which will help me to read any pdf >> files? >> >> Regards >> Harish > > Not sure, what you're after exactly, but I tried googling 'python read pdf' > and found this, so maybe 'reportlab' is what you're looking for: > > Re: Reading PDF files > #2 > Dec 20th, 2006 > To read and manage Portable Document Files you can use the open source > ReportLab toolkit (written in Python) from: > http://www.reportlab.org/rl_toolkit.html > > kind regards jorgen The ReportLab toolkit appears to be concerned with building Portable Document Files. I would be interested in any utility which will read any pdf - for example, to convert pdf -> html Colin W. From arnodel at googlemail.com Thu Dec 4 12:31:46 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 04 Dec 2008 17:31:46 +0000 Subject: Overriding a method at the instance level on a subclass of a builtin type References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> Message-ID: "Zac Burns" writes: > The class method seems to be the most promising, however I have more > 'state' methods to worry about so I might end up building new classes > on the fly rather than have a class per permutation of states! Now the > code isn't quite as clear as I thought it was going to be. > > It seems unfortunate to me that methods are always looked up on the > class for new style objects. Was this done for speed reasons? It's only special methods such as __getitem__, ... You can override normal method on a per-object basis just by adding a callable attribute with its name to the object: >>> class A(object): ... def foo(self): print 'A.foo' ... >>> a = A() >>> a.foo() A.foo >>> def a_foo(): print 'a.foo' ... >>> a.foo = a_foo >>> a.foo() a.foo -- Arnaud From arnodel at googlemail.com Wed Dec 10 16:31:49 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 10 Dec 2008 21:31:49 +0000 Subject: [OT] Google Groups in bad odour References: <4d5498bf-bbf0-4760-83fc-610729bcbce2@h20g2000yqn.googlegroups.com> Message-ID: Frank Millman writes: > Hi all > > I know there have been complaints about spam on Google Groups over the > last few months, with some members rejecting all traffic from them. > > You might be interested in this comment I got in a reply from someone > on comp.os.linux.setup - > > "If you want to be read by a wider audience, you really want to post > from > someplace other than Google Groups. Many (most?) readers of the > Linux > lists kill everything from there automatically." > > Unfortunately it seems that their newsgroup does not have a mail > gateway, so I cannot use gmane. (Please correct me if I am wrong). I > will therefore have to find a suitable news client. Any > recommendations? > > Frank Millman I use Gnus, I don't kill posts from groups.google.com and I don't get a lot of spam. When I do I just press 'Laep'. -- Arnaud From robert.kern at gmail.com Thu Dec 18 19:04:19 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 18 Dec 2008 18:04:19 -0600 Subject: Which sparse matrix package? In-Reply-To: <20081218231851.70dd91e2@Schlamber.localdomain> References: <20081218231851.70dd91e2@Schlamber.localdomain> Message-ID: Martin Manns wrote: > Should I use another type of matrix in scipy.sparse? If yes which? If you have a benchmark, you might just want to try all of them. Should be just a matter of a small script. Block Sparse Row (bsr_matrix) might be the most appropriate in terms of data structure, but it appears that a bunch of stuff important for your use case is unimplemented. > Does a different data-structure suit my above-stated needs better? Something similar to a quadtree might be more suitable. That should let you do queries along both dimensions easily. You probably don't want exactly a quadtree, though; it's good for scattered points, but probably not for largish blocks of points on a precise grid, which you will probably see frequently in a spreadsheet application. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From rocky at panix.com Fri Dec 12 23:14:53 2008 From: rocky at panix.com (R. Bernstein) Date: 12 Dec 2008 23:14:53 -0500 Subject: Deeper tracebacks? References: Message-ID: "Gabriel Genellina" writes: .. > No, last_traceback is the last *printed* traceback in the interactive > interpreter. Well more precisely the traceback that is passed to sys.excepthook() when an unhandled exception occcurs, since the hook that might not decide to print anything ;-) > Use the third element in sys.exc_info() instead: Hmm... I'm not sure what I was thinking when I read that way back when, but you are correct and caught a bug in my code. I really do need to do better about writing tests. Maybe next incarnation... Thanks. From google at mrabarnett.plus.com Sat Dec 13 20:29:59 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 14 Dec 2008 01:29:59 +0000 Subject: subprocess to C program In-Reply-To: <0ebd59c5-95a1-42d4-b597-d1c248490b8e@y1g2000pra.googlegroups.com> References: <0ebd59c5-95a1-42d4-b597-d1c248490b8e@y1g2000pra.googlegroups.com> Message-ID: <49446197.6020607@mrabarnett.plus.com> Aaron Brady wrote: > Hi, > > I am writing a C process and I want to read data from a file that I > write to in Python. I'm creating a pipe in Python, passing it to the > C process, and calling '_read'. It gives me error 9, bad file number. > > Python code: > > import subprocess as s, os > r, w= os.pipe( ) > os.write( w, 'abcdefghij\n' ) > a= s.Popen( [ r'C:\Documents and Settings\usr\Desktop\working > \try_start', '%i'%r, '%i'%w ] ) > > C code: > > char buf[ 16 ]; > memset( buf, 0, 16 ); > int readfd= atoi( argv[ 1 ] ); > int ct= _read( readfd, buf, 15 ); > printf( "\n\n'_read %i %i %i': %s\n", ct, readfd, errno, buf ); > > Output: > > '_read -1 3 9' > > meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9. I want 'ct' > to be 11 at this point. Thanks in advance. > It looks like the ids aren't system global. From prologic at shortcircuit.net.au Wed Dec 17 18:34:12 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 18 Dec 2008 09:34:12 +1000 Subject: The rule of literal string In-Reply-To: <47c890dc0812171525t527353e2m5c8b0597ee183e21@mail.gmail.com> References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> <_PmdnU59w62vGtTUnZ2dnUVZ_hSdnZ2d@pdx.net> <34028b73-7807-4e88-80bc-fe31a7b1a2a0@i20g2000prf.googlegroups.com> <47c890dc0812171525t527353e2m5c8b0597ee183e21@mail.gmail.com> Message-ID: On Thu, Dec 18, 2008 at 9:25 AM, Chris Rebert wrote: > As I stated previously, the key rule is: > > eval(repr(something)) == something This rule is only true for basic data types; For example: >>> eval(repr(1)) == 1 True >>> eval(repr([1, 2, 3])) == [1, 2, 3] True >>> eval(repr({"a": 1, "b": 2, "c": 3})) == {"a": 1, "b": 2, "c": 3} True >>> eval(repr("foo")) == "foo" True I guess the key thing here is that the repr implementation (__repr__) for str, int, float list and dict return sensible represenations that Python _can_ evaluate with eval(...) --JamesMills From tjreedy at udel.edu Tue Dec 9 13:18:26 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 09 Dec 2008 13:18:26 -0500 Subject: Python 3 For Python 2 Users In-Reply-To: References: Message-ID: Tim Daneliuk wrote: > I code in Python 2.x intermittently and have only casually watched the > 3.x development discussions. Now it's time to get up to speed. > Has someone written a tutorial for people in my situation. Yes, I've > looked at the release notes, but I'm looking for something that > motivates all the major changes to give me a better sense of the > Gestalt of the new language. All classes are subclasses of object. Text strings are unicode. Miscellaneous deletions. Some new stuff, especially ABCs, though it may be awhile before they really inpact Python practice. From iofferkicks24 at gmail.com Thu Dec 25 00:36:11 2008 From: iofferkicks24 at gmail.com (www.iofferkicks.com) Date: Wed, 24 Dec 2008 21:36:11 -0800 (PST) Subject: www.iofferkicks.com china cheap wholesale nike shoes,air jordan shoes,air force one shoes. Message-ID: <3308d5ee-ff78-4126-b314-a5dfa9516b88@l33g2000pri.googlegroups.com> Get Nike Shoes at Super Cheap Prices Discount Nike air jordans (www.iofferkicks.com) Discount Nike Air Max 90 Sneakers (www.iofferkicks.com) Discount Nike Air Max 91 Supplier (www.iofferkicks.com) Discount Nike Air Max 95 Shoes Supplier (www.iofferkicks.com) Discount Nike Air Max 97 Trainers (www.iofferkicks.com) Discount Nike Air Max 2003 Wholesale (www.iofferkicks.com) Discount Nike Air Max 2004 Shoes Wholesale (www.iofferkicks.com) Discount Nike Air Max 2005 Shop (www.iofferkicks.com) Discount Nike Air Max 2006 Shoes Shop (www.iofferkicks.com) Discount Nike Air Max 360 Catalogs (www.iofferkicks.com) Discount Nike Air Max Ltd Shoes Catalogs (www.iofferkicks.com) Discount Nike Air Max Tn Men's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 2 Women's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 3 Customize (www.iofferkicks.com) Discount Nike Air Max Tn 4 Shoes Customize ( www.iofferkicks.com) Discount Nike Air Max Tn 6 Supply (www.iofferkicks.com) Discount Nike Shox NZ Shoes Supply (www.iofferkicks.com) Discount Nike Shox OZ Sale (www.iofferkicks.com) Discount Nike Shox TL Store (www.iofferkicks.com) Discount Nike Shox TL 2 Shoes Store (www.iofferkicks.com) Discount Nike Shox TL 3 Distributor (www.iofferkicks.com) Discount Nike Shox Bmw Shoes Distributor (www.iofferkicks.com) Discount Nike Shox Elite Shoes Manufacturer (www.iofferkicks.com) Discount Nike Shox Monster Manufacturer (www.iofferkicks.com) Discount Nike Shox R4 Running Shoes (www.iofferkicks.com) Discount Nike Shox R5 Mens Shoes (www.iofferkicks.com) Discount Nike Shox Ride Womens Shoes (www.iofferkicks.com) Discount Nike Shox Rival Shoes Wholesaler (www.iofferkicks.com) Discount Nike Shox Energia Wholesaler (www.iofferkicks.com) Discount Nike Shox LV Sneaker (www.iofferkicks.com) Discount Nike Shox Turbo Suppliers (www.iofferkicks.com) Discount Nike Shox Classic Shoes Suppliers (www.iofferkicks.com) Discount Nike Shox Dendara Trainer (www.iofferkicks.com) Discount Nike Air Jordan 1 Seller (www.iofferkicks.com) Discount Nike Air Jordan 2 Shoes Seller (www.iofferkicks.com) Discount Nike Air Jordan 3 Collection (www.iofferkicks.com) Discount Nike Air Jordan 4 Shoes Collection (www.iofferkicks.com) Discount Nike Air Jordan 5 Chaussure Shoes (www.iofferkicks.com) Discount Nike Air Jordan 6 Catalog (www.iofferkicks.com) Discount Nike Air Jordan 7 Shoes Catalog (www.iofferkicks.com) Discount Nike Air Jordan 8 Customized (www.iofferkicks.com) Discount Nike Air Jordan 9 Shoes Customized (www.iofferkicks.com) Discount Nike Air Jordan 10 Wholesalers (www.iofferkicks.com) Discount Nike Jordan 11 Shoes Wholesalers (www.iofferkicks.com) Discount Nike Air Jordan 12 Factory (www.iofferkicks.com) Discount Nike Air Jordan 13 Shoes Factory (www.iofferkicks.com) Discount Nike Air Jordan 14 Shoes Sell (www.iofferkicks.com) Discount Nike Air Jordan 16 Exporter (www.iofferkicks.com) Discount Nike Air Jordan 17 Shoes Exporter (www.iofferkicks.com) Discount Nike Air Jordan 18 Offer (www.iofferkicks.com) Discount Nike Air Jordan 19 Shoes Offer (www.iofferkicks.com) Discount Nike Air Jordan 20 Manufacture (www.iofferkicks.com) Discount Nike Jordan 21 Shoes Manufacture (www.iofferkicks.com) EMAIL:IOFFERKICKS at GMAIL.COM MSN :IOFFERKICKS at MSN.COM From andre.roberge at gmail.com Wed Dec 17 22:34:44 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Wed, 17 Dec 2008 19:34:44 -0800 (PST) Subject: getting object instead of string from dir() References: <477b9c2e-a0ab-4b26-b643-4a9369c2aaac@r2g2000vbp.googlegroups.com> Message-ID: On Dec 17, 3:52?pm, Rominsky wrote: > > I do have some understanding of the pythonic methodology of > programming, though by far I still don't consider myself an expert. > The problem at hand is that I am coming from a matlab world and trying > to drag my coworkers with me. ?I have gotten a lot of them excited > about using python for this work, but the biggest gripe everytime is > they want their matlab ide. ?I am trying to experiment with making > similar pieces of the ide, in particular I am working on the workspace > window which lists all the current variables in the namespace, along > with their type, size, value, etc.... ?I am trying to create a python > equivalent. ? You might want to have a look at http://www.physics.ox.ac.uk/users/santoso/Software.WebLab.html Andr? From jstroud at mbi.ucla.edu Fri Dec 5 05:13:49 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 05 Dec 2008 02:13:49 -0800 Subject: dict subclass and pickle bug (?) Message-ID: Hello All, I subclassed dict and overrode __setitem__. When instances are unpickled, the __setstate__ is not called before the keys are assigned via __setitem__ in the unpickling protocol. I googled a bit and found that this a bug filed in 2003: http://bugs.python.org/issue826897 It is still "open" with "normal" priority. Am I missing something? Is there a workaround for this bug that makes fixing it pointless or has it just fallen through the cracks for the last 5 years? Here is an example: class DictPlus(dict): def __init__(self, *args, **kwargs): self.extra_thing = ExtraThingClass() dict.__init__(self, *args, **kwargs) def __setitem__(self, k, v): do_something_with(self.extra_thing, k, v) dict.__setitem__(self, k, v) Upon unpickling, the error would be: AttributeError: 'DictPlus' object has no attribute 'extra_thing' I'm still using python 2.5.1. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From george.sakkis at gmail.com Sun Dec 7 13:53:58 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 7 Dec 2008 10:53:58 -0800 (PST) Subject: how to get a beep, OS independent ? References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> Message-ID: On Dec 7, 7:49?am, Stef Mientki wrote: > Chris Rebert wrote: > > On Sun, Dec 7, 2008 at 1:27 AM, Stef Mientki wrote: > > >> Rainy wrote: > > >>> On Dec 6, 3:40 pm, Stef Mientki wrote: > > >>>> hello, > > >>>> I want to give a small beep, > >>>> for windows there's message-beep, > >>>> and there seems to be something like " curses" , > >>>> but that package seems to be totally broken in P2.5 for windows. > > >>>> Any other suggestions ? > > >>>> thanks, > >>>> Stef Mientki > > >>> For win there's winsound, you have to check sys.platform and do > >>> what's necessary for the platform in question. In linux I think > >>> you can just print '\a' (or does that only work in terminals?). > >>> If you know that ext. speakers are always on, you can do a nicer > >>> beep by using some wav file, in linux it's probably easiest to > >>> use an external program to play it, like wavplay. Basically, > >>> there is no single answer, it depends on circumstances. > >>> -- > >>>http://mail.python.org/mailman/listinfo/python-list > > >> '\a' or chr(7) prints an inverted "BEL". > > > Inverted bell? > > In the output window (stdout) which is black letters on white background, > it prints "bell" in white letters with a black background.> ?What do you mean? And what version dependency are you > > referring to? > > Well some of you actually hear something, > I don't, > so I expect that the Python version differs. Works for me on WinXP, Python 2.5: C:\>python -c "print chr(7)" makes a beep. George From nick at craig-wood.com Wed Dec 3 04:32:50 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 3 Dec 2008 09:32:50 +0000 Subject: Do more imported objects affect performance In-Reply-To: <493602CB.2020907@holdenweb.com> References: <1be78d220812010621u51dead9dnbaa0b4c8c9414362@mail.gmail.com> <493602CB.2020907@holdenweb.com> Message-ID: <20081203093250.GA17602@craig-wood.com> On Tue, Dec 02, 2008 at 10:53:47PM -0500, Steve Holden wrote: > Pardon me for intruding, but timings here are entirely the wrong focus > for a Python newcomer. Given that imports are super-optimized (i.e. the > code in the module is only performed once) such a small difference in > timing is inconsequential, I would suggest. > > As long as "from module import *" is only ever used with modules > specifically designed to support it, the other forms can be used as > required. Sure, there is a timing difference between > > import module > ... > module.something() > > and > > from module import something > ... > something() > > but that's hardly the point. Learning to write sound Python is *much* > more important that learning to write fast Python, and often the two > coincide anyway. > > It was true when Kernighan and Plauger wrote it forty years ago and it's > true now: "First, make it work. Then, *if it doesn't work fast enough*, > make it work faster". You are 100% right of course Steve. I was just trying to answer the specific question "which is faster" question which probably isn't helpful for new Python programmers to focus on. PS I enjoyed your book :-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From sjmachin at lexicon.net Mon Dec 8 23:44:53 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 8 Dec 2008 20:44:53 -0800 (PST) Subject: How to initialize a class variable once References: Message-ID: <804363f5-458a-4e72-8b2f-ad9c3c28b6cb@s9g2000prg.googlegroups.com> On Dec 9, 3:36?pm, Matimus wrote: > On Dec 8, 8:08?pm, Roy Smith wrote: > > > I've got a class with a class variable: > > > class Foo: > > ? ?_map = {} > > > How do I make sure this only gets initialized the *first* time the > > module containing the class is imported? ?What appears to be happening > > as it stands is each time the module gets imported, Foo._map get re- > > initialized. > > Unless you are calling reload() on the module, it will only ever get > _loaded_ once. Each additional import will just yield the existing > module. Perhaps if you post an example of the behavior that leads you > to believe that the class variables are getting reinitialized and change it to class Foo(object): because we care little about old-style classes these days and put a print statement in the module just before the class statement and print statements before and after each import statement so that we can see what is happening. From vedranf at vedranf.mine.nu Fri Dec 19 06:57:35 2008 From: vedranf at vedranf.mine.nu (=?ISO-8859-1?Q?Vedran_Furac=28?=) Date: Fri, 19 Dec 2008 12:57:35 +0100 Subject: List comprehension in if clause of another list comprehension In-Reply-To: References: Message-ID: Peter Otten wrote: > The problem is that list comprehensions do not introduce a new namespace. So > the inner and the outer list comp share the same i. You can either rename > the inner i > >>>> [i for i in a if i not in [k for k in b]] > ['b'] > > or use a generator expression which does give a new namespace: > >>>> list(x for x in "abc") > ['a', 'b', 'c'] >>>> x > Traceback (most recent call last): > File "", line 1, in > NameError: name 'x' is not defined > >>>> [i for i in a if i not in (i for i in b)] > ['b'] Thanks! From gagsl-py2 at yahoo.com.ar Tue Dec 9 01:51:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Dec 2008 04:51:14 -0200 Subject: close has no effect on Mac OSX Python 3.0 References: <83b43edf-81e5-4116-ad7b-2dcacde2d101@f3g2000yqf.googlegroups.com> Message-ID: En Mon, 08 Dec 2008 20:09:23 -0200, resi147 escribi?: > I'm wondering if it's really a bug since it's so trivial: > > fp = open('/etc/services') > ct = fp.read(1048) > print(ct[-80:], end='') > fp.close() > ct = fp.read(17) > print(ct) > > the second read should fail, but happily continues reading the file. > Really a bug? Looks like a real bug to me. In fact it is already reported: http://bugs.python.org/issue4604 -- Gabriel Genellina From lewis.sarah93 at yahoo.com Thu Dec 4 23:56:37 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 20:56:37 -0800 (PST) Subject: Earn Serous money Message-ID: <24612aa6-38dc-4695-b67e-b72a1b636a1d@d14g2000yqb.googlegroups.com> Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From almar.klein at gmail.com Mon Dec 1 03:38:30 2008 From: almar.klein at gmail.com (Almar Klein) Date: Mon, 1 Dec 2008 09:38:30 +0100 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: I did some image processing in Mathematica once. It allocated 2GB of memory to do display a normal size image. The professor (not of my university) who gave the course I was following then, was a big Mathematica fan. He also used lots of sentences containing "quite striking", "highly efficient", "extreme" and other power-terms. I know see whom he got it from. When I hear a person talk like that for long enough, everything he says starts to sound like lies. One good example was the bold statement that Mathematica is MUCH faster than Matlab. Clearly, when considering low level task like convolution both programs will use efficient C implementations, and I can't imagine one being faster than the other. Personally, I liked Mathematica for symbolic calculations, but for numerical stuff, frankly, it sucks. Glad to get that off my chest. Cheers, Almar 2008/12/1 Xah Lee > On Nov 30, 7:30 pm, Xah Lee wrote: > > Wolfram Research's Mathematica Version 7 has just been released. > > > > See: http://www.wolfram.com/products/mathematica/index.html > > > > Among it's marketing material, it has a section on how mathematica > > compares to competitors. > http://www.wolfram.com/products/mathematica/analysis/ > > Stephen Wolfram has a blog entry about Mathematica 7. Quite amazing: > > http://blog.wolfram.com/2008/11/18/surprise-mathematica-70-released-today/ > > Mathematica today in comparsion to all other existing langs, can be > perhaps compared to how lisp was to other langs in the say 1980s: > Quite far beyond all. > > Seeing how lispers today still talking about how to do basic list > processing with its unusable cons, and how they get giddy with 1980's > macros (as opposed to full term rewriting), and still lack pattern > matching, one feels kinda sad. > > see also: > > ? Fundamental Problems of Lisp > http://xahlee.org/UnixResource_dir/writ/lisp_problems.html > > Xah > ? http://xahlee.org/ > > ? > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gh at ghaering.de Thu Dec 4 08:13:37 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 04 Dec 2008 14:13:37 +0100 Subject: Pythonic design patterns In-Reply-To: References: Message-ID: Slaunger wrote: > Hi comp.lang.python > > I am this novice Python programmer, who is not educated as a computer > scientist (I am a physicist), and who (regrettably) has never read the > GOF on design patterns. [...] > I guess I could boost my productivity by learning these well-proven > and well-established design patterns by heart. At least for me I only getter better by actually training. For programming this means: write code. Revisit it later, improve on it. Of course one often wants to apply all cool new tricks you've learnt. That's normal, but remember: """ Brian Kernighan Law of Debugging Difficulty Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -- Brian Kernighan """ > I was therefore wondering if you could recommend a book or a resource > concerning design patterns with special focus on the possibilities in > Python? [...] I have this in my bookmarks: http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html -- Gerhard From martin.hellwig at dcuktec.org Sat Dec 6 13:46:47 2008 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Sat, 06 Dec 2008 18:46:47 +0000 Subject: Learning Python now coming from Perl In-Reply-To: <493ac32b$0$30907$426a74cc@news.free.fr> References: <493ac32b$0$30907$426a74cc@news.free.fr> Message-ID: <493ac897$0$190$e4fe514c@news.xs4all.nl> News123 wrote: > > What's more painful is to learn which functianilty is in which library > and which library exists. > Yes and one mistake I still often find myself doing is, when confronted with a particular problem, that I write some helper code to deal with it. Of course later on I discover that there is a standard module or built-in that does exactly what I want and better. :-) Somehow in the heat of the moment my mind is not thinking 'there must be something out there which does what I want' but rather 'hmmm I think I can do it this way, clicker-di-click'. In my opinion it is a positive attribute to the language that it makes solving problems so easy that you forget about searching for solutions. Maybe python should prompt every 10 lines of code a message saying 'Are you sure this can not be done with a built-in?' Most of the time it will be right anyway :-) -- mph From jpablo.romero at gmail.com Tue Dec 9 08:32:46 2008 From: jpablo.romero at gmail.com (=?ISO-8859-1?Q?Juan_Pablo_Romero_M=E9ndez?=) Date: Tue, 9 Dec 2008 07:32:46 -0600 Subject: Compiling and installing python 2.5.2 with Visual C++ 2008 Message-ID: Hello all, I need to compile python myself because of a module (pivy). So I downloaded MS Visual C++ 2008 express edition. It apparently compiled fine but I don't know how to install it to recreate the standard distribution. In linux i'd take "make install", but on windows? Regards, Juan Pablo From kenneth.m.mcdonald at sbcglobal.net Sun Dec 28 18:22:47 2008 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Sun, 28 Dec 2008 17:22:47 -0600 Subject: Any equivalent to Ruby's 'hpricot' html/xpath/css selector package? Message-ID: <6AA1A7D9-FA43-4413-9041-D5D2CB6EFE6F@sbcglobal.net> Ruby has a package called 'hpricot' which can perform limited xpath queries, and CSS selector queries. However, what makes it really useful is that it does a good job of handling the "broken" html that is so commonly found on the web. Does Python have anything similar, i.e. something that will not only do XPath queries, but will do so on imperfect HTML? (A good HTML neatener would also be fine, of course, as I could then pass the result to a Python XPath package.) And, what are people's favorite Python XPath solutions? Thanks, Ken McDonald From python.list at tim.thechases.com Wed Dec 10 14:33:19 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 10 Dec 2008 13:33:19 -0600 Subject: Python is slow In-Reply-To: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: <4940197F.8050705@tim.thechases.com> [nibbling a little flame-bait] > Python is even slower than PHP! > > Just go to any Python website and you will know. > An example is: > http://www2.ljworld.com/ I'm not sure I'm seeing what you're seeing -- the dynamic page loaded in under 2 seconds -- about on par with sun.com, python.org, php.net or msn.com all being pulled from non-cached servers. You sure you're not mistaking your bandwidth and/or browser-rendering slowness for Python-as-a-web-server slowness? Would it be nice if Python was faster? Sure, why not? Does it meet my needs speed-wise? 99% of the time, yes. With Psyco, 99.9% of the time. As has been shown repeatedly over the last couple months, algorithm-choice makes a far greater impact than some python tweaks. Most of my time spent waiting is usually on I/O (disk, network, or user). And those times I've experienced slowness where I'm not waiting on I/O, it's always been an algorithm aspect (an O(N**2) fuzzy comparison algorithm is my prime offender). A faster Python might shave a 30-60 seconds off a 10 minute run, but it's still a walk around the office either way. > Python is slow. Very slow. However until you have a use-case that *you* have implemented with *real code*, publicly vetted the algorithm, and THEN find it slow as demonstrated by profiled timings, I'm afraid it's all just unsubstantiated hot air to say categorically that "python is slow". It might be "too slow to do some particular CPU-intensive task", but it's repeatedly proven quite sufficient for a wide variety of development needs. -tkc From steve at holdenweb.com Tue Dec 9 23:31:55 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 09 Dec 2008 23:31:55 -0500 Subject: what's so difficult about namespace? In-Reply-To: <7480c61b-cece-47f8-9833-f739312a9e68@a3g2000prm.googlegroups.com> References: <67b23938-1761-4bd7-92b4-6972a73fedb6@d42g2000prb.googlegroups.com> <4491627a-eb71-4c2e-81cd-2b9a9bdbcdb6@r15g2000prd.googlegroups.com> <7480c61b-cece-47f8-9833-f739312a9e68@a3g2000prm.googlegroups.com> Message-ID: Xah Lee wrote: [...] > Steve Holden wrote: >> And therein lies the danger of imagination. > >> Typically the namespace components are looked up one by one, so for >> >> this.that.theother >> >> first "this" will be looked up and (hopefully) yield an object with a >> namespace, which will then be searched for "that", yielding another >> object with a namespace in which "theother" can be looked up. That's >> certainly how it works in Python: > > yes, but Steve, what is your point? > > The question is, what is the technical difficulty, if any, of > introducing namespace into a existing language. > > You pointed out that identifier lookup at least from the perspective > of language user is somewhat like a tree walking processing. However, > that does not answer the main question. > Yawn. My point was you oversimplified the problem due to your ignorance of the issues. You are a good writer when you stick to what you know and avoid the rabid profanity. Unfortunately that doesn't happen often enough for my taste. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From stef.mientki at gmail.com Fri Dec 26 19:41:40 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 27 Dec 2008 01:41:40 +0100 Subject: Is there a function to remove escape characters from a string ? In-Reply-To: <5a29b62a-c38f-409b-8887-6259ad072bf5@w1g2000prk.googlegroups.com> References: <0163882f$0$6988$c3e8da3@news.astraweb.com> <5a29b62a-c38f-409b-8887-6259ad072bf5@w1g2000prk.googlegroups.com> Message-ID: <495579C4.7050502@gmail.com> John Machin wrote: > On Dec 27, 12:05 am, Stef Mientki wrote: > > >> Yep, chr(254), because it's not in the human range of characters >> and it's accepted by windows ini-files. >> > > >>>> import unicodedata as ucd >>>> for i in (0,1,2,3,4,7,8): >>>> > ... s = chr(254) > ... enc = 'cp125' + str(i) > ... try: > ... u = s.decode(enc) > ... except UnicodeDecodeError: > ... continue > ... print enc, 'U+%04X' % ord(u), ucd.name(u) > ... > cp1250 U+0163 LATIN SMALL LETTER T WITH CEDILLA > cp1251 U+044E CYRILLIC SMALL LETTER YU > cp1252 U+00FE LATIN SMALL LETTER THORN > cp1253 U+03CE GREEK SMALL LETTER OMEGA WITH TONOS > cp1254 U+015F LATIN SMALL LETTER S WITH CEDILLA > cp1257 U+017E LATIN SMALL LETTER Z WITH CARON > cp1258 U+20AB DONG SIGN > > Either you have a strange and narrow definition of "human", or you are > so brave as to cheerfully insult (inter alia) Romanians, Russians, > Icelanders, Greeks, Turks, Czechs, Estonians, Finns, Slovaks, > Slovenians, and Vietnamese :-) > Sorry if I offended someone, that was certainly not my intention. And I guess you will be surprised, if I tell you, I don't (want) to understand any bit of the above code ;-) Come on, the home computer was invented about 1980. If we look at hardware, it follows the Moore's law, for software I would expect at least 0.1 of Moore's law ;-) I hope that clarifies my point. cheers, Stef From greg at cosc.canterbury.ac.nz Thu Dec 11 18:46:22 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 12 Dec 2008 12:46:22 +1300 Subject: Preventing execution of a method In-Reply-To: References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> <764daeef-bfbe-411a-8521-bb114321e4ac@b38g2000prf.googlegroups.com> <19304f8c-e34f-4aa9-8df2-6a7d3553007a@e1g2000pra.googlegroups.com> <2eed8876-94d2-4304-88a5-eb4a78b4f41d@33g2000yqm.googlegroups.com> <307fe197-1b42-4305-af0e-94b7ebe3ce70@r15g2000prh.googlegroups.com> <49417c59$0$8491$426a74cc@news.free.fr> Message-ID: <6qdmthFc5ggdU1@mid.individual.net> Emanuele D'Arrigo wrote: > -IF- the application was single-user yes, it wouldn't be a big deal. > But as it is potentially multi-user, I don't want one party to corrupt > the application for everybody else. In that case you definitely want a client-server architecture, with the server managing all the critical data. -- Greg From cmgui2 at gmail.com Mon Dec 22 13:42:49 2008 From: cmgui2 at gmail.com (cm_gui) Date: Mon, 22 Dec 2008 10:42:49 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> <6r6hpfFfb643U3@mid.uni-berlin.de> <494E6FDA.4070401@mrabarnett.plus.com> <4585c27d-d7a9-480f-991c-a869161be55c@g38g2000yqn.googlegroups.com> <3392a51b-d3fd-4986-9c59-fecccc7272da@p2g2000prn.googlegroups.com> Message-ID: <6aad831b-80ce-40df-9b6e-571b1e822795@s1g2000prg.googlegroups.com> On Dec 22, 6:51?am, Lou Pecora wrote: > In article , > ?"James Mills" wrote: > > > In case anyone is not aware, Python is > > also used for heavy scientific computational > > problems, games such as Civilisation and > > others, and I believe (correct me if I"m wrong) > > it's also used by NASA. > > > --JamesMills > i am referring mainly to Python for web applications. Python is slow. > Python has become very popular in scientific computation. ?You'll find > it in use lots of places (universities, national labs, defense labs). ?I > use it for solving partial differential equations for quantum chaos > calculations and went to C for speed up where needed using ctypes which > is very straightforward and plays nice with numpy array/matrix > libraries. ?I've been doing scientific programming for 30 years. ?Python > with C extensions and libraries is the best approach I've ever used. ? > Calculation speed is not a problem and the code can be "tweaked" to > increase it easily. ?Programming speed is incredible. ?I can get > substantial object oriented code up and running much faster than > anything I've ever used. > > -- > -- Lou Pecora From martin at v.loewis.de Fri Dec 19 01:30:13 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Fri, 19 Dec 2008 07:30:13 +0100 Subject: Python for amd64 and mingw-w64 In-Reply-To: References: Message-ID: <494B3F75.10104@v.loewis.de> > - Any extension requires the MS_WIN64 to be defined, but this symbol > is only defined for MS compiler (in PC/pyport.h). Why do you say that? It is only defined when _WIN64 is defined; this has nothing to do with a MS compiler. > Shouldn't it be > defined independantly of the compiler ? You mean, completely unconditional? Definitely not, it should only be defined when you are compiling for 64-bit mode. > - I have some link problems related to Py_InitModule4_64. I believe > the problem is in libpython26.a, which according to nm does not have > this symbol defined, whereas python26.dll has. It's a mistake if libpython26.a gets included in the Win64 installer at all; this library is only provided for 32-bit systems. My copy of mingw doesn't support Win64 at all. Regards, Martin From castironpi at gmail.com Sat Dec 13 21:54:37 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 13 Dec 2008 18:54:37 -0800 (PST) Subject: subprocess to C program References: <0ebd59c5-95a1-42d4-b597-d1c248490b8e@y1g2000pra.googlegroups.com> <8MidneyhDfIG-9nUnZ2dnUVZ_uadnZ2d@posted.visi> Message-ID: <36656830-63a8-479c-8c46-525f2b55eeea@z28g2000prd.googlegroups.com> On Dec 13, 7:51?pm, Grant Edwards wrote: > On 2008-12-14, MRAB wrote: > > > > >> I am writing a C process and I want to read data from a file that I > >> write to in Python. ?I'm creating a pipe in Python, passing it to the > >> C process, and calling '_read'. ?It gives me error 9, bad file number. snip > >> meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9. ?I want 'ct' > >> to be 11 at this point. ?Thanks in advance. > > > It looks like the ids aren't system global. > > They certainly aren't in Unix: Their a property of the process. > > -- > Grant I'm not on Unix. It has to be possible somehow. Do I need to set permissions on the IDs? Are Stdin and Stdout my only options? Or does Popen prevent sharing IDs somehow? From jstroud at mbi.ucla.edu Mon Dec 15 03:53:53 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 15 Dec 2008 00:53:53 -0800 Subject: alt.possessive.its.has.no.apostrophe In-Reply-To: <87r649g9dg.fsf@benfinney.id.au> References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > James Stroud writes: > >> Ben Finney wrote: >>> James Stroud writes: >>> >>>> Yes. I think it was the British who decided that the apostrophe >>>> rule for "it" would be reversed from normal usage relative to >>>> just about every other noun. > > It also seems an indefensible claim to say that anyone ?decided? it > would be that way, especially ?the British?. > >>> Remember that ?it? is a pronoun. I see no reversal: >> Ok. Pronouns are reversed. > > Or, more generally: Pronouns, which are different in just about every > other way from other nouns, are different in this way also. Is that > about right? > Can we start talking about python again? -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From rt8396 at gmail.com Fri Dec 12 12:59:55 2008 From: rt8396 at gmail.com (r) Date: Fri, 12 Dec 2008 09:59:55 -0800 (PST) Subject: newbie question... References: Message-ID: yes, but your script will need to know hoe to handle this.the following will open a file who's name was passed to the script if len(sys.argv) > 1: try: open_file(fname=sys.argv[1]) except: pass From manu3d at gmail.com Thu Dec 11 19:33:02 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 11 Dec 2008 16:33:02 -0800 (PST) Subject: Bidirectional Networking Message-ID: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> Hi everybody! A networking question! I've been looking at and tinkering a little with the various networking modules in python. The examples are pretty clear and a module such as the SimpleXMLRPCServer is actually simple! All the examples though are based on a client interrogating a server, with the client initiating the connection, obtaining something and then closing the connection. Basically the server is a reactive party: only if the client get in touch the server respond. What if the server wanted to notify the client of something of interest, i.e. new data that the client should take into consideration and potentially process? One option would be for the client to periodically poll the server for changes. Fair enough, that would work. But it'd be a bit of a waste if the changes aren't particularly frequent. Is it possible then to establish both a server and a client in the same application? I guess it must be possible but the examples all rely on some kind of server loop (i.e. SocketServer.serve_forever) that if started on both client and server sides would create two listening parties but no talking at all! Furthermore, other libraries might have their own loop, i.e. a graphical client has a loop to redraw the screen and the two loops would somehow have to be interleaved. I'm not quite seeing how this can be done other than we threads. Is that the way to do it? Place the listening loop in a thread while the rest of the application does its own thing? Or is it SocketServer.handle_request() the key? I could call this function periodically, but what happens if a request is made while the application is doing something else? Are the requests queued and dealt with one per loop? Thanks for your help! Manu From jspies at sun.ac.za Tue Dec 9 03:26:02 2008 From: jspies at sun.ac.za (Johann Spies) Date: Tue, 9 Dec 2008 10:26:02 +0200 Subject: Announcement: MindTree for Python beta -- feedback appreciated In-Reply-To: <20841316.post@talk.nabble.com> References: <20841316.post@talk.nabble.com> Message-ID: <20081209082602.GC25955@sun.ac.za> > The MindTree project can be found and downloaded here: > http://code.google.com/p/mindtree/ > I suppose it might be a python3-problem: % /usr/local/bin/python3.0 MindTree.pyw Traceback (most recent call last): File "MindTree.pyw", line 2, in from future_builtins import * ImportError: No module named future_builtins Regards Johann -- Johann Spies Telefoon: 021-808 4036 Informasietegnologie, Universiteit van Stellenbosch "Let not sin therefore reign in your mortal body, that ye should obey it in the lusts thereof." Romans 6:12 From xahlee at gmail.com Wed Dec 3 18:26:26 2008 From: xahlee at gmail.com (Xah Lee) Date: Wed, 3 Dec 2008 15:26:26 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> Message-ID: <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> > I'll pay $20 to see your improved version of the code. The only > references to PayPal I saw on your website were instructions to direct > the payment to x... at xahlee.org, please let me know if that is correct. > > What I want in return is you to execute and time Dr. Harrop's original > code, posting the results to this thread. Then, I would like you to > post your code with the timing results to this thread as well. > > By Dr. Harrop's original code, I specifically mean the code he posted > to this thread. I've pasted it below for clarity. Agreed. My paypal address is ?xah @@@ xahlee.org?. (replace the triple @ to single one.) Once you paid thru paypal, you can post receit here if you want to, or i'll surely acknowledge it here. Here's what i will do: I will give a version of Mathematica code that has the same behavior as his. And i will give timing result. The code will run in Mathematica version 4. (sorry, but that's what i have) As i understand, Jon is running Mathematica 6. However, i don't see anything that'd require Mathematica 6. If my code is not faster or in other ways not satisfactory (by your judgement), or it turns out Mathematica 6 is necessary, or any problem that might occure, i offer money back guarantee. Xah ? http://xahlee.org/ ? On Dec 3, 2:12 pm, "Thomas M. Hermann" wrote: > On Dec 3, 3:15 pm, Xah Lee wrote: > > > > > On Dec 3, 8:24 am, Jon Harrop wrote: > > > > My example demonstrates several of Mathematica's fundamental limitations. > > > enough babble Jon. > > > Come flying $5 to my paypal account, and i'll give you real code, > > amongest the programing tech geekers here for all to see. > > > I'll show, what kinda garbage you cooked up in your Mathematica code > > for ?comparison?. > > > You can actually just post your ?comparisons? to ?comp.soft- > > sys.math.mathematica?, and you'll be ridiculed to death for any > > reasonable judgement of claim on fairness. > > > > Consequently, there is great value in combining Mathematica with performant > > > high-level languages like OCaml and F#. This is what the vast majority of > > > Mathematica users do: they use it as a glorified graph plotter. > > > glorified your ass. > > > Yeah, NASA, Intel, NSA, ... all use Mathematica to glorify their > > pictures. LOL. > > > > What exactly do you believe is wrong with my code? > > > come flies $5 to my paypal, and i'll explain further. > > > > I am not trying to make Mathematica look bad. It is simply not suitable when > > > hierarchical solutions are preferable... > > > Certainly there are areas other langs are more suitable and better > > than Mathematica (for example: assembly langs). But not in the ways > > you painted it to peddle your F# and OCaml books. > > > You see Jon, you are this defensive, trollish guy, who takes every > > opportunity to slight other langs that's not one of your F#, OCml that > > you make a living of. In every opportunity, you injest your gribes > > about static typing and other things, and thru ensuring chaos paves > > the way for you to post urls to your website. > > > With your math and functional programing expertise and Doctor label, > > it can be quite intimidating to many geekers. But when you bump into > > me, i don't think you have a chance. > > > As a scientist, i think perhaps you should check your newsgroup > > demeanor a bit? I mean, you already have a reputation of being biased. > > Too much bias and peddling can be detrimental to your career, y'known? > > > to be sure, i still respect your expertise and in general think that a > > significant percentage of tech geeker's posts in debate with you are > > moronic, especially the Common Moron Lispers, and undoubtably the Java > > and imperative lang slaving morons who can't grope the simplest > > mathematical concepts. Throwing your Mathematica bad mouthing at me > > would be a mistake. > > > Come, fly $5 to my paypal account. Let the challenge begin. > > > Xah > > ?http://xahlee.org/ > > > ? > > Xah, > > I'll pay $20 to see your improved version of the code. The only > references to PayPal I saw on your website were instructions to direct > the payment to x... at xahlee.org, please let me know if that is correct. > > What I want in return is you to execute and time Dr. Harrop's original > code, posting the results to this thread. Then, I would like you to > post your code with the timing results to this thread as well. > > By Dr. Harrop's original code, I specifically mean the code he posted > to this thread. I've pasted it below for clarity. > > Jon Harrop coded a ray tracer in Mathematica: > > > delta = Sqrt[$MachineEpsilon]; > > > RaySphere[o_, d_, c_, r_] := > > Block[{v, b, disc, t1, t2}, > > v = c - o; > > b = v.d; > > disc = Sqrt[b^2 - v.v + r^2]; > > t2 = b + disc; > > If[Im[disc] != 0 || t2 <= 0, \[Infinity], > > t1 = b - disc; > > If[t1 > 0, t1, t2]] > > ] > > > Intersect[o_, d_][{lambda_, n_}, Sphere[c_, r_]] := > > Block[{lambda2 = RaySphere[o, d, c, r]}, > > If[lambda2 >= lambda, {lambda, n}, {lambda2, > > Normalize[o + lambda2 d - c]}] > > ] > > Intersect[o_, d_][{lambda_, n_}, Bound[c_, r_, s_]] := > > Block[{lambda2 = RaySphere[o, d, c, r]}, > > If[lambda2 >= lambda, {lambda, n}, > > Fold[Intersect[o, d], {lambda, n}, s]] > > ] > > > neglight = N at Normalize[{1, 3, -2}]; > > > nohit = {\[Infinity], {0, 0, 0}}; > > > RayTrace[o_, d_, scene_] := > > Block[{lambda, n, g, p}, > > {lambda, n} = Intersect[o, d][nohit, scene]; > > If[lambda == \[Infinity], 0, > > g = n.neglight; > > If[g <= 0, 0, > > {lambda, n} = > > Intersect[o + lambda d + delta n, neglight][nohit, scene]; > > If[lambda < \[Infinity], 0, g]]] > > ] > > > Create[level_, c_, r_] := > > Block[{obj = Sphere[c, r]}, > > If[level == 1, obj, > > Block[{a = 3*r/Sqrt[12], Aux}, > > Aux[x1_, z1_] := Create[level - 1, c + {x1, a, z1}, 0.5 r]; > > Bound[c, > > 3 r, {obj, Aux[-a, -a], Aux[a, -a], Aux[-a, a], Aux[a, a]}]]]] > > > scene = Create[1, {0, -1, 4}, 1]; > > > Main[level_, n_, ss_] := > > Block[{scene = Create[level, {0, -1, 4}, 1]}, > > Table[ > > Sum[ > > RayTrace[{0, 0, 0}, > > N at Normalize[{(x + s/ss/ss)/n - 1/2, (y + Mod[s, ss]/ss)/n - 1/2, > > 1}], scene], {s, 0, ss^2 - 1}]/ss^2, {y, 0, n - 1}, > > {x, 0, n - 1}]] > > > AbsoluteTiming[Export["image.pgm", Graphics at Raster@Main[9, 512, 4]]] From MrJean1 at gmail.com Sun Dec 21 15:43:47 2008 From: MrJean1 at gmail.com (MrJean1) Date: Sun, 21 Dec 2008 12:43:47 -0800 (PST) Subject: trapping all method calls in a class... References: <19ac19520812202312q71409182kb58a0f7aaf3b0e74@mail.gmail.com> Message-ID: <8674b360-1b56-41ee-b55c-6a1ec25b9684@z6g2000pre.googlegroups.com> The decorate_meths() function as given fails: TypeError: 'dictproxy' object does not support item assignment But this version avoids that error (on Python 2.2 thru 2.6): def decorate_meths(klass): for nam, val in klass.__dict__.items(): if callable(val): setattr(klass, nam, decorate(val)) return klass # ? /Jean Brouwers On Dec 20, 11:32?pm, "Chris Rebert" wrote: > On Sat, Dec 20, 2008 at 11:12 PM, Piyush Anonymous > > wrote: > > hi, > > i need to trap all method calls in a class in order to update a counter > > which is increased whenever a method is called and decreased whenever method > > returns. in order to that i am trying to write a decorator for all the > > methods. > > > see the code here with error. > > ------- > >http://codepad.org/2w7JVvDB > > ---- > > any suggestions? any other better way of doing it? > > I call unnecessary use of metaclasses! Here's my (untested) attempt at > a simpler class decorator approach: > > def decorate_meths(klass): > ? ? attrs = klass.__dict__.items() > ? ? ? ? for name, val in attrs: > ? ? ? ? ? ? ? ? if callable(val): > ? ? ? ? ? ? ? ? ? ? ? ? klass.__dict__[name] = decorate(val) > > def decorate(method): > ? ? #should be called for every method call in the class > ? ? def decorated(self, *args, **kwds): > ? ? ? ? print "2 Inside __call__()" > ? ? ? ? returnval = method(self, *args,**kwds) > ? ? ? ? print "3 After self.f(*args)" > ? ? ? ? return returnval > ? ? return decorated > > #@decorate_meths <-- this syntax requires a later Python version > class Person(object): > ? ? ? ? def testprint(self,val): > ? ? ? ? ? ? ? ? print "blah blah" > Person = decorate_meths(Person) > > #rest of code after the class definition would be the same > > Sidenotes about your code: > - `args` and `kwds` are the conventional names for the * and ** > special arguments > - the `methodname` variable was actually getting method objects, not > strings, as its values; this was probably part of the bug in your > program > > Cheers, > Chris > > -- > Follow the path of the Iguana...http://rebertia.com From wr4bbit at gmail.com Fri Dec 12 06:50:41 2008 From: wr4bbit at gmail.com (whiter4bbit) Date: Fri, 12 Dec 2008 03:50:41 -0800 (PST) Subject: Imaging library in jython Message-ID: <3178aaba-b1b1-48cd-a1bd-2bf457e41a09@p2g2000prf.googlegroups.com> Hi, Is there any ways to use python Imaging library in jython? From excord80 at gmail.com Sun Dec 14 23:15:27 2008 From: excord80 at gmail.com (excord80) Date: Sun, 14 Dec 2008 20:15:27 -0800 (PST) Subject: How do I manually uninstall setuptools (installed by egg)? References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> <375bd56a-d92b-4d33-bf70-5bea630a376a@q30g2000vbn.googlegroups.com> Message-ID: <4987e663-0fc8-4d5d-af16-8b4142fc5a23@f40g2000pri.googlegroups.com> On Dec 9, 10:48?pm, excor... at gmail.com wrote: > > Anyway, the direction I'm heading is to try and use setuptools *less*. > It seems like it might be too complicated for me. And, I notice that > the mailing list for it (distutils-sig, if that's the right one) is > loaded with questions on how to use it properly, so maybe I'm not > alone. Ah. This is interesting: http://www.b-list.org/weblog/2008/dec/14/packaging/ From xahlee at gmail.com Tue Dec 9 18:01:11 2008 From: xahlee at gmail.com (Xah Lee) Date: Tue, 9 Dec 2008 15:01:11 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> <0201522a-b15a-4401-a208-5d9af70bdd74@w24g2000prd.googlegroups.com> <8947211d-2ee8-403a-8c8a-c7599aea5f80@k24g2000pri.googlegroups.com> Message-ID: <9f86f78c-776e-4793-b931-67dadc0e24f1@i24g2000prf.googlegroups.com> On Dec 8, 4:56 pm, Jon Harrop wrote: > Xah Lee wrote: > > A moron, wrote: > > > You failed the challenge that you were given. > > > you didn't give me a challenge. > > Thomas gave you the challenge: > > "What I want in return is you to execute and time Dr. Harrop's original > code, posting the results to this thread... By Dr. Harrop's original code, > I specifically mean the code he posted to this thread. I've pasted it below > for clarity.". > > Thomas even quoted my code verbatim to make his requirements totally > unambiguous. Note the parameters [9, 512, 4] in the last line that he and I > both gave: > > AbsoluteTiming[Export["image.pgm", Graphics at Raster@Main[9, 512, 4]]] > > You have not posted timings of that, let alone optimized it. So you failed. The first parameter to your Main specifies some kinda recursively stacked spheres in the rendered image. The second parameter is the width and height of the pixels in the rendered image. I tried to run them but my computer went 100% cpu and after i recall 5 min its still going. So, i reduced your input. In the end, with reduced input, it shows my code is 5 times faster (running Mathematica v4 on OS X 10.4.x with PPC 1.9 GHz), and on the other guy's computer with Mathematica 6 he says it's twice as fast. Given your code's nature, it is reasonably to assume that with your original input my code would still be faster than yours. You claim it is not or that it is perhaps just slightly faster? It is possible you are right. I don't want to spend the energy to run your code and my code and possible hog my computer for hours or perhaps days. As i said, your recursive Intersect is very badly written Mathematica code. It might even start memory swapping. Also, all you did is talking bullshit. Thomas actually is the one took my challenge to you and gave me $20 to prove my argument to YOU. His requirement, after the payment, is actually, i quote: ?Alright, I've sent $20. The only reason I would request a refund is if you don't do anything. As long as you improve the code as you've described and post the results, I'll be satisfied. If the improvements you've described don't result in better performance, that's OK.? He haven't posted since nor emailed me. It is reasonable to assume he is satisfied as far as his payment to me to see my code goes. You, kept on babbling. Now you say that the input is different. Fine. How long does that input actually take on your computer? If days, i'm sorry i cannot run your toy code on my computer for days. If in few hours, i can then run the code overnight, and if necessary, give you another version that will be faster with your given input to shut you the fuck up. However, there's cost to me. What do i get to do your homework? It is possible, that if i spend the energy and time to do this, then you again refuse to acknowledge it, or kept on complaining about something else. You see, newsgroup is the bedrock of bullshit. You bullshit, he bullshits, everybody brags and bullshit because there is no stake. I want sincerity and responsibility backed up, with for example paypal deposits. You kept on bullshitting, Thomas gave me $20 and i produced a code that reasonably demonstrated at least how unprofessional your Mathematica code was. Here's the deal. Pay me $20, then i'll creat a version of Mathematica code that has the same input as yours. Your input is Main[9, 512, 4], as i have exposed, your use of interger in the last part for numerical computation is Mathematica incompetence. You didn't acknowledge even this. I'll give a version of Mathematica with input Main[9, 512, 4.] that will run faster than yours. If not, money back guaranteed. Also, pay me $300, then i can produce a Mathematica version no more than 10 times slower than your OCaml code, this should be a 70000 times improvement according to you. Again, money back guarantee. If i don't receive $20 or $300, this will be my last post to you in this thread. You are just a bullshitter. O wait... my code with Main[9, 512, 4.] and other numerical changes already makes your program run faster regardless of the input size. What a motherfucking bullshit you are. Scratch the $20. The $300 challenge still stands firm. Xah ? http://xahlee.org/ ? From anonymous.c.lisper at gmail.com Mon Dec 1 17:48:21 2008 From: anonymous.c.lisper at gmail.com (anonymous.c.lisper at gmail.com) Date: Mon, 1 Dec 2008 14:48:21 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: <3d81f880-6a90-4a11-8dd4-408741e5baed@j38g2000yqa.googlegroups.com> On Dec 1, 2:23?am, Xah Lee wrote: > On Nov 30, 7:30 pm, Xah Lee wrote: > >>some stuff Are you a bot? I think you failed the Turing test after the 8th time you posted the exact same thing... I'm completely serious. From steve at holdenweb.com Tue Dec 30 08:59:51 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Dec 2008 08:59:51 -0500 Subject: Python list's mail server in DNSBL ? In-Reply-To: <495A2825.4070000@shopzeus.com> References: <495A2825.4070000@shopzeus.com> Message-ID: <495A2957.6090805@holdenweb.com> Laszlo: Read the message again. There's nothing the list admins can do about this, you'll have to contact Postmaster at chello.at to have them remove the blacklisting, since it's their server that's imposing it. regards Steve Laszlo Nagy wrote: > I got this message when I tried to send something to this list, through > my ISP's SMTP server: > > > > This Message was undeliverable due to the following reason: > > Each of the following recipients was rejected by a remote mail server. > The reasons given by the server are included to help you determine why > each recipient was rejected. > > Recipient: > Reason: 5.7.1 : Recipient address > rejected: policyd-weight Mail appears to be spam or forged. Ask your > Mail-/DNS-Administrator to correct HELO and DNS MX settings and to get > removed from DNSBLs; in bogusmx.rfc-ignorant.org > > > Please reply to > if you feel this message to be in error. > > > > Reporting-MTA: dns; viefep19.chello.at > Arrival-Date: Tue, 30 Dec 2008 14:12:36 +0100 > Received-From-MTA: dns; edge04.upc.biz (192.168.13.239) > > Final-Recipient: RFC822; > Action: failed > Status: 5.1.1 > Remote-MTA: dns; mail.python.org (194.109.207.14) > Diagnostic-Code: smtp; 550 5.7.1 : Recipient > address rejected: policyd-weight Mail appears to be spam or forged. Ask > your Mail-/DNS-Administrator to correct HELO and DNS MX settings and to > get removed from DNSBLs; in bogusmx.rfc-ignorant.org > > > > Is python.org really blacklisted? Any admin please, try to remove it. > > Thanks > > Laszlo > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From bdesth.quelquechose at free.quelquepart.fr Wed Dec 17 16:19:43 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 17 Dec 2008 22:19:43 +0100 Subject: Why no lexical scoping for a method within a class? In-Reply-To: <6a76b501-f6dc-41b5-8828-b55fece68651@l33g2000pri.googlegroups.com> References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> <6a76b501-f6dc-41b5-8828-b55fece68651@l33g2000pri.googlegroups.com> Message-ID: <49497aa4$0$9084$426a74cc@news.free.fr> walterbyrd a ?crit : > On Dec 17, 9:04 am, rdmur... at bitdance.com wrote: > >> Yes. It's called Object Oriented Programming. > > I think you mean it's *Python* Object Oriented Programming. I am not > sure that every other OO language works like that. Every OO languages having such a thing as a global variable makes a distinction between an instance attributes and a global variable. Your problem is that you are confusing variables and attributes. In Python, 'anything.anyname' (note the dot) is the attribute 'anyname' of object 'anything'. From greg at cosc.canterbury.ac.nz Wed Dec 10 05:47:05 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 10 Dec 2008 23:47:05 +1300 Subject: Announcement: MindTree for Python beta -- feedback appreciated In-Reply-To: References: <20841316.post@talk.nabble.com> Message-ID: <6q9ksbFbef4kU1@mid.individual.net> Johann Spies wrote: > % /usr/local/bin/python3.0 MindTree.pyw > Traceback (most recent call last): > File "MindTree.pyw", line 2, in > from future_builtins import * > ImportError: No module named future_builtins Hmmm... does this mean that Python3 has no future? :-) -- Greg From pierre.quentel at gmail.com Mon Dec 29 14:18:06 2008 From: pierre.quentel at gmail.com (Pierre Quentel) Date: Mon, 29 Dec 2008 11:18:06 -0800 (PST) Subject: SQL, lite lite lite References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> Message-ID: <5147d0d3-d58c-44c6-b2c2-ab8ce6229a2c@p2g2000prf.googlegroups.com> On 29 d?c, 19:06, Aaron Brady wrote: > Hi all, > > About a year ago, I posted an idea I was having about thread > synchronization to the newsgroup. ?However, I did not explain it well, > and I really erred on the side of brevity. ?(After some finagling, Mr. > Bieber and I decided it wasn't exactly anything groundbreaking.) ?But > I think the brevity cost me some readers, who might have had more > interest. ?The affair was on the whole discouraging. ?So, I'm going to > try another idea, and assume that readers have some time, and will > spend it on it. > > I don't think relational data can be read and written very easily in > Python. ?There are some options, such as 'sqllite3', but they are not > easy. ?'sqllite3' statements are valid SQL expressions, which afford > the entire power of SQL, but contrary to its name, it is not that > 'lite'. ?To me, 'lite' is something you could learn (even make!) in an > afternoon, not a semester; something the size of an ActiveState > recipe, or a little bigger, maybe a file or two. ?If you think SQL is > a breeze, you probably won't find my idea exciting. ?I assume that the > basics of SQL are creating tables, selecting records, and updating > records. > > My idea is to create a 'Relation' class. ?The details are basically > open, such as whether to back it with 'sqllite3', 'shelve', 'mmap', or > just mapping and sequence objects; what the simplest syntax is that > can capture and permit all the basics, and how much and what else can > fit in at that level; how and whether it can include arbitrary Python > objects, and what constraints there are on them if not; how and > whether to permit transactions; and what the simplest and coolest > thing you can do with a little Python syntax is. > > This is basically an invitation for everyone to brainstorm. ?(No > hijackings, good humor & digression ok.) ?Lastly, ... > > **warning, spoiler! ?here's what I thought of already.** > > **repeat! ?spoiler! ?here's what I thought of already.** > > #Just the select and update syntax: > > >>> a= people._select( "firstname== 'Joe'" ) > > #select 'key' from 'people' where 'firstname'== 'joe'>>> a > > [Entry2864, Entry3076, Entry3172]>>> entry1= a[ 0 ] > >>> entry1.phone > > #select 'phone' from 'people' where 'key'==self.key > "555-2413">>> entry1.phone= "555-1234" > > #update 'people' set 'phone'= '555-1234' where 'key'==self.key>>> entry1.phone > > "555-1234" > > #Create table syntax (a-whole-nother beast in itself): > > >>> classes= db.Relation( 'class_', 'person', Unique( 'class_', 'person' ) ) > > #create table 'classes' ( 'key', 'class_', 'person' ) unique > ( 'class_', 'person' ) > > >>> classes._unique( 'class_', 'person' ) > >>> classes.class_.noneok= False #'class_' cannot be null > >>> classes.person.noneok= False > >>> classes._insert( 'Physics', 'Dan' ) > >>> classes._insert( 'Chem', 'Tim' ) > > Hoping-"good critic"-is-self-consistent-ly, hoping-to-hear-it's-too- > complicated-already-ly, > A. Brady Hi, PyDbLite (http://pydblite.sourceforge.net/) is not far from what you describe. The basic version stores data in cPickle format, and there are interfaces to use the same Pythonic syntax with SQLite and MySQL backends Regards, Pierre From clp at rebertia.com Sun Dec 7 04:34:22 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 7 Dec 2008 01:34:22 -0800 Subject: how to get a beep, OS independent ? In-Reply-To: <493B9701.2040402@gmail.com> References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> Message-ID: <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> On Sun, Dec 7, 2008 at 1:27 AM, Stef Mientki wrote: > Rainy wrote: >> >> On Dec 6, 3:40 pm, Stef Mientki wrote: >> >>> >>> hello, >>> >>> I want to give a small beep, >>> for windows there's message-beep, >>> and there seems to be something like " curses" , >>> but that package seems to be totally broken in P2.5 for windows. >>> >>> Any other suggestions ? >>> >>> thanks, >>> Stef Mientki >>> >> >> For win there's winsound, you have to check sys.platform and do >> what's necessary for the platform in question. In linux I think >> you can just print '\a' (or does that only work in terminals?). >> If you know that ext. speakers are always on, you can do a nicer >> beep by using some wav file, in linux it's probably easiest to >> use an external program to play it, like wavplay. Basically, >> there is no single answer, it depends on circumstances. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > '\a' or chr(7) prints an inverted "BEL". Inverted bell? What do you mean? And what version dependency are you referring to? Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > So it looks that Python version independency is even worse than OS > independency ;-) > I'll take a look at wxPython and Pygame if there's something useful. > > anyway thanks, > Stef > -- > http://mail.python.org/mailman/listinfo/python-list > From ppearson at nowhere.invalid Wed Dec 10 11:13:42 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 10 Dec 2008 16:13:42 GMT Subject: [OT] Google Groups in bad odour References: <4d5498bf-bbf0-4760-83fc-610729bcbce2@h20g2000yqn.googlegroups.com> Message-ID: <6qa85mFbj3klU1@mid.individual.net> On Wed, 10 Dec 2008 02:20:24 -0800 (PST), Frank Millman wrote: > . . . I will therefore have to find a suitable news client. Any > recommendations? I'm a happy user of slrn. -- To email me, substitute nowhere->spamcop, invalid->net. From mgreene at bdurham.com Wed Dec 24 03:04:57 2008 From: mgreene at bdurham.com (Malcolm Greene) Date: Wed, 24 Dec 2008 03:04:57 -0500 Subject: Strategy for determing difference between 2 very large dictionaries In-Reply-To: <1230105750.9108.1291619105@webmail.messagingengine.com> References: <1230102996.2303.1291616055@webmail.messagingengine.com> <1230105750.9108.1291619105@webmail.messagingengine.com> Message-ID: <1230105897.9336.1291620453@webmail.messagingengine.com> Hi Roger, By very large dictionary, I mean about 25M items per dictionary. Each item is a simple integer whose value will never exceed 2^15. I populate these dictionaries by parsing very large ASCII text files containing detailed manufacturing events. From each line in my log file I construct one or more keys and increment the numeric values associated with these keys using timing info also extracted from each line. Some of our log files are generated by separate monitoring equipment measuring the same process. In theory, these log files should be identical, but of course they are not. I'm looking for a way to determine the differences between the 2 dictionaries I will create from so-called matching sets of log files. At this point in time, I don't have concerns about memory as I'm running my scripts on a dedicated 64-bit server with 32Gb of RAM (but with budget approval to raise our total RAM to 64Gb if necessary). My main concern is am I applying a reasonably pythonic approach to my problem, eg. am I using appropriate python techniques and data structures? I am also interested in using reasonable techniques that will provide me with the fastest execution time. Thank you for sharing your thoughts with me. Regards, Malcolm ----- Original message ----- From: "Roger Binns" To: python-list at python.org Date: Tue, 23 Dec 2008 23:26:49 -0800 Subject: Re: Strategy for determing difference between 2 very large dictionaries -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 python at bdurham.com wrote: > Feedback on my proposed strategies (or better strategies) would be > greatly appreciated. Both strategies will work but I'd recommend the second approach since it uses already tested code written by other people - the chances of it being wrong are far lower than new code. You also neglected to mention what your concerns are or even what "very large" is. Example concerns are memory consumption, cpu consumption, testability, utility of output (eg as a generator getting each result on demand or a single list with complete results). Some people will think a few hundred entries is large. My idea of large is a working set larger than my workstation's 6GB of memory :-) In general the Pythonic approach is: 1 - Get the correct result 2 - Simple code (developer time is precious) 3 - Optimise for your data and environment Step 3 is usually not needed. Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAklR5DUACgkQmOOfHg372QSuWACgp0xrdpW+NSB6qqCM3oBY2e/I LIEAn080VgNvmEYj47Mm7BtV69J1GwXN =MKLl -----END PGP SIGNATURE----- -- http://mail.python.org/mailman/listinfo/python-list From walterbyrd at iname.com Fri Dec 5 15:52:59 2008 From: walterbyrd at iname.com (walterbyrd) Date: Fri, 5 Dec 2008 12:52:59 -0800 (PST) Subject: Can I load a python program at the interactive >>> prompt? Message-ID: <269e5d69-02b7-409b-ad53-b7702b6ec13a@i24g2000prf.googlegroups.com> I am running cygwin on xp. Much to my annoyance, I can not cut-and-paste from a windows app to the python prompt. I think I could do this with putty, but I do not have the permissions to install putty on my xp box. Can I load a file into the python interactive environment? For example I have a file called test.py that consists of the following: print "hello" print "hello again" Can I load that file into python at the >>> prompt? >>> load "test.py" or something like that? From jerry.carl.mi at gmail.com Sat Dec 27 19:02:51 2008 From: jerry.carl.mi at gmail.com (jerry.carl.mi at gmail.com) Date: Sat, 27 Dec 2008 16:02:51 -0800 (PST) Subject: math module for Decimals Message-ID: Hi, I have been looking for a Python module with math functions that would both eat and spit Decimals. The standard math module eats Decimals allright but spits floats... herefore exp(sin(Decimal())) produces exp () of a float :-( So far, i found: -AJDecimalMathAdditions (http://www.ajgs.com/programming/ PythonForDownload.html) -decimalfuncs (http://pypi.python.org/pypi/decimalfuncs/1.4) -and dmath (http://pypi.python.org/pypi/dmath/0.9) I tried using the AJDecimalMathAdditions, but ran into issues like dSin (1E4) would take forever to calculate and would result in sin() > 1 ... If i understand it correctly, the program is using maclaurin series to calculate the value and since it does not chop off all the multiples of 2*pi, the maclaurin approximation becomes useless when its too far from x=0. I also ran into some issues with the decimalfuncs, but i have never tried the dmath thing. Now, i can go and start modifying these modules to behave more like the standard math module but since i am neither mathematician or programer, i really hesitate. So my questions are: (1) what do folks use when they need to calculate something like exp (sin(Decimal())) or even more complex things? Any recommendations? Or am I completely missing something? (2) Is there any plan to provide a standard python module that would do that? (Python 4.0? ;-) Thanks for your comments and help, Jerry From pavlovevidence at gmail.com Tue Dec 2 17:43:47 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 2 Dec 2008 14:43:47 -0800 (PST) Subject: optimization References: Message-ID: <6754f396-d462-48de-b98f-bd92d7e4d095@x38g2000yqj.googlegroups.com> On Dec 2, 1:56?pm, Neal Becker wrote: > Robert Kern wrote: > > Neal Becker wrote: > >> Arnaud Delobelle wrote: > > >>> Neal Becker writes: > > >>>> I noticed in some profiling, that it seems that: > > >>>> def Func (): > >>>> ? def something(): > >>>> ? ? ... > > >>>> It appears that if Func is called many times, this nested func > >>>> definition will cause significant overhead. ?Is this true? ?I guess > >>>> I've become accustomed to decent compilers performing reasonable > >>>> transformations and so have tended to write code for clarity. > >>> If something() can be defined outside Func(), how is it clearer to > >>> define it inside? > > >> If it's only used inside. > > > I, for one, find that significantly less clear. I only expect functions to > > be defined inside of functions if they are going to use lexical scoping > > for some reason. If I read your code, I'd probably waste a good five > > minutes trying to figure out what part of the local scope you were using > > before I would conclude that you just did it because you thought it looked > > better. > > I'm using the inner function to prevent pollution of the global > namespace. ?Local variables also have this attribute. ?Code is > easier to understand when it is written with the greatest locality > - so you can see immediately that the inner function isn't used > somewhere else. Let me throw this out: The rule-of-thumb should not be whether something is used anywhere else, but rather if it is modified locally or depends on something that exists locally. Use outer scope when possible, inner scope only when necessary. Flat is better than nested. In this case, local variables are different from locally-defined functions, because local variables are typically rebound over the course of the function, or are constant but depend on the function's arguments. (Variables that aren't rebound within the function, or don't depend on the arguments, are considered constants and are typically defined in all caps at the module level.) Locally-defined functions, however, are constant, and unless they use values from the enclosing scope, they do not depend on the local environment. Therefore, by this criterion, the locally-defined function ought to be defined at the module level, just like constants are. I don't buy that nesting functions prevents namespace pollution. IMHO, namespace pollution occurs when you do things like "from module import *"; there is no pollution when you control the whole namespace yourself. Having said that, I do use local functions without closures here and there, when it's something either too silly or too specific to introduce a module-level function for. Judgment call, mostly, but typically I go to the module level. Carl Banks From tjreedy at udel.edu Mon Dec 1 20:42:39 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Dec 2008 20:42:39 -0500 Subject: end of print = lower productivity ? In-Reply-To: <98407948-e24f-4a89-8604-148279620f84@k24g2000pri.googlegroups.com> References: <98407948-e24f-4a89-8604-148279620f84@k24g2000pri.googlegroups.com> Message-ID: alex23 wrote: > On Dec 2, 5:12 am, Alan G Isaac wrote: >> One obvious cost is that working at the >> interpreter prompt is now slightly less >> convenient. > > Not if you use IPython: > > IPython 0.8.1 -- An enhanced Interactive Python. > ? -> Introduction to IPython's features. > %magic -> Information about IPython's 'magic' % functions. > help -> Python's own help system. > object? -> Details about 'object'. ?object also works, ?? prints more. > > In [1]: def prnt(x): print x > ...: > > In [2]: prnt "test" > ------> prnt("test") > test > > In [3]: prnt 1+1 > ------> prnt(1+1) > 2 And not in either Python or IDLE: >>> 'test' 'test' >>> 1+1 2 From floris.bruynooghe at gmail.com Wed Dec 24 17:33:25 2008 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Wed, 24 Dec 2008 14:33:25 -0800 (PST) Subject: Using exceptions in defined in an extension module inside another extension module References: <26443e22-0dd6-4fa9-a58e-8d9314001c6c@o4g2000pra.googlegroups.com> Message-ID: <3532637e-c748-4d0e-aa24-42f64be4e9e9@i20g2000prf.googlegroups.com> Christian Heimes wrote: > Floris Bruynooghe schrieb: > > What I can't work out however is how to then be able to raise this > > exception in another extension module. Just defining it as "extern" > > doesn't work, even if I make sure the first module -that creates the > > exception- gets loaded first. Because the symbol is defined in the > > first extension module the dynamic linker can't find it as it only > > seems to look in the main python executable for symbols used in > > dlloaded sofiles. > > > > Does anyone have an idea of how you can do this? > > The answer is so obvious that you are going to bang your head against > the next wall. You have to do exactly the same as you'd do with a pure > Python module: import it. :) Well, I hope the wall hurts as much as my head... Great tip, at first I wasn't looking forward to importing the module in every function where I wanted the exceptions. But then I realised they are global variables anyway so I could have them as such again and just assign them in the module init function. Thanks Floris From renton at 1gb.ru Tue Dec 2 01:55:33 2008 From: renton at 1gb.ru (Alexey Vlasov) Date: Tue, 2 Dec 2008 09:55:33 +0300 Subject: Import of egg packages installed with easy_install In-Reply-To: <6piqvpF839bkU2@mid.uni-berlin.de> References: <6piqvpF839bkU2@mid.uni-berlin.de> Message-ID: <20081202065533.GB9873@l2.in-solve.ru> Hi Diez. On Mon, Dec 01, 2008 at 08:09:29PM +0100, Diez B. Roggisch wrote: > It's not sufficient to add simply your local site-packages, you must install > it using the module site's addsitedir-function, like this: > > import site > site.addsitedir("/home/username/python/lib/python2.5/site-packages") Thanks for help. -- BRGDS. Alexey Vlasov. From pavlovevidence at gmail.com Thu Dec 4 15:19:44 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 4 Dec 2008 12:19:44 -0800 (PST) Subject: "as" keyword woes References: Message-ID: On Dec 3, 11:42?pm, "Warren DeLano" wrote: > Except that Python syntax has proven itself to be a non-backwards > compatible moving target. ?Eliminating cruft and adding new > functionality is one thing, but introducing a whole new two-letter > keyword so long after the game has begun? ?That seems well over the line > of what can be considered reasonable. "as" has been in the language as a hybrid keyword/identifier since Python 2.0, released in 2000, and it was always the plan to eventually make it a full keyword. (I'm not sure when they decided to finish the job in 2.6.) They could have just made it a keyword right then and broke backwards compatibility instantly, instead they gave developers an eight year transition period. I think that is reasonable enough. You know, with Python being the kind of language that does have frequent releases which do carefully break backwards compatibility, if you are using it and expecting your code to work with future versions, it's your respsonsibility to keep up with planned language changes. You didn't. You were the one who dropped the ball here, not the Python developers. So stop complaining. If you don't want to take a few minutes a year to visit Python.org to see what changes are planned for upcoming releases, then feel free to use a language like Java that has the corporate backing to keep bad decisions around for decades. Carl Banks From pavlovevidence at gmail.com Fri Dec 19 00:20:31 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 18 Dec 2008 21:20:31 -0800 (PST) Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> <6qv7kfFeuf65U1@mid.uni-berlin.de> <6qv9v4Ff1lv9U1@mid.uni-berlin.de> Message-ID: <494a8d63-7936-4071-9461-4bfffa02e867@z6g2000pre.googlegroups.com> On Dec 18, 9:53?am, "Diez B. Roggisch" wrote: > Neal Becker wrote: > > Diez B. Roggisch wrote: > > >> Neal Becker wrote: > > >>> Tino Wildenhain wrote: > > >>>> Neal Becker wrote: > >>>> ... > >>>>>>> So if __str__ is "meant for human eyes", then why isn't print using > >>>>>>> it! > >>>>>> it is: > > >>>>>> ?> print x > >>>>>> str > > >>>>>> but dict just uses repr() for all its childs to print. > > >>>>>> T. > >>>>> That makes no sense to me. ?If I call 'print' on a container, why > >>>>> wouldn't it recursively ?print on the contained objects? ?Since print > >>>>> means call str, printing a container should recursively call str on > >>>>> the objects. > > >>>> Every class is free on how to best implement __str__, you will find > >>>> the same behavior on tuple and list as well. > > >>>> Maybe its discussable to change the implementation sensibly, best if > >>>> you would come with a proposal? Perhaps pprint.pprint is a starting > >>>> point? > > >>>> Regards > >>>> Tino > > >>> First, I'd like to know if there is a rationale for the current design. > >>> Am I correct in thinking this is a defect? > > >> I don't think so. First of all, there is no "generic" way of printing a > >> collection. And the current implementation tries to give an overview what > >> is contained in the collection, without trying to make it "fancy" - any > >> such thing needed to be hand-coded anyway. > > >> Using repr for that is better suited, as for example string keys are > >> printed with quotes around them - making clear what they are, and not > >> irritating the user through potentially contained spaces or even things > >> that look as if they are python objects. > > >> For example, if repr *wasn't* used, > > >> { "{foo=bar}" : "baz"} > > >> would be printed > > >> {{foo=bar} : baz} > > >> Which is *not* what the dictionary actually contains! > > >> The same goes for unicode-objects. They appear with their "funny" > >> characters as \xXX-codes - instead of bailing out on you with > >> unicode-errors. > > >> So, IMHO the current behavior is desired. > > > So if I want to overload something in my custom class, so that I get a > > nice string whether it's printed directly, or as part of a container, what > > is the recommendation? ?Overload both __str__ and __repr__? > > Yep. I would say no. __repr__ should be specific--something that when evaled yields an equal object, if possible--about what the object is. Overloading __repr__ to return an unspecific human-readable message is a mistake, and will frustrate users who are debugging, logging, inspecting objects at the interactive prompt. Neal's problem seems to be with the behavior of dict's __str__ method, which prints repr() of objects when he wants str(). That is intended behavior, like it or not, so I would say the appropriate thing is not use dict's default printed representation, and just write a custom formating function for dicts. Carl Banks From arnodel at googlemail.com Mon Dec 22 17:36:15 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 22 Dec 2008 22:36:15 +0000 Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano writes: > Instead of just whinging, how about making a suggestion to fix it? Go on, > sit down for an hour or ten and try to work out how a BINARY OPERATOR > like % (that means it can only take TWO arguments) can deal with an > arbitrary number of arguments, *without* having any special cases. > > Go on. Take your time. I'll be waiting. Well that's easy. I see 'r' didn't answer so I will: only accept tuples on the right hand side of the %, so all arguments have to be put inside a tuple. >>> "%s" % 42 Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for %: 'str' and 'int' >>> "%s" % (42,) '42' Of course there would still be the possibility of uncaught bugs when people forget to put the argument in a tuple if the argument itself is a tuple of length 1. >>> def foo(x): ... print "foo(%s)" % x ... # should be % (x,) ... >>> foo('a') TypeError: unsupported operand type(s) for %: 'str' and 'str' >>> # But if x is a tuple of length 1 the error is not reported >>> foo((1,)) foo(1) That's why .format() is a better option IMHO. -- Arnaud From kyosohma at gmail.com Mon Dec 1 17:19:32 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 1 Dec 2008 14:19:32 -0800 (PST) Subject: Why doesn't doc has predifined name and location ? References: <493455AD.4040306@gmail.com> Message-ID: <562d585b-97d2-41d6-9df6-695782a99238@41g2000yqf.googlegroups.com> > Sidenote: what Python projects publish their docs in CHM besides > possibly Win32 GUI programs? Doing a quick search in my Python25 directory and all it's sub- folders, all I found was Python25.chm and PyWin32.chm. However, I know wxPython also has a help file in chm format, but it puts it in another directory by default... > > Cheers, > Chris > -- Mike From gauravkec2005 at gmail.com Thu Dec 4 05:30:55 2008 From: gauravkec2005 at gmail.com (gaurav kashyap) Date: Thu, 4 Dec 2008 02:30:55 -0800 (PST) Subject: receive data through a python program from javascript Message-ID: <49c9e72f-5032-437d-ac70-8aea009e9278@i24g2000prf.googlegroups.com> Hi all, I have a javascript.I want to send some data from this javascript to a python program that is on zope on my local system... What can be the python program From fetchinson at googlemail.com Wed Dec 3 22:58:47 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 3 Dec 2008 19:58:47 -0800 Subject: RELEASED Python 3.0 final In-Reply-To: <47c890dc0812031952r6d2adbfav20fde92431443751@mail.gmail.com> References: <47c890dc0812031952r6d2adbfav20fde92431443751@mail.gmail.com> Message-ID: >>> On behalf of the Python development team and the Python community, I >>> am happy to announce the release of Python 3.0 final. >>> >>> Python 3.0 (a.k.a. "Python 3000" or "Py3k") represents a major >>> milestone in Python's history, and was nearly three years in the >>> making. This is a new version of the language that is incompatible >>> with the 2.x line of releases, while remaining true to BDFL Guido van >>> Rossum's vision. Some things you will notice include: >>> >>> * Fixes to many old language warts >>> * Removal of long deprecated features and redundant syntax >>> * Improvements in, and a reorganization of, the standard library >>> * Changes to the details of how built-in objects like strings and >>> dicts work >>> * ...and many more new features >>> >>> While these changes were made without concern for backward >>> compatibility, Python 3.0 still remains very much "Pythonic". >>> >>> We are confident that Python 3.0 is of the same high quality as our >>> previous releases, such as the recently announced Python 2.6. We will >>> continue to support and develop both Python 3 and Python 2 for the >>> foreseeable future, and you can safely choose either version (or both) >>> to use in your projects. Which you choose depends on your own needs >>> and the availability of third-party packages that you depend on. Some >>> other things to consider: >>> >>> * Python 3 has a single Unicode string type; there are no more 8-bit >>> strings >>> * The C API has changed considerably in Python 3.0 and third-party >>> extension modules you rely on may not yet be ported >>> * Tools are available in both Python 2.6 and 3.0 to help you migrate >>> your code >>> * Python 2.6 is backward compatible with earlier Python 2.x releases >>> >>> We encourage you to participate in Python 3.0's development process by >>> joining its mailing list: >>> >>> http://mail.python.org/mailman/listinfo/python-3000 >>> >>> If you find things in Python 3.0 that are broken or incorrect, please >>> submit bug reports at: >>> >>> http://bugs.python.org/ >>> >>> For more information, links to documentation, and downloadable >>> distributions, see the Python 3.0 website: >>> >>> http://www.python.org/download/releases/3.0/ >>> >>> Enjoy, >>> - -Barry >>> >>> Barry Warsaw >>> barry at python.org >>> Python 2.6/3.0 Release Manager >>> (on behalf of the entire python-dev team) >> >> uname -a >> >> Linux fetch 2.6.23.1-42.fc8 #1 SMP Tue Oct 30 13:18:33 EDT 2007 x86_64 >> x86_64 x86_64 GNU/Linux >> >> tar xzvf Python-3.0.tgz >> cd Python-3.0 >> ./configure >> make >> >> Failed to find the necessary bits to build these modules: >> _tkinter > > Do you have Tcl/Tk and their dev libs installed? Tkinter is based on Tcl/Tk. > Also, that error isn't fatal, it just means that Tkinter won't be > installed because it can't find the libs. > > Cheers, > Chris > -- > Follow the path of the Iguana... > http://rebertia.com > >> To find the necessary bits, look in setup.py in detect_modules() for >> the module's name. >> >> >> Cheers, >> Daniel I thought I didn't have to download tcl/tk stuff separately. At least I never did that for python 2.x but maybe somewhere they are installed on my box anyway. But why I have this issue with 3.0 I don't quite get, of course you are right, it's not fatal. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From mdgeorge at cs.cornell.edu Wed Dec 3 17:04:21 2008 From: mdgeorge at cs.cornell.edu (Michael George) Date: Wed, 3 Dec 2008 17:04:21 -0500 Subject: building an extension module with autotools? In-Reply-To: <4936FD1C.1010700@ghaering.de> References: <4936FD1C.1010700@ghaering.de> Message-ID: <49370265.2090904@cs.cornell.edu> Gerhard H?ring wrote: > Michael George wrote: >> I've tried using automake, > > In my opinion, this is serious overkill. automake is good for making > stuff work on a herd of different Unixen with various combinations of > libc functions available etc. But for developing a Python extension, > it doesn't help much at all. All you need to know about Python is > available via macros if you import Python.h. > I'll definitely consider going the simpler route, although the other thing that autotools provides is a standard interface for end-users. For example I'm picky and don't let anything into /usr that isn't under the purview of the package manager. autotools makes life easy because I can just do ./configure --prefix=/opt/pkgname and I know I'm good. Custom build setups force me to figure them out before I can install (and sometimes even use) the program. Since I'll be eventually trying to attract users, I'd like to avoid scaring them away with custom build scripts :) > HTH > > -- Gerhard Thanks for the advice. --Mike From rhf22 at mole.bio.cam.ac.uk Tue Dec 9 14:18:27 2008 From: rhf22 at mole.bio.cam.ac.uk (Rasmus Fogh) Date: Tue, 9 Dec 2008 19:18:27 +0000 (GMT) Subject: Rich Comparisons Gotcha Message-ID: Mark Dickinson wrote: > On Dec 8, 2:24 pm, Rasmus Fogh wrote: >> So, I would much prefer a language change. I am not competent to even >> propose one properly, but I'll try. > I don't see any technical problems in what you propose: as > far as I can see it's entirely feasible. However: >> should. On the minus side there would be the difference between >> '__equal__' and '__eq__' to confuse people. > I think this is exactly what makes the idea a non-starter. There > are already enough questions on the lists about when to use 'is' > and when to use '==', without adding an 'equals' function into > the mix. It would add significant extra complexity to the core > language, for questionable (IMO) gain. So: It is perfectly acceptable behaviour to have __eq__ return a value that cannot be cast to a boolean, but it still does break the python list. The fixes proposed so far all get the thumbs down, for various good reasons. How about: - Define a new built-in Exception BoolNotDefinedError(ValueError) - Have list.__contains__ (etc.) use the following comparison internally: def newCollectionTest(x,y): if x is y: return True else: try: return bool(x == y) except BoolNotDefinedError: return False - Recommend that numpy.array.__nonzero__ and similar cases raise BoolNotDefinedError instead of ValueError Objects that choose to raise BoolNotDefinedError will now work in lists, with identity semantics. Objects that do not raise BoolNotDefinedError have no change in behaviour. Remains to be seen how hard it is to implement, and how much it slows down list.__contains__ Rasmus --------------------------------------------------------------------------- Dr. Rasmus H. Fogh Email: r.h.fogh at bioc.cam.ac.uk Dept. of Biochemistry, University of Cambridge, 80 Tennis Court Road, Cambridge CB2 1GA, UK. FAX (01223)766002 From michele.simionato at gmail.com Wed Dec 3 00:23:37 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 2 Dec 2008 21:23:37 -0800 (PST) Subject: porting modules to Python 3.0 Message-ID: <8f60c779-f1ec-4127-b173-f174c016aa96@a12g2000yqm.googlegroups.com> Python 3.0 is going to be released Real Soon now and I realized that there big holes in my understanding of how libraries working both with Python 2.X and Python 3.X should be written. Let me consider pure Python libraries for the moment. I see various possibilities: 1. I just release two different libraries, say lib2X.py and lib3X.py, the first for the 2.X series and the second for the 3.X series, and the source code of lib3X.py is generated from lib2X.py via 2to3; 2. I release a single library lib.py which consists in a big if: $ cat lib.py if sys.version >= '3': from lib3X import * else: from lib2X import * I am not really happy with any of the options. I think there should be some cooperation between PyPI and easy_install such than when the user type $ easy_install lib the user gets the 2.X version or the 3.X version according to the Python version she is using. Is there something like that already in place? What are the recommendations for library authors willing to support both Python 2.X and 3.X in parallel? Michele Simionato From lkcl at lkcl.net Wed Dec 3 04:34:11 2008 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Wed, 3 Dec 2008 09:34:11 +0000 Subject: [ANN] Pyjamas 0.4: Python Web Toolkit Release In-Reply-To: <3de8e1f70812022054g40f974a1x5bdd676b2d9527ea@mail.gmail.com> References: <3de8e1f70812022054g40f974a1x5bdd676b2d9527ea@mail.gmail.com> Message-ID: On Wed, Dec 3, 2008 at 4:54 AM, Banibrata Dutta wrote: > Amazing concept, and glad that someone thought of this and implemented this. > The book's formatting on IE and Chrome looked a bit unusual. Content wise it > is already firly decent (i.e. enough to get a programmer started), but > sometimes text appears in a long & narrow col. format instead of the more > usual page format ... and the (i) i.e. informative text icons to the left of > informative notes gives a jarring visual feel/urge to scroll to see more :). yehh, the formatter is written in about 100 lines of python as a wiki-like "thing" that turns the txt pages into DOM-model appendChild()s behind the scenes. i was experimenting with a new layout reader: i've removed the experimentation, should work ok.... other than the headings

    and

    don't appear to be added! darn. have to find out why. some day :) l. From Slaunger at gmail.com Mon Dec 1 08:40:22 2008 From: Slaunger at gmail.com (Slaunger) Date: Mon, 1 Dec 2008 05:40:22 -0800 (PST) Subject: How to instantiate in a lazy way? Message-ID: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> Hi comp.lang.python, I am a novice Python programmer working on a project where I deal with large binary files (>50 GB each) consisting of a series of variable sized data packets. Each packet consists of a small header with size and other information and a much large payload containing the actual data. Using Python 2.5, struct and numpy arrays I am capable of parsing such a file quite efficiently into Header and Payload objects which I then manipulate in various ways. The most time consuming part of the parsing is the conversion of a proprietary form of 32 bit floats into the IEEE floats used internally in Python in the payloads. For many use cases I am actually not interested in doing the parsing of the payload right when I pass through it, as I may want to use the attributes of the header to select the 1/1000 payload which I actually have to look into the data for and do the resourceful float conversion. I would therefore like to have two variants of a Payload class. One which is instantiated right away with the payload being parsed up in the float arrays available as instance attributes and another variant, where the Payload object at the time of instantiation only contains a pointer to the place (f.tell()) in file where the payload begins. Only when the non-existing attribute for a parsed up module is actully accessed should the data be read, parsed up and the attribute created. In pseudocode: class PayloadInstant(object): """ This is a normal Payload, where the data are parsed up when instantiated """ @classmethod def read_from_file(cls, f, size): """ Returns a PayloadInstant instance with float data parsed up and immediately accessible in the data attribute. Instantiation is slow but after instantiation, access is fast. """ def __init___(self, the_data): self.data = the_data class PayloadOnDemand(object): """ Behaves as a PayloadInstant object, but instantiation is faster as only the position of the payload in the file is stored initially in the object. Only when acessing the initially non-existing data attribute are the data actually read and the attribure created and bound to the instance. This will actually be a little slower than in PayloadInstant as the correct file position has to be seeked out first. On later calls the object has as efficient attribute access as PayloadInstant """ @classmethod def read_from_file(cls, f, size): pos = f.tell() f.seek(pos + size) #Skip to end of payload return cls(pos) # I probably need some __getattr__ or __getattribute__ magic here...?? def __init__(self, a_file_position): self.file_position = a_file_position My question is this a a pyhtonic way to do it, and they I would like a hint as to how to make the hook inside the PayloadOnDemand class, such that the inner lazy creation of the attribute is completely hidden from the outside. I guess I could also just make a single class, and let an OnDemand attribute decide how it should behave. My real application is considerably more complicated than this, but I think the example grasps the problem in a nutshell. -- Slaunger From bignose+hates-spam at benfinney.id.au Fri Dec 5 20:19:41 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 06 Dec 2008 12:19:41 +1100 Subject: RELEASED Python 3.0 final References: <874p1jux8u.fsf@benfinney.id.au> Message-ID: <87iqpyt80i.fsf@benfinney.id.au> aahz at pythoncraft.com (Aahz) writes: > In article <874p1jux8u.fsf at benfinney.id.au>, > Ben Finney wrote: > >James Stroud writes: > >> > >> comp.lang.python3k ? > > > >The language has undergone an incompatible divide. Hopefully the > >community need not do the same. > > Pish and tosh. James was clearly making a funny; there's not *that* > much difference between 2.x and 3.x. You appear to assume I was not going along with the funny. To be expected, I suppose, given the well-documented context lossage in a message-based medium. I hereby recommend ?pish and tosh? for use by anyone who wants to counter someone's point. It beats by a country furlong the invective that has become regrettably common here in recent months. -- \ ?I was once walking through the forest alone and a tree fell | `\ right in front of me, and I didn't hear it.? ?Steven Wright | _o__) | Ben Finney From Alvin.ONeal at gmail.com Mon Dec 22 11:19:31 2008 From: Alvin.ONeal at gmail.com (Alvin ONeal) Date: Mon, 22 Dec 2008 09:19:31 -0700 Subject: Python's popularity In-Reply-To: <18767.47566.709705.92@montanaro-dyndns-org.local> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <18767.47566.709705.92@montanaro-dyndns-org.local> Message-ID: I decided to start learning python for 2 reasons: #A The white-space is wonderful - you can't code unreadable code. #B I noticed that just about every application I use has extensions written in python. Although it isn't as "cool" as ruby, it certainly has been in widespread use longer. I think that job postings inflate apparant popularity. For example if you look up jobs for "Flex developers", you'll see a lot of posts. There are a lot of people that hear the buzz and they think that they want a programmer with that skill, but in reality what they should be looking for is a java dev who is willing to learn flex because there just aren't that many poeple that know flex yet). I imagine the same is true of ruby. Also worthy of mention: I've seen python pre-installed on consumer HP desktops (I think as part of a backup/restore script, but I'm not sure) I would believe that python is in the top 5 for sure. AJ ONeal -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Dec 24 04:10:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2008 07:10:16 -0200 Subject: Strategy for determing difference between 2 very large dictionaries References: <1230102996.2303.1291616055@webmail.messagingengine.com> <1230106980.12156.1291620725@webmail.messagingengine.com> Message-ID: En Wed, 24 Dec 2008 06:23:00 -0200, escribi?: > Hi Gabriel, > > Thank you very much for your feedback! > >> k1 = set(dict1.iterkeys()) > > I noticed you suggested .iterkeys() vs. .keys(). Is there any advantage > to using an iterator vs. a list as the basis for creating a set? I You've got an excelent explanation from Marc Rintsch. (Note that in Python 3.0 keys() behaves as iterkeys() in previous versions, so the above code is supposed to be written in Python 2.x) >>> can this last step be done via a simple list comprehension? > >> Yes; but isn't a dict comprehension more adequate? >> >> [key: (dict1[key], dict2[key]) for key in common_keys if >> dict1[key]!=dict2[key]} > > Cool!! I'm relatively new to Python and totally missed the ability to > work with dictionary comprehensions. Yes, your dictionary comprehension > technique is much better than the list comprehension approach I was > struggling with. Your dictionary comprehension statement describes > exactly what I wanted to write. This time, note that dict comprehensions require Python 3.0 -- so the code above won't work in Python 2.x. (It's not a good idea to mix both versions in the same post, sorry!) You might use instead: dict((key,(dict1[key],dict2[key])) for key in ...) but it's not as readable. -- Gabriel Genellina From rurpy at yahoo.com Tue Dec 16 01:00:32 2008 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Mon, 15 Dec 2008 22:00:32 -0800 (PST) Subject: ethical questions about global variables References: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> Message-ID: <0d9a9758-f338-4a58-971a-1bd29e40ce32@v5g2000prm.googlegroups.com> On Dec 15, 7:45 pm, "Giampaolo Rodola'" wrote: > in a module of mine (ftpserver.py) I'd want to add a (boolean) global > variable named "use_gmt_times" to decide whether the server has to > return times in GMT or localtime but I'm not sure if it is a good idea > because of the "ethical" doubts I'm gonna write below. > > In first place I've never liked global variables too much and always > preferred per-class-instance variables instead. By "per-class-instance variables", you are talking about instance attributes? I.e. "self.use_gmt_times"? I don't see much difference between global variables and instance attributes. One of the main problems that make global variables bad is that they can be referenced and set anywhere in a program, so it can be very difficult, when one finds a global has a wrong value at some point, to figure out how it got that value. Consider the following: ~~~ Snippet 1 ~~~ #my_module def func1(): global A A = 1 def func2 global A A = 2 def func3 global A #Yes, this is redundant print A ~~~ Snippet 2 ~~~ class my_class: def func1(): self.A = 1 def func2 self.A = 2 def func3 print self.A What's the difference between snippet 1 and snippet 2? In the snippet 1, one says "global A"; in the snippet 2, "self." -- in this case it is just a spelling difference. If globals are "evil" then so must be the isomorphic use of attributes in snippet 2. I suppose one can say that classes are generally smaller than modules so that the "globalish" aspect of attributes is acceptable. But then one must conclude that the prohibition against using globals also applies to using instance attributes in large classes. Or conversely, that globals are perfectly acceptable, even desirable, in small modules. Note also that the common workaround to eliminate globals, passing them as arguments, doesn't really change anything either: #my_module class Config: pass config = Config() def func1(state): config.A = 1 def func2(state) config.A = 2 def func3(state) print config.A In other words, it is not the "global" keyword that causes problems, it is the anti-pattern of making a variable accessible in a read/write manner to a large number of functions without much control over who can change it or when. That anti-pattern can exist with globals, with instance attributes, or with function arguments. Simply avoiding globals is not sufficient to avoid the anti-pattern. > The problem in my case is that I have to use such variable in two > separated classes: FTPHandler and VirtualFileSystem. Also, I want that > for no reason one class uses times in GMT and the other one local > times. > > Another doubt is the naming convention. PEP-8 states that global > variables should use the lower_case_naming_convention but I've seen a > lot of library module using the UPPER_CASE_NAMING_CONVENTION. What am > I supposed to do about it? I generally use an initial capital letter for my global variables. I think it is useful to have some signal that a variable may be set outside the scope of the local function/method. From clp at rebertia.com Mon Dec 15 20:19:08 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 15 Dec 2008 17:19:08 -0800 Subject: parse C expression? In-Reply-To: References: Message-ID: <47c890dc0812151719p56fbd665tcc614f764585c987@mail.gmail.com> On Mon, Dec 15, 2008 at 3:48 PM, Torsten Mohr wrote: > Hi, > > i found some examples when googling for the subject but nothing really > matched. > > Is there a standard module available that lets me parse a syntax like "C" > with numbers, operators, braces, variables and function calls? > > I'd like to use this to parse an own kind of configuration language > and preferred would be just standard modules. Is there something > available that is maybe based on shlex? No, nothing approaching C-syntax as it'd have be much more complicated than shlex and I can't imagine too many uses for such a module. If it's a configuration file, you might consider using either JSON (std lib module `json`) or INI (std lib module `ConfigParser`) as the format instead. Or if you need something really complex, just use Python itself. Custom config file formats are bad anyway. Should you have no control over the format, you'll need to write a proper parser grammar with something like pyparsing as was mentioned by James. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From rhodri at wildebst.demon.co.uk Tue Dec 23 00:48:37 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Tue, 23 Dec 2008 05:48:37 -0000 Subject: iterating initalizations In-Reply-To: <002696D3-E888-4D32-8416-0CFE4AC859AC@gmail.com> References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> <47c890dc0812221943g44bd7222t8c09c088d87e77df@mail.gmail.com> <002696D3-E888-4D32-8416-0CFE4AC859AC@gmail.com> Message-ID: On Tue, 23 Dec 2008 03:52:35 -0000, Aaron Stepp wrote: > Simply put, I just need enough arrays to hold a list of > pitches/rhythms. Then I'll have each list member returned to an > instrument defined in another module. One "array" can hold a list of pitches/rhythms. I'm still not terribly clear as to why you need so many. Is each list intended for a different instrument, so you're more looking at: violin_1 = [ ...stuff... ] violin_2 = [ ...other stuff...] viola = [ ...really sweet stuff... ] cello = [ ...really boring stuff... ] -- Rhodri James *-* Wildebeeste Herder to the Masses From stephane.chazelas at unicyclist.com Mon Dec 1 11:08:16 2008 From: stephane.chazelas at unicyclist.com (Stephane Chazelas) Date: Mon, 1 Dec 2008 16:08:16 +0000 (UTC) Subject: Python surpasses Perl in popularity? References: <5e87aee0-c7fd-4e9d-befb-0cc01cee64ec@f40g2000pri.googlegroups.com> <49316c95$0$2813$742ec2ed@news.sonic.net> <49322ea2$0$2747$742ec2ed@news.sonic.net> Message-ID: 2008-12-1, 10:16(+00), Andre Majorel: [...] >> Tru64: >> /bin/sh can behave either as a Bourne shell or a POSIX shell >> (ksh88) depending on the environment > > How does it decide ? argv[0] ? isatty (STDIN_FILENO) ? That was answered in another article with a quote of the sh man page on Tru64: via an environment variable: BIN_SH. >> most Linux based systems and most other Unices: >> /bin/sh is a POSIX compliant shell (bash generally for Linux) >> and there's no Bourne shell (either there has never been or it >> has been removed/replaced by a POSIX shell). > > Two other Unixen I know of that have a non-POSIX sh are SCO Open > Server and UnixWare. I'm not sure they even provide a > POSIX-compliant alternative like Solaris does. Again, see http://www.in-ulm.de/~mascheck/various/shells/ [...] > Many people assume "standard" equates "portable". As far as > shell programming is concerned, the safest way to get portability > is to ignore the standard and code for the Bourne shell. Yes, it's enough and relatively safe in most cases. It's the only option if you want to be portable to systems over 15 years old. But nowadays, especially since the specifications have been made public, I find that it is sufficiently widespread to make POSIX a safer bet. At least having a specification gives you some sort of guarantee: if you write your script by the rules that are clearly (most of the time) specified, then it should work on any compliant system. If it doesn't work, then it's not your fault (though it's true in many case, you'll still be the one who'll have to do something about it). -- St?phane From martin at v.loewis.de Wed Dec 3 01:21:17 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 03 Dec 2008 07:21:17 +0100 Subject: porting modules to Python 3.0 In-Reply-To: <8f60c779-f1ec-4127-b173-f174c016aa96@a12g2000yqm.googlegroups.com> References: <8f60c779-f1ec-4127-b173-f174c016aa96@a12g2000yqm.googlegroups.com> Message-ID: <4936255D.6000509@v.loewis.de> > Is there something like that already in place? What are the > recommendations for library > authors willing to support both Python 2.X and 3.X in parallel? My recommendation is to use 3.0's build_py_2to3 implementation of the build_py command. See Demo/distutils/test2to3. You will have a single lib.py, written in 2.x. When you install in 3.0, lib2to3 will convert it to 3.x in the build area, and then install the 3.0 version. That, of course, requires you to adjust lib.py in such a way that 2to3 will successfully and completely convert it. In my experience (with porting Django) and Mark Hammond's experience (with porting PythonWin), this should be always possible. You look at what 2to3 does, find out what additional modifications need to be done, and apply them to the input of 2to3 so that a) 2to3 leaves these changes in place b) they either have no effect or still work correctly when run in 2.x. Regards, Martin From renesd at gmail.com Mon Dec 8 04:18:25 2008 From: renesd at gmail.com (illume) Date: Mon, 8 Dec 2008 01:18:25 -0800 (PST) Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? References: <5ccd4a18-cd2b-4040-90c6-33723af15e96@b38g2000prf.googlegroups.com> <7e1a9226-c7a9-4b5e-bfbb-ea079639d6a2@t39g2000prh.googlegroups.com> Message-ID: <682de8aa-62b1-477a-8b31-ae7698b1ffe7@w1g2000prk.googlegroups.com> On Dec 8, 7:31?pm, alex23 wrote: > On Dec 8, 2:26?pm, illume wrote: > > > pygame is simpler to learn, since it doesn't require you to know how > > to create classes or functions. > > I'm not sure if I'd be quick to tout that as an advantage... :) Hi, It's easier to teach only requiring *using* classes, and functions than *creating* them. This is important if it's being used to teach programming - as you don't need to teach people two fairly large concepts before you can do anything. People are motivated by seeing results. So it can be good to let people do things without requiring much learning. Anyone teaching object oriented program will tell you that it's a hard concept to present to people. So if you can avoid teaching parts of OO, and a bunch of other concepts at the same time, it's easier for people to handle. It's quite nice to be able to handle events without requiring callbacks. Everyone hates callbacks, but lots of people use them for event systems. However callbacks aren't needed at all for event programming. Instead you can get an event as an object and then process it. Callbacks for events made more sense in languages like smalltalk where events and method calls were closely aligned concepts(method calls are messages in smalltalk). However in languages where you don't have such a close conceptual alignment(such as python), making events objects instead of method calls is much easier to understand. Also python has very slow function calls, so avoiding using callbacks is also faster. Imagine using callbacks for files? So you would have to subclass file, and make a read_data method. Then your class will call your read data method when some data arrives. Kind of annoying, and not needed. From geon at post.cz Sun Dec 28 03:43:20 2008 From: geon at post.cz (Pavel Kosina) Date: Sun, 28 Dec 2008 09:43:20 +0100 Subject: tkinter 3.0 multiple keyboard events together In-Reply-To: References: <600d4b68-6fe2-4c2c-b425-1a739430bb54@s9g2000prg.googlegroups.com> <7b5e466c-d75d-4e71-b559-f8a0d3718094@r15g2000prd.googlegroups.com> Message-ID: <49573C28.6000808@post.cz> janislaw napsal(a): > Um, I could be only guessing what are you meant to do, unless you > describe your problem in more detailed way. I.e. describe the desired > behaviour, show code which you have, and describe the current > behaviour. > > well, I am working on a tutorial for youngster (thats why i need to stay the code as easy as possible). In this game you are hunted by robots. I could use key"7" on numeric keypad for left-up moving but seems to me, that "4"+"8" is much more standard for them. >> This solution has disadvantage that after you release one key, that the >> function keyPressHandler stopped to be called by the other pressed keys. >> I would have not to build moving the player in KeyPresshandler, but on >> another new function that would have to read periodically "keys" and to >> act afterwards.... >> > > Hmmm. Maybe you'd like to hook into Tkinter event loop, i.e. by custom > events if you don't like periodical polling. > No, that would be even more difficult. I already have a code that use your idea: from Tkinter import * root = Tk() pressedKeys=set() def onKeyPress(event): pressedKeys.add(event.keysym) def onKeyRelease(event): pressedKeys.remove(event.keysym) def move(): print list(pressedKeys) root.after(100,move) root.bind("", onKeyPress) root.bind("", onKeyRelease) root.after(100,move) root.mainloop() well, I thought that gui?s have such a problem already built-in - so that i am not pressed to code it. You know, its not exactly about me - if I do it for myself, for my program, that there is no problem, but I need to explained it to begginners ..... And I do not want, as might be more usual, do my module, that would cover this "insanity" (look at it with 13-years old boy eyes ;-) ). Do you like to say me, that this is not a standard "function" neither in tkinter, not say gtk or the others, too? I would expect something like this: def onKeyTouch(event): print (event.keysymAll) root.bind("", onKeyTouch) and all the pressed keys are printed ....all the functions OnKeyPress, OnKeyRelease, move, even set pressedKeys are in onKeyTouch.... P. From google at mrabarnett.plus.com Tue Dec 30 18:15:35 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 30 Dec 2008 23:15:35 +0000 Subject: get method In-Reply-To: References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> Message-ID: <495AAB97.5010707@mrabarnett.plus.com> James Mills wrote: > On Tue, Dec 30, 2008 at 7:10 PM, Roel Schroeven > wrote: >> Hm, you just changed an O(n) algorithm to an O(n**2) algorithm. No big >> deal for short strings, but try your solution on a string with length >> 10000 and see the difference. On my computer the O(n) version takes >> 0.008 seconds, while your version takes 8.6 seconds. That's 1000 times >> slower. > > Yes you are right :) Sadly :/ > > I wonder if there is a way to implement > the same thing with close to O(n) > complexity using list/dict comprehensions. > A while back I posted a Python implementation of 'bag' (also called a multiset). The code would then become something like: >>> s = "James Mills and Danielle Van Sprang" >>> dict(bag(s).iteritems()) {'a': 5, ' ': 5, 'e': 3, 'd': 1, 'g': 1, 'i': 2, 'm': 1, 'J': 1, 'M': 1, 'l': 4, 'n': 4, 'p': 1, 's': 2, 'r': 1, 'V': 1, 'S': 1, 'D': 1} From kay.schluehr at gmx.net Tue Dec 2 12:15:16 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 2 Dec 2008 09:15:16 -0800 (PST) Subject: Python+Pyjamas+V8=ftw References: <56533d3d-c5cd-4a41-9bc3-525eaa44bba1@d23g2000yqc.googlegroups.com> Message-ID: On 2 Dez., 14:57, lkcl wrote: > ?as a general-purpose plugin replacement for /usr/bin/python, however, > it's not quite there. ?and, given that javascript cheerfully goes > about its way with the "undefined" concept, it's always going to be a > _bit_ tricky to provide absolutely _every_ language feature, > faithfully. For some reasons I'd do it the other way round and model JS entirely in Python first. This is rather gratefully supported by two facts 1) Python is far more powerful than JS and supports lots of metaprogramming facilities. For example providing a Python type that has JS prototype semantics isn't really a big deal. 2) JS is standardized and the standard is very well documented. When JS has been mapped onto a dedicated Python framework one can open the backchannel and translate the Python framework code to JS. Ideally the mapping P_JS -> P_PyJS -> P'_JS is an identity. PyJS is unambiguously fixed by this mapping. Now people may define mappings from Python types to PyJS types and all the checks and tests are performed as usual checks in Python code by API functions of the PyJS framework. The compiler hasn't anything to do with it anymore and can be somewhat liberated from hard work. This roundtrip breaks with the GWT scheme of one way translation for an obvious reasons: Python is not Java. Regards, Kay From scott.p.macdonald at gmail.com Tue Dec 16 13:15:30 2008 From: scott.p.macdonald at gmail.com (Scott MacDonald) Date: Tue, 16 Dec 2008 11:15:30 -0700 Subject: Python Dictionary Algorithm Question In-Reply-To: <3ca641b40812160951h3a13e69am291afb02965451a7@mail.gmail.com> References: <3ca641b40812160951h3a13e69am291afb02965451a7@mail.gmail.com> Message-ID: You might be interested in the "Beautiful Code" book: http://oreilly.com/catalog/9780596510046/ It has a chapter on Python's dict implementation that is pretty good. On Tue, Dec 16, 2008 at 10:51 AM, Brigette Hodson wrote: > Hello! I am in a beginning algorithms class this semester and I am working > on a presentation. I want to discuss in some detail the algorithm python > uses to determine the hash function for python dictionaries. Does anyone > know what this algorithm is? Or where I can go to find information on it? > > Thanks. > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at mrabarnett.plus.com Mon Dec 15 12:14:34 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 15 Dec 2008 17:14:34 +0000 Subject: Structure using whitespace vs logical whitespace In-Reply-To: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> References: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> Message-ID: <4946907A.8040504@mrabarnett.plus.com> cmdrrickhunter at yaho.com wrote: > I've been trying to search through the years of Python talk to find an > answer to this, but my Googlefu is weak. > > In most languages, I'll do something like this > > xmlWriter.BeginElement("parent"); > ----xmlWriter.BeginElement("child"); > ----------xml.Writer.Characters("subtext"); > ----xmlWriter.EndElement(); > xmlWriter.EndElement(); > > Where the dashes are indentation (since some newsgroup handlers don't > do tabs well). XML writing is just an example. > > In general, I'm using indentation to show logical flow through code. > Python's choice to give semantic meaning to whitespace prevents me > from doing such things. What was once reserved for logical use is now > used syntactically. In 90% of cases, its not needed, and whitespace > significance seems to be pretty effective. In that last 10%, however, > I've been frustrated many times. > > I've been using python for a few years, and gotten around this in one > way or another, but now I want to get other who work with me to pick > up Python. All newbies to Python have trouble with the idea of > whitespace sensitivity, but how can I convince them that "it just > works better" when I have this construct which I want to use but > can't. > > Has anybody found a way to emulate this behavior? I've often done it > by opening an expression for the whole thing, but there's a lot of > tasks where a single expression just isn't sufficient (such as things > with assignment). > > PS. In my opinion the solution would be to have the option of entering > a "whitespace insensitive" mode which uses C style {} and ;. The > token to enter it could be as complicated as you want (in fact, it may > make sense to make it complicated to discourage use unless it's really > advantageous). I'd sugest {{ and }} or something bigger like {={ } > =}. Only two problems: 1) I'm sure it would offend Guido's sense of > language aesthetics 2) I'm sure the idea has been hashed over on this > newsgroup to death... hence prefering a workaround instead. > You could use the "with" statement: class xml_element(object): def __init__(self, text): self.text = text def __enter__(self): xmlWriter.BeginElement(self.text) def __exit__(self, *args): xmlWriter.EndElement() with xml_element("parent"): with xml_element("child"): xmlWriter.Characters("subtext") From tjreedy at udel.edu Mon Dec 8 17:01:34 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Dec 2008 17:01:34 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Rasmus Fogh wrote: > For my personal problem I could indeed wrap all objects in a wrapper with > whatever 'correct' behaviour I want (thanks, TJR). It does seem a bit I was not suggesting that you wrap *everything*, merely an adaptor for numpy arrays in whatever subclass and source it is that feeds them to your code. It is fairly unusual, I think, to find numpy arrays 'in the wild', outside the constrained context of numerical code where the programmer uses them intentionally and hopefully understands their peculiarities. > much, though, just to get code like this to work as intended: > alist.append(x) > print ('x is present: ', x in alist) Even if rich comparisons as you propose, the above would *still* not necessarily work. Collection classes can define a __contains__ that overrides the default and that can do anything, though True/False is recommended. As best I can think of at the moment, the only things you can absolutely depend on is that builtin id(ob) will return an int, that 'ob1 is ob2' (based in id()) will be True or False, and that builtin type(ob) will be a class (at least in 3.0, not sure of 2.x). The names can be rebound but you can control that within the module you write. This is what I meant when I said that 'generic' nearly always needs to be qualified to something like 'generic for objects that meet the interface requirements'. Every function has that precondition as part of its implied contract. Your code has an interface requirement that 'x in y' not raise an exception. An x,y pair that does it outside its contract. Terry Jan Reedy From tjreedy at udel.edu Thu Dec 4 13:31:01 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Dec 2008 13:31:01 -0500 Subject: Python 3 read() function In-Reply-To: <16651e80812040900j257fe2acjf5d8817811d32da6@mail.gmail.com> References: <16651e80812040900j257fe2acjf5d8817811d32da6@mail.gmail.com> Message-ID: Jerry Hill wrote: > On Thu, Dec 4, 2008 at 11:48 AM, Christian Heimes wrote: >> Cro wrote: >>> vContent = io.StringIO() >>> vContent = huge.read() # This line takes hours to process !!! >> Do you really mean io.StringIO? I guess you want io.BytesIO() .. > > I don't think it matters. Here's a quick comparison between 2.5 and > 3.0 on a relatively small 17 meg file: > > C:\>c:\Python30\python -m timeit -n 1 > "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" > 1 loops, best of 3: 36.8 sec per loop > > C:\>c:\Python25\python -m timeit -n 1 > "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" > 1 loops, best of 3: 33 msec per loop > > That's 3 orders of magnitude slower on python3.0! Timing of os interaction may depend on os. I verified above on WinXp with 4 meg Pythonxy.chm file. Eye blink versus 3 secs, duplicated. I think something is wrong that needs fixing in 3.0.1. http://bugs.python.org/issue4533 tjr From skip at pobox.com Thu Dec 4 12:49:34 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 4 Dec 2008 11:49:34 -0600 Subject: Python 3 read() function In-Reply-To: <6e24be88-b042-425b-b880-c97d184fee07@s20g2000yqh.googlegroups.com> References: <6e24be88-b042-425b-b880-c97d184fee07@s20g2000yqh.googlegroups.com> Message-ID: <18744.6190.414364.952537@montanaro-dyndns-org.local> >>> huge = io.open("C:\HUGE_FILE.pcl",'r+b',0) Why do you want to disable buffering? From the io.open help: open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True) Open file and return a stream. Raise IOError upon failure. ... buffering is an optional integer used to set the buffering policy. By default full buffering is on. Pass 0 to switch buffering off (only allowed in binary mode), 1 to set line buffering, and an integer > 1 for full buffering. I think you will get better performance if you open the file without the third arg: huge = io.open("C:\HUGE_FILE.pcl",'r+b') -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From kirk at daycos.com Mon Dec 15 15:24:14 2008 From: kirk at daycos.com (Kirk Strauser) Date: Mon, 15 Dec 2008 14:24:14 -0600 Subject: tricky nested list unpacking problem References: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> Message-ID: <87fxkpxk41.fsf@daycos.com> At 2008-12-15T20:03:14Z, "Chris Rebert" writes: > You just need a recursive list-flattening function. There are many > recipes for these. Here's mine: >>>> flattened = flatten([1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]]) >>>> flattened > [1, 2, 3, 5, 6, 10, 11, 7, 9, 1, 2, 3, 4, 5] >>>> '-'.join(str(num) for num in flattened) > '1-2-3-5-6-10-11-7-9-1-2-3-4-5' He doesn't want to flatten them directly. He's using [1,2,3] sort of like a regular expression, so that 1,[2,3],4 means "1,2,4" or "1,3,4", not "1,2,3,4". -- Kirk Strauser The Day Companies From noZ.spamZ at ZZ.ZsvpZ.com Mon Dec 15 18:38:09 2008 From: noZ.spamZ at ZZ.ZsvpZ.com (Michel Claveau - NoSpam SVP ; merci) Date: Tue, 16 Dec 2008 00:38:09 +0100 Subject: Problem Python 2.6.1 vs 2.6 & pyWin32 In-Reply-To: References: <4946754f$0$19000$426a74cc@news.free.fr><4946D09F.6050300@v.loewis.de> Message-ID: <4946ed94$0$22011$426a74cc@news.free.fr> Hi! I noted, also, than, in some cases, Python26.dll is not copied in %WINDIR%\system32 After that, external softs don't find the DLL. But it's a detail, because it's easy to copy the DLL with install scripts. @-salutations -- Michel Claveau From deets at nospam.web.de Wed Dec 10 07:45:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 10 Dec 2008 13:45:43 +0100 Subject: How do I manually uninstall setuptools (installed by egg)? References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> <375bd56a-d92b-4d33-bf70-5bea630a376a@q30g2000vbn.googlegroups.com> Message-ID: <6q9rvnFbj6ogU1@mid.uni-berlin.de> excord80 at gmail.com wrote: > On Dec 9, 10:04?pm, "Chris Rebert" wrote: >> So, why do you think apt and not setuptools is The Right Way(tm)? > > I like to keep > 1 Python on my computer. > > 1. First, there's the system Python, which is installed by my OS and > which I try not to mess with too much. I'm guessing Ubuntu uses this > Python for various system jobs, preferences apps, etc. I try to only > use apt with *this* Python. Start using virtualenv. You need to install that single package, and you can create as many python-instances (derived of your system's python of course) that you like. And inside these, mess around with setuptools as much as you like. > 2. Then there's my *own* Python. Maybe installed in ``/opt/py-i.j.k, > or---more likely---``~/opt/py-i.j.k``. *This* is the one where I've > previously made regular use of setuptools and ``easy_install``. If I > break this one somehow, it doesn't foul up my system Python in any > way, and it's easy to scrap it and start anew if I like. > > So, I'd like to get my *system* Python back to its "fresh out of the > Ubuntu showroom" condition and remove *that* setuptools. > > As an aside, I'm a bit struck by how long the setuptools/easy_install > manuals are, and a bit dismayed at the lack of an easy_install > uninstall command. Thinking of trying life for a while without > setuptools/easy_install. Will have to see how far I get. :) To *long* manuals? So far I haven't heard that complaint in the FOSS world... Diez Diez From google at mrabarnett.plus.com Sun Dec 21 11:31:51 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 21 Dec 2008 16:31:51 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: <494E6F77.2000203@mrabarnett.plus.com> Aaron Brady wrote: > On Dec 20, 8:49 pm, MRAB wrote: >> Aaron Brady wrote: >>> On Dec 20, 7:38 pm, Steven D'Aprano >> cybersource.com.au> wrote: >>>> Instead of just whinging, how about making a suggestion to fix it? Go on, >>>> sit down for an hour or ten and try to work out how a BINARY OPERATOR >>>> like % (that means it can only take TWO arguments) can deal with an >>>> arbitrary number of arguments, *without* having any special cases. >>>> Go on. Take your time. I'll be waiting. >>> Hi, not to take sides, but, there is a possibility. >>> This behavior is currently legal: >>>>>> "%i %%i" % 0 % 1 >>> '0 1' >>> So, just extend it. (Unproduced.) >>>>>> "%i %i" % 0 % 1 >>> '0 1' >>>>>> "%r %i" % (2, 3, 4) % 1 >>> '(2, 3, 4) 1' >>>>>> "%r %i" % (2, 3, 4) >>> '(2, 3, 4) %i' >>> Which is quite clever and way ahead of its (posessive) time. >> A couple of problems: >> >> 1. How do you handle a literal '%'? If you just double up then you'll >> need to fix the string after all your substitutions. >> >> 2. What if a substitution introduces a '%'? >> >> I suppose a possible solution would be to introduce a special format >> string, including a literal, eg: >> >> f"%r %i" % (2, 3, 4) % 1 >> >> and then convert the result to a true string: >> >> print(str(f"%r %i" % (2, 3, 4) % 1)) >> >> (although print() would call __str__ anyway). >> >> The format string would track where the last substitution occurred. >> >> Hmm... I think I'll just learn the new method. :-) > > Now that I'm fighting 'r's war for him/her... > > Um, here's one possibility. On the first interpolation, flags are > noted and stored apart from subsequent interpolations. Then, use a > sentinel to terminate the interpolation. (Unproduced.) > >>>> "%r %i" % ( 2, 3 ) % 0 > '(2, 3) 0' >>>> "%% %r" % ( 2, 3 ) % str.interp_end > '% (2, 3)' >>>> "%sss%i" % "%d" % 0 > '%dss0' > > The first %s is replaced with %d, but doesn't hijack the '0'. If you > want to interpolate the %d, use the sentinel. The sentinel is what > causes '%%' to be handled. > >>>> "%sss%i" % "%d" % 0 % 1 > Traceback (most recent call last): > File "", line 1, in > TypeError: not all arguments converted during string formatting >>>> "%sss%i" % "%d" % 0 % str.interp_end % 1 > '1ss0' > > Treating tuples as a special case appears to be the simpler solution, > but this, 'chaining', to adopt the term, is still feasible. > A possible solution occurred to me shortly after I posted, but I decided that sleep was more important. :-) The original format is a string. The result of '%' is a string if there's only 1 placeholder to fill, or a (partial) format object (class "Format"?) if there's more than one. Similarly, the format object supports '%'. The result of '%' is a string if there's only 1 placeholder to fill, or a new (partial) format object if there's more than one. >>> f = "%r %i" >>> type(f) >>> f = f % (2, 3, 4) >>> type(f) >>> f = f % 1 >>> type(f) From james at agentultra.com Fri Dec 5 11:51:17 2008 From: james at agentultra.com (J Kenneth King) Date: Fri, 05 Dec 2008 11:51:17 -0500 Subject: Python 3.0 automatic decoding of UTF16 References: Message-ID: <85fxl24lbu.fsf@dozer.localdomain> Johannes Bauer writes: > Traceback (most recent call last): > File "./modify.py", line 12, in > a = AddressBook("2008_11_05_Handy_Backup.txt") > File "./modify.py", line 7, in __init__ > line = f.readline() > File "/usr/local/lib/python3.0/io.py", line 1807, in readline > while self._read_chunk(): > File "/usr/local/lib/python3.0/io.py", line 1556, in _read_chunk > self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) > File "/usr/local/lib/python3.0/io.py", line 1293, in decode > output = self.decoder.decode(input, final=final) > File "/usr/local/lib/python3.0/codecs.py", line 300, in decode > (result, consumed) = self._buffer_decode(data, self.errors, final) > File "/usr/local/lib/python3.0/encodings/utf_16.py", line 69, in > _buffer_decode > return self.decoder(input, self.errors, final) > UnicodeDecodeError: 'utf16' codec can't decode bytes in position 74-75: > illegal encoding It probably means what it says: that the input file contains characters it cannot read using the specified encoding. Are you generating the file from python using a file object with the same encoding? If not, then you might want to look at your input data and find a way to deal with the exception. From tinnews at isbd.co.uk Fri Dec 19 11:23:49 2008 From: tinnews at isbd.co.uk (tinnews at isbd.co.uk) Date: 19 Dec 2008 16:23:49 GMT Subject: mailbox.mbox.add() appears to set both access and modification times Message-ID: <494bca95$0$510$bed64819@news.gradwell.net> I'm using mailbox in Python 2.5.2 to filter incoming mail into separate mailboxes. I prefer mbox for various reasons and so I have used that format. It would appear then when I do:- dest = mailbox.mbox(destDir, factory=None) dest.add(m) it sets both the access and modification times of the mbox to the date and time now. This is a disaster for MUAs that detect new mail by looking to see if the mbox has been modified after it was accessed. Is this a known bug in mailbox.mbox.add(), or am I doing something wrong, or what? -- Chris Green From timr at probo.com Sun Dec 28 00:22:05 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 28 Dec 2008 05:22:05 GMT Subject: math.sqrt() in new 3.0 version : solution in input() References: Message-ID: David Lemper wrote: > >I cannot find a mention of this in "The Python Tutorial >release 3.1" The I&O section discusses output formatting >and reading & writing text files. >John pointed out its in Guido's "What's New in Python3.0" >Indeed its mentioned in PEP 3111, near end of What's New >and somewhat obscurely. " raw_input() was renamed to input(). >That is the new input() function function reads a line from >sys.stdin . . ." The issue, in my view, is that input() (and raw_input()) are almost exclusively relegated to the domain of beginners and tutorials. Real programs almost never use them. As a result, this change just isn't seen to be all that important. If you can figure out where this could have been written so that you would have seen it, I'm sure a documentation change could be made. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From Scott.Daniels at Acm.Org Fri Dec 5 12:12:58 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 05 Dec 2008 09:12:58 -0800 Subject: pretty strange behavior of "strip" FORGET THE LAST ONE In-Reply-To: References: <4938693F.6090709@yahoo.ca> <493936EC.9030606@yahoo.ca> Message-ID: Guy Doune wrote: > > > Guy Doune a ?crit : >> Ok, didn't show the whole problem... >> >> I will read the doc anyway, but why "questions.html" keep it "t"?? >> >> >>> test=['03.html', '06.html', 'questions.html', '04.html', >> 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] >> >>> test[4] >> 'toc.html' >> >>> test[4].strip('.html') >> 'oc' >> >>> test[2].strip('.html') >> 'questions' Well, why does ' a b c '.strip() leave two spaces? --Scott David Daniels Scott.Daniels at Acm.Org From bieffe62 at gmail.com Mon Dec 22 04:57:12 2008 From: bieffe62 at gmail.com (bieffe62 at gmail.com) Date: Mon, 22 Dec 2008 01:57:12 -0800 (PST) Subject: How to represent a sequence of raw bytes References: Message-ID: <6d84efe9-7ca9-4031-9ee7-902e4c873f54@a26g2000prf.googlegroups.com> On 22 Dic, 03:23, "Steven Woody" wrote: > Hi, > > What's the right type to represent a sequence of raw bytes. ?In C, we usually do > > 1. ?char buf[200] ?or > 2. ?char buf[] = {0x11, 0x22, 0x33, ... } > > What's the equivalent representation for above in Python? > > Thanks. > > - > narke Usually, if I have to manipulate bytes (e.g. computing checksum, etc...) i just use a list of numbers: buf = [11, 22, 33, ...] then when I need to put it in a buffer similar to the one in C (e.g. before sending a packet of bytes through a socket or another I/O channel), I use struct.pack import struct packed_buf = struct.pack('B'*len(buf), buf ) similarly, if I get a packet of bytes from an I/O channel and I need to do operation on them as single bytes, I do: buf = struct.unpack('B'*len(packed_buf), packed_buf ) Note that struct.pack and struct.unpack can trasform packed bytes in other kind of data, too ... There are other - maybe more efficient - way of handling bytes in python programs, like using array as already suggested, but, up to now, I never needed them in my python programs, which are not real- time stuff, but sometime need to process steady flows of data. Ciao ---- FB From pruebauno at latinmail.com Tue Dec 9 12:13:03 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Tue, 9 Dec 2008 09:13:03 -0800 (PST) Subject: Python 3 For Python 2 Users References: Message-ID: <0c7ddb07-535f-4231-8ba7-ad099ccc19fa@13g2000yql.googlegroups.com> On Dec 9, 11:58?am, Tim Daneliuk wrote: > I code in Python 2.x intermittently and have only casually watched the > 3.x development discussions. ?Now it's time to get up to speed. > Has someone written a tutorial for people in my situation. ?Yes, I've > looked at the release notes, but I'm looking for something that > motivates all the major changes to give me a better sense of the > Gestalt of the new language. > > TIA, > -- > ---------------------------------------------------------------------------- > Tim Daneliuk ? ? tun... at tundraware.com > PGP Key: ? ? ? ?http://www.tundraware.com/PGP/ For starters this should work: http://docs.python.org/dev/3.0/whatsnew/3.0.html From google at mrabarnett.plus.com Fri Dec 12 10:04:51 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 12 Dec 2008 15:04:51 +0000 Subject: Python is slow In-Reply-To: <8156b37b-d1f6-4142-ad6e-8488c95b6592@z28g2000prd.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> <8156b37b-d1f6-4142-ad6e-8488c95b6592@z28g2000prd.googlegroups.com> Message-ID: <49427D93.3090800@mrabarnett.plus.com> sturlamolden wrote: > On Dec 12, 3:04 pm, Luis M. Gonz?lez wrote: > >> Why don't you guys google a little bit to know what's being done to >> address python's "slowness"?? > > Nothing is being done, and woth Py3k it got even worse. > >> It has been mentioned in this thread the pypy project (isn't it enough >> for you??) >> Other hints: shedskin, psyco, pyrex... > > None of those projects addresses inefficacies in the CPython > interpreter, except for psyco - which died of an overdose PyPy. > > PyPy is interesting if they ever will be able to produce something > useful. They have yet to prove that. Even if PyPy can come up with a > Python JIT, they will still be decades behind the technologies of > Strongtalk and Java. That is the problem with reinventing the wheel > all over again. > > Not to forget LLVM and Parrot which also will support Python > frontends. > Python is developed and maintained by volunteers. If you'd like to have a go at writing a JIT interpreter for it, then go ahead. No-one here will stop you. From temotor at gmail.com Fri Dec 19 02:32:02 2008 From: temotor at gmail.com (Sergey Shepelev) Date: Thu, 18 Dec 2008 23:32:02 -0800 (PST) Subject: Python lex settings References: <0dfeb0c3-a524-4a72-aafd-4b88b71ff16c@w39g2000prb.googlegroups.com> Message-ID: On Dec 19, 2:16?am, Robert Kern wrote: > Sergey Shepelev wrote: > > Hello. > > > I'm trying to make almost-Python source to Erlang source translation > > tool. > > > Are there ready ply.lex settings for parsing python source? > > Yes! Andrew Dalke has implemented a PLY grammar for Python for experimenting > with almost-Python languages. > > ? ?http://www.dalkescientific.com/Python/python4ply.html > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > ? that is made terrible by our own mad attempt to interpret it as though it had > ? an underlying truth." > ? ?-- Umberto Eco Wow! Thank you very much, it's exactly what i was searching for. From google at mrabarnett.plus.com Thu Dec 4 12:51:46 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 04 Dec 2008 17:51:46 +0000 Subject: Python 3 read() function In-Reply-To: References: Message-ID: <493818B2.1020404@mrabarnett.plus.com> Cro wrote: > Good day. > I have installed Python 3 and i have a problem with the builtin read() > function. > > [code] > huge = open ( 'C:/HUGE_FILE.pcl', 'rb', 0 ) > import io > vContent = io.StringIO() > vContent = huge.read() # This line takes hours to process !!! > vSplitContent = vContent.split > ( 'BIN;SP1;PW0.3,1;PA100,700;PD625,700;PU;' ) # This one i have neve > tried... > [/code] > > The same thing, in Python 2.5 : > > [code] > huge = open ( 'C:/HUGE_FILE.pcl', 'rb', 0 ) > import StringIO > vContent = StringIO.StringIO() > vContent = huge.read() # This line takes 2 seconds !!! > vSplitContent = vContent.split > ( 'BIN;SP1;PW0.3,1;PA100,700;PD625,700;PU;' ) # This takes a few > seconds... > [/code] > > My "HUGE_FILE" has about 900 MB ... > I know this is not the best method to open the file and split the > content by that code... > Can anyone please suggest a good method to split the file with that > code very fast, in Python 3 ? > The memory is not important for me, i have 4GB of RAM and i rarely use > more than 300 MB of it. > > Thank you very very much. > Can't you read it without StringIO? huge = open('C:/HUGE_FILE.pcl', 'rb', 0) vContent = huge.read() vSplitContent = vContent.split(b'BIN;SP1;PW0.3,1;PA100,700;PD625,700;PU;') vContent will contain a bytestring (bytes), so I think you need to split on a bytestring b'...' (in Python 3 unmarked string literals are Unicode). From svalbardcolaco at gmail.com Fri Dec 5 01:17:45 2008 From: svalbardcolaco at gmail.com (svalbard colaco) Date: Fri, 5 Dec 2008 11:47:45 +0530 Subject: CONNECTION TIMED OUT ERROR using urllib2 Message-ID: <726d283d0812042217w41a0288eg3ee79d4ffdb5ff4b@mail.gmail.com> Hi all I have written a small code snippet to open a URL using urllib2 to open a web page , my python version is 2.4 but i get an urlopen error called connection timed out The following is the code snippet *import urllib2 f = urllib2.urlopen('http://www.google.com/') print f.read(100)* where as the same url http://www.google.com/ works through my browser. The following is the back trace : File "test_url.py", line 3, in ? f = urllib2.urlopen('http://www.google.com/') File "/usr/lib/python2.4/urllib2.py", line 130, in urlopen return _opener.open(url, data) File "/usr/lib/python2.4/urllib2.py", line 358, in open response = self._open(req, data) File "/usr/lib/python2.4/urllib2.py", line 376, in _open '_open', req) File "/usr/lib/python2.4/urllib2.py", line 337, in _call_chain result = func(*args) File "/usr/lib/python2.4/urllib2.py", line 1021, in http_open return self.do_open(httplib.HTTPConnection, req) File "/usr/lib/python2.4/urllib2.py", line 996, in do_open raise URLError(err) *urllib2.URLError: Any pointers in this regard will be of great help. Thanking you'll in advance. Regards, sv -------------- next part -------------- An HTML attachment was scrubbed... URL: From noone at lewscanon.com Mon Dec 1 20:29:44 2008 From: noone at lewscanon.com (Lew) Date: Mon, 01 Dec 2008 20:29:44 -0500 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: anonymous.c.lisper at gmail.com wrote: > A rational human would realize that not too many people peruse this > newsgroup, > and that most of them have already seen the wall of text post that you > generate every time. Just out of curiosity, what do you consider "this" newsgroup, given its wide crossposting? -- Lew From castironpi at gmail.com Sat Dec 13 15:33:34 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 13 Dec 2008 12:33:34 -0800 (PST) Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> Message-ID: <3f834c00-8f5c-4917-b849-239c6231a078@t39g2000prh.googlegroups.com> On Dec 12, 7:31?am, Steve Holden wrote: > sturlamolden wrote: > > On Dec 12, 1:56 pm, sturlamolden wrote: > > >> That is because integers are immutable. When x += 1 is done on an int, > >> there will be a rebinding. But try the same on say, a numpy array, and > >> the result will be different: snip > This was all thrashed out exhaustively in the still-feared call > semantics thread. Yes, augmented operations work differently on mutable > and immutable objects. Nothing to see here, move right along ... Lol! From google at mrabarnett.plus.com Sun Dec 21 21:42:56 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 22 Dec 2008 02:42:56 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <2dfbb87b-019e-43aa-a9ef-5de2b5ada846@s1g2000prg.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <2dfbb87b-019e-43aa-a9ef-5de2b5ada846@s1g2000prg.googlegroups.com> Message-ID: <494EFEB0.3040900@mrabarnett.plus.com> Aaron Brady wrote: > On Dec 21, 6:14 pm, MRAB wrote: >> Aaron Brady wrote: >>> On Dec 21, 10:58 am, MRAB wrote: >>>> Aaron Brady wrote: >>>>> On Dec 21, 10:31 am, MRAB wrote: >>> snip >>>>>> The original format is a string. The result of '%' is a string if >>>>>> there's only 1 placeholder to fill, or a (partial) format object (class >>>>>> "Format"?) if there's more than one. Similarly, the format object >>>>>> supports '%'. The result of '%' is a string if there's only 1 >>>>>> placeholder to fill, or a new (partial) format object if there's more >>>>>> than one. >>>>>> >>> f = "%r %i" >>>>>> >>> type(f) >>>>>> >>>>>> >>> f = f % (2, 3, 4) >>>>>> >>> type(f) >>>>>> >>>>>> >>> f = f % 1 >>>>>> >>> type(f) >>>>>> >>>>> Alright, so how are you handling: >>>>>>>> f= "%s %i" >>>>>>>> type( f ) >>>>> >>>>>>>> f= f% '%i' #now '%i %i' >>>>>>>> type( f ) >>>>> >>>>>>>> f= f% 1 >>>>>>>> type( f ) >>>>> ? >>>>> In other words, are you slipping '1' in to the very first available >>>>> slot, or the next, after the location of the prior? >>>> Let's assume that Format objects display their value like the equivalent >>>> string format: >>>> >>> f = "%r %i" >>>> >>> f >>>> '%r %i' >>>> >>> f = f % (2, 3, 4) >>>> >>> f >>>> >>>> >>> f = f % 1 >>>> >>> f >>>> '(2, 3, 4) 1' >>>> >>> f = "%s %i" >>>> >>> f >>>> '%s %i' >>>> >>> f = f % '%i' >>>> >>> f >>>> >>>> >>> f = f % 1 >>>> >>> f >>>> '%%i 1' >>> I assume you meant '%i 1' since there are no more flags in f, and it's >>> returned to a regular string. >> Correct. >> >>> 'f %= 1' doesn't work any more as in-place modulo, since one time, 'f' >>> is a Format object, the other, 'f' is a string. Just raise an >>> exception for that (or assign to __class__ IINM if I'm not mistaken). >> All assignments rebind, even the augmented form: >> >> >>> class C1(object): >> def __mod__(self, value): >> return C2() >> >> >>> class C2(object): >> def __mod__(self, value): >> return C2() >> >> >>> f = C1() >> >>> f >> <__main__.C1 object at 0x00D144F0> >> >>> f % 0 >> <__main__.C2 object at 0x00D143F0> >> >>> f %= 0 >> >>> f >> <__main__.C2 object at 0x00D145B0> >> >> >> >>> Actually, the class you showed is kind of nifty. Tuples are correctly >>> interpolated. I think on the whole you'll use more parenthesis, since >>> each term in the tuple appears separately, and might be an expression >>> (have a lower-precedence op.), as well as more modulo signs. >>> You can currently do-it-yourself, you just need a constructor in the >>> format string. >>>>>> f = Format("%r %i") >>>>>> type(f) >>> >>>>>> f = f % (2, 3, 4) >>>>>> type(f) >>> >>> Or, as someone suggested earlier, a new literal marking: >> Yes, I suggested that earlier, but it isn't needed because you can >> create a format object with "Format(string)". However, most of the time >> you won't bother to create a format object explicitly because of: >> >> class str(object): >> def __mod__(self, value): >> return Format(self) % value >> >>>>>> f = f"%r %i" >>>>>> type(f) >>> >> >>> # Explicitly >> >>> f = Format("%r %i") >> >>> f >> >> >>> f % (2, 3, 4) >> >> >>> >> >>> # Implicitly, relying on the __mod__ method of str >> >>> f = "%r %i" >> >>> f >> '%r %i' >> >>> f % (2, 3, 4) >> >> >> I'd also like to add that there's nothing to prevent format objects from >> having other methods where multiple placeholders can be filled in one call: >> >> >>> # By position >> >>> f = Format("%r %i") >> >>> f >> >> >>> f.fill([(2, 3, 4), 1]) >> '(2, 3, 4) 1' >> >>> >> >>> # By name >> >>> f = Format("%{tuple}r %{int}i") >> >>> f >> >> >>> f.fill({"tuple": (2, 3, 4), "int": 1}) >> '(2, 3, 4) 1' > > You're choosing to favor the '.chain()' method over the '.fill()' > method for the behavior of '%'. I don't think you've justified it > though. > >>>> Format( "%r %i" ).chain( ( 2, 3, 4 ) ).chain( 0 ) > '(2, 3, 4) 0' >>>> Format( "%r %i" ).fill( ( 2, 3, 4 ), 0 ) > '(2, 3, 4) 0' > > Plus, I almost think we've almost attained defeating the purpose. > The disadvantage of the chaining method is that it's positional, left-to-right. For the purposes of i18n you want tagged placeholders, whether they be integers or names. I think... OK, if the placeholders include a positional tag, eg "%(0)s %(1)s", then they could be filled in according to _that_ order. Not sure about named placeholders, though. Perhaps, like at present, if a dict is given to a format with named placeholders then several placeholders could be filled, the problem being how to fill a _single_ named placeholder with a dict. From michael at stroeder.com Thu Dec 4 11:45:05 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Thu, 04 Dec 2008 17:45:05 +0100 Subject: EBCDIC <--> ASCII In-Reply-To: <091f0404-2be3-4bda-8619-03627bd03fdc@k8g2000yqn.googlegroups.com> References: <091f0404-2be3-4bda-8619-03627bd03fdc@k8g2000yqn.googlegroups.com> Message-ID: martinjamesevans at gmail.com wrote: > I'm having a problem trying to use the codecs package to aid me in > converting some bytes from EBCDIC into ASCII. Which EBCDIC variant? > sEBCDIC = unicode(sSource, 'cp500', 'ignore') Are you sure CP500 is the EBCDIC variant for the language you want? http://www.ietf.org/rfc/rfc1345.txt lists it as: &charset IBM500 &rem source: IBM NLS RM Vol2 SE09-8002-01, March 1990 &alias CP500 &alias ebcdic-cp-be &alias ebcdic-cp-ch > Obviously I could just knock up a 255 character lookup table and do it > myself, I was just trying to be a little more Pythonic and use that > built in table. It's pythonic to implement a Unicode codec for unknown character tables. I've put these two on my web site: http://www.stroeder.com/pylib/encodings/ebcdicatde.py http://www.stroeder.com/pylib/encodings/cp273.py (needs ebcdicatde) Ciao, Michael. From ranjith.priya at gmail.com Fri Dec 19 01:12:55 2008 From: ranjith.priya at gmail.com (Priya Ranjith) Date: Thu, 18 Dec 2008 22:12:55 -0800 (PST) Subject: Openings for Release Management Message-ID: <988ff2f1-b4f3-460f-b087-2406cc6baa41@w1g2000prk.googlegroups.com> Position: Build and Release Engineer Experience Required: 2 - 7 yrs Qualification: B.E/M.E/M.C.A/B.Tech Skills Required: 1) Working experience in distributed version control system like Mercurial / Bazar / GIT or Subversion 2) Experience in RBuilder 3) Working experience in creating software appliance. 4) Experience in Python 5) Working experience in Ant / Maven 6) Should posses good communication skills: excellent English, both written and spoken is a must. 7) High level of professionalism The Release Engineer function has the following key areas of responsibility: 1) Continuous improvement of Release processes, methodologies and tools to ensure best quality for both product lines: Community Edition and Professional Edition. 2) Track and support the whole Release cycle, coordinating teams involved in the Release processes: engineering, QA, Beta Testers and Community. 3) Keep people informed about status, contents, dates, etc. 4) Support Senior Management to define the guidelines of whole release product strategy. From ldo at geek-central.gen.new_zealand Thu Dec 4 17:57:34 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 05 Dec 2008 11:57:34 +1300 Subject: Don't you just love writing this sort of thing :) References: Message-ID: In message , Duncan Booth wrote: > Have you ever considered trying to write readable code instead? > > (I must admit I haven't checked whether GZipFile works with the 'with' > statement... That's why I prefer writing _correct_ code instead. From pavlovevidence at gmail.com Mon Dec 15 14:53:40 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 15 Dec 2008 11:53:40 -0800 (PST) Subject: alt.possessive.its.has.no.apostrophe References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> Message-ID: <4f36bf19-40f2-4e88-8867-18a760000120@u18g2000pro.googlegroups.com> On Dec 15, 1:55?am, Ben Finney wrote: > James Stroud writes: > > Ben Finney wrote: > > > James Stroud writes: > > > >> Yes. I think it was the British who decided that the apostrophe > > >> rule for "it" would be reversed from normal usage relative to > > >> just about every other noun. > > It also seems an indefensible claim to say that anyone ?decided? it > would be that way, especially ?the British?. > > > > Remember that ?it? is a pronoun. I see no reversal: > > > Ok. Pronouns are reversed. > > Or, more generally: Pronouns, which are different in just about every > other way from other nouns, are different in this way also. Is that > about right? No. Most pronouns form their possessives the same way nouns do. E.g.: Someone's hat is over there. One does with one's hand whatever one pleases. Whoever's shoes are downstairs better get them. The computer that's power is still on is wasting energy. The seven personal pronouns and "who" are the only words to form their possessives irregularly. However "it" and "who" *pronounce* their possessives exactly as nouns do. They just spell them differently, for no really good reason. The way I see it, if the rule had been, "Use an apostrophe for any word that forms it's possessive by adding an s or z sound", it would have been less inconsistent. Sadly, that's not the rule. English spelling is the Perl of orthography. Carl Banks (...For that matter, if the rule had been, "Never augment your words spelling with an apostrophe", it would have really simplified things....) From google at mrabarnett.plus.com Sat Dec 20 21:21:36 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 21 Dec 2008 02:21:36 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> <88a122de-14c6-4025-b36c-9a39bdd50d86@i20g2000prf.googlegroups.com> Message-ID: <494DA830.1040502@mrabarnett.plus.com> bearophileHUGS at lycos.com wrote: > walterbyrd: >> As I understand it, that may have been true at one time. But, Ruby 1.9 >> very significantly sped up the language. While Python has been made >> slower, Ruby has been made much faster. > > I have already answered regarding Python3 in this thread. Regarding > Ruby you are right, in computer science there are lot of ways to speed > up things. So it may be quite possible for Ruby to become "faster" > than CPython. > For example this may speed up the PythonVM some: > "Optimizing direct threaded code by selective inlining": > http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.8829&rep=rep1&type=pdf > Interesting. The re module uses a form of bytecode. Not sure about the relative cost of the dispatch code, though. From __peter__ at web.de Mon Dec 8 06:05:47 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 08 Dec 2008 12:05:47 +0100 Subject: Determining whether a variable is less/greater than a range. References: <362ab93b-b804-4ebe-a22f-e422feb301c8@c1g2000yqg.googlegroups.com> Message-ID: simonharrison.uk at googlemail.com wrote: > Hi. I'm having another go at learning Python so I'll probably be > asking a few basic questions. Here is the first one. > > a = list(range(10, 21) > > b = 9 > > c = 21 > > How can I find out if b and c have values less or more than the values > in list a? >>> a = range(10, 21) >>> b = 9 >>> c = 21 Are there any items in a that are less than b or greater than c? >>> any(xc for x in a) False No. Are there any items in a that are greater than b? >>> any(x>b for x in a) True Yes. Peter From zaz600 at gmail.com Wed Dec 24 04:46:30 2008 From: zaz600 at gmail.com (NoName) Date: Wed, 24 Dec 2008 01:46:30 -0800 (PST) Subject: SyntaxError: encoding problem: with BOM Message-ID: i have 1.py in cp866 encoding: # -*- coding: cp866 -*- print ("ff") It's not work in Python 3.0 Error: File "", line 1 SyntaxError: encoding problem: with BOM what's wrong? From youcancallmeal at gmail.com Fri Dec 19 14:03:09 2008 From: youcancallmeal at gmail.com (youcancallmeal at gmail.com) Date: Fri, 19 Dec 2008 11:03:09 -0800 (PST) Subject: Segmentation fault in PyObjectMalloc on FreeBSD Message-ID: <2c36470f-8dff-4fcd-9e86-3abcc01e4c49@s9g2000prm.googlegroups.com> I have a multithreaded python app running on FreeBSD (both 7.0 and 6.3) that crashes with a segmentation fault coming from PyObjectMalloc. This first happened using Python 2.5 built from Ports. I then pulled down r261 from Subversion and built that so I would have debugging symbols; it still crashed. Below is a back trace from gdb: #0 PyObject_Malloc (nbytes=2) at Objects/obmalloc.c:758 #1 0x080942aa in PyString_FromStringAndSize (str=0x0, size=50) at Objects/stringobject.c:83 #2 0x0809b30b in PyString_FromFormatV (format=0x813c6d4 "%.50s instance has no attribute '%.400s'", vargs=0xbf6fa048 "??.\b?Q\031\b??>\b") at Objects/stringobject.c: 238 #3 0x080dcd48 in PyErr_Format (exception=0x8158660, format=0x813c6d4 "%.50s instance has no attribute '%.400s'") at Python/errors.c:538 #4 0x08064549 in instance_getattr1 (inst=0x833ed4c, name=0x81951b0) at Objects/classobject.c:717 #5 0x08067c9f in instance_nonzero (self=0x833ed4c) at Objects/ classobject.c:754 #6 0x0808a592 in PyObject_IsTrue (v=0x8473000) at Objects/object.c: 1532 #7 0x080cb6d3 in PyEval_EvalFrameEx (f=0x857860c, throwflag=0) at Python/ceval.c:2173 #8 0x080cef5d in PyEval_EvalFrameEx (f=0x8574e0c, throwflag=0) at Python/ceval.c:3765 #9 0x080cef5d in PyEval_EvalFrameEx (f=0x856980c, throwflag=0) at Python/ceval.c:3765 #10 0x080cfbe8 in PyEval_EvalCodeEx (co=0x82f7218, globals=0x49, locals=0x815dd40, args=0x819402c, argcount=4, kws=0x83a99a0, kwcount=0, defs=0x833e758, defcount=2, closure=0x0) at Python/ ceval.c:2942 #11 0x08124260 in function_call (func=0x83408b4, arg=0x846ee64, kw=0x845546c) at Objects/funcobject.c:524 #12 0x08060402 in PyObject_Call (func=0x83408b4, arg=0x846ee64, kw=0x845546c) at Objects/abstract.c:2487 #13 0x080cbdbc in PyEval_EvalFrameEx (f=0x856dc0c, throwflag=0) at Python/ceval.c:3978 #14 0x080cfbe8 in PyEval_EvalCodeEx (co=0x82f6cc8, globals=0x49, locals=0x815dd40, args=0x819402c, argcount=2, kws=0x8572154, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c: 2942 #15 0x080cdbda in PyEval_EvalFrameEx (f=0x857200c, throwflag=0) at Python/ceval.c:3774 #16 0x080cef5d in PyEval_EvalFrameEx (f=0x850860c, throwflag=0) at Python/ceval.c:3765 #17 0x080cef5d in PyEval_EvalFrameEx (f=0x850940c, throwflag=0) at Python/ceval.c:3765 #18 0x080cef5d in PyEval_EvalFrameEx (f=0x857680c, throwflag=0) at Python/ceval.c:3765 #19 0x080cfbe8 in PyEval_EvalCodeEx (co=0x83c5f50, globals=0x49, locals=0x815dd40, args=0x819402c, argcount=2, kws=0x8506364, kwcount=0, defs=0x83d1c78, defcount=1, closure=0x0) at Python/ ceval.c:2942 #20 0x080cdbda in PyEval_EvalFrameEx (f=0x850620c, throwflag=0) at Python/ceval.c:3774 #21 0x080cef5d in PyEval_EvalFrameEx (f=0x850980c, throwflag=0) at Python/ceval.c:3765 #22 0x080cef5d in PyEval_EvalFrameEx (f=0x84efa0c, throwflag=0) at Python/ceval.c:3765 #23 0x080cef5d in PyEval_EvalFrameEx (f=0x84ef80c, throwflag=0) at Python/ceval.c:3765 #24 0x080cef5d in PyEval_EvalFrameEx (f=0x84ef60c, throwflag=0) at Python/ceval.c:3765 #25 0x080cef5d in PyEval_EvalFrameEx (f=0x84ef40c, throwflag=0) at Python/ceval.c:3765 #26 0x080cef5d in PyEval_EvalFrameEx (f=0x84ef20c, throwflag=0) at Python/ceval.c:3765 #27 0x080cfbe8 in PyEval_EvalCodeEx (co=0x82cdf98, globals=0x49, locals=0x815dd40, args=0x819402c, argcount=1, kws=0x0, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2942 #28 0x08124260 in function_call (func=0x82e8b8c, arg=0x8471dec, kw=0x0) at Objects/funcobject.c:524 #29 0x08060402 in PyObject_Call (func=0x82e8b8c, arg=0x8471dec, kw=0x0) at Objects/abstract.c:2487 #30 0x08069bed in instancemethod_call (func=0x49, arg=0x8471dec, kw=0x0) at Objects/classobject.c:2579 #31 0x08060402 in PyObject_Call (func=0x83e8a7c, arg=0x819402c, kw=0x0) at Objects/abstract.c:2487 #32 0x080c87da in PyEval_CallObjectWithKeywords (func=0x83e8a7c, arg=0x819402c, kw=0x0) at Python/ceval.c:3548 #33 0x080fccdd in t_bootstrap (boot_raw=0x83a9910) at ./Modules/ threadmodule.c:425 #34 0x281b05cf in pthread_create () from /usr/lib/libthr.so.2 #35 0x00000000 in ?? () This part is particularly interesting: (gdb) frame 1 #1 0x080942aa in PyString_FromStringAndSize (str=0x0, size=50) at Objects/stringobject.c:83 83 op = (PyStringObject *)PyObject_MALLOC(sizeof (PyStringObject) + size); (gdb) print size $7 = 50 (gdb) print sizeof(PyStringObject) $8 = 24 (gdb) frame 0 #0 PyObject_Malloc (nbytes=2) at Objects/obmalloc.c:758 758 if ((pool->freeblock = *(block **)bp) ! = NULL) { (gdb) print nbytes $9 = 2 So 50 + 24 == 2? Or am I missing something? Can anyone suggest how to figure out what's really going on here? From rt8396 at gmail.com Mon Dec 22 22:38:29 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 19:38:29 -0800 (PST) Subject: iterating initalizations References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> Message-ID: <73f58305-b7f3-4536-b193-79d66d68d6f7@t3g2000yqa.googlegroups.com> >>> class test(): def __init__(self, name): self.name = 'My name is %d' %name >>> l = [] >>> for name in range(10): l.append(test(name)) >>> l [<__main__.test instance at 0x02852E18>, <__main__.test instance at 0x02852C38>, <__main__.test instance at 0x028528A0>, <__main__.test instance at 0x02852E90>, <__main__.test instance at 0x02852EE0>, <__main__.test instance at 0x02852F30>, <__main__.test instance at 0x02852F80>, <__main__.test instance at 0x02852FD0>, <__main__.test instance at 0x023AFC60>, <__main__.test instance at 0x02855030>] >>> l[0].name 'My name is 0' >>> l[1].name 'My name is 1' From steve at REMOVE-THIS-cybersource.com.au Sun Dec 21 05:14:24 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Dec 2008 10:14:24 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: <015e0e47$0$20656$c3e8da3@news.astraweb.com> On Sun, 21 Dec 2008 00:57:46 -0800, Patrick Mullen wrote: > 2) In my experience, major version changes tend to be slower than > before. When a lot of things change, especially if very low-level > things change, as happened in python 3.0, the new code has not yet went > through many years of revision and optimization that the old code has. I was around for the change from Python 1.5 -> 2.x. By memory, I skipped a couple of versions... I think I didn't make the move until Python 2.2 or 2.3 was released. Python 2.0 was significantly slower than 1.5 in a number of critical areas, but not for long. Actually, it's quite possible that Python 1.5 is still faster than Python 2.x in some areas -- but of course it misses a lot of features, and at the end of the day, the difference between your script completing in 0.03 seconds or in 0.06 seconds is meaningless. > In my opinion, python 3 was rushed out the door a bit. It could have > done with a few more months of optimization and polishing. However, on > the other hand, it is going to take so long for python infrastructure to > convert to python 3, that an earlier release makes sense, even if it > hasn't been excessively polished. The biggest reason for the speed > change is the rewritten stdio and unicode-everything. Hopefully this > stuff can be improved in future updates. I don't think anyone WANTS > cpython to be slower. I understand that the 3.0.1 release due out around Christmas will have some major speed-ups in stdio. -- Steven From jerry.carl.mi at gmail.com Sun Dec 28 10:55:24 2008 From: jerry.carl.mi at gmail.com (jerry.carl.mi at gmail.com) Date: Sun, 28 Dec 2008 07:55:24 -0800 (PST) Subject: math module for Decimals References: <41937dc9-4b67-43b5-9eab-6f8c851474cf@p2g2000prn.googlegroups.com> Message-ID: > - are you using Decimal for the base-10-ness or the > ? extra precision Decimal provides? ?Or significant zeros? > ? Or compatibility with existing Decimal code, or what? Oh boy, now I will finally prove myself illiterate... well, so be it. But i am after the extra precision: >>> from math import * >>> (1+1e-16)-1 0.0 ...in this trivial example above I will lose the 1e-16... which may be an issue if you code something that evaluates slightly more complex expressions. I would feel much more comfortable if I lose 1e-60. But in physics, one can get parts of an expression equal to 1e-16 while (by mistake or not) other parts are > 1. Hence it becomes a greater puzzle to debug the calculation. Having the possibility to increase precision would help. Sure, you can say, there is such a small market for this application, and maybe I should use other tools. Well, I found Python so much easier to use for other reasons. And, again, it seems like there is a desire for it outside of my own office. > - what 3 functions would you most like to see added? > ? For me, I think it would be something like sin, cos > ? and atan (or possibly atan2). ?Once you've got those > ? three, everything else is fairly easy. ?In particular, > ? atan/atan2 at least gives you access to pi. Agree: sin, cos and atan would do it. > FWIW, I'm the author of the current Decimal log, log10, exp > and pow functions, so I'm probably in a fairly good position > to try to implement reasonably high-quality versions of some > other elementary functions (again, just as an external > addition to the decimal module, not as part of the decimal > module itself). ?This is an itch I've often wanted > scratched, as well. ?I might just have a go.... > (Help in the form of code, tests, suggestions, etc. > would be welcome!) > > Mark Wow, i would never think my posting would go that high in the Python world. I can't wait to tell my colleagues after these holidays ;-) If I improve (in my view that is) the existing modules (dmath) etc. i will keep you posted. For now I am reducing large arguments of goniometric functions by adding the following into the dmath's sin(x) and cos(x): x=Decimal.__mod__(x,Decimal('2')*pi()) Works fine for what i need, but i am sure it's not the right way to do it. Thanks Mark! From sumerc at gmail.com Mon Dec 29 05:17:42 2008 From: sumerc at gmail.com (k3xji) Date: Mon, 29 Dec 2008 02:17:42 -0800 (PST) Subject: Read-Write Lock vs primitive Lock() References: Message-ID: <277c1be7-2560-4fd6-9610-0b4398dc3719@x16g2000prn.googlegroups.com> On 29 Aral?k, 11:52, "Gabriel Genellina" wrote: > En Mon, 29 Dec 2008 05:56:10 -0200, k3xji escribi?: > > > I ?am trying to see on which situations does the Read-Write Lock > > performs better on primitive Lock() itself. Below is the code I am > > using to test the performance: > > import threading > > import locks > > import time > > > class mylock(object): > > (I'm not convinced your lock is correct) No problem.:) > > GLOBAL_VAR = 1 > > #GLOBAL_LOCK = locks.ReadWriteLock() > > GLOBAL_LOCK = threading.Lock() > > #GLOBAL_LOCK = mylock() > > GLOBAL_LOOP_COUNT = 100000 > > GLOBAL_READER_COUNT = 1000 > > GLOBAL_WRITER_COUNT = 1 > > Only one writer? If this is always the case, you don't need a lock at all. No just used for testing. It does not matter, what I want to see is that I want to create a botleneck on readers. > > class wthread(threading.Thread): > > ? ? def run(self): > > ? ? ? ? ? ? try: > > ? ? ? ? ? ? ? ? #GLOBAL_LOCK.acquireWrite() > > ? ? ? ? ? ? ? ? #GLOBAL_LOCK.acquire_write() > > ? ? ? ? ? ? ? ? GLOBAL_LOCK.acquire() > > ? ? ? ? ? ? ? ? for i in range(GLOBAL_LOOP_COUNT): > > ? ? ? ? ? ? ? ? ? ? GLOBAL_VAR = 4 > > ? ? ? ? ? ? finally: > > ? ? ? ? ? ? ? ? #GLOBAL_LOCK.release_write() > > ? ? ? ? ? ? ? ? GLOBAL_LOCK.release() > > Note that the thread acquires the lock ONCE, repeats several thousand > times an assignment to a *local* variable called GLOBAL_VAR (!), finally > releases the lock and exits. As every thread does the same, they just run > one after another, they never have a significant overlap. If I put the for loop outside, in that case, readers will not overlap at all, and you would be amazed by the numbers for that test. They indicate primitive lock is faster than read-write lock, as it requires the lock, executes only one bytecode operation and releases the lock. So, in order to create a bottlenneck on readers, we need to somehow do not release the lock immediately. > Also, you should acquire the lock *before* the try block (you have to > ensure that, *after* acquiring the lock, it is always released; such > requisite does not apply *before* acquiring the lock) Yeah, you are right but it is irrelevant. > I'd test again with something like this: > > class wthread(threading.Thread): > ? ? ? def run(self): > ? ? ? ? ? global GLOBAL_VAR > ? ? ? ? ? for i in xrange(GLOBAL_LOOP_COUNT): > ? ? ? ? ? ? ? GLOBAL_LOCK.acquire() > ? ? ? ? ? ? ? try: > ? ? ? ? ? ? ? ? ? GLOBAL_VAR += 1 > ? ? ? ? ? ? ? finally: > ? ? ? ? ? ? ? ? ? GLOBAL_LOCK.release() With that, primitive locks perform 10 times better than Read-Write lock. See above. > > class rthread(threading.Thread): > > ? ? def run(self): > > ? ? ? ? ? ? try: > > ? ? ? ? ? ? ? ? #GLOBAL_LOCK.acquireRead() > > ? ? ? ? ? ? ? ? #GLOBAL_LOCK.acquire_read() > > ? ? ? ? ? ? ? ? GLOBAL_LOCK.acquire() > > ? ? ? ? ? ? ? ? for i in range(GLOBAL_LOOP_COUNT): > > ? ? ? ? ? ? ? ? ? ? GLOBAL_VAR = 3 > > ? ? ? ? ? ? finally: > > ? ? ? ? ? ? ? ? #GLOBAL_LOCK.release_read() > > ? ? ? ? ? ? ? ? GLOBAL_LOCK.release() > > Hmmm, it's a reader but attempts to modify the value? > You don't have to protect a read operation on a global variable - so a > lock isn't required here. This is just for testing. Suppose that I am actually reading the value. I don't understand why a lock is not required? Are you saying lock is not necesary beacuse GLOBAL_VALUE is an immutable object, if then, suppose it is not. This is just a test. Suppose GLOBAl_VAR is a list and we are calling append() on it which is nt an atomic operation. > > What I am doing is: I am creating multiple readers and try to do > > something. I had assumed that with using primitive Lock() on the above > > situation, it will create a bottleneck on the rthreads. But the > > numbers indicate that there are no difference at all. I had > > implemented my own READ-WRIET lock as can be seen above mylock and > > also used the one here: code.activestate.com/recipes/502283/. > > I hope you now understand why you got the same numbers always. Unfortunately, I do not understand anyhing. Thanks. From bearophileHUGS at lycos.com Sat Dec 13 09:13:20 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 13 Dec 2008 06:13:20 -0800 (PST) Subject: Shorter tracebacks Message-ID: When I write recursive code in Python I sometimes go past the maximum allowed stack depth, so I receive a really long traceback. The show of such traceback on my screen is very slow (despite a CPU able to perform billions of operations each second). So I think I'd like something to shorten them. I am thinking about something like: from __future__ import short_traceback That allows me to see only the first and last parts of the stack trace, and skips the (generally very redundant) middle part. Note that generally using sys.setrecursionlimit(limit) to set a smaller limit isn't good, because I may need a big depth anyway. Bye, bearophile From renesd at gmail.com Sun Dec 7 23:26:36 2008 From: renesd at gmail.com (illume) Date: Sun, 7 Dec 2008 20:26:36 -0800 (PST) Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? References: <5ccd4a18-cd2b-4040-90c6-33723af15e96@b38g2000prf.googlegroups.com> Message-ID: hello, PyOpenGL also has a raw module which includes python bindings closer to the C calls... however mostly you want to use the nicer more pythonic versions of functions. Recent pyopengl 3.x versions have been optimized for speed, including optional C level optimizations. So I imagine they are faster than pyglets wrappers(profiling/testing needed). PyOpenGL is also used a lot more by non-game people, so a wider array of functions are used. It's very unfortunate that pyglet and pyopengl don't share code... however recent versions of pyopengl tried to reuse some of pyglets code... not sure how much has been shared though. Maybe at some point they will come together. For now pyglet has created a fork in the python+opengl community, where the same code can't be reused automatically between the two as the opengl wrappers are slightly different. However it's not terribly difficult to port code from one to the other, as some projects have done. pygame doesn't require opengl be supported by the video card - it can use many different video drivers to get the job done. It's nice to be able to avoid using the 3D parts of gfx cards if you can - to reduce power consumption, and make your game run on more computers. pygame is also much more portable, has more people using it, has more developers, and a stable API. Code you wrote 5 years ago will most likely still work. Code you wrote for older versions of pyglet will not work without changes. pygame is simpler to learn, since it doesn't require you to know how to create classes or functions. Whereas pyglet requires you to sub class to do anything. http://pygame.org/wiki/about * disclaimer - I'm a pygame developer, and have in the past contributed to pyopengl - so obviously I prefer pygame and pyopengl. On Dec 8, 12:53?pm, alex23 wrote: > On Dec 8, 11:23?am, excor... at gmail.com wrote: > > > Does pyglet use PyOpenGL as its OpenGL wrapper? If not, any idea why? > > Seems like it would be a fairly substantial duplication of effort. > > Taken from:http://groups.google.com/group/pyglet-users/msg/832b15389fccd28d > > > > >> IIRC pyglet tries to minimize dependencies, so PyOpenGL won't be > >> used. ?However, pyglet's wrapping of OpenGL isn't meant to be > >> complete; it's only what pyglet itself uses. ?You'll need to use > >> PyOpenGL for the rest. > > That was more or less the original plan. ?pyglet wraps OpenGL at the > > lowest level, so it only provides glVertex3f, glVertex2d, etc., > > whereas PyOpenGL also provides polymorphic functions such as glVertex. > [...] > > pyglet provides all of the error-checking functionalities that > > PyOpenGL does (though these can be disabled for performance). ?At > > last check, pyglet was significantly faster than PyOpenGL 3, but > > slower than PyOpenGL 2. > > From Tribulations at Paralleles.invalid Tue Dec 2 09:09:53 2008 From: Tribulations at Paralleles.invalid (TP) Date: Tue, 02 Dec 2008 15:09:53 +0100 Subject: best way to do this Message-ID: Hi everybody, >>> c=[(5,3), (6,8)] >From c, I want to obtain a list with 5,3,6, and 8, in any order. I do this: >>> [i for (i,j) in c] + [ j for (i,j) in c] [5, 6, 3, 8] Is there a quicker way to do this? Thanks Julien -- python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z (55l4('])" "When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong." (first law of AC Clarke) From steve at REMOVE-THIS-cybersource.com.au Sat Dec 13 22:16:19 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Dec 2008 03:16:19 GMT Subject: [OT] stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> Message-ID: <01547201$0$6988$c3e8da3@news.astraweb.com> On Sat, 13 Dec 2008 19:17:41 +0000, Duncan Booth wrote: > I think you must have fallen asleep during CS101. The lower bound for > sorting where you make a two way branch at each step is O(n * log_2 n), > but if you can choose between k possible orderings in a single > comparison you can get O(n * log_k n). I think you might have been sleeping through Maths 101 :-) The difference between log_2 N and log_k N is a constant factor (log_2 k) and so doesn't effect the big-oh complexity. -- Steven From eckhardt at satorlaser.com Thu Dec 4 11:43:34 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 04 Dec 2008 17:43:34 +0100 Subject: EBCDIC <--> ASCII References: <091f0404-2be3-4bda-8619-03627bd03fdc@k8g2000yqn.googlegroups.com> Message-ID: martinjamesevans at gmail.com wrote: > I've tried starting with something like this, but I assume it is > expecting the source to be in unicode already? > > e.g. (pretend the second half are EBCDIC characters) > > sAll = "This bit is ASCII, " Why pretend? You can use this: "abcde\x81\x82\x83\x84" > sSource = sAll[19:] > > sEBCDIC = unicode(sSource, 'cp500', 'ignore') If you mean this sSource, then no. sSource is treated as byte string here which is converted to Unicode using 'cp500' as encoding. Note that in interactive mode, 'print x' will actually convert the string according to stdout's current encoding (typically ASCII or - I think - Latin 1). s1 = u'abcde' s2 = s1.encode('cp500') s3 = s1.encode('ascii') s4 = unicode( s2, 'cp500') s5 = unicode( s3, 'ascii') Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From rdmurray at bitdance.com Fri Dec 19 23:27:46 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Sat, 20 Dec 2008 04:27:46 +0000 (UTC) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c4ef2$0$20656$c3e8da3@news.astraweb.com> Message-ID: Quoth Steven D'Aprano : > Whether using % or format(), I don't see the need to change the code, > only the strings. > > Using positional arguments is not really that different: > > "{0} {1}".format("dead", "parrot") > "{0} {1}".format("perroquet", "mort") This should be something like: _("{0} {1}").format(_("dead"), _("parrot")) where il8n would substitute the template "{1} {0}" when doing French. > versus: > > "%s %s" % ("dead", "parrot") > "%s %s" % ("perroquet", "mort") > > In this case, the template on the left remains the same, you just have to > reorder the string arguments on the right. Clearly less satisfactory than > the solution using keyword substitution, but whatever solution you pick, > I don't see any advantage to format() over % formatting. Can you show an > example? Not less satisfactory, but rather unworkable. You can't do proper il8n with %s formatting, since there is no way for the il8n machinery to reorder the argument tuple. It can only translate the template string. So when doing il8n, the {} syntax wins out for brevity over the equivalent % syntax (%s(somename)s). Not that brevity is that important an argument. The new system is just so much more flexible than the old. As someone else said, the design is beautiful :) I have a couple thousand lines of python code I wrote a while back to layer on a system with this kind of flexibility...I was shocked and pleased when I saw the PEP, since it echoed so many of the ideas I had implemented in that code, plus more. And all done better of course :) --RDM From steve at REMOVE-THIS-cybersource.com.au Tue Dec 16 20:26:58 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 17 Dec 2008 01:26:58 GMT Subject: Does Python3 offer a FrozenDict? References: Message-ID: <01584ccb$0$20656$c3e8da3@news.astraweb.com> On Tue, 16 Dec 2008 17:59:30 +0100, Johannes Bauer wrote: > Hello group, > > is there anything like a frozen dict in Python3, so I could do a > > foo = { FrozenDict({"a" : "b"}): 3 } > > or something like that? If *all* you want is to use it as a key, then: tuple(sorted(some_dict.items)) may do the job. -- Steven From aahz at pythoncraft.com Sat Dec 6 12:24:36 2008 From: aahz at pythoncraft.com (Aahz) Date: 6 Dec 2008 09:24:36 -0800 Subject: Learning Python now coming from Perl References: Message-ID: In article , Bertilo Wennergren wrote: > >I don't suppose there is any introductory material out there that is >based on Python 3000 and that is also geared at people with a Perl >background? Too early for that I guess.. Honestly, the differences between 2.x and 3.0 are small enough that it doesn't much matter, as long as you're not the kind of person who gets put off by little problems. Because so much material is for 2.x, you may be better off just learning 2.x first and then moving to 3.x. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From simonharrison.uk at googlemail.com Mon Dec 8 08:32:06 2008 From: simonharrison.uk at googlemail.com (simonh) Date: Mon, 8 Dec 2008 05:32:06 -0800 (PST) Subject: Beginner trying to understand functions. Message-ID: In my attempt to learn Python I'm writing a small (useless) program to help me understand the various concepts. I'm going to add to this as I learn to serve as a single place to see how something works, hopefully. Here is the first approach: name = input('Please enter your name: ') print('Hello', name) while True: try: age = int(input('Please enter your age: ')) break except ValueError: print('That was not a valid number. Please try again.') permitted = list(range(18, 31)) if age in permitted: print('Come on in!') elif age < min(permitted): print('Sorry, too young.') elif age > max(permitted): print('Sorry, too old.') input('Press any key to exit.') That works fine. Then I've tried to use functions instead. The first two work fine, the third fails: def getName(): name = input('Please enter your name: ') print('Hello', name) def getAge(): while True: try: age = int(input('Please enter your age: ')) break except ValueError: print('That was not a valid number. Please try again.') def checkAge(): permitted = list(range(18, 31)) if age in permitted: print('Come on in!') elif age < min(permitted): print('Sorry, too young.') elif age > max(permitted): print('Sorry, too old.') getName() getAge() checkAge() I get this error message: NameError: global name 'age' is not defined. I'm stuck, can someone help? Thanks. From tjreedy at udel.edu Wed Dec 24 18:38:12 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 24 Dec 2008 18:38:12 -0500 Subject: Strategy for determing difference between 2 very large dictionaries In-Reply-To: <6rea9hF16p8tU1@mid.uni-berlin.de> References: <1230102996.2303.1291616055@webmail.messagingengine.com> <6rea9hF16p8tU1@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Wed, 24 Dec 2008 03:23:00 -0500, python wrote: >> collection, I don't see the advantage of using an iterator or a list. >> I'm sure I'm missing a subtle point here :) > > `keys()` creates a list in memory, `iterkeys()` does not. With > ``set(dict.keys())`` there is a point in time where the dictionary, the > list, and the set co-exist in memory. With ``set(dict.iterkeys())`` only > the set and the dictionary exist in memory. If you can, consider using 3.0 in which d.keys() is a set-like view of the keys of d. Same for d.values and d.items. The time and space to create such is O(1), I believe. since they are just alternate read-only interfaces to the internal dict storage. There is not even a separate set until you do something like intersect d1.keys() with d2.keys() or d1.keys() - d2.keys(). I think this is an under-appreciated feature of 3.0 which should be really useful with large dicts. tjr From Slaunger at gmail.com Tue Dec 2 06:01:08 2008 From: Slaunger at gmail.com (Slaunger) Date: Tue, 2 Dec 2008 03:01:08 -0800 (PST) Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> Message-ID: <258cf433-f6c9-43e7-a235-f5f6b2b6433f@j39g2000yqn.googlegroups.com> On 2 Dec., 11:30, Nick Craig-Wood wrote: > > For 4 attributes I'd probably go with the __getattr__. > OK, I'll do that! > Or you could easily write your own decorator to cache the result... > > Eghttp://code.activestate.com/recipes/363602/ Cool. I never realized I could write my own decorators! I've so far only used them for @classmethod, @staticmethod and stuff like that. User defined decorators are nice and fun to do as well. I just hope it will be understandable in four years also... > > > ?With the property methology you do the value check on each get, which > > ?does not look as "clean". The property methology is also a little less > > ?arcane I guess for less experienced Python programmers to understand > > ?when re-reading the code. > > Less magic is how I would put it. ?Magic is fun to write, but a pain > to come back to. ?Over the years I find I try to avoid magic more and > more in python. > Ah, I see. I hope you do not consider user defined decorators "magic" then? ;-) > > ?What kind of trouble are you referring to in __getattr__? Is it > > ?recursive calls to the method on accessing object attributes in that > > ?method itself or other complications? > > Every time I write a __getattr__ I get tripped up by infinite > recursion! ?It is probably just me ;-) > And I will probably end up having the same initial problems, but I found an example here, which I may try to be inspired from. http://western-skies.blogspot.com/2008/02/complete-example-of-getattr-in-python.html > > ?On a related issue, thank you for showing me how to use @property as a > > ?decorator - I was not aware of that possibility, just gotta understand > > ?how to decorate a setter and delete method as well, but I should be > > ?able to look that up by myself... > > I'm sure you will! > > http://www.python.org/doc/2.5.2/lib/built-in-funcs.html > Yeah, I just visited that page yesterday! Again, thank you for your assistance, Nick! -- Slaunger From andrew.replogle at gmail.com Tue Dec 16 13:30:48 2008 From: andrew.replogle at gmail.com (Andrew) Date: Tue, 16 Dec 2008 10:30:48 -0800 (PST) Subject: subprocess returncode windows Message-ID: Hello, I'm running into a strange situation with getting incorrect returncodes / exit status from python subprocess.call. I'm using a python script (runtime 2.6.1 on windows) to automate the deploy of java applications to glassfish application server. Below is an example of using a subprocess call to test the success / failure of the glassfish CLI tool "asadmin" Example.py: ---------------------- import sys from subprocess import * try: retcode = call("c:/glassfish/bin/asadmin.bat " + "list-system- properties --host mydomain --port 4848 --user admin server-01", shell=True) if retcode < 0: print >>sys.stderr, "Child was terminated by signal", -retcode else: print >>sys.stderr, "Child returned", retcode except OSError, e: print >>sys.stderr, "Execution failed:", e ---------------------- However, when I execute it, it gets the same returncode whether it fails or succeeds (0). --------------------- C:\>python z:\bin\example.py Please enter the admin password> ***Enters Good Password*** IIOP_SSL_MUTUALAUTH_PORT=33920 JMX_SYSTEM_CONNECTOR_PORT=38686 IIOP_LISTENER_PORT=33700 IIOP_SSL_LISTENER_PORT=33820 HTTP_LISTENER_PORT=38080 AJP_INSTANCE_NAME=WebReporting-01 HTTP_SSL_LISTENER_PORT=38181 JMS_PROVIDER_PORT=37676 AJP_PORT=18009 Command list-system-properties executed successfully. Child returned 0 C:\>python z:\bin\example.py Please enter the admin password>***Enters BAD PASSWORD*** Invalid user or password CLI137 Command list-system-properties failed. Child returned 0 C:\> ------------------------------------------------ When I execute this manually from the cmd.exe and I check the %errorlevel% it returns the correct levels: ----------------------------------------------- C:\>c:\glassfish\bin\asadmin.bat list-system-properties --host mydomain --port 4848 --user admin server-01 Please enter the admin password>***GOOD PASSWORD*** IIOP_SSL_MUTUALAUTH_PORT=33920 JMX_SYSTEM_CONNECTOR_PORT=38686 IIOP_LISTENER_PORT=33700 IIOP_SSL_LISTENER_PORT=33820 HTTP_LISTENER_PORT=38080 AJP_INSTANCE_NAME=WebReporting-01 HTTP_SSL_LISTENER_PORT=38181 JMS_PROVIDER_PORT=37676 AJP_PORT=18009 Command list-system-properties executed successfully. C:\>echo %errorlevel% 0 C:\>c:\glassfish\bin\asadmin.bat list-system-properties --host mydomain --port 4848 --user admin server-01 Please enter the admin password>***BAD PASSWORD*** Invalid user or password CLI137 Command list-system-properties failed. C:\>echo %errorlevel% 1 C:\> ------------------------------------- I'm guessing that returncode isn't the same thing as exit status? Is there a way to get exit status using a subprocess function instead of returncode? Is this the right way to go about this? Thanks for any direction / advice you can provide. Andrew From gagsl-py2 at yahoo.com.ar Mon Dec 29 00:40:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Dec 2008 03:40:41 -0200 Subject: tkinter 3.0 multiple keyboard events together References: <600d4b68-6fe2-4c2c-b425-1a739430bb54@s9g2000prg.googlegroups.com> <7b5e466c-d75d-4e71-b559-f8a0d3718094@r15g2000prd.googlegroups.com> <49573C28.6000808@post.cz> Message-ID: En Sun, 28 Dec 2008 06:43:20 -0200, Pavel Kosina escribi?: > well, I am working on a tutorial for youngster (thats why i need to stay > the code as easy as possible). In this game you are hunted by robots. I > could use key"7" on numeric keypad for left-up moving but seems to me, > that "4"+"8" is much more standard for them. > [...] > well, I thought that gui?s have such a problem already built-in - so > that i am not pressed to code it. You know, its not exactly about me - > if I do it for myself, for my program, that there is no problem, but I > need to explained it to begginners ..... And I do not want, as might be > more usual, do my module, that would cover this "insanity" (look at it > with 13-years old boy eyes ;-) ). Do you like to say me, that this is > not a standard "function" neither in tkinter, not say gtk or the others, > too? I don't recall any application that handles simultaneous keystrokes. Multiple keystrokes are handled at the library level, but only with regard to the "modifier" keys (shift, control, alt), so the application sees Control-P as a *single* synthesized event instead of four. I'm afraid you'll have to roll your own logic, as your use case isn't very common. Perhaps treat "4" followed by "8" in quick succession the same as a fictional event "48" equivalent to "7". -- Gabriel Genellina From sonynamratha2009 at gmail.com Wed Dec 24 15:34:30 2008 From: sonynamratha2009 at gmail.com (sony) Date: Wed, 24 Dec 2008 12:34:30 -0800 (PST) Subject: music maestro Message-ID: develops extraordinary music and heart touching sequences.To know about him and his works watch www.arrehmanfan.blogspot.com http://arrehmanfan.blogspot.com/2008/12/ar-rahman-on-golden-globe-list.html http://arrehmanfan.blogspot.com/2008/12/listen-to-ar-rahman-ft-mia-from-slumdog.html http://arrehmanfan.blogspot.com/2008/12/i-was-completely-devastated-after.html http://arrehmanfan.blogspot.com/2008/12/aishwarya-abhishek-to-croon-for-r.html http://arrehmanfan.blogspot.com/2008/12/ar-rahman-bags-satellite-award.html http://arrehmanfan.blogspot.com/2008/12/kylie-minogue-to-sing-for-ar-rahman.html http://arrehmanfan.blogspot.com/2008/11/rahman-remixes-choli-ke-peechhey.html http://arrehmanfan.blogspot.com/2008/11/r-rahmans-cricket-connection.html http://arrehmanfan.blogspot.com/2008/11/ar-rahman-tunes-for-maheshs-movie.html http://arrehmanfan.blogspot.com/2008/11/r-rahman-inspires-people-to-vote.html http://arrehmanfan.blogspot.com/2008/11/latest-entries.html http://arrehmanfan.blogspot.com/2008/10/people-speak.html http://arrehmanfan.blogspot.com/2008/10/man-behind-music.html http://arrehmanfan.blogspot.com/2008/10/list-of-r-rahman-awards.html http://arrehmanfan.blogspot.com/2008/10/social-work.html http://arrehmanfan.blogspot.com/2008/10/other-works.html http://arrehmanfan.blogspot.com/2008/10/summary-of-career.html http://arrehmanfan.blogspot.com/2008/10/biography.html http://arrehmanfan.blogspot.com/2008/10/archive.html http://arrehmanfan.blogspot.com/2008/10/r-rahman-phat-phish-launch-big-band.html http://arrehmanfan.blogspot.com/2008/09/profile.html http://arrehmanfan.blogspot.com/2008/09/allah-rakkhha-rahman-tamil.html From sjmachin at lexicon.net Wed Dec 24 20:48:43 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 24 Dec 2008 17:48:43 -0800 (PST) Subject: Strategy for determing difference between 2 very large dictionaries References: <1230102996.2303.1291616055@webmail.messagingengine.com> <1230105750.9108.1291619105@webmail.messagingengine.com> Message-ID: <1c9ab93f-0341-4030-948c-8efdc7417c68@b41g2000pra.googlegroups.com> On Dec 24, 7:04?pm, "Malcolm Greene" wrote: > Hi Roger, > > By very large dictionary, I mean about 25M items per dictionary. Each > item is a simple integer whose value will never exceed 2^15. In Python-speak about dictionaries, an "item" is a tuple (key, value). I presume from the gross difference between 25M and 2**15 -- more pedantry: 2^15 is 13 :-) -- that you mean that the values satisfy 0 <= value <= 2**15. > > I populate these dictionaries by parsing very large ASCII text files > containing detailed manufacturing events. From each line in my log file > I construct one or more keys and increment the numeric values associated > with these keys using timing info also extracted from each line. > > Some of our log files are generated by separate monitoring equipment > measuring the same process. In theory, these log files should be > identical, but of course they are not. I'm looking for a way to > determine the differences between the 2 dictionaries I will create from > so-called matching sets of log files. You seem to refer to the dictionaries as part of your requirements, not as part of the solution. Do you *need* the two dictionaries after you have obtained the differences? Let's start from the beginning: You have two log files, each of which can be abstracted as containing lots of (k, v) data, where each k describes an event and each v is a compressed 15-bit timestamp. You want to know for each datum whether it is (a) in both files (b) only in file1 (c) only in file2. Is that a fair summary? If so, there's an alternative that doesn't need to use dictionaries. Each file can be represented by a *list* of 32768 sets. Each set contains the ks that happened at the corresponding time... sets[fileno] [v].add(k). Once you've built that, you trundle through the pairs of sets doing set differences etc. Bear in mind that Python dicts and sets grow as required by doubling (IIRC) in size and rehashing from old to new. Consequently you get periodical disturbances which are not usually noticed but may be noticeable with large amounts of data. HTH, John From jpablo.romero at gmail.com Tue Dec 16 19:31:46 2008 From: jpablo.romero at gmail.com (=?ISO-8859-1?Q?Juan_Pablo_Romero_M=E9ndez?=) Date: Tue, 16 Dec 2008 18:31:46 -0600 Subject: eval() and global variables In-Reply-To: References: Message-ID: P 2008/12/16 : > Quoth "=?ISO-8859-1?Q?Juan_Pablo_Romero_M=E9ndez?=" : >> Hello, >> >> Suppose this function is given: >> >> def f(x,y): >> return x+y+k >> >> Is it possible to somehow assign a value to k without resorting to >> making k global? >> >> I'm thinking something like this: >> >> eval("f(1,1)", {"f":f, "k":1}) >> >> Or even better, something like: >> >> def g(k): >> return f >> >> g(1)(1,1) ==> 3 > > >>> def g(k): > ... def f(x,y): > ... return x+y+k > ... return f > ... > >>> g(1)(1,1) > 3 > > But what's the use case? The above might not satisfy it. I'm making a 3D plotting library (yet another!), but with facilities to graph "parametrized" surfaces. The current code is used like this: ... m = Mesh((-1,1),(-1,1)) m.addQuad( lambda v,w, x, y: (x, y, - w * x**2 - v * y**2 ) ) m.addParameter(('v',0,1)) m.addParameter(('w',0,1)) ... Which plots the surface using OpenInventor and add sliders for each parameter. I'm using QTimeLine, so the slider can be animated, and on each step the mesh is recalculated, thus deforming the mesh on real time. What I'd like to do is something like this: ... m = Mesh((-1,1),(-1,1)) m.addQuad( lambda x, y: (x, y, - w * x**2 - v * y**2 ) ) ... and have the code automatically figure out that w and v are free variables and generate the right code. Right now I can catch w and v (using NameError), but can't figure out how to get python to assign values to w and v (other than declaring them globals). My code needs a function g(x,y) which does not depend on w and v. Given this function: func = lambda v,w, x, y: (x, y, - w * x**2 - v * y**2 ) I use functools.partial, as: g = partial(func,1,1) and then use g to actually generate the mesh for each value of v and w. Juan Pablo > > --RDM > > -- > http://mail.python.org/mailman/listinfo/python-list > From prologic at shortcircuit.net.au Fri Dec 12 19:08:45 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Sat, 13 Dec 2008 10:08:45 +1000 Subject: Bidirectional Networking In-Reply-To: <782258db-2bdc-45a7-8d8f-7a036d574985@t26g2000prh.googlegroups.com> References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <6qeht0Fc3541U1@mid.individual.net> <782258db-2bdc-45a7-8d8f-7a036d574985@t26g2000prh.googlegroups.com> Message-ID: Just as a matter of completeness for my own suggestion, here is my implementation of your code (using circuits): cheers James -------------------------- import random from circuits import listener, Event, Manager from circuits.lib.sockets import TCPServer, TCPClient class Server(TCPServer): channel = "server" @listener("read") def onREAD(self, sock, data): print "-> RECV: %s - Sent by: %s" % (data, hsot) class Client(TCPClient): channel = "client" def __init__(self, remoteServer): super(Client, self).__init__() self.cycle = 0 self.randomNumber = 0 self.message = None self.remoteServer = remoteServer @listener("connect") def onCONNECT(self, host, port): self.write(self.message) print "SENT ->: %d by by local cycle %d" % (self.randomNumber, self.cycle) self.close() self.success = True @listener("disconnect") def onDISCONNECT(self): if not self.success: print "Failed to send number on cycle %d " % self.cycle self.success = None @listener("cycle") def onCYCLE(self): if self.cycle < 1000: chance = random.random() if (chance < 0.01): self.randomNumber = int(random.random() * 1000) self.message = "%d from remote cycle %d" % (self.randomNumber, self.cycle) self.open(*self.remoteServer) self.cycle += 1 manager.push(Event(), "cycle", "client") localServer = (9999, "localhost") remoteServer = ("localhost", 10000) manager = Manager() server = Server(*localServer) client = Client(remoteServer) manager += server manager += client manager.push(Event(), "cycle", "client") while True: try: server.poll() client.poll() manager.flush() except KeyboardInterrupt: client.close() break From shangach at gmail.com Fri Dec 5 10:49:38 2008 From: shangach at gmail.com (ShanMayne) Date: Fri, 5 Dec 2008 07:49:38 -0800 (PST) Subject: Switching windows in PyQT References: <9ef85e1f-9e46-48b6-8d11-a4f6e7176657@d23g2000yqc.googlegroups.com> Message-ID: On Dec 3, 8:12 pm, ?????? ??????????? wrote: > > I am new to PyQT and GUI programming in general. What tutorials I have > > found are relatively clear on standard operations within a single > > window (QtGui.QWidget or QtGui.QMainWindow). Exiting this window exits > > the overall application. > > > How would I switch between windows, that is close one and open > > another, within a running application. I would imagine this to be a > > standard feature often coded. > > most often you don't close windows but hide them. > > Still, the app object has a property quitOnLastWindowClosed that you can > set to false. > > -- > ?????? (http://softver.org.mk/damjan/) > > Q: What's tiny and yellow and very, very, dangerous? > A: A canary with the super-user password. Thanks, that does sound like a more accessible way of doing it. Would know where I could find full application code (as an example to me) so that I can get to grips with the details of it all? Good stuff, merry be From nospam at nospam.com Tue Dec 2 18:36:03 2008 From: nospam at nospam.com (John B. Matthews) Date: Tue, 02 Dec 2008 18:36:03 -0500 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: In article , Xah Lee wrote: [...] > > Dr Jon D Harrop, Flying Frog Consultancy Ltd. > > http://www.ffconsultancy.com/ > > [I] clicked your url in Safari and it says ???Warning: Visiting this > site may harm your computer???. Apparantly, your site set[s] browsers to > auto download ???http ://onlinestat. cn /forum/ sploits/ test.pdf???. > What's up with that? [...] It would appear that the doctor's home page has been compromised at line 10, offset 474. A one-pixel iframe linked to onlinestat.cn may be the fault: -- John B. Matthews trashgod at gmail dot com http://home.roadrunner.com/~jbmatthews/ From mail at microcorp.co.za Tue Dec 23 02:57:24 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 23 Dec 2008 09:57:24 +0200 Subject: I always wonder ... References: Message-ID: <01e301c964e9$cff3f8c0$0d00a8c0@hendrik> "Carl Banks" wrote: >If you have to followup, at least keep your reply to something short >and witty, like, "Go away, troll". OK will do see next post. - Hendrik From fetchinson at googlemail.com Fri Dec 19 14:55:07 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Fri, 19 Dec 2008 11:55:07 -0800 Subject: PIL on 3.x? Message-ID: Does anyone know if PIL will be ported to the 3.x branch? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From tjreedy at udel.edu Tue Dec 9 13:15:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 09 Dec 2008 13:15:58 -0500 Subject: memory leak? In-Reply-To: <493EAB79.6070805@arimaz.com> References: <493EAB79.6070805@arimaz.com> Message-ID: Gabriel Rossetti wrote: > I ran these tests on linux 2.6 (ubuntu 8.04) using python 2.5.2. Have you tried the much newer 2.6? 2.5.3 will be out soon with some bug fixes. From mail at timgolden.me.uk Thu Dec 4 11:14:42 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 04 Dec 2008 16:14:42 +0000 Subject: UnicodeDecodeError quick question In-Reply-To: <6858147d-a213-45ef-9564-bff220688881@e1g2000pra.googlegroups.com> References: <6858147d-a213-45ef-9564-bff220688881@e1g2000pra.googlegroups.com> Message-ID: <493801F2.6030701@timgolden.me.uk> patrick.waldo at gmail.com wrote: > Hi Everyone, > > I am using Python 2.4 and I am converting an excel spreadsheet to a > pipe delimited text file and some of the cells contain utf-8 > characters. I solved this problem in a very unintuitive way and I > wanted to ask why. If I do, > > csvfile.write(cell.encode("utf-8")) > > I get a UnicodeDecodeError. However if I do, > > c = unicode(cell.encode("utf-8"),"utf-8") > csvfile.write(c) > > Why should I have to encode the cell to utf-8 and then make it unicode > in order to write to a text file? Is there a more intuitive way to > get around these bothersome unicode errors? The short answer is that you're writing to a file you've opened with the codecs module. Any write to this file expects unicode data and will automatically encode it to the encoding you specified. You're trying to send it utf8-encoded data -- ie a string of bytes, *not* unicode -- and it presumably tries to decode it to a unicode object before encoding it as utf8 like you asked it to. Without looking at the implementation, it probably just does unicode (x) on what you've passed in, will will use the default ascii codec and fail in the way you saw. (Honestly, that was the short answer). To solve it, assuming cell is already unicode, just pass it unadulterated to csvfile.write. The reason the other thing works is because you're in control of the -- unncessary -- unicode conversion, and you're telling Python what encoding to use for decoding and encoding. TJG From jstroud at mbi.ucla.edu Fri Dec 5 17:10:50 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 05 Dec 2008 14:10:50 -0800 Subject: dict subclass and pickle bug (?) In-Reply-To: References: <6J7_k.6212$hc1.5967@flpi150.ffdc.sbc.com> Message-ID: Terry Reedy wrote: > because there is no bug to fix. I have suggesting closing. May I suggest to add something to this effect within the issue itself so others won't spend time trying to figure out why the "bug" is still open? If this is a more general feature of issues, then perhaps it would be helpful to provide a footnote at the bottom of all issue pages via the page template that explains why they are not bugs and suggests a general course of action for the programmer. James From semanticist at gmail.com Mon Dec 29 19:06:37 2008 From: semanticist at gmail.com (Miles) Date: Mon, 29 Dec 2008 19:06:37 -0500 Subject: why cannot assign to function call In-Reply-To: <495867C2.7080807@gmail.com> References: <495867C2.7080807@gmail.com> Message-ID: On Mon, Dec 29, 2008 at 1:01 AM, scsoce wrote: > I have a function return a reference, and want to assign to the reference, > simply like this: >>>def f(a) > return a > b = 0 > * f( b ) = 1* > but the last line will be refused as "can't assign to function call". > In my thought , the assignment is very nature, but why the interpreter > refused to do that ? Here's some links to help you better understand Python objects: http://effbot.org/zone/python-objects.htm http://effbot.org/zone/call-by-object.htm The second one is a bit denser reading, but it's important to learn that Python's approach to objects and "variables" is fundamentally different from that of C/C++. In the example below, there's no way in the Python language* that bar() can change the value of b, since strings and numbers are immutable. def foo(): b = 0 bar(b) print b # will always be 0 * There are stupid [ctypes/getframe/etc.] tricks, though I think all are implementation-specific -Miles From martin at v.loewis.de Sun Dec 14 18:25:23 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 15 Dec 2008 00:25:23 +0100 Subject: the official way of printing unicode strings In-Reply-To: References: <6qk1o7Fcr01gU3@mid.uni-berlin.de> Message-ID: <494595e4$0$9113$9b622d9e@news.freenet.de> > My main problem is that when I use some language I want to use it the way it > is supposed to be used. Usually doing like that saves many problems. > Especially in Python, where there is one official way to do any elementary > task. And I just want to know what is the normal, official way of printing > unicode strings. I mean, the question is not "how can I print the unicode > string" but "how the creators of the language suppose me to print the > unicode string". I couldn't find an answer to this question in docs, so I > hope somebody here knows it. > > So, is it _the_ python way of printing unicode? The official way to write Unicode strings into a file is not to do that. Explicit is better then implicit - always explicitly pick an encoding, and encode the Unicode string to that encoding. Doing so is possible in any of the forms that you have shown. Now, Python does not mandate any choice of encoding. The right way to encode data is in the encoding that readers of your data expect it in. For printing to the terminal, it is clear what the encoding needs to be (namely, the one that is used by the terminal), hence Python choses that one when printing to the terminal. When printing to the file, the application needs to make a choice. If you have no idea what encoding to use, your best choice is the one returned by locale.getpreferredencoding(). This is the encoding that the user is most likely to expect. Regards, Martin From prologic at shortcircuit.net.au Wed Dec 3 21:36:43 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 4 Dec 2008 12:36:43 +1000 Subject: RELEASED Python 3.0 final In-Reply-To: References: Message-ID: On Thu, Dec 4, 2008 at 11:58 AM, alex23 wrote: > On Dec 4, 11:51 am, Barry Warsaw wrote: >> On behalf of the Python development team and the Python community, I >> am happy to announce the release of Python 3.0 final. > > Thanks to you and everyone involved for your efforts! +1 --JamesMills -- -- -- "Problems are solved by method" From michele.simionato at gmail.com Mon Dec 1 06:16:15 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 1 Dec 2008 03:16:15 -0800 (PST) Subject: What about a decorator module version 3.0? Message-ID: <7504ac87-4e4e-447f-a02c-f9db3f932a57@s20g2000yqh.googlegroups.com> I am thinking about releasing a new version of the decorator module, completely rewritten from scratch. The new implementation takes half the lines of the original one and it is much more general, so I like it more. However, there is an issue of compatibility with the past and I am asking here for feedback from my users. I have already broken backward compatibility in the past, with version 2.0 of the module, and I could break it again in version 3.0. However, the breakage in version 2.0 was very minor and at the time the module had very few users so that nobody ever complained. Nowadays there are a lot of people using it and there are frameworks relying on it (such as Pylons) so I am relectant to break compatibility, even in minor ways. I want to ask people how do they use the module. If you just use the decorator function, that will continue to work as before and I do not think I will ever break that functionality - actually I am thinking of enhancing it. However, over the time I have added other utilities to the module - I am referring to getinfo and new_wrapper - and I would like to get rid of them. Actually I would like to deprecate them in decorator 3.0 and to remove them in decorator 3.1 or later on, after a grace period of one year or so. Also, I would like to remove a new feature introduced in version 2.3, i.e. the direct support to decorator factories. I added it in haste and now I have changed my mind. Is there anybody using that functionality? I want to offer an alternative which does not involve magically adding a __call__ method to a class. In general I want to remove a few things because I feel they add to the learning curve without offering a compelling benefit, or because I think the new implementation offer better ways to do the same job. If nobody uses those features I will remove them; on the other hand, if this is too much of a breakage, I will just start a new project with a different name. The old decorator module will continue to live forever, but the developement on it will stop and the new things will go in the new module. Personally, I would like to keep the name, and to add some support for Python 3.0: decorator 3.0 sounds good for Python 3.0, and the change I have in mind is the same kind of change which happened for Python 3.0, i.e. a simplification more than an addition of new features. What do you people think? From Russ.Paielli at gmail.com Thu Dec 18 22:49:57 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Thu, 18 Dec 2008 19:49:57 -0800 (PST) Subject: Is this pythonic? References: <66d058f9-cfe1-4b3c-ab8a-e6e88bb97770@m22g2000vbp.googlegroups.com> Message-ID: On Dec 18, 8:08?am, ipyt... at gmail.com wrote: > x.validate_output(x.find_text(x.match_filename > (x.determine_filename_pattern(datetime.datetime.now())))) > > Is it even good programming form? I hope you're kidding. From benjamin.kaplan at case.edu Fri Dec 5 17:18:02 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 5 Dec 2008 17:18:02 -0500 Subject: Problems running on hp duo Pentium R processor In-Reply-To: <200812051608.56335.inq1ltd@inqvista.com> References: <200809221443.25765.inq1ltd@inqvista.com> <200812051502.26421.inq1ltd@inqvista.com> <77895c1d0812051227o104ff233m7f16410e3cf8b392@mail.gmail.com> <200812051608.56335.inq1ltd@inqvista.com> Message-ID: On Fri, Dec 5, 2008 at 4:08 PM, jim-on-linux wrote: > On Friday 05 December 2008 15:27, Kevin Kelley wrote: > > If they are running standard Win XP (Home or Pro), > > as opposed to 64-bit Win XP, then whether or not the > > CPU supports the IA64 instruction set really doesn't > > matter. As far as I know every Intel Core2 and > > Pentium Dual-Core CPU since ~ 2006 has supported > > 64bit instructions, even the Atom is 64bit. Also, > > the "R" is for Registered Trademark (of Pentium), > > it's not part of the name/model > > (http://ark.intel.com/cpu.aspx?groupId=33925). > > > > Kevin > > Kevin , > I'm trying to find out why my program gets an import > error on only one machine. Is there any problem with > python running on a 64 bit Architecture machine or is > it something specific to this one HP machine? None of > my other clients have had this problem, nor have I on > any machine that I've tried tested it on. > > jim-on-linux > > What Kevin's saying is that the architecture of the processor doesn't really matter here. Just about every processor made in the last 2 years is a 64-bit processor. Even though they have 64-bit processors, most people are still running the 32-bit version of Windows. In that case, for programming purposes, the computer should be treated as 32-bit. If your customer is using 64-bit Windows, however, things will change. On 64-bit operating systems, you should use the 64-bit version of Python. Windows x64 can run 32-bit programs but the 32-bit programs can't load the 64-bit DLLs and vice-versa so you might see an error like the one you posted.. Try using the AMD64 version of python and see if that fixes the problem for them. > > > > > On Fri, Dec 5, 2008 at 2:02 PM, jim-on-linux > wrote: > > > Python help, > > > > > > In September I wrote: > > > I have a number of clients running a program built > > > with python 2.5. One has just purchased an HP > > > with a duo core Pentium R processor E2200, 2.2G > > > with .99g ram. > > > > > > Only on the new HP, when they try to print they > > > get an import error; > > > File win32ui.pyc line 12, in > > > File win32ui.pyc, line 10, in _load > > > ImportError: DLL load failed: The specified > > > module could not be found. > > > > > > It turns out that the E2200 processor is 64 bit > > > architecture. > > > > > > What are my options? > > > > > > I've run DependecyWalker, > > > They are using Win XP Service Pack 2 > > > > > > > > > > > > jim=on-linux > > > > > > > > > > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-lis > > >t > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Dec 17 20:16:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 17 Dec 2008 23:16:06 -0200 Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> Message-ID: En Wed, 17 Dec 2008 22:46:32 -0200, Aaron Brady escribi?: > On Dec 17, 5:05?pm, "Gabriel Genellina" > wrote: >> En Wed, 17 Dec 2008 12:21:38 -0200, Jeremy Sanders ? >> escribi?: >> >> > It would be nice if Python created pipes that are properly >> inheritable by >> > default by child processes, as they're mostly used for IPC. >> >> I'd say it is a bug in os.pipe implementation; they should be >> inheritable ? >> by default, as in posix (after all, the code is in "posixmodule.c"). > > The code looks like this: > > ok = CreatePipe(&read, &write, NULL, 0); > Py_END_ALLOW_THREADS > if (!ok) > return win32_error("CreatePipe", NULL); > read_fd = _open_osfhandle((Py_intptr_t)read, 0); > write_fd = _open_osfhandle((Py_intptr_t)write, 1); > > 'If lpPipeAttributes is NULL, the handle cannot be inherited.' You > could populate a 'SECURITY_ATTRIBUTES' structure, or call > DuplicateHandle on both of them. > > A patch would look like this: > > SECURITY_ATTRIBUTES sattribs; > sattribs.nLength = sizeof(sattribs); > sattribs.lpSecurityDescriptor = NULL; > sattribs.bInheritHandle = TRUE; > ok = CreatePipe(&read, &write, &sattribs, 0); Yes, that's exactly how os.popen does it (in posixmodule.c) > This still doesn't answer whether the file descriptor return by > '_open_osfhandle' can be inherited too. It doesn't matter. The OS only cares about file handles, not C RTL structures. -- Gabriel Genellina From rlbuvel at gmail.com Mon Dec 29 11:42:59 2008 From: rlbuvel at gmail.com (rlbuvel at gmail.com) Date: Mon, 29 Dec 2008 08:42:59 -0800 (PST) Subject: math module for Decimals References: <4958F3C4.1050103@wi.rr.com> Message-ID: On Dec 29, 10:22 am, Steve Holden wrote: > Raymond L. Buvel wrote: > > Since the interest is more in extended precision than in decimal > > representation, there is another module that may be of interest. > > >http://calcrpnpy.sourceforge.net/clnum.html > > > It interfaces to the Class Library for Numbers (CLN) library to provide > > both arbitrary precision floating point and complex floating point > > numbers and the usual math functions. > > > While I am the author of this module, I agree with Mark that a module > > based on MPFR would be better since you have better control over > > precision and rounding. > > > I have looked at Sage (which uses MPFR) but it is a huge integrated > > package so you can't just import what you need into one of your usual > > Python scripts. > > > I wrote the clnum module mainly to support arbitrary precision in an RPN > > calculator available from the same SourceForge project. However, it > > also works nicely as a stand-alone module. > > > At this time, there is no Windows installer available for Python 2.6 > > because I don't use Windows at home and the person who normally builds > > the installer for me is no longer interested. If someone wants to > > follow the published instructions and send me the resulting installer, I > > will put it up on SourceForge. > > I'm not sure why nobody has mentioned gmpy, except possibly because it > advertises its alpha status and doesn't have many active developers. > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ The main reason is that it doesn't support the functions the OP wanted (sin, cos, log, etc.). This was one of the reasons I developed clnum (in addition to needing complex numbers). Ray From conrad.ammon at gmail.com Mon Dec 15 11:29:31 2008 From: conrad.ammon at gmail.com (cmdrrickhunter@yaho.com) Date: Mon, 15 Dec 2008 08:29:31 -0800 (PST) Subject: Structure using whitespace vs logical whitespace Message-ID: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> I've been trying to search through the years of Python talk to find an answer to this, but my Googlefu is weak. In most languages, I'll do something like this xmlWriter.BeginElement("parent"); ----xmlWriter.BeginElement("child"); ----------xml.Writer.Characters("subtext"); ----xmlWriter.EndElement(); xmlWriter.EndElement(); Where the dashes are indentation (since some newsgroup handlers don't do tabs well). XML writing is just an example. In general, I'm using indentation to show logical flow through code. Python's choice to give semantic meaning to whitespace prevents me from doing such things. What was once reserved for logical use is now used syntactically. In 90% of cases, its not needed, and whitespace significance seems to be pretty effective. In that last 10%, however, I've been frustrated many times. I've been using python for a few years, and gotten around this in one way or another, but now I want to get other who work with me to pick up Python. All newbies to Python have trouble with the idea of whitespace sensitivity, but how can I convince them that "it just works better" when I have this construct which I want to use but can't. Has anybody found a way to emulate this behavior? I've often done it by opening an expression for the whole thing, but there's a lot of tasks where a single expression just isn't sufficient (such as things with assignment). PS. In my opinion the solution would be to have the option of entering a "whitespace insensitive" mode which uses C style {} and ;. The token to enter it could be as complicated as you want (in fact, it may make sense to make it complicated to discourage use unless it's really advantageous). I'd sugest {{ and }} or something bigger like {={ } =}. Only two problems: 1) I'm sure it would offend Guido's sense of language aesthetics 2) I'm sure the idea has been hashed over on this newsgroup to death... hence prefering a workaround instead. From kmtracey at gmail.com Wed Dec 31 10:21:48 2008 From: kmtracey at gmail.com (Karen Tracey) Date: Wed, 31 Dec 2008 10:21:48 -0500 Subject: select.select and socket.setblocking In-Reply-To: <495b4be5$0$11379$5fc30a8@news.tiscali.it> References: <495a661d$0$11384$5fc30a8@news.tiscali.it> <495b34d8$0$11387$5fc30a8@news.tiscali.it> <495b4be5$0$11379$5fc30a8@news.tiscali.it> Message-ID: On Wed, Dec 31, 2008 at 5:39 AM, Francesco Bochicchio wrote: > Francesco Bochicchio ha scritto: > >> >>> No, in blocking mode it will wait to receive _some_ data (1 or >>> more bytes). The "requested" amount is strictly an upper >>> limit: recv won't return more than the requested number of >>> bytes, but it might return less. >>> >>> >> Uhm. In my experience, with TCP protocol recv only returned less than the >> required bytes if the remote end disconnects. I always check the >> returned value of recv and signal an error if the read bytes are less than >> the expected ones, but this error is never occurred (and its about 20 years >> that I use sockets in various languages and various flavor of unix and >> occasionally on windows. Maybe have always been lucky ? :-) >> >> > BTW, this is not a rethorical or ironic question... my applications mostly > run on LANs or dedicated WANs so maybe they never experienced the > kind of network congestion that could cause recv to return less than the > expected amount of bytes ... > > but then, IIRC TCP guarantees that the packet is fully received by > hand-shaking at transport level between sender and receiver. Ad once the > packet is fully in the receiver buffer, why should recv choose to give > back to the application only a piece of it? > One way to get less data than you ask for: TCP internally buffers a finite amount of data for your connection. If you ever ask to receive in one recv() call more than TCP is willing to buffer for your connection, you will get back only what TCP has buffered, not the amount you ask for, even if the other side has sent the larger amount. The remaining data will likely be buffered in the TCP send buffers on the other side of the connection*. Your call to recv() will empty your side's receive buffers (it is likely TCP will return all the data it has buffered in a single call, though I don't think that is an API requirement), causing your side's TCP to send a window update to the other side indicating it is willing to receive more data on the connection, the data will be transfered, and a subsequent recv() call by your application will be able to retrieve more of the data. TCP provides a stream of bytes to its applications, not a datagram/packet interface. Assuming "packets" sent by one side will be received in their entirety on a single receive call on the other side is really asking for trouble. TCP does not maintain any sort of packet boundaries that you seem to think are implied by the sequence of sends issued on one side of the connection. Karen *This is assuming the other side's send buffers aren't filled up by the left-over data your TCP isn't willing to buffer. If they are, and the sending socket is in blocking mode, the sender will have been blocked during the send waiting for buffer space to free up. If the sender's socket is non-blocking, and both the send and receive buffers fill up, then the sending socket will start returning EWOULDBLOCK or EAGAIN (I forget which) on calls to send data, until some buffer space is freed up by your side's receiving some data. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldo at geek-central.gen.new_zealand Wed Dec 3 18:34:59 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 04 Dec 2008 12:34:59 +1300 Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> <126ba84a-0ea0-4a91-b7d2-89ed650e5d6c@d32g2000yqe.googlegroups.com> Message-ID: In message , Philip Semanchuk wrote: > In my experience, the environment in which a cron job runs is > different from the environment in which some command line scripts run... Which is true, but again, cron should report the environment in the mail message. For example, here are some headers from a recent run of the maildir backup task I have scheduled twice a day: Subject: Cron $HOME/bin/backupdir $HOME/.maildir X-Cron-Env: X-Cron-Env: X-Cron-Env: X-Cron-Env: X-Cron-Env: From xahlee at gmail.com Tue Dec 9 18:00:13 2008 From: xahlee at gmail.com (Xah Lee) Date: Tue, 9 Dec 2008 15:00:13 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: <8e80a2e7-5e55-49d0-a173-3796ed1be546@a29g2000pra.googlegroups.com> On Dec 8, 4:56 pm, Jon Harrop wrote: > Xah Lee wrote: > > A moron, wrote: > > > You failed the challenge that you were given. > > > you didn't give me a challenge. > > Thomas gave you the challenge: > > "What I want in return is you to execute and time Dr. Harrop's original > code, posting the results to this thread... By Dr. Harrop's original code, > I specifically mean the code he posted to this thread. I've pasted it below > for clarity.". > > Thomas even quoted my code verbatim to make his requirements totally > unambiguous. Note the parameters [9, 512, 4] in the last line that he and I > both gave: > > AbsoluteTiming[Export["image.pgm", Graphics at Raster@Main[9, 512, 4]]] > > You have not posted timings of that, let alone optimized it. So you failed. The first parameter to your Main specifies some kinda recursively stacked spheres in the rendered image. The second parameter is the width and height of the pixels in the rendered image. I tried to run them but my computer went 100% cpu and after i recall 5 min its still going. So, i reduced your input. In the end, with reduced input, it shows my code is 5 times faster (running Mathematica v4 on OS X 10.4.x with PPC 1.9 GHz), and on the other guy's computer with Mathematica 6 he says it's twice as fast. Given your code's nature, it is reasonably to assume that with your original input my code would still be faster than yours. You claim it is not or that it is perhaps just slightly faster? It is possible you are right. I don't want to spend the energy to run your code and my code and possible hog my computer for hours or perhaps days. As i said, your recursive Intersect is very badly written Mathematica code. It might even start memory swapping. Also, all you did is talking bullshit. Thomas actually is the one took my challenge to you and gave me $20 to prove my argument to YOU. His requirement, after the payment, is actually, i quote: ?Alright, I've sent $20. The only reason I would request a refund is if you don't do anything. As long as you improve the code as you've described and post the results, I'll be satisfied. If the improvements you've described don't result in better performance, that's OK.? He haven't posted since nor emailed me. It is reasonable to assume he is satisfied as far as his payment to me to see my code goes. You, kept on babbling. Now you say that the input is different. Fine. How long does that input actually take on your computer? If days, i'm sorry i cannot run your toy code on my computer for days. If in few hours, i can then run the code overnight, and if necessary, give you another version that will be faster with your given input to shut you the fuck up. However, there's cost to me. What do i get to do your homework? It is possible, that if i spend the energy and time to do this, then you again refuse to acknowledge it, or kept on complaining about something else. You see, newsgroup is the bedrock of bullshit. You bullshit, he bullshits, everybody brags and bullshit because there is no stake. I want sincerity and responsibility backed up, with for example paypal deposits. You kept on bullshitting, Thomas gave me $20 and i produced a code that reasonably demonstrated at least how unprofessional your Mathematica code was. Here's the deal. Pay me $20, then i'll creat a version of Mathematica code that has the same input as yours. Your input is Main[9, 512, 4], as i have exposed, your use of interger in the last part for numerical computation is Mathematica incompetence. You didn't acknowledge even this. I'll give a version of Mathematica with input Main[9, 512, 4.] that will run faster than yours. If not, money back guaranteed. Also, pay me $300, then i can produce a Mathematica version no more than 10 times slower than your OCaml code, this should be a 70000 times improvement according to you. Again, money back guarantee. If i don't receive $20 or $300, this will be my last post to you in this thread. You are just a bullshitter. O wait... my code with Main[9, 512, 4.] and other numerical changes already makes your program run faster regardless of the input size. What a motherfucking bullshit you are. Scratch the $20. The $300 challenge still stands firm. Xah ? http://xahlee.org/ ? From wx1234 at gmail.com Tue Dec 30 14:31:53 2008 From: wx1234 at gmail.com (wx1234 at gmail.com) Date: Tue, 30 Dec 2008 11:31:53 -0800 (PST) Subject: need help with list/variables Message-ID: <63b5acce-d566-48cb-abce-c00fd0e02a39@v39g2000pro.googlegroups.com> I have a list and would like to parse the list appending each list item to the end of a variable on a new line. for instance mylist = ['something\n', 'another something\n', 'something again\n'] then parse mylist to make it appear in my variable in this format: myvar = """ something another something something again""" how would i go about setting a variable like this? From canton.alex at gmail.com Wed Dec 10 21:27:16 2008 From: canton.alex at gmail.com (canton.alex at gmail.com) Date: Wed, 10 Dec 2008 18:27:16 -0800 (PST) Subject: New EasyPC website launch. Message-ID: <45cb3305-fef7-4170-9b62-1a5103549ceb@t26g2000prh.googlegroups.com> Hello Everyone, This post has been posted to discuss the launch of the new forum website named "EasyPC". If you would like to help run this website please email me on eas... at techie.com. If interested please visit http://easypc.top-talk.net It would be greatly appreciated if we could get as many people to register to this site to get the site running. Also it would be great if you could tell your friends about it. Many thanks, The EasyPC Team. From matdata.dims at gmail.com Sat Dec 20 03:25:00 2008 From: matdata.dims at gmail.com (matdata.dims at gmail.com) Date: Sat, 20 Dec 2008 00:25:00 -0800 (PST) Subject: Today' Topic Managerial Values and ethos Message-ID: Delhi Institute of Management & Services Dear friends, We are extremely happy to welcome you to the world of Management... We are in the process of preparing some 5 minutes revision Q & A type lessons for management students. They are in no way, a replacement for the classroom lectures, textbooks or any other study guides. If you wish to go through these lessons. Please visit today's BLOGS: What is Conflict http://www.bookghar.com/What%20is%20Conflict.htm Managerial Values and ethos http://www.bookghar.com/Managerial%20Values%20and%20ethos.htm We want you to suggest improvements or corrections if any, by Email to Ms Sheetal Varma, (Senior HR Executive). Email: dimsjobs at gmail.com If you are looking for a job or you want to change a job, please send your resume to Ms Sheetal (Senior HR Executive). She will try to help you to find a suitable job. Email: dimsnaukri at gmail.com CAREER TRAINING Join University Recognized Courses MBA {BM} MBA {HR}, MBA {MKT}, and MBA {Fin}, MCA, BCA, MMC, BMC, B.com M.com M.Insurance, B.Fashion For Career Development and Job Promotions. CONTACT: Delhi Institute of Management &Services, Study Centre of NMiMS UNIVERSITY, GURU JAMBHESHWAR UNIVERSITY, JAMIA HAMDARD UNIVERSITY, ALL INDIA MANAGEMENT ASSOCIATION, PUNJAB TECHNICAL UNIVERSITY, MUMBAI EDUCATION TRUST . 1108 Akashdeep Building, New Delhi 110001 TEL FAX: 23312187, TEL: 23316475. If you do not want to receive such mail in future. Please send mail Email: bookghar2008 at gmail.com From lewis.sarah93 at yahoo.com Thu Dec 4 23:50:25 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 20:50:25 -0800 (PST) Subject: Earn more money Message-ID: <041ab6eb-5644-4a65-bb5b-27f137800c11@g38g2000yqn.googlegroups.com> Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From wuwei23 at gmail.com Sun Dec 7 20:53:55 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 7 Dec 2008 17:53:55 -0800 (PST) Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? References: Message-ID: <5ccd4a18-cd2b-4040-90c6-33723af15e96@b38g2000prf.googlegroups.com> On Dec 8, 11:23?am, excor... at gmail.com wrote: > Does pyglet use PyOpenGL as its OpenGL wrapper? If not, any idea why? > Seems like it would be a fairly substantial duplication of effort. Taken from: http://groups.google.com/group/pyglet-users/msg/832b15389fccd28d >> IIRC pyglet tries to minimize dependencies, so PyOpenGL won't be >> used. However, pyglet's wrapping of OpenGL isn't meant to be >> complete; it's only what pyglet itself uses. You'll need to use >> PyOpenGL for the rest. > That was more or less the original plan. pyglet wraps OpenGL at the > lowest level, so it only provides glVertex3f, glVertex2d, etc., > whereas PyOpenGL also provides polymorphic functions such as glVertex. [...] > pyglet provides all of the error-checking functionalities that > PyOpenGL does (though these can be disabled for performance). At > last check, pyglet was significantly faster than PyOpenGL 3, but > slower than PyOpenGL 2. From federico at linux.com.uy Wed Dec 24 10:27:40 2008 From: federico at linux.com.uy (Federico Moreira) Date: Wed, 24 Dec 2008 12:27:40 -0300 Subject: python web programming for PHP programmers In-Reply-To: <6rf1igF1f362U1@mid.uni-berlin.de> References: <6rf1igF1f362U1@mid.uni-berlin.de> Message-ID: You can try also web2py (http://mdp.cti.depaul.edu/) but i think you may be interested on http://www.modpython.org/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Thu Dec 11 03:11:02 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Dec 2008 08:11:02 GMT Subject: if expression source format References: Message-ID: "Lambert, David W (S&T)" wrote: > > The "if" expression leads to long statements. Please offer suggestions > to beautify this function. For this example use maximum line length > marked by the ####'s. > > Thank you. > > > ############################################################## > def compute_wind_chill_temperture(T:'Temperature, dF',s:'Wind speed, > mph')->'dF': > ''' > > ''' > return 35.74 + 0.6215*T + s**0.16*(T*0.4275-35.75) if T < 40 else T If the expression is too long for your liking then just don't use the an if expression: if T < 40: return whatever else: return T is probably easier to read. From simonharrison.uk at googlemail.com Mon Dec 8 06:17:47 2008 From: simonharrison.uk at googlemail.com (simonharrison.uk at googlemail.com) Date: Mon, 8 Dec 2008 03:17:47 -0800 (PST) Subject: Determining whether a variable is less/greater than a range. References: <362ab93b-b804-4ebe-a22f-e422feb301c8@c1g2000yqg.googlegroups.com> Message-ID: <5575096e-8b7a-402a-9162-eb9ebbdf2569@j11g2000yqg.googlegroups.com> Wow. Thanks Eric and Peter. Very helpful indeed. From budden73 at gmail.com Mon Dec 1 05:24:09 2008 From: budden73 at gmail.com (budden) Date: Mon, 1 Dec 2008 02:24:09 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: Mathematica is a great language, but: 1. it is too slow 2. It is often hard to read 3. It gives sence to every keystroke. You press escape by occasion and it goes in a code as a new symbol, w/o error. Nasty. 3. I know 5-th version. It does not allow to track the source as SLIME does. This feature as absolutely necessary for serious development So, in fact, Mathematica do not scale well IMO. From luismgz at gmail.com Sun Dec 21 12:52:48 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Sun, 21 Dec 2008 09:52:48 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> <6r6hpfFfb643U3@mid.uni-berlin.de> <494E6FDA.4070401@mrabarnett.plus.com> Message-ID: <4585c27d-d7a9-480f-991c-a869161be55c@g38g2000yqn.googlegroups.com> On Dec 21, 2:34?pm, r wrote: > RTFM, use as much python code and optimize with C where needed, > problem solved! That's true if your *really* need C's extra speed. Most of the times, a better algorithm or psyco (or shedskin) can help without having to use any other language. This is unless you are hacking a kernel, writing device drivers or 3D image processing. For anything else, python is fast enough if you know how to optimize your code. Luis From akineko at gmail.com Tue Dec 30 12:13:04 2008 From: akineko at gmail.com (akineko) Date: Tue, 30 Dec 2008 09:13:04 -0800 (PST) Subject: Python in C References: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> <313583fc-4651-4deb-8a44-c3b1810b722c@z27g2000prd.googlegroups.com> Message-ID: Hello Skip, Thank you for your response. Your posting reminds me that we, Python community as a whole, owe a great deal to Python developers. The problem is ... The more you work on Python, the harder you can go back to C or C++ world. I use SWIG, instead. I think SWIG is a good way to mix two worlds. Aki- On Dec 30, 4:10 am, s... at pobox.com wrote: > aki> Although this is not what you are asking but I'm wondering why you > aki> need to read CPython implementation. > > A couple reasons come to mind: > > * education > * want to make it better (extend it, fix bugs, etc) > * want to see how it relates to the implementation of other languages > (Ruby, Perl, Tcl, etc) > > aki> CPython worked great for me. I don't want to read a large piece of > aki> software, like CPython, unless it is really really necessary. > > Sure, but not everyone works at the Python layer. Which is a good thing, > because if everyone confined themselves to Python code nobody would fix > problems in the language implementation or enhance it. > > -- > Skip Montanaro - s... at pobox.com -http://smontanaro.dyndns.org/ From alexoplocatie at gmail.com Wed Dec 17 05:32:58 2008 From: alexoplocatie at gmail.com (aka) Date: Wed, 17 Dec 2008 02:32:58 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> Message-ID: <41957459-4033-4b63-b4d1-68f957c3e21c@b38g2000prf.googlegroups.com> Due to being in a hurry I didn't paste correctly (sorry). The intention is to parse a csv file and (ultimately) put values of column 1 ("id") in a list (so I need to append in the loop) that will be used to fill a session var. The complete code is: roles = [] inp = 'C:/temp/test.csv' try: fp = open(inp, 'rb') reader = csv.reader(fp, dialect='excel', delimiter=';') for r in reader: roles.append(r) ## ultimately should be something like r.id ## first row of csv file should be skipped because of column names or r[0] except: msg = 'Something's wrong with the csv.reader' return dict(file=inp,roles=str(roles)) The roles list isn't populated at all :( From exarkun at divmod.com Wed Dec 17 15:21:13 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 17 Dec 2008 15:21:13 -0500 Subject: getting object instead of string from dir() In-Reply-To: <477b9c2e-a0ab-4b26-b643-4a9369c2aaac@r2g2000vbp.googlegroups.com> Message-ID: <20081217202113.20272.2140861340.divmod.quotient.22326@ohm> On Wed, 17 Dec 2008 11:52:17 -0800 (PST), Rominsky wrote: >On Dec 17, 10:59?am, Christian Heimes wrote: >> Rominsky schrieb: >> >> > I am trying to use dir to generate a list of methods, variables, etc. >> > I would like to be able to go through the list and seperate the >> > objects by type using the type() command, but the dir command returns >> > a list of strings. ?When I ask for the type of an element, the answer >> > is always string. ?How do I point at the variables themselves. ?A >> > quick example is: >> >> > a = 5 >> > b = 2.0 >> > c = 'c' >> >> > lst = dir() >> >> > for el in lst: >> > ? ? print type(el) >> >> for name, obj in vars().iteritems(): >> print name, obj >> >> Christian > >I do have some understanding of the pythonic methodology of >programming, though by far I still don't consider myself an expert. >The problem at hand is that I am coming from a matlab world and trying >to drag my coworkers with me. I have gotten a lot of them excited >about using python for this work, but the biggest gripe everytime is >they want their matlab ide. I am trying to experiment with making >similar pieces of the ide, in particular I am working on the workspace >window which lists all the current variables in the namespace, along >with their type, size, value, etc.... I am trying to create a python >equivalent. I can get dir to list all the variables names in a list >of strings, but I am trying to get more info them. hence the desire >to do a type command on them. I like the locals and globals commands, >but I am still trying to get more info. I have started using the eval >command with the strings, which is working, but I am curious if there >is a better or more elegant way of getting the info. The eval example >would be something like: > >a = 5 >b = 2.0 >c = 'c' > >lst = dir() > >for el in lst: > print el + '\t' + str(eval('type(%s)'%el)) > >It works, now I am curious if there is a better way. What about this: >> for name, obj in vars().iteritems(): >> print name, obj >> >> Christian Jean-Paul From wrzesniowy at poczta.onet.pl Thu Dec 25 16:52:43 2008 From: wrzesniowy at poczta.onet.pl (blady) Date: Thu, 25 Dec 2008 13:52:43 -0800 (PST) Subject: Big Tits and Big Boobs Message-ID: <9f7be2d5-c2d0-4051-9dcf-9732e2361abb@b41g2000pra.googlegroups.com> http://yeba.pl/show/movies/6044/pucybutka From Astley.lejasper at gmail.com Wed Dec 3 05:28:35 2008 From: Astley.lejasper at gmail.com (Astley Le Jasper) Date: Wed, 3 Dec 2008 02:28:35 -0800 (PST) Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> <9566ebea-d6b9-45bf-9bba-df259508efd3@w3g2000yqc.googlegroups.com> Message-ID: <8ab6010b-1e39-441b-b4ab-632f5b83b2be@f3g2000yqf.googlegroups.com> Ok ... this is odd. I tried gregory's suggestion of redirecting the stdout & stderr to a text file. This worked. I could see all the logging information. However, there was no error to see this time ... the application worked completely without any problems. I also then tried Jon's suggestion of attaching to the console ... this also allowed me to see all the logging info as it went through. Again, there were no problems as the application worked without any problems. Which suggests that it's the logging module or something with the output streams. Here is my logging setup in the primary module. It directs info to the main console and also to a logging file..... >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #Set up logging log = logging.getLogger('scrape_manager') log.setLevel(logging.INFO) my_filename = ss.compact_date() + '_' + time.strftime("%H%M") ensure_dir('logs/') #Checks to see if the dir is there and creates it if not log_file = 'logs/systemlog_' + my_filename + ".log" console_h = logging.StreamHandler() file_h = logging.FileHandler(log_file,'w') log.addHandler(console_h) log.addHandler(file_h) console_fmt = logging.Formatter('%(levelname)s (%(threadName)-10s) % (module)s %(message)s',) file_fmt = logging.Formatter('%(asctime)s\t%(levelname)s\t(% (threadName)-10s)\t%(module)s\t%(message)s',) console_h.setFormatter(console_fmt) file_h.setFormatter(file_fmt) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> I also call this from an auxiliary module that is use my the primary module: log = logging.getLogger('scrape_manager') If I change the name of the logger in the auxilary module then I loose all the loggiing information but the application works. What am I doing wrong with the logging setup? I can't see how I would change it. ALJ From Russ.Paielli at gmail.com Sun Dec 7 19:19:40 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 7 Dec 2008 16:19:40 -0800 (PST) Subject: Python for kids? References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> Message-ID: Thanks to everyone who replied. The information was very helpful. Someone might want to consider putting a kids section on python.org (if it doesn't have one already -- I didn't see one). From walterbyrd at iname.com Wed Dec 17 13:30:00 2008 From: walterbyrd at iname.com (walterbyrd) Date: Wed, 17 Dec 2008 10:30:00 -0800 (PST) Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> Message-ID: <6a76b501-f6dc-41b5-8828-b55fece68651@l33g2000pri.googlegroups.com> On Dec 17, 9:04?am, rdmur... at bitdance.com wrote: > Yes. ?It's called Object Oriented Programming. I think you mean it's *Python* Object Oriented Programming. I am not sure that every other OO language works like that. From s.selvamsiva at gmail.com Tue Dec 2 03:40:33 2008 From: s.selvamsiva at gmail.com (S.Selvam Siva) Date: Tue, 2 Dec 2008 14:10:33 +0530 Subject: Posting File as a parameter to PHP/HTML using HTTP POST In-Reply-To: References: Message-ID: I myself have found the solution. Instead of: br[br['uploadedfile']=open("C:/ > > Documents and Settings/user/Desktop/Today/newurl-ideas.txt") We Need to use: br.add_file(open("C:/ > > Documents and Settings/user/Desktop/Today/newurl-ideas.txt"), > filename="newurl-ideas.txt",name="uploadedfile") > On Tue, Dec 2, 2008 at 1:33 PM, S.Selvam Siva wrote: > I am trying to post file from python to php using HTTP POST method. I tried > mechanize but not able to pass the file object. > > from mechanize import Browser > br=Browser() > response=br.open("http://localhost/test.php") > br.select_form('form1') > br['uploadedfile']=open("C:/Documents and > Settings/user/Desktop/Today/newurl-ideas.txt") > response=br.submit() > print response.read() > > But, i get the error: > br['uploadedfile']=open("C:/Documents and > Settings/user/Desktop/Today/newurl > -ideas.txt") > File > "C:\Python25\lib\site-packages\clientform-0.2.9-py2.5.egg\ClientForm.py", > line 2880, in __setitem__ > ValueError: value attribute is readonly > > But, > When uploading is done using browser, it works. > -- > Yours, > S.Selvam > -- Yours, S.Selvam -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip at pobox.com Fri Dec 5 15:24:04 2008 From: skip at pobox.com (skip at pobox.com) Date: Fri, 5 Dec 2008 14:24:04 -0600 Subject: Centralized logging server... In-Reply-To: <413147e3-aaea-4ae3-a350-4c22a79fe77a@b38g2000prf.googlegroups.com> References: <413147e3-aaea-4ae3-a350-4c22a79fe77a@b38g2000prf.googlegroups.com> Message-ID: <18745.36324.222087.910108@montanaro-dyndns-org.local> Sam> I've been playing with the python logging module. I'd like all of Sam> these applications to write their logs to the same place in order Sam> to make analysis easier. Sam> Any ideas on best practices? Perhaps use logging.handlers.SysLogHandler? Sam> What are my options for a syslog server to receive the messages? Sam> Rsyslog looks like it would be good. Anyone know anything else? If you're running on a Unix system of any type you should have syslog by default. You shouldn't need to install anything. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From rdmurray at bitdance.com Thu Dec 11 11:35:47 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Thu, 11 Dec 2008 11:35:47 -0500 (EST) Subject: Preventing execution of a method In-Reply-To: References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> Message-ID: On Thu, 11 Dec 2008 at 08:16, alex23 wrote: > On Dec 12, 2:07?am, "Emanuele D'Arrigo" wrote: >> I.e. if I have a class with two methods, doSomethingSafe() and >> doSomethingDangerous(), is there a way to prevent another module from >> executing doSomethingDangerous() but allow the execution of >> doSomethingSafe()? >> >> My understanding is that in python this is not possible. Can you >> confirm? > > Your understanding is correct. > > The Python convention is to prefix non-public methods/classes etc with > an underscore, as in _doSomethingDangerous(). This is meant to > indicate to anyone using your module that they shouldn't use this > function, at least not without having a good understanding of what it > does. There is, however, also the possibility of prefixing the method name with '__'. The invokes 'name mangling', which makes it more difficult (though not impossible, the idea is to avoid accidents) for the method to be called from outside the class. http://www.python.org/doc/2.5.2/tut/node11.html#SECTION0011600000000000000000. --RDM From eliben at gmail.com Wed Dec 10 01:15:06 2008 From: eliben at gmail.com (eliben) Date: Tue, 9 Dec 2008 22:15:06 -0800 (PST) Subject: SequenceMatcher bug ? References: Message-ID: <67253331-5b36-4018-b15a-c0b86c5342d3@r37g2000prr.googlegroups.com> On Dec 10, 4:12?am, rdmur... at bitdance.com wrote: > On Mon, 8 Dec 2008 at 23:46, eliben wrote: > > This is about Python 2.5.2 - I don't know if there were fixes to this > > module in 2.6/3.0 > > > I think I ran into a bug with difflib.SequenceMatcherclass. > > Specifically, its ratio() method. The following: > > >SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + [5]).ratio > > () > > > returns 0.0 > > > While the same with 500 replaced by 100 returns .99... something > > Looking at the code ofSequenceMatcherthere's some caching going on > > when the sequences are longer than 200 elements (and indeed, I can > > reproduce the bug above 200 but not below). Can anyone confirm that > > this misbehaves and suggest a workaround ? > > Python 2.5.2 (r252:60911, Sep 29 2008, 20:34:04) > [GCC 4.3.1] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> from difflib importSequenceMatcher > >>>SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + > >>> [5]).ratio() > > 0.99900299102691925 > Strange. I could reproduce the problem both on ActiveState Python 2.5.2 for Windows, and in the online Try Python evaluator: http://try-python.mired.org/ Eli From gagsl-py2 at yahoo.com.ar Mon Dec 8 03:31:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Dec 2008 06:31:16 -0200 Subject: how to get a beep, OS independent ? In-Reply-To: References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> <014c575a$0$20670$c3e8da3@news.astraweb.com> Message-ID: En Sun, 07 Dec 2008 23:34:17 -0200, Joe Strout escribi?: > On Dec 7, 2008, at 4:43 PM, Steven D'Aprano wrote: > >> Of course, if you're volunteering to write such a standard system beep >> for Python, I for one would be grateful. > > I am. But where should I put it? Assuming we don't want to wait for > the (understandably) lengthy and contentious process required to add > something to the Python system libraries, where would be the next best > place for this sort of simple OS abstraction layer? The cookbook? http://www.activestate.com/ASPN/Python/Cookbook/ If you can make it run on several different architectures you could upload a patch as a feature request to http://bugs.python.org/ -- Gabriel Genellina From bearophileHUGS at lycos.com Mon Dec 22 19:26:46 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 22 Dec 2008 16:26:46 -0800 (PST) Subject: iterating initalizations References: Message-ID: Chris Rebert: > It likely goes without saying, but you ought to read the fine tutorial as well. I also suggest to fix the messed up indentations. Bye, bearophile From ss9260 at gmail.com Thu Dec 25 10:19:10 2008 From: ss9260 at gmail.com (sriya) Date: Thu, 25 Dec 2008 07:19:10 -0800 (PST) Subject: Topics on Electronics Message-ID: Electronics is the field of manipulating electrical currents and voltages using passive and active components that are connected together to create circuits. Electronic circuits range from a simple load resistor that converts a current to a voltage, to computer central-processing units (CPUs) that can contain more than a million transistors. The following indices and documents provide a basic reference for understanding electronic components, circuits, and applications. http://electronicstopics.blogspot.com/2008/10/welcome-to-world-of-electronics.html From joe at strout.net Fri Dec 19 17:20:08 2008 From: joe at strout.net (Joe Strout) Date: Fri, 19 Dec 2008 15:20:08 -0700 Subject: encoding problem In-Reply-To: <6r2hvjFfb5kpU6@mid.uni-berlin.de> References: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> <6r1m72Ffb5kpU3@mid.uni-berlin.de> <6r2hvjFfb5kpU6@mid.uni-berlin.de> Message-ID: <494C1E18.50606@strout.net> Marc 'BlackJack' Rintsch wrote: >> And because strings in Python, unlike in (say) REALbasic, do not know >> their encoding -- they're just a string of bytes. If they were a string >> of bytes PLUS an encoding, then every string would know what it is, and >> things like conversion to another encoding, or concatenation of two >> strings that may differ in encoding, could be handled automatically. >> >> I consider this one of the great shortcomings of Python, but it's mostly >> just a temporary inconvenience -- the world is moving to Unicode, and >> with Python 3, we won't have to worry about it so much. > > I don't see the shortcoming in Python <3.0. If you want real strings > with characters instead of just a bunch of bytes simply use `unicode` > objects instead of `str`. Fair enough -- that certainly is the best policy. But working with any other encoding (sometimes necessary when interfacing with any other software), it's still a bit of a PITA. > And does REALbasic really use byte strings plus an encoding!? You betcha! Works like a dream. > Sounds strange. When concatenating which encoding "wins"? The one that is a superset of the other, or if neither is, then both are converted to UTF-8 (which is the "standard" encoding in RB, though it works comfily with any other too). Cheers, - Joe From prologic at shortcircuit.net.au Mon Dec 15 00:00:33 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 15 Dec 2008 15:00:33 +1000 Subject: Python is slow In-Reply-To: References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> Message-ID: On Mon, Dec 15, 2008 at 2:59 PM, James Mills wrote: > On Mon, Dec 15, 2008 at 2:44 PM, Benjamin Kaplan > wrote: >> On Sun, Dec 14, 2008 at 11:38 PM, cm_gui wrote: >>> >>> hahaha, do you know how much money they are spending on hardware to >>> make >>> youtube.com fast??? >> >> Obviously not enough to get to the point where it's cheaper to have the >> programmers write C code. And the hardware is more for handling the intense >> traffic that YouTube gets, not for speeding up the site. > > Seriously cm_gui, you're a fool. > Python is not slow. And I should clarify that by stating that the CPython interpreter is NOT slow. --JamesMills From floris.bruynooghe at gmail.com Wed Dec 24 09:56:21 2008 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Wed, 24 Dec 2008 06:56:21 -0800 (PST) Subject: Using exceptions in defined in an extension module inside another extension module Message-ID: <26443e22-0dd6-4fa9-a58e-8d9314001c6c@o4g2000pra.googlegroups.com> Hello If I have an extension module and want to use an exception I can do by declaring the exception as "extern PyObject *PyExc_FooError" in the object files if I then link those together inside a module where the module has them declared the same (but no extern) and then initialises them in the PyMODINIT_FUNC using PyErr_NewException. What I can't work out however is how to then be able to raise this exception in another extension module. Just defining it as "extern" doesn't work, even if I make sure the first module -that creates the exception- gets loaded first. Because the symbol is defined in the first extension module the dynamic linker can't find it as it only seems to look in the main python executable for symbols used in dlloaded sofiles. Does anyone have an idea of how you can do this? Thanks Floris From bdesth.quelquechose at free.quelquepart.fr Sun Dec 21 14:14:49 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 21 Dec 2008 20:14:49 +0100 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> Message-ID: <494ea35c$0$12776$426a74cc@news.free.fr> r a ?crit : (snip clueless rant) > One more big complaint "THE BACKSLASH PLAGUE". ever tried regexp? Yes. exp = re.compile(r"no \problem \with \backslashes") >, or > file paths?. You mean _dos/windows_ file path separator ? It was indeed a stupid choice _from microsoft_ to choose the by then well established escape char (the backslash) as a file path separator. But hopefully, Python handles it gracefully: you can either use raw strings (which I stronly advise you learn about instead of whining) or just the traditional unix one (forward slash) instead. > All because that little backslash char is a line > continuation character, Totally clueless, as usual... Why don't you just READ THAT FUCKING MANUAL ? From Casper.Dik at Sun.COM Mon Dec 1 03:51:58 2008 From: Casper.Dik at Sun.COM (Casper H.S. Dik) Date: 01 Dec 2008 08:51:58 GMT Subject: Python surpasses Perl in popularity? References: <5e87aee0-c7fd-4e9d-befb-0cc01cee64ec@f40g2000pri.googlegroups.com> <49316c95$0$2813$742ec2ed@news.sonic.net> <49322ea2$0$2747$742ec2ed@news.sonic.net> Message-ID: <4933a5ae$0$185$e4fe514c@news.xs4all.nl> Stephane CHAZELAS writes: >It's true it was vague and misleading, >/bin is not the standard place to look for "sh" as far as the >"POSIX" standard is concerned. That doesn't mean that standard >commands (POSIX or not) cannot be found in /bin. But /bin/sh has >been made a non-standard place for "sh". It's the "legacy" >place. Those commands that have not undergone non-backward >compatible changes with POSIX can still be found in /bin, the >others are to be found in /usr/xpg/bin (for the standard >versions). The proper place is "`getconf PATH`". POSIX doesn't list any pathnames. Of course, the problem is then "where did getconf come from?". Casper -- Expressed in this posting are my opinions. They are in no way related to opinions held by my employer, Sun Microsystems. Statements on Sun products included here are not gospel and may be fiction rather than truth. From ndbecker2 at gmail.com Thu Dec 18 09:20:56 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 18 Dec 2008 09:20:56 -0500 Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> Message-ID: Tino Wildenhain wrote: > Neal Becker wrote: >> Reading some FAQ, I see that __str__ is "meant for human eyes". >> >> But it seems that: >> class X(object): >> def __str__(self): >> return "str" >> def __repr__(self): >> return "repr" >> >> x = X() >> d = {0 : x} >> print d >> {0: repr} >> >> So if __str__ is "meant for human eyes", then why isn't print using it! > > it is: > > > print x > str > > but dict just uses repr() for all its childs to print. > > T. That makes no sense to me. If I call 'print' on a container, why wouldn't it recursively print on the contained objects? Since print means call str, printing a container should recursively call str on the objects. From gandalf at shopzeus.com Thu Dec 18 10:34:38 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 18 Dec 2008 16:34:38 +0100 Subject: psycopg2 and large queries Message-ID: <494A6D8E.1050002@shopzeus.com> psycopg2 is said to be db api 2.0 compilant, but apparent it is buggy. By default, when I create a cursor with cur = conn.cursor() then it creates a cursor that will fetch all rows into memory, even if you call cur.fetchone() on it. (I tested it, see below.) I was looking for psycopg2 documentation, but I found nothing. However, I found some posts telling that named cursors do support fetching a single row at a time. Here is how to create a named cursor: cur = conn.cursor('mycursor') This is very strange, because DB API 2.0 does not have this feature. Why this feature was created, and how to use it? Not documented. Anyway, I wrote a program that uses named/nameless cursors, sets cur.arraysize to different values before callig cur.execute, then fetches all rows with fetchone(). I used the following query on a bigger table: select name from product limit 1000000 Here are the test results for fetchone(): Named cursor, arraysize=1 2613 rec/sec, query opens in 0.005 sec, uses only a few memory Named cursor, arraysize=1000 2831 rec/sec, query opens in 0.005 sec, uses only a few memory Nameless cursor, arraysize=1 41335 rec/sec, query opens in 28 sec, uses 100MB+ memory Nameless cursor, arraysize=1 39602 rec/sec, query opens in 25.8 sec, uses 100MB+ memory It is clear that named cursors have very bad performance, I cannot use them. Nameless cursors cannot be used either, because they are stressing the system, put 100% disk I/O and big memory usage, without any good reason. The only one solution I found is to use named cursors, and use fetchmany(100) instead of fetchone(). This results in fast opening (0.005 sec) of the cursor, and good speed (30 000 rec/sec, about 75% of the nameless version). (Do I really need to implement buffering in Python to be efficient???) However, this is also not usable, because named cursors do not have a ".description" property! You can try this: cur = conn.cursor('mycursor') cur.execute('select name from product limit 1000000') print repr(cur.description) # -> None This is unacceptable! This is not DB API 2.0 compilant. I have to know the names of the columns, how can I do that? What am I doing wrong? Please help me! Thanks, Laszlo p.s.: I tried to subscribe to the psycopg mailing list, but the confirmation email did not arrive in 6 hours... From ethan at stoneleaf.us Fri Dec 12 15:01:35 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 12 Dec 2008 12:01:35 -0800 Subject: newbie question: if var1 == var2: In-Reply-To: <49320E9B.9060606@gmail.com> References: <1drnn4s80telr$.1ofybdk342gmc$.dlg@40tude.net> <49320E9B.9060606@gmail.com> Message-ID: <4942C31F.5050807@stoneleaf.us> Andrew Robert wrote: > Two issues regarding script. > > You have a typo on the file you are trying to open. > > It is listed with a file extension of .in when it should be .ini . Pardon? The OPs original post used .in both in the python code and the command line. Doesn't look like a typo to me. Out of curiosity, what types of .ini files have one text string per line without = ? The ones I have seen follow this format: [section name] setting1 = a value setting2 = another value ~Ethan~ From s.selvamsiva at gmail.com Tue Dec 2 03:03:27 2008 From: s.selvamsiva at gmail.com (S.Selvam Siva) Date: Tue, 2 Dec 2008 13:33:27 +0530 Subject: Posting File as a parameter to PHP/HTML using HTTP POST Message-ID: I am trying to post file from python to php using HTTP POST method. I tried mechanize but not able to pass the file object. from mechanize import Browser br=Browser() response=br.open("http://localhost/test.php") br.select_form('form1') br['uploadedfile']=open("C:/Documents and Settings/user/Desktop/Today/newurl-ideas.txt") response=br.submit() print response.read() But, i get the error: br['uploadedfile']=open("C:/Documents and Settings/user/Desktop/Today/newurl -ideas.txt") File "C:\Python25\lib\site-packages\clientform-0.2.9-py2.5.egg\ClientForm.py", line 2880, in __setitem__ ValueError: value attribute is readonly But, When uploading is done using browser, it works. -- Yours, S.Selvam -------------- next part -------------- An HTML attachment was scrubbed... URL: From tino at wildenhain.de Mon Dec 15 07:35:43 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 15 Dec 2008 13:35:43 +0100 Subject: regex problem .. In-Reply-To: <3b10c2060812150421y1c3e7da6ha1b72c736e2a20d4@mail.gmail.com> References: <3b10c2060812150421y1c3e7da6ha1b72c736e2a20d4@mail.gmail.com> Message-ID: <49464F1F.7040703@wildenhain.de> Analog Kid wrote: > Hi All: > I am new to regular expressions in general, and not just re in python. > So, apologies if you find my question stupid :) I need some help with > forming a regex. Here is my scenario ... > I have strings coming in from a list, each of which I want to check > against a regular expression and see whether or not it "qualifies". By > that I mean I have a certain set of characters that are permissible and > if the string has characters which are not permissible, I need to flag > that string ... here is a snip ... > > flagged = list() > strs = ['HELLO', 'Hi%20There', '123123@#@'] > p = re.compile(r"""[^a-zA-Z0-9]""", re.UNICODE) > for s in strs: > if len(p.findall(s)) > 0: > flagged.append(s) > > print flagged > > my question is ... if I wanted to allow '%20' but not '%', how would my > current regex (r"""[^a-zA-Z0-9]""") be modified? You might want to normalize before checking, e.g. from urllib import unquote p=re.compile("[^a-zA-Z0-9 ]") flagged=[] for s in strs: if p.search(unquote(s)): flagged.append(s) be carefull however if you want to show the flagged ones back to the user. Best is always quote/unquote at the boundaries as appropriate. Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From mavikorsan7 at gmail.com Thu Dec 18 06:37:21 2008 From: mavikorsan7 at gmail.com (=?ISO-8859-9?Q?sevimli_arkada=FE?=) Date: Thu, 18 Dec 2008 03:37:21 -0800 (PST) Subject: www.webhizmetlerim.com Message-ID: <9b9eb8d1-a859-43cf-89a5-f52f3df6764f@r15g2000prd.googlegroups.com> Dear Readers; If you write us our web site's queue and page number at google then three of you can get prices from us.We are going to have a sweepstake for this. If you send more mails,you have more chance to win. Our competition is going to finish at 1 February 2009. Please write google 'web tasar?m' then write us that which queue and which page our web site www.webhizmetlerim.com is. Also you can help to hear your friends at your list by sending them mails for the competition. PR?CES 1.NOTEBOOK 2.MP4 3.MP3 Write us your name,surname and mail adress to www.webhizmetlerim.com communication part,then get the prize. And send this mail to your friends then they will get the prices too.Send mails every day and have more chance. From bignose+hates-spam at benfinney.id.au Mon Dec 15 00:50:01 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 15 Dec 2008 16:50:01 +1100 Subject: alt.possessive.its.has.no.apostrophe (was: Looking for the best way to translate an idiom) References: Message-ID: <87vdtmf0mu.fsf_-_@benfinney.id.au> James Stroud writes: > Yes. I think it was the British who decided that the apostrophe rule > for "it" would be reversed from normal usage relative to just about > every other noun. Remember that ?it? is a pronoun. I see no reversal: he she we they me you it he's she's we're they're I'm you're it's his hers ours theirs mine yours its No reversal there; the apostrophe rule is consistent. All pronouns take an apostrophe *only* for abbreviating the contraction of ?foo is? or ?foo has? or some other two-word form. The possessive never takes an apostrophe on a pronoun. You can find plenty of inconsistencies and rules with exceptions in the English language, but ?possessive pronoun doesn't use an apostrophe? isn't one of them. -- \ ?Don't you try to outweird me, I get stranger things than you | `\ free with my breakfast cereal.? ?Zaphod Beeblebrox, _The | _o__) Restaurant At The End Of The Universe_, Douglas Adams | Ben Finney From james at agentultra.com Sun Dec 21 22:40:53 2008 From: james at agentultra.com (J Kenneth King) Date: Sun, 21 Dec 2008 22:40:53 -0500 Subject: Are Django/Turbogears too specific? References: Message-ID: <85tz8wop16.fsf@agentultra.com> Gilles Ganault writes: > Hi > > I'd like to rewrite a Web 2.0 PHP application in Python with AJAX, and > it seems like Django and Turbogears are the frameworks that have the > most momentum. > > I'd like to use this opportunity to lower the load on servers, as the > PHP application wasn't built to fit the number of users hammering the > servers now. > > I'm concerned, though, that these frameworks they may be too specific > to the tasks they were originally developped for (news articles, > AFAIK). Do you think I should just use eg. CherryPy and some basic > AJAX? > > Thank you for any feedback. They're not "specific" in the sense that they only build certain types of applications. However, they do package their own batteries and expect applications to be designed a certain way. As long as you drink the kool-aid, everything is smooth sailing. That's what any "framework" banks on -- being useful to 85% of the web applications; not all. Even if they advertise themselves as such, it's just not true. My suggestion is web.py -- It too has its own set of conventions and philosophies, but in my experience it is the most loosely coupled in terms of internal dependencies. Import exactly what you want to use and deploy it the way that suits you. It gives you batteries but you have to pick and choose how to put the pieces together. Therefore, it takes a little longer to get running, but IMO that is the most flexibility you can ask for without writing your own servers and frameworks. Cheers. From ldo at geek-central.gen.new_zealand Fri Dec 5 05:17:42 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 05 Dec 2008 23:17:42 +1300 Subject: Don't you just love writing this sort of thing :) References: <0148b086$0$20670$c3e8da3@news.astraweb.com> Message-ID: In message <0148b086$0$20670$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > ... stupid formatting ... withallthedifferenttermsruntogetherintoonelinesoyoudon'tknowwhereoneendsandtheotherbeginsifthat'showyouliketowritecodefinethat'snothowIliketodoit From jeremiah.dodds at gmail.com Tue Dec 23 05:35:38 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Tue, 23 Dec 2008 05:35:38 -0500 Subject: Beep In-Reply-To: References: <47c890dc0812211620h6c19086dhf3a14a662a49fdf6@mail.gmail.com> <6r8qqpFq8rU1@mid.individual.net> Message-ID: <12cbbbfc0812230235l549f48dj2f367f614f32a50e@mail.gmail.com> On Mon, Dec 22, 2008 at 10:42 PM, Jeffrey Barish wrote: > > > On Ubuntu, it is possible to set visual and audible beeps separately. When > I set both, I get the visual beep, but not the audible one. It's not a > Python issue -- so I should take this thread to Ubuntu -- because I observe > this behavior even when I hit backspace at the beginning of a line in a > terminal. > -- > Jeffrey Barish > > -- > http://mail.python.org/mailman/listinfo/python-list > Well, I would try printing a bell character in another language, say ruby or perl, or just in the terminals on the machines that won't print them in python. If you get a bell from those, it's likely some issue with your python installation, otherwise it's likely a problem with Ubuntu configuration somewhere. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ibpet11 at gmail.com Wed Dec 31 04:52:51 2008 From: ibpet11 at gmail.com (ibpet11 at gmail.com) Date: Wed, 31 Dec 2008 01:52:51 -0800 (PST) Subject: SDC lite Message-ID: <0be22daf-17e4-4d62-962f-f3d7658107bf@r34g2000vbp.googlegroups.com> Did anybody have idea on how and what SDC lite looks like and how it works for data conversion. From trfilmographer at gmail.com Fri Dec 12 12:47:39 2008 From: trfilmographer at gmail.com (trfilmographer at gmail.com) Date: Fri, 12 Dec 2008 09:47:39 -0800 (PST) Subject: newbie question... Message-ID: Hi! Im new at python and I just want to know if (and how) it is possible to send parameters to a program. what I mean is that when we start python I can call a file that should be run like this: python myfile.py can I send additional parameters along with it? like::: python myfile.py myVar1 myVar2 Thanks!!! From rlight2 at gmail.com Wed Dec 24 13:24:42 2008 From: rlight2 at gmail.com (Ross) Date: Wed, 24 Dec 2008 10:24:42 -0800 (PST) Subject: Custom C Exception Subclasses References: <41f291ff-d7bd-4334-8689-636e95524cdc@b38g2000prf.googlegroups.com> Message-ID: <2c6c51ee-ba22-4c46-b6f6-c4d41af7ad83@x16g2000prn.googlegroups.com> On Dec 24, 9:24 am, "Gabriel Genellina" wrote: > In fact you can, you could store those pointers as attributes of the > exception object, using a PyCObject. Excellent. I was not aware of the PyCObject type. > Accessing those attributes isn't as easy as doing exc->field, but I think > it's easy enough. Inheriting from some exception type requires you to > define the type structure and fill it right, and IMHO is a lot harder. > > Perhaps there is a misunderstanding here. To subclass a type, you need the > type, not an instance of such type. Ah yes, I probably should have been more clear. In the docs about subclassing, they use a PyListObject as the first field of the Shoddy struct so that the fields are filled in correctly. Now, how would I go about adding methods to a custom exception object? From xi at gamma.dn.ua Sun Dec 28 19:30:36 2008 From: xi at gamma.dn.ua (Kirill Simonov) Date: Mon, 29 Dec 2008 02:30:36 +0200 Subject: [ANN] PyYAML-3.07: YAML parser and emitter for Python Message-ID: <49581A2C.80307@gamma.dn.ua> ======================== Announcing PyYAML-3.07 ======================== A new release of PyYAML is now available: http://pyyaml.org/wiki/PyYAML Changes ======= * The emitter learned to use an optional indentation indicator for block scalars; thus scalars with leading whitespaces could now be represented in a literal or folded style. * The test suite is now included in the source distribution. To run the tests, type 'python setup.py test'. * Refactored the test suite: dropped unittest in favor of a custom test appliance. * Fixed the path resolver in the LibYAML-based dumper. * Forced an explicit document end indicator when there is a possibility of parsing ambiguity. * More setup.py improvements: the package should be usable when any combination of setuptools, Pyrex and LibYAML is installed. * Windows binary packages are statically linked against LibYAML-0.1.2. * Other minor fixes and improvements (Thank to Ingy dot Net and Andrey Somov). Resources ========= PyYAML homepage: http://pyyaml.org/wiki/PyYAML PyYAML documentation: http://pyyaml.org/wiki/PyYAMLDocumentation TAR.GZ package: http://pyyaml.org/download/pyyaml/PyYAML-3.07.tar.gz ZIP package: http://pyyaml.org/download/pyyaml/PyYAML-3.07.zip Windows installer: http://pyyaml.org/download/pyyaml/PyYAML-3.07.win32-py2.3.exe http://pyyaml.org/download/pyyaml/PyYAML-3.07.win32-py2.4.exe http://pyyaml.org/download/pyyaml/PyYAML-3.07.win32-py2.5.exe http://pyyaml.org/download/pyyaml/PyYAML-3.07.win32-py2.6.exe PyYAML SVN repository: http://svn.pyyaml.org/pyyaml Submit a bug report: http://pyyaml.org/newticket?component=pyyaml YAML homepage: http://yaml.org/ YAML-core mailing list: http://lists.sourceforge.net/lists/listinfo/yaml-core About PyYAML ============ YAML is a data serialization format designed for human readability and interaction with scripting languages. PyYAML is a YAML parser and emitter for Python. PyYAML features a complete YAML 1.1 parser, Unicode support, pickle support, capable extension API, and sensible error messages. PyYAML supports standard YAML tags and provides Python-specific tags that allow to represent an arbitrary Python object. PyYAML is applicable for a broad range of tasks from complex configuration files to object serialization and persistance. Example ======= >>> import yaml >>> yaml.load(""" ... name: PyYAML ... description: YAML parser and emitter for Python ... homepage: http://pyyaml.org/wiki/PyYAML ... keywords: [YAML, serialization, configuration, persistance, pickle] ... """) {'keywords': ['YAML', 'serialization', 'configuration', 'persistance', 'pickle'], 'homepage': 'http://pyyaml.org/wiki/PyYAML', 'description': 'YAML parser and emitter for Python', 'name': 'PyYAML'} >>> print yaml.dump(_) name: PyYAML homepage: http://pyyaml.org/wiki/PyYAML description: YAML parser and emitter for Python keywords: [YAML, serialization, configuration, persistance, pickle] Copyright ========= The PyYAML module is written by Kirill Simonov . PyYAML is released under the MIT license. From fakeaddress at nowhere.org Thu Dec 4 14:56:10 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 04 Dec 2008 11:56:10 -0800 Subject: python an sqlite objects In-Reply-To: References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <18742.47391.389709.119341@montanaro-dyndns-org.local> <49382153.80604@mrabarnett.plus.com> Message-ID: skip at pobox.com wrote: > >> # Ensure that we're running Python 3 or later. > >> import sys > >> assert int(sys.version.split()[0].split('.')[0]) >= 3 > >> # If there's a better way to chek, please tell. [...] > Why split at all? Just use sys.version_info: > > >>> import sys > >>> assert sys.version_info[0] > 2, sys.version_info > Traceback (most recent call last): > File "", line 1, in ? > AssertionError: (2, 4, 5, 'final', 0) Thanks. Yes, that's better. To verify that the running version of Python is 3 or higher, import sys assert sys.version_info[0] >= 3 -- --Bryan From jeremiah.dodds at gmail.com Sat Dec 6 20:56:22 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Sat, 6 Dec 2008 20:56:22 -0500 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: <12cbbbfc0812061756l635b84deh831c83cdb7808450@mail.gmail.com> On Fri, Dec 5, 2008 at 9:21 PM, Daniel Fetchinson wrote: > > The proposal is to allow this: > > class C: > def self.method( arg ): > self.value = arg > return self.value > > instead of this: > > class C: > def method( self, arg ): > self.value = arg > return self.value > > I.e. explicit self stays only the syntax is slightly different and may > seem attractive to some. As pointed out by Guido classmethods would > work similarly: > > class C: > @classmethod > def cls.method( arg ): > cls.val = arg > return cls.val > > -1. It doesn't solve a real problem, just shuffles syntax around with very little, if any, gain in clarity. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Tue Dec 30 20:16:24 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Dec 2008 01:16:24 GMT Subject: string in files References: <62075511-08ad-405a-a3af-2da8d2f22c50@v39g2000pro.googlegroups.com> Message-ID: <016abee9$0$6988$c3e8da3@news.astraweb.com> On Tue, 30 Dec 2008 11:53:17 +0100, Glauco wrote: >> thanks brother >> i mean how do i particularly assign (u = this) >> (y = is).... >> in the strings up there. i have been able to split strings with any >> character sign. >> >> > > If i'm not wrong this is simple with RE: If that's your idea of "simple", I'd hate to see what you consider complicated! *Simple* is just using the split method. a, b, c, d, e, f = 'this is a python coding group'.split() -- Steven From Scott.Daniels at Acm.Org Sun Dec 14 19:43:26 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 14 Dec 2008 16:43:26 -0800 Subject: Python shows up checking votes Message-ID: I just saw an interesting post -- The video linked to on http://www.blog.wired.com in Kim Zetter's "Threat Level" blog, there is a video describing the software used to provide open access to ballots after an election. The software used for this system is an open-source system written in Python. Turns out they found election system failures in California's Humboldt County using this software. It also turns out that the failure was not large enough to change the result of any of the races or propositions this time. By Kim Zetter's blog for 8-Dec-08 entitled "Unique Transparency Program Uncovers Problems with Voting Software" --Scott David Daniels Scott.Daniels at Acm.Org From inq1ltd at inqvista.com Fri Dec 5 16:08:56 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Fri, 05 Dec 2008 16:08:56 -0500 Subject: Problems running on hp duo Pentium R processor In-Reply-To: <77895c1d0812051227o104ff233m7f16410e3cf8b392@mail.gmail.com> References: <200809221443.25765.inq1ltd@inqvista.com> <200812051502.26421.inq1ltd@inqvista.com> <77895c1d0812051227o104ff233m7f16410e3cf8b392@mail.gmail.com> Message-ID: <200812051608.56335.inq1ltd@inqvista.com> On Friday 05 December 2008 15:27, Kevin Kelley wrote: > If they are running standard Win XP (Home or Pro), > as opposed to 64-bit Win XP, then whether or not the > CPU supports the IA64 instruction set really doesn't > matter. As far as I know every Intel Core2 and > Pentium Dual-Core CPU since ~ 2006 has supported > 64bit instructions, even the Atom is 64bit. Also, > the "R" is for Registered Trademark (of Pentium), > it's not part of the name/model > (http://ark.intel.com/cpu.aspx?groupId=33925). > > Kevin Kevin , I'm trying to find out why my program gets an import error on only one machine. Is there any problem with python running on a 64 bit Architecture machine or is it something specific to this one HP machine? None of my other clients have had this problem, nor have I on any machine that I've tried tested it on. jim-on-linux > > On Fri, Dec 5, 2008 at 2:02 PM, jim-on-linux wrote: > > Python help, > > > > In September I wrote: > > I have a number of clients running a program built > > with python 2.5. One has just purchased an HP > > with a duo core Pentium R processor E2200, 2.2G > > with .99g ram. > > > > Only on the new HP, when they try to print they > > get an import error; > > File win32ui.pyc line 12, in > > File win32ui.pyc, line 10, in _load > > ImportError: DLL load failed: The specified > > module could not be found. > > > > It turns out that the E2200 processor is 64 bit > > architecture. > > > > What are my options? > > > > I've run DependecyWalker, > > They are using Win XP Service Pack 2 > > > > > > > > jim=on-linux > > > > > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-lis > >t From skip at pobox.com Mon Dec 8 13:57:10 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 8 Dec 2008 12:57:10 -0600 Subject: Public imports In-Reply-To: <66ecdd96-38dd-4054-8009-e145c0a78316@o40g2000prn.googlegroups.com> References: <9623b0a3-7053-41f1-b116-0cd5e54f39e9@v13g2000vbb.googlegroups.com> <493d1ec0$0$32048$426a34cc@news.free.fr> <66ecdd96-38dd-4054-8009-e145c0a78316@o40g2000prn.googlegroups.com> Message-ID: <18749.28166.594048.397131@montanaro-dyndns-org.local> M?rcio> So, no chance of doing this: M?rcio> # "A.py" M?rcio> from __future__ import division, with_statement M?rcio> # "B.py" M?rcio> from A import * M?rcio> print 1 / 2 M?rcio> ...and printing 0.5, right? Too bad :) "from __future__ ..." isn't really an import statement in the usual sense of the term. It affects the byte code compiler immediately and I believe only when using that syntax. That it actually adds a name to the module's namespace is not really used (at least, not often). -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From mrkafk at gmail.com Mon Dec 29 10:29:43 2008 From: mrkafk at gmail.com (mk) Date: Mon, 29 Dec 2008 16:29:43 +0100 Subject: multiprocessing vs thread performance In-Reply-To: References: Message-ID: Christian Heimes wrote: > mk wrote: >> Am I doing smth wrong in code below? Or do I have to use >> multiprocessing.Pool to get any decent results? > > You have missed an important point. A well designed application does > neither create so many threads nor processes. Except I was not developing "well designed application" but writing the test the goal of which was measuring the thread / process creation cost. > The creation of a thread > or forking of a process is an expensive operation. Sure. The point is, how expensive? While still being relatively expensive, it turns out that in Python creating a thread is much, much cheaper than creating a process via multiprocessing on Linux, while this seems to be not necessarily true on Mac OS X. > You should use a pool > of threads or processes. Probably true, except, again, that was not quite the point of this exercise.. > The limiting factor is not the creation time but the communication and > synchronization overhead between multiple threads or processes. Which I am probably going to test as well. From robin at reportlab.com Mon Dec 29 11:04:55 2008 From: robin at reportlab.com (Robin Becker) Date: Mon, 29 Dec 2008 16:04:55 +0000 Subject: Windows SSH (remote execution of commands) - Python Automation In-Reply-To: <7FAD6FCE52421841A11B441DEF3A88CA01F09006@ZMY16EXM70.ds.mot.com> References: <7FAD6FCE52421841A11B441DEF3A88CA01F09006@ZMY16EXM70.ds.mot.com> Message-ID: <4958F527.7030805@chamonix.reportlab.co.uk> Narasimhan Raghu-RBQG84 wrote: > Hi experts, > > I am looking for some information on how to automate remote login to a > UNIX machine using ssh from a windows XP box. > > Possible way: > > 1. Use putty (or any other ssh client from windows XP). -- Can be > automated with command line parameters. The problem is that I am able to > login - Putty window opens up as well. But obviously I am unable to run > any commands in that. I need to find something like a handle to that > Putty window so that I can execute commands there. > > Can anyone provide me some help in achieving this ? > > > Thanks, > > -- > Raghu ........ I have been using plink (companion to putty) without any problem eg plink app1 ls -l where app1 is defined by putty (as a connection) and ls -l etc etc are command args. I have modified the py package's SshGateway to use plink under windows and to allow very reasonable remote python behaviour. -- Robin Becker From s.bez_spamu at remove.that.informa.and.that.pl Thu Dec 4 09:32:31 2008 From: s.bez_spamu at remove.that.informa.and.that.pl (Sebastian Kaliszewski) Date: Thu, 04 Dec 2008 15:32:31 +0100 Subject: Python advocacy ... HELP! In-Reply-To: <5f8c1a52-545e-402e-863a-acdf23d04c78@h20g2000yqn.googlegroups.com> References: <5f8c1a52-545e-402e-863a-acdf23d04c78@h20g2000yqn.googlegroups.com> Message-ID: Michael_D_G wrote: > how do I refute > the notion that Python > is a "marginal" language because according to TOBIE it only less than > a 6% market share. According to the same TIOBE, C++ has less than 11%. So it must be niche then as well :) -- "Never underestimate the power of human stupidity" -- L. Lang -- http://www.tajga.org -- (some photos from my travels) From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 23 04:11:29 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 23 Dec 2008 10:11:29 +0100 Subject: Python's popularity In-Reply-To: References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <494fef38$0$12781$426a74cc@news.free.fr> Message-ID: <4950ab3b$0$27404$426a74cc@news.free.fr> Steve Holden a ?crit : > walterbyrd wrote: > [...]>> Fooled by version numbers ? >> No, but I am giving django the benefit of the doubt. The django >> project told people all along that django was not to be considered >> production ready before 1.0. I will accept that some people decided to >> wait until 1.0 came out to do any production development. Maybe django >> is only lagging because 1.0 just came out? >> > The Django people said no such thing. They maintained the trunk as > stable - they test so well that many people did indeed rely on the trunk > for production systems. Indeed - my first Django app has been in production for more than 3 years now. (snip) >>> My actual CTO is a big Ruby/Rails fan, yet he settled on Python/Django >>> for our current 'big' project. Wonder why ? >> Not knowing much about RoR: yes, I wonder why? Is it because python >> has a cleaner syntax? Or what? > > It's because he decided that Django was the best tool for the particular > job, making him unusually open-minded for a member of the pointy-haired > species. Being a CTO doesn't necessarily makes you pointy-haired !-) We're a small shop (12 peoples), and the guy is a developper too (and yes, an active one). > Unlike some on this list he doesn't let his prejudices blind > him to reality. Yes - that was the point. From clp at rebertia.com Tue Dec 9 10:57:39 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 9 Dec 2008 07:57:39 -0800 Subject: 'pretty print' for built in types In-Reply-To: <051e3a97-b9bc-4a67-8896-93628ca19f59@r15g2000prd.googlegroups.com> References: <051e3a97-b9bc-4a67-8896-93628ca19f59@r15g2000prd.googlegroups.com> Message-ID: <47c890dc0812090757s65771a5cr50e6a0b3bbb6cc71@mail.gmail.com> On Tue, Dec 9, 2008 at 7:31 AM, Robert Dailey wrote: > Hi, > > Is there a built in way to 'pretty print' a dict, list, and tuple > (Amongst other types)? Dicts probably print the ugliest of them all, > and it would be nice to see a way to print them in a readable way. I > can come up with my own function to do this, but I don't want to do > this if I don't have to. There's the `pprint` module in the std lib: http://docs.python.org/library/pprint.html Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > From Slaunger at gmail.com Wed Dec 10 06:37:47 2008 From: Slaunger at gmail.com (Slaunger) Date: Wed, 10 Dec 2008 03:37:47 -0800 (PST) Subject: Best way to report progress at fixed intervals References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> <817384d5-5f68-4c1f-9560-0bc7b7d2b1e3@v5g2000prm.googlegroups.com> <6ccb77a2-a3f1-4b6b-900c-d4626be9e939@s1g2000prg.googlegroups.com> <93371329-5989-4f96-ac79-58a54ba6b07f@35g2000pry.googlegroups.com> Message-ID: <8e368e62-4c0f-46ad-832d-f83f88228511@i20g2000prf.googlegroups.com> On 10 Dec., 12:08, eric wrote: > Don't mind if I give my shot ? > > def work(i): > ? ? """ > ? ? Dummy process function, which takes a random time in the interval > ? ? 0.0-0.5 secs to execute > ? ? """ > ? ? print "Work step %d" % i > ? ? time.sleep(0.5 * random.random()) > > def workAll(work, verbose=True, max_iter=20, progress_interval=1.0): > ? ? ''' > ? ? pass the real job as a callable > ? ? ''' > ? ? progress = time.time() > ? ? for i in range(max_iter): # do the requested loop > ? ? ? ? work(i) > ? ? ? ? if verbose: > ? ? ? ? ? ? print "Work through all %d steps reporting progress every > %3.1f secs..." %(max_iter, progress_interval) > ? ? ? ? interval = time.time()-progress > ? ? ? ? if interval>progress_interval: > ? ? ? ? ? ? print "Processed %d of %d at pace %s" % (i, max_iter, > interval) > ? ? ? ? ? ? progress +=interval > > if __name__=="__main__": > ? ? workAll(work, False) > > It's works fine, and the "pace" is 'almost' the required one. You earn > a no-thread-mess, and cleaner alg. > > But the loop is controlled by the caller (the WorkAll function) this > is also called ass-backward algorithm, and you cannot expect > algorithms to be assbackward (even if it's the best way to implement > them). > > You can use the yield statement, to turn ?easilly your alg into a > nice, stopable assbackward algo: > > def work(): > ? ? """ > ? ? Dummy process function, which takes a random time in the interval > ? ? 0.0-0.5 secs to execute > ? ? """ > ? ? for i in range(50): > ? ? ? ? print "Work step %d" % i > ? ? ? ? time.sleep(0.5 * random.random()) > ? ? ? ? yield i # kind-of "publish it and let the caller do whatever > it want s (good practice anyway) > > def workAll(work, verbose=True, max_iter=20, progress_interval=1.0): > ? ? ''' > ? ? pass the real job as a generator > ? ? ''' > ? ? progress = time.time() > ? ? i = 0 > ? ? for w in work: # do the requested loop > ? ? ? ? if verbose: > ? ? ? ? ? ? print "Work through all %d steps reporting progress every > %3.1f secs..." %(max_iter, progress_interval) > ? ? ? ? interval = time.time()-progress > ? ? ? ? if interval>progress_interval: > ? ? ? ? ? ? print "Processed %d at pace %s" % (w, interval) > ? ? ? ? ? ? progress +=interval > ? ? ? ? if i>=max_iter: > ? ? ? ? ? ? work.close() > ? ? ? ? i+=1 > > if __name__=="__main__": > ? ? workAll(work(), False) ? ? # note the calling difference > > hope it helps. Hi eric, No, I certainly don't mind you giving a try ;-) I actually started out doing something like your first version here, but I am a little annoyed by the fact that the progress report interval is not a sure thing. For instance in my real applications, I have seldomly occuring work steps, which may take significantly longer than the progress_interval, and I'd like to let it keep reporting that, oh, I am still woking, albeit on the same work step, to maintain a sense of the script being alive. I like you generator approach though. Anyway, I have now given my own proposal another iteration based on what I have seen here (and my personal preferences), and I have come up with this: ============ src ======================= """ Test module for testing generic ways of displaying progress information at regular intervals. """ import random import threading import time def work(i): """ Dummy process function, which takes a random time in the interval 0.0-0.5 secs to execute """ print "Work step %d" % i time.sleep(0.5 * random.random()) def workAll(verbose=True, max_iter=20, progress_interval=1.0): class ProgressReporter(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.setDaemon(True) self.i = 0 self.max = max_iter self.start_timer = verbose self.progress_interval = progress_interval def run(self): while self.start_timer: print "Processed %d of %d." % (self.i + 1, self.max) time.sleep(self.progress_interval) p = ProgressReporter() if verbose: print "Work through all %d steps reporting every %3.1f secs..." % \ (max_iter, progress_interval) p.start() for i in xrange(max_iter): work(i) p.i = i if verbose: print "Finished working through %d steps" % max_iter if __name__ == "__main__": workAll() ========= end src ================================ I like this much better than my own first attempt in my initial post on this thread. -- Slaunger From 00515879256 at fastwebnet.it Tue Dec 30 05:53:17 2008 From: 00515879256 at fastwebnet.it (Glauco) Date: Tue, 30 Dec 2008 11:53:17 +0100 Subject: string in files In-Reply-To: <62075511-08ad-405a-a3af-2da8d2f22c50@v39g2000pro.googlegroups.com> References: <62075511-08ad-405a-a3af-2da8d2f22c50@v39g2000pro.googlegroups.com> Message-ID: > > thanks brother > i mean how do i particularly assign (u = this) > (y = is).... > in the strings up there. i have been able to split strings with any > character sign. > If i'm not wrong this is simple with RE: In [1]: st = 'this is a python coding group' In [2]: import re In [3]: re.compile( "(?P.*) (?P.*) (?P.*) (?P.*) (?P.*) (?P.*)" ) Out[3]: <_sre.SRE_Pattern object at 0x9e93ac0> In [4]: rule = re.compile( "(?P.*) (?P.*) (?P.*) (?P.*) (?P.*) (?P.*)" ) In [5]: m = rule.match( st ) In [6]: dir(m) Out[6]: ['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict', 'groups', 'span', 'start'] In [7]: m.groupdict().items() Out[7]: [('si', 'group'), ('second', 'is'), ('t', 'a'), ('fi', 'coding'), ('fo', 'python'), ('first', 'this')] In [8]: dict(m.groupdict().items()) Out[8]: {'fi': 'coding', 'first': 'this', 'fo': 'python', 'second': 'is', 'si': 'group', 't': 'a'} Glauco From wuwei23 at gmail.com Mon Dec 8 23:31:38 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 8 Dec 2008 20:31:38 -0800 (PST) Subject: built-in functions as class attributes References: <75fdbf34-34d9-4373-bbe0-7e3f76dc4c3f@x38g2000yqj.googlegroups.com> Message-ID: <0631fe83-e857-46c0-ae2d-39fbf1febced@v39g2000pro.googlegroups.com> On Dec 8, 8:46?pm, Mark Dickinson wrote: > Here's a curiosity: ?after > > def my_hex(x): > ? ? return hex(x) > > one might expect hex and my_hex to be interchangeable > in most situations. ?But (with both Python 2.x and 3.x) > I get: > > >>> def my_hex(x): return hex(x) > ... > >>> class T(object): f = hex > ... > >>> class T2(object): f = my_hex > ... > >>> T().f(12345) > '0x3039' > >>> T2().f(12345) > > Traceback (most recent call last): > ? File "", line 1, in > TypeError: my_hex() takes exactly 1 argument (2 given) > [36412 refs] You're attaching 'my_hex' as a method to T2, which by default will automatically try to pass in the instance to 'f' when called. This is why you explicitly declare 'self' as the first argument for methods. And as Peter's post points out, this behaviour doesn't happen with built-in functions. However, when attaching 'my_hex', you can explicitly state that you don't want this behaviour by using the 'staticmethod' decorator: >>> def my_hex(x): return hex(x) ... >>> class T2(object): f = staticmethod(my_hex) ... >>> T2().f(12345) '0x3039' Hope this helps. From rt8396 at gmail.com Mon Dec 1 23:18:47 2008 From: rt8396 at gmail.com (r) Date: Mon, 1 Dec 2008 20:18:47 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> Message-ID: alex23, Ok...you don't like my idea...so why keep responding? ajaksu, You insulted me and accused me of trolling, but it looks like your interested. And you also included links. I think your really on board and just can't say it yet *wink*. Thank You Aaron, I agree to disagree with you...although you make some good points... and welcome your views on Lasch's reference to the pitfalls of a Narcissistic society. At least you DO know how to engage in intelligent conversation to the benefit of both parties, and not just flame. Thank you James, By far the most positive post since Greg's. I agree with your overview and welcome your constructive criticism. Thank You friend So I would defiantly say things are starting to turn. The butterfly effect is transforming my crazy idea to garner support for a SU Python integration into maybe becoming reality. I still have hope! All i need is one or two serious people and we could do this. I know you're out there. PS hey...even alex23's post are a little less mean. Either I am wearing him down or he is beginning to believe :) I would love to have you on board alex... i'm thinking... bouncer xD From gslindstrom at gmail.com Thu Dec 4 09:37:10 2008 From: gslindstrom at gmail.com (greg) Date: Thu, 4 Dec 2008 06:37:10 -0800 (PST) Subject: RELEASED Python 3.0 final References: Message-ID: On Dec 3, 7:51?pm, Barry Warsaw wrote: > On behalf of the Python development team and the Python community, I ? > am happy to announce the release of Python 3.0 final. Way to go and congratulations! --greg From eric at ericaro.net Fri Dec 5 09:21:04 2008 From: eric at ericaro.net (eric) Date: Fri, 5 Dec 2008 06:21:04 -0800 (PST) Subject: A more pythonic way of writting Message-ID: <35d176ed-df5f-46b4-8321-4814fcc4398c@f3g2000yqf.googlegroups.com> Hi, I've got this two pieces of code that works together, and fine def testit(): for vals in [[i&mask==mask for mask in [1<', flag(*vals) def flag(IGNORECASE=False, LOCALE=False, MULTILINE=False, DOTALL=False, UNICODE=False, VERBOSE=False): vals = [IGNORECASE, LOCALE, MULTILINE, DOTALL, UNICODE, VERBOSE] filtered = map( lambda m:m[1],filter( lambda m: m[0], zip(vals, 'iLmsux'))) return '?'+''.join( filtered ) testit() but I'm not proud of the way it is written. I dont find it very pythonic. I have to multiplex (using zip) bool and value, filter using only the bool, and demultiplex later using map the first simply parses all the possible combination of 6 boolean (can't hardly be made simpler) the second function, should simply return a string based on the boolean value i, L, m, s, u, x, True, False, False, True, True, False = ?isu that's should take only one line, shouldn't it? any idea ? From kyosohma at gmail.com Tue Dec 30 15:01:09 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 30 Dec 2008 12:01:09 -0800 (PST) Subject: embedding python in wxpython References: <191280cf-ecf9-4135-9737-9923061855d1@t39g2000prh.googlegroups.com> Message-ID: <26066df6-3983-45c7-87eb-81df570ff582@i18g2000prf.googlegroups.com> On Dec 30, 1:52?pm, 5lvqbw... at sneakemail.com wrote: > Hi, I've looked around for a way to allow a python console from within > a wxPython application, but have only found stuff on embedded/ > extending python with C/C++ or wxWidgets in C++, but not wxPython. > > Is this easy to do? ?Can someone point me in the right direction? > > Also, typically when you embed a scripting language into a larger > application, how do you get the console environment to share data with > the larger application? > > For instance, if the application has some gui stuff (for example > clicking on a object and dragging it around), how do you get > "object.select(x,y)" to print out on the console, and vice-versa: the > object gets selected if the user types "object.select(x,y)"? > > I'd like the console to be a bidirectional representation of what's > going on in the gui, plus a general purpose evaluation environment > where you can manipulate application data via some api which is > automatically exposed to the console when the application opens up. > > I'm looking for high-level hints/strategies/directions. > > Thank you > Michael You should ask the guys on the wxPython list for pointers: http://wxpython.org/maillist.php I'm pretty sure I've seen it discussed there before. They already have PyShell and PyCrumb that you could probably use within your program. The wxPython includes demos of them and lots of other widgets. Mike From atagar1 at gmail.com Wed Dec 10 03:46:37 2008 From: atagar1 at gmail.com (Damian Johnson) Date: Wed, 10 Dec 2008 00:46:37 -0800 Subject: Curses Blank Background Message-ID: Does anyone know how to instruct the Python curses bindings to leave the background alone (use the default terminal background)? I'm interested in keeping my semi-transparent background which curses can't replicate. This question was raised on this list before ( http://mail.python.org/pipermail/python-list/2001-July/094581.html) but it never got a reply. From the ncurses man page it looks like this functionality would be mapped to -1 but the Python curses module uses -1 for ERR. I'm new to curses so my apologies if I'm missing something obvious. Cheers! -Damian -------------- next part -------------- An HTML attachment was scrubbed... URL: From gnewsg at gmail.com Sun Dec 28 12:33:00 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sun, 28 Dec 2008 09:33:00 -0800 (PST) Subject: How to "kill" orphaned threads at program exit Message-ID: Hi, I know that it's not possible to "kill" threads but I'm wondering if does exist some workaround for my problem. I have a test suite which does a massive usage of threads. Sometimes happens that one test fails, the test suite keeps running until the end, and when it's finished the program hangs on and the only way to stop is to kill it manually. I noticed that, at the end of the program, I can call threading.enumerate() and see the pending thread objects: def test_main(): ... start_suite() print threading.enumerate() I was wondering if I can do anything with that. I took a look at test/test_support which has threading_setup() and threading_cleanup() functions. Could such functions be useful to me? Thanks in advance, --- Giampaolo http://code.google.com/p/pyftpdlib/ From carsten.kraus at gmail.com Tue Dec 23 08:44:32 2008 From: carsten.kraus at gmail.com (carsn) Date: Tue, 23 Dec 2008 05:44:32 -0800 (PST) Subject: PIL - font kerning Message-ID: Hey all, anybody know, if there?s a way to specify the kerning of a font, when you draw text with PIL? I?d like to achieve the same effect that you get, when you set a negative kerning in Gimp/Photshop - ie. reduce the spacing between glyphs. Can PIL do that or do I use another lib for that? Thx for any pointers & some nice xmas days to U all! carsten From gneuner2 at comcast.net Mon Dec 8 17:40:58 2008 From: gneuner2 at comcast.net (George Neuner) Date: Mon, 08 Dec 2008 17:40:58 -0500 Subject: Mathematica 7 compares to other languages References: <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> Message-ID: <8evqj4p342jvcma5saibf54thv7075r88g@4ax.com> On Sun, 7 Dec 2008 14:53:49 -0800 (PST), Xah Lee wrote: >The phenomenon of creating code that are inefficient is proportional >to the highlevelness or power of the lang. In general, the higher >level of the lang, the less possible it is actually to produce a code >that is as efficient as a lower level lang. This depends on whether someone has taken the time to create a high quality optimizing compiler. >For example, the level or power of lang can be roughly order as >this: > >assembly langs >C, pascal >C++, java, c# >unix shells >perl, python, ruby, php >lisp >Mathematica According to what "power" estimation? Assembly, C/C++, C#, Pascal, Java, Python, Ruby and Lisp are all Turing Complete. I don't know offhand whether Mathematica is also TC, but if it is then it is at most equally powerful. Grammatic complexity is not exactly orthogonal to expressive power, but it is mostly so. Lisp's SEXPRs are an existence proof that a Turing powerful language can have a very simple grammar. And while a 2D symbolic equation editor may be easier to use than spelling out the elements of an equation in a linear textual form, it is not in any real sense "more powerful". >the lower level the lang, the longer it consumes programer's time, but >faster the code runs. Higher level langs may or may not be crafted to >be as efficient. For example, code written in the level of langs such >as perl, python, ruby, will never run as fast as C, regardless what >expert a perler is. There is no language level reason that Perl could not run as fast as C ... it's just that no one has cared to implement it. >C code will never run as fast as assembler langs. For a large function with many variables and/or subcalls, a good C compiler will almost always beat an assembler programmer by sheer brute force - no matter how good the programmer is. I suspect the same is true for most HLLs that have good optimizing compilers. I've spent years doing hard real time programming and I am an expert in C and a number of assembly languages. It is (and has been for a long time) impractical to try to beat a good C compiler for a popular chip by writing from scratch in assembly. It's not just that it takes too long ... it's that most chips are simply too complex for a programmer to keep all the instruction interaction details straight in his/her head. Obviously results vary by programmer, but once a function grows beyond 100 or so instructions, the compiler starts to win consistently. By the time you've got 500 instructions (just a medium sized C function) it's virtually impossible to beat the compiler. In functional languages where individual functions tend to be much smaller, you'll still find very complex functions in the disassembly that arose from composition, aggressive inlining, generic specialization, inlined pattern matching, etc. Here an assembly programmer can quite often match the compiler for a particular function (because it is short), but overall will fail to match the compiler in composition. When maximum speed is necessary it's almost always best to start with an HLL and then hand optimize your optimizing compiler's output. Humans are quite often able to find additional optimizations in assembly code that they could not have written as well overall in the first place. George From xahlee at gmail.com Thu Dec 11 13:28:31 2008 From: xahlee at gmail.com (Xah Lee) Date: Thu, 11 Dec 2008 10:28:31 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <5ebe5a7d-cbdf-4d66-a816-a7d2a0a273c9@40g2000prx.googlegroups.com> Message-ID: <0434d1c7-809a-45bf-b244-d7f79aa37746@s9g2000prm.googlegroups.com> On Dec 11, 12:32?am, Gerard flanagan wrote: > Xah Lee wrote: > > On Dec 10, 2:47 pm, John W Kennedy wrote: > >> Xah Lee wrote: > >>> In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, > >>> you'll have 50 or hundreds lines. > [...] > > > Thanks to various replies. > > > I've now gather code solutions in ruby, python, C, Java, here: > > > ? A Example of Mathematica's Expressiveness > > ?http://xahlee.org/UnixResource_dir/writ/Mathematica_expressiveness.html > > > now lacking is perl, elisp, which i can do well in a condensed way. > > It'd be interesting also to have javascript... > > mmm, stone soup... > > javascript: > > var map = function(fn, a) { > ? ? ?var b = new Array(a.length); > ? ? ?for (i = 0; i < a.length; i++) { > ? ? ? ? ?b[i] = fn(a[i]); > ? ? ?} > ? ? ?return b > > }; > > var reduce = function(fn, a, init) { > ? ? ?var s = init; > ? ? ?for (i = 0; i < a.length; i++) { > ? ? ? ? ?s = fn(s, a[i]); > ? ? ?} > ? ? ?return s > > }; > > var sum = function(a) { > ? ? ?return reduce(function(x, y) { return x + y }, a, 0.0) > > }; > > var norm = function(a) { > ? ? ?var pow = Math.pow; > ? ? ?return Math.sqrt(sum(map(function(x) { return pow(x, 2) }, a))) > > }; > > var Unit = function(a) { > ? ? ?var N = norm(a); > ? ? ?return map(function(x) { return x/N }, a) > > }; thats about 15 lines. I'm pretty sure JavaScript doesn't need that many? Xah ? http://xahlee.org/ ? From pavlovevidence at gmail.com Mon Dec 22 15:10:31 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 22 Dec 2008 12:10:31 -0800 (PST) Subject: I always wonder ... References: Message-ID: On Dec 22, 11:53?am, s... at pobox.com wrote: > ... shouldn't people who spend all their time trolling be doing something > else: studying, working, writing patches which solve the problems they > perceive to exist in the troll subject? ?Is there some online troll game > running where the players earn points for generating responses to their > posts? ...shouldn't poeple who spend all their time following up to trolls, or starting new threads about trolls, being doing something else? Seriously, I participated briefly in the that thread when r still had benefit of the doubt over whether he had any credibility, but now there is no doubt that he none at all, so he's not worth replying to, so I don't. I suggest everyone else does likewise and ignores the fool. If you have to followup, at least keep your reply to something short and witty, like, "Go away, troll". Carl Banks From nospam at nospam.com Tue Dec 16 09:41:38 2008 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 16 Dec 2008 15:41:38 +0100 Subject: [cookielib] How to add cookies myself? Message-ID: <50ffk45borjjdg352t0s4lga2c26vr32uq@4ax.com> Hello I'm using urllib and urlib to download data from a web server that requires cookies. The issue I'm having, is the server uses JavaScript in the response to insert new cookies and send them with the next query, so I need to manually add a couple of cookies in the CookieJar, but I don't know how to do this and Google didn't return examples: ========= import urllib import urllib2 import cookielib headers = {'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' } cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) url = "http://www.acme.com/index.php" req = urllib2.Request(url, None, headers) response = urllib2.urlopen(req).read() print "Fetched cookies:" for index, cookie in enumerate(cj): print index, ' : ', cookie """ How to Add manually? crm_cookieEnabled=1 ctr=1 """ ========= Thanks for any tip. From kw at codebykevin.com Thu Dec 11 20:20:08 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 11 Dec 2008 20:20:08 -0500 Subject: Moving to subprocess from os.popen--pipe closes prematurely Message-ID: Hello, I'm trying to move from os.popen to using subprocess, and I'm having trouble with the pipe suddenly closing. My old code looked something like this: #build and format a list of all packages def getAllPackages(self): self.masterlist=[] for self.catname in self.catlist: time.sleep(.3) self.getpackages = os.popen('%s list --section=%s' % (self.finkpath, self.catname), 'r', os.O_NONBLOCK) for line in self.getpackages: newline = line.split('\t') rawcat = newline[0] if rawcat == '(i)': firstcat=rawcat.replace('(i)', 'outdated') elif rawcat == ' i ': firstcat=rawcat.replace('i', 'current') elif rawcat == ' p ': firstcat=rawcat.replace('p', 'provided') else: firstcat = rawcat self.packagelist = (firstcat, newline[1], newline[2], self.catname, newline[3].strip('\n')) self.masterlist.append(self.packagelist) Using the time.sleep function and adding the os.O_NONBLOCK to the os.popen call let the data stream come through uninterrupted. Here is the comparable code using subprocess: def getAllPackages(self): self.masterlist=[] self.showProgress() self.status.set('Getting all packages') self.update() for self.catname in self.catlist: self.update() self.status.set('Getting all packages by category: %s' % self.catname) self.getpackages = Popen('%s list --section=%s' % (self.finkpath, self.catname), shell=True, bufsize=0, stdout=PIPE).stdout time.sleep(5) fcntl.fcntl(self.getpackages, fcntl.F_SETFL, os.O_NONBLOCK) print "getting %s" % self.catname self.update() for line in self.getpackages: print line time.sleep(.1) self.update() newline = line.split('\t') rawcat = newline[0] if rawcat == '(i)': firstcat=rawcat.replace('(i)', 'outdated') elif rawcat == ' i ': firstcat=rawcat.replace('i', 'current') elif rawcat == ' p ': firstcat=rawcat.replace('p', 'provided') else: firstcat = rawcat self.packagelist = (firstcat, newline[1], newline[2], self.catname, newline[3].strip('\n')) I am using the fcntl call to set the pipe to nonblocking mode, and am trying to time.sleep to give the buffer time to get some data. However, this code crashes with the error "IOError: [Errno 35] Resource temporarily unavailable." Any advice to get the subprocess bits working so that the buffer does not close prematurely would be appreciated. Thank you, Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com From dfnsonfsduifb at gmx.de Sat Dec 6 11:43:13 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Sat, 06 Dec 2008 17:43:13 +0100 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: References: <5u8o06xbqf.ln2@joeserver.homelan.net> Message-ID: <1mmq06x4g6.ln2@joeserver.homelan.net> John Machin schrieb: > On Dec 6, 5:36 am, Johannes Bauer wrote: >> So UTF-16 has an explicit EOF marker within the text? I cannot find one >> in original file, only some kind of starting sequence I suppose >> (0xfeff). The last characters of the file are 0x00 0x0d 0x00 0x0a, >> simple \r\n line ending. > > Sorry, *WRONG*. It ends in 00 0d 00 0a 00. The file is 1559 bytes > long, an ODD number, which shouldn't happen with utf16. The file is > stuffed. Python 3.0 has a bug; it should give a meaningful error > message. Yes, you are right. I fixed the file, yet another error pops up (http://www.file-upload.net/download-1299688/2008_12_05_Handy_Backup.txt.html): Traceback (most recent call last): File "./modify.py", line 12, in a = AddressBook("2008_12_05_Handy_Backup.txt") File "./modify.py", line 7, in __init__ line = f.readline() File "/usr/local/lib/python3.0/io.py", line 1807, in readline while self._read_chunk(): File "/usr/local/lib/python3.0/io.py", line 1556, in _read_chunk self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) File "/usr/local/lib/python3.0/io.py", line 1293, in decode output = self.decoder.decode(input, final=final) File "/usr/local/lib/python3.0/codecs.py", line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) File "/usr/local/lib/python3.0/encodings/utf_16.py", line 69, in _buffer_decode return self.decoder(input, self.errors, final) UnicodeDecodeError: 'utf16' codec can't decode byte 0x0a in position 0: truncated data File size is 1630 bytes - so this clearly cannot be. Regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From inyeol.lee at gmail.com Mon Dec 8 02:06:09 2008 From: inyeol.lee at gmail.com (inyeol.lee at gmail.com) Date: Sun, 7 Dec 2008 23:06:09 -0800 (PST) Subject: tabs and spaces in py3k References: <774909e2-b248-4251-bbba-deb309e72714@x38g2000yqj.googlegroups.com> Message-ID: On Dec 7, 8:51 pm, ru... at yahoo.com wrote: > The following code works under 2.6 > ---- > def foo(): > a = 1 > <.tab..>b = 1 > ---- > but results in a TabError in Python 3k > > File "x.py", line 3 > b = 3 > ^ > TabError: inconsistent use of tabs and spaces in indentation > > The py3k docs say the same thing as the 2.6 docs, > namely that tabs are expanded to spaces prior to > determining the line's indentation. (Language > Ref, Lex Anal, Line Struct, Indentation) > (I wish someone would put the section numbers > back in the docs.) No mention of this change > (that I noticed) in What's New or NEWS.txt. > > Do the Py3k docs need correction? -tt option in python 2.x is now default in python 3.0. Apparently it got slipped from any documentation, including what's new. --Inyeol From nick at craig-wood.com Mon Dec 1 10:30:44 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 01 Dec 2008 09:30:44 -0600 Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> Message-ID: Slaunger wrote: > Slaunger wrote: > > > > class PayloadOnDemand(object): > > ? ? """ > > ? ? Behaves as a PayloadInstant object, but instantiation is faster > > ? ? as only the position of the payload in the file is stored > > initially in the object. > > ? ? Only when acessing the initially non-existing data attribute > > ? ? are the data actually read and the attribure created and bound to > > the instance. > > ? ? This will actually be a little slower than in PayloadInstant as > > the correct file position > > ? ? has to be seeked out first. > > ? ? On later calls the object has as efficient attribute access as > > PayloadInstant > > ? ? """ > > > > ? ? @classmethod > > ? ? def read_from_file(cls, f, size): > > ? ? ? ? pos = f.tell() > > ? ? ? ? f.seek(pos + size) #Skip to end of payload > > ? ? ? ? return cls(pos) > > Extend with ref to file instead: > return cls(f, pos) > > > > ? ? # I probably need some __getattr__ or __getattribute__ magic > > # there...?? > > To answer my own rethorical question I guess I should do something > like this > > def __getattr__(self, attr_name): > """ > Only called if attr_name is not in the __dict__ for the > instance > """ > if attr_name == 'data': > self.__dict__[attr_name] = read_data(self.f, > self.file_position) > > > > > ? ? def __init__(self, a_file_position): > > ? ? ? ? self.file_position = a_file_position > > > and then I need to also store a reference to the file in the > constructor... > > def __init__(self, a_file, a_file_position): > self.f = a_file > self.file_position = a_file_position > > Have I understood correctly how to to it the on demand way? I wouldn't use __getattr__ unless you've got lots of attributes to overload. __getattr__ is a recipe for getting yourself into trouble in my experience ;-) Just do it like this... class PayloadOnDemand(object): def __init__(self, a_file, a_file_position): self._data = None self.f = a_file self.file_position = a_file_position @property def data(self): if self._data is None: self._data = self.really_read_the_data() return self._data then you'll have a .data attribute which when you read it for the first time it will populate itself. If None is a valid value for data then make a sentinel, eg class PayloadOnDemand(object): sentinel = object() def __init__(self, a_file, a_file_position): self._data = self.sentinel self.f = a_file self.file_position = a_file_position @property def data(self): if self._data is self.sentinel: self._data = self.really_read_the_data() return self._data -- Nick Craig-Wood -- http://www.craig-wood.com/nick From martin at v.loewis.de Sun Dec 14 16:13:01 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 14 Dec 2008 22:13:01 +0100 Subject: Python 3.0 crashes displaying Unicode at interactive prompt In-Reply-To: References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> <49443531.5050304@v.loewis.de> <49448FC2.6030306@v.loewis.de> Message-ID: <494576DD.1050505@v.loewis.de> > But shouldn't the production of an object's representation via repr be > a "safe" operation? It's a trade-off. It should also be legible. Regards, Martin From __peter__ at web.de Wed Dec 10 04:29:24 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 10 Dec 2008 10:29:24 +0100 Subject: filter iterable based on predicate take from another iterable References: Message-ID: bernhard.voigt at gmail.com wrote: > is there is a neat way to select items from an iterable based on > predicates stored in another iterable without zipping? I can do > something like this: > > import itertools > foo = range(10) > # select even numbers > bar = map(lambda i: i%2, foo) > foobarselected = itertools.ifilterfalse(lambda t: t[0], itertools.izip > (bar,foo)) > # for simplicity I want to work with the single item list, not the > zipped one > fooselected = list(t[1] for t in foobarselected) > > However, it would be nice to have a function combining the last two > instructions. Something like > itertools.ifilterother(bar, foo) -> yield iterator with items from foo > where bar is true I think it's a good approach to keep the number of primitives low. I find the list comprehension combined with izip() quite readable: [v for f, v in izip(bar, foo) if not f(v)] Peter From stefan_ml at behnel.de Fri Dec 12 10:06:39 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 12 Dec 2008 16:06:39 +0100 Subject: Python is slow In-Reply-To: <0c3e89f2-b67c-4da5-bd33-87c98ee48812@z28g2000prd.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> <49427875$0$30229$9b4e6d93@newsspool1.arcor-online.net> <0c3e89f2-b67c-4da5-bd33-87c98ee48812@z28g2000prd.googlegroups.com> Message-ID: <49427dff$0$30223$9b4e6d93@newsspool1.arcor-online.net> sturlamolden wrote: > How is the numpy support in Cython going? It was supposed to know > about ndarrays natively. It does. > I.e. not treat them as Python objects, but > rather as known C structs. That way an operation like arr[n] would not > result in a callback to Python, but translate directly to fast pointer > arithmetics. http://docs.cython.org/docs/numpy_tutorial.html Stefan From michele.simionato at gmail.com Tue Dec 2 01:23:55 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 1 Dec 2008 22:23:55 -0800 (PST) Subject: What about a decorator module version 3.0? References: <7504ac87-4e4e-447f-a02c-f9db3f932a57@s20g2000yqh.googlegroups.com> Message-ID: <50b08bf6-550a-4033-92d8-0d8a067aae89@j38g2000yqa.googlegroups.com> On Dec 1, 9:18?pm, Terry Reedy wrote: > > Release a final 2.x version with whatever internal changes but with > external api unchanged or at least backward compatible. ?Mark items to > be deleted as deprecated. ?Keep that available indefinately. > > Then release a 3.0 version with Py3.0 support and deprecated items deleted. Uhm ... I don't like that. I want the 2.x versions to be fully compatible, without any annoying warning. The warnings will be in 3.0 and the functionality will be removed in 3.1. BTW, I have uploaded versions 2.3.2 on PyPI and it is intended to be the last version of the 2.x series. From bsk16 at case.edu Mon Dec 8 12:21:08 2008 From: bsk16 at case.edu (Ben Kaplan) Date: Mon, 8 Dec 2008 12:21:08 -0500 Subject: Guido's new method definition idea In-Reply-To: <79139d04-bd26-4f36-b8c9-19554e7d4e95@e18g2000yqo.googlegroups.com> References: <014a071a$0$20670$c3e8da3@news.astraweb.com> <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> <79139d04-bd26-4f36-b8c9-19554e7d4e95@e18g2000yqo.googlegroups.com> Message-ID: On Dec 8, 2008, at 11:59 AM, anthony.tolle at gmail.com wrote: > On Dec 6, 4:15 pm, Carl Banks wrote: >> On Dec 6, 12:47 am, "Patrick Mullen" wrote: >> >>> Could I do something like this: >> >>> def a.add(b): return a+b >> >>> Outside of a class? Of course then that makes you think you could >>> do >>> 5.add(6) or something craaaazy like that. (I mean, you can do >>> (5).__add__(6) but that's something else entirely) >> >> I'd be inclined to think that this defines an instancemethod on an >> existing object a. In other word, I'd read the following two lines >> as >> more or less equivalent. >> >> def a.add(b): return a+b >> >> a.add = lambda b: a+b >> >> Just as the following are equivalent: >> >> def foo(): return bar >> >> foo = lambda: bar >> >> I had been -0 on this, but now I think I'm -1. > > This brings up another question, what would one use when referencing > method names inside the class definition?: > > class C: > def self.method(arg): > self.value = arg > def self.othermethod(arg): > self.value = arg > # do this? > funcs = (self.method, self.othermethod) > # or this? > funcs = (method, othermethod) > > On another related note, I would be interested in seeing this syntax > adopted for a different purpose... > > Normally, if I'm defining a nested function that needs to be stored as > an object attribute, I have to use a dummy name, like the following: > > class C: > def createfunc(self, arg): > def _dummy(arg): > return arg + 1 > self.func = _dummy > > It would be nice to be able to do the following instead: > > class C: > def createfunc(self): > def self.func(arg): > return arg + 1 > > Or, after the class definition is done, to extend it dynamically: > > def C.method(self, arg): > self.value = arg > > ...which would be the equivalent of the following: > > def method(self, arg): > self.value = arg > C.method = method > > Since functions are first-class objects, it seems perfectly reasonable > to me. > -- > http://mail.python.org/mailman/listinfo/python-list I agree, this would be much nicer and would not require any special cases. I'm not convinced that this is needed, but at least this won't confuse newbies as much. From jason.scheirer at gmail.com Thu Dec 11 18:57:17 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Thu, 11 Dec 2008 15:57:17 -0800 (PST) Subject: newbie question: if var1 == var2: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> Message-ID: <44aa0191-e374-4bf0-b039-d05cfa996b1d@p2g2000prn.googlegroups.com> On Dec 11, 3:49?pm, John Machin wrote: > On Dec 12, 10:31?am, "Rhodri James" > wrote: > > > > > On Thu, 11 Dec 2008 19:49:23 -0000, Steve Holden ? > > wrote: > > > > Kirk Strauser wrote: > > >> At 2008-11-29T04:02:11Z, Mel writes: > > > >>> You could try > > > >>> for item in fname: > > >>> ? ? item = item.strip() > > > >> This is one case where I really miss Perl's "chomp" function. ?It ? > > >> removes a > > >> trailing newline and nothing else, so you don't have to worry about ? > > >> losing > > >> leading or trailing spaces if those are important to you. > > > > ... and it's so hard to write > > > > ? ? ?item = item[:-1] > > > Tsk. ?That would be "chop". ?"chomp" would be > > > ? ? ?if item[-1] == '\n': > > ? ? ? ? ?item = item[:-1] > > Better: > if item and item[-1] == '\n': > ? ? return item[:-1] > return item Best: return item \ if not (item and item.endswith('\n')) \ else item[:-1] Though really you should be using item.rstrip() From python.list at tim.thechases.com Tue Dec 16 08:42:59 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 16 Dec 2008 07:42:59 -0600 Subject: String slices work only for first string character ? In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF60249410A@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF60249410A@enbmail01.lsi.com> Message-ID: <4947B063.6030906@tim.thechases.com> > Can any one explain why the following string slice works only for the first character, but not for any other ? > > $ cat /tmp/tmp.py > #!/usr/bin/env python > > data = 'F0023209006-0101' > print data > print "|"+data[0:1]+"|" > print "|"+data[1:1]+"|" > print "|"+data[2:1]+"|" > > $ python `cygpath -w /tmp/tmp.py` > F0023209006-0101 > |F| > || > || Slices are defined by [start_idx:end_idx] not [start_idx:length] so you want data[0:1] data[1:2] data[2:3] -tkc From dotancohen at gmail.com Thu Dec 4 15:43:26 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 4 Dec 2008 22:43:26 +0200 Subject: Mathematica 7 compares to other languages In-Reply-To: <20081219033030.559@gmail.com> References: <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <4b6c3304-2396-4d35-a06f-e5d693cbbb12@f13g2000yqj.googlegroups.com> <20081219033030.559@gmail.com> Message-ID: <880dece00812041243y26e01b6ud0151fa614473102@mail.gmail.com> 2008/12/4 Kaz Kylheku : > Really? I will trade you one Xah Lee for three Jon Harrops and I will even > Xah Lee is interesting because he brings up lots of good points. Also, the few times we've seen his skilz he has shown that he really knows how to code. I am willing to put up with his AI-bot posts, but I do wish that he'd trade his lolcats speak for proper (or the best that he could do) English. English (or another Latin language) is not my native language either, but if a dumbbell like me can grasp it then I'm sure Xah could too. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-??-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From geekmail at usenot.de Sun Dec 7 12:27:21 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sun, 7 Dec 2008 18:27:21 +0100 Subject: Guido's new method definition idea References: Message-ID: <20081207182721.4033466d@usenot.de> On Sat, 6 Dec 2008 23:21:04 -0800 (PST) Lie wrote: > I think we have to test this on newbies. [snip] > Now that's talking like a programmer! Ideas on how such a survey could be conducted? Anyone? > If this dead horse is revived because of that reason, then I'd go with > changing the error message to something that is less confusing to > newbies[1]. + googol > I remember being tripped with the (thinking that python > miscounted the number of argument) when I was new. This has the > advantage of backward compatibility and no syntax change, just less > misleading error message. > > [1] anything could work, but I like this one: (c is an instance of > class C) > if the code is: c.foo(...), Error: "TypeError: c.foo() takes exactly 3 > argument" > while if the code is: C.foo(...), Error: "C.foo() takes exactly 4 > arguments" > You can implement c.foo as a curried C.foo function, catch C.foo's > TypeError exception then reraise it as c.foo exception. I'm not sure that I'd find that less confusing. Because a c.foo() *does* take four arguments, not three. It's just that the first one is implicit (Right?). How about: "TypeError: c.foo() takes exactly 3 arguments in addition to the implicit instance reference." or "TypeError: c.foo() takes exactly 4 arguments (5 given, including the implicit instance reference)" ... or something less kludgy in that general direction. This would explain exactly what is wrong. /W -- My real email address is constructed by swapping the domain with the recipient (local part). From steve at holdenweb.com Thu Dec 11 22:42:24 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 11 Dec 2008 22:42:24 -0500 Subject: Rename of .mdb file -- lock In-Reply-To: <99fbe43e-9b30-4ed2-8355-29a21935e55a@n41g2000yqh.googlegroups.com> References: <4049f296-2a04-4eee-9f09-aa37a973a8cf@r40g2000yqj.googlegroups.com> <8792708a-51c9-4fa6-b39d-4808ed1ffaed@t39g2000prh.googlegroups.com> <99fbe43e-9b30-4ed2-8355-29a21935e55a@n41g2000yqh.googlegroups.com> Message-ID: noydb wrote: > On Dec 11, 9:38 pm, "gudonghua+pyt... at gmail.com" > wrote: [...] > > Thanks! That was simple enough. > > And... > ##os.rename(new91mdb, (os.path.join(output_dir, uChoice))) > os.rename(new91mdb, (os.path.join(output_dir, "C:\TEMP\test1.mdb"))) > > ... of those two lines, the top one worked. The reason the second one didn't work is because "\t" is the tab character. Look for "raw strings" in the documentation. r"C:\TEMP\test1.mdb" should work. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From cs at zip.com.au Mon Dec 29 18:24:08 2008 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 30 Dec 2008 10:24:08 +1100 Subject: flushing of print statements ending with comma In-Reply-To: <25783efa-fa57-49c8-b20a-7bdf6f7cb256@w1g2000prk.googlegroups.com> Message-ID: <20081229232408.GA24226@cskk.homeip.net> On 29Dec2008 11:11, Grebekel wrote: | I have recently noticed that print statements ending with a comma are | not immediately flushed. I will warn you that neither are the more common uncommaed print statements, except on a terminal. | [...] Example: | | print 'Take a walk, because this will take a while...', | i = 0 | while i < 10**10: | i += 1 | print "we're done!" | | | Here the first string is not printed until the second print statement. [...] | Using sys.std.flush after the print fixes this issue, but doing so | each time seems cumbersome and somewhat counterintuitive. | Is there some reasoning behind this behavior or is it a bug? It's correct behaviour. The python print etc is layered on the C library stdio. A stdio stream can be buffered in three standard ways: unbuffered, line buffered and block buffered. On UNIX, on a terminal, stdout is normally line buffered: output is flushed when a newline is encoutered in the data, and this is pleasing to humans. Conversely, is stdout is _not_ attached to a terminal it will be block buffered by default; output is only flushed when the buffer is filled. This is much more _efficient_ in terms of I/O and program activity. By contrast, again by default, stderr is normally unbuffered. Being reserved for error messages, immediate output (before your program explodes:-) is considered more important than system efficiency. So you should sys.stdout.flush() if you want data output right now. For many purposes it is better to let the default behaviour obtain. Also, I suugest that progress reporting such as your be written to stderr anyway. It will appear in a timely fashion, and will also thus not pollute the output stream. Consider: your-program >datafile or your-program | process the output data... Sending your progress reports to stdout puts junk in the data stream. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Gentle suggestions being those which are written on rocks of less than 5lbs. - Tracy Nelson in comp.lang.c From list at qtrac.plus.com Fri Dec 19 11:07:00 2008 From: list at qtrac.plus.com (Mark Summerfield) Date: Fri, 19 Dec 2008 08:07:00 -0800 (PST) Subject: ANN: New Book: Programming in Python 3 References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> Message-ID: <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> Just a follow-up to say that the book has now been published in the U.S. It is now in stock at InformIT, and should reach other stores, e.g., Amazon, in a week or so. Also, the introduction, the first few pages of the first chapter, the whole of chapter 12 (regular expressions), and the index are now available for free download in a PDF from here: http://www.informit.com/store/product.aspx?isbn=0137129297 Oh, and I wrote a short article on descriptors which is here: http://www.informit.com/articles/article.aspx?p=1309289 (The third example is very similar to an example from Chapter 8 and shows a validation technique that combines class decorators with descriptors.) On 4 Dec, 15:02, Mark Summerfield wrote: > Now that Python 3 final has been released I thought it would be a good time > to mention that there's a new book to go with it: > > "Programming in Python 3: > A Complete Introduction to the Python Language" > ISBN 0137129297http://www.qtrac.eu/py3book.html > > I've been working on this for more than a year, testing the examples > against every Python 3 alpha and beta, and against the final release (using > Python's unit test and doctest modules of course:). > > The book has just gone into production and should be available in print at > the end of this month in the U.S., and a month or two later elsewhere. The > book's web page has links to a draft of the introduction and to safari > books online where you can read extracts. > > The book is aimed at a wide audience, but assumes some programming > experience (not necessarily Python, not necessarily object-oriented). It > teaches solid procedural style programming, then builds on that to teach > solid object-oriented programming, and then goes on to more advanced topics > (e.g., including a nice way to create validated attributes by combining > class decorators with descriptors). But even newcomers to Python 3 should > be able to write useful (although small and basic) programs after reading > chapter 1, and then go on to create larger and more sophisticated programs > as they work through the chapters. > > -- > Mark Summerfield, Qtrac Ltd,www.qtrac.eu From steve at holdenweb.com Fri Dec 12 11:00:38 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Dec 2008 11:00:38 -0500 Subject: concept of creating structures in python In-Reply-To: References: Message-ID: Joe Strout wrote: > On Dec 11, 2008, at 10:52 PM, navneet khanna wrote: > >> I want to create a structure within a structure i.e. nested structures >> in python. >> I tried with everything but its not working. >> my code is like this: >> >> class L(Structure): >> >> def __init__(self,Name='ND',Addr=0,ds_obj = D()): > > Change the default value of ds_obj here to None. Otherwise, you will > certainly confuse yourself (there would be just one default object > shared among all instances). > >> self.Name = Name >> self.Addr = Addr >> self.ds_obj = ds_obj >> >> >> class D(Structure): >> >> def __init__(self,dataName='ND',index = 0,ele_obj=E()): >> >> self.dataName = dataName >> self.index = index >> self.ele_obj = ele_obj > > Same thing here with ele_obj -- have it default to None to save yourself > grief. > > Otherwise, these look fine. > Joe missed a piece out here. If you change the signature of your D.__init__() to read def __init__(self, dataName='ND', index = 0, ele_obj=None): then you need to insert the following code at the top of the method: if ele_obj is None: ele_obj = E() [You'll note, by the way, I have inserted standard spacing into the "def" statement to enhance readbility: you should use spaces after all commas if you want your code to be easy for other programmers to read). This avoids a common beginner pitfall. Your original code would create a single E object that would be used as the defauilt for all Ds created without explicitly passing an ele_obj. Then if that object were changed (mutated) in some way, all such E's would see a change had been made to their ele_obj. With the extra code, a different ele_obj is created for each E that isn't passed one. The same argument applies to L.__init__()'s ds_obj argument. > >> these are two structures. I want to refer D structure in L one and use >> it. I want to access the value of D structure like L.D.index = 0. > [...] regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From musiccomposition at gmail.com Thu Dec 4 21:23:01 2008 From: musiccomposition at gmail.com (Benjamin) Date: Thu, 4 Dec 2008 18:23:01 -0800 (PST) Subject: Python 3.0 C API migration tools, or docs? References: <008877d2-8705-48a6-bb09-6c31c6b77970@p2g2000prf.googlegroups.com> Message-ID: <1a5cf43f-5802-4c69-9226-18cbc6256c0c@k19g2000yqg.googlegroups.com> On Dec 4, 7:45?pm, illume wrote: > Hi, > > are there migration tools for C API migration to python 3? > > I'm sure there must be some code somewhere to help change stuff over > right? > > I don't see any docs for migrating code from 2.x to 3.x either:http://docs.python.org/3.0/c-api/index.html At the moment all that is officially available is this rather incomplete howto: http://docs.python.org/howto/cporting.html > > Help needed with this! > > cheers, From skip at pobox.com Sat Dec 27 15:22:09 2008 From: skip at pobox.com (skip at pobox.com) Date: Sat, 27 Dec 2008 14:22:09 -0600 Subject: [2.4.4] creating a datetime.datetime from an XML xs:dateTime In-Reply-To: <5fa6c12e0812271208x4baccaedk262e51becb6e2076@mail.gmail.com> References: <5fa6c12e0812271208x4baccaedk262e51becb6e2076@mail.gmail.com> Message-ID: <18774.36465.346262.883182@montanaro-dyndns-org.local> martin> subject says it all. I'd like to create a python martin> datetime.datetime from an xs:string[1] ... martin> so I'd rather like to find some method (hopefully within the martin> standard lib) that had more peer review than only me :). Not in the standard lib, but you might want to check out the dateutil package. Its dateutil.parser module does an excellent job parsing a wide range of time formats. It's a bit weak in the timezone area though. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From rogerb at rogerbinns.com Fri Dec 19 20:54:22 2008 From: rogerb at rogerbinns.com (Roger Binns) Date: Fri, 19 Dec 2008 17:54:22 -0800 Subject: Jarow-Winkler algorithm: Measuring similarity between strings In-Reply-To: <4f351b3b-4da7-4fee-a1ac-c42179d430f5@s9g2000prm.googlegroups.com> References: <4f351b3b-4da7-4fee-a1ac-c42179d430f5@s9g2000prm.googlegroups.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 ?yvind wrote: > Based on examples and formulas from http://en.wikipedia.org/wiki/Jaro-Winkler. > Useful for measuring similarity between two strings. For example if > you want to detect that the user did a typo. Jaro-Winkler is best when dealing with names (Winkler works for the US census). There are pure Python and C accelerated implementations at http://bitpim.svn.sourceforge.net/viewvc/bitpim/trunk/bitpim/src/native/strings/ If you are concerned about typos then taking into account the keyboard layout will help. For example for a user with a US keyboard, the 'a' or 'd' keys would be a common typo for 's'. Also consider Levenshtein distance: http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Levenshtein_distance Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAklMUEkACgkQmOOfHg372QRTlQCfUoebzX2HRbQ4wLVZ6yRFMHd7 9yMAnjovqefVuQenX0zpHwn/rvv9FLe+ =bACc -----END PGP SIGNATURE----- From nikeshoe.nike30 at gmail.com Fri Dec 19 11:00:14 2008 From: nikeshoe.nike30 at gmail.com (nikeshoe.nike30 at gmail.com) Date: Fri, 19 Dec 2008 08:00:14 -0800 (PST) Subject: HTTP://WWW.STREETCANDY.ORG Message-ID: <8512b63e-02c4-4510-b955-5c9837f25165@d42g2000prb.googlegroups.com> Get Nike Shoes at Super Cheap Prices Discount Nike air jordans (www.streetcandy.org) Discount Nike Air Max 90 Sneakers (www.streetcandy.org) Discount Nike Air Max 91 Supplier (www.streetcandy.org) Discount Nike Air Max 95 Shoes Supplier (www.streetcandy.org) Discount Nike Air Max 97 Trainers (www.streetcandy.org) Discount Nike Air Max 2003 Wholesale (www.streetcandy.org) Discount Nike Air Max 2004 Shoes Wholesale (www.streetcandy.org) Discount Nike Air Max 2005 Shop (www.streetcandy.org) Discount Nike Air Max 2006 Shoes Shop (www.streetcandy.org) Discount Nike Air Max 360 Catalogs (www.streetcandy.orgm) Discount Nike Air Max Ltd Shoes Catalogs (www.streetcandy.org) Discount Nike Air Max Tn Men's Shoes (www.streetcandy.org) Discount Nike Air Max Tn 2 Women's Shoes (www.streetcandy.org) Discount Nike Air Max Tn 3 Customize (www.streetcandy.org) Discount Nike Air Max Tn 4 Shoes Customize ( www.streetcandy.orgm) Discount Nike Air Max Tn 6 Supply (www.streetcandy.org) Discount Nike Shox NZ Shoes Supply (www.streetcandy.org) Discount Nike Shox OZ Sale (www.streetcandy.org) Discount Nike Shox TL Store (www.streetcandy.org) Discount Nike Shox TL 2 Shoes Store (www.streetcandy.org) Discount Nike Shox TL 3 Distributor (www.streetcandy.org) Discount Nike Shox Bmw Shoes Distributor (www.streetcandy.org) Discount Nike Shox Elite Shoes Manufacturer (www.streetcandy.org) Discount Nike Shox Monster Manufacturer (www.streetcandy.org) Discount Nike Shox R4 Running Shoes (www.streetcandy.org) Discount Nike Shox R5 Mens Shoes (www.streetcandy.org) Discount Nike Shox Ride Womens Shoes (www.streetcandy.org) Discount Nike Shox Rival Shoes Wholesaler (www.streetcandy.org) Discount Nike Shox Energia Wholesaler (www.streetcandy.org) Discount Nike Shox LV Sneaker (www.streetcandy.org) Discount Nike Shox Turbo Suppliers (www.streetcandy.org) Discount Nike Shox Classic Shoes Suppliers (www.streetcandy.org) Discount Nike Shox Dendara Trainer (www.streetcandy.org) Discount Nike Air Jordan 1 Seller (www.streetcandy.org) Discount Nike Air Jordan 2 Shoes Seller (www.streetcandy.org) Discount Nike Air Jordan 3 Collection (www.streetcandy.org Discount Nike Air Jordan 4 Shoes Collection (www.streetcandy.org) Discount Nike Air Jordan 5 Chaussure Shoes (www.streetcandy.org) Discount Nike Air Jordan 6 Catalog (www.streetcandy.org) Discount Nike Air Jordan 7 Shoes Catalog (www.streetcandy.org) Discount Nike Air Jordan 8 Customized (www.streetcandy.org) Discount Nike Air Jordan 9 Shoes Customized (www.streetcandy.org) Discount Nike Air Jordan 10 Wholesalers (www.streetcandy.org) Discount Nike Jordan 11 Shoes Wholesalers (www.streetcandy.org) Discount Nike Air Jordan 12 Factory (www.streetcandy.org) Discount Nike Air Jordan 13 Shoes Factory (www.streetcandy.org) Discount Nike Air Jordan 14 Shoes Sell (www.streetcandy.org) Discount Nike Air Jordan 16 Exporter (www.streetcandy.org) Discount Nike Air Jordan 17 Shoes Exporter (www.streetcandy.org) Discount Nike Air Jordan 18 Offer (www.streetcandy.org) Discount Nike Air Jordan 19 Shoes Offer (www.streetcandy.org) Discount Nike Air Jordan 20 Manufacture (www.streetcandy.org) Discount Nike Jordan 21 Shoes Manufacture (www.streetcandy.org) From huwdjones at gmail.com Tue Dec 16 07:14:56 2008 From: huwdjones at gmail.com (huw_at1) Date: Tue, 16 Dec 2008 04:14:56 -0800 (PST) Subject: cx_Oracle issues References: <5b2dad81-2750-4347-8079-6ab31321d579@s1g2000prg.googlegroups.com> <9142a8f1-7f76-4fc0-9ca1-c9dec310f2ce@r37g2000prr.googlegroups.com> <9f436c9e-2319-499c-a306-d255996372fc@e22g2000vbe.googlegroups.com> Message-ID: <844152f0-e946-40f1-8969-4ee5031c68f8@35g2000pry.googlegroups.com> On Dec 15, 12:59?pm, "ron.re... at gmail.com" wrote: > On Dec 15, 2:44?am, huw_at1 wrote: > > > > > On Dec 11, 5:34?pm, "ron.re... at gmail.com" wrote: > > > > On Dec 10, 9:48?am, huw_at1 wrote: > > > > > Hey all. When usingcx_Oracleto run a procedure like: > > > > > cursor.execute("select (obj.function(value)) from table where > > > > id=blah") > > > > > I am getting the following error: > > > > > ORA-06502: PL/SQL: numeric or value error: character string buffer too > > > > small ORA-06512: at line 1 > > > > > Looking at cursor.description I get: > > > > > [('(obj.function(value))', , 4000, 4000, 0, > > > > 0, 1)] > > > > > Any tips - i have never seen this error before but am guessing that > > > > the value being returned is too big for the buffer size set for the > > > > cursor. the procedure fetches data from a LOB. > > > > > Any suggestions/confirmations? > > > > > Many thanks > > > > This error is a problem with the PL/SQL, notcx_Oracle. ?You need to > > > debug obj.function to see what kind of data is being accessed and then > > > a data analysis of that data to understand why this error occurs. ?I > > > can tell you the function is most likely expecting characters from a > > > column that are numeric [0 .. 9] and is getting alpha characters. > > > > -- > > > Ron Reidy > > > Sr. Oracle DBA > > > Hi thanks for the responses. Unfortunately the procedure in question > > is from a third party vendor so I can't really debug it so I'd say I > > was fairly stumped. Just out of interest how do you increase the > > output buffer size withcx_Oracle? > > > Many thanks- Hide quoted text - > > > - Show quoted text - > > Hi, > > Sure you can. ?You can see the PL/SQL source from the ditionary view > ALL_SOURCE: > select text from all_source where name = 'NAME_OF_FUNCTION'; > > From there, reverse engineeer which table(s) and column(s) are being > accesses and do the data analysis. > > -- > Ron Reidy Hi all, So I tried Rons query but unfortunately I got 0 records returned. However I can confirm that running the select query from a client does indeed generate the same error. Is there anything else I could try? Otherwise I'll just get in touch with the vendor I guess. From rdmurray at bitdance.com Tue Dec 9 22:15:51 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Tue, 9 Dec 2008 22:15:51 -0500 (EST) Subject: How do I manually uninstall setuptools (installed by egg)? In-Reply-To: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> Message-ID: On Tue, 9 Dec 2008 at 18:49, excord80 at gmail.com wrote: > On Ubuntu, I accidentally manually installed setuptools > http://pypi.python.org/pypi/setuptools/0.6c9 (by running the .egg file > as a shell script via sudo), and now realize I should just be using > apt to take care of my system Python packages. I also installed one or > two packages using its ``easy_install``. > > Looks like it lives in ``/usr/lib/python2.5/site-packages``. > > How can I manually remove those packages installed using that > ``easy_install``, and then manually remove the setuptools package I > installed? rm -r /usr/lib/python2.5/site-packages/ Then find the .pth file (in the site-packages directory) that references the egg, and delete the line referencing the egg. Setuptools has no uninstall function, as far as I know. --RDM From dotancohen at gmail.com Wed Dec 31 05:43:06 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 31 Dec 2008 12:43:06 +0200 Subject: Easy-to-use Python GUI In-Reply-To: References: Message-ID: <880dece00812310243y1c02e6cete667e37964e354b3@mail.gmail.com> I have been following this thread with interest. Is there a way to build Qt apps with relative easy? I use KDE and would prefer the Qt toolkit for my GUI apps. Thanks. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-??-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From wuwei23 at gmail.com Mon Dec 1 20:09:26 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 1 Dec 2008 17:09:26 -0800 (PST) Subject: end of print = lower productivity ? References: Message-ID: <98407948-e24f-4a89-8604-148279620f84@k24g2000pri.googlegroups.com> On Dec 2, 5:12?am, Alan G Isaac wrote: > One obvious cost is that working at the > interpreter prompt is now slightly less > convenient. Not if you use IPython: IPython 0.8.1 -- An enhanced Interactive Python. ? -> Introduction to IPython's features. %magic -> Information about IPython's 'magic' % functions. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: def prnt(x): print x ...: In [2]: prnt "test" ------> prnt("test") test In [3]: prnt 1+1 ------> prnt(1+1) 2 > My preferred transition would have been to > retain the `print` statement but add a `printf` > function (i.e., the new `print` function). > Presumably many would find this a repulsive > redundancy and a needless maintenance headache. Not to mention the endless "Which should I use, print or print()?" questions this list would get. From brendandetracey at yahoo.com Fri Dec 12 10:36:24 2008 From: brendandetracey at yahoo.com (Brendan) Date: Fri, 12 Dec 2008 07:36:24 -0800 (PST) Subject: Reading online zip files - zipfile and zlib, wbits References: <21ba0ff5-7698-481a-851c-80b9ddcd5814@q26g2000prq.googlegroups.com> Message-ID: On Dec 12, 10:46?am, Brendan wrote: > On Dec 12, 10:25?am, Brendan wrote: > > > I am fooling around with accessing contents of zip files online. I > > download the tail end of the zip and use zipfile to get the zip > > central directory structure. I download the section of the zip file I > > need, directly read the zip file headers and use that information with > > zlib to uncompress the data. The files I am examining will always be > > compressed using deflate, with a wbits value of -15(minus for > > headerless data because I am unsure whether the zip file header is > > what zlib expects). > > > I can not find anywhere in the PK Zip Application notes (http://www.pkware.com/documents/casestudies/APPNOTE.TXT) how to > > determine the value I should uze for wbits with zlib.decompress. I > > have determined it is -15 from experimentation. Does anyone know the > > answer to this? > > Okay, I found part of the answer here in the zip app notes > [quote] > general purpose bit flag: (2 bytes) > > ? ? ? ? ? Bit 0: If set, indicates that the file is encrypted. > > ? ? ? ? ? (For Method 6 - Imploding) > ? ? ? ? ? Bit 1: If the compression method used was type 6, > ? ? ? ? ? ? ? ? ?Imploding, then this bit, if set, indicates > ? ? ? ? ? ? ? ? ?an 8K sliding dictionary was used. ?If clear, > ? ? ? ? ? ? ? ? ?then a 4K sliding dictionary was used. > ? ? ? ? ? Bit 2: If the compression method used was type 6, > ? ? ? ? ? ? ? ? ?Imploding, then this bit, if set, indicates > ? ? ? ? ? ? ? ? ?3 Shannon-Fano trees were used to encode the > ? ? ? ? ? ? ? ? ?sliding dictionary output. ?If clear, then 2 > ? ? ? ? ? ? ? ? ?Shannon-Fano trees were used. > > ? ? ? ? ? (For Methods 8 and 9 - Deflating) > ? ? ? ? ? Bit 2 ?Bit 1 > ? ? ? ? ? ? 0 ? ? ?0 ? ?Normal (-en) compression option was used. > ? ? ? ? ? ? 0 ? ? ?1 ? ?Maximum (-exx/-ex) compression option was > used. > ? ? ? ? ? ? 1 ? ? ?0 ? ?Fast (-ef) compression option was used. > ? ? ? ? ? ? 1 ? ? ?1 ? ?Super Fast (-es) compression option was used. > [/quote] > > Now I just don't understand Why Normal deflate corresponds to 15 > wbits, and why I have to use headerless for the data, i.e. wbits = -15. Seems the bit flags are not properly set, bit 2 should be 0 and bit 1 should be 1, to correspond to maximum compression i.e. wbit = 15. Still don't know why wbits has to be negative. From bdesth.quelquechose at free.quelquepart.fr Tue Dec 30 15:49:45 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 30 Dec 2008 21:49:45 +0100 Subject: SQL, lite lite lite In-Reply-To: <6rvgihF3je6sU1@mid.uni-berlin.de> References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> <4959204f$0$15020$426a74cc@news.free.fr> <6rvgihF3je6sU1@mid.uni-berlin.de> Message-ID: <495a9719$0$25469$426a74cc@news.free.fr> Gerhard H?ring a ?crit : > Bruno Desthuilliers wrote: >> Aaron Brady a ?crit : >>> Hi all, >>> >> (snip) >> > >>> I don't think relational data can be read and written very easily in >>> Python. >> >> Did you try SQLAlchemy or Django's ORM ? >> [...] > > Using an ORM when you don't grasp the relational model and/or the SQL > query language is futile. Yes, indeed. And ? Aaron's post was mostly about a better integration of the relational model in Python - which obviously requires some knowledge of the topic. From NIE_DZIALA at gazeta.pl Sun Dec 14 00:48:19 2008 From: NIE_DZIALA at gazeta.pl (Piotr Sobolewski) Date: Sun, 14 Dec 2008 06:48:19 +0100 Subject: the official way of printing unicode strings Message-ID: Hello, in Python (contrary to Perl, for instance) there is one way to do common tasks. Could somebody explain me what is the official python way of printing unicode strings? I tried to do this such way: s = u"Stanis?aw Lem" print u.encode('utf-8') This works, but is very cumbersome. Then I tried to do this that way: s = u"Stanis?aw Lem" print u This breaks when I redirect the output of my program to some file, like that: $ example.py > log Then I tried to do this that way: sys.stdout = codecs.getwriter("utf-8")(sys.__stdout__) s = u"Stanis?aw Lem" print u This works but is even more combersome. So, my question is: what is the official, recommended Python way? From benjamin.kaplan at case.edu Fri Dec 12 18:40:02 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 12 Dec 2008 18:40:02 -0500 Subject: os.lstat : proper way to do this In-Reply-To: References: Message-ID: On Fri, Dec 12, 2008 at 6:06 PM, wrote: > I'm converting from Perl to Python, so I'm learning the basics - > please be gentle! :) > > In Perl, I can lstat($file) whether $file exists or not: > lstat($file); > unless (-e _) { > print STDERR "$file: No such file or directory\n"; > } > unless (-l _) { > print STDERR "$file: Not a symbolic link\n"; > } > > The lstat() returns normally whether the file exists or not, and I > check for existence with the "-e" conditional. Then I go on and check > other modes. > > In Python,if I os.lstat(file) and file doesn't exist, I get an error > from within the module: > OSError: [Errno 2] No such file or directory: '/etc/xxx' > > I can check first with os.path.exists(file), but then I'm doing two > stat() type calls which is inefficient (especially when we're talking > thousands of files). > > I want to be able to do something like this: > mode = os.lstat(file)[ST_MODE] > if not mode: > print >> sys.stderr, file, ": No such file or directory" > if not S_ISLNK(mode): > print >> sys.stderr, file, ": Not a symbolic link" > > Of course, this isn't valid. How can I do this efficiently without > getting "no such file" error? > In Python, people usually follow the "Easier to Ask Forgiveness than Permission" philosophy. Rather than prevent an error from occurring, just let it happen and deal with if when it does. Wrap your call to os.lstat in a try/except block and just print your error message if the lstat call fails. -------------- next part -------------- An HTML attachment was scrubbed... URL: From manu3d at gmail.com Sat Dec 13 10:21:43 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Sat, 13 Dec 2008 07:21:43 -0800 (PST) Subject: Bidirectional Networking References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> Message-ID: <98a6c3cd-181c-43c9-805b-fb0689c69544@a26g2000prf.googlegroups.com> Hey Bryan, thank you for your reply! On Dec 13, 3:51?am, Bryan Olson wrote: > > Is it possible then to establish both a server and a client in the > > same application? > > Possible, and not all that hard to program, but there's a gotcha. > Firewalls, including home routers and software firewalls, typically > default to disallowing connections in the 'wrong' direction. If the > client initiates all connections, you avoid a world of hassles. Ah yes, I can see that. Uhm. I have absolutely no idea right now how a firewall works from a programming point of view and what happens in normal "residential" circumstances. I.e. it's clear that firewalls are configured to allow http traffic because I can browse the internet. Is that done leaving a specific port open? Or does the browser request the firewall to open a specific port for it and the firewall trust the browser to handle safely anything that comes through? I.e. in the case of the code in this thread, would it be the responsibility of the application to tunnel through the firewall and listen for connections or would it be the responsibility of the user to configure the firewall so that the application can receive a connection? Thanks for your help! Manu From bruno.42.desthuilliers at websiteburo.invalid Thu Dec 4 09:54:26 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 04 Dec 2008 15:54:26 +0100 Subject: Python Runtime Method Call Binding In-Reply-To: References: Message-ID: <4937ef0e$0$27400$426a74cc@news.free.fr> k3xji a ?crit : > Hi, > > Is there a way to hook a function call in python? I know __getattr__ > is doing for variables, it is giving us a chance before a field is > initialized. Note that since the introduction of the "new-style" object model - that is, in Python 2.2 -, computed attributes are better handled with the descriptor protocol, and specially the general purpose 'property' class. The __getattr__ hook should only be used when you want to handle read access to an attribute that doesn't exist at all (ie : automatic delegation etc). Also note that a method is mostly a computed attribute (another application of the descriptor protocol FWIW)... > Do we have same functionality for methods? Which "functionality" ? What do you want to do ? automatically delegate method calls, or "wrap" method calls so you can ie log them or attach more behaviour ? > Example: > > class Foo(object): > def __call_method__(self, ...) # just pseudo > print 'A method is called in object...' > > f = Foo() > f.test_method() Ok, I guess this is the second case. The answer is "decorator". def log(func): def _logged(*args, **kw): print "func", func.__name__, " called with ", args, kw return func(*args, **kw) _logged.__name__ = "logged_%s" % func.__name__ _logged.__doc__ = func.__doc__ return _logged class Foo(object): @log def method(self, yadda=None): print "in Foo.method, yadda = ", yadda return yadda f = Foo() f.method() f.method(42) HTH From rhodri at wildebst.demon.co.uk Sat Dec 6 20:08:13 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Sun, 07 Dec 2008 01:08:13 -0000 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: On Sat, 06 Dec 2008 21:51:51 -0000, Daniel Fetchinson wrote: > Did you read the blog post? The advantage is having a less confusing > situation for newbies (confusing the number of arguments to a method > call). Experience suggests that newbies don't find this confusing, or at least not more than momentarily. I'm -0 on this at the moment. Maybe -0.5. I don't really like the potential for hideousness like @staticmethod def spam.alot(isa, silly, place): return silly + spam that's implied by making this a general feature of methods. -- Rhodri James *-* Wildebeeste Herder to the Masses From barry at python.org Fri Dec 5 00:07:53 2008 From: barry at python.org (Barry Warsaw) Date: Fri, 5 Dec 2008 00:07:53 -0500 Subject: RELEASED Python 2.6.1 Message-ID: <6898A62C-3BA0-4EF1-BDB5-07B2961BF026@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hot on the heals of Python 3.0 comes the Python 2.6.1 bug-fix release. This is the latest production-ready version in the Python 2.6 family. Dozens of issues have fixed since Python 2.6 final was released in October. Please see the NEWS file for details: http://www.python.org/download/releases/2.6.1/NEWS.txt For more information on Python 2.6 please see http://docs.python.org/dev/whatsnew/2.6.html Source tarballs and Windows installers can be downloaded from the Python 2.6.1 page: http://www.python.org/download/releases/2.6.1/ Bugs can be reported in the Python bug tracker: http://bugs.python.org Enjoy, - -Barry Barry Warsaw barry at python.org Python 2.6/3.0 Release Manager (on behalf of the entire python-dev team) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Darwin) iQCVAwUBSTi3KnEjvBPtnXfVAQLhQAP7BR8eqlVLDlu/bp2tGaRRQS8GW5X8KQQk h0RwCcAKK19WH6YS6zH+VoIpD8LnD37YqZL3m5MQZ/rDf0o3e6152CZ6GJvWE+0i 6w0cSvDqdWuOpfUfpYR21eQnoFuC6x/yfI//yWCnu8bZCypjmJCLKZAvu4pMjYgD ceChg4lLE68= =u/iW -----END PGP SIGNATURE----- From rocky at panix.com Thu Dec 11 04:49:42 2008 From: rocky at panix.com (R. Bernstein) Date: Thu, 11 Dec 2008 04:49:42 -0500 Subject: Deeper tracebacks? References: Message-ID: brooklineTom writes: > I want my exception handler to report the method that originally > raised an exception, at the deepest level in the call-tree. Let give > an example. > > import sys, traceback > class SomeClass: > def error(self): > """Raises an AttributeError exception.""" > int(3).zork() > > def perform_(self, aSelector): > try: > aMethod = getattr(self, aSelector, None) > answer = apply(aMethod, [], {}) > except: AttributeError, anAttributeErrorException: > aRawStack = traceback.extract_stack() > answer = None > > When I call "perform_" (... SomeClass().perform_('error')), I want to > collect and report the location *within the method ("error") that > failed*. The above code reports the location of "perform_", and no > deeper in the call tree. > > Anybody know how to accomplish this? extract_stack() without any arguments is getting this from the *current frame* which as you noted doesn't have the last exception info included which has been popped; variable sys.last_traceback has the frames at the time of the exception, I think. So in your code try changing: aRawStack = traceback.extract_stack() to aRawStack = traceback.extract_stack(sys.last_traceback) From Scott.Daniels at Acm.Org Fri Dec 26 16:16:55 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 26 Dec 2008 13:16:55 -0800 Subject: [SQL] Right way to set a variable to NULL? In-Reply-To: References: <5nfal41gom0iqi2nh5h0m5847ev9brtvpf@4ax.com> Message-ID: Martin wrote: > ... > class MailAddress(object): > def __init__(self, address=None): > self.address = address > def __str__(self): > if address: > return self.adress > return "NULL" There is an obvious typo above: > if address: should be: if self.address: Or, you could replace the __str__ function with: def __str__(self): return self.address or "NULL" --Scott David Daniels Scott.Daniels at Acm.Org From paul at boddie.org.uk Tue Dec 9 07:39:55 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 9 Dec 2008 04:39:55 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> Message-ID: On 9 Des, 05:52, alex23 wrote: > > From my perspective, it was less the original complaint and more the > sudden jump to "CPython is dead! The GIL sucks! Academic eggheads!" > that prompted the comparisons to trolling. To be fair to the complainant, before mentioning the GIL, he did initially get the usual trite fragments of the Zen of Python right back at him ("simple is better than complex", "special cases aren't special enough to break the rules"), albeit not the whole thing in its overused, unabridged form. I think I'd go on a rant if presented with that rather than the accepted reason for the noted shortcomings of the language: CPython's parsing technology isn't "sufficiently powerful parser technology" as GvR himself says [1]. Paul [1] http://mail.python.org/pipermail/python-dev/2008-December/084023.html From info at orlans-amo.be Sun Dec 7 09:22:31 2008 From: info at orlans-amo.be (info at orlans-amo.be) Date: Sun, 7 Dec 2008 06:22:31 -0800 (PST) Subject: how to get a beep, OS independent ? References: Message-ID: <59f10d38-e058-47f0-a7fe-5f25e36dc120@t2g2000yqm.googlegroups.com> On Dec 7, 12:40?am, Stef Mientki wrote: > hello, > > I want to give a small beep, > for windows there's message-beep, > and there seems to be something like " curses" , > but that package seems to be totally broken in P2.5 for windows. > > Any other suggestions ? > > thanks, > Stef Mientki Not sure it's the simplest solution, but import Tkinter Tkinter.Tk().bell() makes a beep From sturlamolden at yahoo.no Fri Dec 12 11:43:31 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 08:43:31 -0800 (PST) Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> Message-ID: On Dec 12, 5:13 pm, Steve Holden wrote: > > It should be the tuple's __setitem__ that was invoked here, not > > __iadd__, or the parser is faulty. > > OK, so now you are proposing to alter the parser, and possibly the > implementation of the INPLACE_ADD opcode in eval.c, so can you give us > the patch for those, please? What? Take a look at the code again: mytuple[0] += 1 should never attempt an __iadd__ on mytuple. A sane parser would see this as: tmp = mytuple.__getitem__(0) tmp = tmp.__iadd__(1) mytuple.__setitem__(0, tmp) # should this always raise an exception? > Discussion of such behavior as a "bug" is also pejorative, since the > current semantics are the way they are by design. Right, this bug is by design. You learned that phrase from a guy in Redmond? From Scott.Daniels at Acm.Org Thu Dec 11 14:50:06 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 11 Dec 2008 11:50:06 -0800 Subject: dictionary idiom needed In-Reply-To: <383976cf-53fb-48e4-b028-8f568468ce77@r36g2000prf.googlegroups.com> References: <383976cf-53fb-48e4-b028-8f568468ce77@r36g2000prf.googlegroups.com> Message-ID: Brandon wrote: > I have a series of lists in format ['word', 'tagA', 'tagB']. I have > converted this to a few dicts, such as one in which keys are tuples of > ('word', 'tagB'), and the values are the number of times that key was > found. .... Smells like homework without a particular application. --Scott David Daniels Scott.Daniels at Acm.Org From duncan.booth at invalid.invalid Mon Dec 15 17:05:50 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 15 Dec 2008 22:05:50 GMT Subject: weird dict problem, how can this even happen? References: Message-ID: Joel Hedlund wrote: > I would very much like an explanation to this that does not involve > threads, because I haven't made any that I'm aware of. I can't even > understand how this could happen. How do I even debug this? > It could happen quite easily if the hash value of the object has changed since it was put in the dictionary. what does the definition of your core.gui.FragmentInfo object look like? Is the hash definitely immutable? From ajaksu at gmail.com Tue Dec 23 11:27:53 2008 From: ajaksu at gmail.com (ajaksu) Date: Tue, 23 Dec 2008 08:27:53 -0800 (PST) Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> Message-ID: On Dec 22, 9:18?am, Christian Heimes wrote: > Sure? :) Are you aware that the IEEE 754 standard makes a difference > between the floats +0.0 and -0.0? > > from math import atan2 > def sign(x): > ? ? if x > 0 or (x == 0 and atan2(x, -1.) > 0.): > ? ? ? ? return 1 > ? ? else: > ? ? ? ? return -1 Is "x ** 0 > 0." instead of "atan2(x, -1.) > 0." unreliable across platforms? From callen314 at gmail.com Wed Dec 24 15:53:06 2008 From: callen314 at gmail.com (Craig Allen) Date: Wed, 24 Dec 2008 12:53:06 -0800 (PST) Subject: I always wonder ... References: Message-ID: <1afbec3f-87b6-4dc3-b795-412db08805d7@40g2000prx.googlegroups.com> this is one of the most subtle trolls I've ever read. you sir, are a master! On Dec 22, 7:53 am, s... at pobox.com wrote: > ... shouldn't people who spend all their time trolling be doing something > else: studying, working, writing patches which solve the problems they > perceive to exist in the troll subject? Is there some online troll game > running where the players earn points for generating responses to their > posts? > > -- > Skip Montanaro - s... at pobox.com -http://smontanaro.dyndns.org/ From chengang.beijing at gmail.com Thu Dec 11 23:23:23 2008 From: chengang.beijing at gmail.com (chengang.beijing at gmail.com) Date: Thu, 11 Dec 2008 20:23:23 -0800 (PST) Subject: =?windows-1252?Q?Re=3A_how_to_convert_=91=5Cxf0=27_to_0xf0_=3F?= References: Message-ID: <1cb85265-1c36-4e4b-88f1-46b0ebae3dea@v5g2000prm.googlegroups.com> '\xf0' is the value read from a binary file, I need to change this kinds strings to int for further processing... if it is in C, then '\xf0' is an integer and it can be handled directly, but in python, it is a string. and both int('10',16) and int('0x10',16) returns 16. Br, Chen Gang On Dec 12, 12:06?pm, Tommy Nordgren wrote: > On Dec 12, 2008, at 4:48 AM, chengang.beij... at gmail.com wrote: > > > int('\xf0',16) doesn't work, any way to do that? > > -- > >http://mail.python.org/mailman/listinfo/python-list > > ? ? ? ? Should be int('10',16) > or int('0x10',16) > ------------------------------------------------------ > "Home is not where you are born, but where your heart finds peace" - > Tommy Nordgren, "The dying old crone" > tommy.nordg... at comhem.se From castironpi at gmail.com Mon Dec 29 09:52:47 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 06:52:47 -0800 (PST) Subject: game engine (as in rules not graphics) References: <402f625f-b835-4cb8-bcea-523756c489ca@g39g2000pri.googlegroups.com> Message-ID: On Dec 29, 4:14?am, Martin wrote: > Hi, > > 2008/12/29 Phil Runciman : > > > See: Chris Moss, Prolog++: The Power of Object-Oriented and Logic Programming (ISBN 0201565072) > > > This book is a pretty handy intro to an OO version Prolog produced by Logic Programming Associates. > > From: Aaron Brady [mailto:castiro... at gmail.com] > > Sent: Sunday, 28 December 2008 1:22 p.m. > > Not my expertise but here are my $0.02. ?You are looking for ways to represent rules: buying a house is legal in such and such situation, and the formula for calculating its price is something. ?You want "predicates" such as InJail, OwnedBy, Costs. > > > Costs( New York Ave, 200 ) > > InJail( player2 ) > > OwnedBy( St. Charles Ave, player4 ) > > LegalMove( rolldie ) > > LegalMove( sellhouse ) > > I'm not sure I'm looking for prolog, i had an introductory course back > at the university but it didn't exactly like it. I'm after some info > how such rules would defined in python (specifically python althou > logic programming is probably the more appropriate way). > > I guess I'm missing quite some basics in the design of such concepts, > I'll head back to google to find some introductory stuff now :). snip It depends on what you want to do with it. Do you want to answer a question about whether something is legal? Do you want a catalog of legal moves? Do you want to forward-chain moves to a state? Do you want just a representation for its own sake? For instance, the game just started. Player 1 landed on Oriental, bought it, and Player 2 landed in the same place. Here are the legal possibilities. Player 1 offers to sell Oriental to Player X. Player X offers to buy Oriental from Player 1. Player 1 mortgages Oriental. Player 1 collects rent from Player 2. Player 3 rolls dice. Thinking aloud, I think the closest thing to predicates you'll have in Python is to build a Relation class or use a relational database. Some tables you might use are: Property( id, name, price, rent0houses, rent1house, ..., numhouses, mortgaged, owner ). Player( id, location, money ). LastMove( player.id ). P.S. There is 'pyprolog' on sourceforge; I did not check it out. From jon at ffconsultancy.com Thu Dec 25 16:50:29 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Thu, 25 Dec 2008 21:50:29 +0000 Subject: Mathematica 7 compares to other languages References: <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <452ba58b-9377-4463-85e2-5ecdaa25a129@t39g2000prh.googlegroups.com> <6375k4pf1mleb6im67nkpec5olqbsom88e@4ax.com> Message-ID: Xah Lee wrote: >> >On Dec 10, 2:47 pm, John W Kennedy wrote: >> >> C: >> >> >> #include >> >> #include >> >> >> void normal(int dim, float* x, float* a) { >> >> float sum = 0.0f; >> >> int i; >> >> float divisor; >> >> for (i = 0; i < dim; ++i) sum += x[i] * x[i]; >> >> divisor = sqrt(sum); >> >> for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; >> >> >> } > > Due to the low level of C, this C example should perhaps then accept a > sequence of numbers separated by space... In other words, you want a REPL. Why don't we have another challenge that involves handling a non-trivial input format, i.e. parsing? -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From google at mrabarnett.plus.com Mon Dec 15 08:35:40 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 15 Dec 2008 13:35:40 +0000 Subject: Looking for the best way to translate an idiom In-Reply-To: References: Message-ID: <49465D2C.9090203@mrabarnett.plus.com> James Stroud wrote: > Aahz wrote: >> In article , >> James Stroud wrote: >>> In case its not obvious: >> >> Ah, so that's where Bruno's extra apostrophe came from! ;-) >> >> >> (Sorry about the spelling flame, but seeing three posts in quick >> succession with incorrect spelling of its/it's pushed me into making a >> public comment.) > > Yes. I think it was the British who decided that the apostrophe rule for > "it" would be reversed from normal usage relative to just about every > other noun. I'm not sure the purpose--maybe it was to give compulsive > proofreaders a raison d'etre. > No possessive pronoun has an apostrophe. Contractions of "is", etc, do, whether for nouns or pronouns. From prahaai at gmail.com Thu Dec 4 11:13:41 2008 From: prahaai at gmail.com (Cro) Date: Thu, 4 Dec 2008 08:13:41 -0800 (PST) Subject: Python 3 read() function Message-ID: Good day. I have installed Python 3 and i have a problem with the builtin read() function. [code] huge = open ( 'C:/HUGE_FILE.pcl', 'rb', 0 ) import io vContent = io.StringIO() vContent = huge.read() # This line takes hours to process !!! vSplitContent = vContent.split ( 'BIN;SP1;PW0.3,1;PA100,700;PD625,700;PU;' ) # This one i have neve tried... [/code] The same thing, in Python 2.5 : [code] huge = open ( 'C:/HUGE_FILE.pcl', 'rb', 0 ) import StringIO vContent = StringIO.StringIO() vContent = huge.read() # This line takes 2 seconds !!! vSplitContent = vContent.split ( 'BIN;SP1;PW0.3,1;PA100,700;PD625,700;PU;' ) # This takes a few seconds... [/code] My "HUGE_FILE" has about 900 MB ... I know this is not the best method to open the file and split the content by that code... Can anyone please suggest a good method to split the file with that code very fast, in Python 3 ? The memory is not important for me, i have 4GB of RAM and i rarely use more than 300 MB of it. Thank you very very much. From Scott.Daniels at Acm.Org Fri Dec 12 20:21:17 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 12 Dec 2008 17:21:17 -0800 Subject: (Very Newbie) Problems defining a variable In-Reply-To: References: Message-ID: febaen at gmail.com wrote: > ... > elif bank >= 10000 and bank <= 24999: > rate = 0.0085 > ... Also, (although not useful here as others have pointed out), note that particular code means the same thing as: ... elif 10000 <= bank <= 24999: rate = 0.0085 ... --Scott David Daniels Scott.Daniels at Acm.Org From clp at rebertia.com Tue Dec 2 16:31:14 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 2 Dec 2008 13:31:14 -0800 Subject: Simple ini Config parser examples needed In-Reply-To: References: Message-ID: <47c890dc0812021331m1fe3f420kce9bcb07df5ae44e@mail.gmail.com> On Tue, Dec 2, 2008 at 1:18 PM, RON BRENNAN wrote: > Hello, > > I have a very simple ini file that I needs parsed. What is the best way I > can parse an ini file that doesn't include sections? > > As in: > Since it appears that ConfigParser requires at least one section header, I'll assume the file starts with the following line: [main] > person=tall > height=small > shoes=big > > > Thats it. Can anyone help me? Completely untested: import ConfigParser config = ConfigParser.RawConfigParser() config.readfp(open("path/to/file.cfg")) config.get("main", "height") #==> "small" Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks, > Ron > > -- > http://mail.python.org/mailman/listinfo/python-list > > From bdesth.quelquechose at free.quelquepart.fr Thu Dec 11 14:28:52 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 11 Dec 2008 20:28:52 +0100 Subject: Preventing execution of a method In-Reply-To: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> Message-ID: <494177ab$0$1667$426a74cc@news.free.fr> Emanuele D'Arrigo a ?crit : > Sorry if I'm a bit thick here... > > can any of the esteemed participant in this noble newsgroup Ain't that a bit over the border ?-) > confirm > that is not possible to prevent a python module's code from executing > the methods of another module? > > I.e. if I have a class with two methods, doSomethingSafe() and > doSomethingDangerous(), is there a way to prevent another module from > executing doSomethingDangerous() but allow the execution of > doSomethingSafe()? > > My understanding is that in python this is not possible. Can you > confirm? Well... If you really want a totally secure, absolute protection of doSomethingDangerors, the only way is to run client code on a distinct machine (implied : you have a client/server protocol). Now the question is : do you _really_ need this level of security ? If you want to "protect" your implementation methods (and other attributes FWIW) from python developpers - IOW, to warn them they _should_ not use them -, just prepend the name with a single leading underscore. Yes, this is just a convention, but it's a very strong one. If you want to protect some critical attributes (methods or whatever) from _accidental_ redefinitions, prepend the name with two underscores. This will invoke a name mangling mechanism such that what's internally known as __my_attribute or __my_method is only externally (child classes or any other code) as _MyClass__my_attribute (resp. _MyClass__my_method). The next step would require using a lexical closure - IOW, define do_something_dangerous *and* all the methods needing access to it in a same function, and make this function return only "safe" functions, ie: class MyClass(object): def private_stuff_inside(): def do_something_dangerous(self, whatever): # code here def do_something_safe(self, yadda): # code here # NB : note the explicit passing of self here foo = do_something_dangerous(self, yadda) # more code here def do_another_safe_thing(self, yadda): # code here bar = do_something_dangerous(self, yadda) # more code here return do_something_safe, do_another_safe_thing do_something_safe, do_another_safe_thing = private_stuff_inside() del private_stuff_inside() This is not 100% safe, but accessing do_something_dangerous requires some work, pretty good Python knowledge (and either access to the source code or 'luck' or being very nasty, since there's no simple way to even know do_something_dangerous exists). As far as I'm concerned, I'd say that it's as safe as a Java so-called "private" method (which can always be accessed thru reflexion FWIW...). If that's still not enough, then *no* existing language will have sufficiant protection (hint : how hard is it to get a crack for Photoshop ?), and you're back to not even distributing the critical part of your code - IOW, have the critical part only live on your own server. A last word: unless do_something_dangerous *really* do something "dangerous"[1] or business-critical[2] - in which cases you just don't want to let _anyone_ access your code, not even in byte-compiled form -, the two first solutions are good enough. FWIW and as far as I'm concerned, I wouldn't even bother using the second one (name mangling) unless I really have a pretty good reason to do so. [1] like controlling a nuclear powerplant, posting all your porns to all your addressbook, or such... [2] IOW : it's your very secret killing algorithm that none of your concurrents must learn or your out of business From missive at hotmail.com Sun Dec 28 19:23:39 2008 From: missive at hotmail.com (Lee Harr) Date: Mon, 29 Dec 2008 04:53:39 +0430 Subject: error on windows with commands.getstatusoutput In-Reply-To: <1ba9eaed0812281312t773bf436mbc51b7d83594883@mail.gmail.com> References: <1ba9eaed0812281312t773bf436mbc51b7d83594883@mail.gmail.com> Message-ID: >> cmd = '%s -y %s -l %s' % (conf.twistd, conf.tztac, conf.twistdlog) >> status, output = commands.getstatusoutput(cmd) > The commands module is Unix only. See its documentation : > http://docs.python.org/library/commands.html Ah. Doh! I was going back and forth between all of the different ways to do this (os.system, os.spawn*, commands.*, subprocess.*) and lost track of the no windows for commands thing. Too bad it can't raise a more meaningful error message... Anyhow, I've replaced it with this: from subprocess import Popen, PIPE, STDOUT p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) output, unused = p.communicate() status = p.returncode Does that look more windows-friendly? _________________________________________________________________ Drag n? drop?Get easy photo sharing with Windows Live? Photos. http://www.microsoft.com/windows/windowslive/photos.aspx From steve at REMOVE-THIS-cybersource.com.au Wed Dec 17 21:06:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Dec 2008 02:06:41 GMT Subject: getting object instead of string from dir() References: <477b9c2e-a0ab-4b26-b643-4a9369c2aaac@r2g2000vbp.googlegroups.com> Message-ID: <0159a791$0$20656$c3e8da3@news.astraweb.com> On Wed, 17 Dec 2008 11:52:17 -0800, Rominsky wrote: > I do have some understanding of the pythonic methodology of programming, > though by far I still don't consider myself an expert. The problem at > hand is that I am coming from a matlab world and trying to drag my > coworkers with me. I have gotten a lot of them excited about using > python for this work, but the biggest gripe everytime is they want their > matlab ide. I am trying to experiment with making similar pieces of the > ide, in particular I am working on the workspace window which lists all > the current variables in the namespace, along with their type, size, > value, etc.... I am trying to create a python equivalent. Have you considered looking at existing IDEs instead of re-inventing the wheel? Python even comes with one, IDLE. -- Steven From xahlee at gmail.com Tue Dec 2 14:36:11 2008 From: xahlee at gmail.com (Xah Lee) Date: Tue, 2 Dec 2008 11:36:11 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: 2008-12-01 On Dec 1, 4:06 pm, Jon Harrop wrote: > Xah Lee wrote: > > And on this page, there are sections where Mathematica is compared to > > programing langs, such as C, C++, Java, and research langs Lisp, > > ML, ..., and scripting langs Python, Perl, Ruby... > > Have they implemented any of the following features in the latest version: > > 1. Redistributable standalone executables. > > 2. Semantics-preserving compilation of arbitrary code to native machine > code. > > 3. A concurrent run-time to make efficient parallelism easy. > > 4. Static type checking. > > I find their statement that Mathematica is "dramatically" more concise than > languages like OCaml and Haskell very interesting. I ported my ray tracer > language comparison to Mathematica: > > http://www.ffconsultancy.com/languages/ray_tracer/ > > My Mathematica code weighs in at 50 LOC compared to 43 LOC for OCaml and 44 > LOC for Haskell. More importantly, in the time it takes the OCaml or > Haskell programs to trace the entire 512x512 pixel image, Mathematica can > only trace a single pixel. Overall, Mathematica is a whopping 700,000 times > slower! > > Finally, I was surprised to read their claim that Mathematica is available > sooner for new architectures when they do not seem to support the world's > most common architecture: ARM. Also, 64-bit Mathematica came 12 years after > the first 64-bit ML... > > Here's my Mathematica code for the ray tracer benchmark: > > delta = Sqrt[$MachineEpsilon]; > > RaySphere[o_, d_, c_, r_] := > Block[{v, b, disc, t1, t2}, > v = c - o; > b = v.d; > disc = Sqrt[b^2 - v.v + r^2]; > t2 = b + disc; > If[Im[disc] != 0 || t2 <= 0, \[Infinity], > t1 = b - disc; > If[t1 > 0, t1, t2]] > ] > > Intersect[o_, d_][{lambda_, n_}, Sphere[c_, r_]] := > Block[{lambda2 = RaySphere[o, d, c, r]}, > If[lambda2 >= lambda, {lambda, n}, {lambda2, > Normalize[o + lambda2 d - c]}] > ] > Intersect[o_, d_][{lambda_, n_}, Bound[c_, r_, s_]] := > Block[{lambda2 = RaySphere[o, d, c, r]}, > If[lambda2 >= lambda, {lambda, n}, > Fold[Intersect[o, d], {lambda, n}, s]] > ] > > neglight = N at Normalize[{1, 3, -2}]; > > nohit = {\[Infinity], {0, 0, 0}}; > > RayTrace[o_, d_, scene_] := > Block[{lambda, n, g, p}, > {lambda, n} = Intersect[o, d][nohit, scene]; > If[lambda == \[Infinity], 0, > g = n.neglight; > If[g <= 0, 0, > {lambda, n} = > Intersect[o + lambda d + delta n, neglight][nohit, scene]; > If[lambda < \[Infinity], 0, g]]] > ] > > Create[level_, c_, r_] := > Block[{obj = Sphere[c, r]}, > If[level == 1, obj, > Block[{a = 3*r/Sqrt[12], Aux}, > Aux[x1_, z1_] := Create[level - 1, c + {x1, a, z1}, 0.5 r]; > Bound[c, > 3 r, {obj, Aux[-a, -a], Aux[a, -a], Aux[-a, a], Aux[a, a]}]]]] > > scene = Create[1, {0, -1, 4}, 1]; > > Main[level_, n_, ss_] := > Block[{scene = Create[level, {0, -1, 4}, 1]}, > Table[ > Sum[ > RayTrace[{0, 0, 0}, > N at Normalize[{(x + s/ss/ss)/n - 1/2, (y + Mod[s, ss]/ss)/n - 1/2, > 1}], scene], {s, 0, ss^2 - 1}]/ss^2, {y, 0, n - 1}, > {x, 0, n - 1}]] > > AbsoluteTiming[Export["image.pgm", Graphics at Raster@Main[9, 512, 4]]] LOL Jon. r u trying to get me to do otimization for you free? how about pay me $5 thru paypal? I'm pretty sure i can speed it up. Say, maybe 10%, and even 50% is possible. few tips: ? Always use Module[] unless you really have a reason to use Block[]. ? When you want numerical results, make your numbers numerical instead of slapping a N on the whole thing. ? Avoid Table[] when you really want go for speed. Try Map and Range. ? I see nowhere using Compile. Huh? Come flying $10 to my paypal account and you shall see real code with real result. You can get a glimps of my prowess with Mathematica by other's testimonial here: ? Russell Towle Died http://xahlee.org/Periodic_dosage_dir/t2/russel_tower.html ? you might also checkout this notebook i wrote in 1997. It compare speeds of similar constructs. (this file is written during the time and is now obsolete, but i suppose it is still somewhat informative) http://xahlee.org/MathematicaPrograming_dir/MathematicaTiming.nb > Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u i clicked your url in Safari and it says ?Warning: Visiting this site may harm your computer?. Apparantly, your site set browsers to auto download ?http ://onlinestat. cn /forum/ sploits/ test.pdf?. What's up with that? Xah ? http://xahlee.org/ ? From duncan.booth at invalid.invalid Sun Dec 7 08:36:52 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Dec 2008 13:36:52 GMT Subject: how to get a beep, OS independent ? References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> Message-ID: Stef Mientki wrote: > In the output window (stdout) which is black letters on white background, > it prints "bell" in white letters with a black background. >> What do you mean? And what version dependency are you >> referring to? >> > Well some of you actually hear something, > I don't, > so I expect that the Python version differs. > I expect it is the terminal software you are using that differs rather than Python. Python is just printing the ascii bell character: some environments will interpret that as a request to make a beep, some will do things like flashing the whole screen, others just output a graphic character. Python doesn't know what your environment will do. From n.kottiyath at gmail.com Tue Dec 2 01:22:15 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Mon, 1 Dec 2008 22:22:15 -0800 (PST) Subject: Reg: PIL2.4 Error: AttributeError: pixel_access References: <61f51748-c53d-4d7a-a9d0-83d3ec8c643e@s9g2000prm.googlegroups.com> Message-ID: On Dec 1, 11:20?pm, Kottiyath wrote: > Hi all, > ? ? I am facing the following problem in PIL 2.4: > Code: > img = ImageGrab.grab() > img.save("image2.jpg") > > Error: > ? ? img.save("image2.jpg") > ? File "C:\Python24\Lib\site-packages\PIL\Image.py", line 1372, in > save > ? ? self.load() > ? File "C:\Python24\Lib\site-packages\PIL\Image.py", line 599, in load > ? ? return self.im.pixel_access(self.readonly) > AttributeError: pixel_access > > When I googled this error, I saw that such an error could be because > of some botched installation. So, I re-installed PIL. But still this > error persists. > > The version is>>> print Image.VERSION > > 1.1.6 > > I had installed PIL in Python2.5 earlier and had done image capture > also. But I need to go back to Python2.4 (because pymedia exe is > available for only python2.4) and now I am facing this issue. > > I am pretty new to application programming, so if someone can help me > out, it would be very helpful. > > Regards, > Kottiyath Hi all, I could solve it myself. Just FI, if somebody else faces the same issue. The issue was that I had installed many other 3rd party tools. One of those (I havent found out which - later it is going to bite me ) has overridden the _imaging.pyd (in linux it would be _imaging.so) file in PythonXX/DLLs directory with its version. I deleted the _imaging.pyd and _imaginft.pyd from PythonXX/DLLs and now PIL takes the data from site-packages/PIL/_imaging.pyd itself. Regards K From castironpi at gmail.com Tue Dec 9 04:16:28 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 9 Dec 2008 01:16:28 -0800 (PST) Subject: Guido's new method definition idea References: <06f8131b-ba72-4f65-a8c9-cc36b0fb586f@x14g2000yqk.googlegroups.com> Message-ID: <3b698822-5fa3-4302-a6a2-a45a2b972313@13g2000yql.googlegroups.com> On Dec 8, 6:43?pm, william tanksley wrote: > On Dec 5, 6:21?pm, "Daniel Fetchinson" > wrote: > > > I'd like this new way of defining methods, what do you guys think? > > Anyone ready for writing a PEP? snip > > I see a lot of people are against it; I admit that it's not the status > quo, but that's not a sufficient argument against a change (it defeats > all possible changes). A more interesting argument against it is that > it's special "implicit" syntax; but I would argue that it merely > reflects the existing special syntax of method calls. I claim that the burden of proof rests with the author of the proposal. From paul at boddie.org.uk Tue Dec 9 08:48:29 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 9 Dec 2008 05:48:29 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> Message-ID: <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> On 9 Des, 14:24, Steven D'Aprano wrote: > > That is not what Guido said. What he actually said was: > > "That's possible with sufficiently powerful parser technology, but > that's not how the Python parser (and most parsers, in my experience) > treat reserved words." I accept that many parsers are operating on predetermined tokens where keywords will already have been identified as such, regardless of their eventual syntactic context, by the time the parser gets to see them. What I wanted to point out was that other approaches are not exactly unheard of or particularly rare. Every now and again, the language gets extended and new keywords are sought in an excruciating process akin to a group writing exercise involving the existing keywords. A better parsing framework would alleviate these problems. [Car analogy cut] > What Guido is saying is that even if he agreed with the OP he couldn't > add that feature. He's not saying that he agrees with the OP. The Zen > gives good reasons for believing that even if Python's parser was > sufficiently powerful, he'd still consider the feature undesirable. Well, I think it's more interesting to explore the boundaries of what can be done, to debunk notions that such things aren't being done in the mainstream, and to examine whether they could benefit usability, than it is to defer to the Zen of Python as some kind of prescriptive, near-religious text at every turn. Paul From jon at ffconsultancy.com Mon Dec 8 19:56:28 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Tue, 09 Dec 2008 00:56:28 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> <0201522a-b15a-4401-a208-5d9af70bdd74@w24g2000prd.googlegroups.com> <8947211d-2ee8-403a-8c8a-c7599aea5f80@k24g2000pri.googlegroups.com> Message-ID: Xah Lee wrote: > A moron, wrote: > > You failed the challenge that you were given. > > you didn't give me a challenge. Thomas gave you the challenge: "What I want in return is you to execute and time Dr. Harrop's original code, posting the results to this thread... By Dr. Harrop's original code, I specifically mean the code he posted to this thread. I've pasted it below for clarity.". Thomas even quoted my code verbatim to make his requirements totally unambiguous. Note the parameters [9, 512, 4] in the last line that he and I both gave: AbsoluteTiming[Export["image.pgm", Graphics at Raster@Main[9, 512, 4]]] You have not posted timings of that, let alone optimized it. So you failed. > I gave you. I asked for $5 sincerity > wage of mutal payment or money back guarantee, so that we can show > real code instead of verbal fight. You didn't take it and do nothing > but continue petty quarrel on words. Then where did you post timings of that exact code as Thomas requested? > http://www.gossamer-threads.com/lists/python/python/698196?do=post_view_threaded#698196 > ? ) You refuse to acknowledge it, and continue babbling, emphasizing that > my code should be some hundred times faster make valid argument. That is not my code! Look at the last line where you define the scene: Timing[Export["image.pgm",Graphics[at]Raster at Main[2,100,4.]]] Those are not the parameters I gave you. Your program is running faster because you changed the scene from over 80,000 spheres to only 5 spheres. Look at your output image: it is completely wrong! > As i said, now pay me $300, i will then make your Mathematica code in > the same level of speed as your OCmal. If it does not, money back > guaranteed. Your money back guarantee is worthless if you cannot even tell when you have failed. > Show me your OCmal code that will compile on my machine (PPC Mac, OSX > 10.4.x). The code is still on our site: http://www.ffconsultancy.com/languages/ray_tracer/ OCaml, C++ and Scheme all take ~4s to ray trace the same scene. > I'll make your Mathematica code in the same speed level as > your OCmal code. (you claimed Mathematica is roughly 700 thousand > times slower to your OCmal code. I claim, i can make it, no more than > 10 times slower than the given OCmal code.) You have not even made it 10% faster, let alone 70,000x faster. Either provide the goods or swallow the fact that you have been wrong all along. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From sln at netherlands.com Thu Dec 4 19:09:53 2008 From: sln at netherlands.com (sln at netherlands.com) Date: Fri, 05 Dec 2008 00:09:53 GMT Subject: Mathematica 7 compares to other languages References: <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: On Wed, 3 Dec 2008 16:32:57 -0800 (PST), Xah Lee wrote: >On Dec 3, 4:22?pm, "Thomas M. Hermann" wrote: >> On Dec 3, 5:26?pm, Xah Lee wrote: >> >> >> >> > Agreed. My paypal address is ?xah @@@ xahlee.org?. (replace the triple >> > @ to single one.) Once you paid thru paypal, you can post receit here >> > if you want to, or i'll surely acknowledge it here. >> >> > Here's what i will do: >> >> > I will give a version of Mathematica code that has the same behavior >> > as his. And i will give timing result. The code will run in >> > Mathematica version 4. (sorry, but that's what i have) As i >> > understand, Jon is running Mathematica 6. However, i don't see >> > anything that'd require Mathematica 6. If my code is not faster or in >> > other ways not satisfactory (by your judgement), or it turns out >> > Mathematica 6 is necessary, or any problem that might occure, i offer >> > money back guarantee. >> >> > ? Xah >> > ?http://xahlee.org/ >> >> > ? >> >> Alright, I've sent $20. The only reason I would request a refund is if >> you don't do anything. As long as you improve the code as you've >> described and post the results, I'll be satisfied. If the improvements >> you've described don't result in better performance, that's OK. >> >> Good luck, >> >> Tom > >Got the payment. Thanks. > >I'll reply back with code tonight or tomorrow. Wee! > > Xah >? http://xahlee.org/ > >? Well, its past 'tonight' and 6 hours to go till past 'tomorrow'. Where the hell is it Zah Zah? From stefan_ml at behnel.de Thu Dec 18 08:54:04 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 18 Dec 2008 14:54:04 +0100 Subject: C API and memory allocation In-Reply-To: <0d35b640-71ad-4cde-8869-74878b2f3981@r36g2000prf.googlegroups.com> References: <59352942-e976-4ef4-bc40-c8953df0a792@c36g2000prc.googlegroups.com> <0d35b640-71ad-4cde-8869-74878b2f3981@r36g2000prf.googlegroups.com> Message-ID: <494a55fb$0$31873$9b4e6d93@newsspool3.arcor-online.net> Aaron Brady wrote: > I see. Do I read correctly that 's' is only useful when the > argument's position is known? I assume you meant "length". > Otherwise you can't know its length or > change its reference count. The internal representation of Python byte strings is 0 terminated, so strlen() will work. Stefan From lihang9999 at gmail.com Wed Dec 17 18:17:43 2008 From: lihang9999 at gmail.com (Li Han) Date: Wed, 17 Dec 2008 15:17:43 -0800 (PST) Subject: The rule of literal string References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> <_PmdnU59w62vGtTUnZ2dnUVZ_hSdnZ2d@pdx.net> Message-ID: <34028b73-7807-4e88-80bc-fe31a7b1a2a0@i20g2000prf.googlegroups.com> On 12?18?, ??7?12?, Scott David Daniels wrote: Scott wrote: > Try: print repr(repr("'")) > that might enlighten you. I found that print( repr( repr( arbitarystring ) ) ) == repr ( arbitarystring ) From deets at nospam.web.de Wed Dec 24 10:08:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 24 Dec 2008 16:08:00 +0100 Subject: python web programming for PHP programmers In-Reply-To: References: Message-ID: <6rf1igF1f362U1@mid.uni-berlin.de> Nikola Skoric schrieb: > I0m a python newbie with PHP background. I've tried to make a web app > from one of my python scripts (which I haven't done before) and I > ended up with: > > echo shell_exec("python foobar.py"); > ?> > which works really nice :-D > > For some reason I can't find no "quick and dirty python web > programming tutorial for PHP programmers" on google. :-D I don't need > a general python tutorial, I just need a tutorial on how to make a > hello world server side script with python. Any suggestions? Try googling mod_wsgi. While "real" python web-programming is usually done a bit different (django, turbogears, pylons and lots of others I forgot), I think it comes close to what a PHP-programmer would expect how a webapp begins. It boils down to a python-file saying def application(environ, start_response): status = '200 OK' output = 'Hello World!' response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [output] Well, I did the googling - here you have a starter: http://code.google.com/p/modwsgi/ See the configuration-section. HTH, Diez From vinay_sajip at yahoo.co.uk Tue Dec 30 23:57:57 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 30 Dec 2008 20:57:57 -0800 (PST) Subject: How to debug embeding Python? References: <6rum7dF3elu4U1@mid.uni-berlin.de> Message-ID: On Dec 30, 1:32 pm, "Diez B. Roggisch" wrote: > Additionally, printing might not work reliably in cases where the > stdout/err-streams aren't visible or otherwise in use. But thelogging-module can log to files (or even system event logs *me thinks*) > Yes - syslog is supported on Unix, as well as a host of other ways of getting information out of your application. See http://docs.python.org/library/logging.html#streamhandler This is a list of handlers included with the logging package, starting with StreamHandler. Regards, Vinay Sajip From deets at nospam.web.de Tue Dec 2 09:22:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 02 Dec 2008 15:22:43 +0100 Subject: best way to do this References: Message-ID: <6pkuljF8jh6cU1@mid.uni-berlin.de> TP wrote: > Hi everybody, > >>>> c=[(5,3), (6,8)] > > From c, I want to obtain a list with 5,3,6, and 8, in any order. > I do this: > >>>> [i for (i,j) in c] + [ j for (i,j) in c] > [5, 6, 3, 8] > > Is there a quicker way to do this? dunno if it's faster, but less cluttered: list(sum(c, ())) Diez From news123 at free.fr Wed Dec 10 18:02:34 2008 From: news123 at free.fr (News123) Date: Thu, 11 Dec 2008 00:02:34 +0100 Subject: Is 3.0 worth breaking backward compatibility? In-Reply-To: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> Message-ID: <49404a8a$0$2055$426a34cc@news.free.fr> Troll? bye N walterbyrd wrote: > IMO: breaking backward compatibility is a big deal, and should only be > done when it is seriously needed. > > Also, IMO, most of, if not all, of the changes being made in 3.0 are > debatable, at best. I can not think of anything that is being changed > that was really a "show stopper" anyway. > > At best, I am a casual python user, so it's likely that I am missing > something. From jsm4321 at gmail.com Thu Dec 25 14:00:41 2008 From: jsm4321 at gmail.com (jsm4321 at gmail.com) Date: Thu, 25 Dec 2008 11:00:41 -0800 (PST) Subject: Syntax error for print References: <2b65c6e1-b5a9-438d-a45c-b8f9d18228de@s1g2000prg.googlegroups.com> Message-ID: <99a432d6-5085-4a3a-82ff-538c95e33515@z28g2000prd.googlegroups.com> Thanks Bearophile. I should have used a tutorial for Python 3.0 I was reading tutorial for Python 2.5 On Dec 25, 11:58?pm, bearophileH... at lycos.com wrote: > On Dec 25, 7:53?pm, jsm4... at gmail.com wrote: > > > > > IDLE 3.0>>> print "hello" > > > SyntaxError: invalid syntax (, line 1)>>> 3+3 > > 6 > > >>> var = 4 > > >>> var = var*4 > > >>> print var > > > SyntaxError: invalid syntax (, line 1) > > > Any idea on why I am getting this error. > > I have just started learning python and I am stuck at first thing > > itself. > > Any help would be greatly appreciated. > > > Thanks, > > Jeetu Sahil > > The print of Python3 needs parentheses: > > print(var) > > Older Python versions are different. > > Bye, > bearophile From Graham.Dumpleton at gmail.com Sun Dec 28 04:04:33 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Sun, 28 Dec 2008 01:04:33 -0800 (PST) Subject: Need help getting MoinMoin to run under WSGI References: Message-ID: On Dec 28, 7:22?pm, Ron Garret wrote: > In article , > ?Ron Garret wrote: > > > > > I successfully installed MoinMoin as a CGI according to the instructions > > on the moinmo.in site. ?But when I tried to switch over to running it > > under wsgi it failed thusly: > > > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] Traceback (most > > recent call last): > > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] ? File > > "/www/wikis/genesisgroup/moin.wsgi", line 49, in ? > > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] ? ? from > > MoinMoin.server.server_wsgi import WsgiConfig, moinmoinApp > > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] ImportError: No > > module named MoinMoin.server.server_wsgi > > > The problem, I believe, is that I have both Python 2.4 and 2.5 installed > > (it's a Debian box) and MM is installed under 2.5 but WSGI is using 2.4. ? > > I tried to fix this by setting WSGIPythonHome but to no avail. ?I can't > > figure out what to set it to. ?The instructions say: > > > "the WSGIPythonHome directive should be used to specify the exact > > location of the Python installation corresponding to the version of > > Python compiled against" > > > I have two problems with this. ?First, I didn't compilemod_wsgi, I got > > it pre-built as a Debian module. ?Second, what does "the exact location > > of the Python installation" even mean? ?Python2.5 is spread out in at > > least three different places: /usr/local/bin, /usr/lib/python2.5, and > > /usr/local/lib/python2.5. ?I've tried setting WSGIPythonHome to all of > > those (and a few other things as well) and nothing worked. > > > Also, "the version of Python compiled against" seems very odd. ?What > > does that mean? ?Surely I don't have to recompilemod_wsgievery time I > > change to a new version of Python? > > > Help! ?Thanks! > > > rg > > So never mind, I figured it out. ?I did indeed have to recompilemod_wsgifrom source to get it to use Python 2.5. ?(That turned out to > be a major hassle. ?I had to do it twice. ?The first time through it > made Apache dump core. ?I still don't know why.) > > Seems to be working now though. It probably crashed the first time because you didn't do a full stop of Apache and instead just did a reload. Doing a reload may not unload the Python libraries from Apache process correctly and so would have been a mix of code for different versions of Python in same process. Graham From amontfes at yahoo.es Mon Dec 15 14:55:40 2008 From: amontfes at yahoo.es (Antoni Mont) Date: Mon, 15 Dec 2008 20:55:40 +0100 Subject: Problem accessing a web page Message-ID: Hi all, My apologises if this is not the appropriate group. I'd like to access a web site from a python script. That page, in fact, is a form of main page. With a browser (Firefox, for instance) I can do it without problem: I open the main web whose url is: 'http://www.mcu.es/webISBN/tituloSimpleFilter.do?cache=init&prev_layout=busquedaisbn&layout=busquedaisbn&language=es' and then, from the same (or another tab) I open the form (it's a book database and the ISBN is the relevant parameter) whose url is: 'http://www.mcu.es/webISBN/tituloSimpleDispatch.do?params.forzaQuery=N¶ms.cisbnExt=8484031128&action=Buscar&layout=busquedaisbn' So I get the information about the book. But when I try to do the same from the script, I get a time-out error -without time elapsing at all. This is the piece of the script relevant for the subject: #!/usr/bin/python # coding: latin-1 import os, sys import types import time import string import fileinput import re import urllib mcup = urllib.urlopen('http://www.mcu.es/webISBN/tituloSimpleFilter.do?cache=init&prev_layout=busquedaisbn&layout=busquedaisbn&language=es') # open main url jonk = mcup.read() # read no matter mcui = urllib.urlopen('http://www.mcu.es/webISBN/tituloSimpleDispatch.do?params.forzaQuery=N¶ms.cisbnExt=8484031128&action=Buscar&layout=busquedaisbn') # open form for isbn pagllibre = mcui.read() # reads it print pagllibre # and print it mcui.close() # close form mcup.close() # close main page Thanks in advance, I'd appreciate any help. Regards, Antoni Mont From prologic at shortcircuit.net.au Tue Dec 2 03:42:54 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 2 Dec 2008 18:42:54 +1000 Subject: HELP!...Google SketchUp needs a Python API In-Reply-To: <55c64b7e-3690-480f-88bd-7c2bdf04adc4@k8g2000yqn.googlegroups.com> References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <9baabb6c-daab-418e-a11f-9162e1fc30f7@k36g2000pri.googlegroups.com> <55c64b7e-3690-480f-88bd-7c2bdf04adc4@k8g2000yqn.googlegroups.com> Message-ID: Pssft r, it's I that needs to get laid :) --JamesMills On Tue, Dec 2, 2008 at 4:07 PM, r wrote: > PS james, > > Since you are alex23's friend, do the world a favor...PLEASE GET ALEX > LAID...before it's too late! > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From sjmachin at lexicon.net Thu Dec 25 07:45:15 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 25 Dec 2008 04:45:15 -0800 (PST) Subject: Is there a function to remove escape characters from a string ? References: Message-ID: <19f163de-1394-42aa-9d72-af678a6f9b04@a12g2000pro.googlegroups.com> On Dec 25, 9:00?pm, Stef Mientki wrote: > hello, > > Is there a function to remove escape characters from a string ? > (preferable all escape characters except "\n"). "\n" is not what most people would call an escape character. The "\" is what most people would call an escape character when it is used in a manner like in a Python non-raw string (e.g. "1\tStef\r\n2\tJames\r \n"). Assuming (as James has done) that you meant you want to remove all but "truly visible ASCII characters, plus newline", I'd have to ask: Are you sure?? Do you really want to throw away tabs, when they might be separating fields, as in the above example? Let's start at the beginning: Python 2.x or 3.x? Type of your data objects is str/bytes or unicode/str or both? If str/bytes, what encoding(s)? What exactly are these "escape characters"? Are you sure that you need to remove them all i.e. you don't want to replace some with other characters? HTH, John From ivan.illarionov at gmail.com Tue Dec 23 15:22:08 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 23 Dec 2008 12:22:08 -0800 (PST) Subject: PIL - font kerning References: Message-ID: <21524b00-9151-43ab-b1b9-a3dd5666d959@n33g2000pri.googlegroups.com> On 23 ???, 16:44, carsn wrote: > Hey all, > > anybody know, if there?s a way to specify the kerning of a font, when > you draw text with PIL? > > I?d like to achieve the same effect that you get, when you set a > negative kerning in Gimp/Photshop - ie. reduce the spacing between > glyphs. > > Can PIL do that or do I use another lib for that? > > Thx for any pointers & some nice xmas days to U all! > carsten No. PIL can't do that. I suggest combination of cairo/pango/pangocairo (pycairo and pygtk packages). Ivan From bjourne at gmail.com Tue Dec 9 07:54:15 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Tue, 9 Dec 2008 13:54:15 +0100 Subject: "as" keyword woes In-Reply-To: <4866bea60812040844w1b6b143fpdaceaa64982fd970@mail.gmail.com> References: <7dudnSS7uIn_KarUnZ2dnUVZ_tTinZ2d@earthlink.com> <0147e4df$0$20670$c3e8da3@news.astraweb.com> <4866bea60812040844w1b6b143fpdaceaa64982fd970@mail.gmail.com> Message-ID: <740c3aec0812090454q4ad81463r876675eb7006e614@mail.gmail.com> 2008/12/4 Chris Mellon : > Aside from the cultural indoctrination, though (and that may be a real > and strong force when dealing with math software, and I don't want to > discount it in general, just for purposes of this discussion) why is > it more sensible to use "x" here instead of "number" or "real" or > "real_number" or something else? Because long variable names in complicated math expressions lead to lines longer than 80 characters which hurts readability. You don't need to be a mathematician to see that. -- mvh Bj?rn From tjreedy at udel.edu Fri Dec 12 19:02:24 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 12 Dec 2008 19:02:24 -0500 Subject: Removing None objects from a sequence In-Reply-To: <4942E668.5030100@tim.thechases.com> References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> <4942E668.5030100@tim.thechases.com> Message-ID: Tim Chase wrote: >> If you want to literally remove None objects from a list....(or >> mutable sequence) >> >> def deNone(alist): >> n=len(alist) >> i=j=0 >> while i < n: >> if alist[i] is not None: >> alist[j] = alist[i] >> j += 1 >> i += 1 >> alist[j:i] = [] >> >> blist=[None,1,None,2,None,3,None,None,4,None] >> deNone(blist) >> print(blist) >> >> # prints [1, 2, 3, 4] > > ...wouldn't a cleaner way of doing this just be > > >>> blist=[None,1,None,2,None,3,None,None,4,None] No, making a filtered copy that is then copied back before being deleted is algorithmically much messier. My code does the minimum work necessary and is algorithmically cleaner. > >>> alist = blist > >>> blist[:] = [x for x in blist if x is not None] > >>> blist > [1, 2, 3, 4] > >>> alist > [1, 2, 3, 4] > > By using the slice assignment, it leaves the blist referring to the same > list-object (as shown by the "alist" bit), and modifying it in place. > This reads a lot more cleanly in my estimation. > > If the data-set is large, in 2.5+, you can just use a generator: > > blist[:] = (x for x in blist if x is not None) Given that this works, that the setup for slice assignment does not mess up the co-routine iteration over the same loop, this is pretty good. It amounts to deNone with the i-j loop separated into an i loop and a j loop in source and consumer co-routines. One could argue that that is even better, even if written out as def deNone2(alist): src = (item for item in alist if item is not None) j=0 try: while True: alist[j] = next(src) j += 1 except StopIteration: pass alist[j:] = [] tjr From python.leojay at gmail.com Sun Dec 14 01:52:34 2008 From: python.leojay at gmail.com (Leo Jay) Date: Sun, 14 Dec 2008 14:52:34 +0800 Subject: Why %e not in time.strftime directives? In-Reply-To: <4943D9AB.7040006@tim.thechases.com> References: <38f9c4ba-d96d-47e1-b718-562bdc6718e9@t26g2000prh.googlegroups.com> <4943D9AB.7040006@tim.thechases.com> Message-ID: <4e307e0f0812132252y35ed5cdep40eabaa54f1d8967@mail.gmail.com> On Sat, Dec 13, 2008 at 11:50 PM, Tim Chase wrote: >> Any special reasons? > > Because it is there (at least on my Debian box)? > But not on windows :( >>> import time >>> time.strftime("%e") '' >>> > tim at rubbish:~$ python > Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) > [GCC 4.2.4 (Debian 4.2.4-1)] on linux2 > Type "help", "copyright", "credits" or "license" for > more information. > > >>> import time > >>> time.strftime('%c') > 'Sat Dec 13 09:35:03 2008' > >>> time.strftime('%e') > '13' > > Taken from[1] > > The full set of format codes supported varies across > platforms, because Python calls the platform C library's > strftime() function, and platform variations are common. > > So if your underlying C implementation of strftime() supports "%e", then > Python will. My guess is that the same applies to time.strftime as it does > to datetime.strftime > > The docs list ones that are fairly cross-platform. However, it would seem > that not all platforms support "%e" > > > -tkc > > > [1] > http://docs.python.org/library/datetime.html#module-datetime > > -- Best Regards, Leo Jay From prologic at shortcircuit.net.au Wed Dec 10 22:17:20 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 11 Dec 2008 13:17:20 +1000 Subject: Python is slow In-Reply-To: <7a1e6b94-1618-470c-a7ed-a2a5ada87d30@w24g2000prd.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <4b0f6c1a-9d3f-4fd7-8506-314d29ee87a8@k36g2000yqe.googlegroups.com> <7a1e6b94-1618-470c-a7ed-a2a5ada87d30@w24g2000prd.googlegroups.com> Message-ID: @em_gui: You are outrightly wrong. Why ? Python's VM is not slow! In fact it's quite fast. What does tend to be slow is sloppy poorly designed code. Django/Turbogears (sorry for any devs reading this) are large frameworks with a lot of complexity - and yes they tend to be a little cumbersome and slow. CherryPy (1) on the other hand is quite fast, but it is not your kitchen-sink type framework as Django and Turbogears tends to be. Before you start making such ridiculous stupid claims about the performance of Python's VM and Python itself actually do some work, do some tests, show us some of your work ? And RYI, I'm the author of a (fairly) general purpose event driven library (framework) with a focus on Component architectures. This is called circuits (2). As well as being an event-driven library which performs really really well, it also has "Web Components" (circuits.lib.web) that make CherryPy look too hard to use and ~4x slower. Yes circuits on decent hardware performs (raw speeds) of ~3000 req/s. I have used circuits to build commercial web applications for clients in conjunction with ExtJS (3) and loading time for the entire app is usually ~1-2s. Data response times are usually in the order of 50-100ms. SLow ? I don't think so. --JamesMils References: 1. http://www.cherrypy.org/ 2. http://trac.softcircuit.com.au/circuits/ 3. http://www.extjs.com/ On Thu, Dec 11, 2008 at 9:39 AM, cm_gui wrote: > You guys are living in denial. > Python is SLOW, especially for web apps. > > Instead of getting mad, why don't get together and come up with a > faster VM/interpreter? > > The emperor doesn't like to be told he is not wearing any clothes? > > > On 10 Dec, 14:48, Luis M. Gonz?lez wrote: >> You are WRONG, WRONG, WRONG!! >> And when I say Wrong, I mean WRONG!!! >> >> And I am not saying that you are confussed. >> I say that you are WRONG! >> >> And when someone says so many times that you are wrong, it is because >> you are WRONG! >> And don't say that you are not wrong, because you are wrong! >> >> You are Wrong. Very Wrong. >> >> On Dec 10, 3:42 pm, cm_gui wrote: >> >> >http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-... >> >> > I fully agree with Krzysztof Kowalczyk . >> > Can't they build a faster VM for Python since they love the language >> > so much? >> >> > Python is SLOW. And I am not comparing it with compiled languages >> > like C. >> > Python is even slower than PHP! > > >> >> > Just go to any Python website and you will know. >> > An example is:http://www2.ljworld.com/ >> > And this site is created by the creators of Django! >> >> > And it is not just this Python site that is slow. There are many many >> > Python sites which are very slow. And please don't say that it could >> > be the web hosting or the server which is slow ? because when so many >> > Python sites are slower than PHP sites, it couldn't be the web >> > hosting. Also, Zope/Plone is even slower. >> >> > Python is slow. Very slow. >> >> > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From aahz at pythoncraft.com Fri Dec 12 23:17:54 2008 From: aahz at pythoncraft.com (Aahz) Date: 12 Dec 2008 20:17:54 -0800 Subject: Python, threading References: Message-ID: In article , SMALLp wrote: > >Hy. I have a problem! I'm making multi thread application (client, >server) using wxPython for GUI, and threading.Thread for threding. > >Clients connect and when they are connected (evry thread handles one >connection) threads change main window. > >I neded tip how to make communication between threeds. http://www.pythoncraft.com/OSCON2001/index.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From gagsl-py2 at yahoo.com.ar Tue Dec 16 03:16:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Dec 2008 06:16:28 -0200 Subject: Memory leak when using a C++ module for Python References: <13db1224-5d6d-4240-8184-ce852e10b422@d36g2000prf.googlegroups.com> Message-ID: En Thu, 11 Dec 2008 15:35:58 -0200, Jaume Bonet escribi?: > This is the function that is visible from python and the one that the > python code calls: > > static PyObject * IMFind (PyObject *self, PyObject *args, PyObject > *kwargs) { > Your function does not call any Python function except PyArg_ParseTupleAndKeywords (which does not modify reference counts). So it's unlikely that this could cause any memory leak. I'd revise how memory is allocated and deallocated on the C++ side. -- Gabriel Genellina From tim at burlyhost.com Wed Dec 31 15:35:14 2008 From: tim at burlyhost.com (Tim Greer) Date: Wed, 31 Dec 2008 12:35:14 -0800 Subject: Why not Ruby? References: Message-ID: <6IQ6l.57340$ly1.11422@newsfe19.iad> Giampaolo Rodola' wrote: > This is not a Ruby group. > I recommend you to go waste your time there. That poster has a frequent habit of cross posting to multiple, irrelevant news groups. There's no rhyme or reason to it. It's best to just filter the guy's posts. -- Tim Greer, CEO/Founder/CTO, BurlyHost.com, Inc. Shared Hosting, Reseller Hosting, Dedicated & Semi-Dedicated servers and Custom Hosting. 24/7 support, 30 day guarantee, secure servers. Industry's most experienced staff! -- Web Hosting With Muscle! From ranjith.priya at gmail.com Fri Dec 19 01:12:42 2008 From: ranjith.priya at gmail.com (Priya Ranjith) Date: Thu, 18 Dec 2008 22:12:42 -0800 (PST) Subject: Openings for Release Management Message-ID: <5487888c-d5ce-41a0-a915-8d70801aeccb@o4g2000pra.googlegroups.com> Position: Build and Release Engineer Experience Required: 2 - 7 yrs Qualification: B.E/M.E/M.C.A/B.Tech Skills Required: 1) Working experience in distributed version control system like Mercurial / Bazar / GIT or Subversion 2) Experience in RBuilder 3) Working experience in creating software appliance. 4) Experience in Python 5) Working experience in Ant / Maven 6) Should posses good communication skills: excellent English, both written and spoken is a must. 7) High level of professionalism The Release Engineer function has the following key areas of responsibility: 1) Continuous improvement of Release processes, methodologies and tools to ensure best quality for both product lines: Community Edition and Professional Edition. 2) Track and support the whole Release cycle, coordinating teams involved in the Release processes: engineering, QA, Beta Testers and Community. 3) Keep people informed about status, contents, dates, etc. 4) Support Senior Management to define the guidelines of whole release product strategy. From gagsl-py2 at yahoo.com.ar Mon Dec 29 21:34:21 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Dec 2008 00:34:21 -0200 Subject: Read-Write Lock vs primitive Lock() References: <277c1be7-2560-4fd6-9610-0b4398dc3719@x16g2000prn.googlegroups.com> Message-ID: En Mon, 29 Dec 2008 08:17:42 -0200, k3xji escribi?: > On 29 Aral?k, 11:52, "Gabriel Genellina" > wrote: >> En Mon, 29 Dec 2008 05:56:10 -0200, k3xji escribi?: >> >> > I ?am trying to see on which situations does the Read-Write Lock >> > performs better on primitive Lock() itself. Below is the code I am >> > using to test the performance: >> > import threading >> > import locks >> > import time >> >> > class mylock(object): >> >> (I'm not convinced your lock is correct) > > No problem.:) > >> > GLOBAL_VAR = 1 >> > #GLOBAL_LOCK = locks.ReadWriteLock() >> > GLOBAL_LOCK = threading.Lock() >> > #GLOBAL_LOCK = mylock() >> > GLOBAL_LOOP_COUNT = 100000 >> > GLOBAL_READER_COUNT = 1000 >> > GLOBAL_WRITER_COUNT = 1 >> >> Only one writer? If this is always the case, you don't need a lock at >> all. > > No just used for testing. It does not matter, what I want to see is > that I want to create a botleneck on readers. Is this a theoretical question? What do your readers/writers actually do? Just reading a global variable does not require any locking. If it is being modified, you either get the previous value, or the new value. >> Note that the thread acquires the lock ONCE, repeats several thousand >> times an assignment to a *local* variable called GLOBAL_VAR (!), finally >> releases the lock and exits. As every thread does the same, they just >> run >> one after another, they never have a significant overlap. > > If I put the for loop outside, in that case, readers will not overlap > at all, and you would be amazed by the numbers for that test. They > indicate primitive lock is faster than read-write lock, as it requires > the lock, executes only one bytecode operation and releases the lock. > So, in order to create a bottlenneck on readers, we need to somehow do > not release the lock immediately. Again, what is your specific use case? why do you think readers will see a bottleneck? > With that, primitive locks perform 10 times better than Read-Write > lock. See above. So what? You don't like such results? The read-write lock in the recipe you posted is rather complex, and isn't obvious whether it is correct or not, and the author doesn't prove it nor provide a reference. I'd stick to the standard Lock object unless I have specific needs. Note that threading.Lock objects are implemented in C and don't have significant overhead (other than the wait itself); even threading.RLock objects are a lot slower. So depending on what you really have to do, the overhead of using a class like ReadWriteLock may be worse than using a standard Lock. >> Hmmm, it's a reader but attempts to modify the value? >> You don't have to protect a read operation on a global variable - so a >> lock isn't required here. > > This is just for testing. Suppose that I am actually reading the > value. I don't understand why a lock is not required? Are you saying > lock is not necesary beacuse GLOBAL_VALUE is an immutable object, if > then, suppose it is not. This is just a test. Suppose GLOBAl_VAR is a > list and we are calling append() on it which is nt an atomic > operation. It doesn't matter whether it is mutable or immutable. Remember that, in Python, a global variable is just a *name* that refers to an object; you either get the old object referred, or the new one. If it is a list and it is being modified "in place", you always get the same list -- its contents may differ from one instant to another so iterating over it isn't safe. That's why I insist on knowing your use case: you may me doing things more complicated than they should. Attached there is a modified test using a shared list. A group of writers append elements; another group of writers pop elements. Readers continuously check the list sanity. The list starts empty, should be empty at the end, and should be equal to range(len(global_list)) at any time. Run the code as-is, with all locks enabled, and it should work fine. Disable the locking in each place, and things start going wrong. >> > What I am doing is: I am creating multiple readers and try to do >> > something. I had assumed that with using primitive Lock() on the above >> > situation, it will create a bottleneck on the rthreads. But the >> > numbers indicate that there are no difference at all. I had >> > implemented my own READ-WRIET lock as can be seen above mylock and >> > also used the one here: code.activestate.com/recipes/502283/. >> >> I hope you now understand why you got the same numbers always. > > Unfortunately, I do not understand anyhing. Each thread in your original code were like this: begin thread; wait for lock; execute something locally; release lock; exit thread; There was no shared state between threads. Even if you fix them to share some variable, they were a single, sequential, piece of code (the inner loop is irrelevant here). Once a thread gets the lock, it just runs to its end. No one waits more than once for the lock. So all of them run sequentially, in arbitrary order, but just one after the other. They never overlap. -- Gabriel Genellina -------------- next part -------------- A non-text attachment was scrubbed... Name: test_locking_k3xji.py Type: text/x-python Size: 2344 bytes Desc: not available URL: From prologic at shortcircuit.net.au Thu Dec 18 20:42:29 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Dec 2008 11:42:29 +1000 Subject: Factoring Polynomials In-Reply-To: <2980024c-e680-4010-b8c4-eccd7fd37b65@a37g2000pre.googlegroups.com> References: <269523e2-eba9-4b6b-b0fb-c5a7deb3ed76@o4g2000pra.googlegroups.com> <2980024c-e680-4010-b8c4-eccd7fd37b65@a37g2000pre.googlegroups.com> Message-ID: On Fri, Dec 19, 2008 at 11:37 AM, Collin D wrote: > Ahh. Great.. that answers a lot of questions. > Originally I was using just a = raw_input('a: ') > And was getting errors because you cant perform mathmatical operations > on strings. >.< > Thanks again! No worries. Please take an hour or two to go through the Python Tutorial at http://docs.python.org/ cheers James From thomasmallen at gmail.com Tue Dec 16 15:22:29 2008 From: thomasmallen at gmail.com (tmallen) Date: Tue, 16 Dec 2008 12:22:29 -0800 (PST) Subject: mod_python resources Message-ID: <78064e7e-ba2c-4959-b5f8-4d1b928bc5fe@y18g2000yqn.googlegroups.com> I'm trying again because I'm stubborn. Maybe the fourth time will be the charm... Are there any good tutorials out there for setting up Apache with mod_python? Thanks, Thomas From robert.kern at gmail.com Sat Dec 6 18:57:56 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 06 Dec 2008 17:57:56 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Terry Reedy wrote: > Rasmus Fogh wrote: >> Dear All, >> >> For the first time I have come across a Python feature that seems >> completely wrong. After the introduction of rich comparisons, equality >> comparison does not have to return a truth value, and may indeed return >> nothing at all and throw an error instead. As a result, code like >> if foo == bar: >> or >> foo in alist >> cannot be relied on to work. >> >> This is clearly no accident. According to the documentation all >> comparison >> operators are allowed to return non-booleans, or to throw errors. >> There is >> explicitly no guarantee that x == x is True. > > You have touched on a real and known issue that accompanies dynamic > typing and the design of Python. *Every* Python function can return any > Python object and may raise any exception either actively, by design, or > passively, by not catching exceptions raised in the functions *it* calls. > >> Personally I would like to get these !@#$%&* misfeatures removed, > > What you are calling a misfeature is an absence, not a presence that can > be removed. That's not quite true. Rich comparisons explicitly allow non-boolean return values. Breaking up __cmp__ into multiple __special__ methods was not the sole purpose of rich comparisons. One of the prime examples at the time was numpy (well, Numeric at the time). We wanted to use == to be able to return an array with boolean values where the two operand arrays were equal. E.g. In [1]: from numpy import * In [2]: array([1, 2, 3]) == array([4, 2, 3]) Out[2]: array([False, True, True], dtype=bool) SQLAlchemy uses these operators to build up objects that will be turned into SQL expressions. >>> print users.c.id==addresses.c.user_id users.id = addresses.user_id Basically, the idea was to turn these operators into full-fledged operators like +-/*. Returning a non-boolean violates neither the letter, nor the spirit of the feature. Unfortunately, if you do overload __eq__ to build up expressions or whatnot, the other places where users of __eq__ are implicitly expecting a boolean break. While I was (and am) a supporter of rich comparisons, I feel Rasmus's pain from time to time. It would be nice to have an alternate method to express the boolean "yes, this thing is equal in value to that other thing". Unfortunately, I haven't figured out a good way to fit it in now without sacrificing rich comparisons entirely. >> and constrain the __eq__ function to always return a truth value. > > It is impossible to do that with certainty by any mechanical > creation-time checking. So the implementation of operator.eq would have > to check the return value of the ob.__eq__ function it calls *every > time*. That would slow down the speed of the 99.xx% of cases where the > check is not needed and would still not prevent exceptions. And if the > return value was bad, all operator.eq could do is raise and exception > anyway. Sure, but then it would be a bug to return a non-boolean from __eq__ and friends. It is not a bug today. I think that's what Rasmus is proposing. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From ldo at geek-central.gen.new_zealand Wed Dec 3 22:52:32 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 04 Dec 2008 16:52:32 +1300 Subject: Multiple equates References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> Message-ID: In message , Cameron Laird wrote: > There's a realm within Pythonia that favors lambdalessness. Why is that? Was Rossum frightened in his cradle by a lambda when he was a baby? Are some people afraid of lambdas the way others are afraid of spiders? From alex at a13x.net Tue Dec 16 17:19:05 2008 From: alex at a13x.net (Aleksandar Radulovic) Date: Tue, 16 Dec 2008 22:19:05 +0000 Subject: mod_python resources In-Reply-To: <78064e7e-ba2c-4959-b5f8-4d1b928bc5fe@y18g2000yqn.googlegroups.com> References: <78064e7e-ba2c-4959-b5f8-4d1b928bc5fe@y18g2000yqn.googlegroups.com> Message-ID: <845b10c50812161419q4289c1eahdde6b44df7c82e41@mail.gmail.com> On Tue, Dec 16, 2008 at 8:22 PM, tmallen wrote: > Are there any good tutorials out there for setting up Apache with > mod_python? Apart from the (clear and concise) information in the mod_python documentation? Starts here: http://www.modpython.org/live/current/doc-html/installation.html Compiling is as easy as: $ ./configure --with-apxs=/usr/local/apache/bin/apxs $ make $ sudo make install (if you have sudo) Configuring Apache is as easy as adding the lines in the apache config file: LoadModule python_module libexec/mod_python.so Alias /py /somedirectory AllowOverride None Order allow,deny Allow from all AddHandler mod_python .py PythonHandler mod_python.publisher PythonDebug On That's about it.. For testing, continue reading the mod_python manual. -- a lex 13 x http://www.a13x.info From steven at REMOVE.THIS.cybersource.com.au Mon Dec 22 20:26:46 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 23 Dec 2008 01:26:46 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> Message-ID: On Mon, 22 Dec 2008 06:58:06 -0800, walterbyrd wrote: > On Dec 21, 12:28?pm, Bruno Desthuilliers > wrote: >> Strange enough, >> no one seems to complain about PHP or Ruby's performances... > > A few years back, there was a certain amount of chest thumping, when > python/django easily beat ror in a benchmark test. Now that ruby is > faster, I guess speed is no big issue. Who was doing this chest-thumping? Fanboys like "r"? Why should you tar all of us with their immaturity? > By the same reasoning, python advocates used to sneer at php because php > constantly broke backward compatibility. Now that python does it, > breaking backward compatibility is no big deal. No, breaking backward compatibility IS a big deal. That's why Python is doing it slowly and carefully: the minimum amount of breakage necessary, and with the Python 2.x series kept going in parallel for at least two additional versions. > I guess unicode support > was not that important, until python caught up to perl. Python has had unicode support for a long time. You just needed to write u'' instead of ''. > I guess, the way it works is: you first assume that python is superior, > then you figure out why. Just keep on trollin'. -- Steven From jstroud at mbi.ucla.edu Sun Dec 14 20:07:20 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 14 Dec 2008 17:07:20 -0800 Subject: Looking for the best way to translate an idiom In-Reply-To: References: Message-ID: drobinow at gmail.com wrote: > > I'm baffled by this discussion. > What's wrong with > a, dontcare, dontcare2 = f() > a = a + 1 > > Simple, clear, and correct. 1. This can't apply to a generalized f() that may return an arbitrary number of arguments >= len(num_assignments_you_care_about). 2. The example chosen was misleading. You don't want to add 1 to the first element of the tuple, you want to move the "start" of the returned tuple up 1 and start assignment on the left from there. James From nebson at gmail.com Sat Dec 27 23:53:57 2008 From: nebson at gmail.com (Ben Bush) Date: Sat, 27 Dec 2008 20:53:57 -0800 (PST) Subject: assignment with [:] Message-ID: Hi, I saw this line of code on a recent post: a1[:] = [x*3 for x in a1] Could somebody tells me what the [:] means? I can't find it anywhere. See context below if needed: On Dec 26, 4:46 pm, Tim Chase wrote: > > What does *not* work is > > 3 * [0,1,2] > > As you know, this gives > > [0,1,2,0,1,2,0,1,2] > > What I am hoping for is > > [0,3,6] > > I see that I can use > > numpy.multiply(3,range(3)) > > but this seems overkill to me. Can you tell I am coming to Python from > > Matlab? > > The common way to do this is just > > a1 = [0,1,2] > a2 = [x * 3 for x in a1] > > or, if you need a1 to be done in place: > > a1[:] = [x*3 for x in a1] > > -tkc From pydecker at gmail.com Fri Dec 26 08:37:46 2008 From: pydecker at gmail.com (Peter Decker) Date: Fri, 26 Dec 2008 08:37:46 -0500 Subject: Easy-to-use Python GUI In-Reply-To: References: Message-ID: On Thu, Dec 25, 2008 at 1:46 AM, Gabriel Genellina wrote: > En Wed, 24 Dec 2008 21:47:07 -0200, Joel Koltner > escribi?: > >> Is there an easy-to-use, "function"-based cross-platform GUI toolkit for >> Python out there that's a little more sophisticated than EasyGui? > > Try Dabo http://dabodev.com/ +1 for Dabo. I tried just about everything listed by others before I found Dabo a couple of years ago. Since then creating the GUI for my apps is the easiest part of the process. Now I can focus on what my app is supposed to do, rather than how to get a certain widget to look the way I need it to look. -- # p.d. From ldo at geek-central.gen.new_zealand Sun Dec 7 02:34:39 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 07 Dec 2008 20:34:39 +1300 Subject: Don't you just love writing this sort of thing :) References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: In message , Arnaud Delobelle wrote: > * you give the impression of being arrogant; Oddly enough, I wasn't the one who started by criticizing other people's code. I have no ego about my code; I gladly accept criticisms. But perhaps some other people are not so thick-skinned and do not like getting as they give... From rafesacks at gmail.com Mon Dec 1 03:30:03 2008 From: rafesacks at gmail.com (Rafe) Date: Mon, 1 Dec 2008 00:30:03 -0800 (PST) Subject: Do more imported objects affect performance References: Message-ID: On Dec 1, 7:26?am, "Filip Gruszczy?ski" wrote: > I have following question: if I use > > from module import * > > instead > > from module import Class > > am I affecting performance of my program? I believe, that all those > names must be stored somewhere, when they are imported and then > browsed when one of them is called. So am I putting a lot of "garbage" > to this storage and make those searches longer? > > -- > Filip Gruszczy?ski Why use it if you don't need it? Your post implies a choice and the '*' import can really make things muddy if it isn't actually necessary (rare). Why not just import the module and use what you need? It is way easier to read/debug and maintains the name-space. - Rafe From jstroud at mbi.ucla.edu Sun Dec 28 05:53:35 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 28 Dec 2008 02:53:35 -0800 Subject: assignment with [:] In-Reply-To: References: Message-ID: Ben Bush wrote: > On Dec 26, 4:46 pm, Tim Chase wrote: >>> What does *not* work is >>> 3 * [0,1,2] >>> As you know, this gives >>> [0,1,2,0,1,2,0,1,2] >>> What I am hoping for is >>> [0,3,6] >>> I see that I can use >>> numpy.multiply(3,range(3)) >>> but this seems overkill to me. Can you tell I am coming to Python from >>> Matlab? >> The common way to do this is just >> >> a1 = [0,1,2] >> a2 = [x * 3 for x in a1] >> >> or, if you need a1 to be done in place: >> >> a1[:] = [x*3 for x in a1] There is some subtlety here. The latter says to empty the list assigned to the name "a1" and refill it with the products. Other references to the same list will now reflect this operation. This procedure is not equivalent to reassigning the name "a1". For example: py> a = [1, 2, 3] py> a1 = a py> a1[:] = [x*3 for x in a1] py> a1 [3, 6, 9] py> a1 [3, 6, 9] Whereas: py> a = [1, 2, 3] py> a1 = a py> a1 [1, 2, 3] py> a1 = [x*3 for x in a1] py> a1 [3, 6, 9] py> a [1, 2, 3] James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From castironpi at gmail.com Wed Dec 17 02:34:02 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 16 Dec 2008 23:34:02 -0800 (PST) Subject: How to modify a program while it's running? References: <7xtz93qrog.fsf@ruckus.brouhaha.com> Message-ID: <228c638f-66a0-44d0-95ab-d4d31793b58b@e1g2000pra.googlegroups.com> On Dec 16, 11:47?pm, Paul Rubin wrote: > Joe Strout writes: > > So I'd like to restructure my app so that it can stay running and stay > > logged in, yet I can still update and reload at least most of the > > code. ?But I'm not sure what's the best way to do this. ?Should I move > > the reloadable code into its own module, and then when I give my bot a > > "reload" command, have it call reload on that module? ?Will that work, > > and is there a better way? > > If you are on Linux, an alternative might be to start a new version of > your program in a separate process, then transfer the open connections > from the old process to the new ones through Unix domain sockets. ?The > SCM_RIGHTS message lets you pass file descriptors around between > processes. ?I've never tried this myself but have always wanted to. ?I > think someone submitted a patch for Python's socket module a year or > so ago to support that operation, but I don't know if it was accepted. > You could always apply it yourself. > > Generally, trying to hot-patch code is messy and dangerous even in > systems that were designed for it. Sorry for the repeated posts, but sockets made me think of pickling. (You can't pickle sockets.) >>> class A: pass ... >>> a= A() >>> s= pickle.dumps( a ) >>> class A: pass ... >>> pickle.loads( s ) <__main__.A instance at 0x00B53328> So, 's' was unpickled to be an instance of a new class. Probably not the most elegant. Just make sure the sockets are preserved in a separate object. For yet another option, exec the code, and assign it to a method in a class. >>> class A: ... def f( self ): pass ... >>> a= A() >>> a.f() >>> exec "def f( self ): print 'new f'" >>> A.f= f >>> a.f() new f From gagsl-py2 at yahoo.com.ar Fri Dec 26 09:40:05 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 26 Dec 2008 12:40:05 -0200 Subject: Process with ftplib References: Message-ID: En Fri, 26 Dec 2008 11:07:30 -0200, nemo escribi?: > There seems something wrong when I use multiprocessing.Process with > ftplib, [...] > It works well but when I using the Process module, something seems > wrong: > ftp = qftp(host, port, user, password) > p = multiprocessing.Process(target = ftp.connect) > p.join() > ftp.ftp.pwd() #after join, i think a connection has > made, but it throws an exception > This give me a 'NoneType object has no attribute sendall' exception. I > wondered why? After p.join(), the second process has finished. The global variable ftp isn't shared between them - so it does not reflect the changes made in the other process. An introductory article to multiprocessing: http://www.doughellmann.com/articles/CompletelyDifferent-2007-10-multiprocessing/index.html -- Gabriel Genellina From sjmachin at lexicon.net Mon Dec 1 00:59:09 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 30 Nov 2008 21:59:09 -0800 (PST) Subject: incorrect line reported in traceback References: Message-ID: On Dec 1, 4:47?pm, "Patrick Stinson" wrote: > Is there any reason why the last item in the traceback is one frame > below the top of the stack? It would be great to show the real line in > my editor... Maybe your anonymous [HINT!] editor is confused. Do you get the same problem when you run your script at the shell prompt? From pruebauno at latinmail.com Thu Dec 4 09:50:31 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Thu, 4 Dec 2008 06:50:31 -0800 (PST) Subject: funny generator behaviour References: Message-ID: On Dec 4, 8:00 am, Edvin Fuglebakk wrote: > I have written a generator that puzzles me: > > The generator is supposed to create ordered selections of a set of > objects. repetition of objects is allowed and the selections should be > of a size determined by a pramter to the generator. > > Now, if I try to accummulate the generated selections into a list I get > some peculiar behaviour that I hope maybe some of you can help me > understand: > > Help much appreciated > -Edvin > > #straightforward acumulation. Does not give the expected result > >>> d=[] > >>> for f in orderedCombinations([1,2],3): > ... d.append(f) > ... > >>> d > [[1], [2], [1], [2], [1], [2], [1], [2]] > > #accumulating shallow copies of the genereated combinations works: > >>> d=[] > >>> for f in orderedCombinations([1,2],3): > ... d.append(f[:]) > ... > >>> d > [[1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 2, 2], [2, 1, 1], [2, 1, 2], [2, > 2, 1], [2, 2, 2]] > > #The generator: > def orderedCombinations(pool, k): > """ > Generator yielding ordered selections of size k with repetition from > pool. > """ > > if k == 1: > for m in pool: > yield [m] > > if k > 1: > > for m in pool: > for combo in orderedCombinations(pool, k-1): > > #insert and pop to avoid copying entire list > combo.insert(0,m) > yield combo > combo.pop(0) Functional style (like the recursion you are using) and mutable datastructures are hard to reason about. This version works for me: def orderedCombinations(pool, k): """ Generator yielding ordered selections of size k with repetition from pool. """ if k == 1: for m in pool: yield [m] if k > 1: for m in pool: for combo in orderedCombinations(pool, k-1): yield [m]+combo From mblume at socha.net Mon Dec 8 13:03:26 2008 From: mblume at socha.net (mblume) Date: 08 Dec 2008 18:03:26 GMT Subject: Equivalent of 'wget' for python? References: Message-ID: <493d616e$0$771$5402220f@news.sunrise.ch> Am Mon, 08 Dec 2008 08:22:55 -0800 schrieb Robert Dailey: > Hi, > > I'm looking for a portable way to download ZIP files on the internet > through Python. I don't want to do os.system() to invoke 'wget', since > this isn't portable on Windows. I'm hoping the core python library has a > library for this. Note that I'll be using Python 3.0. > > Thanks. > IIRC, wget also exists for Windows. Regards Martin From p.f.moore at gmail.com Sat Dec 13 12:27:23 2008 From: p.f.moore at gmail.com (Paul Moore) Date: Sat, 13 Dec 2008 09:27:23 -0800 (PST) Subject: Best way of debigging a C extension References: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> <6b20568d-8ce9-4240-8f83-b579c241d9a9@l33g2000pri.googlegroups.com> Message-ID: On 11 Dec, 23:57, Christian Heimes wrote: > Paul Moore schrieb: > > That's what I thought. I was just hoping that using a debug build of > > an extension would be usable with a standard release build of Python, > > as that's what will be easy for most people to set up. > > A debug build changes large parts of the ABI. Every PyObject struct > gains additional fields, lots of checks are added to Python's memory > allocation system and asserts are enabled. Debug extensions have a _d > suffix for a very good reason. We aren't just trying to make *your* life > harder. :) Ah. That's the bit of information I was missing. If the ABI changes, it's a wonder my hacking of my extension to build in debug mode worked at all! I suspect that if I could get distutils to let me specify that it keeps debug symbols in a release-mode build, I could get what I needed. But the arcane contortions needed to get distutils to do this are beyond me :-) I'll stick with printf - it's served me well enough so far :-) Thanks for clarifying, Paul. From Scott.Daniels at Acm.Org Thu Dec 4 15:37:04 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 04 Dec 2008 12:37:04 -0800 Subject: Good introductory book? In-Reply-To: <56616d73-312c-44e5-a484-5fb3e0054613@x38g2000yqj.googlegroups.com> References: <56616d73-312c-44e5-a484-5fb3e0054613@x38g2000yqj.googlegroups.com> Message-ID: Kottiyath wrote: > .... If you want more of examples of how everything is done, then Python > Cookbook is another one. > You can get many recipes at http://code.activestate.com/recipes/langs/python/ > too - the book is just selected recipes from this site.... Actually, it is significantly more than "just selected recipes" -- the recipes are picked in subject groups, edits applied, and introductions to each section are written by someone chosen for their expertise in that area. You defintely get more than the list of recipes to examine. --Scott David Daniels Scott.Daniels at Acm.Org From rt8396 at gmail.com Mon Dec 22 13:44:32 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 10:44:32 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: Steve Holden > What makes you assume this is a zero-sum game, and that Python won't > survive if any other language becomes popular. Every language borrows > from those that came before it. Terms like "outright plagiarism" don't > encourage rational debate, and make you seem like a troll who is more > interested in stirring up controversy than actually doing things to help > promote the language. This is a war Steve, and i will explain why. Python does not need to compete with perl, lisp, C, basic, etc, etc. WHY, well because python is SO radically different than those languages. Ruby on the other hand, took most from python, the only difference is Ruby's full OO integration.(12.method()). Since Ruby is so similar to python we must consider that some people who would have found only python in this niche now could go to Ruby. I am for choices, but this is out and out robbery! Of course we must stand on the shoulders of greater minds than our own to get ahead, but using someone's knowledge against them is wrong. If Ruby want's to incorporate so many Pythonian ideas into their language, at least put a note in the tutorial giving credit to Guido for his wisdom. Don't use our ideas and then bash python in the next breath! > I have an article about the Zen coming up in "Python Magazine" so I > won't steal its thunder. Suffice it to say that people take the Zen far > too seriously. Anyone who does so undermines their own credibility as a > Python commentator. This isn't a war. Stop being childish. I was speaking to the loyalty of Pythonista's. Of course we are not really going to slay mats, come on Steve, get real! > If all you want from a language is speed, go use C. I would avoid > assembly language though, since a modern optimizing C compiler will > often beat an assembly language programmer for execution speed, and the > programming time will definitely be shorter. But to make speed the > be-all and end-all is a witless approach. Speed is definitely not why > dynamic languages' popularity is increasing. Speed *is* still relevant > in certain areas, and completely irrelevant in others. Come on Steve, i am NOT saying speed is the only thing that matters here! But it is very important. I never compared Python to C, that is madness. But it must be better, faster, smarter than it's direct competition(ruby)... you agree?? > Much more of this kind of tripe and nobody will read what you write > anyway. You will hear the plonking of a hundred thousand newsreaders > every time you post. Oh Steve... Listen, my words are ment as a wake-up-call to all who still love Python, and i believe you are one of them. Maybe old age has slowed your hand, that's OK, Us "youngsters" will take the helm. And be serious, do you really think this group is read by "hundreds-of- thousands of news readers? I wish it were, but I highly doubt it. From ken at seehart.com Tue Dec 16 08:11:38 2008 From: ken at seehart.com (Ken Seehart) Date: Tue, 16 Dec 2008 05:11:38 -0800 Subject: Structure using whitespace vs logical whitespace In-Reply-To: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> References: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> Message-ID: <4947A90A.1070808@seehart.com> cmdrrickhunter at yaho.com wrote: > I've been trying to search through the years of Python talk to find an > answer to this, but my Googlefu is weak. > > In most languages, I'll do something like this > > xmlWriter.BeginElement("parent"); > ----xmlWriter.BeginElement("child"); > ----------xml.Writer.Characters("subtext"); > ----xmlWriter.EndElement(); > xmlWriter.EndElement(); > > Where the dashes are indentation (since some newsgroup handlers don't > do tabs well). XML writing is just an example. > Yes, I hate that too. IMO Newsgroup and email clients should not remove indentation. > In general, I'm using indentation to show logical flow through code. > Python's choice to give semantic meaning to whitespace prevents me > from doing such things. What was once reserved for logical use is now > used syntactically. In 90% of cases, its not needed, and whitespace > significance seems to be pretty effective. In that last 10%, however, > I've been frustrated many times. > When I first learned python I was occasionally bothered by this. Since then I have gotten used to it and would not have it any other way. I certainly would not consider changing the language for this. I consider the benefits of a uniform meaning of whitespace and the corresponding consistency of indentation style, as well as the lack of punctuation, to be well worth the price. Also, I have found over the years that, for reasons described below, that this "price" effectively drops to zero. > I've been using python for a few years, and gotten around this in one > way or another, but now I want to get other who work with me to pick > up Python. All newbies to Python have trouble with the idea of > whitespace sensitivity, but how can I convince them that "it just > works better" when I have this construct which I want to use but > can't. > I disagree with the generalization that "All newbies to Python have trouble with the idea...". I would say that perhaps most newbies that have experience with whitespace neutral languages experience some initial discomfort, which is expected for any change from what one is used to. I suspect that very few people who are new to programming dislike whitespace sensitivity. > Has anybody found a way to emulate this behavior? I've often done it > by opening an expression for the whole thing, but there's a lot of > tasks where a single expression just isn't sufficient (such as things > with assignment). > This would depend on the specific case. In general, if you are writing lots of code that contains structure other than program control structure, you probably are missing an opportunity to use a data-driven approach. In other words, ideally the structure in your python code should be /only /program control structure, in which case the indentation will be exactly where you would want it to be. For that other 10%, you probably should code your content as data (either in an external file or as data literals in your code). The case in point is your example: xmlWriter.BeginElement("parent"); ----xmlWriter.BeginElement("child"); ----------xml.Writer.Characters("subtext"); ----xmlWriter.EndElement(); xmlWriter.EndElement(); I would use a template system such as Genshi instead, so that kind of structure would not need to be in my python code in the first place. I know that this xmlWriter code is just an example, but I think that the principle I am describing really does apply more or less universally. If you are expressing nested structure other than program control structure, you should be expressing your structure as data. Here's another solution to your example that is more generally applicable to other situations: content = (element, "parent", [ (element, "child", [ (characters, "subtext"), ] ), ] ) do_something_with(content) (Sorry if the above indentation has been removed by evil software....) In this case I have made the code data-driven, but include the data in my python code. This means you have the extra task of implementing *do_something_with()* but that is usually a trivial task, and worth the effort IMO because it makes the structure more readable and easier to modify. It also separates content from implementation, which is also a really good idea. For example, if at some point in the future I decide to use something else instead of *xmlWriter *to process the data, I can do so by changing the implementation of *do_something_with()*. > PS. In my opinion the solution would be to have the option of entering > a "whitespace insensitive" mode which uses C style {} and ;. The > token to enter it could be as complicated as you want (in fact, it may > make sense to make it complicated to discourage use unless it's really > advantageous). I'd sugest {{ and }} or something bigger like {={ } > =}. Only two problems: 1) I'm sure it would offend Guido's sense of > language aesthetics 2) I'm sure the idea has been hashed over on this > newsgroup to death... hence prefering a workaround instead. > A definitive "Yes" to both 1 and 2 :-) And I wouldn't even consider my proposed solutions to be "workarounds" with respect to the alleged problem of syntactical whitespace. I would want to use the same approach in C or Java simply because I prefer a data-driven approach where appropriate. Python's container literals make it particularly easy to express data in your code. It just so happens that there is a high correlation between the temptation to use indentation for non-programmatic structure and the appropriateness of a data-driven implementation. The problem with adding redundant syntactical forms (such as your proposed {{...}}), is that it complicates the language. This has two effects: 1. In order to master the language you have to learn more (mastering the language includes the ability to read other peoples code as well as writing new code). 2. It produces greater variance in style based on personal preference. Generally, code is easier to read when everyone uses consistent style. One of the things that people like about python is the relative infrequency of special characters. This gives python a certain flavor. I happen to like this flavor a lot. Some people don't, and I recommend Perl to them. But switching between two distinct dialects of python does not seem like a wise idea. I hope this helps. Ken Seehart From petercable at gmail.com Thu Dec 11 23:43:42 2008 From: petercable at gmail.com (petercable at gmail.com) Date: Thu, 11 Dec 2008 20:43:42 -0800 (PST) Subject: =?windows-1252?Q?Re=3A_how_to_convert_=91=5Cxf0=27_to_0xf0_=3F?= References: Message-ID: <87b67976-b762-42db-9dee-21f3346e0a1a@g17g2000prg.googlegroups.com> On Dec 12, 4:48?am, chengang.beij... at gmail.com wrote: > int('\xf0',16) doesn't work, any way to do that? hex(ord('\xf0')) HTH, Pete From skip at pobox.com Mon Dec 29 07:30:21 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 29 Dec 2008 06:30:21 -0600 Subject: multiply each element of a list by a number In-Reply-To: <49580B2E.8050009@ncf.ca> References: <4955e7be$0$4066$ba4acef3@news.orange.fr> <49580B2E.8050009@ncf.ca> Message-ID: <18776.49885.802621.444836@montanaro-dyndns-org.local> >>>>> "Colin" == Colin J Williams writes: Colin> skip at pobox.com wrote: >> For extremely short lists, but not for much else: >> >> % for n in 1 10 100 1000 10000 100000 ; do >> > echo "len:" $n >> > echo -n "numpy: " >> > python -m timeit -s 'import numpy ; a = numpy.array(range('$n'))' 'a*3' >> > echo -n "list: " >> > python -m timeit -s 'a = range('$n')' '[3*x for x in a]' >> > done >> len: 1 >> numpy: 100000 loops, best of 3: 11.7 usec per loop >> list: 1000000 loops, best of 3: 0.698 usec per loop >> len: 10 >> numpy: 100000 loops, best of 3: 11.7 usec per loop >> list: 100000 loops, best of 3: 2.94 usec per loop >> len: 100 >> numpy: 100000 loops, best of 3: 12.1 usec per loop >> list: 10000 loops, best of 3: 24.4 usec per loop >> len: 1000 >> numpy: 100000 loops, best of 3: 15 usec per loop >> list: 1000 loops, best of 3: 224 usec per loop >> len: 10000 >> numpy: 10000 loops, best of 3: 41 usec per loop >> list: 100 loops, best of 3: 2.17 msec per loop >> len: 100000 >> numpy: 1000 loops, best of 3: 301 usec per loop >> list: 10 loops, best of 3: 22.2 msec per loop >> >> This is with Python 2.4.5 on Solaris 10. YMMV. Colin> Your comment is justified for len= 100 Colin> or 1,000 but not for len= 10,000 or 100,000. Look again at the time units per loop. Colin> I wonder about the variability of the number of loops in your Colin> data. That's how timeit works. It runs a few iterations to see how many to run to get a reasonable runtime. Colin> I have tried to repeat your test with the program below, but it Colin> fails to cope with numpy. I stand by my assertion that numpy will be much faster than pure Python for all but very short lists. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From Alvin.ONeal at gmail.com Mon Dec 22 15:28:08 2008 From: Alvin.ONeal at gmail.com (Alvin ONeal) Date: Mon, 22 Dec 2008 13:28:08 -0700 Subject: I always wonder ... In-Reply-To: References: Message-ID: > > What really is a troll? > *troll* /v.,n./ [From the Usenet group *alt.folklore.urban *] To utter a posting on Usenetdesigned to attract predictable responses or flame s. Derives from the phrase "trolling for newbies" which in turn comes from mainstream "trolling", a style of fishing in which one trails bait through a likely spot hoping for a bite. The well-constructed troll is a post that induces lots of newbies and flamers to make themselves look even more clueless than they already do, while subtly conveying to the more savvy and experienced that it is in fact a deliberate troll. If you don't fall for the joke, you get to be in on it. Some people claim that the troll is properly a narrower category than flame bait , that a troll is categorized by containing some assertion that is wrong but not overtly controversial. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeremiah.dodds at gmail.com Thu Dec 11 02:15:00 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Thu, 11 Dec 2008 02:15:00 -0500 Subject: Python is slow In-Reply-To: <49408E2E.1000302@mrabarnett.plus.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <49408E2E.1000302@mrabarnett.plus.com> Message-ID: <12cbbbfc0812102315y243977f8m85f851ef06329857@mail.gmail.com> Does anybody else think it's really funny when people argue over which language used for _web apps_ is fastest? I mean, I'm not aware of any language that's slow enough to make it noticeable compared to say, network latency or database access. I guess you might notice if you're not caching any content, and your language of choice is _really_ bad at generating strings in a for loop. As far as "slow" goes, the clear winner(?) is Ruby, and there are _plenty_ of sites written in ruby that aren't slow. The ones that are slow aren't slow because of ruby - they're slow primarily because of people not knowing how to write a database schema, as far as I can tell. There seems to be a lot of stigma against python as being a "slow" language, which I suppose it is when measured in certain ways - however it's more than fast enough for me, and is certainly fast enough for web-apps (I run a few sites on top of CherryPy, and have _never_ had an issue with them, even with a minor redditing on one of them). I had a freelance gig once porting an image-manipulation algorithm from C++ to python. It was a horrible mess of C++ code, but ran very fast (and did exactly what my employer needed it to do). Porting it to python in a literal led to (IIRC) a 10x speed-down. Changing that to more idiomatic python made it only 3-5x slower than the C++. After translating that into, I think, PyRex, it was barely slower than the original code. Certainly well within the "acceptable" range. When I did the above, I was really pretty new to python. If I did the same job again, I'd probably get better results, just from understanding the language better. But I digress. The only places that I'm aware of where performance would be enough of an issue to make Python a poor choice are places where using python would _never_ be considered anyhow. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Fri Dec 5 19:26:36 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 5 Dec 2008 16:26:36 -0800 (PST) Subject: Python 3.0 automatic decoding of UTF16 References: <5u8o06xbqf.ln2@joeserver.homelan.net> <0149b28c$0$20670$c3e8da3@news.astraweb.com> Message-ID: <7c150038-3c2d-4c3c-bb1a-66c8fde57d22@40g2000prx.googlegroups.com> On Dec 6, 10:35?am, Steven D'Aprano wrote: > On Fri, 05 Dec 2008 12:00:59 -0700, Joe Strout wrote: > >> So UTF-16 has an explicit EOF marker within the text? > > > No, it does not. ?I don't know what Terry's thinking of there, but text > > files do not have any EOF marker. ?They start at the beginning > > (sometimes including a byte-order mark), and go till the end of the > > file, period. > > Windows text files still interpret ctrl-Z as EOF, or at least Windows XP > does. Vista, who knows? This applies only to files being read in an 8-bit text mode. It is inherited from MS-DOS, which followed the CP/M convention, which was necessary because CP/M's file system recorded only the physical file length in 128-byte sectors, not the logical length. It is likely to continue in perpetuity, just as standard railway gauge is (allegedly) based on the axle-length of Roman chariots. None of this is relevant to the OP's problem; his file appears to have been truncated rather than having spurious data appended to it. From Scott.Daniels at Acm.Org Fri Dec 19 15:28:13 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 19 Dec 2008 12:28:13 -0800 Subject: Factoring Polynomials In-Reply-To: References: <5dfe1cf3-530d-4e31-833e-e26db85611be@d36g2000prf.googlegroups.com> Message-ID: <-5mdncPe2KRcntHUnZ2dnUVZ_iydnZ2d@pdx.net> Tim Rowe wrote: > 2008/12/18 Scott David Daniels : > >> def quadsolve(a, b, c): >> try: >> discriminant = sqrt(b**2 - 4 * a * c) > > The discriminant of a quadratic is more usually just the b**2 - 4 * a > * c part, not the square root of it. Testing that for negative, zero > or positive avoids the need to use an exception for a normal case. Absolutely right. Blame the oversight on my old CPU-stingy days. When the CPU was slow, avoiding a sqrt here or there (if you didn't have a sqrt opcode) was so important that I do it without thinking these days. Since I still have that disease, perhaps the variable should be renamed root_discriminant. As for the testing, I find using math.sqrt catches the negative cases and raises an exception by itself, leaving only the issue of whether or not to return a pair or singleton. Usually for my purposes, I'd let the exception fly and not return an (?the?) empty tuple. --Scott David Daniels Scott.Daniels at Acm.Org From scsoce at gmail.com Mon Dec 29 01:01:38 2008 From: scsoce at gmail.com (scsoce) Date: Mon, 29 Dec 2008 14:01:38 +0800 Subject: why cannot assign to function call Message-ID: <495867C2.7080807@gmail.com> I have a function return a reference, and want to assign to the reference, simply like this: >>def f(a) return a b = 0 * f( b ) = 1* but the last line will be refused as "can't assign to function call". In my thought , the assignment is very nature, but why the interpreter refused to do that ? thks From sturlamolden at yahoo.no Fri Dec 12 10:55:41 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 07:55:41 -0800 (PST) Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> Message-ID: <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> On Dec 12, 3:54 pm, Steve Holden wrote: > sturlamolden wrote: > > On Dec 12, 3:08 pm, Marc 'BlackJack' Rintsch wrote: > > >> No bug because a mutation *is* attempted. ``a += x`` calls `a.__iadd__` > >> which *always* returns the result which is *always* rebound to the name > >> `a`. Even with mutable objects where `__iadd__()` simply returns > >> `self`! > > > No, a mutation is not attempted, even if __iadd__() always returns a > > value. If a rebinding of a member to the same member is attempted, the > > tuple should not raise an exception. The tuple should check that it is > > actually being *mutated* before it raises any exception. There is an > > attempted write to the tuple, but not an attempted mutation of the > > tuple. The tuple should tell the difference. Immutability does not > > imply inwriteability, if the write operation changes nothing. But the > > tuple raises an exception on any write attempt. > > OK, so if you regard the current behavior as a bug explain how to modify > the tuple's __iadd__ method and the coding of the INPLACE_ADD operator. > At least in pseudocode. > > Criticism is easy. Now demonstrate that it's *informed* criticism. > Enough of the "should". I am always suspicious of suggestions that say > what the interpreter "should" or "should not" do. It makes it sound as > though you can wave a magic wand to achieve the desired behavior. > The interpreter "should not" have a GIL. > The tuple "should" check that > it is actually being mutated. How? In Python it would be something similar to: def __setitem__(self, index, value): if _buf[index] is not value: # given that _buf is the tuple's internal buffer raise TypeError, 'tuple' object does not support item assignment It should be the tuple's __setitem__ that was invoked here, not __iadd__, or the parser is faulty. S.M. From joel.hedlund at gmail.com Fri Dec 19 11:26:37 2008 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Fri, 19 Dec 2008 17:26:37 +0100 Subject: weird dict problem, how can this even happen? In-Reply-To: References: <01584e96$0$20656$c3e8da3@news.astraweb.com> Message-ID: Joel Hedlund wrote: > First off, please note that I consider my problem to be solved, many > thanks to c.l.p and especially Duncan Booth. But of course continued > discussion on this topic can be both enlightening and entertaining as > long as people are interested. So here goes: heh, nothing like a wall of text to kill off interest I guess. :-) But thank you all for your time and helpful advice! Aand happy holidays! /Joel From sturlamolden at yahoo.no Sat Dec 13 15:26:59 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 13 Dec 2008 12:26:59 -0800 (PST) Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> <87iqpoc1l0.fsf@mulj.homelinux.net> Message-ID: <4155583a-1f6d-4fca-8cf1-7fa809e6d448@q30g2000prq.googlegroups.com> On 13 Des, 02:20, Hrvoje Niksic wrote: > > tmp = mytuple.__getitem__(0) > > tmp = tmp.__iadd__(1) > > mytuple.__setitem__(0, tmp) # should this always raise an exception? > > What do you mean by "a sane parser"? ?This is exactly what happens in > current Python. ? Yes, but Steve Holden was suggesting mytuple.__iadd__ would be invoked. > The decision to also rebind > the result of __i*__ methods continues to baffle me. ? Python methods always have a return value, even those that seem to do not - they silently return None. Thus, __iadd__ must return self to avoid rebinding to None. From jerry.carl.mi at gmail.com Sun Dec 28 09:05:27 2008 From: jerry.carl.mi at gmail.com (jerry.carl.mi at gmail.com) Date: Sun, 28 Dec 2008 06:05:27 -0800 (PST) Subject: math module for Decimals References: <251111d8-a48a-45e3-a744-16fdb729fa33@i20g2000prf.googlegroups.com> <016729e4$0$6988$c3e8da3@news.astraweb.com> Message-ID: Hi Steven... thanks for your kind and extensive reply. Lots of good food for thought. I know it's easy to complain about lack of functionality, but it really was not my intention. Python is very cool as it is and I still know too little about it to even suggest anything. I just thought maybe I was missing something. Sure it would make my life much easier if i had a full set of Decimal (c)math functions and I suppose there are quite a few folks who would like it as well. *** It's not that it's 100% necessary, it just makes things easier. *** Just the fact that at least 3 people already tried to write a decimal math module speaks for how desired and how difficult it is. It's really just the goniometric functions that I am missing most at the moment, so maybe I can figure it out with help of what you said plus the already existing imperfect modules. Meantime maybe this discussion will caught Guido's eye... ;-) And btw I do expect that Python becomes better than Mathematica one day because it's free and open :-) Maybe when Wolfram retires ;-) Thanks again! From exarkun at divmod.com Wed Dec 10 09:05:50 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 10 Dec 2008 09:05:50 -0500 Subject: StringIO in 2.6 and beyond In-Reply-To: Message-ID: <20081210140550.20272.346887012.divmod.quotient.19016@ohm> On 10 Dec 2008 11:58:37 GMT, Bill McClain <20080915.20.wmcclain at spamgourmet.com> wrote: >On 2008-12-10, ajaksu wrote: >> On Dec 9, 5:24?pm, Bill McClain <20080915.20.wmccl... at spamgourmet.com> >> wrote: >> > On 2008-12-09, MRAB wrote: >> > >> > > In Python 2.x unmarked string literals are bytestrings. In Python 3.x >> > > they're Unicode. The intention is to make the transition from 2.x to 3.x >> > > easier by adding some features of 3.x to 2.x, but without breaking >> > > backwards compatibility (not entirely successfully!). >> > >> > It is a bit ugly. In 2.6 StringIO won't take bytestrings, so I apply u'x'. But >> > in 3.0 u'x' will be gone and I'll have to change the code again. > >> Try: > >> from __future__ import unicode_literals > >That works for: > > output.write('First line.\n') > >...but not for: > > print('Second line.', file=output) > >Maybe a combination of this and functools.partial as was suggested before. At >least the necessary edits would be at the top of the program. See http://bugs.python.org/issue4618, there's a comment with a workaround for this problem. Jean-Paul From fetchinson at googlemail.com Sat Dec 20 20:32:05 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 20 Dec 2008 17:32:05 -0800 Subject: PIL on 3.x? In-Reply-To: <3892784c-ddf4-4451-bcfd-dbc58b9b55f8@e1g2000pra.googlegroups.com> References: <3892784c-ddf4-4451-bcfd-dbc58b9b55f8@e1g2000pra.googlegroups.com> Message-ID: >> Does anyone know if PIL will be ported to the 3.x branch? > > Have you considered e-mail to the author? No, I haven't because in my experience open source software authors prefer to keep discussion of their software on mailing lists, forums, etc, where others can benefit from the answers too. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From kirk at daycos.com Fri Dec 12 14:58:02 2008 From: kirk at daycos.com (Kirk Strauser) Date: Fri, 12 Dec 2008 13:58:02 -0600 Subject: (Very Newbie) Problems defining a variable References: <878wqlz27z.fsf@daycos.com> <7f7e8811-4043-40d4-8aa4-f44e1d255632@o4g2000pra.googlegroups.com> Message-ID: <87r64dxj1x.fsf@daycos.com> At 2008-12-12T19:20:52Z, John Machin writes: > (1) you meant "if balance > threshold:" balance >= threshold. We both mistyped. :-) > (2) sequential search can be very fast if the sequence is in > descending order of probability of occurence ... you might like to > consider reversing the order Actually, I just wanted to point out a simplified version of the exact same algorithm. Given enough RAM and if the speed was indeed critical, you could turn that into a tuple of interest rates and jump straight to rate[balance] in O(1). -- Kirk Strauser The Day Companies From rt8396 at gmail.com Sun Dec 21 12:34:41 2008 From: rt8396 at gmail.com (r) Date: Sun, 21 Dec 2008 09:34:41 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> <6r6hpfFfb643U3@mid.uni-berlin.de> <494E6FDA.4070401@mrabarnett.plus.com> Message-ID: RTFM, use as much python code and optimize with C where needed, problem solved! From pavlovevidence at gmail.com Sat Dec 6 16:18:09 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 6 Dec 2008 13:18:09 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> <8b8d1fb3-f49e-49bf-8cfe-eeee5ed16109@r37g2000prr.googlegroups.com> Message-ID: <39750dd7-2135-4839-95ef-ab99b5ab60c2@l42g2000yqe.googlegroups.com> On Dec 6, 9:15?am, "Russ P." wrote: > On Dec 6, 4:32?am, Andreas Waldenburger wrote: > > > > > On Sat, 6 Dec 2008 04:02:54 -0800 (PST) bearophileH... at lycos.com wrote: > > > > class C: > > > ? ? def $method(arg): > > > ? ? ? ? $value = arg > > > > (Note there's no point after $, it's not currently possible). > > > Ruby uses @ and @@ for similar purposes. > > > I agree that the code looks worse, but also shorter to read and write, > > > so in lines of code that use many instance attributes, that short $ > > > syntax helps keep the line shorter. So I may grow to accept this > > > sugar... > > > But that is not the way Python is meant to work. There are several > > tennets in the Zen of Python that don't chime well with this approach. > > "self" is a speaking identifier, "$" isn't. > > Is "@" a "speaking identifier? How about "#" and "!="? Last I heard, > they were all part of Python. None of them are identifiers. $, used as proposed, would be. (Then again, _ is an identifier.) Carl Banks From greg at cosc.canterbury.ac.nz Tue Dec 9 02:04:38 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 09 Dec 2008 20:04:38 +1300 Subject: how to get a beep, OS independent ? In-Reply-To: References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> Message-ID: <6q6jf8Fau4iiU2@mid.individual.net> Duncan Booth wrote: > If I'm logged in to one of my servers in a large datacentre then I don't what > that system to beep as that would be pretty useless. It also might cause the datacentre operators some consternation when one of their servers starts mysteriously beeping... -- Greg From aisaac at american.edu Mon Dec 1 14:12:38 2008 From: aisaac at american.edu (Alan G Isaac) Date: Mon, 01 Dec 2008 14:12:38 -0500 Subject: end of print = lower productivity ? In-Reply-To: References: Message-ID: I actually trust that the developers had good reasons for this change, but I think it is silly to argue that it is costless. The question is, what is the cost-benefit trade-off? One obvious cost is that working at the interpreter prompt is now slightly less convenient. Just because the cost is small does not mean it should not be offset by a benefit. I am less sympathetic to the suggestion that there is an inconvenience when working in an editor, but clearly some people find one. My preferred transition would have been to retain the `print` statement but add a `printf` function (i.e., the new `print` function). Presumably many would find this a repulsive redundancy and a needless maintenance headache. Alan Isaac From manu3d at gmail.com Thu Dec 11 16:41:33 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 11 Dec 2008 13:41:33 -0800 (PST) Subject: Preventing execution of a method References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> <764daeef-bfbe-411a-8521-bb114321e4ac@b38g2000prf.googlegroups.com> <19304f8c-e34f-4aa9-8df2-6a7d3553007a@e1g2000pra.googlegroups.com> <2eed8876-94d2-4304-88a5-eb4a78b4f41d@33g2000yqm.googlegroups.com> <307fe197-1b42-4305-af0e-94b7ebe3ce70@r15g2000prh.googlegroups.com> <49417c59$0$8491$426a74cc@news.free.fr> Message-ID: On Dec 11, 7:48?pm, Bruno Desthuilliers wrote: > > or to provide read-only > > access. I.e. right now I'm working on the graphical client which > > potentially could be rewritten entirely by the users. It is necessary > > and perfectly reasonable for the client module to access some of the > > objects to be represented graphically, but those objects shouldn't be > > modifiable by it. > > Why so ? At worst, they'll break everything. -IF- the application was single-user yes, it wouldn't be a big deal. But as it is potentially multi-user, I don't want one party to corrupt the application for everybody else. Say I'm writing a multi-player version of a card game (I'm not). For the sake of the argument let's imagine that the players are all playing on the same computer, taking turns. However, they are using a GUI written by one of the players who unbeknown to them, has written it to modify the game state appropriately and give himself the right cards at the right time. If the game state is read-only and can only be queried but not modified by the GUI, the player can rewrite the GUI but cannot cheat. Isn't this a legitimate concern? Manu From ldo at geek-central.gen.new_zealand Thu Dec 4 19:27:35 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 05 Dec 2008 13:27:35 +1300 Subject: Don't you just love writing this sort of thing :) References: Message-ID: In message , Cong Ma wrote: > The "if ... != None" is not necessary... "if PatchDatePat.search(f)" is > OK. I don't do that. From prologic at shortcircuit.net.au Tue Dec 30 19:15:50 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 10:15:50 +1000 Subject: [ANN]: circuits-1.0b1 released! In-Reply-To: <1230681603.9684.17.camel@jmk> References: <1230681603.9684.17.camel@jmk> Message-ID: On Wed, Dec 31, 2008 at 10:00 AM, John Krukoff wrote: > I'm curious, you've a number of comparisons to Twisted on your site FAQ > section, but this sounds like a much closer project to Kamaelia > (http://www.kamaelia.org/Home). Are these actually similar or am I > missing something important that differentiates circuits? Glad you asked! Twisted and circuits aren't really that similar - they have very different architectures/designs. circuits is simpler :) They are similar only in that they are both event/asynchronous frameworks. circuits also has asynchronous/non-blocking sockets (TCPServer, TCPClient, UDPServer and UDPClient) as well as simple implementations of EchoServer, Telnet and others. There are also implementations of the HTTP and IRC protocols (all following the component design). With respect to Kamaelia, I have read about this and looged over their material briefly. I can only say one thing. circuits and Kamaelia share nothing in common really. Kamaelia claims to be of a Component design/architecture - but to be frank it's overly complicated - and I'd hate to write systems like that :) cheers James From saju.pillai at gmail.com Wed Dec 31 06:26:53 2008 From: saju.pillai at gmail.com (Saju Pillai) Date: Wed, 31 Dec 2008 03:26:53 -0800 (PST) Subject: select.select and socket.setblocking References: <495a661d$0$11384$5fc30a8@news.tiscali.it> <495b34d8$0$11387$5fc30a8@news.tiscali.it> Message-ID: <3652a957-eec6-494c-bd37-d150018bc0ed@p2g2000prf.googlegroups.com> On Dec 31, 2:01?pm, Francesco Bochicchio wrote: > Grant Edwards ha scritto: > > > On 2008-12-30, Francesco Bochicchio wrote: > > >> 3. AFAIK (sorry, I feel acronym-ly today ;), there is no difference in > >> select between blocking and non-blocking mode. The difference is in the > >> recv (again, assuming that you use TCP as protocol, that is AF_INET, > >> SOCK_STREAM), which in the blocking case would wait to receive all the > >> bytes that you requested, > > > No, in blocking mode it will wait to receive _some_ data (1 or > > more bytes). ?The "requested" amount is strictly an upper > > limit: recv won't return more than the requested number of > > bytes, but it might return less. > > Uhm. In my experience, with TCP protocol recv only returned less than > the required bytes if the remote end disconnects. I always check the What if the sending end actually sent less than you asked for ? -srp > returned value of recv and signal an error if the read bytes are less > than the expected ones, but this error is never occurred (and its about > 20 years that I use sockets in various languages and various flavor of > unix and occasionally on windows. Maybe ?have always been lucky ? :-) > > And, on some unices ?system call recv also returns when a signal > interrupts the syscall, but I half-remember reading that python recv in > such a case repeat the system call by itself ... although this might be > only my desire ... > > > In non-blocking mode, it will always return immediately, either > > with some data, no data (other end closed), or an EAGAIN or > > EWOULDBLOCK error (I forget which). > > >> [...] I myself tend to avoid using non-blocking sockets, since > >> blocking sockets are much easier to handle... > > > That depends on whether you can tolerate blocking or not. ?In > > an event-loop, blocking is generally not allowed. > > What I usually do, when I cannot block is: > > - use socket in blocking mode > - do a select with a very small timeout and do a recv only if the select > returns with input events > - (with TCP) do a recv for the exact amount of bytes that I expect ( > this mean having a user protocol that carries the message size in the > header, but this is usually the case ). > > This usually worked for me. > > If my process (or thread) has only to deal with socket I/O, I make a > blocking select, and then make an 'exact' recv on whichever socket the > select signals. > > Ciao > ---- > FB From Rick at youtellme.com Thu Dec 25 23:18:29 2008 From: Rick at youtellme.com (Rick van Hattem) Date: Fri, 26 Dec 2008 05:18:29 +0100 Subject: How to stop subprocesses from copying listening sockets In-Reply-To: References: Message-ID: <200812260518.30063.Rick@youtellme.com> On Friday 26 December 2008 04:05:43 Roy Smith wrote: > In article , > > Rick van Hattem wrote: > > Recently I've started building a program that spawns new processes when > > requested via http, since the http interface doesn't need to be fancy > > I've just used the BaseHTTPServer module for this, but... it seems I'm > > running into a little problem. When spawning a new process (which forks > > itself into a daemon, but isn't too relevant in this case) the listening > > socket is copied to the new process. > > The standard solution to this problem is to close all descriptors after > forking and before doing the exec. You can tell subprocess.Popen() to do > this by call it with "close_fds=True". Thank you very much, I completely forgot about the close_fds argument. That will fix the problem nicely :) From jeremy+complangpython at jeremysanders.net Mon Dec 1 06:53:03 2008 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Mon, 01 Dec 2008 11:53:03 +0000 Subject: Best way to dynamically get an attribute from a module from within the same module References: <18097f03-dfc9-4671-954a-2871ca0c1910@d42g2000prb.googlegroups.com> Message-ID: Rafe wrote: > I guess, in the end, I'd use getattr() because it feels more pythonic, > and more basic. I got pretty deep in to learning python before I had > to learn what the globals() dict could do for me. Why not store your individual classes inside another class or keep them in a dict? That would be clearer, would not mess around with global namespace, and more pythonic IMHO. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From jura.grozni at gmail.com Wed Dec 3 11:22:19 2008 From: jura.grozni at gmail.com (azrael) Date: Wed, 3 Dec 2008 08:22:19 -0800 (PST) Subject: python an sqlite objects Message-ID: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> is it possible to save a python object into a sqlite database as an atribute of type BLOB From digitig at gmail.com Fri Dec 12 14:49:40 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 12 Dec 2008 19:49:40 +0000 Subject: (Very Newbie) Problems defining a variable In-Reply-To: <7f7e8811-4043-40d4-8aa4-f44e1d255632@o4g2000pra.googlegroups.com> References: <878wqlz27z.fsf@daycos.com> <7f7e8811-4043-40d4-8aa4-f44e1d255632@o4g2000pra.googlegroups.com> Message-ID: 2008/12/12 John Machin : > (2) sequential search can be very fast if the sequence is in > descending order of probability of occurence ... you might like to > consider reversing the order I find it hard to imagine a bank with so many interest rate thresholds that the search of the table is likely to be a significant contribution to the run time! > (3) for a much longer table, binary search using a function from the > bisect module could be considered > (4) in practice, the "default" action would not be "return 0.0"; > perhaps something along these lines: > > if balance < -overdraft_limit: > raise Exception(...) That's more likely to be in the withdrawal routine (and is probably best not handled as an exception, because it's pretty much normal flow). If a bank provided a service such as the one implemented by this program, there'd be no need for it to know about overdraft limits because it's not making actual transactions. Why would they increase coupling unneccesarily? -- Tim Rowe From robert.kern at gmail.com Mon Dec 22 16:28:22 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 22 Dec 2008 15:28:22 -0600 Subject: Python's popularity In-Reply-To: <6rae73F9s47U1@mid.individual.net> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <6ra8t0F925rU1@mid.individual.net> <29feda0d-6432-4cb9-8809-e4d4a7798601@e1g2000pra.googlegroups.com> <6rae73F9s47U1@mid.individual.net> Message-ID: je.s.te.r at hehxduhmp.org wrote: > r wrote: >> We see where you stand. And also see that by removing your comments >> from the archive in 5 days, how small your acorns really are. > > What is "the archive", Google Groups? You do realize that's not the > entirety of Usenet, correct? It's the predominant archive of USENET, but it's not the only one that respects your X-No-Archive header. GMane, for example, will respect it if the list admin has not requested otherwise. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From toby at telegraphics.com.au Mon Dec 1 22:47:47 2008 From: toby at telegraphics.com.au (toby) Date: Mon, 1 Dec 2008 19:47:47 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: <92196910-c849-45d6-a5e9-4d16e1f569ee@x38g2000yqj.googlegroups.com> On Dec 1, 5:24?am, budden wrote: > Mathematica is a great language, but: > 1. it is too slow > 2. It is often hard to read > 3. It gives sence to every keystroke. You press escape by occasion and > it goes in a code as a new > symbol, w/o error. Nasty. > 3. I know 5-th version. It does not allow to track the source as SLIME > does. This feature as absolutely > necessary for serious development Worst of all, it's proprietary, which makes it next to useless. Money corrupts. > > So, in fact, Mathematica do not scale well IMO. From gamersunit at gmail.com Thu Dec 11 14:02:25 2008 From: gamersunit at gmail.com (Gregory Plantaine) Date: Thu, 11 Dec 2008 11:02:25 -0800 (PST) Subject: Find Files in a Folder Between 2 Dates References: <4c54b6c5-ae4d-4b89-8c6d-940c96de29bb@n33g2000pri.googlegroups.com> <94cd4bd7-a69f-48ba-90f7-382014844905@g1g2000pra.googlegroups.com> <862567e3-4469-43ae-b41b-1a1817124f50@k36g2000pri.googlegroups.com> Message-ID: <6b3bed68-3036-4e05-9571-e7dce0db2cff@r36g2000prf.googlegroups.com> On Dec 5, 3:14?pm, John Machin wrote: > On Dec 6, 9:41?am, GregoryPlantaine wrote: > > > That worked perfectly! > > > Thanks Tim! > > > Since we can print the files, does that mean the list of files is in a > > tuple, or something? ?Would there be a way to further split up the > > file names? > > > For example, now that the files are processed into the list, we want > > to look through that list to find different filetypes. > > > files > > > C:\Folder\File_200812051439.111 > > C:\Folder\File_200812051539.222 > > *DANGER* It looks like you are interested in the timestamps that are > embedded in the names of the files. Tim's code assumes [reasonably > given that your problem description was ambiguous and had no examples > of good and bad results] that you are interested in the last > modification time of the file. You may say "same thing". Yes, same > thing, until somebody sucks a file into a text editor, messes with it, > and saves it again. No, Murphy's Law has not been repealed. > > > > > Can we split up .111 files? > > > Actually, where would I look something like this up? > > In the Library Reference Manual ... there are all sorts of goodies in > the os and os.path modules e.g. like those used by Tim; make sure you > read the docs on the methods Tim used so that you understand what's > happening. > > HTH, > John Thanks for the advice John! I was going though the Manual, but I'm having some trouble figuring out how to iterate through each line. So from the same example, we've already created a list called "lists". Now how do I iterate through each line? For eachline in lists Find all .111 files. From rcdailey at gmail.com Mon Dec 8 17:56:19 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 8 Dec 2008 14:56:19 -0800 (PST) Subject: RuntimeError: dictionary changed size during iteration Message-ID: <274eb282-1635-40ca-95af-b82271c57802@v4g2000yqa.googlegroups.com> I'm executing the following code: def CopyBoost( libraries ): pass def CopyEmotionFX( libraries ): pass def Copy( library, aliases ): pass stuff = vars() for key in stuff: print( key, '--', stuff[key] ) I get the following error message: ('CopyEmotionFX', '--', ) Traceback (most recent call last): File "C:\IT\work\jewett\depends.py", line 12, in for key in stuff: RuntimeError: dictionary changed size during iteration Why is this happening? From starsareblueandfaraway at gmail.com Thu Dec 4 08:54:07 2008 From: starsareblueandfaraway at gmail.com (Roy H. Han) Date: Thu, 4 Dec 2008 08:54:07 -0500 Subject: RELEASED Python 3.0 final In-Reply-To: <1a73e3be-1753-4178-8091-eaa890b3e07e@l42g2000yqe.googlegroups.com> References: <1a73e3be-1753-4178-8091-eaa890b3e07e@l42g2000yqe.googlegroups.com> Message-ID: <6a5569ec0812040554h7f5bca4btd4d32c28ed04a0b6@mail.gmail.com> Hi, This is great, however, the link to the What's New page appears to be broken. http://docs.python.org/dev/3.0/whatsnew/3.1.html RHH On Thu, Dec 4, 2008 at 8:37 AM, Istvan Albert wrote: > Congratulations on a fantastic work! > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.dev.9 at gmail.com Fri Dec 12 14:42:24 2008 From: python.dev.9 at gmail.com (mercado) Date: Fri, 12 Dec 2008 14:42:24 -0500 Subject: Testing against different versions of Python Message-ID: <2678157f0812121142y2afcf3bey254dd2b74f61e423@mail.gmail.com> What is the best way to go about testing against different versions of Python? For example, I have 2.5.2 installed on my machine (Ubuntu Hardy 8.04), and I want to test a script against 2.5.2 and 2.5.1 (and possibly other versions as well). Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrea.francia at REMOVE-FROM-HERE.ohoihihoihoih.TO-HERE.gmx.it Tue Dec 16 14:13:00 2008 From: andrea.francia at REMOVE-FROM-HERE.ohoihihoihoih.TO-HERE.gmx.it (Andrea Francia) Date: Tue, 16 Dec 2008 19:13:00 GMT Subject: Where is a good open source python project to be used as example? Message-ID: <05T1l.219074$FR.507685@twister1.libero.it> I'm looking for a python project to use as example to learning python. The project should have these features: 1. is almost fully unit tested 2. use consistently the code convention recommended by PEP 8 3. it's elements are almost fully documented Extra point features are: 4. building, assembling, and release automation Did you know where are such projects? From aleksandr.goretoy at gmail.com Sat Dec 27 18:31:27 2008 From: aleksandr.goretoy at gmail.com (alex goretoy) Date: Sat, 27 Dec 2008 17:31:27 -0600 Subject: parsing csv files class In-Reply-To: References: <49562755.6050205@byoteki.com> Message-ID: I might as well add a UnicodeReader and UnicodeWriter and support for passing delimiter in from other classes. At the same time. Anyone have a good csv class I can pick thru? I'm planning on posting my mysql adn curl classes that I use in my projects I just want to make them better and have less error. On Sat, Dec 27, 2008 at 5:18 PM, alex goretoy wrote: > It's main concern is to grab the file into the buffer for use in other > classes. The self.soc.me_him is just so I know when its ENTERING or EXITING > in that function when I run it in terminal. It's prints it in color. My main > concern right now is to add error handling. I'm still learning how to use > assert and yield, but I got try,except down pat. All this class does is > grabs the file either from http or local storage into a buffer and I use > that in other classes. I want to add support for creating creating csv as > well. I read the doc on csv and will try some things out soon. Thanks for > helping me. > > > On Sat, Dec 27, 2008 at 2:15 PM, Gabriel Genellina > wrote: > >> En Sat, 27 Dec 2008 11:02:13 -0200, Gary M. Josack >> escribi?: >> >>> alex goretoy wrote: >>> >> >> I know it's messy with all those self.soc.* functions, but it works in >>>> one of my current project. I just want to make it more pythonic I also want >>>> to add capability for makeing csv file if I give it input like: >>>> 1234,something nice, hey this is something nice >>>> 2468,something else, something else >>>> >>> >> reader = csv.reader(file(filename, "rb")) >>>> try: >>>> for row in reader: >>>> self.buffer.append(row) >>>> s,a=[],{} >>>> >>> >> Do you know that there is a csv module in the standard library already? >>> >> >> I'd say he already knows, he even used it in the code. >> >> To Alex G.: I didn't understand what's the purpose of this class. Probably >> you want to do too much things in the same place; looks like it has multiple >> concerns, and that's not a good idea usually. >> >> -- >> Gabriel Genellina >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > > -- > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > > > > -- > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > -- ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Thu Dec 4 12:00:49 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 4 Dec 2008 12:00:49 -0500 Subject: Python 3 read() function In-Reply-To: References: Message-ID: <16651e80812040900j257fe2acjf5d8817811d32da6@mail.gmail.com> On Thu, Dec 4, 2008 at 11:48 AM, Christian Heimes wrote: > Cro wrote: >> vContent = io.StringIO() >> vContent = huge.read() # This line takes hours to process !!! > > Do you really mean io.StringIO? I guess you want io.BytesIO() .. I don't think it matters. Here's a quick comparison between 2.5 and 3.0 on a relatively small 17 meg file: C:\>c:\Python30\python -m timeit -n 1 "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" 1 loops, best of 3: 36.8 sec per loop C:\>c:\Python25\python -m timeit -n 1 "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" 1 loops, best of 3: 33 msec per loop That's 3 orders of magnitude slower on python3.0! -- Jerry From bblais at bryant.edu Fri Dec 26 20:30:43 2008 From: bblais at bryant.edu (Brian Blais) Date: Fri, 26 Dec 2008 20:30:43 -0500 Subject: multiply each element of a list by a number In-Reply-To: References: Message-ID: <6E23195F-E079-4F22-829E-ECBEBE891D3B@bryant.edu> On Dec 26, 2008, at 19:05 , Robert.T.Lynch at seagate.com wrote: > but this seems overkill to me. Can you tell I am coming to Python > from Matlab? if you're coming from matlab, then you should think of python lists more like cell arrays than matrices: you can have lists of arbitrary data types, so multiply is not going to work in the matrix way. check out http://web.bryant.edu/~bblais/bryant/numerical_computing/ python_matlab.pdf but more importantly, you need to install numpy (which has the matrix stuff) and scipy (which has the scientific packages). What I do is go to www.enthought.com and they have a single-download package geared specifically for scientists. bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From geon at post.cz Sat Dec 27 09:08:24 2008 From: geon at post.cz (Pavel Kosina) Date: Sat, 27 Dec 2008 15:08:24 +0100 Subject: tkinter 3.0 multiple keyboard events together In-Reply-To: <7b5e466c-d75d-4e71-b559-f8a0d3718094@r15g2000prd.googlegroups.com> References: <600d4b68-6fe2-4c2c-b425-1a739430bb54@s9g2000prg.googlegroups.com> <7b5e466c-d75d-4e71-b559-f8a0d3718094@r15g2000prd.googlegroups.com> Message-ID: <495636D8.3080807@post.cz> janislaw napsal(a): > Use google to find the appropriate site, or browse this site, there > are plenty of examples. You may want to examine the code I wrote to > you to catch the idea: > #---------------------- > import Tkinter > import pprint > > tk = Tkinter.Tk() > f = Tkinter.Frame(tk, width=100, height=100) > msg = Tkinter.StringVar() > msg.set('Hello') > l = Tkinter.Label(f, textvariable=msg) > l.pack() > f.pack() > > keys = set() > > def keyPressHandler(event): > keys.add(event.char) > display() > > def keyReleaseHandler(event): > keys.remove(event.char) > display() > > def display(): > msg.set(str(keys)) > > f.bind_all('', keyPressHandler) > f.bind_all('', keyReleaseHandler) > > f.mainloop() > Is this really the most simple solution how to do this in Tkinter? Is there nothing cleaner "build inside"? This solution has disadvantage that after you release one key, that the function keyPressHandler stopped to be called by the other pressed keys. I would have not to build moving the player in KeyPresshandler, but on another new function that would have to read periodically "keys" and to act afterwards.... I really tried to search for words mentioned in this subject, but nothing, not even this solution, was found by me. PK From joe.hrbek at gmail.com Wed Dec 3 13:40:14 2008 From: joe.hrbek at gmail.com (Joe Hrbek) Date: Wed, 3 Dec 2008 10:40:14 -0800 (PST) Subject: using os.walk to generate objects Message-ID: The code below works (in linux), but I'm wondering if there is a better/easier/cleaner way? It works on directory trees that don't have a lot of "."s in them or other special characters. I haven't implemented a good handler for that yet, so if you run this in your system, choose/make a simple directory structure to use as your root for os.walk(). Also, you must start from the top most directory level, like /test. /tmp/test as a root will not work (yet). :) I wanted to know if I could use os.walk() to construct an object based off of a directory tree. So, the following path: "/test/home/user" would get converted into "test.home.user" and I could then work with it that way in my python program, attaching attributes to those "directories" that I could use to keep track of things. This was more of an exercise in learning than anything, I wanted to see if I could do it. I've never used "type()" before to create new objects, so really that was the point. Can I do this an easier way though? ---- import os from os.path import join, getsize def remove_hidden(dirlist): """For a list containing directory names, remove any that start with a dot""" dirlist[:] = [d for d in dirlist if not d.startswith('.')] def recurse_dir_tree(context,dirs): """recurse through tree structure and add attributes as necessary""" for directory in dirs: fixedDir = directory.replace('.','_').lower() #print ("directory is:%s" % fixedDir) newAttrObj = type(("%s" % fixedDir),(),{}) if newAttrObj.__name__: #print newAttrObj.__name__ #print "context is "+context print "tree."+context setattr(eval ("tree."+context),newAttrObj.__name__,newAttrObj) class Tree(object): def __init__(self,wd): self.__name__ = wd pathroot = '/test' tree = Tree(pathroot) for root, dirs, files in os.walk(pathroot): tree.currentRoot = ".".join(map(str,root.split('/')[1:])) tree.currentRoot = tree.currentRoot.lower() print "currentRoot:" + tree.currentRoot if pathroot == root: #this is the start of the object tree tree.baseRoot = pathroot.split('/')[1] newAttrObj = type(("%s" % tree.currentRoot),(),{}) setattr(tree,newAttrObj.__name__,newAttrObj) #print dirs remove_hidden(dirs) #print dirs if dirs: recurse_dir_tree(tree.currentRoot,dirs) From geekmail at usenot.de Tue Dec 2 15:44:02 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Tue, 2 Dec 2008 21:44:02 +0100 Subject: Reverse zip() ? References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> Message-ID: <20081202214402.4a8a0cde@usenot.de> On Tue, 02 Dec 2008 21:12:19 +0100 Stefan Behnel wrote: > Andreas Waldenburger wrote: > > [snip] > > This is of course trivial to do via iteration or listcomps, BUT, I > > was wondering if there is a function I don't know about that does > > this nicely? > > I think you're asking about zip(): > > >>> l=[1,2,3] > >>> zip(l,l) > [(1, 1), (2, 2), (3, 3)] > >>> zip(*zip(l,l)) > [(1, 2, 3), (1, 2, 3)] > So I am. That sure was weird. Thanks for the quick and somewhat surreal help. Need I say that between posting this question and reading your reply I set out to implement this wonder-function? :) /W -- My real email address is constructed by swapping the domain with the recipient (local part). From gdamjan at gmail.com Mon Dec 15 19:44:15 2008 From: gdamjan at gmail.com (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Tue, 16 Dec 2008 01:44:15 +0100 Subject: Structure using whitespace vs logical whitespace References: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> Message-ID: > In most languages, I'll do something like this > > xmlWriter.BeginElement("parent"); > ----xmlWriter.BeginElement("child"); > ----------xml.Writer.Characters("subtext"); > ----xmlWriter.EndElement(); > xmlWriter.EndElement(); > > Where the dashes are indentation (since some newsgroup handlers don't > do tabs well). XML writing is just an example. Well, XML beeing just an example.. but still for XML in Python you probably want to use some XML templating library like Genshi. And for other stuff there are probably similar sollutions. -- ?????? ( http://softver.org.mk/damjan/ ) war is peace freedom is slavery restrictions are enablement From google at mrabarnett.plus.com Thu Dec 18 09:17:07 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 18 Dec 2008 14:17:07 +0000 Subject: re.match() performance In-Reply-To: <755bd716-f5f6-4953-87a7-04ee148c3298@i18g2000prf.googlegroups.com> References: <755bd716-f5f6-4953-87a7-04ee148c3298@i18g2000prf.googlegroups.com> Message-ID: <494A5B63.6060005@mrabarnett.plus.com> Emanuele D'Arrigo wrote: > Sorry for the previous post, hit the Enter button by mistake... here's > the complete one: > > Hi everybody! > > I've written the code below to test the differences in performance > between compiled and non-compiled regular expression matching but I > don't quite understand the results. It appears that the compiled the > pattern only takes 2% less time to process the match. Is there some > caching going on in the uncompiled section that prevents me from > noticing its otherwise lower speed? > [snip] Yes, the regular expression is compiled and cached internally. From steven at REMOVE.THIS.cybersource.com.au Mon Dec 8 21:41:47 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 09 Dec 2008 02:41:47 GMT Subject: Rich Comparisons Gotcha References: Message-ID: On Mon, 08 Dec 2008 14:24:59 +0000, Rasmus Fogh wrote: > For my personal problem I could indeed wrap all objects in a wrapper > with whatever 'correct' behaviour I want (thanks, TJR). It does seem a > bit much, though, just to get code like this to work as intended: > alist.append(x) > print ('x is present: ', x in alist) > > So, I would much prefer a language change. I am not competent to even > propose one properly, but I'll try. You think changing the language is easier than applying a wrapper to your own data??? Oh my, that's too funny for words. -- Steven From gagsl-py2 at yahoo.com.ar Tue Dec 9 01:58:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Dec 2008 04:58:50 -0200 Subject: [Python 2.x] Pickling a datetime.tzinfo subclass instance? References: Message-ID: En Mon, 08 Dec 2008 12:34:03 -0200, Cong Ma escribi?: > I'm writing a program that pickles an instance of a custom subclass of > datetime.tzinfo. I followed the guides given in the Library Reference > (version > 2.5.2, chapter 5.1.6), which contain the note: > > "Special requirement for pickling: A tzinfo subclass must have an > __init__ > method that can be called with no arguments, else it can be pickled but > possibly > not unpickled again. This is a technical requirement that may be relaxed > in the > future." > > I tried this with an example "FixedOffset" subclass instance given in the > Example section in the manual. It indeed failed to unpickle. To work > around > this, I found two possible solutions: > 1. Modify the __init__ method so that it takes optional arguments with > default > values; Doing that still works with 2.6 and 3.0 > 2. Implement the __getinitargs__ method so that it does the opposite of > __init__: returning a tuple from the instance's internal state that can > be used > to re-initialize an instance, retaining the old value. In fact, it doesn't matter *what* it returns, as far as they're valid arguments to __init__ > My questions: > 1. Is the "technical limitation" fixed in version 2.6 or 3.0? I can't > check it > for myself now... Python.org seems down and I can't find the docs. No, they behave the same (odd) way. > 2. To stick with version 2.5, which of the above 2 methods is better? > Both seems > to unpickle to the correct result, but are there subtle side-effects? > Or there > are better solutions? I'd use method 1, just because the __getinitargs__ are useless. -- Gabriel Genellina From ethan at stoneleaf.us Mon Dec 8 15:38:33 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 08 Dec 2008 12:38:33 -0800 Subject: datetime and the rich-companison operators In-Reply-To: <47c890dc0812080952q32adc09etbd5d4c1601914b98@mail.gmail.com> References: <493CCFBC.90104@stoneleaf.us> <47c890dc0812080952q32adc09etbd5d4c1601914b98@mail.gmail.com> Message-ID: <493D85C9.8040901@stoneleaf.us> Chris Rebert wrote: > On Sun, Dec 7, 2008 at 11:41 PM, Ethan Furman wrote: > >>Greetings All! >> >>I am implementing a NullDate class in order to mirror dates and datetimes >>that have no value (yes, this is for my dbf module :) >> >>I'm still a bit fuzzy about class methods, hashing, and __new__, but my >>question of the moment is this: it seems to me that with two dates or >>datetimes, they should either be equal, or one should precede the other, and >>this can be accomplished quite handily with __cmp__... so does anyone know >>why the rich comparisons were used in the datetime module? Was it simply a >>style choice, or is something being handled that __cmp__ couldn't cope with? > > > Probably because __cmp__ was removed in Python 3.0, thus requiring the > use of the rich comparison methods in its place. > See the earlier thread entitled "Python 3 __cmp__ semantic change?". > > Cheers, > Chris > Thanks, Chris! ~ethan~ From rileyrgdev at gmail.com Mon Dec 1 03:29:03 2008 From: rileyrgdev at gmail.com (Richard Riley) Date: Mon, 01 Dec 2008 09:29:03 +0100 Subject: Emacs vs. Eclipse vs. Vim References: Message-ID: Roy Smith writes: > Clay Hobbs wrote: >> The first real text editor I used was Vim, which I actually started >> using about a year ago. I've looked at Emacs and it just looks >> confusing. > > I've been using emacs for so many years (um let's see, it's got to be close > to 25 years now; first saw it on Columbia's TOPS-20 systems in the early > 80's) that my fingers know what they're doing without my even thinking > about it. In fact, I used to work with another emacs nut. Every so often, > one of use would watch the other do something and ask, "What was that?". > Inevitably, neither of us could evoke the keystrokes we had just typed. We > would just re-do it, and watch our fingers to see what we typed. It didn't > even have to be on a keyboard; we could air-type it, and that was good > enough. > > In any case, the basic logic behind emacs is pretty simple. C-F is forward > one character. C-B is back one character. C-N is Next line. C-P is > Previous line. It's worth pointing out to people making "loony" signs here that the arrow keys work too .... From clp at rebertia.com Mon Dec 1 16:37:42 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 1 Dec 2008 13:37:42 -0800 Subject: Python introspection and namespace weird question In-Reply-To: References: <47c890dc0812011037u64076950o186af7477269cc0a@mail.gmail.com> Message-ID: <47c890dc0812011337v7495a176s8fb29b62f2f2ad17@mail.gmail.com> On Mon, Dec 1, 2008 at 12:23 PM, Rayene Ben Rayana wrote: > Thanks Chris, > > Yeah it is kinda meta thing. My app allows to create a scene (a set of GUI > objects). A scene can be saved as a python script. And, it can be loaded > again using execfile(). > > each GUI object has a label. So, in the script scene, declaring an object in > a scene file should look like this: > > red_car = MyVehicleClass(label = 'red_car') > > But, I wanted to simplify the syntax of scene files and avoid repetition so > it would look like > > red_car = MyVehicleClass() > > with the label attribute automatically set to the name of the corresponding > variable. > I tried your locals().iteritems tip and it works perfectly. > > The question now is: Given what I just explained, do you still think it is > bad programming to do that ? Should I better use the first syntax ? Assuming the object declarations are all at the module-level and you have some rule for dealing with objects with multiple "names", using the trick I outlined but with globals() instead of locals() seems reasonable, albeit a bit of a hack, but since this is just a script, that seems acceptable. IMHO, it's an OK trade-off in order to comply with the DRY (Don't Repeat Yourself) principle in this case. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Cheers, > > Rayene, > > I want to use that to simplify the syntax of the > > On Mon, Dec 1, 2008 at 7:37 PM, Chris Rebert wrote: >> >> On Mon, Dec 1, 2008 at 6:04 AM, Rayene Ben Rayana >> wrote: >> > Hello everybody, >> > >> > Is there an easy way to do something like this in python ? >> > >> >>>> red_car = MyVehicleClass() >> >>>> car = red_car >> >>>> car.labels() >> > ['red_car' , 'car' ] >> > >> > In other words, does an instance has access to its name pointers ? >> >> In short, No. (Cue another debate over whether Python uses call-by-X >> semantics...) >> >> Typically people who want to do such things actually want/should use a >> dictionary mapping string keys to instance values instead. >> >> Note that in certain limited cases, voodoo involving the locals() or >> globals() built-in functions or the `inspect` module can work, but not >> in the common general case. But generally these techniques are >> considered bad style and kludgey unless you're writing a debugger or >> something equally meta, with using a dictionary as explained >> previously being much preferred. >> >> For example, for your particular code above, the following happens to >> work: >> [name for name, obj in locals().iteritems() if obj is car] #==> >> ['red_car' , 'car' ] >> >> But this will only give the names in the current function of the >> particular car object. Likewise, globals() works only for module-level >> names, and the `inspect` module's magic only works for names in >> calling functions (i.e. those below the current one in the callstack). >> >> Cheers, >> Chris >> -- >> Follow the path of the Iguana... >> http://rebertia.com >> >> > >> > Thanks in advance, >> > >> > Rayene >> > >> > >> > -- >> > http://mail.python.org/mailman/listinfo/python-list >> > >> > From cadmuxe at gmail.com Mon Dec 8 09:24:15 2008 From: cadmuxe at gmail.com (cadmuxe) Date: Mon, 8 Dec 2008 22:24:15 +0800 Subject: Beginner trying to understand functions. In-Reply-To: References: Message-ID: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> i think we should use raw_input('Please enter your name: ') instead of input('Please enter your name: ') 2008/12/8 Peter Otten <__peter__ at web.de> > simonh wrote: > > > In my attempt to learn Python I'm writing a small (useless) program to > > help me understand the various concepts. I'm going to add to this as I > > learn to serve as a single place to see how something works, > > hopefully. Here is the first approach: > > > That works fine. Then I've tried to use functions instead. The first > > two work fine, the third fails: > > > def getName(): > > name = input('Please enter your name: ') > > print('Hello', name) > > > > def getAge(): > > while True: > > try: > > age = int(input('Please enter your age: ')) > > break > > except ValueError: > > print('That was not a valid number. Please try again.') > > > > def checkAge(): > > permitted = list(range(18, 31)) > > if age in permitted: > > print('Come on in!') > > elif age < min(permitted): > > print('Sorry, too young.') > > elif age > max(permitted): > > print('Sorry, too old.') > > > > getName() > > getAge() > > checkAge() > > > > I get this error message: NameError: global name 'age' is not > > defined. > > > > I'm stuck, can someone help? Thanks. > > > Generally, when you calculate something within a function you tell it the > caller by returning it: > > >>> def get_age(): > ... return 74 > ... > >>> get_age() > 74 > >>> age = get_age() > >>> age > 74 > > And if you want a function to act upon a value you pass it explicitly: > > >>> def check_age(age): > ... if 18 <= age <= 30: > ... print("Come in") > ... else: > ... print("Sorry, you can't come in") > ... > >>> check_age(10) > Sorry, you can't come in > >>> check_age(20) > Come in > > To check the age determined by the get_age() function you do: > > >>> age = get_age() > >>> check_age(age) > Sorry, you can't come in > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul.nospam at rudin.co.uk Fri Dec 19 13:23:45 2008 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Fri, 19 Dec 2008 18:23:45 +0000 Subject: ANN: New Book: Programming in Python 3 References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> <6r25ckFejl4vU1@mid.individual.net> Message-ID: <877i5wxbv2.fsf@rudin.co.uk> Thomas Heller writes: > Steve Holden schrieb: >> Thomas Heller wrote: >>> Question from a non-native english speaker: is this now valid english? >>> >>> "One of Python?s great strengths" >>> ^ >>> "and also teaches Python?s functional programming features" >>> ^ >>> "The book?s approach is wholly practical" >>> ^ >> It always has been valid English. The apostrophe is only omitted from >> personal pronouns (hers, its, and so on). > > I see, thanks. But, is the apostrophe optional in the above fragments? No. From bayokrapht at googlemail.com Sat Dec 13 02:07:06 2008 From: bayokrapht at googlemail.com (boyombo) Date: Fri, 12 Dec 2008 23:07:06 -0800 (PST) Subject: Preventing execution of a method References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> <764daeef-bfbe-411a-8521-bb114321e4ac@b38g2000prf.googlegroups.com> <19304f8c-e34f-4aa9-8df2-6a7d3553007a@e1g2000pra.googlegroups.com> <2eed8876-94d2-4304-88a5-eb4a78b4f41d@33g2000yqm.googlegroups.com> <307fe197-1b42-4305-af0e-94b7ebe3ce70@r15g2000prh.googlegroups.com> <49417c59$0$8491$426a74cc@news.free.fr> <49421c07$0$3398$426a74cc@news.free.fr> Message-ID: <79a40af9-7f8b-41cf-97f8-92653f475a5d@r36g2000prf.googlegroups.com> On Dec 12, 9:09?am, Bruno Desthuilliers wrote: > Emanuele D'Arrigo a ?crit : > > > On Dec 11, 7:48 pm, Bruno Desthuilliers > > wrote: > >>> or to provide read-only > >>> access. I.e. right now I'm working on the graphical client which > >>> potentially could be rewritten entirely by the users. It is necessary > >>> and perfectly reasonable for the client module to access some of the > >>> objects to be represented graphically, but those objects shouldn't be > >>> modifiable by it. > >> Why so ? At worst, they'll break everything. > > > -IF- the application was single-user yes, it wouldn't be a big deal. > > But as it is potentially multi-user, I don't want one party to corrupt > > the application for everybody else. > > A multi-users application with a GUI usually implies that it's a > client-server app with the GUI deployed is on each client and the domain > logic hosted on the server. This is assuming the 'BAD GUY' does not have access to the server code, right? From drobinow at gmail.com Sun Dec 7 23:31:42 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Sun, 7 Dec 2008 20:31:42 -0800 (PST) Subject: how to get a beep, OS independent ? References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> <014c575a$0$20670$c3e8da3@news.astraweb.com> Message-ID: <962c4197-8730-4ddf-a925-88efe9a2fd84@k41g2000yqn.googlegroups.com> On Dec 7, 8:34?pm, Joe Strout wrote: > On Dec 7, 2008, at 4:43 PM, Steven D'Aprano wrote: > > > Of course, if you're volunteering to write such a standard system beep > > for Python, I for one would be grateful. > > I am. ?But where should I put it? ?Assuming we don't want to wait for ? > the (understandably) lengthy and contentious process required to add ? > something to the Python system libraries, where would be the next best ? > place for this sort of simple OS abstraction layer? > > Thanks, > - Joe Host it on your web site and send an announcement to comp.lang.python.announce If you don't have a web site (I don't) you might try http://pypi.python.org/pypi. See the tutorial there for instructions. If the setup.py requirement is too difficult ask for help here. From skip at pobox.com Tue Dec 30 07:10:22 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 30 Dec 2008 06:10:22 -0600 Subject: Python in C In-Reply-To: <313583fc-4651-4deb-8a44-c3b1810b722c@z27g2000prd.googlegroups.com> References: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> <313583fc-4651-4deb-8a44-c3b1810b722c@z27g2000prd.googlegroups.com> Message-ID: <18778.4014.114778.847498@montanaro-dyndns-org.local> aki> Although this is not what you are asking but I'm wondering why you aki> need to read CPython implementation. A couple reasons come to mind: * education * want to make it better (extend it, fix bugs, etc) * want to see how it relates to the implementation of other languages (Ruby, Perl, Tcl, etc) aki> CPython worked great for me. I don't want to read a large piece of aki> software, like CPython, unless it is really really necessary. Sure, but not everyone works at the Python layer. Which is a good thing, because if everyone confined themselves to Python code nobody would fix problems in the language implementation or enhance it. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From rt8396 at gmail.com Wed Dec 17 14:23:49 2008 From: rt8396 at gmail.com (r) Date: Wed, 17 Dec 2008 11:23:49 -0800 (PST) Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> <175fa5d5-f345-47b8-a686-e0e36e1b99e9@q37g2000vbn.googlegroups.com> <39eec12b-d7cc-44b5-aa65-bfa559dcba05@n33g2000pri.googlegroups.com> Message-ID: On Dec 17, 12:20?pm, walterbyrd wrote: > On Dec 17, 10:00?am, r wrote: > > > When writing > > procedural code how would you like it if vars inside functions were > > automatically global. Your code with be blowing chunks in no time. > > That was my point - I consider python's ordinary use of lexical > scoping to be a good thing, and I was wondering why this "good thing" > was not used in classes, as well as outside of classes. The whole point for even writing a class is for shared attributes. Write procedural code if you don't like classes. When ever you see self.var think of it as Class.instance(var)... makes total sense to me? Obliviously you have not done much procedural coding or you would know why this HAS to be. sorry if i sound rude. From ken at jots.org Sat Dec 6 10:10:11 2008 From: ken at jots.org (Ken D'Ambrosio) Date: Sat, 6 Dec 2008 10:10:11 -0500 (EST) Subject: Detaching e-mail attachments? Message-ID: <58772.75.67.216.99.1228576211.squirrel@webmail.jots.org> Hi, all. I've done some poking around, and can find roughly two million different ways to attach attachments to an e-mail... but darn few to detach them. Any suggestions? I'm assuming I'm just missing looking in The Right Place, but thus-far, my Googling has been for naught. Thanks! -Ken From fetchinson at googlemail.com Fri Dec 19 19:20:02 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Fri, 19 Dec 2008 16:20:02 -0800 Subject: mod_python resources In-Reply-To: References: <78064e7e-ba2c-4959-b5f8-4d1b928bc5fe@y18g2000yqn.googlegroups.com> <4lsl16-15a.ln1@archaeopteryx.softver.org.mk> Message-ID: > Here's my problem (it's a conceptual one). Coming from the world of > mod_php, each file can represent a page with no intervention. I was > not able to achieve the same with mod_python when I tried, and for > that matter, couldn't put the pieces together in a usable way. > > Let me start simply: If I wanted to create a trivial site, (Home, > About, Contact) with a header and footer included, in PHP, it would be > done as such: each page (index.php, about.php, contact.php) includes > the template bits (header.php, footer.php). Is this simplicity > achievable using Python? And by "simplicity," I'm referring to > simplicity in execution; not necessarily an identical approach. Yes, it is possible. As already advised by several posters, reading the documentation actually helps. You may want to have a look at: http://www.modpython.org/live/current/doc-html/pyapi-psp.html The spyce project you may also find helpful: http://spyce.sourceforge.net/ Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From jsm4321 at gmail.com Thu Dec 25 13:53:31 2008 From: jsm4321 at gmail.com (jsm4321 at gmail.com) Date: Thu, 25 Dec 2008 10:53:31 -0800 (PST) Subject: Syntax error for print Message-ID: <2b65c6e1-b5a9-438d-a45c-b8f9d18228de@s1g2000prg.googlegroups.com> IDLE 3.0 >>> print "hello" SyntaxError: invalid syntax (, line 1) >>> 3+3 6 >>> var = 4 >>> var = var*4 >>> print var SyntaxError: invalid syntax (, line 1) >>> Any idea on why I am getting this error. I have just started learning python and I am stuck at first thing itself. Any help would be greatly appreciated. Thanks, Jeetu Sahil From fetchinson at googlemail.com Sat Dec 27 19:44:27 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 27 Dec 2008 16:44:27 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: >> I agree that array.array is more efficient than a list but the input >> for my function will come from PIL and PIL returns a list. So I have a >> list to begin with which will be passed to the C function. > > With recent versions of PIL, numpy can create an array from an Image very > quickly, possibly without any copying of memory. What exactly do you mean? (1) PIL creates a list which can be easily converted by numpy to a numpy.array or (2) with the help of numpy one can create a numpy.array from an image directly? Since I will have to pass the list or numy.array to C anyway I don't see any advantage to (1) although (2) can be useful. Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From tgrav at mac.com Mon Dec 22 21:10:19 2008 From: tgrav at mac.com (Tommy Grav) Date: Mon, 22 Dec 2008 21:10:19 -0500 Subject: Python's popularity In-Reply-To: <495011B8.1050607@strout.net> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <18767.47566.709705.92@montanaro-dyndns-org.local> <495011B8.1050607@strout.net> Message-ID: <8FACC6D5-620D-4328-A0FA-8CFBDC293C75@mac.com> On Dec 22, 2008, at 5:16 PM, Joe Strout wrote: > Alvin ONeal wrote: > >> Also worthy of mention: >> I've seen python pre-installed on consumer HP desktops (I think as >> part of a backup/restore script, but I'm not sure) > > It's pre-installed on every Mac (both desktop and laptop), too. Mac and a lot of linux distros use python as an integral part of their OS development, so most of these actually come with some python pre-installed (and one should not remove it unless you want to screw up your OS). Cheers Tommy From tino at wildenhain.de Mon Dec 22 02:06:53 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 22 Dec 2008 08:06:53 +0100 Subject: How to represent a sequence of raw bytes In-Reply-To: References: <200812220327.36180.motoom@xs4all.nl> Message-ID: <494F3C8D.7040504@wildenhain.de> Steven Woody wrote: > On Mon, Dec 22, 2008 at 10:27 AM, Michiel Overtoom wrote: >> On Monday 22 December 2008 03:23:03 Steven Woody wrote: >> >>> 2. char buf[] = {0x11, 0x22, 0x33, ... } >>> >>> What's the equivalent representation for above in Python? >>>>> buf="\x11\x22\33" ... > I thing "\x11\x22\x33" in python is not the {0x11, 0x22, 0x33} in C. > Since, a string in python is immutable, I can _not_ do something like: > b[1] = "\x55". > > And, how about char buf[200] in my original question? The intension > is to allocate 200 undefined bytes in memory. Thanks. Well in most cases you don't need to do that, instead you could assemble your stream on the way out based on sequences, generators etc. Please note that char in your example is just a bit inapropriate (but common in C) shorthand for unsigned short int. There is no such type in python so you could use int() if you want to operate on the numeric value. Depending on your use case a big integer could also serve well and you can convert it into a byte string. If you want random access to the bytes, you can use list or array (see array module) or, if you want it with much more performance resort to numpy, scipy, they have arrays similar to C and also much more numeric datatypes. Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From prologic at shortcircuit.net.au Tue Dec 30 19:29:14 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 10:29:14 +1000 Subject: get method In-Reply-To: <71508d7a-f678-40ba-801c-0bbfbbab961e@r15g2000prh.googlegroups.com> References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> <495AAB97.5010707@mrabarnett.plus.com> <71508d7a-f678-40ba-801c-0bbfbbab961e@r15g2000prh.googlegroups.com> Message-ID: On Wed, Dec 31, 2008 at 10:22 AM, John Machin wrote: (snip) > The "crawl through the shrubbery looking for evidence" approach > stumbles on the actual code: Yes I found his implementation soon after :) Not bad actually... I wonder why bag() isn't shipped with the std lib - perhaps in teh set module ? --JamesMills From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 9 04:17:02 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 09 Dec 2008 10:17:02 +0100 Subject: Beginner trying to understand functions. In-Reply-To: <040a2896-be99-477e-909c-c55c5a0e6665@y1g2000pra.googlegroups.com> References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> <9df7549a-f28b-4d39-b105-90c099f472f2@z28g2000prd.googlegroups.com> <040a2896-be99-477e-909c-c55c5a0e6665@y1g2000pra.googlegroups.com> Message-ID: <493e3788$0$6842$426a74cc@news.free.fr> simonh a ?crit : > Thanks for the many replies. Thanks especially to Pierre. This works > perfectly: > (snip) Ok, now for some algorithmic stuff: > def checkAge(age,min=18,max=31): > if age in list(range(min, max)): > print('Come on in!') > elif age < min: > print('Sorry, too young.') > elif age >= max: > print('Sorry, too old.') if age is neither greater than max nor lesser than min, then it's it in range(min, max). IOW, you could just skip the first test: def checkAge(age,min=18,max=31): if age < min: print('Sorry, too young.') elif age >= max: print('Sorry, too old.') else: print('Come on in!') !-) From darcy at druid.net Thu Dec 18 16:54:08 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 18 Dec 2008 16:54:08 -0500 Subject: psycopg2 and large queries In-Reply-To: <494AC077.2060605@shopzeus.com> References: <762eed9d-4646-4c62-a9b7-d57d47f03b9e@e1g2000pra.googlegroups.com> <494AC077.2060605@shopzeus.com> Message-ID: <20081218165408.b40d11f1.darcy@druid.net> On Thu, 18 Dec 2008 22:28:23 +0100 Laszlo Nagy wrote: > - PyGresSQL: apparently, it does not support fetching one row, only > fetching all rows (see: > http://www.pygresql.org/pg.html#getresult-get-query-values-as-list-of-tuples), > so this is not an option. (Yes, it also has a db api compilant module, > but it is only a wrapper around pgqueryobject, and it does not support > server side cursors...) I'm not sure where you get that. The DB-API compliant execute function uses server side cursors with fetch. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From iofferkicks21 at gmail.com Wed Dec 24 19:14:38 2008 From: iofferkicks21 at gmail.com (www.iofferkicks.com) Date: Wed, 24 Dec 2008 16:14:38 -0800 (PST) Subject: www.iofferkicks.com china cheap wholesale nike shoes,air jordan shoes,air force one shoes. Message-ID: <79f56140-4828-4d9d-ac5c-ab692b133a9b@35g2000pry.googlegroups.com> Get Nike Shoes at Super Cheap Prices Discount Nike air jordans (www.iofferkicks.com) Discount Nike Air Max 90 Sneakers (www.iofferkicks.com) Discount Nike Air Max 91 Supplier (www.iofferkicks.com) Discount Nike Air Max 95 Shoes Supplier (www.iofferkicks.com) Discount Nike Air Max 97 Trainers (www.iofferkicks.com) Discount Nike Air Max 2003 Wholesale (www.iofferkicks.com) Discount Nike Air Max 2004 Shoes Wholesale (www.iofferkicks.com) Discount Nike Air Max 2005 Shop (www.iofferkicks.com) Discount Nike Air Max 2006 Shoes Shop (www.iofferkicks.com) Discount Nike Air Max 360 Catalogs (www.iofferkicks.com) Discount Nike Air Max Ltd Shoes Catalogs (www.iofferkicks.com) Discount Nike Air Max Tn Men's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 2 Women's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 3 Customize (www.iofferkicks.com) Discount Nike Air Max Tn 4 Shoes Customize ( www.iofferkicks.com) Discount Nike Air Max Tn 6 Supply (www.iofferkicks.com) Discount Nike Shox NZ Shoes Supply (www.iofferkicks.com) Discount Nike Shox OZ Sale (www.iofferkicks.com) Discount Nike Shox TL Store (www.iofferkicks.com) Discount Nike Shox TL 2 Shoes Store (www.iofferkicks.com) Discount Nike Shox TL 3 Distributor (www.iofferkicks.com) Discount Nike Shox Bmw Shoes Distributor (www.iofferkicks.com) Discount Nike Shox Elite Shoes Manufacturer (www.iofferkicks.com) Discount Nike Shox Monster Manufacturer (www.iofferkicks.com) Discount Nike Shox R4 Running Shoes (www.iofferkicks.com) Discount Nike Shox R5 Mens Shoes (www.iofferkicks.com) Discount Nike Shox Ride Womens Shoes (www.iofferkicks.com) Discount Nike Shox Rival Shoes Wholesaler (www.iofferkicks.com) Discount Nike Shox Energia Wholesaler (www.iofferkicks.com) Discount Nike Shox LV Sneaker (www.iofferkicks.com) Discount Nike Shox Turbo Suppliers (www.iofferkicks.com) Discount Nike Shox Classic Shoes Suppliers (www.iofferkicks.com) Discount Nike Shox Dendara Trainer (www.iofferkicks.com) Discount Nike Air Jordan 1 Seller (www.iofferkicks.com) Discount Nike Air Jordan 2 Shoes Seller (www.iofferkicks.com) Discount Nike Air Jordan 3 Collection (www.iofferkicks.com) Discount Nike Air Jordan 4 Shoes Collection (www.iofferkicks.com) Discount Nike Air Jordan 5 Chaussure Shoes (www.iofferkicks.com) Discount Nike Air Jordan 6 Catalog (www.iofferkicks.com) Discount Nike Air Jordan 7 Shoes Catalog (www.iofferkicks.com) Discount Nike Air Jordan 8 Customized (www.iofferkicks.com) Discount Nike Air Jordan 9 Shoes Customized (www.iofferkicks.com) Discount Nike Air Jordan 10 Wholesalers (www.iofferkicks.com) Discount Nike Jordan 11 Shoes Wholesalers (www.iofferkicks.com) Discount Nike Air Jordan 12 Factory (www.iofferkicks.com) Discount Nike Air Jordan 13 Shoes Factory (www.iofferkicks.com) Discount Nike Air Jordan 14 Shoes Sell (www.iofferkicks.com) Discount Nike Air Jordan 16 Exporter (www.iofferkicks.com) Discount Nike Air Jordan 17 Shoes Exporter (www.iofferkicks.com) Discount Nike Air Jordan 18 Offer (www.iofferkicks.com) Discount Nike Air Jordan 19 Shoes Offer (www.iofferkicks.com) Discount Nike Air Jordan 20 Manufacture (www.iofferkicks.com) Discount Nike Jordan 21 Shoes Manufacture (www.iofferkicks.com) EMAIL:IOFFERKICKS at GMAIL.COM MSN :IOFFERKICKS at MSN.COM From mail at microcorp.co.za Mon Dec 29 07:10:28 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 29 Dec 2008 14:10:28 +0200 Subject: poblem regarding opening a html file References: <022701c969a0$a4541ef0$5fc513ac@pwit.com> Message-ID: <006601c969ae$7823ae00$0d00a8c0@hendrik> Sibtey Mehdi wrote: >Hi > I have a GUI application (wxpython) that calls another GUI Application. I m using os.system (cmd) >to launch >The second GUI, in the second GUI I m trying to open the html file using the os.startfile (filename) function >but >It takes lots of time to open the html file. >If I am running only the second application then ?os.startfile? quickly open the html file. >Any one can help me to solve this problem. > Buy more memory? - Hendrik From robert.kern at gmail.com Sun Dec 7 19:14:24 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 07 Dec 2008 18:14:24 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: <014c55e9$0$20670$c3e8da3@news.astraweb.com> References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> <014c55e9$0$20670$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Sun, 07 Dec 2008 23:20:12 +0000, Steven D'Aprano wrote: > >> On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: >> >>> Rasmus Fogh wrote: >>> >>>> Current behaviour is both inconsistent and counterintuitive, as these >>>> examples show. >>>> >>>>>>> x = float('NaN') >>>>>>> x == x >>>> False >>> Blame IEEE for that one. Rich comparisons have nothing to do with that >>> one. >> There is nothing to blame them for. This is the correct behaviour. NaNs >> should *not* compare equal to themselves, that's mathematically >> incoherent. > > Sorry, I should explain why. > > Given: > > x = log(-5) # a NaN > y = log(-2) # the same NaN > x == y # Some people want this to be true for NaNs. > > Then: > > # Compare x and y directly. > log(-5) == log(-2) > # If x == y then exp(x) == exp(y) for all x, y. > exp(log(-5)) == exp(log(-2)) > -5 == -2 > > > and now the entire foundations of mathematics collapses into a steaming > pile of rubble. I didn't mean to suggest that it was incorrect, just that that particular surprising behavior is not related to rich comparisons. Even if the OP gets an __equals__() or some such, NaN will still not compare equal to NaN. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From rridge at csclub.uwaterloo.ca Wed Dec 3 15:21:20 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 03 Dec 2008 15:21:20 -0500 Subject: Debugging a Python Program that Hangs References: Message-ID: Kevin D. Smith wrote: >I have a fairly large python program that, when a certain combination >of options is used, hangs. I have no idea where it is hanging, so >simply putting in print statements to locate the spot would be quite >difficult. Unfortunately, ctrl-C'ing the program doesn't print a >traceback either. Have you tried catching the KeyboardInterrupt exception and printing an exception? Something like: try: rest_of_program() except KeyboardInterrupt: traceback.print_exc() raise Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From python.list at tim.thechases.com Sat Dec 27 10:28:10 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 27 Dec 2008 09:28:10 -0600 Subject: dummy needs help with Python In-Reply-To: References: Message-ID: <4956498A.5030408@tim.thechases.com> > I am trying to find somebody who can give me a simple python > program I can use to "program by analogy". I just want to > read two CSV files and match them on several fields, > manipulate some of the fields, and write a couple of output > files. ... > Please forgive me if this is so, and take pity on a stranger > in a strange land. Pittsburgh is a little strange, but not *that* bad :) Just for fun, I threw together a simple (about 30 lines) program to do what you describe. Consider it a bit of slightly belated Christmas pity on the assumption that this isn't classwork (a little googling suggests that it's not homework). It's 100% untested, so if it formats your hard-drive, steals your spouse, wrecks your truck, kicks your dog, makes a mess of your trailer-home, and drinks all your beer, caveat coder. But you've got the source, so you can vet it...and it's even commented a bit for pedagogical amusement if you plan to mung with it :) from csv import reader SMALL = 'a.txt' OTHER = 'b.txt' smaller_file = {} # key->line mapping dict for the smaller file f_a = file(SMALL) r_a = reader(f_a) #a_headers = reader.next() # optionally discard a header row # build up the map in smaller_file of key->line for i, line in enumerate(r_a): a1, a2, a3, a4, a5 = line # name the fields key = f1, f3, f5 if key in smaller_file: print "Duplicate key [%r] in %s:%i" % (key, SMALL, i+1) #continue # does the 1st or 2nd win? uncomment for 1st smaller_file[key] = line f_a.close() b = file(OTHER) r_b = reader(b) #b_headers = reader.next() # optionally discard a header row for i, line in enumerate(r_b): b1, b2, b3, b4, b5, b6, b7, b8, b9 = line key = b2, b8, b9 if key not in smaller_file: print "Key for line #%i (%r) not in %s" % (i+1, key, SMALL) continue a1, a2, a3, a4, a5 = smaller_file[key] # do manipulation with a[1-5]/b[1-9] here # and do something with them b.close() It makes more sense if instead of calling them a[1-5]/b[1-9], you actually use the field-names that may have be in the header rows such as cost_center, store, location, manager_id = line key = cost_center, store, location You may also have to manipulate some of the values to make key-matches work, such as cc, store, loc, mgr = line cc = cc.strip().upper() store = store.strip().title() key = cc, store, loc ensuring that you do the same manipulations for both files. The code above reads the entire smaller file into memory and uses it for fast lookup. However, if you have gargantuan files, you may need to process them differently. You don't detail the fields/organization of the files, so if they're both sorted by key, you can change the algorithm to behave like the standard *nix "join" command. Other asides: you may have to tweak treatment of a header-row (and correspondingly the line-numbers), as well as conflict-handling for keys in your a.txt source if they exist, along with the behavior when a key can't be found in a.txt but is requested in b.txt (maybe set some defaults instead of logging the error and skipping the row?), and then lastly and most importantly, you have to fill in the manipulations you desire and then actually do something with the processed results (write them to a file, upload them to a database, send them via email, output them to a text-to-speech engine and have it speak them, etc). > I come from 30 years of mainframe programming so I understand > how computers work at a bits/bytes /machine language/ source > vs.executable/reading core dumps level, and I can program in > a lot of languages most people using Python have never even > heard of, If there's such urgency, I hope you resorted to simply using one of these multitude of other languages you know -- Even in C, this wouldn't be too painful as projects go (there's a phrase you won't hear me utter frequently). Or maybe try your hand at it in pascal, shell-scripting (see the "join" command) or even assembly language. Not sure I'd use Logo, Haskel, Erlang, or Prolog. :) > My problem is that I want to do this all yesterday, and the > Python text I bought is not easy to understand. I don't have > time to work my way through the online Python tutorial. As Rick mentioned, there are a number of free online sources for tutorials, books, and the like. Dive Into Python is one of the classics. Searching the archives of comp.lang.python for "beginner books" will yield the same thread coming up every couple weeks. For future reference, if you've got time-sensitive projects to tackle "yesterday", it's usually not the best time to try and learn a new language. Good luck in your exploration of Python. -tkc From gagsl-py2 at yahoo.com.ar Thu Dec 25 01:46:39 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Dec 2008 04:46:39 -0200 Subject: ctypes & strings References: <334452.47084.qm@web30003.mail.mud.yahoo.com> Message-ID: En Wed, 24 Dec 2008 23:07:27 -0200, Red Rackham escribi?: > I would like to pass a string into a dll function.? I notice that to > pass using ctypes, it has to be a ctypes type.? Looking at the ctypes > doc page I don't see a c_string class.? Because the C language doesn't have a string type? Python strings are automatically converted to c_char_p if you set the argtypes attribute. > I tried to pass in?byref("name of string") and got back "TypeError: > byref() argument must be a ctypes instance, not 'str'" byref? Please post the prototype of the function you want to call. If it takes a const char*, or a char* but doesn't modify it, you don't have to use byref. If it takes a char* and modifies it, use create_string_buffer (also, the function SHOULD take the buffer size as an additional parameter...) > If I use astr = create_string_buffer( "name of string" ), and try to > pass that in, I get "ValueError: Procedure probably called with too many > arguments (4 bytes in excess)". Maybe you didn't set correctly the calling convention (cdecl? stdcall?). How did you load the dll and get the function? Libraries loaded using windll use the stdcall convention; cdll uses cdecl. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Sat Dec 27 15:15:58 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 27 Dec 2008 18:15:58 -0200 Subject: parsing csv files class References: <49562755.6050205@byoteki.com> Message-ID: En Sat, 27 Dec 2008 11:02:13 -0200, Gary M. Josack escribi?: > alex goretoy wrote: >> I know it's messy with all those self.soc.* functions, but it works in >> one of my current project. I just want to make it more pythonic I also >> want to add capability for makeing csv file if I give it input like: >> 1234,something nice, hey this is something nice >> 2468,something else, something else >> reader = csv.reader(file(filename, "rb")) >> try: >> for row in reader: >> self.buffer.append(row) >> s,a=[],{} > Do you know that there is a csv module in the standard library already? I'd say he already knows, he even used it in the code. To Alex G.: I didn't understand what's the purpose of this class. Probably you want to do too much things in the same place; looks like it has multiple concerns, and that's not a good idea usually. -- Gabriel Genellina From castironpi at gmail.com Sat Dec 20 20:06:24 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 20 Dec 2008 17:06:24 -0800 (PST) Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> <7e23a789-84c3-47b9-b040-ca7dd062d058@a37g2000pre.googlegroups.com> Message-ID: On Dec 18, 7:21?pm, "Gabriel Genellina" wrote: > En Thu, 18 Dec 2008 19:46:45 -0200, Aaron Brady ? > escribi?: snip > On Windows, file handles are the real OS stuff, the "true" reference to an ? > open file. File descriptors are not, they exist only to please the C ? > runtime library. Programs not written in C (directly, or indirectly like ? > Python) don't care at all about file descriptors. And in case one actually ? > cares, there is _open_osfhandle in the C RTL (available as ? > msvcrt.open_osfhandle from Python). > A subprocess may inherit handles from its parent [there are two filters: ? > the parameter "bInheritHandles" in the CreateProcess call provides global ? > control, and individual handles can be made inheritable or not, before ? > creating the new subprocess]. > "Anonymous" pipes are good to replace stdin/stdout/stderr, because there ? > is no need to explicitely communicate the handle value to the subprocess: ? > one just replaces the corresponding handle with the desired pipe, and the ? > subprocess might not even notice it. > In case this is not enough, one might pass the handle (as a number) in the ? > command line, but probably a "named pipe" would be better. As this is not ? > transparent for the child process, one must explicitely code such things. > > > Will it take calling > > 'CreatePipe' from ctypes directly if on Windows? ?Or can 'os.pipe' be > > made to abstract that? ?If Windows can't inherit descriptors, > > 'os.pipe' should return handles, and 'os.read' &co. should accept > > them. > > I think the best way would be to modify os.pipe so it returns inheritable ? > pipes, as it should have been from the beginning. > > > It is a fairly large patch. > > Not at all, you have already posted most of it. I have marginally tested the patch on a custom build. It works, but there is a catch. The descriptor can't be passed directly to the child on the command line. You need to call 'msvcrt.get_osfhandle' on the descriptor, pass the result, then call 'msvcrt.open_osfhandle' in the child. From gagsl-py2 at yahoo.com.ar Fri Dec 12 16:04:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 12 Dec 2008 19:04:14 -0200 Subject: Bidirectional Networking References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <6qeht0Fc3541U1@mid.individual.net> <782258db-2bdc-45a7-8d8f-7a036d574985@t26g2000prh.googlegroups.com> Message-ID: En Fri, 12 Dec 2008 15:22:34 -0200, Emanuele D'Arrigo escribi?: > Thank you both for the suggestions! Eventually I tried with threading > as illustrated in the code below. > And it works pretty well! The only problem I'm having with it is that > as the server is a daemon the program should end when the client > thread cease to be alive. But it doesn't seem to work that way and I'm > not sure what's going on! I did achieve my objective though. Two > separate instances of the code below will happily send random numbers > to each other for a few seconds! If you're using 2.5 or older, override serve_forever: def serve_forever(self): while not getattr(self, 'quit', False): self.handle_request() and set the server 'quit' attribute to True in response to some command from the client. Python 2.6 has a shutdown() method for the same purpose. -- Gabriel Genellina From pdorange at pas-de-pub-merci.mac.com Mon Dec 22 11:51:52 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Mon, 22 Dec 2008 17:51:52 +0100 Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> <1iscu14.oixxplpgajabN%pdorange@pas-de-pub-merci.mac.com> <9977fd77-9a17-4dcb-9193-49009763c683@33g2000yqm.googlegroups.com> Message-ID: <1isczzk.1ahgisd19z7dg7N%pdorange@pas-de-pub-merci.mac.com> Istvan Albert wrote: > try testing on a large number of candidates that are all (or mostly) > positive or all (or mostly) negative and you'll see performance > numbers that are substantially different than the ones you report: > > candidates = range(1000) > > In general the function sign_1() is expected to be the fastest because > in most cases will detect the sign with the fewest operations, it only > visits the rest of the comparison when it hits the corner cases. Only > if you have lots of +/-0.0 cases will it be slower than the rest, due > to having to call an expensive operation. You're right. On a range or a random list sign_1 is the fastest : with : candidates=[] for i in range(1000): candidates.append(1000.0*random.random()-500.0) In my first candidate list, the two ZERO (-0.0 and +0.0) make sign_1 less productive because it call atan2(). With random number sign_1 is faster, just a bit faster, except if the candidates contain some ZERO. I also make other test, with a range(1000), sign_1 became really faster : -41% (near twice faster than sign_0). I then rewrote a sign_0 version testing first positive, then negative and ZERO as the last test. I also made tests and return integer. It make it faster +20% but not as fast as sign_1 for a range. What is strange is that when testing with "range" list (0 1000) or (-500 +500), sign_1 is twice as fast as with a random generated list. The only thing a saw is that range generate an int list and random a float list... So it seems sign_1 is really fastest with integer, but not with float Range from -500 to +500 sign_0 : 0.38" sign_1 : 0.27" (-40%) Range from 0 to 1000 sign_0 : 0.32" sign_1 : 0.25" (-22%) Range from -1000 to 0 sign_0 : 0.46" sign_1 : 0.30" (-35%) 1000 Random from -500 to +500 sign_0 : 0.37" sign_1 : 0.42" (+13%) -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From manu3d at gmail.com Sun Dec 14 06:37:38 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Sun, 14 Dec 2008 03:37:38 -0800 (PST) Subject: Bidrectional Subprocess Communication References: Message-ID: <5b4f4146-ad39-4fe6-9055-e852bd127143@q26g2000prq.googlegroups.com> On Dec 14, 4:48?am, "Gabriel Genellina" wrote: > - you have to close server.stdin when you don't have more data to send. > The server will see an end-of-file and knows it has to exit the loop. > Same thing on the client side. Hi Gabriel, thanks for modifying the code to make it work. I've just tried tinkering with it to see how far it would go. On your two statements above: does this means that any data must be sent in one batch and then the subprocess must shut down? What I was trying to simulate is a client/server relationship through a subprocess, where the server (the subprocess) keeps listening and the client sends data when it wants to (and eventually viceversa). But when the server.stdin.close() statement is issued, the pipe is closed for good and can't be reopened (can it?). > - you have to wait until the server answers, else it will get a "broken > pipe" error or similar. So, if I want to interrogate the subprocess multiple times I must end and restart the ListenerThread multiple times then? In the meantime, I better brush up on my streams... =) Thanks for your help! Manu From gagsl-py2 at yahoo.com.ar Tue Dec 16 04:44:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Dec 2008 07:44:02 -0200 Subject: Interface & Implementation References: <11e2ac5b5eb.2364397661727502391.6806593866408074890@adventnet.com> Message-ID: En Fri, 12 Dec 2008 19:48:09 -0200, Lie Ryan escribi?: > but if you really want it, simple inheritance might be better anyway, > though not really pythonic: > > class MyIfc(object): > def myMeth1(self): return NotImplemented > def myMeth2(self): return NotImplemented > class MyClass(MyIfc): > def myMeth1(self): > # some implementation > def myMeth2(self): > # some implementation > > # some might notice the (ab)use of NotImplemented sentinel there I'd raise NotImplementedError instead. -- Gabriel Genellina From febaen at gmail.com Tue Dec 16 09:56:07 2008 From: febaen at gmail.com (feba) Date: Tue, 16 Dec 2008 06:56:07 -0800 (PST) Subject: Free place to host python files? References: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> Message-ID: <32599660-2393-4e18-8c48-05d64bccbbc1@t26g2000prh.googlegroups.com> On Dec 16, 8:29?am, s... at pobox.com wrote: > ? ? feba> I'm getting started in python, and it would be helpful to have a > ? ? feba> place to put up various code snippets I've made, so I don't have > ? ? feba> to send them individually to each person I want to show it to. > ? ? feba> I'd prefer to use something that would give me a directory for my > ? ? feba> use only, instead of something where you can only upload one at a > ? ? feba> time. ?I'd especially like to avoid stuff that uses CAPTCHAs > ? ? feba> and/or forced waiting periods. > > http://pastebin.com/? > > -- > Skip Montanaro - s... at pobox.com -http://smontanaro.dyndns.org/ well, ignoring the fact that pastebin doesn't work for me for some reason, I'm talking about hosting it as a .py downloadable, not a hunk of text. From nospam at nospam.com Fri Dec 26 15:33:32 2008 From: nospam at nospam.com (Gilles Ganault) Date: Fri, 26 Dec 2008 21:33:32 +0100 Subject: [SQL] Right way to set a variable to NULL? Message-ID: <5nfal41gom0iqi2nh5h0m5847ev9brtvpf@4ax.com> Hello I use regexes to extract information from a text file. Some of the records don't have e-mails or www addresses, so those must match Null in SQL, but None doesn't work as expected: ======= if itemmatch: web = itemmatch.group(1).strip() else: web = None sql = 'INSERT INTO mytable (name,address,web,mail) VALUES ("%s","%s","%s","%s","%s")' % (name,address,web,mail) ======= Is there a better way in Python to have a variable match NULL than building the SQL query step by step? Thank you. From martin.laloux at gmail.com Fri Dec 19 04:13:42 2008 From: martin.laloux at gmail.com (gene) Date: Fri, 19 Dec 2008 01:13:42 -0800 (PST) Subject: If programming languages were religions... Message-ID: very interesting http://www.aegisub.net/2008/12/if-programming-languages-were-religions.html "Python would be Humanism: It's simple, unrestrictive, and all you need to follow it is common sense. Many of the followers claim to feel relieved from all the burden imposed by other languages, and that they have rediscovered the joy of programming. There are some who say that it is a form of pseudo-code" compare to "Perl would be Voodoo - An incomprehensible series of arcane incantations that involve the blood of goats and permanently corrupt your soul. Often used when your boss requires you to do an urgent task at 21:00 on friday night." and others From exarkun at divmod.com Thu Dec 4 14:42:32 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 4 Dec 2008 14:42:32 -0500 Subject: Python 3 read() function In-Reply-To: Message-ID: <20081204194232.20272.544720092.divmod.quotient.15718@ohm> On Thu, 04 Dec 2008 14:25:48 -0500, Terry Reedy wrote: > [snip] > >In my test, I read Python25.chm with 2.5 and Python30.chm with 3.0. > >Rereading Python30.chm without closing *is* much faster. > >>> f=open('Doc/Python30.chm','rb') > >>> d=f.read() > >>> d=f.read() > >>> d=f.read() Did you think about what this does? Jean-Paul From mmanns at gmx.net Sun Dec 7 12:19:10 2008 From: mmanns at gmx.net (mmanns at gmx.net) Date: Sun, 7 Dec 2008 18:19:10 +0100 Subject: can graphs be made in python as we make in java References: <89ff42d1-6a4c-4d45-a646-238b43e7e8de@s9g2000prm.googlegroups.com> Message-ID: <20081207181910.2d63961c@Schlamber.localdomain> On Sun, 7 Dec 2008 00:29:13 -0800 (PST) suku wrote: > HI folks... > > i need some suggestion on making graphs. Will this be possible > with normal python setup file or do i need to download add ons for > that.. > > help me out rpy Martin From __peter__ at web.de Fri Dec 19 10:55:20 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2008 16:55:20 +0100 Subject: change string to unicode References: Message-ID: jyoung79 at kc.rr.com wrote: > If I have a string like so: > > a = '\\u03B1' > > and I want to make it display a Greek alpha character, is there a way to > convert it to unicode ('\u03B1')? I tried concatenating it like this: > > '\u' + '03B1' > > but that didn't work. I'm working in Python 3.0 and was curious if this > could be done. How about >>> "\\u03b1".encode("ascii").decode("unicode-escape") '?' Peter From stefan_ml at behnel.de Tue Dec 30 17:33:24 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 30 Dec 2008 23:33:24 +0100 Subject: Python in C In-Reply-To: References: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> <313583fc-4651-4deb-8a44-c3b1810b722c@z27g2000prd.googlegroups.com> Message-ID: <495aa1b4$0$31329$9b4e6d93@newsspool4.arcor-online.net> akineko wrote: > The more you work on Python, the harder you can go back to C or C++ > world. > > I use SWIG, instead. I think SWIG is a good way to mix two worlds. If you find it hard to go from Python back to C, you should have a look at Cython. http://cython.org/ Stefan From gagsl-py2 at yahoo.com.ar Wed Dec 17 18:05:21 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 17 Dec 2008 21:05:21 -0200 Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> Message-ID: En Wed, 17 Dec 2008 12:21:38 -0200, Jeremy Sanders escribi?: > Aaron Brady wrote: > >> I thought so too. The web seems to say that on Linux they are, and on >> Windows, you need to call DuplicateHandle for it. Or set bInheritHandle=True when creating the pipe initially. os.pipe() doesn't do that. > I hit this problem - it looks like pipes aren't very versatile on > Windows. > There's also the complicating factor that the handles in windows aren't > the > same as the file numbers that Python uses, so you have to convert between > them. > > It would be nice if Python created pipes that are properly inheritable by > default by child processes, as they're mostly used for IPC. I'd say it is a bug in os.pipe implementation; they should be inheritable by default, as in posix (after all, the code is in "posixmodule.c"). -- Gabriel Genellina From miki.tebeka at gmail.com Mon Dec 1 22:54:54 2008 From: miki.tebeka at gmail.com (Miki) Date: Mon, 1 Dec 2008 19:54:54 -0800 (PST) Subject: Loading required libraries for python script from shell just once References: Message-ID: <3181dc1c-a894-4fe8-8eca-fccc3e2170c4@q30g2000prq.googlegroups.com> > Is it possible to load all the modules used by run-test.py in > a pre-execution environment in order to prevent this delay? Only if you have one script the calls "main" (or any other entry point) in the tests. > I considered a rewrite of the shell script into python, but it has too > many dependencies on shell libraries and I don't want to go that route > (unless an alternative solution is impossible). One other option is to have the python libraries on local disk, but IMO the first solution is better. HTH, -- Miki http://pythonwise.blogspot.com From alexoplocatie at gmail.com Thu Dec 18 06:56:53 2008 From: alexoplocatie at gmail.com (aka) Date: Thu, 18 Dec 2008 03:56:53 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> <0d9ea7cc-b5fb-4edb-be32-490aae9e7204@b41g2000pra.googlegroups.com> <0de3a7bf-a4c4-4103-a4e0-44313405fa94@z28g2000prd.googlegroups.com> <23d6710f-2c6d-4115-817a-053b8e96f1ce@z28g2000prd.googlegroups.com> Message-ID: <5529f88b-8db4-4fad-ad41-42bf39469a08@w1g2000prk.googlegroups.com> On 18 dec, 00:06, John Machin wrote: > On Dec 18, 3:15?am, aka wrote: > > Do you mean that this file was created by whatever.UnicodeWriter? If > so, did you just now discover this information? > > How do you know that "the UnicodeWriter is functioning perfectly"? > What does "functioning perfectly mean to you"? In particular, what > encoding is it using? > > Which do you mean: > (a) you typed those lines into Notepad yourself > (b) you took a copy of a file created by whatever.UnicodeWriter, > opened it with Notepad, trimmed off some rows and columns, and saved > it again > ? > Here's a likely hypothesis: the file was written in utf16. In that > case: > either (i) you really want utf16 (why?), so: > > (1) the csv module will not cope with it, and is not expected to cope > with it > > (2) the whatever.UnicodeReader should (in order of preference): > (a) be allowed to find out for itself that 'utf16' is the go > (b) be told explicitly that 'utf16' is the go > (c) be served with a bug report > > OR (ii) you really want utf8, so: > > (1) the csv module should be happy > (2) the whatever.UnicodeWriter should be told to use 'utf8' > (3) the whatever.UnicodeReader should (in order of preference): > [as above but s/16/8/] > The csv file originally was created by the UnicodeWriter class and was used for a mailmerge function with Microsoft Word which all functioned perfectly. The reverse did not: read back the outputted file so at last I editted it in Notepad, cutting off columns, but I didn't know that the encoding would remain even after that because it still caused problems. Now after testing from the Python command line with a csv file generated from Excel I could get it working so it had to be the encoding. Because the write side of my code, which uses the UnicodeWriter, was ok I didn't pay attention to the fact that I had changed the UW class from UTF-8 to UTF-16 because of difficulties with dutch characters like ? and ?. Then at last I tried changing back to UTF-8 and noticed both out -and input was working, including those special characters, so it was my unjustifiable conclusion that I couldn't get around these special characters at the write side without UTF-16 which ultimately got me in trouble with the read side. With your help I got it straight. Once again minimizing the problem to its bare basics and to prevent big steps is the key. Thanks a lot for your help John. BTW, the TurboGears code by the way is not very different from Python, it just uses some extra identifiers. From NIE_DZIALA at gazeta.pl Sun Dec 14 05:16:56 2008 From: NIE_DZIALA at gazeta.pl (Piotr Sobolewski) Date: Sun, 14 Dec 2008 11:16:56 +0100 Subject: the official way of printing unicode strings References: <6qk1o7Fcr01gU3@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > I'd make that first line: > sys.stdout = codecs.getwriter('utf-8')(sys.stdout) > > Why is it even more cumbersome to execute that line *once* instead > encoding at every ``print`` statement? Oh, maybe it's not cumbersome, but a little bit strange - but sure, I can get used to it. My main problem is that when I use some language I want to use it the way it is supposed to be used. Usually doing like that saves many problems. Especially in Python, where there is one official way to do any elementary task. And I just want to know what is the normal, official way of printing unicode strings. I mean, the question is not "how can I print the unicode string" but "how the creators of the language suppose me to print the unicode string". I couldn't find an answer to this question in docs, so I hope somebody here knows it. So, is it _the_ python way of printing unicode? From mirandasnailvv at gmail.com Fri Dec 19 19:43:03 2008 From: mirandasnailvv at gmail.com (mirandasnailvv at gmail.com) Date: Fri, 19 Dec 2008 16:43:03 -0800 (PST) Subject: cause of paraphilias from behavioral prespective - Free Message-ID: <2d98ed6a-b487-4506-a21c-5c3ea563933d@o4g2000pra.googlegroups.com> cause of paraphilias from behavioral prespective . . . *******CLICK HERE******** http://club247.cn/cause-of-paraphilias-from-behavioral-prespective ***************************** . . . . . . . . . . . . cause of paraphilias from behavioral prespective From rdmurray at bitdance.com Thu Dec 4 15:22:19 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Thu, 4 Dec 2008 15:22:19 -0500 (EST) Subject: Why shouldn't you put config options in py files In-Reply-To: References: Message-ID: On Thu, 4 Dec 2008 at 11:35, HT wrote: > I can think of lots of arguments why this is a bad idea, but I don't > seem to be able to think of a really convincing one. I think it depends on the problem domain. As someone else said, there are issues with being able to inject arbitrary code via the config file. In some applications, this would be a feature, in others it would be a security hole. Another angle to look at is the audience for the config file. If they are all going to be python programmers or python-familiar, great. If not...think about the user reaction to the tracebacks resulting from typos. If you use a purpose-designed config file (whether it is based on ConfigParser or not), you can more easily generate helpful error messages. --RDM From psftw1 at gmail.com Sun Dec 14 17:03:54 2008 From: psftw1 at gmail.com (peter s.) Date: Sun, 14 Dec 2008 14:03:54 -0800 (PST) Subject: Building from source -- zlib/binascii problems 2.5.2/2.6.1 References: <71531b64-535f-49d0-a0c6-7704df83b251@f18g2000vbf.googlegroups.com> <49458079.1000304@v.loewis.de> Message-ID: <003b0307-c8df-489b-98e6-cfaa35d050a4@k1g2000prb.googlegroups.com> On Dec 14, 4:54?pm, "Martin v. L?wis" wrote: > > Target: x86_64-redhat-linux > > gcc -pthread -shared build/temp.linux-x86_64-2.5/location/of/ > > Python-2.5.2/Modules/zlibmodule.o -L/usr/local/lib -lz -o build/ > > lib.linux-x86_64-2.5/zlib.so > > /usr/bin/ld: skipping incompatible /usr/lib/libz.so when searching for > > -lz > > Do > > ? file /usr/lib/libz.so > > It might be a 32-bit library, in which case you can check whether > /usr/lib64 has a 64-bit library. I'm puzzled why it only > happens for -lz; perhaps you are better of compiling with a 32-bit > compiler. > > Regards, > Martin $ file /usr/lib/libz.s* /usr/lib/libz.so: symbolic link to `libz.so.1.2.3' /usr/lib/libz.so.1: symbolic link to `libz.so.1.2.3' /usr/lib/libz.so.1.2.3: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), stripped From prologic at shortcircuit.net.au Tue Dec 16 17:47:32 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 17 Dec 2008 08:47:32 +1000 Subject: Python is slow In-Reply-To: References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <355f1cfe-6abb-4d2c-8bf4-3aa62e713c1f@w34g2000yqm.googlegroups.com> Message-ID: n Wed, Dec 17, 2008 at 8:24 AM, r wrote: >> What kind of performance problem have you find in python that makes >> you so unhappy? >> What are you going to do with all the extra speed provided by c++ (a >> Hello World! ?)... > > Still no reply from cm_gui, he must have googled "C hello world" :D I must be mad for doing this - but I feel so strongly about this topic. In 99.9% of cases generally things are "feast enough"! So here goes: jmills at atomant:~$ cat - > hello.c int main (int argc, char ** argv) { printf("Hello World!\n!"); } jmills at atomant:~$ tcc hello.c -o hello jmills at atomant:~$ wc -l hello.c 3 hello.c jmills at atomant:~$ ls -l hello.c -rw-r--r-- 1 jmills jmills 69 2008-12-17 08:41 hello.c jmills at atomant:~$ ls -l hello -rwxr-xr-x 1 jmills jmills 2972 2008-12-17 08:41 hello jmills at atomant:~$ time ./hello Hello World! ! real 0m0.003s user 0m0.000s sys 0m0.004s jmills at atomant:~$ cat - > hello.py print "Hello World!" jmills at atomant:~$ time python hello.py Hello World! real 0m0.129s user 0m0.016s sys 0m0.020s OMG OMG OMG! Python is slower! If you compare "sys" times ~5x slower! BUT ... This is in fact a misleading as most of this is in the startup time. So let's be fairer: jmills at atomant:~$ time python -E -S hello.py Hello World! real 0m0.011s user 0m0.008s sys 0m0.004s Wow! Only ~2x as slow as C. --JamesMills PS: Yet another useless post! From gabriel.rossetti at arimaz.com Wed Dec 10 05:26:01 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Wed, 10 Dec 2008 11:26:01 +0100 Subject: memory leak? In-Reply-To: <493F8188.1030700@arimaz.com> References: <493EAB79.6070805@arimaz.com> <493F8188.1030700@arimaz.com> Message-ID: <493F9939.2020302@arimaz.com> Gabriel Rossetti wrote: > Terry Reedy wrote: >> Gabriel Rossetti wrote: >> >>> I ran these tests on linux 2.6 (ubuntu 8.04) using python 2.5.2. >> >> Have you tried the much newer 2.6? 2.5.3 will be out soon with some >> bug fixes. >> > Thanks for the reply Terry, I just tried the pyserial example with > python 2.6 and it still has the same problem, here's the output (I > just copy/pasted the example in a running python2.6 interactive > interpreter) : > > test1 at 09:19am : > > $ ps waux | grep python2.6 > 1000 6730 0.2 0.4 6176 4120 pts/12 S+ 09:17 0:00 > python2.6 > > if I try the SIGUSR1 method : > $ kill -SIGUSR1 6730 > > #################################################################### > # DEBUG: The object count is : 12536 > #################################################################### > > test2 at 09:25am : > > $ ps waux | grep python2.6 > 1000 6730 0.0 0.9 12360 10168 pts/12 S+ 09:17 0:00 > python2.6 > > and the SIGUSR1 method gives me : > > #################################################################### > # DEBUG: The object count is : 25089 > #################################################################### > > > I also tried freeing the received string (del t) explicitly but the > results are unchanged. > > Thank you, > Gabriel > Apparently the memory goes up when I use the SIGUSR1 code, If I don't call it, it seams to work fine, my original memory leak must come from somewhere else then..... sorry for the spam. Gabriel From lew at lewscanon.com Mon Dec 29 11:20:34 2008 From: lew at lewscanon.com (Lew) Date: Mon, 29 Dec 2008 08:20:34 -0800 (PST) Subject: HTML Correctness and Validators References: <2fb289be-00b3-440a-b153-ca88f0ba16c5@d42g2000prb.googlegroups.com> <6rsbahF33ndvU1@mid.individual.net> Message-ID: <9eba3125-07e7-42ff-98c0-0b9be6105315@r36g2000prf.googlegroups.com> Xah Lee wrote... >> recently [sic] i [sic] wrote a blog essay about html [sic] correctness and html [sic] >> validators, with relations [sic] to the programing [sic] lang [sic] communities. I hope >> programing [sic] lang [sic] fans will take more consideration on [sic] the correctness >> of the doc [sic] they produces [sic]. "Aaron Gray" wrote: > Do you enjoy spamming comp.lang.functional with OT cross-posts ? Is that a rhetorical question? -- Lew From lepto.python at gmail.com Sat Dec 20 06:20:11 2008 From: lepto.python at gmail.com (oyster) Date: Sat, 20 Dec 2008 19:20:11 +0800 Subject: check whether a JPG is completed? Message-ID: <6a4f17690812200320r5cf05523v39517243a5c33ae4@mail.gmail.com> there are some pics(most of them are JPGs) on my disk, but some are not completed, that is to say, if I view it in irfanview, the bottom is displayed as a gray block. so I want to check where they are completed. but how to do that in python? (No, I am not saying "how to tell the fileszie when I download a file from internet") thanx From python at bdurham.com Wed Dec 24 04:21:30 2008 From: python at bdurham.com (python at bdurham.com) Date: Wed, 24 Dec 2008 04:21:30 -0500 Subject: Most efficient way to build very large dictionaries In-Reply-To: References: <1230104615.5867.1291617213@webmail.messagingengine.com> <1230107768.14060.1291622121@webmail.messagingengine.com> Message-ID: <1230110490.21192.1291625281@webmail.messagingengine.com> Hi Roger, > The performance improvements you are seeing with Python over Oracle are exactly the same range people see with SQLite over Oracle. One common usage reported on the SQLite mailing list is people copying data out of Oracle and running their analysis in SQLite because of the performance advantages. I wasn't aware that SQLite was so fast compared to Oracle. That's great news. I will definitely take a look at SQLite for my current data analysis project. ... hey, you're the author of APSW! :) For those following this thread, see APSW: http://code.google.com/p/apsw/ > The pragmas tune things like cache sizes. The SQLite default is 2MB, relying on the operating system for caching beyond that. Bumping up that kind of size was my suggestion :-) I missed that nuance - a side effect of emailing at 4am :) Thanks again for your help Roger! Regards, Malcolm ----- Original message ----- From: "Roger Binns" To: python-list at python.org Date: Wed, 24 Dec 2008 00:50:49 -0800 Subject: Re: Most efficient way to build very large dictionaries -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 python at bdurham.com wrote: > Thank you for your suggestion about looking at SQLite. I haven't > compared the performance of SQLite to Python dictionaries, but I'm > skeptical that SQLite would be faster than in-memory Python dictionaries > for the type of analysis I'm doing. I'd recommend at least trying a test just to see. As an example SQLite uses indices which will be faster than Python dicts for some set operations. (And if you aren't careful, your various Python based optimizations will end up duplicating what SQLite does internally anyway :-) > Prior to my use of Python, my > customer used a very expensive Oracle system to analyze their log files. > My simple Python scripts are 4-20x faster than the Oracle PL/SQL they > are replacing - and run on much cheaper hardware. SQLite is not like Oracle or any similar database system. It does not operate over the network or similar connection. It is a library in your process that has an optimized disk storage format (single file) and a SQL parser that generates bytecode for a special purpose virtual machine in pretty much the same way CPython operates. The performance improvements you are seeing with Python over Oracle are exactly the same range people see with SQLite over Oracle. One common usage reported on the SQLite mailing list is people copying data out of Oracle and running their analysis in SQLite because of the performance advantages. > Note: Memory is currently not a concern for me so I don't need SQLite's > ability to work with data sets larger than my physical memory. The pragmas tune things like cache sizes. The SQLite default is 2MB, relying on the operating system for caching beyond that. Bumping up that kind of size was my suggestion :-) Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAklR9+UACgkQmOOfHg372QSMbwCdGS5S2/96fWW8knjfBVqReAfV AEwAn2Yc+L9BEZgT69OjwtyqxLtifVpU =mPfy -----END PGP SIGNATURE----- -- http://mail.python.org/mailman/listinfo/python-list From Astley.lejasper at gmail.com Thu Dec 4 04:21:50 2008 From: Astley.lejasper at gmail.com (Astley Le Jasper) Date: Thu, 4 Dec 2008 01:21:50 -0800 (PST) Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> <126ba84a-0ea0-4a91-b7d2-89ed650e5d6c@d32g2000yqe.googlegroups.com> Message-ID: <6a302e08-e8be-4d5e-b754-11fc18468cc8@v4g2000yqa.googlegroups.com> On Dec 4, 12:34?am, Lawrence D'Oliveiro wrote: > In message , Philip > > Semanchuk wrote: > > In my experience, the environment in which a cron job runs is > > different from the environment in which some command line scripts run... > > Which is true, but again, cron should report the environment in the mail > message. For example, here are some headers from a recent run of the > maildir backup task I have scheduled twice a day: > > ? ? Subject: Cron $HOME/bin/backupdir $HOME/.maildir > ? ? X-Cron-Env: > ? ? X-Cron-Env: > ? ? X-Cron-Env: > ? ? X-Cron-Env: > ? ? X-Cron-Env: Where do you get the emails from? From skip at pobox.com Tue Dec 23 08:41:24 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 23 Dec 2008 07:41:24 -0600 Subject: pseudo terminal usage from Python? Message-ID: <18768.60036.20440.46074@montanaro-dyndns-org.local> I ran into an interesting problem yesterday. The mpstat(1) command on Solaris formats its output like so: CPU minf mjf xcal intr ithr csw icsw migr smtx srw syscl usr sys wt idl 0 42 1 1184 812 265 227 12 44 37 0 1131 6 2 0 93 1 25 1 933 447 2 203 37 75 12 0 902 5 4 0 91 2 17 0 195 495 1 201 41 77 13 0 514 5 1 0 94 3 4 0 117 882 405 171 34 65 21 0 449 5 2 0 93 I'm only interested in presenting the CPU numbers and user+sys values prefixed by a timestamp. For example, the above might be formatted like so: 07:28:46.373328 0 8 1 9 2 6 3 7 The obvious solution might be something simple like this: mpstat 1 | python mympstat.py where mympstat.py does a trival amount of reformatting. The problem is that mpstat recognizes when its output is a pipe and block buffers it so the Python script sees input in massive blobs, not the second-by-second output you'd see running "mpstat 1" by itself. I've been reduced to a much more complicated solution which involves forking mpstat with output to a file, then reading the end of that file every second. A three-line Python script balloons into a one-page script. Yuck. Add to that I'm writing this for an admin who is considering Python as a scripting language. Double Yuck. (But not nyuk nyuk, this is not the Stooges.) I suspect there is some magic I can perform with pseudo terminals (this is on Solaris 10.) The documentation for the pty module contains no examples and I've been so far unable to find any using Google. Any pointers/examples? I will gladly add an example to the pty module docs (I have the power!) once I have a couple working examples (maybe one example each of reading and writing?) Thanks, -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From sumerc at gmail.com Mon Dec 15 15:13:03 2008 From: sumerc at gmail.com (k3xji) Date: Mon, 15 Dec 2008 12:13:03 -0800 (PST) Subject: Simple multithreaded profiler using decorators fails on some built-in methods Message-ID: <64fbf6f9-99e4-4adc-b1a1-638f1b8e57b7@w24g2000prd.googlegroups.com> Hi all, I have written a simple multithreaded profiler using decorators. Below is how it works: 1) Iterate all modules in sys.modules and iterate each function/ class methods inside them, means all of them including built-in methods. 2) Decorate the methods and functions to a global function. 3) This global function acquires a global lock and updates callCount, timeElapsed values, the list of running threads and the function that the thread is currently executing. 4) We have a result(..) function which acquires the global lock again and iterates the above info with showing it in the console. The problem arises when following happens: - we call result(..) function from Thread 1 - result(..) acquires the global lock to read the information - Then, somehow in the result __repr__() builtin function is being called and as we also have decorated this function, this leads to a deadlock. Above took me 3 hours of debugging effort, and the worse part is __repr__() is NOT being called in the same place always. It is sometimes called in somestring processing in the top of the function sometimes in the below. So, I ended up avoiding __repr__() profiling in the profiler . However, this situation puts me in a position that there may be other built-in calls that may end up with a deadlock. I can afford to avoid profiling of all built-in functions but how to do that? Or is there any idea on this? IMPORTANT: I am not sure, but this problem may be the real cause of why we don't see realtime profile results on cProfile or Profile libraries? All of these profilers are have to be stopped before showing you the results, that way I can avoid the necessity of locking () in the result(..) function. Regards, From ron.reidy at gmail.com Thu Dec 11 12:34:34 2008 From: ron.reidy at gmail.com (ron.reidy at gmail.com) Date: Thu, 11 Dec 2008 09:34:34 -0800 (PST) Subject: cx_Oracle issues References: <5b2dad81-2750-4347-8079-6ab31321d579@s1g2000prg.googlegroups.com> Message-ID: <9142a8f1-7f76-4fc0-9ca1-c9dec310f2ce@r37g2000prr.googlegroups.com> On Dec 10, 9:48?am, huw_at1 wrote: > Hey all. When using cx_Oracle to run a procedure like: > > cursor.execute("select (obj.function(value)) from table where > id=blah") > > I am getting the following error: > > ORA-06502: PL/SQL: numeric or value error: character string buffer too > small ORA-06512: at line 1 > > Looking at cursor.description I get: > > [('(obj.function(value))', , 4000, 4000, 0, > 0, 1)] > > Any tips - i have never seen this error before but am guessing that > the value being returned is too big for the buffer size set for the > cursor. the procedure fetches data from a LOB. > > Any suggestions/confirmations? > > Many thanks This error is a problem with the PL/SQL, not cx_Oracle. You need to debug obj.function to see what kind of data is being accessed and then a data analysis of that data to understand why this error occurs. I can tell you the function is most likely expecting characters from a column that are numeric [0 .. 9] and is getting alpha characters. -- Ron Reidy Sr. Oracle DBA From geekmail at usenot.de Thu Dec 4 14:21:30 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Thu, 4 Dec 2008 20:21:30 +0100 Subject: Please fix your clock [was Re: Multiple equates] References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> <0147f4b7$0$20670$c3e8da3@news.astraweb.com> <20081204170017.4be41c7f@usenot.de> Message-ID: <20081204202130.326377dc@usenot.de> On Thu, 4 Dec 2008 06:40:02 +0200 "Hendrik van Rooyen" wrote: > "Andreas Waldenburger" > > > On 04 Dec 2008 15:53:21 GMT Steven D'Aprano > > wrote: > > > > > Hendrik, I think your PC's clock is wrong. You seem to be posting > > > from the future. > > > > So? Maybe he is. What's your problem? > > It was probably playing hob with his threading reader... > Sorry, I should probably have enclosed that in a tag. ;) /W -- My real email address is constructed by swapping the domain with the recipient (local part). From paul at boddie.org.uk Thu Dec 18 12:34:39 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 18 Dec 2008 09:34:39 -0800 (PST) Subject: psycopg2 and large queries References: Message-ID: On 18 Des, 16:34, Laszlo Nagy wrote: > psycopg2 is said to be db api 2.0 compilant, but apparent it is buggy. > By default, when I create a cursor with > > cur = conn.cursor() > > then it creates a cursor that will fetch all rows into memory, even if > you call cur.fetchone() on it. (I tested it, see below.) Yes, I filed a bug against psycopg2 on this very subject, although the project doesn't seem to have a bug-tracker any more. > I was looking for psycopg2 documentation, but I found nothing. However, > I found some posts telling that named cursors do support fetching a > single row at a time. Here is how to create a named cursor: > > cur = conn.cursor('mycursor') > > This is very strange, because DB API 2.0 does not have this feature. Why > this feature was created, and how to use it? Not documented. The reason is that PostgreSQL supports server-side cursors through a DECLARE ... CURSOR statement, but that statement can only be used with certain SQL statements. Other DB-API modules employ simple but imperfect tricks to guess whether the statement being issued is compatible with DECLARE ... CURSOR before automatically creating a cursor, but the psycopg2 maintainers refused to introduce such a feature as part of the default behaviour. I didn't pursue the avenue of making a suitable set of patches to satisfy both them and myself, and I subsequently went back to using pyPgSQL instead. [...] > It is clear that named cursors have very bad performance, I cannot use > them. Nameless cursors cannot be used either, because they are stressing > the system, put 100% disk I/O and big memory usage, without any good reason. > > The only one solution I found is to use named cursors, and use > fetchmany(100) instead of fetchone(). This results in fast opening > (0.005 sec) of the cursor, and good speed (30 000 rec/sec, about 75% of > the nameless version). (Do I really need to implement buffering in > Python to be efficient???) You really don't want to be traversing large data sets using fetchone, anyway. My approach (using pyPgSQL) involves fetchmany and then looping over each batch of results, if I really have to process the data in Python; most of the time I can do the processing in the database itself. > However, this is also not usable, because named cursors do not have a > ".description" property! You can try this: > > cur = conn.cursor('mycursor') > cur.execute('select name from product limit 1000000') > print repr(cur.description) ?# -> None > > This is unacceptable! This is not DB API 2.0 compilant. I have to know > the names of the columns, how can I do that? > > What am I doing wrong? Please help me! I'm not really a user of the description property, so I can't advise you there. Strictly, psycopg2 is DB-API compliant, but the interaction between result sets and cursors really doesn't live up to what the specification suggests is possible. Paul From rocky at panix.com Tue Dec 30 05:04:10 2008 From: rocky at panix.com (R. Bernstein) Date: Tue, 30 Dec 2008 05:04:10 -0500 Subject: How do I DRY the following code? References: <0169d83a$0$6988$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano writes: > On Mon, 29 Dec 2008 21:13:55 -0500, R. Bernstein wrote: > >> How do I DRY the following code? >> >> class C(): > [snip code] > > Move the common stuff into methods (or possibly external functions). If > you really need to, make them private by appending an underscore to the > front of the name. > > > class C(): > def common1(self, *args): > return "common1" > def common2(self, *args): > return "common2" > def _more(self, *args): # Private, don't touch! > return "more stuff" > > def f1(self, arg1, arg2=None, globals=None, locals=None): > ... unique stuff #1 ... > self.common1() > ret = eval(args, globals, locals) > self._more() > return retval > > def f2(self, arg1, arg2=None, *args, **kwds): > ... unique stuff #2 ... > self.common1() > ret = arg1(args, *args, **kwds) > self.common2 > return retval > > def f3(self, arg1, globals=None, locals=None): > ... unique stuff #3 ... > self.common1() > exec cmd in globals, locals > self.common2() > return None # unneeded > > def f4(self, arg1, globals=None, locals=None): > ... unique stuff #4 ... > self.common1() > execfile(args, globals, locals) > self._more() > I realize I didn't mention this, but common1 contains "try:" and more contains "except ... finally". So for example there is self.start() try: res = func(*args, **kwds) # this line is different except ... finally: ... Perhaps related is the fact that common1 and common2 are really related and therefore breaking into the function into 3 parts sort of breaks up the flow of reading one individually. I had also considered say passing an extra parameter and having a case statement around the one line that changes, but that's ugly and complicates things too. > > An explicit "return None" is probably not needed. Python functions and > methods automatically return None if they reach the end of the function. "return None" is a perhaps a stylistic idiom. I like to put "returns" at the end of a function because it helps (and Emacs) me keep indentation straight. Generally, I'll put "return None" if the function otherwise returns a value and just "return" if I don't think there is a useable return value. I've also noticed that using pass at the end of blocks also helps me and Emacs keep indntation straight. For example: if foo(): bar() else baz() pass while True: something pass > > > > > >> Above there are two kinds of duplication: that within class C and that >> outside which creates an instance of the class C and calls the >> corresponding method. > > Do you really need them? Perhaps, because they may be the more common idioms. And by having that function there a temporary complex object can be garbage collected and doesn't pollute the parent namespace. Is this a big deal? I don't know but it doesn't hurt. > If so, you're repeating yourself by definition. > That's not necessarily a problem, the stand-alone functions are just > wrappers of methods. You can decrease (but not eliminate) the amount of > repeated code with a factory function: > > def build_standalone(methodname, docstring=None): > def function(arg, arg2=None, globals=None, locals=None): > c = C() > return c.getattr(methodname)(arg, arg2, globals, locals) > function.__name__ = methodname > function.__doc__ = docstring > return function > > f1 = build_standalone('f1', "Docstring f1") > f2 = build_standalone('f2', "Docstring f2") > f3 = build_standalone('f3', "Docstring f3") Yes, this is better than the lambda. Thanks! > > There's no way to avoid the repeated f1 etc. > > But honestly, with only three such functions, I'd consider that overkill. > Yeah, I think so too. > >> Lest the above be too abstract, those who want to look at the full >> (and redundant) code: >> >> http://code.google.com/p/pydbg/source/browse/trunk/api/pydbg/api/ > debugger.py > > > You have parameters called Globals and Locals. It's the usual Python > convention that names starting with a leading uppercase letter is a > class. To avoid shadowing the built-ins, it would be more conventional to > write them as globals_ and locals_. You may or may not care about > following the convention :) Ok. Yes, some earlier code used globals_ and locals_. Thanks. > > I notice you have code like the following: > > if Globals is None: > import __main__ > Globals = __main__.__dict__ > > > I would have written that like: > > if Globals is None: > Globals = globals() Yes, that's better. Thanks. > > or even > > if Globals is None: > from __main__ import __dict__ as Globals > > You also have at least one unnecessary pass statement: > > if not isinstance(expr, types.CodeType): > expr = expr+'\n' > pass > > The pass isn't needed. > > > In your runcall() method, you say: > > res = None > self.start(start_opts) > try: > res = func(*args, **kwds) > except DebuggerQuit: > pass > finally: > self.stop() > return res > > This is probably better written as: > > self.start(start_opts) > try: > return func(*args, **kwds) > except DebuggerQuit: > return None > finally: > self.stop() See above for why I use pass. Thanks for the suggestions! > > > > > -- > Steven From google at mrabarnett.plus.com Mon Dec 15 11:24:45 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 15 Dec 2008 16:24:45 +0000 Subject: alt.possessive.its.has.no.apostrophe In-Reply-To: <4946826E.7060001@tim.thechases.com> References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> <49467CE2.3060401@holdenweb.com> <4946826E.7060001@tim.thechases.com> Message-ID: <494684CD.3@mrabarnett.plus.com> Tim Chase wrote: > Steve Holden wrote: >> This led to a schism between the British and the >> newly-independent Americans, who responded by taking the "u" >> out of colour, valour, and aluminium. > > Darn Americans and their alminim.... ;-) > > Next thing you know, they'll be putting an I in TEAM.[1] > > > > -tkc > > > [1] http://www.quotedb.com/quotes/2417 > But there is ME in TEAM. From R.Bauer at fz-juelich.de Thu Dec 18 09:04:49 2008 From: R.Bauer at fz-juelich.de (Reimar Bauer) Date: Thu, 18 Dec 2008 15:04:49 +0100 Subject: something else instead of PIL? In-Reply-To: <6df075c4-2397-4c41-9c75-64c59e7c0dd3@x16g2000prn.googlegroups.com> References: <6df075c4-2397-4c41-9c75-64c59e7c0dd3@x16g2000prn.googlegroups.com> Message-ID: imageguy schrieb: > On Dec 17, 3:48 pm, Reimar Bauer wrote: >> Hi >> >> what has happened to PIL? No updates since two years. >> >> Or does one know an alternative lib for resizing images? >> >> cheers >> Reimar > > I have found the FreeImage library with the Python bindings quite > workable. I work with multi-page TIF images and this seemed to be the > best option. > > The FreeImage library seems to be actively maintained too (Last > release in July 08 with updates to many of the image processing plug- > ins). The python bindings took me a bit to understand as they try to > emulate PIL, however they are implemented using ctypes, so you can > change/manage yourself if needed. I found working directly with the > functions exported from the .dll the best option and gave the best > performance. > > Freeimage site: http://freeimage.sourceforge.net/ > Python bindings: http://freeimagepy.sourceforge.net/ > > Hope that helps. Good luck. Working with images/graphics can make my > brain hurt sometimes. > > g. > > thanks! Reimar From philip at semanchuk.com Wed Dec 3 13:49:29 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Wed, 3 Dec 2008 13:49:29 -0500 Subject: Running a Python script from crontab In-Reply-To: References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> <126ba84a-0ea0-4a91-b7d2-89ed650e5d6c@d32g2000yqe.googlegroups.com> Message-ID: <6395AA2A-834B-4C5F-9EC9-BDD63E53E3DD@semanchuk.com> On Dec 3, 2008, at 1:33 PM, Astley Le Jasper wrote: > On 3 Dec, 16:41, Philip Semanchuk wrote: >> On Dec 3, 2008, at 10:29 AM, Astley Le Jasper wrote: >> >>> I've included a switch to include or exclude theloggingto console. >>> Whenloggingonly to file, the script runs fine. >> >>> Of course, I still don't understand whyduallogging, and specifically >>> to the console, causes a problem and if anyone has any comments >>> about >>> thedualoutputloggingcode above then I'd still be happy to hear >>> about it. >> >> Trying to write non-ASCII characters perchance? > > Errmmm ... that's kind of spoookey. I using UTF-8 encoding as I have a > lot of European language characters. But would that cause a problem > when running from crontab but not in the terminal? > > Go on then ... spill the beans. Oh, I don't know exactly. It's just what I thought of when you said that the problem occurs when logging to the console but not to files. I don't have a deep Unix background so I can't give you the details on what "the console" means to a cron job. In my experience, the environment in which a cron job runs is different from the environment in which some command line scripts run (remember my earlier suggestion about needing to explicitly set the PATH?) and so if the console for a cron job differed from the console that a Python program sees when run in a terminal, that would not surprise me. Hope it's a useful suggestion Philip From kpalamartchouk at gmail.com Fri Dec 19 08:21:06 2008 From: kpalamartchouk at gmail.com (kpalamartchouk at gmail.com) Date: Fri, 19 Dec 2008 05:21:06 -0800 (PST) Subject: Subclassing standard class: how to write my own __init__? Message-ID: <3fd1e6e7-112d-4ee3-a2ae-23f5d6d644f4@l33g2000pri.googlegroups.com> Dear All, I am trying to create a class that would extend functionality of datetime.date by implementing some functions I need, for example an optional initialisation by (year, day_of_year) instead of (year, month, day). I would like the class constructor to behave in the datetime's default way if there are no keyword arguments and do my own stuff if there are some. Here is the minimal example: ========================================= from datetime import date, timedelta class MyDateTime(date): def __init__(self, *arg, **kw): if len(kw): year = kw['year'] doy = kw['doy'] my_date = date(year=year, month=1, day=1) + timedelta (days=doy-1) date.__init__(self, year = my_date.year, month = my_date.month, day = my_date.day) else: date.__init__(self, *arg) date1 = MyDateTime(2008, 12, 19) date2 = MyDateTime(year=2008, doy=354) ========================================= It works fine when I don't supply any keyword arguments. But if I do, TypeError is happening: TypeError: function takes exactly 3 arguments (1 given) Could you help me to understand where I am wrong? Thanks From clp at rebertia.com Wed Dec 10 22:49:03 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 10 Dec 2008 19:49:03 -0800 Subject: Deeper tracebacks? In-Reply-To: <7e1c74f0-8f72-4a88-935b-90b77fe5aaa5@s37g2000vbp.googlegroups.com> References: <7e1c74f0-8f72-4a88-935b-90b77fe5aaa5@s37g2000vbp.googlegroups.com> Message-ID: <47c890dc0812101949qa793c72h26411d74a1ec0ea@mail.gmail.com> On Wed, Dec 10, 2008 at 3:50 PM, brooklineTom wrote: > On Dec 10, 5:03 pm, "Gabriel Genellina" > wrote: >> En Wed, 10 Dec 2008 16:59:16 -0200, brooklineTom >> escribi?: >> >> > I want my exception handler to report the method that originally >> > raised an exception, at the deepest level in the call-tree. Let give >> > an example. >> >> That's the default behavior, you don't have to do anything special. >> >> > import sys, traceback >> > class SomeClass: >> > def error(self): >> > """Raises an AttributeError exception.""" >> > int(3).zork() >> >> > def perform_(self, aSelector): >> > try: >> > aMethod = getattr(self, aSelector, None) >> > answer = apply(aMethod, [], {}) >> > except: AttributeError, anAttributeErrorException: >> > aRawStack = traceback.extract_stack() >> > answer = None >> >> (I assume you're using Python < 3.0) >> Use the 3-names form of the except statement: >> >> try: >> aMethod = getattr(self, aSelector, None) >> answer = aMethod() >> except AttributeError, e, tb: >> # the tb variable holds the traceback up to the error >> # the same thing you see printed by Python when >> # an unhandled error happens >> answer = None >> >> Alternatively, you can obtain the same thing with sys.exc_info()[2] >> Remember to delete any reference to the traceback object as soon as you're >> done with it; seehttp://docs.python.org/library/sys.html#sys.exc_info >> >> -- >> Gabriel Genellina > > I'm using Python 2.5. > > As I understand it, "aRawStack" (above) has the same information as > sys.exc_info()[2]. > > The deepest entry in aRawStack is the perform_ invocation. The > contents of the two bottom-most stack frames are: >>>> aRawStack[8][3] > "answer = anObject.perform_('error')" >>>> aRawStack[9][3] > 'aRawStack = traceback.extract_stack()' > > > By the time the handler is called, "zork" -- the method that was > called when the exception was raised, and "error", the method that > invoked zork, have already been removed from the stack. There is no zork() method, so it *can't have been called* and therefore *can't be in the traceback*. The error lies in the method that's trying to call a _nonexistent_ method, and that's where Python reports the error. Recall that: x.zork() is equivalent to: _z = x.zork #error occurs here, in the attribute lookup _z() #Python never gets here So no call takes place because you get an AttributeError before Python can get any further. zork() would only in the traceback if (1) it was looked up and called successfully [not the case here] and (2) an error occurred in zork()'s method body [again, not the case because it's not defined]. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From steve at REMOVE-THIS-cybersource.com.au Sat Dec 6 00:25:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Dec 2008 05:25:53 GMT Subject: Can't get exclusive file lock when safely renaming a file Message-ID: <014a049b$0$20670$c3e8da3@news.astraweb.com> I'm trying to safely rename a file without over-writing any existing files, and I've run into a problem with file locks. Here's a naive way of renaming without over-writing: import os oldname = "ham.txt" newname = "spam.txt" if not os.path.exists(newname): os.rename(oldname, newname) It's naive because there's a race-condition: if file newname is created by another process after the call to exists(), but before the call to rename(), then it will be over-written. Here's my current solution, based on advice given by people on this thread: http://mail.python.org/pipermail/python-list/2006-October/411432.html and this recipe: http://code.activestate.com/recipes/65203/ but it isn't working for me. import os, fcntl oldname = "ham.txt" newname = "spam.txt" def lock_destination(name): fileno = os.open(name, os.O_CREAT | os.O_EXCL) fcntl.flock(fileno, fcntl.LOCK_EX) # POSIX systems only return fileno # Create a test file to be renamed. f = open(oldname, 'w') f.write('this is my file\n') f.close() fileno = lock_destination(newname) # At this point, I can see "ham.txt" plus an empty file # "spam.txt" in my file browser os.rename(oldname, newname) The rename works, but here is my problem: after getting what I thought was an exclusive lock on the new file, but before calling os.rename(), I can still over-write it from another process: $ echo "this comes from another process" > spam.txt $ cat spam.txt this comes from another process This is despite running lock_destination("spam.txt"). What am I doing wrong? Before anyone asks, yes I have checked that the Python process and the shell process are in the same working directory, and therefore are writing to the same file: >>> os.read(fileno, 200) 'this comes from another process\n' I'm using Linux (Fedora). -- Steven From clp at rebertia.com Thu Dec 4 00:31:44 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 3 Dec 2008 21:31:44 -0800 Subject: How can I do this (from Perl) in Python? (closures) In-Reply-To: <68b8294c-8771-4b02-bd46-2f25f5e01602@j35g2000yqh.googlegroups.com> References: <68b8294c-8771-4b02-bd46-2f25f5e01602@j35g2000yqh.googlegroups.com> Message-ID: <47c890dc0812032131x497f51bek4388a20c3827ab1@mail.gmail.com> On Wed, Dec 3, 2008 at 9:18 PM, wrote: > I just came across http://www.perl.com/pub/a/2002/05/29/closure.html > and wanted to try the "canonical example of closures" in Python. I > came up with the following, but it fails: > > ####################### > #!/usr/bin/env python > Depending on your version of Python, you need to do either (A) or (B). (A) requires Python 3.0 IIRC. > def make_counter(start_num): > start = start_num (B) replace prev line with: start = [start_num] > def counter(): (A) add: nonlocal start > start += 1 (B) replace prev line with: start[0] += 1 > return counter > > from_ten = make_counter(10) > from_three = make_counter(3) > > print from_ten() # 10 > print from_ten() # 11 > print from_three() # 3 > print from_ten() # 12 > print from_three() # 4 > #################### > > The error message is: "UnboundLocalError: local variable 'start' > referenced before assignment". The same thing happens if I omit start > and just use start_num directly. See http://www.python.org/dev/peps/pep-3104/ for more info. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > How can I do it in Python? > -- > http://mail.python.org/mailman/listinfo/python-list > From joel.hedlund at gmail.com Wed Dec 17 08:17:28 2008 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Wed, 17 Dec 2008 14:17:28 +0100 Subject: weird dict problem, how can this even happen? In-Reply-To: <01584e96$0$20656$c3e8da3@news.astraweb.com> References: <01584e96$0$20656$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Tue, 16 Dec 2008 14:32:39 +0100, Joel Hedlund wrote: >> Duncan Booth wrote: >>> Alternatively give up on defining hash and __eq__ for FragmentInfo and >>> rely on object identity instead. >> Object identity wouldn't work so well for caching. Objects would always >> be drawn as they appeared for the first time. No updates would be shown >> until the objects were flushed from the cache. > > Perhaps I don't understand your program structure, but I don't see how > that follows. First off, please note that I consider my problem to be solved, many thanks to c.l.p and especially Duncan Booth. But of course continued discussion on this topic can be both enlightening and entertaining as long as people are interested. So here goes: I'm making a scientific program that visualizes data. It can be thought of as a freely zoomable map viewer with a configurable stack of data feature renderers, themselves also configurable to enhance different aspects of the individual features. As you zoom in, it becomes possible to render more types of features in a visually recognizable manner, so consequentially more feature renderers become enabled. The determining properties for the final image are then the coordinates and zoom level of the view, and the current renderer stack configuration. Rendering may be time consuming, so I cache the resulting bitmap fragments using a "key object" called FragmentInfo that holds this information. Some renderers may take a very long time to do their work, so in order to keep the gui nice and responsive, I interrupt the rendering chain at that point, put the remainder of the rendering chain in a job pool, and postpone finishing up the rendering until there are cpu cycles to spare. At that time, I go through the job pool and ask the cache which fragment was most recently accessed. This fragment is the most likely to actually be in the current view, and thus the most interesting for the user to have finallized. Now, when the user navigates the view to any given point, the gui asks the cache if the bitmap fragments necessary to tile up the current view have already been rendered, and if so, retrieves them straight from the cache and paints them to the screen. And that's why object identity wouldn't work. If the user changes something in the config for the current renderer stack (=mutates the objects), the renderers still retain the same object identities and therefore the old versions would be retrieved from the cache, and no updates would be shown until the fragments are flushed from the cache, and the fragment subsequently redrawn. I guess you could delve deep into the data members and pull out all their object identities and hash wrt that if you'd really want to, but I don't really see the point. The stupid cache implementation that I originally employed used a dict to store the FragmentInfo:BitmapFragment items plus a use tracker (list) on the side. This obviously doesn't work, because as soon as the renderer stack mutates, list and dict go out of sync and I can no longer selectively flush old items from the dict, because it's not readily apparent how to reconstruct the old keys. Purely using lists here is vastly superior because I can just .pop() the least recently used items from the tail and be done with them. Also for lists as small as this, the cost in performance is at most negligible. >> I've been experimenting with a list cache now and I can't say I'm >> noticing any change in performance for a cache of 100 items. > > 100 items isn't very big though. If you have 50,000 items you may notice > significant slow down :) > > If having many items in the cache is possible, you should consider using > a binary search instead of a linear search through the cache. See the > bisect module. Thanks for the tip, but I don't forsee this cache ever needing to be that big. ~100 is quite enough for keeping the gui reasonably responsive in this case. /Joel From rt8396 at gmail.com Sat Dec 6 12:08:10 2008 From: rt8396 at gmail.com (r) Date: Sat, 6 Dec 2008 09:08:10 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> <20081206133704.1bed455c@usenot.de> <4d1a952e-25ad-4b36-ba46-ed35758331b0@e1g2000pra.googlegroups.com> Message-ID: <50bbef6f-02e3-47d8-810c-179b89ccf62a@d32g2000yqe.googlegroups.com> Bad idea having two ways to do this. Pick one or the other! From steve at REMOVE-THIS-cybersource.com.au Thu Dec 18 20:48:59 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2008 01:48:59 GMT Subject: re.match() performance References: <755bd716-f5f6-4953-87a7-04ee148c3298@i18g2000prf.googlegroups.com> Message-ID: <015af4e5$0$20656$c3e8da3@news.astraweb.com> On Thu, 18 Dec 2008 05:51:33 -0800, Emanuele D'Arrigo wrote: > I've written the code below to test the differences in performance ... > ## TIMED FUNCTIONS > startTime = time.clock() > for i in range(0, numberOfRuns): > re.match(pattern, longMessage) > patternMatchingTime = time.clock() - startTime ... You probably don't need to re-invent the wheel. See the timeit module. In my opinion, the best idiom for timing small code snippets is: from timeit import Timer t = Timer("func(arg)", "from __main__ import func, arg") time_taken = min(t.repeat(number=N))/N where N will depend on how patient you are, but probably shouldn't be less than 100. For small enough code snippets, the default of 1000000 is recommended. For testing re.match, I didn't have enough patience for one million iterations, so I used ten thousand. My results were: >>> t1 = Timer("re.match(pattern, longMessage)", ... "from __main__ import pattern, re, compiledPattern, longMessage") >>> t2 = Timer("compiledPattern.match(longMessage)", ... "from __main__ import pattern, re, compiledPattern, longMessage") >>> t1.repeat(number=10000) [3.8806509971618652, 3.4309241771697998, 4.2391560077667236] >>> t2.repeat(number=10000) [3.5613579750061035, 2.725193977355957, 2.936690092086792] which were typical over a few runs. That suggests that even with no effort made to defeat caching, using pre-compiled patterns is approximately 20% faster than re.match(pattern). However, over 100,000 iterations that advantage falls to about 10%. Given that each run took about 30 seconds, I suspect that the results are being contaminated with some other factor, e.g. networking events or other processes running in the background. But whatever is going on, 10% or 20%, pre-compiled patterns are slightly faster even with caching -- assuming of course that you don't count the time taken to compile it in the first place. -- Steven From dickinsm at gmail.com Tue Dec 23 11:45:37 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 23 Dec 2008 08:45:37 -0800 (PST) Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> Message-ID: On Dec 23, 4:27?pm, ajaksu wrote: > Is "x ** 0 > 0." instead of "atan2(x, -1.) > 0." unreliable across > platforms? x**0 doesn't distinguish between x = -0.0 and x = 0.0. I suspect you're confusing -0.0**0.0 with (-0.0)**0.0. Mark From stefan_ml at behnel.de Fri Dec 19 12:07:50 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 19 Dec 2008 18:07:50 +0100 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <6r219cFfc8ovU1@mid.individual.net> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> Message-ID: <494bd4e6$0$31863$9b4e6d93@newsspool3.arcor-online.net> Thomas Heller wrote: > Mark Summerfield schrieb: >> Just a follow-up to say that the book has now been published in the >> U.S. >> It is now in stock at InformIT, and should reach other stores, e.g., >> Amazon, in a week or so. >> >> Also, the introduction, the first few pages of the first chapter, the >> whole of chapter 12 (regular expressions), and the index are now >> available for free download in a PDF from here: >> http://www.informit.com/store/product.aspx?isbn=0137129297 > > Question from a non-native english speaker: is this now valid english? > > "One of Python?s great strengths" > ^ > "and also teaches Python?s functional programming features" > ^ > "The book?s approach is wholly practical" > ^ 'Always' has been. It's not valid German, though, if that's what you are asking. Stefan From cmgui2 at gmail.com Wed Dec 10 18:39:01 2008 From: cmgui2 at gmail.com (cm_gui) Date: Wed, 10 Dec 2008 15:39:01 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <4b0f6c1a-9d3f-4fd7-8506-314d29ee87a8@k36g2000yqe.googlegroups.com> Message-ID: <7a1e6b94-1618-470c-a7ed-a2a5ada87d30@w24g2000prd.googlegroups.com> You guys are living in denial. Python is SLOW, especially for web apps. Instead of getting mad, why don't get together and come up with a faster VM/interpreter? The emperor doesn't like to be told he is not wearing any clothes? On 10 Dec, 14:48, Luis M. Gonz?lez wrote: > You are WRONG, WRONG, WRONG!! > And when I say Wrong, I mean WRONG!!! > > And I am not saying that you are confussed. > I say that you are WRONG! > > And when someone says so many times that you are wrong, it is because > you are WRONG! > And don't say that you are not wrong, because you are wrong! > > You are Wrong. Very Wrong. > > On Dec 10, 3:42?pm, cm_gui wrote: > > >http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-... > > > I fully agree with Krzysztof Kowalczyk . > > Can't they build a faster VM for Python since they love the language > > so much? > > > Python is SLOW. ? ?And I am not comparing it with compiled languages > > like C. > > Python is even slower than PHP! > > > Just go to any Python website and you will know. > > An example is:http://www2.ljworld.com/ > > And this site is created by the creators of Django! > > > And it is not just this Python site that is slow. There are many many > > Python sites which are very slow. And please don?t say that it could > > be the web hosting or the server which is slow ? because when so many > > Python sites are slower than PHP sites, it couldn?t be the web > > hosting. ? Also, Zope/Plone is even slower. > > > Python is slow. Very slow. > > From iofferkicks007 at gmail.com Mon Dec 22 00:04:26 2008 From: iofferkicks007 at gmail.com (iofferkicks007 at gmail.com) Date: Sun, 21 Dec 2008 21:04:26 -0800 (PST) Subject: www.iofferkicks.com china cheap wholesale nike shoes,air jordan shoes,air force one shoes. Message-ID: <48819351-fd60-48ea-add1-485c67e026df@a26g2000prf.googlegroups.com> Get Nike Shoes at Super Cheap Prices Discount Nike air jordans (www.iofferkicks.com) Discount Nike Air Max 90 Sneakers (www.iofferkicks.com) Discount Nike Air Max 91 Supplier (www.iofferkicks.com) Discount Nike Air Max 95 Shoes Supplier (www.iofferkicks.com) Discount Nike Air Max 97 Trainers (www.iofferkicks.com) Discount Nike Air Max 2003 Wholesale (www.iofferkicks.com) Discount Nike Air Max 2004 Shoes Wholesale (www.iofferkicks.com) Discount Nike Air Max 2005 Shop (www.iofferkicks.com) Discount Nike Air Max 2006 Shoes Shop (www.iofferkicks.com) Discount Nike Air Max 360 Catalogs (www.iofferkicks.com) Discount Nike Air Max Ltd Shoes Catalogs (www.iofferkicks.com) Discount Nike Air Max Tn Men's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 2 Women's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 3 Customize (www.iofferkicks.com) Discount Nike Air Max Tn 4 Shoes Customize ( www.iofferkicks.com) Discount Nike Air Max Tn 6 Supply (www.iofferkicks.com) Discount Nike Shox NZ Shoes Supply (www.iofferkicks.com) Discount Nike Shox OZ Sale (www.iofferkicks.com) Discount Nike Shox TL Store (www.iofferkicks.com) Discount Nike Shox TL 2 Shoes Store (www.iofferkicks.com) Discount Nike Shox TL 3 Distributor (www.iofferkicks.com) Discount Nike Shox Bmw Shoes Distributor (www.iofferkicks.com) Discount Nike Shox Elite Shoes Manufacturer (www.iofferkicks.com) Discount Nike Shox Monster Manufacturer (www.iofferkicks.com) Discount Nike Shox R4 Running Shoes (www.iofferkicks.com) Discount Nike Shox R5 Mens Shoes (www.iofferkicks.com) Discount Nike Shox Ride Womens Shoes (www.iofferkicks.com) Discount Nike Shox Rival Shoes Wholesaler (www.iofferkicks.com) Discount Nike Shox Energia Wholesaler (www.iofferkicks.com) Discount Nike Shox LV Sneaker (www.iofferkicks.com) Discount Nike Shox Turbo Suppliers (www.iofferkicks.com) Discount Nike Shox Classic Shoes Suppliers (www.iofferkicks.com) Discount Nike Shox Dendara Trainer (www.iofferkicks.com) Discount Nike Air Jordan 1 Seller (www.iofferkicks.com) Discount Nike Air Jordan 2 Shoes Seller (www.iofferkicks.com) Discount Nike Air Jordan 3 Collection (www.iofferkicks.com) Discount Nike Air Jordan 4 Shoes Collection (www.iofferkicks.com) Discount Nike Air Jordan 5 Chaussure Shoes (www.iofferkicks.com) Discount Nike Air Jordan 6 Catalog (www.iofferkicks.com) Discount Nike Air Jordan 7 Shoes Catalog (www.iofferkicks.com) Discount Nike Air Jordan 8 Customized (www.iofferkicks.com) Discount Nike Air Jordan 9 Shoes Customized (www.iofferkicks.com) Discount Nike Air Jordan 10 Wholesalers (www.iofferkicks.com) Discount Nike Jordan 11 Shoes Wholesalers (www.iofferkicks.com) Discount Nike Air Jordan 12 Factory (www.iofferkicks.com) Discount Nike Air Jordan 13 Shoes Factory (www.iofferkicks.com) Discount Nike Air Jordan 14 Shoes Sell (www.iofferkicks.com) Discount Nike Air Jordan 16 Exporter (www.iofferkicks.com) Discount Nike Air Jordan 17 Shoes Exporter (www.iofferkicks.com) Discount Nike Air Jordan 18 Offer (www.iofferkicks.com) Discount Nike Air Jordan 19 Shoes Offer (www.iofferkicks.com) Discount Nike Air Jordan 20 Manufacture (www.iofferkicks.com) Discount Nike Jordan 21 Shoes Manufacture (www.iofferkicks.com) EMAIL:IOFFERKICKS at GMAIL.COM MSN :IOFFERKICKS at MSN.COM From martin.hellwig at dcuktec.org Tue Dec 16 15:12:51 2008 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Tue, 16 Dec 2008 20:12:51 +0000 Subject: [ANN] EuroPython 2009 =?windows-1252?Q?=96_Call_for_Partic?= =?windows-1252?Q?ipation!_?= Message-ID: <49480BC3.9030002@dcuktec.org> On behalf of the EuroPython 2009 organisation it is my privilege and honour to announce the 'Call for Participation' for EuroPython 2009! EuroPython is the conference for the communities around Python, including the Django, Zope and Plone communities. This years conference will be held in Birmingham, UK from Monday 29th June to Saturday 4th July 2009. Talk & Themes Do you have something you wish to present at EuroPython? Go to http://www.europython.eu/talks/cfp/ for this years themes and submissions criteria, the deadline is on 5th April 2009. Other Talks, Activities and Events Have you got something which does not fit the above? Visit http://www.europython.eu/talks/ . Help Us Out We could use a hand any contribution is welcome, please take a look at http://www.europython.eu/contact/ . Sponsors An unique opportunity to affiliate with the prestigious EuroPython conference! http://www.europython.eu/sponsors/ Spread the Word Improve our publicity by distributing this announcement in your corner of the community, please coordinate this with the organizers: http://www.europython.eu/contact/ General Information For more information about the conference, please visit http://www.europython.eu/ Looking forward to see you! The EuroPython Team From jody.goldberg at gmail.com Wed Dec 10 06:06:46 2008 From: jody.goldberg at gmail.com (JodyGnumeric) Date: Wed, 10 Dec 2008 03:06:46 -0800 (PST) Subject: getting error...... Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in open_workbook biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) File "C:\Python25\Lib\site-pack References: <6c76b050-5b47-46f3-9097-5c58979b6913@s9g2000prg.googlegroups.com> <16d767d6-be4a-49eb-af5c-3d9e74b45458@m22g2000vbl.googlegroups.com> Message-ID: <17fce6e8-194b-4263-b322-0a8e074b3204@f33g2000vbf.googlegroups.com> On Dec 8, 9:02?pm, John Machin wrote: > On Dec 9, 12:19?pm, JodyGnumeric wrote: > > > > > On Dec 8, 5:54?am, John Machin wrote: > > > > On Dec 8, 6:48?pm, "Gabriel Genellina" wrote: > > > > > En Fri, 05 Dec 2008 02:31:01 -0200, pk sahoo ? > > > > escribi?: > > > > > > hallo everybody, > > > > > when i am running the following command > > > > > >>>> import xlrd > > > > >>>> book=xlrd.open_workbook("C:\\a.xls") > > > > > > i am getting the following error.. > > > > > > *Traceback (most recent call last): > > > > > ? File "", line 1, in > > > > > ? File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in > > > > > open_workb > > > > > ook > > > > > ? ? biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) > > > > > ? File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 1323, in > > > > > getbof > > > > > ? ? raise XLRDError('Expected BOF record; found 0x%04x' % opcode) > > > > > xlrd.biffh.XLRDError: Expected BOF record; found 0x3f3c* > > > > > Looks like your a.xls file is not an Excel file (one of the formats ? > > > > supported by xlrd). > > > > As 0x3f3c corresponds to the characters ' > > > This can be verified easily by opening the file with a simple-minded > > > text editor (e.g. Notepad) ... if the first two lines are > > > """ > > > > > > > > > """ > > > then it's an Excel 2003 XML Spreadsheet that's been manually(?) > > > renamed from .xml to .xls. > > > > The current xlrd release supports only the binary ("BIFF") format .xls > > > files created by Excel 3.0 to Excel 2003. The next release (due out > > > Real Soon Now) will support Excel 2.1 and 2.0 formats [don't ask]. > > > Very soon after that will come support for Excel 2007 .xlsx which is a > > > bunch of XML files inside a ZIP file. Support for Excel 2003 > > > "SpreadsheetML" is way down the to-do list. > > > > If the OP wants to be able to read the file with xlrd: > > > (1) Open it with Excel 200[37] and save as a .xls file > > > or (2) rename it to .xml, start OpenOffice.org Calc, click on File, > > > click on Open, click on "Files of type", choose "Microsoft Excel 2003 > > > XML (*.xml)" from the (long, unsorted) drop-down list, ..., and save > > > as etc etc. Gnumeric is not an option. > > > > HTH, > > > John > > > Gnumeric can read this format. 'MS Excel (tm) 2003 SpreadsheetML' > > [Gnumeric 1.9.1 on Windows XP] > > I'm sorry; I thought I'd exhausted every possible way of trying to > open it. After looking at the file open dialogue box again, I've > spotted the "Advanced" button. Here is what you need to do: > > Have the file named whatever.xls. Click on File / Open , navigate to > correct directory, click on Advanced, choose 'MS Excel (tm) 2003 > SpreadsheetML' from the File-type drop-down list, choose the file, > click on OK. Anything else (Simple (non-Advanced), naming it > whatever.xml, ...) produces no response, yes that's zero bits of > information, not even a Bzzzzt! noise :-( > > *AND* when it does open up, a date cell defined by > ? > ... > ss:Type="DateTime">1999-12-31T00:00:00.000 > > is displayed as "00ort 31at1999" :-( Please send the file to bugzilla.gnome.org it sounds like I need to improve the probe function function for this format and add support for the magic named formats. From mensanator at aol.com Tue Dec 30 21:05:53 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 30 Dec 2008 18:05:53 -0800 (PST) Subject: TypeError: list indices must be integers References: <2e5a61c0-fa99-4170-81ca-eb3a10859400@k36g2000pri.googlegroups.com> Message-ID: <67a3debb-ae30-47d9-ab7b-35040cde730c@q26g2000prq.googlegroups.com> On Dec 30, 7:46?pm, dubux wrote: > here is a function i wrote that doesnt work. i wrote to parse a "news" > file that is going to work in conjunction with a website via mod_wsgi. > my head hurts from looking at it so long. please help! i will further > explain in the post. > > def news(x,y): > ? ? ? ? # usage news(date, number) > ? ? ? ? # x = date/news > ? ? ? ? # y = number > ? ? ? ? news_file = '/home/scam/Desktop/www/info/news' > ? ? ? ? news = open(news_file, 'r') > ? ? ? ? news_list = news.readlines() > ? ? ? ? news.close() > ? ? ? ? if x == 'date': > ? ? ? ? ? ? ? ? mylist = map(lambda i: news_list[i], filter(lambda i: i%2 == 0, range > (len(news_list)))) > ? ? ? ? ? ? ? ? date = mylist[y] > ? ? ? ? ? ? ? ? return '
    %s

    ' % (date) > ? ? ? ? if x == 'news': > ? ? ? ? ? ? ? ? mylist = map(lambda i: news_list[i], filter(lambda i: i%2 == 1, range > (len(news_list)))) > ? ? ? ? ? ? ? ? news = mylist[y] > ? ? ? ? ? ? ? ? return '%s
    ' % (news) > ? ? ? ? else: > ? ? ? ? ? ? ? ? return news_list > > and call it with the follow syntax: news('[date/news]', [any number]) > > i keep getting "TypeError: list indices must be integers" on the > following line "date = mylist[y]" > can someone please explain this and give me the proper way to achieve > what im trying to do? The code you posted assumes y is an integer. The TypeError message shows that assumption is false. Nothing in this code will help you resolve the problem, it's in the code that calls this code. Throw a print type(y),y into tha start of the definition. From jpablo.romero at gmail.com Wed Dec 10 22:02:31 2008 From: jpablo.romero at gmail.com (=?ISO-8859-1?Q?Juan_Pablo_Romero_M=E9ndez?=) Date: Wed, 10 Dec 2008 21:02:31 -0600 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: In R: norm = function(v) v/sqrt(sum(v^2)) :) Juan Pablo 2008/12/10 Arnaud Delobelle : > "Dotan Cohen" writes: > >> 2008/12/10 : >>> On Dec 5, 9:51 am, Xah Lee wrote: >>>> >>>> For those of you who don't know linear algebra but knows coding, this >>>> means, we want a function whose input is a list of 3 elements say >>>> {x,y,z}, and output is also a list of 3 elements, say {a,b,c}, with >>>> the condition that >>>> >>>> a = x/Sqrt[x^2+y^2+z^2] >>>> b = y/Sqrt[x^2+y^2+z^2] >>>> c = z/Sqrt[x^2+y^2+z^2] >>> >>>> >>>> In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, >>>> you'll have 50 or hundreds lines. >>> >>> Ruby: >>> >>> def norm a >>> s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) >>> a.map{|x| x/s} >>> end >> >> If someone doesn't counter with a Python one-liner then I'm going to >> port that to brainfuck. > > def unit(v): > return map((sum(map(lambda x:x*x, v))**0.5).__rdiv__, v) > > The hard bit was to make it less readable than the Ruby version ;) > > -- > Arnaud > -- > http://mail.python.org/mailman/listinfo/python-list > From clp at rebertia.com Mon Dec 29 20:32:08 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 29 Dec 2008 17:32:08 -0800 Subject: Python in C In-Reply-To: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> References: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> Message-ID: <47c890dc0812291732p34ab7710u5b98b30eb926113c@mail.gmail.com> On Mon, Dec 29, 2008 at 5:22 PM, wrote: > 2. Have there been any suggestions in the past to rewrite Python's > mainstream implementation in C++ (or why wasn't it done this way from > the beginning)? I'm not a CPython dev (I bet one will pipe in), but I would speculate it's because C++ is so much more complicated and a bit less portable than C. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From rt8396 at gmail.com Mon Dec 22 14:50:29 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 11:50:29 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <6ra8t0F925rU1@mid.individual.net> Message-ID: <29feda0d-6432-4cb9-8809-e4d4a7798601@e1g2000pra.googlegroups.com> OK je.s.t... whatever, We see where you stand. And also see that by removing your comments from the archive in 5 days, how small your acorns really are. From gnewsg at gmail.com Tue Dec 16 12:45:42 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Tue, 16 Dec 2008 09:45:42 -0800 (PST) Subject: Free place to host python files? References: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> <32599660-2393-4e18-8c48-05d64bccbbc1@t26g2000prh.googlegroups.com> Message-ID: On 16 Dic, 15:56, feba wrote: > On Dec 16, 8:29?am, s... at pobox.com wrote: > > > ? ? feba> I'm getting started in python, and it would be helpful to have a > > ? ? feba> place to put up various code snippets I've made, so I don't have > > ? ? feba> to send them individually to each person I want to show it to. > > ? ? feba> I'd prefer to use something that would give me a directory for my > > ? ? feba> use only, instead of something where you can only upload one at a > > ? ? feba> time. ?I'd especially like to avoid stuff that uses CAPTCHAs > > ? ? feba> and/or forced waiting periods. > > >http://pastebin.com/? > > > -- > > Skip Montanaro - s... at pobox.com -http://smontanaro.dyndns.org/ > > well, ignoring the fact that pastebin doesn't work for me for some > reason, I'm talking about hosting it as a .py downloadable, not a hunk > of text. code.google.com? It also has a SVN repository. --- Giampaolo http://code.google.com/p/pyftpdlib/ From sjmachin at lexicon.net Wed Dec 31 09:56:33 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 31 Dec 2008 06:56:33 -0800 (PST) Subject: Parsing Excel spreadsheets References: <6a54de23-bea4-40c7-ad7c-22c6eba4bd8a@z6g2000pre.googlegroups.com> Message-ID: On Dec 31 2008, 4:02?pm, brooklineTom wrote: > andyh... at gmail.com wrote: > > Hi, > > > Can anybody recommend an approach for loading and parsing Excel > > spreadsheets in Python. Any well known/recommended libraries for this? > > > The only thing I found in a brief search washttp://www.lexicon.net/sjmachin/xlrd.htm, > > but I'd rather get some more input before going with something I don't > > know. > > > Thanks, > > Andy. > > I save the spreadsheets (in Excel) in xml format. Which means that you need to be on a Windows box with a licensed copy of Excel. I presume you talking about using Excel 2003 and saving as "XML Spreadsheet (*.xml)". Do you save the files manually, or using a COM script? What is the largest xls file that you've saved as xml, how big was the xml file, and how long did it take to parse the xml file? Do you extract formatting information or just cell contents? > I started with the > standard xml tools (xml.dom and xml.dom.minidom). I built a > pullparser, and then just crack them. The MS format is tedious and > overly complex (like all MS stuff), but straightforward. What do you think of the xml spat out by Excel 2007's (default) xlsx format? > Once I've > cracked them into their component parts (headers, rows, cells, etc), > then I walk through them doing whatever I want. > > I found this material to be no worse than doing similar crud with > xhtml. I know there are various python packages around that do it, but > I found the learning curve of those packages to be steeper than just > grokking the spreadsheet structure itself. I'm curious to know which are the "various python packages" with the so steep learning curves, and what the steep bits were. Cheers, John From robert.kern at gmail.com Mon Dec 8 13:54:31 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 08 Dec 2008 12:54:31 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> Message-ID: Rhamphoryncus wrote: > On Dec 7, 4:20 pm, Steven D'Aprano cybersource.com.au> wrote: >> On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: >>> Rasmus Fogh wrote: >>>> Current behaviour is both inconsistent and counterintuitive, as these >>>> examples show. >>>>>>> x = float('NaN') >>>>>>> x == x >>>> False >>> Blame IEEE for that one. Rich comparisons have nothing to do with that >>> one. >> There is nothing to blame them for. This is the correct behaviour. NaNs >> should *not* compare equal to themselves, that's mathematically >> incoherent. > > Mathematically, NaNs shouldn't be comparable at all. They should > raise an exception when compared. In fact, they should raise an > exception when *created*. But that's not what we want. What we want > is a dummy value that silently plods through our calculations. For a > dummy value it seems a lot more sense to pick an arbitrary yet > consistent sort order (I suggest just above -Inf), rather than quietly > screwing up the sort. Well, there are explicitly two kinds of NaNs: signalling NaNs and quiet NaNs, to accommodate both requirements. Additionally, there is significant flexibility in trapping the signals. > Regarding the mythical IEEE 754, although it's extremely rare to find > quotations, I have one on just this subject. And it does NOT say "x > == NaN gives false". It says it gives *unordered*. It is C and > probably most other languages that turn that into false (as they want > a dummy value, not an error.) > > http://groups.google.ca/group/sci.math.num-analysis/browse_thread/thread/ead0392e646b7cc0/a5bc354cd46f2c49?lnk=st&q=why+does+NaN+not+equal+itself%3F&rnum=3&hl=en&pli=1 Table 4 on page 9 of the standard is pretty clear on the subject. When the two operands are unordered, the operator == returns False. The standard defines how to do comparisons notionally; two operands can be "greater than", "less than", "equal" or "unordered". It then goes on to map these notional concepts to programming language boolean predicates. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From joe at strout.net Fri Dec 19 10:20:07 2008 From: joe at strout.net (Joe Strout) Date: Fri, 19 Dec 2008 08:20:07 -0700 Subject: encoding problem In-Reply-To: <6r1m72Ffb5kpU3@mid.uni-berlin.de> References: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> <6r1m72Ffb5kpU3@mid.uni-berlin.de> Message-ID: <494BBBA7.9000109@strout.net> Marc 'BlackJack' Rintsch wrote: >> The question is why the Python interpreter use the default encoding >> instead of "utf-8", which I explicitly declared in the source. > > Because the declaration is only for decoding unicode literals in that > very source file. And because strings in Python, unlike in (say) REALbasic, do not know their encoding -- they're just a string of bytes. If they were a string of bytes PLUS an encoding, then every string would know what it is, and things like conversion to another encoding, or concatenation of two strings that may differ in encoding, could be handled automatically. I consider this one of the great shortcomings of Python, but it's mostly just a temporary inconvenience -- the world is moving to Unicode, and with Python 3, we won't have to worry about it so much. Best, - Joe From matt.dubins at sympatico.ca Thu Dec 25 13:22:15 2008 From: matt.dubins at sympatico.ca (Matthew Dubins) Date: Thu, 25 Dec 2008 13:22:15 -0500 Subject: Exec inside a class method to call other class methods? Message-ID: <4953CF57.8080905@sympatico.ca> Hello all, I have made a python script to upload contact information from an excel worksheet to an online database. One part of the program that really tripped me up was when I wanted to call specific class methods that I had made to deal with specific types of contact information (Parent's name, Child's name, Phone #, etc). My first thought was to make it easy using the exec statement. The code (a method within a class) looked like this: ---------- def parse(self, data, data_type) exec "self.__parse_%s(data)" % data_type ---------- The data_type variable contains strings that exactly match the spellings of the 2nd word in the titles of the class methods that I wanted to call for each data_type inputted into the parse function. For some reason, *it didn't work*. Alternately, I found the ugly code shown below to be functional. As you can see, for each data_type, I call the corresponding class method that I've specified. Please help me to transform my ugly functional code into concise functional code. :) Thanks, Matthew ---------- def parse(self, data, data_type): if data_type == 'nocall': self.__parse_nocall(data) elif data_type == 'DOB': self.__parse_DOB(data) elif data_type == 'gender': self.__parse_gender(data) elif data_type == 'Prematurity': self.__parse_Prematurity(data) elif data_type == 'email': self.__parse_email(data) elif data_type == 'languages': self.__parse_languages(data) elif data_type == 'phone': self.__parse_phone(data) elif data_type == 'cname': self.__parse_cname(data) elif data_type == 'pname': self.__parse_pname(data) elif data_type == 'address': self.__parse_address(data) elif data_type == 'duedate': self.__parse_dudedate(data) From rdmurray at bitdance.com Tue Dec 16 11:29:36 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Tue, 16 Dec 2008 16:29:36 +0000 (UTC) Subject: Generator slower than iterator? References: Message-ID: Quoth Lie Ryan : > On Tue, 16 Dec 2008 12:07:14 -0300, Federico Moreira wrote: > > > Hi all, > > > > Im parsing a 4.1GB apache log to have stats about how many times an ip > > request something from the server. > > > > The first design of the algorithm was > > > > for line in fileinput.input(sys.argv[1:]): > > ip = line.split()[0] > > if match_counter.has_key(ip): > > match_counter[ip] += 1 > > else: > > match_counter[ip] = 1 > > nitpick: > dict.has_key is usually replaced with > if ip in match_counter: ... I'd say it's just slightly more than a nitpick nowadays: since Python 3.0 does not support has_key, it's time to get used to not using it :) --RDM From steven at REMOVE.THIS.cybersource.com.au Mon Dec 22 20:48:28 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 23 Dec 2008 01:48:28 GMT Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> <1iscu14.oixxplpgajabN%pdorange@pas-de-pub-merci.mac.com> Message-ID: On Mon, 22 Dec 2008 14:51:32 +0100, Pierre-Alain Dorange wrote: > I'm new to python and here i discover at least 4 methods, i just make a > small script for timing those methods (100 000 times each on a set of 10 > values). > I do not use timeit, i can't make it work easyly as it need a standalone > env for each test. But that's just what timeit does: it creates a standalone environment for each test. > ---- the test script -------------------- #!/usr/bin/env python > > from math import atan2 > import time > > > def sign_0(x): > if x==0.0: > return 0.0 > elif x>0.0: > return 1.0 > else: > return -1.0 > > def sign_1(x): > if x > 0 or (x == 0 and atan2(x, -1.) > 0.): > return 1 > else: > return -1 > > def sign_2(x): > return cmp(x, 0) > > sign_3 = lambda x:+(x > 0) or -(x < 0) > > def main(): > candidates=[1.1,0.0,-0.0,-1.2,2.4,5.6,-8.2,74.1,-23.4,7945.481] > > startTime = time.clock() time.clock() is low resolution on non-Windows systems. If you are using Windows, this is okay, if you are not, you are shooting yourself in the foot. > for i in range(100000): > for value in candidates: Horribly inaccurate, because you are including the time to build a range of 100,000 integers. In Python 3, that will only be a little bit inaccurate, but in Python 2.x that will have a MAJOR effect -- possibly swamping the actual function you are calling. > s=sign_0(value) > print "sign_0 : ",time.clock() - startTime You are (possibly) including the time taken to print to std out in your time. > startTime = time.clock() > for i in range(100000): > for value in candidates: > s=sign_1(value) > print "sign_1 : ",time.clock() - startTime Repeated code is poor coding practice. Write a function that takes a function as argument, and call that: def timer(function, candidates, count=100000): loop = [None]*count startTime = time.clock() for i in loop: for value in candidates: s = function(value) return time.clock() - startTime But this is just duplicating what timeit already does. Trust me, learn to use it, you won't be sorry. Here's a trick that took me a long time to learn: instead of copying your functions into the setup code of timeit, you can just import them. This is what I would do (untested): candidates=[1.1,0.0,-0.0,-1.2,2.4,5.6,-8.2,74.1,-23.4,7945.481] setup = "from __main__ import sign_%d, candidates" from timeit import Timer template = "for x in candidates: s = sign_%d(x)" for i in range(4): t = min( Timer(template % i, setup % i).repeat() ) print "Testing sign_%d:" % i, t, "seconds" > ---- conclusions ------------------------------- None of your conclusions are safe until you have re-tested with a better timing method. That doesn't mean you are wrong, only that your reasons for believing them are weak. -- Steven From nick at craig-wood.com Wed Dec 3 05:30:50 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 03 Dec 2008 04:30:50 -0600 Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> <258cf433-f6c9-43e7-a235-f5f6b2b6433f@j39g2000yqn.googlegroups.com> <33b4cc2f-2311-491c-a2e6-9cc5452b1a6b@g38g2000yqd.googlegroups.com> Message-ID: Slaunger wrote: > Just wanted to show the end result in its actual implementation! > > I ended up *not* making a decorator, as I already had a good idea > about how to do it > using __getattr__ > > class PayloadDualFrqIQOnDemand(PayloadDualFrqIQ): > """ > This class has the same interface as its parent, > but unlike its parent, it is instantiated without > its payload parsed up in its instance attributes > Q1, I1, Q2 and I2. Instead it stores a reference to > the file object in which the Payload data can be > read, the file position and > the version of the payload data. > > On accessing one of the data attributes, the actual > payload data are read from the file, and the reference to > the file object is unbound. > The constructor signature is therefore different from its > parent as it takes the file object, position and version > as arguments instead of the actual data. > """ > > @classmethod > def _unpack_from_file(cls, f, samples, ver): > bytes = samples * cls.bytes_per_sample > initial_pos = f.tell() > f.seek(initial_pos + bytes) #Skip over the payload > return cls(f, initial_pos, samples, ver) > > @classmethod > def unpack_from_ver3_file(cls, f, samples): > return cls._unpack_from_file(f, samples, ver=3) > > @classmethod > def unpack_from_ver4_file(cls, f, samples): > return cls._unpack_from_file(f, samples, ver=4) > > data_attr_names = frozenset(["Q1", "I1", "Q2", "I2"]) > > def __init__(self, a_file, a_file_position, samples, a_version): > """ > Returns an instance where the object knows where to > look for the payload but it will only be loaded on the > first attempt to read one of the data attributes > in a "normal" PayloadDualFrqIQ object. > """ > self.f = a_file > self.file_position = a_file_position > self.samples = samples > self.ver = a_version > > def __getattr__(self, attr_name): > """ > Checks if a request to read a non-existing data attribute > has an attribute corresponding to one of the data attributes > in a normal PayloadDualFrqIQ object. > > If true, the data attributes are created and bound to the > object using the file object instance, the file position > and the version. > > It is a prerequisite that the file object is still open. > The function leaves the file object at the file position > when it entered the method > > """ > cls = self.__class__ > if attr_name in cls.data_attr_names: self.data_attr_names should do instead of cls.data_attr_names unless you are overriding it in the instance (which you don't appear to be). > initial_pos = self.f.tell() > try: > bytes = self.samples * cls.bytes_per_sample > self.f.seek(self.file_position) > buf = self.f.read(bytes) > if self.ver == 3: > bytes_to_data = cls._v3_byte_str_to_data > elif self.ver == 4: > bytes_to_data = cls._v4_byte_str_to_data > else: > raise TermaNotImplemented, \ > "Support for ver. %d not implemented." % > self.ver > I1, Q1, I2, Q2 = bytes_to_data(buf) > self.__dict__["I1"] = I1 > self.__dict__["Q1"] = Q1 > self.__dict__["I2"] = I2 > self.__dict__["Q2"] = Q2 > return self.__dict__[attr_name] I think you want setattr() here - __dict__ is an implemetation detail - classes with __slots__ for instance don't have a __dict__. I'd probably do this for k, v in zip(("I1", "Q1", "I2", "Q2"), bytes_to_data(buf)): setattr(self, k, v) return object.__getattr__(self, attr_name) That then has duplicated a list of "I1", "Q1" etc which needs to be factored out. > finally: > # Restore file position > self.f.seek(initial_pos) > # Unbind lazy attributes > del self.f > del self.ver > del self.file_position > del self.samples > > This seems to work out well. No infinite loops in __getattr__! :-) I would probably factor out the contents of the if statement into a seperate method, but that is a matter of taste! > At least it passes the unit test cases I have come up with so far. > > No guarantees though, as I may simply not have been smart enough to > bring forth unit test cases which make it crash. > > Comments on the code is still appreciated though. Looks fine! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From fakeaddress at nowhere.org Thu Dec 4 12:56:31 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 04 Dec 2008 09:56:31 -0800 Subject: python an sqlite objects In-Reply-To: References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <18742.47391.389709.119341@montanaro-dyndns-org.local> Message-ID: Gerhard H?ring wrote: > Be sure to save it as BLOB, not TEXT. > > Suppose you have serialized your object as Python bytestring. > > serialized = ... > ... .execute("insert into mytable(mycolumn) values (?)", > (sqlite3.Binary(serialized),)) > > This way you will get a BLOB in the form of a Python buffer object when > you later select it from the database [...] Good advice for now, with Python 2.X. Python 3 resolves most of confusion with its distinction between the string type and the bytes types. The 3.x standard library sqlite3 module understands the 'bytes' and 'bytearray' types, and treats them appropriately. Here's a runnable Python 3 demo: # Ensure that we're running Python 3 or later. import sys assert int(sys.version.split()[0].split('.')[0]) >= 3 # If there's a better way to chek, please tell. # sqlite3 became part of the standard library as of Python 2.5. import sqlite3 # Create an in-memory database and one table. db = sqlite3.connect(':memory:') db.execute('CREATE TABLE demo (num INTEGER, txt TEXT, bin BLOB)') # Create a bytes object containing every possible byte value. input_blob = bytes(range(256)) # Demo the bytes object. assert len(input_blob) == 256 for i in range(256): assert input_blob[i] == i # Insert a test record. # The input blob goes into both a TEXT field and a BLOB field db.execute('INSERT INTO demo (num, txt, bin) VALUES (?, ?, ?)', (42537, input_blob, input_blob)) # Fetch back the one and only record. cursor = db.execute('SELECT num, txt, bin FROM demo') num, txt, blob = cursor.fetchone() # Verify that we got back what we stored. assert num == 42537 assert type(txt) == type(blob) == bytes assert txt == blob == input_blob If we change the input type from 'bytes' to 'bytearray', the demo still works in that the value selected back from the database is of type bytes. The database understands that the value is binary and not unicode, and he retrieved value is still the immutable bytes type, not bytearray. Why doesn't the column's declared type, 'TEXT' versus 'BLOB', matter? sqlite is type-loose, which its author considers a valuable feature and some us consider a defect. sqlite does not generally require that the value stored in a field (column) be of the field's declared type. When an inserted value's type does not match the field's declared type, most other database systems will try to convert the given object to the field's declared type. sqlite3 is different; it will try to make an exception to the field's declared type and store the object as the type with which it came in. -- --Bryan From robert.kern at gmail.com Mon Dec 8 00:04:08 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 07 Dec 2008 23:04:08 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: References: <014c593e$0$20670$c3e8da3@news.astraweb.com> Message-ID: James Stroud wrote: > Robert Kern wrote: >> James Stroud wrote: >>> I'm missing how a.all() solves the problem Rasmus describes, namely >>> that the order of a python *list* affects the results of containment >>> tests by numpy.array. E.g. "y in ll1" and "y in ll2" evaluate to >>> different results in his example. It still seems like a bug in numpy >>> to me, even if too much other stuff is broken if you fix it (in which >>> case it apparently becomes an "issue"). >> >> It's an issue, if anything, not a bug. There is no consistent >> implementation of bool(some_array) that works in all cases. numpy's >> predecessor Numeric used to implement this as returning True if at >> least one element was non-zero. This works well for bool(x!=y) (which >> is equivalent to (x!=y).any()) but does not work well for bool(x==y) >> (which should be (x==y).all()), but many people got confused and >> thought that bool(x==y) worked. When we made numpy, we decided to >> explicitly not allow bool(some_array) so that people will not write >> buggy code like this again. >> >> The deficiency is in the feature of rich comparisons, not numpy's >> implementation of it. __eq__() is allowed to return non-booleans; >> however, there are some parts of Python's implementation like >> list.__contains__() that still expect the return value of __eq__() to >> be meaningfully cast to a boolean. >> > > You have explained > > py> 112 = [1, y] > py> y in 112 > Traceback (most recent call last): > File "", line 1, in > ValueError: The truth value of an array with more than one element is... > > but not > > py> ll1 = [y,1] > py> y in ll1 > True > > It's this discrepancy that seems like a bug, not that a ValueError is > raised in the former case, which is perfectly reasonable to me. Nothing to do with numpy. list.__contains__() checks for identity with "is" before it goes to __eq__(). -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From stephen at thorne.id.au Fri Dec 12 17:38:21 2008 From: stephen at thorne.id.au (Stephen Thorne) Date: Sat, 13 Dec 2008 08:38:21 +1000 Subject: How do I manually uninstall setuptools (installed by egg)? In-Reply-To: References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> <47c890dc0812091904p12e75510sbe0b8858eb2f6d9e@mail.gmail.com> Message-ID: <20081212223821.GA4635@thorne.id.au> On 2008-12-12, Nick Craig-Wood wrote: > Failing that I'll use bdist_rpm then alien to convert to a deb which > works well enough I find. Ages ago there was a bdist_deb that was in the python bug tracker, long since that bug tracker has been transitioned to another one, and that attachment was lost. Another pythoneer still had it a few years later, and I got it from him. In an effort to help people create real packages from python software, rpms and debs, I put together a small program to download source from pypi and convert it into an OS installable package. This is known to work on some redhat systems (modulo a problem with the redhat macro for doing python byte compilation automatically on all packages), and debian based systems. You can find the work I did on: https://launchpad.net/packaging http://pypi.python.org/pypi/packaging And more importantly, you can find bdist_deb.py here: http://bazaar.launchpad.net/~jerub/packaging/trunk/annotate/11?file_id=bdist_deb.py-20080507003948-5c5mn3f68meq60hs-1 -- Regards, Stephen Thorne Development Engineer NetBox Blue - 1300 737 060 Scanned by the NetBox from NetBox Blue (http://netboxblue.com/) Can you afford to be without a NetBox? Find out the real cost of internet abuse with our ROI calculator. http://netboxblue.com/roi Scanned by the NetBox from NetBox Blue (http://netboxblue.com/) From manu3d at gmail.com Mon Dec 1 10:43:44 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Mon, 1 Dec 2008 07:43:44 -0800 (PST) Subject: Two attributes! Why? References: <76bc5df8-26fd-4e2d-a134-c5d13ea3b39a@n10g2000yqm.googlegroups.com> <0140c948$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Nov 29, 5:21?am, Steven D'Aprano wrote: > This is a side-effect of name-mangling. Double-underscore names are only > mangled when they are referred to directly as attributes, not when they > are passed to setattr, getattr etc. Those functions don't do any name > mangling. Ah! That make sense! Thank you! It's a bit of an obscure thing right now. I don't see mention of it in the description of the setattr/getattr built-ins: http://docs.python.org/library/functions.html Wouldn't be good to have a hint of the issue there? Manu From martin at marcher.name Fri Dec 26 20:29:39 2008 From: martin at marcher.name (Martin) Date: Sat, 27 Dec 2008 02:29:39 +0100 Subject: multiply each element of a list by a number In-Reply-To: References: Message-ID: <5fa6c12e0812261729t7a689799m92a17aa9d8204d22@mail.gmail.com> you might also want to look into the map(elem), and filter(elem) builtins >>> def multby3(elem): ... return elem * 3 ... >>> map(multby3, (1, 2, 3, )) [3, 6, 9] >>> help(map) >>> def even(elem): ... return not elem % 2 ... >>> filter(even, (1, 2, 3, )) (2,) >>> help(filter) KeyboardInterrupt >>> map(multby3, filter(even, (1, 2, 3, ))) [6] >>> hth martin 2008/12/27 Scott David Daniels : > Tim Chase wrote: >>> >>> What does *not* work is 3 * [0,1,2] >>> As you know, this gives >>> [0,1,2,0,1,2,0,1,2] >>> What I am hoping for is >>> [0,3,6] -- http://soup.alt.delete.co.at http://www.xing.com/profile/Martin_Marcher http://www.linkedin.com/in/martinmarcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From aahz at pythoncraft.com Sun Dec 7 15:09:23 2008 From: aahz at pythoncraft.com (Aahz) Date: 7 Dec 2008 12:09:23 -0800 Subject: [OT] [sort of] Malcom Reynolds? References: <20081207210016.751a33c9@usenot.de> Message-ID: In article <20081207210016.751a33c9 at usenot.de>, Andreas Waldenburger wrote: > >Just found this in the re module's docs: > > m = re.match(r"(?P\w+) (?P\w+)", "Malcom > Reynolds") > >Does this represent an attempt to phase out the gratuitous Monty Python >references in favor of gratuitous Firefly references? Because if so, >I'm all for it. Ask Georg Brandl: http://svn.python.org/view/python/trunk/Doc/library/re.rst?rev=67553&view=log -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From steve at REMOVE-THIS-cybersource.com.au Tue Dec 2 06:06:08 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Dec 2008 11:06:08 GMT Subject: optimization References: <6672532a-f162-4717-b0bb-c613214b57db@d32g2000yqe.googlegroups.com> Message-ID: <01450e77$0$20670$c3e8da3@news.astraweb.com> On Mon, 01 Dec 2008 19:06:24 -0600, Robert Kern wrote: > As Neal has observed, there is a performance hit for creating functions > inside of another function. True, but it's not a big hit, and I believe it is constant time regardless of the size of the function. The inner function has been (mostly) pre-compiled into bits, and assembling the bits is quite fast. On my desktop, I measure the cost of assembling the inner function to be around the same as two function lookups and calls. >>> def outer(): ... def inner(): ... return None ... return inner() ... >>> def ginner(): ... return None ... >>> def gouter(): ... return ginner() ... >>> from timeit import Timer >>> t1 = Timer('outer()', 'from __main__ import outer') >>> t2 = Timer('gouter()', 'from __main__ import gouter, ginner') >>> t1.repeat() [1.782930850982666, 0.96469783782958984, 0.96496009826660156] >>> t2.repeat() [1.362678050994873, 0.77759003639221191, 0.58583498001098633] Not very expensive. > Every time you go through the outer > function, you are creating new function objects for all of the inner > functions. That's how you can get lexical scoping. It is not equivalent > to defining the functions all at the top-level, where all of the > function objects are created at once. The compiler can't optimize that > overhead away because the overhead arises from implementing a real > feature. But the time it takes to parse the function and compile it to code is optimized away. >>> outer.func_code.co_consts (None, ", line 2>) Which makes me wonder, is there anything we can do with that code object from Python code? I can disassemble it: >>> import dis >>> dis.dis(outer.func_code.co_consts[1]) 3 0 LOAD_CONST 0 (None) 3 RETURN_VALUE Anything else? -- Steven From gandalf at shopzeus.com Tue Dec 30 08:42:32 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 30 Dec 2008 14:42:32 +0100 Subject: select.select and socket.setblocking Message-ID: <495A2548.8010007@shopzeus.com> I'm using this method to read from a socket: def read_data(self,size): """Read data from connection until a given size.""" res = "" fd = self.socket.fileno() while not self.stop_requested.isSet(): remaining = size - len(res) if remaining<=0: break # Give one second for an incoming connection so we can stop the # server in seconds when needed ready = select.select([fd], [], [], 1) if fd in ready[0]: data = self.socket.recv(min(remaining,8192)) # 8192 is recommended by socket.socket manual. if not data: # select returns the fd but there is no data to read -> connection closed! raise TransportError("Connection closed.") else: res += data else: pass if self.stop_requested.isSet(): raise SystemExit(0) return res This works: if I close the socket on the other side, then I see this in the traceback: File "/usr/home/gandalf/Python/Projects/OrbToy/orb/endpoint.py", line 233, in read_data raise TransportError("Connection closed.") TransportError: Connection closed. Also when I call stop_requested.set() then the thread stops within one seconds. Then I switch to non blocking mode, my code works exactly the same way, or at least I see no difference. I have read the socket programming howto ( http://docs.python.org/howto/sockets.html#sockets ) but it does not explain how a blocking socket + select is different from a non blocking socket + select. Is there any difference? Thanks From greg at cosc.canterbury.ac.nz Tue Dec 9 01:59:10 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 09 Dec 2008 19:59:10 +1300 Subject: Guido's new method definition idea In-Reply-To: <79139d04-bd26-4f36-b8c9-19554e7d4e95@e18g2000yqo.googlegroups.com> References: <014a071a$0$20670$c3e8da3@news.astraweb.com> <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> <79139d04-bd26-4f36-b8c9-19554e7d4e95@e18g2000yqo.googlegroups.com> Message-ID: <6q6j50Fau4iiU1@mid.individual.net> anthony.tolle at gmail.com wrote: > On another related note, I would be interested in seeing this syntax > adopted for a different purpose... > > class C: > def createfunc(self): > def self.func(arg): > return arg + 1 I agree -- this would be a much better use of the syntax, and I'd like to see this possibility left open. -- Greg From bertilow at gmail.com Sat Dec 6 09:01:29 2008 From: bertilow at gmail.com (Bertilo Wennergren) Date: Sat, 06 Dec 2008 23:01:29 +0900 Subject: Learning Python now coming from Perl In-Reply-To: References: Message-ID: Roy Smith wrote: > Bertilo Wennergren wrote: >> I'm planning to start learning Python now, using Python 3000. >> I have no previous Python skills, but I now Perl pretty well. >> I'm also well experienced with JavaScript. >> >> Any pointers and tips how I should go about getting into >> Python? > I assume you use Perl to solve real problems in whatever job you do. My > recommendation would be the next time some problem comes up that you would > normally solve with Perl, try doing it in Python. Having a real task that > you need to accomplish is a great way to focus the mind. For your first > project, pick something that's small enough that you think you could tackle > it in under 50 lines of Perl. Good advice. > One of the very first things you'll probably discover that's different > between Perl and Python is how they handle string pattern matching. In > Perl, it's a built in part of the language syntax. In Python, you use the > re module. The regular expressions themselves are the same, but the > mechanism you use to apply them to input text is quite different. Thanks. I don't suppose there is any introductory material out there that is based on Python 3000 and that is also geared at people with a Perl background? Too early for that I guess.. -- Bertilo Wennergren From press.saltmarch at gmail.com Thu Dec 4 06:45:45 2008 From: press.saltmarch at gmail.com (Shaguf) Date: Thu, 4 Dec 2008 03:45:45 -0800 (PST) Subject: Microsoft MVP Donald Belcham to Speak on Visual Studio, C# vNext, Aspect Oriented Programming, Live Mesh Message-ID: <99b9f43a-f583-4c94-a823-b17a1910f0be@y1g2000pra.googlegroups.com> Microsoft MVP Donald Belcham to Speak on Visual Studio, C# vNext, Aspect Oriented Programming, Live Mesh Bangalore, December 1, 2008: When writing Microsoft technology-related applications to have strong separations of concerns you inevitably run across some items that, while appearing as separate concerns, do not behave in the same manner as the other concerns. Instead of interacting only with their immediate neighbors, these concerns can interact with some or all of the concerns within the application. Donald Belcham is coming back this summer to India's biggest summit for the developer ecosystem - Great Indian Developer Summit ( http://www.developersummit.com ) to explore crosscutting concerns, how you can use Aspect Oriented Programming to maintain good separation of concerns in your code without losing the crosscutting functionality you also require. Microsoft MVP Donald will also conduct an early discussion of the impending changes in the upcoming version of Visual Studio and the C# language, and how they will affect your every day development work. On April 25, Donald will conduct a 3 hour workshop about Live Mesh for creating Software as a Service (SaaS) applications -- he will detail the architecture of Live Mesh (from the developer's standpoint), how to code to interact with the framework and what possibilities there may be for application in mainstream business software. The President of the Edmonton .NET User Group will also explore the problems encountered during the life of a project -- technical, social and management related. A battle hardened team lead who has survived trench warfare, Donald will explore the problems, solutions tried, successes and failures (there were many) that occurred along the way to help you get your project to near-utopian levels. About Great Indian Developer Summit Great Indian Developer Summit, produced by Saltmarch Media (http:// www.saltmarch.com/) is the biggest gathering of software developers from Java/J2EE, Microsoft computing technologies, Rich Internet Applications (RIA), Web 2.0, Ajax, Agile, SOA, and Enterprise IT. For both veterans and newcomers to the world of .NET, Java, and the Rich Web, the Great Indian Developer Summit provides participants with a well-balanced learning experience that guaranteed they went back with a richer understanding of the technologies that make a difference to their careers. See the GIDS 2008 Red Stripe Report: http://www.developersummit.com/2008/report/pdf/Red_Stripe_Report-GIDS08.zip Over 3000 qualified and talented delegates - Source, attended GIDS 2008: The Hindu - Monday, 26 May 2008 (http://www.developersummit.com/ 2008/report/postPress.html). With outstanding educational sessions, powerhouse speakers, a high-profile award ceremony, GIDS 2009 will feature premium knowledge, action plans and advise from been-there- done-it veterans, creators, and visionaries. For further information on GIDS 2009, please visit the summit on the web http://www.developersummit.com/. A Saltmarch Media Press Release E: info at saltmarch.com Ph: +91 80 4005 1000 From Scott.Daniels at Acm.Org Sat Dec 27 17:12:29 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 27 Dec 2008 14:12:29 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: Daniel Fetchinson wrote: > I'm trying to write an extension module in C which contains a single > function with the following prototype: > void func( int N, int * arg1, int * arg2, int * ret ); > Here arg1 and arg2 are length N arrays, and the function computes ret > which is also an N length array. From python I'd like to call this > function as > ret = func( [ 1, 2, 3 ], [ 2, 3, 4] ) This requirement pretty much dictates the slow answer you have. > Does this mean that I can only pass the arrays from python to C as > generic python objects and in a later operation I need to get the > elements from this generic python object, construct a C array and pass > that to the C function? ... What's the simplest way of doing this? Either use ctypes, look into array.array, or look into numpy.array. I'd just use numpy, myself: import numpy total = numpy.array([1, 2, 3]) + numpy.array([2, 3, 4]) --Scott David Daniels Scott.Daniels at Acm.Org From bj_666 at gmx.net Mon Dec 15 16:35:05 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 15 Dec 2008 21:35:05 GMT Subject: How can I return a non-zero status result from a python script? References: <74b53da4-bf07-431b-898b-49977f7a685c@r36g2000prf.googlegroups.com> Message-ID: <6qo0s9Fda9rhU2@mid.uni-berlin.de> On Mon, 15 Dec 2008 13:12:08 -0800, silverburgh.meryl at gmail.com wrote: > How can I return a non-zero status result from the script? Just do a > return 1? at the end? ``sys.exit(42)`` Ciao, Marc 'BlackJack' Rintsch From joe at strout.net Tue Dec 16 15:25:17 2008 From: joe at strout.net (Joe Strout) Date: Tue, 16 Dec 2008 13:25:17 -0700 Subject: How to modify a program while it's running? Message-ID: Here's my situation: I'm making an AIM bot, but the AIM server will get annoyed if you log in too frequently (and then lock you out for a while). So my usual build-a-little, test-a-little methodology doesn't work too well. So I'd like to restructure my app so that it can stay running and stay logged in, yet I can still update and reload at least most of the code. But I'm not sure what's the best way to do this. Should I move the reloadable code into its own module, and then when I give my bot a "reload" command, have it call reload on that module? Will that work, and is there a better way? Thanks, - Joe From sln at netherlands.com Tue Dec 9 21:09:00 2008 From: sln at netherlands.com (sln at netherlands.com) Date: Wed, 10 Dec 2008 02:09:00 GMT Subject: Mathematica 7 compares to other languages References: <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <4ridneQnkLrPkKDUnZ2dnUVZ8qbinZ2d@posted.plusnet> <986b6ea1-efba-4146-9704-5f9e3787c26a@a37g2000pre.googlegroups.com> Message-ID: On Tue, 9 Dec 2008 15:19:47 -0800 (PST), Xah Lee wrote: >On Dec 8, 4:07 am, Jon Harrop wrote: >> s... at netherlands.com wrote: >> > Well, its past 'tonight' and 6 hours to go till past 'tomorrow'. >> > Where the hell is it Zah Zah? >> >> Note that this program takes several days to compute in Mathematica (even >> though it takes under four seconds in other languages) so don't expect to >> see a genuinely optimized version any time soon... ;-) > >Note that Jon's Mathematica code is of very poor quality, as i've >given detailed analysis here: > >? A Mathematica Optimization Problem > http://xahlee.org/UnixResource_dir/writ/Mathematica_optimization.html > >I'm not sure he's intentionally making Mathematica look bad or just >sloppiness. I presume it is sloppiness, since the Mathematica code is >not shown in his public website on this speed comparison issue. (as >far as i know) I suppose, he initialled tried this draft version, saw >that it is too slow for comparsion, and probably among other reason he >didn't include it in the speed comparison. However, in this thread >about Mathematica 7, he wanted to insert his random gribe to pave >roads to post his website books and url on OCml/f#, so he took out >this piece of Mathematica to bad mouth it and bait. He ignored my >paypal challenge, but it so happens that someone else paid me $20 to >show a better code, and in the showdown, Jon went defensive that just >make him looking like a major idiot. > > Xah >? http://xahlee.org/ > >? Ad hominem From gagsl-py2 at yahoo.com.ar Wed Dec 24 13:48:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2008 16:48:06 -0200 Subject: Iterating over objects of a class References: <2df27de3-7fa3-4ac9-acd9-f946939517cf@r37g2000prr.googlegroups.com> <6rfb7iF1fg5rU1@mid.uni-berlin.de> <7f47994f-13b6-45c4-920a-83aa72282bec@i20g2000prf.googlegroups.com> Message-ID: En Wed, 24 Dec 2008 16:18:55 -0200, Kottiyath escribi?: >> The other thing to remember is that because the 'registry' contains >> references to the instances, they won't be garbage collected. > > Is there any other way out in this case? > I have factory methods - and I have to loop over them - sort of Chain > of Responsibility pattern. > Having a registry inside the class instance and looping through them > was the only clean thing I could think of. > I understand that garbage collection would be an issue - but is there > any way out? You may keep all that structures - just use weak references (see the weakref module). There isn't a WeakList nor WeakSet out-of-the-box but you may use a WeakKeyDictionary (set the value to anything, None by example). -- Gabriel Genellina From jelsas at gmail.com Wed Dec 10 11:45:44 2008 From: jelsas at gmail.com (jelsas) Date: Wed, 10 Dec 2008 08:45:44 -0800 (PST) Subject: Maintaining signature in help(decorated function) References: <48f2fd47-1fc3-4b2f-ad39-24adce7e9a5c@k36g2000yqe.googlegroups.com> <941d9581-6165-4513-b172-a1d6295285d3@b38g2000prf.googlegroups.com> Message-ID: <7859eb26-3ba8-4630-9d0d-ac39b2962180@i20g2000prf.googlegroups.com> Thanks! This is exactly what I needed. From lie.1296 at gmail.com Tue Dec 30 08:24:18 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 30 Dec 2008 13:24:18 +0000 (UTC) Subject: string in files References: <62075511-08ad-405a-a3af-2da8d2f22c50@v39g2000pro.googlegroups.com> Message-ID: On Tue, 30 Dec 2008 11:53:17 +0100, Glauco wrote: >> thanks brother >> i mean how do i particularly assign (u = this) >> (y = is).... >> in the strings up there. i have been able to split strings with any >> character sign. >> >> > > If i'm not wrong this is simple with RE: > Using Regular Expression for this is an overkill, you'd better use the str.split: longstring = 'this is a python string' splitted_string = longstring.split() result = ', '.join(splitted_string[:-1]) + ' and ' + splitted_string[-1] From steven at REMOVE.THIS.cybersource.com.au Mon Dec 8 23:00:21 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 09 Dec 2008 04:00:21 GMT Subject: RuntimeError: dictionary changed size during iteration References: <274eb282-1635-40ca-95af-b82271c57802@v4g2000yqa.googlegroups.com> Message-ID: On Mon, 08 Dec 2008 19:10:00 -0800, Robert Dailey wrote: > On Dec 8, 6:26?pm, Terry Reedy wrote: >> Robert Dailey wrote: >> > stuff = vars() >> >> ?>>> vars() is globals() >> True >> >> > for key in stuff: >> >> You just changed globals, which is aliased as stuff. Stuff changes. >> >> > ? ? print( key, '--', stuff[key] ) >> >> > I get the following error message: >> > ('CopyEmotionFX', '--', ) >> > Traceback (most recent call last): >> > ? File "C:\IT\work\jewett\depends.py", line 12, in >> > ? ? for key in stuff: >> > RuntimeError: dictionary changed size during iteration >> >> > Why is this happening? >> >> >> > How am I changing globals()? I'm simply iterating the keys in the dict. > Can someone explain what is going on please? You create an new name "key": for key in stuff I suppose you could do this: key = None stuff = vars() for key in stuff: but even better would be: for key in vars().copy(): because that protects you from cases where globals() change inside the for loop. -- Steven From sjmachin at lexicon.net Wed Dec 17 10:23:40 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 17 Dec 2008 07:23:40 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> <0d9ea7cc-b5fb-4edb-be32-490aae9e7204@b41g2000pra.googlegroups.com> <0de3a7bf-a4c4-4103-a4e0-44313405fa94@z28g2000prd.googlegroups.com> Message-ID: On Dec 18, 1:28?am, aka wrote: > Hi John, thanks. > You're right, I didn't past the method header because I thought it > didn't matter when the input filename is hardcoded. > The try/except isn't very helpful indeed so I commented it out. > You're right I wrongly referred to the UnicodeReader > class in my first post because that's ultimately where I want to go > so > I outcommented it here for you to see. > The fact is that neither csv.reader nor the UnicodeReader will read > the file, while writing with the UnicodeWriter > works like a charm. > That's why I put str() around roles to see any content. > I simplified the csv-file by cutting off columns without result. The > file looks now like: > > id;company;department > 12;Cadillac;Research > 11;Ford;Accounting > 10;Chrysler;Sales > > The dictionary on the return is because this code is part of my > TurboGears application. > The entire method is: > > import csv > from utilities.urw ? ? ? import UnicodeWriter, UnicodeReader Pardon my ignorance, but what is "utilities.urw"?? > > ? ? @expose(allow_json=True) Means what? Does what? Does the problem still happen without that? Funny, the indentation changed there --- for the very last time, is that the actual code of a standalone script that reproduces the problem? > ? ? def import_roles(self, input=None, *args, **kwargs): > ? ? ? ? inp = 'C:/temp/test.csv' > ? ? ? ? roles = [] > ? ? ? ? msg = '' > ? ? ? ? ## try: > ? ? ? ? fp = open(inp, 'rb') > ? ? ? ? reader = csv.reader(fp, dialect='excel', delimiter=';') > ? ? ? ? ## reader = UnicodeReader(fp, dialect='excel', delimiter=';') > ? ? ? ? for r in reader: > ? ? ? ? ? ? roles.append(r[0]) > ? ? ? ? fp.close() > ? ? ? ? ## except: > ? ? ? ? ? ? ## msg = "Something's wrong with the csv.reader" > ? ? ? ? return dict(filepath=inp, > ? ? ? ? ? ? ? ? ? ? roles=str(roles), > ? ? ? ? ? ? ? ? ? ? msg=msg) > > csv.reader results in: for r in reader: Error: line contains NULL > byte Looks like the file is stuffed. Have you tried inspecting it with a tool that would actually show a '\x00' or a '\xff' unambiguously? If you don't have a fancy one, use the Python interactive prompt: open('your_file.csv', 'rb').read() > > Use of UnicodeReader results in: UnicodeDecodeError: 'utf8' codec > can't decode byte 0xff in position 0: unexpected code byte > > Will post only complete code from now on thanks. Just make sure it's runnable and it's what you actually ran thanks. From hsoft at hardcoded.net Sat Dec 6 18:01:39 2008 From: hsoft at hardcoded.net (Virgil Dupras) Date: Sun, 7 Dec 2008 00:01:39 +0100 Subject: [Python-Dev] "as" keyword woes In-Reply-To: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> Message-ID: <1BA80D7C-44A6-4DE0-AC43-A99B50DF3F5E@hardcoded.net> On 06 Dec 2008, at 20:38, Warren DeLano wrote: > >> Date: Fri, 05 Dec 2008 22:22:38 -0800 >> From: Dennis Lee Bieber >> Subject: Re: "as" keyword woes >> To: python-list at python.org >> Message-ID: >> >> I'm still in the dark as to what type of data could >> even inspire the >> use of "as" as an object name... A collection of "a" objects? In >> which >> case, what are the "a"s? > > Please let me clarify. It is not "as" as a standalone object that we > specifically miss in 2.6/3, but rather, the ability to use ".as" > used as > a method or attribute name. > > In other words we have lost the ability to refer to "as" as the > generalized OOP-compliant/syntax-independent method name for casting: > > new_object = old_object.as(class_hint) > > # For example: > > float_obj = int_obj.as("float") > > # or > > float_obj = int_obj.as(float_class) > > # as opposed to something like > > float_obj = int_obj.asFloat() > > # which requires a separate method for each cast, or > > float_obj = (float)int_obj > > # which required syntax-dependent casting [language-based rather than > object-based]. > > Of course, use of explicit casting syntax "(float)" is fine if you're > restricting yourself to Python and other languages which support > casting, but that solution is unavailable inside of a pure OOP > message-passing paradigm where object.method(argument) invocations are > all you have to work with. > > Please note that use of object.asClassname(...) is a ubiqitous > convention for casting objects to specific classes (seen in > ObjectiveC, > Java, SmallTalk, etc.). > > There, I assert that 'object.as(class_reference)' is the simplest and > most elegant generalization of this widely-used convention. Indeed, > it > is the only obvious concise answer, if you are limited to using > methods > for casting. > > Although there are other valid domain-specific uses for "as" as > either a > local variable or attribute names (e.g. systematic naming: as, bs, > cs), > those aren't nearly as important compared to "as" being available as > the > name of a generalized casting method -- one that is now strictly > denied > to users of Python 2.6 and 3. > > As someone somewhat knowledgable of how parsers work, I do not > understand why a method/attribute name "object_name.as(...)" must > necessarily conflict with a standalone keyword " as ". It seems to me > that it should be possible to unambiguously separate the two without > ambiguity or undue complication of the parser. > > So, assuming I now wish to propose a corrective PEP to remedy this > situation for Python 3.1 and beyond, what is the best way to get > started > on such a proposal? > > Cheers, > Warren > As long as "as" is widely known as a keyword, I don't see the problem. Every python developer knows that the convention is to add a trailing underscore when you want to use a reserved word in your code. Besides, your examples are quite abstract. I'm sure it's possible to find good examples for "while", "with", "import", "from" (I often use "from_") or "try" as well. Or perhaps that the python keywords should be "as_" so we leave "as" free for eventual methods? As for the implicit proposition of allowing keywords only for methods, I agree with Guido about it being a slippery slope. So we would end up with a language where it is allowed to name methods after keywords, but not functions (they can be declared in the local scope)? Yikes! Oh well, maybe it's possible for an intelligent parser to distinguish between keywords and function references, but think of the poor grammar highlighters in all source editors! What a nightmare it will be for them. Anyway, is there any language that does this, allowing keywords as method names? I don't know, but if not, there's probably a reason for it. Your views on code elegance are also rather Javaish. I'd go for "class_reference(object)" (and why the heck would you "be limited to using method for casting"?). Ciao, Virgil From roy at panix.com Tue Dec 9 19:58:18 2008 From: roy at panix.com (Roy Smith) Date: Tue, 09 Dec 2008 19:58:18 -0500 Subject: How to initialize a class variable once References: <493E5700.4030107@aim.com> Message-ID: In article , Joe Strout wrote: > On Dec 9, 2008, at 4:31 AM, Brian Allen Vanderburg II wrote: > > > There is one situation where a module can be imported/executed > > twice, if it is the __main__ module. > Anyway, thanks for pointing this out; I bet it's the root cause of the > OP's observation. Wow, good diagnosis! This was happening in a test framework (using unittest). I had a class which had a @staticmethod factory function, and a class member dict where __init__() registered every instance of the class that got created. Something was going wrong, so in my test code (i.e. in __main__), I imported the module directly and printed the dict. Lo and behold, it was empty! As far as I could tell, class Foo: _map = {} was getting executed again, which made no sense. I even went as far as printing out id(Foo) in both places to make sure I really had the same class (I did). Thanks for the help. I never would have figured this out on my own. From gagsl-py2 at yahoo.com.ar Mon Dec 8 02:48:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Dec 2008 05:48:53 -0200 Subject: getting error...... Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in open_workbook biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) File "C:\Python25\Lib\site-pack References: Message-ID: En Fri, 05 Dec 2008 02:31:01 -0200, pk sahoo escribi?: > hallo everybody, > when i am running the following command > >>>> import xlrd >>>> book=xlrd.open_workbook("C:\\a.xls") > > i am getting the following error.. > > > *Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in > open_workb > ook > biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) > File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 1323, in > getbof > raise XLRDError('Expected BOF record; found 0x%04x' % opcode) > xlrd.biffh.XLRDError: Expected BOF record; found 0x3f3c* Looks like your a.xls file is not an Excel file (one of the formats supported by xlrd). As 0x3f3c corresponds to the characters ' Message-ID: <20081230205725.20272.1180724368.divmod.quotient.29340@ohm> On Tue, 30 Dec 2008 15:55:51 -0500, Jean-Paul Calderone wrote: >On Tue, 30 Dec 2008 14:41:17 -0600, Grant Edwards wrote: >>On 2008-12-30, Francesco Bochicchio wrote: >>>3. AFAIK (sorry, I feel acronym-ly today ;), there is no difference in >>>select between blocking and non-blocking mode. The difference is in the >>>recv (again, assuming that you use TCP as protocol, that is AF_INET, >>>SOCK_STREAM), which in the blocking case would wait to receive all the >>>bytes that you requested, >> >>No, in blocking mode it will wait to receive _some_ data (1 or >>more bytes). The "requested" amount is strictly an upper >>limit: recv won't return more than the requested number of >>bytes, but it might return less. > >Hi Grant, > >I don't think you read Francesco's message carefully enough. :) Ah, no, it was I who didn't read carefully enough. Nevermind. Jean-Paul From ken.faulkner at gmail.com Mon Dec 1 17:38:16 2008 From: ken.faulkner at gmail.com (Ken Faulkner) Date: Tue, 2 Dec 2008 09:38:16 +1100 Subject: pydoc enforcement. In-Reply-To: <1228147384.32081.5.camel@aalcdl07.lib.unc.edu> References: <6ccec696-a8bb-4818-a016-642514677b70@b38g2000prf.googlegroups.com> <1228147384.32081.5.camel@aalcdl07.lib.unc.edu> Message-ID: <8542922d0812011438g529b8806l29e185896274609e@mail.gmail.com> Hi Yeah, I was thinking about something at commit time for a VCS... catch is, soo many VCS's out there. And I wasn't thinking of the default action throwing compile errors, but would only do that if a particular flag was given. Still, just an idea. I'm just finding more and more public modules/API's/libraries that have so little documentation that it really does force reading a LOT of the source to figure out whats going on. Sure, a lot of the time thats required, but some modules are just painful.. oh well... was just a thought. Ken On Tue, Dec 2, 2008 at 3:03 AM, J. Cliff Dyer wrote: > > On Sun, 2008-11-30 at 16:27 -0800, ken.faulkner at gmail.com wrote: > > I've been thinking about implementing (although no idea yet *HOW*) the > > following features/extension for the python compile stage and would be > > interested in any thoughts/comments/flames etc. > > > > Basically I'm interested adding a check to see if: > > 1) pydoc's are written for every function/method. > > 2) There are entries for each parameter, defined by some > > predetermined syntax. > > > > My idea is that as much as I love dynamic typing, there are times when > > using some modules/API's that have less than stellar documentation. I > > was thinking that if it was possible to enable some switch that > > basically forced compilation to fail if certain documentation criteria > > weren't met. > > > > Yes, it should be up to developers to provide documentation in the > > first place. Or, the client developer might need to read the source > > (IF its available)... but having some "forced" documentation might at > > least ease the problem a little. > > > > For example (half borrowing from Javadoc). > > > > class Foo( object ): > > > > def bar( self, ui ): > > pass > > > > > > Would fail, since the bar method has an "unknown" parameter called > > "ui". > > What I think could be interesting is that the compiler forces some > > documentation such as: > > > > class Foo( object ): > > > > def bar( self, ui ): > > """ > > @Param: ui : blah blah blah. > > """ > > pass > > > > > > The compiler could check for @Param matching each parameter passed to > > the method/function. Sure, a lot of people might just not put a > > description in, so we'd be no better off. But at least its getting > > them *that* far, maybe it would encourage them to actually fill in > > details. > > > > Now ofcourse, in statically typed language, they might have the > > description as "Instance of UIClass" or something like that. For > > Python, maybe just a description of "Instance of abstract class UI" or > > "List of Dictionaries"... or whatever. Sure, precise class names > > mightn't be mentioned (since we mightn't know what is being used > > then), but having *some* description would certainly be helpful (I > > feel). > > > > Even if no-one else is interested in this feature, I think it could > > help my own development (and would be an interested "first change" > > into Python itself). > > > > Apart from bagging the idea, does anyone have a suggestion on where in > > the Python source I would start for implementing such an idea? > > > > Thanks > > > > Ken > > For the reasons already stated, I think it's probably a bad idea to > enforce this at compile time. I think it's a great idea to make sure > that this information is present in all your code, but unless you want > to see useless stubs, the correct time to enforce this is at commit > time. Don't accept any improperly documented patches. > > Syntax is not enough to ensure what you want to ensure. The semantics > have to be right as well. > > Cheers, > Cliff > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ken at seehart.com Mon Dec 15 03:38:57 2008 From: ken at seehart.com (Ken Seehart) Date: Mon, 15 Dec 2008 00:38:57 -0800 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: <494617A1.2000103@seehart.com> -*?* Admittedly a tough call. I see the attraction of the proposed syntax. Maybe somewhat more readable since the declaration syntax matches the usage syntax, which is nice. I think it would have been superior to the current syntax if it had been done that way in the first place. However, since newbies will still have to learn both syntaxes in order to read other peoples code, it does not simplify the language. The main thing I don't like about it is that it violates this principle: "There should be one-- and preferably only one --obvious way to do it." Ken Daniel Fetchinson wrote: > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html > > The proposal is to allow this: > > class C: > def self.method( arg ): > self.value = arg > return self.value > > instead of this: > > class C: > def method( self, arg ): > self.value = arg > return self.value > > I.e. explicit self stays only the syntax is slightly different and may > seem attractive to some. As pointed out by Guido classmethods would > work similarly: > > class C: > @classmethod > def cls.method( arg ): > cls.val = arg > return cls.val > > The fact that Guido says, > > "Now, I'm not saying that I like this better than the status quo. But > I like it a lot better than [...] but it has the great advantage that > it is backward compatible, and can be evolved into a PEP with a > reference implementation without too much effort." > > shows that the proposal is viable. > > I'd like this new way of defining methods, what do you guys think? > Anyone ready for writing a PEP? > > Cheers, > Daniel > > From MrJean1 at gmail.com Thu Dec 4 17:31:48 2008 From: MrJean1 at gmail.com (MrJean1) Date: Thu, 4 Dec 2008 14:31:48 -0800 (PST) Subject: simplest way to strip a comment from the end of a line? References: Message-ID: <641d1179-e9f4-4963-9b00-52467551a205@p2g2000prf.googlegroups.com> Using rsplit('#', 1) works for lines *with* comments: >>> 'this is a test'.rsplit('#', 1) ['this is a test'] >>> 'this is a test #with a comment'.rsplit('#', 1) ['this is a test ', 'with a comment'] >>> "this is a '#gnarlier' test #with a comment".rsplit('#', 1) ["this is a '#gnarlier' test ", 'with a comment'] But not if # occurs in lines without comments: >>> "this is a '#gnarlier' test".rsplit('#', 1) ["this is a '", "gnarlier' test"] /Jean Brouwers On Dec 4, 7:50?am, Joe Strout wrote: > I have lines in a config file which can end with a comment (delimited ? > by # as in Python), but which may also contain string literals ? > (delimited by double quotes). ?A comment delimiter within a string ? > literal doesn't count. ?Is there any easy way to strip off such a ? > comment, or do I need to use a loop to find each # and then count the ? > quotation marks to its left? > > Thanks, > - Joe From steve at REMOVE-THIS-cybersource.com.au Sun Dec 14 02:41:55 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Dec 2008 07:41:55 GMT Subject: Optimizing methods away or not? Message-ID: <0154b041$0$6988$c3e8da3@news.astraweb.com> I have a class with a method meant to verify internal program logic (not data supplied by the caller). Because it is time-consuming but optional, I treat it as a complex assertion statement, and optimize it away if __debug__ is false: class Parrot: def __init__(self, *args): print "Initialising instance..." if __debug__: self.verify() # check internal program state, not args if __debug__: def verify(self): print "Verifying..." If I run Python normally, I can do this: >>> p = Parrot() Initialising instance... Verifying... >>> p.verify() Verifying... and if I run Python with the -O flag, I get this: >>> p = Parrot() Initialising instance... >>> p.verify() Traceback (most recent call last): File "", line 1, in AttributeError: Parrot instance has no attribute 'verify' This is the behaviour I want, but I haven't seen it before in other code. What do people think? Is it a good idea or a bad? If you think it is a bad idea to have verify disappear under optimization, would you change your mind if it were called __verify instead? One possible alternative is to do something like this: class Parrot: def __init__(self, *args): print "Initialising instance..." if __debug__: self.verify() def verify(self): if __debug__: print "Verifying..." return None # this is optional else: warnings.warn("verify() is a null op") which now means that Parrot instances will always have a verify method, even if it does nothing. I'm not sure I like that. What do others think? Which do you consider better design? -- Steven From Ron.Barak at lsi.com Mon Dec 22 04:47:02 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Mon, 22 Dec 2008 09:47:02 +0000 Subject: Basic misunderstanding of generators Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6024944BB@enbmail01.lsi.com> Hi All, I want to use generators to print lines taken from a gzipped file. I've never used generators, so probably my problem is basic misunderstanding of generators. In the below program, I expected the last line ("print line_") to print the first line of the sac.log.gz file. Instead, I get: Could you tell me what I'm doing wrong (or point me to a URL that could set me straight) ? Thanks, Ron. $ cat LogManager_try.py #!/usr/bin/env python import gzip import os class LogStream(): """ """ def __init__(self, filename): self.filename = filename self.input_file = self.open_file(filename) def open_file(self, in_file): """ The gzip module checks if the input file is a gzipped file, only at the read stage. This is why the f.readline() is needed. """ try: f = gzip.GzipFile(in_file, "r") f.readline() except IOError: f = open(in_file, "r") f.readline() f.seek(0) return(f) def next_line(self, in_file): """ """ for line_ in in_file: yield line_.strip() if __name__ == "__main__": filename = "sac.log.gz" log_stream = LogStream(filename) line_ = log_stream.next_line(log_stream.input_file) print line_ $ python LogManager_try.py $ -- Ron Barak, System Development Engineer LSI Technologies Israel Ltd 63 Bar Yehuda Road, Nesher 36651 Israel Tel: (+972) 4 8203454 x1542 Fax: (+972) 4 8203464 [cid:263372909 at 22122008-2BEE][cid:263372909 at 22122008-2BF5] Remember, Ginger Rogers did everything Fred Astaire did, but backwards and in high heels. (Faith Whittlesey) -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image001.jpg Type: image/jpeg Size: 1512 bytes Desc: image001.jpg URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image003.jpg Type: image/jpeg Size: 1650 bytes Desc: image003.jpg URL: From pavlovevidence at gmail.com Sat Dec 6 16:15:19 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 6 Dec 2008 13:15:19 -0800 (PST) Subject: Guido's new method definition idea References: <014a071a$0$20670$c3e8da3@news.astraweb.com> Message-ID: <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> On Dec 6, 12:47?am, "Patrick Mullen" wrote: > Could I do something like this: > > def a.add(b): return a+b > > Outside of a class? ?Of course then that makes you think you could do > 5.add(6) or something craaaazy like that. ?(I mean, you can do > (5).__add__(6) but that's something else entirely) I'd be inclined to think that this defines an instancemethod on an existing object a. In other word, I'd read the following two lines as more or less equivalent. def a.add(b): return a+b a.add = lambda b: a+b Just as the following are equivalent: def foo(): return bar foo = lambda: bar I had been -0 on this, but now I think I'm -1. Carl Banks From jay.amorin at gmail.com Wed Dec 3 13:49:21 2008 From: jay.amorin at gmail.com (Jay Jesus Amorin) Date: Thu, 4 Dec 2008 02:49:21 +0800 Subject: python to parse excel file csv format In-Reply-To: References: Message-ID: This is how i do it, but it runs with error. Kindly help #!/usr/bin/env python import csv, sys, os filename = (sys.argv[1]) reader = csv.reader(open(filename, "rb"), delimiter=',', quoting=csv.QUOTE_NONE) try: for row in reader: os.popen("chown row[0] row[1]") except csv.Error, e: sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) ================================================================== testserver:~> ./promote2prod.py test.xls Traceback (most recent call last): File "./promote2prod.py", line 12, in ? sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) AttributeError: '_csv.reader' object has no attribute 'line_num' On Thu, Dec 4, 2008 at 2:25 AM, Jay Jesus Amorin wrote: > Hi all, > > Can anyone please help me. i need to parse the content of my csv excel file > and run the unix command chown. > > test.csv: > > "/dev/trunk/admin/sql/ADBPOS_CMSI_NATIONALITY.syn",814 > "/dev/trunk/bin/ADBPOSCMSDICED.ctl",405 > "/dev/trunk/discoverer/ADBPOS_BUSINESS_AREA.eex",215 > > > Please help me parse the csv file and run chown $csvfile_secondcolumn > $csvfile_firstcolumn. > > Here's how i want to run it. > > ./parsecsv.py test.csv > > > Many thanks. > > > Jay > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ibpet11 at gmail.com Tue Dec 30 05:12:41 2008 From: ibpet11 at gmail.com (ibpet11 at gmail.com) Date: Tue, 30 Dec 2008 02:12:41 -0800 (PST) Subject: string in files Message-ID: <9cda24d9-7a88-45db-b23c-fb43b7d567d4@r37g2000prr.googlegroups.com> guys i need info on how to call up different words in a line of a file using python example : file = 'this is a python coding group' i want to assign a xter to this, is, a, python , coding and group thanks From greg at cosc.canterbury.ac.nz Thu Dec 11 18:49:32 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 12 Dec 2008 12:49:32 +1300 Subject: newbie question: if var1 == var2: In-Reply-To: <87skouzbi5.fsf@daycos.com> References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> <87skouzbi5.fsf@daycos.com> Message-ID: <6qdn3fFc5ggdU2@mid.individual.net> Kirk Strauser wrote: > At 2008-12-11T19:49:23Z, Steve Holden writes: > >> item = item[:-1] > > It's easy - and broken. Bad things happen if you're using something other > than '\n' for EOL. Or if the last line of your file doesn't end with a newline. -- Greg From pyn00b at gmail.com Fri Dec 5 12:46:50 2008 From: pyn00b at gmail.com (n00b) Date: Fri, 5 Dec 2008 09:46:50 -0800 (PST) Subject: etree, minidom unicode Message-ID: <4c78e2e0-3de5-4f18-82f1-0d73ea66eb39@y1g2000pra.googlegroups.com> hi, i have a feew questions concnering unicode and utf-8 handling and would appreciate any insights. 1) i got a xml document, utf-8, encoded and been trying to use etree to parse and then commit to mysql db. using etree, everything i've been extracting is return as a string except ascii char > 127, which come back as a unicode. using minidom on the same document, however, i get all unicode. is there a way to 'force' etree to use unicode? 2) i'm using mysql 5.x on * nix (mac, linux) and after much messing around, have things working, i.e. i have unicode from the (minidom) parser, set all mysql and mysqldb attributes, i get back from mysql. is that expected behavior? #!/usr/bin/env python # -*- coding: UTF-8 -*- from xml.dom import minidom import MySQLdb import codecs from onix_model_01 import * db = MySQLdb.connect(host='localhost', user='root', passwd='', db='lsi', charset='utf8') cur = db.cursor() #cur.execute('SET NAMES utf8') #cur.execute('SET CHARACTER SET utf8') cur.execute('SET character_set_connection=utf8') cur.execute('SET character_set_server=utf8') cur.execute('''SHOW VARIABLES LIKE 'char%'; ''') ... >>> print 'firstname, lastname types from xml: ', type(a.firstname), type(a.lastname) >>>firstname, lastname types from xml: ... >>>cur.execute('''INSERT INTO encoding_test VALUES(null, %s, %s)''', (a.firstname, a.lastname)) ... now i'm getting the results back from mysql >>>cur.execute('SELECT * FROM encoding_test') >>>query = cur.fetchall() >>>for q in query: ....print q, type(q[0]), type(q[1]), type(q[2]) ....print q[1], q[2] ....print repr(q[1]), repr(q[2]) >>>(24L, 'Bront\xc3\xab', 'Charlotte ') >>> Bront? Charlotte >>>'Bront\xc3\xab' 'Charlotte ' so everything is coming back as it should, but i though i would get the sql results back as unicode not str ... what gives? finally, from a utf-8 perspective, is there any advantage using innodb over myisam? thx From imageguy1206 at gmail.com Thu Dec 18 08:56:34 2008 From: imageguy1206 at gmail.com (imageguy) Date: Thu, 18 Dec 2008 05:56:34 -0800 (PST) Subject: something else instead of PIL? References: Message-ID: <6df075c4-2397-4c41-9c75-64c59e7c0dd3@x16g2000prn.googlegroups.com> On Dec 17, 3:48?pm, Reimar Bauer wrote: > Hi > > what has happened to PIL? No updates since two years. > > Or does one know an alternative lib for resizing images? > > cheers > Reimar I have found the FreeImage library with the Python bindings quite workable. I work with multi-page TIF images and this seemed to be the best option. The FreeImage library seems to be actively maintained too (Last release in July 08 with updates to many of the image processing plug- ins). The python bindings took me a bit to understand as they try to emulate PIL, however they are implemented using ctypes, so you can change/manage yourself if needed. I found working directly with the functions exported from the .dll the best option and gave the best performance. Freeimage site: http://freeimage.sourceforge.net/ Python bindings: http://freeimagepy.sourceforge.net/ Hope that helps. Good luck. Working with images/graphics can make my brain hurt sometimes. g. From gandalf at shopzeus.com Thu Dec 18 16:28:23 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 18 Dec 2008 22:28:23 +0100 Subject: psycopg2 and large queries In-Reply-To: <762eed9d-4646-4c62-a9b7-d57d47f03b9e@e1g2000pra.googlegroups.com> References: <762eed9d-4646-4c62-a9b7-d57d47f03b9e@e1g2000pra.googlegroups.com> Message-ID: <494AC077.2060605@shopzeus.com> > Well, there are plenty of PostgreSQL modules around these days, and > even if pyPgSQL isn't suitable, I'm sure that there must be one which > can be made to work on Windows and to support server-side cursors. See > here for more: > > http://wiki.python.org/moin/PostgreSQL > I'm just looking for something that can replace psycopg2, because of the bug mentioned in my original post. Here are my options: - psycopg1: development stalled - psycopg2: memory bug and/or not db api compilant (see my original post) - pyPgSQL: looks like that the last release was in mid 2006 (and it depends on mxDateTime -> licensing problems) - mxODBC: commercial - PyGresSQL: apparently, it does not support fetching one row, only fetching all rows (see: http://www.pygresql.org/pg.html#getresult-get-query-values-as-list-of-tuples), so this is not an option. (Yes, it also has a db api compilant module, but it is only a wrapper around pgqueryobject, and it does not support server side cursors...) So there are many options, but do we have one that: 1. supports server side cursors (fetch some rows after opening the query, but not all of them) 2. open source, with no licensing problems 3. actively maintained Thanks, Laszlo From google at mrabarnett.plus.com Sat Dec 6 13:10:01 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 06 Dec 2008 18:10:01 +0000 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: <493ABFF9.9060702@mrabarnett.plus.com> Neal Becker wrote: > Daniel Fetchinson wrote: > >> Hi folks, >> >> The story of the explicit self in method definitions has been >> discussed to death and we all know it will stay. However, Guido >> himself acknowledged that an alternative syntax makes perfect sense >> and having both (old and new) in a future version of python is a >> possibility since it maintains backward compatibility. The alternative >> syntax will be syntactic sugar for the old one. This blog post of his >> is what I'm talking about: >> >> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html >> >> The proposal is to allow this: >> >> class C: >> def self.method( arg ): >> self.value = arg >> return self.value >> >> instead of this: >> >> class C: >> def method( self, arg ): >> self.value = arg >> return self.value >> >> I.e. explicit self stays only the syntax is slightly different and may >> seem attractive to some. As pointed out by Guido classmethods would >> work similarly: >> >> class C: >> @classmethod >> def cls.method( arg ): >> cls.val = arg >> return cls.val >> >> The fact that Guido says, >> >> "Now, I'm not saying that I like this better than the status quo. But >> I like it a lot better than [...] but it has the great advantage that >> it is backward compatible, and can be evolved into a PEP with a >> reference implementation without too much effort." >> >> shows that the proposal is viable. >> >> I'd like this new way of defining methods, what do you guys think? >> Anyone ready for writing a PEP? >> > What's the advantage? If there is not a good reason, I would strongly opposed polluting the language. > I wouldn't want to see $ for "self." and ? (cent) for "cls." either... From lists at cheimes.de Mon Dec 22 22:19:32 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 23 Dec 2008 04:19:32 +0100 Subject: python3 urlopen(...).read() returns bytes In-Reply-To: References: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> <5496b34d-7ce4-4281-9f01-aed12dab9fd3@f33g2000vbf.googlegroups.com> Message-ID: Glenn G. Chappell schrieb: > Okay, so I guess I didn't really *get* the whole unicode/text/binary > thing. Maybe I still don't, but I think I'm getting closer. Thanks to > everyone who replied. The basic principal is easy. On the one hand you have some text as unicode data, on the other hand you have some binary data that may contain text in an arbitrary encoding. In order to get the text you have to decode the byte data into unicode. The other way around is called encoding. Everybody in the whole world has to deal with unicode *unless* you are living in USA and all you have is plain and simple ASCII text. Python 2.x makes no difference between text in ASCII and arbitrary bytes. Both are stored in the str type. This makes it easy for ASCII country but the rest of the world suffers the consequences. Python 3.0 makes a hard break for ASCII people because with 3.0 really everybody has to deal with encodings. There is no more implicit conversion between ASCII text and unicode. http://www.joelonsoftware.com/articles/Unicode.html explains it in great detail. > > On Dec 22, 1:41 pm, ajaksu wrote: >> On Dec 22, 8:25 pm, Christian Heimes wrote: >> That said, a "decode to declared HTTP header encoding" version of >> urlopen could be useful to give some users the output they want (text >> from network io) or to make it clear why bytes is the safe way. > > Sounds like a great idea. More to the point, it sounds like it's > pretty much a necessary idea. > > Consider: reading a web page is an easy one-liner. Now, no one is > going to write that one-liner, and then spend 20 lines trying to get > the Content-Type and encoding figured out. Instead we're all going to > do it the short, easy, *wrong* way. So every program in the world that > uses urlopen gets to have the same bug. Not good. The *right* way > needs to be the *easy* way. Python 2.x suffers from the same problem. It just doesn't tell you from the beginning that you need to deal with the problem. With 2.x you can read websites fine - until you have to deal with a non English, non ASCII text. 3.0 forces the developer to think about the issue right from the beginning. No more excuses :) I suggest somebody makes a feature request for 3.1. A patch with unit test increases the changes for the patch by at least one magnitude. Christian From steve at holdenweb.com Fri Dec 19 23:02:10 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 19 Dec 2008 23:02:10 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <015c47ad$0$20656$c3e8da3@news.astraweb.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c47ad$0$20656$c3e8da3@news.astraweb.com> Message-ID: <494C6E42.8080008@holdenweb.com> Steven D'Aprano wrote: > On Fri, 19 Dec 2008 10:25:30 -0700, Michael Torrie wrote: > >> So funny that now that Python 3.0 is actually released we have people >> acting all surprised like they've never seen any of the new features in >> Python 3.0 coming. However these features have been discussed for >> years! And debated! > > Debated by who? The entire Python-using community? Every single Python > programmer? Or just the small proportion of Python developers who are > also core developers? > > Are you *really* surprised that some people had never heard of the > changes being debated until it was too late? > It isn't the least surprising that some people have been taken by surprise by the changes. Neither is it surprising that some of them don't like the changes that much. However, at least in the open source world one has the *opportunity* to make one's voice heard and one's opinion known, even thought he majority prefer to remain consumers of the output of open source projects. Where commercial projects are concerned the major influence one has is a post-facto vote with one's wallet. I hope, however, that those who don't like the changes but didn't bother to track developments don't feel in any way disenfranchised. They are still welcome to make their input, and of course there is nothing to stop them keeping Python 2.X alive for as long as they wish. [misconception about print's role] >> Furthermore, the new {} >> notation allows many, many more options for formatting to be used. Want >> to display a floating point number with $#.## notation, and ($#.##) for >> negative? It's all now possible. Couldn't be done before. > > Of course it could be. You just needed to write your own formatting > engine. What you mean is that it couldn't be done with % formatting and > nothing else. > > >> In short, this is a huge improvement, and backwards compatibility is >> preserved for the 2.x style for those that wish it. > > > There clearly is a need for a more heavyweight formatting solution than % > and string.Template. There are things that can't be done easily with % > alone, and format() will make them much simpler. I have no objection to > the addition of the format() method (although I wonder whether it might > have been better as a function). > That's doubtless a debate that will play for a long time, with no really clear advantage either way. Programmers just like to debate these things. Of course it's a trivial addition: def format(s, *args, **kw): return s.format(*args, **kw) [I put **kw in becuase it's easier than checking the docs to se whether keyword arguments are specified]. This doesn't mean there won't be fifteen more posts on this thread about it. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From grante at visi.com Sat Dec 13 20:51:23 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 13 Dec 2008 19:51:23 -0600 Subject: subprocess to C program References: <0ebd59c5-95a1-42d4-b597-d1c248490b8e@y1g2000pra.googlegroups.com> Message-ID: <8MidneyhDfIG-9nUnZ2dnUVZ_uadnZ2d@posted.visi> On 2008-12-14, MRAB wrote: >> I am writing a C process and I want to read data from a file that I >> write to in Python. I'm creating a pipe in Python, passing it to the >> C process, and calling '_read'. It gives me error 9, bad file number. >> >> Python code: >> >> import subprocess as s, os >> r, w= os.pipe( ) >> os.write( w, 'abcdefghij\n' ) >> a= s.Popen( [ r'C:\Documents and Settings\usr\Desktop\working >> \try_start', '%i'%r, '%i'%w ] ) >> >> C code: >> >> char buf[ 16 ]; >> memset( buf, 0, 16 ); >> int readfd= atoi( argv[ 1 ] ); >> int ct= _read( readfd, buf, 15 ); >> printf( "\n\n'_read %i %i %i': %s\n", ct, readfd, errno, buf ); >> >> Output: >> >> '_read -1 3 9' >> >> meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9. I want 'ct' >> to be 11 at this point. Thanks in advance. >> > It looks like the ids aren't system global. They certainly aren't in Unix: Their a property of the process. -- Grant From n.kottiyath at gmail.com Mon Dec 29 22:46:50 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Mon, 29 Dec 2008 19:46:50 -0800 (PST) Subject: Python module import loop issue References: <02bc8567-695a-4277-9698-a95549a0bc98@w39g2000prb.googlegroups.com> <4a0557b7-e901-49ff-b4db-53f4d8a7c0f8@r40g2000yqj.googlegroups.com> Message-ID: <54ed8839-7d47-4690-b1c0-7930aa517955@q30g2000prq.googlegroups.com> On Dec 30, 8:24?am, "Gabriel Genellina" wrote: > En Mon, 29 Dec 2008 19:47:51 -0200, Carl Banks ? > escribi?: > > > On Dec 29, 10:51?am, Kottiyath wrote: > >> Module Factory: > >> A1Factory: {'B1Tag':1.1.B1, 'C1Tag':1.2.C1, 'D1Tag':1.3.D1'} > >> A2Factory: {'B2Tag':2.1.B2, 'C2Tag':2.2.C2, 'D2Tag':2.3.D2'} > > >> But, since Module requires objects of B1, C1 etc, it has to import > >> Factory. > >> Now, there is a import loop. How can we avoid this loop? > > > I'm going to suggest three ways: a straightforward, good-enough way; a > > powerful, intelligent, badass way; and a sneaky way. > > In Python 2.6 (and 3.0) there is a fourth way: class decorators. > > > 1. The straightforward, good-enough way > > > Define functions in Factory.py called register_A1_subclass and > > register_A2_subclass, then call them whenever you create a new > > subclass. > > Class decorators are a clean variant of this approach (in my opinion). > > > package1/module1.py: > > ----------------------------- > > import Factory > > > class B1(A1): > > ? ? # define class B1 here > > > Factory.register_A1_subclass("B1Tag",B1) > > ----------------------------- > > That would become: > > @Factory.register_A1_subclass("B1Tag") > class B1(A1): > ? ?... > > (for an adequate variant of register_A1_subclass). The advantage is that ? > the "register" stuff appears prominently near the name of the class, and ? > there is no need to repeat the name. > Also, "B1Tag" can be left out, if it is stored as a class attribute of B1 ? > (in some cases using __name__ is enough) > > > 2. The powerful, intelligent, badass way > > > Metaclasses. ?I would guess you do not want to do this, and I wouldn't > > recommend it if you haven't studied up on how metaclasses work, but > > it's a textbook example of their usefulness. ?If you expect to use > > factory functions like this a lot, it might be worth your while to > > learn them. > > A problem with metaclasses is when you have intermediate subclasses that ? > are not meant to be registered, but the metaclass applies equally to all ? > of them. > > -- > Gabriel Genellina Hi Gabriel, Carl, Thank you very much for your help. I never knew about metaclassess and class decorators. Thank you again. I am actually inclined towards the straightforward way (1). But still one of the issues that I have mentioned in the first mail remains. How do I actually hit the code because my entry point is the EN module. Importing every module in EN module so that it hits the code atleast once is fraught with danger because later, someone might delete it to clean it up and will start facing issues. Could you give me some pointers in such a case? Regards K From sturlamolden at yahoo.no Sat Dec 13 15:35:41 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 13 Dec 2008 12:35:41 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> On 10 Des, 19:42, cm_gui wrote: > And it is not just this Python site that is slow. There are many many > Python sites which are very slow. And please don?t say that it could > be the web hosting or the server which is slow ? because when so many > Python sites are slower than PHP sites, it couldn?t be the web > hosting. ? Also, Zope/Plone is even slower. > > Python is slow. Very slow. By the way... I know of a very slow Python site called YouTube.com. In fact, it is so slow that nobody ever uses it. From stef.mientki at gmail.com Sat Dec 27 06:16:14 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 27 Dec 2008 12:16:14 +0100 Subject: Is there a function to remove escape characters from a string ? In-Reply-To: <01659326$0$6988$c3e8da3@news.astraweb.com> References: <0163882f$0$6988$c3e8da3@news.astraweb.com> <5a29b62a-c38f-409b-8887-6259ad072bf5@w1g2000prk.googlegroups.com> <01659326$0$6988$c3e8da3@news.astraweb.com> Message-ID: <49560E7E.1050307@gmail.com> Steven D'Aprano wrote: > On Sat, 27 Dec 2008 01:41:40 +0100, Stef Mientki wrote: > > >> Sorry if I offended someone, that was certainly not my intention. And I >> guess you will be surprised, if I tell you, I don't (want) to understand >> any bit of the above code ;-) Come on, the home computer was invented >> about 1980. If we look at hardware, it follows the Moore's law, for >> software I would expect at least 0.1 of Moore's law ;-) I hope that >> clarifies my point. >> > > No, that only makes it even more confusing. What does Moore's Law have to > do with your willful ignorance about the existence of human languages > other than English? > > Nothing. I even don't (want to) see what bits / bytes / escape sequences have to do with modern programming techniques, so I certainly don't see any relation between these and human languages. But the lack of Moore's law in software explains why we still need to concern about bits and bytes ;-) cheers, Stef From garlictrompet at gmail.com Mon Dec 15 07:21:20 2008 From: garlictrompet at gmail.com (Analog Kid) Date: Mon, 15 Dec 2008 17:51:20 +0530 Subject: regex problem .. Message-ID: <3b10c2060812150421y1c3e7da6ha1b72c736e2a20d4@mail.gmail.com> Hi All: I am new to regular expressions in general, and not just re in python. So, apologies if you find my question stupid :) I need some help with forming a regex. Here is my scenario ... I have strings coming in from a list, each of which I want to check against a regular expression and see whether or not it "qualifies". By that I mean I have a certain set of characters that are permissible and if the string has characters which are not permissible, I need to flag that string ... here is a snip ... flagged = list() strs = ['HELLO', 'Hi%20There', '123123@#@'] p = re.compile(r"""[^a-zA-Z0-9]""", re.UNICODE) for s in strs: if len(p.findall(s)) > 0: flagged.append(s) print flagged my question is ... if I wanted to allow '%20' but not '%', how would my current regex (r"""[^a-zA-Z0-9]""") be modified? TIA, AK -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Mon Dec 8 05:54:01 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 8 Dec 2008 02:54:01 -0800 (PST) Subject: getting error...... Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in open_workbook biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) File "C:\Python25\Lib\site-pack References: Message-ID: <6c76b050-5b47-46f3-9097-5c58979b6913@s9g2000prg.googlegroups.com> On Dec 8, 6:48?pm, "Gabriel Genellina" wrote: > En Fri, 05 Dec 2008 02:31:01 -0200, pk sahoo ? > escribi?: > > > > > hallo everybody, > > when i am running the following command > > >>>> import xlrd > >>>> book=xlrd.open_workbook("C:\\a.xls") > > > i am getting the following error.. > > > *Traceback (most recent call last): > > ? File "", line 1, in > > ? File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in > > open_workb > > ook > > ? ? biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) > > ? File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 1323, in > > getbof > > ? ? raise XLRDError('Expected BOF record; found 0x%04x' % opcode) > > xlrd.biffh.XLRDError: Expected BOF record; found 0x3f3c* > > Looks like your a.xls file is not an Excel file (one of the formats ? > supported by xlrd). > As 0x3f3c corresponds to the characters ' """ then it's an Excel 2003 XML Spreadsheet that's been manually(?) renamed from .xml to .xls. The current xlrd release supports only the binary ("BIFF") format .xls files created by Excel 3.0 to Excel 2003. The next release (due out Real Soon Now) will support Excel 2.1 and 2.0 formats [don't ask]. Very soon after that will come support for Excel 2007 .xlsx which is a bunch of XML files inside a ZIP file. Support for Excel 2003 "SpreadsheetML" is way down the to-do list. If the OP wants to be able to read the file with xlrd: (1) Open it with Excel 200[37] and save as a .xls file or (2) rename it to .xml, start OpenOffice.org Calc, click on File, click on Open, click on "Files of type", choose "Microsoft Excel 2003 XML (*.xml)" from the (long, unsorted) drop-down list, ..., and save as etc etc. Gnumeric is not an option. HTH, John From fetchinson at googlemail.com Sat Dec 27 18:50:34 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 27 Dec 2008 15:50:34 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: >> I have considered using ctypes but for my needs using the C API >> directly seems more reasonable. array.array and numpy.array doesn't >> fit my needs since I need to do long and complicated operations on the >> two (pretty large) integer arrays that would be too slow using >> array.array and numpy.array (I've verified this claim by benchmarking >> a numpy.array based solution). > > OK, but if you go to array.array or numpy.array or ctypes, you can > create a uniformly typed (C datatype) array , which is the key to > getting any speed out of the deal. If you insist on using python > lists, you are stuck with extracting data element by element from > its Python language wrap. I thought that going through the python C API will be more cross-platform than using ctypes, but I might be wrong. Anyway, the C API for such a simple thing as a single function doesn't seem too scary :) I agree that array.array is more efficient than a list but the input for my function will come from PIL and PIL returns a list. So I have a list to begin with which will be passed to the C function. I assume converting the list to an array.array and passing that to the C function doesn't make any difference in terms of speed since the operation itself will be done in the C function anyway. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From martin at v.loewis.de Tue Dec 2 14:56:30 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Tue, 02 Dec 2008 20:56:30 +0100 Subject: Multiple Versions of Python on Windows XP In-Reply-To: References: <4934de22$0$27863$9b622d9e@news.freenet.de> Message-ID: <493592EE.9090005@v.loewis.de> >>> What changes are made to the registry? >> >> For a complete list, see Tools/msi/msi.py in the source tree. > > I have scanned the file: > http://svn.python.org/projects/python/branches/py3k/Tools/msi/msi.py > > I don't find anything that addresses this issue. Read the add_registry function. You may need to first understand how the Registry table in an MSI file works. > I am seeking some mechanism such that any of Python 2.5, Python 2.6 or > Python 2.6 can be chosen as the currently active version. If Glenn Lindermann's answer doesn't help, you need to explain: what is a "currently active version"? How is one Python version more active than any other? > I was hoping that there is some simpler way than the "Repair" procedure. See Glenn Lindermann's answer. >> It would be good to be more specific with such statements: what troubles >> specifically? If I play dumb, I'd say "of course - windows explorer >> doesn't support editing Python files; you need a text editor". > > Yes, I should have been clearer. The PyScripter application locks up > and must be killed, using the Task Manager. I think you need to report that to the PyScripter authors as a bug. I can't imagine how the "currently active version" can affect what PyScripter does. Regards, Martin From michaeldg at gmail.com Thu Dec 4 01:52:19 2008 From: michaeldg at gmail.com (Michael_D_G) Date: Wed, 3 Dec 2008 22:52:19 -0800 (PST) Subject: Python advocacy ... HELP! Message-ID: <5f8c1a52-545e-402e-863a-acdf23d04c78@h20g2000yqn.googlegroups.com> I am a faculty member of a cs department. We currently teach C++ in our intro to programming course. I am teaching this class and it seems to me that we would be much better served teaching python in the intro course, C++ for Data structures, as we do now, and Java in object oriented programming, as we do now. Some of my colleagues agree with me but some still see python as a niche language and don't understand how we could teach anything beyond C, C++ or Java. I have looked at several interesting academic papers, on doing just this approach. I have also looked through the python web page to get examples of industry players using python in a non-trivial way. Yes, I know, Google, Microsoft, Sun, CIA website running on Plone, NOAA, NASA. If anyone has any recent articles, or if anyone on the list is at a fortune 500 company, how do I refute the notion that Python is a "marginal" language because according to TOBIE it only less than a 6% market share. -michael From arnodel at googlemail.com Wed Dec 10 17:19:17 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 10 Dec 2008 22:19:17 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: "Dotan Cohen" writes: > 2008/12/10 : >> On Dec 5, 9:51 am, Xah Lee wrote: >>> >>> For those of you who don't know linear algebra but knows coding, this >>> means, we want a function whose input is a list of 3 elements say >>> {x,y,z}, and output is also a list of 3 elements, say {a,b,c}, with >>> the condition that >>> >>> a = x/Sqrt[x^2+y^2+z^2] >>> b = y/Sqrt[x^2+y^2+z^2] >>> c = z/Sqrt[x^2+y^2+z^2] >> >>> >>> In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, >>> you'll have 50 or hundreds lines. >> >> Ruby: >> >> def norm a >> s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) >> a.map{|x| x/s} >> end > > If someone doesn't counter with a Python one-liner then I'm going to > port that to brainfuck. def unit(v): return map((sum(map(lambda x:x*x, v))**0.5).__rdiv__, v) The hard bit was to make it less readable than the Ruby version ;) -- Arnaud From rafesacks at gmail.com Mon Dec 1 03:27:08 2008 From: rafesacks at gmail.com (Rafe) Date: Mon, 1 Dec 2008 00:27:08 -0800 (PST) Subject: pydoc enforcement. References: <6ccec696-a8bb-4818-a016-642514677b70@b38g2000prf.googlegroups.com> Message-ID: <599b252d-5e05-4b30-9027-36a73a1875cc@w1g2000prk.googlegroups.com> On Dec 1, 7:27?am, "ken.faulk... at gmail.com" wrote: > I've been thinking about implementing (although no idea yet *HOW*) the > following features/extension for the python compile stage and would be > interested in any thoughts/comments/flames etc. > > Basically I'm interested adding a check to see if: > ? 1) pydoc's are written for every function/method. > ? 2) There are entries for each parameter, defined by some > predetermined syntax. > > My idea is that as much as I love dynamic typing, there are times when > using some modules/API's that have less than stellar documentation. I > was thinking that if it was possible to enable some switch that > basically forced compilation to fail if certain documentation criteria > weren't met. > > Yes, it should be up to developers to provide documentation in the > first place. Or, the client developer might need to read the source > (IF its available)... ?but having some "forced" documentation might at > least ease the problem a little. > > For example (half borrowing from Javadoc). > > class Foo( object ): > > ? def bar( self, ui ): > ? ? ?pass > > Would fail, since the bar method has an "unknown" parameter called > "ui". > What I think could be interesting is that the compiler forces some > documentation such as: > > class Foo( object ): > > ? def bar( self, ui ): > ? ? """ > ? ? @Param: ui : ?blah blah blah. > ? ? """ > ? ? ?pass > > The compiler could check for @Param matching each parameter passed to > the method/function. Sure, a lot of people might just not put a > description in, so we'd be no better off. But at least its getting > them *that* far, maybe it would encourage them to actually fill in > details. > > Now ofcourse, in statically ?typed language, they might have the > description as "Instance of UIClass" or something like that. For > Python, maybe just a description of "Instance of abstract class UI" or > "List of Dictionaries"... ?or whatever. Sure, precise class names > mightn't be mentioned (since we mightn't know what is being used > then), but having *some* description would certainly be helpful (I > feel). > > Even if no-one else is interested in this feature, I think it could > help my own development (and would be an interested "first change" > into Python itself). > > Apart from bagging the idea, does anyone have a suggestion on where in > the Python source I would start for implementing such an idea? > > Thanks > > Ken As long as it uses RST (reStructuredText) it could be interesting. Maybe as a wrapper on epydoc or something? I have been simply generating my docs and reading through them. This is fine for catching areas which are totally missing, but gets very time consuming to maintain small changes. What would be really great, is something which ties in to subversion to display an easy to see and find alert in the docs when the source has been updated. It would then require some manual action to hide the alert (hopefully someone would read the doc again before killing the alert). - Rafe From brian.wallace at hp.com Mon Dec 8 19:48:01 2008 From: brian.wallace at hp.com (Brian Wallace) Date: Mon, 08 Dec 2008 16:48:01 -0800 Subject: python-devel download and install Message-ID: <1228783681.6826.7.camel@bwallace-laptop.americas.hpqcorp.net> Hi Folks, I am developing in Python version 2.5.2 and need to install and download the python-devel library. (This is needed so I can build and install mysql-python.) Where can I find find this module to download and build/installation instructions? I have been unable to find the source online to download. I am not root on the box where I need to install this module so I need the source (rpm/deb packages will not do). Thank you in advance for the guidance! -Brian From stef.mientki at gmail.com Sat Dec 6 18:40:53 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 07 Dec 2008 00:40:53 +0100 Subject: how to get a beep, OS independent ? Message-ID: <493B0D85.3060404@gmail.com> hello, I want to give a small beep, for windows there's message-beep, and there seems to be something like " curses" , but that package seems to be totally broken in P2.5 for windows. Any other suggestions ? thanks, Stef Mientki From simon at brunningonline.net Mon Dec 22 04:56:59 2008 From: simon at brunningonline.net (Simon Brunning) Date: Mon, 22 Dec 2008 09:56:59 +0000 Subject: [Help] The pywinauto Can't select the MDI's menu using the MenuItems() which return []. In-Reply-To: <85676.52949.qm@web32801.mail.mud.yahoo.com> References: <85676.52949.qm@web32801.mail.mud.yahoo.com> Message-ID: <8c7f10c60812220156k4a290fa1re469bc8c4a4019ae@mail.gmail.com> 2008/12/21 : > The code below opens the Choose Font dialog on my Spanish Windows version: > > py> from pywinauto.application import Application > py> app = Application.start("Notepad.exe") Notepad's menus are build with MFC. Word's menus are not. Trust me, give it up. For automating Word, COM (with Mark Hammond's excellent Python/COM bridge) is the only way to go. -- Cheers, Simon B. simon at brunningonline.net From maresp1 at hotmail.com Mon Dec 22 04:17:03 2008 From: maresp1 at hotmail.com (maresp1 at hotmail.com) Date: Mon, 22 Dec 2008 01:17:03 -0800 (PST) Subject: =?windows-1252?Q?We_are_looking_for_boys_and_girls_to_have_fun=2C_orgie?= =?windows-1252?Q?s=2C_trios=2C_and_whatever=2E_If_you_want_a_do_it=2C_don=92t_be_shy_?= =?windows-1252?Q?and_contact=2E_That=92s_going_to_be_great=21?= Message-ID: We are looking for boys and girls to have fun, orgies, trios, and whatever. If you want a do it, don?t be shy and contact. That?s going to be great! By the way, we are bisexual and we don?t care about gender? Sign in to enjoy with us: http://xxxgente.chueca.com/sexocontacto/ http://galeon.com/sexocontacto/2451.html From pruebauno at latinmail.com Wed Dec 10 10:06:50 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Wed, 10 Dec 2008 07:06:50 -0800 (PST) Subject: StringIO in 2.6 and beyond References: Message-ID: On Dec 10, 6:58?am, Bill McClain <20080915.20.wmccl... at spamgourmet.com> wrote: > On 2008-12-10, ajaksu wrote: > > > On Dec 9, 5:24?pm, Bill McClain <20080915.20.wmccl... at spamgourmet.com> > > wrote: > > > On 2008-12-09, MRAB wrote: > > > > > In Python 2.x unmarked string literals are bytestrings. In Python 3.x > > > > they're Unicode. The intention is to make the transition from 2.x to 3.x > > > > easier by adding some features of 3.x to 2.x, but without breaking > > > > backwards compatibility (not entirely successfully!). > > > > It is a bit ugly. In 2.6 StringIO won't take bytestrings, so I apply u'x'. But > > > in 3.0 u'x' will be gone and I'll have to change the code again. > > Try: > > from __future__ import unicode_literals > > That works for: > > ? ? output.write('First line.\n') > > ...but not for: > > ? ?print('Second line.', file=output) > > Maybe a combination of this and functools.partial as was suggested before. At > least the necessary edits would be at the top of the program. > > -Bill > -- > Sattre Press ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Tales of Warhttp://sattre-press.com/? ? ? ? ? ? ? ? ? ? ? by Lord Dunsany > i... at sattre-press.com ? ? ? ?http://sattre-press.com/tow.html I think this combination might do the trick (I don't have 2.6 to test it right now): from __future__ import print_function from __future__ import unicode_literals from functools import partial import io print = partial(print, sep=" ", end="\n") out = io.StringIO() print("hello", file=out) What puzzles me is the documentation in 2.6 and 3.0: In 2.6 it says: "The StringIO object can accept either Unicode or 8- bit strings". Why does it fail with old str objects then? Why is there no documentation for StringIO in 3.0? From sturlamolden at yahoo.no Sat Dec 13 15:33:28 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 13 Dec 2008 12:33:28 -0800 (PST) Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> <87iqpoc1l0.fsf@mulj.homelinux.net> <4155583a-1f6d-4fca-8cf1-7fa809e6d448@q30g2000prq.googlegroups.com> Message-ID: <92adeebc-07ae-4261-b92d-22ff9f9195b1@y1g2000pra.googlegroups.com> On 13 Des, 21:26, sturlamolden wrote: > Python methods always have a return value, even those that seem to do > not - they silently return None. Thus, __iadd__ must return self to > avoid rebinding to None. Except for immutable types, for which __iadd__ must return a new instance. From kay.schluehr at gmx.net Sun Dec 21 01:13:49 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 20 Dec 2008 22:13:49 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c47ad$0$20656$c3e8da3@news.astraweb.com> Message-ID: On 20 Dez., 02:54, Steven D'Aprano wrote: > Debated by who? The entire Python-using community? Every single Python > programmer? Or just the small proportion of Python developers who are > also core developers? "If I'd asked people what they wanted, they would have asked for a better horse." Henry Ford From v+python at g.nevcal.com Tue Dec 2 02:19:31 2008 From: v+python at g.nevcal.com (Glenn Linderman) Date: Mon, 01 Dec 2008 23:19:31 -0800 Subject: Multiple Versions of Python on Windows XP In-Reply-To: <4934de22$0$27863$9b622d9e@news.freenet.de> References: <4934de22$0$27863$9b622d9e@news.freenet.de> Message-ID: <4934E183.9020404@g.nevcal.com> On approximately 12/1/2008 11:05 PM, came the following characters from the keyboard of Martin v. L?wis: >> Is there some way to specify a default version in such a way that it can >> be changed as necessary? >> > > What do you mean by "default version"? > > There is the version that is associated with the .py/.pyc extensions > at any point in time; you can change these by re-running the respective > installers from add-and-remove-programs. In a well-managed installation, > only one Python installation would have the "Register Extensions" > feature selected; to then change the default, one would unselect the > feature in one version, and reselect it in a different. If only the > default installation procedure was ever used, re-running the installer > in "Repair" mode (from ARP) will also restore the extension > associations. That seems a lot more cumbersome than just using the command line to change the ftype and assoc a bit. Here's how I set up my computer, for multiple versions. Now to change the "default", I just use the assoc command to change the association for .py to one of the three listed ftypes. Simple and quick. c:\>ftype Python25.File ftype Python25.File Python25.File="C:\Python25\python.exe" "%1" %* c:\>ftype Python26.File ftype Python26.File Python26.File="C:\Python26\python.exe" "%1" %* c:\>ftype Python30.File ftype Python30.File Python30.File="C:\Python30\python.exe" "%1" %* c:\>assoc .py assoc .py .py=Python25.File It would be nice if the ftypes were version specific as created by the installer; IIRC, I created the above three from the ftype Python.File as I installed each version. -- Glenn -- http://nevcal.com/ =========================== A protocol is complete when there is nothing left to remove. -- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking From marco at sferacarta.com Mon Dec 22 12:01:26 2008 From: marco at sferacarta.com (Marco Mariani) Date: Mon, 22 Dec 2008 18:01:26 +0100 Subject: Python's popularity In-Reply-To: References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: Richard Riley wrote: > One does not have to by a language maestro to try and assess its > popularity. While his numbers or his reading of the numbers might be > open to some questions, to suggest that one needs to be totally familiar > with a language to determine its popularity is, frankly, ridiculous. I was not judging his competency. But when I am naive on a subject, I don't usually show off like that. The polemic intents in his previous messages are quite clear (python is slow, py3k is an utter failure because it doesn't solve the whitespace issue, etc), and this thread is not different. It seems like a rehash of issues that have been dragged around here by generations of trolls for the last 10 years. Sorry for adding noise to the signal :-/ From bj_666 at gmx.net Fri Dec 19 18:02:08 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Dec 2008 23:02:08 GMT Subject: encoding problem References: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> <6r1m72Ffb5kpU3@mid.uni-berlin.de> <6r2hvjFfb5kpU6@mid.uni-berlin.de> Message-ID: <6r2nfgFfb5kpU7@mid.uni-berlin.de> On Fri, 19 Dec 2008 15:20:08 -0700, Joe Strout wrote: > Marc 'BlackJack' Rintsch wrote: > >>> And because strings in Python, unlike in (say) REALbasic, do not know >>> their encoding -- they're just a string of bytes. If they were a >>> string of bytes PLUS an encoding, then every string would know what it >>> is, and things like conversion to another encoding, or concatenation >>> of two strings that may differ in encoding, could be handled >>> automatically. >>> >>> I consider this one of the great shortcomings of Python, but it's >>> mostly just a temporary inconvenience -- the world is moving to >>> Unicode, and with Python 3, we won't have to worry about it so much. >> >> I don't see the shortcoming in Python <3.0. If you want real strings >> with characters instead of just a bunch of bytes simply use `unicode` >> objects instead of `str`. > > Fair enough -- that certainly is the best policy. But working with any > other encoding (sometimes necessary when interfacing with any other > software), it's still a bit of a PITA. But it has to be. There is no automagic guessing possible. >> And does REALbasic really use byte strings plus an encoding!? > > You betcha! Works like a dream. IMHO a strange design decision. A lot more hassle compared to an opaque unicode string type which uses some internal encoding that makes operations like getting a character at a given index easy or concatenating without the need to reencode. Ciao, Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Fri Dec 26 19:42:58 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 26 Dec 2008 16:42:58 -0800 (PST) Subject: Right way to set a variable to NULL? References: <5nfal41gom0iqi2nh5h0m5847ev9brtvpf@4ax.com> <098da1d1-640c-4aef-b005-5f0932f291cc@35g2000pry.googlegroups.com> Message-ID: <1836b10a-6186-4f27-9a65-96e539d5b174@w1g2000prm.googlegroups.com> On Dec 27, 11:05?am, Martin wrote: > 2008/12/26 John Machin : > > > The above all have the same characteristic: if the input is a zero- > > length string, then NULL is inserted into the database instead of a > > zero-length string. Some folks (not just pedants!) regard that as an > > important difference. > > agreed but I understood the OP specifically wanted NULL and not ''. He wanted None inserted into the database as NULL if his regex didn't match. He didn't invite you to change a matching '' to NULL with no announcement. From rurpy at yahoo.com Sun Dec 7 23:51:50 2008 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Sun, 7 Dec 2008 20:51:50 -0800 (PST) Subject: tabs and spaces in py3k Message-ID: <774909e2-b248-4251-bbba-deb309e72714@x38g2000yqj.googlegroups.com> The following code works under 2.6 ---- def foo(): a = 1 <.tab..>b = 1 ---- but results in a TabError in Python 3k File "x.py", line 3 b = 3 ^ TabError: inconsistent use of tabs and spaces in indentation The py3k docs say the same thing as the 2.6 docs, namely that tabs are expanded to spaces prior to determining the line's indentation. (Language Ref, Lex Anal, Line Struct, Indentation) (I wish someone would put the section numbers back in the docs.) No mention of this change (that I noticed) in What's New or NEWS.txt. Do the Py3k docs need correction? From malkarouri at gmail.com Fri Dec 5 08:44:22 2008 From: malkarouri at gmail.com (malkarouri) Date: Fri, 5 Dec 2008 05:44:22 -0800 (PST) Subject: RELEASED Python 2.6.1 References: Message-ID: On 5 Dec, 05:07, Barry Warsaw wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hot on the heals of Python 3.0 comes the Python 2.6.1 bug-fix ? > release. Nice work. Thanks. > Source tarballs and Windows installers can be downloaded from the ? > Python 2.6.1 page I note that OS X installers have not been released (yet). I don't know if you plan to, but I think it is important to release installers that do not suffer from the bug http://bugs.python.org/issue4017 which renders Tkinter unusable in the 2.6.0 release and which (I believe) is a build issue. Can we expect such an updated release? Many thanks, Muhammad Alkarouri From enleverlesX.XmcX at XmclaveauX.com Fri Dec 19 15:43:37 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Fri, 19 Dec 2008 21:43:37 +0100 Subject: PIL on 3.x? In-Reply-To: <3892784c-ddf4-4451-bcfd-dbc58b9b55f8@e1g2000pra.googlegroups.com> References: <3892784c-ddf4-4451-bcfd-dbc58b9b55f8@e1g2000pra.googlegroups.com> Message-ID: <494c0ad4$0$4096$ba4acef3@news.orange.fr> Hi! This info is interesting for many people. IMO, it's a good idea to write the question in this newsgroup. @-salutations -- Michel Claveau From acerimusdux at comcast.net Sun Dec 7 18:33:37 2008 From: acerimusdux at comcast.net (acerimusdux) Date: Sun, 07 Dec 2008 18:33:37 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: <493C5D51.6060102@comcast.net> James Stroud wrote: >
    Rasmus > Fogh wrote: >> Current behaviour is both inconsistent and counterintuitive, as these >> examples show. >> >>>>> x = float('NaN') >>>>> x == x >> False > > Perhaps this should raise an exception? I think the problem is not > with comparisons in general but with the fact that nan is type float: > > py> type(float('NaN')) > > > No float can be equal to nan, but nan is a float. How can something be > not a number and a float at the same time? The illogicality of nan's > type creates the possibility for the illogical results of comparisons > to nan including comparing nan to itself. > > I initially thought that looked like a bug to me. But, this is apparently standard behavior required for "NaN". I'm only using Wikipedia as a reference here, but about 80% of the way down, under "standard operations": http://en.wikipedia.org/wiki/IEEE_754-1985 "Comparison operations. NaN is treated specially in that NaN=NaN always returns false." Presumably since floating point calculations return "NaN" for some operations, and one "Nan" is usually not equal to another, this is the required behavior. So not a Python issue (though understandably a bit confusing). The array issue seems to be with one 3rd party library, and one can choose to use or not use their library, to ask them to change it, or even to decide to override their == operator, if one doesn't like the way it is designed. From warren at delsci.com Thu Dec 4 04:28:56 2008 From: warren at delsci.com (Warren DeLano) Date: Thu, 4 Dec 2008 01:28:56 -0800 Subject: "as" keyword woes Message-ID: <896B75251BA19745A529B1B867893FA5DB0B@planet.delsci.local> > I don't know how you infer any of those from what I said, nor > from the process of introducing features in Python. None of > what you say there rings at all true with anything I've > experienced in Python's core or the attitudes surrounding > development if the language; indeed, quite the opposite. That has been my experience as well, which is why this particular action seems surprising and out of character. > Speaking of irony, you're complaining about namespace > conflicts with a -two character identifier- you've chosen. > Here's a hint: choose better names. Hey, come on now -- developers working on top of an existing language bear nowhere near the responsibility as the language & implementation maintainers. Also, note that the fields of math and science are filled with short identifiers with well-defined meanings -- brevity doesn't mean ambiguous within a given application domain! But regardless, our scripts use "as" in the same way as Python -- to change the effective appearance of an object, albeit in a representational rather than naming space. So if we're wrong in our choice, then so is Python. In addition, note that my choice of a concise method identifier affects only my users. Python's introduction of a new keyword affects the entire Python world code base, so perhaps you should be directing your "choose better names" criticism in another direction? > To match your honesty, I'm somewhat tired with the trend of > some people to hit -one- issue with Python and suddenly lash > out like children over all the same old tired crap. Have you > even looked at multiprocessing? Have you contributed to any > projects working on GIL- less implementations? Or are you > just regurgitating the same bullet points we've heard time > and time again? Multiprocessing solves some problems, but it is unsuitable for high-frequency handoffs of large (in memory) objects between many independent threads/processes -- the HPC object/data flow parallelization model in a nutshell. Furthermore, not every coder has the compsci chops to work on language & VM implementations (my PhD involved programming DNA and directing evolution in a test tube, not parse trees and state machines). But that isn't to say I didn't try: at one point I even sketched out a possible TLS-based GIL workaround for handling the issue without breaking the existing C/API. It was of course shunned by those who knew better...for performance reasons IIRC. > For chrissake, if you cannot do ANYTHING but BITCH about a > change, then you've no damn right to consider yourself a > programmer. Real programmers find solutions, not excuses. Though I have certainly bitched about the threading issue multiple times on mailing lists including baypiggies and python-dev, bitching is not the only thing I've done. Having come to grips with my own coding limitations, I also offered to contribute financial resources from my own Python-enhanced business in support of GIL-removal -- before Python 3.0 was finalized. Unfortunately, no one responded to my offer. Even today, I am indirectly proposing the solution of "as" not being a reserved keyword since it has worked just fine for years without it. Yes that's late, but I didn't see this particular trainwreck coming (since it is not actually our current code which breaks, but rather, quantities of code created years ago but which must still run with fidelity into the far off future). Installing a Python macro preprocessor is another after-the-fact possible solution which may bear further investigation... Also today, I am proposing a pragmatic general solution for projects like ours in addressing both the 2.6/3.0 compatibility and threading situations. Specifically: deliberate migration away from C/Python and on to alternate VMs which happen to support Python syntax. Obviously none of my past efforts yielded fruit -- but it is wrong and unfair of you to assume and accuse me of not trying to come up with solutions. Solutions are virtually the entire game! > > And if so, then thank you all for so many wonderful years of effort > > and participation! > > You're welcome. Don't let the door hit you on the ass on your way out. But who's leaving who exactly? Surely a language as beautiful as Python will easily transcend the limitations of its flagship implementation (if or to the extent that such an implementation cannot keep pace with the times). That's all well and good -- it may even end up being the next great leap forward for the language. I believe Guido has even said as much himself. Warren From Russ.Paielli at gmail.com Sun Dec 7 19:18:02 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 7 Dec 2008 16:18:02 -0800 (PST) Subject: Python for kids? References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> Message-ID: <3f1995ed-ccdf-4dd1-89ee-8a30b85db2df@i24g2000prf.googlegroups.com> On Dec 7, 12:13?pm, "Russ P." wrote: > I have a 12-year-old son who spends too much time playing Xbox live > and watching silly YouTube videos. I would like to try to get him > interested in programming. Is anyone aware of a good book or website > that addresses this concern, preferably (but not necessarily) using > Python? I could try to teach him Python myself, but I'm afraid I would > just frustrate him and kill his interest in programming. I did a > Google search and found a few things, but not a lot. Thanks. From bignose+hates-spam at benfinney.id.au Thu Dec 4 22:17:05 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 05 Dec 2008 14:17:05 +1100 Subject: RELEASED Python 3.0 final References: Message-ID: <874p1jux8u.fsf@benfinney.id.au> James Stroud writes: > comp.lang.python3k ? The language has undergone an incompatible divide. Hopefully the community need not do the same. -- \ ?People come up to me and say, ?Emo, do people really come up | `\ to you??? ?Emo Philips | _o__) | Ben Finney From levub137 at wi.rr.com Mon Dec 29 10:59:00 2008 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Mon, 29 Dec 2008 09:59:00 -0600 Subject: math module for Decimals Message-ID: <4958F3C4.1050103@wi.rr.com> Since the interest is more in extended precision than in decimal representation, there is another module that may be of interest. http://calcrpnpy.sourceforge.net/clnum.html It interfaces to the Class Library for Numbers (CLN) library to provide both arbitrary precision floating point and complex floating point numbers and the usual math functions. While I am the author of this module, I agree with Mark that a module based on MPFR would be better since you have better control over precision and rounding. I have looked at Sage (which uses MPFR) but it is a huge integrated package so you can't just import what you need into one of your usual Python scripts. I wrote the clnum module mainly to support arbitrary precision in an RPN calculator available from the same SourceForge project. However, it also works nicely as a stand-alone module. At this time, there is no Windows installer available for Python 2.6 because I don't use Windows at home and the person who normally builds the installer for me is no longer interested. If someone wants to follow the published instructions and send me the resulting installer, I will put it up on SourceForge. Ray Jerry Carl wrote: >> 1. mpmath? > 2. sympy? > 3. Sage? Haven't tried those, i guess i have some studying to do. > > x=Decimal.__mod__(x,Decimal('2')*pi()) > > Works fine for what i need, but i am sure it's not the right way to do > > it. > I don't know of any better way to deal with large arguments. > The main problem is that the reduction step can introduce fairly > large errors: for example, if you're using a value of pi > that's accurate to 10**-20, say, then reducing something of > magnitude 10**5*pi will give a result with error of around > 10**-15. As far as I know, this problem is essentially > unavoidable, and it's the reason why implementing sin for inputs > like 10**999999999 isn't feasible. Good point. No tool will work in all parts of the universe (which is especially true for the universal ski wax). Let me check the 3 modules you listed above! From prologic at shortcircuit.net.au Mon Dec 8 09:38:06 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 9 Dec 2008 00:38:06 +1000 Subject: Beginner trying to understand functions. In-Reply-To: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> Message-ID: On Tue, Dec 9, 2008 at 12:24 AM, cadmuxe wrote: > i think we should use raw_input('Please enter your name: ') instead of > input('Please enter your name: ') Good point :) OP: Please take notes :) cheers James -- -- -- "Problems are solved by method" From jarausch at igpm.rwth-aachen.de Wed Dec 3 05:50:48 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Wed, 03 Dec 2008 11:50:48 +0100 Subject: Is it safe to modify the dict returned by vars() or locals() In-Reply-To: References: <4934508b$0$2861$ba620e4c@news.skynet.be> <4935011A.9080406@igpm.rwth-aachen.de> Message-ID: <49366488.80602@igpm.rwth-aachen.de> Duncan Booth wrote: > Helmut Jarausch wrote: > >> Chris Rebert wrote: >>> On Mon, Dec 1, 2008 at 1:01 PM, Helmut Jarausch >>> wrote: >>>> Hi, >>>> >>>> I am looking for an elegant way to solve the following problem: >>>> >>>> Within a function >>>> >>>> def Foo(**parms) >>>> >>>> I have a list of names, say VList=['A','B','C1'] >>>> and I like to generate abbreviation >>>> _A identical to parms['A'] >>> Could you explain what you mean by that? Your sample code doesn't >>> seem to do any "abbreviation"... >>> Otherwise I don't see why you don't just have a proper parameter >>> list. >> In my application parms contains field names of an html form iff these >> fields have been modified. >> I'd like to use the short name _A instead of the longer expression >> parms['A'] >> >> > You haven't yet explained why you don't just do: > > def foo(A=None, **parms): > ... > > The code to call foo remains the same as before, but Python will unpack > the named parameter into the local variable A for you automatically. Any > other parms that you didn't know about in advance remain in the separate > dictionary. > Many thanks, that's a very elegant solution. Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From manu3d at gmail.com Sat Dec 13 19:05:48 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Sat, 13 Dec 2008 16:05:48 -0800 (PST) Subject: Bidirectional Networking References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <98a6c3cd-181c-43c9-805b-fb0689c69544@a26g2000prf.googlegroups.com> Message-ID: <29283382-3e26-492a-8612-9352f32c1c01@r15g2000prd.googlegroups.com> On Dec 13, 11:13 pm, Bryan Olson wrote: > Software firewalls will often simply refuse incoming connections. The > basic protection of the garden-variety home router comes from "network > address translation" (NAT), in which case TCP connections initiated from > the inside will generally work, regardless of port, and incoming > connections will fail. Ok, I think I'm getting the picture here. So this means that in most circumstances where the data flow from the server is frequent the client initiates the connection, usually requests some initial data and keeps polling the server periodically, issuing new requests. In this context can the client simply keep the connection alive and listen for new data from the server coming at any time rather than actively issuing requests? Are there drawbacks to this strategy? I.e. is there a limit to the number of simultaneous connections a server can keep alive? I've noticed that the socket pages mention a 5 connections limit. Is that it? What if I want to make a virtual room with 20 people connected simultaneously? > > or would it be the responsibility of the user > > to configure the firewall so that the application can receive a > > connection? > > That can be a huge hassle. The first choice is for the application to > conform to popular firewall policies, so no special configuration is > required. I agree, I'd rather have the user do nothing in this regard. I'm just wondering how it's done with data intensive application where the server needs to send new data to the client frequently. Does the client just keep the connection live at all time for the server to send stuff or does the client continuously open, sends a request, receives data and closes the connection every time? Here I'm thinking about an online game, with 100 players moving their avatars. Does the client requests their position nearly every frame? Manu From bj_666 at gmx.net Sat Dec 13 06:35:24 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 13 Dec 2008 11:35:24 GMT Subject: Umlauts in idle References: <26880ecf-d0eb-42ab-8ebd-56f64c023999@v39g2000pro.googlegroups.com> <4943829B.9050606@v.loewis.de> Message-ID: <6qhkvsFclvujU2@mid.uni-berlin.de> On Sat, 13 Dec 2008 02:58:48 -0800, a_olme wrote: > On 13 Dec, 10:38, "Martin v. L?wis" wrote: >> > When I try to use umlauts in idle it will only print out as Unicode >> > escape characters. Is it possible to configure idle to print them as >> > ordinary characters? >> >> Did you really use the print statement? They print out fine for me. >> >> Regards, >> Martin > > No I just put the characters in quotes like this "???"[::-1] and pressed > return. Then you have two problems: First, you don't have unicode characters but a bunch of bytes which encode the three characters you've showed above. Reversing the bytes might "break" them if your system uses multiple bytes to encode one character, e.g. UTF-8, because the order does matter. Second, if you don't ``print`` but let the interpreter show the result you get the `repr()` form of that character displayed, which always uses escapes for bytes that are non-printable or not within the ASCII range for strings. Ciao, Marc 'BlackJack' Rintsch From pietersteenekamp at gmail.com Wed Dec 3 03:32:22 2008 From: pietersteenekamp at gmail.com (pieter) Date: Wed, 3 Dec 2008 00:32:22 -0800 (PST) Subject: How to use a Python function that returns a double array in C++. Message-ID: <24b01c57-0197-4971-9489-47345a2777f7@h20g2000yqn.googlegroups.com> I want to use a Python function that returns a double array in C++. I don?t have a problem if the Python function returns a single variable of type double, using the following lines in my C++ code: myPythonObjectPointer = PyObject_CallObject(pFunc, pArgs); myCppDoubleVariable = PyFloat_AsDouble(myPyObjectPointer); (I have obviously done all the required thingies to embed Python in C+ + as per the Python documentation) I can achieve what I want by changing the Python function to a number of functions, each returning a single double variable and call them one by one, using code like above, and then passing them into an array in C++, but I would prefer a more elegant way of doing it, because my return variable could have hundreds, if not thousands, of values.. Can somebody help me please. Thanks Pieter Steenekamp. From jstroud at mbi.ucla.edu Thu Dec 4 21:39:35 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 04 Dec 2008 18:39:35 -0800 Subject: RELEASED Python 3.0 final In-Reply-To: References: Message-ID: Barry Warsaw wrote: > On behalf of the Python development team and the Python community, I am > happy to announce the release of Python 3.0 final. comp.lang.python3k ? From bearophileHUGS at lycos.com Sat Dec 6 07:02:54 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 6 Dec 2008 04:02:54 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> Message-ID: <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> Antoine De Groote: > Allowing "$" as a substitute for "self" wouldn't require this new syntax. > class C: > def method($, arg): > $.value = arg I think this (that is just sugar) may be a little better: class C: def method($, arg): $value = arg Or even this, combined with the idea suggested in the post by Guido: class C: def $method(arg): $value = arg (Note there's no point after $, it's not currently possible). Ruby uses @ and @@ for similar purposes. I agree that the code looks worse, but also shorter to read and write, so in lines of code that use many instance attributes, that short $ syntax helps keep the line shorter. So I may grow to accept this sugar... Bye, bearophile From paul.hermeneutic at gmail.com Tue Dec 16 11:38:56 2008 From: paul.hermeneutic at gmail.com (Paul Watson) Date: Tue, 16 Dec 2008 10:38:56 -0600 Subject: help I'm getting delimited In-Reply-To: <817cf531-225b-4c4e-b79b-10d7657b0749@35g2000pry.googlegroups.com> Message-ID: <1229445534.5328.0.camel@linux-3eb6.site> On Tue, 2008-12-16 at 08:26 -0800, aka wrote: > Hi, I'm going nuts over the csv.reader and UnicodeReader class. > Somehow I can't get this method working which is supposed to read a > csv file which name is inputted but here now hardcoded. What I need > for now is that the string version of the list is put out for control. > Later on I will only need to read the first column (id) of the csv > file to be able to fill in a session var with a list of all ids. > inp = c:/temp/test.csv > roles = [] > try: > fp = open(inp, 'rb') > reader = csv.reader(fp) > for r in reader: > rollen.append(r) > except: > msg = "Er is iets mis met de UnicodeReader" > > return dict(file=in,roles=str(roles)) > Any help greatly appreciated! > Cheers Did you intend inside the loop to write: roles.append(r) From joel.hedlund at gmail.com Tue Dec 16 03:36:38 2008 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Tue, 16 Dec 2008 09:36:38 +0100 Subject: weird dict problem, how can this even happen? In-Reply-To: References: Message-ID: Duncan Booth wrote: > It could happen quite easily if the hash value of the object has changed > since it was put in the dictionary. what does the definition of your > core.gui.FragmentInfo object look like? Dunno if it'll help much, but: class FragmentInfo(object): def __init__(self, renderer, render_area): self.renderer = renderer self.render_area = render_area def __hash__(self): return hash((FragmentInfo, self.renderer, self.render_area)) def __eq__(self, other): return (isinstance(other, self.__class__) and other.renderer == self.renderer and other.render_area == self.render_area) > Is the hash definitely immutable? No. It's a hash of a tuple of its key attributes, themselves similar objects. The program can be thought of as a map viewer. In the gui part, image fragments are cached for speed, and fragments are only half rendered if there's a lot of complex features to draw. The "pool" consists of semi rendered fragments. The reason I did it this way is the cache. The cache is a dict with a use tracker so when the hash changes, the older fragments eventually drop from the cache. Hmm... I'm starting to realise now why my implementation of this isn't so hot. I'm going to hazard a guess here, and then you can correct me ok? I create a dict and populate it with a key-value pair, and then the key's hash changes. When the key is returned by k = d.keys(), then k not in d, even though k in d.keys(). Simple example: > class moo(object): > def __init__(self, a): > self.a = a > def __hash__(self): > return hash(self.a) > > d = {moo(1): 1} > > k = d.keys()[0] > k.a = 2 > > k = d.keys()[0] > print k in d, k in d.keys() > d.pop(k) output: > False True > Traceback (most recent call last): > File "/bioinfo/yohell/eclipse/Test/src/test.py", line 14, in > d.pop(k) > KeyError: <__main__.moo object at 0x7f1c64120590> I'd say that's pretty similar to what I observed. I guess the logical outcome is that the cache dict will fill up with old junk that I can't access and can't selectively flush since the hashes have changed, unless I actually somehow save copies of the keys, which can get pretty complex and probably won't do wonders for execution speed. Yeah this was probably a bad soulution. I should probably do this with lists instead because I can't really think of a way of salvaging this. Am i right? Thanks for your help! /Joel From honey33145 at gmail.com Thu Dec 4 04:20:47 2008 From: honey33145 at gmail.com (navneet khanna) Date: Thu, 4 Dec 2008 14:50:47 +0530 Subject: TypeError: not enough arguments Message-ID: Hello Everbody I have imported a class from vb.net dll in Python. I am able to import all the functions, but its showing such error when trying to access it. g() is a simple function in dll which takes no argument but returns a string. print Class1.g() Traceback (most recent call last): File "", line 1, in print Class1.g() TypeError: not enough arguments Please help me out. Thanks Navneet -------------- next part -------------- An HTML attachment was scrubbed... URL: From notvalid2 at sbcglobal.net Tue Dec 16 21:46:30 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Tue, 16 Dec 2008 18:46:30 -0800 Subject: WinMerge--B/W Shading of Printed Copy to Show Differences? In-Reply-To: References: <3jX1l.6876$pr6.3299@flpi149.ffdc.sbc.com> Message-ID: Jason Scheirer wrote: > On Dec 16, 3:56 pm, "W. eWatson" wrote: >> Is there a way to highlight differences between the two files when printing >> in b/w? Help suggests there may be some texturing, but all I see is color >> choices. >> -- >> W. eWatson >> >> (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) >> Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet >> >> Web Page: > > WinMerge is written in C++ and not even remotely related to Python. Well, yes, but it has applicability to Python (and maybe other languages) in that I can use it to find differences between two sets of code. If not here, where? comp.lang.??? ? -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From ebuyvip at hotmail.com Mon Dec 22 00:32:50 2008 From: ebuyvip at hotmail.com (Jacky) Date: Sun, 21 Dec 2008 21:32:50 -0800 (PST) Subject: Discount (paypal) www.ebuyvip.com nfl jersey ugg boots Message-ID: <8f870e86-4af3-458d-92ea-8a01d291b739@s9g2000prm.googlegroups.com> Hi friend Thanks for your reply. The current stock list with the available jerseys and sizea in the add annex, pls check it. and the jerseys pictures you can check my ablum : http://likenfl.photo.163.com . the moq order: 10 pcs the price : $20 inc shipping fee and tax.If you worry do businees with me first. and cann't trust me, the payment we can by paypal. that we all can trust other. If you have any questions pls tell me , i will give you a satisfaction answer. Hope we can have a nice and long term cooperation. UGG BOOTS: $45 NFL JERSEY: $20 Website: www.ebuyvip.com MSN: ebuyvip at hotmail.com Waiting for your good news. Best Regard Jarky From Eric_Dexter at msn.com Mon Dec 15 12:08:30 2008 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Mon, 15 Dec 2008 09:08:30 -0800 (PST) Subject: Getting in to metaprogramming References: <6cd0d1c2-90ed-4dad-94bf-3e98ddf89118@o40g2000prn.googlegroups.com><842a1a1d-42bd-440d-b4b5-57170adb2f37@l42g2000yqe.googlegroups.com><7832d70e-7bb9-469d-9edd-0864c3bb357d@b38g2000prf.googlegroups.com><15fec804-feb6-48ce-85cc-efbb9a5e30cb@33g2000yqm.googlegroups.com><013d5a5b$0$11497$c3e8da3@news.astraweb.com> Message-ID: On Nov 27, 9:56?pm, "Hendrik van Rooyen" wrote: > ?"Steven D'Aprano" > > >GUI designer. You write a program to let the user create code by clicking > >buttons, dragging objects, drawing lines, etc. The GUI designer may use > >classes, but the purpose of those classes is to generate source code. > > Yikes, this is getting hairy- If "the problem" is to generate source code, > then you have to generate source code... > > >Testing code speed... you might have some functions with a loop, and you > >want to unroll the loop as an optimization. If you have one function, you > >can unroll it yourself. If you have a hundred such functions, you might > >want to write a program to do it. (Yes, I'm stretching...) > > Ok this one I'll buy - I can't think of a way to do this dynamically in a > class and get runnable code back. (but maybe I'm just not trying hard enough.) > > > > >Don't like that Python doesn't optimize tail-recursion? Then write a > >source-code analyzer that detects tail-recursion and re-writes the > >function using a while loop. > > This is like TJR's example (I think) > > > > > > >>> Thinking further back, when I was young and programming in Apple's > >>> Hypercard 4GL, I used to frequently use Hypercard scripts to generate > >>> new Hypercard scripts. That was to work around the limitations of the > >>> scripting language. > > >> What sort of stuff did you do, and would having had simple OO available > >> have rendered it unnecessary? > > >It's been 20-odd years, and the examples were pretty trivial... I don't > >really recall exactly, but it would have been something like this: > > >* design a GUI involving lots of buttons on screen, each one with quite > >similar but not identical code; > > >* since Hypercard didn't have a layout manager, write a script to > >generate each button, place it where needed, and set the button's code. > > >Hypercard did have a message passing hierarchy (like inheritance for > >objects), so often you could take the button's code and place it in a > >higher level of the hierarchy (the card, the background, the stack), but > >there were odd cases where that wasn't enough. > > >Another example: Hypercard had a very limited number of GUI elements > >(text fields and buttons, basically) but I designed a slider control > >using a few buttons, each button with a custom script. To avoid needing > >to create and place the buttons by hand each time I wanted a slider, I > >had a script that did it for me. The script not only created the buttons, > >but it created the scripts used by the buttons. This wasn't as difficult > >as it sounds -- it was basically taking a template and doing some text > >replacements, then telling the button to use it as a script. > > Ok I think I am beginning to get the picture - when you have to do stuff > that the language does not directly support, then you use the simple > available elements, and create source code that strings them together > to make more complex stuff. -in this case its probably not trivial to > do it at run time. > > The "make the source code" then run it, introduces a kind of compiler > stage. > > For an old assembler programmer, this is starting to sound like macros. > > So a different meta law would read like: > > One uses Code Generation Techniques when the language does not > have macros. > > *ducks* > > - Hendrik- Hide quoted text - > > - Show quoted text - I have been converting stuff like sound 100, 1 exc... and just writing like 100, 1 for a number of languages and then just loading it into a spreadsheet so that I can save little pieces of songs exc.. I can even use different compilers or libraries that way.. I have started doing that for quickbasic, qbasic, free basic, qb64, c++.... All I do is use strings and '\n'.. I get to use a large number of older sounds and effects (for basic) on newer compilers that have aditional options.. It just looks like another music tracker.. I am not sure if that fits what you are trying to do though. From wuwei23 at gmail.com Thu Dec 4 07:22:32 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 4 Dec 2008 04:22:32 -0800 (PST) Subject: "as" keyword woes References: Message-ID: On Dec 4, 7:28?pm, "Warren DeLano" wrote: > But who's leaving who exactly? ?Surely a language as beautiful as Python > will easily transcend the limitations of its flagship implementation (if > or to the extent that such an implementation cannot keep pace with the > times). ?That's all well and good -- it may even end up being the next > great leap forward for the language. ?I believe Guido has even said as > much himself. Warren, thank you for a far more reasonable response than my post warranted. There seems a trend on this group for frustration to turn into ultimatums, which is what really triggered my outburst. Well, that and a crappy day at work. As for your above comment, I totally agree. It's probably the main outcome I'd like to see arise from the PyPy project: faster and easier experimentation with implementations. Nothing like some additional evolutionary pressure to make Python more fit. Good luck with resolving your current issue. From wyldwolf at gmail.com Fri Dec 5 15:27:59 2008 From: wyldwolf at gmail.com (Kevin Kelley) Date: Fri, 5 Dec 2008 14:27:59 -0600 Subject: Problems running on hp duo Pentium R processor In-Reply-To: <200812051502.26421.inq1ltd@inqvista.com> References: <200809221443.25765.inq1ltd@inqvista.com> <200809221446.29472.inq1ltd@inqvista.com> <200812051502.26421.inq1ltd@inqvista.com> Message-ID: <77895c1d0812051227o104ff233m7f16410e3cf8b392@mail.gmail.com> If they are running standard Win XP (Home or Pro), as opposed to 64-bit Win XP, then whether or not the CPU supports the IA64 instruction set really doesn't matter. As far as I know every Intel Core2 and Pentium Dual-Core CPU since ~ 2006 has supported 64bit instructions, even the Atom is 64bit. Also, the "R" is for Registered Trademark (of Pentium), it's not part of the name/model (http://ark.intel.com/cpu.aspx?groupId=33925). Kevin On Fri, Dec 5, 2008 at 2:02 PM, jim-on-linux wrote: > Python help, > > In September I wrote: > I have a number of clients running a program built > with python 2.5. One has just purchased an HP with > a duo core Pentium R processor E2200, 2.2G with .99g > ram. > > Only on the new HP, when they try to print they get an > import error; > File win32ui.pyc line 12, in > File win32ui.pyc, line 10, in _load > ImportError: DLL load failed: The specified module > could not be found. > > It turns out that the E2200 processor is 64 bit > architecture. > > What are my options? > > I've run DependecyWalker, > They are using Win XP Service Pack 2 > > > > jim=on-linux > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From 5lvqbwl02 at sneakemail.com Sun Dec 28 03:44:51 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Sun, 28 Dec 2008 00:44:51 -0800 (PST) Subject: Doing set operation on non-hashable objects References: <3a87eb6a-13ff-4aea-8835-3a233cc6cfc4@w39g2000prb.googlegroups.com> Message-ID: <911b1a97-53e7-4f45-bb6f-ae1b8a3d34d1@g1g2000pra.googlegroups.com> > > ... "db" is a dict, where the values are also dicts. > > A function searches through db and returns a list of values, each of > > which is a dict as described above. > > I need to perform set operations on these lists (intersection and > > union) > > However the objects themselves are not hashable, and therefore can't > > be in a set, because they are dicts. > > I'm not sure how large each set will be, but the point is I'm trying > > to avoid anything looking like an O(n^2) algorithm, so I can't just > > use naive double-looping to check for intersection/union on a pair of > > lists. > > Well, if the lists are ordered, you can do intersection and union > in O(n) time. ?If they are orderable, you can sort each first, giving > O(n log n). ?Note you can do lst.sort(key=id) which will sort on ids. The lists are not ordered, since the elements of the list could be arbitrarily complex things consisting of resistors, capacitors, sub- circuits, etc. I'm trying do a little EDA program, taking the best parts from the different EDA/cad tools I've used. I finally came up with an idea using dictionaries in a certain way, so I'd like to be able to do set operators on arbitrary things that may themselves not be hashable. > > How do you get the object back from an ID in python? > > You don't; you remember the mapping in a dictionary and look it up. Exactly. A mapping between the ID and the thing itself. > If there were a way to go from id to object, the whole idea of garbage > collection and reference counts would fly out the window, leading to > nasty crashes (or you might get to an object that is the re-used id of > an older object). Yup, this makes perfect sense. It was rattling around in my head for a bit afer I wrote the original post, then this makes sense. > From steve at holdenweb.com Wed Dec 17 06:18:36 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 17 Dec 2008 06:18:36 -0500 Subject: regex problem .. In-Reply-To: <3b10c2060812170303w1cd8ecdmad7c97c42e44f08@mail.gmail.com> References: <3b10c2060812150421y1c3e7da6ha1b72c736e2a20d4@mail.gmail.com> <3b10c2060812170303w1cd8ecdmad7c97c42e44f08@mail.gmail.com> Message-ID: <4948E00C.2020006@holdenweb.com> Analog Kid wrote: > Hi guys: > Thanks for your responses. Points taken. Basically, I am looking for a > combination of the following ... > [^\w] and %(?!20) ... How do I do this in a single RE? > > Thanks for all you help. > Regards, > AK > > On Mon, Dec 15, 2008 at 10:54 PM, Steve Holden > wrote: > > Analog Kid wrote: > > Hi All: > > I am new to regular expressions in general, and not just re in python. > > So, apologies if you find my question stupid :) I need some help with > > forming a regex. Here is my scenario ... > > I have strings coming in from a list, each of which I want to check > > against a regular expression and see whether or not it "qualifies". By > > that I mean I have a certain set of characters that are > permissible and > > if the string has characters which are not permissible, I need to flag > > that string ... here is a snip ... > > > > flagged = list() > > strs = ['HELLO', 'Hi%20There', '123123@#@'] > > p = re.compile(r"""[^a-zA-Z0-9]""", re.UNICODE) > > for s in strs: > > if len(p.findall(s)) > 0: > > flagged.append(s) > > > > print flagged > > > > my question is ... if I wanted to allow '%20' but not '%', how > would my > > current regex (r"""[^a-zA-Z0-9]""") be modified? > > > The essence of the approach is to observe that each element is a > sequence of zero or more "character", where character is "either > letter/digit or escape." So you would use a pattern like > > "([a-zA-Z0-9]|%[0-9a-f][0-9a-f])+" > > Did you *try* the above pattern? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From victorsubervi at gmail.com Fri Dec 26 10:01:54 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 26 Dec 2008 16:01:54 +0100 Subject: =?ISO-8859-1?Q?Can=B4t_Surf_Python_Pages_in_Windoze?= Message-ID: <4dc0cfea0812260701q6baf0ccbj154c5b3fa2281cdb@mail.gmail.com> Hi; I try to surf to this code in Windoze and it doesn't work...just posts a small, black screen for a split second. Why? print "Content-Type: text/html" print print """ Yeah """ Also, Zope is installed, but when I go to: localhost:8080/manage_main or local:8080/Zope-Instance/manage_main I get a 404, after having started the service and everything is go. I have Python up. What gives? Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Tue Dec 23 03:46:59 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 23 Dec 2008 08:46:59 +0000 Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> <1iscu14.oixxplpgajabN%pdorange@pas-de-pub-merci.mac.com> Message-ID: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) writes: > def sign_0(x): > if x==0.0: > return 0.0 > elif x>0.0: > return 1.0 > else: > return -1.0 > This might be slightly faster: def sign(x): return 1 if x > 0 else x and -1 -- Arnaud From pavlovevidence at gmail.com Sat Dec 6 22:40:58 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 6 Dec 2008 19:40:58 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> <845f784f-8dcd-4f18-ae78-3f528f179b3e@r15g2000prd.googlegroups.com> Message-ID: <94791ba5-b58d-437c-89b6-fc08d142725f@j11g2000yqg.googlegroups.com> On Dec 6, 6:42?pm, "Russ P." wrote: > > But it's ugly. ?No amount of rationalization will make it not ugly. > > The dollar sign is ugly? I beg to differ. Nope, you're wrong. Carl Banks (See where this is going?) From jon at ffconsultancy.com Mon Dec 1 19:06:22 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Tue, 02 Dec 2008 00:06:22 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: Xah Lee wrote: > And on this page, there are sections where Mathematica is compared to > programing langs, such as C, C++, Java, and research langs Lisp, > ML, ..., and scripting langs Python, Perl, Ruby... Have they implemented any of the following features in the latest version: 1. Redistributable standalone executables. 2. Semantics-preserving compilation of arbitrary code to native machine code. 3. A concurrent run-time to make efficient parallelism easy. 4. Static type checking. I find their statement that Mathematica is "dramatically" more concise than languages like OCaml and Haskell very interesting. I ported my ray tracer language comparison to Mathematica: http://www.ffconsultancy.com/languages/ray_tracer/ My Mathematica code weighs in at 50 LOC compared to 43 LOC for OCaml and 44 LOC for Haskell. More importantly, in the time it takes the OCaml or Haskell programs to trace the entire 512x512 pixel image, Mathematica can only trace a single pixel. Overall, Mathematica is a whopping 700,000 times slower! Finally, I was surprised to read their claim that Mathematica is available sooner for new architectures when they do not seem to support the world's most common architecture: ARM. Also, 64-bit Mathematica came 12 years after the first 64-bit ML... Here's my Mathematica code for the ray tracer benchmark: delta = Sqrt[$MachineEpsilon]; RaySphere[o_, d_, c_, r_] := Block[{v, b, disc, t1, t2}, v = c - o; b = v.d; disc = Sqrt[b^2 - v.v + r^2]; t2 = b + disc; If[Im[disc] != 0 || t2 <= 0, \[Infinity], t1 = b - disc; If[t1 > 0, t1, t2]] ] Intersect[o_, d_][{lambda_, n_}, Sphere[c_, r_]] := Block[{lambda2 = RaySphere[o, d, c, r]}, If[lambda2 >= lambda, {lambda, n}, {lambda2, Normalize[o + lambda2 d - c]}] ] Intersect[o_, d_][{lambda_, n_}, Bound[c_, r_, s_]] := Block[{lambda2 = RaySphere[o, d, c, r]}, If[lambda2 >= lambda, {lambda, n}, Fold[Intersect[o, d], {lambda, n}, s]] ] neglight = N at Normalize[{1, 3, -2}]; nohit = {\[Infinity], {0, 0, 0}}; RayTrace[o_, d_, scene_] := Block[{lambda, n, g, p}, {lambda, n} = Intersect[o, d][nohit, scene]; If[lambda == \[Infinity], 0, g = n.neglight; If[g <= 0, 0, {lambda, n} = Intersect[o + lambda d + delta n, neglight][nohit, scene]; If[lambda < \[Infinity], 0, g]]] ] Create[level_, c_, r_] := Block[{obj = Sphere[c, r]}, If[level == 1, obj, Block[{a = 3*r/Sqrt[12], Aux}, Aux[x1_, z1_] := Create[level - 1, c + {x1, a, z1}, 0.5 r]; Bound[c, 3 r, {obj, Aux[-a, -a], Aux[a, -a], Aux[-a, a], Aux[a, a]}]]]] scene = Create[1, {0, -1, 4}, 1]; Main[level_, n_, ss_] := Block[{scene = Create[level, {0, -1, 4}, 1]}, Table[ Sum[ RayTrace[{0, 0, 0}, N at Normalize[{(x + s/ss/ss)/n - 1/2, (y + Mod[s, ss]/ss)/n - 1/2, 1}], scene], {s, 0, ss^2 - 1}]/ss^2, {y, 0, n - 1}, {x, 0, n - 1}]] AbsoluteTiming[Export["image.pgm", Graphics at Raster@Main[9, 512, 4]]] -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From clp at rebertia.com Sun Dec 21 01:56:07 2008 From: clp at rebertia.com (Chris Rebert) Date: Sat, 20 Dec 2008 22:56:07 -0800 Subject: Question: Evaluate an string variable's value to a variable In-Reply-To: <4be6e91b-9fcf-4c22-bfe8-fad73190f87c@b41g2000pra.googlegroups.com> References: <4be6e91b-9fcf-4c22-bfe8-fad73190f87c@b41g2000pra.googlegroups.com> Message-ID: <47c890dc0812202256t392dbd31s8fccded455893d53@mail.gmail.com> On Sat, Dec 20, 2008 at 10:49 PM, Mir Nazim wrote: > Just a quick question. > > For example I have > >>>> class X >>>> ....pass > > Then I do >>>> x = X() >>>> x.name = 'Nazim > > Now my question is whether something like below is possible and how >>>> y = 'name' >>>> print x.y # How can x.y can be evaluated to x.name print getattr(x, y) #==> Nazim There are also analogous setattr() and delattr() functions. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From google at mrabarnett.plus.com Thu Dec 4 13:28:35 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 04 Dec 2008 18:28:35 +0000 Subject: python an sqlite objects In-Reply-To: References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <18742.47391.389709.119341@montanaro-dyndns-org.local> Message-ID: <49382153.80604@mrabarnett.plus.com> Bryan Olson wrote: > Gerhard H?ring wrote: >> Be sure to save it as BLOB, not TEXT. >> >> Suppose you have serialized your object as Python bytestring. >> >> serialized = ... >> ... .execute("insert into mytable(mycolumn) values (?)", >> (sqlite3.Binary(serialized),)) >> >> This way you will get a BLOB in the form of a Python buffer object when >> you later select it from the database [...] > > Good advice for now, with Python 2.X. Python 3 resolves most of > confusion with its distinction between the string type and the bytes > types. The 3.x standard library sqlite3 module understands the 'bytes' > and 'bytearray' types, and treats them appropriately. > > Here's a runnable Python 3 demo: > > # Ensure that we're running Python 3 or later. > import sys > assert int(sys.version.split()[0].split('.')[0]) >= 3 > # If there's a better way to chek, please tell. > [snip] Why split on whitespace and then '.'? assert int(sys.version.split('.')[0]) >= 3 From python-url at phaseit.net Wed Dec 3 13:47:43 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Wed, 3 Dec 2008 18:47:43 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Dec 3) Message-ID: QOTW: "Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out." - GHUM Strategies for developing effective sets of unit tests: http://groups.google.com/group/comp.lang.python/t/e850a45655099217/ Python became more popular than Perl, acording to TIOBE index: http://groups.google.com/group/comp.lang.python/t/fb650cf462bf8f16/ A design problem shows that inheritance isn't always the right relationship between classes: http://groups.google.com/group/comp.lang.python/t/8f8c96c27f2425c2/ Another design question: instance attributes vs. class attributes vs. function arguments: http://groups.google.com/group/comp.lang.python/t/3982be22cc4a0633/ Modules are singletons usually, but beware of duplicate imports under different names: http://groups.google.com/group/comp.lang.python/t/51dd881f83adeb35/ Using module decorators (whatever that means): http://groups.google.com/group/comp.lang.python/t/215216a1e13ba2c6/ Nested functions: are they fast? make the code confusing? when is OK to use them? http://groups.google.com/group/comp.lang.python/t/9d458fc630554307/ Converting a fixed, static function definition into a more generic one: http://groups.google.com/group/comp.lang.python/t/54caf74fd3454b8d/ "Metaprogramming" in Python (Python code generating Python code): http://groups.google.com/group/comp.lang.python/t/d924498ae98e05d3/ Security implications of using open() on untrusted strings: http://groups.google.com/group/comp.lang.python/t/58acb08aac8b62a9/ \w (in a regular expression) does not match all Unicode characters it actually should: http://groups.google.com/group/comp.lang.python/t/669bb61bad1b58d5/ What different editors have to offer (emacs vs eclipse vs vim): http://groups.google.com/group/comp.lang.python/t/dee02886eccfaef2/ This was the longest thread this week - annoying? hilarious? paranoid? Probably worth reading only if you have plenty of time to waste: http://groups.google.com/group/comp.lang.python/t/c403b827231b9a4/ ======================================================================== 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 Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From bignose+hates-spam at benfinney.id.au Fri Dec 19 16:41:56 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 20 Dec 2008 08:41:56 +1100 Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <8763lfetaz.fsf@benfinney.id.au> Michael Torrie writes: > Personally the new string formatter is sorely needed in Python. And > they way it has been implemented is a thing of beauty. Basically the > burden of formatting strings has been moved from the print > statement/function to the objects themselves. This doesn't describe a difference between Python 2.x and Python 3.0. The string formatting in Python 2.x is nothing to do with ?print?, it's implemented in the function that handles the ?%? operator for strings. -- \ ?If consumers even know there's a DRM, what it is, and how it | `\ works, we've already failed.? ?Peter Lee, Disney corporation, | _o__) 2005 | Ben Finney From rhodri at wildebst.demon.co.uk Tue Dec 23 00:50:42 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Tue, 23 Dec 2008 05:50:42 -0000 Subject: Python's popularity In-Reply-To: <5uudnUmykoMD983UnZ2dnUVZ_rrinZ2d@posted.usinternet> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <18767.47566.709705.92@montanaro-dyndns-org.local> <5uudnUmykoMD983UnZ2dnUVZ_rrinZ2d@posted.usinternet> Message-ID: On Tue, 23 Dec 2008 04:35:42 -0000, Grant Edwards wrote: > IIRC, Python came pre-installed on my IBM Thinkpad. However, > it wasn't anyplace the average user would stumble across it... The suggestively named "IBMTOOLS" directory, I believe :-) -- Rhodri James *-* Wildebeeste Herder to the Masses From rt8396 at gmail.com Tue Dec 2 12:28:49 2008 From: rt8396 at gmail.com (r) Date: Tue, 2 Dec 2008 09:28:49 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <9baabb6c-daab-418e-a11f-9162e1fc30f7@k36g2000pri.googlegroups.com> <55c64b7e-3690-480f-88bd-7c2bdf04adc4@k8g2000yqn.googlegroups.com> Message-ID: At least -someone- besides myself has a sense of humor around here. PS James, i will look through my contact list and send you a few "easy" numbers... good luck :) From sjmachin at lexicon.net Wed Dec 3 15:51:44 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 3 Dec 2008 12:51:44 -0800 (PST) Subject: Converting a .xls file to .html References: Message-ID: <7fe462b5-c5df-429a-8fbe-dd2425d66ca4@r36g2000prf.googlegroups.com> On Dec 4, 12:57?am, Tino Wildenhain wrote: > Hi, > > tarun wrote: > > Hello All, > > > I've a .xml file (saved as .xls) that can be opened in Microsoft excel. The file extension is only a vague indication of the *format* of the contents. How was it created? > > Well if its an xml file then just attach a style to it and you can > just view it in a browser w/o involving excel in the first place. > > Also there are lots of xml libraries coming with python so you can > translate it directly into HTML of your choice. > > > I want to write python code that converts this excel file into .html (so > > that it can be viewed as is in an explorer). > > Whats an Explorer? I guess you mean Webbrowser here? > > Now if you manage to have it in Excel, then you could just save > it as HTML (or whatever Microsoft believes is HTML). Possibly an "Internet Explorer" :-) > > If the file is stored elsewhere in Excel-Format, then > you could script that using xlrd (google for it) I'm not sure what "stored elsewhere in Excel-Format" means. Currently xlrd reads only files written by Excel 2.0 up to Excel 2003 in the default "save as .XLS" binary format i.e. "BIFF2" to "BIFF8" format. I'd suggest that the OP inquire further in the python-excel group at http://groups.google.com/group/python-excel ... it would be a good idea to state how the file was created (or supply the first 100 or so bytes for inspection) plus what he really wants to achieve with the file and is this a one-off or regular exercise. HTH, John From castironpi at gmail.com Sat Dec 27 19:21:33 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 27 Dec 2008 16:21:33 -0800 (PST) Subject: game engine (as in rules not graphics) References: Message-ID: <402f625f-b835-4cb8-bcea-523756c489ca@g39g2000pri.googlegroups.com> On Dec 27, 3:02?pm, Martin wrote: > Hello, > > I'd like to get in touch with game development a bit. I'm not talking > about graphics but rather the game rules itself. Something likehttp://en.wikipedia.org/wiki/Monopoly_(game)#Rules, is there even a > general approach to that or should I just go sketch up my rules and > try to implement them. Being totally new to this topic I don't quite > now what to search for to get some decent results that let me make a > mental link between game rules and what the best practices are to > implement them in python (or any other programming language) > > thanks, > martin Not my expertise but here are my $0.02. You are looking for ways to represent rules: buying a house is legal in such and such situation, and the formula for calculating its price is something. You want "predicates" such as InJail, OwnedBy, Costs. Costs( New York Ave, 200 ) InJail( player2 ) OwnedBy( St. Charles Ave, player4 ) LegalMove( rolldie ) LegalMove( sellhouse ) There are rule-based languages out there, such as Prolog. They are equally expressive as Python (you can write a Turing machine in them), but they are more convenient for representing rules in a prog. language. Predicates are more or less equivalent to positive assertions about something. NewYorkAve.cost= 200 player2.injail= True... rolldie.islegal= True Some predicates have to be calculated, rather than stored, but Python descriptors go easy on you for that. Someone else will have to tell you how rule-based programming measures up against object-oriented programming. From ajaksu at gmail.com Tue Dec 23 01:00:36 2008 From: ajaksu at gmail.com (ajaksu) Date: Mon, 22 Dec 2008 22:00:36 -0800 (PST) Subject: python3 urlopen(...).read() returns bytes References: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> <5496b34d-7ce4-4281-9f01-aed12dab9fd3@f33g2000vbf.googlegroups.com> Message-ID: <42ad842c-8d8a-4ff5-a721-0688b7ae20f7@41g2000yqf.googlegroups.com> On Dec 22, 9:05?pm, Christian Heimes wrote: > ajaksu schrieb: > > > That said, a "decode to declared HTTP header encoding" version of > > urlopen could be useful to give some users the output they want (text > > from network io) or to make it clear why bytes is the safe way. > > Yeah, your idea sounds both useful and feasible. A patch is welcome! :) Would monkeypatching what urlopen returns be good enough or should we aim at a cleaner implementation? Glenn, does this sketch work for you? def urlopen_text(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): response = urlopen(url, data, timeout) _readline = response.readline _readlines = response.readlines _read = response.read charset = response.headers.get_charsets()[0] def readline(limit = -1): content = _readline() return str(content, encoding=charset) response.readline = readline def readlines(hint = None): content = _readlines() return [str(line, encoding=charset) for line in content] response.readlines = readlines def read(n = -1): content = _read() return str(content, encoding=charset) response.read = read return response Any comments/suggestions are very welcome. I could use some help from people that know urllib on the best way to get the charset. Maybe after some sleep I can code it in a less awful way :) Daniel From rt8396 at gmail.com Mon Dec 22 17:26:35 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 14:26:35 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <18767.47566.709705.92@montanaro-dyndns-org.local> Message-ID: <19b9ab88-6812-4416-9020-3be16b839fcd@m16g2000vbp.googlegroups.com> On Dec 22, 4:16?pm, Joe Strout wrote: > Alvin ONeal wrote: > > Also worthy of mention: > > I've seen python pre-installed on consumer HP desktops (I think as > > part of a backup/restore script, but I'm not sure) > > It's pre-installed on every Mac (both desktop and laptop), too. > > Cheers, > - Joe I am using a Vista HP right now that came pre-installed with Python. Blew my mind when i found out :). This single reason just reinforced my belief in Python. Now if we can get Python on every windows platform... From wrzesniowy at poczta.onet.pl Fri Dec 19 16:27:33 2008 From: wrzesniowy at poczta.onet.pl (blady) Date: Fri, 19 Dec 2008 13:27:33 -0800 (PST) Subject: Big Tits Big Boobs Message-ID: <10349e34-a52f-428c-aa6a-bf09c9786cf4@z28g2000prd.googlegroups.com> http://yeba.pl/show/movies/6044/pucybutka From benjamin.kaplan at case.edu Tue Dec 2 16:11:59 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 2 Dec 2008 16:11:59 -0500 Subject: Mathematica 7 compares to other languages In-Reply-To: <1B1C50D7-13B3-4E4C-A87F-F4EB4D9C508C@gmail.com> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <1B1C50D7-13B3-4E4C-A87F-F4EB4D9C508C@gmail.com> Message-ID: On Tue, Dec 2, 2008 at 3:39 PM, Petite Abeille wrote: > > On Dec 2, 2008, at 9:21 PM, Lew wrote: > > These are professional software development forums, not some script- >> kiddie cellphone-based chat room. "r" is spelled "are" and "u" should >> be "you". >> > > While Xah Lee arguably represents a cross between "Enfant Provocateur" [1] > and "Evil Clown" [2], this surely qualifies as a "Grammarian" [3] rebuke :D > > Cheers, > It's starting to look like Xah Lee is a Blowhard as well. > > -- > PA. > http://alt.textdrive.com/nanoki/ > > > [1] http://redwing.hutman.net/~mreed/warriorshtm/enfantprovocateur.htm > [2] http://redwing.hutman.net/~mreed/warriorshtm/evilclown.htm > [3] http://redwing.hutman.net/~mreed/warriorshtm/grammarian.htm > -- > > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Tue Dec 16 14:29:44 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 16 Dec 2008 19:29:44 +0000 Subject: Generator slower than iterator? References: Message-ID: Arnaud Delobelle writes: > match_total = dict((key, val()) for key, val in match_counter.iteritems()) Sorry I meant match_total = dict((key, val.next()) for key, val in match_counter.iteritems()) -- Arnaud From marduk at letterboxes.org Tue Dec 9 22:57:36 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Tue, 09 Dec 2008 22:57:36 -0500 Subject: Can't figure out where SyntaxError: can not delete variable 'x' referenced in nested scope us coming from in python >=2.6 In-Reply-To: <014eef7f$0$20670$c3e8da3@news.astraweb.com> References: <014eef7f$0$20670$c3e8da3@news.astraweb.com> Message-ID: <1228881456.11852.3.camel@blackwidow.nbk> On Tue, 2008-12-09 at 22:57 +0000, Steven D'Aprano wrote: [...] > > So is there a way to find the offending code w/o having to go > through > > every line of code in 'foo' by hand? > > Just search for "del x" in your code. Your editor does have a search > function, surely? > > Well, you'd think I'd be smart enough to think of that one, wouldn't you? Actually, how could you since you don't know me ;-)... Anway, I already did that and could not find the offending code. I submitted this bug [1]. I applied the given patch but the line it shows isn't a "del" anything so I'm even more confused. From harish.bhat.m at gmail.com Sat Dec 20 03:06:46 2008 From: harish.bhat.m at gmail.com (Harish) Date: Sat, 20 Dec 2008 00:06:46 -0800 (PST) Subject: Check file is Message-ID: <7caa7d45-ebbe-4c88-bb50-2f01f7315d07@s9g2000prg.googlegroups.com> Hi Friends Is there any utility in python which will help me to read any pdf files? Regards Harish From Alvin.ONeal at gmail.com Wed Dec 24 11:49:35 2008 From: Alvin.ONeal at gmail.com (Alvin ONeal) Date: Wed, 24 Dec 2008 09:49:35 -0700 Subject: Spam??? Message-ID: What's with all the spam on the list? I humbly request that recaptcha or some other sort of captcha be implemented on the registration page. AJ ONeal -------------- next part -------------- An HTML attachment was scrubbed... URL: From mgreene at bdurham.com Wed Dec 24 04:31:21 2008 From: mgreene at bdurham.com (Malcolm Greene) Date: Wed, 24 Dec 2008 04:31:21 -0500 Subject: Strategy for determing difference between 2 very large dictionaries In-Reply-To: <1230111025.22152.1291626575@webmail.messagingengine.com> References: <1230102996.2303.1291616055@webmail.messagingengine.com> <1230106980.12156.1291620725@webmail.messagingengine.com> <1230111025.22152.1291626575@webmail.messagingengine.com> Message-ID: <1230111081.22723.1291627105@webmail.messagingengine.com> Hi Gabriel, > in Python 3.0 keys() behaves as iterkeys() in previous versions, so the above code is supposed to be written in Python 2.x) I understand. Thank you. > note that dict comprehensions require Python 3.0 I'm relieved to know that I didn't miss that feature in my reading of Python's 2.5/2.6 documentation :) > You might use instead: > > dict((key,(dict1[key],dict2[key])) for key in ...) Excellent. Thank you. Regards, Malcolm ----- Original message ----- From: "Gabriel Genellina" To: python-list at python.org Date: Wed, 24 Dec 2008 07:10:16 -0200 Subject: Re: Strategy for determing difference between 2 very large dictionaries En Wed, 24 Dec 2008 06:23:00 -0200, escribi?: > Hi Gabriel, > > Thank you very much for your feedback! > >> k1 = set(dict1.iterkeys()) > > I noticed you suggested .iterkeys() vs. .keys(). Is there any advantage > to using an iterator vs. a list as the basis for creating a set? I You've got an excelent explanation from Marc Rintsch. (Note that in Python 3.0 keys() behaves as iterkeys() in previous versions, so the above code is supposed to be written in Python 2.x) >>> can this last step be done via a simple list comprehension? > >> Yes; but isn't a dict comprehension more adequate? >> >> [key: (dict1[key], dict2[key]) for key in common_keys if >> dict1[key]!=dict2[key]} > > Cool!! I'm relatively new to Python and totally missed the ability to > work with dictionary comprehensions. Yes, your dictionary comprehension > technique is much better than the list comprehension approach I was > struggling with. Your dictionary comprehension statement describes > exactly what I wanted to write. This time, note that dict comprehensions require Python 3.0 -- so the code above won't work in Python 2.x. (It's not a good idea to mix both versions in the same post, sorry!) You might use instead: dict((key,(dict1[key],dict2[key])) for key in ...) but it's not as readable. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list From deets at nospam.web.de Thu Dec 11 18:11:41 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 12 Dec 2008 00:11:41 +0100 Subject: HGE and Python (again) In-Reply-To: <8180969e-9289-4f8c-ab80-30fbc50914d1@g17g2000prg.googlegroups.com> References: <8180969e-9289-4f8c-ab80-30fbc50914d1@g17g2000prg.googlegroups.com> Message-ID: <6qdl1dFc3e1tU1@mid.uni-berlin.de> Cro schrieb: > Good day. > > I've been trying to port HGE (http://hge.relishgames.com) to Python > for more than 4 months now... > HGE is a hardware accelerated 2D game engine. > It comes with the source and examples. In the folder "include", you > can find "hge.h", the file that i am talking about in all the post. > > # > I tried to load the DLL functions with Python Ctypes like this : > [code] >>>> from ctypes import * >>>> HGE = cdll.LoadLibrary("C:/hge181/hge") >>>> HGE.hgeCreate(0x180) > [/code] > But i get this error : "Procedure called with not enough arguments (4 > bytes missing) or wrong calling convention". > The call should be done with hgeCreate(HGE_VERSION) and the constant > is defined as "#define HGE_VERSION 0x180"... > Number 0x180 means 384 in Python. I don't mean what it means in C. > So i am stuck. You are aware that ctypes knows another call for windows dlls with another calling convention? http://docs.python.org/library/ctypes.html#loading-dynamic-link-libraries Looking at the headers, I see #define CALL __stdcall So to me it looks as if you use the wrong DLL-loading mechanism. Diez From bruno.42.desthuilliers at websiteburo.invalid Fri Dec 12 07:56:22 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 12 Dec 2008 13:56:22 +0100 Subject: (Very Newbie) Problems defining a variable In-Reply-To: <11c53a4a-de1e-4bee-ad60-a05befb6cbf4@a12g2000yqm.googlegroups.com> References: <49425146$0$8495$426a74cc@news.free.fr> <11c53a4a-de1e-4bee-ad60-a05befb6cbf4@a12g2000yqm.googlegroups.com> Message-ID: <49425f5c$0$21931$426a74cc@news.free.fr> feba a ?crit : > On Dec 12, 5:56 am, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: (snip) >> I guess you wanted your first test to be: >> >> if bank <= 9999: >> ... (snip) > that's it, thanks! was confused with it being basically in a column of > all >= *. > > I replaced it with > > if bank <= 0: > print("You're in the red!") > quit() > elif bank >= 1 and bank <= 9999: > rate = 0.0060 > elif bank >= 10000 and bank <= 24999: > rate = 0.0085 > elif bank >= 25000 and bank <= 49999: > rate = 0.0124 > elif bank >= 50000 and bank <= 99999: > rate = 0.0149 > elif bank >= 100000: > rate = 0.0173 > else: > print("What's this doing here?") > > which also changes it to keep it from going on forever if you put in a > negative amount. Good point. > Out of curiosity, would you still recommend applying > an 'else' clause in this case? Yes, but I'd use it as a replacement for the last test: # code here ... elif bank >= 50000 and bank <= 99999: rate = 0.0149 else: rate = 0.0173 And finally, I'd simplify the whole damn thing: if bank < 1: print("You're in the red!") quit() elif bank < 10000: rate = 0.0060 elif bank < 25000: rate = 0.0085 elif bank < 50000: rate = 0.0124 elif bank < 100000: rate = 0.0149 else: rate = 0.0173 > I don't see how it could ever be > triggered, even if there's an error of some kind It couldn't, indeed. Which FWIW is a clear indication that the previous test ( elif bank >= 100000:) is redundant !-) HTH From n.kottiyath at gmail.com Sat Dec 6 09:42:57 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Sat, 6 Dec 2008 06:42:57 -0800 (PST) Subject: __import__ problem Message-ID: <8cd0e5b5-e7bc-4fc7-b17b-01e850f340eb@l39g2000yqn.googlegroups.com> Hi all, When I try to import a module via __import__, I am facing ImportError. But, when I tried to import it via usual 'import', it worked fine. Please see below: try: import exact except: logging.exception('Error during importing') try: code = __import__('exact') except: logging.exception('Is it still happening?') The error is as: 2008-12-06 20:06:59,328 ERROR Is it still happening? Traceback (most recent call last): File "C:\django\test\..\test\basic\views.py", line 166, in getValue code = __import__('exact') ImportError: No module named exact Could you please let me know why this is happening? I tried to __import__ 'sys etc, and it worked fine. Is it due to some issue in the path? Regards K From xahlee at gmail.com Mon Dec 8 18:14:18 2008 From: xahlee at gmail.com (Xah Lee) Date: Mon, 8 Dec 2008 15:14:18 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> <8evqj4p342jvcma5saibf54thv7075r88g@4ax.com> Message-ID: <9d5ecca4-3eb8-42ad-b4d8-951719ef874b@n33g2000pri.googlegroups.com> Dear George Neuner, Xah Lee wrote: > >The phenomenon of creating code that are inefficient is proportional > >to the highlevelness or power of the lang. In general, the higher > >level of the lang, the less possible it is actually to produce a code > >that is as efficient as a lower level lang. George Neuner wrote: > This depends on whether someone has taken the time to create a high > quality optimizing compiler. try to read the sentence. I quote: ?The phenomenon of creating code that are inefficient is proportional to the highlevelness or power of the lang. In general, the higher level of the lang, the less possible it is actually to produce a code that is as efficient as a lower level lang.? Xah Lee wrote: > >For example, > >the level or power of lang can be roughly order as > >this: > > >assembly langs > >C, pascal > >C++, java, c# > >unix shells > >perl, python, ruby, php > >lisp > >Mathematica George wrote: > According to what "power" estimation? Assembly, C/C++, C#, Pascal, > Java, Python, Ruby and Lisp are all Turing Complete. I don't know > offhand whether Mathematica is also TC, but if it is then it is at > most equally powerful. it's amazing that every tech geekers (aka idiots) want to quote ?Turing Complete? in every chance. Even a simple cellular automata, such as Conway's game of life or rule 110, are complete. http://en.wikipedia.org/wiki/Conway's_Game_of_Life http://en.wikipedia.org/wiki/Rule_110 in fact, according to Stephen Wolfram's controversial thesis by the name of ?Principle of computational equivalence?, every goddamn thing in nature is just about turing complete. (just imagine, when you take a piss, the stream of yellow fluid is actually doing turning complete computations!) for a change, it'd be far more interesting and effective knowledge showoff to cite langs that are not so-called fuck of the turing complete. the rest of you message went on stupidly on the turing complete point of view on language's power, mixed with lisp fanaticism, and personal gribes about merits and applicability assembly vs higher level langs. It's fine to go on with your gribes, but be careful in using me as a stepping stone. Xah ? http://xahlee.org/ ? From skip at pobox.com Wed Dec 17 16:01:39 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 17 Dec 2008 15:01:39 -0600 Subject: something else instead of PIL? In-Reply-To: References: Message-ID: <18761.26803.980404.494272@montanaro-dyndns-org.local> Reimar> Hi what has happened to PIL? No updates since two years. It's well-written, stable code. As far as I know it does what people want (at least it's done everything I've needed when I've used it). Why should it matter that there hasn't been an official release in two years? -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From clp at rebertia.com Thu Dec 25 19:24:12 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 25 Dec 2008 16:24:12 -0800 Subject: Exec inside a class method to call other class methods? In-Reply-To: <20081226001641.GA22946@sdf.lonestar.org> References: <4953CF57.8080905@sympatico.ca> <20081226001641.GA22946@sdf.lonestar.org> Message-ID: <47c890dc0812251624m7e1c5e55rb538996a52d56675@mail.gmail.com> On Thu, Dec 25, 2008 at 4:16 PM, J. Clifford Dyer wrote: > and so forth. Then your if/else chain can be pulled out to the place where you instantiate each field: > > if data_type=='address': > field=AddressDataField(data) > elif data_type=='due_date': > field=DueDateDataField(data) > else: > field = DataField(data) > And then you use a dictionary of data_type to class to get rid of the if-else chain altogether: type2klass = {'address' : AddressDataField, 'due_date' : DueDateDataField} #etc Klass = type2klass.get(data_type, DataField) #use DataField as fallback default field = Klass(data) Merry Christmas, Chris -- Follow the path of the Iguana... http://rebertia.com From bearophileHUGS at lycos.com Sat Dec 20 20:05:55 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 20 Dec 2008 17:05:55 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> <88a122de-14c6-4025-b36c-9a39bdd50d86@i20g2000prf.googlegroups.com> Message-ID: walterbyrd: > As I understand it, that may have been true at one time. But, Ruby 1.9 > very significantly sped up the language. While Python has been made > slower, Ruby has been made much faster. I have already answered regarding Python3 in this thread. Regarding Ruby you are right, in computer science there are lot of ways to speed up things. So it may be quite possible for Ruby to become "faster" than CPython. For example this may speed up the PythonVM some: "Optimizing direct threaded code by selective inlining": http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.8829&rep=rep1&type=pdf Bye, bearophile From castironpi at gmail.com Sun Dec 14 19:19:32 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 14 Dec 2008 16:19:32 -0800 (PST) Subject: stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <6qll2nFd5qv8U1@mid.individual.net> Message-ID: On Dec 14, 6:04?pm, greg wrote: > Lie Ryan wrote: > > "You know what you just did? You've > > just found a problem that was supposed to be an example of unsolvable > > problem." > > > It has happened before, why not again? > > There's a big difference between an unsolvable problem and an > unsolved problem. In the cases you're talking about, nobody > had solved the problem before, but neither had anybody proved > there was no solution. > > In the case at hand, there is a proof that such an algorithm > is impossible. Overturning that would require finding a > flaw in the proof, which for such a simple proof seems very > unlikely. It's more likely you'd circumvent the assumptions. That is, find an 'outside-the-box' solution. For instance, a deeply parallel architecture could escape the assumption that you can only compare two numbers at a time (per step). The proof's conclusion is still true if its assumption is. From reachrekhakn at gmail.com Fri Dec 26 08:36:15 2008 From: reachrekhakn at gmail.com (reachrekhakn at gmail.com) Date: Fri, 26 Dec 2008 05:36:15 -0800 (PST) Subject: Socket recv function taking longer time Message-ID: Hi, I have designed a recieving system in C. I have used the sockets recv function. The problem I m facing is that the sending system does not wait for the ACK(the amount of time it waits 4 the Ack is too less as the recv takes more time to read the msg), it keeps on sending the same msg again and again even before the recv func has read the whole message and my recieving system gets hanged. How do I solve this. Please Help. Thanks in Advance. From rdmurray at bitdance.com Mon Dec 15 08:13:11 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Mon, 15 Dec 2008 08:13:11 -0500 (EST) Subject: Having Issues with CMD and the 'python' command In-Reply-To: References: Message-ID: On Mon, 15 Dec 2008 at 23:01, James Mills wrote: > On Mon, Dec 15, 2008 at 10:51 PM, Lamonte Harris wrote: >> Every time I start cmd on windows it requires me to "set >> path=%path%;C:\python26" why? I'm getting annoyed... > > "cmd" has _nothing_ to do with Python. > (Top posting corrected.) But the answer is that you need to update your PATH string at the system level. You do that in Control Panel/System/Advanced/Environment variables (it's a button on the advanced screen, which is something that confused me the first time I went looking for it). ObPython: you know, it occurs to me that Windows follows exactly the opposite philosophy from Python when it comes to hierarchy. Python's Zen is "shallow is better than deep", whereas Windows' philosophy is "deep is better than shallow". Every release of Windows seems to bury the things one needs to do to administer the system deeper and deeper inside a nested set of windows...and every time I touch Windows I am reminded how sensible the Python Zen is :) --RDM From python.list at tim.thechases.com Thu Dec 4 12:02:06 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 04 Dec 2008 11:02:06 -0600 Subject: Please fix your clock [was Re: Multiple equates] In-Reply-To: <0147f4b7$0$20670$c3e8da3@news.astraweb.com> References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> <0147f4b7$0$20670$c3e8da3@news.astraweb.com> Message-ID: <49380D0E.7060309@tim.thechases.com> Steven D'Aprano wrote: > Hendrik, I think your PC's clock is wrong. You seem to be posting from > the future. further evidence of the Guido's time-machine[1]. For the secret cabal of core developers who borrow the time-machine, I recommend not sending email from within it. :) -tkc [1] http://catb.org/esr/jargon/html/G/Guido.html From rNOSPAMon at flownet.com Sun Dec 28 19:52:58 2008 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sun, 28 Dec 2008 16:52:58 -0800 Subject: Need help getting MoinMoin to run under SCGI References: Message-ID: So I have a MoinMoin installation running as a cgi and also under wsgi. Since I was on a roll I decided to press my luck and try running it under scgi. Following a suggestion in the following article: http://www.linuxjournal.com/article/9310 I wrote this little server adapter: from MoinMoin.server.server_cgi import CgiConfig, run class Config(CgiConfig): name = 'moin' import scgi import scgi.scgi_server class MoinHandler(scgi.scgi_server.SCGIHandler): def produce_cgilike(self, env, bodysize): run(Config) server = scgi.scgi_server.SCGIServer( handler_class=MoinHandler, port=4000 ) server.serve() It works -- sort of. I can fire it up and get to the login page, but it won't actually let me log in. I'm guessing this is because I haven't munged the CGI form data properly. I thought I'd ask if anyone with experience using SCGI can just tell me what I'm doing wrong before I dive into debugging this. Thanks, rg From wicijowski at gmail.com Mon Dec 29 09:59:18 2008 From: wicijowski at gmail.com (janislaw) Date: Mon, 29 Dec 2008 06:59:18 -0800 (PST) Subject: multiprocessing vs thread performance References: Message-ID: On 29 Gru, 15:52, mk wrote: > Hello everyone, > > After readinghttp://www.python.org/dev/peps/pep-0371/I was under > impression that performance of multiprocessing package is similar to > that of thread / threading. However, to familiarize myself with both > packages I wrote my own test of spawning and returning 100,000 empty > threads or processes (while maintaining at most 100 processes / threads > active at any one time), respectively. > > The results I got are very different from the benchmark quoted in PEP > 371. On twin Xeon machine the threaded version executed in 5.54 secs, > while multiprocessing version took over 222 secs to complete! > > Am I doing smth wrong in code below? Or do I have to use > multiprocessing.Pool to get any decent results? Oooh, 100000 processes! You're fortunate that your OS handled them in finite time. [quick browsing through the code] Ah, so there are 100 processes at time. 200secs still don't sound strange. JW From RBQG84 at motorola.com Mon Dec 29 04:28:47 2008 From: RBQG84 at motorola.com (Narasimhan Raghu-RBQG84) Date: Mon, 29 Dec 2008 17:28:47 +0800 Subject: Windows SSH (remote execution of commands) - Python Automation Message-ID: <7FAD6FCE52421841A11B441DEF3A88CA01F09006@ZMY16EXM70.ds.mot.com> Hi experts, I am looking for some information on how to automate remote login to a UNIX machine using ssh from a windows XP box. Possible way: 1. Use putty (or any other ssh client from windows XP). -- Can be automated with command line parameters. The problem is that I am able to login - Putty window opens up as well. But obviously I am unable to run any commands in that. I need to find something like a handle to that Putty window so that I can execute commands there. Can anyone provide me some help in achieving this ? Thanks, -- Raghu -------------- next part -------------- An HTML attachment was scrubbed... URL: From jpablo.romero at gmail.com Fri Dec 19 02:08:22 2008 From: jpablo.romero at gmail.com (=?ISO-8859-1?Q?Juan_Pablo_Romero_M=E9ndez?=) Date: Fri, 19 Dec 2008 01:08:22 -0600 Subject: eval() and global variables In-Reply-To: References: Message-ID: The hack given by Peter works fine, except in this case: >>> def aaaa(fn): ... f2 = lambda x,y:(x,y,fn(x,y)) ... function = type(f2) ... f3 = function(f2.func_code,dict()) ... print f3 ... >>> aaaa(lambda x,y:x+y) Traceback (most recent call last): File "", line 1, in File "", line 4, in aaaa TypeError: arg 5 (closure) must be tuple >>> Strange... 2008/12/17 Peter Otten <__peter__ at web.de>: > Juan Pablo Romero M?ndez wrote: > >> Suppose this function is given: >> >> def f(x,y): >> return x+y+k >> >> >> Is it possible to somehow assign a value to k without resorting to >> making k global? > > You can replace the function's global dictionary: > >>>> def f(x, y): > ... return x+y+k > ... >>>> function = type(f) >>>> function(f.func_code, dict(k=1))(2, 3) > 6 >>>> k > Traceback (most recent call last): > File "", line 1, in > NameError: name 'k' is not defined > > This is a hack, of course. > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list > From bearophileHUGS at lycos.com Wed Dec 31 03:52:40 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 31 Dec 2008 00:52:40 -0800 (PST) Subject: MemoryError when list append... plz help References: Message-ID: <84780059-0f81-453e-80a3-dc9141b69340@w1g2000prm.googlegroups.com> [BON]: > above sim is floating type. > s.append is totally coducted 60,494,500 times. > but this code raise MemoryError. > > My computer has 4G RAM. > i think it's enough. but it doesn't... Try creating it in a more clean way, here an array of doubles: >>> from array import array >>> a = array("d", [0.0]) * 60494500 This requires about 477 MB to me. Note that I have not used "append" that slows down code a lot and wastes memory, that's what I mean with "clean". If you really need the (i,j) part too (and you may not need it), then you can create two more "parallel arrays". Also a numpy array may be better for such large amount of data. Bye, bearophile From clp at rebertia.com Mon Dec 22 04:53:28 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 22 Dec 2008 01:53:28 -0800 Subject: Basic misunderstanding of generators In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF6024944BB@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF6024944BB@enbmail01.lsi.com> Message-ID: <47c890dc0812220153h2fb80c09ibed9836a9c36f489@mail.gmail.com> On Mon, Dec 22, 2008 at 1:47 AM, Barak, Ron wrote: > Hi All, > > I want to use generators to print lines taken from a gzipped file. > I've never used generators, so probably my problem is basic misunderstanding > of generators. > > In the below program, I expected the last line ("print line_") to print the > first line of the sac.log.gz file. > Instead, I get: > > > > Could you tell me what I'm doing wrong (or point me to a URL that could set > me straight) ? > > Thanks, > Ron. > > > $ cat LogManager_try.py > #!/usr/bin/env python > > import gzip > import os > > class LogStream(): > """ > """ > > def __init__(self, filename): > self.filename = filename > self.input_file = self.open_file(filename) > > def open_file(self, in_file): > """ > The gzip module checks if the input file is a gzipped file, only at > the read stage. > This is why the f.readline() is needed. > """ > try: > f = gzip.GzipFile(in_file, "r") > f.readline() > except IOError: > f = open(in_file, "r") > f.readline() > > f.seek(0) > return(f) > > def next_line(self, in_file): > """ > """ > for line_ in in_file: > yield line_.strip() > > if __name__ == "__main__": > filename = "sac.log.gz" > log_stream = LogStream(filename) generator = log_stream.next_line(log_stream.input_file) #create generator line_ = generator() #get next item from generator print line_ And as you can see, this makes next_line a bit of a misnomer. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From ndbecker2 at gmail.com Thu Dec 18 20:27:36 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 18 Dec 2008 20:27:36 -0500 Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> <6qv7kfFeuf65U1@mid.uni-berlin.de> <015ae9e9$0$20656$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > BTW Neal, your posts aren't word wrapped. When I read your posts, I get > each paragraph as one extremely LONG line scrolling way out to the side. > That's against the Internet standards for both email and Usenet, so could > you please configure your client to word-wrap at (say) 70 characters? > Sorry, it is configured to wrap @76, but it is beta software and perhaps is not working correctly? Odd, when I view my previous posts (knode/gmane) they look fine. From rileyrgdev at gmail.com Mon Dec 1 09:08:04 2008 From: rileyrgdev at gmail.com (Richard Riley) Date: Mon, 01 Dec 2008 15:08:04 +0100 Subject: pydoc enforcement. References: <6ccec696-a8bb-4818-a016-642514677b70@b38g2000prf.googlegroups.com> <6phmg0F82a0lU1@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch writes: > On Sun, 30 Nov 2008 16:27:07 -0800, ken.faulkner at gmail.com wrote: > >> Basically I'm interested adding a check to see if: >> 1) pydoc's are written for every function/method. > > Pylint warns for missing docstrings. > >> 2) There are entries for each parameter, defined by some > predetermined syntax. > > But which syntax? There are several in use out there. Even the (I > think) popular epydoc allows at least three, its own, something JavaDoc > like, and ReST. > > And I dislike forcing to document every parameter. There's lots of code > that is clear just by the names of the parameters and one or two usage > examples in the docs. Forcing to state the obvious again does not add > information for the user and is annoying for the programmer. > >> My idea is that as much as I love dynamic typing, there are times when >> using some modules/API's that have less than stellar documentation. I >> was thinking that if it was possible to enable some switch that >> basically forced compilation to fail if certain documentation criteria >> weren't met. > > But that doesn't enforce good or even real documentation either. Even > worse, you can't spot the undocumented parts of the code anymore, because > now every "docable" object has "documentation" like this just to make the > compiler happy: > > def spam(foo, bar): > """ > :param foo: a foo object. > :param bar: a bar object. > """ > > Which basically tells the same as no documentation at all. > > Ciao, > Marc 'BlackJack' Rintsch +1. Agreed 100%. There is nothing worse than auto generate "useless" documentation or over commenting of "obvious" variables/members. If anything it leads to problems later during maintenance. -- important and urgent problems of the technology of today are no longer the satisfactions of the primary needs or of archetypal wishes, but the reparation of the evils and damages by the technology of yesterday. ~Dennis Gabor, Innovations: Scientific, Technological and Social, 1970 From eckhardt at satorlaser.com Thu Dec 4 08:30:42 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 04 Dec 2008 14:30:42 +0100 Subject: sys.exit and '-i' Message-ID: <4l2l06-qoo.ln1@satorlaser.homedns.org> Hi! The unittest module will invoke sys.exit() after running the tests in order to signal success or failure. However, I sometimes don't want to exit the interpreter but instead e.g. inspect some state or just keep the window open. Normally, using '-i' as commandline argument works, but not in the case here. My questions are: 1. Is that a bug? After all, an explicit request on the commandline was ignored. Is it perhaps simply wrong how the unittest module handles error/success signalling? 2. I can catch the SystemExit exception and ignore it, but that doesn't actually help, because then I get a normal exit even in case of failures. Of course, I could pass that value to sys.exit(), but then I'd be back at the start. Any suggestions? Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From prologic at shortcircuit.net.au Thu Dec 4 06:17:34 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 4 Dec 2008 21:17:34 +1000 Subject: "as" keyword woes In-Reply-To: <10f6ca6d-35d8-45a6-9a3e-dbdd8aacdb78@d23g2000yqc.googlegroups.com> References: <7dudnSS7uIn_KarUnZ2dnUVZ_tTinZ2d@earthlink.com> <10f6ca6d-35d8-45a6-9a3e-dbdd8aacdb78@d23g2000yqc.googlegroups.com> Message-ID: On Thu, Dec 4, 2008 at 9:04 PM, Aaron Brady wrote: [... snip ...] > Does the OP hold the following should be legal? > > if if or or: > and( for ) > if not: > while( def ) I most certainly hope not! :) --JamesMills -- -- -- "Problems are solved by method" From jeff_barish at earthlink.net Sun Dec 21 19:16:41 2008 From: jeff_barish at earthlink.net (Jeffrey Barish) Date: Sun, 21 Dec 2008 17:16:41 -0700 Subject: Beep Message-ID: I use sys.stdout.write('\a') to beep. It works fine on Kubuntu, but not on two other platforms (one of which is Ubuntu). I presume that the problem is due to a system configuration issue. Can someone point me in the right direction? Thanks. -- Jeffrey Barish From bdesth.quelquechose at free.quelquepart.fr Wed Dec 10 14:23:49 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 10 Dec 2008 20:23:49 +0100 Subject: Python is slow In-Reply-To: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: <494024fc$0$7162$426a34cc@news.free.fr> cm_gui a ?crit : (snip FUD) see also: http://groups.google.com/group/comp.lang.python/browse_frm/thread/5cea684680f63c82 by the same troll^M^M^M^M^Msmart guy. From claird at lairds.us Tue Dec 2 20:23:53 2008 From: claird at lairds.us (Cameron Laird) Date: Wed, 3 Dec 2008 01:23:53 +0000 Subject: Multiple equates References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> Message-ID: <9m3h06-vhh.ln1@lairds.us> In article , Lawrence D'Oliveiro wrote: >In message , Cameron Laird wrote: > >> In article , >> Lawrence D'Oliveiro wrote: >> >>>Cameron Laird wrote: >>> >>>> I've been trying to decide if there's any sober reason to advocate >>>> the one-liner >>>> >>>> map(lambda i: a.__setitem__(i, False), [x1, x2, x3, ..., x1024]) >>> >>>Are lambdas like the Dark Side of Python? >>> >>>:) >> >> Enough so, apparently, that I'm reluctant even to touch that question. > >So how else would you express something like > > def shell_escape(Arg) : > """returns Arg suitably escaped for use as a command-line argument > to Bash.""" > return \ > re.sub \ > ( > r"[\<\>\"\'\|\&\$\#\;\(\)\[\]\{\}\`\!\~\ \\]", > lambda Match : "\\" + Match.group(0), > Arg > ) > # Need to catch anything that might be meaningful to shell > #end shell_escape > >? I suspect we're confusing each other. I *like* lambdas--at least, more than Guido does, which I recognize is a low standard. When I take your question at face value, my response is def shell_escape(Arg) : """returns Arg suitably escaped for use as a command-line argument to Bash.""" pattern = r"[\<\>\"\'\|\&\$\#\;\(\)\[\]\{\}\`\!\~\ \\]" def f1(Match): return return re.sub(pattern, f1, Arg) # Need to catch anything that might be meaningful to shell #end shell_escape 'cept that I'd hope to find a way to simplify pattern. Was that what you were asking? From rdcollum at gmail.com Sun Dec 28 15:06:25 2008 From: rdcollum at gmail.com (Roger) Date: Sun, 28 Dec 2008 12:06:25 -0800 (PST) Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <0167cbf7$0$6988$c3e8da3@news.astraweb.com> Message-ID: <676bffeb-4b07-4226-8c14-7da57d94351b@f13g2000yqj.googlegroups.com> > Curious. When I see a bare return, the first thing I think is that the > author forgot to include the return value and that it's a bug. > > The second thing I think is that maybe the function is a generator, and > so I look for a yield. If I don't see a yield, I go back to thinking > they've left out the return value, and have to spend time trying to > understand the function in order to determine whether that is the case or > not. > > In other words, even though it is perfectly valid Python, bare returns > always make the intent of the function less clear for me. I'm with Bruno > -- if you have a function with early exits, and you need to make the > intent of the function clear, explicitly return None. Otherwise, leave it > out altogether. > > -- > Steven To me this is the soundest argument. Thanks for the advice. I think I'll follow this as a rule of thumb hereafter. From hrishys at yahoo.co.uk Thu Dec 11 04:36:38 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Thu, 11 Dec 2008 09:36:38 +0000 (GMT) Subject: Equivalent of 'wget' for python? In-Reply-To: <16651e80812080954p23eb2aeaj8793be4a8d509c77@mail.gmail.com> Message-ID: <123129.76624.qm@web27402.mail.ukl.yahoo.com> Hi Please excuse my OOP but is my understanding correct urllib.urlretrieve(url_of_zip_file,destination_on_local_filesystem) is urllib --->Static Class on which the method urlretrieve method is invoked ? In that case what does the python 3.0 version mean import urllib.request urllib.request.urlretrieve(url, local_file_name) urllib -->static class request -->method urlretrieve--> what is this then ? regards Hrishy --- On Mon, 8/12/08, Jerry Hill wrote: > From: Jerry Hill > Subject: Re: Equivalent of 'wget' for python? > To: python-list at python.org > Date: Monday, 8 December, 2008, 5:54 PM > On Mon, Dec 8, 2008 at 11:53 AM, r0g > wrote: > > urllib.urlretrieve(url_of_zip_file, > destination_on_local_filesystem). > > In python 3.0, that appears to be: > > import urllib.request > urllib.request.urlretrieve(url, local_file_name) > > -- > Jerry > -- > http://mail.python.org/mailman/listinfo/python-list From sjmachin at lexicon.net Fri Dec 19 15:15:13 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 19 Dec 2008 12:15:13 -0800 (PST) Subject: PIL on 3.x? References: Message-ID: <3892784c-ddf4-4451-bcfd-dbc58b9b55f8@e1g2000pra.googlegroups.com> On Dec 20, 6:55?am, "Daniel Fetchinson" wrote: > Does anyone know if PIL will be ported to the 3.x branch? Have you considered e-mail to the author? From excord80 at gmail.com Fri Dec 19 14:52:26 2008 From: excord80 at gmail.com (excord80) Date: Fri, 19 Dec 2008 11:52:26 -0800 (PST) Subject: ANN: New Book: Programming in Python 3 References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> Message-ID: <400e99dc-90e2-441a-b7cf-5c2690915682@g38g2000yqd.googlegroups.com> On Dec 4, 2:42?pm, Alan G Isaac wrote: > Mark Summerfield wrote: > > "Programming in Python 3: > > A Complete Introduction to the Python Language" > > ISBN 0137129297 > >http://www.qtrac.eu/py3book.html > > OMG, you really wrote it in Lout? > I wish you would add to http://www.qtrac.eu/lout.html > a comment on what you get out of that > (compared to using e.g., LaTeX or > reStructuredText). I'm also curious about why you chose Lout over LaTeX or reST. From Slaunger at gmail.com Wed Dec 10 01:51:56 2008 From: Slaunger at gmail.com (Slaunger) Date: Tue, 9 Dec 2008 22:51:56 -0800 (PST) Subject: Best way to report progress at fixed intervals References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> <817384d5-5f68-4c1f-9560-0bc7b7d2b1e3@v5g2000prm.googlegroups.com> Message-ID: <6ccb77a2-a3f1-4b6b-900c-d4626be9e939@s1g2000prg.googlegroups.com> On 10 Dec., 03:44, George Sakkis wrote: > On Dec 9, 11:40?am, Slaunger wrote: > > > I would therefore like some feedback on this proposed generic "report > > progress at regular intervals" approach presented here. What could I > > do better? > > There is a pypi package that might do what you're looking for (haven't > used it though):http://pypi.python.org/pypi/progressbar/. > > HTH, > George Thank you. I will keep that in mind, if I ever get to doing GUI-based progress. -- Slaunger From python at rcn.com Fri Dec 19 06:31:07 2008 From: python at rcn.com (Raymond Hettinger) Date: Fri, 19 Dec 2008 03:31:07 -0800 (PST) Subject: Generator slower than iterator? References: Message-ID: <62013718-57e9-4690-a2be-11e63b9c135b@u18g2000pro.googlegroups.com> > FedericoMoreirawrote: > > Hi all, > > > Im parsing a 4.1GB apache log to have stats about how many times an ip > > request something from the server. > > > The first design of the algorithm was > > > for line in fileinput.input(sys.argv[1:]): > > ? ? ip = line.split()[0] > > ? ? if match_counter.has_key(ip): > > ? ? ? ? match_counter[ip] += 1 > > ? ? else: > > ? ? ? ? match_counter[ip] = 1 . . . > > Should i leave fileinput behind? Yes. fileinput is slow because it does a lot more than just read files. > > Am i using generators with the wrong aproach? No need for a generator here. The time is being lost with fileinput, split, and the counting code. Try this instead: match_counter = collections.defaultdict(int) for filename in sys.argv[1:]: for line in open(filename): ip, sep, rest = line.partition(' ') match_counter[ip] += 1 If you're on *nix, there's a fast command line approach: cut -d' ' -f1 filelist | sort | uniq -c From psaffrey at googlemail.com Thu Dec 18 06:36:06 2008 From: psaffrey at googlemail.com (psaffrey at googlemail.com) Date: Thu, 18 Dec 2008 03:36:06 -0800 (PST) Subject: Selecting a different superclass References: Message-ID: <5adf5202-d80f-4cd1-a5f2-2d1c5f47504f@e1g2000pra.googlegroups.com> On 17 Dec, 20:33, "Chris Rebert" wrote: > superclass = TraceablePointSet if tracing else PointSet > Perfect - many thanks. Good to know I'm absolved from evil, also ;) Peter From malaclypse2 at gmail.com Mon Dec 1 14:51:40 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 1 Dec 2008 14:51:40 -0500 Subject: Checking a string against multiple matches In-Reply-To: <99a3a677-a38d-40f5-9a94-a98865150b69@k19g2000yqg.googlegroups.com> References: <99a3a677-a38d-40f5-9a94-a98865150b69@k19g2000yqg.googlegroups.com> Message-ID: <16651e80812011151o1423aca5w603ed5d63c74a387@mail.gmail.com> On Mon, Dec 1, 2008 at 2:31 PM, Aaron Scott wrote: > Pseudocode: > > if "two" in ["one", "two", "three", "four"]: > return True That works, just like you wrote it: >>> "two" in ["one", "two", "three", "four"] True >>> "two" in ["one", "twofer", "three", "four"] False If that doesn't answer your question, maybe you could give some examples. -- Jerry From lie.1296 at gmail.com Mon Dec 8 02:30:52 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 8 Dec 2008 07:30:52 +0000 (UTC) Subject: Guido's new method definition idea References: <493abe2e$0$15998$426a34cc@news.free.fr> <62bcfe49-bee6-4348-8ec9-8ab85132c8ff@40g2000prx.googlegroups.com> <493bba28$0$8283$426a74cc@news.free.fr> Message-ID: On Sun, 07 Dec 2008 12:57:27 +0100, News123 wrote: > Lie wrote: >> On Dec 7, 1:02 am, News123 wrote: >>> What would be interesting would be some syntactical sugar to get rid >>> of the 'self' (at least in the code body). >>> >>> example: >>> class C: >>> class_elements a,b,c,d >>> >>> def method(self,arg): >>> global d >>> a,b,c = arg[0..3] >>> d = a + b >>> self.e = a + d >>> >>> >> Nah, that would make it not explicit. Explicit here also means that to >> refer to self's a, we need to explicitly refer to self. > > Well being explicit when trying to suggest an implicit syntax (in order > to reduce typing) is a little difficult ;-) > > Though you're right my main goal is not being implicit but would be > reducing typing and have shorter source code lines. > > If 'global '' is accepted inside a def, then moving > 'class_elements ' inside the def could be acceptable as well > though it would requiere, that this statement is repeated per def > The advantage of explicit self is to easily differentiate instance variable with local variable/names. When I need to shorten the code, I'll simply alias it to a local name, no need for syntax change or new keyword. class C(object): def __init__(self): self.a = 2 self.b = 2 self.c = 3 def x(self): #return ((-self.b + math.sqrt(self.b**2 - 4 * self.a * self.c)) / (2 * self.a)), ((-self.b - math.sqrt(self.b**2 - 4 * self.a * self.c)) / (2 * self.a)) a, b, c = self.a, self.b, self.c sq = math.sqrt return ((-b + sq(b**2 - 4*a*c)) / (2*a)), ((-b - sq(b**2 - 4*a*c)) / (2*a)) From zac256 at gmail.com Thu Dec 4 19:01:35 2008 From: zac256 at gmail.com (Zac Burns) Date: Thu, 4 Dec 2008 16:01:35 -0800 Subject: Overriding a method at the instance level on a subclass of a builtin type In-Reply-To: References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> Message-ID: <333edbe80812041601r6c1af7c4g7ae96eb7fe0a82a7@mail.gmail.com> Ok. Feature request then - assignment of a special method name to an instance raises an error. -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer (Digital Overlord) Zindagi Games On Thu, Dec 4, 2008 at 10:13 AM, George Sakkis wrote: > On Dec 4, 1:03 pm, "Zac Burns" wrote: >> Ok... but why are the special methods handled differently? > > Because otherwise they wouldn't be special ;-) And also for > performance and implementation reasons I believe. > > George > -- > http://mail.python.org/mailman/listinfo/python-list > From piyush.subscription at gmail.com Mon Dec 1 07:30:56 2008 From: piyush.subscription at gmail.com (Piyush Anonymous) Date: Mon, 1 Dec 2008 18:00:56 +0530 Subject: finding the difference between the two version of the python program... Message-ID: <19ac19520812010430s7e0e11a6sf787ca1f73e87f36@mail.gmail.com> is there a tool which, given two version of programs, finds the difference like set of classes added, deleted and modified? assuming the python program is written in oops way. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wolfgang.lipp at gmail.com Tue Dec 9 20:27:10 2008 From: wolfgang.lipp at gmail.com (_wolf) Date: Tue, 9 Dec 2008 17:27:10 -0800 (PST) Subject: forcing future re-import from with an imported module Message-ID: <533670ae-6d9d-4b10-9156-e41b31b678c7@g17g2000prg.googlegroups.com> following problem: i have a module importer_1 that first imports importer_2, then importee. importer_2 also imports importee. as we all know, follow-up imports are dealt out from the cache by python?s import mechanism, meaning the importee file gets only cached once. i can force module-level code in importee to be re-executed e.g. by deleting importee from sys.modules. but in this case, code of shich below, that does not work: if you delete importee from sys.modules *from within importee*, you get a nasty "ImportError: Loaded module importee not found in sys.modules" instead. but, the same line `import sys; del sys.modules[ 'importee' ]` does what it says on the tin. how can i say, approximately, "re-import the present module when it is imported the next time, don?t use the cache" in a simple way? i do not want to "reload" the module, that doesn?t help. greets _wolf #------------------------------------------ # importer_1.py #------------------------------------------ print 'this is importer 1' import importer_2 # import sys; del sys.modules[ 'importee' ] import importee print 'importer 1 finished' #------------------------------------------ # importer_2.py #------------------------------------------ print 'this is importer 2' import importee print 'importer 2 finished' #------------------------------------------ # importee.py #------------------------------------------ print 'this is importee' import sys; del sys.modules[ 'importee' ] print 'importee finished' #------------------------------------------ # Output #------------------------------------------ this is importer 1 this is importer 2 this is importee importee finished Traceback (most recent call last): File "C:\temp\active_imports\importer_1.py", line 2, in import importer_2 File "C:\temp\active_imports\importer_2.py", line 2, in import importee ImportError: Loaded module importee not found in sys.modules From ncoghlan at gmail.com Sat Dec 6 20:27:56 2008 From: ncoghlan at gmail.com (Nick Coghlan) Date: Sun, 07 Dec 2008 11:27:56 +1000 Subject: [Python-Dev] "as" keyword woes In-Reply-To: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> Message-ID: <493B269C.9020303@gmail.com> Warren DeLano wrote: > In other words we have lost the ability to refer to "as" as the > generalized OOP-compliant/syntax-independent method name for casting: Other possible spellings: # Use the normal Python idiom for avoiding keyword clashes # and append a trailing underscore new_object = old_object.as_(class_hint) float_obj = int_obj.as_("float") float_obj = int_obj.as_(float_class) # Use a different word (such as, oh, "cast" perhaps?) new_object = old_object.cast(class_hint) float_obj = int_obj.cast("float") float_obj = int_obj.cast(float_class) You could make a PEP if you really wanted to, but it's going to be rejected. Cheers, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia --------------------------------------------------------------- From paul at boddie.org.uk Sun Dec 14 18:32:42 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 14 Dec 2008 15:32:42 -0800 (PST) Subject: Python 3.0 crashes displaying Unicode at interactive prompt References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> <49443531.5050304@v.loewis.de> <49448FC2.6030306@v.loewis.de> <494576DD.1050505@v.loewis.de> Message-ID: <89022013-f7f6-4779-849f-b36fe618104e@r15g2000prh.googlegroups.com> On 14 Des, 22:13, "Martin v. L?wis" wrote: > > But shouldn't the production of an object's representation via repr be > > a "safe" operation? > > It's a trade-off. It should also be legible. Right. I can understand that unlike Python 2.x, a representation of a string in Python 3.x (whose equivalent in Python 2.x would be a Unicode object) must also be a string (as opposed to a byte string in Python 2.x), and that no decision can be taken to choose "safe" representations for characters which cannot be displayed in a terminal. In examples, for Python 2.x... >>> u"???" u'\xe6\xf8\xe5' >>> repr(u"???") "u'\\xe6\\xf8\\xe5'" ...and for Python 3.x... >>> "???" '???' >>> repr("???") "'???'" ...with an ISO-8859-15 terminal. Python 2.x could conceivably be smarter about encoding representations, but chooses not to be since the smarter behaviour would need to involve knowing that an "output situation" was imminent. Python 3.x, on the other hand, leaves issues of encoding to the generic I/O pipeline, causing the described problem. Of course, repr will always work if its output does not get sent to sys.stdout or an insufficiently capable output stream, but I suppose usage of repr for debugging purposes, where one may wish to inspect character values, must be superseded by usage of the ascii function, as you point out. It's unfortunate that the default behaviour isn't optimal at the interactive prompt for some configurations, though. Paul From prologic at shortcircuit.net.au Wed Dec 31 01:23:49 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 16:23:49 +1000 Subject: MemoryError when list append... plz help In-Reply-To: References: <21227745.post@talk.nabble.com> Message-ID: On Wed, Dec 31, 2008 at 4:17 PM, James Mills wrote: > I have no idea how many bytes of memory > storing each element of a list consumes > let alone each float object, but I assure you > it's not going to be anywhere near that of > 60494500 4-bytes spaces (do floats in C > normally consume 4 bytes) in C. Just creating a list of this many elements consumes 60% of my desktops RAM. YOu _SHOLD NOT_ be doing this. >>> L = list(xrange(N)) >>> len(L) 60494500 >>> L[10000] 10000 ps stats: 32351 jmills 20 0 962m 610m 1356 S 0.0 60.6 0:03.36 python It takes several seconds to create this list and several minutes for the Python interpreter to shutdown and deallocate all the memory. --JamesMills From kkylheku at gmail.com Mon Dec 8 23:36:28 2008 From: kkylheku at gmail.com (Kaz Kylheku) Date: Tue, 9 Dec 2008 04:36:28 +0000 (UTC) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> <0201522a-b15a-4401-a208-5d9af70bdd74@w24g2000prd.googlegroups.com> <8947211d-2ee8-403a-8c8a-c7599aea5f80@k24g2000pri.googlegroups.com> Message-ID: <20081224103256.892@gmail.com> On 2008-12-08, Xah Lee wrote: > So, pay me $300 as consulting fee. If the result does not comply to > the above spec, money back guaranteed. *LOL* Did you just offer someone the exciting wager of ``your money back or nothing? No matter what probability we assign to the outcomes, the /upper bound/ on the expected income from the bet is at most zero dollars. Now that's not so bad. Casino games and lotteries have that property too; the net gain is negative. But your game has no variability to suck someone in; the /maximum/ income from any trial is that you break even, which is considered winning. If you ever decide to open a casino, I suggest you stop playing with Mathematica for a while, and spend a little more time with Statistica, Probabilica, and especially Street-Smartica. :) From xahlee at gmail.com Sun Dec 7 17:53:49 2008 From: xahlee at gmail.com (Xah Lee) Date: Sun, 7 Dec 2008 14:53:49 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> For those interested in this Mathematica problem, i've now cleaned up the essay with additional comments here: ? A Mathematica Optimization Problem http://xahlee.org/UnixResource_dir/writ/Mathematica_optimization.html The result and speed up of my code can be verified by anyone who has Mathematica. Here's some additional notes i added to the above that is not previously posted. ------------------------- Advice For Mathematica Optimization Here's some advice for mathematica optimization, roughly from most important to less important: * Any experienced programer knows, that optimization at the algorithm level is far more important than at the level of code construction variation. So, make sure the algorithm used is good, as opposed to doodling with your code forms. If you can optimize your algorithm, the speed up may be a order of magnitude. (for example, various algorithm for sorting algorithms? illustrates this.) * If you are doing numerical computation, always make sure that your input and every intermediate step is using machine precision. This you do by making the numbers in your input using decimal form (e.g. use ?1.?, ?N[Pi]? instead of ?1?, ?Pi?). Otherwise Mathematica may use exact arithmetics. * For numerical computation, do not simply slap ?N[]? into your code. Because the intermediate computation may still be done using exact arithmetic or symbolic computation. * Make sure your core loop, where your calculation is repeated and takes most of the time spent, is compiled, by using Compile. * When optimizing speed, try to avoid pattern matching. If your function is ?f[x_]:= ...?, try to change it to the form of ?f=Function [x,...]? instead. * Do not use complicated patterns if not necessary. For example, use ?f[x_,y_]? instead of ?f[x_][y_]?. ------------------------------ ... Besides the above basic things, there are several aspects that his code can improve in speed. For example, he used rather complicated pattern matching to do intensive numerical computation part. Namely: Intersect[o_, d_][{lambda_, n_}, Bound[c_, r_, s_]] Intersect[o_, d_][{lambda_, n_}, Sphere[c_, r_]] Note that the way the parameters of Intersect defined above is a nested form. The code would be much faster if you just change the forms to: Intersect[o_, d_, {lambda_, n_}, Bound[c_, r_, s_]] Intersect[o_, d_, {lambda_, n_}, Sphere[c_, r_]] or even just this: Intersect[o_, d_, lambda_, n_, c_, r_, s_] Intersect[o_, d_, lambda_, n_, c_, r_] Also, note that the Intersect is recursive. Namely, the Intersect calls itself. Which form is invoked depends on the pattern matching of the parameters. However, not only that, inside one of the Intersect it uses Fold to nest itself. So, there are 2 recursive calls going on in Intersect. Reducing this recursion to a simple one would speed up the code possibly by a order of magnitude. Further, if Intersect is made to take a flat sequence of argument as in ?Intersect[o_, d_, lambda_, n_, c_, r_, s_]?, then pattern matching can be avoided by making it into a pure function ?Function?. And when it is a ?Function?, then Intersect or part of it may be compiled with Compile. When the code is compiled, the speed should be a order of magnitude faster. ----------------------------- Someone keeps claiming that Mathematica code is some ?5 order of magnitude slower?. It is funny how the order of magnitude is quantified. I'm not sure there's a standard interpretation other than hyperbole. There's a famous quote by Alan Perlis ( http://en.wikipedia.org/wiki/Alan_Perlis ) that goes: ?A Lisp programmer knows the value of everything, but the cost of nothing.? this quote captures the nature of lisp in comparison to most other langs at the time the quote is written. Lisp is a functional lang, and in functional langs, the concept of values is critical, because any lisp program is either a function definition or expression. Function and expression act on values and return values. The values along with definitions determines the program behavior. ?the cost of nothing? captures the sense that in high level langs, esp dynamic langs like lisp, it's easy to do something, but it is more difficult to know the algorithmic behavior of constructs. This is in contrast to langs like C, Pascal, or modern lang like Java, where almost anything you write in it is ?fast?, simply forced by the low level nature of the lang. In a similar way, Mathematica is far more higher level than any existing lang, counting other so-called computer algebra systems. A simple one-liner Mathematica construct easily equates to 10 or hundred lines of lisp, perl, python, and if you count its hundreds of mathematical functions such as Solve, Derivative, Integrate, each line of code is equivalent to a few thousands lines in other langs. However, there is a catch, that applies to any higher level langs, namely, it is extremely easy, to create a program that are very inefficient. This can typically be observed in student or beginner's code in lisp. The code may produce the right output, but may be extremely inefficient for lacking expertise with the language. The phenomenon of creating code that are inefficient is proportional to the highlevelness or power of the lang. In general, the higher level of the lang, the less possible it is actually to produce a code that is as efficient as a lower level lang. For example, the level or power of lang can be roughly order as this: assembly langs C, pascal C++, java, c# unix shells perl, python, ruby, php lisp Mathematica the lower level the lang, the longer it consumes programer's time, but faster the code runs. Higher level langs may or may not be crafted to be as efficient. For example, code written in the level of langs such as perl, python, ruby, will never run as fast as C, regardless what expert a perler is. C code will never run as fast as assembler langs. And if the task crafting a raytracing software, then perl, python, ruby, lisp, Mathematica, are simply not suitable, and are not likely to produce any code as fast as C or Java. On the other hand, higher level langs in many applications simply cannot be done with lower level lang for various practical reasons. For example, you can use Mathematica to solve some physics problem in few hours, or give Pi to gazillion digits in few seconds with just ?N [Pi,10000000000000]?. Sure, you can code a solution in lisp, perl, or even C, but that means few years of man hours. Similarly, you can do text processing in C, Java, but perl, python, ruby, php, emacs lisp, Mathematica, can reduce your man hours to 10% or 1% of coding effort. In the above, i left out functional langs that are roughly statically typed and compiled, such as Haskell, OCaml, etc. I do not have experience with these langs. I suppose they do maitain some advantage of low level lang's speed, yet has high level constructs. Thus, for computationally intensive tasks such as writing a raytracer, they may compete with C, Java in speed, yet easier to write with fewer lines of code. personally, i've made some effort to study Haskell but never went thru it. In my experience, i find langs that are (roughly called) strongly typed, difficult to learn and use. (i have reading knowledge of C and working knowledge of Java, but am never good with Java. The verbosity in Java turns me off thoroughly.) ----------------- as to how fast Mathematica can be in the raytracing toy code shown in this thread, i've given sufficient demonstration that it can be speed up significantly. Even Mathematica is not suitable for this task, but i'm pretty sure can make the code's speed in the some level of speed as OCaml. (as opposed to someone's claim that it must be some 700000 times slower or some ?5 orders of magnituted slower?). However, to do so will take me half a day or a day of coding. Come fly $300 to my paypal account, then we'll talk. Money back guaranteed, as i said before. Xah ? http://xahlee.org/ ? From gagsl-py2 at yahoo.com.ar Tue Dec 16 11:59:36 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Dec 2008 14:59:36 -0200 Subject: zipfile.is_zipfile() and string buffers References: <79196ccb-11fb-4a2d-9c2c-79801f108a05@f40g2000pri.googlegroups.com> Message-ID: En Tue, 16 Dec 2008 12:28:00 -0200, Brendan escribi?: > I would like zipfile.is_zipfile(), to operate on a cStringIO.StringIO > string buffer, but is seems only to accept file names as arguments. > Should it not be able to handle string buffers too? A version of zipfile.is_zipfile() accepting both file names and file objects: def _check_zipfile(fp): try: if _EndRecData(fp): return True # file has correct magic number except IOError: pass return False def is_zipfile(filename): """Quickly see if file is a ZIP file by checking the magic number.""" result = False try: if hasattr(filename, "read"): result = _check_zipfile(fp=filename) else: with open(filename, "rb") as fp: result = _check_zipfile(fp) except IOError: pass return result -- Gabriel Genellina From jon at ffconsultancy.com Wed Dec 10 18:02:08 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Wed, 10 Dec 2008 23:02:08 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <20081226055859.604@gmail.com> Message-ID: Xah Lee wrote: > Kaz Kylheku wrote: >> Really? ``50 or hundreds'' of lines in C? >> >> #include /* for sqrt */ >> >> void normalize(double *out, double *in) >> { >> double denom = sqrt(in[0] * in[0] + in[1] * in[1] + in[2] * >> in[2]); >> >> out[0] = in[0]/denom; >> out[1] = in[1]/denom; >> out[2] = in[2]/denom; >> } >> >> Doh? > > Kaz, pay attention: > > Xah wrote: ?Note, that the ?norm? as defined above works for vectors > of any dimention, i.e. list of any length.? That is still only 6 lines of C code and not 50 as you claimed: double il = 0.0; for (int i=0; i Message-ID: <20081231153100.20272.1701611299.divmod.quotient.29806@ohm> On Wed, 31 Dec 2008 15:48:50 +0100, Francesco Bochicchio wrote: >< ... > >>>Uhm. In my experience, with TCP protocol recv only returned less than >>>the required bytes if the remote end disconnects. I always check the >> >>What if the sending end actually sent less than you asked for ? >> >>-srp > >In blocking mode and with TCP protocol, the recv waits until more bytes are >received - mixing up the next message with the previous one and then >loosing the 'sync' and being unable to interpretate the received data - or >the remote end disconnects. Nope, this isn't how TCP works, whether your sockets are blocking or non- blocking. It's easy to see this: >>> s = socket.socket() >>> s.connect(('www.google.com', 80)) >>> s.sendall('GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: keep-alive\r\n\r\n') >>> len(s.recv(1024 * 1024)) 6191 >>> s.sendall('GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: keep-alive\r\n\r\n') >>> len(s.recv(1024 * 1024)) 6191 >>> s.sendall('GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: keep-alive\r\n\r\n') >>> len(s.recv(1024 * 1024)) 6191 >>> s.sendall('GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: keep-alive\r\n\r\n') >>> len(s.recv(1024 * 1024)) 6191 >>> Numerous blocking recv calls which returned fewer bytes than asked for without the connection having been closed. The only guarantee you get with a blocking socket is that the recv will return at least one byte and at most the number of bytes you asked for (or raise an exception instead). On a LAN, it's likely that you'll generally get the exact number of bytes which the sender passed to one call of send (until the sender starts to pass really huge strings to send, then it'll get split up) just because the network has lots of capacity compared to the traffic you're putting on it. However, even on a LAN it's not guaranteed, and on the internet, it's extremely likely that this won't happen most of the time. Jean-Paul From ross.jett at gmail.com Mon Dec 29 20:00:31 2008 From: ross.jett at gmail.com (Ross) Date: Mon, 29 Dec 2008 17:00:31 -0800 (PST) Subject: get method Message-ID: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> I am teaching myself Python by going through Allen Downing's "Think Python." I have come across what should be a simple exercise, but I am not getting the correct answer. Here's the exercise: Given: def histogram(s): d = dict() for c in s: if c not in d: d[c] = 1 else: d[c] += 1 return d Dictionaries have a method called get that takes a key and a default value. If the key appears in the dictionary, get returns the corresponding value; otherwise it returns the default value. For example: >>> h = histogram('a') >>> print h {'a': 1} >>> h.get('a', 0) 1 >>> h.get('b', 0) 0 Use get to write histogram more concisely. You should be able to eliminate the if statement. Here's my code: def histogram(s): d = dict() for c in s: d[c]= d.get(c,0) return d This code returns a dictionary of all the letters to any string s I give it but each corresponding value is incorrectly the default of 0. What am I doing wrong? From steven at REMOVE.THIS.cybersource.com.au Mon Dec 22 20:34:24 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 23 Dec 2008 01:34:24 GMT Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> Message-ID: On Mon, 22 Dec 2008 10:01:21 -0800, r wrote: > Walter, > I just look at the stats for comp.lang.python, and i am 9th place for > most post this month. And about 9,000th place for useful information. -- Steven From sjmachin at lexicon.net Wed Dec 17 07:44:11 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 17 Dec 2008 04:44:11 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> Message-ID: <0d9ea7cc-b5fb-4edb-be32-490aae9e7204@b41g2000pra.googlegroups.com> On Dec 17, 9:39?pm, aka wrote: > Due to being in a hurry I didn't paste correctly (sorry). > > The intention is to put values of column 1 ("id") in the roles list, > therefore appending within the loop, to fill a session var. > > The complete code is: It's *not* complete. It's missing "import csv". > > roles = [] > inp = 'C:/temp/test.csv' > try: > ? ? fp = open(inp, 'rb') > ? ? reader = csv.reader(fp, dialect='excel', delimiter=';') > ? ? for r in reader: > ? ? ? ? roles.append(r) > ? ? ? ? ## ultimately should be something like r.id or r[0] > ? ? ? ? ## first row of csv file should be skipped because of column > names > > except: > ? ? msg = 'Something's wrong with the csv.reader' But you don't print the message! In any case, using the try/except like that *hides* any useful diagnostic information; it gives only an indication that something is wrong, but not what is wrong and where it is wrong. If you throw away the try/except, you will get a more meaningful message -- possibly that "csv" is not defined!! -- and the traceback will tell you in which line the error occured. > return dict(file=inp,roles=str(roles)) Why do you think that you need (a) that complicated expression (b) the str() call? Assuming you are intending to make a function out of all that, what's wrong with returning a (simple) tuple: return inp, roles ? The above 'return' statement is not inside a function/method. You would have got this message: SyntaxError: 'return' outside function People will very soon lose patience with you if you persist in not posting the actual code that you ran. > The roles list isn't populated at all :( This could mean (if the code that was posted is moderately similar to that which was run) that the error happened before the first time that roles.append(r) was executed ;-) Please divulge the contents of test.csv -- but not if it's huge! Considering trying to get your code to work first with a data file of close-to-minimal size and complexity, like this: 8<--- id,other_info tom,1 dick,2 harry,3 8<--- By the way, you mentioned the UnicodeReader class in your original post, but you don't seem to use it ... From martin.hellwig at dcuktec.org Wed Dec 3 19:55:59 2008 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Thu, 04 Dec 2008 00:55:59 +0000 Subject: "as" keyword woes In-Reply-To: <01470229$0$20670$c3e8da3@news.astraweb.com> References: <493701f0$0$194$e4fe514c@news.xs4all.nl> <01470229$0$20670$c3e8da3@news.astraweb.com> Message-ID: <49372a9f$0$194$e4fe514c@news.xs4all.nl> Steven D'Aprano wrote: > On Wed, 03 Dec 2008 22:02:24 +0000, Martin P. Hellwig wrote: > >> Warren DeLano wrote: >>> A bottom line / pragmatic question... hopefully not a FAQ. >>> >>> Why was it necessary to make "as" a reserved keyword? >> >> Because it can be used at the import statement to let the imported thing >> be known under another name? >> Something like: >> >> >>> import xml.etree.ElementTree as ET > > Martin, that doesn't answer the OP's question *at all*. Python 2.5 uses > "as" in that way, and it is not a keyword. > Yes Steven, I realized after the apple fell on my head that I was barking at the wrong tree, in a totally different forest, sorry for the noise. -- mph From peke at iki.fi Sat Dec 6 14:40:48 2008 From: peke at iki.fi (=?ISO-8859-1?Q?Pekka_Kl=E4rck?=) Date: Sat, 6 Dec 2008 21:40:48 +0200 Subject: python book for non technical absolute beginner In-Reply-To: <493a7c6a$0$973$426a34cc@news.free.fr> References: <493a7c6a$0$973$426a34cc@news.free.fr> Message-ID: <7dedbb6d0812061140k25b03edcw84f24e9f070b7951@mail.gmail.com> 2008/12/6 News123 : > No my question does anybody know a nice beginners book (or a learning CD > or on line tutorial)? Ideally it shouldn't be too serious and have a lot > of small nice mini-examples How to Think Like a Computer Scientist - Learning with Python is a good book for beginners and it is available for free under the GNU license. http://www.greenteapress.com/thinkpython/thinkCSpy/ Cheers, .peke From python at bdurham.com Tue Dec 2 23:26:54 2008 From: python at bdurham.com (python at bdurham.com) Date: Tue, 02 Dec 2008 23:26:54 -0500 Subject: Determining number of dict key collisions in a dictionary In-Reply-To: <4935FD01.1000308@rogerbinns.com> References: <1228221594.807.1287801527@webmail.messagingengine.com> <1228271002.8425.1287938717@webmail.messagingengine.com> <4935FD01.1000308@rogerbinns.com> Message-ID: <1228278414.30562.1287962691@webmail.messagingengine.com> Roger, Apologies for responding directly to your email vs. the list (just realized this now). Thank you very much for your detailed answers and the reminder about premature optimization. You have answered all my questions. Regards, Malcolm ----- Original message ----- From: "Roger Binns" To: python at bdurham.com Date: Tue, 02 Dec 2008 19:29:05 -0800 Subject: Re: Determining number of dict key collisions in a dictionary -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 python at bdurham.com wrote: > Any ideas on why the Windows 64-bit version of Python has 32-bit vs. > 64-bit longs? (Is this the case for both the 2.6 and 3.0 64-bit versions > of Python for Windows?) It is part of the ABI for the platform. http://www.unix.org/version2/whatsnew/lp64_wp.html http://en.wikipedia.org/wiki/64-bit#64-bit_data_models http://blogs.msdn.com/oldnewthing/archive/2005/01/31/363790.aspx > If this is the case, then it sounds like Linux/Unix are much better > Python hosts than Windows when it comes to developing 64-bit Python > applications - especially when it comes to working with large > dictionaries (you point about hash collisions not withstanding)? Python uses a type Py_ssize_t which is typedef'ed to 64 bits on a 64 bit platform and 32 bits on a 32 bit platform for things like sizes (eg length of strings, number of items in a container) so there won't be any programmatic or correctness issues. You never said what your idea of large was in the original posting. For example you really only need to start worrying about hash collisions on LP64 if you have more than 4 billion items. Even then things will still work. For people who have really large data sets, it is usually beneficial to write their own custom code often resorting to assembly. This is because the data set is so much larger than caches and saving even a few instructions per item pays back due to how many there are. My advice would be to not worry about collisions, premature optimization etc initially. Get the code working and get it working right. Then do profiling and improve algorithms. You will have test code from earlier so you can verify that the optimizations are correctly. Finally you may have to rewrite core parts in assembly. but again the tests will be there to help. Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAkk1/P4ACgkQmOOfHg372QQdkACg3n0CrXCbctfyKOw3DQ0uTvvt J60AoMyikF/oJUXVrV9XOkQe6eprzPSh =9CYk -----END PGP SIGNATURE----- From beautifu_girl_1418 at hotmail.com Mon Dec 15 06:21:20 2008 From: beautifu_girl_1418 at hotmail.com (=?windows-1256?B?yOTKIMfh09rmz+3l?=) Date: Mon, 15 Dec 2008 03:21:20 -0800 (PST) Subject: =?windows-1256?B?3+3dIMrO3e0g0d7j3yDa5CDH4dDtIMrK1eEgyOU=?= Message-ID: ?? ??: ????? ???? ??? ??? ?? ???? ?? ???????? (?? ??? ??? ????) ????? ??????: ???? ????? ???? ???? ?? ??????? ====> TRA ZDOD ???? ??? ????? ??????? ??????? ????? (77127 )????? ??? ????? ??? ??????? ????? (95312) ????? ??? ????? ?????? ??? ????? (95206) ????? ????? (1081) ???????? ????? (6752) ????? ??? ????? ??????? ???????? ????? (85234) ????? ??? ????? ????????? ???????? ?????? ????? (1489) ??? ????? (2921) ???????? ???????? (2252) ?? ?????? ???????? ????? ??? (2420) ?? ?? From clp at rebertia.com Sun Dec 7 23:45:19 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 7 Dec 2008 20:45:19 -0800 Subject: infering the number of args a function takes at runtime In-Reply-To: References: Message-ID: <47c890dc0812072045g3b9d17c8r5768028afd22262d@mail.gmail.com> On Sun, Dec 7, 2008 at 8:39 PM, sniffer wrote: > hi all, > i am a python newbie, in a project currently doing i need to find out > the number of arguments that a function takes at runtime.? Is this > possible ,if so how do i do this,i ve looked through the python > documentation but couldnt find anything.any help will be great You want inspect.getargspec() or one of its friends in the `inspect` module. See http://docs.python.org/library/inspect.html#inspect.getargspec Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com I really should get back to studying now > > > TIA > -- > http://mail.python.org/mailman/listinfo/python-list > From geekmail at usenot.de Fri Dec 5 10:17:25 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Fri, 5 Dec 2008 16:17:25 +0100 Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> Message-ID: <20081205161725.3f35222b@usenot.de> On Thu, 4 Dec 2008 15:49:46 -0600 skip at pobox.com wrote: > > Andreas> Whenever has it been a pythonic ideal to "not allow" > Andreas> stuff? You get warnings. Everything else is up to you. > > It's more than warnings. With properly crafted combinations of > spaces and tabs you can get code which looks like it has a certain > indentation to the human observer but which looks like it has > different indentation (and thus different semantics) to the byte code > compiler. There is often no warning. > I just looked at "python --help", it seems that there is no warning per default. My point is: If you mix tabs and spaces in a way that breaks code, you'll find out pretty easily, because your program will not work. It's your choice, and I think it's pretty nice that Python lets you choose. After all, some people are of the "indentation for structure, spaces for alignment" faction. Why make their life harder? /W -- My real email address is constructed by swapping the domain with the recipient (local part). From bignose+hates-spam at benfinney.id.au Thu Dec 4 00:07:39 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 04 Dec 2008 16:07:39 +1100 Subject: RELEASED Python 3.0 final References: <1b9568f2-55a0-4f1e-886c-2675b16b58c9@g38g2000yqn.googlegroups.com> Message-ID: <87k5agv884.fsf@benfinney.id.au> Carl Banks writes: > On Dec 3, 7:51?pm, Barry Warsaw wrote: > > On behalf of the Python development team and the Python community, > > I am happy to announce the release of Python 3.0 final. > > Congratulations! This is a great day for the Python community. I'm rather disappointed that crucial information was not given in this announcement: Where is the release party? The public needs to know! :-) Congratulations, and thanks to the entire Python team. -- \ ?I used to work in a fire hydrant factory. You couldn't park | `\ anywhere near the place.? ?Steven Wright | _o__) | Ben Finney From steve at holdenweb.com Tue Dec 23 09:21:13 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 23 Dec 2008 09:21:13 -0500 Subject: pseudo terminal usage from Python? In-Reply-To: <18768.60036.20440.46074@montanaro-dyndns-org.local> References: <18768.60036.20440.46074@montanaro-dyndns-org.local> Message-ID: skip at pobox.com wrote: > I ran into an interesting problem yesterday. The mpstat(1) command on > Solaris formats its output like so: > > CPU minf mjf xcal intr ithr csw icsw migr smtx srw syscl usr sys wt idl > 0 42 1 1184 812 265 227 12 44 37 0 1131 6 2 0 93 > 1 25 1 933 447 2 203 37 75 12 0 902 5 4 0 91 > 2 17 0 195 495 1 201 41 77 13 0 514 5 1 0 94 > 3 4 0 117 882 405 171 34 65 21 0 449 5 2 0 93 > > I'm only interested in presenting the CPU numbers and user+sys values > prefixed by a timestamp. For example, the above might be formatted like so: > > 07:28:46.373328 0 8 1 9 2 6 3 7 > > The obvious solution might be something simple like this: > > mpstat 1 | python mympstat.py > > where mympstat.py does a trival amount of reformatting. > > The problem is that mpstat recognizes when its output is a pipe and block > buffers it so the Python script sees input in massive blobs, not the > second-by-second output you'd see running "mpstat 1" by itself. I've been > reduced to a much more complicated solution which involves forking mpstat > with output to a file, then reading the end of that file every second. A > three-line Python script balloons into a one-page script. Yuck. Add to > that I'm writing this for an admin who is considering Python as a scripting > language. Double Yuck. (But not nyuk nyuk, this is not the Stooges.) > > I suspect there is some magic I can perform with pseudo terminals (this is > on Solaris 10.) The documentation for the pty module contains no examples > and I've been so far unable to find any using Google. > > Any pointers/examples? I will gladly add an example to the pty module docs > (I have the power!) once I have a couple working examples (maybe one example > each of reading and writing?) > Look at the pexpect module - you can run interactive tasks through that. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steve at REMOVE-THIS-cybersource.com.au Sat Dec 20 20:38:35 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Dec 2008 01:38:35 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> Message-ID: <015d9566$0$20656$c3e8da3@news.astraweb.com> On Sat, 20 Dec 2008 16:20:38 -0800, r wrote: > On Dec 20, 6:05?pm, Roy Smith wrote: >> I had an interesting experience with this recently. ?I was giving a >> co-worker quick python into. ?He's an experienced programer in various >> languages, but this was his first exposure to python. >> >> He got really hung up on the % syntax. ?By (bad) luck, he was trying to >> print a tuple (let's call it "t"), did >> >> format % t >> >> and was surprised at the result. ?It set him off on a "but that's >> stupid, blah, blah, blah" rant. ?I haven't absorbed the new syntax well >> enough to figure out if people will get hung up by this with the new >> syntax. > > It is stupid, more reason to fix the current problem instead creating a > whole new one. Instead of just whinging, how about making a suggestion to fix it? Go on, sit down for an hour or ten and try to work out how a BINARY OPERATOR like % (that means it can only take TWO arguments) can deal with an arbitrary number of arguments, *without* having any special cases. Go on. Take your time. I'll be waiting. > One more big complaint "THE BACKSLASH PLAGUE". ever tried regexp?, or > file paths?. All because that little backslash char is a line > continuation character, maybe we should fix that. This makes no sense whatsoever. How does the line continuation character make any difference to backslashes inside a regex or a file path? Again, instead of whinging, what's your suggestion to fix it? Another suggestion, because your first: > Would your life end if '\' was not a continuation char? is just stupid. The line continuation character is *irrelevant* to the problem of backslashes inside strings. For all the use it is, you might as well suggest changing the name None to Null. -- Steven From gregturn at mindspring.com Tue Dec 9 14:06:24 2008 From: gregturn at mindspring.com (Goldfish) Date: Tue, 9 Dec 2008 11:06:24 -0800 (PST) Subject: Spring Python 0 .9.1 has been released Message-ID: I just released Spring Python 0.9.1. One of our users spotted an error in the IoC container involving constructor arguments, and I was able to reproduce the problem, patch it, and get it released quickly to the user community. You can download it right now. Links: * For more information, please visit the website at http://springpython.webfactional.com. * To download the 0.9.1 release, or an archived release, and for access to sample applications use http://www.springsource.com/download/community?project=Spring%20Extensions I cannot emphasize enough how valuable community feedback is to the success of this project. If you are having issues, please post an email to the list, or start a thread at the community forum, and we will examine the situation. Also note, the web site has been updated, which includes a link to API documentation, generated by pydoc. ============================== Release Notes - Spring Python - Version 0.9.1

    Bug

    • [SESPRINGPYTHONPY-86] - XMLConfig doesn't properly lookup constructor-arg's, but instead returns ReferenceDef objects
    =============================== Key Features of Spring Python include: * Inversion Of Control - The idea is to decouple two classes at the interface level. This lets you build many reusable parts in your software, and your whole application becomes more pluggable. You can use either the XmlApplicationContext or the DecoratorBasedApplicationContext. * Aspect-oriented Programming - Spring Python provides great ways to wrap advice around objects. It is utilized for remoting. Another use is for debug tracers and performance tracing. * DatabaseTemplate - Reading from the database requires a monotonous cycle of opening cursors, reading rows, and closing cursors, along with exception handlers. With this template class, all you need is the SQL query and row-handling function. Spring Python does the rest. * Database Transactions - Wrapping multiple database calls with transactions can make your code hard to read. This module provides multiple ways to define transactions without making things complicated. * Security - Plugin security interceptors to lock down access to your methods, utilizing both authentication and domain authorization. * Remoting - It is easy to convert your local application into a distributed one. If you have already built your client and server pieces using the IoC container, then going from local to distributed is just a configuration change. * Samples - to help demonstrate various features of Spring Python, some sample applications have been created: o PetClinic - Everybody's favorite Spring sample application has been rebuilt from the ground up using various web containers including: CherryPy. Go check it out for an example of how to use this framework. o Spring Wiki - Wikis are powerful ways to store and manage content, so we created a simple one as a demo! o Spring Bot - Use Spring Python to build a tiny bot to manage the IRC channel of your open source project. From davidandjoni123 at att.net Sun Dec 7 21:03:18 2008 From: davidandjoni123 at att.net (David and Joni) Date: Sun, 7 Dec 2008 18:03:18 -0800 (PST) Subject: The story of Christmas. Message-ID: Receive the TRUE story of Christmas via e mail, just click on the link. Thank you !! http://app.formassembly.com/forms/view/56128 From MM456Z at yahoo.com Wed Dec 3 05:16:20 2008 From: MM456Z at yahoo.com (MM456Z at yahoo.com) Date: Wed, 3 Dec 2008 02:16:20 -0800 (PST) Subject: Obama's Birth Certificate - Demand that US presidential electors investigate Obama's eligibility References: <89pZk.9151$be.4743@nlpi061.nbdc.sbc.com> Message-ID: On Dec 3, 12:53?am, Bryan Olson wrote: > girbarob... at yahoo.com wrote: > > This message is not about the meaningless computer printout called > > More importantly, it's not about Python. I'm setting follow-ups to > talk.politics. > > > "Certification of Live Birth" that Obama propaganda machine calls his > > "Birth Certificate". The American people are still waiting for a copy > > of Obama's original birth certificate that includes all his birth > > information. > > The document is what Hawaii provides as certified copy of birth record. > It contains all the information the federal government requires to prove > citizenship by birth, and it shows that Barack Hussein Obama was born 04 > August 1961 in Honolulu. See: > > ? ?http://www.factcheck.org/elections-2008/born_in_the_usa.html > This garbage on factcheck.org is a worthless piece of paper insufficient to prove a US citizenship much less a natural born one. You need to have a long version of legitimate birth certificate that includes all birth information. Hawaii officials never even confirmed this piece of garbage on factcheck.org > > Remind your US presidential electors of their constitutional duty to > > investigate Obama's natural-born citizen status. > > > No federal agency like FBI or Secret Service, no Hawaii bureaucrats > > have ever investigated Obama's birth in Hawaii. Many illegal aliens in > > USA have official "birth certificates" issued by state bureaucrats on > > the basis of falsified birth records. > > Janice Okubo of Hawaii's Department of Health confirmed that the state > has Obama?s original birth certificate on record: > > ? ?http://hawaii.gov/health/about/pr/2008/08-93.pdf > > [...] Do you have a sufficient IQ to actually grasp what this news release says? All it says is that Hawaii has "Obama?s original birth certificate". It does not say anything whether this "Obama?s original birth certificate" is from Hawaii or Kenya or from Indonesia. Under the Hawaii laws, a parent could use an original birth certificate from another country to register a child in Hawaii and get today "Certification of Live Birth". People actually born in Hawaii do not get such "Certification of Live Birth", they get another document with different name. Considering all the public pressure on Hawaii officials to confirm Obama's birth in Hawaii, they would start any response with confirmation that Obama was born in Hawaii. Instead, they give you carefully worded garbage so that your low IQ brain can swallow it and Obama propaganda machine can beat into your worthless brain until you repeat it like a low IQ moron. > > > Remind your US presidential electors that they have the legal standing > > and constitutional duty to investigate Obama's birth in Hawaii by > > demanding that Obama provide all his original birth records, and a > > federal agency like FBI or Secret Service fully investigate them. > > That's not what the Constitution says. US Constitution, Article IV, > Section 1: "Full Faith and Credit shall be given in each State to the > public Acts, Records, and judicial Proceedings of every other State. And > the Congress may by general Laws prescribe the Manner in which such > Acts, Records and Proceedings shall be proved, and the Effect thereof." > > These haters seek to make Obama prove his records in ways others have > not had to, and beyond any manner prescribed by Congress within its > constitutional authority. > You do not have enough brain cells to understand anything you just quoted. Get one thing straight for your own self interest! THERE ARE TENS OF MILLIONS OF GUN OWNERS IN USA ONLY WAITING TO USE THEM ON ANYBODY WHO THREATENS THE US CONSTITUTION - so better use all your brain cells in your own self interest to resolve this matter now and not later. Run to Obama and beg him to release all birth records or things will not get any better. You are playing with fire. From eliben at gmail.com Tue Dec 16 01:21:43 2008 From: eliben at gmail.com (eliben) Date: Mon, 15 Dec 2008 22:21:43 -0800 (PST) Subject: parse C expression? References: Message-ID: On Dec 16, 1:48?am, Torsten Mohr wrote: > Hi, > > i found some examples when googling for the subject but nothing really > matched. > > Is there a standard module available that lets me parse a syntax like "C" > with numbers, operators, braces, variables and function calls? > > I'd like to use this to parse an own kind of configuration language > and preferred would be just standard modules. ?Is there something > available that is maybe based on shlex? > > Thanks for any hints, > Torsten. Sorry for the "shameless plug", but pycparser (http://code.google.com/ p/pycparser/) is exactly what you're looking for. It's a complete, pure-Python parser for ANSI C. Eli From castironpi at gmail.com Mon Dec 29 10:35:46 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 07:35:46 -0800 (PST) Subject: multiprocessing vs thread performance References: Message-ID: <7846b653-127c-4879-b7f7-fe5b1e591cb4@g1g2000pra.googlegroups.com> On Dec 29, 8:52?am, mk wrote: > Hello everyone, > > After readinghttp://www.python.org/dev/peps/pep-0371/I was under > impression that performance of multiprocessing package is similar to > that of thread / threading. However, to familiarize myself with both > packages I wrote my own test of spawning and returning 100,000 empty > threads or processes (while maintaining at most 100 processes / threads > active at any one time), respectively. > > The results I got are very different from the benchmark quoted in PEP > 371. On twin Xeon machine the threaded version executed in 5.54 secs, > while multiprocessing version took over 222 secs to complete! > > Am I doing smth wrong in code below? Or do I have to use > multiprocessing.Pool to get any decent results? I'm running a 1.6 GHz. I only ran 10000 empty threads and 10000 empty processes. The threads were the ones you wrote. The processes were empty executables written in a lower language, also run 100 at a time, started with 'subprocess', not 'multiprocessing'. The threads took 1.2 seconds. The processes took 24 seconds. The processes you wrote had only finished 3000 after several minutes. From v+python at g.nevcal.com Fri Dec 5 02:34:01 2008 From: v+python at g.nevcal.com (Glenn Linderman) Date: Thu, 04 Dec 2008 23:34:01 -0800 Subject: Multiple Versions of Python on Windows XP In-Reply-To: <4937DB4B.7060001@ncf.ca> References: <4934de22$0$27863$9b622d9e@news.freenet.de> <493592EE.9090005@v.loewis.de> <49378804.2050807@g.nevcal.com> <4937DB4B.7060001@ncf.ca> Message-ID: <4938D969.6060609@g.nevcal.com> On approximately 12/4/2008 5:29 AM, came the following characters from the keyboard of Colin J. Williams: > > > Glenn Linderman wrote: >> >> The equivalent of those commands is available via Windows Explorer, >> Tools / Folder Options, File Types, scroll-scroll-scroll your way to >> .py, Click Advanced, fiddle, copy paste apply, and other twaddle. > Yes, but what's needed is a further level of indirection. Currently, > this allows .py to be associated with a particular editor. It would > be great if there were some way of associating "Python.File", which is > created in the install process, with a particular editor. Then, one > is left with associating "Python.File" with a given version of > Python. Meanwhile, your suggestion provides a workaround. Sure, it is possible to simply change the Python.File ftype -- just issue the command ftype Python.File="C:\PythonNN\python.exe" "%1" %* for NN = 25, 26 or 30 or whatever. But that is longer and harder to remember and type than the assoc which is why chose to keep three ftypes around and switch between them with the assoc command. But if you put them in a batch file, or shortcut, the length and complexity wouldn't be as much of an issue. But changing one or changing the other is roughly equivalent... ftype is an extra level of indirection over assoc... and it is designed to allow programs that handle multiple extensions to not proliferate the full command for each extensions. For example, a multi-image-format image program, could use something like: assoc .jpg=ImageProg.File assoc .gif=ImageProg.File assoc .tif=ImageProg.File ftype ImageProg.file="C:\Program Files\ImageProg\ImageProg.exe" "%1" %* In that situation, because of the potentially large number of extensions, changing the assoc isn't equivalent to changing the ftype, but for Python, I'm unaware of it needing to handle multiple extensions from the command line or via double clicking in Explorer, so was exploiting the extra level of indirection to save typing, and make the command simpler to remember. Not sure what your reference to an editor is about. ftype only fiddles with the Shell Open command; if you want to do tricks with different editors for different versions of Python, then you have to fiddle the Shell Edit command; this can be done with clever manipulation of the registry... it would be straightforward to create a .reg file that swaps both the Shell Open and Shell Edit commands for different versions of Python, if that is useful... and maybe it is if you use an IDE of some sort. Since I just use emacs to edit .py files, I ignored the Shell Edit command. Instead I have a Shell Emacs command that is set up to apply to all file types, and is available via the context menu from Windows Explorer... but I use that not only for different versions of Python, but source code in other languages, and text files of all types. -- Glenn -- http://nevcal.com/ =========================== A protocol is complete when there is nothing left to remove. -- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking From luismgz at gmail.com Mon Dec 29 16:37:48 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Mon, 29 Dec 2008 13:37:48 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <59dfc7f8-cfd4-4e22-ad83-52cd8ea57c1f@e18g2000yqo.googlegroups.com> On 19 dic, 13:01, walterbyrd wrote: > I have not worked with Python enough to really know. But, it seems to > me that more I look at python 3.0, the more I wonder if it isn't a > step backwards. > > To me, it seems that this: > > print "%s=%d" % ('this',99) > > Is much easier, and faster, to type, and is also easier to read and > understand. It also allows people to leverage their knowledge of C. > > This (if it's right) is much longer, and requires more special > characters. > > print( "{0}={1}".format('this',99)) > > Maybe it's worth all the extra trouble, and breaking backward > compatibilty, and all. But, I never had the idea that the old way was > all that big a problem. Of course, I could be wrong. Was the old way > all that big of a problem? Well, I was playing with python 3k a little bit and, as usual, after a few minutes everything felt natural. The new string formating is perhaps a little more typing, much is much more clear and readable. I know where it came from. Long ago, Guido took a look at Boo, which is a python-like .NET language, and he posted a comment saying how much he liked the string formating, which is identical to the new one in python. I still can't get used to add the parenthesis to "print", and this is the only thing I don't like, but I'm sure there's a good reason for this change... Luis From jsutar at gmail.com Mon Dec 8 08:21:20 2008 From: jsutar at gmail.com (J Sutar) Date: Mon, 8 Dec 2008 13:21:20 +0000 Subject: newbie - merging xls files using xldt and xlwt In-Reply-To: References: <527424.71115.qm@web32704.mail.mud.yahoo.com> Message-ID: Hi, I have been provided with the program below. Which sets out to merge singlesheet excel files into one multisheet excel workbook. Though it manages to merge multiple files into one workbook many of the formats are not preserved. For example, what was originally 22.92% is converted to 0.2292... I was hoping if somebody could please help me understand how this can be fixed. Ideally I would like to create a program which merges files whilst keeping all formats (if at all possible). ####################################### """ Merge all xls files in a given directory into one multisheet xls file. The sheets get the orginal file name, without the extension. File names should not exceed 29 characters """ import xlrd, xlwt import glob, os.path def merge_xls (in_dir, out_file="K:/Stats Jobs 2003/St0883 (CITB - J33882)/3. Results/Excel/merged_output.xls"): xls_files = glob.glob(in_dir + "*.xls") sheet_names = [os.path.basename(v)[:-4] for v in xls_files] sheet_excl = [os.path.basename(v)[:-4] for v in xls_files if len(os.path.basename(v)[:-4]) > 29] merged_book = xlwt.Workbook() if in_dir[-1:] != "/": in_dir = in_dir + "/" xls_files.sort() if xls_files: for k, xls_file in enumerate(xls_files): print "---> Processing file %s" % (xls_file) if len (sheet_names[k]) <= 29: book = xlrd.open_workbook(xls_file) if book.nsheets == 1: ws = merged_book.add_sheet(sheet_names[k]) sheet = book.sheet_by_index(0) for rx in range(sheet.nrows): for cx in range(sheet.ncols): ws.write(rx, cx, sheet.cell_value(rx, cx)) elif book.nsheets in range(2, 100): for sheetx in range(book.nsheets): sheet0n = sheet_names[k]+str(sheetx+1).zfill(2) ws = merged_book.add_sheet(sheet0n) sheet = book.sheet_by_index(sheetx) for rx in range(sheet.nrows): for cx in range(sheet.ncols): ws.write(rx, cx, sheet.cell_value(rx, cx)) else: print "ERROR *** File %s has %s sheets (maximum is 99)" % (xls_file, book.nsheets) raise else: print "WARNING *** File name too long: <%s.xls> (maximum is 29 chars) " % (sheet_names[k]) print "WARNING *** File <%s.xls> was skipped." % (sheet_names[k]) merged_book.save(out_file) print print "---> Merged xls file written to %s using the following source files: " % (out_file) for k, v in enumerate(sheet_names): if len(v) <= 29: print "\t", str(k+1).zfill(3), "%s.xls" % (v) print if sheet_excl: print "--> The following files were skipped because the file name exceeds 29 characters: " for k, v in enumerate(sheet_excl): print "\t", str(k+1).zfill(3), v else: print "NOTE *** No xls files in %s. Nothing to do." % (in_dir) merge_xls(in_dir="C:/temp/test merge xls/") ####################################### Many thanks in advance. Jigs 2008/11/3 J Sutar > Mr Roskam, > > We have interacted before on the SPSS listserve, you have helped me out > fair few times! > > I need a helping hand again, do you have the final solution to this > problem, mergin xls from a given directory? > > Also where do I download the relevant modules from? > > Cheers > Jigs > > 2008/10/15 Albert-jan Roskam > > Hi John, >> >> Thanks! Using a higher xlrd version did the trick! Regarding your other >> remarks: >> -yep, input files with multiple sheets don't work yet. I kinda repressed >> that ;-) Spss outputs only single-sheet xls files, but I agree it's nicer if >> the programs works in other cases too. >> -and no, I don't intend to use data fields. Wouldn't it be easier to >> convert those to string values if I ever came across them? >> >> Thanks again! >> Albert-Jan >> >> >> --- On Wed, 10/15/08, John Machin wrote: >> >> > From: John Machin >> > Subject: Re: newbie - merging xls files using xldt and xlwt >> > To: python-list at python.org >> > Date: Wednesday, October 15, 2008, 3:14 PM >> > On Oct 15, 9:16 pm, Albert-jan Roskam >> > wrote: >> > > Hi, >> > > >> > > I wrote the program below to merge all xls files in a >> > given directory into one multisheet xls file. It uses xlwt >> > and xlrd. The xls files I use for input are generated by >> > Spss. When I open and re-save the files in Excel, the >> > program works, but when I use the xls files as they were >> > created by Spss, the program returns an error message (see >> > below). Some details: Python 2.4, xlwt version 0.7.0, xlrd >> > version 0.5.2, Win NT. >> > > >> > > Any ideas? >> > >> > The version of xlrd that you are using is an antique. Go to >> > http://pypi.python.org/pypi/xlrd and get the latest >> > version. If that >> > doesn't work, send me a copy of one of the files that >> > is displaying >> > this problem. >> > > >> > > Thanks in advance! >> > > >> > > Albert-Jan >> > > >> > > """ >> > > Merge all xls files in a given directory into one >> > multisheet xls file. >> > > The sheets get the orginal file name, without the >> > extension. >> > > File names should not exceed 31 characters, as this is >> > the maximum >> > > sheet name length >> > > """ >> > > >> > > import xlrd, xlwt >> > > import glob, os.path >> > > >> > > def merge_xls (in_dir, >> > out_file="d:/merged_output.xls"): >> > > >> > > xls_files = glob.glob(in_dir + >> > "*.xls") >> > > sheet_names = [] >> > > merged_book = xlwt.Workbook() >> > > >> > > [sheet_names.append(os.path.basename(v)[:-4]) >> > for k, v in enumerate(xls_files)] >> > >> > Wah! Try this: >> > sheet_names = [os.path.basename(v)[:-4]) for v in >> > xls_files] >> > >> > >> > > for k, xls_file in enumerate(xls_files): >> > > if len (sheet_names[k]) <= 31: >> > > book = xlrd.open_workbook(xls_file) >> > > ws = >> > merged_book.add_sheet(sheet_names[k]) >> > > for sheetx in range(book.nsheets): >> > > sheet = >> > book.sheet_by_index(sheetx) >> > > for rx in range(sheet.nrows): >> > > for cx in >> > range(sheet.ncols): >> > > ws.write(rx, cx, >> > sheet.cell_value(rx, cx)) >> > >> > I presume that you're not too worried about any date >> > data. >> > >> > If an input file has more than 1 sheet, you are creating >> > only one >> > sheet in the output file, and overwriting cells. >> > >> > > else: >> > >[snip] >> > > >> > > merge_xls(in_dir="d:/temp/") >> > > >> > > *** WARNING: OLE2 inconsistency: SSCS size is 0 but >> > SSAT size is non-zero *** >> > > put_cell 0 1 >> > > >> > > Traceback (most recent call last): >> > [snip] >> > > self._cell_types[rowx][colx] = ctype >> > > IndexError: list assignment index out of range >> > >> > Yeah, symptom of an xls file with a DIMENSIONS records that >> > lies ... >> > xlrd has like Excel become more resilient over time :-) >> > >> > BTW, consider joining the python-excel group at >> > http://groups.google.com/group/python-excel >> > >> > Cheers, >> > John >> > -- >> > http://mail.python.org/mailman/listinfo/python-list >> >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From prologic at shortcircuit.net.au Mon Dec 22 17:10:31 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 23 Dec 2008 08:10:31 +1000 Subject: Are Django/Turbogears too specific? In-Reply-To: <4E95C128-E1BC-41F8-ACDF-597C77F04512@semanchuk.com> References: <494eb16e$0$22710$426a74cc@news.free.fr> <2B198A4F-5911-456D-A45B-E073DB121446@semanchuk.com> <494F392C.5060201@wildenhain.de> <4E95C128-E1BC-41F8-ACDF-597C77F04512@semanchuk.com> Message-ID: On Tue, Dec 23, 2008 at 12:35 AM, Philip Semanchuk wrote: > > On Dec 22, 2008, at 1:52 AM, Tino Wildenhain wrote: > >> Philip Semanchuk wrote: >> ... >>> >>> I prefer Mako over the other template languages I've seen. >> >> From what I can tell Mako is nearly identical to all other >> template languages you might have seen (e.g. PHP style >> tags). Thats why I personally would not consider it. Its just >> much of a hassle to mix code and design this way. >> >> I prefer TAL (template attribute language, ZPT) [1] >> much over the other attempts I've seen ( and I've seen a lot) > > That's an excellent example of how Python can accommodate different tastes. > =) I can't stand TAL; I find it awkward and unPythonic. Your comment makes > sense, though. Mako and TAL have very different design philosophies, and if > you really like one, you're probably going to find the other strange at > best. I agree! :) And just for the record I prefer Mako :) (Not that I really use it at all) :P --JamesMills PS: Web Services FTW From wuwei23 at gmail.com Mon Dec 8 04:59:48 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 8 Dec 2008 01:59:48 -0800 (PST) Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? References: <5ccd4a18-cd2b-4040-90c6-33723af15e96@b38g2000prf.googlegroups.com> <7e1a9226-c7a9-4b5e-bfbb-ea079639d6a2@t39g2000prh.googlegroups.com> <682de8aa-62b1-477a-8b31-ae7698b1ffe7@w1g2000prk.googlegroups.com> Message-ID: <4b2bcda5-cee2-484e-9fc7-47caaf7a165e@z27g2000prd.googlegroups.com> On Dec 8, 7:18?pm, illume wrote: > It's easier to teach only requiring *using* classes, and functions > than *creating* them. ?This is important if it's being used to teach > programming - as you don't need to teach people two fairly large > concepts before you can do anything. I'm just kind of aghast at the idea of "teaching" anyone how to program games by using large, imperative chunks of code. I don't see functions as being a "fairly large concept" at all, and utterly vital to being able to write anything but the most basic 'hello world' example code. > Also python has very slow function calls, so avoiding using callbacks > is also faster. Wouldn't it be better to teach people the basics of coding -before- setting out to optimise their code? From hard4forget at gmail.com Sun Dec 7 15:44:55 2008 From: hard4forget at gmail.com (philips) Date: Sun, 7 Dec 2008 12:44:55 -0800 (PST) Subject: hi here is video of 13years old pregnent girl showing her belly the new world record www.funreality.com Message-ID: <55b4b121-7cd1-4ef9-bfd7-059bad04e690@j39g2000yqn.googlegroups.com> hi here is video of 13years old pregnent girl showing her belly the new world record www.funreality.com From rt8396 at gmail.com Tue Dec 23 00:05:22 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 21:05:22 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> <7c02eb33-a919-4481-8eda-76062729f233@k19g2000yqg.googlegroups.com> Message-ID: <32d8e3f1-52a7-4bce-a70a-70db488a417b@h20g2000yqn.googlegroups.com> On Dec 22, 10:09?pm, Ben Kaplan wrote: > That's just because most of us don't say anything unless we have ? > something useful to say. We prefer to let the experts answer the ? > questions, but we read the threads so we can benefit from them. OK Ben, So you are saying 1.) do not question the gods! 2.) speak only when spoken to! 3.) do not have an opinion! Somehow this reminds me of some old and brainwashing religions, Not an OSS project. Just observations Ben. From jcd at sdf.lonestar.org Mon Dec 15 16:58:57 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 15 Dec 2008 16:58:57 -0500 Subject: Removing None objects from a sequence In-Reply-To: References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> <0152e35f$0$8244$c3e8da3@news.astraweb.com> Message-ID: <1229378337.31120.13.camel@aalcdl07.lib.unc.edu> On Mon, 2008-12-15 at 02:11 +0000, Lie Ryan wrote: > On Fri, 12 Dec 2008 22:55:20 +0000, Steven D'Aprano wrote: > > > On Fri, 12 Dec 2008 21:18:36 +0000, Lie Ryan wrote: > >> Personally, I'd prefer VB's version: > >> foo IsNot bar > >> > >> or in pseudo-python > >> foo isnot bar > >> > >> since that would make it less ambiguous. > > > > "a is not b" is no more ambiguous than "1+2*3". True, there's ambiguity > > if you are ignorant of the precedence rules, but that's no worse than > > saying that "+" is ambiguous if you don't know what "+" means. > > > > "What's this 'is' operator??? It's ambiguous, it could mean ANYTHING!!! > > Panic panic panic panic!!!" > > > > *wink* > > > > You're allowed to assume the normal conventions, and (lucky for me!) > > despite being Dutch Guido choose to assume the normal English convention > > that "a is not b" means the same as "not (a is b)" rather than "a is > > (not b)". That's probably because the use-cases for the second would be > > rather rare. > > > > So given the normal precedence rules of Python, there is no ambiguity. > > True, you have to learn the rules, but that's no hardship. > > *I* know about the precedence rule, but a newbie or a tired programmer > might not. He might want to reverse the truth value of argument b but > instead has just reversed the whole expression. Probably in a slightly > convoluted code like this: > > if a is not(b and c): > ... > A newbie might make that mistake, but a tired programmer would be testing for equality rather than identity in that case, and if she weren't, she'd have to fix her code in the morning anyway. Cheers, Cliff From clp at rebertia.com Mon Dec 15 20:13:25 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 15 Dec 2008 17:13:25 -0800 Subject: tricky nested list unpacking problem In-Reply-To: <87fxkpxk41.fsf@daycos.com> References: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> <87fxkpxk41.fsf@daycos.com> Message-ID: <47c890dc0812151713u5f912273g7ffd50b86d894f68@mail.gmail.com> On Mon, Dec 15, 2008 at 12:24 PM, Kirk Strauser wrote: > At 2008-12-15T20:03:14Z, "Chris Rebert" writes: > >> You just need a recursive list-flattening function. There are many >> recipes for these. Here's mine: > >>>>> flattened = flatten([1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]]) >>>>> flattened >> [1, 2, 3, 5, 6, 10, 11, 7, 9, 1, 2, 3, 4, 5] >>>>> '-'.join(str(num) for num in flattened) >> '1-2-3-5-6-10-11-7-9-1-2-3-4-5' > > He doesn't want to flatten them directly. He's using [1,2,3] sort of like a > regular expression, so that 1,[2,3],4 means "1,2,4" or "1,3,4", not > "1,2,3,4". Ah, my bad. Misinterpreted. Still, it's a similar principle involved. He just needs to code up the right recursive function. Not all that hard. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From mirnazim at gmail.com Sun Dec 21 02:05:35 2008 From: mirnazim at gmail.com (Mir Nazim) Date: Sat, 20 Dec 2008 23:05:35 -0800 (PST) Subject: Question: Evaluate an string variable's value to a variable References: <4be6e91b-9fcf-4c22-bfe8-fad73190f87c@b41g2000pra.googlegroups.com> Message-ID: <7ec1c381-675a-45e2-994a-b2cebb5a11d7@t39g2000prh.googlegroups.com> On Dec 21, 11:56?am, "Chris Rebert" wrote: > On Sat, Dec 20, 2008 at 10:49 PM, Mir Nazim wrote: > > Just a quick question. > > > For example I have > > >>>> class X > >>>> ....pass > > > Then I do > >>>> x = X() > >>>> x.name = 'Nazim > > > Now my question is whether something like below is possible and how > >>>> y = 'name' > >>>> print x.y ? # ?How can x.y can be evaluated to x.name > > print getattr(x, y) #==> Nazim > > There are also analogous setattr() and delattr() functions. > Damn Right. These functions simply eluded my mind for well 15 minutes Thanks a lot Chris. > Cheers, > Chris > > -- > Follow the path of the Iguana...http://rebertia.com From lihang9999 at gmail.com Wed Dec 17 00:32:30 2008 From: lihang9999 at gmail.com (Li Han) Date: Tue, 16 Dec 2008 21:32:30 -0800 (PST) Subject: The rule of literal string Message-ID: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> Hi! I just began to read the tutorial of python3.0 and I just can't figure out the rule of literal string. There is a example in the tuotrial: >>> '"Isn\'t," she said.' '"Isn\'t," she said.' It is not what I want, I just want '"Isn't," she said.' be printed, why the backslash failed? These don't work at all: >>> '''"Isn't," she said.''' '"Isn\'t," she said.' >>> r"Isn't," she said. SyntaxError: invalid syntax (, line 1) >>> r'"Isn't," she said.' SyntaxError: invalid syntax (, line 1) I have tried to solve it until my brain damaged and now I need to sleep. From rhamph at gmail.com Mon Dec 8 16:10:53 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 8 Dec 2008 13:10:53 -0800 (PST) Subject: Rich Comparisons Gotcha References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Dec 8, 1:04?pm, Robert Kern wrote: > Rhamphoryncus wrote: > > On Dec 8, 11:54 am, Robert Kern wrote: > >> Rhamphoryncus wrote: > >>> On Dec 7, 4:20 pm, Steven D'Aprano >>> cybersource.com.au> wrote: > >>>> On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: > >>>>> Rasmus Fogh wrote: > >>>>>> Current behaviour is both inconsistent and counterintuitive, as these > >>>>>> examples show. > >>>>>>>>> x = float('NaN') > >>>>>>>>> x == x > >>>>>> False > >>>>> Blame IEEE for that one. Rich comparisons have nothing to do with that > >>>>> one. > >>>> There is nothing to blame them for. This is the correct behaviour. NaNs > >>>> should *not* compare equal to themselves, that's mathematically > >>>> incoherent. > >>> Mathematically, NaNs shouldn't be comparable at all. ?They should > >>> raise an exception when compared. ?In fact, they should raise an > >>> exception when *created*. ?But that's not what we want. ?What we want > >>> is a dummy value that silently plods through our calculations. ?For a > >>> dummy value it seems a lot more sense to pick an arbitrary yet > >>> consistent sort order (I suggest just above -Inf), rather than quietly > >>> screwing up the sort. > >> Well, there are explicitly two kinds of NaNs: signalling NaNs and quiet NaNs, to > >> accommodate both requirements. Additionally, there is significant flexibility in > >> trapping the signals. > > > Right, but most of that's lower level. ?By the time it reaches Python > > we only care about quiet NaNs. > > No, signaling NaNs raise the exception that you are asking for. You're right > that if you get a Python float object that is a NaN, it is probably going to be > quiet, but signaling NaNs can affect Python in the way that you want. > > >>> Regarding the mythical IEEE 754, although it's extremely rare to find > >>> quotations, I have one on just this subject. ?And it does NOT say "x > >>> == NaN gives false". ?It says it gives *unordered*. ?It is C and > >>> probably most other languages that turn that into false (as they want > >>> a dummy value, not an error.) > >>>http://groups.google.ca/group/sci.math.num-analysis/browse_thread/thr... > >> Table 4 on page 9 of the standard is pretty clear on the subject. When the two > >> operands are unordered, the operator == returns False. The standard defines how > >> to do comparisons notionally; two operands can be "greater than", "less than", > >> "equal" or "unordered". It then goes on to map these notional concepts to > >> programming language boolean predicates. > > > Ahh, interesting. ?Still though, does it give an explanation for such > > behaviour, or use cases? ?There must be some situation where blindly > > returning false is enough benefit to trump screwing up sorting. > > Well, the standard was written in the days of Fortran. You didn't really have > generic sorting routines. You *could* implement whatever ordering you wanted > because you *had* to implement the ordering yourself. You didn't have to use a > limited boolean predicate. > > Basically, the boolean predicates have to return either True or False. Neither > one is really satisfactory, but that's the constraint you're under. "We've always done it that way" is NOT a use case! Certainly, it's a factor, but it seems quite weak compared to the sort use case. I suppose what I'm hoping for is an small example program (one or a few functions) that needs the "always false" behaviour of NaN. From Mr.HassanShabbir at gmail.com Wed Dec 10 17:49:22 2008 From: Mr.HassanShabbir at gmail.com (Explore_Imagination) Date: Wed, 10 Dec 2008 14:49:22 -0800 (PST) Subject: How to convert uint64 in C into Python 32bit Object [ I am using Python2.2 ] Message-ID: <069f0d65-a3d5-4e8f-a85b-c53743ab99d0@i18g2000prf.googlegroups.com> Hi all I am new to C and python ... I want to convert C data type uint64 variable into the Python 32bit Object. I am currently using Python 2.2 [ It is necessary to use it ] Kindly give your suggestion how and in which way I can achieve this task. Looking forward for your positive feedback. Cheers From vlastimil.brom at gmail.com Wed Dec 3 09:39:11 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Wed, 3 Dec 2008 15:39:11 +0100 Subject: generating a liste of characters In-Reply-To: References: Message-ID: <9fdb569a0812030639x78a4444du710c7e813d4c81a@mail.gmail.com> 2008/12/3 Yves Dorfsman : > Is there any built in way to generate a list of characters, something > along the line of range('a'-'z') ? > > Right now I am using: > > chars = [ chr(l) for l in range(0x30, 0x3a) ] # 0 - 9 > chars += [ chr(l) for l in range(0x41, 0x5b) ] # A - Z > chars += [ chr(l) for l in range(0x61, 0x7b) ] # a - z > > Is there a better, more straight forward way of doing that ? > > > > Thanks. > > > > Yves. > http://www.sollers.ca/blog/2008/swappiness > http://www.sollers.ca/blog/2008/swappiness/.fr > > -- > http://mail.python.org/mailman/listinfo/python-list > If you want tu use it generaly an any characters, maybe ord() can make it a bit simpler: >>> map(unichr, range(ord("a"), ord("z"))) [u'a', u'b', u'c', u'd', u'e', u'f', u'g', u'h', u'i', u'j', u'k', u'l', u'm', u'n', u'o', u'p', u'q', u'r', u's', u't', u'u', u'v', u'w', u'x', u'y'] >>> otherewise see the string module with some predefined ranges. hth, vbr From isabellknauer at googlemail.com Fri Dec 5 09:51:58 2008 From: isabellknauer at googlemail.com (isabellknauer at googlemail.com) Date: Fri, 5 Dec 2008 06:51:58 -0800 (PST) Subject: ftp retrlines with re... Message-ID: Hey! Ive been working on an application quite some time now and i wanted to include something to let the user load a new version. i therefore tried to include this here: from ftplib import FTP import string,re def handleDownload(block): processfile.write(block) print ".", def load_new_version(old_version): host='host.bla' user='usr_ftp_76512' password='45mhBLl3lXRX.332' account='usr_ftp_76512' download='' directory = 'htdocs' server = FTP(host) server.login(user,password,account) server.cwd(directory) filelist=server.retrlines('LIST') #okay this works :logged into the ftpserver,changed dir and now have a #string that tells the files like this: #-rw-r--r-- 1 usr_ftp_76512 ftpgroup 14454 Dec 5 14:10 Pict5.2.2.jpg #-rw-r--r-- 1 usr_ftp_76512 ftpgroup 16174 Dec 5 12:37 Picture 3.jpg #-rw-r--r-- 1 usr_ftp_76512 ftpgroup 14139 Dec 5 12:38 Picture 6.jpg #-rw-r--r-- 1 usr_ftp_76512 ftpgroup 42713 Dec 5 12:38 Picture 7.jpg #226 Transfer complete. print filelist files=re.findall(' .{2,20}[.][a-z]{3,3}', filelist,re.I|re.S) #the dot means every char, because of the flag re.S # re.I ignores case #{2,20} this means 2 to twenty of the char that is before it #heres the problem... if you copy the output and put it into a string he #finds all the files with findall, but not inside here... and i dont get why #help:( print files for file in files: number=re.findall('pict([0-9])[.]([0-9])[.]? ([0-9]?)',file,re.I) version=100*int(number[0][0])+ 10*int(number[0][1])+ int(number [0][2]) if version >old_version: print version print old_version old_version=version download=file if download : processfile = open(download, 'wb') server.retrbinary('RETR ' + download, handleDownload) processfile.close() server.close() return True else: server.close() return False load_new_version(201) #greetz From martinjamesevans at gmail.com Thu Dec 4 10:37:14 2008 From: martinjamesevans at gmail.com (martinjamesevans at gmail.com) Date: Thu, 4 Dec 2008 07:37:14 -0800 (PST) Subject: EBCDIC <--> ASCII Message-ID: <091f0404-2be3-4bda-8619-03627bd03fdc@k8g2000yqn.googlegroups.com> I'm having a problem trying to use the codecs package to aid me in converting some bytes from EBCDIC into ASCII. I have some 8bit text that is in mixed format. I extract the bytes that are coded for EBCDIC and would like to display them correctly. The bytes that are EBCDIC could values 0-255, I'm only really interested in the printable portions and could say leave the rest as dots. I've tried starting with something like this, but I assume it is expecting the source to be in unicode already? e.g. (pretend the second half are EBCDIC characters) sAll = "This bit is ASCII, " sSource = sAll[19:] sEBCDIC = unicode(sSource, 'cp500', 'ignore') sASCII = sEBCDIC.encode('ascii') Obviously I could just knock up a 255 character lookup table and do it myself, I was just trying to be a little more Pythonic and use that built in table. Thanks, Martin From mmanns at gmx.net Thu Dec 18 20:24:37 2008 From: mmanns at gmx.net (mmanns at gmx.net) Date: Fri, 19 Dec 2008 02:24:37 +0100 Subject: Which sparse matrix package? References: <20081218231851.70dd91e2@Schlamber.localdomain> Message-ID: <20081219022437.0362726e@Schlamber.localdomain> On Thu, 18 Dec 2008 18:04:19 -0600 Robert Kern wrote: > Martin Manns wrote: > > > Should I use another type of matrix in scipy.sparse? If yes which? > > If you have a benchmark, you might just want to try all of them. > Should be just a matter of a small script. Block Sparse Row > (bsr_matrix) might be the most appropriate in terms of data > structure, but it appears that a bunch of stuff important for your > use case is unimplemented. This was my first impulse until I saw that the syntax and the actually implemented methods vary considerably inside scipy.sparse (different authors?). Before I code around all of that, I would like to to see, which functionality is really provided by which matrix class. Do you know where to find an overview (some docs)? Currently, I stumble upon unimplemented things in my unit tests and figure out what is going on after reading the sparse code :-( Martin From castironpi at gmail.com Sun Dec 14 18:53:27 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 14 Dec 2008 15:53:27 -0800 (PST) Subject: subprocess to C program References: <0ebd59c5-95a1-42d4-b597-d1c248490b8e@y1g2000pra.googlegroups.com> <8MidneyhDfIG-9nUnZ2dnUVZ_uadnZ2d@posted.visi> <36656830-63a8-479c-8c46-525f2b55eeea@z28g2000prd.googlegroups.com> <6e8f11eb-d773-4ffc-851c-a381228d4ae2@v4g2000yqa.googlegroups.com> Message-ID: <3047f141-bf0e-4c57-baf7-91156024523a@k36g2000pri.googlegroups.com> On Dec 14, 6:32?am, bobicanprogram wrote: > On Dec 13, 10:09 pm, MRAB wrote: > > > > > Aaron Brady wrote: > > > On Dec 13, 7:51 pm, Grant Edwards wrote: > > >> On 2008-12-14, MRAB wrote: > > > >>>> I am writing a C process and I want to read data from a file that I > > >>>> write to in Python. ?I'm creating a pipe in Python, passing it to the > > >>>> C process, and calling '_read'. ?It gives me error 9, bad file number. > > > snip > > >>>> meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9. ?I want 'ct' > > >>>> to be 11 at this point. ?Thanks in advance. > > >>> It looks like the ids aren't system global. > > >> They certainly aren't in Unix: Their a property of the process. > > > >> -- > > >> Grant > > > > I'm not on Unix. ?It has to be possible somehow. ?Do I need to set > > > permissions on the IDs? ?Are Stdin and Stdout my only options? ?Or > > > does Popen prevent sharing IDs somehow? > > > You'd be better off using sockets. > > You might also consider using SIMPL (http://www.icanprogram.com/simpl) > SIMPL has had a Python interface for about 5 years now. ? There is an > online tutorial here. (http://www.icanprogram.com/06py/main.html) > > In one of your responses you mentioned that you were not on Unix (and > I presume Linux). ? SIMPL-Python has recently been extended to work > transparently from a Windows OS as well. > > bob > SIMPL project coordinator The engine uses a disk-based FIFO for interprocess. It's good if you're looking for one- or two- way sequential. From __peter__ at web.de Fri Dec 19 08:54:16 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2008 14:54:16 +0100 Subject: importing csv file into sqlite References: <21067453.post@talk.nabble.com> <7f64f5c6-b130-4f9b-a670-6b32eccba550@n33g2000pri.googlegroups.com> Message-ID: klia wrote: > > > John Machin wrote: >> >> On Dec 18, 6:20?pm, klia wrote: >>> klia wrote: >>> >>> > hey guys, i have a hug .csv file which i need to insert it into sqlite >>> > database using python. >>> > my csv data looks like this >>> > Birthday2,12/5/2008,HTC,this is my birthday >>> > Sea,12/3/2008,kodak,sea >>> > birthday4,14/3/2009,samsung,birthday >>> > love,17/4/2009,SONY,view of island >>> >>> > can any one give me a head start codes. >>> >>> > thanks in advance >>> >>> guys so far i came out with this but i get this error >>> waseem at Linux:~/Project2$ python experment.py >>> Traceback (most recent call last): >>> File "experment.py", line 13, in >>> curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item) >>> sqlite3.ProgrammingError: Incorrect number of bindings supplied. The >>> current >>> statement uses 4, and there are 1 supplied. >>> >>> here's the codes >>> >>> import sqlite3 >>> import csv >>> >>> f = open('/home/waseem/Project2/photos.txt') >>> csv.field_size_limit(100000) #see below! >> >> I see nothing "below" that looks at all like an attempt to justify >> setting the field size limit to 100000 -- why are you doing that? >> Tends to make one suspect a problem with your delimiter and/or your >> line separator. >> >>> input = csv.reader(f, delimiter='\t') >> >> Why \t??? Your data examples show commas -- could this be why you are >> getting one field per line (as Peter has pointed out)? >> >>> conn = sqlite3.connect('/home/waseem/Project2/picutres.db') >> >> Is it really called "picutres" instead of "pictures", or are you >> typing the code that you ran again from (your) memory? >> >>> curse = conn.cursor() >>> >>> curse.execute('CREATE TABLE photos (Name VARCHAR(100) PRIMARY KEY, Date >>> INTEGER, Make VARCHAR(50), Tag VARCHAR(100))') >> >> [OT but to save the next question] >> The column named "Date" is defined to be INTEGER but the data from the >> CSV file will be a str object e.g. "12/5/2008" ... I know sqlite >> cheerfully regards column types as vague reminders rather than >> enforceable constraints on your input, but wouldn't you like to >> convert your dates to e.g. "2008-05-12" before you poke them in? You >> may want to use "ORDER BY Date" at some stage, and so that ORDER BY >> isn't whacked and GROUP BY doesn't give ludicrous results, wouldn't it >> be a good idea to crunch 12/5/2008 and 12/05/2008 into a common format >> so that they compare equal? >>> >>> for item in input: >> >> I strongly suggest that you try to get a clue about exactly what you >> are getting from the csv reader e.g. >> >> for line_num, item in enumerate(input_renamed_as_suggested_by_anor): >> print line_num, repr(item) >> >>> curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item) >>> curse.commit() >>> >> >> HTH, >> John >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > hey guys > i took all of your suggestion but my goal ain't yet achieved :-(( > these are the codes after changes, john i couldn't really catch what do > you mean by renaming input, is it just normal renaming.i am testing the > code on just simple .csv file with few data in as follows before trying on > my hug csv file but still no joy > > "Bithday",12-05-08,"HTC","this is my birthday" > "Sea",12-03-08,"kodak","sea" > "girl","14-03-2009","samsung","birthday" > "love","17-04-2009","SONY","view of island" > > import sqlite3 > import csv > > f = open('/home/waseem/Project2/photos.csv') > input = csv.reader(f, delimiter=',') > conn = sqlite3.connect('/home/waseem/Project2/pictures.db') > curse = conn.cursor() > > curse.execute('CREATE TABLE photos (Name VARCHAR(100) PRIMARY KEY, Date > INTEGER, Make VARCHAR(50), Tag VARCHAR(100))') > for row in input: > curse.execute('INSERT INTO photos VALUES (?,?,?,?)', '*row') This will try to set Name="*" Date="r" Make="o" Tag="w" for all records. Can you work out why? > curse.commit() > > this time i got this error > > waseem at Linux:~/Project2$ python experment.py > Traceback (most recent call last): > File "experment.py", line 12, in > curse.execute('INSERT INTO photos VALUES (?,?,?,?)', '*row') > sqlite3.IntegrityError: column Name is not unique > > i removed the primary key and single quotation mark for '*row' to just > *row but i got the old error which is > > waseem at Linux:~/Project2$ python experment.py > Traceback (most recent call last): > File "experment.py", line 11, in > curse.execute('INSERT INTO photos VALUES (?,?,?,?)', *row) > TypeError: function takes at most 2 arguments (5 given) curse.execute('INSERT INTO photos VALUES (?,?,?,?)', row) (no '*') will work for the sample data you give above. If you get errors with your real data you have to fix that data. Follow John's advice to locate the problematic records. Peter From narkewoody at gmail.com Tue Dec 23 23:27:02 2008 From: narkewoody at gmail.com (Steven Woody) Date: Wed, 24 Dec 2008 12:27:02 +0800 Subject: Multi-dimension list Message-ID: Hi, In the book Python Essential Reference, Chapter 3, I see an example: From fakeaddress at nowhere.org Mon Dec 15 22:12:06 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 15 Dec 2008 19:12:06 -0800 Subject: socket and subprocess problem In-Reply-To: <6d3291c3-4e12-4bdd-884a-21f15f38d105@a12g2000pro.googlegroups.com> References: <6d3291c3-4e12-4bdd-884a-21f15f38d105@a12g2000pro.googlegroups.com> Message-ID: goatold at gmail.com wrote: > In my python code I use subprocess.Popen to run and external program > who will listen to a TCP port. And I also create a socket to connect > to the TCP port that the external program is listening. > I will get 'Connection refused, errno=111' when I try to socket.connect > (). Looks like a race. The first process tries to connect before the external program gets through socket.listen(). If you think about it, it's not that surprising. > But if I run my subprocess.Popen code and socket code in two separate > python process. Socket will connect just fine. It's still a race condition even if the side you want to win almost always does. -- --Bryan From sjmachin at lexicon.net Thu Dec 11 20:59:38 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 11 Dec 2008 17:59:38 -0800 (PST) Subject: newbie question: if var1 == var2: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> <44aa0191-e374-4bf0-b039-d05cfa996b1d@p2g2000prn.googlegroups.com> Message-ID: <37fc3229-b0a2-4d95-990f-61300fc2b257@r37g2000prr.googlegroups.com> On Dec 12, 11:39?am, MRAB wrote: > Jason Scheirer wrote: > > On Dec 11, 3:49 pm, John Machin wrote: > >> On Dec 12, 10:31 am, "Rhodri James" > >> wrote: > > >>> On Thu, 11 Dec 2008 19:49:23 -0000, Steve Holden ? > >>> wrote: > >>>> Kirk Strauser wrote: > >>>>> At 2008-11-29T04:02:11Z, Mel writes: > >>>>>> You could try > >>>>>> for item in fname: > >>>>>> ? ? item = item.strip() > >>>>> This is one case where I really miss Perl's "chomp" function. ?It ? > >>>>> removes a > >>>>> trailing newline and nothing else, so you don't have to worry about ? > >>>>> losing > >>>>> leading or trailing spaces if those are important to you. > >>>> ... and it's so hard to write > >>>> ? ? ?item = item[:-1] > >>> Tsk. ?That would be "chop". ?"chomp" would be > >>> ? ? ?if item[-1] == '\n': > >>> ? ? ? ? ?item = item[:-1] > >> Better: > >> if item and item[-1] == '\n': > >> ? ? return item[:-1] > >> return item > > > Best: > > > return item \ > > ? ? ? ?if not (item and item.endswith('\n')) \ > > ? ? ? ?else item[:-1] > > > Though really you should be using item.rstrip() > > Why not just: > > ? ? ?item[:-1] if item.endswith('\n') else item Some possible reasons: * because you might be supporting old versions of Python (my offering runs on 1.5) * because the " if else " syntax gives you the screaming dry Edgar Britts * because you'd prefer not to have the overhead of a method lookup and method call From rogerb at rogerbinns.com Wed Dec 24 03:50:49 2008 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 24 Dec 2008 00:50:49 -0800 Subject: Most efficient way to build very large dictionaries In-Reply-To: <1230107768.14060.1291622121@webmail.messagingengine.com> References: <1230104615.5867.1291617213@webmail.messagingengine.com> <1230107768.14060.1291622121@webmail.messagingengine.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 python at bdurham.com wrote: > Thank you for your suggestion about looking at SQLite. I haven't > compared the performance of SQLite to Python dictionaries, but I'm > skeptical that SQLite would be faster than in-memory Python dictionaries > for the type of analysis I'm doing. I'd recommend at least trying a test just to see. As an example SQLite uses indices which will be faster than Python dicts for some set operations. (And if you aren't careful, your various Python based optimizations will end up duplicating what SQLite does internally anyway :-) > Prior to my use of Python, my > customer used a very expensive Oracle system to analyze their log files. > My simple Python scripts are 4-20x faster than the Oracle PL/SQL they > are replacing - and run on much cheaper hardware. SQLite is not like Oracle or any similar database system. It does not operate over the network or similar connection. It is a library in your process that has an optimized disk storage format (single file) and a SQL parser that generates bytecode for a special purpose virtual machine in pretty much the same way CPython operates. The performance improvements you are seeing with Python over Oracle are exactly the same range people see with SQLite over Oracle. One common usage reported on the SQLite mailing list is people copying data out of Oracle and running their analysis in SQLite because of the performance advantages. > Note: Memory is currently not a concern for me so I don't need SQLite's > ability to work with data sets larger than my physical memory. The pragmas tune things like cache sizes. The SQLite default is 2MB, relying on the operating system for caching beyond that. Bumping up that kind of size was my suggestion :-) Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAklR9+UACgkQmOOfHg372QSMbwCdGS5S2/96fWW8knjfBVqReAfV AEwAn2Yc+L9BEZgT69OjwtyqxLtifVpU =mPfy -----END PGP SIGNATURE----- From huwdjones at gmail.com Tue Dec 16 07:17:51 2008 From: huwdjones at gmail.com (huw_at1) Date: Tue, 16 Dec 2008 04:17:51 -0800 (PST) Subject: cx_Oracle issues References: <5b2dad81-2750-4347-8079-6ab31321d579@s1g2000prg.googlegroups.com> <9142a8f1-7f76-4fc0-9ca1-c9dec310f2ce@r37g2000prr.googlegroups.com> <9f436c9e-2319-499c-a306-d255996372fc@e22g2000vbe.googlegroups.com> Message-ID: <09b53231-5a92-437c-859b-6e5d0ce106c8@k36g2000pri.googlegroups.com> On Dec 15, 12:59?pm, "ron.re... at gmail.com" wrote: > On Dec 15, 2:44?am, huw_at1 wrote: > > > > > On Dec 11, 5:34?pm, "ron.re... at gmail.com" wrote: > > > > On Dec 10, 9:48?am, huw_at1 wrote: > > > > > Hey all. When usingcx_Oracleto run a procedure like: > > > > > cursor.execute("select (obj.function(value)) from table where > > > > id=blah") > > > > > I am getting the following error: > > > > > ORA-06502: PL/SQL: numeric or value error: character string buffer too > > > > small ORA-06512: at line 1 > > > > > Looking at cursor.description I get: > > > > > [('(obj.function(value))', , 4000, 4000, 0, > > > > 0, 1)] > > > > > Any tips - i have never seen this error before but am guessing that > > > > the value being returned is too big for the buffer size set for the > > > > cursor. the procedure fetches data from a LOB. > > > > > Any suggestions/confirmations? > > > > > Many thanks > > > > This error is a problem with the PL/SQL, notcx_Oracle. ?You need to > > > debug obj.function to see what kind of data is being accessed and then > > > a data analysis of that data to understand why this error occurs. ?I > > > can tell you the function is most likely expecting characters from a > > > column that are numeric [0 .. 9] and is getting alpha characters. > > > > -- > > > Ron Reidy > > > Sr. Oracle DBA > > > Hi thanks for the responses. Unfortunately the procedure in question > > is from a third party vendor so I can't really debug it so I'd say I > > was fairly stumped. Just out of interest how do you increase the > > output buffer size withcx_Oracle? > > > Many thanks- Hide quoted text - > > > - Show quoted text - > > Hi, > > Sure you can. ?You can see the PL/SQL source from the ditionary view > ALL_SOURCE: > select text from all_source where name = 'NAME_OF_FUNCTION'; > > From there, reverse engineeer which table(s) and column(s) are being > accesses and do the data analysis. > > -- > Ron Reidy Hi all, So I tried Rons query but unfortunately I got 0 records returned. However I can confirm that running the select query from a client does indeed generate the same error. Is there anything else I could try? Otherwise I'll just get in touch with the vendor I guess. From michael.mabin at gmail.com Fri Dec 5 11:09:08 2008 From: michael.mabin at gmail.com (Michael Mabin) Date: Fri, 5 Dec 2008 10:09:08 -0600 Subject: To Troll or Not To Troll (aka: "as" keyword woes) In-Reply-To: <896B75251BA19745A529B1B867893FA5DB0E@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA5DB0E@planet.delsci.local> Message-ID: Warren, weren't you aware that Python.org is now a church. So you can never live up to the standards of the Pythonista high priests. You can only ask a question or submit your comment then cower, hoping the pythonista high priests don't beat you with clubs for heresy. ;) 2008/12/4 Warren DeLano > > From: Ben Finney > > > > > > "Chris Mellon" writes: > > > > > Peculiarities in usenet resulted in this discussion having several > > > threads and I missed some messages before I wrote this email. > > > > I'll put this more bluntly: Warren's messages to date > > egregiously break the flow of discussion. > > > > Warren, in the interest of sane discussion in these forums, please: > > > > * preserve attribution lines on quoted material so we can see who > > wrote what. > > > > * use the convention of ?New subject (was: Old subject)? when you > > change the ?Subject? field of a message. > > > > * switch to a client that preserves threading in messages you send, > > i.e. that properly constructs the ?References? and ?In-Reply-To? > > fields. > > > > General advice good for everyone, of course, but particularly > > apropos to this reply. Any one of the above is detrimental to > > omit; striking on all three makes a discussion almost > > impossible to follow. (Thank you, though, for avoiding the > > worse habit of top posting!) > > Thank so much for the suggestions Ben. Sorry that I am personally > unable to live up to your high standards, but it is nevertheless an > honor to partipicate in such a helpful and mutually respectful community > mailing list! > > Warren > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.panesse at gmail.com Sun Dec 21 06:29:29 2008 From: robert.panesse at gmail.com (McCoy Fan) Date: Sun, 21 Dec 2008 03:29:29 -0800 (PST) Subject: Read an image from a URL and write it to the browser Message-ID: I want to do something simple: read an image from an image URL and write the image to the browser in CGI style. I wrote a CGI script to do this (I'm new to Python) and got the following error: "FancyURLopener instance has no attribute 'tempcache'" in Hi, in a module of mine (ftpserver.py) I'd want to add a (boolean) global variable named "use_gmt_times" to decide whether the server has to return times in GMT or localtime but I'm not sure if it is a good idea because of the "ethical" doubts I'm gonna write below. In first place I've never liked global variables too much and always preferred per-class-instance variables instead. The problem in my case is that I have to use such variable in two separated classes: FTPHandler and VirtualFileSystem. Also, I want that for no reason one class uses times in GMT and the other one local times. Another doubt is the naming convention. PEP-8 states that global variables should use the lower_case_naming_convention but I've seen a lot of library module using the UPPER_CASE_NAMING_CONVENTION. What am I supposed to do about it? Thanks in advance for any comment. --- Giampaolo http://code.google.com/p/pyftpdlib/ From manu3d at gmail.com Sat Dec 13 15:19:29 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Sat, 13 Dec 2008 12:19:29 -0800 (PST) Subject: Bidrectional Subprocess Communication Message-ID: Hi everybody, I'm trying to replicate the positive results of the Client/Server scripts from the thread "Bidirectional Networking", but this time using a Process/SubProcess architecture. The SubProcess, acting as a server, is working just fine. But the Process executing the SubProcess, the client, somehow doesn't hear any of the standard output from the SubProcess. What am I missing? Below you can find the two short pieces of code. Thanks for your help! Manu ------------------------------------------- # serverTest.py import sys print("Starting Server!") while True: data = sys.stdin.readline().strip() if(data): print("SERVER RECV: '" + data + "'") if(data == "Stop!"): break print("Server Stopped!") ------------------------------------------- #clientTest.py import sys import threading from time import sleep from subprocess import Popen, PIPE ## Server Thread class ListenerThread(threading.Thread): def __init__(self, inChannel): threading.Thread.__init__(self) self.inChannel = inChannel def run(self): while True: data = self.inChannel.readline().strip() print("serverTest.py says: " + data) print("Starting Client!") server = Popen("python serverTest.py", stdin=PIPE, stdout=PIPE) listenerThread = ListenerThread(server.stdout) listenerThread.setDaemon(True) listenerThread.start() server.stdin.write("Something very meaningful!\n") server.stdin.write("Stop!") print("Client Stopped!") From castironpi at gmail.com Sun Dec 7 06:26:08 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 7 Dec 2008 03:26:08 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> <014b2a09$0$20670$c3e8da3@news.astraweb.com> <5e58fbc8-17df-40ae-8b18-7b07765e898f@v38g2000yqb.googlegroups.com> Message-ID: On Dec 6, 9:35?pm, Carl Banks wrote: > On Dec 6, 8:17?pm, Steven D'Aprano > I don't like "cast", because a cast is an instruction to the compiler to > > treat data as some type other than what it was defined as. > It doesn't > > create a new piece of data. (At least in C-like languages.) > > Actually, C-like languages do exactly that. ?(float)i doesn't take the > bits of int i and treat them as if they were a float, it creates new > data in the appropriate data type that matches the value of i > semantically, which would have a very different bit pattern. '(float&) i' does what he said. int i; float& f= ( (float&) i ); f= 1; printf( "%x %f\n", i, f ); /Output: 3f800000 1.000000 Sorry for the tangent. From _karlo_ at _mosor.net_ Sun Dec 14 06:52:15 2008 From: _karlo_ at _mosor.net_ (Karlo Lozovina) Date: Sun, 14 Dec 2008 11:52:15 +0000 (UTC) Subject: curses and refreshing problem References: <69d2698a-6f44-4d85-adc3-1180ab158632@r15g2000prd.googlegroups.com> Message-ID: Carl Banks wrote in news:69d2698a-6f44-4d85-adc3-1180ab158632 at r15g2000prd.googlegroups.com: > Unless you are referring to some wget screen mode I don't know about, > I suspect wget outputs its progress bar using carriage returns > without newlines. If that's all you want, there is no need to use > curses. > > Here is a little example program to illustrate: > > import time, sys > for i in range(21): > sys.stdout.write('\rProgress: [' + '='*i + ' '*(20-i) + ']') > sys.stdout.flush() > time.sleep(1) > sys.stdout.write("\nFinised!\n") Thanks, that's it! I just assumed wget uses curses for the progress bar, so the carriage return didn't even cross my mind ;). -- _______ Karlo Lozovina - Mosor | | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163 | || _ | _ | Parce mihi domine quia Dalmata sum. |__|_|__||_____|_____| From jeremiah.dodds at gmail.com Tue Dec 2 20:17:48 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Tue, 2 Dec 2008 20:17:48 -0500 Subject: Pyhon (with wxPython) on Windows' cygwin: can it be done fully ? In-Reply-To: <9c313975-874a-4d50-a05c-e984db6ee0f7@l42g2000yqe.googlegroups.com> References: <6p2l98F61ttqU1@mid.uni-berlin.de> <4a4fa55e-779c-47bd-a6bd-4829abaa4824@d42g2000prb.googlegroups.com> <2a7664b4-668c-4269-8feb-cb35e23260dd@o4g2000pra.googlegroups.com> <9c313975-874a-4d50-a05c-e984db6ee0f7@l42g2000yqe.googlegroups.com> Message-ID: <12cbbbfc0812021717o4fcbb16co9926cee5cc36212c@mail.gmail.com> On Mon, Dec 1, 2008 at 12:25 PM, Fernando H. Sanches < fernandohsanches at gmail.com> wrote: > At first I also disliked print's new syntax, but later I realised it > could be useful. > > However, I agree that the parentheses are annoying. Not because of the > parens theirselves, but because of the Shift key. > > Why programmers stilll can't have special keyboards with parens keys > that doesn't need pressing "shift"? Isn't time C programmers have a > "&" key and perl programmers a $ one? And why the heck we need shift > for "(" and not for "[" or "{", since the first one is much more used > (even outside programming)? > > Really, we don't need to change our syntax, we need to change our > keyboards. We are so blinded by tradition that we are losing > productivity. > -- > http://mail.python.org/mailman/listinfo/python-list > Obligatory: http://groups.google.com/group/comp.lang.lisp/msg/f499cca6b478260f?hl=en&pli=1 I've actually always wanted to try doing something like that, but haven't actually worked up the gumption to go anywhere past swapping caps and ctrl. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 9 08:50:58 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 09 Dec 2008 14:50:58 +0100 Subject: Beginner trying to understand functions. In-Reply-To: References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> <9df7549a-f28b-4d39-b105-90c099f472f2@z28g2000prd.googlegroups.com> <040a2896-be99-477e-909c-c55c5a0e6665@y1g2000pra.googlegroups.com> Message-ID: <493e77bb$0$28214$426a74cc@news.free.fr> simonh a ?crit : > Thanks for the extra tips Ivan and Bruno. Here is how the program > looks now. Any problems? > > > > import sys > > def get_name(): > name = input('Please enter your name: ') > print('Hello', name) This one would be better spelled "get_and_display_name" !-) > def get_age(): > try: > return int(input('Please enter your age: ')) > except ValueError: > print('That was not a valid number. Please try again.') > return get_age() Warning : there's a recursion limit in Python. While there are very few chances you hit it in this case, it may bite you one day if you start using recursion instead of iteration. > def check_age(age,min=18,max=31): > if age < min: > print('Sorry, too young.') > elif age >= max: > print('Sorry, too old.') > else: > print('Come on in!') > > def again(): > response = input('Try again? Y or N: ') > while response != "Y": You probably mean 'if response != "Y"' ? > if response == 'N': > print('Program finished.') > input('Press any key to exit.') > sys.exit() > else: > return response This return value is never used in the calling code. And if the user types anything else than "Y" or "N", the program will exit without even a goodbye message. > run() > def run(): > get_name() > a = get_age() > check_age(a) > again() As far as I'm concerned, I'd write it that way: def read_string(question, error=''): if not error: error = "That was not a valid string. Please try again." while True: result = input(question).strip() if result: return result else: print error def read_int(question, error=''): if not error: error = "That was not a valid number. Please try again." while True: try: return int(input(question).strip()) except ValueError: print(error) def check_in_range(obj, mini, maxi, if_ok=0, if_lesser=-1, if_greater=1) if obj < mini: return if_lesser elif age >= max: return if_greater else: return if_ok def again(question="Try again ?", yes="Y", no="N"): # XXX : see appropriate string formatting for Python 3 # in 2.x, I'd write it as: # prompt = "%s (%s or %s): " % (question, yes, no) prompt = question + " " + yes" + " or " + no + ": " while True: response = input(prompt) if response in (yes, no): return response == yes def run(): name = read_string("Please enter your name: ") print("Hello, ", name) age = read_int("Please enter your age: ") messages = { 0: "Come on in!", -1: "Sorry, too young", 1: "Sorry, too old", } message_key = check_in_range(age, 18, 31) print(messages[message_key]) def main(): while True: run() if not again(): print('Program finished.') input('Press any key to exit.') return if __name__ == "__main__": main() NB : the 'if __name__ == "__main__"' will allow you to use your code as both a script (ie : calling it as 'main' program) or as a module (importing it from within another script or module so you can reuse the functions), by only calling 'main()' if the file is used as a script. HTH From rdmurray at bitdance.com Fri Dec 12 10:25:48 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Fri, 12 Dec 2008 10:25:48 -0500 (EST) Subject: Interface & Implementation In-Reply-To: <11e2ac5b5eb.2364397661727502391.6806593866408074890@adventnet.com> References: <11e2ac5b5eb.2364397661727502391.6806593866408074890@adventnet.com> Message-ID: On Fri, 12 Dec 2008 at 16:07, J Ramesh Kumar wrote: > I am new to python. I require some help on implementing interface and > its implementation. I could not find any sample code in the web. Can > you please send me some sample code which is similar to the below java > code ? Thanks in advance for your help. > > ............ > public interface MyIfc > { > public void myMeth1(); > public void myMeth2(); > } > .... > public class MyClass implements MyIfc > { > public void myMeth1() > { > //do some implementation > } > > public void myMeth2() > { > //do some implementation > } > } > ... > > MyClass myc=new MyClass(); > Hashtable hash=new Hashtable(); > hash.put("MYIFC",myc); > ........ > MyIfc myi=(MyIfc)hash.get("MYIFC"); > myi.myMeth1(); > myi.myMeth2(); > ......... The python 2.x way to to this would be: class MyClass(object): def myMeth1(self): #do some implementation def myMeth2(self): #do some implementation myc = MyClass() hash = dict() hash["MYIFC"] = myc myi = hash["MYIFC"] myi.myMeth1() myi.myMeth2() Which is to say, python 2.x does not have any formal notion of interfaces. In python 3.0 if you have a need for an interface you can do this: from abc import ABCMeta, abstractmethod class MyIfc: __metaclass__ = ABCMeta @abstractmethod def myMeth1(self): pass @abstractmethod def myMeth2(self): pass class MyClass(MyIfc): [from here on just like above] Note however, that an Abstract Base Class is _not_ the same thing as a Java interface, though it can serve some of the same purposes. See http://docs.python.org/dev/3.0/whatsnew/2.6.html#pep-3119 for more. --RDM From invalid at invalid Tue Dec 23 12:35:11 2008 From: invalid at invalid (Grant Edwards) Date: Tue, 23 Dec 2008 11:35:11 -0600 Subject: pseudo terminal usage from Python? References: <5t-dnRgMi9Z4lszUnZ2dnUVZ_vOdnZ2d@posted.visi> Message-ID: On 2008-12-23, skip at pobox.com wrote: > Grant> Are you sure it's not Python buffering its input? Have you tried > Grant> "python -u mympstat.py"? > > Hmmm... No, I hadn't considered that. I'll check it out. Thanks... > > Grant> I had a Linux pty example running once upon a time. If "python > Grant> -u" doesn't work post again, and I'll try to find it. > > Would be helpful even if I don't need it for this task, as I've not been > able to find any simple examples on the net. (Maybe there's a recipe at > ActiveState, but Google didn't pick up anything with the search terms I was > using.) I'll try to dig it up. The application for which I was trying to use ptys needed to communication modem control/status line state info between master and slave (as well as parity and word-length settings), so I abandoned ptys when I found they only implement a small subset of the icotl's that are defined for tty devices. I've proposed enhancing the Linux pty driver so that it can actually be used to simulate a serial port, but the proposal has been ignored so far. -- Grant Edwards grante Yow! I'm definitely not at in Omaha! visi.com From rtw at freenet.co.uk Mon Dec 15 16:35:17 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Mon, 15 Dec 2008 15:35:17 -0600 Subject: How can I return a non-zero status result from a python script? References: <74b53da4-bf07-431b-898b-49977f7a685c@r36g2000prf.googlegroups.com> Message-ID: silverburgh.meryl at gmail.com wrote in news:74b53da4-bf07-431b-898b- 49977f7a685c at r36g2000prf.googlegroups.com in comp.lang.python: > Hi > > How can I return a non-zero status result from the script? Just do a > return 1? at the end? > >>> import sys >>> help( sys.exit ) Help on built-in function exit in module sys: exit(...) exit([status]) Exit the interpreter by raising SystemExit(status). If the status is omitted or None, it defaults to zero (i.e., success). If the status is numeric, it will be used as the system exit status. If it is another kind of object, it will be printed and the system exit status will be one (i.e., failure). >>> Rob. -- http://www.victim-prime.dsl.pipex.com/ From prologic at shortcircuit.net.au Tue Dec 2 04:20:59 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 2 Dec 2008 19:20:59 +1000 Subject: How to sort a list of file paths In-Reply-To: <2F0A3D19CA15C143B0688EC94220748720D1F89A61@SE-EX007.groupinfra.com> References: <2F0A3D19CA15C143B0688EC94220748720D1F89A61@SE-EX007.groupinfra.com> Message-ID: Hi Eriksson, It's nice to see people actually contribute what they've learned back to the community. Great problem, well thought out solution and congrats on the learning :) I can't say per say that I've actually run into a situation where I need to sort file paths in this way ... But if I do I'll be sure to use your function :) --JamesMills On Tue, Dec 2, 2008 at 6:36 PM, Eriksson, John wrote: > Hi, > > > > This weekend I had some problems to get a list containing file paths to be > sorted in a way that I could use. > > > > I also found a thread in this mailing list ( > http://mail.python.org/pipermail/python-list/2007-April/433590.html ) and > realized that others might be interested in a solution. > > > > So... here is my five cents regarding file path sorting: > > > > Problem description: > > > > You have a list containing some file names: > > > >>>> file_list = ["File2.txt","File1.txt","File10.txt"] > > > > If you sort this list in the conventional way you end up with a result like: > > > >>>> file_list.sort() > >>>> print file_list > > ['File1.txt','File10.txt','File2.txt'] > > > > Solution: > > > > Sort the list by splitting alphas and digits in to groups and compare them > separately. > > > > import re > > def true_alphanum_cmp(a,b): > > aa = re.findall(r'\d |\D ', a) > > bb = re.findall(r'\d |\D ', b) > > for i in range(min(len(aa),len(bb))): > > if aa[i].isdigit() and bb[i].isdigit(): > > c = cmp(int(aa[i]),int(bb[i])) > > else: > > c = cmp(aa[i],bb[i]) > > if c!=0: > > return c > > return cmp(len(aa),len(bb)) > > > > file_list = ["File2.txt","File1.txt","File10.txt"] > > file_list.sort(true_alphanum_cmp) > > > > If the formatting in this mail is messed up you can find the example at > http://arainyday.se/notebook/true_alphanum_cmp.php > > > > All comments and improvements are welcome! > > > > Best regards > > John Eriksson > > _________________________________________ > > > > Logica - Releasing your potential > > Tegsplan 2b > > 904 20 UME? > > Sweden > > > > T: +46 (0) 90 15 91 38 > > M: +46 (0) 70 366 16 77 > > E: john.eriksson at logica.com > > www.logica.se > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- -- -- "Problems are solved by method" From xahlee at gmail.com Tue Dec 9 18:19:47 2008 From: xahlee at gmail.com (Xah Lee) Date: Tue, 9 Dec 2008 15:19:47 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <4ridneQnkLrPkKDUnZ2dnUVZ8qbinZ2d@posted.plusnet> Message-ID: <986b6ea1-efba-4146-9704-5f9e3787c26a@a37g2000pre.googlegroups.com> On Dec 8, 4:07 am, Jon Harrop wrote: > s... at netherlands.com wrote: > > Well, its past 'tonight' and 6 hours to go till past 'tomorrow'. > > Where the hell is it Zah Zah? > > Note that this program takes several days to compute in Mathematica (even > though it takes under four seconds in other languages) so don't expect to > see a genuinely optimized version any time soon... ;-) Note that Jon's Mathematica code is of very poor quality, as i've given detailed analysis here: ? A Mathematica Optimization Problem http://xahlee.org/UnixResource_dir/writ/Mathematica_optimization.html I'm not sure he's intentionally making Mathematica look bad or just sloppiness. I presume it is sloppiness, since the Mathematica code is not shown in his public website on this speed comparison issue. (as far as i know) I suppose, he initialled tried this draft version, saw that it is too slow for comparsion, and probably among other reason he didn't include it in the speed comparison. However, in this thread about Mathematica 7, he wanted to insert his random gribe to pave roads to post his website books and url on OCml/f#, so he took out this piece of Mathematica to bad mouth it and bait. He ignored my paypal challenge, but it so happens that someone else paid me $20 to show a better code, and in the showdown, Jon went defensive that just make him looking like a major idiot. Xah ? http://xahlee.org/ ? From bearophileHUGS at lycos.com Mon Dec 8 09:37:30 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 8 Dec 2008 06:37:30 -0800 (PST) Subject: Public imports References: <9623b0a3-7053-41f1-b116-0cd5e54f39e9@v13g2000vbb.googlegroups.com> <8e382f56-3048-4fdc-881a-700416d29156@n41g2000yqh.googlegroups.com> Message-ID: <113b1ecc-58a4-46f8-8dd9-6a5b585bfa0b@l39g2000yqn.googlegroups.com> > D type system has several big holes, I meant "D module system", of course. Sorry. Bye, bearophile From Astley.lejasper at gmail.com Wed Dec 3 13:33:57 2008 From: Astley.lejasper at gmail.com (Astley Le Jasper) Date: Wed, 3 Dec 2008 10:33:57 -0800 (PST) Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> <126ba84a-0ea0-4a91-b7d2-89ed650e5d6c@d32g2000yqe.googlegroups.com> Message-ID: On 3 Dec, 16:41, Philip Semanchuk wrote: > On Dec 3, 2008, at 10:29 AM, Astley Le Jasper wrote: > > > I've included a switch to include or exclude theloggingto console. > > Whenloggingonly to file, the script runs fine. > > > Of course, I still don't understand whyduallogging, and specifically > > to the console, causes a problem and if anyone has any comments about > > thedualoutputloggingcode above then I'd still be happy to hear > > about it. > > Trying to write non-ASCII characters perchance? Errmmm ... that's kind of spoookey. I using UTF-8 encoding as I have a lot of European language characters. But would that cause a problem when running from crontab but not in the terminal? Go on then ... spill the beans. From steve at holdenweb.com Fri Dec 12 09:54:02 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Dec 2008 09:54:02 -0500 Subject: var or inout parm? In-Reply-To: <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> Message-ID: <49427B0A.50108@holdenweb.com> sturlamolden wrote: > On Dec 12, 3:08 pm, Marc 'BlackJack' Rintsch wrote: > >> No bug because a mutation *is* attempted. ``a += x`` calls `a.__iadd__` >> which *always* returns the result which is *always* rebound to the name >> `a`. Even with mutable objects where `__iadd__()` simply returns >> `self`! > > No, a mutation is not attempted, even if __iadd__() always returns a > value. If a rebinding of a member to the same member is attempted, the > tuple should not raise an exception. The tuple should check that it is > actually being *mutated* before it raises any exception. There is an > attempted write to the tuple, but not an attempted mutation of the > tuple. The tuple should tell the difference. Immutability does not > imply inwriteability, if the write operation changes nothing. But the > tuple raises an exception on any write attempt. > OK, so if you regard the current behavior as a bug explain how to modify the tuple's __iadd__ method and the coding of the INPLACE_ADD operator. At least in pseudocode. Criticism is easy. Now demonstrate that it's *informed* criticism. Enough of the "should". I am always suspicious of suggestions that say what the interpreter "should" or "should not" do. It makes it sound as though you can wave a magic wand to achieve the desired behavior. The interpreter "should not" have a GIL. The tuple "should" check that it is actually being mutated. How? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steven at REMOVE.THIS.cybersource.com.au Mon Dec 8 21:41:34 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 09 Dec 2008 02:41:34 GMT Subject: Calling function from a string References: <7bc1be6f-121e-409a-9e08-f2dd2a86f241@e25g2000vbe.googlegroups.com> Message-ID: On Mon, 08 Dec 2008 14:29:01 -0800, Chris Rebert wrote: > On Mon, Dec 8, 2008 at 2:23 PM, Robert Dailey > wrote: >> Hi, >> >> I have a string representing the name of a function in Python 3.0. How >> can I call the function name represented by this string *without* >> creating a mapping? > > Assuming the function is within scope: > > return_val = vars()[the_string](arguments, go, here) Or use eval("%s(arguments go here)" % the_string) (untested in Python 3, but should work) Are you aware of the great big enormous security hole you're creating if the_string is untrusted data? -- Steven From gagsl-py2 at yahoo.com.ar Fri Dec 26 09:12:37 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 26 Dec 2008 12:12:37 -0200 Subject: Socket recv function taking longer time References: Message-ID: En Fri, 26 Dec 2008 11:36:15 -0200, escribi?: > I have designed a recieving system in C. I have used the sockets > recv function. The problem I m facing is that the sending system does > not wait for the ACK(the amount of time it waits 4 the Ack is too less > as the recv takes more time to read the msg), it keeps on sending the > same msg again and again even before the recv func has read the whole > message and my recieving system gets hanged. How do I solve this. I don't understand the problem. If the receiving side is in C, I guess the sending side is written in Python? Then just wait for the ACK from the other side for a longer time... Or try to explain better what's your problem - posting some code would be good. -- Gabriel Genellina From rhf22 at mole.bio.cam.ac.uk Wed Dec 10 09:50:07 2008 From: rhf22 at mole.bio.cam.ac.uk (Rasmus Fogh) Date: Wed, 10 Dec 2008 14:50:07 +0000 (GMT) Subject: Rich Comparisons Gotcha Message-ID: Rhodri James wrote: > On Mon, 08 Dec 2008 14:24:59 -0000, Rasmus Fogh wrote: >> On the minus side there would be the difference between >> '__equal__' and '__eq__' to confuse people. > This is a very big minus. It would be far better to spell __equal__ in > such a way as to make it clear why it wasn't the same as __eq__, > otherwise > you end up with the confusion that the Perl "==" and "eq" operators > regularly cause. You are probably right, unfortunately. That proposal is unlikely to fly. Do you think my latest proposal, raising BoolNotDefinedError, has better chances? --------------------------------------------------------------------------- Dr. Rasmus H. Fogh Email: r.h.fogh at bioc.cam.ac.uk Dept. of Biochemistry, University of Cambridge, 80 Tennis Court Road, Cambridge CB2 1GA, UK. FAX (01223)766002 From python.list at tim.thechases.com Fri Dec 12 12:58:32 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 12 Dec 2008 11:58:32 -0600 Subject: newbie question... In-Reply-To: References: Message-ID: <4942A648.3020506@tim.thechases.com> > Im new at python and I just want to know if (and how) it is possible > to send parameters to a program. > > what I mean is that when we start python I can call a file that should > be run like this: python myfile.py > can I send additional parameters along with it? like::: python > myfile.py myVar1 myVar2 You're looking for sys.argv: tim at rubbish:~$ python - one two Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) [GCC 4.2.4 (Debian 4.2.4-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.argv ['-', 'one', 'two'] -tkc From mark.dufour at gmail.com Fri Dec 5 06:24:54 2008 From: mark.dufour at gmail.com (Mark Dufour) Date: Fri, 5 Dec 2008 12:24:54 +0100 Subject: ANN: Shed Skin 0.0.30, an experimental (restricted-)Python-to-C++ Compiler Message-ID: <8180ef690812050324j1dc6c570ib9644137bbc193c6@mail.gmail.com> Hi all, I have just released version 0.0.30 of Shed Skin, an experimental (restricted) Python-to-C++ compiler. Most importantly, this release adds (efficient) support for user-defined classes in generated extension modules, which should make it much easier to integrate compiled code within larger projects. More specifically, compiled classes can now be instantiated on the CPython side, and instances can be passed freely between CPython and Shed Skin without any conversion taking place. (Instances of builtin classes are still (recursively) copied, though, at the moment..) Another major improvement was contributed by FFAO: a new 'set' implementation, directly based on the CPython code. While I haven't tested it on many benchmarks, it is clear that is now much faster, and on one benchmark it even outperforms CPython on my system by about 35%. Other notable changes include complex number support, mapping None to NULL instead of 0 and printing it as 'None', as well as an important type inference fix. With support for user-defined classes in extension modules, it looks like all the major pieces are now there to do a 0.1 release. The only thing I'd really like to do before that, is to improve support for the 'os' module. Please let me know if you'd like to help out here! Hopefully, with many details out of the way, I can have another good look at type inference for 0.2.. Thanks, Mark. -- "One of my most productive days was throwing away 1000 lines of code" - Ken Thompson From rt8396 at gmail.com Sun Dec 21 16:40:47 2008 From: rt8396 at gmail.com (r) Date: Sun, 21 Dec 2008 13:40:47 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <494ea35c$0$12776$426a74cc@news.free.fr> Message-ID: <689c6f0f-f2a0-4978-b0d1-9ffdf5af73b7@r15g2000prh.googlegroups.com> Hey Bruno, Thanks for spelling it out for me :D From spooklight at gmail.com Sun Dec 14 16:51:20 2008 From: spooklight at gmail.com (uair01) Date: Sun, 14 Dec 2008 13:51:20 -0800 (PST) Subject: Output to file gets lost - don't know where to look ... References: <26a47940-c997-4da4-8f05-205b8d3001a8@d42g2000prb.googlegroups.com> Message-ID: > I will try the python program outside of IDLE. Yes, running the program from the Linux shell instead of from IDLE produces all output correctly. Now I'll have to look for a new simple development environment :-( I think I'll try SPE that has worked well for me ... From rt8396 at gmail.com Wed Dec 24 17:00:25 2008 From: rt8396 at gmail.com (r) Date: Wed, 24 Dec 2008 14:00:25 -0800 (PST) Subject: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> <9eae14b8-93d6-4c34-b7d3-56c27408b52f@a26g2000prf.googlegroups.com> Message-ID: <2725aa51-4c75-4a8f-8b74-9f36657522db@v4g2000vbb.googlegroups.com> On Dec 22, 6:55?pm, John Machin wrote: > On Dec 23, 10:24?am, r wrote: > > > Because my balls are so big i walk around bow-legged! > > Have you considered that your alleged testicular enormity may in fact > be an illusion caused by a hernia? John i see some troll rated your post with one star, so i rated it myself with 5. I actually thought it was quite amusing, and shows you yourself have a solid pair, unlike some others around here who's have not even dropped yet. :) From david.andrzejewski at gmail.com Tue Dec 2 16:34:15 2008 From: david.andrzejewski at gmail.com (DaveA) Date: Tue, 2 Dec 2008 13:34:15 -0800 (PST) Subject: Vista Compatibility Message-ID: <21331a9e-64d1-4090-a8c4-d2e3fd6f30f2@y18g2000yqn.googlegroups.com> There was a thread about this about a year ago, but I wanted to see if anyone could clarify this question for me - what is the first officially sanctioned version of Python that is known to be fully working under Windows Vista? The best I could find is some indications that point to 2.5 being the first. I'm asking because we have a Python 2.3.4 runtime for an application that we're now looking into running on Vista. Thanks! From bdesth.quelquechose at free.quelquepart.fr Tue Dec 30 16:12:31 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 30 Dec 2008 22:12:31 +0100 Subject: "return" in def In-Reply-To: <016969d3$0$6988$c3e8da3@news.astraweb.com> References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <40b1b762-459b-4d6f-91f0-0a6e68d233ae@a26g2000prf.googlegroups.com> <4d396242-13c9-4318-97ba-99f18564fbc5@o4g2000pra.googlegroups.com> <016969d3$0$6988$c3e8da3@news.astraweb.com> Message-ID: <495a9c6f$0$14467$426a74cc@news.free.fr> Steven D'Aprano a ?crit : (snip) > Avoiding early exits is an over-reaction to the Bad Old Days of spaghetti > code. Mostly, yes. It can also be a way to help avoiding "resource leaks" (memory or whatever) - just like try/finally blocks or the 'with' statement in Python. > But used wisely, early exists can simplify, not complicate, code. > > Consider the following: > > def find_ham(alist): > for item in alist: > if isinstance(item, Ham): > return item > raise ValueError('no ham found') > > > def find_spam(alist): > found_item = None > for item in alist: > if found_item is not None: > if isinstance(item, Spam): > found_item = item > if found_item is None: > raise ValueError('no spam found') > else: > return found_item > > The second version has double the number of lines of code of the first. And doesn't do the same thing (hint: you forgot a break statement). Also and FWIW, the "single exit" golden rule (hem) comes from languages without exception handling. So a fair comparison would be: def find_egg(alist): for item in alist: if isinstance(item, Egg): return item return None vs: def find_sausage(alist): found = None for item in alist: if isinstance(item, Sausage): found = item break return found Granted, this still doesn't make the second version better than the first !-) But: > I don't think the claim that the version with an early exit is more > complicated than the version without can justified. Certainly not in this simple (simplistic ?) example. Now in C or Pascal, functions tend to be much longer and complicated, thanks to all the gory details one has to take care of. Not that I'm advocating "no early return" as a "golden rule" - specially in Python where functions tend to be short and readable -, but there really are cases (depending on the language *and* concrete use case) where avoiding early returns makes for more readable and robust code. My 2 cents... From sjmachin at lexicon.net Tue Dec 30 17:57:44 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 30 Dec 2008 14:57:44 -0800 (PST) Subject: need help with list/variables References: <63b5acce-d566-48cb-abce-c00fd0e02a39@v39g2000pro.googlegroups.com> Message-ID: <05a4f4df-2e6c-4a36-ab06-31e10c9f2100@s9g2000prg.googlegroups.com> On Dec 31, 6:41?am, 5lvqbw... at sneakemail.com wrote: > On Dec 30, 11:31?am, wx1... at gmail.com wrote: > > > I have a list and would like to parse the list appending each list > > item to the end of a variable on a new line. > > > for instance > > > mylist = ['something\n', 'another something\n', 'something again\n'] > > > then parse mylist to make it appear in my variable in this format: > > > myvar = """ > > something > > another something > > something again""" > > > how would i go about setting a variable like this? > > I think you want to concatenate the three elements in your list and > then assign the resulting string to myvar. ?Strings that are defined > with tripple quotes still get the newline character as though they > were defined with double or single quotes and \n in them. > > >>> conc = lambda x,y: x[:] + y # concatenate 2 lists without side effects > >>> mylist = ['something\n', 'another something\n', 'something again\n'] > >>> myvar = reduce(conc, mylist) > >>> print myvar OTOH escapees from FORTRAN would prefer something like: TOT = '' for I in xrange(len(MYLIST)): TOT = TOT + MYLIST[I] FTNWRITE(6, '*', TOT) SNOpy, anyone? From rt8396 at gmail.com Mon Dec 22 15:56:05 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 12:56:05 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> <494febd1$0$20851$426a74cc@news.free.fr> Message-ID: <430191c4-6ab3-487c-a6f5-616d9dde5596@t26g2000prh.googlegroups.com> On Dec 22, 12:36?pm, Bruno Desthuilliers wrote: > As far as I'm concerned, I don't think Python is "superior" (OMG), I > think it's a good language that happens to fit my brain *and* solve more > than 80% of my programmer's needs. If you're not happy with Python's > perfs, please contribute, you are welcome. He is contributing, by bringing up the subject for debate. Volunteers exist on all levels, not just the people who write code for CPython. Every OOS project needs diversity. There is base code, maintenance code, tutorials, essays, promotion(even if you consider it fanboyism),etc, etc. """Every spoke on a wheel is just as important as all the rest""", Bruno. From sjmachin at lexicon.net Fri Dec 12 13:53:20 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 12 Dec 2008 10:53:20 -0800 (PST) Subject: (Very Newbie) Problems defining a variable References: Message-ID: On Dec 13, 4:50?am, Dennis Lee Bieber wrote: > On Fri, 12 Dec 2008 03:42:55 -0800 (PST), feb... at gmail.com declaimed the > following in comp.lang.python: > > > #!/usr/bin/python > > #Py3k, UTF-8 > > > bank = int(input("How much money is in your account?\n>>")) > > target = int(input("How much money would you like to earn each year? > > \n>>")) > > ? ? ? ? Just for my curiosity -- did Python 3.x (besides turning print into > a function) also change input() to behave as the old raw_input()? Yup. There've been some other tectonic plate shift effects, e.g.: xrange() -> range(); range() -> list(range()) dict.iteritems() -> dict.items(); dict.items() -> list(dict.items()) halfassci() -> repr(); repr() -> ascii() From marco at sferacarta.com Mon Dec 22 10:37:13 2008 From: marco at sferacarta.com (Marco Mariani) Date: Mon, 22 Dec 2008 16:37:13 +0100 Subject: Python's popularity In-Reply-To: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: walterbyrd wrote: > I have read that python is the world's 3rd most popular language, and > that python has surpassed perl in popularity, but I am not seeing it. In 20 days, you've gone from trying to import a module by using: > load "test.py" to questioning the popularity of python. You have many other subject you want to enlighten us about, I suppose? Cause I wonder what you'll come up with, next. From deets at nospam.web.de Thu Dec 4 09:58:38 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 04 Dec 2008 15:58:38 +0100 Subject: Python Runtime Method Call Binding References: Message-ID: <6pq9guF9cb20U1@mid.uni-berlin.de> k3xji wrote: > Hi, > > Is there a way to hook a function call in python? I know __getattr__ > is doing for variables, it is giving us a chance before a field is > initialized. Do we have same functionality for methods? > > Example: > > class Foo(object): > def __call_method__(self, ...) # just pseudo > print 'A method is called in object...' > > f = Foo() > f.test_method() > > I think you understand my point. The special method __call__ is your friend. class SomethingCallable(object): def __call__(self): print "I'm called, and you not!" SomethingCallable()() Diez From zhushenli at gmail.com Wed Dec 3 22:20:33 2008 From: zhushenli at gmail.com (Davy) Date: Wed, 3 Dec 2008 19:20:33 -0800 (PST) Subject: time.sleep() and Tkinter after()? Message-ID: <03613d37-ca4f-4962-bce2-eea0a3f65952@r15g2000prd.googlegroups.com> Hi all, I have used Tkinter after() to do loop update GUI in my previous post. See http://groups.google.com/group/comp.lang.python/browse_thread/thread/6b616abc236c345b/7df7684d33c969c5#7df7684d33c969c5 And I tried to change after() to time.sleep(), but it seems doesn't work at all, the Queue send and receive data properly, but the GUI didn't even appear? //-----code changed----- def draw_canvas_loop(canvas_b): while (True): board = data_queue.get(block = True, timeout=2) print 'get', data_queue.qsize() draw_canvas(board, canvas_b, x, y, block_width, block_height) time.sleep(0.3) ##canvas_b.after(300, lambda:draw_canvas_loop(canvas_b)) //-------------------------------- So, can I use time.sleep() in GUI application? Or Tkinter scheduler just ignore the sleep() function? And if I use after(), will the code form a recursive function call, and the memory usage will boost as the program goes (I have watched the task manager in WinXP and find the python.exe eat more and more memory...). //------code----------- def draw_canvas_loop(canvas_b): board = data_queue.get(block = True, timeout=1) print 'get', data_queue.qsize() draw_canvas(board, canvas_b, x, y, block_width, block_height) canvas_b.after(300, lambda:draw_canvas_loop(canvas_b)) //------------------------- Best regards, Davy From zaz600 at gmail.com Thu Dec 25 08:55:16 2008 From: zaz600 at gmail.com (NoName) Date: Thu, 25 Dec 2008 05:55:16 -0800 (PST) Subject: SyntaxError: encoding problem: with BOM References: <6res8tF1do1sU1@mid.uni-berlin.de> <400f176b-bd9a-4f26-b01b-1aa7c7dcf5ac@z6g2000pre.googlegroups.com> <6rf6m1F1e0f8U1@mid.uni-berlin.de> Message-ID: <26e21f3f-ded1-48ca-8897-2ebd05dd07ad@w39g2000prb.googlegroups.com> > NoName, Asking people to download a zip file from a website written in > a language and character set that they probably are not familiar with > is liable to make them rather nervous and not bother. It's not a good > way to ask for help. sorry:) Now i know where problem. But i dont know how to solve it. Error ---- C:\Documents and Settings\Ra\??????? ????>11.py File "", line 1 SyntaxError: encoding problem: with BOM No error ---- C:\Documents and Settings\Ra\??????? ????>python 11.py test Error when russian symbols in full path to py-script. Is it Python bug? or i need to modify some registry keys? OS: WinXP SP3 Russian. Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32 From benjamin.kaplan at case.edu Sun Dec 14 23:44:37 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 14 Dec 2008 23:44:37 -0500 Subject: Python is slow In-Reply-To: References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> Message-ID: On Sun, Dec 14, 2008 at 11:38 PM, cm_gui wrote: > > hahaha, do you know how much money they are spending on hardware to > make > youtube.com fast??? Obviously not enough to get to the point where it's cheaper to have the programmers write C code. And the hardware is more for handling the intense traffic that YouTube gets, not for speeding up the site. > > > > By the way... I know of a very slow Python site called YouTube.com. In > > fact, it is so slow that nobody ever uses it. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dstanek at dstanek.com Thu Dec 25 19:35:48 2008 From: dstanek at dstanek.com (David Stanek) Date: Thu, 25 Dec 2008 19:35:48 -0500 Subject: Exec inside a class method to call other class methods? In-Reply-To: <47c890dc0812251624m7e1c5e55rb538996a52d56675@mail.gmail.com> References: <4953CF57.8080905@sympatico.ca> <20081226001641.GA22946@sdf.lonestar.org> <47c890dc0812251624m7e1c5e55rb538996a52d56675@mail.gmail.com> Message-ID: You won't need the dictionary at all if each type has a parse method. On 12/25/08, Chris Rebert wrote: > On Thu, Dec 25, 2008 at 4:16 PM, J. Clifford Dyer > wrote: > >> and so forth. Then your if/else chain can be pulled out to the place >> where you instantiate each field: >> >> if data_type=='address': >> field=AddressDataField(data) >> elif data_type=='due_date': >> field=DueDateDataField(data) >> else: >> field = DataField(data) >> > > And then you use a dictionary of data_type to class to get rid of the > if-else chain altogether: > > type2klass = {'address' : AddressDataField, 'due_date' : DueDateDataField} > #etc > Klass = type2klass.get(data_type, DataField) #use DataField as fallback > default > field = Klass(data) > > Merry Christmas, > Chris > > -- > Follow the path of the Iguana... > http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > -- Sent from my mobile device David http://www.traceback.org From stef.mientki at gmail.com Thu Dec 11 13:12:32 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 11 Dec 2008 19:12:32 +0100 Subject: Mathematica 7 compares to other languages In-Reply-To: <20081211180751.4139f2ec@usenot.de> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <87r64f9sma.fsf@rudin.co.uk> <20081211180751.4139f2ec@usenot.de> Message-ID: <49415810.9010103@gmail.com> Andreas Waldenburger wrote: > On Thu, 11 Dec 2008 05:40:45 +0000 Paul Rudin > wrote: > > >> "Dotan Cohen" writes: >> >> >>> 2008/12/10 : >>> >>>> Ruby: >>>> >>>> def norm a >>>> s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) >>>> a.map{|x| x/s} >>>> end >>>> >>> If someone doesn't counter with a Python one-liner then I'm going to >>> port that to brainfuck. >>> >> from numpy.linalg import norm >> >> :) >> > > This is one line of Python code alright, but it's not a "one-liner" in > the "computes the a normalized vector"-sense (which was the original > challenge, if there ever was one). > > If anything, you are now ready to compute the *norm* of a vector in a > subseqent line. (Or, if you must, after a semicolon on the same line.) > > Couldn't we assume that when you doing these kinds of math, there's always import numpy or from numpy import * is always at the start of the program, so it doesn't belong to the functional code ? And for those who use VPython (and thus needs " from visual import *" ) can simply do a = norm ( v ) cheers, Stef From taskinoor.hasan at csebuet.org Tue Dec 2 00:24:29 2008 From: taskinoor.hasan at csebuet.org (Taskinoor Hasan) Date: Tue, 2 Dec 2008 11:24:29 +0600 Subject: Do more imported objects affect performance In-Reply-To: <1be78d220812010621u51dead9dnbaa0b4c8c9414362@mail.gmail.com> References: <1be78d220812010621u51dead9dnbaa0b4c8c9414362@mail.gmail.com> Message-ID: <79153a2e0812012124o7401df57m4ac21dfe37c2ec5@mail.gmail.com> On Mon, Dec 1, 2008 at 8:21 PM, Filip Gruszczy?ski wrote: > I see. Thanks for a really good explanation, I like to know, how to do > things in the proper way :) I always prefer to use import module and then use module.function. The reason is simple. It makes the code more readable and maintainable. > > > 2008/12/1 Nick Craig-Wood : > > Rafe wrote: > >> On Dec 1, 7:26?am, "Filip Gruszczy?ski" wrote: > >> > I have following question: if I use > >> > > >> > from module import * > >> > > >> > instead > >> > > >> > from module import Class > >> > > >> > am I affecting performance of my program? I believe, that all those > >> > names must be stored somewhere, when they are imported and then > >> > browsed when one of them is called. So am I putting a lot of "garbage" > >> > to this storage and make those searches longer? > >> > >> Why use it if you don't need it? Your post implies a choice and the > >> '*' import can really make things muddy if it isn't actually necessary > >> (rare). Why not just import the module and use what you need? It is > >> way easier to read/debug and maintains the name-space. > > > > Importing the module is actualy slower... If you import the name into > > your namespace then there is only one lookup to do. If you import the > > module there are two. > > > > $ python -m timeit -s 'from timeit import Timer' 'Timer' > > 10000000 loops, best of 3: 0.0784 usec per loop > > > > $ python -m timeit -s 'import timeit' 'timeit.Timer' > > 1000000 loops, best of 3: 0.243 usec per loop > > > > I'm not suggestion you should ever use "from module import *" only > > ever import the things you actually need, eg > > "from module import MyClass, my_function" > > > > And here is the test again, actually calling something with the same > > difference in execution speed :- > > > > $ python -m timeit -s 'from os import nice' 'nice(0)' > > 1000000 loops, best of 3: 1.21 usec per loop > > > > $ python -m timeit -s 'import os' 'os.nice(0)' > > 1000000 loops, best of 3: 1.48 usec per loop > > > > -- > > Nick Craig-Wood -- http://www.craig-wood.com/nick > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > Filip Gruszczy?ski > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eric at ericaro.net Fri Dec 5 10:44:21 2008 From: eric at ericaro.net (eric) Date: Fri, 5 Dec 2008 07:44:21 -0800 (PST) Subject: A more pythonic way of writting References: <35d176ed-df5f-46b4-8321-4814fcc4398c@f3g2000yqf.googlegroups.com> Message-ID: <8de7622d-28a7-4f96-9fb0-21cda357dcf3@r36g2000prf.googlegroups.com> On Dec 5, 3:44?pm, "Mark Tolonen" wrote: > "eric" wrote in message > > news:35d176ed-df5f-46b4-8321-4814fcc4398c at f3g2000yqf.googlegroups.com... > > > def flag(IGNORECASE=False, LOCALE=False, MULTILINE=False, > > DOTALL=False, UNICODE=False, VERBOSE=False): > > ? ?vals = [IGNORECASE, LOCALE, MULTILINE, DOTALL, UNICODE, VERBOSE] > > ? ?filtered = map( lambda m:m[1],filter( lambda m: m[0], > > zip(vals,'iLmsux'))) > > ? ?return '?'+''.join( filtered ?) > > ? ? filtered = [c for c,v in zip('iLmsux',vals) if v] > > -Mark thank you very much ! great ! I can't get used to this late 'if' syntax ! @Gerard nice hypercube function. But I'll keep with my implementation : I like to believe that the less the 'debug pointer' stands in the python code, the fastest the code is (or is potentially) I keep thinking that def hypercube(ndims) : for i in range(1< References: <38f9c4ba-d96d-47e1-b718-562bdc6718e9@t26g2000prh.googlegroups.com> Message-ID: <4943D9AB.7040006@tim.thechases.com> > Any special reasons? Because it is there (at least on my Debian box)? tim at rubbish:~$ python Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) [GCC 4.2.4 (Debian 4.2.4-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.strftime('%c') 'Sat Dec 13 09:35:03 2008' >>> time.strftime('%e') '13' Taken from[1] The full set of format codes supported varies across platforms, because Python calls the platform C library's strftime() function, and platform variations are common. So if your underlying C implementation of strftime() supports "%e", then Python will. My guess is that the same applies to time.strftime as it does to datetime.strftime The docs list ones that are fairly cross-platform. However, it would seem that not all platforms support "%e" -tkc [1] http://docs.python.org/library/datetime.html#module-datetime From steve at holdenweb.com Sun Dec 28 23:31:42 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 28 Dec 2008 23:31:42 -0500 Subject: ftp design question In-Reply-To: <74706983-5198-436b-b0ca-b0246a41c67e@v5g2000prm.googlegroups.com> References: <74706983-5198-436b-b0ca-b0246a41c67e@v5g2000prm.googlegroups.com> Message-ID: <495852AE.9030701@holdenweb.com> nemo wrote: > Hi,all. > I'm on a toy ftp project and I want it to be convinient for the user > to cancel an undergoing downloading while continue others. The > following code explains: > for file in download_files: > self.ftp.retrbinary('RETR '+file, fileHandler) > Thers seems not a solid way to cancel this transfer and I considered > thread or process but I can't handle this correctly. > Thread: I can't kill the thread in another thread, so... > Process: There seems something wrong(raise an EOFError exception) when > I use Process(target = download_fun, args = (dir,)) for each > downloading after connection built. > Some suggestions? How about for file in download_files: try: self.ftp.retrbinary('RETR %s' % file, fileHandler) except KeyboardInterrupt: print file, "transfer abandoned" Then you can cancel a single file transfer with Ctrl/C. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steve at REMOVE-THIS-cybersource.com.au Sun Dec 14 04:47:50 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Dec 2008 09:47:50 GMT Subject: Optimizing methods away or not? References: <0154b041$0$6988$c3e8da3@news.astraweb.com> <6qk1dhFcr01gU1@mid.uni-berlin.de> Message-ID: <0154cdc2$0$6988$c3e8da3@news.astraweb.com> On Sun, 14 Dec 2008 09:19:45 +0000, Marc 'BlackJack' Rintsch wrote: > On Sun, 14 Dec 2008 07:41:55 +0000, Steven D'Aprano wrote: > >> I have a class with a method meant to verify internal program logic >> (not data supplied by the caller). Because it is time-consuming but >> optional, I treat it as a complex assertion statement, and optimize it >> away if __debug__ is false: ... >> What do others >> think? Which do you consider better design? > > None of it. Why not simply: > > class Parrot: > def __init__(self, *args): > print "Initialising instance..." > assert self._verify() > > def _verify(self): > print "Verifying..." > return None For your method to work, I'd have to have _verify return a boolean flag instead of None, because assert None always fails. > If you compile with -O the ``assert`` is optimized away. But you still > can call `_verify()` at specific points even in optimized code if you > want or need. That's a reasonable approach, if my use-case was for the caller to call the verify method. It's not: it's verifying my program logic rather than the caller's data, and it's only meaningful to do that verification at initialisation time. -- Steven From castironpi at gmail.com Mon Dec 29 21:35:21 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 18:35:21 -0800 (PST) Subject: get method References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> <4819de67-72dc-415c-b4c8-2353581c2bc7@r2g2000vbp.googlegroups.com> <0169782e$0$6988$c3e8da3@news.astraweb.com> Message-ID: <1a88bbb6-605a-4035-8af0-c4db5f07e945@d42g2000prb.googlegroups.com> On Dec 29, 8:02?pm, Steven D'Aprano wrote: > On Mon, 29 Dec 2008 17:38:36 -0800, Ross wrote: > > On Dec 29, 8:07?pm, Scott David Daniels wrote: > >> Ross wrote: > >> > ... Use get to write histogram more concisely. You should be able to > >> > eliminate the if statement. > > >> > def histogram(s): > >> > ? ?d = dict() > >> > ? ?for c in s: > >> > ? ? ? ? ? ?d[c]= d.get(c,0) > >> > ? ?return d > > >> > This code returns a dictionary of all the letters to any string s I > >> > give it but each corresponding value is incorrectly the default of 0. > >> > What am I doing wrong? > > >> How is this code supposed to count? > > >> --Scott David Daniels > >> Scott.Dani... at Acm.Org > > > I realize the code isn't counting, but how am I to do this without using > > an if statement as the problem instructs? snip > So what you need is: > > * set d[c] to whatever d[c] already is plus one, or 0 plus one if it > isn't already there. > > It's a two character change to one line. Let us know if you still can't > see it. That's actually really sophisticated. Steven is being really clever here, by writing a number in an unusual way. He said: * set d[c] to whatever d[c] already is plus one, or 0 plus one if it isn't already there. It is the same as: * set d[c] to whatever d[c] already is plus one, or one if it isn't already there. Side-by-side. Perhaps you will learn his secret someday. It has to do with 0+1=1. Armed with it, he has: something something +1, something something something +1 Which brings us (to): ( something something, something something something ) +1 Three cheers for thinking. From castironpi at gmail.com Mon Dec 29 08:40:42 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 05:40:42 -0800 (PST) Subject: Get a list of functions in a file References: Message-ID: <44e9ff55-767c-4b61-a645-4e930fb255c7@t39g2000prh.googlegroups.com> On Dec 29, 3:50?am, "Chris Rebert" wrote: > On Sun, Dec 28, 2008 at 11:26 PM, member Basu wrote: > > I'm putting some utility functions in a file and then building a simple > > shell interface to them. Is their some way I can automatically get a list of > > all the functions in the file? I could wrap them in a class and then use > > attributes, but I'd rather leave them as simple functions. > > Assuming you've already imported the module as 'mod': > > func_names = [name for name in dir(mod) if callable(getattr(mod, name))] > funcs = [getattr(mod, name) for name in dir(mod) if > callable(getattr(mod, name))] > > Note that such lists will also include classes (as they too are > callable). There are ways of excluding classes (and other objects that > implement __call__), but it makes the code a bit more complicated. No, not in general. It's a weakness of one of the strengths of Python. For instance, if you define a function in a string, or return one from another function, there's no way to get at it. If you do want to import it, you can put any executable code inside an 'if __name__== "__main__"' block, so it won't get executed while you're trying to index/catalog it. If you're interested in something more hard-core, you might like the 'tokenize' module. And I think the pattern you're looking for is 'every "def" outside a string, and even some in one.' P.S. Did not receive the original message on Google Groups. From walterbyrd at iname.com Sun Dec 7 14:22:23 2008 From: walterbyrd at iname.com (walterbyrd) Date: Sun, 7 Dec 2008 11:22:23 -0800 (PST) Subject: Is 3.0 worth breaking backward compatibility? Message-ID: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> IMO: breaking backward compatibility is a big deal, and should only be done when it is seriously needed. Also, IMO, most of, if not all, of the changes being made in 3.0 are debatable, at best. I can not think of anything that is being changed that was really a "show stopper" anyway. At best, I am a casual python user, so it's likely that I am missing something. From python.list at tim.thechases.com Wed Dec 31 10:48:29 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 31 Dec 2008 09:48:29 -0600 Subject: change only the nth occurrence of a pattern in a string In-Reply-To: <0scs26-7a5.ln1@rama.fbx.proxad.net> References: <0scs26-7a5.ln1@rama.fbx.proxad.net> Message-ID: <495B944D.8020302@tim.thechases.com> > I would like to change only the nth occurence of a pattern in > a string. The problem with "replace" method of strings, and > "re.sub" is that we can only define the number of occurrences > to change from the first one. > >>>> v="coucou" >>>> v.replace("o","i",2) > 'ciuciu' >>>> import re >>>> re.sub( "o", "i", v,2) > 'ciuciu' >>>> re.sub( "o", "i", v,1) > 'ciucou' > > What is the best way to change only the nth occurence > (occurrence number n)? Well, there are multiple ways of doing this, including munging the regexp to skip over the first instances of a match. Something like the following untested: re.sub("((?:[^o]*o){2})o", r"\1i", s) However, for a more generic solution, you could use something like import re class Nth(object): def __init__(self, n_min, n_max, replacement): #assert n_min <= n_max, \ # "Hey, look, I don't know what I'm doing!" if n_max > n_min: # don't be a dope n_min, n_max = n_max, n_min self.n_min = n_min self.n_max = n_max self.replacement = replacement self.calls = 0 def __call__(self, matchobj): self.calls += 1 if self.n_min <= self.calls <= self.n_max: return self.replacement return matchobj.group(0) s = 'coucoucoucou' print "Initial:" print s print "Just positions 3-4:" print re.sub('o', Nth(3,4,'i'), s) for params in [ (1, 1, 'i'), # just the 1st (1, 2, 'i'), # 1-2 (2, 2, 'i'), # just the 2nd (2, 3, 'i'), # 2-3 (2, 4, 'i'), # 2-4 (4, 4, 'i'), # just the 4th ]: print "Nth(%i, %i, %s)" % params print re.sub('o', Nth(*params), s) > Why this default behavior? Can't answer that one, but with so many easy solutions, it's not been a big concern of mine. -tkc From kwmsmith at gmail.com Wed Dec 17 16:59:18 2008 From: kwmsmith at gmail.com (Kurt Smith) Date: Wed, 17 Dec 2008 15:59:18 -0600 Subject: getting object instead of string from dir() In-Reply-To: <477b9c2e-a0ab-4b26-b643-4a9369c2aaac@r2g2000vbp.googlegroups.com> References: <477b9c2e-a0ab-4b26-b643-4a9369c2aaac@r2g2000vbp.googlegroups.com> Message-ID: On Wed, Dec 17, 2008 at 1:52 PM, Rominsky wrote: > On Dec 17, 10:59 am, Christian Heimes wrote: > > Rominsky schrieb: > > > > > I am trying to use dir to generate a list of methods, variables, etc. > > > I would like to be able to go through the list and seperate the > > > objects by type using the type() command, but the dir command returns > > > a list of strings. When I ask for the type of an element, the answer > > > is always string. How do I point at the variables themselves. A > > > quick example is: > > > > > a = 5 > > > b = 2.0 > > > c = 'c' > > > > > lst = dir() > > > > > for el in lst: > > > print type(el) > > > > for name, obj in vars().iteritems(): > > print name, obj > > > > Christian > > I do have some understanding of the pythonic methodology of > programming, though by far I still don't consider myself an expert. > The problem at hand is that I am coming from a matlab world and trying > to drag my coworkers with me. I have gotten a lot of them excited > about using python for this work, but the biggest gripe everytime is > they want their matlab ide. I am trying to experiment with making > similar pieces of the ide, in particular I am working on the workspace > window which lists all the current variables in the namespace, along > with their type, size, value, etc.... I am trying to create a python > equivalent. I can get dir to list all the variables names in a list > of strings, but I am trying to get more info them. hence the desire Are you familiar with the ipython console? http://ipython.scipy.org/moin/ It is quite powerful; in particular, the %who and %whos 'magic functions' will do much of what you'd like: [501]$ ipython Python 2.5.2 (r252:60911, Jul 31 2008, 17:31:22) Type "copyright", "credits" or "license" for more information. IPython 0.8.1 -- An enhanced Interactive Python. ? -> Introduction to IPython's features. %magic -> Information about IPython's 'magic' % functions. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: a = 'foo' In [2]: b = 'bar' In [3]: c = 5.234 In [4]: import os In [5]: d = os In [6]: whos Variable Type Data/Info ------------------------------ a str foo b str bar c float 5.234 d module os module In [7]: import numpy as np In [8]: aa = np.zeros(100) In [9]: whos Variable Type Data/Info ------------------------------- a str foo aa ndarray 100: 100 elems, type `float64`, 800 bytes b str bar c float 5.234 d module np module ages/numpy/__init__.pyc'> os module And I trust you've heard of numpy, scipy and matplotlib? http://www.scipy.org/ http://matplotlib.sourceforge.net/ http://numpy.scipy.org/ Cheers, Kurt -------------- next part -------------- An HTML attachment was scrubbed... URL: From Scott.Daniels at Acm.Org Mon Dec 15 14:01:02 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 15 Dec 2008 11:01:02 -0800 Subject: Rename of .mdb file -- lock In-Reply-To: <4049f296-2a04-4eee-9f09-aa37a973a8cf@r40g2000yqj.googlegroups.com> References: <4049f296-2a04-4eee-9f09-aa37a973a8cf@r40g2000yqj.googlegroups.com> Message-ID: noydb wrote: > I have the code below, which unzips a zipfile containing only one > file. Once it is unzipped, I want to rename the file based on a user > provided name. But I get this (WindowsError: [Error 32] The process > cannot access the file because it is being used by another process) > error, which does not make sense to me as no other apps are open. > Any suggestions? Others have told you the reason you are currently having problems. You should also be aware that Windows can at "random" times be opening the new file in order to either index it or virus scan it, and it may fail to rename during that period. So, a failure should retry in a second a couple of times before giving up. This is my understanding, but someone deeply familiar with Windows internals might reveal that I am operating on older information. --Scott David Daniels Scott.Daniels at Acm.Org From claird at lairds.us Mon Dec 29 09:26:36 2008 From: claird at lairds.us (Cameron Laird) Date: Mon, 29 Dec 2008 14:26:36 +0000 Subject: Windows SSH (remote execution of commands) - Python Automation References: <7FAD6FCE52421841A11B441DEF3A88CA01F09006@ZMY16EXM70.ds.mot.com> Message-ID: In article , Tino Wildenhain wrote: . . . >> I am looking for some information on how to automate remote login to a >> UNIX machine using ssh from a windows XP box. >> >> Possible way: >> >> 1. Use putty (or any other ssh client from windows XP). -- Can be >> automated with command line parameters. The problem is that I am able to >> login - Putty window opens up as well. But obviously I am unable to run >> any commands in that. I need to find something like a handle to that >> Putty window so that I can execute commands there. > >Obviously putty is one (of several) terminal emulators (or in short gui >clients) for ssh protocol. This means they are made for interactive work >with mouse and keyboard rather then for command automation. > >Its easy if you just use one of the many command line ssh clients. You >can use os.popen() and friends or the command module to work with them. > >There is also another solution: > >http://www.lag.net/paramiko/ > >which implements the ssh protocol in python so you can do more and >have finer control over the processes and channels (for example >file transfer and command control w/o resort to multiple connections) > >This is a little bit harder of course. > >Also, sometimes its more easy and relieable to just use cron on unix >side. This works much much better then Task scheduler on windows btw. . . . Good advice, all around. I'll reinforce a few of your points: A. I entirely agree that Mr. Raghu would likely do well to learn about cron(8); automation of the sort that seems to be involved here is generally more convenient with standard Linux tools than from the Windows side. B. One of the Windows command-line automaters to which you alluded is a sibling of putty: plink . It shares configuration and infrastructure elements with putty, and might require the least adjustment. C. 'You think paramiko is harder? I find it a nice solution in many situations. From noZ.spamZ at ZZ.ZsvpZ.com Mon Dec 15 18:33:55 2008 From: noZ.spamZ at ZZ.ZsvpZ.com (Michel Claveau - NoSpam SVP ; merci) Date: Tue, 16 Dec 2008 00:33:55 +0100 Subject: Problem Python 2.6.1 vs 2.6 & pyWin32 In-Reply-To: <4946D09F.6050300@v.loewis.de> References: <4946754f$0$19000$426a74cc@news.free.fr> <4946D09F.6050300@v.loewis.de> Message-ID: <4946ea05$0$31992$426a74cc@news.free.fr> Hi! Thank you very much for your answer. I appreciate many to receive an answer of somebody as you. But I, always, install Python 2.6.1 "for all users" (and, on Vista, UAC is always deactivated). After some tests, the problem seems a bit more complex: call the Python-COM-servers run OK, from Python-Scripts. But it is not possible from others languages (but, I only try JScript, VBScript, JS.Net, ObjectPAL, Autoit). For the moment, I back my install procedures to Python 2.6 ; and, I hope a "global" solution for 2.6.1 @-salutations -- Michel Claveau From bignose+hates-spam at benfinney.id.au Mon Dec 15 06:29:29 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 15 Dec 2008 22:29:29 +1100 Subject: alt.possessive.its.has.no.apostrophe References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> Message-ID: <87myexfzhi.fsf@benfinney.id.au> James Stroud writes: > Ben Finney wrote: > > Or, more generally: Pronouns, which are different in just about > > every other way from other nouns, are different in this way also. > > Is that about right? > > Can we start talking about python again? Not with this thread subject :-) -- \ ?We are not gonna be great; we are not gonna be amazing; we are | `\ gonna be *amazingly* amazing!? ?Zaphod Beeblebrox, _The | _o__) Hitch-Hiker's Guide To The Galaxy_, Douglas Adams | Ben Finney From malkarouri at gmail.com Thu Dec 4 15:05:30 2008 From: malkarouri at gmail.com (malkarouri) Date: Thu, 4 Dec 2008 12:05:30 -0800 (PST) Subject: Why shouldn't you put config options in py files References: Message-ID: On 4 Dec, 19:35, HT wrote: > A colleague of mine is arguing that since it is easy to write config like: > > FOO = {'bar': ('a': 'b'), 'abc': ('z': 'x')} > > in config.py and just import it to get FOO, but difficult to achieve the > same using an ini file and ConfigParser, and since Python files are just > text, we should just write the config options in the Python file and > import it. > > I can think of lots of arguments why this is a bad idea, but I don't > seem to be able to think of a really convincing one. > > Anyone? Some people actually do that. IIRC, ipython is now configured using a python module. The idea, however, is dangerous from a security viewpoint. Because anybody can edit his configuration .py file, you are in effect injecting arbitrary code into your program. Think that your program starts with raw_input() and then goes on the execute whatever you get. Same problems with SQL injection for example. So people prefer to have a much more controlled environment for configuration. In particular, the idea of using json as Chris said should become a best practice now we have the json module. Regards, Muhammad Alkarouri From bearophileHUGS at lycos.com Fri Dec 5 09:52:11 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 5 Dec 2008 06:52:11 -0800 (PST) Subject: Small problem with Psyco Message-ID: <1d71a6ed-4d96-4e86-983c-a54e23fcf158@t3g2000yqa.googlegroups.com> I post it here because I am using a Psyco version that was compiled by people here. I am using Python 2.6.1, on Win, with Psyco (1, 6, 0, 'final', 0). This minimized code: from psyco.classes import psyobj class Bar(psyobj): def __init__(self, baz): pass b = Bar(0) Produces: C:\...\test.py:5: DeprecationWarning: object.__new__() takes no parameters b = Bar(0) Bye, bearophile From prologic at shortcircuit.net.au Thu Dec 18 20:30:33 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Dec 2008 11:30:33 +1000 Subject: Factoring Polynomials In-Reply-To: References: <269523e2-eba9-4b6b-b0fb-c5a7deb3ed76@o4g2000pra.googlegroups.com> Message-ID: UPDATE: jmills at atomant:~/tmp$ cat polycalc.py #!/usr/bin/env python from math import sqrt def f(a, b, c): if (b**2 - (4 * a * c)) < 0: return None, None # Can't solve x1 = -b - (sqrt(b**2 - (4 * a * c)) / (2 * a)) x2 = -b + (sqrt(b**2 - (4 * a * c)) / (2 * a)) return x1, x2 print "Polynomial Solver..." print while True: a = float(raw_input("a: ")) b = float(raw_input("b: ")) c = float(raw_input("c: ")) x = f(a, b, c) if None in x: print "Can't solve!" else: print "x = (%0.2f, %0.2f)" % x jmills at atomant:~/tmp$ ./polycalc.py Polynomial Solver... a: 1 b: 8 c: 5 x = (-11.32, -4.68) From prologic at shortcircuit.net.au Wed Dec 3 09:27:19 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 4 Dec 2008 00:27:19 +1000 Subject: generating a liste of characters In-Reply-To: References: Message-ID: On Thu, Dec 4, 2008 at 12:18 AM, Yves Dorfsman wrote: > Is there any built in way to generate a list of characters, something > along the line of range('a'-'z') ? > > Right now I am using: > > chars = [ chr(l) for l in range(0x30, 0x3a) ] # 0 - 9 > chars += [ chr(l) for l in range(0x41, 0x5b) ] # A - Z > chars += [ chr(l) for l in range(0x61, 0x7b) ] # a - z > > Is there a better, more straight forward way of doing that ? >>> from string import ascii_letters, digits >>> chars = ascii_letters + digits >>> chars 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' >>> cheers James -- -- -- "Problems are solved by method" From xahlee at gmail.com Tue Dec 9 23:36:28 2008 From: xahlee at gmail.com (Xah Lee) Date: Tue, 9 Dec 2008 20:36:28 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <9ecfa224-ce8f-44e9-abca-008314f44e87@40g2000prx.googlegroups.com> Message-ID: <501d76b2-45d1-4475-8d88-e0e51e19fc10@q26g2000prq.googlegroups.com> Jon Harrop moron wrote: > Only for trivial input and not for the challenge you were given. what challenge? > That code is evaluated once to build the scene. There is no point in > optimizing it. The point is optimizing your incompetence. > That performance issue only affects trivial problems and, in particular, > does not affect the problem you were trying to solve. solve your mom? Xah ? http://xahlee.org/ ? From cjw at ncf.ca Sat Dec 6 09:20:42 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 06 Dec 2008 09:20:42 -0500 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: <493A8A3A.6060203@ncf.ca> Daniel Fetchinson wrote: > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html > > The proposal is to allow this: > > class C: > def self.method( arg ): > self.value = arg > return self.value > > instead of this: > > class C: > def method( self, arg ): > self.value = arg > return self.value > > I.e. explicit self stays only the syntax is slightly different and may > seem attractive to some. As pointed out by Guido classmethods would > work similarly: > > class C: > @classmethod > def cls.method( arg ): > cls.val = arg > return cls.val > > The fact that Guido says, > > "Now, I'm not saying that I like this better than the status quo. But > I like it a lot better than [...] but it has the great advantage that > it is backward compatible, and can be evolved into a PEP with a > reference implementation without too much effort." > > shows that the proposal is viable. > > I'd like this new way of defining methods, what do you guys think? > Anyone ready for writing a PEP? > > Cheers, > Daniel > The quoted blogspot is not available. I like the idea but I don't see how explicit and implicit can co-exist. Version 3.0 is the time to introduce the enhancement. Colin W. From akineko at gmail.com Mon Dec 22 12:57:08 2008 From: akineko at gmail.com (akineko) Date: Mon, 22 Dec 2008 09:57:08 -0800 (PST) Subject: 64-bit / 128-bit data element type for array? Message-ID: Hello everyone, I need to handle binary files that contain 64-bit (or 128-bit in the furture) unsigned int data. Python's array seems not supporting unsigned int type beyond 32-bit ('L'). I would like to use Python array as I need to make my program work on both big-endian machines as well as on little-endian machines. What is the best way to deal with 64-bit / 128-bit data elements in Python (must support byteswap())? (must be machine-independent) Any idea, any hints, comments would be greatly appreciated. Thank you! Aki Niimura From ivan.illarionov at gmail.com Tue Dec 16 15:28:51 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 16 Dec 2008 12:28:51 -0800 (PST) Subject: Memory leak when using a C++ module for Python References: <13db1224-5d6d-4240-8184-ce852e10b422@d36g2000prf.googlegroups.com> Message-ID: On Dec 11, 8:35?pm, Jaume Bonet wrote: > ? ? ? ? //Here we take the info coming from python and transform it > into a vector (will allow us to work with numbers instead of > ? ? ? ? // strings) and shareInt which is an array of sets (form > std::set) > ? ? ? ? vector translator = string2int > (shareIntPy,root,shareInt,pSize,max); I guess if there are any problems with Python/C API in your example they are in string2int function. How do you retrieve Python data from 'shareIntPy' Python object? If you have memory leaks you probably forget to Py_DECREF something retrieved with Python/C API functions that return new references (like PyObject_GetAttrString). Ivan From roy at panix.com Mon Dec 1 08:46:06 2008 From: roy at panix.com (Roy Smith) Date: Mon, 01 Dec 2008 08:46:06 -0500 Subject: Emacs vs. Eclipse vs. Vim References: Message-ID: In article , Nick Craig-Wood wrote: > * Syntax colouring (not essential) I never used to use syntax coloring, until somebody turned me on to it a couple of years ago. I was griping on a company mailing list that some previous code monkey had commented out a big swath (more than a screenfull) of C++ code by sticking a "/*" at the beginning and a "*/" at the end. I had just wasted a bunch of time trying to debug a problem, not noticing that the code I was looking at was commented out. Somebody pointed out that if I turned on syntax coloring, it would be obvious. I've been hooked ever since. From zhushenli at gmail.com Wed Dec 3 22:23:11 2008 From: zhushenli at gmail.com (Davy) Date: Wed, 3 Dec 2008 19:23:11 -0800 (PST) Subject: Thread Tkinter problem References: <64c7402c-8b7b-4281-9d7d-1abdd6177d96@r15g2000prh.googlegroups.com> <35672781-eca1-4139-8b5d-88c457960d62@g1g2000pra.googlegroups.com> Message-ID: <98353009-15ea-4029-99d1-42f9d32e7c27@r15g2000prh.googlegroups.com> On Dec 4, 9:08?am, Davy wrote: > On Dec 4, 11:13?am, "Hendrik van Rooyen" wrote:> ?"Davy" wrote: > > > ? ? while(data_queue.full() == False): > > > This will fill the queue and stop. > > Use while true and if queue not full... > > Hi Hendrik, > > It works, thank you:) Add changed code: //------code changed --- def gen_board_thread(): print 'enter here' gen_flip = 1 while(True): time.sleep(0.3) if (data_queue.full() == False): if (gen_flip == 1): gen_flip = 0 data = board_1 else: gen_flip = 1 data = board_2 data_queue.put(data) print 'put', data_queue.qsize() //-------------------- > > Davy > > > > > > > - Hendrik- Hide quoted text - > > - Show quoted text - From steve at holdenweb.com Tue Dec 30 16:34:25 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Dec 2008 16:34:25 -0500 Subject: Triple quoted string in exec function ? In-Reply-To: <495A81A7.8030507@gmail.com> References: <495A253B.6010003@gmail.com> <495A81A7.8030507@gmail.com> Message-ID: Stef Mientki wrote: > ibpet11 at gmail.com wrote: >> On Dec 30, 2:48 pm, Steve Holden wrote: >> >>> Stef Mientki wrote: >>> >>>> hello, >>>> I'm running scripts, with the execute function (Python 2.5), >>>> and it seems that triple quoted strings are not allowed. >>>> Is there a workaround, >>>> or is this a fundamental problem of the exec-function ? >>>> >>> If you think about it, it should be obvious that you can't surround a >>> string to be compiled with any of the quotes that appear inside the >>> string to be compiled. That's about the only limitation I am aware of. >>> >>> And, by the way, exec is a *statement*, not a function! >>> > exec ( Init_Code, PG.P_Globals ) > > I've really doubt that this is a statement, > unless I don't understand what a statement is. We'll have to conclude you don't, then, won't we ;-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From castironpi at gmail.com Sat Dec 13 19:37:54 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 13 Dec 2008 16:37:54 -0800 (PST) Subject: subprocess to C program Message-ID: <0ebd59c5-95a1-42d4-b597-d1c248490b8e@y1g2000pra.googlegroups.com> Hi, I am writing a C process and I want to read data from a file that I write to in Python. I'm creating a pipe in Python, passing it to the C process, and calling '_read'. It gives me error 9, bad file number. Python code: import subprocess as s, os r, w= os.pipe( ) os.write( w, 'abcdefghij\n' ) a= s.Popen( [ r'C:\Documents and Settings\usr\Desktop\working \try_start', '%i'%r, '%i'%w ] ) C code: char buf[ 16 ]; memset( buf, 0, 16 ); int readfd= atoi( argv[ 1 ] ); int ct= _read( readfd, buf, 15 ); printf( "\n\n'_read %i %i %i': %s\n", ct, readfd, errno, buf ); Output: '_read -1 3 9' meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9. I want 'ct' to be 11 at this point. Thanks in advance. From exarkun at divmod.com Thu Dec 4 09:33:37 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 4 Dec 2008 09:33:37 -0500 Subject: schizophrenic view of what is white space In-Reply-To: <4937E8E5.2090306@chamonix.reportlab.co.uk> Message-ID: <20081204143337.20272.1236189783.divmod.quotient.15592@ohm> On Thu, 04 Dec 2008 14:27:49 +0000, Robin Becker wrote: >Is python of two minds about what is white space. I notice that split, strip >seem to regard u'\xa0' (NO-BREAK SPACE) as white, but that code is not >matched by the \s pattern. If this difference is intended can we rely on it >continuing? > > > >>> u'a b'.split() >[u'a', u'b'] > >>> u'a\xa0b'.split() >[u'a', u'b'] > >>> re.compile(r'\s').search(u'a b') ><_sre.SRE_Match object at 0x00DBB2C0> > >>> re.compile(r'\s').search(u'a\xa0b') > >>> > You have to give the re module an additional hint that you care about unicode: exarkun at charm:~$ python Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> print re.compile(r'\s').search(u'a\xa0b') None >>> print re.compile(r'\s', re.U).search(u'a\xa0b') <_sre.SRE_Match object at 0xb7dbb3a0> >>> Jean-Paul From rdmurray at bitdance.com Tue Dec 9 13:35:14 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Tue, 9 Dec 2008 13:35:14 -0500 (EST) Subject: Best way to report progress at fixed intervals In-Reply-To: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> Message-ID: On Tue, 9 Dec 2008 at 08:40, Slaunger wrote: > I am a novice Python 2.5 programmer, who write some cmd line scripts > for processing large amounts of data. > > I would like to have possibility to regularly print out the progress > made during the processing, say every 1 seconds, and i am wondering > what a proper generic way to do this is. > > I have created this test example to show the general problem. Running > the script gives me the output: > > Work through all 20 steps reporting progress every 1.0 secs... > Work step 0 > Work step 1 > Work step 2 > Work step 3 > Work step 4 > Processed 4 of 20 > Work step 5 [...] > Work step 19 > Finished working through 20 steps [...] > Quite frankly, I do not like what I have made! It is a mess, > responsibilities are mixed, and it seems overly complicated. But I > can't figure out how to do this right. > > I would therefore like some feedback on this proposed generic "report > progress at regular intervals" approach presented here. What could I > do better? I felt like a little lunchtime challenge, so I wrote something that I think matches your spec, based on your sample code. This is not necessarily the best implementation, but I think it is simpler and clearer than yours. The biggest change is that the work is being done in the subthread, while the main thread does the monitoring. It would be fairly simple to enhance this so that you could pass arbitrary arguments in to the worker function, in addition to or instead of the loop counter. ----------------------------------------------------------------------- """ Test module for testing generic ways of displaying progress information at regular intervals. """ import random import threading import time def work(i): """ Dummy process function, which takes a random time in the interval 0.0-0.5 secs to execute """ print "Work step %d" % i time.sleep(0.5 * random.random()) class Monitor(object): """ This class creates an object that will execute a worker function in a loop and at regular intervals emit a progress report on how many times the function has been called. """ def dowork(self): """ Call the worker function in a loop, keeping track of how many times it was called in self.no """ for self.no in xrange(self.max_iter): self.func(self.no) def __call__(self, func, verbose=True, max_iter=20, progress_interval=1.0): """ Repeatedly call 'func', passing it the loop count, for max_iter iterations, and every progress_interval seconds report how many times the function has been called. """ # Not all of these need to be instance variables, but they might # as well be in case we want to reference them in an enhanced # dowork function. self.func = func self.verbose = verbose self.max_iter=max_iter self.progress_interval=progress_interval if self.verbose: print ("Work through all %d steps reporting progress every " "%3.1f secs...") % (self.max_iter, self.progress_interval) # Create a thread to run the loop, and start it going. worker = threading.Thread(target=self.dowork) worker.start() # Monitoring loop. loops = 0 # We're going to loop ten times per second using an integer count, # so multiply the seconds parameter by 10 to give it the same # magnitude. intint = int(self.progress_interval*10) # isAlive will be false after dowork returns while worker.isAlive(): loops += 1 # Wait 0.1 seconds between checks so that we aren't chewing # CPU in a spin loop. time.sleep(0.1) # when the modulus (second element of divmod tuple) is zero, # then we have hit a new progress_interval, so emit the report. if not divmod(loops, intint)[1]: print "Processed %d of %d" % (self.no, self.max_iter) if verbose: print "Finished working through %d steps" % max_iter if __name__ == "__main__": #Create the monitor. monitor = Monitor() #Run the work function under monitoring. monitor(work) From malaclypse2 at gmail.com Mon Dec 8 12:54:46 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 8 Dec 2008 12:54:46 -0500 Subject: Equivalent of 'wget' for python? In-Reply-To: References: Message-ID: <16651e80812080954p23eb2aeaj8793be4a8d509c77@mail.gmail.com> On Mon, Dec 8, 2008 at 11:53 AM, r0g wrote: > urllib.urlretrieve(url_of_zip_file, destination_on_local_filesystem). In python 3.0, that appears to be: import urllib.request urllib.request.urlretrieve(url, local_file_name) -- Jerry From gagsl-py2 at yahoo.com.ar Wed Dec 10 16:44:51 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 10 Dec 2008 19:44:51 -0200 Subject: getting back into programming References: <8796344d-1c02-441e-8272-8a7638faae39@j39g2000yqn.googlegroups.com> Message-ID: En Wed, 10 Dec 2008 19:02:16 -0200, escribi?: > I used to program in C and Perl (up until 2001) (a little C++ and Java > too). Since then I've been a Business Analyst and only coded in VBA/ > Excel and written some SQL queries. (we use Sybase) > > I feel the need for other tools. > Primarily I want to write a bunch of small programs to query a > database and perform some calculations. While I can do this inside a > Sybase stored procedure, its a bit messy trying to "reimplement" a set > of calculations from Excel into Sybase. > > I would like to either: > - relearn Perl > or > - learn Python (I have heard its a nice language) I prefer Python over Perl because of its legibility (it's way more clear than Perl!), expressiveness (there is no big difference between "what I want" and "what I write"). (Anyway, I think most people here would say they like Python...) > 1. How good and easy to use is the Python database interface (to > Sybase)? Most database modules implement DBAPI 2.0, the Python standard API for database connectivity, see http://www.python.org/dev/peps/pep-0249/ Migrating from one database to another, if you stick to the API, may have little or no impact on your application. The first hit on Google for "python sybase" points to the python-sybase project on Sourceforge, which claims to be DBAPI 2 compliant, but I've never used it. > 2. Can you suggest some good books, and/or links for learning Python, > as well as teh database interface? If you had some programming experience then Dive into Python http://www.diveintopython.org/ would be a good choice > 3. How difficult is it to install Python vs Perl on PC/Windows > machines? Both, almost zero effort, just run the installer. -- Gabriel Genellina From tjreedy at udel.edu Thu Dec 4 14:25:48 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Dec 2008 14:25:48 -0500 Subject: Python 3 read() function In-Reply-To: References: Message-ID: ?????? ??????????? wrote: >> I don't think it matters. Here's a quick comparison between 2.5 and >> 3.0 on a relatively small 17 meg file: >> >> C:\>c:\Python30\python -m timeit -n 1 >> "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" >> 1 loops, best of 3: 36.8 sec per loop >> >> C:\>c:\Python25\python -m timeit -n 1 >> "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" >> 1 loops, best of 3: 33 msec per loop >> >> That's 3 orders of magnitude slower on python3.0! > > Isn't this because you have the file cached in memory on the second run? In my test, I read Python25.chm with 2.5 and Python30.chm with 3.0. Rereading Python30.chm without closing *is* much faster. >>> f=open('Doc/Python30.chm','rb') >>> d=f.read() >>> d=f.read() >>> d=f.read() Closing, reopening, and rereading is slower. From pofuk at email.t-com.hr Thu Dec 11 08:06:19 2008 From: pofuk at email.t-com.hr (SMALLp) Date: Thu, 11 Dec 2008 14:06:19 +0100 Subject: Python, threading Message-ID: Hy. I have a problem! I'm making multi thread application (client, server) using wxPython for GUI, and threading.Thread for threding. Clients connect and when they are connected (evry thread handles one connection) threads change main window. I neded tip how to make communication between threeds. From alexoplocatie at gmail.com Tue Dec 16 11:26:57 2008 From: alexoplocatie at gmail.com (aka) Date: Tue, 16 Dec 2008 08:26:57 -0800 (PST) Subject: help I'm getting delimited Message-ID: <817cf531-225b-4c4e-b79b-10d7657b0749@35g2000pry.googlegroups.com> Hi, I'm going nuts over the csv.reader and UnicodeReader class. Somehow I can't get this method working which is supposed to read a csv file which name is inputted but here now hardcoded. What I need for now is that the string version of the list is put out for control. Later on I will only need to read the first column (id) of the csv file to be able to fill in a session var with a list of all ids. inp = c:/temp/test.csv roles = [] try: fp = open(inp, 'rb') reader = csv.reader(fp) for r in reader: rollen.append(r) except: msg = "Er is iets mis met de UnicodeReader" return dict(file=in,roles=str(roles)) Any help greatly appreciated! Cheers From clp at rebertia.com Wed Dec 17 15:33:23 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 17 Dec 2008 12:33:23 -0800 Subject: Selecting a different superclass In-Reply-To: References: Message-ID: <47c890dc0812171233v3727106fifd91d9bd217e0e9@mail.gmail.com> On Wed, Dec 17, 2008 at 6:41 AM, psaffrey at googlemail.com wrote: > This might be a pure OO question, but I'm doing it in Python so I'll > ask here. > > > The problem is that IDPointSet and MicroArrayPointSet will need to > inherit from PointSet or TraceablePointSet based on whether I'm > handling traceable points or not. Can I select a superclass > conditionally like this in Python? Am I trying to do something really > evil here? You're doing something really dynamic; don't think I'd call it inherently evil though. All you have to do is use a variable in the inheritance syntax, it's really quite simple: superclass = TraceablePointSet if tracing else PointSet class IDPointSet(superclass): #body code here #use same trick for MicroArrayPointSet Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From fetchinson at googlemail.com Sat Dec 27 22:47:08 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 27 Dec 2008 19:47:08 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: >> This is the function I have, the corresponding python function will >> take two equal length lists of integers and the C function will >> compute their sum and return the result as a python tuple. >> >> >> static PyObject *func( PyObject * self, PyObject * args ) >> { >> int j, N; >> int * src1, * src2; >> PyObject *list1, *list2; >> >> list1 = PyTuple_GetItem( args, 0 ); >> N = PyList_Size( list1 ); >> src1 = ( int * ) malloc( N * sizeof( int ) ); >> for( j = 0; j < N; j++ ) >> { >> src1[j] = (int)PyInt_AsLong( PyList_GetItem( list1, j ) ); >> } >> >> list2 = PyTuple_GetItem( args, 1 ); >> N = PyList_Size( list2 ); >> src2 = ( int * ) malloc( N * sizeof( int ) ); >> for( j = 0; j < N; j++ ) >> { >> src2[j] = (int)PyInt_AsLong( PyList_GetItem( list2, j ) ); >> } >> >> PyObject * tuple; >> tuple = PyTuple_New( N ); >> for( j = 0; j < N; j++ ) >> { >> PyTuple_SetItem( tuple, j, PyInt_FromLong( (long)( src1[j] + >> src2[j] ) ) ); >> } >> >> free( src1 ); >> free( src2 ); >> >> return tuple; >> } > > As others already said, using a Numpy array or an array.array object would > be more efficient (and even easier - the C code gets a pointer to an array > of integers, as usual). I looked for this in the C API docs but couldn't find anything on how to make an array.array python object appear as a pointer to integers (or floats, etc) in C code. On http://docs.python.org/c-api/concrete.html#sequence-objects There is only list and tuple or maybe you mean byte array? That has only been introduced in python 2.6 and I'm working on 2.5. Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From rt8396 at gmail.com Thu Dec 18 11:32:53 2008 From: rt8396 at gmail.com (r) Date: Thu, 18 Dec 2008 08:32:53 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> Message-ID: <71ede5f0-fd88-4155-9f0d-42d0ad5f57dc@v42g2000yqj.googlegroups.com> w.unbind ( sequence, funcid=None ) This method deletes bindings on w for the event described by sequence. If the second argument is a callback bound to that sequence, that callback is removed and the rest, if any, are left in place. If the second argument is omitted, all bindings are deleted. see http://infohost.nmt.edu/tcc/help/pubs/tkinter/universal.html From willian.radicaled at gmail.com Wed Dec 17 09:51:50 2008 From: willian.radicaled at gmail.com (RadicalEd) Date: Wed, 17 Dec 2008 06:51:50 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: <84916f4e-4683-4063-8ebc-41b5ad5e1d2e@v31g2000vbb.googlegroups.com> On Dec 10, 1:42?pm, cm_gui wrote: > http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-... > > I fully agree with Krzysztof Kowalczyk . > Can't they build a faster VM for Python since they love the language > so much? > > Python is SLOW. ? ?And I am not comparing it with compiled languages > like C. > Python is even slower than PHP! > > Just go to any Python website and you will know. > An example is:http://www2.ljworld.com/ > And this site is created by the creators of Django! > > And it is not just this Python site that is slow. There are many many > Python sites which are very slow. And please don?t say that it could > be the web hosting or the server which is slow ? because when so many > Python sites are slower than PHP sites, it couldn?t be the web > hosting. ? Also, Zope/Plone is even slower. > > Python is slow. Very slow. I did a DataBase consult with MySQLdb and PHP with 300000 rows and who you think was the better and faster, YES, Python for almost 10 seconds, and I have to configure the php.ini for PHP could show me the DATA. He is just a futile troll frustrated with Python. From chris.gonnerman at newcenturycomputers.net Thu Dec 25 10:16:40 2008 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 25 Dec 2008 09:16:40 -0600 Subject: os.system('cls') In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF602494700@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF602494700@enbmail01.lsi.com> Message-ID: <4953A3D8.6040308@newcenturycomputers.net> Depends on what operating system you are using. The list of possible commands would be unbounded, if not truly infinite. > From: Dennis van Oosterhout [mailto:de.slotenzwemmer at gmail.com] > > Hi there! I was searching for a way to clear the 'DOS screen'/command > screen etc. and found that os.system('cls') works for this. I was just > wondering where I can find al the commands which can be used for > os.system(). I searched with google but I didn't find an answer. In the > official python tutorial it says os.system('command') executes the > command, but it doesn't say which commands exist (or I'm just blind). > > Does anyone have an answer for this question? > From steve at REMOVE-THIS-cybersource.com.au Thu Dec 4 09:08:30 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Dec 2008 14:08:30 GMT Subject: "as" keyword woes References: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> Message-ID: <0147dc24$0$20670$c3e8da3@news.astraweb.com> On Wed, 03 Dec 2008 17:15:21 -0800, Matimus wrote: >> Couldn't we have continued along just fine using a smarter parser >> without elevating "as" to reserved status (and thus potentially >> breaking a 10+ years of existing code)? > > Nothing broke your code. It works just fine under the version it was > developed for. Who forced you to upgrade to python2.6? Be reasonable. Python 2.5 is not very far away from being put into "security updates only" mode, and in a year or so it won't even get security updates. I dare say there are already platforms that use Python 2.6 as standard. Tying your software to an obsolete version of a language is a good way to force your software into obsolescence. Not that 2.5 is obsolete *now*. But it will be soon (for some definition of soon): in no more than a year or three, software that only runs on Python 2.5 would be like software that only runs on 2.3 now. -- Steven From rt8396 at gmail.com Thu Dec 18 15:26:47 2008 From: rt8396 at gmail.com (r) Date: Thu, 18 Dec 2008 12:26:47 -0800 (PST) Subject: IDLE cursor color References: <65c5974c-e5c5-46c1-9673-371a7c9ea047@a12g2000pro.googlegroups.com> <313c1a14-ac85-4326-a2dc-29955549a708@f11g2000vbf.googlegroups.com> Message-ID: <9f0efea8-a2a6-463a-ad02-ba5844b8328e@a12g2000yqm.googlegroups.com> also try the python forum, great place for beginners... http://www.python-forum.org/pythonforum/index.php From lihang9999 at gmail.com Wed Dec 17 08:47:41 2008 From: lihang9999 at gmail.com (Li Han) Date: Wed, 17 Dec 2008 05:47:41 -0800 (PST) Subject: The rule of literal string References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> Message-ID: <59fa1fe8-b43a-4679-9795-8ac333377b62@z27g2000prd.googlegroups.com> Thank you, Chris! You have made me learn more about Python. From castironpi at gmail.com Sun Dec 21 06:02:21 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 21 Dec 2008 03:02:21 -0800 (PST) Subject: How to transfer data structure or class from Python to C/C++? Message-ID: <7178badb-35a8-4525-8856-0b51b49e93dc@r36g2000prf.googlegroups.com> On Oct 16, 9:10 am, Hongtian wrote: snip > Not exactly. > In my C/C++ application, I have following function or flow: > void func1(....) > { > call PyFunc(struct Tdemo, struct &Tdemo1); > } > I mean I want to invoke Python function 'PyFunc' and transfer a data > structure 'Tdemo' to this function. After some process in Python, I > want it return 'Tdemo1' back to the C/C++ application. snip This is a correction of: Oct 17, 5:03 pm, "Aaron \"Castironpi\" Brady" http://groups.google.com/group/comp.lang.python/msg/f11ac4a34faaf766 Thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/68d59cb670a345ef Revised solution uses 'from_address' instead of '_ctypes._cast_addr'. import ng27ext import ctypes as c class TypeA( c.Structure ): _fields_= [ ( 'a', c.c_int ), ( 'b', c.c_float ) ] def exposed( pobj1, pobj2 ): obj1= TypeA.from_address( pobj1 ) obj2= TypeA.from_address( pobj2 ) print obj1.a, obj1.b obj2.a= c.c_int( 60 ) obj2.b= c.c_float( 65.5 ) print obj2.a, obj2.b print ng27ext.methA( exposed ) From skip at pobox.com Tue Dec 23 11:18:07 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 23 Dec 2008 10:18:07 -0600 Subject: pseudo terminal usage from Python? In-Reply-To: <5t-dnRgMi9Z4lszUnZ2dnUVZ_vOdnZ2d@posted.visi> References: <5t-dnRgMi9Z4lszUnZ2dnUVZ_vOdnZ2d@posted.visi> Message-ID: <18769.3903.26361.253778@montanaro-dyndns-org.local> Grant> Are you sure it's not Python buffering its input? Have you tried Grant> "python -u mympstat.py"? Hmmm... No, I hadn't considered that. I'll check it out. Thanks... Grant> I had a Linux pty example running once upon a time. If "python Grant> -u" doesn't work post again, and I'll try to find it. Would be helpful even if I don't need it for this task, as I've not been able to find any simple examples on the net. (Maybe there's a recipe at ActiveState, but Google didn't pick up anything with the search terms I was using.) Skip From martin at marcher.name Wed Dec 24 05:18:34 2008 From: martin at marcher.name (Martin) Date: Wed, 24 Dec 2008 11:18:34 +0100 Subject: Most efficient way to build very large dictionaries In-Reply-To: <1230107768.14060.1291622121@webmail.messagingengine.com> References: <1230104615.5867.1291617213@webmail.messagingengine.com> <1230107768.14060.1291622121@webmail.messagingengine.com> Message-ID: <5fa6c12e0812240218yc9a7185maaf5211dbddd8134@mail.gmail.com> Hi, 2008/12/24 : > Hi Roger, > >> you may want to consider using SQLite > > Thank you for your suggestion about looking at SQLite. I haven't > compared the performance of SQLite to Python dictionaries, but I'm > skeptical that SQLite would be faster than in-memory Python dictionaries > for the type of analysis I'm doing. I'd think he's talking about in memory SQLite Databases, this way you should be quite fast _and_ could dump all that to a persistent storage... regards martin -- http://soup.alt.delete.co.at http://www.xing.com/profile/Martin_Marcher http://www.linkedin.com/in/martinmarcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From zxo102 at gmail.com Thu Dec 25 04:27:03 2008 From: zxo102 at gmail.com (zxo102) Date: Thu, 25 Dec 2008 01:27:03 -0800 (PST) Subject: How to display Chinese in a list retrieved from database via python References: Message-ID: <22be506d-91c2-4727-ace7-2e3382b6d214@g3g2000pre.googlegroups.com> On 12?25?, ??3?35?, "Chris Rebert" wrote: > On Wed, Dec 24, 2008 at 11:29 PM, zxo102 wrote: > > Hi, > > I retrieve some info in Chinese from postgresql and assign it to a > > variable 'info' defined in javascript of a html page: > > var info = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce > > \xc4'] > > But I want it to be > > var info = ['??','??','??'] > > since in html pages (via javascript), the items in chinese out of the > > former :['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4'] can > > not be displayed correctly when it is inserted into a html page. If > > the list is var info = ['??','??','??'] , then everything works > > fine. > > > Anybody knows how to solve this problem? > > Upgrading to Python 2.6 would probably be beneficial due to its better > handling of Unicode. > Also, posting some of the actual code you're using (to generate > JavaScript, I guess?) would definitely help. > > Merry Christmas, > Chris > > -- > Follow the path of the Iguana...http://rebertia.com Hi Chris: I have to use python2.4 since many other python packages have not been updated to 2.6. Here is my demo: I create a table in postgresql: create table my_table ( id serial, name char(20), phone char(20) ); and insert two records into the table (4, '??', '1334995555555') (5, '??', '3434343434343') I would like to generate a html page dynamically, here is the demo script ############################################################ def do_search(a): # ??ODBC?? import odbc # ??ODBC??"my_odbc"??????????? cc = odbc.odbc('dsn=wisco') cursor1 = cc.cursor() # ??????????"my_table" #cursor1.execute("select * from my_table where name = '%s' "%a) cursor1.execute("select * from my_table where name like '%%%s%%' "%a) rr = cursor1.fetchall() # ????????? row01 = rr[0] row02 = rr[1] print row01, row02 html_str = '' #print "Content-Type: text/html\n\n" html_str += " test \n" html_str += "\n" html_str += " \n" html_str = html_str%(row01,row02) f = open('c:\\xbop_sinopec\\apache\\htdocs\\test01.html','w') f.write(html_str) f.close do_search('??') ######################################################### The html code is as follows test But the '??' is '\xd6\xd0\xce\xc4'. When row01 and row02 is called from somewhere, '\xd6\xd0\xce\xc4' can not be displayed correctly as '??' in html environment. Thanks for your help and Merry Christmas to you too. ouyang From sonicsai at gmail.com Tue Dec 23 23:25:16 2008 From: sonicsai at gmail.com (sai) Date: Tue, 23 Dec 2008 20:25:16 -0800 Subject: turtle ? In-Reply-To: References: <41d04d600812230210s5b90aa0cud8a3161ca816c80e@mail.gmail.com> Message-ID: <41d04d600812232025k63d1b8bcyff82c0fbbce8b3ac@mail.gmail.com> On Tue, Dec 23, 2008 at 2:29 AM, Gerhard H?ring wrote: > sai wrote: >> python newbie here :-) >> >> I am trying to get turtle to run but got stuck here: >> >> $ python >> Python 2.5.2 (r252:60911, Aug 5 2008, 16:17:28) >> [GCC 4.2.2 20071128 (prerelease) (4.2.2-3.1mdv2008.0)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> import turtle >> Traceback (most recent call last): >> File "", line 1, in >> ImportError: No module named turtle >> >> I have used google to search the web and the newsgroup but got >> nothing. The Linux distro is Mandriva, if that makes a difference. > > Mandriva have probably split Python into several packages. If so, > chances are one of them contains the tkinter GUI library. You should > look in your package management tool for a package called > python-tkinter, python-tk or similar and install it. > > HTH > > Gerhard > there is a Mandriva rpm called tkinter-apps ! thanks Gerhard. sai From rt8396 at gmail.com Wed Dec 24 11:49:28 2008 From: rt8396 at gmail.com (r) Date: Wed, 24 Dec 2008 08:49:28 -0800 (PST) Subject: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> <90f06b27-39da-4f1a-a878-f3972e942d57@s24g2000vbp.googlegroups.com> <62caf93b-0455-4450-9895-8a9d9554f75e@r32g2000vba.googlegroups.com> <1isezkk.51e05y1457jqrN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <3cb2a746-1a43-44a1-9825-7667af9fe2fa@s1g2000prg.googlegroups.com> 220 ratings and 1 star, WHOOOO!. I find this all quite amusing :D. Keep em coming. Oh, and FYI, I will always have 1 star! hahahahahha /"\ |\./| | | | | |>~<| | | /'\| |/'\ /~\| | | |__ | | } | | \ | | | | | \ | ~ ~ ~ ~ |` ) | / \ / \ / \ ____ / |--//''`\--| | (( +==)) | |--\_|_//--| From google at mrabarnett.plus.com Mon Dec 15 11:15:41 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 15 Dec 2008 16:15:41 +0000 Subject: alt.possessive.its.has.no.apostrophe In-Reply-To: <49467CE2.3060401@holdenweb.com> References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> <49467CE2.3060401@holdenweb.com> Message-ID: <494682AD.2030900@mrabarnett.plus.com> Steve Holden wrote: > Ben Finney wrote: >> James Stroud writes: >> >>> Ben Finney wrote: >>>> James Stroud writes: >>>> >>>>> Yes. I think it was the British who decided that the >>>>> apostrophe rule for "it" would be reversed from normal usage >>>>> relative to just about every other noun. >> It also seems an indefensible claim to say that anyone ?decided? it >> would be that way, especially ?the British?. >> > It's our language, dammit! Ours, ours, ours! > > This decision was actually taken at a meeting of the Society of > British pedants on November 23, 1786. This led to a schism between > the British and the newly-independent Americans, who responded by > taking the "u" out of colour, valour, and aluminium. > Actually the Americans have been a bit confused about how to spell aluminium. See http://en.wikipedia.org/wiki/Aluminium_(element). >>>> Remember that ?it? is a pronoun. I see no reversal: >>> Ok. Pronouns are reversed. >> Or, more generally: Pronouns, which are different in just about >> every other way from other nouns, are different in this way also. >> Is that about right? >> > > Just think of them as "nounpros" and you won't go wrong. > I've just remembered a pronoun that does take an apostrophe: the indefinite pronoun "one". Not that one uses it that often. :-) From alex.gaynor at gmail.com Tue Dec 9 02:25:12 2008 From: alex.gaynor at gmail.com (Alex_Gaynor) Date: Mon, 8 Dec 2008 23:25:12 -0800 (PST) Subject: Guido's new method definition idea References: <014a071a$0$20670$c3e8da3@news.astraweb.com> <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> <79139d04-bd26-4f36-b8c9-19554e7d4e95@e18g2000yqo.googlegroups.com> <6q6j50Fau4iiU1@mid.individual.net> Message-ID: <63a5723b-e078-4fe5-b046-6196ef5f61b1@n10g2000yqm.googlegroups.com> I'm a huge -1 on this, it adds nothing to the language, and IMO violates quite a few Zens. -Beautiful is better than ugly. A bit subjective, but this is ugly IMO. -Special cases aren't special enough to break the rules. -There should be one-- and preferably only one --obvious way to do it. From stef.mientki at gmail.com Sun Dec 7 07:49:06 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 07 Dec 2008 13:49:06 +0100 Subject: how to get a beep, OS independent ? In-Reply-To: <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> Message-ID: <493BC642.9010104@gmail.com> Chris Rebert wrote: > On Sun, Dec 7, 2008 at 1:27 AM, Stef Mientki wrote: > >> Rainy wrote: >> >>> On Dec 6, 3:40 pm, Stef Mientki wrote: >>> >>> >>>> hello, >>>> >>>> I want to give a small beep, >>>> for windows there's message-beep, >>>> and there seems to be something like " curses" , >>>> but that package seems to be totally broken in P2.5 for windows. >>>> >>>> Any other suggestions ? >>>> >>>> thanks, >>>> Stef Mientki >>>> >>>> >>> For win there's winsound, you have to check sys.platform and do >>> what's necessary for the platform in question. In linux I think >>> you can just print '\a' (or does that only work in terminals?). >>> If you know that ext. speakers are always on, you can do a nicer >>> beep by using some wav file, in linux it's probably easiest to >>> use an external program to play it, like wavplay. Basically, >>> there is no single answer, it depends on circumstances. >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >>> >> '\a' or chr(7) prints an inverted "BEL". >> > > Inverted bell? In the output window (stdout) which is black letters on white background, it prints "bell" in white letters with a black background. > What do you mean? And what version dependency are you > referring to? > Well some of you actually hear something, I don't, so I expect that the Python version differs. cheers, Stef > Cheers, > Chris > > From steve at REMOVE-THIS-cybersource.com.au Mon Dec 1 18:04:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 01 Dec 2008 23:04:45 GMT Subject: Two attributes! Why? References: <76bc5df8-26fd-4e2d-a134-c5d13ea3b39a@n10g2000yqm.googlegroups.com> <0140c948$0$20670$c3e8da3@news.astraweb.com> Message-ID: <01446567$0$20670$c3e8da3@news.astraweb.com> On Mon, 01 Dec 2008 07:43:44 -0800, Emanuele D'Arrigo wrote: > On Nov 29, 5:21?am, Steven D'Aprano cybersource.com.au> wrote: >> This is a side-effect of name-mangling. Double-underscore names are >> only mangled when they are referred to directly as attributes, not when >> they are passed to setattr, getattr etc. Those functions don't do any >> name mangling. > > Ah! That make sense! Thank you! > > It's a bit of an obscure thing right now. I don't see mention of it in > the description of the setattr/getattr built-ins: > > http://docs.python.org/library/functions.html > > Wouldn't be good to have a hint of the issue there? Not really. You seem to assume that name mangling always happens unless the docs say it doesn't. That's backwards. Name mangling *never* happens except where the docs say it does. Hence I can tell you that self.__dict__['__name'] will fail to find a name-mangled attribute self.__name without even trying it, because I know dictionary lookups don't do name-mangling either. -- Steven From lists at cheimes.de Tue Dec 23 09:51:48 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 23 Dec 2008 15:51:48 +0100 Subject: python3 urlopen(...).read() returns bytes In-Reply-To: <42ad842c-8d8a-4ff5-a721-0688b7ae20f7@41g2000yqf.googlegroups.com> References: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> <5496b34d-7ce4-4281-9f01-aed12dab9fd3@f33g2000vbf.googlegroups.com> <42ad842c-8d8a-4ff5-a721-0688b7ae20f7@41g2000yqf.googlegroups.com> Message-ID: ajaksu wrote: > On Dec 22, 9:05 pm, Christian Heimes wrote: >> ajaksu schrieb: >> >>> That said, a "decode to declared HTTP header encoding" version of >>> urlopen could be useful to give some users the output they want (text >>> from network io) or to make it clear why bytes is the safe way. >> Yeah, your idea sounds both useful and feasible. A patch is welcome! :) > > Would monkeypatching what urlopen returns be good enough or should we > aim at a cleaner implementation? If you want to do it right ... It should be a clean patch against the py3k svn branch including documentation and a unit test. Don't worry! It's not as hard as it sounds. Besides Python core development is fun. :) Christian From steve at REMOVE-THIS-cybersource.com.au Tue Dec 9 17:57:37 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Dec 2008 22:57:37 GMT Subject: Can't figure out where SyntaxError: can not delete variable 'x' referenced in nested scope us coming from in python >=2.6 References: Message-ID: <014eef7f$0$20670$c3e8da3@news.astraweb.com> On Tue, 09 Dec 2008 13:11:40 -0500, Albert Hopkins wrote: > The difference is under Python 2.4 I get a traceback with the lineno and > offending line, but I do not get a traceback in Pythons 2.6 and 3.0. If tracebacks are broken, surely that would be a pretty huge bug. It seems to be broken in 2.5 as well: >>> def a(x): ... def b(): ... x ... del x ... SyntaxError: can not delete variable 'x' referenced in nested scope > So is there a way to find the offending code w/o having to go through > every line of code in 'foo' by hand? Just search for "del x" in your code. Your editor does have a search function, surely? -- Steven From steven at REMOVE.THIS.cybersource.com.au Mon Dec 8 21:44:43 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 09 Dec 2008 02:44:43 GMT Subject: Rich Comparisons Gotcha References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Mon, 08 Dec 2008 10:20:56 -0800, Rhamphoryncus wrote: > On Dec 7, 4:20?pm, Steven D'Aprano cybersource.com.au> wrote: >> On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: >> > Rasmus Fogh wrote: >> >> >> Current behaviour is both inconsistent and counterintuitive, as >> >> these examples show. >> >> >>>>> x = float('NaN') >> >>>>> x == x >> >> False >> >> > Blame IEEE for that one. Rich comparisons have nothing to do with >> > that one. >> >> There is nothing to blame them for. This is the correct behaviour. NaNs >> should *not* compare equal to themselves, that's mathematically >> incoherent. > > Mathematically, NaNs shouldn't be comparable at all. They should raise > an exception when compared. In fact, they should raise an exception > when *created*. But that's not what we want. What we want is a dummy > value that silently plods through our calculations. For a dummy value > it seems a lot more sense to pick an arbitrary yet consistent sort order > (I suggest just above -Inf), rather than quietly screwing up the sort. > > Regarding the mythical IEEE 754, It's hardly mythical. http://ieeexplore.ieee.org/ISOL/standardstoc.jsp?punumber=4610933 > although it's extremely rare to find > quotations, I have one on just this subject. And it does NOT say "x == > NaN gives false". It says it gives *unordered*. Unordered means that none of the following is true: x > NaN x < NaN x == NaN It doesn't mean that comparing a NaN with something else is an error. -- Steven From xahlee at gmail.com Tue Dec 2 15:50:44 2008 From: xahlee at gmail.com (Xah Lee) Date: Tue, 2 Dec 2008 12:50:44 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: <591e8625-7e4d-4db8-ae6c-73c4370f8088@q26g2000prq.googlegroups.com> On Dec 2, 12:21 pm, Lew wrote: > Xah Lee wrote: > > LOL Jon. r u trying to get me to do otimization for you free? > > These are professional software development forums, not some script- > kiddie cellphone-based chat room. "r" is spelled "are" and "u" should > be "you". > > > how about pay me $5 thru paypal? I'm pretty sure i [sic] can speed it up. > > Say, maybe 10%, and even 50% is possible. > > The first word in a sentence should be capitalized. "PayPal" is a > trademark and should be capitalized accordingly. The word "I" in > English should be capitalized. > > Proper discipline in these matters helps the habit of mind for > languages like Java, where case counts. > > Jon Harrop has a reputation as an extremely accomplished software > maven and columnist. I find his claims of relative speed and > compactness credible. He was not asking you to speed up his code, but > claiming that yours was not going to be as effective. The rhetorical > device of asking him for money does nothing to counter his points, > indeed it reads like an attempt to deflect the point. Dear tech geeker Lew, If u would like to learn english lang and writing insights from me, peruse: ? Language and English http://xahlee.org/Periodic_dosage_dir/bangu/bangu.html In particular, i recommend these to start with: ? To An Or Not To An http://xahlee.org/Periodic_dosage_dir/bangu/an.html ? I versus i http://xahlee.org/Periodic_dosage_dir/bangu/i_vs_I.html ? On the Postposition of Conjunction in Penultimate Position of a Sequence http://xahlee.org/Periodic_dosage_dir/t2/1_2_and_3.html some analysis of common language use with respect to evolutionary psychology, culture, ethology, ethnology, can be seen ? for examples ? at: ? Hip-Hop Rap and the Quagmire of (American) Blacks http://xahlee.org/Periodic_dosage_dir/sanga_pemci/hiphop.html ? Take A Chance On Me http://xahlee.org/Periodic_dosage_dir/sanga_pemci/take_a_chance_on_me.html ? ????? (Age of Blossom) http://xahlee.org/Periodic_dosage_dir/sanga_pemci/hua3yang4nian2hua2.html As to questioning my expertise of Mathematica in relation to the functional lang expert Jon Harrop, perhaps u'd be surprised if u ask his opinion of me. My own opinion, is that my Mathematica expertise surpasses his. My opinion of his opinion of me is that, my opinion on Mathematica is not to be trifled with. Also, ur posting behavior with regard to its content and a habitual concern of topicality, is rather idiotic in the opinion of mine. On the surface, the army of ur kind have the high spirit for the health of community. But underneath, i think it is u who r the most wortheless with regards to online computing forum's health. I have published a lot essays regarding this issue. See: ? Netiquette Anthropology http://xahlee.org/Netiquette_dir/troll.html PS when it comes to english along with tech geeker's excitement of it, one cannot go by without mentioning shakespeare. ? The Tragedy Of Titus Andronicus, annotated by Xah Lee http://xahlee.org/p/titus/titus.html Please u peruse of it. Xah ? http://xahlee.org/ ? From jasnow1 at gmail.com Fri Dec 26 21:09:30 2008 From: jasnow1 at gmail.com (Al Snow) Date: Fri, 26 Dec 2008 18:09:30 -0800 (PST) Subject: ruby -> python translator exists? References: <04b51f42-e18e-4902-8a98-38f0538c1eda@s9g2000prg.googlegroups.com> <4a10794e-a3e7-4aa4-8d21-580152806277@c36g2000prc.googlegroups.com> Message-ID: <72c2df21-db59-4870-9388-ccaa47cf11e4@20g2000yqt.googlegroups.com> On Dec 26, 8:31?pm, bearophileH... at lycos.com wrote: > rogerdpack: > > > Hi all. ?My name is Roger. > > Hello Roger, my name is bearophile. > > > Anybody know of a Ruby -> Python translator at all? ?I'm looking for a > > way to have my Ruby code take advantage of the coolio speed of Psyco. > > I have never heard of such translator, so far. > > > Also question. Does psyco work with Python 3.0? > > It doesn't work with Python3 and you may need lot of time to see it > come out... if you will ever see it. > > Bye, > bearophile Search for the tool "Unholy". -- Al From rt8396 at gmail.com Sun Dec 21 13:47:21 2008 From: rt8396 at gmail.com (r) Date: Sun, 21 Dec 2008 10:47:21 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> <6r6hpfFfb643U3@mid.uni-berlin.de> <494E6FDA.4070401@mrabarnett.plus.com> <4585c27d-d7a9-480f-991c-a869161be55c@g38g2000yqn.googlegroups.com> Message-ID: <3392a51b-d3fd-4986-9c59-fecccc7272da@p2g2000prn.googlegroups.com> Could not have said it better myself Luis, i stay as far away from C as i can. But there are usage cases for it. From fetchinson at googlemail.com Sat Dec 27 21:40:52 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 27 Dec 2008 18:40:52 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: >> This is the function I have, the corresponding python function will >> take two equal length lists of integers and the C function will >> compute their sum and return the result as a python tuple. >> >> >> static PyObject *func( PyObject * self, PyObject * args ) >> { >> int j, N; >> int * src1, * src2; >> PyObject *list1, *list2; >> >> list1 = PyTuple_GetItem( args, 0 ); >> N = PyList_Size( list1 ); >> src1 = ( int * ) malloc( N * sizeof( int ) ); >> for( j = 0; j < N; j++ ) >> { >> src1[j] = (int)PyInt_AsLong( PyList_GetItem( list1, j ) ); >> } >> >> list2 = PyTuple_GetItem( args, 1 ); >> N = PyList_Size( list2 ); >> src2 = ( int * ) malloc( N * sizeof( int ) ); >> for( j = 0; j < N; j++ ) >> { >> src2[j] = (int)PyInt_AsLong( PyList_GetItem( list2, j ) ); >> } >> >> PyObject * tuple; >> tuple = PyTuple_New( N ); >> for( j = 0; j < N; j++ ) >> { >> PyTuple_SetItem( tuple, j, PyInt_FromLong( (long)( src1[j] + >> src2[j] ) ) ); >> } >> >> free( src1 ); >> free( src2 ); >> >> return tuple; >> } > > As others already said, using a Numpy array or an array.array object would > be more efficient (and even easier - the C code gets a pointer to an array > of integers, as usual). Thanks, I didn't know that an array.array can be passed to C code as a C pointer to an array. So I'll use an array.array because this is really convenient. >> Do I have to free the memory occupied by the python objects list1 and >> list2? > > No. Usually you don't do that for any Python object - just > increment/decrement its reference count (using Py_INCREF/Py_DECREF). Great, one headache less :) >> Do I have to do any refcounting for list1, list2, tuple? > > In this case list1 and list2 come from PyTuple_GetItem; the docs say it > returns a "borrowed reference" (that is, the function doesn't increment > the refcount itself). So you don't have to decrement it yourself (and it > isn't necesary to increment it in the first place, because the "args" > tuple holds a reference, so the object can't disappear until the function > exits, at least) > >> Any comment on the above code will be very appreciated! If I'm pushed >> in the right direction I'm a fast learner but the beginning steps are >> always hard :) > > You MUST check EVERY function call for errors! Yes, I know :) > And check the argument's type (how do you know it is a list?). Once you > are sure the first parameter *is* a list, you may use the "macro" version > of several functions, like PyList_GET_SIZE and PyList_GET_ITEM. The macro versions are preferable because they are faster? > You should check that both lists have the same length too. > And you should check that elements are integers, or convertible to > integers (in case of error, PyInt_AsLong returns -1 and PyErr_Occurred() > is true) > To fill the resulting tuple, use PyTuple_SET_ITEM instead. BTW, why return > a tuple and not a list? No particular reason, other than the fact that I won't need to modify these lists/tuples from python so whenever something will not change, I use a tuple because it's immutable. Or this is not a very good practice? There is no difference between lists and tuples in terms of speed I suppose (getitem, setitem, etc). Thanks a lot, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From darcy at druid.net Tue Dec 16 14:26:33 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 16 Dec 2008 14:26:33 -0500 Subject: Where is a good open source python project to be used as example? In-Reply-To: <05T1l.219074$FR.507685@twister1.libero.it> References: <05T1l.219074$FR.507685@twister1.libero.it> Message-ID: <20081216142633.3671422a.darcy@druid.net> On Tue, 16 Dec 2008 19:13:00 GMT Andrea Francia wrote: > I'm looking for a python project to use as example to learning python. > > The project should have these features: > > 1. is almost fully unit tested > 2. use consistently the code convention recommended by PEP 8 > 3. it's elements are almost fully documented > > Extra point features are: > > 4. building, assembling, and release automation > > Did you know where are such projects? http://www.PyGreSQL.org/. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From lie.1296 at gmail.com Tue Dec 16 11:04:24 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 16 Dec 2008 16:04:24 +0000 (UTC) Subject: Generator slower than iterator? References: Message-ID: On Tue, 16 Dec 2008 12:07:14 -0300, Federico Moreira wrote: > Hi all, > > Im parsing a 4.1GB apache log to have stats about how many times an ip > request something from the server. > > The first design of the algorithm was > > for line in fileinput.input(sys.argv[1:]): > ip = line.split()[0] > if match_counter.has_key(ip): > match_counter[ip] += 1 > else: > match_counter[ip] = 1 > > And it took 3min 58 seg to give me the stats > > Then i tried a generator solution like > > def generateit(): > for line in fileinput.input(sys.argv[1:]): > yield line.split()[0] > > for ip in generateit(): > ...the same if sentence > > Instead of being faster it took 4 min 20 seg > > Should i leave fileinput behind? > Am i using generators with the wrong aproach? What's fileinput? A file-like object (unlikely)? Also, what's fileinput.input? I guess the reason why you don't see much difference (and is in fact slower) lies in what fileinput.input does. Generators excels in processing huge data since it doesn't have to create huge intermediate lists which eats up memory, given an infinite memory, a generator solution is almost always slower than straight up solution using lists. However in real life we don't have infinite memory, hogging our memory with the huge intermediate list would make the system start swapping, swapping is very slow and is a big hit to performance. This is the way generator could be faster than list. From benjamin.kaplan at case.edu Wed Dec 31 16:30:31 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 31 Dec 2008 16:30:31 -0500 Subject: Creating an application for Linux In-Reply-To: <7d2fe328-064c-46da-9150-7305b6f9e94e@b41g2000pra.googlegroups.com> References: <7d2fe328-064c-46da-9150-7305b6f9e94e@b41g2000pra.googlegroups.com> Message-ID: On Wed, Dec 31, 2008 at 4:06 PM, Mike Driscoll wrote: > Hi, > > My boss wants me to port one of my applications to Ubuntu. I > successfully ported it without too many headaches but now I need a way > to distribute it to people that may or may not already have the > dependencies my application requires. I'm a newb with Linux so I'm not > even sure what they call the distribution (rpms, deb, source code). > Debian packages (debs) are basically a zipped directory with all of the files, descriptions of where to put them, and a list of dependencies. You can find more about them here. http://www.debian.org/doc/FAQ/ch-pkg_basics.en.html > After browsing the various "installer" docs out there, it looks like > bbfreeze or PyInstaller might work, but I couldn't find any examples. > Any advice is appreciated. Thanks! When you create a debian package, you are trying to create a program for one specific distro. Deb files are installers, closer to MSI files than EXE (I assume you're coming from Windows). Using the deb files, you can install the program into /usr/lib or /usr/local/lib, put the program on the system path, and add it to the applications menu. You don't need to create a binary for this- you can just run the python files directly. Using debian packages, you can also add documentation and man pages. Apt will ensure that all of the dependencies are installed before your program is. Using apt, you can also uninstall the program easily. I haven't created any packages, so I don't know how hard it is to generate the package. bbfreeze and PyInstaller work differently. They create a binary executible that the user can run. Everything the user needs (Python and all your libraries) are put into a single file (or into an executable and a bunch of library files). This is easier to distribute and will work on all versions of Linux, but it won't be "installed" (to remove it, you have to manually remove all the files). If you want to use these, you should probably look at gui2exe (http://code.google.com/p/gui2exe/) rather than trying to figure out the commands yourself. Andrea Gavana, the program's creator, follows the wxPython-users list if you need help with it. > > I am using Python 2.5.2 and this is a wxPython application with > SqlAlchemy and a few other external packages. > > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 23:29:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Dec 2008 04:29:45 GMT Subject: Don't you just love writing this sort of thing :) References: Message-ID: <0149f773$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 20:19:22 -0800, Istvan Albert wrote: > On Dec 3, 8:07?pm, Lawrence D'Oliveiro central.gen.new_zealand> wrote: > > > > Originally, like many others here I said YIKES! but on a second read, it > is not that bad. It actually grows on you. Just like a disfiguring skin disease. > After looking at it one more time I found it neat, very concise without > being unreadable. It would have been far more concise without the for statement (not the entire loop) being spread over EIGHT lines... one of which was a lonely colon, all by itself. -- Steven From nick-news at net4u.hr Wed Dec 24 09:40:31 2008 From: nick-news at net4u.hr (Nikola Skoric) Date: Wed, 24 Dec 2008 14:40:31 +0000 (UTC) Subject: python web programming for PHP programmers Message-ID: I0m a python newbie with PHP background. I've tried to make a web app from one of my python scripts (which I haven't done before) and I ended up with: which works really nice :-D For some reason I can't find no "quick and dirty python web programming tutorial for PHP programmers" on google. :-D I don't need a general python tutorial, I just need a tutorial on how to make a hello world server side script with python. Any suggestions? -- "Now the storm has passed over me I'm left to drift on a dead calm sea And watch her forever through the cracks in the beams Nailed across the doorways of the bedrooms of my dreams" From swapnak01 at gmail.com Thu Dec 4 08:57:37 2008 From: swapnak01 at gmail.com (sona) Date: Thu, 4 Dec 2008 05:57:37 -0800 (PST) Subject: operational amplifier Message-ID: <2b4c352e-df02-40e9-ae63-d56bb1bbfc23@r15g2000prh.googlegroups.com> An operational amplifier, often called an op-amp , is a DC-coupled high-gain electronic voltage amplifier with differential inputs and, usually, a single output. Typically the output of the op-amp is controlled either by negative feedback, which largely determines the magnitude of its output voltage gain, or by positive feedback, which facilitates regenerative gain and oscillation. High input impedance at the input terminals and low output impedance are important typical characteristics. http://electronicstopics.blogspot.com/2008/10/operational-amplifier.html From jon at ffconsultancy.com Mon Dec 8 07:08:48 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Mon, 08 Dec 2008 12:08:48 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> Message-ID: <4ridnecnkLopkKDUnZ2dnUVZ8qbinZ2d@posted.plusnet> Xah Lee wrote: > The result and speed up of my code can be verified by anyone who has > Mathematica. You changed the scene that is being rendered => your speedup is bogus! Trace the scene I originally gave and you will see that your program is no faster than mine was. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From theller at python.net Fri Dec 19 11:43:25 2008 From: theller at python.net (Thomas Heller) Date: Fri, 19 Dec 2008 17:43:25 +0100 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> Message-ID: <6r219cFfc8ovU1@mid.individual.net> Mark Summerfield schrieb: > Just a follow-up to say that the book has now been published in the > U.S. > It is now in stock at InformIT, and should reach other stores, e.g., > Amazon, in a week or so. > > Also, the introduction, the first few pages of the first chapter, the > whole of chapter 12 (regular expressions), and the index are now > available for free download in a PDF from here: > http://www.informit.com/store/product.aspx?isbn=0137129297 Question from a non-native english speaker: is this now valid english? "One of Python?s great strengths" ^ "and also teaches Python?s functional programming features" ^ "The book?s approach is wholly practical" ^ Curious, Thomas From lkcl at lkcl.net Tue Dec 2 07:45:02 2008 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Tue, 2 Dec 2008 12:45:02 +0000 Subject: [ANN] Pyjamas 0.4: Python Web Toolkit Release Message-ID: This is the 0.4 Release of Pyjamas, the python-to-javascript compiler and Web Widget set and framework. Download Pyjamas 0.4 here: https://sourceforge.net/project/showfiles.php?group_id=239074 http://code.google.com/p/pyjamas/downloads/list Pyjamas started as a port of Google's Web Toolkit, to python. Explaining why Pyjamas (and GWT) is so significant takes some doing: the summary is that comprehensive desktop-like user interfaces can be developed very simply, to run in any modern web browser, without having to write a single line of JavaScript. Further recommended reading is here: http://advogato.org/article/993.html http://advogato.org/article/981.html The homepage is http://pyjs.org The sister project, Pyjamas-Desktop, is at http://pyjd.org Documentation on Pyjamas is considerable, and includes: http://pyjs.org/book/output/Bookreader.html http://pyjs.org/showcase/Showcase.html http://pyjd.sf.net/api http://pyjd.sf.net/controls_tutorial.html http://lkcl.net/pyjamas-desktop/docs/output/docui.html Also, as the Pyjamas UI API is near-identical to that of GWT 1.5, the GWT JavaDoc reference guide is still relevant: http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/index.html From lie.1296 at gmail.com Sat Dec 13 22:31:14 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 14 Dec 2008 03:31:14 +0000 (UTC) Subject: Python 3.0 crashes displaying Unicode at interactive prompt References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> Message-ID: On Sat, 13 Dec 2008 14:09:04 -0800, John Machin wrote: > On Dec 14, 8:07?am, "Chris Rebert" wrote: >> On Sat, Dec 13, 2008 at 12:28 PM, John Machin >> wrote: >> >> > Python 2.6.1 (r261:67517, Dec ?4 2008, 16:51:00) [MSC v.1500 32 bit >> > (Intel)] on win32 >> > Type "help", "copyright", "credits" or "license" for more >> > information. >> >>>> x = u'\u9876' >> >>>> x >> > u'\u9876' >> >> > # As expected >> >> > Python 3.0 (r30:67507, Dec ?3 2008, 20:14:27) [MSC v.1500 32 bit >> > (Intel)] on win 32 >> > Type "help", "copyright", "credits" or "license" for more >> > information. >> >>>> x = '\u9876' >> >>>> x >> > Traceback (most recent call last): >> > ?File "", line 1, in >> > ?File "C:\python30\lib\io.py", line 1491, in write >> > ? ?b = encoder.encode(s) >> > ?File "C:\python30\lib\encodings\cp850.py", line 19, in encode >> > ? ?return codecs.charmap_encode(input,self.errors,encoding_map)[0] >> > UnicodeEncodeError: 'charmap' codec can't encode character '\u9876' >> > in position >> > 1: character maps to >> >> > # *NOT* as expected (by me, that is) >> >> > Is this the intended outcome? >> >> When Python tries to display the character, it must first encode it >> because IO is done in bytes, not Unicode codepoints. When it tries to >> encode it in CP850 (apparently your system's default encoding judging >> by the traceback), it unsurprisingly fails (CP850 is an old Western >> Europe codec, which obviously can't encode an Asian character like the >> one in question). To signal that failure, it raises an exception, thus >> the error you see. >> This is intended behavior. > > I see. That means that the behaviour in Python 1.6 to 2.6 (i.e. encoding > the text using the repr() function (as then defined) was not intended > behaviour? > >> Either change your default system/terminal encoding to one that can >> handle such characters or explicitly encode the string and use one of >> the provided options for dealing with unencodable characters. > > You are missing the point. I don't care about the visual representation. > What I care about is an unambiguous representation that can be used when > communicating about problems across cultures/ > networks/mail-clients/news-readers ... the sort of problems that are > initially advised as "I got this UnicodeEncodeError" and accompanied by > no data or garbled data. Python defaulted to using strict encoding, which means to throw errors on unencodable characters, but this is NOT the only behavior, you can change the behavior to "replace using placeholder character" or "ignore any errors and discard unencodable characters" | errors can be 'strict', 'replace' or 'ignore' and defaults | to 'strict'. If you don't like the default behavior or you want another kind of behavior, you're welcome to file a bug report at http://bugs.python.org >> Also, please don't call it a "crash" as that's very misleading. The >> Python interpreter didn't dump core, an exception was merely thrown. > > "spew nonsense on the screen and then stop" is about as useful and as > astonishing as "dump core". That's an interesting definition of crash. You're just like saying: "C has crashed because I made a bug in my program". In this context, it is your program that crashes, not python nor C, it is misleading to say so. It will be python's crash if: 1. Python 'segfault'ed 2. Python interpreter exits before there is instruction to exit (either implicit (e.g. falling to the last line of the script) or explicit (e.g sys.exit or raise SystemExit)) 3. Python core dumped 4. Python does something that is not documented From torriem at gmail.com Mon Dec 22 11:21:45 2008 From: torriem at gmail.com (Michael Torrie) Date: Mon, 22 Dec 2008 09:21:45 -0700 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: <494FBE99.6050507@gmail.com> r wrote: > Steven, > Would you like to elaborate on -why- escaped backslashes are needed in > strings... i waiting??? Some character was needed. It just happens that backslashes have been used in this manner for composing nonprintable sequences, codes, etc. It's only in use because someone arbitrarily picked it about 40 years ago. Any character could have been used; any such character would still be have to escaped. Kind of funny that you are complaining about Python in particular when this behavior is in almost all languages today, including Perl, Ruby, Don't blame python for a mistake that Microsoft made, that of choosing a commonly-accepted escape character (long before Python was even though of!) as their path delimiter. Fortunately sane operating systems use a standard slash. Even Windows APIs accept forward slashes as path delimiters. So really your complaint about the backslash is a bit silly. Are you going to campaign that C# and Java also "fix" this problem by choosing another character? From eric at ericaro.net Thu Dec 18 17:30:19 2008 From: eric at ericaro.net (eric) Date: Thu, 18 Dec 2008 14:30:19 -0800 (PST) Subject: Factoring Polynomials References: <5dfe1cf3-530d-4e31-833e-e26db85611be@d36g2000prf.googlegroups.com> Message-ID: On Dec 18, 9:40?pm, "J. Cliff Dyer" wrote: > On Thu, 2008-12-18 at 11:52 -0800, eric wrote: > > On Dec 18, 8:37 pm, collin.da... at gmail.com wrote: > > > I am trying to write a simple application to factor polynomials. I > > > wrote (simple) raw_input lines to collect the a, b, and c values from > > > the user, but I dont know how to implement the quadratic equation > > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > > into python. Any ideas? > > > with numpy: > > from numpy import * > > > s=[1,-1] > > x = -b+s*sqrt( b**2-4*a*c )/(2*a) > > > Eric > > Without the Nump. > > def polynomial(a, b, c): > ? ? N = ((b**2 - 4*a*c)**.5) / 2*a > ? ? return (-b + N, -b - N) there is a little mistake in your formula : def roots_of(a, b, c): N = ((b**2 - 4*a*c)**.5) return ((-b + N)/(2*a), (-b - N)/(2*a)) but I stick with numpy, numpy is heavy, but not as much as using a computer to solve this problem ! And numpy should be standard module for computer science student ! Eric http://codeslash.blogspot.com From febaen at gmail.com Tue Dec 16 09:10:31 2008 From: febaen at gmail.com (feba) Date: Tue, 16 Dec 2008 06:10:31 -0800 (PST) Subject: Free place to host python files? Message-ID: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> I'm getting started in python, and it would be helpful to have a place to put up various code snippets I've made, so I don't have to send them individually to each person I want to show it to. I'd prefer to use something that would give me a directory for my use only, instead of something where you can only upload one at a time. I'd especially like to avoid stuff that uses CAPTCHAs and/or forced waiting periods. I'd really rather not have to run a server off my own computer, if it can be avoided at all. From robin at reportlab.com Thu Dec 4 09:27:49 2008 From: robin at reportlab.com (Robin Becker) Date: Thu, 04 Dec 2008 14:27:49 +0000 Subject: schizophrenic view of what is white space Message-ID: <4937E8E5.2090306@chamonix.reportlab.co.uk> Is python of two minds about what is white space. I notice that split, strip seem to regard u'\xa0' (NO-BREAK SPACE) as white, but that code is not matched by the \s pattern. If this difference is intended can we rely on it continuing? >>> u'a b'.split() [u'a', u'b'] >>> u'a\xa0b'.split() [u'a', u'b'] >>> re.compile(r'\s').search(u'a b') <_sre.SRE_Match object at 0x00DBB2C0> >>> re.compile(r'\s').search(u'a\xa0b') >>> -- Robin Becker From steve at REMOVE-THIS-cybersource.com.au Fri Dec 12 07:21:55 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Dec 2008 12:21:55 GMT Subject: Removing None objects from a sequence References: Message-ID: <01524eee$0$20617$c3e8da3@news.astraweb.com> On Fri, 12 Dec 2008 10:18:35 +0100, Filip Gruszczy?ski wrote: > Hi! > > I would like to iterate over a sequence nad ignore all None objects. The > most obvious way is explicitly checking if element is not None, but it > takes too much space. Too much space??? seq = [x for x in seq if x is not None] It's one line, less than 40 characters. If your hard disk is so full that you're worrying about 40 characters, I suggest you need a bigger disk. > And I would like to get something faster. Faster than what? What speed do we have to beat? > I can use > [ sth for sth in self.__sth if not sth is None ], but I don't know if > that's the best way. Who cares if it's the "best" way? What's important is, is it good enough? It is easier to optimize correct code than to correct optimized code. Get your code working first, then worry about shaving microseconds off the runtime *if you need to*. > I checked itertools, but the only thing that seemed > ok, was ifilter - this requires seperate function though, so doesn't > seem too short. How can I get it the shortest and fastest way? You could do this: seq = filter(None, seq) but only if you know that seq doesn't contain any false objects other than None. -- Steven From martin at v.loewis.de Mon Dec 8 20:04:18 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 09 Dec 2008 02:04:18 +0100 Subject: python-devel download and install In-Reply-To: References: Message-ID: <493DC412.8060909@v.loewis.de> > I am developing in Python version 2.5.2 and need to install and download > the python-devel library. (This is needed so I can build and install > mysql-python.) Where can I find find this module to download and > build/installation instructions? I have been unable to find the source > online to download. > > I am not root on the box where I need to install this module so I need > the source (rpm/deb packages will not do). The sources of Python 2.5.2 are available from http://www.python.org/ftp/python/2.5.2/Python-2.5.2.tar.bz2 The term "python-devel" specifically refers to a rpm/deb package, though. You might need to layout the sources so that they meet your needs (e.g. by installing them locally). Regards, Martin From hniksic at xemacs.org Mon Dec 29 15:22:44 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 29 Dec 2008 21:22:44 +0100 Subject: multiprocessing vs thread performance References: Message-ID: <877i5ipw8b.fsf@mulj.homelinux.net> Roy Smith writes: > In article , > Christian Heimes wrote: > >> You have missed an important point. A well designed application does >> neither create so many threads nor processes. The creation of a thread >> or forking of a process is an expensive operation. You should use a pool >> of threads or processes. > > It's worth noting that forking a new process is usually a much more > expensive operation than creating a thread. If by "forking" you mean an actual fork() call, as opposed to invoking a different executable, the difference is not necessarily that great. Modern Unix systems tend to implement a 1:1 mapping between threads and kernel processes, so creating a thread and forking a process require similar amount of work. On my system, as measured by timeit, spawning and joining a thread takes 111 usecs, while forking and waiting for a process takes 260. Slower, but not catastrophically so. > Not that I would want to create 100,000 of either! Agreed. > Not everybody realizes it, but threads eat up a fair chunk of memory > (you get one stack per thread, which means you need to allocate a > hunk of memory for each stack). I did a quick look around; 256k > seems like a common default stack size. 1 meg wouldn't be unheard > of. Note that this memory is virtual memory, so it doesn't use up the physical RAM until actually used. I've seen systems running legacy Java applications that create thousands of threads where *virtual* memory was the bottleneck. From alex.pulver at gmail.com Sun Dec 21 10:52:02 2008 From: alex.pulver at gmail.com (Alex) Date: Sun, 21 Dec 2008 07:52:02 -0800 (PST) Subject: How to read stdout from subprocess as it is being produced References: <263c3946-86aa-4db0-bdaf-42d0c8e5e5d6@q18g2000vbn.googlegroups.com> Message-ID: <1651a451-dd38-4733-8685-5d9f1906785e@i24g2000prf.googlegroups.com> On Dec 19, 5:09?pm, Albert Hopkins wrote: > On Fri, 2008-12-19 at 06:34 -0800, Alex wrote: > > Hi, > > > I have a Pyhon GUI application that launches subprocess. > > I would like to read the subprocess' stdout as it is being produced > > (show it in GUI), without hanging the GUI. > > > I guess threading will solve the no-hanging issue, but as far as I > > searched for now, I've only seen how to read the stdout after > > subprocess is finished. > > I believe that's going to be highly dependent upon the particular, yet > unspecified, GUI toolkit/API. > > There are probably a few ways. You're toolkit might native support for > this, but one way would be to use a timer. ?Here is some pseudocode: > > class MyWindow(toolkit.Window): > ? ? def __init__(self, ...): > ? ? ? ? ... > ? ? ? ? self.subprocess = subprocess.Popen(..., stdout=subprocess.PIPE) > ? ? ? ? self.running = True > > ? ? ? ? ... > ? ? ? ? toolkit.set_timeout(TIMEOUT_VAL, self.read_stdout) > > ? ? def read_stdout(self, ...): > ? ? ? ? if not self.running: > ? ? ? ? ? ? return > ? ? ? ? char = self.subprocess.stdout.read(1) > ? ? ? ? if char == '': > ? ? ? ? ? ? self.running = False > ? ? ? ? ? ? return > ? ? ? ? self.update_something(char) > ? ? ? ? toolkit.set_timeout(TIMEOUT_VAL, self.read_stdout) Hi, Thanks a lot for the tip! Alex From bearophileHUGS at lycos.com Tue Dec 23 14:51:15 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 23 Dec 2008 11:51:15 -0800 (PST) Subject: 2to3 used in the Shootout Message-ID: <4f1a8f03-fd7f-49ea-8031-61f73fb0c0e8@x16g2000prn.googlegroups.com> They have translated the Python benchmarks of the Shootout site from Py2 to Py3 using 2to3: http://shootout.alioth.debian.org/u32/benchmark.php?test=all&lang=python3 It shows some "performance bugs" of Python3 itself (especially regarding the binary-trees benchmark, that was unexpected by me), and two points where 2to3 may be improved, for example after the translation this gives error: table=string.maketrans('ACBDGHK\nMNSRUTWVYacbdghkmnsrutwvy', 'TGVHCDM \nKNSYAAWBRTGVHCDMKNSYAAWBR')): Gives: TypeError: maketrans arguments must be bytes objects Bye, bearophile From tjreedy at udel.edu Fri Dec 19 02:43:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 19 Dec 2008 02:43:58 -0500 Subject: Factoring Polynomials In-Reply-To: <919062f9-765e-4279-aa26-2c130d4deacf@o4g2000pra.googlegroups.com> References: <919062f9-765e-4279-aa26-2c130d4deacf@o4g2000pra.googlegroups.com> Message-ID: Collin D wrote: > UPDATE: > ' > > #import > from math import sqrt > > # collect data > a = float(raw_input('Type a value: ')) > b = float(raw_input('Type b value: ')) > c = float(raw_input('Type c value: ')) > > # create solver > def solver(a,b,c): > if b**2 - 4*a*c < 0: > return 'No real solution.' > else: > sol1 = (-1 * b + (sqrt(b**2 - 4*a*c))) / 2*a > sol2 = (-1 * b - (sqrt(b**2 - 4*a*c))) / 2*a > return (sol1, sol2) > > # execute > print solver(a,b,c) TEST your code. From Allen.Chenal at gmail.com Fri Dec 5 03:09:08 2008 From: Allen.Chenal at gmail.com (Allen) Date: Fri, 5 Dec 2008 00:09:08 -0800 (PST) Subject: How to distribute C/C++ python extension module on Linux? Message-ID: I have build an extension module PyRPC.so (why not be libPyRPC.so?). The PyRPC.so uses API in libRPCPacker.so. How to distribute the PyRPC.so? I just put PyRPC.so and libRPCPacker.so in the same folder. And under this folder, run python. It tells PyRPC module cannot find a method in libRPCPacker.so. From __peter__ at web.de Wed Dec 17 03:48:01 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 17 Dec 2008 09:48:01 +0100 Subject: eval() and global variables References: Message-ID: Juan Pablo Romero M?ndez wrote: > Suppose this function is given: > > def f(x,y): > return x+y+k > > > Is it possible to somehow assign a value to k without resorting to > making k global? You can replace the function's global dictionary: >>> def f(x, y): ... return x+y+k ... >>> function = type(f) >>> function(f.func_code, dict(k=1))(2, 3) 6 >>> k Traceback (most recent call last): File "", line 1, in NameError: name 'k' is not defined This is a hack, of course. Peter From andrei.avk at gmail.com Sat Dec 6 18:47:51 2008 From: andrei.avk at gmail.com (Rainy) Date: Sat, 6 Dec 2008 15:47:51 -0800 (PST) Subject: how to get a beep, OS independent ? References: Message-ID: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> On Dec 6, 3:40?pm, Stef Mientki wrote: > hello, > > I want to give a small beep, > for windows there's message-beep, > and there seems to be something like " curses" , > but that package seems to be totally broken in P2.5 for windows. > > Any other suggestions ? > > thanks, > Stef Mientki For win there's winsound, you have to check sys.platform and do what's necessary for the platform in question. In linux I think you can just print '\a' (or does that only work in terminals?). If you know that ext. speakers are always on, you can do a nicer beep by using some wav file, in linux it's probably easiest to use an external program to play it, like wavplay. Basically, there is no single answer, it depends on circumstances. From research at johnohagan.com Fri Dec 19 21:34:33 2008 From: research at johnohagan.com (John O'Hagan) Date: Sat, 20 Dec 2008 02:34:33 +0000 Subject: Namespaces, multiple assignments, and exec() Message-ID: <200812200234.33852.research@johnohagan.com> I have a lot of repetitive assignments to make, within a generator, that use a function outside the generator: var1 = func("var1", args) var2 = func("var2", args) var3 = func("var3", args) etc... In each case the args are identical, but the first argument is a string of the name being assigned. It works fine but I'd like to reduce the clutter by doing the assignments in a loop. I've tried using exec(): for name in name_string_list: exec(name + ' = func(\"' + name + '\", args)') but in the local namespace it doesn't understand func(), and if I give it globals() it doesn't understand the args, which come from within the generator. What's a good way to do this kind of thing? Thanks, John From george.sakkis at gmail.com Mon Dec 15 10:34:01 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 15 Dec 2008 07:34:01 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <355f1cfe-6abb-4d2c-8bf4-3aa62e713c1f@w34g2000yqm.googlegroups.com> Message-ID: <504053d8-c482-4db0-8a2c-dcb3f1769eed@s24g2000vbp.googlegroups.com> On Dec 15, 8:15?am, Luis M. Gonz?lez wrote: > On Dec 15, 1:38?am, cm_gui wrote: > > > hahaha, do you know how much money they are spending on hardware to > > make > > youtube.com fast??? > > > > By the way... I know of a very slow Python site called YouTube.com. In > > > fact, it is so slow that nobody ever uses it. > > Buddy, just stop whining and go with c++ if it makes you happy. > By the way, what's the blazingly fast application you need to write so > desperately? > What kind of performance problem have you find in python that makes > you so unhappy? > What are you going to do with all the extra speed provided by c++ (a > Hello World! ?)... Folks, do you *really* feel the urge to feed this troll and his 8-year- old "arguments" again and again ? Please think twice before hitting send on this pointless thread. From lolekk1223 at wp.pl Tue Dec 2 10:48:28 2008 From: lolekk1223 at wp.pl (lolekk1223 at wp.pl) Date: Tue, 2 Dec 2008 07:48:28 -0800 (PST) Subject: Ideal girl dance WEBCAM ! Ideal boobs ! Message-ID: http://yeba.pl/show/movies/5257/Perfect_babe_-_Idealna_kobieta From joel.hedlund at gmail.com Tue Dec 16 08:32:39 2008 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Tue, 16 Dec 2008 14:32:39 +0100 Subject: weird dict problem, how can this even happen? In-Reply-To: References: Message-ID: Duncan Booth wrote: > I think you probably are correct. The only thing I can think that might > help is if you can catch all the situations where changes to the dependent > values might change the hash and wrap them up: before changing the hash pop > the item out of the dict, then reinsert it after the change. That would probably require a lot of uncomfortable signal handling, especially for a piece of functionality I'd like to be as unobtrusive as possible in the application. > Alternatively give up on defining hash and __eq__ for FragmentInfo and rely > on object identity instead. Object identity wouldn't work so well for caching. Objects would always be drawn as they appeared for the first time. No updates would be shown until the objects were flushed from the cache. I've been experimenting with a list cache now and I can't say I'm noticing any change in performance for a cache of 100 items. I'm still using the hash to "freeze" a sort of object tag in order to detect changes, and I require both hash and object equality for cache hits, like so: > def index(self, key): > h = hash(key) > for i, item in enumerate(self.items): > if item.hash == h and item.key == key: > return i > raise KeyError(key) This seems to do what I want and does OK performance wise. Thanks again! /Joel From bigblueswope at gmail.com Wed Dec 3 22:30:14 2008 From: bigblueswope at gmail.com (BJ Swope) Date: Wed, 3 Dec 2008 22:30:14 -0500 Subject: Obtaining SMTP address of a sender and receiver of an outlook mail In-Reply-To: References: Message-ID: If you have access to the AD server that hosts those DNs you can use python's ldap module to retrieve the smtp attribute for the DN you've just parsed from the message. On Wed, Dec 3, 2008 at 2:06 AM, venutaurus539 at gmail.com < venutaurus539 at gmail.com> wrote: > Hi all, > I am trying to use python for extracting contents of an outlook > email. For extracting the list of Recipients addresses I tried using > the "MAPI.message.Recipients.Address" property, but the problem I am > facing is that it is giving the complete DN name which is putting me > in further complications. Is there any way to obtain the actual SMTP > mail address (username at domain.com) from the above object? I searched > for it in the MSDN help but couldn't succeed. > > Thanks in advance, > Venu > -- > http://mail.python.org/mailman/listinfo/python-list > -- We are all slave to our own paradigm. -- Joshua Williams If the letters PhD appear after a person's name, that person will remain outdoors even after it's started raining. -- Jeff Kay Fascism is a term used to describe authoritarian nationalist political ideologies or mass movements that are concerned with notions of cultural decline or decadence and seek to achieve a millenarian national rebirth by exalting the nation or race, and promoting cults of unity, strength and purity. - Wikipedia -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Dec 8 09:00:54 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 08 Dec 2008 15:00:54 +0100 Subject: Beginner trying to understand functions. References: Message-ID: simonh wrote: > In my attempt to learn Python I'm writing a small (useless) program to > help me understand the various concepts. I'm going to add to this as I > learn to serve as a single place to see how something works, > hopefully. Here is the first approach: > That works fine. Then I've tried to use functions instead. The first > two work fine, the third fails: > def getName(): > name = input('Please enter your name: ') > print('Hello', name) > > def getAge(): > while True: > try: > age = int(input('Please enter your age: ')) > break > except ValueError: > print('That was not a valid number. Please try again.') > > def checkAge(): > permitted = list(range(18, 31)) > if age in permitted: > print('Come on in!') > elif age < min(permitted): > print('Sorry, too young.') > elif age > max(permitted): > print('Sorry, too old.') > > getName() > getAge() > checkAge() > > I get this error message: NameError: global name 'age' is not > defined. > > I'm stuck, can someone help? Thanks. Generally, when you calculate something within a function you tell it the caller by returning it: >>> def get_age(): ... return 74 ... >>> get_age() 74 >>> age = get_age() >>> age 74 And if you want a function to act upon a value you pass it explicitly: >>> def check_age(age): ... if 18 <= age <= 30: ... print("Come in") ... else: ... print("Sorry, you can't come in") ... >>> check_age(10) Sorry, you can't come in >>> check_age(20) Come in To check the age determined by the get_age() function you do: >>> age = get_age() >>> check_age(age) Sorry, you can't come in Peter From mohitranka at gmail.com Wed Dec 3 09:18:29 2008 From: mohitranka at gmail.com (Mohit Ranka) Date: Wed, 3 Dec 2008 19:48:29 +0530 Subject: hello In-Reply-To: <63fb26950812030543j2e019219r618390d96a1a493a@mail.gmail.com> References: <63fb26950812030543j2e019219r618390d96a1a493a@mail.gmail.com> Message-ID: <63fb26950812030618u4a957688u7119e15ede257ac6@mail.gmail.com> Hi, Apologies for the previous email. Some hacker/spammer hacked my email password, and sent email using it. Thanks and regards, Mohit Ranka -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp at rebertia.com Fri Dec 26 17:16:30 2008 From: clp at rebertia.com (Chris Rebert) Date: Fri, 26 Dec 2008 14:16:30 -0800 Subject: strange behavior of math.sqrt() in new 3.0 version In-Reply-To: References: Message-ID: <47c890dc0812261416t4c4bc19apc1b8652cee729b@mail.gmail.com> On Fri, Dec 26, 2008 at 1:52 PM, wrote: > I'm a newbee trying 3.0 Please help with math.sqrt() > > At the command line this function works correctly > >>> import math > n = input("enter a number > ") raw_input() was renamed input() in Python 3.0, and it returns a *string*, not a *number*. Therefore, you need to convert the string to an int or float. Change the line to: n = float(input("enter a number > ")) And it should work just fine. > s = math.sqrt(n) > An entry of 9 or 9.0 will yield 3.0 > > Yet the same code in a script gives an error message > Script1 > import math > n = input("enter a number > ") > s = math.sqrt(n) > > Traceback (most recent call last) : > File "", line 1, in > File "script1.py" line 3 in > s = math.sqrt(n) > TypeError : a float is required You're currently giving it a string, not a number, which is nonsensical, hence the TypeError. I presume ints would be coerced to floats by the function. > Entering 9 or 9.0 gives same error message. > > According to the math module the results of all > functions are floats. However it says nothing about > inputs. > > Strangely the above code runs fine in version 2.5 ( ? ) > and will handle large integers. > > I've read the documentation for 3.0 including the section > "Floating Point Arithmetic: Issues & Limitations" and it > helps nada. You should read "What's New in Python 3.0", it covers changes such as the one you've encountered - http://docs.python.org/3.0/whatsnew/3.0.html Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From robert.kern at gmail.com Thu Dec 18 16:27:17 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 18 Dec 2008 15:27:17 -0600 Subject: confused about __str__ vs. __repr__ In-Reply-To: References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> <6qv7kfFeuf65U1@mid.uni-berlin.de> <6qv9v4Ff1lv9U1@mid.uni-berlin.de> Message-ID: Mikael Olofsson wrote: > Diez B. Roggisch wrote: >> Yep. And it's easy enough if you don't care about them being different.. >> >> def __repr__(self): >> return str(self) > > If I ever wanted __str__ and __repr__ to return the same thing, I would > make them equal: > > def __str__(self): > return 'whatever you want' > __repr__ = __str__ > > That makes it more obvious to me what's going on. As a bonus, it saves > one method call for every repr call. Or just define __repr__(). str() falls back to __repr__() if __str__() is not defined. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From joe at strout.net Fri Dec 5 14:00:59 2008 From: joe at strout.net (Joe Strout) Date: Fri, 5 Dec 2008 12:00:59 -0700 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: <5u8o06xbqf.ln2@joeserver.homelan.net> References: <5u8o06xbqf.ln2@joeserver.homelan.net> Message-ID: On Dec 5, 2008, at 11:36 AM, Johannes Bauer wrote: >> I suspect that '?' after \n (\u0a00) is indicates not 'question-mark' >> but 'uninterpretable as a utf16 character'. The traceback below >> confirms that. It should be an end-of-file marker and should not be >> passed to Python. I strongly suspect that whatever wrote the file >> screwed up the (OS-specific) end-of-file marker. I have seen this >> occasionally on Dos/Windows with ascii byte files, with the same >> symptom >> of reading random garbage pass the end of the file. Or perhaps >> end-of-file does not work right with utf16. > > So UTF-16 has an explicit EOF marker within the text? No, it does not. I don't know what Terry's thinking of there, but text files do not have any EOF marker. They start at the beginning (sometimes including a byte-order mark), and go till the end of the file, period. > I cannot find one in original file, only some kind of starting > sequence I suppose > (0xfeff). That's your byte-order mark (BOM). > The last characters of the file are 0x00 0x0d 0x00 0x0a, > simple \r\n line ending. Sounds like a perfectly normal file to me. It's hard to imagine, but it looks to me like you've found a bug. Best, - Joe From news123 at free.fr Sun Dec 14 07:15:28 2008 From: news123 at free.fr (News123) Date: Sun, 14 Dec 2008 13:15:28 +0100 Subject: 1 or 1/0 doesn't raise an exception In-Reply-To: References: Message-ID: <4944f8e0$0$32019$426a74cc@news.free.fr> Hi. r wrote: > These are just the kind of things that make Python so beautiful ;) > Thanks Guido! You shouldn't forget to thank K&R ;-) Shortcutting logical operation shortcuts existed already in C and has been adopted by quite a lot of programming languages. bye N From tjreedy at udel.edu Mon Dec 8 17:09:34 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Dec 2008 17:09:34 -0500 Subject: Beginner trying to understand functions. In-Reply-To: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> Message-ID: cadmuxe wrote: > i think we should use raw_input('Please enter your name: ') instead of > input('Please enter your name: ') 3.0 input == 2.x raw_input 2.5 input == Posters: please include Python version used, as correct answers may depend on that. From steve at holdenweb.com Fri Dec 19 23:02:10 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 19 Dec 2008 23:02:10 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <015c47ad$0$20656$c3e8da3@news.astraweb.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c47ad$0$20656$c3e8da3@news.astraweb.com> Message-ID: <494C6E42.8080008@holdenweb.com> Steven D'Aprano wrote: > On Fri, 19 Dec 2008 10:25:30 -0700, Michael Torrie wrote: > >> So funny that now that Python 3.0 is actually released we have people >> acting all surprised like they've never seen any of the new features in >> Python 3.0 coming. However these features have been discussed for >> years! And debated! > > Debated by who? The entire Python-using community? Every single Python > programmer? Or just the small proportion of Python developers who are > also core developers? > > Are you *really* surprised that some people had never heard of the > changes being debated until it was too late? > It isn't the least surprising that some people have been taken by surprise by the changes. Neither is it surprising that some of them don't like the changes that much. However, at least in the open source world one has the *opportunity* to make one's voice heard and one's opinion known, even thought he majority prefer to remain consumers of the output of open source projects. Where commercial projects are concerned the major influence one has is a post-facto vote with one's wallet. I hope, however, that those who don't like the changes but didn't bother to track developments don't feel in any way disenfranchised. They are still welcome to make their input, and of course there is nothing to stop them keeping Python 2.X alive for as long as they wish. [misconception about print's role] >> Furthermore, the new {} >> notation allows many, many more options for formatting to be used. Want >> to display a floating point number with $#.## notation, and ($#.##) for >> negative? It's all now possible. Couldn't be done before. > > Of course it could be. You just needed to write your own formatting > engine. What you mean is that it couldn't be done with % formatting and > nothing else. > > >> In short, this is a huge improvement, and backwards compatibility is >> preserved for the 2.x style for those that wish it. > > > There clearly is a need for a more heavyweight formatting solution than % > and string.Template. There are things that can't be done easily with % > alone, and format() will make them much simpler. I have no objection to > the addition of the format() method (although I wonder whether it might > have been better as a function). > That's doubtless a debate that will play for a long time, with no really clear advantage either way. Programmers just like to debate these things. Of course it's a trivial addition: def format(s, *args, **kw): return s.format(*args, **kw) [I put **kw in becuase it's easier than checking the docs to se whether keyword arguments are specified]. This doesn't mean there won't be fifteen more posts on this thread about it. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From rayene.benrayana at gmail.com Mon Dec 1 15:23:10 2008 From: rayene.benrayana at gmail.com (Rayene Ben Rayana) Date: Mon, 1 Dec 2008 21:23:10 +0100 Subject: Python introspection and namespace weird question In-Reply-To: <47c890dc0812011037u64076950o186af7477269cc0a@mail.gmail.com> References: <47c890dc0812011037u64076950o186af7477269cc0a@mail.gmail.com> Message-ID: Thanks Chris, Yeah it is kinda meta thing. My app allows to create a scene (a set of GUI objects). A scene can be saved as a python script. And, it can be loaded again using execfile(). each GUI object has a label. So, in the script scene, declaring an object in a scene file should look like this: red_car = MyVehicleClass(*label* = 'red_car') But, I wanted to simplify the syntax of scene files and avoid repetition so it would look like red_car = MyVehicleClass() with the *label* attribute automatically set to the name of the corresponding variable. I tried your locals().iteritems tip and it works perfectly. The question now is: Given what I just explained, do you still think it is bad programming to do that ? Should I better use the first syntax ? Cheers, Rayene, I want to use that to simplify the syntax of the On Mon, Dec 1, 2008 at 7:37 PM, Chris Rebert wrote: > On Mon, Dec 1, 2008 at 6:04 AM, Rayene Ben Rayana > wrote: > > Hello everybody, > > > > Is there an easy way to do something like this in python ? > > > >>>> red_car = MyVehicleClass() > >>>> car = red_car > >>>> car.labels() > > ['red_car' , 'car' ] > > > > In other words, does an instance has access to its name pointers ? > > In short, No. (Cue another debate over whether Python uses call-by-X > semantics...) > > Typically people who want to do such things actually want/should use a > dictionary mapping string keys to instance values instead. > > Note that in certain limited cases, voodoo involving the locals() or > globals() built-in functions or the `inspect` module can work, but not > in the common general case. But generally these techniques are > considered bad style and kludgey unless you're writing a debugger or > something equally meta, with using a dictionary as explained > previously being much preferred. > > For example, for your particular code above, the following happens to work: > [name for name, obj in locals().iteritems() if obj is car] #==> > ['red_car' , 'car' ] > > But this will only give the names in the current function of the > particular car object. Likewise, globals() works only for module-level > names, and the `inspect` module's magic only works for names in > calling functions (i.e. those below the current one in the callstack). > > Cheers, > Chris > -- > Follow the path of the Iguana... > http://rebertia.com > > > > > Thanks in advance, > > > > Rayene > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at mrabarnett.plus.com Tue Dec 30 14:04:11 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 30 Dec 2008 19:04:11 +0000 Subject: duck typing at will In-Reply-To: <6e1bfdea0812301042x70ab57capf99ce73d364d54db@mail.gmail.com> References: <6e1bfdea0812301042x70ab57capf99ce73d364d54db@mail.gmail.com> Message-ID: <495A70AB.4020401@mrabarnett.plus.com> Jose Mora wrote: > Duck typing is called that way because "If it looks like a duck and > quacks like a duck, it must be a duck." I think it would be good to > have also "If the programmer wants to deal with it like a duck, it > must be a duck" > > I mean, some tasks are rather boring in python when compared with php, > for example, let's imagine we have a dictionary that contains > dictionaries that contain the times that a key appears. We, or at > least I, would like to write something as short as: > > dict[k1][k2] += 1 > > However we will have to do a longer code (this is the smallest code I > could come up with): > > dict = {} > if not k1 in dict: > dict[k1] = {} > if not k2 in dict[k1]: > dict[k1][k2] = 0 > dict[k1][k2] += 1 > > I know it is not the Apocalypse nor something really important when > compared with other things, but maybe it would be better if it wasn't > necessary to declare the variables when they are built-in types or to > initialize the keys in a dictionary, having special values (the > identity element of the operation that causes the initialization) to > initialize when it has not been done, initializing with the most > general type that supports the operation that causes the > initialization, casting to other type if necessary after that. > > This is just an idea, maybe I'm not the first one suggesting it, or > maybe it is completely impossible to implement it because it would > require deep changes in python, but I wanted to discuss it. > You could use defaultdict like this: from collections import defaultdict my_dict = defaultdict(lambda: defaultdict(int)) my_dict[k1][k2] += 1 The disadvantage is that my_dict will then return values even when you don't want it to: >>> print my_dict[unknown_key] defaultdict(, {}) so after you've filled it you might want to turn it into a 'normal' dict of dict: my_dict = dict((key, dict(inner.iteritems())) for key, inner in my_dict.iteritems()) From cjw at ncf.ca Fri Dec 19 19:32:22 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Fri, 19 Dec 2008 19:32:22 -0500 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <6r219cFfc8ovU1@mid.individual.net> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> Message-ID: Thomas Heller wrote: > Mark Summerfield schrieb: >> Just a follow-up to say that the book has now been published in the >> U.S. >> It is now in stock at InformIT, and should reach other stores, e.g., >> Amazon, in a week or so. >> >> Also, the introduction, the first few pages of the first chapter, the >> whole of chapter 12 (regular expressions), and the index are now >> available for free download in a PDF from here: >> http://www.informit.com/store/product.aspx?isbn=0137129297 > > Question from a non-native english speaker: is this now valid english? > > "One of Python???s great strengths" > ^ > "and also teaches Python???s functional programming features" > ^ > "The book???s approach is wholly practical" > ^ > > Curious, > Thomas No. Is this a quote from some advertising stuff or was it written by the author? Colin W. From aleksandr.goretoy at gmail.com Sat Dec 27 19:25:05 2008 From: aleksandr.goretoy at gmail.com (alex goretoy) Date: Sat, 27 Dec 2008 18:25:05 -0600 Subject: parsing csv files class In-Reply-To: References: <49562755.6050205@byoteki.com> Message-ID: How would I change this to work with numpy: (Would it be more feasible for storing big files? 300-30,000 records) for row in reader: self.buffer.append(row) s,a=[],{} for j in range(len(self.buffer[0])): a[self.buffer[0][j]]=row[j] self.bufferp.append(a) i+=1 self.total = i-1 Instead of doing self.buffer.append(row) would I initialize numpy like this: self.buffer=numpy.array() and then in the loop do: self.buffer.append(row) ? How do I achieve the same for lower code, where it appends to a dict with header of each column? Thank you. On Sat, Dec 27, 2008 at 5:31 PM, alex goretoy wrote: > I might as well add a UnicodeReader and UnicodeWriter and support for > passing delimiter in from other classes. At the same time. Anyone have a > good csv class I can pick thru? I'm planning on posting my mysql adn curl > classes that I use in my projects I just want to make them better and have > less error. > > > On Sat, Dec 27, 2008 at 5:18 PM, alex goretoy > wrote: > >> It's main concern is to grab the file into the buffer for use in other >> classes. The self.soc.me_him is just so I know when its ENTERING or EXITING >> in that function when I run it in terminal. It's prints it in color. My main >> concern right now is to add error handling. I'm still learning how to use >> assert and yield, but I got try,except down pat. All this class does is >> grabs the file either from http or local storage into a buffer and I use >> that in other classes. I want to add support for creating creating csv as >> well. I read the doc on csv and will try some things out soon. Thanks for >> helping me. >> >> >> On Sat, Dec 27, 2008 at 2:15 PM, Gabriel Genellina < >> gagsl-py2 at yahoo.com.ar> wrote: >> >>> En Sat, 27 Dec 2008 11:02:13 -0200, Gary M. Josack >>> escribi?: >>> >>>> alex goretoy wrote: >>>> >>> >>> I know it's messy with all those self.soc.* functions, but it works in >>>>> one of my current project. I just want to make it more pythonic I also want >>>>> to add capability for makeing csv file if I give it input like: >>>>> 1234,something nice, hey this is something nice >>>>> 2468,something else, something else >>>>> >>>> >>> reader = csv.reader(file(filename, "rb")) >>>>> try: >>>>> for row in reader: >>>>> self.buffer.append(row) >>>>> s,a=[],{} >>>>> >>>> >>> Do you know that there is a csv module in the standard library already? >>>> >>> >>> I'd say he already knows, he even used it in the code. >>> >>> To Alex G.: I didn't understand what's the purpose of this class. >>> Probably you want to do too much things in the same place; looks like it has >>> multiple concerns, and that's not a good idea usually. >>> >>> -- >>> Gabriel Genellina >>> >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> >> >> >> -- >> ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? >> ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? >> >> >> >> -- >> ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? >> ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? >> > > > > -- > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > -- ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp at rebertia.com Wed Dec 24 01:43:19 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 23 Dec 2008 22:43:19 -0800 Subject: socket send help In-Reply-To: References: Message-ID: <47c890dc0812232243l2923696aid4a36020a7acfa7a@mail.gmail.com> On Tue, Dec 23, 2008 at 9:59 PM, greywine at gmail.com wrote: > Hi everyone, > > New guy here. I'm trying to figure out sockets in order to one day do > a multiplayer game. Here's my problem: even the simplest examples > don't work on my computer: > > A simple server: > > from socket import * > myHost = '' > myPort = 21500 > > s = socket(AF_INET, SOCK_STREAM) # create a TCP socket > s.bind((myHost, myPort)) # bind it to the server port > s.listen(5) # allow 5 simultaneous connections > > while True: > connection, address = s.accept() > while True: > data = connection.recv(1024) > if data: > connection.send('echo -> ' + data) > else: > break > connection.close() # close socket > > And a simple client: > > import sys > from socket import * > serverHost = 'localhost' # servername is localhost > serverPort = 21500 # use arbitrary port > 1024 > > s = socket(AF_INET, SOCK_STREAM) # create a TCP socket > > > s.connect((serverHost, serverPort)) # connect to server on the port > s.send('Hello world') # send the data > data = s.recv(1024) # receive up to 1K bytes > print(data) > > > If I run testserver.py via the cmd prompt in Windows XP and then the > testclient.py program, I get the following error: > > Traceback (most recent call last): > File "C:\Python30\testclient.py", line 12, in > s.send('Hello world') # send the data > TypeError: send() argument 1 must be string or buffer, not str > > This happens in 2.6 or 3.0 and with different example client & server > programs from the web. What am I missing? The text of the error message seems outdated (it should probably say "bytes or bytearray" instead of "string or buffer"), but what it's trying to say is that you can only send() bytes, not unicode strings. For a byte literal, you need to add a 'b' prefix, e.g. b'Hello World' Alternatively, you can encode the unicode into bytes using .encode(), e.g. "Hello World".encode('utf8') Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From rhamph at gmail.com Mon Dec 8 13:20:56 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 8 Dec 2008 10:20:56 -0800 (PST) Subject: Rich Comparisons Gotcha References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Dec 7, 4:20?pm, Steven D'Aprano wrote: > On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: > > Rasmus Fogh wrote: > > >> Current behaviour is both inconsistent and counterintuitive, as these > >> examples show. > > >>>>> x = float('NaN') > >>>>> x == x > >> False > > > Blame IEEE for that one. Rich comparisons have nothing to do with that > > one. > > There is nothing to blame them for. This is the correct behaviour. NaNs > should *not* compare equal to themselves, that's mathematically > incoherent. Mathematically, NaNs shouldn't be comparable at all. They should raise an exception when compared. In fact, they should raise an exception when *created*. But that's not what we want. What we want is a dummy value that silently plods through our calculations. For a dummy value it seems a lot more sense to pick an arbitrary yet consistent sort order (I suggest just above -Inf), rather than quietly screwing up the sort. Regarding the mythical IEEE 754, although it's extremely rare to find quotations, I have one on just this subject. And it does NOT say "x == NaN gives false". It says it gives *unordered*. It is C and probably most other languages that turn that into false (as they want a dummy value, not an error.) http://groups.google.ca/group/sci.math.num-analysis/browse_thread/thread/ead0392e646b7cc0/a5bc354cd46f2c49?lnk=st&q=why+does+NaN+not+equal+itself%3F&rnum=3&hl=en&pli=1 From alexoplocatie at gmail.com Wed Dec 17 08:26:48 2008 From: alexoplocatie at gmail.com (aka) Date: Wed, 17 Dec 2008 05:26:48 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> <0d9ea7cc-b5fb-4edb-be32-490aae9e7204@b41g2000pra.googlegroups.com> Message-ID: <36eb36c0-333c-4084-8fc1-1a12d1d2d7d3@a37g2000pre.googlegroups.com> Hi John, thanks. You're right, I didn't past the method header because I thought it didn't matter when the input filename is hardcoded. The try/except isn't very helpful indeed so I commented it out. You're right I wrongly referred to the UnicodeReader class in my first post because that's ultimately where I want to go so I outcommented it here for you to see. The fact is that neither csv.reader nor the UnicodeReader will read the file, while writing with the UnicodeWriter works like a charm. That's why I put str() around roles to see any content. I simplified the csv-file by cutting off columns without result. The file looks now like: id;company;department 12;Cadillac;Research 11;Ford;Accounting 10;Chrysler;Sales The dictionary on the return is because this code is part of my TurboGears application. The entire method is: import csv from utilities.urw import UnicodeWriter, UnicodeReader @expose(allow_json=True) def import_roles(self, input=None, *args, **kwargs): inp = 'C:/temp/test.csv' roles = [] msg = '' ## try: fp = open(inp, 'rb') reader = csv.reader(fp, dialect='excel', delimiter=';') ## reader = UnicodeReader(fp, dialect='excel', delimiter=';') for r in reader: roles.append(r[0]) fp.close() ## except: ## msg = "Something's wrong with the csv.reader" return dict(filepath=inp, roles=str(roles), msg=msg) csv.reader results in: for r in myreader: Error: line contains NULL byte Use of UnicodeReader results in: UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: unexpected code byte Will post only complete code from now on thanks. From gubatron at gmail.com Wed Dec 3 12:54:51 2008 From: gubatron at gmail.com (Gubatron) Date: Wed, 3 Dec 2008 09:54:51 -0800 (PST) Subject: Jython: Packing several .py on .jar, problem importing .py modules within the .jar References: Message-ID: <0ad925d8-f890-4b12-b0e0-e8c3a7dacf8c@v4g2000yqa.googlegroups.com> I've managed to solve this problem. I can now run a python script that lives inside a Jar. The python script is now able to import other scripts within the same jar, and it's also able to import java classes that live within the jar. The problem was solved by giving the Jython Interpreter the proper initialization. This entails: - Giving it a class loader that has put the Jar on it's class path - Adding the path of the jar to the interpreter's sys.path Here's an example: org.python.core.PySystemState pySys = new org.python.core.PySystemState(); pySys.setClassLoader(((URLClassLoader) classLoaders.get(jarFile))); //We also have to pass the jar to JYTHON_PATH (sys.path) //so that it can properly import inner python modules. pySys.path.insert(0,new PyString(jarFile)); //We pass the PythonInterpreter the modified PySystemState PythonInterpreter i = new PythonInterpreter(null, pySys); i.exec(pythonScriptName); On Dec 3, 6:31?am, Gubatron wrote: > Hello all, > > I've a problem with Jython and importing .py inside a jar. > > I'm putting .class and .py files inside .jar files. > > myjar.jar > ? MyJar\SomeClass.class > ? MyJar\main.py > ? MyJar\otherModule.py > > So I add the myjar.jar to Jython's sys.path > > ? ? ? ? ? ? ? ? ? ? ? ? org.python.core.PySystemState pySys = new > org.python.core.PySystemState(); > ? ? ? ? ? ? ? ? ? ? ? ? pySys.path.insert(0,new PyString("/path/to/myjar.jar")); > > and execute main.py > > ? ? ? ? ? ? ? ? ? ? ? ? //We pass the PythonInterpreter the modified PySystemState > ? ? ? ? ? ? ? ? ? ? ? ? PythonInterpreter i = new PythonInterpreter(null, pySys); > > ? ? ? ? ? ? ? ? ? ? ? ? //Find the entry in the jar for the python file and execute it. > ? ? ? ? ? ? ? ? ? ? ? ? //It should be able to find any resource inside the jar. > ? ? ? ? ? ? ? ? ? ? ? ? JarFile jFile = new JarFile("/path/to/myjar.jar"); > ? ? ? ? ? ? ? ? ? ? ? ? ZipEntry zipEntry = jFile.getEntry("MyJar/main.py"); > > ? ? ? ? ? ? ? ? ? ? ? ? InputStream pythonInputStream = > jFile.getInputStream(zipEntry); > ? ? ? ? ? ? ? ? ? ? ? ? i.execfile(pythonInputStream); > > main.py will execute fine, it'll be able to do > > from MyJar import SomeClass > > with no problem > > However, If I try to import the other .py in the same jar, it won't > find it: > > from otherModule import * > > or > > from MyJar.otherModule import * > > I always get this: > > ImportError: no module named otherModule > > ? ? ? ? at org.python.core.Py.ImportError(Unknown Source) > ? ? ? ? at org.python.core.imp.import_first(Unknown Source) > ? ? ? ? at org.python.core.imp.import_name(Unknown Source) > ? ? ? ? at org.python.core.imp.importName(Unknown Source) > ? ? ? ? at org.python.core.ImportFunction.load(Unknown Source) > ? ? ? ? at org.python.core.ImportFunction.__call__(Unknown Source) > ? ? ? ? at org.python.core.PyObject.__call__(Unknown Source) > ? ? ? ? at org.python.core.__builtin__.__import__(Unknown Source) > ? ? ? ? at org.python.core.imp.importFromAs(Unknown Source) > ? ? ? ? at org.python.core.imp.importFrom(Unknown Source) > ? ? ? ? at org.python.pycode._pyx1.f$0(:26) > ? ? ? ? at org.python.pycode._pyx1.call_function() > ? ? ? ? at org.python.core.PyTableCode.call(Unknown Source) > ? ? ? ? at org.python.core.PyCode.call(Unknown Source) > ? ? ? ? at org.python.core.Py.runCode(Unknown Source) > ? ? ? ? at org.python.util.PythonInterpreter.execfile(Unknown Source) > > I've tried adding more paths to sys.path, with no luck: > > pySys.path.insert(0,new PyString("/path/to/myjar.jar/MyJar")); > pySys.path.insert(0,new PyString("file:jar:/path/to/myjar.jar!")); > > and nothing works, any ideas would help. I know this has to work, > because I previously had a problem where I couldn't do > > import os > > and then I added the "Lib/" folder inside jython.jar and now I'm able > to import all those standard jython modules, so, somehow, jython is > able to import .py within a .jar, help would be very much appreciated. > > Angel Leon From dfnsonfsduifb at gmx.de Fri Dec 5 12:28:04 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Fri, 05 Dec 2008 18:28:04 +0100 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: <85fxl24lbu.fsf@dozer.localdomain> References: <85fxl24lbu.fsf@dozer.localdomain> Message-ID: <4u4o06xkhf.ln2@joeserver.homelan.net> J Kenneth King schrieb: > It probably means what it says: that the input file contains characters > it cannot read using the specified encoding. No, it doesn't. The file is just fine, just as the example. > Are you generating the file from python using a file object with the > same encoding? If not, then you might want to look at your input data > and find a way to deal with the exception. I did. The file is fine. Could you try out the example? Regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From Slaunger at gmail.com Wed Dec 3 06:24:04 2008 From: Slaunger at gmail.com (Slaunger) Date: Wed, 3 Dec 2008 03:24:04 -0800 (PST) Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> <258cf433-f6c9-43e7-a235-f5f6b2b6433f@j39g2000yqn.googlegroups.com> <33b4cc2f-2311-491c-a2e6-9cc5452b1a6b@g38g2000yqd.googlegroups.com> Message-ID: <2772646a-623f-400b-a606-281a7e3220d4@20g2000yqt.googlegroups.com> On 3 Dec., 11:30, Nick Craig-Wood wrote: > > ? ? ? ? ?cls = self.__class__ > > ? ? ? ? ?if attr_name in cls.data_attr_names: > > self.data_attr_names should do instead of cls.data_attr_names unless > you are overriding it in the instance (which you don't appear to be). Yeah, I know. I just like the cls notation for code readability because it tells you that it is a class attribute, which is not instance- dependent. That may be legacy from my Java past, where I used to do it that way. I know perfectly well that self. would do it. i just find that notation a little misleading > > ? ? ? ? ? ? ? ? ?I1, Q1, I2, Q2 = bytes_to_data(buf) > > ? ? ? ? ? ? ? ? ?self.__dict__["I1"] = I1 > > ? ? ? ? ? ? ? ? ?self.__dict__["Q1"] = Q1 > > ? ? ? ? ? ? ? ? ?self.__dict__["I2"] = I2 > > ? ? ? ? ? ? ? ? ?self.__dict__["Q2"] = Q2 > > ? ? ? ? ? ? ? ? ?return self.__dict__[attr_name] > > I think you want setattr() here - __dict__ is an implemetation detail > - classes with __slots__ for instance don't have a __dict__. ?I'd > probably do this Oh my, I did not know that. __slots__?? Something new I got to understand. But you are right. thanks! > > ? ? ? ? ? ? ? ? ? ?for k, v in zip(("I1", "Q1", "I2", "Q2"), bytes_to_data(buf)): > ? ? ? ? ? ? ? ? ? ? ? ?setattr(self, k, v) > ? ? ? ? ? ? ? ? ? ?return object.__getattr__(self, attr_name) > And perhaps even more readable (how I do it now, no need to call __getattr__ for an attribute, whcih is already there): ... for attr, value in zip(cls.data_attr_names, bytes_to_data(buf)): setattr(self, attr, value) return getattr(self, attr_name) > :-) > > I would probably factor out the contents of the if statement into a > seperate method, but that is a matter of taste! Agreed. I thought about that myself for better code readability. As a final comment, I have actually refacted the code quite a bit as I have to do this ...OnDemand trick for several classes, which have different data attributes with different names. In this process I have actaully managed to isolate all the ...OnDemand stuff in an abstract PayloadOnDemand class I can now use this "decorator-like"/helper class to very easily make an ...OnDemand variant of a class by just doing multiple inheritance - no implementation: class PayloadBaconAndEggsOnDemand(PayloadOnDemand, PayloadBaconAndEggs): pass I guess this somewhat resembles the decorator approach - I just could not figure out how to kake a general purpose decorator. For this to actually work the "instant" PayloadBaconAndEggs class simply has to define and implement a few class attributes and static utility functions for the unpacking. -- Slaunger From asteinarson at gmail.com Sat Dec 6 16:47:26 2008 From: asteinarson at gmail.com (ats) Date: Sat, 6 Dec 2008 13:47:26 -0800 (PST) Subject: Source code generation using Python Message-ID: <82098706-978f-4920-ac75-57ef3573ac44@x38g2000yqj.googlegroups.com> Hello, This is my first posting to a Python group (and I'm starting with Python seriously only now) , so bear with me if I make some mistakes. I want to generate 3 different versions of a C++ source code, basically injecting different flavours of inline assembler depending on target compiler/CPU. Code generation should be integrated into a 'master source file' which is the processed and generates the right code for GCC / MSVC or other cases. Something like: int FastAdd( int t1, int t2 ){ int r; ##if USE_INLINE_ASM #ARG( eax, "t1") #ARG( ebx, "t2") #ASM( "add", ebx, eax ) #RES( eax, "r" ) ##else r = t1+t2; ##endif return r; } On processing, given constant USE_INLINE_ASM (or not) the right code is generated to a target file, which goes into the build process. I was looking for packages that can do this and came up with some candidates: - "empy" - http://www.alcyone.com/pyos/empy/ - It looks like it could do the job, but appears non-maintained since 2003. - "Cheetah" - Looks like more of a tool to do fix replacements of code snippets. There is some logic going on in the "ARG", "ASM" and "RES" sections, so I need to link code generation with true Python functions. The situation is really quite similar to HTML/PHP except, here we would have C++/Python. Any suggestions? Thanks, //Arne S. From bthayre at physics.ucsd.edu Thu Dec 11 18:38:14 2008 From: bthayre at physics.ucsd.edu (Robocop) Date: Thu, 11 Dec 2008 15:38:14 -0800 (PST) Subject: list organization question References: Message-ID: <3040d38a-cc25-41ea-a472-281072137044@c36g2000prc.googlegroups.com> On Dec 11, 3:31?pm, Arnaud Delobelle wrote: > Robocop writes: > > I have a list of objects, each object having two relevant attributes: > > date and id. ?I'd like not only organize by id, but also by date. > > I.e. i would like to parse my list into smaller lists such that each > > new mini-list has a unique date, but consists of only objects with a > > specific id. ?Are there any handy imports i could use to accomplish > > something like this? ?I'm relatively new to python and as such don't > > know all of the preloaded functions at my disposal. ?Thanks for any > > help in advance, the community here is always ridiculously helpful. > > Look at itertools.groupby. > > E.g. > > from itertools import groupby > > data = [ my objects ] > > def getdate(x): return x.date > > by_date = {} > for date, objs in groupby(sorted(data, key=getdate), getdate): > ? ? by_date[date] = list(objs) > ? ? # list(objs) is the list of all objects in data whose date is date > > I'm sorry if this is a bit terse... > > -- > Arnaud This looks to be exactly what i'm looking for! I will try and implement this immediately, thank you all for the suggestions. From temotor at gmail.com Thu Dec 18 18:04:14 2008 From: temotor at gmail.com (Sergey Shepelev) Date: Thu, 18 Dec 2008 15:04:14 -0800 (PST) Subject: Python lex settings Message-ID: <0dfeb0c3-a524-4a72-aafd-4b88b71ff16c@w39g2000prb.googlegroups.com> Hello. I'm trying to make almost-Python source to Erlang source translation tool. Are there ready ply.lex settings for parsing python source? From paul at boddie.org.uk Thu Dec 18 16:13:56 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 18 Dec 2008 13:13:56 -0800 (PST) Subject: psycopg2 and large queries References: Message-ID: <762eed9d-4646-4c62-a9b7-d57d47f03b9e@e1g2000pra.googlegroups.com> On 18 Des, 19:09, Steve Holden wrote: > > Hmm, pypgsql doesn't provide a 2.5 Windows installer. I take it you > aren't a Windows user ... ? Well, there are plenty of PostgreSQL modules around these days, and even if pyPgSQL isn't suitable, I'm sure that there must be one which can be made to work on Windows and to support server-side cursors. See here for more: http://wiki.python.org/moin/PostgreSQL Paul From skip at pobox.com Thu Dec 4 16:49:46 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 4 Dec 2008 15:49:46 -0600 Subject: RELEASED Python 3.0 final In-Reply-To: <20081204204525.414db889@usenot.de> References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> Message-ID: <18744.20602.92835.175628@montanaro-dyndns-org.local> Andreas> Whenever has it been a pythonic ideal to "not allow" stuff? You Andreas> get warnings. Everything else is up to you. It's more than warnings. With properly crafted combinations of spaces and tabs you can get code which looks like it has a certain indentation to the human observer but which looks like it has different indentation (and thus different semantics) to the byte code compiler. There is often no warning. Skip From iNkOhSnPaAtMon at free.fr Mon Dec 8 09:47:13 2008 From: iNkOhSnPaAtMon at free.fr (Pascal) Date: 08 Dec 2008 14:47:13 GMT Subject: [Py2exe-users] py2exe 0.6.9 released References: <49216608$0$9585$426a74cc@news.free.fr> Message-ID: <493d3371$0$15192$426a74cc@news.free.fr> On Mon, 17 Nov 2008 12:39:36 +0000, Pascal wrote: > On Sun, 16 Nov 2008 21:23:59 -0500, Chris Spencer wrote: > >> After I "compile" my program with py2exe 0.6.9 with Python 2.6, I'm >> still getting the "Application Did Not Initialize Properly" error >> dialog whenever I run my code. What am I doing wrong? > > I have exactly the same problem. > I have tried just anything I could think of to no avail : Copied the 3 > msvc_90.dll to the system32 subdir of Windows, to the directory of my > application, reinstalled the whole Microsoft Visual C++ 2008 > Redistributable Package, embedded the manifest data into the exe or kept > it in a .manifest file... > Could not make it work. Always got the "Application Did Not Initialize > Properly" message. > I'm with Windows XP SP3. I tried all this on 2 different systems and I > got the same results. I think I narrowed down a little bit the problem. It's not the common one when the msvc_90.dll are not located, though the result is similar. The problem is when you try to generate at least 2 exe in one setup (with 2 scripts specified in the "windows" command of the setup). This works OK with py2exe 0.6.9 for Python 2.5, but fails with Python 2.6 (and 2.6.1). None of the generated exe can be started. When I compare the content of library.zip in both versions, this file doesn't contain any .pyc for the scripts you want to generate an exe for with Python 2.5, but always contains a .pyc for one of the scripts you want to generate an .exe for with Python 2.6. Don't know if it's a clue for finding a fix. I have tested many ways to figure this out but I can't find any solution for the moment so I'm sticking with Python 2.5. From google at mrabarnett.plus.com Mon Dec 8 17:56:31 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 08 Dec 2008 22:56:31 +0000 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: <493DA61F.7020207@mrabarnett.plus.com> Terry Reedy wrote: > Rasmus Fogh wrote: > >> For my personal problem I could indeed wrap all objects in a wrapper with >> whatever 'correct' behaviour I want (thanks, TJR). It does seem a bit > > I was not suggesting that you wrap *everything*, merely an adaptor for > numpy arrays in whatever subclass and source it is that feeds them to > your code. It is fairly unusual, I think, to find numpy arrays 'in the > wild', outside the constrained context of numerical code where the > programmer uses them intentionally and hopefully understands their > peculiarities. > >> much, though, just to get code like this to work as intended: >> alist.append(x) >> print ('x is present: ', x in alist) > > Even if rich comparisons as you propose, the above would *still* not > necessarily work. Collection classes can define a __contains__ that > overrides the default and that can do anything, though True/False is > recommended. > If you have a list of results and you want to see whether one of them is Nan then the obvious way is "Nan in results", but __contains__ uses __eq__ and Nan == Nan returns False, so "Nan in results" returns False. Hmm... "Nan is Nan" returns True, so if there was a version of __contains__ which used "is" then "Nan in results" would return True. Perhaps "Nan is in results"? Or would that be too confusing, ie "in" vs "is in"? > As best I can think of at the moment, the only things you can absolutely > depend on is that builtin id(ob) will return an int, that 'ob1 is ob2' > (based in id()) will be True or False, and that builtin type(ob) will be > a class (at least in 3.0, not sure of 2.x). The names can be rebound > but you can control that within the module you write. > I wonder whether there could be some syntactic sugar which would wrap try...except... around an expression, eg "except(foo(), False)", which would return False if foo() raised an exception, otherwise return the result of foo(). > This is what I meant when I said that 'generic' nearly always needs to > be qualified to something like 'generic for objects that meet the > interface requirements'. Every function has that precondition as part > of its implied contract. Your code has an interface requirement that 'x > in y' not raise an exception. An x,y pair that does it outside its > contract. > From pacsciadmin at gmail.com Sun Dec 7 21:24:08 2008 From: pacsciadmin at gmail.com (pacsciadmin at gmail.com) Date: Sun, 7 Dec 2008 18:24:08 -0800 (PST) Subject: Infinite hangup when using CGI sys.stdin.read() Message-ID: I maintain a CGI framework named PyTin, and while previously the developer was only allowed to access GET and POST by cgi.FieldStorage. I'm trying to add code to my request gatherer that looks like: 1. request.rawpost = StringIO() # Just normal StringIO 2. request.rawpost.write(sys.stdin.read()) 3. request.rawpost.seek(0) 4. request.fields = cgi.FieldStorage(fp=request.rawpost) 5. request.rawpost.seek(0) Obviously, my actual code doesn't have the line numbers. I'm testing it out on the CGIHTTPRequestHandler with BaseHTTPServer, and whenever my test script reaches line 2, it hangs up. It doesn't spit out a traceback, or stop in less than a minute, whenever I use sys.stdin.read(). Can anyone explain what is going on? Regards, LeafStorm BDFL: Pacific Science From bruno.42.desthuilliers at websiteburo.invalid Thu Dec 4 08:26:02 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 04 Dec 2008 14:26:02 +0100 Subject: python an sqlite objects In-Reply-To: References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <4936bceb$0$16783$426a34cc@news.free.fr> <4936dab7$0$9107$426a74cc@news.free.fr> <493792a9$0$16763$426a74cc@news.free.fr> Message-ID: <4937da56$0$10438$426a74cc@news.free.fr> skip at pobox.com a ?crit : > Bruno> If you serialize a dict, you'll obviously get a dict back. Note > Bruno> that the point of json is *not* to replace pickle. json is a > Bruno> *data* serialization format meant to represent "basic" types > Bruno> (dicts, lists, strings and numbers) in human readable and > Bruno> (mostly) language-agnostic way. > > Right, which makes it unsuitable as a general object serialization format. which makes it unsuitable as a full-fledged generic Python serialization format, at least OOTB (Django knows how to get model objects back from json, and I think one could write a more generic json serializer / deserializer with about the same limitations as pickle). > The OP was unclear what he meant when he asked about storing Python objects > in a sqlite database. In the general case json doesn't cut it. I indeed assumed (possibly wrongly) that this would be enough, given the use of a relational database. But as I said: > Bruno> If you want a Python object store, you'll be better looking at > Bruno> ZODB, Durus or friends. -- > > Or SQLAlchemy or SQLObject. Not the same thing. From ldo at geek-central.gen.new_zealand Wed Dec 3 06:09:39 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 04 Dec 2008 00:09:39 +1300 Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> Message-ID: In message <21ddcf54-e64c-411e-835f-a2d06644dfa0 at x38g2000yqj.googlegroups.com>, Astley Le Jasper wrote: > The trouble is that obviously I get no console when using crontab so > can't see any traceback. Cron normally sends you mail if a cron task generated any output (this should include error messages). From __peter__ at web.de Sat Dec 13 09:44:45 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 13 Dec 2008 15:44:45 +0100 Subject: Shorter tracebacks References: Message-ID: bearophileHUGS at lycos.com wrote: > When I write recursive code in Python I sometimes go past the maximum > allowed stack depth, so I receive a really long traceback. The show of > such traceback on my screen is very slow (despite a CPU able to > perform billions of operations each second). So I think I'd like > something to shorten them. > I am thinking about something like: > from __future__ import short_traceback > > That allows me to see only the first and last parts of the stack > trace, and skips the (generally very redundant) middle part. > > Note that generally using sys.setrecursionlimit(limit) to set a > smaller limit isn't good, because I may need a big depth anyway. That's none of __future__'s business, I think. Python offers a hook which you can modify: >>> import sys, traceback >>> from functools import partial >>> sys.excepthook = partial(traceback.print_exception, limit=5) >>> x = 0 >>> def f(): ... global x ... x += 1 ... f() ... >>> f() Traceback (most recent call last): File "", line 1, in File "", line 4, in f File "", line 4, in f File "", line 4, in f File "", line 4, in f RuntimeError: maximum recursion depth exceeded >>> x 999 Peter From nick at craig-wood.com Mon Dec 1 06:30:44 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 01 Dec 2008 05:30:44 -0600 Subject: Do more imported objects affect performance References: Message-ID: Rafe wrote: > On Dec 1, 7:26?am, "Filip Gruszczy?ski" wrote: > > I have following question: if I use > > > > from module import * > > > > instead > > > > from module import Class > > > > am I affecting performance of my program? I believe, that all those > > names must be stored somewhere, when they are imported and then > > browsed when one of them is called. So am I putting a lot of "garbage" > > to this storage and make those searches longer? > > Why use it if you don't need it? Your post implies a choice and the > '*' import can really make things muddy if it isn't actually necessary > (rare). Why not just import the module and use what you need? It is > way easier to read/debug and maintains the name-space. Importing the module is actualy slower... If you import the name into your namespace then there is only one lookup to do. If you import the module there are two. $ python -m timeit -s 'from timeit import Timer' 'Timer' 10000000 loops, best of 3: 0.0784 usec per loop $ python -m timeit -s 'import timeit' 'timeit.Timer' 1000000 loops, best of 3: 0.243 usec per loop I'm not suggestion you should ever use "from module import *" only ever import the things you actually need, eg "from module import MyClass, my_function" And here is the test again, actually calling something with the same difference in execution speed :- $ python -m timeit -s 'from os import nice' 'nice(0)' 1000000 loops, best of 3: 1.21 usec per loop $ python -m timeit -s 'import os' 'os.nice(0)' 1000000 loops, best of 3: 1.48 usec per loop -- Nick Craig-Wood -- http://www.craig-wood.com/nick From anthony.tolle at gmail.com Mon Dec 8 12:01:18 2008 From: anthony.tolle at gmail.com (anthony.tolle at gmail.com) Date: Mon, 8 Dec 2008 09:01:18 -0800 (PST) Subject: Guido's new method definition idea References: <014a071a$0$20670$c3e8da3@news.astraweb.com> <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> Message-ID: On Dec 6, 4:15?pm, Carl Banks wrote: > On Dec 6, 12:47?am, "Patrick Mullen" wrote: > > > Could I do something like this: > > > def a.add(b): return a+b > > > Outside of a class? ?Of course then that makes you think you could do > > 5.add(6) or something craaaazy like that. ?(I mean, you can do > > (5).__add__(6) but that's something else entirely) > > I'd be inclined to think that this defines an instancemethod on an > existing object a. ?In other word, I'd read the following two lines as > more or less equivalent. > > def a.add(b): return a+b > > a.add = lambda b: a+b > > Just as the following are equivalent: > > def foo(): return bar > > foo = lambda: bar > > I had been -0 on this, but now I think I'm -1. This brings up another question, what would one use when referencing method names inside the class definition?: class C: def self.method(arg): self.value = arg def self.othermethod(arg): self.value = arg # do this? funcs = (self.method, self.othermethod) # or this? funcs = (method, othermethod) On another related note, I would be interested in seeing this syntax adopted for the very purpose Carl hinted at... Normally, if I'm defining a nested function that needs to be stored as an object attribute, I have to use a dummy name, like the following: class C: def createfunc(self, arg): def _dummy(arg): return arg + 1 self.func = _dummy It would be nice to be able to do the following instead: class C: def createfunc(self): def self.func(arg): return arg + 1 Or, after the class definition is done, to extend it dynamically: def C.method(self, arg): self.value = arg ...which would be the equivalent of the following: def method(self, arg): self.value = arg C.method = method Since functions are first-class objects, it seems perfectly reasonable to me. From steve at REMOVE-THIS-cybersource.com.au Sun Dec 28 09:31:11 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Dec 2008 14:31:11 GMT Subject: sys.stdout.write()'s bug or doc bug? References: Message-ID: <016784c1$0$6988$c3e8da3@news.astraweb.com> On Sun, 28 Dec 2008 02:37:55 -0800, Qiangning Hong wrote: >> > So, my question is, as sys.stdout IS a file object, why it does not >> > use its encoding attribute to convert the given unicode? An >> > implementation bug? A documenation bug? >> >> hmm I always thought "sys.stdout" is a "file-like object" not that it >> IS a file. > > In my original post, I have figured out that sys.stdout IS a file, by > using type() function. And isinstance() function tells the same: > > Python 2.5.2 (r252:60911, Dec 18 2008, 12:39:19) [GCC 4.2.1 (Apple Inc. > build 5564)] on darwin Type "help", "copyright", "credits" or "license" > for more information. >>>> import sys >>>> type(sys.stdout) is file > True >>>> isinstance(sys.stdout, file) > True > > So, sys.stdout SHOULD do what the doc says, otherwise there is a bug > either in implementation of sys.stdout, or in the documentation of file. The documentation says: file.encoding The encoding that this file uses. When Unicode strings are written to a file, they will be converted to byte strings using this encoding. In addition, when the file is connected to a terminal, the attribute gives the encoding that the terminal is likely to use (that information might be incorrect if the user has misconfigured the terminal). The attribute is read-only and may not be present on all file-like objects. It may also be None, in which case the file uses the system default encoding for converting Unicode strings. New in version 2.3. http://docs.python.org/library/stdtypes.html#file.encoding And I agree that sys.stdout is a file. Using Python 2.6: >>> type(sys.stdout) I can confirm the behaviour you report: >>> sys.stdout.encoding 'UTF-8' >>> u = u"\u554a" >>> print u ? >>> sys.stdout.write(u) Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\u554a' in position 0: ordinal not in range(128) But if you explicitly convert the string, it works: >>> sys.stdout.write(u.encode('utf-8')) ? I agree that this appears to be a bug, either of the write() method or the documentation. -- Steven From google at mrabarnett.plus.com Thu Dec 18 17:52:11 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 18 Dec 2008 22:52:11 +0000 Subject: Which sparse matrix package? In-Reply-To: References: <20081218231851.70dd91e2@Schlamber.localdomain> Message-ID: <494AD41B.3090501@mrabarnett.plus.com> James Mills wrote: > On Fri, Dec 19, 2008 at 8:18 AM, Martin Manns wrote: >> Hi: > > Hi, > >> I am writing a spreadsheet application in Python > > What's wrong with pyspread ? > > [ ... snip ... ] > >> The dict that I tried out is of the type: >> >> {(1,2,3): "2323", (1,2,545): "2324234", ... } >> >> It is too slow for my application when it grows. One slicing operation >> with list comprehensions takes about 1/2 s on my computer for 1E6 >> elements. > > Let me get this straight. > It's taking 0.5s to slice your matrix > of 1E7 (10000000.0 rows/columns) > > Are you mad ? This is TEN Millions and you > required it faster than 0.5s ? > No, 1E6, or ONLY 1 million. :-) > Am I missing something here ? > Would a matrix of matrices work better, ie a supermatrix where each element is either a submatrix of cells or None if the submatrix is empty? How much memory it would save would depend on how sparse the matrix is. From prologic at shortcircuit.net.au Mon Dec 8 01:09:13 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Dec 2008 16:09:13 +1000 Subject: A question about reference in Python. In-Reply-To: <493CB003.3080209@gmail.com> References: <493CB003.3080209@gmail.com> Message-ID: Hi, This is really really really pointless code and a really really pointless exercise, but nonetheless, here is a very very basic and minimal implementation of what you're expecting. This should almost *never* be done in Python! Python is a superior dynamic programming language, but it's NOT C! Here goes: jmills at atomant:~/tmp$ ./list.py >>> x[0] 0 >>> x[1] 1 >>> x[2] 2 >>> x[3] 3 >>> x[4] Traceback (most recent call last): File "", line 1, in File "./list.py", line 36, in __getitem__ return node.value AttributeError: 'NoneType' object has no attribute 'value' >>> jmills at atomant:~/tmp$ And the code: #!/home/jmills/bin/python -i class Node(object): value = None prev = None next = None def __init__(self, value, prev=None, next=None): self.value = value self.prev = prev self.next = next class List(object): data = None def __init__(self, *seq): if seq: first = prev = node = None for x in seq: if not first: first = Node(x) prev = node = first else: node = Node(x, prev) prev.next = node prev = node self.data = first def __getitem__(self, x): node = self.data for i in xrange(x): node = node.next return node.value x = List(0, 1, 2, 3) Notes: I have not implemented any error checking whatsoever. I have not implemented any of your normal list operations whatsoever (except 1). __getitem__. Have fun, cheers James On Mon, Dec 8, 2008 at 3:26 PM, Group wrote: > Hello, I'm studying algorithom. For concentrating on the question itself, I > intend to use Python to implement the algorithoms. > > Now, I want to write a Red-Black Tree, and a List structure. In C/C++, I can > use pointers to refer to children notes (or next notes). But, in Python, > how > can I do it? Except the sequence, I know not any way. > > You'd better help me understan how can I transform the following C code into > Python: > > /* a List */ > struct { > int data; > int *next; > int *prev; > } > > That's all. Thanks! > Kermit > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From bkamrani at gmail.com Thu Dec 4 04:26:13 2008 From: bkamrani at gmail.com (bkamrani at gmail.com) Date: Thu, 4 Dec 2008 01:26:13 -0800 (PST) Subject: performance question: dictionary or list, float or string? References: <434bf4e3-54f4-4e15-b8b0-510a988f25b8@z1g2000yqn.googlegroups.com> Message-ID: <904a19e9-3800-4d61-aea0-4bdabc0674fa@j32g2000yqn.googlegroups.com> Matt, really thanks for your comments! Even thogh it was not a direct answer to my questions, I like your coding style very much and I think you have a good point. About the number of line in the file, because I get that info from another in advance. Therefore I thought it could be hard coded. BTW, could you recommend a book or a note on points you have mentioned so that I can learn more like that? Thanks, /Ben On Dec 2, 8:37?pm, Matimus wrote: > On Dec 2, 3:51?am, bkamr... at gmail.com wrote: > > > > > I forgot to mention that I did a simple timeit test which doesn't > > show > > significant runtime difference 3.5 sec for dictionary case and 3.48 > > for > > list case. > > > def read_as_dictionary(): > > ? ? fil = open('myDataFile', 'r') > > ? ? forces = {} > > ? ? for region in range(25): > > ? ? ? ? forces[region] = {} > > > ? ? for step in range(20000): > > ? ? ? ? for region in range(25): > > ? ? ? ? ? ? line = fil.next(); spl = line.split() > > ? ? ? ? ? ? forces[region] [step] = spl > > > def read_as_list(): > > ? ? fil = open('myDataFile.txt', 'r') > > ? ? forces = [] > > ? ? for region in range(25): > > ? ? ? ? forces.append([]) > > > ? ? for step in range(20000): > > ? ? ? ? for region in range(25): > > ? ? ? ? ? ? line = fil.next(); spl = line.split() > > ? ? ? ? ? ? forces[region].append(spl) > > > Cheers, > > /Ben > > There really isn't enough information to recommend a particular > direction. A dictionary doesn't seem appropriate for > this information though. Also, you are hard coding the step range to > 20000. Is that the number of lines in the file? That isn't really a > safe way to do it. > > # this is just bad style in python: > line = fil.next(); spl = line.split() > # better written > spl = fil.next().split() > > I would just do it this way: > > def read_as_list(data, regions=25, maxlines=20000): > ? ? # If data is a filename, open the file. If it is a file > ? ? # object or any sequence of 'lines' it should just work. > > ? ? file_opened = False > ? ? if isinstance(data, basestring): > ? ? ? ? data = open(data, 'r') > ? ? ? ? file_opened = True > > ? ? forces = [[] for _ in xrange(regions)] > ? ? try: > ? ? ? ? for i, line in data: > ? ? ? ? ? ? if i == maxlines: > ? ? ? ? ? ? ? ? break > ? ? ? ? ? ? forces[i % 25].append(line.split()) > ? ? finally: > ? ? ? ? if file_opened: > ? ? ? ? ? ? f.close() > ? ? return forces > > Matt From jarausch at igpm.rwth-aachen.de Tue Dec 2 04:34:18 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Tue, 02 Dec 2008 10:34:18 +0100 Subject: Is it safe to modify the dict returned by vars() or locals() In-Reply-To: References: <4934508b$0$2861$ba620e4c@news.skynet.be> Message-ID: <4935011A.9080406@igpm.rwth-aachen.de> Chris Rebert wrote: > On Mon, Dec 1, 2008 at 1:01 PM, Helmut Jarausch wrote: >> Hi, >> >> I am looking for an elegant way to solve the following problem: >> >> Within a function >> >> def Foo(**parms) >> >> I have a list of names, say VList=['A','B','C1'] >> and I like to generate abbreviation >> _A identical to parms['A'] > > Could you explain what you mean by that? Your sample code doesn't seem > to do any "abbreviation"... > Otherwise I don't see why you don't just have a proper parameter list. In my application parms contains field names of an html form iff these fields have been modified. I'd like to use the short name _A instead of the longer expression parms['A'] -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From clp at rebertia.com Wed Dec 31 08:29:36 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 31 Dec 2008 05:29:36 -0800 Subject: Pass by reference In-Reply-To: References: <529e1d98-8932-49f0-b569-85285bd50f23@p2g2000prn.googlegroups.com> Message-ID: <47c890dc0812310529i73f5c673me1810bb2ac97a1fb@mail.gmail.com> On Wed, Dec 31, 2008 at 5:04 AM, iu2 wrote: > For the 2 targets I have the variables comm1 and comm2. They are of > some class I wrote, representing many properties of the communication, > including the IP address. > There is one function that sends data, and it receives a commX var > (comm1 or comm2) as the means for sending the data. > Before sending the data the function needs to initilze commX (if it is > still None), or creating it a new, if it sees that the IP for that > target has changed. Based on the naming alone (though further corroborated by your details), I can recommend that you use a dictionary instead of variables for the commX-s. Basically, remove the comm1, comm2, etc variables and instead do (you might want to use a defaultdict or list rather than a plain dict): comms = {1 : MyComm(...), 2 : None} > > Something like this: > > def send_data(comm, data, current_ip_from_gui): > if comm is None: > # I want to assign comm a new MyComm > elif comm.ip != current_ip_from_gui: > # I want to re-assign a new MyComm that uses the new IP > comm.socket.SendTo(comm.addr, data) # eventually send the data Instead that becomes: def send_data(comms, id_num, data, current_ip_from_gui): if comms[id_num] is None: comms[id_num] = MyComm(...) elif comms[id_num].ip != current_ip_from_gui: comms[id_num] = MyComm(current_ip_from_gui, ...) comm = comms[id_num] comm.socket.SendTo(comm.addr, data) # eventually send the data > But I guess I can achieve this using a class holding my vars, maybe > like this: That's similar to what I'm suggesting, but mine has less indirection. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From lie.1296 at gmail.com Tue Dec 9 17:10:19 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 9 Dec 2008 22:10:19 +0000 (UTC) Subject: Is 3.0 worth breaking backward compatibility? References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> <1228857008.4109.38.camel@brotherus.rdu.redhat.com> Message-ID: On Tue, 09 Dec 2008 16:10:08 -0500, Albert Hopkins wrote: > On Tue, 2008-12-09 at 20:56 +0000, Lie Ryan wrote: >> Actually I noticed a tendency from open-source projects to have slow >> increment of version number, while proprietary projects usually have >> big >> version numbers. >> >> Linux 2.x: 1991 Python 3.x.x: 1991. Apache 2.0: 1995. OpenOffice.org >> 3.0: >> acquired by Sun at 1999. GIMP 2.x: 1995. Wine 1.x: 1993. >> > One exeption would be GNU Emacs 22: 1984, but according to Wikipedia: > > "Versions 2 to 12 never existed. Earlier versions of GNU Emacs > had been numbered "1.x.x", but sometime after version 1.12 the > decision was made to drop the "1", as it was thought the major > number would never change." > > So you can think of Emacs 22 as being 1.22. most odd is TeX an METAFONT: TeX has an idiosyncratic version numbering system. Since version 3, updates have been indicated by adding an extra digit at the end, so that the version number asymptotically approaches ?. The current version is 3.1415926. This is a reflection of the fact that TeX is now very stable, and only minor updates are anticipated. TeX developer Donald Knuth has stated that the "absolutely final change (to be made after my death)" will be to change the version number to ?, at which point all remaining bugs will become permanent features. In a similar way, the version number of METAFONT asymptotically approaches e. From antoine at vo.lu Sat Dec 6 10:56:41 2008 From: antoine at vo.lu (Antoine De Groote) Date: Sat, 06 Dec 2008 16:56:41 +0100 Subject: Guido's new method definition idea In-Reply-To: References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> Message-ID: Russ P. wrote: > On Dec 6, 1:02 am, Antoine De Groote wrote: >> Allowing "$" as a substitute for "self" wouldn't require this new syntax. >> >> class C: >> def method($, arg): >> $.value = arg >> >> I'm strongly against this. This looks ugly and reminds me of Perl and >> Ruby. (I don't have anything against these languages, but there's a >> reason I use Python). > > It looks "ugly" simply because it is new to you. Once you get used to > it, I'll bet it will look fine. And resemblance to another language is > not a very good reason to reject it. I would not say that "ugly" and "new" (or "unused" for that matter) are the same. There are going to be a number of things in Python 3 that are new and to which one is not used, but they certainly are not ugly. Ugly is of course a matter of taste, I'll give you that, but to me it's still ugly. From joe at strout.net Mon Dec 15 10:29:37 2008 From: joe at strout.net (Joe Strout) Date: Mon, 15 Dec 2008 08:29:37 -0700 Subject: %s place holder does not let me insert ' in an sql query with python. In-Reply-To: <1229348763.31093.38.camel@krishna-laptop> References: <1229345178.31093.24.camel@krishna-laptop> <1229348763.31093.38.camel@krishna-laptop> Message-ID: <764E2489-284E-4064-B7B3-8736E41969B2@strout.net> On Dec 15, 2008, at 6:46 AM, Krishnakant wrote: > in this case, I get a problem when there is ' in any of the values > during insert or update. That's because ' is the SQL string literal delimiter. But any SQL- compliant database allows you to "escape" an apostrophe within a string literal by doubling it. So for each of your values, just do: value = value.replace("'", "''") before stuffing them into your INSERT or UPDATE statement. (If these values come from the user, and especially if they come over the network, then you probably want to do a few other replacements; google "SQL injection" for details.) Note that I'm not familiar with the cursor.execute binding that RDM pointed out, so that may provide a better solution... but the above should work. Best, - Joe From bsk16 at case.edu Mon Dec 22 23:09:05 2008 From: bsk16 at case.edu (Ben Kaplan) Date: Mon, 22 Dec 2008 23:09:05 -0500 Subject: Python's popularity In-Reply-To: <7c02eb33-a919-4481-8eda-76062729f233@k19g2000yqg.googlegroups.com> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> <7c02eb33-a919-4481-8eda-76062729f233@k19g2000yqg.googlegroups.com> Message-ID: <5590A15E-D3BC-4094-A3B5-5CCE2717F8AC@case.edu> On Dec 22, 2008, at 9:51 PM, r wrote: > On Dec 22, 7:34 pm, Steven D'Aprano > wrote: >> On Mon, 22 Dec 2008 10:01:21 -0800, r wrote: >>> Walter, >>> I just look at the stats for comp.lang.python, and i am 9th place >>> for >>> most post this month. >> >> And about 9,000th place for useful information. >> >> -- >> Steven > > I think you missed my point Steven, I was in no way proud of the fact > of my 9th place rating. It just proves my point to the small following > of this group. And frankly makes me feel bad. That's just because most of us don't say anything unless we have something useful to say. We prefer to let the experts answer the questions, but we read the threads so we can benefit from them. Steven was pointing out that the number of posts you made has nothing to do with the overall audience of this list or how much real content you are contributing From saju.pillai at gmail.com Thu Dec 11 05:41:21 2008 From: saju.pillai at gmail.com (saju.pillai at gmail.com) Date: Thu, 11 Dec 2008 02:41:21 -0800 (PST) Subject: Equivalent of 'wget' for python? References: Message-ID: On Dec 11, 3:36?pm, "saju.pil... at gmail.com" wrote: > On Dec 11, 2:36?pm, hrishy wrote: > > > Hi > > > Please excuse my OOP but is my understanding correct > > > urllib.urlretrieve(url_of_zip_file,destination_on_local_filesystem) > > > is urllib --->Static Class on which the method urlretrieve method is invoked ? > > No urllib is a "method". Use type(obj) to find out what python thinks typo c/method/module > the "type" of that object is. Note that "object" here is not meant in > the same sense as the OOP definition. > > > > > In that case what does the python 3.0 version mean > > > import urllib.request > > urllib.request.urlretrieve(url, local_file_name) > > > urllib -->static class > > request -->method > > urlretrieve--> what is this then ? > > A 'function'. urllib.request.urlretrieve is the fully qualified name > of the function urlretrieve. In other words urlretrieve lives in the > urllib.request namespace. > > -srp > > > > > regards > > Hrishy > > > --- On Mon, 8/12/08, Jerry Hill wrote: > > > > From: Jerry Hill > > > Subject: Re: Equivalent of 'wget' for python? > > > To: python-l... at python.org > > > Date: Monday, 8 December, 2008, 5:54 PM > > > On Mon, Dec 8, 2008 at 11:53 AM, r0g > > > wrote: > > > > urllib.urlretrieve(url_of_zip_file, > > > destination_on_local_filesystem). > > > > In python 3.0, that appears to be: > > > > import urllib.request > > > urllib.request.urlretrieve(url, local_file_name) > > > > -- > > > Jerry > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > From deets at nospam.web.de Thu Dec 11 18:55:30 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 12 Dec 2008 00:55:30 +0100 Subject: Best way of debigging a C extension In-Reply-To: References: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> <6qdjt7Fc1fg0U1@mid.uni-berlin.de> Message-ID: <6qdnjjFc3ic3U1@mid.uni-berlin.de> Christian Heimes schrieb: > Diez B. Roggisch schrieb: >> I never tried this on windows - but what happens if you start python >> inside GDB, and then set breakpoints inside your extension? >> >> This works flawlessly for me under *nix. >> >> The debug-build of python isn't needed for this - and I doubt a bit that >> it helps you much, as being inside the interpreter & getting detailed >> information isn't your goal - you want to see your extensions functions, >> what parameters they get and so on. > > It doesn't work well with all debugging symbols stripped and with -O2 > optimized code. The compiler rearranges the code. You could try to > compile your own code with different compiler arguments. I don't know if > that's easily possible on Windows with Python 2.5. As I said - as long as you don't care about the python debug code itself, it works pretty well. Usually, the problems are within your extension, which you have the full control over regarding symbols & optimization settings. Diez From barry at python.org Wed Dec 3 21:24:23 2008 From: barry at python.org (Barry Warsaw) Date: Wed, 3 Dec 2008 21:24:23 -0500 Subject: RELEASED Python 3.0 final In-Reply-To: <880dece00812031813t78ec560cy69dd3710fbd4c2a9@mail.gmail.com> References: <880dece00812031813t78ec560cy69dd3710fbd4c2a9@mail.gmail.com> Message-ID: <46FC4EDF-A0A6-4310-A854-4CB5F7A791EE@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Dec 3, 2008, at 9:13 PM, Dotan Cohen wrote: > On this page: > http://www.python.org/download/releases/3.0/ > > The text "This is a proeuction release" should probably read "This is > a production release". It would give a better first impression :) Fixed, thanks! - -Barry -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Darwin) iQCVAwUBSTc/WHEjvBPtnXfVAQL8TwP+M2Ryv7WY36ICEvzGU4EzlRG/gI4MolQe cD8DJUJfQuR6INTot/t7vTcL8oDHq7q9OHbfvd3jmSwH/ZytsMz2OvJUYlKDQjwG BcQRpioprcesoU6cufSmKAUiUP+L0RTAMmT0WDbbeCzzMZRq3Humd4Zs43nL26NT uFb83Dk6yWA= =qPjn -----END PGP SIGNATURE----- From wiggly at wiggly.org Wed Dec 10 11:48:40 2008 From: wiggly at wiggly.org (Nigel Rantor) Date: Wed, 10 Dec 2008 16:48:40 +0000 Subject: To Troll or Not To Troll (aka: "as" keyword woes) In-Reply-To: References: <20081205163107.1815df40@usenot.de> Message-ID: <493FF2E8.3080404@wiggly.org> James Stroud wrote: > Andreas Waldenburger wrote: >> Is it me, or has c.l.p. developed a slightly harsher tone recently? >> (Haven't been following for a while.) > > Yep. I can only post here for about a week or two until someone blows a > cylinder and gets ugly because they interpreted something I said as a > criticism of the language and took it personally by extension. Then I > have to take a 4 month break because I'm VERY prone to > reciprocating--nastily. I think its a symptom of the language's > maturing, getting popular, and a minority fraction* of the language's > most devout advocates developing an egotism that complements their > python worship in a most unsavory way. > > I wish they would instead spend their energy volunteering to moderate > this list and culling out some of the spam. > > *No names were mentioned in the making of this post. I joined this list some time ago, I am not a regular python user. I have maintained my list subscription because when I'm bored the flames here are very entertaining. I don't think I need to mention specifics really. Oh, and the weekly thread about immutable default arguments is a cracker...more please. n From gandalf at shopzeus.com Tue Dec 30 09:35:37 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 30 Dec 2008 15:35:37 +0100 Subject: Python list's mail server in DNSBL ? In-Reply-To: <495A2957.6090805@holdenweb.com> References: <495A2825.4070000@shopzeus.com> <495A2957.6090805@holdenweb.com> Message-ID: <495A31B9.6020507@shopzeus.com> Steve Holden wrote: > Laszlo: > > Read the message again. There's nothing the list admins can do about > this, you'll have to contact Postmaster at chello.at to have them remove > the blacklisting, since it's their server that's imposing it. > Maybe it is my bad English but this part: > Ask your > > Mail-/DNS-Administrator to correct HELO and DNS MX settings and to get > > removed from DNSBLs; in bogusmx.rfc-ignorant.org > > > > > > Please reply to > > if you feel this message to be in error. tells that the problem is with the MX record of python.org and/or the HELO message of the python.org smtp server. At least one of them is said to be RFC ignorant, and this is why the recipient is on the blacklist. Without making those changes, the python.org domain will not be removed from the blacklist. Changing the MX record / configuring the SMTP server needs to be done by the DNS or SMTP admin of python.org. At least I think if I ask chello.at to remove the entry, the first thing they will do is check if the changes has been made. From ronaldrdguez at gmail.com Sun Dec 21 16:46:16 2008 From: ronaldrdguez at gmail.com (Ronald Rodriguez) Date: Sun, 21 Dec 2008 13:46:16 -0800 Subject: noob trouble with IDLE Message-ID: <68f1552e0812211346i96bf18hf28dccc1f8dd1a99@mail.gmail.com> Hi, Im new to python and I've just started using Byte of Python, running the samples etc. Im using IDLE on Xp. Ok, here's the thing. A sample script makes a call to the os.system() function in order to zip some files. Everything works fine when running from the command line, but the same code fails when I try Run --> Run module on IDLE. Im using 7z to zip the files. Again, everything is OK when running from the command line. Remember, Im new to python and programming. I've done some google search without results. Maybe its just too simple :-( . Any help would be appreciated. Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mdgeorge at cs.cornell.edu Wed Dec 3 17:05:58 2008 From: mdgeorge at cs.cornell.edu (Michael George) Date: Wed, 3 Dec 2008 17:05:58 -0500 Subject: building an extension module with autotools? In-Reply-To: <4936FE6D.1000805@v.loewis.de> References: <4936FE6D.1000805@v.loewis.de> Message-ID: <493702C6.5030901@cs.cornell.edu> Martin v. L?wis wrote: >> I've tried using automake, however I'm worried about libtool not getting >> the options right while building my module. >> > > You should use python-config(1) to obtain the command line options > necessary to build and link extension modules. > > HTH, > Martin > Sweet, I think that's exactly what I wanted. Thanks! --Mike From pavlovevidence at gmail.com Wed Dec 24 15:52:02 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 24 Dec 2008 12:52:02 -0800 (PST) Subject: Doing set operation on non-hashable objects References: <3a87eb6a-13ff-4aea-8835-3a233cc6cfc4@w39g2000prb.googlegroups.com> Message-ID: <6c043bc7-19e6-4e3d-bf01-5ade35d8a90a@s1g2000prg.googlegroups.com> On Dec 24, 1:16?pm, 5lvqbw... at sneakemail.com wrote: > Hi, > > I'm writing an application which is structured roughly as follows: > > "db" is a dict, where the values are also dicts. > A function searches through db and returns a list of values, each of > which is a dict as described above. > I need to perform set operations on these lists (intersection and > union) > However the objects themselves are not hashable, and therefore can't > be in a set, because they are dicts. > I'm not sure how large each set will be, but the point is I'm trying > to avoid anything looking like an O(n^2) algorithm, so I can't just > use naive double-looping to check for intersection/union on a pair of > lists. > > The only way I can think of to do this right is to hash the dicts by > freezing them, turning them all into tuples, which can then be > hashed. ?But this is a problem because more dicts might be nested > inside. ?At any rate, I'd need to thaw them out when I'm done and turn > them back into dicts, which seems complicated and annoying, and all > this leads me to believe there is a better way. > > What I really need is a set of pointers, so at the end of the > operation I have the actual objects pointed to. ?Can I somehow use the > object IDs as set elements, then recreate a list with the actual > objects they point to? > > How do you get the object back from an ID in python? Quick and dirty way is to reference the dicts with a lightweight hashable object that uses the dict's identity. For instance: class Identity(object): def __init__(self,obj): self.obj = obj def __hash__(self): return hash(id(self.obj)) def __eq__(self,other): return self.obj is other.obj Then, instead of "s.add(d)" use "s.add(Identity(d))". Instead of "d = s.pop()" use "d = s.pop().obj". Instead of "d in s" use "Identity(d) in s". And so on. To do it a bit better, you could create an IdentitySet class that subclasses set and wraps the methods so that they automatically apply wrap and unwrap the arguments on their way in and out (I'd bet there's already a cookbook recipe to do that). Carl Banks From rt8396 at gmail.com Tue Dec 2 22:06:04 2008 From: rt8396 at gmail.com (r) Date: Tue, 2 Dec 2008 19:06:04 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> <00ab327a-c3fc-4b15-a084-4f8c6aed6a8e@o2g2000yqd.googlegroups.com> <8119ab7e-09f1-44de-bdbc-8fdff969d9e4@33g2000yqm.googlegroups.com> Message-ID: <36056737-3c78-499a-a81d-f6241e904460@t11g2000yqg.googlegroups.com> "If we can laugh what else would we do" I'd like to touch also on some comments by ajaksu: [ajaksu] I'd like to try hacking some form of Python to work in SketchUp (on top of Ruby, that is). Now, why won't I try to? I'm a Linux user and we don't get a SU version. So much for FREEDOM. BTW, some things in SU have encrypted Ruby code behind them :) [/ajaksu] You CAN use SketchUp on Linux...ajaksu...thru Wine, but I know this is not good enough. I would love to see FULL SketchUp support for linux and I HAVE made my voice heard. I urge you brother to make make your voice heard also. Go to this thread and let your voice be heard: http://groups.google.com/group/sketchupsuggestions/browse_thread/thread/7c0c810b88ad4d5/dfabe1e01bab12b3?hl=en#dfabe1e01bab12b3 This is the reason...amoung many others...that Linux has yet to take any noticable market from MS. Linux could...If the Linux devolpers would ban together and unite to make package managment and portability between all *nix's universal, OR one great linux distro that the average dummy can use(ubuntu looks promising, but still has a long way to go)...compete with microsoft on a grand level. We have to steal the idiots from under microsoft's feet, and they will come crumbling down. But as long as a poor n00b installs his shiny new *nix system and can't even connect to the network to see the latest janet jackson "wardrobe malfunction", or fiqure out how to mount a flash drive, Linux will be nothing more than our beloved oddessy. There will NEVER be good support on linux for most applications, games, etc... Until people start to get behind linux and support it. Now you say, well i don't have time to support this, my life is too busy, my back hurts. I say stop making excuses. You DON'T have to invest your life, just simply make your voice heard.(myself and other dedicated people will tow the load). But at least get off your bum and do something. It's time to change the world, the hour is upon us, Microsoft is asleep at the wheel, the time for revolution is NOW! From wicijowski at gmail.com Fri Dec 26 05:09:04 2008 From: wicijowski at gmail.com (janislaw) Date: Fri, 26 Dec 2008 02:09:04 -0800 (PST) Subject: tkinter 3.0 multiple keyboard events together References: Message-ID: <600d4b68-6fe2-4c2c-b425-1a739430bb54@s9g2000prg.googlegroups.com> On 26 Gru, 05:52, Pavel Kosina wrote: > Is it possible to catch in an event more that one key from keyboard? In > my code, I can handle always the only one, the first I press, the others > are omitted. Say, I press both "4" and "8" and only "4" is catched. > > def movePlayer(event): > ? ? print (event.keysym) > > Thank you. > > -- > geon > Pavel Kosina Each keypress triggers another event. Fortunately there are two types of events: reaction to press and release. The logic to write to recognize those as simultaneous clicks is up to you :) JW From rocky at panix.com Thu Dec 11 23:12:52 2008 From: rocky at panix.com (R. Bernstein) Date: 11 Dec 2008 23:12:52 -0500 Subject: pydb 1.24 References: <85vdtqejqr.fsf@dozer.localdomain> Message-ID: J Kenneth King writes: > > I watched the demo video, look forward to working with it. Any links to > that emacs front-end being used in the video? > > Cheers and thanks! In short, the emacs code is bundled in with the tar and should be installed when you run "make install" However if you install from a Debian distribution, Alex Moskalenko has done the work to make sure it will automatically be autoloaded from emacs. And it looks like Manfred Tremmel for SuSE (packman) did so as well. Mandriva gets kudos for being the first to make a package (RPM) for version 1.24 -- the day of the release! I'll dropping just a couple more names -- which is really my way to say thank you to all these kind people. The Emacs code got improved for Python as the result of Emacs some code and Python patches by Alberto Griggio. When pydb "annotation" is set to level 3, what you see is a bit more sophisticated than that shown in the demo. Finally, largely through the efforts of Anders Lindgren, the most sophisticated integration is in the emacs interface for the Ruby debugger, ruby-debug. (Although to my mind that code is still little bit incomplete.) There's no reason that code couldn't be modified to work for Python as well since the command interfaces between the two debuggers are very much the same. Ideally common code would be pulled out and could be used in other gdb-like debuggers as well (kshdb, zshdb, or bashdb). All's it takes is someone to do the work! :-) From stef.mientki at gmail.com Wed Dec 10 15:04:12 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 10 Dec 2008 21:04:12 +0100 Subject: Python is slow In-Reply-To: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: <494020BC.6020700@gmail.com> cm_gui wrote: > http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-a-faster-python-vm.html > > I fully agree with Krzysztof Kowalczyk . > Can't they build a faster VM for Python since they love the language > so much? > > Python is SLOW. And I am not comparing it with compiled languages > like C. > Python is even slower than PHP! > > Just go to any Python website and you will know. > An example is: > http://www2.ljworld.com/ > And this site is created by the creators of Django! > > And it is not just this Python site that is slow. There are many many > Python sites which are very slow. And please don?t say that it could > be the web hosting or the server which is slow ? because when so many > Python sites are slower than PHP sites, it couldn?t be the web > hosting. Also, Zope/Plone is even slower. > > Python is slow. Very slow. > > -- > http://mail.python.org/mailman/listinfo/python-list > Put this guy in the junk filter, in may of this year he (or it) started the same discussion. Stef From joe at strout.net Wed Dec 10 18:55:06 2008 From: joe at strout.net (Joe Strout) Date: Wed, 10 Dec 2008 16:55:06 -0700 Subject: var or inout parm? In-Reply-To: <1228951784.5698.1.camel@mctell> References: <493cda2a$0$17080$426a34cc@news.free.fr> <47c890dc0812080057r6d117bbcic377cb96de52d973@mail.gmail.com> <1228951784.5698.1.camel@mctell> Message-ID: <0AA900D0-F20F-4137-A42A-838468B23648@strout.net> On Dec 10, 2008, at 4:29 PM, J. Clifford Dyer wrote: >>>> mh at pixar.com wrote: >>>>> >>>>> How can I make a "var" parm, where the called function can modify >>>>> the value of the parameter in the caller? >>>>> >> See Also: the earlier heated debate thread over what evaluation >> strategy Python uses (Survey says!: call-by-object). >> > > Oh dear God. PLEASE don't see also that thread. That way lies > madness. > Just google for call-by-object, and ignore the hell out of that > thread. Agreed on that point! Anyway, to the OP, see for a detailed explanation of why you can't do quite what you're asking for in Python (or Java, for that matter). Best, - Joe From istvan.albert at gmail.com Thu Dec 4 08:37:45 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Thu, 4 Dec 2008 05:37:45 -0800 (PST) Subject: RELEASED Python 3.0 final References: Message-ID: <1a73e3be-1753-4178-8091-eaa890b3e07e@l42g2000yqe.googlegroups.com> Congratulations on a fantastic work! From hyugaricdeau at gmail.com Mon Dec 29 10:22:22 2008 From: hyugaricdeau at gmail.com (Hyuga) Date: Mon, 29 Dec 2008 07:22:22 -0800 (PST) Subject: I always wonder ... References: Message-ID: <3d10435f-7a6e-4e47-9ea5-a573151a86de@v5g2000prm.googlegroups.com> On Dec 22, 1:51?pm, Grant Edwards wrote: > On 2008-12-22, s... at pobox.com wrote: > > > ... shouldn't people who spend all their time trolling be > > doing something else: studying, working, writing patches which > > solve the problems they perceive to exist in the troll > > subject? > > I think you misunderstand the point of trolling. ?The author of > a troll post doesn't actually care about the "problems" (and > may not even genuinely perceive them as problems). > > > Is there some online troll game running where the players earn > > points for generating responses to their posts? > > Yup. It's called Usenet. a.k.a. multi-player Emacs in deathmatch mode on nightmare difficulty. ;) From goldnery at gmail.com Thu Dec 25 18:32:53 2008 From: goldnery at gmail.com (Gandalf) Date: Thu, 25 Dec 2008 15:32:53 -0800 (PST) Subject: python interpreter black window Message-ID: I use WX gui so the user doesn't actually need it, Is their any way to hide it? thanks From bj_666 at gmx.net Fri Dec 19 08:34:26 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Dec 2008 13:34:26 GMT Subject: encoding problem References: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> Message-ID: <6r1m72Ffb5kpU3@mid.uni-berlin.de> On Fri, 19 Dec 2008 04:05:12 -0800, digisatori at gmail.com wrote: > The below snippet code generates UnicodeDecodeError. > #!/usr/bin/env > python > #--*-- coding: utf-8 --*-- > s = '???' > u = unicode(s) > > > It seems that the system use the default encoding- ASCII to decode the > utf8 encoded string literal, and thus generates the error. > > The question is why the Python interpreter use the default encoding > instead of "utf-8", which I explicitly declared in the source. Because the declaration is only for decoding unicode literals in that very source file. Ciao, Marc 'BlackJack' Rintsch From ethan at stoneleaf.us Mon Dec 15 11:31:53 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 15 Dec 2008 08:31:53 -0800 Subject: Limit traceback from most recent call In-Reply-To: <49454B4E.30308@aim.com> References: <49454B4E.30308@aim.com> Message-ID: <49468679.4050705@stoneleaf.us> Brian Allen Vanderburg II wrote: > I've looked at traceback module but I can't find how to limit traceback > from the most recent call if it is possible. I see that extract_tb has > a limit parameter, but it limits from the start and not the end. > Currently I've made my own traceback code to do this but wonder if > python already has a way to do this build in: > > def format_partial_exc(limit=None): > > (type, value, tb) = sys.exc_info() > > items = traceback.extract_tb(tb) > > if limit: > > items = items[-limit:] # Get last 'limit' items and not first > > result = 'Traceback (most recent call last):\n' > > items = traceback.format_list(items) > > for i in items: > > result += i # Newline already included > > result += type.__name__ + ': ' + str(value) > > return result > > Is this possible currently from traceback or other python module? > > Brian A. Vanderburg II If memory serves, you can catch the exception, then re-raise it -- this should hide all the traceback below where you caught it, but still return the actual error. Hope this helps. ~Ethan~ From collin.day.0 at gmail.com Thu Dec 18 21:17:19 2008 From: collin.day.0 at gmail.com (Collin D) Date: Thu, 18 Dec 2008 18:17:19 -0800 (PST) Subject: Factoring Polynomials References: Message-ID: <919062f9-765e-4279-aa26-2c130d4deacf@o4g2000pra.googlegroups.com> On Dec 18, 6:12?pm, Collin D wrote: > On Dec 18, 11:37?am, collin.da... at gmail.com wrote: > > > I am trying to write a simple application to factor polynomials. I > > wrote (simple) raw_input lines to collect the a, b, and c values from > > the user, but I dont know how to implement the quadratic equation > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > into python. Any ideas? > > I completed the code: > > #import > from math import sqrt > > # collect data > a = float(raw_input('Type a value: ')) > b = float(raw_input('Type b value: ')) > c = float(raw_input('Type c value: ')) > > # create solver > def solver(a,b,c): > ? ? if b**2 - 4*a*c < 0: > ? ? ? ? return 'No real solution.' > ? ? else: > ? ? ? ? sol1 = -1 * b + (sqrt(b**2 - 4*a*c)) / 2*a > ? ? ? ? sol2 = -1 * b - (sqrt(b**2 - 4*a*c)) / 2*a > ? ? ? ? return (sol1, sol2) > > # execute > print solver(a,b,c) > > Thanks to everyone who helped... > This really expanded my knowledge on some of the mathematical > functions in Python. UPDATE: ' #import from math import sqrt # collect data a = float(raw_input('Type a value: ')) b = float(raw_input('Type b value: ')) c = float(raw_input('Type c value: ')) # create solver def solver(a,b,c): if b**2 - 4*a*c < 0: return 'No real solution.' else: sol1 = (-1 * b + (sqrt(b**2 - 4*a*c))) / 2*a sol2 = (-1 * b - (sqrt(b**2 - 4*a*c))) / 2*a return (sol1, sol2) # execute print solver(a,b,c) From rt8396 at gmail.com Mon Dec 22 23:50:06 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 20:50:06 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <18767.47566.709705.92@montanaro-dyndns-org.local> <5uudnUmykoMD983UnZ2dnUVZ_rrinZ2d@posted.usinternet> Message-ID: <8a43ed9b-51c6-4c3f-9f90-7caf0e910093@k36g2000yqe.googlegroups.com> The average user thinks python is only a very large snake! From bdesth.quelquechose at free.quelquepart.fr Sat Dec 6 10:08:59 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 06 Dec 2008 16:08:59 +0100 Subject: Pythonic design patterns In-Reply-To: <815c6e46-283f-44c3-ba78-b1f9223dd48b@v13g2000yqm.googlegroups.com> References: <815c6e46-283f-44c3-ba78-b1f9223dd48b@v13g2000yqm.googlegroups.com> Message-ID: <493aa345$0$14438$426a74cc@news.free.fr> r.grimm at science-computing.de a ?crit : > Hallo, >> users in this forum has been kind enough to point out. Only my >> implementations are often not that clean, and I may call things >> something different than the normal convention, which is a source of >> confusion for myself and others trying to communicate with me. > I think, you should start with the classical books of Design Patterns > to get a solid understanding and especially vocabulary to communicate > with your coworkers. Its easier and better to say, that you will use a > strategy pattern than to describe the architecture in many sentences > to your partner in a ambigious way. Indeed. But now there's the risk that coworkers implement this as: class AbstractFooStrategy(object): def run(self, yadda): raise NotImplementedError class SimpleFooStrategy(AbstractFooStrategy): def run(self, yadda): # code here class Bar(object): def __init__(self, foo_strategy): if not isinstance(foo_strategy, AbstractFooStrategy): raise ValueError("yadda yadda") self.foo_strategy = foo_strategy def do_this(self, yadda): return self.foo_strategy.run(yadda) b = Bar(SimpleFooStrategy()) instead of: class Bar(object): def __init__(self, foo_strategy): self.foo_strategy = foo_strategy def do_this(self, yadda): return self.foo_strategy(yadda) def baaz(yadda): # code here b = Bar(baaz) > Thats in my opinion the first and > the key benefit of Design Patterns. Totally agree - at least as long as coworkers clearly understand the difference between design and implementation. > Speaking in the same language. The > next step should be to apply your knowledge to your programming > language. Indeed !-) > So I will recommend the classical GOF Books While most implementation example are way over the top in the context of a hi-level dynamic language like Python, the GOF is one of the best book on OO design I've ever read - if not the only that was worth reading (disclaimer : I didn't read much dead-tree stuff on OO). From castironpi at gmail.com Tue Dec 16 23:09:47 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 16 Dec 2008 20:09:47 -0800 (PST) Subject: How to modify a program while it's running? References: <01584cbd$0$20656$c3e8da3@news.astraweb.com> <1fe20306-39ff-4169-b49e-5ae5dd8159af@v5g2000prm.googlegroups.com> Message-ID: On Dec 16, 7:54?pm, "James Mills" wrote: > @Aaron > > Your code and suggestion is way too complicated. > Just register your objects. When you need to > reload your module, destroy the existing > objects and re-creat them. > > This works well assuming you have a stable > running core that maintains the connection > and that code doesn't change much. > > --JamesMills The practical and general solutions aren't very similar. Practically, I agree. You could do something generic like reassign __dict__ (like the Borg pattern), or __class__. To be completely general, you'd need an object which passes the type test: "TypeError: unbound method f() must be called with A instance as first argument ( got B instance instead)". Then you could call it in anything, Cls.meth ( obj ), regardless of if you created it before or after the class was created. Or you could have a class that looked up its (posessive) methods' names on a deeper class which could be loaded later: the Delegate, Proxy, or Adapter patterns. Maybe Cls.meth( obj ) should be permitted to work on arbitrary objects by a compiler switch or __future__ import. From rt8396 at gmail.com Tue Dec 23 11:06:35 2008 From: rt8396 at gmail.com (r) Date: Tue, 23 Dec 2008 08:06:35 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: On Dec 23, 8:21?am, Thorsten Kampe wrote: > * r (Mon, 22 Dec 2008 10:44:32 -0800 (PST))> > > > Steve Holden > > > What makes you assume this is a zero-sum game, and that Python won't > > > survive if any other language becomes popular. Every language borrows > > > from those that came before it. Terms like "outright plagiarism" don't > > > encourage rational debate, and make you seem like a troll who is more > > > interested in stirring up controversy than actually doing things to help > > > promote the language. > > > This is a war Steve, and i will explain why. Python does not need to > > compete with perl, lisp, C, basic, etc, etc. WHY, well because python > > is SO radically different than those languages. Ruby on the other > > hand, took most from python, the only difference is Ruby's full OO > > integration.(12.method()). Since Ruby is so similar to python [...] > > You don't have a single clue about neither Python nor Ruby: > 'According to the Ruby FAQ, "If you like Perl, you will like Ruby and be > right at home with its syntax. [...] If you like Python, you may or may > not be put off by the huge difference in design philosophy between > Python and Ruby/Perl."'[1] > > Thorsten > [1]http://en.wikipedia.org/wiki/Ruby_(programming_language)#Semantics Thats "Thurstan", thank you very much! :) From t.gkikopoulos at dundee.ac.uk Mon Dec 8 10:03:37 2008 From: t.gkikopoulos at dundee.ac.uk (trias) Date: Mon, 8 Dec 2008 07:03:37 -0800 (PST) Subject: appending values into array instead of a list Message-ID: <20896957.post@talk.nabble.com> Hi, I have this little script: import csv import numpy signal=[] ref=[] for x in csv.reader(open('reffile.csv').readlines()): ref.append(x) for x in csv.reader(open('signalfile.csv').readlines()): signal.append(x) signalarray=numpy.array(signal, dtype=float) signaldict={} signaldict.update(dict(signalarray)) intarray=[0.0 for x in range(301)] cntarray=[0 for x in range(301)] for line in ref: print line locstr=line[1] endstr=line[2] loc=float(locstr) end=float(endstr) print loc print end i=0 while float(i) <= 300.0: if signaldict.has_key(end+float(i)): expr=signaldict[end+float(i)] print expr intarray[i]+=expr cntarray[i]+=1 y=i i+=1 print intarray print cntarray fo=file('outfile.txt','w') s=str(intarray) fo.write(s) fo.close() So on the above I am appending values from signaldict indexed by i for every object in the ref list. This way I calculate the sum of all values with similar indexing i value. Would I be able to store the signaldict[i] for every line individually in a multidimensional array? cheers -- View this message in context: http://www.nabble.com/appending-values-into-array-instead-of-a-list-tp20896957p20896957.html Sent from the Python - python-list mailing list archive at Nabble.com. From bertilow at gmail.com Sat Dec 6 21:05:15 2008 From: bertilow at gmail.com (Bertilo Wennergren) Date: Sun, 07 Dec 2008 11:05:15 +0900 Subject: Learning Python now coming from Perl In-Reply-To: References: Message-ID: Aahz wrote: > In article , > Bertilo Wennergren wrote: >> I don't suppose there is any introductory material out there that is >> based on Python 3000 and that is also geared at people with a Perl >> background? Too early for that I guess.. > Honestly, the differences between 2.x and 3.0 are small enough that it > doesn't much matter, as long as you're not the kind of person who gets > put off by little problems. Because so much material is for 2.x, you > may be better off just learning 2.x first and then moving to 3.x. The main reason I waited until Python 3000 came out is the new way Unicode is handled. The old way seemed really broken to me. Much of what I do when I program consists of juggling Unicode text (real Unicode text with lots of actual characters outside of Latin 1). So in my case learning version 2.x first might not be very convenient. I'd just get bogged down with the strange way 2.x handles such data. I'd rather skip that completely and just go with the Unicode handling in 3.0. -- Bertilo Wennergren From jeremiah.dodds at gmail.com Wed Dec 3 06:50:49 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Wed, 3 Dec 2008 06:50:49 -0500 Subject: Converting a .xls file to .html In-Reply-To: References: Message-ID: <12cbbbfc0812030350u26b8f41cw6569d7b17bf21d41@mail.gmail.com> On Wed, Dec 3, 2008 at 5:54 AM, tarun wrote: > Hello All, > > I've a .xml file (saved as .xls) that can be opened in Microsoft excel. I > want to write python code that converts this excel file into .html (so that > it can be viewed as is in an explorer). > > Can any one help? > > Regards, > Tarun > > -- > http://mail.python.org/mailman/listinfo/python-list > > A quick google search shows http://pyxlreader.sourceforge.net/ , and a few other libraries for reading xls files. I don't use excel, so I can't test it. There may not be a library for going straight from xls -> html, but if you can get xls -> text or a list or whatnot, then you could use pretty much any html generation tool you want on it, python's got plenty of templating libraries available. -------------- next part -------------- An HTML attachment was scrubbed... URL: From darcy at druid.net Tue Dec 16 17:24:16 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 16 Dec 2008 17:24:16 -0500 Subject: Need help improving number guessing game In-Reply-To: References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> <01564c98$0$21844$c3e8da3@news.astraweb.com> <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> <4946df78$0$19771$426a74cc@news.free.fr> <1f33580b-84f9-4059-a0f0-b6a8d71325af@b38g2000prf.googlegroups.com> <4947742c$0$25951$426a34cc@news.free.fr> Message-ID: <20081216172416.186e0d43.darcy@druid.net> On Tue, 16 Dec 2008 13:59:24 -0800 Scott David Daniels wrote: >> > def yesno(s): > > s = s.strip().lower() > > if not s in ("y", "n"): You could also do this to be a little more user friendly: if not (s and s[0] in ("y", "n")): Or reverse the test for clarity. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From fakeaddress at nowhere.org Mon Dec 15 01:59:24 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 14 Dec 2008 22:59:24 -0800 Subject: Bidirectional Networking In-Reply-To: References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <98a6c3cd-181c-43c9-805b-fb0689c69544@a26g2000prf.googlegroups.com> <29283382-3e26-492a-8612-9352f32c1c01@r15g2000prd.googlegroups.com> Message-ID: Brian Allen Vanderburg II wrote: > As for the backlog (5), this > doesn't mean that you can only have a maximum of 5 established > connections. Each established connection gets a new socket object. But > what I think it means is that during the listen for an incoming > connection on the listening socket, if multiple connection attempts are > coming in at one time it can keep a backlog of up to 5 of these > connection attempts for that individual socket. Right. An incoming connect adds a connection to the listen queue, and the application's accept() call removes one connections from the queue. The limited backlog is relevant to the OP's suggestion of calling SocketServer.handle_request() periodically. The accept() that pulls connections off the listen queue is within handle_request(), thus during the period between these calls incoming connections will queue up and could easily reach the limit. -- --Bryan From steve at REMOVE-THIS-cybersource.com.au Fri Dec 12 17:54:18 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Dec 2008 22:54:18 GMT Subject: concept of creating structures in python References: Message-ID: <0152e321$0$8244$c3e8da3@news.astraweb.com> On Fri, 12 Dec 2008 09:07:21 -0700, Joe Strout wrote: >> Joe missed a piece out here. If you change the signature of your >> D.__init__() to read >> >> def __init__(self, dataName='ND', index = 0, ele_obj=None): >> >> then you need to insert the following code at the top of the method: >> >> if ele_obj is None: >> ele_obj = E() > > Yes, if you really need to guarantee that ele_obj is not None, then this > is the way to do it. > > Of course this would mean that you can't get a None ele_obj even by > passing it in explicitly as the parameter value -- if you need to > support that as well, then the solution is a little more complex. > Perhaps best in that case would be to just not give ele_obj any default > value at all, so it becomes a required parameter. Just use a sentinel that isn't None. class D(...): sentinel = object() def __init__(self, dataName='ND', index = 0, ele_obj=sentinel): if ele_obj is D.sentinel: ... -- Steven From bdesth.quelquechose at free.quelquepart.fr Mon Dec 22 13:50:45 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 22 Dec 2008 19:50:45 +0100 Subject: Python's popularity In-Reply-To: References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: <494fef38$0$12781$426a74cc@news.free.fr> walterbyrd a ?crit : > On Dec 22, 10:13 am, r wrote: >> Since the >> advent of Ruby(Python closet competitor), Python's hold on this niche >> is slipping. > > About the only place I ever hear of ruby being used is web development > with RoR. When it comes to web development, it seems to me that ruby > (because of rails) is far more popular s/popular/hyped/ But being (perhaps over ?) hyped too soon is not necessarily the best move... > than python. It seems to me > that ruby is the niche player, and python (with fairly new frameworks) > is trying to catch up to ruby in that niche. It seems to me that the > python web framework that best competes with rails, is Django, and > Django 1.0 just came out a few months back. Fooled by version numbers ? Heck, Python 3.0 just came out a couple weeks ago, and PHP is already at 6.x !-) FWIW, I wrote my first django app years ago (and it's still in production). >> A lot of Ruby noobies don't even realize that most of >> Ruby is an out-right plagiarism of Python. I don't know who asserted such a stupid thing, but he manages to be equally clueless wrt/ both languages. > Maybe. But the rails framework seems to have a different philosophy > than the django, turbogears, or pylons, frameworks. RoR values > convention over configuration, and has a lot of "magic" whereas the > python frameworks seem to have the opposite philosophy - in those > regards. I see pros and cons to both approaches. I wonder what the > market with think? My actual CTO is a big Ruby/Rails fan, yet he settled on Python/Django for our current 'big' project. Wonder why ? From pavlovevidence at gmail.com Fri Dec 19 21:16:09 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 19 Dec 2008 18:16:09 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <863a4a88-5051-4526-b882-c448eb2ea2ad@k36g2000pri.googlegroups.com> On Dec 19, 12:10?pm, Christian Heimes wrote: > walterbyrd schrieb: > > > On Dec 19, 9:13 am, "Giampaolo Rodola'" wrote: > >> You can use the old 2.x syntax also in Python 3.x: > > > Yeah, but it's deprecated, and - as I understand it - may be removed > > completely in future versions. Also, in the future, if you are working > > with code from another developer, it's likely that developer will use > > the new format. I suppose you can use both - but what an awful mess > > that would be. > > It's not going to be removed for many years - if ever. The % string > formatting system is not deprecated in 3.0. For that very reason it must > stay until 3.2. We don't have plans to deprecate it in 3.1 so it will > stay at least until Python 3.3 which is to be released about 2014. I wish they would have at least deprecated or got rid of the % operator, because that's ugly. There's no reason they couldn't have added another method for printf-style formating, e.g.: "The answer is %s.".sprintf("yes") Carl Banks From mnordhoff at mattnordhoff.com Tue Dec 23 19:54:32 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Wed, 24 Dec 2008 00:54:32 +0000 Subject: using subprocess module in Python CGI In-Reply-To: References: Message-ID: <49518848.1080602@mattnordhoff.com> ANURAG BAGARIA wrote: > Hello, > > I am a Python Newbie and would like to call a short python script via > browser using a CGI script, but initially I am trying to call the same > python script directly through python command line. The script intends > to perform a few command line in a pipe and I have written the script (a > short one) as follows. > > #!/usr/bin/python > > import cgi, string, os, sys, cgitb, commands, subprocess > import posixpath, macpath > #file = "x.tar.gz" > #comd = "tar -xf %s" % (file) > #os.system(comd) > #commands.getoutput('tar -xf x.tar.gz | cd demo; cp README ../') > comd = [\ > "tar -xf x.tar.gz", \ > "cd demo", \ > "cp README ../", \ > ] That's not how subprocess.call() works. You're trying to run an executable called "tar -xf x.tar.gz", passing it the arguments "cd demo" and "cp README ../". > outFile = os.path.join(os.curdir, "output.log") > outptr = file(outFile, "w") > errFile = os.path.join(os.curdir, "error.log") > errptr = file(errFile, "w") > retval = subprocess.call(comd, 0, None, None, outptr, errptr) > errptr.close() > outptr.close() > if not retval == 0: > errptr = file(errFile, "r") > errData = errptr.read() > errptr.close() > raise Exception("Error executing command: " + repr(errData)) > > > but after trying to execute this independently, I get the following > error which I am unable to interpret : > > Traceback (most recent call last): > File "process.py", line 18, in > retval = subprocess.call(comd, 0, None, None, outptr, errptr) > File "/usr/lib/python2.5/subprocess.py", line 443, in call > return Popen(*popenargs, **kwargs).wait() > File "/usr/lib/python2.5/subprocess.py", line 593, in __init__ > errread, errwrite) > File "/usr/lib/python2.5/subprocess.py", line 1135, in _execute_child > raise child_exception > > > Could someone suggest where am I going wrong and if corrected, what is > the probability of this script being compatible with being called > through the browser. Thanking you people in advance. Well, you'd need to output something, but otherwise, sure, why not? print "Content-Type: text/html" print print "..." > Regards. Why do you even need to use subprocess to do this? All it's doing is extracting the README file from a tarball, right? You can use the tarfile module for that. -- From rtomek at ceti.com.pl Mon Dec 15 22:16:06 2008 From: rtomek at ceti.com.pl (Tomasz Rola) Date: Tue, 16 Dec 2008 04:16:06 +0100 (CET) Subject: Python is slow In-Reply-To: <25b4d503-5073-4e66-8914-ca5fa7b144e1@w39g2000prb.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <25b4d503-5073-4e66-8914-ca5fa7b144e1@w39g2000prb.googlegroups.com> Message-ID: On Fri, 12 Dec 2008, bearophileHUGS at lycos.com wrote: > In the next years people that use low-level languages like C may need > to invent a new language fitter for multi-core CPUs, able to be used > on GPUs too (see the OpenCL), less error-prone than C, able to use the > CPU vector instructions efficiently. (The D language is probably unfit > for this purpose, because even if it's meant to be a system language, > I don't think it can be used much to replace C everywhere it's used > now.) A C+ maybe? :-) > > Bye, > bearophile I would say, this probably will be some descendant of Erlang and/or Haskell. As evolutionary step, they look very promising to me, they just are "not quite there" yet. As of C++, I cannot tell before I read their new standard. Regards, Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** From darcy at druid.net Thu Dec 25 08:51:43 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 25 Dec 2008 08:51:43 -0500 Subject: os.system('cls') In-Reply-To: References: <05BADA85-33ED-48BF-B251-2CC830D6D55E@rgbaz.eu> Message-ID: <20081225085143.fc9be5c4.darcy@druid.net> On Thu, 25 Dec 2008 13:11:09 +0100 "Dennis van Oosterhout" wrote: > Btw...does that mean that system('cls') only works on Windows...or to > say it otherwise: the program isn't platform independant? Exactly - sort of. Unless, of course, you have a program called "cls" installed on other platforms. The "system" method is platform independent in that it runs system commands on all platforms but it has no control over what system commands happen to exist on your system. Depending on the command you run it may not even be portable to another Windows system of exactly the same version. BTW, "os.system('clear') will clear the screen on many Unix systems. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From clp at rebertia.com Thu Dec 18 01:08:02 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 17 Dec 2008 22:08:02 -0800 Subject: importing csv file into sqlite In-Reply-To: <21067453.post@talk.nabble.com> References: <21067453.post@talk.nabble.com> Message-ID: <47c890dc0812172208s4b827b2fw4f4bb946783108fa@mail.gmail.com> On Wed, Dec 17, 2008 at 9:58 PM, klia wrote: > > hey guys, i have a hug .csv file which i need to insert it into sqlite > database using python. > my csv data looks like this > Birthday2,12/5/2008,HTC,this is my birthday > Sea,12/3/2008,kodak,sea > birthday4,14/3/2009,samsung,birthday > love,17/4/2009,SONY,view of island > > can any one give me a head start codes. > Use the `csv` module to read the CSV file: http://docs.python.org/library/csv.html I think one who knows sqlite can quite easily figure it out from there. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From skip at pobox.com Tue Dec 9 21:07:24 2008 From: skip at pobox.com (Skip Montanaro) Date: Wed, 10 Dec 2008 02:07:24 +0000 (UTC) Subject: Test message - please ignore References: Message-ID: Skip Montanaro pobox.com> writes: > > Testing a new news-to-mail gateway on mail.python.org. > This post is from gmane. Please ignore. Test #4. Another one to ignore... S From bdesth.quelquechose at free.quelquepart.fr Fri Dec 12 14:41:57 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 12 Dec 2008 20:41:57 +0100 Subject: Python is slow In-Reply-To: <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> Message-ID: <4942cc3c$0$21936$426a74cc@news.free.fr> sturlamolden a ?crit : (snip) > Creating a fast implementation of a dynamic language is almost rocket > science. But it has been done. There is Stronghold, the fastest > version of Smalltalk known to man, on which the Sun Java VM is based. > On a recent benchmark Java 6 -server beats C compiled by GCC 4.2.3 cf bearophile's comment on this point (CPU architecture and RAM) > And > most of that magic comes from an implementation of a dynamically typed > language (Smalltalk). Err... Where is _Java_ "dynamic" actually ? A benchmark of _Smalltalk_ VM vs CPython VM would make more sense. > Second, there are other fast implementations of dynamic languages. The > CMUCL and SBCL versions of Common Lisp comes to min; you can see how > SBCL does in the same benchmark (CMUCL tends to be even faster). Could it be that there are some type hints in the lisp versions of the source code ? > So Python is a lot slower than it needs to be. Please fix it, you're welcome. From kirk at daycos.com Fri Dec 12 13:18:40 2008 From: kirk at daycos.com (Kirk Strauser) Date: Fri, 12 Dec 2008 12:18:40 -0600 Subject: (Very Newbie) Problems defining a variable References: Message-ID: <878wqlz27z.fsf@daycos.com> At 2008-12-12T18:12:39Z, "Tim Rowe" writes: > Is there a tidy way of making rates and thresholds local to get_rate, > without recalculating each time? I suppose going object oriented is > the proper way. > > #Py3k,UTF-8 > > rates = {0: 0.006, 10000: 0.0085, 25000: 0.0124, 50000: 0.0149, 100000: 0.0173} > thresholds = list(rates.keys()) > thresholds.sort() > thresholds.reverse() > > def get_rate(balance): > for threshold in thresholds: > if balance >= threshold: > return rates[threshold] > else: > return 0.0 How 'bout: def get_rate(balance): for threshold, rate in ((100000, .0173), (50000, .0149), (25000, .0124), (10000, .0085), (0, .006)): if balance > threshold: return rate return .0 -- Kirk Strauser The Day Companies From sumerc at gmail.com Thu Dec 4 09:23:28 2008 From: sumerc at gmail.com (k3xji) Date: Thu, 4 Dec 2008 06:23:28 -0800 (PST) Subject: Python Runtime Method Call Binding Message-ID: Hi, Is there a way to hook a function call in python? I know __getattr__ is doing for variables, it is giving us a chance before a field is initialized. Do we have same functionality for methods? Example: class Foo(object): def __call_method__(self, ...) # just pseudo print 'A method is called in object...' f = Foo() f.test_method() I think you understand my point. Thanks, From geekmail at usenot.de Thu Dec 4 14:41:21 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Thu, 4 Dec 2008 20:41:21 +0100 Subject: "as" keyword woes References: <7dudnSS7uIn_KarUnZ2dnUVZ_tTinZ2d@earthlink.com> <0147e4df$0$20670$c3e8da3@news.astraweb.com> Message-ID: <20081204204121.0fda015c@usenot.de> On Thu, 4 Dec 2008 10:44:33 -0600 "Chris Mellon" wrote: > Aside from the cultural indoctrination, though (and that may be a real > and strong force when dealing with math software, and I don't want to > discount it in general, just for purposes of this discussion) why is > it more sensible to use "x" here instead of "number" or "real" or > "real_number" or something else? I think "aside from" doesn't really apply. It is habitual to write mathematics in shorthand. That is a, if not *the* factor to consider. Also: Variable names in programs tend to describe what those things *do* not what they are. If I call a variable "number", the reader will usually none the wiser, because you deal with numbers a lot anyway. You'd call your numbers "counter", "height", "pressure" and the like. If however you do lots of numerical computations, your numbers tend to be just that, numbers. You'll gain nothing but confusion by calling them "number1", "number2", "number3". They are then much easier to discern by calling them x, y and z. I think. /W -- My real email address is constructed by swapping the domain with the recipient (local part). From rhodri at wildebst.demon.co.uk Sun Dec 7 18:26:14 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Sun, 07 Dec 2008 23:26:14 -0000 Subject: Don't you just love writing this sort of thing :) In-Reply-To: References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: On Sun, 07 Dec 2008 07:27:51 -0000, Lawrence D'Oliveiro wrote: > In message , Rhodri > James wrote: > >> Yes, it's very pretty, and you're terribly clever. In six months' time >> when you come back to make some engineering change and have to sit down >> and break it back down into those simple pieces to remind yourself what >> it's doing, "pretty" and "clever" will not be the words you are using. >> Trust me on this one. > > Considering I've been writing and maintaining and debugging code for > about > 30 years now, I figure I have the hard-earned right to judge what I will > be > able to understand in six months and what I won't... Huh. I can only claim 25 years, but I would still strongly discourage people from playing that sort of game. -- Rhodri James *-* Wildebeeste Herder to the Masses From __peter__ at web.de Thu Dec 18 09:19:49 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 18 Dec 2008 15:19:49 +0100 Subject: re.match() performance References: <755bd716-f5f6-4953-87a7-04ee148c3298@i18g2000prf.googlegroups.com> Message-ID: Emanuele D'Arrigo wrote: > I've written the code below to test the differences in performance > between compiled and non-compiled regular expression matching but I > don't quite understand the results. It appears that the compiled the > pattern only takes 2% less time to process the match. Is there some > caching going on in the uncompiled section that prevents me from > noticing its otherwise lower speed? Yes: >>> import re >>> re._cache {} >>> re.match("yadda", "") >>> re._cache {(, 'yadda', 0): <_sre.SRE_Pattern object at 0x2ac6e66e9e70>} Hint: questions like this are best answered by the source code, and Python is open source. You don't even have to open an editor: >>> import inspect >>> print(inspect.getsource(re.match)) def match(pattern, string, flags=0): """Try to apply the pattern at the start of the string, returning a match object, or None if no match was found.""" return _compile(pattern, flags).match(string) >>> print(inspect.getsource(re._compile)) def _compile(*key): # internal: compile pattern cachekey = (type(key[0]),) + key p = _cache.get(cachekey) if p is not None: return p pattern, flags = key if isinstance(pattern, _pattern_type): if flags: raise ValueError( "Cannot process flags argument with a compiled pattern") return pattern if not sre_compile.isstring(pattern): raise TypeError("first argument must be string or compiled pattern") p = sre_compile.compile(pattern, flags) if len(_cache) >= _MAXCACHE: _cache.clear() _cache[cachekey] = p return p Peter From philip at semanchuk.com Sun Dec 21 16:27:25 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Sun, 21 Dec 2008 16:27:25 -0500 Subject: Are Django/Turbogears too specific? In-Reply-To: <494eb16e$0$22710$426a74cc@news.free.fr> References: <494eb16e$0$22710$426a74cc@news.free.fr> Message-ID: <2B198A4F-5911-456D-A45B-E073DB121446@semanchuk.com> On Dec 21, 2008, at 3:14 PM, Bruno Desthuilliers wrote: > Philip Semanchuk a ?crit : > (snip) >> From the reading I did, I gathered that Django was really good if >> you want to do what Django is good at, but not as easy to customize >> as, say, Pylons. > > That was my first impression too, and was more or less true some > years ago. After more experience, having gained a deeper knowledge > of Django's internals, I can tell you this is just not true. You can > "customize" it as you want - meaning: you can use any ORM (or no ORM > at all) and any template language you want, as long as you don't > intend to use django's ORM and template language related features > (which just don't exist in Pylons). IOW : Django is just as flexible > as Pylons (or pretty close to), but has more to offer if you stick > to builtin components. Based on what I read, I got the idea that Django *can* be as flexible as Pylons, but most people find it *easier* to take advantage of Pylons' flexibility. In other words, no one is saying Django is incapable, but that it is less focused on making it easy to allow developers to mix & match components and more focused on providing a smooth tool with which to work. > NB : not to dismiss Pylons, which is a pretty great framework too, > and use IMHO better default components (namely SQLAlchemy and Mako). I prefer Mako over the other template languages I've seen. From iainking at gmail.com Wed Dec 3 05:54:55 2008 From: iainking at gmail.com (Iain King) Date: Wed, 3 Dec 2008 02:54:55 -0800 (PST) Subject: Obama's Birth Certificate - Demand that US presidential electors investigate Obama's eligibility References: <89pZk.9151$be.4743@nlpi061.nbdc.sbc.com> Message-ID: <6cf32afd-f167-4c3e-884a-48452eaa8f82@w34g2000yqm.googlegroups.com> On Dec 3, 10:16 am, MM4... at yahoo.com wrote: > On Dec 3, 12:53 am, Bryan Olson wrote: > > > > > girbarob... at yahoo.com wrote: > > > This message is not about the meaningless computer printout called > > > More importantly, it's not about Python. I'm setting follow-ups to > > talk.politics. > > > > "Certification of Live Birth" that Obama propaganda machine calls his > > > "Birth Certificate". The American people are still waiting for a copy > > > of Obama's original birth certificate that includes all his birth > > > information. > > > The document is what Hawaii provides as certified copy of birth record. > > It contains all the information the federal government requires to prove > > citizenship by birth, and it shows that Barack Hussein Obama was born 04 > > August 1961 in Honolulu. See: > > > http://www.factcheck.org/elections-2008/born_in_the_usa.html > > This garbage on factcheck.org is a worthless piece of paper > insufficient to prove a US citizenship much less a natural born one. > You need to have a long version of legitimate birth certificate that > includes all birth information. Hawaii officials never even confirmed > this piece of garbage on factcheck.org > > > > Remind your US presidential electors of their constitutional duty to > > > investigate Obama's natural-born citizen status. > > > > No federal agency like FBI or Secret Service, no Hawaii bureaucrats > > > have ever investigated Obama's birth in Hawaii. Many illegal aliens in > > > USA have official "birth certificates" issued by state bureaucrats on > > > the basis of falsified birth records. > > > Janice Okubo of Hawaii's Department of Health confirmed that the state > > has Obama?s original birth certificate on record: > > > http://hawaii.gov/health/about/pr/2008/08-93.pdf > > > [...] > > Do you have a sufficient IQ to actually grasp what this news release > says? > > All it says is that Hawaii has "Obama?s original birth certificate". > It does not say anything whether this "Obama?s original birth > certificate" is from Hawaii or Kenya or from Indonesia. Under the > Hawaii laws, a parent could use an original birth certificate from > another country to register a child in Hawaii and get today > "Certification of Live Birth". People actually born in Hawaii do not > get such "Certification of Live Birth", they get another document with > different name. > > Considering all the public pressure on Hawaii officials to confirm > Obama's birth in Hawaii, they would start any response with > confirmation that Obama was born in Hawaii. Instead, they give you > carefully worded garbage so that your low IQ brain can swallow it and > Obama propaganda machine can beat into your worthless brain until you > repeat it like a low IQ moron. > > > > > > > > Remind your US presidential electors that they have the legal standing > > > and constitutional duty to investigate Obama's birth in Hawaii by > > > demanding that Obama provide all his original birth records, and a > > > federal agency like FBI or Secret Service fully investigate them. > > > That's not what the Constitution says. US Constitution, Article IV, > > Section 1: "Full Faith and Credit shall be given in each State to the > > public Acts, Records, and judicial Proceedings of every other State. And > > the Congress may by general Laws prescribe the Manner in which such > > Acts, Records and Proceedings shall be proved, and the Effect thereof." > > > These haters seek to make Obama prove his records in ways others have > > not had to, and beyond any manner prescribed by Congress within its > > constitutional authority. > > You do not have enough brain cells to understand anything you just > quoted. > > Get one thing straight for your own self interest! THERE ARE TENS OF > MILLIONS OF GUN OWNERS IN USA ONLY WAITING TO USE THEM ON ANYBODY WHO > THREATENS THE US CONSTITUTION - so better use all your brain cells in > your own self interest to resolve this matter now and not later. Run > to Obama and beg him to release all birth records or things will not > get any better. You are playing with fire. Heh, you're awesome. Keep it up! From jules at REMOVETHIS.op59.net Wed Dec 10 06:58:25 2008 From: jules at REMOVETHIS.op59.net (Julian Smith) Date: Wed, 10 Dec 2008 11:58:25 +0000 Subject: Using the `email' module in a bazaar plugin Message-ID: <20081210115825.01853c3b.jules@REMOVETHIS.op59.net> I don't seem to be able to use the `email' module from within a bazaar plugin. Other modules work ok, e.g. nntplib. Here's my plugin, cut-down to show just the email problem: import sys print 'sys.version', sys.version import nntplib n = nntplib.NNTP( 'jsmith-ubuntu2' ) print n import email m=email.MIMEText.MIMEText('text of email') - and here's the output when i run any bazaar command: > bzr status sys.version 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] 'module' object has no attribute 'MIMEText' Unable to load plugin 'js_notify' from '/home/jsmith/.bazaar/plugins' ... The plugin runs fine on its own, it's only when loaded into Bazaar that things go wrong. I thought perhaps this could be caused by the `email' module's use of LazyImporter. I've tried various things such as `from email.mime.text import MIMEText', and they fail in similar ways. I'm using bzr-1.9, python 2.5.2, on Ubuntu-8.xx. Does anyone have any ideas ? Thanks, - Julian -- http://op59.net/ From castironpi at gmail.com Sun Dec 7 06:16:56 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 7 Dec 2008 03:16:56 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> Message-ID: On Dec 6, 2:29?pm, "Guido van Rossum" wrote: snip > > So, assuming I now wish to propose a corrective PEP to remedy this > > situation for Python 3.1 and beyond, what is the best way to get started > > on such a proposal? > > Don't bother writing a PEP to make 'as' available as an attribute > again. It has no chance of being accepted. Instead, think of a > different word you could use. You could use the Latin 'qua' or the Spanish 'como', for example. qua: -dictionary.com ?adverb as; as being; in the character or capacity of: The work of art qua art can be judged by aesthetic criteria only. From rhodri at wildebst.demon.co.uk Tue Dec 23 16:38:34 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Tue, 23 Dec 2008 21:38:34 -0000 Subject: iterating initalizations In-Reply-To: References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> <20081223092504.aaf25192.darcy@druid.net> Message-ID: On Tue, 23 Dec 2008 15:39:52 -0000, Aaron Stepp wrote: > import random > from rtcmix import * > from chimes_source import * # Chime.play() > from rhythmblock import * # rhythmBlock.rhythmTwist() and > rhythmBlock.printStuff() > from pitchblock import * # pitchBlock.pitchTwist() and > pitchBlock.printStuff() > from lenEval import * #greaterThan.sovler() > > indexrand = random.Random() > indexrand.seed(2) > > chime = Chime() > notes = pitchBlock() > rhythm = rhythmBlock() > solve = greaterThan() > > class arrayBlock: > > def __init__(self, theTempo, start): > self.__A = [] > self.__B = [] > self.__start = start > self.__tempo = theTempo > > def player(self, length, tempo, octave, pan, seed): > > tempo = (120, self.__tempo) > > for a in range(length): > > one = indexrand.randint(0, 3) > > two = indexrand.randint(0, 7) > > self.__A = self.__A + notes.pitchTwist(one , two) > > for b in range(length): > > one = indexrand.randint(0, 3) > > two = indexrand.randint(0, 7) > > self.__B = self.__B + rhythm.rhythmTwist(one , two) > > lenA = len(self.__A) > lenB = len(self.__B) > > var = solve.solver(lenA, lenB) > > > for c in range(var): > > print self.__A[c] > > self.__start = self.__start + tb(self.__B[var]) > > chime.play(self.__start, self.__A[var], octave, pan, seed) > > This almost does exactly what I want, and is far cleaner than my > previous attempts. > > The only problem is that now all my arguments are being passed as zeros! Which "all" your arguments? There are an awful lot there; what *exactly* do you mean? > I assume this has to do with WHEN I'm referencing self.__A and self.__B? If you mean __A and __B are full of zeroes, then you should suspect your notes.pitchTwist() and rhythm.rhythmTwist() methods of returning zeroes. -- Rhodri James *-* Wildebeeste Herder to the Masses From joe at strout.net Thu Dec 11 10:43:00 2008 From: joe at strout.net (Joe Strout) Date: Thu, 11 Dec 2008 08:43:00 -0700 Subject: Call by reference in SWIG? In-Reply-To: References: Message-ID: <9D295CD0-2DA3-4572-A2A5-57301D67BEED@strout.net> On Dec 10, 2008, at 10:19 PM, Nok wrote: > I can't get call-by-reference functions to work in SWIG... Python doesn't have any call-by-reference support at all [1], so I'm not surprised that a straight translation of the call-by-reference C function doesn't work. Unfortunately I don't know enough about SWIG to suggest a work- around. Hopefully someone more versed in SWIG will have a bright idea. If you don't find anything in the Python space, you might try poking around in Java references, since Java has the same call semantics as Python. Best wishes, - Joe [1] http://www.strout.net/info/coding/valref/ From nopsidy at gmail.com Sat Dec 27 23:57:33 2008 From: nopsidy at gmail.com (RP) Date: Sat, 27 Dec 2008 22:57:33 -0600 Subject: how to make a class to get all forms and input fields from webpage In-Reply-To: References: Message-ID: Thank you. On Sat, Dec 27, 2008 at 8:39 PM, Gabriel Genellina wrote: > En Sat, 27 Dec 2008 21:54:02 -0200, alex goretoy < > aleksandr.goretoy at gmail.com> escribi?: > > How do I make a class for retrieving all forms and input fields on a web >> page. Meaning, form name, form url,all input fields, >> text,textarea,select,etc...I have something currently and it kinda >> > > I'd use BeautifulSoup: http://pypi.python.org/pypi/BeautifulSoup/ > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -- ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Fri Dec 12 16:06:41 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 12 Dec 2008 21:06:41 +0000 (UTC) Subject: Testing against different versions of Python References: <2678157f0812121142y2afcf3bey254dd2b74f61e423@mail.gmail.com> Message-ID: On Fri, 12 Dec 2008 14:42:24 -0500, mercado wrote: > What is the best way to go about testing against different versions of > Python? For example, I have 2.5.2 installed on my machine (Ubuntu Hardy > 8.04), and I want to test a script against 2.5.2 and 2.5.1 (and possibly > other versions as well). definitely you need to have the test code first (unittest or doctest) then it's just a matter of running a shell script (or python script with subprocess) to check if the code generated any errors in any version. The problem might be how to install multiple sub-minor version of python. I often see a machine with multiple minor versions, but have no idea whether multiple sub-minor versions could coexists. From gnewsg at gmail.com Thu Dec 11 13:53:03 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 11 Dec 2008 10:53:03 -0800 (PST) Subject: How to know when it's possible to bind a socket on an unprivileged port? References: <799ba4ea-0ef8-499b-909e-507bf4abe4aa@z28g2000prd.googlegroups.com> Message-ID: On 11 Dic, 19:09, "Giampaolo Rodola'" wrote: > Hi, > For a purpose of testing I need a function which could tell me whether > it is possible to bind sockets on privileged ports or not. > I wrote down this simple function. It seems reasonably working to me > but I'd like to hear your opinion first. > > Thanks in advance. > > import socket, errno > > def bind_on_privileged_ports(port=21): > ? ? """Return True if it is possible to bind sockets on privileged > ? ? ports (< 1024).""" > ? ? try: > ? ? ? ? s = socket.socket() > ? ? ? ? s.bind(("", port)) > ? ? except socket.error, err: > ? ? ? ? if err[0] == errno.EACCES: > ? ? ? ? ? ? return False > ? ? s.close() > ? ? return True > Just to clarify: I don't really care *which* port to use for binding the socket. I just need to try to bind a socket on a free random privileged port and return True if that has been possible. --- Giampaolo http://code.google.com/p/pyftpdlib/ From luismgz at gmail.com Mon Dec 22 15:03:54 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Mon, 22 Dec 2008 12:03:54 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> <6r6hpfFfb643U3@mid.uni-berlin.de> <494E6FDA.4070401@mrabarnett.plus.com> <4585c27d-d7a9-480f-991c-a869161be55c@g38g2000yqn.googlegroups.com> <3392a51b-d3fd-4986-9c59-fecccc7272da@p2g2000prn.googlegroups.com> <6aad831b-80ce-40df-9b6e-571b1e822795@s1g2000prg.googlegroups.com> Message-ID: <1c7c21bd-62db-4397-a3cf-ed58431fb192@q26g2000prq.googlegroups.com> On Dec 22, 3:42?pm, cm_gui wrote: > Python is slow. Haven't you said that already? Well, you did it so many times that you convinced me... I'll tell the Google folks that they are a bunch of ignorant fools for choosing python. That's why their business is doing that bad. They will surely go to hell. This Google search engine and that silly site "youtube"... they won't work. THEY ARE SLOW! From castironpi at gmail.com Mon Dec 8 16:22:14 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 8 Dec 2008 13:22:14 -0800 (PST) Subject: Guido's new method definition idea References: <014a071a$0$20670$c3e8da3@news.astraweb.com> <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> Message-ID: On Dec 8, 2:55?pm, Arnaud Delobelle wrote: > anthony.to... at gmail.com writes: > > class C: > > ? ? def createfunc(self): > > ? ? ? ? def self.func(arg): > > ? ? ? ? ? ? return arg + 1 > > > Or, after the class definition is done, to extend it dynamically: > > > def C.method(self, arg): > > ? ? self.value = arg > > > ...which would be the equivalent of the following: > > > def method(self, arg): > > ? ? self.value = arg > > C.method = method > > What about the following then? > > functions = {} > > def functions['square'](x): > ? ? return x*x > > def functions['cube'](x): > ? ? return x**3 > > -- > Arnaud I agree that it's an extension (extrapolation) of the 'def self.meth' notation. For 'func_name', would you use the quoted string? Would you allow arbitrary expressions for the string, and the dictionary to add to? For example: def dict_val( )[ "name%i"% int_val( ) ]( self, arg, arg, arg ): ... It's not much worse than: (Unproduced) def anon( self, arg, arg, arg ): ... dict_val( )[ "name%i"% int_val( ) ]= anon #or if you really want the target before the def: @assign( dict_val( ), "name%i"% int_val( ) ) def _( self, arg, arg, arg ): ... And the latter are already both legal. But there have been PEPs accepted before that abbreviate 2 lines into 1. From inq1ltd at inqvista.com Thu Dec 11 16:16:13 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Thu, 11 Dec 2008 16:16:13 -0500 Subject: Problems running on HP Intel duo core machine In-Reply-To: <200812111458.16157.inq1ltd@inqvista.com> References: <200809221443.25765.inq1ltd@inqvista.com> <200812111458.16157.inq1ltd@inqvista.com> Message-ID: <200812111616.14104.inq1ltd@inqvista.com> Aaron, The TraceBack is : TraceBack: File win32ui.pyc, line 12, in File win32ui.pyc Line 10, in _load ImportError: DLL Load Failed: The specified module could not be found. On Thursday 11 December 2008 14:58, jim-on-linux wrote: > py help, > > I produced a program that runs on windows. > One client is using an HP machine with an Intel cpu > E2200 @ 2.2ghz., and with .99 G ram. > The machine is using Win XP Pro 32 bit OS with > service pack 2 > > I ran Dependency Walker and everything is OK. > > I used py2exe to build the exe file with bundle > files:1 and also 3, with the same traceback results. > > I created a test print module that imports both > win32api and win32ui modules and its only job is to > print a page of text. > > The first module that is imported is win32api. > line 8 of that module adds to the path the module > named 'win32api.pyd'. > The import is is completed without error. > > The next module that is imported is win32ui. > line 8 of that module adds to the path a module > named 'win32ui.pyd'. > The search for the win32ui.pyd module seems to be > the cause of the problem. > Traceback: > ImportError: Dll load failed: The specified module > could not be found. > > Both modules 'win32api.pyd' and win32ui.pyd are in > the same directory. > > Below is a copy of the win32ui.py module. The only > difference between this and win32api.py module is > the name that is installed when creating the path. > > def __load(): > import imp, os, sys > try: > dirname = > os.path.dirname(__loader__.archive) except > NameError: > dirname = sys.prefix > path = os.path.join(dirname, 'win32ui.pyd') > #print "py2exe extension module", __name__, > "->", path > mod = imp.load_dynamic(__name__, path) > ## mod.frozen = 1 > __load() > del __load > > The only difference I can find is that this program > works fine on every machine that it is tried on > except the HP duo core machine, with Intel E2200 > cpu. Somehow the path is affected? > > I've tried all of the suggestions and checked a lot > of things but I'm not there yet, Any suggestions > would be helpful. > > > jim-on-linux > > > > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From sjmachin at lexicon.net Mon Dec 1 18:40:37 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 1 Dec 2008 15:40:37 -0800 (PST) Subject: newbie question: parse a variable inside an RE? References: <6pj4svF832i3U1@mid.uni-berlin.de> Message-ID: On Dec 2, 8:56?am, "Diez B. Roggisch" wrote: > joemacbusin... at gmail.com schrieb: > > > Hi All, > > > How do I parse a variable inside an RE? > > What is the re.search() syntax when your > > search string is a variable? > > It's easy to parse hardcoded RE's but not > > if you use a variable. > > Both are exactly equal in difficulty. > > > > > > > Here is my code, input and runtime: > > > $ cat test45.py > > #!/usr/bin/python > > > import re > > > resp = raw_input('Selection: ') > > newresp = resp.strip() > > print "you chose ", newresp > > > fname = open('test44.in') > > for I in fname: > > # ? ?if re.search('^newresp', "%s"%(I)): ? ? # returns nothing > > # ? ?if re.search(^newresp, "%s"%(I)): ? ? ? # syntax error > > ? ? if re.search("^newresp", "%s"%(I)): ? ? ?# returns nothing > > ? ? ? ? print I, > > How should python know that you want the newresp being expanded? And not > that you want to search for the word "newresp"? > > You need to use the *variable* newresp: > > if re.search(newresp, I): ... > > If you want to alter it to have a "^" prepended before you use it, you > need to do so: > > newresp = "^" + newresp > > And as show above, > > "%s" % I > > is nothing but I - no need for the string-interpolation. In fact what the OP is trying to do amounts to a convoluted version of I.startswith(newresp) which probably isn't his real requirement anyway :-( From febaen at gmail.com Sat Dec 13 10:21:59 2008 From: febaen at gmail.com (feba) Date: Sat, 13 Dec 2008 07:21:59 -0800 (PST) Subject: Need help improving number guessing game References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> Message-ID: <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> #!/usr/bin/python #Py3k, UTF-8 import random def startup(): print("WELCOME TO THE SUPER NUMBER GUESSING GAME!") global pnum, play, player, p1sc, p2sc pnum = int(input("1 OR 2 PLAYERS?\n> ")) play = True player = "P1" #P1 goes first p1sc = 0 #Number of times... p2sc = 0 #player guessed before opponent def setup(): global target, guess, a, b a = 1 b = 99 target = random.randint(a, b) guess = 0 #Won't fall between 1 and 99 def playerswap(): global player if player == "P1": player = "P2" else: player = "P1" def guessing(): global guess, player, target, play, pnum, p1sc, p2sc, a, b guess = int(input("[%s-%s]%s>> " % (a, b, player))) #keeps the user aware of min/max if guess == target: if pnum == 1: print("CONGRATULATIONS!" ) else: if player == "P1": p1sc += 1 else: p2sc += 1 print("CONGRATULATIONS %s! SCORE -- P1:%s P2:%s" %(player, p1sc, p2sc)) playover = input("PLAY AGAIN? Y/N: ") if playover.strip().lower() == "y": play = True setup() else: play = False elif guess > b: print("NUMBER MUST BE IN RANGE") elif guess <= a: print("NUMBER MUST BE IN RANGE") elif guess > target: print("TOO HIGH") b = guess else: print("TOO LOW") a = guess if pnum ==2: playerswap() startup() setup() while play is True: guessing() This is what I have so far. better? worse? I'm guessing a mix of the two. It took me a lot longer to get working, but I think it works better. I also added a bit that tells you if you go higher or lower than an already specified too high/low markers; although it doesn't make you repeat that turn. I'm not sure if all those 'globals' are bad, but they don't seem like they're something that should be good. Functionally, it seems to work just fine. From rt8396 at gmail.com Sat Dec 20 21:23:00 2008 From: rt8396 at gmail.com (r) Date: Sat, 20 Dec 2008 18:23:00 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <015d9ca5$0$20656$c3e8da3@news.astraweb.com> Message-ID: <60b419d3-4cbc-4bba-af79-a6d6146ac472@e6g2000vbe.googlegroups.com> Answering a question with a question, that leaves me with a question of my own?? > Instead of just whinging, how about making a suggestion to fix it? Go on, > sit down for an hour or ten and try to work out how a BINARY OPERATOR > like % (that means it can only take TWO arguments) can deal with an > arbitrary number of arguments, *without* having any special cases. Instead of being a blind fanboy and chastising everyone who dares to question pydev, Guido, or YOU... why don't you offer a good rebuttal? If i did not give a rats behind about Python i would not be here arguing with you. I would give up and "require" my packages ;). I prefer to import I believe Python has the best chance of surviving and becoming the king of high level languages, IF we don't muck it up! From stepp.aaron at gmail.com Mon Dec 22 22:32:17 2008 From: stepp.aaron at gmail.com (Aaron Stepp) Date: Mon, 22 Dec 2008 22:32:17 -0500 Subject: iterating initalizations In-Reply-To: <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> Message-ID: On Dec 22, 2008, at 10:15 PM, r wrote: > I can't check you code because i don't have these modules but here is > the code with proper indention > > import random > from rtcmix import * > from chimes_source import * > from rhythmblock import * > from pitchblock import * > indexrand = random.Random() > indexrand.seed(2) > rhythm = rhythmBlock() > pitch = pitchBlock() > > class pitchAndRhythm: > def __init__(self): > self.__abet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' > def listCreate(self, num): > if num > 25: > print "Oops. This won't work" > else: > for a in range(num): > b = indexrand.randint(0, 3) > c = indexrand.randint(0, 7) > index = self.__abet[a] > index = [ ] > index = index.append(rhythm.rhythmTwist(b, c)) > > take 2: notice the "(" and ")" around the arg to __init__ Thanks for the help so far, I think I'm starting to get a hang of the syntax. I think I need to state my goal more clearly. Instead of writing a long list of initializations like so: A = [ ] B = [ ] ... Y = [ ] Z = [ ] I'd like to save space by more elegantly turning this into a loop. If I need to just write it out, I guess that's ok... but it would be much cleaner. I'm a composer, not a programmer, so some of this is quite above me. I usually ask as a last resort, but I've been through the tutorial and didn't find this. I've got a couple python books, but I'd like to finish this piece sooner than later. Thanks! AS From gagsl-py2 at yahoo.com.ar Wed Dec 31 13:57:03 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 31 Dec 2008 16:57:03 -0200 Subject: MemoryError when list append... plz help References: <016b25a5$0$6988$c3e8da3@news.astraweb.com> Message-ID: En Wed, 31 Dec 2008 06:34:48 -0200, Steven D'Aprano escribi?: > Each time you are appending to the list, you append a tuple: > > ((i, j), sim) > > where sim is a float and i and j are ints. How much memory does each of > those take? > >>>> sys.getsizeof( ((0, 1), 1.1) ) > 32 (On Windows, 32 bits, I get 36) > So each entry requires 32 bytes. 60 million times 32 bytes = almost 2GB > alone. Plus the list itself will require (approximately) between 230MB > and 460MB just for the pointers. That was just the size of the "outer" tuple; you have to add the size of each element too. First one is another 2-item tuple (36 bytes too) plus its elements (two integers, 12 bytes each). Second element is a float and takes 16 bytes. Total: 112 bytes per item; the final size may be a bit smaller because some objects may be shared (e.g. small integers) -- Gabriel Genellina From R.Brodie at rl.ac.uk Wed Dec 17 12:17:02 2008 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Wed, 17 Dec 2008 17:17:02 -0000 Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> Message-ID: "walterbyrd" wrote in message news:518b9dd9-69c5-4d5b-bd5f-ad567be6249b at b38g2000prf.googlegroups.com... > However in the methods are within a class, the scoping seems to work > differently. Not really, self is a formal parameter to the function. It would be a strange language where a function's own arguments weren't in scope. > def b(self): > print self.x Try changing it to: def b(somethingotherthanself): print self.x From steve at REMOVE-THIS-cybersource.com.au Sun Dec 14 20:48:43 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Dec 2008 01:48:43 GMT Subject: [OT] stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> Message-ID: <0155aef3$0$6988$c3e8da3@news.astraweb.com> On Sun, 14 Dec 2008 21:42:33 +0000, Lie Ryan wrote: > I'm sure someday, there will be a student who comes to class late and > sees this on the board: "Design a comparison sorting algorithm that has > better than O(n * log n) lower bound complexity." The unsuspecting > student copied it, thinking it's a homework. He crunched to the problem, > going to various meditations and yoga classes before finding a way that > works just before deadline, handing out the work a bit late. Six weeks > later, his professor called and said: "You know what you just did? > You've just found a problem that was supposed to be an example of > unsolvable problem." > > It has happened before, why not again? > http://www.snopes.com/college/homework/unsolvable.asp Because as you described it, it *hasn't* happened before. There is the world of difference between an unsolvABLE problem and one that is unsolvED. All the positive thinking in the world won't help you: * make a four-sided triangle; * write down a completely accurate rational expansion for pi or the square-root of 2; * split a magnet into two individual poles; * find an integer solution to 3*n = 7; * solve the Halting Problem; * fit n items into n-1 pigeonholes without putting two items in the one pigeonhole; * create a compression algorithm that will compress random data; * or design a comparison sort which does fewer than O(n*log n) two-way comparisons in the worst case, or fewer than O(n) comparisons in the best case. Some things really don't have a solution, no matter how much power of positive thinking you apply to it. -- Steven From skip at pobox.com Mon Dec 8 19:59:52 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 8 Dec 2008 18:59:52 -0600 Subject: how to add command line flags to distutils setup script? Message-ID: <18749.49928.182089.131317@montanaro-dyndns-org.local> Suppose I have a setup.py script which imports distutils.core.setup. Is there some way to, for example, add a command line flag to the build command so that I can run it like python setup.py build --frob=True ? I see that the setup function takes an options parameter but the distutils.core.setup doc says little other than that it is a string and "default options for the setup script". There is also a script_args parameter, but the docs are similarly mum about what exactly it's used for. A posting by Greg Ward announcing it in Aug 2000 says script_args is a sub for sys.argv[1:]. Pointers to other documentation or tutorials on the topic cheerfully appreciated. Thanks, -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From torriem at gmail.com Fri Dec 19 12:27:27 2008 From: torriem at gmail.com (Michael Torrie) Date: Fri, 19 Dec 2008 10:27:27 -0700 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <494BD97F.5080205@gmail.com> walterbyrd wrote: > On Dec 19, 9:13 am, "Giampaolo Rodola'" wrote: >> You can use the old 2.x syntax also in Python 3.x: > > Yeah, but it's deprecated, and - as I understand it - may be removed > completely in future versions. Also, in the future, if you are working > with code from another developer, it's likely that developer will use > the new format. I suppose you can use both - but what an awful mess > that would be. > > It seems to me that 3.0 is changing a lot of non-problems. And it's > going to be slower to boot. How is this? With projects like PyPy eventually enabling the JIT'ing of python3 code, I don't see how this is going to be "slower." If anything we have a python that can be made to run faster than ever before. Please qualify your remarks. Are you a Python core developer? From kyosohma at gmail.com Mon Dec 8 12:19:15 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 8 Dec 2008 09:19:15 -0800 (PST) Subject: Calling C# COM (.NET) from python References: Message-ID: <5788ade5-3334-47a2-8289-03dac8b193bc@41g2000yqf.googlegroups.com> On Dec 8, 10:53?am, Andrew Falanga wrote: > Hi, > > I've never programmed in python and only have a small understanding of > what is wrapped up in the terms COM and .NET. ?Is there a way of using > python to get a hold of objects written in C# as COM objects using > python? ?I'm looking for ways to avoid VBScript (which, after a couple > of weeks, I've determined to be horrid). ?That is, is there a way of > getting at COM objects in python that's similar to doing a > CreateObject call in VBScript (http://msdn.microsoft.com/en-us/library/ > dcw63t7z.aspx)? > > Thanks, > Andy You're probably looking for the PyWin32 package (AKA: Python for Windows extensions). It's an external package for Python created mainly by Mark Hammond. You can find it here: http://sourceforge.net/projects/pywin32/ It's a loose wrapper to the win32 bindings. It has a win32com module in it. You can usually take some VB type code and tweak it slightly to work with Python. There's some docs here: http://docs.activestate.com/activepython/2.4/pywin32/win32_modules.html You may also be able to use ctypes. Regardless, the PyWin32 package has a great mailing list with helpful people that I highly recommend: http://mail.python.org/mailman/listinfo/python-win32 Other than that, you have the option of using IronPython which can actually import .NET modules itself. I've messed with it a little, but I'm not fluent enough in .NET to be able to use a lot of its capabilities. Regardless, you should read up on it as it offers lots of interesting capabilities: http://www.codeplex.com/IronPython Mike From __peter__ at web.de Mon Dec 1 15:59:17 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 01 Dec 2008 21:59:17 +0100 Subject: Chmod to a group only References: <83e430f3-0c4c-4aae-84e3-7a8bb6dc1b74@t11g2000yqg.googlegroups.com> Message-ID: Kless wrote: > On 1 dic, 18:17, Kless wrote: >> How to chmod a file to: o-rwx ? (to change only the others mode) >> >> os.chmod(fname, ) >> >> I was reading this [1], but the truth is that anything as 'S_IRUSR' >> doesn't help enought. >> >> [1]http://www.python.org/doc/2.5.2/lib/os-file-dir.html > > I have tried: > > mode = os.stat(fname).st_mode > os.chmod(fname, mode | stat.S_IRWXO) => Changes to o+rwx How did the result of the above differ from what you want? The way I read your original post something like the above would have been my answer... Peter From rt8396 at gmail.com Sat Dec 6 11:52:53 2008 From: rt8396 at gmail.com (r) Date: Sat, 6 Dec 2008 08:52:53 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> <00ab327a-c3fc-4b15-a084-4f8c6aed6a8e@o2g2000yqd.googlegroups.com> <8119ab7e-09f1-44de-bdbc-8fdff969d9e4@33g2000yqm.googlegroups.com> <36056737-3c78-499a-a81d-f6241e904460@t11g2000yqg.googlegroups.com> Message-ID: [Lie] Sketchup's target users is not power users but those who need quick sketches, so scripting isn't an extremely important feature in Sketchup.[/Lie] Your Wrong, SketchUp PRO is marketed at ACAD users and other high profile CAD and CAM applications. SketchUp models can be exported to ACAD and ACAD models can be imported to SketckUp. Anyone who would say scripting is not important to a modeler has never spent much time modeling. Scripting is of upmost importance to the usefulness of SketchUP(or any CAD/CAM app), without it more advanced modeler types would not be interested. As far as Google earth goes...that is more a marketing ploy, and that Google is a cool company, rather than the primary use for SketchUP...and it has worked well! Your Right, creating a Python extension and getting people interested, is the gateway to convincing SketchUp DEV to include Python alongside Ruby.(and even if they don't it won't matter once the wrapping is there). I hang out a lot in the SketchUp Ruby Group, and a lots of people are turned off by Ruby. I think Python could help them get going. This is the reason for my crusade. Not just for me...but because there is a real void python can fill in SketchUp. Once there is a python wrapping of Ruby API I will take over, writing tutorials, writing example code, fielding Python related questions...This is my commitment to this project. I AM willing to work extremely hard to make this happen. If just ONE other person would get on board this will happen. No...I DO NOT know how to wrap the Ruby API myself...but once the Python wrapping is there i will take over and bring this to life. From that point on, i will not need any help. I will maintain the code, And i will be happy to let this person(s) take ALL the credit for bringing Python to SketchUp...I do not want the credit. From arnodel at googlemail.com Wed Dec 17 05:46:42 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 17 Dec 2008 10:46:42 +0000 Subject: Need help improving number guessing game References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> <01564c98$0$21844$c3e8da3@news.astraweb.com> <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> <4946df78$0$19771$426a74cc@news.free.fr> <1f33580b-84f9-4059-a0f0-b6a8d71325af@b38g2000prf.googlegroups.com> <4947742c$0$25951$426a34cc@news.free.fr> Message-ID: "D'Arcy J.M. Cain" writes: > On Tue, 16 Dec 2008 13:59:24 -0800 > Scott David Daniels wrote: >>> > def yesno(s): >> > s = s.strip().lower() >> > if not s in ("y", "n"): There was a thread about "is not" recently. Python also allows "not in". if s not in ("y", "n"): > You could also do this to be a little more user friendly: > if not (s and s[0] in ("y", "n")): Or: if s[:1] not in ("y", n"): -- Arnaud From tino at wildenhain.de Mon Dec 22 01:52:28 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 22 Dec 2008 07:52:28 +0100 Subject: Are Django/Turbogears too specific? In-Reply-To: <2B198A4F-5911-456D-A45B-E073DB121446@semanchuk.com> References: <494eb16e$0$22710$426a74cc@news.free.fr> <2B198A4F-5911-456D-A45B-E073DB121446@semanchuk.com> Message-ID: <494F392C.5060201@wildenhain.de> Philip Semanchuk wrote: ... > > I prefer Mako over the other template languages I've seen. From what I can tell Mako is nearly identical to all other template languages you might have seen (e.g. PHP style tags). Thats why I personally would not consider it. Its just much of a hassle to mix code and design this way. I prefer TAL (template attribute language, ZPT) [1] much over the other attempts I've seen ( and I've seen a lot) Cheers Tino [1] http://en.wikipedia.org/wiki/Template_Attribute_Language -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From hjtoi-better-remove-when_replying at comcast.net Wed Dec 10 14:16:16 2008 From: hjtoi-better-remove-when_replying at comcast.net (Heikki Toivonen) Date: Wed, 10 Dec 2008 11:16:16 -0800 Subject: pexpect and inconsistent exit codes Message-ID: I don't seem to be able to figure out how to get the exit values of commands executed with pexpect reliably. Here's first with regular shell: heikki at ubuntu:~$ true; echo $? 0 Let's try with pexpect. Below is the program: ---CLIP--- import sys, pexpect cmd = "true" print 'cmd=', cmd child = pexpect.spawn(cmd, logfile=sys.stdout) child.close() print 'child exitstatus=', child.exitstatus print 'child signalstatus=', child.signalstatus print 'child status=', child.status ---CLIP--- The output: (fabexp)heikki at ubuntu:~/python_virtualenvs/fabexp$ python dep.py cmd= true child exitstatus= 1 child signalstatus= None child status= 256 (fabexp)heikki at ubuntu:~/python_virtualenvs/fabexp$ python dep.py cmd= true child exitstatus= 0 child signalstatus= None child status= 0 (fabexp)heikki at ubuntu:~/python_virtualenvs/fabexp$ python dep.py cmd= true child exitstatus= None child signalstatus= 1 child status= 1 I have tried various other commands, and I just can't seem to be able to get reliable exit codes from commands I execute. Any ideas what is going on? -- Heikki Toivonen - http://heikkitoivonen.net From bkamrani at gmail.com Tue Dec 2 06:41:29 2008 From: bkamrani at gmail.com (bkamrani at gmail.com) Date: Tue, 2 Dec 2008 03:41:29 -0800 (PST) Subject: performance question: dictionary or list, float or string? Message-ID: Hi Python gurus! I'm going to read in an Ascii file containing float numbers in rows and columns (say 10 columns 500000 rows) for further numerical process. Which format is best to save them in, eg, dictionary, list, or numpy array when it comes to performance? Will it be beneficial to convert all strings to float directly after reading or it doesn't matter to save them as string and thereafter when it comes to calculation convert them to floats? Thank you! /Ben From pavlovevidence at gmail.com Sat Dec 6 16:01:53 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 6 Dec 2008 13:01:53 -0800 (PST) Subject: Learning Python now coming from Perl References: Message-ID: On Dec 6, 12:30?pm, Roy Smith wrote: > In article , a... at pythoncraft.com (Aahz) > wrote: > > > In article , > > Bertilo Wennergren ? wrote: > > > >I don't suppose there is any introductory material out there that is > > >based on Python 3000 and that is also geared at people with a Perl > > >background? Too early for that I guess.. > > > Honestly, the differences between 2.x and 3.0 are small enough that it > > doesn't much matter, as long as you're not the kind of person who gets > > put off by little problems. ?Because so much material is for 2.x, you > > may be better off just learning 2.x first and then moving to 3.x. > > I'm not sure I agree. ?If you're starting out, you might as well learn the > new stuff. ?Then there's no need to unlearn the old way. One disadvantage of learning Python 3 first is the availability of third-party libraries (especially extension libraries), most of which will not be updated for Python 3.x for quite a while. Also, I don't think it's really advisable to be completely ignorant of the 2.x difference even if one intends to start with 3.0. There is a lot of code and material out there for 2.x, and until these start to be widely available for 3.x, people will sometimes have to make do with the 2.x stuff. Carl Banks From lists at cheimes.de Tue Dec 16 13:12:08 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 16 Dec 2008 19:12:08 +0100 Subject: Python Dictionary Algorithm Question In-Reply-To: <3ca641b40812160951h3a13e69am291afb02965451a7@mail.gmail.com> References: <3ca641b40812160951h3a13e69am291afb02965451a7@mail.gmail.com> Message-ID: Brigette Hodson schrieb: > Hello! I am in a beginning algorithms class this semester and I am working > on a presentation. I want to discuss in some detail the algorithm python > uses to determine the hash function for python dictionaries. Does anyone > know what this algorithm is? Or where I can go to find information on it? Python's dict implementation doesn't have its own hashing algorithm. It completely relies upon the __hash__() function and the __eq__() comparison function of the objects that are used as keys. The source repository contains a document with some insights. Make your you read dictnotes.txt and the cmments in dictobject.c http://svn.python.org/view/python/branches/release25-maint/Objects/ Christian From stef.mientki at gmail.com Mon Dec 1 16:22:53 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 01 Dec 2008 22:22:53 +0100 Subject: Why doesn't doc has predifined name and location ? Message-ID: <493455AD.4040306@gmail.com> hello, I'm very satisfied about the great standardization of doc strings in python. Now in contrast to that, the general documentation of libraries, either in plain text, html, pdf, chm, ... doesn't have a standarized name nor location. Why is that ? thanks, Stef Mientki From castironpi at gmail.com Thu Dec 18 05:35:58 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 18 Dec 2008 02:35:58 -0800 (PST) Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> Message-ID: <51866e70-8a6e-4338-94bd-59913990e342@k36g2000pri.googlegroups.com> On Dec 17, 7:16?pm, "Gabriel Genellina" wrote: > En Wed, 17 Dec 2008 22:46:32 -0200, Aaron Brady ? > escribi?: > > > > > On Dec 17, 5:05?pm, "Gabriel Genellina" > > wrote: > >> En Wed, 17 Dec 2008 12:21:38 -0200, Jeremy Sanders ? > >> escribi?: > > >> > It would be nice if Python created pipes that are properly ? > >> inheritable by > >> > default by child processes, as they're mostly used for IPC. > > >> I'd say it is a bug in os.pipe implementation; they should be ? > >> inheritable ? > >> by default, as in posix (after all, the code is in "posixmodule.c"). > > > The code looks like this: > > > ? ?ok = CreatePipe(&read, &write, NULL, 0); > > ? ?Py_END_ALLOW_THREADS > > ? ?if (!ok) > > ? ? ? ? ? ?return win32_error("CreatePipe", NULL); > > ? ?read_fd = _open_osfhandle((Py_intptr_t)read, 0); > > ? ?write_fd = _open_osfhandle((Py_intptr_t)write, 1); > > > 'If lpPipeAttributes is NULL, the handle cannot be inherited.' ?You > > could populate a 'SECURITY_ATTRIBUTES' structure, or call > > DuplicateHandle on both of them. > > > A patch would look like this: > > > SECURITY_ATTRIBUTES sattribs; > > sattribs.nLength = sizeof(sattribs); > > sattribs.lpSecurityDescriptor = NULL; > > sattribs.bInheritHandle = TRUE; > > ok = CreatePipe(&read, &write, &sattribs, 0); > > Yes, that's exactly how os.popen does it (in posixmodule.c) > > > This still doesn't answer whether the file descriptor return by > > '_open_osfhandle' can be inherited too. > > It doesn't matter. The OS only cares about file handles, not C RTL ? > structures. > > -- > Gabriel Genellina Ah, I see. Was it an executive decision about what is Pythonic, or just a bug? Do you think the patch would be accepted? I probably ought to mimic a small Python embedding to see if it needs anything else. From gagsl-py2 at yahoo.com.ar Sat Dec 27 15:03:13 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 27 Dec 2008 18:03:13 -0200 Subject: ctypes & strings References: <334452.47084.qm@web30003.mail.mud.yahoo.com> <000f01c96822$5c300f00$0d00a8c0@hendrik> Message-ID: En Sat, 27 Dec 2008 10:54:32 -0200, Hendrik van Rooyen escribi?: > The c routine will actually break Python's normal string > immmutability and give you back a changed ins. ...so don't do that! If you require a mutable string to pass to C functions, use ctypes.create_string_buffer() > It is in general not a good idea to change the passed string > like I am doing - but you wanted to know how > to pass a python string, and the outs example should get > you going - a string is an array of characters in c... Hmmm, I don't think posting a potentially harmful example is actually a good idea... -- Gabriel Genellina From lewis.sarah93 at yahoo.com Fri Dec 5 00:11:00 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 21:11:00 -0800 (PST) Subject: Reduce Debt Message-ID: Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com Earn From bdesth.quelquechose at free.quelquepart.fr Sun Dec 14 11:23:55 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 14 Dec 2008 17:23:55 +0100 Subject: execution time In-Reply-To: References: Message-ID: <494540d1$0$1127$426a74cc@news.free.fr> David Hl??ik a ?crit : > Hi guys, > > #! /usr/bin/python > > import random > import bucket2 > > data = [ random.randint(1,25) for i in range(5)] > print "random data : %s" % data > print "result: %s" %bucket2.sort(data) > > How to write a test script which will outputs execution time for > bucket2.sort(data) ? http://docs.python.org/library/timeit.html HTH From sln at netherlands.com Tue Dec 9 21:46:02 2008 From: sln at netherlands.com (sln at netherlands.com) Date: Wed, 10 Dec 2008 02:46:02 GMT Subject: Mathematica 7 compares to other languages References: <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> <0201522a-b15a-4401-a208-5d9af70bdd74@w24g2000prd.googlegroups.com> <8947211d-2ee8-403a-8c8a-c7599aea5f80@k24g2000pri.googlegroups.com> <9f86f78c-776e-4793-b931-67dadc0e24f1@i24g2000prf.googlegroups.com> Message-ID: On Tue, 9 Dec 2008 15:01:11 -0800 (PST), Xah Lee wrote: > >On Dec 8, 4:56 pm, Jon Harrop wrote: >> Xah Lee wrote: >> > A moron, wrote: >> > > You failed the challenge that you were given. >> >> > you didn't give me a challenge. >> >> Thomas gave you the challenge: >> >> "What I want in return is you to execute and time Dr. Harrop's original >> code, posting the results to this thread... By Dr. Harrop's original code, >> I specifically mean the code he posted to this thread. I've pasted it below >> for clarity.". >> >> Thomas even quoted my code verbatim to make his requirements totally >> unambiguous. Note the parameters [9, 512, 4] in the last line that he and I >> both gave: >> >> AbsoluteTiming[Export["image.pgm", Graphics at Raster@Main[9, 512, 4]]] >> >> You have not posted timings of that, let alone optimized it. So you failed. > >The first parameter to your Main specifies some kinda recursively >stacked spheres in the rendered image. The second parameter is the >width and height of the pixels in the rendered image. > >I tried to run them but my computer went 100% cpu and after i recall 5 >min its still going. So, i reduced your input. In the end, with >reduced input, it shows my code is 5 times faster (running Mathematica >v4 on OS X 10.4.x with PPC 1.9 GHz), and on the other guy's computer >with Mathematica 6 he says it's twice as fast. > >Given your code's nature, it is reasonably to assume that with your >original input my code would still be faster than yours. You claim it >is not or that it is perhaps just slightly faster? > >It is possible you are right. I don't want to spend the energy to run >your code and my code and possible hog my computer for hours or >perhaps days. As i said, your recursive Intersect is very badly >written Mathematica code. It might even start memory swapping. > >Also, all you did is talking bullshit. Thomas actually is the one took >my challenge to you and gave me $20 to prove my argument to YOU. His >requirement, after the payment, is actually, i quote: > >?Alright, I've sent $20. The only reason I would request a refund is >if you don't do anything. As long as you improve the code as you've >described and post the results, I'll be satisfied. If the improvements >you've described don't result in better performance, that's OK.? > >He haven't posted since nor emailed me. It is reasonable to assume he >is satisfied as far as his payment to me to see my code goes. > >You, kept on babbling. Now you say that the input is different. Fine. >How long does that input actually take on your computer? If days, i'm >sorry i cannot run your toy code on my computer for days. If in few >hours, i can then run the code overnight, and if necessary, give you >another version that will be faster with your given input to shut you >the fuck up. > >However, there's cost to me. What do i get to do your homework? It is >possible, that if i spend the energy and time to do this, then you >again refuse to acknowledge it, or kept on complaining about something >else. > >You see, newsgroup is the bedrock of bullshit. You bullshit, he >bullshits, everybody brags and bullshit because there is no stake. I >want sincerity and responsibility backed up, with for example paypal >deposits. You kept on bullshitting, Thomas gave me $20 and i produced >a code that reasonably demonstrated at least how unprofessional your >Mathematica code was. > >Here's the deal. Pay me $20, then i'll creat a version of Mathematica >code that has the same input as yours. Your input is Main[9, 512, 4], >as i have exposed, your use of interger in the last part for numerical >computation is Mathematica incompetence. You didn't acknowledge even >this. I'll give a version of Mathematica with input Main[9, 512, 4.] >that will run faster than yours. If not, money back guaranteed. Also, >pay me $300, then i can produce a Mathematica version no more than 10 >times slower than your OCaml code, this should be a 70000 times >improvement according to you. Again, money back guarantee. > >If i don't receive $20 or $300, this will be my last post to you in >this thread. You are just a bullshitter. > >O wait... my code with Main[9, 512, 4.] and other numerical changes >already makes your program run faster regardless of the input size. >What a motherfucking bullshit you are. Scratch the $20. The $300 >challenge still stands firm. > > Xah >? http://xahlee.org/ > >? Ad hominem From sjmachin at lexicon.net Sat Dec 20 21:31:48 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 20 Dec 2008 18:31:48 -0800 (PST) Subject: PIL on 3.x? References: <3892784c-ddf4-4451-bcfd-dbc58b9b55f8@e1g2000pra.googlegroups.com> Message-ID: <56c72738-3f92-4c88-9e51-3a592f661b11@r15g2000prd.googlegroups.com> On Dec 21, 12:32?pm, "Daniel Fetchinson" wrote: > >> Does anyone know if PIL will be ported to the 3.x branch? > > > Have you considered e-mail to the author? > > No, I haven't because in my experience open source software authors > prefer to keep discussion of their software on mailing lists, forums, > etc, where others can benefit from the answers too. True, so try a forum where the author has been active within the last week: http://mail.python.org/mailman/listinfo/image-sig From kyosohma at gmail.com Thu Dec 11 13:50:25 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 11 Dec 2008 10:50:25 -0800 (PST) Subject: Python to open command script file References: Message-ID: On Dec 11, 12:04?pm, dave rose wrote: > Hello all > ?I would like to know how to do the following. ?I'd like to have a generic > python program that the user will open a command-script file to do actions. > > So, my python program will get a list of servers, enumerate them within a > checklistbox in wxpython. ?Then I want to open a command-file that will run > against each selected server that will look like this: > > ---------------------------SAMPLE------------------------ > copy abc.xyz from c:\source to u:\target > copy all ? ? from c:\source to u:\target > unload netshld from server1 > -------------------------END SAMPLE---------------------- > > (where I have a class serverfuncs, where I can: > s = serverfuncs() > s.unload('', '') > > Really, I can do all the actions, but I don't know how to trigger them from an > independent script file. > > Thanks! > -Dave I usually use python's included shutil module for copying files and directories. I think that would be a little more cross-platform friendly. However, if you want to execute those commands above, try using the subprocess module or os.system. Mike From fred at gmail.com Wed Dec 24 17:11:22 2008 From: fred at gmail.com (Dan) Date: Wed, 24 Dec 2008 17:11:22 -0500 Subject: Python 3 and my Mac (Leopard) Message-ID: <4952b38d$0$20300$607ed4bc@cv.net> Wanted to learn python, got Mark Summerfield's new book "Programming in Python 3". Having a hard time getting python 3 and IDLE working on my Mac with Leopard. The mac "resources" on the python.org site seem a bit out of date, and don't really mention python 3. Are there any resources out there? Is the python community just not interested in Macs? I've tried googling and the usual search strategies. Any help would be appreciated. DAN From bdesth.quelquechose at free.quelquepart.fr Tue Dec 9 14:39:35 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 09 Dec 2008 20:39:35 +0100 Subject: When (and why) to use del? In-Reply-To: References: Message-ID: <493ed72f$0$7090$426a74cc@news.free.fr> malkarouri a ?crit : (snip) > The del statement doesn't actually free memory. It just removes the > binding from the corresponding namespace. So in your first example, > my_string cannot be used after the deletion. Of course, if the string > referenced by my_string was referenced by some other name then it will > still stay in memory. And even if it wasn't, and as such ends up being garbage-collected, this doesn't mean the allocated memory will go back to the system. (snip) From robert.kern at gmail.com Mon Dec 8 02:13:26 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 08 Dec 2008 01:13:26 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: References: <014c593e$0$20670$c3e8da3@news.astraweb.com> Message-ID: James Stroud wrote: > Robert Kern wrote: >> James Stroud wrote: >>> py> 112 = [1, y] >>> py> y in 112 >>> Traceback (most recent call last): >>> File "", line 1, in >>> ValueError: The truth value of an array with more than one element is... >>> >>> but not >>> >>> py> ll1 = [y,1] >>> py> y in ll1 >>> True >>> >>> It's this discrepancy that seems like a bug, not that a ValueError is >>> raised in the former case, which is perfectly reasonable to me. >> >> Nothing to do with numpy. list.__contains__() checks for identity with >> "is" before it goes to __eq__(). > > ...but only for the first element of the list: > > py> import numpy > py> y = numpy.array([1,2,3]) > py> y > array([1, 2, 3]) > py> y in [1, y] > ------------------------------------------------------------ > Traceback (most recent call last): > File "", line 1, in > : The truth value of an array with more > than one element is ambiguous. Use a.any() or a.all() > py> y is [1, y][1] > True > > I think it skips straight to __eq__ if the element is not the first in > the list. No, it doesn't skip straight to __eq__(). "y is 1" returns False, so (y==1) is checked. When y is a numpy array, this returns an array of bools. list.__contains__() tries to convert this array to a bool and ndarray.__nonzero__() raises the exception. list.__contains__() checks "is" then __eq__() for each element before moving on to the next element. It does not try "is" for all elements, then try __eq__() for all elements. > That no one acknowledges this makes me feel like a conspiracy > is afoot. I don't know what you think I'm not acknowledging. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From manu3d at gmail.com Thu Dec 11 14:04:17 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 11 Dec 2008 11:04:17 -0800 (PST) Subject: Preventing execution of a method References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> <764daeef-bfbe-411a-8521-bb114321e4ac@b38g2000prf.googlegroups.com> <19304f8c-e34f-4aa9-8df2-6a7d3553007a@e1g2000pra.googlegroups.com> <2eed8876-94d2-4304-88a5-eb4a78b4f41d@33g2000yqm.googlegroups.com> Message-ID: <307fe197-1b42-4305-af0e-94b7ebe3ce70@r15g2000prh.googlegroups.com> Thank you all for the confirmation and the suggestions (including the tangential ones: I didn't know one could remove your his own posts!). As much as I really like Python (which I've been using full-time only for the past two months) I really wish it did have regular private/ protected/public methods. I'm building an application that can be extended by the users and I really wish there was a solid way to prevent them from accessing parts of the application that they shouldn't access or to provide read-only access. I.e. right now I'm working on the graphical client which potentially could be rewritten entirely by the users. It is necessary and perfectly reasonable for the client module to access some of the objects to be represented graphically, but those objects shouldn't be modifiable by it. I now wonder, would developing the graphical client as an entirely separate application, communicating with the server via the localhost network interface and messages, solve the problem? Would it keep the objects of the two applications (server/client) entirely separate? Manu From deets at nospam.web.de Mon Dec 8 14:57:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 Dec 2008 20:57:31 +0100 Subject: easy_install of module produces un-importable result In-Reply-To: References: Message-ID: <6q5chbFast45U1@mid.uni-berlin.de> Val schrieb: > I've written my first module, " " and uploaded it as an egg to > PyPI. I can use easy_istall to install my own module, but when I try > to import it I get an ImportError "No module named gpsparser". > > So I've done some research and found that in my site-packages/ > directory gpsparser exists as an egg file, while all the other > packages I've installed exist as an egg directory. > > If this makes any sense, can anyone explain what I've done wrong in > building my package that the installation process does not unpack the > egg file? This has nothing to do with that - it's simply that your egg is empty. Take a look at this: (gpsparser)mac-dir:Application Support deets$ unzip -l /Users/deets/.virtualenvs/gpsparser/lib/python2.5/site-packages/gpsparser-0.0.1-py2.5.egg Archive: /Users/deets/.virtualenvs/gpsparser/lib/python2.5/site-packages/gpsparser-0.0.1-py2.5.egg Length Date Time Name -------- ---- ---- ---- 1 12-08-08 12:04 EGG-INFO/dependency_links.txt 249 12-08-08 12:04 EGG-INFO/PKG-INFO 599 12-08-08 12:04 EGG-INFO/SOURCES.txt 1 12-08-08 12:04 EGG-INFO/top_level.txt 1 12-08-08 11:25 EGG-INFO/zip-safe -------- ------- 851 5 files (gpsparser)mac-dir:Application Support deets$ I presume you miss a packages=find_packages(), line in your setup.py, with from setuptools import setup, find_packages to actually get the find_packages. Diez From clp at rebertia.com Mon Dec 8 12:52:49 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 8 Dec 2008 09:52:49 -0800 Subject: datetime and the rich-companison operators In-Reply-To: <493CCFBC.90104@stoneleaf.us> References: <493CCFBC.90104@stoneleaf.us> Message-ID: <47c890dc0812080952q32adc09etbd5d4c1601914b98@mail.gmail.com> On Sun, Dec 7, 2008 at 11:41 PM, Ethan Furman wrote: > Greetings All! > > I am implementing a NullDate class in order to mirror dates and datetimes > that have no value (yes, this is for my dbf module :) > > I'm still a bit fuzzy about class methods, hashing, and __new__, but my > question of the moment is this: it seems to me that with two dates or > datetimes, they should either be equal, or one should precede the other, and > this can be accomplished quite handily with __cmp__... so does anyone know > why the rich comparisons were used in the datetime module? Was it simply a > style choice, or is something being handled that __cmp__ couldn't cope with? Probably because __cmp__ was removed in Python 3.0, thus requiring the use of the rich comparison methods in its place. See the earlier thread entitled "Python 3 __cmp__ semantic change?". Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks in advance! > ~ethan~ > -- > http://mail.python.org/mailman/listinfo/python-list > From hniksic at xemacs.org Wed Dec 3 04:17:20 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 03 Dec 2008 10:17:20 +0100 Subject: How to use a Python function that returns a double array in C++. References: <24b01c57-0197-4971-9489-47345a2777f7@h20g2000yqn.googlegroups.com> Message-ID: <87hc5lr527.fsf@mulj.homelinux.net> pieter writes: > I want to use a Python function that returns a double array in C++. Return an array.array('d') object, and use the buffer protocol (for example PyObject_AsReadBuffer()) to get the address of the underlying array of native doubles. From r.drew.davis at gmail.com Tue Dec 16 22:18:03 2008 From: r.drew.davis at gmail.com (r.drew.davis at gmail.com) Date: Tue, 16 Dec 2008 19:18:03 -0800 (PST) Subject: Need help improving number guessing game References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> <01564c98$0$21844$c3e8da3@news.astraweb.com> <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> Message-ID: On Dec 15, 1:29?pm, feba wrote: > 6; can anyone think of anything else to add on to/do with this game? > With the minr/maxr display, multiplayer, score keeping, and > automation, I'm just about all of ideas. All I can think of left to > add is 3 and 4 player modes, or a fork where player 2 can't win > (kekekekeke. Though I'm not sure how to do it...), both of which I > feel are somewhat pointless for a game like this. If I can't learn > anything more from it, I will probably go back to reading python > guides for a bit, and then try to make something else. Well, if you want to aim for several more rounds of refinement, how about having the game allow many players identified by name and have it keep records in a file: player name, number of times played, best score, best elapsed time for game completion - for each player. Can you do it in such a way that multiple people on different PC's can all play the game at the same time and not scribble over each other's scores? One approach would be to insist that the player's computers be able to share access to a particular directory, perhaps using a network mount of a disk from somewhere. A fancier approach would be to have a score keeping "service" that runs somewhere and each player's computer uses the network to interact with that score keeping service. Besides the game playing front end to the score keeping service, maybe you should have an administrative front end to the score keeping service to allow you to delete the names of deceased game players. (The only thing keeping him on his perch were tiny little nails through his feet). Can just anyone play the game or does the administrator have to add their name as an authorized player to the score keeping service before they are allowed to play? Is it "Scout's honor" that palyers are who they say they are, or is there some kind of authentication for a player to "prove" their identify before they are allowed to play? I remember many years ago back in graduate school, a friend implemented a clone of "pong" with record keeping. People would sit with that stupid game into the middle of the night striving to improve their standings in the best score display. May be more addictive with a "harder" game than this number guessing game but having your score being visible to other players can be powerful motivation to strive for better scores. If only my friend had figured out a way to have the little DEC GT40 demand quarters if the player wanted to play again, he'd have had most of his tuition nicely covered. If your mind is ready to try something completely different, another thing you could strive to do is change the game from a "tty" interface to something more screen oriented. e.g. instead of having a prompt for "play again (y or n):" you'd have buttons on the screen that the player can click that say "quit" or "start new game". Note that the player might decide to click on either of those buttons at any time, not just after they have completed a game. Python has several many different libraries that would give you a basis for building such a "graphical user interface" (GUI) version of your game, but I'm not experienced enough to tell you which GUI package you should look into. Not so much related to the business of making a niftier game, but another area you might want to look into is change management (e.g. "subversion") so you can track the evolution and refinement of your source code over time. The player-visible part of that is perhaps just to have something that announces which revision of the game they are running such that you can tell from that which revision of the source code to look at if you are tracking down a fix for a problem they have encountered and reported to you. Drew From ivlenin at gmail.com Sun Dec 7 15:56:40 2008 From: ivlenin at gmail.com (I V) Date: Sun, 07 Dec 2008 20:56:40 GMT Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> Message-ID: On Sat, 06 Dec 2008 16:34:56 -0800, Erik Max Francis wrote: > `$` as a shortcut for self, on the other hand, gives absolutely no > mnemonic indication what it stands for, and users would be simply left > guessing. However, $ is sometimes used as an alternative way of writing S? (I've attempted to write here S followed by U+0338 COMBINING LONG SOLIDUS OVERLAY, in order to produce an S with a stroke through it). This is the symbol of the "barred subject" in Lacanian psychoanalysis, which is the Lacanian symbol for the concept of the "self" (see http://nosubject.com/Bar ). So, if we want Python to the programming language of choice for Lacanian psychoanalysts, perhaps we should adopt the symbol "$" (or even, with Python 3's support for unicode identifiers, S followed by U+0388) instead of "self." From geekmail at usenot.de Sat Dec 6 07:37:04 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sat, 6 Dec 2008 13:37:04 +0100 Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> Message-ID: <20081206133704.1bed455c@usenot.de> On Sat, 6 Dec 2008 13:32:58 +0100 Andreas Waldenburger wrote: > On Sat, 6 Dec 2008 04:02:54 -0800 (PST) bearophileHUGS at lycos.com > suggested: > > > > class C: > > def $method(arg): > > $value = arg > > > > [snip] > > > [snip] > "self" is a speaking identifier, "$" isn't. > Also, nothing prevents you from replacing "self" with "s" if you really want it short. Same effect as your "s" suggestion (OK, plus one "."). /W -- My real email address is constructed by swapping the domain with the recipient (local part). From rileyrgdev at gmail.com Mon Dec 22 13:42:55 2008 From: rileyrgdev at gmail.com (Richard Riley) Date: Mon, 22 Dec 2008 19:42:55 +0100 Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: Marco Mariani writes: > Richard Riley wrote: > >> One does not have to by a language maestro to try and assess its >> popularity. While his numbers or his reading of the numbers might be >> open to some questions, to suggest that one needs to be totally familiar >> with a language to determine its popularity is, frankly, ridiculous. > > I was not judging his competency. But when I am naive on a subject, I > don't usually show off like that. I do not see what is showing off about judging a languages popularity. In many cases a languages popularity can be a useful metric in picking a language to do a job. > The polemic intents in his previous messages are quite clear (python > is slow, py3k is an utter failure because it doesn't solve the > whitespace issue, etc), and this thread is not different. It seems > like a rehash of issues that have been dragged around here by > generations of trolls for the last 10 years. I find it difficult myself to accept certain criticisms of certain things when I am close to them. This does not, however, make the criticisms unfair or untrue or even unimportant. > > Sorry for adding noise to the signal :-/ -- important and urgent problems of the technology of today are no longer the satisfactions of the primary needs or of archetypal wishes, but the reparation of the evils and damages by the technology of yesterday. ~Dennis Gabor, Innovations: Scientific, Technological and Social, 1970 From robert.kern at gmail.com Wed Dec 3 16:22:04 2008 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 03 Dec 2008 15:22:04 -0600 Subject: Numpy record array - field names for all dimensions In-Reply-To: <74c0e6f0-8caf-4e06-a162-1d107977ff3c@d32g2000yqe.googlegroups.com> References: <74c0e6f0-8caf-4e06-a162-1d107977ff3c@d32g2000yqe.googlegroups.com> Message-ID: ShanMayne wrote: > Greetings All Greetings! If you have more numpy questions, you will find numpy-discussion to be a better forum: http://www.scipy.org/Mailing_Lists > I am seeking to represent datasets where each data element is the > calculated result from several (4 for now) other data types. A matrix- > like (in the general mathematical sense) seems logical, where the > intersection of each of the 4 values (from different data sets) holds > the value derived from those 4 values here serving as indexes. > > So, each matrix/array element is associated with 4 fields. > eg: > matrix element/output value = 24.235 --> > 'Formula' = 'C12H24O2N2' > 'Solvent' = 'Acetonitrile' > 'fragmentation_method' = 'CID' > 'resolution' = 'unit' > > ideally I would like to call the output value by indexing the matrix > with the input information. eg: > > matrix['C12H24O2N2']['Acetonitrile']['CID']['unit'] = 24.235 > > Numpy's record arrays seemingly don't allow all dimensions to carry > field names. ie. each column/row carrying a label. Instead fieldname > usage appears to create a "new dimension" as denoted by square > brackets. Pretty much. You can make nested dtypes, but that's not really the data structure that you want. You probably want a simple dictionary. d = { ('C12H24O2N2','Acetonitrile','CID','unit'): 24.235, ... } assert d['C12H24O2N2','Acetonitrile','CID','unit'] == 24.235 If you want to make partial queries (e.g. Formula='C12H23O2N2' and resolution='unit'), this becomes more like a typical relational database, but you can probably get along with a few simple functions to loop over the dictionary and pull out the relevant keys pretty quickly. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From Slaunger at gmail.com Wed Dec 3 17:30:10 2008 From: Slaunger at gmail.com (Slaunger) Date: Wed, 3 Dec 2008 14:30:10 -0800 (PST) Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> <258cf433-f6c9-43e7-a235-f5f6b2b6433f@j39g2000yqn.googlegroups.com> <33b4cc2f-2311-491c-a2e6-9cc5452b1a6b@g38g2000yqd.googlegroups.com> <2772646a-623f-400b-a606-281a7e3220d4@20g2000yqt.googlegroups.com> Message-ID: <69d7fe1d-11d9-4d28-a3b7-8a6fb6ecbccc@h5g2000yqh.googlegroups.com> On 3 Dec., 15:30, Nick Craig-Wood wrote: > Slaunger wrote: > > ?On 3 Dec., 11:30, Nick Craig-Wood wrote: > > > > ? ? ? ? ?cls = self.__class__ > > > > ? ? ? ? ?if attr_name in cls.data_attr_names: > > > > self.data_attr_names should do instead of cls.data_attr_names unless > > > you are overriding it in the instance (which you don't appear to be). > > > ?Yeah, I know. I just like the cls notation for code readability > > ?because it tells you that it is a class attribute, which is not > > ?instance- dependent. > > > ?That may be legacy from my Java past, where I used to do it that > > ?way. ?I know perfectly well that self. would do it. i just find > > ?that notation a little misleading > > I quite like it... It looks in the instance, then in the class which I > find to be very elegant - you can set a default in the class and > override it on a per object or per subclass basis. > In principle yes. In the particular case in which it is used I happen to know that it would not make sense to have a different attribute at the instance level. That is, however quite hard to realize for outside reviewers based on the small snippets I have revealed here. So, i certainly understand your view point. The cls notation sort of emphasizes that instances are not supposed to override it (for me at least), and if they did, it would be ignored. In other applications, I would use self. too. > > > > ? ? ? ? ? ? ? ? ? ?for k, v in zip(("I1", "Q1", "I2", "Q2"), bytes_to_data(buf)): > > > ? ? ? ? ? ? ? ? ? ? ? ?setattr(self, k, v) > > > ? ? ? ? ? ? ? ? ? ?return object.__getattr__(self, attr_name) > > > ?And perhaps even more readable (how I do it now, no need to call > > ?__getattr__ for an attribute, whcih is already there): > > ? ? ? ? ? ? ? ? ?... > > ? ? ? ? ? ? ? ? ?for attr, value in zip(cls.data_attr_names, > > ?bytes_to_data(buf)): > > ? ? ? ? ? ? ? ? ? ? ?setattr(self, attr, value) > > > ? ? ? ? ? ? ? ? ?return getattr(self, attr_name) > > I wrote the object.__getattr__ call to stop recursion troubles. ?If > you are sure you've set the attribute then plain getattr() is OK I > guess... Ah, Ok. I am sure and my unit tests verify my assurance. > > > ?In this process I have actaully managed to isolate all the > > ?...OnDemand stuff in an abstract PayloadOnDemand class > > > ?I can now use this "decorator-like"/helper class to very easily > > ?make an ...OnDemand variant of a class by just doing multiple > > ?inheritance - no implementation: > > > ?class PayloadBaconAndEggsOnDemand(PayloadOnDemand, PayloadBaconAndEggs): pass > > You've reinvented a Mixin class! > > ?http://en.wikipedia.org/wiki/Mixin > > It is a good technique. > Wow, there is a name for it! It did not know that. Hmm... I never really took the time to study those GoF design patterns. (I am a physicist after all... and really a programmer) I guess I could save a lot of time constantly re-inventing the wheel. Are there any good design pattern books focused on applications in Python? (Actually, I will post that question in a separate thread) Once again, I am extremely pleased with your very thoughtful comments, Nick. Thanks! -- Slaunger From news123 at free.fr Wed Dec 10 18:36:04 2008 From: news123 at free.fr (News123) Date: Thu, 11 Dec 2008 00:36:04 +0100 Subject: Python for kids? In-Reply-To: <53f406ed-c261-4d86-a8dc-4001d10d05b5@s20g2000yqh.googlegroups.com> References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> <53f406ed-c261-4d86-a8dc-4001d10d05b5@s20g2000yqh.googlegroups.com> Message-ID: <49405265$0$24620$426a74cc@news.free.fr> Hi, bearophileHUGS at lycos.com wrote: > On Dec 7, 9:13 pm, "Russ P." wrote: >> I have a 12-year-old son who spends too much time playing Xbox live >> and watching silly YouTube videos. I would like to try to get him >> interested in programming. > . . . > But I think it's better for you to help him get interest in problem- > solving . . . > Once those interests are in place, he will > probably go looking by himself for things like programming languages, > . . . > > Otherwise you risk pushing a person to learn using a tool (programming > is interesting by itself, but it's mostly a tool still) before having > any use for such tool or desire to learn it. And this may lead to > someone with no passion to solve problems and learn. > People are different. I for example learnt programming at 13 without having any initial use for it. My main motivation was, that my father brought the first computer, I ever saw (AIM-65) from work, but didn't want to spent time to explain me what it does and how it works. Instead he just gave me a book about BASIC and hoped I wouldn't bother him anymore. (For me as a slightly stubborn teenager this was challenge enough to show, that I could write a (whatever) basic program. If the book, that teaches programming has just a few 'fun examples' it could be enough to get him (Rus' son) started thinking about his own problems he could then solve with writing programs. Russ should best be able to know what could be 'fun-examples' for his son. Fun-examples could be things like: - high low number guessing program - drawing funny pictures with turtle graphics - printing out all possible combinations / permutations of som digits letters. - towers of hanoi - a very basic pong game - writing a mini data base for his 'whatever' - collection It might however be a little more complicated to motivate somebody to write some small rather simple programsm when it's so simple to google and download so much SW without knowing anythng about programming. 20-30 years ago it was basically impossible to locate and download (even did'nt have a modem :-) ) ready made SW Depending on his interests he might also be more interested in learning a spreadsheet SW / a drawing program and then attack the related macros / scripting language bye N From duncan.booth at invalid.invalid Sun Dec 21 10:30:34 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Dec 2008 15:30:34 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <015da0a4$0$20656$c3e8da3@news.astraweb.com> <6r6uvbFfb643U5@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: >> a+b+c+d might execute a.__add__(b,c,d) allowing more efficient string >> concatenations or matrix operations, and a%b%c%d might execute as >> a.__mod__(b,c,d). > > But that needs special casing strings and ``%`` in the comiler, because > it might not be always safe to do this on arbitrary objects. Only in > cases where the type of `a` is known at compile time and ``a % b`` > returns an object of ``type(a)``. > I could be wrong, but I don't see that would be the case. I think it would be safe (in this hypothetical universe) any time that 'a' had a method __mod__ which accepted more than one argument. It might be simpler if I'd suggested an imaginary __mmod__ method so the opcode for multiple-mod could check for that method or fall back to doing mod of the first two values and then mmod of the result and any remaining values until only two remain. From pruebauno at latinmail.com Mon Dec 29 11:36:44 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Mon, 29 Dec 2008 08:36:44 -0800 (PST) Subject: 2to3 used in the Shootout References: <4f1a8f03-fd7f-49ea-8031-61f73fb0c0e8@x16g2000prn.googlegroups.com> <65a43a69-1ef2-4a41-b860-a370891aecbd@g39g2000pri.googlegroups.com> Message-ID: <67424d25-69c3-4c9d-ba38-0df208a28428@k19g2000yqg.googlegroups.com> On Dec 23, 5:21?pm, Isaac Gouy wrote: > On Dec 23, 11:51?am, bearophileH... at lycos.com wrote: > > > They have translated the Python benchmarks of the Shootout site from > > Py2 to Py3 using 2to3: > > >http://shootout.alioth.debian.org/u32/benchmark.php?test=all?=pyt... > > So please re-write those programs to remove problems created by > automatic translation and better take advantage of Python 3 > functionality... > > http://shootout.alioth.debian.org/u32/faq.php#play > > > It shows some "performance bugs" of Python3 itself (especially > > regarding the binary-trees benchmark, that was unexpected by me), and > > two points where 2to3 may be improved, for example after the > > translation this gives error: > > ? ? ? ? ?table=string.maketrans('ACBDGHK\nMNSRUTWVYacbdghkmnsrutwvy', > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 'TGVHCDM > > \nKNSYAAWBRTGVHCDMKNSYAAWBR')): > > > Gives: > > TypeError: maketrans arguments must be bytes objects > > > Bye, > > bearophile > > BTW I am not sure how to submit this or if this is actually valid to do, but I have a faster version for the pidigits program that uses basically the same algorithm but removes function calls and unused terms of the formula.
    import time
    
    def pi_digits(n, width):
        out = []
        wrt = out.append
        aq = 1
        ar = 0
        at = 1
        k = 0
        f = 1
        g = 2
        i = 0
        while i < n:
            y = (aq*3+ar)//at
            while y != ((aq*4+ar)//at):
                k += 1
                f += 2
                g += 4
                ar = aq*g+ar*f
                aq = aq*k
                at = at*f
                y = (aq*3+ar)//at
            aq = 10*aq
            ar = 10*ar-10*y*at
            i += 1
            wrt(str(y))
            if not i%width:
                wrt('\t:%d\n'%i)
        wrt(' '*(width-i%width))
        wrt('\t:%d\n'%i)
        return ''.join(out)
    
    
    def main():
        begin = time.time()
        n = 1000
        width = 70
        print pi_digits(n,width)
        print 'Total Time:', time.time()-begin
    
    main()
    
    
    From skip at pobox.com Fri Dec 12 14:04:43 2008 From: skip at pobox.com (skip at pobox.com) Date: Fri, 12 Dec 2008 13:04:43 -0600 Subject: Python extension: callbacks blocked when holding button down In-Reply-To: <05533b81-de89-4ee2-90c5-8f19533b65a9@g17g2000prg.googlegroups.com> References: <05533b81-de89-4ee2-90c5-8f19533b65a9@g17g2000prg.googlegroups.com> Message-ID: <18754.46539.568766.995728@montanaro-dyndns-org.local> alan> I'm developing a Python extension. It's a wrapper for some alan> firmware, and simulates the target hardware environment. I'm using alan> wxPython. I pass a function to the extension so it can let Python alan> know about certain events. The code is currently single threaded. alan> My problem is that the callback seems to have no effect if it is alan> called while I am holding down a wxButton in the Python GUI. Long alan> button presses are significant in the firmware so this seems a bit alan> limiting. alan> Can anyone explain what is going on? What's the best workaround? You don't say what platform you're running on, but in many environments, holding down a menu button "grabs" the window server for the duration of the button press. This is certainly the case on Unix running the X Window System. In many cases multithreading is the best way around this problem. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From ndbecker2 at gmail.com Tue Dec 2 14:56:00 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 02 Dec 2008 14:56 -0500 Subject: optimization References: Message-ID: Robert Kern wrote: > Neal Becker wrote: >> Arnaud Delobelle wrote: >> >>> Neal Becker writes: >>> >>>> I noticed in some profiling, that it seems that: >>>> >>>> def Func (): >>>> def something(): >>>> ... >>>> >>>> It appears that if Func is called many times, this nested func >>>> definition will cause significant overhead. Is this true? I guess >>>> I've become accustomed to decent compilers performing reasonable >>>> transformations and so have tended to write code for clarity. >>> If something() can be defined outside Func(), how is it clearer to >>> define it inside? >> >> If it's only used inside. > > I, for one, find that significantly less clear. I only expect functions to > be defined inside of functions if they are going to use lexical scoping > for some reason. If I read your code, I'd probably waste a good five > minutes trying to figure out what part of the local scope you were using > before I would conclude that you just did it because you thought it looked > better. > I'm using the inner function to prevent pollution of the global namespace. Local variables also have this attribute. Code is easier to understand when it is written with the greatest locality - so you can see immediately that the inner function isn't used somewhere else. From mal at egenix.com Wed Dec 10 10:50:57 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 10 Dec 2008 16:50:57 +0100 Subject: Rich Comparisons Gotcha In-Reply-To: <1228923619.493fe2e3c3073@comuh.uh.cu> References: <1228923619.493fe2e3c3073@comuh.uh.cu> Message-ID: <493FE561.6030007@egenix.com> On 2008-12-10 16:40, Luis Zarrabeitia wrote: > Quoting Rasmus Fogh : >> Rhamphoryncus wrote: >>> You grossly overvalue using the "in" operator on lists. >> Maybe. But there is more to it than just 'in'. If you do: >>>>> c = numpy.zeros((2,)) >>>>> ll = [1, c, 3.] >> then the following all throw errors: >> 3 in ll, 3 not in ll, ll.index(3), ll.count(3), ll.remove(3) >> c in ll, c not in ll, ll.index(c), ll.count(c), ll.remove(c) >> >> Note how the presence of c in the list makes it behave wrong for 3 as >> well. > > I think I lost the first messages on this thread, but... Wouldn't be easier to > just fix numpy? I see no need to have the == return anything but a boolean, at > least on Numpy's case. The syntax 'a == b' is an equality test, not a detailed > summary of why they may be different, and (a==b).all() makes no little sense to > read unless you know beforehad that a and b are numpy arrays. When I'm comparing > normal objects, I do not expect (nor should I) the == operator to return an > attribute-by-attribute summary of what was equal and what wasn't. > > Why is numpy's == overloaded in such a counter intuitive way? I realize that an > elementwise comparison makes a lot of sense, but it could have been done instead > with a.compare_with(b) (or even better, a.compare_with(b, epsilon=e)). No > unexpected breakage, and you have the chance of specifying when you consider two > elements to be equal - very useful. Rich comparisons were added to Python at the request of the Numeric (now numpy) developers and they have been part of Python a Numeric for many many years. I don't think it's likely they'll change things back to the days of Python 1.5.2 ;-) > Even the transition itself could be done without breaking much code... Make the > == op return an object that wraps the array of bools (instead of the array > itself), give it the any() and all() methods, and make __nonzero__/__bool__ > equivalent to all(). That would cause a lot of confusion on its own, since such an object wouldn't behave in the same way as say a regular Python list (bool([0]) == True). -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 10 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-12-02: Released mxODBC.Connect 1.0.0 http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From exarkun at divmod.com Tue Dec 30 14:27:16 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 30 Dec 2008 14:27:16 -0500 Subject: select.select and socket.setblocking In-Reply-To: <495a661d$0$11384$5fc30a8@news.tiscali.it> Message-ID: <20081230192716.20272.501856153.divmod.quotient.29293@ohm> On Tue, 30 Dec 2008 19:19:08 +0100, Francesco Bochicchio wrote: > [snip] > >If you are interested in socket errors, you should >also fill the third 'fd-set' in the select call, and after select returns >check that fd is not in it anymore: > >ready = select.select( [fd],[], [fd] ) >if fd in ready[2]: > # raise your error here The third argument to select() isn't for monitoring sockets for errors. Its behavior is also rather platform sensitive. In general, you don't need it at all on POSIX, but on Windows you should pass the same list for it as you pass for the write-set, merge the results, and treat them all as writeable. Or use a higher-level library that deals with all the asinine details for you. ;) Jean-Paul From lists at cheimes.de Thu Dec 25 19:48:55 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 26 Dec 2008 01:48:55 +0100 Subject: SyntaxError: encoding problem: with BOM In-Reply-To: <26e21f3f-ded1-48ca-8897-2ebd05dd07ad@w39g2000prb.googlegroups.com> References: <6res8tF1do1sU1@mid.uni-berlin.de> <400f176b-bd9a-4f26-b01b-1aa7c7dcf5ac@z6g2000pre.googlegroups.com> <6rf6m1F1e0f8U1@mid.uni-berlin.de> <26e21f3f-ded1-48ca-8897-2ebd05dd07ad@w39g2000prb.googlegroups.com> Message-ID: NoName schrieb: >> NoName, Asking people to download a zip file from a website written in >> a language and character set that they probably are not familiar with >> is liable to make them rather nervous and not bother. It's not a good >> way to ask for help. > > sorry:) > > Now i know where problem. > But i dont know how to solve it. > > Error > ---- > C:\Documents and Settings\Ra\??????? ????>11.py > File "", line 1 > SyntaxError: encoding problem: with BOM > > No error > ---- > C:\Documents and Settings\Ra\??????? ????>python 11.py > test > > Error when russian symbols in full path to py-script. > Is it Python bug? or i need to modify some registry keys? > > OS: WinXP SP3 Russian. > Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit > (Intel)] on win32 It's a bug, please report it. I though we fixed all Windows path bugs for 3.0 but apparently one slipped through. Christian From fakeaddress at nowhere.org Sat Dec 13 18:13:39 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 13 Dec 2008 15:13:39 -0800 Subject: Bidirectional Networking In-Reply-To: <98a6c3cd-181c-43c9-805b-fb0689c69544@a26g2000prf.googlegroups.com> References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <98a6c3cd-181c-43c9-805b-fb0689c69544@a26g2000prf.googlegroups.com> Message-ID: Emanuele D'Arrigo wrote: > Hey Bryan, thank you for your reply! > > Bryan Olson wrote: >>> Is it possible then to establish both a server and a client in the >>> same application? >> Possible, and not all that hard to program, but there's a gotcha. >> Firewalls, including home routers and software firewalls, typically >> default to disallowing connections in the 'wrong' direction. If the >> client initiates all connections, you avoid a world of hassles. > > Ah yes, I can see that. Uhm. I have absolutely no idea right now how a > firewall works from a programming point of view and what happens in > normal "residential" circumstances. I.e. it's clear that firewalls are > configured to allow http traffic because I can browse the internet. Is > that done leaving a specific port open? Or does the browser request > the firewall to open a specific port for it and the firewall trust the > browser to handle safely anything that comes through? Software firewalls will often simply refuse incoming connections. The basic protection of the garden-variety home router comes from "network address translation" (NAT), in which case TCP connections initiated from the inside will generally work, regardless of port, and incoming connections will fail. Internet server farms often enforce the other side of the client-side policy, with firewalls configured to disallow outgoing initiation of connections. If the application need to work in restrictive environments where firewalls only pass known protocols, a popular approach to build the application protocol on top of HTTP, with all the required standard headers and a new content-type. > I.e. in the case of the code in this thread, would it be the > responsibility of the application to tunnel through the firewall and > listen for connections I'm not clear on what that means. > or would it be the responsibility of the user > to configure the firewall so that the application can receive a > connection? That can be a huge hassle. The first choice is for the application to conform to popular firewall policies, so no special configuration is required. -- --Bryan From mail at microcorp.co.za Wed Dec 3 16:09:17 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 3 Dec 2008 23:09:17 +0200 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> Message-ID: <001901c9558b$7e4c1420$0d00a8c0@hendrik> "Xah Lee" wrote: >Chances are, $10 is not enough for me to take the >trouble of disappearing from the face of this earth. What a pity. It would be cheap at the price. - Hendrik From rdcollum at gmail.com Thu Dec 18 14:38:58 2008 From: rdcollum at gmail.com (Roger) Date: Thu, 18 Dec 2008 11:38:58 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <71ede5f0-fd88-4155-9f0d-42d0ad5f57dc@v42g2000yqj.googlegroups.com> <61f45e65-2404-4cc0-9d81-f848c1ba566f@i18g2000prf.googlegroups.com> Message-ID: <553bb989-d445-4ebb-b0e4-0ba78ce67cb8@r15g2000prh.googlegroups.com> On Dec 18, 12:49?pm, r wrote: > Maybe someone will chime in with an answer, sorry i could not help. > ponder this, i must... Regardless, thanks for your help! I truly appreciate it. Roger. From prologic at shortcircuit.net.au Mon Dec 29 20:35:44 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 30 Dec 2008 11:35:44 +1000 Subject: get method In-Reply-To: References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> Message-ID: On Tue, Dec 30, 2008 at 11:32 AM, James Mills wrote: > Ross, the others have informed you that you are not > actually incrementing the count. I'll assume you've > fixed your function now :) ... I want to show you a far > simpler way to do this which takes advantage of > Python's list comprehensions and mappings (which are > really what dictionaries are): > >>>> s = "James Mills and Danielle Van Sprang" >>>> dict([(k, len([x for x in s if x == k])) for k in s]) > {'a': 5, ' ': 5, 'e': 3, 'd': 1, 'g': 1, 'i': 2, 'M': 1, 'J': 1, 'm': > 1, 'l': 4, 'n': 4, 'p': 1, 's': 2, 'r': 1, 'V': 1, 'S': 1, 'D': 1} >>>> > > Let us know when you get to the "List Comprehension" > section - They are very powerful - As as Generators > and Generator Expressions. > > Have fun learning Python, Also, here's a nice function: >>> def histogram(s): ... d = dict([(k, len([x for x in s if x == k])) for k in s]) ... for k, v in d.iteritems(): ... print "%s: %s" % (k, "*" * v) ... >>> histogram("Hello World!") !: * : * e: * d: * H: * l: *** o: ** r: * W: * cheers James From invalid at invalid Mon Dec 22 10:45:24 2008 From: invalid at invalid (Grant Edwards) Date: Mon, 22 Dec 2008 09:45:24 -0600 Subject: How to represent a sequence of raw bytes References: <200812220327.36180.motoom@xs4all.nl> <015f66d7$0$20615$c3e8da3@news.astraweb.com> Message-ID: On 2008-12-22, Steven D'Aprano wrote: > On Mon, 22 Dec 2008 14:56:45 +0800, Steven Woody wrote: > >> The intension is to allocate 200 undefined bytes in memory. > > You *want* undefined bytes? Out of curiosity, what do you intend to do > with them? Predict the future, of course. -- Grant Edwards grante Yow! MERYL STREEP is my at obstetrician! visi.com From gagsl-py2 at yahoo.com.ar Fri Dec 26 07:35:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 26 Dec 2008 10:35:00 -0200 Subject: Exec inside a class method to call other class methods? References: <4953CF57.8080905@sympatico.ca> <20081226001641.GA22946@sdf.lonestar.org> <47c890dc0812251624m7e1c5e55rb538996a52d56675@mail.gmail.com> <6706036c-98e0-46c1-b3c2-5a9a0a92af56@w39g2000prb.googlegroups.com> Message-ID: En Fri, 26 Dec 2008 03:59:25 -0200, Carl Banks escribi?: > To be honest I am a little concerned over the more-or-less knee-jerk > suggestions to refactor this into a highly object-oriented approach. > For the task at hand the OP's approach is fine (aside from the use of > exec). Yep. There is a simple solution that still nobody suggested: rename all of __parse_foo as _parse_foo (single leading underscore), then: def parse(self, data, data_type) return getattr(self, "_parse_%s" % data_type)(data) unless there are strong reasons to keep the __ names. -- Gabriel Genellina From jon at ffconsultancy.com Mon Dec 8 16:31:29 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Mon, 08 Dec 2008 21:31:29 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> <0201522a-b15a-4401-a208-5d9af70bdd74@w24g2000prd.googlegroups.com> Message-ID: Xah Lee wrote: > Also, in this discussion, thanks to Thomas M Hermann's $20 offered to > me for my challenge to you, that i have taken the time to show working > code that demonstrate many problems in your code. You failed the challenge that you were given. Specifically, your code is not measurably faster on the problem that I set. Moreover, you continued to write as if you had not failed and, worse, went on to give even more awful advice as if your credibility had not just been destroyed. > If you are a Mathematica expert, you could make it recurse yet have > the speed as other langs. No, you cannot. That is precisely why you just failed this challenge. You should accept the fact that Mathematica currently has these insurmountable limitations. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From john.rominsky at gmail.com Wed Dec 17 19:32:58 2008 From: john.rominsky at gmail.com (Rominsky) Date: Wed, 17 Dec 2008 16:32:58 -0800 (PST) Subject: getting object instead of string from dir() References: Message-ID: <1bb0df81-380c-46eb-a3aa-863c468c6aff@x14g2000yqk.googlegroups.com> On Dec 17, 1:21?pm, Jean-Paul Calderone wrote: > On Wed, 17 Dec 2008 11:52:17 -0800 (PST), Rominsky wrote: > >On Dec 17, 10:59?am, Christian Heimes wrote: > >> Rominsky schrieb: > > >> > I am trying to use dir to generate a list of methods, variables, etc. > >> > I would like to be able to go through the list and seperate the > >> > objects by type using the type() command, but the dir command returns > >> > a list of strings. ?When I ask for the type of an element, the answer > >> > is always string. ?How do I point at the variables themselves. ?A > >> > quick example is: > > >> > a = 5 > >> > b = 2.0 > >> > c = 'c' > > >> > lst = dir() > > >> > for el in lst: > >> > ? ? print type(el) > > >> for name, obj in vars().iteritems(): > >> ? ? print name, obj > > >> Christian > > >I do have some understanding of the pythonic methodology of > >programming, though by far I still don't consider myself an expert. > >The problem at hand is that I am coming from a matlab world and trying > >to drag my coworkers with me. ?I have gotten a lot of them excited > >about using python for this work, but the biggest gripe everytime is > >they want their matlab ide. ?I am trying to experiment with making > >similar pieces of the ide, in particular I am working on the workspace > >window which lists all the current variables in the namespace, along > >with their type, size, value, etc.... ?I am trying to create a python > >equivalent. ?I can get dir to list all the variables names in a list > >of strings, but I am trying to get more info them. ?hence the desire > >to do a type command on them. ?I like the locals and globals commands, > >but I am still trying to get more info. ?I have started using the eval > >command with the strings, which is working, but I am curious if there > >is a better or more elegant way of getting the info. ?The eval example > >would be something like: > > >a = 5 > >b = 2.0 > >c = 'c' > > >lst = dir() > > >for el in lst: > > ? print el + '\t' + str(eval('type(%s)'%el)) > > >It works, now I am curious if there is a better way. > > What about this: > > >> for name, obj in vars().iteritems(): > >> ? ? print name, obj > > >> Christian > > Jean-Paul vars seems to give an identical response as locals and globals, at least in my test name space. All three are new commands for me. I like the idea of adopting either vars or locals instead of dir as it sets up the value for me to use. I will play with them both a little more and read up on them to learn there uses and limitations. The key step for me is still to be able to automatically query the key names from vars or locals for what type the variable is. In my previous post I discussed using eval and the string in the key name such as eval('type(%s)'%vars().keys()[0]) I definitely have enough to move forward. Thanks everyone. If anyone has any other ideas I would still be interested in learning more. Thanks again. From danebarney at gmail.com Fri Dec 26 23:20:16 2008 From: danebarney at gmail.com (Jugdish) Date: Fri, 26 Dec 2008 20:20:16 -0800 (PST) Subject: raw_input can't handle pound sign? Message-ID: Hi, I'm having problems getting a pound sign to go through as input sent to the raw_input() command. I'm running Python 2.5.1 on Windows XP. Here's my simple little script: while True: response = raw_input("Please enter a file name: ") if os.path.exists(response): break Problem is if the filename has a "#" in it, the script interprets that as the beginning of a comment (not sure why -- isn't raw_input supposed to treat the user's input as raw text and not do any sort of evals?) Any ideas how to get a # to go through? Thanks! From stef.mientki at gmail.com Wed Dec 10 03:21:17 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 10 Dec 2008 09:21:17 +0100 Subject: Mathematica 7 compares to other languages In-Reply-To: <9ecfa224-ce8f-44e9-abca-008314f44e87@40g2000prx.googlegroups.com> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <9ecfa224-ce8f-44e9-abca-008314f44e87@40g2000prx.googlegroups.com> Message-ID: <3dfd60f20812100021j638bf420v37bb6d81fa02d064@mail.gmail.com> On 12/10/08, Xah Lee wrote: > On Dec 8, 5:25 pm, Terry Reedy wrote: >> Lest anyone doubt that problem size is important for comparing program >> run times, consider ... > > just in case there's any doubt: > > Simply change these lines in Jon's program: > > Main[9, 512, 4] to Main[9, 512, 4.] > > and it will run faster. > Who said Mathematica was a high level language ? cheers, Stef From amr at vimov.com Mon Dec 1 16:49:22 2008 From: amr at vimov.com (Amr) Date: Mon, 1 Dec 2008 13:49:22 -0800 (PST) Subject: Aviate, the Web Deployer Message-ID: Announcing the first public release of Aviate, a cross-platform web deployment tool written in Python. Aviate is designed to make deploying your web applications very easy, while providing you with a rich feature set to make repeated task performed in a snap, and being extensible so you can extend its features with your own Python code. Among its feature is being based on XML, an intuitive GUI to create deployment files, a large number of built-in commands, multiple protocol support, extensibility, language constructs, and more. More details on Aviate: http://www.vimov.com/aviate/ Download: http://www.vimov.com/aviate/download/ Front-end: http://blog.vimov.com/2008/11/aviate-front/ From musiccomposition at gmail.com Fri Dec 5 22:33:42 2008 From: musiccomposition at gmail.com (Benjamin) Date: Fri, 5 Dec 2008 19:33:42 -0800 (PST) Subject: Python 3.0 C API migration tools, or docs? References: <008877d2-8705-48a6-bb09-6c31c6b77970@p2g2000prf.googlegroups.com> <1a5cf43f-5802-4c69-9226-18cbc6256c0c@k19g2000yqg.googlegroups.com> Message-ID: <67098ab1-131b-4169-9f65-7efd4038d0ab@r40g2000yqj.googlegroups.com> On Dec 4, 9:06?pm, illume wrote: > Cool thanks Benjamin! > > Maybe it should be in a wiki as well? ?So that as people convert their > modules we can add notes as well. > > I started a wiki with that in mind here:http://wiki.python.org/moin/cporting > > It'd be good if there was a link from the 2to3 docs, and in the C API > docs to either/both of these resources. > > I thought there'd be much more help for people migrating considering > the 2to3 tool exists... but I'll get over it... hehe. Thanks for being so positive. If you'd like to help with the HowTo, feel free to email docs at python.org. > > cheers, From castironpi at gmail.com Mon Dec 22 18:53:38 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 22 Dec 2008 15:53:38 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> Message-ID: <80427165-02a0-4401-ade9-3cef1d520e6c@v39g2000pro.googlegroups.com> On Dec 22, 11:40?am, r wrote: > On Dec 22, 8:58?am, walterbyrd wrote: > > > > > On Dec 21, 12:28?pm, Bruno Desthuilliers > > > wrote: > > > Strange enough, > > > no one seems to complain about PHP or Ruby's performances... > > > A few years back, there was a certain amount of chest thumping, when > > python/django easily beat ror in a benchmark test. Now that ruby is > > faster, I guess speed is no big issue. > > > By the same reasoning, python advocates used to sneer at php because > > php constantly broke backward compatibility. Now that python does it, > > breaking backward compatibility is no big deal. I guess unicode > > support was not that important, until python caught up to perl. > > > I guess, the way it works is: you first assume that python is > > superior, then you figure out why. > > I think what walter is saying is the loyalty is gone. > > community: > """If python makes great, if it doesn't, why should "i" care if it > goes down the toilet? ?i just move to ruby""" > > Were is your loyalty pyfans?, Has the fight left you??? Point: It is not rational for the crew to go down with the ship, only the captain. Case: Loyalty is a complex emotion, and it's not clear that it's our highest priority, or that it's anyone's. I want to use a good language. If Python stops being good (that is, a good version of Python stops being maintained and supported), then I'll stop using it, and that's the rational thing to do. Just to be fair, though, it's (contraction) not obviously irrational for a captain to go down with the ship. The mentality, commitments, and principles that it lets him keep and make may be better on the whole in the long run for captains, crews, and ships, only if they have that consequence. That is, captains that will go down with the ship are better captains of ships, and captains that have the capacity to betray, forge, or abandon principles make worse captains; therefore a good captain will go down, and can't change his mind. However, as critics and fans of Python, our actions don't really have the same consequences as the captains. That is, it is not rational for the crew to go down with the ship, only the captain. From banibrata.dutta at gmail.com Thu Dec 4 00:31:32 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Thu, 4 Dec 2008 11:01:32 +0530 Subject: Good introductory book? In-Reply-To: <56616d73-312c-44e5-a484-5fb3e0054613@x38g2000yqj.googlegroups.com> References: <56616d73-312c-44e5-a484-5fb3e0054613@x38g2000yqj.googlegroups.com> Message-ID: <3de8e1f70812032131t49715c61r194fb39b7650655@mail.gmail.com> 1+ for "Dive into Python"... get's you started very fast. After you are thru with DiP book, it's time to keep google (or ur favourite search engine) handy... search at the ActivePython site in the cookbooks, PEP's, mailing-list archive... the answer is generally found within first 4-5 hits. And then, a good Language Reference is indipespensible... for which the standard Python docs are pretty good. On Thu, Dec 4, 2008 at 10:48 AM, Kottiyath wrote: > On Dec 3, 7:44 pm, "Ken D'Ambrosio" wrote: >> Hi, all. I'm getting ready to do some projects in Python, and I've cut my >> teeth a little bit, but I've found the "Learning|Programming Python" books >> from O'Reilly to be more-or-less useless (to my surprise -- I'm usually an >> O'Reilly fan). I really, really like "Python Essential Reference", but >> it's -- well, more of a reference than an intro. So, an introductory text >> that actually assumes some previous programming experience (as opposed to >> "Learning Python" which must be the most slowly-paced programming book >> ever) would be terrific. >> >> Thanks for your suggestions! >> >> -Ken > > Dive into python is a very good one. It is free too. > http://diveintopython.org/ > > Try it out. > If you want more of examples of how everything is done, then Python > Cookbook is another one. > You can get many recipes at http://code.activestate.com/recipes/langs/python/ > too - the book is just selected recipes from this site. > > > Regards > K > -- > http://mail.python.org/mailman/listinfo/python-list > -- regards, Banibrata http://www.linkedin.com/in/bdutta http://octapod.wordpress.com From kyosohma at gmail.com Wed Dec 24 19:37:40 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 24 Dec 2008 16:37:40 -0800 (PST) Subject: Easy-to-use Python GUI References: Message-ID: <26db7a5a-5636-4d47-a593-7a4e8b6e3a01@s9g2000prg.googlegroups.com> On Dec 24, 5:47?pm, "Joel Koltner" wrote: > Is there an easy-to-use, "function"-based cross-platform GUI toolkit for > Python out there that's a little more sophisticated than EasyGui? ?EasyGui > looks good, but it's a little more restrictive than what I'd like to have, yet > I'm (stubbornly :-) ) resistant to stepping up to a "full service" GUI toolkit > such as pyGTK or wxPython where it's all about event loops and callbacks and > you need to start planning how the GUI affects the overall program flow rather > than just using a "forms" (or "Wizard")-type approach where you put up a few > dialogs, users fill in some variables, and your program just sits around > waiting until "OK" or "Cancel" is clicked. > > One approach that I like comes from SAX BASIC/WinWrap, which is more or less a > clone of Microsoft's Visual BASIC for Applications, but they (apparently) > wanted everything to still be human-readable, so they have a simple GUI > ("form") builder that generates code that looks like this: > > --- > > ?Begin Dialog UserDialog 850,497,"Export Control" ' %GRID:10,7,1,1 > > ? GroupBox 20,7,360,217,"Drill File Generation",.GroupBox1 > ? CheckBox 40,35,130,14,"Output drill file(s)",.genDrill > ? Text 40,63,270,28,"Identify via layers as any that contain this text in > their names:",.Text > ? TextBox 40,98,220,21,.viaLayerName > ? Text 40,140,100,14,"Output method:",.Text8 > ? DropListBox 160,140,180,21,DrillStyle(),.drillStyle > ? Text 40,175,130,28,"Select drill table units:",.Text2 > ? ListBox 200,175,120,28,unitNames(),.unitName > > ? OKButton 310,469,90,21 > ? CancelButton 410,469,90,21 > > ?End Dialog > > ' GUI builder generates or modifies everything above, but can also be edited > by hand > ' You write the following code... > > ?Dim dlg As UserDialog > > ?dlg.genDrill = 1 > ?ReDim DrillStyle(1) > ?DrillStyle(0) = "All Via Layers In One File" > ?DrillStyle(1) = "One File Per Via Layer" > ?dlg.drillStyle = 1 > > ?func=Dialog(dlg) > > --- > > This is pretty darned easy for me understand and modify either by hand or with > the GUI builder. ?Still, it's quite powerful, since it supports all the common > GUI elements (text, group boxes, checkboxes, drop-down lists, text boxes, > buttons, etc.). ?This is about the level of sophistication I'm looking for. > > Anything like this for Python? > > Thanks, > ---Joel Some people like Boa Constructor, XRC or wxGlade: http://boa-constructor.sourceforge.net/ http://wxglade.sourceforge.net/ http://wiki.wxpython.org/XRCTutorial Technically, you can switch to IronPython and then use Visual Studio to design your GUIs and IronPython to control it. I think there's something similar to Jython and Cocoa as well. Probably not what you wanted though. Mike From pdorange at pas-de-pub-merci.mac.com Sun Dec 14 18:25:36 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Mon, 15 Dec 2008 00:25:36 +0100 Subject: Game to test : MicroWar 2.0 alpha 6 Message-ID: <1iryrns.1xzj14rqka5s0N%pdorange@pas-de-pub-merci.mac.com> MicroWar 2.0 alpha 3 for test purpose Download : http://microwar.sourceforge.net/ Presentation ----------------- MicroWar is "Space Invaders" style arcade game, in the cruel world of micro-compter industry. You're a Macintosh faced to invading Wintel hordes year after year, kill more PC. Bonuses let you improve your Mac performances or restore life... Minimum Configuration (Macintosh) ------------------------------------------------ Processor : PowerPC G4 minimum System : MacOS X 10.3.9 or more Memory : 512 MB Screen : 1024 x 768 pixels The bundled application is only available for Mac now. The source code, is therefore cross-platform and can run on Macintosh, Windows and Linux : see source documentation for details Change log : ----------------- * handle mouse for menus * option to play the game with the keyboard (default) or the mouse * loading advancement feedback on splash screen * default option : fullscreen * bug fix : display year information correctly for 0 and 1 line. * first run screen, user can choose it default language * automatic game update check over internet and download to the desktop * adding Clarus Power-Up Bonus (give 5 super-bomb) * adding Saucer explosion : generate Virus that can infect PC * clean the screens handling -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From vlastimil.brom at gmail.com Mon Dec 22 05:07:45 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Mon, 22 Dec 2008 11:07:45 +0100 Subject: wxpython for python 3.0 ? In-Reply-To: References: Message-ID: <9fdb569a0812220207l2dc1a966xdce9b434fcaa747c@mail.gmail.com> >> The wxpython web describes compatability with python 2.4 & 2.5 . >> Does it work with 3.0 ? If not, anyone have a clue as to when ? > > This question was asked a couple of times on the wxpython-users mailing > list. It's probably going to take a while. For now, I'd stick to python 2.x. > The next version of wxPython should support 2.6, so use that and try to make > your code relatively compatible with Python 3 ... The last version of wxPython (2.8.9.1) available on http://wxpython.org/download.php already supports python 2.6; there are prebuilt binaries for this version too. The 3.0 will probably need a bit more time. vbr From nemokingdom at gmail.com Sun Dec 28 07:44:11 2008 From: nemokingdom at gmail.com (nemo) Date: Sun, 28 Dec 2008 04:44:11 -0800 (PST) Subject: ftp EOF error, thread and process Message-ID: <8feadf33-0798-4eaf-ac7c-d16392692722@e1g2000pra.googlegroups.com> Hi all, My code like this raise an EOFError, It happens if I use the Process module, while, if I use thread.start_new_thread(ftp.pwd,()), it seems works well. And I wondered why. from ftplib import FTP import thread from multiprocessing import Process if __name__ == '__main__': ftp = FTP('localhost', 'movie', 'movie') print ftp.pwd() p = Process(target = ftp.pwd) # thread.start_new_thread (ftp.pwd,()), p.start() p.join() From bj_666 at gmx.net Sun Dec 21 04:35:22 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Dec 2008 09:35:22 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: <6r6gupFfb643U1@mid.uni-berlin.de> On Sat, 20 Dec 2008 22:15:23 -0800, r wrote: > It would be nice to get a vote together and see what does the average > pythoneer want? What do they like, What do they dislike. What is the > state of the Python Union? Does anybody know, Does anybody care? I think > python is slipping away from it's dominate foothold on the world. > Google's use of python may be the only thing holding this house of cards > together. Ruby's "hype" is defiantly growing and unless we strive for > greatness, python may fail. I think ruby may have their act together a > little better than us right now. And since Ruby is such a hodge-podge of > different languages, the __init__ hold is there for many. > > what does joe-python want??? That's not completely irrelevant but I think one of Python's strength is that we have a BDFL who decides carefully what he thinks is best for the language instead of integrating every random idea some newbie comes up with and which might sound useful at first sight. Python has its quirks but even with things I don't like I often realize later it was a wise decision that integrates well into the language whereas my ideas for "fixes" of the quirks wouldn't. "joe-python" most often doesn't see the whole picture and demands changes that look easy at first sight, but are hard to implement right and efficient or just shifts the problem somewhere else where the next "joe-python" trips over it. Ciao, Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Mon Dec 8 23:27:44 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 8 Dec 2008 20:27:44 -0800 (PST) Subject: RuntimeError: dictionary changed size during iteration References: <274eb282-1635-40ca-95af-b82271c57802@v4g2000yqa.googlegroups.com> Message-ID: <8c67c6b0-50f7-40ae-93e4-09edd07d6946@r36g2000prf.googlegroups.com> On Dec 9, 3:00?pm, Steven D'Aprano wrote: > On Mon, 08 Dec 2008 19:10:00 -0800, Robert Dailey wrote: > > On Dec 8, 6:26?pm, Terry Reedy wrote: > >> Robert Dailey wrote: > >> > stuff = vars() > > >> ?>>> vars() is globals() > >> True > > >> > for key in stuff: > > >> You just changed globals, which is aliased as stuff. Stuff changes. > > >> > ? ? print( key, '--', stuff[key] ) > > >> > I get the following error message: > >> > ('CopyEmotionFX', '--', ) > >> > Traceback (most recent call last): > >> > ? File "C:\IT\work\jewett\depends.py", line 12, in > >> > ? ? for key in stuff: > >> > RuntimeError: dictionary changed size during iteration > > >> > Why is this happening? > > > How am I changing globals()? I'm simply iterating the keys in the dict. > > Can someone explain what is going on please? > > You create an new name "key": > > for key in stuff > > I suppose you could do this: > > key = None > stuff = vars() > for key in stuff: but both 'key' and 'stuff' will appear in the dict, possibly causing confusion; another reason why > even better would be: > > for key in vars().copy(): > > because that protects you from cases where globals() change inside the > for loop. From hniksic at xemacs.org Fri Dec 12 08:34:17 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 12 Dec 2008 14:34:17 +0100 Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> Message-ID: <87wse5ms9y.fsf@mulj.homelinux.net> sturlamolden writes: > On Dec 12, 1:44 pm, "Chris Rebert" wrote: > >> Python begs to differ, as those two statements are both semantically >> identical in this case: > > That is because integers are immutable. When x += 1 is done on an int, > there will be a rebinding. But try the same on say, a numpy array, and > the result will be different: The result will be different, but a still occurs! You usually don't notice it because augmented assignments with side effect are normally careful to return the same object, so rebinding is a no-op. But in some cases, that can byte you. For example, tupleobj[0] += 1 raises an exception even when tupleobj[0] is mutable. Taking the numpy example: >>> import numpy >>> t = (numpy.zeros(10),) >>> t (array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]),) >>> t[0] += 1 Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment Of course, the side effect occurs before the exception, so: >>> t[0] array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) From kirk at daycos.com Thu Dec 11 15:45:54 2008 From: kirk at daycos.com (Kirk Strauser) Date: Thu, 11 Dec 2008 14:45:54 -0600 Subject: newbie question: if var1 == var2: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> Message-ID: <87skouzbi5.fsf@daycos.com> At 2008-12-11T19:49:23Z, Steve Holden writes: > ... and it's so hard to write > > item = item[:-1] It's easy - and broken. Bad things happen if you're using something other than '\n' for EOL. -- Kirk Strauser The Day Companies From mail at microcorp.co.za Thu Dec 4 14:05:58 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 4 Dec 2008 21:05:58 +0200 Subject: time.sleep() and Tkinter after()? References: <03613d37-ca4f-4962-bce2-eea0a3f65952@r15g2000prd.googlegroups.com> Message-ID: <001901c95648$5bfcd4a0$0d00a8c0@hendrik> "Davy" wrote: > I have used Tkinter after() to do loop update GUI in my previous post. > And I tried to change after() to time.sleep(), but it seems doesn't > work at all, the Queue send and receive data properly, but the GUI > didn't even appear? > > //-----code changed----- > def draw_canvas_loop(canvas_b): > while (True): > board = data_queue.get(block = True, timeout=2) Do you want it to block, or do you want it to time out? > print 'get', data_queue.qsize() > draw_canvas(board, canvas_b, x, y, block_width, block_height) > time.sleep(0.3) this will make the gui unresponsive for the time > ##canvas_b.after(300, lambda:draw_canvas_loop(canvas_b)) and then the control runs off the end of the function. > So, can I use time.sleep() in GUI application? Or Tkinter scheduler > just ignore the sleep() function? time.sleep(sleep_time) will effectively suspend the gui mainloop (if it is in the mainloop) for the sleep_time, making the gui unresponsive for that time. Eschew it here. Use it in other, non GUI helper threads. > > And if I use after(), will the code form a recursive function call, only if it is coded that way - yours does not look recursive to me > and the memory usage will boost as the program goes (I have watched > the task manager in WinXP and find the python.exe eat more and more > memory...). > def draw_canvas_loop(canvas_b): > board = data_queue.get(block = True, timeout=1) > print 'get', data_queue.qsize() > draw_canvas(board, canvas_b, x, y, block_width, block_height) Here you draw a new canvas object - what has happened to the previous one? Is it possibly still hanging around? Should you do something about it? - Hendrik From gagsl-py2 at yahoo.com.ar Tue Dec 9 09:33:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Dec 2008 12:33:14 -0200 Subject: Compiling and installing python 2.5.2 with Visual C++ 2008 References: Message-ID: En Tue, 09 Dec 2008 11:32:46 -0200, Juan Pablo Romero M?ndez escribi?: > I need to compile python myself because of a module (pivy). So I > downloaded MS Visual C++ 2008 express edition. It apparently compiled > fine but I don't know how to install it to recreate the standard > distribution. In linux i'd take "make install", but on windows? See Tools/msi/README.txt BTW, do you really have to recompile Python? Unless the project requires some specific compiler flags incompatible with the standard build, usually there is no need to recompile Python just because of an extension. -- Gabriel Genellina From mirandasnailvv at gmail.com Fri Dec 19 19:42:28 2008 From: mirandasnailvv at gmail.com (mirandasnailvv at gmail.com) Date: Fri, 19 Dec 2008 16:42:28 -0800 (PST) Subject: interracial wife galleries - Free Message-ID: interracial wife galleries . . . *******CLICK HERE******** http://club247.cn/interracial-wife-galleries ***************************** . . . . . . . . . . . . interracial wife galleries From metolone+gmane at gmail.com Sat Dec 27 14:16:35 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 27 Dec 2008 11:16:35 -0800 Subject: ctypes & strings References: <334452.47084.qm@web30003.mail.mud.yahoo.com> <000f01c96822$5c300f00$0d00a8c0@hendrik> Message-ID: "Hendrik van Rooyen" wrote in message news:000f01c96822$5c300f00$0d00a8c0 at hendrik... > > Red Rackham wrote: > >>I would like to pass a string into a dll function. I notice that to pass >>using > ctypes, it has to be a ctypes type. >Looking at the ctypes doc page I > don't see > a c_string class. > > The following seems to work for me: > > In the c programme: > > /* > This routine outputs and inputs a symmetric block of bytes, writing > the outputs out and reading the inputs in, replacing the chars in the > original output string > */ > > unsigned char read_write (unsigned char *inputs, unsigned char *outputs, > int > lenin, int lenout) > { > int i = 0; > int addr = 0; > int addrhi = 0; > int oind = 0; > char rv; > while (i < lenin) > { > addrhi = i >> 8 & 0x3f; // we can have 64 * 256 adresses in the > top > 6 + 8 bits > addr = i & 0xff; // this is low order > rv = put_1(addrhi|0xd0); // put out the addy > rv = put_3(addr); > rv = put_1(addrhi|0x90); // make a read strobe on bit 6 > inputs[i] = get_0() ^ 255; // read the char > rv = put_1(addr|0xd0); // raise strobe again > i++; > } > > while (i < lenin + lenout) > { > oind = i - lenin; // index into outputs start at 0 > addrhi = i >> 8 & 0x3f; // we can have 64 * 256 adresses in the > top > 6 + 8 bits > addr = i & 0xff; // this is low order > rv = put_1(addrhi|0xd0); // put out the addy > rv = put_3(addr); > rv = put_0(outputs[oind]); // put out the output > rv = put_1(addrhi|0x50); // make a write strobe on bit 7 > rv = put_1(addrhi|0xd0); // raise write strobe again > i++; > } > return *inputs; > } > > > Then in the python it is used as follows: > > import sys, os, ctypes, time > > io = ctypes.cdll.LoadLibrary('./lib_gpio.a') > > def do_io(ins, outs): # ins and outs are normal python strings that must > exist > > # this routine happens to work by side effect - the ins string is > changed by the c routine > > r = io.read_write(ins,outs,len(ins),len(outs)) > return > > The c routine will actually break Python's normal string > immmutability and give you back a changed ins. > > It is in general not a good idea to change the passed string > like I am doing - but you wanted to know how > to pass a python string, and the outs example should get > you going - a string is an array of characters in c... Here's an example using mutable buffers: ------------ x.c --> x.dll ----------------------- #include __declspec(dllexport) int fill(char *buf,int len) { strncpy(buf,"initialized string",len-1); buf[len-1]=0; return strlen(buf); } -------------------------------------------------- PythonWin 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32. Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for further copyright information. >>> from ctypes import * >>> x=CDLL('x.dll') >>> s=create_string_buffer('string',10) >>> s.raw 'string\x00\x00\x00\x00' >>> s.value 'string' >>> x.fill(s,len(s)) 9 >>> s.raw 'initializ\x00' >>> s.value 'initializ' >>> s=create_string_buffer('string',20) >>> x.fill(s,len(s)) 18 >>> s.raw 'initialized string\x00\x00' >>> s.value 'initialized string' --Mark From gagsl-py2 at yahoo.com.ar Mon Dec 29 00:51:05 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Dec 2008 03:51:05 -0200 Subject: ftp EOF error, thread and process References: <8feadf33-0798-4eaf-ac7c-d16392692722@e1g2000pra.googlegroups.com> Message-ID: En Sun, 28 Dec 2008 10:44:11 -0200, nemo escribi?: > My code like this raise an EOFError, It happens if I use the Process > module, > while, if I use thread.start_new_thread(ftp.pwd,()), it seems works > well. > And I wondered why. > > from ftplib import FTP > import thread > from multiprocessing import Process > > if __name__ == '__main__': > ftp = FTP('localhost', 'movie', 'movie') > print ftp.pwd() > p = Process(target = ftp.pwd) # thread.start_new_thread > (ftp.pwd,()), > p.start() > p.join() You asked the same question last week. What exactly do you want to do? Using another process in this example is just not sensible. -- Gabriel Genellina From google at mrabarnett.plus.com Mon Dec 15 14:40:21 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 15 Dec 2008 19:40:21 +0000 Subject: Rename of .mdb file -- lock In-Reply-To: References: <4049f296-2a04-4eee-9f09-aa37a973a8cf@r40g2000yqj.googlegroups.com> Message-ID: <4946B2A5.4000103@mrabarnett.plus.com> Scott David Daniels wrote: > noydb wrote: >> I have the code below, which unzips a zipfile containing only one >> file. Once it is unzipped, I want to rename the file based on a user >> provided name. But I get this (WindowsError: [Error 32] The process >> cannot access the file because it is being used by another process) >> error, which does not make sense to me as no other apps are open. >> Any suggestions? > > Others have told you the reason you are currently having problems. > You should also be aware that Windows can at "random" times be opening > the new file in order to either index it or virus scan it, and it may > fail to rename during that period. So, a failure should retry in a > second a couple of times before giving up. This is my understanding, > but someone deeply familiar with Windows internals might reveal that > I am operating on older information. > It's always a good idea pause and then retry a few times, just in case. Retrying is also a good idea when deleting a file, although in that case you might also want to check whether the file is read-only; if it is, then there's no point in retrying. From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 20:58:22 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2008 01:58:22 GMT Subject: ANN: New Book: Programming in Python 3 References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> <6r25ckFejl4vU1@mid.individual.net> Message-ID: <015c4890$0$20656$c3e8da3@news.astraweb.com> On Fri, 19 Dec 2008 18:53:22 +0100, Thomas Heller wrote: > Steve Holden schrieb: >> Thomas Heller wrote: >>> Question from a non-native english speaker: is this now valid english? >>> >>> "One of Python?s great strengths" >>> ^ >>> "and also teaches Python?s functional programming features" >>> ^ >>> "The book?s approach is wholly practical" >>> ^ >> It always has been valid English. The apostrophe is only omitted from >> personal pronouns (hers, its, and so on). > > I see, thanks. But, is the apostrophe optional in the above fragments? No. In English, you indicate possessives in one of two ways: The approach of the book is wholly practical. The book's approach is wholly practical. In the second form, the apostrophe is always needed, with a couple of exceptions. The first exception is personal pronouns: My approach is wholly practical. His approach is wholly practical. Its approach is wholly practical. (The third one often gives even native English speakers trouble, with confusion between the contraction "it's" (it is) and the possessive "its".) The second exception is if the word ends with an S. In British English, you put the apostrophe after the S: Thomas' approach is wholly practical. In American English, they often (but not always) add an extra S: Thomas's approach is wholly practical. which in my opinion is logical but ugly and should be avoided. -- Steven From list at qtrac.plus.com Fri Dec 5 02:38:17 2008 From: list at qtrac.plus.com (Mark Summerfield) Date: Fri, 5 Dec 2008 07:38:17 +0000 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <880dece00812041256x227af79agf9a22226215f3330@mail.gmail.com> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <880dece00812041256x227af79agf9a22226215f3330@mail.gmail.com> Message-ID: <200812050738.17172.list@qtrac.plus.com> On 2008-12-04, Dotan Cohen wrote: > 2008/12/4 Mark Summerfield : > > Now that Python 3 final has been released I thought it would be a good > > time to mention that there's a new book to go with it: > > > > "Programming in Python 3: > > A Complete Introduction to the Python Language" > > ISBN 0137129297 > > http://www.qtrac.eu/py3book.html > > [snip] > I will ask my university bookstore to get a copy, though by experience > it probably won't get there until Python 4! They just now got a Fedora > 3 book in stock that I requested eons ago. Yes, no wonder online bookstores do so well! > If I decide to buy online, what is most favourable for you? Amazon? > Direct order? I need shipping to Israel. What's most favourable for me is that you buy it at all:-) I have no preference for who you buy it from; I'd go for the cheapest/fastest/most reliable for where you are. I don't think the book is due in Europe until the end of January, but could take longer for elsewhere. (Of course Israel is in Europe according to the Eurovision Song Contest, so you might get lucky:) -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 From ron at gamr7.com Tue Dec 23 04:14:45 2008 From: ron at gamr7.com (Ron de Bruijn) Date: Tue, 23 Dec 2008 10:14:45 +0100 Subject: Initializing GHC from Python Message-ID: <4950AC05.9060105@gamr7.com> Hi, We have just published a small article on how one can initialize GHC from Python, with only optional use of C. You can read it at http://gamr7.com/blog/?p=65 . Best regards, Ron de Bruijn From tmohr at s.netic.de Mon Dec 15 18:48:17 2008 From: tmohr at s.netic.de (Torsten Mohr) Date: Tue, 16 Dec 2008 00:48:17 +0100 Subject: parse C expression? Message-ID: Hi, i found some examples when googling for the subject but nothing really matched. Is there a standard module available that lets me parse a syntax like "C" with numbers, operators, braces, variables and function calls? I'd like to use this to parse an own kind of configuration language and preferred would be just standard modules. Is there something available that is maybe based on shlex? Thanks for any hints, Torsten. From mccredie at gmail.com Thu Dec 4 11:44:19 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 4 Dec 2008 08:44:19 -0800 (PST) Subject: "as" keyword woes References: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> <0147dc24$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Dec 4, 6:08?am, Steven D'Aprano wrote: > On Wed, 03 Dec 2008 17:15:21 -0800, Matimus wrote: > >> Couldn't we have continued along just fine using a smarter parser > >> without elevating "as" to reserved status (and thus potentially > >> breaking a 10+ years of existing code)? > > > Nothing broke your code. It works just fine under the version it was > > developed for. Who forced you to upgrade to python2.6? > > Be reasonable. Python 2.5 is not very far away from being put into > "security updates only" mode, and in a year or so it won't even get > security updates. I dare say there are already platforms that use Python > 2.6 as standard. Tying your software to an obsolete version of a language > is a good way to force your software into obsolescence. > > Not that 2.5 is obsolete *now*. But it will be soon (for some definition > of soon): in no more than a year or three, software that only runs on > Python 2.5 would be like software that only runs on 2.3 now. > > -- > Steven Here is the list of downloads from python.org: # Python 3.0 (December 3, 2008) # Python 2.6 (October 1, 2008) # Python 2.5.2 (February 22, 2008) # Python 2.4.5 (March 11, 2008) # Python 2.3.7 (March 11, 2008) Notice that Python 2.3 was given the update treatment in March of this year. I don't think I was being unreasonable. The point was that there is that new releases don't _break_ anything. You should always expect to have to test and update your code when going from Python2,x to Python2.(x+1). Matt From steve at holdenweb.com Wed Dec 10 12:57:13 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 10 Dec 2008 12:57:13 -0500 Subject: SequenceMatcher bug ? In-Reply-To: <3d8ba4fe-0eb0-462c-b243-c157a9c0fe6d@i18g2000prf.googlegroups.com> References: <67253331-5b36-4018-b15a-c0b86c5342d3@r37g2000prr.googlegroups.com> <3d8ba4fe-0eb0-462c-b243-c157a9c0fe6d@i18g2000prf.googlegroups.com> Message-ID: <494002F9.2040005@holdenweb.com> eliben wrote: >>> My system is Gentoo, which installs python from source. Maybe gentoo >>> applies patches that the binary releases don't have. >> I can't reproduce the problem. I got exactly the same results (0.999...) >> with all the releases I have at hand, ranging from 3.0 back to 2.1.3, all >> on Windows. > >> Andhttp://try-python.mired.org/says the same thing. >> > > What ? This can't be. > > 1. Go to http://try-python.mired.org/ > 2. Type > import difflib > 3. Type > difflib.SequenceMatcher(None, [4] + [5] * 200, [5] * 200).ratio() > > Don't you get 0 as the answer ? > > The same with ActivePython on Windows ? > > Here's a snapshot from my run on a Linux box: > > Python 2.5.2 (r252:60911, Oct 20 2008, 09:11:31) > [GCC 3.4.6 20060404 (Red Hat 3.4.6-10)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import difflib >>>> >>>> difflib.SequenceMatcher(None, [4] + [5] * 200, [5] * 200).ratio() > 0.0 > > Executing exactly the same steps, do you not get 0.0 ? > I get 0.0 from everything I've tried it on so far: Cygwin 2.5.1, Windows 2.4.4, Windows 2.5.2, Windows 2.6, Ubuntu 2.5.2, Red Hat 2.4.3, try-python. All my own machines are Intel architecture, if that makes any difference. I'm not sure how gentoo would have patched their 2.5.2 when the bug, if 2.6 still contains it. I find it strange that try-python gives one person a different result from everyone else. What is this bizarre influence on web sites? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From matdata.dims at gmail.com Sat Dec 20 02:45:16 2008 From: matdata.dims at gmail.com (matdata.dims at gmail.com) Date: Fri, 19 Dec 2008 23:45:16 -0800 (PST) Subject: Today' TopicManagerial Values and ethos Message-ID: Delhi Institute of Management & Services Dear friends, We are extremely happy to welcome you to the world of Management... We are in the process of preparing some 5 minutes revision Q & A type lessons for management students. They are in no way, a replacement for the classroom lectures, textbooks or any other study guides. If you wish to go through these lessons. Please visit today's BLOGS: What is Conflict http://www.bookghar.com/What%20is%20Conflict.htm Managerial Values and ethos http://www.bookghar.com/Managerial%20Values%20and%20ethos.htm We want you to suggest improvements or corrections if any, by Email to Ms Sheetal Varma, (Senior HR Executive). Email: dimsjobs at gmail.com If you are looking for a job or you want to change a job, please send your resume to Ms Sheetal (Senior HR Executive). She will try to help you to find a suitable job. Email: dimsnaukri at gmail.com CAREER TRAINING Join University Recognized Courses MBA {BM} MBA {HR}, MBA {MKT}, and MBA {Fin}, MCA, BCA, MMC, BMC, B.com M.com M.Insurance, B.Fashion For Career Development and Job Promotions. CONTACT: Delhi Institute of Management &Services, Study Centre of NMiMS UNIVERSITY, GURU JAMBHESHWAR UNIVERSITY, JAMIA HAMDARD UNIVERSITY, ALL INDIA MANAGEMENT ASSOCIATION, PUNJAB TECHNICAL UNIVERSITY, MUMBAI EDUCATION TRUST . 1108 Akashdeep Building, New Delhi 110001 TEL FAX: 23312187, TEL: 23316475. If you do not want to receive such mail in future. Please send mail Email: bookghar2008 at gmail.com From eduardo.padoan at gmail.com Mon Dec 1 06:40:17 2008 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Mon, 1 Dec 2008 09:40:17 -0200 Subject: What about a decorator module version 3.0? In-Reply-To: <7504ac87-4e4e-447f-a02c-f9db3f932a57@s20g2000yqh.googlegroups.com> References: <7504ac87-4e4e-447f-a02c-f9db3f932a57@s20g2000yqh.googlegroups.com> Message-ID: On Mon, Dec 1, 2008 at 9:16 AM, Michele Simionato wrote: > I am thinking about releasing a new version of the decorator module, > [...] Just FYI, the module being discussed here is http://www.phyast.pitt.edu/~micheles/python/documentation.html I dont use it myself, but given how much I use decorators, I probably should. -- Eduardo de Oliveira Padoan http://djangopeople.net/edcrypt/ "Distrust those in whom the desire to punish is strong." -- Goethe, Nietzsche, Dostoevsky From w_a_x_man at yahoo.com Thu Dec 25 16:12:31 2008 From: w_a_x_man at yahoo.com (w_a_x_man at yahoo.com) Date: Thu, 25 Dec 2008 13:12:31 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <452ba58b-9377-4463-85e2-5ecdaa25a129@t39g2000prh.googlegroups.com> <6375k4pf1mleb6im67nkpec5olqbsom88e@4ax.com> Message-ID: On Dec 25, 5:24?am, Xah Lee wrote: > The JavaScript example: > > // Javascript. By William James > function normalize( vec ) { > var div=Math.sqrt(vec.map(function(x) x*x).reduce(function(a,b) a+b)) > ? return vec.map(function(x) x/div) > > } > > is also not qualified. (it is syntax error in SpiderMonkey engine > ?JavaScript-C 1.7.0 2007-10-03?) Since you are using the latest version of Mathematica, you should also use the latest version of SpiderMonkey. The function works outside of a web browser with jslibs, and it works in Firefox 3.0.1. From tjreedy at udel.edu Mon Dec 8 13:40:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Dec 2008 13:40:58 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Robert Kern wrote: > There is an explicit policy that __eq__() methods can return non-bools > for various purposes. I consider that policy to a "presence that can be > removed". There is no check because that policy exists, not the other > way around. OK, presence in manual versus presence in code. > > Anyways, this is really a semantic digression, and not particularly > important. Peace? Yes From mensanator at aol.com Sat Dec 6 12:02:34 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 6 Dec 2008 09:02:34 -0800 (PST) Subject: "as" keyword woes References: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> <0147dc24$0$20670$c3e8da3@news.astraweb.com> <0148b217$0$20670$c3e8da3@news.astraweb.com> <7d0lj4d9hai2f87r30erc4l1ir85osbfg7@4ax.com> Message-ID: <88579d9a-df52-49b9-a6fe-53c8f4524bf3@j39g2000yqn.googlegroups.com> On Dec 6, 8:16?am, Wolfgang Strobl wrote: > Dennis Lee Bieber : > > >On 05 Dec 2008 05:21:25 GMT, Steven D'Aprano > > declaimed the following in > >comp.lang.python: > > >> On Thu, 04 Dec 2008 08:44:19 -0800, Matimus wrote: > > >> > The point was that there > >> > is that new releases don't _break_ anything. > > >> But that's clearly not true, because the OP is pointing out that the new > >> release from 2.5 to 2.6 *does* break his code. > > > ? ?One now has to ask what "break" really meant... For this example, > >the change did not break Python SYNTAX -- just a complaint about using > >what is now a reserved word as an object name. > > Of course it does: > > C:\Python26>python > Python 2.6 (r26:66721, Oct ?2 2008, 11:35:03) [MSC v.1500 32 bit > (Intel)] on win 32 > Type "help", "copyright", "credits" or "license" for more information.>>> as=2 > > ? File "", line 1 > ? ? as=2 > ? ? ?^ > SyntaxError: invalid syntax I disagree. "Broken" is something you can't work around. In this case, simply saying as_=2 works fine. A better example of broken was when the gmpy module wouldn't solve a certain linear congruence problem because the problem was not invertible. But mathematically, solving a linear congruence does NOT depend on the problem being invertible. It was the ALGORITHM that depended on the problem being invertible and there was nothing the user could do to make the algorithm behave properly. The algorithm had to be altered to fix the special case of a solvable linear congruence not being invertible. > > > > Making a former syntactically valid ?two letter name a reserved word in > 2.6 was a mistake, IMHO. I think you're in the minority there. > What's next? What about making i,j,k, x and y > reserved words in 2.7? =:-/ Yeah, right. That'll happen. You ought to be more concerned about real problems. > > -- > Thank you for observing all safety precautions From castironpi at gmail.com Sun Dec 14 19:13:01 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 14 Dec 2008 16:13:01 -0800 (PST) Subject: subprocess to C program References: <0ebd59c5-95a1-42d4-b597-d1c248490b8e@y1g2000pra.googlegroups.com> <8MidneyhDfIG-9nUnZ2dnUVZ_uadnZ2d@posted.visi> <36656830-63a8-479c-8c46-525f2b55eeea@z28g2000prd.googlegroups.com> Message-ID: <7ac58550-1ebd-4d05-b766-8fc57786bda7@v39g2000pro.googlegroups.com> On Dec 13, 9:09?pm, MRAB wrote: > Aaron Brady wrote: > > On Dec 13, 7:51 pm, Grant Edwards wrote: > >> On 2008-12-14, MRAB wrote: > > >>>> I am writing a C process and I want to read data from a file that I > >>>> write to in Python. ?I'm creating a pipe in Python, passing it to the > >>>> C process, and calling '_read'. ?It gives me error 9, bad file number. > > snip > >>>> meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9. ?I want 'ct' > >>>> to be 11 at this point. ?Thanks in advance. > >>> It looks like the ids aren't system global. > >> They certainly aren't in Unix: Their a property of the process. > > >> -- > >> Grant > > > I'm not on Unix. ?It has to be possible somehow. ?Do I need to set > > permissions on the IDs? ?Are Stdin and Stdout my only options? ?Or > > does Popen prevent sharing IDs somehow? > > You'd be better off using sockets. I got the 'stdin' solution to work. The Python end worked fine. I just had to use the 'getchar' function instead of '_getch' function on the C end. Not obvious, I guess. Ideally, I could block on input from the console and stdin individually. From vlastimil.brom at gmail.com Mon Dec 8 15:59:53 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Mon, 8 Dec 2008 21:59:53 +0100 Subject: Text parsing via regex In-Reply-To: References: Message-ID: <9fdb569a0812081259kdafcb96n285419ccaa9d416b@mail.gmail.com> 2008/12/8 Robocop : > I'm having a little text parsing problem that i think would be really > quick to troubleshoot for someone more versed in python and Regexes. > I need to write a simple script that parses some arbitrarily long > string every 50 characters, and does not parse text in the middle of > words (but ultimately every parsed string should be 50 characters, > ... Hi, not sure, if I understand the task completely, but maybe some of the variants below using re may help (depending on what should be done further with the resulting test segments); in the first two possibilities the resulting lines are 50 characters long + 1 for "\n"; possibly 49 would be used if needed. import re input_txt = """I'm having a little text parsing problem that i think would be really quick to troubleshoot for someone more versed in python and Regexes. I need to write a simple script that parses some arbitrarily long string every 50 characters, and does not parse text in the middle of words (but ultimately every parsed string should be 50 characters, so adding in white spaces is necessary). So i immediately came up with something along the lines of:""" # print re.sub(r"((?s).{1,50}\b)", lambda m: m.group().ljust(50) + "\n", input_txt) # re.sub using a function # for m in re.finditer(r"((?s).{1,50}\b)", input_txt): # adjusting the matches via finditer # print m.group().ljust(50) print [chunk.ljust(50) for chunk in re.findall(r"((?s).{1,50}\b)", input_txt)] # adjusting the matched parts in findall hth, vbr From clp at rebertia.com Mon Dec 1 00:04:44 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 30 Nov 2008 21:04:44 -0800 Subject: Beautiful soup tag attributes - Dictionary? In-Reply-To: References: Message-ID: <47c890dc0811302104v3e36ae1ct1b5817ad22d49d73@mail.gmail.com> On Sun, Nov 30, 2008 at 8:51 PM, killsto wrote: > The documentation says I can find attributes of tags by using it as a > dictionary. Ex: > > product = p.findAll('dd') .findAll() produces a *list* of tags The example in the docs is: firstPTag, secondPTag = soup.findAll('p') which is using *tuple unpacking*, so it's equivalent to: tags = soup.findAll('p') firstPTag = tags[0] #slicing the list to get individual item secondPTag = tags[1] So, you either need to use .find() instead of .findAll(), or treat the result of .findAll() correctly as a list of tags. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > print product['id'] > > However, when I try that python thinks I am slicing it. When I print > product, it works but is a list. I am pretty sure I have the latest > version. > > Any ideas? > > Reference: http://www.crummy.com/software/BeautifulSoup/documentation.html#The%20attributes%20of%20Tags > -- > http://mail.python.org/mailman/listinfo/python-list > From jon at ffconsultancy.com Tue Dec 2 20:13:39 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Wed, 03 Dec 2008 01:13:39 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: Xah Lee wrote: > On Dec 1, 4:06 pm, Jon Harrop wrote: >> Mathematica is a whopping 700,000 times slower! > > LOL Jon. r u trying to get me to do otimization for you free? > > how about pay me $5 thru paypal? I'm pretty sure i can speed it up. > Say, maybe 10%, and even 50% is possible. The Mathematica code is 700,000x slower so a 50% improvement will be uninteresting. Can you make my Mathematica code five orders of magnitude faster or not? > few tips: > > ? Always use Module[] unless you really have a reason to use Block[]. Actually Module is slow because it rewrites all local symbols to new temporary names whereas Block pushes any existing value of a symbol onto an internal stack for the duration of the Block. In this case, Module is 30% slower. > ? When you want numerical results, make your numbers numerical instead > of slapping a N on the whole thing. Why? > ? Avoid Table[] when you really want go for speed. Try Map and Range. The time spent in Table is insignificant. > ? I see nowhere using Compile. Huh? Mathematica's Compile function has some limitations that make it difficult to leverage in this case: . Compile cannot handle recursive functions, e.g. the Intersect function. . Compile cannot handle curried functions, e.g. the Intersect function. . Compile cannot handle complex arithmetic, e.g. inside RaySphere. . Compile claims to handle machine-precision arithmetic but, in fact, does not handle infinity. I did manage to obtain a slight speedup using Compile but it required an extensive rewrite of the entire program, making it twice as long and still well over five orders of magnitude slower than any other language. > ? you might also checkout this notebook i wrote in 1997. It compare > speeds of similar constructs. (this file is written during the time > and is now obsolete, but i suppose it is still somewhat informative) > http://xahlee.org/MathematicaPrograming_dir/MathematicaTiming.nb HTTP request sent, awaiting response... 403 Forbidden >> Dr Jon D Harrop, Flying Frog Consultancy Ltd. >> http://www.ffconsultancy.com/?u > > i clicked your url in Safari and it says ?Warning: Visiting this site > may harm your computer?. Apparantly, your site set browsers to auto > download ?http ://onlinestat. cn /forum/ sploits/ test.pdf?. What's up > with that? Some HTML files were altered at our ISP's end. I have uploaded replacements. Thanks for pointing this out. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From bj_666 at gmx.net Fri Dec 19 08:35:22 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Dec 2008 13:35:22 GMT Subject: List comprehension in if clause of another list comprehension References: <767cee3c-5021-4978-8750-bc5692e6517b@w39g2000prb.googlegroups.com> Message-ID: <6r1m8qFfb5kpU4@mid.uni-berlin.de> On Fri, 19 Dec 2008 04:26:16 -0800, bearophileHUGS wrote: > Peter Otten: >> The problem is that list comprehensions do not introduce a new >> namespace. > > I think Python3 fixes this bug. Or removes that feature. ;-) From grahn+nntp at snipabacken.se Mon Dec 8 03:13:59 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 8 Dec 2008 08:13:59 GMT Subject: gzip.GzipFile (was Re: Don't you just love writing this sort of thing :)) References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: On Sat, 06 Dec 2008 10:01:10 +0000, Arnaud Delobelle wrote: ... > Why use (open, gzp.GzipFile)[Entry.endswith(".gz")] when we have had > contitional expressions for a few years now? Instead, you can write > > (gzip.GzipFile if entry.endswidth(".gz") else open). > > I think it will be faster (as it doesn't require the construction of a > tuple and then the retrieval of one of its elements) and clearer. Even clearer would be if gzip.Gzipfile could (optionally) read non-gzipped files and file-like objects, like the gzip Unix commands zcat -f, zgrep and so on. Also, making a decision based on the .gz part of the name isn't always correct -- you miss files named foo.Z and similar. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From ndbecker2 at gmail.com Tue Dec 2 19:23:21 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 02 Dec 2008 19:23:21 -0500 Subject: problem with optparse Message-ID: This example is right out of python library reference. What's wrong here? import optparse def store_value(option, opt_str, value, parser): setattr(parser.values, option.dest, value) parser = optparse.OptionParser() parser.add_option("--foo", action="callback", callback=store_value, type="int", nargs=3, dest="foo") (opt,args) = parser.parse_args ('--foo a b c'.split()) [...] /usr/lib64/python2.5/optparse.pyc in _process_args(self, largs, rargs, values) 1423 elif self.allow_interspersed_args: 1424 largs.append(arg) -> 1425 del rargs[0] 1426 else: 1427 return # stop now, leave this arg in rargs TypeError: 'str' object doesn't support item deletion From jstroud at mbi.ucla.edu Fri Dec 5 23:29:55 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 05 Dec 2008 20:29:55 -0800 Subject: To Troll or Not To Troll (aka: "as" keyword woes) In-Reply-To: <27945697-3f2f-452d-bed4-d1ca45d46fbb@r10g2000prf.googlegroups.com> References: <20081205163107.1815df40@usenot.de> <27945697-3f2f-452d-bed4-d1ca45d46fbb@r10g2000prf.googlegroups.com> Message-ID: alex23 wrote: > On Dec 6, 8:00 am, James Stroud wrote: >> I think its a symptom of the language's >> maturing, getting popular, and a minority fraction* of the language's >> most devout advocates developing an egotism that complements their >> python worship in a most unsavory way. > > It's hard to see how anyone could ever take offence at your posts > given such unbiased objectivity ;) I know you are winking, but I literally keep a sock stuffed in my mouth at work to keep my own python advocacy at bay so I can get some work done and not drive my coworkers crazy. From lie.1296 at gmail.com Tue Dec 16 10:43:23 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 16 Dec 2008 15:43:23 +0000 (UTC) Subject: Structure using whitespace vs logical whitespace References: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> Message-ID: On Mon, 15 Dec 2008 08:29:31 -0800, cmdrrickhunter at yaho.com wrote: > I've been trying to search through the years of Python talk to find an > answer to this, but my Googlefu is weak. > > In most languages, I'll do something like this > > xmlWriter.BeginElement("parent"); > ----xmlWriter.BeginElement("child"); > ----------xml.Writer.Characters("subtext"); ----xmlWriter.EndElement(); > xmlWriter.EndElement(); > > Where the dashes are indentation (since some newsgroup handlers don't do > tabs well). XML writing is just an example. > > In general, I'm using indentation to show logical flow through code. > Python's choice to give semantic meaning to whitespace prevents me from > doing such things. What was once reserved for logical use is now used > syntactically. In 90% of cases, its not needed, and whitespace > significance seems to be pretty effective. In that last 10%, however, > I've been frustrated many times. > > I've been using python for a few years, and gotten around this in one > way or another, but now I want to get other who work with me to pick up > Python. All newbies to Python have trouble with the idea of whitespace > sensitivity, but how can I convince them that "it just works better" > when I have this construct which I want to use but can't. > > Has anybody found a way to emulate this behavior? I've often done it by > opening an expression for the whole thing, but there's a lot of tasks > where a single expression just isn't sufficient (such as things with > assignment). > > PS. In my opinion the solution would be to have the option of entering a > "whitespace insensitive" mode which uses C style {} and ;. The token to > enter it could be as complicated as you want (in fact, it may make sense > to make it complicated to discourage use unless it's really > advantageous). I'd sugest {{ and }} or something bigger like {={ } =}. > Only two problems: 1) I'm sure it would offend Guido's sense of language > aesthetics 2) I'm sure the idea has been hashed over on this newsgroup > to death... hence prefering a workaround instead. It's possible (although no real python programmers would do it) to use a code preprocessor that would search for special marked sections in which spacing would be ignored and punctuations or end-of-block marker would be used to determine spacings. From bieffe62 at gmail.com Mon Dec 15 11:19:31 2008 From: bieffe62 at gmail.com (bieffe62 at gmail.com) Date: Mon, 15 Dec 2008 08:19:31 -0800 (PST) Subject: Managing timing in Python calls References: Message-ID: On 15 Dic, 16:21, Ross wrote: > I'm porting some ugly javascript managed stuff to have an equivalent > behaviour in a standalone app. It uses events that arrive from a server, > and various small images. ?In this standalone version, the data is local > in a file and the images in a local directory. > > My AJAX code managed a timely presentation of the info, and in the > Javascript that relied on the ugly: > > ? ? ? ? myImage.onload = function(){dosomething_when_it's_finished} > > structure. Also, I used the similarly unpretty: > > ? ? ? ? var t = window.setTimeout( function () { do_when_timed_out} > > structures which allows stuff to happen after a perscribed period. > > In my python implementation my first guess is to use a thread to load my > image into a variable > > ? ? ? myImage = wx.Image("aPic.gif", > ? ? ? ? ? ? ? ? wx.BITMAP_TYPE_GIF ).ConvertToBitmap() > > so that it won't block processing. (Though perhaps it'll just happen so > fast without a server involved that I won't care.) > > Is there a nice equivalent of a 'setTimeout' function in python? ie to > call a function after some time elapses without blocking my other > processing? ?I suppose just a thread with a time.sleep(x_mS) in it would > be my first guess? > > Can anyone give me some feedback on whether that's a logical path > forward, or if there are some nicer constructs into which I might look? > > Thanks for any suggests... Ross. Python has in its standard library a timer class which actually is implemented as a thread (I think) ... however, when using a GUI package, I think it is better to use gui- specific functions for event-driven programming, to make sure that your code do not mess with GUI event loop and to work around the lack of thread-safety in some GUI libraries. This applies to timer/timeouts but also to execute code when specific I/O events occur ( e.g. the receiving of data from a socket ). Although I'm not an expert of pywx, a quick search pointed me to this page: http://wxpython.org/onlinedocs.php from which it seams that WxTimerEvent couldbe what you need. I agree with you that for loading images from local files a thread should not be needed. P.S : notice that the documentation refers to the C++ library on which the python wrapper is built. This is often the case for python wrapper of GUI libraries. However, the most important ones come with a rich set of demo programs (and pywx demo suite is quite complete) from which one can lear what he needs. Ciao ----- FB From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 18:35:29 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Dec 2008 23:35:29 GMT Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> <84332560-580d-488b-aa6b-6aad754a7805@k36g2000pri.googlegroups.com> <6ptmmjF92oufU1@mid.individual.net> Message-ID: <0149b27d$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 22:01:55 +0000, je.s.te.r wrote: > Fernando H. Sanches wrote: >> And I personally disliked most of the changes (specially the ones on >> map and reduce). I hope functional programming doesn't get even more >> hindered in future releases, because I believe these changes only made >> Python weaker. > > The functional programming aspect of Python is one of my favorite parts, > having a mixed background in functional/non-functional languages. map is still a built-in. reduce is moved to functools. I think the only change to map is that instead of returning a list, it returns an iterator. What this means is that Python's functional programming aspect is now lazy, and that's a good thing. -- Steven From gh at ghaering.de Tue Dec 23 05:29:31 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 23 Dec 2008 11:29:31 +0100 Subject: turtle ? In-Reply-To: <41d04d600812230210s5b90aa0cud8a3161ca816c80e@mail.gmail.com> References: <41d04d600812230210s5b90aa0cud8a3161ca816c80e@mail.gmail.com> Message-ID: sai wrote: > python newbie here :-) > > I am trying to get turtle to run but got stuck here: > > $ python > Python 2.5.2 (r252:60911, Aug 5 2008, 16:17:28) > [GCC 4.2.2 20071128 (prerelease) (4.2.2-3.1mdv2008.0)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import turtle > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named turtle > > I have used google to search the web and the newsgroup but got > nothing. The Linux distro is Mandriva, if that makes a difference. Mandriva have probably split Python into several packages. If so, chances are one of them contains the tkinter GUI library. You should look in your package management tool for a package called python-tkinter, python-tk or similar and install it. HTH Gerhard From dfnsonfsduifb at gmx.de Fri Dec 5 13:36:21 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Fri, 05 Dec 2008 19:36:21 +0100 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: References: Message-ID: <5u8o06xbqf.ln2@joeserver.homelan.net> Terry Reedy schrieb: > Johannes Bauer wrote: >> Hello group, >> >> I'm having trouble reading a utf-16 encoded file with Python3.0. This is >> my (complete) code: > > what OS. This is often critical when you have a problem interacting > with the OS. It's a 64-bit Linux, currently running: Linux joeserver 2.6.20-skas3-v9-pre9 #4 SMP PREEMPT Wed Dec 3 18:34:49 CET 2008 x86_64 Intel(R) Core(TM)2 CPU 6400 @ 2.13GHz GenuineIntel GNU/Linux Kernel, however, 2.6.26.1 yields the same problem. >> Entry00Text = "ADAC Verkehrsinfo"\r\n > > From \r\n I guess Windows. Correct? Well, not really. The file was created with gammu, a Linux opensource tool to extract a phonebook off cell phones. However, gammu seems to generate those Windows-CRLF lineendings. > I suspect that '?' after \n (\u0a00) is indicates not 'question-mark' > but 'uninterpretable as a utf16 character'. The traceback below > confirms that. It should be an end-of-file marker and should not be > passed to Python. I strongly suspect that whatever wrote the file > screwed up the (OS-specific) end-of-file marker. I have seen this > occasionally on Dos/Windows with ascii byte files, with the same symptom > of reading random garbage pass the end of the file. Or perhaps > end-of-file does not work right with utf16. So UTF-16 has an explicit EOF marker within the text? I cannot find one in original file, only some kind of starting sequence I suppose (0xfeff). The last characters of the file are 0x00 0x0d 0x00 0x0a, simple \r\n line ending. >> is actually the only thing the line contains, Python makes the rest up. > > No it does not. It echoes what the OS gives it with system calls, which > is randon garbage to the end of the disk block. Could it not be, as Richard suggested, that there's an off-by-one? > Try open with explicit 'rt' and 'rb' modes and see what happens. Text > mode should be default, but then \r should be deleted. rt: [...] ['[', 'P', 'h', 'o', 'n', 'e', 'P', 'B', 'K', '0', '0', '3', ']', '\n'] ['L', 'o', 'c', 'a', 't', 'i', 'o', 'n', ' ', '=', ' ', '0', '0', '3', '\n'] ['E', 'n', 't', 'r', 'y', '0', '0', 'T', 'y', 'p', 'e', ' ', '=', ' ', 'N', 'a', 'm', 'e', '\n'] Traceback (most recent call last): File "./modify.py", line 12, in a = AddressBook("2008_11_05_Handy_Backup.txt") File "./modify.py", line 7, in __init__ line = f.readline() File "/usr/local/lib/python3.0/io.py", line 1807, in readline while self._read_chunk(): File "/usr/local/lib/python3.0/io.py", line 1556, in _read_chunk self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) File "/usr/local/lib/python3.0/io.py", line 1293, in decode output = self.decoder.decode(input, final=final) File "/usr/local/lib/python3.0/codecs.py", line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) File "/usr/local/lib/python3.0/encodings/utf_16.py", line 69, in _buffer_decode return self.decoder(input, self.errors, final) UnicodeDecodeError: 'utf16' codec can't decode bytes in position 74-75: illegal encoding rb works, as it doesn't take an encoding parameter. > Malformed EOF more likely. Could you please elaborate? Kind regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From bakul+usenet at bitblocks.com Wed Dec 10 19:25:02 2008 From: bakul+usenet at bitblocks.com (Bakul Shah) Date: Wed, 10 Dec 2008 16:25:02 -0800 Subject: Mathematica 7 compares to other languages In-Reply-To: <49405AD2.7010207@bitblocks.com> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <49405AD2.7010207@bitblocks.com> Message-ID: <49405DDE.4020509@bitblocks.com> Bakul Shah wrote: > John W Kennedy wrote: >> Xah Lee wrote: >>> In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, >>> you'll have 50 or hundreds lines. >> >> C: >> >> #include >> #include >> >> void normal(int dim, float* x, float* a) { >> float sum = 0.0f; >> int i; >> float divisor; >> for (i = 0; i < dim; ++i) sum += x[i] * x[i]; >> divisor = sqrt(sum); >> for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; >> } >> >> Java: >> >> static float[] normal(final float[] x) { >> float sum = 0.0f; >> for (int i = 0; i < x.length; ++i) sum += x[i] * x[i]; >> final float divisor = (float) Math.sqrt(sum); >> float[] a = new float[x.length]; >> for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor; >> return a; >> } >> >> > > q){x%sqrt sum x}3 4 > 0.6 0.8 Oops. I meant to write {x%sqrt sum x*x}3 4 From sln at netherlands.com Thu Dec 25 19:05:02 2008 From: sln at netherlands.com (sln at netherlands.com) Date: Fri, 26 Dec 2008 00:05:02 GMT Subject: Mathematica 7 compares to other languages References: <49404775$0$4893$607ed4bc@cv.net> <452ba58b-9377-4463-85e2-5ecdaa25a129@t39g2000prh.googlegroups.com> <6375k4pf1mleb6im67nkpec5olqbsom88e@4ax.com> Message-ID: <8j78l4drqjg46ps74up555bfu44kct27f7@4ax.com> On Thu, 25 Dec 2008 21:50:29 +0000, Jon Harrop wrote: >Xah Lee wrote: >>> >On Dec 10, 2:47 pm, John W Kennedy wrote: >>> >> C: >>> >>> >> #include >>> >> #include >>> >>> >> void normal(int dim, float* x, float* a) { >>> >> float sum = 0.0f; >>> >> int i; >>> >> float divisor; >>> >> for (i = 0; i < dim; ++i) sum += x[i] * x[i]; >>> >> divisor = sqrt(sum); >>> >> for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; >>> >>> >> } >> >> Due to the low level of C, this C example should perhaps then accept a >> sequence of numbers separated by space... > >In other words, you want a REPL. > >Why don't we have another challenge that involves handling a non-trivial >input format, i.e. parsing? Maybe you could speed it up. sln ---------------------------------- void normal (int Dimension, double *X, double *A) { double *xp, *ap, divisor, sum; int i; for ( i=0, sum=0., xp=X; i hello, I'm running scripts, with the execute function (Python 2.5), and it seems that triple quoted strings are not allowed. Is there a workaround, or is this a fundamental problem of the exec-function ? thanks, Stef Mientki From hniksic at xemacs.org Sun Dec 21 09:17:44 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sun, 21 Dec 2008 15:17:44 +0100 Subject: C API and memory allocation References: <59352942-e976-4ef4-bc40-c8953df0a792@c36g2000prc.googlegroups.com> <0d35b640-71ad-4cde-8869-74878b2f3981@r36g2000prf.googlegroups.com> <494a55fb$0$31873$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <87ocz5obnb.fsf@mulj.homelinux.net> Aaron Brady writes: > I hold this is strong enough to put the burden of proof on the > defenders of having 's'. What is its use case? Passing the string to a C API that can't handle (or don't care about) embedded null chars anyway. Filename API's are a typical example. From walterbyrd at iname.com Wed Dec 17 10:19:32 2008 From: walterbyrd at iname.com (walterbyrd) Date: Wed, 17 Dec 2008 07:19:32 -0800 (PST) Subject: Why no lexical scoping for a method within a class? Message-ID: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> For a language as well structured as Python, this seems somewhat sloppy, and inconsistant. Or is there some good reason for this? Here is what I mean: def a(): x = 99 print x def b(): print x a() b() # raises an exception because x is not defined. However in the methods are within a class, the scoping seems to work differently. class ab(): def a(self): self.x = 99 print self.x def b(self): print self.x i = ab() i.a() i.b() # this works, why no lexical scoping? From steve at REMOVE-THIS-cybersource.com.au Fri Dec 26 22:04:43 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Dec 2008 03:04:43 GMT Subject: math.sqrt() in new 3.0 version : solution in input() References: Message-ID: <01659267$0$6988$c3e8da3@news.astraweb.com> On Fri, 26 Dec 2008 20:34:45 -0600, David Lemper wrote: > On Fri, 26 Dec 2008 15:52:24 -0600, David Lemper wrote: > >>At the command line this function works correctly >> >>> import math >> n = input("enter a number > ") >> s = math.sqrt(n) >> An entry of 9 or 9.0 will yield 3.0 >> >>Yet the same code in a script gives an error message >> Script1 >> import math >> n = input("enter a number > ") >> s = math.sqrt(n) >> >> Traceback (most recent call last) : >> File "", line 1, in >> File "script1.py" line 3 in >> s = math.sqrt(n) >> TypeError : a float is required > > Problem is the new input() function. Yields a string. > > Thanks to Scott, Chris, Gabriel & John. > > Some thought I was not using the Python 3 command line. I was : Python > 3.0 (r30:67507... > Erratic behavior was that I was sometimes using n = input() and > sometimes entering the integer directly into the math.sqrt() function, > eg s = math.sqrt(4194304) Ah, that explains it! When you said that s = math.sqrt(n) worked at the command line, that is what is technically known as a "falsehood" or "lie". Beginners often make the mistake of telling falsehoods when they ask for help. The best way to prevent this error is to read over what you wrote before hitting send, take note of any place where you explicitly or implicitly suggest that you did something, then ask yourself "Did I actually do that, or did I do something different?" If the answer is "I did something different", then you are about to tell a falsehood, and the quality of the answers you get will correspondingly suffer. > I cannot find a mention of this in "The Python Tutorial release 3.1" > The I&O section discusses output formatting and reading & writing text > files. I don't have Python 3 installed here. At the Python command line, what does help(input) say? -- Steven From cournape at gmail.com Mon Dec 8 09:31:05 2008 From: cournape at gmail.com (David Cournapeau) Date: Mon, 8 Dec 2008 23:31:05 +0900 Subject: Python and audio frequency analysis In-Reply-To: References: Message-ID: <5b8d13220812080631n38e72394l28b103a890b89277@mail.gmail.com> On Mon, Dec 8, 2008 at 10:20 PM, manatlan wrote: > I'd like to make a kind of "spectrum analyzer" ... > Which should display "bars" according bands of frequencies ... in real > time... > > Is anybody know an audio processing lib in python for that ? Hi, It is possible to use python for audio processing: I am doing in PhD in audio signal processing, and I mostly use python for my research: audio file IO, relatively advanced processing, display. You will need scientific packages to do the processing: numpy at minimum, to give you an array class ala matlab, for fast vector operations, and scipy to give you more tools (filtering, multi-dimensional fft, etc...). Now, it may not be usable depending on your application: if you know matlab, and your application is doable in matlab, it is doable in python + numpy/scipy. You can see an example of real-time spectrogram with the whole scientific python stack here: http://code.enthought.com/projects/chaco/gallery.php (last example at the bottom) But it may not work out depending on what you mean by real-time: if you use the term precisely, in its computer-science meaning (time-bound process), then it will be difficult if not impossible, by the very nature of python. You need a very precise control of resources in that context, which python does not give. David From pruebauno at latinmail.com Tue Dec 9 11:39:14 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Tue, 9 Dec 2008 08:39:14 -0800 (PST) Subject: StringIO in 2.6 and beyond References: Message-ID: <7374e36d-a84d-4549-a0d9-b626fa013f68@t26g2000prh.googlegroups.com> On Dec 9, 11:28?am, Bill McClain <20080915.20.wmccl... at spamgourmet.com> wrote: > On 2008-12-08, Bill McClain <20080915.20.wmccl... at spamgourmet.com> wrote: > > > On 2008-12-08, Christian Heimes wrote: > > > In this context 'str' means Python 3.0's str type, which is unicode in > > > 2.x. Please report the misleading error message. > > So this is an encoding problem? Can you give me a hint on how to correct in my > > example? I see that io.StringIO() has an encoding parameter, but I'm unclear > > what to specify. > > I still don't have this working. I've been specifying encodings without > success. > > The StringIO example usage in the Python 3.0 documentation here: > > ? ? ?http://docs.python.org/3.0/library/io.html#io.StringIO > > gives me the same error on 2.6: > > ? ? #! /usr/bin/env python > > ? ? from __future__ import print_function > ? ? import io > > ? ? output = io.StringIO() > ? ? output.write('First line.\n') > ? ? print('Second line.', file=output) > > ? ? # Retrieve file contents -- this will be > ? ? # 'First line.\nSecond line.\n' > ? ? contents = output.getvalue() > > ? ? # Close object and discard memory buffer -- > ? ? # .getvalue() will now raise an exception. > ? ? output.close() > > ./stringio30.py > Traceback (most recent call last): > ? File "./stringio30.py", line 7, in > ? ? output.write('First line.\n') > ? File "/usr/local/lib/python2.6/io.py", line 1487, in write > ? ? s.__class__.__name__) > TypeError: can't write str to text stream > > -Bill > -- > Sattre Press ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?History of Astronomyhttp://sattre-press.com/? ? ? ? ? ? ? During the 19th Century > i... at sattre-press.com ? ? ? ? ? ? ? ? ? ? ? by Agnes M. Clerke > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?http://sattre-press.com/han.html This puzzles me too. According to the documentation StringIO accepts both byte strings and unicode strings. Try to replace output.write('First line.\n') with output.write(unicode('First line.\n')) or output.write(str('First line.\n')) and see if one of those works. From andrei.avk at gmail.com Sat Dec 6 15:28:36 2008 From: andrei.avk at gmail.com (Rainy) Date: Sat, 6 Dec 2008 12:28:36 -0800 (PST) Subject: Learning Python now coming from Perl References: Message-ID: On Dec 6, 5:00?am, Bertilo Wennergren wrote: > I'm planning to start learning Python now, using Python 3000. > I have no previous Python skills, but I now Perl pretty well. > I'm also well experienced with JavaScript. > > Any pointers and tips how I should go about getting into > Python? > > -- > Bertilo Wennergren There's a lot of hoopla about Py3k being different, incompatible with Py2.x. However, you have to keep in mind that this matters most of all to old, large programs, which will need to be changed if one would like to run them on Py3k. For learning the differences don't matter much. If you learn to code in py2.x for half a year, you will be able to pick up on most of the differences and transfer to py3k in a few days. If you find good docs on py2.x go ahead and use them and don't worry. From robin at reportlab.com Thu Dec 4 12:19:43 2008 From: robin at reportlab.com (Robin Becker) Date: Thu, 04 Dec 2008 17:19:43 +0000 Subject: schizophrenic view of what is white space In-Reply-To: <20081204143337.20272.1236189783.divmod.quotient.15592@ohm> References: <4937E8E5.2090306@chamonix.reportlab.co.uk> <20081204143337.20272.1236189783.divmod.quotient.15592@ohm> Message-ID: <4938112F.5030706@chamonix.reportlab.co.uk> Jean-Paul Calderone wrote: ......... > > You have to give the re module an additional hint that you care about > unicode: > > exarkun at charm:~$ python > Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu > 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import re > >>> print re.compile(r'\s').search(u'a\xa0b') > None > >>> print re.compile(r'\s', re.U).search(u'a\xa0b') > <_sre.SRE_Match object at 0xb7dbb3a0> > >>> > > Jean-Paul ....... so the default behaviour differs for unicode and re working on unicode. I suppose that won't be true in Python 3. -- Robin Becker From coleb2 at gmail.com Fri Dec 19 17:40:23 2008 From: coleb2 at gmail.com (Brian Cole) Date: Fri, 19 Dec 2008 14:40:23 -0800 (PST) Subject: IDLE doesn't show stderr output from extension modules Message-ID: <6406df08-36bb-4cd8-a356-6d563c2eac7f@e1g2000pra.googlegroups.com> I'm importing an extension module created with SWIG. When working with the module interactively in IDLE there should be warning and error messages printed to stderr by the extension module. However, these are not being caught by the IDLE window, they are going directly to the terminal that was used to start IDLE. Strange, because sys.stderr.write() does print to the IDLE window. I've tried this on Windows and OSX, so it doesn't appear to be a platform issue. Is this just a fundamental deficiency in the IDLE shell prompt? -Brian From gagsl-py2 at yahoo.com.ar Thu Dec 18 19:11:23 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Dec 2008 22:11:23 -0200 Subject: Factoring Polynomials References: Message-ID: En Thu, 18 Dec 2008 17:37:35 -0200, escribi?: > I am trying to write a simple application to factor polynomials. I > wrote (simple) raw_input lines to collect the a, b, and c values from > the user, but I dont know how to implement the quadratic equation > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > into python. Any ideas? Read the section on "Numeric Types" (under "Built-in Types") in the Library Reference: http://docs.python.org/library/index.html Then you should be able to write two expressions to evaluate your formula above. -- Gabriel Genellina From Scott.Daniels at Acm.Org Fri Dec 19 01:19:41 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 18 Dec 2008 22:19:41 -0800 Subject: Factoring Polynomials In-Reply-To: References: <269523e2-eba9-4b6b-b0fb-c5a7deb3ed76@o4g2000pra.googlegroups.com> <2980024c-e680-4010-b8c4-eccd7fd37b65@a37g2000pre.googlegroups.com> Message-ID: James Mills wrote: > No worries. Please take an hour or two to go through the > Python Tutorial at http://docs.python.org/ I'll bet is been more than a couple of days since you (James) ran through the tutorial. It is absolutely worth going through, but _nobody_ should imagine they are slow if they cannot get through in two hours. --Scott David Daniels Scott.Daniels at Acm.Org From gnewsg at gmail.com Thu Dec 11 18:22:53 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 11 Dec 2008 15:22:53 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <9e0bb906-e019-45ef-8047-b33982c7c5ad@l39g2000yqn.googlegroups.com> Message-ID: <4c9ba1a9-db8d-43a5-86f5-09f688200ea4@w24g2000prd.googlegroups.com> On 11 Dic, 13:06, Luis M. Gonz?lez wrote: > On Dec 10, 3:42 pm, cm_gui wrote: > > > > > > >http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-... > > > I fully agree with Krzysztof Kowalczyk . > > Can't they build a faster VM for Python since they love the language > > so much? > > > Python is SLOW. And I am not comparing it with compiled languages > > like C. > > Python is even slower than PHP! > > > Just go to any Python website and you will know. > > An example is:http://www2.ljworld.com/ > > And this site is created by the creators of Django! > > > And it is not just this Python site that is slow. There are many many > > Python sites which are very slow. And please don?t say that it could > > be the web hosting or the server which is slow ? because when so many > > Python sites are slower than PHP sites, it couldn?t be the web > > hosting. Also, Zope/Plone is even slower. > > > Python is slow. Very slow. > > Now seriously, just to finish your idiotic rant, check the Pypy > project: > > http://codespeak.net/pypyhttp://morepypy.blogspot.com > > And if you still think this is not enough, why don't you help these > guys to make it faster? > > Luis- Nascondi testo citato > > - Mostra testo citato - The real (and still unsolved) problem with PyPy is the installation which requires something like a dozen of third-party packages to be installed. Unfortunately it seems there are no plans yet for releasing any Windows/Linux/Mac installer in the near future. --- Giampaolo http://code.google.com/p/pyftpdlib/ From siona at chiark.greenend.org.uk Tue Dec 23 06:23:16 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 23 Dec 2008 11:23:16 +0000 (GMT) Subject: Very basic question References: <21ab1917-f0c9-48fb-baa9-02e5bf229bf5@s9g2000prm.googlegroups.com> Message-ID: Sengly wrote: >I would like to calculate a string expression to a float. For example, >I have ('12/5') and I want 2.4 as a result. I tried to use eval but it >only gives me 2 instead of 2.5 py> from __future__ import division py> print eval('12/5') 2.4 py> print eval('12//5') 2 Or switch to 3.0 which gives you this behaviour without the __future__ import. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From duncan.booth at invalid.invalid Sun Dec 21 10:30:34 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Dec 2008 15:30:34 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <015da0a4$0$20656$c3e8da3@news.astraweb.com> <015e4162$0$20656$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: >> a+b+c+d might execute a.__add__(b,c,d) allowing more efficient string >> concatenations or matrix operations, and a%b%c%d might execute as >> a.__mod__(b,c,d). > > That's only plausible if the operations are associative. Addition is > associative, but string interpolation is not: Addition is not associative on arbitrary types. > >>>> "%%%s" % ("%s" % "b") > '%b' >>>> ("%%%s" % "%s") % "b" > Traceback (most recent call last): > File "", line 1, in > TypeError: not all arguments converted during string formatting > > Since string interpolation isn't associative, your hypothetical > __mod__ method might take multiple arguments, but it would have to > deal with them two at a time, unlike concatenation where the compiler > could do them all at once. So whether __mod__ takes two arguments or > many is irrelevant: its implementation must rely on some other > function which takes two arguments and must succeed or fail on that. I don't see that. What I suggested was that a % b % c would map to a.__mod__(b,c). (a % b) % c would also map to that, but a % (b % c) could only possibly map to a.__mod__(b.__mod__(c)) From robert.kern at gmail.com Mon Dec 8 16:51:23 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 08 Dec 2008 15:51:23 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> Message-ID: Rhamphoryncus wrote: > On Dec 8, 1:04 pm, Robert Kern wrote: >> Rhamphoryncus wrote: >>> On Dec 8, 11:54 am, Robert Kern wrote: >>>> Rhamphoryncus wrote: >>>>> On Dec 7, 4:20 pm, Steven D'Aprano >>>> cybersource.com.au> wrote: >>>>>> On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: >>>>>>> Rasmus Fogh wrote: >>>>>>>> Current behaviour is both inconsistent and counterintuitive, as these >>>>>>>> examples show. >>>>>>>>>>> x = float('NaN') >>>>>>>>>>> x == x >>>>>>>> False >>>>>>> Blame IEEE for that one. Rich comparisons have nothing to do with that >>>>>>> one. >>>>>> There is nothing to blame them for. This is the correct behaviour. NaNs >>>>>> should *not* compare equal to themselves, that's mathematically >>>>>> incoherent. >>>>> Mathematically, NaNs shouldn't be comparable at all. They should >>>>> raise an exception when compared. In fact, they should raise an >>>>> exception when *created*. But that's not what we want. What we want >>>>> is a dummy value that silently plods through our calculations. For a >>>>> dummy value it seems a lot more sense to pick an arbitrary yet >>>>> consistent sort order (I suggest just above -Inf), rather than quietly >>>>> screwing up the sort. >>>> Well, there are explicitly two kinds of NaNs: signalling NaNs and quiet NaNs, to >>>> accommodate both requirements. Additionally, there is significant flexibility in >>>> trapping the signals. >>> Right, but most of that's lower level. By the time it reaches Python >>> we only care about quiet NaNs. >> No, signaling NaNs raise the exception that you are asking for. You're right >> that if you get a Python float object that is a NaN, it is probably going to be >> quiet, but signaling NaNs can affect Python in the way that you want. >> >>>>> Regarding the mythical IEEE 754, although it's extremely rare to find >>>>> quotations, I have one on just this subject. And it does NOT say "x >>>>> == NaN gives false". It says it gives *unordered*. It is C and >>>>> probably most other languages that turn that into false (as they want >>>>> a dummy value, not an error.) >>>>> http://groups.google.ca/group/sci.math.num-analysis/browse_thread/thr... >>>> Table 4 on page 9 of the standard is pretty clear on the subject. When the two >>>> operands are unordered, the operator == returns False. The standard defines how >>>> to do comparisons notionally; two operands can be "greater than", "less than", >>>> "equal" or "unordered". It then goes on to map these notional concepts to >>>> programming language boolean predicates. >>> Ahh, interesting. Still though, does it give an explanation for such >>> behaviour, or use cases? There must be some situation where blindly >>> returning false is enough benefit to trump screwing up sorting. >> Well, the standard was written in the days of Fortran. You didn't really have >> generic sorting routines. You *could* implement whatever ordering you wanted >> because you *had* to implement the ordering yourself. You didn't have to use a >> limited boolean predicate. >> >> Basically, the boolean predicates have to return either True or False. Neither >> one is really satisfactory, but that's the constraint you're under. > > "We've always done it that way" is NOT a use case! Certainly, it's a > factor, but it seems quite weak compared to the sort use case. I didn't say it was. I was explaining that sorting was probably *not* a use case for the boolean predicates at the time of writing of the standard. In fact, it suggests implementing a Compare() function that returns "greater than", "less than", "equal" or "unordered" in addition to the boolean predicates. That Python eventually chose to use a generic boolean predicate as the basis of its sorting routine many years after the IEEE-754 standard is another matter entirely. In any case, the standard itself is quite short, and does not spend much time justifying itself in any detail. > I suppose what I'm hoping for is an small example program (one or a > few functions) that needs the "always false" behaviour of NaN. Steven D'Aprano gave one earlier in the thread. Additionally, (x!=x) is a simple test for NaNs if an IsNaN(x) function is not available. Really, though, the result falls out from the way that IEEE-754 constructed the logic of the system. It is not defined that (NaN==NaN) should return False, per se. Rather, all of the boolean predicates are defined in terms of that Compare(x,y) function. If that function returns "unordered", then (x==y) is False. It doesn't matter if one or both are NaNs; in either case, the result is "unordered". -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From Juergen.Hermann at 1und1.de Wed Dec 17 05:48:48 2008 From: Juergen.Hermann at 1und1.de (jhermann) Date: Wed, 17 Dec 2008 02:48:48 -0800 (PST) Subject: Python 3.0 crashes displaying Unicode at interactive prompt References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> <49443531.5050304@v.loewis.de> <49448FC2.6030306@v.loewis.de> <494576DD.1050505@v.loewis.de> <89022013-f7f6-4779-849f-b36fe618104e@r15g2000prh.googlegroups.com> <494599CD.3030408@v.loewis.de> Message-ID: <854e02a8-eaa4-4e02-b668-7b6d4a36fd12@e1g2000pra.googlegroups.com> Assuming those survived the switch to 3.0, you can use site.py und sys.displayhook to customize to the old behaviour (i.e. change it to a version using ascii instead of repr). Since this only affects interactive use, it's also no problem for portability of code, unlike "solutions" like forcing the defaultencoding etc. From philip at semanchuk.com Sat Dec 6 17:19:27 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Sat, 6 Dec 2008 17:19:27 -0500 Subject: Source code generation using Python In-Reply-To: <82098706-978f-4920-ac75-57ef3573ac44@x38g2000yqj.googlegroups.com> References: <82098706-978f-4920-ac75-57ef3573ac44@x38g2000yqj.googlegroups.com> Message-ID: On Dec 6, 2008, at 4:47 PM, ats wrote: > Hello, > > This is my first posting to a Python group (and I'm starting with > Python seriously only now) , so bear with me if I make some mistakes. > > I want to generate 3 different versions of a C++ source code, > basically injecting different flavours of inline assembler depending > on target compiler/CPU. > > Code generation should be integrated into a 'master source file' which > is the processed and generates the right code for GCC / MSVC or other > cases. Something like: > > int FastAdd( int t1, int t2 ){ > int r; > ##if USE_INLINE_ASM > #ARG( eax, "t1") > #ARG( ebx, "t2") > #ASM( "add", ebx, eax ) > #RES( eax, "r" ) > ##else > r = t1+t2; > ##endif > return r; > } > > On processing, given constant USE_INLINE_ASM (or not) the right code > is generated to a target file, which goes into the build process. > > I was looking for packages that can do this and came up with some > candidates: > > - "empy" - http://www.alcyone.com/pyos/empy/ - It looks like it could > do the job, but appears non-maintained since 2003. > - "Cheetah" - Looks like more of a tool to do fix replacements of code > snippets. > > > There is some logic going on in the "ARG", "ASM" and "RES" sections, > so I need to link code generation with true Python functions. Hi Arne, There are *lots* of packages for Python that replace chunks of predefined templates. Most are HTML-focused, some more so than others. I've used Mako (http://www.makotemplates.org/) to generate both HTML and Apache config files. It could certainly do C++. Some alternatives to Mako are mentioned in the documentation -- Kid, Genshi and Cheetah. Rather than invite a flame war as to which is a better templating engine, I'll just say that I'm happy with how Mako addresses *my* needs. =) Good luck finding something that addresses yours. Cheers Philip > > > The situation is really quite similar to HTML/PHP except, here we > would have C++/Python. > > Any suggestions? > > Thanks, > //Arne S. > -- > http://mail.python.org/mailman/listinfo/python-list From arnodel at googlemail.com Wed Dec 3 14:11:47 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 03 Dec 2008 19:11:47 +0000 Subject: Overriding a method at the instance level on a subclass of a builtin type References: Message-ID: "Zac Burns" writes: > Sorry for the long subject. > > I'm trying to create a subclass dictionary that runs extra init code > on the first __getitem__ call. However, the performance of __getitem__ > is quite important - so I'm trying in the subclassed __getitem__ > method to first run some code and then patch in the original dict > method for the instance to avoid even the check to see if the init > code has been run. Various recipes using instancemethod and the like > have failed me. > > Curiously if __slots__ is not specified no error occurs when setting > self.__getitem__ but the function is not overriden. If __slots__ is > ['__getitem__'] however it complains that __getitem__ is read only. I > do not understand that behavior. You can change the class on the fly to achieve what you want: >>> class D1(dict): ... def __getitem__(self, key): ... print 'first call' ... self.__class__ = D2 ... return dict.__getitem__(self, key) ... >>> class D2(dict): ... pass ... >>> d = D1(foo=42) >>> d['foo'] first call 42 >>> d['foo'] 42 >>> HTH -- Arnaud From arnodel at googlemail.com Sun Dec 14 07:29:10 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 14 Dec 2008 12:29:10 +0000 Subject: Optimizing methods away or not? References: <0154b041$0$6988$c3e8da3@news.astraweb.com> <0154df65$0$6988$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano writes: > On Sun, 14 Dec 2008 10:52:25 +0000, Arnaud Delobelle wrote: > >> You could also not use the metaclass and use post_verify as a decorator > > Except that self.verify doesn't exist if __debug__ is false. OK I wrote this as an afterthought. I'm, sure it's not beyond your ability to add if not __debug__: return method at the start of the post_verify function :) -- Arnaud From msdark at archlinux.us Thu Dec 18 21:38:23 2008 From: msdark at archlinux.us (=?ISO-8859-1?Q?Mat=EDas_Hern=E1ndez?=) Date: Thu, 18 Dec 2008 23:38:23 -0300 Subject: python mysql hash generator Message-ID: <494B091F.6010808@archlinux.us> sorry for my english, but i'm speak spanish) Hi list.. this is my first post... and obviously if for help.. I try to implement the password function of mysql in a python script. I read that the password function of mysql was implemented with a double sha1() I python i try this: example1: if __name__=="__main__": s = hashlib.sha1() s.update('test') s2 = hashlib.sha1() s2.update(s.digest() print s2.hexdigest() This script show me the same hash that password function of mysql, but when i implement this in a class the hash is different??? why??? And if is posible??? can you show a example code of old_password function of mysql in python??? THNX From jstroud at mbi.ucla.edu Sun Dec 14 20:24:34 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 14 Dec 2008 17:24:34 -0800 Subject: Looking for the best way to translate an idiom In-Reply-To: References: Message-ID: James Stroud wrote: > inspect.stack()[1][0].f_locals[name] = val I just double checked this. Because of the way locals are implemented in cPython, this won't have the desired affect. James From XX.XmcX at XX.XmclaveauX.com Fri Dec 19 02:11:53 2008 From: XX.XmcX at XX.XmclaveauX.com (MC) Date: Fri, 19 Dec 2008 08:11:53 +0100 Subject: Very Slow PythonWin 2.6.1 Startup on Windows XP SP3 References: <_PG2l.570$P5.31@nwrddc02.gnilink.net> Message-ID: Hi! Perhaps, if you copy DLL in others strategic places, it's better... -- @-salutations Michel Claveau From ldo at geek-central.gen.new_zealand Fri Dec 5 20:20:55 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 06 Dec 2008 14:20:55 +1300 Subject: Don't you just love writing this sort of thing :) References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: In message <32cf4a79-a6e3-4250-9b5a-1ec80c748618 at j32g2000yqn.googlegroups.com>, Aaron Brady wrote: > On Dec 5, 4:32?am, Lawrence D'Oliveiro central.gen.new_zealand> wrote: > >> The code people write is probably a direct reflection of their thinking >> processes: For example, slow, plodding, one step at a time, incapable of >> imaginative leaps, versus those who operate directly on larger patterns >> at once... > > That distinction operates indirectly on smaller patterns. Do you find this (open, gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir, Entry), "r") complicated or hard to understand? It's made up of very simple pieces, combined according to very simple rules, viz:- A tuple of candidate functions: (open, gzip.GzipFile) A choice from that tuple according to a condition: [Entry.endswith(".gz")] And finally, arguments to pass to the chosen function: (os.path.join(PatchesDir, Entry), "r") See, it's so simple, a child could understand it. A child who isn't burdened with the preconceptions that seem to afflict some participants in this noisegroup... From pecora at anvil.nrl.navy.mil Mon Dec 22 09:51:01 2008 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Mon, 22 Dec 2008 09:51:01 -0500 Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> <6r6hpfFfb643U3@mid.uni-berlin.de> <494E6FDA.4070401@mrabarnett.plus.com> <4585c27d-d7a9-480f-991c-a869161be55c@g38g2000yqn.googlegroups.com> <3392a51b-d3fd-4986-9c59-fecccc7272da@p2g2000prn.googlegroups.com> Message-ID: In article , "James Mills" wrote: > In case anyone is not aware, Python is > also used for heavy scientific computational > problems, games such as Civilisation and > others, and I believe (correct me if I"m wrong) > it's also used by NASA. > > --JamesMills Python has become very popular in scientific computation. You'll find it in use lots of places (universities, national labs, defense labs). I use it for solving partial differential equations for quantum chaos calculations and went to C for speed up where needed using ctypes which is very straightforward and plays nice with numpy array/matrix libraries. I've been doing scientific programming for 30 years. Python with C extensions and libraries is the best approach I've ever used. Calculation speed is not a problem and the code can be "tweaked" to increase it easily. Programming speed is incredible. I can get substantial object oriented code up and running much faster than anything I've ever used. -- -- Lou Pecora From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 8 08:20:03 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 08 Dec 2008 14:20:03 +0100 Subject: Guido's new method definition idea In-Reply-To: <49d12ec1-2be9-497b-80bc-9f0402a9086d@s20g2000yqh.googlegroups.com> References: <493a9fed$0$18973$426a34cc@news.free.fr> <493c1ff6$0$4942$426a34cc@news.free.fr> <49d12ec1-2be9-497b-80bc-9f0402a9086d@s20g2000yqh.googlegroups.com> Message-ID: <493d1f03$0$32048$426a34cc@news.free.fr> Philip Slate a ?crit : > On Dec 7, 1:13 pm, Bruno Desthuilliers > wrote: > >>> and friendlier to newbies. >> I'd rather say "more acceptable to java-brainwashed developpers". > > And I'd rather say you're trolling, Almost, indeed. But not as much as you !-) From prahaai at gmail.com Thu Dec 4 11:57:31 2008 From: prahaai at gmail.com (Cro) Date: Thu, 4 Dec 2008 08:57:31 -0800 (PST) Subject: Python 3 read() function References: Message-ID: <6e24be88-b042-425b-b880-c97d184fee07@s20g2000yqh.googlegroups.com> > Do you really mean io.StringIO? I guess you want io.BytesIO() .. > > Christian Mmm... i don't know. I also tried : [code] IDLE 3.0 >>> import io >>> vContent = io.BytesIO() >>> huge = io.open("C:\HUGE_FILE.pcl",'r+b',0) >>> vContent = huge.read() [/code] It still waits a lot... i don't have the patience to wait for the file to load completely... it takes a lot! Thank you for your reply. From philip at semanchuk.com Wed Dec 3 10:41:16 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Wed, 3 Dec 2008 10:41:16 -0500 Subject: Running a Python script from crontab In-Reply-To: <126ba84a-0ea0-4a91-b7d2-89ed650e5d6c@d32g2000yqe.googlegroups.com> References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> <126ba84a-0ea0-4a91-b7d2-89ed650e5d6c@d32g2000yqe.googlegroups.com> Message-ID: On Dec 3, 2008, at 10:29 AM, Astley Le Jasper wrote: > I've included a switch to include or exclude the logging to console. > When logging only to file, the script runs fine. > > Of course, I still don't understand why dual logging, and specifically > to the console, causes a problem and if anyone has any comments about > the dual output logging code above then I'd still be happy to hear > about it. Trying to write non-ASCII characters perchance? From sturlamolden at yahoo.no Fri Dec 12 08:04:12 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 05:04:12 -0800 (PST) Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> Message-ID: On Dec 12, 1:56 pm, sturlamolden wrote: > That is because integers are immutable. When x += 1 is done on an int, > there will be a rebinding. But try the same on say, a numpy array, and > the result will be different: And a consequence of this is, if you have a function like def foobar(x): x += 1 then the parameter x will be modified given that x have mutable type. However, if we have a function like def foobar(x): x = x + 1 then x will not be modified, mutable or not. (Well, you could abuse operator overlaoding to make unexpected side effects in the latter case. But except for such insanity it will not have side-effects.) From steve at REMOVE-THIS-cybersource.com.au Sat Dec 6 19:10:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 00:10:45 GMT Subject: Learning Python now coming from Perl References: <014a96e0$0$20670$c3e8da3@news.astraweb.com> Message-ID: <014b0c3a$0$20670$c3e8da3@news.astraweb.com> On Sat, 06 Dec 2008 14:15:28 -0500, Roy Smith wrote: > In article <014a96e0$0$20670$c3e8da3 at news.astraweb.com>, > Steven D'Aprano wrote: > >> On Sat, 06 Dec 2008 08:50:20 -0500, Roy Smith wrote: >> >> > For your first >> > project, pick something that's small enough that you think you could >> > tackle it in under 50 lines of Perl. >> >> Is there anything which *can't* be written in under 50 lines of Perl? > [...] >> Also, Perl REs are faster than Python REs, or so I'm told. Between the >> speed and the convenience, Perl programmers tend to use RE's for >> everything they can. Python programmers tend to use REs only for >> problems that *should* be solved with REs rather than *can* be solved >> with a RE. > > Well, as an old-time unix hacker (who learned REs long before Perl > existed), my question to you would be, "Is there any problem which > *shouldn't* be solved with an RE?" :-) I think you've answered your own question: > One of the reasons REs don't get used in Python as much as in Perl is > because strings have useful methods like startswith(), endswith(), and > split(), and also the "in" operator. These combine to give you easy > ways to do many things you might otherwise do with REs. Also: * splitting pathnames and file extensions * dealing with arbitrarily nested parentheses * any time you need a full-blown parser (e.g. parsing HTML or XML) * sanitizing untrusted user input ("I bet I can think of *every* bad input and detect them all with this regex!") * validating email addresses http://northernplanets.blogspot.com/2007/03/how-not-to-validate-email-addresses.html * testing prime numbers http://jtauber.com/blog/2007/03/18/python_primality_regex/ * doing maths http://blog.stevenlevithan.com/archives/algebra-with-regexes http://weblogs.asp.net/rosherove/archive/2004/11/08/253992.aspx There's probably more. -- Steven From Lie.1296 at gmail.com Sun Dec 7 02:21:04 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 6 Dec 2008 23:21:04 -0800 (PST) Subject: Guido's new method definition idea References: Message-ID: On Dec 6, 9:21?am, "Daniel Fetchinson" wrote: > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... > > The proposal is to allow this: > > class C: > ? ? def self.method( arg ): > ? ? ? ? self.value = arg > ? ? ? ? return self.value > > instead of this: > > class C: > ? ? def method( self, arg ): > ? ? ? ? self.value = arg > ? ? ? ? return self.value > > I.e. explicit self stays only the syntax is slightly different and may > seem attractive to some. As pointed out by Guido classmethods would > work similarly: > > class C: > ? ? @classmethod > ? ? def cls.method( arg ): > ? ? ? ? cls.val = arg > ? ? ? ? return cls.val To sum up: Arguments on Status Quo: + Andreas Waldenburger: it works and there just is no need to change it + need no change + Andreas Waldenburger: Getting the Python comunity to replace self with something shorter will never compensate for the time you spent bullying it through - Confusion for number of parameters - The standard 'self' is too long - Newbie FAQ - It is ugly Arguments on "def self.method(" as "def method(self" inside a class: + OP: It reduces confusion for number of parameters + Patrick Mullen: The symetry of "def self.func(blah)==def func (self,blah)" and "ob.func(blah)==func(ob.blah)" is kind of neat. + OP: Backward compatible + OP: It is explicit - Marc 'Blackjack' Rintsch: they [newcomers] will run into *both* variants in tutorials, code, and books, so it might be even more confusing. - Carl Banks: def (): == = , but def self.method(): return 1 != self.method = lambda: 1 - `self` in this context might be misconstrued as the class object and thus `def self.foo` might be misunderstood ... as a defining a classmethod rather than an instance method. - It is ugly ? Syntax sugar or replacement? Many people prefers this to be replacement to reduce confusion. Arguments on variants of $ + Russ P.: looks like S(elf) + Russ P.: more succinct with no loss of readability - Antoine de Groote: slightly less readable. - Antoine de Groote: wouldn't require this new syntax (def meth($, args): $.foo) - Andreas Waldenburger: "self" is a speaking identifier, "$" isn't - Obscure symbol - It is ugly Unresolved: ? Patrick Mullen: Outside a class definition? I think we have to test this on newbies. Personally, I think the new syntax would confuse newbies too, though not as much as the tricky error message we currently have (code: foo.bar(1, 2, 3, 4); Error: TypeError: foo() takes exactly 4 arguments (5 given); Newbie: "what the... 1.. 2.. 3.. 4.., I correctly gave 4 arguments, python counted the wrong number of arguments"). If this dead horse is revived because of that reason, then I'd go with changing the error message to something that is less confusing to newbies[1]. I remember being tripped with the (thinking that python miscounted the number of argument) when I was new. This has the advantage of backward compatibility and no syntax change, just less misleading error message. [1] anything could work, but I like this one: (c is an instance of class C) if the code is: c.foo(...), Error: "TypeError: c.foo() takes exactly 3 argument" while if the code is: C.foo(...), Error: "C.foo() takes exactly 4 arguments" You can implement c.foo as a curried C.foo function, catch C.foo's TypeError exception then reraise it as c.foo exception. From febaen at gmail.com Sat Dec 13 03:57:12 2008 From: febaen at gmail.com (feba) Date: Sat, 13 Dec 2008 00:57:12 -0800 (PST) Subject: Need help improving number guessing game Message-ID: #!/usr/bin/python/ #Py3k, UTF-8 import random print(" --- WELCOME TO THE SUPER NUMBER GUESSING GAME --- " + ("\n" * 5)) pnum = int(input("1 OR 2 PLAYER?\nP#: ")) target = random.randint(1, 99) #Pick a random number under two digits guess1 = 0 #Zero will never be picked as target... guess2 = 0 #so it makes a good default value p1score = 0 #For two player mode... p2score = 0 #let's keep score! print("LET'S START THE GAME. \nGUESS ANY WHOLE NUMBER FROM 1 TO 99.") while True: if pnum == 1: #1p mode while True: guess1 = int(input("\n>> ")) if guess1 > 100: print("ONLY NUMBERS FROM 1 TO 99") elif guess1 > target: print("TOO HIGH") elif guess1 == target: print("CONGLATGURATIONS! PLAY AGAIN?") target = random.randint(1, 99) #Set up the game again play = int(input("0 TO END: ")) if play == 0: print("GOOD BYE. PLAY AGAIN SOON!") quit() else: print("TOO LOW") if pnum == 2: #2p mode while True: guess1 = int(input("\nP1> ")) #Player 1's turn if guess1 > 100: print("ONLY NUMBERS FROM 1 to 99") elif guess1 > target: print("TOO HIGH") elif guess1 == target: p1score += 1 print("GOOD JOB, PLAYER 1! THE SCORE IS:\nP1: %s --- P2: %s\nPLAY AGAIN?" % (p1score, p2score)) target = random.randint(1, 99) #Set up game again play = int(input("0 TO END: ")) if play == 0: print("GOOD BYE. PLAY AGAIN SOON!") else: print("TOO LOW") guess2 = int(input("\nP2> ")) #Player 2's turn if guess2 > 100: print("ONLY NUMBERS FROM 1 to 99") elif guess2 > target: print("TOO HIGH") elif guess2 == target: p2score += 1 print("GOOD JOB, PLAYER 2! THE SCORE IS:\nP1: %s --- P2: %s\nPLAY AGAIN?" % (p1score, p2score)) target = random.randint(1, 99) #Set up game again play = int(input("0 TO END: ")) if play == 0: print("GOOD BYE. PLAY AGAIN SOON!") else: print("TOO LOW") else: print("INVALID PLAYER SELECTION") pnum = int(input("1 OR 2 PLAYER?\nPN#: ")) I have one major problem with this; the 'replay' selection. It quits if you put in 0, as it should, and continues if you put in any other number. However, if you just press enter, it exits with an error. it also looks really ugly, and I'm sure there has to be plenty of better ways to do it. I'd also appreciate tips on how it could be better in general. I should think that P1 and P2's turns shouldn't have to be completely repeated; but I'm not quite sure how to def something like that. From python.list at tim.thechases.com Mon Dec 15 11:14:38 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 15 Dec 2008 10:14:38 -0600 Subject: alt.possessive.its.has.no.apostrophe In-Reply-To: <49467CE2.3060401@holdenweb.com> References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> <49467CE2.3060401@holdenweb.com> Message-ID: <4946826E.7060001@tim.thechases.com> Steve Holden wrote: > This led to a schism between the British and the > newly-independent Americans, who responded by taking the "u" > out of colour, valour, and aluminium. Darn Americans and their alminim.... ;-) Next thing you know, they'll be putting an I in TEAM.[1] -tkc [1] http://www.quotedb.com/quotes/2417 From kw at codebykevin.com Sat Dec 27 22:13:59 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Sat, 27 Dec 2008 22:13:59 -0500 Subject: Python 3 and my Mac (Leopard) In-Reply-To: <4952b38d$0$20300$607ed4bc@cv.net> References: <4952b38d$0$20300$607ed4bc@cv.net> Message-ID: <4956EEF7.60407@codebykevin.com> Dan wrote: > Wanted to learn python, got Mark Summerfield's new book "Programming in > Python 3". Having a hard time getting python 3 and IDLE working on my > Mac with Leopard. The mac "resources" on the python.org site seem a bit > out of date, and don't really mention python 3. Are there any resources > out there? Is the python community just not interested in Macs? I've > tried googling and the usual search strategies. Any help would be > appreciated. > > DAN > There's a mailing list devoted to Python on the Mac: http://mail.python.org/mailman/listinfo/pythonmac-sig It is a pretty good resource, better than the Python wiki, more up to date. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From warren at delsci.com Thu Dec 4 15:53:53 2008 From: warren at delsci.com (Warren DeLano) Date: Thu, 4 Dec 2008 12:53:53 -0800 Subject: "as" keyword woes Message-ID: <896B75251BA19745A529B1B867893FA50679D9@planet.delsci.local> > I still have not > >> seen a single post from you even hinting that you might have any > >> responsibility in the matter. > > > > Well then, let me set the record straight on that one point: > > > > I admit that it was entirely my mistake (and mine alone) to implicitly > > assume, by adopting such a logging & persistence architecture (dating > > back to 1.5.2, mind you!), that new keywords would not be introduced > > into the Python language so as to potentially break all existing Python > > code. > > > > Silly me! How unreasonable. > > > > Pythons backwards compatibility policy is available here: > http://www.python.org/dev/peps/pep-0005/ Thank you! Just to end on a more positive note: As someone who makes a living from Python rather than someone who lives to make Python, I recognize that there will be ancillary casualties in every major battle. Though I may whine incessantly about all of our pre-2.5 log-file/documents being one such casualty (your various accusations notwithstanding, we did indeed patch our own code as soon as the deprecation warnings appeared in 2.5!), if the Python 2.6 "as" keyword break is truly for the greater good, then so be it. Warren From marduk at letterboxes.org Tue Dec 23 09:41:06 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Tue, 23 Dec 2008 09:41:06 -0500 Subject: print to console without a line break In-Reply-To: References: Message-ID: <1230043266.22581.1.camel@brotherus.rdu.redhat.com> On Tue, 2008-12-23 at 13:18 +0000, Lie Ryan wrote: > On Tue, 23 Dec 2008 11:50:59 +0100, Qian Xu wrote: > > > Hello All, > > > > Is it possible to print something to console without a line break? > > > > I tried: > > sys.stdout.write("Testing something ...") // nothing will be printed > > time.sleep(1) > > sys.stdout.write("done\n") // now, the whole string will be printed > > Probably because your stdout is line-buffered. Try: sys.stdout.write("Testing something...") sys.stout.flush() # flush the stdout buffer From huwdjones at gmail.com Thu Dec 18 05:34:13 2008 From: huwdjones at gmail.com (huw_at1) Date: Thu, 18 Dec 2008 02:34:13 -0800 (PST) Subject: cx_Oracle issues References: <5b2dad81-2750-4347-8079-6ab31321d579@s1g2000prg.googlegroups.com> <9142a8f1-7f76-4fc0-9ca1-c9dec310f2ce@r37g2000prr.googlegroups.com> <9f436c9e-2319-499c-a306-d255996372fc@e22g2000vbe.googlegroups.com> <09b53231-5a92-437c-859b-6e5d0ce106c8@k36g2000pri.googlegroups.com> Message-ID: <75a97df3-7ee9-41ce-9f10-e525c42a7653@e18g2000vbe.googlegroups.com> On Dec 16, 12:17?pm, huw_at1 wrote: > On Dec 15, 12:59?pm, "ron.re... at gmail.com" > wrote: > > > > > On Dec 15, 2:44?am, huw_at1 wrote: > > > > On Dec 11, 5:34?pm, "ron.re... at gmail.com" wrote: > > > > > On Dec 10, 9:48?am, huw_at1 wrote: > > > > > > Hey all. When usingcx_Oracleto run a procedure like: > > > > > > cursor.execute("select (obj.function(value)) from table where > > > > > id=blah") > > > > > > I am getting the following error: > > > > > > ORA-06502: PL/SQL: numeric or value error: character string buffer too > > > > > small ORA-06512: at line 1 > > > > > > Looking at cursor.description I get: > > > > > > [('(obj.function(value))', , 4000, 4000, 0, > > > > > 0, 1)] > > > > > > Any tips - i have never seen this error before but am guessing that > > > > > the value being returned is too big for the buffer size set for the > > > > > cursor. the procedure fetches data from a LOB. > > > > > > Any suggestions/confirmations? > > > > > > Many thanks > > > > > This error is a problem with the PL/SQL, notcx_Oracle. ?You need to > > > > debug obj.function to see what kind of data is being accessed and then > > > > a data analysis of that data to understand why this error occurs. ?I > > > > can tell you the function is most likely expecting characters from a > > > > column that are numeric [0 .. 9] and is getting alpha characters. > > > > > -- > > > > Ron Reidy > > > > Sr. Oracle DBA > > > > Hi thanks for the responses. Unfortunately the procedure in question > > > is from a third party vendor so I can't really debug it so I'd say I > > > was fairly stumped. Just out of interest how do you increase the > > > output buffer size withcx_Oracle? > > > > Many thanks- Hide quoted text - > > > > - Show quoted text - > > > Hi, > > > Sure you can. ?You can see the PL/SQL source from the ditionary view > > ALL_SOURCE: > > select text from all_source where name = 'NAME_OF_FUNCTION'; > > > From there, reverse engineeer which table(s) and column(s) are being > > accesses and do the data analysis. > > > -- > > Ron Reidy > > Hi all, > > So I tried Rons query but unfortunately I got 0 records returned. > However I can confirm that running the select query from a client does > indeed generate the same error. Is there anything else I could try? > Otherwise I'll just get in touch with the vendor I guess. Hi again. A further update to these issues is that I found some java executable which seemed to execute the SQL query without hitch. My Java isn't great but from what I could make out it seems that the query is broken down from: select (obj.function(value)) from table where id=blah to: select value from table where id=blah obj.function(value) So make two queries. In the first retrieve the BLOB (value) and store it in a java.sql.blob object. Then pass this back in to the stored procedure. I'm a bit puzzled as to why this way would work over just performing the straight select statement. Culd it be the jdbc connector handles BLOBs better? Anyway I was wondering if I could implement something similar using cx_Oracle. however I am a bit stuck on how to pass a BLOB in to the second query - specifically: cursor.execute(obj.function(value)) where value is the BLOB. I get an error: cx_Oracle.NotSupportedError: Variable_TypeByValue(): unhandled data type cx_Oracle.LOB So I wonder if I need to set something for the input type but I do not know how to do this. Any suggestions? Many thanks again. From conrad.ammon at gmail.com Mon Dec 15 16:00:11 2008 From: conrad.ammon at gmail.com (cmdrrickhunter@yaho.com) Date: Mon, 15 Dec 2008 13:00:11 -0800 (PST) Subject: stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> <015612ac$0$20639$c3e8da3@news.astraweb.com> <52cfb77e-4baf-4fba-8eac-cc6c7ddb5be5@k1g2000prb.googlegroups.com> <5504f9ac0812150828m14f6999ak6112c5975042dc88@mail.gmail.com> Message-ID: <1ffd301f-16d3-4dc7-988c-7741d658ca10@z28g2000prd.googlegroups.com> Just because its such an interesting problem, I'll take a stab at it. It can be proven that you cannot sort an arbitrarily large set of numbers, given no extra information, faster than O(n log n). It is provable using information theory. However, if your teacher is giving you evil problems, there's no reason you can't be evil in return: Evil trick 1: Allocate an array of n^2 booleans, initialized to false (This is O(n^2)). Declare this to be "before the sort" Then iterate through the list and set each matching entry in the array to True (This is O(n)). Now you have them "sorted." To get access to the data, you need to iterate across the array O(n^2), but this is "after the sort" Evil trick 2: inserting into a set is O(1), so you could insert n items into a set. This is O(n). Then you can argue that, since the set cares not about order, it is as good as ordered! Evil trick 3: pull up your python debugger, and have your program search for the right answer in your teacher's test library. If done smart, this could even be an O(1) sort O_o (queue Nukees reference: "Welcome to my computer security course. Your grades have already been entered into the school's grading systems as Fs. You have one semester to change that, good luck") ... these are fun =) From quian.xu at stud.tu-ilmenau.de Tue Dec 23 09:52:50 2008 From: quian.xu at stud.tu-ilmenau.de (Qian Xu) Date: Tue, 23 Dec 2008 15:52:50 +0100 Subject: print to console without a line break References: Message-ID: Lie Ryan wrote: > If you don't mind an extra space, you can use this: > > print 'Testing something ...', > # note the trailing comma Thanks. However, the contents will be saved in buffer and will not be shown until print "(last piece)" sys.stdout.flush() can solve this problem :-) From xahlee at gmail.com Mon Dec 8 17:32:59 2008 From: xahlee at gmail.com (Xah Lee) Date: Mon, 8 Dec 2008 14:32:59 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> <0201522a-b15a-4401-a208-5d9af70bdd74@w24g2000prd.googlegroups.com> Message-ID: <8947211d-2ee8-403a-8c8a-c7599aea5f80@k24g2000pri.googlegroups.com> 2008-12-08 Xah Lee wrote: > > Also, in this discussion, thanks to Thomas M Hermann's $20 offered to > > me for my challenge to you, that i have taken the time to show working > > code that demonstrate many problems in your code. A moron, wrote: > You failed the challenge that you were given. you didn't give me a challenge. I gave you. I asked for $5 sincerity wage of mutal payment or money back guarantee, so that we can show real code instead of verbal fight. You didn't take it and do nothing but continue petty quarrel on words. Thomas was nice to pay me, which results in my code that is demonstratably faster than yours. (verified by a post from ?jason-sage @@@ creativetrax.com?, quote: ?So Xah's code is about twice as fast as Jon's code, on my computer.?, message can be seen at ? http://www.gossamer-threads.com/lists/python/python/698196?do=post_view_threaded#698196 ? ) You refuse to acknowledge it, and continue babbling, emphasizing that my code should be some hundred times faster make valid argument. As i said, now pay me $300, i will then make your Mathematica code in the same level of speed as your OCmal. If it does not, money back guaranteed. Here's more precise terms i ask: Show me your OCmal code that will compile on my machine (PPC Mac, OSX 10.4.x). I'll make your Mathematica code in the same speed level as your OCmal code. (you claimed Mathematica is roughly 700 thousand times slower to your OCmal code. I claim, i can make it, no more than 10 times slower than the given OCmal code.) So, pay me $300 as consulting fee. If the result does not comply to the above spec, money back guaranteed. > You should accept the fact that Mathematica currently has these > insurmountable limitations. insurmountable ur mom. Xah ? http://xahlee.org/ ? From malkarouri at gmail.com Mon Dec 8 07:39:29 2008 From: malkarouri at gmail.com (malkarouri) Date: Mon, 8 Dec 2008 04:39:29 -0800 (PST) Subject: how to get a beep, OS independent ? References: Message-ID: <85932553-02a8-481e-add2-945effc77b22@j39g2000yqn.googlegroups.com> On 6 Dec, 23:40, Stef Mientki wrote: > hello, > > I want to give a small beep, Just to add to the options here. Where ncurses work you can use: python -c 'from curses import *;wrapper(lambda s:beep())' To try it just enter the whole line above in the command line.. Regards, Muhammad Alkarouri From lie.1296 at gmail.com Sun Dec 14 21:11:10 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 15 Dec 2008 02:11:10 +0000 (UTC) Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> <0152e35f$0$8244$c3e8da3@news.astraweb.com> Message-ID: On Fri, 12 Dec 2008 22:55:20 +0000, Steven D'Aprano wrote: > On Fri, 12 Dec 2008 21:18:36 +0000, Lie Ryan wrote: >> Personally, I'd prefer VB's version: >> foo IsNot bar >> >> or in pseudo-python >> foo isnot bar >> >> since that would make it less ambiguous. > > "a is not b" is no more ambiguous than "1+2*3". True, there's ambiguity > if you are ignorant of the precedence rules, but that's no worse than > saying that "+" is ambiguous if you don't know what "+" means. > > "What's this 'is' operator??? It's ambiguous, it could mean ANYTHING!!! > Panic panic panic panic!!!" > > *wink* > > You're allowed to assume the normal conventions, and (lucky for me!) > despite being Dutch Guido choose to assume the normal English convention > that "a is not b" means the same as "not (a is b)" rather than "a is > (not b)". That's probably because the use-cases for the second would be > rather rare. > > So given the normal precedence rules of Python, there is no ambiguity. > True, you have to learn the rules, but that's no hardship. *I* know about the precedence rule, but a newbie or a tired programmer might not. He might want to reverse the truth value of argument b but instead has just reversed the whole expression. Probably in a slightly convoluted code like this: if a is not(b and c): ... From weir009 at sina.com Tue Dec 30 04:23:52 2008 From: weir009 at sina.com (weir009 at sina.com) Date: Tue, 30 Dec 2008 01:23:52 -0800 (PST) Subject: How to debug embeding Python? References: Message-ID: <0c5f8b3f-873b-4b41-8435-9191c0fec875@w39g2000prb.googlegroups.com> Using udp to send out message is a convenient way, you may define a log function like following, and start a udp server to lisen. ############# from socket import * udpSock = socket(AF_INET,SOCK_DGRAM) def log(s): udpSock.sendto(s, ('127.0.0.1', 514)) log('hello') From nemokingdom at gmail.com Sun Dec 28 22:11:06 2008 From: nemokingdom at gmail.com (nemo) Date: Sun, 28 Dec 2008 19:11:06 -0800 (PST) Subject: ftp design question Message-ID: <74706983-5198-436b-b0ca-b0246a41c67e@v5g2000prm.googlegroups.com> Hi,all. I'm on a toy ftp project and I want it to be convinient for the user to cancel an undergoing downloading while continue others. The following code explains: for file in download_files: self.ftp.retrbinary('RETR '+file, fileHandler) Thers seems not a solid way to cancel this transfer and I considered thread or process but I can't handle this correctly. Thread: I can't kill the thread in another thread, so... Process: There seems something wrong(raise an EOFError exception) when I use Process(target = download_fun, args = (dir,)) for each downloading after connection built. Some suggestions? From rdmurray at bitdance.com Thu Dec 18 11:14:31 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Thu, 18 Dec 2008 16:14:31 +0000 (UTC) Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> <6qv7kfFeuf65U1@mid.uni-berlin.de> Message-ID: Quoth "Diez B. Roggisch" : > Neal Becker wrote: > > > Tino Wildenhain wrote: > > > >> Neal Becker wrote: > >> ... > >>> That makes no sense to me. If I call 'print' on a container, why > >>> wouldn't it recursively print on the contained objects? Since print > >>> means call str, printing a container should recursively call str on the > >>> objects. [...] > >> Every class is free on how to best implement __str__, you will find > >> the same behavior on tuple and list as well. > >> > >> Maybe its discussable to change the implementation sensibly, best if you > >> would come with a proposal? Perhaps pprint.pprint is a starting point? > >> > >> Regards > >> Tino > > > > First, I'd like to know if there is a rationale for the current design. > > Am I correct in thinking this is a defect? > > I don't think so. First of all, there is no "generic" way of printing a > collection. And the current implementation tries to give an overview what > is contained in the collection, without trying to make it "fancy" - any > such thing needed to be hand-coded anyway. > > Using repr for that is better suited, as for example string keys are printed > with quotes around them - making clear what they are, and not irritating > the user through potentially contained spaces or even things that look as > if they are python objects. > > For example, if repr *wasn't* used, > > { "{foo=bar}" : "baz"} > > would be printed > > {{foo=bar} : baz} > > Which is *not* what the dictionary actually contains! > > The same goes for unicode-objects. They appear with their "funny" characters > as \xXX-codes - instead of bailing out on you with unicode-errors. Note that this last is no longer true in Python 3.0. There, repr prints into the current encoding of the output, and so you may get decode errors. This is an accepted usability tradeoff, as it allows people using these character sets (and who therefore will have terminals set to display them!) to actually see the characters in their data. If you need the old behavior you use 'ascii'. --RDM From rhamph at gmail.com Tue Dec 9 14:34:31 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Tue, 9 Dec 2008 11:34:31 -0800 (PST) Subject: Rich Comparisons Gotcha References: Message-ID: <874a0b69-b5f3-4b9c-8fe3-d6a3275da422@w1g2000prm.googlegroups.com> You grossly overvalue using the "in" operator on lists. It's far more common to use a dict or set for containment tests, due to O(1) performance rather than O(n). I doubt the numpy array supports hashing, so an error for misuse is all you should expect. In the rare case that you want to test for identity in a list, you can easily write your own function to do it upfront: def idcontains(seq, obj): for i in seq: if i is obj: return True return False From steve at REMOVE-THIS-cybersource.com.au Wed Dec 31 03:34:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Dec 2008 08:34:48 GMT Subject: MemoryError when list append... plz help References: Message-ID: <016b25a5$0$6988$c3e8da3@news.astraweb.com> On Tue, 30 Dec 2008 22:02:49 -0800, [BON] wrote: > ====================== > s=[] > for i in range(11000-1): > for j in range(i+1, 11000): > .... > s.append(((i,j),sim)) > ====================== > above sim is floating type. > s.append is totally coducted 60,494,500 times. but this code raise > MemoryError. > > My computer has 4G RAM. > i think it's enough. but it doesn't... Your computer might have 4GB, but how much memory can Python allocate? What operating system are you using? Each time you are appending to the list, you append a tuple: ((i, j), sim) where sim is a float and i and j are ints. How much memory does each of those take? >>> sys.getsizeof( ((0, 1), 1.1) ) 32 So each entry requires 32 bytes. 60 million times 32 bytes = almost 2GB alone. Plus the list itself will require (approximately) between 230MB and 460MB just for the pointers. What are you expecting to do with this enormous list, and why do you need it all at once? -- Steven From arnodel at googlemail.com Fri Dec 5 15:27:27 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 05 Dec 2008 20:27:27 +0000 Subject: Overriding a method at the instance level on a subclass of a builtin type References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> Message-ID: Arnaud Delobelle writes: > "Zac Burns" writes: > >> Ok. Feature request then - assignment of a special method name to an >> instance raises an error. > > I haven't got the time to implement it, but I'm sure you can obtain the > behaviour you want. OK I've had half an hour to fill this afternoon so I tried to implement it. I've restriced the ability to override special methods to __getitem__ but this could be extended to any special method AFAICS. It combines a metaclass and two descriptors (one for the metaclass and one for the class), there may be a simpler way! It is proof-of-concept code, I have not tried to make it behave sensibly when no __getitem__ method is defined (although that would be straighforward) and I have not thought about how it would work with (multiple) inheritance (this may require lots more thinking). Here it is, tested very succintly on Python 2.5: class ClassGetItem(object): def __get__(self, obj, objtype=None): return obj._getitem_ def __set__(self, obj, val): obj._getitem_ = val class GetItem(object): def __get__(self, obj, objtype=None): return obj._getitem_ def __set__(self, obj, val): obj._getitem_ = val class MetaOverrideSpecial(type): def __new__(meta, name, bases, attrs): if '__getitem__' in attrs: attrs['_getitem_'] = attrs['__getitem__'] attrs['__getitem__'] = GetItem() return type.__new__(meta, name, bases, attrs) __getitem__ = ClassGetItem() class OverrideSpecial(object): __metaclass__ = MetaOverrideSpecial Here is an example that shows it in action: >>> class Foo(OverrideSpecial): ... def __getitem__(self, key): return 'Class getitem(%s)' % key ... >>> foo=Foo() >>> foo[3] 'Class getitem(3)' Override the class's __getitem__ special method: >>> Foo.__getitem__ = lambda self, key: 'Overriden class getitem(%s)' % key >>> foo['bar'] 'Overriden class getitem(bar)' Override the instance's __getitem__ special method: >>> foo.__getitem__ = lambda key: 'Instance getitem(%s)' % key >>> foo['baz'] 'Instance getitem(baz)' What-a-way-to-waste-time'ly yours -- Arnaud From steven at REMOVE.THIS.cybersource.com.au Mon Dec 22 20:25:48 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 23 Dec 2008 01:25:48 GMT Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: On Mon, 22 Dec 2008 07:11:02 -0800, walterbyrd wrote: > I have read that python is the world's 3rd most popular language Oh, well if it's written down it must be true. > But, I can't help but wonder how python's popularity was determined. Why don't you ask the people who made the claim? -- Steven From nick at craig-wood.com Tue Dec 2 13:30:47 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 02 Dec 2008 12:30:47 -0600 Subject: Do more imported objects affect performance References: <1be78d220812010621u51dead9dnbaa0b4c8c9414362@mail.gmail.com> <79153a2e0812012124o7401df57m4ac21dfe37c2ec5@mail.gmail.com> <01453438$0$20670$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Tue, 02 Dec 2008 11:12:31 +0000, Nick Craig-Wood wrote: > > > I prefer the "from module import function". That means that if "module" > > doesn't supply "function" it raises an exception at compile time, not > > run time when you try to run "module.function". > > Wanna bet? > > > >>> def spam(): > ... from math import harmonic_series > ... return harmonic_series() > ... > >>> dis.dis(spam) > 2 0 LOAD_CONST 1 (-1) > 3 LOAD_CONST 2 (('harmonic_series',)) > 6 IMPORT_NAME 0 (math) > 9 IMPORT_FROM 1 (harmonic_series) > 12 STORE_FAST 0 (harmonic_series) > 15 POP_TOP > > 3 16 LOAD_FAST 0 (harmonic_series) > 19 CALL_FUNCTION 0 > 22 RETURN_VALUE > >>> spam() > Traceback (most recent call last): > File "", line 1, in > File "", line 2, in spam > ImportError: cannot import name harmonic_series > > > The same thing happens if the from...import is at the top level of the > module, except that compilation is immediately followed by > execution. You are technically right I am sure. However the error happens when you import the module with the error in, not when you run stuff from it which is the major difference. $ echo -e "from os import sausage\n" > import_test.py $ python Python 2.5.2 (r252:60911, Sep 29 2008, 21:15:13) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> # This does produce an error >>> import import_test Traceback (most recent call last): File "", line 1, in File "import_test.py", line 1, in from os import sausage ImportError: cannot import name sausage >>> $ # This produces an error also $ python import_test.py Traceback (most recent call last): File "import_test.py", line 1, in from os import sausage ImportError: cannot import name sausage $ Unlike $ echo -e "import os\ndef f(): os.sausage\n" > import_test.py $ python Python 2.5.2 (r252:60911, Sep 29 2008, 21:15:13) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> # This doesn't produce an error >>> import import_test >>> # Until you actually call it >>> import_test.f() Traceback (most recent call last): File "", line 1, in File "import_test.py", line 2, in f def f(): os.sausage AttributeError: 'module' object has no attribute 'sausage' >>> $ # No error here either $ python import_test.py $ > > It then becomes very easy to see which functions you use from any > > given module too. > > If that's important to you. Personally, I find it more useful to know > where a function is defined. We can agree to differ there I'm sure ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From stef.mientki at gmail.com Tue Dec 23 07:53:07 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 23 Dec 2008 13:53:07 +0100 Subject: Why MyHDL? In-Reply-To: <4950d063$0$2853$ba620e4c@news.skynet.be> References: <4950d063$0$2853$ba620e4c@news.skynet.be> Message-ID: <4950DF33.3010100@gmail.com> hello Jan, Jan Decaluwe wrote: > Hello: > > MyHDL is a Python package for using Python as a > Hardware Description Language. > > A new release is upcoming, and on this occasion > we have prepared a page about why MyHDL may > be useful to you: > > http://www.myhdl.org/doku.php/why > Very Interesting, I'm no expert at all (but as an exercise I'm just now writing an EDIF-v2 to SystemC converter in Python) , I wonder why I only see comparison with VHDL and SystemVerilog, and not with SystemC ? thanks, Stef From hackingkk at gmail.com Mon Dec 15 13:00:43 2008 From: hackingkk at gmail.com (Krishnakant) Date: Mon, 15 Dec 2008 23:30:43 +0530 Subject: %s place holder does not let me insert ' in an sql query with python. In-Reply-To: <49469568.2090203@holdenweb.com> References: <1229345178.31093.24.camel@krishna-laptop> <49469568.2090203@holdenweb.com> Message-ID: <1229364043.31093.67.camel@krishna-laptop> Hi steve. you are right. Thanks for all you who helped to understand how to and *not* to pass queries through psycopg2 which is a module based on python dbapi. the following query worked. cursor.execute("insert into vendors values(%s,%s)", lstParams) lstParams contained all the values and yes one had an ' in it. thanks again for all the help. happy hacking. Krishnakant. On Mon, 2008-12-15 at 12:35 -0500, Steve Holden wrote: > Lamonte Harris wrote: > > I had this problem too. If you've upgraded to python 2.6 you need to > > use the new sytnax "format > > > > queryString = "insert into venders > > values('{0}','{1}','{2}'".format(field1,field2,field3) > > > Will all readers of this thread kindly regard this as an example of how > *not* to generate and execute SQL queries in Python. Study the > cursor.execute() method, and provide parameterized queries and a data > tuple instead. > > Please also note that the above technique explicitly continues to > generate SQL syntax errors in Krishnakan's case where the data values > themselves contain apostrophes. > > regards > Steve From bblais at bryant.edu Sun Dec 7 15:27:08 2008 From: bblais at bryant.edu (Brian Blais) Date: Sun, 7 Dec 2008 15:27:08 -0500 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: On Dec 5, 2008, at 21:21 , Daniel Fetchinson wrote: > The proposal is to allow this: > > class C: > def self.method( arg ): > self.value = arg > return self.value > > instead of this: > > class C: > def method( self, arg ): > self.value = arg > return self.value > I have never understood the objection to the explicit self. As far as I can tell it just stems from laziness, and perhaps (more legitimately) from an unclear error message about arguments. When I was a python newbie, a short while ago, I would have to look twice at the number of arguments in the error, but quickly learned what this meant. Forgetting self, which I still do, makes me do a face slap, but I always felt that it is *my* problem, and I still do. It is far clearer what is going on with the explicit self. Even if I were lazy, and didn't want to type it, it seems as if the proposal saves me nothing there....so why have it? It is also confusing, because when you're reading the code, "self" is not defined at the time, so it looks weird to have self.method pop up. Allowing both would be *ultra* confusing. I teach python to a lot of students who are new programmers, and for them to see two different forms for the same thing would be very bad, and I see absolutely no benefit, even to experienced programmers. What problem is it supposed to solve? +1 on changing the error text, however, perhaps even with a suggestion..."possibly missing 'self' argument." bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at microcorp.co.za Tue Dec 23 05:21:18 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 23 Dec 2008 12:21:18 +0200 Subject: Python's popularity (a bit OT) References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> <7c02eb33-a919-4481-8eda-76062729f233@k19g2000yqg.googlegroups.com> Message-ID: <01e601c964e9$d1b7a1c0$0d00a8c0@hendrik> "r" wrote: >I think you missed my point Steven, I was in no way proud of the fact >of my 9th place rating. It just proves my point to the small following >of this group. And frankly makes me feel bad. This spurt of high frequency posts is something that seems to happen to most newcomers to the group. (I think - I have done no stats on it, but I get the feeling...) So maybe the advice is to settle down and enjoy using the resource, because it is an amazing one - there are some hyper intelligent people around. Some of them have some experience. Some of them even know a little python... It also helps if you answer some of the newbie questions, as it crystallises your own knowledge of the language. - that is the way to show how big your cojones are. Nobody believes your claims based on mere descriptions. As you go along, you will find that this group will rarely let you get away with talking nonsense - It has been my experience that my slightest error or fumble has almost always been pitilessly pointed out. I think it is because the volume is high, and people get irritated if they have to wade through stuff like this post that has more to do with etiquette than python. - Hendrik From Scott.Daniels at Acm.Org Mon Dec 29 14:05:52 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 29 Dec 2008 11:05:52 -0800 Subject: why cannot assign to function call In-Reply-To: <97a11245-a034-4558-82d4-0c87e02bdb7e@u18g2000pro.googlegroups.com> References: <97a11245-a034-4558-82d4-0c87e02bdb7e@u18g2000pro.googlegroups.com> Message-ID: <47-dnUx1_OP7gsTUnZ2dnUVZ_r6dnZ2d@pdx.net> John Machin wrote: > On Dec 29, 5:01 pm, scsoce wrote: >> I have a function return a reference, > > Stop right there. You don't have (and can't have, in Python) a > function which returns a reference that acts like a pointer in C or C+ > +. Please tell us what manual, tutorial, book, blog or Usenet posting > gave you that idea, and we'll get the SWAT team sent out straight > away. Perhaps we can send the the Pennsylvania State University out after them. I don't know why, but some fairly substantial people here are scared of the PSU. ... Oh, I have just been informed by my captors that the are the Python Secre.... From rt8396 at gmail.com Tue Dec 2 19:24:06 2008 From: rt8396 at gmail.com (r) Date: Tue, 2 Dec 2008 16:24:06 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> Message-ID: <00ab327a-c3fc-4b15-a084-4f8c6aed6a8e@o2g2000yqd.googlegroups.com> I added you name to my "for" list. thanks From martin at marcher.name Fri Dec 26 15:42:34 2008 From: martin at marcher.name (Martin) Date: Fri, 26 Dec 2008 21:42:34 +0100 Subject: [SQL] Right way to set a variable to NULL? In-Reply-To: <5nfal41gom0iqi2nh5h0m5847ev9brtvpf@4ax.com> References: <5nfal41gom0iqi2nh5h0m5847ev9brtvpf@4ax.com> Message-ID: <5fa6c12e0812261242l34d26484k3e1661e3f567cad8@mail.gmail.com> Hi, I'd create a simple wrapper object class MailAddress(object): def __init__(self, address=None): self.address = address def __str__(self): if address: return self.adress return "NULL" you can keep most of your code just replace the original instantiation of the mail str-instance with the MailAddress This is just scratched up quickly. Hope it helps Martin 2008/12/26 Gilles Ganault : > sql = 'INSERT INTO mytable (name,address,web,mail) VALUES > ("%s","%s","%s","%s","%s")' % (name,address,web,mail) > ======= > > Is there a better way in Python to have a variable match NULL than > building the SQL query step by step? > > Thank you. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://soup.alt.delete.co.at http://www.xing.com/profile/Martin_Marcher http://www.linkedin.com/in/martinmarcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From sturlamolden at yahoo.no Fri Dec 12 08:43:05 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 05:43:05 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> Message-ID: <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> On Dec 12, 2:29 pm, sturlamolden wrote: > Creating a fast implementation of a dynamic language is almost rocket > science. But it has been done. There is Stronghold, I meant of course Strongtalk... From shao.tu at gmail.com Fri Dec 12 01:50:06 2008 From: shao.tu at gmail.com (stalex) Date: Thu, 11 Dec 2008 22:50:06 -0800 (PST) Subject: Py_GetPath() C API in python 3 References: <772bb62b-1ef1-4ffa-90f6-c1cbdc728fdd@q30g2000prq.googlegroups.com> Message-ID: On 12?11?, ??5?53?, stalex wrote: > Hi all, > > I want to build a new, requires total control, python interpreter. So > I implement my own version of Py_GetPath(), Py_GetPrefix(), > Py_GetExecPrefix() and Py_GetProgramFullPath(). When compiling, I > always get error messages, for each API function, look like > followings: > > /opt/python-3.0/lib/python3.0/config/libpython3.0.a(getpath.o)(.text > +0x211c): In function `Py_GetPath': > ./Modules/getpath.c:739: multiple definition of `Py_GetPath' > myApp.o(.text+0x0):/home/alex/workspace/develop/src/myApp.c:11: first > defined here > /usr/bin/ld: Warning: size of symbol `Py_GetPath' changed from 126 in > system.o to 32 in /opt/python-3.0/lib/python3.0/config/libpython3.0.a > (getpath.o) > collect2: ld returned 1 exit status > > If I compile my application with python 2.x, everything's just okay > and my application as well. Any ideas on how to get this working for > python 3? Nobody could answer this question? From martin at v.loewis.de Mon Dec 8 20:04:18 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 09 Dec 2008 02:04:18 +0100 Subject: python-devel download and install In-Reply-To: References: Message-ID: <493DC412.8060909@v.loewis.de> > I am developing in Python version 2.5.2 and need to install and download > the python-devel library. (This is needed so I can build and install > mysql-python.) Where can I find find this module to download and > build/installation instructions? I have been unable to find the source > online to download. > > I am not root on the box where I need to install this module so I need > the source (rpm/deb packages will not do). The sources of Python 2.5.2 are available from http://www.python.org/ftp/python/2.5.2/Python-2.5.2.tar.bz2 The term "python-devel" specifically refers to a rpm/deb package, though. You might need to layout the sources so that they meet your needs (e.g. by installing them locally). Regards, Martin From bsk16 at case.edu Mon Dec 8 12:14:56 2008 From: bsk16 at case.edu (Ben Kaplan) Date: Mon, 8 Dec 2008 12:14:56 -0500 Subject: Calling C# COM (.NET) from python In-Reply-To: References: Message-ID: <2CE93A19-C4D3-4AA0-890C-43BB9F6747CE@case.edu> On Dec 8, 2008, at 11:53 AM, Andrew Falanga wrote: > Hi, > > I've never programmed in python and only have a small understanding of > what is wrapped up in the terms COM and .NET. Is there a way of using > python to get a hold of objects written in C# as COM objects using > python? I'm looking for ways to avoid VBScript (which, after a couple > of weeks, I've determined to be horrid). That is, is there a way of > getting at COM objects in python that's similar to doing a > CreateObject call in VBScript (http://msdn.microsoft.com/en-us/ > library/ > dcw63t7z.aspx)? > > Thanks, > Andy > -- > http://mail.python.org/mailman/listinfo/python-list I would not deal with COM at all. I personally have not used it, but there is a version of python called IronPython that's written in C#, so it can use .NET and, I think, other C# objects. Other people will probably help you more, but you might want to look into that and maybe ask this on the python-win list. From gandalf at shopzeus.com Sun Dec 7 13:27:05 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Sun, 07 Dec 2008 19:27:05 +0100 Subject: How to Write to csv file to create bulk address book In-Reply-To: <5387c7a1-eb04-4d27-826c-d6257298e2db@f40g2000pri.googlegroups.com> References: <5387c7a1-eb04-4d27-826c-d6257298e2db@f40g2000pri.googlegroups.com> Message-ID: <493C1579.7030302@shopzeus.com> > I am new to scripting, I am working on script which would create 'n' > number address book entries into a csv file which would be used to > import into a address book. I need suggestions for the same > Please check out the 'csv' module. It comes with Python. Batteries included. :-) http://docs.python.org/library/csv.html There are nice examples at the end of that page. From vinay_sajip at yahoo.co.uk Sun Dec 7 07:21:57 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Sun, 7 Dec 2008 04:21:57 -0800 (PST) Subject: Select, interrupted system call, log rotation? References: <2b8928dd-4d0c-4e90-ba1e-1c68068c73d1@t3g2000yqa.googlegroups.com> Message-ID: <0a3e3a05-4815-4325-97dc-8aa5e77e1f8d@l16g2000yqo.googlegroups.com> On Dec 6, 8:39 pm, Rainy wrote: > I got an interrupted system call exception in select and I don't know > what could have caused it. Here's the error: > > select.select(inputs, [], [], 9) > error: (4, 'Interrupted system call') > Caught an exception, shutting down... > > It's py2.3, on mach architecture. > > I'm trying to figure out what caused it, and the only idea I have so > far is that it could be that I have python's logging system log > rotation thing running and I think I've seen a reference somewhere > that it uses SIGALRM when log file reaches set size to stop and switch Python's logging package doesn't use signals, as it's cross-platform. The handler just checks when a log event is handled whether rotation should occur, and if it should, then the log files are rotated. Regards, Vinay Sajip From tjreedy at udel.edu Thu Dec 4 14:37:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Dec 2008 14:37:58 -0500 Subject: schizophrenic view of what is white space In-Reply-To: <49381C2E.3060707@mrabarnett.plus.com> References: <4937E8E5.2090306@chamonix.reportlab.co.uk> <20081204143337.20272.1236189783.divmod.quotient.15592@ohm> <4938112F.5030706@chamonix.reportlab.co.uk> <49381C2E.3060707@mrabarnett.plus.com> Message-ID: MRAB wrote: > Robin Becker wrote: >> Jean-Paul Calderone wrote: >> ......... >>> >>> You have to give the re module an additional hint that you care about >>> unicode: >>> >>> exarkun at charm:~$ python >>> Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu >>> 4.2.3-2ubuntu7)] on linux2 >>> Type "help", "copyright", "credits" or "license" for more information. >>> >>> import re >>> >>> print re.compile(r'\s').search(u'a\xa0b') >>> None >>> >>> print re.compile(r'\s', re.U).search(u'a\xa0b') >>> <_sre.SRE_Match object at 0xb7dbb3a0> >>> >>> >>> >>> Jean-Paul >> ....... >> >> so the default behaviour differs for unicode and re working on >> unicode. I suppose that won't be true in Python 3. > > > I'm not sure why the Unicode flag is needed in the API. I reckon that it > should just look at the text that the regular expression is being > applied to: if it's Unicode then follow the Unicode rules, if not then > don't. I presume because \b is interpreted and replaced when the re is compiled into internal state machine form. From mail at microcorp.co.za Fri Dec 5 13:54:11 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 5 Dec 2008 20:54:11 +0200 Subject: Guido's new method definition idea References: Message-ID: <006201c95745$12e30e80$0d00a8c0@hendrik> "James Stroud" wrote: > Consider the maverick who insists on 8<--------example with "me" instead of "self" -------- > What's the interpreter going to do with our maverick's code? Took me a while, but after I remembered that a "maverick" is an unmarked, wild member of the bovine species that is effectively res nullius, I suppose the answer should be that he or she be brought back into the fold by being branded in the normal fashion - the application of a hot iron, in the shape of the standard python logo, to the buttocks. - Hendrik From Eric_Dexter at msn.com Mon Dec 1 03:39:08 2008 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Mon, 1 Dec 2008 00:39:08 -0800 (PST) Subject: tkinter question References: <538f4349-02a1-4c2b-b892-a01f1f48cb5b@l64g2000hse.googlegroups.com> Message-ID: On Oct 26, 7:02?am, "Chuckk Hubbard" wrote: > Hello. > How about this? ?I changed the if statements so the coordinates are > always updated, but only changed if within the right limits, otherwise > updated to the existing value. ?Now if you drag outside the limits of > one dimension, it still moves in the other dimension. ?Not sure if > that's what you want. ?I'm amazed that this can be so simple, I came > up with an intricate system for my app, not realizing I could bind > events to canvas items! > BTW, I've never come across csoundroutines, can you give me a synopsis > of what it's for? ?I'm using thePythonCsoundAPI. ?This is why I > commented out all the references to csoundroutines, I don't have it > installed at the moment. > -Chuckk > > #!/usr/bin/python > from Tkinter import * > #import csoundroutines as cs > > root = Tk() > > global canv > xx = {} > > def makeFrame(root): > ? global canv > # ?test = cs.csdInstrumentlist3('bay-at-night.csd') > ? canv = Canvas (root, height = 200, width = 350) > > # ?for i in range (0, len(test.instr_number)): > ? for i in range (0, 4): > # ? ?canv.create_text(10, i *10, text=str(test.instr_number[i]) + > ? ? canv.create_text(10, i *10, text=str(i) + > '...', tags=('movable')) > ? ? xx[i] = canv.tag_bind('movable', '', slide) #B1-motion > is a drag with left button down > ? ? canv.pack() > > def slide (event): > ? ''' > ? triggered when something is dragged on the canvas - move thing > under > mouse ('current') to new position > ? ''' > ? if 0 < event.x < 200: > ? ? ? newx = event.x > ? else: newx = canv.coords('current')[0] > ? if 0 < event.y < 100: > ? ? newy = event.y > ? else: newy = canv.coords('current')[1] > ? canv.coords('current', newx, newy) > > makeFrame(root) > root.mainloop() > > > > > > On Fri, Oct 3, 2008 at 3:44 PM, Eric_Dex... at msn.com wrote: > > I saw this (close to this anyway) lieing around on the internet and > > was wanting to use it to define a start point exc but I need the > > graphics to stay within a set y coords and I am not realy sure how to > > do that. ?I have no idea on how to bind a min/max y to it. ?(the > > concept is inspired by the javacsoundblue). > > > #!/usr/bin/python > > from Tkinter import * > > import csoundroutines as cs > > > root = Tk() > > > global canv > > xx = {} > > > def makeFrame(root): > > ? global canv > > ? test = cs.csdInstrumentlist3('bay-at-night.csd') > > ? canv = Canvas (root, height = 200, width = 350) > > > ? for i in range (0, len(test.instr_number)): > > ? ? canv.create_text(10, i *10, text=str(test.instr_number[i]) + > > '...', tags=('movable')) > > ? ? xx[i] = canv.tag_bind('movable', '', slide) #B1-motion > > is a drag with left button down > > ? ? canv.pack() > > > def slide (event): > > ? ''' > > ? triggered when something is dragged on the canvas - move thing > > under > > mouse ('current') to new position > > ? ''' > > ? newx = event.x > > ? if event.y < 10 and event.y > 0: > > ? ? newy = event.y > > ? ? canv.coords('current', newx, newy) > > > makeFrame(root) > > root.mainloop() > > -- > >http://mail.python.org/mailman/listinfo/python-list > > --http://www.badmuthahubbard.com- Hide quoted text - > > - Show quoted text - sorry to take so long to reply... You should be able to find the latest version of csound routines in the csound blog.. an older version is in dex tracker available on source forge.. From castironpi at gmail.com Mon Dec 29 21:52:59 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 18:52:59 -0800 (PST) Subject: multiprocessing vs thread performance References: <26f7d44e-552c-41e9-9290-17e5c4e6deb9@q30g2000prq.googlegroups.com> Message-ID: On Dec 29, 7:40?pm, "James Mills" wrote: > On Tue, Dec 30, 2008 at 11:34 AM, Aaron Brady wrote: > > The OP may be interested in Erlang, which Wikipedia (end-all, be-all) > > claims is a 'distribution oriented language'. snip > I'm presently looking at Virtual Synchrony and > other distributed processing architectures - but > circuits is meant to be general purpose enough > to fit event-driven applications/systems. I noticed a while ago that threads can be used to simulate generators. 'next', 'send', and 'yield' are merely replaced by synchronizor calls (coining the term). Not the other way around, though, unless the generator guarantees a yield frequently. 'settrace' anyone? From bearophileHUGS at lycos.com Wed Dec 31 13:42:42 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 31 Dec 2008 10:42:42 -0800 (PST) Subject: How to initialize an array with a large number of members ? References: <5m4nl4hs8f9q6rfcp7b1jt7nk1o6sq6r0f@4ax.com> Message-ID: <2ef1ba2a-ae6f-4206-990e-d148a80dd17a@p2g2000prf.googlegroups.com> MRAB: > ?>>> # With a list > ?>>> tally = array('H', [0] * 75) > ?>>> > ?>>> # With a generator > ?>>> tally = array('H', (0 for i in range(75))) Time ago we have had a long discussion about this, the right way is: tally = array(someformat, [0]) * 75 (If you need to initialize it to something that isn't constant then you may have to do something different). Bye, bearophile From gagsl-py2 at yahoo.com.ar Sat Dec 13 23:10:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 14 Dec 2008 02:10:41 -0200 Subject: Bidirectional Networking References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <6qeht0Fc3541U1@mid.individual.net> <782258db-2bdc-45a7-8d8f-7a036d574985@t26g2000prh.googlegroups.com> <2cf74767-e331-4fa6-8915-8f87ba01ca34@l33g2000pri.googlegroups.com> Message-ID: En Sat, 13 Dec 2008 13:03:17 -0200, Emanuele D'Arrigo escribi?: > On Dec 12, 9:04 pm, "Gabriel Genellina" > wrote: >> If you're using 2.5 or older, override serve_forever: >> >> def serve_forever(self): >> while not getattr(self, 'quit', False): >> self.handle_request() >> >> and set the server 'quit' attribute to True in response to some command >> from the client. > > Ok, I've tried this method and it would work if I wanted to shut down > the server from the remote client. But if I want the server to shut > down from the server itself upon some condition it doesn't work > because the while statement is evaluated again only after there has > been a request. If requests are infrequent or have ceased the Yes, this is the problem with this simple approach, handle_request is blocking. Python 2.6 has great improvements on this situation. > The problem was that in my code I used: > > asyncServer.daemon = True > > but somehow that doesn't work. I then tried: > > asyncServer.setDaemon(True) > > and that does work: daemon became a property in Python 2.6; setDaemon was the only way to set it in previous versions. > Thanks for your help! Thanks for sharing your code! -- Gabriel Genellina From bearophileHUGS at lycos.com Sun Dec 7 15:27:45 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 7 Dec 2008 12:27:45 -0800 (PST) Subject: Is 3.0 worth breaking backward compatibility? References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> Message-ID: walterbyrd: > I can not think of anything that is being changed that was really a "show stopper" anyway.< I agree, but Python and its culture has a characteristic that not many other languages share: it tries to be a tidy language, to have one obvious way to do most things, it values readability and sometimes even elegance. So even if those problems aren't "showstoppers" for most languages, for the Python culture they are bad enough to need a fix. The amount of warts in the language that a Python programmer is used to tolerate in the the language is probably 1/20 of the warts a C++ programmer digests with no problem every day. Different languages, different cultures, and sometimes even different psychology & cognitive profile of the programmer. Bye, bearophile From zip610041 at gmail.com Sun Dec 7 08:14:01 2008 From: zip610041 at gmail.com (zip610041 at gmail.com) Date: Sun, 7 Dec 2008 05:14:01 -0800 (PST) Subject: Free Partitioning Software Introduction Message-ID: <6e756b72-3325-4282-aa00-e36da90fb097@k36g2000pri.googlegroups.com> Free Partitioning Software (Partition Editors, Managers, and Recovery Tools) The partition manager (editors,software,recovery tools) listed as below: Cute Partition Manager GParted LiveCD Partition Logic SwissKnife SystemRescueCD Ultimate Boot CD Ranish Partition Manager The Partition Resizer Diskman NTFS Resize TestDisk Extended FDISK More Detail http://partition-manager.blogspot.com/2008/12/free-partitioning-software-introduction.html From __peter__ at web.de Fri Dec 19 06:45:56 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2008 12:45:56 +0100 Subject: List comprehension in if clause of another list comprehension References: Message-ID: Vedran Furac( wrote: > Hi! > > In [69]: a = 'a b c' > In [70]: b = 'a b, c d' > > In [74]: [i for i in a.split() if i not in b.split()] > Out[74]: ['b'] > > Everything ok. > > In [77]: b.split() == [i for i in b.split()] > Out[77]: True > > As expected. Now, put this in the first list comprehension: > > In [80]: [i for i in a.split() if i not in [i for i in b.split()] ] > Out[80]: ['d'] > > Hmmmm... why is that? >>> a = "abc" >>> b = "a b, c d".split() >>> b ['a', 'b,', 'c', 'd'] >>> [i for i in a if i not in b] ['b'] As expected, so far, but now comes the critical step: >>> [i for i in a if i not in [i for i in b]] ['d'] The problem is that list comprehensions do not introduce a new namespace. So the inner and the outer list comp share the same i. You can either rename the inner i >>> [i for i in a if i not in [k for k in b]] ['b'] or use a generator expression which does give a new namespace: >>> list(x for x in "abc") ['a', 'b', 'c'] >>> x Traceback (most recent call last): File "", line 1, in NameError: name 'x' is not defined >>> [i for i in a if i not in (i for i in b)] ['b'] Peter From jason-sage at creativetrax.com Thu Dec 4 21:09:23 2008 From: jason-sage at creativetrax.com (jason-sage at creativetrax.com) Date: Thu, 04 Dec 2008 20:09:23 -0600 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: <49388D53.7020808@creativetrax.com> Xah Lee wrote: > alright, here's my improved code, pasted near the bottom. > > let me say a few things about Jon's code. > > If we rate that piece of mathematica code on the level of: Beginner > Mathematica programer, Intermediate, Advanced, where Beginner is > someone who just learned tried to program Mathematica no more than 6 > months, then that piece of code is Beginner level. > > Here's some basic analysis and explanation. > > The program has these main functions: > > ? RaySphere > ? Intersect > ? RayTrace > ? Create > ? Main > > The Main calls Create then feed it to RayTrace. > Create calls itself recursively, and basically returns a long list of > a repeating element, each of the element differ in their parameter. > > RayTrace calls Intersect 2 times. Intersect has 2 forms, one of them > calls itself recursively. Both forms calls RaySphere once. > > So, the core loop is with the Intersect function and RaySphere. Some > 99.99% of time are spent there. > > ------------------ > > I didn't realize until after a hour, that if Jon simply give numerical > arguments to Main and Create, the result timing by a factor of 0.3 of > original. What a incredible sloppiness! and he intended this to show > Mathematica speed with this code? > > The Main[] function calls Create. The create has 3 parameters: level, > c, and r. The level is a integer for the recursive level of > raytracing . The c is a vector for sphere center i presume. The r is > radius of the sphere. His input has c and r as integers, and this in > Mathematica means computation with exact arithmetics (and automatic > kicks into infinite precision if necessary). Changing c and r to float > immediately reduced the timing to 0.3 of original. > > ------------------ > now, back to the core loop. > > The RaySphere function contain codes that does symbolic computation by > calling Im, which is the imaginary part of a complex number!! and if > so, it returns the symbol Infinity! The possible result of Infinity is > significant because it is used in Intersect to do a numerical > comparison in a If statement. So, here in these deep loops, > Mathematica's symbolic computation is used for numerical purposes! > > So, first optimization at the superficial code form level is to get > rid of this symbolic computation. > > Instead of checking whethere his ?disc = Sqrt[b^2 - v.v + r^2]? has > imaginary part, one simply check whether the argument to sqrt is > negative. > > after getting rid of the symbolic computation, i made the RaySphere > function to be a Compiled function. > > I stopped my optimization at this step. > > The above are some _fundamental_ things any dummy who claims to code > Mathematica for speed should know. Jon has written a time series > Mathematica package that he's selling commercially. So, either he got > very sloppy with this Mathematica code, or he intentionally made it > look bad, or that his Mathematica skill is truely beginner level. Yet > he dares to talk bullshit in this thread. > > Besides the above basic things, there are several aspects that his > code can improve in speed. For example, he used pattern matching to do > core loops. > e.g. Intersect[o_, d_][{lambda_, n_}, Bound[c_, r_, s_]] > > any Mathematica expert knows that this is something you don't want to > do if it is used in a core loop. Instead of pattern matching, one can > change the form to Function and it'll speed up. > > Also, he used ?Block?, which is designed for local variables and the > scope is dynamic scope. However the local vars used in this are local > constants. A proper code would use ?With? instead. (in lisp, this is > various let, let*. Lispers here can imagine how lousy the code is > now.) > > Here's a improved code. The timing of this code is about 0.2 of the > original. Also, optimization is purely based on code doodling. That > is, i do not know what his code is doing, i do not have experience in > writing a ray tracer. All i did is eyeballing his code flow, and > improved the form. > > norm=Function[#/Sqrt@(Plus@@(#^2))]; > delta=Sqrt[$MachineEpsilon]; > myInfinity=10000.; > > Clear[RaySphere]; > RaySphere = Compile[{o1, o2, o3, d1, d2, d3, c1, c2, c3, r}, > Block[{v = {c1 - o1, c2 - o2, c3 - o3}, > b = d1*(c1 - o1) + d2*(c2 - o2) + d3*(c3 - o3), > discriminant = -(c1 - o1)^2 - (c2 - o2)^2 + > (d1*(c1 - o1) + d2*(c2 - o2) + d3*(c3 - o3))^2 - > (c3 - o3)^2 + r^2, disc, t1, t2}, > If[discriminant < 0., myInfinity, > disc = Sqrt[discriminant]; If[(t1 = b - disc) > 0., > t1, If[(t2 = b + disc) <= 0., myInfinity, t2]]]]]; > > Remove[Intersect]; > Intersect[{o1_,o2_,o3_},{d1_,d2_,d3_}][{lambda_,n_},Sphere > [{c1_,c2_,c3_},r_]]:= > Block[{lambda2=RaySphere[o1,o2,o3,d1,d2,d3,c1,c2,c3,r]}, > If[lambda2?lambda,{lambda,n},{lambda2, > norm[{o1,o2,o3}+lambda2 *{d1,d2,d3}-{c1,c2,c3}]}]] > > Intersect[{o1_,o2_,o3_},{d1_,d2_,d3_}][{lambda_,n_}, > Bound[{c1_,c2_,c3_},r_,s_]]:= > Block[{lambda2=RaySphere[o1,o2,o3,d1,d2,d3,c1,c2,c3,r]}, > If[lambda2?lambda,{lambda,n}, > Fold[Intersect[{o1,o2,o3},{d1,d2,d3}],{lambda,n},s]]] > > Clear[neglight,nohit] > neglight=N at norm[{1,3,-2}]; > nohit={myInfinity,{0.,0.,0.}}; > > Clear[RayTrace]; > RayTrace[o_,d_,scene_]:= > Block[{lambda,n,g,p},{lambda,n}=Intersect[o,d][nohit,scene]; > If[lambda\[Equal]myInfinity,0,g=n.neglight; > If[g?0, > 0,{lambda,n}=Intersect[o+lambda d+delta n,neglight] > [nohit,scene]; > If[lambda > Clear[Create]; > Create[level_,c_,r_]:= > Block[{obj=Sphere[c,r]}, > If[level\[Equal]1,obj, > Block[{a=3*r/Sqrt[12],Aux}, > Aux[x1_,z1_]:=Create[level-1,c+{x1,a,z1},0.5 r]; > Bound[c,3 r,{obj,Aux[-a,-a],Aux[a,-a],Aux[-a,a],Aux[a,a]}] > ] > ]] > > Main[level_,n_,ss_]:= > With[{scene=Create[level,{0.,-1.,4.},1.]}, > Table[Sum[ > RayTrace[{0,0,0}, > N at norm[{(x+s/ss/ss)/n-1/2,(y+Mod[s,ss]/ss)/ > n-1/2,1}],scene],{s,0, > ss^2-1}]/ss^2,{y,0,n-1},{x,0,n-1}]] > > Timing[Export["image.pgm",Graphics at Raster@Main[2,100,4.]]] > > > Note to those who have Mathematica. > Mathematica 6 has Normalize, but that's not in Mathematica 4, so i > cooked up above. > Also, Mathematica 6 has AbsoluteTiming, which is intended to be > equivalent if you use stop watch to measure timing. Mathematica 4 has > only Timing, which measures CPU time. My speed improvement is based on > Timing. But the same factor will shown when using Mathematica 6 too. > > For the interested, with MMA 6, on a Pentium 4 3.8Ghz: The code that Jon posted: Timing[Export["image-jon.pgm", Graphics at Raster@Main[2, 100, 4]]] {80.565, "image-jon.pgm"} The code that Xah posted: Timing[Export["image-xah.pgm", Graphics at Raster@Main[2, 100, 4.]]] {42.3186, "image-xah.pgm"} So Xah's code is about twice as fast as Jon's code, on my computer. The resulting files were identical (and both looked like pure white images; I thought they'd be interesting!). -J From prologic at shortcircuit.net.au Tue Dec 30 17:32:13 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 08:32:13 +1000 Subject: get method In-Reply-To: References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> Message-ID: On Tue, Dec 30, 2008 at 7:10 PM, Roel Schroeven wrote: > Hm, you just changed an O(n) algorithm to an O(n**2) algorithm. No big > deal for short strings, but try your solution on a string with length > 10000 and see the difference. On my computer the O(n) version takes > 0.008 seconds, while your version takes 8.6 seconds. That's 1000 times > slower. Yes you are right :) Sadly :/ I wonder if there is a way to implement the same thing with close to O(n) complexity using list/dict comprehensions. cheers James From pyth0nc0d3r at gmail.com Mon Dec 15 08:21:55 2008 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Mon, 15 Dec 2008 07:21:55 -0600 Subject: %s place holder does not let me insert ' in an sql query with python. In-Reply-To: References: <1229345178.31093.24.camel@krishna-laptop> Message-ID: sorry about that queryString = "insert into venders values('{0}','{1}','{2}')".format(field1,field2,field3) On Mon, Dec 15, 2008 at 7:21 AM, Lamonte Harris wrote: > I had this problem too. If you've upgraded to python 2.6 you need to use > the new sytnax "format > > queryString = "insert into venders > values('{0}','{1}','{2}'".format(field1,field2,field3) > > > On Mon, Dec 15, 2008 at 6:46 AM, Krishnakant wrote: > >> hello all hackers. >> This is some kind of an interesting situation although many of you must >> have already gone through it. >> I am facing a situation where I have to use psycopg2 and insert rows in >> a postgresql table. >> That's pritty easy and no need to say that it works well. But there are >> some entries which have an ' in the value. >> I have a venders table in my database and one of the values tryed was >> "His Master's Voice " >> now the master's word has the ' which is used for starting and ending a >> varchar value for postgresql or almost any standard RDBMS. >> Does any one know what is the way out of this? >> how do you let the ' go as a part of the string? >> I have used %s as placeholder as in >> queryString = "insert into venders values ('%s,%s,%s" % >> (field1,field2,field3 ) ... >> This is not working for the ' values. >> can any one suggest a suitable solution? >> happy hacking. >> Krishnakant. >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From marco at sferacarta.com Fri Dec 5 08:06:37 2008 From: marco at sferacarta.com (Marco Mariani) Date: Fri, 05 Dec 2008 14:06:37 +0100 Subject: Don't you just love writing this sort of thing :) In-Reply-To: <01490cc5$0$20670$c3e8da3@news.astraweb.com> References: <01490cc5$0$20670$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Gosh Lawrence, do tell, which category do YOU fall into? I suppose a mix-up between a cowbody (or Fonzie) coder and a troll. His programs have an inner poetry that we're obviously too stupid to understand. From jstroud at mbi.ucla.edu Mon Dec 15 01:33:11 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 14 Dec 2008 22:33:11 -0800 Subject: Looking for the best way to translate an idiom In-Reply-To: References: Message-ID: I V wrote: > On Sun, 14 Dec 2008 21:08:33 -0800, James Stroud wrote: >> Yes. I think it was the British who decided that the apostrophe rule for >> "it" would be reversed from normal usage relative to just about every >> other noun. I'm not sure the purpose--maybe it was to give compulsive >> proofreaders a raison d'etre. > > It's because "it" is a pronoun; you don't put an apostrophe in "his," > either. Its called humor. From geekmail at usenot.de Sun Dec 7 14:41:26 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sun, 7 Dec 2008 20:41:26 +0100 Subject: Is 3.0 worth breaking backward compatibility? References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> <20081207203553.7d62434a@usenot.de> Message-ID: <20081207204126.344bb814@usenot.de> On Sun, 7 Dec 2008 20:35:53 +0100 Andreas Waldenburger wrote: > On Sun, 7 Dec 2008 11:22:23 -0800 (PST) walterbyrd > wrote: > > > At best, I am a casual python user, so it's likely that I am missing > > something. > Yes, the big picture. > OK, that was a bit harsh. I apologize. But my point remains. To reiterate: * It's not like they rewrote Pascal and called it Python 3. * There is a script that helps you porting. Jeez. * Also: Spilt milk. Sorry, I do get agitated over things like this. /W -- My real email address is constructed by swapping the domain with the recipient (local part). From castironpi at gmail.com Thu Dec 4 05:38:36 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 4 Dec 2008 02:38:36 -0800 (PST) Subject: Overriding a method at the instance level on a subclass of a builtin type References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> Message-ID: <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> On Dec 3, 1:25?pm, Jason Scheirer wrote: > On Dec 2, 6:13?pm, Aaron Brady wrote: > > >>> class A: > > > ... ? ? def methA( self ): > > ... ? ? ? ? ? ? print 'methA' > > ... ? ? ? ? ? ? self.meth= self.methB > > ... ? ? meth= methA > > ... ? ? def methB( self ): > > ... ? ? ? ? ? ? print 'methB' > > ...>>> a= A() > > >>> a.meth() > > methA > > >>> a.meth() > > > methB > > The problem with using this this pattern in the way that you've > specified is that you have a potential memory leak/object lifetime > issue. Assigning a bound method of an instance (which itself holds a > reference to self) to another attribute in that same instance creates > a kind of circular dependency that I have discovered can trip up the > GC more often than not. > > You can subclass it as easily: > > class dictsubclass(dict): > ? ? def __getitem__(self, keyname): > ? ? ? ? if not hasattr(self, '_run_once'): > ? ? ? ? ? ? self.special_code_to_run_once() > ? ? ? ? ? ? self._run_once = True > ? ? ? ? return super(self, dict).__getitem__(keyname) > > If that extra ~16 bytes associated with the subclass is really a > problem: > > class dictsubclass(dict): > ? ? def __getitem__(self, keyname): > ? ? ? ? self.special_code_to_run_once() > ? ? ? ? self.__class__ = dict > ? ? ? ? return super(self, dict).__getitem__(keyname) > > But I don't think that's a good idea at all. Interesting. The following code ran, and process memory usage rose to 150MB. It failed to return to normal afterward. >>> for x in range( 10000000 ): ... a= [] ... a.append(a) ... However, the following code succeeded in returning usage to normal. >>> import gc >>> gc.collect() It was in version 2.6. So, the GC succeeded in collecting circularly linked garbage when invoked manually. That might have implications in the OP's use case. In another language, it would work differently, if it lacked unbound method descriptors. C++ for example, untested: class C { public: func_t meth; C( ) { meth= methA; } void methA( ) { meth= methB; } void methB( ) { } }; It has no problems with memory consumption (an extra pointer per object), or circular references; functions are not first-class objects. However they are in Python, which creates an entire bound method object per instance. The OP stated: > run some code and then patch in the original dict > method for the instance to avoid even the check to see if the init > code has been run. So your, Arnaud's, and Bryan's '.__class__' solution is probably best, and possibly even truer to the intent of the State Pattern. It is too bad that you can't assign an unbound method to the member, and derive the bound method on the fly. That might provide a middle- ground solution. From collin.day.0 at gmail.com Thu Dec 18 17:31:45 2008 From: collin.day.0 at gmail.com (Collin D) Date: Thu, 18 Dec 2008 14:31:45 -0800 (PST) Subject: Factoring Polynomials References: <5dfe1cf3-530d-4e31-833e-e26db85611be@d36g2000prf.googlegroups.com> Message-ID: On Dec 18, 1:09?pm, Mark Dickinson wrote: > On Dec 18, 8:47?pm, Scott David Daniels wrote: > > > ? ? ?else: # a single result (discriminant is zero) > > ? ? ? ? ?return (-b / (2 * a),) > > Maybe make that (-b / (2. * a)) to avoid getting funny results > when a and b are integers. ?(Or do a from __future__ import > division, or use Python 3.0, or ....) > > And to make the function more bullet-proof, you might want to > do something like (untested): > > ? ? from math import copysign > > ? ? [rest of example as in Scott's post] > > ? ? if discriminant: # two results > ? ? ? ? root1 = (-b - copysign(discriminant, b))/(2*a) > ? ? ? ? root2 = c/(a*root1) > ? ? ? ? return (root1, root2) > > to avoid numerical problems when b*b is much larger > than abs(a*c). Compare with the results of the usual > formula when a = c = 1, b = 10**9, for example. ?But > that still doesn't help you when the computation > of the discriminant underflows or overflows... > > Isn't floating-point a wonderful thing! ?:) > > Mark Thanks for all your help! Its good to know how to do it w/ without numpy. And yes, floating point is the best thing since sliced bread. ^^ -CD From bj_666 at gmx.net Fri Dec 12 11:21:29 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 12 Dec 2008 16:21:29 GMT Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> <31443882-cb41-420b-8269-b1590581783d@c36g2000prc.googlegroups.com> Message-ID: <6qfhc9Fc3a5jU5@mid.uni-berlin.de> On Fri, 12 Dec 2008 07:56:58 -0800, sturlamolden wrote: > On Dec 12, 4:55 pm, sturlamolden wrote: > >> def __setitem__(self, index, value): >> if _buf[index] is not value: # given that _buf is the tuple's >> internal buffer >> raise TypeError, 'tuple' object does not support item >> assignment > > bl?h, that should be self._buf[index] But then the error message is not true anymore because tuples *would* support item assignment when the old and new value are the same. Which leads to strange things like code that may or may not raise that exception, depending on implementation details: t = (1, 2) t[0] = 1 # Maybe okay -- maybe not. t[1] += 0 # Same here. I'd find that quite odd. Ciao, Marc 'BlackJack' Rintsch From list at qtrac.plus.com Sat Dec 20 05:37:46 2008 From: list at qtrac.plus.com (Mark Summerfield) Date: Sat, 20 Dec 2008 02:37:46 -0800 (PST) Subject: ANN: New Book: Programming in Python 3 References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> Message-ID: <06daa32b-aff7-4104-99bb-3cd1365be600@w1g2000prm.googlegroups.com> On 20 Dec, 00:32, "Colin J. Williams" wrote: > Thomas Heller wrote: > > Mark Summerfield schrieb: > >> Just a follow-up to say that the book has now been published in the > >> U.S. > >> It is now in stock at InformIT, and should reach other stores, e.g., > >> Amazon, in a week or so. > > >> Also, the introduction, the first few pages of the first chapter, the > >> whole of chapter 12 (regular expressions), and the index are now > >> available for free download in a PDF from here: > >>http://www.informit.com/store/product.aspx?isbn=0137129297 > > > Question from a non-native english speaker: is this now valid english? > > > ? "One of Python's great strengths" > > ? ? ? ? ? ? ? ? ^ > > ? "and also teaches Python's functional programming features" > > ? ? ? ? ? ? ? ? ? ? ? ? ? ^ > > ? "The book's approach is wholly practical" > > ? ? ? ? ? ?^ > > > Curious, > > Thomas > > No. ?Is this a quote from some > advertising stuff or was it written by > the author? > > Colin W. All three fragments are taken from the book's Introduction, and all are correct English---both U.S. and British as it happens. (You can read them in context by downloading the sample pages PDF.) See: http://en.wikipedia.org/wiki/Apostrophe You'll also find a few instances of possessive plurals (s') in later chapters:-) The whole book was proof read by a professional (American) proof reader---in addition to the several technical reviewers who read it. There is one point of (minor) controversy in my English usage---I make my writing gender-neutral by using singular they. This is valid in both U.S. and British English but doesn't seem to be very common, but I much prefer it to all the alternatives I've seen. http://en.wikipedia.org/wiki/Singular_they With two dozen postings on my use of English I'm now rather nervous about the feeback I'll get on my Python 3! PS Although Amazon.com still says the publication date is the 27th, they now expect to have it in stock on Monday (the 22nd). From arkanes at gmail.com Tue Dec 9 13:23:24 2008 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 9 Dec 2008 12:23:24 -0600 Subject: "as" keyword woes In-Reply-To: References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> Message-ID: <4866bea60812091023p6b85b328q9c5510a7d3ef8b83@mail.gmail.com> On Tue, Dec 9, 2008 at 6:39 AM, Paul Boddie wrote: > On 9 Des, 05:52, alex23 wrote: >> >> From my perspective, it was less the original complaint and more the >> sudden jump to "CPython is dead! The GIL sucks! Academic eggheads!" >> that prompted the comparisons to trolling. > > To be fair to the complainant, before mentioning the GIL, he did > initially get the usual trite fragments of the Zen of Python right > back at him ("simple is better than complex", "special cases aren't > special enough to break the rules"), albeit not the whole thing in its > overused, unabridged form. I think I'd go on a rant if presented with > that rather than the accepted reason for the noted shortcomings of the > language: CPython's parsing technology isn't "sufficiently powerful > parser technology" as GvR himself says [1]. > > Paul > So hold up a second. I'm out of line for calling someone on making a trollish post that's not relevant to the topic, and for being pretty late to the party even with the part that *was* on topic, and for (even in the original post) going the ad-hominem route by not so subtly implying that Python is an ivory tower language that's not good enough for people with real problems - a clearly false statement by any standards, and doubly offensive from someone who *is* using it for real problems and who himself is a less than shining example of responsible software management, but the OPs lapse into ranting in response to trite but accurate answers to a question he could have answered for himself, in detail, had he bothered to read the threads from the time when the issue actually matter is a reasonable response that we should support and validate? Sometimes you're not a crusader for thinking differently and change by confrontation and speaking truth to power. Sometimes you're just an asshole. For clarification: The OPs original complaint is legitimate, if dated and partially his own fault. His phrasing of the problem, the tone and content of his email, and his lapse into flaming when he wasn't immediately hailed as a herald of sanity is not legitimate. From sturlamolden at yahoo.no Fri Dec 12 08:39:35 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 05:39:35 -0800 (PST) Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> Message-ID: <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> On Dec 12, 2:34 pm, Hrvoje Niksic wrote: > >>> import numpy > >>> t = (numpy.zeros(10),) > >>> t > > (array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]),)>>> t[0] += 1 > > Traceback (most recent call last): > File "", line 1, in > TypeError: 'tuple' object does not support item assignment > > Of course, the side effect occurs before the exception, so: > > >>> t[0] > array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) Actually I would consider this to be a bug. The tuple is immutable, but no mutation of the tuple is ever attempted. Sturla Molden From tjreedy at udel.edu Mon Dec 15 13:10:19 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 15 Dec 2008 13:10:19 -0500 Subject: Structure using whitespace vs logical whitespace In-Reply-To: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> References: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> Message-ID: cmdrrickhunter at yaho.com wrote: > I've been trying to search through the years of Python talk to find an > answer to this, but my Googlefu is weak. > > In most languages, I'll do something like this > > xmlWriter.BeginElement("parent"); > ----xmlWriter.BeginElement("child"); > ----------xml.Writer.Characters("subtext"); > ----xmlWriter.EndElement(); > xmlWriter.EndElement(); > > Where the dashes are indentation (since some newsgroup handlers don't > do tabs well). XML writing is just an example. > > In general, I'm using indentation to show logical flow through code. That, of course, is what Python does. > Python's choice to give semantic meaning to whitespace prevents me > from doing such things. You, of course, also want to giving semantic meaning to whitespace, but one that happens to be different from Python's. 'Logical control flow' versus 'output text structure'. > What was once reserved for logical use is now used syntactically. False opposition. > In 90% of cases, its not needed, and whitespace > significance seems to be pretty effective. In that last 10%, however, > I've been frustrated many times. > > I've been using python for a few years, and gotten around this in one > way or another, but now I want to get other who work with me to pick > up Python. All newbies to Python have trouble with the idea of > whitespace sensitivity, Absolutely not true. Python's indentation is +/- the same as what people routinely (but usually optionally) do when writing other algorithmic languages, including most pseudocode. It also mimics standard outline mode and other structured text (as you with to do). I choose Python in part *because* it has a standard mandated indentation scheme versus the multiple optional schemes of C programmers. Enough of the endless C whitespace wars. I strongly suggest that you not project *your* troubles onto others. Let them come upon it by themselves -- or not. > but how can I convince them that "it just works better" The tradeoff is between personal flexibility (a loss to you) and uniformity across programs (you can read *any* Python program and understand the meaning of the indentation). Someone who does not see the latter as a gain perhaps should not use Python. > when I have this construct which I want to use but can't. Yet > Has anybody found a way to emulate this behavior? New question: this answer has perhaps been posted before. For your example, write a context manager 'Element' (possible in 2.5+, but I use 3.0). class Element(): def __init__(self, item): self.item = item def __enter__(self): print('' % self.item) def __exit__(self, t,v,tb): print('') # Then with Element('parent'): with Element('child'): print("subtext") # prints subtext Of course, the element class(es) could be in a module with global indent and delta, methods that add and subtract the delta as appropriate, and a print function that prepends the current indent to get something like subtext To me, this Python-style construct is better. You get the Element closure written 'for free'. Less need to match indent levels, no possibility of forgetting closures. If there are multiple container elements with different closures, you get the right one automatically and cannot mismatch. > I've often done it > by opening an expression for the whole thing, but there's a lot of > tasks where a single expression just isn't sufficient (such as things > with assignment). I do not understand this without a concrete example. > PS. In my opinion the solution would be to have the option of entering > a "whitespace insensitive" mode which uses C style {} and ;. I think the above is much better ;-). And yes, such ideas have been discussed and rejected. Terry Jan Reedy From alitosis at gmail.com Thu Dec 18 20:53:46 2008 From: alitosis at gmail.com (alito) Date: Thu, 18 Dec 2008 17:53:46 -0800 (PST) Subject: psycopg2 and large queries References: Message-ID: <1de36399-f94f-42b3-87ea-3812fed4bd86@r36g2000prf.googlegroups.com> On Dec 19, 2:34?am, Laszlo Nagy wrote: > > I was looking for psycopg2 documentation, but I found nothing. However, > I found some posts telling that named cursors do support fetching a > single row at a time. Here is how to create a named cursor: > > cur = conn.cursor('mycursor') > > This is very strange, because DB API 2.0 does not have this feature. Why > this feature was created, and how to use it? Not documented. > The feature was created to use server-side cursors. The DB API doesn't specify how to create them. I've got no idea why it isn't documented. > However, this is also not usable, because named cursors do not have a > ".description" property! You can try this: > > cur = conn.cursor('mycursor') > cur.execute('select name from product limit 1000000') > print repr(cur.description) ?# -> None > They do have a description attribute, but it is only populated after you fetch a row. eg try cur = conn.cursor(name='mycursor') cur.execute('select name from blah') cur.fetchone() print cur.description > This is unacceptable! Really? I accepted it just fine. > > p.s.: I tried to subscribe to the psycopg mailing list, but the > confirmation email did not arrive in 6 hours... psycopg website and development in general seems to be comatose. Emails to the list are being silently dropped. Also, don't believe the front page, development stopped happening on that svn branch a while ago and moved to a bzr branch, which has failed to respond for the last few weeks. Maybe the relevant people are on holidays. If this persists for a while someone will fork it, since quite a few people are interested in its continued development. From castironpi at gmail.com Fri Dec 19 19:59:53 2008 From: castironpi at gmail.com (Aaron Brady) Date: Fri, 19 Dec 2008 16:59:53 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <063b192e-fbde-4614-b90f-2d88f4dc51b5@z6g2000pre.googlegroups.com> On Dec 19, 1:43?pm, excord80 wrote: snip cons of Python > But, Python is Python. It's always surprising to me to hear this, but especially so in writing. It speech, it has connotations. A millionaire can say (dismissively), "Two bucks is two bucks." A poor person can say (wondrously), "Two bucks is two bucks." Without knowing the expository (the facts about the speakers), you could glean some of the context from the tone and pitch. You could say, 'The speaker sounds wondrous', or 'The speaker sounds dismissive.' I take the repetition to mean, roughly, 'But these is the speaker's overall evaluation of the subject.' The stereotypical case is a girl or boy in a tough social situation; and I don't know what countries they do this in, or even how widespread it is in mine. A friend says, "What s/he is doing is no good." You say, "But it's [person's name]." Literally, that doesn't add any information to the debate, which is stereotypically over a decision or resolution. It does facilitate expression (free expression is good), but I think it would have been more productive, informative, fruitful, etc., to leave the last word with the opposition; that is, when the friend says, "What s/he is doing is no good." Period. The facts merit it, and it's merely escapist to withdraw back to the big picture, since it is the small details in the situation that need the concentration and attention. Without context, in writing, 'Two bucks is two bucks' is exactly the same as 'Two bucks is two bucks'. Readers can't hear pitch, and do not have context about fiscal status. Excord, was your tone dismissive, or wondrous? Or a little whiny? Or authoritative? The statement carried no more information than "A square is a square" or "A bachelor is unmarried", and to readers, even lacked the expressive value too. (No .WAV file attached!) From castironpi at gmail.com Sun Dec 21 10:40:25 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 21 Dec 2008 07:40:25 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <015da0a4$0$20656$c3e8da3@news.astraweb.com> <6r6uvbFfb643U5@mid.uni-berlin.de> Message-ID: <9a6cd17c-667e-4ad0-90d9-c09f34dba606@w39g2000prb.googlegroups.com> On Dec 21, 7:34?am, Marc 'BlackJack' Rintsch wrote: > On Sun, 21 Dec 2008 12:45:32 +0000, Duncan Booth wrote: > > You seem to have made an unwarranted assumption, namely that a binary > > operator has to compile to a function with two operands. There is no > > particular reason why this has to always be the case: for example, I > > believe that C# when given several strings to add together optimises > > this into a single call to a concatenation method. > > > Python *could* do something similar if the appropriate opcodes/methods > > supported more than two arguments: > > > a+b+c+d might execute a.__add__(b,c,d) allowing more efficient string > > concatenations or matrix operations, and a%b%c%d might execute as > > a.__mod__(b,c,d). > > But that needs special casing strings and ``%`` in the comiler, because > it might not be always safe to do this on arbitrary objects. ?Only in > cases where the type of `a` is known at compile time and ``a % b`` > returns an object of ``type(a)``. 'x+y' makes no guarantees whatsoever. It could return an object of type(x), type(y), or neither. 'a%b' in the case of strings is just, str.__mod__, returning string. In a+b+c, 'a' gets dibs over what the rest see, so there's no more danger in the multi-ary case, than in binary; and that hasn't stopped us before. You might be confusing the cases of arbitrary operators vs. uniform operators. 'a' does not get dibs in 'a+b*c'; 'b*c' are allowed to carry out their affairs. But in 'a+b+c', 'a*b*c', 'a%b%c', and so on, 'a' has final say on b's and c's behaviors via its return value, so loses nothing by combining such a call. In short, you can force it anyway, so it's syntactic sugar after that. From wuwei23 at gmail.com Mon Dec 1 20:01:35 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 1 Dec 2008 17:01:35 -0800 (PST) Subject: Checking a string against multiple matches References: <99a3a677-a38d-40f5-9a94-a98865150b69@k19g2000yqg.googlegroups.com> Message-ID: <200af09b-adba-4d8f-9ed9-2343030f9718@i24g2000prf.googlegroups.com> On Dec 2, 5:31?am, Aaron Scott wrote: > I was using .index on the > list, but it would return True for strings that contained the search > string rather than match it exactly, leading to false positives in my > code. Are you sure? That doesn't seem like standard behaviour. >>> l = ["one", "two", "three", "four"] >>> l.index('on') Traceback (most recent call last): File "", line 1, in ValueError: list.index(x): x not in list >>> l.index('thre') Traceback (most recent call last): File "", line 1, in ValueError: list.index(x): x not in list The only time I'd expect it to do partial matches is if you were doing string.index(string), rather than list.index(string): >>> "four".index('our') 1 From martin at marcher.name Sat Dec 27 15:55:33 2008 From: martin at marcher.name (Martin) Date: Sat, 27 Dec 2008 21:55:33 +0100 Subject: [2.4.4] creating a datetime.datetime from an XML xs:dateTime In-Reply-To: <18774.36465.346262.883182@montanaro-dyndns-org.local> References: <5fa6c12e0812271208x4baccaedk262e51becb6e2076@mail.gmail.com> <18774.36465.346262.883182@montanaro-dyndns-org.local> Message-ID: <5fa6c12e0812271255l4f4893e8w9f96e9ace73ea50c@mail.gmail.com> Hi, 2008/12/27 : > Not in the standard lib, but you might want to check out the dateutil > package. Its dateutil.parser module does an excellent job parsing a wide > range of time formats. It's a bit weak in the timezone area though. is that http://labix.org/python-dateutil, I'll have a look at it. -- http://soup.alt.delete.co.at http://www.xing.com/profile/Martin_Marcher http://www.linkedin.com/in/martinmarcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From svalbardcolaco at gmail.com Fri Dec 5 03:44:47 2008 From: svalbardcolaco at gmail.com (svalbard colaco) Date: Fri, 5 Dec 2008 14:14:47 +0530 Subject: CONNECTION TIMED OUT ERROR using urllib2 In-Reply-To: <180b672e0812042317v55308ff1x42959d08dfe63bb5@mail.gmail.com> References: <726d283d0812042217w41a0288eg3ee79d4ffdb5ff4b@mail.gmail.com> <180b672e0812042227j12a4d647k84e507dfae77d665@mail.gmail.com> <726d283d0812042236j792f4706v373ca6449861e3e2@mail.gmail.com> <180b672e0812042317v55308ff1x42959d08dfe63bb5@mail.gmail.com> Message-ID: <726d283d0812050044y22eecd02xf541c469c8440f2@mail.gmail.com> Hi I set my http_proxy and now i get the following error *urllib2.HTTPError: HTTP Error 403: Forbidden ( The ISA Server denied the specified Uniform Resource Locator (URL). * what other variables have to be set ? Regards, sv On Fri, Dec 5, 2008 at 12:47 PM, rishi pathak wrote: > Before executing script do > export http_proxy=http://:/ > > > > On Fri, Dec 5, 2008 at 12:06 PM, svalbard colaco > wrote: > >> Hi rishi, >> >> Thanks for ur reply, >> yes i set the following enviroment variables (FC6 platform) >> http_proxy,http_user,http_password >> >> But i get the same error; Can u tell me which other variables i need to >> set or am i going wrong in the syntax of these >> variables? >> >> Regards >> sv >> >> >> On Fri, Dec 5, 2008 at 11:57 AM, rishi pathak wrote: >> >>> Are you sitting behind a proxy. If so then you have to set proxy for http >>> >>> On Fri, Dec 5, 2008 at 11:47 AM, svalbard colaco < >>> svalbardcolaco at gmail.com> wrote: >>> >>>> Hi all >>>> >>>> I have written a small code snippet to open a URL using urllib2 to open >>>> a web page , my python version is 2.4 but i get an urlopen error called >>>> connection timed out >>>> >>>> The following is the code snippet >>>> >>>> *import urllib2 >>>> >>>> f = urllib2.urlopen('http://www.google.com/') >>>> print f.read(100)* >>>> >>>> >>>> where as the same url http://www.google.com/ works through my browser. >>>> >>>> The following is the back trace : >>>> >>>> File "test_url.py", line 3, in ? >>>> f = urllib2.urlopen('http://www.google.com/') >>>> File "/usr/lib/python2.4/urllib2.py", line 130, in urlopen >>>> return _opener.open(url, data) >>>> File "/usr/lib/python2.4/urllib2.py", line 358, in open >>>> response = self._open(req, data) >>>> File "/usr/lib/python2.4/urllib2.py", line 376, in _open >>>> '_open', req) >>>> File "/usr/lib/python2.4/urllib2.py", line 337, in _call_chain >>>> result = func(*args) >>>> File "/usr/lib/python2.4/urllib2.py", line 1021, in http_open >>>> return self.do_open(httplib.HTTPConnection, req) >>>> File "/usr/lib/python2.4/urllib2.py", line 996, in do_open >>>> raise URLError(err) >>>> *urllib2.URLError: >>>> >>>> >>>> Any pointers in this regard will be of great help. >>>> >>>> Thanking you'll in advance. >>>> >>>> Regards, >>>> sv >>>> >>>> >>>> >>>> -- >>>> http://mail.python.org/mailman/listinfo/python-list >>>> >>>> >>> >>> >>> -- >>> Regards-- >>> Rishi Pathak >>> Pune-Maharastra >>> >> >> > > > -- > Regards-- > Rishi Pathak > Pune-Maharastra > -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Sun Dec 21 07:45:32 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Dec 2008 12:45:32 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <015da0a4$0$20656$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Errors should never pass silently, unless explicitly silenced. You > have implicitly silenced the TypeError you get from not having enough > arguments for the first format operation. That means that you will > introduce ambiguity and bugs. > > "%i %i %i %i" % 5 % 3 %7 > > Here I have four slots and only three numbers. Which output did I > expect? > > '%i 5 3 7' > '5 %i 3 7' > '5 3 %i 7' > '5 3 7 %i' > > Or more likely, the three numbers is a mistake, there is supposed to > be a fourth number there somewhere, only now instead of the error > being caught immediately, it won't be discovered until much later. > You seem to have made an unwarranted assumption, namely that a binary operator has to compile to a function with two operands. There is no particular reason why this has to always be the case: for example, I believe that C# when given several strings to add together optimises this into a single call to a concatenation method. Python *could* do something similar if the appropriate opcodes/methods supported more than two arguments: a+b+c+d might execute a.__add__(b,c,d) allowing more efficient string concatenations or matrix operations, and a%b%c%d might execute as a.__mod__(b,c,d). In that alternate universe your example: "%i %i %i %i" % 5 % 3 %7 simply throws "TypeError: not enough arguments for format string", and "%s" % (1,2,3) just converts the tuple as a single argument. It also provides the answer to how you put a percent in the format string (double it) and what happens if a substitution inserts a percent (it doesn't interact with the formatting operators). From skip at pobox.com Mon Dec 29 10:19:58 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 29 Dec 2008 09:19:58 -0600 Subject: multiply each element of a list by a number In-Reply-To: <4958E794.1070704@ncf.ca> References: <4955e7be$0$4066$ba4acef3@news.orange.fr> <49580B2E.8050009@ncf.ca> <4958E794.1070704@ncf.ca> Message-ID: <18776.60062.360057.614861@montanaro-dyndns-org.local> Colin> That's interesting but that's not the Colin> way timeit is documented for Python 2.5: Colin> timeit( [number=1000000]) That's how it works when invoked as a main program using -m. Colin> In spite of the fact that your own data doesn't support the Colin> assertion? Colin> I would have expected numpy to be the clear winner for len > Colin> 1,500. It is. In fact, it's the clear winner well below that. Below I have reorganized the timeit output so the units are the same for all runs (*microseconds* per loop): length numpy pure python 1 11.7 0.698 10 11.7 2.94 100 12.1 24.4 1000 15 224 10000 41 2170 100000 301 22200 -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From Scott.Daniels at Acm.Org Wed Dec 31 14:12:40 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 31 Dec 2008 11:12:40 -0800 Subject: select.select and socket.setblocking In-Reply-To: References: Message-ID: Jean-Paul Calderone wrote: > ... > On a LAN, it's likely that you'll generally get the exact number of bytes > which the sender passed to one call of send (until the sender starts to > pass really huge strings to send, then it'll get split up) just because > the network has lots of capacity compared to the traffic you're putting > on it. However, even on a LAN it's not guaranteed, and on the internet, > it's extremely likely that this won't happen most of the time. I don't mean to rebut your point here,rather to "pile on" with a bit more information. One point I haven't seen mentioned in this discussion is that nodes in the internet that carry the TCP/IP traffic are allowed to, for their own purposes, break large packets up into several smaller packets, and combine several smaller packets into a single larger packet. So, no matter how your TCP/IP packets leave your machine, there is no guarantee they will reach the destination in the same clumps. It is the stream, and not the packets, that is provided by TCP/IP. --Scott David Daniels Scott.Daniels at Acm.Org From Slaunger at gmail.com Tue Dec 9 11:40:53 2008 From: Slaunger at gmail.com (Slaunger) Date: Tue, 9 Dec 2008 08:40:53 -0800 (PST) Subject: Best way to report progress at fixed intervals Message-ID: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> Hi comp.lang.python I am a novice Python 2.5 programmer, who write some cmd line scripts for processing large amounts of data. I would like to have possibility to regularly print out the progress made during the processing, say every 1 seconds, and i am wondering what a proper generic way to do this is. I have created this test example to show the general problem. Running the script gives me the output: Work through all 20 steps reporting progress every 1.0 secs... Work step 0 Work step 1 Work step 2 Work step 3 Work step 4 Processed 4 of 20 Work step 5 Work step 6 Work step 7 Work step 8 Processed 8 of 20 Work step 9 Work step 10 Work step 11 Work step 12 Work step 13 Processed 13 of 20 Work step 14 Work step 15 Work step 16 Work step 17 Processed 17 of 20 Work step 18 Work step 19 Finished working through 20 steps The script that does this is as follows: testregularprogress.py: """ Test module for testing generic ways of displaying progress information at regular intervals. """ import random import threading import time def work(i): """ Dummy process function, which takes a random time in the interval 0.0-0.5 secs to execute """ print "Work step %d" % i time.sleep(0.5 * random.random()) def workAll(verbose=True, max_iter=20, progress_interval=1.0): class _Progress(object): def __init__(self): self.no = 0 self.max = max_iter self.start_timer = verbose def __str__(self): self.start_timer = True # I do not like this appraoch return "Processed %d of %d" % (self.no, self.max) p = _Progress() def report_progress(): print p if verbose: print "Work through all %d steps reporting progress every %3.1f secs..." % \ (max_iter, progress_interval) for i in xrange(max_iter): if p.start_timer : p.start_timer = False # Let the progress instance set the flag timer = threading.Timer(progress_interval, report_progress) timer.start() work(i) p.no = i + 1 # Kill the last timer, which is still active at this time timer.cancel() if verbose: print "Finished working through %d steps" % max_iter if __name__ == "__main__": workAll() Quite frankly, I do not like what I have made! It is a mess, responsibilities are mixed, and it seems overly complicated. But I can't figure out how to do this right. I would therefore like some feedback on this proposed generic "report progress at regular intervals" approach presented here. What could I do better? -- Slaunger From rdcollum at gmail.com Thu Dec 18 14:19:40 2008 From: rdcollum at gmail.com (Roger) Date: Thu, 18 Dec 2008 11:19:40 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <71ede5f0-fd88-4155-9f0d-42d0ad5f57dc@v42g2000yqj.googlegroups.com> <61f45e65-2404-4cc0-9d81-f848c1ba566f@i18g2000prf.googlegroups.com> Message-ID: On Dec 18, 12:49?pm, r wrote: > Maybe someone will chime in with an answer, sorry i could not help. > ponder this, i must... Regardless, thanks for your help! I truly appreciate it. Roger. From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 29 07:23:08 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 29 Dec 2008 13:23:08 +0100 Subject: "return" in def In-Reply-To: <7f340e90-c288-4592-8a4c-b008c24cf62a@q26g2000prq.googlegroups.com> References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <0167cbf7$0$6988$c3e8da3@news.astraweb.com> <676bffeb-4b07-4226-8c14-7da57d94351b@f13g2000yqj.googlegroups.com> <3afba310-dcde-4dc1-825a-7c63b97e2a40@w1g2000prk.googlegroups.com> <495897c4$0$8481$426a74cc@news.free.fr> <7f340e90-c288-4592-8a4c-b008c24cf62a@q26g2000prq.googlegroups.com> Message-ID: <4958c12b$0$16065$426a34cc@news.free.fr> John Machin a ?crit : > On Dec 29, 8:26 pm, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: >> John Machin a ?crit : (snip) >>> Please don't. Follow MRAB's advice, with the corollary that a >>> generator is forced by the compiler to be a "procedure" in MRAB's >>> terminology. >> I fail to see any *practical* difference between MRAB's and Steven's >> POVs. In both cases, it boils down to >> - don't use a bare return at the end of a def statement's body, >> - either use only bare returns ('procedure') or explicitely return None >> ('function') > > Steven's treatment was somewhat discursive, and didn't explicitly > mention the 'procedure' possibility. In fact, this sentence "if you > have a function with early exits, and you need to make the intent of > the function clear, explicitly return None." would if applied to a > 'procedure' cause a stylistic horror as bad as a bare return at the > end of the def. Ok. You're right. From yinon.me at gmail.com Tue Dec 16 09:32:20 2008 From: yinon.me at gmail.com (Yinon Ehrlich) Date: Tue, 16 Dec 2008 06:32:20 -0800 (PST) Subject: os.environ.get('SSH_ORIGINAL_COMMAND') returns None References: Message-ID: On Dec 15, 8:51?pm, Tzury Bar Yochay wrote: > Trying to follow a technique found at bzr I did the following > > added to ~/.ssh/authorized_keys the command="my_parder" parameter > which point to a python script file named 'my_parser' and located in / > usr/local/bin ?(file was chmoded as 777) > > in that script file '/usr/local/bin/my_parser' I got the following > lines: > > #!/usr/bin/env python > import os > print os.environ.get('SSH_ORIGINAL_COMMAND', None) > > When trying to ssh e.g. 'ssh localhost' > I get None on the terminal and then the connection is closed. > You should define SSH_ORIGINAL_COMMAND in environment of the calling shell/application. From andreas at kostyrka.org Fri Dec 12 12:18:33 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 12 Dec 2008 18:18:33 +0100 Subject: Python is slow In-Reply-To: <8156b37b-d1f6-4142-ad6e-8488c95b6592@z28g2000prd.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> <8156b37b-d1f6-4142-ad6e-8488c95b6592@z28g2000prd.googlegroups.com> Message-ID: <20081212171833.GC25004@hell.kostyrka.org> On Fri, Dec 12, 2008 at 06:17:43AM -0800, sturlamolden wrote: > None of those projects addresses inefficacies in the CPython > interpreter, except for psyco - which died of an overdose PyPy. Bullshit. All that discussion about performance forgets that performance is a function of the whole system, not the language. Worse you can measure it really badly. E.g. it's relative simple to compare CPython versus IronPython versus Jython. For a given benchmark program. As programs do not trivially translate from language A to language B, nor does fluency in language A make you automatically fluent in language B after learning the syntax. > > PyPy is interesting if they ever will be able to produce something > useful. They have yet to prove that. Even if PyPy can come up with a > Python JIT, they will still be decades behind the technologies of > Strongtalk and Java. That is the problem with reinventing the wheel > all over again. Well, it's reinventing the wheel. The problem that Java is a different kind of wheel (boxed vs. unboxed objects, plus more static compile time bindings), Smalltalk is also different (e.g. multiple inheritence), so you need to have a specific toolbox for the wheel, sorry. Keeping and enhancing the tribal wisdom about toolbox design is what a subtribe of the Computer Scientists do. Btw, Psyco is not a JIT like most JVMs had them, it's a specializing compiler. JVM JITs traditionally speeded up the unboxed data type operations. Psyco does something comparable, but it has to specialize first on data types. The end effect is similiar, but the background of what happens is quite different. > > Not to forget LLVM and Parrot which also will support Python > frontends. When they do, they'll do. There have flown quite a bit of Python version since the time that it was announced that Parrot will have a Python frontend. Andreas From jon at ffconsultancy.com Wed Dec 10 17:23:54 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Wed, 10 Dec 2008 22:23:54 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <40b4b23f-c1eb-4ac5-bb42-e0f6276e97bf@r37g2000prr.googlegroups.com> Message-ID: Xah Lee wrote: > On Dec 10, 12:37 pm, w_a_x_... at yahoo.com wrote: >> Ruby: >> >> def norm a >> s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) >> a.map{|x| x/s} >> end > > I don't know ruby, but i tried to run it and it does not work. > > #ruby > def norm a > s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) > a.map{|x| x/s} > end > > v = [3,4] > > p norm(v) # returns [0.6, 0.8] That is the correct answer. > The correct result for that input would be 5. No, you're confusing normalization with length. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From phd at phd.pp.ru Mon Dec 1 08:48:24 2008 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 1 Dec 2008 16:48:24 +0300 Subject: SQLObject 0.9.8 Message-ID: <20081201134824.GD19187@phd.pp.ru> Hello! I'm pleased to announce version 0.9.8, a minor bug fix release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.9.8 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.9.7 ---------------- * Changed interpretation of strings in the DB URI for boolean parameters: '0', 'no', 'off' and 'false' are now interpreted as False. * Fixed a bug with incorrect handling of calls like connectionForURI(dburi, cache=False) when dburi already contains some parameters in the URI. * Convert decimal.to_eng_string() to str to work around a bug in Python 2.5.2; see http://mail.python.org/pipermail/python-dev/2008-March/078189.html * Added test_default_style.py. * Fixed a minor bug in SQLiteConnection that fails to parse Enum columns. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From gagsl-py2 at yahoo.com.ar Sat Dec 27 21:39:54 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 28 Dec 2008 00:39:54 -0200 Subject: how to make a class to get all forms and input fields from webpage References: Message-ID: En Sat, 27 Dec 2008 21:54:02 -0200, alex goretoy escribi?: > How do I make a class for retrieving all forms and input fields on a web > page. Meaning, form name, form url,all input fields, > text,textarea,select,etc...I have something currently and it kinda I'd use BeautifulSoup: http://pypi.python.org/pypi/BeautifulSoup/ -- Gabriel Genellina From rdmurray at bitdance.com Wed Dec 17 10:51:53 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Wed, 17 Dec 2008 15:51:53 +0000 (UTC) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> <0d9ea7cc-b5fb-4edb-be32-490aae9e7204@b41g2000pra.googlegroups.com> <0de3a7bf-a4c4-4103-a4e0-44313405fa94@z28g2000prd.googlegroups.com> Message-ID: Quoth John Machin : > On Dec 18, 1:28 am, aka wrote: > > @expose(allow_json=True) > > Means what? Does what? > Does the problem still happen without that? Means what he's posting is not a standalone script :) He says it's part of his turbogears ap. @expose says that this method is callable by name from a URL, and allow_json means it can be called with a parameter requesting a json formatted response instead of html. > Funny, the indentation changed there --- for the very last time, is > that the actual code of a standalone script that reproduces the > problem? Alex, I would strongly suggest that you move your code out into a standalone script and debug it there (you'll get more help from this group if you do, for one thing!). After you get it working standalone you can incorporate it back into your Turbogears ap. --RDM From bdesth.quelquechose at free.quelquepart.fr Sun Dec 7 13:18:49 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 07 Dec 2008 19:18:49 +0100 Subject: Guido's new method definition idea In-Reply-To: <493bba28$0$8283$426a74cc@news.free.fr> References: <493abe2e$0$15998$426a34cc@news.free.fr> <62bcfe49-bee6-4348-8ec9-8ab85132c8ff@40g2000prx.googlegroups.com> <493bba28$0$8283$426a74cc@news.free.fr> Message-ID: <493c2141$0$4942$426a34cc@news.free.fr> News123 a ?crit : > Lie wrote: >> On Dec 7, 1:02 am, News123 wrote: >>> What would be interesting would be some syntactical sugar to get rid of >>> the 'self' (at least in the code body). This has been debated to hell and back. And it's *not* going to happen. >>> example: >>> class C: >>> class_elements a,b,c,d >>> >>> def method(self,arg): >>> global d >>> a,b,c = arg[0..3] >>> d = a + b >>> self.e = a + d >>> >> Nah, that would make it not explicit. Explicit here also means that to >> refer to self's a, we need to explicitly refer to self. > > Well being explicit when trying to suggest an implicit syntax (in order > to reduce typing) is a little difficult ;-) > > Though you're right my main goal is not being implicit but would be > reducing typing and have shorter source code lines. then use 's' instead of 'self'. > If 'global '' is accepted inside a def, then moving > 'class_elements ' inside the def could be acceptable as well self.x is an instance attribute, not a class attribute. Aslo, the def statement creates a function, not a method, so the notion of "class_element" or however you name it is totally irrelevant here. From jerry.carl.mi at gmail.com Sun Dec 28 13:16:29 2008 From: jerry.carl.mi at gmail.com (jerry.carl.mi at gmail.com) Date: Sun, 28 Dec 2008 10:16:29 -0800 (PST) Subject: math module for Decimals References: <41937dc9-4b67-43b5-9eab-6f8c851474cf@p2g2000prn.googlegroups.com> <0896c2d8-78ff-489e-801d-abef957601d0@s9g2000prg.googlegroups.com> <59c08a51-da39-467b-9576-fa0cc1db3207@i18g2000prf.googlegroups.com> Message-ID: <1fb93396-6a0c-435d-9115-859df2f32fbc@g3g2000pre.googlegroups.com> mpmath... wow... just did what i needed :-) Thanks, Mark! Hopefully i did not waste too much of your time... and perhaps this discussion will send other lost sheeps in the right direction. (Still, it would make sense to have the goniometric functions in decimal.) From eric at ericaro.net Fri Dec 5 05:56:48 2008 From: eric at ericaro.net (eric) Date: Fri, 5 Dec 2008 02:56:48 -0800 (PST) Subject: simplest way to strip a comment from the end of a line? References: <52e3f2a9-6fb1-42ef-9871-c904ede5520e@t3g2000yqa.googlegroups.com> <9cdc9039-6b7b-42fb-b261-4ad721ccd1d4@j39g2000yqn.googlegroups.com> Message-ID: <340697a3-3f17-477a-aea2-c85344da93d4@k41g2000yqn.googlegroups.com> On Dec 4, 11:35?pm, Paul McGuire wrote: > Yowza! ?My eyes glaze over when I see re's like "r'(?m)^(?P.*? > (".*?".*?)*)(?:#.*?)?$"! > yeah, I know ... :( ( I love complicated regexp ... it's like a puzzle game for me) > from pyparsing import quotedString, Suppress, restOfLine > > comment = Suppress('#' + restOfLine) > recognizer = quotedString | comment > > for t in tests: > ? ? print t > ? ? print recognizer.transformString(t) > ? ? print > > Prints: > > this is a test 1 > this is a test 1 > > this is a test 2 #with a comment > this is a test 2 > > this is a '#gnarlier' test #with a comment > this is a '#gnarlier' test > > this is a "#gnarlier" test #with a comment > this is a "#gnarlier" test > > For some added fun, add a parse action to quoted strings, to know when > we've really done something interesting: > > def detectGnarliness(tokens): > ? ? if '#' in tokens[0]: > ? ? ? ? print "Ooooh, how gnarly! ->", tokens[0] > quotedString.setParseAction(detectGnarliness) > > Now our output becomes: > > this is a test 1 > this is a test 1 > > this is a test 2 #with a comment > this is a test 2 > > this is a '#gnarlier' test #with a comment > Ooooh, how gnarly! -> '#gnarlier' > this is a '#gnarlier' test > > this is a "#gnarlier" test #with a comment > Ooooh, how gnarly! -> "#gnarlier" > this is a "#gnarlier" test > > -- Paul I didn't knew pyparsing. It's amazing ! thanks From iainking at gmail.com Thu Dec 4 07:31:31 2008 From: iainking at gmail.com (Iain King) Date: Thu, 4 Dec 2008 04:31:31 -0800 (PST) Subject: RELEASED Python 3.0 final References: Message-ID: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> On Dec 4, 1:51 am, Barry Warsaw wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > On behalf of the Python development team and the Python community, I > am happy to announce the release of Python 3.0 final. > > Python 3.0 (a.k.a. "Python 3000" or "Py3k") represents a major > milestone in Python's history, and was nearly three years in the > making. This is a new version of the language that is incompatible > with the 2.x line of releases, while remaining true to BDFL Guido van > Rossum's vision. Some things you will notice include: > > * Fixes to many old language warts > * Removal of long deprecated features and redundant syntax > * Improvements in, and a reorganization of, the standard library > * Changes to the details of how built-in objects like strings and > dicts work > * ...and many more new features > > While these changes were made without concern for backward > compatibility, Python 3.0 still remains very much "Pythonic". > > We are confident that Python 3.0 is of the same high quality as our > previous releases, such as the recently announced Python 2.6. We will > continue to support and develop both Python 3 and Python 2 for the > foreseeable future, and you can safely choose either version (or both) > to use in your projects. Which you choose depends on your own needs > and the availability of third-party packages that you depend on. Some > other things to consider: > > * Python 3 has a single Unicode string type; there are no more 8-bit > strings > * The C API has changed considerably in Python 3.0 and third-party > extension modules you rely on may not yet be ported > * Tools are available in both Python 2.6 and 3.0 to help you migrate > your code > * Python 2.6 is backward compatible with earlier Python 2.x releases > > We encourage you to participate in Python 3.0's development process by > joining its mailing list: > > http://mail.python.org/mailman/listinfo/python-3000 > > If you find things in Python 3.0 that are broken or incorrect, please > submit bug reports at: > > http://bugs.python.org/ > > For more information, links to documentation, and downloadable > distributions, see the Python 3.0 website: > > http://www.python.org/download/releases/3.0/ > > Enjoy, > - -Barry > > Barry Warsaw > ba... at python.org > Python 2.6/3.0 Release Manager > (on behalf of the entire python-dev team) > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.9 (Darwin) > > iQCVAwUBSTc3pXEjvBPtnXfVAQI69wP/dPHh8IL3GxziEV9QzlveKG+KyZb2X16x > fxJnTCiXAbiAhT5C+m43OEnbF1PJgMDKtcZ5b7aQb4TQ0mJxISTQh0RfLCpArmlo > tdTbzCLnh13KzB+3sUHCx+MeQNXERoWDV8hLz+4Ae71UsuUGynhtyP7ZJMJDue8j > so2gv3fOMSs= > =vkiy > -----END PGP SIGNATURE----- Props. I just looked through the What's New and the change log, but I couldn't find the answer to something: has any change been made to how tabs and spaces are used as indentation? Can they still be (inadvisably) mixed in one file? Or, more extremely, has one or the other been abolished? Iain From roy at panix.com Thu Dec 4 15:44:57 2008 From: roy at panix.com (Roy Smith) Date: Thu, 4 Dec 2008 12:44:57 -0800 (PST) Subject: Checking if an int fits in 32 bits? References: <6pqt56F9bvoiU1@mid.individual.net> Message-ID: On Dec 4, 3:33?pm, Thomas Heller wrote: > Roy Smith schrieb: > > > I'm working with marshaling data over a binary wire protocol. ?I'm > > using struct.pack() to handle the low-level encoding of ints. ?One of > > the things I need to do is make sure an int can be represented in 4 > > bytes. > You could try something like this: > > import ctypes > def int_fits_in_32bit(value): ? > ? return ctypes.c_int32(value) == value Good idea! It turns out you've got to do types.c_int32(value).value() == value, but that does indeed seem to do exactly what I want. Thanks. From steve at holdenweb.com Mon Dec 22 11:57:27 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 22 Dec 2008 11:57:27 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> Message-ID: walterbyrd wrote: > On Dec 21, 12:28 pm, Bruno Desthuilliers > wrote: >> Strange enough, >> no one seems to complain about PHP or Ruby's performances... > > A few years back, there was a certain amount of chest thumping, when > python/django easily beat ror in a benchmark test. Now that ruby is > faster, I guess speed is no big issue. > A fairly limited amount of chest-thumping, as I remember it. > By the same reasoning, python advocates used to sneer at php because > php constantly broke backward compatibility. Now that python does it, > breaking backward compatibility is no big deal. I guess unicode > support was not that important, until python caught up to perl. > Python advocates shouldn't sneer at other languages. There's no need. If you like Python, use it because of its merits, not because it's better than something else. Having said which, I must say that Python's "breaking backward incompatibility" is of a somewhat different nature than (say) Visual Basic's. It was known about for *several years* in advance, even before Guido went to work for Google and finally had time to get the work underway. Also it's defined to be a singular event, not a continuous set of creeping changes. Python 3's updated syntax now constrains the developers in the same way that Python 2's used to. I wouldn't say that could remotely be described as "constantly" breaking backward compatibility. > I guess, the way it works is: you first assume that python is > superior, then you figure out why. > That's the way some people operate, but by no means all. Is it the language or the people that are pissing you off. You sound a little discontented for a c.l.py reader. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 20:54:43 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2008 01:54:43 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> <88ff7c46-2b23-49e4-865e-781d23433799@l33g2000pri.googlegroups.com> Message-ID: <015c47b6$0$20656$c3e8da3@news.astraweb.com> On Fri, 19 Dec 2008 10:44:25 -0800, r wrote: > And lets not forget Python forcing of indention, that is Pythons > greatest strength! Oh "r", haven't you heard? Python has braces too. Just start your code with from __future__ import braces and see what happens. -- Steven From cournape at gmail.com Sun Dec 21 03:56:42 2008 From: cournape at gmail.com (David Cournapeau) Date: Sun, 21 Dec 2008 17:56:42 +0900 Subject: Python for amd64 and mingw-w64 In-Reply-To: <494B3F75.10104@v.loewis.de> References: <494B3F75.10104@v.loewis.de> Message-ID: <5b8d13220812210056r58a01f53h585d59d0bf81e663@mail.gmail.com> On Fri, Dec 19, 2008 at 3:30 PM, "Martin v. L?wis" wrote: >> - Any extension requires the MS_WIN64 to be defined, but this symbol >> is only defined for MS compiler (in PC/pyport.h). > > Why do you say that? It is only defined when _WIN64 is defined; this > has nothing to do with a MS compiler. > >> Shouldn't it be >> defined independantly of the compiler ? > > You mean, completely unconditional? Definitely not, it should only > be defined when you are compiling for 64-bit mode. I put a more detailed explanation of the problem with an example + a patch on the bug tracker: http://bugs.python.org/issue4709 This is the only problem on python side of things to make extensions buildable on windows x64 (all the other problems I have encountered so far to make numpy build with mingw-w64 are numpy's or mingw-w64). David From geekmail at usenot.de Sun Dec 7 14:47:42 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sun, 7 Dec 2008 20:47:42 +0100 Subject: Importing the re module fails References: <20081207202326.4b5ab73d@usenot.de> <6q2muqFahsfnU1@mid.uni-berlin.de> Message-ID: <20081207204742.67ca7ee2@usenot.de> On Sun, 07 Dec 2008 20:36:58 +0100 "Diez B. Roggisch" wrote: > Andreas Waldenburger schrieb: > > This is a little puzzling. > > > > > > Using ipython: > > > > [wildemar at localhost Logstuff]$ ipython > > Python 2.5.2 (r252:60911, Sep 30 2008, 15:41:38) > > Type "copyright", "credits" or "license" for more information. > > > > [snip ipython help message] > > > > In [1]: import re > > > > > > This works fine. But with the regular python interpreter I get this: > > > > [wildemar at localhost Logstuff]$ python > > Python 2.5.2 (r252:60911, Sep 30 2008, 15:41:38) > > [GCC 4.3.2 20080917 (Red Hat 4.3.2-4)] on linux2 > > Type "help", "copyright", "credits" or "license" for more > > information. > > >>> import re > > Traceback (most recent call last): > > File "", line 1, in > > File "/usr/lib/python2.5/re.py", line 10, in > > # AB (info at pythonware.com). > > AttributeError: 'module' object has no attribute 'compile' > > > > > > What gives? Has Fedora-10 botched python or does anybody else have > > that problem es well? > > In my re.py module on line 10, there is no import - it has way to > much comments on the module beginning. > > So - how does your /usr/lib/python2.5/re.py look like? Just like the error message says: " # AB (info at pythonware.com)." on line ten. That's what confused me so much (among being confused anyway). > And what > about some modules lying around (potentially *pycs) that mask system > modules? > Bullseye. I had a re.pyc in the current directory, because I stupidly created a testbed called re.py. Realizing my folly I renamed it to something else, while forgetting to delete the already created re.pyc. Thanks, and sorry for the noise. (I do wonder why ipython didn't complain, though.) /W -- My real email address is constructed by swapping the domain with the recipient (local part). From istvan.albert at gmail.com Fri Dec 5 13:54:39 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Fri, 5 Dec 2008 10:54:39 -0800 (PST) Subject: slow Python 3.0 write performance? Message-ID: Could someone run the code below on both Python 2.5 and 3.0 For me (on Windows) it runs over 7 times slower with Python 3.0 import time lo, hi, step = 10**5, 10**6, 10**5 # writes increasingly more lines to a file for N in range(lo, hi, step): fp = open('foodata.txt', 'wt') start = time.time() for i in range( N ): fp.write( '%s\n' % i) fp.close() stop = time.time() print ( "%s\t%s" % (N, stop-start) ) From geekmail at usenot.de Fri Dec 5 11:40:26 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Fri, 5 Dec 2008 17:40:26 +0100 Subject: Whitespace in Python (3) [was: RELEASED Python 3.0 final] References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> <20081205161725.3f35222b@usenot.de> <534215df-0ba3-471a-b4d4-e495a3e4daf7@w35g2000yqm.googlegroups.com> Message-ID: <20081205174026.17b24a9a@usenot.de> On Fri, 5 Dec 2008 07:46:02 -0800 (PST) bearophileHUGS at lycos.com wrote: > Andreas Waldenburger: > > My point is: If you mix tabs and spaces in a way that breaks code, > > you'll find out pretty easily, because your program will not work. > > - Most newbies don't know that. > - Sometimes it may produce wrong results. > - And even if you are an expert when you go changing a little a source > code that mixes tabs and spaces you usually break the code. > Is this enough for you? > No. While you are right on all accounts, forcing uniformity would still interfere with (some) people's coding styles, "wrong" as they might be. Python is not Gnome. Maybe having Python issue warnings for inconsistent whitespace per default might be a good idea. But that's about as far as I would go. /W -- My real email address is constructed by swapping the domain with the recipient (local part). From steve at REMOVE-THIS-cybersource.com.au Sat Dec 6 10:50:01 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Dec 2008 15:50:01 GMT Subject: Learning Python now coming from Perl References: Message-ID: <014a96e0$0$20670$c3e8da3@news.astraweb.com> On Sat, 06 Dec 2008 08:50:20 -0500, Roy Smith wrote: > For your first > project, pick something that's small enough that you think you could > tackle it in under 50 lines of Perl. Is there anything which *can't* be written in under 50 lines of Perl? :-) > One of the very first things you'll probably discover that's different > between Perl and Python is how they handle string pattern matching. In > Perl, it's a built in part of the language syntax. In Python, you use > the re module. The regular expressions themselves are the same, but > the mechanism you use to apply them to input text is quite different. Also, Perl REs are faster than Python REs, or so I'm told. Between the speed and the convenience, Perl programmers tend to use RE's for everything they can. Python programmers tend to use REs only for problems that *should* be solved with REs rather than *can* be solved with a RE. Well, I say "tend", but in truth we get our fair share of questions like "Hi, how do I factorize a 20 digit number with a regular expression?" too. Probably the biggest difference is that in Python, you always refer to objects the same way, regardless of what sort of data they contain. Regardless of whether x is a scalar or a vector, you always call it just plain x. -- Steven From grante at visi.com Wed Dec 31 11:34:21 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 31 Dec 2008 10:34:21 -0600 Subject: Graphics Library with Standard Interaction Features, 2D and 3D References: <69c3eca8-5e17-49fb-8354-5fdc0bd73f9a@r15g2000prd.googlegroups.com> Message-ID: On 2008-12-31, Benjamin Blundell wrote: > Hi all. I've had a look around the forums and the we and im looking > for a library (or a set of libraries) for dealing with Visualisation > and Interaction in Python. Have you looked at VTK? http://www.vtk.org/ I've only used some of the numerical stuff (rather than the visualization stuff). The parts I've used have a rather screwy, overly complex API because it's a thinly wrapped C++ library. But, it appears to be quite powerful and well documented. http://cens.ioc.ee/projects/pyvtk/ http://www.imaging.robarts.ca/~dgobbi/vtk/vtkpython.html -- Grant From excord80 at gmail.com Tue Dec 9 22:48:10 2008 From: excord80 at gmail.com (excord80 at gmail.com) Date: Tue, 9 Dec 2008 19:48:10 -0800 (PST) Subject: How do I manually uninstall setuptools (installed by egg)? References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> <375bd56a-d92b-4d33-bf70-5bea630a376a@q30g2000vbn.googlegroups.com> Message-ID: On Dec 9, 10:29?pm, "Chris Rebert" wrote: > On Tue, Dec 9, 2008 at 7:16 PM, ? wrote: > > On Dec 9, 10:04 pm, "Chris Rebert" wrote: > >> So, why do you think apt and not setuptools is The Right Way(tm)? > > > I like to keep > 1 Python on my computer. > > Ah, now I get it. I had no idea setuptools could install Python > *itself* until I checked just now. That's kinda neat, but mostly > silly, because, as you point out, management of Python itself is much > better left to the platform's package manager. > Not sure what you mean, Chris. I install my own Python using the usual procedure (``./configure -- prefix=/home/me/opt/py-..; make; make install``). Never heard of using setuptools (``easy_install``?) to install Python itself. Sounds kooky. :) Anyway, the direction I'm heading is to try and use setuptools *less*. It seems like it might be too complicated for me. And, I notice that the mailing list for it (distutils-sig, if that's the right one) is loaded with questions on how to use it properly, so maybe I'm not alone. From febaen at gmail.com Mon Dec 15 04:06:51 2008 From: febaen at gmail.com (feba) Date: Mon, 15 Dec 2008 01:06:51 -0800 (PST) Subject: Need help improving number guessing game References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> Message-ID: >Seems ok. You may want to use arguments with default values for a and b >(and possibly to use more meaningfull names): I changed it to minr and maxr. Mini is fine, but I can't name a variable maxi unless I have a good feminine hygiene joke to use with it. I don't see the aim of your changes to setup(). I can kinda understand checking to make sure that you didn't make the minimum higher than the maximum, but I think where you put minr/maxr would make it use the same minr/maxr as the end of the previous game, wouldn't it? >Minor point for a short program, but still good practice : use >constants. IE : I had done this initially, but it seemed wasteful and needlessly confusing in this situation. >I assume 'p1sc' means "player_1_score" ? >If so, you may want to use a dict for scores: I don't really understand dicts yet; actually, the tutorial I'm following (http://www.briggs.net.nz/log/writing/snake-wrangling-for- kids/ , designed for tweens, but other than the pointless anecdote and joke here and there, I've found it a very good guide) doesn't even seem to mention them, from a search of the pdf. Actually, apparently I stopped and started working on this just before the chapter on functions and modules. I'll look into that later on, but for now I'm pretty happy with how it works. >Is it really necessary to WRITE THIS IN ALL UPPERS ?-) If you didn't notice, in the original it was "CONGLATURATIONS". I could also make a "VIDEO GAME BAND. Heavy Metal's Not Dead." joke here, but I'm afraid a disappointingly small amount of people will get it. >Python has proper booleans too Yeah, I had those initially too, but "play = True" was causing trouble for some reason when I copy/pasted it into IDLE to try to troubleshoot, so I changed it to 1. I'll probably change it back later. >You should either put this in it's own function (could be named 'main'), >or at least "protect" it with an "if __name__ == '__main__':" test. Could you go into a bit more detail on this? I don't understand what should be its own function, nor do I understand what that line would do or how to use it. James, could you work that into a section of what I have to make it a bit easier to understand? From philip at semanchuk.com Sun Dec 14 10:07:36 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Sun, 14 Dec 2008 10:07:36 -0500 Subject: changing string encoding to different charset? In-Reply-To: <4c0a037d0812140621j5d4f4d47mb4a3097586bacac5@mail.gmail.com> References: <4c0a037d0812140621j5d4f4d47mb4a3097586bacac5@mail.gmail.com> Message-ID: <4D15DF85-C6F6-40CC-AF5D-EF09E8A72E63@semanchuk.com> On Dec 14, 2008, at 9:21 AM, Daniel Woodhouse wrote: > Is it possible to re-encode a string to a different character set in > python? To be more specific, I want to change a text file encoded in > windows-1251 to UTF-8. > I've tried using string.encode, but get the error: > UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position > 0: > ordinal not in range(128) Without seeing your code, I can't be sure, but I suspect that first you need to decode the file to Unicode. # Untested -- s = file("in.txt").read() s = s.decode("win-1251") # Might be "cp1251" instead assert(isinstance(s, unicode)) s = s.encode("utf-8") file("out.txt", "w").write(s) From martin at v.loewis.de Sat Dec 13 23:46:58 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 14 Dec 2008 05:46:58 +0100 Subject: Python 3.0 crashes displaying Unicode at interactive prompt In-Reply-To: References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> <49443531.5050304@v.loewis.de> Message-ID: <49448FC2.6030306@v.loewis.de> > "Sure" as in "sure, it was not intended behaviour"? It was intended behavior, and still is in 3.0. >> This behavior has not changed. It still uses repr(). >> >> Of course, the string type has changed in 3.0, and now uses a different >> definition of repr. > > So was the above-reported non-crash consequence of the change of > definition of repr intended? Yes. If you want a display that is guaranteed to work on your terminal, use the ascii() builtin function. py> x = '\u9876' py> ascii(x) "'\\u9876'" py> print(ascii(x)) '\u9876' Regards, Martin From davidgshi at yahoo.co.uk Wed Dec 3 13:20:27 2008 From: davidgshi at yahoo.co.uk (David Shi) Date: Wed, 3 Dec 2008 18:20:27 +0000 (GMT) Subject: Python calling COM compliant .dll Message-ID: <740322.52556.qm@web26308.mail.ukl.yahoo.com> Hello, there. ? I am looking for a concise working example of Python script calling COM compliant .dll. ? Regards. ? David -------------- next part -------------- An HTML attachment was scrubbed... URL: From invalid at invalid Tue Dec 9 10:52:52 2008 From: invalid at invalid (Grant Edwards) Date: Tue, 09 Dec 2008 09:52:52 -0600 Subject: how to get a beep, OS independent ? References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> <6q6jf8Fau4iiU2@mid.individual.net> Message-ID: On 2008-12-09, greg wrote: > Duncan Booth wrote: > >> If I'm logged in to one of my servers in a large datacentre >> then I don't what that system to beep as that would be pretty >> useless. > > It also might cause the datacentre operators some > consternation when one of their servers starts mysteriously > beeping... If they can hear it. Those tiny fans they put in rack-mount stuff are awfully loud. -- Grant Edwards grante Yow! Where do your SOCKS at go when you lose them in visi.com th' WASHER? From walterbyrd at iname.com Fri Dec 19 12:16:19 2008 From: walterbyrd at iname.com (walterbyrd) Date: Fri, 19 Dec 2008 09:16:19 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: On Dec 19, 9:13?am, "Giampaolo Rodola'" wrote: > You can use the old 2.x syntax also in Python 3.x: Yeah, but it's deprecated, and - as I understand it - may be removed completely in future versions. Also, in the future, if you are working with code from another developer, it's likely that developer will use the new format. I suppose you can use both - but what an awful mess that would be. It seems to me that 3.0 is changing a lot of non-problems. And it's going to be slower to boot. From geekmail at usenot.de Thu Dec 11 12:07:51 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Thu, 11 Dec 2008 18:07:51 +0100 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <87r64f9sma.fsf@rudin.co.uk> Message-ID: <20081211180751.4139f2ec@usenot.de> On Thu, 11 Dec 2008 05:40:45 +0000 Paul Rudin wrote: > "Dotan Cohen" writes: > > > 2008/12/10 : > >> Ruby: > >> > >> def norm a > >> s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) > >> a.map{|x| x/s} > >> end > > > > If someone doesn't counter with a Python one-liner then I'm going to > > port that to brainfuck. > > from numpy.linalg import norm > > :) This is one line of Python code alright, but it's not a "one-liner" in the "computes the a normalized vector"-sense (which was the original challenge, if there ever was one). If anything, you are now ready to compute the *norm* of a vector in a subseqent line. (Or, if you must, after a semicolon on the same line.) :) /W -- My real email address is constructed by swapping the domain with the recipient (local part). From google at mrabarnett.plus.com Sat Dec 13 22:09:08 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 14 Dec 2008 03:09:08 +0000 Subject: subprocess to C program In-Reply-To: <36656830-63a8-479c-8c46-525f2b55eeea@z28g2000prd.googlegroups.com> References: <0ebd59c5-95a1-42d4-b597-d1c248490b8e@y1g2000pra.googlegroups.com> <8MidneyhDfIG-9nUnZ2dnUVZ_uadnZ2d@posted.visi> <36656830-63a8-479c-8c46-525f2b55eeea@z28g2000prd.googlegroups.com> Message-ID: <494478D4.40201@mrabarnett.plus.com> Aaron Brady wrote: > On Dec 13, 7:51 pm, Grant Edwards wrote: >> On 2008-12-14, MRAB wrote: >> >> >> >>>> I am writing a C process and I want to read data from a file that I >>>> write to in Python. I'm creating a pipe in Python, passing it to the >>>> C process, and calling '_read'. It gives me error 9, bad file number. > snip >>>> meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9. I want 'ct' >>>> to be 11 at this point. Thanks in advance. >>> It looks like the ids aren't system global. >> They certainly aren't in Unix: Their a property of the process. >> >> -- >> Grant > > I'm not on Unix. It has to be possible somehow. Do I need to set > permissions on the IDs? Are Stdin and Stdout my only options? Or > does Popen prevent sharing IDs somehow? > You'd be better off using sockets. From exarkun at divmod.com Fri Dec 19 12:36:47 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 19 Dec 2008 12:36:47 -0500 Subject: IMAP: How to implement GMail-like threaded conversations view In-Reply-To: Message-ID: <20081219173647.20272.584484393.divmod.quotient.23072@ohm> On Fri, 19 Dec 2008 08:47:18 -0800 (PST), Martin wrote: >Currently I am trying to get used to Python's imaplib and email >modules. >I'like to create a webmail client simmilar to GMail. I'd suggest using Twisted's IMAP4 client. It's somewhat easier to use than Python's imaplib because it does much more parsing of IMAP4's complex syntax for you. It will also be easier to do IMAP4 and HTTP simultaneously if you're using Twisted. Twisted won't help with the threading feature you want to implement though, it lets you use the email package if you want to examine the structure of the messages you retrieve. Jean-Paul From senthilkas at gmail.com Mon Dec 8 13:42:30 2008 From: senthilkas at gmail.com (Senthil Kumar) Date: Mon, 8 Dec 2008 10:42:30 -0800 (PST) Subject: Catching Python exceptions in C Message-ID: Hi Pythoneers ! Can somebody give a quick solution? I am trying to raise exceptions in python and trying to handle it in C. I am able to raise exceptions successfully. However could not catch those in C. I am using the following function to run the python from C: Pyrun_SimpleString(). After the exception is raised, I am checking PyErr_Occurred(). It always returns NULL, and I cannot catch the exception. Pls help me a way out. Thanx in advance ! From Eric_Dexter at msn.com Mon Dec 1 03:41:40 2008 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Mon, 1 Dec 2008 00:41:40 -0800 (PST) Subject: tkinter question References: <538f4349-02a1-4c2b-b892-a01f1f48cb5b@l64g2000hse.googlegroups.com> Message-ID: On Oct 26, 7:02?am, "Chuckk Hubbard" wrote: > Hello. > How about this? ?I changed the if statements so the coordinates are > always updated, but only changed if within the right limits, otherwise > updated to the existing value. ?Now if you drag outside the limits of > one dimension, it still moves in the other dimension. ?Not sure if > that's what you want. ?I'm amazed that this can be so simple, I came > up with an intricate system for my app, not realizing I could bind > events to canvas items! > BTW, I've never come across csoundroutines, can you give me a synopsis > of what it's for? ?I'm using thePythonCsoundAPI. ?This is why I > commented out all the references to csoundroutines, I don't have it > installed at the moment. > -Chuckk > > #!/usr/bin/python > from Tkinter import * > #import csoundroutines as cs > > root = Tk() > > global canv > xx = {} > > def makeFrame(root): > ? global canv > # ?test = cs.csdInstrumentlist3('bay-at-night.csd') > ? canv = Canvas (root, height = 200, width = 350) > > # ?for i in range (0, len(test.instr_number)): > ? for i in range (0, 4): > # ? ?canv.create_text(10, i *10, text=str(test.instr_number[i]) + > ? ? canv.create_text(10, i *10, text=str(i) + > '...', tags=('movable')) > ? ? xx[i] = canv.tag_bind('movable', '', slide) #B1-motion > is a drag with left button down > ? ? canv.pack() > > def slide (event): > ? ''' > ? triggered when something is dragged on the canvas - move thing > under > mouse ('current') to new position > ? ''' > ? if 0 < event.x < 200: > ? ? ? newx = event.x > ? else: newx = canv.coords('current')[0] > ? if 0 < event.y < 100: > ? ? newy = event.y > ? else: newy = canv.coords('current')[1] > ? canv.coords('current', newx, newy) > > makeFrame(root) > root.mainloop() > > > > > > On Fri, Oct 3, 2008 at 3:44 PM, Eric_Dex... at msn.com wrote: > > I saw this (close to this anyway) lieing around on the internet and > > was wanting to use it to define a start point exc but I need the > > graphics to stay within a set y coords and I am not realy sure how to > > do that. ?I have no idea on how to bind a min/max y to it. ?(the > > concept is inspired by the javacsoundblue). > > > #!/usr/bin/python > > from Tkinter import * > > import csoundroutines as cs > > > root = Tk() > > > global canv > > xx = {} > > > def makeFrame(root): > > ? global canv > > ? test = cs.csdInstrumentlist3('bay-at-night.csd') > > ? canv = Canvas (root, height = 200, width = 350) > > > ? for i in range (0, len(test.instr_number)): > > ? ? canv.create_text(10, i *10, text=str(test.instr_number[i]) + > > '...', tags=('movable')) > > ? ? xx[i] = canv.tag_bind('movable', '', slide) #B1-motion > > is a drag with left button down > > ? ? canv.pack() > > > def slide (event): > > ? ''' > > ? triggered when something is dragged on the canvas - move thing > > under > > mouse ('current') to new position > > ? ''' > > ? newx = event.x > > ? if event.y < 10 and event.y > 0: > > ? ? newy = event.y > > ? ? canv.coords('current', newx, newy) > > > makeFrame(root) > > root.mainloop() > > -- > >http://mail.python.org/mailman/listinfo/python-list > > --http://www.badmuthahubbard.com- Hide quoted text - > > - Show quoted text - haven't tried this yet but I look foward to trying it out.. From benjamin.kaplan at case.edu Tue Dec 9 00:04:32 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 9 Dec 2008 00:04:32 -0500 Subject: How to initialize a class variable once In-Reply-To: <804363f5-458a-4e72-8b2f-ad9c3c28b6cb@s9g2000prg.googlegroups.com> References: <804363f5-458a-4e72-8b2f-ad9c3c28b6cb@s9g2000prg.googlegroups.com> Message-ID: On Mon, Dec 8, 2008 at 11:44 PM, John Machin wrote: > On Dec 9, 3:36 pm, Matimus wrote: > > On Dec 8, 8:08 pm, Roy Smith wrote: > > > > > I've got a class with a class variable: > > > > > class Foo: > > > _map = {} > > > > > How do I make sure this only gets initialized the *first* time the > > > module containing the class is imported? What appears to be happening > > > as it stands is each time the module gets imported, Foo._map get re- > > > initialized. > > > > Unless you are calling reload() on the module, it will only ever get > > _loaded_ once. Each additional import will just yield the existing > > module. Perhaps if you post an example of the behavior that leads you > > to believe that the class variables are getting reinitialized > > and change it to > class Foo(object): > because we care little about old-style classes these days unless the OP is using Python 3 in which case that would be redundant. This is going to be really confusing unless every poster lists their python version. > > and put a print statement in the module just before the class > statement and print statements before and after each import statement > so that we can see what is happening. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From exarkun at divmod.com Thu Dec 4 17:27:55 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 4 Dec 2008 17:27:55 -0500 Subject: schizophrenic view of what is white space In-Reply-To: <878wqvy5y9.fsf@mulj.homelinux.net> Message-ID: <20081204222755.20272.1632534177.divmod.quotient.15780@ohm> On Thu, 04 Dec 2008 22:40:46 +0100, Hrvoje Niksic wrote: > [snip] > >Whitespace is probably not controversial, but many parsers tend to >expect things like \d to match [0-9], not any Unicode character marked >as "digit". For example, I'm not sure if this behavior would be a >good default: > >>>> re.match(r'\d', u'\u0660', re.UNICODE) ><_sre.SRE_Match object at 0xb7da0250> > >What digit is \u0660, out of 0-9? Hard to say. Why's it hard? int(u'\u0660') == 0 :) Jean-Paul From deets at nospam.web.de Sun Dec 7 06:13:59 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 07 Dec 2008 12:13:59 +0100 Subject: var or inout parm? In-Reply-To: References: Message-ID: <6q1pfoFaapofU1@mid.uni-berlin.de> mh at pixar.com schrieb: > How can I make a "var" parm, where the called function can modify > the value of the parameter in the caller? > > def f(x): > x = x + 1 > > n = 1 > f(n) > # n should now be 2 Chris showed one way, another is simply returning it. As python can return ad-hoc created tuples & unpack them, some C++-wrappers for example treat out/inout vars like this: def foo(in, inout): return inout, out1, out2 x, y, z = foo(a, x) Obviously you are responsible for properly assigning the returned inout to the right name again. Diez From eric at ericaro.net Fri Dec 19 11:21:42 2008 From: eric at ericaro.net (eric) Date: Fri, 19 Dec 2008 08:21:42 -0800 (PST) Subject: best way to code Message-ID: hi, I need to find a "good" design pattern to instanciate, and add specific code all in one. Let me explain it : I need to define "some" code, better be in a class, something like class LinkA(object): def mystuff(self): class LinkB(object): def mystuff(self): AND I need an instance of this class { "stuff A": LinkA() "stuff B": LinkB() } This kind of code "would" be fine, I mean, the result effect in memory is fine for me. But I don't like the way I have to 1/ give a useless name to LinkA, linkB (there can be hundreds of names like that) 2/ I have to write it down two times (and that's one time too much) any ideas ? something like [ new object(): def mystuff(self): , new object(): def mystuff(self): ] would be really perfect (but I know it does not work, or at least, I don't know how to make it work) In fact, I would like to define a class, and an instance in a single statement thanks -- Eric http://codeslash.blogspot.com From prologic at shortcircuit.net.au Mon Dec 8 08:10:48 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Dec 2008 23:10:48 +1000 Subject: A question about reference in Python. In-Reply-To: References: <493CB003.3080209@gmail.com> <47c890dc0812072213q20cb415fjbd4c80e7af7a7ef5@mail.gmail.com> Message-ID: In case the OP is interested here is a more complete implementation (others are welcome to comment): http://codepad.org/drIhqb7Z Enjoy :) cheers James -- -- -- "Problems are solved by method" From thorsten at thorstenkampe.de Tue Dec 23 09:21:42 2008 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 23 Dec 2008 15:21:42 +0100 Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: * r (Mon, 22 Dec 2008 10:44:32 -0800 (PST))> > Steve Holden > > What makes you assume this is a zero-sum game, and that Python won't > > survive if any other language becomes popular. Every language borrows > > from those that came before it. Terms like "outright plagiarism" don't > > encourage rational debate, and make you seem like a troll who is more > > interested in stirring up controversy than actually doing things to help > > promote the language. > > This is a war Steve, and i will explain why. Python does not need to > compete with perl, lisp, C, basic, etc, etc. WHY, well because python > is SO radically different than those languages. Ruby on the other > hand, took most from python, the only difference is Ruby's full OO > integration.(12.method()). Since Ruby is so similar to python [...] You don't have a single clue about neither Python nor Ruby: 'According to the Ruby FAQ, "If you like Perl, you will like Ruby and be right at home with its syntax. [...] If you like Python, you may or may not be put off by the huge difference in design philosophy between Python and Ruby/Perl."'[1] Thorsten [1] http://en.wikipedia.org/wiki/Ruby_(programming_language)#Semantics From carsten.kraus at gmail.com Tue Dec 30 15:41:18 2008 From: carsten.kraus at gmail.com (carsn) Date: Tue, 30 Dec 2008 12:41:18 -0800 (PST) Subject: PIL - font kerning References: <21524b00-9151-43ab-b1b9-a3dd5666d959@n33g2000pri.googlegroups.com> <013a0d90-e70e-49e9-ad7c-73d93e7bd79a@z28g2000prd.googlegroups.com> Message-ID: On Dec 23, 9:51 pm, Ivan Illarionov wrote: > On Dec 23, 11:22 pm, Ivan Illarionov > wrote: > > > > > On 23 ???, 16:44, carsn wrote: > > > > Hey all, > > > > anybody know, if there?s a way to specify the kerning of a font, when > > > you draw text withPIL? > > > > I?d like to achieve the same effect that you get, when you set a > > > negative kerning in Gimp/Photshop - ie. reduce the spacing between > > > glyphs. > > > > CanPILdo that or do I use another lib for that? > > > > Thx for any pointers & some nice xmas days to U all! > > > carsten > > > No.PILcan't do that. I suggest combination of cairo/pango/pangocairo > > (pycairo and pygtk packages). > > > Ivan > > I found a little helper function that does what you want (and more) > > import cairo > import pango > import pangocairo > > def draw_text(surface, context, text, font="sans 14", position=None, > color=None, > box_width=None, > alignment=pango.ALIGN_CENTER, > line_spacing=None, letter_spacing=None, > extra_kerning=None): > if color is None: > color = (0.0, 0.0, 0.0) > context.set_source_rgb(*color) > pc = pangocairo.CairoContext(context) > layout = pc.create_layout() > layout.set_text(text) > layout.set_font_description(pango.FontDescription(font)) > if box_width: layout.set_width(box_width) > layout.set_alignment(alignment) > if line_spacing: layout.set_spacing(spacing) > alist = pango.AttrList() > if letter_spacing: > alist.insert(pango.AttrLetterSpacing(letter_spacing, 0, len > (text))) > if extra_kerning: > for pos, kern in extra_kerning.iteritems(): > alist.insert(pango.AttrLetterSpacing(kern, pos, pos > +1)) > layout.set_attributes(alist) > if position is None: > width, height = surface.get_width(), surface.get_height() > w, h = layout.get_pixel_size() > position = (width/2.0 - w/2.0, height/2.0 - h/2.0) > context.move_to(*position) > pc.show_layout(layout) > > And example usage: > > surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) > context = cairo.Context(surface) > draw_text(surface, context, 'Hello world!', > font="sans 52", color=(.25,.28,.33), > letter_spacing=-6000, > extra_kerning={0:-9000, 1:-1000, 6:6000, 7:-15000, 8:5000, > 9:-7000}) > > surface.write_to_png("hello.png") > > -- > Ivan Works great, thanks a lot!! From steve at holdenweb.com Sat Dec 20 08:21:43 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 20 Dec 2008 08:21:43 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <494cc88c$0$31344$9b4e6d93@newsspool4.arcor-online.net> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c47ad$0$20656$c3e8da3@news.astraweb.com> <494cc88c$0$31344$9b4e6d93@newsspool4.arcor-online.net> Message-ID: Stefan Behnel wrote: [...] > I think '...'.format() makes sense given that we already have '...'.join(). > Sure it does, but that doesn't stop a lot of people disliking str.join() regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From robert.kern at gmail.com Sat Dec 20 22:37:28 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 20 Dec 2008 21:37:28 -0600 Subject: linecache vs egg - reading line of a file in an egg In-Reply-To: References: Message-ID: R. Bernstein wrote: > Does linecache work with source in Python eggs? If not, is it > contemplated that this is going to be fixed or is there something else > like linecache that currently works? linecache works with eggs and other zipped Python source, but it had to extend the API in order to do so. Some of the debuggers don't use the extended API. This will be fixed in the next 2.6.x bugfix release, but not in 2.5.3. http://bugs.python.org/issue4201 -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From cjw at ncf.ca Sat Dec 6 08:18:07 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 06 Dec 2008 08:18:07 -0500 Subject: Multiple Versions of Python on Windows XP In-Reply-To: References: <4934de22$0$27863$9b622d9e@news.freenet.de> <4934E183.9020404@g.nevcal.com> <4934E3BF.7000403@v.loewis.de> Message-ID: <493A7B8F.8070806@ncf.ca> Glenn Linderman wrote: > On approximately 12/1/2008 11:29 PM, came the following characters from > the keyboard of Martin v. L?wis: >>> It would be nice if the ftypes were version specific as created by the >>> installer; IIRC, I created the above three from the ftype Python.File as >>> I installed each version. >>> >> >> That's a good idea; please submit a wish list item to bugs.python.org. >> There may be issues (such as people relying on this being Python.File), >> but I can't see any problems off-hand. >> >> Regards, >> Martin >> > > OK, Issue 4485 created. My first one, so let me know if I goofed. I > elaborated a bit from the original email, upon reflection. Seemed > useful, but also seemed complex by the time I got done. > > I don't really have a clue what the uninstaller should do with these; > nor have I fiddled to know if it presently removes Python.File. I > suppose it should delete them, if and only if the ftype and assoc have > the same content as was created by the corresponding version installation. > Here's another approach to handling multiple versions of Python, thanks to the PyScripter List. It does not address the need to access different versions of the Python Interpreter. Here is the full story. There are two types of Python installation a) For all users Python creates registry entries at HKEY_LOCAL_MACHINE\SOFTWARE\Python \PythonCore\2.x with installation info and puts the dll in c:\Windows \System32. b) For a single user Python creates registry entries at HKEY_CURRENT_USER\SOFTWARE\Python \PythonCore\2.x with installation info and does not put the dll in c: \Windows\System32. PyScripter without any command line flags looks at the registry to find the latest version of Python and then for an all user installation tries to load the relevant Python dll from the system path. For a single user installation tries to load the DLL from the Install path that is in the registry. When PyScripter is used with a --PYTHONxx flag then it does the above but searching only for the specific version. The Registry lookup does not take place when Python is used with the -- PYTHONDLLPATH. Instead PyScripter tries to load the Python dll from the specified path. The --PYTHONDLLPATH flag should be used with the --PYTHONxx flag. See http://pyscripter.googlepages.com/portablepython for an example of using PyScripter with portable Python. The %PYTHONHOME% variable is not used by PyScripter directly but by Python to find the installed libraries. See the Python documentation for its use. Colin W. From trfilmographer at gmail.com Fri Dec 12 13:55:14 2008 From: trfilmographer at gmail.com (trfilmographer at gmail.com) Date: Fri, 12 Dec 2008 10:55:14 -0800 (PST) Subject: newbie question... References: Message-ID: On Dec 12, 12:59?pm, r wrote: > yes, but your script will need to know hoe to handle this.the > following will open a file who's name was passed to the script > > if len(sys.argv) > 1: > ? ? try: > ? ? ? ? open_file(fname=sys.argv[1]) > ? ? except: > ? ? ? ? pass ah, ok. now what if I want the variable to be an integer that I send? for instance if I send 99 to the program, it is picking it up as a string instead of an integer value. How do I handle this with python?? From kirk at daycos.com Fri Dec 12 10:59:56 2008 From: kirk at daycos.com (Kirk Strauser) Date: Fri, 12 Dec 2008 09:59:56 -0600 Subject: newbie question: if var1 == var2: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> <87y6ymzecp.fsf@daycos.com> Message-ID: <87myf1z8n7.fsf@daycos.com> At 2008-12-12T15:35:11Z, "J. Cliff Dyer" writes: > Python has a version equally good: > > def chomp(s): > return s.rstrip('\r\n') > > You'll hardly miss Perl at all. ;) I haven't missed Perl in years! I just wish there was a basestring.stripeol method because I seem to end up writing the inline version of "chomp" every time I iterate across a file. -- Kirk Strauser The Day Companies From steve at holdenweb.com Mon Dec 22 20:31:16 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 22 Dec 2008 20:31:16 -0500 Subject: Python's popularity In-Reply-To: References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <494fef38$0$12781$426a74cc@news.free.fr> Message-ID: walterbyrd wrote: [...]>> Fooled by version numbers ? > > No, but I am giving django the benefit of the doubt. The django > project told people all along that django was not to be considered > production ready before 1.0. I will accept that some people decided to > wait until 1.0 came out to do any production development. Maybe django > is only lagging because 1.0 just came out? > The Django people said no such thing. They maintained the trunk as stable - they test so well that many people did indeed rely on the trunk for production systems. They did, sensibly in my opinion, refuse to promise that the 1.0 release would be backward-compatible with the development versions. Indeed they frequently changed the trunk in incompatible ways while they were working to find the best APIs, and this only affected those brave or stupid enough to update their Django installation automatically as checkins were made. Anyone would expect trouble doing that, and yet the affected sites were usually easily fixed, thanks to the project's conscientious maintenance of a list of incompatible changes. >> My actual CTO is a big Ruby/Rails fan, yet he settled on Python/Django >> for our current 'big' project. Wonder why ? > > Not knowing much about RoR: yes, I wonder why? Is it because python > has a cleaner syntax? Or what? It's because he decided that Django was the best tool for the particular job, making him unusually open-minded for a member of the pointy-haired species. Unlike some on this list he doesn't let his prejudices blind him to reality. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From ldo at geek-central.gen.new_zealand Mon Dec 1 02:57:24 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 01 Dec 2008 20:57:24 +1300 Subject: end of print = lower productivity ? References: Message-ID: In message , cptnwillard at gmail.com wrote: > Now the print statement disappeared, and I have to write print("f") > instead. These parentheses not only take time to write, they also make > me think twice about using print for debugging purposes. Trouble is, print defaulted to printing to stdout, and I usually wanted debug messages to go to stderr. So print saved me nothing, which is why I never got into the habit of using it. From antoine at vo.lu Sat Dec 6 08:56:54 2008 From: antoine at vo.lu (Antoine De Groote) Date: Sat, 06 Dec 2008 14:56:54 +0100 Subject: Guido's new method definition idea In-Reply-To: <7c56a65c-ca99-4d00-b425-ae6385ff1a0a@v42g2000yqv.googlegroups.com> References: <7c56a65c-ca99-4d00-b425-ae6385ff1a0a@v42g2000yqv.googlegroups.com> Message-ID: Aaron Brady wrote: > On Dec 5, 8:21 pm, "Daniel Fetchinson" > wrote: >> Hi folks, >> >> The story of the explicit self in method definitions has been >> discussed to death and we all know it will stay. However, Guido >> himself acknowledged that an alternative syntax makes perfect sense >> and having both (old and new) in a future version of python is a >> possibility since it maintains backward compatibility. The alternative >> syntax will be syntactic sugar for the old one. This blog post of his >> is what I'm talking about: >> >> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... >> >> The proposal is to allow this: >> >> class C: >> def self.method( arg ): >> self.value = arg >> return self.value >> >> instead of this: >> >> class C: >> def method( self, arg ): >> self.value = arg >> return self.value >> >> I.e. explicit self stays only the syntax is slightly different and may >> seem attractive to some. > ... > > Would it be valid outside class definitions too? (As follows...) > > def sequence.shuffle( ): > x= sequence[ 0 ] > sequence[ 0 ]= sequence[ -1 ] > ...etc. > > shuffle( listA ) This is not what was intended. The discussion was explicitly only about class methods. What you are describing is weird and not generalizable. What if your method takes more than one parameter? You might argue that "sequence" would be the first argument in the list, like def sequence.shuffle(a, b): """ a, b: dummy arguments, just for the sake of the example """ x = sequence[0] sequence[0] = sequence[-1 ...etc. shuffle(listA, 1, 1) I can't think of any good reason to do this. What's more, the whole discussion was partly due to error messages like Traceback (most recent call last): File "classes.py", line 9, in obj.m2(1) TypeError: m2() takes exactly 3 arguments (2 given) Your proposition (well actually it is only a question) would result in error messages exactly like this one when one would not carefully read the method signature for example. > > Can you still call it by class membership? (As follows...) > > C.method( inst, arg ) That should not change at all, as the alternative syntax would actually be only syntactic sugar. From exarkun at divmod.com Mon Dec 8 11:36:36 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 8 Dec 2008 11:36:36 -0500 Subject: Equivalent of 'wget' for python? In-Reply-To: <6q50bfFaqa0aU1@mid.uni-berlin.de> Message-ID: <20081208163636.20272.716624751.divmod.quotient.17901@ohm> On Mon, 08 Dec 2008 17:29:35 +0100, "Diez B. Roggisch" wrote: >Robert Dailey wrote: > >> Hi, >> >> I'm looking for a portable way to download ZIP files on the internet >> through Python. I don't want to do os.system() to invoke 'wget', since >> this isn't portable on Windows. I'm hoping the core python library has >> a library for this. Note that I'll be using Python 3.0. > >Module urllib2 > There isn't such a module in Python 3.0. Jean-Paul From lists at cheimes.de Thu Dec 11 18:48:43 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 12 Dec 2008 00:48:43 +0100 Subject: Best way of debigging a C extension In-Reply-To: <6qdjt7Fc1fg0U1@mid.uni-berlin.de> References: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> <6qdjt7Fc1fg0U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch schrieb: > I never tried this on windows - but what happens if you start python > inside GDB, and then set breakpoints inside your extension? > > This works flawlessly for me under *nix. > > The debug-build of python isn't needed for this - and I doubt a bit that > it helps you much, as being inside the interpreter & getting detailed > information isn't your goal - you want to see your extensions functions, > what parameters they get and so on. It doesn't work well with all debugging symbols stripped and with -O2 optimized code. The compiler rearranges the code. You could try to compile your own code with different compiler arguments. I don't know if that's easily possible on Windows with Python 2.5. Christian From fuzzyman at gmail.com Sun Dec 14 17:59:26 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 14 Dec 2008 14:59:26 -0800 (PST) Subject: Looking for the best way to translate an idiom References: <4945406a$0$1127$426a74cc@news.free.fr> <2c5ad999-47f9-4040-85c9-4c9438afe4bb@b41g2000pra.googlegroups.com> Message-ID: On Dec 14, 5:51?pm, Paul Moore wrote: > On 14 Dec, 16:22, Bruno Desthuilliers > > wrote: > > if you only want the first returned value, you can just apply a slice: > > > def f(): > > ? ? return 1,2,3 > > > a = f()[0] + 1 > > Hmm, true. I'm not sure it's any less ugly, though :-) > > > FWIW, Python 2.6 has NamedTuple objects... > > I know, but I want to target 2.5+ (I still have a number of systems > running 2.5) > There is a Python implementation of NamedTuple on the Python cookbook that is compatible with Python 2.5. Michael Foord http://www.ironpythoninaction.com/ From rdmurray at bitdance.com Tue Dec 9 21:12:04 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Tue, 9 Dec 2008 21:12:04 -0500 (EST) Subject: SequenceMatcher bug ? In-Reply-To: References: Message-ID: On Mon, 8 Dec 2008 at 23:46, eliben wrote: > This is about Python 2.5.2 - I don't know if there were fixes to this > module in 2.6/3.0 > > I think I ran into a bug with difflib.SequenceMatcher class. > Specifically, its ratio() method. The following: > > SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + [5]).ratio > () > > returns 0.0 > > While the same with 500 replaced by 100 returns .99... something > Looking at the code of SequenceMatcher there's some caching going on > when the sequences are longer than 200 elements (and indeed, I can > reproduce the bug above 200 but not below). Can anyone confirm that > this misbehaves and suggest a workaround ? Python 2.5.2 (r252:60911, Sep 29 2008, 20:34:04) [GCC 4.3.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from difflib import SequenceMatcher >>> SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + >>> [5]).ratio() 0.99900299102691925 --RDM From antoine at vo.lu Tue Dec 9 06:38:25 2008 From: antoine at vo.lu (Antoine De Groote) Date: Tue, 09 Dec 2008 12:38:25 +0100 Subject: primera Message-ID: <16149$493e58b1$d9a2276f$4726@news.hispeed.ch> zalli, du spills jo net mat am volley oder? mengs de du kinns dann mat mengem auto an den MCM an eventuell op sandweiler fueren? well m?indes ass volley, densdes fussball, an mettwochs ass schon hellejen owend... nuecht antoine From bj_666 at gmx.net Fri Dec 12 11:13:56 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 12 Dec 2008 16:13:56 GMT Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> Message-ID: <6qfgu4Fc3a5jU4@mid.uni-berlin.de> On Fri, 12 Dec 2008 16:51:15 +0100, Marco Mariani wrote: > Filip Gruszczy?ski wrote: > > >> I am not doing it, because I need it. I can as well use "if not elem is >> None", > > I suggest "if elem is not None", which is not quite the same. In which way is it not the same? Has the same behavior at least: In [256]: elem = None In [257]: not elem is None Out[257]: False In [258]: elem is not None Out[258]: False In [259]: elem = 42 In [260]: not elem is None Out[260]: True In [261]: elem is not None Out[261]: True > If you slip such an error in a post, I suggest to practice some time > writing correct code before having one-liner contests with your > perl-loving friends :) If you call something an error, make sure it really is one. :-) Ciao, Marc 'BlackJack' Rintsch From 5lvqbwl02 at sneakemail.com Fri Dec 26 20:28:10 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Fri, 26 Dec 2008 17:28:10 -0800 (PST) Subject: Doing set operation on non-hashable objects References: <3a87eb6a-13ff-4aea-8835-3a233cc6cfc4@w39g2000prb.googlegroups.com> <6c043bc7-19e6-4e3d-bf01-5ade35d8a90a@s1g2000prg.googlegroups.com> Message-ID: <73bb9180-ee52-4718-8041-c03ed33f0441@a29g2000pra.googlegroups.com> On Dec 24, 12:52?pm, Carl Banks wrote: > On Dec 24, 1:16?pm, 5lvqbw... at sneakemail.com wrote: > > > > > > > Hi, > > > I'm writing an application which is structured roughly as follows: > > > "db" is a dict, where the values are also dicts. > > A function searches through db and returns a list of values, each of > > which is a dict as described above. > > I need to perform set operations on these lists (intersection and > > union) > > However the objects themselves are not hashable, and therefore can't > > be in a set, because they are dicts. > > I'm not sure how large each set will be, but the point is I'm trying > > to avoid anything looking like an O(n^2) algorithm, so I can't just > > use naive double-looping to check for intersection/union on a pair of > > lists. > > > The only way I can think of to do this right is to hash the dicts by > > freezing them, turning them all into tuples, which can then be > > hashed. ?But this is a problem because more dicts might be nested > > inside. ?At any rate, I'd need to thaw them out when I'm done and turn > > them back into dicts, which seems complicated and annoying, and all > > this leads me to believe there is a better way. > > > What I really need is a set of pointers, so at the end of the > > operation I have the actual objects pointed to. ?Can I somehow use the > > object IDs as set elements, then recreate a list with the actual > > objects they point to? > > > How do you get the object back from an ID in python? > > Quick and dirty way is to reference the dicts with a lightweight > hashable object that uses the dict's identity. ?For instance: > > class Identity(object): > ? ? def __init__(self,obj): > ? ? ? ? self.obj = obj > ? ? def __hash__(self): > ? ? ? ? return hash(id(self.obj)) > ? ? def __eq__(self,other): > ? ? ? ? return self.obj is other.obj > > Then, instead of "s.add(d)" use "s.add(Identity(d))". > > Instead of "d = s.pop()" use "d = s.pop().obj". > > Instead of "d in s" use "Identity(d) in s". > > And so on. > > To do it a bit better, you could create an IdentitySet class that > subclasses set and wraps the methods so that they automatically apply > wrap and unwrap the arguments on their way in and out (I'd bet there's > already a cookbook recipe to do that). > > Carl Banks Thank you, I like this idea a lot. It's close to what I've been thinking but a bit cleaner. Michael From jstroud at mbi.ucla.edu Sun Dec 7 03:41:10 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 07 Dec 2008 00:41:10 -0800 Subject: Brain going crazy with recursive functions In-Reply-To: <181d6cf8-8df3-46d4-9d21-197d34b3de87@d36g2000prf.googlegroups.com> References: <181d6cf8-8df3-46d4-9d21-197d34b3de87@d36g2000prf.googlegroups.com> Message-ID: 5lvqbwl02 at sneakemail.com wrote: > I'm trying to solve the 9-tile puzzle using as functional an approach > as possible. I've recently finished reading SICP and am deliberately > avoiding easy python-isms for the more convoluted scheme/functional > methods. The following function is trivial to do with for loops and > directly accessing arrays with [] syntax. I'm trying to limit myself > to the types of idioms/semantics one finds in minimal scheme, such as > in SICP. I want eventually to port this to scheme, but I know python > better, so that's where I'm starting. > > My current problem is the following. The 9-tile puzzle consists of a > list of lists like this [[1,2,3],[4,5,6],[7,8,0]], where the numbers > can be jumbled up. I'm looking for the location of the zero using > *only* recursion and operators that are similar to car/cdr. The > return value should be the row,col of the zero. For example above the > return value would be (2,2). > > I'm also trying to define a single "linear_search(...)" function which > does the search for within the row (an inner list above) and within > the whole list. linear_search takes as an argument a "truth_function" > which does the actual work. What's tricky is that the truth function > for the array-as-a-whole is also the linear_search for a row. Once > I'm in linear_search for the array, I also call linear_search for each > row. > > The problem is the line where it says acc.insert(0,idx) looks fishy to > me. It works fine and returns the row,col of the location of the zero > tile, but it seems to be mutating a variable, and that's the thing I'm > trying to avoid. In a sense, it's not hard enough and python is > making this too easy :) (although it took a bit of mind-wrenching to > get to this point. Recursion makes you either dumber or smarter, I'm > not sure which). > > How do I accumulate the inner value of the search so it pops out at > the end, without resorting to a mutable variable? I did a bit of > search and the word "monad" came up, but I'm not sure what that is (I > know it relates to haskell and some other purely functional stuff, but > I get very lost when trying to read that stuff). > > def linear_search(array, truth_func, acc): > # Goes through each element of array and applies truth_func. > # Returns index if found, otherwise returns None > def linear_search_iter(idx, truth_func, arr, acc): > if arr: > tf = truth_func(arr[0]) > if tf or type(tf) is int: > acc.insert(0,idx) > return idx, acc+[idx] > else: > return linear_search_iter(idx+1, truth_func, arr[1:], acc) > return linear_search_iter(0, truth_func, array, acc) > > > > def locate_zero(p): > # Locates empty tile. Returns (r,c) tuple > def find_zero_in_row(row): > return linear_search(row, lambda x: x==0, acc) > > acc = [] > ls = linear_search(p, find_zero_in_row, acc) > print acc > return acc > thanks > Michael I am honestly getting lost in your code. The following fulfills your requirements as far as I can tell. It uses None as a sentinel for the truth function matching no elements of the array. Some assignments are made within the code simply to make it more readable. They are not necessary. The first element that the truth function evaluates to True is returned. I hope it helps. James def linear_search(array, truth_func, loc=(0,0)): idx1, idx2 = loc if idx1 >= len(array): return None if idx2 >= len(array[idx1]): return linear_search(array, truth_func, (idx1+1, 0)) value = array[idx1][idx2] tf = truth_func(value) if tf: return loc else: return linear_search(array, truth_func, (idx1, idx2+1)) a = [[5, 3, 4], [2, 0, 1], [8, 6, 7]] linear_search(a, lambda x: x==0) From Slaunger at gmail.com Tue Dec 2 10:01:44 2008 From: Slaunger at gmail.com (Slaunger) Date: Tue, 2 Dec 2008 07:01:44 -0800 (PST) Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> <258cf433-f6c9-43e7-a235-f5f6b2b6433f@j39g2000yqn.googlegroups.com> Message-ID: <33b4cc2f-2311-491c-a2e6-9cc5452b1a6b@g38g2000yqd.googlegroups.com> Just wanted to show the end result in its actual implementation! I ended up *not* making a decorator, as I already had a good idea about how to do it using __getattr__ class PayloadDualFrqIQOnDemand(PayloadDualFrqIQ): """ This class has the same interface as its parent, but unlike its parent, it is instantiated without its payload parsed up in its instance attributes Q1, I1, Q2 and I2. Instead it stores a reference to the file object in which the Payload data can be read, the file position and the version of the payload data. On accessing one of the data attributes, the actual payload data are read from the file, and the reference to the file object is unbound. The constructor signature is therefore different from its parent as it takes the file object, position and version as arguments instead of the actual data. """ @classmethod def _unpack_from_file(cls, f, samples, ver): bytes = samples * cls.bytes_per_sample initial_pos = f.tell() f.seek(initial_pos + bytes) #Skip over the payload return cls(f, initial_pos, samples, ver) @classmethod def unpack_from_ver3_file(cls, f, samples): return cls._unpack_from_file(f, samples, ver=3) @classmethod def unpack_from_ver4_file(cls, f, samples): return cls._unpack_from_file(f, samples, ver=4) data_attr_names = frozenset(["Q1", "I1", "Q2", "I2"]) def __init__(self, a_file, a_file_position, samples, a_version): """ Returns an instance where the object knows where to look for the payload but it will only be loaded on the first attempt to read one of the data attributes in a "normal" PayloadDualFrqIQ object. """ self.f = a_file self.file_position = a_file_position self.samples = samples self.ver = a_version def __getattr__(self, attr_name): """ Checks if a request to read a non-existing data attribute has an attribute corresponding to one of the data attributes in a normal PayloadDualFrqIQ object. If true, the data attributes are created and bound to the object using the file object instance, the file position and the version. It is a prerequisite that the file object is still open. The function leaves the file object at the file position when it entered the method """ cls = self.__class__ if attr_name in cls.data_attr_names: initial_pos = self.f.tell() try: bytes = self.samples * cls.bytes_per_sample self.f.seek(self.file_position) buf = self.f.read(bytes) if self.ver == 3: bytes_to_data = cls._v3_byte_str_to_data elif self.ver == 4: bytes_to_data = cls._v4_byte_str_to_data else: raise TermaNotImplemented, \ "Support for ver. %d not implemented." % self.ver I1, Q1, I2, Q2 = bytes_to_data(buf) self.__dict__["I1"] = I1 self.__dict__["Q1"] = Q1 self.__dict__["I2"] = I2 self.__dict__["Q2"] = Q2 return self.__dict__[attr_name] finally: # Restore file position self.f.seek(initial_pos) # Unbind lazy attributes del self.f del self.ver del self.file_position del self.samples This seems to work out well. No infinite loops in __getattr__! At least it passes the unit test cases I have come up with so far. No guarantees though, as I may simply not have been smart enough to bring forth unit test cases which make it crash. Comments on the code is still appreciated though. I am still a novice Python programmer, and I may have overlooked more Pythonic ways to do it. -- Slaunger From wuwei23 at gmail.com Wed Dec 3 00:40:31 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 2 Dec 2008 21:40:31 -0800 (PST) Subject: Debugging a Python Program that Hangs References: Message-ID: On Dec 3, 2:19?am, Kevin D. Smith wrote: > I have a fairly large python program that, when a certain combination > of options is used, hangs. ?I have no idea where it is hanging, so > simply putting in print statements to locate the spot would be quite > difficult. ?Unfortunately, ctrl-C'ing the program doesn't print a > traceback either. ?Looking through the python debugger documentation, I > don't see how to run a python program and interactively stopping it > while it is running. ?Is there a way to stop within a running python > program to see where it is getting hung up? Hey Kevin, long time fan of your films! (I bet you get that a lot...) The trace module might help you identify where it's getting caught up: http://www.python.org/doc/2.5.2/lib/trace-cli.html From gherron at islandtraining.com Wed Dec 10 15:26:40 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 10 Dec 2008 12:26:40 -0800 Subject: How to pass out the result from iterated function In-Reply-To: References: Message-ID: <49402600.8040202@islandtraining.com> JD wrote: > I got a iterated function like this: > > def iterSomething(list): > has_something = False > for cell in list: > if something in cell: > has_something = True > output = something > if has_something: > iterSomething(output) > else: > final_out = outupt > > The problem is how can I read this final_out outside of the function. > I tried the global statement, it seems not work. Any idea? > Without examining the intent of your code, I'll suggest this: if has_something: return iterSomething(output) else: return output So either way, *something* is returned, and in the case of the recursive call, the innermost result is returned back up through all levels of the recursion. Is that what you wanted? Gary Herron From manu3d at gmail.com Tue Dec 16 11:25:59 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Tue, 16 Dec 2008 08:25:59 -0800 (PST) Subject: Bidirectional Networking References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <98a6c3cd-181c-43c9-805b-fb0689c69544@a26g2000prf.googlegroups.com> <29283382-3e26-492a-8612-9352f32c1c01@r15g2000prd.googlegroups.com> Message-ID: <60d40b0a-079c-4f87-a055-6d952526dfb3@i24g2000prf.googlegroups.com> Thanks everybody and in particular Gabriel and Bryan for their contributions to this thread. Very much useful information. Manu From steve at holdenweb.com Wed Dec 10 13:13:22 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 10 Dec 2008 13:13:22 -0500 Subject: get todays files In-Reply-To: <3090b59b-a0b2-4bfb-a08f-6d6accfb363a@k36g2000pri.googlegroups.com> References: <3090b59b-a0b2-4bfb-a08f-6d6accfb363a@k36g2000pri.googlegroups.com> Message-ID: Andrew D wrote: > On Dec 10, 5:55 pm, Steve Holden wrote: >> Andrew D wrote: >>> I have a script that will login to my ftp server and download all the >>> backup files, but I want it to only download the files that were >>> created today, e.g. if I ran the script today I want it to only fetch >>> files created today. >>> I am really not sure about how to do this, but it is quite important >>> to me, so all help is highly appreciated! >> IIRC there's an "ftpmirror" script in the Tools directory (if you're on >> Windows - Linux/Unix users have to download the source). I adapted it to >> several different purposes. >> > > Thanks Steve, > > I don't want to sound rude here, but I really want some code to add to > my script so that it will only download todays files. > That's OK. Maybe somebody's already got that code ready to go. I don't ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From rdmurray at bitdance.com Tue Dec 9 18:11:40 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Tue, 9 Dec 2008 18:11:40 -0500 (EST) Subject: Best way to report progress at fixed intervals In-Reply-To: References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> Message-ID: On Tue, 9 Dec 2008 at 13:27, Slaunger wrote: > On 9 Dec., 19:35, rdmur... at bitdance.com wrote: >> >> I felt like a little lunchtime challenge, so I wrote something that >> I think matches your spec, based on your sample code. ?This is not >> necessarily the best implementation, but I think it is simpler and >> clearer than yours. ?The biggest change is that the work is being >> done in the subthread, while the main thread does the monitoring. >> > Well, thank you for spending your lunch time break on my little > problem. > >> It would be fairly simple to enhance this so that you could pass >> arbitrary arguments in to the worker function, in addition to >> or instead of the loop counter. >> > Yes, I agree > >> ----------------------------------------------------------------------- >> """ >> Test module for testing generic ways of displaying progress >> information at regular intervals. >> """ >> import random >> import threading >> import time >> >> def work(i): >> ? ? ?""" >> ? ? ?Dummy process function, which takes a random time in the interval >> ? ? ?0.0-0.5 secs to execute >> ? ? ?""" >> ? ? ?print "Work step %d" % i >> ? ? ?time.sleep(0.5 * random.random()) >> >> class Monitor(object): >> ? ? ?""" >> ? ? ?This class creates an object that will execute a worker function >> ? ? ?in a loop and at regular intervals emit a progress report on >> ? ? ?how many times the function has been called. >> ? ? ?""" >> >> ? ? ?def dowork(self): >> ? ? ? ? ?""" >> ? ? ? ? ?Call the worker function in a loop, keeping track of how >> ? ? ? ? ?many times it was called in self.no >> ? ? ? ? ?""" >> ? ? ? ? ?for self.no in xrange(self.max_iter): >> ? ? ? ? ? ? ?self.func(self.no) >> >> ? ? ?def __call__(self, func, verbose=True, max_iter=20, progress_interval=1.0): > I had to look up the meaning of __call__, to grasp this, but I get > your methology >> ? ? ? ? ?""" >> ? ? ? ? ?Repeatedly call 'func', passing it the loop count, for max_iter >> ? ? ? ? ?iterations, and every progress_interval seconds report how >> ? ? ? ? ?many times the function has been called. >> ? ? ? ? ?""" >> ? ? ? ? ?# Not all of these need to be instance variables, but they might >> ? ? ? ? ?# as well be in case we want to reference them in an enhanced >> ? ? ? ? ?# dowork function. >> ? ? ? ? ?self.func = func >> ? ? ? ? ?self.verbose = verbose >> ? ? ? ? ?self.max_iter=max_iter >> ? ? ? ? ?self.progress_interval=progress_interval >> >> ? ? ? ? ?if self.verbose: >> ? ? ? ? ? ? ?print ("Work through all %d steps reporting progress every " >> ? ? ? ? ? ? ? ? ?"%3.1f secs...") % (self.max_iter, self.progress_interval) >> >> ? ? ? ? ?# Create a thread to run the loop, and start it going. >> ? ? ? ? ?worker = threading.Thread(target=self.dowork) >> ? ? ? ? ?worker.start() >> >> ? ? ? ? ?# Monitoring loop. >> ? ? ? ? ?loops = 0 >> ? ? ? ? ?# We're going to loop ten times per second using an integer count, >> ? ? ? ? ?# so multiply the seconds parameter by 10 to give it the same >> ? ? ? ? ?# magnitude. >> ? ? ? ? ?intint = int(self.progress_interval*10) > Is this not an unnecessary complication? >> ? ? ? ? ?# isAlive will be false after dowork returns >> ? ? ? ? ?while worker.isAlive(): >> ? ? ? ? ? ? ?loops += 1 >> ? ? ? ? ? ? ?# Wait 0.1 seconds between checks so that we aren't chewing >> ? ? ? ? ? ? ?# CPU in a spin loop. >> ? ? ? ? ? ? ?time.sleep(0.1) > Why not just call this with progress_interval directly? Because then the program make take up to progress_interval seconds to complete even after all the work is done. For a long running program and a short progress_interval that might not matter, so yes, that would be a reasonable simplification depending on your requirements. >> ? ? ? ? ? ? ?# when the modulus (second element of divmod tuple) is zero, >> ? ? ? ? ? ? ?# then we have hit a new progress_interval, so emit the report. > And then avoid this if expression? >> ? ? ? ? ? ? ?if not divmod(loops, intint)[1]: >> ? ? ? ? ? ? ? ? ?print "Processed %d of %d" % (self.no, self.max_iter) >> >> ? ? ? ? ?if verbose: >> ? ? ? ? ? ? ?print "Finished working through %d steps" % max_iter >> >> if __name__ == "__main__": >> ? ? ?#Create the monitor. >> ? ? ?monitor = Monitor() >> ? ? ?#Run the work function under monitoring. >> ? ? ?monitor(work) > I was unfamiliar with this notation, but now I understand it simply > invokes __call__. Thank you for showing me that! Yes, it is a very nice feature of python :) > OK. I agree this is a more elegant implementation, although I my mind, > I find it more natural if the reporting goes on in a subthread, but You could pretty easily rewrite it to put the reporter in the subthread, it was just more natural to _me_ to put the worker in the subthread, so that's how I coded it. Note, however, that if you were to write a GUI front end it might be important to put the worker in the background because on some OSes it is hard to update GUI windows from anything other than the main thread. (I ran into this in a Windows GUI ap I wrote using wxPython). > that is a matter of taste, I guess. Anyway: Thank you again for > spending your lunch break on this! No problem, it was fun. --RDM From clp at rebertia.com Mon Dec 29 04:50:07 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 29 Dec 2008 01:50:07 -0800 Subject: Get a list of functions in a file In-Reply-To: References: Message-ID: <47c890dc0812290150m1a1651bexaed7d59a9bf6911f@mail.gmail.com> On Sun, Dec 28, 2008 at 11:26 PM, member Basu wrote: > I'm putting some utility functions in a file and then building a simple > shell interface to them. Is their some way I can automatically get a list of > all the functions in the file? I could wrap them in a class and then use > attributes, but I'd rather leave them as simple functions. Assuming you've already imported the module as 'mod': func_names = [name for name in dir(mod) if callable(getattr(mod, name))] funcs = [getattr(mod, name) for name in dir(mod) if callable(getattr(mod, name))] Note that such lists will also include classes (as they too are callable). There are ways of excluding classes (and other objects that implement __call__), but it makes the code a bit more complicated. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From __peter__ at web.de Sun Dec 21 07:25:16 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 21 Dec 2008 13:25:16 +0100 Subject: Read an image from a URL and write it to the browser References: Message-ID: McCoy Fan wrote: > I want to do something simple: read an image from an image URL and > write the image to the browser in CGI style. > > I wrote a CGI script to do this (I'm new to Python) and got the > following error: > > "FancyURLopener instance has no attribute 'tempcache'" in method FancyURLopener.__del__ of > I have no idea what that error means and neither does Google. > > Any idea where I went wrong in the code below? > import urllib > > urlString = "http://www.google.com/google_logo.jpg" > imgStream = urllib.urlopen(urlString) > imgBuffer = imgStream.read() > imgStream.close() > print "Content-Type: image/jpeg" > print > print imgBuffer Your script runs without error here, but I can provoke the attribute error by passing an invalid proxies argument to urlopen(): $ python -c"import urllib; urllib.urlopen('whatever', proxies=42)" Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/urllib.py", line 75, in urlopen opener = FancyURLopener(proxies=proxies) File "/usr/lib/python2.5/urllib.py", line 609, in __init__ URLopener.__init__(self, *args, **kwargs) File "/usr/lib/python2.5/urllib.py", line 117, in __init__ assert hasattr(proxies, 'has_key'), "proxies must be a mapping" AssertionError: proxies must be a mapping Exception exceptions.AttributeError: "FancyURLopener instance has no attribute 'tempcache'" in > ignored Please post your complete traceback, Python version, and OS to allow for a more detailed diagnosis. You can also try to run your script with > imgStream = urllib.urlopen(urlString) changed to imgStream = urllib.urlopen(urlString, proxies={}) to bypass the code in which I suppose the failure to occur. Peter From pyn00b at gmail.com Tue Dec 9 00:36:59 2008 From: pyn00b at gmail.com (n00b) Date: Mon, 8 Dec 2008 21:36:59 -0800 (PST) Subject: fuzzy or boolean text search Message-ID: <104335ff-e507-4429-9ad3-baecb63da8b3@k36g2000yqe.googlegroups.com> hi, i'm looking for advice/suggestions for text search, preferably with boolean or even fuzzy capabilities, and for use with mysql innodb tables. asking too much :) ??? thx a bunch From febaen at gmail.com Fri Dec 12 07:58:36 2008 From: febaen at gmail.com (feba) Date: Fri, 12 Dec 2008 04:58:36 -0800 (PST) Subject: (Very Newbie) Problems defining a variable References: <49425146$0$8495$426a74cc@news.free.fr> <11c53a4a-de1e-4bee-ad60-a05befb6cbf4@a12g2000yqm.googlegroups.com> <7cb69ff5-9034-41cc-b667-d69329707b18@d36g2000prf.googlegroups.com> Message-ID: Actually, I have gedit set to four spaces per tab. I have no reason why it's showing up that large on copy/paste, but the file itself is fine. Thanks for the advice Chris, Stephen, I can definitely see how those are both far better ways of doing it. I have it as: #!/usr/bin/python #Py3k, UTF-8 bank = int(input("How much money is in your account?\n>>")) if bank <=0: print("You need a postive amount to gain interest.") quit() target = int(input("How much money would you like to earn each year? \n>>")) interest = 0 i = 0 while interest < target: #determine the interest rate to use if bank >= 100000: rate = 0.0173 elif bank >= 50000: rate = 0.0149 elif bank >= 25000: rate = 0.0124 elif bank >= 10000: rate = 0.0085 else: rate = 0.0060 #Now that we know what interest rate to use, apply it... lastbank = bank #To calculate interest... bank += (bank * rate) #Update earnings... interest = bank - lastbank #And figure out how much interest is made! i += 1 #So we can see which year a calculation represents print("Year %s, at %s rate: %s paid, %s in bank." % (i, rate, interest, bank)) now it checks to make sure the account is positive before moving on, in addition to using your recommendations on readability and efficiency in getting the rate From pete.forman at westerngeco.com Tue Dec 16 03:53:54 2008 From: pete.forman at westerngeco.com (Pete Forman) Date: Tue, 16 Dec 2008 08:53:54 +0000 Subject: alt.possessive.its.has.no.apostrophe References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> Message-ID: Steve Holden writes: > Ben Finney wrote: >> James Stroud writes: >> >>> Ben Finney wrote: >>>> James Stroud writes: >>>> >>>>> Yes. I think it was the British who decided that the apostrophe >>>>> rule for "it" would be reversed from normal usage relative to >>>>> just about every other noun. >> >> It also seems an indefensible claim to say that anyone "decided" it >> would be that way, especially "the British". >> > It's our language, dammit! Ours, ours, ours! > > This decision was actually taken at a meeting of the Society of > British pedants on November 23, 1786. This led to a schism between > the British and the newly-independent Americans, who responded by > taking the "u" out of colour, valour, and aluminium. I'd thought that the main schism was triggered by a tax on tea but it turns out that it was due to an apostrophe after t. ;-) -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- the opinion of Schlumberger or http://petef.22web.net -./\.- WesternGeco. From roy at panix.com Wed Dec 31 10:23:05 2008 From: roy at panix.com (Roy Smith) Date: Wed, 31 Dec 2008 10:23:05 -0500 Subject: change only the nth occurrence of a pattern in a string References: <0scs26-7a5.ln1@rama.fbx.proxad.net> Message-ID: In article <0scs26-7a5.ln1 at rama.fbx.proxad.net>, TP wrote: > Hi everybody, > > I would like to change only the nth occurence of a pattern in a string. It's a little ugly, but the following looks like it works. The gist is to split the string on your pattern, then re-join the pieces using the original delimiter everywhere except for the n'th splice. Split() is a wonderful tool. I'm a hard-core regex geek, but I find that most things I might have written a big hairy regex for are easier solved by doing split() and then attacking the pieces. There may be some fencepost errors here. I got the basics working, and left the details as an exercise for the reader :-) This version assumes the pattern is a literal string. If it's really a regex, you'll need to put the pattern in parens when you call split(); this will return the exact text matched each time as elements of the list. And then your post-processing gets a little more complicated, but nothing that's too bad. This does a couple of passes over the data, but at least all the operations are O(n), so the whole thing is O(n). #!/usr/bin/python import re v = "coucoucoucou" pattern = "o" n = 2 parts = re.split(pattern, v) print parts first = parts[:n] last = parts[n:] print first print last j1 = pattern.join(first) j2 = pattern.join(last) print j1 print j2 print "i".join([j1, j2]) print v From fakeaddress at nowhere.org Wed Dec 3 00:53:18 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 02 Dec 2008 21:53:18 -0800 Subject: Obama's Birth Certificate - Demand that US presidential electors investigate Obama's eligibility In-Reply-To: References: Message-ID: <89pZk.9151$be.4743@nlpi061.nbdc.sbc.com> girbarobert at yahoo.com wrote: > This message is not about the meaningless computer printout called More importantly, it's not about Python. I'm setting follow-ups to talk.politics. > "Certification of Live Birth" that Obama propaganda machine calls his > "Birth Certificate". The American people are still waiting for a copy > of Obama's original birth certificate that includes all his birth > information. The document is what Hawaii provides as certified copy of birth record. It contains all the information the federal government requires to prove citizenship by birth, and it shows that Barack Hussein Obama was born 04 August 1961 in Honolulu. See: http://www.factcheck.org/elections-2008/born_in_the_usa.html > Remind your US presidential electors of their constitutional duty to > investigate Obama's natural-born citizen status. > > No federal agency like FBI or Secret Service, no Hawaii bureaucrats > have ever investigated Obama's birth in Hawaii. Many illegal aliens in > USA have official "birth certificates" issued by state bureaucrats on > the basis of falsified birth records. Janice Okubo of Hawaii's Department of Health confirmed that the state has Obama?s original birth certificate on record: http://hawaii.gov/health/about/pr/2008/08-93.pdf [...] > Remind your US presidential electors that they have the legal standing > and constitutional duty to investigate Obama's birth in Hawaii by > demanding that Obama provide all his original birth records, and a > federal agency like FBI or Secret Service fully investigate them. That's not what the Constitution says. US Constitution, Article IV, Section 1: "Full Faith and Credit shall be given in each State to the public Acts, Records, and judicial Proceedings of every other State. And the Congress may by general Laws prescribe the Manner in which such Acts, Records and Proceedings shall be proved, and the Effect thereof." These haters seek to make Obama prove his records in ways others have not had to, and beyond any manner prescribed by Congress within its constitutional authority. -- --Bryan From __peter__ at web.de Fri Dec 19 11:35:11 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2008 17:35:11 +0100 Subject: best way to code References: Message-ID: eric wrote: > hi, > > I need to find a "good" design pattern to instanciate, and add > specific code all in one. Let me explain it : > > I need to define "some" code, better be in a class, something like > > class LinkA(object): > def mystuff(self): > > > class LinkB(object): > def mystuff(self): > > > > AND I need an instance of this class > { "stuff A": LinkA() > "stuff B": LinkB() > } > > This kind of code "would" be fine, I mean, the result effect in memory > is fine for me. > But I don't like the way I have to > 1/ give a useless name to LinkA, linkB (there can be hundreds of names > like that) > 2/ I have to write it down two times (and that's one time too much) > > any ideas ? > > something like > [ > new object(): > def mystuff(self): > > , > new object(): > def mystuff(self): > > ] > > would be really perfect (but I know it does not work, or at least, I > don't know how to make it work) > > In fact, I would like to define a class, and an instance in a single > statement >>> class Register: ... def __init__(self): ... self.items = [] ... def __call__(self, method): ... class Link(object): ... mystuff = method ... self.items.append(Link()) ... >>> register = Register() >>> @register ... def mystuff(self): print "first" ... >>> @register ... def mystuff(self): print "second" ... >>> for item in register.items: ... item.mystuff() ... first second Peter From google at mrabarnett.plus.com Sat Dec 13 14:20:54 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 13 Dec 2008 19:20:54 +0000 Subject: [OT] stable algorithm with complexity O(n) In-Reply-To: <6qidmbFc4qduU1@mid.uni-berlin.de> References: <6qidmbFc4qduU1@mid.uni-berlin.de> Message-ID: <49440B16.8070000@mrabarnett.plus.com> Diez B. Roggisch wrote: > David Hl??ik schrieb: >> Hi guys, >> >> i am really sorry for making offtopic, hope you will not kill me, but >> this is for me life important problem which needs to be solved within >> next 12 hours.. >> >> I have to create stable algorithm for sorting n numbers from interval >> [1,n^2] with time complexity O(n) . >> >> Can someone please give me a hint. Would be very very thankful! > > Unless I grossly miss out on something in computer science 101, the > lower bound for sorting is O(n * log_2 n). Which makes your task > impossible, unless there is something to be assumed about the > distribution of numbers in your sequence. > > Who has given you that assignment - a professor? Or some friend who's > playing tricks on you? > I'm assuming that the numbers are integers. I can think of an O(n) algorithm for this particular problem provided that n isn't huge, but if it's your assignment then it's up to you to discover it. From Scott.Daniels at Acm.Org Wed Dec 17 18:12:11 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 17 Dec 2008 15:12:11 -0800 Subject: The rule of literal string In-Reply-To: References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> Message-ID: <_PmdnU59w62vGtTUnZ2dnUVZ_hSdnZ2d@pdx.net> Li Han wrote: > But what repr() do remain a black hole! > Han > Try: print repr(repr("'")) that might enlighten you. From delmararlee at gmail.com Tue Dec 9 09:17:09 2008 From: delmararlee at gmail.com (delmararlee at gmail.com) Date: Tue, 9 Dec 2008 06:17:09 -0800 (PST) Subject: our real femme Message-ID: <7677bccb-03df-4126-ab2d-4b2ed0dd33fd@k24g2000pri.googlegroups.com> Some of our real femme http://wesexy.byethost8.com/ From __peter__ at web.de Sun Dec 14 10:49:06 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 14 Dec 2008 16:49:06 +0100 Subject: 1 or 1/0 doesn't raise an exception References: <49446E39.6020807@tim.thechases.com> Message-ID: Grant Edwards wrote: > Short circuit evaluation of booleans is very common (and has > been for decades), so I don't know why people would expect > something else. Visual Basic ;) From kyosohma at gmail.com Tue Dec 30 13:44:33 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 30 Dec 2008 10:44:33 -0800 (PST) Subject: wxPython.button.disabled still catching clicks References: <8cb6da6a-7df4-4cce-a28e-385448a25b26@w39g2000prb.googlegroups.com> <1ff2aad7-29a1-48cd-b3de-29fab443aa3e@u18g2000pro.googlegroups.com> <0e9a5ab7-8078-4d12-adb2-aaf92a78b007@s9g2000prm.googlegroups.com> <007bab05-6451-48c8-94bc-a34631795e32@v5g2000prm.googlegroups.com> Message-ID: On Dec 30, 3:04?am, mynthon wrote: > On Dec 23, 6:12?pm, Mike Driscoll wrote: > > > > > On Dec 23, 7:27?am,mynthon wrote: > > > > On Dec 23, 11:58?am, Aaron Brady wrote: > > > > > On Dec 23, 4:50?am,mynthon wrote: > > > > > > Hello! (sorry for my english) > > > > > > I have a problem with buttons in wxPython. When button is disabled > > > > > (by .Disable() or .Enable(False)) it is grayed out but still receive > > > > > clicks. > > > > > > Eg. i have button that disable itself, runs long action and enable > > > > > itself: > > > > > > def onClick(self, evt): > > > > > ? ? self.btn.Enable(False) > > > > > ? ? for i in range (1000): > > > > > ? ? ? ? print i > > > > > ? ? self.btn.Enable(True) > > > > > > when for loop is running button is greyed out and when i click on it > > > > > nothing happens but when loop ends another one is started because > > > > > button "remebered" thad i click on it when was diabled. My only idea > > > > > is to reposition button outside frame instead of disabling it but this > > > > > solution is...not good. > > > > > > thanks for any help. Ive searched groups, google and it looks that > > > > > only i have this problem :) > > > > > No, it is very common. ?During your for loop, the loop is dominating > > > > the process completely. ?Events are just building up in the app's > > > > message queue, and don't get handled until after you yield on control. > > > > > If you need to run a long task, look into threading, the OnIdle > > > > method, the 'multiprocessing' module, or pump messages during your > > > > long task. > > > > ok, maybe someone will need it. I dont know how it works because i > > > didnt have time to read docs and i cannot explain everything. I used > > > google and wxPython demo (in tree: wxpython overview / process and > > > events / process) > > > > class leftPanel(wx.Panel): > > > ? ? def __init__(self, parent, id): > > > ? ? ? ? wx.Panel.__init__(self, parent, id, style=wx.BORDER_SUNKEN) > > > > ? ? ? ? # here you have to define new process, IDLE event, and > > > onPRocessEnd event > > > ? ? ? ? self.process = None > > > ? ? ? ? self.GetParent().Bind(wx.EVT_IDLE, self.onIdle) > > > ? ? ? ? self.Bind(wx.EVT_END_PROCESS, self.onProcessEnd) > > > > ? ? ? ? # create button and bind event to it > > > ? ? ? ? self.runScriptBtn = wx.Button(self, -1, 'RUN ME!', (10,220)) > > > ? ? ? ? self.runScriptBtn.Bind(wx.EVT_BUTTON, self.onClick, > > > self.runScriptBtn) > > > > ? ? def onClick(self, evt): > > > ? ? ? ? # disable button > > > ? ? ? ? self.runScriptBtn.Enable(False) > > > > ? ? ? ? # here you have to enter command to run > > > ? ? ? ? # previusly i heve here exec('pythonmyScript.py') > > > ? ? ? ? # but now it will be a subprocess > > > ? ? ? ? cmd = 'pythonxxx1.py' > > > > ? ? ? ? #create new process > > > ? ? ? ? self.process = wx.Process(self) > > > > ? ? ? ? # dont know what it is for > > > ? ? ? ? self.process.Redirect() > > > > ? ? ? ? # execute cmd command > > > ? ? ? ? pid = wx.Execute(cmd, wx.EXEC_ASYNC, self.process) > > > > ? ? def onIdle(self, evt): > > > ? ? ? ? # beacuse this method is called only when app enters idle mode > > > ? ? ? ? # the line below is nedded to "simulate" entering idle mode > > > ? ? ? ? # dont know how it works but it works > > > ? ? ? ? evt.RequestMore(True) > > > > ? ? ? ? # here is some code to catch subprocess output > > > ? ? ? ? if self.process is not None: > > > ? ? ? ? ? ? stream = self.process.GetInputStream() > > > ? ? ? ? ? ? if stream.CanRead(): > > > ? ? ? ? ? ? ? ? text = stream.read() > > > ? ? ? ? ? ? ? ? print text > > > > ? ? def onProcessEnd(self, evt): > > > ? ? ? ? # here is some code to catch subprocess output > > > ? ? ? ? # when it is destroyed > > > ? ? ? ? stream = self.process.GetInputStream() > > > ? ? ? ? if stream.CanRead(): > > > ? ? ? ? ? ? text = stream.read() > > > ? ? ? ? ? ? print text > > > > ? ? ? ? # dont know it is necessary > > > ? ? ? ? self.process.CloseOutput() > > > > ? ? ? ? # remove (clear) process object > > > ? ? ? ? self.process.Destroy() > > > ? ? ? ? self.process = None > > > > ? ? ? ? # show button again > > > ? ? ? ? self.runScriptBtn.Enable() > > > I'm pretty sure there's a better way to do this. If you disable the > > button and click on it, you'll notice that it isn't firing events, so > > something else is going on here. It seems like the wx.Frame or > > wx.Application is queuing the mouse button clicks or something. I > > would post to the wxPython mailing list:http://wxpython.org/maillist.php > > > They'll be better able to address this and they'll probably have a > > simpler solution too. > > > Mike > > I changed it. Now i'm running separate thread instead of process. > First example at:http://wiki.wxpython.org/LongRunningTasks I should have posted that link when I posted originally. Oh well. Glad you found a workaround. Mike From bockman at virgilio.it Wed Dec 31 05:39:32 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: Wed, 31 Dec 2008 11:39:32 +0100 Subject: select.select and socket.setblocking In-Reply-To: <495b34d8$0$11387$5fc30a8@news.tiscali.it> References: <495a661d$0$11384$5fc30a8@news.tiscali.it> <495b34d8$0$11387$5fc30a8@news.tiscali.it> Message-ID: <495b4be5$0$11379$5fc30a8@news.tiscali.it> Francesco Bochicchio ha scritto: >> >> No, in blocking mode it will wait to receive _some_ data (1 or >> more bytes). The "requested" amount is strictly an upper >> limit: recv won't return more than the requested number of >> bytes, but it might return less. >> > > Uhm. In my experience, with TCP protocol recv only returned less than > the required bytes if the remote end disconnects. I always check the > returned value of recv and signal an error if the read bytes are less > than the expected ones, but this error is never occurred (and its about > 20 years that I use sockets in various languages and various flavor of > unix and occasionally on windows. Maybe have always been lucky ? :-) > BTW, this is not a rethorical or ironic question... my applications mostly run on LANs or dedicated WANs so maybe they never experienced the kind of network congestion that could cause recv to return less than the expected amount of bytes ... but then, IIRC TCP guarantees that the packet is fully received by hand-shaking at transport level between sender and receiver. Ad once the packet is fully in the receiver buffer, why should recv choose to give back to the application only a piece of it? Ciao ----- FB From kylefranki at gmail.com Wed Dec 24 16:32:10 2008 From: kylefranki at gmail.com (kylefranki at gmail.com) Date: Wed, 24 Dec 2008 13:32:10 -0800 (PST) Subject: Lesbians cuple USA Message-ID: <0d1af4d7-9987-4d62-a3a7-f9810144951e@c36g2000prc.googlegroups.com> Lesbi cuple want sex right now http://lesbicouple.pornblink.com/ From prologic at shortcircuit.net.au Thu Dec 18 19:41:37 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Dec 2008 10:41:37 +1000 Subject: Factoring Polynomials In-Reply-To: References: Message-ID: On Fri, Dec 19, 2008 at 10:11 AM, Gabriel Genellina wrote: > En Thu, 18 Dec 2008 17:37:35 -0200, escribi?: > >> I am trying to write a simple application to factor polynomials. I >> wrote (simple) raw_input lines to collect the a, b, and c values from >> the user, but I dont know how to implement the quadratic equation >> >> x = (-b +or- (b^2 - 4ac)^1/2) / 2a Why is this so hard ? This is simple simple expression. Reading through the Python tutorial and reading up on how to define functions is all you need! :) Here goes: >>> def f(a, b, c): ... x = (-1 * b) + ((b**2 - (4 * a * c)) / (2 * a)) ... return (-1 * x), x ... >>> f(1, 2, 3) (6, -6) >>> cheers James From aspersieman at gmail.com Tue Dec 9 10:45:32 2008 From: aspersieman at gmail.com (aspersieman) Date: Tue, 09 Dec 2008 17:45:32 +0200 Subject: 'pretty print' for built in types In-Reply-To: <051e3a97-b9bc-4a67-8896-93628ca19f59@r15g2000prd.googlegroups.com> References: <051e3a97-b9bc-4a67-8896-93628ca19f59@r15g2000prd.googlegroups.com> Message-ID: On Tue, 09 Dec 2008 17:31:41 +0200, Robert Dailey wrote: > > Is there a built in way to 'pretty print' a dict, list, and tuple > (Amongst other types)? Dicts probably print the ugliest of them all, > and it would be nice to see a way to print them in a readable way. I > can come up with my own function to do this, but I don't want to do > this if I don't have to. For lists use 'join'. >>> lista = ['a', 'b', 'c', 4] >>> ','.join(lista) >>> a,b,c,4 For more info google 'python join' or see [1] Regards Nicol [1] http://docs.python.org/library/stdtypes.html#string-methods -- Christopher Columbus was, after all, a super intelligent hypersquirrel from the planet Klepton. How else could he have known where to find america? From steve at holdenweb.com Tue Dec 16 13:42:14 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 16 Dec 2008 13:42:14 -0500 Subject: Python Dictionary Algorithm Question In-Reply-To: <3ca641b40812160951h3a13e69am291afb02965451a7@mail.gmail.com> References: <3ca641b40812160951h3a13e69am291afb02965451a7@mail.gmail.com> Message-ID: <4947F686.2040904@holdenweb.com> Brigette Hodson wrote: > Hello! I am in a beginning algorithms class this semester and I am > working on a presentation. I want to discuss in some detail the > algorithm python uses to determine the hash function for python > dictionaries. Does anyone know what this algorithm is? Or where I can go > to find information on it? > > Thanks. > Look in http://svn.python.org/view/python/tags/r26/Objects/ for dictnotes.txt and dictobject.c. Good luck with the class! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steve at REMOVE-THIS-cybersource.com.au Sun Dec 28 02:28:55 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Dec 2008 07:28:55 GMT Subject: math module for Decimals References: <01671a9e$0$6988$c3e8da3@news.astraweb.com> Message-ID: <016721cc$0$6988$c3e8da3@news.astraweb.com> On Sun, 28 Dec 2008 06:58:18 +0000, Steven D'Aprano wrote: > def make_decimal(f, precision=16): > # choose how many decimal places you want to keep return > Decimal.from_float(f, precision) Ah crap, I forgot that from_float() has been left out of the decimal API. That's very annoying. Sorry about that. -- Steven From ivan.illarionov at gmail.com Wed Dec 24 12:00:36 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Wed, 24 Dec 2008 09:00:36 -0800 (PST) Subject: Custom C Exception Subclasses References: <41f291ff-d7bd-4334-8689-636e95524cdc@b38g2000prf.googlegroups.com> Message-ID: On Dec 24, 6:42?pm, Ross wrote: > For a project that I am doing, it would be useful to have an exception > class that stores some additional data along with the message. > However, I want to be able to store a couple pointers to C++ classes, > so I can't just use an exception created with PyExc_NewException. ?If > I were to subclass the built-in Exception type, I would need to have > access to the PyExc_ExceptionObject, but the headers only give > PyExc_Exception, the type object. ?This seems like a rather > straightforward task, but I can't seem to find any documentation for > it. ?Does anyone know how to do this? ?Thanks! When you raise an exception in C++ you can set it to ANY Python object via PyErr_SetObject and that object could store pointers to C++ classes. Ivan From ferdinandsousa at gmail.com Wed Dec 17 07:11:46 2008 From: ferdinandsousa at gmail.com (Ferdinand Sousa) Date: Wed, 17 Dec 2008 17:41:46 +0530 Subject: Transferring a file over sockets Message-ID: I am using sockets to transfer a file over LAN. There are 2 scripts, the server opens a listens for connection and the client is run on another machine. I always make sure the server is run first. The strange thing is that if the the server script is double-clicked and executed (run in a console with title %Python path%python.exe) the output file saved on the server is truncated. It works just fine if you open the server script in IDLE and then run it. The client script can be run in either way, it still works. You could try using any arbitrary file to test this behaviour after changing the file name in both the scripts. ========================================================== # file receiver # work in progress import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) HOST = '192.168.1.17' PORT = 31400 s.bind((HOST, PORT)) s.listen(3) conn, addr = s.accept() print 'conn at address',addr conn.send('READY') f = open('C:\\Documents and Settings\\USER\\Desktop\\test.pdf','wb') fsize=int(conn.recv(8)) print 'File size',fsize f.write(conn.recv(fsize)) f.close() conn.close() s.close() raw_input('Press any key to exit') =========================================================== # file sender !!! # Work in progress import socket, os from stat import ST_SIZE HOST = '192.168.1.17' PORT = 31400 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST,PORT)) if s.recv(5)!='READY': raw_input('Unable to connect \n\n Press any key to exit ...') s.close() exit() f=open('C:\\Documents and Settings\\USER\\Desktop\\t.pdf', 'rb') fsize=os.stat(f.name)[ST_SIZE] s.send(str(fsize)) s.send(f.read()) s.close() f.close() =========================================================== Thanks for reading!! Best regards, Ferdi -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Dec 19 12:07:50 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 19 Dec 2008 12:07:50 -0500 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <6r219cFfc8ovU1@mid.individual.net> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> Message-ID: Thomas Heller wrote: > Mark Summerfield schrieb: >> Just a follow-up to say that the book has now been published in the >> U.S. >> It is now in stock at InformIT, and should reach other stores, e.g., >> Amazon, in a week or so. >> >> Also, the introduction, the first few pages of the first chapter, the >> whole of chapter 12 (regular expressions), and the index are now >> available for free download in a PDF from here: >> http://www.informit.com/store/product.aspx?isbn=0137129297 > > Question from a non-native english speaker: is this now valid english? > > "One of Python?s great strengths" > ^ > "and also teaches Python?s functional programming features" > ^ > "The book?s approach is wholly practical" > ^ It always has been valid English. The apostrophe is only omitted from personal pronouns (hers, its, and so on). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From digitig at gmail.com Fri Dec 12 06:24:56 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 12 Dec 2008 11:24:56 +0000 Subject: Removing None objects from a sequence In-Reply-To: <1be78d220812120315y70688a4do455bdf41d7e53b03@mail.gmail.com> References: <1be78d220812120315y70688a4do455bdf41d7e53b03@mail.gmail.com> Message-ID: 2008/12/12 Filip Gruszczy?ski : > I don't mean memory, but space in code ;-) Trying to save printer paper for your listings, then? -- Tim Rowe From gabriel.rossetti at arimaz.com Tue Dec 9 12:31:37 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Tue, 09 Dec 2008 18:31:37 +0100 Subject: memory leak? Message-ID: <493EAB79.6070805@arimaz.com> I have been debugging a distributed application for about 2 days that has a memory leak. My app is a Twisted app, so I thought that maybe it was on the twisted side, I finally isolated it to no being a Twisted problem but a Python problem. The problem comes from the code that uses wxPython and pySerial, these each run in a different process. I wrote test programs, one "pure" wxPython, one "pure" pySerial and let them run. The number of objects in the wxPython code doubles in about an hour, the pySerial code doubles about every 10 minutes. I think there is something wrong with the GC/memory management or C lib. The wxPython lib is big, so it may have bugs, but pySerial is small and pure python (no C/C++ directly, event thought it uses os.open/close & termios that themselves use C (unless I mistaking)) and I reviewed it's code and I see nothing that could cause this. I ran these tests on linux 2.6 (ubuntu 8.04) using python 2.5.2. I used the "ps" command to see the memory usage and also a recipe that I found that counts the number of objects. I attached the pyserial, wxPython code & the recipe. To test them just run each example and run "ps waux | grep python" once in a while, or send the process a SIGUSR1 and it will print in the terminal the object count. The wxCode has a refresh problem, if you use the SIGUSR1/object count method you have to right click on the taskbar icon to have it show up in the terminal. I hope I wrong and the problem is elsewhere though. Thank you very much, Gabriel -------------- next part -------------- A non-text attachment was scrubbed... Name: debug_utils.py Type: text/x-python Size: 1431 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: pyserial_meme_leak_test.py Type: text/x-python Size: 627 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: wxPythonTaskBarTest3.py Type: text/x-python Size: 4487 bytes Desc: not available URL: From steven at REMOVE.THIS.cybersource.com.au Sun Dec 7 22:39:09 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 08 Dec 2008 03:39:09 GMT Subject: Rich Comparisons Gotcha References: Message-ID: On Sun, 07 Dec 2008 16:23:59 +0000, Rasmus Fogh wrote: > Just to keep you from shooting at straw men: > > I would have liked it to be part of the design contract (a convention, > if you like) that > 1) bool(x == y) should return a boolean and never throw an error Can't be done without making bool a "magic function". If x==y raises an exception, bool() won't even be called. The only way around that would be for the Python compiler to recognise bool(x=y) and perform special magic. What if you did this? trueorfalse = bool # I don't like George Boole trueoffalse( [x][0].__class__.__getattr__('__dict__')['__eq__'](y) ) Should that have special magic performed too? Just how much work must the compiler put in to special-casing bool? > 2) x == x return True Which goes against the IEEE 754 floating-point standard. http://grouper.ieee.org/groups/754/ Python used to optimize x==x and always return True. This was removed because it caused problems. > I do *not* say that bool(x) should never throw an error. I do *not* say > that Python should guess a return value if an __eq__ function throws an > error, But to get what you want, the above is implied. I suppose, just barely, that you could avoid making bool() magic and just make if magic. When the compiler sees "if expr": it could swallow all exceptions inside expr and force it to evaluate to True or False. (How? By guessing? Randomly?) This would cause many problems, but it could be done, and much easier than ensuring that bool(x) always succeeds. > only that it should have been considered a bug, or at least bad > form, for __eq__ functions to do so. It's certainly *unusual* for comparisons to return non-bools, but it's not bad form. > What might be a sensible behaviour (unlike your proposed wrapper) What do you dislike about my wrapper class? Perhaps it is fixable. > would be the following: > > def eq(x, y): > if x is y: > return True I've already mentioned NaNs. Sentinel values also sometimes need to compare not equal with themselves. Forcing them to compare equal will cause breakage. > else: > try: > return (x == y) > except Exception: > return False Why False? Why not True? If an error occurs inside __eq__, how do you know that the correct result was False? class Broken(object): def __eq__(self, other): return Treu # oops, raises NameError -- Steven From hamish at valvesoftware.com Wed Dec 31 15:35:20 2008 From: hamish at valvesoftware.com (Hamish McKenzie) Date: Wed, 31 Dec 2008 12:35:20 -0800 Subject: type conversion In-Reply-To: <613a20bf-6e5a-435e-9a83-36766e12f0ab@k8g2000yqn.googlegroups.com> References: <4b7188db-63b2-4ac5-80cb-d1326ca3694a@q26g2000prq.googlegroups.com> <613a20bf-6e5a-435e-9a83-36766e12f0ab@k8g2000yqn.googlegroups.com> Message-ID: sometimes I want to be able to initialize an instance with a variety of different data types. as an obvious example I might want to initialize a 4x4 matrix with either 16 floats, a list/tuple or 16 floats, another matrix or a quaternion. is there any other way to do it other than putting case statements in the __init__ method of the class, or having a Matrix.FromQuaternion( quat )? thx From george.sakkis at gmail.com Tue Dec 2 12:33:00 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 2 Dec 2008 09:33:00 -0800 (PST) Subject: Scanner class References: <737a0550-0b92-4f65-829e-953882d74419@y18g2000yqn.googlegroups.com> Message-ID: <5d73aeb2-a4f1-4dd4-9c16-67db39df9e0c@u14g2000yqg.googlegroups.com> On Dec 1, 5:42?pm, Arnaud Delobelle wrote: > George Sakkis writes: > > Is there any stdlib or (more likely) 3rd party module that provides a > > similar functionality to the java.util.Scanner class [1] ? If not, > > would there be any interest in porting it (with a more Pythonic API of > > course) or are there better alternatives ? > > > George > > > [1]http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html > > Have you looked at: > > >>> import re > >>> re.Scanner > > > > Last time I checked it was undocumented though, although I vaguely > recall a Cookbook recipe. ?Ah here it is: > > http://code.activestate.com/recipes/457664/ Thanks, didn't know about it. I also found Plex [1] which seems more powerful. George [1] http://www.cosc.canterbury.ac.nz/greg.ewing/python/Plex/version/doc/index.html From rhf22 at mole.bio.cam.ac.uk Sat Dec 6 11:42:54 2008 From: rhf22 at mole.bio.cam.ac.uk (Rasmus Fogh) Date: Sat, 6 Dec 2008 16:42:54 +0000 (GMT) Subject: Rich Comparisons Gotcha Message-ID: Dear All, For the first time I have come across a Python feature that seems completely wrong. After the introduction of rich comparisons, equality comparison does not have to return a truth value, and may indeed return nothing at all and throw an error instead. As a result, code like if foo == bar: or foo in alist cannot be relied on to work. This is clearly no accident. According to the documentation all comparison operators are allowed to return non-booleans, or to throw errors. There is explicitly no guarantee that x == x is True. Personally I would like to get these !@#$%&* misfeatures removed, and constrain the __eq__ function to always return a truth value. That is clearly not likely to happen. Unless I have misunderstood something, could somebody explain to me 1) Why was this introduced? I can understand relaxing the restrictions on '<', '<=' etc. - after all you cannot define an ordering for all types of object. But surely you can define an equal/unequal classification for all types of object, if you want to? Is it just the numpy people wanting to type 'a == b' instead of 'equals(a,b)', or is there a better reason? 2) If I want to write generic code, can I somehow work around the fact that if foo == bar: or foo in alist does not work for arbitrary objects? Yours, Rasmus Some details: CCPN has a table display class that maintains a list of arbitrary objects, one per line in the table. The table class is completely generic, and subclassed for individual cases. It contains the code: if foo in tbllist: ... else: ... tbllist.append(foo) ... One day the 'if' statement gave this rather obscure error: "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()" A subclass had used objects passed in from some third party code, and as it turned out foo happened to be a tuple containing a tuple containing a numpy array. Some more precise tests gave the following: # Python 2.5.2 (r252:60911, Jul 31 2008, 17:31:22) # [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 # set up import numpy a = float('NaN') b = float('NaN') ll = [a,b] c = numpy.zeros((2,3)) d = numpy.zeros((2,3)) mm = [c,d] # try NaN print (a == a) # gives False print (a is a) # gives True print (a == b) # gives False print (a is b) # gives False print (a in ll) # gives True print (b in ll) # gives True print (ll.index(a)) # gives 0 print (ll.index(b)) # gives 1 # try numpy array print (c is c) # gives True print (c is d) # gives False print (c in mm) # gives True print (mm.index(c)) # 0 print (c == c) # gives [[ True True True][ True True True]] print (c == d) # gives [[ True True True][ True True True]] print (bool(1 == c)) # raises error - see below print (d in mm) # raises error - see below print (mm.index(d)) # raises error - see below print (c in ll) # raises error - see below print (ll.index(c)) # raises error - see below The error was the same in each case: "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()" --------------------------------------------------------------------------- Dr. Rasmus H. Fogh Email: r.h.fogh at bioc.cam.ac.uk Dept. of Biochemistry, University of Cambridge, 80 Tennis Court Road, Cambridge CB2 1GA, UK. FAX (01223)766002 From nad at acm.org Tue Dec 30 14:13:47 2008 From: nad at acm.org (Ned Deily) Date: Tue, 30 Dec 2008 11:13:47 -0800 Subject: duck typing at will References: <6e1bfdea0812301042x70ab57capf99ce73d364d54db@mail.gmail.com> Message-ID: In article <6e1bfdea0812301042x70ab57capf99ce73d364d54db at mail.gmail.com>, "Jose Mora" wrote: >[...] > I mean, some tasks are rather boring in python when compared with php, > for example, let's imagine we have a dictionary that contains > dictionaries that contain the times that a key appears. We, or at > least I, would like to write something as short as: > > dict[k1][k2] += 1 > > However we will have to do a longer code (this is the smallest code I > could come up with): > > dict = {} > if not k1 in dict: > dict[k1] = {} > if not k2 in dict[k1]: > dict[k1][k2] = 0 > dict[k1][k2] += 1 How about one line plus an import? $ python2.5 Python 2.5.3c1 (release25-maint, Dec 17 2008, 21:50:37) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from collections import defaultdict >>> dic = defaultdict(lambda : defaultdict(int)) >>> dic["spam"]["eggs"] += 1 >>> dic[42][3] += 1 >>> dic[42][3] += 1 >>> dic[42][3] 2 >>> dic defaultdict( at 0x661f0>, {42: defaultdict(, {3: 2}), 'spam': defaultdict(, {'eggs': 1})}) -- Ned Deily, nad at acm.org From gagsl-py2 at yahoo.com.ar Mon Dec 8 02:49:10 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Dec 2008 05:49:10 -0200 Subject: mod_python and files directory References: <200812061326.40226.metebilgin48@gmail.com> Message-ID: En Sat, 06 Dec 2008 09:26:40 -0200, mete escribi?: > but i want to take it somewhere else...i want to it work some other path > in > other system. os.path.dirname(os.path.abspath(__file__)) returns the directory where the current file resides. Execute it early in your code. -- Gabriel Genellina From google at mrabarnett.plus.com Wed Dec 24 13:00:26 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 24 Dec 2008 18:00:26 +0000 Subject: How to change a generator ? In-Reply-To: References: <7F0503CD69378F49BE0DC30661C6CCF6024946E6@enbmail01.lsi.com> <49526B7E.20904@mrabarnett.plus.com> Message-ID: <495278BA.7040301@mrabarnett.plus.com> Gabriel Genellina wrote: > En Wed, 24 Dec 2008 15:03:58 -0200, MRAB > escribi?: > >>> I have a generator whose aim is to returns consecutive lines from a >>> file (the listing below is a simplified version). >>> However, as it is written now, the generator method changes the text >>> file pointer to end of file after first invocation. >>> Namely, the file pointer changes from 0 to 6623 on line 24. >>> >> It might be that the generator method of self.input_file is reading >> the file a chunk at a time for efficiency even though it's yielding a >> line at a time. > > I think this is the case too. > I can think of 3 alternatives: > > a) open the file unbuffered (bufsize=0). But I think this would greatly > decrease performance. > > b) keep track internally of file position (by adding each line length). > The file should be opened in binary mode in this case (to avoid any '\n' > translation). > > c) return line numbers only, instead of file positions. Seeking to a > certain line number requires to re-read the whole file from start; > depending on how often this is required, and how big is the file, this > might be acceptable. > readline() appears to work as expected, leaving the file position at the start of the next line. From linda_octa at yahoo.com Wed Dec 3 07:13:45 2008 From: linda_octa at yahoo.com (Linda Octalina) Date: Wed, 3 Dec 2008 04:13:45 -0800 (PST) Subject: Converting a .xls file to .html References: <12cbbbfc0812030350u26b8f41cw6569d7b17bf21d41@mail.gmail.com> Message-ID: <524848.86507.qm@web30802.mail.mud.yahoo.com> Do you have styles attached to the text of the document in the xls? (bold, italic, etc) if not, then you can just do the mapping by creating table and cells by yourself... (or xslt) {^(00)^} LiNdA OcTaLiNa ---GeEeEee--- ________________________________ From: Jeremiah Dodds To: python-list at python.org Sent: Wednesday, December 3, 2008 9:50:49 PM Subject: Re: Converting a .xls file to .html On Wed, Dec 3, 2008 at 5:54 AM, tarun wrote: Hello All, I've a .xml file (saved as .xls) that can be opened in Microsoft excel. I want to write python code that converts this excel file into .html (so that it can be viewed as is in an explorer). Can any one help? Regards, Tarun -- http://mail.python.org/mailman/listinfo/python-list A quick google search shows http://pyxlreader.sourceforge.net/ , and a few other libraries for reading xls files. I don't use excel, so I can't test it. There may not be a library for going straight from xls -> html, but if you can get xls -> text or a list or whatnot, then you could use pretty much any html generation tool you want on it, python's got plenty of templating libraries available. -------------- next part -------------- An HTML attachment was scrubbed... URL: From federico at linux.com.uy Sat Dec 20 13:14:32 2008 From: federico at linux.com.uy (Federico Moreira) Date: Sat, 20 Dec 2008 21:14:32 +0300 Subject: Generator slower than iterator? In-Reply-To: References: <62013718-57e9-4690-a2be-11e63b9c135b@u18g2000pro.googlegroups.com> Message-ID: Wow, thanks again =) -------------- next part -------------- An HTML attachment was scrubbed... URL: From eckhardt at satorlaser.com Thu Dec 11 03:24:28 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 11 Dec 2008 09:24:28 +0100 Subject: Memory leak when using a C++ module for Python References: Message-ID: Jaume Bonet wrote: > When I test the code from C++ each time I delete a vector the consumed > memory decreases, but it does not happen when the module is called > from python. What is a "vector" for you? Do you mean std::vector? A vector allocated using malloc()? A vector allocated using new? Just provide a simple piece of C++ and Python example code that demonstrates the problem and you will probably get help immediatel. > I've read that the even when you delete the content of the vectors the > memory is not freed when you are working with python. Is that so? There are things like that, but without context it's pretty hard to tell what's going on. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From cjw at ncf.ca Mon Dec 1 19:49:36 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Mon, 01 Dec 2008 19:49:36 -0500 Subject: Multiple Versions of Python on Windows XP Message-ID: Could anyone please point me to documentation on the way the msi installer handles multiple versions eg. Python 2.5, 2.6 and 3.0? What changes are made to the registry? Is there some way to specify a default version in such a way that it can be changed as necessary? PyScripter uses an option to select a version eg. C:\Program Files\PyScripter\PyScripter.exe --python26 but I'm having some trouble with it when I attempt edit a python file from the Windows Explorer. I would appreciate any information. Colin W. From castironpi at gmail.com Wed Dec 17 19:46:32 2008 From: castironpi at gmail.com (Aaron Brady) Date: Wed, 17 Dec 2008 16:46:32 -0800 (PST) Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> Message-ID: On Dec 17, 5:05?pm, "Gabriel Genellina" wrote: > En Wed, 17 Dec 2008 12:21:38 -0200, Jeremy Sanders ? > escribi?: > > > Aaron Brady wrote: > > >> I thought so too. ?The web seems to say that on Linux they are, and on > >> Windows, you need to call DuplicateHandle for it. > > Or set bInheritHandle=True when creating the pipe initially. os.pipe() ? > doesn't do that. > > > I hit this problem - it looks like pipes aren't very versatile on ? > > Windows. > > There's also the complicating factor that the handles in windows aren't ? > > the > > same as the file numbers that Python uses, so you have to convert between > > them. > > > It would be nice if Python created pipes that are properly inheritable by > > default by child processes, as they're mostly used for IPC. > > I'd say it is a bug in os.pipe implementation; they should be inheritable ? > by default, as in posix (after all, the code is in "posixmodule.c"). The code looks like this: ok = CreatePipe(&read, &write, NULL, 0); Py_END_ALLOW_THREADS if (!ok) return win32_error("CreatePipe", NULL); read_fd = _open_osfhandle((Py_intptr_t)read, 0); write_fd = _open_osfhandle((Py_intptr_t)write, 1); 'If lpPipeAttributes is NULL, the handle cannot be inherited.' You could populate a 'SECURITY_ATTRIBUTES' structure, or call DuplicateHandle on both of them. A patch would look like this: SECURITY_ATTRIBUTES sattribs; sattribs.nLength = sizeof(sattribs); sattribs.lpSecurityDescriptor = NULL; sattribs.bInheritHandle = TRUE; ok = CreatePipe(&read, &write, &sattribs, 0); This still doesn't answer whether the file descriptor return by '_open_osfhandle' can be inherited too. From rdmurray at bitdance.com Mon Dec 15 08:03:38 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Mon, 15 Dec 2008 08:03:38 -0500 (EST) Subject: %s place holder does not let me insert ' in an sql query with python. In-Reply-To: <1229345178.31093.24.camel@krishna-laptop> References: <1229345178.31093.24.camel@krishna-laptop> Message-ID: On Mon, 15 Dec 2008 at 18:16, Krishnakant wrote: > how do you let the ' go as a part of the string? > I have used %s as placeholder as in > queryString = "insert into venders values ('%s,%s,%s" % > (field1,field2,field3 ) ... > This is not working for the ' values. This is untested, but I think what you want is: cursor.execute("insert into venders values (?, ?, ?)", field1, field2, field3) This uses parameter binding and should properly quote the values. It's also the "right way" to do it to avoid sql injection attacks and for efficiency if you run the same query multiple times. --RDM From bj_666 at gmx.net Sun Dec 7 09:46:53 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Dec 2008 14:46:53 GMT Subject: how to get a beep, OS independent ? References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> Message-ID: <6q25utFa7km1U1@mid.uni-berlin.de> On Sun, 07 Dec 2008 07:17:30 -0700, Joe Strout wrote: > But invoking the standard system beep is such a basic function that it > ought to be easier than this. I'm pretty sure it's a single OS call on > all platforms. On OS X, for example, it's > > void NSBeep(void); > > declared in NSGraphics.h. I'm sure it's something similarly simple on > other platforms. I'm not so sure. Under Unix the "system beep" is usually in the terminal emulation and triggered by sending '\a' to it. AFAIK there is no standard beep in X-Windows so every desktop environment implements something like audio notifications. Ciao, Marc 'BlackJack' Rintsch From arkanes at gmail.com Thu Dec 4 15:40:16 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 4 Dec 2008 14:40:16 -0600 Subject: To Troll or Not To Troll In-Reply-To: <896B75251BA19745A529B1B867893FA50679D3@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA50679D3@planet.delsci.local> Message-ID: <4866bea60812041240o1f57ba3bq84e9978800a5c17b@mail.gmail.com> On Thu, Dec 4, 2008 at 2:11 PM, Warren DeLano wrote: >> I still would have to call your management of the problem considerably >> into question - your expertise at writing mathematical software may >> not be in question, but your skills and producing and managing a >> software product are. You have nobody at your organization, which >> sells a product that relies on Python, who follows python-dev? Or who >> even reads the changelogs for new python versions? You should have >> known about the "as" keyword change *over a year ago*, even if the >> import bug was masking the deprecation warning. Everything else aside, >> I can't get past that issue with your complaints. I *have* gone back >> now and read all the posts in all the threads and I still have not >> seen a single post from you even hinting that you might have any >> responsibility in the matter. > > Well then, let me set the record straight on that one point: > > I admit that it was entirely my mistake (and mine alone) to implicitly > assume, by adopting such a logging & persistence architecture (dating > back to 1.5.2, mind you!), that new keywords would not be introduced > into the Python language so as to potentially break all existing Python > code. > > Silly me! How unreasonable. > Pythons backwards compatibility policy is available here: http://www.python.org/dev/peps/pep-0005/ From istvan.albert at gmail.com Mon Dec 22 09:33:12 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Mon, 22 Dec 2008 06:33:12 -0800 (PST) Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> <1iscu14.oixxplpgajabN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <9977fd77-9a17-4dcb-9193-49009763c683@33g2000yqm.googlegroups.com> > ---- conclusions ------------------------------- try testing on a large number of candidates that are all (or mostly) positive or all (or mostly) negative and you'll see performance numbers that are substantially different than the ones you report: candidates = range(1000) In general the function sign_1() is expected to be the fastest because in most cases will detect the sign with the fewest operations, it only visits the rest of the comparison when it hits the corner cases. Only if you have lots of +/-0.0 cases will it be slower than the rest, due to having to call an expensive operation. i. From steve at holdenweb.com Fri Dec 19 20:56:57 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 19 Dec 2008 20:56:57 -0500 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> Message-ID: Colin J. Williams wrote: > Steve Holden wrote: >> Thomas Heller wrote: [...] >>> Question from a non-native english speaker: is this now valid english? >>> >>> "One of Python???s great strengths" >>> ^ >>> "and also teaches Python???s functional programming features" >>> ^ >>> "The book???s approach is wholly practical" >>> ^ >> It always has been valid English. The apostrophe is only omitted from >> personal pronouns (hers, its, and so on). >> >> regards >> Steve > > What is the subject of "teaches"? > > I have no problem with the second sentence. > I don't have a problem with any of the three, which are all correct usage. Of course they aren't sentences but fragments thereof, so we don't know the subject of the verb in the second example (though we might guess it's the advertised book). Why would it matter? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From badmuthahubbard at usenet.cnntp.org Fri Dec 19 04:02:35 2008 From: badmuthahubbard at usenet.cnntp.org (Bad Mutha Hubbard) Date: 19 Dec 2008 09:02:35 GMT Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <494b5f47$0$17068$6e1ede2f@read.cnntp.org> Message-ID: <494b632b$0$17070$6e1ede2f@read.cnntp.org> Bad Mutha Hubbard wrote: > Roger wrote: > >> I've done a lot of googling for this topic and I fear that it's not >> possible. I have a widget that is overloaded with several bindings. >> I want to be able to unbind one method form the same Event without >> destroying all the other bindings to the same event that's associated >> to the same widget. >> >> For example: >> >> import Tkinter >> >> def test(): >> print 'test' >> >> def test2(): >> print 'test2' >> >> root = Tkinter.Tk() >> funcid1 = root.bind("<1>", lambda e: test()) >> funcid2 = root.bind("<1>", lambda e: test2(), add='+') >> root.unbind("<1>", funcid2) >> root.mainloop() >> >> When run neither <1> binding will exist against the root because the >> unbind will unbind all the functions associated with that event. >> However, in this example, I only want to unbind test2 not test1. >> >> Any help is greatly appreciated. Thanks! >> Roger. > > I believe you've discovered a bug. Aside from recommending trying > wxWidgets, here's the source of the unbind function in Tkinter.py: > > def unbind(self, sequence, funcid=None): > """Unbind for this widget for event SEQUENCE the > function identified with FUNCID.""" > self.tk.call('bind', self._w, sequence, '') > if funcid: > self.deletecommand(funcid) > > ------------------------------------------- > First, it replaces all bindings for the sequence with the empty string, > i.e., it deletes all bindings for that event unconditionally. THEN it > calls deletecommand() with the funcid, who knows what that does. My Tcl > is not so sharp. > I have an idea for a workaround, let me see if it works... > -Chuckk Alas, my workaround doesn't work either. Tkinter.py also states that calling bind with only an event sequence will return all bindings for that sequence; I was thinking I could then remove the function in question from that list and call bind again with each of the functions in the remaning list as argument. I had high hopes. The return value of calling bind with no target function is just about Tcl nonsense: #!/usr/bin/env python import Tkinter def test(event): print 'test' def test2(event): print 'test2' root = Tkinter.Tk() funcid1 = root.bind("<1>", test) funcid2 = root.bind("<1>", test2, add='+') print funcid1, funcid2 bound = root.bind('') print "bound:", bound #root.unbind("<1>", funcid=funcid2) root.mainloop() --------------------------- Note that I took out the lambdas and gave event arguments to the functions; if you did that on purpose, because you need to call the same functions without events, then just ignore that... SO, the other workaround, which I've used, is to bind the event to a generic function, and have that generic function conditionally call the functions you want. I'll go back and try to make an example from your example. -Chuckk From vkseashoremack at googlemail.com Sat Dec 20 11:56:38 2008 From: vkseashoremack at googlemail.com (vkseashoremack at googlemail.com) Date: Sat, 20 Dec 2008 08:56:38 -0800 (PST) Subject: sapphic er - Free Message-ID: <7cc1abe7-8e1e-4da7-9578-48360e5431b7@g1g2000pra.googlegroups.com> sapphic er . . . *******CLICK HERE******** http://club247.cn/sapphic-er ***************************** . . . . . . . . . . . . sapphic er From news123 at free.fr Sat Dec 6 17:08:08 2008 From: news123 at free.fr (News123) Date: Sat, 06 Dec 2008 23:08:08 +0100 Subject: operators as variables In-Reply-To: References: <103920.71204.qm@web26006.mail.ukl.yahoo.com> Message-ID: <493af7c8$0$2062$426a74cc@news.free.fr> Terry Reedy wrote: > macc_200 wrote: >> Hi, >> just starting programming and have an elementary question after >> playing around with lists but cannot find the answer with googling. >> I have a list of variables and I would like some of those variables to >> be integers and some to be operators so the list would look something >> like [5 * 4 - 4 + 6] and then be able to evaluate the result (i.e. get >> 10). How do you make the interpreter see the operator as that instead >> of a string and just echo the list back to me. > Without sanity checking following would work: a= [ '1' , '+' , '3' ] txt= ' '.join(a) rslt = eval(txt) bye N From bruno.42.desthuilliers at websiteburo.invalid Thu Dec 4 08:32:23 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 04 Dec 2008 14:32:23 +0100 Subject: receive data through a python program from javascript In-Reply-To: <49c9e72f-5032-437d-ac70-8aea009e9278@i24g2000prf.googlegroups.com> References: <49c9e72f-5032-437d-ac70-8aea009e9278@i24g2000prf.googlegroups.com> Message-ID: <4937dbd4$0$12623$426a74cc@news.free.fr> gaurav kashyap a ?crit : > Hi all, > I have a javascript.I want to send some data from this javascript to a > python program that is on zope on my local system... google for Ajax. > What can be the python program Anything on your zope instance that can handle an HTTP request. From the server side POV, how the request is made is mostly (if not totally) irrelevant [1]. [1] ok, you may want the request handler to put something specific in the response... but that's still HTTP anyway). From eric at ericaro.net Fri Dec 5 20:50:07 2008 From: eric at ericaro.net (eric) Date: Fri, 5 Dec 2008 17:50:07 -0800 (PST) Subject: A more pythonic way of writting References: <35d176ed-df5f-46b4-8321-4814fcc4398c@f3g2000yqf.googlegroups.com> <8de7622d-28a7-4f96-9fb0-21cda357dcf3@r36g2000prf.googlegroups.com> <0149aea6$0$20670$c3e8da3@news.astraweb.com> Message-ID: <57e915f5-13a3-4ada-b684-fa7e75405fda@g38g2000yqn.googlegroups.com> On Dec 6, 12:19?am, Steven D'Aprano wrote: > On Fri, 05 Dec 2008 07:44:21 -0800, eric wrote: > > I like to believe that the less the 'debug pointer' stands in the python > > code, the fastest the code is (or is potentially) > > What's a debug pointer? > > Pre-mature optimization is the root of evil in programming. Unless you > have actually *measured* the speed of the code, how do you know you > aren't making it slower instead of faster? > > Experience with other languages often is misleading when programming with > Python. If you are used to programming in C, for example, then you will > tend to program one way because comparisons are fast and moving records > is slow. But in Python, comparisons can be slow and moving records is > fast, so the C programmer's intuitions about "fast code" are often > pessimations instead of optimizations. > > -- > Steven you are right about premature optimization. I cannot disagree. My 'rule of thumb' was more about that: 1/ keep the code the more descriptive and the less procedural as possible. 2/ the less instructions you write, the more optimization you'll get from the others the hypercube function is cool, and I would use it, if I weren't in charge of maintaining the code. I've done some 'timeit' import timeit t1 = timeit.Timer( """ h1 = hypercube(6) """, """def hypercube(ndims): return [[i&mask==mask for mask in [1< Message-ID: <4fb8097d-44b3-418e-84c6-231e5be6487b@a29g2000pra.googlegroups.com> On Dec 10, 10:06?am, prueba... at latinmail.com wrote: > On Dec 10, 6:58?am, Bill McClain > > > > <20080915.20.wmccl... at spamgourmet.com> wrote: > > On 2008-12-10, ajaksu wrote: > > > > On Dec 9, 5:24?pm, Bill McClain <20080915.20.wmccl... at spamgourmet.com> > > > wrote: > > > > On 2008-12-09, MRAB wrote: > > > > > > In Python 2.x unmarked string literals are bytestrings. In Python 3.x > > > > > they're Unicode. The intention is to make the transition from 2.x to 3.x > > > > > easier by adding some features of 3.x to 2.x, but without breaking > > > > > backwards compatibility (not entirely successfully!). > > > > > It is a bit ugly. In 2.6 StringIO won't take bytestrings, so I apply u'x'. But > > > > in 3.0 u'x' will be gone and I'll have to change the code again. > > > Try: > > > from __future__ import unicode_literals > > > That works for: > > > ? ? output.write('First line.\n') > > > ...but not for: > > > ? ?print('Second line.', file=output) > > > Maybe a combination of this and functools.partial as was suggested before. At > > least the necessary edits would be at the top of the program. > > > -Bill > > -- > > Sattre Press ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Tales of Warhttp://sattre-press.com/?? ? ? ? ? ? ? ? ? ? by Lord Dunsany > > i... at sattre-press.com ? ? ? ?http://sattre-press.com/tow.html > > I think this combination might do the trick (I don't have 2.6 to test > it right now): > > from __future__ import print_function > from __future__ import unicode_literals > from functools import partial > import io > print = partial(print, sep=" ", end="\n") > out = io.StringIO() > print("hello", file=out) > > What puzzles me is the documentation in 2.6 and 3.0: > In 2.6 it says: "The StringIO object can accept either Unicode or 8- > bit strings". Why does it fail with old str objects then? > Why is there no documentation for StringIO in 3.0? OK I found StringIO it is called io.StringIO now. From robert.kern at gmail.com Thu Dec 18 17:52:01 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 18 Dec 2008 16:52:01 -0600 Subject: Which sparse matrix package? In-Reply-To: References: <20081218231851.70dd91e2@Schlamber.localdomain> Message-ID: James Mills wrote: > On Fri, Dec 19, 2008 at 8:18 AM, Martin Manns wrote: >> Hi: > > Hi, > >> I am writing a spreadsheet application in Python > > What's wrong with pyspread ? pyspread *is* the spreadsheet application he is writing. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From prologic at shortcircuit.net.au Mon Dec 29 22:23:50 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 30 Dec 2008 13:23:50 +1000 Subject: print a vs print '%s' % a vs print '%f' a In-Reply-To: <5b8d13220812291919h700f1586q5ab68ec6edb927f1@mail.gmail.com> References: <5b8d13220812291919h700f1586q5ab68ec6edb927f1@mail.gmail.com> Message-ID: On Tue, Dec 30, 2008 at 1:19 PM, David Cournapeau wrote: (... snip ...) > print '%f' % a # -> print '1.#INF' Would this not be controlled by: 1. float(a) or a.__float__() 2. tp_print cheers James From tjreedy at udel.edu Fri Dec 19 21:38:12 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 19 Dec 2008 21:38:12 -0500 Subject: Namespaces, multiple assignments, and exec() In-Reply-To: <200812200234.33852.research@johnohagan.com> References: <200812200234.33852.research@johnohagan.com> Message-ID: John O'Hagan wrote: > I have a lot of repetitive assignments to make, within a generator, that use a > function outside the generator: > > var1 = func("var1", args) > var2 = func("var2", args) > var3 = func("var3", args) > etc... > > In each case the args are identical, but the first argument is a string of the > name being assigned. It works fine but I'd like to reduce the clutter by > doing the assignments in a loop. I've tried using exec(): > > for name in name_string_list: > exec(name + ' = func(\"' + name + '\", args)') > > but in the local namespace it doesn't understand func(), and if I give it > globals() it doesn't understand the args, which come from within the > generator. > > What's a good way to do this kind of thing? Put everything in your own namespace myvars={} for name in namelist: myvars[name]=func(name,args) From hrishys at yahoo.co.uk Thu Dec 11 05:52:18 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Thu, 11 Dec 2008 10:52:18 +0000 (GMT) Subject: Equivalent of 'wget' for python? In-Reply-To: Message-ID: <904110.93273.qm@web27404.mail.ukl.yahoo.com> Hi Saju Thanks for helping the oop challenged regards Hrishy --- On Thu, 11/12/08, saju.pillai at gmail.com wrote: > From: saju.pillai at gmail.com > Subject: Re: Equivalent of 'wget' for python? > To: python-list at python.org > Date: Thursday, 11 December, 2008, 10:41 AM > On Dec 11, 3:36?pm, "saju.pil... at gmail.com" > > wrote: > > On Dec 11, 2:36?pm, hrishy > wrote: > > > > > Hi > > > > > Please excuse my OOP but is my understanding > correct > > > > > > urllib.urlretrieve(url_of_zip_file,destination_on_local_filesystem) > > > > > is urllib --->Static Class on which the method > urlretrieve method is invoked ? > > > > No urllib is a "method". Use type(obj) to > find out what python thinks > > typo c/method/module > > > the "type" of that object is. Note that > "object" here is not meant in > > the same sense as the OOP definition. > > > > > > > > > In that case what does the python 3.0 version > mean > > > > > import urllib.request > > > urllib.request.urlretrieve(url, local_file_name) > > > > > urllib -->static class > > > request -->method > > > urlretrieve--> what is this then ? > > > > A 'function'. urllib.request.urlretrieve is > the fully qualified name > > of the function urlretrieve. In other words > urlretrieve lives in the > > urllib.request namespace. > > > > -srp > > > > > > > > > regards > > > Hrishy > > > > > --- On Mon, 8/12/08, Jerry Hill > wrote: > > > > > > From: Jerry Hill > > > > > Subject: Re: Equivalent of 'wget' > for python? > > > > To: python-l... at python.org > > > > Date: Monday, 8 December, 2008, 5:54 PM > > > > On Mon, Dec 8, 2008 at 11:53 AM, r0g > > > > wrote: > > > > > urllib.urlretrieve(url_of_zip_file, > > > > destination_on_local_filesystem). > > > > > > In python 3.0, that appears to be: > > > > > > import urllib.request > > > > urllib.request.urlretrieve(url, > local_file_name) > > > > > > -- > > > > Jerry > > > > -- > > > > >http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From george.sakkis at gmail.com Tue Dec 9 11:57:22 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 9 Dec 2008 08:57:22 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> Message-ID: On Dec 9, 9:28?am, MRAB wrote: > I certainly wouldn't want something like PL/I, where "IF", "THEN" and > "ELSE" could be identifiers, so you could have code like: > > ? ? ?IF IF = THEN THEN > ? ? ? ? ?THEN = ELSE; > ? ? ?ELSE > ? ? ? ? ?ELSE = IF; Although I agree with the sentiment, you can write uncomprehensibly insane code in any language; Python already gives a lot of horsepower to run wild with metaclass magic, bytecode hacking, etc. The fact that you *can* write abominations as the above doesn't mean that you should; the OP's use case - using "foo.as(int)" - is pretty reasonable and readable. I believe the responsibility to not abuse the power of the language should be on the application programmer, not the language designer. George From martin at v.loewis.de Tue Dec 16 16:58:17 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 16 Dec 2008 22:58:17 +0100 Subject: Problem Python 2.6.1 vs 2.6 & pyWin32 In-Reply-To: References: <4946754f$0$19000$426a74cc@news.free.fr> <4946D09F.6050300@v.loewis.de> <4946e680$0$9099$9b622d9e@news.freenet.de> Message-ID: <49482479$0$3997$9b622d9e@news.freenet.de> > Sorry for not being explicit. With "installer" I meant the binary > Windows installer you create with command "python setup.py > bdist_wininst". In the past we've been able to use > "package-version.win32.exe" files created with Python 2.5 on older > version, but that doesn't seem to be case with 2.6. I see. This has nothing to do with the OP's question, then. For Python 2.6, we switched to VS 2008. Apparently, the bdist_msi installers now get linked with the VS 2008 CRT (msvcr90.dll), which must be present on the system (in WinSxS) for the installer to run; one way of installing the CRT is to install Python for all users, another is to install it "just for me", and put \python26 into PATH (so that the installer can find msvcr90.dll). Regards, Martin From no.spam at from.net Thu Dec 11 15:51:40 2008 From: no.spam at from.net (Giuseppe Di Martino) Date: 11 Dec 2008 20:51:40 GMT Subject: Problems running on HP Intel duo core machine References: <200809221443.25765.inq1ltd@inqvista.com> <200812051608.56335.inq1ltd@inqvista.com> Message-ID: <49417d5c$0$18157$4fafbaef@reader3.news.tin.it> Il Thu, 11 Dec 2008 14:58:16 -0500, jim-on-linux ha scritto: > The first module that is imported is win32api. line 8 of that module > adds to the path the module named 'win32api.pyd'. > The import is is completed without error. > > The next module that is imported is win32ui. line 8 of that module adds > to the path a module named 'win32ui.pyd'. > The search for the win32ui.pyd module seems to be the cause of the > problem. > Traceback: > ImportError: Dll load failed: The specified module could not be found. > > Both modules 'win32api.pyd' and win32ui.pyd are in the same directory. Have you checked if there is a file named "win32api.pyd" somewhere in the system path (c:\windows\, c:\windows\system32, etc. ) ? Try to add the path to the folder containing your win32api.pyd and win32ui.pyd to the PATH enviroinment variable, before running your application. Giuseppe From rt8396 at gmail.com Mon Dec 22 22:03:09 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 19:03:09 -0800 (PST) Subject: noob trouble with IDLE References: <68f1552e0812211346i96bf18hf28dccc1f8dd1a99@mail.gmail.com> Message-ID: <16bf1bde-af9e-45bf-acfd-e776442000ac@q30g2000vbn.googlegroups.com> Yea, if you use Tkinter in concert with IDLE, your script will lock up. From rcdailey at gmail.com Mon Dec 8 22:10:00 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 8 Dec 2008 19:10:00 -0800 (PST) Subject: RuntimeError: dictionary changed size during iteration References: <274eb282-1635-40ca-95af-b82271c57802@v4g2000yqa.googlegroups.com> Message-ID: On Dec 8, 6:26?pm, Terry Reedy wrote: > Robert Dailey wrote: > > stuff = vars() > > ?>>> vars() is globals() > True > > > for key in stuff: > > You just changed globals, which is aliased as stuff. > Stuff changes. > > > ? ? print( key, '--', stuff[key] ) > > > I get the following error message: > > ('CopyEmotionFX', '--', ) > > Traceback (most recent call last): > > ? File "C:\IT\work\jewett\depends.py", line 12, in > > ? ? for key in stuff: > > RuntimeError: dictionary changed size during iteration > > > Why is this happening? > > How am I changing globals()? I'm simply iterating the keys in the dict. Can someone explain what is going on please? From notvalid2 at sbcglobal.net Wed Dec 17 08:02:55 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Wed, 17 Dec 2008 05:02:55 -0800 Subject: WinMerge--B/W Shading of Printed Copy to Show Differences? In-Reply-To: References: <3jX1l.6876$pr6.3299@flpi149.ffdc.sbc.com> Message-ID: W. eWatson wrote: > Jason Scheirer wrote: >> On Dec 16, 3:56 pm, "W. eWatson" wrote: >>> Is there a way to highlight differences between the two files when >>> printing >>> in b/w? Help suggests there may be some texturing, but all I see is >>> color >>> choices. >>> -- >>> W. eWatson >>> >>> (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) >>> Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet >>> >>> Web Page: >> >> WinMerge is written in C++ and not even remotely related to Python. > Well, yes, but it has applicability to Python (and maybe other > languages) in that I can use it to find differences between two sets of > code. > > If not here, where? comp.lang.??? ? > Hmm, I guess no one here uses it. I did find a winmerge mailing list, so will work it out there. -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From cmr.pent at gmail.com Mon Dec 22 13:59:46 2008 From: cmr.pent at gmail.com (=?UTF-8?B?0JDQvdC00YDQtdC5INCf0LDRgNCw0LzQvtC90L7Qsg==?=) Date: Mon, 22 Dec 2008 21:59:46 +0300 Subject: Calling ImageMagick's convert In-Reply-To: <47c890dc0812220033g49d35ae9w24aede0b438adb4b@mail.gmail.com> References: <47c890dc0812220033g49d35ae9w24aede0b438adb4b@mail.gmail.com> Message-ID: <5f0660120812221059w32175880ya9aac8982640365f@mail.gmail.com> 2008/12/22 Chris Rebert : > I think this needs to be: > > subprocess.call(['convert', 'in.png', '-resize', '640x480', 'out.png']) > > Otherwise, it gets '-resize 640x480' as a single escaped option when > it's really 2 options, which is the error message you're getting. > You have to split the arguments up just like the shell would, which > basically means at whitespace unless quoting is used, which is not the > case here. > > Cheers, > Chris It worked, many thanks! Andrey From fred.sells at adventistcare.org Wed Dec 24 23:24:35 2008 From: fred.sells at adventistcare.org (Sells, Fred) Date: Wed, 24 Dec 2008 23:24:35 -0500 Subject: Python advocacy . HELP! In-Reply-To: <5f8c1a52-545e-402e-863a-acdf23d04c78@h20g2000yqn.googlegroups.com> References: <5f8c1a52-545e-402e-863a-acdf23d04c78@h20g2000yqn.googlegroups.com> Message-ID: Prof. Kanabar (kanabar.bu.edu) is planning to offer a python course there soon. Perhaps he could help. Tell him you got his name from me (Fred Sells). > -----Original Message----- > From: python-list-bounces+frsells=adventistcare.org at python.org > [mailto:python-list-bounces+frsells=adventistcare.org at python.org] On > Behalf Of Michael_D_G > Sent: Thursday, December 04, 2008 1:52 AM > To: python-list at python.org > Subject: Python advocacy . HELP! > > > I am a faculty member of a cs department. We currently teach C++ in > our intro to programming course. I am teaching this class and it seems > to me that we would be much better served teaching python in the intro > course, C++ for Data structures, as we do now, and Java in object > oriented programming, as we do now. > Some of my colleagues agree with me but some still see python as a > niche language and don't understand > how we could teach anything beyond C, C++ or Java. > > I have looked at several interesting academic papers, on doing just > this approach. I have also looked through the > python web page to get examples of industry players using python in a > non-trivial way. Yes, I know, Google, > Microsoft, Sun, CIA website running on Plone, NOAA, NASA. If anyone > has any recent articles, > or if anyone on the list is at a fortune 500 company, how do I refute > the notion that Python > is a "marginal" language because according to TOBIE it only less than > a 6% market share. > > -michael > -- > http://mail.python.org/mailman/listinfo/python-list From bradcausey at gmail.com Wed Dec 24 13:27:51 2008 From: bradcausey at gmail.com (Brad Causey) Date: Wed, 24 Dec 2008 12:27:51 -0600 Subject: VERY simple string comparison issue Message-ID: <89f89940812241027o40e3d079v9f9d76e76b1af4a6@mail.gmail.com> Python Version: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 List, I am trying to do some basic log parsing, and well, I am absolutely floored at this seemingly simple problem. I am by no means a novice in python, but yet this is really stumping me. I have extracted the pertinent code snippets and modified them to function as a standalone script. Basically I am reading a log file ( in this case, testlog.log) for entries and comparing them to entries in a safe list (in this case, safelist.lst). I have spent numerous hours doing this several ways and this is the most simple way I can come up with: import string safelistfh = file('safelist.lst', 'r') safelist = safelistfh.readlines() logfh = file('testlog.log', 'r') loglines = logfh.readlines() def safecheck(line): for entry in safelist: print 'I am searching for\n' print entry print '\n' print 'to exist in\n' print line comp = line.find(entry) if comp <> -1: out = 'Failed' else: out = 'Passed' return out for log in loglines: finalentry = safecheck(log) if finalentry == 'Failed': print 'This is an internal site' else: print 'This is an external site' The contents of the two files are as follows: http://www.mysite.com http://www.mysite.com/images/homepage/xmlslideshow-personal.swf It seems that no matter what I do, I can't get this to fail the " if comp <> -1:" check. (My goal is for the check to fail so that I know this is just a URL to a safe[internal] site) My assumption is that the HTTP:// is somehow affecting the searching capabilities of the string.find function. But I can't seem to locate any documentation online that outlines restrictions when using special characters. Any thoughts? Thanks! -Brad -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at mrabarnett.plus.com Tue Dec 9 13:40:03 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 09 Dec 2008 18:40:03 +0000 Subject: "as" keyword woes In-Reply-To: References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> Message-ID: <493EBB83.5080108@mrabarnett.plus.com> Aaron Brady wrote: > On Dec 9, 8:28 am, MRAB wrote: > snip >> In some languages (I think Delphi is one of them - it's been a while!) >> some words which would normally be identifiers have a special meaning in >> certain contexts, but the syntax precludes any ambiguity, and not in a >> difficult way. "as" in Python was one of those. >> >> I certainly wouldn't want something like PL/I, where "IF", "THEN" and >> "ELSE" could be identifiers, so you could have code like: >> >> IF IF = THEN THEN >> THEN = ELSE; >> ELSE >> ELSE = IF; >> >> See http://en.wikipedia.org/wiki/PL/I_(programming_language). > snip > > The following are semantically equivalent: > > I certainly wouldn't want something like PL/I, where "IF", "THEN" and > "ELSE" could be identifiers. > > I wouldn't want something like PL/I, where "IF", "THEN" and "ELSE" > could be identifiers. > > That is, 'certainly' doesn't change the meaning of your statement > any. You wouldn't want it, but King George III didn't want the > American Revolution. > It's called emphasis. > You wouldn't want it. What does that mean for me (the generic > reader), and Python? What can I learn from that fact? > From wuwei23 at gmail.com Thu Dec 4 07:28:03 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 4 Dec 2008 04:28:03 -0800 (PST) Subject: performance question: dictionary or list, float or string? References: <434bf4e3-54f4-4e15-b8b0-510a988f25b8@z1g2000yqn.googlegroups.com> <904a19e9-3800-4d61-aea0-4bdabc0674fa@j32g2000yqn.googlegroups.com> <842b13b2-1df5-4b34-af14-7b082970682b@41g2000yqf.googlegroups.com> Message-ID: <796f927e-5def-4637-bb31-88965b9bcb44@z28g2000prd.googlegroups.com> On Dec 4, 8:12?pm, bkamr... at gmail.com wrote: > About the piece of code you posted, there is something I don't > understand. > > ? ? ? ? for i, line in data: > > where data is a file object. Is it legal to write that? > I believe it results in "too many values to unpack" or do I miss > something? >From the context, my guess is Matimus intended to write: for i, line in enumerate(data): From gagsl-py2 at yahoo.com.ar Sat Dec 6 13:47:40 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 06 Dec 2008 16:47:40 -0200 Subject: Python calling COM compliant .dll References: <740322.52556.qm@web26308.mail.ukl.yahoo.com> Message-ID: En Wed, 03 Dec 2008 16:20:27 -0200, David Shi escribi?: > I am looking for a concise working example of Python script calling COM > compliant .dll. The best source of information is Mark Hammond's book "Python Programming in Win32". The sample chapters available are about using COM objects, AFAIR. -- Gabriel Genellina From nick at craig-wood.com Fri Dec 12 11:30:54 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 12 Dec 2008 10:30:54 -0600 Subject: How do I manually uninstall setuptools (installed by egg)? References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> <47c890dc0812091904p12e75510sbe0b8858eb2f6d9e@mail.gmail.com> Message-ID: David Cournapeau wrote: > On Thu, Dec 11, 2008 at 10:30 PM, Nick Craig-Wood wrote: > > David Cournapeau wrote: > >> On Wed, Dec 10, 2008 at 12:04 PM, Chris Rebert wrote: > >> > On Tue, Dec 9, 2008 at 6:49 PM, wrote: > >> >> On Ubuntu, I accidentally manually installed setuptools > >> >> http://pypi.python.org/pypi/setuptools/0.6c9 (by running the .egg file > >> >> as a shell script via sudo), and now realize I should just be using > >> >> apt to take care of my system Python packages. > >> > > >> > Really, why? setuptools has more Python packages/programs available > >> > and updates faster than Debian. > >> > It's also likely that some of the Debian Python packages are installed > >> > using setuptools anyway. > >> > So, why do you think apt and not setuptools is The Right Way(tm)? > >> > >> Setuptools is certainly not the right way to install packages > >> system-wide on debian, it is very likely to break the whole thing. > > > > It wouldn't be too difficult to make a .deb target which would collect > > all the files that did get installed into a package. It would be a > > rather rough and ready package but would do the job. > > Depends what you mean by would do the job: rather rough certainly does > not mean "would do the job" for something as essential as a package > IMO. Essentially a package has files in it in a fixed possition in the filesystem. The package manager's (dpkg at this level) job is to keep track of those file and tell you about conflicts. You can use alien to turn a tar.gz into a perfectly usable debian package. It won't have dependencies, or help or any of the other things a package needs to be a proper package, but it satisfies my basic needs that all software is installed as packages, so it can be uninstalled cleanly. > > The .deb would then be uninstallable in the usual (dpkg --purge) way. > > > > Did anyone think about that? > > Yes, there is stddeb which does that (make a .deb package from a > setuptools package). Cool, I've not seen that before. Probably because it isn't in debian! > > easy_install can do that I think... > > Not without a lot of hoola, unfortunately; for example, it breaks > stow, so I have to use specialy scripts to circumvent the damn thing > and make it what I tell him to do. I never understood what's easy > about easy install: it is broken in so many ways, and has caused me so > many pains - even when I was not using - that I do not trust it at > all. I only use it to download packages (and even then it manage to > fail more than work), and always install them from setup.py afterwards > (at which step I of course also have to circumvent setuptools if the > package uses setuptools). ;-) As a mostly linux developer I always install stuff in packages if possible. Failing that I'll use bdist_rpm then alien to convert to a deb which works well enough I find. However when I have to make my stuff work on Windows, I find easy_install to be a fantastic timesaver as compared to looking for the package on a web site, downloading it, unpacking it installing it and then repeating for all the dependencies. easy_install is a long way from being a proper package manager though :-( I guess it is aiming at the same territory as the cpan installer with perl. My experiences with that is that it works very well, but again splatters untracked files all over your filesystem. Debian comes with dh-make-perl which can use CPAN directly to make .debs which works quite well. Something similar based on easy_install for python would be ideal. It looks like stdeb could become that one day. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From steve at holdenweb.com Tue Dec 23 09:19:26 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 23 Dec 2008 09:19:26 -0500 Subject: On Whose Desktop In-Reply-To: <4950db7e$0$14770$426a74cc@news.free.fr> References: <4950db7e$0$14770$426a74cc@news.free.fr> Message-ID: Fuzzyman wrote: > On Dec 23, 12:06 pm, Steve Holden wrote: >> Thanks to Barry Warsaw the "On Your Desktop" blog now has a new entry: >> >> http://onyourdesktop.blogspot.com/ >> >> Who would you like to see profiled next? > > Guido (of course), Brett Cannon, Martin v Loewis, Jim Hugunin, Ted > Leung, Dino Viehland (core developer of IronPython), Titus Brown, Ivan > Kristic, Mark Shuttleworth, Tim Golden, Michele Simionato, Thomas > Heller, Greg Ewing - any and all of these would be great. > > Any women in Python you could ask - how about Anna Ravenscroft? > Bruno Desthuilliers wrote: > > The effbot ? > skip at pobox.com wrote: > Maybe Martin v. Loewis? He contributes so much to Python. I met him once > several years ago at a Python conference (or maybe it was still just a > workshop then), but beyond seeing his titanic contributions to Python, I > know little about the guy. I hope *everyone* knows that Martin was the winner of this year's Frank Willison Award: http://www.python.org/community/awards/frank-willison/#martin-von-l-wis-2008 Great! Keep the suggestions coming, please! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From google at mrabarnett.plus.com Wed Dec 10 22:51:10 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 11 Dec 2008 03:51:10 +0000 Subject: Python is slow In-Reply-To: References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> Message-ID: <49408E2E.1000302@mrabarnett.plus.com> Benjamin Kaplan wrote: > > > On Wed, Dec 10, 2008 at 10:25 PM, Carl Banks > wrote: > > On Dec 10, 12:42 pm, cm_gui > wrote: > > Python is SLOW. And I am not comparing it with compiled languages > > like C. > > Python is even slower than PHP! > > > cm_gui is TROLL. And I am not compring it with bots like Aaron > Castironpi Brody. cm_gui is even troller than Xah Lee! > > > actually Castironpi has made some coherent replies lately. Xah Lee is > worse than ever though. > Perhaps there's a Law of Conservation of Trolling. :-) From hakan.hagenrud at ikea.com Mon Dec 8 04:26:05 2008 From: hakan.hagenrud at ikea.com (=?ISO-8859-1?Q?H=E5kan_Hagenrud?=) Date: Mon, 8 Dec 2008 10:26:05 +0100 Subject: Shutdown Mac OSX computer using python Message-ID: <0D77FD19-CA33-48BC-9D7D-72E336143D1C@ikea.com> Hello, i'm a python noob! But I would like to shutdown a 10.5.x mac computer using python (2.5.1) this is my code: #!/usr/bin/python import SystemEvents down = SystemEvents.Power_Suite.Power_Suite_Events() down.shut_down() the last call needs an additional argument, I cant find any documentation about this. Anybody knows? Thank you! H?kan Hagenrud From deets at nospam.web.de Sun Dec 7 16:21:46 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 07 Dec 2008 22:21:46 +0100 Subject: how to get a beep, OS independent ? In-Reply-To: <6q2sjfFai65qU1@mid.individual.net> References: <6q2sjfFai65qU1@mid.individual.net> Message-ID: <6q2t3aFajp2pU1@mid.uni-berlin.de> Peter Pearson schrieb: > On Sun, 07 Dec 2008 00:40:53 +0100, Stef Mientki wrote: >> I want to give a small beep, >> for windows there's message-beep, >> and there seems to be something like " curses" , >> but that package seems to be totally broken in P2.5 for windows. >> >> Any other suggestions ? > > Many people have suggested sending an ASCII 07 to your > terminal window, but sometimes you don't have a terminal > window. > > Then there's the question of using the sound card versus > using the PC speaker. Too complicated for me. > > I used a kluge: a short C program that beeps the way I want, > in this case using ioctl(fd,KDMKTONE,arg) on /dev/tty0 (this > is Linux). The program has enough privileges to execute > even when run by unprivileged users, and of course can be > invoked by whatever language you're working in. This can be done with python also, no need for C. See the module fcntl. The privilege-problem persists of course. Diez From philip.slate at gmail.com Sun Dec 7 17:23:50 2008 From: philip.slate at gmail.com (Philip Slate) Date: Sun, 7 Dec 2008 14:23:50 -0800 (PST) Subject: Guido's new method definition idea References: <493a9fed$0$18973$426a34cc@news.free.fr> <493c1ff6$0$4942$426a34cc@news.free.fr> Message-ID: <49d12ec1-2be9-497b-80bc-9f0402a9086d@s20g2000yqh.googlegroups.com> On Dec 7, 1:13?pm, Bruno Desthuilliers wrote: > > and friendlier to newbies. > > I'd rather say "more acceptable to java-brainwashed developpers". And I'd rather say you're trolling, but that's ok since you're preaching to the converted. You conveniently forgot to mention the C++/ Eiffel/Smalltalk/pretty-much-every-OO-lang "brainwashed" developers too. In reality Python, with its kludgy OO and objects being essentially glorified dicts, is the odd one out, not the other way around. From walterbyrd at iname.com Sat Dec 20 18:14:44 2008 From: walterbyrd at iname.com (walterbyrd) Date: Sat, 20 Dec 2008 15:14:44 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> On Dec 19, 12:43?pm, excord80 wrote: > Also, I like having only *one* special symbol (`%') to worry > about in my strings instead of two (`{' and `}'). > Actually the new way has, at least three special symbols: ( '{', '}' , '.') as well as the method name "format" so "%s=%s" % (k, v) for k, v in params.items() becomes: "{0}={1}".format((k, v) for k, v in params.items()) or something like that. From bearophileHUGS at lycos.com Thu Dec 11 13:39:03 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 11 Dec 2008 10:39:03 -0800 (PST) Subject: dictionary idiom needed References: <383976cf-53fb-48e4-b028-8f568468ce77@r36g2000prf.googlegroups.com> <0c4950c1-4833-40c7-ac19-260b61d5289f@k24g2000pri.googlegroups.com> Message-ID: bearophile: > you can do with a dict > that has the tuple ('word', 'tagB') as key, and as value has a > collections.defaultdict(int) that maps 'tagB' to its count. Where's 'tagA'? Probably I haven't understood your problem well enough. I need a better example of your data and what you need... Sorry, bye, bearophile From excord80 at gmail.com Sun Dec 7 19:43:05 2008 From: excord80 at gmail.com (excord80 at gmail.com) Date: Sun, 7 Dec 2008 16:43:05 -0800 (PST) Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? Message-ID: Trying to decide which to get started with. Can anyone suggest some pros and cons to each of them? Would PyOpenGL be in the same camp as Pygame and pyglet? Do either of Pygame or pyglet make use of PyOpenGL behind the scenes? From arnodel at googlemail.com Mon Dec 1 17:42:24 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 01 Dec 2008 22:42:24 +0000 Subject: Scanner class References: <737a0550-0b92-4f65-829e-953882d74419@y18g2000yqn.googlegroups.com> Message-ID: George Sakkis writes: > Is there any stdlib or (more likely) 3rd party module that provides a > similar functionality to the java.util.Scanner class [1] ? If not, > would there be any interest in porting it (with a more Pythonic API of > course) or are there better alternatives ? > > George > > [1] http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html Have you looked at: >>> import re >>> re.Scanner Last time I checked it was undocumented though, although I vaguely recall a Cookbook recipe. Ah here it is: http://code.activestate.com/recipes/457664/ HTH -- Arnaud From john.rominsky at gmail.com Wed Dec 17 12:16:35 2008 From: john.rominsky at gmail.com (Rominsky) Date: Wed, 17 Dec 2008 09:16:35 -0800 (PST) Subject: getting object instead of string from dir() Message-ID: I am trying to use dir to generate a list of methods, variables, etc. I would like to be able to go through the list and seperate the objects by type using the type() command, but the dir command returns a list of strings. When I ask for the type of an element, the answer is always string. How do I point at the variables themselves. A quick example is: a = 5 b = 2.0 c = 'c' lst = dir() for el in lst: print type(el) Right now I am understandably getting all types being output as strings, how do i get the type of the actual objects returned from dir ()? From riklaunim at gmail.com Wed Dec 31 12:08:46 2008 From: riklaunim at gmail.com (riklaunim at gmail.com) Date: Wed, 31 Dec 2008 09:08:46 -0800 (PST) Subject: Desktop/File management support on MS Windows Message-ID: <4b7188db-63b2-4ac5-80cb-d1326ca3694a@q26g2000prq.googlegroups.com> Are there any Python libraries that can trash files (move to Trash, not delete) or for example return a list of applications that can open given file? I can't find anything related to this for Windows. From rocky at panix.com Mon Dec 29 21:13:55 2008 From: rocky at panix.com (R. Bernstein) Date: Mon, 29 Dec 2008 21:13:55 -0500 Subject: How do I DRY the following code? Message-ID: How do I DRY the following code? class C(): def f1(self, arg1, arg2=None, globals=None, locals=None): ... unique stuff #1 ... ... some common stuff #1 ... ret = eval(args, globals, locals) ... more stuff #2 ... return retval def f2(self, arg1, arg2=None, *args, **kwds): ... unique stuff #2 ... ... some common stuff #1 ... ret = arg1(args, *args, **kwds) ... more common stuff #2 ... return retval def f3(self, arg1, globals=None, locals=None): ... unique stuff #3 ... ... some common stuff #1 ... exec cmd in globals, locals ... more common stuff #2 ... return None def f4(self, arg1, globals=None, locals=None): ... unique stuff #4 ... ... some common stuff #1 ... execfile(args, globals, locals) ... more stuff #2 ... return None f1(...): "Docstring f1" c = C() return c.f1(...) f2(...): "Docstring f2" c = C() return c.f2(...) f3(...): "Docstring f3" c = C() return c.f3(...) Above there are two kinds of duplication: that within class C and that outside which creates an instance of the class C and calls the corresponding method. For the outside duplication, I considered trying: _call_internal = lambda name, *args, **kwds \ c = C() \ fn = getattr(c, name) \ return fn(*args, **kwds) f1 = lambda arg, arg2=None, globals=None, locals=None: _call_internal('f1', ...) f1.__doc__ = """ Docstring f1 """ f2= lambda arg, arg1=None, arg2, *args, **kwds: _call_internal('f2', ...) f2.__doc__ = """ Docstring f2 """ However this strikes me as a little bit cumbersome, and harder understand and maintain than the straightforward duplicated code. Thoughts? Lest the above be too abstract, those who want to look at the full (and redundant) code: http://code.google.com/p/pydbg/source/browse/trunk/api/pydbg/api/debugger.py From tjreedy at udel.edu Mon Dec 15 13:30:08 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 15 Dec 2008 13:30:08 -0500 Subject: stable algorithm with complexity O(n) In-Reply-To: <5504f9ac0812150828m14f6999ak6112c5975042dc88@mail.gmail.com> References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> <015612ac$0$20639$c3e8da3@news.astraweb.com> <52cfb77e-4baf-4fba-8eac-cc6c7ddb5be5@k1g2000prb.googlegroups.com> <5504f9ac0812150828m14f6999ak6112c5975042dc88@mail.gmail.com> Message-ID: Dan Upton wrote: > And if n is small and sparse (ie, k > n) , O(k*n) for radix sort could > be worse than O(n^2). You could also ask why people make such a big > deal about quicksort over mergesort, since mergesort has a guaranteed > O(n log n) time whereas quicksort can be O(n^2) on pathological cases. Python's current list.sort uses mergesort because it better exploits existing structure in a list. > I think I remember learning in my algorithms class that for small > sorts (n < ~40) , bubblesort can actually be the fastest (or close to > the fastest) in terms of wall-clock time because it has a relatively > small constant factor in its O(n^2) complexity. It uses binary insert sort for n < 64 (chosen empirically) . That also does O(n logn) comparisons and is only O(n**2) for data movement, which a decent C compiler translates into fast block-move assembly instructions. tjr From icanbob at gmail.com Sun Dec 14 07:32:46 2008 From: icanbob at gmail.com (bobicanprogram) Date: Sun, 14 Dec 2008 04:32:46 -0800 (PST) Subject: subprocess to C program References: <0ebd59c5-95a1-42d4-b597-d1c248490b8e@y1g2000pra.googlegroups.com> <8MidneyhDfIG-9nUnZ2dnUVZ_uadnZ2d@posted.visi> <36656830-63a8-479c-8c46-525f2b55eeea@z28g2000prd.googlegroups.com> Message-ID: <6e8f11eb-d773-4ffc-851c-a381228d4ae2@v4g2000yqa.googlegroups.com> On Dec 13, 10:09 pm, MRAB wrote: > Aaron Brady wrote: > > On Dec 13, 7:51 pm, Grant Edwards wrote: > >> On 2008-12-14, MRAB wrote: > > >>>> I am writing a C process and I want to read data from a file that I > >>>> write to in Python. I'm creating a pipe in Python, passing it to the > >>>> C process, and calling '_read'. It gives me error 9, bad file number. > > snip > >>>> meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9. I want 'ct' > >>>> to be 11 at this point. Thanks in advance. > >>> It looks like the ids aren't system global. > >> They certainly aren't in Unix: Their a property of the process. > > >> -- > >> Grant > > > I'm not on Unix. It has to be possible somehow. Do I need to set > > permissions on the IDs? Are Stdin and Stdout my only options? Or > > does Popen prevent sharing IDs somehow? > > You'd be better off using sockets. You might also consider using SIMPL (http://www.icanprogram.com/simpl) SIMPL has had a Python interface for about 5 years now. There is an online tutorial here. (http://www.icanprogram.com/06py/main.html) In one of your responses you mentioned that you were not on Unix (and I presume Linux). SIMPL-Python has recently been extended to work transparently from a Windows OS as well. bob SIMPL project coordinator From febaen at gmail.com Fri Dec 12 06:42:55 2008 From: febaen at gmail.com (febaen at gmail.com) Date: Fri, 12 Dec 2008 03:42:55 -0800 (PST) Subject: (Very Newbie) Problems defining a variable Message-ID: #!/usr/bin/python #Py3k, UTF-8 bank = int(input("How much money is in your account?\n>>")) target = int(input("How much money would you like to earn each year? \n>>")) interest = 0 i = 0 while interest < target: #determine the interest rate to use if bank >= 9999: rate = 0.006 elif bank >= 10000 and bank <= 24999: rate = 0.0085 elif bank >= 25000 and bank <= 49999: rate = 0.0124 elif bank >= 50000 and bank <= 99999: rate = 0.0149 elif bank >= 100000: rate = 0.0173 #Now that we know what interest rate to use, apply it... lastbank = bank #To calculate interest... bank += (bank * rate) #Update earnings... interest = bank - lastbank #And figure out how much interest is made! i += 1 #So we can see which year a calculation represents print("Year %s, at %s rate: %s paid, %s in bank." % (i, rate, interest, bank)) I wrote this expanding off an 'interest' exercise in a tutorial, which was fairly simple (assume %1, calculate for ten years). It's intended to take how much the user has in the bank and determine how long it will be until it generates a certain amount in interest each year. The problem is that rates are not solid, and increase at certain points. I put the rates from the basic account option at my bank in as an example. I'm pretty certain that that is also the problem in the code. I'm pretty sure it's a problem with the 'if' statements', and it looks like it's one of those mistakes that's so simple you look back on it and laugh at yourself. If you put in a bank number <= 9999, it fails, saying "NameError: name 'rate' is not defined". If you put in one higher, it runs correctly, but thinks that the rate is 0.006 I tried def'ing a function for it, which didn't work any better. I'm having a hard time figuring out exactly why it is those if statements are wrong. From ethan at stoneleaf.us Mon Dec 8 09:44:53 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 08 Dec 2008 06:44:53 -0800 Subject: dBase III files and Visual Foxpro 6 files In-Reply-To: <917126a8-c2c6-49c5-b001-07c953992dac@q26g2000prq.googlegroups.com> References: <917126a8-c2c6-49c5-b001-07c953992dac@q26g2000prq.googlegroups.com> Message-ID: <493D32E5.1030000@stoneleaf.us> sniffer wrote: > On Dec 8, 12:53 pm, Ethan Furman wrote: >> Greetings All! >> >> I nearly have support complete for dBase III dbf/dbt files -- just >> wrapping up support for dates. The null value has been a hindrance for >> awhile but I nearly have that solved as well. >> >> For any who know of a cool dbf module already in existence for dBase III >> and Visual Foxpro -- where were you six months ago when I was searching? >> ;) Seriously, though, this has been a great learning experience for me. >> >> As I said -- dbf/dbt files are 99% ready. idx files -- no support: for >> my purposes I just don't need them. I've found no problem in loading >> tables up to 300,000 records with 50 fields per record, and re-ordering >> them on the fly in memory. >> >> However, after putting much effort into this code, and wanting it to be >> useful to others in the community, are there others who work with dbf >> files that would need idx/cdx support? Or tables so large they won't >> fit comfortably into memory? >> >> ~ethan~ > > hi ethan, > great to hear that someone has finally written something for > interacting with vfp6 data,when do you plan to release it Well, let's see... A couple more days to have the datetime bit worked out (I don't support datetimes prior to 1981 in vfp tables), longer for currency types, and of course, no idx/cdx support at this point. Tell you what -- I'll trade you a copy of the code as it stands with date and datetime working for null values, for an answer of whether you need idx/cdx file support. ;) ~ethan~ From timr at probo.com Sun Dec 28 00:46:29 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 28 Dec 2008 05:46:29 GMT Subject: parsing csv files class References: Message-ID: "alex goretoy" wrote: > >class parsercsvy(object): > """Return a line from a csv file or total amount of lines""" > def __init__(self,file_name=""): > self.func_me_color="white_on_black" > self.soc=stdout_colours.stdout_colors() > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > self.filename = file_name > self.buffer = [] > self.bufferp= [] > if string.find(self.filename,"http") != -1: > resp=urllib2.urlopen(self.filename) > file=resp.read() > lfi=len(string.split(self.filename,"/")) > filename = "/tmp/"+string.split(self.filename,"/")[lfi-1] Style issue: unless you are running Python 1.x, you virtually never need to import the "string" module. Also, you can always refer to the last element of a list or tuple by using [-1]: parts = self.filename.split( "/" ) filename = "/tmp/" + parts[-1] > def parse(self,filename,ret=0): > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > i = 0 > try: > reader = csv.reader(file(filename, "rb")) > try: > for row in reader: > self.buffer.append(row) > s,a=[],{} > > for j in range(len(self.buffer[0])): > a[self.buffer[0][j]]=row[j] > self.bufferp.append(a) > i+=1 > self.total = i-1 You might consider keeping the header line separate. reader = csv.reader(open(filename, "rb")) header = reader.next() self.buffer = list(reader) self.bufferp = [ dict( zip( header, line ) ) for line in reader ] self.header = header Also, you don't really need a separate "total" variable, since it's equal to len(self.buffer). > def total(self): > """return total number of lines in csv file""" > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > self.soc.me_him(['RETURN:',self.total,__name__],self.func_me_color) > return self.total There's a problem here, as this was originally written. "self.total" starts out being a function (this one here). But after self.parse runs, "self.total" will be an integer, and this function is lost. You need to decide whether you want users to just access the self.total integer, or force them to use the function. In the latter case, you can change the counter to self._total. On the other hand, the self.total counter is unnecessary: def total(self): return len(self.buffer) > def find_and_replace(self,li,fi,re): > """ > find and replace a string inside a string, return list > find_and_replace(list,find,replace) > """ > this=[] > for l in li: ># found_index=string.find(l,fi) > this.append(l.replace(fi,re)) > return this def find_and_replace(self,li,fi,re): return [l.replace(fi,re) for l in li] I'm not sure why this is a member of the class; it doesn't use any of the members. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From duncan.booth at invalid.invalid Tue Dec 9 13:55:05 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Dec 2008 18:55:05 GMT Subject: When (and why) to use del? References: Message-ID: Albert Hopkins wrote: > def otherfunction(): > try: > # some stuff > except SomeException, e: > # more stuff > del e > return > > > I think this looks ugly, but also does it not hurt performance by > preempting the gc? My feeling is that this is a misuse of 'del'. Am I > wrong? Is there any advantage of doing the above? > It is probably a complete waste of time, but there are situations where code similar to this can be useful: def otherfunction(): try: # some stuff except SomeException, e: # more stuff del e raise return The point of code like this is that when a function exits by throwing an exception the traceback includes a reference to the stack frame and all the local variables. In some situations that can result in large data structures not being freed for a very long time (e.g. until another exception is thrown that is handled at the same level). So, *in very specialised situations* it may be important to delete particular names from the local namespace. From steve at REMOVE-THIS-cybersource.com.au Tue Dec 2 05:27:00 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Dec 2008 10:27:00 GMT Subject: optimization References: Message-ID: <0145054b$0$20670$c3e8da3@news.astraweb.com> On Mon, 01 Dec 2008 18:11:16 -0600, Robert Kern wrote about nested functions: > I, for one, find that significantly less clear. I only expect functions > to be defined inside of functions if they are going to use lexical > scoping for some reason. If I read your code, I'd probably waste a good > five minutes trying to figure out what part of the local scope you were > using before I would conclude that you just did it because you thought > it looked better. Hah, I bet you aren't an ex-Pascal programmer :-) Speaking as one, it took me a long time to teach myself not to bother nesting functions for the purpose of avoiding scoping clashes. I'd write something like this: def parrot(): def colour(): return "Blue" return "Norwegian %s" % colour() def cardinal(x): def colour(): return "crimson" return "Cardinal Fang wears a %s robe" % colour() Except of course that's a trivially silly example. (For the sake of the argument, let's pretend the two functions colour() do actual calculations.) These days, I'd write them something like this: def parrot_colour(): return "Blue" def cardinal_colour(): return "crimson" def parrot(): return "Norwegian %s" % parrot_colour() def cardinal(x): return "Cardinal Fang wears a %s robe" % cardinal_colour() These days, almost the only time I use nested functions is for function factories. -- Steven From cousinstanley at gmail.com Wed Dec 10 11:28:50 2008 From: cousinstanley at gmail.com (Cousin Stanley) Date: Wed, 10 Dec 2008 17:28:50 +0100 (CET) Subject: [OT] Google Groups in bad odour References: <4d5498bf-bbf0-4760-83fc-610729bcbce2@h20g2000yqn.googlegroups.com> Message-ID: > .... > I will therefore have to find a suitable news client. > Any recommendations ? Frank .... You might try the python-based xpn news client .... http://xpn.altervista.org/index-en.html To thine own snake be true .... :-) -- Stanley C. Kitching Human Being Phoenix, Arizona From rhamph at gmail.com Wed Dec 10 13:39:40 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Wed, 10 Dec 2008 10:39:40 -0800 (PST) Subject: Rich Comparisons Gotcha References: Message-ID: On Dec 10, 7:49?am, Rasmus Fogh wrote: > Rhamphoryncus wrote: > > You grossly overvalue using the "in" operator on lists. > > Maybe. But there is more to it than just 'in'. If you do:>>> c = numpy.zeros((2,)) > >>> ll = [1, c, 3.] > > then the following all throw errors: > 3 in ll, 3 not in ll, ll.index(3), ll.count(3), ll.remove(3) > c in ll, c not in ll, ll.index(c), ll.count(c), ll.remove(c) > > Note how the presence of c in the list makes it behave wrong for 3 as > well. All of these are O(n). Use a set or dict. What is your use case anyway? > > It's far more > > common to use a dict or set for containment tests, due to O(1) > > performance rather than O(n). ?I doubt the numpy array supports > > hashing, so an error for misuse is all you should expect. > > Indeed it doees not. So there is not much to be gained from modifying > equality comparison with sets/dicts. > > > In the rare case that you want to test for identity in a list, you can > > easily write your own function to do it upfront: > > def idcontains(seq, obj): > > ? ? for i in seq: > > ? ? ? ? if i is obj: > > ? ? ? ? ? ? return True > > ? ? return False > > Again, you can code around any particular case (though wrappers look like > a more robust solution). Still, why not get rid of this wart, if we can > find a way? The wart is a feature. I agree that it's confusing, but the cost of adding a special case to work around it is far in excess of the original problem. Now if you phrased it as a hypothetical discussion for the purpose of learning about language design, that'd be another matter. From theller at python.net Fri Dec 19 12:53:22 2008 From: theller at python.net (Thomas Heller) Date: Fri, 19 Dec 2008 18:53:22 +0100 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> Message-ID: <6r25ckFejl4vU1@mid.individual.net> Steve Holden schrieb: > Thomas Heller wrote: >> Question from a non-native english speaker: is this now valid english? >> >> "One of Python?s great strengths" >> ^ >> "and also teaches Python?s functional programming features" >> ^ >> "The book?s approach is wholly practical" >> ^ > It always has been valid English. The apostrophe is only omitted from > personal pronouns (hers, its, and so on). I see, thanks. But, is the apostrophe optional in the above fragments? Thomas From castironpi at gmail.com Tue Dec 30 11:11:20 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 30 Dec 2008 08:11:20 -0800 (PST) Subject: thread, multiprocessing: communication overhead References: Message-ID: On Dec 30, 9:46?am, mk wrote: > Hello everyone, > > This time I decided to test communication overhead in multithreaded / > multiprocess communication. The results are rather disappointing, that > is, communication overhead seems to be very high. In each of the > following functions, I send 10,000 numbers to the function / 10 threads > / 10 processes, which simply returns it in its respective way. > > Function: notfun ? ? ? ? ? ?Best: 0.00622 sec ? Average: 0.00633 sec > (simple function) > > Function: threadsemfun ? ? ?Best: 0.64428 sec ? Average: 0.64791 sec > (10 threads synchronizing using semaphore) > > Function: threadlockfun ? ? Best: 0.66288 sec ? Average: 0.66453 sec > (10 threads synchronizing using locks) > > Function: procqueuefun ? ? ?Best: 1.16291 sec ? Average: 1.17217 sec > (10 processes communicating with main process using queues) > > Function: procpoolfun ? ? ? Best: 1.18648 sec ? Average: 1.19577 sec > (a pool of 10 processes) > > If I'm doing smth wrong in the code below (smth that would result in > performance suffering), please point it out. snips > def threadsemfun(): > ? ? ? ? ?sem = threading.Semaphore() > def threadlockfun(): > ? ? ? ? ?sem = threading.Semaphore() You used a Semaphore for both lock objects here. 'multiprocessing' is a really high level layer that makes a lot of decisions about trade-offs, has highly redundant communication, and is really easy to use. If you want to save a byte, you'll have to make your own decisions about trade-offs and redundancies (possibly even looking at real result data to make them). I actually think 'multiprocessing' is really good, and even if I hand- wrote my own IPC, it would be slower! CMIIW, but I believe your timing function includes the time to launch the actual processes and threads, create the synch. objects, etc. You might try it again, creating them first, starting the timer, then loading them. From lie.1296 at gmail.com Sun Dec 7 15:07:56 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 7 Dec 2008 20:07:56 +0000 (UTC) Subject: Brain going crazy with recursive functions References: <6470511f-093e-42c2-a6c2-4bb90b336ac9@r15g2000prd.googlegroups.com> Message-ID: On Sat, 06 Dec 2008 23:33:35 -0800, 5lvqbwl02 wrote: > I'm trying to solve the 9-tile puzzle using as functional an approach as > possible. I've recently finished reading SICP and am deliberately > avoiding easy python-isms for the more convoluted scheme/functional > methods. The following function is trivial to do with for loops and > directly accessing arrays with [] syntax. I'm trying to limit myself to > the types of idioms/semantics one finds in minimal scheme, such as in > SICP. I want eventually to port this to scheme, but I know python > better, so that's where I'm starting. > > My current problem is the following. The 9-tile puzzle consists of a > list of lists like this [[1,2,3],[4,5,6],[7,8,0]], where the numbers can > be jumbled up. I'm looking for the location of the zero using *only* > recursion and operators that are similar to car/cdr. The return value > should be the row,col of the zero. For example above the > return value would be (2,2). > > I'm also trying to define a single "linear_search(...)" function which > does the search for within the row (an inner list above) and within the > whole list. linear_search takes as an argument a "truth_function" > which does the actual work. What's tricky is that the truth function > for the array-as-a-whole is also the linear_search for a row. Once I'm > in linear_search for the array, I also call linear_search for each > row. > > The problem is the line where it says acc.insert(0,idx) looks fishy to > me. It works fine and returns the row,col of the location of the zero > tile, but it seems to be mutating a variable, and that's the thing I'm > trying to avoid. In a sense, it's not hard enough and python is making > this too easy :) (although it took a bit of mind-wrenching to get to > this point. Recursion makes you either dumber or smarter, I'm not sure > which). > > How do I accumulate the inner value of the search so it pops out at the > end, without resorting to a mutable variable? I did a bit of search and > the word "monad" came up, but I'm not sure what that is (I know it > relates to haskell and some other purely functional stuff, but > I get very lost when trying to read that stuff). > > > > > def linear_search(array, truth_func, acc): > # Goes through each element of array and applies truth_func. # Returns > index if found, otherwise returns None def linear_search_iter(idx, > truth_func, arr, acc): > if arr: > tf = truth_func(arr[0]) > if tf or type(tf) is int: > acc.insert(0,idx) > return idx, acc+[idx] > else: > return linear_search_iter(idx+1, truth_func, arr[1:], acc) > return linear_search_iter(0, truth_func, array, acc) > > > > def locate_zero(p): > # Locates empty tile. Returns (r,c) tuple def find_zero_in_row (row): > return linear_search(row, lambda x: x==0, acc) > > acc = [] > ls = linear_search(p, find_zero_in_row, acc) print acc > return acc > > locate_zero([[5, 3, 4], [2, 0, 1], [8, 6, 7]]) correctly returns (1,1) In most functional languages, their natural data types differs. For example, Haskell's list is a linked list, which if expressed in python would look like this: Python: [1, 2, 3, 4, 5] Haskell-in-Python: [1, [2, [3, [4, [5, []]]]]] linked list is more natural to use with recursive functions, so your locate zero would be like this: def search_tile(row, depth = 0): head, tail = row if head == 0: return depth elif len(tail) == 0: return None else: return search_tile(tail, depth + 1) def search_row(grid, depth = 0): head, tail = grid st = search_tile(head) if st is not None: return depth, st elif tail == []: return None else: return search_row(tail, depth + 1) Now, you noticed that lots of the code is similar, we want to generalize it. It's easy: def search_linear(list_, checker, depth = 0): head, tail = list_ if checker(head): return depth, () if checker(head) is True else checker(head) # I intentionally doesn't factor out checker(head) # as most functional language would automatically # do so because side-effect is impossible elif tail == (): return () else: return search_linear(tail, checker, depth + 1) data = (1, (2, (3, (0, ())))) print search_linear(data, lambda x: x == 0) # (3, ()) data = (0, (2, (3, (4, ())))) print search_linear(data, lambda x: x == 0) #(0, ()) data = (1, (2, (3, (4, ())))) print search_linear(data, lambda x: x == 0) #() data = ((5, (3, (4, ()))), ((2, (0, (1, ()))), ((8, (6, (7, ()))), ()))) print search_linear(data, lambda row: search_linear(row, lambda tile: tile == 0)) #(1, (1, ())) From jcd at sdf.lonestar.org Thu Dec 18 10:03:44 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Thu, 18 Dec 2008 10:03:44 -0500 Subject: help I'm getting delimited In-Reply-To: <0de3a7bf-a4c4-4103-a4e0-44313405fa94@z28g2000prd.googlegroups.com> References: <1229445534.5328.0.camel@linux-3eb6.site> <0d9ea7cc-b5fb-4edb-be32-490aae9e7204@b41g2000pra.googlegroups.com> <0de3a7bf-a4c4-4103-a4e0-44313405fa94@z28g2000prd.googlegroups.com> Message-ID: <1229612624.5928.15.camel@aalcdl07.lib.unc.edu> On Wed, 2008-12-17 at 06:28 -0800, aka wrote: > Hi John, thanks. > You're right, I didn't past the method header because I thought it > didn't matter when the input filename is hardcoded. > The try/except isn't very helpful indeed so I commented it out. > You're right I wrongly referred to the UnicodeReader > class in my first post because that's ultimately where I want to go > so > I outcommented it here for you to see. > The fact is that neither csv.reader nor the UnicodeReader will read > the file, while writing with the UnicodeWriter > works like a charm. > That's why I put str() around roles to see any content. > I simplified the csv-file by cutting off columns without result. The > file looks now like: > > id;company;department > 12;Cadillac;Research > 11;Ford;Accounting > 10;Chrysler;Sales > > > The dictionary on the return is because this code is part of my > TurboGears application. > The entire method is: > > > import csv > from utilities.urw import UnicodeWriter, UnicodeReader > > > @expose(allow_json=True) > def import_roles(self, input=None, *args, **kwargs): > inp = 'C:/temp/test.csv' > roles = [] > msg = '' > ## try: > fp = open(inp, 'rb') > reader = csv.reader(fp, dialect='excel', delimiter=';') > ## reader = UnicodeReader(fp, dialect='excel', delimiter=';') > for r in reader: > roles.append(r[0]) > fp.close() > ## except: > ## msg = "Something's wrong with the csv.reader" > return dict(filepath=inp, > roles=str(roles), > msg=msg) > > > csv.reader results in: for r in reader: Error: line contains NULL > byte > > > Use of UnicodeReader results in: UnicodeDecodeError: 'utf8' codec > can't decode byte 0xff in position 0: unexpected code byte > This looks like the problem might be in your choice of codec. A UTF-8 file will never have 0xff in it, and would be unlikely to have 0x00 either. My guess is that you will need to decode your input from UTF-16. (and then use the UnicodeReader). > > Will post only complete code from now on thanks. > > -- > http://mail.python.org/mailman/listinfo/python-list > From info at egenix.com Tue Dec 2 05:10:38 2008 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Tue, 02 Dec 2008 11:10:38 +0100 Subject: ANN: eGenix mxODBC Connect - Python Database Interface 1.0.0 Message-ID: <4935099E.6080708@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com mxODBC Connect Python Database Interface Version 1.0.0 Our new client-server product for connecting Python applications to relational databases - from all major platforms This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-mxODBC-Connect-1.0.0-GA.html ________________________________________________________________________ INTRODUCTION The mxODBC Connect Database Interface for Python allows users to easily connect Python applications to all major databases on the market today in a highly portable and convenient way. Unlike our mxODBC Python extension, mxODBC Connect is designed as client-server application, so you no longer need to find production quality ODBC drivers for all the platforms you target with your Python application. Instead you use an easy to install Python client library which connects directly to the mxODBC Connect database server over the network. This makes mxODBC Connect the ideal basis for writing cross-platform database programs and utilities in Python, especially if you run applications that need to communicate with databases such as MS SQL Server and MS Access, Oracle Database, IBM DB2 and Informix, Sybase ASE and Sybase Anywhere, MySQL, PostgreSQL, SAP MaxDB and many more, that run on Windows or Linux machines. By removing the need to install and configure ODBC drivers on the client side, mxODBC Connect greatly simplifies setup and configuration of database driven client applications, while at the same time making the network communication between client and database server more efficient and more secure. For more information, please see the product page: http://www.egenix.com/products/python/mxODBCConnect/ ________________________________________________________________________ NEWS mxODBC Connect 1.0.0 is the first general availability release of our new mxODBC Connect product. With this release we have further improved the performance and round-trip times of the mxODBC Connect network layer even more. We are now able to achieve a *more than 10 times better performance* for a typical multi-tier application that runs on Linux and connects to a MS SQL Server database running on a Windows host, compared to the same application using mxODBC and the FreeTDS ODBC driver. Thanks to everyone who participated in the public beta ! ________________________________________________________________________ DOWNLOADS The download archives as well as instructions for installation and configuration of the product can be found on the product page: http://www.egenix.com/products/python/mxODBCConnect/ Evaluation licenses for the server part are available free of charge: http://www.egenix.com/products/python/mxODBCConnect/#Evaluation The client part of mxODBC Connect is always free of charge. _______________________________________________________________________ SUPPORT Commercial support for this product is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 02 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-12-02: Released mxODBC.Connect 1.0.0 http://python.egenix.com/ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From steve at REMOVE-THIS-cybersource.com.au Tue Dec 2 08:47:14 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Dec 2008 13:47:14 GMT Subject: Do more imported objects affect performance References: <1be78d220812010621u51dead9dnbaa0b4c8c9414362@mail.gmail.com> <79153a2e0812012124o7401df57m4ac21dfe37c2ec5@mail.gmail.com> Message-ID: <01453438$0$20670$c3e8da3@news.astraweb.com> On Tue, 02 Dec 2008 11:12:31 +0000, Nick Craig-Wood wrote: > I prefer the "from module import function". That means that if "module" > doesn't supply "function" it raises an exception at compile time, not > run time when you try to run "module.function". Wanna bet? >>> def spam(): ... from math import harmonic_series ... return harmonic_series() ... >>> dis.dis(spam) 2 0 LOAD_CONST 1 (-1) 3 LOAD_CONST 2 (('harmonic_series',)) 6 IMPORT_NAME 0 (math) 9 IMPORT_FROM 1 (harmonic_series) 12 STORE_FAST 0 (harmonic_series) 15 POP_TOP 3 16 LOAD_FAST 0 (harmonic_series) 19 CALL_FUNCTION 0 22 RETURN_VALUE >>> spam() Traceback (most recent call last): File "", line 1, in File "", line 2, in spam ImportError: cannot import name harmonic_series The same thing happens if the from...import is at the top level of the module, except that compilation is immediately followed by execution. > It then becomes very > easy to see which functions you use from any given module too. If that's important to you. Personally, I find it more useful to know where a function is defined. -- Steven From arnodel at googlemail.com Fri Dec 5 16:59:11 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 05 Dec 2008 21:59:11 +0000 Subject: Overriding a method at the instance level on a subclass of a builtin type References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> Message-ID: Arnaud Delobelle writes: [...] > class ClassGetItem(object): > def __get__(self, obj, objtype=None): > return obj._getitem_ > def __set__(self, obj, val): > obj._getitem_ = val > > class GetItem(object): > def __get__(self, obj, objtype=None): > return obj._getitem_ > def __set__(self, obj, val): > obj._getitem_ = val It's funny how the brain works. I didn't realise both classes were the same until I read my own post! [...] -- Arnaud From Chris.Rathman at gmail.com Wed Dec 10 21:43:07 2008 From: Chris.Rathman at gmail.com (Chris Rathman) Date: Wed, 10 Dec 2008 18:43:07 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <5ebe5a7d-cbdf-4d66-a816-a7d2a0a273c9@40g2000prx.googlegroups.com> Message-ID: <16459ac1-32b7-408c-80ff-16469af4228a@l33g2000pri.googlegroups.com> On Dec 10, 6:51?pm, Xah Lee wrote: > I've now gather code solutions in ruby, python, C, Java, here: > > now lacking is perl, elisp, which i can do well in a condensed way. > It'd be interesting also to have javascript... and perhaps erlang, > OCaml/F#, Haskell too. Pay me $600 for my time and I'll even throw in an Algol-68 version. :-) From knabberknusperhaus at yahoo.de Thu Dec 25 08:56:10 2008 From: knabberknusperhaus at yahoo.de (KKH) Date: Thu, 25 Dec 2008 13:56:10 +0000 (GMT) Subject: Getting a locked buffer from objects (PEP 3118) Message-ID: <603279.94632.qm@web24403.mail.ird.yahoo.com> Hi, it seems the whole locking-theme has gone from PEP 3118 (PyBUF_LOCK is gone). Yet the string and byte objects seem to provide locked buffers through PyArg_Parse arguments s*, y* and z* (documentation says so). Could someone please clarify the situation for me: Is it save to release the GIL after getting a reference to a buffer-object by the arguments above and only talking to this buffer while the GIL is gone? And while we are at it :-) Is "PyArg_Parse('[syz]*'..." the only way to get a locked buffer-view from string/byte objects? Regards ebfe From rt8396 at gmail.com Tue Dec 23 11:38:05 2008 From: rt8396 at gmail.com (r) Date: Tue, 23 Dec 2008 08:38:05 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: Benjamin Kaplin wrote: You're the one who keeps bringing up the need to spread python. For most people, this is a forum to ask questions and have experts respond to them. Most people who post here aren't looking for your opinion, they want answers. If you know the answer to a question, answer it. If not, read the answers of people who have seen it before. When you post your opinions, you're just creating more noise. School time son, This forum is much more than a question answer session, son. Sure people are welcome to ask a Python related question. But this forum is really the main highway of Python development and future. If your a n00b go to the "Python forum.org", you will feel more comfy over there. If you have no opinion(Benjamin) thats your perogitive, don't tell me how to live my life, or what "I" should do when i visit this forum. Do I go to any of "your" threads and start a ruckus? NO, because if i do not like what you are saying I will just ignore it. Take an example son! Sure i may have went off in thread, by i have kept my thought true to the thread subject. A troll go's from thread to thread posting off subject insults and attacks on other posters... hmmm, i have seen some of those kind in this thread?? Know of who i speak, Bennie? From martin at v.loewis.de Sat Dec 13 17:20:33 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 13 Dec 2008 23:20:33 +0100 Subject: Python 3.0 crashes displaying Unicode at interactive prompt In-Reply-To: References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> Message-ID: <49443531.5050304@v.loewis.de> >> This is intended behavior. > > I see. That means that the behaviour in Python 1.6 to 2.6 (i.e. > encoding the text using the repr() function (as then defined) was not > intended behaviour? Sure. This behavior has not changed. It still uses repr(). Of course, the string type has changed in 3.0, and now uses a different definition of repr. Regards, Martin From fetchinson at googlemail.com Sat Dec 27 16:45:38 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 27 Dec 2008 13:45:38 -0800 Subject: C API: array of floats/ints from python to C and back Message-ID: I'm trying to write an extension module in C which contains a single function with the following prototype: void func( int N, int * arg1, int * arg2, int * ret ); Here arg1 and arg2 are length N arrays, and the function computes ret which is also an N length array. From python I'd like to call this function as ret = func( [ 1, 2, 3 ], [ 2, 3, 4] ) I've read through the docs at http://docs.python.org/extending/extending.html and also http://docs.python.org/c-api/arg.html from which I learned how to pass a fixed number of basic datatypes (int, float, string) from python to C and back. What I don't know is how to pass an array back and forth. As far as I can see PyArg_ParseTuple is the function I should use for converting the python arguments to C but the format string passed to PyArg_ParseTuple can only be one of the basic data types ("s", "i", etc) or a generic python object ("O"). Does this mean that I can only pass the arrays from python to C as generic python objects and in a later operation I need to get the elements from this generic python object, construct a C array and pass that to the C function? Since I assume this is a frequent operation I'd think there are some shortcuts, aren't there? Or what's the simplest way of doing this? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From cournape at gmail.com Fri Dec 12 09:27:43 2008 From: cournape at gmail.com (David Cournapeau) Date: Fri, 12 Dec 2008 23:27:43 +0900 Subject: Python is slow In-Reply-To: <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> Message-ID: <5b8d13220812120627l5e5a4657i6406d47ac17a5562@mail.gmail.com> On Fri, Dec 12, 2008 at 11:04 PM, Luis M. Gonz?lez wrote: > It has been mentioned in this thread the pypy project (isn't it enough > for you??) Since pypy can't be used today for most production use (most python packages can't work on it), I don't see how it could be enough for anyone interested in solving problems today. I want faster function calls to use with numpy: do you know of any solution ? Pypy certainly isn't, at least today. cheers, David From deets at nospam.web.de Sat Dec 20 06:52:34 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 20 Dec 2008 12:52:34 +0100 Subject: PIL on 3.x? In-Reply-To: <494c0ad4$0$4096$ba4acef3@news.orange.fr> References: <3892784c-ddf4-4451-bcfd-dbc58b9b55f8@e1g2000pra.googlegroups.com> <494c0ad4$0$4096$ba4acef3@news.orange.fr> Message-ID: <6r44k2Fff3hbU1@mid.uni-berlin.de> M?ta-MCI (MVP) schrieb: > Hi! > > This info is interesting for many people. > IMO, it's a good idea to write the question in this newsgroup. Which only makes sense if the author of PIL reads it. Which he seems not to (or at least doesn't answer here, as he used to). Diez From antoine at vo.lu Tue Dec 9 06:53:49 2008 From: antoine at vo.lu (Antoine De Groote) Date: Tue, 09 Dec 2008 12:53:49 +0100 Subject: primera In-Reply-To: <16149$493e58b1$d9a2276f$4726@news.hispeed.ch> References: <16149$493e58b1$d9a2276f$4726@news.hispeed.ch> Message-ID: <2cac8$493e5c4d$d9a2276f$7521@news.hispeed.ch> Oops, sorry, this message was not intended for the group. Apologies Antoine De Groote wrote: > zalli, > > du spills jo net mat am volley oder? mengs de du kinns dann mat mengem > auto an den MCM an eventuell op sandweiler fueren? well m?indes ass > volley, densdes fussball, an mettwochs ass schon hellejen owend... > > nuecht > antoine From nospam at forMe.thks Mon Dec 15 10:21:03 2008 From: nospam at forMe.thks (Ross) Date: Mon, 15 Dec 2008 10:21:03 -0500 Subject: Managing timing in Python calls Message-ID: I'm porting some ugly javascript managed stuff to have an equivalent behaviour in a standalone app. It uses events that arrive from a server, and various small images. In this standalone version, the data is local in a file and the images in a local directory. My AJAX code managed a timely presentation of the info, and in the Javascript that relied on the ugly: myImage.onload = function(){dosomething_when_it's_finished} structure. Also, I used the similarly unpretty: var t = window.setTimeout( function () { do_when_timed_out} structures which allows stuff to happen after a perscribed period. In my python implementation my first guess is to use a thread to load my image into a variable myImage = wx.Image("aPic.gif", wx.BITMAP_TYPE_GIF ).ConvertToBitmap() so that it won't block processing. (Though perhaps it'll just happen so fast without a server involved that I won't care.) Is there a nice equivalent of a 'setTimeout' function in python? ie to call a function after some time elapses without blocking my other processing? I suppose just a thread with a time.sleep(x_mS) in it would be my first guess? Can anyone give me some feedback on whether that's a logical path forward, or if there are some nicer constructs into which I might look? Thanks for any suggests... Ross. From benjamin.kaplan at case.edu Sun Dec 14 12:09:33 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 14 Dec 2008 12:09:33 -0500 Subject: 1 or 1/0 doesn't raise an exception In-Reply-To: References: <49446E39.6020807@tim.thechases.com> Message-ID: On Sun, Dec 14, 2008 at 2:38 AM, Gabriel Genellina wrote: > En Sun, 14 Dec 2008 02:40:10 -0200, Benjamin Kaplan > escribi?: > > On Sat, Dec 13, 2008 at 10:49 PM, Daniel Fetchinson < >> fetchinson at googlemail.com> wrote: >> >> >> Is it a feature that >>> >> >>> >> 1 or 1/0 >>> >> >>> >> returns 1 and doesn't raise a ZeroDivisionError? If so, what's the >>> >> rationale? >>> > >>> > http://en.wikipedia.org/wiki/Short-circuit_evaluation >>> >>> Let me just point out that unsuspecting people (like me) might rely on >>> the whole expression to be evaluated and rely on exceptions being >>> raised if needed. >>> >> >> If you want both expressions evaluated, you can use & and |, just like in >> C >> and Java (&& and || are used for short circuit evaluation in those >> languages). >> > > No: &, | (and ^, too) perform bitwise operations in Python, C and Java: > Perhaps I should have mentioned that you have to restrict yourself to bools (or 0 and 1) when doing this. I know that they perform bitwise operations when you do them with ints- I was assuming the OP was dealing with bools. > > py> 1 & 2 > 0 > > && and || --in both C and Java-- are like `and` and `or` in Python; they > perform logical operations, and short-circuit evaluation of their operands. > If you want to evaluate a logical expression without short circuiting, do > that explicitely: > > a = first part > b = second part > if a or b: ... > > -- > Gabriel Genellina > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Russ.Paielli at gmail.com Sat Dec 6 11:01:40 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 6 Dec 2008 08:01:40 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> <8b8d1fb3-f49e-49bf-8cfe-eeee5ed16109@r37g2000prr.googlegroups.com> <014a932b$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Dec 6, 7:34?am, Steven D'Aprano wrote: > On Sat, 06 Dec 2008 07:15:27 -0800, Russ P. wrote: > > On Dec 6, 4:32?am, Andreas Waldenburger wrote: > >> On Sat, 6 Dec 2008 04:02:54 -0800 (PST) bearophileH... at lycos.com wrote: > > >> > class C: > >> > ? ? def $method(arg): > >> > ? ? ? ? $value = arg > > >> > (Note there's no point after $, it's not currently possible). > > If -- and that's a HUGE if -- the compiler is changed to allow $method, > it could certainly be changed to allow $.method. > > >> > Ruby > >> > uses @ and @@ for similar purposes. I agree that the code looks > >> > worse, but also shorter to read and write, so in lines of code that > >> > use many instance attributes, that short $ syntax helps keep the line > >> > shorter. So I may grow to accept this sugar... > > If a line of code uses too many instance attributes to fit comfortably on > a line, spread it over two lines. There is no newline shortage, they are > a renewable resource. > > >> But that is not the way Python is meant to work. There are several > >> tennets in the Zen of Python that don't chime well with this approach. > >> "self" is a speaking identifier, "$" isn't. > > > Is "@" a "speaking identifier? How about "#" and "!="? Last I heard, > > they were all part of Python. > > Yes they are. > > @f > > is pronounced "at f" or "decorate f". > > # comment > > is pronounced "hash comment" or even not pronounced at all. > > x != y > > is pronounced "x not equal to y" > > The proposed > > def $method(arg): > > would be pronounced "def dollar method arg" or "def method self arg". The > first is ugly to my ears, the second confusing. Regarding "$" as a stand-in for "self" is less of a stretch than the examples you gave. > -2 on this proposal. Did you get two votes in the Presidential election too? 8^) From bj_666 at gmx.net Sat Dec 20 06:14:31 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 20 Dec 2008 11:14:31 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <1332da3c-8075-4552-9498-3ceb23faca8f@v31g2000vbb.googlegroups.com> Message-ID: <6r42cnFfc57aU1@mid.uni-berlin.de> On Fri, 19 Dec 2008 17:12:00 -0800, r wrote: > Marc, > Why move away from a concise and widely accepted way of sting > formatting, just to supposedly make it a little easier for n00bs? (which > i disagree this is easier) In turn, creating more syntactical clutter. > (%s %f %d) is all you need to remember. If people can't understand that, > i fear for the future of Humans as a species! Yeah, doomsday is near. Curly brackets and a number instead of a percent sign followed by an 's' is a sure sign of the end? You're a funny little troll, Sir. Ciao, Marc 'BlackJack' Rintsch From benjamin.kaplan at case.edu Sat Dec 13 16:13:29 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sat, 13 Dec 2008 16:13:29 -0500 Subject: Python is slow In-Reply-To: <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> Message-ID: On Sat, Dec 13, 2008 at 3:35 PM, sturlamolden wrote: > On 10 Des, 19:42, cm_gui wrote: > > > And it is not just this Python site that is slow. There are many many > > Python sites which are very slow. And please don't say that it could > > be the web hosting or the server which is slow ? because when so many > > Python sites are slower than PHP sites, it couldn't be the web > > hosting. Also, Zope/Plone is even slower. > > > > Python is slow. Very slow. > > > By the way... I know of a very slow Python site called YouTube.com. In > fact, it is so slow that nobody ever uses it. > And there's also a web crawler written in Python, used by a site called Google, that's so slow that the search engine gives very few results. > > > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Fri Dec 26 17:27:52 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 26 Dec 2008 20:27:52 -0200 Subject: strange behavior of math.sqrt() in new 3.0 version References: Message-ID: En Fri, 26 Dec 2008 19:52:24 -0200, escribi?: > I'm a newbee trying 3.0 Please help with math.sqrt() > > At the command line this function works correctly > >>> import math > n = input("enter a number > ") > s = math.sqrt(n) > An entry of 9 or 9.0 will yield 3.0 > > Yet the same code in a script gives an error message > Script1 > import math > n = input("enter a number > ") > s = math.sqrt(n) > Traceback (most recent call last) : > File "", line 1, in > File "script1.py" line 3 in > s = math.sqrt(n) > TypeError : a float is required > Entering 9 or 9.0 gives same error message. > > According to the math module the results of all > functions are floats. However it says nothing about > inputs. > > Strangely the above code runs fine in version 2.5 ( ? ) > and will handle large integers. > > I've read the documentation for 3.0 including the section > "Floating Point Arithmetic: Issues & Limitations" and it > helps nada. And you won't find nothing - the change is in "input" behavior, not in the math functions. For versions prior to 3.0, there are: raw_input(message) -> string typed input(message) -> result of evaluating the string typed raw_input just returns whatever you type, as a string. Using the input function, Python evaluates whatever you type to obtain a result: if you type the three characters "nine" "dot" "zero" the result is the double 9.0; you can even type (17+1)/2.0 to get the same value (try it with your Python 2.5) Since version 3.0, input behaves as raw_input in the older versions, and there is no builtin function equivalent to the old input function. Use this instead: n = float(input("enter a number > ")) -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Tue Dec 30 20:15:35 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Dec 2008 01:15:35 GMT Subject: Triple quoted string in exec function ? References: <495A253B.6010003@gmail.com> Message-ID: <016abeb8$0$6988$c3e8da3@news.astraweb.com> On Tue, 30 Dec 2008 21:16:39 +0100, Stef Mientki wrote: > I guess I've to remove all triple quoted strings from my code. There's no problem with triple-quoted strings. You just have to quote them properly. >>> text = """x = 1 ... y = x+2 ... del x ... print y ... """ >>> exec text 3 You can even embed triple-quoted strings inside the string to be executed. >>> text = "s = '''%s'''" % """This is a ... triple quoted ... string""" >>> >>> exec text >>> s 'This is a\ntriple quoted\nstring' If you're going to remove anything, I'd look at why you are using exec in the first place. To me, it's a code smell -- not necessarily wrong, but exec is awfully open to abuse and potential security flaws. -- Steven From ldo at geek-central.gen.new_zealand Fri Dec 5 05:32:49 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 05 Dec 2008 23:32:49 +1300 Subject: Don't you just love writing this sort of thing :) References: Message-ID: In message , Duncan Booth wrote: > ... but the mess you posted is going to be virtually untestable ... The "mess" I posted did actually work as written. > ... whereas splitting it up into small testable functions will make it > much easier for you to actually get somewhere near your goal of correct > code. The code people write is probably a direct reflection of their thinking processes: For example, slow, plodding, one step at a time, incapable of imaginative leaps, versus those who operate directly on larger patterns at once... From deets at nospam.web.de Thu Dec 18 09:20:48 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 18 Dec 2008 15:20:48 +0100 Subject: confused about __str__ vs. __repr__ References: Message-ID: <6qv4i0FenjboU1@mid.uni-berlin.de> Neal Becker wrote: > Reading some FAQ, I see that __str__ is "meant for human eyes". > > But it seems that: > class X(object): > ? ? def __str__(self): > ? ? ? ? return "str" > ? ? def __repr__(self): > ? ? ? ? return "repr" > > x = X() > d = {0 : x} > print d > {0: repr} > > So if __str__ is "meant for human eyes", then why isn't print using it! Because the __str__ of dict uses __repr__. Do a print x to see that print itself does use __str__. BTW, could you configure your newsreader to not put the GMANE-group as follow-up? NNTP doesn't work for that. Diez From lewis.sarah93 at yahoo.com Thu Dec 4 23:52:58 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 20:52:58 -0800 (PST) Subject: Earn More Noney Message-ID: <8b1cdd10-5803-44c7-b400-df6d89db1bb0@t3g2000yqa.googlegroups.com> Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From nick at craig-wood.com Tue Dec 2 06:12:31 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 2 Dec 2008 11:12:31 +0000 Subject: Do more imported objects affect performance In-Reply-To: <79153a2e0812012124o7401df57m4ac21dfe37c2ec5@mail.gmail.com> References: <1be78d220812010621u51dead9dnbaa0b4c8c9414362@mail.gmail.com> <79153a2e0812012124o7401df57m4ac21dfe37c2ec5@mail.gmail.com> Message-ID: <20081202111231.GA13523@craig-wood.com> On Tue, Dec 02, 2008 at 11:24:29AM +0600, Taskinoor Hasan wrote: > On Mon, Dec 1, 2008 at 8:21 PM, Filip Gruszczy?ski wrote: > > > I see. Thanks for a really good explanation, I like to know, how to do > > things in the proper way :) > > I always prefer to use import module and then use module.function. The > reason is simple. It makes the code more readable and maintainable. I prefer the "from module import function". That means that if "module" doesn't supply "function" it raises an exception at compile time, not run time when you try to run "module.function". It then becomes very easy to see which functions you use from any given module too. It is also very slightly faster but that isn't a major consideration. PEP 8 endorses this style somewhat http://www.python.org/dev/peps/pep-0008/ - see the Imports section. [...] it's okay to say this though: from subprocess import Popen, PIPE [...] When importing a class from a class-containing module, it's usually okay to spell this from myclass import MyClass from foo.bar.yourclass import YourClass If this spelling causes local name clashes, then spell them import myclass import foo.bar.yourclass and use "myclass.MyClass" and "foo.bar.yourclass.YourClass" Ultimately it is a matter of taste I think! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From aioe.org at technicalbloke.com Sat Dec 6 01:56:55 2008 From: aioe.org at technicalbloke.com (r0g) Date: Sat, 06 Dec 2008 01:56:55 -0500 Subject: Quick Newbie Question References: Message-ID: Josh wrote: > Can Python be used on one Linux machine to drive another Linux machine > through SSH? I am currently running Putty on my XP box to run tests on a > Linux box. I need to automate these tests and thought it would be fun to > do so from a Linux VMWare Image I recently setup. Does this sound > do-able without too much effort? I already know the Linux commands I > need to run but just need an interactive shell connection through SSH. > Again is Python a good choice for this or something else? > Thanks, > > JR Yep, python has several options, I've been using paramiko for this for a couple of years: http://www.lag.net/paramiko/ Roger Heathocte From rdmurray at bitdance.com Thu Dec 11 14:06:34 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Thu, 11 Dec 2008 14:06:34 -0500 (EST) Subject: internal circular class references In-Reply-To: <49414EDA.2050509@stoneleaf.us> References: <49414EDA.2050509@stoneleaf.us> Message-ID: On Thu, 11 Dec 2008 at 09:33, Ethan Furman wrote: > Carl Banks wrote: >> On Dec 10, 5:26 pm, Ethan Furman wrote: >> First of all, do you even need to wrap the datetime.date class? With >> Python's duck typing ability, you could have a separate NullDate class >> to go alongside the datetime.date, and use a regular datetime.date >> object when the date is present, and NullDate when it's absent. If >> necessary you can subclass datetime.date to add any new methods it >> would have to have. Use a factory function to return either NullDate >> or a datetime.date depending on whether the dbf cell is empty. >> >> class ValidDate(datetime.date): >> def is_valid(self): >> return True >> >> class NullDate(object): >> # implement any necessary methods of datetime.date interface here >> def is_valid(self): >> return False >> >> def create_date_from_dbf_cell(dbf_cell): >> if dbf_cell.empty(): >> return NullDate() >> return ValidDate(dbf_cell.value) >> >> >> If you do this, you don't have to muck around with __getattr__ or >> __new__ or snooping to datetime.date's class dict anything like that. >> >> >> Carl Banks > > Good question. My goal with NullDate is to have a date object that I can > treat the same regardless of whether or not it actually holds a date. > NullDates with no value should sort before any NullDates with a value, should > be comparable to dates as well as NullDates, and should support all the same > methods. In other words, I don't want to have to worry about whether my date > object has an actual date under most circumstances (printing, using as > dictionary keys, comparing, etc.). > > Does my design make more sense given these expanded requirements, or could it > still be done simpler? For that matter, do my requirements make sense? What Carl is saying is that since python uses duck typing ("if it quacks like a duck, it is a duck"), all you need to do is make your NullDate object quack enough like a date to handle your use cases, and then you can freely mix dates and NullDates _without having to care which one a given object is_ (python won't care). (Until you do care, at which point you can use isinstance to find out if it is a NullDate). As far as I can see, your requirements as you've outlined them can be met by mixing date objects and appropriately implemented NullDate objects. And that way NullDates will _only_ represent null dates, thus making its name more meaningful :). To do this you just need to implement on NullDate those methods that are going to give NullDate the behavior you need: the rich comparison operators, __str__, __hash__, etc. Or it might be easier to subclass date and override some of the methods. Unless I'm misunderstanding your requirements, of course :) --RDM From aahz at pythoncraft.com Fri Dec 5 18:51:43 2008 From: aahz at pythoncraft.com (Aahz) Date: 5 Dec 2008 15:51:43 -0800 Subject: RELEASED Python 3.0 final References: <874p1jux8u.fsf@benfinney.id.au> Message-ID: In article <874p1jux8u.fsf at benfinney.id.au>, Ben Finney wrote: >James Stroud writes: >> >> comp.lang.python3k ? > >The language has undergone an incompatible divide. Hopefully the >community need not do the same. Pish and tosh. James was clearly making a funny; there's not *that* much difference between 2.x and 3.x. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From deets at nospam.web.de Thu Dec 18 09:16:02 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 18 Dec 2008 15:16:02 +0100 Subject: re.match() performance References: <755bd716-f5f6-4953-87a7-04ee148c3298@i18g2000prf.googlegroups.com> Message-ID: <6qv492Feuto8U1@mid.uni-berlin.de> Emanuele D'Arrigo wrote: > Sorry for the previous post, hit the Enter button by mistake... here's > the complete one: > > Hi everybody! > > I've written the code below to test the differences in performance > between compiled and non-compiled regular expression matching but I > don't quite understand the results. It appears that the compiled the > pattern only takes 2% less time to process the match. Is there some > caching going on in the uncompiled section that prevents me from > noticing its otherwise lower speed? Yes. There is even a purge-function to clear that cache, for whatever reason. To answer that question yourself, you could have taken a look into the python library, it's not as scary as you might think :) Diez From msdark at archlinux.us Tue Dec 16 08:33:53 2008 From: msdark at archlinux.us (=?ISO-8859-1?Q?Mat=EDas_Hern=E1ndez?=) Date: Tue, 16 Dec 2008 10:33:53 -0300 Subject: mysql hash generator in python Message-ID: <4947AE41.8010204@archlinux.us> (sorry for my english, but i'm speak spanish) Hi list.. this is my first post... and obviously if for help.. I try to implement the password function of mysql in a python script. I read that the password function of mysql was implemented with a double sha1() I python i try this: example1: if __name__=="__main__": s = hashlib.sha1() s.update('test') s2 = hashlib.sha1() s2.update(s.digest() print s2.hexdigest() This script show me the same hash that password function of mysql, but when i implement this in a class the hash is different??? why??? And if is posible??? can you show a example code of old_password function of mysql in python??? THNX From aahz at pythoncraft.com Mon Dec 15 10:41:55 2008 From: aahz at pythoncraft.com (Aahz) Date: 15 Dec 2008 07:41:55 -0800 Subject: Looking for the best way to translate an idiom References: <494611c2$0$21934$426a34cc@news.free.fr> Message-ID: In article <494611c2$0$21934$426a34cc at news.free.fr>, Bruno Desthuilliers wrote: >Aahz a ?crit : >> In article , >> James Stroud wrote: >>> >>> In case its not obvious: >> >> Ah, so that's where Bruno's extra apostrophe came from! ;-) > >Err... Which one exactly ? Don't remember, it was a post I read about five minutes earlier that had something like, "...has it's place..." -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From jurgenex at hotmail.com Wed Dec 3 23:45:39 2008 From: jurgenex at hotmail.com (Jürgen Exner) Date: Wed, 03 Dec 2008 20:45:39 -0800 Subject: Mathematica 7 compares to other languages References: <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <4b6c3304-2396-4d35-a06f-e5d693cbbb12@f13g2000yqj.googlegroups.com> Message-ID: toby wrote: >On Dec 3, 4:15 pm, Xah Lee wrote: >> On Dec 3, 8:24 am, Jon Harrop wrote: >> >> > My example demonstrates several of Mathematica's fundamental limitations. >> >> enough babble Jon. >> >> Come flying $5 to my paypal account, and i'll give you real code, > >I'll give you $5 to go away if you add "and never come back" then count me in, too. jue From metolone+gmane at gmail.com Mon Dec 29 14:19:48 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Mon, 29 Dec 2008 11:19:48 -0800 Subject: How to display Chinese in a list retrieved from database via python References: <22be506d-91c2-4727-ace7-2e3382b6d214@g3g2000pre.googlegroups.com><979fdf6d-0500-47ba-87fd-0f0361ca3059@p2g2000prf.googlegroups.com><19680ed2-c78f-4ab9-8ca0-8ce26fd5b6a7@o4g2000pra.googlegroups.com><2560a6e0-c103-46d2-aa5a-8604de4d1968@b38g2000prf.googlegroups.com> <7e38e76a-d5ee-41d9-9ed5-73a2e2993733@w1g2000prm.googlegroups.com> Message-ID: "zxo102" wrote in message news:7e38e76a-d5ee-41d9-9ed5-73a2e2993733 at w1g2000prm.googlegroups.com... > On 12?29?, ??5?06?, "Mark Tolonen" wrote: >> "zxo102" wrote in message >> >> news:2560a6e0-c103-46d2-aa5a-8604de4d1968 at b38g2000prf.googlegroups.com... >> [snip] >> That said, learn to use Unicode strings by trying the following program, >> but >> set the first line to the encoding *your editor* saves files in. You can >> use the actual Chinese characters instead of escape codes this way. The >> encoding used for the source code and the encoding used for the html file >> don't have to match, but the charset declared in the file and the >> encoding >> used to write the file *do* have to match. >> >> # coding: utf8 >> >> import codecs >> >> mydict = {} >> mydict['JUNK'] = [u'??',u'??',u'??'] >> >> def conv_list2str(value): >> return u'["' + u'","'.join(s for s in value) + u'"]' >> >> f_str = u''' >> >> test >> >> >> ''' >> >> s = conv_list2str(mydict['JUNK']) >> f=codecs.open('test04.html','wt',encoding='gb2312') >> f.write(f_str % s) >> f.close() >> >> -Mark >> >> P.S. Python 3.0 makes this easier for what you want to do, because the >> representation of a dictionary changes. You'll be able to skip the >> conv_list2str() function and all strings are Unicode by default. > > Thanks for your comments, Mark. I understand it now. The list(escape > codes): ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4'] is > from a postgresql database with "select" statement.I will postgresql > database configurations and see if it is possible to return ['??','? > ?','??'] directly with "select" statement. > > ouyang The trick with working with Unicode is convert anything read into the program (from a file, database, etc.) to Unicode characters, manipulate it, then convert it back to a specific encoding when writing it back. So if postgresql is returning gb2312 data, use: data.decode('gb2312') to get the Unicode equivalent: >>> '\xd6\xd0\xce\xc4'.decode('gb2312') u'\u4e2d\u6587' >>> print '\xd6\xd0\xce\xc4'.decode('gb2312') ?? Google for some Python Unicode tutorials. -Mark From nebson at gmail.com Wed Dec 24 17:56:45 2008 From: nebson at gmail.com (Sponge Nebson) Date: Wed, 24 Dec 2008 14:56:45 -0800 (PST) Subject: PythonCard timer/thread tutorial Message-ID: <59e602b0-937c-4bd5-bc71-30094e1cd596@r36g2000prf.googlegroups.com> Hello all, This is my first post. Nice to meet you all! Could one of you walk me through this code? def myThread(*argtuple): """ A little thread we've added """ print "myThread: entered" q = argtuple[0] print "myThread: starting loop" x = 10 while True: time.sleep(10) # time unit is seconds print "myThread x=%d" % x q.put(str(x)) # stick something on message queue wx.WakeUpIdle() # triggers 'idle' handlers x += 10 It is from David McNab and Alex Tweedly's tutorial on timers and threads, which can be found here: http://pythoncard.sourceforge.net/timers-threads.html Among my questions are: """ A little thread we've added""" seems to be an isolated string. It does not seem to be doing anything there, almost like a comment. Why is it there? What is argtuple for? how does it work? What is the queue for? Thanks! -Ben From luke.leighton at googlemail.com Tue Dec 2 08:57:00 2008 From: luke.leighton at googlemail.com (lkcl) Date: Tue, 2 Dec 2008 05:57:00 -0800 (PST) Subject: Python+Pyjamas+V8=ftw References: Message-ID: <56533d3d-c5cd-4a41-9bc3-525eaa44bba1@d23g2000yqc.googlegroups.com> > Another project similar-ish to Pyjamas is > HotRuby:http://hotruby.yukoba.jp/ also there's RubyJS: http://rubyforge.org/projects/rubyjs/ it's again a javascript compiler - ruby to javascript - and the beginnings of a port of GWT to Ruby, called rwt. this project _definitely_ needs more attention. michael's talk (included in the docs/) shows that he has spent considerable effort in ensuring that not only is the compiler faithful to the features of ruby, but also that the features are translated _efficiently_. which takes a hell of a lot of doing. the nice thing about michael's work is that he's leading the way in showing the pyjamas compiler how it _really_ should be done. pyjamas is capable of running a very significant amount of python, but it _is_ missing some crucial features: **kwargs for example, and the 0.4 release has just added a _very_ basic type of exception handling. that having been said: for the majority of purposes - most web development - pyjamas is _more_ than adequate. as a general-purpose plugin replacement for /usr/bin/python, however, it's not quite there. and, given that javascript cheerfully goes about its way with the "undefined" concept, it's always going to be a _bit_ tricky to provide absolutely _every_ language feature, faithfully. that having been said, the speedup factor of pyv8 should make the pyjamas compiler a _really_ attractive option, and i think that when it becomes the "norm" to have a javascript interpreter as part of a sysadmin's / developer's dailiy life in the same way that /usr/bin/ perl and /usr/bin/python are, then compilers like RubyJS, Pyjamas and GWT will have a much bigger significance. l. From jarausch at igpm.rwth-aachen.de Tue Dec 2 04:34:18 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Tue, 02 Dec 2008 10:34:18 +0100 Subject: Is it safe to modify the dict returned by vars() or locals() In-Reply-To: References: <4934508b$0$2861$ba620e4c@news.skynet.be> Message-ID: <4935011A.9080406@igpm.rwth-aachen.de> Chris Rebert wrote: > On Mon, Dec 1, 2008 at 1:01 PM, Helmut Jarausch wrote: >> Hi, >> >> I am looking for an elegant way to solve the following problem: >> >> Within a function >> >> def Foo(**parms) >> >> I have a list of names, say VList=['A','B','C1'] >> and I like to generate abbreviation >> _A identical to parms['A'] > > Could you explain what you mean by that? Your sample code doesn't seem > to do any "abbreviation"... > Otherwise I don't see why you don't just have a proper parameter list. In my application parms contains field names of an html form iff these fields have been modified. I'd like to use the short name _A instead of the longer expression parms['A'] -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From lambertdw at corning.com Thu Dec 11 12:04:16 2008 From: lambertdw at corning.com (lambertdw at corning.com) Date: Thu, 11 Dec 2008 09:04:16 -0800 (PST) Subject: if expression source format References: Message-ID: <662cc393-d9bd-48d2-9b6e-54b9ae416c94@m15g2000vbp.googlegroups.com> Consider following snippets: # must examine code carefully to see that result has a value if condition: result = expression1 else: result = another_expression return result # result has a value but difficult to understand how it comes about result = expression1 if condition else another_expression return result # must examine code carefully to ensure that it always # returns a computed value if condition: return true_expression else: return false_expression # Ahh! I do use this idiom quite often. if condition: return true_expression return default_expression Actually, I was simply wondering if there is yet a preferred way to write the python ternary expression. Samples: # break expression near convenient max line length A) true_expression if condition else (fa lse_expression) # break expression near convenient max line length B) # ("Humans be damned!" form.) true_expr \ ession if cond \ ition else \ false_e \ xpressi \ on # ternary nature of expression extremely visible (true_expression if condition else false_expression) # I use this form but not happily, # providing functions as necessary to make it fit onto two lines # loosely guided by the K&R admonition (or maybe it was K&P) that # "a conditional expression is too complicated if you can't read # it to your mother over the phone" or something like that. (true_expression if condition else false_expression) From bearophileHUGS at lycos.com Fri Dec 5 10:46:02 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 5 Dec 2008 07:46:02 -0800 (PST) Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> <20081205161725.3f35222b@usenot.de> Message-ID: <534215df-0ba3-471a-b4d4-e495a3e4daf7@w35g2000yqm.googlegroups.com> Andreas Waldenburger: > My point is: If you mix tabs and spaces in a way that breaks code, > you'll find out pretty easily, because your program will not work. - Most newbies don't know that. - Sometimes it may produce wrong results. - And even if you are an expert when you go changing a little a source code that mixes tabs and spaces you usually break the code. Is this enough for you? Bye, bearophile From steve at REMOVE-THIS-cybersource.com.au Sat Dec 27 00:00:26 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Dec 2008 05:00:26 GMT Subject: raw_input can't handle pound sign? References: Message-ID: <0165ad86$0$6988$c3e8da3@news.astraweb.com> On Fri, 26 Dec 2008 20:20:16 -0800, Jugdish wrote: > Hi, I'm having problems getting a pound sign to go through as input sent > to the raw_input() command. I'm running Python 2.5.1 on Windows XP. > Here's my simple little script: > > while True: > response = raw_input("Please enter a file name: ") if > os.path.exists(response): > break > > Problem is if the filename has a "#" in it, the script interprets that > as the beginning of a comment (not sure why -- isn't raw_input supposed > to treat the user's input as raw text and not do any sort of evals?) Yes it is. What makes you think it is being interpreted as a comment? What results are you getting? > Any ideas how to get a # to go through? Thanks! Works for me (although I'm not using Windows XP). Can you execute this line at the interactive interpreter? print raw_input("Type something with a hash sign: ") At the prompt, type "test # string" (without the quotes) and show us what result you get. When I do this, I get the following: >>> print raw_input("Type something with a hash sign: ") Type something with a hash sign: test # string test # string -- Steven From kyosohma at gmail.com Wed Dec 24 19:59:23 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 24 Dec 2008 16:59:23 -0800 (PST) Subject: PythonCard timer/thread tutorial References: <59e602b0-937c-4bd5-bc71-30094e1cd596@r36g2000prf.googlegroups.com> Message-ID: <6f7164cc-56dc-4022-8943-067b8ca44e61@40g2000prx.googlegroups.com> On Dec 24, 4:56?pm, Sponge Nebson wrote: > Hello all, > > This is my first post. Nice to meet you all! Could one of you walk me > through this code? > > ? ?def myThread(*argtuple): > ? ? ? ? """ > ? ? ? ? A little thread we've added > ? ? ? ? """ > ? ? ? ? print "myThread: entered" > ? ? ? ? q = argtuple[0] > ? ? ? ? print "myThread: starting loop" > ? ? ? ? x = 10 > ? ? ? ? while True: > ? ? ? ? ? ? time.sleep(10) # time unit is seconds > ? ? ? ? ? ? print "myThread x=%d" % x > ? ? ? ? ? ? q.put(str(x)) # stick something on message queue > ? ? ? ? ? ? wx.WakeUpIdle() # triggers 'idle' handlers > ? ? ? ? ? ? x += 10 > > It is from David McNab and Alex Tweedly's tutorial on timers and > threads, which can be found here: > > ?http://pythoncard.sourceforge.net/timers-threads.html > > Among my questions are: > """ A little thread we've added""" seems to be an isolated string. It > does not seem to be doing anything there, almost like a comment. Why > is it there? That's what some people call a doc string. It is like a comment in that it helps the user know what the function is for. Notice the triple quotes. If you were to type "help(myFunction)", it would grab the functions doc string and display it. You can read up on them here: http://diveintopython.org/getting_to_know_python/documenting_functions.html > > What is argtuple for? how does it work? This allows the programmer to pass an arbitrarily long argument list to the function. It took a little digging, but I found it in the docs (scroll down towards the bottom): http://docs.python.org/tutorial/controlflow.html#SECTION006600000000000000000 > > What is the queue for? > > Thanks! > > -Ben I haven't messed with queues as yet, but they are one way of dealing with multiple threads in GUI programming. The idea is to stick something in the queue for the GUI thread (or potentially some other thread) to pick up when it's not busy. So one thread sticks something on the queue and another thread checks the queue periodically to see if there's something there and if there is, it picks it up. At least, that's my understanding. You can read up on various methods of messing with threads in wxPython here: http://wiki.wxpython.org/LongRunningTasks And here are the queue docs (for 2.6...): http://docs.python.org/library/queue.html I recommend learning how to use Google effectively. I found about half the links above using it. You might also find joining the wxPython mailing list beneficial. I learn a lot there just by reading and posting to it: http://wxpython.org/maillist.php - Mike From hatchar at gmail.com Fri Dec 26 20:30:32 2008 From: hatchar at gmail.com (kather) Date: Fri, 26 Dec 2008 17:30:32 -0800 (PST) Subject: online money earnings In-Reply-To: References: Message-ID: <21180899.post@talk.nabble.com> Classical program and new investment programs . Join here : Paying : http://www.geniusfunds.com/?c=501251 http://www.geniusfunds.com/ Seem not bad : http://www.forexinv.net/?refer=jhon1092 http://www.forexinv.net/ -- View this message in context: http://www.nabble.com/online-money-earnings-tp17422431p21180899.html Sent from the Python - python-list mailing list archive at Nabble.com. From huwdjones at gmail.com Mon Dec 15 04:44:06 2008 From: huwdjones at gmail.com (huw_at1) Date: Mon, 15 Dec 2008 01:44:06 -0800 (PST) Subject: cx_Oracle issues References: <5b2dad81-2750-4347-8079-6ab31321d579@s1g2000prg.googlegroups.com> <9142a8f1-7f76-4fc0-9ca1-c9dec310f2ce@r37g2000prr.googlegroups.com> Message-ID: <9f436c9e-2319-499c-a306-d255996372fc@e22g2000vbe.googlegroups.com> On Dec 11, 5:34?pm, "ron.re... at gmail.com" wrote: > On Dec 10, 9:48?am, huw_at1 wrote: > > > > > Hey all. When using cx_Oracle to run a procedure like: > > > cursor.execute("select (obj.function(value)) from table where > > id=blah") > > > I am getting the following error: > > > ORA-06502: PL/SQL: numeric or value error: character string buffer too > > small ORA-06512: at line 1 > > > Looking at cursor.description I get: > > > [('(obj.function(value))', , 4000, 4000, 0, > > 0, 1)] > > > Any tips - i have never seen this error before but am guessing that > > the value being returned is too big for the buffer size set for the > > cursor. the procedure fetches data from a LOB. > > > Any suggestions/confirmations? > > > Many thanks > > This error is a problem with the PL/SQL, not cx_Oracle. ?You need to > debug obj.function to see what kind of data is being accessed and then > a data analysis of that data to understand why this error occurs. ?I > can tell you the function is most likely expecting characters from a > column that are numeric [0 .. 9] and is getting alpha characters. > > -- > Ron Reidy > Sr. Oracle DBA Hi thanks for the responses. Unfortunately the procedure in question is from a third party vendor so I can't really debug it so I'd say I was fairly stumped. Just out of interest how do you increase the output buffer size with cx_Oracle? Many thanks From steve at holdenweb.com Wed Dec 24 07:59:17 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 24 Dec 2008 07:59:17 -0500 Subject: Multi-dimension list In-Reply-To: References: Message-ID: James Stroud wrote: > Steven Woody wrote: >> Hi, >> >> In the book Python Essential Reference, Chapter 3, when talking about >> extended slicing, it gives an example: a = m[0:10, 3:20]. But I >> don't understand how the 'm' was defined. What should it looks like? > > m could be an instance of the Krayzee class. > > py> class Krayzee(object): > ... def __getitem__(self, i): > ... try: > ... r = ['WTF?' for j in i] > ... except: > ... r = 'WTF?' > ... return r > ... > py> m = Krayzee() > py> m[1:2:3, 4:5:6] > ['WTF?', 'WTF?'] > py> m['your moms'] > ['WTF?', 'WTF?', 'WTF?', 'WTF?', 'WTF?', 'WTF?', 'WTF?', 'WTF?', 'WTF?'] > > I'm not sure what this is supposed to prove. It might be more helpful to show what's actually going on ... >>> class k(object): ... def __getitem__(self, i): ... try: ... r = [j for j in i] ... except Exception, e: ... print i, ":", e ... r = i ... return r ... >>> m = k() >>> m[1:2:3, 4:5:6] [slice(1, 2, 3), slice(4, 5, 6)] >>> m["help!"] ['h', 'e', 'l', 'p', '!'] >>> As you can see, no exceptions are raised here, and the x:y:z notation introduces a slice object, which the code doesn't handle in any way shape or form. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From dmitrey.kroshko at scipy.org Mon Dec 15 17:32:23 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Mon, 15 Dec 2008 14:32:23 -0800 (PST) Subject: OpenOpt 0.21 (free optimization framework) Message-ID: Hi all, OpenOpt 0.21, free optimization framework (license: BSD) with some own solvers and connections to tens of 3rd party ones, has been released. All details here: http://openopt.blogspot.com/2008/12/openopt-release-021.html Regards, OpenOpt developers. From duncan.booth at invalid.invalid Mon Dec 1 04:54:01 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Dec 2008 09:54:01 GMT Subject: Emacs vs. Eclipse vs. Vim References: Message-ID: Roy Smith wrote: > Clay Hobbs wrote: >> The first real text editor I used was Vim, which I actually started >> using about a year ago. I've looked at Emacs and it just looks >> confusing. > > I've been using emacs for so many years (um let's see, it's got to be > close to 25 years now; first saw it on Columbia's TOPS-20 systems in > the early 80's) that my fingers know what they're doing without my > even thinking about it. In fact, I used to work with another emacs > nut. Every so often, one of use would watch the other do something > and ask, "What was that?". Inevitably, neither of us could evoke the > keystrokes we had just typed. We would just re-do it, and watch our > fingers to see what we typed. It didn't even have to be on a > keyboard; we could air-type it, and that was good enough. > I also started using Emacs about 25 years ago, but then when I moved to using DOS machines which at the time weren't capable of running Emacs I suffered withdrawal symptoms until I found Epsilon (http://lugaru.com) which started life as an Emacs style editor on DOS. I still use Epsilon today, even when I'm using Linux: it isn't free software in any sense of the word, but I find that a lot of the things I use it for it actually does better than Emacs. If you are willing to consider paying for an editor then download the evaluation copy of Epsilon and give it a go. -- Duncan Booth http://kupuguy.blogspot.com From cmpython at gmail.com Mon Dec 22 05:10:22 2008 From: cmpython at gmail.com (CM) Date: Mon, 22 Dec 2008 02:10:22 -0800 (PST) Subject: wxpython for python 3.0 ? References: Message-ID: <3381d5f8-2a62-45ec-900c-d9849e3cc554@x38g2000yqj.googlegroups.com> On Dec 21, 4:42?pm, dlemper wrote: > The wxpython web describes compatability with python 2.4 & 2.5 . > Does it work with 3.0 ? ? If not, anyone have a clue as to when ? Not yet. I think it will be a while until then. From fetchinson at googlemail.com Sun Dec 28 02:44:29 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 27 Dec 2008 23:44:29 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: >>> As others already said, using a Numpy array or an array.array object >>> would >>> be more efficient (and even easier - the C code gets a pointer to an >>> array >>> of integers, as usual). >> >> I looked for this in the C API docs but couldn't find anything on how >> to make an array.array python object appear as a pointer to integers >> (or floats, etc) in C code. On >> >> http://docs.python.org/c-api/concrete.html#sequence-objects >> >> There is only list and tuple or maybe you mean byte array? That has >> only been introduced in python 2.6 and I'm working on 2.5. > > array is a library module, and isn't really part of the API. You're > looking for the buffer protocol: > PyObject_AsReadBuffer/PyObject_AsWriteBuffer; see > http://docs.python.org/c-api/objbuffer.html > > Given an array.array('l') (containing C long integers): > > int do_something(PyObject* obj) > { > long *vec; > Py_ssize_t nbytes, nitems, i; > > if (PyObject_AsReadBuffer(obj, (const void **)&vec, &nbytes) != 0) > return NULL; > nitems = nbytes/sizeof(long); > for (i=0; i /* do something with vec[i] */ > } > return ret; > } > > From Python you can get "vec" and "nitems" using the buffer_info() method > of array objects. Thanks very much, this was very helpful! Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From bearophileHUGS at lycos.com Thu Dec 25 13:55:51 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 25 Dec 2008 10:55:51 -0800 (PST) Subject: Exec inside a class method to call other class methods? References: Message-ID: <3dc6f013-3f10-425f-bd65-d44b5ffe5a67@40g2000prx.googlegroups.com> Matthew Dubins: > def parse(self, data, data_type) > ? ? exec "self.__parse_%s(data)" % data_type > For some reason, *it didn't work*. You can try defining this class attribute: data_types = set("nocall DOB gender Prematurity email languages phone cname pname address duedate".split()) And then a possible method can be: def parse(self, data, data_type): if data_type in Classname.data_types: getattr(self, "__parse_" + data_type)(data) If performance isn't a problem you can move data_types inside the parse method. If performance is a problem, data_types may become a dict, whose values are references to the methods. That you can use as: def parse(self, data, data_type): if data_type in data_types: data_types[data_type](data) Or even as (but may be a little slower): def parse(self, data, data_type): data_types.get(data_type, lambda x: None)(data) Bye, bearophile From ht at example.com Thu Dec 4 14:35:43 2008 From: ht at example.com (HT) Date: Thu, 04 Dec 2008 11:35:43 -0800 Subject: Why shouldn't you put config options in py files Message-ID: A colleague of mine is arguing that since it is easy to write config like: FOO = {'bar': ('a': 'b'), 'abc': ('z': 'x')} in config.py and just import it to get FOO, but difficult to achieve the same using an ini file and ConfigParser, and since Python files are just text, we should just write the config options in the Python file and import it. I can think of lots of arguments why this is a bad idea, but I don't seem to be able to think of a really convincing one. Anyone? From expora at gmail.com Mon Dec 8 21:01:38 2008 From: expora at gmail.com (Edwin) Date: Mon, 8 Dec 2008 18:01:38 -0800 (PST) Subject: Programming exercises/challenges References: <1d6140d1-7eff-49ee-bc2c-5b3d8868897a@13g2000yql.googlegroups.com> <9fd90236-63bd-4e60-8c88-c0d69b06b84f@41g2000yqf.googlegroups.com> Message-ID: <57a0b1da-b0e5-4626-90bb-7824d8328ee4@v42g2000yqv.googlegroups.com> On Nov 22, 2:15?am, Arnaud Delobelle wrote: > I'm only a very occasional user of vi, so I don't really know how vim > integrates with MacOS X but have you tried aquamacs > (http://aquamacs.org/)? > > -- > Arnaud I've tried it but I ended up using original (I'm sure there's a better adjective) Emacs compiled --with-ns... it's very nice (at least for what I do, in the little experience I've gained). Cheers, From MLDSpenser at aol.com Thu Dec 25 21:24:41 2008 From: MLDSpenser at aol.com (MLDSpenser at aol.com) Date: Thu, 25 Dec 2008 21:24:41 EST Subject: dummy needs help with Python Message-ID: I am trying to find somebody who can give me a simple python program I can use to "program by analogy". I just want to read two CSV files and match them on several fields, manipulate some of the fields, and write a couple of output files. I come from 30 years of mainframe programming so I understand how computers work at a bits/bytes /machine language/ source vs.executable/reading core dumps level, and I can program in a lot of languages most people using Python have never even heard of, but I don't know any of the modern jargon; the Python home site is full of statements that mean nothing to me. I can't understand the descriptions of most of the software in the Python Package Index. I can't even figure out most of the descriptions of the help available in the Python community, so sending this e-mail may be highly inappropriate. Please forgive me if this is so, and take pity on a stranger in a strange land. I have done some Python programming in a module supplied by the author of software (Readerware) I bought; he takes care of all the file handling outside of the module he lets you mess with; I just manipulated selected fields he had defined. It seems like a fantastic language but I need help. My problem is that I want to do this all yesterday, and the Python text I bought is not easy to understand. I don't have time to work my way through the online Python tutorial. I've tried a couple of forums but nobody has answered my questions. A simple program with comments that say "here's where I read File A and define/map/ the fields in it" would let me learn by testing and trying things out, the same way I learned to work with the fields in the module. Peace on earth to all people of good will. Margie Spenser Pittsburgh, PA -------------- next part -------------- An HTML attachment was scrubbed... URL: From joe at strout.net Fri Dec 12 11:07:21 2008 From: joe at strout.net (Joe Strout) Date: Fri, 12 Dec 2008 09:07:21 -0700 Subject: concept of creating structures in python In-Reply-To: References: Message-ID: <25EDE674-3566-4720-BCEB-6A4D3865C9E2@strout.net> On Dec 12, 2008, at 9:00 AM, Steve Holden wrote: >> Change the default value of ds_obj here to None. Otherwise, you will >> certainly confuse yourself (there would be just one default object >> shared among all instances). >> > Joe missed a piece out here. If you change the signature of your > D.__init__() to read > > def __init__(self, dataName='ND', index = 0, ele_obj=None): > > then you need to insert the following code at the top of the method: > > if ele_obj is None: > ele_obj = E() Yes, if you really need to guarantee that ele_obj is not None, then this is the way to do it. Of course this would mean that you can't get a None ele_obj even by passing it in explicitly as the parameter value -- if you need to support that as well, then the solution is a little more complex. Perhaps best in that case would be to just not give ele_obj any default value at all, so it becomes a required parameter. Best, - Joe From steve at holdenweb.com Mon Dec 15 10:47:28 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 15 Dec 2008 10:47:28 -0500 Subject: Looking for the best way to translate an idiom In-Reply-To: References: Message-ID: James Stroud wrote: > Aahz wrote: >> In article , >> James Stroud wrote: >>> In case its not obvious: >> >> Ah, so that's where Bruno's extra apostrophe came from! ;-) >> >> >> (Sorry about the spelling flame, but seeing three posts in quick >> succession with incorrect spelling of its/it's pushed me into making a >> public comment.) > > Yes. I think it was the British who decided that the apostrophe rule for > "it" would be reversed from normal usage relative to just about every > other noun. I'm not sure the purpose--maybe it was to give compulsive > proofreaders a raison d'etre. In fact it applies to personal pronouns generally, though in English most personal pronouns have an irregular genitive. I me my mine you you your yours he him his his she her her hers it it its its we us our ours you you your yours they them their theirs regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From walterbyrd at iname.com Thu Dec 11 13:21:55 2008 From: walterbyrd at iname.com (walterbyrd) Date: Thu, 11 Dec 2008 10:21:55 -0800 (PST) Subject: Is 3.0 worth breaking backward compatibility? References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> <20081207203553.7d62434a@usenot.de> Message-ID: <4731f7cf-ef15-4328-85a4-de4437009f2e@40g2000prx.googlegroups.com> On Dec 7, 12:35?pm, Andreas Waldenburger wrote: > Pleeeeze. Python 3 is shipping now, and so is 2.x, where x > 5. Python > 2 is going to be around for quite some time. What is everybody's > problem? A possible, potential, problem, could arise if you were using python 2.x, but some other code, that you wanted to include, was writen in python 3.x. It always surprises me that so many python developers never consider the possibility that you may not always be working with your own code. From rcdailey at gmail.com Mon Dec 8 11:22:55 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 8 Dec 2008 08:22:55 -0800 (PST) Subject: Equivalent of 'wget' for python? Message-ID: Hi, I'm looking for a portable way to download ZIP files on the internet through Python. I don't want to do os.system() to invoke 'wget', since this isn't portable on Windows. I'm hoping the core python library has a library for this. Note that I'll be using Python 3.0. Thanks. From nils.krahnstoever at gmail.com Thu Dec 11 00:19:51 2008 From: nils.krahnstoever at gmail.com (Nok) Date: Wed, 10 Dec 2008 21:19:51 -0800 (PST) Subject: Call by reference in SWIG? Message-ID: I can't get call-by-reference functions to work in SWIG... Even when wrapping a trivial example like this: /* File : trivial.i */ %module trivial %inline %{ class test { public: void foo(int *t) { *t=42; } }; %} I get a TypeError when trying to use it: import trivial x=10 c=trivial.test() c.foo(x) The error is: def foo(*args): return _trivial.test_foo(*args) TypeError: in method 'test_foo', argument 2 of type 'int &' From wuwei23 at gmail.com Mon Dec 8 23:39:34 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 8 Dec 2008 20:39:34 -0800 (PST) Subject: How to initialize a class variable once References: Message-ID: <707edf86-c223-4cf5-b6ca-a7c396a5edce@t26g2000prh.googlegroups.com> On Dec 9, 2:08?pm, Roy Smith wrote: > I've got a class with a class variable: > > class Foo: > ? ?_map = {} > > How do I make sure this only gets initialized the *first* time the > module containing the class is imported? ?What appears to be happening > as it stands is each time the module gets imported, Foo._map get re- > initialized. What you're asking for is actually the default behaviour. The Foo class should only be created once, on the first import, and all subsequent imports should refer to it: foo.py: class Foo: _map = {} a.py: from foo import Foo Foo._map['a'] = 1 b.py: from foo import Foo print Foo._map c.py: import a import b This outputs "{'a': 1}", as expected. The Foo._map that b.py prints is the same Foo._map that a.py has modified. You might need to provide some more details about your code. From google at mrabarnett.plus.com Sun Dec 21 19:14:22 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 22 Dec 2008 00:14:22 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: <494EDBDE.3020307@mrabarnett.plus.com> Aaron Brady wrote: > On Dec 21, 10:58 am, MRAB wrote: >> Aaron Brady wrote: >>> On Dec 21, 10:31 am, MRAB wrote: > snip >>>> The original format is a string. The result of '%' is a string if >>>> there's only 1 placeholder to fill, or a (partial) format object (class >>>> "Format"?) if there's more than one. Similarly, the format object >>>> supports '%'. The result of '%' is a string if there's only 1 >>>> placeholder to fill, or a new (partial) format object if there's more >>>> than one. >>>> >>> f = "%r %i" >>>> >>> type(f) >>>> >>>> >>> f = f % (2, 3, 4) >>>> >>> type(f) >>>> >>>> >>> f = f % 1 >>>> >>> type(f) >>>> >>> Alright, so how are you handling: >>>>>> f= "%s %i" >>>>>> type( f ) >>> >>>>>> f= f% '%i' #now '%i %i' >>>>>> type( f ) >>> >>>>>> f= f% 1 >>>>>> type( f ) >>> ? >>> In other words, are you slipping '1' in to the very first available >>> slot, or the next, after the location of the prior? >> Let's assume that Format objects display their value like the equivalent >> string format: >> >> >>> f = "%r %i" >> >>> f >> '%r %i' >> >>> f = f % (2, 3, 4) >> >>> f >> >> >>> f = f % 1 >> >>> f >> '(2, 3, 4) 1' >> >>> >> >>> f = "%s %i" >> >>> f >> '%s %i' >> >>> f = f % '%i' >> >>> f >> >> >>> f = f % 1 >> >>> f >> '%%i 1' > > I assume you meant '%i 1' since there are no more flags in f, and it's > returned to a regular string. > Correct. > 'f %= 1' doesn't work any more as in-place modulo, since one time, 'f' > is a Format object, the other, 'f' is a string. Just raise an > exception for that (or assign to __class__ IINM if I'm not mistaken). > All assignments rebind, even the augmented form: >>> class C1(object): def __mod__(self, value): return C2() >>> class C2(object): def __mod__(self, value): return C2() >>> f = C1() >>> f <__main__.C1 object at 0x00D144F0> >>> f % 0 <__main__.C2 object at 0x00D143F0> >>> f %= 0 >>> f <__main__.C2 object at 0x00D145B0> > Actually, the class you showed is kind of nifty. Tuples are correctly > interpolated. I think on the whole you'll use more parenthesis, since > each term in the tuple appears separately, and might be an expression > (have a lower-precedence op.), as well as more modulo signs. > > You can currently do-it-yourself, you just need a constructor in the > format string. > >>>> f = Format("%r %i") >>>> type(f) > >>>> f = f % (2, 3, 4) >>>> type(f) > > > Or, as someone suggested earlier, a new literal marking: > Yes, I suggested that earlier, but it isn't needed because you can create a format object with "Format(string)". However, most of the time you won't bother to create a format object explicitly because of: class str(object): def __mod__(self, value): return Format(self) % value >>>> f = f"%r %i" >>>> type(f) > > >>> # Explicitly >>> f = Format("%r %i") >>> f >>> f % (2, 3, 4) >>> >>> # Implicitly, relying on the __mod__ method of str >>> f = "%r %i" >>> f '%r %i' >>> f % (2, 3, 4) I'd also like to add that there's nothing to prevent format objects from having other methods where multiple placeholders can be filled in one call: >>> # By position >>> f = Format("%r %i") >>> f >>> f.fill([(2, 3, 4), 1]) '(2, 3, 4) 1' >>> >>> # By name >>> f = Format("%{tuple}r %{int}i") >>> f >>> f.fill({"tuple": (2, 3, 4), "int": 1}) '(2, 3, 4) 1' From bockman at virgilio.it Wed Dec 31 03:31:57 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: Wed, 31 Dec 2008 09:31:57 +0100 Subject: MemoryError when list append... plz help In-Reply-To: References: Message-ID: <495b2dfe$0$11377$5fc30a8@news.tiscali.it> [BON] ha scritto: > ====================== > s=[] > for i in range(11000-1): > for j in range(i+1, 11000): > .... > s.append(((i,j),sim)) > ====================== > above sim is floating type. > s.append is totally coducted 60,494,500 times. > but this code raise MemoryError. > > My computer has 4G RAM. > i think it's enough. but it doesn't... > > So, i've tested below code. > ====================== > a=[] > i=0 > while i<60494500 : > a.append(i) > i+=1 > ====================== > but this code raise also MemoryError. > > How can i resolve this problem? > please, help... > > Regards, If you _really_ have to store so many numbers in memory (hint: if you are processing them sequentially, you don't need to store all them - use generators instead) then you may have better luck using mmap module to create a huge file-memory object, that you can access both as a file and as a list, and put numbers in it after packing/unpacking with struct. Something like this (only marginally tested ): >>> memory = mmap.mmap(-1, 60494500*4) >>> def memory_put(offset, f): ... memory[offset*4:(offset+1)*4] = struct.pack( "%f", f ) >>> def memory_get(offset): ... return struct.unpack( "f", memory[offset*4:(offset+1)*4] )[0] >>> memory_put(12, 3.14 ) >>> memory_get(12) 3.1400001049041748 Ciao ------ FB From Scott.Daniels at Acm.Org Tue Dec 16 16:59:24 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 16 Dec 2008 13:59:24 -0800 Subject: Need help improving number guessing game In-Reply-To: <4947742c$0$25951$426a34cc@news.free.fr> References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> <01564c98$0$21844$c3e8da3@news.astraweb.com> <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> <4946df78$0$19771$426a74cc@news.free.fr> <1f33580b-84f9-4059-a0f0-b6a8d71325af@b38g2000prf.googlegroups.com> <4947742c$0$25951$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > .... The generic version of your above code could be: > > def safeinput(prompt, convert): > while True: > x = input(prompt) > try: > x = convert(x) > except ValueError, e: > print("Bad input : %s" % e) > else: > return x Or (I think more straightforwardly): def safeinput(prompt, convert): while True: text = input(prompt) try: return convert(text) except ValueError as e: print("Bad input ({0!r}): {1}".format(text, e)) > ... > > def yesno(s): > s = s.strip().lower() > if not s in ("y", "n"): > raise ValueError("please answer with 'y' or 'n'") > # we return a boolean > return s == 'y' def yesno(s): s = s.strip().lower() if s in ("y", "n"): return s == 'y' # return a boolean raise ValueError("please answer with 'y' or 'n'") > def int_in_range(x, mini, maxi): > x = int(x) > if not mini <= x <= maxi: > raise ValueError("%s is not in range (%s, %s)" % (x, mini, maxi)) > return x def int_in_range(x, below, above): x = int(x) # may cause ValueError on its own if below < x < above: return x raise ValueError("{0} is not between {1} and {2}".format( x, mini, maxi)) These changes are mostly: (1) Negated tests are harder yo read (2) raise and return change the flow of control, so if ...: else: ... is "fat" (more trouble to read). (3) Adopting to the new 3.0 string formatting. --Scott David Daniels Scott.Daniels at Acm.Org From sukeerthmex at gmail.com Sun Dec 7 03:29:13 2008 From: sukeerthmex at gmail.com (suku) Date: Sun, 7 Dec 2008 00:29:13 -0800 (PST) Subject: can graphs be made in python as we make in java Message-ID: <89ff42d1-6a4c-4d45-a646-238b43e7e8de@s9g2000prm.googlegroups.com> HI folks... i need some suggestion on making graphs. Will this be possible with normal python setup file or do i need to download add ons for that.. help me out From darcy at druid.net Wed Dec 24 11:44:45 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 24 Dec 2008 11:44:45 -0500 Subject: python web programming for PHP programmers In-Reply-To: References: Message-ID: <20081224114445.a954ed62.darcy@druid.net> On Wed, 24 Dec 2008 14:40:31 +0000 (UTC) Nikola Skoric wrote: > a general python tutorial, I just need a tutorial on how to make a > hello world server side script with python. Any suggestions? #! /usr/bin/env python import sys, re colour = re.sub('=', '=#', ''.join(sys.argv[1:])) print """Content-type: text/html Hello World

    Hello World

    """ % colour print """

    Hello World """ -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From castironpi at gmail.com Mon Dec 29 11:03:54 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 08:03:54 -0800 (PST) Subject: why cannot assign to function call References: Message-ID: On Dec 29, 12:01?am, scsoce wrote: > I have a function return a reference, and want to assign to the > reference, simply like this: > ?>>def f(a) > ? ? ? ? ? return a > ? ? ?b = 0 > ? ? * f( b ) = 1* > but the last line will be refused as "can't assign to function call". > In my thought , the assignment is very nature, ?but ?why the interpreter > refused to do that ? 'Why' is a long question. The syntax has advantages and disadvantages (pros and cons), which weigh different amounts in different languages. In Python, the cons weigh more. In C, the pros weigh more. The short answer is, there is no such thing as assigning to objects, only to variables. You are talking like it could save you ten lines of code or something. From icanbob at gmail.com Wed Dec 10 15:32:02 2008 From: icanbob at gmail.com (bobicanprogram) Date: Wed, 10 Dec 2008 12:32:02 -0800 (PST) Subject: upgrading my SIMPL Programming with Python nofee online course need some volunteer testers Message-ID: <8576fde2-b407-4ab8-b92d-4d76f1d469d9@r36g2000prf.googlegroups.com> SIMPL is an open source project which has been around for almost 10 years. It maintains a very compact interprocesss communication library which gives Linux developers the Send/Receive/Reply messaging paradigm first popularized by QNX almost 30 years ago. (http://www.icanprogram.com/simpl). SIMPL has had a Python shared library for almost 5 years now. I believe that the SIMPL-Python hooks are one of the underused gems in the SIMPL project. I also maintain a couple of nofee online courses including one whose subject is this Python interface into the SIMPL world (although I'm not the author of the lesson material). http://www.icanprogram.com/06py/main.html There is active work in the SIMPL project to bring two upgrades in the Python area. a) the ability to run Python code on Windows and seamlessly interface with a SIMPL application running under Linux b) the ability to interface to a SIMPL-Python application from a simple browser interface The plan is to enhance this course material with this new functionality just as soon as it arrives. Meanwhile I've been working to upgrade the course installation experience with a self installing archive. http://www.icanprogram.com/python.self.html I'm exactly the wrong person to debug this stuff as I'm not a Python programmer and I'm too close in to spot the obvious flaws. I'm looking for Python/Linux volunteers to give this stuff a spin and supply constructive criticism to help improve the student installation experience. Thanks in advance. bob SIMPL project coordinator PS. If anyone is interested in reading more about SIMPL and SIMPL-Python I'm the co-author of a recent book on the subject. Google Books has a free preview of many of the chapters. (see http://www.icanprogram.com/lulu.html). From nagle at animats.com Thu Dec 4 12:24:54 2008 From: nagle at animats.com (John Nagle) Date: Thu, 04 Dec 2008 09:24:54 -0800 Subject: "as" keyword woes In-Reply-To: <493701f0$0$194$e4fe514c@news.xs4all.nl> References: <493701f0$0$194$e4fe514c@news.xs4all.nl> Message-ID: <49380c25$0$2766$742ec2ed@news.sonic.net> > Warren DeLano wrote: >> Why was it necessary to make "as" a reserved keyword? Embrace the pain. John Nagle From geekmail at usenot.de Sat Dec 6 05:30:00 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sat, 6 Dec 2008 11:30:00 +0100 Subject: Guido's new method definition idea References: <48db9$493a3e2b$d9a2276f$10794@news.hispeed.ch> <6puuasFa29upU1@mid.uni-berlin.de> Message-ID: <20081206113000.4da8b7df@usenot.de> On 6 Dec 2008 09:18:20 GMT Marc 'BlackJack' Rintsch wrote: > On Sat, 06 Dec 2008 09:56:12 +0100, Antoine De Groote wrote: > > [snip reference to "preferably only one way to do it"] > > The reason why I'm against that change too. It adds a second, > alternative way to express something that is already in the language. > > > I agree that for newcomers to Python, the class method definition > > might seem strange. > > And after the change it continues to because they will run into > *both* variants in tutorials, code, and books, so it might be even > more confusing. > I agree with that view. Not much to add to it, just increasing the weight. /W -- My real email address is constructed by swapping the domain with the recipient (local part). From gandalf at shopzeus.com Tue Dec 9 03:52:38 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 09 Dec 2008 09:52:38 +0100 Subject: ORB for Python and PHP In-Reply-To: <6q5idtFb0dk0U1@mid.uni-berlin.de> References: <6q5idtFb0dk0U1@mid.uni-berlin.de> Message-ID: <493E31D6.9010106@shopzeus.com> >> >> There are others but they do not support both Python and PHP. Should >> I implement my own ORB, or do you know a suitable solution? > > > The whole purpose of an ORB ist that it is interoperable. So if you > have a good python orb (I personally prefer OmniORB), and a good one > for PHP - connect them. Are all ORBs compatible with each other? I know that this is offtopic, but do you know any ORB for PHP? I couldn't find any. > I would suggest a consistent XMLRPC-interface though. Unfortunately, this would not be good. Sometimes we need to pass through binary data (image file), do session management (which is hard to do with xml-rpc, where each request is a new connection) and optimize speed for communication when the parties are on the same machine. Laszlo From deets at nospam.web.de Tue Dec 2 14:58:47 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 02 Dec 2008 20:58:47 +0100 Subject: help me~!about base64 In-Reply-To: <0ff1ba7b-8a17-4647-99fc-9c8e32f83de7@g1g2000pra.googlegroups.com> References: <0ff1ba7b-8a17-4647-99fc-9c8e32f83de7@g1g2000pra.googlegroups.com> Message-ID: <6plibnF8qbjoU1@mid.uni-berlin.de> ylj798 at gmail.com schrieb: > my code? > ????????????????????????????????????? > import base64 > def deflashget(st): > if st.startswith('Flashget://'): > return base64.decodestring(st[len('Flashget://'):])[10:-10] > elif st.startswith('http://') or st.startswith('ftp://'): > return 'Flashget://' + base64.encodestring('[FLASHGET]' + st > +'[FLASHGET]').replace('\n', '') > > st='Flashget:// > W0ZMQVNIR0VUXWh0dHA6Ly9kb3duLnJub3ZlbC5jb20vYm9va3R4dC8zLzEzNjgyLzEzNjgyLnppcFtGTEFTSEdFVF0=&1064' > print deflashget(st) > ???????????????????????????????????????? > it's run ,Eric gave me error,the error is "'module' object has no > attribute 'decodestring'", > what can I do? who can help me? How is the file called that the above code is in? I *bet* it is called base64.py, or has been called that way. Jerry had the same idea, however you must make sure that the code he gave you is run from inside the above module - because only then you'll have the same environment. Python on the commandline isn't sufficient. Diez From metebilgin48 at gmail.com Mon Dec 15 02:25:19 2008 From: metebilgin48 at gmail.com (mete) Date: Mon, 15 Dec 2008 09:25:19 +0200 Subject: mod_python and files directory In-Reply-To: References: <200812061326.40226.metebilgin48@gmail.com> Message-ID: <200812150925.20246.metebilgin48@gmail.com> On Monday 08 December 2008 10:31:28 Gabriel Genellina wrote: > os.path.dirname(os.path.abspath(__file__)) thanks a lot it's working. From pyth0nc0d3r at gmail.com Mon Dec 15 07:51:07 2008 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Mon, 15 Dec 2008 06:51:07 -0600 Subject: Having Issues with CMD and the 'python' command Message-ID: Every time I start cmd on windows it requires me to "set path=%path%;C:\python26" why? I'm getting annoyed... -------------- next part -------------- An HTML attachment was scrubbed... URL: From asteinarson at gmail.com Sat Dec 6 18:04:55 2008 From: asteinarson at gmail.com (ats) Date: Sat, 6 Dec 2008 15:04:55 -0800 (PST) Subject: Source code generation using Python References: <82098706-978f-4920-ac75-57ef3573ac44@x38g2000yqj.googlegroups.com> Message-ID: <52736f53-1676-4400-a181-20badc0a2b01@k19g2000yqg.googlegroups.com> On Dec 6, 11:19?pm, Philip Semanchuk wrote: > On Dec 6, 2008, at 4:47 PM, ats wrote: > > > > > Hello, > > > This is my first posting to a Python group (and I'm starting with > > Python seriously only now) , so bear with me if I make some mistakes. > > > I want to generate 3 different versions of a C++ source code, > > basically injecting different flavours of inline assembler depending > > on target compiler/CPU. > > > Code generation should be integrated into a 'master source file' which > > is the processed and generates the right code for GCC / MSVC or other > > cases. Something like: > > > ?int FastAdd( int t1, int t2 ){ > > ? ?int r; > > ? ?##if USE_INLINE_ASM > > ? ? ?#ARG( eax, "t1") > > ? ? ?#ARG( ebx, "t2") > > ? ? ?#ASM( "add", ebx, eax ) > > ? ? ?#RES( eax, "r" ) > > ? ?##else > > ? ? ?r = t1+t2; > > ? ?##endif > > ? ?return r; > > ?} > > > On processing, given constant USE_INLINE_ASM (or not) the right code > > is generated to a target file, which goes into the build process. > > > I was looking for packages that can do this and came up with some > > candidates: > > > - "empy" -http://www.alcyone.com/pyos/empy/- It looks like it could > > do the job, but appears non-maintained since 2003. > > - "Cheetah" - Looks like more of a tool to do fix replacements of code > > snippets. > > > There is some logic going on in the "ARG", "ASM" and "RES" sections, > > so I need to link code generation with true Python functions. > > Hi Arne, > There are *lots* of packages for Python that replace chunks of ? > predefined templates. Most are HTML-focused, some more so than others. ? > I've used Mako (http://www.makotemplates.org/) to generate both HTML ? > and Apache config files. It could certainly do C++. Some alternatives ? > to Mako are mentioned in the documentation -- Kid, Genshi and Cheetah. > > Rather than invite a flame war as to which is a better templating ? > engine, I'll just say that I'm happy with how Mako addresses *my* ? > needs. =) Good luck finding something that addresses yours. > > Cheers > Philip > > > > > The situation is really quite similar to HTML/PHP except, here we > > would have C++/Python. > > > Any suggestions? > > > Thanks, > > //Arne S. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Thanks, Mako looks neat. Regards // Arne S. From BrianVanderburg2 at aim.com Sat Dec 13 21:40:00 2008 From: BrianVanderburg2 at aim.com (Brian Allen Vanderburg II) Date: Sat, 13 Dec 2008 21:40:00 -0500 Subject: Bidirectional Networking In-Reply-To: <29283382-3e26-492a-8612-9352f32c1c01@r15g2000prd.googlegroups.com> References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <98a6c3cd-181c-43c9-805b-fb0689c69544@a26g2000prf.googlegroups.com> <29283382-3e26-492a-8612-9352f32c1c01@r15g2000prd.googlegroups.com> Message-ID: <49447200.4030302@aim.com> manu3d at gmail.com wrote: > On Dec 13, 11:13 pm, Bryan Olson wrote: > >> Software firewalls will often simply refuse incoming connections. The >> basic protection of the garden-variety home router comes from "network >> address translation" (NAT), in which case TCP connections initiated from >> the inside will generally work, regardless of port, and incoming >> connections will fail. >> > > Ok, I think I'm getting the picture here. So this means that in most > circumstances where the data flow from the server is frequent the > client initiates the connection, usually requests some initial data > and keeps polling the server periodically, issuing new requests. In > this context can the client simply keep the connection alive and > listen for new data from the server coming at any time rather than > actively issuing requests? Are there drawbacks to this strategy? I.e. > is there a limit to the number of simultaneous connections a server > can keep alive? I've noticed that the socket pages mention a 5 > connections limit. Is that it? What if I want to make a virtual room > with 20 people connected simultaneously? > I've done some network programming not much. I think if you need to receive update from a server frequently a constant connection would be better than connect-request-disconnect. As for the backlog (5), this doesn't mean that you can only have a maximum of 5 established connections. Each established connection gets a new socket object. But what I think it means is that during the listen for an incoming connection on the listening socket, if multiple connection attempts are coming in at one time it can keep a backlog of up to 5 of these connection attempts for that individual socket. Brian Vanderburg II From ibpet11 at gmail.com Tue Dec 30 05:31:21 2008 From: ibpet11 at gmail.com (ibpet11 at gmail.com) Date: Tue, 30 Dec 2008 02:31:21 -0800 (PST) Subject: string in files References: Message-ID: <62075511-08ad-405a-a3af-2da8d2f22c50@v39g2000pro.googlegroups.com> On Dec 30, 11:17?am, "Narasimhan Raghu-RBQG84" wrote: > Simple solution: us result=yourString.split(" ") and you get a list with > all the words. > > -----Original Message----- > From: python-list-bounces+rbqg84=motorola.... at python.org > > [mailto:python-list-bounces+rbqg84=motorola.... at python.org] On Behalf Of > ibpe... at gmail.com > Sent: Tuesday, December 30, 2008 3:43 PM > To: python-l... at python.org > Subject: string in files > > guys i need info on how to call up different words in a line of a file > using python example : file = 'this is a python coding group' > > i want to assign a xter to this, is, a, python , coding and group > > thanks > --http://mail.python.org/mailman/listinfo/python-list > > thanks brother i mean how do i particularly assign (u = this) (y = is).... in the strings up there. i have been able to split strings with any character sign. From ebuyvip at hotmail.com Sat Dec 20 06:57:19 2008 From: ebuyvip at hotmail.com (Jacky) Date: Sat, 20 Dec 2008 03:57:19 -0800 (PST) Subject: New sell cheap Jordan Air max Shox AF1 sneakers NBA NFL NHL Jersey Message-ID: <7dd75638-469f-49d5-8040-310f81129371@s9g2000prg.googlegroups.com> Hi friend My company wholesale all kinds brand products: shoes=$28, T-shirt=$12, hair straightener=$45-$60,purses=$16, sunglass=$14,jeans=$38,hat=$6,jacky=$55,nfl jersey=$20,handbag= $45,watches=$45,memory card=$5-$22, ugg=$45 this price inc shipping fee and tax. 1)payment: western union,T/T,money gram, paypal 2)shipment: ems,dpex,ups,dhl,fedex,tnt 3)delivery times: 4-7 days (send door to door) more details,please contact me: www.ebuyvip.com email/msn: ebuyvip at hotmail.com best regards Jarky From castironpi at gmail.com Tue Dec 30 09:29:19 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 30 Dec 2008 06:29:19 -0800 (PST) Subject: multiprocessing vs thread performance References: <26f7d44e-552c-41e9-9290-17e5c4e6deb9@q30g2000prq.googlegroups.com> Message-ID: <47cfc6de-4b13-4a74-accc-c1d027c44d5a@35g2000pry.googlegroups.com> On Dec 29, 9:08?pm, "James Mills" wrote: > On Tue, Dec 30, 2008 at 12:52 PM, Aaron Brady wrote: > > On Dec 29, 7:40 pm, "James Mills" > > wrote: > >> On Tue, Dec 30, 2008 at 11:34 AM, Aaron Brady wrote: > >> > The OP may be interested in Erlang, which Wikipedia (end-all, be-all) > >> > claims is a 'distribution oriented language'. > > snip > >> I'm presently looking at Virtual Synchrony and > >> other distributed processing architectures - but > >> circuits is meant to be general purpose enough > >> to fit event-driven applications/systems. > > > I noticed a while ago that threads can be used to simulate > > generators. ?'next', 'send', and 'yield' are merely replaced by > > synchronizor calls (coining the term). > > > Not the other way around, though, unless the generator guarantees a > > yield frequently. ?'settrace' anyone? > > Aaron, circuits doesn't use generators :) > What did your comment have to do with this ? > > I have often seen generators used to > facilitate coroutine and coooperative > programming though. > > cheers > James James, Hi. I'm glad you asked; I never know how "out there" my comments are (but surmise that feedback is always a good thing). What I was thinking was, I didn't know Virtual Synchrony, and I've never used Erlang, but I'm interested in concurrency especially as it pertains to units of work, division of labor, and division of context; and generators are another way to divide context. So: I wanted to put more of my background and interests on the table. What I said wasn't directly relevant, I see. But it's not like I "dissertated" (discussed) the Tibettan-Austrian spice trade. I think I just want to say stuff about threading! Maybe I'm just excited to meet people who share my interests... not unheard of. In Economics, you can divide a market into vertical and horizontal dimensions, vertical being the chain from raw resources to finished products, and horizontal being market coverage. With a similar division in tasks, horizontal units would handle incoming events, prepare them, then pass them on to a next unit, which processes a little, then passes it on, like an assembly line (bucket brigade/ alternating current); and vertical units would take one incoming event, and see it through start to finish (direct current). You don't have to use that depiction. The terminology is transposed from that of a distributed matrix multiplication task depiction, where horizontal works start-to-finish, and vertical takes handoffs from its predecessor. 'Circuits' doesn't use generators. I think generators are an underexplored technique. Is 'circuits' assembly line or start-to- finish, if my analogy makes any sense? 'Circuits' is event-driven, but I don't see any difference between 'event-driven' and multithreaded in general. (I think contrast can create a good picture and a clear understanding.) What is special about an 'event-driven' architecture? Are you distinguishing blocking from polling? From gardsted at yahoo.com Sat Dec 20 04:46:26 2008 From: gardsted at yahoo.com (gardsted) Date: Sat, 20 Dec 2008 10:46:26 +0100 Subject: Check file is In-Reply-To: <7caa7d45-ebbe-4c88-bb50-2f01f7315d07@s9g2000prg.googlegroups.com> References: <7caa7d45-ebbe-4c88-bb50-2f01f7315d07@s9g2000prg.googlegroups.com> Message-ID: <494cbef5$0$90267$14726298@news.sunsite.dk> Harish wrote: > Hi Friends > Is there any utility in python which will help me to read any pdf > files? > > Regards > Harish Not sure, what you're after exactly, but I tried googling 'python read pdf' and found this, so maybe 'reportlab' is what you're looking for: Re: Reading PDF files #2 Dec 20th, 2006 To read and manage Portable Document Files you can use the open source ReportLab toolkit (written in Python) from: http://www.reportlab.org/rl_toolkit.html kind regards jorgen From steve at REMOVE-THIS-cybersource.com.au Wed Dec 24 02:19:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 24 Dec 2008 07:19:48 GMT Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> <1iscu14.oixxplpgajabN%pdorange@pas-de-pub-merci.mac.com> <1isenn3.1g8fxa21aqzibkN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <0161d9c7$0$20621$c3e8da3@news.astraweb.com> On Tue, 23 Dec 2008 14:36:53 +0100, Pierre-Alain Dorange wrote: > Steven D'Aprano wrote: > >> But this is just duplicating what timeit already does. Trust me, learn >> to use it, you won't be sorry. Here's a trick that took me a long time >> to learn: instead of copying your functions into the setup code of >> timeit, you can just import them. > > Thanks for the advise, i made the test using timeit and your very > interesting method to import... Now i know how to use timeit simply ;-) > > New results on 1000 float values randomized from -500.0 to +500.0. Each > test is timeit(1000) > > sign_0 : 0.375 > sign_1 : 0.444 (+18%) > sign_2 : 0.661 (+76%) > sign_3 : 0.498 (+33%) Looking at those results, and remembering that each time is for one million iterations of one thousand calls each, I'd say that there's so little difference in speed between them, that you should choose whichever function is easier to understand. At least until you profile your application and discover that the sign() function is the bottleneck keeping your program slow. -- Steven From list at qtrac.plus.com Fri Dec 19 17:21:15 2008 From: list at qtrac.plus.com (Mark Summerfield) Date: Fri, 19 Dec 2008 14:21:15 -0800 (PST) Subject: ANN: New Book: Programming in Python 3 References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <400e99dc-90e2-441a-b7cf-5c2690915682@g38g2000yqd.googlegroups.com> Message-ID: <93e24f4e-a5d6-4952-93ce-f79b192a3666@a29g2000pra.googlegroups.com> On 19 Dec, 19:52, excord80 wrote: > On Dec 4, 2:42?pm, Alan G Isaac wrote: > > > Mark Summerfield wrote: > > > "Programming in Python 3: > > > A Complete Introduction to the Python Language" > > > ISBN 0137129297 > > >http://www.qtrac.eu/py3book.html > > > OMG, you really wrote it in Lout? > > I wish you would add tohttp://www.qtrac.eu/lout.html > > a comment on what you get out of that > > (compared to using e.g., LaTeX or > > reStructuredText). > > I'm also curious about why you chose Lout over LaTeX or reST. It seems to me that markups can be broken into two groups: semantics- oriented (reST, docbook, etc), and output oriented (lout, LaTeX). For books I want the best possible typesetting control and don't care about semantics (since I don't repurpose my text), so I chose an output oriented markup. (I know this is a gross simplification --- I'm not trying to start a religious debate.) I haven't used LaTeX much, but here're my main reasons for using lout: - easy to do easy stuff; hard stuff possible - everything in one package (tables, equations, drawing, charts, etc) - I can't draw but I can tell lout to draw for me and that works well for my simple needs - embedding graphics (e.g., screenshots) is easy (just convert to EPS) - lout lets me specify Type1 fonts so I can easily use my own custom Venus font for code & it is easy to embed it which makes publication easier - lots of books that use LaTeX have a certain sameness & I don't like the computer modern fonts (IMO -- no offence intended) - after more than a decade of using lout I can pretty well get it to do anything & everything I want (but I don't claim to be an expert user) IMO lout has three major downsides: - doesn't support Unicode - doesn't support Type1 fonts (well, apparently it does but I haven't managed it) - is much slower than LaTeX; so I'm told, but never been a problem for me except: - the design of the support for indexes is awful & index generation is slowwww (If you want to know how more about lout please ask me off-list or ask on the lout mailing list since this is now way off-topic:-) From enleverlesX.XmcX at XmclaveauX.com Tue Dec 2 15:59:01 2008 From: enleverlesX.XmcX at XmclaveauX.com (=?utf-8?Q?M=C3=A9ta-MCI_=28MVP=29?=) Date: Tue, 2 Dec 2008 21:59:01 +0100 Subject: Multiple Versions of Python on Windows XP In-Reply-To: References: Message-ID: <4935a3d1$0$945$ba4acef3@news.orange.fr> Hi! Multiple versions of Python is possible (example: Python standard + Python by OOo). But, multiple versions of Python+PyWin32 is not possible. Suggestion: use VirtualBox or Virtual-PC. @-salutations -- Michel Claveau From prologic at shortcircuit.net.au Mon Dec 29 19:05:06 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 30 Dec 2008 10:05:06 +1000 Subject: multiprocessing vs thread performance In-Reply-To: References: Message-ID: On Tue, Dec 30, 2008 at 12:52 AM, mk wrote: > Hello everyone, > > After reading http://www.python.org/dev/peps/pep-0371/ I was under > impression that performance of multiprocessing package is similar to that of > thread / threading. However, to familiarize myself with both packages I > wrote my own test of spawning and returning 100,000 empty threads or > processes (while maintaining at most 100 processes / threads active at any > one time), respectively. > > The results I got are very different from the benchmark quoted in PEP 371. > On twin Xeon machine the threaded version executed in 5.54 secs, while > multiprocessing version took over 222 secs to complete! > > Am I doing smth wrong in code below? Or do I have to use > multiprocessing.Pool to get any decent results? The overhead in starting OS level processes is quite high. This is why event-driven, single process servers can perform far better than ones that fork (spawn multiple processes) per request. As others have mentioned, it's not suprising that spawning even 100 processes took some time. Bottom line: multiprocessing should not be used this way. (nor should threading). cheers James From prologic at shortcircuit.net.au Mon Dec 15 19:00:38 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 16 Dec 2008 10:00:38 +1000 Subject: parse C expression? In-Reply-To: References: Message-ID: On Tue, Dec 16, 2008 at 9:48 AM, Torsten Mohr wrote: > Hi, > > i found some examples when googling for the subject but nothing really > matched. > > Is there a standard module available that lets me parse a syntax like "C" > with numbers, operators, braces, variables and function calls? Try pyparsing. cheers James From clp at rebertia.com Mon Dec 1 16:30:51 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 1 Dec 2008 13:30:51 -0800 Subject: Why doesn't doc has predifined name and location ? In-Reply-To: <493455AD.4040306@gmail.com> References: <493455AD.4040306@gmail.com> Message-ID: <47c890dc0812011330m1965757cgc7d21f971f01c305@mail.gmail.com> On Mon, Dec 1, 2008 at 1:22 PM, Stef Mientki wrote: > hello, > > I'm very satisfied about the great standardization of doc strings in python. > Now in contrast to that, > the general documentation of libraries, > either in plain text, html, pdf, chm, ... > doesn't have a standarized name nor location. > > Why is that ? I suppose the need for such standardization has just never arisen. Googling for docs, checking the library's website, or doing `locate library-name-here | grep doc` in bash seems to work well enough for people that no one has found it necessary to pursue the creation of such a standard. Sidenote: what Python projects publish their docs in CHM besides possibly Win32 GUI programs? Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > thanks, > Stef Mientki > -- > http://mail.python.org/mailman/listinfo/python-list > From Lie.1296 at gmail.com Sat Dec 6 06:37:48 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 6 Dec 2008 03:37:48 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> <00ab327a-c3fc-4b15-a084-4f8c6aed6a8e@o2g2000yqd.googlegroups.com> <8119ab7e-09f1-44de-bdbc-8fdff969d9e4@33g2000yqm.googlegroups.com> <36056737-3c78-499a-a81d-f6241e904460@t11g2000yqg.googlegroups.com> Message-ID: On Dec 3, 10:06?am, r wrote: > "If we can laugh what else would we do" > > I'd like to touch also on some comments by ajaksu: > [ajaksu] > I'd like to try hacking some form of Python to work in SketchUp (on > top of Ruby, that is). Now, why won't I try to? I'm a Linux user and > we don't get a SU version. So much for FREEDOM. BTW, some things in > SU > have encrypted Ruby code behind them :) > [/ajaksu] > > You CAN use SketchUp on Linux...ajaksu...thru Wine, but I know this is > not good enough. I would love to see FULL SketchUp support for linux > and I HAVE made my voice heard. I urge you brother to make make your > voice heard also. > > Go to this thread and let your voice be heard:http://groups.google.com/group/sketchupsuggestions/browse_thread/thre... > > This is the reason...amoung many others...that Linux has yet to take > any noticable market from MS. Linux could...If the Linux devolpers > would ban together and unite to make package managment and portability > between all *nix's universal, OR one great linux distro that the > average dummy can use(ubuntu looks promising, but still has a long way > to go)...compete with microsoft on a grand level. We have to steal the > idiots from under microsoft's feet, and they will come crumbling down. > But as long as a poor n00b installs his shiny new *nix system and > can't even connect to the network to see the latest janet jackson > "wardrobe malfunction", or fiqure out how to mount a flash drive, > Linux will be nothing more than our beloved oddessy. > > There will NEVER be good support on linux for most applications, > games, etc... Until people start to get behind linux and support it. > Now you say, well i don't have time to support this, my life is too > busy, my back hurts. I say stop making excuses. You DON'T have to > invest your life, just simply make your voice heard.(myself and other > dedicated people will tow the load). But at least get off your bum and > do something. > > It's time to change the world, the hour is upon us, Microsoft is > asleep at the wheel, the time for revolution is NOW! Action speaks louder than words. Not that I have done anything than talking lately though. For Google to implement a huge feature like python scripting, they would want to calculate its business feasibility (though Google is one of the rare companies that is extremely lax on this side). Sketchup's target users is not power users but those who need quick sketches, so scripting isn't an extremely important feature in Sketchup. Moreover, if they implement python scripting because someone wants it, other languages would demand the same. So, it does have to start from you creating a python-extension and getting enough users to make Google think: "There are much more python programmers than Ruby programmers in Sketchup, implementing python scripting would be a sound decision." From bearophileHUGS at lycos.com Fri Dec 26 20:31:39 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 26 Dec 2008 17:31:39 -0800 (PST) Subject: ruby -> python translator exists? References: <04b51f42-e18e-4902-8a98-38f0538c1eda@s9g2000prg.googlegroups.com> Message-ID: <4a10794e-a3e7-4aa4-8d21-580152806277@c36g2000prc.googlegroups.com> rogerdpack: > Hi all. ?My name is Roger. Hello Roger, my name is bearophile. > Anybody know of a Ruby -> Python translator at all? ?I'm looking for a > way to have my Ruby code take advantage of the coolio speed of Psyco. I have never heard of such translator, so far. > Also question. Does psyco work with Python 3.0? It doesn't work with Python3 and you may need lot of time to see it come out... if you will ever see it. Bye, bearophile From gagsl-py2 at yahoo.com.ar Sat Dec 27 21:33:36 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 28 Dec 2008 00:33:36 -0200 Subject: math module for Decimals References: Message-ID: En Sat, 27 Dec 2008 22:02:51 -0200, escribi?: > I have been looking for a Python module with math functions that would > both eat and spit Decimals. The standard math module eats Decimals > allright but spits floats... herefore exp(sin(Decimal())) produces exp > () of a float :-( Which math functions? ln, log10, exp, sqrt already exist as methods of Decimal instances. At the end of the Decimal docs there are a few examples, including computing sin and cos (but apparently they na?vely use a McLaurin series like you noticed in other module). There is a way to convert a float into a Decimal object with no loss in precision, see the FAQ (using float.as_integer_ratio(), I think such function was implemented for exactly this use case) So you might convert to float, operate, and go back -- if the precision of "double" operands is enough for you. -- Gabriel Genellina From ivlenin at gmail.com Mon Dec 15 00:49:45 2008 From: ivlenin at gmail.com (I V) Date: Mon, 15 Dec 2008 05:49:45 GMT Subject: Looking for the best way to translate an idiom References: Message-ID: On Sun, 14 Dec 2008 21:08:33 -0800, James Stroud wrote: > Yes. I think it was the British who decided that the apostrophe rule for > "it" would be reversed from normal usage relative to just about every > other noun. I'm not sure the purpose--maybe it was to give compulsive > proofreaders a raison d'etre. It's because "it" is a pronoun; you don't put an apostrophe in "his," either. From __peter__ at web.de Wed Dec 24 03:46:51 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 24 Dec 2008 09:46:51 +0100 Subject: Strategy for determing difference between 2 very large dictionaries References: <1230102996.2303.1291616055@webmail.messagingengine.com> Message-ID: Gabriel Genellina wrote: > En Wed, 24 Dec 2008 05:16:36 -0200, escribi?: [I didn't see the original post] >> I'm looking for suggestions on the best ('Pythonic') way to >> determine the difference between 2 very large dictionaries >> containing simple key/value pairs. >> By difference, I mean a list of keys that are present in the >> first dictionary, but not the second. And vice versa. And a list >> of keys in common between the 2 dictionaries whose values are >> different. >> The 2 strategies I'm considering are: >> 1. Brute force: Iterate through first dictionary's keys and >> determine which keys it has that are missing from the second >> dictionary. If keys match, then verify that the 2 dictionaries >> have identical values for the same key. Repeat this process for >> the second dictionary. >> 2. Use sets: Create sets from each dictionary's list of keys and >> use Python's set methods to generate a list of keys present in >> one dictionary but not the other (for both dictionaries) as well >> as a set of keys the 2 dictionaries have in common. > > I cannot think of any advantage of the first approach - so I'd use sets. > > k1 = set(dict1.iterkeys()) > k2 = set(dict2.iterkeys()) > k1 - k2 # keys in dict1 not in dict2 > k2 - k1 # keys in dict2 not in dict1 > k1 & k2 # keys in both > >> Using the set >> of keys in common, compare values across dictionaries to >> determine which keys have different values (can this last step be >> done via a simple list comprehension?) If you are not interested in the intermediate results and the dictionary values are hashable you can get the difference by >>> a = dict(a=1, b=2, c=3) >>> b = dict(b=2, c=30, d=4) >>> dict(set(a.iteritems()) ^ set(b.iteritems())) {'a': 1, 'c': 3, 'd': 4} Peter From luismgz at gmail.com Fri Dec 12 12:36:40 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Fri, 12 Dec 2008 09:36:40 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> <8156b37b-d1f6-4142-ad6e-8488c95b6592@z28g2000prd.googlegroups.com> Message-ID: On Dec 12, 11:17?am, sturlamolden wrote: > On Dec 12, 3:04 pm, Luis M. Gonz?lez wrote: > > > Why don't you guys google a little bit to know what's being done to > > address python's "slowness"?? > > Nothing is being done, and woth Py3k it got even worse. > > > It has been mentioned in this thread the pypy project (isn't it enough > > for you??) > > Other hints: shedskin, psyco, pyrex... > > None of those projects addresses inefficacies in the CPython > interpreter, except for psyco - which died of an overdose PyPy. > > PyPy is interesting if they ever will be able to produce something > useful. They have yet to prove that. Even if PyPy can come up with a > Python JIT, they will still be decades behind the technologies of > Strongtalk and Java. That is the problem with reinventing the wheel > all over again. > > Not to forget LLVM and Parrot which also will support Python > frontends. So, what's your conclusion? From mark at qtrac.eu Thu Dec 4 10:02:21 2008 From: mark at qtrac.eu (Mark Summerfield) Date: Thu, 04 Dec 2008 15:02:21 +0000 Subject: ANN: New Book: Programming in Python 3 Message-ID: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> Now that Python 3 final has been released I thought it would be a good time to mention that there's a new book to go with it: "Programming in Python 3: A Complete Introduction to the Python Language" ISBN 0137129297 http://www.qtrac.eu/py3book.html I've been working on this for more than a year, testing the examples against every Python 3 alpha and beta, and against the final release (using Python's unit test and doctest modules of course:). The book has just gone into production and should be available in print at the end of this month in the U.S., and a month or two later elsewhere. The book's web page has links to a draft of the introduction and to safari books online where you can read extracts. The book is aimed at a wide audience, but assumes some programming experience (not necessarily Python, not necessarily object-oriented). It teaches solid procedural style programming, then builds on that to teach solid object-oriented programming, and then goes on to more advanced topics (e.g., including a nice way to create validated attributes by combining class decorators with descriptors). But even newcomers to Python 3 should be able to write useful (although small and basic) programs after reading chapter 1, and then go on to create larger and more sophisticated programs as they work through the chapters. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu From narkewoody at gmail.com Sun Dec 21 21:23:03 2008 From: narkewoody at gmail.com (Steven Woody) Date: Mon, 22 Dec 2008 10:23:03 +0800 Subject: How to represent a sequence of raw bytes Message-ID: Hi, What's the right type to represent a sequence of raw bytes. In C, we usually do 1. char buf[200] or 2. char buf[] = {0x11, 0x22, 0x33, ... } What's the equivalent representation for above in Python? Thanks. - narke From zhushenli at gmail.com Thu Dec 4 08:37:04 2008 From: zhushenli at gmail.com (Davy) Date: Thu, 4 Dec 2008 05:37:04 -0800 (PST) Subject: time.sleep() and Tkinter after()? References: <03613d37-ca4f-4962-bce2-eea0a3f65952@r15g2000prd.googlegroups.com> Message-ID: On Dec 5, 3:05?am, "Hendrik van Rooyen" wrote: > "Davy" wrote: > > I have used Tkinter after() to do loop update GUI in my previous post. > > And I tried to change after() to time.sleep(), but it seems doesn't > > work at all, the Queue send and receive data properly, but the GUI > > didn't even appear? > > > //-----code changed----- > > def draw_canvas_loop(canvas_b): > > ? ? while (True): > > ? ? ? ? board = data_queue.get(block = True, timeout=2) > > Do you want it to block, or do you want it to time out? Hi Hendrik, nice comments :-) Do you think block and time out are contradict to each other? > > > ? ? ? ? print 'get', data_queue.qsize() > > ? ? ? ? draw_canvas(board, canvas_b, x, y, block_width, block_height) > > ? ? ? ? time.sleep(0.3) > > this will make the gui unresponsive for the time > > > ? ? ##canvas_b.after(300, lambda:draw_canvas_loop(canvas_b)) > > and then the control runs off the end of the function. > > > So, can I use time.sleep() in GUI application? Or Tkinter scheduler > > just ignore the sleep() function? > > time.sleep(sleep_time) will effectively suspend the gui mainloop > (if it is in the mainloop) for the sleep_time, making the gui unresponsive > for that time. ?Eschew it here. ?Use it in other, non GUI helper threads. Although I don't understand your explaination very well(I guess maybe .after() re-schedule is better than .sleep unresponsive in GUI application?)I will take it as a golden rule. > > > > > And if I use after(), will the code form a recursive function call, > > only if it is coded that way - yours does not look recursive to me > > > and the memory usage will boost as the program goes (I have watched > > the task manager in WinXP and find the python.exe eat more and more > > memory...). > > def draw_canvas_loop(canvas_b): > > ? ? board = data_queue.get(block = True, timeout=1) > > ? ? print 'get', data_queue.qsize() > > ? ? draw_canvas(board, canvas_b, x, y, block_width, block_height) > > Here you draw a new canvas object - what has happened to the > previous one? Is it possibly still hanging around? Should you > do something about it? Yeah, I forgot to *delete* the rectangle object I generate before. One more question, besides create/delete method, can I just create two rectangles (one black/one white), and assign two tags to these two rectangles, and place rectangle by just using tags(that is, can I place one object on several places of the canvas)? > > - Hendrik From steve at holdenweb.com Tue Dec 2 22:53:47 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 02 Dec 2008 22:53:47 -0500 Subject: Do more imported objects affect performance In-Reply-To: <1be78d220812010621u51dead9dnbaa0b4c8c9414362@mail.gmail.com> References: <1be78d220812010621u51dead9dnbaa0b4c8c9414362@mail.gmail.com> Message-ID: <493602CB.2020907@holdenweb.com> Filip Gruszczy?ski wrote: [something I moved to after Nick's reply, where it belongs] > 2008/12/1 Nick Craig-Wood : >> Rafe wrote: >>> On Dec 1, 7:26?am, "Filip Gruszczy?ski" wrote: >>>> I have following question: if I use >>>> >>>> from module import * >>>> >>>> instead >>>> >>>> from module import Class >>>> >>>> am I affecting performance of my program? I believe, that all those >>>> names must be stored somewhere, when they are imported and then >>>> browsed when one of them is called. So am I putting a lot of "garbage" >>>> to this storage and make those searches longer? >>> Why use it if you don't need it? Your post implies a choice and the >>> '*' import can really make things muddy if it isn't actually necessary >>> (rare). Why not just import the module and use what you need? It is >>> way easier to read/debug and maintains the name-space. >> Importing the module is actualy slower... If you import the name into >> your namespace then there is only one lookup to do. If you import the >> module there are two. >> >> $ python -m timeit -s 'from timeit import Timer' 'Timer' >> 10000000 loops, best of 3: 0.0784 usec per loop >> >> $ python -m timeit -s 'import timeit' 'timeit.Timer' >> 1000000 loops, best of 3: 0.243 usec per loop >> >> I'm not suggestion you should ever use "from module import *" only >> ever import the things you actually need, eg >> "from module import MyClass, my_function" >> >> And here is the test again, actually calling something with the same >> difference in execution speed :- >> >> $ python -m timeit -s 'from os import nice' 'nice(0)' >> 1000000 loops, best of 3: 1.21 usec per loop >> >> $ python -m timeit -s 'import os' 'os.nice(0)' >> 1000000 loops, best of 3: 1.48 usec per loop >> > I see. Thanks for a really good explanation, I like to know, how to do > things in the proper way :) > Pardon me for intruding, but timings here are entirely the wrong focus for a Python newcomer. Given that imports are super-optimized (i.e. the code in the module is only performed once) such a small difference in timing is inconsequential, I would suggest. As long as "from module import *" is only ever used with modules specifically designed to support it, the other forms can be used as required. Sure, there is a timing difference between import module ... module.something() and from module import something ... something() but that's hardly the point. Learning to write sound Python is *much* more important that learning to write fast Python, and often the two coincide anyway. It was true when Kernighan and Plauger wrote it forty years ago and it's true now: "First, make it work. Then, *if it doesn't work fast enough*, make it work faster". regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From banibrata.dutta at gmail.com Sat Dec 27 01:10:47 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Sat, 27 Dec 2008 11:40:47 +0530 Subject: ruby -> python translator exists? In-Reply-To: <9c579c5a-ac9f-4716-8300-6d41ed52fd72@a26g2000prf.googlegroups.com> References: <04b51f42-e18e-4902-8a98-38f0538c1eda@s9g2000prg.googlegroups.com> <4a10794e-a3e7-4aa4-8d21-580152806277@c36g2000prc.googlegroups.com> <72c2df21-db59-4870-9388-ccaa47cf11e4@20g2000yqt.googlegroups.com> <9c579c5a-ac9f-4716-8300-6d41ed52fd72@a26g2000prf.googlegroups.com> Message-ID: <3de8e1f70812262210oa41d804g4cb2ec4c6ded3e40@mail.gmail.com> http://github.com/why/unholy/tree/master On Sat, Dec 27, 2008 at 11:19 AM, rogerdpack wrote: > > Search for the tool "Unholy". -- Al > > Thank you for your replies. > -=r > -- > http://mail.python.org/mailman/listinfo/python-list > -- regards, Banibrata http://www.linkedin.com/in/bdutta http://octapod.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 8 08:18:57 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 08 Dec 2008 14:18:57 +0100 Subject: Public imports In-Reply-To: <9623b0a3-7053-41f1-b116-0cd5e54f39e9@v13g2000vbb.googlegroups.com> References: <9623b0a3-7053-41f1-b116-0cd5e54f39e9@v13g2000vbb.googlegroups.com> Message-ID: <493d1ec0$0$32048$426a34cc@news.free.fr> M?rcio Faustino a ?crit : > Hi, > > Does Python support public imports instead of the default private? Python has no notion of "public" or "private" !-) > Something like D's "public import" (see 2.0/module.html>) Python imports don't work as D imports (as far as I can tell from the above link). The Python import statement binds imported name - whether the module object itself[1] or the explicitely[2] or implicitely[3] specified names from the module object - into the importing module's namespace. [1] import some_module [2] from some_module import some_name [3] from some_module import * IOW, if module_b imports module_a and module_c import module_a, module_a will be accessible in module_c as module_b.module_a. If module_b import name_x from module_a and module_c imports module_b, name_x will be accessible in module_c as module_b.name_x. Etc, etc.... HTH From zaz600 at gmail.com Thu Dec 25 07:36:17 2008 From: zaz600 at gmail.com (NoName) Date: Thu, 25 Dec 2008 04:36:17 -0800 (PST) Subject: SyntaxError: encoding problem: with BOM References: <6res8tF1do1sU1@mid.uni-berlin.de> <400f176b-bd9a-4f26-b01b-1aa7c7dcf5ac@z6g2000pre.googlegroups.com> <6rf6m1F1e0f8U1@mid.uni-berlin.de> Message-ID: On 25 ???, 03:35, "Diez B. Roggisch" wrote: > NoName schrieb: > > > > > On 25 ???, 00:37, "Diez B. Roggisch" wrote: > >> NoName schrieb: > > >>> i have 1.py in cp866 encoding: > >>> # -*- coding: cp866 -*- > >>> print ("ff") > >>> It's not work in Python 3.0 > >>> Error: > >>> File "", line 1 > >>> SyntaxError: encoding problem: with BOM > >>> what's wrong? > >> I can only guess, but just because you write the coding-header that > >> doesn't mean that the editor you use does actually *use* that encoding. > >> What I presume it does is to use utf-8, and write that stupid BOM > >> microsoft uses for denoting utf-8-content as first byte. Try using a > >> different editor, or alter it's settings to really use your desired > >> encoding. > > >> Diez > > > I used Far Manager editor. and it *really* used cp866 > > I can print hex dump of source file. > > I don't want to use UTF-8 for py-file! > > How about you show us the python file in question? > > diez you can get it here http://slil.ru/26481345 From excord80 at gmail.com Tue Dec 9 22:28:48 2008 From: excord80 at gmail.com (excord80 at gmail.com) Date: Tue, 9 Dec 2008 19:28:48 -0800 (PST) Subject: How do I manually uninstall setuptools (installed by egg)? References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> Message-ID: <7ca0d6d8-983c-4354-b49a-84461fe5a034@g17g2000prg.googlegroups.com> On Dec 9, 10:15?pm, rdmur... at bitdance.com wrote: > On Tue, 9 Dec 2008 at 18:49, excor... at gmail.com wrote: > > On Ubuntu, I accidentally manually installed setuptools > >http://pypi.python.org/pypi/setuptools/0.6c9(by running the .egg file > > as a shell script via sudo), and now realize I should just be using > > apt to take care of my system Python packages. I also installed one or > > two packages using its ``easy_install``. > > > Looks like it lives in ``/usr/lib/python2.5/site-packages``. > > > How can I manually remove those packages installed using that > > ``easy_install``, and then manually remove the setuptools package I > > installed? > > rm -r /usr/lib/python2.5/site-packages/ Ok. "" presumably refers to the packages I installed using the ``easy_install`` command. I'm guessing I should also jettison the ``setuptools-0.6c9-py2.5.egg`` and ``setuptools.pth`` files. > Then find the .pth file (in the site-packages directory) that > references the egg, and delete the line referencing the egg. I guess you mean the ``easy-install.pth`` file. Ok. I should probably also get rid of ``/usr/bin/easy_install`` and ``/usr/ bin/easy_install-2.5``... > Setuptools has no uninstall function, as far as I know. Unfortunate. It's usually one of the first things I look for in a piece of software. Thanks. From kirk at daycos.com Thu Dec 11 11:24:13 2008 From: kirk at daycos.com (Kirk Strauser) Date: Thu, 11 Dec 2008 10:24:13 -0600 Subject: newbie question: if var1 == var2: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> Message-ID: <87abb21xzm.fsf@daycos.com> At 2008-11-29T04:02:11Z, Mel writes: > You could try > > for item in fname: > item = item.strip() This is one case where I really miss Perl's "chomp" function. It removes a trailing newline and nothing else, so you don't have to worry about losing leading or trailing spaces if those are important to you. -- Kirk Strauser The Day Companies From skip at pobox.com Tue Dec 23 15:05:31 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 23 Dec 2008 14:05:31 -0600 Subject: pseudo terminal usage from Python? In-Reply-To: References: <5t-dnRgMi9Z4lszUnZ2dnUVZ_vOdnZ2d@posted.visi> Message-ID: <18769.17547.722458.304993@montanaro-dyndns-org.local> Grant> Are you sure it's not Python buffering its input? Have you tried Grant> "python -u mympstat.py"? >> Nope. -u unbuffers stdout and stderr, not stdin. It really must be >> mpstat being uncooperative. Grant> That's not what my python man page says: Grant> -u Force stdin, stdout and stderr to be totally Grant> unbuffered. On systems where it matters, also put Grant> stdin, stdout and stderr in binary mode. Grant> That's for 2.5.2, but that's how I remember previous versions Grant> working as well. I'm still running 2.4.5 at work. It's -u help: -u : unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x) see man page for details on internal buffering relating to '-u' Was stdin unbuffering maybe added in 2.5? Skip From bearophileHUGS at lycos.com Fri Dec 12 07:14:19 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 12 Dec 2008 04:14:19 -0800 (PST) Subject: (Very Newbie) Problems defining a variable References: <49425146$0$8495$426a74cc@news.free.fr> <11c53a4a-de1e-4bee-ad60-a05befb6cbf4@a12g2000yqm.googlegroups.com> Message-ID: <7cb69ff5-9034-41cc-b667-d69329707b18@d36g2000prf.googlegroups.com> feba: > ? ? ? ? if bank <= 0: > ? ? ? ? ? ? ? ? print("You're in the red!") > ? ? ? ? ? ? ? ? quit() > ? ? ? ? elif bank >= 1 and bank <= 9999: > ? ? ? ? ? ? ? ? rate = 0.0060 > ? ? ? ? elif bank >= 10000 and bank <= 24999: > ? ? ? ? ? ? ? ? rate = 0.0085 > ? ? ? ? elif bank >= 25000 and bank <= 49999: > ? ? ? ? ? ? ? ? rate = 0.0124 > ? ? ? ? elif bank >= 50000 and bank <= 99999: > ? ? ? ? ? ? ? ? rate = 0.0149 > ? ? ? ? elif bank >= 100000: > ? ? ? ? ? ? ? ? rate = 0.0173 > ? ? ? ? else: > ? ? ? ? ? ? ? ? print("What's this doing here?") I think your indents are a little too much large (the soft standard is 4 spaces). The last else can be removed. Does bank == 0 mean being in red? That list of if-elif seems bug-prone. In the future you will learn ways to write that in a less bug-prone (but also probably more complex to read and understand) way. Bye, bearophile From castironpi at gmail.com Mon Dec 29 20:34:46 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 17:34:46 -0800 (PST) Subject: multiprocessing vs thread performance References: Message-ID: <26f7d44e-552c-41e9-9290-17e5c4e6deb9@q30g2000prq.googlegroups.com> On Dec 29, 6:05?pm, "James Mills" wrote: > On Tue, Dec 30, 2008 at 12:52 AM, mk wrote: > > Hello everyone, > > > After readinghttp://www.python.org/dev/peps/pep-0371/I was under > > impression that performance of multiprocessing package is similar to that of > > thread / threading. However, to familiarize myself with both packages I > > wrote my own test of spawning and returning 100,000 empty threads or > > processes (while maintaining at most 100 processes / threads active at any > > one time), respectively. snip > As others have mentioned, it's not suprising > that spawning even 100 processes took some > time. > > Bottom line: multiprocessing should not be used this way. > (nor should threading). The OP may be interested in Erlang, which Wikipedia (end-all, be-all) claims is a 'distribution oriented language'. You might also find it interesting to examine a theoretical OS that is optimized for process overhead. In other words, what is the minimum overhead possible? Can processes be as small as threads? Can entire threads be only a few bytes (words) big? Also, could generators provide any of the things you need with your multiple threads? You could, say, call 'next()' on many items in a list, and just remove them on StopIteration. From deets at nospam.web.de Sat Dec 20 06:59:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 20 Dec 2008 12:59:00 +0100 Subject: [OT] Re: IMAP: How to implement GMail-like threaded conversations view In-Reply-To: References: Message-ID: <6r4504FfpdmiU1@mid.uni-berlin.de> > Anything else is madness. And the fact the Outlook doesn't do proper > referral fields just infuriates me. Sigh. I'm overjoyed about the opaque winmail.dat attachments I get. Which seem to appear randomly from the same sender sending the same stuff (like a meeting invitation) to me - depending on the moon cycle or something I presume... Diez From israelu at elbit.co.il Wed Dec 31 08:04:15 2008 From: israelu at elbit.co.il (iu2) Date: Wed, 31 Dec 2008 05:04:15 -0800 (PST) Subject: Pass by reference References: <529e1d98-8932-49f0-b569-85285bd50f23@p2g2000prn.googlegroups.com> Message-ID: On Dec 31, 1:48?pm, "Chris Rebert" wrote: ... > > Not really, or at the very least it'll be kludgey. Python uses > call-by-object (http://effbot.org/zone/call-by-object.htm), not > call-by-value or call-by-reference. > > Could you explain why you have to set so many variables to the same > value (if they're None)? It's a bit strange and could be a sign that > there's a better way to structure your program (e.g. use a > dictionary). We might be able to offer more helpful suggestions if you > explain. > > Cheers, > Chris > > -- Hi, thanks for your reply. Well, I wrote an application that talks via UDP to several targets (embedded). Currently there are only two of them connected to my PC, but there could be more. Let's call them target 1 and target 2. Now, each target has its own IP address, and is connected straight to my PC, no DHCP or common bus or whatsover The GUI of my application enables the user to enter the IP for each target. The user can disconnect one target, and then connect a different one with a different IP. Let's say he replaces target 2 with a different one. Then he must tell the python app that target 2 now has a different IP. He does that by entering a different IP for target 2 in the GUI. When the app sends data to a target, it must know whether to create a new socket or use the previous one for that target. It deduces this by observing a change in the IP address in the GUI for that target. For the 2 targets I have the variables comm1 and comm2. They are of some class I wrote, representing many properties of the communication, including the IP address. There is one function that sends data, and it receives a commX var (comm1 or comm2) as the means for sending the data. Before sending the data the function needs to initilze commX (if it is still None), or creating it a new, if it sees that the IP for that target has changed. Something like this: def send_data(comm, data, current_ip_from_gui): if comm is None: # I want to assign comm a new MyComm elif comm.ip != current_ip_from_gui: # I want to re-assign a new MyComm that uses the new IP comm.socket.SendTo(comm.addr, data) # eventually send the data I could re-design it to have send_data be a method of MyComm. But I don't think I should, beacuse I planned MyComm to have only properties. I'd like functions to receive it and manipulate it. MyComm could also be a mere string just as well... Since I can apply this idiom in C (pointer), Lisp (macro), tcl (upvar) and C# (ref) I wondered what the python way was. But I guess I can achieve this using a class holding my vars, maybe like this: class CommVars: comm1 = None comm2 = None myvars = CommVars() and then change a value like this: def set_var(dict0, varname, val): dict0[varname] = val set_var(myvars.__dict__, 'comm1', MyComm(...)) From stef.mientki at gmail.com Thu Dec 25 05:00:18 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 25 Dec 2008 11:00:18 +0100 Subject: Is there a function to remove escape characters from a string ? Message-ID: <495359B2.10201@gmail.com> hello, Is there a function to remove escape characters from a string ? (preferable all escape characters except "\n"). thanks, Stef From aioe.org at technicalbloke.com Fri Dec 5 19:52:20 2008 From: aioe.org at technicalbloke.com (r0g) Date: Fri, 05 Dec 2008 19:52:20 -0500 Subject: Progressive download with Urllib2. Message-ID: Hi There, I am trying to download some video with python but have run aground on the rocky shores of pseudostreaming. Fingers crossed someone else here has some experience with this! Here's what I've done so far... The initial link is foo.asx so I download that with... handle = urllib2.urlopen( 'http://www.example.com/foo.asx' ) mime_type = url_handle.info().getheader("Content-Type","") data = urllib2.read() It comes back with mime type of 'video/x-ms-asf' and the content... 'ASF http://www.example.com/foo-100.wmv' I then used the same code again to grab the URL (ditching the 'ASF ' bit) and this time it comes back with a mime type of 'video/x-ms-wvx' and two URLs... Ref1=http://www.example.com/foo-100.wmv?MSWMExt=.asf Ref2=http://192.168.0.1/foo-100.wmv?MSWMExt=.asf The latter is no use as it's on a private LAN and the second is the same URL as last time, just with a different mime type and naturally it returns the same thing if I use Urllib2 open and read to fetch it with or without the '?MSWMExt=.asf' part. So... I fired up wireshark and spotted these lines coming back in the headers: Server: Cougar/9.01.01.3862 Supported: com.microsoft.wm.srvppair, com.microsoft.wm.sswitch, com.microsoft.wm.predstrm, com.microsoft.wm.fastcache, com.microsoft.wm.startupprofile Euw... I suspected for a second that meant I have to connect with a MS media player or something but the same URL works fine when I paste it into Firefox and the video starts pseudostreaming away so... How can I get their server to give me the video data? Do I need to ask for the file with some other protocol? RTSP? or change my user_agent string and pretend to be Windows Media Player?? Do I need another module as opposed to urllib2? and if so which one? I've had a search but drawn a blank. I guess I'll plug on in wireshark and see what some other programs do but I'd appreciate it if anyone can put me out of my misery! Yours stuck, Roger Heathcote. From castironpi at gmail.com Sat Dec 6 07:03:21 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 6 Dec 2008 04:03:21 -0800 (PST) Subject: Guido's new method definition idea References: Message-ID: <7c56a65c-ca99-4d00-b425-ae6385ff1a0a@v42g2000yqv.googlegroups.com> On Dec 5, 8:21?pm, "Daniel Fetchinson" wrote: > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... > > The proposal is to allow this: > > class C: > ? ? def self.method( arg ): > ? ? ? ? self.value = arg > ? ? ? ? return self.value > > instead of this: > > class C: > ? ? def method( self, arg ): > ? ? ? ? self.value = arg > ? ? ? ? return self.value > > I.e. explicit self stays only the syntax is slightly different and may > seem attractive to some. ... Would it be valid outside class definitions too? (As follows...) def sequence.shuffle( ): x= sequence[ 0 ] sequence[ 0 ]= sequence[ -1 ] ...etc. shuffle( listA ) Can you still call it by class membership? (As follows...) C.method( inst, arg ) From castironpi at gmail.com Sat Dec 6 06:48:55 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 6 Dec 2008 03:48:55 -0800 (PST) Subject: Don't you just love writing this sort of thing :) References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: <26f4ec27-91b9-4f87-9c12-023e1af0c86f@v13g2000yqm.googlegroups.com> On Dec 5, 7:20?pm, Lawrence D'Oliveiro wrote: > In message <32cf4a79-a6e3-4250-9b5a-1ec80c748... at j32g2000yqn.googlegroups.com>, Aaron Brady wrote: > > > On Dec 5, 4:32?am, Lawrence D'Oliveiro > central.gen.new_zealand> wrote: > > >> The code people write is probably a direct reflection of their thinking > >> processes: For example, slow, plodding, one step at a time, incapable of > >> imaginative leaps, versus those who operate directly on larger patterns > >> at once... > > > That distinction operates indirectly on smaller patterns. Well, I was trying to be funny. But sarcasm is defined as something said in jest that someone else would say seriously; so perhaps it's not the most reliable tone for text. Chalk it up to a failed communication, even though a successful expression. I agree that programming takes imaginative leaps and operates on large patterns. You implied that people's thinking processes vary by "pattern size", which I thought was interesting. But 'leaps' implies carelessness (wrong word, possibly). Is it possible to tackle a large pattern one step at a time? Say, writing a quick sort in assembly? > Do you find this > > (open, gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir, Entry), "r") > > complicated or hard to understand? It's not easy. I can't understand it at a glance, if that is your question. But it's not obfuscated, that is true. If I can compare programming to chess: I look at a board and you tell me, 'white to play, mate in 5 moves.' If the board is busy (not just Rook and King), it could take a long time to find the mate. It's complicated, but not hard to understand. It requires "holding" (introducing a term) several things in mind at once: first expose the Bishop, then capture the Pawn, etc. But it is not easy in the same way that a 'mate in one' board is, even though the pieces are the same. > It's made up of very simple pieces, > combined according to very simple rules, viz:- > > A tuple of candidate functions: > > ? ? (open, gzip.GzipFile) > > A choice from that tuple according to a condition: > > ? ? [Entry.endswith(".gz")] > > And finally, arguments to pass to the chosen function: > > ? ? (os.path.join(PatchesDir, Entry), "r") As you explain, your program (taking the fragment to be an entire program) is composed of three "very simple pieces". I would say, write them as three very simple pieces. Here's a possible compromise between yours and Arnaud's: if Entry.endswith(".gz"): opener= gzip.GzipFile else: opener= open opener( os.path.join(PatchesDir, Entry), "r" ) It's kind of swampy, I concede. About the same number of characters, 5x the lines. Maybe something in between: opener= (open, gzip.GzipFile)[Entry.endswith(".gz")] path= os.path.join(PatchesDir, Entry) opener( path, "r" ) > See, it's so simple, a child could understand it. A child who isn't burdened > with the preconceptions that seem to afflict some participants in this > noisegroup... 'No preconceptions' is a pretty tall order. The most basic facts about the natural numbers weren't formalized until the 1880s, but people used them successfully for thousands of years before, evidently on preconception alone. To be plodding and slow (as well as meticulous and deliberate, by the way), the child would need 'preconceptions' about tuples, functions, Boolean variables, etc. You might call those plain 'conceptions', and use the other definition, 'bias' for noisegroup participants. Emotions are biased, as are small sample sizes (small-sized samples). I think it's also a tall order to ask a group of people to keep objective for any length of time. Thus, since we're people, and we're interacting, and we can't keep objective forever, we'll be non- objective sometimes, and therefore won't all understand your program. Perhaps you are wanting to write a 'preconception-tolerant' program: a program that is tolerant of (can be read by) readers with preconceptions. But I'll bite: what preconceptions? Favoritism? From benjamin.kaplan at case.edu Tue Dec 9 17:25:59 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 9 Dec 2008 17:25:59 -0500 Subject: Is 3.0 worth breaking backward compatibility? In-Reply-To: References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> Message-ID: On Tue, Dec 9, 2008 at 3:56 PM, Lie Ryan wrote: > On Sun, 07 Dec 2008 21:48:46 +0000, Tim Rowe wrote: > > > 2008/12/7 walterbyrd : > >> IMO: breaking backward compatibility is a big deal, and should only be > >> done when it is seriously needed. > >> > >> Also, IMO, most of, if not all, of the changes being made in 3.0 are > >> debatable, at best. I can not think of anything that is being changed > >> that was really a "show stopper" anyway. > > > > > > But that's what a major release number does for you. Modula2 was quite a > > break from Modula. Think of Python3.0 it as a new language, if you like, > > that's inspired by Python2. You can stay with Python2 or you can adopt > > the new language. That way you won't have to think of it in terms of > > breaking any sort of backwards compatibility because there is no > > backwards ;-) > > > > -- > > Tim Rowe > > Actually I noticed a tendency from open-source projects to have slow > increment of version number, while proprietary projects usually have big > version numbers. > > Linux 2.x: 1991 Python 3.x.x: 1991. Apache 2.0: 1995. OpenOffice.org 3.0: > acquired by Sun at 1999. GIMP 2.x: 1995. Wine 1.x: 1993. > Wine actually timed the 1.0 release to be at about t the 15th "birthday" of the project. > > Compare with > Windows: NT 3.1-NT 6.x: 1993. Visual Studio 97, 6.0, .NET, .NET > 2003, .NET 2005, 2008: 1997. Photoshop (11 versions to CS4): 1987. > Microsoft Office 3, 4, 95, 97, 2000, XP, 2003, 2007: 1990. Flash MX, 9, > CS 1-4. iTunes 8: 2001. RealPlayer 4-11: 1995. Macintosh 1.0-9: > 1984-2001, X.5: 2001. Winzip 12.0: early 1990s. > Just to note: Office 2007 is also known as Office 12, if you want to look at version numbers. Also, Mac OS hasn't increased the major version number past 10 since they switched from their own proprietary kernel to using the open-source Darwin. > > Interestingly, many linux _distro_ also inhibit this quick version number > change. Fedora 10, Ubuntu is 2 years old, version 8 (they start from > version 6 not 1). > That's because 8 isn't the verison number- it's the year the version was released (8.10 is October 2008, not the 10th update to version 8). > Probably having higher version numbers sells better and looks more > attractive (since it'd make it seem like the software is not a new > product), having quick changing version number also makes users doesn't > mind compatibility breaks. Also a pattern is that prop software often > change how they version their product, (extreme example: visual studio: > from using years, version number, .NET, .NET + Year, back to year). > Changing how you version your product would make it "looks" like it's a > fresh new product (boring ol' photoshop 9 looks fresh with the new CS- > tag). > By having quick changing version number and often changing how product is > versioned, vendors could also say: "its two/three major version away, we > don't support that feature anymore since a veeery long time". > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rileyrgdev at gmail.com Tue Dec 2 17:04:58 2008 From: rileyrgdev at gmail.com (Richard Riley) Date: Tue, 02 Dec 2008 23:04:58 +0100 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: Petite Abeille writes: > On Dec 2, 2008, at 9:21 PM, Lew wrote: > >> These are professional software development forums, not some script- >> kiddie cellphone-based chat room. "r" is spelled "are" and "u" should >> be "you". > > While Xah Lee arguably represents a cross between "Enfant Provocateur" > [1] and "Evil Clown" [2], this surely qualifies as a "Grammarian" > [3] rebuke :D > > Cheers, >From being mildly shocked at such a telling off for minor shortcuts I would suggest more of a http://redwing.hutman.net/~mreed/warriorshtm/android.htm It would seem the soul contributions made are rebukes and petty prodding. Every group has one. > > -- > PA. > http://alt.textdrive.com/nanoki/ > > > [1] http://redwing.hutman.net/~mreed/warriorshtm/enfantprovocateur.htm > [2] http://redwing.hutman.net/~mreed/warriorshtm/evilclown.htm > [3] http://redwing.hutman.net/~mreed/warriorshtm/grammarian.htm -- important and urgent problems of the technology of today are no longer the satisfactions of the primary needs or of archetypal wishes, but the reparation of the evils and damages by the technology of yesterday. ~Dennis Gabor, Innovations: Scientific, Technological and Social, 1970 From prologic at shortcircuit.net.au Wed Dec 10 01:00:20 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 10 Dec 2008 16:00:20 +1000 Subject: List Problem In-Reply-To: References: Message-ID: On Wed, Dec 10, 2008 at 3:40 PM, dongzhi wrote: > If I execute part[1], I have got 'a'. If I execute part[2], I have > got ' '. But, if I execute part[1::2], I have got ['a', '', '']. I > don't know why. Please tell me why. Perhaps you meant: part[1:2] pydoc list This will tell you there are 3 arguments to __getslice__ i, j, y Without doing any further reading I presume from my experience that this works much like range and xrange and that the 3rd parameter is the step size. Consider this: >>> x = [9, 1, 2, 3, 4] >>> x [9, 1, 2, 3, 4] >>> x[1:2] [1] >>> x[1::2] [1, 3] >>> x[1::1] [1, 2, 3, 4] >>> x[1::2] [1, 3] >>> x[1::3] [1, 4] >>> cheers James -- -- -- "Problems are solved by method From njuk.njuk at gmail.com Thu Dec 4 21:54:42 2008 From: njuk.njuk at gmail.com (njuk.njuk at gmail.com) Date: Thu, 4 Dec 2008 18:54:42 -0800 (PST) Subject: allocating an unsigned int memory buffer for C (swig) struct Message-ID: <30e7f6aa-eae4-4b4e-bced-797b27aee2e1@r37g2000prr.googlegroups.com> i am using python (via swig) to interface with the comedi (http:// www.comedi.org/) library for some simple data acquisition. a general category of problems i am having has to do with basic comedi structs whose members require being set to a pointer of an allocated memory buffer. one specific example is the 'insn' struct that has a 'data' member that should point to a buffer i have previously allocated. the comedi type is 'lsampl_t*' but underneath this is simply an 'unsigned int*'. for the life of me, i haven't been able to figure out how to instantiate a memory buffer of the correct underlying type in python. whatever i try always fails when i set the struct member. TypeError: in method 'comedi_insn_struct_data_set', argument 2 of type 'lsampl_t *' [the underlying swig code seems to be (correctly) checking for an unsigned int pointer]. aside: i am currently running python v2.4.4 but could upgrade to a 2.5 version. thanks for any help. From mwilson at the-wire.com Sun Dec 14 11:52:27 2008 From: mwilson at the-wire.com (Mel) Date: Sun, 14 Dec 2008 11:52:27 -0500 Subject: 1 or 1/0 doesn't raise an exception References: <49446E39.6020807@tim.thechases.com> Message-ID: Daniel Fetchinson wrote: [ ... ] > Let me just point out that unsuspecting people (like me) might rely on > the whole expression to be evaluated and rely on exceptions being > raised if needed. There are a lot of threads on comp.lang.python that mention beginners' possible reactions to language features, so I'll mention this paper relating to teaching programming: . ? The early draft which I've read, , references quite a lot of literature on what new programmers do, discusses a new test for programming aptitude. ? ? ? ? Mel. From the.brown.dragon.blog at gmail.com Thu Dec 11 10:24:00 2008 From: the.brown.dragon.blog at gmail.com (the.brown.dragon.blog at gmail.com) Date: Thu, 11 Dec 2008 07:24:00 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <91bf5d87-0154-472b-9350-e3290ab867e1@k1g2000prb.googlegroups.com> Message-ID: <43743da2-7ad2-4ec9-86d1-b2e548d11cf1@k24g2000pri.googlegroups.com> On Dec 11, 7:50?pm, the.brown.dragon.b... at gmail.com wrote: > On Dec 11, 4:53?pm, "William James" wrote: > > > > > William James wrote: > > > John W Kennedy wrote: > > > > > Xah Lee wrote: > > > > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or > > > > > Java, you'll have 50 or hundreds lines. > > > > > Java: > > > > > static float[] normal(final float[] x) { > > > > ? ?float sum = 0.0f; > > > > ? ?for (int i = 0; i < x.length; ++i) sum += x[i] * x[i]; > > > > ? ?final float divisor = (float) Math.sqrt(sum); > > > > ? ?float[] a = new float[x.length]; > > > > ? ?for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor; > > > > ? ?return a; > > > > } > > > > "We don't need no stinkin' loops!" > > > > SpiderMonkey Javascript: > > > > function normal( ary ) > > > { div=Math.sqrt(ary.map(function(x) x*x).reduce(function(a,b) a+b)) > > > ? return ary.map(function(x) x/div) > > > } > > > The variable "div" shouldn't be global. > > > function normal( ary ) > > { var div = Math.sqrt( > > ? ? ary.map(function(x) x*x).reduce(function(a,b) a+b) ) > > ? return ary.map(function(x) x/div) > > > } > > Chicken Scheme: > > (require 'srfi-1) > (define (norm vec) > ? (map (cute / <> (sqrt (reduce + 0 (map (cute expt <> 2) vec)))) > vec)) > > Cute huh? ;-) Haskell looks the best though: norm v = map (/ (sqrt (sum (map (^2) v)))) v From quian.xu at stud.tu-ilmenau.de Mon Dec 22 07:54:56 2008 From: quian.xu at stud.tu-ilmenau.de (Qian Xu) Date: Mon, 22 Dec 2008 13:54:56 +0100 Subject: pg_result_status Message-ID: Hi All, I am using the pg module (http://www.pygresql.org/pg.html) for database testing. I have got a problem now: I want to check the result status of postgresql database, which can be done in php by using pg_result_status (http://www.phpbuilder.com/manual/en/function.pg-result-status.php) How can I do the same thing in python (2.5)? Thanks in advance -- Qian Xu From mccredie at gmail.com Wed Dec 3 20:15:21 2008 From: mccredie at gmail.com (Matimus) Date: Wed, 3 Dec 2008 17:15:21 -0800 (PST) Subject: "as" keyword woes References: Message-ID: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> > What I want to understand is why this parser change was necessary in > order to enable new 2.6/3.0 features. Was this change potentially > avoidable? Does it really matter? The change occurred and it isn't going to go back. What you should be asking yourself is whether the affect it had on your code could have been avoided. What could you have done to prevent your current situation? > Couldn't we have continued along just fine using a smarter parser > without elevating "as" to reserved status (and thus potentially breaking > a 10+ years of existing code)? Nothing broke your code. It works just fine under the version it was developed for. Who forced you to upgrade to python2.6? 'as' was already coming close to being a keyword with its use in import statements. It be came a full fledged keyword to support context managers: with open('filename.x', 'w') as fout: # do stuff > (Unfortunately, our project may now have to maintain a branch at 2.5.x > in order to preserve compatibility with existing third-party scripts & > infrastructure which routinely rely upon "as" as an object method. > Sigh.) Not necessarily. You can do something like this: import sys import warnings class MyClass(object): def new_as(self): # call this something appropriate, it is your new 'as' method pass # do what 'as' does if sys.version[:3] <= '2.5': def _old_as(self): warnings.warn( DeprecationWarning( 'This method is deprecated, use `new_as` instead')) return self.new_as() exec 'as = _old_as' You could even write a metaclass that does this (a little more elegantly). Your users will get a nice warning telling them not to use the 'as' method anymore. It will work in both code bases, and you can schedule to remove it at some later version after customers have had the opportunity to remove 'as' from their code. Matt From Python.LeoJay at gmail.com Sat Dec 13 10:28:05 2008 From: Python.LeoJay at gmail.com (Leo jay) Date: Sat, 13 Dec 2008 07:28:05 -0800 (PST) Subject: Why %e not in time.strftime directives? Message-ID: <38f9c4ba-d96d-47e1-b718-562bdc6718e9@t26g2000prh.googlegroups.com> Any special reasons? Thanks. From phd at phd.pp.ru Mon Dec 8 12:07:59 2008 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 8 Dec 2008 20:07:59 +0300 Subject: SQLObject 0.9.9 Message-ID: <20081208170759.GG7441@phd.pp.ru> Hello! I'm pleased to announce version 0.9.10, a minor bugfix release of 0.9 branch of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.9.9 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.9.8 ---------------- * Backported from the trunk: under MySQL use the connection's dbEncoding instead of ascii, when converting a unicode value from python to database for a StringCol. * Fixed createSQL constrains generation under MySQL when the table's name includes the database's name (contains a dot). For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From steve at REMOVE-THIS-cybersource.com.au Sun Dec 7 07:17:02 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 12:17:02 GMT Subject: var or inout parm? References: Message-ID: <014bb66f$0$20670$c3e8da3@news.astraweb.com> On Sun, 07 Dec 2008 08:54:46 +0000, mh wrote: > How can I make a "var" parm, where the called function can modify the > value of the parameter in the caller? By using another language. > def f(x): > x = x + 1 > > n = 1 > f(n) > # n should now be 2 Python doesn't work like that. You should read this: http://effbot.org/zone/python-objects.htm Some work arounds, in order from worst-to-best: (1) Use a hard-coded global name: x = 1 def f(): global x x = x + 1 f() assert x == 2 (2) Wrap the value you want to change in a list, then modify the list in place. n = [1] def f(alist): alist[0] = alist[0] + 1 f(n) assert n[0] == 2 (4) Just use an ordinary function. Functions can return multiple values. n = 1 def f(x): return (x+1, 99) n, y = f(n) assert y == 99 assert n == 2 (5) Find another way to solve your problem. Why do you think you need var parameters? What problem are you hoping to solve by using them? As a former Pascal programmer, I missed var parameters at first, but now I don't. -- Steven From python.leojay at gmail.com Thu Dec 11 03:30:01 2008 From: python.leojay at gmail.com (Leo Jay) Date: Thu, 11 Dec 2008 16:30:01 +0800 Subject: Why optimization mode is slower than normal mode? Message-ID: <4e307e0f0812110030m6d82b063oa98cdc14cdafe6a8@mail.gmail.com> Hi all, I'm using python 2.6 in a windows xp box, when I try pystone, I get: C:\Python26\Lib\test>python pystone.py 500000 Pystone(1.1) time for 500000 passes = 5.93632 This machine benchmarks at 84227.3 pystones/second C:\Python26\Lib\test>python -OO pystone.py 500000 Pystone(1.1) time for 500000 passes = 6.00515 This machine benchmarks at 83261.8 pystones/second I tried many times, and get the same result. Why optimization mode is slower than normal mode? -- Best Regards, Leo Jay From aioe.org at technicalbloke.com Mon Dec 8 13:42:00 2008 From: aioe.org at technicalbloke.com (r0g) Date: Mon, 08 Dec 2008 13:42:00 -0500 Subject: Text parsing via regex References: Message-ID: Robocop wrote: > I'm having a little text parsing problem that i think would be really > quick to troubleshoot for someone more versed in python and Regexes. > I need to write a simple script that parses some arbitrarily long > string every 50 characters, and does not parse text in the middle of > words (but ultimately every parsed string should be 50 characters, so > adding in white spaces is necessary). So i immediately came up with > something along the lines of: > > string = "a bunch of nonsense that could be really long, or really > short depending on the situation" > r = re.compile(r".{50}") > m = r.match(string) > > then i started to realize that i didn't know how to do exactly what i > wanted. At this point i wanted to find a way to simply use something > like: > > parsed_1, parsed_2,...parsed_n = m.groups() > > However i'm having several problems. I know that playskool regular > expression i wrote above will only parse every 50 characters, and will > blindly cut words in half if the parsed string doesn't end with a > whitespace. I'm relatively new to regexes and i don't know how to > have it take that into account, or even what type of logic i would > need to fill in the extra whitespaces to make the string the proper > length when avoiding cutting words up. So that's problem #1. Problem > #2 is that because the string is of arbitrary length, i never know how > many parsed strings i'll have, and thus do not immediately know how > many variables need to be created to accompany them. It's easy enough > with each pass of the function to find how many i will have by doing: > mag = len(string) > upper_lim = mag/50 + 1 > But i'm not sure how to declare and set them to my parsed strings. > Now problem #1 isn't as pressing, i can technically get away with > cutting up the words, i'd just prefer not to. The most pressing > problem right now is #2. Any help, or suggestions would be great, > anything to get me thinking differently is helpful. Hi Robocop, What do you mean by "parses some arbitrarily long string every 50 characters"? What does your source data look like? Can you give us an example of of a) it and b) what a match would look like. I think you will get good mileage out of using '\b' to match word boundaries and that you may be better off rexing your string into a list and then padding it with whitespace after the fact but I can't say for sure. Please clarify. From __peter__ at web.de Mon Dec 1 06:08:01 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 01 Dec 2008 12:08:01 +0100 Subject: Is there any library that can convert RGB colors to ANSI colors? References: <52e45dc6-d4f5-4275-a424-dea91d1ccf26@a37g2000pre.googlegroups.com> Message-ID: ZelluX wrote: > Convert RGB colors to the closest ANSI colors. For example, given RGB > color FF0000, it should print [31m. from functools import partial def to_rgb(color): return (color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF target_colors = { 0x000000: "\33[30m", 0xFF0000: "\33[31m", # ... 0xFFFFFF: "\33[37m",} def euclidian(c1, c2): r, g, b = to_rgb(c1) s, h, c = to_rgb(c2) r -= s g -= h b -= c return r*r+g*g+b*b def closest_color(color, target_colors=target_colors, dist=euclidian): return min(target_colors, key=partial(dist, color)) if __name__ == "__main__": black = target_colors[0] for color in 0xff0000, 0x00ff00, 0x808080, 0x008000: bestmatch = closest_color(color) code = target_colors[bestmatch] print "#%06x --> %sSAMPLE%s" % (color, code, black) If the results are not good enough for your application you can convert to another colorspace before calculating the distance. Peter From cousinstanley at gmail.com Thu Dec 4 09:55:10 2008 From: cousinstanley at gmail.com (Cousin Stanley) Date: Thu, 4 Dec 2008 15:55:10 +0100 (CET) Subject: Python advocacy ... HELP! References: <5f8c1a52-545e-402e-863a-acdf23d04c78@h20g2000yqn.googlegroups.com> Message-ID: > .... > I have looked at several interesting academic papers, on doing just > this approach. I have also looked through the > python web page to get examples of industry players using python in a > non-trivial way. Yes, I know, Google, Microsoft, Sun, CIA website > running on Plone, NOAA, NASA. If anyone has any recent articles, > or if anyone on the list is at a fortune 500 company, how do I > refute the notion that Python is a "marginal" language > because according to TOBIE it only less than a 6% market share. Michael .... If you haven't seen it, The Python Success Stories page might provide a quick overview for those that are currently unaware of the rather diverse nature of Python usage among a wide group of well known users .... http://pythonology.org/success -- Stanley C. Kitching Human Being Phoenix, Arizona From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 06:42:23 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Dec 2008 11:42:23 GMT Subject: Don't you just love writing this sort of thing :) References: <0148b086$0$20670$c3e8da3@news.astraweb.com> Message-ID: <01490b5f$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 23:28:48 +1300, Lawrence D'Oliveiro wrote: > In message <0148b086$0$20670$c3e8da3 at news.astraweb.com>, Steven D'Aprano > wrote: > >> Since the context has been deleted, it's hard to tell whether the code >> as written by Lawrence ... > > If you want to reply to my message, reply to my message, don't reply to > my reply to someone else's reply to my message. I did reply to your message. It was your message that was missing all the context necessary to tell what you were rabbiting on about. -- Steven From nadiasvertex at gmail.com Mon Dec 8 11:24:58 2008 From: nadiasvertex at gmail.com (Christopher) Date: Mon, 8 Dec 2008 08:24:58 -0800 (PST) Subject: Guido's new method definition idea References: Message-ID: > > I'd like this new way of defining methods, what do you guys think? > Anyone ready for writing a PEP? I don't really see any advantage. IMHO, it is not clearer, it is not more concise, it makes the definition of class shared variables look really out of place. It also makes the new programmer wonder where the function attaches if you *don't* specify self. I also give it a -1. From rt8396 at gmail.com Wed Dec 24 18:39:22 2008 From: rt8396 at gmail.com (r) Date: Wed, 24 Dec 2008 15:39:22 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <0161d999$0$20621$c3e8da3@news.astraweb.com> Message-ID: On Dec 24, 1:19?am, Steven D'Aprano wrote: > On Tue, 23 Dec 2008 08:06:35 -0800, the anonymous troll known only as "r" > replied to Thorsten Kampe and said: > > > Thats "Thurstan", thank you very much! :) > > I think Thorsten knows how to spell his own name. > > -- > Steven OK Steven, you caught me fair and square. This is my first mistake and i will admit it. Sorry "Thorsten" From rileyrgdev at gmail.com Mon Dec 1 09:09:05 2008 From: rileyrgdev at gmail.com (Richard Riley) Date: Mon, 01 Dec 2008 15:09:05 +0100 Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <3a30f601-7128-4e5f-a97e-9f899404912c@o40g2000prn.googlegroups.com> <4f31c483-8382-480e-8417-b7eef1b1792d@z1g2000yqn.googlegroups.com> <8c856b01-7f0c-4d5b-a1d2-cfe7dc74389f@w3g2000yqc.googlegroups.com> <1680020c-521c-4498-8e74-92e99c03da6b@w35g2000yqm.googlegroups.com> <0d9d2404-cb3f-4390-b97c-79251db8ac95@k8g2000yqn.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> Message-ID: cptnwillard at gmail.com writes: > Don't feed the troll. > Yet you did and made the previous post visible to me. If you don't want people to feed the troll, do not do it yourself. From aspersieman at gmail.com Wed Dec 3 05:53:27 2008 From: aspersieman at gmail.com (Aspersieman) Date: Wed, 03 Dec 2008 12:53:27 +0200 Subject: How to send body and attachements in an email message? In-Reply-To: <140952.77709.qm@web7901.mail.in.yahoo.com> References: <140952.77709.qm@web7901.mail.in.yahoo.com> Message-ID: On Wed, 03 Dec 2008 12:40:30 +0200, srinivasan srinivas wrote: > HI, > I would like to send an email message with body-content 'test' and?an > attachment. > The snippet i used is: > outer = email.mime.multipart.MIMEMultipart() > msg1 = email.mime.text.MIMEText(, _subtype = 'text') > msg1.add_header('Content-Disposition', 'attachment') > outer.attach(msg1) > > body = email.mime.text.MIMEText(, _subtype = 'text') > outer.attach(body) > > smtp_client = smtplib.SMTP() > smtp_client.connect() > smtp_client.sendmail(, , outer.as_string()) > smtp_client.close() > > If i do like above, i am receiving the body also as an attachment. How > to set body to Multipart email message? > > Thanks, > Srini > > > Add more friends to your messenger and enjoy! Go to > http://messenger.yahoo.com/invite/ > -- > http://mail.python.org/mailman/listinfo/python-list Hi there I have used this method for a while. Works pretty good. (Apologies if the formatting is a bit wonky - gmail reformats my stuff) import mimetypes import poplib import email import smtplib import os from email import * from email.mime import * def SendMail(self, send_from, send_to, subject, text, files=[], server="localhost", username = None, password = None): # {{{ """ Sends an email. With optional attachment files. """ assert type(send_to)==list assert type(files)==list msg = MIMEMultipart.MIMEMultipart() msg['From'] = send_from msg['To'] = Utils.COMMASPACE.join(send_to) msg['Date'] = Utils.formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText.MIMEText(text)) for f in files: part = MIMEBase.MIMEBase("application", "octet-stream") part.set_payload(open(f,"rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server, 25) smtp.sock.settimeout(120) try: if username and password: smtp.login(username, password) smtp.sendmail(send_from, send_to, msg.as_string()) else: smtp.sendmail(send_from, send_to, msg.as_string()) except Exception, err: print "Error sending to " + str(send_to) + " ERROR : " + str(err) if self.logger: self.logger.error("Email error - error sending message to : " + str(send_to) + " Error : " + str(err)) smtp.close() # }}} HTH Nicol -- Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo From jstroud at mbi.ucla.edu Sun Dec 14 19:25:02 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 14 Dec 2008 16:25:02 -0800 Subject: Looking for the best way to translate an idiom In-Reply-To: References: Message-ID: James Stroud wrote: > py> class mytuple(tuple): > def magic(self, astr): > names = astr.split() > for name, val in zip(names, self): > globals()[name] = val > ... > py> t = mytuple((1,2,3)) > py> t.magic('a b') > py> a > 1 > py> b > 2 > > James In case its not obvious: def f(): return mytuple((1,2,3)) f().magic('a b') You can parameterize lobbing off values, or use more magic: py> class mytuple(tuple): ... def magic(self, astr): ... names = astr.split() ... for name, val in zip(names, self): ... globals()[name] = val ... def __add__(self, other): ... if isinstance(other, tuple): ... return mytuple(tuple.__add__(self, other)) ... else: ... return mytuple(self[other:]) ... py> t = mytuple((1,2,3)) py> t + 1 (2, 3) py> def f(): return mytuple((1,2,3)) ... py> (f() + 1).magic('a b') py> a 2 py> b 3 It's not as bad as a lot of the cynics are about to tell you it is. If it has any badness at all, it's because of the need (according to what I infer from your specification) to use the global namespace. If you want to modify a "more local" namespace, you can use some stack frame inspection to do some real magic: py> import inspect py> class mytuple(tuple): def magic(self, astr): names = astr.split() for name, val in zip(names, self): inspect.stack()[1][0].f_locals[name] = val def __add__(self, other): if isinstance(other, tuple): return mytuple(tuple.__add__(self, other)) else: return mytuple(self[other:]) ... py> def f(): return mytuple((6,7,8)) ... py> (f() + 1).magic('a b') py> a 7 py> b 8 James From exarkun at divmod.com Tue Dec 16 13:17:53 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 16 Dec 2008 13:17:53 -0500 Subject: AIM client code for Python? In-Reply-To: <732D7AE5-1429-4482-82FA-78328D6C3CF5@strout.net> Message-ID: <20081216181753.20272.1787674525.divmod.quotient.21873@ohm> On Tue, 16 Dec 2008 10:54:38 -0700, Joe Strout wrote: >I'd like to write an AIM bot in Python. I found and tried >, but it doesn't work for me: > >Connecting... >Traceback (most recent call last): > File "aimbot-1.py", line 17, in > bot.go() > File "/Users/jstrout/Documents/Python-Dev/AIMbot/toc.py", line 62, in go > self.process_loop() > File "/Users/jstrout/Documents/Python-Dev/AIMbot/toc.py", line 156, in >process_loop > event = self.recv_event() > File "/Users/jstrout/Documents/Python-Dev/AIMbot/toc.py", line 230, in >recv_event > dtemp = self._socket.recv(buflen - len(data)) >socket.error: (54, 'Connection reset by peer') > > >I wrote to the author a week ago, but never got a reply. It could be as >simple as changing the server addresses in toc.py, currently: > >TOC_SERV_AUTH = ("login.oscar.aol.com", 29999 ) >TOC_SERV = ( "toc.oscar.aol.com", 9898 ) > >...but I don't understand AIM well enough to know the correct values (and >was rather hoping that I wouldn't have to). > >Does anyone know how to get Py-TOC to work, or have another Python TOC >implementation to suggest? > You need an OSCAR-based AIM library. AOL discontinued TOC support several years ago. No TOC-based client can work on the AIM network. Twisted includes a (somewhat crufty) OSCAR implementation. There are probably also other Python OSCAR implementations. Jean-Paul From markguildwars1 at hotmail.com Tue Dec 16 21:54:54 2008 From: markguildwars1 at hotmail.com (Mark Jordaan) Date: Wed, 17 Dec 2008 04:54:54 +0200 Subject: unsubscribe In-Reply-To: References: Message-ID: > From: p.f.moore at gmail.com> Subject: Re: Does Python3 offer a FrozenDict?> Date: Tue, 16 Dec 2008 09:56:57 -0800> To: python-list at python.org> > On 16 Dec, 17:28, bearophileH... at lycos.com wrote:> > Johannes Bauer:> >> > > is there anything like a frozen dict in Python3, so I could do a> > > foo = { FrozenDict({"a" : "b"}): 3 }> >> > You can adapt this code to Python3 (and post a new recipe? It may be> > positive to create a new section of the Cookbook for Py3 only):http://code.activestate.com/recipes/414283/> > There's actually only tiny changes needed (I believe)> - Change exception syntax: raise AttributeError("A frozendict cannot> be modified.")> - (bugfix for the original version): add **kw arg to __new__ (passed> to dict.__init__)> > Simple testing looks OK. And the resulting code is OK for both 2.x and> 3.0.> > Moral - don't assume that all code needs to be rewritten for Python> 3.0 :-)> > Paul.> > PS I imagine that 2to3 would have fixed this up fine, but it was so> easy to do by hand that I didn't bother :-)> --> http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Get the next generation of Free Windows Live Services http://get.live.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Dec 12 11:50:38 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Dec 2008 11:50:38 -0500 Subject: Removing None objects from a sequence In-Reply-To: <87ej0dz894.fsf@daycos.com> References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> Message-ID: Kirk Strauser wrote: > At 2008-12-12T15:51:15Z, Marco Mariani writes: > >> Filip Gruszczy?ski wrote: >> >>> I am not doing it, because I need it. I can as well use "if not elem >>> is None", > >> I suggest "if elem is not None", which is not quite the same. > > So what's the difference exactly? "foo is not None" is actually surprising > to me, since "not None" is True. "0 is True" is False, but "0 is not None" > is True. Why is that? "is not" is an operator, so the parse is foo (is not) None not foo is (not None) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From research at johnohagan.com Sat Dec 20 09:47:29 2008 From: research at johnohagan.com (John O'Hagan) Date: Sat, 20 Dec 2008 14:47:29 +0000 Subject: Namespaces, multiple assignments, and exec() In-Reply-To: References: Message-ID: <200812201447.29230.research@johnohagan.com> On Sat, 20 Dec 2008, Arnaud Delobelle wrote: > John O'Hagan writes: > > I have a lot of repetitive assignments to make, within a generator, > > that use a function outside the generator: > > > > var1 = func("var1", args) > > var2 = func("var2", args) > > var3 = func("var3", args) > > etc... > > > > In each case the args are identical, but the first argument is a > > string of the name being assigned. It works fine but I'd like to > > reduce the clutter by doing the assignments in a loop. I've tried > > using exec(): > > > > for name in name_string_list: > > exec(name + ' = func(\"' + name + '\", args)') > > > > but in the local namespace it doesn't understand func(), and if I give > > it globals() it doesn't understand the args, which come from within > > the generator. > > > > What's a good way to do this kind of thing? > > Your problem is describe in too vague a way to get good answers IMHO. > Are var1, var2, ... globals or local to the generator? Can you give > some sample code to show what doesn't work? The vars are all local to the generator. This is what doesn't work (I have omitted some functions called by the first function for brevity): def iterizer(options_dict): """Convert controllable option values to generators""" range_ctrls = ['length', 'variety', 'z_depth', 'z_variety'] numerical_ctrls = ['bank', 'bell', 'channel', 'click', 'chord', 'descend', 'divisor', 'forte', 'inv', 'large_scaly', 'metarandomt', 'metat', 'mirrors', 'part', 'pause', 'prime', 'program', 'rand', 'randomt', 'rotate', 'shuffle_phrase', 'split', 'small_scaly', 'tempo', 'translate', 'transpose', 'updown' , 'voice', 'volume'] list_ctrls = ['all_check', 'degrees', 'exclude', 'finelist', 'nondegrees', 'include', 'only', 'pattern', 'rhythm', 'z_test'] generators = {} for item in options_dict.iteritems(): opt, value = item[0], item[1] if value is not None: if value[0] == "C": ctrl_opts = optparse(value[1:]) iterator = sequence_engine(ctrl_opts) if opt in numerical_ctrls: iterator = numerical_iter(iterator) elif opt in range_ctrls: iterator = range_iter(iterator) else: iterator = dummy_ctrl(value) if opt not in list_ctrls: iterator = numerical_iter(iterator) generators[opt] = iterator return generators def inext(option, generators, options_dict): """Cycling version of next()""" if generators.has_key(option): try : return generators[option].next() except StopIteration: minidict = {option:options_dict[option]} minigens = iterizer(minidict) generators.update(minigens) return generators[option].next() def sequence_engine(options): """Produce Sequence instances""" engine_opts = ['length', 'variety', 'z_depth', 'z_variety', 'descend', 'divisor', 'forte', 'inv', 'large_scaly', 'mirrors', 'part', 'prime', 'rand', 'rotate', 'shuffle_phrase', 'split', 'small_scaly', 'translate', 'transpose', 'updown' , 'voice', 'all_check', 'degrees', 'exclude', 'finelist', 'nondegrees','include', 'only', 'pattern', 'z_test', 'cardinal'] engine_dict = {} for item in engine_opts: engine_dict[item] = options.__dict__[item] generators = iterizer(engine_dict) for name in engine_opts: exec(name + ' = inext(\"' + name + '\" ,generators, engine_dict)') ....etc.. The last loop fails to assign any names for the reasons described in the OP. Regards, John From ylj798 at gmail.com Tue Dec 2 14:08:48 2008 From: ylj798 at gmail.com (ylj798 at gmail.com) Date: Tue, 2 Dec 2008 11:08:48 -0800 (PST) Subject: help me~!about base64 References: <0ff1ba7b-8a17-4647-99fc-9c8e32f83de7@g1g2000pra.googlegroups.com> Message-ID: On 12?3?, ??1?50?, "Jerry Hill" wrote: > 2008/12/2 : > > > it's run ,Eric gave me error,the error is "'module'objecthasno > >attribute'decodestring'", > > Do you have your own base64.py (or base64.pyc) that's shadowing the > standardmodulebase64? Try this: > > >>> import base64 > >>> print base64.__file__ > > C:\Python25\lib\base64.py > > > > What does that say when you do it? > > -- > Jerry look,when i work it,tell me blow >>>print base64.__file__ /usr/lib/python2.5/base64.pyc From warren at delsci.com Thu Dec 4 15:11:15 2008 From: warren at delsci.com (Warren DeLano) Date: Thu, 4 Dec 2008 12:11:15 -0800 Subject: To Troll or Not To Troll Message-ID: <896B75251BA19745A529B1B867893FA50679D3@planet.delsci.local> > I still would have to call your management of the problem considerably > into question - your expertise at writing mathematical software may > not be in question, but your skills and producing and managing a > software product are. You have nobody at your organization, which > sells a product that relies on Python, who follows python-dev? Or who > even reads the changelogs for new python versions? You should have > known about the "as" keyword change *over a year ago*, even if the > import bug was masking the deprecation warning. Everything else aside, > I can't get past that issue with your complaints. I *have* gone back > now and read all the posts in all the threads and I still have not > seen a single post from you even hinting that you might have any > responsibility in the matter. Well then, let me set the record straight on that one point: I admit that it was entirely my mistake (and mine alone) to implicitly assume, by adopting such a logging & persistence architecture (dating back to 1.5.2, mind you!), that new keywords would not be introduced into the Python language so as to potentially break all existing Python code. Silly me! How unreasonable. From steve at REMOVE-THIS-cybersource.com.au Wed Dec 24 02:19:01 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 24 Dec 2008 07:19:01 GMT Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: <0161d999$0$20621$c3e8da3@news.astraweb.com> On Tue, 23 Dec 2008 08:06:35 -0800, the anonymous troll known only as "r" replied to Thorsten Kampe and said: > Thats "Thurstan", thank you very much! :) I think Thorsten knows how to spell his own name. -- Steven From steve at REMOVE-THIS-cybersource.com.au Mon Dec 29 21:02:16 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Dec 2008 02:02:16 GMT Subject: get method References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> <4819de67-72dc-415c-b4c8-2353581c2bc7@r2g2000vbp.googlegroups.com> Message-ID: <0169782e$0$6988$c3e8da3@news.astraweb.com> On Mon, 29 Dec 2008 17:38:36 -0800, Ross wrote: > On Dec 29, 8:07?pm, Scott David Daniels wrote: >> Ross wrote: >> > ... Use get to write histogram more concisely. You should be able to >> > eliminate the if statement. >> >> > def histogram(s): >> > ? ?d = dict() >> > ? ?for c in s: >> > ? ? ? ? ? ?d[c]= d.get(c,0) >> > ? ?return d >> >> > This code returns a dictionary of all the letters to any string s I >> > give it but each corresponding value is incorrectly the default of 0. >> > What am I doing wrong? >> >> How is this code supposed to count? >> >> --Scott David Daniels >> Scott.Dani... at Acm.Org > > I realize the code isn't counting, but how am I to do this without using > an if statement as the problem instructs? You don't increment a value using if. This would be silly: # increment x if x == 0: x = 1 elif x == 1: x = 2 elif x == 2: x = 3 # can I stop yet? else: x = "I can't count that high!" You increment a value using + 1: x = x + 1 or x += 1 In the original code, the program did this: def histogram(s): d = dict() for c in s: if c not in d: d[c] = 1 else: d[c] += 1 * look for c in the dict * if it isn't there, set d[c] to 1 * but if it is there, increment d[c] by 1 Your attempt was quite close: def histogram(s): d = dict() for c in s: d[c]= d.get(c,0) return d which is pretty much the same as: * set d[c] to whatever d[c] already is, or 0 if it isn't already there. So what you need is: * set d[c] to whatever d[c] already is plus one, or 0 plus one if it isn't already there. It's a two character change to one line. Let us know if you still can't see it. -- Steven From ajaksu at gmail.com Mon Dec 29 17:18:25 2008 From: ajaksu at gmail.com (ajaksu) Date: Mon, 29 Dec 2008 14:18:25 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <59dfc7f8-cfd4-4e22-ad83-52cd8ea57c1f@e18g2000yqo.googlegroups.com> Message-ID: <523f88c6-d3ff-4b9f-b585-a435e112b05e@k8g2000yqn.googlegroups.com> On Dec 29, 7:37?pm, Luis M. Gonz?lez wrote: > I still can't get used to add the parenthesis to "print", and this is > the only thing I don't like, but I'm sure there's a good reason for > this change... I should know better than to post such an awful hack: __past__.py: from sys import excepthook as sys_excepthook from sys import modules --- def printhook(exctype, value, traceback): skip = True if isinstance(value, SyntaxError): if 'print ' in value.text: printable = value.text.replace('print ', '')[:-1] skip = False toprint = 'print(' + printable +')' print('Trying to convert your mess into', toprint) try: exec(toprint) except NameError as ne: name = str(ne).replace("name '", '').replace("' is not defined", '') try: var = str(getattr(modules['__main__'], name)) exec('print(' + printable.replace(name, var) + ')') except AttributeError as ae: sys_excepthook(NameError, ne, traceback) except SyntaxError as se: print('NameError workaround replaced something bad') skip = True except NameError as ne2: print('Too many names to map to objects :P') skip = True except: print('Sorry, something went wrong and I am too lazy to find out what') skip = True except: raise skip = True if skip: sys_excepthook(exctype, value, traceback) --- Then, as I'd check some stuff in parallel on 2.5 and 3.0, I do this on the 3.0 prompt: --- import sys exchook = sys.excepthook from __past__ import printhook sys.excepthook = printhook --- As soon as I wrote that mess^H^H^H^H helper, remembering to use print () became easier (I think the trauma helped) and I haven't imported much from __past__ since. Should I hit 'send'? Daniel From benjamin.kaplan at case.edu Sat Dec 13 22:25:07 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sat, 13 Dec 2008 22:25:07 -0500 Subject: 1 or 1/0 doesn't raise an exception In-Reply-To: References: Message-ID: Not that I'm against promoting Python, but most languages have support for short circuit evaluation. That's why you usually use && and || in C, C++, C# and Java- & and | will always evaluate both sides. Short circuit evaluation is what allows you to write things like "if foo is not None and foo.isTrue()". On Sat, Dec 13, 2008 at 9:57 PM, r wrote: > These are just the kind of things that make Python so beautiful ;) > Thanks Guido! > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From callen314 at gmail.com Tue Dec 16 15:37:26 2008 From: callen314 at gmail.com (Craig Allen) Date: Tue, 16 Dec 2008 12:37:26 -0800 (PST) Subject: How to modify a program while it's running? References: Message-ID: <6e2cfc09-5aae-480c-b32d-d5a942044ba3@i24g2000prf.googlegroups.com> On Dec 16, 10:25 am, Joe Strout wrote: > Here's my situation: I'm making an AIM bot, but the AIM server will > get annoyed if you log in too frequently (and then lock you out for a > while). So my usual build-a-little, test-a-little methodology doesn't > work too well. > > So I'd like to restructure my app so that it can stay running and stay > logged in, yet I can still update and reload at least most of the > code. But I'm not sure what's the best way to do this. Should I move > the reloadable code into its own module, and then when I give my bot a > "reload" command, have it call reload on that module? Will that work, > and is there a better way? > > Thanks, > - Joe yes you want reload. Design the high level part that knows how to log in to be able to reload the stuff that changes. My guess is that is the best way, though I wouldn't be surprised if there are other solutions. From jarausch at skynet.be Mon Dec 1 16:01:00 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Mon, 01 Dec 2008 22:01:00 +0100 Subject: Is it safe to modify the dict returned by vars() or locals() Message-ID: <4934508b$0$2861$ba620e4c@news.skynet.be> Hi, I am looking for an elegant way to solve the following problem: Within a function def Foo(**parms) I have a list of names, say VList=['A','B','C1'] and I like to generate abbreviation _A identical to parms['A'] for that I could write def Foo(**parms) : for N in VList : if N in parms : vars()[N]= parms[N] else : vars()[N]= None Does this work, is it typical Python? Many thanks for a hint, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From invalid at invalid Mon Dec 22 13:51:46 2008 From: invalid at invalid (Grant Edwards) Date: Mon, 22 Dec 2008 12:51:46 -0600 Subject: I always wonder ... References: Message-ID: On 2008-12-22, skip at pobox.com wrote: > ... shouldn't people who spend all their time trolling be > doing something else: studying, working, writing patches which > solve the problems they perceive to exist in the troll > subject? I think you misunderstand the point of trolling. The author of a troll post doesn't actually care about the "problems" (and may not even genuinely perceive them as problems). > Is there some online troll game running where the players earn > points for generating responses to their posts? Yup. It's called Usenet. I'm sure we all have our, um, "non-productive" hobbies and forms of entertainment. A well done troll [which, I admit, is somewhat rare] is a bit of an art, and can be rather entertaining to watch. Of course there's the other, much larger, category of posters (sometimes confused with trollers): the lazy, ignorant whingers. Apart from being much more common, they're also much less entertaining to everybody except the ranting flamer. As you can see, Usenet is a rather complex eco-system with a lot of niches... -- Grant Edwards grante Yow! What PROGRAM are they at watching? visi.com From stef.mientki at gmail.com Tue Dec 16 18:02:56 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 17 Dec 2008 00:02:56 +0100 Subject: Python is slow In-Reply-To: References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <355f1cfe-6abb-4d2c-8bf4-3aa62e713c1f@w34g2000yqm.googlegroups.com> Message-ID: <494833A0.7050905@gmail.com> r wrote: > On Dec 15, 7:15 am, Luis M. Gonz?lez wrote: > >> On Dec 15, 1:38 am, cm_gui wrote: >> >> >>> hahaha, do you know how much money they are spending on hardware to >>> make >>> youtube.com fast??? >>> >>>> By the way... I know of a very slow Python site called YouTube.com. In >>>> fact, it is so slow that nobody ever uses it. >>>> >> Buddy, just stop whining and go with c++ if it makes you happy. >> By the way, what's the blazingly fast application you need to write so >> desperately? >> What kind of performance problem have you find in python that makes >> you so unhappy? >> What are you going to do with all the extra speed provided by c++ (a >> Hello World! ?)... >> > > Still no reply from cm_gui, he must have googled "C hello world" :D > or cm_gui is slow, btw I thought r was a statistic package ;-) cheers, Stef > -- > http://mail.python.org/mailman/listinfo/python-list > From febaen at gmail.com Mon Dec 15 16:23:30 2008 From: febaen at gmail.com (feba) Date: Mon, 15 Dec 2008 13:23:30 -0800 (PST) Subject: Need help improving number guessing game References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> <01564c98$0$21844$c3e8da3@news.astraweb.com> <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> Message-ID: I added the ability to select your own range. It takes two new modules: def customrange(game, lowunsafe=True): game['defrang'] = False #Keeps setup from changing range to defaults while lowunsafe: #makes sure that the low number is positive picklow = int(input("PLEASE PICK THE LOW NUMBER: ")) if picklow < 0: print("LOW NUMBER MUST BE POSTIVE") else: lowunsafe = False pickhigh = int(input("PLEASE PICK THE HIGH NUMBER: ")) if pickhigh - picklow <= 2: #see setup(). print("HIGH MUST BE AT LEAST THREE GREATER THAN LOW") else: game['minr'], game['maxr'] = picklow, pickhigh print("RANGE IS [%s-%s]!" % (game['minr'], game['maxr'])) def wantcustom(game, unsure=True): #Allows user to decide their own range for guessing. while unsure: pickrange = input("WOULD YOU LIKE TO CREATE A CUSTOM RANGE? Y/ N: ") if pickrange.lower() == "n": game['minr'], game['maxr'] = 1, 99 #Default range unsure = False elif pickrange.lower() == "y": customrange(game) unsure = False else: print("INVALID INPUT") A slightly updated setup (it needed it anyway): def setup(game): #minr, maxr make minimum and maximum. Can be adjusted. #Make sure that maxr - minr is at least 3. #1 or less would be impossible. 2 would only have one guess for victory #The first would be unplayable, the second would play itself if game['maxr'] - game['minr'] <= 2: raise ValueError("INVALID RANGE!") game['gcount'] = 0 #Reset guess count game['target'] = random.randint(game['minr'], game['maxr']) and putting wantcustom(game) immediately before setup(game) in main(). From roy at panix.com Tue Dec 9 08:31:02 2008 From: roy at panix.com (Roy Smith) Date: Tue, 09 Dec 2008 08:31:02 -0500 Subject: Learning Python now coming from Perl References: Message-ID: Nick Craig-Wood wrote: > > On the other hand, leaving out the parens returns the function itself, > > which you can then call later. I've often used this to create data-driven > > logic. > > I didn't say it wasn't useful, just that if you came from Perl like I > did, it is an easy mistake to make ;-) Agreed. > OO lore says whenever you see a type field in an instance you've gone > wrong - types should be represented by what sort of object you've got, > not by a type field. OO lore lives in an ivory tower sometimes :-) I'm working with an existing system, where objects are marshaled on the wire as type codes followed by a type-specific number of bytes of data. Internally, it calls these AnyVals and the concept is pervasive in the architecture. I could work within the existing architecture, or I could try to fight it. Yes, I could get rid of the dispatch table and create 20 or 30 classes to represent all the possible types. I'd end up with several times as much code, most of it boilerplate. Instead of having a dispatch table of read/write functions, I'd have a dispatch table of classes, each of which has a read method and a write method. It doesn't buy anything, and I'd still have the type codes exposed because I need them to read and write values to the wire. From tjreedy at udel.edu Fri Dec 5 13:24:34 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 05 Dec 2008 13:24:34 -0500 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: References: Message-ID: Johannes Bauer wrote: > Hello group, > > I'm having trouble reading a utf-16 encoded file with Python3.0. This is > my (complete) code: what OS. This is often critical when you have a problem interacting with the OS. > #!/usr/bin/python3.0 > > class AddressBook(): > def __init__(self, filename): > f = open(filename, "r", encoding="utf16") > while True: > line = f.readline() > if line == "": break > print([line[x] for x in range(len(line))]) > f.close() > > a = AddressBook("2008_11_05_Handy_Backup.txt") > > This is the file (only 1 kB, if hosting doesn't work please tell me and > I'll see if I can put it someplace else): > > http://www.file-upload.net/download-1297291/2008_11_05_Handy_Backup.txt.gz.html > > What I get: The file reads file the first few lines. Then, in the last > line, I get lots of garbage (looking like uninitialized memory): > > ['E', 'n', 't', 'r', 'y', '0', '0', 'T', 'e', 'x', 't', ' ', '=', ' ', > '"', 'A', 'D', 'A', 'C', ' ', 'V', 'e', 'r', 'k', 'e', 'h', 'r', 's', > 'i', 'n', 'f', 'o', '"', '\u0d00', '\u0a00', '?', '?', '?', '?', '? > ', '\u3000', '\u3100', '?', '?', '?', '?', '\u2000', '?', '\u2000', > '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', > '\u0d00', '\u0a00', '?', '?', '?', '?', '?', '\u3000', '\u3100', ' > ?', '?', '?', '?', '\u2000', '?', '\u2000', '?', '?', '?', '?', > '\u3100', '?', '?', '?', '?', '?', '?', '?', '?', '\u0d00', > '\u0a00', '\u0d00', '\u0a00', '?', '?', '?', '?', '?', '?', '?', > '?', '?', '\u3000', '\u3000', '?', '?', '\u0d00', '\u0a00'] > > Where the line > > Entry00Text = "ADAC Verkehrsinfo"\r\n From \r\n I guess Windows. Correct? I suspect that '?' after \n (\u0a00) is indicates not 'question-mark' but 'uninterpretable as a utf16 character'. The traceback below confirms that. It should be an end-of-file marker and should not be passed to Python. I strongly suspect that whatever wrote the file screwed up the (OS-specific) end-of-file marker. I have seen this occasionally on Dos/Windows with ascii byte files, with the same symptom of reading random garbage pass the end of the file. Or perhaps end-of-file does not work right with utf16. > is actually the only thing the line contains, Python makes the rest up. No it does not. It echoes what the OS gives it with system calls, which is randon garbage to the end of the disk block. Try open with explicit 'rt' and 'rb' modes and see what happens. Text mode should be default, but then \r should be deleted. > The actual file is much longer and contains private numbers, so I > truncated them away. When I let python process the original file, it > dies with another error: > > Traceback (most recent call last): > File "./modify.py", line 12, in > a = AddressBook("2008_11_05_Handy_Backup.txt") > File "./modify.py", line 7, in __init__ > line = f.readline() > File "/usr/local/lib/python3.0/io.py", line 1807, in readline > while self._read_chunk(): > File "/usr/local/lib/python3.0/io.py", line 1556, in _read_chunk > self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) > File "/usr/local/lib/python3.0/io.py", line 1293, in decode > output = self.decoder.decode(input, final=final) > File "/usr/local/lib/python3.0/codecs.py", line 300, in decode > (result, consumed) = self._buffer_decode(data, self.errors, final) > File "/usr/local/lib/python3.0/encodings/utf_16.py", line 69, in > _buffer_decode > return self.decoder(input, self.errors, final) > UnicodeDecodeError: 'utf16' codec can't decode bytes in position 74-75: > illegal encoding > > With the place where it dies being exactly the place where it outputs > the weird garbage in the shortened file. I guess it runs over some page > boundary here or something? Malformed EOF more likely. Terry Jan Reedy From mrkafk at gmail.com Mon Dec 29 10:14:14 2008 From: mrkafk at gmail.com (mk) Date: Mon, 29 Dec 2008 16:14:14 +0100 Subject: multiprocessing vs thread performance In-Reply-To: References: Message-ID: janislaw wrote: > Ah, so there are 100 processes at time. 200secs still don't sound > strange. I ran the PEP 371 code on my system (Linux) on Python 2.6.1: Linux SLES (9.156.44.174) [15:18] root ~/tmp/src # ./run_benchmarks.py empty_func.py Importing empty_func Starting tests ... non_threaded (1 iters) 0.000005 seconds threaded (1 threads) 0.000235 seconds processes (1 procs) 0.002607 seconds non_threaded (2 iters) 0.000006 seconds threaded (2 threads) 0.000461 seconds processes (2 procs) 0.004514 seconds non_threaded (4 iters) 0.000008 seconds threaded (4 threads) 0.000897 seconds processes (4 procs) 0.008557 seconds non_threaded (8 iters) 0.000010 seconds threaded (8 threads) 0.001821 seconds processes (8 procs) 0.016950 seconds This is very different from PEP 371. It appears that the PEP 371 code was written on Mac OS X. The conclusion I get from comparing above costs sis that OS X must have very low cost of creating the process, at least when compared to Linux, not that multiprocessing is a viable alternative to thread / threading module. :-( From kyosohma at gmail.com Mon Dec 1 09:21:37 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 1 Dec 2008 06:21:37 -0800 (PST) Subject: How to distribute a Python app together with its dependencies? References: Message-ID: <2343b577-215b-4b4c-8ea0-00dd49369df1@x38g2000yqj.googlegroups.com> On Nov 30, 6:22?am, Alessio Pace wrote: > Hi, > > I have to distribute a Python application which relies on an external > library, and I'm not very fluent in this kind of stuff with Python (I > come from the Java world where I would have used the Maven build tool > to create an "assembly with dependencies" of all it is needed to run > the app), so I was wondering if someone here could give me some > suggestions :-) > > The external library is generally not present on the machines where I > have to distribute my app, and the set of machines on which I have to > distribute this application is not known a priori (it is just known > they are Unix systems). In fact by means of SSH I will have to copy > (and install) the app+library and make it runnable onto the specified > destination(s). > > My question is: how would you do that? ?At the moment my current > solution is to make a tarball of the sources of my app + the > "distutils" archive of the external library, copy all into the target > machine, decompress and install via distutils(*) the external library, > setup some PYTHONPATH stuff on the destination machine, and finally be > able to launch the application. > > (*) specifying a prefix into the user home, as I'm not root there > > So in the end I was wondering if there is a more elegant way of doing > this because, as I said before, I'm not very experienced in these kind > of tasks in Python. > > Thanks in advance for any suggestion or comment. > > Alessio Pace. I recommend GUI2Exe, a nice wrapper to py2exe, py2app, PyInstaller, cx_Freeze and bbFreeze: http://code.google.com/p/gui2exe/ I've only used the py2exe portion of the program, but it works great and the developers behind the project are very responsive and helpful. Mike From castironpi at gmail.com Tue Dec 23 05:46:08 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 23 Dec 2008 02:46:08 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com><6ra8t0F925rU1@mid.individual.net><29feda0d-6432-4cb9-8809-e4d4a7798601@e1g2000pra.googlegroups.com><6raeb8F9s47U2@mid.individual.net><25b1ece0-712b-4516-af28-88c50d00ab8c@s9g2000prg.googlegroups.com> Message-ID: On Dec 23, 2:33?am, "Hendrik van Rooyen" wrote: > "r" wrote: > >Now thats the kind of friendly banter this group could use. Instead of > >people acting as if their bowel-movements smell like bakery fresh > >cinnamon rolls! > > What an amazing thing to say! > > Doesn't yours? > > - Hendrik You think your ships don't sink? From hniksic at xemacs.org Fri Dec 12 09:51:31 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 12 Dec 2008 15:51:31 +0100 Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> Message-ID: <87oczhmop8.fsf@mulj.homelinux.net> sturlamolden writes: > On Dec 12, 3:08 pm, Marc 'BlackJack' Rintsch wrote: > >> No bug because a mutation *is* attempted. ``a += x`` calls `a.__iadd__` >> which *always* returns the result which is *always* rebound to the name >> `a`. Even with mutable objects where `__iadd__()` simply returns >> `self`! > > No, a mutation is not attempted, even if __iadd__() always returns a > value. Mutation is attempted. A += x (where "A" could be anything valid at the left-hand side of assignment, including item subscript) is not implemented intuitivaly, as: if hasattr(b, '__iadd__'): A.__iadd__(x) # ignore return value else: A = A.__add__(x) It is implemented as something like: if hasattr(b, '__iadd__'): newval = A.__iadd__(x) else: newval = A.__add__(x) A = newval So the only difference between __add__ and __iadd__ is that __iadd__ is only consulted on +=, where as __add__ is consulted on both + and += (in the latter case only if __iadd__ is missing). > The tuple should check that it is > actually being *mutated* before it raises any exception. Tuple has no way to check that. What tuple sees is only the last line: t[0] = newval At that point, the information about what is really going on is long lost. The only thing tuple could do is detect that the same object is being written that's already there, but tuple doesn't do that by design. From enleverlesX.XmcX at XmclaveauX.com Sat Dec 27 03:30:41 2008 From: enleverlesX.XmcX at XmclaveauX.com (=?UTF-8?Q?M=C3=A9ta-MCI_=28MVP=29?=) Date: Sat, 27 Dec 2008 09:30:41 +0100 Subject: multiply each element of a list by a number In-Reply-To: References: Message-ID: <4955e7be$0$4066$ba4acef3@news.orange.fr> Hi! > map(multby3, (1, 2, 3, )) ...with lambda: map(lambda x: x*3, [1,2,3]) @-salutations -- Michel Claveau From prologic at shortcircuit.net.au Wed Dec 31 00:02:21 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 15:02:21 +1000 Subject: How to get back a list object from its string representation? In-Reply-To: <78f8019c0812302046j31fa38aeif33d659ec5f2c84e@mail.gmail.com> References: <78f8019c0812302046j31fa38aeif33d659ec5f2c84e@mail.gmail.com> Message-ID: On Wed, Dec 31, 2008 at 2:46 PM, Harish Vishwanath wrote: > Hello, > Consider : >>>> li = [1,2,3] >>>> repr(li) > '[1, 2, 3]' > Is there a standard way to get back li, from repr(li) ? Normally you would use eval(..) however this is considered by many to be evil and bad practise (especially by me!) I would advise you use pickle instead. Using eval (evil): >>> li = [1, 2, 3] >>> s = repr(li) >>> s '[1, 2, 3]' >>> lii = eval(s) >>> lii [1, 2, 3] >>> lii == li True Using pickle (better): >>> from pickle import dumps, loads >>> li = [1, 2, 3] >>> s = dumps(li) >>> s '(lp0\nI1\naI2\naI3\na.' >>> lii = loads(s) >>> lii [1, 2, 3] >>> lii == li True cheers James From rt8396 at gmail.com Mon Dec 22 22:15:20 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 19:15:20 -0800 (PST) Subject: iterating initalizations References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> Message-ID: <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> I can't check you code because i don't have these modules but here is the code with proper indention import random from rtcmix import * from chimes_source import * from rhythmblock import * from pitchblock import * indexrand = random.Random() indexrand.seed(2) rhythm = rhythmBlock() pitch = pitchBlock() class pitchAndRhythm: def __init__(self): self.__abet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def listCreate(self, num): if num > 25: print "Oops. This won't work" else: for a in range(num): b = indexrand.randint(0, 3) c = indexrand.randint(0, 7) index = self.__abet[a] index = [ ] index = index.append(rhythm.rhythmTwist(b, c)) take 2: notice the "(" and ")" around the arg to __init__ From onidaito at gmail.com Wed Dec 31 07:37:00 2008 From: onidaito at gmail.com (Benjamin Blundell) Date: Wed, 31 Dec 2008 04:37:00 -0800 (PST) Subject: Graphics Library with Standard Interaction Features, 2D and 3D Message-ID: <69c3eca8-5e17-49fb-8354-5fdc0bd73f9a@r15g2000prd.googlegroups.com> Hi all. I've had a look around the forums and the we and im looking for a library (or a set of libraries) for dealing with Visualisation and Interaction in Python. At the moment i've been using Flash with the Five3D library to do most of the work. Sadly this isnt an option anymore but it is a good example. Pretty,anti-aliased 2D and 3D graphics, simple interaction and no need to rewrite the wheel. Im a fan of OpenGL and PyOpenGL is fairly cool but I really dont want to have to write yet another camera, another way of dealing with Vectors, texture organiser, picking, etc etc. Is there a library or set of libraries that people are aware of that might do this? I remember a few in C++ and C but it'd be nicer to stick to working with Python Cheers Ben From walterbyrd at iname.com Sun Dec 21 00:11:16 2008 From: walterbyrd at iname.com (walterbyrd) Date: Sat, 20 Dec 2008 21:11:16 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> On Dec 20, 5:05?pm, Roy Smith > He got really hung up on the % syntax. I guess it's good to know that there is, at least, one person in the world doesn't like the % formatting. As least the move was not entirely pointless. But, you must admit, of all the things people complain about with Python, the % formatting is probably one of the least common complaints. Complaints about Python's speed seem much more common. Yet, 3.0 makes the speed worse, and "fixes" a non-problem. I can see where the new formatting might be helpful in some cases. But, I am not sure it's worth the cost. From pruebauno at latinmail.com Mon Dec 15 11:05:25 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Mon, 15 Dec 2008 08:05:25 -0800 (PST) Subject: stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> <015612ac$0$20639$c3e8da3@news.astraweb.com> Message-ID: <52cfb77e-4baf-4fba-8eac-cc6c7ddb5be5@k1g2000prb.googlegroups.com> > Non-comparison sorts are a useful technique, but it's changing the > problem, and they are only useful in very limited circumstances. There's > a good reason that most sort routines are based on O(n*log n) comparison > sorts instead of O(n) bucket sorts or radix sorts. > This is an assumption that I never quite understood. What most people want is to have sorted data, they don't care if I used a sorting or non-sorting comparison to do it. I think it is just that in most cases n is not very big anyway and comparison sorts make it easier on the programmer to create arbitrary types that are sortable. From the.brown.dragon.blog at gmail.com Thu Dec 11 09:50:18 2008 From: the.brown.dragon.blog at gmail.com (the.brown.dragon.blog at gmail.com) Date: Thu, 11 Dec 2008 06:50:18 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> Message-ID: <91bf5d87-0154-472b-9350-e3290ab867e1@k1g2000prb.googlegroups.com> On Dec 11, 4:53?pm, "William James" wrote: > William James wrote: > > John W Kennedy wrote: > > > > Xah Lee wrote: > > > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or > > > > Java, you'll have 50 or hundreds lines. > > > > Java: > > > > static float[] normal(final float[] x) { > > > ? ?float sum = 0.0f; > > > ? ?for (int i = 0; i < x.length; ++i) sum += x[i] * x[i]; > > > ? ?final float divisor = (float) Math.sqrt(sum); > > > ? ?float[] a = new float[x.length]; > > > ? ?for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor; > > > ? ?return a; > > > } > > > "We don't need no stinkin' loops!" > > > SpiderMonkey Javascript: > > > function normal( ary ) > > { div=Math.sqrt(ary.map(function(x) x*x).reduce(function(a,b) a+b)) > > ? return ary.map(function(x) x/div) > > } > > The variable "div" shouldn't be global. > > function normal( ary ) > { var div = Math.sqrt( > ? ? ary.map(function(x) x*x).reduce(function(a,b) a+b) ) > ? return ary.map(function(x) x/div) > > } > > Chicken Scheme: (require 'srfi-1) (define (norm vec) (map (cute / <> (sqrt (reduce + 0 (map (cute expt <> 2) vec)))) vec)) Cute huh? ;-) From kylefranki at gmail.com Thu Dec 25 08:38:22 2008 From: kylefranki at gmail.com (kylefranki at gmail.com) Date: Thu, 25 Dec 2008 05:38:22 -0800 (PST) Subject: Canada lesbian couple Message-ID: <1a933c28-e2d5-43c5-877a-c89349d9046b@a12g2000pro.googlegroups.com> couple de lesbienne cherche sex occasionnelle femme seulement http://canada-lesbi.blogbugs.org/ From sjmachin at lexicon.net Fri Dec 19 19:38:25 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 19 Dec 2008 16:38:25 -0800 (PST) Subject: Jarow-Winkler algorithm: Measuring similarity between strings References: <4f351b3b-4da7-4fee-a1ac-c42179d430f5@s9g2000prm.googlegroups.com> Message-ID: On Dec 20, 10:02?am, ?yvind wrote: > Based on examples and formulas fromhttp://en.wikipedia.org/wiki/Jaro-Winkler. For another Python implementation, google "febrl". > Useful for measuring similarity between two strings. For example if > you want to detect that the user did a typo. You mean like comparing the user's input word with some collection of valid words? You would need to be using something else as a quick-and- dirty filter ... Jaro-Winkler is relatively slow. > > def jarow(s1,s2): > > ? ? """ ?Returns a number between 1 and 0, where 1 is the most similar > > ? ? ? ? example: > > ? ? ? ? print jarow("martha","marhta") > > ? ? ? ? """ > ? ? m= jarow_m(s1,s2) > ? ? t1 = jarow_t(s1,s2) > ? ? t2 = jarow_t(s2,s1) > ? ? t = float(t1)/float(t2) Huh? t1 and t2 are supposed to be counts of transpositions. So is t. So how come t is a ratio of t1 to t2?? BTW, suppose t2 is zero. One usually prefers symmetry i.e dist(s1, s2) == dist(s2, s1). You can't have symmetry if t = t1/t2. Also as the Wikipedia article says, it's not a metric. I.e. it doesn't satisfy dist(a, c) <= dist(a, b) + dist(b, c). > > ? ? d = 0.1 > > ? ? # this is the jaro-distance > ? ? d_j = 1.0/3.0 * ((m/len(s1)) + (m/len(s2)) + ((m - t)/float(m))) > > ? ? # if the strings are prefixed similar, they are weighted more > heavily > ? ? l = winkler_l(s1,s2) > ? ? print l > ? ? return d_j + (l * 0.1 * (1 - d_j)) > > def winkler_l(s1,s2): > ? ? """ Number of the four first characters matching """ > > ? ? l = 0 > ? ? counter = 0 > ? ? for s_j,s_i in zip(s1,s2): > > ? ? ? ? if s_j == s_i: > > ? ? ? ? ? ? l += 1 > ? ? ? ? counter += 1 > > ? ? ? ? if counter > 4: > ? ? ? ? ? ? break > > ? ? return l > > def jarow_m(s1,s2): > > ? ? """ Number of matching characters """ This code ignores the caveat from the Wikipedia article """ Two characters from s1 and s2 respectively, are considered matching only if they are not farther than \left\lfloor\frac{\max(|s_1|,|s_2|)} {2}\right\rfloor-1. """ which looks as though it is missing the words "characters apart" or some such from the end of it. FWIW I've never seen this "distance apart" restriction expressed unambiguously in the case where the strings are of unequal length. > ? ? m = 0 > ? ? d = {} > ? ? for s in s1: > > ? ? ? ? d[s] = True > > ? ? for s in s2: > > ? ? ? ? if d.has_key(s): > > ? ? ? ? ? ? m += 1 > ? ? return m The above code is not symmetrical; jarow_m(s1, s2) does not necessarily equal jarow_m(s2, s1). The article talks about one "m", not two of them. > def jarow_t(s1,s2): > > ? ? """ > ? ? Number of transpositions > > ? ? """ > > ? ? t= 0 > ? ? pos ={} > ? ? counter = 0 > ? ? for s in s1: > > ? ? ? ? pos[s] = counter > ? ? ? ? counter += 1 > ? ? counter = 0 > ? ? for s in s2: > > ? ? ? ? if pos.has_key(s): > > ? ? ? ? ? ? if pos[s] != counter: This test is likely to come up with the wrong answer if the string lengths differ. > > ? ? ? ? ? ? ? ? t += 1 > > ? ? ? ? counter += 1 > > ? ? return t Cheers, John From steve at REMOVE-THIS-cybersource.com.au Thu Dec 18 20:02:07 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2008 01:02:07 GMT Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> <6qv7kfFeuf65U1@mid.uni-berlin.de> Message-ID: <015ae9e9$0$20656$c3e8da3@news.astraweb.com> On Thu, 18 Dec 2008 10:49:27 -0500, Neal Becker wrote: > So if I want to overload something in my custom class, so that I get a > nice string whether it's printed directly, or as part of a container, > what is the recommendation? Overload both __str__ and __repr__? Either or both or neither, whatever you feel is best. Or create a pretty- print method, and call that manually. I've done all of the above at times. Remember though, that ideally you should be able to round-trip your objects to strings and back again: obj = MyClass(args) eval(repr(obj)) == obj should be true. This isn't compulsory, and it isn't always possible, but unless you have good reason to avoid it, you should aim for that behaviour. BTW Neal, your posts aren't word wrapped. When I read your posts, I get each paragraph as one extremely LONG line scrolling way out to the side. That's against the Internet standards for both email and Usenet, so could you please configure your client to word-wrap at (say) 70 characters? -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun Dec 7 18:51:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 23:51:45 GMT Subject: Rich Comparisons Gotcha References: Message-ID: <014c593e$0$20670$c3e8da3@news.astraweb.com> On Sun, 07 Dec 2008 13:57:54 -0800, James Stroud wrote: > Rasmus Fogh wrote: >> Current behaviour is both inconsistent and counterintuitive, as these >> examples show. >> >>>>> x = float('NaN') >>>>> x == x >> False > > Perhaps this should raise an exception? Why on earth would you want checking equality on NaN to raise an exception??? What benefit does it give? > I think the problem is not with > comparisons in general but with the fact that nan is type float: > > py> type(float('NaN')) > > > No float can be equal to nan, but nan is a float. How can something be > not a number and a float at the same time? Because floats are not real numbers. They are *almost* numbers, they often (but not always) behave like numbers, but they're actually not numbers. The difference is subtle enough that it is easy to forget that floats are not numbers, but it's easy enough to find examples proving it: Some perfectly good numbers don't exist as floats: >>> 2**-10000 == 0.0 True Try as you might, you can't get the number 0.1 *exactly* as a float: >>> 0.1 0.10000000000000001 For any numbers x and y not equal to zero, x+y != x. But that fails for floats: >>> 1001.0 + 1e99 == 1e99 True The above is because of overflow. But even avoiding overflow doesn't solve the problem. With a little effort, you can also find examples of "ordinary sized" floats where (x+y)-y != x. >>> 0.9+0.1-0.9 == 0.1 False >>>>> import numpy >>>>> y = numpy.zeros((3,)) >>>>> y >> array([ 0., 0., 0.]) >>>>> bool(y==y) >> Traceback (most recent call last): >> File "", line 1, in >> ValueError: The truth value of an array with more than one element is >> ambiguous. Use a.any() or a.all() > > But the equality test is not what fails here. It's the cast to bool that > fails And it is right to do so, because it is ambiguous and the library designers rightly avoided the temptation of guessing what result is needed. >>>>> ll1 = [y,1] >>>>> y in ll1 >> True >>>>> ll2 = [1,y] >>>>> y in ll2 >> Traceback (most recent call last): >> File "", line 1, in >> ValueError: The truth value of an array with more than one element is >> ambiguous. Use a.any() or a.all() > > I think you could be safe calling this a bug with numpy. Only in the sense that there are special cases where the array elements are all true, or all false, and numpy *could* safely return a bool. But special cases are not special enough to break the rules. Better for the numpy caller to write this: a.all() # or any() instead of: try: bool(a) except ValueError: a.all() as they would need to do if numpy sometimes returned a bool and sometimes raised an exception. -- Steven From bthayre at physics.ucsd.edu Mon Dec 8 17:43:32 2008 From: bthayre at physics.ucsd.edu (Robocop) Date: Mon, 8 Dec 2008 14:43:32 -0800 (PST) Subject: Text parsing via regex References: Message-ID: Wow! Thanks for all the input, it looks like that textwrapper will work great for my needs. And thanks for the regex help everyone. Also, i was thinking of using a list, but i haven't used them much in python. Is there anything in python that is equivalent to pushback in c++ for vectors? As in, could i just initialize a list, and then pushback values into it as i need them? Thanks again! From mirandasnailvv at gmail.com Fri Dec 19 19:42:11 2008 From: mirandasnailvv at gmail.com (mirandasnailvv at gmail.com) Date: Fri, 19 Dec 2008 16:42:11 -0800 (PST) Subject: tonya cooley softcore porn - Free Message-ID: tonya cooley softcore porn . . . *******CLICK HERE******** http://club247.cn/tonya-cooley-softcore-porn ***************************** . . . . . . . . . . . . tonya cooley softcore porn From sjmachin at lexicon.net Sun Dec 28 17:12:11 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 28 Dec 2008 14:12:11 -0800 (PST) Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <0167cbf7$0$6988$c3e8da3@news.astraweb.com> <676bffeb-4b07-4226-8c14-7da57d94351b@f13g2000yqj.googlegroups.com> Message-ID: <3afba310-dcde-4dc1-825a-7c63b97e2a40@w1g2000prk.googlegroups.com> On Dec 29, 7:06?am, Roger wrote: > > Curious. When I see a bare return, the first thing I think is that the > > author forgot to include the return value and that it's a bug. > > > The second thing I think is that maybe the function is a generator, and > > so I look for a yield. If I don't see a yield, I go back to thinking > > they've left out the return value, and have to spend time trying to > > understand the function in order to determine whether that is the case or > > not. > > > In other words, even though it is perfectly valid Python, bare returns > > always make the intent of the function less clear for me. I'm with Bruno > > -- if you have a function with early exits, and you need to make the > > intent of the function clear, explicitly return None. Otherwise, leave it > > out altogether. > > > -- > > Steven > > To me this is the soundest argument. ?Thanks for the advice. ?I think > I'll follow this as a rule of thumb hereafter. Please don't. Follow MRAB's advice, with the corollary that a generator is forced by the compiler to be a "procedure" in MRAB's terminology. From quian.xu at stud.tu-ilmenau.de Tue Dec 23 05:50:59 2008 From: quian.xu at stud.tu-ilmenau.de (Qian Xu) Date: Tue, 23 Dec 2008 11:50:59 +0100 Subject: print to console without a line break Message-ID: Hello All, Is it possible to print something to console without a line break? I tried: sys.stdout.write("Testing something ...") // nothing will be printed time.sleep(1) sys.stdout.write("done\n") // now, the whole string will be printed What I want, is to see "Testing something ..." first. And after 1 second, to see "done" (with a line break) The only one solution I have found is to call "echo -n 'my_string'". But it is not nice. Because I have to escape all special chars in the string manually. Any advice? Best regards -- Qian Xu From http Wed Dec 17 00:47:11 2008 From: http (Paul Rubin) Date: 16 Dec 2008 21:47:11 -0800 Subject: How to modify a program while it's running? References: Message-ID: <7xtz93qrog.fsf@ruckus.brouhaha.com> Joe Strout writes: > So I'd like to restructure my app so that it can stay running and stay > logged in, yet I can still update and reload at least most of the > code. But I'm not sure what's the best way to do this. Should I move > the reloadable code into its own module, and then when I give my bot a > "reload" command, have it call reload on that module? Will that work, > and is there a better way? If you are on Linux, an alternative might be to start a new version of your program in a separate process, then transfer the open connections from the old process to the new ones through Unix domain sockets. The SCM_RIGHTS message lets you pass file descriptors around between processes. I've never tried this myself but have always wanted to. I think someone submitted a patch for Python's socket module a year or so ago to support that operation, but I don't know if it was accepted. You could always apply it yourself. Generally, trying to hot-patch code is messy and dangerous even in systems that were designed for it. From gagsl-py2 at yahoo.com.ar Tue Dec 30 09:12:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Dec 2008 12:12:32 -0200 Subject: Python module import loop issue References: <02bc8567-695a-4277-9698-a95549a0bc98@w39g2000prb.googlegroups.com> <4a0557b7-e901-49ff-b4db-53f4d8a7c0f8@r40g2000yqj.googlegroups.com> Message-ID: En Tue, 30 Dec 2008 01:32:48 -0200, Carl Banks escribi?: > Gabriel Genellina wrote: >> A problem with metaclasses is when you have intermediate subclasses that >> are not meant to be registered, but the metaclass applies equally to all >> of them. > > Not the way I wrote it. If you'll note, the metaclass only added the > class to the factory map if a tag attribute was defined in the class > dict. Ah, I didn't notice that, sorry! -- Gabriel Genellina From google at mrabarnett.plus.com Fri Dec 5 15:59:06 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 05 Dec 2008 20:59:06 +0000 Subject: slow Python 3.0 write performance? In-Reply-To: References: Message-ID: <4939961A.8080205@mrabarnett.plus.com> Istvan Albert wrote: > On Dec 5, 3:06 pm, s... at pobox.com wrote: > >> It should get faster over time. It will get faster over a shorter period of >> time if people contribute patches. > > I see, thanks for the clarification. > > I will make the point though that this makes python 3.0 unsuited for > anyone who has to process data. One could live with slowdowns of say > 20-50 percent, to get the goodies that 3.0 offers, but when a process > that takes 1 second suddenly starts to take 10, it is makes the > situation untenable. > Does pysco with with Python 3.0 (the homepage says 2.5)? If it does then that might help! :-) From steve at REMOVE-THIS-cybersource.com.au Thu Dec 18 20:51:38 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2008 01:51:38 GMT Subject: Factoring Polynomials References: <015aebdf$0$20656$c3e8da3@news.astraweb.com> Message-ID: <015af585$0$20656$c3e8da3@news.astraweb.com> On Fri, 19 Dec 2008 01:10:28 +0000, Steven D'Aprano wrote: > Because this looks like homework... Homework or not, of course others have answered it completely, more or less error-free. -- Steven From federico at linux.com.uy Fri Dec 19 12:03:53 2008 From: federico at linux.com.uy (Federico Moreira) Date: Fri, 19 Dec 2008 14:03:53 -0300 Subject: Generator slower than iterator? In-Reply-To: <494BC8CC.6020706@mrabarnett.plus.com> References: <62013718-57e9-4690-a2be-11e63b9c135b@u18g2000pro.googlegroups.com> <494BC8CC.6020706@mrabarnett.plus.com> Message-ID: Yep i meant split sorry. Thanks for the answer! -------------- next part -------------- An HTML attachment was scrubbed... URL: From fakeaddress at nowhere.org Mon Dec 15 01:43:55 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 14 Dec 2008 22:43:55 -0800 Subject: Bidirectional Networking In-Reply-To: <29283382-3e26-492a-8612-9352f32c1c01@r15g2000prd.googlegroups.com> References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <98a6c3cd-181c-43c9-805b-fb0689c69544@a26g2000prf.googlegroups.com> <29283382-3e26-492a-8612-9352f32c1c01@r15g2000prd.googlegroups.com> Message-ID: Emanuele D'Arrigo wrote: > Bryan Olson wrote: >> Software firewalls will often simply refuse incoming connections. The >> basic protection of the garden-variety home router comes from "network >> address translation" (NAT), in which case TCP connections initiated from >> the inside will generally work, regardless of port, and incoming >> connections will fail. > > Ok, I think I'm getting the picture here. So this means that in most > circumstances where the data flow from the server is frequent the > client initiates the connection, usually requests some initial data > and keeps polling the server periodically, issuing new requests. In > this context can the client simply keep the connection alive and > listen for new data from the server coming at any time rather than > actively issuing requests? Sure. You might include a method for the client to ensure the connection is alive, either with TCP keep-alive or your own messages over the connection. > Are there drawbacks to this strategy? I.e. > is there a limit to the number of simultaneous connections a server > can keep alive? I've noticed that the socket pages mention a 5 > connections limit. Is that it? What if I want to make a virtual room > with 20 people connected simultaneously? Five is not the connection limit. Twenty connections is no problem, and modern systems should support hundreds by default, and thousands with a bit of care and tuning. >>> or would it be the responsibility of the user >>> to configure the firewall so that the application can receive a >>> connection? >> That can be a huge hassle. The first choice is for the application to >> conform to popular firewall policies, so no special configuration is >> required. > > I agree, I'd rather have the user do nothing in this regard. I'm just > wondering how it's done with data intensive application where the > server needs to send new data to the client frequently. Does the > client just keep the connection live at all time for the server to > send stuff or does the client continuously open, sends a request, > receives data and closes the connection every time? Here I'm thinking > about an online game, with 100 players moving their avatars. Does the > client requests their position nearly every frame? I'd say keeping an open connection to each client is reasonable there. SocketServer and its descendants may not be sophisticated enough for such an application. -- --Bryan From mrkafk at gmail.com Mon Dec 29 12:11:37 2008 From: mrkafk at gmail.com (mk) Date: Mon, 29 Dec 2008 18:11:37 +0100 Subject: multiprocessing vs thread performance In-Reply-To: References: Message-ID: Jarkko Torppa wrote: > On the PEP371 it says "All benchmarks were run using the following: > Python 2.5.2 compiled on Gentoo Linux (kernel 2.6.18.6)" Right... I overlooked that. My tests I quoted above were done on SLES 10, kernel 2.6.5. > With python2.5 and pyProcessing-0.52 > > iTaulu:src torppa$ python2.5 run_benchmarks.py empty_func.py > Importing empty_func > Starting tests ... > non_threaded (1 iters) 0.000003 seconds > threaded (1 threads) 0.000143 seconds > processes (1 procs) 0.002794 seconds > > non_threaded (2 iters) 0.000004 seconds > threaded (2 threads) 0.000277 seconds > processes (2 procs) 0.004046 seconds > > non_threaded (4 iters) 0.000005 seconds > threaded (4 threads) 0.000598 seconds > processes (4 procs) 0.007816 seconds > > non_threaded (8 iters) 0.000008 seconds > threaded (8 threads) 0.001173 seconds > processes (8 procs) 0.015504 seconds There's smth wrong with numbers posted in PEP. This is what I got on 4-socket Xeon (+ HT) with Python 2.6.1 on Debian (Etch), with kernel upgraded to 2.6.22.14: non_threaded (1 iters) 0.000004 seconds threaded (1 threads) 0.000159 seconds processes (1 procs) 0.001067 seconds non_threaded (2 iters) 0.000005 seconds threaded (2 threads) 0.000301 seconds processes (2 procs) 0.001754 seconds non_threaded (4 iters) 0.000006 seconds threaded (4 threads) 0.000581 seconds processes (4 procs) 0.003906 seconds non_threaded (8 iters) 0.000009 seconds threaded (8 threads) 0.001148 seconds processes (8 procs) 0.008178 seconds From rdmurray at bitdance.com Tue Dec 9 15:27:42 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Tue, 9 Dec 2008 15:27:42 -0500 (EST) Subject: When (and why) to use del? In-Reply-To: References: Message-ID: On Tue, 9 Dec 2008 at 18:55, Duncan Booth wrote: > Albert Hopkins wrote: > >> def otherfunction(): >> try: >> # some stuff >> except SomeException, e: >> # more stuff >> del e >> return >> >> >> I think this looks ugly, but also does it not hurt performance by >> preempting the gc? My feeling is that this is a misuse of 'del'. Am I >> wrong? Is there any advantage of doing the above? >> > It is probably a complete waste of time, but there are situations where > code similar to this can be useful: > > def otherfunction(): > try: > # some stuff > except SomeException, e: > # more stuff > del e > raise > return > > The point of code like this is that when a function exits by throwing an > exception the traceback includes a reference to the stack frame and all the > local variables. In some situations that can result in large data > structures not being freed for a very long time (e.g. until another > exception is thrown that is handled at the same level). So, *in very > specialised situations* it may be important to delete particular names from > the local namespace. If I'm reading http://www.python.org/dev/peps/pep-3110/ right, Python 3.0 eliminates even this use case :) I have had occasions to use del, when I don't want the variable in the namespace anymore for some reason (for example, when I'm later going to be scanning the namespace for some reason). --RDM From manu3d at gmail.com Sun Dec 14 08:01:18 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Sun, 14 Dec 2008 05:01:18 -0800 (PST) Subject: Bidirectional Networking References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <98a6c3cd-181c-43c9-805b-fb0689c69544@a26g2000prf.googlegroups.com> <29283382-3e26-492a-8612-9352f32c1c01@r15g2000prd.googlegroups.com> Message-ID: <606a02c9-ae34-42c6-82b2-94582d22dab2@r15g2000prh.googlegroups.com> On Dec 14, 2:40?am, Brian Allen Vanderburg II wrote: > But what I think it means is that during the listen for an incoming > connection on the listening socket, if multiple connection attempts are > coming in at one time it can keep a backlog of up to 5 of these > connection attempts for that individual socket. Ah, Gotcha! Thank you, that makes sense! Manu From mensanator at aol.com Wed Dec 3 19:08:23 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 3 Dec 2008 16:08:23 -0800 (PST) Subject: "as" keyword woes References: <493701f0$0$194$e4fe514c@news.xs4all.nl> <01470229$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Dec 3, 4:38?pm, Steven D'Aprano wrote: > On Wed, 03 Dec 2008 22:02:24 +0000, Martin P. Hellwig wrote: > > Warren DeLano wrote: > >> A bottom line / pragmatic question... hopefully not a FAQ. > > >> Why was it necessary to make "as" a reserved keyword? > > > > Because it can be used at the import statement to let the imported thing > > be known under another name? > > Something like: > > > ?>>> import xml.etree.ElementTree as ET > > Martin, that doesn't answer the OP's question *at all*. Python 2.5 uses > "as" in that way, and it is not a keyword. > > >>> import math as MATHS > >>> MATHS > > >>> as = 45 > > :1: Warning: 'as' will become a reserved keyword in Python 2.6>>> as > > :1: Warning: 'as' will become a reserved keyword in Python 2.6 > 45 > > I'd guess that the change was to simplify the CPython parser. I have no > idea if it was a tiny change or a significant change, if it made a huge > difference to Python-dev or a little difference. Perhaps someone on the > dev team could comment. > > While I feel sympathy for the OP, I do have to ask: he's been using > Python 2.5 for, what, a couple of years now? How many times did he see > the depreciation warning, and almost certainly the pending depreciation > warning before that? Python-dev has been talking about making "as" a > keyword since at least Python 2.3. Why wait until after version 2.6 is > released before saying anything? When I brought this up a short while ago (because sympy crashed in Python 2.6) someone said that there was a bug in Python 2.5 that prevented the display of the deprecation message (when "as" appeared inside imported modules). So apparently, the sympy developers never saw a deprecation warning in all the years they were using 2.5. There was, however, no excuse for not testing it in 2.6. > > -- > Steven From Ron.Barak at lsi.com Tue Dec 16 03:00:21 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Tue, 16 Dec 2008 08:00:21 +0000 Subject: tutorial on parser In-Reply-To: References: Message-ID: <7F0503CD69378F49BE0DC30661C6CCF602494098@enbmail01.lsi.com> Hi John, You may want to read http://nedbatchelder.com/text/python-parsers.html Bye, Ron. -----Original Message----- From: John Fabiani [mailto:jfabiani at yolo.com] Sent: Tuesday, December 16, 2008 08:47 To: python-list at python.org Subject: tutorial on parser Hi, I'm attempting to learn how to convert MsSQl Transact-SQL to postgres pgsql. So far my readings have led me to finding a parser. I'm looking for a tutorial on how to get it done. I did find a commercial product but they want over $10,000 us. This way beyond my means. Therefore, I need to get it done either myself to find a open source project. Thanks in advance. John Fabiani From riklaunim at gmail.com Mon Dec 1 02:43:14 2008 From: riklaunim at gmail.com (riklaunim at gmail.com) Date: Sun, 30 Nov 2008 23:43:14 -0800 (PST) Subject: Cross platform desktop operations in Python Message-ID: Hi I'm looking for a cross platform (Linux/Win/Mac) solution of common desktop operations like: * Getting system icon theme (icons for files, folders etc.) * Determine mimetype (better than mimetypes using mapped extension to mime) Under Unix/Linux there are freedesktop.org standards and pyxdg that can do that, but it won't work for example on Windows. Are there solutions for this, or do I have to implement a backed for every system? From clp at rebertia.com Sun Dec 28 07:04:13 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 28 Dec 2008 04:04:13 -0800 Subject: What is site-packages? In-Reply-To: References: Message-ID: <47c890dc0812280404w233c2977sf1b75f33945b3ae3@mail.gmail.com> On Sun, Dec 28, 2008 at 3:40 AM, Hussein B wrote: > Hey, > What is /usr/lib/pythonx.y/site-packages folder and for what it is > used usually? I believe it's where third-party libraries are typically installed to. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From clp at rebertia.com Fri Dec 12 18:28:13 2008 From: clp at rebertia.com (Chris Rebert) Date: Fri, 12 Dec 2008 15:28:13 -0800 Subject: var or inout parm? In-Reply-To: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> Message-ID: <47c890dc0812121528s58638b4eha9a2c02e2cd45ee6@mail.gmail.com> On Fri, Dec 12, 2008 at 4:56 AM, sturlamolden wrote: > On Dec 12, 1:44 pm, "Chris Rebert" wrote: > >> Python begs to differ, as those two statements are both semantically >> identical in this case: > > That is because integers are immutable. When x += 1 is done on an int, > there will be a rebinding. But try the same on say, a numpy array, and > the result will be different: Yes, I know that. Did you not read the end of my email? Here it is again: """ If you were talking about lists rather than integers though, you'd be absolutely correct, as the += ends up being a method call to __iadd__ instead of a plain assignment. """ Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From google at mrabarnett.plus.com Fri Dec 5 14:36:16 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 05 Dec 2008 19:36:16 +0000 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: References: <5u8o06xbqf.ln2@joeserver.homelan.net> Message-ID: <493982B0.2050903@mrabarnett.plus.com> Joe Strout wrote: > On Dec 5, 2008, at 11:36 AM, Johannes Bauer wrote: > >>> I suspect that '?' after \n (\u0a00) is indicates not 'question-mark' >>> but 'uninterpretable as a utf16 character'. The traceback below >>> confirms that. It should be an end-of-file marker and should not be >>> passed to Python. I strongly suspect that whatever wrote the file >>> screwed up the (OS-specific) end-of-file marker. I have seen this >>> occasionally on Dos/Windows with ascii byte files, with the same symptom >>> of reading random garbage pass the end of the file. Or perhaps >>> end-of-file does not work right with utf16. >> >> So UTF-16 has an explicit EOF marker within the text? > > No, it does not. I don't know what Terry's thinking of there, but text > files do not have any EOF marker. They start at the beginning > (sometimes including a byte-order mark), and go till the end of the > file, period. > Text files _do_ sometimes have an EOF marker, such as character 0x1A. It can occur in text files in Windows. >> I cannot find one in original file, only some kind of starting >> sequence I suppose >> (0xfeff). > > That's your byte-order mark (BOM). > >> The last characters of the file are 0x00 0x0d 0x00 0x0a, >> simple \r\n line ending. > > Sounds like a perfectly normal file to me. > > It's hard to imagine, but it looks to me like you've found a bug. > From sjmachin at lexicon.net Wed Dec 31 08:55:57 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 31 Dec 2008 05:55:57 -0800 (PST) Subject: TypeError: list indices must be integers References: <2e5a61c0-fa99-4170-81ca-eb3a10859400@k36g2000pri.googlegroups.com> <98f638c1-d191-4f95-9668-01bc3c47526c@i20g2000prf.googlegroups.com> Message-ID: <00f88aeb-5651-424a-b324-04695a0d397a@w39g2000prb.googlegroups.com> On Dec 31 2008, 3:26?pm, dubux wrote: > thanks for help everyone. it turned out the function itself worked > fine.. it was the way i was calling it that was messing everything up. > i ended up re-doing the whole thing as follows, and it now works > perfectly. > > def news(x,y): > ? ? ? ? news_file = '/home/scam/Desktop/www/info/news' > ? ? ? ? news = open(news_file, 'r') > ? ? ? ? news_list = news.readlines() > ? ? ? ? news.close() > ? ? ? ? if x == 'date': > ? ? ? ? ? ? ? ? mylist = map(lambda i: news_list[i], filter(lambda i: i%2 == 0, range > (len(news_list)))) > ? ? ? ? ? ? ? ? date = mylist[y].replace("\n","") > ? ? ? ? ? ? ? ? return '

    %s

    \n\n' % (date) > ? ? ? ? if x == 'news': > ? ? ? ? ? ? ? ? mylist = map(lambda i: news_list[i], filter(lambda i: i%2 == 1, range > (len(news_list)))) > ? ? ? ? ? ? ? ? news = mylist[y].replace("\n","") > ? ? ? ? ? ? ? ? return '

    %s

    \n
    \n' % (news) > ? ? ? ? else: > ? ? ? ? ? ? ? ? return news_list > > news_parse, count, news_list = " ", 0, news('list','list') > newss = map(lambda i: news_list[i], filter(lambda i: i%2 == 1, range > (len(news_list)))) > while count < len(newss): > ? ? ? ? get_date = news('date', count) > ? ? ? ? get_news = news('news', count) > ? ? ? ? news_parse = '%s %s %s' % (news_parse, get_date, get_news) > ? ? ? ? count = count + 1 Unless I'm sorely mistaken, the whole of the above can be replaced by something like (untested): news_file = '/home/scam/Desktop/www/info/news' news = open(news_file, 'r') accum = [] for lineno, line in enumerate(news): accum.append('

    %s

    \n%s\n' % (line.strip(), ('', '
    ')[lineno % 1])) news_parse = ' '.join(accum) news.close() count = (lineno + 1) // 2 # if indeed count is needed with the virtues of brevity and speed ... if there are N (date, news) items, your code reads the file 2*N+1 times!!! How big is N? From nick at craig-wood.com Mon Dec 1 06:30:44 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 01 Dec 2008 05:30:44 -0600 Subject: distinct fcntl flags for stdin and stdout References: Message-ID: mbuna wrote: > Hello, > when I set non blocking flag with fcntl on sys.stdin, then sys.stdout > turns into non blocking mode too. Is it normal behaviour? How can I > turn stdin into non blocking mode but not stdout? Thanks. > > This is a quick program that shows the (my?) problem: > > import fcntl > import os > import sys > > print "STDIN", sys.stdin, "fd=%d" % sys.stdin.fileno() > print "STDOUT", sys.stdout, "fd=%d" % sys.stdout.fileno() > print "os.O_NDELAY=%04x" % os.O_NDELAY > def state(): > flag = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL) > print "stdin: flag=%04x" % flag > flag = fcntl.fcntl(sys.stdout.fileno(), fcntl.F_GETFL) > print "stdout: flag=%04x" % flag > state() > print "setting non blocking on stdin..." > flag = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL) > fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, flag | os.O_NDELAY) > state() > print "removing non blocking on stdin..." > flag = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL) > fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, flag & ~os.O_NDELAY) > state() > > > RESULT > STDIN ', mode 'r' at 0x2aaaaaacd120> fd=0 > STDOUT ', mode 'w' at 0x2aaaaaacd198> fd=1 > os.O_NDELAY=0800 > stdin: flag=8002 > stdout: flag=8002 > setting non blocking on stdin... > stdin: flag=8802 > stdout: flag=8802 > removing non blocking on stdin... > stdin: flag=8002 > stdout: flag=8002 If you try this with output redirected to a file, you get this (under linux) STDIN ', mode 'r' at 0xb7d03020> fd=0 STDOUT ', mode 'w' at 0xb7d03068> fd=1 os.O_NDELAY=0800 stdin: flag=0002 stdout: flag=8001 setting non blocking on stdin... stdin: flag=0802 stdout: flag=8001 removing non blocking on stdin... stdin: flag=0002 stdout: flag=8001 So I suspect your result is because stdin and stdout refer to the same file (eg /dev/tty0 or /dev/pts/25). No idea whether this is correct behaviour or not though! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From geekmail at usenot.de Fri Dec 5 10:09:30 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Fri, 5 Dec 2008 16:09:30 +0100 Subject: "as" keyword woes References: <7dudnSS7uIn_KarUnZ2dnUVZ_tTinZ2d@earthlink.com> <0147e4df$0$20670$c3e8da3@news.astraweb.com> <01485198$0$20670$c3e8da3@news.astraweb.com> Message-ID: <20081205160930.6e297c00@usenot.de> On 04 Dec 2008 22:29:41 GMT Steven D'Aprano wrote: > Thank goodness we don't have to program in verbose, explicit English! Then you'll HATE Inform 7: http://en.wikipedia.org/wiki/Inform_7#Example_game_2 :) /W -- My real email address is constructed by swapping the domain with the recipient (local part). From zac256 at gmail.com Tue Dec 2 20:19:41 2008 From: zac256 at gmail.com (Zac Burns) Date: Tue, 2 Dec 2008 17:19:41 -0800 Subject: Reverse zip() ? In-Reply-To: <333edbe80812021647i4621271p7f87dff8d0926951@mail.gmail.com> References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> <333edbe80812021647i4621271p7f87dff8d0926951@mail.gmail.com> Message-ID: <333edbe80812021719x6bb03418pe3041fbdd387337f@mail.gmail.com> More succinct failure: keys, values = zip(*{}.iteritems()) -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer (Digital Overlord) Zindagi Games On Tue, Dec 2, 2008 at 4:47 PM, Zac Burns wrote: > There is a problem with this however, which prompted me to actually > write an unzip function. > > One might expect to be able to do something like so (pseudocode)... > > def filesAndAttributes(): > files = walk() > attributes = [attr(f) for f in files] > return zip(files, attributes) > > files, attributes = zip(*filesAndAttributes()) > > The corner case is when dealing with empty lists and there aren't > enough items to unpack. > > The unzip function therefore has an elementsForEmpty keyword that > handles this case. Perhaps something like this could be added to zip? > I have not (yet) dealt with the PEP process, so I'm not sure where > that starts. Perhaps a discussion could start here. > > -- > Zachary Burns > (407)590-4814 > Aim - Zac256FL > Production Engineer (Digital Overlord) > Zindagi Games > > > > On Tue, Dec 2, 2008 at 4:14 PM, John Machin wrote: >> On Dec 3, 7:12 am, Stefan Behnel wrote: >>> Andreas Waldenburger wrote: >>> > we all know about the zip builtin that combines several iterables into >>> > a list of tuples. >>> >>> > I often find myself doing the reverse, splitting a list of tuples into >>> > several lists, each corresponding to a certain element of each tuple >>> > (e.g. matplotlib/pyplot needs those, rather than lists of points). >>> >>> > This is of course trivial to do via iteration or listcomps, BUT, I was >>> > wondering if there is a function I don't know about that does this >>> > nicely? >>> >>> I think you're asking about zip(): >>> >>> >>> l=[1,2,3] >>> >>> zip(l,l) >>> [(1, 1), (2, 2), (3, 3)] >>> >>> zip(*zip(l,l)) >>> [(1, 2, 3), (1, 2, 3)] >>> >> >> Here's a version that makes it slightly easier to comprehend: >> >> Q: I know how to zip sequences together: >> | >>> a = (1, 2, 3) >> | >>> b = (4, 5, 6) >> | >>> z = zip(a, b) >> | >>> z >> | [(1, 4), (2, 5), (3, 6)] >> but how do I reverse the process? >> >> A: Use zip()! >> | >>> a2, b2 = zip(*z) >> | >>> a2 >> | (1, 2, 3) >> | >>> b2 >> | (4, 5, 6) >> >> Cheers, >> John >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > From mail at timgolden.me.uk Fri Dec 5 16:05:55 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 05 Dec 2008 21:05:55 +0000 Subject: Can I load a python program at the interactive >>> prompt? In-Reply-To: <269e5d69-02b7-409b-ad53-b7702b6ec13a@i24g2000prf.googlegroups.com> References: <269e5d69-02b7-409b-ad53-b7702b6ec13a@i24g2000prf.googlegroups.com> Message-ID: <493997B3.20707@timgolden.me.uk> walterbyrd wrote: > I am running cygwin on xp. .... and I just noticed this vital bit. So not sure how much of my other post applies. Sorry. Maybe it'll help anyway. :) TJG From rt8396 at gmail.com Wed Dec 17 12:00:01 2008 From: rt8396 at gmail.com (r) Date: Wed, 17 Dec 2008 09:00:01 -0800 (PST) Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> Message-ID: <175fa5d5-f345-47b8-a686-e0e36e1b99e9@q37g2000vbn.googlegroups.com> I think there is a simpler answer to all this(not to take away from the other ones here though which are all great). When writing procedural code how would you like it if vars inside functions were automatically global. Your code with be blowing chunks in no time. Thats the reason for global declarations and instance.var :) From mickey at localhost.vanille.zapto.org Thu Dec 11 17:34:21 2008 From: mickey at localhost.vanille.zapto.org (Michael 'Mickey' Lauer) Date: 11 Dec 2008 22:34:21 GMT Subject: using distutils to cross-compile extensions? References: Message-ID: <6qdircFbgacnU1@mid.dfncis.de> Michael George wrote: > I have an extension module that I've built using distutils. I wonder if > it's possible to use distutils to cross-compile it for windows on my > linux box, and whether the pain involved is great. Can anyone point me > in the right direction? Take a look at OpenEmbedded; I have patches against distutils that make it crosscompile most packages. :M: From geekmail at usenot.de Sat Dec 6 05:15:54 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sat, 6 Dec 2008 11:15:54 +0100 Subject: Don't you just love writing this sort of thing :) References: <0148b086$0$20670$c3e8da3@news.astraweb.com> <01490b5f$0$20670$c3e8da3@news.astraweb.com> Message-ID: <20081206111554.0bb35558@usenot.de> On Sat, 06 Dec 2008 20:28:17 +1300 Lawrence D'Oliveiro wrote: > Does that make any sense to you, or should I start drawing simple > diagrams? People, please! Is some civility too much to ask? /W -- My real email address is constructed by swapping the domain with the recipient (local part). From mdgeorge at cs.cornell.edu Thu Dec 4 17:42:03 2008 From: mdgeorge at cs.cornell.edu (Michael George) Date: Thu, 4 Dec 2008 17:42:03 -0500 Subject: using distutils to cross-compile extensions? Message-ID: <49385CBB.7060207@cs.cornell.edu> Hi, Please CC me in replying as I am off list. I have an extension module that I've built using distutils. I wonder if it's possible to use distutils to cross-compile it for windows on my linux box, and whether the pain involved is great. Can anyone point me in the right direction? Thanks, --Mike From steve at REMOVE-THIS-cybersource.com.au Sat Dec 13 05:03:35 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Dec 2008 10:03:35 GMT Subject: Need help improving number guessing game References: Message-ID: <01537ffa$0$6988$c3e8da3@news.astraweb.com> On Sat, 13 Dec 2008 00:57:12 -0800, feba wrote: > I have one major problem with this; the 'replay' selection. It quits if > you put in 0, as it should, and continues if you put in any other > number. However, if you just press enter, it exits with an error. it > also looks really ugly, and I'm sure there has to be plenty of better > ways to do it. Start by refactoring your code into small, easy to understand functions. For example, You mix in the same piece of code the logic for: - error handling; - starting a new game; - quiting (although you use a function for this, well done); - and game logic and then you have to repeat it all again, almost word-for-word, for one player mode and two player mode. Start with a high-level approach. The guessing game has the following structure: while you want to play a game: play a game ask play again? which in Python might look like this: playing = True while playing: play_one_game() playing = play_again() def play_again(): # For Python 3, change "raw_input" to "input". response = raw_input("Would you like to play again? y/n ") return response.strip().lower() == "y" This function accepts *only* Y or y to play another game. Later, after you've got the game working, you can come back to this and modify it so that it accepts Yes or just enter on it's own. Make it work as simply as possible first, then come back and make it more complicated later. Now do the same thing for playing one game. A single game in two player mode looks something like this: pick a target number start with one person as the guesser until the target is guessed: guess a number let the other person be the guesser which in Python might look like this: def play_one_game(): target = pick_target() # you need to write this function guessed = False player = "Player One" while not guessed: guess = guess_number(player) # you need to write this too if guess == target: guessed = True else: player = swap_player(player) # player one <=> player two # When we exit the loop, player is the person who guessed correctly. if player == "Player One": p1score += 1 else: p2score += 1 Best of all, you can change from two player mode to one player mode just by skipping the line "player = swap_player(player)". The rest of the code remains exactly the same, and you don't need to repeat everything. Have a play around with this approach, and then come back to us if you need more hints. -- Steven From bdesth.quelquechose at free.quelquepart.fr Mon Dec 22 13:36:14 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 22 Dec 2008 19:36:14 +0100 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> Message-ID: <494febd1$0$20851$426a74cc@news.free.fr> walterbyrd a ?crit : > On Dec 21, 12:28 pm, Bruno Desthuilliers > wrote: >> Strange enough, >> no one seems to complain about PHP or Ruby's performances... > > A few years back, there was a certain amount of chest thumping, when > python/django easily beat ror in a benchmark test. I don't remember it, and honestly, I just don't give a damn. > Now that ruby is > faster, "faster" than what ? Than Python ? or than it's previous version ? > I guess speed is no big issue. Please use your google-fu (if you have any). As far as I'm concerned, my position didn't change these 7+ past years: Python is (and has always been) fast enough for most of what I use it for (and when it isn't, neither PHP nor Ruby are going to be solution anyway). Now improvements are always welcomes, and if you compare 1.5.2 with 2.5.1, you'll find out that the core developpers did improve Python's perfs. Now do you have any serious argument, or are you just trolling ? > By the same reasoning, python advocates used to sneer at php because > php constantly broke backward compatibility. Now that python does it, > breaking backward compatibility is no big deal. There's a lot 1.5.2 days code still running *unmodified* on 2.6.x. You'll have hard time finding (non-trivial, and even then) PHP3 code running unmodified on PHP5. > I guess unicode > support was not that important, until python caught up to perl. > > I guess, the way it works is: you first assume that python is > superior, then you figure out why. Whoever said Python was "superior" (except your good friend 'r') ? As far as I'm concerned, I don't think Python is "superior" (OMG), I think it's a good language that happens to fit my brain *and* solve more than 80% of my programmer's needs. If you're not happy with Python's perfs, please contribute, you are welcome. From nmiyasato at gmail.com Sat Dec 20 19:26:25 2008 From: nmiyasato at gmail.com (miya) Date: Sat, 20 Dec 2008 16:26:25 -0800 (PST) Subject: best way to code References: Message-ID: <041d4bd9-c847-4130-8188-1817908f83dc@r24g2000vbp.googlegroups.com> On Dec 19, 2:35?pm, Peter Otten <__pete... at web.de> wrote: > eric wrote: > > hi, > > > I need to find a "good" design pattern to instanciate, and add > > specific code all in one. Let me explain it : > > > I need to define "some" code, better be in a class, something like > > > class LinkA(object): > > ? ? def mystuff(self): > > ? ? ? ? ? > > > class LinkB(object): > > ? ? def mystuff(self): > > ? ? ? ? ? > > > AND I need an instance of this class > > { "stuff A": LinkA() > > ? "stuff B": LinkB() > > } > > > This kind of code "would" be fine, I mean, the result effect in memory > > is fine for me. > > But I don't like the way I have to > > 1/ give a useless name to LinkA, linkB (there can be hundreds of names > > like that) > > 2/ I have to write it down two times (and that's one time too much) > > > any ideas ? > > > something like > > [ > > new object(): > > ? ? def mystuff(self): > > ? ? ? ? > > , > > new object(): > > ? ? def mystuff(self): > > ? ? ? ? > > ] > > > would be really perfect (but I know it does not work, or at least, I > > don't know how to make it work) > > > In fact, I would like to define a class, and an instance in a single > > statement > >>> class Register: > > ... ? ? def __init__(self): > ... ? ? ? ? ? ? self.items = [] > ... ? ? def __call__(self, method): > ... ? ? ? ? ? ? class Link(object): > ... ? ? ? ? ? ? ? ? ? ? mystuff = method > ... ? ? ? ? ? ? self.items.append(Link()) > ...>>> register = Register() > >>> @register > > ... def mystuff(self): print "first" > ...>>> @register > > ... def mystuff(self): print "second" > ...>>> for item in register.items: > > ... ? ? item.mystuff() > ... > first > second > > Peter Wow, loved this solution. Never thought about using decorators to solve this kinda problems. nice - Nicol?s Miyasato (miya) http://myPythonNotes.wordpress.com http://nmiyasato.blogspot.com From luismgz at gmail.com Mon Dec 15 08:15:30 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Mon, 15 Dec 2008 05:15:30 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> Message-ID: <355f1cfe-6abb-4d2c-8bf4-3aa62e713c1f@w34g2000yqm.googlegroups.com> On Dec 15, 1:38?am, cm_gui wrote: > hahaha, do you know how much money they are spending on hardware to > make > youtube.com fast??? > > > By the way... I know of a very slow Python site called YouTube.com. In > > fact, it is so slow that nobody ever uses it. > > Buddy, just stop whining and go with c++ if it makes you happy. By the way, what's the blazingly fast application you need to write so desperately? What kind of performance problem have you find in python that makes you so unhappy? What are you going to do with all the extra speed provided by c++ (a Hello World! ?)... From n.kottiyath at gmail.com Thu Dec 4 00:18:19 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Wed, 3 Dec 2008 21:18:19 -0800 (PST) Subject: Good introductory book? References: Message-ID: <56616d73-312c-44e5-a484-5fb3e0054613@x38g2000yqj.googlegroups.com> On Dec 3, 7:44?pm, "Ken D'Ambrosio" wrote: > Hi, all. ?I'm getting ready to do some projects in Python, and I've cut my > teeth a little bit, but I've found the "Learning|Programming Python" books > from O'Reilly to be more-or-less useless (to my surprise -- I'm usually an > O'Reilly fan). ?I really, really like "Python Essential Reference", but > it's -- well, more of a reference than an intro. ?So, an introductory text > that actually assumes some previous programming experience (as opposed to > "Learning Python" which must be the most slowly-paced programming book > ever) would be terrific. > > Thanks for your suggestions! > > -Ken Dive into python is a very good one. It is free too. http://diveintopython.org/ Try it out. If you want more of examples of how everything is done, then Python Cookbook is another one. You can get many recipes at http://code.activestate.com/recipes/langs/python/ too - the book is just selected recipes from this site. Regards K From pavlovevidence at gmail.com Thu Dec 4 16:08:46 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 4 Dec 2008 13:08:46 -0800 (PST) Subject: "as" keyword woes References: <777c7313-267f-4dc2-b6fd-fad0c9714f41@l42g2000yqe.googlegroups.com> Message-ID: On Dec 4, 2:42?pm, Albert Hopkins wrote: > It's been a while so I can't remember, but it seems like "yield" was > dropped in to python relatively quickly in 2.2. ?Was there a similar > outrage when "yield" became a keyword? This is just one guy complaining. Yes, I'd imagine when "yield" and "with" were made into keywords there was probably someone, somewhere who complained about that, too. I doubt there will much outrage over "as". It has been in the works for eight years and six releases, after all. Anyone who was paying attention wouldn't have been using "as" as an identifier. Among those who weren't paying attention, anyone smart wouldn't have been using "as" as an identifier because A) it is used as a syntactic element, and even if it's not a keyword it's poor style to use it also as an identifier, and B) you had to suspect sooner or later they would make it into a real keyword. Among those who were using "as" as an identifier, the vast majority will simply do an interactive search-and-replace to fix it. People like Warren here who have distributed codebases they can't easily fix up, and who were neither smart nor informed enough to avoid using "as", are a pretty tiny minority, I would guess. Carl Banks From pythonnutter at gmail.com Sat Dec 6 20:54:49 2008 From: pythonnutter at gmail.com (Python Nutter) Date: Sun, 7 Dec 2008 12:54:49 +1100 Subject: Learning Python now coming from Perl In-Reply-To: References: <014a96e0$0$20670$c3e8da3@news.astraweb.com> Message-ID: > In article <014a96e0$0$20670$c3e8da3 at news.astraweb.com>, > Steven D'Aprano wrote: > > Well, as an old-time unix hacker (who learned REs long before Perl > existed), my question to you would be, "Is there any problem which > *shouldn't* be solved with an RE?" :-) > > One of the reasons REs don't get used in Python as much as in Perl is > because strings have useful methods like startswith(), endswith(), and > split(), and also the "in" operator. These combine to give you easy ways > to do many things you might otherwise do with REs. I agree, I'm going through the new book Python for Unix and Linux Administration now and although in general I like what they say, they take you through the built in string functions and then introduce REs and end the chapter leaving the reader with the impression that REs are the better solution and I only agree with the case of the problem/program they presented. However I used the built ins more effectively using the indexes returned within the string and I've built plenty of scripts that did not need to move to REs to perform the text/file processing that I did. This intermediate use of string built-in functions was missing between the first string-function and RE versions of code and imho it is not letting the readers see that string-functions are even more powerful than the reader is lead to believe and that REs are pushed more towards edge cases than the impression the reader seems to be left with which is to use REs more. At least if you push REs inform the readers where to get the a RE GUI builder written in Python so they can build and *test* the complex and unwieldy REs to perform anything beyond the basic pattern searches. Cheers, PN From max at alcyone.com Mon Dec 29 01:56:27 2008 From: max at alcyone.com (Erik Max Francis) Date: Sun, 28 Dec 2008 22:56:27 -0800 Subject: why cannot assign to function call In-Reply-To: References: Message-ID: scsoce wrote: > I have a function return a reference, and want to assign to the > reference, simply like this: > >>def f(a) > return a > b = 0 > * f( b ) = 1* > but the last line will be refused as "can't assign to function call". > In my thought , the assignment is very nature, but why the interpreter > refused to do that ? Because, as in most languages, it's not even clear what you might mean by this syntax. It doesn't have any meaning; assignments are made to variables, not the results of function calls. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Only love is worth the risk -- Oleta Adams From tgrav at mac.com Mon Dec 22 12:59:37 2008 From: tgrav at mac.com (Tommy Grav) Date: Mon, 22 Dec 2008 12:59:37 -0500 Subject: Python's popularity In-Reply-To: References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: On Dec 22, 2008, at 12:48 PM, walterbyrd wrote: >> Now since Python *is not* the only language on it's block, we have to >> compete with our main nemesis(Ruby) for survival > > I think both python and ruby will "survive." I think python is also > competing with perl in the sysadmin space - although I see perl as > being much more popular there. Python is making great headway in the physical sciences. Especially in astronomy Python has become a real player as not only a tool for quick and dirty calculations, but more serious number crunching using the great numpy and scipy libraries. With Cython, I, think it will even start taking over some of the speed critical niche from C and Fortran. Cheers Tommy From roy at panix.com Mon Dec 8 23:08:04 2008 From: roy at panix.com (Roy Smith) Date: Mon, 8 Dec 2008 20:08:04 -0800 (PST) Subject: How to initialize a class variable once Message-ID: I've got a class with a class variable: class Foo: _map = {} How do I make sure this only gets initialized the *first* time the module containing the class is imported? What appears to be happening as it stands is each time the module gets imported, Foo._map get re- initialized. From clp at rebertia.com Mon Dec 8 03:57:44 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 8 Dec 2008 00:57:44 -0800 Subject: var or inout parm? In-Reply-To: <493cda2a$0$17080$426a34cc@news.free.fr> References: <493cda2a$0$17080$426a34cc@news.free.fr> Message-ID: <47c890dc0812080057r6d117bbcic377cb96de52d973@mail.gmail.com> On Mon, Dec 8, 2008 at 12:26 AM, Bruno Desthuilliers wrote: > Colin J. Williams a ?crit : >> >> mh at pixar.com wrote: >>> >>> How can I make a "var" parm, where the called function can modify >>> the value of the parameter in the caller? >>> >>> def f(x): >>> x = x + 1 >>> >>> n = 1 >>> f(n) >>> # n should now be 2 >>> >>> Many TIA!! >>> Mark >>> >>> >> >> Why not run it and see? >> >> Your function returns None. >> >> The function in effect takes a copy of n. > > Nope, it takes the object bound to global name 'n'. See Also: the earlier heated debate thread over what evaluation strategy Python uses (Survey says!: call-by-object). Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > -- > http://mail.python.org/mailman/listinfo/python-list > From benjamin.kaplan at case.edu Wed Dec 10 14:57:23 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 10 Dec 2008 14:57:23 -0500 Subject: "as" keyword woes In-Reply-To: References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> <493FD8F6.3050803@mrabarnett.plus.com> Message-ID: On Wed, Dec 10, 2008 at 12:22 PM, Patrick Mullen wrote: > On Wed, Dec 10, 2008 at 6:57 AM, MRAB wrote: > > Aaron Brady wrote: > >> > >> On Dec 9, 12:40 pm, MRAB wrote: > >>> > >>> Aaron Brady wrote: > >>>> > >>>> On Dec 9, 8:28 am, MRAB wrote: > >>>> snip > >>>>> > >>>>> In some languages (I think Delphi is one of them - it's been a > while!) > >>>>> some words which would normally be identifiers have a special meaning > >>>>> in > >>>>> certain contexts, but the syntax precludes any ambiguity, and not in > a > >>>>> difficult way. "as" in Python was one of those. > >>>>> I certainly wouldn't want something like PL/I, where "IF", "THEN" and > >>>>> "ELSE" could be identifiers, so you could have code like: > >>>>> IF IF = THEN THEN > >>>>> THEN = ELSE; > >>>>> ELSE > >>>>> ELSE = IF; > >>>>> Seehttp://en.wikipedia.org/wiki/PL/I_(programming_language) > . > >>>> > >>>> snip > >>>> That is, 'certainly' doesn't change the meaning of your statement > >>>> any. You wouldn't want it, but King George III didn't want the > >>>> American Revolution. > >>> > >>> It's called emphasis. > >> > >> I just take you to have meant, then, +1 on excluding keywords from > >> identifiers. You said it the long way though, so I thought I missed > >> something deeper, that didn't come across. > >> > > IIRC, most computer languages have an LL(1) grammar, which means that > when > > they are parsed you need to look at only the next word. If you're about > to > > parse a statement and the next word is "IF" then you know it's an > > IF-statement, if it's an identifier then it's either a call or an > assignment > > statement (OK, you don't know exactly what kind of statement it is at > that > > point, but it works out just fine!). > > > > In the example from PL/I, "IF" could be the start of an IF-statement "IF > > THEN" or an assignment statement "IF = ". It's a > bit > > more tricky for the parser as well as the programmer. > > > > Life is easier if words having special meanings are reserved. > > > > However, that doesn't mean that all special words /must/ be reserved > > (pragmatism beats purity). Sometimes the syntax makes it clear and > > unambiguous, so you can get away with not making it a reserved word. The > > word "as" in Python doesn't need to be reserved because the syntax > precludes > > ambiguity, but it's the only such word in the language, so it's just > tidier > > to make it reserved too. > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > I don't have a huge stake in this, but I wouldn't mind a change to > allow anything proceeding a "." or preceeding a "(" to not be > identified as a keyword. It is obvious to me a s a human reader that > something.if is quite a bit different than just a bare if. And as far > as parsing technology goes, isn't it supposed to go for the biggest > match first? I would not be for allowing bare keywords to be used in > the situations described above, but since we are so used to being able > to being able to have say, myclass.dir() or myclass.len() without them > overwriting the builtin functions, it makes sense to me to be able to > define a myclass.as() or myclass.with() without overwriting the > keywords. Though I know the semantics behind these two things are > very different, the rules I go through when reading the code are very > similar. The parser change might be a hassle, and it might not be > worth it at all of course, but from a conceptual point of view it is > simple. I mean, even now you can do class.__dict__["as"]. > so what happens here? if(some_condition()) : do_something(a) Yes, I know you don't need the parenthesis there in Python, but you still can use it. > I guess I'm -1 for full PL/1 craziness, but +1 for qualified keyword usage. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From n.kottiyath at gmail.com Sun Dec 21 13:27:57 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Sun, 21 Dec 2008 10:27:57 -0800 (PST) Subject: Twisted for non-networking applications Message-ID: <82e49b84-43c9-452f-a139-c77378c12908@a12g2000pro.googlegroups.com> Hi all, Is it a good idea to use Twisted inside my application, even though it has no networking part in it? Basically, my application needs lots of parallel processing - but I am rather averse to using threads - due to myraid issues it can cause. So, I was hoping to use a reactor pattern to avoid the threads. I am using twisted in another part of the application for networking, so I was hoping to use the same for the non-networking part for reusing the reactor pattern. If somebody can help me on this, it would be very helpful. Regards K From gagsl-py2 at yahoo.com.ar Wed Dec 10 07:46:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 10 Dec 2008 10:46:53 -0200 Subject: forcing future re-import from with an imported module References: <533670ae-6d9d-4b10-9156-e41b31b678c7@g17g2000prg.googlegroups.com> Message-ID: En Tue, 09 Dec 2008 23:27:10 -0200, _wolf escribi?: > how can i say, approximately, "re-import the present module when it is > imported the next time, don?t use the cache" in a simple way? i do not > want to "reload" the module, that doesn?t help. I'd say you're using modules the wrong way then. The code inside a module is executed *once*, and that's by design. If you want to execute something more than once, put that code inside a function, and call it as many times as you want. -- Gabriel Genellina From newsgroups at debain.org Sun Dec 28 14:29:35 2008 From: newsgroups at debain.org (Samuel) Date: Sun, 28 Dec 2008 19:29:35 +0000 (UTC) Subject: Apache/mod_python: Registering a request handler dynamically Message-ID: Hi, Is there a way to dynamically overwrite the request handler from within mod_python scripts? Something along those lines: --------------- from mod_python import apache def myhandler(request): request.content_type = 'text/plain' request.write('Hello world') apache.set_default_handler(myhandler) --------------- I specifically want to avoid changing the Apache directive, as this code is supposed to function in a place where the user has no permission to override the Apache directive. The reason is that I am trying to hide the difference between different environments (such as mod_python or CGI) from the developer, such that the following is possible: --------------- #!/usr/bin/python import os, os.path os.chdir(os.path.dirname(__file__)) from PleaseHideMyEnvironment import RequestHandler def index(request): request.write('Hello World') RequestHandler(index) --------------- So at the time at which RequestHandler() is created, I need a way to make sure that mod_python calls to the RequestHandler instead of the normal handler, whenever a new request is made. Any idea? -Samuel From lists at cheimes.de Mon Dec 22 06:18:27 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 22 Dec 2008 12:18:27 +0100 Subject: no sign() function ? In-Reply-To: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> Message-ID: Pierre-Alain Dorange schrieb: > I don't find any sign(x) function in the math library (return the sign > of the value). > I've read that math module is a wrapper to C math lib and that C math > lib has not sign(), so... Starting with Python 2.6 the math and cmath modules have a copysign function. > I've implement my own sign function of course (it's easy) but a standard > one in math would be better and could be faster. Sure? :) Are you aware that the IEEE 754 standard makes a difference between the floats +0.0 and -0.0? from math import atan2 def sign(x): if x > 0 or (x == 0 and atan2(x, -1.) > 0.): return 1 else: return -1 From xahlee at gmail.com Wed Dec 3 19:32:57 2008 From: xahlee at gmail.com (Xah Lee) Date: Wed, 3 Dec 2008 16:32:57 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: On Dec 3, 4:22?pm, "Thomas M. Hermann" wrote: > On Dec 3, 5:26?pm, Xah Lee wrote: > > > > > Agreed. My paypal address is ?xah @@@ xahlee.org?. (replace the triple > > @ to single one.) Once you paid thru paypal, you can post receit here > > if you want to, or i'll surely acknowledge it here. > > > Here's what i will do: > > > I will give a version of Mathematica code that has the same behavior > > as his. And i will give timing result. The code will run in > > Mathematica version 4. (sorry, but that's what i have) As i > > understand, Jon is running Mathematica 6. However, i don't see > > anything that'd require Mathematica 6. If my code is not faster or in > > other ways not satisfactory (by your judgement), or it turns out > > Mathematica 6 is necessary, or any problem that might occure, i offer > > money back guarantee. > > > ? Xah > > ?http://xahlee.org/ > > > ? > > Alright, I've sent $20. The only reason I would request a refund is if > you don't do anything. As long as you improve the code as you've > described and post the results, I'll be satisfied. If the improvements > you've described don't result in better performance, that's OK. > > Good luck, > > Tom Got the payment. Thanks. I'll reply back with code tonight or tomorrow. Wee! Xah ? http://xahlee.org/ ? From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 20:54:35 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2008 01:54:35 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <015c47ad$0$20656$c3e8da3@news.astraweb.com> On Fri, 19 Dec 2008 10:25:30 -0700, Michael Torrie wrote: > So funny that now that Python 3.0 is actually released we have people > acting all surprised like they've never seen any of the new features in > Python 3.0 coming. However these features have been discussed for > years! And debated! Debated by who? The entire Python-using community? Every single Python programmer? Or just the small proportion of Python developers who are also core developers? Are you *really* surprised that some people had never heard of the changes being debated until it was too late? > Personally the new string formatter is sorely needed in Python. And > they way it has been implemented is a thing of beauty. Basically the > burden of formatting strings has been moved from the print > statement/function to the objects themselves. That's clearly not true. The print statement was not involved in formatting strings in the past. From Python 2.5: >>> s = "%s and %s" % ("spam", "eggs") >>> list(s) ['s', 'p', 'a', 'm', ' ', 'a', 'n', 'd', ' ', 'e', 'g', 'g', 's'] No print required until well after the string substitution was completed. > Furthermore, the new {} > notation allows many, many more options for formatting to be used. Want > to display a floating point number with $#.## notation, and ($#.##) for > negative? It's all now possible. Couldn't be done before. Of course it could be. You just needed to write your own formatting engine. What you mean is that it couldn't be done with % formatting and nothing else. > In short, this is a huge improvement, and backwards compatibility is > preserved for the 2.x style for those that wish it. There clearly is a need for a more heavyweight formatting solution than % and string.Template. There are things that can't be done easily with % alone, and format() will make them much simpler. I have no objection to the addition of the format() method (although I wonder whether it might have been better as a function). -- Steven From ianare at gmail.com Tue Dec 16 12:01:17 2008 From: ianare at gmail.com (=?ISO-8859-1?B?aWFuYXLp?=) Date: Tue, 16 Dec 2008 09:01:17 -0800 (PST) Subject: ethical questions about global variables References: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> Message-ID: <148d911b-5c43-48a1-baea-5a46c04cacfd@o4g2000pra.googlegroups.com> For anything more complicated than a simple script, I find it easier to use some sort of config object. This could be a simple dictionnary type class, where the values can be set/retrieved by the other classes directly, or a more elaborate class including functions to set/ retrieve the variables. This way setting/retrieving can be 'smart' -- possibly looking at other variables, program states, thread count, whatever, for the requested config option. It also allows for a lot of expansion down the line if need be, rather than dealing with all sorts of global variables floating around - which gets annoying pretty quickly. On Dec 15, 9:45?pm, "Giampaolo Rodola'" wrote: > Hi, > in a module of mine (ftpserver.py) I'd want to add a (boolean) global > variable named "use_gmt_times" to decide whether the server has to > return times in GMT or localtime but I'm not sure if it is a good idea > because of the "ethical" doubts I'm gonna write below. > > In first place I've never liked global variables too much and always > preferred per-class-instance variables instead. > The problem in my case is that I have to use such variable in two > separated classes: FTPHandler and VirtualFileSystem. Also, I want that > for no reason one class uses times in GMT and the other one local > times. > > Another doubt is the naming convention. PEP-8 states that global > variables should use the lower_case_naming_convention but I've seen a > lot of library module using the UPPER_CASE_NAMING_CONVENTION. What am > I supposed to do about it? > > Thanks in advance for any comment. > > --- Giampaolohttp://code.google.com/p/pyftpdlib/ From kay.schluehr at gmx.net Wed Dec 3 14:04:44 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Wed, 3 Dec 2008 11:04:44 -0800 (PST) Subject: Debugging a Python Program that Hangs References: Message-ID: On 2 Dez., 17:19, Kevin D. Smith wrote: > I have a fairly large python program that, when a certain combination > of options is used, hangs. ?I have no idea where it is hanging, so > simply putting in print statements to locate the spot would be quite > difficult. ?Unfortunately, ctrl-C'ing the program doesn't print a > traceback either. ?Looking through the python debugger documentation, I > don't see how to run a python program and interactively stopping it > while it is running. ?Is there a way to stop within a running python > program to see where it is getting hung up? > > -- > Kevin D. Smith You might approximate the critical location using exceptions instead of prints. That's more costly of course because the program has to be restarted more often but it will serve the same purpose. From yohell at ifm.liu.se Mon Dec 15 16:50:45 2008 From: yohell at ifm.liu.se (Joel Hedlund) Date: Mon, 15 Dec 2008 22:50:45 +0100 Subject: weird dict problem, how can this even happen? Message-ID: I'm having a very hard time explaining why this snippet *sometimes* raises KeyError: snippet: > print type(self.pool) > for frag in self.pool.keys(): > if frag is fragment_info: > print "the fragment_info *is* in the pool", hash(frag), hash(fragment_info), hash(frag) == hash(fragment_info), frag == fragment_info, frag in self.pool, frag in self.pool.keys() > try: > renderer_index = self.pool.pop(fragment_info) > except KeyError: > print "Glorious KeyError!" > for frag in self.pool.keys(): > if frag is fragment_info: > print "the fragment_info *is* in the pool", hash(frag), hash(fragment_info), hash(frag) == hash(fragment_info), frag == fragment_info, frag in self.pool, frag in self.pool.keys() > raise output: > > the fragment_info *is* in the pool 987212075 987212075 True True False True > Glorious KeyError! > the fragment_info *is* in the pool 987212075 987212075 True True False True > Traceback (most recent call last): > File "/home/yohell/workspace/missy/core/gui.py", line 92, in process_job > renderer_index = self.pool.pop(fragment_info) > KeyError: This snippet is part of a much larger gtk program, and the problem only from time to time, predominantly when the cpu is under heavy load and this method gets called a lot. If I didn't know better I'd say it's a bug in python's dict implementation, but I do know better, so I know it's far more likely that I've made a mistake somewhere. I'll be damned if I can figure out what and where though. I've reproduced this bug (?) with python-2.5.2 on Ubuntu 8.10 and python-2.5.1 on WinXP. I would very much like an explanation to this that does not involve threads, because I haven't made any that I'm aware of. I can't even understand how this could happen. How do I even debug this? Please help, I feel like I've taken crazy pills here! /Joel Hedlund From gruszczy at gmail.com Mon Dec 1 09:21:54 2008 From: gruszczy at gmail.com (=?UTF-8?Q?Filip_Gruszczy=C5=84ski?=) Date: Mon, 1 Dec 2008 15:21:54 +0100 Subject: Do more imported objects affect performance In-Reply-To: References: Message-ID: <1be78d220812010621u51dead9dnbaa0b4c8c9414362@mail.gmail.com> I see. Thanks for a really good explanation, I like to know, how to do things in the proper way :) 2008/12/1 Nick Craig-Wood : > Rafe wrote: >> On Dec 1, 7:26?am, "Filip Gruszczy?ski" wrote: >> > I have following question: if I use >> > >> > from module import * >> > >> > instead >> > >> > from module import Class >> > >> > am I affecting performance of my program? I believe, that all those >> > names must be stored somewhere, when they are imported and then >> > browsed when one of them is called. So am I putting a lot of "garbage" >> > to this storage and make those searches longer? >> >> Why use it if you don't need it? Your post implies a choice and the >> '*' import can really make things muddy if it isn't actually necessary >> (rare). Why not just import the module and use what you need? It is >> way easier to read/debug and maintains the name-space. > > Importing the module is actualy slower... If you import the name into > your namespace then there is only one lookup to do. If you import the > module there are two. > > $ python -m timeit -s 'from timeit import Timer' 'Timer' > 10000000 loops, best of 3: 0.0784 usec per loop > > $ python -m timeit -s 'import timeit' 'timeit.Timer' > 1000000 loops, best of 3: 0.243 usec per loop > > I'm not suggestion you should ever use "from module import *" only > ever import the things you actually need, eg > "from module import MyClass, my_function" > > And here is the test again, actually calling something with the same > difference in execution speed :- > > $ python -m timeit -s 'from os import nice' 'nice(0)' > 1000000 loops, best of 3: 1.21 usec per loop > > $ python -m timeit -s 'import os' 'os.nice(0)' > 1000000 loops, best of 3: 1.48 usec per loop > > -- > Nick Craig-Wood -- http://www.craig-wood.com/nick > -- > http://mail.python.org/mailman/listinfo/python-list > -- Filip Gruszczy?ski From jonas.esp at googlemail.com Mon Dec 1 15:10:11 2008 From: jonas.esp at googlemail.com (Kless) Date: Mon, 1 Dec 2008 12:10:11 -0800 (PST) Subject: Chmod to a group only References: Message-ID: <83e430f3-0c4c-4aae-84e3-7a8bb6dc1b74@t11g2000yqg.googlegroups.com> On 1 dic, 18:17, Kless wrote: > How to chmod a file to: o-rwx ? (to change only the others mode) > > os.chmod(fname, ) > > I was reading this [1], but the truth is that anything as 'S_IRUSR' > doesn't help enought. > > [1]http://www.python.org/doc/2.5.2/lib/os-file-dir.html I have tried: mode = os.stat(fname).st_mode os.chmod(fname, mode | stat.S_IRWXO) => Changes to o+rwx and if is used: os.chmod(fname, mode & stat.S_IRWXO) => Delete all modes Any help? please From johnroth1 at gmail.com Sat Dec 6 09:49:08 2008 From: johnroth1 at gmail.com (John Roth) Date: Sat, 6 Dec 2008 06:49:08 -0800 (PST) Subject: Guido's new method definition idea References: Message-ID: <36e2dafd-f4ba-4348-8080-8d6786043653@n41g2000yqh.googlegroups.com> On Dec 5, 7:21?pm, "Daniel Fetchinson" wrote: > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... > > The proposal is to allow this: > > class C: > ? ? def self.method( arg ): > ? ? ? ? self.value = arg > ? ? ? ? return self.value > > instead of this: > > class C: > ? ? def method( self, arg ): > ? ? ? ? self.value = arg > ? ? ? ? return self.value > > I.e. explicit self stays only the syntax is slightly different and may > seem attractive to some. As pointed out by Guido classmethods would > work similarly: > > class C: > ? ? @classmethod > ? ? def cls.method( arg ): > ? ? ? ? cls.val = arg > ? ? ? ? return cls.val > > The fact that Guido says, > > "Now, I'm not saying that I like this better than the status quo. But > I like it a lot better than [...] but it has the great advantage that > it is backward compatible, and can be evolved into a PEP with a > reference implementation without too much effort." > > shows that the proposal is viable. > > I'd like this new way of defining methods, what do you guys think? > Anyone ready for writing a PEP? > > Cheers, > Daniel > > -- > Psss, psss, put it down! -http://www.cafepress.com/putitdown Sigh. If you make --both-- self and cls keywords, then 90% of the problems that Guido mentions in the blogspot post just vanish because whether it's an instance method, a class method or a static method can be inferred from the method body. In particular, the decorator problem goes away (the decorators are irrelevant, and can be ignored) and so does the problem with injecting a method into an object. It is, of course, harder to implement, and it would not be backwards compatible because all the internal wrappers vanish as well. That makes problems for anyone who is looking through __dict__ to find particular kinds of method. John Roth From google at mrabarnett.plus.com Sat Dec 20 18:47:53 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 20 Dec 2008 23:47:53 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> Message-ID: <494D8429.8050508@mrabarnett.plus.com> walterbyrd wrote: > On Dec 19, 12:43 pm, excord80 wrote: > >> Also, I like having only *one* special symbol (`%') to worry >> about in my strings instead of two (`{' and `}'). >> > > Actually the new way has, at least three special symbols: ( '{', '}' , > '.') as well as the method name "format" so > > "%s=%s" % (k, v) for k, v in params.items() > > becomes: > > "{0}={1}".format((k, v) for k, v in params.items()) > > or something like that. > "{0}={1}".format(k, v) for k, v in params.items() or: "{0}={1}".format(*i) for i in params.items() From p.f.moore at gmail.com Thu Dec 11 17:12:11 2008 From: p.f.moore at gmail.com (Paul Moore) Date: Thu, 11 Dec 2008 14:12:11 -0800 (PST) Subject: Best way of debigging a C extension References: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> Message-ID: <6b20568d-8ce9-4240-8f83-b579c241d9a9@l33g2000pri.googlegroups.com> On 11 Dec, 21:57, Christian Heimes wrote: > You have to build Python on your own to get debug builds. Only debug > builds allow to do extension debugging like memory leak finding. The trouble is, I only have mingw to build extensions, not MSVC7.1 - so I can't build Python (and I don't know if I still have the toolkit compiler to build with that - I certainly don't have all the pieces installed). With Python 2.6, I guess things will be better as I have VS2008 Express, so I can use this to build a debug Python plus my extension. It's more work than I really want to do to go that way, but I guess it'll work. > You are working against the system ;) > On Windows all extensions and shared libraries of a debug build have a > _d suffix. That's what I thought. I was just hoping that using a debug build of an extension would be usable with a standard release build of Python, as that's what will be easy for most people to set up. Ah, well, I'll stick to printf, combined with hacking a debug build to work with a release Python. It's ugly and unreliable, maybe, but good enough. Maybe sometime (probably not until I'm targeting 2.6 only) I'll set up my own debug build of Python, in a virtual machine somewhere. Thanks for the explanation. Paul. From skip.montanaro at gmail.com Tue Dec 9 21:06:14 2008 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Tue, 9 Dec 2008 18:06:14 -0800 (PST) Subject: Test posting #2 - please ignore References: Message-ID: On Dec 9, 3:40?pm, Skip Montanaro wrote: > This is another posting you can ignore. ?This time posted > via Google Groups. Test #3. Still fiddling around... Skip From darcy at druid.net Tue Dec 23 09:25:04 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 23 Dec 2008 09:25:04 -0500 Subject: iterating initalizations In-Reply-To: References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> Message-ID: <20081223092504.aaf25192.darcy@druid.net> On Mon, 22 Dec 2008 22:32:17 -0500 Aaron Stepp wrote: > Instead of writing a long list of initializations like so: > > A = [ ] > B = [ ] > ... > Y = [ ] > Z = [ ] > > I'd like to save space by more elegantly turning this into a loop. If Well, if all you want is a loop: for v in vars: locals()[v] = [] It's hard to tell if that's what you actually need though without deeper analysis of your requirements. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From martin at v.loewis.de Sun Dec 14 16:54:01 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 14 Dec 2008 22:54:01 +0100 Subject: Building from source -- zlib/binascii problems 2.5.2/2.6.1 In-Reply-To: <71531b64-535f-49d0-a0c6-7704df83b251@f18g2000vbf.googlegroups.com> References: <71531b64-535f-49d0-a0c6-7704df83b251@f18g2000vbf.googlegroups.com> Message-ID: <49458079.1000304@v.loewis.de> > Target: x86_64-redhat-linux > gcc -pthread -shared build/temp.linux-x86_64-2.5/location/of/ > Python-2.5.2/Modules/zlibmodule.o -L/usr/local/lib -lz -o build/ > lib.linux-x86_64-2.5/zlib.so > /usr/bin/ld: skipping incompatible /usr/lib/libz.so when searching for > -lz Do file /usr/lib/libz.so It might be a 32-bit library, in which case you can check whether /usr/lib64 has a 64-bit library. I'm puzzled why it only happens for -lz; perhaps you are better of compiling with a 32-bit compiler. Regards, Martin From adi at lspl.net Mon Dec 8 13:06:28 2008 From: adi at lspl.net (sniffer) Date: Mon, 8 Dec 2008 10:06:28 -0800 (PST) Subject: dBase III files and Visual Foxpro 6 files References: <917126a8-c2c6-49c5-b001-07c953992dac@q26g2000prq.googlegroups.com> Message-ID: <7d5b9758-e16e-4774-bee7-aac74e207bb9@q30g2000prq.googlegroups.com> On Dec 8, 7:44?pm, Ethan Furman wrote: > sniffer wrote: > > On Dec 8, 12:53 pm, Ethan Furman wrote: > >> Greetings All! > > >> I nearly have support complete for dBase III dbf/dbt files -- just > >> wrapping up support for dates. ?The null value has been a hindrance for > >> awhile but I nearly have that solved as well. > > >> For any who know of a cool dbf module already in existence for dBase III > >> and Visual Foxpro -- where were you six months ago when I was searching? > >> ? ;) ?Seriously, though, this has been a great learning experience for me. > > >> As I said -- dbf/dbt files are 99% ready. ?idx files -- no support: ?for > >> my purposes I just don't need them. ?I've found no problem in loading > >> tables up to 300,000 records with 50 fields per record, and re-ordering > >> them on the fly in memory. > > >> However, after putting much effort into this code, and wanting it to be > >> useful to others in the community, are there others who work with dbf > >> files that would need idx/cdx support? ?Or tables so large they won't > >> fit comfortably into memory? > > >> ~ethan~ > > > hi ethan, > > great to hear that someone has finally written something for > > interacting with vfp6 data,when do you plan to release it > > Well, let's see... > > A couple more days to have the datetime bit worked out (I don't support > datetimes prior to 1981 in vfp tables), > longer for currency types, and of course, no idx/cdx support at this point. > > Tell you what -- ?I'll trade you a copy of the code as it stands with > date and datetime working for null values, for an answer of whether you > need idx/cdx file support. ?;) > > ~ethan~ well ethan luckily i dont require idx/cdx support From simon at brunningonline.net Thu Dec 18 08:28:54 2008 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 18 Dec 2008 13:28:54 +0000 Subject: [Help] The pywinauto Can't select the MDI's menu using the MenuItems() which return []. In-Reply-To: References: Message-ID: <8c7f10c60812180528k2f755d6aj1564a19efb813db0@mail.gmail.com> 2008/12/18 ???? : > This problem also use the following discription: > How to use pywinauto to open WORD and select its Menu. > I can't do that and have no idea why! > Looking forward your help,Thanks! Word can be automated with COM. My golden rule is that automation via GUI driving is always a last resort. -- Cheers, Simon B. simon at brunningonline.net From philip at semanchuk.com Wed Dec 10 17:25:13 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Wed, 10 Dec 2008 17:25:13 -0500 Subject: When (and why) to use del? In-Reply-To: References: <1228840517.4109.10.camel@brotherus.rdu.redhat.com> Message-ID: <4F7C906E-807A-473A-A3C8-F659D79A11BD@semanchuk.com> On Dec 10, 2008, at 5:23 PM, Gabriel Genellina wrote: > En Tue, 09 Dec 2008 15:29:17 -0200, Philip Semanchuk > escribi?: >> On Dec 9, 2008, at 11:35 AM, Albert Hopkins wrote: >> >>> def myfunction(): >>> # do some stuff stuff >>> my_string = function_that_returns_string() >>> # do some stuff with my_string >>> del my_string >>> # do some other stuff >>> return >>> >>> I think this looks ugly, but also does it not hurt performance by >>> preempting the gc? My feeling is that this is a misuse of 'del'. >>> Am I >>> wrong? Is there any advantage of doing the above? >> >> The code above doesn't pre-empt the GC, it just provides it with a >> useful hint. When you del a variable you just tell the GC, "I'm >> done with this, so you might be able to get rid of it next time you >> collect garbage". If the variable wasn't explicitly del-ed, you'd >> still hold a reference and the GC would be unable to collect it >> while the section "do some other stuff" runs. > > Note that CPython has a garbage collector AND uses reference counts. > Objects are deallocated *immediately* as soon as their reference > count reaches zero. The GC is used only to detect and dispose of > reference cycles. > So, if you `del` a name and it happens to be the last reference to > certain object, the object is immediately destroyed; the GC isn't > involved at all. Thanks for the clarification -- I didn't know that. From pavlovevidence at gmail.com Thu Dec 4 15:32:08 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 4 Dec 2008 12:32:08 -0800 (PST) Subject: "as" keyword woes References: Message-ID: <777c7313-267f-4dc2-b6fd-fad0c9714f41@l42g2000yqe.googlegroups.com> On Dec 4, 3:44?am, James Stroud wrote: > You probably aren't a developer for the cPython implementation, but, if > you were, I'd recommend taking rants like Warren's to heart because they > are born of honest frustration and practical concern. Hopefully > developers for python 2.7 are listening and won't break backward > compatibility just because the "Zen of Python" suggests it might be a > good idea. I think they should. Python didn't get to where it is by being bogged down with obsolesence. It has grown and grown in popularity in spite of (and, I would say, in part because of) a history of backward- incompatible changes with every major release. It's not like Python has ignored the users; it's been very careful and considerate when making backwards-incompatible change. This change was planned for eight freaking years. Carl Banks From robert.kern at gmail.com Tue Dec 2 16:11:15 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 02 Dec 2008 15:11:15 -0600 Subject: optimization In-Reply-To: References: Message-ID: Neal Becker wrote: > Robert Kern wrote: > >> Neal Becker wrote: >>> Arnaud Delobelle wrote: >>> >>>> Neal Becker writes: >>>> >>>>> I noticed in some profiling, that it seems that: >>>>> >>>>> def Func (): >>>>> def something(): >>>>> ... >>>>> >>>>> It appears that if Func is called many times, this nested func >>>>> definition will cause significant overhead. Is this true? I guess >>>>> I've become accustomed to decent compilers performing reasonable >>>>> transformations and so have tended to write code for clarity. >>>> If something() can be defined outside Func(), how is it clearer to >>>> define it inside? >>> If it's only used inside. >> I, for one, find that significantly less clear. I only expect functions to >> be defined inside of functions if they are going to use lexical scoping >> for some reason. If I read your code, I'd probably waste a good five >> minutes trying to figure out what part of the local scope you were using >> before I would conclude that you just did it because you thought it looked >> better. > > I'm using the inner function to prevent pollution of the global namespace. Local variables also have this attribute. Code is easier to understand when it is written with the greatest locality - so you can see immediately that the inner function isn't used somewhere else. I don't think that the greatest locality metric is the only factor in understandability. You're introducing more nesting, which means more context switching as I read the code. I like shortish functions with one coherent idea per function. I like to see the argument spec, the docstring, and the body of the code all on one page. If the functions it calls are reasonably well-named, or their calls are commented, I can read that function all the way through without having to page around. By nesting the definitions of the functions inside, I have to skip from the argument spec and docstring down to the body. And I'm still going to spend time trying to figure out what lexical scoping you are using before giving up. I still think that defining a function inside of a function for organizational purposes is a (mild) abuse of the feature. Packages, modules, __all__, and the _underscoring conventions are the language features for organizing namespaces of functions. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From metolone+gmane at gmail.com Mon Dec 29 04:06:18 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Mon, 29 Dec 2008 01:06:18 -0800 Subject: How to display Chinese in a list retrieved from database via python References: <22be506d-91c2-4727-ace7-2e3382b6d214@g3g2000pre.googlegroups.com><979fdf6d-0500-47ba-87fd-0f0361ca3059@p2g2000prf.googlegroups.com><19680ed2-c78f-4ab9-8ca0-8ce26fd5b6a7@o4g2000pra.googlegroups.com> <2560a6e0-c103-46d2-aa5a-8604de4d1968@b38g2000prf.googlegroups.com> Message-ID: "zxo102" wrote in message news:2560a6e0-c103-46d2-aa5a-8604de4d1968 at b38g2000prf.googlegroups.com... > I have a list in a dictionary and want to insert it into the html > file. I test it with following scripts of CASE 1, CASE 2 and CASE 3. I > can see "??" in CASE 1 but that is not what I want. CASE 2 does not > show me correct things. > So, in CASE 3, I hacked the script of CASE 2 with a function: > conv_list2str() to 'convert' the list into a string. CASE 3 can show > me "??". I don't know what is wrong with CASE 2 and what is right with > CASE 3. > > Without knowing why, I have just hard coded my python application > following CASE 3 for displaying Chinese characters from a list in a > dictionary in my web application. > > Any ideas? > See below each case...????? > Happy a New Year: 2009 > > ouyang > > > > CASE 1: > ######################################################## > f=open('test.html','wt') > f.write(''' > > test > > > ''') > f.close() In CASE 1, the *4 bytes* D6 D0 CE C4 are written to the file, which is the correct gb2312 encoding for ??. > CASE 2: > ####################################################### > mydict = {} > mydict['JUNK'] = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce > \xc4'] > f_str = ''' > > test > > > ''' > > f_str = f_str%mydict > f=open('test02.html','wt') > f.write(f_str) > f.close() In CASE 2, the *16 characters* "\xd6\xd0\xce\xc4" are written to the file, which is NOT the correct gb2312 encoding for ??, and will be interpreted however javascript pleases. This is because the str() representation of mydict['JUNK'] in Python 2.x is the characters "['\xd6\xd0\xce\xc4', '\xd6\xd0\xce\xc4', '\xd6\xd0\xce\xc4']". > CASE 3: > ################################################### > mydict = {} > mydict['JUNK'] = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce > \xc4'] > > f_str = ''' > > test > > > ''' > > import string > > def conv_list2str(value): > list_len = len(value) > list_str = "[" > for ii in range(list_len): > list_str += '"'+string.strip(str(value[ii])) + '"' > if ii != list_len-1: > list_str += "," > list_str += "]" > return list_str > > mydict['JUNK'] = conv_list2str(mydict['JUNK']) > > f_str = f_str%mydict > f=open('test03.html','wt') > f.write(f_str) > f.close() CASE 3 works because you build your own, correct, gb2312 representation of mydict['JUNK'] (value[ii] above is the correct 4-byte sequence for ??). That said, learn to use Unicode strings by trying the following program, but set the first line to the encoding *your editor* saves files in. You can use the actual Chinese characters instead of escape codes this way. The encoding used for the source code and the encoding used for the html file don't have to match, but the charset declared in the file and the encoding used to write the file *do* have to match. # coding: utf8 import codecs mydict = {} mydict['JUNK'] = [u'??',u'??',u'??'] def conv_list2str(value): return u'["' + u'","'.join(s for s in value) + u'"]' f_str = u''' test ''' s = conv_list2str(mydict['JUNK']) f=codecs.open('test04.html','wt',encoding='gb2312') f.write(f_str % s) f.close() -Mark P.S. Python 3.0 makes this easier for what you want to do, because the representation of a dictionary changes. You'll be able to skip the conv_list2str() function and all strings are Unicode by default. From mr.spoon21 at gmail.com Thu Dec 18 05:34:42 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Thu, 18 Dec 2008 11:34:42 +0100 Subject: OT: Binary tree logarithms properties In-Reply-To: References: <8f67b6f80812170914m377191f4g81345ffe5d0b7f26@mail.gmail.com> Message-ID: <8f67b6f80812180234u103b31e2kcde80c2cd7f250e3@mail.gmail.com> 2008/12/17 Terry Reedy : > Nodes only have single number indexes if you arrange them linearly. Then the > index depends on how you arrange them, whether you start the array indexes > with 0 or 1, and whether you start the level numbers with 0 or 1. Call the > breadth-first sequence bf. Then the 1-based slice for 1-first level k is > bf[2**(k-1):2**k)]. Again, proof by induction. Yes, I was referring to the heap numeration. Anyway, Francesco Guerrieri answered me in a private message and explained me the formula. But actually I was searching for other similar properties. From grahn+nntp at snipabacken.se Fri Dec 5 07:10:52 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 5 Dec 2008 12:10:52 GMT Subject: Python surpasses Perl in popularity? References: <5e87aee0-c7fd-4e9d-befb-0cc01cee64ec@f40g2000pri.googlegroups.com> <49316c95$0$2813$742ec2ed@news.sonic.net> Message-ID: ["Followup-To:" header set to comp.unix.shell.] On 29 Nov 2008 16:23:49 GMT, Tam Ha wrote: > Jorgen Grahn wrote: >>(I could get away with using Bash in these cases. It has functions, >>local variables and so on. Writing portable Bourne shell is not as >>much fun.) > > Can you explain this? Sorry for the late answer. No, it's actually what I said: I could get away with using bash in these cases, so I did it. It was an in-house application, it had already unknown dependencies to bash, and to Linux versions of other utilities. If I had asked for time to modify it to make sure it was portable Bourne shell, people would have laughed at me. > Bourne is always more portable than Bash. > That's why you'll find experienced shell programmers writing everything > that doesn't absolutely require a bash feature in /bin/sh. Boot scripts, > install scripts, etc. should never be written in bash and if where you > find one using bash you can be sure a Linux-only newbie has written it. Sure, nothing controversial about that. I don't argue that people should use bash features in any random script they write. I just noted that if you decide to use it, it's a pretty useful language. Probably more useful than Python in my case, where most of the work was about starting and managing external commands and pipelines. > For one there are too many versions of bash, for two it is not installed > by default on every Unix/Linux OS, for three it has poor backwards > (and forwards) compatibility. Worse compatibility than Perl or Python? The Bourne shell timescale is probably impressive, but often you aren't interested in decades. > It is also found at different places on > the path. Surely that applies to almost any interpreter, like perl and python. It's a problem (on the non-free Unixes at least) but if you let it be the deciding factor, you could use no scripting language except /bin/sh and awk. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From phd at phd.pp.ru Mon Dec 8 12:09:21 2008 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 8 Dec 2008 20:09:21 +0300 Subject: SQLObject 0.10.4 Message-ID: <20081208170921.GK7441@phd.pp.ru> Hello! I'm pleased to announce version 0.10.4, a minor bugfix release of 0.10 branch of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.10.4 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.10.3 ----------------- * Fixed createSQL constrains generation under MySQL when the table's name includes the database's name (contains a dot). For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From ndbecker2 at gmail.com Thu Dec 18 09:09:05 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 18 Dec 2008 09:09:05 -0500 Subject: confused about __str__ vs. __repr__ Message-ID: Reading some FAQ, I see that __str__ is "meant for human eyes". But it seems that: class X(object): def __str__(self): return "str" def __repr__(self): return "repr" x = X() d = {0 : x} print d {0: repr} So if __str__ is "meant for human eyes", then why isn't print using it! From rt8396 at gmail.com Mon Dec 22 17:47:52 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 14:47:52 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <6ra8t0F925rU1@mid.individual.net> <29feda0d-6432-4cb9-8809-e4d4a7798601@e1g2000pra.googlegroups.com> <6raeb8F9s47U2@mid.individual.net> <6rahpaFav7kU2@mid.individual.net> Message-ID: <97e49a8c-6730-42f2-b4d0-35eaff38b69f@y1g2000pra.googlegroups.com> On Dec 22, 4:14?pm, je.s.t... at hehxduhmp.org wrote: > r wrote: > > Would you trust my words more if i used a name like "Thurstan Howell > > III".... Come on, don't tell me you are that shallow. To attack my > > credibility solely based on my user name is the sport of small minded > > people. Surely you can bring more thought, and intelligence to this > > thread than that?... > > I'm just saying that there's absolutely no more credibility attached > to some random & anonymous account than there is to someone due to > not having X-No-Archive. ?You are no more accountable for your words than > I am. ?So you might be throwing stones at my use of X-No-Archive, but > you are living in a glass house. > > And for the record, the obfuscation of my email address and the use of > X-No-Archive has a lot more to do with random people being able to > track me via the internet than it does with believing/not believing what > I'm saying. ?If one wanted to put in some small bit of effort, it isn't > particularly difficult to track down usenet posts authored by me from > 15ish years ago, but I raise the bar so that any random joker probably won't > bother (and making the reverse mapping - knowing my real identity and then > looking for recent net activity - is much more difficult to do). An exercise in thought... To go a bit further, what if we could post a picture of ourselves on the Usenet?? What would stop me from posting a picture of someone else besides myself? NOTHING! Do not put your trust in such weak beliefs. My name and picture mean squat on a this medium. If you want to validate my intelligence, use my words, not shallow assumptions. Your logic is like that fruitcake my auntie makes every Christmas. Please put more thought into you post. My words are here and they will stay here, sure some may disagree with my thoughts, but i will not be ashamed of them! Thats called having "brass Cohones" mi hijo. From dickinsm at gmail.com Mon Dec 8 05:46:12 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 8 Dec 2008 02:46:12 -0800 (PST) Subject: built-in functions as class attributes Message-ID: <75fdbf34-34d9-4373-bbe0-7e3f76dc4c3f@x38g2000yqj.googlegroups.com> Here's a curiosity: after def my_hex(x): return hex(x) one might expect hex and my_hex to be interchangeable in most situations. But (with both Python 2.x and 3.x) I get: >>> def my_hex(x): return hex(x) ... >>> class T(object): f = hex ... >>> class T2(object): f = my_hex ... >>> T().f(12345) '0x3039' >>> T2().f(12345) Traceback (most recent call last): File "", line 1, in TypeError: my_hex() takes exactly 1 argument (2 given) [36412 refs] Anyone know what the precise rules that lead to this behaviour are, or where they're documented? Surprised'ly yours, Mark From Astley.lejasper at gmail.com Tue Dec 2 14:05:21 2008 From: Astley.lejasper at gmail.com (Astley Le Jasper) Date: Tue, 2 Dec 2008 11:05:21 -0800 (PST) Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> Message-ID: <24f0dc02-9461-4b93-a2f8-a56fa5919ffc@n10g2000yqm.googlegroups.com> James ... thanks for the suggestion. I have done this and the error logging usually catches all my errors and logs them. I wondered if logging itself was failing! Philip ... thanks also. I did wonder about making the everything explicit. I've seen that mentioned elsewhere. Writing out the stdout & stderr to another file is a great idea. I'll have ago. But I think our dinner guests are starting to make comments so I'd better go! From bdesth.quelquechose at free.quelquepart.fr Fri Dec 12 14:31:09 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 12 Dec 2008 20:31:09 +0100 Subject: (Very Newbie) Problems defining a variable In-Reply-To: References: <878wqlz27z.fsf@daycos.com> Message-ID: <4942c9b4$0$1651$426a34cc@news.free.fr> Tim Rowe a ?crit : > 2008/12/12 Kirk Strauser : > >> def get_rate(balance): >> for threshold, rate in ((100000, .0173), >> (50000, .0149), >> (25000, .0124), >> (10000, .0085), >> (0, .006)): >> if balance > threshold: >> return rate >> return .0 > > Yes, once it's changed from a dictionary to tuples it becomes easier, > doesn't it? D'oh! > A sequence of pairs and a dict are _almost_ interchangeable (mmm... is that the correct word ?) representations of a same data set[1] - the main difference being ordering. If ordering matters, choose a sequence of pairs as main representation - you can easily build a dict from it if/when you need it. [1] >>> d = dict(a=1, b=2, c=3) >>> dict(d.items()) == d True >>> From mark at thomaszone.com Mon Dec 29 07:40:22 2008 From: mark at thomaszone.com (Mark Thomas) Date: Mon, 29 Dec 2008 04:40:22 -0800 (PST) Subject: Any equivalent to Ruby's 'hpricot' html/xpath/css selector package? References: Message-ID: On Dec 28, 6:22?pm, Kenneth McDonald wrote: > Ruby has a package called 'hpricot' which can perform limited xpath ? > queries, and CSS selector queries. However, what makes it really ? > useful is that it does a good job of handling the "broken" html that ? > is so commonly found on the web. Does Python have anything similar, ? > i.e. something that will not only do XPath queries, but will do so on ? > imperfect HTML? Hpricot is a fine package but I prefer Nokogiri (see http://www.rubyinside.com/nokogiri-ruby-html-parser-and-xml-parser-1288.html) because it is based on libxml2 and therefore is faster, conforms to the full XPath 1.0 spec, works on imperfect HTML, and exposes the Hpricot API. In python, the equivalent is lxml (http://codespeak.net/lxml/), which is similarly based on libxml2, very fast, XPath-1.0 conformant, and exposes the now-standard ElementTree API. The main difference is that lxml doesn't have CSS selector syntax, but IMHO that's a gimmick when you have a full XPath 1.0 engine at your disposal. -- Mark. From pavlovevidence at gmail.com Sun Dec 14 00:15:17 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 13 Dec 2008 21:15:17 -0800 (PST) Subject: curses and refreshing problem References: Message-ID: <69d2698a-6f44-4d85-adc3-1180ab158632@r15g2000prd.googlegroups.com> On Dec 13, 2:29?pm, Karlo Lozovina <_karlo_ at _mosor.net_> wrote: > Hi, I'm trying to implement text output interface, something similar to > wget, using curses module. There are just two things I can't find out how > to do: prevent curses from clearing the terminal when starting my program, > and leaving my output after the program closes. Any way to do this with > curses? Unless you are referring to some wget screen mode I don't know about, I suspect wget outputs its progress bar using carriage returns without newlines. If that's all you want, there is no need to use curses. Here is a little example program to illustrate: import time, sys for i in range(21): sys.stdout.write('\rProgress: [' + '='*i + ' '*(20-i) + ']') sys.stdout.flush() time.sleep(1) sys.stdout.write("\nFinised!\n") Notice I'm using sys.stdout.write instead of print, because print automatically appends a newline (which we don't want here). Yes you can suppress the newline on print by using a trailing comma, but that creates an undesirable artifact--a leading space--on the following cycle. Notice the '\r' at the beginning of the sys.stdout.write call. This tells the terminal to move the cursor back to the beginning of the line, whence it draws the new progress bar over the old progress bar. And finally, notice the call to sys.stdout.flush(). When a program is run on a terminal the underlying I/O is usually line-buffered, meaning that nothing actually gets output until a newline character is sent. Therefore we have to call sys.stdout.flush() to flush the buffer manually. Carl Banks From steve at REMOVE-THIS-cybersource.com.au Thu Dec 25 08:56:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Dec 2008 13:56:21 GMT Subject: Is there a function to remove escape characters from a string ? References: Message-ID: <0163882f$0$6988$c3e8da3@news.astraweb.com> On Thu, 25 Dec 2008 11:00:18 +0100, Stef Mientki wrote: > hello, > > Is there a function to remove escape characters from a string ? > (preferable all escape characters except "\n"). Can you explain what you mean? I can think of at least four alternatives: (1) Remove literal escape sequences (backslash-char): "abc\\t\\ad" => "abcd" r"abc\t\ad" => "abcd" (2) Replace literal escape sequences with the character they represent: "abc\\t\\ad" => "abc\t\ad" (3) Remove characters generated by escape sequences: "abc\t\ad" => "abcd" "abc" => "abc" but "a\x62c" => "ac" This is likely to be impossible without deep magic. (4) Remove so-called binary characters which are typically inserted using escape sequences: "abc\t\ad" => "abcd" "abc" => "abc" but "a\x62c" => "abc" This is probably the easiest, assuming you have bytes instead of unicode. import string table = string.maketrans('', '') delchars =''.join(chr(n) for n in range(32)) s = string.translate(s, table, delchars) -- Steven From kay.schluehr at gmx.net Sat Dec 6 01:55:38 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Fri, 5 Dec 2008 22:55:38 -0800 (PST) Subject: Guido's new method definition idea References: Message-ID: <9e9d9410-a1a0-4736-a635-490f5e80454b@l39g2000yqn.googlegroups.com> On 6 Dez., 03:21, "Daniel Fetchinson" wrote: > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... > > The proposal is to allow this: > > class C: > def self.method( arg ): > self.value = arg > return self.value > > instead of this: > > class C: > def method( self, arg ): > self.value = arg > return self.value > > I.e. explicit self stays only the syntax is slightly different and may > seem attractive to some. As pointed out by Guido classmethods would > work similarly: > > class C: > @classmethod > def cls.method( arg ): > cls.val = arg > return cls.val > > The fact that Guido says, > > "Now, I'm not saying that I like this better than the status quo. But > I like it a lot better than [...] but it has the great advantage that > it is backward compatible, and can be evolved into a PEP with a > reference implementation without too much effort." > > shows that the proposal is viable. So both forms are dual to each other ( "backwards compatibility" ) and can be used both? I'm -0 on this although I think the proposition fits better with the method call syntax. From gagsl-py2 at yahoo.com.ar Sun Dec 14 16:30:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 14 Dec 2008 19:30:41 -0200 Subject: Bidirectional Networking References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <6qeht0Fc3541U1@mid.individual.net> <782258db-2bdc-45a7-8d8f-7a036d574985@t26g2000prh.googlegroups.com> <2cf74767-e331-4fa6-8915-8f87ba01ca34@l33g2000pri.googlegroups.com> Message-ID: En Sun, 14 Dec 2008 11:00:18 -0200, Emanuele D'Arrigo escribi?: > On Dec 14, 4:10 am, "Gabriel Genellina" > wrote: >> daemon became a property in Python 2.6; setDaemon was the only way to >> set >> it in previous versions. > > I thought that might be the case! The documentation is a bit vague: > > http://docs.python.org/library/threading.html?highlight=threading#threading.Thread.setDaemon > > Should we maybe add "New in 2.6" to the Thread.daemon paragraph? That would be a nice addition, but if you are using Python 2.5, you should read the 2.5 version of the docs: http://www.python.org/doc/2.5.2/lib/thread-objects.html -- Gabriel Genellina From ethan at stoneleaf.us Mon Dec 8 02:53:23 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Sun, 07 Dec 2008 23:53:23 -0800 Subject: dBase III files and Visual Foxpro 6 files Message-ID: <493CD273.90404@stoneleaf.us> Greetings All! I nearly have support complete for dBase III dbf/dbt files -- just wrapping up support for dates. The null value has been a hindrance for awhile but I nearly have that solved as well. For any who know of a cool dbf module already in existence for dBase III and Visual Foxpro -- where were you six months ago when I was searching? ;) Seriously, though, this has been a great learning experience for me. As I said -- dbf/dbt files are 99% ready. idx files -- no support: for my purposes I just don't need them. I've found no problem in loading tables up to 300,000 records with 50 fields per record, and re-ordering them on the fly in memory. However, after putting much effort into this code, and wanting it to be useful to others in the community, are there others who work with dbf files that would need idx/cdx support? Or tables so large they won't fit comfortably into memory? ~ethan~ From jstroud at mbi.ucla.edu Mon Dec 8 03:10:20 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 08 Dec 2008 00:10:20 -0800 Subject: Rich Comparisons Gotcha In-Reply-To: References: <014c593e$0$20670$c3e8da3@news.astraweb.com> Message-ID: Robert Kern wrote: > James Stroud wrote: >> I think it skips straight to __eq__ if the element is not the first in >> the list. > > No, it doesn't skip straight to __eq__(). "y is 1" returns False, so > (y==1) is checked. When y is a numpy array, this returns an array of > bools. list.__contains__() tries to convert this array to a bool and > ndarray.__nonzero__() raises the exception. > > list.__contains__() checks "is" then __eq__() for each element before > moving on to the next element. It does not try "is" for all elements, > then try __eq__() for all elements. Ok. Thanks for the explanation. > > That no one acknowledges this makes me feel like a conspiracy > > is afoot. > > I don't know what you think I'm not acknowledging. Sorry. That was a failed attempt at humor. James From Astley.lejasper at gmail.com Wed Dec 3 10:29:25 2008 From: Astley.lejasper at gmail.com (Astley Le Jasper) Date: Wed, 3 Dec 2008 07:29:25 -0800 (PST) Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> Message-ID: <126ba84a-0ea0-4a91-b7d2-89ed650e5d6c@d32g2000yqe.googlegroups.com> I've included a switch to include or exclude the logging to console. When logging only to file, the script runs fine. Of course, I still don't understand why dual logging, and specifically to the console, causes a problem and if anyone has any comments about the dual output logging code above then I'd still be happy to hear about it. ALJ From kyosohma at gmail.com Thu Dec 25 08:38:17 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 25 Dec 2008 05:38:17 -0800 (PST) Subject: PythonCard timer/thread tutorial References: <59e602b0-937c-4bd5-bc71-30094e1cd596@r36g2000prf.googlegroups.com> <6f7164cc-56dc-4022-8943-067b8ca44e61@40g2000prx.googlegroups.com> <0163809d$0$6988$c3e8da3@news.astraweb.com> Message-ID: <76e23107-b4c6-41cb-8199-f2a80b61cda7@v39g2000pro.googlegroups.com> On Dec 25, 7:24?am, Steven D'Aprano wrote: > On Wed, 24 Dec 2008 16:59:23 -0800, Mike Driscoll wrote: > >> Among my questions are: > >> """ A little thread we've added""" seems to be an isolated string. It > >> does not seem to be doing anything there, almost like a comment. Why is > >> it there? > > > That's what some people call a doc string. > > Other people call it "Maurice". *wink* > > A doc[umentation] string is the accepted name for it. Anytime a function, > class or module starts immediately with a loan string, that string is > stored by the Python compiler in an attribute __doc__. E.g.: > > >>> def parrot(x): > > ... ? ? "This is a doc string." > ... ? ? return "Norwegian Blue" > ...>>> parrot.__doc__ > > 'This is a doc string.' > > > It is like a comment in that > > it helps the user know what the function is for. Notice the triple > > quotes. > > Triple quotes are a red herring. Any string literal will do. > > -- > Steven Thanks for clearing that up. I suppose that's more of a recommended style choice than a requirement. I'm pretty sure some of the Python books I've read have implied that the triple quotes matter...oh well. Live and learn. Merry Christmas! Mike From pavlovevidence at gmail.com Sat Dec 6 22:35:42 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 6 Dec 2008 19:35:42 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> <014b2a09$0$20670$c3e8da3@news.astraweb.com> Message-ID: <5e58fbc8-17df-40ae-8b18-7b07765e898f@v38g2000yqb.googlegroups.com> On Dec 6, 8:17?pm, Steven D'Aprano wrote: > On Sun, 07 Dec 2008 11:27:56 +1000, Nick Coghlan wrote: > > Warren DeLano wrote: > >> In other words we have lost the ability to refer to "as" as the > >> generalized OOP-compliant/syntax-independent method name for casting: > > > Other possible spellings: > > > # Use the normal Python idiom for avoiding keyword clashes # and append > > a trailing underscore > > new_object = old_object.as_(class_hint) float_obj = int_obj.as_("float") > > float_obj = int_obj.as_(float_class) > > > # Use a different word (such as, oh, "cast" perhaps?) new_object = > > old_object.cast(class_hint) float_obj = int_obj.cast("float") > > float_obj = int_obj.cast(float_class) > > I don't like "cast", because a cast is an instruction to the compiler to > treat data as some type other than what it was defined as. It doesn't > create a new piece of data. (At least in C-like languages.) Actually, C-like languages do exactly that. (float)i doesn't take the bits of int i and treat them as if they were a float, it creates new data in the appropriate data type that matches the value of i semantically, which would have a very different bit pattern. Pointer-to-int and pointer-to-pointer typecasts are really the only ones that tend to preserve the bits of the data (which, since they are the most common kinds of typecast, has misled some people to think that typecasts in C are all about preserving bits). However, in general typecasts preserve the semantic value of the original data. That's exactly what these methods would be doing, changing the type while preserving the semantic value as much as possble, so cast is a perfectly appropriate name for it. (BTW, in C++, even pointer-to-pointer static casts don't always preserve the bits.) Carl Banks From steve at holdenweb.com Tue Dec 23 11:10:52 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 23 Dec 2008 11:10:52 -0500 Subject: iterating initalizations In-Reply-To: <20081223105911.9b265bf2.darcy@druid.net> References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> <20081223092504.aaf25192.darcy@druid.net> <20081223105911.9b265bf2.darcy@druid.net> Message-ID: D'Arcy J.M. Cain wrote: > On Tue, 23 Dec 2008 10:20:59 -0500 > Steve Holden wrote: >> D'Arcy J.M. Cain wrote: >>> Well, if all you want is a loop: >>> >>> for v in vars: >>> locals()[v] = [] >>> >> Note that this isn't guaranteed to work. While locals() will return a >> dict containing the names and values from the local namespace, you won't >> affect the local namespace by assigning values to the appropriate keys: >> >>>>> def f(): >> ... a = "hello" >> ... locals()["a"] = "goodbye" >> ... print a > > This was my test: > >>>> locals()['x'] = "hello" >>>> x > 'hello' >>>> locals()['x'] = "goodbye" >>>> x > 'goodbye' > > Just didn't want people to think that I post without testing. > > In any case, even if that worked as expected I am pretty sure that it > is the wrong solution but without knowing more about what the OP is > doing it is impossible to know what the right answer is. > The thing you overlooked was that the locals of a function are special. The locals of a module are the globals! >>> def lisg(): ... return locals() is globals() ... >>> locals() is globals() True >>> lisg() False >>> regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From jon at ffconsultancy.com Mon Dec 8 07:07:10 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Mon, 08 Dec 2008 12:07:10 +0000 Subject: Mathematica 7 compares to other languages References: <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: <4ridneQnkLrPkKDUnZ2dnUVZ8qbinZ2d@posted.plusnet> sln at netherlands.com wrote: > Well, its past 'tonight' and 6 hours to go till past 'tomorrow'. > Where the hell is it Zah Zah? Note that this program takes several days to compute in Mathematica (even though it takes under four seconds in other languages) so don't expect to see a genuinely optimized version any time soon... ;-) -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From Russ.Paielli at gmail.com Sat Dec 6 10:15:27 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 6 Dec 2008 07:15:27 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> Message-ID: <8b8d1fb3-f49e-49bf-8cfe-eeee5ed16109@r37g2000prr.googlegroups.com> On Dec 6, 4:32?am, Andreas Waldenburger wrote: > On Sat, 6 Dec 2008 04:02:54 -0800 (PST) bearophileH... at lycos.com wrote: > > > class C: > > ? ? def $method(arg): > > ? ? ? ? $value = arg > > > (Note there's no point after $, it's not currently possible). > > Ruby uses @ and @@ for similar purposes. > > I agree that the code looks worse, but also shorter to read and write, > > so in lines of code that use many instance attributes, that short $ > > syntax helps keep the line shorter. So I may grow to accept this > > sugar... > > But that is not the way Python is meant to work. There are several > tennets in the Zen of Python that don't chime well with this approach. > "self" is a speaking identifier, "$" isn't. Is "@" a "speaking identifier? How about "#" and "!="? Last I heard, they were all part of Python. From Slaunger at gmail.com Wed Dec 10 02:50:45 2008 From: Slaunger at gmail.com (Slaunger) Date: Tue, 9 Dec 2008 23:50:45 -0800 (PST) Subject: Best way to report progress at fixed intervals References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> <817384d5-5f68-4c1f-9560-0bc7b7d2b1e3@v5g2000prm.googlegroups.com> <6ccb77a2-a3f1-4b6b-900c-d4626be9e939@s1g2000prg.googlegroups.com> Message-ID: On 10 Dec., 08:03, Arnaud Delobelle wrote: > Slaunger writes: > > On 10 Dec., 03:44, George Sakkis wrote: > >> On Dec 9, 11:40?am, Slaunger wrote: > > >> > I would therefore like some feedback on this proposed generic "report > >> > progress at regular intervals" approach presented here. What could I > >> > do better? > > >> There is a pypi package that might do what you're looking for (haven't > >> used it though):http://pypi.python.org/pypi/progressbar/. > > >> HTH, > >> George > > > Thank you. I will keep that in mind, if I ever get to doing GUI-based > > progress. > > > -- Slaunger > > It's a text progress bar > > -- > Arnaud- Skjul tekst i anf?rselstegn - > > - Vis tekst i anf?rselstegn - Sorry, apparently I did not realize that at first sight. Anyway, I'd rather avoid using further external modules besides the standard batteries, as I would have to update several workstations with different OSes (some of which I do not have admin access to) to use the new module. -- Slaunger From gh at ghaering.de Wed Dec 3 16:21:54 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 03 Dec 2008 22:21:54 +0100 Subject: python an sqlite objects In-Reply-To: References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <18742.47391.389709.119341@montanaro-dyndns-org.local> Message-ID: <4936F872.2020207@ghaering.de> azrael wrote: > It logical that it would be more efficient and logical to use a object > oriented database, but in this case I ask because of the portable > nature of sqlite. > > so, if I get it right, this should be possible [...] Did you try it? Did it work? If so,it was pure luck. Attached is a script that shows how to do it right. -- Gerhard -------------- next part -------------- A non-text attachment was scrubbed... Name: sqlite_serialize.py Type: text/x-python Size: 1642 bytes Desc: not available URL: From prologic at shortcircuit.net.au Tue Dec 30 18:58:34 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 09:58:34 +1000 Subject: get method In-Reply-To: <495AAB97.5010707@mrabarnett.plus.com> References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> <495AAB97.5010707@mrabarnett.plus.com> Message-ID: On Wed, Dec 31, 2008 at 9:15 AM, MRAB wrote: (snip) > A while back I posted a Python implementation of 'bag' (also called a > multiset). The code would then become something like: What complexity is this ? cheers James From steven at REMOVE.THIS.cybersource.com.au Tue Dec 9 23:10:30 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 10 Dec 2008 04:10:30 GMT Subject: Can't figure out where SyntaxError: can not delete variable 'x' referenced in nested scope us coming from in python >=2.6 References: <014eef7f$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Tue, 09 Dec 2008 22:57:36 -0500, Albert Hopkins wrote: > On Tue, 2008-12-09 at 22:57 +0000, Steven D'Aprano wrote: [...] >> > So is there a way to find the offending code w/o having to go >> through >> > every line of code in 'foo' by hand? >> >> Just search for "del x" in your code. Your editor does have a search >> function, surely? >> >> >> > Well, you'd think I'd be smart enough to think of that one, wouldn't > you? Actually, how could you since you don't know me ;-)... Anway, I > already did that and could not find the offending code. You should have said :) > I submitted this bug [1]. I applied the given patch but the line it > shows isn't a "del" anything so I'm even more confused. Ouch. You have my sympathies. I guess you're going to have to just import each module one at a time until you find the module that fails, then search that one. -- Steven From python at bdurham.com Wed Dec 24 02:16:36 2008 From: python at bdurham.com (python at bdurham.com) Date: Wed, 24 Dec 2008 02:16:36 -0500 Subject: Strategy for determing difference between 2 very large dictionaries Message-ID: <1230102996.2303.1291616055@webmail.messagingengine.com> I'm looking for suggestions on the best ('Pythonic') way to determine the difference between 2 very large dictionaries containing simple key/value pairs. By difference, I mean a list of keys that are present in the first dictionary, but not the second. And vice versa. And a list of keys in common between the 2 dictionaries whose values are different. The 2 strategies I'm considering are: 1. Brute force: Iterate through first dictionary's keys and determine which keys it has that are missing from the second dictionary. If keys match, then verify that the 2 dictionaries have identical values for the same key. Repeat this process for the second dictionary. 2. Use sets: Create sets from each dictionary's list of keys and use Python's set methods to generate a list of keys present in one dictionary but not the other (for both dictionaries) as well as a set of keys the 2 dictionaries have in common. Using the set of keys in common, compare values across dictionaries to determine which keys have different values (can this last step be done via a simple list comprehension?) Feedback on my proposed strategies (or better strategies) would be greatly appreciated. Thank you, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip at pobox.com Wed Dec 3 12:37:21 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 3 Dec 2008 11:37:21 -0600 Subject: python an sqlite objects In-Reply-To: <4936bceb$0$16783$426a34cc@news.free.fr> References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <4936bceb$0$16783$426a34cc@news.free.fr> Message-ID: <18742.50129.573798.742119@montanaro-dyndns-org.local> Bruno> Or if you want something more portable, serialize the object to Bruno> json. At least you'll have a chance to deserialize it with some Bruno> other language. Assuming json can serialize more-or-less arbitrary Python objects. Can it serialize class instances? Skip From n.kottiyath at gmail.com Wed Dec 24 12:37:31 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Wed, 24 Dec 2008 09:37:31 -0800 (PST) Subject: Iterating over objects of a class Message-ID: <2df27de3-7fa3-4ac9-acd9-f946939517cf@r37g2000prr.googlegroups.com> Hi, How can I iterate over all the objects of a class? I wrote the code like following: class baseClass(object): __registry = [] def __init__(self, name): self.__registry.append(self) self.name = name def __iter__(self): baseClass.item = 0 return self.__registry[0] def next(self): if baseClass.item >= len(self.__registry): raise StopIteration baseClass.item += 1 return self.__registry[baseClass.item - 1] For testing, create the following objects- a = baseClass("Test1") b = baseClass("Test2") class subClass (baseClass): pass c = subClass("Test3") ---->Actual Iteration<---- for i in a: print i.name Test1 Test2 Test3 --------------------------------------------------- I see the following problems in the code: 1. I have to iterate over any of the objects. For correctness, I wanted to iterate over the class, like for i in baseClass(): do x but that will will create one more object - which I do not want. 2. If the subclass wants to do somethings in its constructor, I am not sure how to update the registry. class subClass (baseClass): def __init__(self, name): **do something** super.init(self, name) ----> This errors out, saying it needs super, not subClass Another method I thought of implementing it was using generators - where-in baseClass.objects() is a generator which will yield the objects one by one - but even then the second issue remains. If somebody can help me out, I would be very thankful. Regards K From ldo at geek-central.gen.new_zealand Fri Dec 5 05:16:08 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 05 Dec 2008 23:16:08 +1300 Subject: Don't you just love writing this sort of thing :) References: <0148b086$0$20670$c3e8da3@news.astraweb.com> Message-ID: In message <0148b086$0$20670$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > On Fri, 05 Dec 2008 13:27:35 +1300, Lawrence D'Oliveiro wrote: > >> In message , Cong >> Ma wrote: >> >>> The "if ... != None" is not necessary... "if PatchDatePat.search(f)" >>> is OK. >> >> I don't do that. > > Perhaps you should? I prefer using explicitly Boolean values for conditions. From andrea.francia at REMOVE-FROM-HERE.ohoihihoihoih.TO-HERE.gmx.it Tue Dec 16 15:03:21 2008 From: andrea.francia at REMOVE-FROM-HERE.ohoihihoihoih.TO-HERE.gmx.it (Andrea Francia) Date: Tue, 16 Dec 2008 20:03:21 GMT Subject: Where is a good open source python project to be used as example? In-Reply-To: References: <05T1l.219074$FR.507685@twister1.libero.it> Message-ID: D'Arcy J.M. Cain wrote: > On Tue, 16 Dec 2008 19:13:00 GMT > Andrea Francia wrote: >> I'm looking for a python project to use as example to learning python. >> >> The project should have these features: >> >> 1. is almost fully unit tested >> 2. use consistently the code convention recommended by PEP 8 >> 3. it's elements are almost fully documented >> >> Extra point features are: >> >> 4. building, assembling, and release automation >> >> Did you know where are such projects? > > http://www.PyGreSQL.org/. > Thanks! But I can't find any unit test in the code. From mrkafk at gmail.com Tue Dec 30 11:22:47 2008 From: mrkafk at gmail.com (mk) Date: Tue, 30 Dec 2008 17:22:47 +0100 Subject: thread, multiprocessing: communication overhead In-Reply-To: References: Message-ID: Aaron Brady wrote: > snips >> def threadsemfun(): >> sem = threading.Semaphore() >> def threadlockfun(): >> sem = threading.Semaphore() > > You used a Semaphore for both lock objects here. Right... I corrected that (simply changed to threading.Lock() in threadlockfun) and the result is much better, though still an order of magnitude worse than plain function: Function: threadlockfun Best: 0.08665 sec Average: 0.08910 sec Function: notfun Best: 0.00987 sec Average: 0.01003 sec > 'multiprocessing' is a really high level layer that makes a lot of > decisions about trade-offs, has highly redundant communication, and is > really easy to use. If you want to save a byte, you'll have to make > your own decisions about trade-offs and redundancies (possibly even > looking at real result data to make them). Hmm, do you think that lower-level 'thread' module might work more efficiently? > I actually think 'multiprocessing' is really good, and even if I hand- > wrote my own IPC, it would be slower! > > CMIIW, but I believe your timing function includes the time to launch > the actual processes and threads, create the synch. objects, etc. You > might try it again, creating them first, starting the timer, then > loading them. Except I don't know how to do that using timeit.Timer. :-/ From asmodai at in-nomine.org Thu Dec 25 04:49:11 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 25 Dec 2008 10:49:11 +0100 Subject: How to display Chinese in a list retrieved from database via python In-Reply-To: References: Message-ID: <20081225094911.GS12670@nexus.in-nomine.org> -On [20081225 08:30], zxo102 (zxo102 at gmail.com) wrote: > Anybody knows how to solve this problem? You are assigning/pushing out Python byte sequences, not Unicode. Look at u'' string variables, x.encode() and x.decode() to help you. It's widely documented on the Internet, a quick Python Unicode (with encode or decode) should get you there. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B Knowledge is soon changed, then lost in the mist, an echo half-heard... From antoine at vo.lu Tue Dec 9 06:06:13 2008 From: antoine at vo.lu (Antoine De Groote) Date: Tue, 09 Dec 2008 12:06:13 +0100 Subject: Guido's new method definition idea In-Reply-To: <79139d04-bd26-4f36-b8c9-19554e7d4e95@e18g2000yqo.googlegroups.com> References: <014a071a$0$20670$c3e8da3@news.astraweb.com> <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> <79139d04-bd26-4f36-b8c9-19554e7d4e95@e18g2000yqo.googlegroups.com> Message-ID: <1349e$493e5125$d9a2276f$3662@news.hispeed.ch> anthony.tolle at gmail.com wrote: > On Dec 6, 4:15 pm, Carl Banks wrote: [...] > > This brings up another question, what would one use when referencing > method names inside the class definition?: > > class C: > def self.method(arg): > self.value = arg > def self.othermethod(arg): > self.value = arg > # do this? > funcs = (self.method, self.othermethod) > # or this? > funcs = (method, othermethod) > > On another related note, I would be interested in seeing this syntax > adopted for a different purpose... > > Normally, if I'm defining a nested function that needs to be stored as > an object attribute, I have to use a dummy name, like the following: > > class C: > def createfunc(self, arg): > def _dummy(arg): > return arg + 1 > self.func = _dummy > > It would be nice to be able to do the following instead: > > class C: > def createfunc(self): > def self.func(arg): > return arg + 1 > > Or, after the class definition is done, to extend it dynamically: > > def C.method(self, arg): > self.value = arg > > ...which would be the equivalent of the following: > > def method(self, arg): > self.value = arg > C.method = method > > Since functions are first-class objects, it seems perfectly reasonable > to me. A decorator might be more advisable here. class C: def createfunc(self): @some_decorator_name def func(arg): return arg + 1 Altough I'm not a huge fan of decorators, this would be more in line what Python already can do an would lean on the @staticmethod and @classmethod decorators. From ivan.illarionov at gmail.com Tue Dec 9 04:42:21 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 9 Dec 2008 01:42:21 -0800 (PST) Subject: Catching Python exceptions in C References: <72713421-97ed-453f-8f2f-06cc5f0ca355@o40g2000prn.googlegroups.com> Message-ID: On Dec 9, 12:33?pm, Ivan Illarionov wrote: > On Dec 8, 9:42?pm, Senthil Kumar wrote: > > > Hi Pythoneers ! > > Can somebody give a quick solution? > > I am trying to raise exceptions in python and trying to handle it in > > C. > > I am able to raise exceptions successfully. However could not catch > > those in C. > > I am using the following function to run the python from C: > > Pyrun_SimpleString(). > > After the exception is raised, I am checking PyErr_Occurred(). It > > always returns NULL, and I cannot catch the exception. > > Pls help me a way out. > > > Thanx in advance ! > > I use something like this: > > if (PyErr_Occurred()) { > ? ? if (PyErr_ExceptionMatches(ExceptionName)) { > ? ? ? ? /* do something about ExceptionName */ > ? ? } else if (PyErr_ExceptionMatches(AnotherExceptionName)) { > ? ? /* if we want to get the exception string */ > ? ? ? ? PyObject *errtype, *errvalue, *traceback; > ? ? ? ? PyErr_Fetch(&errtype, &errvalue, &traceback); > ? ? ? ? if(errvalue != NULL) { > ? ? ? ? ? ? ?PyObject *s = PyObject_Str(errvalue); > ? ? ? ? ? ? ?/* ? ?Now 'PyString_AS_STRING(s)' > ? ? ? ? ? ? ? contains C string of error message > ? ? ? ? ? ? ? do something with it > ? ? ? ? ? ? ?*/ > ? ? ? ? ? ? ?Py_DECREF(s); > ? ? ? ? } > ? ? ? ? Py_XDECREF(errvalue); > ? ? ? ? Py_XDECREF(errtype); > ? ? ? ? Py_XDECREF(traceback); > ? ? } > > } > > Goof luck. And, as others have said, use 'PyRun_String', not 'PyRun_SimpleString' Sorry, I missed this in previous reply. From cesium5500 at yahoo.ca Fri Dec 5 09:13:00 2008 From: cesium5500 at yahoo.ca (Guy Doune) Date: Fri, 05 Dec 2008 09:13:00 -0500 Subject: pretty strange behavior of "strip" In-Reply-To: <4938693F.6090709@yahoo.ca> References: <4938693F.6090709@yahoo.ca> Message-ID: <493936EC.9030606@yahoo.ca> Ok, didn't show the whole problem... I will read the doc anyway, but why "questions.html" keep it "t"?? >>> test=['03.html', '06.html', 'questions.html', '04.html', 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] >>> test[4] 'toc.html' >>> test[4].strip('.html') 'oc' >>> test[2].strip('.html') 'questions' Thanks. Guy Guy Doune a ?crit : > Hi everybody, > > Could it be a bug????? > > Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> test=['03.html', '06.html', 'questions.html', '04.html', > 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test > ['03.html', '06.html', 'questions.html', '04.html', 'toc.html', > '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test[4] > 'toc.html' > >>> test[4].strip('.html') > 'oc' > > Can't figure out what is going on, really. > > Guy > From deets at nospam.web.de Thu Dec 11 09:38:01 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 11 Dec 2008 15:38:01 +0100 Subject: Python, threading References: Message-ID: <6qcmu9Fbna75U1@mid.uni-berlin.de> SMALLp wrote: > Hy. I have a problem! I'm making multi thread application (client, > server) using wxPython for GUI, and threading.Thread for threding. > > Clients connect and when they are connected (evry thread handles one > connection) threads change main window. > > I neded tip how to make communication between threeds. Are you aware that mixing multi-threading and GUIs usually not works the naive way? Read up on your toolkits documentation how to deal with multi-threading. Diez From deets at nospam.web.de Wed Dec 17 10:41:09 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 17 Dec 2008 16:41:09 +0100 Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> Message-ID: <6qskslFehsbrU1@mid.uni-berlin.de> walterbyrd wrote: > For a language as well structured as Python, this seems somewhat > sloppy, and inconsistant. Or is there some good reason for this? > > Here is what I mean: > > def a(): > x = 99 > print x > > def b(): > print x > > a() > b() # raises an exception because x is not defined. > > However in the methods are within a class, the scoping seems to work > differently. > > class ab(): > def a(self): > self.x = 99 > print self.x > def b(self): > print self.x > > i = ab() > i.a() > i.b() # this works, why no lexical scoping? Because what you do is to create instance variables. Why do you expect them not working if you explicitly access them? The real analog of your example would be this: class ab(): def a(self): x = 100 print x def b(self): print x which provokes the same error. however, there *are* different scoping rules, classes don't create a lexical scope for their own variables: class foo(object): x = 100 def a(self): print x Diez From jgardner at jonathangardner.net Tue Dec 30 17:00:39 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Tue, 30 Dec 2008 14:00:39 -0800 (PST) Subject: need help with list/variables References: <63b5acce-d566-48cb-abce-c00fd0e02a39@v39g2000pro.googlegroups.com> Message-ID: On Dec 30, 11:41?am, 5lvqbw... at sneakemail.com wrote: > > >>> conc = lambda x,y: x[:] + y # concatenate 2 lists without side effects > >>> mylist = ['something\n', 'another something\n', 'something again\n'] > >>> myvar = reduce(conc, mylist) > >>> print myvar > "conc"? "side effects"? Missing Lisp much? ;-) Let's try to Pythonize your lisp. One: Assigning a lambda to a variable? Just use def. It's pretty much the same thing. >>> def conc(x,y): return x[:]+y Two: I don't think x+y affects x at all when x and y are lists. (Is that a lispism?) So x[:]+y has an unnecessary array copy. >>> def conc(x,y): return x+y Three: Python may still be slow at string concatenation. (Perl is fast.) Rather than concatenating one at a time, it's better, I understand, to build up a list and then join() them together. The other posters got the right answer in the pythonic way. From steve at REMOVE-THIS-cybersource.com.au Wed Dec 31 17:26:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Dec 2008 22:26:45 GMT Subject: type conversion References: <4b7188db-63b2-4ac5-80cb-d1326ca3694a@q26g2000prq.googlegroups.com> <613a20bf-6e5a-435e-9a83-36766e12f0ab@k8g2000yqn.googlegroups.com> Message-ID: <016be89e$0$6988$c3e8da3@news.astraweb.com> On Wed, 31 Dec 2008 12:35:20 -0800, Hamish McKenzie wrote: > sometimes I want to be able to initialize an instance with a variety of > different data types. Type conversion is a bit of a misleading subject line. You're not really converting different types, just initialising from different types. > as an obvious example I might want to initialize a 4x4 matrix with > either 16 floats, a list/tuple or 16 floats, another matrix or a > quaternion. > > is there any other way to do it other than putting case statements in > the __init__ method of the class, or having a Matrix.FromQuaternion( > quat )? You could have an external function qtom: def qtom(quaternion): a, b, c, d = quaternion return Matrix([ a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 0, 0, 0, 0, d]) But the first two solutions seem reasonable to me, except of course Python doesn't have a case statement you have to use an if...elseif block. -- Steven From ilikefbsd at web.de Sun Dec 28 03:15:12 2008 From: ilikefbsd at web.de (Marco) Date: Sun, 28 Dec 2008 09:15:12 +0100 Subject: python and rcp, portbind communication Message-ID: <49573590.9010308@web.de> Hello python list, i want to write a program in python which can communicate with rpcservices. At the first stage it shall talk with portbind on port 111 and figure out the running rpc services. Is there already a implementation for python to do so? Best regards, marco From 20080915.20.wmcclain at spamgourmet.com Mon Dec 8 16:30:44 2008 From: 20080915.20.wmcclain at spamgourmet.com (Bill McClain) Date: 8 Dec 2008 21:30:44 GMT Subject: StringIO in 2.6 and beyond References: Message-ID: On 2008-12-08, Christian Heimes wrote: > In this context 'str' means Python 3.0's str type, which is unicode in > 2.x. Please report the misleading error message. So this is an encoding problem? Can you give me a hint on how to correct in my example? I see that io.StringIO() has an encoding parameter, but I'm unclear what to specify. -Bill -- Sattre Press History of Astronomy http://sattre-press.com/ During the 19th Century info at sattre-press.com by Agnes M. Clerke http://sattre-press.com/han.html From v+python at g.nevcal.com Tue Dec 2 22:47:59 2008 From: v+python at g.nevcal.com (Glenn Linderman) Date: Tue, 02 Dec 2008 19:47:59 -0800 Subject: Simple ini Config parser examples needed In-Reply-To: <47c890dc0812021522g7f42b00o2a831bac1e15aa05@mail.gmail.com> References: <47c890dc0812021331m1fe3f420kce9bcb07df5ae44e@mail.gmail.com> <4935BBE5.3020607@g.nevcal.com> <47c890dc0812021522g7f42b00o2a831bac1e15aa05@mail.gmail.com> Message-ID: <4936016F.8010401@g.nevcal.com> On approximately 12/2/2008 3:22 PM, came the following characters from the keyboard of Chris Rebert: > On Tue, Dec 2, 2008 at 2:51 PM, Glenn Linderman wrote: > >> On approximately 12/2/2008 1:31 PM, came the following characters from the >> keyboard of Chris Rebert: >> >>> On Tue, Dec 2, 2008 at 1:18 PM, RON BRENNAN >>> wrote: >>> >>> >>>> Hello, >>>> >>>> I have a very simple ini file that I needs parsed. What is the best way >>>> I >>>> can parse an ini file that doesn't include sections? >>>> > > *Bangs head against wall repeatedly* > I merely glossed the question and missed that all-important second > sentence! fsck! > My apologies, I shouldn't write email before having coffee :) > Fortunately Tim followed quickly with the correct answer to the OP. > Tim provided a correct-looking answer, albeit somewhat complex, as it doesn't reuse the logic in the ConfigParser. That's why I suggested yet another alternative, yet left one key item off myself (added below). >>>> As in: >>>> >>> Since it appears that ConfigParser requires at least one section >>> header, I'll assume the file starts with the following line: >>> >>> [main] >>> >>> >>>> person=tall >>>> height=small >>>> shoes=big >>>> >>>> >>>> Thats it. Can anyone help me? >>>> >>>> >>> Completely untested: >>> >>> import ConfigParser >>> config = ConfigParser.RawConfigParser() >>> config.readfp(open("path/to/file.cfg")) >>> config.get("main", "height") #==> "small" >>> >>> Cheers, >>> Chris >>> >>> >> Of course the OP question was that the line you assume isn't there. But if >> the ini is simple, maybe it is short enough to read into a string, then >> prepend the line, then parse with ConfigParser. >> And I meant to add "parse with ConfigParser by passing the combined string in via StringIO. -- Glenn -- http://nevcal.com/ =========================== A protocol is complete when there is nothing left to remove. -- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking From lists at cheimes.de Tue Dec 16 15:24:44 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 16 Dec 2008 21:24:44 +0100 Subject: sys.maxint in Python 2.6.1 (amd64) on Windows XP x64 In-Reply-To: <7a629cb1-0fbc-41d4-ac51-d0be68df1df5@r36g2000prf.googlegroups.com> References: <4bddf65a-bb9f-406c-a544-8c38b27547a7@b38g2000prf.googlegroups.com> <7a629cb1-0fbc-41d4-ac51-d0be68df1df5@r36g2000prf.googlegroups.com> Message-ID: Lin schrieb: > Ah, this makes sense. Thanks...... The main reason I'm trying 64-bit > Python is that I want to write files bigger than 4GB. This should work > on Windows x64, right? (i.e., are the pointers bona fide 64 bit?) You can create files with more than 4GB on a 32bit OS, too. It depends on the file system. It works with NTFS but I'm not sure how FAT32 deals with large files. My DVB-S receiver with USB port chokes on files with more than 2 GB. Christian From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 00:21:25 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Dec 2008 05:21:25 GMT Subject: "as" keyword woes References: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> <0147dc24$0$20670$c3e8da3@news.astraweb.com> Message-ID: <0148b217$0$20670$c3e8da3@news.astraweb.com> On Thu, 04 Dec 2008 08:44:19 -0800, Matimus wrote: > The point was that there > is that new releases don't _break_ anything. But that's clearly not true, because the OP is pointing out that the new release from 2.5 to 2.6 *does* break his code. -- Steven From hongqn at gmail.com Fri Dec 26 00:44:11 2008 From: hongqn at gmail.com (Qiangning Hong) Date: Thu, 25 Dec 2008 21:44:11 -0800 (PST) Subject: sys.stdout.write()'s bug or doc bug? Message-ID: >>> u = u'\u554a' >>> print u ? >>> sys.stdout.write(u) Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\u554a' in position 0: ordinal not in range(128) >>> type(sys.stdout) >>> sys.stdout.encoding 'UTF-8' Quote from file object's documentation: encoding The encoding that this file uses. When Unicode strings are written to a file, they will be converted to byte strings using this encoding. ..... So, my question is, as sys.stdout IS a file object, why it does not use its encoding attribute to convert the given unicode? An implementation bug? A documenation bug? From clp at rebertia.com Sun Dec 7 04:05:55 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 7 Dec 2008 01:05:55 -0800 Subject: var or inout parm? In-Reply-To: References: Message-ID: <47c890dc0812070105l24953730tc450c49ea30658ed@mail.gmail.com> On Sun, Dec 7, 2008 at 12:54 AM, wrote: > How can I make a "var" parm, where the called function can modify > the value of the parameter in the caller? Not directly possible or encouraged. You can emulate it by sticking the value in a container object (e.g. list) though: def f(x): x[0] += 1 #non-augmented assignment would work too n = [1] f(n) print n[0] #==> 2 Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > def f(x): > x = x + 1 > > n = 1 > f(n) > # n should now be 2 > > Many TIA!! > Mark > > > -- > Mark Harrison > Pixar Animation Studios > -- > http://mail.python.org/mailman/listinfo/python-list > From rocky at panix.com Wed Dec 10 16:07:15 2008 From: rocky at panix.com (R. Bernstein) Date: Wed, 10 Dec 2008 16:07:15 -0500 Subject: pydb 1.24 Message-ID: This release is to clear out some old issues. It contains some bugfixes, document corrections, and enhancements. Tests were revised for Python 2.6 and Python without readline installed. A bug involving invoking from ipython was fixed. The "frame" command is a little more like gdb's. Exceptions are now caught in runcall(). This is the last release contemplated before a major rewrite. download: https://sourceforge.net/project/showfiles.php?group_id=61395&package_id=175827 bug reports: https://sourceforge.net/tracker/?group_id=61395&atid=497159 From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 29 07:19:38 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 29 Dec 2008 13:19:38 +0100 Subject: AttributeError: 'module' object has no attribute 'DatagramHandler' (ubuntu-8.10, python 2.5.2) In-Reply-To: <4c6f0831-c05f-401f-b956-376600b38e06@r15g2000prd.googlegroups.com> References: <4c6f0831-c05f-401f-b956-376600b38e06@r15g2000prd.googlegroups.com> Message-ID: <4958c059$0$16065$426a34cc@news.free.fr> Tzury Bar Yochay a ?crit : > $ ~/devel/ice/snoip/freespeech$ python > Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) > [GCC 4.3.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import logging >>>> logging.DatagramHandler > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute 'DatagramHandler' > > > That is odd since the documentation says there is DatagramHandler for > module logging It also says that DatagramHandler is located in the logging.handlers modules: http://www.python.org/doc/2.5.2/lib/node415.html HTH From google at mrabarnett.plus.com Thu Dec 4 14:40:49 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 04 Dec 2008 19:40:49 +0000 Subject: Python 3 read() function In-Reply-To: References: Message-ID: <49383241.4050708@mrabarnett.plus.com> Terry Reedy wrote: > ?????? ??????????? wrote: >>> I don't think it matters. Here's a quick comparison between 2.5 and >>> 3.0 on a relatively small 17 meg file: >>> >>> C:\>c:\Python30\python -m timeit -n 1 >>> "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" >>> 1 loops, best of 3: 36.8 sec per loop >>> >>> C:\>c:\Python25\python -m timeit -n 1 >>> "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" >>> 1 loops, best of 3: 33 msec per loop >>> >>> That's 3 orders of magnitude slower on python3.0! >> >> Isn't this because you have the file cached in memory on the second run? > > In my test, I read Python25.chm with 2.5 and Python30.chm with 3.0. > > Rereading Python30.chm without closing *is* much faster. > >>> f=open('Doc/Python30.chm','rb') > >>> d=f.read() > >>> d=f.read() > >>> d=f.read() > Closing, reopening, and rereading is slower. > It certainly is faster if you're already at the end of the file. :-) From kirk at daycos.com Thu Dec 11 11:31:36 2008 From: kirk at daycos.com (Kirk Strauser) Date: Thu, 11 Dec 2008 10:31:36 -0600 Subject: Do more imported objects affect performance References: Message-ID: <874p1a1xnb.fsf@daycos.com> At 2008-12-01T11:30:44Z, Nick Craig-Wood writes: > Importing the module is actualy slower... If you import the name into > your namespace then there is only one lookup to do. If you import the > module there are two. Note that if you're importing the entire module but want to call a function that many times, you can do something like: import timeit Timer = timeit.Timer for _ in xrange(1000000): Timer -- Kirk Strauser The Day Companies From rt8396 at gmail.com Thu Dec 18 16:41:30 2008 From: rt8396 at gmail.com (r) Date: Thu, 18 Dec 2008 13:41:30 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <71ede5f0-fd88-4155-9f0d-42d0ad5f57dc@v42g2000yqj.googlegroups.com> <61f45e65-2404-4cc0-9d81-f848c1ba566f@i18g2000prf.googlegroups.com> Message-ID: <9136d71c-01cf-48fa-a5cf-6b445e882eb1@n10g2000vbl.googlegroups.com> On Dec 18, 1:48?pm, Roger wrote: > On Dec 18, 12:49?pm, r wrote: > > > Maybe someone will chime in with an answer, sorry i could not help. > > ponder this, i must... > > Regardless, thanks for your help! I truly appreciate it. > > Roger. 'no problema mi amigo!'.to_english(no problem my friend!) :) From prologic at shortcircuit.net.au Tue Dec 16 01:03:55 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 16 Dec 2008 16:03:55 +1000 Subject: socket and subprocess problem In-Reply-To: <73dca20d-3378-4c96-aa30-f0617f111fa0@i18g2000prf.googlegroups.com> References: <6d3291c3-4e12-4bdd-884a-21f15f38d105@a12g2000pro.googlegroups.com> <73dca20d-3378-4c96-aa30-f0617f111fa0@i18g2000prf.googlegroups.com> Message-ID: On Tue, Dec 16, 2008 at 3:30 PM, wrote: > Guys thanks to point it out. > Yes, it's a race problem. I tried sleep long enough, then I can > connect to the socket. I should add code to try to connect to the > socket for a given time out. This is where event-driven approaches become really useful :) subprocess process: #1. When my subprocess process has successfully started notify the parent. #2. When my subprocess process has successfully created a listening socket, notify the parent. parent process: #1. When our subprocess process has successfully started a listening socket initiate a connection. I could implement a prototype of this if the OP is interested. --JamesMills From clp at rebertia.com Tue Dec 23 02:11:53 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 22 Dec 2008 23:11:53 -0800 Subject: String Format Error. In-Reply-To: References: Message-ID: <47c890dc0812222311m2a67b798v167b40de9dfcd53d@mail.gmail.com> On Mon, Dec 22, 2008 at 10:19 PM, Paulo Repreza wrote: > Hi, > > I'm a newbie with python and I recently bought Beginning with Python (Which > is a book I recommend) but the problem that I'm facing it's the following: > > This is the code: > > #!/usr/bin/python2.5 > # Filename: str_format.py > > age = 25 > name = 'foobar' > > print('{0} is {1} years old'.format(name, age)) > print('Why is {0} playing with that python?'.format(name)) > > > But when I run the script I receive this error: > > Traceback (most recent call last): > File "str_format.py", line 7, in > print('{0} is {1} years old'.format(name, age)) > AttributeError: 'str' object has no attribute 'format' > > > It is an error because of the version that I'm using ? Python 2.5.2 (Debian > lenny) Yes, Python 2.6 or higher is required to use .format() according to http://docs.python.org/whatsnew/2.6.html Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From rhodri at wildebst.demon.co.uk Thu Dec 11 20:58:22 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Fri, 12 Dec 2008 01:58:22 -0000 Subject: newbie question: if var1 == var2: In-Reply-To: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> Message-ID: On Thu, 11 Dec 2008 23:49:10 -0000, John Machin wrote: > On Dec 12, 10:31?am, "Rhodri James" > wrote: >> On Thu, 11 Dec 2008 19:49:23 -0000, Steve Holden ? >> wrote: >> > ... and it's so hard to write >> >> > ? ? ?item = item[:-1] >> >> Tsk. ?That would be "chop". ?"chomp" would be >> >> ? ? ?if item[-1] == '\n': >> ? ? ? ? ?item = item[:-1] > > Better: > if item and item[-1] == '\n': > return item[:-1] > return item If we aren't going for rstrip, yes, but I was trying to stick to Steve's metier. -- Rhodri James *-* Wildebeeste Herder to the Masses From eric at ericaro.net Fri Dec 19 12:36:31 2008 From: eric at ericaro.net (eric) Date: Fri, 19 Dec 2008 09:36:31 -0800 (PST) Subject: best way to code References: Message-ID: On Dec 19, 5:35?pm, Peter Otten <__pete... at web.de> wrote: > eric wrote: > > hi, > > > I need to find a "good" design pattern to instanciate, and add > > specific code all in one. Let me explain it : > > > I need to define "some" code, better be in a class, something like > > > class LinkA(object): > > ? ? def mystuff(self): > > ? ? ? ? ? > > > class LinkB(object): > > ? ? def mystuff(self): > > ? ? ? ? ? > > > AND I need an instance of this class > > { "stuff A": LinkA() > > ? "stuff B": LinkB() > > } > > > This kind of code "would" be fine, I mean, the result effect in memory > > is fine for me. > > But I don't like the way I have to > > 1/ give a useless name to LinkA, linkB (there can be hundreds of names > > like that) > > 2/ I have to write it down two times (and that's one time too much) > > > any ideas ? > > > something like > > [ > > new object(): > > ? ? def mystuff(self): > > ? ? ? ? > > , > > new object(): > > ? ? def mystuff(self): > > ? ? ? ? > > ] > > > would be really perfect (but I know it does not work, or at least, I > > don't know how to make it work) > > > In fact, I would like to define a class, and an instance in a single > > statement > >>> class Register: > > ... ? ? def __init__(self): > ... ? ? ? ? ? ? self.items = [] > ... ? ? def __call__(self, method): > ... ? ? ? ? ? ? class Link(object): > ... ? ? ? ? ? ? ? ? ? ? mystuff = method > ... ? ? ? ? ? ? self.items.append(Link()) > ...>>> register = Register() > >>> @register > > ... def mystuff(self): print "first" > ...>>> @register > > ... def mystuff(self): print "second" > ...>>> for item in register.items: > > ... ? ? item.mystuff() > ... > first > second > > Peter hi, I've tried something like this : import inspect class Test(object): class Inner(object): def mystuff(self): print "hello stuff" class InnerB(object): def mystuff(self): print "hello B" def filter(member): return inspect.isclass(member) and not member==Test.__class__ d = dict( (name, c()) for name, c in inspect.getmembers(Test, filter ) ) print d it works too, but I prefer your method thanks -- Eric http://codeslash.blogspot.com From christophedeze at gmail.com Tue Dec 23 03:23:50 2008 From: christophedeze at gmail.com (Toff) Date: Tue, 23 Dec 2008 00:23:50 -0800 (PST) Subject: join a samba domain References: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> <494fd597$0$90267$14726298@news.sunsite.dk> <73194a24-f14e-46f1-8789-886ba4729084@r15g2000prd.googlegroups.com> Message-ID: <1a326512-3c74-404d-9c51-fde35f39702e@t39g2000prh.googlegroups.com> On 22 d?c, 19:37, Toff wrote: > On 22 d?c, 18:59, Jens Henrik Leonhard Jensen > > wrote: > > Toff wrote: > > > ? ?d = c.Win32_ComputerSystem > > > ? ?d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") > > > Shouldn't r"admin\\mydom" be "admin\\mydom" or r"admin\mydom". > > Or maybe just "admin" > > > /Jens Henrik > > you are right but i've got the same error. the more i look at my script the more i think it s a BUG. #ALL works great import wmi c = wmi.WMI() for computer in c.Win32_ComputerSystem(): if computer.PartOfDomain: print computer.Domain #DOMCD print computer.SystemStartupOptions # (u'"Microsoft Windows XP Professionnel" /noexecute=optin /fastdetect',) #error message computer.JoinDomainOrWorkGroup('DOMCD', 'adminLocal', 'admin\ \DOMCD',None,3 ) ############## DOMCD (u'"Microsoft Windows XP Professionnel" /noexecute=optin / fastdetect',) Traceback (most recent call last): File "integrdom.py", line 51, in main() File "integrdom.py", line 13, in main joindom() File "integrdom.py", line 47, in joindom computer.JoinDomainOrWorkGroup('DOMCD', 'adminLocal', 'admin\ \DOMCD',None,3 ) File "c:\Python25\Lib\site-packages\wmi.py", line 493, in __getattr__ handle_com_error (error_info) File "c:\Python25\Lib\site-packages\wmi.py", line 189, in handle_com_error raise x_wmi, "\n".join (exception_string) wmi.x_wmi From skip at pobox.com Thu Dec 4 19:33:40 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 4 Dec 2008 18:33:40 -0600 Subject: Importing Version Specific Modules In-Reply-To: <558b73fb0812041529g313a27bpcfd09fc90f474f6e@mail.gmail.com> References: <558b73fb0812041529g313a27bpcfd09fc90f474f6e@mail.gmail.com> Message-ID: <18744.30436.32591.969670@montanaro-dyndns-org.local> Michael> if sys.version_info[:2] >= (2, 5): Michael> from string import Template Michael> else: Michael> from our.compat.string import Template This is "look before you leap" (LBYL). Michael> try: Michael> from string import Template Michael> except ImportError: Michael> from our.compat.string import Template This is "easier to ask forgiveness than permission" (EAFP). This tends to be more Pythonic (and thus, preferred). You don't *really* care what the version just, but whether or not the string module has a Template object. Besides, what if some bright admin at some customer decides to backport the Template implementation to their 2.4 installation? The first form would load your compatibility version, probably not what they were hoping when they put in the effort to backport. This might be more obvious if the example was ctypes, a module which is available recently as part of Python proper, but can also be built for older versions of Python (for some vague definition of "older"). Some of your customers might have installed the external version to work with their Python installation. Your simple version test would miss that. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From lewis.sarah93 at yahoo.com Thu Dec 4 23:43:25 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 20:43:25 -0800 (PST) Subject: Reduice Debt Message-ID: <7dc218e0-caba-4834-85eb-44fb5eefa469@w34g2000yqm.googlegroups.com> Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From warren at delsci.com Sat Dec 6 14:38:51 2008 From: warren at delsci.com (Warren DeLano) Date: Sat, 6 Dec 2008 11:38:51 -0800 Subject: "as" keyword woes Message-ID: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> > Date: Fri, 05 Dec 2008 22:22:38 -0800 > From: Dennis Lee Bieber > Subject: Re: "as" keyword woes > To: python-list at python.org > Message-ID: > > I'm still in the dark as to what type of data could > even inspire the > use of "as" as an object name... A collection of "a" objects? In which > case, what are the "a"s? Please let me clarify. It is not "as" as a standalone object that we specifically miss in 2.6/3, but rather, the ability to use ".as" used as a method or attribute name. In other words we have lost the ability to refer to "as" as the generalized OOP-compliant/syntax-independent method name for casting: new_object = old_object.as(class_hint) # For example: float_obj = int_obj.as("float") # or float_obj = int_obj.as(float_class) # as opposed to something like float_obj = int_obj.asFloat() # which requires a separate method for each cast, or float_obj = (float)int_obj # which required syntax-dependent casting [language-based rather than object-based]. Of course, use of explicit casting syntax "(float)" is fine if you're restricting yourself to Python and other languages which support casting, but that solution is unavailable inside of a pure OOP message-passing paradigm where object.method(argument) invocations are all you have to work with. Please note that use of object.asClassname(...) is a ubiqitous convention for casting objects to specific classes (seen in ObjectiveC, Java, SmallTalk, etc.). There, I assert that 'object.as(class_reference)' is the simplest and most elegant generalization of this widely-used convention. Indeed, it is the only obvious concise answer, if you are limited to using methods for casting. Although there are other valid domain-specific uses for "as" as either a local variable or attribute names (e.g. systematic naming: as, bs, cs), those aren't nearly as important compared to "as" being available as the name of a generalized casting method -- one that is now strictly denied to users of Python 2.6 and 3. As someone somewhat knowledgable of how parsers work, I do not understand why a method/attribute name "object_name.as(...)" must necessarily conflict with a standalone keyword " as ". It seems to me that it should be possible to unambiguously separate the two without ambiguity or undue complication of the parser. So, assuming I now wish to propose a corrective PEP to remedy this situation for Python 3.1 and beyond, what is the best way to get started on such a proposal? Cheers, Warren From manu3d at gmail.com Sun Dec 14 08:00:18 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Sun, 14 Dec 2008 05:00:18 -0800 (PST) Subject: Bidirectional Networking References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <6qeht0Fc3541U1@mid.individual.net> <782258db-2bdc-45a7-8d8f-7a036d574985@t26g2000prh.googlegroups.com> <2cf74767-e331-4fa6-8915-8f87ba01ca34@l33g2000pri.googlegroups.com> Message-ID: On Dec 14, 4:10 am, "Gabriel Genellina" wrote: > daemon became a property in Python 2.6; setDaemon was the only way to set > it in previous versions. I thought that might be the case! The documentation is a bit vague: http://docs.python.org/library/threading.html?highlight=threading#threading.Thread.setDaemon Should we maybe add "New in 2.6" to the Thread.daemon paragraph? Manu From jcd at sdf.lonestar.org Fri Dec 12 10:35:11 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Fri, 12 Dec 2008 10:35:11 -0500 Subject: newbie question: if var1 == var2: In-Reply-To: <87y6ymzecp.fsf@daycos.com> References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> <87y6ymzecp.fsf@daycos.com> Message-ID: <1229096111.26125.3.camel@aalcdl07.lib.unc.edu> On Thu, 2008-12-11 at 13:44 -0600, Kirk Strauser wrote: > At 2008-12-11T17:24:44Z, rdmurray at bitdance.com writes: > > > >>> ' ab c \r\n'.rstrip('\r\n') > > ' ab c ' > > >>> ' ab c \n'.rstrip('\r\n') > > ' ab c ' > > >>> ' ab c '.rstrip('\r\n') > > ' ab c ' > > I didn't say it couldn't be done. I just like the Perl version better. Python has a version equally good: def chomp(s): return s.rstrip('\r\n') chomp("foo\n") chomp("foo") chomp("perl\r\n") You'll hardly miss Perl at all. ;) From jody.goldberg at gmail.com Mon Dec 8 20:19:27 2008 From: jody.goldberg at gmail.com (JodyGnumeric) Date: Mon, 8 Dec 2008 17:19:27 -0800 (PST) Subject: getting error...... Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in open_workbook biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) File "C:\Python25\Lib\site-pack References: <6c76b050-5b47-46f3-9097-5c58979b6913@s9g2000prg.googlegroups.com> Message-ID: <16d767d6-be4a-49eb-af5c-3d9e74b45458@m22g2000vbl.googlegroups.com> On Dec 8, 5:54?am, John Machin wrote: > On Dec 8, 6:48?pm, "Gabriel Genellina" wrote: > > > > > En Fri, 05 Dec 2008 02:31:01 -0200, pk sahoo ? > > escribi?: > > > > hallo everybody, > > > when i am running the following command > > > >>>> import xlrd > > >>>> book=xlrd.open_workbook("C:\\a.xls") > > > > i am getting the following error.. > > > > *Traceback (most recent call last): > > > ? File "", line 1, in > > > ? File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in > > > open_workb > > > ook > > > ? ? biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) > > > ? File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 1323, in > > > getbof > > > ? ? raise XLRDError('Expected BOF record; found 0x%04x' % opcode) > > > xlrd.biffh.XLRDError: Expected BOF record; found 0x3f3c* > > > Looks like your a.xls file is not an Excel file (one of the formats ? > > supported by xlrd). > > As 0x3f3c corresponds to the characters ' > This can be verified easily by opening the file with a simple-minded > text editor (e.g. Notepad) ... if the first two lines are > """ > > > """ > then it's an Excel 2003 XML Spreadsheet that's been manually(?) > renamed from .xml to .xls. > > The current xlrd release supports only the binary ("BIFF") format .xls > files created by Excel 3.0 to Excel 2003. The next release (due out > Real Soon Now) will support Excel 2.1 and 2.0 formats [don't ask]. > Very soon after that will come support for Excel 2007 .xlsx which is a > bunch of XML files inside a ZIP file. Support for Excel 2003 > "SpreadsheetML" is way down the to-do list. > > If the OP wants to be able to read the file with xlrd: > (1) Open it with Excel 200[37] and save as a .xls file > or (2) rename it to .xml, start OpenOffice.org Calc, click on File, > click on Open, click on "Files of type", choose "Microsoft Excel 2003 > XML (*.xml)" from the (long, unsorted) drop-down list, ..., and save > as etc etc. Gnumeric is not an option. > > HTH, > John Gnumeric can read this format. 'MS Excel (tm) 2003 SpreadsheetML' From rt8396 at gmail.com Mon Dec 22 12:13:41 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 09:13:41 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: I think when Python was first brought to this dark world by a genius named Guido van Rossum, it had complete dominance in it's niche, actually Python created a niche where none existed before. Since the advent of Ruby(Python closet competitor), Python's hold on this niche is slipping. A lot of Ruby noobies don't even realize that most of Ruby is an out-right plagiarism of Python. But I guess that's OK, because Python has borrowed from other languages itself.. just not in such a -sell your soul- kind of way as Ruby!. Now since Python *is not* the only language on it's block, we have to compete with our main nemesis(Ruby) for survival(I wonder if mats would have been so revolutionary to introduce indention if Guido had not done it first??, it seems to me he is a braces fanboy ;) Now more than ever we must stick to the Zen and clean up Python's warts to keep the dream alive and regain our right full crown. Python is better than Ruby, I have no doubt in my mind, but if we let ruby become -faster- than Python, people will gravitate away from Python. Speed IS important even in high level languages. We must never forget that! The war is not over just because we have Google, Nasa, and ILM. On the Contrary, it has just begun. I believe mats is not going to accept Ruby as 2nd best to Python, he will wage war on Pythonia. And if we fail to preempt this attack, we shall be like the burning ships of pearl harbor! Maybe Guido has a secret weapon up his sleeve(big boy), but 3.0 was defiantly not the bomb! Mats will now take advantage of the weaknesses in Py3000 and run with them. Whispering in everyones ear how much faster Ruby is to Python. And weather you like to hear it or not, this ROR thing is exploding, we must counter attack this vile disgrace to Pythonia. Do not sit back and say "well we are the best and we don't need to try any harder". For you will be left in the evolutionary dust of Ruby. And next year, left wanting... We need to sound the battle cries and gather the legions. Then we shall march across Rubonia and *raise* their cities to the ground. We shall encompass thy house O' Ruby -- and lay waste to it! After we slay thee, we shall breed with thy women and convert thy children. We shall rule with an iron fist!, crushing all resistance to Python's absolute power. Like the great kings of olde, monuments will be erected so all generations shall be witness of our power, and glory. """ O' Python, for the sound of thy chariots will be so fear full no army could stand against thee!""" We shall avenge the atrocities and hypocrocies you have brought upon this world Ruby! And then you shall know that we are the Lord of this world, when our vengeance is cast upon you! I will be monitoring comp.lang.python and over the next 6 months I will conduct a census of the users of this group. So far I have only seen maybe 20 regulars here. I had hoped they numbered several thousand, but i am starting to think more in the hundreds or even less :(. I will post my findings to this group. It shall be a wake up call for those of you who think the war is over. Get off your bums you lazy-coach-potatos, the fight is not over yet. Do not let your eye's become "wide shut"!!! Truth shall be the judge... From castironpi at gmail.com Tue Dec 16 20:36:22 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 16 Dec 2008 17:36:22 -0800 (PST) Subject: How to modify a program while it's running? References: <01584cbd$0$20656$c3e8da3@news.astraweb.com> Message-ID: <1fe20306-39ff-4169-b49e-5ae5dd8159af@v5g2000prm.googlegroups.com> On Dec 16, 7:26?pm, Steven D'Aprano wrote: > On Tue, 16 Dec 2008 13:25:17 -0700, Joe Strout wrote: > > So I'd like to restructure my app so that it can stay running and stay > > logged in, yet I can still update and reload at least most of the code. > > But I'm not sure what's the best way to do this. ?Should I move the > > reloadable code into its own module, and then when I give my bot a > > "reload" command, have it call reload on that module? ?Will that work, > > and is there a better way? > > That should work for functions, but less successfully with classes. The > problem is that existing objects will still have the old behaviour even > after reloading the class. Good catch, Mr. Steven. You could re-query on every call to a method with __getattr__. def __getattr__( I, name ): cls= module.class_to_query return cls.__getattr__( I, name ) #need to call __get__ on this That way, when 'class_to_query' changes, the behavior changes. Here's the implementation: >>> class Behavior( object ): ... def methA( I ): ... print 'methA one' ... >>> class Dynamic( object ): ... def __getattr__( I, key ): ... return getattr( Behavior, key ).__get__( I, Behavior ) ... >>> x= Dynamic( ) >>> x.methA( ) methA one >>> class Behavior( object ): ... def methA( I ): ... print 'methA two' ... >>> x.methA( ) methA two You would have to soft-code 'Behavior' into the initializer of 'Dynamic' as a string, not the class object. From warren at delsci.com Sat Dec 6 23:19:08 2008 From: warren at delsci.com (Warren DeLano) Date: Sat, 6 Dec 2008 20:19:08 -0800 Subject: "as" keyword woes Message-ID: <896B75251BA19745A529B1B867893FA5DB11@planet.delsci.local> > Date: Sat, 6 Dec 2008 12:13:16 -0800 (PST) > From: Carl Banks > Subject: Re: "as" keyword woes > To: python-list at python.org > Message-ID: > > (snip) > > If you write a PEP, I advise you to try to sound less whiny and than > you have in this thread. > > (snip) Ehem, well, such comments notwithstanding, I thank everyone who responded to my latest post on this topic for taking my inquiry seriously, and for providing cogent, focused, well-reasoned feedback while not resorting to name-calling, to false accusations on top of baseless assumptions, or to explicit personal attacks on my competence, sincerity, experience, credibility, or form. To you especially, I am grateful for your input for your years of service to the community and to the noble ideals you embody in the Python project. May the rest of us (not just myself) be ashamed of our lesser conduct and learn from you exemplary performance. So to summarize, having assimilated all responses over the past several days (python-list as well as python-dev, for the newcomers), I now accept the following as self-evident: -> "as", as a Python keyword, is a here to stay: Love it or leave it. -> Likewise ditto for the GIL: if you truly need Python concurrency within a single process, then use a Python implementation other than CPython. Season's greetings to all! Peace. Cheers, Warren From see.signature at no.spam Tue Dec 16 10:51:58 2008 From: see.signature at no.spam (Eric Brunel) Date: Tue, 16 Dec 2008 16:51:58 +0100 Subject: Structure using whitespace vs logical whitespace References: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> Message-ID: On Tue, 16 Dec 2008 10:00:32 +0100, Gabriel Genellina wrote: > En Mon, 15 Dec 2008 14:29:31 -0200, cmdrrickhunter at yaho.com > escribi?: > >> PS. In my opinion the solution would be to have the option of entering >> a "whitespace insensitive" mode which uses C style {} and ;. The >> token to enter it could be as complicated as you want (in fact, it may >> make sense to make it complicated to discourage use unless it's really >> advantageous). I'd sugest {{ and }} or something bigger like {={ } >> =}. Only two problems: 1) I'm sure it would offend Guido's sense of >> language aesthetics 2) I'm sure the idea has been hashed over on this >> newsgroup to death... hence prefering a workaround instead. > > It's a hidden feature, already implemented. Try: > > from __future__ import braces I was almost shocked so I tried it. It's much clearer now... ;-) -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From David Fri Dec 26 21:34:45 2008 From: David (David) Date: Fri, 26 Dec 2008 20:34:45 -0600 Subject: math.sqrt() in new 3.0 version : solution in input() References: Message-ID: On Fri, 26 Dec 2008 15:52:24 -0600, David Lemper wrote: >At the command line this function works correctly > >>> import math > n = input("enter a number > ") > s = math.sqrt(n) > An entry of 9 or 9.0 will yield 3.0 > >Yet the same code in a script gives an error message > Script1 > import math > n = input("enter a number > ") > s = math.sqrt(n) > > Traceback (most recent call last) : > File "", line 1, in > File "script1.py" line 3 in > s = math.sqrt(n) > TypeError : a float is required Problem is the new input() function. Yields a string. Thanks to Scott, Chris, Gabriel & John. Some thought I was not using the Python 3 command line. I was : Python 3.0 (r30:67507... Erratic behavior was that I was sometimes using n = input() and sometimes entering the integer directly into the math.sqrt() function, eg s = math.sqrt(4194304) I cannot find a mention of this in "The Python Tutorial release 3.1" The I&O section discusses output formatting and reading & writing text files. John pointed out its in Guido's "What's New in Python3.0" Indeed its mentioned in PEP 3111, near end of What's New and somewhat obscurely. " raw_input() was renamed to input(). That is the new input() function function reads a line from sys.stdin . . ." Dave Lemper, Texas From google at mrabarnett.plus.com Thu Dec 11 19:39:24 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 12 Dec 2008 00:39:24 +0000 Subject: newbie question: if var1 == var2: In-Reply-To: <44aa0191-e374-4bf0-b039-d05cfa996b1d@p2g2000prn.googlegroups.com> References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> <44aa0191-e374-4bf0-b039-d05cfa996b1d@p2g2000prn.googlegroups.com> Message-ID: <4941B2BC.7080806@mrabarnett.plus.com> Jason Scheirer wrote: > On Dec 11, 3:49 pm, John Machin wrote: >> On Dec 12, 10:31 am, "Rhodri James" >> wrote: >> >> >> >>> On Thu, 11 Dec 2008 19:49:23 -0000, Steve Holden >>> wrote: >>>> Kirk Strauser wrote: >>>>> At 2008-11-29T04:02:11Z, Mel writes: >>>>>> You could try >>>>>> for item in fname: >>>>>> item = item.strip() >>>>> This is one case where I really miss Perl's "chomp" function. It >>>>> removes a >>>>> trailing newline and nothing else, so you don't have to worry about >>>>> losing >>>>> leading or trailing spaces if those are important to you. >>>> ... and it's so hard to write >>>> item = item[:-1] >>> Tsk. That would be "chop". "chomp" would be >>> if item[-1] == '\n': >>> item = item[:-1] >> Better: >> if item and item[-1] == '\n': >> return item[:-1] >> return item > > Best: > > return item \ > if not (item and item.endswith('\n')) \ > else item[:-1] > > Though really you should be using item.rstrip() > Why not just: item[:-1] if item.endswith('\n') else item From Graham.Dumpleton at gmail.com Sat Dec 20 03:42:42 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Sat, 20 Dec 2008 00:42:42 -0800 (PST) Subject: mod_python resources References: <78064e7e-ba2c-4959-b5f8-4d1b928bc5fe@y18g2000yqn.googlegroups.com> <4lsl16-15a.ln1@archaeopteryx.softver.org.mk> Message-ID: On Dec 20, 2:47?pm, "Anjanesh Lekshminarayanan" wrote: > Same requirement here. > But isnt there any mod_python for Python 3.0 ? > Or do we need to build it from source ourselves ? > > I was hoping there would bemod_wsgibinaries for Python 3.0. At this stage it looks like there will not be a mod_python for Python 3.0. If you want the ability to run Python embedded in Apache like mod_python did, use a framework that can host on top of WSGI and host it on mod_wsgi instead. The version of mod_wsgi in subversion repository already supports Python 3.0. Graham From igouy2 at yahoo.com Sat Dec 13 10:17:00 2008 From: igouy2 at yahoo.com (Isaac Gouy) Date: Sat, 13 Dec 2008 07:17:00 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <25b4d503-5073-4e66-8914-ca5fa7b144e1@w39g2000prb.googlegroups.com> Message-ID: <4bb159b5-528c-481e-bfde-9b326a37daa6@u18g2000pro.googlegroups.com> On Dec 12, 6:58?am, bearophileH... at lycos.com wrote: > sturlamolden: > > > On a recent benchmark Java 6 -server beats C compiled by GCC 4.2.3 And > > most of that magic comes from an implementation of a dynamically typed > > language (Smalltalk). [...] > >http://shootout.alioth.debian.org/u32q/benchmark.php?test=all?=all > > That is indeed a nice result, JavaVM has come a long way from the > first one used for applets. That result comes mostly from the fact > that this is a test on a 4-core CPU, that is less easy to manage from > C. You can see that in the single 64-bit core tests:http://shootout.alioth.debian.org/u64/benchmark.php?test=all?=all Whether or not it's less easy to manage from C is unclear, but you are correct to point out few of those C programs have been updated to exploit quadcore - so the reasonable comparison is with C++. And the benchmarks game also provides x86 measurements with programs forced onto a single core which shows GCC ahead http://shootout.alioth.debian.org/u32/benchmark.php?test=all&lang=all > And take a look at the memory used too, up to 34 times higher for the > JVM on the 4-core CPU. > > In the next years people that use low-level languages like C may need > to invent a new language fitter for multi-core CPUs, able to be used > on GPUs too (see the OpenCL), less error-prone than C, able to use the > CPU vector instructions efficiently. (The D language is probably unfit > for this purpose, because even if it's meant to be a system language, > I don't think it can be used much to replace C everywhere it's used > now.) A C+ maybe? :-) > > I agree that CPython may quite enjoy having something built-in like > Psyco, but it's a lot of work for an open source project. Probably > with 1/3 or 1/2 of the work poured on PyPy you may create that > improvement for CPython. Maybe PyPy will someday produce some fruit, > but I think they have used the wrong strategy: instead of trying to > create something very new that someday will work, it's often better to > try to improve something that today everybody uses, AND try to be > useful from almost the very beginning. > > Bye, > bearophile From m.faustino at gmail.com Mon Dec 8 07:47:49 2008 From: m.faustino at gmail.com (=?ISO-8859-1?Q?M=E1rcio_Faustino?=) Date: Mon, 8 Dec 2008 04:47:49 -0800 (PST) Subject: Public imports Message-ID: <9623b0a3-7053-41f1-b116-0cd5e54f39e9@v13g2000vbb.googlegroups.com> Hi, Does Python support public imports instead of the default private? Something like D's "public import" (see ) or even Perl's "export_to_level". Thanks, From casey.mcginty at gmail.com Mon Dec 1 22:19:42 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Mon, 1 Dec 2008 17:19:42 -1000 Subject: Google App Engine Code Challenge - write a tetris playing algorithm In-Reply-To: References: Message-ID: On Sun, Nov 30, 2008 at 2:41 PM, russ.au wrote: > I've got more features to add, depending on how > popular it is.. > Are you going to create a leader board to track the high scores? -------------- next part -------------- An HTML attachment was scrubbed... URL: From rt8396 at gmail.com Tue Dec 23 11:21:57 2008 From: rt8396 at gmail.com (r) Date: Tue, 23 Dec 2008 08:21:57 -0800 (PST) Subject: Python's popularity References: 6rch06Fk4p2U1@mid.individual.net Message-ID: On Dec 23, 10:12?am, je.s.t... at hehxduhmp.org wrote: > r wrote: > > You are the epitimy of an internet troll. A troll tries to hide his > > identity. Why are you so concerned about your TRUE identity. Are the > > I've already stated, and you've already proven, that it's pretty trivial > to ascertain my true identity, if one actually cares. ?OTOH, that's > *not* the case with you. ?Who is hiding now? I told you, my name is Thurstan Howell III. Do you want to know my favorite color too? From aioe.org at technicalbloke.com Mon Dec 8 11:53:08 2008 From: aioe.org at technicalbloke.com (r0g) Date: Mon, 08 Dec 2008 11:53:08 -0500 Subject: Equivalent of 'wget' for python? References: Message-ID: Robert Dailey wrote: > Hi, > > I'm looking for a portable way to download ZIP files on the internet > through Python. I don't want to do os.system() to invoke 'wget', since > this isn't portable on Windows. I'm hoping the core python library has > a library for this. Note that I'll be using Python 3.0. > > Thanks. urllib.urlretrieve(url_of_zip_file, destination_on_local_filesystem). There's also a third argument you can use to link a progress update function of your choosing if you need it. Roger. From ajaksu at gmail.com Tue Dec 23 00:12:01 2008 From: ajaksu at gmail.com (ajaksu) Date: Mon, 22 Dec 2008 21:12:01 -0800 (PST) Subject: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> Message-ID: <90f06b27-39da-4f1a-a878-f3972e942d57@s24g2000vbp.googlegroups.com> On Dec 22, 9:24?pm, r wrote: > You know what i hate more than a troll, a spineless jellyfish who goes > around rating peoples post with one star. You are the lowest form of > life. You are the same type of person who would key someones car in > the parking lot. You do not have the balls to face you enemy. > > If who made a rating were visible, then i would have respect for you, > but since you lurk in the shadows, you are scum. Come out and face me > if you dare! > > I never have rated a post UNLESS i rate it with 5 stars, WHY, you ask, > Because my balls are so big i walk around bow-legged! F'in ?Cowards! That would be me, for at least a dozen of your posts. Glad to know it was more effective than telling you to shut up or calm down. Cnidaria-ly y'rs, Daniel From sjmachin at lexicon.net Mon Dec 8 21:02:07 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 8 Dec 2008 18:02:07 -0800 (PST) Subject: getting error...... Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in open_workbook biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) File "C:\Python25\Lib\site-pack References: <6c76b050-5b47-46f3-9097-5c58979b6913@s9g2000prg.googlegroups.com> <16d767d6-be4a-49eb-af5c-3d9e74b45458@m22g2000vbl.googlegroups.com> Message-ID: On Dec 9, 12:19?pm, JodyGnumeric wrote: > On Dec 8, 5:54?am, John Machin wrote: > > > > > On Dec 8, 6:48?pm, "Gabriel Genellina" wrote: > > > > En Fri, 05 Dec 2008 02:31:01 -0200, pk sahoo ? > > > escribi?: > > > > > hallo everybody, > > > > when i am running the following command > > > > >>>> import xlrd > > > >>>> book=xlrd.open_workbook("C:\\a.xls") > > > > > i am getting the following error.. > > > > > *Traceback (most recent call last): > > > > ? File "", line 1, in > > > > ? File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in > > > > open_workb > > > > ook > > > > ? ? biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) > > > > ? File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 1323, in > > > > getbof > > > > ? ? raise XLRDError('Expected BOF record; found 0x%04x' % opcode) > > > > xlrd.biffh.XLRDError: Expected BOF record; found 0x3f3c* > > > > Looks like your a.xls file is not an Excel file (one of the formats ? > > > supported by xlrd). > > > As 0x3f3c corresponds to the characters ' > > This can be verified easily by opening the file with a simple-minded > > text editor (e.g. Notepad) ... if the first two lines are > > """ > > > > > > """ > > then it's an Excel 2003 XML Spreadsheet that's been manually(?) > > renamed from .xml to .xls. > > > The current xlrd release supports only the binary ("BIFF") format .xls > > files created by Excel 3.0 to Excel 2003. The next release (due out > > Real Soon Now) will support Excel 2.1 and 2.0 formats [don't ask]. > > Very soon after that will come support for Excel 2007 .xlsx which is a > > bunch of XML files inside a ZIP file. Support for Excel 2003 > > "SpreadsheetML" is way down the to-do list. > > > If the OP wants to be able to read the file with xlrd: > > (1) Open it with Excel 200[37] and save as a .xls file > > or (2) rename it to .xml, start OpenOffice.org Calc, click on File, > > click on Open, click on "Files of type", choose "Microsoft Excel 2003 > > XML (*.xml)" from the (long, unsorted) drop-down list, ..., and save > > as etc etc. Gnumeric is not an option. > > > HTH, > > John > > Gnumeric can read this format. 'MS Excel (tm) 2003 SpreadsheetML' [Gnumeric 1.9.1 on Windows XP] I'm sorry; I thought I'd exhausted every possible way of trying to open it. After looking at the file open dialogue box again, I've spotted the "Advanced" button. Here is what you need to do: Have the file named whatever.xls. Click on File / Open , navigate to correct directory, click on Advanced, choose 'MS Excel (tm) 2003 SpreadsheetML' from the File-type drop-down list, choose the file, click on OK. Anything else (Simple (non-Advanced), naming it whatever.xml, ...) produces no response, yes that's zero bits of information, not even a Bzzzzt! noise :-( *AND* when it does open up, a date cell defined by ... 1999-12-31T00:00:00.000 is displayed as "00ort 31at1999" :-( From steve at REMOVE-THIS-cybersource.com.au Wed Dec 10 07:03:07 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 10 Dec 2008 12:03:07 GMT Subject: [OT] Google Groups in bad odour References: <4d5498bf-bbf0-4760-83fc-610729bcbce2@h20g2000yqn.googlegroups.com> Message-ID: <014fa796$0$20670$c3e8da3@news.astraweb.com> On Wed, 10 Dec 2008 02:20:24 -0800, Frank Millman wrote: > Unfortunately it seems that their newsgroup does not have a mail > gateway, so I cannot use gmane. (Please correct me if I am wrong). I > will therefore have to find a suitable news client. Any recommendations? Pan and KNode. -- Steven From grflanagan at gmail.com Sun Dec 28 12:56:23 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Sun, 28 Dec 2008 09:56:23 -0800 (PST) Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> Message-ID: <40b1b762-459b-4d6f-91f0-0a6e68d233ae@a26g2000prf.googlegroups.com> On Dec 28, 5:19?pm, Roger wrote: > Hi Everyone, [...] > When I define a method I always include a return statement out of > habit even if I don't return anything explicitly: > > def something(): > ? ? ? ? # do something > ? ? ? ? return > > Is this pythonic or excessive? ?Is this an unnecessary affectation > that only adds clock ticks to my app and would I be better off > removing "returns" where nothing is returned or is it common practice > to have returns. > It's not particularly excessive but it is uncommon. A nekkid return can sometimes be essential within a function body, so a non-essential nekkid return could be considered just noise. G. From gagsl-py2 at yahoo.com.ar Thu Dec 18 19:11:19 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Dec 2008 22:11:19 -0200 Subject: [Help] The pywinauto Can't select the MDI's menu using the MenuItems() which return []. References: <8c7f10c60812180528k2f755d6aj1564a19efb813db0@mail.gmail.com> Message-ID: En Thu, 18 Dec 2008 11:28:54 -0200, Simon Brunning escribi?: > 2008/12/18 ???? : >> This problem also use the following discription: >> How to use pywinauto to open WORD and select its Menu. >> I can't do that and have no idea why! >> Looking forward your help,Thanks! > > Word can be automated with COM. My golden rule is that automation via > GUI driving is always a last resort. To complement that answer: You'll need the pywin32 package by Mark Hammond http://sourceforge.net/projects/pywin32/ He coauthored the book "Python Programming On Win32"; automating Word (or any other COM application) is covered on that book. I think the freely available chapters cover this specific topic exactly. -- Gabriel Genellina From clp at rebertia.com Mon Dec 22 03:33:56 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 22 Dec 2008 00:33:56 -0800 Subject: Calling ImageMagick's convert In-Reply-To: References: Message-ID: <47c890dc0812220033g49d35ae9w24aede0b438adb4b@mail.gmail.com> On Mon, Dec 22, 2008 at 12:15 AM, cmr.Pent at gmail.com wrote: > Hello group! > > I'm a Python beginner. I'm trying to call ImageMagick's convert > program from my code. > My OS is Debian testing, and my version of Python is 2.5. > > I've just stumbled upon a problem: > > (1) subprocess.call('convert in.png -resize 640x480 out.png', shell = > True) > > works, but none of the following does: > > (2) subprocess.call('convert in.png -resize 640x480 out.png') > (3) subprocess.call(['convert', 'in.png', '-resize 640x480', > 'out.png']) I think this needs to be: subprocess.call(['convert', 'in.png', '-resize', '640x480', 'out.png']) Otherwise, it gets '-resize 640x480' as a single escaped option when it's really 2 options, which is the error message you're getting. You have to split the arguments up just like the shell would, which basically means at whitespace unless quoting is used, which is not the case here. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > (4) subprocess.call(['convert', 'in.png', '-resize 640x480', > 'out.png'], shell = True) > > In these cases, convert program says 'unrecognized option -resize > 640x480'. > At the same time, > > subprocess.call(['ls', '-l']) > > works as expected. > > I'd like to use variant (3), as it seems the most handy. I don't > understand why is shell = True required in case of convert. Is it a > bug in Python, in ImageMagick, or am I missing something very basic > here? > Any hint appreciated. > > Andrey > -- > http://mail.python.org/mailman/listinfo/python-list > From bkamrani at gmail.com Thu Dec 4 05:12:44 2008 From: bkamrani at gmail.com (bkamrani at gmail.com) Date: Thu, 4 Dec 2008 02:12:44 -0800 (PST) Subject: performance question: dictionary or list, float or string? References: <434bf4e3-54f4-4e15-b8b0-510a988f25b8@z1g2000yqn.googlegroups.com> <904a19e9-3800-4d61-aea0-4bdabc0674fa@j32g2000yqn.googlegroups.com> Message-ID: <842b13b2-1df5-4b34-af14-7b082970682b@41g2000yqf.googlegroups.com> About the piece of code you posted, there is something I don't understand. for i, line in data: where data is a file object. Is it legal to write that? I believe it results in "too many values to unpack" or do I miss something? /Ben On Dec 4, 10:26?am, bkamr... at gmail.com wrote: > Matt, really thanks for your comments! > Even thogh it was not a direct answer to my questions, > I like your coding style very much and I think you have a good point. > > About the number of line in the file, because I get that info from > another > in advance. Therefore I thought it could be hard coded. > > BTW, could you recommend a book or a note on points you have mentioned > so that I can learn more like that? > > Thanks, > /Ben > > > # this is just bad style in python: > > line = fil.next(); spl = line.split() > > # better written > > spl = fil.next().split() > > > I would just do it this way: > > > def read_as_list(data, regions=25, maxlines=20000): > > ? ? # If data is a filename, open the file. If it is a file > > ? ? # object or any sequence of 'lines' it should just work. > > > ? ? file_opened = False > > ? ? if isinstance(data, basestring): > > ? ? ? ? data = open(data, 'r') > > ? ? ? ? file_opened = True > > > ? ? forces = [[] for _ in xrange(regions)] > > ? ? try: > > ? ? ? ? for i, line in data: > > ? ? ? ? ? ? if i == maxlines: > > ? ? ? ? ? ? ? ? break > > ? ? ? ? ? ? forces[i % 25].append(line.split()) > > ? ? finally: > > ? ? ? ? if file_opened: > > ? ? ? ? ? ? f.close() > > ? ? return forces > > > Matt > > From wicijowski at gmail.com Sat Dec 27 06:38:31 2008 From: wicijowski at gmail.com (janislaw) Date: Sat, 27 Dec 2008 03:38:31 -0800 (PST) Subject: tkinter 3.0 multiple keyboard events together References: <600d4b68-6fe2-4c2c-b425-1a739430bb54@s9g2000prg.googlegroups.com> Message-ID: <7b5e466c-d75d-4e71-b559-f8a0d3718094@r15g2000prd.googlegroups.com> On 26 Gru, 17:44, Pavel Kosina wrote: > janislaw napsal(a): > > > On 26 Gru, 05:52, Pavel Kosina wrote: > > >> Is it possible to catch in an event more that one key from keyboard? In > >> my code, I can handle always the only one, the first I press, the others > >> are omitted. Say, I press both "4" and "8" and only "4" is catched. > > >> def movePlayer(event): > >> ? ? print (event.keysym) > > > Each keypress triggers another event. Fortunately there are two types > > of events: reaction to press and release. The logic to write to > > recognize those as simultaneous clicks is up to you :) > > Might you give me a little bit more? Just a link to a site where this is > explained and showed would be OK. I really did my best but everything is > bad. > > geon Use google to find the appropriate site, or browse this site, there are plenty of examples. You may want to examine the code I wrote to you to catch the idea: #---------------------- import Tkinter import pprint tk = Tkinter.Tk() f = Tkinter.Frame(tk, width=100, height=100) msg = Tkinter.StringVar() msg.set('Hello') l = Tkinter.Label(f, textvariable=msg) l.pack() f.pack() keys = set() def keyPressHandler(event): keys.add(event.char) display() def keyReleaseHandler(event): keys.remove(event.char) display() def display(): msg.set(str(keys)) f.bind_all('', keyPressHandler) f.bind_all('', keyReleaseHandler) f.mainloop() #---------------- Regards, JW From rogerb at rogerbinns.com Tue Dec 2 14:38:49 2008 From: rogerb at rogerbinns.com (Roger Binns) Date: Tue, 02 Dec 2008 11:38:49 -0800 Subject: Determining number of dict key collisions in a dictionary In-Reply-To: <1228221594.807.1287801527@webmail.messagingengine.com> References: <1228221594.807.1287801527@webmail.messagingengine.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 python at bdurham.com wrote: > Background: I'm working on a project using very large dictionaries (64 > bit Python) and question from my client is how effective is Python's > default hash technique for our data set? Python hash functions return a long which in a 64 bit process is 32 bits on Windows and 64 bits on pretty much every other 64 bit environment. > Their concern is based on the > belief that Python's default dictionary hash scheme is optimized for 32 > bit vs. 64 bit environments and may not have anticipated the additional > range of keys that can be generated in a 64 bit environment. Our keys > are based on 20 to 44 byte ASCII (7-bit) alpha-numeric strings. Why not have them look at the source code? It is well commented and there is another file with various notes. Look at Objects/dictobject.c and Objects/dictnotes.txt A teaser comment for you: Most hash schemes depend on having a "good" hash function, in the sense of simulating randomness. Python doesn't. Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAkk1jsUACgkQmOOfHg372QTeEQCeJwkRphiPeDefkANg1IdG3HH1 oocAoICJk6NGxVmtZTZtLOL4Sv4aCw1n =IqsO -----END PGP SIGNATURE----- From sturlamolden at yahoo.no Fri Dec 12 09:41:27 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 06:41:27 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> Message-ID: On Dec 12, 3:27 pm, "David Cournapeau" wrote: > I want faster function > calls to use with numpy: do you know of any solution ? Pypy certainly > isn't, at least today. An interesting thing for numpy would be to use CUDA. If we can move floating point ops to the GPU, a common desktop computer could yield teraflops. A subclass of ndarray could be written for the nvidia GPU. Using OpenMP within NumPy would also be interesting. There are desktop computers available today with two quadcore processors. There is multiprocessing, which works nicely with numpy. You can even have multiple processes working on ndarrys that point to the same shared memory. Just allocate a multiprocessing.Array and use its buffer to create ndarray views. From aioe.org at technicalbloke.com Mon Dec 8 12:45:00 2008 From: aioe.org at technicalbloke.com (r0g) Date: Mon, 08 Dec 2008 12:45:00 -0500 Subject: How to Write to csv file to create bulk address book References: <5387c7a1-eb04-4d27-826c-d6257298e2db@f40g2000pri.googlegroups.com> Message-ID: k.i.n.g. wrote: > Hi , > > I am new to scripting, I am working on script which would create 'n' > number address book entries into a csv file which would be used to > import into a address book. I need suggestions for the same > > The fileds for csv file are as follows > > ""Title","First Name","Middle Name","Last > Name","Suffix","Company","Department","Job Title","Business > Street","Business Street 2","Business Street 3","Business > City","Business State","Business Postal Code","Business Country","Home > Street","Home Street 2","Home Street 3","Home City","Home State","Home > Postal Code","Home Country","Other Street","Other Street 2","Other > Street 3","Other City","Other State","Other Postal Code","Other > Country","Assistant's Phone","Business Fax","Business Phone","Business > Phone 2","Callback","Car Phone","Company Main Phone","Home Fax","Home > Phone","Home Phone 2","ISDN","Mobile Phone","Other Fax","Other > Phone","Pager","Primary Phone","Radio Phone","TTY/TDD > Phone","Telex","Account","Anniversary","Assistant's Name","Billing > Information","Birthday","Business Address PO > Box","Categories","Children","Directory Server","E-mail Address","E- > mail Type","E-mail Display Name","E-mail 2 Address","E-mail 2 Type","E- > mail 2 Display Name","E-mail 3 Address","E-mail 3 Type","E-mail 3 > Display Name","Gender","Government ID Number","Hobby","Home Address PO > Box","Initials","Internet Free > Busy","Keywords","Language","Location","Manager's > Name","Mileage","Notes","Office Location","Organizational ID > Number","Other Address PO > Box","Priority","Private","Profession","Referred > By","Sensitivity","Spouse","User 1","User 2","User 3","User 4","Web > Page"" > > All the entries written by csv file by script can be random & dummy as > this address book is used for testing purpose. > > > Thank you in advance, > Kanthi Hi Kanthi, the simple case is to make yourself a list of the fields. For each field specify what type of data to generate and a lower and upper bound for it's length/value. fields = [ ("Title", "txt", 0, 4), ("First", "txt", 0, 40), ("Tel", num, 8, 15) etc...] Then repeatedly loop though that list generating random values of the appropriate type and appending them to another list to build records. import random new_record = [] for each_field in fields: if each_field[1] == "txt": r = random.randint( each_field[2], each_field[3] ) new_record.append( r ) elif each_field[1] == "num": r = random.randint( each_field[2], each_field[3] ) s = "".join( [random.choice("qwerty...etc.") for i in range( r )] ) new_record.append( s ) print new_record() Then basically make a big list of these records and squirt them out to file. You might need read up on the random, csv and copy modules and you'll probably want to expand on the data types it can generate. Also I use the following class to choose random words from a specified word list... class WordList: def __init__(self, dictionary_filename): self.dictionary_list = [] f = open(dictionary_filename,'r') for each in f: #print each self.dictionary_list.append(each.rstrip()) f.close() self.dictionary_length = len(self.dictionary_list) def random(self,x): outlist = [] for each in range(0,x): outlist.append(self.dictionary_list[random.randrange(0, self.dictionary_length-1)]) return ' '.join(outlist) This would allow you to say: firstnames = Wordlist('big_list_of_first_names.txt') name = firstnames.random(1) From sjmachin at lexicon.net Mon Dec 22 15:51:11 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 22 Dec 2008 12:51:11 -0800 (PST) Subject: Python-list Digest, Vol 63, Issue 420 References: Message-ID: On Dec 23, 5:31?am, wblu... at verizon.net wrote: > Sent from my Verizon Wireless BlackBerry [snip] That was kind of your parents to let you open your Christmas presents early. From virtual at gmx.de Tue Dec 23 17:08:40 2008 From: virtual at gmx.de (Nikolas Tautenhahn) Date: Tue, 23 Dec 2008 23:08:40 +0100 Subject: SuSE11.1 eclipse 64 pydev can't add python path In-Reply-To: References: Message-ID: Hi, Reimar Bauer wrote: > I can install pydev using the update manager in eclipse for 64 bit from the > SuSE 11.1 repo. But I can't configure pydev without crashing it. > I can select the interpreter /usr/bin/python > and I do see the System PYTHONPATH > Forced builtin libs also looks good. > > But Apply gives me > # > # An unexpected error has been detected by Java Runtime Environment: > # > # SIGSEGV (0xb) at pc=0x00007f2d7abebaed, pid=6544, tid=139832007596368 > # > # Java VM: IcedTea 64-Bit Server VM (1.7.0-b24 mixed mode linux-amd64) > # Problematic frame: > # V [libjvm.so+0x21baed] > # > # An error report file with more information is saved as: > # /home/user/hs_err_pid6544.log > # > # If you would like to submit a bug report, please visit: > # http://icedtea.classpath.org/bugzilla > # The crash happened outside the Java Virtual Machine in native code. > # See problematic frame for where to report the bug. unfortunately I can't help but reproduce the problem. My eclipse was already configured when I updated openSuSE 11.0 to 11.1 so it is not *that* bad for me (only when I install new eggs and want pydev to take notice of them). The question is who is responsible for this... java? pydev? (suse?) If you open a ticket in a bugtracker, please post the url here and I will add myself, too Best regards, Nikolas Tautenhahn From banibrata.dutta at gmail.com Sat Dec 20 03:51:00 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Sat, 20 Dec 2008 14:21:00 +0530 Subject: Check file is In-Reply-To: <7caa7d45-ebbe-4c88-bb50-2f01f7315d07@s9g2000prg.googlegroups.com> References: <7caa7d45-ebbe-4c88-bb50-2f01f7315d07@s9g2000prg.googlegroups.com> Message-ID: <3de8e1f70812200051y73329b4eq95c9c620512e9f0b@mail.gmail.com> AFAI can tell... (from a quick google search), there is only a commercial product that can "read" PDF... i.e. PageCatcher from ReportLabs.http://www.reportlab.org/devfaq.html (look at item 2.1.5) BTW, an apparently, non platform-neutral way may be described here: http://www.daniweb.com/code/snippet618.html Alternatively, you could always use tools like "pdf2txt" to convert PDF into text, and then read it in, however, as you could guess, you completely miss out on the graphics (i.e. images), and the formatting aspects. On Sat, Dec 20, 2008 at 1:36 PM, Harish wrote: > Hi Friends > Is there any utility in python which will help me to read any pdf > files? > > Regards > Harish > -- > http://mail.python.org/mailman/listinfo/python-list > -- regards, Banibrata http://www.linkedin.com/in/bdutta http://octapod.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Dec 24 15:21:12 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2008 18:21:12 -0200 Subject: Doing set operation on non-hashable objects References: <3a87eb6a-13ff-4aea-8835-3a233cc6cfc4@w39g2000prb.googlegroups.com> Message-ID: En Wed, 24 Dec 2008 17:16:59 -0200, <5lvqbwl02 at sneakemail.com> escribi?: > I'm writing an application which is structured roughly as follows: > > "db" is a dict, where the values are also dicts. > A function searches through db and returns a list of values, each of > which is a dict as described above. > I need to perform set operations on these lists (intersection and > union) > However the objects themselves are not hashable, and therefore can't > be in a set, because they are dicts. See this thread from last week: http://groups.google.com/group/comp.lang.python/t/d6818ff713bd4421 > What I really need is a set of pointers, so at the end of the > operation I have the actual objects pointed to. Can I somehow use the > object IDs as set elements, then recreate a list with the actual > objects they point to? If you *only* care about object identity, you might use a dictionary that only compares by identity to anyone else: class nc_dict(dict): "A hashable dictionary that isn't equal to anyone else" def __eq__(self, other): return cmp(id(self),id(other))==0 def __hash__(self): return hash(id(self)) d1 = nc_dict(a=1, b=2, c=3) d2 = nc_dict(b=2, c=0, d=4) d3 = nc_dict(a=1, c=3, e=5) dd1 = nc_dict(x=d1, y=d2) dd2 = nc_dict(x=d1, y=d3) dd3 = nc_dict(y=d2, z=d3, w=d1) l1 = [dd1, dd2] l2 = [dd2, dd3] s1 = set(l1) s2 = set(l2) print s1-s2 print s2-s1 print s1&s2 # instances of nc_dict with the same contents are NOT equal d4 = nc_dict(a=1, b=2, c=3) print d1, d4, d1==d4 # output: False # but we can use this function to compare contents def cmp_contents(d1, d2): try: return cmp(sorted(d1.items()), sorted(d2.items())) except Exception: return 1 # assume they're unequal print cmp_contents(d1,d4)==0 # output: True > How do you get the object back from an ID in python? You don't :) -- Gabriel Genellina From marduk at letterboxes.org Tue Dec 9 16:10:08 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Tue, 09 Dec 2008 16:10:08 -0500 Subject: Is 3.0 worth breaking backward compatibility? In-Reply-To: References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> Message-ID: <1228857008.4109.38.camel@brotherus.rdu.redhat.com> On Tue, 2008-12-09 at 20:56 +0000, Lie Ryan wrote: > Actually I noticed a tendency from open-source projects to have slow > increment of version number, while proprietary projects usually have > big > version numbers. > > Linux 2.x: 1991 Python 3.x.x: 1991. Apache 2.0: 1995. OpenOffice.org > 3.0: > acquired by Sun at 1999. GIMP 2.x: 1995. Wine 1.x: 1993. > One exeption would be GNU Emacs 22: 1984, but according to Wikipedia: "Versions 2 to 12 never existed. Earlier versions of GNU Emacs had been numbered "1.x.x", but sometime after version 1.12 the decision was made to drop the "1", as it was thought the major number would never change." So you can think of Emacs 22 as being 1.22. From stefan_ml at behnel.de Tue Dec 2 15:12:19 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 02 Dec 2008 21:12:19 +0100 Subject: Reverse zip() ? In-Reply-To: <20081202210930.2ac88ec6@usenot.de> References: <20081202210930.2ac88ec6@usenot.de> Message-ID: <493596A3.4010306@behnel.de> Andreas Waldenburger wrote: > we all know about the zip builtin that combines several iterables into > a list of tuples. > > I often find myself doing the reverse, splitting a list of tuples into > several lists, each corresponding to a certain element of each tuple > (e.g. matplotlib/pyplot needs those, rather than lists of points). > > This is of course trivial to do via iteration or listcomps, BUT, I was > wondering if there is a function I don't know about that does this > nicely? I think you're asking about zip(): >>> l=[1,2,3] >>> zip(l,l) [(1, 1), (2, 2), (3, 3)] >>> zip(*zip(l,l)) [(1, 2, 3), (1, 2, 3)] Stefan From tjreedy at udel.edu Mon Dec 1 13:59:51 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Dec 2008 13:59:51 -0500 Subject: optimization In-Reply-To: <18740.10122.833580.878015@montanaro-dyndns-org.local> References: <18740.10122.833580.878015@montanaro-dyndns-org.local> Message-ID: skip at pobox.com wrote: > Neal> I noticed in some profiling, that it seems that: > > Neal> def Func (): > Neal> def something(): > Neal> ... > > Neal> It appears that if Func is called many times, this nested func > Neal> definition will cause significant overhead. Is this true? I > Neal> guess I've become accustomed to decent compilers performing > Neal> reasonable transformations and so have tended to write code for > Neal> clarity. > > It could. OTOH, the code object which implements the something body is > stored as a local var (or a constant, can't remember off the top of my > head), so it's not compiled over and over again. Constant. With 3.0... >>> def f(): def g(): pass >>> import dis >>> dis.dis(f) 2 0 LOAD_CONST 1 (", line 2>) 3 MAKE_FUNCTION 0 6 STORE_FAST 0 (g) 9 LOAD_CONST 0 (None) 12 RETURN_VALUE If the inner function is constant and does not directly access outer function locals, and if every last tick of speed is a concern, then it can be move out and given a name like _outer_helper. I would go for clarity and correctness first, but I would also wonder whether an inner function that is independent of its setting and therefore movable might be turned into something of more general use and usefully moved out for purposes other than just speed. Terry Jan Reedy From alessio.pace at gmail.com Mon Dec 1 12:35:31 2008 From: alessio.pace at gmail.com (Alessio Pace) Date: Mon, 1 Dec 2008 09:35:31 -0800 (PST) Subject: How to distribute a Python app together with its dependencies? References: <2343b577-215b-4b4c-8ea0-00dd49369df1@x38g2000yqj.googlegroups.com> Message-ID: <066f1687-64f4-4d3e-b307-6f1df96a399a@20g2000yqt.googlegroups.com> On 1 Dic, 15:21, Mike Driscoll wrote: > On Nov 30, 6:22?am, Alessio Pace wrote: > > > > > Hi, > > > I have to distribute a Python application which relies on an external > > library, and I'm not very fluent in this kind of stuff with Python (I > > come from the Java world where I would have used the Maven build tool > > to create an "assembly with dependencies" of all it is needed to run > > the app), so I was wondering if someone here could give me some > > suggestions :-) > > > The external library is generally not present on the machines where I > > have to distribute my app, and the set of machines on which I have to > > distribute this application is not known a priori (it is just known > > they are Unix systems). In fact by means of SSH I will have to copy > > (and install) the app+library and make it runnable onto the specified > > destination(s). > > > My question is: how would you do that? ?At the moment my current > > solution is to make a tarball of the sources of my app + the > > "distutils" archive of the external library, copy all into the target > > machine, decompress and install via distutils(*) the external library, > > setup some PYTHONPATH stuff on the destination machine, and finally be > > able to launch the application. > > > (*) specifying a prefix into the user home, as I'm not root there > > > So in the end I was wondering if there is a more elegant way of doing > > this because, as I said before, I'm not very experienced in these kind > > of tasks in Python. > > > Thanks in advance for any suggestion or comment. > > > Alessio Pace. > > I recommend GUI2Exe, a nice wrapper to py2exe, py2app, PyInstaller, > cx_Freeze and bbFreeze: > > http://code.google.com/p/gui2exe/ > > I've only used the py2exe portion of the program, but it works great > and the developers behind the project are very responsive and helpful. > > Mike Hi all and thanks for the replies. Apparenlty I managed to make the standalone application with bbfreeze (used directly), I still have to tune a little bit how it can pack in it also classes which are loaded dynamically, and which from a static examination of the code are not found then... I'll try to give a look at GUI2Exe also, thank you for the suggestion. Regards, Alessio Pace. From steve at holdenweb.com Fri Dec 12 11:53:53 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Dec 2008 11:53:53 -0500 Subject: var or inout parm? In-Reply-To: References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> Message-ID: sturlamolden wrote: > On Dec 12, 5:13 pm, Steve Holden wrote: > >>> It should be the tuple's __setitem__ that was invoked here, not >>> __iadd__, or the parser is faulty. >> OK, so now you are proposing to alter the parser, and possibly the >> implementation of the INPLACE_ADD opcode in eval.c, so can you give us >> the patch for those, please? > > What? Take a look at the code again: > > mytuple[0] += 1 > > should never attempt an __iadd__ on mytuple. > > A sane parser would see this as: > > tmp = mytuple.__getitem__(0) > tmp = tmp.__iadd__(1) > mytuple.__setitem__(0, tmp) # should this always raise an exception? > > >> Discussion of such behavior as a "bug" is also pejorative, since the >> current semantics are the way they are by design. > > Right, this bug is by design. You learned that phrase from a guy in > Redmond? > "It's not a bug, it's a feature" predates Microsoft by several years. If I say you are ugly, that doesn't make it true. Neither does your calling this a bug make it a bug. The fact is that Python doesn't behave the way you want it to. If your friend doesn't want to do what you do, does that make it a bug in his behavior. You're being a little juvenile here. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From pyth0nc0d3r at gmail.com Mon Dec 15 01:56:05 2008 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Mon, 15 Dec 2008 00:56:05 -0600 Subject: HTTPConnection Sending Cookies to server Message-ID: Right now I can login to www.phpbb.com's forums import httplib, urllib params = urllib.urlencode({'username':'TheInfernoSin','password':'PASSWORD','login':1,'sid':'','redirect':'index.php','autologin':1}) headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"} con = httplib.HTTPConnection(url) con.request("POST","/community/ucp.php?mode=login",params,headers) data = con.getresponse() #print data.read() hdrs = data.getheader('set-cookie') header = {"Cookie": hdrs} print header #print hdrs con2 = httplib.HTTPConnection(url) #con2.request("GET","/community/ucp.php",None,header) con2.connect() con2.putrequest("POST","/community/ucp.php") con2.putheader("Cookie",hdrs) con2.endheaders() data = con2.getresponse() print data.read() The first block of code logins in and if printed it'll show the logged in successful html code, but when trying to go to another page and sending that cookie back to the server, it wont allow me to stay logged in. -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Sat Dec 13 17:18:34 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 13 Dec 2008 22:18:34 +0000 Subject: [OT] stable algorithm with complexity O(n) References: Message-ID: "David Hl??ik" writes: > Hi guys, > > i am really sorry for making offtopic, hope you will not kill me, but > this is for me life important problem which needs to be solved within > next 12 hours.. > > I have to create stable algorithm for sorting n numbers from interval > [1,n^2] with time complexity O(n) . > > Can someone please give me a hint. Would be very very thankful! > > Thanks in advance! > D. I don't have an algorithm but I have an implementation :) def sort2(numbers): "sort n positive integers in O(n) provided that they are all < n^2" N = len(numbers) units = [[] for i in xrange(N)] tens = [[] for i in xrange(N)] for n in numbers: units[n % N].append(n) for l in units: for n in l: tens[n / N].append(n) return [n for l in tens for n in l] -- Arnaud From steve at REMOVE-THIS-cybersource.com.au Tue Dec 16 20:34:37 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 17 Dec 2008 01:34:37 GMT Subject: weird dict problem, how can this even happen? References: Message-ID: <01584e96$0$20656$c3e8da3@news.astraweb.com> On Tue, 16 Dec 2008 14:32:39 +0100, Joel Hedlund wrote: > Duncan Booth wrote: >> I think you probably are correct. The only thing I can think that might >> help is if you can catch all the situations where changes to the >> dependent values might change the hash and wrap them up: before >> changing the hash pop the item out of the dict, then reinsert it after >> the change. > > That would probably require a lot of uncomfortable signal handling, > especially for a piece of functionality I'd like to be as unobtrusive as > possible in the application. > >> Alternatively give up on defining hash and __eq__ for FragmentInfo and >> rely on object identity instead. > > Object identity wouldn't work so well for caching. Objects would always > be drawn as they appeared for the first time. No updates would be shown > until the objects were flushed from the cache. Perhaps I don't understand your program structure, but I don't see how that follows. > I've been experimenting with a list cache now and I can't say I'm > noticing any change in performance for a cache of 100 items. 100 items isn't very big though. If you have 50,000 items you may notice significant slow down :) If having many items in the cache is possible, you should consider using a binary search instead of a linear search through the cache. See the bisect module. -- Steven From almar.klein at gmail.com Wed Dec 3 07:09:22 2008 From: almar.klein at gmail.com (Almar Klein) Date: Wed, 3 Dec 2008 13:09:22 +0100 Subject: Multiple equates In-Reply-To: <12cbbbfc0812030345m5afa83d3m518e108d11d3e0fb@mail.gmail.com> References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> <9m3h06-vhh.ln1@lairds.us> <12cbbbfc0812030345m5afa83d3m518e108d11d3e0fb@mail.gmail.com> Message-ID: Hi, what about numpy? import numpy a = numpy.ones((10,),dtype=numpy.bool) I = [1,3,8] a[I]=False print a gives: [ True False True False True True True True False True] Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From info at orlans-amo.be Sun Dec 7 09:32:30 2008 From: info at orlans-amo.be (info at orlans-amo.be) Date: Sun, 7 Dec 2008 06:32:30 -0800 (PST) Subject: how to get a beep, OS independent ? References: <59f10d38-e058-47f0-a7fe-5f25e36dc120@t2g2000yqm.googlegroups.com> Message-ID: <5a3fe3be-0bbc-45d2-b79d-c01ae8319c50@f20g2000yqg.googlegroups.com> Sorry, with import Tkinter Tkinter.Tk().bell() you get a new window for the same price... So it's usefull only when using tkinter From rtw at freenet.co.uk Tue Dec 30 16:35:28 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Tue, 30 Dec 2008 15:35:28 -0600 Subject: Triple quoted string in exec function ? References: Message-ID: Stef Mientki wrote in news:mailman.6399.1230668197.3487.python- list at python.org in comp.lang.python: >>> And, by the way, exec is a *statement*, not a function! >>> > exec ( Init_Code, PG.P_Globals ) > > I've really doubt that this is a statement, > unless I don't understand what a statement is. >>> > In python 2.x the above is a statement that is passed a tuple: http://docs.python.org/reference/simple_stmts.html#exec its a statement like print is: >>> print ( 1,2 ) (1, 2) >>> In 3.x it is a function: http://docs.python.org/3.0/library/functions.html#exec print is also a function in python 3.x, so: >>> print(1, 2) 1 2 >>> Rob. -- http://www.victim-prime.dsl.pipex.com/ From robert.kern at gmail.com Thu Dec 4 18:45:06 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 04 Dec 2008 17:45:06 -0600 Subject: pretty strange behavior of "strip" In-Reply-To: <4938693F.6090709@yahoo.ca> References: <4938693F.6090709@yahoo.ca> Message-ID: Guy Doune wrote: > Hi everybody, > > Could it be a bug????? > > Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> test=['03.html', '06.html', 'questions.html', '04.html', > 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test > ['03.html', '06.html', 'questions.html', '04.html', 'toc.html', > '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test[4] > 'toc.html' > >>> test[4].strip('.html') > 'oc' > > Can't figure out what is going on, really. http://docs.python.org/library/stdtypes.html#str.strip str.strip([chars]) Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped: >>> ' spacious '.strip() 'spacious' >>> 'www.example.com'.strip('cmowz.') 'example' -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From zo0omafrinzocheck at gmail.com Wed Dec 17 16:24:53 2008 From: zo0omafrinzocheck at gmail.com (zo0oma) Date: Wed, 17 Dec 2008 13:24:53 -0800 (PST) Subject: Meet Singles From All Over The World .. FOR FREE !! Message-ID: Meet Singles In Your Area Arabs, American, Russian Singles >From All Over The World Waiting For You At Frinzo Join Frinzo And Start Your Love Life Now Join Frinzo Now For Free !! Enjoy exciting features offered by our site: * Profiles with galleries and audio/video * Personal weblogs and friends-lists * Audio/video chat, IM and recorder * SPAM-blocking and anti-SPAM system * ZIP-codes search, matchmaking and so much more!! http://www.frinzo.com From febaen at gmail.com Mon Dec 15 19:39:09 2008 From: febaen at gmail.com (feba) Date: Mon, 15 Dec 2008 16:39:09 -0800 (PST) Subject: Need help improving number guessing game References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> <01564c98$0$21844$c3e8da3@news.astraweb.com> <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> <4946df78$0$19771$426a74cc@news.free.fr> Message-ID: <1f33580b-84f9-4059-a0f0-b6a8d71325af@b38g2000prf.googlegroups.com> > .strip() returns a copy of the string without leading and ending whitespaces (inlcuding newlines, tabs etc). Ahh. I had removed it because it didn't seem to do anything, but I've readded it. And I understand your dictionary stuff correctly now, I think, and I worked it in. Currently, I have: import random def safeint(prompt="y"): while True: x = input(prompt) try: x = int(x) except ValueError: print("BAD INPUT!") else: break return x def safestr(prompt="y"): while True: x = input(prompt) try: x = str(x) except ValueError: print("BAD INPUT!") else: break return x def customrange(game, lowunsafe=True): game['defrang'] = False #Keeps setup from changing range to defaults while lowunsafe: #makes sure that the low number is positive picklow = safeint(prompt="PLEASE PICK THE LOW NUMBER: ") if picklow < 0: print("LOW NUMBER MUST BE POSITIVE") else: lowunsafe = False pickhigh = safeint(prompt="PLEASE PICK THE HIGH NUMBER: ") if pickhigh - picklow <= 2: #see setup(). print("HIGH MUST BE AT LEAST THREE GREATER THAN LOW") else: game['minr'], game['maxr'] = picklow, pickhigh print("RANGE IS [%s-%s]!" % (game['minr'], game['maxr'])) def wantcustom(game, unsure=True): #Allows user to decide their own range for guessing. while unsure: tryrange = safestr(prompt=\ "WOULD YOU LIKE TO CREATE A CUSTOM RANGE? "\ +"Y/N: ") if tryrange.strip().lower() == "n": game['minr'], game['maxr'] = 1, 99 #Default range. see setup unsure = False elif tryrange.strip().lower() == "y": customrange(game) unsure = False else: print("INVALID INPUT") def samesettings(game, unsure=True): while unsure: keepset = safestr(prompt="USE SAME SETTINGS? Y/N: ") if keepset.strip().lower() == "y": game['minr'], game['maxr'] = 1, 99 #Default range. see setup unsure = False elif keepset.strip().lower() == "n": wantcustom(game) numplayers(game) unsure = False else: print("INVALID INPUT") def setup(game): #minr, maxr make minimum and maximum. Can be adjusted. #Make sure that maxr - minr is at least 3. #1 or less would be impossible. 2 would only have one guess for victory #The first would be unplayable, the second would play itself if game['maxr'] - game['minr'] <= 2: raise ValueError("INVALID RANGE!") #If this fails, check line 43 game['gcount'] = 0 #Reset guess count game['target'] = random.randint(game['minr'], game['maxr']) def playerswitch(game): #Player Switch #if player's a witch: burn(her) if game['player'] is game['player1']: game['player'] = game['player2'] else: game['player'] = game['player1'] def youwin(game): if game['pnum'] == 1: print("CONGRATULATIONS! IT TOOK YOU %s GUESSES" % game ['gcount']) else: game['player']['score'] += 1 end = "CONGRATULATIONS %s! SCORE -- P1:%s P2:%s" print(end % (game['player']['name'],\ game['player1']['score'], game['player2']['score'])) def playagain(game, unsure=True): while unsure: playover = safestr(prompt="PLAY AGAIN? Y/N: ") if playover.strip().lower() == "y": game['play'] = True samesettings(game) setup(game) unsure = False elif playover.strip().lower() == "n": print("GOOD BYE. PLAY AGAIN SOON!") game['play'] = False unsure = False else: print("INVALID INPUT") def autofinish(game): if game['maxr'] - game['minr'] == 2: print("...ONLY ONE OPTION LEFT!") youwin(game) playagain(game) def numplayers(game, unsafe=True): while unsafe: num = safeint(prompt="1 OR 2 PLAYERS?\n> ") if num == 1 or 2: #ONLY allow 1 or 2P. unsafe = False else: print("INVALID INPUT") game['pnum'] = num def guesses(game, unsafe=True): while unsafe: guess = safeint(prompt="[%s-%s]%s>> " % \ #Shows range (game['minr'], game['maxr'],\ #And which player's turn game['player']['name'])) if guess >= game['maxr']: print("NUMBER MUST BE IN RANGE") guesses(game) guesscheck(game) elif guess <= game['minr']: print("NUMBER MUST BE IN RANGE") guesses(game) guesscheck(game) else: unsafe = False game['guess'] = guess def guesscheck(game): if game['guess'] == game['target']: if game['pnum'] == 1: game['gcount'] += 1 youwin(game) playagain(game) elif game['guess'] > game['target']: print("TOO HIGH") if game['pnum'] == 1: game['gcount'] += 1 game['maxr'] = game['guess'] else: print("TOO LOW") if game['pnum'] == 1: game['gcount'] += 1 game['minr'] = game['guess'] def guessing(game): guesses(game) guesscheck(game) if game['pnum'] == 2: playerswitch(game) autofinish(game) def main(game=None): player1, player2 = dict(name="P1",score=0), dict (name="P2",score=0) if game is None: game = dict( player1 = player1, player2 = player2, player = player1, play = True ) print("WELCOME TO THE SUPER NUMBER GUESSING GAME!") wantcustom(game) numplayers(game) setup(game) while game['play'] is True: guessing(game) if __name__ == "__main__": main() >rewrite it once again using objects instead of dicts ? I'd need to find out how those work, and I have a list of python stuff to read piling up anyway... That said, I think for something like that, something that's not a major flaw, I'd prefer to make something else, and maybe work on this again later on. There is only so much guessing numbers one person can take. From anders.olme at gmail.com Fri Dec 12 15:51:42 2008 From: anders.olme at gmail.com (a_olme) Date: Fri, 12 Dec 2008 12:51:42 -0800 (PST) Subject: Umlauts in idle Message-ID: <26880ecf-d0eb-42ab-8ebd-56f64c023999@v39g2000pro.googlegroups.com> Hello all, When I try to use umlauts in idle it will only print out as Unicode escape characters. Is it possible to configure idle to print them as ordinary characters? Best Regards Anders Olme From http Mon Dec 29 20:51:43 2008 From: http (Paul Rubin) Date: 29 Dec 2008 17:51:43 -0800 Subject: Python in C References: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> Message-ID: <7x8wpyph00.fsf@ruckus.brouhaha.com> thmpsn.m.k at gmail.com writes: > 1. Can anyone explain to me what kind of program structuring technique > (which paradigm, etc) CPython uses? How do modules interact together? > What conventions does it use? There are a bunch of docs about this, you could read them. The program is written about the way you would expect if you have worked on interpreters written in C before. > 2. Have there been any suggestions in the past to rewrite Python's > mainstream implementation in C++ (or why wasn't it done this way from > the beginning)? I don't think there has ever been any interest in this. There is an effort under way to rewrite Python in Python. This is called PyPy (you should be able to websearch for it easily) and should be much more advanced than the C implementation. It works now, under some preliminary definition of "working", but it will be a while before it is ready for wide deployment. From LambertDW at Corning.com Thu Dec 11 02:02:15 2008 From: LambertDW at Corning.com (Lambert, David W (S&T)) Date: Thu, 11 Dec 2008 02:02:15 -0500 Subject: if expression source format Message-ID: <84B204FFB016BA4984227335D8257FBA625678@CVCV0XI05.na.corning.com> The "if" expression leads to long statements. Please offer suggestions to beautify this function. For this example use maximum line length marked by the ####'s. Thank you. ############################################################## def compute_wind_chill_temperture(T:'Temperature, dF',s:'Wind speed, mph')->dF: ''' ''' return 35.74 + 0.6215*T + s**0.16*(T*0.4275-35.75) if T < 40 else T From jason.dusek at gmail.com Tue Dec 23 16:31:11 2008 From: jason.dusek at gmail.com (Jason Dusek) Date: Tue, 23 Dec 2008 13:31:11 -0800 Subject: [Haskell-cafe] Initializing GHC from Python In-Reply-To: <4950AC05.9060105@gamr7.com> References: <4950AC05.9060105@gamr7.com> Message-ID: <42784f260812231331h6b8628b0tf8d4c0da0277f269@mail.gmail.com> I upmodded this on Reddit. Thank you for your work. -- Jason Dusek From org.python.pythonlist at pooryorick.com Sat Dec 13 06:29:17 2008 From: org.python.pythonlist at pooryorick.com (=?utf-8?Q?Poor=20Yorick?=) Date: Sat, 13 Dec 2008 11:29:17 +0000 Subject: =?utf-8?B?X19mdXR1cmVfXyBhbmQgY29tcGlsZTogIHVucmVjb2duaXNlZCBmbGFncw==?= Message-ID: <20081213112917.6209.qmail@s461.sureserver.com> I have a future statement in a script which is intended to work in 2.6 and 3. Shouldn't compile flags in __future__ objects essentially be noops for versions that already support the feature? doctest is complaining about unrecognised flags. This illustrates the problem: Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> from __future__ import unicode_literals >>> src = 'a = "hello"' >>> c1 = compile(src,'','exec',unicode_literals.compiler_flag) Traceback (most recent call last): File "", line 1, in ValueError: compile(): unrecognised flags -- Yorick From google at mrabarnett.plus.com Wed Dec 10 12:38:39 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 10 Dec 2008 17:38:39 +0000 Subject: "as" keyword woes In-Reply-To: References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> <493FD8F6.3050803@mrabarnett.plus.com> Message-ID: <493FFE9F.7030000@mrabarnett.plus.com> Patrick Mullen wrote: > On Wed, Dec 10, 2008 at 6:57 AM, MRAB > wrote: >> Aaron Brady wrote: >>> On Dec 9, 12:40 pm, MRAB wrote: >>>> Aaron Brady wrote: >>>>> On Dec 9, 8:28 am, MRAB wrote: >>>>> snip >>>>>> In some languages (I think Delphi is one of them - it's >>>>>> been a while!) some words which would normally be >>>>>> identifiers have a special meaning in certain contexts, but >>>>>> the syntax precludes any ambiguity, and not in a difficult >>>>>> way. "as" in Python was one of those. I certainly wouldn't >>>>>> want something like PL/I, where "IF", "THEN" and "ELSE" >>>>>> could be identifiers, so you could have code like: IF IF = >>>>>> THEN THEN THEN = ELSE; ELSE ELSE = IF; >>>>>> Seehttp://en.wikipedia.org/wiki/PL/I_(programming_language). >>>>>> >>>>> snip That is, 'certainly' doesn't change the meaning of your >>>>> statement any. You wouldn't want it, but King George III >>>>> didn't want the American Revolution. >>>> It's called emphasis. >>> I just take you to have meant, then, +1 on excluding keywords >>> from identifiers. You said it the long way though, so I thought >>> I missed something deeper, that didn't come across. >>> >> IIRC, most computer languages have an LL(1) grammar, which means >> that when they are parsed you need to look at only the next word. >> If you're about to parse a statement and the next word is "IF" then >> you know it's an IF-statement, if it's an identifier then it's >> either a call or an assignment statement (OK, you don't know >> exactly what kind of statement it is at that point, but it works >> out just fine!). >> >> In the example from PL/I, "IF" could be the start of an >> IF-statement "IF THEN" or an assignment statement "IF = >> ". It's a bit more tricky for the parser as well as the >> programmer. >> >> Life is easier if words having special meanings are reserved. >> >> However, that doesn't mean that all special words /must/ be >> reserved (pragmatism beats purity). Sometimes the syntax makes it >> clear and unambiguous, so you can get away with not making it a >> reserved word. The word "as" in Python doesn't need to be reserved >> because the syntax precludes ambiguity, but it's the only such word >> in the language, so it's just tidier to make it reserved too. >> > > I don't have a huge stake in this, but I wouldn't mind a change to > allow anything proceeding a "." or preceeding a "(" to not be > identified as a keyword. Don't you mean 'following a "."'? IMHO if you forbid "bar = True" then you should also forbid "foo.bar = True". As for preceding a "(", what about the call "if(True)"? It looks like an if-statement! > It is obvious to me a s a human reader that something.if is quite a > bit different than just a bare if. And as far as parsing technology > goes, isn't it supposed to go for the biggest match first? I would > not be for allowing bare keywords to be used in the situations > described above, but since we are so used to being able to being able > to have say, myclass.dir() or myclass.len() without them overwriting > the builtin functions, it makes sense to me to be able to define a > myclass.as() or myclass.with() without overwriting the keywords. > Though I know the semantics behind these two things are very > different, the rules I go through when reading the code are very > similar. The parser change might be a hassle, and it might not be > worth it at all of course, but from a conceptual point of view it is > simple. I mean, even now you can do class.__dict__["as"]. > > I guess I'm -1 for full PL/1 craziness, but +1 for qualified keyword > usage. > Parsing isn't about the biggest match. Ideally you want something that's simple without being simplistic. Python is a good example. From lewis.sarah93 at yahoo.com Thu Dec 4 23:57:54 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 20:57:54 -0800 (PST) Subject: Get Debt Fre Message-ID: <82c3f62b-e713-4e22-a484-20233656b8de@33g2000yqm.googlegroups.com> Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From lists at cheimes.de Fri Dec 5 15:41:50 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 05 Dec 2008 21:41:50 +0100 Subject: slow Python 3.0 write performance? In-Reply-To: References: Message-ID: Istvan Albert wrote: > I see, thanks for the clarification. > > I will make the point though that this makes python 3.0 unsuited for > anyone who has to process data. One could live with slowdowns of say > 20-50 percent, to get the goodies that 3.0 offers, but when a process > that takes 1 second suddenly starts to take 10, it is makes the > situation untenable. The speed issue slipped through the alpha and beta releases. Apparently no user has tested Python 3.0 with large files so far. Some bugs just can't be found by the developers. I've fixed the read() slowness yesterday. You'll get the fix in the next release of Python 3.0 in a couple of weeks. Christian From bdesth.quelquechose at free.quelquepart.fr Sun Dec 21 14:28:55 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 21 Dec 2008 20:28:55 +0100 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> Message-ID: <494ea6ab$0$7769$426a74cc@news.free.fr> walterbyrd a ?crit : > On Dec 20, 5:05 pm, Roy Smith > >> He got really hung up on the % syntax. > > I guess it's good to know that there is, at least, one person in the > world doesn't like the % formatting. As least the move was not > entirely pointless. > > But, you must admit, of all the things people complain about with > Python, the % formatting is probably one of the least common > complaints. Complaints about Python's speed seem much more common. People complaining about the perceived issues wrt/ Python's speed are welcome to fix it. As far as I'm concerned, I find the perfs more than acceptable when you take Python's dynamism into account. Strange enough, no one seems to complain about PHP or Ruby's performances... > Yet, 3.0 makes the speed worse, first make it right, then make it fast... > and "fixes" a non-problem. > > I can see where the new formatting might be helpful in some cases. > But, I am not sure it's worth the cost. Err... _Which_ cost exactly ? From nick at craig-wood.com Thu Dec 4 07:30:47 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 04 Dec 2008 06:30:47 -0600 Subject: How can I do this (from Perl) in Python? (closures) References: <68b8294c-8771-4b02-bd46-2f25f5e01602@j35g2000yqh.googlegroups.com> Message-ID: Duncan Booth wrote: > excord80 at gmail.com wrote: > > > I just came across http://www.perl.com/pub/a/2002/05/29/closure.html > > and wanted to try the "canonical example of closures" in Python. I > > came up with the following, but it fails: > > > > def make_counter(start_num): > > start = start_num > > def counter(): > > start += 1 > > return counter > > The other answers you got will work, but here's an alternative to > consider: you can convert the function into a generator and then just > move the variable inside. > > >>> def make_counter(start_num): > def counter(): > start = start_num > while 1: > yield start > start += 1 > return counter().next Interesting... You can also write it without nested functions / closures def counter(x): while 1: yield x x += 1 def make_counter(start_num): return counter(start_num).next I expect the machinery is similar between generators and closures, but with generators it is a lot more obvious exactly which version of which variable you are using! In fact you can always do what you can do with a closure with the above technique I think... def make_closure(*args, **kwargs): # initialisation to local vars def closure(): # stuff, being careful with nonlocal args & kwargs return result vs def closure(*args, **kwargs): # initialisation to local vars while 1: # normal stuff using args and kwargs yield result def make_closure(*args, **kwargs): return closure(*args, **kwargs).next I still prefer doing it explicitly with a class though ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From jstroud at mbi.ucla.edu Sun Dec 7 06:57:07 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 07 Dec 2008 03:57:07 -0800 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Rasmus Fogh wrote: > Dear All, > > For the first time I have come across a Python feature that seems > completely wrong. After the introduction of rich comparisons, equality > comparison does not have to return a truth value, and may indeed return > nothing at all and throw an error instead. As a result, code like > if foo == bar: > or > foo in alist > cannot be relied on to work. > > This is clearly no accident. According to the documentation all comparison > operators are allowed to return non-booleans, or to throw errors. There is > explicitly no guarantee that x == x is True. I'm not a computer scientist, so my language and perspective on the topic may be a bit naive, but I'll try to demonstrate my caveman understanding example. First, here is why the ability to throw an error is a feature: class Apple(object): def __init__(self, appleness): self.appleness = appleness def __cmp__(self, other): assert isinstance(other, Apple), 'must compare apples to apples' return cmp(self.appleness, other.appleness) class Orange(object): pass Apple(42) == Orange() Second, consider that any value in python also evaluates to a truth value in boolean context. Third, every function returns something. A function's returning nothing is not a possibility in the python language. None is something but evaluates to False in boolean context. > But surely you can define an equal/unequal classification for all > types of object, if you want to? This reminds me of complex numbers: would 4 + 4i be equal to sqrt(32)? Even in the realm of pure mathematics, the generality of objects (i.e. numbers) can not be assumed. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From bearophileHUGS at lycos.com Fri Dec 5 17:19:35 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 5 Dec 2008 14:19:35 -0800 (PST) Subject: slow Python 3.0 write performance? References: Message-ID: <012eed1c-78ee-4ea6-9ed3-9ca5ea012b73@d23g2000yqc.googlegroups.com> Christian Heimes: > I've fixed the read() slowness yesterday. You'll get the fix in the next > release of Python 3.0 in a couple of weeks. Thank you. Bye, bearophile From enleverlesX.XmcX at XmclaveauX.com Mon Dec 22 11:44:13 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Mon, 22 Dec 2008 17:44:13 +0100 Subject: join a samba domain In-Reply-To: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> References: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> Message-ID: <494fc690$0$9382$ba4acef3@news.orange.fr> Hi! If you are under Vista, you must change the LSA parameter. See: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa LMCompatibilityLevel try with value 1 or 0 And use a Samba not too old. @-salutations -- Michel Claveau From aboudouvas at panafonet.gr Sun Dec 7 12:39:02 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Sun, 7 Dec 2008 09:39:02 -0800 (PST) Subject: Netbeans Early Access and Python3 References: Message-ID: On Dec 6, 12:54?pm, king kikapu wrote: > Hi, > > have anyone using this release of NetBeans (6.5 with Python support) > with Python 3 without any problems ? I mean, does it work with Python3 > or only with 2.x ? No-one is using NetBeans for Python development ?? From fakeaddress at nowhere.org Tue Dec 2 20:55:27 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 02 Dec 2008 17:55:27 -0800 Subject: Reverse zip() ? In-Reply-To: References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> Message-ID: <6ElZk.8756$Ei5.6992@flpi143.ffdc.sbc.com> Zac Burns wrote: > There is a problem with this however, which prompted me to actually > write an unzip function. > > One might expect to be able to do something like so (pseudocode)... > > def filesAndAttributes(): > files = walk() > attributes = [attr(f) for f in files] > return zip(files, attributes) You could do away with that zip and just let the list comprehension return tuples. [(f, attr(f)) for f in walker()] > files, attributes = zip(*filesAndAttributes()) > > The corner case is when dealing with empty lists and there aren't > enough items to unpack. Can you give a concrete example? > The unzip function therefore has an elementsForEmpty keyword that > handles this case. Perhaps something like this could be added to zip? The built-in zip stops when any of the given iterables stops. The itertools module has izip_longest (or zip_longest in Python 3), which takes a fillvalue argument. Perhaps that's what you want? -- --Bryan From ldo at geek-central.gen.new_zealand Fri Dec 5 05:28:48 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 05 Dec 2008 23:28:48 +1300 Subject: Don't you just love writing this sort of thing :) References: <0148b086$0$20670$c3e8da3@news.astraweb.com> Message-ID: In message <0148b086$0$20670$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > Since the context has been deleted, it's hard to tell whether the code as > written by Lawrence ... If you want to reply to my message, reply to my message, don't reply to my reply to someone else's reply to my message. From prologic at shortcircuit.net.au Tue Dec 16 20:35:53 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 17 Dec 2008 11:35:53 +1000 Subject: How to modify a program while it's running? In-Reply-To: <01584cbd$0$20656$c3e8da3@news.astraweb.com> References: <01584cbd$0$20656$c3e8da3@news.astraweb.com> Message-ID: On Wed, Dec 17, 2008 at 11:26 AM, Steven D'Aprano wrote: >> So I'd like to restructure my app so that it can stay running and stay >> logged in, yet I can still update and reload at least most of the code. >> But I'm not sure what's the best way to do this. Should I move the >> reloadable code into its own module, and then when I give my bot a >> "reload" command, have it call reload on that module? Will that work, >> and is there a better way? > > That should work for functions, but less successfully with classes. The > problem is that existing objects will still have the old behaviour even > after reloading the class. You need to build a subscribe/unsubscribe facility. Or a plugin system :) My IRC/Jabber bot kdb uses such features and is capable of loading/unloading/reloading plugins on the fly. YOu're welcome to borrow some of it's code :) http://hg.softcircuit.com.au/projects/kdb/ cheers James From Scott.Daniels at Acm.Org Mon Dec 29 20:07:32 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 29 Dec 2008 17:07:32 -0800 Subject: get method In-Reply-To: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> Message-ID: Ross wrote: > ... Use get to write histogram more concisely. You should be able to > eliminate the if statement. > > def histogram(s): > d = dict() > for c in s: > d[c]= d.get(c,0) > return d > > This code returns a dictionary of all the letters to any string s I > give it but each corresponding value is incorrectly the default of 0. > What am I doing wrong? How is this code supposed to count? --Scott David Daniels Scott.Daniels at Acm.Org From jstroud at mbi.ucla.edu Mon Dec 15 05:40:08 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 15 Dec 2008 02:40:08 -0800 Subject: Need help improving number guessing game In-Reply-To: References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> Message-ID: feba wrote: > I don't see the aim of your changes to setup(). I can kinda understand > checking to make sure that you didn't make the minimum higher than the > maximum, but I think where you put minr/maxr would make it use the > same minr/maxr as the end of the previous game, wouldn't it? No. Each function call creates its own name space. The function as Bruno has written it will have default values (mini & maxi). A call to this function can set different values optionally: setup(2) #==> range from 2 to 99 setup(maxi=101) #==> range from 1 to 101 setup(5, 10) #==> range from 5 to 10 setup(10, 5) #==> throws an error >> Minor point for a short program, but still good practice : use >> constants. IE : > > I had done this initially, but it seemed wasteful and needlessly > confusing in this situation. No. Tracking down and changing hard-coded values within a module is wasteful and needlessly confusing. Creating well named and well documented module level constants is good style and will make your life easier in the long run. >> I assume 'p1sc' means "player_1_score" ? >> If so, you may want to use a dict for scores: > > I don't really understand dicts yet; actually, the tutorial I'm > following (http://www.briggs.net.nz/log/writing/snake-wrangling-for- > kids/ , designed for tweens, but other than the pointless anecdote and > joke here and there, I've found it a very good guide) doesn't even > seem to mention them, from a search of the pdf. Actually, apparently I > stopped and started working on this just before the chapter on > functions and modules. scores = {'player 1' : 0, 'player 2' : 0 } scores['player 2'] = 10 #==> now player 2's score is 10 scores['player 1'] += 1 #==> now player 1's score is 1 print scores['player 0'] #==> prints "0" print scores['player 2'] * 2 #==> prints "20" If you get that, you'll have about all you need to know about dicts to use them for keeping track of scores (and other values) in your game. > I'll look into that later on, but for now I'm pretty happy with how it > works. Try it sooner rather than later. I didn't get this kind of advice when I was first learning. It would have shaved months from my learning curve. >> You should either put this in it's own function (could be named 'main'), >> or at least "protect" it with an "if __name__ == '__main__':" test. > > Could you go into a bit more detail on this? I don't understand what > should be its own function, nor do I understand what that line would > do or how to use it. The idea is that everything you write is reusable and can be imported as a module. Upon importing a module, it's code is executed. So, as written, if someone imports it as a library module, they will start playing the game. Wrapping in the "if __name__ == '__main__':" test prevents the main loop of the game from executing on import. Only when the module is "__main__" will that test evaluate to true and its commands execute. For small programs like you have here, I'd do it like this (again combining ideas): def num_players(game, prompt='1 or 2 Players?\n> '): while True: num = input(prompt) try: num = int(num) except ValueError: print "Bad Value" else: break game['pnum'] = num def main(game=None): if game is None: game = {} print("WELCOME TO THE SUPER NUMBER GUESSING GAME!") num_players(game) game['play'] = 1 # P1 goes first game['player'] = "P1" #Scores, keep track of times player guessed first. game['p1sc'], game['p2sc'] = 0, 0 setup(game) while game['play'] == 1: guessing(game) if __name__ == "__main__": main() I just threw a little advanced stuff at you. But you would be doing yourself a huge favor if you struggled to understand it. The idea is that since game is a dict, you can modify game inside of the functions, and all you do is pass the game around to functions that need the values of its contents. For example: def setup(game): game['a'], game['b'] = 1, 99 game['target'] = random.randint(a, b) def playagain(game): playover = input("PLAY AGAIN? Y/N: ") if playover.strip().lower() == "y": game['play'] = 1 setup(game) else: print("GOOD BYE. PLAY AGAIN SOON!") quit() Notice that I just made return values obsolete. You will also notice that management of all of your values now becomes more tractable using the mutability of dict ("game"). Long, ugly lines now become simple function calls. See if you can understand what I'm doing here and try to propagate the idea through your game using the game dict. If you can do it, you'll be at least 80% of the way to understanding object oriented programming, by the way. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From zapwireDASHgroups at yahoo.com Mon Dec 29 18:49:46 2008 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Mon, 29 Dec 2008 15:49:46 -0800 Subject: Easy-to-use Python GUI References: Message-ID: Thanks to everyone who responded; I'll be checking out the various toolkits people have listed! ---Joel From venutaurus539 at gmail.com Wed Dec 3 02:06:50 2008 From: venutaurus539 at gmail.com (venutaurus539 at gmail.com) Date: Tue, 2 Dec 2008 23:06:50 -0800 (PST) Subject: Obtaining SMTP address of a sender and receiver of an outlook mail Message-ID: Hi all, I am trying to use python for extracting contents of an outlook email. For extracting the list of Recipients addresses I tried using the "MAPI.message.Recipients.Address" property, but the problem I am facing is that it is giving the complete DN name which is putting me in further complications. Is there any way to obtain the actual SMTP mail address (username at domain.com) from the above object? I searched for it in the MSDN help but couldn't succeed. Thanks in advance, Venu From mh at pixar.com Wed Dec 10 16:47:18 2008 From: mh at pixar.com (mh at pixar.com) Date: Wed, 10 Dec 2008 21:47:18 GMT Subject: var or inout parm? References: Message-ID: Chris Rebert wrote: > Not directly possible or encouraged. You can emulate it by sticking > the value in a container object (e.g. list) though: Thanks, that's just what I needed. I'm using this to monkeypatch a test driver into some code that I can't touch, otherwise I would just have the function return a tuple with the replacement values. Cheers! Mark -- Mark Harrison Pixar Animation Studios From simonharrison.uk at googlemail.com Tue Dec 9 06:21:29 2008 From: simonharrison.uk at googlemail.com (simonh) Date: Tue, 9 Dec 2008 03:21:29 -0800 (PST) Subject: Beginner trying to understand functions. References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> <9df7549a-f28b-4d39-b105-90c099f472f2@z28g2000prd.googlegroups.com> <040a2896-be99-477e-909c-c55c5a0e6665@y1g2000pra.googlegroups.com> Message-ID: Thanks for the extra tips Ivan and Bruno. Here is how the program looks now. Any problems? import sys def get_name(): name = input('Please enter your name: ') print('Hello', name) def get_age(): try: return int(input('Please enter your age: ')) except ValueError: print('That was not a valid number. Please try again.') return get_age() def check_age(age,min=18,max=31): if age < min: print('Sorry, too young.') elif age >= max: print('Sorry, too old.') else: print('Come on in!') def again(): response = input('Try again? Y or N: ') while response != "Y": if response == 'N': print('Program finished.') input('Press any key to exit.') sys.exit() else: return response run() def run(): get_name() a = get_age() check_age(a) again() run() From jstroud at mbi.ucla.edu Fri Dec 5 17:13:37 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 05 Dec 2008 14:13:37 -0800 Subject: dict subclass and pickle bug (?) In-Reply-To: References: <6J7_k.6212$hc1.5967@flpi150.ffdc.sbc.com> Message-ID: James Stroud wrote: > Terry Reedy wrote: >> because there is no bug to fix. I have suggesting closing. > > May I suggest to add something to this effect within the issue itself so > others won't spend time trying to figure out why the "bug" is still > open? Sorry, you did that. James From rdmurray at bitdance.com Fri Dec 19 21:42:14 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Sat, 20 Dec 2008 02:42:14 +0000 (UTC) Subject: ANN: New Book: Programming in Python 3 References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> <6r25ckFejl4vU1@mid.individual.net> <015c4890$0$20656$c3e8da3@news.astraweb.com> Message-ID: Quoth Steven D'Aprano : >The second exception is if the word ends with an S. In British English, >you put the apostrophe after the S: > >Thomas' approach is wholly practical. > >In American English, they often (but not always) add an extra S: > >Thomas's approach is wholly practical. > >which in my opinion is logical but ugly and should be avoided. I disagree. For indicating the possessive of the plural ("the books' spines were damaged), putting the apostrophe after makes perfect sense. However, when a word like "Thomas" is made possessive in American English, it is pronounced differently (eg: "Thomases"). In that case, spelling it Thomas's makes it read more like it sounds. So you may find it ugly, but I find it reads better to my ear :) --RDM From rocky at panix.com Sat Dec 20 22:18:44 2008 From: rocky at panix.com (R. Bernstein) Date: Sat, 20 Dec 2008 22:18:44 -0500 Subject: linecache vs egg - reading line of a file in an egg Message-ID: Does linecache work with source in Python eggs? If not, is it contemplated that this is going to be fixed or is there something else like linecache that currently works? Right now, I think pdb and pydb (and probably other debuggers) are broken when they try to trace into code that is part of an egg. Here's what I tried recently: Using this egg: http://pypi.python.org/packages/2.5/t/tracer/tracer-0.1.0-py2.5.egg I install that and look for the filename of one of the functions. Here's a sample session: >>> import tracer >>> tracer >>> tracer.size >>> tracer.size.func_code.co_filename 'build/bdist.linux-i686/egg/tracer.py' >>> tracer.size.func_code.co_firstlineno 216 >>> To read the source for tracer.py, information from "Accessing Package Resources" (http://peak.telecommunity.com/DevCenter/PythonEggs#accessing-package-resources) suggests: >>> from pkg_resources import resource_string >>> print resource_string('tracer', 'tracer.py') This gives me one long string which I can split and then index. Note that I used "tracer.py" above, not "build/bdist.linux-8686/egg/tracer.py" How do tracebacks and things that read frame information deal with the discrepency? Before reinventing the wheel and trying to extend linecache to do something like the above, has someone already come up with a solution? Thanks From rt8396 at gmail.com Mon Dec 22 22:09:06 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 19:09:06 -0800 (PST) Subject: iterating initalizations References: Message-ID: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> I can't check you code because i don't have these modules but here is the code with proper indention import random from rtcmix import * from chimes_source import * from rhythmblock import * from pitchblock import * indexrand = random.Random() indexrand.seed(2) rhythm = rhythmBlock() pitch = pitchBlock() class pitchAndRhythm: def __init__self: self.__abet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def listCreate(self, num): if num > 25: print "Oops. This won't work" else: for a in range(num): b = indexrand.randint(0, 3) c = indexrand.randint(0, 7) index = self.__abet[a] index = [ ] index = index.append(rhythm.rhythmTwist(b, c)) From mikael at isy.liu.se Thu Dec 18 11:05:32 2008 From: mikael at isy.liu.se (Mikael Olofsson) Date: Thu, 18 Dec 2008 17:05:32 +0100 Subject: confused about __str__ vs. __repr__ In-Reply-To: <6qv9v4Ff1lv9U1@mid.uni-berlin.de> References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> <6qv7kfFeuf65U1@mid.uni-berlin.de> <6qv9v4Ff1lv9U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Yep. And it's easy enough if you don't care about them being different.. > > def __repr__(self): > return str(self) If I ever wanted __str__ and __repr__ to return the same thing, I would make them equal: def __str__(self): return 'whatever you want' __repr__ = __str__ That makes it more obvious to me what's going on. As a bonus, it saves one method call for every repr call. /MiO From stefan_ml at behnel.de Fri Dec 12 09:43:01 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 12 Dec 2008 15:43:01 +0100 Subject: Python is slow In-Reply-To: References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> Message-ID: <49427875$0$30229$9b4e6d93@newsspool1.arcor-online.net> David Cournapeau wrote: > I want faster function > calls to use with numpy: do you know of any solution ? http://cython.org/ Stefan From noone at lewscanon.com Tue Dec 2 22:28:23 2008 From: noone at lewscanon.com (Lew) Date: Tue, 02 Dec 2008 22:28:23 -0500 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <591e8625-7e4d-4db8-ae6c-73c4370f8088@q26g2000prq.googlegroups.com> Message-ID: George Sakkis wrote: > As a Slashdotter would put it... you must be new here ;-) For certain values of "here". I've seen Xah before, and I'm happy to engage if he behaves himself. Some of his initial ideas I actually find engaging. His followups leave a lot to be desired. f/u set to comp.lang.functional. It looks like he's got nothing to offer us Java weenies this time around. -- Lew From phd at phd.pp.ru Mon Dec 1 08:49:27 2008 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 1 Dec 2008 16:49:27 +0300 Subject: SQLObject 0.10.3 Message-ID: <20081201134927.GG19187@phd.pp.ru> Hello! I'm pleased to announce version 0.10.3, a minor bugfix release of 0.10 branch of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.10.3 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.10.2 ----------------- * Changed interpretation of strings in the DB URI for boolean parameters: '0', 'no', 'off' and 'false' are now interpreted as False. * Fixed a bug with incorrect handling of calls like connectionForURI(dburi, cache=False) when dburi already contains some parameters in the URI. * Convert decimal.to_eng_string() to str to work around a bug in Python 2.5.2; see http://mail.python.org/pipermail/python-dev/2008-March/078189.html * Added test_default_style.py. * Fixed a minor bug in SQLiteConnection that fails to parse Enum columns. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From prologic at shortcircuit.net.au Tue Dec 30 18:44:53 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 09:44:53 +1000 Subject: [ANN]: circuits-1.0b1 released! Message-ID: Hi all, I'm pleased to announce the release of circuits-1.0b1 Overview ====== circuits is an event-driven framework with a focus on Component Software Architectures where System Functionality is defined in Components. Components communicate with one another by propagating events throughout the system. Each Component can react to events and expose events to other parts of the system Components are able to manage their own events and can also be linked to other Components. circuits has a clean architecture and has no external dependencies on any other library. It's simplistic design is unmatchable but yet delivers a powerful framework for building large, scalable, maintainable applications and systems. circuits was a core integral part of the pymills library developed in 2006 and was partly inspired by the Trac architecture. Quick Examples -------------------- Hello World! ~~~~~~~~ >>> from circuits.core import listener, Component, Event, Manager >>> >>> class Hello(Component): ... @listener("hello") ... def onHELLO(self): ... print "Hello World!" >>> manager = Manager() >>> manager += Hello() >>> manager.push(Event(), "hello") >>> manager.flush() Hello World! Hello Web! ~~~~~~~ from circuits.lib.web import Server, Controller class HelloWorld(Controller): def index(self): return "Hello World!" server = Server(8000) server += HelloWorld() server.run() Hello Web! (WSGI) ~~~~~~~~~~~~ from circuits.lib.web import Application, Controller class HelloWorld(Controller): def index(self): return "Hello World!" application = Application() application += HelloWorld() Download circuits using easy_install or from here: http://trac.softcircuit.com.au/circuits/downloads or from the Python Package Index. Please visit the circuits website for more information about circuits, or to file bug reports or enhancements. http://trac.softcircuit.com.au/circuits/ --JamesMills -- -- -- "Problems are solved by method" From clp at rebertia.com Thu Dec 11 19:08:11 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 11 Dec 2008 16:08:11 -0800 Subject: Dictionary as Keyword Arguments In-Reply-To: References: Message-ID: <47c890dc0812111608n712c9f2fr2a1949df6b02b75e@mail.gmail.com> On Thu, Dec 11, 2008 at 4:02 PM, bfrederi wrote: > I was wondering if I had a dictionary of keywords and values like so: > > keyword_arg_dict = { > 'attribute': 'stone', > 'contents': 'cave people', > 'path': '/path/to/cave', > 'name': 'Ogg's Cave', > } > > And I had a function that accepted keyword arguments like so: > > make_dwelling( > attribute='stone', > contents='cave people', > path='/path/to/cave', > name='Ogg's Cave', > ) > > Is there any way I could use my keyword_arg_dict as my keyword args > for the make_dwelling function, since I am not the creator of the > make_dwelling function, and need to take that dictionary of key-value > pairs and turn it into keyword-value arguments for the make_dwelling > function? make_dwelling(**keyword_arg_dict) Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > From patrickstinson.lists at gmail.com Mon Dec 1 01:05:35 2008 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Sun, 30 Nov 2008 21:05:35 -0900 Subject: incorrect line reported in traceback In-Reply-To: References: Message-ID: <6214d7a20811302205tad3bdf5n8f690a873d93eaa4@mail.gmail.com> No, I've embedded the interpreter and an editor in my app, which might have something to do with it. I can't run the scripts at the command line because my app provides an API to built-ins that isn't availbel in the standard interpreter. I am simply calling a python method in the script module using PyObject_CallObject(), and fetching the traceback using PyErr_Fetch() and PyErr_Normalize(), like this: PyObject *type, *value, *traceback; PyErr_Fetch(&type, &value, &traceback); PyErr_NormalizeException(&type, &value, &traceback); if(traceback) // traceback.tb_lineno *lineno = ((PyTracebackObject *) traceback)->tb_lineno; On Sun, Nov 30, 2008 at 8:59 PM, John Machin wrote: > On Dec 1, 4:47 pm, "Patrick Stinson" > wrote: >> Is there any reason why the last item in the traceback is one frame >> below the top of the stack? It would be great to show the real line in >> my editor... > > Maybe your anonymous [HINT!] editor is confused. Do you get the same > problem when you run your script at the shell prompt? > -- > http://mail.python.org/mailman/listinfo/python-list > From xahlee at gmail.com Thu Dec 11 13:36:42 2008 From: xahlee at gmail.com (Xah Lee) Date: Thu, 11 Dec 2008 10:36:42 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> Message-ID: <76f52f8a-5520-4cf6-9be6-fe7acb3483f6@s1g2000prg.googlegroups.com> Xah Lee wrote: ? A Example of Mathematica's Expressiveness http://xahlee.org/UnixResource_dir/writ/Mathematica_expressiveness.html On Dec 11, 3:53 am, "William James" wrote: > function normal( ary ) > { var div = Math.sqrt( > ary.map(function(x) x*x).reduce(function(a,b) a+b) ) > return ary.map(function(x) x/div) > > } I run your code in SpiderMonkey: // SpiderMonkey javascript. By William James. function normal(v) { var div=Math.sqrt(v.map(function(x) x*x).reduce(function(a,b) a+b)) return v.map(function(x) x/div) } print normal [3,4]; i got: /Users/xah/Documents/temp/xx.js:3: SyntaxError: missing { before function body: /Users/xah/Documents/temp/xx.js:3: var div=Math.sqrt(v.map(function(x) x*x).reduce(function(a,b) a+b)) /Users/xah/Documents/temp/xx.js: 3: ....................................^ Xah ? http://xahlee.org/ ? From pdorange at pas-de-pub-merci.mac.com Sat Dec 27 03:13:58 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Sat, 27 Dec 2008 09:13:58 +0100 Subject: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> <90f06b27-39da-4f1a-a878-f3972e942d57@s24g2000vbp.googlegroups.com> <62caf93b-0455-4450-9895-8a9d9554f75e@r32g2000vba.googlegroups.com> <1isezkk.51e05y1457jqrN%pdorange@pas-de-pub-merci.mac.com> <3cb2a746-1a43-44a1-9825-7667af9fe2fa@s1g2000prg.googlegroups.com> <1isi4sn.11mpft612g7udcN%pdorange@pas-de-pub-merci.mac.com> <1isk1kn.1s8efppxapfeaN%pdorange@pas-de-pub-merci.mac.com> <301a2968-21d6-475d-958c-890e0fc27249@m15g2000vbl.googlegroups.com> Message-ID: <1islo9k.bm5j6213cuveoN%pdorange@pas-de-pub-merci.mac.com> r wrote: > > > Go to Google groups... it looks perfect :) > > > > It's a usenet group here, nothing to do with google groups. > > To get back to the group subject, what is your actual python projects ? > > I am crusading to bring python scripting to Google SketchUp, do want > to get on board? I've other real project on the run, no crusade just programming. Google sketchup doesn't really interest me, sorry... -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From duncan.booth at invalid.invalid Tue Dec 30 14:40:17 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Dec 2008 19:40:17 GMT Subject: thread, multiprocessing: communication overhead References: Message-ID: mk wrote: >> CMIIW, but I believe your timing function includes the time to launch >> the actual processes and threads, create the synch. objects, etc. You >> might try it again, creating them first, starting the timer, then >> loading them. > > Except I don't know how to do that using timeit.Timer. :-/ > Easy enough: put the code into a class which creates the worker pool when instantiated and has a method to execute the code you want to time. Then you create an instance from the setup argument and time a call to the method. From tn.pablo at gmail.com Tue Dec 9 09:45:06 2008 From: tn.pablo at gmail.com (ptn) Date: Tue, 9 Dec 2008 06:45:06 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> <8b8d1fb3-f49e-49bf-8cfe-eeee5ed16109@r37g2000prr.googlegroups.com> Message-ID: <57eea3ce-0171-44ce-a8cf-d2510b7834e9@a29g2000pra.googlegroups.com> On Dec 6, 10:15?am, "Russ P." wrote: > On Dec 6, 4:32?am, Andreas Waldenburger wrote: > > > > > On Sat, 6 Dec 2008 04:02:54 -0800 (PST) bearophileH... at lycos.com wrote: > > > > class C: > > > ? ? def $method(arg): > > > ? ? ? ? $value = arg > > > > (Note there's no point after $, it's not currently possible). > > > Ruby uses @ and @@ for similar purposes. > > > I agree that the code looks worse, but also shorter to read and write, > > > so in lines of code that use many instance attributes, that short $ > > > syntax helps keep the line shorter. So I may grow to accept this > > > sugar... > > > But that is not the way Python is meant to work. There are several > > tennets in the Zen of Python that don't chime well with this approach. > > "self" is a speaking identifier, "$" isn't. > > Is "@" a "speaking identifier? How about "#" and "!="? Last I heard, > they were all part of Python. Those are operators and the comment starter, not identifiers. I think that the more used an operator/variable is, the least mnemonic it' name has to be. Given that you'll be useing it all the time, you don't need it's name reminding you what it's supposed to be used for. So the "it's not a speaking-identifier" argument is not a good one, in my opinion. However, $ being ugly is a very strong argument. Python is supposed to be beautiful. And sure you can get used to it, just as you can get used to Pearl, assembly language or Brainfuck. By beautiful we mean beautiful at first sight. From steve at holdenweb.com Tue Dec 30 13:46:14 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Dec 2008 13:46:14 -0500 Subject: Parsing Excel spreadsheets In-Reply-To: <495A6033.6040908@wildenhain.de> References: <6a54de23-bea4-40c7-ad7c-22c6eba4bd8a@z6g2000pre.googlegroups.com> <4894d0fe-a238-4675-9e79-0b0755c001e8@y1g2000pra.googlegroups.com> <495A6033.6040908@wildenhain.de> Message-ID: Tino Wildenhain wrote: > r wrote: >> On Dec 30, 10:07 am, "andyh... at gmail.com" wrote: >>> Hi, >>> >>> Can anybody recommend an approach for loading and parsing Excel >>> spreadsheets in Python. Any well known/recommended libraries for this? >>> >>> The only thing I found in a brief search >>> washttp://www.lexicon.net/sjmachin/xlrd.htm, >>> but I'd rather get some more input before going with something I don't >>> know. >>> >>> Thanks, >>> Andy. >> >> xlrd(read only) >> also see pyExcelerator > > which is now replaced by xlwt :-) > I've had very good results with xlrd, having used it to extract data from spreadsheets for storage into a relational database. It's also cross-platform, which means you don't need to run under Windows. I don't know anything at all about xlwt. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From mu at problemlos.ch Thu Dec 18 09:28:36 2008 From: mu at problemlos.ch (Kurt Mueller) Date: Thu, 18 Dec 2008 15:28:36 +0100 Subject: Minor Typo in doc Message-ID: <494A5E14.10508@problemlos.ch> Hi There is a minor typo in the new doc in: http://www.python.org/doc/2.6/library/signal.html ------------------------------------------------------------------ signal.SIG_DFL? This is one of two standard signal handling options; it will simply perform the default function for the signal. For example, on most systems the default action for SIGQUIT is to dump core and exit, while the default action for SIGCLD is to simply ignore it. ------------------------------------------------------------------ SIGCLD should be SIGCHLD Should I make a bug report in http://bugs.python.org? Gr?essli -- Kurt M?ller, mu at problemlos.ch From Ron.Barak at lsi.com Thu Dec 25 02:27:23 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Thu, 25 Dec 2008 07:27:23 +0000 Subject: How to change a generator ? - resolved In-Reply-To: <495278BA.7040301@mrabarnett.plus.com> References: <7F0503CD69378F49BE0DC30661C6CCF6024946E6@enbmail01.lsi.com> <49526B7E.20904@mrabarnett.plus.com> <495278BA.7040301@mrabarnett.plus.com> Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6024946EC@enbmail01.lsi.com> Hi Gabriel, Your remarks fixed my problem. Now my code looks as below, and behaves as expected. Thanks Gabriel. Merry Christmas and Happy Hanukkah, Ron. $ cat generator.py #!/usr/bin/env python import gzip from Debug import _line as line class LogStream(): def __init__(self, filename): self.filename = filename self.input_file = self.open_file(filename) def open_file(self, in_file): try: f = gzip.GzipFile(in_file, "r") f.readline() except IOError: f = open(in_file, "r") f.readline() f.seek(0) return(f) def line_generator(self): print line()+". self.input_file.tell()==",self.input_file.tell() while True: line_ = self.input_file.readline() print line()+". self.input_file.tell()==",self.input_file.tell() if not line_: break yield line_.strip() if __name__ == "__main__": filename = "sac.log.50lines" log_stream = LogStream(filename) log_stream.input_file.seek(0) line_generator = log_stream.line_generator() line_ = line_generator.next() $ python generator.py 23. self.input_file.tell()== 0 26. self.input_file.tell()== 247 $ !wc wc -c sac.log.50lines 6623 sac.log.50lines $ -----Original Message----- From: MRAB [mailto:google at mrabarnett.plus.com] Sent: Wednesday, December 24, 2008 20:00 To: python-list at python.org Subject: Re: How to change a generator ? Gabriel Genellina wrote: > En Wed, 24 Dec 2008 15:03:58 -0200, MRAB > escribi?: > >>> I have a generator whose aim is to returns consecutive lines from a >>> file (the listing below is a simplified version). >>> However, as it is written now, the generator method changes the text >>> file pointer to end of file after first invocation. >>> Namely, the file pointer changes from 0 to 6623 on line 24. >>> >> It might be that the generator method of self.input_file is reading >> the file a chunk at a time for efficiency even though it's yielding a >> line at a time. > > I think this is the case too. > I can think of 3 alternatives: > > a) open the file unbuffered (bufsize=0). But I think this would > greatly decrease performance. > > b) keep track internally of file position (by adding each line length). > The file should be opened in binary mode in this case (to avoid any '\n' > translation). > > c) return line numbers only, instead of file positions. Seeking to a > certain line number requires to re-read the whole file from start; > depending on how often this is required, and how big is the file, this > might be acceptable. > readline() appears to work as expected, leaving the file position at the start of the next line. -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.simionato at gmail.com Thu Dec 4 04:19:41 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 4 Dec 2008 01:19:41 -0800 (PST) Subject: Pythonic design patterns References: Message-ID: <7cfb208a-cdf7-4932-9356-00c0428a8497@d14g2000yqb.googlegroups.com> On Dec 4, 10:09?am, Slaunger wrote: > Hi comp.lang.python > > I am this novice Python programmer, who is not educated as a computer > scientist (I am a physicist), and who (regrettably) has never read the > GOF on design patterns. > > I find myself spending a lot of time in Python making some designs, to > solve some task, which is the end turn out to be closely related to > well established design patterns / programming idioms, which other > users in this forum has been kind enough to point out. Only my > implementations are often not that clean, and I may call things > something different than the normal convention, which is a source of > confusion for myself and others trying to communicate with me. > > I guess I could boost my productivity by learning these well-proven > and well-established design patterns by heart. > > I was therefore wondering if you could recommend a book or a resource > concerning design patterns with special focus on the possibilities in > Python? > > In that manner I may be able to both learn programming more pythonic > AND learn the design patterns. > > -- Slaunger The Python Cookbook (the printed version) is the best you can find in this direction. Also, consider the more recent "Expert Python Programming" by Tarek Ziade'. From sjmachin at lexicon.net Thu Dec 4 18:11:16 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 4 Dec 2008 15:11:16 -0800 (PST) Subject: Checking if an int fits in 32 bits? References: Message-ID: On Dec 5, 7:11?am, Roy Smith wrote: > At first I thought pack() might raise an exception on a value > overflow, that but doesn't seem to be the case: > > >>> [hex(ord(c)) for c in struct.pack('!i', 999999999999999999999L)] > > ['0xde', '0x9f', '0xff', '0xff'] Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 >>> import struct >>> [hex(ord(c)) for c in struct.pack('!i', 999999999999999999999L)] __main__:1: DeprecationWarning: struct integer overflow masking is deprecated ['0xde', '0x9f', '0xff', '0xff'] You must be using an older version of Python. I'd go with Jean-Paul's suggestion of (inline no-function-call- overhead portable no-bit-twiddling) bounds checking. Cheers, John From cournape at gmail.com Fri Dec 12 19:41:09 2008 From: cournape at gmail.com (David Cournapeau) Date: Sat, 13 Dec 2008 09:41:09 +0900 Subject: How do I manually uninstall setuptools (installed by egg)? In-Reply-To: References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> <47c890dc0812091904p12e75510sbe0b8858eb2f6d9e@mail.gmail.com> Message-ID: <5b8d13220812121641u3b3d90dgaa242eec3a9ffc43@mail.gmail.com> On Sat, Dec 13, 2008 at 1:30 AM, Nick Craig-Wood wrote: > David Cournapeau wrote: >> On Thu, Dec 11, 2008 at 10:30 PM, Nick Craig-Wood wrote: >> > David Cournapeau wrote: >> >> On Wed, Dec 10, 2008 at 12:04 PM, Chris Rebert wrote: >> >> > On Tue, Dec 9, 2008 at 6:49 PM, wrote: >> >> >> On Ubuntu, I accidentally manually installed setuptools >> >> >> http://pypi.python.org/pypi/setuptools/0.6c9 (by running the .egg file >> >> >> as a shell script via sudo), and now realize I should just be using >> >> >> apt to take care of my system Python packages. >> >> > >> >> > Really, why? setuptools has more Python packages/programs available >> >> > and updates faster than Debian. >> >> > It's also likely that some of the Debian Python packages are installed >> >> > using setuptools anyway. >> >> > So, why do you think apt and not setuptools is The Right Way(tm)? >> >> >> >> Setuptools is certainly not the right way to install packages >> >> system-wide on debian, it is very likely to break the whole thing. >> > >> > It wouldn't be too difficult to make a .deb target which would collect >> > all the files that did get installed into a package. It would be a >> > rather rough and ready package but would do the job. >> >> Depends what you mean by would do the job: rather rough certainly does >> not mean "would do the job" for something as essential as a package >> IMO. > > Essentially a package has files in it in a fixed possition in the > filesystem. The package manager's (dpkg at this level) job is to keep > track of those file and tell you about conflicts. Yes, but this description is so high level that it hides the difficulty of the task :) First, and firstmost, it is difficult if not impossible to automatically translate from distutils/setuptools file locations to a typical debian (or most other distribution for that matter - the one which follow the FHS) description. Because distutils does not make the distinction between doc, data, etc... as well as for example autotools does. > > You can use alien to turn a tar.gz into a perfectly usable debian > package. It won't have dependencies, or help or any of the other > things a package needs to be a proper package, but it satisfies my > basic needs that all software is installed as packages, so it can be > uninstalled cleanly. This only works for very simple packages - pure python or no dependencies, no post/pre install scripts, etc... If you want to install a web framework, it won't be enough. If you want to install a package which depends on C libraries, it won't work either. > > However when I have to make my stuff work on Windows, I find > easy_install to be a fantastic timesaver as compared to looking for > the package on a web site, downloading it, unpacking it installing it > and then repeating for all the dependencies. I agree that its features are useful. I just don't think the implementation and the design are right - partly because it inherits some fundamental distutils deficiencies with respect to package description. David From python-url at phaseit.net Mon Dec 29 07:44:19 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 29 Dec 2008 12:44:19 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Dec 29) Message-ID: QOTW: "The fundamental economics of software development leads you to open-source software." David Rivas http://www.ddj.com/linux-open-source/212201757 Python 2.5.4 final released (replaces 2.5.3 due to a critical bug) http://groups.google.com/group/comp.lang.python/t/4042c08bbbb783c2/ Doing set operations with non-hashable objects: http://groups.google.com/group/comp.lang.python/t/83972f948754ee36/ Reading a file one line at a time *and* getting accurate line offsets: http://groups.google.com/group/comp.lang.python/t/7cd79e287ebf51cf/ Moving from C to Python: how to represent a sequence of bytes? http://groups.google.com/group/comp.lang.python/t/1ee718148cecc39f/ Keeping track of all instances of a class: http://groups.google.com/group/comp.lang.python/t/3ceee5e64d909bce/ return, return None, or nothing? Which is the right one to choose? http://groups.google.com/group/comp.lang.python/t/99d0ba4075f6684e/ Best way to find the differences between two large dictionaries: http://groups.google.com/group/comp.lang.python/t/4f3220dce8a3cf23/ xkcd Christmas special contains another Python reference: http://xkcd.com/521/ ======================================================================== 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 Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From alia_khouri at yahoo.com Sun Dec 7 07:03:47 2008 From: alia_khouri at yahoo.com (Alia Khouri) Date: Sun, 7 Dec 2008 04:03:47 -0800 (PST) Subject: Source code generation using Python References: <82098706-978f-4920-ac75-57ef3573ac44@x38g2000yqj.googlegroups.com> Message-ID: <3b44efcd-a909-4465-b2aa-f05544aa1c4b@k8g2000yqn.googlegroups.com> > Any suggestions? I've happily used Cheetah with Leo (http://webpages.charter.net/ edreamleo/front.html) to organise and script my code generation needs, but you may also be happy with cog (http://nedbatchelder.com/code/ cog/). AK From clp at rebertia.com Tue Dec 9 22:04:22 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 9 Dec 2008 19:04:22 -0800 Subject: How do I manually uninstall setuptools (installed by egg)? In-Reply-To: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> Message-ID: <47c890dc0812091904p12e75510sbe0b8858eb2f6d9e@mail.gmail.com> On Tue, Dec 9, 2008 at 6:49 PM, wrote: > On Ubuntu, I accidentally manually installed setuptools > http://pypi.python.org/pypi/setuptools/0.6c9 (by running the .egg file > as a shell script via sudo), and now realize I should just be using > apt to take care of my system Python packages. Really, why? setuptools has more Python packages/programs available and updates faster than Debian. It's also likely that some of the Debian Python packages are installed using setuptools anyway. So, why do you think apt and not setuptools is The Right Way(tm)? Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From muhamed.hmd at gmail.com Wed Dec 10 14:09:14 2008 From: muhamed.hmd at gmail.com (john adam) Date: Wed, 10 Dec 2008 11:09:14 -0800 (PST) Subject: conratulations....... Message-ID: conratulatios...... Here's my dear friend largest mobile library programs All you care programs : Witness all the programs in the modern world Alkmiotr Honored by your visit You'll see in the blogger 1.If you are suffering from a virus protection programs most important to you AVG Anti-Virus Free Edition "avG" http://mesotheliomame.blogspot.com/2008/11/pericardial-mesothelioma-and-modern.html 2.If you turn suffering from transmitting the files LimeWire Pro 4.14.7 http://mesotheliomame.blogspot.com/2008/11/overview-of-mesothelioma-cancer.html 3.If you have files you spy on your computer solution Ad-Aware 2008 http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawsuits-faq.html 4.You stronger virus program Ante 2008 Avira AntiVir Personal - Free Antivirus http://mesotheliomame.blogspot.com/2008/11/number-form-of-mesothelioma-pleural.html 5.Now a program of protection and anti-virus and anti-spy files Avast Home Edition http://mesotheliomame.blogspot.com/2008/11/what-to-look-for-in-california.html 6.If you are suffering from non-fast you download this program FrostWire http://mesotheliomame.blogspot.com/2008/11/if-you-are-diagnosed-with-mesothelioma_15.html 7.If you have difficulty loading of the Diaspora and Google Orbit Downloader http://mesotheliomame.blogspot.com/2008/11/if-you-are-diagnosed-with-mesothelioma.html 8.If you have difficulty difficult compression "file" winrar http://mesotheliomame.blogspot.com/2008/11/contacting-mesothelioma-lawyer.html 9.If you are suffering from aAdware/Malware files you solution Malwarebytes' Anti-Malware http://mesotheliomame.blogspot.com/2008/11/scientists-conduct-clincial-trials-of.html 10.Now the most powerful video chat in the world Camfrog Video Chat http://mesotheliomame.blogspot.com/2008/11/new-drug-study-for-abdominal.html 11.Program chat world is a lot mIRC http://mesotheliomame.blogspot.com/2008/11/ohio-mesothelioma-lawyer-help-you-get.html 12.If you have difficulty reading flv files FLV Player http://mesotheliomame.blogspot.com/2008/11/detailed-information-on-mesothelioma.html 13.If you have difficulty download from youtube YouTube Downloader http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawyers-in-high-demand.html 14.If you are suffering from penetrating the strongest program you repel breakthroughs in the world Spybot - Search & Destroy http://mesotheliomame.blogspot.com/2008/11/chemotherapy-treatment-for-mesothelioma.html 15.If you have difficulty with the way they spread the images IrfanView http://mesotheliomame.blogspot.com/2008/11/california-mesothelioma-laws-and.html 16.Now have a major program of the torrent file and upload files BitComet http://mesotheliomame.blogspot.com/2008/11/facing-mesothelioma-without-california.html 17.The program is exclusive download from the Web at high speed Download Accelerator Plus http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-diagnoses-increase_15.html 18.If you are suffering from problems with the performance of the solution you Smart Defrag http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-diagnoses-increase.html 19.If you have difficulty in performing the solution you Advanced WindowsCare Personal http://mesotheliomame.blogspot.com/2008/11/mesothelioma-is-deadly-cancer.html 20.If you have difficulty in operating the sound and video files you solution real player http://mesotheliomame.blogspot.com/2008/11/facts-and-misconceptions-about.html 21.Here is the most important video player program in America GOM Media Player http://mesotheliomame.blogspot.com/2008/11/how-severe-is-mesothelioma-disease.html 22.If you have difficulty operating Flash Games Flash Player http://mesotheliomame.blogspot.com/2008/11/glimpse-at-mesothelioma-info-from-past.html 23.If you have difficulty in cleaning Riggstir professionally you the best solution http://mesotheliomame.blogspot.com/2008/11/detection-of-asbestos-mesothelioma.html 24.If you turn suffering from your computer and the difficulty you download this program"System Mechanic" http://mesotheliomame.blogspot.com/2008/11/brief-overview-of-malignant.html 25.If you are suffering from problems in the cleaning solution you Riggstir http://mesotheliomame.blogspot.com/2008/11/mesothelioma-and-911.html 26.Use the latest hour computer in the world in the magnificence of beauty http://mesotheliomame.blogspot.com/2008/11/precise-idea-about-pericardial.html 27.If you have difficulty in maintaining from hard disk http://mesotheliomame.blogspot.com/2008/11/mesothelioma-at-glance.html 28.If you have difficulty in managing personal and protection of your system you program http://mesotheliomame.blogspot.com/2008/11/financial-burden-of-mesothelioma.html 29.If you have difficulty in recording data and operation of your system http://mesotheliomame.blogspot.com/2008/11/how-to-find-mesothelioma-lawyer.html 30.Here's this program that offers you much time http://mesotheliomame.blogspot.com/2008/11/hurricane-victims-at-risk-for.html 31.If you have difficulty in browsing files http://mesotheliomame.blogspot.com/2008/11/3-top-florida-mesothelioma-lawyer.html 32.Here's this program, which automatically corrects the mistakes of your system security http://mesotheliomame.blogspot.com/2008/11/if-diagnosed-with-mesothelioma-call.html 33.The enjoyment of this program to register images from camera to the computer during the talk http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-diagnosed-questions.html 34.If you have difficulty transforming stretches in games or votes you this giant http://mesotheliomame.blogspot.com/2008/11/mesothelioma-ready-reckoner.html 35.If you have difficulty in operation all formats video files http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawyers-how-to-choose-them.html 36.If you have difficulty in the organization and ease of cleaning solution you http://mesotheliomame.blogspot.com/2008/11/mesothelioma-exposure-could-be-fatal.html 37.Very popular program in the compression winzip http://mesotheliomame.blogspot.com/2008/11/mesothelioma-greed-cancer-profits.html 38..If you want to broadcast material on the Internet you solution Virtual DJ Software http://mesotheliomame.blogspot.com/2008/11/abc-mesothelioma-new-treatments-for.html 39.now The creation of program files pdf PrimoPDF http://mesotheliomame.blogspot.com/2008/11/abc-mesothelioma-treatments-for.html 40..If you have difficulty operating the extensions you solution "MPEG-1, MPEG-2, MPEG-DivX, mp3, ogg VLC Media Player http://mesotheliomame.blogspot.com/2008/11/brachytherapy-for-treatment-of.html 41.If you have difficulty browser you this treasure Mozilla Firefox http://mesotheliomame.blogspot.com/2008/11/asbestos-mesothelioma-treatment-how.html 42.If you are difficult to clean your computer you solution Glary Utilities http://mesotheliomame.blogspot.com/2008/11/mesothelioma-treatment-research.html 43.very Free program to repair and improve and see photos PhotoScape http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-history.html 44.If you have difficulty operating films and cartoons BS.Player http://mesotheliomame.blogspot.com/2008/11/mesothelioma-attorney.html 45.Conversion formulas giant cylinders to the chimerical not want the program ... PowerISO http://mesotheliomame.blogspot.com/2008/11/deadly-mesothelioma-symptoms-could-be_15.html 46.You program the operator of high-quality video DivX for Windows with DivX Player http://mesotheliomame.blogspot.com/2008/11/deadly-mesothelioma-symptoms-could-be.html 47.If you have difficulty copies of CDs nero "9"new http://mesotheliomame.blogspot.com/2008/11/association-of-asbestos-and.html 48.If you have difficulty audio chat on the net you the solution Windows Live Messenger http://mesotheliomame.blogspot.com/2008/11/need-for-mesothelioma-lawyer-to-fight.html 49.If you have difficulty download on the net ActiveX Download Control http://mesotheliomame.blogspot.com/2008/11/funding-for-mesothelioma-research-noble_15.html 50.If you have difficulty in registration at the sites and forums you solution RoboForm http://mesotheliomame.blogspot.com/2008/11/funding-for-mesothelioma-research-noble.html 51.If you are an amateur or design you a solution designed sites you Adobe Photoshop CS3 Extended http://mesotheliomame.blogspot.com/2008/11/brief-overview-of-peritoneal.html 52.If you have difficulty cleaning you stronger cleaning program in the world ccleaner http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawyers-helping-hands.html 53.If you have difficulty in Alturrent know what files you need them all uTorrent http://mesotheliomame.blogspot.com/2008/11/how-to-proceed-with-mesothelioma_15.html 54.If you have difficulty in loading files from the iPod Lalai iTunes http://mesotheliomame.blogspot.com/2008/11/how-to-proceed-with-mesothelioma.html 55.If you have difficulty converting audio files to any formulas you solution Easy CD-DA Extractor http://mesotheliomame.blogspot.com/2008/11/difference-between-pleural-and.html 56.If you have difficulty converting video files to the formula psp PSP Video 9 http://mesotheliomame.blogspot.com/2008/11/positive-guideline-to-deal-with.html 57.If you have difficulty in the work of videos from YouTube to evict you like you solution Windows Movie Maker http://mesotheliomame.blogspot.com/2008/11/history-of-asbestos-related.html 58.If you have difficulty in Works with all audio files extranet windows media player http://mesotheliomame.blogspot.com/2008/11/tips-on-choosing-your-mesothelioma.html 59.If you have difficulty in Browser you the most powerful browser in the world Avant Browse http://mesotheliomame.blogspot.com/2008/11/good-mesothelioma-attorney-is-hard-to.html 60.If you have difficulty in Video-sharing to you this wonderful program BearFlix http://mesotheliomame.blogspot.com/2008/11/peritoneal-mesothelioma-information.html 61.If you have difficulty in Survey of spyware on your computer SpywareBlaster http://mesotheliomame.blogspot.com/2008/11/how-to-care-for-someone-with.html 62.If you are suffering from problems in Alhard Disek you this legend smart PerfectDisk http://mesotheliomame.blogspot.com/2008/11/why-is-mesothelioma-so-deadly.html 63.If you have difficulty in the liberation of files "pdf" http://mesotheliomame.blogspot.com/2008/11/when-do-you-need-mesothelioma-attorney.html 64.If you have difficulty in personal control of your system next to you http://mesotheliomame.blogspot.com/2008/11/all-about-mesothelioma-lawyer.html 65.If you have difficulty in the key to jump easily be you next http://mesotheliomame.blogspot.com/2008/11/what-is-mesothelioma-cancer.html 66.If you have difficulty playing in the pictures and the amendment http://mesotheliomame.blogspot.com/2008/11/mesothelioma-information.html 67.If you have difficulty in protecting your system security followed CAPS http://mesotheliomame.blogspot.com/2008/11/symptoms-of-mesothelioma.html 68.If you have difficulty in speed of your computer you this program http://mesotheliomame.blogspot.com/2008/11/what-radical-mesothelioma-treatments.html 69.If you have difficulty maintaining a malfunction in your computer that you legend http://mesotheliomame.blogspot.com/2008/11/can-washington-mesothelioma-attorneys.html 70.If you have difficulty in the transfer of files between disks http://mesotheliomame.blogspot.com/2008/11/causes-of-mesothelioma-cancer.html 71.Discovered the most important program on the Web EZ Macros http://mesotheliomame.blogspot.com/2008/11/mesothelioma-treatment-radiation-or.html 72.If you are suffering from similar files, you repeat this unique program http://mesotheliomame.blogspot.com/2008/11/types-of-mesothelioma-cancer.html http://mesotheliomame.blogspot.com/ From R.Bauer at fz-juelich.de Thu Dec 18 08:56:44 2008 From: R.Bauer at fz-juelich.de (Reimar Bauer) Date: Thu, 18 Dec 2008 14:56:44 +0100 Subject: something else instead of PIL? In-Reply-To: References: Message-ID: skip at pobox.com schrieb: > Reimar> Hi what has happened to PIL? No updates since two years. > > It's well-written, stable code. As far as I know it does what people want > (at least it's done everything I've needed when I've used it). Why should > it matter that there hasn't been an official release in two years? > I am interested to get some new features added e.g. some special conversion routines for colorblind people. http://scien.stanford.edu/class/psych221/projects/05/ofidaner/colorblindness_project.htm How can that be archieved? cheers Reimar From castironpi at gmail.com Wed Dec 10 01:45:03 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 9 Dec 2008 22:45:03 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> Message-ID: On Dec 9, 12:40?pm, MRAB wrote: > Aaron Brady wrote: > > On Dec 9, 8:28 am, MRAB wrote: > > snip > >> In some languages (I think Delphi is one of them - it's been a while!) > >> some words which would normally be identifiers have a special meaning in > >> certain contexts, but the syntax precludes any ambiguity, and not in a > >> difficult way. "as" in Python was one of those. > > >> I certainly wouldn't want something like PL/I, where "IF", "THEN" and > >> "ELSE" could be identifiers, so you could have code like: > > >> ? ? ?IF IF = THEN THEN > >> ? ? ? ? ?THEN = ELSE; > >> ? ? ?ELSE > >> ? ? ? ? ?ELSE = IF; > > >> Seehttp://en.wikipedia.org/wiki/PL/I_(programming_language). > > snip > > That is, 'certainly' doesn't change the meaning of your statement > > any. ?You wouldn't want it, but King George III didn't want the > > American Revolution. > > It's called emphasis. I just take you to have meant, then, +1 on excluding keywords from identifiers. You said it the long way though, so I thought I missed something deeper, that didn't come across. From info at egenix.com Fri Dec 19 05:05:35 2008 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Fri, 19 Dec 2008 11:05:35 +0100 Subject: ANN: eGenix pyOpenSSL Distribution 0.8.0-0.9.8i-1 Message-ID: <494B71EF.20200@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com pyOpenSSL Distribution Version 0.8.0-0.9.8i-1 An easy to install and use repackaged distribution of the pyOpenSSL Python interface for OpenSSL - available on Windows and Unix platforms This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-pyOpenSSL-Distribution-0.8.0-0.9.8i-1-GA.html ________________________________________________________________________ INTRODUCTION The eGenix.com pyOpenSSL Distribution includes everything you need to get started with SSL in Python. It comes with an easy to use installer that includes the most recent OpenSSL library versions in pre-compiled form. pyOpenSSL is an open-source Python add-on (http://pyopenssl.sf.net/) that allows writing SSL aware networking applications as well as certificate management tools. OpenSSL is an open-source implementation of the SSL protocol (http://www.openssl.org/). For more information, please see the product page: http://www.egenix.com/products/python/pyOpenSSL/ ________________________________________________________________________ NEWS This third release of the eGenix.com pyOpenSSL Distribution upgrades pyOpenSSL to version 0.8, which includes a few bug fixes related to threading. Please note that OpenSSL, the underlying SSL engine, does not allow sharing connections between threads. This is a little known fact which could in the past cause pyOpenSSL to crash Python. Jean-Paul Calderone, the maintainer of pyOpenSSL, has added fixes in 0.8 to prevent those crashes. We have also fixed several compiler warnings found in the code. The version of pyOpenSSL you find in the source release has those patches applied. Binaries are available for Linux x86 and x64 as well as Windows x86 and include pyOpenSSL 0.8.0 as well as the OpenSSL 0.9.8i libraries. ________________________________________________________________________ DOWNLOADS The download archives and instructions for installing the package can be found at: http://www.egenix.com/products/python/pyOpenSSL/ ________________________________________________________________________ UPGRADING Before installing this version of pyOpenSSL, please make sure that you uninstall any previously installed pyOpenSSL version. Otherwise, you could end up not using the included OpenSSL libs. _______________________________________________________________________ SUPPORT Commercial support for these packages is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 19 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-12-02: Released mxODBC.Connect 1.0.0 http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From gagsl-py2 at yahoo.com.ar Mon Dec 29 01:12:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Dec 2008 04:12:02 -0200 Subject: /kolab/bin/python: double free or corruption (fasttop) References: <78edebdd-030f-4517-b9ed-5225511724d7@t39g2000prh.googlegroups.com> Message-ID: En Sun, 28 Dec 2008 12:10:06 -0200, aspineux escribi?: > I got this. > This is a test script, to help me to understand why I have unexpected > result in application. > But I got a more unexpected result, and probably wrong error message > about the read-only cursor. > def server(): > dbenv, db=init_db(read_only=False) > > update_thread=threading.Thread(target=lambda : cleanup(db)) > update_thread.setDaemon(True) > update_thread.start() I'd write it as update_thread = threading.Thread(target=cleanup, args=(db,)) or: update_thread = threading.Thread(target=lambda db=db: cleanup(db)) The original code is creating a closure and I'm unsure how closures interact with threads. -- Gabriel Genellina From prologic at shortcircuit.net.au Mon Dec 8 08:56:10 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Dec 2008 23:56:10 +1000 Subject: Beginner trying to understand functions. In-Reply-To: References: Message-ID: On Mon, Dec 8, 2008 at 11:32 PM, simonh wrote: > That works fine. Then I've tried to use functions instead. The first > two work fine, the third fails: [ ... snip ... ] Try this: def getName(): name = input('Please enter your name: ') print('Hello', name) return name def getAge(): while True: try: return int(input('Please enter your age: ')) except ValueError: print('That was not a valid number. Please try again.') def checkAge(age): permitted = list(range(18, 31)) if age in permitted: print('Come on in!') return True elif age < min(permitted): print('Sorry, too young.') elif age > max(permitted): print('Sorry, too old.') return False name = getName() age = getAge() if checkAge(age): # Do something else: # Do something else cheers James PS: Read the Tutorial :) -- -- -- "Problems are solved by method" From debl2NoSpam at verizon.net Fri Dec 19 01:04:42 2008 From: debl2NoSpam at verizon.net (David Lees) Date: Fri, 19 Dec 2008 06:04:42 GMT Subject: Very Slow PythonWin 2.6.1 Startup on Windows XP SP3 Message-ID: <_PG2l.570$P5.31@nwrddc02.gnilink.net> PythonWin used to startup in a second or two on my Windows XP desktop. now it takes around 20 seconds. I tried turning off Google Desktop indexing and Norton AV, but it still takes a long time to start. Other random apps such as Firefox 3.0 (which I just updated to) and Thunderbird have normal startup times. Does anyone have suggestions on how to speed up Python startup? David Lees From collin.day.0 at gmail.com Thu Dec 18 19:59:04 2008 From: collin.day.0 at gmail.com (Collin D) Date: Thu, 18 Dec 2008 16:59:04 -0800 (PST) Subject: Factoring Polynomials References: Message-ID: <269523e2-eba9-4b6b-b0fb-c5a7deb3ed76@o4g2000pra.googlegroups.com> On Dec 18, 4:41?pm, "James Mills" wrote: > On Fri, Dec 19, 2008 at 10:11 AM, Gabriel Genellina > > wrote: > > En Thu, 18 Dec 2008 17:37:35 -0200, escribi?: > > >> I am trying to write a simple application to factor polynomials. I > >> wrote (simple) raw_input lines to collect the a, b, and c values from > >> the user, but I dont know how to implement the quadratic equation > > >> x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > Why is this so hard ? This is simple simple > expression. Reading through the Python > tutorial and reading up on how to define > functions is all you need! :) > > Here goes: > > >>> def f(a, b, c): > > ... ? ? x = (-1 * b) + ((b**2 - (4 * a * c)) / (2 * a)) > ... ? ? return (-1 * x), x > ... > > >>> f(1, 2, 3) > (6, -6) > > cheers > James Hiya James! Just one small problem with your equation above... The quadratic formula is: x = -b +or- (b**2 - (4 * a * c))^1/2 / 2a You just forgot the square root which makes quadratic a bit more complicated. You would have to download and import sqrt() from numpy or **.5 Also.. I need to build in functionality so the user does not have to directly call the function like: f(a,b,c) Instead.. they should be able to just raw_input their values. Also.. as with some of the examples above its a good idea to analyze the discriminant to make sure we have a real solution. Of course.. thats all pretty simple to build in. Thanks a lot! From w_a_x_man at yahoo.com Thu Dec 11 06:46:34 2008 From: w_a_x_man at yahoo.com (William James) Date: 11 Dec 2008 11:46:34 GMT Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> Message-ID: John W Kennedy wrote: > Xah Lee wrote: > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or > > Java, you'll have 50 or hundreds lines. > > Java: > > static float[] normal(final float[] x) { > float sum = 0.0f; > for (int i = 0; i < x.length; ++i) sum += x[i] * x[i]; > final float divisor = (float) Math.sqrt(sum); > float[] a = new float[x.length]; > for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor; > return a; > } "We don't need no stinkin' loops!" SpiderMonkey Javascript: function normal( ary ) { div=Math.sqrt(ary.map(function(x) x*x).reduce(function(a,b) a+b)) return ary.map(function(x) x/div) } From bearophileHUGS at lycos.com Tue Dec 16 13:42:11 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 16 Dec 2008 10:42:11 -0800 (PST) Subject: Does Python3 offer a FrozenDict? References: Message-ID: <451520af-b9ff-4b63-ba0c-27b11f5043ce@a26g2000prf.googlegroups.com> Paul Moore: > Moral - don't assume that all code needs to be rewritten for Python > 3.0 :-) In practice this time your moral is of little use: having a place that allows you to choose Py3 OR Py2 code is much better and tidier, helps you save time, helps you avoid wasting some time, etc. Bye, bearophile From lie.1296 at gmail.com Sun Dec 14 16:42:33 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 14 Dec 2008 21:42:33 +0000 (UTC) Subject: [OT] stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> Message-ID: On Sat, 13 Dec 2008 19:17:41 +0000, Duncan Booth wrote: > "Diez B. Roggisch" wrote: > >> David Hl????ik schrieb: >>> Hi guys, >>> >>> i am really sorry for making offtopic, hope you will not kill me, but >>> this is for me life important problem which needs to be solved within >>> next 12 hours.. >>> >>> I have to create stable algorithm for sorting n numbers from interval >>> [1,n^2] with time complexity O(n) . >>> >>> Can someone please give me a hint. Would be very very thankful! >> >> Unless I grossly miss out on something in computer science 101, the >> lower bound for sorting is O(n * log_2 n). Which makes your task >> impossible, unless there is something to be assumed about the >> distribution of numbers in your sequence. >> >> Who has given you that assignment - a professor? Or some friend who's >> playing tricks on you? >> > I think you must have fallen asleep during CS101. The lower bound for > sorting where you make a two way branch at each step is O(n * log_2 n), > but if you can choose between k possible orderings in a single > comparison you can get O(n * log_k n). > > To beat n * log_2 n just use a bucket sort: for numbers with a known > maximum you can sort them digit by digit for O(n log_k n), and if you > don't restrict yourself to decimal then k can be as large as you want, > so for the problem in question I think you can set k=n and (log_n n)==1 > so you get O(n) > I'm sure someday, there will be a student who comes to class late and sees this on the board: "Design a comparison sorting algorithm that has better than O(n * log n) lower bound complexity." The unsuspecting student copied it, thinking it's a homework. He crunched to the problem, going to various meditations and yoga classes before finding a way that works just before deadline, handing out the work a bit late. Six weeks later, his professor called and said: "You know what you just did? You've just found a problem that was supposed to be an example of unsolvable problem." It has happened before, why not again? http://www.snopes.com/college/homework/unsolvable.asp From tleeuwenburg at gmail.com Mon Dec 15 00:26:24 2008 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: Sun, 14 Dec 2008 21:26:24 -0800 (PST) Subject: Unit tests / build tools Message-ID: <754749aa-820c-43c0-867a-33c4fa6ae228@k1g2000prb.googlegroups.com> Hi all, I don't know if there is an equivalent to Maven for Python, or whether Maven could be used for Python projects. However, it would be great if there were something available that would let me produce unit test and code coverage statistics, then have those presented through an attractive web system. I am looking to integrate more testing, profiling and analysis into a significant codebase, and would like to automate as much of this as possible to make my workload lighter. Thanks, -Tennessee From marco at sferacarta.com Fri Dec 12 11:20:51 2008 From: marco at sferacarta.com (Marco Mariani) Date: Fri, 12 Dec 2008 17:20:51 +0100 Subject: Removing None objects from a sequence In-Reply-To: <87ej0dz894.fsf@daycos.com> References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> Message-ID: Kirk Strauser wrote: > So what's the difference exactly? "foo is not None" is actually surprising > to me, since "not None" is True. "0 is True" is False, but "0 is not None" > is True. Why is that? Cause I was tired of course, and got the not precedente not right!! Argh From mrtot at gmx.de Fri Dec 19 11:47:18 2008 From: mrtot at gmx.de (Martin) Date: Fri, 19 Dec 2008 08:47:18 -0800 (PST) Subject: IMAP: How to implement GMail-like threaded conversations view Message-ID: Currently I am trying to get used to Python's imaplib and email modules. I'like to create a webmail client simmilar to GMail. My Questions: a) Is there any feature hidden in Python's built-in modules (imaplib, email) that already can group all my mails into threads? b) If not a... what would be the best way to implement this? I can think of two approaches: b.1) Use the "References:" field of the messages in order to find out which messages are related to each other. I tried a first implementation which works quite well but I don't know if there can occur situations where one message is related to two parents. Also I don't know what happens if someone is too lazy to type my address. He might click at "Reply", delete topic and old mail-text and compose a new mail. Theoretically his mail client would set the "References:" field accordingly never the less, wouldn't it? Therefore my mail client would consider that completely new mail as part of an older conversation. The thoughts above might lead to the second approach: b.2) Use the "Subject:" field of the messages. I also tried this implementation and it also works (at first glance). I stripped all subjects of all mails so that all those "Re:", "Fw:" tags at the beginning get deleted. Afterwards I grouped those having the same subject and the same participants. Problem: I have no clue what "Re:"-tags might exist around the world. I guess each mail client and each language uses different ones, right? c) Does anyone know good resources to gain more knowledge about imap / mailing? Currently I am using those sites as a reference: http://www.devshed.com/c/a/Python/Python-Email-Libraries-part-2-IMAP/ (as a start *g) http://tools.ietf.org/html/rfc3501 http://tools.ietf.org/html/rfc2822 http://docs.python.org/library/imaplib.html http://docs.python.org/library/email.html Maybe there are other sources of interest on the web? :) This is my first post in this newsgroup. So: "Hello everybody!" :-) I've been reading this group for quite a while and I am really astonished how fast people give valuable answers here. This is a really great community! Many thanks in advance for all ideas! Greetz, Martin From __peter__ at web.de Fri Dec 19 09:03:29 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2008 15:03:29 +0100 Subject: How to parsing a sequence of integers References: <494ba258$0$18998$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Steven Woody a ?crit : >> In additional to max/min, is there something like average()? > > Not AFAIK, but it's really trivial > > def average(lst): > """ assume lst is a list of numerics """ > return sum(lst) / len(lst) If you are using Python 2.x: >>> def average(lst): ... return sum(lst)/len(lst) ... >>> average([1,2]) 1 So you better throw in a float(...): >>> def average(lst): ... return sum(lst)/float(len(lst)) ... >>> average([1,2]) 1.5 Peter From skip at pobox.com Wed Dec 3 11:51:43 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 3 Dec 2008 10:51:43 -0600 Subject: python an sqlite objects In-Reply-To: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> Message-ID: <18742.47391.389709.119341@montanaro-dyndns-org.local> azrael> is it possible to save a python object into a sqlite database as azrael> an atribute of type BLOB Sure. Just pickle the object and save the resulting string. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From rt8396 at gmail.com Fri Dec 19 12:41:08 2008 From: rt8396 at gmail.com (r) Date: Fri, 19 Dec 2008 09:41:08 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <6e232ab0-306a-4598-969a-211c4054e836@f40g2000pri.googlegroups.com> I was actually looking forward to 3.0, but the more I hear about 3.0, the more I am turned off. I think there are a lot of other pythonista's and pythoneers out there who agree but are not saying anything. This syntax for string formatting is completely ridiculous. What is the purpose of breaking backward compatibility just to write a print() function. This is going to push people away from python. I am trying to bring people to Python. I heard map is going away too, is that true also??, and there was talk at one time(serious talk from Guido) about removing lambda functions. Is this planned for the future?? Python has been beautifully designed from the beginning. But, I feel a shift from this now. Are they scared of Ruby, if they are, why the hell should they be. We do not need to lose any of the great pythonista's right now, and we damn sure don't want to turn off the new recruits. It seems like most of the backward breaks are really just for dumb reasons(sorry but its true). What is the logic behind this? The whole reason for not having a print function was the need to use it so much in debugging. And I was actually going to overlook that until I saw this perl/ruby like format method. WTF! From marduk at letterboxes.org Tue Dec 9 11:35:17 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Tue, 09 Dec 2008 11:35:17 -0500 Subject: When (and why) to use del? Message-ID: <1228840517.4109.10.camel@brotherus.rdu.redhat.com> I'm looking at a person's code and I see a lot of stuff like this: def myfunction(): # do some stuff stuff my_string = function_that_returns_string() # do some stuff with my_string del my_string # do some other stuff return and also def otherfunction(): try: # some stuff except SomeException, e: # more stuff del e return I think this looks ugly, but also does it not hurt performance by preempting the gc? My feeling is that this is a misuse of 'del'. Am I wrong? Is there any advantage of doing the above? From gherron at islandtraining.com Tue Dec 16 11:30:00 2008 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 16 Dec 2008 08:30:00 -0800 Subject: Generator slower than iterator? In-Reply-To: References: Message-ID: <4947D788.3040508@islandtraining.com> Lie Ryan wrote: > On Tue, 16 Dec 2008 12:07:14 -0300, Federico Moreira wrote: > > >> Hi all, >> >> Im parsing a 4.1GB apache log to have stats about how many times an ip >> request something from the server. >> >> The first design of the algorithm was >> >> for line in fileinput.input(sys.argv[1:]): >> ip = line.split()[0] >> if match_counter.has_key(ip): >> match_counter[ip] += 1 >> else: >> match_counter[ip] = 1 >> >> And it took 3min 58 seg to give me the stats >> >> Then i tried a generator solution like >> >> def generateit(): >> for line in fileinput.input(sys.argv[1:]): >> yield line.split()[0] >> >> for ip in generateit(): >> ...the same if sentence >> >> Instead of being faster it took 4 min 20 seg >> >> Should i leave fileinput behind? >> Am i using generators with the wrong aproach? >> > > What's fileinput? A file-like object (unlikely)? Also, what's > fileinput.input? I guess the reason why you don't see much difference > (and is in fact slower) lies in what fileinput.input does. > > Fileinput is a standard module distributed with Python: >From the manual: 11.2 fileinput -- Iterate over lines from multiple input streams This module implements a helper class and functions to quickly write a loop over standard input or a list of files. The typical use is: import fileinput for line in fileinput.input(): process(line) ... > Generators excels in processing huge data since it doesn't have to create > huge intermediate lists which eats up memory, given an infinite memory, a > generator solution is almost always slower than straight up solution > using lists. However in real life we don't have infinite memory, hogging > our memory with the huge intermediate list would make the system start > swapping, swapping is very slow and is a big hit to performance. This is > the way generator could be faster than list. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From rdmurray at bitdance.com Thu Dec 4 12:07:42 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Thu, 4 Dec 2008 12:07:42 -0500 (EST) Subject: simplest way to strip a comment from the end of a line? In-Reply-To: References: Message-ID: On Thu, 4 Dec 2008 at 08:50, Joe Strout wrote: > I have lines in a config file which can end with a comment (delimited by # as > in Python), but which may also contain string literals (delimited by double > quotes). A comment delimiter within a string literal doesn't count. Is > there any easy way to strip off such a comment, or do I need to use a loop to > find each # and then count the quotation marks to its left? >>> from shlex import split >>> split("this is a test") ['this', 'is', 'a', 'test'] >>> split("this is a test #with a comment") ['this', 'is', 'a', 'test', '#with', 'a', 'comment'] >>> split("this is a test #with a comment", comments=True) ['this', 'is', 'a', 'test'] >>> split("this is a '#gnarlier' test #with a comment", comments=True) ['this', 'is', 'a', '#gnarlier', 'test'] http://docs.python.org/library/shlex.html --RDM From jstroud at mbi.ucla.edu Sat Dec 13 05:19:08 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 13 Dec 2008 02:19:08 -0800 Subject: Need help improving number guessing game In-Reply-To: References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> Message-ID: I forgot to return target: def guess(player, p1score, p2score): target = None guess1 = int(input("\n>> ")) if guess1 > 100: print("ONLY NUMBERS FROM 1 TO 99") elif guess1 > target: print("TOO HIGH") elif guess1 == target: print("GOOD JOB, PLAYER %s! THE SCORE IS:" % player) print("P1: %s --- P2: %s" % (p1score, p2score))) print("PLAY AGAIN?") #Set up the game again play = int(input("0 TO END: ")) if play == 0: print("GOOD BYE. PLAY AGAIN SOON!") quit() else: target = random.randint(1, 99) else: print("TOO LOW") return target -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From castironpi at gmail.com Tue Dec 23 05:48:39 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 23 Dec 2008 02:48:39 -0800 (PST) Subject: Very basic question References: <21ab1917-f0c9-48fb-baa9-02e5bf229bf5@s9g2000prm.googlegroups.com> Message-ID: On Dec 23, 4:46?am, Sengly wrote: > Hello all, > > I would like to calculate a string expression to a float. For example, > I have ('12/5') and I want 2.4 as a result. I tried to use eval but it > only gives me 2 instead of 2.5 > > Help!!! > > Regards, > > Sengly >>> float('12')/float('5') 2.3999999999999999 >>> print float('12')/float('5') 2.4 >>> float(12/5) 2.0 >>> print float(12/5) 2.0 From narkewoody at gmail.com Mon Dec 22 01:56:45 2008 From: narkewoody at gmail.com (Steven Woody) Date: Mon, 22 Dec 2008 14:56:45 +0800 Subject: How to represent a sequence of raw bytes In-Reply-To: <200812220327.36180.motoom@xs4all.nl> References: <200812220327.36180.motoom@xs4all.nl> Message-ID: On Mon, Dec 22, 2008 at 10:27 AM, Michiel Overtoom wrote: > On Monday 22 December 2008 03:23:03 Steven Woody wrote: > >> 2. char buf[] = {0x11, 0x22, 0x33, ... } >> >> What's the equivalent representation for above in Python? > >>>> buf="\x11\x22\33" >>>> for b in buf: print ord(b) > ... > 17 > 34 > 27 >>>> > Hi, Michiel I thing "\x11\x22\x33" in python is not the {0x11, 0x22, 0x33} in C. Since, a string in python is immutable, I can _not_ do something like: b[1] = "\x55". And, how about char buf[200] in my original question? The intension is to allocate 200 undefined bytes in memory. Thanks. Regards, From clp at rebertia.com Tue Dec 23 00:58:10 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 22 Dec 2008 21:58:10 -0800 Subject: iterating initalizations In-Reply-To: <002696D3-E888-4D32-8416-0CFE4AC859AC@gmail.com> References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> <47c890dc0812221943g44bd7222t8c09c088d87e77df@mail.gmail.com> <002696D3-E888-4D32-8416-0CFE4AC859AC@gmail.com> Message-ID: <47c890dc0812222158r551265e2p81a12488e72b19de@mail.gmail.com> On Mon, Dec 22, 2008 at 7:52 PM, Aaron Stepp wrote: > > On Dec 22, 2008, at 10:43 PM, Chris Rebert wrote: > >> On Mon, Dec 22, 2008 at 7:32 PM, Aaron Stepp >> wrote: >> >>> >>> Thanks for the help so far, I think I'm starting to get a hang of the >>> syntax. >>> >>> I think I need to state my goal more clearly. >>> >>> Instead of writing a long list of initializations like so: >>> >>> A = [ ] >>> B = [ ] >>> ... >>> Y = [ ] >>> Z = [ ] >>> >>> I'd like to save space by more elegantly turning this into a loop. If I >>> need to just write it out, I guess that's ok... but it would be much >>> cleaner. I'm a composer, not a programmer, so some of this is quite >>> above >>> me. >>> >> >> So, are these variables supposed to be module-level, or attributes of >> class pitchAndRhythm, or what? >> Also, are you going to use the variables normally or are you going to >> need "variable variables" (e.g. like $$var in PHP, which gives the >> value of the variable with the name of the string stored in $var)? >> >> Cheers, >> Chris >> >> -- >> Follow the path of the Iguana... >> http://rebertia.com > > > The're going to only be part of the pitchAndRhythm class. Simply put, I > just need enough arrays to hold a list of pitches/rhythms. Then I'll have > each list member returned to an instrument defined in another module. > > As I'm hacking away at the code, I'm realizing that maybe I can do this with > just and A = [] and B = []. But I'm not sure... > Do you really need to name them, or are the names arbitrary and you only really care about having N distinct lists? Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From skip at pobox.com Thu Dec 4 07:20:59 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 4 Dec 2008 06:20:59 -0600 Subject: python an sqlite objects In-Reply-To: <493792a9$0$16763$426a74cc@news.free.fr> References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <4936bceb$0$16783$426a34cc@news.free.fr> <4936dab7$0$9107$426a74cc@news.free.fr> <493792a9$0$16763$426a74cc@news.free.fr> Message-ID: <18743.52011.536628.470841@montanaro-dyndns-org.local> Bruno> If you serialize a dict, you'll obviously get a dict back. Note Bruno> that the point of json is *not* to replace pickle. json is a Bruno> *data* serialization format meant to represent "basic" types Bruno> (dicts, lists, strings and numbers) in human readable and Bruno> (mostly) language-agnostic way. Right, which makes it unsuitable as a general object serialization format. The OP was unclear what he meant when he asked about storing Python objects in a sqlite database. In the general case json doesn't cut it. Bruno> If you want a Python object store, you'll be better looking at Bruno> ZODB, Durus or friends. -- Or SQLAlchemy or SQLObject. Skip From raj.indian.08 at gmail.com Mon Dec 22 00:25:10 2008 From: raj.indian.08 at gmail.com (RajNewbie) Date: Sun, 21 Dec 2008 21:25:10 -0800 (PST) Subject: Twisted for non-networking applications References: <82e49b84-43c9-452f-a139-c77378c12908@a12g2000pro.googlegroups.com> Message-ID: <9faa4fa5-6fd1-4ebb-bf1b-382a7d74ba0a@d42g2000prb.googlegroups.com> On Dec 22, 3:26?am, "James Mills" wrote: > On Mon, Dec 22, 2008 at 4:27 AM, Kottiyath wrote: > > Hi all, > > ? Is it a good idea to use Twisted inside my application, even though > > it has no networking part in it? > > ? Basically, my application needs lots of parallel processing - but I > > am rather averse to using threads - due to myraid issues it can cause. > > So, I was hoping to use a reactor pattern to avoid the threads. I am > > using twisted in another part of the application for networking, so I > > was hoping to use the same for the non-networking part for reusing the > > reactor pattern. > > ? If somebody can help me on this, it would be very helpful. > > Alternatively you could give circuits (1) > a go. It _can_ be a nice alternative to > Twisted and isn't necessarily focused on > Networking applications. > > cheers > James > > 1.http://trac.softcircuit.com.au/circuits/ I was unable to see documentation explaining this - so asking again. Suppose the event handlers in the component is doing blocking work, how is it handled? I went through ciruits.core, but was unable to understand exactly how blocking mechanisms are handled. My scenario is as follows: I have 4 loops, 1 small and high priority, 3 quite large and blocking (takes upto 3 seconds) and comparatively low priority. The small loops goes through everytime and does some work - and optionally uses the data sent by the other 3 loops. I do not want the smaller loop to get blocked by the other loops. So, if the event handler does blocking work, can that cause the whole loop to block? From jelsas at gmail.com Wed Dec 10 11:07:14 2008 From: jelsas at gmail.com (jelsas) Date: Wed, 10 Dec 2008 08:07:14 -0800 (PST) Subject: Maintaining signature in help(decorated function) Message-ID: <48f2fd47-1fc3-4b2f-ad39-24adce7e9a5c@k36g2000yqe.googlegroups.com> Hi -- I can't seem to maintain the function signature when applying a decorator. I'm using functools.wraps. Example: >>> def mydecorator(fn): ... from functools import wraps ... # simple decorator ... @wraps(fn) ... def wrapped(*args, **kwargs): ... print 'i\'m wrapped!' ... return fn(*args, **kwargs) ... return wrapped ... >>> >>> @mydecorator ... def f(foo, bar): ... '''docstring for f''' ... pass ... >>> >>> help(f) displays: Help on function f in module __main__: f(*args, **kwargs) docstring for f I would like to maintain f's signature in the help message, (foo, bar) instead of (*args, **kwargs) Thanks in advance! From castironpi at gmail.com Sat Dec 27 19:40:39 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 27 Dec 2008 16:40:39 -0800 (PST) Subject: C API: array of floats/ints from python to C and back References: Message-ID: On Dec 27, 6:06?pm, Scott David Daniels wrote: > Daniel Fetchinson wrote: > >.... I have a list to begin with which will be passed to the C function. > > ?> I assume converting the list to an array.array and passing that to the C > > > function doesn't make any difference in terms of speed since the > > operation itself will be done in the C function anyway. > > Right, but why bother to do the conversion in C where you'll have to > fiddle with refcounts and error propogation? ?convert in python, and > go to the underlying data in C. I think you could use ctypes.c_int* 20, which is an awesome data type-- a 20-element array of integers. You could also use this, which I just discovered, and is actually moderately disturbing. #WARNING unsafe code >>> from ctypes import * >>> i= c_int(42) >>> pi= pointer(i) >>> pi[0] 42 >>> pi[1] 0 >>> pi[2] 0 >>> pi[1]= 20 >>> pi <__main__.LP_c_long object at 0x00A97D00> >>> pi[1] 20 What memory is it overwriting? From tarun.kap at gmail.com Fri Dec 19 14:35:51 2008 From: tarun.kap at gmail.com (TkNeo) Date: Fri, 19 Dec 2008 11:35:51 -0800 (PST) Subject: pymssql for python 2.6 ? Message-ID: when would pymssql come out with a release that is compatible with python 2.6 ? Thanks -TK From hniksic at xemacs.org Tue Dec 2 09:36:01 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 02 Dec 2008 15:36:01 +0100 Subject: best way to do this References: Message-ID: <87ljuyr6em.fsf@mulj.homelinux.net> TP writes: > Hi everybody, > >>>> c=[(5,3), (6,8)] > > From c, I want to obtain a list with 5,3,6, and 8, in any order. > I do this: > >>>> [i for (i,j) in c] + [ j for (i,j) in c] > [5, 6, 3, 8] > > Is there a quicker way to do this? Quicker? Hard to say. Using itertools elegantly? Definitely: list(chain(*c)) As an added benefit, it works regardless of the number of elements in the tuple. (Also assumes from itertools import chain for effect.) From mail at microcorp.co.za Fri Dec 19 01:19:23 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 19 Dec 2008 08:19:23 +0200 Subject: Is this pythonic? References: <66d058f9-cfe1-4b3c-ab8a-e6e88bb97770@m22g2000vbp.googlegroups.com> <494a761c$0$20035$426a34cc@news.free.fr> Message-ID: <000001c961a4$c4611f80$0d00a8c0@hendrik> "Bruno Desthuilliers" wrote: >ipytest at gmail.com a ?crit : >> x.validate_output(x.find_text(x.match_filename >> (x.determine_filename_pattern(datetime.datetime.now())))) >> >> Is it even good programming form? > >functional programming addicts might say yes. But as far as I'm >concerned, I find it a bit too nested... > +1 I would call it onionskin programming. There is of course nothing technically wrong with it, and you can do the same kind of thing in C, but every time I see something like it, my reaction is WTF. - Hendrik From vinay_sajip at yahoo.co.uk Tue Dec 30 23:53:15 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 30 Dec 2008 20:53:15 -0800 (PST) Subject: AttributeError: 'module' object has no attribute 'DatagramHandler' (ubuntu-8.10, python 2.5.2) References: <4c6f0831-c05f-401f-b956-376600b38e06@r15g2000prd.googlegroups.com> Message-ID: On Dec 29, 12:18 pm, "Chris Rebert" wrote: > There's your answer. I do agree though that the "class logging.DatagramHandler" line in the docs is misleading to say the > least. Perhaps a docs bug should be filed... I've raised it on the sphinx-dev Google group. The documentation source markup for the class just says "DatagramHandler", and the "logging" prefix is added by Sphinx at HTML generation time. Regards, Vinay Sajip From kkylheku at gmail.com Wed Dec 10 16:37:34 2008 From: kkylheku at gmail.com (Kaz Kylheku) Date: Wed, 10 Dec 2008 21:37:34 +0000 (UTC) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: <20081226055859.604@gmail.com> On 2008-12-05, Xah Lee wrote: > Let's say for example, we want to write a function that takes a vector > (of linear algebra), and return a vector in the same direction but > with length 1. In linear algebar terminology, the new vector is called > the ?normalized? vector of the original. > > For those of you who don't know linear algebra but knows coding, this If I were to guess who that would be ... > means, we want a function whose input is a list of 3 elements say > {x,y,z}, and output is also a list of 3 elements, say {a,b,c}, with > the condition that > > a = x/Sqrt[x^2+y^2+z^2] > b = y/Sqrt[x^2+y^2+z^2] > c = z/Sqrt[x^2+y^2+z^2] > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, > you'll have 50 or hundreds lines. Really? ``50 or hundreds'' of lines in C? #include /* for sqrt */ void normalize(double *out, double *in) { double denom = sqrt(in[0] * in[0] + in[1] * in[1] + in[2] * in[2]); out[0] = in[0]/denom; out[1] = in[1]/denom; out[2] = in[2]/denom; } Doh? Now try writing a device driver for your wireless LAN adapter in Mathematica. From gagsl-py2 at yahoo.com.ar Mon Dec 8 03:36:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Dec 2008 06:36:53 -0200 Subject: ftp retrlines with re... In-Reply-To: References: Message-ID: En Fri, 05 Dec 2008 12:51:58 -0200, isabellknauer at googlemail.com escribi?: > Ive been working on an application quite some time now and i wanted to > include something to let the user load a new version. i therefore > tried to include this here: Too much code, unclear question... please post again, shortening code to the minimum necesary to show the problem. And tell us *what* is the problem, what did you expect to happen, what actually happened... -- Gabriel Genellina From Sengly.Heng at gmail.com Tue Dec 23 05:49:44 2008 From: Sengly.Heng at gmail.com (Sengly) Date: Tue, 23 Dec 2008 02:49:44 -0800 (PST) Subject: Very basic question References: <21ab1917-f0c9-48fb-baa9-02e5bf229bf5@s9g2000prm.googlegroups.com> Message-ID: <38f6b145-8615-4bcc-88f6-1988f9a7f68f@q30g2000prq.googlegroups.com> I can hack it by doing eval('1.0*12/5') but is there any better method? From 5lvqbwl02 at sneakemail.com Tue Dec 30 14:52:08 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Tue, 30 Dec 2008 11:52:08 -0800 (PST) Subject: embedding python in wxpython Message-ID: <191280cf-ecf9-4135-9737-9923061855d1@t39g2000prh.googlegroups.com> Hi, I've looked around for a way to allow a python console from within a wxPython application, but have only found stuff on embedded/ extending python with C/C++ or wxWidgets in C++, but not wxPython. Is this easy to do? Can someone point me in the right direction? Also, typically when you embed a scripting language into a larger application, how do you get the console environment to share data with the larger application? For instance, if the application has some gui stuff (for example clicking on a object and dragging it around), how do you get "object.select(x,y)" to print out on the console, and vice-versa: the object gets selected if the user types "object.select(x,y)"? I'd like the console to be a bidirectional representation of what's going on in the gui, plus a general purpose evaluation environment where you can manipulate application data via some api which is automatically exposed to the console when the application opens up. I'm looking for high-level hints/strategies/directions. Thank you Michael From benjamin.kaplan at case.edu Wed Dec 10 14:29:25 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 10 Dec 2008 14:29:25 -0500 Subject: Python is slow In-Reply-To: <075d8c52-93e9-40f4-9eb6-794ce275651e@g38g2000yqd.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <075d8c52-93e9-40f4-9eb6-794ce275651e@g38g2000yqd.googlegroups.com> Message-ID: On Wed, Dec 10, 2008 at 2:07 PM, Paul McGuire wrote: > On Dec 10, 12:42 pm, cm_gui wrote: > > Python is slow. Very slow. > > And... ? Was there a question or specific suggestion in there > somewhere? > > Do you go to your mechanic and say "My car wont go as fast as the > other cars on the road! They should make it faster!"? > > Good luck to you in your futile, uh I meant, *future* endeavors. (No > wait, I really meant "futile".) > > -- Paul > Don't bother arguing. It's just a pathetic attempt to start a flame war. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Fri Dec 12 17:23:33 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 12 Dec 2008 17:23:33 -0500 Subject: Removing None objects from a sequence In-Reply-To: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> Message-ID: If you want to literally remove None objects from a list....(or mutable sequence) def deNone(alist): n=len(alist) i=j=0 while i < n: if alist[i] is not None: alist[j] = alist[i] j += 1 i += 1 alist[j:i] = [] blist=[None,1,None,2,None,3,None,None,4,None] deNone(blist) print(blist) # prints [1, 2, 3, 4] Terry Jan Reedy From bj_666 at gmx.net Sun Dec 21 04:42:47 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Dec 2008 09:42:47 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <6r6hcmFfb643U2@mid.uni-berlin.de> On Sat, 20 Dec 2008 15:27:43 -0800, walterbyrd wrote: > On Dec 19, 10:25?am, Michael Torrie wrote: > >> Personally the new string formatter is sorely needed in Python. > > Really? You know, it's funny, but when I read problems that people have > with python, I don't remember seeing that. Loads of people complain > about the white space issue. Some people complain about the speed. Lots > of complaints about certain quirky behavior, but I have not come across > any complaints about the string formatting. Many newbie code I have seen avoids it by string concatenation: greeting = 'Hello, my name is ' + name + ' and I am ' + str(age) + ' old.' That's some kind of indirect complaint. :-) > In fact, from what I have seen, many of the "problems" being "fixed" > seem to be non-problems. And even if nobody has problems with the limitations of ``%`` string formatting why shouldn't they add a more flexible and powerful way!? Python?3.0 is not a bug fix release. Ciao, Marc 'BlackJack' Rintsch From prahaai at gmail.com Thu Dec 11 11:20:08 2008 From: prahaai at gmail.com (Cro) Date: Thu, 11 Dec 2008 08:20:08 -0800 (PST) Subject: HGE and Python (again) Message-ID: <8180969e-9289-4f8c-ab80-30fbc50914d1@g17g2000prg.googlegroups.com> Good day. I've been trying to port HGE (http://hge.relishgames.com) to Python for more than 4 months now... HGE is a hardware accelerated 2D game engine. It comes with the source and examples. In the folder "include", you can find "hge.h", the file that i am talking about in all the post. # I tried to load the DLL functions with Python Ctypes like this : [code] >>> from ctypes import * >>> HGE = cdll.LoadLibrary("C:/hge181/hge") >>> HGE.hgeCreate(0x180) [/code] But i get this error : "Procedure called with not enough arguments (4 bytes missing) or wrong calling convention". The call should be done with hgeCreate(HGE_VERSION) and the constant is defined as "#define HGE_VERSION 0x180"... Number 0x180 means 384 in Python. I don't mean what it means in C. So i am stuck. I also tried to modify the "hge.h" file on line 408, and export the rest of the classes... [code] __declspec (dllexport) hgeVertex; __declspec (dllexport) hgeTriple; __declspec (dllexport) hgeQuad; __declspec (dllexport) hgeInputEvent; [/code] But after compilation, i am not able to access them from Python "ctypes". They seem to remain invisible. Perhaps i am not doing it right?... # I tried Cython. I tried to load "hge.h" in Cython and use the structures. The first error i get is at line 173: "typedef bool (*hgeCallback) ();". I am not that good in C/C++ to understand what it means. So i commented it... The second big error is at line 408: "extern "C" { EXPORT HGE * CALL hgeCreate(int ver); }". This should be the DLL export. I comented that too... I used this code in Cython, loading from "hge.h": [code] # file HGE.pyx cdef extern from "windows.h": pass cdef extern from "hge.h": pass [/code] And i get this errors: [code] ..\hge.h(215) : error C2061: syntax error : identifier 'hgeVertex' ..\hge.h(218) : error C2059: syntax error : '}' ..\hge.h(226) : error C2061: syntax error : identifier 'hgeVertex' ..\hge.h(229) : error C2059: syntax error : '}' ..\hge.h(274) : error C2061: syntax error : identifier 'HGE' ..\hge.h(274) : error C2059: syntax error : ';' ..\hge.h(275) : error C2449: found '{' at file scope (missing function header?) ..\hge.h(407) : error C2059: syntax error : '}' [/code] Then i tried to define hgeVertex in Cython like: [code] struct hgeVertex: float x, y # screen position float z # Z-buffer depth 0..1 DWORD col # color float tx, ty # texture coordinates [/code] But i get the exact same errors. If i comment all the structures hgeVertex and Triple and Quad and the HGE class, the Cython file compiles !... But it's not useful at all. My Cython is okay, i compiled a few programs before, so that's not a problem... # Then i tried Swig (and it worked with the examples )... But the problems with "hge,h" seem to be somewhat similar. I call swig like this : "swig -c++ -python hge.i" And the file "hge.i" contains: [code] /* File : hge.i */ %module hge %{ #include "hge.h" %} /* Let's just grab the original header file here */ %include "hge.h" [/code] And the error i get after commenting the HGE callback and DLL export is this : "hge.h(276): Error: Syntax error in input(3)." Line 276 is exactly the first call of HGE class : "virtual void CALL Release() = 0;". # I tried Boost.Python (and it works with embedding and extending examples), but i could't compile "hge.h" even after commenting the structures and classes. I have to write some wrapper code in "hge.h" and i am probably doing it completely wrong. [code] BOOST_PYTHON_MODULE(hge) { using namespace boost::python; class_ base("hgeVertex"); } [/code] So i am stuck again... I am not that good in neither C or Python. Can anyone suggest any ideas? Please? I really really really want to port HGE in Python. It's the greatest game engine i have ever seen. The particle engine is EXCELLENT and i need it. Thank you in advance. From andre.roberge at gmail.com Tue Dec 30 23:21:06 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Tue, 30 Dec 2008 20:21:06 -0800 (PST) Subject: Memory leak problem (while using tkinter) Message-ID: I have written a small program (my first Tkinter-based app) to play around the idea mentioned on http://rogeralsing.com/2008/12/07/genetic-programming-evolution-of-mona-lisa/ and, in doing so, have encountered a memory leak problem. I have seen mentions on the web of using the delete() method of canvas to prevent such problems - which I have tried to do with limited success. Below is the code I wrote; to run it, you will need a small image file (I used the one found on http://alteredqualia.com/visualization/evolve/) that is saved under "mona_lisa.png". Any help would be greatly appreciated. Andr? ========== from Tkinter import Canvas, Tk, Label import Image, ImageTk, ImageChops, ImageStat # PIL import aggdraw from random import randint import time import copy FITNESS_OFFSET = 0 saved = [None, None] def fitness(im1, im2): """Calculate a value derived from the root mean squared of the difference between two images. It is normalized so that when a black image is compared with the original one (img1), the fitness given is 0, and when the image is identical, the fitness value is 100.""" global FITNESS_OFFSET stat = ImageStat.Stat(ImageChops.difference(im1, im2)) fit = 1. - sum(stat.rms[:3])/(255*3) if FITNESS_OFFSET == 0: black_image = aggdraw.Draw("RGBA", im1.size, "black") s = black_image.tostring() raw = Image.fromstring('RGBA', im1.size, s) stat = ImageStat.Stat(ImageChops.difference(im1, raw)) FITNESS_OFFSET = 1. - sum(stat.rms[:3])/(255*3) return 100*(fit-FITNESS_OFFSET)/(1.-FITNESS_OFFSET) class DNA(object): def __init__(self, width, height, polygons=50, edges=6): self.polygons = polygons self.edges = edges self.width = width self.height = height self.dna = [] def init_dna(self): for i in range(self.polygons): self.dna.append(self.random_polygon()) def random_polygon(self): edges = [] for i in range(self.edges): edges.append(randint(0, self.width)) edges.append(randint(0, self.height)) col = [randint(0, 255), randint(0, 255), randint(0, 255), randint(0, 255)] return edges, col def mutate(self): selected = randint(0, self.polygons-1) _type = randint(0, 2) if _type == 0: # colour col_index = randint(0, 3) self.dna[selected][1][col_index] = randint(0, 255) elif _type == 1: # x coordinate coord = randint(0, self.edges-1) self.dna[selected][0][2*coord] = randint(0, self.width) elif _type == 2: # y coordinate coord = randint(0, self.edges-1) self.dna[selected][0][2*coord+1] = randint(0, self.height) class AggDrawCanvas(Canvas): def __init__(self, width, height, win): Canvas.__init__(self, win) self.image_id = None self.win = win self._width = width self._height = height self._size = width, height self.config(width=width, height=height+20) self.info = self.create_text(width/2, height+20) self.pack() self.dna = DNA(self._width, self._height) self.mutations = 0 def draw_dna(self): img = Image.new("RGBA", self._size, "black") self.context = aggdraw.Draw(img) for gene in self.dna.dna: brush = aggdraw.Brush(tuple(gene[1][0:3]), opacity=gene[1] [3]) self.context.polygon(gene[0], brush) self.delete(img) self.redraw() def redraw(self): self.mutations += 1 s = self.context.tostring() self.delete(self.context) raw = Image.fromstring('RGBA', self._size, s) self.fitness = fitness(mona_lisa, raw) self.itemconfig(self.info, text="%2.2f %d"%(self.fitness, self.mutations), fill="black") self.image = ImageTk.PhotoImage(raw) self.delete(self.image_id) self.image_id = self.create_image(self._width/2, self._height/ 2, image=self.image) self.update() win = Tk() mona_lisa = Image.open("mona_lisa.png") img = ImageTk.PhotoImage(mona_lisa) original_image = Canvas(win) original_image.pack() fitness_label = Label(win) _w, _h = img.width(), img.height() original_image.config(width=_w, height=_h) original_image.create_image(_w/2, _h/2, image=img) best_fit = AggDrawCanvas(_w, _h, win) best_fit.dna.dna = [] best_fit.draw_dna() current_fit = AggDrawCanvas(_w, _h, win) current_fit.dna.init_dna() current_fit.draw_dna() while True: current_fit.dna.mutate() current_fit.draw_dna() if current_fit.fitness > best_fit.fitness: best_fit.dna.dna = copy.deepcopy(current_fit.dna.dna) best_fit.draw_dna() else: current_fit.dna.dna = copy.deepcopy(best_fit.dna.dna) if __name__ == '__main__': win.mainloop() From Ron.Barak at lsi.com Thu Dec 25 07:23:39 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Thu, 25 Dec 2008 12:23:39 +0000 Subject: os.system('cls') In-Reply-To: References: Message-ID: <7F0503CD69378F49BE0DC30661C6CCF602494700@enbmail01.lsi.com> Hi Dennis, print dir(os.system) print os.__dict__ might help Bye, Ron. ________________________________ From: Dennis van Oosterhout [mailto:de.slotenzwemmer at gmail.com] Sent: Thursday, December 25, 2008 12:22 To: python-list at python.org Subject: os.system('cls') Hi there! I was searching for a way to clear the 'DOS screen'/command screen etc. and found that os.system('cls') works for this. I was just wondering where I can find al the commands which can be used for os.system(). I searched with google but I didn't find an answer. In the official python tutorial it says os.system('command') executes the command, but it doesn't say which commands exist (or I'm just blind). Does anyone have an answer for this question? Thanks, Devilly -------------- next part -------------- An HTML attachment was scrubbed... URL: From fetchinson at googlemail.com Sun Dec 7 14:39:43 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sun, 7 Dec 2008 11:39:43 -0800 Subject: Guido's new method definition idea In-Reply-To: <493c2276$0$9254$426a34cc@news.free.fr> References: <493c2276$0$9254$426a34cc@news.free.fr> Message-ID: >>>> The story of the explicit self in method definitions has been >>>> discussed to death and we all know it will stay. However, Guido >>>> himself acknowledged that an alternative syntax makes perfect sense >>>> and having both (old and new) in a future version of python is a >>>> possibility since it maintains backward compatibility. The alternative >>>> syntax will be syntactic sugar for the old one. This blog post of his >>>> is what I'm talking about: >>>> >>>> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html >>>> >>>> The proposal is to allow this: >>>> >>>> class C: >>>> def self.method( arg ): >>>> self.value = arg >>>> return self.value >>>> >>>> instead of this: >>>> >>>> class C: >>>> def method( self, arg ): >>>> self.value = arg >>>> return self.value >>>> >>>> I.e. explicit self stays only the syntax is slightly different and may >>>> seem attractive to some. As pointed out by Guido classmethods would >>>> work similarly: >>>> >>>> class C: >>>> @classmethod >>>> def cls.method( arg ): >>>> cls.val = arg >>>> return cls.val >>>> >>>> The fact that Guido says, >>>> >>>> "Now, I'm not saying that I like this better than the status quo. But >>>> I like it a lot better than [...] but it has the great advantage that >>>> it is backward compatible, and can be evolved into a PEP with a >>>> reference implementation without too much effort." >>>> >>>> shows that the proposal is viable. >>>> >>>> I'd like this new way of defining methods, what do you guys think? >>>> Anyone ready for writing a PEP? >>>> >>> What's the advantage? If there is not a good reason, I would strongly >>> opposed polluting the language. >> >> Did you read the blog post? The advantage is having a less confusing >> situation for newbies > > Once again: how is adding "magical" syntax going to reduce confusion ? > >> (confusing the number of arguments to a method >> call). > > This is only confusing the first time. The correct solution to this > problem is IMHO to better document Python's object model, specially how > the descriptor protocol turns functions into methods. As I've said in another reply the argument that "def self.meth( arg )" is confusing because "self" doesn't exist in the current scope as an instance is convincing to me. So I no longer like the alternate syntax mentioned by Guido. Still, improved error messages would be desirable (concerning the number of arguments passed to an instance method). Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From wyldwolf at gmail.com Mon Dec 22 10:22:58 2008 From: wyldwolf at gmail.com (Kevin Kelley) Date: Mon, 22 Dec 2008 09:22:58 -0600 Subject: Python's popularity In-Reply-To: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: <77895c1d0812220722x45a85c0eq55a39deff75f0345@mail.gmail.com> Python has it's place, usually getting things done, rather than being flashy. For example, while Java is still the "Enterprise King", both the leading application servers (Weblogic and Websphere) adopted Jython as their internal scripting language last year (or was it 2006?). It's used heavily for internal game scripting (Eve Online uses it very heavily (specifically Stackless), as does BF 2142). I don't know if in fact Python is the 3rd most popular language, but I would not be surprised by it passing up other high level scripting languages like Perl and Ruby. Kevin On Mon, Dec 22, 2008 at 9:11 AM, walterbyrd wrote: > I have read that python is the world's 3rd most popular language, and > that python has surpassed perl in popularity, but I am not seeing it. > > >From what I have seen: > > - in unix/linux sysadmin, perl is far more popular than python, > windows sysadmins typically don't use either. > - in web-development, php is far more popular than python - it's not > even close. > - when I did a search on dice, I found over 20X more jobs advertised > for ruby on rails developers, than for python dango developers. > - application development is dominated by java, c/c++, and maybe a > little visual basic. > - as I understand it, fortran is still the most popular language for > numberical programming. > > Of course, these are just observations on my part, nothing scientific > about it. But, I can't help but wonder how python's popularity was > determined. I suspect that a lot of people use python as a secondary > skill. For example, I use ms-word, but I'm not an ms-word > professional. > > Please note: I am not confusing popularity with quality. I am not > saying that php is better for web-dev, or anything like that. I am > just wondering how python is rated as being so popular, when python > does not seem to dominate anything. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From spooklight at gmail.com Sun Dec 14 16:35:44 2008 From: spooklight at gmail.com (uair01) Date: Sun, 14 Dec 2008 13:35:44 -0800 (PST) Subject: Output to file gets lost - don't know where to look ... Message-ID: <26a47940-c997-4da4-8f05-205b8d3001a8@d42g2000prb.googlegroups.com> I'm running python in IDLE on suse11. I have a python program and after writing 100kB to 200kB to a file, the write statements seem to stop working. Basically the print statements look like this: some loops: logFile.write(string1) logFile.write(string2) end of loops print(stringA) logFile.write(string3) logFile.write(string4) print(stringB) String1 and sometimes string2 / string3 (or a part of it) will end up in the file, but string4 not. stringsA and stringB get printed to the concole as expected. Stepping through the program with a debugger shows that *all* write- statements get executed. I use several logFile.flush() statements and a logFile.close() at the end. Is there some kind of file-size-limit or some kind of memory or buffer problem? Or could it be a bug in IDLE? I don't know where to look further. OH ... maybe just writing this message has helped. Now I see the following error messages inside the window from where I started IDLE. Could that be the cause? Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 1403, in __call__ return self.func(*args) File "/usr/lib/python2.5/idlelib/MultiCall.py", line 151, in handler r = l[i](event) File "/usr/lib/python2.5/idlelib/CallTips.py", line 62, in refresh_calltip_event self.open_calltip(False) File "/usr/lib/python2.5/idlelib/CallTips.py", line 65, in open_calltip self._remove_calltip_window() File "/usr/lib/python2.5/idlelib/CallTips.py", line 41, in _remove_calltip_window self.calltip.hidetip() File "/usr/lib/python2.5/idlelib/CallTipWindow.py", line 126, in hidetip self.label.destroy() AttributeError: 'NoneType' object has no attribute 'destroy' I will try the python program outside of IDLE. From xahlee at gmail.com Thu Dec 25 06:24:31 2008 From: xahlee at gmail.com (Xah Lee) Date: Thu, 25 Dec 2008 03:24:31 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <452ba58b-9377-4463-85e2-5ecdaa25a129@t39g2000prh.googlegroups.com> <6375k4pf1mleb6im67nkpec5olqbsom88e@4ax.com> Message-ID: > >On Dec 10, 2:47 pm, John W Kennedy wrote: > >> C: > > >> #include > >> #include > > >> void normal(int dim, float* x, float* a) { > >> float sum = 0.0f; > >> int i; > >> float divisor; > >> for (i = 0; i < dim; ++i) sum += x[i] * x[i]; > >> divisor = sqrt(sum); > >> for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; > > >> } Due to the low level of C, this C example should perhaps then accept a sequence of numbers separated by space, and print the output. Having dimension as part of input is not acceptable. For examples in other langs that can take any input (in source code) and print output, see: http://xahlee.org/UnixResource_dir/writ/Mathematica_expressiveness.html A new addition is in Scheme Lisp: ;; Scheme Lisp. By Bakul Shah (define (normalize vec) (let ((d (sqrt (apply + (map (lambda (x) (* x x)) vec))))) (map (lambda (x) (/ x d)) vec))) (normalize '(3 4)) The JavaScript example: // Javascript. By William James function normalize( vec ) { var div=Math.sqrt(vec.map(function(x) x*x).reduce(function(a,b) a+b)) return vec.map(function(x) x/div) } is also not qualified. (it is syntax error in SpiderMonkey engine ?JavaScript-C 1.7.0 2007-10-03?) Xah ? http://xahlee.org/ ? From mirandasnailvv at gmail.com Fri Dec 19 19:43:25 2008 From: mirandasnailvv at gmail.com (mirandasnailvv at gmail.com) Date: Fri, 19 Dec 2008 16:43:25 -0800 (PST) Subject: old bay shrimp boil recipe - Free Message-ID: <544e07fe-ea30-4b78-9328-43c7d36608dd@r15g2000prd.googlegroups.com> old bay shrimp boil recipe . . . *******CLICK HERE******** http://club247.cn/old-bay-shrimp-boil-recipe ***************************** . . . . . . . . . . . . old bay shrimp boil recipe From pavlovevidence at gmail.com Sat Dec 6 19:19:31 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 6 Dec 2008 16:19:31 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> Message-ID: On Dec 6, 4:39?pm, "Russ P." wrote: > On Dec 6, 1:21?pm, Carl Banks wrote: > > > > > On Dec 6, 9:12?am, "Russ P." wrote: > > > > On Dec 6, 1:02?am, Antoine De Groote wrote: > > > > > Allowing "$" as a substitute for "self" wouldn't require this new syntax. > > > > > class C: > > > > ? ? def method($, arg): > > > > ? ? ? ? $.value = arg > > > > > I'm strongly against this. This looks ugly and reminds me of Perl and > > > > Ruby. (I don't have anything against these languages, but there's a > > > > reason I use Python). > > > > > Russ P. wrote: > > > > > On Dec 5, 6:21 pm, "Daniel Fetchinson" > > > > > wrote: > > > > >> Hi folks, > > > > > >> The story of the explicit self in method definitions has been > > > > >> discussed to death and we all know it will stay. However, Guido > > > > >> himself acknowledged that an alternative syntax makes perfect sense > > > > >> and having both (old and new) in a future version of python is a > > > > >> possibility since it maintains backward compatibility. The alternative > > > > >> syntax will be syntactic sugar for the old one. This blog post of his > > > > >> is what I'm talking about: > > > > > >>http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... > > > > > >> The proposal is to allow this: > > > > > >> class C: > > > > >> ? ? def self.method( arg ): > > > > >> ? ? ? ? self.value = arg > > > > >> ? ? ? ? return self.value > > > > > >> instead of this: > > > > > >> class C: > > > > >> ? ? def method( self, arg ): > > > > >> ? ? ? ? self.value = arg > > > > >> ? ? ? ? return self.value > > > > > >> I.e. explicit self stays only the syntax is slightly different and may > > > > >> seem attractive to some. As pointed out by Guido classmethods would > > > > >> work similarly: > > > > > >> class C: > > > > >> ? ? @classmethod > > > > >> ? ? def cls.method( arg ): > > > > >> ? ? ? ? cls.val = arg > > > > >> ? ? ? ? return cls.val > > > > > >> The fact that Guido says, > > > > > >> "Now, I'm not saying that I like this better than the status quo. But > > > > >> I like it a lot better than [...] but it has the great advantage that > > > > >> it is backward compatible, and can be evolved into a PEP with a > > > > >> reference implementation without too much effort." > > > > > >> shows that the proposal is viable. > > > > > >> I'd like this new way of defining methods, what do you guys think? > > > > >> Anyone ready for writing a PEP? > > > > > >> Cheers, > > > > >> Daniel > > > > > >> -- > > > > >> Psss, psss, put it down! -http://www.cafepress.com/putitdown > > > > > > I like it. > > > > > > I'll even go a step further and suggest that "$" be allowed as a > > > > > substitute for "self". It looks like a capital "S" (for Self), and it > > > > > stands out clearly. It also makes code more succinct with no loss of > > > > > readability. Think of the line wraps that could be avoided. > > > > It looks "ugly" simply because it is new to you. Once you get used to > > > it, I'll bet it will look fine. And resemblance to another language is > > > not a very good reason to reject it. > > > Perl is not new to me and I am familiar with the syntax, such as it > > is. ?I find it unspeakably ugly. ?So, no, you would lose your bet if > > it were me. > > > Carl Banks > > I don't know much about Perl, but my understanding is that a dollar > sign must be used every time a variable is dereferenced, as in bash or > other shell languages. What we are proposing here is something > entirely different: the dollar sign would simply be a shorthand for > "self". In Perl, the dollar sign is clutter, but in this case it > actually reduces clutter. But it's ugly. No amount of rationalization will make it not ugly. > Python already uses shorthand extensively. How about "def"? For people > who are so worried about self-explanatory symbols, what the heck does > that stand for? Default? Defeat? Defect? Defunct? Defer? > > At some time in the past, a conscious decision was made to save three > characters in the word "define" by abbreviating it as "def". The > suggestion to abbreviate "self" as "$" also saves three characters. > And "self" appears much more often than "def", so an abbreviation is > equally or more justified in my opinion. def isn't ugly. Carl Banks From gagsl-py2 at yahoo.com.ar Thu Dec 18 19:11:15 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Dec 2008 22:11:15 -0200 Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> <51866e70-8a6e-4338-94bd-59913990e342@k36g2000pri.googlegroups.com> Message-ID: En Thu, 18 Dec 2008 08:35:58 -0200, Aaron Brady escribi?: > On Dec 17, 7:16?pm, "Gabriel Genellina" > wrote: >> En Wed, 17 Dec 2008 22:46:32 -0200, Aaron Brady ? >> escribi?: >> >> >> >> > On Dec 17, 5:05?pm, "Gabriel Genellina" >> > wrote: >> >> En Wed, 17 Dec 2008 12:21:38 -0200, Jeremy Sanders ? >> >> escribi?: >> >> >> > It would be nice if Python created pipes that are properly ? >> >> inheritable by >> >> > default by child processes, as they're mostly used for IPC. >> >> >> I'd say it is a bug in os.pipe implementation; they should be ? >> >> inheritable ? >> >> by default, as in posix (after all, the code is in "posixmodule.c"). >> >> > The code looks like this: >> >> > ? ?ok = CreatePipe(&read, &write, NULL, 0); >> > ? ?Py_END_ALLOW_THREADS >> > ? ?if (!ok) >> > ? ? ? ? ? ?return win32_error("CreatePipe", NULL); >> > ? ?read_fd = _open_osfhandle((Py_intptr_t)read, 0); >> > ? ?write_fd = _open_osfhandle((Py_intptr_t)write, 1); >> >> > 'If lpPipeAttributes is NULL, the handle cannot be inherited.' ?You >> > could populate a 'SECURITY_ATTRIBUTES' structure, or call >> > DuplicateHandle on both of them. >> >> > A patch would look like this: >> >> > SECURITY_ATTRIBUTES sattribs; >> > sattribs.nLength = sizeof(sattribs); >> > sattribs.lpSecurityDescriptor = NULL; >> > sattribs.bInheritHandle = TRUE; >> > ok = CreatePipe(&read, &write, &sattribs, 0); >> >> Yes, that's exactly how os.popen does it (in posixmodule.c) >> >> > This still doesn't answer whether the file descriptor return by >> > '_open_osfhandle' can be inherited too. >> >> It doesn't matter. The OS only cares about file handles, not C RTL ? >> structures. >> >> -- >> Gabriel Genellina > > Ah, I see. Was it an executive decision about what is Pythonic, or > just a bug? Do you think the patch would be accepted? I probably > ought to mimic a small Python embedding to see if it needs anything > else. I don't know - I guess someone (years ago) blindly just replaced the pipe() system call by a CreatePipe call without further analysis. This is how I would summarize the issue: Pros (of changing os.pipe() to return inheritable pipes): - it isn't explicitely documented whether os.pipe() returns inheritable pipes or not, so both versions are "right" according to the documentation. - if someone relies on pipes being non-inheritable on Windows, that is undocumented behaviour, and Python has the right to change it. - the change would improve POSIX compatibility, it mimics what os.pipe() does on those OS. - inheritable pipes are less surprising for guys coming from other OS - inheritable pipes are a lot more useful than non-inheritable ones when doing IPC (probably its main usage). Cons: - os.pipe has behaved that way since long time ago. - some programs *might* break, if they relied on pipes being non-inheritable on Windows, even if that was undocumented behaviour. -- Gabriel Genellina From manu3d at gmail.com Fri Dec 12 12:22:34 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Fri, 12 Dec 2008 09:22:34 -0800 (PST) Subject: Bidirectional Networking References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <6qeht0Fc3541U1@mid.individual.net> Message-ID: <782258db-2bdc-45a7-8d8f-7a036d574985@t26g2000prh.googlegroups.com> Thank you both for the suggestions! Eventually I tried with threading as illustrated in the code below. And it works pretty well! The only problem I'm having with it is that as the server is a daemon the program should end when the client thread cease to be alive. But it doesn't seem to work that way and I'm not sure what's going on! I did achieve my objective though. Two separate instances of the code below will happily send random numbers to each other for a few seconds! Manu ------------------------- To use the following code, cut&paste into two separate *.py files and invert the port numbers in one file. Then, start them in two separate shells. WARNING: as mentioned above the two program do not exit and must be killed, i.e. through the Windows Task Manager or the unix kill command. ------------------------- import SocketServer import socket import threading import random from time import sleep ## Network request handler class MyTCPHandler(SocketServer.StreamRequestHandler): def handle(self): self.data = self.rfile.readline().strip() print "-> RECV: " + self.data + " - Sent by:" + self.client_address[0] ## Server Thread class AsyncServer(threading.Thread): def __init__(self, localServer): threading.Thread.__init__(self) self.server = SocketServer.TCPServer(localServer, MyTCPHandler) def run(self): self.server.serve_forever() ## Client Thread class AsyncClient(threading.Thread): def __init__(self, remoteServer): threading.Thread.__init__(self) self.remoteServer = remoteServer def run(self): cycle = 0 while cycle < 1000: chance = random.random() if(chance < 0.01): randomNumber = int(random.random() * 1000) message = str(randomNumber) + " from remote cycle " + str(cycle) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(self.remoteServer) sock.send(message + "\n") sock.close() print("SENT ->: "+str(randomNumber)+ " by local cycle "+str(cycle)) except: print("Failed to send number on cycle "+str (cycle)) pass cycle += 1 sleep(0.01) ## Simulating local/remote servers with different ports localServer = ("localhost", 9999) remoteServer = ("localhost", 10000) asyncServer = AsyncServer(localServer) asyncServer.daemon = True asyncServer.start() asyncClient = AsyncClient(remoteServer) asyncClient.start() From bernhard.voigt at gmail.com Wed Dec 10 03:56:48 2008 From: bernhard.voigt at gmail.com (bernhard.voigt at gmail.com) Date: Wed, 10 Dec 2008 00:56:48 -0800 (PST) Subject: filter iterable based on predicate take from another iterable Message-ID: Hi, is there is a neat way to select items from an iterable based on predicates stored in another iterable without zipping? I can do something like this: import itertools foo = range(10) # select even numbers bar = map(lambda i: i%2, foo) foobarselected = itertools.ifilterfalse(lambda t: t[0], itertools.izip (bar,foo)) # for simplicity I want to work with the single item list, not the zipped one fooselected = list(t[1] for t in foobarselected) However, it would be nice to have a function combining the last two instructions. Something like itertools.ifilterother(bar, foo) -> yield iterator with items from foo where bar is true Thanks! Bernhard From python at bdurham.com Wed Dec 24 03:39:56 2008 From: python at bdurham.com (python at bdurham.com) Date: Wed, 24 Dec 2008 03:39:56 -0500 Subject: Strategy for determing difference between 2 very large dictionaries In-Reply-To: <6rea9hF16p8tU1@mid.uni-berlin.de> References: <1230102996.2303.1291616055@webmail.messagingengine.com> <6rea9hF16p8tU1@mid.uni-berlin.de> Message-ID: <1230107996.14276.1291622859@webmail.messagingengine.com> Hi Marc, > `keys()` creates a list in memory, `iterkeys()` does not. With > ``set(dict.keys())`` there is a point in time where the dictionary, the > list, and the set co-exist in memory. With ``set(dict.iterkeys())`` > only the set and the dictionary exist in memory. Perfect explanation. Thank you! Malcolm ----- Original message ----- From: "Marc 'BlackJack' Rintsch" To: python-list at python.org Date: 24 Dec 2008 08:30:41 GMT Subject: Re: Strategy for determing difference between 2 very large dictionaries On Wed, 24 Dec 2008 03:23:00 -0500, python wrote: > Hi Gabriel, > > Thank you very much for your feedback! > >> k1 = set(dict1.iterkeys()) > > I noticed you suggested .iterkeys() vs. .keys(). Is there any advantage > to using an iterator vs. a list as the basis for creating a set? I > understand that an iterator makes sense if you're working with a large > set of items one at a time, but if you're creating a non-filtered > collection, I don't see the advantage of using an iterator or a list. > I'm sure I'm missing a subtle point here :) `keys()` creates a list in memory, `iterkeys()` does not. With ``set(dict.keys())`` there is a point in time where the dictionary, the list, and the set co-exist in memory. With ``set(dict.iterkeys())`` only the set and the dictionary exist in memory. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list From dotancohen at gmail.com Sat Dec 6 10:06:44 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Sat, 6 Dec 2008 17:06:44 +0200 Subject: RELEASED Python 3.0 final In-Reply-To: <006101c95745$124bfea0$0d00a8c0@hendrik> References: <874p1jux8u.fsf@benfinney.id.au> <87iqpyt80i.fsf@benfinney.id.au> <006101c95745$124bfea0$0d00a8c0@hendrik> Message-ID: <880dece00812060706k480735d4o8f03c65918309f93@mail.gmail.com> 2008/12/5 Hendrik van Rooyen : > I second the motion to use pish and tosh for a first level of disagreement. > > I recommend the rather archaic "Balderdash" as the next step in the > escalation of disagreement... > http://bash.org/?23396 -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-??-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From riklaunim at gmail.com Tue Dec 23 11:29:45 2008 From: riklaunim at gmail.com (riklaunim at gmail.com) Date: Tue, 23 Dec 2008 08:29:45 -0800 (PST) Subject: Get applications to open a given file (Mac and, or Windows) Message-ID: Under Linux/Unix I use GIO (pygobject) or gnome-vfs-python to get a list of installed applications that can open given file (for example image in graphics software). Is there something that can be used for MS Windows or Mac OS X? From bearophileHUGS at lycos.com Thu Dec 25 13:58:14 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 25 Dec 2008 10:58:14 -0800 (PST) Subject: Syntax error for print References: <2b65c6e1-b5a9-438d-a45c-b8f9d18228de@s1g2000prg.googlegroups.com> Message-ID: On Dec 25, 7:53?pm, jsm4... at gmail.com wrote: > IDLE 3.0>>> print "hello" > > SyntaxError: invalid syntax (, line 1)>>> 3+3 > 6 > >>> var = 4 > >>> var = var*4 > >>> print var > > SyntaxError: invalid syntax (, line 1) > > > > Any idea on why I am getting this error. > I have just started learning python and I am stuck at first thing > itself. > Any help would be greatly appreciated. > > Thanks, > Jeetu Sahil The print of Python3 needs parentheses: print(var) Older Python versions are different. Bye, bearophile From your.master at gmail.com Thu Dec 11 12:08:04 2008 From: your.master at gmail.com (Brandon) Date: Thu, 11 Dec 2008 09:08:04 -0800 (PST) Subject: dictionary idiom needed Message-ID: <383976cf-53fb-48e4-b028-8f568468ce77@r36g2000prf.googlegroups.com> Hi all, I have a series of lists in format ['word', 'tagA', 'tagB']. I have converted this to a few dicts, such as one in which keys are tuples of ('word', 'tagB'), and the values are the number of times that key was found. I need an dictionary idiom whereby I can find all instances of a given 'word' with any 'tagB', and then subdivide into all instances of a given 'tagB'. In both cases I would want the value as a count of all instances found. Can this be done with dictionaries? Or should I back up and do this with lists? All of the nested for loops I have tried return replicated results, so I can't trust those values. Thanks for any pointers, Brandon From lists at cheimes.de Mon Dec 22 18:05:58 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 23 Dec 2008 00:05:58 +0100 Subject: python3 urlopen(...).read() returns bytes In-Reply-To: <5496b34d-7ce4-4281-9f01-aed12dab9fd3@f33g2000vbf.googlegroups.com> References: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> <5496b34d-7ce4-4281-9f01-aed12dab9fd3@f33g2000vbf.googlegroups.com> Message-ID: ajaksu schrieb: > That said, a "decode to declared HTTP header encoding" version of > urlopen could be useful to give some users the output they want (text > from network io) or to make it clear why bytes is the safe way. Yeah, your idea sounds both useful and feasible. A patch is welcome! :) Christian From elbertlev at hotmail.com Sun Dec 14 00:53:17 2008 From: elbertlev at hotmail.com (Lev Elbert) Date: Sat, 13 Dec 2008 21:53:17 -0800 (PST) Subject: stable algorithm with complexity O(n) References: Message-ID: <42d4f840-47d4-4473-be58-7a6793dfdfae@o4g2000pra.googlegroups.com> 1. Comparison sorts have n*ln(n) complexity - does not do 2. Counting sort has the complexity O(d), where d is domain (in our case n^2) - does not do. 3. Radix sorts have the complexity O(n*k), where k is number of bits in integer. (32?) There are 2 variants: a. most significant digit (MSD), b. least significant digit (LSD). The LSD radix sort is stable. Good luck. From iofferkicks003 at gmail.com Sun Dec 21 08:58:13 2008 From: iofferkicks003 at gmail.com (www.iofferkicks.com) Date: Sun, 21 Dec 2008 05:58:13 -0800 (PST) Subject: www.iofferkicks.com china cheap wholesale nike shoes,air jordan shoes,air force one shoes. Message-ID: Get Nike Shoes at Super Cheap Prices Discount Nike air jordans (www.iofferkicks.com) Discount Nike Air Max 90 Sneakers (www.iofferkicks.com) Discount Nike Air Max 91 Supplier (www.iofferkicks.com) Discount Nike Air Max 95 Shoes Supplier (www.iofferkicks.com) Discount Nike Air Max 97 Trainers (www.iofferkicks.com) Discount Nike Air Max 2003 Wholesale (www.iofferkicks.com) Discount Nike Air Max 2004 Shoes Wholesale (www.iofferkicks.com) Discount Nike Air Max 2005 Shop (www.iofferkicks.com) Discount Nike Air Max 2006 Shoes Shop (www.iofferkicks.com) Discount Nike Air Max 360 Catalogs (www.iofferkicks.com) Discount Nike Air Max Ltd Shoes Catalogs (www.iofferkicks.com) Discount Nike Air Max Tn Men's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 2 Women's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 3 Customize (www.iofferkicks.com) Discount Nike Air Max Tn 4 Shoes Customize ( www.iofferkicks.com) Discount Nike Air Max Tn 6 Supply (www.iofferkicks.com) Discount Nike Shox NZ Shoes Supply (www.iofferkicks.com) Discount Nike Shox OZ Sale (www.iofferkicks.com) Discount Nike Shox TL Store (www.iofferkicks.com) Discount Nike Shox TL 2 Shoes Store (www.iofferkicks.com) Discount Nike Shox TL 3 Distributor (www.iofferkicks.com) Discount Nike Shox Bmw Shoes Distributor (www.iofferkicks.com) Discount Nike Shox Elite Shoes Manufacturer (www.iofferkicks.com) Discount Nike Shox Monster Manufacturer (www.iofferkicks.com) Discount Nike Shox R4 Running Shoes (www.iofferkicks.com) Discount Nike Shox R5 Mens Shoes (www.iofferkicks.com) Discount Nike Shox Ride Womens Shoes (www.iofferkicks.com) Discount Nike Shox Rival Shoes Wholesaler (www.iofferkicks.com) Discount Nike Shox Energia Wholesaler (www.iofferkicks.com) Discount Nike Shox LV Sneaker (www.iofferkicks.com) Discount Nike Shox Turbo Suppliers (www.iofferkicks.com) Discount Nike Shox Classic Shoes Suppliers (www.iofferkicks.com) Discount Nike Shox Dendara Trainer (www.iofferkicks.com) Discount Nike Air Jordan 1 Seller (www.iofferkicks.com) Discount Nike Air Jordan 2 Shoes Seller (www.iofferkicks.com) Discount Nike Air Jordan 3 Collection (www.iofferkicks.com) Discount Nike Air Jordan 4 Shoes Collection (www.iofferkicks.com) Discount Nike Air Jordan 5 Chaussure Shoes (www.iofferkicks.com) Discount Nike Air Jordan 6 Catalog (www.iofferkicks.com) Discount Nike Air Jordan 7 Shoes Catalog (www.iofferkicks.com) Discount Nike Air Jordan 8 Customized (www.iofferkicks.com) Discount Nike Air Jordan 9 Shoes Customized (www.iofferkicks.com) Discount Nike Air Jordan 10 Wholesalers (www.iofferkicks.com) Discount Nike Jordan 11 Shoes Wholesalers (www.iofferkicks.com) Discount Nike Air Jordan 12 Factory (www.iofferkicks.com) Discount Nike Air Jordan 13 Shoes Factory (www.iofferkicks.com) Discount Nike Air Jordan 14 Shoes Sell (www.iofferkicks.com) Discount Nike Air Jordan 16 Exporter (www.iofferkicks.com) Discount Nike Air Jordan 17 Shoes Exporter (www.iofferkicks.com) Discount Nike Air Jordan 18 Offer (www.iofferkicks.com) Discount Nike Air Jordan 19 Shoes Offer (www.iofferkicks.com) Discount Nike Air Jordan 20 Manufacture (www.iofferkicks.com) Discount Nike Jordan 21 Shoes Manufacture (www.iofferkicks.com) EMAIL:IOFFERKICKS at GMAIL.COM MSN :IOFFERKICKS at MSN.COM From bkamrani at gmail.com Thu Dec 4 04:11:17 2008 From: bkamrani at gmail.com (bkamrani at gmail.com) Date: Thu, 4 Dec 2008 01:11:17 -0800 (PST) Subject: performance question: dictionary or list, float or string? References: <01453507$0$20670$c3e8da3@news.astraweb.com> Message-ID: Thanks for your questions. Here come some answer below. On Dec 2, 2:50?pm, Steven D'Aprano wrote: > On Tue, 02 Dec 2008 03:41:29 -0800,bkamraniwrote: > > Hi Python gurus! > > I'm going to read in an Ascii file containing float numbers in rows and > > columns (say 10 columns 500000 rows) for further numerical process. > > Which format is best to save them in, eg, dictionary, list, or numpy > > array when it comes to performance? > > That depends on: > > (1) What do you mean by performance? Speed or memory use? Well, I think the speed is more important in this case as the volume of data is not large. > (2) Do you care about the performance of reading the data in, or the > performance of working with the data later, or both? The reading process is pretty fast and in range of some second, but I meant the performance of working with data. > (3) What do you intend to do with the numbers later? Normal numercal calcualtion such as sum, multiplication. (but not matrix multiplication) Thanks /Ben > > Will it be beneficial to convert all strings to float directly after > > reading or it doesn't matter to save them as string and thereafter when > > it comes to calculation convert them to floats? > > That depends on what you intend to do with them. Since you're doing > numerical processing, it's probably a good idea to convert them to > numbers rather than strings. > > -- > Steven From prologic at shortcircuit.net.au Tue Dec 30 19:56:11 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 10:56:11 +1000 Subject: get method In-Reply-To: <495AC2B3.7040706@mrabarnett.plus.com> References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> <495AAB97.5010707@mrabarnett.plus.com> <71508d7a-f678-40ba-801c-0bbfbbab961e@r15g2000prh.googlegroups.com> <495AC2B3.7040706@mrabarnett.plus.com> Message-ID: On Wed, Dec 31, 2008 at 10:54 AM, MRAB wrote: > Occasionally someone posts here wanting to count items and solutions > involving dict or defaultdict are suggested, and I think that a 'bag' class > would be useful. The 'set' class was introduced first in a module, but it > soon became a builtin. My posting was intended a possible reference > implementation. I think it would be a nice addition to the collections module. cheers James From steve at holdenweb.com Sun Dec 28 09:29:51 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 28 Dec 2008 09:29:51 -0500 Subject: strange behavior of math.sqrt() in new 3.0 version In-Reply-To: References: Message-ID: Tim Roberts wrote: > Scott David Daniels wrote: >> I avoid using single-letter variables except where I know the types >>from the name (so I use i, j, k, l, m, n as integers, s as string, >> and w, x, y, and z I am a little looser with (but usually float or >> complex). > > It's amazing to me that Fortran continues to live on in the hearts and > minds of today's programmers. Well I think it's more that the original Fortran programmers were applied mathematicians, who have always tended to use i through m as integer variables, and that usage continues both in programming and mathematics today. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From prabhu.ranjith at gmail.com Wed Dec 10 21:12:22 2008 From: prabhu.ranjith at gmail.com (free online study about computer language) Date: Wed, 10 Dec 2008 18:12:22 -0800 (PST) Subject: @ you can study through online freely all the computer language. Easy way and free registration. Visit www.tiketin.blogspot.com @ Message-ID: Now easy way to clear all your computer language doubts and to learn more visit www.tiketin.blogspot.com everything is free. You can also get e-books freely. No need to waste time and money visit www.tiketin.blogspot.com way to learn from your home itself visit www.tiketin.blogspot.com From tjreedy at udel.edu Wed Dec 10 21:59:07 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 10 Dec 2008 21:59:07 -0500 Subject: internal circular class references In-Reply-To: References: Message-ID: James Stroud wrote: > I resisted posting a similar question recently. After much > consideration, I realized that the inability to reference a class inside > its own definition must have been a deliberate design of the language. The class *does not exist* to be referenced from inside its body until after the body is executed and type(name, bases, namespace) is called. class name(bases): body is more or less equivalent to name = type('name', bases, exec(body,{})) except that the exec function (in 3.0) returns None instead of the passed in namespace. I think is would be possible to create and name-bind a blank class first, but then there would need to be a mechanism delete the class if the body execution failed. Because class definition can be nested, the mechanism would need a stack of classes. In addition, this would be a change in sequence from the usual assignment statement. tjr From benjamin.kaplan at case.edu Mon Dec 8 09:48:27 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 8 Dec 2008 09:48:27 -0500 Subject: Beginner trying to understand functions. In-Reply-To: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> Message-ID: On Mon, Dec 8, 2008 at 9:24 AM, cadmuxe wrote: > i think we should use raw_input('Please enter your name: ') instead of > input('Please enter your name: ') > Print is a function in this code and range returns an iterator (or else list(range(18,31)) is redundant). I think the OP is using python 3. Guess we're all going to have to get used to some of the changes, like raw_input being renamed to input. > 2008/12/8 Peter Otten <__peter__ at web.de> > > simonh wrote: >> >> > In my attempt to learn Python I'm writing a small (useless) program to >> > help me understand the various concepts. I'm going to add to this as I >> > learn to serve as a single place to see how something works, >> > hopefully. Here is the first approach: >> >> > That works fine. Then I've tried to use functions instead. The first >> > two work fine, the third fails: >> >> > def getName(): >> > name = input('Please enter your name: ') >> > print('Hello', name) >> > >> > def getAge(): >> > while True: >> > try: >> > age = int(input('Please enter your age: ')) >> > break >> > except ValueError: >> > print('That was not a valid number. Please try again.') >> > >> > def checkAge(): >> > permitted = list(range(18, 31)) >> > if age in permitted: >> > print('Come on in!') >> > elif age < min(permitted): >> > print('Sorry, too young.') >> > elif age > max(permitted): >> > print('Sorry, too old.') >> > >> > getName() >> > getAge() >> > checkAge() >> > >> > I get this error message: NameError: global name 'age' is not >> > defined. >> > >> > I'm stuck, can someone help? Thanks. >> >> >> Generally, when you calculate something within a function you tell it the >> caller by returning it: >> >> >>> def get_age(): >> ... return 74 >> ... >> >>> get_age() >> 74 >> >>> age = get_age() >> >>> age >> 74 >> >> And if you want a function to act upon a value you pass it explicitly: >> >> >>> def check_age(age): >> ... if 18 <= age <= 30: >> ... print("Come in") >> ... else: >> ... print("Sorry, you can't come in") >> ... >> >>> check_age(10) >> Sorry, you can't come in >> >>> check_age(20) >> Come in >> >> To check the age determined by the get_age() function you do: >> >> >>> age = get_age() >> >>> check_age(age) >> Sorry, you can't come in >> >> Peter >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Tue Dec 9 01:59:10 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Dec 2008 04:59:10 -0200 Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <1228766842.5709.28.camel@aalcdl07.lib.unc.edu> Message-ID: En Mon, 08 Dec 2008 18:07:22 -0200, J. Cliff Dyer escribi?: > On Wed, 2008-12-03 at 21:42 -0800, Warren DeLano wrote: >> Anyway, it seems obvious that the right decision for our customers (or >> more importantly, for their countless lines of autogenerated-Python >> log, >> state, and code files from the past decade) is to stick with C/Python >> 2.5.x for the time being and plan to make the jump to a > > All that broken code does sound like a hassle. However, I think the > workaround would be a fairly simple refactor: > > 1) make 'as_type' (or some other equivalent name like 'as_') a synonym > for 'as': Another workaround was posted last Wednesday by Matimus in message http://groups.google.com/group/comp.lang.python/msg/128a2cec74a96d3d Both seem like a reasonable solution. -- Gabriel Genellina From aahz at pythoncraft.com Sat Dec 6 23:18:35 2008 From: aahz at pythoncraft.com (Aahz) Date: 6 Dec 2008 20:18:35 -0800 Subject: Learning Python now coming from Perl References: Message-ID: In article , Bertilo Wennergren wrote: > >The main reason I waited until Python 3000 came out is the new way >Unicode is handled. The old way seemed really broken to me. Much of >what I do when I program consists of juggling Unicode text (real >Unicode text with lots of actual characters outside of Latin 1). So in >my case learning version 2.x first might not be very convenient. I'd >just get bogged down with the strange way 2.x handles such data. I'd >rather skip that completely and just go with the Unicode handling in >3.0. Sounds like you have a good use-case for 3.0 -- go to it! -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From basu at archlinux.us Mon Dec 29 02:26:52 2008 From: basu at archlinux.us (member Basu) Date: Mon, 29 Dec 2008 02:26:52 -0500 Subject: Get a list of functions in a file Message-ID: I'm putting some utility functions in a file and then building a simple shell interface to them. Is their some way I can automatically get a list of all the functions in the file? I could wrap them in a class and then use attributes, but I'd rather leave them as simple functions. Thanks, Basu -------------- next part -------------- An HTML attachment was scrubbed... URL: From eric at ericaro.net Thu Dec 18 14:52:52 2008 From: eric at ericaro.net (eric) Date: Thu, 18 Dec 2008 11:52:52 -0800 (PST) Subject: Factoring Polynomials References: Message-ID: <5dfe1cf3-530d-4e31-833e-e26db85611be@d36g2000prf.googlegroups.com> On Dec 18, 8:37?pm, collin.da... at gmail.com wrote: > I am trying to write a simple application to factor polynomials. I > wrote (simple) raw_input lines to collect the a, b, and c values from > the user, but I dont know how to implement the quadratic equation > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > into python. Any ideas? with numpy: from numpy import * s=[1,-1] x = -b+s*sqrt( b**2-4*a*c )/(2*a) Eric http://codeslash.blogspot.com From dickinsm at gmail.com Tue Dec 9 06:22:11 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 9 Dec 2008 03:22:11 -0800 (PST) Subject: Rich Comparisons Gotcha References: Message-ID: <07cbe992-97a0-4c30-9244-ad4acb75e743@q26g2000prq.googlegroups.com> On Dec 8, 2:24?pm, Rasmus Fogh wrote: > So, I would much prefer a language change. I am not competent to even > propose one properly, but I'll try. I don't see any technical problems in what you propose: as far as I can see it's entirely feasible. However: > should. On the minus side there would be the difference between > '__equal__' and '__eq__' to confuse people. I think this is exactly what makes the idea a non-starter. There are already enough questions on the lists about when to use 'is' and when to use '==', without adding an 'equals' function into the mix. It would add significant extra complexity to the core language, for questionable (IMO) gain. There are certainly other languages for which this distinction would make sense; I just don't think it's appropriate for Python, with its emphasis on practicality and and simplicity. Mark On the plus side the behaviour > of objects inside collections would now be explicitly defined, and __eq__ > and __equal__ would be so similar that most people could ignore the > distinction. > > Some examples: > > # NaN: > # For floats, __equal__ would be the same as __eq__. For NaN this gives>>> x = float('NaN') > >>> y = float('NaN') > >>> x == x > False > >>> equal(x,x) > True > >>> equal(x,y) > > False > # It may be problematical mathematically, but computationally it makes > # perfect sense that looking in a given storage location will give you the > # same value every time, even if the actual value happens to be undefined. > # The behaviour is simple to describe, and indeed NaN does behave this way > # in collections at the moment. All we are doing is documenting it clearly. > > # numpy > Numpy would have no __equal__ function, so we would have pure identity > semantics - 'equals(x,y)' would be the same as 'x is y' > > # ordinary numbers. > Any Python object with value semantics would need an __equal__ function > with the correct behaviour. > Mark Dickinson pointed out the thread "Comparing float and decimal", which > shows that comparisons between float and decimal numbers do not currently > satisfy 3). It would not be attractive to have __equal__ and __eq__ behave > differently for ordinary numbers, so if the relevant __eq__ can not be > fixed that is a problem for my proposal. > > At this point I shall try to retire gracefully. Regrettably I am not > competent to discuss if this can be done, how it can be done, and how > much work is required. > > Rasmus > > --------------------------------------------------------------------------- > Dr. Rasmus H. Fogh ? ? ? ? ? ? ? ? ?Email: r.h.f... at bioc.cam.ac.uk > Dept. of Biochemistry, University of Cambridge, > 80 Tennis Court Road, Cambridge CB2 1GA, UK. ? ? FAX (01223)766002 From bearophileHUGS at lycos.com Sun Dec 21 12:51:58 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 21 Dec 2008 09:51:58 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> <88a122de-14c6-4025-b36c-9a39bdd50d86@i20g2000prf.googlegroups.com> Message-ID: <9b3e509d-25d4-44d1-99a2-ee3515225f88@w24g2000prd.googlegroups.com> MRAB: > Interesting. The re module uses a form of bytecode. Not sure about the > relative cost of the dispatch code, though. I was talking about the main CPython VM, but the same ideas may be adapted for the RE engine too. Bye, bearophile From rcdailey at gmail.com Mon Dec 8 17:23:19 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 8 Dec 2008 14:23:19 -0800 (PST) Subject: Calling function from a string Message-ID: <7bc1be6f-121e-409a-9e08-f2dd2a86f241@e25g2000vbe.googlegroups.com> Hi, I have a string representing the name of a function in Python 3.0. How can I call the function name represented by this string *without* creating a mapping? From nad at acm.org Thu Dec 4 13:53:06 2008 From: nad at acm.org (Ned Deily) Date: Thu, 04 Dec 2008 10:53:06 -0800 Subject: Pythonic design patterns References: Message-ID: In article , Slaunger wrote: > I was therefore wondering if you could recommend a book or a resource > concerning design patterns with special focus on the possibilities in > Python? Check out any or all of Alex Martelli's talks on Python Design Patterns (search YouTube for "google developer python alex"), and download the notes at . -- Ned Deily, nad at acm.org From gagsl-py2 at yahoo.com.ar Mon Dec 8 03:30:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Dec 2008 06:30:56 -0200 Subject: Don't you just love writing this sort of thing :) In-Reply-To: References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: En Sun, 07 Dec 2008 05:34:39 -0200, Lawrence D'Oliveiro escribi?: > In message , Arnaud Delobelle wrote: > >> * you give the impression of being arrogant; > > Oddly enough, I wasn't the one who started by criticizing other people's > code. I have no ego about my code; I gladly accept criticisms. But > perhaps > some other people are not so thick-skinned and do not like getting as > they > give... May I ask then *why* did you chose to post your code fragment? Did I miss something? -- Gabriel Genellina From castironpi at gmail.com Thu Dec 18 20:45:21 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 18 Dec 2008 17:45:21 -0800 (PST) Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> <51866e70-8a6e-4338-94bd-59913990e342@k36g2000pri.googlegroups.com> Message-ID: <7f601ac7-fe98-464e-a661-2b4eebf38ffb@o40g2000prn.googlegroups.com> On Dec 18, 6:11?pm, "Gabriel Genellina" wrote: > En Thu, 18 Dec 2008 08:35:58 -0200, Aaron Brady > escribi?: > > > > > On Dec 17, 7:16?pm, "Gabriel Genellina" > > wrote: > >> En Wed, 17 Dec 2008 22:46:32 -0200, Aaron Brady ? > >> escribi?: > > >> > On Dec 17, 5:05?pm, "Gabriel Genellina" > >> > wrote: > >> >> En Wed, 17 Dec 2008 12:21:38 -0200, Jeremy Sanders ? > >> >> escribi?: > > >> >> > It would be nice if Python created pipes that are properly ? > >> >> inheritable by > >> >> > default by child processes, as they're mostly used for IPC. > > >> >> I'd say it is a bug in os.pipe implementation; they should be ? > >> >> inheritable ? > >> >> by default, as in posix (after all, the code is in "posixmodule.c"). > > >> > The code looks like this: > > >> > ? ?ok = CreatePipe(&read, &write, NULL, 0); > >> > ? ?Py_END_ALLOW_THREADS > >> > ? ?if (!ok) > >> > ? ? ? ? ? ?return win32_error("CreatePipe", NULL); > >> > ? ?read_fd = _open_osfhandle((Py_intptr_t)read, 0); > >> > ? ?write_fd = _open_osfhandle((Py_intptr_t)write, 1); > > >> > 'If lpPipeAttributes is NULL, the handle cannot be inherited.' ?You > >> > could populate a 'SECURITY_ATTRIBUTES' structure, or call > >> > DuplicateHandle on both of them. > > >> > A patch would look like this: > > >> > SECURITY_ATTRIBUTES sattribs; > >> > sattribs.nLength = sizeof(sattribs); > >> > sattribs.lpSecurityDescriptor = NULL; > >> > sattribs.bInheritHandle = TRUE; > >> > ok = CreatePipe(&read, &write, &sattribs, 0); > > >> Yes, that's exactly how os.popen does it (in posixmodule.c) > > >> > This still doesn't answer whether the file descriptor return by > >> > '_open_osfhandle' can be inherited too. > > >> It doesn't matter. The OS only cares about file handles, not C RTL ? > >> structures. > > >> -- > >> Gabriel Genellina > > > Ah, I see. ?Was it an executive decision about what is Pythonic, or > > just a bug? ?Do you think the patch would be accepted? ?I probably > > ought to mimic a small Python embedding to see if it needs anything > > else. > > I don't know - I guess someone (years ago) blindly just replaced the > pipe() system call by a CreatePipe call without further analysis. > > This is how I would summarize the issue: > > Pros (of changing os.pipe() to return inheritable pipes): > > - it isn't explicitely documented whether os.pipe() returns inheritable > pipes or not, so both versions are "right" according to the documentation. > - if someone relies on pipes being non-inheritable on Windows, that is > undocumented behaviour, and Python has the right to change it. > - the change would improve POSIX compatibility, it mimics what os.pipe() > does on those OS. > - inheritable pipes are less surprising for guys coming from other OS > - inheritable pipes are a lot more useful than non-inheritable ones when > doing IPC (probably its main usage). > > Cons: > > - os.pipe has behaved that way since long time ago. > - some programs *might* break, if they relied on pipes being > non-inheritable on Windows, even if that was undocumented behaviour. > > -- > Gabriel Genellina Hi, Microsoft has this example: http://msdn.microsoft.com/en-us/library/aa298531.aspx It creates two descriptors (not handles) with '_pipe'. Then it spawns a subprocess using 'spawnl', which correctly inherits a descriptor. So, if 'Popen' could mimic 'spawnl', then 'os.pipe', and consequently, 'os.read', 'os.write', &c. could stay as is. From nopsidy at gmail.com Tue Dec 9 00:53:20 2008 From: nopsidy at gmail.com (RP) Date: Mon, 8 Dec 2008 23:53:20 -0600 Subject: Password input in console/terminal Message-ID: Hello All, This is my first REAL post(question) to Python-List. I know I can take input from a user with raw_input() How do I take password input in console? Any Help would be Greatly Appreciated. Thank You. RP -------------- next part -------------- An HTML attachment was scrubbed... URL: From warren at delsci.com Thu Dec 4 00:42:37 2008 From: warren at delsci.com (Warren DeLano) Date: Wed, 3 Dec 2008 21:42:37 -0800 Subject: "as" keyword woes Message-ID: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> > > Why was it necessary to make "as" a reserved keyword? > > I can't answer for the Python developers as to why they *did* make it > a reserved word. > > But I can offer what I believe is a good reason why it *should* be a > reserved word: Because simple is better than complex, and special > cases aren't special enough to break the rules. So you prefer broken code to broken rules, eh? Your customers must love that! This is exactly the kind of ivory-tower thinking I feared might be behind the decision (form over function, damn the users to hell, etc.) > > And more to the point, why was it necessary to prevent developers > > from being able to refer to attributes named "as"? > > There aren't special rules for which names can be use in which way, > and that's a *good* thing. Any name that is valid in one area of > Python syntax is valid in all Python syntax. Except that Python syntax has proven itself to be a non-backwards compatible moving target. Eliminating cruft and adding new functionality is one thing, but introducing a whole new two-letter keyword so long after the game has begun? That seems well over the line of what can be considered reasonable. > > Why can't the parser distinguish between a standalone " as " keyword > > and ".as" used as an object/attribute reference? > > Because that would require special-casing some names as being > forbidden in syntax where other names are allowed. Special cases in > language syntax are to be avoided where feasible. Am I the only one picking up on the irony here? "as" exists largely to provide a mechanism for working around namespace conflicts -- except, apparently, conflicts involving "as". The fact that "as" itself creates an insurmountable namespace collision is just killing me! How absurd. Anyway, it seems obvious that the right decision for our customers (or more importantly, for their countless lines of autogenerated-Python log, state, and code files from the past decade) is to stick with C/Python 2.5.x for the time being and plan to make the jump to a threads-capable and hopefully backwards-compatible Python implementation as soon as possible (IronPython perhaps?). That seems like a sensible path around the breakage and enduring limitations of C/Python 2.6 or 3. Or in other words, if we're all going to go through a Python compatibility-disconnect, then we might as well kill as many birds as possible in a single pass -- and that single-threaded interpreter bird is definitely a "dodo" in danger of extinction. By the way, congratulations on 3.0 final! But to be brutally honest...in this many-core world we must all accept and deal with today, it is hard to imagine how a non-multithreaded AND non-backwards compatible Python implementation can have much of a life ahead of it, with or without an "as" keyword. I do sincerely hope I am wrong about this, but it is seems quite possible that C/Python's glory days are now behind us. And if so, then thank you all for so many wonderful years of effort and participation! C/Python has had a great run, and Python syntax, in a multiplicity of forms, will surely live on for many decades to come. Python has changed the world, and very much so for the better. Well done! Cheers, Warren From steve at REMOVE-THIS-cybersource.com.au Mon Dec 29 20:00:59 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Dec 2008 01:00:59 GMT Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <40b1b762-459b-4d6f-91f0-0a6e68d233ae@a26g2000prf.googlegroups.com> <4d396242-13c9-4318-97ba-99f18564fbc5@o4g2000pra.googlegroups.com> Message-ID: <016969d3$0$6988$c3e8da3@news.astraweb.com> On Mon, 29 Dec 2008 05:31:17 -0800, Aaron Brady wrote: > One style of coding I heard about once only permits returns at the end > of a function. It claims it makes it easier to see the function as a > mathematical object. That's silly. You treat the function as a black box: input comes in, and output comes out. You have no idea of what happens inside the black box: it could loop a thousand times, take 150 different branches, or take one of 37 different exit points. From the outside, it's still exactly like a mathematical object. Internal complexity is irrelevant. This is why mathematicians can perform algebra on complicated functions like Bessel's function (of the first or second kind), without needing to care that actually calculating Bessel's function is quite tricky. What I think the one-return-per-function style is aiming at is that it is (sometimes) easier to analyse the internals of the function if there are few branches. The more complicated branches you have, the harder it is to analyse the function. Early exits on their own are not the cause of the complexity: it's the number of branches leading to the early exit that causes the problem. Avoiding early exits is an over-reaction to the Bad Old Days of spaghetti code. But used wisely, early exists can simplify, not complicate, code. Consider the following: def find_ham(alist): for item in alist: if isinstance(item, Ham): return item raise ValueError('no ham found') def find_spam(alist): found_item = None for item in alist: if found_item is not None: if isinstance(item, Spam): found_item = item if found_item is None: raise ValueError('no spam found') else: return found_item The second version has double the number of lines of code of the first. It introduces an extra variable "found_item" and two extra if blocks. I don't think the claim that the version with an early exit is more complicated than the version without can justified. -- Steven From flarefight at googlemail.com Wed Dec 10 07:30:22 2008 From: flarefight at googlemail.com (ff) Date: Wed, 10 Dec 2008 04:30:22 -0800 (PST) Subject: Flushing PyQt's Event Queue Message-ID: <19d41195-a734-4974-ad02-b6ddf62c316f@v5g2000prm.googlegroups.com> Hi, I am writing an app which models growth of a system over time visually which is activated by button clicks, and when the loop finishes running i dont want any events [mainly clicking on buttons] that happened during the loop to be put into action since then it may run multiple times without the user realising what they have done, is there way to flush the event queue when the loop has finished?? ff From Russ.Paielli at gmail.com Sat Dec 6 17:39:34 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 6 Dec 2008 14:39:34 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> Message-ID: <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> On Dec 6, 1:21?pm, Carl Banks wrote: > On Dec 6, 9:12?am, "Russ P." wrote: > > > > > On Dec 6, 1:02?am, Antoine De Groote wrote: > > > > Allowing "$" as a substitute for "self" wouldn't require this new syntax. > > > > class C: > > > ? ? def method($, arg): > > > ? ? ? ? $.value = arg > > > > I'm strongly against this. This looks ugly and reminds me of Perl and > > > Ruby. (I don't have anything against these languages, but there's a > > > reason I use Python). > > > > Russ P. wrote: > > > > On Dec 5, 6:21 pm, "Daniel Fetchinson" > > > > wrote: > > > >> Hi folks, > > > > >> The story of the explicit self in method definitions has been > > > >> discussed to death and we all know it will stay. However, Guido > > > >> himself acknowledged that an alternative syntax makes perfect sense > > > >> and having both (old and new) in a future version of python is a > > > >> possibility since it maintains backward compatibility. The alternative > > > >> syntax will be syntactic sugar for the old one. This blog post of his > > > >> is what I'm talking about: > > > > >>http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... > > > > >> The proposal is to allow this: > > > > >> class C: > > > >> ? ? def self.method( arg ): > > > >> ? ? ? ? self.value = arg > > > >> ? ? ? ? return self.value > > > > >> instead of this: > > > > >> class C: > > > >> ? ? def method( self, arg ): > > > >> ? ? ? ? self.value = arg > > > >> ? ? ? ? return self.value > > > > >> I.e. explicit self stays only the syntax is slightly different and may > > > >> seem attractive to some. As pointed out by Guido classmethods would > > > >> work similarly: > > > > >> class C: > > > >> ? ? @classmethod > > > >> ? ? def cls.method( arg ): > > > >> ? ? ? ? cls.val = arg > > > >> ? ? ? ? return cls.val > > > > >> The fact that Guido says, > > > > >> "Now, I'm not saying that I like this better than the status quo. But > > > >> I like it a lot better than [...] but it has the great advantage that > > > >> it is backward compatible, and can be evolved into a PEP with a > > > >> reference implementation without too much effort." > > > > >> shows that the proposal is viable. > > > > >> I'd like this new way of defining methods, what do you guys think? > > > >> Anyone ready for writing a PEP? > > > > >> Cheers, > > > >> Daniel > > > > >> -- > > > >> Psss, psss, put it down! -http://www.cafepress.com/putitdown > > > > > I like it. > > > > > I'll even go a step further and suggest that "$" be allowed as a > > > > substitute for "self". It looks like a capital "S" (for Self), and it > > > > stands out clearly. It also makes code more succinct with no loss of > > > > readability. Think of the line wraps that could be avoided. > > > It looks "ugly" simply because it is new to you. Once you get used to > > it, I'll bet it will look fine. And resemblance to another language is > > not a very good reason to reject it. > > Perl is not new to me and I am familiar with the syntax, such as it > is. ?I find it unspeakably ugly. ?So, no, you would lose your bet if > it were me. > > Carl Banks I don't know much about Perl, but my understanding is that a dollar sign must be used every time a variable is dereferenced, as in bash or other shell languages. What we are proposing here is something entirely different: the dollar sign would simply be a shorthand for "self". In Perl, the dollar sign is clutter, but in this case it actually reduces clutter. Python already uses shorthand extensively. How about "def"? For people who are so worried about self-explanatory symbols, what the heck does that stand for? Default? Defeat? Defect? Defunct? Defer? At some time in the past, a conscious decision was made to save three characters in the word "define" by abbreviating it as "def". The suggestion to abbreviate "self" as "$" also saves three characters. And "self" appears much more often than "def", so an abbreviation is equally or more justified in my opinion. From google at mrabarnett.plus.com Tue Dec 30 19:54:11 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 31 Dec 2008 00:54:11 +0000 Subject: get method In-Reply-To: References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> <495AAB97.5010707@mrabarnett.plus.com> <71508d7a-f678-40ba-801c-0bbfbbab961e@r15g2000prh.googlegroups.com> Message-ID: <495AC2B3.7040706@mrabarnett.plus.com> James Mills wrote: > On Wed, Dec 31, 2008 at 10:22 AM, John Machin wrote: > (snip) > >> The "crawl through the shrubbery looking for evidence" approach >> stumbles on the actual code: > > Yes I found his implementation soon after :) > Not bad actually... I wonder why bag() isn't > shipped with the std lib - perhaps in teh set > module ? > Occasionally someone posts here wanting to count items and solutions involving dict or defaultdict are suggested, and I think that a 'bag' class would be useful. The 'set' class was introduced first in a module, but it soon became a builtin. My posting was intended a possible reference implementation. From arnodel at googlemail.com Tue Dec 16 05:15:08 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 16 Dec 2008 10:15:08 +0000 Subject: tricky nested list unpacking problem References: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> Message-ID: bearophileHUGS at lycos.com writes: > I was waiting to answer because so far I have found a bad-looking > solution only. Seeing there's only your solution, I show mine too. It > seems similar to your one. I think that the solution below is a bit clearer, although I think it is more resource intensive than my first one. I've switched to a generator function to make it more easily comparable. It's true that it's a problem that seems designed for Scheme! l1 = [1,2,3,[5,6]] l2 = [1,2,3,[5,6],[7,8,9]] l3 = [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]] def flatten(x): if isinstance(x, list): for y in x: for z in flatten(y): yield z else: yield x def unpack(lst, acc=[]): i = len(acc) if i == len(lst): yield '-'.join(map(str, acc)) else: for x in flatten(lst[i]): for res in unpack(lst, acc + [x]): yield res -- Arnaud From version5 at gmail.com Sun Dec 7 16:31:59 2008 From: version5 at gmail.com (nnp) Date: Sun, 7 Dec 2008 21:31:59 +0000 Subject: Is 3.0 worth breaking backward compatibility? In-Reply-To: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> Message-ID: <28749c0e0812071331p1a509ad6w74fb258d766a518c@mail.gmail.com> Have a read of this http://www.b-list.org/weblog/2008/dec/05/python-3000/ It's a response to questions similar to yours by James Bennett On Sun, Dec 7, 2008 at 7:22 PM, walterbyrd wrote: > IMO: breaking backward compatibility is a big deal, and should only be > done when it is seriously needed. > > Also, IMO, most of, if not all, of the changes being made in 3.0 are > debatable, at best. I can not think of anything that is being changed > that was really a "show stopper" anyway. > > At best, I am a casual python user, so it's likely that I am missing > something. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.unprotectedhex.com http://www.smashthestack.org From george.sakkis at gmail.com Thu Dec 4 10:17:20 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 4 Dec 2008 07:17:20 -0800 (PST) Subject: Pythonic design patterns References: <0147e8b9$0$20670$c3e8da3@news.astraweb.com> Message-ID: <45fdd23c-0ccc-4135-b10c-1ef1d5ea4e6b@p2g2000prf.googlegroups.com> On Dec 4, 10:02?am, Steven D'Aprano wrote: > On Thu, 04 Dec 2008 01:09:08 -0800, Slaunger wrote: > > I find myself spending a lot of time in Python making some designs, to > > solve some task, which is the end turn out to be closely related to well > > established design patterns / programming idioms, which other users in > > this forum has been kind enough to point out. Only my implementations > > are often not that clean, and I may call things something different than > > the normal convention, which is a source of confusion for myself and > > others trying to communicate with me. > > > I guess I could boost my productivity by learning these well-proven and > > well-established design patterns by heart. > > This is all very good, but don't drink the design pattern Kool-Aid and > start pushing design patterns everywhere. (Not everything needs to be a > singleton. No, really.) Obligatory reading: http://www.mortendahl.dk/thoughts/blog/view.aspx?id=122 George From jcd at sdf.lonestar.org Thu Dec 18 15:56:11 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Thu, 18 Dec 2008 15:56:11 -0500 Subject: confused about __str__ vs. __repr__ In-Reply-To: References: <494A5ACA.8060205@wildenhain.de> Message-ID: <1229633772.10976.13.camel@aalcdl07.lib.unc.edu> On Thu, 2008-12-18 at 13:35 -0500, Neal Becker wrote: > Mel wrote: > > > Neal Becker wrote: > > > >> Tino Wildenhain wrote: > >> > >>> Neal Becker wrote: > >>>> Reading some FAQ, I see that __str__ is "meant for human eyes". > >>>> > >>>> But it seems that: > >>>> class X(object): > >>>> def __str__(self): > >>>> return "str" > >>>> def __repr__(self): > >>>> return "repr" > >>>> > >>>> x = X() > >>>> d = {0 : x} > >>>> print d > >>>> {0: repr} > >>>> > >>>> So if __str__ is "meant for human eyes", then why isn't print using it! > >>> > >>> it is: > >>> > >>> > print x > >>> str > >>> > >>> but dict just uses repr() for all its childs to print. > >>> > >>> T. > >> That makes no sense to me. If I call 'print' on a container, why > >> wouldn't > >> it recursively print on the contained objects? Since print means call > >> str, printing a container should recursively call str on the objects. > > > > Basically because there are too many right ways to format the resulting > > report. Space separated? Tab separated? One per line? Boxes around > > them? As HTML definition lists? Creating a standard report form would > > take a lot of work and wouldn't, finally, solve very many peoples' > > problems. > > > > Mel. > > > Thanks, but the question of how to format the container is different from how to format the primitive elements of the container. I was suggesting that printing an element of a container should be consistent with printing the element without the container, i.e., > > print [a] > should be consistent with > print a > > Well, first of all, an object is an object. Whether it is a container or not is a matter of semantic convenience. And how an object prints itself is up to that object and that object alone. If the object chooses to recursively call __str__ on its elements, it is free to do so, but since that causes ambiguity (as many people have pointed out), python has (wisely) chosen to use repr instead. If I wanted to implement a list-like class that doesn't show it's elements at all when printed, but instead shows its length, I am free to do so. For example: >>> hl = HiddenList(1,2,3) >>> hl >>> hl[1] 2 (Implementation of HiddenList left as an exercise for the reader.) If you want to implement a list-like object that returns the str of its elements, go right ahead, or implement a function that digs into containers and creates its own list representation for them. But that's not how python works by default, nor should it be, for reasons already explained by others. Cheers, Cliff From gagsl-py2 at yahoo.com.ar Thu Dec 18 19:11:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Dec 2008 22:11:27 -0200 Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> <6qv7kfFeuf65U1@mid.uni-berlin.de> <6qv9v4Ff1lv9U1@mid.uni-berlin.de> Message-ID: En Thu, 18 Dec 2008 14:05:32 -0200, Mikael Olofsson escribi?: > Diez B. Roggisch wrote: >> Yep. And it's easy enough if you don't care about them being different.. >> def __repr__(self): >> return str(self) > > If I ever wanted __str__ and __repr__ to return the same thing, I would > make them equal: > > def __str__(self): > return 'whatever you want' > __repr__ = __str__ > > That makes it more obvious to me what's going on. As a bonus, it saves > one method call for every repr call. It's even easier to define only __repr__, __str__ defaults to it: >>> class OnlyRepr(object): ... def __repr__(self): return "repr called" ... >>> class OnlyStr(object): ... def __str__(self): return "str called" ... >>> class Both(OnlyRepr, OnlyStr): ... pass ... >>> r = OnlyRepr() >>> s = OnlyStr() >>> b = Both() >>> print "only repr:", repr(r), str(r) only repr: repr called repr called >>> print "only str: ", repr(s), str(s) only str: <__main__.OnlyStr object at 0x00BA10F0> str called >>> print "both: ", repr(b), str(b) both: repr called str called -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Wed Dec 31 13:05:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 31 Dec 2008 16:05:07 -0200 Subject: How to get back a list object from its string representation? References: <78f8019c0812302046j31fa38aeif33d659ec5f2c84e@mail.gmail.com> <016b07b4$0$6988$c3e8da3@news.astraweb.com> Message-ID: En Wed, 31 Dec 2008 04:27:01 -0200, Steven D'Aprano escribi?: > On Wed, 31 Dec 2008 03:08:29 -0200, Gabriel Genellina wrote: > >> eval is like Pandora?s box, all kind of bad things can come from it. Do >> not use it with any user-supplied string. If you can restrict the values >> to be just constants, there is a "safe eval" recipe in >> http://code.activestate.com > > The ast module in Python 2.6 includes a "literal eval" function: > >>>> ast.literal_eval("[1, 2, 3]") > [1, 2, 3] That's a very nice addition! -- Gabriel Genellina From lists at cheimes.de Tue Dec 23 09:59:36 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 23 Dec 2008 15:59:36 +0100 Subject: no sign() function ? In-Reply-To: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> Message-ID: All algorithm including my own suffer from one mistake. Nobody accounts for NaN (not a number). You have to check for NaNs, too. NaNs have no sign at all. You could also try to do some fancy bit mask operation like >>> ord(struct.pack("d", 0.)[7]) & 0x80 0 >>> ord(struct.pack("d", -0.)[7]) & 0x80 128 But you have to take care of little endian, big endian and mixd endian IEEE 754 platforms, too. There are also platforms that don't have IEEE 754 floats at all ... Have fun :) Christian From banshee.welton at gmail.com Thu Dec 18 13:40:19 2008 From: banshee.welton at gmail.com (banshee.welton at gmail.com) Date: Thu, 18 Dec 2008 10:40:19 -0800 (PST) Subject: Adjusting filename and line number Message-ID: <4f1456af-ab2e-4b71-bc88-776fd6bd3a69@q30g2000prq.googlegroups.com> Hello, I'm working with some embedded python and would like to be able to adjust the reported filename and line number of some embedded user- written code so that errors returned coincide with things the user might actually be familiar with. In perl I could do this by adjusting the filename and line within a script like so: foo.pl ------ #!/usr/bin/env perl #line 1000 "myfile.txt" this is a syntax error $ perl foo.pl Can't locate object method "a" via package "syntax" (perhaps you forgot to load "syntax"?) at myfile.txt line 1000. For what it's worth, the same directive also works as a "C" preprocessor macro. I have searched for ways of managing this in python, but so far have not found any way of accomplishing this. Anyone know how it could be done? Thanks From manatlan at gmail.com Fri Dec 5 13:20:11 2008 From: manatlan at gmail.com (manatlan) Date: Fri, 5 Dec 2008 10:20:11 -0800 (PST) Subject: pytz and timezone specialists Message-ID: <1f6172c1-4f70-42ea-8010-b72beb0af487@w24g2000prd.googlegroups.com> Here is a really simple code : ------------------------------------------------------- from datetime import datetime from pytz import timezone tz=timezone("Europe/Paris") d=datetime(2008,12,12,19,00,00,tzinfo=tz) print d.isoformat() d=datetime.now(tz) print d.isoformat() ------------------------------------------------------- when I run it, it displays (according current time ;-): 2008-12-12T19:00:00+00:09 2008-12-05T19:15:38.135467+01:00 The Europe/Paris timezone is GMT+1 ... the second date seems to be right (+01:00 at the end) But why the first date ends with "+00:09" ?!? it should be +01:00 ... no ?! Where's the bug ?!? (sure : it's me ;-) ... but i don't understand this simple thing) From darcy at druid.net Wed Dec 10 15:22:38 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 10 Dec 2008 15:22:38 -0500 Subject: Python is slow In-Reply-To: <494020BC.6020700@gmail.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <494020BC.6020700@gmail.com> Message-ID: <20081210152238.6b98626c.darcy@druid.net> On Wed, 10 Dec 2008 21:04:12 +0100 Stef Mientki wrote: > cm_gui wrote: > > [...] > Put this guy in the junk filter, What's the point if people like you are just going to repost his entire message like that? -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From duncan.booth at invalid.invalid Sat Dec 13 14:17:41 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Dec 2008 19:17:41 GMT Subject: [OT] stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote: > David Hl????ik schrieb: >> Hi guys, >> >> i am really sorry for making offtopic, hope you will not kill me, but >> this is for me life important problem which needs to be solved within >> next 12 hours.. >> >> I have to create stable algorithm for sorting n numbers from interval >> [1,n^2] with time complexity O(n) . >> >> Can someone please give me a hint. Would be very very thankful! > > Unless I grossly miss out on something in computer science 101, the > lower bound for sorting is O(n * log_2 n). Which makes your task > impossible, unless there is something to be assumed about the > distribution of numbers in your sequence. > > Who has given you that assignment - a professor? Or some friend who's > playing tricks on you? > I think you must have fallen asleep during CS101. The lower bound for sorting where you make a two way branch at each step is O(n * log_2 n), but if you can choose between k possible orderings in a single comparison you can get O(n * log_k n). To beat n * log_2 n just use a bucket sort: for numbers with a known maximum you can sort them digit by digit for O(n log_k n), and if you don't restrict yourself to decimal then k can be as large as you want, so for the problem in question I think you can set k=n and (log_n n)==1 so you get O(n) i.e. digit by digit bucket sort the numbers in base n. Something like (untested): n = len(data) buckets1 = [[] for i in range(n)] buckets2 = [[] for i in range(n)] for x in data: buckets1[x % n].append(x) for x in (v for b in buckets1 for v in reversed(b)): buckets2[x // n].append(x) for x in (v for b in buckets2 for v in b): print x All loops are order n (the last two have about 2*n steps). I lied about the untested: >>> def f(data): n = len(data) buckets1 = [[] for i in range(n)] buckets2 = [[] for i in range(n)] for x in data: buckets1[x % n].append(x) for x in (v for b in buckets1 for v in reversed(b)): buckets2[x // n].append(x) for x in (v for b in buckets2 for v in b): print x >>> import random >>> data = [ random.randint(1,100) for i in range(10)] >>> f(data) 1 16 30 35 70 70 75 76 82 99 From Scott.Daniels at Acm.Org Wed Dec 24 15:28:29 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 24 Dec 2008 12:28:29 -0800 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <494febd1$0$20851$426a74cc@news.free.fr> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> <494febd1$0$20851$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > ... Now improvements are always welcomes, and if you compare 1.5.2 with > 2.5.1, you'll find out that the core developpers did improve Python's > perfs. Cool, palindromic inverses as compatible versions! From silverburgh.meryl at gmail.com Mon Dec 15 16:12:08 2008 From: silverburgh.meryl at gmail.com (silverburgh.meryl at gmail.com) Date: Mon, 15 Dec 2008 13:12:08 -0800 (PST) Subject: How can I return a non-zero status result from a python script? Message-ID: <74b53da4-bf07-431b-898b-49977f7a685c@r36g2000prf.googlegroups.com> Hi How can I return a non-zero status result from the script? Just do a return 1? at the end? From scalet at yebu.de Tue Dec 9 07:06:03 2008 From: scalet at yebu.de (resi147) Date: Tue, 9 Dec 2008 04:06:03 -0800 (PST) Subject: close has no effect on Mac OSX Python 3.0 References: <83b43edf-81e5-4116-ad7b-2dcacde2d101@f3g2000yqf.googlegroups.com> Message-ID: On 9 Dez., 07:51, "Gabriel Genellina" wrote: > En Mon, 08 Dec 2008 20:09:23 -0200, resi147 escribi?: > > > I'm wondering if it's really a bug since it's so trivial: > > > fp = open('/etc/services') > > ct = fp.read(1048) > > print(ct[-80:], end='') > > fp.close() > > ct = fp.read(17) > > print(ct) > > > the second read should fail, but happily continues reading the file. > > Really a bug? > > Looks like a real bug to me. In fact it is already reported:http://bugs.python.org/issue4604 > > -- > Gabriel Genellina Thanks to Skip Montanaro, he did it (for me, thanks :-) Karl. From exarkun at divmod.com Mon Dec 15 10:36:45 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 15 Dec 2008 10:36:45 -0500 Subject: %s place holder does not let me insert ' in an sql query with python. In-Reply-To: <1229345178.31093.24.camel@krishna-laptop> Message-ID: <20081215153645.20272.1331140571.divmod.quotient.21352@ohm> On Mon, 15 Dec 2008 18:16:18 +0530, Krishnakant wrote: >hello all hackers. >This is some kind of an interesting situation although many of you must >have already gone through it. >I am facing a situation where I have to use psycopg2 and insert rows in >a postgresql table. >That's pritty easy and no need to say that it works well. But there are >some entries which have an ' in the value. >I have a venders table in my database and one of the values tryed was >"His Master's Voice " >now the master's word has the ' which is used for starting and ending a >varchar value for postgresql or almost any standard RDBMS. >Does any one know what is the way out of this? >how do you let the ' go as a part of the string? >I have used %s as placeholder as in >queryString = "insert into venders values ('%s,%s,%s" % >(field1,field2,field3 ) ... >This is not working for the ' values. >can any one suggest a suitable solution? You got pretty close to the right approach. All you have to do is stop doing Python string interpolation. Don't do this: cursor.execute("foo (%s, %s, %s)" % (f1, f2, f3)) Instead, do this: cursor.execute("foo (%s, %s, %s)", (f1, f2, f3)) This works for all data and avoid numerous potential security issues. Doing it this way is called using "bind parameters". You should always use bind parameters when executing a statement with variable data. You should never ever use Python string interpolation as in the code you included in your original post (or in some of the other responses you received). Jean-Paul From research at johnohagan.com Wed Dec 10 20:21:24 2008 From: research at johnohagan.com (John O'Hagan) Date: Thu, 11 Dec 2008 01:21:24 +0000 Subject: Python music sequencer timing problems In-Reply-To: <3b52b652-df61-4eb4-bcff-0d1fb6f20891@r15g2000prh.googlegroups.com> References: <3b52b652-df61-4eb4-bcff-0d1fb6f20891@r15g2000prh.googlegroups.com> Message-ID: <200812110121.25825.research@johnohagan.com> On Wed, 10 Dec 2008, badmuthahubbard wrote: > I've been trying to get the timing right for a music sequencer using > Tkinter. First I just loaded the Csound API module and ran a Csound > engine in its own performance thread. The score timing was good, > being controlled internally by Csound, but any time I moved the mouse > I got audio dropouts. > It was suggested I run the audio engine as a separate process, with > elevated/realtime priority and use sockets to tell it what to play, > and that way, too, people could set up servers for the audio on > different CPUs. But I've found that the method I came up with for > timing the beats/notes is too slow (using threading.Timer on a > function that calls itself over and over), and the whole thing played > too slowly (and still gave me noise when moving the mouse). I've been > using subprocesses, but I'm now wondering if sockets would or could > make a difference. > > The overall goal is this: when the user wants to audition a piece, > create an audio engine process with elevated/realtime priority. This > engine also has all the synthesis and sound processing rules for the > various instruments, due to the way Csound is structured. Set up a > scheduler- possibly in another process, or just another thread- and > fill it with all the notes from the score and their times. Also, the > user should be able to see a time-cursor moving across the piece so > they can see where they are in the score. As this last bit is GUI, > the scheduler should be able to send callbacks back to the GUI as well > as notes to the audio engine. But neither the scheduler nor the audio > engine should wait for Tkinter's updating of the location of the time- > cursor. Naturally, all notes will have higher priorities in the > scheduler than all GUI updates, but they won't necessarily always be > at the same time. > > So, I have a few ideas about how to proceed, but I want to know if > I'll need to learn more general things first: > 1. > Create both the scheduler and the audio engine as separate processes > and communicate with them through sockets. When all events are > entered in the scheduler, open a server socket in the main GUI process > and listen for callbacks to move the cursor (is it possible to do this > using Tkinter's mainloop, so the mouse can be moved, albeit > sluggishly, at the same time the cursor is moving continuously?); the > audio engine runs at as high priority as possible, and the scheduler > runs somewhere between that and the priority of the main GUI, which > should even perhaps be temporarily lowered below default for good > measure. > > or > > 2. > Create the audio engine as an elevated priority process, and the > scheduler as a separate thread in the main process. The scheduler > sends notes to the audio engine and callbacks within its own process > to move the GUI cursor. Optionally, every tiny update of the cursor > could be a separate thread that dies an instant later. > > 3. > Closer to my original idea, but I'm hoping to avoid this. All note > scheduling and tempo control is done by Csound as audio engine, and a > Csound channel is set aside for callbacks to update the cursor > position. Maybe this would be smoothest, as timing is built into > Csound already, but the Csound score will be full of thousands of > pseudo-notes that only exist for those callbacks. Down the road I'd > like to have notes sound whenever they are added or moved on the > score, not just when playing the piece, as well as the option of > adjusting the level, pan, etc. of running instruments. > Hi Chuckk, I've recently been fooling with something involving timing and synchronising multiple note-on/note-off events, and also tried threading and subprocesses without much success - out of the box, the high-tempo precision wasn't there. But I had more luck with this approach, if it's not way too simple for your purpose (I'm not using a gui, for example); in psuedocode: from time import time, sleep start = time() for event in music: duration=len(event) #Really, the length of the event play(event) while 1: timer = time() remaining = start + duration - timer if remaining < 0.001: break else: sleep(remaining / 2) stop(event) start += duration IOW, just check the time, wait half the remaining note duration, check the time again, etc, till you've reached your desired precision level (in this case 0.001 sec). The halving of each succesive sleep() means that there is only a handful of calls to time() per note, 5-10 depending on the tempo. (Of course it could be any fraction, I just pulled that out of a hat; it would probably be better too if the fraction decremented as the deadline approached). Even with this naive algorithm, I'm getting accuracy of <0.001 sec consistently, up to stupidly high tempos like 3000 bpm (as measured by inserting a "print remaining" in the loop) without using a separate timing thread or "sync pulse", and with only a few calls. Any processes started this way stay in sync, even if individual events are delayed, because the "start" variable is incremented by the correct (not actual) duration of the note. (But I guess that's just scheduling, right? :) ) Obviously there is a limit imposed by arithmetical precision, but I've left things running all day without seeing a discrepancy. In terms of audio process communication, I'm using sox in a subprocess to play samples (and its cheesey synth sound!), and fluidsynth via a socket for midi. The latter is far superior and seems to handle whatever is thrown at it, and with the jack driver with realtime priority, the dropouts you mentioned caused by mouse movements and so on disappear. Of course, this doesn't prove that using a socket is better; I don't think sox is jack-aware, and if the subprocesses could have different priorities from the parent process, that may help with the difficulties we're having with them. Anyone out there know about that? I've been putting off getting into Csound, but by all accounts it's _the_ audio language. Good luck with your project, it sounds interesting. Regards, john From mail at timgolden.me.uk Mon Dec 22 11:02:49 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 22 Dec 2008 16:02:49 +0000 Subject: join a samba domain In-Reply-To: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> References: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> Message-ID: <494FBA29.30207@timgolden.me.uk> Toff wrote: > hi, > > I 'm trying to write a script to make my computer join a samba. > > domeone have any idea ?? Ummm. It's not clear if you're saying that your code doesn't work, or asking for general advice, or what? I'm not in a position to have my machine join a domain or workgroup, but you seem to have got most things in place already. The only thing I would expect to have to change is this last line: > import wmi > c = wmi.WMI() > d = c.Win32_ComputerSystem > d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") because the d is only a WMI *class*, not a WMI *instance*, so doesn't refer as it should to your computer system but to the class of computer systems. Try something like this (untested): import wmi c = wmi.WMI () for d in c.Win32_ComputerSystem (): d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") TJG From rt8396 at gmail.com Fri Dec 19 22:07:49 2008 From: rt8396 at gmail.com (r) Date: Fri, 19 Dec 2008 19:07:49 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c4ef2$0$20656$c3e8da3@news.astraweb.com> Message-ID: <2d53cd36-52b0-4a1a-913d-0c545cfadc23@v15g2000vbb.googlegroups.com> Thanks Steven, We need a real Pepsi challenge here to show the insignificance of this change. I am not against change. But when we lose something as - compact- as %formating i'm going to want to see a damn good reason for it! Especially when this breaks code, and the "French Connection" is not good enough reason for me :) Christian said this was not going to be depreciated until 3.2, but that still puts the accepted way on the chopping block. From clp at rebertia.com Mon Dec 8 00:36:42 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 7 Dec 2008 21:36:42 -0800 Subject: A question about reference in Python. In-Reply-To: <493CB003.3080209@gmail.com> References: <493CB003.3080209@gmail.com> Message-ID: <47c890dc0812072136v4e36dc1crbf0c913760f477d4@mail.gmail.com> On Sun, Dec 7, 2008 at 9:26 PM, Group wrote: > Hello, I'm studying algorithom. For concentrating on the question itself, I > intend to use Python to implement the algorithoms. > > Now, I want to write a Red-Black Tree, and a List structure. In C/C++, I can > use pointers to refer to children notes (or next notes). But, in Python, > how > can I do it? Except the sequence, I know not any way. > > You'd better help me understan how can I transform the following C code into > Python: > > /* a List */ > struct { > int data; > int *next; > int *prev; > } Possibly not an exact literal translation, but: class ListNode(object): def __init__(self, data, prev=None, next=None) self.data = data self.prev = prev self.next = next Keep in mind that Python uses call-by-object (google it), so it doesn't have pointers/references per-se. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > That's all. Thanks! > Kermit > > -- > http://mail.python.org/mailman/listinfo/python-list > From badmuthahubbard at usenet.cnntp.org Sun Dec 14 09:29:10 2008 From: badmuthahubbard at usenet.cnntp.org (Bad Mutha Hubbard) Date: 14 Dec 2008 14:29:10 GMT Subject: Python music sequencer timing problems References: <3b52b652-df61-4eb4-bcff-0d1fb6f20891@r15g2000prh.googlegroups.com> Message-ID: <49451835$0$17068$6e1ede2f@read.cnntp.org> John O'Hagan wrote: > On Wed, 10 Dec 2008, badmuthahubbard wrote: >> I've been trying to get the timing right for a music sequencer using >> Tkinter. First I just loaded the Csound API module and ran a Csound >> engine in its own performance thread. The score timing was good, >> being controlled internally by Csound, but any time I moved the mouse >> I got audio dropouts. >> It was suggested I run the audio engine as a separate process, with >> elevated/realtime priority and use sockets to tell it what to play, >> and that way, too, people could set up servers for the audio on >> different CPUs. But I've found that the method I came up with for >> timing the beats/notes is too slow (using threading.Timer on a >> function that calls itself over and over), and the whole thing played >> too slowly (and still gave me noise when moving the mouse). I've been >> using subprocesses, but I'm now wondering if sockets would or could >> make a difference. >> >> The overall goal is this: when the user wants to audition a piece, >> create an audio engine process with elevated/realtime priority. This >> engine also has all the synthesis and sound processing rules for the >> various instruments, due to the way Csound is structured. Set up a >> scheduler- possibly in another process, or just another thread- and >> fill it with all the notes from the score and their times. Also, the >> user should be able to see a time-cursor moving across the piece so >> they can see where they are in the score. As this last bit is GUI, >> the scheduler should be able to send callbacks back to the GUI as well >> as notes to the audio engine. But neither the scheduler nor the audio >> engine should wait for Tkinter's updating of the location of the time- >> cursor. Naturally, all notes will have higher priorities in the >> scheduler than all GUI updates, but they won't necessarily always be >> at the same time. >> >> So, I have a few ideas about how to proceed, but I want to know if >> I'll need to learn more general things first: >> 1. >> Create both the scheduler and the audio engine as separate processes >> and communicate with them through sockets. When all events are >> entered in the scheduler, open a server socket in the main GUI process >> and listen for callbacks to move the cursor (is it possible to do this >> using Tkinter's mainloop, so the mouse can be moved, albeit >> sluggishly, at the same time the cursor is moving continuously?); the >> audio engine runs at as high priority as possible, and the scheduler >> runs somewhere between that and the priority of the main GUI, which >> should even perhaps be temporarily lowered below default for good >> measure. >> >> or >> >> 2. >> Create the audio engine as an elevated priority process, and the >> scheduler as a separate thread in the main process. The scheduler >> sends notes to the audio engine and callbacks within its own process >> to move the GUI cursor. Optionally, every tiny update of the cursor >> could be a separate thread that dies an instant later. >> >> 3. >> Closer to my original idea, but I'm hoping to avoid this. All note >> scheduling and tempo control is done by Csound as audio engine, and a >> Csound channel is set aside for callbacks to update the cursor >> position. Maybe this would be smoothest, as timing is built into >> Csound already, but the Csound score will be full of thousands of >> pseudo-notes that only exist for those callbacks. Down the road I'd >> like to have notes sound whenever they are added or moved on the >> score, not just when playing the piece, as well as the option of >> adjusting the level, pan, etc. of running instruments. >> > > Hi Chuckk, > > I've recently been fooling with something involving timing and synchronising > multiple note-on/note-off events, and also tried threading and subprocesses > without much success - out of the box, the high-tempo precision wasn't there. > > But I had more luck with this approach, if it's not way too simple for your > purpose (I'm not using a gui, for example); in psuedocode: > > from time import time, sleep > > start = time() > for event in music: > duration=len(event) #Really, the length of the event > play(event) > while 1: > timer = time() > remaining = start + duration - timer > if remaining < 0.001: > break > else: > sleep(remaining / 2) > stop(event) > start += duration > > IOW, just check the time, wait half the remaining note duration, check the > time again, etc, till you've reached your desired precision level (in this > case 0.001 sec). The halving of each succesive sleep() means that there is > only a handful of calls to time() per note, 5-10 depending on the tempo. (Of > course it could be any fraction, I just pulled that out of a hat; it would > probably be better too if the fraction decremented as the deadline > approached). > > Even with this naive algorithm, I'm getting accuracy of <0.001 sec > consistently, up to stupidly high tempos like 3000 bpm (as measured by > inserting a "print remaining" in the loop) without using a separate timing > thread or "sync pulse", and with only a few calls. > > Any processes started this way stay in sync, even if individual events are > delayed, because the "start" variable is incremented by the correct (not > actual) duration of the note. (But I guess that's just scheduling, > right? :) ) > > Obviously there is a limit imposed by arithmetical precision, but I've left > things running all day without seeing a discrepancy. > > In terms of audio process communication, I'm using sox in a subprocess to play > samples (and its cheesey synth sound!), and fluidsynth via a socket for midi. > The latter is far superior and seems to handle whatever is thrown at it, and > with the jack driver with realtime priority, the dropouts you mentioned > caused by mouse movements and so on disappear. > > Of course, this doesn't prove that using a socket is better; I don't think sox > is jack-aware, and if the subprocesses could have different priorities from > the parent process, that may help with the difficulties we're having with > them. Anyone out there know about that? > > I've been putting off getting into Csound, but by all accounts it's _the_ > audio language. Good luck with your project, it sounds interesting. > > Regards, > > john Hi John. Very interesting approach, halving the remaining duration. Right now I'm not working with note-offs, Csound takes care of the duration. I just need to be able to call the notes at the right times. I've managed to get all the networking/IPC stuff working, I just need to test the sched.scheduler functioning. If it isn't accurate enough, as some have told me it won't be, I'll have to fall back on using Csound to time the notes; it's a C library, so I think it will be pretty fast. I have nothing but respect and awe for sox. I chose Csound partially because I want the app to work cross-platform. Csound and the Csound API work fine with Jack, but for some reason I got the audio static even connected to Jack with realtime preemption. There are ways for the subprocesses to have different priorities; they inherit the parent's priority, but any later changes made by, e.g., os.nice() only affect the parent. So one could run os.nice(-2), then spawn a subprocess, then run os.nice(4), to leave the child process -2 from the default and the parent process +2. I also like and respect Fluidsynth, but I'm working on a pretty microtonal system, and MIDI doesn't have enough microtonal support. Csound is the shiznet. It's pretty engrossing, though. I've written a fraction of the amount of music I wrote before since I discovered it! -Chuckk From raj.indian.08 at gmail.com Mon Dec 1 10:35:48 2008 From: raj.indian.08 at gmail.com (RajNewbie) Date: Mon, 1 Dec 2008 07:35:48 -0800 (PST) Subject: 11001, 'getaddrinfo failed' : Error in httplib but not in urllib2 References: Message-ID: <0de72923-08b7-4631-a48d-b5249150dd1b@p2g2000prf.googlegroups.com> On Dec 1, 7:43?pm, Tim Golden wrote: > RajNewbie wrote: > > Hi all, > > ? ? I am trying to connect to localhost via httplib, but it fails. > > ? ? To check whether it is a firewall problem etc, I tried to connect > > via urllib2, but it went through fine. > > ? ? ?Could some one help me out on this? I cannot use urllib2 in the > > > program because I have to send files via post to a url, and urllib2 > > doesn't support it (Python2.4) > > > Please see the code below: > > -->HTTPLIB<-- > > h = httplib.HTTPConnection("http://127.0.0.1:8000") > > h.request('GET', "/accounts/") > > res = h.getresponse() > > Which aspect of the documentation: > > http://docs.python.org/library/httplib.html > > leads you to think that the first parameter to > httplib.HTTPConnection should be a URL? > > >>> import httplib > >>> httplib.HTTPConnection ("127.0.0.1") > > >>> httplib.HTTPConnection ("localhost") > > > > > > > > TJG oops. My mistake. I am sorry to post such a braindead question here. I mistook the host for the url here. Sorry. From jason-sage at creativetrax.com Wed Dec 3 13:30:56 2008 From: jason-sage at creativetrax.com (jason-sage at creativetrax.com) Date: Wed, 03 Dec 2008 12:30:56 -0600 Subject: Mathematica 7 compares to other languages In-Reply-To: <673ca33e-9c1e-4c8e-a81d-d46828fe47b1@n10g2000yqm.googlegroups.com> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <673ca33e-9c1e-4c8e-a81d-d46828fe47b1@n10g2000yqm.googlegroups.com> Message-ID: <4936D060.9090004@creativetrax.com> bearophileHUGS at lycos.com wrote: > > So when you need an algorithm, you can often find it already inside, > for example in the large Combinatorics package. So it has WAY more > batteries included, compared to Python. I'd like to see something as > complete as that Combinatorics package in Python. > Sage (http://www.sagemath.org/, based on Python) already has some pretty powerful and comprehensive combinatorics functionality (including lots of things that Mma doesn't have). What's more, one of the most comprehensive combinatorics libraries out there, MuPAD combinat, is currently in the process of switching to Sage (and becoming the Sage-combinat project). See http://wiki.sagemath.org/combinat/. If you are interested in graph theory, then you might be interested in the comparison to the Combinatorica package at http://wiki.sagemath.org/CombinatoricaCompare . This page is a little old, but it gives you an idea of how things compare. Jason From lists at cheimes.de Mon Dec 8 13:55:31 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 08 Dec 2008 19:55:31 +0100 Subject: StringIO in 2.6 and beyond In-Reply-To: References: Message-ID: Bill McClain wrote: > I've just installed 2.6, had been using 2.4. > > This was working for me: > > #! /usr/bin/env python > import StringIO > out = StringIO.StringIO() > print >> out, 'hello' > > I used 2to3, and added import from future to get: > > #! /usr/bin/env python > from __future__ import print_function > import io > out = io.StringIO() > print('hello', file=out) > > ....which gives an error: > > Traceback (most recent call last): > File "./example.py", line 5, in > print('hello', file=out) > File "/usr/local/lib/python2.6/io.py", line 1487, in write > s.__class__.__name__) > TypeError: can't write str to text stream > > ....which has me stumped. Why can't it? In this context 'str' means Python 3.0's str type, which is unicode in 2.x. Please report the misleading error message. Christian From adi at lspl.net Mon Dec 8 05:40:03 2008 From: adi at lspl.net (sniffer) Date: Mon, 8 Dec 2008 02:40:03 -0800 (PST) Subject: infering the number of args a function takes at runtime References: Message-ID: <25dcb5a7-1f31-4ef3-8b07-fb355dfd31e5@p2g2000prf.googlegroups.com> On Dec 8, 9:39?am, sniffer wrote: > hi all, > i am a python newbie, in a project currently doing i need to find out > the number of arguments that a function takes at runtime.? Is this > possible ,if so how do i do this,i ve looked through the python > documentation but couldnt find anything.any help will be great > > TIA Thanks guys , i think this should work for me.btw as enquired i am working o a mvc thingie where in need to call functions in a controller,and pass the arguments as recieved from the end user so i need to make sure that the number of arguments passed from the front end are correct or not in the context of the function being called From fakeaddress at nowhere.org Tue Dec 23 06:36:16 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 23 Dec 2008 03:36:16 -0800 Subject: Very basic question In-Reply-To: <38f6b145-8615-4bcc-88f6-1988f9a7f68f@q30g2000prq.googlegroups.com> References: <21ab1917-f0c9-48fb-baa9-02e5bf229bf5@s9g2000prm.googlegroups.com> <38f6b145-8615-4bcc-88f6-1988f9a7f68f@q30g2000prq.googlegroups.com> Message-ID: Sengly wrote: > I can hack it by doing eval('1.0*12/5') but is there any better method? Where did you get the string? If you generated it, you might as well make one or both the operands float to begin with. If you got it as input, calling eval() on it is a world of security hurt. The right way would be to parse the expression, so you can evaluate it as you wish. Security defects aside, just prepending '1.0 *' doesn't work in general, because the string could be something like '5 + 12 / 5'. If you replace each '/' that isn't immediately followed by another '/' with '* 1.0 /', that might work... or maybe someone fill find counter-examples. Python 3 does what you want. The / operator is float division. The // operator is still integer division. -- --Bryan From prologic at shortcircuit.net.au Mon Dec 29 20:32:35 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 30 Dec 2008 11:32:35 +1000 Subject: get method In-Reply-To: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> Message-ID: On Tue, Dec 30, 2008 at 11:00 AM, Ross wrote: > I am teaching myself Python by going through Allen Downing's "Think > Python." I have come across what should be a simple exercise, but I am > not getting the correct answer. Here's the exercise: > > Given: > > def histogram(s): > d = dict() > for c in s: > if c not in d: > d[c] = 1 > else: > d[c] += 1 > return d > > > Dictionaries have a method called get that takes a key and a default > value. If the key appears in the dictionary, get returns the > corresponding value; otherwise it returns the default value. For > example: > >>>> h = histogram('a') >>>> print h > {'a': 1} >>>> h.get('a', 0) > 1 >>>> h.get('b', 0) > 0 > > Use get to write histogram more concisely. You should be able to > eliminate the if statement. > > Here's my code: > > def histogram(s): > d = dict() > for c in s: > d[c]= d.get(c,0) > return d > > This code returns a dictionary of all the letters to any string s I > give it but each corresponding value is incorrectly the default of 0. > What am I doing wrong? Ross, the others have informed you that you are not actually incrementing the count. I'll assume you've fixed your function now :) ... I want to show you a far simpler way to do this which takes advantage of Python's list comprehensions and mappings (which are really what dictionaries are): >>> s = "James Mills and Danielle Van Sprang" >>> dict([(k, len([x for x in s if x == k])) for k in s]) {'a': 5, ' ': 5, 'e': 3, 'd': 1, 'g': 1, 'i': 2, 'M': 1, 'J': 1, 'm': 1, 'l': 4, 'n': 4, 'p': 1, 's': 2, 'r': 1, 'V': 1, 'S': 1, 'D': 1} >>> Let us know when you get to the "List Comprehension" section - They are very powerful - As as Generators and Generator Expressions. Have fun learning Python, cheers James From roy at panix.com Sat Dec 6 14:15:28 2008 From: roy at panix.com (Roy Smith) Date: Sat, 06 Dec 2008 14:15:28 -0500 Subject: Learning Python now coming from Perl References: <014a96e0$0$20670$c3e8da3@news.astraweb.com> Message-ID: In article <014a96e0$0$20670$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > On Sat, 06 Dec 2008 08:50:20 -0500, Roy Smith wrote: > > > For your first > > project, pick something that's small enough that you think you could > > tackle it in under 50 lines of Perl. > > Is there anything which *can't* be written in under 50 lines of Perl? [...] > Also, Perl REs are faster than Python REs, or so I'm told. Between the > speed and the convenience, Perl programmers tend to use RE's for > everything they can. Python programmers tend to use REs only for problems > that *should* be solved with REs rather than *can* be solved with a RE. Well, as an old-time unix hacker (who learned REs long before Perl existed), my question to you would be, "Is there any problem which *shouldn't* be solved with an RE?" :-) It's easy to go nuts with REs, and create write-only code. On the other hand, they are an extremely powerful tool. If you are wise in the ways of RE-fu, they can not only be the most compact way to write something, but also the most efficient and even the most comprehensible. Unfortunately, REs seem to be regarded as some kind of monster these days and few people take the time to master them fully. Which is a shame. One really nice feature of REs in Python is the VERBOSE flag. It lets you write some way-complicated REs in a way which is still easy for somebody to read and understand. Python's raw strings, and triple-quoted strings, also help reduce the sea of backslashes which often make REs seem much worse than they really are. One of the reasons REs don't get used in Python as much as in Perl is because strings have useful methods like startswith(), endswith(), and split(), and also the "in" operator. These combine to give you easy ways to do many things you might otherwise do with REs. From lists at cheimes.de Tue Dec 9 06:14:22 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 09 Dec 2008 12:14:22 +0100 Subject: python3.0 - any hope it will get faster? In-Reply-To: <6q70udFb5dmqU1@mid.dfncis.de> References: <6q70udFb5dmqU1@mid.dfncis.de> Message-ID: Helmut Jarausch wrote: > I know that processing unicode is inherently slower, > but still I was surprised that it's so much slower. > > Is there any hope Python-3.0 will get faster or > is the main potential for optimizations exhausted, already? > > That's not to start a flame war! > I know computers get faster, we human beings don't (me, at least) Don't worry, it's going to get faster. Our top priority was feature completeness and stability. With the first final version out we are focusing on bug fixes and speed ups. We have a fair bunch of speed patches and ideas in our work queue. For example Mark and Victor are working on long integer optimizations, Alexandre and I are focusing on the new IO library and so on. Some of the speedup will make it into 3.0.1 and future patch releases of the 3.0 series. Larger and more complex chances can be expected for Python 3.1. There are interesting experiments with LLVM and threaded code (not to confuse with multithreading) going on. Gr??e an die andere Seite von Aachen Christian From jay.amorin at gmail.com Thu Dec 4 09:57:48 2008 From: jay.amorin at gmail.com (Jay Jesus Amorin) Date: Thu, 4 Dec 2008 22:57:48 +0800 Subject: python to parse excel file csv format In-Reply-To: <4936ECF7.3040400@wildenhain.de> References: <4936DC35.6010404@mrabarnett.plus.com> <4936ECF7.3040400@wildenhain.de> Message-ID: This is what i have done and its giving me error. #!/usr/bin/env python import csv, sys, os filename = (sys.argv[1]) reader = csv.reader(open(filename, "rb"), delimiter=',', quoting=csv.QUOTE_NONE) try: #for row in reader: for fmodes,fname in reader: os.chmod(fname,fmodes) except csv.Error, e: sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) testserver:~> ./parsecsv.py chown.csv Traceback (most recent call last): File "./promote2prod.py", line 10, in ? os.chmod(fname,fmodes) TypeError: an integer is required Please help I'm a complete newbie to python. Many thanks. Jay On Thu, Dec 4, 2008 at 4:32 AM, Tino Wildenhain wrote: > MRAB wrote: > >> Jay Jesus Amorin wrote: >> >>> This is how i do it, but it runs with error. Kindly help >>> >>> >>> #!/usr/bin/env python >>> >>> import csv, sys, os >>> filename = (sys.argv[1]) >>> reader = csv.reader(open(filename, "rb"), delimiter=',', >>> quoting=csv.QUOTE_NONE) >>> >>> try: >>> for row in reader: >>> os.popen("chown row[0] row[1]") >>> >> This should be: >> >> os.popen("chown %s %s" % (row[0], row[1])) >> >> or: >> >> os.popen("chown %s %s" % tuple(row)) >> > > No, it should really be os.popen(("chown",row[0],row[1])) > or better yet, > > for fmodes,fname in reader: > os.popen(("chown",fmodes,fname)) > > or even plus better: > > for fmodes,fname in reader: > os.chmod(fname,fmodes) > > (Both my examples avoid problems with unquoted filenames) > > Regards > Tino > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Mon Dec 15 10:56:29 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 15 Dec 2008 10:56:29 -0500 Subject: Having Issues with CMD and the 'python' command In-Reply-To: References: Message-ID: On Mon, Dec 15, 2008 at 8:13 AM, wrote: > On Mon, 15 Dec 2008 at 23:01, James Mills wrote: > >> On Mon, Dec 15, 2008 at 10:51 PM, Lamonte Harris >> wrote: >> >>> Every time I start cmd on windows it requires me to "set >>> path=%path%;C:\python26" why? I'm getting annoyed... >>> >> >> "cmd" has _nothing_ to do with Python. >> >> > (Top posting corrected.) > > But the answer is that you need to update your PATH string at the system > level. You do that in Control Panel/System/Advanced/Environment variables > (it's a button on the advanced screen, which is something that confused > me the first time I went looking for it). > > ObPython: you know, it occurs to me that Windows follows exactly the > opposite philosophy from Python when it comes to hierarchy. Python's > Zen is "shallow is better than deep", whereas Windows' philosophy > is "deep is better than shallow". Every release of Windows seems > to bury the things one needs to do to administer the system deeper > and deeper inside a nested set of windows...and every time I touch > Windows I am reminded how sensible the Python Zen is :) > It's not a question of sensibility. It's a question of purpose. The Zen is the philosophy of a language that tries to be easy to learn and easy to use. Python is used by programmers who want to experiment with it, but who usually know enough not to os.system("rm -r /") or anything similar. Windows, on the other hand, wants to hide everything that can potentially ruin the system as deep as possible so that many of the idiots who use that system don't do stupid things like delete the registry, wipe the environment settings, turn off the "Nag Screen" (UAC), and other things of that nature. > --RDM > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Tue Dec 9 13:20:27 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 9 Dec 2008 10:20:27 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> Message-ID: <1ddabaf6-c129-4395-8d81-738e67e6f3ca@q26g2000prq.googlegroups.com> On Dec 9, 7:48?am, Paul Boddie wrote: > On 9 Des, 14:24, Steven D'Aprano > cybersource.com.au> wrote: > > > That is not what Guido said. What he actually said was: > > > "That's possible with sufficiently powerful parser technology, but > > that's not how the Python parser (and most parsers, in my experience) > > treat reserved words." > > I accept that many parsers are operating on predetermined tokens where > keywords will already have been identified as such, regardless of > their eventual syntactic context, by the time the parser gets to see > them. What I wanted to point out was that other approaches are not > exactly unheard of or particularly rare. Every now and again, the > language gets extended and new keywords are sought in an excruciating > process akin to a group writing exercise involving the existing > keywords. A better parsing framework would alleviate these problems. And introduce an assload of new ones. > > What Guido is saying is that even if he agreed with the OP he couldn't > > add that feature. He's not saying that he agrees with the OP. The Zen > > gives good reasons for believing that even if Python's parser was > > sufficiently powerful, he'd still consider the feature undesirable. > > Well, I think it's more interesting to explore the boundaries of what > can be done, to debunk notions that such things aren't being done in > the mainstream, and to examine whether they could benefit usability, > than it is to defer to the Zen of Python as some kind of prescriptive, > near-religious text at every turn. As GvR mentioned in this thread, someone already did that with regard to "parsing frameworks", and the result was PL/1. Seriously, that's not a good thing. To hell with the parser, what is everyone focusing on the parser in this thread? What about the human reader? Do you want the human reader to have to have all kinds of rules to memorize about when a symbol is an identifier and when it's a syntactic element? Do you want people to have to learn when to escape a symbol so that the parser treats it as an identifier instead of syntax? I'm not saying "as" alone was causing that--for once again Python showed what the best way to enter unpleasant waters is: with a lot of restraint--but a "better parsing framework" that eliminated keywords would cause lots of confusion. And finally: it's just plain bad style to use a syntactic element as an identifier, even when allowed. Carl Banks From andyhume at gmail.com Tue Dec 30 11:07:24 2008 From: andyhume at gmail.com (andyhume at gmail.com) Date: Tue, 30 Dec 2008 08:07:24 -0800 (PST) Subject: Parsing Excel spreadsheets Message-ID: <6a54de23-bea4-40c7-ad7c-22c6eba4bd8a@z6g2000pre.googlegroups.com> Hi, Can anybody recommend an approach for loading and parsing Excel spreadsheets in Python. Any well known/recommended libraries for this? The only thing I found in a brief search was http://www.lexicon.net/sjmachin/xlrd.htm, but I'd rather get some more input before going with something I don't know. Thanks, Andy. From sumerc at gmail.com Mon Dec 29 02:56:10 2008 From: sumerc at gmail.com (k3xji) Date: Sun, 28 Dec 2008 23:56:10 -0800 (PST) Subject: Read-Write Lock vs primitive Lock() Message-ID: Hi, I am trying to see on which situations does the Read-Write Lock performs better on primitive Lock() itself. Below is the code I am using to test the performance: import threading import locks import time class mylock(object): def __init__(self): self.__notreading = threading.Event() self.__notwriting = threading.Event() self.__notreading.set() self.__notwriting.set() def acquire_read(self): self.__notreading.clear() self.__notwriting.wait() def acquire_write(self): self.__notreading.wait() self.__notwriting.clear() def release_read(self): self.__notreading.set() def release_write(self): self.__notwriting.set() GLOBAL_VAR = 1 #GLOBAL_LOCK = locks.ReadWriteLock() GLOBAL_LOCK = threading.Lock() #GLOBAL_LOCK = mylock() GLOBAL_LOOP_COUNT = 100000 GLOBAL_READER_COUNT = 1000 GLOBAL_WRITER_COUNT = 1 class wthread(threading.Thread): def run(self): try: #GLOBAL_LOCK.acquireWrite() #GLOBAL_LOCK.acquire_write() GLOBAL_LOCK.acquire() for i in range(GLOBAL_LOOP_COUNT): GLOBAL_VAR = 4 finally: #GLOBAL_LOCK.release_write() GLOBAL_LOCK.release() class rthread(threading.Thread): def run(self): try: #GLOBAL_LOCK.acquireRead() #GLOBAL_LOCK.acquire_read() GLOBAL_LOCK.acquire() for i in range(GLOBAL_LOOP_COUNT): GLOBAL_VAR = 3 finally: #GLOBAL_LOCK.release_read() GLOBAL_LOCK.release() # module executed? if __name__ == "__main__": starttime = time.clock() threads = [] for i in range(GLOBAL_READER_COUNT): rt = rthread() threads.append(rt) for i in range(GLOBAL_WRITER_COUNT): wt = wthread() threads.append(wt) for thread in threads: thread.start() for thread in threads: thread.join() print "All operations took " + str(time.clock() - starttime) + " msecs" What I am doing is: I am creating multiple readers and try to do something. I had assumed that with using primitive Lock() on the above situation, it will create a bottleneck on the rthreads. But the numbers indicate that there are no difference at all. I had implemented my own READ-WRIET lock as can be seen above mylock and also used the one here: code.activestate.com/recipes/502283/. Both have the same numbers: above test with primitive Lock: C:\Python25\mytest>python test_rw.py All operations took 14.4584082614 msecs above test with mylock: C:\Python25\mytest>python test_rw.py All operations took 14.5185156214 msecs abive test with the one in recipe: C:\Python25\mytest>python test_rw.py All operations took 14.4641975447 msecs So, I am confused in which situations Read-Write lock scales better? Thanks, From grante at visi.com Wed Dec 31 11:28:30 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 31 Dec 2008 10:28:30 -0600 Subject: select.select and socket.setblocking References: <495a661d$0$11384$5fc30a8@news.tiscali.it> <495b34d8$0$11387$5fc30a8@news.tiscali.it> Message-ID: On 2008-12-31, Francesco Bochicchio wrote: > Grant Edwards ha scritto: >> On 2008-12-30, Francesco Bochicchio wrote: >> >>> 3. AFAIK (sorry, I feel acronym-ly today ;), there is no difference in >>> select between blocking and non-blocking mode. The difference is in the >>> recv (again, assuming that you use TCP as protocol, that is AF_INET, >>> SOCK_STREAM), which in the blocking case would wait to receive all the >>> bytes that you requested, >> >> No, in blocking mode it will wait to receive _some_ data (1 or >> more bytes). The "requested" amount is strictly an upper >> limit: recv won't return more than the requested number of >> bytes, but it might return less. > > Uhm. In my experience, with TCP protocol recv only returned less than > the required bytes if the remote end disconnects. I've no idea how you got recv() to behave that way, because I've never seen it do that. Take a look at the echo client/server examples at http://docs.python.org/library/socket.html. If recv worked the way you claimed it did, those programs wouldn't work -- they would deadlock. But, that example does work. In that example, the server program calls recv(1024), and yet it returns 12 bytes. The manual page for recv() specifically states that the "len" parameter is a maximum: The maximum amount of data to be received at once is specified by bufsize. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero. Note: For best match with hardware and network realities, the value of bufsize should be a relatively small power of 2, for example, 4096. The Linux man page for recv() also says len is the length of the receive buffer and is an upper limit on the number of bytes to read. Can you post an example program that exhibits the behavior you describe? > [...] > What I usually do, when I cannot block is: > > - use socket in blocking mode > - do a select with a very small timeout and do a recv only if the select > returns with input events > - (with TCP) do a recv for the exact amount of bytes that I expect ( > this mean having a user protocol that carries the message size in the > header, but this is usually the case ). > > This usually worked for me. Yes that will usually (almost always) work. But, IIRC, there are theoretically situraitons where something happens after select returns and before you call recv() that could cause recv() to block. -- Grant Edwards From rocky at panix.com Sun Dec 21 05:07:18 2008 From: rocky at panix.com (R. Bernstein) Date: Sun, 21 Dec 2008 05:07:18 -0500 Subject: linecache vs egg - reading line of a file in an egg References: Message-ID: Robert Kern writes: > R. Bernstein wrote: >> Does linecache work with source in Python eggs? If not, is it >> contemplated that this is going to be fixed or is there something else >> like linecache that currently works? > > linecache works with eggs and other zipped Python source, but it had > to extend the API in order to do so. Some of the debuggers don't use > the extended API. This will be fixed in the next 2.6.x bugfix release, > but not in 2.5.3. Ok. I have committed a change in pydb sources to deal with the 2 and 3 argument linecache.getline interface which should cover Python releases both before and after version 2.5. > > http://bugs.python.org/issue4201 Many thanks! I should have dug deeper myself. For pdb/bdb though isn't there still a problem in reporting the file location? There is that weird "build" name that seems to be stored in func_code.co_filename mentioned in the original post. I just tried patching pdb/bdb along from the current 2.6 svn sources and here is what I see: $ pdb /tmp/lc.py > /tmp/lc.py(1)() -> import tracer (Pdb) s --Call-- > /src/external-vcs/python/build/bdist.linux-i686/egg/tracer.py(6)() The above filename is wrong. It's very possible I did something wrong, so I'd be grateful if someone else double checked. Furthermore, if there is a problem I'm not sure I see how to fix this. I can think of heuristics to tell if module lives an inside an egg, but is there a reliable way? Is there a standard convention for reporting a file location inside of an egg? Thanks again. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco From eric at ericaro.net Fri Dec 19 14:28:12 2008 From: eric at ericaro.net (eric) Date: Fri, 19 Dec 2008 11:28:12 -0800 (PST) Subject: best way to code References: Message-ID: <04476e1e-a077-4abc-9a37-4e27a67ae7cc@v5g2000prm.googlegroups.com> On Dec 19, 6:36?pm, eric wrote: > On Dec 19, 5:35?pm, Peter Otten <__pete... at web.de> wrote: > > > > > eric wrote: > > > hi, > > > > I need to find a "good" design pattern to instanciate, and add > > > specific code all in one. Let me explain it : > > > > I need to define "some" code, better be in a class, something like > > > > class LinkA(object): > > > ? ? def mystuff(self): > > > ? ? ? ? ? > > > > class LinkB(object): > > > ? ? def mystuff(self): > > > ? ? ? ? ? > > > > AND I need an instance of this class > > > { "stuff A": LinkA() > > > ? "stuff B": LinkB() > > > } > > > > This kind of code "would" be fine, I mean, the result effect in memory > > > is fine for me. > > > But I don't like the way I have to > > > 1/ give a useless name to LinkA, linkB (there can be hundreds of names > > > like that) > > > 2/ I have to write it down two times (and that's one time too much) > > > > any ideas ? > > > > something like > > > [ > > > new object(): > > > ? ? def mystuff(self): > > > ? ? ? ? > > > , > > > new object(): > > > ? ? def mystuff(self): > > > ? ? ? ? > > > ] > > > > would be really perfect (but I know it does not work, or at least, I > > > don't know how to make it work) > > > > In fact, I would like to define a class, and an instance in a single > > > statement > > >>> class Register: > > > ... ? ? def __init__(self): > > ... ? ? ? ? ? ? self.items = [] > > ... ? ? def __call__(self, method): > > ... ? ? ? ? ? ? class Link(object): > > ... ? ? ? ? ? ? ? ? ? ? mystuff = method > > ... ? ? ? ? ? ? self.items.append(Link()) > > ...>>> register = Register() > > >>> @register > > > ... def mystuff(self): print "first" > > ...>>> @register > > > ... def mystuff(self): print "second" > > ...>>> for item in register.items: > > > ... ? ? item.mystuff() > > ... > > first > > second > > > Peter > > hi, > > I've tried something like this : > > import inspect > > class Test(object): > ? ? class Inner(object): > ? ? ? ? def mystuff(self): > ? ? ? ? ? ? print "hello stuff" > > ? ? class InnerB(object): > ? ? ? ? def mystuff(self): > ? ? ? ? ? ? print "hello B" > > def filter(member): > ? ? return inspect.isclass(member) and not member==Test.__class__ > d = dict( (name, c()) for name, c in inspect.getmembers(Test, > filter ) ) > print d > > it works too, but I prefer your method > > thanks > > -- > Erichttp://codeslash.blogspot.com Finally here is my 'final' shot: context: when building a glade GUI I wanted to connect 'nicely' signals (I hate coding the same info in several places) here is my main : if __name__=="__main__": pathname = os.path.dirname(sys.argv[0]) startup = os.path.join(pathname, 'pyshow/pyshow.glade') xml = gtk.glade.XML(startup) #'filename.glade') #the stuff starts here m = MainApp() for widget_name, codget in m.items(): codget.set_widget( xml.get_widget(widget_name) ) gtk.main() and here is the 'MainApp' code, based on the question, and finally I get stuck to my second solution import inspect class Controller(dict): def __init__(self): dict.__init__(self) self.update( (name, c()) for name, c in inspect.getmembers (self.__class__, lambda member: inspect.isclass(member) and not member==self.__class__.__class__ ) ) class MainApp(Controller): def __init__(self): Controller.__init__(self) class main_window(codget): def on_destroy(self, widget, modget): print "bye bye" class play(codget): def on_clicked(self, widget, modget): print "you have clicked" the business is hidden in codget ( as COntroller gaDGET), and what's interesting for me, is that every signal handler has a 'modget' ( as in model gadget) that it can use to do the job (part of the MVC pattern) thanks Peter anyway, I didn't use your solution in this specific case, but I loved the solution anyway, and I'm sure that I'll use it one day. From cournape at gmail.com Fri Dec 5 03:36:45 2008 From: cournape at gmail.com (David Cournapeau) Date: Fri, 5 Dec 2008 17:36:45 +0900 Subject: How to distribute C/C++ python extension module on Linux? In-Reply-To: References: Message-ID: <5b8d13220812050036m7637c83p63646ac44170832f@mail.gmail.com> On Fri, Dec 5, 2008 at 5:09 PM, Allen wrote: > I have build an extension module PyRPC.so (why not be libPyRPC.so?). > The PyRPC.so uses API in libRPCPacker.so. > How to distribute the PyRPC.so? The simple answer is you can't. Depending on the distribution, the python interpreter is built differently in an ABI-incompatible way. As on other platforms, the binary also depends on the python version. The only real solution is to package it using the native package manager of the distributions you are interested in supporting (rpm, deb, etc...); you still have to build the package for all different combinations, though. Something like the opensuse build service can help in those situations. > I just put PyRPC.so and libRPCPacker.so in the same folder. > And under this folder, run python. > It tells PyRPC module cannot find a method in libRPCPacker.so. We need more informations on how you built the extension, and about the exact error message. Note also that on Linux, by default, libraries are not looked in the current directory, so it is likely that PyRPC.so does not look in the libRPCPaker.so in your current directory, but from another path (you can check how the loader resolves libraries paths with the command ldd). David From eric at ericaro.net Thu Dec 4 11:15:47 2008 From: eric at ericaro.net (eric) Date: Thu, 4 Dec 2008 08:15:47 -0800 (PST) Subject: simplest way to strip a comment from the end of a line? References: Message-ID: <52e3f2a9-6fb1-42ef-9871-c904ede5520e@t3g2000yqa.googlegroups.com> On Dec 4, 4:50?pm, Joe Strout wrote: > I have lines in a config file which can end with a comment (delimited ? > by # as in Python), but which may also contain string literals ? > (delimited by double quotes). ?A comment delimiter within a string ? > literal doesn't count. ?Is there any easy way to strip off such a ? > comment, or do I need to use a loop to find each # and then count the ? > quotation marks to its left? > > Thanks, > - Joe Hi, if the string literal you wan't to escape, is not escaped (i.e contains \" ) then a regexp like .*?(?:".*?".*?)*#(?P .*?)$ (not tested) .*? everything but keep it greedy ".*?" the string literal not escaped From prologic at shortcircuit.net.au Thu Dec 18 20:33:27 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Dec 2008 11:33:27 +1000 Subject: Which sparse matrix package? In-Reply-To: <20081219014932.7846a547@Schlamber.localdomain> References: <20081218231851.70dd91e2@Schlamber.localdomain> <20081219014932.7846a547@Schlamber.localdomain> Message-ID: On Fri, Dec 19, 2008 at 10:49 AM, wrote: > On Fri, 19 Dec 2008 08:33:28 +1000 > "James Mills" wrote: > >> > The dict that I tried out is of the type: >> > >> > {(1,2,3): "2323", (1,2,545): "2324234", ... } >> > >> > It is too slow for my application when it grows. One slicing >> > operation with list comprehensions takes about 1/2 s on my computer >> > for 1E6 elements. >> >> Let me get this straight. >> It's taking 0.5s to slice your matrix >> of 1E7 (10000000.0 rows/columns) > > My benchmark is as follows: > > 1) Each of the numbers in the 3-tuple is in the range [0, 1E7). > 2) There are 1 000 000 elements in the dict (randomly distributed). > 3) The content string is a random number in the range [0, 1E10) that is > casted into a string. > 4) Measure the time that retrieving all elements in a 10000x100x10 cube > requires. Does a spreadsheet really get this complex ? >> Are you mad ? This is TEN Millions and you >> required it faster than 0.5s ? > > Think about how often a spreadsheet re-calculates cells. > Furthermore, people tend to copy&paste cells. > > I had some small example (Wagner-Whitin algorithm demo) > with hundreds of slicing operations on one screen. I believe that > no-one wants to wait for 1/2 s times 500 == 250 s each time the > spreadsheet is updated. Hmmm From fetchinson at googlemail.com Sat Dec 6 16:51:51 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 6 Dec 2008 13:51:51 -0800 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: >> Hi folks, >> >> The story of the explicit self in method definitions has been >> discussed to death and we all know it will stay. However, Guido >> himself acknowledged that an alternative syntax makes perfect sense >> and having both (old and new) in a future version of python is a >> possibility since it maintains backward compatibility. The alternative >> syntax will be syntactic sugar for the old one. This blog post of his >> is what I'm talking about: >> >> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html >> >> The proposal is to allow this: >> >> class C: >> def self.method( arg ): >> self.value = arg >> return self.value >> >> instead of this: >> >> class C: >> def method( self, arg ): >> self.value = arg >> return self.value >> >> I.e. explicit self stays only the syntax is slightly different and may >> seem attractive to some. As pointed out by Guido classmethods would >> work similarly: >> >> class C: >> @classmethod >> def cls.method( arg ): >> cls.val = arg >> return cls.val >> >> The fact that Guido says, >> >> "Now, I'm not saying that I like this better than the status quo. But >> I like it a lot better than [...] but it has the great advantage that >> it is backward compatible, and can be evolved into a PEP with a >> reference implementation without too much effort." >> >> shows that the proposal is viable. >> >> I'd like this new way of defining methods, what do you guys think? >> Anyone ready for writing a PEP? >> > What's the advantage? If there is not a good reason, I would strongly > opposed polluting the language. Did you read the blog post? The advantage is having a less confusing situation for newbies (confusing the number of arguments to a method call). > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From exarkun at divmod.com Mon Dec 22 10:05:42 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 22 Dec 2008 10:05:42 -0500 Subject: Event Driven programming - Doubts In-Reply-To: <80f360e4-2880-4c66-a6b4-e05d6dbc9031@b41g2000pra.googlegroups.com> Message-ID: <20081222150542.20272.906262414.divmod.quotient.25533@ohm> On Mon, 22 Dec 2008 06:57:55 -0800 (PST), Kottiyath wrote: >Hi, > I have been looking at Twisted and lately Circuits as examples for >event driven programming in Python. > [snip] > > My question is as follows: > I have not understood how the callbacks are hit without (a) >blocking the code or (b) having new threads. There is blocking code - but just in one place. For example, http://twistedmatrix.com/trac/browser/trunk/twisted/internet/selectreactor.py#L93 Jean-Paul From bdesth.quelquechose at free.quelquepart.fr Sun Dec 14 11:29:40 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 14 Dec 2008 17:29:40 +0100 Subject: 1 or 1/0 doesn't raise an exception In-Reply-To: References: <49446E39.6020807@tim.thechases.com> Message-ID: <4945422a$0$1127$426a74cc@news.free.fr> Grant Edwards a ?crit : > On 2008-12-14, Daniel Fetchinson wrote: > >> Let me just point out that unsuspecting people (like me) might rely on >> the whole expression to be evaluated and rely on exceptions being >> raised if needed. > > Short circuit evaluation of booleans is very common (and has > been for decades), so I don't know why people would expect > something else. > Because they either have no previous programming experience, or only experience with one of the few languages that don't do short-circuit evaluation ? You can consider that short-circuit is the norm and it's absence the exception. From n.kottiyath at gmail.com Mon Dec 1 13:20:51 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Mon, 1 Dec 2008 10:20:51 -0800 (PST) Subject: Reg: PIL2.4 Error: AttributeError: pixel_access Message-ID: <61f51748-c53d-4d7a-a9d0-83d3ec8c643e@s9g2000prm.googlegroups.com> Hi all, I am facing the following problem in PIL 2.4: Code: img = ImageGrab.grab() img.save("image2.jpg") Error: img.save("image2.jpg") File "C:\Python24\Lib\site-packages\PIL\Image.py", line 1372, in save self.load() File "C:\Python24\Lib\site-packages\PIL\Image.py", line 599, in load return self.im.pixel_access(self.readonly) AttributeError: pixel_access When I googled this error, I saw that such an error could be because of some botched installation. So, I re-installed PIL. But still this error persists. The version is >>> print Image.VERSION 1.1.6 I had installed PIL in Python2.5 earlier and had done image capture also. But I need to go back to Python2.4 (because pymedia exe is available for only python2.4) and now I am facing this issue. I am pretty new to application programming, so if someone can help me out, it would be very helpful. Regards, Kottiyath From steve at REMOVE-THIS-cybersource.com.au Sun Dec 7 18:44:00 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 23:44:00 GMT Subject: Is 3.0 worth breaking backward compatibility? References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> Message-ID: <014c576d$0$20670$c3e8da3@news.astraweb.com> On Sun, 07 Dec 2008 11:22:23 -0800, walterbyrd wrote: > IMO: breaking backward compatibility is a big deal, and should only be > done when it is seriously needed. > > Also, IMO, most of, if not all, of the changes being made in 3.0 are > debatable, at best. I can not think of anything that is being changed > that was really a "show stopper" anyway. > > At best, I am a casual python user, so it's likely that I am missing > something. To answer your subject line: "Is 3.0 worth breaking backward compatibility?" That depends on what you are doing with Python. Python 3 is the future of Python. "Show stopper" or not, all the new (mis)features in Python 3 are here to stay, and all the (mis)features in Python 2 are on the way out. You can start moving to Python 3 now, or you can do it later, but *eventually* you will have to move. -- Steven From castironpi at gmail.com Mon Dec 29 08:31:17 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 05:31:17 -0800 (PST) Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <40b1b762-459b-4d6f-91f0-0a6e68d233ae@a26g2000prf.googlegroups.com> Message-ID: <4d396242-13c9-4318-97ba-99f18564fbc5@o4g2000pra.googlegroups.com> On Dec 28, 11:56?am, Gerard Flanagan wrote: > On Dec 28, 5:19?pm, Roger wrote: > > > Hi Everyone, > [...] > > When I define a method I always include a return statement out of > > habit even if I don't return anything explicitly: > > > def something(): > > ? ? ? ? # do something > > ? ? ? ? return > > > Is this pythonic or excessive? ?Is this an unnecessary affectation > > that only adds clock ticks to my app and would I be better off > > removing "returns" where nothing is returned or is it common practice > > to have returns. > > It's not particularly excessive but it is uncommon. A nekkid return > can sometimes be essential within a function body, so a non-essential > nekkid return could be considered just noise. One style of coding I heard about once only permits returns at the end of a function. It claims it makes it easier to see the function as a mathematical object. It's a slick idea, but multiple exit points are really practical. Incidentally, generators have multiple entry points. They "yield multiple times, they have more than one entry point and their execution can be suspended" -- http://docs.python.org/reference/expressions.html#yield-expressions The discussion makes me think that 'clear' is subjective, just like 'natural' has 39 definitions. From martin at v.loewis.de Tue Dec 23 15:21:01 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 23 Dec 2008 21:21:01 +0100 Subject: [ANN] Python 2.5.4 (final) Message-ID: <4951482D.8050302@v.loewis.de> On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.5.4 (final). Python 2.5.3 unfortunately contained an incorrect patch that could cause interpreter crashes; the only change in Python 2.5.4 relative to 2.5.4 is the reversal of this patch. 2.5.4 is the last bug fix release of Python 2.5. Future 2.5.x releases will only include security fixes. According to the release notes, about 80 bugs and patches have been addressed since Python 2.5.2, many of them improving the stability of the interpreter, and improving its portability. See the release notes at the website (also available as Misc/NEWS in the source distribution) for details of bugs fixed; most of them prevent interpreter crashes (and now cause proper Python exceptions in cases where the interpreter may have crashed before). For more information on Python 2.5.4, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.5.4 Highlights of the previous major Python releases are available from the Python 2.5 page, at http://www.python.org/2.5/highlights.html Enjoy this release, Martin Martin v. Loewis martin at v.loewis.de Python Release Manager (on behalf of the entire python-dev team) From rt8396 at gmail.com Wed Dec 31 12:23:15 2008 From: rt8396 at gmail.com (r) Date: Wed, 31 Dec 2008 09:23:15 -0800 (PST) Subject: Desktop/File management support on MS Windows References: <4b7188db-63b2-4ac5-80cb-d1326ca3694a@q26g2000prq.googlegroups.com> Message-ID: <613a20bf-6e5a-435e-9a83-36766e12f0ab@k8g2000yqn.googlegroups.com> On Dec 31, 11:08?am, "riklau... at gmail.com" wrote: > Are there any Python libraries that can trash files (move to Trash, > not delete) or for example return a list of applications that can open > given file? I can't find anything related to this for Windows. try pywin32 http://python.net/crew/mhammond/win32/Downloads.html From wuwei23 at gmail.com Mon Dec 1 20:12:27 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 1 Dec 2008 17:12:27 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <4f31c483-8382-480e-8417-b7eef1b1792d@z1g2000yqn.googlegroups.com> <8c856b01-7f0c-4d5b-a1d2-cfe7dc74389f@w3g2000yqc.googlegroups.com> <1680020c-521c-4498-8e74-92e99c03da6b@w35g2000yqm.googlegroups.com> <0d9d2404-cb3f-4390-b97c-79251db8ac95@k8g2000yqn.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> Message-ID: On Dec 2, 6:29?am, r wrote: > In such a society of constant competition, there can be no allies, and > little transparency. The threats to acquisitions of social symbols are > so numerous, varied and frequently incomprehensible, that > defensiveness, as well as competitiveness, becomes a way of life. Any > real sense of community is undermined -- or even destroyed -- to be > replaced by virtual equivalents that strive, unsuccessfully, to > synthesize a sense of community. It can mean also many other things. Right. Like we're going to take lessons in "community" from someone who has done nothing to understand the one he's currently antagonising. > -food for thought- I sincerely hope you choke on it. From alooha at live.co.kr Wed Dec 31 01:02:49 2008 From: alooha at live.co.kr (BON) Date: Tue, 30 Dec 2008 22:02:49 -0800 (PST) Subject: MemoryError when list append... plz help Message-ID: <21227745.post@talk.nabble.com> ====================== s=[] for i in range(11000-1): for j in range(i+1, 11000): .... s.append(((i,j),sim)) ====================== above sim is floating type. s.append is totally coducted 60,494,500 times. but this code raise MemoryError. My computer has 4G RAM. i think it's enough. but it doesn't... So, i've tested below code. ====================== a=[] i=0 while i<60494500 : a.append(i) i+=1 ====================== but this code raise also MemoryError. How can i resolve this problem? please, help... Regards, -- View this message in context: http://www.nabble.com/MemoryError-when-list-append...-plz-help-tp21227745p21227745.html Sent from the Python - python-list mailing list archive at Nabble.com. From renton at 1gb.ru Mon Dec 1 11:37:44 2008 From: renton at 1gb.ru (Alexey Vlasov) Date: Mon, 1 Dec 2008 19:37:44 +0300 Subject: Import of egg packages installed with easy_install Message-ID: <20081201163744.GA9873@l2.in-solve.ru> Hi. There's an already installed with easy_install packet, let's say flup, to the home catalog: $ ls -la ~/python/lib/python2.5/site-packages/ total 176 drwxr-xr-x 3 4096 Nov 29 18:57 . drwxr-xr-x 3 4096 Nov 29 18:51 .. -rw-r--r-- 1 208 Nov 29 18:57 easy-install.pth -rw-r--r-- 1 134573 Nov 29 18:51 flup-1.0.1-py2.5.egg -rw-r--r-- 1 2362 Nov 29 18:51 site.py -rw-r--r-- 1 1853 Nov 29 18:51 site.pyc $ cat ~/python/lib/python2.5/site-packages/easy-install.pth import sys; sys.__plen = len(sys.path) ./flup-1.0.1-py2.5.egg import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sys.path[p:p]=new; sys.__egginsert = p+len(new) $ echo $PYTHONPATH /usr/lib64/portage/pym:/home/username/python/lib64/python2.5/site-packages $ python Python 2.5.2 (r252:60911, Nov 13 2008, 15:01:36) [GCC 4.1.2 (Gentoo 4.1.2 p1.1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import flup No errors. Then I create a simple CGI script: ======== #!/usr/bin/python print "Content-type: text/plain"; print import sys sys.path.insert (0, '/home/username/python/lib64/python2.5/site-packages') print sys.path import flup ======== Browser says: ['/home/username/python/lib64/python2.5/site-packages', '/home/username/http', '/usr/lib64/python25.zip', '/usr/lib64/python2.5', '/usr/lib64/python2.5/plat-linux2', '/usr/lib64/python2.5/lib-tk', '/usr/lib64/python2.5/lib-dynload', '/usr/lib64/python2.5/site-packages'] in error log: [Sat Nov 29 19:41:15 2008] [error] Traceback (most recent call last): [Sat Nov 29 19:41:15 2008] [error] File "path.cgi", line 9, in [Sat Nov 29 19:41:15 2008] [error] import flup [Sat Nov 29 19:41:15 2008] [error] ImportError: No module named flup If you start it with console, you get the same, but there appears also another path: /home/username/python/lib64/python2.5/site-packages/flup-1.0.1-py2.5.egg As I understand it is the problem actually, but I can't get why sys.path doesn't contain this path when I request with HTTP. -- BRGDS. Alexey Vlasov. From jhlj at statsbiblioteket.dk Mon Dec 22 12:59:51 2008 From: jhlj at statsbiblioteket.dk (Jens Henrik Leonhard Jensen) Date: Mon, 22 Dec 2008 18:59:51 +0100 Subject: join a samba domain In-Reply-To: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> References: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> Message-ID: <494fd597$0$90267$14726298@news.sunsite.dk> Toff wrote: > d = c.Win32_ComputerSystem > d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") Shouldn't r"admin\\mydom" be "admin\\mydom" or r"admin\mydom". Or maybe just "admin" /Jens Henrik From lewis.sarah93 at yahoo.com Thu Dec 4 23:44:59 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 20:44:59 -0800 (PST) Subject: Reduce Debt Message-ID: Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From steve at holdenweb.com Mon Dec 15 12:35:36 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 15 Dec 2008 12:35:36 -0500 Subject: %s place holder does not let me insert ' in an sql query with python. In-Reply-To: References: <1229345178.31093.24.camel@krishna-laptop> Message-ID: <49469568.2090203@holdenweb.com> Lamonte Harris wrote: > I had this problem too. If you've upgraded to python 2.6 you need to > use the new sytnax "format > > queryString = "insert into venders > values('{0}','{1}','{2}'".format(field1,field2,field3) > Will all readers of this thread kindly regard this as an example of how *not* to generate and execute SQL queries in Python. Study the cursor.execute() method, and provide parameterized queries and a data tuple instead. Please also note that the above technique explicitly continues to generate SQL syntax errors in Krishnakan's case where the data values themselves contain apostrophes. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From castironpi at gmail.com Wed Dec 17 19:51:03 2008 From: castironpi at gmail.com (Aaron Brady) Date: Wed, 17 Dec 2008 16:51:03 -0800 (PST) Subject: C API and memory allocation References: Message-ID: On Dec 17, 6:42?pm, "Gabriel Genellina" wrote: > En Wed, 17 Dec 2008 21:35:04 -0200, Floris Bruynooghe ? > escribi?: > Yes; but you don't have to dig into the implementation; from ?http://docs.python.org/c-api/arg.html: > > s (string or Unicode object) [const char *] > Convert a Python string or Unicode object to a C pointer to a character ? > string. You must not provide storage for the string itself; a pointer to ? > an existing string is stored into the character pointer variable whose ? > address you pass. > > > But how can python now know how long to keep that buffer object in > > memory for? > > It doesn't - *you* have to ensure that the original string object isn't ? > destroyed (by example, incrementing its reference count as long as you ? > keep the pointer), or copy the string contents into your own buffer. I missed something. How did you get a reference to the original string object, with which to increment its reference count? How do you know its length to copy it into your own buffer? From robert.kern at gmail.com Sat Dec 27 19:37:30 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 27 Dec 2008 19:37:30 -0500 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: Daniel Fetchinson wrote: > I agree that array.array is more efficient than a list but the input > for my function will come from PIL and PIL returns a list. So I have a > list to begin with which will be passed to the C function. With recent versions of PIL, numpy can create an array from an Image very quickly, possibly without any copying of memory. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From gagsl-py2 at yahoo.com.ar Thu Dec 11 13:33:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 11 Dec 2008 16:33:08 -0200 Subject: Deeper tracebacks? References: Message-ID: En Thu, 11 Dec 2008 07:49:42 -0200, R. Bernstein escribi?: > brooklineTom writes: > >> I want my exception handler to report the method that originally >> raised an exception, at the deepest level in the call-tree. Let give >> an example. > extract_stack() without any arguments is getting this from the > *current frame* which as you noted doesn't have the last exception > info included which has been popped; variable sys.last_traceback has the > frames > at the time of the exception, I think. > > So in your code try changing: > aRawStack = traceback.extract_stack() > to > aRawStack = traceback.extract_stack(sys.last_traceback) No, last_traceback is the last *printed* traceback in the interactive interpreter. Use the third element in sys.exc_info() instead: import sys, traceback class SomeClass: def error(self): """Raises an AttributeError exception.""" int(3).zork() def perform_(self, aSelector): try: aMethod = getattr(self, aSelector) answer = aMethod() except AttributeError: tb = sys.exc_info()[2] try: print "Using traceback.print_tb:" traceback.print_tb(tb) print "Using traceback.print_exception:" traceback.print_exception(*sys.exc_info()) print "Using traceback.extract_tb:" print traceback.extract_tb(tb) finally: del tb SomeClass().perform_("error") output: Using traceback.print_tb: File "test_tb.py", line 11, in perform_ answer = aMethod() File "test_tb.py", line 6, in error int(3).zork() Using traceback.print_exception: Traceback (most recent call last): File "test_tb.py", line 11, in perform_ answer = aMethod() File "test_tb.py", line 6, in error int(3).zork() AttributeError: 'int' object has no attribute 'zork' Using traceback.extract_tb: [('test_tb.py', 11, 'perform_', 'answer = aMethod()'), ('test_tb.py', 6, 'error' , 'int(3).zork()')] (The "3-name form of the except clause" that I menctioned previously only exists in my imagination :) ) -- Gabriel Genellina From mensanator at aol.com Sat Dec 6 21:09:07 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 6 Dec 2008 18:09:07 -0800 (PST) Subject: "as" keyword woes References: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> <0147dc24$0$20670$c3e8da3@news.astraweb.com> <0148b217$0$20670$c3e8da3@news.astraweb.com> <7d0lj4d9hai2f87r30erc4l1ir85osbfg7@4ax.com> <88579d9a-df52-49b9-a6fe-53c8f4524bf3@j39g2000yqn.googlegroups.com> <70llj41hie2svs68o5efn22i97f649svfh@4ax.com> <1cda9a9a-1641-424b-9f3d-c4e2635efed7@j38g2000yqa.googlegroups.com> <014b0f94$0$20670$c3e8da3@news.astraweb.com> Message-ID: <4469f2ed-f012-400d-9d4f-bd44cd075d0d@w34g2000yqm.googlegroups.com> On Dec 6, 6:25?pm, Steven D'Aprano wrote: > On Sat, 06 Dec 2008 14:36:07 -0800, Mensanator wrote: > > It was extremely simple for me to fix the sympy module where I noticed > > it. I'm not saying it wasn't a problem, I'm saying it wasn't BROKEN. > > If it wasn't broken, why did you need to fix it? If my tire is flat, I have to fix it. But it may just need air, in which case it's not broken. > > "Broken" means "not working", not "unfixable". So, you're saying that Python is broken and will remain so forever, since "as" will remain a keyword? Are you advocating that we all switch to Ruby? > > -- > Steven From mail at timgolden.me.uk Mon Dec 1 09:43:07 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 01 Dec 2008 14:43:07 +0000 Subject: 11001, 'getaddrinfo failed' : Error in httplib but not in urllib2 In-Reply-To: References: Message-ID: <4933F7FB.2010204@timgolden.me.uk> RajNewbie wrote: > Hi all, > I am trying to connect to localhost via httplib, but it fails. > To check whether it is a firewall problem etc, I tried to connect > via urllib2, but it went through fine. Could some one help me out on this? I cannot use urllib2 in the > program because I have to send files via post to a url, and urllib2 > doesn't support it (Python2.4) > > Please see the code below: > -->HTTPLIB<-- > h = httplib.HTTPConnection("http://127.0.0.1:8000") > h.request('GET', "/accounts/") > res = h.getresponse() Which aspect of the documentation: http://docs.python.org/library/httplib.html leads you to think that the first parameter to httplib.HTTPConnection should be a URL? >>> import httplib >>> httplib.HTTPConnection ("127.0.0.1") >>> httplib.HTTPConnection ("localhost") >>> TJG From rcdailey at gmail.com Tue Dec 9 10:20:43 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 9 Dec 2008 07:20:43 -0800 (PST) Subject: RuntimeError: dictionary changed size during iteration References: <274eb282-1635-40ca-95af-b82271c57802@v4g2000yqa.googlegroups.com> <8c67c6b0-50f7-40ae-93e4-09edd07d6946@r36g2000prf.googlegroups.com> Message-ID: On Dec 8, 10:27?pm, John Machin wrote: > On Dec 9, 3:00?pm, Steven D'Aprano > > > > wrote: > > On Mon, 08 Dec 2008 19:10:00 -0800, Robert Dailey wrote: > > > On Dec 8, 6:26?pm, Terry Reedy wrote: > > >> Robert Dailey wrote: > > >> > stuff = vars() > > > >> ?>>> vars() is globals() > > >> True > > > >> > for key in stuff: > > > >> You just changed globals, which is aliased as stuff. Stuff changes. > > > >> > ? ? print( key, '--', stuff[key] ) > > > >> > I get the following error message: > > >> > ('CopyEmotionFX', '--', ) > > >> > Traceback (most recent call last): > > >> > ? File "C:\IT\work\jewett\depends.py", line 12, in > > >> > ? ? for key in stuff: > > >> > RuntimeError: dictionary changed size during iteration > > > >> > Why is this happening? > > > > How am I changing globals()? I'm simply iterating the keys in the dict. > > > Can someone explain what is going on please? > > > You create an new name "key": > > > for key in stuff > > > I suppose you could do this: > > > key = None > > stuff = vars() > > for key in stuff: > > but both 'key' and 'stuff' will appear in the dict, possibly causing > confusion; another reason why > > > even better would be: > > > for key in vars().copy(): > > > because that protects you from cases where globals() change inside the > > for loop. > > When I do: for key in stuff.keys(): It works! I wonder why .keys() makes a difference. It is using a 'view', which is a new concept in Python 3.0 that I'm not totally familiar with yet. From paul.hermeneutic at gmail.com Thu Dec 4 16:01:26 2008 From: paul.hermeneutic at gmail.com (Paul Watson) Date: Thu, 04 Dec 2008 15:01:26 -0600 Subject: Running Python 2 and Python 3 on the same machine Message-ID: <1228424486.5873.6.camel@linux-3eb6.site> The migration strategy detailed in PEP 3000 using 2to3 is quite nice. However, I am looking for suggestions for migrating to 3 while I still have code that requires 2. Since the source code is incompatible, I was expecting the Python executable to have a new name such as 'python3' or for the default source code filename to change to '.py3' or something. Yes, I have searched some on the web and the newsgroup, so please don't beat me up if this is well known. Thanks. From exarkun at divmod.com Thu Dec 4 17:32:30 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 4 Dec 2008 17:32:30 -0500 Subject: Checking if an int fits in 32 bits? In-Reply-To: Message-ID: <20081204223230.20272.353777632.divmod.quotient.15783@ohm> On Thu, 4 Dec 2008 12:11:08 -0800 (PST), Roy Smith wrote: >I'm working with marshaling data over a binary wire protocol. I'm >using struct.pack() to handle the low-level encoding of ints. One of >the things I need to do is make sure an int can be represented in 4 >bytes. Is there a portable way to do that? For now, I'm doing signed >ints, but I'll certainly have to do unsigned 32-bit ints (and 64-bit >ints) at some point. Not to mention shorts and chars. > >At first I thought pack() might raise an exception on a value >overflow, that but doesn't seem to be the case: > >>>> [hex(ord(c)) for c in struct.pack('!i', 999999999999999999999L)] >['0xde', '0x9f', '0xff', '0xff'] > >Should I be thinking more along the lines of bit masking (and worrying >about all the niggling 2-complement issues) in the Python code? Or is >there some cleaner way to do this? How about simple bounds checking? An integer fits in an unsigned 32bit representation if it is greater than or equal to 0 and less than 2 ** 32. The bounds for the sizes are similarly simple to determine and check. Jean-Paul From walterbyrd at iname.com Wed Dec 17 13:31:57 2008 From: walterbyrd at iname.com (walterbyrd) Date: Wed, 17 Dec 2008 10:31:57 -0800 (PST) Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> Message-ID: On Dec 17, 10:17?am, "Richard Brodie" wrote: > Not really, self is a formal parameter to the function. It would be > a strange language where a function's own arguments weren't in scope. Thank you, that makes sense to me. From sjmachin at lexicon.net Fri Dec 19 18:38:26 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 19 Dec 2008 15:38:26 -0800 (PST) Subject: encoding problem References: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> <6r1m72Ffb5kpU3@mid.uni-berlin.de> <6r2hvjFfb5kpU6@mid.uni-berlin.de> <6r2nfgFfb5kpU7@mid.uni-berlin.de> Message-ID: <2a3d8359-b614-44df-988c-7ebe2187e46d@e1g2000pra.googlegroups.com> On Dec 20, 10:02?am, Marc 'BlackJack' Rintsch wrote: > On Fri, 19 Dec 2008 15:20:08 -0700, Joe Strout wrote: > > Marc 'BlackJack' Rintsch wrote: > > >>> And because strings in Python, unlike in (say) REALbasic, do not know > >>> their encoding -- they're just a string of bytes. ?If they were a > >>> string of bytes PLUS an encoding, then every string would know what it > >>> is, and things like conversion to another encoding, or concatenation > >>> of two strings that may differ in encoding, could be handled > >>> automatically. > > >>> I consider this one of the great shortcomings of Python, but it's > >>> mostly just a temporary inconvenience -- the world is moving to > >>> Unicode, and with Python 3, we won't have to worry about it so much. > > >> I don't see the shortcoming in Python <3.0. ?If you want real strings > >> with characters instead of just a bunch of bytes simply use `unicode` > >> objects instead of `str`. > > > Fair enough -- that certainly is the best policy. ?But working with any > > other encoding (sometimes necessary when interfacing with any other > > software), it's still a bit of a PITA. > > But it has to be. ?There is no automagic guessing possible. > > >> And does REALbasic really use byte strings plus an encoding!? > > > You betcha! ?Works like a dream. > > IMHO a strange design decision. ?A lot more hassle compared to an opaque > unicode string type which uses some internal encoding that makes > operations like getting a character at a given index easy or > concatenating without the need to reencode. In general I quite agree with you ... hoever with Unicode "getting a character at a given index" is fine unless and until you stray (or are dragged!) outside the BMP and you have only a 16-bit Unicode implementation. From steve at holdenweb.com Thu Dec 18 13:09:37 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 18 Dec 2008 13:09:37 -0500 Subject: psycopg2 and large queries In-Reply-To: References: Message-ID: Paul Boddie wrote: [...]> > You really don't want to be traversing large data sets using fetchone, > anyway. My approach (using pyPgSQL) involves fetchmany and then > looping over each batch of results, if I really have to process the > data in Python; most of the time I can do the processing in the > database itself. Hmm, pypgsql doesn't provide a 2.5 Windows installer. I take it you aren't a Windows user ... ? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From jim.hefferon at gmail.com Sat Dec 20 17:37:36 2008 From: jim.hefferon at gmail.com (Jim) Date: Sat, 20 Dec 2008 14:37:36 -0800 (PST) Subject: ANN: New Book: Programming in Python 3 References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <400e99dc-90e2-441a-b7cf-5c2690915682@g38g2000yqd.googlegroups.com> <93e24f4e-a5d6-4952-93ce-f79b192a3666@a29g2000pra.googlegroups.com> Message-ID: I too will be interested in seeing the book. Nothing wrong with Lout -- and you can choose what suits you best, of course -- but just a couple of comments on the alternative. On Dec 19, 5:21 pm, Mark Summerfield wrote: : > - I can't draw but I can tell lout to draw for me and that works well > for my simple needs There are very competent and widely used packages to draw in LaTeX. Two are PSTricks and TikZ (you can google them each). > - embedding graphics (e.g., screenshots) is easy (just convert to EPS) Similarly for LaTeX. > - lout lets me specify Type1 fonts so I can easily use my own custom > Venus font for code & it is easy to embed it which makes publication > easier Current distributions of LaTeX contain XeLaTeX which allows you to use any T1 font that you have (to use it in mathematical text you need to do more, but I don't expect that you have a lot of mathematical text in your book). > - lots of books that use LaTeX have a certain sameness & I don't like > the computer modern fonts (IMO -- no offence intended) There are many alternative document styles and fonts available. > - after more than a decade of using lout I can pretty well get it to > do anything & everything I want (but I don't claim to be an expert > user) Fair enough. Jim From wolfgang.lipp at gmail.com Wed Dec 10 17:53:12 2008 From: wolfgang.lipp at gmail.com (_wolf) Date: Wed, 10 Dec 2008 14:53:12 -0800 (PST) Subject: forcing future re-import from with an imported module References: <533670ae-6d9d-4b10-9156-e41b31b678c7@g17g2000prg.googlegroups.com> Message-ID: On Dec 10, 1:46 pm, "Gabriel Genellina" wrote: > En Tue, 09 Dec 2008 23:27:10 -0200, _wolf > escribi?: > > > how can i say, approximately, "re-import the present module when it is > > imported the next time, don?t use the cache" in a simple way? i do not > > want to "reload" the module, that doesn?t help. > > I'd say you're using modules the wrong way then. The code inside a module > is executed *once*, and that's by design. If you want to execute something > more than once, put that code inside a function, and call it as many times > as you want. > > -- > Gabriel Genellina thanks for your answer. i am aware that imports are not designed to have side-effects, but this is exactly what i want: to trigger an action with `import foo`. you get foo, and doing this can have a side- effect for the module, in roughly the way that a `from __future__ import with_statement` changes the interpretation of the current module (of course, i do not intend to effect syntactic changes---my idea is to look into the module namespace and modify it). think of it as ?metamodule programming? (? la metaclass programming). maybe import hooks are the way to go? somtimes it would be good if there was a signalling system that broadcasts all kinds of system state change. cheers & ~flow ok so the question is: how to make it so each import of a given module has a side-effect, even repeated imports? From clp at rebertia.com Sun Dec 21 02:32:14 2008 From: clp at rebertia.com (Chris Rebert) Date: Sat, 20 Dec 2008 23:32:14 -0800 Subject: trapping all method calls in a class... In-Reply-To: <19ac19520812202312q71409182kb58a0f7aaf3b0e74@mail.gmail.com> References: <19ac19520812202312q71409182kb58a0f7aaf3b0e74@mail.gmail.com> Message-ID: <47c890dc0812202332n8be3837v2b1252416e60d334@mail.gmail.com> On Sat, Dec 20, 2008 at 11:12 PM, Piyush Anonymous wrote: > hi, > i need to trap all method calls in a class in order to update a counter > which is increased whenever a method is called and decreased whenever method > returns. in order to that i am trying to write a decorator for all the > methods. > > see the code here with error. > ------- > http://codepad.org/2w7JVvDB > ---- > any suggestions? any other better way of doing it? I call unnecessary use of metaclasses! Here's my (untested) attempt at a simpler class decorator approach: def decorate_meths(klass): attrs = klass.__dict__.items() for name, val in attrs: if callable(val): klass.__dict__[name] = decorate(val) def decorate(method): #should be called for every method call in the class def decorated(self, *args, **kwds): print "2 Inside __call__()" returnval = method(self, *args,**kwds) print "3 After self.f(*args)" return returnval return decorated #@decorate_meths <-- this syntax requires a later Python version class Person(object): def testprint(self,val): print "blah blah" Person = decorate_meths(Person) #rest of code after the class definition would be the same Sidenotes about your code: - `args` and `kwds` are the conventional names for the * and ** special arguments - the `methodname` variable was actually getting method objects, not strings, as its values; this was probably part of the bug in your program Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From noZ.spamZ at ZZ.ZsvpZ.com Mon Dec 15 10:13:20 2008 From: noZ.spamZ at ZZ.ZsvpZ.com (Michel Claveau - NoSpam SVP ; merci) Date: Mon, 15 Dec 2008 16:13:20 +0100 Subject: Problem Python 2.6.1 vs 2.6 & pyWin32 Message-ID: <4946754f$0$19000$426a74cc@news.free.fr> Hi, all! I have several softwares using Python+PyWin32, often as COM?server. Ok with Python 2.5.x. I want migrate to Python 2.6. But when I install python-2.6.1.msi + pywin32-212.win32-py2.6, my softs don't run. Tried on five machines (two XP & three Vista). But... if I install python-2.6.msi , IT'S OK!!! And, if I installl 2.6.1 once again, after 2.6, ... don't run ???!!! ;-((( In reality, soft run, but COM server can not be used. I get these messages : File "C:\Python26\Lib\site-packages\win32com\server\policy.py", line 728, in resolve_func module = _import_module(mname) File "C:\Python26\Lib\site-packages\win32com\server\policy.py", line 747, in _import_module __import__(mname) File "C:\Ponx\ponx.py", line 54, in import socket File "C:\Python26\lib\socket.py", line 46, in import _socket : DLL load failed: Le module sp?cifi? est introuvable. "Erreur non sp?cifi?e" (with call from JScript test, or VBScript test). (These tests run OK with 2.6 or 2.5.x) I am very disappointed. Help me, please. Thanks in advance. *** and sorry for my bad english *** @-salutations -- Michel Claveau From clp at rebertia.com Wed Dec 17 16:04:34 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 17 Dec 2008 13:04:34 -0800 Subject: something else instead of PIL? In-Reply-To: References: Message-ID: <47c890dc0812171304u4bfd1d9eq2f55b2681e7302e4@mail.gmail.com> On Wed, Dec 17, 2008 at 12:48 PM, Reimar Bauer wrote: > Hi > > what has happened to PIL? No updates since two years. The Python Imaging Library is still current; I guess they just haven't found any new bugs or seen fit to add new functionality in a while, though I presume they'll start working on a Python 3.0 port eventually. If you don't like PIL, there's always the (much less popular) Python bindings to ImageMagick: http://www.imagemagick.org/script/api.php#python Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From mirnazim at gmail.com Sun Dec 21 01:49:29 2008 From: mirnazim at gmail.com (Mir Nazim) Date: Sat, 20 Dec 2008 22:49:29 -0800 (PST) Subject: Question: Evaluate an string variable's value to a variable Message-ID: <4be6e91b-9fcf-4c22-bfe8-fad73190f87c@b41g2000pra.googlegroups.com> Just a quick question. For example I have >>> class X >>> ....pass Then I do >>> x = X() >>> x.name = 'Nazim Now my question is whether something like below is possible and how >>> y = 'name' >>> print x.y # How can x.y can be evaluated to x.name PS: In PHP this can be done by a $x->$y. I sure there is some way in Python also Thanks in advance. From lists at cheimes.de Thu Dec 11 16:57:39 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 11 Dec 2008 22:57:39 +0100 Subject: Best way of debigging a C extension In-Reply-To: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> References: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> Message-ID: <49418CD3.6080509@cheimes.de> Paul Moore wrote: > I have gdb (although I've hardly used it, but I can learn :-)) but if > I try building my extension with python setup.py build --debug, I get > an error because -lpython25_d does not exist. I'm not surprised by > this, as I don't have a debug build of Python - but that should be OK, > I'm only looking for debugging info from my code. You have to build Python on your own to get debug builds. Only debug builds allow to do extension debugging like memory leak finding. > I tried copying libpython25.a to libpython25_d.a - my extension now > builds, but the resulting pyd is XXX_d.pyd, which won't import. If I > rename this to XXX.pyd, I can import and things seem to work - but it > seems a bit of a roundabout way of doing things. Is there a simpler > way that I've missed? It seems to me that this (debugging a C > extension without compiling a debug build of Python) would be a fairly > common situation, so I would have expected a "cleaner" way of doing > it. You are working against the system ;) On Windows all extensions and shared libraries of a debug build have a _d suffix. > At the very least, a documentation patch to explain the best way of > doing things might be useful. I'll see what I can put together based > on the responses I get here. http://svn.python.org/view/python/branches/release25-maint/PCbuild/readme.txt?rev=51333&view=auto Christian From ed at leafe.com Wed Dec 3 22:29:41 2008 From: ed at leafe.com (Ed Leafe) Date: Wed, 3 Dec 2008 21:29:41 -0600 Subject: RELEASED Python 3.0 final In-Reply-To: References: Message-ID: <20739B1C-8B6F-4A7A-B699-76DD938DA2E3@leafe.com> On Dec 3, 2008, at 7:51 PM, Barry Warsaw wrote: > On behalf of the Python development team and the Python community, I > am happy to announce the release of Python 3.0 final. Props to all the folks whose hard work made this possible! You guys rock! -- Ed Leafe From prologic at shortcircuit.net.au Sun Dec 14 18:10:26 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 15 Dec 2008 09:10:26 +1000 Subject: Python 3.0 crashes displaying Unicode at interactive prompt In-Reply-To: <3fad7e29-c9ac-4b2e-aabe-e23a4cc5cb2c@q30g2000prq.googlegroups.com> References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> <3fad7e29-c9ac-4b2e-aabe-e23a4cc5cb2c@q30g2000prq.googlegroups.com> Message-ID: On Mon, Dec 15, 2008 at 9:03 AM, Fuzzyman wrote: > It seems to me to be a generally accepted term when an application > stops due to an unhandled error to say that it crashed. it == application Yes. -------------------- #!/usr/bin/env python from traceback import format_exc def foo(): print "Hello World!" def main(): try: foo() except Exception, error: print "ERROR: %s" % error print format_exc() if __name__ == "__main__": main() -------------------- --JamesMills From aleksandr.goretoy at gmail.com Tue Dec 30 22:39:23 2008 From: aleksandr.goretoy at gmail.com (alex goretoy) Date: Wed, 31 Dec 2008 03:39:23 +0000 Subject: pycurl urllib fallback Message-ID: Hello All, I have this class I like to call pcrunchly. That works to do all my request via libcurl library. What I want to do is add capability for this class to fallback to urllib if pycurl module is not install or is not importable for some reason. I'm posting my whole class. Use it however you want, just please help me to make it better. As you can see from the code I've already started to add this functionality. I found some code on Google that I'm trying to combine with my class, so that it can achieve this task. I want to ask the reader of this thread. Is this a good conservative thing to do. Will this make my class to bulky. Is this something I want? or do I want something else? Is there a better way to achieve this perhaps? I would appreciate any comments on this matter. I would like this class to be able to handle any protocol you throw at it. So as to make it other apps that need to use a different protocol and stuff. Please notice the first huge comment. That is what I'm currently combining into my working pycurl class. Is this good? Oh yeah, please don't mind all those self.soc functions calls. They print things in color to my terminal for me. #!/usr/bin/env python from ctypes import * import os, sys, types, urllib, urllib2, urlparse import stdout_colours #1. #!/usr/bin/env python #2. # -*- coding: UTF-8 -*- #3. #4. import cookielib #5. import urllib #6. import urllib2 #7. #8. cj = cookielib.CookieJar() #9. opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(c j)) #10. resp = opener.open('http://www.amm.com/login.asp') # save a cookie #11. #12. theurl = 'http://www.amm.com/login.asp' #13. # an example url that sets a cookie, try different urls here and see the cookie collection you can make ! #14. body={'username':'AMMT54590570','password':'AMMT32 564288'} #15. txdata = urllib.urlencode(body) #16. # if we were making a POST type request, we could encode a dictionary of values here - using urllib.urlencode #17. txheaders = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'} #18. # fake a user agent, some websites (like google) don't like automated exploration #19. #20. #21. try: #22. req = urllib2.Request(theurl, txdata, txheaders) # create a request object #23. handle = opener.open(req) # and open it to return a handle on the url #24. HTMLSource = handle.read() #25. f = file('test.html', 'w') #26. f.write(HTMLSource) #27. f.close() #28. #29. except IOError, e: #30. print 'We failed to open "%s".' % theurl #31. if hasattr(e, 'code'): #32. print 'We failed with error code - %s.' % e.code #33. elif hasattr(e, 'reason'): #34. print "The error object has the following 'reason' attribute :", e.reason #35. print "This usually means the server doesn't exist, is down, or we don't have an internet connection." #36. sys.exit() #37. #38. else: #39. print 'Here are the headers of the page :' #40. print handle.info() # handle.read() returns the page, handle.geturl() returns the true url of the page fetched (in case urlopen has followed any redirects, which it sometimes does) class curl(object): "Encapsulate user operations on CGIs through curl." def __init__(self, base_url=""): self.func_me_color="white_on_black" self.soc=stdout_colours.stdout_colors() self.soc.me_him(['ENTER:',__name__],self.func_me_color) # These members might be set. self.base_url = base_url self.verbose = 0 self.response = "" self.PYCURL=None try: import pycurl self.PYCURL = True except ImportError,e: import cookielib import urllib import urllib2 self.PYCURL = False #print "\ntrouble with importing pycurl %s\n" % e #sys.exit(1) # Nothing past here should be modified by the caller. if self.PYCURL: self.curlobj = pycurl.Curl() # Verify that we've got the right site... #self.curlobj.setopt(pycurl.SSL_VERIFYHOST, 2) # Follow redirects in case it wants to take us to a CGI... self.curlobj.setopt(pycurl.FOLLOWLOCATION, 1) #self.curlobj.setopt(pycurl.MAXREDIRS, 15) # Setting this option with even a nonexistent file makes libcurl # handle cookie capture and playback automatically. self.curlobj.setopt(pycurl.COOKIEFILE, "/dev/null") # Set timeouts to avoid hanging too long self.curlobj.setopt(pycurl.CONNECTTIMEOUT, 60) self.curlobj.setopt(pycurl.TIMEOUT, 600) #self.set_verbosity(self.verbose) # Set up a callback to capture else: self.cj=cookielib.CookieJar() print "\nurllib:\n" def response_callback(x): self.soc.me_him(['ENTER:',__name__],self.func_me_color) if self.PYCURL: self.response += x self.curlobj.setopt(pycurl.WRITEFUNCTION, response_callback) self.soc.me_him(['EXIT:',__name__],self.func_me_color) def set_verbosity(self, level): "Set verbosity to 1 to see transactions." self.soc.me_him(['ENTER:',__name__],self.func_me_color) if self.PYCURL: self.verbose=int(level) self.curlobj.setopt(pycurl.VERBOSE, self.verbose) self.soc.me_him(['EXIT:',__name__],self.func_me_color) def get(self, cgi, params=""): "Ship a GET request to a specified CGI, capture the response body." self.soc.me_him(['ENTER:',__name__],self.func_me_color) if self.PYCURL: if params: cgi += "?" + urllib.urlencode(params) self.curlobj.setopt(pycurl.URL, os.path.join(self.base_url, cgi)) self.curlobj.setopt(pycurl.HTTPGET, 1) self.response = "" self.curlobj.perform() # if self.verbose > 0: # print self.response self.soc.me_him(['EXIT:',__name__],self.func_me_color) def post(self, cgi, params): "Ship a POST request to a specified CGI, capture the response body.." self.soc.me_him(['ENTER:',__name__],self.func_me_color) if self.PYCURL: self.curlobj.setopt(pycurl.URL, os.path.join(self.base_url, cgi)) self.curlobj.setopt(pycurl.POST, 1) self.curlobj.setopt(pycurl.POSTFIELDS, urllib.urlencode(params)) self.response = "" self.curlobj.perform() # if self.verbose>0: # print self.response self.soc.me_him(['EXIT:',__name__],self.func_me_color) def upload(self, cgi, file_name, file): "POST file from localhost to location/cgi." self.soc.me_him(['ENTER:',__name__],self.func_me_color) if self.PYCURL: self.curlobj.setopt(pycurl.URL, os.path.join(self.base_url, cgi)) self.curlobj.setopt(pycurl.HTTPPOST,[(file_name, (pycurl.FORM_FILE,file))]) self.response = "" self.curlobj.perform() if self.verbose>0: print self.response self.soc.me_him(['EXIT:',__name__],self.func_me_color) # -------------------------------- # DJANGO RECEIVE TEST APPLICATION # -------------------------------- # --------- urls.py ---------------- #from django.conf.urls.defaults import * #urlpatterns = patterns('', #(r'^receive/$', 'web.views.receive'), #) # --------- web\views.py ---------------- #def receive(request): #assert request.method=="POST" #print "receive.META.SERVER_PORT", request.META["SERVER_PORT"], request.POST #files = [] #for multipart_name in request.FILES.keys(): #multipart_obj = request.FILES[multipart_name] #content_type = multipart_obj['content-type'] #filename = multipart_obj['filename'] #content = multipart_obj['content'] #files.append((filename, content_type, content)) #import datetime # write file to the system - add timestamp in the name #file("c:\\tmp\\%s_%s" % (datetime.datetime.now().isoformat().replace(":", "-"), filename), "wb").write(content) #fnames = ",".join([fname for fname, ct, c in files]) #return HttpResponse("me-%s-RECEIVE-OK[POST=%s,files=%s]" % (request.META["SERVER_PORT"], request.POST.values(), fnames )) def answered(self, check): "Does a given check string occur in the response?" self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.soc.me_him(['RETURN:',__name__],self.func_me_color) if self.PYCURL: return self.response.find(check) >= 0 def close(self): "Close a session, freeing resources." self.soc.me_him(['ENTER:',__name__],self.func_me_color) if self.PYCURL: self.curlobj.close() self.soc.me_him(['EXIT:',__name__],self.func_me_color) class session(curl): def login(self, cgisite,username, password): """login - cgi="login.php",params=(("username",name),("password",pass),("foo","bar")) """ self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.post(cgisite, (("username",username), ("password",password))) self.soc.me_him(['EXIT:',__name__],self.func_me_color) def logout(self, cgisite): """logout - cgi="logout.php" """ self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.get(cgisite) self.soc.me_him(['EXIT:',__name__],self.func_me_color) if __name__ == "__main__": if len(sys.argv) < 3: print "Usage: %s \"schema://site/cgi\" \"username\" \"password\"" % sys.argv[0] site=sys.argv[1] username=sys.argv[2] password=sys.argv[3] sess=session("") sess.set_verbosity(1) sess.login(site,username,password) a="" for i in range(len(password)): a+="*" print "YOU ARE LOGGED IN!",site,username,a sess.logout() sess.close() -- ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? -------------- next part -------------- An HTML attachment was scrubbed... URL: From denisbz at t-online.de Mon Dec 22 12:29:36 2008 From: denisbz at t-online.de (denisbz at t-online.de) Date: Mon, 22 Dec 2008 09:29:36 -0800 (PST) Subject: stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> <015612ac$0$20639$c3e8da3@news.astraweb.com> <52cfb77e-4baf-4fba-8eac-cc6c7ddb5be5@k1g2000prb.googlegroups.com> <5504f9ac0812150828m14f6999ak6112c5975042dc88@mail.gmail.com> <1ffd301f-16d3-4dc7-988c-7741d658ca10@z28g2000prd.googlegroups.com> Message-ID: On Dec 15, 10:00?pm, "cmdrrickhun... at yaho.com" wrote: > It can be proven that you cannot sort an arbitrarily large set of > numbers, given no extra information, faster than O(n log n). Cormen Leiserson and Rivest, "Algorithms", have a short clear chapter on "Sorting in linear time": " ... counting sort, radix sort and bucket sort ... use operations other than comparisons. Consequently, the Omega( n lg n ) lower bound does not apply to them." Some of the book is in books.google.com; enjoy From rNOSPAMon at flownet.com Sun Dec 28 03:22:49 2008 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sun, 28 Dec 2008 00:22:49 -0800 Subject: Need help getting MoinMoin to run under WSGI References: Message-ID: In article , Ron Garret wrote: > I successfully installed MoinMoin as a CGI according to the instructions > on the moinmo.in site. But when I tried to switch over to running it > under wsgi it failed thusly: > > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] Traceback (most > recent call last): > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] File > "/www/wikis/genesisgroup/moin.wsgi", line 49, in ? > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] from > MoinMoin.server.server_wsgi import WsgiConfig, moinmoinApp > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] ImportError: No > module named MoinMoin.server.server_wsgi > > The problem, I believe, is that I have both Python 2.4 and 2.5 installed > (it's a Debian box) and MM is installed under 2.5 but WSGI is using 2.4. > I tried to fix this by setting WSGIPythonHome but to no avail. I can't > figure out what to set it to. The instructions say: > > "the WSGIPythonHome directive should be used to specify the exact > location of the Python installation corresponding to the version of > Python compiled against" > > I have two problems with this. First, I didn't compile mod_wsgi, I got > it pre-built as a Debian module. Second, what does "the exact location > of the Python installation" even mean? Python2.5 is spread out in at > least three different places: /usr/local/bin, /usr/lib/python2.5, and > /usr/local/lib/python2.5. I've tried setting WSGIPythonHome to all of > those (and a few other things as well) and nothing worked. > > Also, "the version of Python compiled against" seems very odd. What > does that mean? Surely I don't have to recompile mod_wsgi every time I > change to a new version of Python? > > Help! Thanks! > > rg So never mind, I figured it out. I did indeed have to recompile mod_wsgi from source to get it to use Python 2.5. (That turned out to be a major hassle. I had to do it twice. The first time through it made Apache dump core. I still don't know why.) Seems to be working now though. rg From gandalf at shopzeus.com Tue Dec 30 08:54:45 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 30 Dec 2008 14:54:45 +0100 Subject: Python list's mail server in DNSBL ? Message-ID: <495A2825.4070000@shopzeus.com> I got this message when I tried to send something to this list, through my ISP's SMTP server: This Message was undeliverable due to the following reason: Each of the following recipients was rejected by a remote mail server. The reasons given by the server are included to help you determine why each recipient was rejected. Recipient: Reason: 5.7.1 : Recipient address rejected: policyd-weight Mail appears to be spam or forged. Ask your Mail-/DNS-Administrator to correct HELO and DNS MX settings and to get removed from DNSBLs; in bogusmx.rfc-ignorant.org Please reply to if you feel this message to be in error. Reporting-MTA: dns; viefep19.chello.at Arrival-Date: Tue, 30 Dec 2008 14:12:36 +0100 Received-From-MTA: dns; edge04.upc.biz (192.168.13.239) Final-Recipient: RFC822; Action: failed Status: 5.1.1 Remote-MTA: dns; mail.python.org (194.109.207.14) Diagnostic-Code: smtp; 550 5.7.1 : Recipient address rejected: policyd-weight Mail appears to be spam or forged. Ask your Mail-/DNS-Administrator to correct HELO and DNS MX settings and to get removed from DNSBLs; in bogusmx.rfc-ignorant.org Is python.org really blacklisted? Any admin please, try to remove it. Thanks Laszlo From clp at rebertia.com Mon Dec 15 15:03:14 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 15 Dec 2008 12:03:14 -0800 Subject: tricky nested list unpacking problem In-Reply-To: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> References: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> Message-ID: <47c890dc0812151203m7931ec0eif71b2ca8451465aa@mail.gmail.com> On Mon, Dec 15, 2008 at 11:06 AM, Reckoner wrote: > Hi, > > I have lists of the following type: > > [1,2,3,[5,6]] > > and I want to produce the following strings from this as > > '0-1-2-3-5' > '0-1-2-3-6' > > That was easy enough. The problem is that these can be nested. For > example: > > [1,2,3,[5,6],[7,8,9]] > > which should produce > > '0-1-2-3-5-7' > '0-1-2-3-5-8' > '0-1-2-3-5-9' > '0-1-2-3-6-7' > '0-1-2-3-6-8' > '0-1-2-3-6-9' > > also, > > [1,2,3,[5,6],7,[9]] > > should produce > > '0-1-2-3-5-7-9' > '0-1-2-3-6-7-9' > > obviously, these are nested loops over the lists. The problem is that > I don't know ahead of time how many lists there are or how deep they > go. In other words, you could have: > > [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]] > > Any help appreciated. I've really been having trouble with this. > > I hope that made sense. You just need a recursive list-flattening function. There are many recipes for these. Here's mine: def flatten(lst): if isinstance(lst, list): result = [] for item in lst: result += flatten(item) return result else: return [lst] >>> flattened = flatten([1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]]) >>> flattened [1, 2, 3, 5, 6, 10, 11, 7, 9, 1, 2, 3, 4, 5] >>> '-'.join(str(num) for num in flattened) '1-2-3-5-6-10-11-7-9-1-2-3-4-5' Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From bdesth.quelquechose at free.quelquepart.fr Sun Dec 7 13:23:57 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 07 Dec 2008 19:23:57 +0100 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: <493c2276$0$9254$426a34cc@news.free.fr> Daniel Fetchinson a ?crit : >>> Hi folks, >>> >>> The story of the explicit self in method definitions has been >>> discussed to death and we all know it will stay. However, Guido >>> himself acknowledged that an alternative syntax makes perfect sense >>> and having both (old and new) in a future version of python is a >>> possibility since it maintains backward compatibility. The alternative >>> syntax will be syntactic sugar for the old one. This blog post of his >>> is what I'm talking about: >>> >>> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html >>> >>> The proposal is to allow this: >>> >>> class C: >>> def self.method( arg ): >>> self.value = arg >>> return self.value >>> >>> instead of this: >>> >>> class C: >>> def method( self, arg ): >>> self.value = arg >>> return self.value >>> >>> I.e. explicit self stays only the syntax is slightly different and may >>> seem attractive to some. As pointed out by Guido classmethods would >>> work similarly: >>> >>> class C: >>> @classmethod >>> def cls.method( arg ): >>> cls.val = arg >>> return cls.val >>> >>> The fact that Guido says, >>> >>> "Now, I'm not saying that I like this better than the status quo. But >>> I like it a lot better than [...] but it has the great advantage that >>> it is backward compatible, and can be evolved into a PEP with a >>> reference implementation without too much effort." >>> >>> shows that the proposal is viable. >>> >>> I'd like this new way of defining methods, what do you guys think? >>> Anyone ready for writing a PEP? >>> >> What's the advantage? If there is not a good reason, I would strongly >> opposed polluting the language. > > Did you read the blog post? The advantage is having a less confusing > situation for newbies Once again: how is adding "magical" syntax going to reduce confusion ? > (confusing the number of arguments to a method > call). This is only confusing the first time. The correct solution to this problem is IMHO to better document Python's object model, specially how the descriptor protocol turns functions into methods. From lie.1296 at gmail.com Mon Dec 8 07:16:24 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 8 Dec 2008 12:16:24 +0000 (UTC) Subject: infering the number of args a function takes at runtime References: <25dcb5a7-1f31-4ef3-8b07-fb355dfd31e5@p2g2000prf.googlegroups.com> Message-ID: On Mon, 08 Dec 2008 02:40:03 -0800, sniffer wrote: > On Dec 8, 9:39?am, sniffer wrote: >> hi all, >> i am a python newbie, in a project currently doing i need to find out >> the number of arguments that a function takes at runtime.? Is this >> possible ,if so how do i do this,i ve looked through the python >> documentation but couldnt find anything.any help will be great >> >> TIA > > Thanks guys , i think this should work for me.btw as enquired i am > working o a mvc thingie where in need to call functions in a > controller,and pass the arguments as recieved from the end user so i > need to make sure that the number of arguments passed from the front end > are correct or not in the context of the function being called In python, usually you'll just pass the them all and maybe catch errors. def callback(*args, **kargs): try: return func(*args, **kargs) except TypeError: print('An error happened') From gagsl-py2 at yahoo.com.ar Thu Dec 25 15:58:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Dec 2008 18:58:07 -0200 Subject: How to display Chinese in a list retrieved from database via python References: <22be506d-91c2-4727-ace7-2e3382b6d214@g3g2000pre.googlegroups.com> Message-ID: En Thu, 25 Dec 2008 07:27:03 -0200, zxo102 escribi?: > On 12?25?, ??3?35?, "Chris Rebert" wrote: >> On Wed, Dec 24, 2008 at 11:29 PM, zxo102 wrote: >> > Hi, >> > I retrieve some info in Chinese from postgresql and assign it to a >> > variable 'info' defined in javascript of a html page: >> > var info = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce >> > \xc4'] >> > But I want it to be >> > var info = ['??','??','??'] >> > since in html pages (via javascript), the items in chinese out of the >> > former :['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4'] can >> > not be displayed correctly when it is inserted into a html page. If >> > the list is var info = ['??','??','??'] , then everything works >> > fine. >> > > The html code is as follows > > test > > > > But the '??' is '\xd6\xd0\xce\xc4'. When row01 and row02 is called > from somewhere, > '\xd6\xd0\xce\xc4' can not be displayed correctly as '??' in html > environment. You forgot to specify the page encoding, gb2312 presumably. If adding the encoding does not help, I'd say the problem must reside on how you later use row01 and row02 (your html page does not those variables for anything). '??' is the same as '\xd6\xd0\xce\xc4', and both javascript and Python share the same representation for strings (mostly) so this should not be an issue. My PC is unable to display those characters, but I get "true" from this: test -- Gabriel Genellina From pdorange at pas-de-pub-merci.mac.com Mon Dec 22 05:18:00 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Mon, 22 Dec 2008 11:18:00 +0100 Subject: no sign() function ? Message-ID: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> I don't find any sign(x) function in the math library (return the sign of the value). I've read that math module is a wrapper to C math lib and that C math lib has not sign(), so... I've implement my own sign function of course (it's easy) but a standard one in math would be better and could be faster. How do you implement this or is there any other module with a sign() function ? -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From clp at rebertia.com Sat Dec 6 16:53:56 2008 From: clp at rebertia.com (Chris Rebert) Date: Sat, 6 Dec 2008 13:53:56 -0800 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: <47c890dc0812061353x6214cfb4s1d729d36ab93f3dc@mail.gmail.com> On Sat, Dec 6, 2008 at 1:33 PM, Carl Banks wrote: > On Dec 5, 8:21 pm, "Daniel Fetchinson" > wrote: >> Hi folks, >> >> The story of the explicit self in method definitions has been >> discussed to death and we all know it will stay. However, Guido >> himself acknowledged that an alternative syntax makes perfect sense >> and having both (old and new) in a future version of python is a >> possibility since it maintains backward compatibility. The alternative >> syntax will be syntactic sugar for the old one. This blog post of his >> is what I'm talking about: >> >> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... >> >> The proposal is to allow this: >> >> class C: >> def self.method( arg ): >> self.value = arg >> return self.value >> >> instead of this: >> >> class C: >> def method( self, arg ): >> self.value = arg >> return self.value > > > > -1 > > I explained why deep in the thread but I'll elaborate more here. When > I see a def statement, I mentally equate that to an assigment to the > thing being def'ed. So for instance, when I see this: > > def (): > > I think of it like this: > > = > > > Thus, if I were to see a function definition like this > > def foo.bar(): return 1 > > I would think you were defining a function and assigning it to > foo.bar. IOW, it would be mostly equivalent to this: > > foo.bar = lambda: 1 > > > (Analogously, I would expect a definition like this: > > def baz[10](): return 1 > > to be equivalent to this: > > baz[10] = lambda: 1 ) > > > So, if, inside a class definition, I were to see this: > > def self.method(): return 1 > > Well, I'd understand that is was a method assigment, of course, but it > would conflict with what I would expect the natural meaning of > something like def a.b() would be. The above statement is not > equivalent to: > > self.method = lambda: 1 > > but I think that's what it ought to be, in general. Similarly, to those coming from Ruby or those operating under the frequent misunderstanding that the `def`s are happening in the context of a class object (which in reality has yet to be created), `self` in this context might be misconstrued as the class object and thus `def self.foo` might be misunderstood (through the intuitive equivalence you mention) as a defining a classmethod rather than an instance method. I also strongly echo the TOOWTDI arguments against adding this duplicative syntax. It's a minor gain but costs much more than it's worth for violating The Zen. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > > > Carl Banks > > > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Mon Dec 15 19:08:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 15 Dec 2008 22:08:18 -0200 Subject: Bidrectional Subprocess Communication References: <6qjspkFcv81kU1@mid.individual.net> Message-ID: En Sun, 14 Dec 2008 06:03:26 -0200, greg escribi?: > Gabriel Genellina wrote: > >> (Pipes don't work the same as sockets, although unix-like systems try >> hard to hide the differences...) > > BSD-based unixes implement pipes using socketpair(), so > pipes actually *are* sockets (or at least they used to be, > not sure whether it's still true). But not on Linux; a visible difference is that pipes are half-duplex on Linux (it seems that's enough for POSIX). I don't know for sure how they're implemented on Windows but they seem to be file system objects (they use functions like CreateFile, ReadFile, WriteFile, etc.) -- Gabriel Genellina From ajaksu at gmail.com Wed Dec 10 00:29:25 2008 From: ajaksu at gmail.com (ajaksu) Date: Tue, 9 Dec 2008 21:29:25 -0800 (PST) Subject: StringIO in 2.6 and beyond References: Message-ID: On Dec 9, 5:24?pm, Bill McClain <20080915.20.wmccl... at spamgourmet.com> wrote: > On 2008-12-09, MRAB wrote: > > > In Python 2.x unmarked string literals are bytestrings. In Python 3.x > > they're Unicode. The intention is to make the transition from 2.x to 3.x > > easier by adding some features of 3.x to 2.x, but without breaking > > backwards compatibility (not entirely successfully!). > > It is a bit ugly. In 2.6 StringIO won't take bytestrings, so I apply u'x'. But > in 3.0 u'x' will be gone and I'll have to change the code again. Try: from __future__ import unicode_literals From cjw at ncf.ca Mon Dec 1 19:56:44 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Mon, 01 Dec 2008 19:56:44 -0500 Subject: Why doesn't doc has predifined name and location ? In-Reply-To: References: <493455AD.4040306@gmail.com> Message-ID: Chris Rebert wrote: > On Mon, Dec 1, 2008 at 1:22 PM, Stef Mientki wrote: >> hello, >> >> I'm very satisfied about the great standardization of doc strings in python. >> Now in contrast to that, >> the general documentation of libraries, >> either in plain text, html, pdf, chm, ... >> doesn't have a standarized name nor location. >> >> Why is that ? > > I suppose the need for such standardization has just never arisen. > Googling for docs, checking the library's website, or doing `locate > library-name-here | grep doc` in bash seems to work well enough for > people that no one has found it necessary to pursue the creation of > such a standard. > > Sidenote: what Python projects publish their docs in CHM besides > possibly Win32 GUI programs? Python for windows or PyScripter. Colin W. > > Cheers, > Chris From psftw1 at gmail.com Sun Dec 14 14:00:16 2008 From: psftw1 at gmail.com (peter s.) Date: Sun, 14 Dec 2008 11:00:16 -0800 (PST) Subject: Building from source -- zlib/binascii problems 2.5.2/2.6.1 Message-ID: <71531b64-535f-49d0-a0c6-7704df83b251@f18g2000vbf.googlegroups.com> I am trying to build Python from source on a RHEL system where I do not have root access. There are two modules that I am having trouble with: zlib & binascii. zlib -- This seems like a make configuration issue. I have noticed that 'gcc -v' returns '--with-system-zlib': $ gcc -v Using built-in specs. Target: x86_64-redhat-linux Configured with: ../configure --prefix=/usr --mandir=/usr/share/man -- infodir=/usr/share/info --enable-shared --enable-threads=posix -- enable-checking=release --with-system-zlib --enable-__cxa_atexit -- disable-libunwind-exceptions --enable-libgcj-multifile --enable- languages=c,c++,objc,obj-c++,java,fortran,ada --enable-java-awt=gtk -- disable-dssi --enable-plugin --with-java-home=/usr/lib/jvm/java-1.4.2- gcj-1.4.2.0/jre --with-cpu=generic --host=x86_64-redhat-linux Thread model: posix gcc version 4.1.2 20071124 (Red Hat 4.1.2-42) and then when I run 'make' I see: building 'zlib' extension gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - Wstrict-prototypes -I. -I/location/of/Python-2.5.2/./Include -I. - IInclude -I./Include -I/usr/local/include -I/location/of/Python-2.5.2/ Include -I/location/of/Python-2.5.2 -c /location/of/Python-2.5.2/ Modules/zlibmodule.c -o build/temp.linux-x86_64-2.5/location/of/ Python-2.5.2/Modules/zlibmodule.o gcc -pthread -shared build/temp.linux-x86_64-2.5/location/of/ Python-2.5.2/Modules/zlibmodule.o -L/usr/local/lib -lz -o build/ lib.linux-x86_64-2.5/zlib.so /usr/bin/ld: skipping incompatible /usr/lib/libz.so when searching for -lz /usr/bin/ld: skipping incompatible /usr/lib/libz.a when searching for - lz /usr/bin/ld: cannot find -lz collect2: ld returned 1 exit status It seems as though I need to force the build process to use the zlib that comes with python source. binascii -- I have no idea what binascii requires in order to compile, so I am clueless. It properly compiles with 2.5.2, but fails to build in 2.6.1. I am OK using 2.5.2 if I could get zlib to work. Thanks, Peter From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 23 07:37:25 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 23 Dec 2008 13:37:25 +0100 Subject: On Whose Desktop In-Reply-To: References: Message-ID: <4950db7e$0$14770$426a74cc@news.free.fr> Steve Holden a ?crit : > Thanks to Barry Warsaw the "On Your Desktop" blog now has a new entry: > > http://onyourdesktop.blogspot.com/ > > Who would you like to see profiled next? The effbot ? > regards > Steve From cheney at halliburton.com Mon Dec 1 05:16:36 2008 From: cheney at halliburton.com (Andre Majorel) Date: Mon, 1 Dec 2008 10:16:36 +0000 (UTC) Subject: Python surpasses Perl in popularity? References: <5e87aee0-c7fd-4e9d-befb-0cc01cee64ec@f40g2000pri.googlegroups.com> <49316c95$0$2813$742ec2ed@news.sonic.net> <49322ea2$0$2747$742ec2ed@news.sonic.net> Message-ID: On 2008-11-30, Stephane Chazelas wrote: > 2008-11-30, 06:11(+00), Tam Ha: >> Stephane CHAZELAS wrote: >>> There's a common confusion in this in the nature of /bin/sh. >>> There's no standard (neither POSIX nor Unix) that specifies that >>> /bin/sh should be any variant of the Bourne shell. >> >> Sure there is, POSIX. > [...] > > And on this. First, POSIX has no juridiction on defining the > Bourne shell, let alone its location as the Bourne shell is > completely outside POSIX, it's a legacy shell and as been for > years. Then, POSIX makes it clear that the location of its sh > utility (again, which the Bourne shell is not) is unspecified, > only that the lookup of "sh" via $PATH in a conformant > environment should resolve to a conformant "sh". > > And if you need some examples to be convinced, see the different > choices of those 4 different POSIX conformant Unices: > > Solaris (7, 8, 9 at least): > /bin/sh: legacy Bourne/SVr4 shell > /usr/xpg4/bin/sh: a POSIX compliant shell (actually ksh88) > Solaris choice was to keep /bin/sh as the Bourne shell for > backward compatibility (as changing it for a POSIX shell > introduces a slight chance of breaking some existing scripts > as there are a few corner-case areas where the POSIX shells > are not backward compatible with the Bourne shell), and make > /bin a non standard place. How to get a conformant environment > (typically one where /usr/xpg4/bin/sh is before /bin) is > described in standards(5). The default one is not, which makes > Solaris a pain when porting scripts. > > HPUX (10.10 and newer at least): > /usr/bin/sh (and /bin/sh if there's a symlink /bin -> > usr/bin): a POSIX compliant shell (based on ksh88) > > /usr/old/bin/sh: the Bourne shell (though I think nowadays, > it's part of an optional package). > > Tru64: > /bin/sh can behave either as a Bourne shell or a POSIX shell > (ksh88) depending on the environment How does it decide ? argv[0] ? isatty (STDIN_FILENO) ? > most Linux based systems and most other Unices: > /bin/sh is a POSIX compliant shell (bash generally for Linux) > and there's no Bourne shell (either there has never been or it > has been removed/replaced by a POSIX shell). Two other Unixen I know of that have a non-POSIX sh are SCO Open Server and UnixWare. I'm not sure they even provide a POSIX-compliant alternative like Solaris does. On the other hand, their utilities (awk, grep, sed et al.) seem to be POSIX-compliant, at least to the extent that I've always managed. Unlike Solaris where I've often had to use the ones in /usr/xpg4/bin. Many people assume "standard" equates "portable". As far as shell programming is concerned, the safest way to get portability is to ignore the standard and code for the Bourne shell. -- Andr? Majorel "After 15 minutes, I wanted to marry her. After a half hour, I completely gave up the idea of snatching her purse." -- _Take the Money and Run_ From jcd at sdf.lonestar.org Tue Dec 2 09:33:35 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 02 Dec 2008 09:33:35 -0500 Subject: pydoc enforcement. In-Reply-To: <8542922d0812011438g529b8806l29e185896274609e@mail.gmail.com> References: <6ccec696-a8bb-4818-a016-642514677b70@b38g2000prf.googlegroups.com> <1228147384.32081.5.camel@aalcdl07.lib.unc.edu> <8542922d0812011438g529b8806l29e185896274609e@mail.gmail.com> Message-ID: <1228228415.5945.3.camel@aalcdl07.lib.unc.edu> On Tue, 2008-12-02 at 09:38 +1100, Ken Faulkner wrote: > Hi > > Yeah, I was thinking about something at commit time for a VCS... > catch is, soo many VCS's out there. > And I wasn't thinking of the default action throwing compile errors, > but would only do that if a particular flag was given. > Still, just an idea. > I meant more that a cultural solution might work better than a technical one. Don't allow commits that aren't documented, and *properly* documented. If you find them, back them out, scold the commiter, and revise. > I'm just finding more and more public modules/API's/libraries that > have so little documentation that it really does force reading a LOT > of the source to figure out whats going on. Sure, a lot of the time > thats required, but some modules are just painful.. > > oh well... was just a thought. > > Ken > > > > On Tue, Dec 2, 2008 at 3:03 AM, J. Cliff Dyer > wrote: > > > On Sun, 2008-11-30 at 16:27 -0800, ken.faulkner at gmail.com > wrote: > > I've been thinking about implementing (although no idea yet > *HOW*) the > > following features/extension for the python compile stage > and would be > > interested in any thoughts/comments/flames etc. > > > > Basically I'm interested adding a check to see if: > > 1) pydoc's are written for every function/method. > > 2) There are entries for each parameter, defined by some > > predetermined syntax. > > > > My idea is that as much as I love dynamic typing, there are > times when > > using some modules/API's that have less than stellar > documentation. I > > was thinking that if it was possible to enable some switch > that > > basically forced compilation to fail if certain > documentation criteria > > weren't met. > > > > Yes, it should be up to developers to provide documentation > in the > > first place. Or, the client developer might need to read the > source > > (IF its available)... but having some "forced" > documentation might at > > least ease the problem a little. > > > > For example (half borrowing from Javadoc). > > > > class Foo( object ): > > > > def bar( self, ui ): > > pass > > > > > > Would fail, since the bar method has an "unknown" parameter > called > > "ui". > > What I think could be interesting is that the compiler > forces some > > documentation such as: > > > > class Foo( object ): > > > > def bar( self, ui ): > > """ > > @Param: ui : blah blah blah. > > """ > > pass > > > > > > The compiler could check for @Param matching each parameter > passed to > > the method/function. Sure, a lot of people might just not > put a > > description in, so we'd be no better off. But at least its > getting > > them *that* far, maybe it would encourage them to actually > fill in > > details. > > > > Now ofcourse, in statically typed language, they might have > the > > description as "Instance of UIClass" or something like that. > For > > Python, maybe just a description of "Instance of abstract > class UI" or > > "List of Dictionaries"... or whatever. Sure, precise class > names > > mightn't be mentioned (since we mightn't know what is being > used > > then), but having *some* description would certainly be > helpful (I > > feel). > > > > Even if no-one else is interested in this feature, I think > it could > > help my own development (and would be an interested "first > change" > > into Python itself). > > > > Apart from bagging the idea, does anyone have a suggestion > on where in > > the Python source I would start for implementing such an > idea? > > > > Thanks > > > > Ken > > > For the reasons already stated, I think it's probably a bad > idea to > enforce this at compile time. I think it's a great idea to > make sure > that this information is present in all your code, but unless > you want > to see useless stubs, the correct time to enforce this is at > commit > time. Don't accept any improperly documented patches. > > Syntax is not enough to ensure what you want to ensure. The > semantics > have to be right as well. > > Cheers, > Cliff > > > > > From cmgui2 at gmail.com Sun Dec 14 23:38:58 2008 From: cmgui2 at gmail.com (cm_gui) Date: Sun, 14 Dec 2008 20:38:58 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> Message-ID: hahaha, do you know how much money they are spending on hardware to make youtube.com fast??? > By the way... I know of a very slow Python site called YouTube.com. In > fact, it is so slow that nobody ever uses it. From steve at holdenweb.com Sun Dec 28 12:38:50 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 28 Dec 2008 12:38:50 -0500 Subject: "return" in def In-Reply-To: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> Message-ID: Roger wrote: > Hi Everyone, > > First I want to thank everyone that posts to this group. I read it > daily and always learn something new even if I never feel like I have > anything to contribute but my questions. > > When I define a method I always include a return statement out of > habit even if I don't return anything explicitly: > > def something(): > # do something > return > > Is this pythonic or excessive? Is this an unnecessary affectation > that only adds clock ticks to my app and would I be better off > removing "returns" where nothing is returned or is it common practice > to have returns. > It's an unnecessary affectation, but I don't believe it adds any clock ticks to your app, as the function has to return anyway. The dis module shows you they both generate exactly the same code: >>> from dis import dis >>> def f1(): ... print "hello" ... >>> def f2(): ... print "hello" ... return ... >>> dis(f1) 2 0 LOAD_CONST 1 ('hello') 3 PRINT_ITEM 4 PRINT_NEWLINE 5 LOAD_CONST 0 (None) 8 RETURN_VALUE >>> dis(f2) 2 0 LOAD_CONST 1 ('hello') 3 PRINT_ITEM 4 PRINT_NEWLINE 3 5 LOAD_CONST 0 (None) 8 RETURN_VALUE >>> > Even when I'm not explicitly returning something I like to add > "return" because it's a good additional visual marker for me to see > where a method definition ends especially in cases where I may use a > nested method. > Well, I suppose at least you aren't writing "return None" ... Normally a blank line or two suffices for me. Take a look at PEP 8 for some discussion for Python coding style. http://www.python.org/dev/peps/pep-0008/ regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From andrew at doadesweb.co.uk Thu Dec 11 14:03:57 2008 From: andrew at doadesweb.co.uk (Andrew Doades) Date: Thu, 11 Dec 2008 19:03:57 +0000 Subject: get todays files In-Reply-To: <4941628E.7070902@tim.thechases.com> References: <4632c353-0462-485b-9e1b-6a5c56682363@s9g2000prg.googlegroups.com> <494015F7.3020302@tim.thechases.com> <49415258.2010101@doadesweb.co.uk> <4941628E.7070902@tim.thechases.com> Message-ID: <4941641D.8050209@doadesweb.co.uk> Tim Chase wrote: >> I know this will sound like I am being very cheeky, but is there a >> way you can make this for where the ftp server is actually windows >> server? > > For Windows Server, I don't have a Windows FTP server to test with -- > I've got the company Linux server, and the previous testing site I > used (I think I used ftp.mozilla.org) which also likely runs some > flavor of Linux. Neither supports the NLST from my testing. > >> curr_date = strftime("%d %B %Y", gmtime()) > > The first thing I noticed was that your strftime formating needs to > match the format of the date that comes back from the FTP site. In my > test, that was "YYYYMMDD". As such, your "%d %B %Y" would likely need > to be "%Y%m%d". > >> ftp.retrlines('NLST',makelist) > > The servers I tried didn't support the NLST command so I can't exactly > follow along here. However assuming that it correctly populates the > list of files here > >> for ff in files: > > correctly, that's immaterial to me. > >> ftp = FTP(ftp_server) >> ftp.set_pasv(False) >> resp = ftp.login(ftp_uname,ftp_pwd) > > Just curious why you're logging into the server each pass through the > loop -- I'd just connect once at the beginning of the loop, pull the > files, and then disconnect at the end of the loop. I support it would be somewhat better to download in a 'bulk' download rather that a file at a time, this script was not written by me, I am just the developer who has to make a new or modify the old one. > >> assert code == "213", "Unexpected result" > > Does this assert fail at any point? Nope, nothing shows up in my logs or on screen. > >> if stamp[:8] == today: > > Given the above date-formatting, this should fail *every* time unless > your FTP server is returning the date in some format other than > "YYYYMMDDhhmmss" This line appears to just get missed in the code, I think it might be one of the problems when it downloads all the files. > > > > It's hard to pinpoint actual problems as this block of code has been > modified, or doesn't run...there's some bogus indentation in your post: > >> log('Transferring: ' + ff[0]) >> # make parameters to wget the backup file >> params = ' ftp://' + ftp_server + '/' + ff[0] >> rcode = subprocess.call('c:/wget.exe ' + params) >> log('Return code from wget = ' + str(rcode)) >> if (rcode == 0): >> ff[1] = 1 >> else: >> log('File ' + ff[0] + ' already exists locally, not >> transferring') > > because this "else" is hanging oddly. Additionally, the FTP object > has methods for downloading the content of a file, so I'd not bother > shelling out to wget as an additional dependency I am running kubuntu 8.04 and have edited the code in kate, It seemed to indent on every line, so I just 'pulled' it back a little. > . > > -tkc Thanks for you comments, I think I will try and start from scratch and see what I get. Andrew > > > > From lewis.sarah93 at yahoo.com Fri Dec 5 00:14:30 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 21:14:30 -0800 (PST) Subject: Reduce Debt Message-ID: Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From hongqn at gmail.com Sun Dec 28 05:37:55 2008 From: hongqn at gmail.com (Qiangning Hong) Date: Sun, 28 Dec 2008 02:37:55 -0800 (PST) Subject: sys.stdout.write()'s bug or doc bug? References: Message-ID: On Dec 27, 12:31 am, Martin wrote: > Python 2.4.4 (#2, Oct 22 2008, 19:52:44) > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> u = u"\u554a" > >>> print u > ? > >>> sys.stdout.write(u + "\n") > > Traceback (most recent call last): > File "", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode character u'\u554a' in > position 0: ordinal not in range(128) > > >>> # you are trying to write unicode, you need to encode it to something that suits your needs > >>> sys.stdout.write(u.encode("UTF-8") + "\n") > ? > >>> # now go and write a hundred times "Unicode is not an encoding" :) Actually, I know relationship between unicode and str objects very well. That's why I only quoted the unicode-related part of file.encoding's documentation in my original post. Thank you. > > So, my question is, as sys.stdout IS a file object, why it does not > > use its encoding attribute to convert the given unicode? An > > implementation bug? A documenation bug? > > hmm I always thought "sys.stdout" is a "file-like object" not that it IS a file. In my original post, I have figured out that sys.stdout IS a file, by using type() function. And isinstance() function tells the same: Python 2.5.2 (r252:60911, Dec 18 2008, 12:39:19) [GCC 4.2.1 (Apple Inc. build 5564)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> type(sys.stdout) is file True >>> isinstance(sys.stdout, file) True So, sys.stdout SHOULD do what the doc says, otherwise there is a bug either in implementation of sys.stdout, or in the documentation of file. From python at bdurham.com Wed Dec 24 03:36:08 2008 From: python at bdurham.com (python at bdurham.com) Date: Wed, 24 Dec 2008 03:36:08 -0500 Subject: Most efficient way to build very large dictionaries In-Reply-To: References: <1230104615.5867.1291617213@webmail.messagingengine.com> Message-ID: <1230107768.14060.1291622121@webmail.messagingengine.com> Hi Roger, > you may want to consider using SQLite Thank you for your suggestion about looking at SQLite. I haven't compared the performance of SQLite to Python dictionaries, but I'm skeptical that SQLite would be faster than in-memory Python dictionaries for the type of analysis I'm doing. Prior to my use of Python, my customer used a very expensive Oracle system to analyze their log files. My simple Python scripts are 4-20x faster than the Oracle PL/SQL they are replacing - and run on much cheaper hardware. Note: Memory is currently not a concern for me so I don't need SQLite's ability to work with data sets larger than my physical memory. Regards, Malcolm ----- Original message ----- From: "Roger Binns" To: python-list at python.org Date: Wed, 24 Dec 2008 00:19:56 -0800 Subject: Re: Most efficient way to build very large dictionaries -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 python at bdurham.com wrote: > I would appreciate your thoughts on whether there are advantages to > working with a pre-built dictionary and if so, what are the best ways to > create a pre-loaded dictionary. Based on this and your other thread, you may want to consider using SQLite (standard Python module is available for it). SQL queries are very similar to set operations and indices take care of performance (by using more storage). You also get transactions for free. If you look into SQLite pragmas you can get it to use more RAM to improve performance. And by using a SQL layer you can later switch to another database should you need really hard core storage. It also makes the data available to other programs in a uniform way. Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAklR8KgACgkQmOOfHg372QSrHQCfVJzueXVKme8QZcxoLf70BL4K RL8AoM9QOFykOLrr5QXtpmZ5f7CFHm6e =zAPG -----END PGP SIGNATURE----- -- http://mail.python.org/mailman/listinfo/python-list From nebson at gmail.com Wed Dec 24 19:57:47 2008 From: nebson at gmail.com (Sponge Nebson) Date: Wed, 24 Dec 2008 16:57:47 -0800 (PST) Subject: Easy-to-use Python GUI References: Message-ID: <68d3a930-2cb6-4c6c-bcaf-cf50cb76093f@x16g2000prn.googlegroups.com> On Dec 24, 3:47?pm, "Joel Koltner" wrote: > Is there an easy-to-use, "function"-based cross-platform GUI toolkit for > Python out there that's a little more sophisticated than EasyGui? ?EasyGui > looks good, but it's a little more restrictive than what I'd like to have, yet > I'm (stubbornly :-) ) resistant to stepping up to a "full service" GUI toolkit > such as pyGTK or wxPython where it's all about event loops and callbacks and > you need to start planning how the GUI affects the overall program flow rather > than just using a "forms" (or "Wizard")-type approach where you put up a few > dialogs, users fill in some variables, and your program just sits around > waiting until "OK" or "Cancel" is clicked. > > One approach that I like comes from SAX BASIC/WinWrap, which is more or less a > clone of Microsoft's Visual BASIC for Applications, but they (apparently) > wanted everything to still be human-readable, so they have a simple GUI > ("form") builder that generates code that looks like this: > > --- > > ?Begin Dialog UserDialog 850,497,"Export Control" ' %GRID:10,7,1,1 > > ? GroupBox 20,7,360,217,"Drill File Generation",.GroupBox1 > ? CheckBox 40,35,130,14,"Output drill file(s)",.genDrill > ? Text 40,63,270,28,"Identify via layers as any that contain this text in > their names:",.Text > ? TextBox 40,98,220,21,.viaLayerName > ? Text 40,140,100,14,"Output method:",.Text8 > ? DropListBox 160,140,180,21,DrillStyle(),.drillStyle > ? Text 40,175,130,28,"Select drill table units:",.Text2 > ? ListBox 200,175,120,28,unitNames(),.unitName > > ? OKButton 310,469,90,21 > ? CancelButton 410,469,90,21 > > ?End Dialog > > ' GUI builder generates or modifies everything above, but can also be edited > by hand > ' You write the following code... > > ?Dim dlg As UserDialog > > ?dlg.genDrill = 1 > ?ReDim DrillStyle(1) > ?DrillStyle(0) = "All Via Layers In One File" > ?DrillStyle(1) = "One File Per Via Layer" > ?dlg.drillStyle = 1 > > ?func=Dialog(dlg) > > --- > > This is pretty darned easy for me understand and modify either by hand or with > the GUI builder. ?Still, it's quite powerful, since it supports all the common > GUI elements (text, group boxes, checkboxes, drop-down lists, text boxes, > buttons, etc.). ?This is about the level of sophistication I'm looking for. > > Anything like this for Python? > > Thanks, > ---Joel You may want to try PythonCard. It is a GUI toolkit that runs on wxPython, but it is much easier to use. Visit http://pythoncard.sourceforge.net/ and check out all the samples and screenshots. You may also want to listen to this podcast: http://libsyn.com/media/awaretek/Python411_070509_GUItoolkits.mp3 It discusses python GUI toolkits in general. You should also listen to: http://media.libsyn.com/media/awaretek/Python411_060730_PythonCard.mp3 which discusses PythonCard in detail. The python podcast collection can be found at: http://www.awaretek.com/python/ I just started out with PythonCard and I'm picking it up really fast. Hope this helps! -Sponge From srimogroupin at gmail.com Fri Dec 5 01:45:43 2008 From: srimogroupin at gmail.com (srimo) Date: Thu, 4 Dec 2008 22:45:43 -0800 (PST) Subject: Free Domain Name for life. supports for CNAME, A, MX, NS records! - Full DNS control - URL forwarding Message-ID: <05f28c1d-ac36-4b3f-bad5-6f0a45636477@y18g2000yqn.googlegroups.com> Register A Domain Name Free for life. Up to 2 free domain names. - You can transfer ownership of you domain to another person. Get a cool, simple and FREE domain! No Ads supports for CNAME, A, MX, NS records! Search for the domain you want - if it's available, register it today for FREE! Full DNS control and domain management provides free DNS and MX services. URL forwarding - Turn your long and boring URL http://www.sreemoo.com From bdesth.quelquechose at free.quelquepart.fr Sun Dec 7 13:54:10 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 07 Dec 2008 19:54:10 +0100 Subject: Guido's new method definition idea In-Reply-To: References: <493c2276$0$9254$426a34cc@news.free.fr> Message-ID: <493c298a$0$9254$426a34cc@news.free.fr> Daniel Fetchinson a ?crit : (snip) > > Still, improved error messages would be desirable (concerning the > number of arguments passed to an instance method). Then count me as +2 on this !-) From google at mrabarnett.plus.com Wed Dec 3 14:21:25 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 03 Dec 2008 19:21:25 +0000 Subject: python to parse excel file csv format In-Reply-To: References: Message-ID: <4936DC35.6010404@mrabarnett.plus.com> Jay Jesus Amorin wrote: > This is how i do it, but it runs with error. Kindly help > > > #!/usr/bin/env python > > import csv, sys, os > filename = (sys.argv[1]) > reader = csv.reader(open(filename, "rb"), delimiter=',', > quoting=csv.QUOTE_NONE) > > try: > for row in reader: > os.popen("chown row[0] row[1]") This should be: os.popen("chown %s %s" % (row[0], row[1])) or: os.popen("chown %s %s" % tuple(row)) > > except csv.Error, e: You could try adding: print e and perhaps: print repr(reader), dir(reader) here to see what the message was and why the following line raises an exception. > sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) > > > ================================================================== > > > testserver:~> ./promote2prod.py test.xls > Traceback (most recent call last): > File "./promote2prod.py", line 12, in ? > sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) > AttributeError: '_csv.reader' object has no attribute 'line_num' > From martin at v.loewis.de Fri Dec 19 01:30:13 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Fri, 19 Dec 2008 07:30:13 +0100 Subject: Python for amd64 and mingw-w64 In-Reply-To: References: Message-ID: <494B3F75.10104@v.loewis.de> > - Any extension requires the MS_WIN64 to be defined, but this symbol > is only defined for MS compiler (in PC/pyport.h). Why do you say that? It is only defined when _WIN64 is defined; this has nothing to do with a MS compiler. > Shouldn't it be > defined independantly of the compiler ? You mean, completely unconditional? Definitely not, it should only be defined when you are compiling for 64-bit mode. > - I have some link problems related to Py_InitModule4_64. I believe > the problem is in libpython26.a, which according to nm does not have > this symbol defined, whereas python26.dll has. It's a mistake if libpython26.a gets included in the Win64 installer at all; this library is only provided for 32-bit systems. My copy of mingw doesn't support Win64 at all. Regards, Martin From bj_666 at gmx.net Fri Dec 12 09:00:23 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 12 Dec 2008 14:00:23 GMT Subject: (Very Newbie) Problems defining a variable References: <49425146$0$8495$426a74cc@news.free.fr> <11c53a4a-de1e-4bee-ad60-a05befb6cbf4@a12g2000yqm.googlegroups.com> <7cb69ff5-9034-41cc-b667-d69329707b18@d36g2000prf.googlegroups.com> Message-ID: <6qf93mFc3a5jU2@mid.uni-berlin.de> On Fri, 12 Dec 2008 04:58:36 -0800, feba wrote: > Actually, I have gedit set to four spaces per tab. I have no reason why > it's showing up that large on copy/paste, but the file itself is fine. The file contains one tab character per indentation level and it depends on the software you use to look at the text how many spaces will be displayed. Better use four real spaces to indent one level so it looks the same everywhere. Ciao, Marc 'BlackJack' Rintsch From benjamin.kaplan at case.edu Fri Dec 19 14:49:57 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 19 Dec 2008 14:49:57 -0500 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <6r25ckFejl4vU1@mid.individual.net> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> <6r25ckFejl4vU1@mid.individual.net> Message-ID: On Fri, Dec 19, 2008 at 12:53 PM, Thomas Heller wrote: > Steve Holden schrieb: > > Thomas Heller wrote: > >> Question from a non-native english speaker: is this now valid english? > >> > >> "One of Python's great strengths" > >> ^ > >> "and also teaches Python's functional programming features" > >> ^ > >> "The book's approach is wholly practical" > >> ^ > > It always has been valid English. The apostrophe is only omitted from > > personal pronouns (hers, its, and so on). > > I see, thanks. But, is the apostrophe optional in the above fragments? > No. The apostrophe on the nouns is used to denote possession. If you don't include it, the word becomes plural (which makes no sense on proper nouns). The way to write the sentance without the apostrophe would be "One of the great strengths of Python" and "The approach of the book is wholly practical". To a native English speaker, this alternative is much more awkward. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ee1394 at gmail.com Thu Dec 11 14:44:46 2008 From: ee1394 at gmail.com (ee1394 at gmail.com) Date: Thu, 11 Dec 2008 11:44:46 -0800 (PST) Subject: EARN 15,000$ /- PER MONTH Message-ID: <86a0d986-65e7-457b-9719-1885fffc62f0@o4g2000pra.googlegroups.com> TURN YOUR PC INTO A CASH GENERATING, MACHINE.WORK ONLINE FROM HOME. GUARANTEED,EXTRA CASH, 15,000$ /- PER MONTH. NO INVESTMENT http://fishery.homestead.com/ From greywine at gmail.com Wed Dec 24 20:43:31 2008 From: greywine at gmail.com (greywine at gmail.com) Date: Wed, 24 Dec 2008 17:43:31 -0800 (PST) Subject: socket send help References: Message-ID: Chris & Gabriel, Thank you so much. My simple example now works. It was very frustrating that even the simple example didn't work, so your help is most appreciated. b'hello world' was the key. As for the error, I do still get it with 3.0 final so I'll go ahead and report it. John. On Dec 24, 12:03?am, "Gabriel Genellina" wrote: > En Wed, 24 Dec 2008 03:59:42 -0200, greyw... at gmail.com ? > escribi?: > > > New guy here. ?I'm trying to figure out sockets in order to one day do > > a multiplayer game. ?Here's my problem: ?even the simplest examples > > don't work on my computer: > > > A simple server: > > > fromsocketimport * > > myHost = '' > > Try with myHost = '127.0.0.1' instead - a firewall might be blocking your ? > server. > > > s.listen(5) ? ? ? ? ? ? ? ? ? ? ? ? # allow 5 simultaneous connections > > Not exactly: your server program only handles a single connection at a ? > time. The 5 above specifies how many connections may exist "on hold" ? > waiting for you to accept() them. > > > ? ? ? ? ? ? connection.send('echo -> ' + data) > > That's fine for Python 2.6, but you must use b'echo -> ' with 3.0 > > > And a simple client: > > > s.send('Hello world') ? ? ? ? ? ? ? # send the data > > Same as above, should be b'Hello world' with Python 3.0 > > > If I run testserver.py via the cmd prompt in Windows XP and then the > > testclient.py program, I get the following error: > > > Traceback (most recent call last): > > ? File "C:\Python30\testclient.py", line 12, in > > ? ? s.send('Hello world') ? ? ? ? ? ? ? # send the data > > TypeError: send() argument 1 must be string or buffer, not str > > The above error message is wrong (and I think it was corrected on the 3.0 ? > final release; if you got it with 3.0 final, file a bug report at ?http://bugs.python.org/) > > > This happens in 2.6 or 3.0 and with different example client & server > > programs from the web. ?What am I missing? > > The error above surely comes from 3.0; with 2.6 you should get a different ? > error (if it fails at all). Try again with 2.6.1. I didn't run the code ? > but it looks fine -- if you got it from a book or article, unless it ? > explicitely says "Python 3.0", assume it was written for the 2.x series. > > -- > Gabriel Genellina From duncan.booth at invalid.invalid Tue Dec 2 07:52:55 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Dec 2008 12:52:55 GMT Subject: optimization References: <6672532a-f162-4717-b0bb-c613214b57db@d32g2000yqe.googlegroups.com> <01450e77$0$20670$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Which makes me wonder, is there anything we can do with that code object > from Python code? I can disassemble it: > >>>> import dis >>>> dis.dis(outer.func_code.co_consts[1]) > 3 0 LOAD_CONST 0 (None) > 3 RETURN_VALUE > > Anything else? Provided it doesn't take any arguments you can run the code with exec or eval: >>> def outer(): def inner(): print "inner called" return inner() >>> eval(outer.func_code.co_consts[1]) inner called More usefully you could use the code object to construct another function, e.g. if you wanted to change the values of some default arguments. >>> types.FunctionType(outer.func_code.co_consts[1], globals())() inner called -- Duncan Booth http://kupuguy.blogspot.com From kyosohma at gmail.com Fri Dec 5 17:17:49 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 5 Dec 2008 14:17:49 -0800 (PST) Subject: To Troll or Not To Troll (aka: "as" keyword woes) References: <20081205163107.1815df40@usenot.de> Message-ID: <98e6c908-2bc5-49bd-8b2a-845b4de4b287@f3g2000yqf.googlegroups.com> On Dec 5, 4:00?pm, James Stroud wrote: > Andreas Waldenburger wrote: > > Is it me, or has c.l.p. developed a slightly harsher tone recently? > > (Haven't been following for a while.) > > Yep. I can only post here for about a week or two until someone blows a > cylinder and gets ugly because they interpreted something I said as a > criticism of the language and took it personally by extension. Then I > have to take a 4 month break because I'm VERY prone to > reciprocating--nastily. I think its a symptom of the language's > maturing, getting popular, and a minority fraction* of the language's > most devout advocates developing an egotism that complements their > python worship in a most unsavory way. > > I wish they would instead spend their energy volunteering to moderate > this list and culling out some of the spam. > > *No names were mentioned in the making of this post. I really like Python, but I seem to get blasted enough on this list that I don't post much on here any more without being extremely careful in how I word my answers. Bleh! Oh well. You win some, you lose some. Mike From Tribulations at Paralleles.invalid Wed Dec 31 09:40:32 2008 From: Tribulations at Paralleles.invalid (TP) Date: Wed, 31 Dec 2008 15:40:32 +0100 Subject: change only the nth occurrence of a pattern in a string Message-ID: <0scs26-7a5.ln1@rama.fbx.proxad.net> Hi everybody, I would like to change only the nth occurence of a pattern in a string. The problem with "replace" method of strings, and "re.sub" is that we can only define the number of occurrences to change from the first one. >>> v="coucou" >>> v.replace("o","i",2) 'ciuciu' >>> import re >>> re.sub( "o", "i", v,2) 'ciuciu' >>> re.sub( "o", "i", v,1) 'ciucou' What is the best way to change only the nth occurence (occurrence number n)? Why this default behavior? For the user, it would be easier to put re.sub or replace in a loop to change the first n occurences. Thanks Julien -- python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\ 9&1+,\'Z4(55l4('])" "When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong." (first law of AC Clarke) From jantod at gmail.com Wed Dec 3 10:08:52 2008 From: jantod at gmail.com (Janto Dreijer) Date: Wed, 3 Dec 2008 07:08:52 -0800 (PST) Subject: Reverse zip() ? References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> <20081203095154.1bb33d4d@usenot.de> <8000d0b0-c9e5-4dbd-a6a0-e35b83277e72@d42g2000prb.googlegroups.com> <20081203114855.3915af9e@usenot.de> Message-ID: I'd like to point out that since your where thinking in terms of matplotlib, you might actually find numpy's own transpose useful, instead of using zip(*seq) :) untested: t = linspace(0,2*pi*3) seq = asarray(zip(t, sin(t))) t, y = seq.T # or seq.transpose() or numpy.transpose(seq) pylab.plot(t,y) Regards Janto Andreas Waldenburger wrote: > On Wed, 3 Dec 2008 02:11:51 -0800 (PST) alex23 > wrote: > > > On Dec 3, 6:51?pm, Andreas Waldenburger wrote: > > > On Tue, 02 Dec 2008 18:16:13 -0800 Bryan Olson > > > > zip as its own inverse might be even easier to comprehend if we > > > > call zip by its more traditional name, "transpose". > > > > > > Sounds like a Py4k change to me. > > > > Nah, just add the following to your sitecustomize.py: > > > > transpose = zip > > > > :) > > Gaaahh! > > :) > /W > > -- > My real email address is constructed by swapping the domain with the > recipient (local part). From steve at holdenweb.com Wed Dec 17 22:03:49 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 17 Dec 2008 22:03:49 -0500 Subject: getting object instead of string from dir() In-Reply-To: <0159a791$0$20656$c3e8da3@news.astraweb.com> References: <477b9c2e-a0ab-4b26-b643-4a9369c2aaac@r2g2000vbp.googlegroups.com> <0159a791$0$20656$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Wed, 17 Dec 2008 11:52:17 -0800, Rominsky wrote: > >> I do have some understanding of the pythonic methodology of programming, >> though by far I still don't consider myself an expert. The problem at >> hand is that I am coming from a matlab world and trying to drag my >> coworkers with me. I have gotten a lot of them excited about using >> python for this work, but the biggest gripe everytime is they want their >> matlab ide. I am trying to experiment with making similar pieces of the >> ide, in particular I am working on the workspace window which lists all >> the current variables in the namespace, along with their type, size, >> value, etc.... I am trying to create a python equivalent. > > > Have you considered looking at existing IDEs instead of re-inventing the > wheel? Python even comes with one, IDLE. > > > I realise there are some very competent Python programmers whose primary environment is IDLE, but I'm afraid I always end up frustrated with it. I think Rominsky will learn a lot by noodling around in the way he proposes - he does, after all, confess he is experimenting, and that sounds to me like a great way to find out a lot in a fairly short time. Matlab is a very specific environment, and students have told me that there are pieces of its IDE that they really miss in Python, so this work may result in something that attracts more users to Python. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From de.slotenzwemmer at gmail.com Thu Dec 25 05:22:01 2008 From: de.slotenzwemmer at gmail.com (Dennis van Oosterhout) Date: Thu, 25 Dec 2008 11:22:01 +0100 Subject: os.system('cls') Message-ID: Hi there! I was searching for a way to clear the 'DOS screen'/command screen etc. and found that os.system('cls') works for this. I was just wondering where I can find al the commands which can be used for os.system(). I searched with google but I didn't find an answer. In the official python tutorial it says os.system('command') executes the command, but it doesn't say which commands exist (or I'm just blind). Does anyone have an answer for this question? Thanks, Devilly -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Mon Dec 29 09:01:58 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 06:01:58 -0800 (PST) Subject: poblem regarding opening a html file References: <022701c969a0$a4541ef0$5fc513ac@pwit.com> Message-ID: On Dec 29, 6:10?am, "Hendrik van Rooyen" wrote: > Sibtey Mehdi ?wrote: > >Hi > > ? ? ? ? ? ?I have a GUI application (wxpython) that calls another GUI > > Application. I m using os.system (cmd) >to launch>The second GUI, in the second GUI I m trying to open the html file using the > > os.startfile (filename) function >but > > >It takes lots of time to open the html file. > >If I am running only the second application then ?os.startfile? quickly open > the html file. > >Any one can help me to solve this problem. > > Buy more memory? > > - Hendrik You might be running into problems with duelling message pumps in the GUI loops. The 'os.system' call runs in a subprocess, not in an independent one. If you use 'subprocess.Popen', you can explicitly wait on the second process, which will hang your first GUI, but may cause the second one to run better. Or, you have the option to not wait for it. I see that 'os.system' waits for the second process to complete, while 'startfile' does not. Just a thought, are you looking for the 'webbrowser' module? Another option is to run it from a separate thread. From google at mrabarnett.plus.com Mon Dec 8 09:21:40 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 08 Dec 2008 14:21:40 +0000 Subject: gzip.GzipFile (was Re: Don't you just love writing this sort of thing :)) In-Reply-To: References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: <493D2D74.5060708@mrabarnett.plus.com> Jorgen Grahn wrote: > On Sat, 06 Dec 2008 10:01:10 +0000, Arnaud Delobelle wrote: > > ... >> Why use (open, gzp.GzipFile)[Entry.endswith(".gz")] when we have had >> contitional expressions for a few years now? Instead, you can write >> >> (gzip.GzipFile if entry.endswidth(".gz") else open). >> >> I think it will be faster (as it doesn't require the construction of a >> tuple and then the retrieval of one of its elements) and clearer. > > Even clearer would be if gzip.Gzipfile could (optionally) read > non-gzipped files and file-like objects, like the gzip Unix commands > zcat -f, zgrep and so on. > > Also, making a decision based on the .gz part of the name isn't > always correct -- you miss files named foo.Z and similar. > gzip is for reading gzipped files. IMHO it would be better to have a de-archive module which uses the gzip, tarfile, etc, modules as necessary. From pdorange at pas-de-pub-merci.mac.com Mon Dec 8 05:17:36 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Mon, 8 Dec 2008 11:17:36 +0100 Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? References: <5ccd4a18-cd2b-4040-90c6-33723af15e96@b38g2000prf.googlegroups.com> Message-ID: <1irmm85.6rh7brf6my0eN%pdorange@pas-de-pub-merci.mac.com> illume wrote: > pygame is also much more portable, has more people using it, has more > developers, and a stable API. Code you wrote 5 years ago will most > likely still work. Code you wrote for older versions of pyglet will > not work without changes. I'm a new python and pygame user (i came from C/C++), very easy to learn and you got results very fast. I've done a low investigation before choosing pygame over pyglet. I choose pygame because i only need 2D and also because it seems there is more documentations, samples, books and developers for pygame. pygame is really easy to learn and seems fast to me and easy to extend (derivate class), support image, sound, etc... And can be bundled with py2app (Mac) : important to distribute the project. I just run a bug whn using background music, py2app fail ti create the bundle... On my iMac intel, i run my small arcade game (a spaceinvader like) between 800-1400 fps using dirtyrect. I can also run without modification on Windows and Unbuntu using WMWare on the same machine. -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From collin.day.0 at gmail.com Thu Dec 18 20:42:28 2008 From: collin.day.0 at gmail.com (Collin D) Date: Thu, 18 Dec 2008 17:42:28 -0800 (PST) Subject: Factoring Polynomials References: <015aebdf$0$20656$c3e8da3@news.astraweb.com> Message-ID: On Dec 18, 5:10?pm, Steven D'Aprano wrote: > On Thu, 18 Dec 2008 11:37:35 -0800, collin.day.0 wrote: > > I am trying to write a simple application to factor polynomials. I wrote > > (simple) raw_input lines to collect the a, b, and c values from the > > user, but I dont know how to implement the quadratic equation > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > into python. Any ideas? > > def quadratic_solution(a, b, c): > ? ? sol1 = (-b + (b**2 - 4*a*c)**0.5)/2*a > ? ? sol2 = (-b - (b**2 - 4*a*c)**0.5)/2*a > ? ? return (sol1, sol2) > > Because this looks like homework, I've deliberately left in two errors in > the above. One of them is duplicated in the two lines above the return, > and you must fix it or you'll get radically wrong answers. > > The second is more subtle, and quite frankly if this is homework you > could probably leave it in and probably not even lose marks. You will > need to do significant research into numerical methods to learn what it > is, but you will then get significantly more accurate results. > > -- > Steven The corrected function is: def quadratic_solution(a,b,c) sol1 = -1*b + ((b**2 - 4*a*c)**.5)/2*a sol1 = -1*b - ((b**2 - 4*a*c)**.5)/2*a return (sol1, sol2) Squaring the -b would give you some strange solutions.... :D -CD From onidaito at gmail.com Wed Dec 31 08:12:59 2008 From: onidaito at gmail.com (Benjamin Blundell) Date: Wed, 31 Dec 2008 05:12:59 -0800 (PST) Subject: Graphics Library with Standard Interaction Features, 2D and 3D References: <69c3eca8-5e17-49fb-8354-5fdc0bd73f9a@r15g2000prd.googlegroups.com> Message-ID: On Dec 31, 12:55?pm, Python wrote: > On 31 dec 2008, at 13:37, Benjamin Blundell wrote: > > > > > Hi all. I've had a look around the forums and the we and im looking > > for a library (or a set of libraries) for dealing with Visualisation > > and Interaction in Python. At the moment i've been using Flash with > > the Five3D library to do most of the work. Sadly this isnt an option > > anymore but it is a good example. Pretty,anti-aliased 2D and 3D > > graphics, simple interaction and no need to rewrite the wheel. > > > Im a fan of OpenGL and PyOpenGL is fairly cool but I really dont want > > to have to write yet another camera, another way of dealing with > > Vectors, texture organiser, picking, etc etc. Is there a library or > > set of libraries that people are aware of that might do this? I > > remember a few in C++ and C but it'd be nicer to stick to working with > > Python > > > Cheers > > Ben > > Hey Ben, > > dunno if this is exactly what you;re looking for, > yet you could have a look at Blenderhttp://blender.org/http://wiki.blender.org/index.php/Scripts > > it's an open source 3D application and has a python > scripting engine... (just like maya from Autodesk) > > gr > Arno Sorry, I should have explained a little more. I've used Blender quite a bit and its an ace program. But what im after is a set of tools for creating a visualisation program. A while ago, we used QT with the OpenGL plugins and this library: http://www.libqglviewer.com/ Essentially, you mashed these 3 together and you got a proper OpenGL window with basic mouse looks, picks and all the rest of the 'standard' stuff you cant be arsed coding for the 15th time or so ;) Model loading is also supported from a small array of formats. im not uber keen that it has to be opengl but im sure there must be a similar set of python libs out there. PyGame isnt a bad one at all but its graphic manipulation routines can be a pain (rotations) and its 2D only but its certainly along the right lines. Cheers Ben From deets at nospam.web.de Sat Dec 13 14:35:58 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 13 Dec 2008 20:35:58 +0100 Subject: [OT] stable algorithm with complexity O(n) In-Reply-To: References: <6qidmbFc4qduU1@mid.uni-berlin.de> Message-ID: <6qih4uFconetU1@mid.uni-berlin.de> Duncan Booth schrieb: > "Diez B. Roggisch" wrote: > >> David Hl????ik schrieb: >>> Hi guys, >>> >>> i am really sorry for making offtopic, hope you will not kill me, but >>> this is for me life important problem which needs to be solved within >>> next 12 hours.. >>> >>> I have to create stable algorithm for sorting n numbers from interval >>> [1,n^2] with time complexity O(n) . >>> >>> Can someone please give me a hint. Would be very very thankful! >> Unless I grossly miss out on something in computer science 101, the >> lower bound for sorting is O(n * log_2 n). Which makes your task >> impossible, unless there is something to be assumed about the >> distribution of numbers in your sequence. >> >> Who has given you that assignment - a professor? Or some friend who's >> playing tricks on you? >> > I think you must have fallen asleep during CS101. The lower bound for > sorting where you make a two way branch at each step is O(n * log_2 n), but > if you can choose between k possible orderings in a single comparison you > can get O(n * log_k n). > > To beat n * log_2 n just use a bucket sort: for numbers with a known > maximum you can sort them digit by digit for O(n log_k n), and if you don't > restrict yourself to decimal then k can be as large as you want, so for the > problem in question I think you can set k=n and (log_n n)==1 so you get > O(n) Thanks. I *totally* forgot about that. Diez From steve at REMOVE-THIS-cybersource.com.au Wed Dec 3 17:38:22 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 03 Dec 2008 22:38:22 GMT Subject: "as" keyword woes References: <493701f0$0$194$e4fe514c@news.xs4all.nl> Message-ID: <01470229$0$20670$c3e8da3@news.astraweb.com> On Wed, 03 Dec 2008 22:02:24 +0000, Martin P. Hellwig wrote: > Warren DeLano wrote: >> A bottom line / pragmatic question... hopefully not a FAQ. >> >> Why was it necessary to make "as" a reserved keyword? > > Because it can be used at the import statement to let the imported thing > be known under another name? > Something like: > > >>> import xml.etree.ElementTree as ET Martin, that doesn't answer the OP's question *at all*. Python 2.5 uses "as" in that way, and it is not a keyword. >>> import math as MATHS >>> MATHS >>> as = 45 :1: Warning: 'as' will become a reserved keyword in Python 2.6 >>> as :1: Warning: 'as' will become a reserved keyword in Python 2.6 45 I'd guess that the change was to simplify the CPython parser. I have no idea if it was a tiny change or a significant change, if it made a huge difference to Python-dev or a little difference. Perhaps someone on the dev team could comment. While I feel sympathy for the OP, I do have to ask: he's been using Python 2.5 for, what, a couple of years now? How many times did he see the depreciation warning, and almost certainly the pending depreciation warning before that? Python-dev has been talking about making "as" a keyword since at least Python 2.3. Why wait until after version 2.6 is released before saying anything? -- Steven From rNOSPAMon at flownet.com Sun Dec 28 17:26:23 2008 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sun, 28 Dec 2008 14:26:23 -0800 Subject: Need help getting MoinMoin to run under WSGI References: Message-ID: In article , Graham Dumpleton wrote: > On Dec 28, 7:22?pm, Ron Garret wrote: > > In article , > > ?Ron Garret wrote: > > > > > > > > > I successfully installed MoinMoin as a CGI according to the instructions > > > on the moinmo.in site. ?But when I tried to switch over to running it > > > under wsgi it failed thusly: > > > > > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] Traceback (most > > > recent call last): > > > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] ? File > > > "/www/wikis/genesisgroup/moin.wsgi", line 49, in ? > > > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] ? ? from > > > MoinMoin.server.server_wsgi import WsgiConfig, moinmoinApp > > > [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] ImportError: No > > > module named MoinMoin.server.server_wsgi > > > > > The problem, I believe, is that I have both Python 2.4 and 2.5 installed > > > (it's a Debian box) and MM is installed under 2.5 but WSGI is using 2.4. > > > ? > > > I tried to fix this by setting WSGIPythonHome but to no avail. ?I can't > > > figure out what to set it to. ?The instructions say: > > > > > "the WSGIPythonHome directive should be used to specify the exact > > > location of the Python installation corresponding to the version of > > > Python compiled against" > > > > > I have two problems with this. ?First, I didn't compilemod_wsgi, I got > > > it pre-built as a Debian module. ?Second, what does "the exact location > > > of the Python installation" even mean? ?Python2.5 is spread out in at > > > least three different places: /usr/local/bin, /usr/lib/python2.5, and > > > /usr/local/lib/python2.5. ?I've tried setting WSGIPythonHome to all of > > > those (and a few other things as well) and nothing worked. > > > > > Also, "the version of Python compiled against" seems very odd. ?What > > > does that mean? ?Surely I don't have to recompilemod_wsgievery time I > > > change to a new version of Python? > > > > > Help! ?Thanks! > > > > > rg > > > > So never mind, I figured it out. ?I did indeed have to > > recompilemod_wsgifrom source to get it to use Python 2.5. ?(That turned out > > to > > be a major hassle. ?I had to do it twice. ?The first time through it > > made Apache dump core. ?I still don't know why.) > > > > Seems to be working now though. > > It probably crashed the first time because you didn't do a full stop > of Apache and instead just did a reload. Doing a reload may not unload > the Python libraries from Apache process correctly and so would have > been a mix of code for different versions of Python in same process. > > Graham Yes, I don't specifically recall exactly what happened now, but that seems likely. Thanks, rg From google at mrabarnett.plus.com Fri Dec 19 11:16:12 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 19 Dec 2008 16:16:12 +0000 Subject: Generator slower than iterator? In-Reply-To: References: <62013718-57e9-4690-a2be-11e63b9c135b@u18g2000pro.googlegroups.com> Message-ID: <494BC8CC.6020706@mrabarnett.plus.com> Federico Moreira wrote: > Great, 2min 34 secs with the open method =) > > but why? > > ip, sep, rest = line.partition(' ') > match_counter[ip] += 1 > > instead of > > match_counter[line.strip()[0]] += 1 > > strip really takes more time than partition? > > I'm having the same results with both of them right now. > I think you meant split(), not strip(). split() might split the string into many parts, but you want only the first part (at most 1 split), so the extra splits are unnecessary and waste time. split(None, 1) and partition(' ') do at most 1 split, so they don't do unnecessary work. From collin.day.0 at gmail.com Thu Dec 18 21:31:11 2008 From: collin.day.0 at gmail.com (Collin D) Date: Thu, 18 Dec 2008 18:31:11 -0800 (PST) Subject: Factoring Polynomials References: <919062f9-765e-4279-aa26-2c130d4deacf@o4g2000pra.googlegroups.com> <4479b464-3a9b-4dd8-bf66-fea7d9471091@n33g2000pri.googlegroups.com> Message-ID: <661fd2d0-251d-4899-a015-8d257310a159@q26g2000prq.googlegroups.com> On Dec 18, 6:27?pm, Collin D wrote: > On Dec 18, 6:23?pm, "Russ P." wrote: > > > > > > > On Dec 18, 6:17?pm, Collin D wrote: > > > > On Dec 18, 6:12?pm, Collin D wrote: > > > > > On Dec 18, 11:37?am, collin.da... at gmail.com wrote: > > > > > > I am trying to write a simple application to factor polynomials. I > > > > > wrote (simple) raw_input lines to collect the a, b, and c values from > > > > > the user, but I dont know how to implement the quadratic equation > > > > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > > > > into python. Any ideas? > > > > > I completed the code: > > > > > #import > > > > from math import sqrt > > > > > # collect data > > > > a = float(raw_input('Type a value: ')) > > > > b = float(raw_input('Type b value: ')) > > > > c = float(raw_input('Type c value: ')) > > > > > # create solver > > > > def solver(a,b,c): > > > > ? ? if b**2 - 4*a*c < 0: > > > > ? ? ? ? return 'No real solution.' > > > > ? ? else: > > > > ? ? ? ? sol1 = -1 * b + (sqrt(b**2 - 4*a*c)) / 2*a > > > > ? ? ? ? sol2 = -1 * b - (sqrt(b**2 - 4*a*c)) / 2*a > > > > ? ? ? ? return (sol1, sol2) > > > > > # execute > > > > print solver(a,b,c) > > > > > Thanks to everyone who helped... > > > > This really expanded my knowledge on some of the mathematical > > > > functions in Python. > > > > UPDATE: > > > ' > > > > #import > > > from math import sqrt > > > > # collect data > > > a = float(raw_input('Type a value: ')) > > > b = float(raw_input('Type b value: ')) > > > c = float(raw_input('Type c value: ')) > > > > # create solver > > > def solver(a,b,c): > > > ? ? if b**2 - 4*a*c < 0: > > > ? ? ? ? return 'No real solution.' > > > ? ? else: > > > ? ? ? ? sol1 = (-1 * b + (sqrt(b**2 - 4*a*c))) / 2*a > > > ? ? ? ? sol2 = (-1 * b - (sqrt(b**2 - 4*a*c))) / 2*a > > > ? ? ? ? return (sol1, sol2) > > > > # execute > > > print solver(a,b,c) > > > You need to put your denominator, 2*a, in parens. The way it stands, > > you are dividing by 2, then multiplying by a. That's not what you > > want. > > > Also, for better style, I suggest you compute the discriminanat once > > and store it for reuse rather than repeating the expression three > > times.- Hide quoted text - > > > - Show quoted text - > > I see what you mean on the denominator and discriminant. Ill do that.- Hide quoted text - > > - Show quoted text - UPDATE: #import from math import sqrt # collect data a = float(raw_input('Type a value: ')) b = float(raw_input('Type b value: ')) c = float(raw_input('Type c value: ')) # find discriminant disc = b**2 - 4*a*c # create solver def solver(a,b,c): if disc < 0: return 'No real solution.' else: sol1 = (-1 * b + (sqrt(disc))) / (2*a) sol2 = (-1 * b - (sqrt(disc))) / (2*a) return (sol1, sol2) # execute print solver(a,b,c) From lists at cheimes.de Wed Dec 17 12:59:03 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 17 Dec 2008 18:59:03 +0100 Subject: getting object instead of string from dir() In-Reply-To: References: Message-ID: Rominsky schrieb: > I am trying to use dir to generate a list of methods, variables, etc. > I would like to be able to go through the list and seperate the > objects by type using the type() command, but the dir command returns > a list of strings. When I ask for the type of an element, the answer > is always string. How do I point at the variables themselves. A > quick example is: > > a = 5 > b = 2.0 > c = 'c' > > lst = dir() > > for el in lst: > print type(el) for name, obj in vars().iteritems(): print name, obj Christian From nad at acm.org Mon Dec 29 13:46:11 2008 From: nad at acm.org (Ned Deily) Date: Mon, 29 Dec 2008 10:46:11 -0800 Subject: SQL, lite lite lite References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> Message-ID: In article , Philip Semanchuk wrote: > On Dec 29, 2008, at 1:06 PM, Aaron Brady wrote: > > I don't think relational data can be read and written very easily in > > Python. There are some options, such as 'sqllite3', but they are not > > easy. 'sqllite3' statements are valid SQL expressions, which afford > > the entire power of SQL, but contrary to its name, it is not that > > 'lite'. To me, 'lite' is something you could learn (even make!) in an > > afternoon, not a semester; something the size of an ActiveState > > recipe, or a little bigger, maybe a file or two. > [...] > After a look at the syntax you're proposing, I wonder how you feel it > differs from ORMs like SQLAlchemy (for instance). ... and Elixir, a declarative layer on top of SQLAlchemy: -- Ned Deily, nad at acm.org From Edvin.Fuglebakk at ii.uib.no Thu Dec 4 08:00:24 2008 From: Edvin.Fuglebakk at ii.uib.no (Edvin Fuglebakk) Date: Thu, 04 Dec 2008 14:00:24 +0100 Subject: funny generator behaviour Message-ID: <4937D468.1030201@ii.uib.no> I have written a generator that puzzles me: The generator is supposed to create ordered selections of a set of objects. repetition of objects is allowed and the selections should be of a size determined by a pramter to the generator. Now, if I try to accummulate the generated selections into a list I get some peculiar behaviour that I hope maybe some of you can help me understand: Help much appreciated -Edvin #straightforward acumulation. Does not give the expected result >>> d=[] >>> for f in orderedCombinations([1,2],3): ... d.append(f) ... >>> d [[1], [2], [1], [2], [1], [2], [1], [2]] #accumulating shallow copies of the genereated combinations works: >>> d=[] >>> for f in orderedCombinations([1,2],3): ... d.append(f[:]) ... >>> d [[1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 2, 2], [2, 1, 1], [2, 1, 2], [2, 2, 1], [2, 2, 2]] #The generator: def orderedCombinations(pool, k): """ Generator yielding ordered selections of size k with repetition from pool. """ if k == 1: for m in pool: yield [m] if k > 1: for m in pool: for combo in orderedCombinations(pool, k-1): #insert and pop to avoid copying entire list combo.insert(0,m) yield combo combo.pop(0) From marco at sferacarta.com Fri Dec 12 10:51:15 2008 From: marco at sferacarta.com (Marco Mariani) Date: Fri, 12 Dec 2008 16:51:15 +0100 Subject: Removing None objects from a sequence In-Reply-To: References: <01524eee$0$20617$c3e8da3@news.astraweb.com> Message-ID: Filip Gruszczy?ski wrote: > I am not doing it, because I need it. I can as well use "if not elem > is None", I suggest "if elem is not None", which is not quite the same. If you slip such an error in a post, I suggest to practice some time writing correct code before having one-liner contests with your perl-loving friends :) From bdesth.quelquechose at free.quelquepart.fr Sat Dec 6 09:54:44 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 06 Dec 2008 15:54:44 +0100 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: <493a9fed$0$18973$426a34cc@news.free.fr> Daniel Fetchinson a ?crit : > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html > > The proposal is to allow this: > > class C: > def self.method( arg ): > self.value = arg > return self.value > > instead of this: > > class C: > def method( self, arg ): > self.value = arg > return self.value > (snip) > I'd like this new way of defining methods, what do you guys think? -1 As far as I'm concerned, it doesn't add anything to the language, nor doesn't save any typing, so I just don't see the point. And having it co-existing with the normal syntax will only add more confusion. NB : FWIW, I would eventually have voted -0 if it had been proposed for Python 3, and as a _replacement_ (not _alternative_) to the current syntax. But Python 3 is now released, so... From mdgeorge at cs.cornell.edu Wed Dec 3 16:12:54 2008 From: mdgeorge at cs.cornell.edu (Michael George) Date: Wed, 3 Dec 2008 16:12:54 -0500 Subject: building an extension module with autotools? Message-ID: <4936F656.40104@cs.cornell.edu> Hello, (Please CC me in replies, as I am off-list) I'm building an application (a game) in python, with a single C module containing some performance-critical code. I'm trying to figure out the best way to set it up to build. Distutils seems to be designed only for building and distributing code that lives in site-packages. I'd prefer not to install it in the global site-packages, but rather group all of the files together. I've tried using automake, however I'm worried about libtool not getting the options right while building my module. It seems to me like the ideal frankenstein monster would be for automake to invoke distutils to do the actual building. However I'm relatively new to both autotools and distutils, so getting this rigged up has been a bit of a challenge. Can anybody point me to a good example of something like this or give me any pointers? Thanks! --Mike From steve at REMOVE-THIS-cybersource.com.au Wed Dec 17 20:46:18 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Dec 2008 01:46:18 GMT Subject: The rule of literal string References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> <_PmdnU59w62vGtTUnZ2dnUVZ_hSdnZ2d@pdx.net> <34028b73-7807-4e88-80bc-fe31a7b1a2a0@i20g2000prf.googlegroups.com> Message-ID: <0159a2cc$0$20656$c3e8da3@news.astraweb.com> On Wed, 17 Dec 2008 15:25:41 -0800, Chris Rebert wrote: > 2008/12/17 Li Han : >> On 12?18?, ??7?12?, Scott David Daniels wrote: >> Scott wrote: >>> Try: print repr(repr("'")) >>> that might enlighten you. >> >> I found that print( repr( repr( arbitarystring ) ) ) == repr ( >> arbitarystring ) > > As I stated previously, the key rule is: > > eval(repr(something)) == something > > That is, repr() gives a string of Python code that, when evaluated, > results in what you gave to repr(). That is not true in general. >>> from urllib2 import HTTPError >>> h = HTTPError("404 quoth the Raven", None, None, None, None) >>> eval(repr(h)) Traceback (most recent call last): File "", line 1, in File "", line 1, in TypeError: __init__() takes exactly 6 arguments (1 given) Even for built-ins, it's not always true: >>> eval(repr(float('inf'))) Traceback (most recent call last): File "", line 1, in File "", line 1, in NameError: name 'inf' is not defined In other words, there is no guarantee that repr(obj) will round-trip correctly, or at all. It's a Nice To Have, and it will often work, but it's not something you should rely on for arbitrary objects. However, I believe it is true for strings. -- Steven From stefan_ml at behnel.de Thu Dec 18 01:43:21 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 18 Dec 2008 07:43:21 +0100 Subject: C API and memory allocation In-Reply-To: References: Message-ID: <4949f109$0$31329$9b4e6d93@newsspool4.arcor-online.net> Floris Bruynooghe wrote: > I'm slightly confused about some memory allocations in the C API. If you want to reduce the number of things you have to get your head around, learn Cython instead of the raw C-API. It's basically Python, does all the reference counting for you and also reduces the amount of memory handling you have to care about. http://cython.org/ Stefan From stef.mientki at gmail.com Wed Dec 3 10:52:31 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 3 Dec 2008 16:52:31 +0100 Subject: Debugging a Python Program that Hangs In-Reply-To: References: Message-ID: <3dfd60f20812030752p156d307enb3ddd95c29e8eb1f@mail.gmail.com> check winpdb / rpdb2, cheers, Stef On 12/3/08, alex23 wrote: > On Dec 3, 2:19 am, Kevin D. Smith wrote: >> I have a fairly large python program that, when a certain combination >> of options is used, hangs. I have no idea where it is hanging, so >> simply putting in print statements to locate the spot would be quite >> difficult. Unfortunately, ctrl-C'ing the program doesn't print a >> traceback either. Looking through the python debugger documentation, I >> don't see how to run a python program and interactively stopping it >> while it is running. Is there a way to stop within a running python >> program to see where it is getting hung up? > > Hey Kevin, long time fan of your films! (I bet you get that a lot...) > > The trace module might help you identify where it's getting caught up: > > http://www.python.org/doc/2.5.2/lib/trace-cli.html > > -- > http://mail.python.org/mailman/listinfo/python-list > From skip at pobox.com Wed Dec 24 12:10:46 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 24 Dec 2008 11:10:46 -0600 Subject: Spam??? In-Reply-To: References: Message-ID: <18770.27926.482932.23654@montanaro-dyndns-org.local> Alvin> What's with all the spam on the list? Alvin> I humbly request that recaptcha or some other sort Alvin> of captcha be implemented on the registration page. Known issue. The spam filters are currently not applied to messages gatewayed to the mailing list from Usenet. I have been working on a solution as I have time, but it's not there yet. Even if/when the spam filtering on the list gets better you should run your own spam filter anyway. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From robert.kern at gmail.com Mon Dec 22 18:21:23 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 22 Dec 2008 17:21:23 -0600 Subject: 64-bit / 128-bit data element type for array? In-Reply-To: References: <880c8478-8b40-40e0-8597-aef960612f09@s9g2000prg.googlegroups.com> Message-ID: akineko wrote: > Hello Robert, > >> Is that actually a 2s-complement 128-bit unsigned integer, or is it just a >> 128-bit-long chunk of data? > > That is a good question. > A 128-bit data can be anything. > A 128-bit data can be an instrution code (VLIW machines use such wide > instruction). A 128-bit can be a packed ascill (16 chrs). > A 128-bit can be a descriptor (a structure of various fields). > It is probably safe to say that only unsigned 128-bit is required. > (I cannot think of any situations where signed 128-bit is necessary) Ah, good. numpy lets you construct your own data types from the primitives. Since you don't actually need uint128 arithmetic, you don't need a uint128 primitive. You can just use dtype('V16') (meaning "void, 16 bytes long") for the "anything" and "instruction codes" and possible as an intermediate format. Byteswapping will work just fine. Use can use dtype('S16') for the ASCII. If the structure can be described by bytes, then the structured dtypes will work just fine. Unfortunately, we don't support bit-fields. If you need bit-field support, you may want to take a look at Construct. Actually, you may want to look at Construct anyways. http://construct.wikispaces.com/ -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From fakeaddress at nowhere.org Mon Dec 1 08:53:51 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 01 Dec 2008 05:53:51 -0800 Subject: unicode and hashlib In-Reply-To: References: <8af54b5f-d21b-4794-9bce-afc96ea4db74@j11g2000yqg.googlegroups.com> Message-ID: Jeff H wrote: > [...] So once I have character strings transformed > internally to unicode objects, I should encode them in 'utf-8' before > attempting to do things that guess at the proper way to encode them > for further processing.(i.e. hashlib) It looks like hashlib in Python 3 will not even attempt to digest a unicode object. Trying to hash 'abcdefg' in in Python 3.0rc3 I get: TypeError: object supporting the buffer API required I think that's good behavior, except that the error message is likely to send beginners to look up the obscure buffer interface before they find they just need mystring.decode('utf8') or bytes(mystring, 'utf8'). >>>> a='Andr?' >>>> b=unicode(a,'cp1252') >>>> b > u'Andr\xc3\xa9' >>>> hashlib.md5(b.encode('utf-8')).hexdigest() > 'b4e5418a36bc4badfc47deb657a2b50c' Incidentally, MD5 has fallen and SHA-1 is falling. Python's hashlib also includes the stronger SHA-2 family. -- --Bryan From traef at ebasedsecurity.com Sun Dec 21 20:36:33 2008 From: traef at ebasedsecurity.com (Thomas Raef) Date: Sun, 21 Dec 2008 19:36:33 -0600 Subject: Threads, forks, multiplexing - oh my Message-ID: I have a program that was created by someone else and it does it's job beautifully. I now want to run multiple instances of this program on a client, after receiving the command line and args from a broker, dispatcher, whatever you want to call it. This dispatcher will listen for a connection from a client and then pass this client the command line to run this python program. The client will receive the command line, run the python program and then go get another one to run. It might run this program 4 times simultaneously (or so it will seem). I've read where forks will run programs but they replace the calling program - is that correct? Am I reading that right? If so, then my client program will have to use forks so it can run a program. Then are threads to run functions and not full-fledged programs? When, if ever, would I want to look at implementing multiplexing? Please help me clarify and if possible give me some direction for this. Thank you in advance. Thomas J. Raef www.ebasedsecurity.com www.wewatchyourwebsite.com "We Watch Your Website because - you don't" -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp at rebertia.com Mon Dec 22 22:43:46 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 22 Dec 2008 19:43:46 -0800 Subject: iterating initalizations In-Reply-To: References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> Message-ID: <47c890dc0812221943g44bd7222t8c09c088d87e77df@mail.gmail.com> On Mon, Dec 22, 2008 at 7:32 PM, Aaron Stepp wrote: > > Thanks for the help so far, I think I'm starting to get a hang of the > syntax. > > I think I need to state my goal more clearly. > > Instead of writing a long list of initializations like so: > > A = [ ] > B = [ ] > ... > Y = [ ] > Z = [ ] > > I'd like to save space by more elegantly turning this into a loop. If I > need to just write it out, I guess that's ok... but it would be much > cleaner. I'm a composer, not a programmer, so some of this is quite above > me. > So, are these variables supposed to be module-level, or attributes of class pitchAndRhythm, or what? Also, are you going to use the variables normally or are you going to need "variable variables" (e.g. like $$var in PHP, which gives the value of the variable with the name of the string stored in $var)? Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From clp at rebertia.com Mon Dec 8 01:25:12 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 7 Dec 2008 22:25:12 -0800 Subject: A question about reference in Python. In-Reply-To: References: <493CB003.3080209@gmail.com> <47c890dc0812072213q20cb415fjbd4c80e7af7a7ef5@mail.gmail.com> Message-ID: <47c890dc0812072225u7cde16eh9ba69a2f4cdacd16@mail.gmail.com> On Sun, Dec 7, 2008 at 10:17 PM, James Mills wrote: > On Mon, Dec 8, 2008 at 4:13 PM, Chris Rebert wrote: >> The following three lines serve no purpose and can only lead to confusion: >>> value = None >>> prev = None >>> next = None > > You are absolutely right :) > > Updated code: > > > cheers > Jaems > > PS: Sorry Chris :) No apology necessary of course, i just didn't want the newbie OP to pick up any bad Python coding habits. Apologies that I might have phrased my criticism a bit harshly. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > -- > -- > -- "Problems are solved by method" > From jon at ffconsultancy.com Mon Dec 8 08:10:32 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Mon, 08 Dec 2008 13:10:32 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> Message-ID: Xah Lee wrote: > For those interested in this Mathematica problem, i've now cleaned up > the essay with additional comments here: > > ? A Mathematica Optimization Problem > http://xahlee.org/UnixResource_dir/writ/Mathematica_optimization.html In that article you say: > Further, if Intersect is made to take a flat sequence of argument as > in ?Intersect[o_, d_, lambda_, n_, c_, r_, s_]?, then pattern matching can > be avoided by making it into a pure function ?Function?. And when it is > a ?Function?, then Intersect or part of it may be compiled with Compile. > When the code is compiled, the speed should be a order of magnitude > faster. That is incorrect. Mathematica's Compile function cannot handle recursive functions like Intersect. For example: In[1]:= Compile[{n_, _Integer}, If[# == 0, 1, #0[[# n - 1]] #1] &[n]] During evaluation of In[1]:= Compile::fun: Compilation of (If[#1==0,1,#0[[#1 n-1]] #1]&)[Compile`FunctionVariable$435] cannot proceed. It is not possible to compile pure functions with arguments that represent the function itself. >> -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From stefan_ml at behnel.de Fri Dec 19 04:46:22 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 19 Dec 2008 10:46:22 +0100 Subject: C API and memory allocation In-Reply-To: References: <59352942-e976-4ef4-bc40-c8953df0a792@c36g2000prc.googlegroups.com> <0d35b640-71ad-4cde-8869-74878b2f3981@r36g2000prf.googlegroups.com> <494a55fb$0$31873$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <494b6d6e$0$31861$9b4e6d93@newsspool3.arcor-online.net> Aaron Brady wrote: >>> Otherwise you can't know its length or change its reference count. >> The internal representation of Python byte strings is 0 terminated, so >> strlen() will work. > > As MRAB said, Python strings can contain null bytes, Sure, they can. Most byte strings I've seen didn't, though. And if you know that they don't contain any null bytes (UTF-8 serialised XML, for example, or ASCII encoded text, or ...), 's' is just fine. If you need content *and* length, use 's#'. Matter of use case, as usual. Stefan From bthayre at physics.ucsd.edu Mon Dec 8 13:13:20 2008 From: bthayre at physics.ucsd.edu (Robocop) Date: Mon, 8 Dec 2008 10:13:20 -0800 (PST) Subject: Text parsing via regex Message-ID: I'm having a little text parsing problem that i think would be really quick to troubleshoot for someone more versed in python and Regexes. I need to write a simple script that parses some arbitrarily long string every 50 characters, and does not parse text in the middle of words (but ultimately every parsed string should be 50 characters, so adding in white spaces is necessary). So i immediately came up with something along the lines of: string = "a bunch of nonsense that could be really long, or really short depending on the situation" r = re.compile(r".{50}") m = r.match(string) then i started to realize that i didn't know how to do exactly what i wanted. At this point i wanted to find a way to simply use something like: parsed_1, parsed_2,...parsed_n = m.groups() However i'm having several problems. I know that playskool regular expression i wrote above will only parse every 50 characters, and will blindly cut words in half if the parsed string doesn't end with a whitespace. I'm relatively new to regexes and i don't know how to have it take that into account, or even what type of logic i would need to fill in the extra whitespaces to make the string the proper length when avoiding cutting words up. So that's problem #1. Problem #2 is that because the string is of arbitrary length, i never know how many parsed strings i'll have, and thus do not immediately know how many variables need to be created to accompany them. It's easy enough with each pass of the function to find how many i will have by doing: mag = len(string) upper_lim = mag/50 + 1 But i'm not sure how to declare and set them to my parsed strings. Now problem #1 isn't as pressing, i can technically get away with cutting up the words, i'd just prefer not to. The most pressing problem right now is #2. Any help, or suggestions would be great, anything to get me thinking differently is helpful. From rt8396 at gmail.com Tue Dec 23 10:55:32 2008 From: rt8396 at gmail.com (r) Date: Tue, 23 Dec 2008 07:55:32 -0800 (PST) Subject: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> <90f06b27-39da-4f1a-a878-f3972e942d57@s24g2000vbp.googlegroups.com> Message-ID: <62caf93b-0455-4450-9895-8a9d9554f75e@r32g2000vba.googlegroups.com> On Dec 22, 11:12?pm, ajaksu wrote: > On Dec 22, 9:24?pm, r wrote: > > > You know what i hate more than a troll, a spineless jellyfish who goes > > around rating peoples post with one star. You are the lowest form of > > life. You are the same type of person who would key someones car in > > the parking lot. You do not have the balls to face you enemy. > > > If who made a rating were visible, then i would have respect for you, > > but since you lurk in the shadows, you are scum. Come out and face me > > if you dare! > > > I never have rated a post UNLESS i rate it with 5 stars, WHY, you ask, > > Because my balls are so big i walk around bow-legged! F'in ?Cowards! > > That would be me, for at least a dozen of your posts. Glad to know it > was more effective than telling you to shut up or calm down. > > Cnidaria-ly y'rs, > Daniel Well that shows that even lads with tiny nads can be brave, any of the other trolls want to expose them selfs? From mail at johnohagan.com Sat Dec 20 10:27:50 2008 From: mail at johnohagan.com (John O'Hagan) Date: Sat, 20 Dec 2008 15:27:50 +0000 Subject: Namespaces, multiple assignments, and exec() In-Reply-To: <015c5ab8$0$20656$c3e8da3@news.astraweb.com> References: <200812200234.33852.research@johnohagan.com> <015c5ab8$0$20656$c3e8da3@news.astraweb.com> Message-ID: <200812201527.51146.mail@johnohagan.com> On Sat, 20 Dec 2008, Steven D'Aprano wrote: > On Sat, 20 Dec 2008 02:53:16 +0000, MRAB wrote: > > If you're sure you want to use the current namespace then: > > > > for name in namelist: > > vars()[name] = func(name, args) > > Doesn't work inside a function: > >>> def parrot(): > > ... for name in ['A', 'B', 'C']: > ... vars()[name] = ord(name) > ... print vars() > ... print A > ... > > >>> parrot() > > {'A': 65, 'C': 67, 'B': 66, 'name': 'C'} > Traceback (most recent call last): > File "", line 1, in > File "", line 5, in parrot > NameError: global name 'A' is not defined Historical note: I found an old post which stated that this used to work in a function which invoked exec(): http://mail.python.org/pipermail/python-list/2000-September/050840.html but I tried it in 2.5 and it doesn't any longer. Regards, John From andrei.avk at gmail.com Sat Dec 6 15:39:17 2008 From: andrei.avk at gmail.com (Rainy) Date: Sat, 6 Dec 2008 12:39:17 -0800 (PST) Subject: Select, interrupted system call, log rotation? Message-ID: <2b8928dd-4d0c-4e90-ba1e-1c68068c73d1@t3g2000yqa.googlegroups.com> I got an interrupted system call exception in select and I don't know what could have caused it. Here's the error: select.select(inputs, [], [], 9) error: (4, 'Interrupted system call') Caught an exception, shutting down... It's py2.3, on mach architecture. I'm trying to figure out what caused it, and the only idea I have so far is that it could be that I have python's logging system log rotation thing running and I think I've seen a reference somewhere that it uses SIGALRM when log file reaches set size to stop and switch the files. The program was running for about a week without any problem and then I got this exception and after I restarted it it's been running for a few days and I only got the exception once in all that time. Am I going in a completely wrong direction here? I'm thinking of just putting select in try: except: , is that a good idea here? I don't understand signals all that well. Thanks. From bj_666 at gmx.net Tue Dec 9 17:55:02 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 9 Dec 2008 22:55:02 GMT Subject: Is 3.0 worth breaking backward compatibility? References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> Message-ID: <6q8ba6Fb9jsuU1@mid.uni-berlin.de> On Tue, 09 Dec 2008 20:56:19 +0000, Lie Ryan wrote: > Interestingly, many linux _distro_ also inhibit this quick version > number change. Fedora 10, Ubuntu is 2 years old, version 8 (they start > from version 6 not 1). Ubuntu's version numbers don't follow the usual rules but are year and month of release. So this year's releases have "version" 8 and the latest is from october so it is 8.10. Ciao, Marc 'BlackJack' Rintsch From manu3d at gmail.com Sat Dec 13 10:06:48 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Sat, 13 Dec 2008 07:06:48 -0800 (PST) Subject: Bidirectional Networking References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <6qeht0Fc3541U1@mid.individual.net> <782258db-2bdc-45a7-8d8f-7a036d574985@t26g2000prh.googlegroups.com> Message-ID: <8adf1135-ca47-4bed-b490-ab8ae8ccb89f@i18g2000prf.googlegroups.com> On Dec 13, 12:08?am, "James Mills" wrote: > Just as a matter of completeness for my own suggestion, here > is my implementation of your code (using circuits): It's longer! But I bet is a little bit more resilient against all sorts of problems that arise while using network connections. Well, thank you for that. The code I posted in this thread it was just a test to understand how it all works and how it all works with python out of the box. When I get to write the actual application I might end up using circuits instead! Thank you again! Manu From ivan.illarionov at gmail.com Tue Dec 16 16:22:38 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 16 Dec 2008 13:22:38 -0800 (PST) Subject: How to modify a program while it's running? References: Message-ID: <2a748fce-1931-4202-814d-3223fa31e85f@u18g2000pro.googlegroups.com> On Dec 16, 11:25?pm, Joe Strout wrote: > Here's my situation: I'm making an AIM bot, but the AIM server will ? > get annoyed if you log in too frequently (and then lock you out for a ? > while). ?So my usual build-a-little, test-a-little methodology doesn't ? > work too well. > > So I'd like to restructure my app so that it can stay running and stay ? > logged in, yet I can still update and reload at least most of the ? > code. ?But I'm not sure what's the best way to do this. ?Should I move ? > the reloadable code into its own module, and then when I give my bot a ? > "reload" command, have it call reload on that module? ?Will that work, ? > and is there a better way? > > Thanks, > - Joe Take a look at: http://code.djangoproject.com/browser/django/trunk/django/utils/autoreload.py From theiviaxx at gmail.com Wed Dec 10 20:19:01 2008 From: theiviaxx at gmail.com (TheIvIaxx) Date: Wed, 10 Dec 2008 17:19:01 -0800 (PST) Subject: lxml.etree error: xmlSchematronSetValidStructuredErrors References: <33c18d97-598e-4c8c-ac1d-b7c839862eda@a26g2000prf.googlegroups.com> Message-ID: nvm, i got it working. Checking the docs for libxsltmod i was given the tip to add: export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib From saju.pillai at gmail.com Wed Dec 17 01:42:58 2008 From: saju.pillai at gmail.com (Saju Pillai) Date: Tue, 16 Dec 2008 22:42:58 -0800 (PST) Subject: Can anyone suggest a good HTTP/1.1 web client? References: Message-ID: <03019813-2c1c-4489-b370-7e2dbb7f35ce@e1g2000pra.googlegroups.com> On Dec 17, 1:18?am, Kottiyath wrote: > Hi all, > ? ? I have to connect to a secure website every second to get the data > and then post to it. I have been investigating on many web clients in > python, but nothing fits the bill properly. > ? ? The ones I tried implementing are: > ? ? 1. httplib based - I created myself. (I cannot use urllib2 since I > have to transfer files, and urllib2 doesnt have multipart content-type > support) > ? ? 2. Twisted web client. > ? ? I also looked at mechanize etc too. > > ? ? The problems I face are - > ? ? 1. I liked twisted a lot, but when I implemented it, I found that > client support is there only for twisted.web and not twisted.web2. > Since I connect to the same website every time, I would like to have > persistent connections and since twisted.web is HTTP/1.0, persistent > connection support is not yet there. Without persistent connections, I > would have to have TCP connection handshake everytime and it is taking > too much time. > ? ? 2. Since I connect to the website every second, I have to have > many connections running at the same time. I am worried that creating > threads for each connection is going to be a big problem (esp if the > server response is slow), since the processor will get swamped - > especially since there are many other activities going on in the > machine. > ? ?3. I would also like to pipe line the requests - esp if the > response is slow. > > ? ?Other requirements: > ? ?1. HTTPS Support > ? ?2. Connection through proxy. You could take a look at pycurl - python bindings for libcurl. http://pycurl.sourceforge.net/ srp > > ? ?Is there any good web client which I can use straight up? Or would > I have to implement the whole thing myself? It looks like a big beast > and I was wondering whether python provides it straight up. > > Regards > K From jonas.esp at googlemail.com Sun Dec 21 07:21:30 2008 From: jonas.esp at googlemail.com (Kless) Date: Sun, 21 Dec 2008 04:21:30 -0800 (PST) Subject: HMAC with RIPEMD-160 Message-ID: Is there any way of use HMAC with RIPEMD-160? Since that to create a ripemd-160 hash there is to use: h = hashlib.new('ripemd160') it looks that isn't possible For HMAC-SHA256 would be: --------- import hashlib import hmac hm = hmac.new('key', msg='message', digestmod=hashlib.sha256) --------- http://docs.python.org/library/hashlib.html http://docs.python.org/library/hmac.html From lance.ellinghaus at eds.com Thu Dec 25 15:15:48 2008 From: lance.ellinghaus at eds.com (Ellinghaus, Lance) Date: Thu, 25 Dec 2008 15:15:48 -0500 Subject: odfpy examples Message-ID: <752A61D5C34D41478E638FC92AF9051B035638BB@usahm207.amer.corp.eds.com> Has anyone created any complex spreadsheets using odfpy? The samples that come with odfpy are pretty simple and I need some examples of more complex spreadsheets. Thank you, lance -------------- next part -------------- An HTML attachment was scrubbed... URL: From bthayre at physics.ucsd.edu Thu Dec 11 18:17:06 2008 From: bthayre at physics.ucsd.edu (Robocop) Date: Thu, 11 Dec 2008 15:17:06 -0800 (PST) Subject: list organization question References: Message-ID: <79587def-2112-48dd-bab2-95427a2dca8b@y1g2000pra.googlegroups.com> I'm currently trying something along the lines of a sort.compare, but as i'm never sure how many mini-lists i'll end up with, i'm not sure how exactly to begin. Maybe something like a C vector, i.e. a list of pointers to other lists? Or more specifically, compare dates in my list, push that into some empty dates[], then do something along the lines of for looping over dates to create subset lists, and nesting some more compares within these lists to further sort the data by id. Sound crazy or plausible? From lists at cheimes.de Fri Dec 5 16:39:32 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 05 Dec 2008 22:39:32 +0100 Subject: slow Python 3.0 write performance? In-Reply-To: <4939961A.8080205@mrabarnett.plus.com> References: <4939961A.8080205@mrabarnett.plus.com> Message-ID: MRAB wrote: > Does pysco with with Python 3.0 (the homepage says 2.5)? If it does then > that might help! :-) No, it won't help. From info at wingware.com Mon Dec 15 13:04:26 2008 From: info at wingware.com (Wingware) Date: Mon, 15 Dec 2008 13:04:26 -0500 Subject: Wing IDE 3.1.6 released Message-ID: <49469C2A.2050202@wingware.com> Hi, Wingware has released version 3.1.6 of Wing IDE, a bugfix release for all three product levels of Wing IDE. *Release Highlights* This release includes the following: * Added previously missing support for x64 Python on Windows * Avoid auto-starting batch searches when a project is opened * Several vi mode fixes * Added 'watch' item to editor context menu * Recognize type of 'x' in 'from x import y' * Allow debugger to start even if replacing sys.stdin fails * Store list of test files in shared project file (*.wpr) * About 16 other bug fixes: see the change log for details: http://wingware.com/pub/wingide/3.1.6/CHANGELOG.txt *Downloads* Wing IDE Professional and Wing IDE Personal are commercial software and require a license to run. A free trial license can be obtained directly from the product when launched. Wing IDE Pro 3.1.6 http://wingware.com/downloads/wingide/3.1 Wing IDE Personal 3.1.6 http://wingware.com/downloads/wingide-personal/3.1 Wing IDE 101 3.1.6 http://wingware.com/downloads/wingide-101/3.1 *About Wing IDE* Wing IDE is an integrated development environment for the Python programming language. It provides powerful debugging, editing, code intelligence, testing, and search capabilities that reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. Wing IDE is available in three product levels: Wing IDE Professional is the full-featured Python IDE, Wing IDE Personal offers a reduced feature set at a low price, and Wing IDE 101 is a free simplified version designed for teaching entry level programming courses with Python. System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit). Wing IDE 3.1 supports Python versions 2.0.x through 2.5.x. *New Features in Wing 3.1* This release adds the following features not found in Wing 3.0.x: * Support for zip archives * Support for pkg_resources name spaces and eggs * Support for doctest and nose style unit tests (*) * Scan for sys.path changes such as those used in buildout * How-To and support for Google App Engine * Inline context appropriate templates/snippets integrated with autocompleter (*) * Word list driven auto-completion in non-Python files (**) * Quick navigation to files and symbols by typing a fragment (**) * Improved support for Stackless Python * Preference to strip trailing white space on save * Display gi_running and gi_frame for generators * Improved code analysis for Python 2.5 * Other minor features and bug fixes not found in Wing 3.0.x (*)'d items are available in Wing IDE Professional only. (**)'d items are available in Wing IDE Personal or Professional only. Please see the change log for a detailed list of changes: http://wingware.com/pub/wingide/3.1.6/CHANGELOG.txt *Purchasing and Upgrading* Wing 3.1 is a free upgrade for all Wing IDE 3.0 and 3.1 users. Any 2.x license sold after May 2nd 2006 is free to upgrade; others cost 1/2 the normal price to upgrade. Upgrade a 2.x license: https://wingware.com/store/upgrade Purchase a 3.x license: https://wingware.com/store/purchase -- The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com From roy at panix.com Mon Dec 8 10:28:36 2008 From: roy at panix.com (Roy Smith) Date: Mon, 08 Dec 2008 10:28:36 -0500 Subject: Learning Python now coming from Perl References: Message-ID: In article , Nick Craig-Wood wrote: > My favourite mistake when I made the transition was calling methods > without parentheses. In perl it is common to call methods without > parentheses - in python this does absolutely nothing! pychecker does > warn about it though. > > perl -> $object->method > python -> object.method() On the other hand, leaving out the parens returns the function itself, which you can then call later. I've often used this to create data-driven logic. For example, I'm currently working on some code that marshals objects of various types to a wire protocol. I've got something like: encoders = { SM_INT: write_int, SM_SHORT: write_short, SM_FLOAT: write_float, # and so on } class AnyVal: def __init__(self, type, value): self.type = type self.value = value def write_anyval(any): encoders[any.type](any.value) The fact that functions are objects which can be assigned and stored in containers makes this easy to do. From bj_666 at gmx.net Fri Dec 19 08:32:31 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Dec 2008 13:32:31 GMT Subject: How to parsing a sequence of integers References: Message-ID: <6r1m3eFfb5kpU2@mid.uni-berlin.de> On Fri, 19 Dec 2008 21:20:48 +0800, Steven Woody wrote: > Hi, > > I am a newbie and is reading the python book. Could anyone tell me, how > to parsing the following string > "123 100 12 37 ..." > into a list of integers on which I can then apply max()/min()? In [376]: '123 100 12 37'.split() Out[376]: ['123', '100', '12', '37'] In [377]: map(int, '123 100 12 37'.split()) Out[377]: [123, 100, 12, 37] In [378]: max(map(int, '123 100 12 37'.split())) Out[378]: 123 > In additional to max/min, is there something like average()? No, but it's easy to implement with `sum()`, `len()` and ``/``. Ciao, Marc 'BlackJack' Rintsch From jstroud at mbi.ucla.edu Sun Dec 7 04:11:25 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 07 Dec 2008 01:11:25 -0800 Subject: can graphs be made in python as we make in java In-Reply-To: <89ff42d1-6a4c-4d45-a646-238b43e7e8de@s9g2000prm.googlegroups.com> References: <89ff42d1-6a4c-4d45-a646-238b43e7e8de@s9g2000prm.googlegroups.com> Message-ID: suku wrote: > HI folks... > > i need some suggestion on making graphs. Will this be possible > with normal python setup file or do i need to download add ons for > that.. > > help me out I like pychart. It has the advantage of being pure python and makes very nice looking plots. You might also check out matplotlib if you are into heavyweight plotting and interactive application development. James From walterbyrd at iname.com Sat Dec 20 10:19:06 2008 From: walterbyrd at iname.com (walterbyrd) Date: Sat, 20 Dec 2008 07:19:06 -0800 (PST) Subject: WAGs on when django will use Python 3.0? Message-ID: <7f6a70f9-4b97-44f9-86fe-db84ae733077@g1g2000pra.googlegroups.com> Will Django be primarily using Python 3.0 one year from now? Two years from now? Any WAGs? From argus.max at googlemail.com Sun Dec 14 12:43:01 2008 From: argus.max at googlemail.com (Max Argus) Date: Sun, 14 Dec 2008 18:43:01 +0100 Subject: Deepcopying slice objects Message-ID: I stumbled across a thread about that suggests fixing deepcopy to let it copy slice objects. ( http://mail.python.org/pipermail/python-list/2006-August/398206.html). I expected this to work and don't see any reason why it shouldn't in case there is a good reason why it dosen't work can someone please explain it. Max Argus -------------- next part -------------- An HTML attachment was scrubbed... URL: From pacsciadmin at gmail.com Mon Dec 15 21:49:46 2008 From: pacsciadmin at gmail.com (pacsciadmin at gmail.com) Date: Mon, 15 Dec 2008 18:49:46 -0800 (PST) Subject: Copying files in directory Message-ID: <2a815b7d-f01f-4666-bfc6-e9c43a75019b@t3g2000yqa.googlegroups.com> I'm writing a project management system, and I need the ability to accept a directory name and move its contents to another directory. Can someone give me a code sample that will handle this? I can't find any "copying" functions in os or os.path. Regards, LeafStorm From ldo at geek-central.gen.new_zealand Sat Dec 6 02:32:13 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 06 Dec 2008 20:32:13 +1300 Subject: Don't you just love writing this sort of thing :) References: Message-ID: In message , Istvan Albert wrote: > Originally, like many others here I said YIKES! but on a second read, > it is not that bad. It actually grows on you. > > After looking at it one more time I found it neat, very concise > without being unreadable. The key thing is, it's functional, not procedural. Instead of a sequence of statements performing actions, it uses expressions that compute values. Here's another one (from ): def MapRect(SrcRect, DstRect) : """returns a Matrix that does appropriate scaling and translation to map the corners of SrcRect to DstRect.""" return \ ( Matrix.translation(- SrcRect.topleft()) * Matrix.scaling(DstRect.dimensions() / SrcRect.dimensions()) * Matrix.translation(DstRect.topleft()) ) #end MapRect From KDawg44 at gmail.com Tue Dec 16 16:26:56 2008 From: KDawg44 at gmail.com (KDawg44) Date: Tue, 16 Dec 2008 13:26:56 -0800 (PST) Subject: Using Mechanize to Fill Out a Form References: Message-ID: On Dec 16, 3:44?pm, KDawg44 wrote: > Hi, > > I am trying to use the Mechanize module to browse to a site, fill out > a form, and login. ?However, it hangs on the opening of the URL. ?The > URL is https, will this cause the open from mechanize to fail? > > Thanks. > > Kevin Apparently, the HTTPS does not matter, but it is still hanging on the open(URL). I am trying to login to Yahoo!. Code below: #!/usr/bin/python import urllib import urllib2 import mechanize baseURL = 'https://login.yahoo.com/' br = mechanize.Browser() br.set_handle_robots(False) br.addheaders = [('User-Agent', 'Firefox')] #try: br.open(baseURL) It just hangs until I kill it. When I kill it, it gives me the following traceback: Traceback (most recent call last): File "FantasyHockeyLoginAndGetTeam.py", line 14, in br.open(baseURL) File "build/bdist.linux-i686/egg/mechanize/_mechanize.py", line 209, in open File "build/bdist.linux-i686/egg/mechanize/_mechanize.py", line 236, in _mech_open File "build/bdist.linux-i686/egg/mechanize/_opener.py", line 202, in open File "build/bdist.linux-i686/egg/mechanize/_http.py", line 578, in http_response KeyboardInterrupt Thanks for any advice. Kevin From tjreedy at udel.edu Mon Dec 8 20:02:38 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Dec 2008 20:02:38 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Robert Kern wrote: > Terry Reedy wrote: >> Rasmus Fogh wrote: > >>> much, though, just to get code like this to work as intended: >>> alist.append(x) >>> print ('x is present: ', x in alist) >> >> Even if rich comparisons as you propose, the above would *still* not >> necessarily work. Collection classes can define a __contains__ that >> overrides the default and that can do anything, though True/False is >> recommended. > > No, it's actually required. > > In [4]: class A(object): > def __contains__(self, other): > return 'foo' > ...: > ...: > > In [7]: a = A() > > In [8]: 1 in a > Out[8]: True > > > Okay, so it will coerce to True/False for you, but unlike rich > comparisons, the return value must be interpretable as a boolean. Interesting. I did not expect that from "Should return true if item is in self, false otherwise.", but maybe the lowercase true/false is an (undocumented?) abbreviation for 'object with Boolean value True/False'. Of course, if the return value is not so interpretable, or if __contains__ raises an exception, there is no coercion and the OP's code will not work. A different summary of my main point in this thread: Dynamic binding and special method hooks make somewhat generic code possible, but the same special method hooks make absolutely generic code nearly impossible. tjr From xahlee at gmail.com Wed Dec 10 17:08:12 2008 From: xahlee at gmail.com (Xah Lee) Date: Wed, 10 Dec 2008 14:08:12 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <20081226055859.604@gmail.com> Message-ID: Xah Lee wrote: > > Let's say for example, we want to write a function that takes a vector > > (of linear algebra), and return a vector in the same direction but > > with length 1. In linear algebar terminology, the new vector is called > > the ?normalized? vector of the original. > > > For those of you who don't know linear algebra but knows coding, this > > If I were to guess who that would be ... > > > means, we want a function whose input is a list of 3 elements say > > {x,y,z}, and output is also a list of 3 elements, say {a,b,c}, with > > the condition that > > > a = x/Sqrt[x^2+y^2+z^2] > > b = y/Sqrt[x^2+y^2+z^2] > > c = z/Sqrt[x^2+y^2+z^2] > > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, > > you'll have 50 or hundreds lines. Kaz Kylheku wrote: > Really? ``50 or hundreds'' of lines in C? > > #include /* for sqrt */ > > void normalize(double *out, double *in) > { > double denom = sqrt(in[0] * in[0] + in[1] * in[1] + in[2] * in[2]); > > out[0] = in[0]/denom; > out[1] = in[1]/denom; > out[2] = in[2]/denom; > } > > Doh? Kaz, pay attention: Xah wrote: ?Note, that the ?norm? as defined above works for vectors of any dimention, i.e. list of any length.? The essay on the example of Mathematica expressiveness of defining Normalize is now cleaned up and archived at: ? A Example of Mathematica's Expressiveness http://xahlee.org/UnixResource_dir/writ/Mathematica_expressiveness.html Xah ? http://xahlee.org/ ? From bruno.42.desthuilliers at websiteburo.invalid Thu Dec 11 08:22:27 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 11 Dec 2008 14:22:27 +0100 Subject: var or inout parm? In-Reply-To: References: <493cda2a$0$17080$426a34cc@news.free.fr> <47c890dc0812080057r6d117bbcic377cb96de52d973@mail.gmail.com> <1228951784.5698.1.camel@mctell> Message-ID: <494113ff$0$1703$426a34cc@news.free.fr> Joe Strout a ?crit : > On Dec 10, 2008, at 4:29 PM, J. Clifford Dyer wrote: > >>>>> mh at pixar.com wrote: >>>>>> >>>>>> How can I make a "var" parm, where the called function can modify >>>>>> the value of the parameter in the caller? >>>>>> >>> See Also: the earlier heated debate thread over what evaluation >>> strategy Python uses (Survey says!: call-by-object). >>> >> >> Oh dear God. PLEASE don't see also that thread. That way lies madness. >> Just google for call-by-object, and ignore the hell out of that thread. > > Agreed on that point! > > Anyway, to the OP, see Do you really want to start a new flame war, Joe ?-) From python at rgbaz.eu Thu Dec 25 07:17:30 2008 From: python at rgbaz.eu (Python) Date: Thu, 25 Dec 2008 13:17:30 +0100 Subject: os.system('cls') In-Reply-To: References: <05BADA85-33ED-48BF-B251-2CC830D6D55E@rgbaz.eu> Message-ID: On 25 dec 2008, at 12:56, Dennis van Oosterhout wrote: > Hello Arno, > > thanks for the explanation! I have one more question: on the python > site it says it's better to replace the system commands by subprocess > and Popen. > Now I searched for some good example for my specific case (as I have > no idea how it should work and I don't get it any clearer by reading > http://docs.python.org/3.0/library/subprocess.html#module-subprocess) > and I found this: > >> import subprocess >> def clear(): >> subProcess.Popen('clear') > never used it myself either, but from reading the manual i think you need import subprocess subprocess.Open('cls') what you did is create a function that you need to call to execute it (and a capital P typo in subprocess) 'clear' is for *nix systems it won;t work in DOS i think (I'm don;t have windows here...) > But it just doesn't seem to work. Would you have any idea how it > would work? > > Once more thanks for the first answer, >> you;re welcome :) From 20080915.20.wmcclain at spamgourmet.com Mon Dec 8 13:46:16 2008 From: 20080915.20.wmcclain at spamgourmet.com (Bill McClain) Date: 8 Dec 2008 18:46:16 GMT Subject: StringIO in 2.6 and beyond Message-ID: I've just installed 2.6, had been using 2.4. This was working for me: #! /usr/bin/env python import StringIO out = StringIO.StringIO() print >> out, 'hello' I used 2to3, and added import from future to get: #! /usr/bin/env python from __future__ import print_function import io out = io.StringIO() print('hello', file=out) ...which gives an error: Traceback (most recent call last): File "./example.py", line 5, in print('hello', file=out) File "/usr/local/lib/python2.6/io.py", line 1487, in write s.__class__.__name__) TypeError: can't write str to text stream ...which has me stumped. Why can't it? -Bill -- Sattre Press History of Astronomy http://sattre-press.com/ During the 19th Century info at sattre-press.com by Agnes M. Clerke http://sattre-press.com/han.html From david at boddie.org.uk Fri Dec 12 19:17:25 2008 From: david at boddie.org.uk (David Boddie) Date: Sat, 13 Dec 2008 01:17:25 +0100 Subject: PyQt: Pulling Abstract Item Data from Mime Data using Drag and Drop. References: <150086b2-b02d-4204-8c06-b08c0aa119c4@k1g2000prb.googlegroups.com> Message-ID: On Friday 12 December 2008 02:05, Mudcat wrote: > The drag is working up until the point I try to actually retrieve the > data. At that point I get an unhandled Runtime Error saying "no access > to protected functions or signals for objects not created in Python". That's correct, retrieveData() is a protected function in C++ and the QMimeData object was created by the framework, not you, in this case. > Obviously I am not retrieving them in the correct format. Does anyone > know how to convert/retrieve the information into a Python list? You could use the data() method to get the serialized data then try to extract the list item-by-item using the QDataStream class, or perhaps PyQt has a convenience function to unpack the items. Alternatively - and this is a bit speculative - perhaps you can copy the data to another QMimeData object which you have created, and use its retrieveData() method to retrieve the items. You might get a more detailed response by asking on the PyQt mailing list: http://www.riverbankcomputing.com/mailman/listinfo/pyqt Hope this helps, David From jstroud at mbi.ucla.edu Sun Dec 7 19:39:09 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 07 Dec 2008 16:39:09 -0800 Subject: Rich Comparisons Gotcha In-Reply-To: <014c593e$0$20670$c3e8da3@news.astraweb.com> References: <014c593e$0$20670$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Sun, 07 Dec 2008 13:57:54 -0800, James Stroud wrote: > >> Rasmus Fogh wrote: >>>>>> ll1 = [y,1] >>>>>> y in ll1 >>> True >>>>>> ll2 = [1,y] >>>>>> y in ll2 >>> Traceback (most recent call last): >>> File "", line 1, in >>> ValueError: The truth value of an array with more than one element is >>> ambiguous. Use a.any() or a.all() >> I think you could be safe calling this a bug with numpy. > > Only in the sense that there are special cases where the array elements > are all true, or all false, and numpy *could* safely return a bool. But > special cases are not special enough to break the rules. Better for the > numpy caller to write this: > > a.all() # or any() > > instead of: > > try: > bool(a) > except ValueError: > a.all() > > as they would need to do if numpy sometimes returned a bool and sometimes > raised an exception. I'm missing how a.all() solves the problem Rasmus describes, namely that the order of a python *list* affects the results of containment tests by numpy.array. E.g. "y in ll1" and "y in ll2" evaluate to different results in his example. It still seems like a bug in numpy to me, even if too much other stuff is broken if you fix it (in which case it apparently becomes an "issue"). James From joe at strout.net Sun Dec 7 14:56:14 2008 From: joe at strout.net (Joe Strout) Date: Sun, 7 Dec 2008 12:56:14 -0700 Subject: how to get a beep, OS independent ? In-Reply-To: References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> Message-ID: <320A8AF5-DF3F-482F-93BE-073C74AA6462@strout.net> On Dec 7, 2008, at 8:48 AM, Grant Edwards wrote: > On 2008-12-07, Joe Strout wrote: > >> But invoking the standard system beep > > What makes you think there is such a thing as "the standard system > beep"? Because OS X (the platform with which I'm most familiar) certainly has one, and REALbasic has had a "Beep" method for years which works on all platforms. If RB can do it, we can do it too. Best, - Joe From kyosohma at gmail.com Mon Dec 8 16:54:00 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 8 Dec 2008 13:54:00 -0800 (PST) Subject: Calling C# COM (.NET) from python References: <65482a31-8091-486f-8a9b-8f6bdf947af6@w1g2000prk.googlegroups.com> <0e2ec315-a5ef-419e-a224-78ab965db99c@r15g2000prd.googlegroups.com> Message-ID: On Dec 8, 3:33?pm, Andrew Falanga wrote: > On Dec 8, 11:52?am, Mike Driscoll wrote: > > > > > On Dec 8, 11:14?am, Ben Kaplan wrote: > > > > On Dec 8, 2008, at 11:53 AM, Andrew Falanga wrote: > > > > > Hi, > > > > > I've never programmed in python and only have a small understanding of > > > > what is wrapped up in the terms COM and .NET. ?Is there a way of using > > > > python to get a hold of objects written in C# as COM objects using > > > > python? ?I'm looking for ways to avoid VBScript (which, after a couple > > > > of weeks, I've determined to be horrid). ?That is, is there a way of > > > > getting at COM objects in python that's similar to doing a > > > > CreateObject call in VBScript (http://msdn.microsoft.com/en-us/ > > > > library/ > > > > dcw63t7z.aspx)? > > > > > Thanks, > > > > Andy > > > > -- > > > >http://mail.python.org/mailman/listinfo/python-list > > > > I would not deal with COM at all. I personally have not used it, but ? > > > there is a version of python called IronPython that's written in C#, ? > > > so it can use .NET and, I think, other C# objects. Other people will ? > > > probably help you more, but you might want to look into that and maybe ? > > > ask this on the python-win list. > > > As I understand it, IronPython can use anything done in the CLR, so > > technically I could write something in VB.NET, C# or any of the other > > VS languages and then use them from within IronPython. It should be > > noted that IronPython does not support most 3rd party packages that > > are not pure python. As I recall, it doesn't have the complete builtin > > library either, but it's close. > > > Reads the docs and check it out at least. If you already know .NET > > languages, then you'll probably find IronPython helpful. > > > Mike > > To all, thanks for the great replies. ?I've got something to work with > here. ?Thanks to for the link to PyWin32 and the mailing list. ?That > sounds promising as does this IronPython. ?I wished I knew more > of .NET and python more (as my original post claims, I've never > written Python and I only wished I knew the .NET stuff better for > better footing in this). ?I'm very much the proverbial, "fish out of > water," as I'm a UNIX man now stuck in a Windows world. > > Thanks again, > Andy Andy, Welcome to the wonderful world of Python programming. It's fun and cool! Windows is a complex place, but the Python crew on that PyWin32 mailing list will help you out with that stuff and the people here will help you with your more general questions. Last week, there was another beginner who needed some clues for where to go for learning the language. I suggest you read that thread as it had lots of good examples: http://groups.google.com/group/comp.lang.python/browse_frm/thread/29278b3db85a1341# I recommend the Dive Into Python online book too, which is listed in the link above. There are also lots of quality physical books out there. Let me know if you need any suggestions for those. Have a nice day! Mike From wuwei23 at gmail.com Thu Dec 11 12:22:21 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 11 Dec 2008 09:22:21 -0800 (PST) Subject: Preventing execution of a method References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> Message-ID: <764daeef-bfbe-411a-8521-bb114321e4ac@b38g2000prf.googlegroups.com> On Dec 12, 2:35?am, rdmur... at bitdance.com wrote: > There is, however, also the possibility of prefixing the method name > with '__'. ?The invokes 'name mangling', which makes it more difficult > (though not impossible, the idea is to avoid accidents) for the method > to be called from outside the class. That only works for methods, it has no effect on functions or classes within modules: module.py: def __f(): pass class __F(object): def __f(): pass >>> import module as m >>> m.__f >>> m.__F >>> f = m.__F() >>> f.__f Traceback (most recent call last): File "", line 1, in AttributeError: '__F' object has no attribute '__f' >>> f._F__f > From arnodel at googlemail.com Sat Dec 20 04:28:55 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 20 Dec 2008 09:28:55 +0000 Subject: Namespaces, multiple assignments, and exec() References: Message-ID: John O'Hagan writes: > I have a lot of repetitive assignments to make, within a generator, > that use a function outside the generator: > > var1 = func("var1", args) > var2 = func("var2", args) > var3 = func("var3", args) > etc... > > In each case the args are identical, but the first argument is a > string of the name being assigned. It works fine but I'd like to > reduce the clutter by doing the assignments in a loop. I've tried > using exec(): > > for name in name_string_list: > exec(name + ' = func(\"' + name + '\", args)') > > but in the local namespace it doesn't understand func(), and if I give > it globals() it doesn't understand the args, which come from within > the generator. > > What's a good way to do this kind of thing? Your problem is describe in too vague a way to get good answers IMHO. Are var1, var2, ... globals or local to the generator? Can you give some sample code to show what doesn't work? -- Arnaud From martin at v.loewis.de Mon Dec 15 19:05:58 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 16 Dec 2008 01:05:58 +0100 Subject: Problem Python 2.6.1 vs 2.6 & pyWin32 In-Reply-To: <4946ed94$0$22011$426a74cc@news.free.fr> References: <4946754f$0$19000$426a74cc@news.free.fr><4946D09F.6050300@v.loewis.de> <4946ed94$0$22011$426a74cc@news.free.fr> Message-ID: <4946f0e6$0$6492$9b622d9e@news.freenet.de> > I noted, also, than, in some cases, Python26.dll is not copied in > %WINDIR%\system32 > After that, external softs don't find the DLL. Right. Only in "for all users" installations, python26.dll is put into system32. In a "just for me" installation, the user is not expected to have permissions to system32, hence the DLL is put into c:\python26. Regards, Martin From tjreedy at udel.edu Thu Dec 4 13:43:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Dec 2008 13:43:02 -0500 Subject: schizophrenic view of what is white space In-Reply-To: <4938112F.5030706@chamonix.reportlab.co.uk> References: <4937E8E5.2090306@chamonix.reportlab.co.uk> <20081204143337.20272.1236189783.divmod.quotient.15592@ohm> <4938112F.5030706@chamonix.reportlab.co.uk> Message-ID: > so the default behaviour differs for unicode and re working on unicode. > I suppose that won't be true in Python 3. import re print(re.compile(r'\s').search('a b')) print(re.compile(r'\s').search('a\xa0b') ) >>> ================================ RESTART =============== >>> <_sre.SRE_Match object at 0x00ADAA68> <_sre.SRE_Match object at 0x00ADAA68> From jobs.teaching.english.asia at gmail.com Fri Dec 5 23:28:04 2008 From: jobs.teaching.english.asia at gmail.com (Jobs Teaching English in Asia) Date: Fri, 5 Dec 2008 20:28:04 -0800 (PST) Subject: Cambodia TEFL - Gap Year, Travel & Study, Paid Teaching Job - http://www.cambodiatefl.com Message-ID: <00091596-dee3-4435-b675-e02322f8df94@a29g2000pra.googlegroups.com> Cambodia TEFL - Gap Year, Travel & Study, Paid Teaching Job http://www.cambodiatefl.com From lie.1296 at gmail.com Mon Dec 8 02:06:06 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 8 Dec 2008 07:06:06 +0000 (UTC) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> Message-ID: On Sun, 07 Dec 2008 20:56:40 +0000, I V wrote: > So, if we want Python to the programming language of choice for Lacanian > psychoanalysts, perhaps we should adopt the symbol "$" (or even, with > Python 3's support for unicode identifiers, S followed by U+0388) > instead of "self." Is that supposed to be a serious argument or a joke? :) From joe at strout.net Sun Dec 7 20:34:17 2008 From: joe at strout.net (Joe Strout) Date: Sun, 7 Dec 2008 18:34:17 -0700 Subject: how to get a beep, OS independent ? In-Reply-To: <014c575a$0$20670$c3e8da3@news.astraweb.com> References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> <014c575a$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Dec 7, 2008, at 4:43 PM, Steven D'Aprano wrote: > Of course, if you're volunteering to write such a standard system beep > for Python, I for one would be grateful. I am. But where should I put it? Assuming we don't want to wait for the (understandably) lengthy and contentious process required to add something to the Python system libraries, where would be the next best place for this sort of simple OS abstraction layer? Thanks, - Joe From lewis.sarah93 at yahoo.com Thu Dec 4 23:49:12 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 20:49:12 -0800 (PST) Subject: Get out of Debt Message-ID: Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 18:19:06 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Dec 2008 23:19:06 GMT Subject: A more pythonic way of writting References: <35d176ed-df5f-46b4-8321-4814fcc4398c@f3g2000yqf.googlegroups.com> <8de7622d-28a7-4f96-9fb0-21cda357dcf3@r36g2000prf.googlegroups.com> Message-ID: <0149aea6$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 07:44:21 -0800, eric wrote: > I like to believe that the less the 'debug pointer' stands in the python > code, the fastest the code is (or is potentially) What's a debug pointer? Pre-mature optimization is the root of evil in programming. Unless you have actually *measured* the speed of the code, how do you know you aren't making it slower instead of faster? Experience with other languages often is misleading when programming with Python. If you are used to programming in C, for example, then you will tend to program one way because comparisons are fast and moving records is slow. But in Python, comparisons can be slow and moving records is fast, so the C programmer's intuitions about "fast code" are often pessimations instead of optimizations. -- Steven From febaen at gmail.com Fri Dec 12 07:05:21 2008 From: febaen at gmail.com (feba) Date: Fri, 12 Dec 2008 04:05:21 -0800 (PST) Subject: (Very Newbie) Problems defining a variable References: <49425146$0$8495$426a74cc@news.free.fr> Message-ID: <11c53a4a-de1e-4bee-ad60-a05befb6cbf4@a12g2000yqm.googlegroups.com> On Dec 12, 5:56?am, Bruno Desthuilliers wrote: > feb... at gmail.com a ?crit : > > > > > #!/usr/bin/python > > #Py3k, UTF-8 > > > bank = int(input("How much money is in your account?\n>>")) > > target = int(input("How much money would you like to earn each year? > > \n>>")) > > > interest = 0 > > i = 0 > > > while interest < target: > > #determine the interest rate to use > > ? ?if bank >= 9999: > > ? ? ? ? ? ?rate = 0.006 > > ? ?elif bank >= 10000 and bank <= 24999: > > ? ? ? ? ? ?rate = 0.0085 > > ? ?elif bank >= 25000 and bank <= 49999: > > ? ? ? ? ? ?rate = 0.0124 > > ? ?elif bank >= 50000 and bank <= 99999: > > ? ? ? ? ? ?rate = 0.0149 > > ? ?elif bank >= 100000: > > ? ? ? ? ? ?rate = 0.0173 > > (snip) > > > I'm pretty certain that that is also the problem in the code. I'm > > pretty sure it's a problem with the 'if' statements', and it looks > > like it's one of those mistakes that's so simple you look back on it > > and laugh at yourself. If you put in a bank number <= 9999, it fails, > > saying ?"NameError: name 'rate' is not defined". ?If you put in one > > higher, it runs correctly, but thinks that the rate is 0.006 > > Indeed. That's what you asked for. If bank is >= 9999, then rate will be > set to 0.006, and the following tests will be skipped. Else - since you > just don't handle the case -, rate is not defined at all. > > I guess you wanted your first test to be: > > ? ? if bank <= 9999: > ? ? ? ?... > > FWIW, when using if/elif that way, make sure you always end with a > "default" else clause (even if just to signal you didn't expect to be > there...) > > HTH that's it, thanks! was confused with it being basically in a column of all >= *. I replaced it with if bank <= 0: print("You're in the red!") quit() elif bank >= 1 and bank <= 9999: rate = 0.0060 elif bank >= 10000 and bank <= 24999: rate = 0.0085 elif bank >= 25000 and bank <= 49999: rate = 0.0124 elif bank >= 50000 and bank <= 99999: rate = 0.0149 elif bank >= 100000: rate = 0.0173 else: print("What's this doing here?") which also changes it to keep it from going on forever if you put in a negative amount. Out of curiosity, would you still recommend applying an 'else' clause in this case? I don't see how it could ever be triggered, even if there's an error of some kind From python.list at tim.thechases.com Sun Dec 14 14:34:24 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 14 Dec 2008 13:34:24 -0600 Subject: Why %e not in time.strftime directives? In-Reply-To: <4e307e0f0812132252y35ed5cdep40eabaa54f1d8967@mail.gmail.com> References: <38f9c4ba-d96d-47e1-b718-562bdc6718e9@t26g2000prh.googlegroups.com> <4943D9AB.7040006@tim.thechases.com> <4e307e0f0812132252y35ed5cdep40eabaa54f1d8967@mail.gmail.com> Message-ID: <49455FC0.5070807@tim.thechases.com> >>> Any special reasons? >> Because it is there (at least on my Debian box)? > > But not on windows :( >>>> import time >>>> time.strftime("%e") > '' Guess you'll have to take it up with the authors of strftime() at Microsoft :) >> The full set of format codes supported varies across >> platforms, because Python calls the platform C library's >> strftime() function, and platform variations are common. >> >> So if your underlying C implementation of strftime() supports "%e", then >> Python will. My guess is that the same applies to time.strftime as it does >> to datetime.strftime >> >> The docs list ones that are fairly cross-platform. However, it would seem >> that not all platforms support "%e" If you don't have any luck convincing Microsoft to add "%e" to their strftime implementation, you can use strftime('%d').lstrip('0').rjust(2) to replicate the desired behavior :) -tkc From Mr.HassanShabbir at gmail.com Thu Dec 11 08:45:13 2008 From: Mr.HassanShabbir at gmail.com (Explore_Imagination) Date: Thu, 11 Dec 2008 05:45:13 -0800 (PST) Subject: How to convert uint64 in C into Python 32bit Object [ I am using Python2.2 ] References: <069f0d65-a3d5-4e8f-a85b-c53743ab99d0@i18g2000prf.googlegroups.com> <8485fb8f-4425-436d-9e0b-2079c80c9802@q26g2000prq.googlegroups.com> Message-ID: <6b710b67-0e91-4c55-8ef7-23891addfc51@q26g2000prq.googlegroups.com> On Dec 11, 4:45 am, John Machin wrote: > On Dec 11, 9:49 am, Explore_Imagination > wrote: > > > Hi all > > > I am new to C and python ... I want to convert C data type uint64 > > variable into the Python 32bit Object. I am currently using Python 2.2 > > [ It is necessary to use it ] > > > Kindly give your suggestion how and in which way I can achieve this > > task. > > I'm not sure what you mean by "the Python 32bit Object". A Python int > object holds a signed 32-bit integer. A Python long object holds a > signed integer of arbitrary size. You will need to convert your uint64 > into a Python long; then, if necessary, check that the result will fit > in an int (result <= sys.maxint). > > If the "C variable" is in an 8-byte string that you have read from a > file, the unpack function in the struct module will do the job. > Assuming your computer is little-endian: > > >>> maxu64 = '\xff' * 8 # example input string > >>> import struct > >>> result = struct.unpack(' >>> result > > 18446744073709551615L>>> 2 ** 64 - 1 > > 18446744073709551615L > > If however you mean that in C code you need to build a Python object > to pass over to Python code: According to the Python/C API Reference > Manual (http://www.python.org/doc/2.2.3/api/longObjects.html): > > PyObject* PyLong_FromUnsignedLongLong(unsigned long long v) > Return value: New reference. > Returns a new PyLongObject object from a C unsigned long long, or > NULL on failure. > > If however you mean something else, .... > > HTH, > John Thanks for your feedback ... Actually I want to pass unit64 variable in C to python but at the same time I want to have a generic code which should work on both little-endian and big endian architectures Any suggestions ? From castironpi at gmail.com Sat Dec 13 15:53:11 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 13 Dec 2008 12:53:11 -0800 (PST) Subject: stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> Message-ID: <1ff0d642-b560-433c-b793-3a05f5b051b9@g1g2000pra.googlegroups.com> On Dec 13, 1:17?pm, Duncan Booth wrote: > "Diez B. Roggisch" wrote: > > > > > David Hl??ik schrieb: > >> Hi guys, > > >> i am really sorry for making offtopic, hope you will not kill me, but > >> this is for me life important problem which needs to be solved within > >> next 12 hours.. > > >> I have to create stable algorithm for sorting n numbers from interval > >> [1,n^2] with time complexity O(n) . > > >> Can someone please give me a hint. Would be very very thankful! > > > Unless I grossly miss out on something in computer science 101, the > > lower bound for sorting is O(n * log_2 n). Which makes your task > > impossible, unless there is something to be assumed about the > > distribution of numbers in your sequence. > > > Who has given you that assignment - a professor? Or some friend who's > > playing tricks on you? > > I think you must have fallen asleep during CS101. The lower bound for > sorting where you make a two way branch at each step is O(n * log_2 n), but > if you can choose between k possible orderings in a single comparison you > can get O(n * log_k n). > > To beat n * log_2 n just use a bucket sort: for numbers with a known > maximum you can sort them digit by digit for O(n log_k n), and if you don't > restrict yourself to decimal then k can be as large as you want, so for the > problem in question I think you can set k=n and (log_n n)==1 so you get > O(n) Minor detail: with k= n, you have log_n (n^2)= 2, so you get O(2n)= O (n). Same answer. The generic sort theorems also assume you can compare arbitrarily large numbers in constant time, which isn't true. That is, for any given machine, there exist numbers that you can't compare on them in constant time. But with a known upper bound k, you can just use a k- bit machine. So, what's the group policy on helping with homework? From steve at holdenweb.com Tue Dec 30 08:48:31 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Dec 2008 08:48:31 -0500 Subject: Triple quoted string in exec function ? In-Reply-To: <495A253B.6010003@gmail.com> References: <495A253B.6010003@gmail.com> Message-ID: Stef Mientki wrote: > hello, > > I'm running scripts, with the execute function (Python 2.5), > and it seems that triple quoted strings are not allowed. > > Is there a workaround, > or is this a fundamental problem of the exec-function ? > If you think about it, it should be obvious that you can't surround a string to be compiled with any of the quotes that appear inside the string to be compiled. That's about the only limitation I am aware of. And, by the way, exec is a *statement*, not a function! >>> exec """print '''This is ... a long string''' ... """ This is a long string >>> regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From alessio.pace at gmail.com Mon Dec 1 08:36:16 2008 From: alessio.pace at gmail.com (Alessio Pace) Date: Mon, 1 Dec 2008 05:36:16 -0800 (PST) Subject: How to distribute a Python app together with its dependencies? References: <35377946-378c-484d-88cc-396145090d2f@l39g2000yqn.googlegroups.com> Message-ID: On 1 Dic, 10:37, BlueBird wrote: > Alessio Pace wrote: > > Hi, > > > I have to distribute a Python application which relies on an external > > library, and I'm not very fluent in this kind of stuff with Python (I > > come from the Java world where I would have used the Maven build tool > > to create an "assembly with dependencies" of all it is needed to run > > the app), so I was wondering if someone here could give me some > > suggestions :-) > > > The external library is generally not present on the machines where I > > have to distribute my app, and the set of machines on which I have to > > distribute this application is not known a priori (it is just known > > they are Unix systems). In fact by means of SSH I will have to copy > > (and install) the app+library and make it runnable onto the specified > > destination(s). > > I have never used it myself, but bbfreeze claims to create packaged > versions of an application, for windows and Unix : > > http://pypi.python.org/pypi/bbfreeze/0.95.2 > Thank you. What's the difference with "Freeze" shipped with Python, or with PyInstaller ? Do you have experiences with any of them? From prologic at shortcircuit.net.au Thu Dec 4 05:53:38 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 4 Dec 2008 20:53:38 +1000 Subject: "as" keyword woes In-Reply-To: <7dudnSS7uIn_KarUnZ2dnUVZ_tTinZ2d@earthlink.com> References: <7dudnSS7uIn_KarUnZ2dnUVZ_tTinZ2d@earthlink.com> Message-ID: One of the things I'd like to point out here is what we've been learning in new job during Induction Training... That is, it's part of the coding standard and design standards to name variables sensibly. For instance, naming a variable "db" when it's really a "database" object is a no no. Instead you should be naming it "db". Another example, "db_id" vs. "database_id". So my point here is that you should not really/ideally be naming variables with such short un-meaningful names such as "as", "if", "id", "xs" or what not. Readability of your code becomes very important especially if you're working with many developers over time. 1. Use sensible meaningful names. 2. Don't use abbreviations. cheers James On Thu, Dec 4, 2008 at 8:43 PM, Dennis Lee Bieber wrote: > On Thu, 4 Dec 2008 01:28:56 -0800, "Warren DeLano" > declaimed the following in comp.lang.python: > >> In addition, note that my choice of a concise method identifier affects >> only my users. Python's introduction of a new keyword affects the >> entire Python world code base, so perhaps you should be directing your >> "choose better names" criticism in another direction? >> > Dropping in... > > If a "chosen name" mirrors a syntactic element -- whether reserved > or not -- I'd consider that name potentially ambiguous or conflicted. > > While "if" has been long a reserved word, I can as easily see > someone using "if" as a shorthand name for "interface". And if "if" were > not a reserved word, one might encounter code on the lines of > > if = if + 1 > > which is quite obnoxious to my eyes... or maybe > > if if.connected: > if.close() > > > Since > > import x as y > > has been a syntactic capability for some time, even if not reserved, I'd > have avoided using "as" as anything other than that usage... > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From kkylheku at gmail.com Wed Dec 10 19:34:00 2008 From: kkylheku at gmail.com (Kaz Kylheku) Date: Thu, 11 Dec 2008 00:34:00 +0000 (UTC) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <20081226055859.604@gmail.com> Message-ID: <20081226091336.487@gmail.com> On 2008-12-10, Xah Lee wrote: > Xah Lee wrote: >> > means, we want a function whose input is a list of 3 elements say ^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^ > Kaz, pay attention: [ reformatted to 7 bit USASCII ] > Xah wrote: Note, that the norm > of any dimention, i.e. list of any length. It was coded to the above requirements. From anthony.tolle at gmail.com Mon Dec 8 12:09:30 2008 From: anthony.tolle at gmail.com (anthony.tolle at gmail.com) Date: Mon, 8 Dec 2008 09:09:30 -0800 (PST) Subject: Guido's new method definition idea References: <014a071a$0$20670$c3e8da3@news.astraweb.com> <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> Message-ID: <08049caf-04a4-45ff-afbc-212ab40a43a1@v13g2000yqm.googlegroups.com> On Dec 8, 12:01?pm, anthony.to... at gmail.com wrote: > > It would be nice to be able to do the following instead: > > class C: > ? ? def createfunc(self): > ? ? ? ? def self.func(arg): > ? ? ? ? ? ? return arg + 1 > The above example should have read as follows: class C: def createfunc(self, arg): def self.func(arg): return arg + 1 ----- Anthony Tolle From n.kottiyath at gmail.com Wed Dec 24 14:08:27 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Wed, 24 Dec 2008 11:08:27 -0800 (PST) Subject: Iterating over objects of a class References: <2df27de3-7fa3-4ac9-acd9-f946939517cf@r37g2000prr.googlegroups.com> <6rfb7iF1fg5rU1@mid.uni-berlin.de> <7f47994f-13b6-45c4-920a-83aa72282bec@i20g2000prf.googlegroups.com> Message-ID: <77eaa70f-971b-4274-8136-0961313a34a7@f40g2000pri.googlegroups.com> On Dec 24, 11:48?pm, "Gabriel Genellina" wrote: > En Wed, 24 Dec 2008 16:18:55 -0200, Kottiyath ? > escribi?: > > >> The other thing to remember is that because the 'registry' contains > >> references to the instances, they won't be garbage collected. > > > Is there any other way out in this case? > > I have factory methods - and I have to loop over them - sort of Chain > > of Responsibility pattern. > > Having a registry inside the class instance and looping through them > > was the only clean thing I could think of. > > I understand that garbage collection would be an issue - but is there > > any way out? > > You may keep all that structures - just use weak references (see the ? > weakref module). > There isn't a WeakList nor WeakSet out-of-the-box but you may use a ? > WeakKeyDictionary (set the value to anything, None by example). > > -- > Gabriel Genellina Thank you very much, Gabriel. I am very thankful to everyone. From steve at holdenweb.com Thu Dec 18 16:37:45 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 18 Dec 2008 16:37:45 -0500 Subject: confused about __str__ vs. __repr__ In-Reply-To: References: <494A5ACA.8060205@wildenhain.de> Message-ID: Neal Becker wrote: > Mel wrote: > >> Neal Becker wrote: >> >>> Tino Wildenhain wrote: >>> >>>> Neal Becker wrote: >>>>> Reading some FAQ, I see that __str__ is "meant for human eyes". >>>>> >>>>> But it seems that: >>>>> class X(object): >>>>> def __str__(self): >>>>> return "str" >>>>> def __repr__(self): >>>>> return "repr" >>>>> >>>>> x = X() >>>>> d = {0 : x} >>>>> print d >>>>> {0: repr} >>>>> >>>>> So if __str__ is "meant for human eyes", then why isn't print using it! >>>> it is: >>>> >>>> > print x >>>> str >>>> >>>> but dict just uses repr() for all its childs to print. >>>> >>>> T. >>> That makes no sense to me. If I call 'print' on a container, why >>> wouldn't >>> it recursively print on the contained objects? Since print means call >>> str, printing a container should recursively call str on the objects. >> Basically because there are too many right ways to format the resulting >> report. Space separated? Tab separated? One per line? Boxes around >> them? As HTML definition lists? Creating a standard report form would >> take a lot of work and wouldn't, finally, solve very many peoples' >> problems. >> >> Mel. >> > Thanks, but the question of how to format the container is different from how to format the primitive elements of the container. I was suggesting that printing an element of a container should be consistent with printing the element without the container, i.e., > > print [a] > should be consistent with > print a > Indeed, but that only demonstrates that you have failed to take the point of the more perspicacious replied to your query. Python is trying to avoid throwing away useful information. The only people who would want to see a representation of a data structure such as a list are programmers: if you want to show a list of values to a regular user you format it in some required way. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From skip at pobox.com Sun Dec 21 09:59:53 2008 From: skip at pobox.com (skip at pobox.com) Date: Sun, 21 Dec 2008 08:59:53 -0600 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <6r6hcmFfb643U2@mid.uni-berlin.de> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <6r6hcmFfb643U2@mid.uni-berlin.de> Message-ID: <18766.23017.450136.943072@montanaro-dyndns-org.local> Marc> Many newbie code I have seen avoids it by string concatenation: Marc> greeting = 'Hello, my name is ' + name + ' and I am ' + str(age) + ' old.' Marc> That's some kind of indirect complaint. :-) I see Python code like that written by people with a C/C++ background. I don't think you can necessarily chalk that up to %-string avoidance. They learn that + will concatenate two strings and don't look further. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From prologic at shortcircuit.net.au Tue Dec 2 09:44:23 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 3 Dec 2008 00:44:23 +1000 Subject: Running a Python script from crontab In-Reply-To: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> Message-ID: Put your main function in a big try, except. Catch any and all errors and log them. Example: def main(): try: do_something() except Exception, error: log("ERROR: %s" % error) log(format_exc()) Hope this helps. cheers James On Wed, Dec 3, 2008 at 12:35 AM, Astley Le Jasper wrote: > I need help ... I've been looking at this every evening for over a > week now. I'd like to see my kids again! > > I have script that runs fine in the terminal but when I try to run it > in a crontab for either myself or root, it bails out. > > The trouble is that obviously I get no console when using crontab so > can't see any traceback. I use logging which shows 'info' messages as > the script is working, but no error messages. I've peppered it with > debug messages to try to track it down to a line, but it stops it the > middle of appending data to a list. I'd expect it to bail out when > calling a module or reading/writing to a different file. > > Is there any way of getting more info from the app, like popping up a > console while its running? > > my crontab is: > > 30 15 * * * cd /home/myusername/src && python myscript.py > > ALJ > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From benjamin.kaplan at case.edu Fri Dec 12 15:52:40 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 12 Dec 2008 15:52:40 -0500 Subject: Testing against different versions of Python In-Reply-To: <2678157f0812121142y2afcf3bey254dd2b74f61e423@mail.gmail.com> References: <2678157f0812121142y2afcf3bey254dd2b74f61e423@mail.gmail.com> Message-ID: On Fri, Dec 12, 2008 at 2:42 PM, mercado wrote: > What is the best way to go about testing against different versions of > Python? For example, I have 2.5.2 installed on my machine (Ubuntu Hardy > 8.04), and I want to test a script against 2.5.2 and 2.5.1 (and possibly > other versions as well). > There are no incompatibilities between 2.5.2 and 2.5.1, unless you were relying on a bug in your code. AFAIK, the only way to test it against both would be to compile 2.5.1 yourself. Then, /usr/bin/python would point to 2.5.2 and /usr/local/bin/python would point to python 2.5.1. To test your script against 2.4, just install the Python2.4 package from apt and invoke the interpreter with the command python2.4 instead of python. The same thing goes for python 2.3. Intrepid has a package for Python 3 as well, if you are willing to do a distro upgrade. > > Thanks in advance. > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstroud at mbi.ucla.edu Sun Dec 7 22:36:17 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 07 Dec 2008 19:36:17 -0800 Subject: Rich Comparisons Gotcha In-Reply-To: References: <014c593e$0$20670$c3e8da3@news.astraweb.com> Message-ID: Robert Kern wrote: > James Stroud wrote: >> I'm missing how a.all() solves the problem Rasmus describes, namely >> that the order of a python *list* affects the results of containment >> tests by numpy.array. E.g. "y in ll1" and "y in ll2" evaluate to >> different results in his example. It still seems like a bug in numpy >> to me, even if too much other stuff is broken if you fix it (in which >> case it apparently becomes an "issue"). > > It's an issue, if anything, not a bug. There is no consistent > implementation of bool(some_array) that works in all cases. numpy's > predecessor Numeric used to implement this as returning True if at least > one element was non-zero. This works well for bool(x!=y) (which is > equivalent to (x!=y).any()) but does not work well for bool(x==y) (which > should be (x==y).all()), but many people got confused and thought that > bool(x==y) worked. When we made numpy, we decided to explicitly not > allow bool(some_array) so that people will not write buggy code like > this again. > > The deficiency is in the feature of rich comparisons, not numpy's > implementation of it. __eq__() is allowed to return non-booleans; > however, there are some parts of Python's implementation like > list.__contains__() that still expect the return value of __eq__() to be > meaningfully cast to a boolean. > You have explained py> 112 = [1, y] py> y in 112 Traceback (most recent call last): File "", line 1, in ValueError: The truth value of an array with more than one element is... but not py> ll1 = [y,1] py> y in ll1 True It's this discrepancy that seems like a bug, not that a ValueError is raised in the former case, which is perfectly reasonable to me. All I can imagine is that something like the following lives in the bowels of the python code for list: def __contains__(self, other): foundit = False for i, v in enumerate(self): if i == 0: # evaluates to bool numpy array foundit = one_kind_of_test(v, other) else: # raises exception for numpy array foundit = another_kind_of_test(v, other) if foundit: break return foundit I'm trying to imagine some other way to get the results mentioned but I honestly can't. It's beyond me why someone would do such a thing, but perhaps it's an optimization of some sort. James From upton at virginia.edu Sat Dec 13 14:08:19 2008 From: upton at virginia.edu (Dan Upton) Date: Sat, 13 Dec 2008 14:08:19 -0500 Subject: [OT] stable algorithm with complexity O(n) In-Reply-To: References: <6qidmbFc4qduU1@mid.uni-berlin.de> Message-ID: <5504f9ac0812131108n25d867d4x3ff247dae5230fe5@mail.gmail.com> On Sat, Dec 13, 2008 at 2:00 PM, David Hl??ik wrote: >> Unless I grossly miss out on something in computer science 101, the lower >> bound for sorting is O(n * log_2 n). Which makes your task impossible, >> unless there is something to be assumed about the distribution of numbers in >> your sequence. This is only true for comparison-based sorts. > > There is n numbers from interval [1 , n^2] > I should do measurement for : > n = 500, 1000, 1500, 2000, ..., 4500, 5000 > > O(n) means linear complexivity, so complexivity of algorithmus must be > linear, which i have to prove. > > >> >> Who has given you that assignment - a professor? Or some friend who's >> playing tricks on you? > > It is official assignment , by professor from Data Structures & > Algorithms course. > > Thanks in advance! >> >> Diez >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > -- > http://mail.python.org/mailman/listinfo/python-list > Look at things like bucket sort and radix sort. You can also do tricky things like translating your problem domain by making a fixed number of linear-time passes without affecting the asymptotic run time. (Hopefully that's helpful... don't want to give too much away on a homework assignment, plus tricky algorithms have never been my strong suit.) From jcd at sdf.lonestar.org Mon Dec 8 16:05:36 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 08 Dec 2008 16:05:36 -0500 Subject: how to get a beep, OS independent ? In-Reply-To: <6q2sjfFai65qU1@mid.individual.net> References: <6q2sjfFai65qU1@mid.individual.net> Message-ID: <1228770336.5709.37.camel@aalcdl07.lib.unc.edu> On Sun, 2008-12-07 at 21:13 +0000, Peter Pearson wrote: > On Sun, 07 Dec 2008 00:40:53 +0100, Stef Mientki wrote: > > > > I want to give a small beep, > > for windows there's message-beep, > > and there seems to be something like " curses" , > > but that package seems to be totally broken in P2.5 for windows. > > > > Any other suggestions ? > > Many people have suggested sending an ASCII 07 to your > terminal window, but sometimes you don't have a terminal > window. > > Then there's the question of using the sound card versus > using the PC speaker. Too complicated for me. > > I used a kluge: a short C program that beeps the way I want, > in this case using ioctl(fd,KDMKTONE,arg) on /dev/tty0 (this > is Linux). The program has enough privileges to execute > even when run by unprivileged users, and of course can be > invoked by whatever language you're working in. > If you're already using /dev/tty0, why not just open a file object on /dev/tty0, and write "\a"=="\x07" to that. No C required. #!/usr/bin/env python nonstdout = file("/dev/tty0") nonstdout.write("\a") nonstdout.flush() (same permissions caveats apply) On the other hand, the OP was looking for a cross-platform solution. I don't think Windows has a /dev/tty0, but I don't work on windows, so I can't help with cross platform issues. Cheers, Cliff From xahlee at gmail.com Mon Dec 1 02:23:43 2008 From: xahlee at gmail.com (Xah Lee) Date: Sun, 30 Nov 2008 23:23:43 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: On Nov 30, 7:30 pm, Xah Lee wrote: > Wolfram Research's Mathematica Version 7 has just been released. > > See: http://www.wolfram.com/products/mathematica/index.html > > Among it's marketing material, it has a section on how mathematica > compares to competitors. http://www.wolfram.com/products/mathematica/analysis/ Stephen Wolfram has a blog entry about Mathematica 7. Quite amazing: http://blog.wolfram.com/2008/11/18/surprise-mathematica-70-released-today/ Mathematica today in comparsion to all other existing langs, can be perhaps compared to how lisp was to other langs in the say 1980s: Quite far beyond all. Seeing how lispers today still talking about how to do basic list processing with its unusable cons, and how they get giddy with 1980's macros (as opposed to full term rewriting), and still lack pattern matching, one feels kinda sad. see also: ? Fundamental Problems of Lisp http://xahlee.org/UnixResource_dir/writ/lisp_problems.html Xah ? http://xahlee.org/ ? From news123 at free.fr Sun Dec 7 06:43:13 2008 From: news123 at free.fr (News123) Date: Sun, 07 Dec 2008 12:43:13 +0100 Subject: Guido's new method definition idea In-Reply-To: References: <493abe2e$0$15998$426a34cc@news.free.fr> Message-ID: <493bb6d1$0$10599$426a74cc@news.free.fr> Sorry Dennis, I don't understand your answer. I'm not very knowledgable with all the OO vocabulary, but just use OO. self.a , self.b , self.c are stored in the object and could later be used by other object-methods. like def print_a_b_c(self): print self,a,self.b,self.c the name 'class_elements' was just a suggestion it could be also something like 'auto_prepend_self' or whatever. bye N Dennis Lee Bieber wrote: > On Sat, 06 Dec 2008 19:02:22 +0100, News123 declaimed > the following in comp.lang.python: > > >> example: >> class C: >> class_elements a,b,c,d >> >> def method(self,arg): >> global d >> a,b,c = arg[0..3] >> d = a + b >> self.e = a + d >> >> instead of >> class C: >> def method(self,arg): >> self.a,self.b,self.c,self.d = arg[0..4] >> self.e = self.a + self.b >> > I would declare this a poor example, since a, b, c, aren't used as > attributes -- they are just invocation locals. From wmacintosh91834 at live.ca Mon Dec 8 21:42:58 2008 From: wmacintosh91834 at live.ca (Wesley MacIntosh) Date: Mon, 08 Dec 2008 21:42:58 -0500 Subject: Mathematica 7 compares to other languages In-Reply-To: <8947211d-2ee8-403a-8c8a-c7599aea5f80@k24g2000pri.googlegroups.com> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> <0201522a-b15a-4401-a208-5d9af70bdd74@w24g2000prd.googlegroups.com> <8947211d-2ee8-403a-8c8a-c7599aea5f80@k24g2000pri.googlegroups.com> Message-ID: A flamer wrote: > A moron, wrote: [snip] > my machine (PPC Mac, OSX 10.4.x). Well, that explains a great deal. Actually, I suspect all these newsgroups are being trolled. From tjreedy at udel.edu Sat Dec 6 13:49:47 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 06 Dec 2008 13:49:47 -0500 Subject: operators as variables In-Reply-To: <103920.71204.qm@web26006.mail.ukl.yahoo.com> References: <103920.71204.qm@web26006.mail.ukl.yahoo.com> Message-ID: macc_200 wrote: > Hi, > just starting programming and have an elementary question after playing > around with lists but cannot find the answer with googling. > I have a list of variables and I would like some of those variables to > be integers and some to be operators so the list would look something > like [5 * 4 - 4 + 6] and then be able to evaluate the result (i.e. get > 10). How do you make the interpreter see the operator as that instead > of a string and just echo the list back to me. I am not sure what you actually want to do, but the following may help: 1. Strings can be evaluated. 2. Operators are syntax sugar for functions. The functions are available in the operator module. IDLE 3.0 >>> eval('5 * 4 - 4 + 6') 22 >>> import operator as op >>> op.add(2,3) 5 tjr From timr at probo.com Wed Dec 31 02:39:59 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 31 Dec 2008 07:39:59 GMT Subject: why cannot assign to function call References: <495867C2.7080807@gmail.com> <5e807c67-7d97-4b8a-8c5f-a3b97f5c5003@i20g2000prf.googlegroups.com> <5fb29c80-a6a4-4cb4-aa62-0d2aeb437662@o4g2000pra.googlegroups.com> Message-ID: Aaron Brady wrote: > >I think the problem goes deeper than just English. In any language >that has a plural, the propositions in question come out as, 'one >thing is two things' or 'two things are one thing'. According to some >rules, these are ungrammatical sentences, due to plurality >disagreement. Ex: > >The Morning Star is ... >The Evening Star is ... >*The Morning Star and The Evening Star is... >*The Morning Star and The Evening Star are... > >Neither of the latter two is correct. (* marks ungrammatical.) As >such, the listener isn't sure what meaning to take. This is taking a serious twist into off-topicness, but I need to dispute this. I will assert that the 4th line is, in fact, grammatically correct, modulo the capitalization of the second "The". The fragment is clearly of the form "X and Y are...", and regardless of the substitution of X and Y, the plurality of the subject agrees with the verb. The Morning Star and the Evening Star are bright tonight. Ignoring the fact that we can't see both at the same time, why is the meaning of that unclear? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From castironpi at gmail.com Tue Dec 9 11:30:26 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 9 Dec 2008 08:30:26 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> Message-ID: On Dec 9, 8:28?am, MRAB wrote: snip > In some languages (I think Delphi is one of them - it's been a while!) > some words which would normally be identifiers have a special meaning in > certain contexts, but the syntax precludes any ambiguity, and not in a > difficult way. "as" in Python was one of those. > > I certainly wouldn't want something like PL/I, where "IF", "THEN" and > "ELSE" could be identifiers, so you could have code like: > > ? ? ?IF IF = THEN THEN > ? ? ? ? ?THEN = ELSE; > ? ? ?ELSE > ? ? ? ? ?ELSE = IF; > > See http://en.wikipedia.org/wiki/PL/I_(programming_language). snip The following are semantically equivalent: I certainly wouldn't want something like PL/I, where "IF", "THEN" and "ELSE" could be identifiers. I wouldn't want something like PL/I, where "IF", "THEN" and "ELSE" could be identifiers. That is, 'certainly' doesn't change the meaning of your statement any. You wouldn't want it, but King George III didn't want the American Revolution. You wouldn't want it. What does that mean for me (the generic reader), and Python? What can I learn from that fact? From arkanes at gmail.com Thu Dec 11 14:02:26 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 11 Dec 2008 13:02:26 -0600 Subject: Call by reference in SWIG? In-Reply-To: <9D295CD0-2DA3-4572-A2A5-57301D67BEED@strout.net> References: <9D295CD0-2DA3-4572-A2A5-57301D67BEED@strout.net> Message-ID: <4866bea60812111102t7780a613lede2ab07ea3db8ef@mail.gmail.com> On Thu, Dec 11, 2008 at 9:43 AM, Joe Strout wrote: > On Dec 10, 2008, at 10:19 PM, Nok wrote: > >> I can't get call-by-reference functions to work in SWIG... > > Python doesn't have any call-by-reference support at all [1], so I'm not > surprised that a straight translation of the call-by-reference C function > doesn't work. > > Unfortunately I don't know enough about SWIG to suggest a work-around. > Hopefully someone more versed in SWIG will have a bright idea. If you > don't find anything in the Python space, you might try poking around in Java > references, since Java has the same call semantics as Python. > I'm not sure if SWIG has tools to do this for you or if you need to do the mapping by hand, but the usual idiom is to translate them into return values (keeping the original arg if the passed in value matters also). From feinepost at bluewin.ch Tue Dec 9 02:32:19 2008 From: feinepost at bluewin.ch (feinepost at bluewin.ch) Date: Tue, 9 Dec 2008 08:32:19 +0100 Subject: Python & LEGO Mindstorm control... Message-ID: <000001c959d0$49b1f9c0$dd15ed40$@ch> Hi Toni Meyer, I would be quite interested in your Python extension to send ir signals to the rcx. I am quite new to this stuff, hope I'll understand what you did? Could you send it to me? Thanks a lot! Daniel Rupp -------------- next part -------------- An HTML attachment was scrubbed... URL: From wuwei23 at gmail.com Thu Dec 11 12:25:16 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 11 Dec 2008 09:25:16 -0800 (PST) Subject: Preventing execution of a method References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> <764daeef-bfbe-411a-8521-bb114321e4ac@b38g2000prf.googlegroups.com> Message-ID: <19304f8c-e34f-4aa9-8df2-6a7d3553007a@e1g2000pra.googlegroups.com> On Dec 12, 3:22?am, alex23 wrote: > On Dec 12, 2:35?am, rdmur... at bitdance.com wrote: > > > There is, however, also the possibility of prefixing the method name > > with '__'. ?The invokes 'name mangling', which makes it more difficult > > (though not impossible, the idea is to avoid accidents) for the method > > to be called from outside the class. > > That only works for methods, it has no effect on functions or classes > within modules: And of course -now- I realise that the OP was asking for protecting methods. Please disregard my last post :) From timr at probo.com Sun Dec 28 00:13:14 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 28 Dec 2008 05:13:14 GMT Subject: strange behavior of math.sqrt() in new 3.0 version References: Message-ID: Scott David Daniels wrote: > >I avoid using single-letter variables except where I know the types >from the name (so I use i, j, k, l, m, n as integers, s as string, >and w, x, y, and z I am a little looser with (but usually float or >complex). It's amazing to me that Fortran continues to live on in the hearts and minds of today's programmers. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From dfnsonfsduifb at gmx.de Sun Dec 7 10:05:53 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Sun, 07 Dec 2008 16:05:53 +0100 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: References: <5u8o06xbqf.ln2@joeserver.homelan.net> <1mmq06x4g6.ln2@joeserver.homelan.net> Message-ID: John Machin schrieb: > He did. Ugly stuff using readline() :-) Should still work, though. Well, well, I'm a C kinda guy used to while (fgets(b, sizeof(b), f)) kinda loops :-) But, seriously - I find that whole "while True:" and "if line == """ construct ugly as hell, too. How can reading a file line by line be achieved in a more pythonic kind of way? Regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From sgeiger at ncee.net Wed Dec 3 09:22:28 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Wed, 03 Dec 2008 09:22:28 -0500 Subject: generating a liste of characters In-Reply-To: References: Message-ID: <49369624.7020103@ncee.net> import string alphabet=list(string.letters[0:26]) print alphabet Yves Dorfsman wrote: > Is there any built in way to generate a list of characters, something > along the line of range('a'-'z') ? > > Right now I am using: > > chars = [ chr(l) for l in range(0x30, 0x3a) ] # 0 - 9 > chars += [ chr(l) for l in range(0x41, 0x5b) ] # A - Z > chars += [ chr(l) for l in range(0x61, 0x7b) ] # a - z > > Is there a better, more straight forward way of doing that ? > > > > Thanks. > > > > Yves. > http://www.sollers.ca/blog/2008/swappiness > http://www.sollers.ca/blog/2008/swappiness/.fr > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From steve at REMOVE-THIS-cybersource.com.au Thu Dec 18 20:15:35 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2008 01:15:35 GMT Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> <6qv7kfFeuf65U1@mid.uni-berlin.de> <6qv9v4Ff1lv9U1@mid.uni-berlin.de> Message-ID: <015aed12$0$20656$c3e8da3@news.astraweb.com> On Thu, 18 Dec 2008 22:11:27 -0200, Gabriel Genellina wrote: > En Thu, 18 Dec 2008 14:05:32 -0200, Mikael Olofsson > escribi?: ... >> If I ever wanted __str__ and __repr__ to return the same thing, I would >> make them equal: >> >> def __str__(self): >> return 'whatever you want' >> __repr__ = __str__ >> >> That makes it more obvious to me what's going on. As a bonus, it saves >> one method call for every repr call. > > It's even easier to define only __repr__, __str__ defaults to it: Easier, yes, but less obvious. I can never remember whether __repr__ calls __str__ or __str__ calls __repr__ if one or the other is missing. And it costs a failed method lookup. The method lookup is a micro-optimization, and therefore not important, but as far as I'm concerned the extra clarity of doing __repr__ = __str__ is valuable. -- Steven From digitig at gmail.com Mon Dec 15 09:11:20 2008 From: digitig at gmail.com (Tim Rowe) Date: Mon, 15 Dec 2008 14:11:20 +0000 Subject: 1 or 1/0 doesn't raise an exception In-Reply-To: <8972c415-2fbb-479f-8a03-b8b29b20ac42@g38g2000yqn.googlegroups.com> References: <49446E39.6020807@tim.thechases.com> <8972c415-2fbb-479f-8a03-b8b29b20ac42@g38g2000yqn.googlegroups.com> Message-ID: Unfortunately, >>>> bool('Ruby totally pwn3s Python!') > True Using Python is not total protection against buggy programs ;-) -- Tim Rowe From ethan at stoneleaf.us Mon Dec 8 02:41:48 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Sun, 07 Dec 2008 23:41:48 -0800 Subject: datetime and the rich-companison operators Message-ID: <493CCFBC.90104@stoneleaf.us> Greetings All! I am implementing a NullDate class in order to mirror dates and datetimes that have no value (yes, this is for my dbf module :) I'm still a bit fuzzy about class methods, hashing, and __new__, but my question of the moment is this: it seems to me that with two dates or datetimes, they should either be equal, or one should precede the other, and this can be accomplished quite handily with __cmp__... so does anyone know why the rich comparisons were used in the datetime module? Was it simply a style choice, or is something being handled that __cmp__ couldn't cope with? Thanks in advance! ~ethan~ From steve at REMOVE-THIS-cybersource.com.au Sat Dec 20 21:49:43 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Dec 2008 02:49:43 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <015d9ca5$0$20656$c3e8da3@news.astraweb.com> <60b419d3-4cbc-4bba-af79-a6d6146ac472@e6g2000vbe.googlegroups.com> Message-ID: <015da611$0$20656$c3e8da3@news.astraweb.com> On Sat, 20 Dec 2008 18:23:00 -0800, r wrote: > Answering a question with a question, that leaves me with a question of > my own?? > >> Instead of just whinging, how about making a suggestion to fix it? Go >> on, sit down for an hour or ten and try to work out how a BINARY >> OPERATOR like % (that means it can only take TWO arguments) can deal >> with an arbitrary number of arguments, *without* having any special >> cases. > > Instead of being a blind fanboy and chastising everyone who dares to > question pydev, Guido, or YOU... why don't you offer a good rebuttal? Because I thought it was obvious even you could see it. I'm disappointed to be proven wrong. A binary operator can only take two arguments: one on the left, and one on the right: 2 + 3 5 * 7 x == 2 "%i" % 7 The typical use-case for string formatting operations requires more than two arguments. Since % is a binary operator, it can only take two arguments. One of those arguments must be the template string, so the other argument has to wrap all the rest of the arguments into one object: "The %s ate %d slices of %s." % ("python", 7, "spam") Python could have insisted that even single arguments be wrapped in a tuple: "%s" % ("python",) At the cost of breaking backwards compatibility, that would solve the problem of treating tuples as a special case, but it seems wasteful and silly to be forced to write this: "The answer is: %d" % (5,) instead of "The answer is: %d" % 5 especially when people will invariably leave out the comma and then complain about the "wart" or "bug" that: "The answer is: %d" % (5) doesn't do what they expect. So tuples are treated as a special case: you only need to wrap a single argument in a tuple if that argument itself is a tuple: "%s" % ((0, 1, 2),) and everything else just works as you would expect. Again, at the cost of breaking backwards compatibility, Python could change the special case from tuples to something else, but what? And why bother? There will always be a special case, one way or another. Consequently, there is no way to "fix" the special casing of tuples without just shifting the problem. The problem is fundamental to the nature of binary operators: you can't fit an arbitrary number of arguments into two places (the left hand side, and the right hand side) of the % operator without having to special case something. The real solution is to stop trying to force arbitrary numbers of arguments into a single place, and instead use a function or method that takes multiple arguments. That's what the "".format() method and the format() function do. -- Steven From wuwei23 at gmail.com Fri Dec 12 04:45:55 2008 From: wuwei23 at gmail.com (alex23) Date: Fri, 12 Dec 2008 01:45:55 -0800 (PST) Subject: Removing None objects from a sequence References: Message-ID: On Dec 12, 7:18?pm, "Filip Gruszczy?ski" wrote: > Hi! > > I would like to iterate over a sequence nad ignore all None objects. > The most obvious way is explicitly checking if element is not None, > but it takes too much space. And I would like to get something faster. > I can use > [ sth for sth in self.__sth if not sth is None ], but I don't know if > that's the best way. I checked itertools, but the only thing that > seemed ok, was ifilter - this requires seperate function though, so > doesn't seem too short. How can I get it the shortest and fastest way? Rather than a list comprehension, use a generator expression: for item in (x for x in sequence if x is not None): do_something(x) This doesn't generate the intermediate list with None elements removed, rather it steps one at a time through the original sequence and only returns the non-None elements. From steve at REMOVE-THIS-cybersource.com.au Thu Dec 4 10:48:33 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Dec 2008 15:48:33 GMT Subject: Python Runtime Method Call Binding References: Message-ID: <0147f396$0$20670$c3e8da3@news.astraweb.com> On Thu, 04 Dec 2008 06:23:28 -0800, k3xji wrote: > Hi, > > Is there a way to hook a function call in python? I know __getattr__ is > doing for variables, What do you mean "variables"? Do you mean attributes? > it is giving us a chance before a field is > initialized. What field? Is a field the same as a variable, or something else? > Do we have same functionality for methods? Yes, methods are attributes too, they are reached by the exact same mechanism as any other attribute. Any object with a __call__ method can be called. Normally you create objects with a __call__ method by using def or lambda. > Example: > > class Foo(object): > def __call_method__(self, ...) # just pseudo > print 'A method is called in object...' > > f = Foo() > f.test_method() > > I think you understand my point. I wish I did. It might have helped if you actually showed the expected output of your "test_method", instead of expecting us to *guess* what you expect to happen. I'm going to guess what you mean, and show you one possible solution. Read it carefully: it shows three examples of __getattr__, starting from the simplest to the relatively complicated. class Parrot(object): def __getattr__(self, name): if name == "colour": return "red" elif name == "talk": return lambda x: "Hi, I'm %s the talking parrot" % x elif name == "speak": class Birdy(object): def __init__(self, name): self.name = name def __call__(self): return "I'm the talking Parrot %s" % self.name return Birdy('Fred') else: raise AttributeError And in use: >>> p = Parrot() >>> p.colour 'red' >>> p.talk # get the attribute "talk" at 0x81fab1c> >>> >>> p.talk("Fred") # call the attribute (method) "talk" "Hi, I'm Fred the talking parrot" >>> >>> p.speak <__main__.Birdy object at 0x820076c> >>> p.speak() "I'm the talking Parrot Fred" -- Steven From pavlovevidence at gmail.com Thu Dec 25 17:53:51 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 25 Dec 2008 14:53:51 -0800 (PST) Subject: Exec inside a class method to call other class methods? References: Message-ID: On Dec 25, 12:22?pm, Matthew Dubins wrote: > Hello all, > > I have made a python script to upload contact information from an excel > worksheet to an online database. ?One part of the program that really > tripped me up was when I wanted to call specific class methods that I > had made to deal with specific types of contact information (Parent's > name, Child's name, Phone #, etc). ?My first thought was to make it easy > using the exec statement. Bad idea. You should not use exec and eval unless it's your intention to allow the user to run arbitrary Python code. Any other time you think you need to use exec (such as when constructing an attribute name), you should find out whether there's another way to do it, and there usually is. Such is the case here; there is a function, getattr, that does what you want. See below. > The code (a method within a class) looked like this: > ---------- > def parse(self, data, data_type) > ? ? exec "self.__parse_%s(data)" % data_type > ---------- I presume you're aware that the double underscore is a sort of private variable. It causes the Python compiler to mangle the name when used inside a class definition (it converts __parse_email to _Parser__parse_email under the covers, assuming Parser is the class name). Well, it turns out that the Python compiler doesn't know that the string in the exec statement is part of the class, so it doesn't mangle the name for you. If you want to get the method name from within the exec statement, you have to mangle it by hand, like so: def parse(self,data,data_ype): exec "self._Parser__parse_%s(data)" % data_type However, you shouldn't do that. Instead, use getattr, which is a function that was designed exactly for that purpose, and is much less of a security risk. def parse(self,data,data_ype): method = getattr(self,"_Parser__parse_%s" % data_type) method(data) Note that you still have to use the mangled version of the name with getattr (getattr doesn't know it's inside the class, either). And, although this is much safer than exec, you should still be wary of passing user input into it. Here is why you shouldn't use exec for this. You say this program reads data from a spreadsheet. What would happen if, in the data type field, a malicious user were to enter the following string (without surrounding quotes): "email(); import os; os.system('format c:');" Your exec statement would blindly execute this, oops, it happened to format your hard disk. exec and eval are prone to security holes like this, and they usually entail a performance penalty (since the compiler has to be invoked for every call), so please use them only what they were intended for. Carl Banks From gagsl-py2 at yahoo.com.ar Sun Dec 28 23:33:19 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Dec 2008 02:33:19 -0200 Subject: How to "kill" orphaned threads at program exit References: Message-ID: En Sun, 28 Dec 2008 15:47:24 -0200, Roy Smith escribi?: > In article > , > "Giampaolo Rodola'" wrote: > >> I know that it's not possible to "kill" threads but I'm wondering if >> does exist some workaround for my problem. >> I have a test suite which does a massive usage of threads. >> Sometimes happens that one test fails, the test suite keeps running >> until the end, and when it's finished the program hangs on and the >> only way to stop is to kill it manually. > > You don't say how you're creating your threads, so I'll assume you're > using > threading.Thread(). After creating each thread, and before calling > start() > on it, call setDaemon(True). The hard part is, then, to figure out some condition for the non-daemon thread to wait for before exiting. As a last resort -let's say, after waiting for N seconds for all threads to exit- one can use PyThreadState_SetAsyncExc to "inject" an exception into the unfinished threads. I think there is a recipe in the Python Cookbook for doing that using ctypes. -- Gabriel Genellina From google at mrabarnett.plus.com Fri Dec 19 21:19:24 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 20 Dec 2008 02:19:24 +0000 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <015c4890$0$20656$c3e8da3@news.astraweb.com> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> <6r25ckFejl4vU1@mid.individual.net> <015c4890$0$20656$c3e8da3@news.astraweb.com> Message-ID: <494C562C.1070301@mrabarnett.plus.com> Steven D'Aprano wrote: > On Fri, 19 Dec 2008 18:53:22 +0100, Thomas Heller wrote: > >> Steve Holden schrieb: >>> Thomas Heller wrote: >>>> Question from a non-native english speaker: is this now valid english? >>>> >>>> "One of Python?s great strengths" >>>> ^ >>>> "and also teaches Python?s functional programming features" >>>> ^ >>>> "The book?s approach is wholly practical" >>>> ^ >>> It always has been valid English. The apostrophe is only omitted from >>> personal pronouns (hers, its, and so on). >> I see, thanks. But, is the apostrophe optional in the above fragments? > > No. In English, you indicate possessives in one of two ways: > > The approach of the book is wholly practical. > The book's approach is wholly practical. > > In the second form, the apostrophe is always needed, with a couple of > exceptions. The first exception is personal pronouns: > > My approach is wholly practical. > His approach is wholly practical. > Its approach is wholly practical. > > (The third one often gives even native English speakers trouble, with > confusion between the contraction "it's" (it is) and the possessive > "its".) > > The second exception is if the word ends with an S. In British English, > you put the apostrophe after the S: > > Thomas' approach is wholly practical. > > In American English, they often (but not always) add an extra S: > > Thomas's approach is wholly practical. > > which in my opinion is logical but ugly and should be avoided. > There's disagreement on the subject. A simple rule is to follow speech: if you say /tomasIz/ (as I do) then add "'s", therefore "Thomas's". From Ron.Barak at lsi.com Tue Dec 16 08:35:27 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Tue, 16 Dec 2008 13:35:27 +0000 Subject: String slices work only for first string character ? In-Reply-To: References: Message-ID: <7F0503CD69378F49BE0DC30661C6CCF60249410A@enbmail01.lsi.com> Hi, Can any one explain why the following string slice works only for the first character, but not for any other ? $ cat /tmp/tmp.py #!/usr/bin/env python data = 'F0023209006-0101' print data print "|"+data[0:1]+"|" print "|"+data[1:1]+"|" print "|"+data[2:1]+"|" $ python `cygpath -w /tmp/tmp.py` F0023209006-0101 |F| || || $ Thanks, Ron. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Scott.Daniels at Acm.Org Thu Dec 18 16:29:44 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 18 Dec 2008 13:29:44 -0800 Subject: confused about __str__ vs. __repr__ In-Reply-To: References: <494A5ACA.8060205@wildenhain.de> Message-ID: J. Cliff Dyer wrote: > ... how an object prints itself is up to that object and that object alone.... > If I wanted to implement a list-like class that doesn't show it's elements at > all when printed, but instead shows its length, I am free to do so. > For example: > >>>> hl = HiddenList(1,2,3) >>>> hl > >>>> hl[1] > 2 > > (Implementation of HiddenList left as an exercise for the reader.) And just so some of you who wonder how hard this implementation is: (2.4.X, 2.5.X, 2.6.X): class HiddenList(list): def __repr__(self): return '<%s object: length=%s>' % ( type(self).__name__, len(self)) (3.0): class HiddenList(list): def __repr__(self): return '<{0} object: length={1}>'.format( type(self).__name__, len(self)) --Scott David Daniels Scott.Daniels at Acm.Org From arnodel at googlemail.com Thu Dec 4 12:14:17 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 04 Dec 2008 17:14:17 +0000 Subject: simplest way to strip a comment from the end of a line? References: Message-ID: Joe Strout writes: > I have lines in a config file which can end with a comment (delimited > by # as in Python), but which may also contain string literals > (delimited by double quotes). A comment delimiter within a string > literal doesn't count. Is there any easy way to strip off such a > comment, or do I need to use a loop to find each # and then count the > quotation marks to its left? > > Thanks, > - Joe FWIW this is what comes to mind. >>> def strip_comment(line): ... i = -1 ... while True: ... i = line.find('#', i+1) ... if i == -1: ... return line ... if line.count('"', 0, i) % 2 == 0: ... return line[:i] ... >>> strip_comment('foo=1 # set foo') 'foo=1 ' >>> strip_comment('foo="bar" # set foo') 'foo="bar" ' >>> strip_comment('foo="bar # set foo"') 'foo="bar # set foo"' >>> strip_comment('foo="bar # set foo" # set foo') 'foo="bar # set foo" ' >>> strip_comment('foo="bar # set foo" + "baz ## fubar" # set foo') 'foo="bar # set foo" + "baz ## fubar" ' >>> strip_comment('foo="bar # set foo" + "baz ## fubar # set foo"') 'foo="bar # set foo" + "baz ## fubar # set foo"' >>> strip_comment(r'foo="bar\" baz" # this breaks') 'foo="bar\\" baz" # this breaks' As the last example shows, it won't work if there is an escaped double quote in the string. -- Arnaud From castironpi at gmail.com Sun Dec 21 18:17:12 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 21 Dec 2008 15:17:12 -0800 (PST) Subject: Are python objects thread-safe? References: Message-ID: <012b2014-de2a-498f-adbf-43f1727a109f@b41g2000pra.googlegroups.com> On Dec 21, 12:51?pm, RajNewbie wrote: > Say, I have two threads, updating the same dictionary object - but for > different parameters: > Please find an example below: > a = {file1Data : '', > ? ? ? ?file2Data : ''} > > Now, I send it to two different threads, both of which are looping > infinitely: > In thread1: > a['file1Data'] = open(filename1).read > ? ? ? ? ? and > in thread2: > a['file2Data'] = open(filename2).read > > My question is ?- is this object threadsafe? - since we are working on > two different parameters in the object. Or should I have to block the > whole object? Threads take turns with the Global Interpreter Lock, so a Python thread is sure to have the GIL before it calls a method on some object. So yes, with the rare exception (that I don't want to not mention) that if you've got non-Python threads running in your process somehow, they don't make the guarantee of enforcing that. From zac256 at gmail.com Thu Dec 4 13:03:40 2008 From: zac256 at gmail.com (Zac Burns) Date: Thu, 4 Dec 2008 10:03:40 -0800 Subject: Overriding a method at the instance level on a subclass of a builtin type In-Reply-To: References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> Message-ID: <333edbe80812041003i2e653d6dp31e64eab7bb62701@mail.gmail.com> Ok... but why are the special methods handled differently? -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer (Digital Overlord) Zindagi Games On Thu, Dec 4, 2008 at 9:57 AM, George Sakkis wrote: > On Dec 4, 12:31 pm, Arnaud Delobelle wrote: >> "Zac Burns" writes: >> > The class method seems to be the most promising, however I have more >> > 'state' methods to worry about so I might end up building new classes >> > on the fly rather than have a class per permutation of states! Now the >> > code isn't quite as clear as I thought it was going to be. >> >> > It seems unfortunate to me that methods are always looked up on the >> > class for new style objects. Was this done for speed reasons? >> >> It's only special methods such as __getitem__, ... >> >> You can override normal method on a per-object basis just by adding a >> callable attribute with its name to the object: >> >> >>> class A(object): >> >> ... def foo(self): print 'A.foo' >> ...>>> a = A() >> >>> a.foo() >> A.foo >> >>> def a_foo(): print 'a.foo' >> ... >> >>> a.foo = a_foo >> >>> a.foo() > > Note that the overriden "method" here is a plain function; it doesn't > take self as the first argument. If you want to bind it to a callable > that expects the first argument to be self, you have to bind > explicitly self to the object: > >>>> def a_foo(self): print 'a.foo' >>>> a.foo = a_foo >>>> a.foo() > TypeError: a_foo() takes exactly 1 argument (0 given) >>>> from functools import partial >>>> a.foo = partial(a_foo,a) >>>> a.foo() > a_foo > > George > -- > http://mail.python.org/mailman/listinfo/python-list > From castironpi at gmail.com Sun Dec 21 06:37:50 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 21 Dec 2008 03:37:50 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: On Dec 20, 8:49?pm, MRAB wrote: > Aaron Brady wrote: > > On Dec 20, 7:38 pm, Steven D'Aprano > cybersource.com.au> wrote: > >> Instead of just whinging, how about making a suggestion to fix it? Go on, > >> sit down for an hour or ten and try to work out how a BINARY OPERATOR > >> like % (that means it can only take TWO arguments) can deal with an > >> arbitrary number of arguments, *without* having any special cases. > > >> Go on. Take your time. I'll be waiting. > > > Hi, not to take sides, but, there is a possibility. > > > This behavior is currently legal: > > >>>> "%i %%i" % 0 % 1 > > '0 1' > > > So, just extend it. ?(Unproduced.) > > >>>> "%i %i" % 0 % 1 > > '0 1' > >>>> "%r %i" % (2, 3, 4) % 1 > > '(2, 3, 4) 1' > >>>> "%r %i" % (2, 3, 4) > > '(2, 3, 4) %i' > > > Which is quite clever and way ahead of its (posessive) time. > > A couple of problems: > > 1. How do you handle a literal '%'? If you just double up then you'll > need to fix the string after all your substitutions. > > 2. What if a substitution introduces a '%'? > > I suppose a possible solution would be to introduce a special format > string, including a literal, eg: > > ? ? ?f"%r %i" % (2, 3, 4) % 1 > > and then convert the result to a true string: > > ? ? ?print(str(f"%r %i" % (2, 3, 4) % 1)) > > (although print() would call __str__ anyway). > > The format string would track where the last substitution occurred. > > Hmm... I think I'll just learn the new method. :-) Now that I'm fighting 'r's war for him/her... Um, here's one possibility. On the first interpolation, flags are noted and stored apart from subsequent interpolations. Then, use a sentinel to terminate the interpolation. (Unproduced.) >>> "%r %i" % ( 2, 3 ) % 0 '(2, 3) 0' >>> "%% %r" % ( 2, 3 ) % str.interp_end '% (2, 3)' >>> "%sss%i" % "%d" % 0 '%dss0' The first %s is replaced with %d, but doesn't hijack the '0'. If you want to interpolate the %d, use the sentinel. The sentinel is what causes '%%' to be handled. >>> "%sss%i" % "%d" % 0 % 1 Traceback (most recent call last): File "", line 1, in TypeError: not all arguments converted during string formatting >>> "%sss%i" % "%d" % 0 % str.interp_end % 1 '1ss0' Treating tuples as a special case appears to be the simpler solution, but this, 'chaining', to adopt the term, is still feasible. From jervisau at gmail.com Tue Dec 30 16:09:21 2008 From: jervisau at gmail.com (Jervis Whitley) Date: Wed, 31 Dec 2008 08:09:21 +1100 Subject: embedding python in wxpython In-Reply-To: <495A82D9.3000902@gmail.com> References: <191280cf-ecf9-4135-9737-9923061855d1@t39g2000prh.googlegroups.com> <495A82D9.3000902@gmail.com> Message-ID: <8e63a5ce0812301309p705b2fe0x9ad5d0b039a0dad4@mail.gmail.com> On Wed, Dec 31, 2008 at 7:21 AM, Stef Mientki wrote: > 5lvqbwl02 at sneakemail.com wrote: > >> Hi, I've looked around for a way to allow a python console from within >> a wxPython application, but have only found stuff on embedded/ >> extending python with C/C++ or wxWidgets in C++, but not wxPython. >> >> Is this easy to do? Can someone point me in the right direction? >> >> Also, typically when you embed a scripting language into a larger >> application, how do you get the console environment to share data with >> the larger application? >> >> For instance, if the application has some gui stuff (for example >> clicking on a object and dragging it around), how do you get >> "object.select(x,y)" to print out on the console, and vice-versa: the >> object gets selected if the user types "object.select(x,y)"? >> >> I'd like the console to be a bidirectional representation of what's >> going on in the gui, plus a general purpose evaluation environment >> where you can manipulate application data via some api which is >> automatically exposed to the console when the application opens up. >> >> I'm looking for high-level hints/strategies/directions. >> >> > If you're looking for "high-level", > I don't understand why you want to see what's going on in the gui, > as I see the gui just a tool to control the real data. > For a pretty high level data manipulation, > something like PyLab_Works ? > http://code.google.com/p/pylab-works/ > > cheers, > Stef > > -- > http://mail.python.org/mailman/listinfo/python-list > Try checking out the wxPython demo package. There is an example of a widget inspection tool in the help menu. This tool has an embedded python console and allows introspection of live widgets and sizers in an application. Cheers, Jervis -------------- next part -------------- An HTML attachment was scrubbed... URL: From kkylheku at gmail.com Wed Dec 3 23:54:31 2008 From: kkylheku at gmail.com (Kaz Kylheku) Date: Thu, 4 Dec 2008 04:54:31 +0000 (UTC) Subject: Mathematica 7 compares to other languages References: <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <4b6c3304-2396-4d35-a06f-e5d693cbbb12@f13g2000yqj.googlegroups.com> Message-ID: <20081219033030.559@gmail.com> On 2008-12-04, J?rgen Exner wrote: > toby wrote: >>On Dec 3, 4:15 pm, Xah Lee wrote: >>> On Dec 3, 8:24 am, Jon Harrop wrote: >>> >>> > My example demonstrates several of Mathematica's fundamental limitations. >>> >>> enough babble Jon. >>> >>> Come flying $5 to my paypal account, and i'll give you real code, >> >>I'll give you $5 to go away > > if you add "and never come back" then count me in, too. Really? I will trade you one Xah Lee for three Jon Harrops and I will even throw in a free William James. From sri_annauni at yahoo.co.in Wed Dec 3 05:40:30 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Wed, 3 Dec 2008 16:10:30 +0530 (IST) Subject: How to send body and attachements in an email message? Message-ID: <140952.77709.qm@web7901.mail.in.yahoo.com> HI, I would like to send an email message with body-content 'test' and?an attachment. The snippet i used is: outer = email.mime.multipart.MIMEMultipart() msg1 = email.mime.text.MIMEText(, _subtype = 'text') msg1.add_header('Content-Disposition', 'attachment') outer.attach(msg1) body = email.mime.text.MIMEText(, _subtype = 'text') outer.attach(body) smtp_client = smtplib.SMTP() smtp_client.connect() smtp_client.sendmail(, , outer.as_string()) smtp_client.close() If i do like above, i am receiving the body also as an attachment. How to set body to Multipart email message? Thanks, Srini Add more friends to your messenger and enjoy! Go to http://messenger.yahoo.com/invite/ From mynthon1 at gmail.com Tue Dec 30 04:04:33 2008 From: mynthon1 at gmail.com (mynthon) Date: Tue, 30 Dec 2008 01:04:33 -0800 (PST) Subject: wxPython.button.disabled still catching clicks References: <8cb6da6a-7df4-4cce-a28e-385448a25b26@w39g2000prb.googlegroups.com> <1ff2aad7-29a1-48cd-b3de-29fab443aa3e@u18g2000pro.googlegroups.com> <0e9a5ab7-8078-4d12-adb2-aaf92a78b007@s9g2000prm.googlegroups.com> Message-ID: <007bab05-6451-48c8-94bc-a34631795e32@v5g2000prm.googlegroups.com> On Dec 23, 6:12?pm, Mike Driscoll wrote: > On Dec 23, 7:27?am,mynthon wrote: > > > > > On Dec 23, 11:58?am, Aaron Brady wrote: > > > > On Dec 23, 4:50?am,mynthon wrote: > > > > > Hello! (sorry for my english) > > > > > I have a problem with buttons in wxPython. When button is disabled > > > > (by .Disable() or .Enable(False)) it is grayed out but still receive > > > > clicks. > > > > > Eg. i have button that disable itself, runs long action and enable > > > > itself: > > > > > def onClick(self, evt): > > > > ? ? self.btn.Enable(False) > > > > ? ? for i in range (1000): > > > > ? ? ? ? print i > > > > ? ? self.btn.Enable(True) > > > > > when for loop is running button is greyed out and when i click on it > > > > nothing happens but when loop ends another one is started because > > > > button "remebered" thad i click on it when was diabled. My only idea > > > > is to reposition button outside frame instead of disabling it but this > > > > solution is...not good. > > > > > thanks for any help. Ive searched groups, google and it looks that > > > > only i have this problem :) > > > > No, it is very common. ?During your for loop, the loop is dominating > > > the process completely. ?Events are just building up in the app's > > > message queue, and don't get handled until after you yield on control. > > > > If you need to run a long task, look into threading, the OnIdle > > > method, the 'multiprocessing' module, or pump messages during your > > > long task. > > > ok, maybe someone will need it. I dont know how it works because i > > didnt have time to read docs and i cannot explain everything. I used > > google and wxPython demo (in tree: wxpython overview / process and > > events / process) > > > class leftPanel(wx.Panel): > > ? ? def __init__(self, parent, id): > > ? ? ? ? wx.Panel.__init__(self, parent, id, style=wx.BORDER_SUNKEN) > > > ? ? ? ? # here you have to define new process, IDLE event, and > > onPRocessEnd event > > ? ? ? ? self.process = None > > ? ? ? ? self.GetParent().Bind(wx.EVT_IDLE, self.onIdle) > > ? ? ? ? self.Bind(wx.EVT_END_PROCESS, self.onProcessEnd) > > > ? ? ? ? # create button and bind event to it > > ? ? ? ? self.runScriptBtn = wx.Button(self, -1, 'RUN ME!', (10,220)) > > ? ? ? ? self.runScriptBtn.Bind(wx.EVT_BUTTON, self.onClick, > > self.runScriptBtn) > > > ? ? def onClick(self, evt): > > ? ? ? ? # disable button > > ? ? ? ? self.runScriptBtn.Enable(False) > > > ? ? ? ? # here you have to enter command to run > > ? ? ? ? # previusly i heve here exec('pythonmyScript.py') > > ? ? ? ? # but now it will be a subprocess > > ? ? ? ? cmd = 'pythonxxx1.py' > > > ? ? ? ? #create new process > > ? ? ? ? self.process = wx.Process(self) > > > ? ? ? ? # dont know what it is for > > ? ? ? ? self.process.Redirect() > > > ? ? ? ? # execute cmd command > > ? ? ? ? pid = wx.Execute(cmd, wx.EXEC_ASYNC, self.process) > > > ? ? def onIdle(self, evt): > > ? ? ? ? # beacuse this method is called only when app enters idle mode > > ? ? ? ? # the line below is nedded to "simulate" entering idle mode > > ? ? ? ? # dont know how it works but it works > > ? ? ? ? evt.RequestMore(True) > > > ? ? ? ? # here is some code to catch subprocess output > > ? ? ? ? if self.process is not None: > > ? ? ? ? ? ? stream = self.process.GetInputStream() > > ? ? ? ? ? ? if stream.CanRead(): > > ? ? ? ? ? ? ? ? text = stream.read() > > ? ? ? ? ? ? ? ? print text > > > ? ? def onProcessEnd(self, evt): > > ? ? ? ? # here is some code to catch subprocess output > > ? ? ? ? # when it is destroyed > > ? ? ? ? stream = self.process.GetInputStream() > > ? ? ? ? if stream.CanRead(): > > ? ? ? ? ? ? text = stream.read() > > ? ? ? ? ? ? print text > > > ? ? ? ? # dont know it is necessary > > ? ? ? ? self.process.CloseOutput() > > > ? ? ? ? # remove (clear) process object > > ? ? ? ? self.process.Destroy() > > ? ? ? ? self.process = None > > > ? ? ? ? # show button again > > ? ? ? ? self.runScriptBtn.Enable() > > I'm pretty sure there's a better way to do this. If you disable the > button and click on it, you'll notice that it isn't firing events, so > something else is going on here. It seems like the wx.Frame or > wx.Application is queuing the mouse button clicks or something. I > would post to the wxPython mailing list:http://wxpython.org/maillist.php > > They'll be better able to address this and they'll probably have a > simpler solution too. > > Mike I changed it. Now i'm running separate thread instead of process. First example at: http://wiki.wxpython.org/LongRunningTasks From collin.day.0 at gmail.com Thu Dec 18 21:48:08 2008 From: collin.day.0 at gmail.com (Collin D) Date: Thu, 18 Dec 2008 18:48:08 -0800 (PST) Subject: Factoring Polynomials References: <919062f9-765e-4279-aa26-2c130d4deacf@o4g2000pra.googlegroups.com> <4479b464-3a9b-4dd8-bf66-fea7d9471091@n33g2000pri.googlegroups.com> <661fd2d0-251d-4899-a015-8d257310a159@q26g2000prq.googlegroups.com> Message-ID: On Dec 18, 6:41?pm, "Russ P." wrote: > On Dec 18, 6:31?pm, Collin D wrote: > > > > > > > On Dec 18, 6:27?pm, Collin D wrote: > > > > On Dec 18, 6:23?pm, "Russ P." wrote: > > > > > On Dec 18, 6:17?pm, Collin D wrote: > > > > > > On Dec 18, 6:12?pm, Collin D wrote: > > > > > > > On Dec 18, 11:37?am, collin.da... at gmail.com wrote: > > > > > > > > I am trying to write a simple application to factor polynomials. I > > > > > > > wrote (simple) raw_input lines to collect the a, b, and c values from > > > > > > > the user, but I dont know how to implement the quadratic equation > > > > > > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > > > > > > into python. Any ideas? > > > > > > > I completed the code: > > > > > > > #import > > > > > > from math import sqrt > > > > > > > # collect data > > > > > > a = float(raw_input('Type a value: ')) > > > > > > b = float(raw_input('Type b value: ')) > > > > > > c = float(raw_input('Type c value: ')) > > > > > > > # create solver > > > > > > def solver(a,b,c): > > > > > > ? ? if b**2 - 4*a*c < 0: > > > > > > ? ? ? ? return 'No real solution.' > > > > > > ? ? else: > > > > > > ? ? ? ? sol1 = -1 * b + (sqrt(b**2 - 4*a*c)) / 2*a > > > > > > ? ? ? ? sol2 = -1 * b - (sqrt(b**2 - 4*a*c)) / 2*a > > > > > > ? ? ? ? return (sol1, sol2) > > > > > > > # execute > > > > > > print solver(a,b,c) > > > > > > > Thanks to everyone who helped... > > > > > > This really expanded my knowledge on some of the mathematical > > > > > > functions in Python. > > > > > > UPDATE: > > > > > ' > > > > > > #import > > > > > from math import sqrt > > > > > > # collect data > > > > > a = float(raw_input('Type a value: ')) > > > > > b = float(raw_input('Type b value: ')) > > > > > c = float(raw_input('Type c value: ')) > > > > > > # create solver > > > > > def solver(a,b,c): > > > > > ? ? if b**2 - 4*a*c < 0: > > > > > ? ? ? ? return 'No real solution.' > > > > > ? ? else: > > > > > ? ? ? ? sol1 = (-1 * b + (sqrt(b**2 - 4*a*c))) / 2*a > > > > > ? ? ? ? sol2 = (-1 * b - (sqrt(b**2 - 4*a*c))) / 2*a > > > > > ? ? ? ? return (sol1, sol2) > > > > > > # execute > > > > > print solver(a,b,c) > > > > > You need to put your denominator, 2*a, in parens. The way it stands, > > > > you are dividing by 2, then multiplying by a. That's not what you > > > > want. > > > > > Also, for better style, I suggest you compute the discriminanat once > > > > and store it for reuse rather than repeating the expression three > > > > times.- Hide quoted text - > > > > > - Show quoted text - > > > > I see what you mean on the denominator and discriminant. Ill do that.- Hide quoted text - > > > > - Show quoted text - > > > UPDATE: > > > #import > > from math import sqrt > > > # collect data > > a = float(raw_input('Type a value: ')) > > b = float(raw_input('Type b value: ')) > > c = float(raw_input('Type c value: ')) > > > # find discriminant > > disc = b**2 - 4*a*c > > > # create solver > > def solver(a,b,c): > > ? ? if disc < 0: > > ? ? ? ? return 'No real solution.' > > ? ? else: > > ? ? ? ? sol1 = (-1 * b + (sqrt(disc))) / (2*a) > > ? ? ? ? sol2 = (-1 * b - (sqrt(disc))) / (2*a) > > ? ? ? ? return (sol1, sol2) > > > # execute > > print solver(a,b,c) > > A couple of style points. I would use -b rather than -1 * b. Also, you > don't need the else clause. You can simplify it to > > def solver(a, b, c): > > ? ? disc = b**2 - 4 * a * c > > ? ? if disc < 0: return "No real solution." > > ? ? sol1 = (-b + sqrt(disc)) / (2*a) > ? ? sol2 = (-b - sqrt(disc)) / (2*a) > > ? ? return sol1, sol2- Hide quoted text - > > - Show quoted text - UPDATE: #import from math import sqrt # collect data a = float(raw_input('Type a value: ')) b = float(raw_input('Type b value: ')) c = float(raw_input('Type c value: ')) # create solver def solver(a,b,c): disc = b**2 - 4*a*c if disc < 0: return 'No real solution.' else: sol1 = (-b + (sqrt(disc))) / (2*a) sol2 = (-b - (sqrt(disc))) / (2*a) return (sol1, sol2) # execute print solver(a,b,c) From ethan at stoneleaf.us Tue Dec 9 18:43:10 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 09 Dec 2008 15:43:10 -0800 Subject: Don't you just love writing this sort of thing :) In-Reply-To: References: Message-ID: <493F028E.5050608@stoneleaf.us> Lawrence D'Oliveiro wrote: > for \ > Entry \ > in \ > sorted \ > ( > f for f in os.listdir(PatchesDir) if PatchDatePat.search(f) != None > ) \ > : > Patch = (open, gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir, Entry), "r") > ... read from Patch ... > Patch.close() > #end for Not all code has to be written for everyone. Not all code will be read by the masses. Some code you write for yourself... an expression of who you are, how you think... While my own quirks are not as visually entertaining, I think it's another mark in Python's favor that such self-expression is possible, and functional. Yes, Lawrence, I do love writing fun code. ~ethan~ From steve at holdenweb.com Mon Dec 15 10:50:58 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 15 Dec 2008 10:50:58 -0500 Subject: alt.possessive.its.has.no.apostrophe In-Reply-To: <87r649g9dg.fsf@benfinney.id.au> References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> Message-ID: <49467CE2.3060401@holdenweb.com> Ben Finney wrote: > James Stroud writes: > >> Ben Finney wrote: >>> James Stroud writes: >>> >>>> Yes. I think it was the British who decided that the apostrophe >>>> rule for "it" would be reversed from normal usage relative to >>>> just about every other noun. > > It also seems an indefensible claim to say that anyone ?decided? it > would be that way, especially ?the British?. > It's our language, dammit! Ours, ours, ours! This decision was actually taken at a meeting of the Society of British pedants on November 23, 1786. This led to a schism between the British and the newly-independent Americans, who responded by taking the "u" out of colour, valour, and aluminium. >>> Remember that ?it? is a pronoun. I see no reversal: >> Ok. Pronouns are reversed. > > Or, more generally: Pronouns, which are different in just about every > other way from other nouns, are different in this way also. Is that > about right? > Just think of them as "nounpros" and you won't go wrong. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From fetchinson at googlemail.com Wed Dec 17 16:09:04 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 17 Dec 2008 13:09:04 -0800 Subject: something else instead of PIL? In-Reply-To: <47c890dc0812171304u4bfd1d9eq2f55b2681e7302e4@mail.gmail.com> References: <47c890dc0812171304u4bfd1d9eq2f55b2681e7302e4@mail.gmail.com> Message-ID: >> what has happened to PIL? No updates since two years. > > The Python Imaging Library is still current; I guess they just haven't > found any new bugs or seen fit to add new functionality in a while, > though I presume they'll start working on a Python 3.0 port > eventually. That's actually an interesting question. Does anybody know if PIL is being ported to 3.0? Are there such plans? Maybe even code? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From endroussandrodelperkasa at gmail.com Fri Dec 12 07:24:51 2008 From: endroussandrodelperkasa at gmail.com (andrew) Date: Fri, 12 Dec 2008 04:24:51 -0800 (PST) Subject: IF YOU WANT TO LIVE LONGER, YOU SHOULD CHECK THIS!! Message-ID: <0905b402-2630-4057-87eb-11e15b9dad97@d42g2000prb.googlegroups.com> http://www.associatedcontent.com/article/995306/parameningeal_infection_brain_abscess.html?cat=70 From sjmachin at lexicon.net Tue Dec 30 19:22:09 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 30 Dec 2008 16:22:09 -0800 (PST) Subject: get method References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> <495AAB97.5010707@mrabarnett.plus.com> Message-ID: <71508d7a-f678-40ba-801c-0bbfbbab961e@r15g2000prh.googlegroups.com> On Dec 31, 10:58?am, "James Mills" wrote: > On Wed, Dec 31, 2008 at 9:15 AM, MRAB wrote: > > (snip) > > > A while back I posted a Python implementation of 'bag' (also called a > > multiset). The code would then become something like: > > What complexity is this ? The "armchair philosopher" approach: bag has an iteritems method so it's probably using a dict internally in which case a reasonable assumption is that the counting is implemented efficiently ... guess: bag(iterable) is O(len(iterable)) The "crawl through the shrubbery looking for evidence" approach stumbles on the actual code: def __init__(self, iterable=None): self._items = {} if iterable is not None: for item in iterable: self._items[item] = self._items.get(item, 0) + 1 confirming the guess. From yves at zioup.com Wed Dec 3 09:18:32 2008 From: yves at zioup.com (Yves Dorfsman) Date: Wed, 03 Dec 2008 14:18:32 GMT Subject: generating a liste of characters Message-ID: Is there any built in way to generate a list of characters, something along the line of range('a'-'z') ? Right now I am using: chars = [ chr(l) for l in range(0x30, 0x3a) ] # 0 - 9 chars += [ chr(l) for l in range(0x41, 0x5b) ] # A - Z chars += [ chr(l) for l in range(0x61, 0x7b) ] # a - z Is there a better, more straight forward way of doing that ? Thanks. Yves. http://www.sollers.ca/blog/2008/swappiness http://www.sollers.ca/blog/2008/swappiness/.fr From ibpet11 at gmail.com Tue Dec 30 10:30:55 2008 From: ibpet11 at gmail.com (ibpet11 at gmail.com) Date: Tue, 30 Dec 2008 07:30:55 -0800 (PST) Subject: folder extraction Message-ID: how do i get along with this task of extracting multiples folder and generating their names individually in a their respective files as they were generated. From fuzzyman at gmail.com Sun Dec 14 18:03:01 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 14 Dec 2008 15:03:01 -0800 (PST) Subject: Python 3.0 crashes displaying Unicode at interactive prompt References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> Message-ID: <3fad7e29-c9ac-4b2e-aabe-e23a4cc5cb2c@q30g2000prq.googlegroups.com> > That's an interesting definition of crash. You're just like saying: "C > has crashed because I made a bug in my program". In this context, it is > your program that crashes, not python nor C, it is misleading to say so. > > It will be python's crash if: > 1. Python 'segfault'ed > 2. Python interpreter exits before there is instruction to exit (either > implicit (e.g. falling to the last line of the script) or explicit (e.g > sys.exit or raise SystemExit)) > 3. Python core dumped > 4. Python does something that is not documented It seems to me to be a generally accepted term when an application stops due to an unhandled error to say that it crashed. Michael Foord http://www.ironpythoninaction.com/ From org.python.python-list at pooryorick.com Wed Dec 3 09:06:02 2008 From: org.python.python-list at pooryorick.com (=?utf-8?Q?Poor=20Yorick?=) Date: Wed, 03 Dec 2008 14:06:02 +0000 Subject: =?utf-8?B?UHl0aG9uMzogc29ydGluZyBpbWFnZSBvYmplY3RzIGFjY29yZGluZyB0byBhIGNtcCBmdW5jdGlvbg==?= Message-ID: <20081203140602.10205.qmail@s461.sureserver.com> I'm looking for a Python3-compatible way to sort a list of PIL image objects based on a computed difference between the two images. In 2.x, this would work: imagelist.sort(cmp=image_diff(a,b)) Maybe this could be done by creating a new class with the appropriate __lt__, ____gt__, __eq__ methods, but that seems like more work than should be necessary. Any suggestions? -- Yorick From suppertravel at gmail.com Fri Dec 12 15:40:38 2008 From: suppertravel at gmail.com (suppertravel at gmail.com) Date: Fri, 12 Dec 2008 12:40:38 -0800 (PST) Subject: No Scams plz! Read only if you are interested to work from home. Message-ID: <74e37d4a-5389-4ce8-b74f-e8d1ae90380b@e1g2000pra.googlegroups.com> Lowest air fares, tickets, packages, all inclusive, lower than any other agencies, we beat other prices: http://suppertravel.worldventures.com/ Become a travel agent and work from home make $$$$, we even pay for your car payment and mortgage: http://suppertravel.worldventures.biz/ From jcd at sdf.lonestar.org Sun Dec 14 16:55:07 2008 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Sun, 14 Dec 2008 16:55:07 -0500 Subject: the official way of printing unicode strings In-Reply-To: <6qk1o7Fcr01gU3@mid.uni-berlin.de> References: <6qk1o7Fcr01gU3@mid.uni-berlin.de> Message-ID: <20081214215507.GA28375@sdf.lonestar.org> On Sun, 2008-12-14 at 11:16 +0100, Piotr Sobolewski wrote: > Marc 'BlackJack' Rintsch wrote: > > > I'd make that first line: > > sys.stdout = codecs.getwriter('utf-8')(sys.stdout) > > > > Why is it even more cumbersome to execute that line *once* instead > > encoding at every ``print`` statement? > > Oh, maybe it's not cumbersome, but a little bit strange - but sure, I can > get used to it. > > My main problem is that when I use some language I want to use it the way it > is supposed to be used. Usually doing like that saves many problems. > Especially in Python, where there is one official way to do any elementary > task. And I just want to know what is the normal, official way of printing > unicode strings. I mean, the question is not "how can I print the unicode > string" but "how the creators of the language suppose me to print the > unicode string". I couldn't find an answer to this question in docs, so I > hope somebody here knows it. > > So, is it _the_ python way of printing unicode? > The "right way" to print a unicode string is to encode it in the encoding that is appropriate for your needs (which may or may not be UTF-8), and then to print it. What this means in terms of your three examples is that the first and third are correct, and the second is incorrect. The second one breaks when writing to a file, so don't use it. Both the first and third behave in the way that I suggest. The first (print u'foo'.encode('utf-8')) is less cumbersome if you do it once, but the third method (rebinding sys.stdout using codecs.open) is less cumbersome if you'll be doing a lot of printing on stdout. In the end, they are the same method, but one of them introduces another layer of abstraction. If you'll be using more than two print statements that need to be bound to a non-ascii encoding, I'd recommend the third, as it rapidly becomes less cumbersome, the more you print. That said, you should also consider whether you want to rebind sys.stdout or not. It makes your print statements less verbose, but it also loses your reference to the basic stdout. What if you want to print using UTF-8 for a while, but then you need to switch to another encoding later? If you've used a new name, you can still refer back to the original sys.stdout. Right: my_out = codecs.getwriter('utf-8')(sys.stdout) print >> my_out u"Stuff" my_out = codecs.getwriter('ebcdic')(sys.stdout) print >> my_out u"Stuff" Wrong sys.stdout = codecs.getwriter('utf-8')(sys.stdout) print u"Stuff" sys.stdout = codecs.getwriter('ebcdic')(sys.stdout) # Now sys.stdout is geting encoded twice, and you'll probably # get garbage out. :( print u"Stuff" Though I guess this is why the OP is doing: sys.stdout = codecs.getwriter('utf-8')(sys.__stdout__) That avoids the problem by not rebinding the original file object. sys.__stdout__ is still in its original state. Carry on, then. Cheers, Cliff From prologic at shortcircuit.net.au Tue Dec 16 20:54:59 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 17 Dec 2008 11:54:59 +1000 Subject: How to modify a program while it's running? In-Reply-To: <1fe20306-39ff-4169-b49e-5ae5dd8159af@v5g2000prm.googlegroups.com> References: <01584cbd$0$20656$c3e8da3@news.astraweb.com> <1fe20306-39ff-4169-b49e-5ae5dd8159af@v5g2000prm.googlegroups.com> Message-ID: @Aaron Your code and suggestion is way too complicated. Just register your objects. When you need to reload your module, destroy the existing objects and re-creat them. This works well assuming you have a stable running core that maintains the connection and that code doesn't change much. --JamesMills From bdesth.quelquechose at free.quelquepart.fr Sun Dec 7 13:13:18 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 07 Dec 2008 19:13:18 +0100 Subject: Guido's new method definition idea In-Reply-To: References: <493a9fed$0$18973$426a34cc@news.free.fr> Message-ID: <493c1ff6$0$4942$426a34cc@news.free.fr> Daniel Fetchinson a ?crit : (snip) > It doesn't add anything but makes something that exists a bit clearer Err... I fail to see how magically transforming def self.foo(...) into def foo(self, ...) makes anything clearer about what really happens and how Python's object model works. > and friendlier to newbies. I'd rather say "more acceptable to java-brainwashed developpers". From rogerb at rogerbinns.com Sun Dec 7 15:30:01 2008 From: rogerb at rogerbinns.com (Roger Binns) Date: Sun, 07 Dec 2008 12:30:01 -0800 Subject: Source code generation using Python In-Reply-To: <82098706-978f-4920-ac75-57ef3573ac44@x38g2000yqj.googlegroups.com> References: <82098706-978f-4920-ac75-57ef3573ac44@x38g2000yqj.googlegroups.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 ats wrote: > I want to generate 3 different versions of a C++ source code, > basically injecting different flavours of inline assembler depending > on target compiler/CPU. Are you aware that there are also packages that let you generate and call C code from Python on the fly? I find it most productive to write my code in all Python first and to also develop a comprehensive test suite. Then profile and replace selected portions with lower level C code with the tests being able to confirm your code is correct. Here are some packages that take an alternate approach: http://www.cs.tut.fi/~ask/cinpy/ http://code.google.com/p/shedskin/ http://pyinline.sourceforge.net/ http://scipy.org/Weave http://mdevan.nfshost.com/llvm-py/ I like LLVM the most. Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAkk8MkUACgkQmOOfHg372QRhsgCcCUzWHAHmjC1490yYba7c9Xrt DxMAnj/Ur2GoJkQgMrx65hYEqPwKLdVV =CvGB -----END PGP SIGNATURE----- From acerimusdux at comcast.net Wed Dec 10 21:33:51 2008 From: acerimusdux at comcast.net (acerimusdux) Date: Wed, 10 Dec 2008 21:33:51 -0500 Subject: Python is slow In-Reply-To: <7a1e6b94-1618-470c-a7ed-a2a5ada87d30@w24g2000prd.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <4b0f6c1a-9d3f-4fd7-8506-314d29ee87a8@k36g2000yqe.googlegroups.com> <7a1e6b94-1618-470c-a7ed-a2a5ada87d30@w24g2000prd.googlegroups.com> Message-ID: <49407C0F.10509@comcast.net> cm_gui wrote: > You guys are living in denial. > Python is SLOW, especially for web apps. > > Instead of getting mad, why don't get together and come up with a > faster VM/interpreter? > > The emperor doesn't like to be told he is not wearing any clothes? > > > O The one in denial is the one without any evidence to back his assertions. as someone once said, "In God we Trust. All others must have data." For example, the most recent benchmarks from The Computer Language Benchmark Game: http://shootout.alioth.debian.org/u64/benchmark.php?test=all&lang=al http://shootout.alioth.debian.org/u32/benchmark.php?test=all&lang=all http://shootout.alioth.debian.org/gp4/benchmark.php?test=all&lang=all On Gentoo on a Pentium 4 for example: mean 07.10 Python Psyco 19.34 Lua 23.00 Python 28.27 Perl 30.00 PHP 66.28 Javascript SpiderMonkey 75.12 Ruby I have no idea about Zope, but if that's slow, go complain to the devlopers of Zope. The Python interpreter is one of the fastest for a dynamically interpreted language. And Psyco is competitive with many other JIT compilers. I would think someone who has been obsessing about the speed of Python since May, and especially interested in a Python "VM" would have learned by now about Psyco? From steve at holdenweb.com Sat Dec 13 08:03:10 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 13 Dec 2008 08:03:10 -0500 Subject: __future__ and compile: unrecognised flags In-Reply-To: <20081213112917.6209.qmail@s461.sureserver.com> References: <20081213112917.6209.qmail@s461.sureserver.com> Message-ID: Poor Yorick wrote: > I have a future statement in a script which is intended to work in 2.6 and 3. > Shouldn't compile flags in __future__ objects essentially be noops for versions > that already support the feature? doctest is complaining about unrecognised > flags. This illustrates the problem: > > Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win > 32 > Type "help", "copyright", "credits" or "license" for more information. > >>> from __future__ import unicode_literals > >>> src = 'a = "hello"' > >>> c1 = compile(src,'','exec',unicode_literals.compiler_flag) > Traceback (most recent call last): > File "", line 1, in > ValueError: compile(): unrecognised flags > This could arguably be classed as a bug given that the 2.6 documentation for __future__ says "No feature description will ever be deleted from __future__." However I suspect that the feature has been removed because all string literals are Unicode in 3.0 and up, and 3.0 is allowed to break compatibility. One question is whether the 2to3 translator will remove such an import. If it does then one could argue this is just another of the many expected incompatibilities between 2.x and 3.x. If it doesn't, it should probably be made to. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steve at REMOVE-THIS-cybersource.com.au Thu Dec 4 09:45:46 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Dec 2008 14:45:46 GMT Subject: "as" keyword woes References: <7dudnSS7uIn_KarUnZ2dnUVZ_tTinZ2d@earthlink.com> Message-ID: <0147e4df$0$20670$c3e8da3@news.astraweb.com> On Thu, 04 Dec 2008 20:53:38 +1000, James Mills wrote: > Readability of your code becomes very important especially if you're > working with many developers over time. > > 1. Use sensible meaningful names. > 2. Don't use abbreviations. This is excellent advice, but remember, what is a sensible meaningful name is domain-specific. In a maths library, this would be sensible: def poly(x): return 4*x**3 -2*x**2 +3*x -7 and this ridiculous: def poly(real_number): return 4*real_number**3 -2*real_number**2 +3*real_number -7 Sometimes there are name clashes between keywords and sensible names in your problem space. I'm sure every regular Python developer has found themselves writing something like: prnt print_ print2 cls klass class_ or similar. In the standard library, the random module uses an argument "lambd" because lambda is a keyword. -- Steven From jstroud at mbi.ucla.edu Fri Dec 5 23:35:07 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 05 Dec 2008 20:35:07 -0800 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: Daniel Fetchinson wrote: > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html > > The proposal is to allow this: > > class C: > def self.method( arg ): > self.value = arg > return self.value > > instead of this: > > class C: > def method( self, arg ): > self.value = arg > return self.value > I'd like this new way of defining methods, what do you guys think? Consider the maverick who insists on class C: def me.method(arg): self.value = arg which should be equivalent to class C: def method(me, arg): me.value = arg What's the interpreter going to do with our maverick's code? James From rogerb at rogerbinns.com Wed Dec 24 05:44:59 2008 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 24 Dec 2008 02:44:59 -0800 Subject: Most efficient way to build very large dictionaries In-Reply-To: <5fa6c12e0812240218yc9a7185maaf5211dbddd8134@mail.gmail.com> References: <1230104615.5867.1291617213@webmail.messagingengine.com> <1230107768.14060.1291622121@webmail.messagingengine.com> <5fa6c12e0812240218yc9a7185maaf5211dbddd8134@mail.gmail.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Martin wrote: > I'd think he's talking about in memory SQLite Databases, this way you > should be quite fast _and_ could dump all that to a persistent > storage... I was just talking about regular on disk SQLite databases. In terms of priming the pump, you can just open/read/close the whole database file which will cause the database to be in the operating system cache buffers, or just let SQLite do its thing. For anyone who is curious about what Martin is referring to, SQLite does support the database file being memory (although it isn't a file at that point). It has a fake filename of :memory:. As an example you can copy the table 'example' to memory using: ATTACH ':memory:' as memdb; CREATE TABLE memdb.memexample AS select * from example; As with Python, all this stuff is premature optimization. Get it working right first and then try tweaks to improve performance. Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAklSEqcACgkQmOOfHg372QTPpgCgvSKGMCJAKhnm5I8qHdmZtRh3 SgMAoI3DVhWCVdUE1TLck9ZEfp/Ln1H5 =5kNT -----END PGP SIGNATURE----- From digitalarena.tk at gmail.com Thu Dec 4 06:44:05 2008 From: digitalarena.tk at gmail.com (anum) Date: Thu, 4 Dec 2008 03:44:05 -0800 (PST) Subject: hi Message-ID: www.digitalarena.tk From geekmail at usenot.de Sun Dec 7 14:35:53 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sun, 7 Dec 2008 20:35:53 +0100 Subject: Is 3.0 worth breaking backward compatibility? References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> Message-ID: <20081207203553.7d62434a@usenot.de> On Sun, 7 Dec 2008 11:22:23 -0800 (PST) walterbyrd wrote: > IMO: breaking backward compatibility is a big deal, and should only be > done when it is seriously needed. > Pleeeeze. Python 3 is shipping now, and so is 2.x, where x > 5. Python 2 is going to be around for quite some time. What is everybody's problem? > Also, IMO, most of, if not all, of the changes being made in 3.0 are > debatable, at best. I can not think of anything that is being changed > that was really a "show stopper" anyway. > Right. But warts accumulate, and some day you'll have a troglodyte of a language. Better to scrubb off some warts every now and then, so the whole thing remains agile. > At best, I am a casual python user, so it's likely that I am missing > something. Yes, the big picture. Also, being a casual Python user (like myself, just to clarify), *you* will least be bitten by the incombatibilties. I *really* don't get all the outrage. It's a major new version. What better time to tighten things up a bit? /W -- My real email address is constructed by swapping the domain with the recipient (local part). From w_a_x_man at yahoo.com Wed Dec 10 15:37:50 2008 From: w_a_x_man at yahoo.com (w_a_x_man at yahoo.com) Date: Wed, 10 Dec 2008 12:37:50 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: On Dec 5, 9:51?am, Xah Lee wrote: > > For those of you who don't know linear algebra but knows coding, this > means, we want a function whose input is a list of 3 elements say > {x,y,z}, and output is also a list of 3 elements, say {a,b,c}, with > the condition that > > a = x/Sqrt[x^2+y^2+z^2] > b = y/Sqrt[x^2+y^2+z^2] > c = z/Sqrt[x^2+y^2+z^2] > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, > you'll have 50 or hundreds lines. Ruby: def norm a s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) a.map{|x| x/s} end From ndbecker2 at gmail.com Sat Dec 6 13:03:11 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Sat, 06 Dec 2008 13:03:11 -0500 Subject: Guido's new method definition idea References: Message-ID: Daniel Fetchinson wrote: > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html > > The proposal is to allow this: > > class C: > def self.method( arg ): > self.value = arg > return self.value > > instead of this: > > class C: > def method( self, arg ): > self.value = arg > return self.value > > I.e. explicit self stays only the syntax is slightly different and may > seem attractive to some. As pointed out by Guido classmethods would > work similarly: > > class C: > @classmethod > def cls.method( arg ): > cls.val = arg > return cls.val > > The fact that Guido says, > > "Now, I'm not saying that I like this better than the status quo. But > I like it a lot better than [...] but it has the great advantage that > it is backward compatible, and can be evolved into a PEP with a > reference implementation without too much effort." > > shows that the proposal is viable. > > I'd like this new way of defining methods, what do you guys think? > Anyone ready for writing a PEP? > What's the advantage? If there is not a good reason, I would strongly opposed polluting the language. From vniboris at hotmail.com Tue Dec 2 10:19:35 2008 From: vniboris at hotmail.com (B R) Date: Tue, 2 Dec 2008 15:19:35 +0000 Subject: "server chain" with python socket module Message-ID: dear all, I want to connect my A machine to the E server via servers B, C and D, is there a way to set-up such "server chain" with python socket module (or other module) ? many thanks boris vn%ibo%ris[at]hotmail.com _________________________________________________________________ News, entertainment and everything you care about at Live.com. Get it now! http://www.live.com/getstarted.aspx -------------- next part -------------- An HTML attachment was scrubbed... URL: From mnordhoff at mattnordhoff.com Tue Dec 9 03:11:08 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Tue, 09 Dec 2008 08:11:08 +0000 Subject: html codes In-Reply-To: References: Message-ID: <493E281C.1030609@mattnordhoff.com> Daniel Fetchinson wrote: > Hi folks, > > I came across a javascript library that returns all sorts of html > codes in the cookies it sets and I need my web framework (written in > python :)) to decode them. I'm aware of htmlentitydefs but > htmlentitydefs.entitydefs.keys( ) are of the form '&#xxx' but this > javascript library uses stuff like '%3A' for the ':' for example. The > conversion is here: > > http://www.ascii.cl/htmlcodes.htm > > Is there a python package/module/whatever that does the conversion for > me or do I have to write a little wrapper myself (and introduce bugs > while doing so :))? > > Cheers, > Daniel >>> import urllib >>> urllib.unquote('%20') ' ' -- From mal at egenix.com Wed Dec 10 16:17:40 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 10 Dec 2008 22:17:40 +0100 Subject: getting back into programming In-Reply-To: <8796344d-1c02-441e-8272-8a7638faae39@j39g2000yqn.googlegroups.com> References: <8796344d-1c02-441e-8272-8a7638faae39@j39g2000yqn.googlegroups.com> Message-ID: <494031F4.7060004@egenix.com> On 2008-12-10 22:02, usawargamer at yahoo.com wrote: > I used to program in C and Perl (up until 2001) (a little C++ and Java > too). Since then I've been a Business Analyst and only coded in VBA/ > Excel and written some SQL queries. (we use Sybase) > > I feel the need for other tools. > Primarily I want to write a bunch of small programs to query a > database and perform some calculations. While I can do this inside a > Sybase stored procedure, its a bit messy trying to "reimplement" a set > of calculations from Excel into Sybase. > > I would like to either: > - relearn Perl > or > - learn Python (I have heard its a nice language) > > 1. How good and easy to use is the Python database interface (to > Sybase)? If you're looking for a reliable database interface to Sybase, I'd suggest mxODBC: http://www.egenix.com/products/python/mxODBC/ It's been used in production by many banks for years and so far without problems. > 2. Can you suggest some good books, and/or links for learning Python, > as well as teh database interface? One of the best books is "Learning Python": http://oreilly.com/catalog/9781565924642/ > 3. How difficult is it to install Python vs Perl on PC/Windows > machines? There's an MSI installer, so it's basically just a few clicks away: http://www.python.org/download/ Hope that helps, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 10 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-12-02: Released mxODBC.Connect 1.0.0 http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From prologic at shortcircuit.net.au Mon Dec 8 01:17:57 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Dec 2008 16:17:57 +1000 Subject: A question about reference in Python. In-Reply-To: <47c890dc0812072213q20cb415fjbd4c80e7af7a7ef5@mail.gmail.com> References: <493CB003.3080209@gmail.com> <47c890dc0812072213q20cb415fjbd4c80e7af7a7ef5@mail.gmail.com> Message-ID: On Mon, Dec 8, 2008 at 4:13 PM, Chris Rebert wrote: > The following three lines serve no purpose and can only lead to confusion: >> value = None >> prev = None >> next = None You are absolutely right :) Updated code: #!/home/jmills/bin/python -i class Node(object): def __init__(self, value, prev=None, next=None): self.value = value self.prev = prev self.next = next class List(object): def __init__(self, *seq): if seq: first = prev = node = None for x in seq: if not first: first = Node(x) prev = node = first else: node = Node(x, prev) prev.next = node prev = node self.data = first else: self.data = None def __getitem__(self, x): node = self.data for i in xrange(x): node = node.next return node.value x = List(0, 1, 2, 3) cheers Jaems PS: Sorry Chris :) -- -- -- "Problems are solved by method" From lists at cheimes.de Mon Dec 22 17:25:10 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 22 Dec 2008 23:25:10 +0100 Subject: python3 urlopen(...).read() returns bytes In-Reply-To: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> References: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> Message-ID: Glenn G. Chappell schrieb: > I just ran 2to3 on a py2.5 script that does pattern matching on the > text of a web page. The resulting script crashed, because when I did > > f = urllib.request.urlopen(url) > text = f.read() > > then "text" is a bytes object, not a string, and so I can't do a > regexp on it. > > Of course, this is easy to patch: just do "f.read().decode()". > However, it strikes me as an obvious bug, which ought to be fixed. > That is, read() should return a string, as it did in py2.5. It's not possible unless you know the encoding of the bytes. Network io only returns byte and you must encode it explicitly. You "patch" breaks as soon as a remote sites returns the data in a different encoding. It also breaks if the site returns an image/*, appliation/*, audio/* or any other mimetype than text. There is no generic and simple way to detect the encoding of a remote site. Sometimes the encoding is mentioned in the HTTP header, sometimes it's embedded in the section of the HTML document. > This change breaks pretty much every Python program that opens a > webpage, doesn't it? 2to3 doesn't catch it, and, in any case, why > should read() return bytes, not string? Am I missing something? I hope I was able to explain the issue. By the way Python 2.x and 3.0 are both returning bytes (str in 2.x, bytes in 3.0). Christian From geekmail at usenot.de Fri Dec 5 15:39:52 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Fri, 5 Dec 2008 21:39:52 +0100 Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> <84332560-580d-488b-aa6b-6aad754a7805@k36g2000pri.googlegroups.com> Message-ID: <20081205213952.35e9ec3e@usenot.de> On Fri, 5 Dec 2008 12:16:47 -0800 (PST) "Fernando H. Sanches" wrote: > On Dec 4, 5:45?pm, Andreas Waldenburger wrote: > > On Thu, 4 Dec 2008 11:52:38 -0600 s... at pobox.com wrote: > > [snip] > > Whenever has it been a pythonic ideal to "not allow" stuff? You get > > warnings. Everything else is up to you. > > > > [snip] > > Python has "not allowed stuff" for a long time. > > For example, it disallows statements in lambdas. > Which is sensible (for Python) because it does not have block delimiters. Also, lambdas are syntactic sugar for special use cases. It's not like they are needed at all. But sometimes mixing tabs and spaces can be needed (think coding standards). What else is disallowed? > "Disallowing" is not bad. Disallowing bad practices (like mixing tabs > and spaces) is actually good! > This presupposes that mixing tabs and spaces is "bad". That's like saying C++ is bad. > I agree that the tab/space thing should be changed. Would it be too > hard to make the parser see if the indentation is consistent in the > whole file? Maybe not, but it would be rather hard to agree on what can be called consistent and what can not, I think. You can mix spaces and tabs consistently, just as you can use any one consistently. > This is a annoying source of problems, specially since > you can't tell a whitespace from a tab just looking at it. > There are editors that let you show different symbols for spaces and tabs (I know, I know ...). > And I personally disliked most of the changes (specially the ones on > map and reduce). I hope functional programming doesn't get even more > hindered in future releases, because I believe these changes only made > Python weaker. > +1 /W -- My real email address is constructed by swapping the domain with the recipient (local part). From steve at REMOVE-THIS-cybersource.com.au Sat Dec 13 06:07:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Dec 2008 11:07:53 GMT Subject: Removing None objects from a sequence References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> <4942E668.5030100@tim.thechases.com> Message-ID: <01538f0c$0$6988$c3e8da3@news.astraweb.com> On Fri, 12 Dec 2008 19:02:24 -0500, Terry Reedy wrote: > Tim Chase wrote: >>> If you want to literally remove None objects from a list....(or >>> mutable sequence) >>> >>> def deNone(alist): >>> n=len(alist) >>> i=j=0 >>> while i < n: >>> if alist[i] is not None: >>> alist[j] = alist[i] >>> j += 1 >>> i += 1 >>> alist[j:i] = [] >>> >>> blist=[None,1,None,2,None,3,None,None,4,None] deNone(blist) >>> print(blist) >>> >>> # prints [1, 2, 3, 4] >> >> ...wouldn't a cleaner way of doing this just be >> >> >>> blist=[None,1,None,2,None,3,None,None,4,None] > > No, making a filtered copy that is then copied back before being deleted > is algorithmically much messier. My code does the minimum work > necessary and is algorithmically cleaner. Er what? You're joking, right? Your function has eight lines, all of which are very low level: you're dealing with not one but TWO list indexes yourself. You have three internal names to deal with, although in fairness one is set once then used as a constant from then on. The algorithm is unclear: try explaining what you are doing in English, and see how difficult it is. "Keep two indexes into the list. If the first index isn't pointing at None, copy that value to the second index, which is either the same as the first index, or pointing at None. Then advance the second index, and the first index, as needed. It will never over-write a non-None value, but just try proving it." Contrast that with the alternative suggested by Tim: def deNone2(alist): alist[:] = [x for x in alist if x is not None] It's one line, with one internal variable. You don't have to manipulate index variables. The explanation is simple: "Make a new list with the non-None values and assign it in-place to the old list." Clear, succinct, and understandable, with no corner cases like empty lists to worry about. Here's another low-level algorithm, the classical delete items in place algorithm. Three lines, one index, lousy O(N**2) performance. def deNone3(alist): for i in xrange(len(alist)-1, -1, -1): if alist[i] is None: del alist[i] Now, let's do a shoot-out. Do they return the same thing? >>> masterlist = [None]*2 + range(5) + [None]*3 + range(5, 10) + [None]*4 + [10, None, 11, None, 12, None] >>> alist = masterlist[:] >>> blist = masterlist[:] >>> clist = masterlist[:] >>> deNone(alist) >>> deNone2(blist) >>> deNone3(clist) >>> alist == blist == clist True Which is faster? >>> from timeit import Timer >>> setup = "from __main__ import deNone, deNone2, deNone3;" \ ... " from __main__ import masterlist as m" >>> t1 = Timer("a=m[:];deNone(a)", setup) >>> t2 = Timer("a=m[:];deNone2(a)", setup) >>> t3 = Timer("a=m[:];deNone3(a)", setup) >>> t1.repeat(number=10000) [0.39079904556274414, 0.38915109634399414, 0.39700794219970703] >>> t2.repeat(number=10000) [0.17854905128479004, 0.1782989501953125, 0.17886185646057129] >>> t3.repeat(number=10000) [0.26834988594055176, 0.25835609436035156, 0.25850009918212891] Not surprisingly, Tim's version is twice as fast as yours. Surprisingly, even the deNone3 function is faster than yours. What about a real test? None of these piddly toy data sets, with 25 items. Something *real*. >>> masterlist = masterlist*100 >>> masterlist += range(1000) >>> masterlist += [None]*1000 >>> masterlist += [None, 0]*1000 >>> masterlist += [1]*10000 >>> len(masterlist) 16500 >>> t1.repeat(number=100) [2.1611621379852295, 1.2539350986480713, 1.2424759864807129] >>> t2.repeat(number=100) [0.93860101699829102, 0.44704914093017578, 0.41285014152526855] >>> t3.repeat(number=100) [4.5643420219421387, 3.216562032699585, 3.2176508903503418] Not surprisingly, my version really suffers. But so does yours: it's now three times slower than Tim's. I expect that Tim's version will look better and better until the list is so huge that memory paging to disk becomes a factor. Now, sure, most of the work in Tim's version is executed in fast C code instead of slow Python code. If we were programming in C, your version might perform better relative to Tim's. But even if performance was better, I wouldn't describe the algorithm as particularly clean. -- Steven. From skip at pobox.com Sat Dec 27 13:54:00 2008 From: skip at pobox.com (Skip Montanaro) Date: Sat, 27 Dec 2008 18:54:00 +0000 (UTC) Subject: Test message - please ignore Message-ID: Test post via gmane. Please ignore. From rogerb at rogerbinns.com Wed Dec 24 03:19:56 2008 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 24 Dec 2008 00:19:56 -0800 Subject: Most efficient way to build very large dictionaries In-Reply-To: <1230104615.5867.1291617213@webmail.messagingengine.com> References: <1230104615.5867.1291617213@webmail.messagingengine.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 python at bdurham.com wrote: > I would appreciate your thoughts on whether there are advantages to > working with a pre-built dictionary and if so, what are the best ways to > create a pre-loaded dictionary. Based on this and your other thread, you may want to consider using SQLite (standard Python module is available for it). SQL queries are very similar to set operations and indices take care of performance (by using more storage). You also get transactions for free. If you look into SQLite pragmas you can get it to use more RAM to improve performance. And by using a SQL layer you can later switch to another database should you need really hard core storage. It also makes the data available to other programs in a uniform way. Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAklR8KgACgkQmOOfHg372QSrHQCfVJzueXVKme8QZcxoLf70BL4K RL8AoM9QOFykOLrr5QXtpmZ5f7CFHm6e =zAPG -----END PGP SIGNATURE----- From bdesth.quelquechose at free.quelquepart.fr Thu Dec 4 14:35:01 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 Dec 2008 20:35:01 +0100 Subject: Python Runtime Method Call Binding In-Reply-To: <0ad65087-9b50-4d11-85a4-0ebf7e8e01a0@c1g2000yqg.googlegroups.com> References: <0147f396$0$20670$c3e8da3@news.astraweb.com> <0ad65087-9b50-4d11-85a4-0ebf7e8e01a0@c1g2000yqg.googlegroups.com> Message-ID: <49383e9e$0$16497$426a74cc@news.free.fr> k3xji a ?crit : > test failed !-) From martin at v.loewis.de Tue Dec 2 13:56:19 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 02 Dec 2008 19:56:19 +0100 Subject: Multiple Versions of Python on Windows XP In-Reply-To: <4934F82D.1090601@g.nevcal.com> References: <4934de22$0$27863$9b622d9e@news.freenet.de> <4934E183.9020404@g.nevcal.com> <4934E3BF.7000403@v.loewis.de> <4934F82D.1090601@g.nevcal.com> Message-ID: <493584D3.1090301@v.loewis.de> > OK, Issue 4485 created. My first one, so let me know if I goofed. I > elaborated a bit from the original email, upon reflection. Seemed > useful, but also seemed complex by the time I got done. Looks about right to me. > I don't really have a clue what the uninstaller should do with these; > nor have I fiddled to know if it presently removes Python.File. I > suppose it should delete them, if and only if the ftype and assoc have > the same content as was created by the corresponding version installation. The uninstaller will currently just remove it all. Conditional removal of the associations will be tricky; I'll look into it. I also wonder whether assoc only changes the settings for the current user. In that case, uninstalling a Python version that was per-machine would not affect the user's association, anyway. Regards, Martin From ionut.vancea at gmail.com Thu Dec 4 08:56:53 2008 From: ionut.vancea at gmail.com (Ionut Vancea) Date: Thu, 4 Dec 2008 13:56:53 +0000 Subject: RELEASED Python 3.0 final In-Reply-To: <6a5569ec0812040554h7f5bca4btd4d32c28ed04a0b6@mail.gmail.com> References: <1a73e3be-1753-4178-8091-eaa890b3e07e@l42g2000yqe.googlegroups.com> <6a5569ec0812040554h7f5bca4btd4d32c28ed04a0b6@mail.gmail.com> Message-ID: <368177940812040556i679ba4fewfee395a8923a4a6d@mail.gmail.com> Hi On Thu, Dec 4, 2008 at 1:54 PM, Roy H. Han wrote: > Hi, > > This is great, however, the link to the What's New page appears to be > broken. > http://docs.python.org/dev/3.0/whatsnew/3.1.html replace 3.1 with 3.0 :), so it has to be: http://docs.python.org/dev/3.0/whatsnew/3.0.html Cheers, -- === Ioan Vancea http://www.vioan.ro From lihang9999 at gmail.com Wed Dec 17 18:00:35 2008 From: lihang9999 at gmail.com (Li Han) Date: Wed, 17 Dec 2008 15:00:35 -0800 (PST) Subject: The rule of literal string References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> Message-ID: But what repr() do remain a black hole! Han From wuwei23 at gmail.com Wed Dec 3 00:28:04 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 2 Dec 2008 21:28:04 -0800 (PST) Subject: best way to do this References: <137514ca-d16c-4713-b14f-e12ab4f607ab@c36g2000prc.googlegroups.com> Message-ID: <8f29535d-56e6-4818-ba34-7e128e05c197@d36g2000prf.googlegroups.com> On Dec 3, 1:38?pm, thor wrote: > >>> c = [(5, 3), (6, 8)] > >>> [x for t in zip(*c) for x in t] > [5, 6, 3, 8] The zip here is superfluous. >>> c = [(5, 3), (6, 8)] >>> zip(*c) [(5, 6), (3, 8)] Unless you're -only- using it to ensure your result is the same order as the OP...but he also stressed that order was unimportant. Leaving out the zip call gives you Arnaud's solution, which seems the clearest. From news123 at free.fr Sat Dec 6 13:02:22 2008 From: news123 at free.fr (News123) Date: Sat, 06 Dec 2008 19:02:22 +0100 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: <493abe2e$0$15998$426a34cc@news.free.fr> Daniel Fetchinson wrote: > The proposal is to allow this: > > class C: > def self.method( arg ): > self.value = arg > return self.value > > instead of this: > > class C: > def method( self, arg ): > self.value = arg > return self.value Hmm, I'd give the proposal a -1. Perhaps I'm missing something though. Does this really justify an enhancement? Whether the implicit parameter is prepended with a dot or whether it's the first parameter with the parantheses doesn't save me any typing and the benefit of 'visualizing' how the function should be called seems minor to me. What would be interesting would be some syntactical sugar to get rid of the 'self' (at least in the code body). example: class C: class_elements a,b,c,d def method(self,arg): global d a,b,c = arg[0..3] d = a + b self.e = a + d instead of class C: def method(self,arg): self.a,self.b,self.c,self.d = arg[0..4] self.e = self.a + self.b As far as I understood (I never really followed any of these threads), getting rid of self has already been discussed and rejected many times. bye N From duncan.booth at invalid.invalid Tue Dec 16 05:10:24 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Dec 2008 10:10:24 GMT Subject: weird dict problem, how can this even happen? References: Message-ID: Joel Hedlund wrote: > I should probably do this with lists instead because I can't really > think of a way of salvaging this. Am i right? > I think you probably are correct. The only thing I can think that might help is if you can catch all the situations where changes to the dependent values might change the hash and wrap them up: before changing the hash pop the item out of the dict, then reinsert it after the change. Alternatively give up on defining hash and __eq__ for FragmentInfo and rely on object identity instead. -- Duncan Booth http://kupuguy.blogspot.com From Shawn.Gong at drdc-rddc.gc.ca Thu Dec 11 16:04:38 2008 From: Shawn.Gong at drdc-rddc.gc.ca (Gong, Shawn (Contractor)) Date: Thu, 11 Dec 2008 16:04:38 -0500 Subject: Python 2.5.2 error on Solaris, No module named _md5 Message-ID: hi list, I tried to build Python 2.5.2 on Solaris 9 with gcc 3.4.6 under my user account. (there is already an older 2.5.1 on /usr/local/, so I used "make -I install") When I "import md5", I got: Python 2.5.2 (r252:60911, Dec 11 2008, 15:16:41) [GCC 3.4.6] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import md5 Traceback (most recent call last): File "", line 1, in File "/home/sgong/dev181/dist/lib/python2.5/md5.py", line 6, in from hashlib import md5 File "/home/sgong/dev181/dist/lib/python2.5/hashlib.py", line 133, in md5 = __get_builtin_constructor('md5') File "/home/sgong/dev181/dist/lib/python2.5/hashlib.py", line 60, in __get_builtin_constructor import _md5 ImportError: No module named _md5 I then tried Python 2.6.1 but with the same error. Any help is appreciated. thanks, Shawn -------------- next part -------------- An HTML attachment was scrubbed... URL: From bdesth.quelquechose at free.quelquepart.fr Tue Dec 30 15:52:47 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 30 Dec 2008 21:52:47 +0100 Subject: SQL, lite lite lite In-Reply-To: <186e44f7-f949-45e2-b1e2-a913560acf94@s9g2000prg.googlegroups.com> References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> <8da5c6b1-951f-4abd-8ee7-07b63802b9f6@13g2000yql.googlegroups.com> <186e44f7-f949-45e2-b1e2-a913560acf94@s9g2000prg.googlegroups.com> Message-ID: <495a97ce$0$25469$426a74cc@news.free.fr> Aaron Brady a ?crit : > On Dec 30, 11:16 am, prueba... at latinmail.com wrote: (snip) >> You really do like to reinvent the wheels do you? :-) Nothing wrong >> with that. Just be aware that most people that really need what you >> are proposing are probably already using mature feature rich libraries >> for that. >> >> http://wiki.python.org/moin/HigherLevelDatabaseProgramming > > Look at these options! Who invents the wheel? Naturally, I've had > time to master every one. > Oh, so that's why you propose to add yet another item to the list ? From metebilgin48 at gmail.com Fri Dec 5 09:52:01 2008 From: metebilgin48 at gmail.com (mete bilgin) Date: Fri, 5 Dec 2008 16:52:01 +0200 Subject: mod_python and files directory Message-ID: Hi all, I try to make a websevice with python and mod_python. ? try to make a po files, but i can not reach them in the page. When i ask the page like " os.listdir('.') " but i want to get files directory, what can i do? sorry for my bad describe of that. Thanks a lot... -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrew at doadesweb.co.uk Thu Dec 11 12:48:08 2008 From: andrew at doadesweb.co.uk (Andrew Doades) Date: Thu, 11 Dec 2008 17:48:08 +0000 Subject: get todays files In-Reply-To: <494015F7.3020302@tim.thechases.com> References: <4632c353-0462-485b-9e1b-6a5c56682363@s9g2000prg.googlegroups.com> <494015F7.3020302@tim.thechases.com> Message-ID: <49415258.2010101@doadesweb.co.uk> Tim Chase wrote: >> This looks very good and I have tested successfully, but is there a >> way I can set the today to automatically become todays date in that >> format? > > Yes...see the python datetime module[1]...particularly the strftime() > call on date/datetime objects. > > -tkc > > [1] > http://docs.python.org/library/datetime.html I know this will sound like I am being very cheeky, but is there a way you can make this for where the ftp server is actually windows server? The script runs and it shows the date the file was modified, but still downloads them, I have attached the script I am now using with your code in. import os from ftplib import FTP import subprocess from datetime import datetime from time import gmtime, strftime curr_date = strftime("%d %B %Y", gmtime()) # config ftp_uname = '' ftp_pwd = '' ftp_server = '' # end of config fileroot = 'DBBackup_' os.chdir('c:/') files = [] logfile = open('c:/dbbackup/getmdbackups.log','a+') def makelist(line): if (line.startswith(fileroot)): fs = [line] files.append(fs) def log(line): ll = str(datetime.now()) + ' : ' + str(line) print ll logfile.write(ll + '\n') def fileexists(ff, size): if (os.path.exists(ff)): stat = os.stat(ff) if (stat.st_size == size): return True return False try: # first connect using ftp to get a list of valid backup failes available log('Connecting to ftp server') ftp = FTP(ftp_server) ftp.set_pasv(False) #ftp.set_debuglevel(2) resp = ftp.login(ftp_uname,ftp_pwd) log(resp) ftp.retrlines('NLST',makelist) log(str(files)) ftp.quit() # fetch files in a loop using wget. for ff in files: ftp = FTP(ftp_server) ftp.set_pasv(False) resp = ftp.login(ftp_uname,ftp_pwd) log(resp) size = ftp.size(ff[0]) log('Size of server file = ' + str(size)) #ftp.quit() try: if (not fileexists(ff[0],size)): results = ftp.sendcmd("MDTM %s" % ff[0]) code, stamp = results.split(None, 1) assert code == "213", "Unexpected result" print "%s was modified on %s" % (ff[0], stamp) today = curr_date if stamp[:8] == today: log('Transferring: ' + ff[0]) # make parameters to wget the backup file params = ' ftp://' + ftp_server + '/' + ff[0] rcode = subprocess.call('c:/wget.exe ' + params) log('Return code from wget = ' + str(rcode)) if (rcode == 0): ff[1] = 1 else: log('File ' + ff[0] + ' already exists locally, not transferring') ff[1] = 1 except Exception, e: log(str(e)) log('Transfer complete') # delete the server files that have been transferred or are already here with the right filesize. for ff in files: if (ff[1] == 1): log('delete ' + ff[0]) except Exception,e: log(str(e)) # clean up temp files log('Finished.') logfile.close() From robert.kern at gmail.com Thu Dec 4 17:46:53 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 04 Dec 2008 16:46:53 -0600 Subject: using distutils to cross-compile extensions? In-Reply-To: <49385CBB.7060207@cs.cornell.edu> References: <49385CBB.7060207@cs.cornell.edu> Message-ID: <49385DDD.2030108@gmail.com> Michael George wrote: > Hi, > > Please CC me in replying as I am off list. > > I have an extension module that I've built using distutils. I wonder if > it's possible to use distutils to cross-compile it for windows on my > linux box, and whether the pain involved is great. Can anyone point me > in the right direction? It *might* be possible with a number of ugly hacks, but the pain involved would, indeed, be great. distutils does not support cross-compiling at all. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From deets at nospam.web.de Mon Dec 1 14:09:29 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 01 Dec 2008 20:09:29 +0100 Subject: Import of egg packages installed with easy_install References: Message-ID: <6piqvpF839bkU2@mid.uni-berlin.de> Alexey Vlasov wrote: > Hi. > > There's an already installed with easy_install packet, let's say flup, > to the home catalog: > $ ls -la ~/python/lib/python2.5/site-packages/ > total 176 > drwxr-xr-x 3 4096 Nov 29 18:57 . > drwxr-xr-x 3 4096 Nov 29 18:51 .. > -rw-r--r-- 1 208 Nov 29 18:57 easy-install.pth > -rw-r--r-- 1 134573 Nov 29 18:51 flup-1.0.1-py2.5.egg > -rw-r--r-- 1 2362 Nov 29 18:51 site.py > -rw-r--r-- 1 1853 Nov 29 18:51 site.pyc > > > $ cat ~/python/lib/python2.5/site-packages/easy-install.pth > import sys; sys.__plen = len(sys.path) > ./flup-1.0.1-py2.5.egg > import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; > p=getattr(sys,'__egginsert',0); sys.path[p:p]=new; sys.__egginsert = > p+len(new) > > $ echo $PYTHONPATH > /usr/lib64/portage/pym:/home/username/python/lib64/python2.5/site-packages > > $ python > Python 2.5.2 (r252:60911, Nov 13 2008, 15:01:36) > [GCC 4.1.2 (Gentoo 4.1.2 p1.1)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import flup > > No errors. > > Then I create a simple CGI script: > ======== > #!/usr/bin/python > > print "Content-type: text/plain"; > print > > import sys > sys.path.insert (0, > '/home/username/python/lib64/python2.5/site-packages') > print sys.path > import flup > ======== > > Browser says: > ['/home/username/python/lib64/python2.5/site-packages', > '/home/username/http', '/usr/lib64/python25.zip', > '/usr/lib64/python2.5', '/usr/lib64/python2.5/plat-linux2', > '/usr/lib64/python2.5/lib-tk', '/usr/lib64/python2.5/lib-dynload', > '/usr/lib64/python2.5/site-packages'] > > in error log: > [Sat Nov 29 19:41:15 2008] [error] Traceback (most recent call last): > [Sat Nov 29 19:41:15 2008] [error] File "path.cgi", line 9, in > [Sat Nov 29 19:41:15 2008] [error] import flup > [Sat Nov 29 19:41:15 2008] [error] ImportError: No module named flup > > > If you start it with console, you get the same, but there appears also > another path: > /home/username/python/lib64/python2.5/site-packages/flup-1.0.1-py2.5.egg > > As I understand it is the problem actually, but I can't get why sys.path > doesn't contain this path when I request with HTTP. It's not sufficient to add simply your local site-packages, you must install it using the module site's addsitedir-function, like this: import site site.addsitedir("/home/username/python/lib/python2.5/site-packages") The reason is that otherwise the *.pth-files in the site-packages aren't picked up. Diez From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 21:07:33 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2008 02:07:33 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <015c4ab6$0$20656$c3e8da3@news.astraweb.com> On Fri, 19 Dec 2008 19:10:59 +0100, Christian Heimes wrote about % formatting in Python 3: > It's not going to be removed for many years - if ever. The % string > formatting system is not deprecated in 3.0. For that very reason it must > stay until 3.2. We don't have plans to deprecate it in 3.1 so it will > stay at least until Python 3.3 which is to be released about 2014. I am very glad to hear that. -- Steven From steve at holdenweb.com Sat Dec 20 11:31:38 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 20 Dec 2008 11:31:38 -0500 Subject: WAGs on when django will use Python 3.0? In-Reply-To: <7f6a70f9-4b97-44f9-86fe-db84ae733077@g1g2000pra.googlegroups.com> References: <7f6a70f9-4b97-44f9-86fe-db84ae733077@g1g2000pra.googlegroups.com> Message-ID: walterbyrd wrote: > Will Django be primarily using Python 3.0 one year from now? Two years > from now? > I doubt they will drop 2.X support in the next two years. 3.0 will likely be supported fairly fully in the next year. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From prahaai at gmail.com Thu Dec 11 11:31:40 2008 From: prahaai at gmail.com (Cro) Date: Thu, 11 Dec 2008 08:31:40 -0800 (PST) Subject: Why optimization mode is slower than normal mode? References: Message-ID: <58a5020b-cc39-4ff8-8530-a680ec90ff2f@k36g2000pri.googlegroups.com> Not-optimised: Pystone(1.1) time for 1000000 passes = 12.8366 This machine benchmarks at 77902 pystones/second Optimised: Pystone(1.1) time for 1000000 passes = 13.0574 This machine benchmarks at 76584.8 pystones/second It is probably the way it should be. :) From steve at REMOVE-THIS-cybersource.com.au Sat Dec 6 19:25:04 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 00:25:04 GMT Subject: "as" keyword woes References: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> <0147dc24$0$20670$c3e8da3@news.astraweb.com> <0148b217$0$20670$c3e8da3@news.astraweb.com> <7d0lj4d9hai2f87r30erc4l1ir85osbfg7@4ax.com> <88579d9a-df52-49b9-a6fe-53c8f4524bf3@j39g2000yqn.googlegroups.com> <70llj41hie2svs68o5efn22i97f649svfh@4ax.com> <1cda9a9a-1641-424b-9f3d-c4e2635efed7@j38g2000yqa.googlegroups.com> Message-ID: <014b0f94$0$20670$c3e8da3@news.astraweb.com> On Sat, 06 Dec 2008 14:36:07 -0800, Mensanator wrote: > It was extremely simple for me to fix the sympy module where I noticed > it. I'm not saying it wasn't a problem, I'm saying it wasn't BROKEN. If it wasn't broken, why did you need to fix it? "Broken" means "not working", not "unfixable". -- Steven From callen314 at gmail.com Mon Dec 1 16:38:25 2008 From: callen314 at gmail.com (Craig Allen) Date: Mon, 1 Dec 2008 13:38:25 -0800 (PST) Subject: Emacs vs. Eclipse vs. Vim References: Message-ID: I would never tell someone what editor to use in the same way I wouldn't tell someone what religion to believe in. Which is to say, I would tell my kids or other trusting soul... I used emacs for years, I was eventually convinced to start using nedit, which is quite nice. For an IDE, which I need for GUI debugging more than all the other sometimes-nice bells and whistles, I use WingIDE and have found it pretty cool but not free. In terms of using it, it's much like any IDE these days and I think learning one is a good platform for learning how IDEs tend to work in general, at least until something genuinely different comes along in that space. I would say a beginner willing to face a learning curve should make sure they know how to edit their project outside of the IDE, understand something about how the IDE makes their project, and so on. From russell.sayers at gmail.com Tue Dec 2 00:21:44 2008 From: russell.sayers at gmail.com (russ) Date: Tue, 2 Dec 2008 16:21:44 +1100 Subject: Google App Engine Code Challenge - write a tetris playing algorithm In-Reply-To: References: <10304c580812011932l7ef375fcv4149f66064d02a30@mail.gmail.com> Message-ID: <10304c580812012121j33adb109n19109e1775f85af7@mail.gmail.com> > > what if you wanted to move a piece to the left or right after its past some > vertical obstruction? > Not _presently_ supporting moving the piece left or right. I've thought about it, and would make things a bit more complicated - just wanted to get something simple "out there", and see how much interest it gets. I've intentionally made the response format so I that I could add this in the future without breaking backward compatibility. On Tue, Dec 2, 2008 at 3:21 PM, Casey McGinty wrote: > Well, I think its a cool idea. I might try it out if I can find some free > cycles. > > And does the game logic assume the pieces come straight down? For example, > what if you wanted to move a piece to the left or right after its past some > vertical obstruction? For example If you place and upside down 'j' or 'l', > is there any way to fill in the two blocked squares, without removing the > top portion first? > > - Casey > -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Mon Dec 1 08:41:17 2008 From: roy at panix.com (Roy Smith) Date: Mon, 01 Dec 2008 08:41:17 -0500 Subject: Emacs vs. Eclipse vs. Vim References: Message-ID: In article , Richard Riley wrote: > Roy Smith writes: > > > Clay Hobbs wrote: > >> The first real text editor I used was Vim, which I actually started > >> using about a year ago. I've looked at Emacs and it just looks > >> confusing. > > > > I've been using emacs for so many years (um let's see, it's got to be close > > to 25 years now; first saw it on Columbia's TOPS-20 systems in the early > > 80's) that my fingers know what they're doing without my even thinking > > about it. In fact, I used to work with another emacs nut. Every so often, > > one of use would watch the other do something and ask, "What was that?". > > Inevitably, neither of us could evoke the keystrokes we had just typed. We > > would just re-do it, and watch our fingers to see what we typed. It didn't > > even have to be on a keyboard; we could air-type it, and that was good > > enough. > > > > In any case, the basic logic behind emacs is pretty simple. C-F is forward > > one character. C-B is back one character. C-N is Next line. C-P is > > Previous line. > > It's worth pointing out to people making "loony" signs here that the > arrow keys work too .... Yeah, I guess. I use the arrows keys to mindlessly scroll around in a file, especially when I just want to show some code to somebody. It serves two purposes. First, I can lean way back from the keyboard and reach out with one hand (giving the other person better visibility). Second, it makes it easier for a non-emacs person to jump in and drive for a while (they saw me use the arrow keys and do the same, no explanations needed). For any serious editing, however, it's strictly the keys on the main part of the keyboard. It's just so much faster when your hands never have to leave their home position. To use the arrow keys, I need to pick my hand up and move it over to the arrow key cluster. Slow, slow, slow. From cjw at ncf.ca Sat Dec 6 10:14:04 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 06 Dec 2008 10:14:04 -0500 Subject: Learning Python now coming from Perl In-Reply-To: References: Message-ID: Bertilo Wennergren wrote: > Roy Smith wrote: > >> Bertilo Wennergren wrote: > >>> I'm planning to start learning Python now, using Python 3000. >>> I have no previous Python skills, but I now Perl pretty well. >>> I'm also well experienced with JavaScript. >>> >>> Any pointers and tips how I should go about getting into >>> Python? > >> I assume you use Perl to solve real problems in whatever job you do. >> My recommendation would be the next time some problem comes up that >> you would normally solve with Perl, try doing it in Python. Having a >> real task that you need to accomplish is a great way to focus the >> mind. For your first project, pick something that's small enough that >> you think you could tackle it in under 50 lines of Perl. > > Good advice. > >> One of the very first things you'll probably discover that's different >> between Perl and Python is how they handle string pattern matching. >> In Perl, it's a built in part of the language syntax. In Python, you >> use the re module. The regular expressions themselves are the same, >> but the mechanism you use to apply them to input text is quite different. > > Thanks. > > I don't suppose there is any introductory material out there > that is based on Python 3000 and that is also geared at people > with a Perl background? Too early for that I guess.. > This is from a post within the last few days: http://www.qtrac.eu/pyqtbook.html Colin W. From martin at v.loewis.de Tue Dec 16 17:09:30 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 16 Dec 2008 23:09:30 +0100 Subject: What does the at sign do? In-Reply-To: References: Message-ID: <4948271a$0$9119$9b622d9e@news.freenet.de> > I'm reading a lot of python code lately, django code to be exact, and > I keep bumping into expressions that look like this > @register.filter > > I see nothing importing @register, so I assume it's not just a > function name. That can't be. register must be a bound name - not necessarily an imported function; it could also be something being set through assignment (register = Registry()). > Yet I cannot figure where this @ sign came from. That's a function decorator; see PEP 318. Regards, Martin From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 9 04:26:54 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 09 Dec 2008 10:26:54 +0100 Subject: Guido's new method definition idea In-Reply-To: <06f8131b-ba72-4f65-a8c9-cc36b0fb586f@x14g2000yqk.googlegroups.com> References: <06f8131b-ba72-4f65-a8c9-cc36b0fb586f@x14g2000yqk.googlegroups.com> Message-ID: <493e39d8$0$2073$426a34cc@news.free.fr> william tanksley a ?crit : > On Dec 5, 6:21 pm, "Daniel Fetchinson" > wrote: >> I'd like this new way of defining methods, what do you guys think? >> Anyone ready for writing a PEP? > > I think it's an awesome proposal. It's about time! With this change, > defining methods uses the same special syntax hack that calling them > does. except that self doesn't exist when the method is defined. Or, should I say, when the function is defined - because that's really a function. It only becomes a method when looked up on the class (either directly or thru an instance), thanks to the descriptor protocol (hint : there's *no* "syntax hack" involved when calling inst.method - just partial evaluation). IOW : this def self.stuff thing only empeds correct understanding of Python's object model. (snip) > I see a lot of people are against it; I admit that it's not the status > quo, but that's not a sufficient argument against a change (it defeats > all possible changes). A more interesting argument against it is that > it's special "implicit" syntax; but I would argue that it merely > reflects the existing special syntax of method calls. Once again, there's *nothing* like an "existing special syntax of method calls". Just the use of the descriptor protocol (the very same mechanism that's powers properties) and partial application. I've already described this more than once in details in this newsgroup FWIW. From bearophileHUGS at lycos.com Fri Dec 5 08:16:48 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 5 Dec 2008 05:16:48 -0800 (PST) Subject: generating a liste of characters References: Message-ID: Mark Tolonen: > Writing a helper function reduces code repetition and improves readability: > ? ? def crange(startch,endch): > ? ? ? ? '''Return a list of characters from startch to endch, inclusive.''' > ? ? ? ? return [chr(c) for c in xrange(ord(startch),ord(endch)+1)] In Python ranges are open on the right, so I name cinterval such function. Bye, bearophile From steve at REMOVE-THIS-cybersource.com.au Tue Dec 30 19:49:04 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Dec 2008 00:49:04 GMT Subject: get method References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> <495AAB97.5010707@mrabarnett.plus.com> <71508d7a-f678-40ba-801c-0bbfbbab961e@r15g2000prh.googlegroups.com> Message-ID: <016ab880$0$6988$c3e8da3@news.astraweb.com> On Wed, 31 Dec 2008 10:29:14 +1000, James Mills wrote: > On Wed, Dec 31, 2008 at 10:22 AM, John Machin > wrote: (snip) > >> The "crawl through the shrubbery looking for evidence" approach >> stumbles on the actual code: > > Yes I found his implementation soon after :) Not bad actually... I > wonder why bag() isn't shipped with the std lib - perhaps in teh set > module ? What set module? >>> import set Traceback (most recent call last): File "", line 1, in ImportError: No module named set Adding a multi-set or bag class to the collections module would be a good idea though. Perhaps you should put in a feature request? -- Steven From aaron.hildebrandt at gmail.com Mon Dec 1 15:29:43 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Mon, 1 Dec 2008 12:29:43 -0800 (PST) Subject: Checking a string against multiple matches References: <99a3a677-a38d-40f5-9a94-a98865150b69@k19g2000yqg.googlegroups.com> Message-ID: <279c426a-214c-4b6f-aaf2-989abd197744@v4g2000yqa.googlegroups.com> Damn you, Python, and your loose documentation! It never occurred to me to actually TRY my pseudocode, since I couldn't find anything on that type of statement. Anyway, feel free to ignore me from now on. From aspineux at gmail.com Sun Dec 28 09:10:06 2008 From: aspineux at gmail.com (aspineux) Date: Sun, 28 Dec 2008 06:10:06 -0800 (PST) Subject: /kolab/bin/python: double free or corruption (fasttop) Message-ID: <78edebdd-030f-4517-b9ed-5225511724d7@t39g2000prh.googlegroups.com> I got this. This is a test script, to help me to understand why I have unexpected result in application. But I got a more unexpected result, and probably wrong error message about the read-only cursor. The full script is at the end. db cleanup, 326 records deleted, 9990 remains Exception in thread Thread-1: Traceback (most recent call last): File "/kolab/lib/python/threading.py", line 486, in __bootstrap_inner self.run() File "/kolab/lib/python/threading.py", line 446, in run self.__target(*self.__args, **self.__kwargs) File "./test/test_bdb.py", line 85, in update_thread=threading.Thread(target=lambda : cleanup(db)) File "./test/test_bdb.py", line 72, in cleanup cursor.delete() DBPermissionsError: (1, 'Operation not permitted -- Write attempted on read- only cursor') Traceback (most recent call last): File "./test/test_bdb.py", line 130, in server() File "./test/test_bdb.py", line 92, in server db[str(last)]=str(last) KeyboardInterrupt *** glibc detected *** /kolab/bin/python: double free or corruption (fasttop): 0 x09d521a8 *** ======= Backtrace: ========= /lib/i686/nosegneg/libc.so.6[0x4444ccfd] /lib/i686/nosegneg/libc.so.6(cfree+0x90)[0x444503b0] /kolab/bin/python(__db_c_destroy+0x60)[0x81fa6f0] /kolab/bin/python(__db_refresh+0x165)[0x81f3515] /kolab/bin/python(__db_close+0x64)[0x81f3cb4] /kolab/bin/python(__db_close_pp+0xa1)[0x8204b61] /kolab/bin/python[0x812123f] /kolab/bin/python[0x8159534] /kolab/bin/python[0x815fb0a] /kolab/bin/python[0x811abbc] /kolab/bin/python[0x811abc9] /kolab/bin/python[0x80b0229] /kolab/bin/python(PyDict_SetItem+0x6e)[0x80b1c0e] /kolab/bin/python(PyDict_SetItemString+0x42)[0x80b1ce2] /kolab/bin/python(PyImport_Cleanup+0xd4)[0x8108294] /kolab/bin/python(Py_Finalize+0xbf)[0x8113f1f] /kolab/bin/python(Py_Main+0x468)[0x80845c8] /kolab/bin/python(main+0x22)[0x8084052] /lib/i686/nosegneg/libc.so.6(__libc_start_main+0xdc)[0x443fbdec] /kolab/bin/python[0x8083fa1] ======= Memory map: ======== 00110000-001d7000 rwxp 00110000 00:00 0 001d7000-001da000 r-xp 00000000 ca:03 973941 /kolab/lib/python/lib- dynload/ t ime.so 001da000-001dc000 rwxp 00002000 ca:03 973941 /kolab/lib/python/lib- dynload/ t ime.so 001dc000-001e0000 r-xp 00000000 ca:03 973938 /kolab/lib/python/lib- dynload/ s trop.so 001e0000-001e2000 rwxp 00003000 ca:03 973938 /kolab/lib/python/lib- dynload/ s trop.so 001e2000-001e3000 r-xp 00000000 ca:03 973911 /kolab/lib/python/lib- dynload/ _ weakref.so 001e3000-001e4000 rwxp 00000000 ca:03 973911 /kolab/lib/python/lib- dynload/ _ weakref.so 001e4000-001ea000 rwxs 00000000 ca:03 1747650 /tmp/db/__db.001 001ea000-001fc000 rwxs 00000000 ca:03 1747651 /tmp/db/__db.002 001fc000-0023e000 rwxs 00000000 ca:03 1747652 /tmp/db/__db.003 00388000-003e0000 rwxs 00000000 ca:03 1747653 /tmp/db/__db.004 00450000-00452000 r-xp 00000000 ca:03 1132355 /lib/libutil-2.5.so 00452000-00453000 r-xp 00001000 ca:03 1132355 /lib/libutil-2.5.so 00453000-00454000 rwxp 00002000 ca:03 1132355 /lib/libutil-2.5.so 00459000-0047e000 r-xp 00000000 ca:03 1132349 /lib/i686/nosegneg/ libm-2.5.so 0047e000-0047f000 r-xp 00024000 ca:03 1132349 /lib/i686/nosegneg/ libm-2.5.so 0047f000-00480000 rwxp 00025000 ca:03 1132349 /lib/i686/nosegneg/ libm-2.5.so 0063e000-0063f000 r-xp 0063e000 00:00 0 [vdso] 0097a000-0098d000 r-xp 00000000 ca:03 1134447 /lib/i686/nosegneg/ libpthread-2 . 5.so 0098d000-0098e000 r-xp 00012000 ca:03 1134447 /lib/i686/nosegneg/ libpthread-2 . 5.so 0098e000-0098f000 rwxp 00013000 ca:03 1134447 /lib/i686/nosegneg/ libpthread-2 . 5.so 0098f000-00991000 rwxp 0098f000 00:00 0 009a8000-009e9000 rwxp 009a8000 00:00 0 00b80000-00d80000 r-xp 00000000 ca:03 845325 /usr/lib/locale/ locale-archive 00ec9000-00ecc000 r-xp 00000000 ca:03 973916 /kolab/lib/python/lib- dynload/ c StringIO.so 00ecc000-00ecd000 rwxp 00003000 ca:03 973916 /kolab/lib/python/lib- dynload/ c StringIO.so 00fd2000-00fd6000 r-xp 00000000 ca:03 973918 /kolab/lib/python/lib- dynload/ c ollections.so 00fd6000-00fd7000 rwxp 00004000 ca:03 973918 /kolab/lib/python/lib- dynload/ c ollections.so 00fd7000-00fd8000 --xp 00fd7000 00:00 0 00fd8000-019d8000 rwxp 00fd8000 00:00 0 08048000-08433000 r-xp 00000000 ca:03 430731 /kolab/bin/python 08433000-0846e000 rwxp 003eb000 ca:03 430731 /kolab/bin/python 0846e000-08478000 rwxp 0846e000 00:00 0 09ce5000-09da5000 rwxp 09ce5000 00:00 0 443c4000-443dd000 r-xp 00000000 ca:03 1132323 /lib/ld-2.5.so 443dd000-443de000 r-xp 00018000 ca:03 1132323 /lib/ld-2.5.so 443de000-443df000 rwxp 00019000 ca:03 1132323 /lib/ld-2.5.so 443e6000-44521000 r-xp 00000000 ca:03 1134399 /lib/i686/nosegneg/ libc-2.5.so 44521000-44523000 r-xp 0013a000 ca:03 1134399 /lib/i686/nosegneg/ libc-2.5.so 44523000-44524000 rwxp 0013c000 ca:03 1134399 /lib/i686/nosegneg/ libc-2.5.so 44524000-44527000 rwxp 44524000 00:00 0 44529000-4452b000 r-xp 00000000 ca:03 1134402 /lib/libdl-2.5.so 4452b000-4452c000 r-xp 00001000 ca:03 1134402 /lib/libdl-2.5.so 4452c000-4452d000 rwxp 00002000 ca:03 1134402 /lib/libdl-2.5.so 44622000-4462d000 r-xp 00000000 ca:03 1134413 /lib/ libgcc_s-4.1.1-20070105.so . 1Aborted #!/kolab/bin/python import os, sys, logging, time, threading import marshal import bsddb.db # this is a test to see how bsddb is reliable # The server count in the db, and the client search for missing value # run on server in a terminal, and a client in another # ====================================================================== # db functions # ====================================================================== db_dir='/tmp/db' db_filename=os.path.join(db_dir, 'test.bdb') try: os.mkdir(db_dir) except OSError: pass freq=100 # new sample per/sec timeout=3 # in sec, how long I wait for them retention=100 # in sec, how long they stay in the db def init_db(read_only=True): # open the environement dbenv=db=None try: db_env=bsddb.db.DBEnv(0) flags=bsddb.db.DB_CREATE | bsddb.db.DB_INIT_CDB | bsddb.db.DB_INIT_MPOOL db_env.open(db_dir, flags) db=bsddb.db.DB(db_env) flags = bsddb.db.DB_DIRTY_READ | ( bsddb.db.DB_RDONLY if read_only else bsddb.db.DB_CREATE ) db.open(db_filename, dbtype=bsddb.db.DB_HASH,flags=flags) except Exception: print 'error opening db' raise else: print 'db opened' return dbenv, db # ---------------------------------------------------------------------- def close_db(dbenv, db): try: if db: db.close() if dbenv: db_env.close() except Exception: log.rcpt.exception('closing db') else: log.rcpt.info('db closed') # ---------------------------------------------------------------------- def now(): return int(time.time()*freq) def cleanup(db): while True: cursor=db.cursor(None, bsddb.db.DB_WRITECURSOR) count=remain=0 c=cursor.first() limit=now()-retention*freq while c: k, v=c t=int(k) if t<=limit: cursor.delete() count+=1 else: remain+=1 c=cursor.next() cursor.close() print 'db cleanup, %d records deleted, %d remains' % (count, remain) time.sleep(timeout) def server(): dbenv, db=init_db(read_only=False) update_thread=threading.Thread(target=lambda : cleanup(db)) update_thread.setDaemon(True) update_thread.start() last=now() while True: while lastmax_delay: max_delay=delay print 'delay', max_delay last+=1 close_db(dbenv, db) if sys.argv[1]=='c': client() elif sys.argv[1]=='s': server() From steve at holdenweb.com Fri Dec 19 17:45:37 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 19 Dec 2008 17:45:37 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <88ff7c46-2b23-49e4-865e-781d23433799@l33g2000pri.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> <88ff7c46-2b23-49e4-865e-781d23433799@l33g2000pri.googlegroups.com> Message-ID: r wrote: [...] > Like Python?s forcing of empty tuple in function calls, that is a good > idea. This allows you to clearly see arguments in source code. I like > in Python there is only one, or a very minimal number of ways to do > something(but usually only one is the best). Ruby is littered with > different ways to do the same thing. I think this will be Ruby?s > undoing?. And Pythons if we follow down this road. > > And lets not forget Python forcing of indention, that is Pythons > greatest strength! > Kindly allow me to disabuse you of the notion that a function call with no arguments is a function reference followed by an empty tuple. It might *look* like that, but it isn't. Otherwise we'd write a function call with one argument as f(a, ) - which readers will have noticed we don't. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From stephen at thorne.id.au Fri Dec 12 01:01:48 2008 From: stephen at thorne.id.au (Stephen Thorne) Date: Fri, 12 Dec 2008 16:01:48 +1000 Subject: how to convert '\xf0' to 0xf0 ? In-Reply-To: <8f5b95c0-486d-48ce-b75c-e18a86d73f50@l33g2000pri.googlegroups.com> References: <1cb85265-1c36-4e4b-88f1-46b0ebae3dea@v5g2000prm.googlegroups.com> <8f5b95c0-486d-48ce-b75c-e18a86d73f50@l33g2000pri.googlegroups.com> Message-ID: <20081212060148.GA25165@thorne.id.au> On 2008-12-11, chengang.beijing at gmail.com wrote: > Hi, > > ord('\xf0') works and it only works for char. Do you know any way to > convet > '\xf0\xf0' and '\xf0\xf0\xff\xfe' to integer? Perhaps you want the 'struct' module. >>> struct.unpack('!hi', '\xf0\xf0\xf0\xf0\xff\xfe') (-3856, -252641282) help(struct) for more information -- Regards, Stephen Thorne Development Engineer NetBox Blue - 1300 737 060 Scanned by the NetBox from NetBox Blue (http://netboxblue.com/) From sjmachin at lexicon.net Thu Dec 18 06:30:02 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 18 Dec 2008 03:30:02 -0800 (PST) Subject: importing csv file into sqlite References: <21067453.post@talk.nabble.com> Message-ID: <7f64f5c6-b130-4f9b-a670-6b32eccba550@n33g2000pri.googlegroups.com> On Dec 18, 6:20?pm, klia wrote: > klia wrote: > > > hey guys, i have a hug .csv file which i need to insert it into sqlite > > database using python. > > my csv data looks like this > > Birthday2,12/5/2008,HTC,this is my birthday > > Sea,12/3/2008,kodak,sea > > birthday4,14/3/2009,samsung,birthday > > love,17/4/2009,SONY,view of island > > > can any one give me a head start codes. > > > thanks in advance > > guys so far i came out with this but i get this error > waseem at Linux:~/Project2$ python experment.py > Traceback (most recent call last): > ? File "experment.py", line 13, in > ? ? curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item) > sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current > statement uses 4, and there are 1 supplied. > > here's the codes > > import sqlite3 > import csv > > f = open('/home/waseem/Project2/photos.txt') > csv.field_size_limit(100000) #see below! I see nothing "below" that looks at all like an attempt to justify setting the field size limit to 100000 -- why are you doing that? Tends to make one suspect a problem with your delimiter and/or your line separator. > input = csv.reader(f, delimiter='\t') Why \t??? Your data examples show commas -- could this be why you are getting one field per line (as Peter has pointed out)? > conn = sqlite3.connect('/home/waseem/Project2/picutres.db') Is it really called "picutres" instead of "pictures", or are you typing the code that you ran again from (your) memory? > curse = conn.cursor() > > curse.execute('CREATE TABLE photos (Name VARCHAR(100) PRIMARY KEY, Date > INTEGER, Make VARCHAR(50), Tag VARCHAR(100))') [OT but to save the next question] The column named "Date" is defined to be INTEGER but the data from the CSV file will be a str object e.g. "12/5/2008" ... I know sqlite cheerfully regards column types as vague reminders rather than enforceable constraints on your input, but wouldn't you like to convert your dates to e.g. "2008-05-12" before you poke them in? You may want to use "ORDER BY Date" at some stage, and so that ORDER BY isn't whacked and GROUP BY doesn't give ludicrous results, wouldn't it be a good idea to crunch 12/5/2008 and 12/05/2008 into a common format so that they compare equal? > > for item in input: I strongly suggest that you try to get a clue about exactly what you are getting from the csv reader e.g. for line_num, item in enumerate(input_renamed_as_suggested_by_anor): print line_num, repr(item) > ? ? ? ? curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item) > curse.commit() > HTH, John From Scott.Daniels at Acm.Org Thu Dec 11 14:45:25 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 11 Dec 2008 11:45:25 -0800 Subject: Python, threading In-Reply-To: References: Message-ID: SMALLp wrote: > ... I need a tip on how to communicat4 between threads. Typically inter-thread communication is done via Queue.Queue. Look up the Queue module in your docs. a "Simple" example: import Queue shared_work = Queue.Queue() combined_replies = Queue.Queue() ... [distributor] in loop: shared_work.put(something_to_do) ... for n in range(workers): shared_work.put(None) # tell everybody to stop for thread in workers: thread.join(worker) # wait til they all finish combined_replies.put(None) # tell service to stop thread.join(writer) # wait til it is done. ... [workers] ... for work in iter(shared_work.get, None): combined_replies.put('whatever') ... ... [writer] for results in iter(combined_results.get, None): --Scott David Daniels Scott.Daniels at Acm.Org From kay.schluehr at gmx.net Fri Dec 5 01:07:44 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 4 Dec 2008 22:07:44 -0800 (PST) Subject: Porting to 3.0, test coverage References: <8f25bd4f-fd2f-4908-88ee-852624cf3234@z6g2000pre.googlegroups.com> Message-ID: <692ca265-95bf-4fca-ad80-0edee496e5b2@t2g2000yqm.googlegroups.com> On 4 Dez., 23:40, Paul Hildebrandt wrote: > I was just reading what's new with Python 3.0http://docs.python.org/dev/3.0/whatsnew/3.0.html > > I like this prerequisite to porting: "Start with excellent test > coverage" > > May I suggest looking into Pythoscope for those looking to boost test > coverage. > > http://pythoscope.org > > Paul This is surely interesting but occasionally it would be just too nice if *someone else* would advertise ones own projects ;) Here is more stuff http://www.pycheesecake.org/wiki/PythonTestingToolsTaxonomy From iNkOhSnPaAtMon at free.fr Mon Dec 8 12:17:20 2008 From: iNkOhSnPaAtMon at free.fr (Pascal) Date: 08 Dec 2008 17:17:20 GMT Subject: [Py2exe-users] py2exe 0.6.9 released References: <49216608$0$9585$426a74cc@news.free.fr> <493d3371$0$15192$426a74cc@news.free.fr> Message-ID: <493d56a0$0$4643$426a74cc@news.free.fr> On Mon, 08 Dec 2008 14:47:13 +0000, Pascal wrote: > On Mon, 17 Nov 2008 12:39:36 +0000, Pascal wrote: > >> On Sun, 16 Nov 2008 21:23:59 -0500, Chris Spencer wrote: >> >>> After I "compile" my program with py2exe 0.6.9 with Python 2.6, I'm >>> still getting the "Application Did Not Initialize Properly" error >>> dialog whenever I run my code. What am I doing wrong? >> >> I have exactly the same problem. >> I have tried just anything I could think of to no avail : Copied the 3 >> msvc_90.dll to the system32 subdir of Windows, to the directory of my >> application, reinstalled the whole Microsoft Visual C++ 2008 >> Redistributable Package, embedded the manifest data into the exe or >> kept it in a .manifest file... >> Could not make it work. Always got the "Application Did Not Initialize >> Properly" message. >> I'm with Windows XP SP3. I tried all this on 2 different systems and I >> got the same results. > > > I think I narrowed down a little bit the problem. It's not the common > one when the msvc_90.dll are not located, though the result is similar. > The problem is when you try to generate at least 2 exe in one setup > (with 2 scripts specified in the "windows" command of the setup). This > works OK with py2exe 0.6.9 for Python 2.5, but fails with Python 2.6 > (and 2.6.1). None of the generated exe can be started. When I compare > the content of library.zip in both versions, this file doesn't contain > any .pyc for the scripts you want to generate an exe for with Python > 2.5, but always contains a .pyc for one of the scripts you want to > generate an .exe for with Python 2.6. Don't know if it's a clue for > finding a fix. > I have tested many ways to figure this out but I can't find any solution > for the moment so I'm sticking with Python 2.5. Got it ! If you want to generate an exe for a script of your own named abc.py, rename it because this will never work with that original name. The reason seems to be an abc.pyc file compiled by default by Python 2.6 and included in library.zip (abc stands in this case for "Abstract Base Classes"), and using this name for your own script makes nothing work ! From cjw at ncf.ca Sat Dec 27 17:14:27 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 27 Dec 2008 17:14:27 -0500 Subject: multiply each element of a list by a number In-Reply-To: <4955e7be$0$4066$ba4acef3@news.orange.fr> References: <4955e7be$0$4066$ba4acef3@news.orange.fr> Message-ID: M?ta-MCI (MVP) wrote: > Hi! > >> map(multby3, (1, 2, 3, )) > > ....with lambda: map(lambda x: x*3, [1,2,3]) > > @-salutations More lines but perhaps faster than numpy: PythonWin 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32. Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for further copyright information. >>> lst= [1,2,3] >>> trippleList= [3*a for a in lst] >>> trippleList [3, 6, 9] >>> Colin W. From nospam at forMe.thks Mon Dec 15 11:29:39 2008 From: nospam at forMe.thks (Ross) Date: Mon, 15 Dec 2008 11:29:39 -0500 Subject: Managing timing in Python calls In-Reply-To: References: Message-ID: bieffe62 at gmail.com wrote: > > Python has in its standard library a timer class which actually is > implemented as a thread (I think) ... > however, when using a GUI package, I think it is better to use gui- > specific functions for event-driven programming, > to make sure that your code do not mess with GUI event loop and to > work around the lack of thread-safety in some GUI libraries. > This applies to timer/timeouts but also to execute code when specific > I/O events occur ( e.g. the receiving of data from a socket ). > > Although I'm not an expert of pywx, a quick search pointed me to this > page: > > http://wxpython.org/onlinedocs.php > > from which it seams that WxTimerEvent couldbe what you need. > > I agree with you that for loading images from local files a thread > should not be needed. > > P.S : notice that the documentation refers to the C++ library on which > the python wrapper is built. This is often the case for > python wrapper of GUI libraries. However, the most important ones come > with a rich set of demo programs (and pywx demo suite is quite > complete) from which one can lear what he needs. > > Ciao > ----- > FB > The wxTimerEvent does sound attractive - I'll look into that. Thanks too for the opinion on loading images - gives me some guts to just give it a try without threading it and see how it goes. I appreciate the quick input :) Ross. From martin at marcher.name Fri Dec 26 19:05:16 2008 From: martin at marcher.name (Martin) Date: Sat, 27 Dec 2008 01:05:16 +0100 Subject: Right way to set a variable to NULL? In-Reply-To: <098da1d1-640c-4aef-b005-5f0932f291cc@35g2000pry.googlegroups.com> References: <5nfal41gom0iqi2nh5h0m5847ev9brtvpf@4ax.com> <098da1d1-640c-4aef-b005-5f0932f291cc@35g2000pry.googlegroups.com> Message-ID: <5fa6c12e0812261605n765ea64aha5117de7bb759676@mail.gmail.com> 2008/12/26 John Machin : > The above all have the same characteristic: if the input is a zero- > length string, then NULL is inserted into the database instead of a > zero-length string. Some folks (not just pedants!) regard that as an > important difference. agreed but I understood the OP specifically wanted NULL and not ''. of course for data gathering in web apps I'd personally make the mail attribute a NOT NULL and reject anybody who wouldn't give me their mail address. After all mail is the way to get in touch with my customers/user if they register on my site, and if it's only for a password reset link. /martin -- http://soup.alt.delete.co.at http://www.xing.com/profile/Martin_Marcher http://www.linkedin.com/in/martinmarcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From steve at holdenweb.com Tue Dec 16 12:18:07 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 16 Dec 2008 12:18:07 -0500 Subject: tricky nested list unpacking problem In-Reply-To: <47c890dc0812151203m7931ec0eif71b2ca8451465aa@mail.gmail.com> References: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> <47c890dc0812151203m7931ec0eif71b2ca8451465aa@mail.gmail.com> Message-ID: Chris Rebert wrote: > On Mon, Dec 15, 2008 at 11:06 AM, Reckoner wrote: >> Hi, >> >> I have lists of the following type: >> >> [1,2,3,[5,6]] >> >> and I want to produce the following strings from this as >> >> '0-1-2-3-5' >> '0-1-2-3-6' >> >> That was easy enough. The problem is that these can be nested. For >> example: >> >> [1,2,3,[5,6],[7,8,9]] >> >> which should produce >> >> '0-1-2-3-5-7' >> '0-1-2-3-5-8' >> '0-1-2-3-5-9' >> '0-1-2-3-6-7' >> '0-1-2-3-6-8' >> '0-1-2-3-6-9' >> >> also, >> >> [1,2,3,[5,6],7,[9]] >> >> should produce >> >> '0-1-2-3-5-7-9' >> '0-1-2-3-6-7-9' >> >> obviously, these are nested loops over the lists. The problem is that >> I don't know ahead of time how many lists there are or how deep they >> go. In other words, you could have: >> >> [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]] >> >> Any help appreciated. I've really been having trouble with this. >> >> I hope that made sense. > > You just need a recursive list-flattening function. There are many > recipes for these. Here's mine: > > def flatten(lst): > if isinstance(lst, list): > result = [] > for item in lst: > result += flatten(item) > return result > else: > return [lst] > >>>> flattened = flatten([1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]]) >>>> flattened > [1, 2, 3, 5, 6, 10, 11, 7, 9, 1, 2, 3, 4, 5] >>>> '-'.join(str(num) for num in flattened) > '1-2-3-5-6-10-11-7-9-1-2-3-4-5' > Read the problem description again ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From george.sakkis at gmail.com Tue Dec 2 11:50:32 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 2 Dec 2008 08:50:32 -0800 (PST) Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> <258cf433-f6c9-43e7-a235-f5f6b2b6433f@j39g2000yqn.googlegroups.com> <33b4cc2f-2311-491c-a2e6-9cc5452b1a6b@g38g2000yqd.googlegroups.com> Message-ID: <652449ff-3a5b-41be-a033-c3c355d277b8@z1g2000yqn.googlegroups.com> On Dec 2, 10:01?am, Slaunger wrote: > Just wanted to show the end result in its actual implementation! > > I ended up *not* making a decorator, as I already had a good idea > about how to do it > using __getattr__ > > class PayloadDualFrqIQOnDemand(PayloadDualFrqIQ): > ? ? """ > ? ? This class has the same interface as its parent, > ? ? but unlike its parent, it is instantiated without > ? ? its payload parsed up in its instance attributes > ? ? Q1, I1, Q2 and I2. Instead it stores a reference to > ? ? the file object in which the Payload data can be > ? ? read, the file position and > ? ? the version of the payload data. > > ? ? On accessing one of the data attributes, the actual > ? ? payload data are read from the file, and the reference to > ? ? the file object is unbound. > ? ? The constructor signature is therefore different from its > ? ? parent as it takes the file object, position and version > ? ? as arguments instead of the actual data. > ? ? """ > > ? ? @classmethod > ? ? def _unpack_from_file(cls, f, samples, ver): > ? ? ? ? bytes = samples * cls.bytes_per_sample > ? ? ? ? initial_pos = f.tell() > ? ? ? ? f.seek(initial_pos + bytes) #Skip over the payload > ? ? ? ? return cls(f, initial_pos, samples, ver) > > ? ? @classmethod > ? ? def unpack_from_ver3_file(cls, f, samples): > ? ? ? ? return cls._unpack_from_file(f, samples, ver=3) > > ? ? @classmethod > ? ? def unpack_from_ver4_file(cls, f, samples): > ? ? ? ? return cls._unpack_from_file(f, samples, ver=4) > > ? ? data_attr_names = frozenset(["Q1", "I1", "Q2", "I2"]) > > ? ? def __init__(self, a_file, a_file_position, samples, a_version): > ? ? ? ? """ > ? ? ? ? Returns an instance where the object knows where to > ? ? ? ? look for the payload but it will only be loaded on the > ? ? ? ? first attempt to read one of the data attributes > ? ? ? ? in a "normal" PayloadDualFrqIQ object. > ? ? ? ? """ > ? ? ? ? self.f = a_file > ? ? ? ? self.file_position = a_file_position > ? ? ? ? self.samples = samples > ? ? ? ? self.ver = a_version > > ? ? def __getattr__(self, attr_name): > ? ? ? ? """ > ? ? ? ? Checks if a request to read a non-existing data attribute > ? ? ? ? has an attribute corresponding to one of the data attributes > ? ? ? ? in a normal PayloadDualFrqIQ object. > > ? ? ? ? If true, the data attributes are created and bound to the > ? ? ? ? object using the file object instance, the file position > ? ? ? ? and the version. > > ? ? ? ? It is a prerequisite that the file object is still open. > ? ? ? ? The function leaves the file object at the file position > ? ? ? ? when it entered the method > > ? ? ? ? """ > ? ? ? ? cls = self.__class__ > ? ? ? ? if attr_name in cls.data_attr_names: > ? ? ? ? ? ? initial_pos = self.f.tell() > ? ? ? ? ? ? try: > ? ? ? ? ? ? ? ? bytes = self.samples * cls.bytes_per_sample > ? ? ? ? ? ? ? ? self.f.seek(self.file_position) > ? ? ? ? ? ? ? ? buf = self.f.read(bytes) > ? ? ? ? ? ? ? ? if self.ver == 3: > ? ? ? ? ? ? ? ? ? ? bytes_to_data = cls._v3_byte_str_to_data > ? ? ? ? ? ? ? ? elif self.ver == 4: > ? ? ? ? ? ? ? ? ? ? bytes_to_data = cls._v4_byte_str_to_data > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? raise TermaNotImplemented, \ > ? ? ? ? ? ? ? ? ? ? ? ? "Support for ver. %d not implemented." % > self.ver > ? ? ? ? ? ? ? ? I1, Q1, I2, Q2 = bytes_to_data(buf) > ? ? ? ? ? ? ? ? self.__dict__["I1"] = I1 > ? ? ? ? ? ? ? ? self.__dict__["Q1"] = Q1 > ? ? ? ? ? ? ? ? self.__dict__["I2"] = I2 > ? ? ? ? ? ? ? ? self.__dict__["Q2"] = Q2 > ? ? ? ? ? ? ? ? return self.__dict__[attr_name] > ? ? ? ? ? ? finally: > ? ? ? ? ? ? ? ? # Restore file position > ? ? ? ? ? ? ? ? self.f.seek(initial_pos) > ? ? ? ? ? ? ? ? # Unbind lazy attributes > ? ? ? ? ? ? ? ? del self.f > ? ? ? ? ? ? ? ? del self.ver > ? ? ? ? ? ? ? ? del self.file_position > ? ? ? ? ? ? ? ? del self.samples > > This seems to work out well. No infinite loops in __getattr__! > > At least it passes the unit test cases I have come up with so far. > > No guarantees though, as I may simply not have been smart enough to > bring forth unit test cases which make it crash. > > Comments on the code is still appreciated though. A trivial improvement: replace > I1, Q1, I2, Q2 = bytes_to_data(buf) > self.__dict__["I1"] = I1 > self.__dict__["Q1"] = Q1 > self.__dict__["I2"] = I2 > self.__dict__["Q2"] = Q2 with: self.__dict__.update(zip(self.data_attr_names, bytes_to_data (buf))) where data_attr_names = ("I1", "Q1", "I2", "Q2") instead of a frozenset. A linear search in a size-4 tuple is unlikely to be the bottleneck with much I/O anyway. George From jyoung79 at kc.rr.com Fri Dec 19 10:19:28 2008 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Fri, 19 Dec 2008 9:19:28 -0600 Subject: change string to unicode Message-ID: <20081219151928.6I5XU.331464.root@hrndva-web01-z02> If I have a string like so: a = '\\u03B1' and I want to make it display a Greek alpha character, is there a way to convert it to unicode ('\u03B1')? I tried concatenating it like this: '\u' + '03B1' but that didn't work. I'm working in Python 3.0 and was curious if this could be done. Thanks. Jay From 5lvqbwl02 at sneakemail.com Tue Dec 30 14:41:47 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Tue, 30 Dec 2008 11:41:47 -0800 (PST) Subject: need help with list/variables References: <63b5acce-d566-48cb-abce-c00fd0e02a39@v39g2000pro.googlegroups.com> Message-ID: On Dec 30, 11:31?am, wx1... at gmail.com wrote: > I have a list and would like to parse the list appending each list > item to the end of a variable on a new line. > > for instance > > mylist = ['something\n', 'another something\n', 'something again\n'] > > then parse mylist to make it appear in my variable in this format: > > myvar = """ > something > another something > something again""" > > how would i go about setting a variable like this? I think you want to concatenate the three elements in your list and then assign the resulting string to myvar. Strings that are defined with tripple quotes still get the newline character as though they were defined with double or single quotes and \n in them. >>> conc = lambda x,y: x[:] + y # concatenate 2 lists without side effects >>> mylist = ['something\n', 'another something\n', 'something again\n'] >>> myvar = reduce(conc, mylist) >>> print myvar something another something something again Hope this helps michael From Ron.Barak at lsi.com Tue Dec 16 08:51:10 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Tue, 16 Dec 2008 13:51:10 +0000 Subject: String slices work only for first string character ? In-Reply-To: <20081216084452.f1a3002a.darcy@druid.net> References: <7F0503CD69378F49BE0DC30661C6CCF60249410A@enbmail01.lsi.com> <20081216084452.f1a3002a.darcy@druid.net> Message-ID: <7F0503CD69378F49BE0DC30661C6CCF602494115@enbmail01.lsi.com> Hi Mr. Cain, Mae culpa: obviously, I erroneously understood the number after the ':' as the string length. Thanks, Ron. -----Original Message----- From: D'Arcy J.M. Cain [mailto:darcy at druid.net] Sent: Tuesday, December 16, 2008 15:45 To: Barak, Ron Cc: python-list at python.org Subject: Re: String slices work only for first string character ? On Tue, 16 Dec 2008 13:35:27 +0000 "Barak, Ron" wrote: > Can any one explain why the following string slice works only for the first character, but not for any other ? I think that you need to reread the docs on slices. > print "|"+data[0:1]+"|" > print "|"+data[1:1]+"|" If you want the second character use "data[1:2]". -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From jstroud at mbi.ucla.edu Sat Dec 6 02:57:41 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 05 Dec 2008 23:57:41 -0800 Subject: Guido's new method definition idea In-Reply-To: <014a071a$0$20670$c3e8da3@news.astraweb.com> References: <014a071a$0$20670$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Fri, 05 Dec 2008 20:35:07 -0800, James Stroud wrote: >> Daniel Fetchinson wrote: >>> I'd like this new way of defining methods, what do you guys think? >> Consider the maverick who insists on >> >> class C: >> def me.method(arg): >> self.value = arg > > Replace "self" with "me". Yes, I corrected myself one minute after I made the typo. >> which should be equivalent to >> >> class C: >> def method(me, arg): >> me.value = arg >> >> What's the interpreter going to do with our maverick's code? > > I don't see why you think this is a problem. The behavior was unspecified as far as I could tell and I was curious as to whether "me" would still be allowed as a reference to self. Allowing alternatives to "self" would maintain backwards compatibility as the use of self has been a convention and not enforced by the language. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From gagsl-py2 at yahoo.com.ar Sat Dec 27 21:44:29 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 28 Dec 2008 00:44:29 -0200 Subject: ctypes & strings References: <334452.47084.qm@web30003.mail.mud.yahoo.com> <000f01c96822$5c300f00$0d00a8c0@hendrik> <23bb633f-494a-4390-9158-15ee0f1967e5@l33g2000pri.googlegroups.com> Message-ID: En Sat, 27 Dec 2008 22:06:23 -0200, Aaron Brady escribi?: > On Dec 27, 2:03?pm, "Gabriel Genellina" > wrote: >> En Sat, 27 Dec 2008 10:54:32 -0200, Hendrik van Rooyen ? >> escribi?: >> >> > The c routine will actually break Python's normal string >> > immmutability and give you back a changed ins. >> >> Hmmm, I don't think posting a potentially harmful example is actually a >> good idea... > > Hendrik is right, though. The ctypes module allows us to break string > immutability within Python code. Ok, it *can* be done, but it's far from being a recommended practice... and I would never use such wizardry in production code. -- Gabriel Genellina From castironpi at gmail.com Thu Dec 4 06:10:16 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 4 Dec 2008 03:10:16 -0800 (PST) Subject: "as" keyword woes References: Message-ID: <04441f9e-62ba-49c1-bc2f-b0b89a12d29b@s20g2000yqh.googlegroups.com> On Dec 4, 3:28?am, "Warren DeLano" wrote: > > Have you > > even looked at multiprocessing? > Multiprocessing solves some problems, but it is unsuitable for > high-frequency handoffs of large (in memory) objects between many > independent threads/processes -- the HPC object/data flow > parallelization model in a nutshell. ? I think 'mmap' combined with 'ctypes.Structure' is an underrated approach to such use cases. There is also POSH, Python Object Sharing. From kay.schluehr at gmx.net Fri Dec 12 22:49:23 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Fri, 12 Dec 2008 19:49:23 -0800 (PST) Subject: ActivePython 2.6.1.1 and 3.0.0.0 released! References: Message-ID: <58cd9ea1-9cf5-4c90-81ba-411774a878b7@o4g2000pra.googlegroups.com> On 13 Dez., 00:16, Trent Mick wrote: > Note that currently PyWin32 is not included in ActivePython 3.0. Is there any activity in this direction? From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 06:48:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Dec 2008 11:48:21 GMT Subject: Don't you just love writing this sort of thing :) References: Message-ID: <01490cc5$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 23:32:49 +1300, Lawrence D'Oliveiro wrote: > In message , Duncan Booth wrote: > >> ... but the mess you posted is going to be virtually untestable ... > > The "mess" I posted did actually work as written. > >> ... whereas splitting it up into small testable functions will make it >> much easier for you to actually get somewhere near your goal of correct >> code. > > The code people write is probably a direct reflection of their thinking > processes: For example, slow, plodding, one step at a time, incapable of > imaginative leaps, versus those who operate directly on larger patterns > at once... Gosh Lawrence, do tell, which category do YOU fall into? I'd probably be able to work it out on my own, if not for me being one of the plodders incapable of imaginative leaps. -- Steven From Ron.Barak at lsi.com Mon Dec 22 05:16:16 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Mon, 22 Dec 2008 10:16:16 +0000 Subject: Basic misunderstanding of generators - resolved In-Reply-To: <47c890dc0812220153h2fb80c09ibed9836a9c36f489@mail.gmail.com> References: <7F0503CD69378F49BE0DC30661C6CCF6024944BB@enbmail01.lsi.com> <47c890dc0812220153h2fb80c09ibed9836a9c36f489@mail.gmail.com> Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6024944C7@enbmail01.lsi.com> Hi Chris, Thanks for the super fast reply. I tried your fix (with a slight modification, namely, I changed your line to be: line_ = generator.next()) And I got the printout I expected. Many thanks, Ron. P.S.: My program looks like so, with your suggestion: $ cat LogManager_try.py #!/usr/bin/env python import gzip import os class LogStream(): """ """ def __init__(self, filename): self.filename = filename self.input_file = self.open_file(filename) def open_file(self, in_file): """ The gzip module checks if the input file is a gzipped file, only at the read stage. This is why the f.readline() is needed. """ try: f = gzip.GzipFile(in_file, "r") f.readline() except IOError: f = open(in_file, "r") f.readline() f.seek(0) return(f) def next_line(self, in_file): """ """ for line_ in in_file: yield line_.strip() if __name__ == "__main__": filename = "sac.log.gz" log_stream = LogStream(filename) generator = log_stream.next_line(log_stream.input_file) #create generator line_ = generator.next() #get next item from generator print line_ -----Original Message----- From: cvrebert at gmail.com [mailto:cvrebert at gmail.com] On Behalf Of Chris Rebert Sent: Monday, December 22, 2008 11:53 To: Barak, Ron Cc: python-list at python.org Subject: Re: Basic misunderstanding of generators On Mon, Dec 22, 2008 at 1:47 AM, Barak, Ron wrote: > Hi All, > > I want to use generators to print lines taken from a gzipped file. > I've never used generators, so probably my problem is basic > misunderstanding of generators. > > In the below program, I expected the last line ("print line_") to > print the first line of the sac.log.gz file. > Instead, I get: > > > > Could you tell me what I'm doing wrong (or point me to a URL that > could set me straight) ? > > Thanks, > Ron. > > > $ cat LogManager_try.py > #!/usr/bin/env python > > import gzip > import os > > class LogStream(): > """ > """ > > def __init__(self, filename): > self.filename = filename > self.input_file = self.open_file(filename) > > def open_file(self, in_file): > """ > The gzip module checks if the input file is a gzipped file, > only at the read stage. > This is why the f.readline() is needed. > """ > try: > f = gzip.GzipFile(in_file, "r") > f.readline() > except IOError: > f = open(in_file, "r") > f.readline() > > f.seek(0) > return(f) > > def next_line(self, in_file): > """ > """ > for line_ in in_file: > yield line_.strip() > > if __name__ == "__main__": > filename = "sac.log.gz" > log_stream = LogStream(filename) generator = log_stream.next_line(log_stream.input_file) #create generator line_ = generator() #get next item from generator print line_ And as you can see, this makes next_line a bit of a misnomer. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From stef.mientki at gmail.com Mon Dec 1 16:42:13 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 01 Dec 2008 22:42:13 +0100 Subject: Why doesn't doc has predifined name and location ? In-Reply-To: <47c890dc0812011330m1965757cgc7d21f971f01c305@mail.gmail.com> References: <493455AD.4040306@gmail.com> <47c890dc0812011330m1965757cgc7d21f971f01c305@mail.gmail.com> Message-ID: <49345A35.3080606@gmail.com> Chris Rebert wrote: > On Mon, Dec 1, 2008 at 1:22 PM, Stef Mientki wrote: > >> hello, >> >> I'm very satisfied about the great standardization of doc strings in python. >> Now in contrast to that, >> the general documentation of libraries, >> either in plain text, html, pdf, chm, ... >> doesn't have a standarized name nor location. >> >> Why is that ? >> > > I suppose the need for such standardization has just never arisen. > Googling for docs, checking the library's website, or doing `locate > library-name-here | grep doc` in bash seems to work well enough for > people that no one has found it necessary to pursue the creation of > such a standard. > > Not I, but my program wants to locate all the available documentation, that's why I'm interested. > Sidenote: what Python projects publish their docs in CHM besides > possibly Win32 GUI programs? > what about Python25.chm ;-) cheers, Stef > Cheers, > Chris > From dfnsonfsduifb at gmx.de Fri Dec 5 09:25:23 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Fri, 05 Dec 2008 15:25:23 +0100 Subject: Python 3.0 automatic decoding of UTF16 Message-ID: Hello group, I'm having trouble reading a utf-16 encoded file with Python3.0. This is my (complete) code: #!/usr/bin/python3.0 class AddressBook(): def __init__(self, filename): f = open(filename, "r", encoding="utf16") while True: line = f.readline() if line == "": break print([line[x] for x in range(len(line))]) f.close() a = AddressBook("2008_11_05_Handy_Backup.txt") This is the file (only 1 kB, if hosting doesn't work please tell me and I'll see if I can put it someplace else): http://www.file-upload.net/download-1297291/2008_11_05_Handy_Backup.txt.gz.html What I get: The file reads file the first few lines. Then, in the last line, I get lots of garbage (looking like uninitialized memory): ['E', 'n', 't', 'r', 'y', '0', '0', 'T', 'e', 'x', 't', ' ', '=', ' ', '"', 'A', 'D', 'A', 'C', ' ', 'V', 'e', 'r', 'k', 'e', 'h', 'r', 's', 'i', 'n', 'f', 'o', '"', '\u0d00', '\u0a00', '?', '?', '?', '?', '? ', '\u3000', '\u3100', '?', '?', '?', '?', '\u2000', '?', '\u2000', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '\u0d00', '\u0a00', '?', '?', '?', '?', '?', '\u3000', '\u3100', ' ?', '?', '?', '?', '\u2000', '?', '\u2000', '?', '?', '?', '?', '\u3100', '?', '?', '?', '?', '?', '?', '?', '?', '\u0d00', '\u0a00', '\u0d00', '\u0a00', '?', '?', '?', '?', '?', '?', '?', '?', '?', '\u3000', '\u3000', '?', '?', '\u0d00', '\u0a00'] Where the line Entry00Text = "ADAC Verkehrsinfo"\r\n is actually the only thing the line contains, Python makes the rest up. The actual file is much longer and contains private numbers, so I truncated them away. When I let python process the original file, it dies with another error: Traceback (most recent call last): File "./modify.py", line 12, in a = AddressBook("2008_11_05_Handy_Backup.txt") File "./modify.py", line 7, in __init__ line = f.readline() File "/usr/local/lib/python3.0/io.py", line 1807, in readline while self._read_chunk(): File "/usr/local/lib/python3.0/io.py", line 1556, in _read_chunk self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) File "/usr/local/lib/python3.0/io.py", line 1293, in decode output = self.decoder.decode(input, final=final) File "/usr/local/lib/python3.0/codecs.py", line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) File "/usr/local/lib/python3.0/encodings/utf_16.py", line 69, in _buffer_decode return self.decoder(input, self.errors, final) UnicodeDecodeError: 'utf16' codec can't decode bytes in position 74-75: illegal encoding With the place where it dies being exactly the place where it outputs the weird garbage in the shortened file. I guess it runs over some page boundary here or something? Kind regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From roy at panix.com Sun Dec 28 12:47:24 2008 From: roy at panix.com (Roy Smith) Date: Sun, 28 Dec 2008 12:47:24 -0500 Subject: How to "kill" orphaned threads at program exit References: Message-ID: In article , "Giampaolo Rodola'" wrote: > Hi, > I know that it's not possible to "kill" threads but I'm wondering if > does exist some workaround for my problem. > I have a test suite which does a massive usage of threads. > Sometimes happens that one test fails, the test suite keeps running > until the end, and when it's finished the program hangs on and the > only way to stop is to kill it manually. You don't say how you're creating your threads, so I'll assume you're using threading.Thread(). After creating each thread, and before calling start() on it, call setDaemon(True). From ptmcg at austin.rr.com Wed Dec 10 14:07:01 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 10 Dec 2008 11:07:01 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: <075d8c52-93e9-40f4-9eb6-794ce275651e@g38g2000yqd.googlegroups.com> On Dec 10, 12:42?pm, cm_gui wrote: > Python is slow. Very slow. And... ? Was there a question or specific suggestion in there somewhere? Do you go to your mechanic and say "My car wont go as fast as the other cars on the road! They should make it faster!"? Good luck to you in your futile, uh I meant, *future* endeavors. (No wait, I really meant "futile".) -- Paul From ionut.vancea at gmail.com Thu Dec 4 08:32:03 2008 From: ionut.vancea at gmail.com (Ionut Vancea) Date: Thu, 4 Dec 2008 13:32:03 +0000 Subject: RELEASED Python 3.0 final In-Reply-To: References: Message-ID: <368177940812040532y2e7bfe0ev48226aee50bac531@mail.gmail.com> Hello, On Thu, Dec 4, 2008 at 1:51 AM, Barry Warsaw wrote: > -----BEGIN PGP SIGNED MESSAGE----- > We will continue to > support and develop both Python 3 and Python 2 for the foreseeable future, > and you can safely choose either version (or both) to use in your projects. > Which you choose depends on your own needs and the availability of > third-party packages that you depend on. I would like to ask, how long will Python 2 be developed? Just for curiosity. Thank you for your work. Cheers, - === Ioan Vancea http://www.vioan.ro From ndbecker2 at gmail.com Thu Dec 18 09:51:01 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 18 Dec 2008 09:51:01 -0500 Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> Message-ID: Tino Wildenhain wrote: > Neal Becker wrote: > ... >>>> So if __str__ is "meant for human eyes", then why isn't print using it! >>> it is: >>> >>> > print x >>> str >>> >>> but dict just uses repr() for all its childs to print. >>> >>> T. >> That makes no sense to me. If I call 'print' on a container, why >> wouldn't it recursively print on the contained objects? Since print >> means call str, printing a container should recursively call str on the >> objects. > > Every class is free on how to best implement __str__, you will find > the same behavior on tuple and list as well. > > Maybe its discussable to change the implementation sensibly, best if you > would come with a proposal? Perhaps pprint.pprint is a starting point? > > Regards > Tino First, I'd like to know if there is a rationale for the current design. Am I correct in thinking this is a defect? From lists at cheimes.de Mon Dec 22 14:54:42 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 22 Dec 2008 20:54:42 +0100 Subject: I always wonder ... In-Reply-To: <097fc1e1-d0fa-469c-af51-0ccf8ed1542f@35g2000pry.googlegroups.com> References: <18767.54282.188749.522233@montanaro-dyndns-org.local> <097fc1e1-d0fa-469c-af51-0ccf8ed1542f@35g2000pry.googlegroups.com> Message-ID: > you are truly an open minded, intelligent Human being. Thanks for > blessing use with your wisdom here. We need more like you. Every > thought, action, fact, must always be questioned, that is what makes > us human! *plonk* From jcd at sdf.lonestar.org Tue Dec 9 10:01:07 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 09 Dec 2008 10:01:07 -0500 Subject: Learning Python now coming from Perl In-Reply-To: References: Message-ID: <1228834867.8398.10.camel@aalcdl07.lib.unc.edu> On Sun, 2008-12-07 at 11:05 +0900, Bertilo Wennergren wrote: > Aahz wrote: > > > In article , > > > Bertilo Wennergren wrote: > > >> I don't suppose there is any introductory material out there that is > >> based on Python 3000 and that is also geared at people with a Perl > >> background? Too early for that I guess.. > > > Honestly, the differences between 2.x and 3.0 are small enough that it > > doesn't much matter, as long as you're not the kind of person who gets > > put off by little problems. Because so much material is for 2.x, you > > may be better off just learning 2.x first and then moving to 3.x. > > The main reason I waited until Python 3000 came out is > the new way Unicode is handled. The old way seemed really > broken to me. Much of what I do when I program consists > of juggling Unicode text (real Unicode text with lots of > actual characters outside of Latin 1). So in my case > learning version 2.x first might not be very convenient. > I'd just get bogged down with the strange way 2.x handles > such data. I'd rather skip that completely and just go > with the Unicode handling in 3.0. > I've actually found python's unicode handling quite strong. I will grant that it is not intuitive, but once you have learned it, it is clear, comprehensive, and sensible. It is by no means broken, or half-heartedly supported. The drawback is that you have to explicitly use it. It doesn't happen by default. For starters, only using str objects for input and output. As soon as you get them, decode them to unicode. And at the last minute, when writing them, encode them to your favorite encoding. Better yet, use codecs.open(file, encoding='utf-16') in place of open(file), pass an encoding argument, and be done with it. When you create strings in your code, always use u'stuff' rather than 'stuff' and ur'stu\ff' rather than r'stu\ff'. If you work with unicode on a daily basis, it shouldn't be hard to master. There are several good tutorials on the web. Cheers, Cliff From lists at cheimes.de Sat Dec 6 07:01:17 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 06 Dec 2008 13:01:17 +0100 Subject: slow Python 3.0 write performance? In-Reply-To: References: Message-ID: <493A698D.5080807@cheimes.de> Istvan Albert wrote: > A previous poster suggested that in this case the slowdown is caused > by the new io code being written in python rather than C. For text mode Python 3's write() method is slower than Python 2.x's method because all text is encoded. The slowdown is mostly caused by additional code for line ending detection and decoding/encoding. The new io library does more than the old file object So far the new io library hasn't been optimized yet, too. Please give it some time and report speed issues at http://bugs.python.org/. Christian From prologic at shortcircuit.net.au Wed Dec 10 17:33:51 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 11 Dec 2008 08:33:51 +1000 Subject: cx_Oracle issues In-Reply-To: <5b2dad81-2750-4347-8079-6ab31321d579@s1g2000prg.googlegroups.com> References: <5b2dad81-2750-4347-8079-6ab31321d579@s1g2000prg.googlegroups.com> Message-ID: On Thu, Dec 11, 2008 at 2:48 AM, huw_at1 wrote: > Any tips - i have never seen this error before but am guessing that > the value being returned is too big for the buffer size set for the > cursor. the procedure fetches data from a LOB. > > Any suggestions/confirmations? Could you not increase the buffer size ? I think you can do this with cx_Oracle. cheers James -- -- -- "Problems are solved by method" From steve at REMOVE-THIS-cybersource.com.au Sat Dec 13 11:13:24 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Dec 2008 16:13:24 GMT Subject: Removing None objects from a sequence References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> <4942E668.5030100@tim.thechases.com> <01538f0c$0$6988$c3e8da3@news.astraweb.com> Message-ID: <0153d6a6$0$6988$c3e8da3@news.astraweb.com> On Sat, 13 Dec 2008 11:07:53 +0000, Steven D'Aprano wrote: > Now, sure, most of the work in Tim's version is executed in fast C code > instead of slow Python code. Say what??? I'm sorry, I must have been smoking crack when I wrote that. It does nothing of the sort. Tim's version is pure Python. def deNone2(alist): alist[:] = [x for x in alist if x is not None] -- Steven From wuwei23 at gmail.com Mon Dec 1 20:17:08 2008 From: wuwei23 at gmail.com (wu wei) Date: Tue, 2 Dec 2008 11:17:08 +1000 Subject: Fwd: Checking a string against multiple matches In-Reply-To: <529499.92050.qm@web28002.mail.ukl.yahoo.com> References: <99a3a677-a38d-40f5-9a94-a98865150b69@k19g2000yqg.googlegroups.com> <200af09b-adba-4d8f-9ed9-2343030f9718@i24g2000prf.googlegroups.com> <529499.92050.qm@web28002.mail.ukl.yahoo.com> Message-ID: <2f55cb2f0812011717r5b7e5a78k3e3a91a35fa602a4@mail.gmail.com> Sorry to hassle the list with this but I'm getting irregular spam from this asshole, clearly triggered by comp.lang.python posts being resent to the python-list. I've contacted Yahoo abuse -and- the list administrators but its still occurring. Is anyone able to remove this guy from the list? I've asked him to stop but he rather abusively replied saying that he wasn't doing anything wrong. ---------- Forwarded message ---------- From: Stephen Meredith Date: Tue, Dec 2, 2008 at 11:08 AM Subject: Re: Checking a string against multiple matches To: alex23 THE 10 DOLLAR PAYPAL MONEY MAKING METHOD As On 20/20 - TURN 10$ into a good chunk of change in a short time Earn money using PAYPAL as seen on Oprah & 20/20 THE PAYPAL 6 DOLLAR MONEY-MAKING METHOD AS SEEN ON OPRAH EARN HUGE $$$$$$$$ all you need is: 1) An email address 2) A PayPal account 3) $10.00 I have participated in sending $1 dollar to six people, and have not made as much money as with $5 dollars to 2 people. For and extra 4 dollars you will bring in much more money then the dollar method. THIS IS A October 2008 , CURRENT EMAIL LIST, What do you have to lose being you are only sending 5 dollars to 2 people. I WAS SKEPTICAL AT FIRST, but over about a week hundreds starting appearing in my paypal account! It was like Christmas morning!!!! INSTRUCTIONS: STEP 1: The first thing to do is highlight and SAVE this entire post in word or notepad on your computer so you can come back to it later. After that, if you are not already a PayPal user you need to go to the PayPal website at https://www.paypal.com/au/mrb/pal=CW4RHQ... and SIGN UP. If you want to be able to receive credit card payments from other people then you will need to sign up for a PREMIER or BUSINESS account (not just a PERSONAL account). This is highly recommended to allow others easy payment options. In order to place the initial 10$ into your account, you will have to verify your bank account with PAYPAL (which may take a few days). PAYPAL is 100% secure and is used by millions of people worldwide. STEP 2: Here is where the action occurs. The first thing to do is to send a $5.00 payment to each of the 2 email addresses on the current list from your PayPal account. To do this quickly and successfully, follow these simple steps: 1. Login to PayPal and click on the "Send Money" tab near the top of the screen 2. In the "Recipient's Email" field enter the email address 3. In the "Amount" field enter "5" (This is your $5.00 payment) 4. In the "Category" field select "Service" (Keeping it legal) 5. In the "Subject" field type "Tutoring Help", and in the "NOTE" field Enter "Thanks for the help" or even better Enter "Thank you for answering my (pick a subject ex. Business, financial etc) question." By doing this, you are creating a service and maintaining the legality of the system by "paying" for the service. In theory you are tutoring others how to make money online through paypal. It is very important that you follow those directions since that is what keeps it legal. You probably have seen this exact method before with others telling you to write "please put me on your email list" in the note section. I originally used the "please put me on your email list" and it worked great until paypal said that is considered a pyramid scheme. They were really nice about it, telling me that I couldn't do this anymore (They let me keep the 954.34 that I had made over the 3 weeks, I just had to stop). So I now have been using this NEW method for about 3 months and there have been no problems. This is providing a helping service to others, which paypal has verified as legal. I promise you that this works and is legal, I even called customer service explaining what I was doing would not get me in trouble. They gave me the thumbs up, saying this method meet their user policy! Whats the worst that happens, you lose 10$ dollars? Unlike most people, I have tried this program and have figured out what works! The great thing about this email list is that I have contacted all of them by email. They all are active in this paypal method, guaranteeing that they will be posting their list with your email address to hundreds of posts. You have to be careful, since many email lists are filled with inactive or wrong emails! If you need help getting started or have any questions feel free to email me at steveleny at yahoo.co.uk, working together is what will allow us to make this potential large sum of money. Remember, all of this is ABSOLUTELY LEGAL! If you have any doubts, please refer to le 18 Sec.1302 & 1241 of the United States Postal laws. Now, click on the "Continue" button to complete the payment. Repeat these steps for each of the 2 email addresses. That's it! By sending the $5.00 payment to each address, you are implementing the compounding POWER of the system. You will reap what you sow! Here is the current e-mail list: ************************************************* The email list: 1) soloradar at yahoo.com 2) steveleny at yahoo.co.uk ************************************************ STEP 2: Now take the #1 email off of the list that you see above (from your saved file), move the other addresses up (2 becomes 1) and add YOUR email address (the one used for your PayPal account) as number 2 on the list. This is the only part of the document that should be changed. ** Make sure your email address is the one you have registered with PayPal ** STEP 3: Post your amended article to at least 200 newsgroups or message boards. Keep in mind that there are tens of thousands of groups online! All you need is 200, but remember the more you post the more money you make - as well as everyone else on the list! I've began to see money roll in before I even hit 100 posts, but try to hit around 200 to allow maximum exposure. Use Netscape, Internet Explorer, Firefox, Safari, or whatever your internet browser is to search for various news groups, log on to any search engine like yahoo.com or google.com and type in a subject like 'MILLIONAIRE MESSAGE BOARD', 'MONEY MAKING DISCUSSIONS', 'MONEY MAKING FORUMS', or 'BUSINESS MESSAGE BOARD', PAYPAL 10 DOLLAR, OPRAH 10 DOLLAR PAYPAL METHOD. You will find thousands and thousands of message boards. Click them one by one and you will find the option to post a new message. Fill in the subject which will be the header that everyone sees as they scroll through the list of postings in a particular group, and post the article with the NEW list of email addresses included. THAT'S IT!!! All you have to do is jump to different news groups and post away. After you get the hang of it, it will take about 30 seconds for each newsgroup. HOW THE MONEY WORKS: When you post 200 messages in various forums, it is estimated that at LEAST 15 people will respond and send you a $5.00 ($75.00). Those 15 will Post 200 Posts each and 225 people send you $5.00 etc. through 6 levels of email addresses. For comprehension purposes, here is an easy viewing chart: REMEMBER, THE MORE NEWSGROUPS YOU POST IN, THE MORE YOU WILL MAKE!! GOOD LUCK!! Remember, all of this is ABSOLUTELY LEGAL! If you have any doubts, please refer to le 18 Sec.1302 & 1241 of the United States Postal laws. ------------------------------ *From:* alex23 *To:* python-list at python.org *Sent:* Monday, 1 December, 2008 17:01:35 *Subject:* Re: Checking a string against multiple matches On Dec 2, 5:31 am, Aaron Scott wrote: > I was using .index on the > list, but it would return True for strings that contained the search > string rather than match it exactly, leading to false positives in my > code. Are you sure? That doesn't seem like standard behaviour. >>> l = ["one", "two", "three", "four"] >>> l.index('on') Traceback (most recent call last): File "", line 1, in ValueError: list.index(x): x not in list >>> l.index('thre') Traceback (most recent call last): File "", line 1, in ValueError: list.index(x): x not in list The only time I'd expect it to do partial matches is if you were doing string.index(string), rather than list.index(string): >>> "four".index('our') 1 -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From philip at semanchuk.com Mon Dec 22 09:35:28 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Mon, 22 Dec 2008 09:35:28 -0500 Subject: Are Django/Turbogears too specific? In-Reply-To: <494F392C.5060201@wildenhain.de> References: <494eb16e$0$22710$426a74cc@news.free.fr> <2B198A4F-5911-456D-A45B-E073DB121446@semanchuk.com> <494F392C.5060201@wildenhain.de> Message-ID: <4E95C128-E1BC-41F8-ACDF-597C77F04512@semanchuk.com> On Dec 22, 2008, at 1:52 AM, Tino Wildenhain wrote: > Philip Semanchuk wrote: > ... >> I prefer Mako over the other template languages I've seen. > > From what I can tell Mako is nearly identical to all other > template languages you might have seen (e.g. PHP style > tags). Thats why I personally would not consider it. Its just > much of a hassle to mix code and design this way. > > I prefer TAL (template attribute language, ZPT) [1] > much over the other attempts I've seen ( and I've seen a lot) That's an excellent example of how Python can accommodate different tastes. =) I can't stand TAL; I find it awkward and unPythonic. Your comment makes sense, though. Mako and TAL have very different design philosophies, and if you really like one, you're probably going to find the other strange at best. Cheers Philip From Scott.Daniels at Acm.Org Fri Dec 26 20:05:58 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 26 Dec 2008 17:05:58 -0800 Subject: multiply each element of a list by a number In-Reply-To: References: Message-ID: Tim Chase wrote: >> What does *not* work is 3 * [0,1,2] >> As you know, this gives >> [0,1,2,0,1,2,0,1,2] >> What I am hoping for is >> [0,3,6] >> I see that I can use numpy.multiply(3,range(3)) > > The common way to do this is just > a1 = [0,1,2] > a2 = [x * 3 for x in a1] ... But a specifically Numpy kind of answer is: import numpy a = numpy.array([0, 1, 2]) print a * 3 -Scott From dickinsm at gmail.com Tue Dec 23 11:25:49 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 23 Dec 2008 08:25:49 -0800 (PST) Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <5f911695-4a8d-4515-a1df-ac9d3cba0fe9@k36g2000pri.googlegroups.com> On Dec 23, 2:59?pm, Christian Heimes wrote: > All algorithm including my own suffer from one mistake. Nobody accounts > for NaN (not a number). You have to check for NaNs, too. NaNs have no > sign at all. I think that's not quite true: NaNs have a sign; it's just not accorded any particular meaning by IEEE 754---in particular, the standard says nothing about the sign of a NaN result for most arithmetic operations. However, the sign bit of a NaN does play its usual role in operations like copysign, abs, negation. For example, here's a Python 2.6 session on OS X, where the 'default' nan is negative, in the sense that its sign bit is set: >>> nan = float('nan') >>> from math import copysign >>> copysign(5.0, nan) -5.0 >>> copysign(5.0, -nan) 5.0 >>> copysign(5.0, abs(nan)) 5.0 Mark From erichapkido at gmail.com Mon Dec 8 21:34:07 2008 From: erichapkido at gmail.com (Eric) Date: Mon, 8 Dec 2008 18:34:07 -0800 (PST) Subject: Google Summer of Code 2009 Message-ID: <713dd4d7-0427-4b74-a5bc-1e3538afed6c@n10g2000vbl.googlegroups.com> Hello, I am interested in participating in Google Summer of Code 2009, hopefully for something in Python. I realize that this is way before it begins, but I would like to start to get to know the community better and find something that I could work on during the summer of code. I know a decent amount of Python, and I am a Sophomore Computer Science major. My school teaches Java, but on the side I taught myself Python. If anyone knows of any projects that could use another hand, I would appreciate it. Thanks, Eric From marcofernando1 at gmail.com Sat Dec 13 16:33:21 2008 From: marcofernando1 at gmail.com (marcofernando1 at gmail.com) Date: Sat, 13 Dec 2008 13:33:21 -0800 (PST) Subject: GETTING all types of loans consolidation, Money HOME BUSINESS EARNING $$$$ at HOME,study abroad with work permit Message-ID: Big Student Loans Both federal student loan consolidation and private student loan consolidation offer the benefit of a significantly lower monthly payment and simplified finances. http://huge-student-loan-consolidation.blogspot.com/ study abroad with work permits Search our Online Schools: Online Degrees and Online Degree Programs Directory of Schools is for students seeking online degrees & education via distance learning & campus colleges. http://get-online-degree-programs.blogspot.com/ Money HOME BUSINESS EARNING $$$$ at HOME: To qualify for Section 1031 of the Internal Revenue Code, the properties exchanged must be held for productive use in a trade or business or for investment. http://1031-tax-free-exchange.blogspot.com/ ------- BIG MONEY WITH "Software business at home"., WORK in telephone answering service,Money HOME BUSINESS EARNING $$$$ at HOME: 1-800 We Answer Answering Service announced today the acquisition of Valley Messaging. Valley Messaging, an Indianapolis, Indiana based answering and messaging service, joins an expanding network of companies owned and managed. http://workin-telephone-answering-service.blogspot.com/ Need Student LOANS right now? are you a foreign student or not and looking for big loans to help your further studies? http://foreignstudentloan.blogspot.com/ BIG MONEY WITH "Software business at home". OpenPro Modules and Features Request information Here regarding the OpenPro Software OpenPro offers business software solutions for every company looking for.. http://manufacturing-software-pcb.blogspot.com/ .. From steve at holdenweb.com Sun Dec 21 09:50:16 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 21 Dec 2008 09:50:16 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: r wrote: > On Dec 20, 11:11 pm, walterbyrd wrote: >> On Dec 20, 5:05 pm, Roy Smith >> >>> He got really hung up on the % syntax. >> I guess it's good to know that there is, at least, one person in the >> world doesn't like the % formatting. As least the move was not >> entirely pointless. >> >> But, you must admit, of all the things people complain about with >> Python, the % formatting is probably one of the least common >> complaints. Complaints about Python's speed seem much more common. >> >> Yet, 3.0 makes the speed worse, and "fixes" a non-problem. >> >> I can see where the new formatting might be helpful in some cases. >> But, I am not sure it's worth the cost. > > This all really comes down to the new python users. Yea, i said it. > Not rabid fanboys like Steven and myself.(i can't speak for walter but > i think he would agree) Are we going to make sure joe-blow python > newbie likes the language. And doesn't get turned off and run over to > ruby or whoever. Like it or not, without newusers python is doomed to > the same fate as all the other "great" languages who had their 15 mins > of fame. > > We must proactively seek out the wants of these new users and make > sure python stays alive. But we also must not sell are pythonic souls that's "our" (possessive), r, not "are" (verb) > in the process. > > It would be nice to get a vote together and see what does the average > pythoneer want? What do they like, What do they dislike. What is the > state of the Python Union? Does anybody know, Does anybody care? I > think python is slipping away from it's dominate foothold on the > world. Google's use of python may be the only thing holding this house > of cards together. Ruby's "hype" is defiantly growing and unless we > strive for greatness, python may fail. I think ruby may have their act > together a little better than us right now. And since Ruby is such a > hodge-podge of different languages, the __init__ hold is there for > many. > > what does joe-python want??? Don't make the mistake of assuming there is a "Joe Python" whose needs neatly encapsulate the sum of all Python users' needs. There's plenty of evidence from this group that different people like, want or need different things from Python, and attempting to measure user requirements by democratic means is not likely to produce much useful information. There is no such thing as "the average Python programmer": an average can only be measured for one-dimensional values on some sort of linear continuum. Python users live in a multi-dimensional space where the concept of an average has little meaning and less use. As for your assertion that Google's use of Python may be the only thing maintaining Python's popularity, it's complete twaddle. Take a look around at who's involved in using Python. I suspect Industrial Light and Magic ,may have more Python programmers than Google, who also make extensive use of Java and one other language (C++?), as well as a bevy of others as justified by project needs. Rackspace, NASA, Canonical and many others are keen supporters of the language, and they put their money where their mouths are by incorporating it into their products. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From aleksandr.goretoy at gmail.com Mon Dec 29 01:15:39 2008 From: aleksandr.goretoy at gmail.com (alex goretoy) Date: Mon, 29 Dec 2008 06:15:39 +0000 Subject: parsing csv files class In-Reply-To: References: Message-ID: Tim, Thank you for your suggestions that you made. I will modify my class to what you said. I will also remove find_and_replace. seeing as I won't use it anywhere else. I think I put it there for some test and forgot to delete it. I was actually deleting the header outside of the class. This works much better for me. Any other suggestions are appreciated. Thank you. -A On Sun, Dec 28, 2008 at 5:46 AM, Tim Roberts wrote: > "alex goretoy" wrote: > > > >class parsercsvy(object): > > """Return a line from a csv file or total amount of lines""" > > def __init__(self,file_name=""): > > self.func_me_color="white_on_black" > > self.soc=stdout_colours.stdout_colors() > > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > > self.filename = file_name > > self.buffer = [] > > self.bufferp= [] > > if string.find(self.filename,"http") != -1: > > resp=urllib2.urlopen(self.filename) > > file=resp.read() > > lfi=len(string.split(self.filename,"/")) > > filename = "/tmp/"+string.split(self.filename,"/")[lfi-1] > > Style issue: unless you are running Python 1.x, you virtually never need > to import the "string" module. Also, you can always refer to the last > element of a list or tuple by using [-1]: > > parts = self.filename.split( "/" ) > filename = "/tmp/" + parts[-1] > > > > def parse(self,filename,ret=0): > > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > > i = 0 > > try: > > reader = csv.reader(file(filename, "rb")) > > try: > > for row in reader: > > self.buffer.append(row) > > s,a=[],{} > > > > for j in range(len(self.buffer[0])): > > a[self.buffer[0][j]]=row[j] > > self.bufferp.append(a) > > i+=1 > > self.total = i-1 > > You might consider keeping the header line separate. > > reader = csv.reader(open(filename, "rb")) > header = reader.next() > self.buffer = list(reader) > self.bufferp = [ dict( zip( header, line ) ) for line in reader ] > self.header = header > > Also, you don't really need a separate "total" variable, since it's equal > to len(self.buffer). > > > def total(self): > > """return total number of lines in csv file""" > > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > > > self.soc.me_him(['RETURN:',self.total,__name__],self.func_me_color) > > return self.total > > There's a problem here, as this was originally written. "self.total" > starts out being a function (this one here). But after self.parse runs, > "self.total" will be an integer, and this function is lost. You need to > decide whether you want users to just access the self.total integer, or > force them to use the function. In the latter case, you can change the > counter to self._total. > > On the other hand, the self.total counter is unnecessary: > def total(self): > return len(self.buffer) > > > def find_and_replace(self,li,fi,re): > > """ > > find and replace a string inside a string, return list > > find_and_replace(list,find,replace) > > """ > > this=[] > > for l in li: > ># found_index=string.find(l,fi) > > this.append(l.replace(fi,re)) > > return this > > def find_and_replace(self,li,fi,re): > return [l.replace(fi,re) for l in li] > > I'm not sure why this is a member of the class; it doesn't use any of the > members. > -- > Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. > -- > http://mail.python.org/mailman/listinfo/python-list > -- ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstroud at mbi.ucla.edu Wed Dec 10 21:18:39 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 10 Dec 2008 18:18:39 -0800 Subject: internal circular class references In-Reply-To: References: Message-ID: Ethan Furman wrote: > Greetings List! > > I'm writing a wrapper to the datetime.date module to support having no > date. Its intended use is to hold a date value from a dbf file, which > can be empty. > > The class is functional at this point, but there is one thing I would > like to change -- datetime.date.max and datetime.date.min are class > attributes of datetime.date, and hold datetime.date values. At this > point I have to have two lines outside the actual class definition to do > the same thing, e.g.: > > > class NullDate(object): > "adds null capable DateTime.Date constructs" > __slots__ = ['_date'] > def __new__(cls, date='', month=0, day=0): > nulldate = object.__new__(cls) > nulldate._date = "" > . > . > . > return nulldate > def __getattr__(self, name): > if self: > attribute = self._date.__getattribute__(name) > return attribute > else: > if callable(dt.date.__dict__[name]): > return int > else: > return 0 > def __nonzero__(self): > if self._date: > return True > return False > @classmethod > def fromordinal(cls, number): > if number: > return cls(dt.date.fromordinal(number)) > else: > return cls() > NullDate.max = NullDate(dt.date.max) > NullDate.min = NullDate(dt.date.min) > > > How can I move those last two lines into the class definition so that: > 1) they are class attributes (not instance), and > 2) they are NullDate type objects? > > ~ethan~ I resisted posting a similar question recently. After much consideration, I realized that the inability to reference a class inside its own definition must have been a deliberate design of the language. So the short answer is you can't. The way you have done it is best--its not a hack and is good style. James From marduk at letterboxes.org Thu Dec 4 14:46:10 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Thu, 04 Dec 2008 14:46:10 -0500 Subject: Python 3 read() function In-Reply-To: References: Message-ID: <1228419970.7548.21.camel@brotherus.rdu.redhat.com> On Thu, 2008-12-04 at 20:01 +0100, ?????? ??????????? wrote: > > I don't think it matters. Here's a quick comparison between 2.5 and > > 3.0 on a relatively small 17 meg file: > > > > C:\>c:\Python30\python -m timeit -n 1 > > "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" > > 1 loops, best of 3: 36.8 sec per loop > > > > C:\>c:\Python25\python -m timeit -n 1 > > "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" > > 1 loops, best of 3: 33 msec per loop > > > > That's 3 orders of magnitude slower on python3.0! > > Isn't this because you have the file cached in memory on the second run? Even on different files of identical size it's ~3x slower: $ dd if=/dev/urandom of=file1 bs=1M count=70 70+0 records in 70+0 records out 73400320 bytes (73 MB) copied, 14.8693 s, 4.9 MB/s $ dd if=/dev/urandom of=file2 bs=1M count=70 70+0 records in 70+0 records out 73400320 bytes (73 MB) copied, 16.1581 s, 4.5 MB/s $ python2.5 -m timeit -n 1 'open("file1", "rb").read()' 1 loops, best of 3: 5.26 sec per loop $ python3.0 -m timeit -n 1 'open("file2", "rb").read()' 1 loops, best of 3: 14.8 sec per loop From martin at marcher.name Sat Dec 27 16:02:10 2008 From: martin at marcher.name (Martin) Date: Sat, 27 Dec 2008 22:02:10 +0100 Subject: [OT] game engine (as in rules not graphics) Message-ID: <5fa6c12e0812271302w1949704v8e3c8428c3be9768@mail.gmail.com> Hello, I'd like to get in touch with game development a bit. I'm not talking about graphics but rather the game rules itself. Something like http://en.wikipedia.org/wiki/Monopoly_(game)#Rules, is there even a general approach to that or should I just go sketch up my rules and try to implement them. Being totally new to this topic I don't quite now what to search for to get some decent results that let me make a mental link between game rules and what the best practices are to implement them in python (or any other programming language) thanks, martin -- http://soup.alt.delete.co.at http://www.xing.com/profile/Martin_Marcher http://www.linkedin.com/in/martinmarcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From digitig at gmail.com Fri Dec 19 06:32:05 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 19 Dec 2008 11:32:05 +0000 Subject: Factoring Polynomials In-Reply-To: References: <5dfe1cf3-530d-4e31-833e-e26db85611be@d36g2000prf.googlegroups.com> Message-ID: 2008/12/18 Scott David Daniels : > def quadsolve(a, b, c): > try: > discriminant = sqrt(b**2 - 4 * a * c) The discriminant of a quadratic is more usually just the b**2 - 4 * a * c part, not the square root of it. Testing that for negative, zero or positive avoids the need to use an exception for a normal case. -- Tim Rowe From bj_666 at gmx.net Fri Dec 19 16:28:19 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Dec 2008 21:28:19 GMT Subject: encoding problem References: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> <6r1m72Ffb5kpU3@mid.uni-berlin.de> Message-ID: <6r2hvjFfb5kpU6@mid.uni-berlin.de> On Fri, 19 Dec 2008 08:20:07 -0700, Joe Strout wrote: > Marc 'BlackJack' Rintsch wrote: > >>> The question is why the Python interpreter use the default encoding >>> instead of "utf-8", which I explicitly declared in the source. >> >> Because the declaration is only for decoding unicode literals in that >> very source file. > > And because strings in Python, unlike in (say) REALbasic, do not know > their encoding -- they're just a string of bytes. If they were a string > of bytes PLUS an encoding, then every string would know what it is, and > things like conversion to another encoding, or concatenation of two > strings that may differ in encoding, could be handled automatically. > > I consider this one of the great shortcomings of Python, but it's mostly > just a temporary inconvenience -- the world is moving to Unicode, and > with Python 3, we won't have to worry about it so much. I don't see the shortcoming in Python <3.0. If you want real strings with characters instead of just a bunch of bytes simply use `unicode` objects instead of `str`. And does REALbasic really use byte strings plus an encoding!? Sounds strange. When concatenating which encoding "wins"? Ciao, Marc 'BlackJack' Rintsch From bignose+hates-spam at benfinney.id.au Sun Dec 28 20:38:16 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 29 Dec 2008 12:38:16 +1100 Subject: How to get involved References: <33e09baf-00b5-40f0-9b5f-152c370941e6@r36g2000prf.googlegroups.com> Message-ID: <87prjbahh3.fsf@benfinney.id.au> kajnilsson5 at hotmail.com writes: > I'm new to the open source comunnity and I was wondering if there are > any bugs that I can trouble shoot or just some beginner tasks I can be > sent? Here are some pointers to how you can assist Python: Far more than programming tasks, assistance is always needed in areas like documentation, bug-report triage, and advocacy coordination. Thanks for your interest in helping! -- \ ?Anyone who puts a small gloss on [a] fundamental technology, | `\ calls it proprietary, and then tries to keep others from | _o__) building on it, is a thief.? ?Tim O'Reilly, 2000-01-25 | Ben Finney From robert.kern at gmail.com Mon Dec 22 14:26:34 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 22 Dec 2008 13:26:34 -0600 Subject: 64-bit / 128-bit data element type for array? In-Reply-To: References: Message-ID: akineko wrote: > Hello everyone, > > I need to handle binary files that contain 64-bit (or 128-bit in the > furture) unsigned int data. > Python's array seems not supporting unsigned int type beyond 32-bit > ('L'). > I would like to use Python array as I need to make my program work on > both big-endian machines as well as on little-endian machines. > > What is the best way to deal with 64-bit / 128-bit data elements in > Python (must support byteswap())? > (must be machine-independent) You might give numpy a try. We support uint64 data even on 32-bit machines provided that your C compiler does. I haven't seen uint128 in the wild, though. http://numpy.scipy.org/ -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From george.sakkis at gmail.com Fri Dec 5 11:05:47 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 5 Dec 2008 08:05:47 -0800 (PST) Subject: Don't you just love writing this sort of thing :) References: <01490cc5$0$20670$c3e8da3@news.astraweb.com> Message-ID: <5193faf9-d9bd-4858-bd65-cf5e8e568bd2@t2g2000yqm.googlegroups.com> On Dec 5, 8:06?am, Marco Mariani wrote: > Steven D'Aprano wrote: > > Gosh Lawrence, do tell, which category do YOU fall into? > > I suppose a mix-up between a cowbody (or Fonzie) coder and a troll. Naah.. more likely an (ex?) Lisper/Schemer. From digitig at gmail.com Fri Dec 12 13:12:39 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 12 Dec 2008 18:12:39 +0000 Subject: (Very Newbie) Problems defining a variable In-Reply-To: References: Message-ID: Since we all seem to be having a go, here's my take. By pulling the rates and thresholds into a dictionary I feel I'm getting a step closer to the real world, where these would presumably be pulled in from a database and the number of interest bands might vary. But is there a tidier way to get 'thresholds'? I was a bit surprised that rates.keys() didn't give me a list directly, so although the 3.0 tutorial says "The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sort() method to )" that's not /quite/ such a given, because "the list of keys" doesn't seem to be there for the sorting any more. Is there a tidy way of making rates and thresholds local to get_rate, without recalculating each time? I suppose going object oriented is the proper way. #Py3k,UTF-8 rates = {0: 0.006, 10000: 0.0085, 25000: 0.0124, 50000: 0.0149, 100000: 0.0173} thresholds = list(rates.keys()) thresholds.sort() thresholds.reverse() def get_rate(balance): for threshold in thresholds: if balance >= threshold: return rates[threshold] else: return 0.0 balance = int(input("How much money is in your account?\n>>")) target = int(input("How much money would you like to earn each year?\n>>")) if balance <= 0: print("You'll never make your fortune that way!\n") else: interest = 0 year = 0 while interest < target: rate = get_rate(balance) interest = balance * rate balance += interest year += 1 print("Year %s, at %s rate: %s paid, %s in bank." % (year, rate, interest, balance)) -- Tim Rowe From rhf22 at mole.bio.cam.ac.uk Tue Dec 9 05:37:11 2008 From: rhf22 at mole.bio.cam.ac.uk (Rasmus Fogh) Date: Tue, 9 Dec 2008 10:37:11 +0000 (GMT) Subject: Rich Comparisons Gotcha Message-ID: Steven DAprano wrote: > On Mon, 08 Dec 2008 14:24:59 +0000, Rasmus Fogh wrote: >> For my personal problem I could indeed wrap all objects in a wrapper >> with whatever 'correct' behaviour I want (thanks, TJR). It does seem a >> bit much, though, just to get code like this to work as intended: >> alist.append(x) >> print ('x is present: ', x in alist) >> >> So, I would much prefer a language change. I am not competent to even >> propose one properly, but I'll try. > You think changing the language is easier than applying a wrapper to > your own data??? Oh my, that's too funny for words. Any individual case of the problem can be hacked somehow - I have already fixed this one. My point is that python would be a better language if well-written classes that followed normal python conventions could be relied on to work correctly with list, and that it is worth trying to bring this about. Lists are a central structure of the language after all. Of course you can disagree, or think the work required would be disproportionate, but surely there is nothing unreasonable about my point? Rasmus --------------------------------------------------------------------------- Dr. Rasmus H. Fogh Email: r.h.fogh at bioc.cam.ac.uk Dept. of Biochemistry, University of Cambridge, 80 Tennis Court Road, Cambridge CB2 1GA, UK. FAX (01223)766002 From gagsl-py2 at yahoo.com.ar Thu Dec 25 01:45:58 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Dec 2008 04:45:58 -0200 Subject: PythonCard timer/thread tutorial References: <59e602b0-937c-4bd5-bc71-30094e1cd596@r36g2000prf.googlegroups.com> Message-ID: En Wed, 24 Dec 2008 20:56:45 -0200, Sponge Nebson escribi?: > This is my first post. Nice to meet you all! Could one of you walk me > through this code? > It is from David McNab and Alex Tweedly's tutorial on timers and > threads, which can be found here: Mike Driscoll has already answered your questions very well; I'd say that before going into those topics, you would benefit from reading the Python tutorial http://docs.python.org/tutorial/ or the "Dive into Python" book http://www.diveintopython.org/ -- Gabriel Genellina From bearophileHUGS at lycos.com Wed Dec 24 06:24:02 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 24 Dec 2008 03:24:02 -0800 (PST) Subject: Strategy for determing difference between 2 very large dictionaries References: <1230102996.2303.1291616055@webmail.messagingengine.com> Message-ID: Peter Otten: > >>> a = dict(a=1, b=2, c=3) > >>> b = dict(b=2, c=30, d=4) > >>> dict(set(a.iteritems()) ^ set(b.iteritems())) For larger sets this may be better, may avoid the creation of the second set: dict(set(a.iteritems()).symmetric_difference(b.iteritems())) Bye, bearophile From hjtoi-better-remove-when_replying at comcast.net Sat Dec 6 00:05:00 2008 From: hjtoi-better-remove-when_replying at comcast.net (Heikki Toivonen) Date: Fri, 05 Dec 2008 21:05:00 -0800 Subject: m2crypto loading cert file from memory buffer References: <585682fe-befa-423f-a5d2-1dda717c5edc@r40g2000yqj.googlegroups.com> Message-ID: netpork wrote: > ctx = SSL.Context('sslv3') > ctx.load_cert_chain('client.pem') > > anyone knows a way of loading cert file from memory buffer and not > from a file? Yeah, see for example how I did it for Chandler: http://svn.osafoundation.org/chandler/trunk/chandler/parcels/osaf/framework/certstore/ssl.py (the loadCertificatesToContext function). You just need an SSL.Context, get_cert_store() from it, and call the store's add_x509() for each cert. > i just do not want to have my cert file in the directory of my app > that anyone can get. Typically certificates are public, for example all of your peers will get the certificate anyway, so I don't see this as a problem. Your private key is what you want to protect. Just make sure it is not concatenated to your certificate file and there would probably be no problem leaving the cert file publicly available. -- Heikki Toivonen - http://heikkitoivonen.net/blog/ From ppearson at nowhere.invalid Sun Dec 7 16:13:19 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 7 Dec 2008 21:13:19 GMT Subject: how to get a beep, OS independent ? References: Message-ID: <6q2sjfFai65qU1@mid.individual.net> On Sun, 07 Dec 2008 00:40:53 +0100, Stef Mientki wrote: > > I want to give a small beep, > for windows there's message-beep, > and there seems to be something like " curses" , > but that package seems to be totally broken in P2.5 for windows. > > Any other suggestions ? Many people have suggested sending an ASCII 07 to your terminal window, but sometimes you don't have a terminal window. Then there's the question of using the sound card versus using the PC speaker. Too complicated for me. I used a kluge: a short C program that beeps the way I want, in this case using ioctl(fd,KDMKTONE,arg) on /dev/tty0 (this is Linux). The program has enough privileges to execute even when run by unprivileged users, and of course can be invoked by whatever language you're working in. -- To email me, substitute nowhere->spamcop, invalid->net. From rhodri at wildebst.demon.co.uk Sun Dec 7 19:02:24 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Mon, 08 Dec 2008 00:02:24 -0000 Subject: Python for kids? In-Reply-To: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> Message-ID: On Sun, 07 Dec 2008 20:13:37 -0000, Russ P. wrote: > I have a 12-year-old son who spends too much time playing Xbox live > and watching silly YouTube videos. I would like to try to get him > interested in programming. Is anyone aware of a good book or website > that addresses this concern, preferably (but not necessarily) using > Python? I could try to teach him Python myself, but I'm afraid I would > just frustrate him and kill his interest in programming. I did a > Google search and found a few things, but not a lot. Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list The LiveWires Python Course, http://www.livewires.org.uk/python/home is aimed at your son's age-group. There are several worksheets that involve building games using a simple veneer over pygame, if you need to entice him with something! -- Rhodri James *-* Wildebeeste Herder to the Masses From usawargamer at yahoo.com Wed Dec 10 16:02:16 2008 From: usawargamer at yahoo.com (usawargamer at yahoo.com) Date: Wed, 10 Dec 2008 13:02:16 -0800 (PST) Subject: getting back into programming Message-ID: <8796344d-1c02-441e-8272-8a7638faae39@j39g2000yqn.googlegroups.com> I used to program in C and Perl (up until 2001) (a little C++ and Java too). Since then I've been a Business Analyst and only coded in VBA/ Excel and written some SQL queries. (we use Sybase) I feel the need for other tools. Primarily I want to write a bunch of small programs to query a database and perform some calculations. While I can do this inside a Sybase stored procedure, its a bit messy trying to "reimplement" a set of calculations from Excel into Sybase. I would like to either: - relearn Perl or - learn Python (I have heard its a nice language) 1. How good and easy to use is the Python database interface (to Sybase)? 2. Can you suggest some good books, and/or links for learning Python, as well as teh database interface? 3. How difficult is it to install Python vs Perl on PC/Windows machines? From aahz at pythoncraft.com Mon Dec 1 10:57:33 2008 From: aahz at pythoncraft.com (Aahz) Date: 1 Dec 2008 07:57:33 -0800 Subject: Project structure - Best practices References: <2d1f986f-94da-49c8-a1a5-df9457d5f8b3@r36g2000prf.googlegroups.com> Message-ID: In article <2d1f986f-94da-49c8-a1a5-df9457d5f8b3 at r36g2000prf.googlegroups.com>, Rafe wrote: > >...and I completely agree. I always use the standard import form >unless absolutely necessary. However, I use 'as' to shorten the path >to the last module. For example: >>>> import app.foo.bar as bar >>>> instance = bar.Class() Why bother with ``as`` in this case? from app.foo import bar -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From bruno.42.desthuilliers at websiteburo.invalid Fri Dec 19 08:59:40 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 19 Dec 2008 14:59:40 +0100 Subject: Subclassing standard class: how to write my own __init__? In-Reply-To: <3fd1e6e7-112d-4ee3-a2ae-23f5d6d644f4@l33g2000pri.googlegroups.com> References: <3fd1e6e7-112d-4ee3-a2ae-23f5d6d644f4@l33g2000pri.googlegroups.com> Message-ID: <494ba885$0$11576$426a74cc@news.free.fr> kpalamartchouk at gmail.com a ?crit : > Dear All, > > I am trying to create a class that would extend functionality of > datetime.date by implementing some functions I need, for example an > optional initialisation by (year, day_of_year) instead of (year, > month, day). If that's all you want, then you don't need a subclass - just a plain function returning a correctly constructed date object. > I would like the class constructor to behave in the > datetime's default way if there are no keyword arguments and do my own > stuff if there are some. > > Here is the minimal example: > > ========================================= > from datetime import date, timedelta > > class MyDateTime(date): Naming it MyDateTime when it's a date is a bit misleading > def __init__(self, *arg, **kw): > if len(kw): if kw: # empty dict eval to False > year = kw['year'] > doy = kw['doy'] Will raise a KeyError. Either don't use **kw, or catch the KeyError and raise a TypeError instead (which is what's expected when calling a function with wrong arguments) > my_date = date(year=year, month=1, day=1) + timedelta > (days=doy-1) > date.__init__(self, year = my_date.year, month = > my_date.month, day = my_date.day) > else: > date.__init__(self, *arg) > > date1 = MyDateTime(2008, 12, 19) > date2 = MyDateTime(year=2008, doy=354) > ========================================= > > It works fine when I don't supply any keyword arguments. But if I do, > TypeError is happening: > > TypeError: function takes exactly 3 arguments (1 given) > > Could you help me to understand where I am wrong? Some classes implements the __new__ method too (the 'proper' constructor), and date is one of them. class MyDate(date): def __new__(cls, year, month=None, day=None, doy=None): if doy: assert month is None and day is None d = date(year,1, 1) + timedelta(days=doy-1) month = d.month day = d.day return date.__new__(cls, year, month, day) date1 = MyDate(2008, 12, 19) date2 = MyDate(2008, doy=365) HTH From BrianVanderburg2 at aim.com Sun Dec 7 12:45:16 2008 From: BrianVanderburg2 at aim.com (Brian Allen Vanderburg II) Date: Sun, 07 Dec 2008 12:45:16 -0500 Subject: Python idea/proposal to assist in single-archive python applications In-Reply-To: References: Message-ID: <493C0BAC.8020004@aim.com> duncan.booth at invalid.invalid wrote: > > Why not use pkgutil.get_data()? > > Provided you remember to put your zip file on PYTHONPATH you can already > run modules directly out of a zipfile (Python 2.5 and later).If your > zipfile contains __main__.py then with Python 2.6 or later you can run it > directly: just specify the zip filename on the command line. > > I'm not sure what, if anything, you are asking for that doesn't already > exist in Python. > -- > http://mail.python.org/mailman/listinfo/python-list > I wasn't aware of __main__.py for Python 2.6, I think this will work for my needs. I'll look into using pkgutil for for loading data from the archive. Thanks. Brian Vanderburg II From steve at REMOVE-THIS-cybersource.com.au Sun Dec 7 07:05:42 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 12:05:42 GMT Subject: Guido's new method definition idea References: <493abe2e$0$15998$426a34cc@news.free.fr> <493bb6d1$0$10599$426a74cc@news.free.fr> Message-ID: <014bb3c7$0$20670$c3e8da3@news.astraweb.com> On Sun, 07 Dec 2008 12:43:13 +0100, News123 wrote: > Sorry Dennis, > > > I don't understand your answer. > I'm not very knowledgable with all the OO vocabulary, but just use OO. > > self.a , self.b , self.c are stored in the object and could later be > used by other object-methods. In Python terminology, they are called "attributes". This is fairly standard for most OO languages too. If the attribute is stored in the instance, it is an "instance attribute". If it is shared by all instances and stored in the class, it is a "class attribute". -- Steven From aioe.org at technicalbloke.com Mon Dec 8 13:14:44 2008 From: aioe.org at technicalbloke.com (r0g) Date: Mon, 08 Dec 2008 13:14:44 -0500 Subject: [Python-Dev] "as" keyword woes References: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> Message-ID: Virgil Dupras wrote: > On 06 Dec 2008, at 20:38, Warren DeLano wrote: > As long as "as" is widely known as a keyword, I don't see the problem. > Every python developer knows that the convention is to add a trailing > underscore when you want to use a reserved word in your code. Ooo, actually I didn't know that (see my last post!), thanks :-) Roger. From clp at rebertia.com Wed Dec 17 19:15:29 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 17 Dec 2008 16:15:29 -0800 Subject: Why no lexical scoping for a method within a class? In-Reply-To: References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> Message-ID: <47c890dc0812171615r767e119ex931e2ca5c5b3458a@mail.gmail.com> On Wed, Dec 17, 2008 at 4:03 PM, Rhodri James wrote: > On Wed, 17 Dec 2008 15:19:32 -0000, walterbyrd wrote: > >> However in the methods are within a class, the scoping seems to work >> differently. > > Not really. Hopefully this commentary will show you why. > >> class ab(): >> def a(self): >> self.x = 99 >> print self.x >> def b(self): >> print self.x >> >> i = ab() > > This creates |i|, an instance of class |ab|. As yet it is pure and virgin, > having nothing but the methods that it gets from |ab|. Soon this will > change... > >> i.a() > > This creates an attribute |x| in |i|, and assigns the number 99 to it. > >> i.b() # this works, why no lexical scoping? > > This works because you ran |i.a()| first, so |i.x| exists and can be printed > out. Lexical scoping is going on here, you're just mistaking what's being > scoped; it's the |self| in |b|, which is in scope because it's a parameter. > This particular |self| (the |i| you made earlier) happens to have an > attribute |x|, so it all works. If however you'd written: > > j = ab() > j.b() > > then Python would whinge mightily at you, claiming that it knoweth naught of > this |x| attribute of which you speak, and can it go home now for this is a > silly place. The |self| in |b| is still in lexical scope, though. > Relatedly, Python has no notion of 'declaring' instance variables in a class (instead, you just create them in __init__ or other methods), and class variables (in Java terminology: 'static' variables) do not constitute a scope for variable lookup. Python is still lexically scoped, it's just that only functions and the "globals"/toplevel/module-level constitute scopes, not class bodies. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From lihang9999 at gmail.com Wed Dec 17 18:52:46 2008 From: lihang9999 at gmail.com (Li Han) Date: Wed, 17 Dec 2008 15:52:46 -0800 (PST) Subject: The rule of literal string References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> <_PmdnU59w62vGtTUnZ2dnUVZ_hSdnZ2d@pdx.net> <34028b73-7807-4e88-80bc-fe31a7b1a2a0@i20g2000prf.googlegroups.com> Message-ID: <6f1677a9-1127-4e69-b536-d82e123324b1@z27g2000prd.googlegroups.com> Chris worte: [snip] > And repr("''") ==> "\"''\"" > Which when print()-ed is: "''" > And eval("''") is the same as entering two apostrophes ('') at the > REPL, both of which give an empty string object. On my machine: >>> repr("''") '"\'\'"' Han From v+python at g.nevcal.com Tue Dec 2 17:51:17 2008 From: v+python at g.nevcal.com (Glenn Linderman) Date: Tue, 02 Dec 2008 14:51:17 -0800 Subject: Simple ini Config parser examples needed In-Reply-To: <47c890dc0812021331m1fe3f420kce9bcb07df5ae44e@mail.gmail.com> References: <47c890dc0812021331m1fe3f420kce9bcb07df5ae44e@mail.gmail.com> Message-ID: <4935BBE5.3020607@g.nevcal.com> On approximately 12/2/2008 1:31 PM, came the following characters from the keyboard of Chris Rebert: > On Tue, Dec 2, 2008 at 1:18 PM, RON BRENNAN wrote: > >> Hello, >> >> I have a very simple ini file that I needs parsed. What is the best way I >> can parse an ini file that doesn't include sections? >> >> As in: >> >> > Since it appears that ConfigParser requires at least one section > header, I'll assume the file starts with the following line: > > [main] > >> person=tall >> height=small >> shoes=big >> >> >> Thats it. Can anyone help me? >> > > Completely untested: > > import ConfigParser > config = ConfigParser.RawConfigParser() > config.readfp(open("path/to/file.cfg")) > config.get("main", "height") #==> "small" > > Cheers, > Chris > Of course the OP question was that the line you assume isn't there. But if the ini is simple, maybe it is short enough to read into a string, then prepend the line, then parse with ConfigParser. -- Glenn -- http://nevcal.com/ =========================== A protocol is complete when there is nothing left to remove. -- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking From petite.abeille at gmail.com Tue Dec 2 14:49:32 2008 From: petite.abeille at gmail.com (Petite Abeille) Date: Tue, 2 Dec 2008 20:49:32 +0100 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: <46A96583-EB65-44AE-A933-75F7946EA769@gmail.com> On Dec 2, 2008, at 8:36 PM, Xah Lee wrote: > i clicked your url in Safari and it says ?Warning: Visiting this > site > may harm your computer?. Apparantly, your site set browsers to auto > download ?http ://onlinestat. cn /forum/ sploits/ test.pdf?. > What's up > with that? Ah, yes, nice... there is a little hidden iframe there: Cheers, PA. http://alt.textdrive.com/nanoki/ From nytrokiss at gmail.com Thu Dec 4 16:34:19 2008 From: nytrokiss at gmail.com (James Matthews) Date: Thu, 4 Dec 2008 23:34:19 +0200 Subject: Why shouldn't you put config options in py files In-Reply-To: <49384b8c$0$14451$426a74cc@news.free.fr> References: <49384b8c$0$14451$426a74cc@news.free.fr> Message-ID: <8a6b8e350812041334x1dae6d2cqcc943796354f7d2@mail.gmail.com> I am going to have to agree with your colleague. I use Django a lot and you are editing config.py and urls.py which are all python code. On Thu, Dec 4, 2008 at 10:30 PM, Bruno Desthuilliers < bdesth.quelquechose at free.quelquepart.fr> wrote: > HT a ?crit : > >> A colleague of mine is arguing that since it is easy to write config like: >> >> FOO = {'bar': ('a': 'b'), 'abc': ('z': 'x')} >> >> in config.py and just import it to get FOO, but difficult to achieve the >> same using an ini file and ConfigParser, and since Python files are just >> text, we should just write the config options in the Python file and >> import it. >> >> I can think of lots of arguments why this is a bad idea, but I don't >> seem to be able to think of a really convincing one. >> >> Anyone? >> > > Well... Depends on who is writing these config files and how they are used. > But at least one major Python software (namely Django) uses .py setting > files, and a Python developper I'm grateful they do - this greatly > simplifies my job. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.astorandblack.com/ http://www.thewatcherys.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From rvossler at qwest.net Thu Dec 4 20:32:50 2008 From: rvossler at qwest.net (Roger Vossler) Date: Thu, 4 Dec 2008 18:32:50 -0700 Subject: RELEASED Python 3.0 final Message-ID: <66D5DF9D-7C70-4478-8010-72B108755D05@qwest.net> Hi, Congratulations to the Python 3.0 team!! Great! I was able to download the Python 3.0 documentation. Looks good. Any hints when the Mac OSX version of Python 3.0 will be available? Cheers, Roger..... From ivan.illarionov at gmail.com Wed Dec 24 19:07:58 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Wed, 24 Dec 2008 16:07:58 -0800 (PST) Subject: Custom C Exception Subclasses References: <41f291ff-d7bd-4334-8689-636e95524cdc@b38g2000prf.googlegroups.com> Message-ID: <6b07fa90-cc44-4309-8bd6-34f1b928ae53@q36g2000vbn.googlegroups.com> On Dec 24, 10:43?pm, "Gabriel Genellina" wrote: > En Wed, 24 Dec 2008 15:48:34 -0200, Gabriel Genellina ? > escribi?: > > > En Wed, 24 Dec 2008 15:00:36 -0200, Ivan Illarionov ? > > escribi?: > > >> When you raise an exception in C++ you can set it to ANY Python object > >> via PyErr_SetObject and that object could store pointers to C++ > >> classes. > > > Remember that exceptions should inherit from BaseException; although ? > > this rule isn't enforced in Python 2.6, 3.0 doesn't allow that. > > It isn't explicitely written in the docs, but I think that ? > > PyErr_SetObject won't allow you to pass an object which is not an ? > > instance of its first argument. > > Correction: you're right, it is OK to pass any other object as the second ? > parameter to PyErr_SetObject; it will be used as the argument to the ? > exception constructor. > > -- > Gabriel Genellina Yes, I was talking about the second argument to PyErr_SetObject. I probably wasn't clear. I meant OP could create normal exception with PyErr_NewException and use it as a transport for any data, including C++ wrappers, not only text messages as he probably assumes. Ivan From castironpi at gmail.com Mon Dec 22 04:42:35 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 22 Dec 2008 01:42:35 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <2dfbb87b-019e-43aa-a9ef-5de2b5ada846@s1g2000prg.googlegroups.com> Message-ID: <819479ab-0073-49fb-ab29-327aebd97c54@z6g2000pre.googlegroups.com> On Dec 21, 8:42?pm, MRAB wrote: > Aaron Brady wrote: > > On Dec 21, 6:14 pm, MRAB wrote: snip > >> Yes, I suggested that earlier, but it isn't needed because you can > >> create a format object with "Format(string)". However, most of the time > >> you won't bother to create a format object explicitly because of: > > >> class str(object): > >> ? ? ?def __mod__(self, value): > >> ? ? ? ? ?return Format(self) % value > > >>>>>> f = f"%r %i" > >>>>>> type(f) > >>> > >> ?>>> # Explicitly > >> ?>>> f = Format("%r %i") > >> ?>>> f > >> > >> ?>>> f % (2, 3, 4) > >> > > >> ?>>> # Implicitly, relying on the __mod__ method of str > >> ?>>> f = "%r %i" > >> ?>>> f > >> '%r %i' > >> ?>>> f % (2, 3, 4) > >> > > >> I'd also like to add that there's nothing to prevent format objects from > >> having other methods where multiple placeholders can be filled in one call: > > >> ?>>> # By position > >> ?>>> f = Format("%r %i") > >> ?>>> f > >> > >> ?>>> f.fill([(2, 3, 4), 1]) > >> '(2, 3, 4) 1' > > >> ?>>> # By name > >> ?>>> f = Format("%{tuple}r %{int}i") > >> ?>>> f > >> > >> ?>>> f.fill({"tuple": (2, 3, 4), "int": 1}) > >> '(2, 3, 4) 1' > > > You're choosing to favor the '.chain()' method over the '.fill()' > > method for the behavior of '%'. ?I don't think you've justified it > > though. > > >>>> Format( "%r %i" ).chain( ( 2, 3, 4 ) ).chain( 0 ) > > '(2, 3, 4) 0' > >>>> Format( "%r %i" ).fill( ( 2, 3, 4 ), 0 ) > > '(2, 3, 4) 0' > > > Plus, I almost think we've almost attained defeating the purpose. > > The disadvantage of the chaining method is that it's positional, > left-to-right. For the purposes of i18n you want tagged placeholders, > whether they be integers or names. I think... OK, if the placeholders > include a positional tag, eg "%(0)s %(1)s", then they could be filled in > according to _that_ order. Not sure about named placeholders, though. > Perhaps, like at present, if a dict is given to a format with named > placeholders then several placeholders could be filled, the problem > being how to fill a _single_ named placeholder with a dict. Just pass a keyword argument to chain. >>> Format( "%(tup)r %(int_)i" ).chain( tup= ( 2, 3, 4 ) ).chain( int_= 0 ) '(2, 3, 4) 0' You might want to call it 'fchain' or 'chainf'. From rt8396 at gmail.com Thu Dec 18 12:49:59 2008 From: rt8396 at gmail.com (r) Date: Thu, 18 Dec 2008 09:49:59 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <71ede5f0-fd88-4155-9f0d-42d0ad5f57dc@v42g2000yqj.googlegroups.com> Message-ID: <61f45e65-2404-4cc0-9d81-f848c1ba566f@i18g2000prf.googlegroups.com> Maybe someone will chime in with an answer, sorry i could not help. ponder this, i must... From prasannaksahoo at gmail.com Thu Dec 4 23:31:01 2008 From: prasannaksahoo at gmail.com (pk sahoo) Date: Fri, 5 Dec 2008 10:01:01 +0530 Subject: getting error...... Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in open_workbook biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) File "C:\Python25\Lib\site-pack Message-ID: hallo everybody, when i am running the following command >>> import xlrd >>> book=xlrd.open_workbook("C:\\a.xls") i am getting the following error.. *Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 370, in open_workb ook biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) File "C:\Python25\Lib\site-packages\xlrd\__init__.py", line 1323, in getbof raise XLRDError('Expected BOF record; found 0x%04x' % opcode) xlrd.biffh.XLRDError: Expected BOF record; found 0x3f3c* what is the reason.... pz help me out.. regards prasanna * * -------------- next part -------------- An HTML attachment was scrubbed... URL: From money.maker20096 at gmail.com Sat Dec 27 00:10:04 2008 From: money.maker20096 at gmail.com (money_maker) Date: Fri, 26 Dec 2008 21:10:04 -0800 (PST) Subject: Online Trading Message-ID: Online Trading http://209.188.94.20/~x69/?p=81 The Best Online Money Maker Ever http://209.188.94.20/~x69/?p=66 Google Adsense Program Is Like Finding Money In The Street http://209.188.94.20/~x69/?p=99 Hit Success Street With Google Adsense http://209.188.94.20/~x69/?p=98 Earn Money Running Ads http://209.188.94.20/~x69/?p=96 How And Where To Get Jobs At Home? http://209.188.94.20/~x69/?p=94 How Do You Become A Successful Affiliate Marketer? http://209.188.94.20/~x69/?p=93 7 Ways You Can Make Money On-line http://209.188.94.20/~x69/?p=92 Why Do Most People Fail At Working From Home? http://209.188.94.20/~x69/?p=90 Earn $500 To $1000 Daily Working From Home http://209.188.94.20/~x69/?p=88 Earn Money Online Securely http://209.188.94.20/~x69/?p=86 How do I make money from home? http://209.188.94.20/~x69/?p=84 The Best Online Money Maker Ever http://209.188.94.20/~x69/?p=186 3Quick Ways To Make Money Online http://209.188.94.20/~x69/?p=169 Online Trading http://209.188.94.20/~x69/?p=168 HOW TO START AND OPERATE YOUR OWN PROFITABLE IMPORT/EXPORT BUSINESS AT HOME http://209.188.94.20/~x69/?p=61 Why read online stock-trading articles? http://209.188.94.20/~x69/?p=60 Online Trading http://209.188.94.20/~x69/?p=59 Quick Ways To Make Money Online 3 http://209.188.94.20/~x69/?p=58 Remergent Skin Care Products Restore Dna And Promote Healthy Skin From mail at microcorp.co.za Sat Dec 27 07:54:32 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 27 Dec 2008 14:54:32 +0200 Subject: ctypes & strings References: <334452.47084.qm@web30003.mail.mud.yahoo.com> Message-ID: <000f01c96822$5c300f00$0d00a8c0@hendrik> Red Rackham wrote: >I would like to pass a string into a dll function. I notice that to pass using ctypes, it has to be a ctypes type. >Looking at the ctypes doc page I don't see a c_string class. The following seems to work for me: In the c programme: /* This routine outputs and inputs a symmetric block of bytes, writing the outputs out and reading the inputs in, replacing the chars in the original output string */ unsigned char read_write (unsigned char *inputs, unsigned char *outputs, int lenin, int lenout) { int i = 0; int addr = 0; int addrhi = 0; int oind = 0; char rv; while (i < lenin) { addrhi = i >> 8 & 0x3f; // we can have 64 * 256 adresses in the top 6 + 8 bits addr = i & 0xff; // this is low order rv = put_1(addrhi|0xd0); // put out the addy rv = put_3(addr); rv = put_1(addrhi|0x90); // make a read strobe on bit 6 inputs[i] = get_0() ^ 255; // read the char rv = put_1(addr|0xd0); // raise strobe again i++; } while (i < lenin + lenout) { oind = i - lenin; // index into outputs start at 0 addrhi = i >> 8 & 0x3f; // we can have 64 * 256 adresses in the top 6 + 8 bits addr = i & 0xff; // this is low order rv = put_1(addrhi|0xd0); // put out the addy rv = put_3(addr); rv = put_0(outputs[oind]); // put out the output rv = put_1(addrhi|0x50); // make a write strobe on bit 7 rv = put_1(addrhi|0xd0); // raise write strobe again i++; } return *inputs; } Then in the python it is used as follows: import sys, os, ctypes, time io = ctypes.cdll.LoadLibrary('./lib_gpio.a') def do_io(ins, outs): # ins and outs are normal python strings that must exist # this routine happens to work by side effect - the ins string is changed by the c routine r = io.read_write(ins,outs,len(ins),len(outs)) return The c routine will actually break Python's normal string immmutability and give you back a changed ins. It is in general not a good idea to change the passed string like I am doing - but you wanted to know how to pass a python string, and the outs example should get you going - a string is an array of characters in c... HTH - Hendrik From tjreedy at udel.edu Tue Dec 9 13:25:10 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 09 Dec 2008 13:25:10 -0500 Subject: RuntimeError: dictionary changed size during iteration In-Reply-To: References: <274eb282-1635-40ca-95af-b82271c57802@v4g2000yqa.googlegroups.com> <8c67c6b0-50f7-40ae-93e4-09edd07d6946@r36g2000prf.googlegroups.com> Message-ID: Robert Dailey wrote: > When I do: > > for key in stuff.keys(): > > > It works! I wonder why .keys() makes a difference. It is using a > 'view', which is a new concept in Python 3.0 that I'm not totally > familiar with yet. Because stuff.keys() is evaluated *once* and the result is a separate object from stuff == globals(), so creating the new entry 'key' in globals == stuff does not change that new object. From rt8396 at gmail.com Fri Dec 19 20:12:00 2008 From: rt8396 at gmail.com (r) Date: Fri, 19 Dec 2008 17:12:00 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <1332da3c-8075-4552-9498-3ceb23faca8f@v31g2000vbb.googlegroups.com> Scott, Oh, so Python 3.0 is an Equal Opportunity Enigma, now i get it :D Steve, Obviously i was referring to the look, not the actuality of a tuple Marc, Why move away from a concise and widely accepted way of sting formatting, just to supposedly make it a little easier for n00bs? (which i disagree this is easier) In turn, creating more syntactical clutter. (%s %f %d) is all you need to remember. If people can't understand that, i fear for the future of Humans as a species! [bearophile], """So I think it's right to make Python3 become a little higher level language even if this slows it down a little. For the kind of programs Python is often used for, I think this is a Win. (Ruby programs are often slower than Python ones (because Ruby is a little higher level than Python) but it's very useful anyway). If Python will continue to develop in the following years (think about a Python4000) then I think it may become good to make it become even more slower, if this will help make it a little more higher level still.""" [/bearophile], Yea, if your keeping up with the "Rubies" i guess. Python's strengths are in it's simplicity -and- it's constraints. Turning Python into a language so stupid a monkey could use it(there by slowing it down in the process),is counter intuitive, and will chase away core followers. Let Ruby try to include every way possible known to man to do one simple process, just to please the most people. Are we Python coders or "Corrupt Politicians" looking to grab every vote by trying to please the masses thereby sacrificing our souls in the process --> Ruby. *It may be time to start hacking my own personal version of the Python interpreter. hmm... Keep you ears to the ground... From kirk at daycos.com Thu Dec 11 14:44:22 2008 From: kirk at daycos.com (Kirk Strauser) Date: Thu, 11 Dec 2008 13:44:22 -0600 Subject: newbie question: if var1 == var2: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> Message-ID: <87y6ymzecp.fsf@daycos.com> At 2008-12-11T17:24:44Z, rdmurray at bitdance.com writes: > >>> ' ab c \r\n'.rstrip('\r\n') > ' ab c ' > >>> ' ab c \n'.rstrip('\r\n') > ' ab c ' > >>> ' ab c '.rstrip('\r\n') > ' ab c ' I didn't say it couldn't be done. I just like the Perl version better. -- Kirk Strauser The Day Companies From gandalf at shopzeus.com Fri Dec 19 02:54:26 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 19 Dec 2008 08:54:26 +0100 Subject: psycopg2 and large queries In-Reply-To: <1de36399-f94f-42b3-87ea-3812fed4bd86@r36g2000prf.googlegroups.com> References: <1de36399-f94f-42b3-87ea-3812fed4bd86@r36g2000prf.googlegroups.com> Message-ID: <494B5332.3090407@shopzeus.com> > They do have a description attribute, but it is only populated after > you fetch a row. eg try > cur = conn.cursor(name='mycursor') > cur.execute('select name from blah') > cur.fetchone() > print cur.description > Oh, great. I should have known. Thanks. Maybe I can live with psycopg2, because combining server side (named) cursors with fetchmany(100) gives fast query opening and relatively fast row fetching. Thank you for all! Laszlo From martin at marcher.name Sat Dec 27 21:19:06 2008 From: martin at marcher.name (Martin) Date: Sun, 28 Dec 2008 03:19:06 +0100 Subject: Is there a function to remove escape characters from a string ? In-Reply-To: <49560E7E.1050307@gmail.com> References: <0163882f$0$6988$c3e8da3@news.astraweb.com> <5a29b62a-c38f-409b-8887-6259ad072bf5@w1g2000prk.googlegroups.com> <01659326$0$6988$c3e8da3@news.astraweb.com> <49560E7E.1050307@gmail.com> Message-ID: <5fa6c12e0812271819t1b218c7h4bef3b426e477754@mail.gmail.com> 2008/12/27 Stef Mientki : > Steven D'Aprano wrote: >> No, that only makes it even more confusing. What does Moore's Law have to >> do with your willful ignorance about the existence of human languages other >> than English? >> > Nothing. > I even don't (want to) see what bits / bytes / escape sequences have to do > with modern programming techniques, > so I certainly don't see any relation between these and human languages. > > But the lack of Moore's law in software explains why we still need to > concern about bits and bytes ;-) http://www.joelonsoftware.com/articles/Unicode.html -- http://soup.alt.delete.co.at http://www.xing.com/profile/Martin_Marcher http://www.linkedin.com/in/martinmarcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From prologic at shortcircuit.net.au Mon Dec 8 01:37:19 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Dec 2008 16:37:19 +1000 Subject: A question about reference in Python. In-Reply-To: <47c890dc0812072225u7cde16eh9ba69a2f4cdacd16@mail.gmail.com> References: <493CB003.3080209@gmail.com> <47c890dc0812072213q20cb415fjbd4c80e7af7a7ef5@mail.gmail.com> <47c890dc0812072225u7cde16eh9ba69a2f4cdacd16@mail.gmail.com> Message-ID: On Mon, Dec 8, 2008 at 4:25 PM, Chris Rebert wrote: > No apology necessary of course, i just didn't want the newbie OP to > pick up any bad Python coding habits. Apologies that I might have > phrased my criticism a bit harshly. No not at all :) I do use class variables in some places in my library as well as instance variables. Force of habit :) Actually to be honest I think I only use it in one or two places! Haha :) *meh* Hope the OP learns what he needs to! cheers James -- -- -- "Problems are solved by method" From Ron.Barak at lsi.com Wed Dec 17 02:43:16 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Wed, 17 Dec 2008 07:43:16 +0000 Subject: String slices work only for first string character ? In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF60249410A@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF60249410A@enbmail01.lsi.com> Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6024941AE@enbmail01.lsi.com> Thanks to all who pointed my wrong understanding of how string slices are defined. Bye, Ron. ________________________________ From: Barak, Ron [mailto:Ron.Barak at lsi.com] Sent: Tuesday, December 16, 2008 15:35 To: python-list at python.org Subject: String slices work only for first string character ? Hi, Can any one explain why the following string slice works only for the first character, but not for any other ? $ cat /tmp/tmp.py #!/usr/bin/env python data = 'F0023209006-0101' print data print "|"+data[0:1]+"|" print "|"+data[1:1]+"|" print "|"+data[2:1]+"|" $ python `cygpath -w /tmp/tmp.py` F0023209006-0101 |F| || || $ Thanks, Ron. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gdamjan at gmail.com Wed Dec 3 15:12:13 2008 From: gdamjan at gmail.com (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Wed, 03 Dec 2008 21:12:13 +0100 Subject: Switching windows in PyQT References: <9ef85e1f-9e46-48b6-8d11-a4f6e7176657@d23g2000yqc.googlegroups.com> Message-ID: > I am new to PyQT and GUI programming in general. What tutorials I have > found are relatively clear on standard operations within a single > window (QtGui.QWidget or QtGui.QMainWindow). Exiting this window exits > the overall application. > > How would I switch between windows, that is close one and open > another, within a running application. I would imagine this to be a > standard feature often coded. most often you don't close windows but hide them. Still, the app object has a property quitOnLastWindowClosed that you can set to false. -- ?????? ( http://softver.org.mk/damjan/ ) Q: What's tiny and yellow and very, very, dangerous? A: A canary with the super-user password. From google at mrabarnett.plus.com Sun Dec 14 10:43:46 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 14 Dec 2008 15:43:46 +0000 Subject: 1 or 1/0 doesn't raise an exception In-Reply-To: <6e2d11cd-a57e-4cd4-9cd7-a65eb08f220e@u18g2000pro.googlegroups.com> References: <49446E39.6020807@tim.thechases.com> <6e2d11cd-a57e-4cd4-9cd7-a65eb08f220e@u18g2000pro.googlegroups.com> Message-ID: <494529B2.60108@mrabarnett.plus.com> Rohannes wrote: > 'Dive into Python' has a very memorable and interesting section on the > exact behaviour of 'and' and 'or' in Python: > > http://diveintopython.org/power_of_introspection/and_or.html > >> No: &, | (and ^, too) perform bitwise operations in Python, C and Java: > > "In complete evaluation ... both expressions are always evaluated. To > obtain complete evaluation in Java, you use & rather than && ... and > use | in place of ||" - Walter Savitch, Absolute Java 2nd ed. > > Although & IS the bitwise-AND operator in Java: > http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html > > I guess it's a matter of context. > Java has a bool type that's distinct from the int type. &, | and ^ are bitwise for int and Boolean for bool, and in both cases they are strict. && and || are for bool only and they are lazy. In Pascal the behaviour of "and" and "or" is implementation-dependant... From martin at v.loewis.de Mon Dec 8 19:55:43 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 09 Dec 2008 01:55:43 +0100 Subject: Number of Python 3.x packages at the PyPI In-Reply-To: <3b2464a1-84d4-4833-ac26-accd317d978d@k19g2000yqg.googlegroups.com> References: <9c1ab0f3-6686-4c0f-8a6c-12e20539f354@41g2000yqf.googlegroups.com> <493b954e$0$4021$9b622d9e@news.freenet.de> <2d656e64-deff-40ed-8066-57b6f8874ec4@b38g2000prf.googlegroups.com> <493c29a7$0$27869$9b622d9e@news.freenet.de> <3b2464a1-84d4-4833-ac26-accd317d978d@k19g2000yqg.googlegroups.com> Message-ID: <493DC20F.7040606@v.loewis.de> >> On second thought: can't you just include the source of both versions >> in a single source distribution file? > > The .tar.gz distributions are built by distutils/setuptools. If I > manually combine them into a single archive That's not what I'm proposing, though. Assuming you have two different versions of your package, they should both live next to each other, in a single root directory, e.g. foo/ setup.py bar_2x/ bar_3x/ Then sdist should package it all, through a MANIFEST.in, and install/bdist/... should package it version-dependent: if sys.version >= (3,0): package_dir = {'bar':'bar_3x'} else: package_dir = {'bar':'bar_2x'} setup(... package=dir = package_dir, ... ) > I'm guessing that > 'easy_install appscript' won't know how to read that custom archive > when building and installing from source. (Which also raises a further > question: if I do eventually manage to upload both 2.x and 3.x > versions under the same PyPI entry, will easy_install know which one > to download?) See above. Won't this solve these problems? (although I don't know what the "appscript" command does) Regards, Martin From bj_666 at gmx.net Sun Dec 14 04:25:27 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 14 Dec 2008 09:25:27 GMT Subject: the official way of printing unicode strings References: Message-ID: <6qk1o7Fcr01gU3@mid.uni-berlin.de> On Sun, 14 Dec 2008 06:48:19 +0100, Piotr Sobolewski wrote: > Then I tried to do this that way: > sys.stdout = codecs.getwriter("utf-8")(sys.__stdout__) > s = u"Stanis?aw Lem" > print u > This works but is even more combersome. > > So, my question is: what is the official, recommended Python way? I'd make that first line: sys.stdout = codecs.getwriter('utf-8')(sys.stdout) Why is it even more cumbersome to execute that line *once* instead encoding at every ``print`` statement? Ciao, Marc 'BlackJack' Rintsch From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 20:46:13 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2008 01:46:13 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> Message-ID: <015c45b8$0$20656$c3e8da3@news.astraweb.com> On Fri, 19 Dec 2008 09:55:01 -0800, bearophileHUGS wrote: > C string formatting is short and a flexible enough, but it's out of > place in a language as high level as Python3. The new syntax allows more > flexibility, and it's better for most people that don't know C already, > like newbies, etc. I'm somebody who frequently argues that we shouldn't assume that everybody knows C. But on the other hand, we shouldn't assume that newbies don't know C either! % formatting is so very common that even a duffer like me who never learned C came to Python already knowing the basics of % formatting. -- Steven From muhamed.hmd at gmail.com Wed Dec 10 14:09:50 2008 From: muhamed.hmd at gmail.com (john adam) Date: Wed, 10 Dec 2008 11:09:50 -0800 (PST) Subject: hi...hi.....hi Message-ID: <2560fe66-626b-49b5-afc1-77d7c9bbd76e@d36g2000prf.googlegroups.com> conratulatios...... Here's my dear friend largest mobile library programs All you care programs : Witness all the programs in the modern world Alkmiotr Honored by your visit You'll see in the blogger 1.If you are suffering from a virus protection programs most important to you AVG Anti-Virus Free Edition "avG" http://mesotheliomame.blogspot.com/2008/11/pericardial-mesothelioma-and-modern.html 2.If you turn suffering from transmitting the files LimeWire Pro 4.14.7 http://mesotheliomame.blogspot.com/2008/11/overview-of-mesothelioma-cancer.html 3.If you have files you spy on your computer solution Ad-Aware 2008 http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawsuits-faq.html 4.You stronger virus program Ante 2008 Avira AntiVir Personal - Free Antivirus http://mesotheliomame.blogspot.com/2008/11/number-form-of-mesothelioma-pleural.html 5.Now a program of protection and anti-virus and anti-spy files Avast Home Edition http://mesotheliomame.blogspot.com/2008/11/what-to-look-for-in-california.html 6.If you are suffering from non-fast you download this program FrostWire http://mesotheliomame.blogspot.com/2008/11/if-you-are-diagnosed-with-mesothelioma_15.html 7.If you have difficulty loading of the Diaspora and Google Orbit Downloader http://mesotheliomame.blogspot.com/2008/11/if-you-are-diagnosed-with-mesothelioma.html 8.If you have difficulty difficult compression "file" winrar http://mesotheliomame.blogspot.com/2008/11/contacting-mesothelioma-lawyer.html 9.If you are suffering from aAdware/Malware files you solution Malwarebytes' Anti-Malware http://mesotheliomame.blogspot.com/2008/11/scientists-conduct-clincial-trials-of.html 10.Now the most powerful video chat in the world Camfrog Video Chat http://mesotheliomame.blogspot.com/2008/11/new-drug-study-for-abdominal.html 11.Program chat world is a lot mIRC http://mesotheliomame.blogspot.com/2008/11/ohio-mesothelioma-lawyer-help-you-get.html 12.If you have difficulty reading flv files FLV Player http://mesotheliomame.blogspot.com/2008/11/detailed-information-on-mesothelioma.html 13.If you have difficulty download from youtube YouTube Downloader http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawyers-in-high-demand.html 14.If you are suffering from penetrating the strongest program you repel breakthroughs in the world Spybot - Search & Destroy http://mesotheliomame.blogspot.com/2008/11/chemotherapy-treatment-for-mesothelioma.html 15.If you have difficulty with the way they spread the images IrfanView http://mesotheliomame.blogspot.com/2008/11/california-mesothelioma-laws-and.html 16.Now have a major program of the torrent file and upload files BitComet http://mesotheliomame.blogspot.com/2008/11/facing-mesothelioma-without-california.html 17.The program is exclusive download from the Web at high speed Download Accelerator Plus http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-diagnoses-increase_15.html 18.If you are suffering from problems with the performance of the solution you Smart Defrag http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-diagnoses-increase.html 19.If you have difficulty in performing the solution you Advanced WindowsCare Personal http://mesotheliomame.blogspot.com/2008/11/mesothelioma-is-deadly-cancer.html 20.If you have difficulty in operating the sound and video files you solution real player http://mesotheliomame.blogspot.com/2008/11/facts-and-misconceptions-about.html 21.Here is the most important video player program in America GOM Media Player http://mesotheliomame.blogspot.com/2008/11/how-severe-is-mesothelioma-disease.html 22.If you have difficulty operating Flash Games Flash Player http://mesotheliomame.blogspot.com/2008/11/glimpse-at-mesothelioma-info-from-past.html 23.If you have difficulty in cleaning Riggstir professionally you the best solution http://mesotheliomame.blogspot.com/2008/11/detection-of-asbestos-mesothelioma.html 24.If you turn suffering from your computer and the difficulty you download this program"System Mechanic" http://mesotheliomame.blogspot.com/2008/11/brief-overview-of-malignant.html 25.If you are suffering from problems in the cleaning solution you Riggstir http://mesotheliomame.blogspot.com/2008/11/mesothelioma-and-911.html 26.Use the latest hour computer in the world in the magnificence of beauty http://mesotheliomame.blogspot.com/2008/11/precise-idea-about-pericardial.html 27.If you have difficulty in maintaining from hard disk http://mesotheliomame.blogspot.com/2008/11/mesothelioma-at-glance.html 28.If you have difficulty in managing personal and protection of your system you program http://mesotheliomame.blogspot.com/2008/11/financial-burden-of-mesothelioma.html 29.If you have difficulty in recording data and operation of your system http://mesotheliomame.blogspot.com/2008/11/how-to-find-mesothelioma-lawyer.html 30.Here's this program that offers you much time http://mesotheliomame.blogspot.com/2008/11/hurricane-victims-at-risk-for.html 31.If you have difficulty in browsing files http://mesotheliomame.blogspot.com/2008/11/3-top-florida-mesothelioma-lawyer.html 32.Here's this program, which automatically corrects the mistakes of your system security http://mesotheliomame.blogspot.com/2008/11/if-diagnosed-with-mesothelioma-call.html 33.The enjoyment of this program to register images from camera to the computer during the talk http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-diagnosed-questions.html 34.If you have difficulty transforming stretches in games or votes you this giant http://mesotheliomame.blogspot.com/2008/11/mesothelioma-ready-reckoner.html 35.If you have difficulty in operation all formats video files http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawyers-how-to-choose-them.html 36.If you have difficulty in the organization and ease of cleaning solution you http://mesotheliomame.blogspot.com/2008/11/mesothelioma-exposure-could-be-fatal.html 37.Very popular program in the compression winzip http://mesotheliomame.blogspot.com/2008/11/mesothelioma-greed-cancer-profits.html 38..If you want to broadcast material on the Internet you solution Virtual DJ Software http://mesotheliomame.blogspot.com/2008/11/abc-mesothelioma-new-treatments-for.html 39.now The creation of program files pdf PrimoPDF http://mesotheliomame.blogspot.com/2008/11/abc-mesothelioma-treatments-for.html 40..If you have difficulty operating the extensions you solution "MPEG-1, MPEG-2, MPEG-DivX, mp3, ogg VLC Media Player http://mesotheliomame.blogspot.com/2008/11/brachytherapy-for-treatment-of.html 41.If you have difficulty browser you this treasure Mozilla Firefox http://mesotheliomame.blogspot.com/2008/11/asbestos-mesothelioma-treatment-how.html 42.If you are difficult to clean your computer you solution Glary Utilities http://mesotheliomame.blogspot.com/2008/11/mesothelioma-treatment-research.html 43.very Free program to repair and improve and see photos PhotoScape http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-history.html 44.If you have difficulty operating films and cartoons BS.Player http://mesotheliomame.blogspot.com/2008/11/mesothelioma-attorney.html 45.Conversion formulas giant cylinders to the chimerical not want the program ... PowerISO http://mesotheliomame.blogspot.com/2008/11/deadly-mesothelioma-symptoms-could-be_15.html 46.You program the operator of high-quality video DivX for Windows with DivX Player http://mesotheliomame.blogspot.com/2008/11/deadly-mesothelioma-symptoms-could-be.html 47.If you have difficulty copies of CDs nero "9"new http://mesotheliomame.blogspot.com/2008/11/association-of-asbestos-and.html 48.If you have difficulty audio chat on the net you the solution Windows Live Messenger http://mesotheliomame.blogspot.com/2008/11/need-for-mesothelioma-lawyer-to-fight.html 49.If you have difficulty download on the net ActiveX Download Control http://mesotheliomame.blogspot.com/2008/11/funding-for-mesothelioma-research-noble_15.html 50.If you have difficulty in registration at the sites and forums you solution RoboForm http://mesotheliomame.blogspot.com/2008/11/funding-for-mesothelioma-research-noble.html 51.If you are an amateur or design you a solution designed sites you Adobe Photoshop CS3 Extended http://mesotheliomame.blogspot.com/2008/11/brief-overview-of-peritoneal.html 52.If you have difficulty cleaning you stronger cleaning program in the world ccleaner http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawyers-helping-hands.html 53.If you have difficulty in Alturrent know what files you need them all uTorrent http://mesotheliomame.blogspot.com/2008/11/how-to-proceed-with-mesothelioma_15.html 54.If you have difficulty in loading files from the iPod Lalai iTunes http://mesotheliomame.blogspot.com/2008/11/how-to-proceed-with-mesothelioma.html 55.If you have difficulty converting audio files to any formulas you solution Easy CD-DA Extractor http://mesotheliomame.blogspot.com/2008/11/difference-between-pleural-and.html 56.If you have difficulty converting video files to the formula psp PSP Video 9 http://mesotheliomame.blogspot.com/2008/11/positive-guideline-to-deal-with.html 57.If you have difficulty in the work of videos from YouTube to evict you like you solution Windows Movie Maker http://mesotheliomame.blogspot.com/2008/11/history-of-asbestos-related.html 58.If you have difficulty in Works with all audio files extranet windows media player http://mesotheliomame.blogspot.com/2008/11/tips-on-choosing-your-mesothelioma.html 59.If you have difficulty in Browser you the most powerful browser in the world Avant Browse http://mesotheliomame.blogspot.com/2008/11/good-mesothelioma-attorney-is-hard-to.html 60.If you have difficulty in Video-sharing to you this wonderful program BearFlix http://mesotheliomame.blogspot.com/2008/11/peritoneal-mesothelioma-information.html 61.If you have difficulty in Survey of spyware on your computer SpywareBlaster http://mesotheliomame.blogspot.com/2008/11/how-to-care-for-someone-with.html 62.If you are suffering from problems in Alhard Disek you this legend smart PerfectDisk http://mesotheliomame.blogspot.com/2008/11/why-is-mesothelioma-so-deadly.html 63.If you have difficulty in the liberation of files "pdf" http://mesotheliomame.blogspot.com/2008/11/when-do-you-need-mesothelioma-attorney.html 64.If you have difficulty in personal control of your system next to you http://mesotheliomame.blogspot.com/2008/11/all-about-mesothelioma-lawyer.html 65.If you have difficulty in the key to jump easily be you next http://mesotheliomame.blogspot.com/2008/11/what-is-mesothelioma-cancer.html 66.If you have difficulty playing in the pictures and the amendment http://mesotheliomame.blogspot.com/2008/11/mesothelioma-information.html 67.If you have difficulty in protecting your system security followed CAPS http://mesotheliomame.blogspot.com/2008/11/symptoms-of-mesothelioma.html 68.If you have difficulty in speed of your computer you this program http://mesotheliomame.blogspot.com/2008/11/what-radical-mesothelioma-treatments.html 69.If you have difficulty maintaining a malfunction in your computer that you legend http://mesotheliomame.blogspot.com/2008/11/can-washington-mesothelioma-attorneys.html 70.If you have difficulty in the transfer of files between disks http://mesotheliomame.blogspot.com/2008/11/causes-of-mesothelioma-cancer.html 71.Discovered the most important program on the Web EZ Macros http://mesotheliomame.blogspot.com/2008/11/mesothelioma-treatment-radiation-or.html 72.If you are suffering from similar files, you repeat this unique program http://mesotheliomame.blogspot.com/2008/11/types-of-mesothelioma-cancer.html http://mesotheliomame.blogspot.com/ From ivan.illarionov at gmail.com Tue Dec 9 05:43:38 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 9 Dec 2008 02:43:38 -0800 (PST) Subject: Beginner trying to understand functions. References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> <9df7549a-f28b-4d39-b105-90c099f472f2@z28g2000prd.googlegroups.com> <040a2896-be99-477e-909c-c55c5a0e6665@y1g2000pra.googlegroups.com> Message-ID: On Dec 8, 9:02?pm, simonh wrote: > Thanks for the many replies. Thanks especially to Pierre. This works > perfectly: > def getAge(): > ? ? while True: > ? ? ? ? try: > ? ? ? ? ? ? age = int(input('Please enter your age: ')) > ? ? ? ? ? ? return age > > ? ? ? ? except ValueError: > ? ? ? ? ? ? print('That was not a valid number. Please try again.') You could also drop the while loop and the 'age' variable: def getAge(): try: return int(input('Please enter your age: ')) except ValueError: print('That was not a valid number. Please try again.') return getAge() From lew at lewscanon.com Tue Dec 2 16:57:35 2008 From: lew at lewscanon.com (Lew) Date: Tue, 2 Dec 2008 13:57:35 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <591e8625-7e4d-4db8-ae6c-73c4370f8088@q26g2000prq.googlegroups.com> Message-ID: Xah Lee wrote: > If [yo]u would like to learn [the] [E]nglish lang[uage] and writing insights from me, > peruse: /Au contraire/, I was suggesting a higher standard for your posts. > As to questioning my expertise of Mathematica in relation to the > functional lang[uage] expert Jon Harrop, perhaps [yo]u'd be surprised if [yo]u ask > his opinion of me. My own opinion, is that my Mathematica expertise > surpasses his. My opinion of his opinion of me is that, my opinion on > Mathematica is not to be trifled with. I have no assertion or curiosity about Jon Harrop's expertise compared to yours. I was expressing my opinion of his expertise, which is high. > Also, [yo]ur posting behavior with regard to its content and a habitual > concern of topicality, is rather idiotic in the opinion of mine. On There is no reason for you to engage in an /ad hominem/ attack. It does not speak well of you to resort to deflection when someone expresses a contrary opinion, as you did with both Jon Harrop and with me. I suggest that your ideas will be taken more seriously if you engage in more responsible behavior. > the surface, the army of [yo]ur kind have the high spirit for the health > of community. But underneath, i [sic] think it is [yo]u who [a]r[e] the most > wortheless with regards to online computing forum's health. You are entitled to your opinion. I take no offense at your attempts to insult me. How does your obfuscatory behavior in any way support your technical points? -- Lew From boyee118 at gmail.com Thu Dec 18 06:25:27 2008 From: boyee118 at gmail.com (=?UTF-8?B?5Li654ix6ICM55Sf?=) Date: Thu, 18 Dec 2008 19:25:27 +0800 Subject: [Help] The pywinauto Can't select the MDI's menu using the MenuItems() which return []. In-Reply-To: References: Message-ID: This problem also use the following discription:How to use pywinauto to open WORD and select its Menu. I can't do that and have no idea why! Looking forward your help,Thanks! 2008/12/17 ???? > I can't use the MenuItems() in my MDI application. > Any example is very nice!!!! Thanks a lot! > > -- > "OpenBookProject"-?????????? > ??: http://groups.google.com/group/OpenBookProject > ??: http://wiki.woodpecker.org.cn/ > -- "OpenBookProject"-?????????? ??: http://groups.google.com/group/OpenBookProject ??: http://wiki.woodpecker.org.cn/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From h0leforfun at gmail.com Wed Dec 17 09:33:53 2008 From: h0leforfun at gmail.com (Hole) Date: Wed, 17 Dec 2008 06:33:53 -0800 (PST) Subject: Python, XML and XPath References: <49490c49$0$1115$4fafbaef@reader3.news.tin.it> Message-ID: > > I need to use XML parsing with xpath: a simple xml reader. > > You can try lxml, have a look herehttp://codespeak.net/lxml/xpathxslt.html Thanks a lot to everyone! From 20080915.20.wmcclain at spamgourmet.com Wed Dec 10 13:55:10 2008 From: 20080915.20.wmcclain at spamgourmet.com (Bill McClain) Date: 10 Dec 2008 18:55:10 GMT Subject: StringIO in 2.6 and beyond References: Message-ID: On 2008-12-10, pruebauno at latinmail.com wrote: > I think this combination might do the trick (I don't have 2.6 to test > it right now): > from __future__ import print_function > from __future__ import unicode_literals > from functools import partial > import io > print = partial(print, sep=" ", end="\n") > out = io.StringIO() > print("hello", file=out) The example works, but unicode_literals causes problems elsewhere, in optparse for example. I didn't look into it too closely. I'll probably give up trying to anticipate 3.0 with 2.6 too closely. -Bill -- Sattre Press Tales of War http://sattre-press.com/ by Lord Dunsany info at sattre-press.com http://sattre-press.com/tow.html From google at mrabarnett.plus.com Fri Dec 12 13:30:19 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 12 Dec 2008 18:30:19 +0000 Subject: (Very Newbie) Problems defining a variable In-Reply-To: References: Message-ID: <4942ADBB.8030309@mrabarnett.plus.com> Tim Rowe wrote: > Since we all seem to be having a go, here's my take. By pulling the > rates and thresholds into a dictionary I feel I'm getting a step > closer to the real world, where these would presumably be pulled in > from a database and the number of interest bands might vary. But is > there a tidier way to get 'thresholds'? I was a bit surprised that > rates.keys() didn't give me a list directly, so although the 3.0 > tutorial says "The keys() method of a dictionary object returns a list > of all the keys used in the dictionary, in arbitrary order (if you > want it sorted, just apply the sort() method to )" that's not /quite/ > such a given, because "the list of keys" doesn't seem to be there for > the sorting any more. > > Is there a tidy way of making rates and thresholds local to get_rate, > without recalculating each time? I suppose going object oriented is > the proper way. > > #Py3k,UTF-8 > > rates = {0: 0.006, 10000: 0.0085, 25000: 0.0124, 50000: 0.0149, 100000: 0.0173} > thresholds = list(rates.keys()) > thresholds.sort() > thresholds.reverse() > Why are you putting them into a dict at all? Surely a list of tuples is better? # I could've just written the list in descending order here! rates = [(0, 0.006), (10000, 0.0085), (25000, 0.0124), (50000, 0.0149), (100000, 0.0173)] thresholds.sort(reversed=True) > def get_rate(balance): > for threshold in thresholds: > if balance >= threshold: > return rates[threshold] > else: > return 0.0 > def get_rate(balance): for threshold, rate in thresholds: if balance >= threshold: return rate return 0.0 > balance = int(input("How much money is in your account?\n>>")) > target = int(input("How much money would you like to earn each year?\n>>")) > > if balance <= 0: > print("You'll never make your fortune that way!\n") > else: > interest = 0 > year = 0 > while interest < target: > rate = get_rate(balance) > interest = balance * rate > balance += interest > year += 1 > print("Year %s, at %s rate: %s paid, %s in bank." % (year, > rate, interest, balance)) > From jstroud at mbi.ucla.edu Wed Dec 10 05:44:11 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 10 Dec 2008 02:44:11 -0800 Subject: filter iterable based on predicate take from another iterable In-Reply-To: References: Message-ID: <%3N%k.9174$x%.5002@nlpi070.nbdc.sbc.com> Peter Otten wrote: > bernhard.voigt at gmail.com wrote: > >> is there is a neat way to select items from an iterable based on >> predicates stored in another iterable without zipping? I can do >> something like this: >> >> import itertools >> foo = range(10) >> # select even numbers >> bar = map(lambda i: i%2, foo) >> foobarselected = itertools.ifilterfalse(lambda t: t[0], itertools.izip >> (bar,foo)) >> # for simplicity I want to work with the single item list, not the >> zipped one >> fooselected = list(t[1] for t in foobarselected) >> >> However, it would be nice to have a function combining the last two >> instructions. Something like >> itertools.ifilterother(bar, foo) -> yield iterator with items from foo >> where bar is true > > I think it's a good approach to keep the number of primitives low. I find > the list comprehension combined with izip() quite readable: > > [v for f, v in izip(bar, foo) if not f(v)] > > Peter If you want an iterator without requiring making a list, you can simply use parentheses instead of brackets: agenerator = (v for f, v in izip(bar, foo) if not f(v)) This is perfectly lazy but not immune to problems when foo or bar is changed before the generator is fully consumed. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From christophedeze at gmail.com Mon Dec 22 13:37:56 2008 From: christophedeze at gmail.com (Toff) Date: Mon, 22 Dec 2008 10:37:56 -0800 (PST) Subject: join a samba domain References: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> <494fd597$0$90267$14726298@news.sunsite.dk> Message-ID: <73194a24-f14e-46f1-8789-886ba4729084@r15g2000prd.googlegroups.com> On 22 d?c, 18:59, Jens Henrik Leonhard Jensen wrote: > Toff wrote: > > ? ?d = c.Win32_ComputerSystem > > ? ?d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") > > Shouldn't r"admin\\mydom" be "admin\\mydom" or r"admin\mydom". > Or maybe just "admin" > > /Jens Henrik you are right but i've got the same error. From bdesth.quelquechose at free.quelquepart.fr Thu Dec 4 15:30:10 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 Dec 2008 21:30:10 +0100 Subject: Why shouldn't you put config options in py files In-Reply-To: References: Message-ID: <49384b8c$0$14451$426a74cc@news.free.fr> HT a ?crit : > A colleague of mine is arguing that since it is easy to write config like: > > FOO = {'bar': ('a': 'b'), 'abc': ('z': 'x')} > > in config.py and just import it to get FOO, but difficult to achieve the > same using an ini file and ConfigParser, and since Python files are just > text, we should just write the config options in the Python file and > import it. > > I can think of lots of arguments why this is a bad idea, but I don't > seem to be able to think of a really convincing one. > > Anyone? Well... Depends on who is writing these config files and how they are used. But at least one major Python software (namely Django) uses .py setting files, and a Python developper I'm grateful they do - this greatly simplifies my job. From jonanin at gmail.com Wed Dec 10 00:13:36 2008 From: jonanin at gmail.com (Jon Morton) Date: Tue, 9 Dec 2008 21:13:36 -0800 (PST) Subject: Best way to report progress at fixed intervals References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> <817384d5-5f68-4c1f-9560-0bc7b7d2b1e3@v5g2000prm.googlegroups.com> Message-ID: <14672e99-00bf-4f6b-bed7-afa7a02dc629@g38g2000yqn.googlegroups.com> I think there is something I've run into, and it will only ever get _loaded_ once. See below for sour output of an easy example case of my problem. The wxPython lib is big, so it may have bugs, but pySer l and pure python (no C/C++ directly, event thought it uses os.open/ close & termios that themselves use mistaking)) and I see nothing that could cause this. I used the "ps" command to see the memory usage recipe that I found that counts the number of objects. To test them just run each example and run "ps python" once in a few days. This is probably just bias from my last programming environment, though. From mrkafk at gmail.com Mon Dec 29 09:52:07 2008 From: mrkafk at gmail.com (mk) Date: Mon, 29 Dec 2008 15:52:07 +0100 Subject: multiprocessing vs thread performance Message-ID: Hello everyone, After reading http://www.python.org/dev/peps/pep-0371/ I was under impression that performance of multiprocessing package is similar to that of thread / threading. However, to familiarize myself with both packages I wrote my own test of spawning and returning 100,000 empty threads or processes (while maintaining at most 100 processes / threads active at any one time), respectively. The results I got are very different from the benchmark quoted in PEP 371. On twin Xeon machine the threaded version executed in 5.54 secs, while multiprocessing version took over 222 secs to complete! Am I doing smth wrong in code below? Or do I have to use multiprocessing.Pool to get any decent results? # multithreaded version #!/usr/local/python2.6/bin/python import thread import time class TCalc(object): def __init__(self): self.tactivnum = 0 self.reslist = [] self.tid = 0 self.tlock = thread.allocate_lock() def testth(self, tid): if tid % 1000 == 0: print "== Thread %d working ==" % tid self.tlock.acquire() self.reslist.append(tid) self.tactivnum -= 1 self.tlock.release() def calc_100thousand(self): tid = 1 while tid <= 100000: while self.tactivnum > 99: time.sleep(0.01) self.tlock.acquire() self.tactivnum += 1 self.tlock.release() t = thread.start_new_thread(self.testth, (tid,)) tid += 1 while self.tactivnum > 0: time.sleep(0.01) if __name__ == "__main__": tc = TCalc() tstart = time.time() tc.calc_100thousand() tend = time.time() print "Total time: ", tend-tstart # multiprocessing version #!/usr/local/python2.6/bin/python import multiprocessing import time def testp(pid): if pid % 1000 == 0: print "== Process %d working ==" % pid def palivelistlen(plist): pll = 0 for p in plist: if p.is_alive(): pll += 1 else: plist.remove(p) p.join() return pll def testp_100thousand(): pid = 1 proclist = [] while pid <= 100000: while palivelistlen(proclist) > 99: time.sleep(0.01) p = multiprocessing.Process(target=testp, args=(pid,)) p.start() proclist.append(p) pid += 1 print "=== Main thread waiting for all processes to finish ===" for p in proclist: p.join() if __name__ == "__main__": tstart = time.time() testp_100thousand() tend = time.time() print "Total time:", tend - tstart From invalid at invalid Mon Dec 22 16:02:37 2008 From: invalid at invalid (Grant Edwards) Date: Mon, 22 Dec 2008 15:02:37 -0600 Subject: Check file is References: <7caa7d45-ebbe-4c88-bb50-2f01f7315d07@s9g2000prg.googlegroups.com> Message-ID: On 2008-12-20, Harish wrote: > Is there any utility in python which will help me to read any > pdf files? There are two things I can think off the top of my head 1) The Poppler library. I don't know if there's a Python binding for it. The poppler home page and Wikipedia page would probably be a good place to start reading. 2) Qoppa Software has some Java PDF libraries that you could probably use with Jython. -- Grant Edwards grante Yow! Did I do an INCORRECT at THING?? visi.com From andrew.gregory at npl.co.uk Fri Dec 19 10:14:47 2008 From: andrew.gregory at npl.co.uk (andrew.gregory at npl.co.uk) Date: Fri, 19 Dec 2008 07:14:47 -0800 (PST) Subject: Tix.Balloon crashes in Python 2.61 Windows Message-ID: I've found that Tix GUI applications crash after switching to Python 2.6.1 (Windows XP) when Balloons are used. IDLE gives this error message: Traceback (most recent call last): File "D:\PyFiles\InstrumentSetup\Automenu.py", line 217, in else: displayedwidget=MainWidget(root, CS) File "D:\PyFiles\InstrumentSetup\Automenu.py", line 155, in __init__ b = Tix.Balloon(MyFrame) File "C:\Python26\lib\lib-tk\Tix.py", line 529, in __init__ TixWidget.__init__(self, master, 'tixBalloon', static, cnf, kw) File "C:\Python26\lib\lib-tk\Tix.py", line 307, in __init__ self.tk.call(widgetName, self._w, *extra) TclError: unknown color name "{#ffff60}" A Windows message box came up also. It gave the message: The exception unknown exception (0x40000015) occurred in the application at location 0x1e03a63b Perhaps Tix.Balloon has been omitted from the test suite? I tried searching but cannot see this reported elsewhere. Can anyone else confirm this behaviour? Where is the best place to report this bug? I can supply a script demonstrating the problem. Andrew. From jon at ffconsultancy.com Sun Dec 7 12:39:30 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Sun, 07 Dec 2008 17:39:30 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: Xah Lee wrote: > I didn't realize until after a hour, that if Jon simply give numerical > arguments to Main and Create, the result timing by a factor of 0.3 of > original. What a incredible sloppiness! and he intended this to show > Mathematica speed with this code? > > The Main[] function calls Create. The create has 3 parameters: level, > c, and r. The level is a integer for the recursive level of > raytracing . The c is a vector for sphere center i presume. The r is > radius of the sphere. His input has c and r as integers, and this in > Mathematica means computation with exact arithmetics (and automatic > kicks into infinite precision if necessary). Changing c and r to float > immediately reduced the timing to 0.3 of original. That is only true if you solve a completely different and vastly simpler problem, which I see you have (see below). > The RaySphere function contain codes that does symbolic computation by > calling Im, which is the imaginary part of a complex number!! and if > so, it returns the symbol Infinity! The possible result of Infinity is > significant because it is used in Intersect to do a numerical > comparison in a If statement. So, here in these deep loops, > Mathematica's symbolic computation is used for numerical purposes! Infinity is a floating point number. > So, first optimization at the superficial code form level is to get > rid of this symbolic computation. That does not speed up the original computation. > Instead of checking whethere his ?disc = Sqrt[b^2 - v.v + r^2]? has > imaginary part, one simply check whether the argument to sqrt is > negative. That does not speed up the original computation. > after getting rid of the symbolic computation, i made the RaySphere > function to be a Compiled function. That should improve performance but the Mathematica remains well over five orders of magnitude slower than OCaml, Haskell, Scheme, C, C++, Fortran, Java and even Lisp! > Besides the above basic things, there are several aspects that his > code can improve in speed. For example, he used pattern matching to do > core loops. > e.g. Intersect[o_, d_][{lambda_, n_}, Bound[c_, r_, s_]] > > any Mathematica expert knows that this is something you don't want to > do if it is used in a core loop. Instead of pattern matching, one can > change the form to Function and it'll speed up. Your code does not implement this change. > Also, he used ?Block?, which is designed for local variables and the > scope is dynamic scope. However the local vars used in this are local > constants. A proper code would use ?With? instead. (in lisp, this is > various let, let*. Lispers here can imagine how lousy the code is > now.) Earlier, you said that "Module" should be used. Now you say "With". Which is it and why? Your code does not implement this change either. > Here's a improved code. The timing of this code is about 0.2 of the > original. > ... > Timing[Export["image.pgm",Graphics at Raster@Main[2,100,4.]]] You have only observed a speedup because you have drastically simplified the scene being rendered. Specifically, the scene I gave contained over 80,000 spheres but you are benchmarking with only 5 spheres and half of the image is blank! Using nine levels of spheres as I requested originally, your version is not measurably faster at all. Perhaps you should give a refund? -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From stephen.thorne at gmail.com Fri Dec 12 05:49:48 2008 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Fri, 12 Dec 2008 20:49:48 +1000 Subject: Removing None objects from a sequence In-Reply-To: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> Message-ID: <20081212104948.GA3254@thorne.id.au> On 2008-12-12, Filip Gruszczy?ski wrote: > Hi! > > I would like to iterate over a sequence nad ignore all None objects. > The most obvious way is explicitly checking if element is not None, > but it takes too much space. And I would like to get something faster. > I can use > [ sth for sth in self.__sth if not sth is None ], but I don't know if > that's the best way. I checked itertools, but the only thing that > seemed ok, was ifilter - this requires seperate function though, so > doesn't seem too short. How can I get it the shortest and fastest way? There's a little hack that will remove all elements from a list that are 'False' when considered as a boolean. So None, [], '', False, etc. filter(None, myseq) an example: >>> l = ['1', 2, 0, None, '5'] >>> filter(None, l) ['1', 2, '5'] -- Regards, Stephen Thorne Development Engineer NetBox Blue - 1300 737 060 Scanned by the NetBox from NetBox Blue (http://netboxblue.com/) Can you afford to be without a NetBox? Find out the real cost of internet abuse with our ROI calculator. http://netboxblue.com/roi Scanned by the NetBox from NetBox Blue (http://netboxblue.com/) From kermit.mei at gmail.com Mon Dec 8 00:44:09 2008 From: kermit.mei at gmail.com (Kermit Mei) Date: Mon, 08 Dec 2008 13:44:09 +0800 Subject: A question about reference in Python. In-Reply-To: <47c890dc0812072136v4e36dc1crbf0c913760f477d4@mail.gmail.com> References: <493CB003.3080209@gmail.com> <47c890dc0812072136v4e36dc1crbf0c913760f477d4@mail.gmail.com> Message-ID: <493CB429.2050103@gmail.com> Chris Rebert wrote: > On Sun, Dec 7, 2008 at 9:26 PM, Group wrote: > >> Hello, I'm studying algorithom. For concentrating on the question itself, I >> intend to use Python to implement the algorithoms. >> >> Now, I want to write a Red-Black Tree, and a List structure. In C/C++, I can >> use pointers to refer to children notes (or next notes). But, in Python, >> how >> can I do it? Except the sequence, I know not any way. >> >> You'd better help me understan how can I transform the following C code into >> Python: >> >> /* a List */ >> struct { >> int data; >> int *next; >> int *prev; >> } >> > > Possibly not an exact literal translation, but: > > class ListNode(object): > def __init__(self, data, prev=None, next=None) > self.data = data > self.prev = prev > self.next = next > > > Keep in mind that Python uses call-by-object (google it), so it > doesn't have pointers/references per-se. > > Cheers, > Chris > Yes, I see. Thank you, very much! From rogerpack2005 at gmail.com Fri Dec 26 20:19:23 2008 From: rogerpack2005 at gmail.com (rogerdpack) Date: Fri, 26 Dec 2008 17:19:23 -0800 (PST) Subject: ruby -> python translator exists? Message-ID: <04b51f42-e18e-4902-8a98-38f0538c1eda@s9g2000prg.googlegroups.com> Hi all. My name is Roger. Anyway question. Anybody know of a Ruby -> Python translator at all? I'm looking for a way to have my Ruby code take advantage of the coolio speed of Psyco. Also question. Does psyco work with Python 3.0? Thanks! -=r From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 23 04:03:36 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 23 Dec 2008 10:03:36 +0100 Subject: Are Django/Turbogears too specific? In-Reply-To: References: Message-ID: <4950a963$0$32051$426a74cc@news.free.fr> Daniel Fetchinson a ?crit : (snip) > The 1.x branch of tg is built on cherrypy, the 2.x branch is built on > pylons. Both branches depend on external packages for most of their > functionality which makes them very flexible. Django is monolithic Except that 1/ you can use each component (request handler/dispatcher, templating system and ORM) standalone, and 2/ you can use any other ORM or templating system. > and was intended to be monolithic. "highly integrated" would be more accurate than "monolithic" IMHO. > Of course you can customize it and use > different components than the defaults, but after all *everything* is > customizable since the source code is there and you can modify it. You don't need to touch the source to swap ORM or templating system. > The > point is that tg was designed with flexibility and customizability in > mind, while django was designed with a monolithic infrastructure in > mind. s/monolithic/integrated/ From python at bdurham.com Wed Dec 24 03:23:00 2008 From: python at bdurham.com (python at bdurham.com) Date: Wed, 24 Dec 2008 03:23:00 -0500 Subject: Strategy for determing difference between 2 very large dictionaries In-Reply-To: References: <1230102996.2303.1291616055@webmail.messagingengine.com> Message-ID: <1230106980.12156.1291620725@webmail.messagingengine.com> Hi Gabriel, Thank you very much for your feedback! > k1 = set(dict1.iterkeys()) I noticed you suggested .iterkeys() vs. .keys(). Is there any advantage to using an iterator vs. a list as the basis for creating a set? I understand that an iterator makes sense if you're working with a large set of items one at a time, but if you're creating a non-filtered collection, I don't see the advantage of using an iterator or a list. I'm sure I'm missing a subtle point here :) >> can this last step be done via a simple list comprehension? > Yes; but isn't a dict comprehension more adequate? > > [key: (dict1[key], dict2[key]) for key in common_keys if > dict1[key]!=dict2[key]} Cool!! I'm relatively new to Python and totally missed the ability to work with dictionary comprehensions. Yes, your dictionary comprehension technique is much better than the list comprehension approach I was struggling with. Your dictionary comprehension statement describes exactly what I wanted to write. Regards, Malcolm ----- Original message ----- From: "Gabriel Genellina" To: python-list at python.org Date: Wed, 24 Dec 2008 05:46:04 -0200 Subject: Re: Strategy for determing difference between 2 very large dictionaries En Wed, 24 Dec 2008 05:16:36 -0200, escribi?: > I'm looking for suggestions on the best ('Pythonic') way to > determine the difference between 2 very large dictionaries > containing simple key/value pairs. > By difference, I mean a list of keys that are present in the > first dictionary, but not the second. And vice versa. And a list > of keys in common between the 2 dictionaries whose values are > different. > The 2 strategies I'm considering are: > 1. Brute force: Iterate through first dictionary's keys and > determine which keys it has that are missing from the second > dictionary. If keys match, then verify that the 2 dictionaries > have identical values for the same key. Repeat this process for > the second dictionary. > 2. Use sets: Create sets from each dictionary's list of keys and > use Python's set methods to generate a list of keys present in > one dictionary but not the other (for both dictionaries) as well > as a set of keys the 2 dictionaries have in common. I cannot think of any advantage of the first approach - so I'd use sets. k1 = set(dict1.iterkeys()) k2 = set(dict2.iterkeys()) k1 - k2 # keys in dict1 not in dict2 k2 - k1 # keys in dict2 not in dict1 k1 & k2 # keys in both > Using the set > of keys in common, compare values across dictionaries to > determine which keys have different values (can this last step be > done via a simple list comprehension?) Yes; but isn't a dict comprehension more adequate? [key: (dict1[key], dict2[key]) for key in common_keys if dict1[key]!=dict2[key]} (where common_keys=k1&k2 as above) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list From jpablo.romero at gmail.com Tue Dec 16 18:48:13 2008 From: jpablo.romero at gmail.com (=?ISO-8859-1?Q?Juan_Pablo_Romero_M=E9ndez?=) Date: Tue, 16 Dec 2008 17:48:13 -0600 Subject: eval() and global variables Message-ID: Hello, Suppose this function is given: def f(x,y): return x+y+k Is it possible to somehow assign a value to k without resorting to making k global? I'm thinking something like this: eval("f(1,1)", {"f":f, "k":1}) Or even better, something like: def g(k): return f g(1)(1,1) ==> 3 Regards, Juan Pablo From rdcollum at gmail.com Mon Dec 29 16:01:33 2008 From: rdcollum at gmail.com (Roger) Date: Mon, 29 Dec 2008 13:01:33 -0800 (PST) Subject: tkInter constraining the width only References: Message-ID: <2d06d584-f398-4bf2-9452-bc2d915b1d17@k19g2000yqg.googlegroups.com> On Dec 29, 3:23?pm, akineko wrote: > Hello everyone, > > I'm writing a Tkinter program and trying to constraint the window > size. > I want to set the minimum of the width and the height and the maximum > of the width, but not the height. You want to set the max height to 0. I know this is counter- intuitive. Both values must be a number or None, not mixed. So to do what you want to do it would be this: some_window.wm_minsize(width=min_width, height=min_height) some_window.wm_maxsize(width=max_width, height=0) Note that these numbers are in pixels if you're using .pack() and according to the docs it's in grid coordinates if you're using .grid() Good luck! Roger. From timr at probo.com Tue Dec 16 02:23:02 2008 From: timr at probo.com (Tim Roberts) Date: Tue, 16 Dec 2008 07:23:02 GMT Subject: os.environ.get('SSH_ORIGINAL_COMMAND') returns None References: Message-ID: Tzury Bar Yochay wrote: > >added to ~/.ssh/authorized_keys the command="my_parder" parameter >which point to a python script file named 'my_parser' and located in / >usr/local/bin (file was chmoded as 777) > >in that script file '/usr/local/bin/my_parser' I got the following >lines: > >#!/usr/bin/env python >import os >print os.environ.get('SSH_ORIGINAL_COMMAND', None) > >When trying to ssh e.g. 'ssh localhost' >I get None on the terminal and then the connection is closed. > >I wonder if anyone have done such or alike in the past and can help me >with this. >Is there anything I should do in my python file in order to get that >environment variable? The SSH_ORIGINAL_COMMAND variable is set to the command that was passed in on the ssh command line. Since you are not specifying a command, you aren't going to find anything in that variable. Try this: ssh localhost 'ls -l' -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From kyosohma at gmail.com Tue Dec 23 12:12:11 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 23 Dec 2008 09:12:11 -0800 (PST) Subject: wxPython.button.disabled still catching clicks References: <8cb6da6a-7df4-4cce-a28e-385448a25b26@w39g2000prb.googlegroups.com> <1ff2aad7-29a1-48cd-b3de-29fab443aa3e@u18g2000pro.googlegroups.com> <0e9a5ab7-8078-4d12-adb2-aaf92a78b007@s9g2000prm.googlegroups.com> Message-ID: On Dec 23, 7:27?am, mynthon wrote: > On Dec 23, 11:58?am, Aaron Brady wrote: > > > > > On Dec 23, 4:50?am, mynthon wrote: > > > > Hello! (sorry for my english) > > > > I have a problem with buttons in wxPython. When button is disabled > > > (by .Disable() or .Enable(False)) it is grayed out but still receive > > > clicks. > > > > Eg. i have button that disable itself, runs long action and enable > > > itself: > > > > def onClick(self, evt): > > > ? ? self.btn.Enable(False) > > > ? ? for i in range (1000): > > > ? ? ? ? print i > > > ? ? self.btn.Enable(True) > > > > when for loop is running button is greyed out and when i click on it > > > nothing happens but when loop ends another one is started because > > > button "remebered" thad i click on it when was diabled. My only idea > > > is to reposition button outside frame instead of disabling it but this > > > solution is...not good. > > > > thanks for any help. Ive searched groups, google and it looks that > > > only i have this problem :) > > > No, it is very common. ?During your for loop, the loop is dominating > > the process completely. ?Events are just building up in the app's > > message queue, and don't get handled until after you yield on control. > > > If you need to run a long task, look into threading, the OnIdle > > method, the 'multiprocessing' module, or pump messages during your > > long task. > > ok, maybe someone will need it. I dont know how it works because i > didnt have time to read docs and i cannot explain everything. I used > google and wxPython demo (in tree: wxpython overview / process and > events / process) > > class leftPanel(wx.Panel): > ? ? def __init__(self, parent, id): > ? ? ? ? wx.Panel.__init__(self, parent, id, style=wx.BORDER_SUNKEN) > > ? ? ? ? # here you have to define new process, IDLE event, and > onPRocessEnd event > ? ? ? ? self.process = None > ? ? ? ? self.GetParent().Bind(wx.EVT_IDLE, self.onIdle) > ? ? ? ? self.Bind(wx.EVT_END_PROCESS, self.onProcessEnd) > > ? ? ? ? # create button and bind event to it > ? ? ? ? self.runScriptBtn = wx.Button(self, -1, 'RUN ME!', (10,220)) > ? ? ? ? self.runScriptBtn.Bind(wx.EVT_BUTTON, self.onClick, > self.runScriptBtn) > > ? ? def onClick(self, evt): > ? ? ? ? # disable button > ? ? ? ? self.runScriptBtn.Enable(False) > > ? ? ? ? # here you have to enter command to run > ? ? ? ? # previusly i heve here exec('python myScript.py') > ? ? ? ? # but now it will be a subprocess > ? ? ? ? cmd = 'python xxx1.py' > > ? ? ? ? #create new process > ? ? ? ? self.process = wx.Process(self) > > ? ? ? ? # dont know what it is for > ? ? ? ? self.process.Redirect() > > ? ? ? ? # execute cmd command > ? ? ? ? pid = wx.Execute(cmd, wx.EXEC_ASYNC, self.process) > > ? ? def onIdle(self, evt): > ? ? ? ? # beacuse this method is called only when app enters idle mode > ? ? ? ? # the line below is nedded to "simulate" entering idle mode > ? ? ? ? # dont know how it works but it works > ? ? ? ? evt.RequestMore(True) > > ? ? ? ? # here is some code to catch subprocess output > ? ? ? ? if self.process is not None: > ? ? ? ? ? ? stream = self.process.GetInputStream() > ? ? ? ? ? ? if stream.CanRead(): > ? ? ? ? ? ? ? ? text = stream.read() > ? ? ? ? ? ? ? ? print text > > ? ? def onProcessEnd(self, evt): > ? ? ? ? # here is some code to catch subprocess output > ? ? ? ? # when it is destroyed > ? ? ? ? stream = self.process.GetInputStream() > ? ? ? ? if stream.CanRead(): > ? ? ? ? ? ? text = stream.read() > ? ? ? ? ? ? print text > > ? ? ? ? # dont know it is necessary > ? ? ? ? self.process.CloseOutput() > > ? ? ? ? # remove (clear) process object > ? ? ? ? self.process.Destroy() > ? ? ? ? self.process = None > > ? ? ? ? # show button again > ? ? ? ? self.runScriptBtn.Enable() I'm pretty sure there's a better way to do this. If you disable the button and click on it, you'll notice that it isn't firing events, so something else is going on here. It seems like the wx.Frame or wx.Application is queuing the mouse button clicks or something. I would post to the wxPython mailing list: http://wxpython.org/maillist.php They'll be better able to address this and they'll probably have a simpler solution too. Mike From deets at nospam.web.de Mon Dec 8 16:49:57 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 Dec 2008 22:49:57 +0100 Subject: Public imports In-Reply-To: <66ecdd96-38dd-4054-8009-e145c0a78316@o40g2000prn.googlegroups.com> References: <9623b0a3-7053-41f1-b116-0cd5e54f39e9@v13g2000vbb.googlegroups.com> <493d1ec0$0$32048$426a34cc@news.free.fr> <66ecdd96-38dd-4054-8009-e145c0a78316@o40g2000prn.googlegroups.com> Message-ID: <6q5j45Faq0g7U2@mid.uni-berlin.de> M?rcio Faustino schrieb: > So, no chance of doing this: > > # "A.py" > from __future__ import division, with_statement > > # "B.py" > from A import * > print 1 / 2 > > ...and printing 0.5, right? Too bad :) Au contraire - *very* good. If it were otherwise, what would happen to code that _relies_ on / returning an int - some 3rd-party-lib for example? The same goes for code that contains "with" as variable name or some such. Diez From bearophileHUGS at lycos.com Fri Dec 19 12:55:01 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 19 Dec 2008 09:55:01 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> r: > I always thought of Python as an intuitive way to write C code.< C is a very low level language, not far from assembly, and often it's not intuitive at all. C string formatting is short and a flexible enough, but it's out of place in a language as high level as Python3. The new syntax allows more flexibility, and it's better for most people that don't know C already, like newbies, etc. ------------------ walterbyrd: >It seems to me that 3.0 is changing a lot of non-problems. And it's going to be slower to boot.< They are non-problems for people that already know lot of Python (and some C). But for all the other people, especially newbies, it's better in most things. Most language designers (and generally people very used a certain language) become so accustomed to their language that they most of the times become like "blind" to the defects and warts of their language (I have said this four years ago too, when I have started learning Python, listing many problems in Python, and among them there were C string formatting too). So I think it was a feat for the Python developers to see many characteristics of the Python2.x as what they are: warts, bugs, etc, and fix them (and most of the times their newer designs are "the right thing" with just few exceptions, I have counted only 3 of them, and they are small). They have gained even more of my respect. Regarding the speed of Python3 programs, they will go faster because people will be forced to use things like lazy ranges, lazy map and filter, lazy keys and values, and the "key" of sort/sorted. All those things can be used in Python2.x too, but lot of people aren't expert enough (or they are just lazy) and don't use them, so the average Python3 program will probably be faster (and use less memory) thanks to them. Python3 programs will go slower because they use 2-byte long Unicode strings by default (it can be compiled for 4-byte Unicode too, and I think this has to become the default, eventually, because I think it will become silly to save few bytes for strings when you will have 8-16-32+ GB of RAM), and they use multi-precision integers only. Such strings and numbers allow to reduce some troubles, even "bugs", etc. At the moment Python3 isn't much optimized for speed, you can think of it an experimental release still. I/O and multiprecision integers will probably be speed up (and some form of transparent on-the-fly compression or smart representation can in most times halve the memory used by Py3 strings, putting the performance almost back to the Py2.x one. In computer science there are LOT of tricks that can be used if you have the brain and time to invent and implement them. You can see that for example in how Psyco manages internally string/list/tuple slices). Anyway, CPUs and computers are now much faster than the CPUs present when Python was created. And Python is first of all designed for the programmer and not for the CPU. So I think it's right to make Python3 become a little higher level language even if this slows it down a little. For the kind of programs Python is often used for, I think this is a Win. (Ruby programs are often slower than Python ones (because Ruby is a little higher level than Python) but it's very useful anyway). If Python will continue to develop in the following years (think about a Python4000) then I think it may become good to make it become even more slower, if this will help make it a little more higher level still. Bye, bearophile From arnodel at googlemail.com Tue Dec 23 03:54:41 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 23 Dec 2008 08:54:41 +0000 Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: skip at pobox.com writes: > If you look back at the Tour de France results from the 80's I > believe Greg Lemond won it one year without ever winning a stage. Well I think it was actually in 1990, his last win sadly. -- Arnaud From exarkun at divmod.com Tue Dec 30 15:22:07 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 30 Dec 2008 15:22:07 -0500 Subject: Triple quoted string in exec function ? In-Reply-To: <495A81A7.8030507@gmail.com> Message-ID: <20081230202207.20272.1714261156.divmod.quotient.29322@ohm> On Tue, 30 Dec 2008 21:16:39 +0100, Stef Mientki wrote: >ibpet11 at gmail.com wrote: >>On Dec 30, 2:48 pm, Steve Holden wrote: >> >>>Stef Mientki wrote: >>> >>>>hello, >>>> I'm running scripts, with the execute function (Python 2.5), >>>>and it seems that triple quoted strings are not allowed. >>>> Is there a workaround, >>>>or is this a fundamental problem of the exec-function ? >>>> >>>If you think about it, it should be obvious that you can't surround a >>>string to be compiled with any of the quotes that appear inside the >>>string to be compiled. That's about the only limitation I am aware of. >>> >>>And, by the way, exec is a *statement*, not a function! >>> > exec ( Init_Code, PG.P_Globals ) > >I've really doubt that this is a statement, >unless I don't understand what a statement is. What do you think a statement is? According to the Python grammar, exec is this: exec_stmt: 'exec' expr ['in' test [',' test]] "stmt" is short for "statement". :) A more satisfying demonstration of the statementness of exec is this, though: >>> x = exec "foo" File "", line 1 x = exec "foo" ^ SyntaxError: invalid syntax >>> And no, putting parenthesis around the expression given to exec doesn't make a difference: >>> x = exec("foo") File "", line 1 x = exec("foo") ^ SyntaxError: invalid syntax >>> Jean-Paul From george.sakkis at gmail.com Thu Dec 4 14:19:53 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 4 Dec 2008 11:19:53 -0800 (PST) Subject: Python 3 read() function References: Message-ID: On Dec 4, 2:01?pm, ?????? ??????????? wrote: > > I don't think it matters. ?Here's a quick comparison between 2.5 and > > 3.0 on a relatively small 17 meg file: > > > C:\>c:\Python30\python -m timeit -n 1 > > "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" > > 1 loops, best of 3: 36.8 sec per loop > > > C:\>c:\Python25\python -m timeit -n 1 > > "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" > > 1 loops, best of 3: 33 msec per loop > > > That's 3 orders of magnitude slower on python3.0! > > Isn't this because you have the file cached in memory on the second run? That's probably it; I see much more modest slowdown (2-3X) if I repeat many times each run. George From fakeaddress at nowhere.org Tue Dec 2 21:16:13 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 02 Dec 2008 18:16:13 -0800 Subject: Reverse zip() ? In-Reply-To: References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> Message-ID: John Machin wrote: > Here's a version that makes it slightly easier to comprehend: > > Q: I know how to zip sequences together: > | >>> a = (1, 2, 3) > | >>> b = (4, 5, 6) > | >>> z = zip(a, b) > | >>> z > | [(1, 4), (2, 5), (3, 6)] > but how do I reverse the process? > > A: Use zip()! > | >>> a2, b2 = zip(*z) > | >>> a2 > | (1, 2, 3) > | >>> b2 > | (4, 5, 6) zip as its own inverse might be even easier to comprehend if we call zip by its more traditional name, "transpose". -- --Bryan From cma at mail.bnu.edu.cn Thu Dec 4 04:39:15 2008 From: cma at mail.bnu.edu.cn (Cong Ma) Date: Thu, 04 Dec 2008 17:39:15 +0800 Subject: Don't you just love writing this sort of thing :) In-Reply-To: References: Message-ID: Lawrence D'Oliveiro wrote: > for \ > Entry \ > in \ > sorted \ > ( > f for f in os.listdir(PatchesDir) if PatchDatePat.search(f) != None > ) \ > : > Patch = (open, gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir, Entry), "r") > ... read from Patch ... > Patch.close() > #end for > > -- > http://mail.python.org/mailman/listinfo/python-list > The "if ... != None" is not necessary... "if PatchDatePat.search(f)" is OK. And I don't like it... From jstroud at mbi.ucla.edu Thu Dec 4 03:59:00 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 04 Dec 2008 00:59:00 -0800 Subject: How can I do this (from Perl) in Python? (closures) In-Reply-To: <68b8294c-8771-4b02-bd46-2f25f5e01602@j35g2000yqh.googlegroups.com> References: <68b8294c-8771-4b02-bd46-2f25f5e01602@j35g2000yqh.googlegroups.com> Message-ID: excord80 at gmail.com wrote: > from_ten = make_counter(10) > from_three = make_counter(3) > > print from_ten() # 10 > print from_ten() # 11 > print from_three() # 3 > print from_ten() # 12 > print from_three() # 4 > #################### > > The error message is: "UnboundLocalError: local variable 'start' > referenced before assignment". The same thing happens if I omit start > and just use start_num directly. > > How can I do it in Python? Since no one has suggested it: class make_counter(object): def __init__(self, i): self.i = i def __call__(self): i = self.i self.i += 1 return i James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From rdmurray at bitdance.com Tue Dec 9 22:05:40 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Tue, 9 Dec 2008 22:05:40 -0500 (EST) Subject: Text parsing via regex In-Reply-To: References: Message-ID: On Mon, 8 Dec 2008 at 16:51, Robert Kern wrote: > Robocop wrote: >> Wow! Thanks for all the input, it looks like that textwrapper will >> work great for my needs. And thanks for the regex help everyone. >> Also, i was thinking of using a list, but i haven't used them much in >> python. Is there anything in python that is equivalent to pushback in >> c++ for vectors? > > list.append() Fun with lists: >>> l = list() >>> l.append('a') >>> l ['a'] >>> l.extend(['b', 'c']) >>> l ['a', 'b', 'c'] >>> l[1:] = [1, 2, 3] >>> l ['a', 1, 2, 3] >>> l.pop() 3 >>> l ['a', 1, 2] >>> l[:0] = ['z'] >>> l ['z', 'a', 1, 2] --RDM From google at mrabarnett.plus.com Tue Dec 16 12:50:15 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 16 Dec 2008 17:50:15 +0000 Subject: help I'm getting delimited In-Reply-To: <1229445534.5328.0.camel@linux-3eb6.site> References: <1229445534.5328.0.camel@linux-3eb6.site> Message-ID: <4947EA57.9060509@mrabarnett.plus.com> Paul Watson wrote: > On Tue, 2008-12-16 at 08:26 -0800, aka wrote: >> Hi, I'm going nuts over the csv.reader and UnicodeReader class. >> Somehow I can't get this method working which is supposed to read a >> csv file which name is inputted but here now hardcoded. What I need >> for now is that the string version of the list is put out for control. >> Later on I will only need to read the first column (id) of the csv >> file to be able to fill in a session var with a list of all ids. >> inp = c:/temp/test.csv >> roles = [] >> try: >> fp = open(inp, 'rb') >> reader = csv.reader(fp) >> for r in reader: >> rollen.append(r) >> except: >> msg = "Er is iets mis met de UnicodeReader" >> >> return dict(file=in,roles=str(roles)) >> Any help greatly appreciated! >> Cheers > > Did you intend inside the loop to write: > > roles.append(r) > Also, the bare "except" will catch _all_ exceptions. You should catch only those you expect. In this case, it's catching your use of "rollen" instead of "roles" (probably unintentional) and then complaining about UnicodeReader, even though that's (probably, again!) not the problem. From jaume.bonet at gmail.com Tue Dec 16 14:04:01 2008 From: jaume.bonet at gmail.com (Jaume Bonet) Date: Tue, 16 Dec 2008 11:04:01 -0800 (PST) Subject: Memory leak when using a C++ module for Python References: <13db1224-5d6d-4240-8184-ce852e10b422@d36g2000prf.googlegroups.com> Message-ID: <15733cb7-c520-40d7-bacd-3f4e18d5fe3c@u18g2000pro.googlegroups.com> When I tried the C++ function with a C++ main() (skipping the Python part) it didn't show any memory problem, but I'll re-check it anyway, thanks... On Dec 16, 9:16?am, "Gabriel Genellina" wrote: > En Thu, 11 Dec 2008 15:35:58 -0200, Jaume Bonet ? > escribi?: > > > This is the function that is visible from python and the one that the > > python code calls: > > > static PyObject * IMFind (PyObject *self, PyObject *args, PyObject > > *kwargs) { > > Your function does not call any Python function except ? > PyArg_ParseTupleAndKeywords (which does not modify reference counts). > So it's unlikely that this could cause any memory leak. I'd revise how ? > memory is allocated and deallocated on the C++ side. > > -- > Gabriel Genellina From castironpi at gmail.com Tue Dec 23 11:57:14 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 23 Dec 2008 08:57:14 -0800 (PST) Subject: On Whose Desktop References: <4950db7e$0$14770$426a74cc@news.free.fr> Message-ID: <89ca6cc9-fa26-42c9-be67-35aad569500b@i18g2000prf.googlegroups.com> On Dec 23, 8:19?am, Steve Holden wrote: > Fuzzyman wrote: > > On Dec 23, 12:06 pm, Steve Holden wrote: > >> Thanks to Barry Warsaw the "On Your Desktop" blog now has a new entry: > > >> ?http://onyourdesktop.blogspot.com/ > > >> Who would you like to see profiled next? > > > Guido (of course), Brett Cannon, Martin v Loewis, Jim Hugunin, Ted > > Leung, Dino Viehland (core developer of IronPython), Titus Brown, Ivan > > Kristic, Mark Shuttleworth, Tim Golden, Michele Simionato, Thomas > > Heller, Greg Ewing - any and all of these would be great. > > > Any women in Python you could ask - how about Anna Ravenscroft? > > Bruno Desthuilliers wrote: > > > The effbot ? > > s... at pobox.com wrote: > > Maybe Martin v. Loewis? ?He contributes so much to Python. ?I met him once > > several years ago at a Python conference (or maybe it was still just a > > workshop then), but beyond seeing his titanic contributions to Python, I > > know little about the guy. > > I hope *everyone* knows that Martin was the winner of this year's Frank > Willison Award: > > http://www.python.org/community/awards/frank-willison/#martin-von-l-w... > > Great! Keep the suggestions coming, please! +1 whose (posessive) From bearophileHUGS at lycos.com Mon Dec 15 18:24:13 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 15 Dec 2008 15:24:13 -0800 (PST) Subject: tricky nested list unpacking problem References: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> Message-ID: Arnaud Delobelle: > Here is a not thought out solution: >... I was waiting to answer because so far I have found a bad-looking solution only. Seeing there's only your solution, I show mine too. It seems similar to your one. def xflatten(seq): if isinstance(seq, list): stack = [iter(seq)] while stack: for item in stack[-1]: if isinstance(item, list): stack.append(iter(item)) break yield item else: stack.pop() else: yield seq def product(pools): if isinstance(pools, list): result = [[]] for pool in pools: if isinstance(pool, list): result = [x+[y] for x in result for y in xflatten(list (product(pool)))] else: result = [x+[pool] for x in result] for prod in result: yield prod else: yield pools s1 = [1,[2, 3, 4], 5,[6, 7]] s2 = [1,[2, [3, 4]], 5,[6,7],8,[9]] s3 = [1,2,3,[4,5,[6, 7]],8,[9,[10, 11, 12, 13, 14]]] def stringify(seq): for el in product(seq): yield "0-" + "-".join(map(str, el)) for seq in [s1, s2, s3]: for txt in stringify(seq): print txt print It's ugly, I agree. No much tested. *surely* there are shorter and much nicer solutions. It reminds me the exercises of the "Little Schemer" :-) Bye, bearophile From ndbecker2 at gmail.com Sat Dec 13 23:05:03 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Sat, 13 Dec 2008 23:05:03 -0500 Subject: subprocess to pipe through several processes? Message-ID: How would I use suprocess to do the equivalent of: cat - | program_a | program_b From fakeaddress at nowhere.org Mon Dec 22 22:50:40 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 22 Dec 2008 19:50:40 -0800 Subject: Twisted for non-networking applications In-Reply-To: <82e49b84-43c9-452f-a139-c77378c12908@a12g2000pro.googlegroups.com> References: <82e49b84-43c9-452f-a139-c77378c12908@a12g2000pro.googlegroups.com> Message-ID: Kottiyath wrote: > Is it a good idea to use Twisted inside my application, even though > it has no networking part in it? > Basically, my application needs lots of parallel processing - but I > am rather averse to using threads - With or without threads, the Python interpreter does not do parallel processing. You could use multiple processes, or a thread could call an extension module that releases Python's global interpreter lock, but Python itself does not offer parallel processing. > due to myraid issues it can cause. > So, I was hoping to use a reactor pattern to avoid the threads. The reactor pattern describes event-driven I/0, not parallel processing. -- --Bryan From nad at acm.org Fri Dec 5 14:46:47 2008 From: nad at acm.org (Ned Deily) Date: Fri, 05 Dec 2008 11:46:47 -0800 Subject: pytz and timezone specialists References: <1f6172c1-4f70-42ea-8010-b72beb0af487@w24g2000prd.googlegroups.com> Message-ID: In article <1f6172c1-4f70-42ea-8010-b72beb0af487 at w24g2000prd.googlegroups.com>, manatlan wrote: > Here is a really simple code : > ------------------------------------------------------- > from datetime import datetime > from pytz import timezone > > tz=timezone("Europe/Paris") > > d=datetime(2008,12,12,19,00,00,tzinfo=tz) > print d.isoformat() > > d=datetime.now(tz) > print d.isoformat() > ------------------------------------------------------- > when I run it, it displays (according current time ;-): > > 2008-12-12T19:00:00+00:09 > 2008-12-05T19:15:38.135467+01:00 > > The Europe/Paris timezone is GMT+1 ... the second date seems to be > right (+01:00 at the end) > > But why the first date ends with "+00:09" ?!? it should be +01:00 ... > no ?! > Where's the bug ?!? (sure : it's me ;-) ... but i don't understand > this simple thing) >>> tz = timezone("Europe/Paris") >>> d = tz.localize(datetime(2008,12,12,19,00,00)) >>> print d.isoformat() 2008-12-12T19:00:00+01:00 "This library only supports two ways of building a localized time. The first is to use the .localize() method provided by the pytz library. This is used to localize a naive datetime (datetime with no timezone information). ... Unfortunately using the tzinfo argument of the standard datetime constructors ''does not work'' with pytz for many timezones." -- Ned Deily, nad at acm.org From tjreedy at udel.edu Tue Dec 23 17:07:16 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Dec 2008 17:07:16 -0500 Subject: 2to3 used in the Shootout In-Reply-To: <4f1a8f03-fd7f-49ea-8031-61f73fb0c0e8@x16g2000prn.googlegroups.com> References: <4f1a8f03-fd7f-49ea-8031-61f73fb0c0e8@x16g2000prn.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > They have translated the Python benchmarks of the Shootout site from > Py2 to Py3 using 2to3: > > http://shootout.alioth.debian.org/u32/benchmark.php?test=all&lang=python3 > > It shows some "performance bugs" of Python3 itself (especially > regarding the binary-trees benchmark, that was unexpected by me), and > two points where 2to3 may be improved, for example after the > translation this gives error: > table=string.maketrans('ACBDGHK\nMNSRUTWVYacbdghkmnsrutwvy', > 'TGVHCDM > \nKNSYAAWBRTGVHCDMKNSYAAWBR')): > > Gives: > TypeError: maketrans arguments must be bytes objects Perhaps you could file a tracker item. From cadmuxe at gmail.com Tue Dec 9 03:05:58 2008 From: cadmuxe at gmail.com (cadmuxe) Date: Tue, 9 Dec 2008 00:05:58 -0800 (PST) Subject: Password input in console/terminal References: Message-ID: <36579eb6-df1e-4ab7-86b0-dde3f0235080@p2g2000prf.googlegroups.com> On 12?9?, ??2?01?, "Chris Rebert" wrote: > On Mon, Dec 8, 2008 at 9:53 PM, RP wrote: > > Hello All, > > > This is my first REAL post(question) to Python-List. I know I can take input > > from a user with raw_input() > > How do I take password input in console? Any Help would be Greatly > > Appreciated. Thank You. RP > > You use the appropriately-named `getpass` module:http://docs.python.org/library/getpass.html > > Cheers, > Chris > > -- > Follow the path of the Iguana...http://rebertia.com you can use getpass() import getpass passwd = getpass.getpass() ------- >>> import getpass >>> passwd = getpass.getpass() Password: From mirandasnailvv at gmail.com Fri Dec 19 19:42:02 2008 From: mirandasnailvv at gmail.com (mirandasnailvv at gmail.com) Date: Fri, 19 Dec 2008 16:42:02 -0800 (PST) Subject: tickling handjob video torrent - Free Message-ID: tickling handjob video torrent . . . *******CLICK HERE******** http://club247.cn/tickling-handjob-video-torrent ***************************** . . . . . . . . . . . . tickling handjob video torrent From xi at gamma.dn.ua Tue Dec 30 17:03:16 2008 From: xi at gamma.dn.ua (Kirill Simonov) Date: Wed, 31 Dec 2008 00:03:16 +0200 Subject: [ANN] PyYAML-3.08: Now with Python 3 support Message-ID: <495A9AA4.4050406@gamma.dn.ua> ======================== Announcing PyYAML-3.08 ======================== A new release of PyYAML is now available: http://pyyaml.org/wiki/PyYAML This release features complete support for Python 3. For compatibility notes between Python 2 and Python 3 versions, please see http://pyyaml.org/wiki/PyYAMLDocumentation#Python3support Changes ======= * Python 3 support (Thank to Erick Tryzelaar). * Use Cython instead of Pyrex to build LibYAML bindings. Note that the source package is distributed with a pre-generated '_yaml.c' file so you don't need Cython installed to build LibYAML bindings. * Refactored support for unicode and byte input/output streams. Resources ========= PyYAML homepage: http://pyyaml.org/wiki/PyYAML PyYAML documentation: http://pyyaml.org/wiki/PyYAMLDocumentation TAR.GZ package: http://pyyaml.org/download/pyyaml/PyYAML-3.08.tar.gz ZIP package: http://pyyaml.org/download/pyyaml/PyYAML-3.08.zip Windows installers: http://pyyaml.org/download/pyyaml/PyYAML-3.08.win32-py2.3.exe http://pyyaml.org/download/pyyaml/PyYAML-3.08.win32-py2.4.exe http://pyyaml.org/download/pyyaml/PyYAML-3.08.win32-py2.5.exe http://pyyaml.org/download/pyyaml/PyYAML-3.08.win32-py2.6.exe http://pyyaml.org/download/pyyaml/PyYAML-3.08.win32-py3.0.exe PyYAML SVN repository: http://svn.pyyaml.org/pyyaml Submit a bug report: http://pyyaml.org/newticket?component=pyyaml YAML homepage: http://yaml.org/ YAML-core mailing list: http://lists.sourceforge.net/lists/listinfo/yaml-core About PyYAML ============ YAML is a data serialization format designed for human readability and interaction with scripting languages. PyYAML is a YAML parser and emitter for Python. PyYAML features a complete YAML 1.1 parser, Unicode support, pickle support, capable extension API, and sensible error messages. PyYAML supports standard YAML tags and provides Python-specific tags that allow to represent an arbitrary Python object. PyYAML is applicable for a broad range of tasks from complex configuration files to object serialization and persistance. Example ======= >>> import yaml >>> yaml.load(""" ... name: PyYAML ... description: YAML parser and emitter for Python ... homepage: http://pyyaml.org/wiki/PyYAML ... keywords: [YAML, serialization, configuration, persistance, pickle] ... """) {'keywords': ['YAML', 'serialization', 'configuration', 'persistance', 'pickle'], 'homepage': 'http://pyyaml.org/wiki/PyYAML', 'description': 'YAML parser and emitter for Python', 'name': 'PyYAML'} >>> print yaml.dump(_) name: PyYAML homepage: http://pyyaml.org/wiki/PyYAML description: YAML parser and emitter for Python keywords: [YAML, serialization, configuration, persistance, pickle] Copyright ========= The PyYAML module is written by Kirill Simonov . PyYAML is released under the MIT license. From mal at egenix.com Wed Dec 10 14:44:45 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 10 Dec 2008 20:44:45 +0100 Subject: Rich Comparisons Gotcha In-Reply-To: <200812101401.35786.kyrie@uh.cu> References: <1228923619.493fe2e3c3073@comuh.uh.cu> <493FE561.6030007@egenix.com> <200812101401.35786.kyrie@uh.cu> Message-ID: <49401C2D.4050209@egenix.com> On 2008-12-10 20:01, Luis Zarrabeitia wrote: > On Wednesday 10 December 2008 10:50:57 am M.-A. Lemburg wrote: >> On 2008-12-10 16:40, Luis Zarrabeitia wrote: >>> Quoting Rasmus Fogh : >>>> Rhamphoryncus wrote: >> Rich comparisons were added to Python at the request of the >> Numeric (now numpy) developers and they have been part of Python >> a Numeric for many many years. >> >> I don't think it's likely they'll change things back to the days >> of Python 1.5.2 ;-) > > Please define "rich comparisons" for me. It seems that I do not understand the > term - I was thinking it meant the ability to override the comparison > operators, and specially, the ability to override them independently. That's one of the features, rich comparisons added. Another is the ability to return arbitrary objects instead of just booleans or integers: http://www.python.org/dev/peps/pep-0207/ David was a Numeric developer at the time (among other things). > Even in statically typed languages, when you override the equality > operator/function you can choose not to return a valid answer (raise an > exception). And it would break all the cases mentioned above (element in > list, etc). But that isn't the right thing to do. The language doesn't/can't > prohibit you from breaking the equality test, but that shouldn't be > considered a feature. (a==b).all() makes no sense. Perhaps not in your application, but it does make sense in other numeric applications, e.g. ones that work on vectors or matrixes. I'd suggest you simply wrap the comparison in a function and then have that apply the necessary conversion to a boolean. >>> Even the transition itself could be done without breaking much code... >>> Make the == op return an object that wraps the array of bools (instead of >>> the array itself), give it the any() and all() methods, and make >>> __nonzero__/__bool__ equivalent to all(). >> That would cause a lot of confusion on its own, since such an >> object wouldn't behave in the same way as say a regular Python >> list (bool([0]) == True). > > I'm certain that something could be worked out. A quick paragraph that took me > just a few minutes to type shouldn't be construed as a PEP that will solve > all the problems :D. As always: the Devil is in the details :-) -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 10 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-12-02: Released mxODBC.Connect 1.0.0 http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From james at agentultra.com Thu Dec 4 10:21:28 2008 From: james at agentultra.com (J Kenneth King) Date: Thu, 04 Dec 2008 10:21:28 -0500 Subject: RELEASED Python 3.0 final References: Message-ID: <85tz9k3r0n.fsf@dozer.localdomain> Barry Warsaw writes: > On behalf of the Python development team and the Python community, I > am happy to announce the release of Python 3.0 final. Yay! Thanks for all the great work. From ronen.agranat at gmail.com Sun Dec 14 05:32:41 2008 From: ronen.agranat at gmail.com (Rohannes) Date: Sun, 14 Dec 2008 02:32:41 -0800 (PST) Subject: 1 or 1/0 doesn't raise an exception References: <49446E39.6020807@tim.thechases.com> Message-ID: <6e2d11cd-a57e-4cd4-9cd7-a65eb08f220e@u18g2000pro.googlegroups.com> 'Dive into Python' has a very memorable and interesting section on the exact behaviour of 'and' and 'or' in Python: http://diveintopython.org/power_of_introspection/and_or.html > No: &, | (and ^, too) perform bitwise operations in Python, C and Java: "In complete evaluation ... both expressions are always evaluated. To obtain complete evaluation in Java, you use & rather than && ... and use | in place of ||" - Walter Savitch, Absolute Java 2nd ed. Although & IS the bitwise-AND operator in Java: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html I guess it's a matter of context. From thatiparthysreenivas at gmail.com Tue Dec 30 07:21:28 2008 From: thatiparthysreenivas at gmail.com (Sreenivas) Date: Tue, 30 Dec 2008 04:21:28 -0800 (PST) Subject: using def in pythons References: <235ffe4b-9f36-4d41-bee8-24cb4a69728d@q30g2000prq.googlegroups.com> Message-ID: On Dec 30, 3:37?pm, ibpe... at gmail.com wrote: > hi, > > i want to have a broad knowledge on the use of "def" in python as i > know i might need it > to my string handling and for a lot of things in general. > > I will really appreciate anybody who can support my mission of > becoming a python Programmer > as per constant chatting and support or manuals to read. > > thanks go through this link http://www.python.org/doc/2.5.1/ref/function.html From lie.1296 at gmail.com Wed Dec 10 09:45:26 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 10 Dec 2008 14:45:26 +0000 (UTC) Subject: Is 3.0 worth breaking backward compatibility? References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> Message-ID: On Tue, 09 Dec 2008 17:25:59 -0500, Benjamin Kaplan wrote: > On Tue, Dec 9, 2008 at 3:56 PM, Lie Ryan wrote: > >> On Sun, 07 Dec 2008 21:48:46 +0000, Tim Rowe wrote: >> >> > >> > But that's what a major release number does for you. Modula2 was >> > quite a break from Modula. Think of Python3.0 it as a new language, >> > if you like, that's inspired by Python2. You can stay with Python2 or >> > you can adopt the new language. That way you won't have to think of >> > it in terms of breaking any sort of backwards compatibility because >> > there is no backwards ;-) >> > >> > -- >> > Tim Rowe >> >> Actually I noticed a tendency from open-source projects to have slow >> increment of version number, while proprietary projects usually have >> big version numbers. >> >> Linux 2.x: 1991 Python 3.x.x: 1991. Apache 2.0: 1995. OpenOffice.org >> 3.0: acquired by Sun at 1999. GIMP 2.x: 1995. Wine 1.x: 1993. >> >> > Wine actually timed the 1.0 release to be at about t the 15th "birthday" > of the project. 15 years is a very long time to get to version 1.0, many other (usually commercial or commercial-oriented front of a software) software release version 1.0 after 2-3 years of development, often shorter. wine has been used by a lot of people, not only a few internal developers and beta testers. > >> Compare with >> Windows: NT 3.1-NT 6.x: 1993. Visual Studio 97, 6.0, .NET, .NET 2003, >> .NET 2005, 2008: 1997. Photoshop (11 versions to CS4): 1987. Microsoft >> Office 3, 4, 95, 97, 2000, XP, 2003, 2007: 1990. Flash MX, 9, CS 1-4. >> iTunes 8: 2001. RealPlayer 4-11: 1995. Macintosh 1.0-9: 1984-2001, X.5: >> 2001. Winzip 12.0: early 1990s. >> >> > Just to note: Office 2007 is also known as Office 12, if you want to > look at version numbers. Also, Mac OS hasn't increased the major version > number past 10 since they switched from their own proprietary kernel to > using the open-source Darwin. > > > >> Interestingly, many linux _distro_ also inhibit this quick version >> number change. Fedora 10, Ubuntu is 2 years old, version 8 (they start >> from version 6 not 1). >> >> > That's because 8 isn't the verison number- it's the year the version was > released (8.10 is October 2008, not the 10th update to version 8). I know about that, but in my definition (and Wikipedia's), it is still the version number (maybe I forget to put a footnote). My point is that commercial software and commercial front of a free software (linux distros, Cedega 6.1) prefers having big version numbers. From collin.day.0 at gmail.com Thu Dec 18 15:13:46 2008 From: collin.day.0 at gmail.com (Collin D) Date: Thu, 18 Dec 2008 12:13:46 -0800 (PST) Subject: Factoring Polynomials References: <5dfe1cf3-530d-4e31-833e-e26db85611be@d36g2000prf.googlegroups.com> Message-ID: <0459f66d-fb43-4c42-a0d2-926b4b04fa06@z6g2000pre.googlegroups.com> On Dec 18, 11:52?am, eric wrote: > On Dec 18, 8:37?pm, collin.da... at gmail.com wrote: > > > I am trying to write a simple application to factor polynomials. I > > wrote (simple) raw_input lines to collect the a, b, and c values from > > the user, but I dont know how to implement the quadratic equation > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > into python. Any ideas? > > with numpy: > from numpy import * > > s=[1,-1] > x = -b+s*sqrt( b**2-4*a*c )/(2*a) > > Erichttp://codeslash.blogspot.com Ahh. Great.. thank you. I didnt know about the sqrt function.. saves me from doing "^1/2". Thanks again. -CD From rileyrgdev at gmail.com Mon Dec 22 11:33:34 2008 From: rileyrgdev at gmail.com (Richard Riley) Date: Mon, 22 Dec 2008 17:33:34 +0100 Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: Marco Mariani writes: > walterbyrd wrote: > >> I have read that python is the world's 3rd most popular language, and >> that python has surpassed perl in popularity, but I am not seeing it. > > > In 20 days, you've gone from trying to import a module by using: > >> load "test.py" > > > to questioning the popularity of python. > > You have many other subject you want to enlighten us about, I suppose? > Cause I wonder what you'll come up with, next. > One does not have to by a language maestro to try and assess its popularity. While his numbers or his reading of the numbers might be open to some questions, to suggest that one needs to be totally familiar with a language to determine its popularity is, frankly, ridiculous. -- important and urgent problems of the technology of today are no longer the satisfactions of the primary needs or of archetypal wishes, but the reparation of the evils and damages by the technology of yesterday. ~Dennis Gabor, Innovations: Scientific, Technological and Social, 1970 From jyoung79 at kc.rr.com Fri Dec 19 13:14:53 2008 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Fri, 19 Dec 2008 18:14:53 +0000 Subject: change string to unicode Message-ID: <20081219181453.43GVB.336864.root@hrndva-web05-z02> Hi Steven and Peter, Thank you both very much for taking the time to answer my question. Your solutions work perfect! :-) Thanks again! Jay > How about > > >>> "\\u03b1".encode("ascii").decode("unicode-escape") > '?' > > Peter From lists at cheimes.de Mon Dec 29 10:17:37 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 29 Dec 2008 16:17:37 +0100 Subject: multiprocessing vs thread performance In-Reply-To: References: Message-ID: mk wrote: > Am I doing smth wrong in code below? Or do I have to use > multiprocessing.Pool to get any decent results? You have missed an important point. A well designed application does neither create so many threads nor processes. The creation of a thread or forking of a process is an expensive operation. You should use a pool of threads or processes. The limiting factor is not the creation time but the communication and synchronization overhead between multiple threads or processes. Christian From febaen at gmail.com Tue Dec 16 07:51:58 2008 From: febaen at gmail.com (feba) Date: Tue, 16 Dec 2008 04:51:58 -0800 (PST) Subject: Need help improving number guessing game References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> <01564c98$0$21844$c3e8da3@news.astraweb.com> <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> <4946df78$0$19771$426a74cc@news.free.fr> <1f33580b-84f9-4059-a0f0-b6a8d71325af@b38g2000prf.googlegroups.com> <4947742c$0$25951$426a34cc@news.free.fr> Message-ID: <19ad95bd-519f-4256-8bd9-1dfbbddf615f@s1g2000prg.googlegroups.com> >The good news is that Python functions are objects too, so you can pass >them as params to another function. duh, duh, duh, duh, duh! I knew I was missing something there. Thanks. >if not mini <= x <= maxi: also thanks for this, I forgot about that. But I have it as if not minr < guess < maxr: because it's to DISALLOW the numbers to stay the same. >That was just a suggestion, and it would have been pretty >interesting IMHO as a basis for a "from Q&D procedural scripting to OO >application programing" tutorial. Yeah, I can see that. From darcy at druid.net Thu Dec 11 10:03:12 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 11 Dec 2008 10:03:12 -0500 Subject: How can I understan the "for" here? In-Reply-To: <49412744.8040301@gmail.com> References: <49412744.8040301@gmail.com> Message-ID: <20081211100312.9d68eeab.darcy@druid.net> On Thu, 11 Dec 2008 22:44:20 +0800 Kermit Mei wrote: > >>> ["%s=%s" % (k, v) for k, v in params.items()] > ['pwd=secret', 'database=master', 'uid=sa', 'server=mpilgrim'] > > I can't understand the second sentence because of the "for ... in". > I consider that the syntactics of "for" should be: > > for k,v in params.items(): I think you are binding ':' here too tightly to the 'for' construct in your mind. The for construct is "for in " which can be used as : in block constructs. The above is not a block construct but a list comprehension so it follows different rules. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From zhang_killer at hotmail.com Thu Dec 11 00:03:48 2008 From: zhang_killer at hotmail.com (frendy zhang) Date: Thu, 11 Dec 2008 13:03:48 +0800 Subject: encrypt and descrypt a created file Message-ID: if form.accepts(request.vars,session): for table in db.tables: rows=db(db[table].id).select() print rows open(str(os.sep).join([os.getcwd(), 'applications', request.application, 'databases', table+'.csv']),'w').write(str(db(db[table].id).select ())) How can i encrypt and descrypt the created file above?? thanks in advance... _________________________________________________________________ NEW! Get Windows Live FREE. http://www.get.live.com/wl/all -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmurray at bitdance.com Sat Dec 13 09:33:36 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Sat, 13 Dec 2008 09:33:36 -0500 (EST) Subject: Shorter tracebacks In-Reply-To: References: Message-ID: On Sat, 13 Dec 2008 at 06:13, bearophileHUGS at lycos.com wrote: > When I write recursive code in Python I sometimes go past the maximum > allowed stack depth, so I receive a really long traceback. The show of > such traceback on my screen is very slow (despite a CPU able to > perform billions of operations each second). So I think I'd like > something to shorten them. > I am thinking about something like: > from __future__ import short_traceback > > That allows me to see only the first and last parts of the stack > trace, and skips the (generally very redundant) middle part. _If_ such a feature were to be added, it should be a runtime option to the interpreter, not a __future__ import. --RDM From lie.1296 at gmail.com Tue Dec 9 15:56:19 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 9 Dec 2008 20:56:19 +0000 (UTC) Subject: Is 3.0 worth breaking backward compatibility? References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> Message-ID: On Sun, 07 Dec 2008 21:48:46 +0000, Tim Rowe wrote: > 2008/12/7 walterbyrd : >> IMO: breaking backward compatibility is a big deal, and should only be >> done when it is seriously needed. >> >> Also, IMO, most of, if not all, of the changes being made in 3.0 are >> debatable, at best. I can not think of anything that is being changed >> that was really a "show stopper" anyway. > > > But that's what a major release number does for you. Modula2 was quite a > break from Modula. Think of Python3.0 it as a new language, if you like, > that's inspired by Python2. You can stay with Python2 or you can adopt > the new language. That way you won't have to think of it in terms of > breaking any sort of backwards compatibility because there is no > backwards ;-) > > -- > Tim Rowe Actually I noticed a tendency from open-source projects to have slow increment of version number, while proprietary projects usually have big version numbers. Linux 2.x: 1991 Python 3.x.x: 1991. Apache 2.0: 1995. OpenOffice.org 3.0: acquired by Sun at 1999. GIMP 2.x: 1995. Wine 1.x: 1993. Compare with Windows: NT 3.1-NT 6.x: 1993. Visual Studio 97, 6.0, .NET, .NET 2003, .NET 2005, 2008: 1997. Photoshop (11 versions to CS4): 1987. Microsoft Office 3, 4, 95, 97, 2000, XP, 2003, 2007: 1990. Flash MX, 9, CS 1-4. iTunes 8: 2001. RealPlayer 4-11: 1995. Macintosh 1.0-9: 1984-2001, X.5: 2001. Winzip 12.0: early 1990s. Interestingly, many linux _distro_ also inhibit this quick version number change. Fedora 10, Ubuntu is 2 years old, version 8 (they start from version 6 not 1). Probably having higher version numbers sells better and looks more attractive (since it'd make it seem like the software is not a new product), having quick changing version number also makes users doesn't mind compatibility breaks. Also a pattern is that prop software often change how they version their product, (extreme example: visual studio: from using years, version number, .NET, .NET + Year, back to year). Changing how you version your product would make it "looks" like it's a fresh new product (boring ol' photoshop 9 looks fresh with the new CS- tag). By having quick changing version number and often changing how product is versioned, vendors could also say: "its two/three major version away, we don't support that feature anymore since a veeery long time". From benjamin.kaplan at case.edu Wed Dec 10 22:32:31 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 10 Dec 2008 22:32:31 -0500 Subject: Python is slow In-Reply-To: <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> Message-ID: On Wed, Dec 10, 2008 at 10:25 PM, Carl Banks wrote: > On Dec 10, 12:42 pm, cm_gui wrote: > > Python is SLOW. And I am not comparing it with compiled languages > > like C. > > Python is even slower than PHP! > > > cm_gui is TROLL. And I am not compring it with bots like Aaron > Castironpi Brody. cm_gui is even troller than Xah Lee! > actually Castironpi has made some coherent replies lately. Xah Lee is worse than ever though. > > > Carl Banks > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Dec 12 08:27:59 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Dec 2008 08:27:59 -0500 Subject: Removing None objects from a sequence In-Reply-To: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> Message-ID: Filip Gruszczy?ski wrote: > Hi! > > I would like to iterate over a sequence nad ignore all None objects. > The most obvious way is explicitly checking if element is not None, > but it takes too much space. And I would like to get something faster. > I can use > [ sth for sth in self.__sth if not sth is None ], but I don't know if > that's the best way. I checked itertools, but the only thing that > seemed ok, was ifilter - this requires seperate function though, so > doesn't seem too short. How can I get it the shortest and fastest way? > The problem with the list comprehension you quote above is that it creates a new list, which costs both time and memory. You might want to try using a generator expression instead: (sth for sth in self.__sth if not sth is None) This will give you the same sequence of values, but will produce them only as they need to be consumed, saving the memory and compute overhead of creating a second list. >>> lst = [1, None, 3, None, "five", None] >>> mylst = [l for l in lst if l is not None] >>> mygen = (l for l in lst if l is not None) >>> mylst, mygen ([1, 3, 'five'], ) >>> for l in mylst: print l, ... 1 3 five >>> for l in mygen: print l, ... 1 3 five >>> regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From drexeldragon at gmail.com Wed Dec 24 22:23:41 2008 From: drexeldragon at gmail.com (Mark) Date: Wed, 24 Dec 2008 22:23:41 -0500 Subject: Python 3 and my Mac (Leopard) In-Reply-To: <4952b38d$0$20300$607ed4bc@cv.net> References: <4952b38d$0$20300$607ed4bc@cv.net> Message-ID: <3e3cae6c0812241923h797d0661l2d713c6beb3e123e@mail.gmail.com> On Wed, Dec 24, 2008 at 5:11 PM, Dan wrote: > > Wanted to learn python, got Mark Summerfield's new book "Programming in Python 3". Having a hard time getting python 3 and IDLE working on my Mac with Leopard. The mac "resources" on the python.org site seem a bit out of date, and don't really mention python 3. Are there any resources out there? Is the python community just not interested in Macs? I've tried googling and the usual search strategies. Any help would be appreciated. > > DAN I used the following link when installing Python 3 on my Mac running Leopard, it worked like a charm: http://farmdev.com/thoughts/66/python-3-0-on-mac-os-x-alongside-2-6-2-5-etc-/ These instructions are based around installing Python 3 alongside your existing install, which is what I was looking for. YMMV, especially concerning IDLE, I haven't used it with 3.0 as of yet. -Mark From huffman at tokyo.email.ne.jp Fri Dec 26 20:18:13 2008 From: huffman at tokyo.email.ne.jp (Tokyo Dan) Date: Fri, 26 Dec 2008 17:18:13 -0800 (PST) Subject: SVG & Canvas: Graphics for the Web Message-ID: <767f7870-9d62-407e-99e8-9bdc437b582e@d42g2000prb.googlegroups.com> Is there a Python library that can draw/write graphics to web browsers vis SVG & Canvas via some kind of Python to javascript translation/ compilation? From python.list at tim.thechases.com Tue Dec 30 14:51:53 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 30 Dec 2008 13:51:53 -0600 Subject: need help with list/variables In-Reply-To: <63b5acce-d566-48cb-abce-c00fd0e02a39@v39g2000pro.googlegroups.com> References: <63b5acce-d566-48cb-abce-c00fd0e02a39@v39g2000pro.googlegroups.com> Message-ID: <495A7BD9.9090801@tim.thechases.com> > I have a list and would like to parse the list appending each list > item to the end of a variable on a new line. > > for instance > > mylist = ['something\n', 'another something\n', 'something again\n'] > > then parse mylist to make it appear in my variable in this format: > > myvar = """ > something > another something > something again""" Just use the join() method on an empty string: myvar = "".join(mylist) (though your example would need to be tweaked to make the newlines match the newlines in your result, given the newlines in your list) myvar = """something another something something again """ Or you can do something like myvar = '\n'.join(s.rstrip('\n') for s in mylist) Mix and match to get your desired output. -tkc From nicolas.delanos at gmail.com Thu Dec 25 08:51:18 2008 From: nicolas.delanos at gmail.com (Nicolas Delanos) Date: Thu, 25 Dec 2008 08:51:18 -0500 Subject: DomainKey library for python Message-ID: Hello, Do you know if there is a domainkey library for python ? thanks From david at abbottdavid.com Tue Dec 2 16:15:19 2008 From: david at abbottdavid.com (David) Date: Tue, 02 Dec 2008 16:15:19 -0500 Subject: Running a Python script from crontab In-Reply-To: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> Message-ID: <4935A567.2030208@abbottdavid.com> Astley Le Jasper wrote: > >> my crontab is: >> >> 30 15 * * * cd /home/myusername/src && python myscript.py I create a file runmyscript.sh and put it in /usr/bin #!/bin/bash cd /home/myusername.src python /path/to/myscript then chmod a+x /usr/bin/runmyscript.sh test it ./runmyscript add it to the crontab 30 15 * * * /usr/bin/runmyscript.sh -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From delroth at gmail.com Sun Dec 28 16:12:43 2008 From: delroth at gmail.com (Pierre Bourdon) Date: Sun, 28 Dec 2008 22:12:43 +0100 Subject: error on windows with commands.getstatusoutput In-Reply-To: References: Message-ID: <1ba9eaed0812281312t773bf436mbc51b7d83594883@mail.gmail.com> The commands module is Unix only. See its documentation : http://docs.python.org/library/commands.html On Sun, Dec 28, 2008 at 10:03 PM, Lee Harr wrote: > > My application is trying to start twistd in a cross-platform way. > > Unfortunately, it works fine on my linux system, but I do not > have windows, and I am trying to debug this remotely on a > system I never use :o( > > Anyhow, here is the error I am getting: > > cmd = '%s -y %s -l %s' % (conf.twistd, conf.tztac, conf.twistdlog) > status, output = commands.getstatusoutput(cmd) > > > > Error code: 1 > Command: C:/Python25/Scripts/twistd.bat -y tzmud.tac -l var/log/twistd.log > Output: > '{' is not recognized as an internal or external command, > operable program or batch file. > > > Apparently, the Command works fine from the command line. > > > So... > > Can I run a .bat file on windows with getstatusoutput? > > Anyone recognize this kind of error? > > > Thanks for any assistance. > > > _________________________________________________________________ > Show them the way! Add maps and directions to your party invites. > http://www.microsoft.com/windows/windowslive/events.aspx > -- > http://mail.python.org/mailman/listinfo/python-list > From skip at pobox.com Mon Dec 15 19:42:48 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 15 Dec 2008 18:42:48 -0600 Subject: Insatlling python on compute-node-linux (Cray). In-Reply-To: References: Message-ID: <18758.63880.530636.366516@montanaro-dyndns-org.local> Rahul> Has anyone tried installing Python on Compute Node Linux (on a Rahul> cray)? I was having trouble getting it running. I see that CNL Rahul> does not support dynamic libraries but I am not sure what the Rahul> best way then is to get Python running. In the Modules directory note there is a file named Setup (or Setup.dist, which you can copy to Setup to start. Scan that file looking for modules you want to support in your installation, uncomment the relevant line(s) and adjust as necessary. Then do the normal configure/make dance. Those modules which you've enabled will be statically linked into the Python interpreter executable and not built as shared objects. At least that's how I recall it from the days before Python supported shared libraries. It's been awhile. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From deets at nospam.web.de Thu Dec 18 10:53:08 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 18 Dec 2008 16:53:08 +0100 Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> <6qv7kfFeuf65U1@mid.uni-berlin.de> Message-ID: <6qv9v4Ff1lv9U1@mid.uni-berlin.de> Neal Becker wrote: > Diez B. Roggisch wrote: > >> Neal Becker wrote: >> >>> Tino Wildenhain wrote: >>> >>>> Neal Becker wrote: >>>> ... >>>>>>> So if __str__ is "meant for human eyes", then why isn't print using >>>>>>> it! >>>>>> it is: >>>>>> >>>>>> > print x >>>>>> str >>>>>> >>>>>> but dict just uses repr() for all its childs to print. >>>>>> >>>>>> T. >>>>> That makes no sense to me. If I call 'print' on a container, why >>>>> wouldn't it recursively print on the contained objects? Since print >>>>> means call str, printing a container should recursively call str on >>>>> the objects. >>>> >>>> Every class is free on how to best implement __str__, you will find >>>> the same behavior on tuple and list as well. >>>> >>>> Maybe its discussable to change the implementation sensibly, best if >>>> you would come with a proposal? Perhaps pprint.pprint is a starting >>>> point? >>>> >>>> Regards >>>> Tino >>> >>> First, I'd like to know if there is a rationale for the current design. >>> Am I correct in thinking this is a defect? >> >> I don't think so. First of all, there is no "generic" way of printing a >> collection. And the current implementation tries to give an overview what >> is contained in the collection, without trying to make it "fancy" - any >> such thing needed to be hand-coded anyway. >> >> Using repr for that is better suited, as for example string keys are >> printed with quotes around them - making clear what they are, and not >> irritating the user through potentially contained spaces or even things >> that look as if they are python objects. >> >> For example, if repr *wasn't* used, >> >> { "{foo=bar}" : "baz"} >> >> would be printed >> >> {{foo=bar} : baz} >> >> Which is *not* what the dictionary actually contains! >> >> The same goes for unicode-objects. They appear with their "funny" >> characters as \xXX-codes - instead of bailing out on you with >> unicode-errors. >> >> So, IMHO the current behavior is desired. >> > > So if I want to overload something in my custom class, so that I get a > nice string whether it's printed directly, or as part of a container, what > is the recommendation? Overload both __str__ and __repr__? Yep. And it's easy enough if you don't care about them being different.. def __repr__(self): return str(self) BTW, you newsreader still produces bogus follow-ups, which makes replying to you unnerving. Diez From andrew at doadesweb.co.uk Wed Dec 10 12:42:04 2008 From: andrew at doadesweb.co.uk (Andrew D) Date: Wed, 10 Dec 2008 09:42:04 -0800 (PST) Subject: get todays files Message-ID: I have a script that will login to my ftp server and download all the backup files, but I want it to only download the files that were created today, e.g. if I ran the script today I want it to only fetch files created today. I am really not sure about how to do this, but it is quite important to me, so all help is highly appreciated! Andrew From google at mrabarnett.plus.com Thu Dec 4 10:13:44 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 04 Dec 2008 15:13:44 +0000 Subject: python to parse excel file csv format In-Reply-To: References: <4936DC35.6010404@mrabarnett.plus.com> <4936ECF7.3040400@wildenhain.de> Message-ID: <4937F3A8.7080108@mrabarnett.plus.com> Jay Jesus Amorin wrote: > This is what i have done and its giving me error. > > #!/usr/bin/env python > > import csv, sys, os > filename = (sys.argv[1]) > reader = csv.reader(open(filename, "rb"), delimiter=',', > quoting=csv.QUOTE_NONE) > > try: > #for row in reader: > for fmodes,fname in reader: fmodes and fname are both strings. > os.chmod(fname,fmodes) os.chmod() expects its second argument to be an int: os.chmod(fname, int(fmodes)) > > except csv.Error, e: > sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) > > > testserver:~> ./parsecsv.py chown.csv > Traceback (most recent call last): > File "./promote2prod.py", line 10, in ? > os.chmod(fname,fmodes) > TypeError: an integer is required > > > Please help I'm a complete newbie to python. > > Many thanks. > From db3l.net at gmail.com Sat Dec 6 17:01:24 2008 From: db3l.net at gmail.com (David Bolen) Date: Sat, 06 Dec 2008 17:01:24 -0500 Subject: Python 3.0 automatic decoding of UTF16 References: <55d79070-0c11-4fb9-8cf5-b8cc7c54b5d2@v42g2000yqv.googlegroups.com> Message-ID: Johannes Bauer writes: > This is very strange - when using "utf16", endianness should be detected > automatically. When I simply truncate the trailing zero byte, I receive: Any chance that whatever you used to "simply truncate the trailing zero byte" also removed the BOM at the start of the file? Without it, utf16 wouldn't be able to detect endianness and would, I believe, fall back to native order. -- David From kyosohma at gmail.com Wed Dec 31 16:54:22 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 31 Dec 2008 13:54:22 -0800 (PST) Subject: Creating an application for Linux References: <7d2fe328-064c-46da-9150-7305b6f9e94e@b41g2000pra.googlegroups.com> Message-ID: <67d1e9f1-5515-47ea-a0c1-1e8faf9c056c@a12g2000pro.googlegroups.com> On Dec 31, 3:36?pm, lkcl wrote: > hiya mike: where do i know you from? ?i've heard your name somewhere > and for the life of me can't remember where! ?anyway... onwards. > I don't know...while your username looks vaguely familiar, I don't think I've communicated with you recently. I spend most of my time on the wxPython list now... > your simplest bet is to take advantage of the .deb install system, > which, if you follow that, will allow you to pull in all of the > dependencies _without_ screwing around with the ubuntu distribution, > or requiring that you build "special" versions of the dependencies. > > so - your first port of call is to locate a similar app to your own > one: > > apt-cache ?search wxwidgets > [rose-tinted filter on the results...] > cryptonit - A client side PKI (X.509) cryptographic tool > fontypython - A GUI tool to manage ttf fonts > jmdlx - jugglemaster deluxe using wxWidgets > wxmaxima - a wxWidgets GUI for the computer algebra system maxima > multiget - graphical download manager > > then, do apt-cache show , paying particular attention to > the dependencies. ?apt-cache show fontypython looks like a good > candidate. > > so, do apt-get source fontypython (or other candidate) > > also do apt-get build-essential dh-make dpkg-dev debutils python-dev > devscripts python-setuptools juuust for fun, but the essential ones > are probably dh-make and dpkg-dev. > > then you have something to work from (an example - the source of the > deb-wrapped fontypython) and you will have most of the debian > developer utils etc. etc. > > _then_ you go to e.g. oooo this:http://www.pythonmark.com/python-library/debian/howto-build-a-debian-... > the preamble for which says "don't bother with that annoying ubuntu > python deb howto video, particularly on the basis that who gives a > stuff about _verbal_ instructions when you actually want stuff you can > READ!" > > :) > > the most important thing that _you_ need to remember is that you > _must_ identify the correct libraries (and their debian packagenames - > can't bring myself to say ubuntu packagenames) and make damn sure that > you add them into the dependencies in the debian/control file. > > do _not_ be tempted to "bundle" customised versions of python- > pysqlite, python-sqlalchemy etc. etc. > > testing: you should really use a debootstrap absolute "basic" > environment (set up a chroot, or a virtual KVM or other virtual PC, > qemu, whatever, or even a real machine) do NOT do a "full" install of > ubuntu, do an absolute minimalist install (netbook, businesscard, > whatever). I thought the general practice was to test on the closest software/ hardware combo that your application was most likely to run on. I have heard of doing testing on the lowest common denominator before though. Unfortunately, I don't have time to set up a bare-bones VM since we're closing soon, but I may give this a go on Friday and report back. > > ... and _then_ install your .deb (with dpkg -i) followed by apt-get -f > install (to pull in all of the dependencies). > > then, use export DISPLAY=192.168.1.5:0.0 (adapt as necessary), run > xhost + on 192.168.1.5 (adapt as necessary), and _then_ fire up your > test app. > > if you get a python library not found runtime error, you know that you > got your dependencies wrong, in the debian/control file. > > if you install a "vanilla" ubuntu desktop, various other packages will > pull in the dependencies for you - and you will never find out if you > got all of the dependencies correct. > > that having been said, if you don't _care_ about correctness, skip the > above six sentences :) > > l. > Thanks for the instructions. Mike From prologic at shortcircuit.net.au Thu Dec 18 20:26:14 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Dec 2008 11:26:14 +1000 Subject: Factoring Polynomials In-Reply-To: <269523e2-eba9-4b6b-b0fb-c5a7deb3ed76@o4g2000pra.googlegroups.com> References: <269523e2-eba9-4b6b-b0fb-c5a7deb3ed76@o4g2000pra.googlegroups.com> Message-ID: Hi Collin, Here you go: jmills at atomant:~/tmp$ cat polycalc.py #!/usr/bin/env python from math import sqrt def f(a, b, c): if (b**2 - (4 * a * c)) < 0: return None, None # Can't solve x = (-1 * b) + (((b**2 - (4 * a * c)) ** 0.5) / (2 * a)) return (-1 * x), x print "Polynomial Solver..." print while True: a = float(raw_input("a: ")) b = float(raw_input("b: ")) c = float(raw_input("c: ")) x = f(a, b, c) if None in x: print "Can't solve!" else: print "x = -%0.2f" % x[0] print "x = +%0.2f" % x[1] jmills at atomant:~/tmp$ cheers James From bj_666 at gmx.net Mon Dec 15 16:42:23 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 15 Dec 2008 21:42:23 GMT Subject: Structure using whitespace vs logical whitespace References: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> <89b3cbe5-e61b-49eb-926a-e96a43a35fe5@s1g2000prg.googlegroups.com> Message-ID: <6qo19vFda9rhU3@mid.uni-berlin.de> On Mon, 15 Dec 2008 12:27:12 -0800, cmdrrickhunter at yaho.com wrote: > On Dec 15, 11:10?am, Terry Reedy wrote: >> > In general, I'm using indentation to show logical flow through code. >> >> That, of course, is what Python does. >> > Python does NOT use indentation to show logical flow. It uses it to > show syntactical flow. What the heck is "syntactical flow"? Of course Python uses indentation for logical flow -- the indentation reflects the program logic. > The XML writer is the perfect example of a case where they are > different. No the program flow there is just some linear calls to methods. It's the XML structure that is not reflected by the indentation, the program flow is represented just fine here. Ciao, Marc 'BlackJack' Rintsch From jstroud at mbi.ucla.edu Mon Dec 8 01:05:54 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 07 Dec 2008 22:05:54 -0800 Subject: Rich Comparisons Gotcha In-Reply-To: References: <014c593e$0$20670$c3e8da3@news.astraweb.com> Message-ID: Robert Kern wrote: > James Stroud wrote: >> py> 112 = [1, y] >> py> y in 112 >> Traceback (most recent call last): >> File "", line 1, in >> ValueError: The truth value of an array with more than one element is... >> >> but not >> >> py> ll1 = [y,1] >> py> y in ll1 >> True >> >> It's this discrepancy that seems like a bug, not that a ValueError is >> raised in the former case, which is perfectly reasonable to me. > > Nothing to do with numpy. list.__contains__() checks for identity with > "is" before it goes to __eq__(). ...but only for the first element of the list: py> import numpy py> y = numpy.array([1,2,3]) py> y array([1, 2, 3]) py> y in [1, y] ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in : The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() py> y is [1, y][1] True I think it skips straight to __eq__ if the element is not the first in the list. That no one acknowledges this makes me feel like a conspiracy is afoot. From digitig at gmail.com Fri Dec 12 15:07:42 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 12 Dec 2008 20:07:42 +0000 Subject: newbie question... In-Reply-To: References: Message-ID: 2008/12/12 : > ah, ok. now what if I want the variable to be an integer that I > send? for instance if I send 99 to the program, it is picking it up > as a string instead of an integer value. How do I handle this with > python?? As 'r' has said, you can cast it to integer. In the real world you'd want to handle the case where the user passes in something that isn't an integer, or passes in nothing at all -- it's generally a good idea to check anything the user enters for validity. It's possibly too early for you to try to code it, but it's never too early to start thinking about what you would /want/ it to do. What do you think it will do for invalid or no command line arguments at the moment? Try it! -- Tim Rowe From R.Bauer at fz-juelich.de Tue Dec 23 07:49:11 2008 From: R.Bauer at fz-juelich.de (Reimar Bauer) Date: Tue, 23 Dec 2008 13:49:11 +0100 Subject: SuSE11.1 eclipse 64 pydev can't add python path Message-ID: Hi I can install pydev using the update manager in eclipse for 64 bit from the SuSE 11.1 repo. But I can't configure pydev without crashing it. I can select the interpreter /usr/bin/python and I do see the System PYTHONPATH Forced builtin libs also looks good. But Apply gives me # # An unexpected error has been detected by Java Runtime Environment: # # SIGSEGV (0xb) at pc=0x00007f2d7abebaed, pid=6544, tid=139832007596368 # # Java VM: IcedTea 64-Bit Server VM (1.7.0-b24 mixed mode linux-amd64) # Problematic frame: # V [libjvm.so+0x21baed] # # An error report file with more information is saved as: # /home/user/hs_err_pid6544.log # # If you would like to submit a bug report, please visit: # http://icedtea.classpath.org/bugzilla # The crash happened outside the Java Virtual Machine in native code. # See problematic frame for where to report the bug. That problem happens also with the recent eclipse-cpp-ganymede-SR1-linux-gtk-x86_64.tar.gz What can be the cause for this problem? Do you know a workaround e.g. manually configuring pydev? Does one have pydev or eclipse working on SuSE11.1? cheers Reimar From rhodri at wildebst.demon.co.uk Mon Dec 22 20:29:31 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Tue, 23 Dec 2008 01:29:31 -0000 Subject: noob trouble with IDLE In-Reply-To: <68f1552e0812211346i96bf18hf28dccc1f8dd1a99@mail.gmail.com> References: <68f1552e0812211346i96bf18hf28dccc1f8dd1a99@mail.gmail.com> Message-ID: On Sun, 21 Dec 2008 21:46:16 -0000, Ronald Rodriguez wrote: > Hi, Im new to python and I've just started using Byte of Python, running > the > samples etc. Im using IDLE on Xp. Ok, here's the thing. > A sample script makes a call to the os.system() function in order to zip > some files. Everything works fine when running from the command line, but > the same code fails when I try Run --> Run module on IDLE. Im using 7z to > zip the files. Again, everything is OK when running from the command > line. > Remember, Im new to python and programming. I've done some google search > without results. Maybe its just too simple :-( . Any help would be > appreciated. Thanks in advance. When you say "the same code fails" when run via IDLE, what exactly do you mean? Does it produce huge amounts of traceback and whinging? Does it lock up IDLE entirely? Does it thumb its nose at you and go off to dance the night away in Ibiza? Absent that information, my best guess is that 7z has its own internal event loop (a quick Google suggests that it's a GUI tool) which fights for dominance with IDLE's event loop. This is a fairly common problem, and a good reason for avoiding using IDLE's "Run Module" for anything but the most straightforward Python code. -- Rhodri James *-* Wildebeeste Herder to the Masses From rNOSPAMon at flownet.com Sun Dec 28 00:57:15 2008 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sat, 27 Dec 2008 21:57:15 -0800 Subject: Need help getting MoinMoin to run under WSGI Message-ID: I successfully installed MoinMoin as a CGI according to the instructions on the moinmo.in site. But when I tried to switch over to running it under wsgi it failed thusly: [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] Traceback (most recent call last): [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] File "/www/wikis/genesisgroup/moin.wsgi", line 49, in ? [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] from MoinMoin.server.server_wsgi import WsgiConfig, moinmoinApp [Sat Dec 27 21:44:14 2008] [error] [client 66.214.189.2] ImportError: No module named MoinMoin.server.server_wsgi The problem, I believe, is that I have both Python 2.4 and 2.5 installed (it's a Debian box) and MM is installed under 2.5 but WSGI is using 2.4. I tried to fix this by setting WSGIPythonHome but to no avail. I can't figure out what to set it to. The instructions say: "the WSGIPythonHome directive should be used to specify the exact location of the Python installation corresponding to the version of Python compiled against" I have two problems with this. First, I didn't compile mod_wsgi, I got it pre-built as a Debian module. Second, what does "the exact location of the Python installation" even mean? Python2.5 is spread out in at least three different places: /usr/local/bin, /usr/lib/python2.5, and /usr/local/lib/python2.5. I've tried setting WSGIPythonHome to all of those (and a few other things as well) and nothing worked. Also, "the version of Python compiled against" seems very odd. What does that mean? Surely I don't have to recompile mod_wsgi every time I change to a new version of Python? Help! Thanks! rg From sjmachin at lexicon.net Sun Dec 7 17:20:03 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 7 Dec 2008 14:20:03 -0800 (PST) Subject: Python 3.0 automatic decoding of UTF16 References: <5u8o06xbqf.ln2@joeserver.homelan.net> <1mmq06x4g6.ln2@joeserver.homelan.net> Message-ID: <66cb8fac-d903-4324-a0b9-e12949d639f0@y1g2000pra.googlegroups.com> On Dec 8, 2:05?am, Johannes Bauer wrote: > John Machin schrieb: > > > He did. Ugly stuff using readline() :-) Should still work, though. > > Well, well, I'm a C kinda guy used to while (fgets(b, sizeof(b), f)) > kinda loops :-) > > But, seriously - I find that whole "while True:" and "if line == """ > construct ugly as hell, too. How can reading a file line by line be > achieved in a more pythonic kind of way? By using for line in open(.....) as mentioned in (1) my message that you were replying to (2) the tutorial: http://docs.python.org/3.0/tutorial/inputoutput.html#reading-and-writing-files ... skip the stuff on readline() and readlines() this time :-) While waiting for the bug to be fixed, you'll need something like the following: def utf16_getlines(fname, newline_terminated=True): f = open(fname, 'rb') raw_bytes = f.read() f.close() decoded = raw_bytes.decode('utf16') if newline_terminated: normalised = decoded.replace('\r\n', '\n') lines = normalised.splitlines(True) else: lines = decoded.splitlines() return lines That avoids the chunk-reading problem by reading the whole file in one go. In fact given the way I've written it, there can be 4 copies of the file contents. Fortunately your files are tiny. HTH, John From steve at REMOVE-THIS-cybersource.com.au Sat Dec 20 21:26:34 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Dec 2008 02:26:34 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: <015da0a4$0$20656$c3e8da3@news.astraweb.com> On Sat, 20 Dec 2008 17:55:35 -0800, Aaron Brady wrote: > On Dec 20, 7:38?pm, Steven D'Aprano cybersource.com.au> wrote: >> Instead of just whinging, how about making a suggestion to fix it? Go >> on, sit down for an hour or ten and try to work out how a BINARY >> OPERATOR like % (that means it can only take TWO arguments) can deal >> with an arbitrary number of arguments, *without* having any special >> cases. >> >> Go on. Take your time. I'll be waiting. > > Hi, not to take sides, but, there is a possibility. > > This behavior is currently legal: > >>>> "%i %%i" % 0 % 1 > '0 1' > > So, just extend it. (Unproduced.) > >>>> "%i %i" % 0 % 1 > '0 1' Errors should never pass silently, unless explicitly silenced. You have implicitly silenced the TypeError you get from not having enough arguments for the first format operation. That means that you will introduce ambiguity and bugs. "%i %i %i %i" % 5 % 3 %7 Here I have four slots and only three numbers. Which output did I expect? '%i 5 3 7' '5 %i 3 7' '5 3 %i 7' '5 3 7 %i' Or more likely, the three numbers is a mistake, there is supposed to be a fourth number there somewhere, only now instead of the error being caught immediately, it won't be discovered until much later. (BTW, if you want that behaviour, you should look at the string module.) -- Steven From tjreedy at udel.edu Wed Dec 17 14:09:53 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 17 Dec 2008 14:09:53 -0500 Subject: OT: Binary tree logarithms properties In-Reply-To: <8f67b6f80812170914m377191f4g81345ffe5d0b7f26@mail.gmail.com> References: <8f67b6f80812170914m377191f4g81345ffe5d0b7f26@mail.gmail.com> Message-ID: Mr.SpOOn wrote: > Hi, > I'm searching for a clear explanation of binary tree properties, > expecially the ones related to logarithms. > > For example, I know that in a tree with 2n-1 nodes, we have log(n) > levels, from 0 to log(n). A *complete* binary tree with n levels has 2**n - 1 nodes. This is easily shown by induction. (Try Wikipedia for induction proof if you are not familiar with such.) > So, if k is the level, the nodes on a level have indexes between 2^k > and 2^(k+1)-1. > > For k=0 we have 2 and 3. > For k=1 we have 4, 5, 6, 7 > and so on. Nodes only have single number indexes if you arrange them linearly. Then the index depends on how you arrange them, whether you start the array indexes with 0 or 1, and whether you start the level numbers with 0 or 1. Call the breadth-first sequence bf. Then the 1-based slice for 1-first level k is bf[2**(k-1):2**k)]. Again, proof by induction. Terry Jan Reedy From pavlovevidence at gmail.com Wed Dec 10 22:19:16 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 10 Dec 2008 19:19:16 -0800 (PST) Subject: internal circular class references References: Message-ID: <419f5539-9787-48a5-b6af-09a6b923e3f9@f24g2000vbf.googlegroups.com> On Dec 10, 8:18?pm, James Stroud wrote: > Ethan Furman wrote: > > Greetings List! > > > I'm writing a wrapper to the datetime.date module to support having no > > date. ?Its intended use is to hold a date value from a dbf file, which > > can be empty. > > > The class is functional at this point, but there is one thing I would > > like to change -- datetime.date.max and datetime.date.min are class > > attributes of datetime.date, and hold datetime.date values. ?At this > > point I have to have two lines outside the actual class definition to do > > the same thing, e.g.: > > > > > ? class NullDate(object): > > ? ? ? "adds null capable DateTime.Date constructs" > > ? ? ? __slots__ = ['_date'] > > ? ? ? def __new__(cls, date='', month=0, day=0): > > ? ? ? ? ? nulldate = object.__new__(cls) > > ? ? ? ? ? nulldate._date = "" > > ? ? ? ? ? . > > ? ? ? ? . > > ? ? ? ? . > > ? ? ? ? return nulldate > > ? ? ? def __getattr__(self, name): > > ? ? ? ? ? if self: > > ? ? ? ? ? ? ? attribute = self._date.__getattribute__(name) > > ? ? ? ? ? ? ? return attribute > > ? ? ? ? ? else: > > ? ? ? ? ? ? ? if callable(dt.date.__dict__[name]): > > ? ? ? ? ? ? ? ? ? return int > > ? ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? ? return 0 > > ? ? ? def __nonzero__(self): > > ? ? ? ? ? if self._date: > > ? ? ? ? ? ? ? return True > > ? ? ? ? ? return False > > ? ? ? @classmethod > > ? ? ? def fromordinal(cls, number): > > ? ? ? ? ? if number: > > ? ? ? ? ? ? ? return cls(dt.date.fromordinal(number)) > > ? ? ? ? ? else: > > ? ? ? ? ? ? ? return cls() > > ? NullDate.max = NullDate(dt.date.max) > > ? NullDate.min = NullDate(dt.date.min) > > > > > How can I move those last two lines into the class definition so that: > > ? 1) they are class attributes (not instance), and > > ? 2) they are NullDate type objects? > > > ~ethan~ > > I resisted posting a similar question recently. After much > consideration, I realized that the inability to reference a class inside > its own definition must have been a deliberate design of the language. I think mostly it's just a logistical issue. It's reasonable for a class's attributes to be objects of that class (the datetime.date class is a perfect example of when it's useful). It would be preferrable to assign such objects inside the class scope like all other class attributes. Problem is, the class doesn't exist until after all the statements in the class scope have been evaluated. > So the short answer is you can't. > > The way you have done it is best--its not a hack and is good style. Yes, it's straightforward and readable, a perfectly good workaround for a very minor style issue. Carl Banks From pavlovevidence at gmail.com Wed Dec 3 23:12:10 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 3 Dec 2008 20:12:10 -0800 (PST) Subject: RELEASED Python 3.0 final References: Message-ID: <1b9568f2-55a0-4f1e-886c-2675b16b58c9@g38g2000yqn.googlegroups.com> On Dec 3, 7:51?pm, Barry Warsaw wrote: > On behalf of the Python development team and the Python community, I > am happy to announce the release of Python 3.0 final. Congratulations! This is a great day for the Python community. Carl Banks From xahlee at gmail.com Fri Dec 5 10:51:20 2008 From: xahlee at gmail.com (Xah Lee) Date: Fri, 5 Dec 2008 07:51:20 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: On Dec 4, 6:09 pm, jason-s... at creativetrax.com wrote: > For the interested, with MMA 6, on a Pentium 4 3.8Ghz: > > The code that Jon posted: > > Timing[Export["image-jon.pgm", Graphics at Raster@Main[2, 100, 4]]] > {80.565, "image-jon.pgm"} > > The code that Xah posted: > > Timing[Export["image-xah.pgm", Graphics at Raster@Main[2, 100, 4.]]] > {42.3186, "image-xah.pgm"} > > So Xah's code is about twice as fast as Jon's code, on my computer. > > The resulting files were identical (and both looked like pure white > images; I thought they'd be interesting!). The result is not pure white images. They are ray traced spheres stacked in some recursive way. Here's the output in both my and jon's version: http://xahlee.org/xx/image.pgm also, note that Mathematica 6 has the function Normalize builtin, which is used in Jon's code deeply in the core. Normalize is not in Mathematica 4, so i had to code it myself, in this line: ?norm=Function [#/Sqrt@(Plus@@(#^2))];?. This possibly slow down my result a lot. You might want to replace any call of ?norm? in my program by the builtin Normalize. Also, each version of Mathematica has more optimizations. So, that might explain why on v4 the speed factor is ~0.2 on my machine while in v6 you see ~0.5. My machine is OS X 10.4.x, PPC G5 1.9 Ghz. ------------------------- let me take the opportunity to explain some high powered construct of Mathematica. Let's say for example, we want to write a function that takes a vector (of linear algebra), and return a vector in the same direction but with length 1. In linear algebar terminology, the new vector is called the ?normalized? vector of the original. For those of you who don't know linear algebra but knows coding, this means, we want a function whose input is a list of 3 elements say {x,y,z}, and output is also a list of 3 elements, say {a,b,c}, with the condition that a = x/Sqrt[x^2+y^2+z^2] b = y/Sqrt[x^2+y^2+z^2] c = z/Sqrt[x^2+y^2+z^2] For much of the history of Mathematica, normalize is not a builtin function. It was introduced in v6, released sometimes in 2007. See bottom of: http://reference.wolfram.com/mathematica/ref/Normalize.html Now, suppose our task is to write this function. In my code, you see it is: norm=Function[#/Sqrt@(Plus@@(#^2))]; let me explain how it is so succinct. Mathematica's syntax support what's called FullForm, which is basically a fully nested notation like lisp's. In fact, the Mathematica compiler works with FullForm. The FullForm is not something internal. A programer can type his code that way if he so pleases. in FullForm, the above expression is this: Set[ norm, Function[ Times[Slot[1], Power[ Sqrt[ Apply[ Plus, Power [ Slot[1], 2 ] ] ], -1 ] ] ] Now, in this norm=Function[#/Sqrt@(Plus@@(#^2))] The ?Function? is your lisper's ?lambda?. The ?#? is the formal parameter. So, in the outset we set ?norm? to be a pure function. Now, note that the ?#? is not just a number, but can be any argument, including vector of the form {x,y,z}. So, we see here that math operations are applied to list entities directly. For example, in Mathematica, {3,4,5}/2 returns {3/2,2,5/2} and {3,4,5}^2 returns {9,16,25}. In typical lang such as python, including lisp, you would have to map the operation into each lisp elements instead. The ?Sqrt at ...? is a syntax shortcut for ?Sqrt[...]?, and the ?Plus@@...? is a syntax shortcut for ?Apply[Plus, ...]?, which is lisp's ?funcall?. So, taking the above all together, the code for ?norm? given above is _syntactically equivalent_ to this: norm=Function[ #/Sqrt[ Apply[Plus, #^2] ]] this means, square the vector, add them together, take the square root, then have the original vector divide it. The ?#? is in fact a syntax shortcut for ?Slot[1]?, meaning the first formal parameter. The ?=? is in fact a syntax shortcut for ?Set[]?. The ?^? is a shortcut for ?Power[]?, and the ?/? is a shortcut for ?Power[..., -1]?. Putting all these today, you can see how the code is syntactically equivalent to the above nested FullFolm. Note, that the ?norm? as defined above works for any dimentional vectors, i.e. list of any length. In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, you'll have 50 or hundreds lines. For more detail on syntax, see: ? The Concepts and Confusions of Prefix, Infix, Postfix and Fully Nested Notations http://xahlee.org/UnixResource_dir/writ/notations.html Xah ? http://xahlee.org/ ? From martin at v.loewis.de Wed Dec 3 16:47:25 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 03 Dec 2008 22:47:25 +0100 Subject: building an extension module with autotools? In-Reply-To: References: Message-ID: <4936FE6D.1000805@v.loewis.de> > I've tried using automake, however I'm worried about libtool not getting > the options right while building my module. You should use python-config(1) to obtain the command line options necessary to build and link extension modules. HTH, Martin From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 10:35:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2008 15:35:53 GMT Subject: change string to unicode References: Message-ID: <015bb6ae$0$20656$c3e8da3@news.astraweb.com> On Fri, 19 Dec 2008 09:19:28 -0600, jyoung79 wrote: > If I have a string like so: > > a = '\\u03B1' > > and I want to make it display a Greek alpha character, is there a way to > convert it to unicode ('\u03B1')? I tried concatenating it like this: > > '\u' + '03B1' > > but that didn't work. I'm working in Python 3.0 and was curious if this > could be done. This is from Python 2.5: >>> print unichr(0x03B1) ? I don't have Python 3 here, but I guess that you would just use chr() instead of unichr(). If you literally have to start with the actual string '\\u03B1' (that is, backslash lowercase-U zero three uppercase-B one), then I'd do this: >>> s = '\\u03B1' >>> if s.startswith('\\u'): ... s = s[2:] ... >>> print unichr(int(s, 16)) ? -- Steven From alwaseem307ster at yahoo.com Thu Dec 18 00:58:31 2008 From: alwaseem307ster at yahoo.com (klia) Date: Wed, 17 Dec 2008 21:58:31 -0800 (PST) Subject: importing csv file into sqlite Message-ID: <21067453.post@talk.nabble.com> hey guys, i have a hug .csv file which i need to insert it into sqlite database using python. my csv data looks like this Birthday2,12/5/2008,HTC,this is my birthday Sea,12/3/2008,kodak,sea birthday4,14/3/2009,samsung,birthday love,17/4/2009,SONY,view of island can any one give me a head start codes. thanks in advance -- View this message in context: http://www.nabble.com/importing-csv-file-into-sqlite-tp21067453p21067453.html Sent from the Python - python-list mailing list archive at Nabble.com. From xahlee at gmail.com Thu Dec 11 13:41:59 2008 From: xahlee at gmail.com (Xah Lee) Date: Thu, 11 Dec 2008 10:41:59 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> Message-ID: <452ba58b-9377-4463-85e2-5ecdaa25a129@t39g2000prh.googlegroups.com> On Dec 10, 2:47?pm, John W Kennedy wrote: > Xah Lee wrote: > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, > > you'll have 50 or hundreds lines. > > C: > > #include > #include > > void normal(int dim, float* x, float* a) { > ? ? float sum = 0.0f; > ? ? int i; > ? ? float divisor; > ? ? for (i = 0; i < dim; ++i) sum += x[i] * x[i]; > ? ? divisor = sqrt(sum); > ? ? for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; > > } i don't have experience coding C. The code above doesn't seems to satisfy the spec. The input should be just a vector, array, list, or whatever the lang supports. The output is the same datatype of the same dimension. Xah ? http://xahlee.org/ ? From cjw at ncf.ca Tue Dec 2 14:50:03 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Tue, 02 Dec 2008 14:50:03 -0500 Subject: Multiple Versions of Python on Windows XP In-Reply-To: <4934de22$0$27863$9b622d9e@news.freenet.de> References: <4934de22$0$27863$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: >> Could anyone please point me to documentation on the way the msi >> installer handles multiple versions eg. Python 2.5, 2.6 and 3.0? > > I don't think that is documented anywhere. > >> What changes are made to the registry? > > For a complete list, see Tools/msi/msi.py in the source tree. I have scanned the file: http://svn.python.org/projects/python/branches/py3k/Tools/msi/msi.py I don't find anything that addresses this issue. > >> Is there some way to specify a default version in such a way that it can >> be changed as necessary? > > What do you mean by "default version"? I am seeking some mechanism such that any of Python 2.5, Python 2.6 or Python 2.6 can be chosen as the currently active version. > > There is the version that is associated with the .py/.pyc extensions > at any point in time; you can change these by re-running the respective > installers from add-and-remove-programs. In a well-managed installation, > only one Python installation would have the "Register Extensions" > feature selected; to then change the default, one would unselect the > feature in one version, and reselect it in a different. If only the > default installation procedure was ever used, re-running the installer > in "Repair" mode (from ARP) will also restore the extension > associations. I was hoping that there is some simpler way than the "Repair" procedure. > >> PyScripter uses an option to select a version eg. >> >> C:\Program Files\PyScripter\PyScripter.exe --python26 >> >> but I'm having some trouble with it when I attempt edit a python file >> from the Windows Explorer. > > It would be good to be more specific with such statements: what troubles > specifically? If I play dumb, I'd say "of course - windows explorer > doesn't support editing Python files; you need a text editor". Yes, I should have been clearer. The PyScripter application locks up and must be killed, using the Task Manager. Many thanks for your response. Best wishes, Colin W. > > Regards, > Martin From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 29 04:26:28 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 29 Dec 2008 10:26:28 +0100 Subject: "return" in def In-Reply-To: <3afba310-dcde-4dc1-825a-7c63b97e2a40@w1g2000prk.googlegroups.com> References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <0167cbf7$0$6988$c3e8da3@news.astraweb.com> <676bffeb-4b07-4226-8c14-7da57d94351b@f13g2000yqj.googlegroups.com> <3afba310-dcde-4dc1-825a-7c63b97e2a40@w1g2000prk.googlegroups.com> Message-ID: <495897c4$0$8481$426a74cc@news.free.fr> John Machin a ?crit : > On Dec 29, 7:06 am, Roger wrote: >>> Curious. When I see a bare return, the first thing I think is that the >>> author forgot to include the return value and that it's a bug. >>> The second thing I think is that maybe the function is a generator, and >>> so I look for a yield. If I don't see a yield, I go back to thinking >>> they've left out the return value, and have to spend time trying to >>> understand the function in order to determine whether that is the case or >>> not. >>> In other words, even though it is perfectly valid Python, bare returns >>> always make the intent of the function less clear for me. I'm with Bruno >>> -- if you have a function with early exits, and you need to make the >>> intent of the function clear, explicitly return None. Otherwise, leave it >>> out altogether. >>> -- >>> Steven >> To me this is the soundest argument. Thanks for the advice. I think >> I'll follow this as a rule of thumb hereafter. > > Please don't. Follow MRAB's advice, with the corollary that a > generator is forced by the compiler to be a "procedure" in MRAB's > terminology. I fail to see any *practical* difference between MRAB's and Steven's POVs. In both cases, it boils down to - don't use a bare return at the end of a def statement's body, - either use only bare returns ('procedure') or explicitely return None ('function') From malaclypse2 at gmail.com Tue Dec 2 14:26:50 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 2 Dec 2008 14:26:50 -0500 Subject: help me~!about base64 In-Reply-To: References: <0ff1ba7b-8a17-4647-99fc-9c8e32f83de7@g1g2000pra.googlegroups.com> Message-ID: <16651e80812021126g303a8d6ai5862857dd0038b7a@mail.gmail.com> On Tue, Dec 2, 2008 at 2:08 PM, wrote: >>>>print base64.__file__ > /usr/lib/python2.5/base64.pyc That looks fine, and matches what I have on my linux box. Your code works fine for me when I run it, so I'm out of ideas. -- Jerry From ivlenin at gmail.com Mon Dec 8 14:22:14 2008 From: ivlenin at gmail.com (I V) Date: Mon, 08 Dec 2008 19:22:14 GMT Subject: Text parsing via regex References: Message-ID: On Mon, 08 Dec 2008 13:42:00 -0500, r0g wrote: > Robocop wrote: >> However i'm having several problems. I know that playskool regular >> expression i wrote above will only parse every 50 characters, and will >> blindly cut words in half if the parsed string doesn't end with a >> whitespace. I'm relatively new to regexes and i don't know how to have >> it take that into account, or even what type of logic i would need to >> fill in the extra whitespaces to make the string the proper length when >> avoiding cutting words up. So that's problem #1. Regexps may not be the solution here. You could consider the textwrap module ( http://docs.python.org/library/textwrap.html ), although that will only split your text into strings up to 50 characters long, rather than padding with whitespace to exactly 50 characters. If you really need the strings to be exactly 50 characters long (and, are you sure you do?), try: # Split the input up into separate words words = input_string.split() groups = [] current_string = '' current_length = 0 for word in words: if current_length + len(word) +1 <= 50: # If adding a space followed by the current word # wouldn't take us over 50 chars, add the word. current_string += ' ' + word current_length += len(word)+1 else: # Pad the string with spaces, and add it to our # list of string current_string += ' ' * (50 - current_length) groups.append(current_string) current_string = word current_length = len(word) >> Problem #2 is that >> because the string is of arbitrary length, i never know how many parsed >> strings i'll have, and thus do not immediately know how many variables >> need to be created to accompany them. It's easy enough with each pass >> of the function to find how many i will have by doing: mag = >> len(string) >> upper_lim = mag/50 + 1 >> But i'm not sure how to declare and set them to my parsed strings. Whenever you find yourself thinking "I don't know how many variables I need," the answer is almost always that you need one variable, which is a list. In the code above, the 50-char-long strings will all get put in the list called "groups". From steve at holdenweb.com Tue Dec 23 06:49:11 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 23 Dec 2008 06:49:11 -0500 Subject: String Format Error. In-Reply-To: <47c890dc0812222311m2a67b798v167b40de9dfcd53d@mail.gmail.com> References: <47c890dc0812222311m2a67b798v167b40de9dfcd53d@mail.gmail.com> Message-ID: Chris Rebert wrote: > On Mon, Dec 22, 2008 at 10:19 PM, Paulo Repreza wrote: >> Hi, >> >> I'm a newbie with python and I recently bought Beginning with Python (Which >> is a book I recommend) but the problem that I'm facing it's the following: >> >> This is the code: >> >> #!/usr/bin/python2.5 >> # Filename: str_format.py >> >> age = 25 >> name = 'foobar' >> >> print('{0} is {1} years old'.format(name, age)) >> print('Why is {0} playing with that python?'.format(name)) >> >> >> But when I run the script I receive this error: >> >> Traceback (most recent call last): >> File "str_format.py", line 7, in >> print('{0} is {1} years old'.format(name, age)) >> AttributeError: 'str' object has no attribute 'format' >> >> >> It is an error because of the version that I'm using ? Python 2.5.2 (Debian >> lenny) > > Yes, Python 2.6 or higher is required to use .format() according to > http://docs.python.org/whatsnew/2.6.html > For a replacement that will work in 2.5, see the "%" sign as an operator (sometimes called "string interpolation"). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From Slaunger at gmail.com Tue Dec 9 11:45:37 2008 From: Slaunger at gmail.com (Slaunger) Date: Tue, 9 Dec 2008 08:45:37 -0800 (PST) Subject: When (and why) to use del? References: Message-ID: On 9 Dec., 17:35, Albert Hopkins wrote: > I'm looking at a person's code and I see a lot of stuff like this: > > ? ? ? ? def myfunction(): > ? ? ? ? ? ? # do some stuff stuff > ? ? ? ? ? ? my_string = function_that_returns_string() > ? ? ? ? ? ? # do some stuff with my_string > ? ? ? ? ? ? del my_string > ? ? ? ? ? ? # do some other stuff > ? ? ? ? ? ? return > > and also > > ? ? ? ? def otherfunction(): > ? ? ? ? ? ? try: > ? ? ? ? ? ? ? ? # some stuff > ? ? ? ? ? ? except SomeException, e: > ? ? ? ? ? ? ? ? # more stuff > ? ? ? ? ? ? ? ? del e > ? ? ? ? ? ? return > > I think this looks ugly, but also does it not hurt performance by > preempting the gc? ?My feeling is that this is a misuse of 'del'. Am I > wrong? ?Is there any advantage of doing the above? I agree with you. In my mind there is no reason for such kinds of deletes. The code seems to have been made by a person who ?sually programs in a language which does not have a garbage collector. I do not know if it has any noticeable impact on the performance. -- Slaunger From tjreedy at udel.edu Sat Dec 6 15:12:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 06 Dec 2008 15:12:02 -0500 Subject: "as" keyword woes In-Reply-To: <7d0lj4d9hai2f87r30erc4l1ir85osbfg7@4ax.com> References: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> <0147dc24$0$20670$c3e8da3@news.astraweb.com> <0148b217$0$20670$c3e8da3@news.astraweb.com> <7d0lj4d9hai2f87r30erc4l1ir85osbfg7@4ax.com> Message-ID: In my opinion, this thread is a crock of balony. Python *occasionally* adds keywords after giving a warning or requiring a future import in previous versions. In 2.2, one had to 'from __future__ import generators' to make a generator because doing so required the new 'yield' keyword. In 2.3, yield became a keyword without the import. In 2.5, one had to 'from __future__ import with_statement' to make a 'with' statement. In 2.6, with because a keyword without the import. And no one seems to have noticed. No '"with" keyword woes. In 2.6, 'as' also because a full-time keyword after several releases of being an anomalous part-time contextual keyword. tjr From ajaksu at gmail.com Wed Dec 24 10:57:40 2008 From: ajaksu at gmail.com (ajaksu) Date: Wed, 24 Dec 2008 07:57:40 -0800 (PST) Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> <1iscu14.oixxplpgajabN%pdorange@pas-de-pub-merci.mac.com> <1isenn3.1g8fxa21aqzibkN%pdorange@pas-de-pub-merci.mac.com> <0161d9c7$0$20621$c3e8da3@news.astraweb.com> <1isg3dq.1yyxrjp5eqcj5N%pdorange@pas-de-pub-merci.mac.com> Message-ID: <5d46665d-7d53-414d-8ae0-b8499b951781@n10g2000yqm.googlegroups.com> On Dec 24, 5:59?am, pdora... at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) wrote: > > For me sign_0 is the simplest one to understood. > So in the domain of my little arcade game, this is what i'll use. > I don't need the accuraccy of sign_1, because in the application i just > need to know if the target is right or left or if the speed direction is > right or left. If there is a chance of getting bogus input to sign_0 (like a list, None or other non-numeric types) it might be worth to add a quick check like: def sign_0(x): x + 0 if x==0.0: ... From castironpi at gmail.com Thu Dec 4 10:05:53 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 4 Dec 2008 07:05:53 -0800 (PST) Subject: funny generator behaviour References: Message-ID: <2e89735b-0a0e-42f1-a620-37459e51a4c3@v38g2000yqb.googlegroups.com> On Dec 4, 7:00?am, Edvin Fuglebakk wrote: ... > def orderedCombinations(pool, k): > ? ? """ > ? ? Generator yielding ordered selections of size k with repetition from > pool. > ? ? """ > > ? ? if k == 1: > ? ? ? ? for m in pool: > ? ? ? ? ? ? yield [m] > > ? ? if k > 1: > > ? ? ? ? for m in pool: > ? ? ? ? ? ? for combo in orderedCombinations(pool, k-1): > > ? ? ? ? ? ? ? ? #insert and pop to avoid copying entire list > ? ? ? ? ? ? ? ? combo.insert(0,m) > ? ? ? ? ? ? ? ? yield combo > ? ? ? ? ? ? ? ? combo.pop(0) 'combo.pop' is the problem. When the caller saves the iteration variable, the generator modifies it on the next call. >>> a= [] >>> b= [0] >>> a.append( b ) >>> a [[0]] >>> b.insert( 0, 1 ) >>> a [[1, 0]] If you want your output to have X lists, you need to create X lists. Perhaps copy is not the most efficient, but you can't have one list try do be X different lists when viewed from different angles. Though that would be cool. From icanbob at gmail.com Thu Dec 11 20:03:24 2008 From: icanbob at gmail.com (bobicanprogram) Date: Thu, 11 Dec 2008 17:03:24 -0800 (PST) Subject: problem adding custom module in cgi script Message-ID: Problem: Apache server serving an HTML file to a Firefox Browser containing a form and a CGI python CGI script. HTML works fine, meat of the CGI script works fine except that when a home grown and ordinarily functional module that is to be imported is added, the interpreter cannot find it. Running cgi.test() reveals that PYTHONPATH is correctly set. Still nada. Adding the sys.* stuff still nada. Items: Firefox Browser, Apache server, Python 2.5. ======================================= The CGI script: #! /usr/bin/python import cgi #cgi.test() import sys #sys.path.append("/myModulePath") #sys.path.insert(0, "/myModulePath") import myModule **************** Problem here ******************** =========================================== httpd error_log excerpt: [Wed Dec 10 13:39:46 2008] [error] [client 192.168.1.1] Traceback (most recent call last):, referer: http://192.168.1.1/nee.html [Wed Dec 10 13:39:46 2008] [error] [client 192.168.1.1] File "/var/www/cgi-bin/noo.py", line 11, in , referer: http://192.168.1.1/nee.html [Wed Dec 10 13:39:46 2008] [error] [client 192.168.1.1] import myModule, referer: http://192.168.1.1/nee.html [Wed Dec 10 13:39:46 2008] [error] [client 192.168.1.1] ImportError: No module named myModule, referer: http://192.168.1.1/nee.html ============================================= Relevant lines from http.conf: ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" SetEnv PYTHONPATH /myModulePath PassEnv PYTHONPATH Thanks in advance for any pointers. bob From kyrie at uh.cu Wed Dec 10 17:58:49 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Wed, 10 Dec 2008 17:58:49 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: <200812101758.50276.kyrie@uh.cu> On Sunday 07 December 2008 09:21:18 pm Robert Kern wrote: > The deficiency is in the feature of rich comparisons, not numpy's > implementation of it. __eq__() is allowed to return non-booleans; however, > there are some parts of Python's implementation like list.__contains__() > that still expect the return value of __eq__() to be meaningfully cast to a > boolean. list.__contains__, tuple.__contains__, the 'if' keyword... How do can you suggest to fix the list.__contains__ implementation? Should I wrap all my "if"s with this?: if isinstance(a, numpy.array) or isisntance(b,numpy.array): res = compare_numpy(a,b) elif isinstance(a,some_otherclass) or isinstance(b,someotherclass): res = compare_someotherclass(a,b) ... else: res = (a == b) if res: # do whatever -- Luis Zarrabeitia (aka Kyrie) Fac. de Matem?tica y Computaci?n, UH. http://profesores.matcom.uh.cu/~kyrie From steve at holdenweb.com Thu Dec 18 10:36:23 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 18 Dec 2008 10:36:23 -0500 Subject: Minor Typo in doc In-Reply-To: <494A5E14.10508@problemlos.ch> References: <494A5E14.10508@problemlos.ch> Message-ID: Kurt Mueller wrote: > Hi > > > > There is a minor typo in the new doc in: > http://www.python.org/doc/2.6/library/signal.html > > ------------------------------------------------------------------ > signal.SIG_DFL? > This is one of two standard signal handling options; > it will simply perform the default function for the signal. > For example, on most systems the default action for SIGQUIT > is to dump core and exit, while the default action for > SIGCLD > is to simply ignore it. > ------------------------------------------------------------------ > > SIGCLD > should be > SIGCHLD > > > Should I make a bug report in http://bugs.python.org? > Yes. The documentation give you a link to follow from the bottom of each page. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steve at holdenweb.com Mon Dec 22 12:56:06 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 22 Dec 2008 12:56:06 -0500 Subject: Python's popularity In-Reply-To: References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: r wrote: > I think when Python was first brought to this dark world by a genius > named Guido van Rossum, it had complete dominance in it's niche, > actually Python created a niche where none existed before. Since the > advent of Ruby(Python closet competitor), Python's hold on this niche > is slipping. A lot of Ruby noobies don't even realize that most of > Ruby is an out-right plagiarism of Python. But I guess that's OK, > because Python has borrowed from other languages itself.. just not in > such a -sell your soul- kind of way as Ruby!. > > Now since Python *is not* the only language on it's block, we have to > compete with our main nemesis(Ruby) for survival(I wonder if mats > would have been so revolutionary to introduce indention if Guido had > not done it first??, it seems to me he is a braces fanboy ;) > What makes you assume this is a zero-sum game, and that Python won't survive if any other language becomes popular. Every language borrows from those that came before it. Terms like "outright plagiarism" don't encourage rational debate, and make you seem like a troll who is more interested in stirring up controversy than actually doing things to help promote the language. > Now more than ever we must stick to the Zen and clean up Python's > warts to keep the dream alive and regain our right full crown. Python > is better than Ruby, I have no doubt in my mind, but if we let ruby > become -faster- than Python, people will gravitate away from Python. > Speed IS important even in high level languages. We must never forget > that! The war is not over just because we have Google, Nasa, and ILM. > On the Contrary, it has just begun. I believe mats is not going to > accept Ruby as 2nd best to Python, he will wage war on Pythonia. And > if we fail to preempt this attack, we shall be like the burning ships > of pearl harbor! Maybe Guido has a secret weapon up his sleeve(big > boy), but 3.0 was defiantly not the bomb! > I have an article about the Zen coming up in "Python Magazine" so I won't steal its thunder. Suffice it to say that people take the Zen far too seriously. Anyone who does so undermines their own credibility as a Python commentator. This isn't a war. Stop being childish. > Mats will now take advantage of the weaknesses in Py3000 and run with > them. Whispering in everyones ear how much faster Ruby is to Python. > And weather you like to hear it or not, this ROR thing is exploding, > we must counter attack this vile disgrace to Pythonia. Do not sit back > and say "well we are the best and we don't need to try any harder". > For you will be left in the evolutionary dust of Ruby. And next year, > left wanting... > If all you want from a language is speed, go use C. I would avoid assembly language though, since a modern optimizing C compiler will often beat an assembly language programmer for execution speed, and the programming time will definitely be shorter. But to make speed the be-all and end-all is a witless approach. Speed is definitely not why dynamic languages' popularity is increasing. Speed *is* still relevant in certain areas, and completely irrelevant in others. > We need to sound the battle cries and gather the legions. Then we > shall march across Rubonia and *raise* their cities to the ground. We > shall encompass thy house O' Ruby -- and lay waste to it! After we > slay thee, we shall breed with thy women and convert thy children. We > shall rule with an iron fist!, crushing all resistance to Python's > absolute power. Like the great kings of olde, monuments will be > erected so all generations shall be witness of our power, and glory. > """ O' Python, for the sound of thy chariots will be so fear full no > army could stand against thee!""" We shall avenge the atrocities and > hypocrocies you have brought upon this world Ruby! And then you shall > know that we are the Lord of this world, when our vengeance is cast > upon you! > > I will be monitoring comp.lang.python and over the next 6 months I > will conduct a census of the users of this group. So far I have only > seen maybe 20 regulars here. I had hoped they numbered several > thousand, but i am starting to think more in the hundreds or even > less :(. I will post my findings to this group. It shall be a wake up > call for those of you who think the war is over. Get off your bums you > lazy-coach-potatos, the fight is not over yet. Do not let your eye's > become "wide shut"!!! > > Truth shall be the judge... Much more of this kind of tripe and nobody will read what you write anyway. You will hear the plonking of a hundred thousand newsreaders every time you post. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From sjmachin at lexicon.net Fri Dec 26 17:05:47 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 26 Dec 2008 14:05:47 -0800 (PST) Subject: Right way to set a variable to NULL? References: <5nfal41gom0iqi2nh5h0m5847ev9brtvpf@4ax.com> Message-ID: <098da1d1-640c-4aef-b005-5f0932f291cc@35g2000pry.googlegroups.com> On Dec 27, 8:16?am, Scott David Daniels wrote: > Martin wrote: > > ... > > class MailAddress(object): > > ? def __init__(self, address=None): > > ? ? self.address = address > > ? def __str__(self): > > ? ? if address: > > ? ? ? return self.adress > > ? ? return "NULL" > > There is an obvious typo above: > ?> ? ? if address: > should be: > ? ? ? ?if self.address: > > Or, you could replace the __str__ function with: > ? ? ?def __str__(self): > ? ? ? ? ?return self.address or "NULL" The above all have the same characteristic: if the input is a zero- length string, then NULL is inserted into the database instead of a zero-length string. Some folks (not just pedants!) regard that as an important difference. From rdmurray at bitdance.com Thu Dec 11 17:04:11 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Thu, 11 Dec 2008 17:04:11 -0500 (EST) Subject: Preventing execution of a method In-Reply-To: References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> <764daeef-bfbe-411a-8521-bb114321e4ac@b38g2000prf.googlegroups.com> <19304f8c-e34f-4aa9-8df2-6a7d3553007a@e1g2000pra.googlegroups.com> <2eed8876-94d2-4304-88a5-eb4a78b4f41d@33g2000yqm.googlegroups.com> <307fe197-1b42-4305-af0e-94b7ebe3ce70@r15g2000prh.googlegroups.com> <49417c59$0$8491$426a74cc@news.free.fr> Message-ID: On Thu, 11 Dec 2008 at 13:41, Emanuele D'Arrigo wrote: > On Dec 11, 7:48?pm, Bruno Desthuilliers > wrote: >>> or to provide read-only >>> access. I.e. right now I'm working on the graphical client which >>> potentially could be rewritten entirely by the users. It is necessary >>> and perfectly reasonable for the client module to access some of the >>> objects to be represented graphically, but those objects shouldn't be >>> modifiable by it. >> >> Why so ? At worst, they'll break everything. > > -IF- the application was single-user yes, it wouldn't be a big deal. > But as it is potentially multi-user, I don't want one party to corrupt > the application for everybody else. Say I'm writing a multi-player > version of a card game (I'm not). For the sake of the argument let's > imagine that the players are all playing on the same computer, taking > turns. However, they are using a GUI written by one of the players who > unbeknown to them, has written it to modify the game state > appropriately and give himself the right cards at the right time. If > the game state is read-only and can only be queried but not modified > by the GUI, the player can rewrite the GUI but cannot cheat. Isn't > this a legitimate concern? In that case, you've got much bigger problems than a lack of private methods. As someone else pointed out, _no_ language is secure in the face of this requirement. Proving this kind of interface requires a lot of careful security oriented thinking. Whole operating systems have been designed to address these kinds of issues... --RDM From skip at pobox.com Tue Dec 23 10:33:11 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 23 Dec 2008 09:33:11 -0600 Subject: pseudo terminal usage from Python? In-Reply-To: References: <18768.60036.20440.46074@montanaro-dyndns-org.local> Message-ID: <18769.1207.160812.2745@montanaro-dyndns-org.local> Steve> Look at the pexpect module - you can run interactive tasks Steve> through that. Thanks. Worked like a charm. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From katrinalovers at gmail.com Thu Dec 25 11:52:36 2008 From: katrinalovers at gmail.com (Katrina Lovers) Date: Thu, 25 Dec 2008 08:52:36 -0800 (PST) Subject: Celebrity wars (personal blog) @ http://www.bestbollywoodwallpapers.blogspot.com & http://www.besthollywoodwallpapers.blogspot.com Message-ID: <2b1ef63d-de33-449e-b797-f4c99c04f1e3@a29g2000pra.googlegroups.com> Celebrity wars, BOLLYWOOD ACTRESSES (http://www.bestbollywoodwallpapers.blogspot.com) Aishwarya Rai - http://www.hotandsexyaishwaryaraiwallpapers.blogspot.com Katrina Kaif - http://www.sexykatrinakaifwallpapers.blogspot.com PriyankaChopra - http://www.hotpriyankachoprawallpapers.blogspot.com Bipasha Basu - http://www.hotbipashabasuwallpapers.blogspot.com Kareena Kapoor - http://www.hotkareenakapoorwallpapers.blogspot.com Deepika Padokone - http://www.deepikapadokonewallpapers.blogspot.com Mallika Sherawat - http://www.hotmallikasherawatwallpapers.blogspot.com Riya Sen - http://www.hotriyasenwallpapers.blogspot.com Rakhi Sawant - http://www.rakhisawantwallpapers.blogspot.com Sayali Bhagat - http://www.sayalibhagatwallpapers.blogspot.com Diya Mirza - http://www.diyamirzawallpapers.blogspot.com Ayesha Takia - http://www.hotayeshatakiawallpapers.blogspot.com Neha Dhupia - http://www.hotnehadhupiawallpapers.blogspot.com Celina Jaitley - http://www.hotcelinajaitleywallpapers.blogspot.com Lara Dutta - http://www.hotlaraduttawallpapers.blogspot.com Sameera Reddy - http://www.sameerareddywallpapers.blogspot.com Hansika Motwani - http://www.hansikamotwaniwallpapers.blogspot.com Amrita Arora - http://www.hotamritaarorawallpapers.blogspot.com Amrita Rao - http://www.hotamritaraowallpapers.blogspot.com Aarti Chhabria - http://www.aartichhabriawallpapers.blogspot.com Preity Zinta - http://www.preityzintawallpapers.blogspot.com Shamita Shetty - http://www.shamitashettywallpapers.blogspot.com Isha Koppikar - http://www.ishakoppikarwallpapers.blogspot.com Geeta Basra - http://www.geetabasrawallpapers.blogspot.com Brinda Parekh - http://www.brindaparekhwallpapers.blogspot.com Genelia Dsouza - http://www.geneliadsouzawallpapers.blogspot.com Esha Deol - http://www.eshadeolwallpapers.blogspot.com Kangana Ranaut - http://www.kanganaranautwallpapers.blogspot.com Nisha Kothari - http://www.nishakothariwallpapers.blogspot.com Masumi Makhija - http://www.masumimakhijawallpapers.blogspot.com Manjari Fadnis - http://www.manjarifadniswallpapers.blogspot.com Thanks, Katrina From pydecker at gmail.com Fri Dec 12 14:12:38 2008 From: pydecker at gmail.com (Peter Decker) Date: Fri, 12 Dec 2008 13:12:38 -0600 Subject: [wxpython-users] Dabo 0.9.0 Released In-Reply-To: <47C9D05A-1D50-4690-8062-03939E1C9AE7@leafe.com> References: <47C9D05A-1D50-4690-8062-03939E1C9AE7@leafe.com> Message-ID: On Wed, Dec 10, 2008 at 1:24 PM, Ed Leafe wrote: > We are proud (and relieved!) to finally release Dabo 0.9.0, the first > official release of the framework in six months. We haven't been taking it > easy during that period; rather, we made some changes that clean up some > weak spots in the codebase, and as a result can offer a much more solid > framework, and are on course for a 1.0 release in the near future. Thanks for all your great work. I've been using Dabo for a couple of years now, and it just keeps getting better and better! -- # p.d. From ajaksu at gmail.com Mon Dec 22 17:13:50 2008 From: ajaksu at gmail.com (ajaksu) Date: Mon, 22 Dec 2008 14:13:50 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: <4a3150a1-531a-4aed-a7c9-c359b1f97323@s9g2000prg.googlegroups.com> On Dec 22, 4:44?pm, r wrote: > Oh Steve... Listen, my words are ment as a wake-up-call to all who r, can you do me a favor? Go read the archives of this newsgroup for a month or two, then come back with some perspective. I hope that will make your posts a little less nonsensical and annoying. My words are 'ment' as a shut-up-call, you make as much sense as jeff here: http://www.python.org/doc/humor/#nolo-contendre Daniel P.S.: You think Steve 'one of those who love python'? Geez, he's the one that made us weak in this war by sabotaging a major source of revenue for Python! -> http://pyfound.blogspot.com/2006/04/python-25-licensing-change.html From cma at mail.bnu.edu.cn Mon Dec 8 09:34:03 2008 From: cma at mail.bnu.edu.cn (Cong Ma) Date: Mon, 08 Dec 2008 22:34:03 +0800 Subject: [Python 2.x] Pickling a datetime.tzinfo subclass instance? Message-ID: Hello, I'm writing a program that pickles an instance of a custom subclass of datetime.tzinfo. I followed the guides given in the Library Reference (version 2.5.2, chapter 5.1.6), which contain the note: "Special requirement for pickling: A tzinfo subclass must have an __init__ method that can be called with no arguments, else it can be pickled but possibly not unpickled again. This is a technical requirement that may be relaxed in the future." I tried this with an example "FixedOffset" subclass instance given in the Example section in the manual. It indeed failed to unpickle. To work around this, I found two possible solutions: 1. Modify the __init__ method so that it takes optional arguments with default values; 2. Implement the __getinitargs__ method so that it does the opposite of __init__: returning a tuple from the instance's internal state that can be used to re-initialize an instance, retaining the old value. My questions: 1. Is the "technical limitation" fixed in version 2.6 or 3.0? I can't check it for myself now... Python.org seems down and I can't find the docs. 2. To stick with version 2.5, which of the above 2 methods is better? Both seems to unpickle to the correct result, but are there subtle side-effects? Or there are better solutions? Regards, Cong. From steve at holdenweb.com Fri Dec 12 08:21:16 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Dec 2008 08:21:16 -0500 Subject: File names, character sets and Unicode In-Reply-To: <49423DBB.9090401@logix.net.nz> References: <49423DBB.9090401@logix.net.nz> Message-ID: Michal Ludvig wrote: > Hi all, > > is there any way to determine what's the charset of filenames returned > by os.walk()? > > The trouble is, if I pass argument to os.walk() I get the > filenames as byte-strings. Possibly UTF-8 encoded Unicode, who knows. > > OTOH If I pass to os.walk() all the filenames I get in > the loop are already unicode()d. > > However with some locales settings os.walk() dies with for example: > Traceback (most recent call last): > File "tst.py", line 10, in > for root, dirs, files in filelist: > File "/usr/lib/python2.5/os.py", line 303, in walk > for x in walk(path, topdown, onerror): > File "/usr/lib/python2.5/os.py", line 293, in walk > if isdir(join(top, name)): > File "/usr/lib/python2.5/posixpath.py", line 65, in join > path += '/' + b > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1: > ordinal not in range(128) > > I can't even skip over these files with 'os.walk(..., onerror=handler)' > the handler() is never called. > > That happens for instance when the file names have some non-ascii > characters and locales are set to ascii, but reportedly in some other > cases as well. > > What's the right and safe way to walk the filesystem and get some > meaningful filenames? > > > Related question - if the directory is given name on a command line > what's the right way to preprocess the argument before passing it down > to os.walk()? > > For instance with LANG=en_NZ.UTF-8 (i.e. UTF-8 system): > * directory is called 'smile?' > * sys.argv[1] will be 'smile\xe2\x98\xba' (type str) > * after .decode("utf-8") I get u'smile\u263a' (type unicode) > > But how should I decode() it when running on a system where $LANG > doesn't end with "UTF-8"? Apparently some locales have non-ascii default > charsets. For instance zh_TW is BIG5 charset by default, ru_RU is > ISO-8850-5, etc. How do I detect that to get the right charset for decode()? > > I tend to have everything internally in Unicode but it's often unclear > how to convert some inputs to Unicode in the first place. What are the > best practices for dealing with these chraset issues in Python? > There's currently a huge thread on python-dev dealing with (or rather discussing) this very tortuous issue. Look for "Python-3.0, unicode, and os.environ" in the archives. (The same issue, by the way, also applies to environment variables). In a nutshell, this is likely to cause pain until all file systems are standardized on a particular encoding of Unicode. Probably only about another fifteen years to go ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From cmgui2 at gmail.com Wed Dec 10 13:42:40 2008 From: cmgui2 at gmail.com (cm_gui) Date: Wed, 10 Dec 2008 10:42:40 -0800 (PST) Subject: Python is slow Message-ID: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-a-faster-python-vm.html I fully agree with Krzysztof Kowalczyk . Can't they build a faster VM for Python since they love the language so much? Python is SLOW. And I am not comparing it with compiled languages like C. Python is even slower than PHP! Just go to any Python website and you will know. An example is: http://www2.ljworld.com/ And this site is created by the creators of Django! And it is not just this Python site that is slow. There are many many Python sites which are very slow. And please don?t say that it could be the web hosting or the server which is slow ? because when so many Python sites are slower than PHP sites, it couldn?t be the web hosting. Also, Zope/Plone is even slower. Python is slow. Very slow. From benjamin.kaplan at case.edu Wed Dec 3 14:09:51 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 3 Dec 2008 14:09:51 -0500 Subject: Reverse zip() ? In-Reply-To: <20081203171957.1a476f75@usenot.de> References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> <20081203095154.1bb33d4d@usenot.de> <8000d0b0-c9e5-4dbd-a6a0-e35b83277e72@d42g2000prb.googlegroups.com> <20081203114855.3915af9e@usenot.de> <20081203171957.1a476f75@usenot.de> Message-ID: On Wed, Dec 3, 2008 at 11:19 AM, Andreas Waldenburger wrote: > On Wed, 3 Dec 2008 07:08:52 -0800 (PST) Janto Dreijer > wrote: > > > I'd like to point out that since your where thinking in terms of > > matplotlib, you might actually find numpy's own transpose useful, > > instead of using zip(*seq) :) > > > This was, of course, to be expected. :) > > Whenever will I have an original problem that has not been solved > millions of times yet? > > /W > When GvR's time machine breaks. > > > -- > My real email address is constructed by swapping the domain with the > recipient (local part). > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fetchinson at googlemail.com Sat Dec 13 21:08:37 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 13 Dec 2008 18:08:37 -0800 Subject: 1 or 1/0 doesn't raise an exception Message-ID: Is it a feature that 1 or 1/0 returns 1 and doesn't raise a ZeroDivisionError? If so, what's the rationale? -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From hongtian.info at gmail.com Thu Dec 25 09:50:31 2008 From: hongtian.info at gmail.com (Hongtian) Date: Thu, 25 Dec 2008 06:50:31 -0800 (PST) Subject: question; C/C++ with Python Message-ID: <123f104c-0edc-423f-841d-70d8d9492ddd@r15g2000prd.googlegroups.com> Hi friends, I have a C/C++ application and I wrote a .py file to extend it. The .py file includes some simple functions without import any other modules. Today, I want to update my .py file and import SMTP library in the file, but it seems fail to import SMTP library. So I want to ask: when the .py file is used to extend C/C++ application, can it import other modules? How to do that? should I copy all pythons libs to my C/C++ application directory? That could be terrible... Thanks. From sturlamolden at yahoo.no Fri Dec 12 07:34:48 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 04:34:48 -0800 (PST) Subject: var or inout parm? References: Message-ID: On Dec 7, 9:54 am, m... at pixar.com wrote: > How can I make a "var" parm, where the called function can modify > the value of the parameter in the caller? > > def f(x): > x = x + 1 Short ansver: You can modify function parameters if they are mutable. If they are immutable any attempt to modify the parameter will trigger a copy. You cannot modify parameters by rebinding. x = x + 1 is a rebinding. x += 1 is not. If you need to modify immutable parameters or do the modification by rebinding, pass the variable back. Python allows multiple return values. From 00515879256 at fastwebnet.it Wed Dec 31 03:29:19 2008 From: 00515879256 at fastwebnet.it (Glauco) Date: Wed, 31 Dec 2008 09:29:19 +0100 Subject: string in files In-Reply-To: <016abee9$0$6988$c3e8da3@news.astraweb.com> References: <62075511-08ad-405a-a3af-2da8d2f22c50@v39g2000pro.googlegroups.com> <016abee9$0$6988$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano ha scritto: > On Tue, 30 Dec 2008 11:53:17 +0100, Glauco wrote: > > >>> thanks brother >>> i mean how do i particularly assign (u = this) >>> (y = is).... >>> in the strings up there. i have been able to split strings with any >>> character sign. >>> >>> >> If i'm not wrong this is simple with RE: > > If that's your idea of "simple", I'd hate to see what you consider > complicated! > > *Simple* is just using the split method. > > a, b, c, d, e, f = 'this is a python coding group'.split() > I've done a lot of file import procedure and IMHO this solution help you in all situation. You can validate line before import, you can do a specific RE for check a more detailed line and so on, it's more powerful. For simple i mean simple programming code. Glauco From bignose+hates-spam at benfinney.id.au Thu Dec 4 18:04:44 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 05 Dec 2008 10:04:44 +1100 Subject: To Troll or Not To Troll References: <896B75251BA19745A529B1B867893FA50679CE@planet.delsci.local> Message-ID: <878wqvv8xf.fsf@benfinney.id.au> "Chris Mellon" writes: > Peculiarities in usenet resulted in this discussion having several > threads and I missed some messages before I wrote this email. I'll put this more bluntly: Warren's messages to date egregiously break the flow of discussion. Warren, in the interest of sane discussion in these forums, please: * preserve attribution lines on quoted material so we can see who wrote what. * use the convention of ?New subject (was: Old subject)? when you change the ?Subject? field of a message. * switch to a client that preserves threading in messages you send, i.e. that properly constructs the ?References? and ?In-Reply-To? fields. General advice good for everyone, of course, but particularly apropos to this reply. Any one of the above is detrimental to omit; striking on all three makes a discussion almost impossible to follow. (Thank you, though, for avoiding the worse habit of top posting!) -- \ ?The cost of education is trivial compared to the cost of | `\ ignorance.? ?Thomas Jefferson | _o__) | Ben Finney From excord80 at gmail.com Tue Dec 9 22:16:32 2008 From: excord80 at gmail.com (excord80 at gmail.com) Date: Tue, 9 Dec 2008 19:16:32 -0800 (PST) Subject: How do I manually uninstall setuptools (installed by egg)? References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> Message-ID: <375bd56a-d92b-4d33-bf70-5bea630a376a@q30g2000vbn.googlegroups.com> On Dec 9, 10:04?pm, "Chris Rebert" wrote: > So, why do you think apt and not setuptools is The Right Way(tm)? I like to keep > 1 Python on my computer. 1. First, there's the system Python, which is installed by my OS and which I try not to mess with too much. I'm guessing Ubuntu uses this Python for various system jobs, preferences apps, etc. I try to only use apt with *this* Python. 2. Then there's my *own* Python. Maybe installed in ``/opt/py-i.j.k, or---more likely---``~/opt/py-i.j.k``. *This* is the one where I've previously made regular use of setuptools and ``easy_install``. If I break this one somehow, it doesn't foul up my system Python in any way, and it's easy to scrap it and start anew if I like. So, I'd like to get my *system* Python back to its "fresh out of the Ubuntu showroom" condition and remove *that* setuptools. As an aside, I'm a bit struck by how long the setuptools/easy_install manuals are, and a bit dismayed at the lack of an easy_install uninstall command. Thinking of trying life for a while without setuptools/easy_install. Will have to see how far I get. :) From warren at delsci.com Thu Dec 4 14:10:12 2008 From: warren at delsci.com (Warren DeLano) Date: Thu, 4 Dec 2008 11:10:12 -0800 Subject: To Troll or Not To Troll Message-ID: <896B75251BA19745A529B1B867893FA50679CE@planet.delsci.local> > Yet Another Python Troll (the ivory tower reference, as well as the > abrupt shift from complaining about keywords to multiprocessing), I > have to point out that Python does add new keywords, it has done so in > the past, and there was a considerable amount of warning, including an > automated deprecation warning in the very version you are going to > recommend to your "customers' (I don't actually think you have any > customers). ROFL! I'm sorry, you're right -- this has all been a figment of my imagination... http://www.pymolwiki.org/index.php/Covers http://images.google.com/images?q=pymol So don't mind me -- I clearly don't know what I'm talking about. From castironpi at gmail.com Mon Dec 22 19:18:59 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 22 Dec 2008 16:18:59 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <6ra8t0F925rU1@mid.individual.net> <29feda0d-6432-4cb9-8809-e4d4a7798601@e1g2000pra.googlegroups.com> <6raeb8F9s47U2@mid.individual.net> Message-ID: <25b1ece0-712b-4516-af28-88c50d00ab8c@s9g2000prg.googlegroups.com> On Dec 22, 4:07?pm, r wrote: > On Dec 22, 3:15?pm, je.s.t... at hehxduhmp.org wrote: > > > r wrote: > > > We see where you stand. And also see that by removing your comments > > > from the archive in 5 days, how small your acorns really are. > > > Also, it is pretty hard to take such accusations seriously from someone > > who themselves is using a generic gmail address w/o their real name > > attached to it. ?If I didn't care about using a proper NNTP client, I > > could quite easily create some dufus account on Gmail and post through > > that just like you did - I'm sure that'd really increase my credibility! > > Would you trust my words more if i used a name like "Thurstan Howell > III".... Come on, don't tell me you are that shallow. To attack my > credibility solely based on my user name is the sport of small minded > people. Surely you can bring more thought, and intelligence to this > thread than that?... Us small-minded people have hopes and dreams just like anybody else, Thurston. From martin at v.loewis.de Thu Dec 4 19:44:51 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 05 Dec 2008 01:44:51 +0100 Subject: RELEASED Python 3.0 final In-Reply-To: References: Message-ID: <49387983$0$27885$9b622d9e@news.freenet.de> > I would like to ask, how long will Python 2 be developed? Just for curiosity. > There won't be a 2.10 release of Python. Whether that means that 2.9 will be the last one, or whether development stops earlier, remains to be seen. Regards, Martin From benjamin.kaplan at case.edu Thu Dec 18 20:05:54 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 18 Dec 2008 20:05:54 -0500 Subject: Factoring Polynomials In-Reply-To: <269523e2-eba9-4b6b-b0fb-c5a7deb3ed76@o4g2000pra.googlegroups.com> References: <269523e2-eba9-4b6b-b0fb-c5a7deb3ed76@o4g2000pra.googlegroups.com> Message-ID: On Thu, Dec 18, 2008 at 7:59 PM, Collin D wrote: > On Dec 18, 4:41 pm, "James Mills" > wrote: > > On Fri, Dec 19, 2008 at 10:11 AM, Gabriel Genellina > > > > wrote: > > > En Thu, 18 Dec 2008 17:37:35 -0200, escribi?: > > > > >> I am trying to write a simple application to factor polynomials. I > > >> wrote (simple) raw_input lines to collect the a, b, and c values from > > >> the user, but I dont know how to implement the quadratic equation > > > > >> x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > > Why is this so hard ? This is simple simple > > expression. Reading through the Python > > tutorial and reading up on how to define > > functions is all you need! :) > > > > Here goes: > > > > >>> def f(a, b, c): > > > > ... x = (-1 * b) + ((b**2 - (4 * a * c)) / (2 * a)) > > ... return (-1 * x), x > > ... > > > > >>> f(1, 2, 3) > > (6, -6) > > > > cheers > > James > > Hiya James! > > Just one small problem with your equation above... > The quadratic formula is: > x = -b +or- (b**2 - (4 * a * c))^1/2 / 2a > > You just forgot the square root which makes quadratic a bit more > complicated. > You would have to download and import sqrt() from numpy or **.5 > why do you need sqrt from numpy? Is there a problem with math.sqrt or does no one realize that it exists? > > Also.. I need to build in functionality so the user does not have to > directly call the function like: > f(a,b,c) > a = float(raw_input("a=")) b = float(raw_input("b=")) c = float(raw_input("c=")) result = f(a,b,c) > > Instead.. they should be able to just raw_input their values. > Also.. as with some of the examples above its a good idea to analyze > the discriminant to make sure we have a real solution. > Of course.. thats all pretty simple to build in. Thanks a lot! > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From antoine at vo.lu Sat Dec 6 08:38:50 2008 From: antoine at vo.lu (Antoine De Groote) Date: Sat, 06 Dec 2008 14:38:50 +0100 Subject: Guido's new method definition idea In-Reply-To: <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Antoine De Groote: >> Allowing "$" as a substitute for "self" wouldn't require this new syntax. >> class C: >> def method($, arg): >> $.value = arg > > I think this (that is just sugar) may be a little better: > > class C: > def method($, arg): > $value = arg Well, in this case there would be no need to have the $ in the arguments list, as it would be like a "keyword", or a keysymbol in this case, like the "this" keyword in Java for instance. I dislike this even more than the dotted version. > > Or even this, combined with the idea suggested in the post by Guido: > > class C: > def $method(arg): > $value = arg > > (Note there's no point after $, it's not currently possible). > Ruby uses @ and @@ for similar purposes. > I agree that the code looks worse, but also shorter to read and write, > so in lines of code that use many instance attributes, that short $ > syntax helps keep the line shorter. So I may grow to accept this > sugar... > > Bye, > bearophile From noone at lewscanon.com Thu Dec 4 09:19:04 2008 From: noone at lewscanon.com (Lew) Date: Thu, 04 Dec 2008 09:19:04 -0500 Subject: Mathematica 7 compares to other languages In-Reply-To: <20081204111115.7cee2ecc@usenot.de> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <20081204111115.7cee2ecc@usenot.de> Message-ID: Andreas Waldenburger wrote: > On Wed, 03 Dec 2008 20:38:44 -0500 Lew wrote: > >> Xah Lee wrote: >>> enough babble ... >> Good point. Plonk. Guun dun! >> > > I vaguely remember you plonking the guy before. Did you unplonk him in > the meantime? Or was that just a figure of speech? I have had some hard drive and system changes that wiped out my old killfiles. -- Lew From ivanov.maxim at gmail.com Mon Dec 1 10:03:28 2008 From: ivanov.maxim at gmail.com (redbaron) Date: Mon, 1 Dec 2008 07:03:28 -0800 (PST) Subject: setuptools - library dependencies Message-ID: <66735aa9-b9e7-4006-8516-101cd4d295ce@z1g2000yqn.googlegroups.com> I try to write setup.py which compiles C Extenstion (A). The problem is the fact, that my C Extension depends on another C lib (B). I've digged it setuptools sources a bit and found "libraries" option for setuptools.setup. Now it compile B library at build_clib stage and A Extenstion at build_ext stage. But it doesn't pack B library in final egg file, only A one. Even more, it compiles B as static lib, but links it to A as dynamic, it leads to undefined symbols in A. How could I either: 1) link A with B staticaly? 2) put B in final egg in same dir as A? From steve at REMOVE-THIS-cybersource.com.au Sun Dec 7 09:44:55 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 14:44:55 GMT Subject: Rich Comparisons Gotcha References: Message-ID: <014bd916$0$20670$c3e8da3@news.astraweb.com> On Sun, 07 Dec 2008 13:03:43 +0000, Rasmus Fogh wrote: > Jamed Stroud Wrote: ... >> Second, consider that any value in python also evaluates to a truth >> value in boolean context. But bool(x) can fail too. So not every object in Python can be interpreted as a truth value. >> Third, every function returns something. Unless it doesn't return at all. >> A function's returning nothing >> is not a possibility in the python language. None is something but >> evaluates to False in boolean context. > > Indeed. The requirement would be not that return_value was a boolean, > but that bool(return_value) was defined and gave the correct result. If __bool__ or __nonzero__ raises an exception, you would like Python to ignore the exception and return True or False. Which should it be? How do you know what the correct result should be? >From the Zen of Python: "In the face of ambiguity, refuse the temptation to guess." All binary operators are ambiguous when dealing with vector or array operands. Should the operator operate on the array as a whole, or on each element? The numpy people have decided that element-wise equality testing is more useful for them, and this is their prerogative to do so. In fact, the move to rich comparisons was driven by the needs of numpy. http://www.python.org/dev/peps/pep-0207/ It is a *VERY* important third-party library, and this was not the first and probably won't be the last time that their needs will move into Python the language. Python encourages such domain-specific behaviour. In fact, that's what operator-overloading is all about: classes can define what any operator means for *them*. There's no requirement that the infinity of potential classes must all define operators in a mutually compatible fashion, not even for comparison operators. For example, consider a class implementing one particular version of three-value logic. It isn't enough for == to only return True or False, because you also need Maybe: True == False => returns False True == True => returns True True == Maybe => returns Maybe etc. Or consider fuzzy logic, where instead of two truth values, you have a continuum of truth values between 0.0 and 1.0. What should comparing two such fuzzy values for equality return? A boolean True/False? Another fuzzy value? Another one from the Zen: "Special cases aren't special enough to break the rules." The rules are that classes can customize their behaviour, that methods can fail, and that Python should not try to guess what the correct value should have been in the event of such a failure. Equality is a special case, but it isn't so special that it needs to be an exception from those rules. If you really need a guaranteed-can't-fail[1] equality test, try something like this untested wrapper class: class EqualityWrapper(object): def __init__(self, obj): self.wrapped = obj def __eq__(self, other): try: return bool(self.wrapped == other) except Exception: return False # or maybe True? Now wrap all your data: data = [a list of arbitrary objects] data = map(EqualityWrapper, data) process(data) [1] Not a guarantee. -- Steven From duncan.booth at invalid.invalid Wed Dec 10 03:41:18 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Dec 2008 08:41:18 GMT Subject: how to get a beep, OS independent ? References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> <6q6jf8Fau4iiU2@mid.individual.net> Message-ID: Grant Edwards wrote: > On 2008-12-09, greg wrote: >> Duncan Booth wrote: >> >>> If I'm logged in to one of my servers in a large datacentre >>> then I don't what that system to beep as that would be pretty >>> useless. >> >> It also might cause the datacentre operators some >> consternation when one of their servers starts mysteriously >> beeping... > > If they can hear it. Those tiny fans they put in rack-mount > stuff are awfully loud. > http://www.thinkgeek.com/gadgets/electronic/8c52/ -- Duncan Booth http://kupuguy.blogspot.com From ivan.illarionov at gmail.com Thu Dec 18 06:11:46 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 18 Dec 2008 03:11:46 -0800 (PST) Subject: C API and memory allocation References: <59352942-e976-4ef4-bc40-c8953df0a792@c36g2000prc.googlegroups.com> Message-ID: <7e3387a0-2159-4965-aa99-3f8fa7e4ccc0@l33g2000pri.googlegroups.com> On 18 ???, 14:09, Ivan Illarionov wrote: > ... PyArg_ParseTuple(args, "O!", &PyStringObject, &pystr) ... Sorry, I must have said &PyString_Type, not &PyStringObject From pavlovevidence at gmail.com Thu Dec 11 13:56:13 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 11 Dec 2008 10:56:13 -0800 (PST) Subject: internal circular class references References: Message-ID: <5db5a57e-483d-437e-bfab-0ae897ee3680@o4g2000pra.googlegroups.com> On Dec 11, 11:33?am, Ethan Furman wrote: > Good question. ?My goal with NullDate is to have a date object that I > can treat the same regardless of whether or not it actually holds a > date. ?NullDates with no value should sort before any NullDates with a > value, should be comparable to dates as well as NullDates, and should > support all the same methods. ?In other words, I don't want to have to > worry about whether my date object has an actual date under most > circumstances (printing, using as dictionary keys, comparing, etc.). > > Does my design make more sense given these expanded requirements, or > could it still be done simpler? ?For that matter, do my requirements > make sense? Your requirements make sense, but I think your approach is overkill. In particular, I think you are unnecessarily constraining yourself by forcing the dates and non-dates to be of the same data type. There's usually no reason for that. Python's duck typing allows you to write code that supports multiple types, as long as each type provides the same methods and operations and such. For instance, say you have a function like this that works for ordinary datetime.date objects: def print_date(date): print date.strftime() Now you want to be able to pass it a particular object that indicates no date was specified. Just define the class, like so: class NullDate(object): def strftime(self): print "" Now you could pass either a regular datetime.date object, or a NullDate object, like so: print_date(datetime.date(1976,10,6)) print_date(NullDate()) So, to (almost) get what you want, you need to just define a NullDate class that implements all the methods of datetime.date. Then the only thing you have to do is, when you're extracting the date from your dbf file, instead of always creating a datetime.date, create a datetime.date object when the date is specified, and a NullDate object when it's not. You could write a factory function to do it, for instance: def create_date_or_not(dbf_cell): if dbf_cell.contents: return datetime.date.fromordinal(dbf_cell.contents) return NullDate() Now, you did throw one little curveball into the requirements above: that NullDate needs to be comparable with datetime.date objects. I'd handle this by subclassing datetime.date to allow comparisons with NullDates. class ValidDate(datetime.date): def __eq__(self,other): if isinstance(other,NullDate): return False return super(ValidDate,self).__eq__(other) # and so on class NullDate(object): def __eq__(self,other): if isinstance(other,NullDate): return True return False # note: in Python 3.0 you would want to throw exceptions # for unexpected types Then use ValidDate instead of datetime.date when the date is specified. Carl Banks From nick at craig-wood.com Thu Dec 4 05:30:47 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 04 Dec 2008 04:30:47 -0600 Subject: How can I do this (from Perl) in Python? (closures) References: <68b8294c-8771-4b02-bd46-2f25f5e01602@j35g2000yqh.googlegroups.com> Message-ID: excord80 at gmail.com wrote: > I just came across http://www.perl.com/pub/a/2002/05/29/closure.html > and wanted to try the "canonical example of closures" in Python. I > came up with the following, but it fails: > > def make_counter(start_num): > start = start_num > def counter(): > start += 1 > return counter > > from_ten = make_counter(10) > from_three = make_counter(3) > > print from_ten() # 10 > print from_ten() # 11 > print from_three() # 3 > print from_ten() # 12 > print from_three() # 4 > > The error message is: "UnboundLocalError: local variable 'start' > referenced before assignment". The same thing happens if I omit start > and just use start_num directly. > > How can I do it in Python? With a class is the best way IMHO. class make_counter(object): def __init__(self, start_num): self.x = start_num def __call__(self): x = self.x self.x += 1 return x -- Nick Craig-Wood -- http://www.craig-wood.com/nick From frank at chagford.com Wed Dec 10 05:20:24 2008 From: frank at chagford.com (Frank Millman) Date: Wed, 10 Dec 2008 02:20:24 -0800 (PST) Subject: [OT] Google Groups in bad odour Message-ID: <4d5498bf-bbf0-4760-83fc-610729bcbce2@h20g2000yqn.googlegroups.com> Hi all I know there have been complaints about spam on Google Groups over the last few months, with some members rejecting all traffic from them. You might be interested in this comment I got in a reply from someone on comp.os.linux.setup - "If you want to be read by a wider audience, you really want to post from someplace other than Google Groups. Many (most?) readers of the Linux lists kill everything from there automatically." Unfortunately it seems that their newsgroup does not have a mail gateway, so I cannot use gmane. (Please correct me if I am wrong). I will therefore have to find a suitable news client. Any recommendations? Frank Millman From rafesacks at gmail.com Mon Dec 1 04:01:45 2008 From: rafesacks at gmail.com (Rafe) Date: Mon, 1 Dec 2008 01:01:45 -0800 (PST) Subject: noob needs help References: Message-ID: <507189ab-751f-4699-adca-fc1ed924c820@v5g2000prm.googlegroups.com> On Dec 1, 12:50?am, toveysnake wrote: > I decided that I want to learn python, and have no previous > programming experience. I was reading the guide A byte of python and > got to the part where you create and run the program helloworld.py I > used kate to create this program and save it as helloworld.py. I then > entered the command python helloworld.py into the terminal(I am using > ubuntu 8.10) and I get this error: > > collin at collin-laptop:~$ python helloworld.py > python: can't open file 'helloworld.py': [Errno 2] No such file or > directory > > Am I saving the file in the wrong spot?(I saved it in documents) > Should I use a different editor? Is there a better python book > available online? if you go to the directory where you put the file and run the python command, it should work (or supply the full path and not just 'helloworld.py') - Rafe From miki.tebeka at gmail.com Thu Dec 11 16:13:35 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 11 Dec 2008 13:13:35 -0800 (PST) Subject: Best way of debigging a C extension References: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> Message-ID: <4de560df-3c1f-4861-915b-582c66799d0a@i24g2000prf.googlegroups.com> Hello Paul, > I'm writing a C extension. My environment is Python 2.5, with the > mingw compiler, on Windows XP. At the moment I'm debugging by > scattering printf() statements around, but it's not always easy. Is > there a better way of debugging - particularly for diagnosing crashes? No guaranteed to work ... * Download WinDbg from http://www.microsoft.com/whdc/devtools/debugging/installx86.mspx#a * Add "hard" breakpoints in your code using __asm int 3; * Run your program If everything works well, when a breakpoint is reached you'll get message box asking if you want to debug the program. When you hit "OK", WinDbg should open with your code. Just point it to the source location and you should be set. HTH, -- Miki http://pythonwise.blogspot.com From benjamin.kaplan at case.edu Tue Dec 2 13:44:02 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 2 Dec 2008 13:44:02 -0500 Subject: HELP!...Google SketchUp needs a Python API In-Reply-To: <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> Message-ID: On Tue, Dec 2, 2008 at 1:36 PM, Craig Allen wrote: > > Just remember thought that if you threat Python like a > > hammer, suddenly everything will look like a bail. > > > > don't you mean if you use Python like a pitchfork? Or that everything else looks like a nail. B and N are right next to each other, so that seems more likely to me. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sun Dec 14 20:55:33 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Dec 2008 01:55:33 GMT Subject: execution time References: Message-ID: <0155b08d$0$6988$c3e8da3@news.astraweb.com> On Sun, 14 Dec 2008 18:35:24 +0100, Andreas Kostyrka wrote: > On Sun, Dec 14, 2008 at 05:03:38PM +0100, David Hl??ik wrote: >> Hi guys, >> >> #! /usr/bin/python >> >> import random >> import bucket2 >> >> data = [ random.randint(1,25) for i in range(5)] print "random data : >> %s" % data >> print "result: %s" %bucket2.sort(data) >> >> How to write a test script which will outputs execution time for >> bucket2.sort(data) ? > > Well: > > import time > > starttime = time.time() > > .... > > endtime = time.time() > print "Whatever .... does, it took %5.3fs to do." % (endtime - > starttime) Is subject to lots of timing errors for small code snippets. Sorting five numbers is (probably) going to be very quick, so the random timing errors will probably be larger than the time it actually takes to sort! Just for reference, here's the size of errors from timing naively on my machine: def timer(alist): from time import time t = time() alist.sort() return time() - t def make_list(): from random import random return [random() for i in range(5)] data = [timer(make_list()) for i in range(100)] mean = sum(data)/len(data) average_error = sum(abs(x-mean) for x in data)/len(data) print "The average timing is %f seconds." % mean print "The average error is %f seconds." % average_error print "Percentage error: %f%%" % (average_error/mean*100) And here is the output: The average timing is 0.000050 seconds. The average error is 0.000089 seconds. Percentage error: 177.953157% What this tells us is that the likely error in any one timing of a small code snippet using time.time() directly is so large that it is useless for anything other than the most crude measurements. Using time() on its own is a good example of "measure with micrometer, mark with chalk, cut with axe". This is precisely the problem the timeit module is written to solve. > Alternativly take a look at the timeit standard module. I'd reverse that recommendation: start with the timeit module first, and if and only if it is unsuitable, consider writing your own solution. -- Steven From skip.montanaro at gmail.com Tue Dec 9 16:40:44 2008 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Tue, 9 Dec 2008 13:40:44 -0800 (PST) Subject: Test posting #2 - please ignore Message-ID: This is another posting you can ignore. This time posted via Google Groups. Skip Montanaro From robert.kern at gmail.com Tue Dec 2 19:59:53 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 02 Dec 2008 18:59:53 -0600 Subject: problem with optparse In-Reply-To: References: Message-ID: Neal Becker wrote: > Robert Kern wrote: > >> Neal Becker wrote: >>> This example is right out of python library reference. What's wrong >>> here? >>> >>> import optparse >>> >>> def store_value(option, opt_str, value, parser): >>> setattr(parser.values, option.dest, value) >>> >>> parser = optparse.OptionParser() >>> parser.add_option("--foo", >>> action="callback", callback=store_value, >>> type="int", nargs=3, dest="foo") >>> >>> (opt,args) = parser.parse_args ('--foo a b c'.split()) >>> >>> [...] >>> /usr/lib64/python2.5/optparse.pyc in _process_args(self, largs, rargs, >>> values) >>> 1423 elif self.allow_interspersed_args: >>> 1424 largs.append(arg) >>> -> 1425 del rargs[0] >>> 1426 else: >>> 1427 return # stop now, leave this >>> arg in rargs >>> >>> TypeError: 'str' object doesn't support item deletion >> Dunno. It works for me (i.e. I get the expected "error: option --foo: >> invalid integer value: 'a'"). Have you tried it outside of IPython? >> > yes: > python test_opt.py > Traceback (most recent call last): > File "test_opt.py", line 12, in > (opt,args) = parser.parse_args ('--foo') Ah, that's different. parse_args() takes a list, not a string. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From igouy2 at yahoo.com Sat Dec 13 10:18:28 2008 From: igouy2 at yahoo.com (Isaac Gouy) Date: Sat, 13 Dec 2008 07:18:28 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <4942cc3c$0$21936$426a74cc@news.free.fr> Message-ID: <9927611c-d15e-43d9-96da-2fd28d4f464a@x16g2000prn.googlegroups.com> On Dec 12, 11:41?am, Bruno Desthuilliers wrote: > sturlamolden a ?crit : > (snip) > > > Creating a fast implementation of a dynamic language is almost rocket > > science. But it has been done. There is Stronghold, the fastest > > version of Smalltalk known to man, on which the Sun Java VM is based. > > On a recent benchmark Java 6 -server beats C compiled by GCC 4.2.3 > > cf bearophile's comment on this point (CPU architecture and RAM) > > > And > > most of that magic comes from an implementation of a dynamically typed > > language (Smalltalk). > > Err... Where is _Java_ "dynamic" actually ? A benchmark of _Smalltalk_ > VM vs CPython VM would make more sense. http://shootout.alioth.debian.org/u32/benchmark.php?test=all&lang=vw&lang2=python > > > Second, there are other fast implementations of dynamic languages. The > > CMUCL and SBCL versions of Common Lisp comes to min; you can see how > > SBCL does in the same benchmark (CMUCL tends to be even faster). > > Could it be that there are some type hints in the lisp versions of the > source code ? > > > So Python is a lot slower than it needs to be. > > Please fix it, you're welcome. From pavlovevidence at gmail.com Tue Dec 2 18:47:03 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 2 Dec 2008 15:47:03 -0800 (PST) Subject: optimization References: Message-ID: <442729e3-2735-4d8e-a701-48d3f3219eee@v15g2000yqn.googlegroups.com> On Dec 1, 11:41?am, Neal Becker wrote: > I guess I've become accustomed to decent compilers performing > reasonable transformations and so have tended to write code for > clarity. Python isn't that language. It'll do what it can, but a very aggressive optimizing compiler wouldn't be possible with Python's dynamicism, at least not without a lot of effort (both man and computer). Python does not actually compile the function every invocation, but it does create a function object from the compiled code object, which does take a bit of time. If it is a concern, run it through a profiler to get an idea of how much it costs, so you can make an informed decision. Carl Banks From toby at telegraphics.com.au Wed Dec 3 23:19:01 2008 From: toby at telegraphics.com.au (toby) Date: Wed, 3 Dec 2008 20:19:01 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> Message-ID: <4b6c3304-2396-4d35-a06f-e5d693cbbb12@f13g2000yqj.googlegroups.com> On Dec 3, 4:15 pm, Xah Lee wrote: > On Dec 3, 8:24 am, Jon Harrop wrote: > > > My example demonstrates several of Mathematica's fundamental limitations. > > enough babble Jon. > > Come flying $5 to my paypal account, and i'll give you real code, I'll give you $5 to go away --T From mu at problemlos.ch Fri Dec 19 04:04:34 2008 From: mu at problemlos.ch (Kurt Mueller) Date: Fri, 19 Dec 2008 10:04:34 +0100 Subject: Minor Typo in doc In-Reply-To: References: <494A5E14.10508@problemlos.ch> Message-ID: <494B63A2.6050803@problemlos.ch> Steve Holden schrieb: > Kurt Mueller wrote: >> Hi >> There is a minor typo in the new doc in: >> http://www.python.org/doc/2.6/library/signal.html >> ------------------------------------------------------------------ >> signal.SIG_DFL? >> This is one of two standard signal handling options; >> it will simply perform the default function for the signal. >> For example, on most systems the default action for SIGQUIT >> is to dump core and exit, while the default action for >> SIGCLD >> is to simply ignore it. >> ------------------------------------------------------------------ >> SIGCLD >> should be >> SIGCHLD >> Should I make a bug report in http://bugs.python.org > Yes. The documentation give you a link to follow from the bottom of > each page. > regards > Steve Yesterday evening I made a bug report on bugs.python.org. (I opened a issue). This morning it has already been fixed. (It has been assigned to benjamin.peterson. He has fixed it. The issue has been closed.) > Benjamin Peterson added the comment: > Thanks for the report! Fixed in r67848. > ---------- > nosy: +benjamin.peterson > resolution: -> fixed > status: open -> closed So, that is a great community! isn't it? Thanks to all who make this possible. Gr?essli -- Kurt Mueller -- Kurt M?ller, mu at problemlos.ch From castironpi at gmail.com Mon Dec 8 15:26:34 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 8 Dec 2008 12:26:34 -0800 (PST) Subject: Guido's new method definition idea References: <493a9fed$0$18973$426a34cc@news.free.fr> <493c1ff6$0$4942$426a34cc@news.free.fr> <49d12ec1-2be9-497b-80bc-9f0402a9086d@s20g2000yqh.googlegroups.com> Message-ID: <699ea750-8dd9-472f-a7aa-90492c32c519@z1g2000yqn.googlegroups.com> On Dec 7, 4:23?pm, Philip Slate wrote: > On Dec 7, 1:13?pm, Bruno Desthuilliers > > wrote: > > > and friendlier to newbies. > > > I'd rather say "more acceptable to java-brainwashed developpers". > > And I'd rather say you're trolling, but that's ok since you're > preaching to the converted. You conveniently forgot to mention the C++/ > Eiffel/Smalltalk/pretty-much-every-OO-lang "brainwashed" developers > too. In reality Python, with its kludgy OO and objects being > essentially glorified dicts, is the odd one out, not the other way > around. That's true. But what would a Python-brainwashed developer be? From skip at pobox.com Thu Dec 18 09:53:35 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 18 Dec 2008 08:53:35 -0600 Subject: something else instead of PIL? In-Reply-To: References: Message-ID: <18762.25583.71898.279331@montanaro-dyndns-org.local> Reimar> I am interested to get some new features added e.g. some special Reimar> conversion routines for colorblind people. Reimar> http://scien.stanford.edu/class/psych221/projects/05/ofidaner/colorblindness_project.htm Reimar> How can that be archieved? Contact Fredrik Lundh? http://effbot.org/ Skip From bakul+usenet at bitblocks.com Fri Dec 12 16:19:29 2008 From: bakul+usenet at bitblocks.com (Bakul Shah) Date: Fri, 12 Dec 2008 13:19:29 -0800 Subject: Mathematica 7 compares to other languages In-Reply-To: <6375k4pf1mleb6im67nkpec5olqbsom88e@4ax.com> References: <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <452ba58b-9377-4463-85e2-5ecdaa25a129@t39g2000prh.googlegroups.com> <6375k4pf1mleb6im67nkpec5olqbsom88e@4ax.com> Message-ID: <4942D561.5020203@bitblocks.com> George Neuner wrote: > On Thu, 11 Dec 2008 10:41:59 -0800 (PST), Xah Lee > wrote: > >> On Dec 10, 2:47 pm, John W Kennedy wrote: >>> Xah Lee wrote: >>>> In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, >>>> you'll have 50 or hundreds lines. >>> C: >>> >>> #include >>> #include >>> >>> void normal(int dim, float* x, float* a) { >>> float sum = 0.0f; >>> int i; >>> float divisor; >>> for (i = 0; i < dim; ++i) sum += x[i] * x[i]; >>> divisor = sqrt(sum); >>> for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; >>> >>> } >> i don't have experience coding C. > > Then why do you talk about it as if you know something? > >> The code above doesn't seems to satisfy the spec. > > It does. > >> The input should be just a vector, array, list, or >> whatever the lang supports. The output is the same >> datatype of the same dimension. > > C's native arrays are stored contiguously. Multidimensional arrays > can be accessed as a vector of length (dim1 * dim2 * ... * dimN). > > This code handles arrays of any dimensionality. The poorly named > argument 'dim' specifies the total number of elements in the array. > > George Only if the length in each dimension is known at compile time (or in C99, if this is an automatic array). When this is not the case, you may have to implement something like the following (not the only way, just one way): float** new_matrix(int rows, int cols) { float** m = malloc(sizeof(float*)*rows); int i; for (i = 0; i < rows; i++) m[i] = malloc(sizeof(float)*cols); return m; } In this case normal() fails since matrix m is not in a single contiguous area. But I suspect Xah is complaining because the function doesn't *return* a value of the same type; instead you have to pass in the result vector. But such is life if you code in C! From ron.reidy at gmail.com Mon Dec 15 07:59:50 2008 From: ron.reidy at gmail.com (ron.reidy at gmail.com) Date: Mon, 15 Dec 2008 04:59:50 -0800 (PST) Subject: cx_Oracle issues References: <5b2dad81-2750-4347-8079-6ab31321d579@s1g2000prg.googlegroups.com> <9142a8f1-7f76-4fc0-9ca1-c9dec310f2ce@r37g2000prr.googlegroups.com> <9f436c9e-2319-499c-a306-d255996372fc@e22g2000vbe.googlegroups.com> Message-ID: On Dec 15, 2:44?am, huw_at1 wrote: > On Dec 11, 5:34?pm, "ron.re... at gmail.com" wrote: > > > > > > > On Dec 10, 9:48?am, huw_at1 wrote: > > > > Hey all. When usingcx_Oracleto run a procedure like: > > > > cursor.execute("select (obj.function(value)) from table where > > > id=blah") > > > > I am getting the following error: > > > > ORA-06502: PL/SQL: numeric or value error: character string buffer too > > > small ORA-06512: at line 1 > > > > Looking at cursor.description I get: > > > > [('(obj.function(value))', , 4000, 4000, 0, > > > 0, 1)] > > > > Any tips - i have never seen this error before but am guessing that > > > the value being returned is too big for the buffer size set for the > > > cursor. the procedure fetches data from a LOB. > > > > Any suggestions/confirmations? > > > > Many thanks > > > This error is a problem with the PL/SQL, notcx_Oracle. ?You need to > > debug obj.function to see what kind of data is being accessed and then > > a data analysis of that data to understand why this error occurs. ?I > > can tell you the function is most likely expecting characters from a > > column that are numeric [0 .. 9] and is getting alpha characters. > > > -- > > Ron Reidy > > Sr. Oracle DBA > > Hi thanks for the responses. Unfortunately the procedure in question > is from a third party vendor so I can't really debug it so I'd say I > was fairly stumped. Just out of interest how do you increase the > output buffer size withcx_Oracle? > > Many thanks- Hide quoted text - > > - Show quoted text - Hi, Sure you can. You can see the PL/SQL source from the ditionary view ALL_SOURCE: select text from all_source where name = 'NAME_OF_FUNCTION'; >From there, reverse engineeer which table(s) and column(s) are being accesses and do the data analysis. -- Ron Reidy From Scott.Daniels at Acm.Org Wed Dec 24 14:19:03 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 24 Dec 2008 11:19:03 -0800 Subject: Strategy for determing difference between 2 very large dictionaries In-Reply-To: References: <1230102996.2303.1291616055@webmail.messagingengine.com> <1230106980.12156.1291620725@webmail.messagingengine.com> Message-ID: Gabriel Genellina wrote: > En Wed, 24 Dec 2008 06:23:00 -0200, escribi?: >> ... k1 = set(dict1.iterkeys()) > You've got an excelent explanation from Marc Rintsch. (Note that in > Python 3.0 keys() behaves as iterkeys() in previous versions, so the > above code is supposed to be written in Python 2.x) And, in fact, a dictionary iterates its keys, so: k1 = set(dict1) works in 2.4, 2.5, 2.6, and 3.0 --Scott David Daniels Scott.Daniels at Acm.Org From python.list at tim.thechases.com Sat Dec 13 21:23:53 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 13 Dec 2008 20:23:53 -0600 Subject: 1 or 1/0 doesn't raise an exception In-Reply-To: References: Message-ID: <49446E39.6020807@tim.thechases.com> > Is it a feature that > > 1 or 1/0 > > returns 1 and doesn't raise a ZeroDivisionError? If so, what's the rationale? Yes, it's a feature: http://en.wikipedia.org/wiki/Short-circuit_evaluation When you have "True or False", you know it's true by the time you've got the first piece, so there's no need to evaluate the 2nd piece. The opposite is helpful too: lst = [some list or an empty list] ... if lst and lst[0] == 42: This ensures that the "lst[0]" doesn't fail if lst is empty, because lst evaluating to false (an empty list) short-circuits preventing the evaluation of "lst[0]". -tkc From vschmidt13 at gmail.com Mon Dec 8 16:47:59 2008 From: vschmidt13 at gmail.com (Val) Date: Mon, 8 Dec 2008 13:47:59 -0800 (PST) Subject: easy_install of module produces un-importable result References: <6q5chbFast45U1@mid.uni-berlin.de> Message-ID: <352dc248-600b-4415-9354-cb1aab5f6889@41g2000yqf.googlegroups.com> On Dec 8, 2:57?pm, "Diez B. Roggisch" wrote: > Val schrieb:> I've written my first module, " > > " and uploaded it as an egg to > > > PyPI. I can use easy_istall to install my own module, but when I try > > to import it I get an ImportError "No module named gpsparser". > > > So I've done some research and found that in my site-packages/ > > directory gpsparser exists as an egg file, while all the other > > packages I've installed exist as an egg directory. > > > If this makes any sense, can anyone explain what I've done wrong in > > building my package that the installation process does not unpack the > > egg file? > > This has nothing to do with that - it's simply that your egg is empty. > Take a look at this: > > (gpsparser)mac-dir:Application Support deets$ unzip -l > /Users/deets/.virtualenvs/gpsparser/lib/python2.5/site-packages/gpsparser-0 .0.1-py2.5.egg > Archive: > /Users/deets/.virtualenvs/gpsparser/lib/python2.5/site-packages/gpsparser-0 .0.1-py2.5.egg > ? ?Length ? ? Date ? Time ? ?Name > ? -------- ? ?---- ? ---- ? ?---- > ? ? ? ? ?1 ?12-08-08 12:04 ? EGG-INFO/dependency_links.txt > ? ? ? ?249 ?12-08-08 12:04 ? EGG-INFO/PKG-INFO > ? ? ? ?599 ?12-08-08 12:04 ? EGG-INFO/SOURCES.txt > ? ? ? ? ?1 ?12-08-08 12:04 ? EGG-INFO/top_level.txt > ? ? ? ? ?1 ?12-08-08 11:25 ? EGG-INFO/zip-safe > ? -------- ? ? ? ? ? ? ? ? ? ------- > ? ? ? ?851 ? ? ? ? ? ? ? ? ? 5 files > (gpsparser)mac-dir:Application Support deets$ > > I presume you miss a > > ? ? ?packages=find_packages(), > > line in your setup.py, with > > from setuptools import setup, find_packages > > to actually get the find_packages. > > Diez You are absolutely right. How embarrassing. Thank you SO much! -Val From castironpi at gmail.com Tue Dec 2 21:13:56 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 2 Dec 2008 18:13:56 -0800 (PST) Subject: Overriding a method at the instance level on a subclass of a builtin type References: Message-ID: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> On Dec 2, 6:58?pm, "Zac Burns" wrote: > Sorry for the long subject. > > I'm trying to create a subclass dictionary that runs extra init code > on the first __getitem__ call. However, the performance of __getitem__ > is quite important - so I'm trying in the subclassed __getitem__ > method to first run some code and then patch in the original dict > method for the instance to avoid even the check to see if the init > code has been run. Various recipes using instancemethod and the like > have failed me. > > Curiously if __slots__ is not specified no error occurs when setting > self.__getitem__ but the function is not overriden. If __slots__ is > ['__getitem__'] however it complains that __getitem__ is read only. I > do not understand that behavior. > > -- > Zachary Burns > (407)590-4814 > Aim - Zac256FL > Production Engineer (Digital Overlord) > Zindagi Games That sounds like the State Pattern, from GoF. http://en.wikipedia.org/wiki/State_pattern I like the idea of 'renaming', not redefining, but reassigning methods at different points during an object's lifetime. I often wish I had more experience with it, and more docs talked about it. It's hard on memory usage, since each instance has its own function attribute, even if there's still only one instance of the function. Without it, the function attribute is just looked up on the class. Not thoroughly tested: >>> class A: ... def methA( self ): ... print 'methA' ... self.meth= self.methB ... meth= methA ... def methB( self ): ... print 'methB' ... >>> a= A() >>> a.meth() methA >>> a.meth() methB From akineko at gmail.com Mon Dec 22 16:13:08 2008 From: akineko at gmail.com (akineko) Date: Mon, 22 Dec 2008 13:13:08 -0800 (PST) Subject: 64-bit / 128-bit data element type for array? References: Message-ID: <880c8478-8b40-40e0-8597-aef960612f09@s9g2000prg.googlegroups.com> Hello, bearophile and Robert, thank you for your prompt response. I will try NumPy (this is a good execuse to learn and to use a new package). > I haven't seen uint128 in the wild, though. Of course, not many applications require uinit128 as a scalar value. I may need to deal with 128-bit data as it is now not uncommon to have 128-bit data bus (or even 256-bit wide and beyond) in ASICs (microchip) design. Unfortunately, some designs use big-endian and others use little-endian ... Thank you and Happy Holidays! Aki Niimura On Dec 22, 11:26 am, Robert Kern wrote: > akineko wrote: > > Hello everyone, > > > I need to handle binary files that contain 64-bit (or 128-bit in the > > furture) unsigned int data. > > Python's array seems not supporting unsigned int type beyond 32-bit > > ('L'). > > I would like to use Python array as I need to make my program work on > > both big-endian machines as well as on little-endian machines. > > > What is the best way to deal with 64-bit / 128-bit data elements in > > Python (must support byteswap())? > > (must be machine-independent) > > You might give numpy a try. We support uint64 data even on 32-bit machines > provided that your C compiler does. I haven't seen uint128 in the wild, though. > > http://numpy.scipy.org/ > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco From rhf22 at mole.bio.cam.ac.uk Sun Dec 7 08:03:43 2008 From: rhf22 at mole.bio.cam.ac.uk (Rasmus Fogh) Date: Sun, 7 Dec 2008 13:03:43 +0000 (GMT) Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Jamed Stroud Wrote: > Rasmus Fogh wrote: >> Dear All, >> For the first time I have come across a Python feature that seems >> completely wrong. After the introduction of rich comparisons, equality >> comparison does not have to return a truth value, and may indeed return >> nothing at all and throw an error instead. As a result, code like >> if foo == bar: >> or >> foo in alist >> cannot be relied on to work. >> This is clearly no accident. According to the documentation all >> comparison operators are allowed to return non-booleans, or to throw >> errors. There is >> explicitly no guarantee that x == x is True. > I'm not a computer scientist, so my language and perspective on the > topic may be a bit naive, but I'll try to demonstrate my caveman > understanding example. > First, here is why the ability to throw an error is a feature: > class Apple(object): > def __init__(self, appleness): > self.appleness = appleness > def __cmp__(self, other): > assert isinstance(other, Apple), 'must compare apples to apples' > return cmp(self.appleness, other.appleness) > class Orange(object): pass > Apple(42) == Orange() True, but that does not hold for __eq__, only for __cmp__, and for__gt__, __le__, etc. Consider: Class Apple(object): def __init__(self, appleness): self.appleness = appleness def __gt__(self, other): assert isinstance(other, Apple), 'must compare apples to apples' return (self.appleness > other.appleness) def __eq__(self, other): if isinstance(other, Apple): return (self.appleness == other.appleness) else: return False > Second, consider that any value in python also evaluates to a truth > value in boolean context. > > Third, every function returns something. A function's returning nothing > is not a possibility in the python language. None is something but > evaluates to False in boolean context. Indeed. The requirement would be not that return_value was a boolean, but that bool(return_value) was defined and gave the correct result. I understand that in some old Numeric/numpy version the numpy array __eq__ function returned a non-empty array, so that bool(numarray1 == numarray2) was true for any pair of arguments, which is one way of breaking '=='. In current numpy, even bool(numarray1 == 1) throws an error, which is another way of breaking '=='. >> But surely you can define an equal/unequal classification for all >> types of object, if you want to? > This reminds me of complex numbers: would 4 + 4i be equal to sqrt(32)? > Even in the realm of pure mathematics, the generality of objects (i.e. > numbers) can not be assumed. It sounds like that problem is simpler in computing. sqrt(32) evaluates to 5.6568542494923806 on my computer. A complex number c with non-zero imaginary part would be unequal to sqrt(32) even if it so happened that c*c==32. Yours, Rasmus --------------------------------------------------------------------------- Dr. Rasmus H. Fogh Email: r.h.fogh at bioc.cam.ac.uk Dept. of Biochemistry, University of Cambridge, 80 Tennis Court Road, Cambridge CB2 1GA, UK. FAX (01223)766002 From goldnery at gmail.com Tue Dec 30 16:22:19 2008 From: goldnery at gmail.com (Gandalf) Date: Tue, 30 Dec 2008 13:22:19 -0800 (PST) Subject: win32gui Message-ID: I'm searching the win32gui hooks for a function to get the windowClass position any idea? thanks! From akineko at gmail.com Mon Dec 29 15:23:15 2008 From: akineko at gmail.com (akineko) Date: Mon, 29 Dec 2008 12:23:15 -0800 (PST) Subject: tkInter constraining the width only Message-ID: Hello everyone, I'm writing a Tkinter program and trying to constraint the window size. I want to set the minimum of the width and the height and the maximum of the width, but not the height. I can use minsize(width=min_width, height=min_height) from Wm method to limit the minimum sizes. Similarly I thought I could use maxsize(width=max_width, height=None) to limit the maximum sizes. Unfortunately, it didn't work. maxsize() complained if only width is given. Is there any easy way to constraint a Tkinter window so that the sizes are set except it can grow vertically. Any suggestions are greatly appreciated. Best regards, Aki Niimura From george.sakkis at gmail.com Wed Dec 10 12:21:14 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 10 Dec 2008 09:21:14 -0800 (PST) Subject: Best way to report progress at fixed intervals References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> <817384d5-5f68-4c1f-9560-0bc7b7d2b1e3@v5g2000prm.googlegroups.com> <6ccb77a2-a3f1-4b6b-900c-d4626be9e939@s1g2000prg.googlegroups.com> Message-ID: On Dec 10, 2:50?am, Slaunger wrote: > > Sorry, apparently I did not realize that at first sight. Anyway, I'd > rather avoid using further external modules besides the standard > batteries, as I would have to update several workstations with > different OSes (some of which I do not have admin access to) to use > the new module. How is this different from writing your own module from scratch ? You don't need admin access to use a 3rd party package. George From jstroud at mbi.ucla.edu Sun Dec 7 03:47:13 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 07 Dec 2008 00:47:13 -0800 Subject: Brain going crazy with recursive functions In-Reply-To: References: <181d6cf8-8df3-46d4-9d21-197d34b3de87@d36g2000prf.googlegroups.com> Message-ID: James Stroud wrote: > def linear_search(array, truth_func, loc=(0,0)): > idx1, idx2 = loc > if idx1 >= len(array): > return None > if idx2 >= len(array[idx1]): > return linear_search(array, truth_func, (idx1+1, 0)) > value = array[idx1][idx2] > tf = truth_func(value) > if tf: > return loc > else: > return linear_search(array, truth_func, (idx1, idx2+1)) > > a = [[5, 3, 4], [2, 0, 1], [8, 6, 7]] > linear_search(a, lambda x: x==0) PS: If I just made it to easy for you, you can practice by generalizing this to an N-dimensional array using recursion. I'm tempted to do it myself but I'm going to try to resist instead and do some work that pays. From sjmachin at lexicon.net Thu Dec 11 22:43:53 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 11 Dec 2008 19:43:53 -0800 (PST) Subject: newbie question: if var1 == var2: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> <44aa0191-e374-4bf0-b039-d05cfa996b1d@p2g2000prn.googlegroups.com> <37fc3229-b0a2-4d95-990f-61300fc2b257@r37g2000prr.googlegroups.com> Message-ID: <4977851c-40ea-4397-99ee-f7a343cba73e@z28g2000prd.googlegroups.com> On Dec 12, 1:11?pm, MRAB wrote: > John Machin wrote: > > On Dec 12, 11:39 am, MRAB wrote: > >> Jason Scheirer wrote: > >>> On Dec 11, 3:49 pm, John Machin wrote: > >>>> On Dec 12, 10:31 am, "Rhodri James" > >>>> wrote: > >>>>> On Thu, 11 Dec 2008 19:49:23 -0000, Steve Holden ? > >>>>> wrote: > >>>>>> Kirk Strauser wrote: > >>>>>>> At 2008-11-29T04:02:11Z, Mel writes: > >>>>>>>> You could try > >>>>>>>> for item in fname: > >>>>>>>> ? ? item = item.strip() > >>>>>>> This is one case where I really miss Perl's "chomp" function. ?It ? > >>>>>>> removes a > >>>>>>> trailing newline and nothing else, so you don't have to worry about ? > >>>>>>> losing > >>>>>>> leading or trailing spaces if those are important to you. > >>>>>> ... and it's so hard to write > >>>>>> ? ? ?item = item[:-1] > >>>>> Tsk. ?That would be "chop". ?"chomp" would be > >>>>> ? ? ?if item[-1] == '\n': > >>>>> ? ? ? ? ?item = item[:-1] > >>>> Better: > >>>> if item and item[-1] == '\n': > >>>> ? ? return item[:-1] > >>>> return item > >>> Best: > >>> return item \ > >>> ? ? ? ?if not (item and item.endswith('\n')) \ > >>> ? ? ? ?else item[:-1] > >>> Though really you should be using item.rstrip() > >> Why not just: > > >> ? ? ?item[:-1] if item.endswith('\n') else item > > > Some possible reasons: > > * because you might be supporting old versions of Python (my offering > > runs on 1.5) > > * because the " if else " syntax > > gives you the screaming dry Edgar Britts > > * because you'd prefer not to have the overhead of a method lookup and > > method call > > OK: > > ? ? ?if item[-1:] == '\n': > ? ? ? ? ?return item[:-1] > ? ? ?return item I'll pay that :-) From steven at REMOVE.THIS.cybersource.com.au Mon Dec 8 21:45:17 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 09 Dec 2008 02:45:17 GMT Subject: Rich Comparisons Gotcha References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> <014c55e9$0$20670$c3e8da3@news.astraweb.com> <11d8b41a-a910-4915-8969-fc90e978350b@j11g2000yqg.googlegroups.com> Message-ID: On Sun, 07 Dec 2008 16:24:58 -0800, George Sakkis wrote: > On Dec 7, 6:37?pm, Steven D'Aprano cybersource.com.au> wrote: ... >> Given: >> >> x = log(-5) ?# a NaN >> y = log(-2) ?# the same NaN >> x == y ?# Some people want this to be true for NaNs. >> >> Then: >> >> # Compare x and y directly. >> log(-5) == log(-2) >> # If x == y then exp(x) == exp(y) for all x, y. exp(log(-5)) == >> exp(log(-2)) >> -5 == -2 >> >> and now the entire foundations of mathematics collapses into a steaming >> pile of rubble. > > And why doesn't this happen with the current behavior if x = y = log > (-5) ? According to the same proof, -5 != -5. You're right, I was a little sloppy in my "proof". There are additional subtleties going on. -- Steven From rdmurray at bitdance.com Wed Dec 17 21:36:57 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Thu, 18 Dec 2008 02:36:57 +0000 (UTC) Subject: getting object instead of string from dir() References: <1bb0df81-380c-46eb-a3aa-863c468c6aff@x14g2000yqk.googlegroups.com> Message-ID: Quoth Rominsky : > vars seems to give an identical response as locals and globals, at > least in my test name space. All three are new commands for me. I Without arguments vars() returns the same thing as locals(). > like the idea of adopting either vars or locals instead of dir as it > sets up the value for me to use. I will play with them both a little > more and read up on them to learn there uses and limitations. The key > step for me is still to be able to automatically query the key names > from vars or locals for what type the variable is. In my previous > post I discussed using eval and the string in the key name such as > > eval('type(%s)'%vars().keys()[0]) >>> eval('type(%s)'%vars().keys()[0]) >>> vars().keys()[0] '__builtins__' >>> vars().values()[0] >>> type(vars().values()[0]) >>> for name, obj in vars().items(): ... print "%s (%s)" % (name, type(obj)) ... __builtins__ () __name__ () __doc__ () __package__ () From prologic at shortcircuit.net.au Mon Dec 22 00:46:29 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Dec 2008 15:46:29 +1000 Subject: Twisted for non-networking applications In-Reply-To: <9faa4fa5-6fd1-4ebb-bf1b-382a7d74ba0a@d42g2000prb.googlegroups.com> References: <82e49b84-43c9-452f-a139-c77378c12908@a12g2000pro.googlegroups.com> <9faa4fa5-6fd1-4ebb-bf1b-382a7d74ba0a@d42g2000prb.googlegroups.com> Message-ID: On Mon, Dec 22, 2008 at 3:25 PM, RajNewbie wrote: > I was unable to see documentation explaining this - so asking again. Documentation is available here: http://trac.softcircuit.com.au/circuits/wiki/docs And here: pydoc circuits The code itself is heavily documented. I'm still writing better online references, tutorials and what not ... :) Please see the examples/ > Suppose the event handlers in the component is doing blocking work, > how is it handled? You have a few options. 1. Do your work in a thread. 2. Do your work in a process. You could utilize the Worker component for such things. I'm also building a Process component that uses the multiprocessing module. > I went through ciruits.core, but was unable to understand exactly how > blocking mechanisms are handled. They aren't. It's up to you to handle such situations. If your "event-handler" blocks, everything, it will block every other event handler from being processes. In what situation would you have this ? I'm curious :) > My scenario is as follows: > I have 4 loops, 1 small and high priority, 3 quite large and blocking > (takes upto 3 seconds) and comparatively low priority. > The small loops goes through everytime and does some work - and > optionally uses the data sent by the other 3 loops. > I do not want the smaller loop to get blocked by the other loops. This sounds complex :) What is your application ? What's being processes ? > So, if the event handler does blocking work, can that cause the whole > loop to block? Yes. If you decide to use circuits, I suggest you restructure your program. Try to do your work (if it's blocking) in Worker components (threads). cheers James From christophedeze at gmail.com Tue Dec 23 04:36:56 2008 From: christophedeze at gmail.com (Toff) Date: Tue, 23 Dec 2008 01:36:56 -0800 (PST) Subject: join a samba domain References: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> <494fd597$0$90267$14726298@news.sunsite.dk> <73194a24-f14e-46f1-8789-886ba4729084@r15g2000prd.googlegroups.com> <1a326512-3c74-404d-9c51-fde35f39702e@t39g2000prh.googlegroups.com> Message-ID: Or maybe could I try with LoadLibrary("netapi32.dll"); and the netjoindomain function ? but it doesn't look very easy .... From zaz600 at gmail.com Wed Dec 24 10:09:30 2008 From: zaz600 at gmail.com (NoName) Date: Wed, 24 Dec 2008 07:09:30 -0800 (PST) Subject: SyntaxError: encoding problem: with BOM References: <6res8tF1do1sU1@mid.uni-berlin.de> Message-ID: <400f176b-bd9a-4f26-b01b-1aa7c7dcf5ac@z6g2000pre.googlegroups.com> On 25 ???, 00:37, "Diez B. Roggisch" wrote: > NoName schrieb: > > > i have 1.py in cp866 encoding: > > > # -*- coding: cp866 -*- > > print ("ff") > > > It's not work in Python 3.0 > > Error: > > > File "", line 1 > > SyntaxError: encoding problem: with BOM > > > what's wrong? > > I can only guess, but just because you write the coding-header that > doesn't mean that the editor you use does actually *use* that encoding. > What I presume it does is to use utf-8, and write that stupid BOM > microsoft uses for denoting utf-8-content as first byte. Try using a > different editor, or alter it's settings to really use your desired > encoding. > > Diez I used Far Manager editor. and it *really* used cp866 I can print hex dump of source file. I don't want to use UTF-8 for py-file! From clp at rebertia.com Tue Dec 2 18:22:41 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 2 Dec 2008 15:22:41 -0800 Subject: Simple ini Config parser examples needed In-Reply-To: <4935BBE5.3020607@g.nevcal.com> References: <47c890dc0812021331m1fe3f420kce9bcb07df5ae44e@mail.gmail.com> <4935BBE5.3020607@g.nevcal.com> Message-ID: <47c890dc0812021522g7f42b00o2a831bac1e15aa05@mail.gmail.com> On Tue, Dec 2, 2008 at 2:51 PM, Glenn Linderman wrote: > On approximately 12/2/2008 1:31 PM, came the following characters from the > keyboard of Chris Rebert: >> >> On Tue, Dec 2, 2008 at 1:18 PM, RON BRENNAN >> wrote: >> >>> >>> Hello, >>> >>> I have a very simple ini file that I needs parsed. What is the best way >>> I >>> can parse an ini file that doesn't include sections? *Bangs head against wall repeatedly* I merely glossed the question and missed that all-important second sentence! fsck! My apologies, I shouldn't write email before having coffee :) Fortunately Tim followed quickly with the correct answer to the OP. - Chris >>> >>> As in: >>> >>> >> >> Since it appears that ConfigParser requires at least one section >> header, I'll assume the file starts with the following line: >> >> [main] >> >>> >>> person=tall >>> height=small >>> shoes=big >>> >>> >>> Thats it. Can anyone help me? >>> >> >> Completely untested: >> >> import ConfigParser >> config = ConfigParser.RawConfigParser() >> config.readfp(open("path/to/file.cfg")) >> config.get("main", "height") #==> "small" >> >> Cheers, >> Chris >> > > Of course the OP question was that the line you assume isn't there. But if > the ini is simple, maybe it is short enough to read into a string, then > prepend the line, then parse with ConfigParser. > > -- > Glenn -- http://nevcal.com/ > =========================== > A protocol is complete when there is nothing left to remove. > -- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking > > -- Follow the path of the Iguana... http://rebertia.com From duncan.booth at invalid.invalid Tue Dec 9 08:05:36 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Dec 2008 13:05:36 GMT Subject: how to get a beep, OS independent ? References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> <6q6jf8Fau4iiU2@mid.individual.net> Message-ID: greg wrote: > Duncan Booth wrote: >> If I'm logged in to one of my servers in a large datacentre then I >> don't what that system to beep as that would be pretty useless. > > It also might cause the datacentre operators some consternation > when one of their servers starts mysteriously beeping... > That could be fun, especially if I can have a proximity sensor so I can stop the beeping whenever someone comes near the rack. :^) -- Duncan Booth http://kupuguy.blogspot.com From googler.1.webmaster at spamgourmet.com Fri Dec 5 03:26:58 2008 From: googler.1.webmaster at spamgourmet.com (googler.1.webmaster at spamgourmet.com) Date: Fri, 5 Dec 2008 00:26:58 -0800 (PST) Subject: Python C API Message-ID: <54fbb55d-3c39-459d-86a3-302b69721f0f@s20g2000yqh.googlegroups.com> Hi :) I have a main() function of my app which intializes the Python Interpreter and some other stuff. When I am finished I call: PyGILState state = PyGILState_Ensure() //call PyRun_String() PyGILStateRelease(state); The first question is, I found out the API contains other commands lik PyEval_AcquireLock(). I don't really understand if I have to use them too, could anyone explain? Thanks. Okay, back to topic. In PyRun_String() I call a wrapped function. This wrapped function does some internal calculations and takes a pointer to another function which is called in another thread while it calculates the stuff. void MyProgressbar(Real p, void* hook) // this function wil be called in another thread { PyGILState_STATE gilstate = PyGILState_Ensure(); PyObject* func = (PyObject*)hook; //do some python stuff PyGILState_Release(gilstate) } PyObject *pyMyFunction(PyObject *pSelf, PyObject *args, PyObject *keywords) { static char *kwlist[] = {"hook", NULL}; PyObject *hook=NULL; if (!PyArg_ParseTupleAndKeywords(args, keywords, "O!", kwlist, &PyFunction_Type, &hook)) return NULL; LONG ok = MyFunction(myprogress, hook); //hook is a pointer which is passed to the threaded function. Py_RETURN_INT(ok); } I want to do the same in Python. I want to pass a reference of a function to the function which is called from the other thread. But it stops (not crash) here: PyGILState_STATE gilstate = PyGILState_Ensure (); What can I do? Thank you very much. From zxo102 at gmail.com Mon Dec 29 00:08:12 2008 From: zxo102 at gmail.com (zxo102) Date: Sun, 28 Dec 2008 21:08:12 -0800 (PST) Subject: How to display Chinese in a list retrieved from database via python References: <22be506d-91c2-4727-ace7-2e3382b6d214@g3g2000pre.googlegroups.com> <979fdf6d-0500-47ba-87fd-0f0361ca3059@p2g2000prf.googlegroups.com> <19680ed2-c78f-4ab9-8ca0-8ce26fd5b6a7@o4g2000pra.googlegroups.com> Message-ID: <2560a6e0-c103-46d2-aa5a-8604de4d1968@b38g2000prf.googlegroups.com> On 12?27?, ??4?08?, "Gabriel Genellina" wrote: > En Sat, 27 Dec 2008 03:03:24 -0200,zxo102 escribi?: > > > > > On 12?26?, ??3?16?, "Mark Tolonen" ? > > wrote: > > >> I was able to display ?? successfully with this code: > > >> f=open('test.html','wt') > >> f.write(''' > >> > >> test > >> \xd6\xd0\xce\xc4''') > >> f.close() > > > Mark, > > ? ?I have exactly copied your code into the htdocs of my Apache > > server, > > > > > > > test > > \xd6\xd0\xce\xc4 > > > but it still shows me \xd6\xd0\xce\xc4. Any ideas? > > That's not the same thing as Mark T. said. > The original was Python code to *write* a test file that you could open in > a browser. Things like "\xd6\xd0" are escape sequences interpreted by > Python, not meant to literally appear in a file. Like \n -- it means > "start a new line", one wants a new line in the output, *not* a backslash > and a letter n. "\xd6\xd0" generate *two* bytes, not eight. If the file is ? > interpreted as containing latin-1 characters, you see them as ??. But due ? > to the "charset=gb2312" line, those two bytes together make the ideograph ? > ?. > > So, write the Python code (from f=open... up to f.close()) in a file and > execute it. Then open the generated test.html file. You should see the two > ideographs. > > -- > Gabriel Genellina Thanks for your explanation. The example works now. It is close to my real case. I have a list in a dictionary and want to insert it into the html file. I test it with following scripts of CASE 1, CASE 2 and CASE 3. I can see "??" in CASE 1 but that is not what I want. CASE 2 does not show me correct things. So, in CASE 3, I hacked the script of CASE 2 with a function: conv_list2str() to 'convert' the list into a string. CASE 3 can show me "??". I don't know what is wrong with CASE 2 and what is right with CASE 3. Without knowing why, I have just hard coded my python application following CASE 3 for displaying Chinese characters from a list in a dictionary in my web application. Any ideas? Happy a New Year: 2009 ouyang CASE 1: ######################################################## f=open('test.html','wt') f.write(''' test ''') f.close() CASE 2: ####################################################### mydict = {} mydict['JUNK'] = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce \xc4'] f_str = ''' test ''' f_str = f_str%mydict f=open('test02.html','wt') f.write(f_str) f.close() CASE 3: ################################################### mydict = {} mydict['JUNK'] = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce \xc4'] f_str = ''' test ''' import string def conv_list2str(value): list_len = len(value) list_str = "[" for ii in range(list_len): list_str += '"'+string.strip(str(value[ii])) + '"' if ii != list_len-1: list_str += "," list_str += "]" return list_str mydict['JUNK'] = conv_list2str(mydict['JUNK']) f_str = f_str%mydict f=open('test03.html','wt') f.write(f_str) f.close() From rhamph at gmail.com Mon Dec 8 14:32:18 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 8 Dec 2008 11:32:18 -0800 (PST) Subject: Rich Comparisons Gotcha References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Dec 8, 11:54?am, Robert Kern wrote: > Rhamphoryncus wrote: > > On Dec 7, 4:20 pm, Steven D'Aprano > cybersource.com.au> wrote: > >> On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: > >>> Rasmus Fogh wrote: > >>>> Current behaviour is both inconsistent and counterintuitive, as these > >>>> examples show. > >>>>>>> x = float('NaN') > >>>>>>> x == x > >>>> False > >>> Blame IEEE for that one. Rich comparisons have nothing to do with that > >>> one. > >> There is nothing to blame them for. This is the correct behaviour. NaNs > >> should *not* compare equal to themselves, that's mathematically > >> incoherent. > > > Mathematically, NaNs shouldn't be comparable at all. ?They should > > raise an exception when compared. ?In fact, they should raise an > > exception when *created*. ?But that's not what we want. ?What we want > > is a dummy value that silently plods through our calculations. ?For a > > dummy value it seems a lot more sense to pick an arbitrary yet > > consistent sort order (I suggest just above -Inf), rather than quietly > > screwing up the sort. > > Well, there are explicitly two kinds of NaNs: signalling NaNs and quiet NaNs, to > accommodate both requirements. Additionally, there is significant flexibility in > trapping the signals. Right, but most of that's lower level. By the time it reaches Python we only care about quiet NaNs. > > Regarding the mythical IEEE 754, although it's extremely rare to find > > quotations, I have one on just this subject. ?And it does NOT say "x > > == NaN gives false". ?It says it gives *unordered*. ?It is C and > > probably most other languages that turn that into false (as they want > > a dummy value, not an error.) > > >http://groups.google.ca/group/sci.math.num-analysis/browse_thread/thr... > > Table 4 on page 9 of the standard is pretty clear on the subject. When the two > operands are unordered, the operator == returns False. The standard defines how > to do comparisons notionally; two operands can be "greater than", "less than", > "equal" or "unordered". It then goes on to map these notional concepts to > programming language boolean predicates. Ahh, interesting. Still though, does it give an explanation for such behaviour, or use cases? There must be some situation where blindly returning false is enough benefit to trump screwing up sorting. From google at mrabarnett.plus.com Sat Dec 6 12:54:55 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 06 Dec 2008 17:54:55 +0000 Subject: "as" keyword woes In-Reply-To: <88579d9a-df52-49b9-a6fe-53c8f4524bf3@j39g2000yqn.googlegroups.com> References: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> <0147dc24$0$20670$c3e8da3@news.astraweb.com> <0148b217$0$20670$c3e8da3@news.astraweb.com> <7d0lj4d9hai2f87r30erc4l1ir85osbfg7@4ax.com> <88579d9a-df52-49b9-a6fe-53c8f4524bf3@j39g2000yqn.googlegroups.com> Message-ID: <493ABC6F.5090501@mrabarnett.plus.com> Mensanator wrote: > On Dec 6, 8:16?am, Wolfgang Strobl wrote: >> Dennis Lee Bieber : >> >>> On 05 Dec 2008 05:21:25 GMT, Steven D'Aprano >>> declaimed the following in >>> comp.lang.python: >>>> On Thu, 04 Dec 2008 08:44:19 -0800, Matimus wrote: >>>>> The point was that there >>>>> is that new releases don't _break_ anything. >>>> But that's clearly not true, because the OP is pointing out that the new >>>> release from 2.5 to 2.6 *does* break his code. >>> ? ?One now has to ask what "break" really meant... For this example, >>> the change did not break Python SYNTAX -- just a complaint about using >>> what is now a reserved word as an object name. >> Of course it does: >> >> C:\Python26>python >> Python 2.6 (r26:66721, Oct ?2 2008, 11:35:03) [MSC v.1500 32 bit >> (Intel)] on win 32 >> Type "help", "copyright", "credits" or "license" for more information.>>> as=2 >> >> ? File "", line 1 >> ? ? as=2 >> ? ? ?^ >> SyntaxError: invalid syntax > > I disagree. "Broken" is something you can't work > around. In this case, simply saying as_=2 works fine. > > A better example of broken was when the gmpy module > wouldn't solve a certain linear congruence problem > because the problem was not invertible. But > mathematically, solving a linear congruence does > NOT depend on the problem being invertible. It was > the ALGORITHM that depended on the problem being > invertible and there was nothing the user could do > to make the algorithm behave properly. The algorithm > had to be altered to fix the special case of a > solvable linear congruence not being invertible. > >> >> >> Making a former syntactically valid ?two letter name a reserved word in >> 2.6 was a mistake, IMHO. > > I think you're in the minority there. > I think that its special use is clear from the syntax, so IMHO it could've been left for Python 3, but I'm not going to lose any sleep over it. >> What's next? What about making i,j,k, x and y >> reserved words in 2.7? =:-/ > > Yeah, right. That'll happen. You ought to be more > concerned about real problems. > From Sengly.Heng at gmail.com Tue Dec 23 06:58:24 2008 From: Sengly.Heng at gmail.com (Sengly) Date: Tue, 23 Dec 2008 03:58:24 -0800 (PST) Subject: Very basic question References: <21ab1917-f0c9-48fb-baa9-02e5bf229bf5@s9g2000prm.googlegroups.com> <38f6b145-8615-4bcc-88f6-1988f9a7f68f@q30g2000prq.googlegroups.com> Message-ID: <91ccfbbd-806c-4770-a121-597df3f4aff3@r10g2000prf.googlegroups.com> Thank you very much everyone. Regards, -- Sengly From bdesth.quelquechose at free.quelquepart.fr Mon Dec 15 16:27:27 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 15 Dec 2008 22:27:27 +0100 Subject: %s place holder does not let me insert ' in an sql query with python. In-Reply-To: References: <1229345178.31093.24.camel@krishna-laptop> <1229348763.31093.38.camel@krishna-laptop> Message-ID: <4946d975$0$15020$426a74cc@news.free.fr> Joe Strout a ?crit : > On Dec 15, 2008, at 6:46 AM, Krishnakant wrote: > >> in this case, I get a problem when there is ' in any of the values >> during insert or update. > > That's because ' is the SQL string literal delimiter. But any > SQL-compliant database allows you to "escape" an apostrophe within a > string literal by doubling it. So for each of your values, just do: > > value = value.replace("'", "''") > > before stuffing them into your INSERT or UPDATE statement. (If these > values come from the user, and especially if they come over the network, > then you probably want to do a few other replacements; google "SQL > injection" for details.) Or just learn to make proper use of the db-api, ie use cursor.execute( "select yadda from mytable where foo=%s or bar=%s", (foo, bar) ) NB : replace '%s' with '?' or whatever is the correct placeholder for you particular db-api connector. From brendandetracey at yahoo.com Fri Dec 12 09:46:38 2008 From: brendandetracey at yahoo.com (Brendan) Date: Fri, 12 Dec 2008 06:46:38 -0800 (PST) Subject: Reading online zip files - zipfile and zlib, wbits References: Message-ID: <21ba0ff5-7698-481a-851c-80b9ddcd5814@q26g2000prq.googlegroups.com> On Dec 12, 10:25?am, Brendan wrote: > I am fooling around with accessing contents of zip files online. I > download the tail end of the zip and use zipfile to get the zip > central directory structure. I download the section of the zip file I > need, directly read the zip file headers and use that information with > zlib to uncompress the data. The files I am examining will always be > compressed using deflate, with a wbits value of -15(minus for > headerless data because I am unsure whether the zip file header is > what zlib expects). > > I can not find anywhere in the PK Zip Application notes (http://www.pkware.com/documents/casestudies/APPNOTE.TXT) how to > determine the value I should uze for wbits with zlib.decompress. I > have determined it is -15 from experimentation. Does anyone know the > answer to this? Okay, I found part of the answer here in the zip app notes [quote] general purpose bit flag: (2 bytes) Bit 0: If set, indicates that the file is encrypted. (For Method 6 - Imploding) Bit 1: If the compression method used was type 6, Imploding, then this bit, if set, indicates an 8K sliding dictionary was used. If clear, then a 4K sliding dictionary was used. Bit 2: If the compression method used was type 6, Imploding, then this bit, if set, indicates 3 Shannon-Fano trees were used to encode the sliding dictionary output. If clear, then 2 Shannon-Fano trees were used. (For Methods 8 and 9 - Deflating) Bit 2 Bit 1 0 0 Normal (-en) compression option was used. 0 1 Maximum (-exx/-ex) compression option was used. 1 0 Fast (-ef) compression option was used. 1 1 Super Fast (-es) compression option was used. [/quote] Now I just don't understand Why Normal deflate corresponds to 15 wbits, and why I have to use headerless for the data, i.e. wbits = -15. From Russ.Paielli at gmail.com Sat Dec 6 10:21:40 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 6 Dec 2008 07:21:40 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> <20081206133704.1bed455c@usenot.de> Message-ID: <4d1a952e-25ad-4b36-ba46-ed35758331b0@e1g2000pra.googlegroups.com> On Dec 6, 4:37?am, Andreas Waldenburger wrote: > On Sat, 6 Dec 2008 13:32:58 +0100 Andreas Waldenburger > > wrote: > > On Sat, 6 Dec 2008 04:02:54 -0800 (PST) bearophileH... at lycos.com > > suggested: > > > > class C: > > > ? ? def $method(arg): > > > ? ? ? ? $value = arg > > > > [snip] > > > [snip] > > "self" is a speaking identifier, "$" isn't. > > Also, nothing prevents you from replacing "self" with "s" if you really > want it short. Same effect as your "s" suggestion (OK, plus one "."). Yes, you can always use "s". But single-letter identifiers are not usually a good idea, because they are hard to search on. A slightly better option is "S", which is a little better for searching but not as good as "$". I have considered using "S" extensively in my code, but I hesitate because it is not recognized in official Python coding standards. From prabhu.ranjith at gmail.com Wed Dec 10 19:50:22 2008 From: prabhu.ranjith at gmail.com (free online study about computer language) Date: Wed, 10 Dec 2008 16:50:22 -0800 (PST) Subject: @ you can study through online freely all the computer language. Easy way and free registration. Visit www.tiketin.blogspot.com @ Message-ID: <1ed142af-346c-451c-a3ec-0d88170828d3@x8g2000yqk.googlegroups.com> Now easy way to clear all your computer language doubts and to learn more visit www.tiketin.blogspot.com everything is free. You can also get e-books freely. No need to waste time and money visit www.tiketin.blogspot.com way to learn from your home itself visit www.tiketin.blogspot.com From david at boddie.org.uk Thu Dec 18 18:28:00 2008 From: david at boddie.org.uk (David Boddie) Date: Fri, 19 Dec 2008 00:28:00 +0100 Subject: how to dock another application under Linux ? References: Message-ID: On Thursday 18 December 2008 20:09, Stef Mientki wrote: > Under windows it's fairly easy to capture an application > and dock in to your own wxPython application, > something like this: > - start the external application from within wxPython > - give the caption of the application a special name > - find de windows handler of the applications mainform > - tell the applications mainform, that some wxpanel is the parent > > I use this to dock VPython in wxPython. > > Is there a similar solution for Linux ( and Mac) ? On X11 systems, you can use the X11Embed protocol to do this. I would be surprised if wxWidgets doesn't have a component for this given that there's one for GTK+: http://library.gnome.org/devel/gtk/stable/GtkSocket.html David From ron.longo at cox.net Thu Dec 4 15:02:06 2008 From: ron.longo at cox.net (Ron Longo) Date: Thu, 4 Dec 2008 12:02:06 -0800 (PST) Subject: Announcement: MindTree for Python beta -- feedback appreciated Message-ID: <20841316.post@talk.nabble.com> I would like to take the time to announce the first public beta for Mindtree 2. MindTree is an Information Organizer/Outliner, note taker, web publisher written for Python 2.6 and Qt4. MindTree 2.x is a complete rewrite. The original MindTree was written for Tkinter and Tix. The original product, which never got past alpha version, has reached end-of-life. Its current state is unknown and unsupported. The MindTree project can be found and downloaded here: http://code.google.com/p/mindtree/ Please note that this is a first beta of a complete rewrite. It is suggested that this version of the software be used for evaluation purposes only. MindTree is targeted for those who have a need to organize and publish to the web large amounts of information. This information is organized in the form of an outline. The Application GUI displays a dual-pane editor in which the outline is viewed as a collapsible tree on the left and notes for the outline entries are displayed and edited on the right. MindTree will take any outline and create a web site from it which has a similar layout and functionality to the MindTree desktop application complete with collapsible/navigable tree on the left and notes on the right. Some future plans for MindTree include ReStructured Text editing, improved text styling capabilities, Inclusion of structured text objects into articles such as lists and tables and customizable HTML generation. Thanks for you interest, Ron Longo -- View this message in context: http://www.nabble.com/Announcement%3A--MindTree-for-Python-beta----feedback-appreciated-tp20841316p20841316.html Sent from the Python - python-list mailing list archive at Nabble.com. From alwaseem307ster at yahoo.com Fri Dec 19 07:17:46 2008 From: alwaseem307ster at yahoo.com (klia) Date: Fri, 19 Dec 2008 04:17:46 -0800 (PST) Subject: importing csv file into sqlite In-Reply-To: <7f64f5c6-b130-4f9b-a670-6b32eccba550@n33g2000pri.googlegroups.com> References: <21067453.post@talk.nabble.com> <7f64f5c6-b130-4f9b-a670-6b32eccba550@n33g2000pri.googlegroups.com> Message-ID: <21090356.post@talk.nabble.com> John Machin wrote: > > On Dec 18, 6:20?pm, klia wrote: >> klia wrote: >> >> > hey guys, i have a hug .csv file which i need to insert it into sqlite >> > database using python. >> > my csv data looks like this >> > Birthday2,12/5/2008,HTC,this is my birthday >> > Sea,12/3/2008,kodak,sea >> > birthday4,14/3/2009,samsung,birthday >> > love,17/4/2009,SONY,view of island >> >> > can any one give me a head start codes. >> >> > thanks in advance >> >> guys so far i came out with this but i get this error >> waseem at Linux:~/Project2$ python experment.py >> Traceback (most recent call last): >> ? File "experment.py", line 13, in >> ? ? curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item) >> sqlite3.ProgrammingError: Incorrect number of bindings supplied. The >> current >> statement uses 4, and there are 1 supplied. >> >> here's the codes >> >> import sqlite3 >> import csv >> >> f = open('/home/waseem/Project2/photos.txt') >> csv.field_size_limit(100000) #see below! > > I see nothing "below" that looks at all like an attempt to justify > setting the field size limit to 100000 -- why are you doing that? > Tends to make one suspect a problem with your delimiter and/or your > line separator. > >> input = csv.reader(f, delimiter='\t') > > Why \t??? Your data examples show commas -- could this be why you are > getting one field per line (as Peter has pointed out)? > >> conn = sqlite3.connect('/home/waseem/Project2/picutres.db') > > Is it really called "picutres" instead of "pictures", or are you > typing the code that you ran again from (your) memory? > >> curse = conn.cursor() >> >> curse.execute('CREATE TABLE photos (Name VARCHAR(100) PRIMARY KEY, Date >> INTEGER, Make VARCHAR(50), Tag VARCHAR(100))') > > [OT but to save the next question] > The column named "Date" is defined to be INTEGER but the data from the > CSV file will be a str object e.g. "12/5/2008" ... I know sqlite > cheerfully regards column types as vague reminders rather than > enforceable constraints on your input, but wouldn't you like to > convert your dates to e.g. "2008-05-12" before you poke them in? You > may want to use "ORDER BY Date" at some stage, and so that ORDER BY > isn't whacked and GROUP BY doesn't give ludicrous results, wouldn't it > be a good idea to crunch 12/5/2008 and 12/05/2008 into a common format > so that they compare equal? >> >> for item in input: > > I strongly suggest that you try to get a clue about exactly what you > are getting from the csv reader e.g. > > for line_num, item in enumerate(input_renamed_as_suggested_by_anor): > print line_num, repr(item) > >> ? ? ? ? curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item) >> curse.commit() >> > > HTH, > John > -- > http://mail.python.org/mailman/listinfo/python-list > > hey guys i took all of your suggestion but my goal ain't yet achieved :-(( these are the codes after changes, john i couldn't really catch what do you mean by renaming input, is it just normal renaming.i am testing the code on just simple .csv file with few data in as follows before trying on my hug csv file but still no joy "Bithday",12-05-08,"HTC","this is my birthday" "Sea",12-03-08,"kodak","sea" "girl","14-03-2009","samsung","birthday" "love","17-04-2009","SONY","view of island" import sqlite3 import csv f = open('/home/waseem/Project2/photos.csv') input = csv.reader(f, delimiter=',') conn = sqlite3.connect('/home/waseem/Project2/pictures.db') curse = conn.cursor() curse.execute('CREATE TABLE photos (Name VARCHAR(100) PRIMARY KEY, Date INTEGER, Make VARCHAR(50), Tag VARCHAR(100))') for row in input: curse.execute('INSERT INTO photos VALUES (?,?,?,?)', '*row') curse.commit() this time i got this error waseem at Linux:~/Project2$ python experment.py Traceback (most recent call last): File "experment.py", line 12, in curse.execute('INSERT INTO photos VALUES (?,?,?,?)', '*row') sqlite3.IntegrityError: column Name is not unique i removed the primary key and single quotation mark for '*row' to just *row but i got the old error which is waseem at Linux:~/Project2$ python experment.py Traceback (most recent call last): File "experment.py", line 11, in curse.execute('INSERT INTO photos VALUES (?,?,?,?)', *row) TypeError: function takes at most 2 arguments (5 given) -- View this message in context: http://www.nabble.com/importing-csv-file-into-sqlite-tp21067453p21090356.html Sent from the Python - python-list mailing list archive at Nabble.com. From yameenaziz at gmail.com Sat Dec 13 17:57:54 2008 From: yameenaziz at gmail.com (yameenaziz at gmail.com) Date: Sat, 13 Dec 2008 14:57:54 -0800 (PST) Subject: http://1000earndollars.blogspot.com/ Message-ID: "How To Make $1,000,000 THIS YEAR With our Online Business" From aleksandr.goretoy at gmail.com Sat Dec 27 18:18:37 2008 From: aleksandr.goretoy at gmail.com (alex goretoy) Date: Sat, 27 Dec 2008 17:18:37 -0600 Subject: parsing csv files class In-Reply-To: References: <49562755.6050205@byoteki.com> Message-ID: It's main concern is to grab the file into the buffer for use in other classes. The self.soc.me_him is just so I know when its ENTERING or EXITING in that function when I run it in terminal. It's prints it in color. My main concern right now is to add error handling. I'm still learning how to use assert and yield, but I got try,except down pat. All this class does is grabs the file either from http or local storage into a buffer and I use that in other classes. I want to add support for creating creating csv as well. I read the doc on csv and will try some things out soon. Thanks for helping me. On Sat, Dec 27, 2008 at 2:15 PM, Gabriel Genellina wrote: > En Sat, 27 Dec 2008 11:02:13 -0200, Gary M. Josack > escribi?: > >> alex goretoy wrote: >> > > I know it's messy with all those self.soc.* functions, but it works in one >>> of my current project. I just want to make it more pythonic I also want to >>> add capability for makeing csv file if I give it input like: >>> 1234,something nice, hey this is something nice >>> 2468,something else, something else >>> >> > reader = csv.reader(file(filename, "rb")) >>> try: >>> for row in reader: >>> self.buffer.append(row) >>> s,a=[],{} >>> >> > Do you know that there is a csv module in the standard library already? >> > > I'd say he already knows, he even used it in the code. > > To Alex G.: I didn't understand what's the purpose of this class. Probably > you want to do too much things in the same place; looks like it has multiple > concerns, and that's not a good idea usually. > > -- > Gabriel Genellina > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? -- ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? -------------- next part -------------- An HTML attachment was scrubbed... URL: From p.f.moore at gmail.com Thu Dec 11 14:51:35 2008 From: p.f.moore at gmail.com (Paul Moore) Date: Thu, 11 Dec 2008 11:51:35 -0800 (PST) Subject: Best way of debigging a C extension Message-ID: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> I'm writing a C extension. My environment is Python 2.5, with the mingw compiler, on Windows XP. At the moment I'm debugging by scattering printf() statements around, but it's not always easy. Is there a better way of debugging - particularly for diagnosing crashes? I have gdb (although I've hardly used it, but I can learn :-)) but if I try building my extension with python setup.py build --debug, I get an error because -lpython25_d does not exist. I'm not surprised by this, as I don't have a debug build of Python - but that should be OK, I'm only looking for debugging info from my code. I tried copying libpython25.a to libpython25_d.a - my extension now builds, but the resulting pyd is XXX_d.pyd, which won't import. If I rename this to XXX.pyd, I can import and things seem to work - but it seems a bit of a roundabout way of doing things. Is there a simpler way that I've missed? It seems to me that this (debugging a C extension without compiling a debug build of Python) would be a fairly common situation, so I would have expected a "cleaner" way of doing it. At the very least, a documentation patch to explain the best way of doing things might be useful. I'll see what I can put together based on the responses I get here. Thanks, Paul. From honey33145 at gmail.com Wed Dec 3 08:20:56 2008 From: honey33145 at gmail.com (navneet khanna) Date: Wed, 3 Dec 2008 18:50:56 +0530 Subject: Where does the clr in IronPython look the dll Message-ID: Hello Everybody I am trying to import dll with clr.AddReference("TCdll") I am getting the following error. Traceback (most recent call last): File "", line 1, in clr.AddReference("TCdll") FileNotFoundException: Unable to find assembly 'TCdll'. at Python.Runtime.CLRModule.AddReference(String name) I have loaded the dll in system32 folder. Have I loaded the dll at the right place or do I need to place it anywhere else? Waiting for your replies. Regards Navneet -------------- next part -------------- An HTML attachment was scrubbed... URL: From geekmail at usenot.de Thu Dec 4 14:41:59 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Thu, 4 Dec 2008 20:41:59 +0100 Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> Message-ID: <20081204204159.716f98b4@usenot.de> On Thu, 4 Dec 2008 09:30:52 -0800 "Daniel Fetchinson" wrote: > >> As you have probably guessed: nothing changed here. > >> Also see:http://www.python.org/dev/peps/pep-0666/ > > > > What? Do you mean it's possible to mix tabs and spaces still? Why? > > Why not? > +1 -- My real email address is constructed by swapping the domain with the recipient (local part). From sjmachin at lexicon.net Sat Dec 6 22:30:40 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 6 Dec 2008 19:30:40 -0800 (PST) Subject: Python 3.0 automatic decoding of UTF16 References: <55d79070-0c11-4fb9-8cf5-b8cc7c54b5d2@v42g2000yqv.googlegroups.com> <0e37191f-3672-4313-bc5c-ffcd904e4796@k24g2000pri.googlegroups.com> Message-ID: On Dec 7, 9:34?am, John Machin wrote: > On Dec 7, 9:01?am, David Bolen wrote: > > > Johannes Bauer writes: > > > This is very strange - when using "utf16", endianness should be detected > > > automatically. When I simply truncate the trailing zero byte, I receive: > > > Any chance that whatever you used to "simply truncate the trailing > > zero byte" also removed the BOM at the start of the file? ?Without it, > > utf16 wouldn't be able to detect endianness and would, I believe, fall > > back to native order. > > When I read this, I thought "O no, surely not!". Seems that you are > correct: > [Python 2.5.2, Windows XP] > | >>> nobom = u'abcde'.encode('utf_16_be') > | >>> nobom > | '\x00a\x00b\x00c\x00d\x00e' > | >>> nobom.decode('utf16') > | u'\u6100\u6200\u6300\u6400\u6500' > > This may well explain one of the Python 3.0 problems that the OP's 2 > files exhibit: data appears to have been byte-swapped under some > conditions. Possibility: it is reading the file a chunk at a time and > applying the utf_16 encoding independently to each chunk -- only the > first chunk will have a BOM. Well, no, on further investigation, we're not byte-swapped, we've tricked ourselves into decoding on odd-byte boundaries. Here's the scoop: It's a bug in the newline handling (in io.py, class IncrementalNewlineDecoder, method decode). It reads text files in 128- byte chunks. Converting CR LF to \n requires special case handling when '\r' is detected at the end of the decoded chunk n in case there's an LF at the start of chunk n+1. Buggy solution: prepend b'\r' to the chunk n+1 bytes and decode that -- suddenly with a 2-bytes-per- char encoding like UTF-16 we are 1 byte out of whack. Better (IMVH[1] O) solution: prepend '\r' to the result of decoding the chunk n+1 bytes. Each of the OP's files have \r on a 64-character boundary. Note: They would exhibit the same symptoms if encoded in utf-16LE instead of utf-16BE. With the better solution applied, the first file [the truncated one] gave the expected error, and the second file [the apparently OK one] gave sensible looking output. [1] I thought it best to be Very Humble given what you see when you do: import io print(io.__author__) Hope my surge protector can cope with this :-) ^%!//() NO CARRIER From fankaicn at gmail.com Mon Dec 29 20:30:16 2008 From: fankaicn at gmail.com (Fan Kai) Date: Mon, 29 Dec 2008 17:30:16 -0800 (PST) Subject: Why threading.Thread has no detach method Message-ID: <63111136-5048-4321-a7b4-1655b8f35619@q30g2000prq.googlegroups.com> Does this mean terminated threads will automatically release all resouce? From has.temp3 at virgin.net Mon Dec 8 18:22:49 2008 From: has.temp3 at virgin.net (has) Date: Mon, 8 Dec 2008 15:22:49 -0800 (PST) Subject: Number of Python 3.x packages at the PyPI References: <9c1ab0f3-6686-4c0f-8a6c-12e20539f354@41g2000yqf.googlegroups.com> <493b954e$0$4021$9b622d9e@news.freenet.de> <2d656e64-deff-40ed-8066-57b6f8874ec4@b38g2000prf.googlegroups.com> <493c29a7$0$27869$9b622d9e@news.freenet.de> Message-ID: <3b2464a1-84d4-4833-ac26-accd317d978d@k19g2000yqg.googlegroups.com> On 7 Dec, 19:53, "Martin v. L?wis" wrote: > > I've had to fork my appscript project's codebase in order to add > > support for Python 3.x. I would like to distribute both 2.x and 3.x > > versions under the same package name for obvious reasons. This isn't a > > problem with eggs as the Python version number is included in each > > egg's name, but what about source distributions where both filenames > > are exactly the same (appscript-0.19.0.tar.gz)? > > I see. My initial reaction was that something should be done about this; > please do bring this up on catalog-... at python.org. OK, will do. > On second thought: can't you just include the source of both versions > in a single source distribution file? The .tar.gz distributions are built by distutils/setuptools. If I manually combine them into a single archive, I'm guessing that 'easy_install appscript' won't know how to read that custom archive when building and installing from source. (Which also raises a further question: if I do eventually manage to upload both 2.x and 3.x versions under the same PyPI entry, will easy_install know which one to download?) Thanks, has -- Control AppleScriptable applications from Python, Ruby and ObjC: http://appscript.sourceforge.net From jonas.esp at googlemail.com Fri Dec 19 06:39:40 2008 From: jonas.esp at googlemail.com (Kless) Date: Fri, 19 Dec 2008 03:39:40 -0800 (PST) Subject: [Pyrex] Compiling via setuptools Message-ID: <2198b635-7bf8-43c1-889e-66582675294d@p2g2000prf.googlegroups.com> When I use the next command in my home system: $ python setup.py develop Pyrex compiles the '.pyx' file without any problem. But after of uploading it to Pypi, and when is installed via 'easy_install' it doesn't builds any more. (I had to upload the '.c' file compiled on my system) You can see here how has been configured: http://www.bitbucket.org/ares/bcryptwrap/src/tip/setup.py and here where I had to add any files: http://www.bitbucket.org/ares/bcryptwrap/src/tip/MANIFEST.in From tenax.raccoon at gmail.com Thu Dec 18 10:20:08 2008 From: tenax.raccoon at gmail.com (Jason) Date: Thu, 18 Dec 2008 07:20:08 -0800 (PST) Subject: Selecting a different superclass References: <5adf5202-d80f-4cd1-a5f2-2d1c5f47504f@e1g2000pra.googlegroups.com> Message-ID: On Dec 18, 4:36?am, "psaff... at googlemail.com" wrote: > On 17 Dec, 20:33, "Chris Rebert" wrote: > > > superclass = TraceablePointSet if tracing else PointSet > > Perfect - many thanks. Good to know I'm absolved from evil, also ;) > > Peter Another way would be to have a factory function that builds the appropriate instance: class PointSet(object): @staticmethod def Create_Instance(*args, **keyargs): if TRACE_DATA: return TraceablePointSet(*args, **keyargs) else: return PointSet(*args, **keyargs) # Normal release class body goes here. class TraceablePointSet(object): # Normal debug class body goes here point_set = PointSet.Create_Instance() This is the way you'd do things if you wanted a mix of your release class instances and debug class instances. Perhaps there's only a certain set of initial arguments that need to be checked, or maybe the TRACE_DATA global can change. Inside the body you could also explicitly check for a "trace" parameter, like so: if keyargs.get( 'trace_data', False ): # Create debug instance .... That would allow you to create debug instances only when you want them. A variation on Chris Rebert's option is also possible: class _PointSet(object): # Normal body definition here class _TraceablePointSet(object): # Traceable body definition here if TRACE_DATA: PointSet = _TraceablePointSet else: PointSet = _PointSet Hope this helps. Python's dynamic nature loves you! --Jason From rt8396 at gmail.com Mon Dec 22 14:08:48 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 11:08:48 -0800 (PST) Subject: I always wonder ... References: <18767.54282.188749.522233@montanaro-dyndns-org.local> Message-ID: <097fc1e1-d0fa-469c-af51-0ccf8ed1542f@35g2000pry.googlegroups.com> On Dec 22, 1:02?pm, Christian Heimes wrote: > Don't worry about the trolling, Skip. I'd be more worried if nobody > trolls about Python. It would mean Python loses popularity and our work > is all in vain. Christain, you are truly an open minded, intelligent Human being. Thanks for blessing use with your wisdom here. We need more like you. Every thought, action, fact, must always be questioned, that is what makes us human! From rt8396 at gmail.com Thu Dec 18 14:52:27 2008 From: rt8396 at gmail.com (r) Date: Thu, 18 Dec 2008 11:52:27 -0800 (PST) Subject: IDLE cursor color References: <65c5974c-e5c5-46c1-9673-371a7c9ea047@a12g2000pro.googlegroups.com> Message-ID: <313c1a14-ac85-4326-a2dc-29955549a708@f11g2000vbf.googlegroups.com> in IDLE go to: Options -> Configure IDLE -> Highlighting... 1.) in the box click the word "cursor" 2.) press the button that says "Choose Color for" 3.) Pick a color and save the changes viola! you did it! :) From steve at holdenweb.com Sun Dec 21 21:01:12 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 21 Dec 2008 21:01:12 -0500 Subject: Read an image from a URL and write it to the browser In-Reply-To: References: Message-ID: McCoy Fan wrote: > On Dec 21, 7:25 am, Peter Otten <__pete... at web.de> wrote: >> McCoy Fan wrote: >>> I want to do something simple: read an image from an image URL and >>> write the image to the browser in CGI style. >>> I wrote a CGI script to do this (I'm new to Python) and got the >>> following error: >>> "FancyURLopener instance has no attribute 'tempcache'" in >> method FancyURLopener.__del__ of >> I have no idea what that error means and neither does Google. >>> Any idea where I went wrong in the code below? >>> import urllib >>> urlString = "http://www.google.com/google_logo.jpg" >>> imgStream = urllib.urlopen(urlString) >>> imgBuffer = imgStream.read() >>> imgStream.close() >>> print "Content-Type: image/jpeg" >>> print >>> print imgBuffer >> Your script runs without error here, but I can provoke the attribute error >> by passing an invalid proxies argument to urlopen(): >> >> $ python -c"import urllib; urllib.urlopen('whatever', proxies=42)" >> Traceback (most recent call last): >> File "", line 1, in >> File "/usr/lib/python2.5/urllib.py", line 75, in urlopen >> opener = FancyURLopener(proxies=proxies) >> File "/usr/lib/python2.5/urllib.py", line 609, in __init__ >> URLopener.__init__(self, *args, **kwargs) >> File "/usr/lib/python2.5/urllib.py", line 117, in __init__ >> assert hasattr(proxies, 'has_key'), "proxies must be a mapping" >> AssertionError: proxies must be a mapping >> Exception exceptions.AttributeError: "FancyURLopener instance has no >> attribute 'tempcache'" in > > ignored >> >> Please post your complete traceback, Python version, and OS to allow for a >> more detailed diagnosis. >> >> You can also try to run your script with >> >>> imgStream = urllib.urlopen(urlString) >> changed to >> >> imgStream = urllib.urlopen(urlString, proxies={}) >> >> to bypass the code in which I suppose the failure to occur. >> >> Peter > > I appreciate your response. Thank you. > > After reading your reply, I realized this must be related to the fact > that I am running this script on Google App Engine. > > It turns out, App Engine does not allow direct socket communication so > urllib is not allowed. > > Instead they provide their own library called urlfetch. So my script > should look something like this: > > from google.appengine.api import urlfetch > print 'Content-Type: text/plain' > print '' > result = urlfetch.fetch('http://www.google.com/google_logo.jpg') > print result.content > > I haven't been able to get it to work yet but at least I'm heading in > the right direction now. I'll keep digging. Thanks! You might also want to bear in mind that at least for me the content that this URL returns is HTML with embedded javascript, and not the JPEG you were expecting. That's because the URL gives a 404 response. This might be a seasonal thing: right now they are showing a "Happy Holidays" motif on their front page. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From bdesth.quelquechose at free.quelquepart.fr Sun Dec 21 09:17:45 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 21 Dec 2008 15:17:45 +0100 Subject: a small doubt In-Reply-To: References: <19ac19520812201750hb592e4dsa5ef7d2a1906c2ed@mail.gmail.com> Message-ID: <494e5dbc$0$16190$426a34cc@news.free.fr> (answering to the OP) > Piyush Anonymous wrote: >> i wrote this code >> -- >> class Person(object): >> instancesCount = 0 >> def __init__(self, title=""): >> Person.instancesCount += 1 >> self.id = "tempst" >> def testprint(self): >> print "blah blah" >> def __getattribute__(self, name): >> print "in get attribute" >> >> a = Person() >> a.testprint() >> print a.id >> ----- >> but i am getting this error >> ---- >> in get attribute >> Traceback (most recent call last): >> File "trapmethodcall1.py", line 15, in >> a.testprint() >> TypeError: 'NoneType' object is not callable >> ------ >> why is it so? __getattribute__ is called whenever an attribute or >> method is called, rt? Yes. Methods are attributes too. And __getattribute__ is the attribute lookup operator implementation - it is invoked *everytime* you have obj.attr or getattr(obj, "attr") or hasattr(obj, "attr"). IOW, you'd better *not* touch it unless 1/ you really know what you're doing, 2/ you have a very compelling reason to do so and 3/ you're ok to pay the performance hit (the default implementation in 'object' being optimized). >> or if i set __getattribute__ , i cannot have >> methods in class? Yes, you can. But you have to write a proper implementation of __getattribute__. The one above will prevent you from accessing any class or instance attribute (or, more exactly, will always return None). >> actually my aim is to trap all method calls and keep a counter which >> is update whenever method called or returned. how should i go about it? Using __getattribute__, you'll only get at the method when it is looked up (which doesn't imply it will be called). If you want to log calls and returns, you'll have to wrap the method in a decorator. You can do this either manually (ie manually adding the logger decorator on methods), via monkeypatching on class objects (but this can be tricky too), or adding a properly implemented version of __getattribute__ (but this won't work if the method is looked up on the class itself) # a Q&D method call logger def log(meth): if hasattr(meth, "logged"): # already wrapped return meth def logged(*args, **kw): if hasattr(meth, "im_self"): # wrapping a method what = "method %s " % meth else: # wrapping a function, 'self' or 'cls' is the first arg what = "method %s of object %s" % (meth, args[0]) print "%s called with %s %s" % (what, str(args), kw) try: result = meth(*args, **kw) except Exception, e: print "%s raised %s" % (what, e) raise else: print "%s returned %s" % (what, str(result)) return result logged.logged = True return logged # manual decoration class Foo(object): @log def bar(self): pass # using __getattribute__ class Foo(object): def bar(self): pass def __getattribute__(self, name): attr = super(Foo2, self).__getattribute__(name) if hasattr(attr, "im_self"): attr = log(attr) return attr Given the shortcomings of the __getattribute__ version (performance hit and only triggered on instance lookup), I'd strongly suggest the manual decoration - possibly using a flag (global setting or environment variable) to switch it off, ie: if globals().get("DEBUG", False): def log(func): def logged(*args, **kw): # wrapping a function # we assume this function is used as a method, so # 'self' or 'cls' is the first arg what = "method %s of object %s" % (func, args[0]) print "%s called with %s %s" % (what, str(args), kw) try: result = func(*args, **kw) except Exception, e: print "%s raised %s" % (what, e) raise print "%s returned %s" % (what, str(result)) return result return logged else: def log(func): # no-op return func NB : all this is pretty Q&D and mostly untested, but it should get you started. HTH From jkrukoff at ltgc.com Tue Dec 30 19:00:03 2008 From: jkrukoff at ltgc.com (John Krukoff) Date: Tue, 30 Dec 2008 17:00:03 -0700 Subject: [ANN]: circuits-1.0b1 released! In-Reply-To: References: Message-ID: <1230681603.9684.17.camel@jmk> On Wed, 2008-12-31 at 09:44 +1000, James Mills wrote: > Hi all, > > I'm pleased to announce the release of circuits-1.0b1 I'm curious, you've a number of comparisons to Twisted on your site FAQ section, but this sounds like a much closer project to Kamaelia (http://www.kamaelia.org/Home). Are these actually similar or am I missing something important that differentiates circuits? -- John Krukoff Land Title Guarantee Company From prologic at shortcircuit.net.au Mon Dec 8 09:53:32 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 9 Dec 2008 00:53:32 +1000 Subject: Beginner trying to understand functions. In-Reply-To: References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> Message-ID: On Tue, Dec 9, 2008 at 12:46 AM, Peter Otten <__peter__ at web.de> wrote: > I think the OP is using Python 3.0. What used to cause trouble Well of course he/she/it is! I'm too blind to have noticed that! :) --JamesMills -- -- -- "Problems are solved by method" From darcy at druid.net Sun Dec 7 10:14:30 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sun, 7 Dec 2008 10:14:30 -0500 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: References: <5u8o06xbqf.ln2@joeserver.homelan.net> <1mmq06x4g6.ln2@joeserver.homelan.net> Message-ID: <20081207101430.85707592.darcy@druid.net> On Sun, 07 Dec 2008 16:05:53 +0100 Johannes Bauer wrote: > But, seriously - I find that whole "while True:" and "if line == """ > construct ugly as hell, too. How can reading a file line by line be > achieved in a more pythonic kind of way? for line in open(filename): -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From lie.1296 at gmail.com Mon Dec 1 19:54:16 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 02 Dec 2008 07:54:16 +0700 Subject: end of print = lower productivity ? In-Reply-To: <493406E3.6090304@tim.thechases.com> References: <757b4e03-7d13-4758-85c4-f5224ee9853b@j35g2000yqh.googlegroups.com> <21d250f9-1477-450e-9587-c4b28d08ea00@t3g2000yqa.googlegroups.com> <981d3e99-d2b4-4455-a52a-e906bd0fe7c4@r36g2000prf.googlegroups.com> <4931D571.8070007@tim.thechases.com> <1228032887.6627.53.camel@lieryan-laptop> <493406E3.6090304@tim.thechases.com> Message-ID: <1228179256.7037.16.camel@lieryan-laptop> On Mon, 2008-12-01 at 09:46 -0600, Tim Chase wrote: > > For a proof, let's see what Google has to say about this: > > "Windows text editor". Vim is on page 3, near the turning > > point where nobody is talking about text-editor anymore and > > more about text-editor reviews. Even worse is Emacs, on page > > 6, after many other popular text-editors have been mentioned > > several times. > > That's a pretty malformed "proof": > > http://www.google.com/search?q=people%20you%20should%20listen%20to%20regarding%20choice%20of%20text-editor > > You don't appear anywhere in the top *10* pages...QED ;-) That's a pretty malformed dis-proof. > However, if you want to play that game, vim.org appears on page #1 of > > http://www.google.com/search?q=best+text+editor Not a valid proof. When people queried for "best text editor", they'll be looking for reviews instead of official site of text editor. So the placement of vim.org in the first page for "best text editor" is out of context (although I do agree that vim is one of the best editor, if not the best, in terms of power and speed). > Use what editor works for you -- but if evolution in the > language's features makes difficulties for you but not for users > of other editors, it's your editor that's the problem, not the > language. Personally, I don't think having two parens is adding much difficulties, but I symphatize those who think it is. Actually I wanna say: It's vi(m)'s fault for being too powerful making its avid users doesn't care about users of other editors. Not many text editors are nearly as powerful as vi(m) (or emacs), although most (all?) are much easier to use for day-to-day editing. but I don't want to start a war here. From duncan.booth at invalid.invalid Tue Dec 30 11:39:52 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Dec 2008 16:39:52 GMT Subject: thread, multiprocessing: communication overhead References: Message-ID: mk wrote: > This time I decided to test communication overhead in multithreaded / > multiprocess communication. The results are rather disappointing, that > is, communication overhead seems to be very high. In each of the > following functions, I send 10,000 numbers to the function / 10 threads > / 10 processes, which simply returns it in its respective way. > > > Function: notfun Best: 0.00622 sec Average: 0.00633 sec > (simple function) > > Function: threadsemfun Best: 0.64428 sec Average: 0.64791 sec > (10 threads synchronizing using semaphore) > > Function: threadlockfun Best: 0.66288 sec Average: 0.66453 sec > (10 threads synchronizing using locks) > > Function: procqueuefun Best: 1.16291 sec Average: 1.17217 sec > (10 processes communicating with main process using queues) > > Function: procpoolfun Best: 1.18648 sec Average: 1.19577 sec > (a pool of 10 processes) > > If I'm doing smth wrong in the code below (smth that would result in > performance suffering), please point it out. You aren't just timing the communication overhead: each of your functions creates a pool of 10 threads or 10 processes on every run, so your times include the startup and shutdown times. From deets at nospam.web.de Sun Dec 7 14:36:58 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 07 Dec 2008 20:36:58 +0100 Subject: Importing the re module fails In-Reply-To: <20081207202326.4b5ab73d@usenot.de> References: <20081207202326.4b5ab73d@usenot.de> Message-ID: <6q2muqFahsfnU1@mid.uni-berlin.de> Andreas Waldenburger schrieb: > This is a little puzzling. > > > Using ipython: > > [wildemar at localhost Logstuff]$ ipython > Python 2.5.2 (r252:60911, Sep 30 2008, 15:41:38) > Type "copyright", "credits" or "license" for more information. > > [snip ipython help message] > > In [1]: import re > > > This works fine. But with the regular python interpreter I get this: > > [wildemar at localhost Logstuff]$ python > Python 2.5.2 (r252:60911, Sep 30 2008, 15:41:38) > [GCC 4.3.2 20080917 (Red Hat 4.3.2-4)] on linux2 > Type "help", "copyright", "credits" or "license" for more > information. > >>> import re > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.5/re.py", line 10, in > # AB (info at pythonware.com). > AttributeError: 'module' object has no attribute 'compile' > > > What gives? Has Fedora-10 botched python or does anybody else have that > problem es well? In my re.py module on line 10, there is no import - it has way to much comments on the module beginning. So - how does your /usr/lib/python2.5/re.py look like? And what about some modules lying around (potentially *pycs) that mask system modules? Diez From chengang.beijing at gmail.com Fri Dec 12 00:28:06 2008 From: chengang.beijing at gmail.com (chengang.beijing at gmail.com) Date: Thu, 11 Dec 2008 21:28:06 -0800 (PST) Subject: how to convert '\xf0' to 0xf0 ? References: <1cb85265-1c36-4e4b-88f1-46b0ebae3dea@v5g2000prm.googlegroups.com> Message-ID: <8f5b95c0-486d-48ce-b75c-e18a86d73f50@l33g2000pri.googlegroups.com> Hi, ord('\xf0') works and it only works for char. Do you know any way to convet '\xf0\xf0' and '\xf0\xf0\xff\xfe' to integer? Br, Chen Gang On Dec 12, 12:40?pm, Steve Holden wrote: > chengang.beij... at gmail.com wrote: > > '\xf0' is the value read from a binary file, I need to change this > > kinds strings to int for further processing... > > if it is in C, then '\xf0' is an integer and it can be handled > > directly, but in python, it is a string. > > > and both int('10',16) and int('0x10',16) returns 16. > > > Br, Chen Gang > > > On Dec 12, 12:06 pm, Tommy Nordgren wrote: > >> On Dec 12, 2008, at 4:48 AM, chengang.beij... at gmail.com wrote: > > >>> int('\xf0',16) doesn't work, any way to do that? > >>> -- > >>>http://mail.python.org/mailman/listinfo/python-list > >> ? ? ? ? Should be int('10',16) > >> or int('0x10',16) > > It seems that you want the integer value of a character you read in from > a file. Is this correct? Note that '\xf0' is the interpreter's way of > representing a one-character string whose only character has the > hexadecimal value f0, because the actual character is not printable: the > backslash has a special meaning in character string literals. > > Any one-character string, however, can be converted to the equivalent > integer value using the ord() function. You can convert the other way > using the chr() function: > > > > >>> ord('A') > 65 > >>> chr(65) > 'A' > >>> ord('\xf0') > 240 > >>> chr(240) > '\xf0' > >>> hex(240) > '0xf0' > > So just apply the ord() function to the character and you'll get its > integer value! > > regards > ?Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ From jeremiah.dodds at gmail.com Sat Dec 13 23:30:58 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Sat, 13 Dec 2008 23:30:58 -0500 Subject: Error with SOAPpy In-Reply-To: <2da206ed-f3bb-4ef9-b43e-88ba799a9d87@a12g2000pro.googlegroups.com> References: <2da206ed-f3bb-4ef9-b43e-88ba799a9d87@a12g2000pro.googlegroups.com> Message-ID: <12cbbbfc0812132030t468365cfiaf7ef18a863586c2@mail.gmail.com> On Sat, Dec 13, 2008 at 10:54 PM, Amit Goyal wrote: > Hi All, > > I am new to Python and was trying the sample code on Dive into Python > for WSDL. Below is the error I get. > > Traceback (most recent call last): > File "", line 4, in -toplevel- > print 'Light sensor value: ' + server._ns(namespace).readLSpercent > (int_1 = "1") > File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 470, in > __call__ > return self.__r_call(*args, **kw) > File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 492, in > __r_call > self.__hd, self.__ma) > File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 363, in > __call > config = self.config) > File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 187, in > call > r.endheaders() > File "c:\Python24\lib\httplib.py", line 798, in endheaders > self._send_output() > File "c:\Python24\lib\httplib.py", line 679, in _send_output > self.send(msg) > File "c:\Python24\lib\httplib.py", line 646, in send > self.connect() > File "c:\Python24\lib\httplib.py", line 614, in connect > socket.SOCK_STREAM): > gaierror: (11001, 'getaddrinfo failed') > > I am using Python 2.4.4 and the following versions. > > >>> xml.__version__ > '0.8.4' > >>> fpconst.__version__ > '0.7.2' > >>> SOAPpy.__version__ > '0.12.0' > > Regards, > Amit > -- > http://mail.python.org/mailman/listinfo/python-list > Are you behind a proxy? -------------- next part -------------- An HTML attachment was scrubbed... URL: From gnewsg at gmail.com Fri Dec 19 11:13:34 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Fri, 19 Dec 2008 08:13:34 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: On 19 Dic, 17:01, walterbyrd wrote: > I have not worked with Python enough to really know. But, it seems to > me that more I look at python 3.0, the more I wonder if it isn't a > step backwards. > > To me, it seems that this: > > print "%s=%d" % ('this',99) > > Is much easier, and faster, to type, and is also easier to read and > understand. It also allows people to leverage their knowledge of C. > > This (if it's right) is much longer, and requires more special > characters. > > print( "{0}={1}".format('this',99)) > > Maybe it's worth all the extra trouble, and breaking backward > compatibilty, and all. But, I never had the idea that the old way was > all that big a problem. Of course, I could be wrong. Was the old way > all that big of a problem? You can use the old 2.x syntax also in Python 3.x: C:\>C:\python30\python.exe Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> print("%s=%d" % ('this',99)) this=99 --- Giampaolo http://code.google.com/p/pyftpdlib/ From pdorange at pas-de-pub-merci.mac.com Wed Dec 24 02:59:16 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Wed, 24 Dec 2008 08:59:16 +0100 Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> <1iscu14.oixxplpgajabN%pdorange@pas-de-pub-merci.mac.com> <1isenn3.1g8fxa21aqzibkN%pdorange@pas-de-pub-merci.mac.com> <0161d9c7$0$20621$c3e8da3@news.astraweb.com> Message-ID: <1isg3dq.1yyxrjp5eqcj5N%pdorange@pas-de-pub-merci.mac.com> Steven D'Aprano wrote: > > sign_0 : 0.375 > > sign_1 : 0.444 (+18%) > > sign_2 : 0.661 (+76%) > > sign_3 : 0.498 (+33%) > > > Looking at those results, and remembering that each time is for one > million iterations of one thousand calls each, one million iteration only, that's enough but yes indeed this function is fast. > I'd say that there's so > little difference in speed between them, that you should choose whichever > function is easier to understand. Yes, you're right. I just made those test for pure intellectual reason. For me sign_0 is the simplest one to understood. So in the domain of my little arcade game, this is what i'll use. I don't need the accuraccy of sign_1, because in the application i just need to know if the target is right or left or if the speed direction is right or left. > At least until you profile your > application and discover that the sign() function is the bottleneck > keeping your program slow. In each frame i'll have to use about 10 to 20 sign() call, so it'll not be the bottleneck. -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From steve at REMOVE-THIS-cybersource.com.au Fri Dec 12 17:55:20 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Dec 2008 22:55:20 GMT Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> Message-ID: <0152e35f$0$8244$c3e8da3@news.astraweb.com> On Fri, 12 Dec 2008 21:18:36 +0000, Lie Ryan wrote: > On Fri, 12 Dec 2008 11:50:38 -0500, Steve Holden wrote: > >> Kirk Strauser wrote: >>> At 2008-12-12T15:51:15Z, Marco Mariani writes: >>> >>>> Filip Gruszczy?ski wrote: >>>> >>>>> I am not doing it, because I need it. I can as well use "if not elem >>>>> is None", >>> >>>> I suggest "if elem is not None", which is not quite the same. >>> >>> So what's the difference exactly? "foo is not None" is actually >>> surprising to me, since "not None" is True. "0 is True" is False, but >>> "0 is not None" is True. Why is that? >> >> "is not" is an operator, so the parse is >> >> foo (is not) None >> >> not >> >> foo is (not None) >> >> > Personally, I'd prefer VB's version: > foo IsNot bar > > or in pseudo-python > foo isnot bar > > since that would make it less ambiguous. "a is not b" is no more ambiguous than "1+2*3". True, there's ambiguity if you are ignorant of the precedence rules, but that's no worse than saying that "+" is ambiguous if you don't know what "+" means. "What's this 'is' operator??? It's ambiguous, it could mean ANYTHING!!! Panic panic panic panic!!!" *wink* You're allowed to assume the normal conventions, and (lucky for me!) despite being Dutch Guido choose to assume the normal English convention that "a is not b" means the same as "not (a is b)" rather than "a is (not b)". That's probably because the use-cases for the second would be rather rare. So given the normal precedence rules of Python, there is no ambiguity. True, you have to learn the rules, but that's no hardship. -- Steven From hongtian.info at gmail.com Tue Dec 30 01:22:52 2008 From: hongtian.info at gmail.com (Hongtian) Date: Mon, 29 Dec 2008 22:22:52 -0800 (PST) Subject: How to debug embeding Python? Message-ID: Hi Friends, My application is written in C/C++ and Python is embed to extend some functions (several .py files are invoked). But I am confused how to debug these embed Python? Can I use 'print-debuging'? and where can I capture the output string? Or Python can support 'break' debug for such scenario? Thanks. From roy at panix.com Sat Dec 6 08:50:20 2008 From: roy at panix.com (Roy Smith) Date: Sat, 06 Dec 2008 08:50:20 -0500 Subject: Learning Python now coming from Perl References: Message-ID: In article , Bertilo Wennergren wrote: > I'm planning to start learning Python now, using Python 3000. > I have no previous Python skills, but I now Perl pretty well. > I'm also well experienced with JavaScript. > > Any pointers and tips how I should go about getting into > Python? I assume you use Perl to solve real problems in whatever job you do. My recommendation would be the next time some problem comes up that you would normally solve with Perl, try doing it in Python. Having a real task that you need to accomplish is a great way to focus the mind. For your first project, pick something that's small enough that you think you could tackle it in under 50 lines of Perl. One of the very first things you'll probably discover that's different between Perl and Python is how they handle string pattern matching. In Perl, it's a built in part of the language syntax. In Python, you use the re module. The regular expressions themselves are the same, but the mechanism you use to apply them to input text is quite different. From gnewsg at gmail.com Tue Dec 16 07:19:57 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Tue, 16 Dec 2008 04:19:57 -0800 (PST) Subject: ethical questions about global variables References: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> Message-ID: On 16 Dic, 07:23, Michele Simionato wrote: > On Dec 16, 3:45?am, "Giampaolo Rodola'" wrote: > > > Hi, > > in a module of mine (ftpserver.py) I'd want to add a (boolean) global > > variable named "use_gmt_times" to decide whether the server has to > > return times in GMT or localtime but I'm not sure if it is a good idea > > because of the "ethical" doubts I'm gonna write below. > > Global variables have a bad reputation, but they are not > so bad in Python. Notice that: > > 1. global variables in Python are local to the module they > ? ?are defined in; > > 2. class names and module names are usually global variables > ? ?and nobody complains about that. > > 3. if you use an ALL_CAPS convention it is quite quite clear > ? ?that you are using a global variable. > > Actually the ALL_CAPS convention is for constants, but > sometimes I use it for configuration variables too, if > they are set at the beginning and they are never changed > during the running of the program. If you have more than > a single global, it makes sense to introduce a configuration > object, as others have said (this is how typically work) > but if you have a single parameter the confuguration > object is not worth the effort, IMO. > > ? ? ? ? ? ? ? ? ?M. Simionato No, all the other "configurable" variables are offered as class attributes. --- Giampaolo http://code.google.com/p/pyftpdlib/ From bignose+hates-spam at benfinney.id.au Mon Dec 15 02:55:55 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 15 Dec 2008 18:55:55 +1100 Subject: alt.possessive.its.has.no.apostrophe References: <87vdtmf0mu.fsf_-_@benfinney.id.au> Message-ID: <87r649g9dg.fsf@benfinney.id.au> James Stroud writes: > Ben Finney wrote: > > James Stroud writes: > > > >> Yes. I think it was the British who decided that the apostrophe > >> rule for "it" would be reversed from normal usage relative to > >> just about every other noun. It also seems an indefensible claim to say that anyone ?decided? it would be that way, especially ?the British?. > > Remember that ?it? is a pronoun. I see no reversal: > > Ok. Pronouns are reversed. Or, more generally: Pronouns, which are different in just about every other way from other nouns, are different in this way also. Is that about right? -- \ ?I met my girlfriend in Macy's; she was buying clothes, and I | `\ was putting Slinkies on the escalators.? ?Steven Wright | _o__) | Ben Finney From python.list at tim.thechases.com Wed Dec 3 06:10:28 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 03 Dec 2008 05:10:28 -0600 Subject: Simple ini Config parser examples needed In-Reply-To: <4936016F.8010401@g.nevcal.com> References: <47c890dc0812021331m1fe3f420kce9bcb07df5ae44e@mail.gmail.com> <4935BBE5.3020607@g.nevcal.com> <47c890dc0812021522g7f42b00o2a831bac1e15aa05@mail.gmail.com> <4936016F.8010401@g.nevcal.com> Message-ID: <49366924.7050806@tim.thechases.com> > Tim provided a correct-looking answer, albeit somewhat > complex, as it doesn't reuse the logic in the ConfigParser. It didn't start out very complex, but it was so easy to make it a bit more robust with such a scant few lines of code that I went ahead. The original just looked like options = {} for line in file("simple.ini"): line = line.rstrip("\r\n") if '=' in line: key, value = line.split('=', 1) options[key] = value which is about as simple as it gets. However, this doesn't handle commented lines nicely (OP didn't mention whether there were comments), the keys are case-sensitive (often not a desired behavior), and leading/trailing whitespace for both the key & value are preserved (also rarely desired), and in the event of a malformed line (with no '='), it fails indistinguishably from a blank line and silently. The big advantages given by the ConfigParser hack (tacking on a fake section-header) - it provides the convenience methods for pulling out an int/float/bool in addition to a string - possibly handles continued lines (I saw something in the source referring to this) - it handles merging config files from multiple sources (such as /etc/foo_rc then merged with ~/.foo_rc) - encourages use-of and learning-about a standard library module - and it handles string substitution if you want it. It also provides for defaults, but the standard dict has the get() method to allow for defaults, and the library offers the default-dict. As a personal aside, it does bug me that the ConfigParser .get*() methods don't afford an optional default value like dict.get() in the event you want a value that may be present in the config file but isn't in the [DEFAULT] section when present raising a NoSectionError or NoOptionError. I.e. I'd like to be able to call cp.get('some_section', 'some_key', '42') on an empty config.ini file and get back the "42" as if it existed in "some_section" rather than throwing an exception/error (and why the heck do these "exceptions" descend from Error rather than Exception? These aren't errors...they're exceptions) -tkc From yinon.me at gmail.com Mon Dec 15 08:29:00 2008 From: yinon.me at gmail.com (Yinon Ehrlich) Date: Mon, 15 Dec 2008 05:29:00 -0800 (PST) Subject: Limit traceback from most recent call References: Message-ID: <8ab4f9a8-3629-4f6a-bbf2-1deed8624215@w24g2000prd.googlegroups.com> On Dec 14, 8:07?pm, Brian Allen Vanderburg II wrote: > I've looked at traceback module but I can't find how to limit traceback > from the most recent call if it is possible. ?I see that extract_tb has > a limit parameter, but it limits from the start and not the end. ? > Currently I've made my own traceback code to do this but wonder if > python already has a way to do this build in: > > def format_partial_exc(limit=None): > > ? ? (type, value, tb) = sys.exc_info() > > ? ? items = traceback.extract_tb(tb) > > ? ? if limit: > > ? ? ? ? items = items[-limit:] # Get last 'limit' items and not first > > ? ? result = 'Traceback (most recent call last):\n' > > ? ? items = traceback.format_list(items) > > ? ? for i in items: > > ? ? ? ? result += i # Newline already included > > ? ? result += type.__name__ + ': ' + str(value) > > ? ? return result > > Is this possible currently from traceback or other python module? > > Brian A. Vanderburg II Hi, The interface of extract_tb is: traceback.extract_tb(tb, limit=None) try to play with the 'limit' argument Good luck, Yinon From torriem at gmail.com Mon Dec 22 12:04:15 2008 From: torriem at gmail.com (Michael Torrie) Date: Mon, 22 Dec 2008 10:04:15 -0700 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <52b8e001-2cc7-4891-8540-a3cdb6b78533@e25g2000vbe.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> <59153e28-bf86-4158-96d9-23aa5b9f0205@j35g2000yqh.googlegroups.com> <52b8e001-2cc7-4891-8540-a3cdb6b78533@e25g2000vbe.googlegroups.com> Message-ID: <494FC88F.10706@gmail.com> r wrote: > Thanks MRAB, > except the float is not 2 decimal places, but its there > > Come on... They did this for the interpreter not us. It's easer to > parse this string with positional arguments and a dict of format > descriptions. Come on pydev, at least be honest about it! No. They did this for the *language*. Come on, R. Read the PEP on the new string formatter. The rationale is very clear. From desas2 at gmail.com Mon Dec 1 15:58:19 2008 From: desas2 at gmail.com (desas2 at gmail.com) Date: Mon, 1 Dec 2008 12:58:19 -0800 (PST) Subject: python 2.5.2 or Python 2.6 compilation problem on AIX 5.3 References: <26fbc708-1b64-4271-9c7d-4394aa281f47@j39g2000yqn.googlegroups.com> Message-ID: <5eae5283-2f52-4b05-9a8c-0c9ced3e54db@h20g2000yqn.googlegroups.com> On Dec 1, 1:06 pm, Terry Reedy wrote: > des... at gmail.com wrote: > > Hello: > > I am trying to compile Python 2.5.2 on AIX 5.3 with gcc 4.2.3. I am > > getting following error. (I also tried Python 2.6 with same error) > > > creating build/temp.aix-5.3-2.5/share/tmhsdsd2/tmp/Python-2.5.2/ > > Modules > > gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - > > Wstrict-prototypes -I. -I/share/tmhsdsd2/tmp/Python-2.5.2/./Include - > > I. -IInclude -I./Include -I/usr/local/include -I/share/tmhsdsd2/tmp/ > > Python-2.5.2/Include -I/share/tmhsdsd2/tmp/Python-2.5.2 -c /share/ > > tmhsdsd2/tmp/Python-2.5.2/Modules/_struct.c -o build/temp.aix-5.3-2.5/ > > share/tmhsdsd2/tmp/Python-2.5.2/Modules/_struct.o > > creating build/lib.aix-5.3-2.5 > > > ./Modules/ld_so_aix gcc -pthread -bI:Modules/python.exp build/ > > temp.aix-5.3-2.5/share/tmhsdsd2/tmp/Python-2.5.2/Modules/_struct.o -L/ > > usr/local/lib -lpython2.5 -o build/lib.aix-5.3-2.5/_struct.so > > collect2: library libpython2.5 not found > > Have you checked all the directories on PATH to see if any contain > libpython2.5? > Thanks for your response. libpython2.5.a is in the current directory same as Makefile. Thank you. Dinakar From 5lvqbwl02 at sneakemail.com Sun Dec 28 03:54:51 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Sun, 28 Dec 2008 00:54:51 -0800 (PST) Subject: Doing set operation on non-hashable objects References: <3a87eb6a-13ff-4aea-8835-3a233cc6cfc4@w39g2000prb.googlegroups.com> Message-ID: On Dec 24, 12:21?pm, "Gabriel Genellina" wrote: > En Wed, 24 Dec 2008 17:16:59 -0200, <5lvqbw... at sneakemail.com> escribi?: > > > I'm writing an application which is structured roughly as follows: > > > "db" is a dict, where the values are also dicts. > > A function searches through db and returns a list of values, each of > > which is a dict as described above. > > I need to perform set operations on these lists (intersection and > > union) > > However the objects themselves are not hashable, and therefore can't > > be in a set, because they are dicts. > > > If you *only* care about object identity, you might use a dictionary that ? > only compares by identity to anyone else: > > class nc_dict(dict): > ? ?"A hashable dictionary that isn't equal to anyone else" > > ? ?def __eq__(self, other): > ? ? ?return cmp(id(self),id(other))==0 > > ? ?def __hash__(self): > ? ? ?return hash(id(self)) > > d1 = nc_dict(a=1, b=2, c=3) > d2 = nc_dict(b=2, c=0, d=4) > d3 = nc_dict(a=1, c=3, e=5) > dd1 = nc_dict(x=d1, y=d2) > dd2 = nc_dict(x=d1, y=d3) > dd3 = nc_dict(y=d2, z=d3, w=d1) > l1 = [dd1, dd2] > l2 = [dd2, dd3] > s1 = set(l1) > s2 = set(l2) > print s1-s2 > print s2-s1 > print s1&s2 > > # instances of nc_dict with the same contents are NOT equal > d4 = nc_dict(a=1, b=2, c=3) > print d1, d4, d1==d4 ?# output: False > > # but we can use this function to compare contents > def cmp_contents(d1, d2): > ? ? ?try: return cmp(sorted(d1.items()), sorted(d2.items())) > ? ? ?except Exception: return 1 # assume they're unequal > > print cmp_contents(d1,d4)==0 # output: True Good idea. I'll try this out. I don't think it's likely that I'll have a case where the dicts have identical values, but different identities. And if they do I probably don't care too much. Thanks From luke.leighton at googlemail.com Tue Dec 2 15:54:19 2008 From: luke.leighton at googlemail.com (lkcl) Date: Tue, 2 Dec 2008 12:54:19 -0800 (PST) Subject: Pyjamas 0.4: Python Web Toolkit Release References: Message-ID: <655eff24-100b-494f-802e-c59f9539fb1b@h5g2000yqh.googlegroups.com> On Dec 2, 6:52 pm, Duncan Booth wrote: > "Luke Kenneth Casson Leighton" wrote: > > >Pyjamasstarted as a port of Google's Web Toolkit, to python. > > Explaining whyPyjamas(and GWT) is so significant takes > > some doing: the summary is that comprehensive desktop-like > > user interfaces can be developed very simply, to run in > > any modern web browser, without having to write a single > > line of JavaScript. > > Great concept. 's'wikkid :) > The demos are a bit flakey (especially with IE): ehn? o dear. well, i try my best with ies4linux (ie6 under wine). ie7 doesn't quiiiite cut it, and the script debugger just doesn't quite want to play nice under wine. so if you do make a report, please _do_ make sure it includes a full stack trace, not just a line number. > where do you want bug > reports (the sourceforge tracker seems to be empty so I wondered if you > used somewhere else)? code.google.com - http://code.google.com/p/pyjamas/issues/list thanks! From kyrie at uh.cu Wed Dec 10 14:01:35 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Wed, 10 Dec 2008 14:01:35 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: <493FE561.6030007@egenix.com> References: <1228923619.493fe2e3c3073@comuh.uh.cu> <493FE561.6030007@egenix.com> Message-ID: <200812101401.35786.kyrie@uh.cu> On Wednesday 10 December 2008 10:50:57 am M.-A. Lemburg wrote: > On 2008-12-10 16:40, Luis Zarrabeitia wrote: > > Quoting Rasmus Fogh : > >> Rhamphoryncus wrote: > > Rich comparisons were added to Python at the request of the > Numeric (now numpy) developers and they have been part of Python > a Numeric for many many years. > > I don't think it's likely they'll change things back to the days > of Python 1.5.2 ;-) Please define "rich comparisons" for me. It seems that I do not understand the term - I was thinking it meant the ability to override the comparison operators, and specially, the ability to override them independently. Even in statically typed languages, when you override the equality operator/function you can choose not to return a valid answer (raise an exception). And it would break all the cases mentioned above (element in list, etc). But that isn't the right thing to do. The language doesn't/can't prohibit you from breaking the equality test, but that shouldn't be considered a feature. (a==b).all() makes no sense. > > Even the transition itself could be done without breaking much code... > > Make the == op return an object that wraps the array of bools (instead of > > the array itself), give it the any() and all() methods, and make > > __nonzero__/__bool__ equivalent to all(). > > That would cause a lot of confusion on its own, since such an > object wouldn't behave in the same way as say a regular Python > list (bool([0]) == True). I'm certain that something could be worked out. A quick paragraph that took me just a few minutes to type shouldn't be construed as a PEP that will solve all the problems :D. -- Luis Zarrabeitia (aka Kyrie) Fac. de Matem?tica y Computaci?n, UH. http://profesores.matcom.uh.cu/~kyrie From kyosohma at gmail.com Tue Dec 30 16:40:04 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 30 Dec 2008 13:40:04 -0800 (PST) Subject: win32gui References: Message-ID: <4af4b9c7-b7d0-40c4-ba86-38a62df4fb19@e1g2000pra.googlegroups.com> On Dec 30, 3:22?pm, Gandalf wrote: > I'm searching the win32gui hooks for a function to get the windowClass > position any idea? > > thanks! Try looking in the docs: http://docs.activestate.com/activepython/2.4/pywin32/win32gui.html I think the GetWindowPlacement() might be what you're looking for, although it's kind of hard to tell from what little info you gave. Mike From arnodel at googlemail.com Thu Dec 11 18:31:03 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 11 Dec 2008 23:31:03 +0000 Subject: list organization question References: Message-ID: Robocop writes: > I have a list of objects, each object having two relevant attributes: > date and id. I'd like not only organize by id, but also by date. > I.e. i would like to parse my list into smaller lists such that each > new mini-list has a unique date, but consists of only objects with a > specific id. Are there any handy imports i could use to accomplish > something like this? I'm relatively new to python and as such don't > know all of the preloaded functions at my disposal. Thanks for any > help in advance, the community here is always ridiculously helpful. Look at itertools.groupby. E.g. from itertools import groupby data = [ my objects ] def getdate(x): return x.date by_date = {} for date, objs in groupby(sorted(data, key=getdate), getdate): by_date[date] = list(objs) # list(objs) is the list of all objects in data whose date is date I'm sorry if this is a bit terse... -- Arnaud From gagsl-py2 at yahoo.com.ar Mon Dec 8 02:48:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Dec 2008 05:48:45 -0200 Subject: Don't you just love writing this sort of thing :) References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: En Sun, 07 Dec 2008 05:34:39 -0200, Lawrence D'Oliveiro escribi?: > In message , Arnaud Delobelle wrote: > >> * you give the impression of being arrogant; > > Oddly enough, I wasn't the one who started by criticizing other people's > code. I have no ego about my code; I gladly accept criticisms. But > perhaps > some other people are not so thick-skinned and do not like getting as > they > give... May I ask then *why* did you chose to post your code fragment? Did I miss something? -- Gabriel Genellina From jan at jandecaluwe.com Tue Dec 23 06:32:32 2008 From: jan at jandecaluwe.com (Jan Decaluwe) Date: Tue, 23 Dec 2008 12:32:32 +0100 Subject: Why MyHDL? Message-ID: <4950d063$0$2853$ba620e4c@news.skynet.be> Hello: MyHDL is a Python package for using Python as a Hardware Description Language. A new release is upcoming, and on this occasion we have prepared a page about why MyHDL may be useful to you: http://www.myhdl.org/doku.php/why Regards, Jan -- Jan Decaluwe - Resources bvba - http://www.jandecaluwe.com Python as a hardware description language: http://www.myhdl.org From steven at REMOVE.THIS.cybersource.com.au Thu Dec 11 03:10:12 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 11 Dec 2008 08:10:12 GMT Subject: Rich Comparisons Gotcha References: Message-ID: On Wed, 10 Dec 2008 17:58:49 -0500, Luis Zarrabeitia wrote: > On Sunday 07 December 2008 09:21:18 pm Robert Kern wrote: >> The deficiency is in the feature of rich comparisons, not numpy's >> implementation of it. __eq__() is allowed to return non-booleans; >> however, there are some parts of Python's implementation like >> list.__contains__() that still expect the return value of __eq__() to >> be meaningfully cast to a boolean. > > list.__contains__, tuple.__contains__, the 'if' keyword... > > How do can you suggest to fix the list.__contains__ implementation? I suggest you don't, because I don't think it's broken. I think it's working as designed. It doesn't succeed with arbitrary data types which may be broken, buggy or incompatible with __contain__'s design, but that's okay, it's not supposed to. > Should I wrap all my "if"s with this?: > > if isinstance(a, numpy.array) or isisntance(b,numpy.array): > res = compare_numpy(a,b) > elif isinstance(a,some_otherclass) or isinstance(b,someotherclass): > res = compare_someotherclass(a,b) > ... > else: > res = (a == b) > if res: > # do whatever No, inlining that code everywhere you have an if would be stupid. What you should do is write a single function equals(x, y) that does precisely what you want it to do, in whatever way you want, and then call it: if equals(a, b): Or, put your data inside a wrapper. If you read back over my earlier posts in this thread, I suggested a lightweight wrapper class you could use. You could make it even more useful by using delegation to make the wrapped class behave *exactly* like the original, except for __eq__. You don't even need to wrap every single item: def wrap_or_not(obj): if obj in list_of_bad_types_i_know_about: return EqualityWrapper(obj) return obj data = [1, 2, 3, BadData, 4] data = map(wrap_or_not, data) It isn't really that hard to deal with these things, once you give up the illusion that your code should automatically work with arbitrarily wacky data types that you don't control. -- Steven From biltar at hotmail.com Mon Dec 15 08:03:12 2008 From: biltar at hotmail.com (Ali art) Date: Mon, 15 Dec 2008 13:03:12 +0000 Subject: UnicodeEncodeError Message-ID: Hello! I am using Windows XP professional version 2002 Service pack 3. AMD Athlon(TM)XP 2400+ 2.00GHz 992MB RAM. I have downloaded Windows x86 MSI Instaler Python 3.0 (sig) (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32 Control Panel -> System -> Advanced -> Environment Variables. System Variables -> Path -> edit C:\Windows\System32\Wbem;C:\Python30 start -> programs -> python 3.0 -> IDLE(Python GUI) -> IDLE 3.0 -> File -> New Window -> i wrote "print('??????')" without qutes-> File -> Save -> Python30 -> i gave file name "d2.py" without qutes-> and Run -> Run Module -> it gives error "invalid character in identifier" then i tried second method start -> run -> cmd -> d2.py and enter it gives the error C:\>d2.pyTraceback (most recent call last): File "C:\Python30\d2.py", line 4, in print('\u011f?\u015f??\u0131') File "C:\Python30\lib\io.py", line 1491, in write b = encoder.encode(s) File "C:\Python30\lib\encodings\cp437.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0]UnicodeEncodeError: 'charmap' codec can't encode character '\u011f' in position0: character maps to C:\> But if i write in Phyton Shell -> >>> print('??????') and pressed enter -> gives '??????' it works. What is wrong? all the best _________________________________________________________________ Connect to the next generation of MSN Messenger? http://imagine-msn.com/messenger/launch80/default.aspx?locale=en-us&source=wlmailtagline -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at microcorp.co.za Wed Dec 3 23:33:41 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 4 Dec 2008 06:33:41 +0200 Subject: Please fix your clock [was Re: Multiple equates] References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> <0147f4b7$0$20670$c3e8da3@news.astraweb.com> Message-ID: <001601c955c9$94034700$0d00a8c0@hendrik> "Steven D'Aprano" wrote: >Hendrik, I think your PC's clock is wrong. You seem to be posting from >the future. I always knew I was more advanced than other people... :-) Well spotted! Thanks - Hendrik From zak.mc.kraken at libero.it Fri Dec 12 10:34:42 2008 From: zak.mc.kraken at libero.it (Vito De Tullio) Date: Fri, 12 Dec 2008 16:34:42 +0100 Subject: Removing None objects from a sequence References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> Message-ID: Filip Gruszczy?ski wrote: > I checked itertools, but the only thing that > seemed ok, was ifilter - this requires seperate function though, so > doesn't seem too short. is this too much long? >>> from itertools import ifilter >>> for element in ifilter(lambda x: x is not None, [0,1,2,None,3,None,4]): ... print element ... 0 1 2 3 4 >>> -- By ZeD From cjw at ncf.ca Wed Dec 3 11:51:04 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Wed, 03 Dec 2008 11:51:04 -0500 Subject: Multiple Versions of Python on Windows XP In-Reply-To: <493592EE.9090005@v.loewis.de> References: <4934de22$0$27863$9b622d9e@news.freenet.de> <493592EE.9090005@v.loewis.de> Message-ID: Martin v. L??wis wrote: >>>> What changes are made to the registry? >>> For a complete list, see Tools/msi/msi.py in the source tree. >> I have scanned the file: >> http://svn.python.org/projects/python/branches/py3k/Tools/msi/msi.py >> >> I don't find anything that addresses this issue. > > Read the add_registry function. You may need to first understand > how the Registry table in an MSI file works. > >> I am seeking some mechanism such that any of Python 2.5, Python 2.6 or >> Python 2.6 can be chosen as the currently active version. > > If Glenn Lindermann's answer doesn't help, you need to explain: > what is a "currently active version"? How is one Python version > more active than any other? > >> I was hoping that there is some simpler way than the "Repair" procedure. > > See Glenn Lindermann's answer. > >>> It would be good to be more specific with such statements: what troubles >>> specifically? If I play dumb, I'd say "of course - windows explorer >>> doesn't support editing Python files; you need a text editor". >> Yes, I should have been clearer. The PyScripter application locks up >> and must be killed, using the Task Manager. > > I think you need to report that to the PyScripter authors as a bug. > I can't imagine how the "currently active version" can affect what > PyScripter does. > > Regards, > Martin Martin, Many thanks for your responses. Yes, Glen Lindermann's suggestion seems to meet the need. It's been a while since I've looked at DOS and I didn't remember fType or assoc. Michel Claveau suggests VirtualBox, this seems a big hammer to kill this particular fly. It's interesting that each install sets up a Python.File variable in the registry. It's a pity that this can't be used to achieve this more simply. Best wishes, Colin W. From mark at thomaszone.com Tue Dec 30 08:38:55 2008 From: mark at thomaszone.com (Mark Thomas) Date: Tue, 30 Dec 2008 05:38:55 -0800 (PST) Subject: Any equivalent to Ruby's 'hpricot' html/xpath/css selector package? References: <495a2031$0$31867$9b4e6d93@newsspool3.arcor-online.net> Message-ID: On Dec 30, 8:20?am, Stefan Behnel wrote: > Mark Thomas wrote: > > The main difference is that lxml doesn't have CSS selector syntax > > Feel free to read the docs: > > http://codespeak.net/lxml/cssselect.html Don't know how I missed that... So lxml is pretty much an exact equivalent to what Ruby has to offer (Hpricot or Nokogiri). Nice. From martin at v.loewis.de Tue Dec 2 02:29:03 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 02 Dec 2008 08:29:03 +0100 Subject: Multiple Versions of Python on Windows XP In-Reply-To: <4934E183.9020404@g.nevcal.com> References: <4934de22$0$27863$9b622d9e@news.freenet.de> <4934E183.9020404@g.nevcal.com> Message-ID: <4934E3BF.7000403@v.loewis.de> > It would be nice if the ftypes were version specific as created by the > installer; IIRC, I created the above three from the ftype Python.File as > I installed each version. That's a good idea; please submit a wish list item to bugs.python.org. There may be issues (such as people relying on this being Python.File), but I can't see any problems off-hand. Regards, Martin From darcy at druid.net Tue Dec 16 15:18:00 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 16 Dec 2008 15:18:00 -0500 Subject: Where is a good open source python project to be used as example? In-Reply-To: References: <05T1l.219074$FR.507685@twister1.libero.it> Message-ID: <20081216151800.ec03bf25.darcy@druid.net> On Tue, 16 Dec 2008 20:03:21 GMT Andrea Francia wrote: > >> Did you know where are such projects? > > > > http://www.PyGreSQL.org/. > > > > Thanks! But I can't find any unit test in the code. Look again. They are in the files named TEST_PyGreSQL_classic.py and TEST_PyGreSQL_dbapi20.py. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 00:14:44 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Dec 2008 05:14:44 GMT Subject: Don't you just love writing this sort of thing :) References: Message-ID: <0148b086$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 13:27:35 +1300, Lawrence D'Oliveiro wrote: > In message , Cong > Ma wrote: > >> The "if ... != None" is not necessary... "if PatchDatePat.search(f)" >> is OK. > > I don't do that. Perhaps you should? Since the context has been deleted, it's hard to tell whether the code as written by Lawrence is incorrect or merely bad style. Here's his original piece of code, with the stupid formatting fixed to a more readable style: for Entry in sorted( f for f in os.listdir(PatchesDir) if PatchDatePat.search(f) != None ): Patch = (open, gzip.GzipFile)[Entry.endswith(".gz")]( os.path.join(PatchesDir, Entry), "r") ... read from Patch ... Patch.close() Still pretty obfuscated. The for block could be made considerably more readable. Here's one way: opener = gzip.GzipFile if Entry.endswith(".gz") else open Patch = opener(os.path.join(PatchesDir, Entry), "r") ... read from Patch ... Patch.close() Looking at the call to sorted(), Cong Ma suggested that if PatchDatePat.search(f) != None should be replaced by the much shorter: if PatchDatePat.search(f) The replacement is much more Pythonic style, but it could fail if PatchDatePat.search() returns a false value (0, empty string, empty list, etc) which is intended to count as a match. Without knowing what the search method does, it is impossible to tell whether this is a risk or not. On the other hand, Lawrence's code can also fail if the search method returns an object which for some reason tests equal to None despite being a match. In other words, *both* techniques are fragile, because they make assumptions about the sort of object the search method can return. The best way of doing this test, given *only* the assumption that None indicates no match, is with: if PatchDatePat.search(f) is not None This also happens to be (marginally) faster that either of the others, as it relies only on an identity test, and doesn't need to make an equality test or a __nonzero__ test, both of which require method lookups. -- Steven From rdcollum at gmail.com Wed Dec 31 14:55:14 2008 From: rdcollum at gmail.com (Roger) Date: Wed, 31 Dec 2008 11:55:14 -0800 (PST) Subject: Why not Ruby? References: Message-ID: <0640abb6-ab69-4709-a46c-b0ee8c9f0c09@n21g2000vba.googlegroups.com> On Dec 31, 12:55?pm, Xah Lee wrote: > Just spent 3 hours looking into Ruby today. Here's my short impression > for those interested. > Who are you? In case no one tells you, you are a cocky, egotistical windbag with opinions that border constructive but never gets there. Why would anyone care what you think? Again, who are you? Xah Lee? And? I didn't subscribe to read reviews on Ruby. And I'm pretty sure anyone that bothers to subscribe to a group about programming has the wherewithal to research a language themselves and come to their own determiniation. Also, this is a Python group and not Ruby. I knew I should have avoided this post and read the one about Nike Shoes from China. At least those bits of trolling spam don't try to mask themselves as something worthwhile. From info at orlans-amo.be Fri Dec 5 14:15:33 2008 From: info at orlans-amo.be (info at orlans-amo.be) Date: Fri, 5 Dec 2008 11:15:33 -0800 (PST) Subject: Python 3.0 automatic decoding of UTF16 References: Message-ID: <55d79070-0c11-4fb9-8cf5-b8cc7c54b5d2@v42g2000yqv.googlegroups.com> On Dec 5, 3:25?pm, Johannes Bauer wrote: > Hello group, > > I'm having trouble reading a utf-16 encoded file with Python3.0. This is > my (complete) code: > > #!/usr/bin/python3.0 > > class AddressBook(): > ? ? ? ? def __init__(self, filename): > ? ? ? ? ? ? ? ? f = open(filename, "r", encoding="utf16") > ? ? ? ? ? ? ? ? while True: > ? ? ? ? ? ? ? ? ? ? ? ? line = f.readline() > ? ? ? ? ? ? ? ? ? ? ? ? if line == "": break > ? ? ? ? ? ? ? ? ? ? ? ? print([line[x] for x in range(len(line))]) > ? ? ? ? ? ? ? ? f.close() > > a = AddressBook("2008_11_05_Handy_Backup.txt") > > This is the file (only 1 kB, if hosting doesn't work please tell me and > I'll see if I can put it someplace else): > > http://www.file-upload.net/download-1297291/2008_11_05_Handy_Backup.t... > > What I get: The file reads file the first few lines. Then, in the last > line, I get lots of garbage (looking like uninitialized memory): > > ['E', 'n', 't', 'r', 'y', '0', '0', 'T', 'e', 'x', 't', ' ', '=', ' ', > '"', 'A', 'D', 'A', 'C', ' ', 'V', 'e', 'r', 'k', 'e', 'h', 'r', 's', > 'i', 'n', 'f', 'o', '"', '\u0d00', '\u0a00', '?', '?', '?', '?', '? > ', '\u3000', '\u3100', '?', '?', '?', '?', '\u2000', '?', '\u2000', > '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', > '\u0d00', '\u0a00', '?', '?', '?', '?', '?', '\u3000', '\u3100', ' > ?', '?', '?', '?', '\u2000', '?', '\u2000', '?', '?', '?', '?', > '\u3100', '?', '?', '?', '?', '?', '?', '?', '?', '\u0d00', > '\u0a00', '\u0d00', '\u0a00', '?', '?', '?', '?', '?', '?', '?', > '?', '?', '\u3000', '\u3000', '?', '?', '\u0d00', '\u0a00'] > > Where the line > > Entry00Text = "ADAC Verkehrsinfo"\r\n > > is actually the only thing the line contains, Python makes the rest up. > > The actual file is much longer and contains private numbers, so I > truncated them away. When I let python process the original file, it > dies with another error: > > Traceback (most recent call last): > ? File "./modify.py", line 12, in > ? ? a = AddressBook("2008_11_05_Handy_Backup.txt") > ? File "./modify.py", line 7, in __init__ > ? ? line = f.readline() > ? File "/usr/local/lib/python3.0/io.py", line 1807, in readline > ? ? while self._read_chunk(): > ? File "/usr/local/lib/python3.0/io.py", line 1556, in _read_chunk > ? ? self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) > ? File "/usr/local/lib/python3.0/io.py", line 1293, in decode > ? ? output = self.decoder.decode(input, final=final) > ? File "/usr/local/lib/python3.0/codecs.py", line 300, in decode > ? ? (result, consumed) = self._buffer_decode(data, self.errors, final) > ? File "/usr/local/lib/python3.0/encodings/utf_16.py", line 69, in > _buffer_decode > ? ? return self.decoder(input, self.errors, final) > UnicodeDecodeError: 'utf16' codec can't decode bytes in position 74-75: > illegal encoding > > With the place where it dies being exactly the place where it outputs > the weird garbage in the shortened file. I guess it runs over some page > boundary here or something? > > Kind regards, > Johannes > > -- > "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, > verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." > ? ? ? ? ?-- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik > ? ? ? ? ? ? ? ? ? ? ? ? ?<48d8bf1d$0$7510$54022... at news.sunrise.ch> 2 problems: endianness and trailing zer byte. This works for me: class AddressBook(): def __init__(self, filename): f = open(filename, "r", encoding="utf_16_be", newline="\r\n") while True: line = f.readline() if len(line) == 0: break print (line.replace("\r\n","")) f.close() a = AddressBook("2008_11_05_Handy_Backup2.txt") Please note the filename: I modified your file by dropping the trailing zer byte From shao.tu at gmail.com Thu Dec 11 04:53:58 2008 From: shao.tu at gmail.com (stalex) Date: Thu, 11 Dec 2008 01:53:58 -0800 (PST) Subject: Py_GetPath() C API in python 3 Message-ID: <772bb62b-1ef1-4ffa-90f6-c1cbdc728fdd@q30g2000prq.googlegroups.com> Hi all, I want to build a new, requires total control, python interpreter. So I implement my own version of Py_GetPath(), Py_GetPrefix(), Py_GetExecPrefix() and Py_GetProgramFullPath(). When compiling, I always get error messages, for each API function, look like followings: /opt/python-3.0/lib/python3.0/config/libpython3.0.a(getpath.o)(.text +0x211c): In function `Py_GetPath': ./Modules/getpath.c:739: multiple definition of `Py_GetPath' myApp.o(.text+0x0):/home/alex/workspace/develop/src/myApp.c:11: first defined here /usr/bin/ld: Warning: size of symbol `Py_GetPath' changed from 126 in system.o to 32 in /opt/python-3.0/lib/python3.0/config/libpython3.0.a (getpath.o) collect2: ld returned 1 exit status If I compile my application with python 2.x, everything's just okay and my application as well. Any ideas on how to get this working for python 3? From pdorange at pas-de-pub-merci.mac.com Thu Dec 18 09:21:16 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Thu, 18 Dec 2008 15:21:16 +0100 Subject: re.match() performance References: <755bd716-f5f6-4953-87a7-04ee148c3298@i18g2000prf.googlegroups.com> Message-ID: <1is5gvp.1bafifnn1ir2uN%pdorange@pas-de-pub-merci.mac.com> Emanuele D'Arrigo wrote: > I've written the code below to test the differences in performance > between compiled and non-compiled regular expression matching but I > don't quite understand the results. It appears that the compiled the > pattern only takes 2% less time to process the match. Is there some > caching going on in the uncompiled section that prevents me from > noticing its otherwise lower speed? Running your sample i got also a 2% the first time, but next time i got a different speed : 4 time faster. Running 1st time Pattern Matching Time: 0.122432 (Compiled) Pattern Matching Time: 0.12012 Ratio Compiled/NotCompiled: 0.981116048092 2nd time and more Pattern Matching Time: 0.00257 (Compiled) Pattern Matching Time: 0.000619 Ratio Compiled/NotCompiled: 0.240856031128 Config python 2.5.1 / MacOS X 10.5 -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From christophedeze at gmail.com Mon Dec 22 12:27:14 2008 From: christophedeze at gmail.com (Toff) Date: Mon, 22 Dec 2008 09:27:14 -0800 (PST) Subject: join a samba domain References: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> <5428c77b-ed4f-49ec-a808-dccd77a2a01c@g3g2000pre.googlegroups.com> Message-ID: On 22 d?c, 17:57, Tim Golden wrote: > Toff wrote: > > On 22 d?c, 17:02, Tim Golden wrote: > >> Toff wrote: > >>> hi, > >>> I 'm trying to write a script to make my computer join a samba. > >>> domeone have any idea ?? > >> Ummm. It's not clear if you're saying that your code doesn't > >> work, or asking for general advice, or what? I'm not in a > >> position to have my machine join a domain or workgroup, but > >> you seem to have got most things in place already. The only > >> thing I would expect to have to change is this last line: > > >>> ? ?import wmi > >>> ? ?c = wmi.WMI() > >>> ? ?d = c.Win32_ComputerSystem > >>> ? ?d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") > >> because the d is only a WMI *class*, not a WMI *instance*, > >> so doesn't refer as it should to your computer system but > >> to the class of computer systems. Try something like this (untested): > > >> > >> import wmi > > >> c = wmi.WMI () > >> for d in c.Win32_ComputerSystem (): > >> ? d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") > > >> > > >> TJG > > thanks but it doesn't work > > I've got this errors > > > Traceback (most recent call last): > > ?File "integrdom.py", line 51, in > > ? ?main() > > ?File "integrdom.py", line 13, in main > > ? ?joindom() > > ?File "integrdom.py", line 44, in joindom > > ? ?d.JoinDomainOrWorkGroup(None, 3, "domcd", "adminLocal", r"admin > > \domcd") > > ?File "c:\Python25\Lib\site-packages\wmi.py", line 493, in __getattr__ > > ? ?handle_com_error (error_info) > > ?File "c:\Python25\Lib\site-packages\wmi.py", line 189, in > > handle_com_error > > ? ?raise x_wmi, "\n".join (exception_string) > > wmi.x_wmi > > Do you not get *anything* after than wmi.x_wmi? Not even > a messy exception string? > > TJG no pessy string something strange: import wmi c = wmi.WMI() os = c.Win32_ComputerSystem for method_name in os.methods: method = getattr(os, method_name) print method it doesn't give the same parameter order for JoinDomainOrWorkGroup than MSDN doc From bruno.42.desthuilliers at websiteburo.invalid Fri Dec 19 08:33:19 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 19 Dec 2008 14:33:19 +0100 Subject: How to parsing a sequence of integers In-Reply-To: References: Message-ID: <494ba258$0$18998$426a74cc@news.free.fr> Steven Woody a ?crit : > Hi, > > I am a newbie and is reading the python book. Could anyone tell me, > how to parsing the following string > "123 100 12 37 ..." > into a list of integers on which I can then apply max()/min()? source = "123 100 12 37" list_of_ints = [int(part) for part in source.strip().split()] > > In additional to max/min, is there something like average()? Not AFAIK, but it's really trivial def average(lst): """ assume lst is a list of numerics """ return sum(lst) / len(lst) From roy at panix.com Thu Dec 4 15:11:08 2008 From: roy at panix.com (Roy Smith) Date: Thu, 4 Dec 2008 12:11:08 -0800 (PST) Subject: Checking if an int fits in 32 bits? Message-ID: I'm working with marshaling data over a binary wire protocol. I'm using struct.pack() to handle the low-level encoding of ints. One of the things I need to do is make sure an int can be represented in 4 bytes. Is there a portable way to do that? For now, I'm doing signed ints, but I'll certainly have to do unsigned 32-bit ints (and 64-bit ints) at some point. Not to mention shorts and chars. At first I thought pack() might raise an exception on a value overflow, that but doesn't seem to be the case: >>> [hex(ord(c)) for c in struct.pack('!i', 999999999999999999999L)] ['0xde', '0x9f', '0xff', '0xff'] Should I be thinking more along the lines of bit masking (and worrying about all the niggling 2-complement issues) in the Python code? Or is there some cleaner way to do this? From alwaseem307ster at yahoo.com Thu Dec 18 02:20:15 2008 From: alwaseem307ster at yahoo.com (klia) Date: Wed, 17 Dec 2008 23:20:15 -0800 (PST) Subject: importing csv file into sqlite In-Reply-To: <21067453.post@talk.nabble.com> References: <21067453.post@talk.nabble.com> Message-ID: <21068111.post@talk.nabble.com> klia wrote: > > hey guys, i have a hug .csv file which i need to insert it into sqlite > database using python. > my csv data looks like this > Birthday2,12/5/2008,HTC,this is my birthday > Sea,12/3/2008,kodak,sea > birthday4,14/3/2009,samsung,birthday > love,17/4/2009,SONY,view of island > > can any one give me a head start codes. > > thanks in advance > guys so far i came out with this but i get this error waseem at Linux:~/Project2$ python experment.py Traceback (most recent call last): File "experment.py", line 13, in curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item) sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 4, and there are 1 supplied. here's the codes import sqlite3 import csv f = open('/home/waseem/Project2/photos.txt') csv.field_size_limit(100000) #see below! input = csv.reader(f, delimiter='\t') conn = sqlite3.connect('/home/waseem/Project2/picutres.db') curse = conn.cursor() curse.execute('CREATE TABLE photos (Name VARCHAR(100) PRIMARY KEY, Date INTEGER, Make VARCHAR(50), Tag VARCHAR(100))') for item in input: curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item) curse.commit() -- View this message in context: http://www.nabble.com/importing-csv-file-into-sqlite-tp21067453p21068111.html Sent from the Python - python-list mailing list archive at Nabble.com. From cesium5500 at yahoo.ca Fri Dec 5 09:27:39 2008 From: cesium5500 at yahoo.ca (Guy Doune) Date: Fri, 05 Dec 2008 09:27:39 -0500 Subject: pretty strange behavior of "strip" FORGET THE LAST ONE In-Reply-To: <493936EC.9030606@yahoo.ca> References: <4938693F.6090709@yahoo.ca> <493936EC.9030606@yahoo.ca> Message-ID: <49393A5B.9090009@yahoo.ca> Guy Doune a ?crit : > Ok, didn't show the whole problem... > > I will read the doc anyway, but why "questions.html" keep it "t"?? > > >>> test=['03.html', '06.html', 'questions.html', '04.html', > 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test[4] > 'toc.html' > >>> test[4].strip('.html') > 'oc' > >>> test[2].strip('.html') > 'questions' > > Thanks. > > Guy > > Guy Doune a ?crit : >> Hi everybody, >> >> Could it be a bug????? >> >> Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) >> [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> test=['03.html', '06.html', 'questions.html', '04.html', >> 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] >> >>> test >> ['03.html', '06.html', 'questions.html', '04.html', 'toc.html', >> '01.html', '05.html', '07.html', '02.html', '08.html'] >> >>> test[4] >> 'toc.html' >> >>> test[4].strip('.html') >> 'oc' >> >> Can't figure out what is going on, really. >> >> Guy >> > From bignose+hates-spam at benfinney.id.au Mon Dec 1 15:54:55 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 02 Dec 2008 07:54:55 +1100 Subject: Emacs vs. Eclipse vs. Vim References: <1228094836.4406.6.camel@generator> Message-ID: <87myffwr8g.fsf@benfinney.id.au> Peter Anderson writes: > What I have done is skipped the whole Vim/Emacs obscure editor thing > and opted for PyScripter PyScripter is not obscure, compared to Emacs and Vim? I think I need a new ironometer. -- \ ?I went to a garage sale. ?How much for the garage?? ?It's not | `\ for sale.?? ?Steven Wright | _o__) | Ben Finney From rt8396 at gmail.com Sun Dec 14 01:24:42 2008 From: rt8396 at gmail.com (r) Date: Sat, 13 Dec 2008 22:24:42 -0800 (PST) Subject: 1 or 1/0 doesn't raise an exception References: <49446E39.6020807@tim.thechases.com> Message-ID: <8972c415-2fbb-479f-8a03-b8b29b20ac42@g38g2000yqn.googlegroups.com> > Let me just point out that unsuspecting people (like me) might rely on > the whole expression to be evaluated and rely on exceptions being > raised if needed. This happens when people assume something ;) Use a different construct if you want to catch error's, I don't understand how you could not get it? >>> bool(1) True >>> bool(0) False >>> bool([]) False >>> bool([0]) True >>> bool([0,0,0]) True >>> bool({}) False >>> bool(()) False see a pattern here? >>> [] or {} or () or 0 or 1 1 >>> bool('python rules!') True From noone at lewscanon.com Mon Dec 1 20:31:17 2008 From: noone at lewscanon.com (Lew) Date: Mon, 01 Dec 2008 20:31:17 -0500 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: Jon Harrop wrote: > Xah Lee wrote: (nothing Java-related) Please take this crud out of the Java newsgroup. -- Lew From eliben at gmail.com Tue Dec 9 02:46:01 2008 From: eliben at gmail.com (eliben) Date: Mon, 8 Dec 2008 23:46:01 -0800 (PST) Subject: SequenceMatcher bug ? Message-ID: Hello, This is about Python 2.5.2 - I don't know if there were fixes to this module in 2.6/3.0 I think I ran into a bug with difflib.SequenceMatcher class. Specifically, its ratio() method. The following: SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + [5]).ratio () returns 0.0 While the same with 500 replaced by 100 returns .99... something Looking at the code of SequenceMatcher there's some caching going on when the sequences are longer than 200 elements (and indeed, I can reproduce the bug above 200 but not below). Can anyone confirm that this misbehaves and suggest a workaround ? P.S. quick_ratio() works fine, it seems. Thanks Eli From tjreedy at udel.edu Wed Dec 10 13:54:42 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 10 Dec 2008 13:54:42 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Rasmus Fogh wrote: > Rhamphoryncus wrote: >> You grossly overvalue using the "in" operator on lists. > > Maybe. But there is more to it than just 'in'. If you do: >>>> c = numpy.zeros((2,)) >>>> ll = [1, c, 3.] > then the following all throw errors: > 3 in ll, 3 not in ll, ll.index(3), ll.count(3), ll.remove(3) > c in ll, c not in ll, ll.index(c), ll.count(c), ll.remove(c) > > Note how the presence of c in the list makes it behave wrong for 3 as > well. So do not put numpy arrays into lists without wrapping them. They were designed and semi-optimized, by a separate community, for a specific purpose -- numerical computation -- and not for 'playing nice' with other Python objects. It is a design feature of Python that people can implement specialized objects with specialized behaviors for specialized purposes. From paul at boddie.org.uk Fri Dec 5 08:45:40 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 5 Dec 2008 05:45:40 -0800 (PST) Subject: ANN: Shed Skin 0.0.30, an experimental (restricted-)Python-to-C++ Compiler References: Message-ID: <69be21c3-c71d-42a2-9d23-fdea8a832dd0@o40g2000prn.googlegroups.com> On 5 Des, 12:24, "Mark Dufour" wrote: > Hi all, > > I have just released version 0.0.30 of Shed Skin, an experimental > (restricted) Python-to-C++ compiler. I think Mark forgot to post some links. ;-) http://shed-skin.blogspot.com/ http://code.google.com/p/shedskin/ Paul From bdesth.quelquechose at free.quelquepart.fr Sun Dec 21 14:41:37 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 21 Dec 2008 20:41:37 +0100 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: <494ea9a5$0$24542$426a34cc@news.free.fr> r a ?crit : > I noticed when i mentioned "self" nobody wants to touch that subject. > There could be many reasons why... > > 0.) nobody but the 10 regulars i see here exists > 1.) nobody cares(doubt it) > 2.) nobody is brave enough to question it(maybe) > 3.) most people like to type self over and over again(doubt it) > 4.) most people here have given up on changing the BDFL's mind about > it. (good possibility) > 5.) this is a hot-button topic(no doubt in my mind!) 6.) you are definitevely clueless. (snip) > I love python's classes, but HATE self.redundant! This declaration only makes clear that answer to your above question is #6. > This really needs to > be fixed, Your ignorance needs to be fixed, yes, indeed. Please go and fix it - all the relevant materials is available in (or linked from somewhere in) this newgroup's archives. > and you have not heard the last from me about it!!! As far as I'm concerned, yes. Welcome to my bozo filter. Please come back when you'll have grown a brain. From p.f.moore at gmail.com Sun Dec 14 12:51:03 2008 From: p.f.moore at gmail.com (Paul Moore) Date: Sun, 14 Dec 2008 09:51:03 -0800 (PST) Subject: Looking for the best way to translate an idiom References: <4945406a$0$1127$426a74cc@news.free.fr> Message-ID: <2c5ad999-47f9-4040-85c9-4c9438afe4bb@b41g2000pra.googlegroups.com> On 14 Dec, 16:22, Bruno Desthuilliers wrote: > if you only want the first returned value, you can just apply a slice: > > def f(): > ? ? return 1,2,3 > > a = f()[0] + 1 Hmm, true. I'm not sure it's any less ugly, though :-) > FWIW, Python 2.6 has NamedTuple objects... I know, but I want to target 2.5+ (I still have a number of systems running 2.5) > > - have 2 calls, one to return just the position, one to return both. > > This feels awkward, because of the 2 method names to remember. > > You forgot one solution: passing a flag to the function to specify if > you want only the main result or the extra ones as well, and give this > flag the appropriate default value depending on most common use case. True, that's another option. It might work, I'll think about it. > The one that happens to be the most simple for the most common usecase, > while still providing support for more advanced stuff. Exactly. I'll have to think some more about real use cases. > > I suspect my intuition isn't accurate here, as most of the use I've > > made of the library is in writing tests, which isn't typical use :-( > > So perhaps you should start writing some real-life code ? :-) Once I have a library that's functional enough to do so, I may well. Chicken and egg situation, to some extent... And I don't really feel like switching to Lua just to get a feel for how the library gets used! > > Thanks for any assistance. > > Not sure I've been that helpful. Sorry... Any feedback helps. Thanks for taking the time. Paul. From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 30 04:34:21 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 30 Dec 2008 10:34:21 +0100 Subject: SQL, lite lite lite In-Reply-To: <8vco26x1v6.ln2@joelaptop.homelan.net> References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> <8vco26x1v6.ln2@joelaptop.homelan.net> Message-ID: <4959eb17$0$32023$426a74cc@news.free.fr> Johannes Bauer a ?crit : (snip) > Even if it took (as you mentioned) a semester of SQL studies - which it > does not - why do you think your syntax is easier? The only person your > proposed syntax is easier for is you. Get over it, learn SQL, and enjoy > the benefits of one unified standard - not everyone cooking their own > soup. You'll be able to learn PostgreSQL, Oracle SQL, mySQL, SQlite all > at once! Oh what a beautiful dream... We all wish we'd live in such a perfect world. Sadly, it's not the case. First because each SQL vendor cooks its own soup, so you still have to learn each SQL implementation, limitations and gory details. Also, because handling SQL queries as raw strings is more than painfull. It just doesn't play well with the host language. So any non trivial project ends up reinventing its own half-backed abstraction layer, that you have to learn too. Now I don't mean that learning SQL (and the relational theory behind SQL) is a waste of time. You obviously need a good understanding of SQL to use a SQL database - directly or thru any abstraction layer. We definitively agree on this. But a smart abstraction layer (like SQLAlchemy, or even the less powerfull but still pretty good Django ORM) at least avoids reinventing a new one for each project. My 2 cents... From google at mrabarnett.plus.com Sun Dec 21 11:33:30 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 21 Dec 2008 16:33:30 +0000 Subject: Python is slow In-Reply-To: <6r6hpfFfb643U3@mid.uni-berlin.de> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> <6r6hpfFfb643U3@mid.uni-berlin.de> Message-ID: <494E6FDA.4070401@mrabarnett.plus.com> Marc 'BlackJack' Rintsch wrote: > On Sat, 20 Dec 2008 14:18:40 -0800, cm_gui wrote: > >>> Seriously cm_gui, you're a fool. >>> Python is not slow. >> haha, getting hostile? >> python fans sure are a nasty crowd. >> >> Python is SLOW. >> >> when i have the time, i will elaborate on this. > > You are not fast enough to elaborate on Python's slowness!? :-) > > cm_gui is slow! > > Ciao, > Marc 'BlackJack' Rintsch > Correction: cm_gui is SLOW! :-) From ptmcg at austin.rr.com Mon Dec 8 14:21:00 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 8 Dec 2008 11:21:00 -0800 (PST) Subject: Text parsing via regex References: Message-ID: <37b28494-c98f-4e06-a451-8a4702030f10@v38g2000yqb.googlegroups.com> On Dec 8, 12:13?pm, Robocop wrote: > I'm having a little text parsing problem that i think would be really > quick to troubleshoot for someone more versed in python and Regexes. > I need to write a simple script that parses some arbitrarily long > string every 50 characters, and does not parse text in the middle of > words Are you just wrapping text? If so, then use the textwrap module. import textwrap source_string = "a bunch of nonsense that could be really long, or really short depending on the situation" print textwrap.fill(source_string,50) print textwrap.wrap(source_string,50) print map(len,textwrap.wrap(source_string,50)) pad50 = lambda s : (s+ " "*50)[:50] print '|\n'.join(map(pad50,textwrap.wrap(source_string,50))) Prints: a bunch of nonsense that could be really long, or really short depending on the situation ['a bunch of nonsense that could be really long, or', 'really short depending on the situation'] [49, 39] a bunch of nonsense that could be really long, or | really short depending on the situation -- Paul From ed at leafe.com Wed Dec 10 14:24:39 2008 From: ed at leafe.com (Ed Leafe) Date: Wed, 10 Dec 2008 13:24:39 -0600 Subject: Dabo 0.9.0 Released Message-ID: <47C9D05A-1D50-4690-8062-03939E1C9AE7@leafe.com> We are proud (and relieved!) to finally release Dabo 0.9.0, the first official release of the framework in six months. We haven't been taking it easy during that period; rather, we made some changes that clean up some weak spots in the codebase, and as a result can offer a much more solid framework, and are on course for a 1.0 release in the near future. To do this, we made some decisions that break backwards compatibility. We dropped support for Python versions earlier than 2.4, and wxPython versions below 2.8. Supporting everything is nice to aim for, but completely impractical. There is also a major addition to the framework: the ability to deploy Dabo applications as true web apps. Imagine: being able to develop a rich internet app using nothing but Python on both the client and server! It's still early in the development process, so it's lacking a lot of the supporting tools, and almost no documentation has been created, but that will be coming in the next few weeks/months. When you deploy your app as a web app, all data access and business logic is on the server, and the framework automatically handles the communication between the client and server. The framework also automatically grabs file changes from the server, making UI updates seamless and quick. Lots more interesting stuff will be happening in this area in the near future, so stay tuned! If you're not already familiar with Dabo, we're the premier open source framework for developing desktop (and now web!) applications in Python. We make the difficult stuff like binding databases to UI controls simple. You can grab the latest version from http://dabodev.com/download A fairly comprehensive list of the changes we've made since the last release can be found at http://svn.dabodev.com/dabo/tags/dabo-0.9.0/ChangeLog And if you want to learn more, join our email list: http://leafe.com/mailman/listinfo/dabo-users -- Ed Leafe From jeremiah.dodds at gmail.com Thu Dec 25 07:19:39 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Thu, 25 Dec 2008 07:19:39 -0500 Subject: os.system('cls') In-Reply-To: References: <05BADA85-33ED-48BF-B251-2CC830D6D55E@rgbaz.eu> Message-ID: <12cbbbfc0812250419m68de6079v7ea0d47f5c21ad94@mail.gmail.com> On Thu, Dec 25, 2008 at 7:11 AM, Dennis van Oosterhout < de.slotenzwemmer at gmail.com> wrote: > Btw...does that mean that system('cls') only works on Windows...or to > say it otherwise: the program isn't platform independant? > > Yes. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Thu Dec 25 16:29:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Dec 2008 19:29:14 -0200 Subject: question; C/C++ with Python References: <123f104c-0edc-423f-841d-70d8d9492ddd@r15g2000prd.googlegroups.com> Message-ID: En Thu, 25 Dec 2008 12:50:31 -0200, Hongtian escribi?: > I have a C/C++ application and I wrote a .py file to extend it. > The .py file includes some simple functions without import any other > modules. And you embedded the Python interpreter into your application, I presume? > Today, I want to update my .py file and import SMTP library in the > file, but it seems fail to import SMTP library. > > So I want to ask: when the .py file is used to extend C/C++ > application, can it import other modules? Sure! Just make sure the desired modules can be found along the Python search path (that is, sys.path) > How to do that? should I > copy all pythons libs to my C/C++ application directory? That could be > terrible... If you want to distribute your application, this would be a good thing, else you must rely on the right Python version being installed somewhere. You may add the required entries to sys.path manually, in your code. Or you may define the PYTHONPATH environment variable (also in your code) before initializing the interpreter. Or you may call the function Py_SetProgramName (before initializing) pointing to your external Python installation. -- Gabriel Genellina From google at mrabarnett.plus.com Mon Dec 22 14:10:11 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 22 Dec 2008 19:10:11 +0000 Subject: Python's popularity In-Reply-To: References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: <494FE613.5080107@mrabarnett.plus.com> r wrote: > Steve Holden >> What makes you assume this is a zero-sum game, and that Python won't >> survive if any other language becomes popular. Every language borrows >> from those that came before it. Terms like "outright plagiarism" don't >> encourage rational debate, and make you seem like a troll who is more >> interested in stirring up controversy than actually doing things to help >> promote the language. > > This is a war Steve, and i will explain why. Python does not need to > compete with perl, lisp, C, basic, etc, etc. WHY, well because python > is SO radically different than those languages. Ruby on the other > hand, took most from python, the only difference is Ruby's full OO > integration.(12.method()). Since Ruby is so similar to python we must > consider that some people who would have found only python in this > niche now could go to Ruby. I am for choices, but this is out and out > robbery! > Of course we must stand on the shoulders of greater minds than our own > to get ahead, but using someone's knowledge against them is wrong. If > Ruby want's to incorporate so many Pythonian ideas into their > language, at least put a note in the tutorial giving credit to Guido > for his wisdom. Don't use our ideas and then bash python in the next > breath! > [snip] "Pythonian"? A real Pythonista would know it's "Pythonic"! A real Pythonista would be called "p", not "r", which sounds very Rubish(?) to me... From Slaunger at gmail.com Thu Dec 4 04:09:08 2008 From: Slaunger at gmail.com (Slaunger) Date: Thu, 4 Dec 2008 01:09:08 -0800 (PST) Subject: Pythonic design patterns Message-ID: Hi comp.lang.python I am this novice Python programmer, who is not educated as a computer scientist (I am a physicist), and who (regrettably) has never read the GOF on design patterns. I find myself spending a lot of time in Python making some designs, to solve some task, which is the end turn out to be closely related to well established design patterns / programming idioms, which other users in this forum has been kind enough to point out. Only my implementations are often not that clean, and I may call things something different than the normal convention, which is a source of confusion for myself and others trying to communicate with me. I guess I could boost my productivity by learning these well-proven and well-established design patterns by heart. I was therefore wondering if you could recommend a book or a resource concerning design patterns with special focus on the possibilities in Python? In that manner I may be able to both learn programming more pythonic AND learn the design patterns. -- Slaunger From jamskip at googlemail.com Mon Dec 15 04:56:37 2008 From: jamskip at googlemail.com (jamskip at googlemail.com) Date: Mon, 15 Dec 2008 01:56:37 -0800 (PST) Subject: Thread Locking issue - Can't allocate lock (sem_init fail) Message-ID: Hi all, I have a peculiar problem with a multithreaded program of mine (actually I've sort of inherited it). Before i show you the error, here's a litle background. Its a program to check email addresses are valid, and its main task is to verify the domain names. Here's the basic functionality: * The prog has a list of domains it has seen before which is read into memory (the 'rollover'). * A new list of emails is read-in from a file (to a queue) and is checked against the rollover. * If we've seen the domain before then update the existing entry. * If we've not seen the domain before, add it. The program is multithreaded to speed up the processing...there are input and output Queues. Now, each domain entry is an class object containing various bits of info. Each domain class also has its own lock, so that only one thread can modify each domain at a time. I'm load-testing the program with a sample of 1 million email addresses and when i hit about the 500,000 mark i get a locking error... sem_init: No space left on device Exception in thread Thread-2: Traceback (most recent call last): File "/usr/local/lib/python2.4/threading.py", line 442, in __bootstrap self.run() File "/usr/local/lib/python2.4/threading.py", line 422, in run self.__target(*self.__args, **self.__kwargs) File "jess.py", line 250, in worker record.result = function( id, record.value ) File "jess.py", line 291, in action found_domain = domains.addNewDomain( domain_name ) File "jess.py", line 123, in addNewDomain self.domain_store.append( self.Domain( name = name ) ) File "jess.py", line 46, in __init__ self.lock = Lock() error: can't allocate lock Googling for this sort of error doesn't yield any results, and i can't find any information about limits to the number of locks you can have in Python. The 'No space left on device' message indicates a memory issue, however i doubt this since its running on a linux server with 4 cores and 16GB ram. It seems more like an internal Python limit has been hit (sem_init - semaphore initialisation?). Does anyone know more about threading internals and any internal limits? For the timebeing, I've implemented locking at a higher level which will reduce performance but keep the number of lock objects to a minumum. Thanks From skip at pobox.com Thu Dec 11 09:48:48 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 11 Dec 2008 08:48:48 -0600 Subject: How can I understan the "for" here? In-Reply-To: <49412744.8040301@gmail.com> References: <49412744.8040301@gmail.com> Message-ID: <18753.10320.829867.403714@montanaro-dyndns-org.local> Kermit> I can't understand the second sentence because of the "for Kermit> ... in". Google for "python list comprehensions". -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From arnodel at googlemail.com Tue Dec 2 17:38:14 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 2 Dec 2008 14:38:14 -0800 (PST) Subject: best way to do this References: Message-ID: <24947f71-3a1c-4ea9-9b8b-8efdcbfbe5f4@v42g2000yqv.googlegroups.com> On Dec 2, 2:09?pm, TP wrote: > Hi everybody, > > >>> c=[(5,3), (6,8)] > > From c, I want to obtain a list with 5,3,6, and 8, in any order. > I do this: > > >>> [i for (i,j) in c] + [ j for (i,j) in c] > > [5, 6, 3, 8] > > Is there a quicker way to do this? > One list comprehension is enough: >>> c=[(5,3), (6,8)] >>> [x for t in c for x in t] [5, 3, 6, 8] HTH -- Arnaud From xahlee at gmail.com Mon Dec 8 12:34:43 2008 From: xahlee at gmail.com (Xah Lee) Date: Mon, 8 Dec 2008 09:34:43 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> Message-ID: <0201522a-b15a-4401-a208-5d9af70bdd74@w24g2000prd.googlegroups.com> On Dec 8, 5:10 am, Jon Harrop wrote: > Xah Lee wrote: > > For those interested in this Mathematica problem, i've now cleaned up > > the essay with additional comments here: > > > ? A Mathematica Optimization Problem > > http://xahlee.org/UnixResource_dir/writ/Mathematica_optimization.html > > In that article you say: > > > Further, if Intersect is made to take a flat sequence of argument as > > in ?Intersect[o_, d_, lambda_, n_, c_, r_, s_]?, then pattern matching can > > be avoided by making it into a pure function ?Function?. And when it is > > a ?Function?, then Intersect or part of it may be compiled with Compile. > > When the code is compiled, the speed should be a order of magnitude > > faster. > That is incorrect. Mathematica's Compile function cannot handle recursive > functions like Intersect. i didn't claim it can. You can't expect to have a fast or good program if you code Java style in a functional lang. Similarly, if you want code to run fast in Mathematica, you don't just slap in your OCaml code into Mathematica syntax and expect it to work fast. If you are a Mathematica expert, you could make it recurse yet have the speed as other langs. First, by changing your function's form, to avoid pattern matching, and rewrite your bad recursion. That is what i claimed in the above paragraph. Read it again to see. > For example: > In[1]:= Compile[{n_, _Integer}, If[# == 0, 1, #0[[# n - 1]] #1] &[n]] > > During evaluation of In[1]:= Compile::fun: Compilation of > (If[#1==0,1,#0[[#1 n-1]] #1]&)[Compile`FunctionVariable$435] cannot > proceed. It is not possible to compile pure functions with arguments > that represent the function itself. >> Mathematica's Compile function is intended to speed up numerical computation. To want Compile to handle recursion in the context of Mathematica's programing features, is not something possible even in theoretical sense. Scheme lisp implementations can compile recursive code, but lisp is a lower level lang than Mathematica, where perhaps the majority of Mathematica's builtin functions can equate to 10 or more lines of lisp, and any of its hundreds math functions equates to entire libraries of other langs. It is reasonable, but silly, to expect Mathematica's Compile function to compile any code in Mathematica. Perhaps in the future version of Mathematica, its Compile function can handle basic recursive forms. Also, in this discussion, thanks to Thomas M Hermann's $20 offered to me for my challenge to you, that i have taken the time to show working code that demonstrate many problems in your code. Unless you think my code and replies to you are totally without merit or fairness, but otherwise you should acknowledge it, in whole or in parts you agree, in a honest and wholehearted way, instead of pushing on with petty verbal fights. Xah ? http://xahlee.org/ ? From bdesth.quelquechose at free.quelquepart.fr Wed Dec 17 16:11:19 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 17 Dec 2008 22:11:19 +0100 Subject: Why no lexical scoping for a method within a class? In-Reply-To: <5ad98089-883f-4ca6-934e-605e2376439c@f40g2000pri.googlegroups.com> References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> <5ad98089-883f-4ca6-934e-605e2376439c@f40g2000pri.googlegroups.com> Message-ID: <494978ad$0$22014$426a74cc@news.free.fr> walterbyrd a ?crit : > On Dec 17, 8:41 am, prueba... at latinmail.com wrote: > >> If scoping worked as you want, how, pray tell, would you define object >> attributes?- Hide quoted text - > > I suppose you could do this: > > class className(): > varname = "whatever" This defines a class attribute - that is, an attribute of the className class object, accessible either thru the className object or it's instances if not shadowed by an instance attribute by the same name/ > def fname(self, varname): > . . . . > > Instead of having variable defined within methods to be global > everywhere within the class. There's nothing like a "variable defined within (a) method", because you never define methods in Python - only functions. So there's no difference in scoping rules for functions defined within a class statement block or outside a class statement block. > Anyway, it's not a matter of what I like, I am just trying to > understand the reason behind the scoping rules. Then you should start with understanding the scoping rules. From deets at nospam.web.de Sat Dec 13 13:36:59 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 13 Dec 2008 19:36:59 +0100 Subject: [OT] stable algorithm with complexity O(n) In-Reply-To: References: Message-ID: <6qidmbFc4qduU1@mid.uni-berlin.de> David Hl??ik schrieb: > Hi guys, > > i am really sorry for making offtopic, hope you will not kill me, but > this is for me life important problem which needs to be solved within > next 12 hours.. > > I have to create stable algorithm for sorting n numbers from interval > [1,n^2] with time complexity O(n) . > > Can someone please give me a hint. Would be very very thankful! Unless I grossly miss out on something in computer science 101, the lower bound for sorting is O(n * log_2 n). Which makes your task impossible, unless there is something to be assumed about the distribution of numbers in your sequence. Who has given you that assignment - a professor? Or some friend who's playing tricks on you? Diez From grante at visi.com Sun Dec 7 10:48:19 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 07 Dec 2008 09:48:19 -0600 Subject: how to get a beep, OS independent ? References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> Message-ID: On 2008-12-07, Joe Strout wrote: > But invoking the standard system beep What makes you think there is such a thing as "the standard system beep"? -- Grant From invalid at invalid Tue Dec 23 15:57:52 2008 From: invalid at invalid (Grant Edwards) Date: Tue, 23 Dec 2008 14:57:52 -0600 Subject: pseudo terminal usage from Python? References: <5t-dnRgMi9Z4lszUnZ2dnUVZ_vOdnZ2d@posted.visi> Message-ID: <1JqdnU9Oz9ZNzczUnZ2dnUVZ_hCdnZ2d@posted.visi> On 2008-12-23, skip at pobox.com wrote: > Grant> Are you sure it's not Python buffering its input? Have you tried > Grant> "python -u mympstat.py"? > > >> Nope. -u unbuffers stdout and stderr, not stdin. It really must be > >> mpstat being uncooperative. > > Grant> That's not what my python man page says: > > Grant> -u Force stdin, stdout and stderr to be totally > Grant> unbuffered. On systems where it matters, also put > Grant> stdin, stdout and stderr in binary mode. > > Grant> That's for 2.5.2, but that's how I remember previous versions > Grant> working as well. > > I'm still running 2.4.5 at work. It's -u help: > > -u : unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x) > see man page for details on internal buffering relating to '-u' > > Was stdin unbuffering maybe added in 2.5? Let's do some experiments... $ cat echo.py import sys while 1: line = sys.stdin.readline() sys.stdout.write(line) $ (while sleep 1; do date; done) | python2.4 echo.py [I see a line printed once per second.] $ (while sleep 1; do date; done) | python2.5 echo.py [same as 2.4] Is python stdin is line-buffered by default? We'll do a version that doesn't have newlines in the input stream... $ cat echo2.py import sys while 1: sys.stdout.write(sys.stdin.read(1)) $ (while sleep 1; do echo -n $(date); done) | python2.4 echo2.py [wait 10-20 seconds -- no output. When I hit ctrl-C, I see a all the output.] $ (while sleep 1; do echo -n $(date); done) | python2.5 echo2.py [same as 2.4] It appears the by default both 2.4 and 2.5 have line-buffered stdin. Let's try -u... $ (while sleep 1; do echo -n $(date); done) | python2.4 -u echo2.py [I see output once per second.] $ (while sleep 1; do echo -n $(date); done) | python2.5 -u echo2.py [same as 2.4] Under Linux, the '-u' option unbuffers stdin in both 2.4 and 2.5. It just isn't mentioned in the help output or the man page for 2.4. -- Grant Edwards grante Yow! Will the third world at war keep "Bosom Buddies" visi.com off the air? From Slaunger at gmail.com Tue Dec 9 18:24:28 2008 From: Slaunger at gmail.com (Slaunger) Date: Tue, 9 Dec 2008 15:24:28 -0800 (PST) Subject: Best way to report progress at fixed intervals References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> Message-ID: <43016471-d0ce-4912-b18d-03407928acf1@w1g2000prm.googlegroups.com> On 10 Dec., 00:11, rdmur... at bitdance.com wrote: > >> ? ? ? ? ?# Monitoring loop. > >> ? ? ? ? ?loops = 0 > >> ? ? ? ? ?# We're going to loop ten times per second using an integer count, > >> ? ? ? ? ?# so multiply the seconds parameter by 10 to give it the same > >> ? ? ? ? ?# magnitude. > >> ? ? ? ? ?intint = int(self.progress_interval*10) > > Is this not an unnecessary complication? > >> ? ? ? ? ?# isAlive will be false after dowork returns > >> ? ? ? ? ?while worker.isAlive(): > >> ? ? ? ? ? ? ?loops += 1 > >> ? ? ? ? ? ? ?# Wait 0.1 seconds between checks so that we aren't chewing > >> ? ? ? ? ? ? ?# CPU in a spin loop. > >> ? ? ? ? ? ? ?time.sleep(0.1) > > Why not just call this with progress_interval directly? > > Because then the program make take up to progress_interval seconds to > complete even after all the work is done. ?For a long running program > and a short progress_interval that might not matter, so yes, that would > be a reasonable simplification depending on your requirements. > Ah, OK. With my timer.cancel() statement in my original proposal I avoided that. > > > OK. I agree this is a more elegant implementation, although I my mind, > > I find it more natural if the reporting goes on in a subthread, but > > You could pretty easily rewrite it to put the reporter in the subthread, > it was just more natural to _me_ to put the worker in the subthread, > so that's how I coded it. ?Note, however, that if you were to write a > GUI front end it might be important to put the worker in the background > because on some OSes it is hard to update GUI windows from anything > other than the main thread. ?(I ran into this in a Windows GUI ap I > wrote using wxPython). > Ah, yes, you right. For GUIs this is often quite important. I don't do much GUI, so This is not something I had strongly in mind. Br, -- Slaunger From lists at cheimes.de Fri Dec 12 10:55:57 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 12 Dec 2008 16:55:57 +0100 Subject: Python is slow In-Reply-To: <8156b37b-d1f6-4142-ad6e-8488c95b6592@z28g2000prd.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> <8156b37b-d1f6-4142-ad6e-8488c95b6592@z28g2000prd.googlegroups.com> Message-ID: sturlamolden schrieb: > On Dec 12, 3:04 pm, Luis M. Gonz?lez wrote: > >> Why don't you guys google a little bit to know what's being done to >> address python's "slowness"?? > > Nothing is being done, and woth Py3k it got even worse. Indeed, it *is* slower for now. As I already said in another thread our top priorities were feature completeness and bug fixing. Optimizations will follow the features in the near future. Christian From joe at strout.net Mon Dec 22 17:16:24 2008 From: joe at strout.net (Joe Strout) Date: Mon, 22 Dec 2008 15:16:24 -0700 Subject: Python's popularity In-Reply-To: References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <18767.47566.709705.92@montanaro-dyndns-org.local> Message-ID: <495011B8.1050607@strout.net> Alvin ONeal wrote: > Also worthy of mention: > I've seen python pre-installed on consumer HP desktops (I think as > part of a backup/restore script, but I'm not sure) It's pre-installed on every Mac (both desktop and laptop), too. Cheers, - Joe From skip at pobox.com Thu Dec 11 17:50:12 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 11 Dec 2008 16:50:12 -0600 Subject: Python 2.5.2 error on Solaris, No module named _md5 In-Reply-To: References: Message-ID: <18753.39204.493828.300991@montanaro-dyndns-org.local> Shawn> When I "import md5", I got: ... Shawn> import _md5 Shawn> ImportError: No module named _md5 Check the output of the build process to see if the _md5 extension failed to build, and if so, dig into the setup.py file a bit. It's likely that you forgot to include the proper include and lib directories when building Python so distutils didn't know where to find the necessary header files and libraries. Also, make sure the necessary stuff is actually installed on your system. Many Linux systems install header files and libraries as separate packages. You might have the latter but not the former. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From rt8396 at gmail.com Sat Dec 20 19:27:22 2008 From: rt8396 at gmail.com (r) Date: Sat, 20 Dec 2008 16:27:22 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> <59153e28-bf86-4158-96d9-23aa5b9f0205@j35g2000yqh.googlegroups.com> Message-ID: <52b8e001-2cc7-4891-8540-a3cdb6b78533@e25g2000vbe.googlegroups.com> Thanks MRAB, except the float is not 2 decimal places, but its there Come on... They did this for the interpreter not us. It's easer to parse this string with positional arguments and a dict of format descriptions. Come on pydev, at least be honest about it! From BrooklineTom at gmail.com Wed Dec 10 23:48:01 2008 From: BrooklineTom at gmail.com (brooklineTom) Date: Wed, 10 Dec 2008 20:48:01 -0800 (PST) Subject: Deeper tracebacks? References: <7e1c74f0-8f72-4a88-935b-90b77fe5aaa5@s37g2000vbp.googlegroups.com> Message-ID: On Dec 10, 10:49 pm, "Chris Rebert" wrote: > On Wed, Dec 10, 2008 at 3:50 PM, brooklineTom wrote: > > On Dec 10, 5:03 pm, "Gabriel Genellina" > > wrote: > >> En Wed, 10 Dec 2008 16:59:16 -0200, brooklineTom > >> escribi?: > > >> > I want my exception handler to report the method that originally > >> > raised an exception, at the deepest level in the call-tree. Let give > >> > an example. > > >> That's the default behavior, you don't have to do anything special. > > >> > import sys, traceback > >> > class SomeClass: > >> > def error(self): > >> > """Raises an AttributeError exception.""" > >> > int(3).zork() > > >> > def perform_(self, aSelector): > >> > try: > >> > aMethod = getattr(self, aSelector, None) > >> > answer = apply(aMethod, [], {}) > >> > except: AttributeError, anAttributeErrorException: > >> > aRawStack = traceback.extract_stack() > >> > answer = None > > >> (I assume you're using Python < 3.0) > >> Use the 3-names form of the except statement: > > >> try: > >> aMethod = getattr(self, aSelector, None) > >> answer = aMethod() > >> except AttributeError, e, tb: > >> # the tb variable holds the traceback up to the error > >> # the same thing you see printed by Python when > >> # an unhandled error happens > >> answer = None > > >> Alternatively, you can obtain the same thing with sys.exc_info()[2] > >> Remember to delete any reference to the traceback object as soon as you're > >> done with it; seehttp://docs.python.org/library/sys.html#sys.exc_info > > >> -- > >> Gabriel Genellina > > > I'm using Python 2.5. > > > As I understand it, "aRawStack" (above) has the same information as > > sys.exc_info()[2]. > > > The deepest entry in aRawStack is the perform_ invocation. The > > contents of the two bottom-most stack frames are: > >>>> aRawStack[8][3] > > "answer = anObject.perform_('error')" > >>>> aRawStack[9][3] > > 'aRawStack = traceback.extract_stack()' > > > By the time the handler is called, "zork" -- the method that was > > called when the exception was raised, and "error", the method that > > invoked zork, have already been removed from the stack. > > There is no zork() method, so it *can't have been called* and > therefore *can't be in the traceback*. The error lies in the method > that's trying to call a _nonexistent_ method, and that's where Python > reports the error. > > Recall that: > x.zork() > > is equivalent to: > _z = x.zork #error occurs here, in the attribute lookup > _z() #Python never gets here > > So no call takes place because you get an AttributeError before Python > can get any further. zork() would only in the traceback if (1) it was > looked up and called successfully [not the case here] and (2) an error > occurred in zork()'s method body [again, not the case because it's not > defined]. > > Cheers, > Chris > > -- > Follow the path of the Iguana...http://rebertia.com I understand that there is no method named "zork". The attempted call to zork occurred in the method named "error", *not* the method named "perform_". I suggest that the failing method is "error", and the reported line number should be the line that contains "int(3).zork". Specifically, I think that aRawStack should contain the following: >>> aRawStack[8][3] "answer = anObject.perform_('error')" >>> aRawStack[9][3] "answer = anObject.error()" >>> aRawStack[10][3] 'aRawStack = traceback.extract_stack()' The entry at aRawStack[9] is the stack frame that I suggest is missing. Thx, Tom From igouy2 at yahoo.com Tue Dec 23 17:21:01 2008 From: igouy2 at yahoo.com (Isaac Gouy) Date: Tue, 23 Dec 2008 14:21:01 -0800 (PST) Subject: 2to3 used in the Shootout References: <4f1a8f03-fd7f-49ea-8031-61f73fb0c0e8@x16g2000prn.googlegroups.com> Message-ID: <65a43a69-1ef2-4a41-b860-a370891aecbd@g39g2000pri.googlegroups.com> On Dec 23, 11:51?am, bearophileH... at lycos.com wrote: > They have translated the Python benchmarks of the Shootout site from > Py2 to Py3 using 2to3: > > http://shootout.alioth.debian.org/u32/benchmark.php?test=all?=pyt... So please re-write those programs to remove problems created by automatic translation and better take advantage of Python 3 functionality... http://shootout.alioth.debian.org/u32/faq.php#play > It shows some "performance bugs" of Python3 itself (especially > regarding the binary-trees benchmark, that was unexpected by me), and > two points where 2to3 may be improved, for example after the > translation this gives error: > ? ? ? ? ?table=string.maketrans('ACBDGHK\nMNSRUTWVYacbdghkmnsrutwvy', > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 'TGVHCDM > \nKNSYAAWBRTGVHCDMKNSYAAWBR')): > > Gives: > TypeError: maketrans arguments must be bytes objects > > Bye, > bearophile From ali2862006 at gmail.com Thu Dec 4 18:33:30 2008 From: ali2862006 at gmail.com (mido) Date: Thu, 4 Dec 2008 15:33:30 -0800 (PST) Subject: watch football online for free Message-ID: watch football online for free Watch with us through the Internet the most important football games, watched all the competition directly and free Egyptian league - Champions of Europe - the English league - regular French - German Bundesliga - Dutch league - Portuguese league - Spanish league - Turkish league Moment by moment on our site http://live-football.t35.com From metolone+gmane at gmail.com Fri Dec 5 07:39:26 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Fri, 5 Dec 2008 04:39:26 -0800 Subject: generating a liste of characters References: Message-ID: "Yves Dorfsman" wrote in message news:YywZk.17248$st1.2898 at newsfe10.iad... > Is there any built in way to generate a list of characters, something > along the line of range('a'-'z') ? > > Right now I am using: > > chars = [ chr(l) for l in range(0x30, 0x3a) ] # 0 - 9 > chars += [ chr(l) for l in range(0x41, 0x5b) ] # A - Z > chars += [ chr(l) for l in range(0x61, 0x7b) ] # a - z > > Is there a better, more straight forward way of doing that ? Writing a helper function reduces code repetition and improves readability: def crange(startch,endch): '''Return a list of characters from startch to endch, inclusive.''' return [chr(c) for c in xrange(ord(startch),ord(endch)+1)] chars = crange('0','9') + crange('A','Z') + crange('a','z') -Mark From __peter__ at web.de Mon Dec 8 06:23:58 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 08 Dec 2008 12:23:58 +0100 Subject: built-in functions as class attributes References: <75fdbf34-34d9-4373-bbe0-7e3f76dc4c3f@x38g2000yqj.googlegroups.com> Message-ID: Mark Dickinson wrote: > Here's a curiosity: after > > def my_hex(x): > return hex(x) > > one might expect hex and my_hex to be interchangeable > in most situations. But (with both Python 2.x and 3.x) > I get: > >>>> def my_hex(x): return hex(x) > ... >>>> class T(object): f = hex > ... >>>> class T2(object): f = my_hex > ... >>>> T().f(12345) > '0x3039' >>>> T2().f(12345) > Traceback (most recent call last): > File "", line 1, in > TypeError: my_hex() takes exactly 1 argument (2 given) > [36412 refs] > > Anyone know what the precise rules that lead to this > behaviour are, or where they're documented? To work properly as a method a callable needs a __get__() method implementing the binding mechanism. Functions written in C generally don't have that. >>> class A(object): ... def __call__(self, *args): ... print "called with", args ... >>> class B(object): ... a = A() ... >>> B().a() called with () Now let's turn A into a descriptor: >>> def __get__(self, inst, cls=None): ... print inst, cls ... if inst is not None: ... def bound(*args): ... self(inst, *args) ... return bound ... return self ... >>> A.__get__ = __get__ >>> B().a() <__main__.B object at 0x2ae49971b890> called with (<__main__.B object at 0x2ae49971b890>,) I don't know if there is something official, I google for http://users.rcn.com/python/download/Descriptor.htm or "descrintro" every time I need a refresher. Peter From rt8396 at gmail.com Mon Dec 22 14:57:23 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 11:57:23 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <1d03c66b-c725-42f4-af6e-2351a7841b30@z1g2000yqn.googlegroups.com> Message-ID: On Dec 22, 1:50?pm, Luis M. Gonz?lez wrote: > On Dec 22, 3:44?pm, r wrote: > > > > > Steve Holden > > > > What makes you assume this is a zero-sum game, and that Python won't > > > survive if any other language becomes popular. Every language borrows > > > from those that came before it. Terms like "outright plagiarism" don't > > > encourage rational debate, and make you seem like a troll who is more > > > interested in stirring up controversy than actually doing things to help > > > promote the language. > > > This is a war Steve, and i will explain why. Python does not need to > > compete with perl, lisp, C, basic, etc, etc. WHY, well because python > > is SO radically different than those languages. Ruby on the other > > hand, took most from python, the only difference is Ruby's full OO > > integration.(12.method()). Since Ruby is so similar to python we must > > consider that some people who would have found only python in this > > niche now could go to Ruby. I am for choices, but this is out and out > > robbery! > > Of course we must stand on the shoulders of greater minds than our own > > to get ahead, but using someone's knowledge against them is wrong. If > > Ruby want's to incorporate so many Pythonian ideas into their > > language, at least put a note in the tutorial giving credit to Guido > > for his wisdom. Don't use our ideas and then bash python in the next > > breath! > > > > I have an article about the Zen coming up in "Python Magazine" so I > > > won't steal its thunder. Suffice it to say that people take the Zen far > > > too seriously. Anyone who does so undermines their own credibility as a > > > Python commentator. This isn't a war. Stop being childish. > > > I was speaking to the loyalty of Pythonista's. Of course we are not > > really going to slay mats, come on Steve, get real! > > > > If all you want from a language is speed, go use C. I would avoid > > > assembly language though, since a modern optimizing C compiler will > > > often beat an assembly language programmer for execution speed, and the > > > programming time will definitely be shorter. But to make speed the > > > be-all and end-all is a witless approach. Speed is definitely not why > > > dynamic languages' popularity is increasing. Speed *is* still relevant > > > in certain areas, and completely irrelevant in others. > > > Come on Steve, i am NOT saying speed is the only thing that matters > > here! But it is very important. I never compared Python to C, that is > > madness. But it must be better, faster, smarter than it's direct > > competition(ruby)... you agree?? > > > > Much more of this kind of tripe and nobody will read what you write > > > anyway. You will hear the plonking of a hundred thousand newsreaders > > > every time you post. > > > Oh Steve... Listen, my words are ment as a wake-up-call to all who > > still love Python, and i believe you are one of them. Maybe old age > > has slowed your hand, that's OK, Us "youngsters" will take the helm. > > And be serious, do you really think this group is read by "hundreds-of- > > thousands of news readers? I wish it were, but I highly doubt it. > > Dude, calm down... There is no war here. > Please turn off your computer, go take a walk for awhile, experience > some real life in the outer world, and then think about this again. > Python is cool language, Ruby too. We are all happy and competition is > good. > Nobody will win this "war" and the loser won't be annihilated. I hope > there will be some healthy cross-pollination. > There is actually, for example python borrowed list-comprehensions > from haskell and I've never heard any haskell fan calling for jihad. > > Did you know that people are looking forward to use pypy to create a > fast ruby implementation? > Pypy is being developed by python developers and they will be happy to > see a ruby, perl, logo or whatever language implemented with pypy. We > are talking about tools, not religions. > Those who use them to create useful, real life applications know it. > > Soon, we will be able to use python libraries from ruby and the other > way around. the differences will be just a matter of taste, different > syntax to achieve the same tasks. > > Luis Your right, Python needs Ruby, and do you know why??? The same reason MS needs, Mac & Linux. So they do not fall asleep at the wheel! This keeps MS on there toes(although still no explanation for their piss- poor product). Python needs Ruby so we don't fall asleep. Ruby may be the best thing that happened to Python. Wake Up people! The writing is on the Wall! From wblusk1 at verizon.net Mon Dec 22 13:31:57 2008 From: wblusk1 at verizon.net (wblusk1 at verizon.net) Date: Mon, 22 Dec 2008 18:31:57 +0000 Subject: Python-list Digest, Vol 63, Issue 420 In-Reply-To: References: Message-ID: <1679064795-1229970717-cardhu_decombobulator_blackberry.rim.net-395278973-@bxe345.bisx.prod.on.blackberry> Sent from my Verizon Wireless BlackBerry -----Original Message----- From: python-list-request at python.org Date: Mon, 22 Dec 2008 19:01:06 To: Subject: Python-list Digest, Vol 63, Issue 420 Send Python-list mailing list submissions to python-list at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/python-list or, via email, send a message with subject or body 'help' to python-list-request at python.org You can reach the person managing the list at python-list-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Python-list digest..." From tino at wildenhain.de Mon Dec 29 14:45:31 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 29 Dec 2008 20:45:31 +0100 Subject: math module for Decimals In-Reply-To: References: <251111d8-a48a-45e3-a744-16fdb729fa33@i20g2000prf.googlegroups.com> <016729e4$0$6988$c3e8da3@news.astraweb.com> Message-ID: <495928DB.7040209@wildenhain.de> jerry.carl.mi at gmail.com wrote: ... > It's really just the goniometric functions that I am missing most at > the moment, so maybe I can figure it out with help of what you said > plus the already existing imperfect modules. Meantime maybe this > discussion will caught Guido's eye... ;-) And btw I do expect that > Python becomes better than Mathematica one day because it's free and > open :-) Maybe when Wolfram retires ;-) Thanks again! I agree having full support for all math.* functions for all builtin types would be nice. However if you are more looking for replacement of mathematica and friends with python you might check scipy/numpy. Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From rt8396 at gmail.com Fri Dec 26 14:07:55 2008 From: rt8396 at gmail.com (r) Date: Fri, 26 Dec 2008 11:07:55 -0800 (PST) Subject: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> <90f06b27-39da-4f1a-a878-f3972e942d57@s24g2000vbp.googlegroups.com> <62caf93b-0455-4450-9895-8a9d9554f75e@r32g2000vba.googlegroups.com> <1isezkk.51e05y1457jqrN%pdorange@pas-de-pub-merci.mac.com> <3cb2a746-1a43-44a1-9825-7667af9fe2fa@s1g2000prg.googlegroups.com> <1isi4sn.11mpft612g7udcN%pdorange@pas-de-pub-merci.mac.com> <1isk1kn.1s8efppxapfeaN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <301a2968-21d6-475d-958c-890e0fc27249@m15g2000vbl.googlegroups.com> On Dec 26, 5:06?am, pdora... at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) wrote: > r wrote: > > > Go to Google groups... it looks perfect :) > > It's a usenet group here, nothing to do with google groups. > To get back to the group subject, what is your actual python projects ? I am crusading to bring python scripting to Google SketchUp, do want to get on board? From clp at rebertia.com Mon Dec 1 13:37:57 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 1 Dec 2008 10:37:57 -0800 Subject: Python introspection and namespace weird question In-Reply-To: References: Message-ID: <47c890dc0812011037u64076950o186af7477269cc0a@mail.gmail.com> On Mon, Dec 1, 2008 at 6:04 AM, Rayene Ben Rayana wrote: > Hello everybody, > > Is there an easy way to do something like this in python ? > >>>> red_car = MyVehicleClass() >>>> car = red_car >>>> car.labels() > ['red_car' , 'car' ] > > In other words, does an instance has access to its name pointers ? In short, No. (Cue another debate over whether Python uses call-by-X semantics...) Typically people who want to do such things actually want/should use a dictionary mapping string keys to instance values instead. Note that in certain limited cases, voodoo involving the locals() or globals() built-in functions or the `inspect` module can work, but not in the common general case. But generally these techniques are considered bad style and kludgey unless you're writing a debugger or something equally meta, with using a dictionary as explained previously being much preferred. For example, for your particular code above, the following happens to work: [name for name, obj in locals().iteritems() if obj is car] #==> ['red_car' , 'car' ] But this will only give the names in the current function of the particular car object. Likewise, globals() works only for module-level names, and the `inspect` module's magic only works for names in calling functions (i.e. those below the current one in the callstack). Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Thanks in advance, > > Rayene > > > -- > http://mail.python.org/mailman/listinfo/python-list > > From prologic at shortcircuit.net.au Tue Dec 30 19:54:45 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 10:54:45 +1000 Subject: get method In-Reply-To: <016ab880$0$6988$c3e8da3@news.astraweb.com> References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> <495AAB97.5010707@mrabarnett.plus.com> <71508d7a-f678-40ba-801c-0bbfbbab961e@r15g2000prh.googlegroups.com> <016ab880$0$6988$c3e8da3@news.astraweb.com> Message-ID: On Wed, Dec 31, 2008 at 10:49 AM, Steven D'Aprano wrote: > What set module? Sorry I must have meant the collections module :) > Adding a multi-set or bag class to the collections module would be a good > idea though. Perhaps you should put in a feature request? :) Perhaps I will. cheers James From stdazi at gmail.com Sat Dec 13 07:00:26 2008 From: stdazi at gmail.com (stdazi) Date: Sat, 13 Dec 2008 04:00:26 -0800 (PST) Subject: Parallelizing python code - design/implementation questions Message-ID: Hello! I'm about to parallelize some algorithm that turned out to be too slow. Before I start doing it, I'd like to hear some suggestions/hints from you. The algorithm essentially works like this: There is a iterator function "foo" yielding a special kind permutation of [1,....n]. The main program then iterates through this permutations calculating some proprieties. Each time a calculation ends, a counter is incremented and each time the counter is divisible by 100, the current progress is printed. The classical idea is to spawn m threads and use some global lock when calling the instance of the iterator + one global lock for incrementing the progress counter. Is there any better way? I'm especially concerned with performance degradation due to locking - is there any way to somehow avoid it? I've also read about the `multiprocessing' module and as far as I've understood : ==== permutation = foo() threadlst = [] for i in xrange(m) : p = Process(target=permutation.next) threadlst.append(p) p.start() for p in threadlst: p.join() ==== should do the trick. Am I right? Is there any better way other than this? From martin at v.loewis.de Tue Dec 2 02:05:06 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Tue, 02 Dec 2008 08:05:06 +0100 Subject: Multiple Versions of Python on Windows XP In-Reply-To: References: Message-ID: <4934de22$0$27863$9b622d9e@news.freenet.de> > Could anyone please point me to documentation on the way the msi > installer handles multiple versions eg. Python 2.5, 2.6 and 3.0? I don't think that is documented anywhere. > What changes are made to the registry? For a complete list, see Tools/msi/msi.py in the source tree. > Is there some way to specify a default version in such a way that it can > be changed as necessary? What do you mean by "default version"? There is the version that is associated with the .py/.pyc extensions at any point in time; you can change these by re-running the respective installers from add-and-remove-programs. In a well-managed installation, only one Python installation would have the "Register Extensions" feature selected; to then change the default, one would unselect the feature in one version, and reselect it in a different. If only the default installation procedure was ever used, re-running the installer in "Repair" mode (from ARP) will also restore the extension associations. > PyScripter uses an option to select a version eg. > > C:\Program Files\PyScripter\PyScripter.exe --python26 > > but I'm having some trouble with it when I attempt edit a python file > from the Windows Explorer. It would be good to be more specific with such statements: what troubles specifically? If I play dumb, I'd say "of course - windows explorer doesn't support editing Python files; you need a text editor". Regards, Martin From castironpi at gmail.com Sun Dec 21 05:35:59 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 21 Dec 2008 02:35:59 -0800 (PST) Subject: trapping all method calls in a class... References: <19ac19520812202312q71409182kb58a0f7aaf3b0e74@mail.gmail.com> Message-ID: <9ae69de7-a56f-44fc-8916-97ae6de32155@u18g2000pro.googlegroups.com> On Dec 21, 1:32?am, "Chris Rebert" wrote: > On Sat, Dec 20, 2008 at 11:12 PM, Piyush Anonymous > > wrote: > > hi, > > i need to trap all method calls in a class in order to update a counter > > which is increased whenever a method is called and decreased whenever method > > returns. in order to that i am trying to write a decorator for all the > > methods. > > > see the code here with error. > > ------- > >http://codepad.org/2w7JVvDB > > ---- > > any suggestions? any other better way of doing it? > > I call unnecessary use of metaclasses! Here's my (untested) attempt at > a simpler class decorator approach: > > def decorate_meths(klass): > ? ? attrs = klass.__dict__.items() > ? ? ? ? for name, val in attrs: > ? ? ? ? ? ? ? ? if callable(val): > ? ? ? ? ? ? ? ? ? ? ? ? klass.__dict__[name] = decorate(val) > > def decorate(method): > ? ? #should be called for every method call in the class > ? ? def decorated(self, *args, **kwds): > ? ? ? ? print "2 Inside __call__()" > ? ? ? ? returnval = method(self, *args,**kwds) > ? ? ? ? print "3 After self.f(*args)" > ? ? ? ? return returnval > ? ? return decorated > > #@decorate_meths <-- this syntax requires a later Python version > class Person(object): > ? ? ? ? def testprint(self,val): > ? ? ? ? ? ? ? ? print "blah blah" > Person = decorate_meths(Person) > > #rest of code after the class definition would be the same > > Sidenotes about your code: > - `args` and `kwds` are the conventional names for the * and ** > special arguments > - the `methodname` variable was actually getting method objects, not > strings, as its values; this was probably part of the bug in your > program > > Cheers, > Chris > > -- > Follow the path of the Iguana...http://rebertia.com Two more possibilities. 1. Use sys.settrace, and a dictionary mapping functions to integers. The functions are given in the frame object, which is a parameter to the settrace function. 2. __getattribute__, which either maps a function to an integer, and returns the function; or returns a function that increments an integer, then calls the requested function. P.S. I did not see the original post in Google Groups. From theller at python.net Thu Dec 4 15:33:43 2008 From: theller at python.net (Thomas Heller) Date: Thu, 04 Dec 2008 21:33:43 +0100 Subject: Checking if an int fits in 32 bits? In-Reply-To: References: Message-ID: <6pqt56F9bvoiU1@mid.individual.net> Roy Smith schrieb: > I'm working with marshaling data over a binary wire protocol. I'm > using struct.pack() to handle the low-level encoding of ints. One of > the things I need to do is make sure an int can be represented in 4 > bytes. Is there a portable way to do that? For now, I'm doing signed > ints, but I'll certainly have to do unsigned 32-bit ints (and 64-bit > ints) at some point. Not to mention shorts and chars. > > At first I thought pack() might raise an exception on a value > overflow, that but doesn't seem to be the case: > >>>> [hex(ord(c)) for c in struct.pack('!i', 999999999999999999999L)] > ['0xde', '0x9f', '0xff', '0xff'] > > Should I be thinking more along the lines of bit masking (and worrying > about all the niggling 2-complement issues) in the Python code? Or is > there some cleaner way to do this? > You could try something like this: import ctypes def int_fits_in_32bit(value): return ctypes.c_int32(value) == value and similar for signed/unsigned short/int/long. Packing and unpacking with the struct module, however, does basically the same. Thomas From jeremiah.dodds at gmail.com Thu Dec 25 04:42:31 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Thu, 25 Dec 2008 04:42:31 -0500 Subject: =?ISO-8859-1?Q?Re:_object_ori=EBnted?= In-Reply-To: References: Message-ID: <12cbbbfc0812250142k801b445v55628e935d932e5e@mail.gmail.com> On Wed, Dec 24, 2008 at 10:54 AM, Dennis van Oosterhout < de.slotenzwemmer at gmail.com> wrote: > I know that python is an Object Ori?nted language but I was wondering if it > gets used as a non-OOP also (by a good amount of people). > > -- > http://mail.python.org/mailman/listinfo/python-list > > I, for one, use the different "paradigms" (OO, procedural, functional, etc) where they feel appropriate for solving different problems. I have quite a few strictly procedural scripts, mainly for sysadmin stuff and generating project skeletons. Most of the "complete" programs that I write use a mix of OO and functional paradigms. -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Sun Dec 21 18:37:04 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 21 Dec 2008 15:37:04 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: On Dec 21, 10:58?am, MRAB wrote: > Aaron Brady wrote: > > On Dec 21, 10:31 am, MRAB wrote: snip > >> The original format is a string. The result of '%' is a string if > >> there's only 1 placeholder to fill, or a (partial) format object (class > >> "Format"?) if there's more than one. Similarly, the format object > >> supports '%'. The result of '%' is a string if there's only 1 > >> placeholder to fill, or a new (partial) format object if there's more > >> than one. > > >> ?>>> f = "%r %i" > >> ?>>> type(f) > >> > >> ?>>> f = f % (2, 3, 4) > >> ?>>> type(f) > >> > >> ?>>> f = f % 1 > >> ?>>> type(f) > >> > > > Alright, so how are you handling: > > >>>> f= "%s %i" > >>>> type( f ) > > > >>>> f= f% '%i' ?#now '%i %i' > >>>> type( f ) > > > >>>> f= f% 1 > >>>> type( f ) > > ? > > > In other words, are you slipping '1' in to the very first available > > slot, or the next, after the location of the prior? > > Let's assume that Format objects display their value like the equivalent > string format: > > ?>>> f = "%r %i" > ?>>> f > '%r %i' > ?>>> f = f % (2, 3, 4) > ?>>> f > > ?>>> f = f % 1 > ?>>> f > '(2, 3, 4) 1' > ?>>> > ?>>> f = "%s %i" > ?>>> f > '%s %i' > ?>>> f = f % '%i' > ?>>> f > > ?>>> f = f % 1 > ?>>> f > '%%i 1' I assume you meant '%i 1' since there are no more flags in f, and it's returned to a regular string. 'f %= 1' doesn't work any more as in-place modulo, since one time, 'f' is a Format object, the other, 'f' is a string. Just raise an exception for that (or assign to __class__ IINM if I'm not mistaken). Actually, the class you showed is kind of nifty. Tuples are correctly interpolated. I think on the whole you'll use more parenthesis, since each term in the tuple appears separately, and might be an expression (have a lower-precedence op.), as well as more modulo signs. You can currently do-it-yourself, you just need a constructor in the format string. >>> f = Format("%r %i") >>> type(f) >>> f = f % (2, 3, 4) >>> type(f) Or, as someone suggested earlier, a new literal marking: >>> f = f"%r %i" >>> type(f) From gagsl-py2 at yahoo.com.ar Mon Dec 8 02:49:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Dec 2008 05:49:07 -0200 Subject: i use the urllib question In-Reply-To: References: Message-ID: En Fri, 05 Dec 2008 10:23:44 -0200, Huytason escribi?: > i use pthon 3.0 today > > python code: > import urllib.request > > then use PyRun_StringFlag to run it. > > get this > > it's a bug? You should tell us more details. You are embedding Python, I presume? The default search path (sys.path) is initialized based on the executable location; very probably you don't have a 'lib' directory. Either set the PYTHONPATH environment var, or copy the required libraries, or call Py_SetProgramName. -- Gabriel Genellina From cadmuxe at gmail.com Mon Dec 8 09:59:53 2008 From: cadmuxe at gmail.com (cadmuxe) Date: Mon, 8 Dec 2008 06:59:53 -0800 (PST) Subject: Beginner trying to understand functions. References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> Message-ID: <9df7549a-f28b-4d39-b105-90c099f472f2@z28g2000prd.googlegroups.com> On 12?8?, ??10?53?, "James Mills" wrote: > On Tue, Dec 9, 2008 at 12:46 AM, Peter Otten <__pete... at web.de> wrote: > > I think the OP is using Python 3.0. What used to cause trouble > > Well of course he/she/it is! > I'm too blind to have noticed that! :) > > --JamesMills > > -- > -- > -- "Problems are solved by method" oh,i think i should go to read the new document of py3k thanks for all From metolone+gmane at gmail.com Fri Dec 5 09:44:35 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Fri, 5 Dec 2008 06:44:35 -0800 Subject: A more pythonic way of writting References: <35d176ed-df5f-46b4-8321-4814fcc4398c@f3g2000yqf.googlegroups.com> Message-ID: "eric" wrote in message news:35d176ed-df5f-46b4-8321-4814fcc4398c at f3g2000yqf.googlegroups.com... > def flag(IGNORECASE=False, LOCALE=False, MULTILINE=False, > DOTALL=False, UNICODE=False, VERBOSE=False): > vals = [IGNORECASE, LOCALE, MULTILINE, DOTALL, UNICODE, VERBOSE] > filtered = map( lambda m:m[1],filter( lambda m: m[0], > zip(vals,'iLmsux'))) > return '?'+''.join( filtered ) filtered = [c for c,v in zip('iLmsux',vals) if v] -Mark From rocky at panix.com Tue Dec 30 05:09:35 2008 From: rocky at panix.com (R. Bernstein) Date: Tue, 30 Dec 2008 05:09:35 -0500 Subject: How do I DRY the following code? References: Message-ID: "Patrick Mullen" writes: >> f1(...): >> "Docstring f1" >> c = C() >> return c.f1(...) >> >> f2(...): >> "Docstring f2" >> c = C() >> return c.f2(...) > > Why not just do either this: > C().f2(..) where you need f2 Yes, this is a little better. Thanks! From python.list at tim.thechases.com Mon Dec 8 06:12:02 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 08 Dec 2008 05:12:02 -0600 Subject: Determining whether a variable is less/greater than a range. In-Reply-To: <362ab93b-b804-4ebe-a22f-e422feb301c8@c1g2000yqg.googlegroups.com> References: <362ab93b-b804-4ebe-a22f-e422feb301c8@c1g2000yqg.googlegroups.com> Message-ID: <493D0102.6030808@tim.thechases.com> > a = list(range(10, 21)) > > b = 9 > > c = 21 > > How can I find out if b and c have values less or more than the values > in list a? Sounds like a good use for 2.5's addition of the any() and all() functions -- you don't mention whether you want your variable compared against *any* of the list items or *all* of the list items. You also don't mention whether you want the comparison results, or just a single scalar. Lastly, you omit the details of what happens if your target value ("d" below) falls within the range. One of the following should do it for you: >>> a = range(10,21) >>> b = 9 >>> c = 21 >>> d = 15 >>> any(b < x for x in a) True >>> all(b < x for x in a) True >>> any(c < x for x in a) False >>> any(d < x for x in a) True >>> all(d < x for x in a) False >>> any(c > x for x in a) True >>> all(c > x for x in a) True >>> any(d > x for x in a) True >>> all(d > x for x in a) False If you just want the comparisons: y1 = [bx) for x in a] z2 = [(cx) for x in a] z3 = [(dx) for x in a] -tkc From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 2 08:08:05 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 02 Dec 2008 14:08:05 +0100 Subject: Do more imported objects affect performance In-Reply-To: References: <1be78d220812010621u51dead9dnbaa0b4c8c9414362@mail.gmail.com> <79153a2e0812012124o7401df57m4ac21dfe37c2ec5@mail.gmail.com> Message-ID: <4935332e$0$1138$426a74cc@news.free.fr> Nick Craig-Wood a ?crit : > On Tue, Dec 02, 2008 at 11:24:29AM +0600, Taskinoor Hasan wrote: >> On Mon, Dec 1, 2008 at 8:21 PM, Filip Gruszczy?ski wrote: >> >>> I see. Thanks for a really good explanation, I like to know, how to do >>> things in the proper way :) >> I always prefer to use import module and then use module.function. The >> reason is simple. It makes the code more readable and maintainable. > > I prefer the "from module import function". That means that if > "module" doesn't supply "function" it raises an exception at compile > time, not run time when you try to run "module.function". Nope. import is an executable statement, and ImportError happens at runtime too. From martin.hellwig at dcuktec.org Sat Dec 6 07:53:35 2008 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Sat, 06 Dec 2008 12:53:35 +0000 Subject: Can't get exclusive file lock when safely renaming a file In-Reply-To: <014a049b$0$20670$c3e8da3@news.astraweb.com> References: <014a049b$0$20670$c3e8da3@news.astraweb.com> Message-ID: <493a75cf$0$185$e4fe514c@news.xs4all.nl> Steven D'Aprano wrote: > import os, fcntl > oldname = "ham.txt" > newname = "spam.txt" > > def lock_destination(name): > fileno = os.open(name, os.O_CREAT | os.O_EXCL) > fcntl.flock(fileno, fcntl.LOCK_EX) # POSIX systems only > return fileno > > # Create a test file to be renamed. > f = open(oldname, 'w') > f.write('this is my file\n') > f.close() > fileno = lock_destination(newname) > > # At this point, I can see "ham.txt" plus an empty file > # "spam.txt" in my file browser > > os.rename(oldname, newname) > > The rename works, but here is my problem: after getting what I thought > was an exclusive lock on the new file, but before calling os.rename(), I > can still over-write it from another process: > > $ echo "this comes from another process" > spam.txt > $ cat spam.txt > this comes from another process > This is weird, you would indeed expect it to be locked, I tried it on FreeBSD and it behaves the same. I guess the behavior of os.rename should be changed so it raises an exception when the source destination exists independent on the below platform. I tried searching for another way to do it but the closest I came was to popen mv and raise an exception if it asks to overwrite the existing file. Sorry I can't be of more help. -- mph From manatlan at gmail.com Mon Dec 8 08:15:55 2008 From: manatlan at gmail.com (manatlan) Date: Mon, 8 Dec 2008 05:15:55 -0800 (PST) Subject: pytz and timezone specialists References: <1f6172c1-4f70-42ea-8010-b72beb0af487@w24g2000prd.googlegroups.com> Message-ID: On 5 d?c, 20:46, Ned Deily wrote: > In article > <1f6172c1-4f70-42ea-8010-b72beb0af... at w24g2000prd.googlegroups.com>, > > > > ?manatlan wrote: > > Here is a really simple code : > > ------------------------------------------------------- > > from datetime import datetime > > frompytzimport timezone > > > tz=timezone("Europe/Paris") > > > d=datetime(2008,12,12,19,00,00,tzinfo=tz) > > print d.isoformat() > > > d=datetime.now(tz) > > print d.isoformat() > > ------------------------------------------------------- > > when I run it, it displays (according current time ;-): > > > 2008-12-12T19:00:00+00:09 > > 2008-12-05T19:15:38.135467+01:00 > > > The Europe/Paris timezone is GMT+1 ... the second date seems to be > > right (+01:00 at the end) > > > But why the first date ends with "+00:09" ?!? it should be +01:00 ... > > no ?! > > Where's the bug ?!? (sure : it's me ;-) ... but i don't understand > > this simple thing) > >>> tz = timezone("Europe/Paris") > >>> d = tz.localize(datetime(2008,12,12,19,00,00)) > >>> print d.isoformat() > > 2008-12-12T19:00:00+01:00 > > > > "This library only supports two ways of building a localized time. The > first is to use the .localize() method provided by thepytzlibrary. > This is used to localize a naive datetime (datetime with no timezone > information). ?... Unfortunately using the tzinfo argument of the > standard datetime constructors ''does not work'' withpytzfor many > timezones." > > -- > ?Ned Deily, > ?n... at acm.org now, I use : d=datetime.now(tz).replace(2008,12,12,19,00,00) and it works like expected ... btw, thanks for your answer From greg at cosc.canterbury.ac.nz Sun Dec 14 03:03:26 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Sun, 14 Dec 2008 21:03:26 +1300 Subject: Bidrectional Subprocess Communication In-Reply-To: References: Message-ID: <6qjspkFcv81kU1@mid.individual.net> Gabriel Genellina wrote: > (Pipes don't work the same as sockets, although unix-like systems try > hard to hide the differences...) BSD-based unixes implement pipes using socketpair(), so pipes actually *are* sockets (or at least they used to be, not sure whether it's still true). -- Greg From iofferkicks24 at gmail.com Wed Dec 24 21:25:03 2008 From: iofferkicks24 at gmail.com (www.iofferkicks.com) Date: Wed, 24 Dec 2008 18:25:03 -0800 (PST) Subject: www.iofferkicks.com china cheap wholesale nike shoes,air jordan shoes,air force one shoes. Message-ID: <33a3a127-a22b-41a7-8193-a23698d34c7f@w1g2000prk.googlegroups.com> Get Nike Shoes at Super Cheap Prices Discount Nike air jordans (www.iofferkicks.com) Discount Nike Air Max 90 Sneakers (www.iofferkicks.com) Discount Nike Air Max 91 Supplier (www.iofferkicks.com) Discount Nike Air Max 95 Shoes Supplier (www.iofferkicks.com) Discount Nike Air Max 97 Trainers (www.iofferkicks.com) Discount Nike Air Max 2003 Wholesale (www.iofferkicks.com) Discount Nike Air Max 2004 Shoes Wholesale (www.iofferkicks.com) Discount Nike Air Max 2005 Shop (www.iofferkicks.com) Discount Nike Air Max 2006 Shoes Shop (www.iofferkicks.com) Discount Nike Air Max 360 Catalogs (www.iofferkicks.com) Discount Nike Air Max Ltd Shoes Catalogs (www.iofferkicks.com) Discount Nike Air Max Tn Men's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 2 Women's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 3 Customize (www.iofferkicks.com) Discount Nike Air Max Tn 4 Shoes Customize ( www.iofferkicks.com) Discount Nike Air Max Tn 6 Supply (www.iofferkicks.com) Discount Nike Shox NZ Shoes Supply (www.iofferkicks.com) Discount Nike Shox OZ Sale (www.iofferkicks.com) Discount Nike Shox TL Store (www.iofferkicks.com) Discount Nike Shox TL 2 Shoes Store (www.iofferkicks.com) Discount Nike Shox TL 3 Distributor (www.iofferkicks.com) Discount Nike Shox Bmw Shoes Distributor (www.iofferkicks.com) Discount Nike Shox Elite Shoes Manufacturer (www.iofferkicks.com) Discount Nike Shox Monster Manufacturer (www.iofferkicks.com) Discount Nike Shox R4 Running Shoes (www.iofferkicks.com) Discount Nike Shox R5 Mens Shoes (www.iofferkicks.com) Discount Nike Shox Ride Womens Shoes (www.iofferkicks.com) Discount Nike Shox Rival Shoes Wholesaler (www.iofferkicks.com) Discount Nike Shox Energia Wholesaler (www.iofferkicks.com) Discount Nike Shox LV Sneaker (www.iofferkicks.com) Discount Nike Shox Turbo Suppliers (www.iofferkicks.com) Discount Nike Shox Classic Shoes Suppliers (www.iofferkicks.com) Discount Nike Shox Dendara Trainer (www.iofferkicks.com) Discount Nike Air Jordan 1 Seller (www.iofferkicks.com) Discount Nike Air Jordan 2 Shoes Seller (www.iofferkicks.com) Discount Nike Air Jordan 3 Collection (www.iofferkicks.com) Discount Nike Air Jordan 4 Shoes Collection (www.iofferkicks.com) Discount Nike Air Jordan 5 Chaussure Shoes (www.iofferkicks.com) Discount Nike Air Jordan 6 Catalog (www.iofferkicks.com) Discount Nike Air Jordan 7 Shoes Catalog (www.iofferkicks.com) Discount Nike Air Jordan 8 Customized (www.iofferkicks.com) Discount Nike Air Jordan 9 Shoes Customized (www.iofferkicks.com) Discount Nike Air Jordan 10 Wholesalers (www.iofferkicks.com) Discount Nike Jordan 11 Shoes Wholesalers (www.iofferkicks.com) Discount Nike Air Jordan 12 Factory (www.iofferkicks.com) Discount Nike Air Jordan 13 Shoes Factory (www.iofferkicks.com) Discount Nike Air Jordan 14 Shoes Sell (www.iofferkicks.com) Discount Nike Air Jordan 16 Exporter (www.iofferkicks.com) Discount Nike Air Jordan 17 Shoes Exporter (www.iofferkicks.com) Discount Nike Air Jordan 18 Offer (www.iofferkicks.com) Discount Nike Air Jordan 19 Shoes Offer (www.iofferkicks.com) Discount Nike Air Jordan 20 Manufacture (www.iofferkicks.com) Discount Nike Jordan 21 Shoes Manufacture (www.iofferkicks.com) EMAIL:IOFFERKICKS at GMAIL.COM MSN :IOFFERKICKS at MSN.COM From rt8396 at gmail.com Mon Dec 22 12:40:29 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 09:40:29 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> Message-ID: On Dec 22, 8:58?am, walterbyrd wrote: > On Dec 21, 12:28?pm, Bruno Desthuilliers > > wrote: > > Strange enough, > > no one seems to complain about PHP or Ruby's performances... > > A few years back, there was a certain amount of chest thumping, when > python/django easily beat ror in a benchmark test. Now that ruby is > faster, I guess speed is no big issue. > > By the same reasoning, python advocates used to sneer at php because > php constantly broke backward compatibility. Now that python does it, > breaking backward compatibility is no big deal. I guess unicode > support was not that important, until python caught up to perl. > > I guess, the way it works is: you first assume that python is > superior, then you figure out why. I think what walter is saying is the loyalty is gone. community: """If python makes great, if it doesn't, why should "i" care if it goes down the toilet? i just move to ruby""" Were is your loyalty pyfans?, Has the fight left you??? From torriem at gmail.com Thu Dec 11 14:19:19 2008 From: torriem at gmail.com (Michael Torrie) Date: Thu, 11 Dec 2008 12:19:19 -0700 Subject: just got the g1 In-Reply-To: References: Message-ID: <494167B7.9090304@gmail.com> garywood wrote: > Hi > > Just got the G1, is their any way to get python running on the andriod platform ? Nope. But some day when other languages are supported, Python will be high on the list. In the meantime, Android is java only. And no you can't use Jython because Android statically compiles normal java byte code to the special bytecode their own VM uses. Jython being a dynamic language does not emit static java classes. From what I understand, porting Jython to work on this special VM is not trivial. From wojciech_mula at poczta.null.onet.pl.invalid Sat Dec 13 21:14:37 2008 From: wojciech_mula at poczta.null.onet.pl.invalid (Wojciech =?ISO-8859-2?Q?Mu=B3a?=) Date: Sun, 14 Dec 2008 03:14:37 +0100 Subject: 1 or 1/0 doesn't raise an exception References: Message-ID: <20081214031437.48078f5d.wojciech_mula@poczta.null.onet.pl.invalid> "Daniel Fetchinson" wrote: > Is it a feature that > > 1 or 1/0 > > returns 1 and doesn't raise a ZeroDivisionError? If so, what's the rationale? See: http://en.wikipedia.org/wiki/Short-circuit_evaluation From bj_666 at gmx.net Sat Dec 20 07:07:07 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 20 Dec 2008 12:07:07 GMT Subject: encoding problem References: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> <6r1m72Ffb5kpU3@mid.uni-berlin.de> <6r2hvjFfb5kpU6@mid.uni-berlin.de> <6r2nfgFfb5kpU7@mid.uni-berlin.de> Message-ID: <6r45fbFfc57aU2@mid.uni-berlin.de> On Fri, 19 Dec 2008 16:50:39 -0700, Joe Strout wrote: > Marc 'BlackJack' Rintsch wrote: > >>>> And does REALbasic really use byte strings plus an encoding!? >>> You betcha! Works like a dream. >> >> IMHO a strange design decision. > > I get that you don't grok it, but I think that's because you haven't > worked with it. RB added encoding data to its strings years ago, and > changed the default string encoding to UTF-8 at about the same time, and > life has been delightful since then. The only time you ever have to > think about it is when you're importing a string from some unknown > source (e.g. a socket), at which point you need to tell RB what encoding > it is. From that point on, you can pass that string around, extract > substrings, split it into words, concatenate it with other strings, > etc., and it all Just Works (tm). Except that you don't know for sure what the output encoding will be, as it depends on the operations on the strings in the program flow. So to be sure you have to en- or recode at output too. And then it is the same as in Python -- decode when bytes enter the program and encode when (unicode) strings leave the program. > In comparison, Python requires a lot more thought on the part of the > programmer to keep track of what's what (unless, as you point out, you > convert everything into unicode strings as soon as you get them, but > that can be a very expensive operation to do on, say, a 500MB UTF-8 text > file). So it doesn't require more thought. Unless you complicate it yourself, but that is language independent. I would not do operations on 500?MiB text in any language if there is any way to break that down into smaller chunks. Slurping in large files doesn't scale very well. On my Eee-PC even a 500?MiB byte `str` is (too) expensive. > But saying that having only one string type that knows it's Unicode, and > another string type that hasn't the foggiest clue how to interpret its > data as text, is somehow easier than every string knowing what it is and > doing the right thing -- well, that's just silly. Sorry, I meant the implementation not the POV of the programmer, which seems to be quite the same. Ciao, Marc 'BlackJack' Rintsch From bdesth.quelquechose at free.quelquepart.fr Thu Dec 4 13:44:07 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 Dec 2008 19:44:07 +0100 Subject: Python Runtime Method Call Binding In-Reply-To: <9f2308eb-9eb9-4431-8af7-975c3e054849@e18g2000yqo.googlegroups.com> References: <0147f396$0$20670$c3e8da3@news.astraweb.com> <9f2308eb-9eb9-4431-8af7-975c3e054849@e18g2000yqo.googlegroups.com> Message-ID: <493832b1$0$17775$426a34cc@news.free.fr> k3xji a ?crit : (snip) > My problem is that I have a very-multithreaded application that I want > to profile dynamically. And I want to see how many functions are > called/how much time spent on them.(I tried Profilers but lack of > multithreading support I cannot do what I want to do.) ??? I didn't found any mention of such a limitation on the profile / cProfile doc: http://www.python.org/doc/2.6/library/profile.html#module-cProfile > So, from your answers above, if I use a decorator I will not be able > to understand that the function has finished processing. Yes you will: def log(func): def _logged(*args, **kw): print "func", func.__name__, " called with ", args, kw result = func(*args, **kw) print "func", func.__name__, " returned ", result return result _logged.__name__ = "logged_%s" % func.__name__ _logged.__doc__ = func.__doc__ return _logged > I think problem is clarified now. Maybe you have other suggestions? Yes. 1/ the @decorator def func(): pass syntax is really syntactic sugar for def func(): pass func = decorator(func) 2/ nothing prevents you from dynamically rebinding methods at runtime: def log(func): # cf below if getattr(func, "_decorated", False): # already decorated, just return the func or method as is return func def _logged(*args, **kw): print "func", func.__name__, " called with ", args, kw result = func(*args, **kw) print "func", func.__name__, " returned ", result return result _logged.__name__ = "logged_%s" % func.__name__ _logged.__doc__ = func.__doc__ # IMPORTANT : mark the function / method as already decorated _logged._decorated = True return _logged class Foo(object): def bar(self): pass Foo.bar = log(Foo.bar) 3/ Now fact is that even all this won't probably be enough to implement a robust generic profiler - something which obviously requires a deep understanding of the language *and* it's implementation. From bkamrani at gmail.com Thu Dec 4 07:48:10 2008 From: bkamrani at gmail.com (bkamrani at gmail.com) Date: Thu, 4 Dec 2008 04:48:10 -0800 (PST) Subject: performance question: dictionary or list, float or string? References: <434bf4e3-54f4-4e15-b8b0-510a988f25b8@z1g2000yqn.googlegroups.com> <904a19e9-3800-4d61-aea0-4bdabc0674fa@j32g2000yqn.googlegroups.com> <842b13b2-1df5-4b34-af14-7b082970682b@41g2000yqf.googlegroups.com> <796f927e-5def-4637-bb31-88965b9bcb44@z28g2000prd.googlegroups.com> Message-ID: On Dec 4, 1:28?pm, alex23 wrote: > On Dec 4, 8:12?pm, bkamr... at gmail.com wrote: > > > About the piece of code you posted, there is something I don't > > understand. > > > ? ? ? ? for i, line in data: > > > where data is a file object. Is it legal to write that? > > I believe it results in "too many values to unpack" or do I miss > > something? > > From the context, my guess is Matimus intended to write: > > ? ? ? ? ?for i, line in enumerate(data): You're right! That was interesting! From zxo102 at gmail.com Thu Dec 25 18:32:22 2008 From: zxo102 at gmail.com (zxo102) Date: Thu, 25 Dec 2008 15:32:22 -0800 (PST) Subject: How to display Chinese in a list retrieved from database via python References: <22be506d-91c2-4727-ace7-2e3382b6d214@g3g2000pre.googlegroups.com> Message-ID: <979fdf6d-0500-47ba-87fd-0f0361ca3059@p2g2000prf.googlegroups.com> On 12?26?, ??4?58?, "Gabriel Genellina" wrote: > En Thu, 25 Dec 2008 07:27:03 -0200, zxo102 escribi?: > > > > > On 12?25?, ??3?35?, "Chris Rebert" wrote: > >> On Wed, Dec 24, 2008 at 11:29 PM, zxo102 wrote: > >> > Hi, > >> > I retrieve some info in Chinese from postgresql and assign it to a > >> > variable 'info' defined in javascript of a html page: > >> > var info = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce > >> > \xc4'] > >> > But I want it to be > >> > var info = ['??','??','??'] > >> > since in html pages (via javascript), the items in chinese out of the > >> > former :['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4'] can > >> > not be displayed correctly when it is inserted into a html page. If > >> > the list is var info = ['??','??','??'] , then everything works > >> > fine. > > > The html code is as follows > > > test > > > > > > > But the '??' is '\xd6\xd0\xce\xc4'. When row01 and row02 is called > > from somewhere, > > '\xd6\xd0\xce\xc4' can not be displayed correctly as '??' in html > > environment. > > You forgot to specify the page encoding, gb2312 presumably. If adding the > encoding does not help, I'd say the problem must reside on how you later > use row01 and row02 (your html page does not those variables for > anything). '??' is the same as '\xd6\xd0\xce\xc4', and both javascript > and Python share the same representation for strings (mostly) so this > should not be an issue. > > My PC is unable to display those characters, but I get "true" from this: > > test > > > -- > Gabriel Genellina I did that: , but it does not work. Alert('\xd6\xd0\xce\xc4') displays some "junks". I am thinking there may be some way to convert '\xd6\xd0\xce\xc4' to '??' in the list with python before I generate the html page. As a result, when I open the html file with Vi, I can see '??' directly instead of '\xd6\xd0\xce\xc4'. That will solve my problem. Any ideas? Ouyang From af300wsm at gmail.com Mon Dec 8 11:53:55 2008 From: af300wsm at gmail.com (Andrew Falanga) Date: Mon, 8 Dec 2008 08:53:55 -0800 (PST) Subject: Calling C# COM (.NET) from python Message-ID: Hi, I've never programmed in python and only have a small understanding of what is wrapped up in the terms COM and .NET. Is there a way of using python to get a hold of objects written in C# as COM objects using python? I'm looking for ways to avoid VBScript (which, after a couple of weeks, I've determined to be horrid). That is, is there a way of getting at COM objects in python that's similar to doing a CreateObject call in VBScript (http://msdn.microsoft.com/en-us/library/ dcw63t7z.aspx)? Thanks, Andy From steve at holdenweb.com Fri Dec 26 16:13:11 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 26 Dec 2008 16:13:11 -0500 Subject: [SQL] Right way to set a variable to NULL? In-Reply-To: <5nfal41gom0iqi2nh5h0m5847ev9brtvpf@4ax.com> References: <5nfal41gom0iqi2nh5h0m5847ev9brtvpf@4ax.com> Message-ID: Gilles Ganault wrote: > Hello > > I use regexes to extract information from a text file. Some of the > records don't have e-mails or www addresses, so those must match Null > in SQL, but None doesn't work as expected: > > ======= > if itemmatch: > web = itemmatch.group(1).strip() > else: > web = None > > sql = 'INSERT INTO mytable (name,address,web,mail) VALUES > ("%s","%s","%s","%s","%s")' % (name,address,web,mail) > ======= > I take it this code isn't pasted from an actual program, since the statement above would give a run time ValueError. > Is there a better way in Python to have a variable match NULL than > building the SQL query step by step? > You could, of course, have replaced None in your code with "NULL", and that should have removed the database errors you were observing. Retaining the None, however, you could move to using parameterized queries. Replace each '"%s"' in your sql string with the appropriate parameter mark (could be '%s', could be '?', could be three other things depending on your database platform. Then you provide a tuple of data items (using None for the NULL values) as a second argument to the cursor's .execute() method, and the database driver module inserts the data in to the SQL statement, escaping things where appropriate. So, supposing you were using MySQL or PostgreSQL you would write if itemmatch: web = itemmatch.group(1).strip() else: web = None sql = '''INSERT INTO mytable (name,address,web,mail) VALUES (%s, %s, %s, %s)''' cursor.execute(sql, (name,address,web,mail)) Don't forget to call the connection's .commit() method to ensure the database changes are made permanent. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From upton at virginia.edu Mon Dec 15 11:28:03 2008 From: upton at virginia.edu (Dan Upton) Date: Mon, 15 Dec 2008 11:28:03 -0500 Subject: stable algorithm with complexity O(n) In-Reply-To: <52cfb77e-4baf-4fba-8eac-cc6c7ddb5be5@k1g2000prb.googlegroups.com> References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> <015612ac$0$20639$c3e8da3@news.astraweb.com> <52cfb77e-4baf-4fba-8eac-cc6c7ddb5be5@k1g2000prb.googlegroups.com> Message-ID: <5504f9ac0812150828m14f6999ak6112c5975042dc88@mail.gmail.com> On Mon, Dec 15, 2008 at 11:05 AM, wrote: >> Non-comparison sorts are a useful technique, but it's changing the >> problem, and they are only useful in very limited circumstances. There's >> a good reason that most sort routines are based on O(n*log n) comparison >> sorts instead of O(n) bucket sorts or radix sorts. >> > This is an assumption that I never quite understood. What most people > want is to have sorted data, they don't care if I used a sorting or > non-sorting comparison to do it. I think it is just that in most cases > n is not very big anyway and comparison sorts make it easier on the > programmer to create arbitrary types that are sortable. And if n is small and sparse (ie, k > n) , O(k*n) for radix sort could be worse than O(n^2). You could also ask why people make such a big deal about quicksort over mergesort, since mergesort has a guaranteed O(n log n) time whereas quicksort can be O(n^2) on pathological cases. I think I remember learning in my algorithms class that for small sorts (n < ~40) , bubblesort can actually be the fastest (or close to the fastest) in terms of wall-clock time because it has a relatively small constant factor in its O(n^2) complexity. From miki.tebeka at gmail.com Tue Dec 9 11:39:38 2008 From: miki.tebeka at gmail.com (Miki) Date: Tue, 9 Dec 2008 08:39:38 -0800 (PST) Subject: pickling a circular object inherited from list References: Message-ID: <3b1bab42-657c-4b93-9236-aa5236c16826@w1g2000prk.googlegroups.com> Hello Klaus, > I have a problem with inheritance from list. I want to create a tree > like object where child nodes are kept in self[:] and every child has a > field that points to its parent. Pickling such an object, however, > throws an AssertionError. See below for source code and output of an > easy example case of my problem. > > What did I do wrong? Old Python version? :) Seems to work in 3.0 (don't have 2.6 currently to check but IMO it's fixed there as well). HTH, -- Miki http://pythonwise.blogspot.com From dfnsonfsduifb at gmx.de Tue Dec 16 23:50:50 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Wed, 17 Dec 2008 05:50:50 +0100 Subject: Does Python3 offer a FrozenDict? In-Reply-To: <01584ccb$0$20656$c3e8da3@news.astraweb.com> References: <01584ccb$0$20656$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano schrieb: > On Tue, 16 Dec 2008 17:59:30 +0100, Johannes Bauer wrote: > >> Hello group, >> >> is there anything like a frozen dict in Python3, so I could do a >> >> foo = { FrozenDict({"a" : "b"}): 3 } >> >> or something like that? > > > If *all* you want is to use it as a key, then: > > tuple(sorted(some_dict.items)) > > may do the job. Well, I'd like to access it like a dict afterwards, e.g. for (i, j) in foo.items(): print(i["a"]) Regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From ajaksu at gmail.com Mon Dec 22 17:30:56 2008 From: ajaksu at gmail.com (ajaksu) Date: Mon, 22 Dec 2008 14:30:56 -0800 (PST) Subject: I always wonder ... References: Message-ID: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> On Dec 22, 3:53?pm, s... at pobox.com wrote: > ... shouldn't people who spend all their time trolling be doing something > else: studying, working, writing patches which solve the problems they > perceive to exist in the troll subject? ? Sure. So should I. Hmm. Shutting-up-and-back-to-work-ly y'rs, Daniel From rogerpack2005 at gmail.com Sat Dec 27 00:49:38 2008 From: rogerpack2005 at gmail.com (rogerdpack) Date: Fri, 26 Dec 2008 21:49:38 -0800 (PST) Subject: ruby -> python translator exists? References: <04b51f42-e18e-4902-8a98-38f0538c1eda@s9g2000prg.googlegroups.com> <4a10794e-a3e7-4aa4-8d21-580152806277@c36g2000prc.googlegroups.com> <72c2df21-db59-4870-9388-ccaa47cf11e4@20g2000yqt.googlegroups.com> Message-ID: <9c579c5a-ac9f-4716-8300-6d41ed52fd72@a26g2000prf.googlegroups.com> > Search for the tool "Unholy". -- Al Thank you for your replies. -=r From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 21:30:26 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2008 02:30:26 GMT Subject: ANN: New Book: Programming in Python 3 References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> Message-ID: <015c5013$0$20656$c3e8da3@news.astraweb.com> On Fri, 19 Dec 2008 19:35:20 -0500, Colin J. Williams wrote: > Steve Holden wrote: >> Thomas Heller wrote: (Fixing broken unicode again) >>> "One of Python's great strengths" >>> ^ >>> "and also teaches Python's functional programming features" >>> ^ >>> "The book's approach is wholly practical" >>> ^ >> It always has been valid English. The apostrophe is only omitted from >> personal pronouns (hers, its, and so on). >> >> regards >> Steve > > What is the subject of "teaches"? The example given is obviously a sentence fragment. The subject will be in the part of the sentence left out, and from context it is almost certainly going to be the book being discussed, or possibly the author of the book. -- Steven From joelh at planetjoel.com Wed Dec 3 00:32:27 2008 From: joelh at planetjoel.com (Joel Heenan) Date: Wed, 3 Dec 2008 16:32:27 +1100 Subject: Query netgroup information through python In-Reply-To: <843700460811051534l71704b71pd85cc023d0c4e395@mail.gmail.com> References: <843700460811051534l71704b71pd85cc023d0c4e395@mail.gmail.com> Message-ID: <4f89225b0812022132h564f261bob1a10b84129f364a@mail.gmail.com> Well it doesn't appear that this exists in the standard library or in any other library, so I ended up writing my own C interface to the underlying functions. If you are trying to do the same thing, then you can find the module here: http://www.planetjoel.com/viewarticle/629/Python+NSS+netgroups+interface Cheers Joel On Thu, Nov 6, 2008 at 10:34 AM, Joel Heenan wrote: > Python List, > > We have a setup where we have implemented NIS Netgroups through LDAP. > I'm looking to query this information through python. We don't have a > nis domain or nis server so I don't think the nis module is > appropriate, what I think I'm looking for is python bindings for nss > (name switching services). Does such a module exist? grp, pwd, spwd I > think are all going through NSS but do not handle netgroups. > > Thanks > > Joel > -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Sun Dec 7 09:36:18 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 07 Dec 2008 14:36:18 +0000 Subject: Don't you just love writing this sort of thing :) References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: Lawrence D'Oliveiro writes: > In message , Arnaud Delobelle wrote: > >> * you seem to disregard the fact that in 'programming language' there >> is the word 'language'. A language is a way to _communicate_ >> information, in the case of a programming language you communicate >> it to the computer but also to other human beings. > > It was Niklaus Wirth, I think who pointed out that programming languages are > not properly "languages" but are actually "notations". Like mathematics is > a notation. I suppose anyone could call them what they want. The fact is that they are languages with grammars. Anyway, replace 'language' with 'notation' in my point and it is still meaningful. > And mathematics, too, is a predominantly functional, not a procedural, > notation. Well, mathematics is seldom concerned with procedures, that's true. But mathematics is more preoccupied with relations than functions. > Could that be why so many people are frightened of functional > constructs, like my code example and things like lambdas? Because they > look too much like mathematics? I don't think that people have been frightened by it. They don't think it's expressed elegantly as Python is designed to be used as an imperative language. -- Arnaud -- Arnaud From jarausch at skynet.be Mon Dec 1 11:09:55 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Mon, 01 Dec 2008 17:09:55 +0100 Subject: double import protection - how to ? In-Reply-To: References: <49313901$0$2854$ba620e4c@news.skynet.be> <49316253.5010701@skynet.be> Message-ID: <49340C53.8000504@skynet.be> Peter Otten wrote: > Helmut Jarausch wrote: > >> Peter Otten wrote: >>> Helmut Jarausch wrote: >> Then it's a problem with a problem with a webserver written in Python >> (Karrigell-3.0) and probably related to multi-threading (the statements in >> my module get definitely executed more than once). > > Maybe you have the reload_modules* option switched on? That would defeat > Python's caching in order to ease development. > > (*) see http://karrigell.sourceforge.net/en/configuration.htm > Thanks Peter for the hint. Indeed, I am trying to port my application to Karrigell-3.0, where Python's caching is bypassed and the statements in the module get executed each time. So, I have to install a trap door using a global variable. Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From nick at craig-wood.com Tue Dec 2 05:30:46 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 02 Dec 2008 04:30:46 -0600 Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> Message-ID: Slaunger wrote: > On 1 Dec., 16:30, Nick Craig-Wood wrote: > > > > I wouldn't use __getattr__ unless you've got lots of attributes to > > overload. ?__getattr__ is a recipe for getting yourself into trouble > > in my experience ;-) > > > > Just do it like this... > > > > class PayloadOnDemand(object): > > ? ? ? def __init__(self, a_file, a_file_position): > > ? ? ? ? ? self._data = None > > ? ? ? ? ? self.f = a_file > > ? ? ? ? ? self.file_position = a_file_position > > > > ? ? ? @property > > ? ? ? def data(self): > > ? ? ? ? ? if self._data is None: > > ? ? ? ? ? ? ? self._data = self.really_read_the_data() > > ? ? ? ? ? return self._data > > > > then you'll have a .data attribute which when you read it for the > > first time it will populate itself. > > > > If None is a valid value for data then make a sentinel, eg > > > > class PayloadOnDemand(object): > > ? ? ? sentinel = object() > > > > ? ? ? def __init__(self, a_file, a_file_position): > > ? ? ? ? ? self._data = self.sentinel > > ? ? ? ? ? self.f = a_file > > ? ? ? ? ? self.file_position = a_file_position > > > > ? ? ? @property > > ? ? ? def data(self): > > ? ? ? ? ? if self._data is self.sentinel: > > ? ? ? ? ? ? ? self._data = self.really_read_the_data() > > ? ? ? ? ? return self._data > > > > > > - Vis tekst i anf?rselstegn - > > OK, I get it. In my case I have four attributes to create when one of > them is accessed, I do not know if that is a lot of attributes;-) One > thing I like about the __getattr__ is that it is only called that one > single time where an attempt to read a data attribute fails because > the attribute name is not defined in the __dict__ of the object. For 4 attributes I'd probably go with the __getattr__. Or you could easily write your own decorator to cache the result... Eg http://code.activestate.com/recipes/363602/ > With the property methology you do the value check on each get, which > does not look as "clean". The property methology is also a little less > arcane I guess for less experienced Python programmers to understand > when re-reading the code. Less magic is how I would put it. Magic is fun to write, but a pain to come back to. Over the years I find I try to avoid magic more and more in python. > What kind of trouble are you referring to in __getattr__? Is it > recursive calls to the method on accessing object attributes in that > method itself or other complications? Every time I write a __getattr__ I get tripped up by infinite recursion! It is probably just me ;-) > On a related issue, thank you for showing me how to use @property as a > decorator - I was not aware of that possibility, just gotta understand > how to decorate a setter and delete method as well, but I should be > able to look that up by myself... I'm sure you will! http://www.python.org/doc/2.5.2/lib/built-in-funcs.html -- Nick Craig-Wood -- http://www.craig-wood.com/nick From googler.1.webmaster at spamgourmet.com Fri Dec 5 18:29:45 2008 From: googler.1.webmaster at spamgourmet.com (googler.1.webmaster at spamgourmet.com) Date: Fri, 5 Dec 2008 15:29:45 -0800 (PST) Subject: Python C API References: <54fbb55d-3c39-459d-86a3-302b69721f0f@s20g2000yqh.googlegroups.com> <4938ed67$0$30227$9b4e6d93@newsspool1.arcor-online.net> <3d1b6644-c943-412d-8860-6779a981fa44@20g2000yqt.googlegroups.com> Message-ID: <83d478fd-f4a8-495c-b216-b42f4147768c@a12g2000yqm.googlegroups.com> Hi! Any ideas? Thanks, :) From skip at pobox.com Thu Dec 4 12:52:38 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 4 Dec 2008 11:52:38 -0600 Subject: RELEASED Python 3.0 final In-Reply-To: References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> Message-ID: <18744.6374.72609.825058@montanaro-dyndns-org.local> >>> As you have probably guessed: nothing changed here. >>> Also see:http://www.python.org/dev/peps/pep-0666/ >> >> What? Do you mean it's possible to mix tabs and spaces still? Why? Daniel> Why not? Because it has historically been a source of errors in a mixed development environment (people using text editors with different tab stops). Better to not allow them to be mixed. Skip From iofferkicks21 at gmail.com Wed Dec 24 09:41:42 2008 From: iofferkicks21 at gmail.com (www.iofferkicks.com) Date: Wed, 24 Dec 2008 06:41:42 -0800 (PST) Subject: www.iofferkicks.com china cheap wholesale nike shoes,air jordan shoes,air force one shoes. Message-ID: Get Nike Shoes at Super Cheap Prices Discount Nike air jordans (www.iofferkicks.com) Discount Nike Air Max 90 Sneakers (www.iofferkicks.com) Discount Nike Air Max 91 Supplier (www.iofferkicks.com) Discount Nike Air Max 95 Shoes Supplier (www.iofferkicks.com) Discount Nike Air Max 97 Trainers (www.iofferkicks.com) Discount Nike Air Max 2003 Wholesale (www.iofferkicks.com) Discount Nike Air Max 2004 Shoes Wholesale (www.iofferkicks.com) Discount Nike Air Max 2005 Shop (www.iofferkicks.com) Discount Nike Air Max 2006 Shoes Shop (www.iofferkicks.com) Discount Nike Air Max 360 Catalogs (www.iofferkicks.com) Discount Nike Air Max Ltd Shoes Catalogs (www.iofferkicks.com) Discount Nike Air Max Tn Men's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 2 Women's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 3 Customize (www.iofferkicks.com) Discount Nike Air Max Tn 4 Shoes Customize ( www.iofferkicks.com) Discount Nike Air Max Tn 6 Supply (www.iofferkicks.com) Discount Nike Shox NZ Shoes Supply (www.iofferkicks.com) Discount Nike Shox OZ Sale (www.iofferkicks.com) Discount Nike Shox TL Store (www.iofferkicks.com) Discount Nike Shox TL 2 Shoes Store (www.iofferkicks.com) Discount Nike Shox TL 3 Distributor (www.iofferkicks.com) Discount Nike Shox Bmw Shoes Distributor (www.iofferkicks.com) Discount Nike Shox Elite Shoes Manufacturer (www.iofferkicks.com) Discount Nike Shox Monster Manufacturer (www.iofferkicks.com) Discount Nike Shox R4 Running Shoes (www.iofferkicks.com) Discount Nike Shox R5 Mens Shoes (www.iofferkicks.com) Discount Nike Shox Ride Womens Shoes (www.iofferkicks.com) Discount Nike Shox Rival Shoes Wholesaler (www.iofferkicks.com) Discount Nike Shox Energia Wholesaler (www.iofferkicks.com) Discount Nike Shox LV Sneaker (www.iofferkicks.com) Discount Nike Shox Turbo Suppliers (www.iofferkicks.com) Discount Nike Shox Classic Shoes Suppliers (www.iofferkicks.com) Discount Nike Shox Dendara Trainer (www.iofferkicks.com) Discount Nike Air Jordan 1 Seller (www.iofferkicks.com) Discount Nike Air Jordan 2 Shoes Seller (www.iofferkicks.com) Discount Nike Air Jordan 3 Collection (www.iofferkicks.com) Discount Nike Air Jordan 4 Shoes Collection (www.iofferkicks.com) Discount Nike Air Jordan 5 Chaussure Shoes (www.iofferkicks.com) Discount Nike Air Jordan 6 Catalog (www.iofferkicks.com) Discount Nike Air Jordan 7 Shoes Catalog (www.iofferkicks.com) Discount Nike Air Jordan 8 Customized (www.iofferkicks.com) Discount Nike Air Jordan 9 Shoes Customized (www.iofferkicks.com) Discount Nike Air Jordan 10 Wholesalers (www.iofferkicks.com) Discount Nike Jordan 11 Shoes Wholesalers (www.iofferkicks.com) Discount Nike Air Jordan 12 Factory (www.iofferkicks.com) Discount Nike Air Jordan 13 Shoes Factory (www.iofferkicks.com) Discount Nike Air Jordan 14 Shoes Sell (www.iofferkicks.com) Discount Nike Air Jordan 16 Exporter (www.iofferkicks.com) Discount Nike Air Jordan 17 Shoes Exporter (www.iofferkicks.com) Discount Nike Air Jordan 18 Offer (www.iofferkicks.com) Discount Nike Air Jordan 19 Shoes Offer (www.iofferkicks.com) Discount Nike Air Jordan 20 Manufacture (www.iofferkicks.com) Discount Nike Jordan 21 Shoes Manufacture (www.iofferkicks.com) EMAIL:IOFFERKICKS at GMAIL.COM MSN :IOFFERKICKS at MSN.COM From bearophileHUGS at lycos.com Fri Dec 5 22:23:42 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 5 Dec 2008 19:23:42 -0800 (PST) Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> <5926cb50-e53f-4e9e-8672-b4e29e2280b5@r36g2000prf.googlegroups.com> <0149a9be$0$20670$c3e8da3@news.astraweb.com> Message-ID: <32eb24d8-c402-4104-8488-e79ec7998d24@v4g2000yqa.googlegroups.com> Steven D'Aprano: >I think you're talking about mixed spaces/tabs in the one module.< Right. >My gut feeling is that you have to have a fairly unusual set of circumstances before it causes actual bugs.< I don't mix tab and spaces in my code, and my editor is able to convert them, so after the first few days of Python coding, it more or less never caused me problems. But such thing in code written by others has caused me enough troubles, I am generally unable to edit such code keeping it functional, so I have to (sometimes by trial and error) convert it to a space only (or tabs only) format. Such troubles aren't that large compared for example to the usual troubles I receive writing and comping C++ code, but enough compared to the usual smoothness of coding in Python :-) >Er, what do you mean? What wart?< Not using {:}/{} as literals for empty dict/set. Bye, bearophile From clp at rebertia.com Mon Dec 22 02:08:32 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 21 Dec 2008 23:08:32 -0800 Subject: How to represent a sequence of raw bytes In-Reply-To: References: <200812220327.36180.motoom@xs4all.nl> Message-ID: <47c890dc0812212308i68cd7925w7ff8d5a21584a3ba@mail.gmail.com> On Sun, Dec 21, 2008 at 10:56 PM, Steven Woody wrote: > On Mon, Dec 22, 2008 at 10:27 AM, Michiel Overtoom wrote: >> On Monday 22 December 2008 03:23:03 Steven Woody wrote: >> >>> 2. char buf[] = {0x11, 0x22, 0x33, ... } >>> >>> What's the equivalent representation for above in Python? >> >>>>> buf="\x11\x22\33" >>>>> for b in buf: print ord(b) >> ... >> 17 >> 34 >> 27 >>>>> >> > > Hi, Michiel > > I thing "\x11\x22\x33" in python is not the {0x11, 0x22, 0x33} in C. > Since, a string in python is immutable, I can _not_ do something like: > b[1] = "\x55". > > And, how about char buf[200] in my original question? The intension > is to allocate 200 undefined bytes in memory. Thanks. You want the `bytearray` type referred to in PEP 3137 (http://www.python.org/dev/peps/pep-3137/). However, I believe `bytearray` is only available in Python 3.0 Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From istvan.albert at gmail.com Fri Dec 5 15:17:55 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Fri, 5 Dec 2008 12:17:55 -0800 (PST) Subject: slow Python 3.0 write performance? References: Message-ID: On Dec 5, 3:06?pm, s... at pobox.com wrote: > It should get faster over time. ?It will get faster over a shorter period of > time if people contribute patches. I see, thanks for the clarification. I will make the point though that this makes python 3.0 unsuited for anyone who has to process data. One could live with slowdowns of say 20-50 percent, to get the goodies that 3.0 offers, but when a process that takes 1 second suddenly starts to take 10, it is makes the situation untenable. best, Istvan From Werner.Merkl at fujitsu-siemens.com Wed Dec 17 03:09:38 2008 From: Werner.Merkl at fujitsu-siemens.com (Werner Merkl) Date: Wed, 17 Dec 2008 09:09:38 +0100 Subject: Windows PE and Python 2.6 (Side-by-Side error) In-Reply-To: <491DAA05.7080301@v.loewis.de> References: <491DAA05.7080301@v.loewis.de> Message-ID: <4948B3C2.4010301@fujitsu-siemens.com> Martin v. L?wis schrieb: >> Has anyone an idea? > > You should not install "for all users" before copying it, > but "just for me". > > Regards, > Martin This works! Thank you very much! (Sorry for the delay. I had been on a conference, than I was ill and than, there were more urgent things...) But now PyScripter may not use Python 2.6 internally. E. g., if I load a python-dll (import bz2) I receise an Runtime ERROR! R6034... Again, thanx a lot Werner From maakiduwaha at gmail.com Wed Dec 3 05:37:48 2008 From: maakiduwaha at gmail.com (pappu rana) Date: Wed, 3 Dec 2008 02:37:48 -0800 (PST) Subject: USA JOB 1500$ PER DAY Message-ID: <8794fac3-d4ee-41d8-9812-bc4abdf816f7@k24g2000pri.googlegroups.com> make money any where in the world work 1 hour in day,& get 15,000$ per month. No Investment. 100% Guaranteed Income.Proofs & Details On http://multilinsolition.homestead.com From clp at rebertia.com Wed Dec 17 18:40:21 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 17 Dec 2008 15:40:21 -0800 Subject: The rule of literal string In-Reply-To: References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> <_PmdnU59w62vGtTUnZ2dnUVZ_hSdnZ2d@pdx.net> <34028b73-7807-4e88-80bc-fe31a7b1a2a0@i20g2000prf.googlegroups.com> <47c890dc0812171525t527353e2m5c8b0597ee183e21@mail.gmail.com> Message-ID: <47c890dc0812171540oab568fay928577fd3a98b51a@mail.gmail.com> On Wed, Dec 17, 2008 at 3:34 PM, James Mills wrote: > On Thu, Dec 18, 2008 at 9:25 AM, Chris Rebert wrote: >> As I stated previously, the key rule is: >> >> eval(repr(something)) == something > > This rule is only true for basic data types; > > For example: > >>>> eval(repr(1)) == 1 > True >>>> eval(repr([1, 2, 3])) == [1, 2, 3] > True >>>> eval(repr({"a": 1, "b": 2, "c": 3})) == {"a": 1, "b": 2, "c": 3} > True >>>> eval(repr("foo")) == "foo" > True > > I guess the key thing here is that the repr > implementation (__repr__) for str, int, float > list and dict return sensible represenations > that Python _can_ evaluate with eval(...) > > --JamesMills > True, I oversimplified to make things easier to understand. Strictly speaking, only the basic types make the guarantee I stated. Arbitrary types can have arbitrary, non-eval()-able repr()s. But the docs do state eval()-ability as a goal: repr(object) Return a string containing a printable representation of an object. [...] For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From arnodel at googlemail.com Sun Dec 14 05:52:25 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 14 Dec 2008 10:52:25 +0000 Subject: Optimizing methods away or not? References: <0154b041$0$6988$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano writes: > I have a class with a method meant to verify internal program logic (not > data supplied by the caller). Because it is time-consuming but optional, > I treat it as a complex assertion statement, and optimize it away if > __debug__ is false: > > class Parrot: > def __init__(self, *args): > print "Initialising instance..." > if __debug__: > self.verify() # check internal program state, not args > if __debug__: > def verify(self): > print "Verifying..." > > > If I run Python normally, I can do this: FWIW here is a way with a metaclass: ===== verify_init.py ===== from functools import wraps def post_verify(method): @wraps(method) def decorated(self, *args): result = method(self, *args) self.verify() return result return decorated class VerifyInit(type): def __new__(meta, name, bases, attrs): if __debug__: attrs['__init__'] = post_verify(attrs['__init__']) else: del attrs['verify'] return type.__new__(meta, name, bases, attrs) class Parrot: __metaclass__ = VerifyInit def __init__(self, *args): print "Initialising instance..." def verify(self): print "Verifying..." coco = Parrot() ========== marigold:junk arno$ python verify_init.py Initialising instance... Verifying... marigold:junk arno$ python -O verify_init.py Initialising instance... You could also not use the metaclass and use post_verify as a decorator: class Parrot: @post_verify def __init__(self, *args): print "Initialising instance..." if __debug__: def verify(self): print "Verifying..." -- Arnaud From excord80 at gmail.com Thu Dec 4 00:18:53 2008 From: excord80 at gmail.com (excord80 at gmail.com) Date: Wed, 3 Dec 2008 21:18:53 -0800 (PST) Subject: How can I do this (from Perl) in Python? (closures) Message-ID: <68b8294c-8771-4b02-bd46-2f25f5e01602@j35g2000yqh.googlegroups.com> I just came across http://www.perl.com/pub/a/2002/05/29/closure.html and wanted to try the "canonical example of closures" in Python. I came up with the following, but it fails: ####################### #!/usr/bin/env python def make_counter(start_num): start = start_num def counter(): start += 1 return counter from_ten = make_counter(10) from_three = make_counter(3) print from_ten() # 10 print from_ten() # 11 print from_three() # 3 print from_ten() # 12 print from_three() # 4 #################### The error message is: "UnboundLocalError: local variable 'start' referenced before assignment". The same thing happens if I omit start and just use start_num directly. How can I do it in Python? From malkia at mac.com Thu Dec 4 15:08:48 2008 From: malkia at mac.com (Dimiter "malkia" Stanev) Date: Thu, 04 Dec 2008 12:08:48 -0800 Subject: Mathematica 7 compares to other languages In-Reply-To: <6c702fda-1a8a-4c3d-a7c0-82e45edab2ce@k41g2000yqn.googlegroups.com> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <591e8625-7e4d-4db8-ae6c-73c4370f8088@q26g2000prq.googlegroups.com> <6plpnsF8pi3oU1@mid.individual.net> <6c702fda-1a8a-4c3d-a7c0-82e45edab2ce@k41g2000yqn.googlegroups.com> Message-ID: > You think the posts are bad... check out his web site... Just don't go to every page on the Xah website - some of his stuff is NSFW (Not Safe For Work). From yohell at ifm.liu.se Tue Dec 16 20:09:08 2008 From: yohell at ifm.liu.se (Joel Hedlund) Date: Wed, 17 Dec 2008 02:09:08 +0100 Subject: weird dict problem, how can this even happen? In-Reply-To: <88idnfej99XAtNXUnZ2dnUVZ_hednZ2d@pdx.net> References: <88idnfej99XAtNXUnZ2dnUVZ_hednZ2d@pdx.net> Message-ID: Scott David Daniels wrote: > Perhaps your hash function could be something like: I'm not sure I understand what you're suggesting. /Joel From gagsl-py2 at yahoo.com.ar Tue Dec 2 01:48:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Dec 2008 04:48:55 -0200 Subject: Creating classes and objects more than once? References: <5f3a7d84-d07e-417c-a228-e07bdf3b676b@v42g2000yqv.googlegroups.com> <5037872d-d2a3-4d70-be00-18fbf4279767@j35g2000yqh.googlegroups.com> <874p1syzxh.fsf@benfinney.id.au> <58cfdea8-f75f-43c4-bf60-a2dbb8ceed1d@g38g2000yqn.googlegroups.com> <87zljjy3c5.fsf@benfinney.id.au> <1e035b98-418f-4b7b-86f6-14fbfa5844b6@o2g2000yqd.googlegroups.com> <9e804f42-447a-489e-9e44-b2c81c01ddc9@g38g2000yqd.googlegroups.com> Message-ID: En Sat, 29 Nov 2008 04:51:59 -0200, Carl Banks escribi?: > On Nov 28, 11:51?pm, Carl Banks >> Absolute versus relative imports don't have anything to do with the >> issue here. ?PEP 328 concerns itself with imports relative to the >> executing module in package space. ?It has nothing to do with imports >> relative to the current directory in filename space. > > > I thought of another way to put this to help explain things. Suppose > you have two files in your current directory, a Python script file > (app.py) which imports a Python module (work.py). > > Near the top of the file app.py, there is line like this: > > import work > > What happens beneath the covers when this statement is excuted (and > from __future__ import absolute_import hasn't been run)? Many people > seem to think that the Python interpreter first considers whether this > is a relative import and starts by looking for "sister" modules in the > same "package" (i.e., directory). Python would thus see the file > work.py in the same "package" and complete this as a relative import. > > Thus, they reason, if one were to add "from __future__ import > absolute_import" to the top of app.py, the import would no longer work > because implicit relative imports have been disabled. One would have > to use "from . import work" instead. > > Well, this is not how it happens. No top level module, including > __main__, is in a package. Thus, when Python sees "import work" in a > top-level module, it doesn't consider it to be a relative import, even > when implicit relative imports have not been disabled. > > The point of this is, disabling implicit relative imports has no > effect on imports from top-level modules since they were never > relative imports anyway. Python is able to find the "sisters" of top- > level modules and scripts not because it is doing a relative import, > but because those "sister" modules are in one of the directories > listed in sys.path. > > In particular, if "" is listed in sys.path, the current working > directory--even when modified by os.chdir--will be searched for > "sisters" of top-level modules. While all the above explanation is true for scripts executed using "python xxx.py", it's not the same when you execute a module using runpy.py, that is, using "python -m xxx" If you execute a module inside a package in that way, Python recognizes the fact it's inside a package, and honors relative imports (starting from version 2.6, when PEP366 was implemented). So the statement "from __future__ import absolute_import" *does* change how imports are handled on the top module. A simple test showing the difference: C:\temp\test366>dir /b b.py pkga C:\temp\test366>type b.py msg='this is the external b module' C:\temp\test366>cd pkga C:\temp\test366\pkga>dir /b abs.py b.py rel.py __init__.py C:\temp\test366\pkga>type __init__.py C:\temp\test366\pkga>type b.py msg='this is the b module inside package pkga' C:\temp\test366\pkga>type rel.py print "this script uses 'traditional' import semantics" from b import msg print msg print "using a bare import:" import b print b.msg C:\temp\test366\pkga>type abs.py from __future__ import absolute_import print "this script sets absolute_import" print "using an absolute import:" from b import msg print msg print "using a bare import:" import b print b.msg print "using an explicit relative import:" from .b import msg print msg C:\temp\test366\pkga>cd .. C:\temp\test366>python -m pkga.rel this script uses 'traditional' import semantics this is the b module inside package pkga using a bare import: this is the b module inside package pkga C:\temp\test366>python -m pkga.abs this script sets absolute_import using an absolute import: this is the external b module using a bare import: this is the external b module using an explicit relative import: this is the b module inside package pkga -- Gabriel Genellina From roy at panix.com Sat Dec 20 19:05:41 2008 From: roy at panix.com (Roy Smith) Date: Sat, 20 Dec 2008 19:05:41 -0500 Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: In article , walterbyrd wrote: > On Dec 19, 10:25?am, Michael Torrie wrote: > > > Personally the new string formatter is sorely needed in Python. ? > > Really? You know, it's funny, but when I read problems that people > have with python, I don't remember seeing that. Loads of people > complain about the white space issue. Some people complain about the > speed. Lots of complaints about certain quirky behavior, but I have > not come across any complaints about the string formatting. > > In fact, from what I have seen, many of the "problems" being "fixed" > seem to be non-problems. > > I dunno, maybe it's just me. I had an interesting experience with this recently. I was giving a co-worker quick python into. He's an experienced programer in various languages, but this was his first exposure to python. He got really hung up on the % syntax. By (bad) luck, he was trying to print a tuple (let's call it "t"), did format % t and was surprised at the result. It set him off on a "but that's stupid, blah, blah, blah" rant. I haven't absorbed the new syntax well enough to figure out if people will get hung up by this with the new syntax. From google at mrabarnett.plus.com Thu Dec 11 11:44:44 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 11 Dec 2008 16:44:44 +0000 Subject: Preventing execution of a method In-Reply-To: References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> Message-ID: <4941437C.8040901@mrabarnett.plus.com> alex23 wrote: > On Dec 12, 2:07 am, "Emanuele D'Arrigo" wrote: >> I.e. if I have a class with two methods, doSomethingSafe() and >> doSomethingDangerous(), is there a way to prevent another module from >> executing doSomethingDangerous() but allow the execution of >> doSomethingSafe()? >> >> My understanding is that in python this is not possible. Can you >> confirm? > > Your understanding is correct. > > The Python convention is to prefix non-public methods/classes etc with > an underscore, as in _doSomethingDangerous(). This is meant to > indicate to anyone using your module that they shouldn't use this > function, at least not without having a good understanding of what it > does. > You could add a little bit of protection by always passing a certain object into _doSomethingDangerous(). _guard = object() def _doSomethingDangerous(g): if g is not _guard: raise Exception("Don't do that!") That would at least stop accidental calls. From jcd at sdf.lonestar.org Thu Dec 25 19:16:41 2008 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Thu, 25 Dec 2008 19:16:41 -0500 Subject: Exec inside a class method to call other class methods? In-Reply-To: <4953CF57.8080905@sympatico.ca> References: <4953CF57.8080905@sympatico.ca> Message-ID: <20081226001641.GA22946@sdf.lonestar.org> On Thu, 25 Dec 2008 13:22:15 -0500 Matthew Dubins wrote: > Hello all, > > I have made a python script to upload contact information from an > excel worksheet to an online database. One part of the program that > really tripped me up was when I wanted to call specific class methods > that I had made to deal with specific types of contact information > (Parent's name, Child's name, Phone #, etc). My first thought was to > make it easy using the exec statement. > > The code (a method within a class) looked like this: > ---------- > def parse(self, data, data_type) > exec "self.__parse_%s(data)" % data_type > ---------- > The data_type variable contains strings that exactly match the > spellings of the 2nd word in the titles of the class methods that I > wanted to call for each data_type inputted into the parse function. > For some reason, *it didn't work*. Alternately, I found the ugly > code shown below to be functional. As you can see, for each > data_type, I call the corresponding class method that I've > specified. Please help me to transform my ugly functional code into > concise functional code. :) > > Thanks, > Matthew > ---------- > def parse(self, data, data_type): > if data_type == 'nocall': > self.__parse_nocall(data) > elif data_type == 'DOB': > self.__parse_DOB(data) > elif data_type == 'gender': > self.__parse_gender(data) > elif data_type == 'Prematurity': > self.__parse_Prematurity(data) > elif data_type == 'email': > self.__parse_email(data) > elif data_type == 'languages': > self.__parse_languages(data) > elif data_type == 'phone': > self.__parse_phone(data) > elif data_type == 'cname': > self.__parse_cname(data) > elif data_type == 'pname': > self.__parse_pname(data) > elif data_type == 'address': > self.__parse_address(data) > elif data_type == 'duedate': > self.__parse_dudedate(data) > This is precisely what subclasses were designed for: class DataField(object): def __init__(self, data): self.data = data def parse(self): pass class AddressDataField(DataField): def parse(self): self.data = do_something(self.data) class DueDateDataField(DataField): def parse(self): self.data = parse_date(self.data) and so forth. Then your if/else chain can be pulled out to the place where you instantiate each field: if data_type=='address': field=AddressDataField(data) elif data_type=='due_date': field=DueDateDataField(data) else: field = DataField(data) Then a simple field.parse() will do the right thing to field.data(). You might even include the parsing in __init__(). Define __init__() once on the base class (DataField), and it will pull the proper parse method from the subclass. Happy Hacking, and Merry Christmas. Cliff From rileyrgdev at gmail.com Mon Dec 1 09:04:00 2008 From: rileyrgdev at gmail.com (Richard Riley) Date: Mon, 01 Dec 2008 15:04:00 +0100 Subject: Emacs vs. Eclipse vs. Vim References: Message-ID: Roy Smith writes: > In article , > Richard Riley wrote: > >> Roy Smith writes: >> >> > Clay Hobbs wrote: >> >> The first real text editor I used was Vim, which I actually started >> >> using about a year ago. I've looked at Emacs and it just looks >> >> confusing. >> > >> > I've been using emacs for so many years (um let's see, it's got to be close >> > to 25 years now; first saw it on Columbia's TOPS-20 systems in the early >> > 80's) that my fingers know what they're doing without my even thinking >> > about it. In fact, I used to work with another emacs nut. Every so often, >> > one of use would watch the other do something and ask, "What was that?". >> > Inevitably, neither of us could evoke the keystrokes we had just typed. We >> > would just re-do it, and watch our fingers to see what we typed. It didn't >> > even have to be on a keyboard; we could air-type it, and that was good >> > enough. >> > >> > In any case, the basic logic behind emacs is pretty simple. C-F is forward >> > one character. C-B is back one character. C-N is Next line. C-P is >> > Previous line. >> >> It's worth pointing out to people making "loony" signs here that the >> arrow keys work too .... > > Yeah, I guess. I use the arrows keys to mindlessly scroll around in a > file, especially when I just want to show some code to somebody. It serves > two purposes. First, I can lean way back from the keyboard and reach out > with one hand (giving the other person better visibility). Second, it > makes it easier for a non-emacs person to jump in and drive for a while > (they saw me use the arrow keys and do the same, no explanations needed). > > For any serious editing, however, it's strictly the keys on the main part > of the keyboard. It's just so much faster when your hands never have to > leave their home position. To use the arrow keys, I need to pick my hand > up and move it over to the arrow key cluster. Slow, slow, slow. Have to disagree. I could never use C-f etc. If I want to navigate the cursor its generally to browse and the 10th of a second it takes to rest hand on the cursor pad is immaterial in the time compared to sit back and read the code. I find the reference to using control keys to naviaget code character and line at time leads to more people abandoning emacs than you would believe. All it needs is a "cursor keys or, for hardcore types, the following key sequences". Still. all to their own. -- important and urgent problems of the technology of today are no longer the satisfactions of the primary needs or of archetypal wishes, but the reparation of the evils and damages by the technology of yesterday. ~Dennis Gabor, Innovations: Scientific, Technological and Social, 1970 From steve at REMOVE-THIS-cybersource.com.au Thu Dec 25 08:24:03 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Dec 2008 13:24:03 GMT Subject: PythonCard timer/thread tutorial References: <59e602b0-937c-4bd5-bc71-30094e1cd596@r36g2000prf.googlegroups.com> <6f7164cc-56dc-4022-8943-067b8ca44e61@40g2000prx.googlegroups.com> Message-ID: <0163809d$0$6988$c3e8da3@news.astraweb.com> On Wed, 24 Dec 2008 16:59:23 -0800, Mike Driscoll wrote: >> Among my questions are: >> """ A little thread we've added""" seems to be an isolated string. It >> does not seem to be doing anything there, almost like a comment. Why is >> it there? > > > That's what some people call a doc string. Other people call it "Maurice". *wink* A doc[umentation] string is the accepted name for it. Anytime a function, class or module starts immediately with a loan string, that string is stored by the Python compiler in an attribute __doc__. E.g.: >>> def parrot(x): ... "This is a doc string." ... return "Norwegian Blue" ... >>> parrot.__doc__ 'This is a doc string.' > It is like a comment in that > it helps the user know what the function is for. Notice the triple > quotes. Triple quotes are a red herring. Any string literal will do. -- Steven From mudzot at gmail.com Tue Dec 16 12:47:11 2008 From: mudzot at gmail.com (mudzot) Date: Tue, 16 Dec 2008 09:47:11 -0800 (PST) Subject: Free place to host python files? References: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> <32599660-2393-4e18-8c48-05d64bccbbc1@t26g2000prh.googlegroups.com> Message-ID: > well, ignoring the fact that pastebin doesn't work for me for some > reason, I'm talking about hosting it as a .py downloadable, not a hunk > of text. maybe one option is registering in some free project hosting service like code.google.com From geekmail at usenot.de Wed Dec 3 05:48:55 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Wed, 3 Dec 2008 11:48:55 +0100 Subject: Reverse zip() ? References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> <20081203095154.1bb33d4d@usenot.de> <8000d0b0-c9e5-4dbd-a6a0-e35b83277e72@d42g2000prb.googlegroups.com> Message-ID: <20081203114855.3915af9e@usenot.de> On Wed, 3 Dec 2008 02:11:51 -0800 (PST) alex23 wrote: > On Dec 3, 6:51?pm, Andreas Waldenburger wrote: > > On Tue, 02 Dec 2008 18:16:13 -0800 Bryan Olson > > > zip as its own inverse might be even easier to comprehend if we > > > call zip by its more traditional name, "transpose". > > > > Sounds like a Py4k change to me. > > Nah, just add the following to your sitecustomize.py: > > transpose = zip > > :) Gaaahh! :) /W -- My real email address is constructed by swapping the domain with the recipient (local part). From stefan_ml at behnel.de Sat Dec 20 05:27:24 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 20 Dec 2008 11:27:24 +0100 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <015c47ad$0$20656$c3e8da3@news.astraweb.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c47ad$0$20656$c3e8da3@news.astraweb.com> Message-ID: <494cc88c$0$31344$9b4e6d93@newsspool4.arcor-online.net> Steven D'Aprano wrote: > I have no objection to > the addition of the format() method (although I wonder whether it might > have been better as a function). I actually learned about the String.format() method in Java a while after having read about str.format() in Python, and my first reaction was to recognise how stupid you'd have to be to make that a static method that ignores the string it's called on. :) I think '...'.format() makes sense given that we already have '...'.join(). Stefan From jon at ffconsultancy.com Wed Dec 3 11:24:36 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Wed, 03 Dec 2008 16:24:36 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> Message-ID: Xah Lee wrote: > On Dec 2, 5:13 pm, Jon Harrop wrote: >> The Mathematica code is 700,000x slower so a 50% improvement will be >> uninteresting. Can you make my Mathematica code five orders of magnitude >> faster or not? > > Pay me $10 thru paypal, i'll can increase the speed so that timing is > 0.5 of before. > > Pay me $100 thru paypal, i'll try to make it timing 0.1 of before. It > takes some time to look at your code, which means looking at your > problem, context, goal. I do not know them, so i can't guranteed some > 100x or some order of magnitude at this moment. > > Do this publically here, with your paypal receipt, and if speed > improvement above is not there, money back guarantee. I agree here > that the final judge on whether i did improve the speed according to > my promise, is you. Your risk would not be whether we disagree, but if > i eat your money. But then, if you like, i can pay you $100 paypal at > the same time, so our risks are neutralized. However, that means i'm > risking my time spend on working at your code. So, i suggest $10 to me > would be good. Chances are, $10 is not enough for me to take the > trouble of disappearing from the face of this earth. My example demonstrates several of Mathematica's fundamental limitations. They cannot be avoided without improving or replacing Mathematica itself. These issues are never likely to be addressed in Mathematica because its users value features and not general performance. Consequently, there is great value in combining Mathematica with performant high-level languages like OCaml and F#. This is what the vast majority of Mathematica users do: they use it as a glorified graph plotter. >> > few tips: >> >> > ? Always use Module[] unless you really have a reason to use Block[]. >> >> Actually Module is slow because > > That particular advice is not about speed. It is about lexical scoping > vs dynamic scoping. > >> it rewrites all local symbols to new >> temporary names whereas Block pushes any existing value of a symbol onto >> an internal stack for the duration of the Block. > > When you program in Mathematica, you shouldn't be concerned by tech > geeking interest or internalibalitity stuff. Optimization is > important, but not with choice of Block vs Module. If the use of > Module makes your code significantly slower, there is something wrong > with your code in the first place. What exactly do you believe is wrong with my code? >> In this case, Module is 30% slower. > > Indeed, because somethnig is very wrong with your code. No, that is a well-known characteristic of Mathematica's Module and it has nothing to do with my code. >> > ? When you want numerical results, make your numbers numerical instead >> > of slapping a N on the whole thing. >> >> Why? > > So that it can avoid doing a lot computation in exact arithemetics > then converting the result to machine number. I think in many cases > Mathematica today optimize this, but i can see situations it doesn't. That is a premature optimization that has no significant effect in this case because all applications of N have already been hoisted. >> > ? Avoid Table[] when you really want go for speed. Try Map and Range. >> >> The time spent in Table is insignificant. > > just like Block vs Module. It depends on how you code it. If Table is > used in some internal loop, you pay for it. It is insignificant in this case. >> > ? I see nowhere using Compile. Huh? >> >> Mathematica's Compile function has some limitations that make it >> difficult to leverage in this case: > > When you are doing intensive numerical computation, your core loop > should be compiled. No, such computations must be off-loaded to a more performant high-level language implementation like OCaml or F#. With up to five orders of magnitude performance difference, that means almost all computations. >> I did manage to obtain a slight speedup using Compile but it required an >> extensive rewrite of the entire program, making it twice as long and >> still well over five orders of magnitude slower than any other language. > > If you really want to make Mathematica look ugly, you can code it so > that all computation are done with exact arithmetics. You can show the > world how Mathematica is one googleplex times slower. I am not trying to make Mathematica look bad. It is simply not suitable when hierarchical solutions are preferable, e.g. FMM, BSPs, adaptive subdivision for cosmology, hydrodynamics, geophysics, finite element materials... The Mathematica language is perhaps the best example of what a Lisp-like language can be good for in the real world but you cannot compare it to modern FPLs like OCaml, Haskell, F# and Scala because it doesn't even have a type system, let alone a state-of-the-art static type system. Mathematica is suitable for graph plotting and for solving problems where it provides a prepackaged solution that is a perfect fit. Even then, you can have unexpected problems. Compute the FFT of 2^20 random machine-precision floats and it works fine. Raise them to the power of 100 and it becomes 100x slower, at which point you might as well be writing your numerical code in PHP. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From bearophileHUGS at lycos.com Tue Dec 16 11:44:42 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 16 Dec 2008 08:44:42 -0800 (PST) Subject: Generator slower than iterator? References: Message-ID: MRAB: > from collections import defaultdict > match_counter = defaultdict(int) > for line in fileinput.input(sys.argv[1:]): > ip = line.split()[0] > match_counter[ip] += 1 This can be a little faster still: match_counter = defaultdict(int) for line in fileinput.input(sys.argv[1:]): ip = line.split(None, 1)[0] match_counter[ip] += 1 Bye, bearophile From David Fri Dec 26 16:52:24 2008 From: David (David) Date: Fri, 26 Dec 2008 15:52:24 -0600 Subject: strange behavior of math.sqrt() in new 3.0 version Message-ID: I'm a newbee trying 3.0 Please help with math.sqrt() At the command line this function works correctly >>> import math n = input("enter a number > ") s = math.sqrt(n) An entry of 9 or 9.0 will yield 3.0 Yet the same code in a script gives an error message Script1 import math n = input("enter a number > ") s = math.sqrt(n) Traceback (most recent call last) : File "", line 1, in File "script1.py" line 3 in s = math.sqrt(n) TypeError : a float is required Entering 9 or 9.0 gives same error message. According to the math module the results of all functions are floats. However it says nothing about inputs. Strangely the above code runs fine in version 2.5 ( ? ) and will handle large integers. I've read the documentation for 3.0 including the section "Floating Point Arithmetic: Issues & Limitations" and it helps nada. From federico at linux.com.uy Tue Dec 16 10:07:14 2008 From: federico at linux.com.uy (Federico Moreira) Date: Tue, 16 Dec 2008 12:07:14 -0300 Subject: Generator slower than iterator? Message-ID: Hi all, Im parsing a 4.1GB apache log to have stats about how many times an ip request something from the server. The first design of the algorithm was for line in fileinput.input(sys.argv[1:]): ip = line.split()[0] if match_counter.has_key(ip): match_counter[ip] += 1 else: match_counter[ip] = 1 And it took 3min 58 seg to give me the stats Then i tried a generator solution like def generateit(): for line in fileinput.input(sys.argv[1:]): yield line.split()[0] for ip in generateit(): ...the same if sentence Instead of being faster it took 4 min 20 seg Should i leave fileinput behind? Am i using generators with the wrong aproach? Thanks in advance, Federico. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jon at ffconsultancy.com Wed Dec 10 05:45:25 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Wed, 10 Dec 2008 10:45:25 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <9ecfa224-ce8f-44e9-abca-008314f44e87@40g2000prx.googlegroups.com> Message-ID: <3sOdnVyMm5m4AKLUnZ2dnUVZ8hydnZ2d@posted.plusnet> Stef Mientki wrote: > Who said Mathematica was a high level language ? Xah is using what he calls "highlevelness" as an excuse for poor performance. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From bearophileHUGS at lycos.com Fri Dec 12 09:58:39 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 12 Dec 2008 06:58:39 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> Message-ID: <25b4d503-5073-4e66-8914-ca5fa7b144e1@w39g2000prb.googlegroups.com> sturlamolden: > On a recent benchmark Java 6 -server beats C compiled by GCC 4.2.3 And > most of that magic comes from an implementation of a dynamically typed > language (Smalltalk). [...] > http://shootout.alioth.debian.org/u32q/benchmark.php?test=all?=all That is indeed a nice result, JavaVM has come a long way from the first one used for applets. That result comes mostly from the fact that this is a test on a 4-core CPU, that is less easy to manage from C. You can see that in the single 64-bit core tests: http://shootout.alioth.debian.org/u64/benchmark.php?test=all&lang=all And take a look at the memory used too, up to 34 times higher for the JVM on the 4-core CPU. In the next years people that use low-level languages like C may need to invent a new language fitter for multi-core CPUs, able to be used on GPUs too (see the OpenCL), less error-prone than C, able to use the CPU vector instructions efficiently. (The D language is probably unfit for this purpose, because even if it's meant to be a system language, I don't think it can be used much to replace C everywhere it's used now.) A C+ maybe? :-) I agree that CPython may quite enjoy having something built-in like Psyco, but it's a lot of work for an open source project. Probably with 1/3 or 1/2 of the work poured on PyPy you may create that improvement for CPython. Maybe PyPy will someday produce some fruit, but I think they have used the wrong strategy: instead of trying to create something very new that someday will work, it's often better to try to improve something that today everybody uses, AND try to be useful from almost the very beginning. Bye, bearophile From gagsl-py2 at yahoo.com.ar Mon Dec 29 04:52:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Dec 2008 07:52:16 -0200 Subject: Read-Write Lock vs primitive Lock() References: Message-ID: En Mon, 29 Dec 2008 05:56:10 -0200, k3xji escribi?: > I am trying to see on which situations does the Read-Write Lock > performs better on primitive Lock() itself. Below is the code I am > using to test the performance: > import threading > import locks > import time > > class mylock(object): (I'm not convinced your lock is correct) > GLOBAL_VAR = 1 > #GLOBAL_LOCK = locks.ReadWriteLock() > GLOBAL_LOCK = threading.Lock() > #GLOBAL_LOCK = mylock() > GLOBAL_LOOP_COUNT = 100000 > GLOBAL_READER_COUNT = 1000 > GLOBAL_WRITER_COUNT = 1 Only one writer? If this is always the case, you don't need a lock at all. > class wthread(threading.Thread): > def run(self): > try: > #GLOBAL_LOCK.acquireWrite() > #GLOBAL_LOCK.acquire_write() > GLOBAL_LOCK.acquire() > for i in range(GLOBAL_LOOP_COUNT): > GLOBAL_VAR = 4 > finally: > #GLOBAL_LOCK.release_write() > GLOBAL_LOCK.release() Note that the thread acquires the lock ONCE, repeats several thousand times an assignment to a *local* variable called GLOBAL_VAR (!), finally releases the lock and exits. As every thread does the same, they just run one after another, they never have a significant overlap. Also, you should acquire the lock *before* the try block (you have to ensure that, *after* acquiring the lock, it is always released; such requisite does not apply *before* acquiring the lock) I'd test again with something like this: class wthread(threading.Thread): def run(self): global GLOBAL_VAR for i in xrange(GLOBAL_LOOP_COUNT): GLOBAL_LOCK.acquire() try: GLOBAL_VAR += 1 finally: GLOBAL_LOCK.release() > class rthread(threading.Thread): > def run(self): > try: > #GLOBAL_LOCK.acquireRead() > #GLOBAL_LOCK.acquire_read() > GLOBAL_LOCK.acquire() > for i in range(GLOBAL_LOOP_COUNT): > GLOBAL_VAR = 3 > finally: > #GLOBAL_LOCK.release_read() > GLOBAL_LOCK.release() Hmmm, it's a reader but attempts to modify the value? You don't have to protect a read operation on a global variable - so a lock isn't required here. > What I am doing is: I am creating multiple readers and try to do > something. I had assumed that with using primitive Lock() on the above > situation, it will create a bottleneck on the rthreads. But the > numbers indicate that there are no difference at all. I had > implemented my own READ-WRIET lock as can be seen above mylock and > also used the one here: code.activestate.com/recipes/502283/. I hope you now understand why you got the same numbers always. -- Gabriel Genellina From fetchinson at googlemail.com Thu Dec 11 03:30:56 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 11 Dec 2008 00:30:56 -0800 Subject: why doesn't pop/clear call __delitem__ on a dict? In-Reply-To: <47c890dc0812110005m3106ff39i9f9211a99c0afc9e@mail.gmail.com> References: <47c890dc0812110005m3106ff39i9f9211a99c0afc9e@mail.gmail.com> Message-ID: >> I just found out that if I want to have a custom dict it's not enough >> to overload __getitem__, __setitem__ and __delitem__ because, for >> example, pop and clear don't call __delitem__. I.e. an instance of the >> following will not print 'deleted' upon instance.pop( 'key' ): >> >> class mydict( dict ): >> def __setitem__( self, key, value ): >> print 'set' >> super( mydict, self ).__setitem__( key, value ) >> def __getitem__( self, key ): >> print 'get' >> super( mydict, self ).__getitem__( key ) >> def __delitem__( self, key ): >> print 'deleted' >> super( mydict, self ).__delitem__( key ) >> >> Why is this? > > For optimization purposes essentially, so that the built-in dict can > be as fast as possible as it is used pervasively in Python. > >> what other methods do I have to overload so that >> I get what I expect for all dict operations? > > You might consider just subclassing UserDict.DictMixin instead: > http://docs.python.org/library/userdict.html#UserDict.DictMixin > It implements the complete dict interface all in terms of provided > __getitem__(), __setitem__(), __delitem__(), and keys() methods. Thanks a lot! -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From ivan.illarionov at gmail.com Tue Dec 23 15:51:18 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 23 Dec 2008 12:51:18 -0800 (PST) Subject: PIL - font kerning References: <21524b00-9151-43ab-b1b9-a3dd5666d959@n33g2000pri.googlegroups.com> Message-ID: <013a0d90-e70e-49e9-ad7c-73d93e7bd79a@z28g2000prd.googlegroups.com> On Dec 23, 11:22 pm, Ivan Illarionov wrote: > On 23 ???, 16:44, carsn wrote: > > > Hey all, > > > anybody know, if there?s a way to specify the kerning of a font, when > > you draw text with PIL? > > > I?d like to achieve the same effect that you get, when you set a > > negative kerning in Gimp/Photshop - ie. reduce the spacing between > > glyphs. > > > Can PIL do that or do I use another lib for that? > > > Thx for any pointers & some nice xmas days to U all! > > carsten > > No. PIL can't do that. I suggest combination of cairo/pango/pangocairo > (pycairo and pygtk packages). > > Ivan I found a little helper function that does what you want (and more) import cairo import pango import pangocairo def draw_text(surface, context, text, font="sans 14", position=None, color=None, box_width=None, alignment=pango.ALIGN_CENTER, line_spacing=None, letter_spacing=None, extra_kerning=None): if color is None: color = (0.0, 0.0, 0.0) context.set_source_rgb(*color) pc = pangocairo.CairoContext(context) layout = pc.create_layout() layout.set_text(text) layout.set_font_description(pango.FontDescription(font)) if box_width: layout.set_width(box_width) layout.set_alignment(alignment) if line_spacing: layout.set_spacing(spacing) alist = pango.AttrList() if letter_spacing: alist.insert(pango.AttrLetterSpacing(letter_spacing, 0, len (text))) if extra_kerning: for pos, kern in extra_kerning.iteritems(): alist.insert(pango.AttrLetterSpacing(kern, pos, pos +1)) layout.set_attributes(alist) if position is None: width, height = surface.get_width(), surface.get_height() w, h = layout.get_pixel_size() position = (width/2.0 - w/2.0, height/2.0 - h/2.0) context.move_to(*position) pc.show_layout(layout) And example usage: surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) context = cairo.Context(surface) draw_text(surface, context, 'Hello world!', font="sans 52", color=(.25,.28,.33), letter_spacing=-6000, extra_kerning={0:-9000, 1:-1000, 6:6000, 7:-15000, 8:5000, 9:-7000}) surface.write_to_png("hello.png") -- Ivan From saving.energy150 at gmail.com Sat Dec 6 10:02:48 2008 From: saving.energy150 at gmail.com (Energy Saver) Date: Sat, 6 Dec 2008 07:02:48 -0800 (PST) Subject: How you can save fuel and the environment Message-ID: Driving and Car Maintenance Transportation accounts for 66% of U.S. oil use -mainly in the form of gasoline. Luckily, there are plenty of ways to improve gas mileage. Driving Tips:- Idling gets you 0 miles per gallon. The best way to warm up a vehicle is to drive it. No more than 30 seconds of idling on winter days is needed. Anything more simply wastes fuel and increases emissions.- Aggressive driving (speeding, rapid acceleration, and hard braking) wastes gas. It can lower your highway gas mileage 33% and city mileage 5%. Drive at lowest and constant rpms; 2000 rpm are enough; you can save up to 30%. Even a Porsche can be driven at the 4th gear at 20 mph and at the 6th gear at 50 mph with 2.5 times less fuel consumption.- Avoid high speeds. Driving 75 mph, rather than 65 mph, could cut your fuel economy by 15%.- When you use overdrive gearing, your cars engine speed goes down. This saves gas and reduces wear.- Use air conditioning only when necessary.- Clear out your car; extra weight decreases gas mileage. Each 60 pounds increases fuel consumption by 10%. - Reduce drag by placing items inside the car or trunk rather than on roof racks. A roof rack or carrier provides additional cargo space and may allow you to buy a smaller car. However, a loaded roof rack can decrease your fuel economy by 5%.- Check into carpooling and public transit to cut mileage and car maintenance costs. Car Maintenance Tips:- Use the grade of motor oil recommended by your cars manufacturer. Using a different motor oil can lower your gasoline mileage by 1% to 2%.- Keep tires properly inflated and aligned to improve your gasoline mileage by around 3.3%.- Get regular engine tune- ups and car maintenance checks to avoid fuel economy problems due to worn spark plugs, dragging brakes, low transmission fluid, or transmission problems.- Replace clogged air filters to improve gas mileage by as much as 10% and protect your engine.- Combine errands into one trip. Several short trips, each one taken from a cold start, can use twice as much fuel as one trip covering the same distance when the engine is warm. Do not forget that in the first mile your car uses 8 times more fuel, in the second mile 4 times and only after the fourth mile it becomes normal.Long-Term Savings Tip- Consider buying a highly fuel-efficient vehicle. A fuelefficient vehicle, a hybrid vehicle, or an alternative fuel vehicle could save you a lot at the gas pump and help the environment.See the Fuel Economy Guide (www.fueleconomy.gov) for more on buying a new fuel-efficient car or truck. Source: www.eere.energy.gov and http://www.vcd.org/155.html From arnodel at googlemail.com Fri Dec 12 14:26:27 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 12 Dec 2008 19:26:27 +0000 Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> <31443882-cb41-420b-8269-b1590581783d@c36g2000prc.googlegroups.com> <6qfhc9Fc3a5jU5@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch writes: > On Fri, 12 Dec 2008 07:56:58 -0800, sturlamolden wrote: > >> On Dec 12, 4:55 pm, sturlamolden wrote: >> >>> def __setitem__(self, index, value): >>> if _buf[index] is not value: # given that _buf is the tuple's >>> internal buffer >>> raise TypeError, 'tuple' object does not support item >>> assignment >> >> bl?h, that should be self._buf[index] > > But then the error message is not true anymore because tuples *would* > support item assignment when the old and new value are the same. Which > leads to strange things like code that may or may not raise that > exception, depending on implementation details: > > t = (1, 2) > t[0] = 1 # Maybe okay -- maybe not. > t[1] += 0 # Same here. > > I'd find that quite odd. > > Ciao, > Marc 'BlackJack' Rintsch What I find a bit annoying is when you get both * an exception * a mutation E.g. >>> t[1] *= 2 Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment Now is t the same as before? Sometimes it is: >>> t (1, 2) >>> t[1] *= 2 Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment >>> t (1, 2) Sometimes not: >>> t (1, [2]) >>> t[1] *= 2 Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment >>> t (1, [2, 2]) I agree it's not a bug, but I never feel comfortable with it. -- Arnaud From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 18:50:29 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Dec 2008 23:50:29 GMT Subject: To Troll or Not To Troll (aka: "as" keyword woes) References: <20081205163107.1815df40@usenot.de> Message-ID: <0149b601$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 14:00:18 -0800, James Stroud wrote: > Andreas Waldenburger wrote: >> Is it me, or has c.l.p. developed a slightly harsher tone recently? >> (Haven't been following for a while.) > > Yep. I can only post here for about a week or two until someone blows a > cylinder and gets ugly because they interpreted something I said as a > criticism of the language and took it personally by extension. What do you mean??? Python is PERFECT and if you don't AGREE than you should go back to Ruby you Ruby-lover!!! *wink* -- Steven From kyrie at uh.cu Sun Dec 21 14:54:55 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Sun, 21 Dec 2008 14:54:55 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: <1229889295.494e9f0f58182@mail.uh.cu> Quoting r : > I noticed when i mentioned "self" nobody wants to touch that subject. > There could be many reasons why... > > 0.) nobody but the 10 regulars i see here exists > 1.) nobody cares(doubt it) > 2.) nobody is brave enough to question it(maybe) > 3.) most people like to type self over and over again(doubt it) > 4.) most people here have given up on changing the BDFL's mind about > it. (good possibility) > 5.) this is a hot-button topic(no doubt in my mind!) You forgot 6.) it is the best, cleanest, most consistent and extensible way to do it. > This was the reason for using indention over the bracket plague in > python. REDUNDANCY!!! Why not dump self and make the language cleaner. > I love python's classes, but HATE self.redundant! This really needs to > be fixed, and you have not heard the last from me about it!!! Do you also hate cls.redundant on a classmethod? Would you rather type 'self' even when it is referring to a class? Would you like to resort to a hack, like C#3.0's 'this' explicit argument, when monkey-patching? I used to hate 'self'. Then I met classmethods, metaclasses and decorators, and the 'new'/'types' modules. It's just one of those examples where Guido's time machine works flawlessly. > 3000 would have been the perfect time to dump self and really clean up > the language, and it's not too late, dawn is not upon us yet. No need to wait for python 3000. You can have a 'selfless metaclass' right now: http://www.voidspace.org.uk/python/articles/metaclasses.shtml (BTW, I really hope you are complaining about the explicit self on the argument list, and not about the 'self.' prefix - if that were the case, what magic would you propose for the compiler to guess when you are referring to locals, globals, class or instance variables?) -- Luis Zarrabeitia Facultad de Matem?tica y Computaci?n, UH http://profesores.matcom.uh.cu/~kyrie From bdesth.quelquechose at free.quelquepart.fr Thu Dec 11 14:48:49 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 11 Dec 2008 20:48:49 +0100 Subject: Preventing execution of a method In-Reply-To: <307fe197-1b42-4305-af0e-94b7ebe3ce70@r15g2000prh.googlegroups.com> References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> <764daeef-bfbe-411a-8521-bb114321e4ac@b38g2000prf.googlegroups.com> <19304f8c-e34f-4aa9-8df2-6a7d3553007a@e1g2000pra.googlegroups.com> <2eed8876-94d2-4304-88a5-eb4a78b4f41d@33g2000yqm.googlegroups.com> <307fe197-1b42-4305-af0e-94b7ebe3ce70@r15g2000prh.googlegroups.com> Message-ID: <49417c59$0$8491$426a74cc@news.free.fr> Emanuele D'Arrigo a ?crit : > Thank you all for the confirmation and the suggestions (including the > tangential ones: I didn't know one could remove your his own posts!). > > As much as I really like Python (which I've been using full-time only > for the past two months) I really wish it did have regular private/ > protected/public methods. What for ? What you need is a way to tell the client code what's part of the interface and what's implementation detail. From experience (*years* fo experience), no one in it's own mind will mess with implementation unless he has a very compelling reason _and_ is willing to pay the price ("shit, I broke everything... Ok, my fault.") > I'm building an application that can be extended by the users and I > really wish there was a solid way to prevent them from accessing parts > of the application that they shouldn't access In Python, "shouldn't access" is spelled with a single leading underscore !-) > or to provide read-only > access. I.e. right now I'm working on the graphical client which > potentially could be rewritten entirely by the users. It is necessary > and perfectly reasonable for the client module to access some of the > objects to be represented graphically, but those objects shouldn't be > modifiable by it. Why so ? At worst, they'll break everything. So what ? As long as they mess with your implementation, they are responsible for what happens. OTHO, someone may have a perfectly valid reason to rewrite parts (or whole) of your GUI - and he'll just love you for not standing in the way. > I now wonder, would developing the graphical client as an entirely > separate application, communicating with the server via the localhost > network interface and messages, solve the problem? *which* problem ? Seriously ? What do you fear ? Extension code breaking your app ? How is that *your* problem (I mean, as long as you explicitely told the user what was part of the API and what wasn't ?). What if your program was written in C, distributed only as compiled machine code, and one of your users decided to make random edits in the binary code ? Would you feel responsible ? *Nothing* in this world is idiot-proof, so don't waste time trying to protect idiots from themselves. From banibrata.dutta at gmail.com Tue Dec 2 23:54:27 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Wed, 3 Dec 2008 10:24:27 +0530 Subject: [ANN] Pyjamas 0.4: Python Web Toolkit Release In-Reply-To: References: Message-ID: <3de8e1f70812022054g40f974a1x5bdd676b2d9527ea@mail.gmail.com> Amazing concept, and glad that someone thought of this and implemented this. The book's formatting on IE and Chrome looked a bit unusual. Content wise it is already firly decent (i.e. enough to get a programmer started), but sometimes text appears in a long & narrow col. format instead of the more usual page format ... and the (i) i.e. informative text icons to the left of informative notes gives a jarring visual feel/urge to scroll to see more :). On Tue, Dec 2, 2008 at 6:15 PM, Luke Kenneth Casson Leighton wrote: > This is the 0.4 Release of Pyjamas, the python-to-javascript > compiler and Web Widget set and framework. > > Download Pyjamas 0.4 here: > https://sourceforge.net/project/showfiles.php?group_id=239074 > http://code.google.com/p/pyjamas/downloads/list > > Pyjamas started as a port of Google's Web Toolkit, to python. > Explaining why Pyjamas (and GWT) is so significant takes > some doing: the summary is that comprehensive desktop-like > user interfaces can be developed very simply, to run in > any modern web browser, without having to write a single > line of JavaScript. Further recommended reading is here: > http://advogato.org/article/993.html > http://advogato.org/article/981.html > > The homepage is http://pyjs.org > The sister project, Pyjamas-Desktop, is at http://pyjd.org > > Documentation on Pyjamas is considerable, and includes: > http://pyjs.org/book/output/Bookreader.html > http://pyjs.org/showcase/Showcase.html > http://pyjd.sf.net/api > http://pyjd.sf.net/controls_tutorial.html > http://lkcl.net/pyjamas-desktop/docs/output/docui.html > Also, as the Pyjamas UI API is near-identical to that of > GWT 1.5, the GWT JavaDoc reference guide is still relevant: > http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/index.html > -- > http://mail.python.org/mailman/listinfo/python-list > -- regards, Banibrata http://www.linkedin.com/in/bdutta http://octapod.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From BrooklineTom at gmail.com Wed Dec 31 00:02:11 2008 From: BrooklineTom at gmail.com (brooklineTom) Date: Tue, 30 Dec 2008 21:02:11 -0800 (PST) Subject: Parsing Excel spreadsheets References: <6a54de23-bea4-40c7-ad7c-22c6eba4bd8a@z6g2000pre.googlegroups.com> Message-ID: andyhume at gmail.com wrote: > Hi, > > Can anybody recommend an approach for loading and parsing Excel > spreadsheets in Python. Any well known/recommended libraries for this? > > The only thing I found in a brief search was http://www.lexicon.net/sjmachin/xlrd.htm, > but I'd rather get some more input before going with something I don't > know. > > Thanks, > Andy. I save the spreadsheets (in Excel) in xml format. I started with the standard xml tools (xml.dom and xml.dom.minidom). I built a pullparser, and then just crack them. The MS format is tedious and overly complex (like all MS stuff), but straightforward. Once I've cracked them into their component parts (headers, rows, cells, etc), then I walk through them doing whatever I want. I found this material to be no worse than doing similar crud with xhtml. I know there are various python packages around that do it, but I found the learning curve of those packages to be steeper than just grokking the spreadsheet structure itself. In spite of all the hair, the underlying MS structure really does have everything you'll need. My suggestion is just go for it, it isn't all that hard. From jfabiani at yolo.com Tue Dec 16 01:47:25 2008 From: jfabiani at yolo.com (John Fabiani) Date: Mon, 15 Dec 2008 22:47:25 -0800 Subject: tutorial on parser Message-ID: Hi, I'm attempting to learn how to convert MsSQl Transact-SQL to postgres pgsql. So far my readings have led me to finding a parser. I'm looking for a tutorial on how to get it done. I did find a commercial product but they want over $10,000 us. This way beyond my means. Therefore, I need to get it done either myself to find a open source project. Thanks in advance. John Fabiani From joe at strout.net Tue Dec 30 16:55:24 2008 From: joe at strout.net (Joe Strout) Date: Tue, 30 Dec 2008 14:55:24 -0700 Subject: embedding python in wxpython In-Reply-To: References: <191280cf-ecf9-4135-9737-9923061855d1@t39g2000prh.googlegroups.com> Message-ID: <495A98CC.5070808@strout.net> Steve Holden wrote: >> I'd like the console to be a bidirectional representation of what's >> going on in the gui, plus a general purpose evaluation environment >> where you can manipulate application data via some api which is >> automatically exposed to the console when the application opens up. >> >> I'm looking for high-level hints/strategies/directions. >> > I seem to remember you can create your wxApp with an argument of True or > False. One of those settings creates a window containing any output to > sys.stderr, if I remember rightly. You do -- True (the default) redirects standard output to a window, while False does not redirect it. However, neither setting will create a bidirectional console or evaluation environment as the OP was asking for. (But other wx widgets do provide that, as other replies have pointed out.) Best, - Joe From upton at virginia.edu Thu Dec 4 15:32:12 2008 From: upton at virginia.edu (Dan Upton) Date: Thu, 4 Dec 2008 15:32:12 -0500 Subject: Off Topic: Re: Obama's Birth Certificate - Demand that US presidential electors investigate Obama's eligibility In-Reply-To: References: <89pZk.9151$be.4743@nlpi061.nbdc.sbc.com> Message-ID: <5504f9ac0812041232x2a22a63m8217779c57d44ebd@mail.gmail.com> [snip > > > Follow-ups again set to talk.politics. Of course that may be futile in > dealing with this kind of scumbag. > > -- > --Bryan Also, changing newsgroups followups doesn't affect replying to the mailing list. From aleksandr.goretoy at gmail.com Sat Dec 27 05:54:59 2008 From: aleksandr.goretoy at gmail.com (alex goretoy) Date: Sat, 27 Dec 2008 04:54:59 -0600 Subject: parsing csv files class Message-ID: Hello All, I have this class that I use in one of my projects. I know it's missing functionality and some things could have been done differently. Can you ehlp me make this class better? What can I do to make it more resistant to error? You can find the stdout_colours class on Google if you want it, JFGI I want to make it more pythonic. I come from a PHP background, can you tell? Any and all help is appreciated -Alex #!/usr/bin/env python from ctypes import * import os, sys, types, csv, urllib, urllib2, urlparse, string,stdout_colours class parsercsvy(object): """Return a line from a csv file or total amount of lines""" def __init__(self,file_name=""): self.func_me_color="white_on_black" self.soc=stdout_colours.stdout_colors() self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.filename = file_name self.buffer = [] self.bufferp= [] if string.find(self.filename,"http") != -1: resp=urllib2.urlopen(self.filename) file=resp.read() lfi=len(string.split(self.filename,"/")) filename = "/tmp/"+string.split(self.filename,"/")[lfi-1] f=open(filename,"w") f.write(file) f.close self.parse(self.filename) else: self.parse(self.filename) self.soc.me_him(['EXIT:',__name__],self.func_me_color) def parse(self,filename,ret=0): self.soc.me_him(['ENTER:',__name__],self.func_me_color) i = 0 try: reader = csv.reader(file(filename, "rb")) try: for row in reader: self.buffer.append(row) s,a=[],{} for j in range(len(self.buffer[0])): a[self.buffer[0][j]]=row[j] self.bufferp.append(a) i+=1 self.total = i-1 except csv.Error, e: sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) except IOError, e: sys.exit('file %s, IOError: %s' % (filename, e)) self.soc.me_him(['EXIT:',__name__],self.func_me_color) def index(self, index): """return line for index""" self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.soc.me_him(['RETURN:',self.buffer[int(index)],__name__],self.func_me_color) return self.buffer[int(index)] def total(self): """return total number of lines in csv file""" self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.soc.me_him(['RETURN:',self.total,__name__],self.func_me_color) return self.total def header(self): """return csv header == line 0""" self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.soc.me_him(['RETURN:',self.buffer[0],__name__],self.func_me_color) return self.buffer[0] def find_and_replace(self,li,fi,re): """ find and replace a string inside a string, return list find_and_replace(list,find,replace) """ this=[] for l in li: # found_index=string.find(l,fi) this.append(l.replace(fi,re)) return this def return_buffer(self): self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.soc.me_him(['RETURN:',self.buffer,__name__],self.func_me_color) return self.buffer if __name__ == "__main__": if len(sys.argv) < 1: print "Usage: %s file"% sys.argv[0] f=sys.argv[1] c=csv_parser(f) print c.bufferp -- ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at cheimes.de Mon Dec 22 14:02:58 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 22 Dec 2008 20:02:58 +0100 Subject: I always wonder ... In-Reply-To: <18767.54282.188749.522233@montanaro-dyndns-org.local> References: <18767.54282.188749.522233@montanaro-dyndns-org.local> Message-ID: skip at pobox.com schrieb: > .... shouldn't people who spend all their time trolling be doing something > else: studying, working, writing patches which solve the problems they > perceive to exist in the troll subject? Is there some online troll game > running where the players earn points for generating responses to their > posts? Don't worry about the trolling, Skip. I'd be more worried if nobody trolls about Python. It would mean Python loses popularity and our work is all in vain. Prepare yourself for the worst, Christmas holidays are near! The fading day light usually increased the amount of troll posts. Christian From sjmachin at lexicon.net Fri Dec 26 22:22:09 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 26 Dec 2008 19:22:09 -0800 (PST) Subject: math.sqrt() in new 3.0 version : solution in input() References: Message-ID: On Dec 27, 1:34?pm, David Lemper wrote: > > Problem is the new input() function. Yields a string. > > Thanks to Scott, Chris, Gabriel & John. > > Some thought I was not using the Python 3 command line. > I was : ?Python 3.0 (r30:67507... > Erratic behavior was that I was sometimes using n = input() > and sometimes entering the integer directly into the > math.sqrt() function, eg s = math.sqrt(4194304) > > I cannot find a mention of this in "The Python Tutorial > release 3.1" ? The I&O section discusses output formatting > and reading & writing text files. Yes, it's not in the Tutorial. But you must have found out about its existence somewhere ... 2.x manuals? > John pointed out its in Guido's "What's New in Python3.0" > Indeed its mentioned in PEP 3111, near end of What's New > and somewhat obscurely. " raw_input() was renamed to input(). > That is the new input() function function reads a line from > sys.stdin . . ." ? ? ? ? ? ? ? ? ? ? ? ? ? If you are sticking to 3.0, then you're not in the target audience for "What's New in Python3.0". Just read the docs on the input function: http://docs.python.org/3.0/library/functions.html#input or use help() at the interactive prompt: Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> help(input) Help on built-in function input in module builtins: input(...) input([prompt]) -> string Read a string from standard input. The trailing newline is stripped. [snip] HTH, John From duncan.booth at invalid.invalid Wed Dec 10 14:43:23 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Dec 2008 19:43:23 GMT Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: Tim Chase wrote: > [nibbling a little flame-bait] > >> Python is even slower than PHP! >> >> Just go to any Python website and you will know. >> An example is: >> http://www2.ljworld.com/ > > I'm not sure I'm seeing what you're seeing -- the dynamic page > loaded in under 2 seconds -- about on par with sun.com, > python.org, php.net or msn.com all being pulled from non-cached > servers. You sure you're not mistaking your bandwidth and/or > browser-rendering slowness for Python-as-a-web-server slowness? > For another example try http://www.novell.com. That's a Plone site which gets a lot of visitors and isn't noticeably slow. From kyrie at uh.cu Wed Dec 10 10:40:19 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Wed, 10 Dec 2008 10:40:19 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: <1228923619.493fe2e3c3073@comuh.uh.cu> Quoting Rasmus Fogh : > Rhamphoryncus wrote: > > You grossly overvalue using the "in" operator on lists. > > Maybe. But there is more to it than just 'in'. If you do: > >>> c = numpy.zeros((2,)) > >>> ll = [1, c, 3.] > then the following all throw errors: > 3 in ll, 3 not in ll, ll.index(3), ll.count(3), ll.remove(3) > c in ll, c not in ll, ll.index(c), ll.count(c), ll.remove(c) > > Note how the presence of c in the list makes it behave wrong for 3 as > well. I think I lost the first messages on this thread, but... Wouldn't be easier to just fix numpy? I see no need to have the == return anything but a boolean, at least on Numpy's case. The syntax 'a == b' is an equality test, not a detailed summary of why they may be different, and (a==b).all() makes no little sense to read unless you know beforehad that a and b are numpy arrays. When I'm comparing normal objects, I do not expect (nor should I) the == operator to return an attribute-by-attribute summary of what was equal and what wasn't. Why is numpy's == overloaded in such a counter intuitive way? I realize that an elementwise comparison makes a lot of sense, but it could have been done instead with a.compare_with(b) (or even better, a.compare_with(b, epsilon=e)). No unexpected breakage, and you have the chance of specifying when you consider two elements to be equal - very useful. Even the transition itself could be done without breaking much code... Make the == op return an object that wraps the array of bools (instead of the array itself), give it the any() and all() methods, and make __nonzero__/__bool__ equivalent to all(). -- Luis Zarrabeitia Facultad de Matem?tica y Computaci?n, UH http://profesores.matcom.uh.cu/~kyrie From gagsl-py2 at yahoo.com.ar Mon Dec 29 01:15:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Dec 2008 04:15:56 -0200 Subject: /kolab/bin/python: double free or corruption (fasttop) References: <78edebdd-030f-4517-b9ed-5225511724d7@t39g2000prh.googlegroups.com> Message-ID: En Mon, 29 Dec 2008 04:12:02 -0200, Gabriel Genellina escribi?: > En Sun, 28 Dec 2008 12:10:06 -0200, aspineux > escribi?: > >> I got this. >> This is a test script, to help me to understand why I have unexpected >> result in application. >> But I got a more unexpected result, and probably wrong error message >> about the read-only cursor. > >> def server(): >> dbenv, db=init_db(read_only=False) >> >> update_thread=threading.Thread(target=lambda : cleanup(db)) >> update_thread.setDaemon(True) >> update_thread.start() > > I'd write it as > update_thread = threading.Thread(target=cleanup, args=(db,)) > or: > update_thread = threading.Thread(target=lambda db=db: cleanup(db)) > > The original code is creating a closure and I'm unsure how closures > interact with threads. Anyway, the crash should not happen, this may be a bug in Python or bsddb: http://bugs.python.org/ -- Gabriel Genellina From martin.hellwig at dcuktec.org Wed Dec 3 17:04:58 2008 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 03 Dec 2008 22:04:58 +0000 Subject: "as" keyword woes In-Reply-To: <493701f0$0$194$e4fe514c@news.xs4all.nl> References: <493701f0$0$194$e4fe514c@news.xs4all.nl> Message-ID: <4937028a$0$194$e4fe514c@news.xs4all.nl> Martin P. Hellwig wrote: > Warren DeLano wrote: >> A bottom line / pragmatic question... hopefully not a FAQ. >> >> Why was it necessary to make "as" a reserved keyword? > > Because it can be used at the import statement to let the imported thing > be known under another name? > Something like: > > >>> import xml.etree.ElementTree as ET > Sorry forget about the post, you know full well why not :-) -- mph From tino at wildenhain.de Thu Dec 18 09:14:34 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Thu, 18 Dec 2008 15:14:34 +0100 Subject: confused about __str__ vs. __repr__ In-Reply-To: References: Message-ID: <494A5ACA.8060205@wildenhain.de> Neal Becker wrote: > Reading some FAQ, I see that __str__ is "meant for human eyes". > > But it seems that: > class X(object): > def __str__(self): > return "str" > def __repr__(self): > return "repr" > > x = X() > d = {0 : x} > print d > {0: repr} > > So if __str__ is "meant for human eyes", then why isn't print using it! it is: > print x str but dict just uses repr() for all its childs to print. T. -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From tino at wildenhain.de Fri Dec 26 10:43:27 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Fri, 26 Dec 2008 16:43:27 +0100 Subject: =?ISO-8859-1?Q?Can=B4t_Surf_Python_Pages_in_Windoz?= =?ISO-8859-1?Q?e?= In-Reply-To: <4dc0cfea0812260701q6baf0ccbj154c5b3fa2281cdb@mail.gmail.com> References: <4dc0cfea0812260701q6baf0ccbj154c5b3fa2281cdb@mail.gmail.com> Message-ID: <4954FB9F.5050702@wildenhain.de> hi, Victor Subervi wrote: > Hi; > > I try to surf to this code in Windoze and it doesn't work...just posts a > small, black screen for a split second. Why? I don't know what "surf this code" means (or what Windoze should be) > print "Content-Type: text/html" > print > print """ > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> > > > > > Yeah > > """ this could be fine if called in CGI context. > Also, Zope is installed, but when I go to: > localhost:8080/manage_main > or > local:8080/Zope-Instance/manage_main > I get a 404, after having started the service and everything is go. I > have Python up. What gives? Don't know what "gives" but how did you make sure Zope could really start and bind the port? There are a lot things which could go wrong: Applications using this port already, firewall in your way... a 404 however indicates the service is there but you are not authorized. Please read "User and Permission" chapter in the zope book. Please note the above code you cited is not useable (or sensible) in a zope environment. Happy coding Tino > Victor > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From gagsl-py2 at yahoo.com.ar Tue Dec 30 19:00:24 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Dec 2008 22:00:24 -0200 Subject: Triple quoted string in exec function ? References: <495A253B.6010003@gmail.com> <495A81A7.8030507@gmail.com> Message-ID: En Tue, 30 Dec 2008 18:16:39 -0200, Stef Mientki escribi?: > ibpet11 at gmail.com wrote: >> the message Steven sent you is ok to explain how to work with triple >> quote >> > Yes, but not to work around my problem. > I guess I've to remove all triple quoted strings from my code. Why so? You only have to avoid repeating the *same* kind of triple quotes inside a triple quoted string literal. But you are free to use any other combination of ' and ", even include the surrounding triple quotes escape inside (escaping them with \) >>> x = """This is line 'one'. ... ''line "two" starts '''here ... and this is line three'' ... this last line contains \"\"\" too""" >>> print x This is line 'one'. ''line "two" starts '''here and this is line three'' this last line contains """ too With so much freedom I can't imagine what prevents you from using triple quoted strings. -- Gabriel Genellina From roy at panix.com Sat Dec 6 23:07:10 2008 From: roy at panix.com (Roy Smith) Date: Sat, 06 Dec 2008 23:07:10 -0500 Subject: Learning Python now coming from Perl References: <014a96e0$0$20670$c3e8da3@news.astraweb.com> Message-ID: In article , "Python Nutter" wrote: > At least if you push REs inform the readers where to get the a RE GUI > builder written in Python so they can build and *test* the complex and > unwieldy REs to perform anything beyond the basic pattern searches. Oh, my, I think my brain's about to explode. A RE GUI builder? Cough, gasp, sputter. This is literally the first time I've ever heard of such a thing, and it's leaving a bad taste in my mouth. RE is the last bastion of Real Programmers. Real Programmers don't use GUI builders. Using a GUI to build an RE is like trying to program by pushing little UMLish things around with a mouse. It's Just Wrong. From wuwei23 at gmail.com Tue Dec 2 10:10:22 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 2 Dec 2008 07:10:22 -0800 (PST) Subject: Checking a string against multiple matches References: <99a3a677-a38d-40f5-9a94-a98865150b69@k19g2000yqg.googlegroups.com> <200af09b-adba-4d8f-9ed9-2343030f9718@i24g2000prf.googlegroups.com> <376e669e-20b8-4734-a01e-e7a739362f8a@d23g2000yqc.googlegroups.com> Message-ID: <56eb7ee1-2801-4d7d-9e8e-af2bd5065c89@t39g2000prh.googlegroups.com> On Dec 2, 10:09?pm, Chris wrote: > On Dec 2, 3:01?am, alex23 wrote: > > The only time I'd expect it to do partial matches is if you were doing > > string.index(string), rather than list.index(string): > It would if the OP was iterating over the list and checking that item > with .index so it uses the string.index instead of list.index Which is what I was implying when I wrote "The only time I'd expect it to do partial matches is if you were doing string.index(string), rather than list.index(string)", oddly enough :) From grahn+nntp at snipabacken.se Mon Dec 8 16:47:27 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 8 Dec 2008 21:47:27 GMT Subject: how to get a beep, OS independent ? References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> <6q25utFa7km1U1@mid.uni-berlin.de> Message-ID: On 7 Dec 2008 14:46:53 GMT, Marc 'BlackJack' Rintsch wrote: > On Sun, 07 Dec 2008 07:17:30 -0700, Joe Strout wrote: > >> But invoking the standard system beep is such a basic function that it >> ought to be easier than this. I'm pretty sure it's a single OS call on >> all platforms. On OS X, for example, it's >> >> void NSBeep(void); >> >> declared in NSGraphics.h. I'm sure it's something similarly simple on >> other platforms. > > I'm not so sure. Under Unix the "system beep" is usually in the terminal > emulation and triggered by sending '\a' to it. Yes, and a terminal which prints a control character instead of beeping or flashing the screen, that's highly unusual. I think the poster tested this in some IDE with an "output window" rather than a real terminal. > AFAIK there is no standard beep in X-Windows There is, actually. It's called the bell, and it can be somewhat configured using xset(1). It's the single sound you can squeeze of a standard X server, and it's obviously modeled after the terminal bell. > so every desktop environment implements > something like audio notifications. KDE and Gnome might, but mine doesn't. Things vary so much on Unix. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From esgameserver at gmail.com Thu Dec 4 02:23:57 2008 From: esgameserver at gmail.com (esgameserver at gmail.com) Date: Wed, 3 Dec 2008 23:23:57 -0800 (PST) Subject: Python Dynamic Profiling Message-ID: Hi, Sorry for re-posting but I want to clarify my question again here. So, we have a multithreaded server application and I want to see the profile of our code means which function is executed how many times and time spent in that function dynamically. With dynamic, I mean without stopping the profiled thread. Is there any way to do that, other than hacking my own code with hooks and calculating the info above by hand? P.S:cProfile and Profile modules are very good indeed, but as far as I understand you need to stop the profiler and the associated thread to see the profile results. That is unacceptable for my situation. Thanks, From timr at probo.com Wed Dec 31 02:31:11 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 31 Dec 2008 07:31:11 GMT Subject: Cheetah References: Message-ID: sopherfish at gmail.com wrote: > >1. In Cheetah 2.0.1, both from python 2.5.2 and 2.6, after I do a >#from datetime import date, most of the datetime objects seem to work >fine. For example, $date(2008, 12, 15) works. However $date.today() >does not work and I get an exception required argument year not found. >In Python both 2.5.2 and 2.6 (without Cheetah), the today() works >fine. For some reason, though, it does not work from Cheetah. Show us the EXACT code and the EXACT error. >2. In reportlab 2.2, when I generate a PDF, no matter how many  s >I put it, I only get one space. I am using it with python 2.6. The PDF >generates fine and one $nbsp works, but for some reason, when I put it >in multiple times, I still only get one space. Well, you've spelled it two ways here, and neither way is correct. It's spelled   with an ampersand before and a semicolon after. Again, show us a complete, runnable example and we can check it out. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From stefan_ml at behnel.de Sun Dec 7 02:51:11 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 07 Dec 2008 08:51:11 +0100 Subject: Don't you just love writing this sort of thing :) In-Reply-To: References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: <493b806f$0$31336$9b4e6d93@newsspool4.arcor-online.net> Lawrence D'Oliveiro wrote: > In message , Arnaud Delobelle wrote: > >> * you seem to disregard the fact that in 'programming language' there >> is the word 'language'. A language is a way to _communicate_ >> information, in the case of a programming language you communicate >> it to the computer but also to other human beings. > > It was Niklaus Wirth, I think who pointed out that programming languages are > not properly "languages" but are actually "notations". Like mathematics is > a notation. > > And mathematics, too, is a predominantly functional, not a procedural, > notation. Could that be why so many people are frightened of functional > constructs, like my code example and things like lambdas? Because they look > too much like mathematics? That's not the impression I got from reading this thread. Stefan From sjmachin at lexicon.net Thu Dec 25 08:21:03 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 25 Dec 2008 05:21:03 -0800 (PST) Subject: SyntaxError: encoding problem: with BOM References: <6res8tF1do1sU1@mid.uni-berlin.de> <400f176b-bd9a-4f26-b01b-1aa7c7dcf5ac@z6g2000pre.googlegroups.com> <6rf6m1F1e0f8U1@mid.uni-berlin.de> Message-ID: On Dec 25, 11:36?pm, NoName wrote: > On 25 ???, 03:35, "Diez B. Roggisch" wrote: > > > > > NoName schrieb: > > > > On 25 ???, 00:37, "Diez B. Roggisch" wrote: > > >> NoName schrieb: > > > >>> i have 1.py in cp866 encoding: > > >>> # -*- coding: cp866 -*- > > >>> print ("ff") > > >>> It's not work in Python 3.0 > > >>> Error: > > >>> File "", line 1 > > >>> SyntaxError: encoding problem: with BOM > > >>> what's wrong? > > >> I can only guess, but just because you write the coding-header that > > >> doesn't mean that the editor you use does actually *use* that encoding. > > >> What I presume it does is to use utf-8, and write that stupid BOM > > >> microsoft uses for denoting utf-8-content as first byte. Try using a > > >> different editor, or alter it's settings to really use your desired > > >> encoding. > > > >> Diez > > > > I used Far Manager editor. and it *really* used cp866 > > > I can print hex dump of source file. > > > I don't want to use UTF-8 for py-file! > > > How about you show us the python file in question? > > > diez > > you can get it here http://slil.ru/26481345 NoName, Asking people to download a zip file from a website written in a language and character set that they probably are not familiar with is liable to make them rather nervous and not bother. It's not a good way to ask for help. All you had to do was display the file contents unambiguously, like this: C:\downloads>\python30\python Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> open('11.py', 'rb').read() b"# -*- coding: cp866 -*- \r\nprint('test')" >>> ^Z So, there's nothing very remarkable there ... a trailing space on the end of the first line, the second line is not terminated by \r\n, no non-ASCII characters in the file, ... nothing that might cause Python to give you a syntax error. ... and it doesn't give a syntax error: C:\downloads>\python30\python 11.py test If you still maintain that you are getting the syntax error mentioned in your first posting, please construct a file that causes the error to happen on your machine (what type of machine? what OS are you using?) and show (like I did above) firstly what is in the file and secondly what happens when you run it. No hex editors, no websites, no zip files, just plain Python like I did. From martin at v.loewis.de Sun Dec 14 18:42:05 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 15 Dec 2008 00:42:05 +0100 Subject: Python 3.0 crashes displaying Unicode at interactive prompt In-Reply-To: <89022013-f7f6-4779-849f-b36fe618104e@r15g2000prh.googlegroups.com> References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> <49443531.5050304@v.loewis.de> <49448FC2.6030306@v.loewis.de> <494576DD.1050505@v.loewis.de> <89022013-f7f6-4779-849f-b36fe618104e@r15g2000prh.googlegroups.com> Message-ID: <494599CD.3030408@v.loewis.de> > It's unfortunate that the default behaviour isn't > optimal at the interactive prompt for some configurations, though. As I said, it's a trade-off. The alternative, if it was the default, wouldn't be optimal at the interactive prompt for some other configurations. In particular, users of non-latin scripts have been complaining that they can't read their strings - hence the change, which now actually allows these users to read the text that is stored in the strings. The question really is why John Machin has a string that contains '\u9876' (which is a Chinese character), yet his terminal is incapable of displaying that character. More likely, people will typically encounter only characters in their data that their terminals are also capable of displaying (or else the terminal would be pretty useless) In the long run, it might be useful to have an error handler on sys.stdout in interactive mode, which escapes characters that cannot be encoded (perhaps in a different color, if the terminal supports colors, to make it clear that it is an escape sequence) Regards, Martin From mal at egenix.com Thu Dec 18 18:02:29 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 19 Dec 2008 00:02:29 +0100 Subject: psycopg2 and large queries In-Reply-To: <494AC077.2060605@shopzeus.com> References: <762eed9d-4646-4c62-a9b7-d57d47f03b9e@e1g2000pra.googlegroups.com> <494AC077.2060605@shopzeus.com> Message-ID: <494AD685.7010009@egenix.com> On 2008-12-18 22:28, Laszlo Nagy wrote: > >> Well, there are plenty of PostgreSQL modules around these days, and >> even if pyPgSQL isn't suitable, I'm sure that there must be one which >> can be made to work on Windows and to support server-side cursors. See >> here for more: >> >> http://wiki.python.org/moin/PostgreSQL >> > I'm just looking for something that can replace psycopg2, because of the > bug mentioned in my original post. Here are my options: > > - psycopg1: development stalled > - psycopg2: memory bug and/or not db api compilant (see my original post) > - pyPgSQL: looks like that the last release was in mid 2006 (and it > depends on mxDateTime -> licensing problems) mxDateTime is open-source, just like everything you find in our eGenix mx Base distribution: http://www.egenix.com/products/python/mxBase/ mxODBC and mxODBC Connect are commercial products, work well with PostgreSQL and are actively maintained: http://www.egenix.com/products/python/ Why not give them a try ? -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 18 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-12-02: Released mxODBC.Connect 1.0.0 http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From stef.mientki at gmail.com Fri Dec 26 08:05:15 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 26 Dec 2008 14:05:15 +0100 Subject: Is there a function to remove escape characters from a string ? In-Reply-To: References: <0163882f$0$6988$c3e8da3@news.astraweb.com> Message-ID: <4954D68B.5080900@gmail.com> >> I have the following kind of strings, >> the funny "?" is ASCII character 254, used as a separator character >> > > ASCII ends at 127. Just refer to it as chr(254). > > note 1) >> [FSM] >> Counts = "1?11?16" ==> 1,11,16 >> Init1 = "1?\BCtrl" ==> 1,Ctrl >> State5 = "8?\BJUMP_COMPL\b\n>PCWrite = 1\n>PCSource = 10" >> ==> 8, JUMP_COMPL\n>PCWrite = 1\n>PCSource = 10 >> > > After making those substitutions, what are you going to do with it? > Split it up into fields using the csv module or stuff.split(",") or > some other DIY method? Is there a possibility that whoever "designed" > that data format used chr(254) as a separator because the data fields > contained "," sometimes and so "," could not be used as a separator? > > Yep, chr(254), because it's not in the human range of characters and it's accepted by windows ini-files. >> Seeing and testing all your answers, with great solutions that I've >> never seen before, >> > > As far as str methods and built-ins that work on str objects are > concerned, there is no corpus of secret knowledge known only to a > cabal of wizards; it's all in the manual, and you don't need special > magical spectacles to see it :-) > > note 2) >> knowing nothing of escape sequences (I'm a windows guy ;-) >> > > Why do you think that whether or not you are a "windows guy" is > relevant to knowing anything about escape sequences? > > Just a windows guy, or maybe better, "being a windows guy for many years", windows users are wysiwyg users, they are not dealing with individual bits. I personally left escape sequences and values of ASCII characters behind me more than 25 years ago. And now maybe you might understand note 1) and note 2) . cheers, Stef From Lie.1296 at gmail.com Sun Dec 7 01:17:12 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 6 Dec 2008 22:17:12 -0800 (PST) Subject: Guido's new method definition idea References: <493abe2e$0$15998$426a34cc@news.free.fr> Message-ID: <62bcfe49-bee6-4348-8ec9-8ab85132c8ff@40g2000prx.googlegroups.com> On Dec 7, 1:02?am, News123 wrote: > What would be interesting would be some syntactical sugar to get rid of > the 'self' (at least in the code body). > > example: > class C: > ? ? class_elements a,b,c,d > > ? ? def method(self,arg): > ? ? ? ? global d > ? ? ? ? a,b,c = arg[0..3] > ? ? ? ? d = a + b > ? ? ? ? self.e = a + d > Nah, that would make it not explicit. Explicit here also means that to refer to self's a, we need to explicitly refer to self. From cjw at ncf.ca Fri Dec 19 19:38:33 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Fri, 19 Dec 2008 19:38:33 -0500 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <6r25ckFejl4vU1@mid.individual.net> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> <6r25ckFejl4vU1@mid.individual.net> Message-ID: Thomas Heller wrote: > Steve Holden schrieb: >> Thomas Heller wrote: >>> Question from a non-native english speaker: is this now valid english? >>> >>> "One of Python???s great strengths" >>> ^ >>> "and also teaches Python???s functional programming features" >>> ^ >>> "The book???s approach is wholly practical" >>> ^ >> It always has been valid English. The apostrophe is only omitted from >> personal pronouns (hers, its, and so on). > > I see, thanks. But, is the apostrophe optional in the above fragments? > > Thomas Whoops. I read the first two lines as one sentence. Thomas Heller was questioning the possessive. I don't see any problem with the three examples he gives. Colin W. From invalid at invalid Tue Dec 16 10:43:38 2008 From: invalid at invalid (Grant Edwards) Date: Tue, 16 Dec 2008 09:43:38 -0600 Subject: alt.possessive.its.has.no.apostrophe References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> <9ImdneOohuZCNdvUnZ2dnUVZ_s3inZ2d@earthlink.com> Message-ID: On 2008-12-16, Hendrik van Rooyen wrote: > "Dennis Lee Bieber" wrote: > > 8<----- stuff blaming Davy for "aluminum" ---------- > >> Isn't Davy a Brit? > > No, he was a Brit. > He's dead now. > His safety lamp lives on. > It's a good thing its got that heat-sink sieve- should be "it's got" (contracted form of "it has got"). > it's enabled countless miners > to flee when they see its change of colour. > Thus it's saved the lives of a lot of canaries, > and that's of ecological importance. > > Spot the apostrophe error, if you can. -- Grant Edwards grante Yow! RHAPSODY in Glue! at visi.com From clp at rebertia.com Mon Dec 1 16:21:31 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 1 Dec 2008 13:21:31 -0800 Subject: Is it safe to modify the dict returned by vars() or locals() In-Reply-To: <4934508b$0$2861$ba620e4c@news.skynet.be> References: <4934508b$0$2861$ba620e4c@news.skynet.be> Message-ID: <47c890dc0812011321h66f4309cya7a750b169d994ca@mail.gmail.com> On Mon, Dec 1, 2008 at 1:01 PM, Helmut Jarausch wrote: > Hi, > > I am looking for an elegant way to solve the following problem: > > Within a function > > def Foo(**parms) > > I have a list of names, say VList=['A','B','C1'] > and I like to generate abbreviation > _A identical to parms['A'] Could you explain what you mean by that? Your sample code doesn't seem to do any "abbreviation"... Otherwise I don't see why you don't just have a proper parameter list. > > for that I could write > > def Foo(**parms) : > for N in VList : > if N in parms : > vars()[N]= parms[N] > else : > vars()[N]= None > > Does this work, is it typical Python? >From the docs (http://docs.python.org/library/functions.html): locals() Update and return a dictionary representing the current local symbol table. *Warning*: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter. Free variables are returned by locals() when it is called in a function block. Modifications of free variables may not affect the values used by the interpreter. Free variables are not returned in class blocks. As the warning states, it modifying the dict doesn't really work (except at the module level, but that's an implementation detail IIRC) For example: >>> def foo(): ... a = 3 ... l = locals() ... l['a'] = 5 ... print a ... >>> foo() 3 In any case, it'd be considered a bit of a hack. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Many thanks for a hint, > Helmut. > > -- > Helmut Jarausch > > Lehrstuhl fuer Numerische Mathematik > RWTH - Aachen University > D 52056 Aachen, Germany > -- > http://mail.python.org/mailman/listinfo/python-list > From ibpet11 at gmail.com Tue Dec 30 05:37:46 2008 From: ibpet11 at gmail.com (ibpet11 at gmail.com) Date: Tue, 30 Dec 2008 02:37:46 -0800 (PST) Subject: using def in pythons Message-ID: <235ffe4b-9f36-4d41-bee8-24cb4a69728d@q30g2000prq.googlegroups.com> hi, i want to have a broad knowledge on the use of "def" in python as i know i might need it to my string handling and for a lot of things in general. I will really appreciate anybody who can support my mission of becoming a python Programmer as per constant chatting and support or manuals to read. thanks From prologic at shortcircuit.net.au Sun Dec 14 04:23:49 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Sun, 14 Dec 2008 19:23:49 +1000 Subject: XMPP xmpppy - User Authorization In-Reply-To: <66b3831b-b26d-4ce9-80b2-e0e8c85ecbc4@k9g2000vbl.googlegroups.com> References: <66b3831b-b26d-4ce9-80b2-e0e8c85ecbc4@k9g2000vbl.googlegroups.com> Message-ID: On Sun, Dec 14, 2008 at 3:47 PM, Henson wrote: > In my own bot, using the latest xmpppy, I've been printing everything > going to the message handler to the screen. I've yet to see a > 'subscribe' string. Has this changed? No this hasn't changed. This is the string you need to check for. It does work :) cheers James > -- -- "Problems are solved by method" From christophedeze at gmail.com Mon Dec 22 11:22:51 2008 From: christophedeze at gmail.com (Toff) Date: Mon, 22 Dec 2008 08:22:51 -0800 (PST) Subject: join a samba domain References: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> Message-ID: <5428c77b-ed4f-49ec-a808-dccd77a2a01c@g3g2000pre.googlegroups.com> On 22 d?c, 17:02, Tim Golden wrote: > Toff wrote: > > hi, > > > I 'm trying to write a script to make my computer join a samba. > > > domeone have any idea ?? > > Ummm. It's not clear if you're saying that your code doesn't > work, or asking for general advice, or what? I'm not in a > position to have my machine join a domain or workgroup, but > you seem to have got most things in place already. The only > thing I would expect to have to change is this last line: > > > ? ?import wmi > > ? ?c = wmi.WMI() > > ? ?d = c.Win32_ComputerSystem > > ? ?d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") > > because the d is only a WMI *class*, not a WMI *instance*, > so doesn't refer as it should to your computer system but > to the class of computer systems. Try something like this (untested): > > > import wmi > > c = wmi.WMI () > for d in c.Win32_ComputerSystem (): > ? d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") > > > > TJG thanks but it doesn't work I've got this errors Traceback (most recent call last): File "integrdom.py", line 51, in main() File "integrdom.py", line 13, in main joindom() File "integrdom.py", line 44, in joindom d.JoinDomainOrWorkGroup(None, 3, "domcd", "adminLocal", r"admin \domcd") File "c:\Python25\Lib\site-packages\wmi.py", line 493, in __getattr__ handle_com_error (error_info) File "c:\Python25\Lib\site-packages\wmi.py", line 189, in handle_com_error raise x_wmi, "\n".join (exception_string) wmi.x_wmi From martin at v.loewis.de Sun Dec 7 04:20:14 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 07 Dec 2008 10:20:14 +0100 Subject: Number of Python 3.x packages at the PyPI In-Reply-To: <9c1ab0f3-6686-4c0f-8a6c-12e20539f354@41g2000yqf.googlegroups.com> References: <9c1ab0f3-6686-4c0f-8a6c-12e20539f354@41g2000yqf.googlegroups.com> Message-ID: <493b954e$0$4021$9b622d9e@news.freenet.de> excord80 at gmail.com wrote: > Is there an easy way to see the number of PyPI packages which have > been ported to Python 3? Yes: browse all pacakges classified with Programming Language :: Python :: 3 You can find them at http://pypi.python.org/pypi?:action=browse&c=533 It seems that some package authors only classify with Programming Language :: Python :: 3 > Are there any special arrangements necessary for PyPI packages which > have both a Python 2.x version and a Python 3.x version? So far, no such need has been identified. Regards, Martin From google at mrabarnett.plus.com Sat Dec 6 11:50:24 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 06 Dec 2008 16:50:24 +0000 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: References: <55d79070-0c11-4fb9-8cf5-b8cc7c54b5d2@v42g2000yqv.googlegroups.com> Message-ID: <493AAD50.4050904@mrabarnett.plus.com> Johannes Bauer wrote: > info at orlans-amo.be schrieb: > >> 2 problems: endianness and trailing zer byte. >> This works for me: > > This is very strange - when using "utf16", endianness should be detected > automatically. When I simply truncate the trailing zero byte, I receive: > > Traceback (most recent call last): > File "./modify.py", line 12, in > a = AddressBook("2008_11_05_Handy_Backup.txt") > File "./modify.py", line 7, in __init__ > line = f.readline() > File "/usr/local/lib/python3.0/io.py", line 1807, in readline > while self._read_chunk(): > File "/usr/local/lib/python3.0/io.py", line 1556, in _read_chunk > self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) > File "/usr/local/lib/python3.0/io.py", line 1293, in decode > output = self.decoder.decode(input, final=final) > File "/usr/local/lib/python3.0/codecs.py", line 300, in decode > (result, consumed) = self._buffer_decode(data, self.errors, final) > File "/usr/local/lib/python3.0/encodings/utf_16.py", line 69, in > _buffer_decode > return self.decoder(input, self.errors, final) > UnicodeDecodeError: 'utf16' codec can't decode byte 0x0a in position 0: > truncated data > > But I suppose something *is* indeed weird because the file I uploaded > and which did not yield the "truncated data" error ia 1559 bytes, which > just cannot be. > It might be that the EOF marker (b'\x1A' or u'\u001A') was written or is being read as a single byte instead of 2 bytes for UTF-16 text. From bearophileHUGS at lycos.com Tue Dec 16 12:28:09 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 16 Dec 2008 09:28:09 -0800 (PST) Subject: Does Python3 offer a FrozenDict? References: Message-ID: Johannes Bauer: > is there anything like a frozen dict in Python3, so I could do a > foo = { FrozenDict({"a" : "b"}): 3 } You can adapt this code to Python3 (and post a new recipe? It may be positive to create a new section of the Cookbook for Py3 only): http://code.activestate.com/recipes/414283/ Please remember that Py3 is very new, so 99% of the stuff present for Py2.x is absent. Using Py3 is your choice. Bye, bearophile From excord80 at gmail.com Sat Dec 6 22:56:10 2008 From: excord80 at gmail.com (excord80 at gmail.com) Date: Sat, 6 Dec 2008 19:56:10 -0800 (PST) Subject: Number of Python 3.x packages at the PyPI Message-ID: <9c1ab0f3-6686-4c0f-8a6c-12e20539f354@41g2000yqf.googlegroups.com> Is there an easy way to see the number of PyPI packages which have been ported to Python 3? Are there any special arrangements necessary for PyPI packages which have both a Python 2.x version and a Python 3.x version? From wodemoneke at gmail.com Sun Dec 14 09:21:16 2008 From: wodemoneke at gmail.com (Daniel Woodhouse) Date: Sun, 14 Dec 2008 16:21:16 +0200 Subject: changing string encoding to different charset? Message-ID: <4c0a037d0812140621j5d4f4d47mb4a3097586bacac5@mail.gmail.com> Is it possible to re-encode a string to a different character set in python? To be more specific, I want to change a text file encoded in windows-1251 to UTF-8. I've tried using string.encode, but get the error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 0: ordinal not in range(128) -------------- next part -------------- An HTML attachment was scrubbed... URL: From fetchinson at googlemail.com Thu Dec 4 12:30:52 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 4 Dec 2008 09:30:52 -0800 Subject: RELEASED Python 3.0 final In-Reply-To: <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> Message-ID: >> As you have probably guessed: nothing changed here. >> Also see:http://www.python.org/dev/peps/pep-0666/ > > What? Do you mean it's possible to mix tabs and spaces still? Why? Why not? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From rdmurray at bitdance.com Tue Dec 16 18:59:31 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Tue, 16 Dec 2008 23:59:31 +0000 (UTC) Subject: eval() and global variables References: Message-ID: Quoth "=?ISO-8859-1?Q?Juan_Pablo_Romero_M=E9ndez?=" : > Hello, > > Suppose this function is given: > > def f(x,y): > return x+y+k > > Is it possible to somehow assign a value to k without resorting to > making k global? > > I'm thinking something like this: > > eval("f(1,1)", {"f":f, "k":1}) > > Or even better, something like: > > def g(k): > return f > > g(1)(1,1) ==> 3 >>> def g(k): ... def f(x,y): ... return x+y+k ... return f ... >>> g(1)(1,1) 3 But what's the use case? The above might not satisfy it. --RDM From rt8396 at gmail.com Mon Dec 22 16:09:13 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 13:09:13 -0800 (PST) Subject: I always wonder ... References: Message-ID: <4b1d5c89-166e-415f-8bb4-b8d5a4089368@h20g2000yqn.googlegroups.com> On Dec 22, 2:31?pm, s... at pobox.com wrote: > ? ? Carl> ...shouldn't poeple who spend all their time following up to > ? ? Carl> trolls, or starting new threads about trolls, being doing > ? ? Carl> something else? > > Sure. ?It was just a momentary break from work, as is this. ?I thought an > implied smiley was enough, but I guess not. > > Skip Pythonic.explicit_smiley() -> :) From rt8396 at gmail.com Mon Dec 22 13:01:21 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 10:01:21 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> Walter, I just look at the stats for comp.lang.python, and i am 9th place for most post this month. That makes me completely sad. With just 50 post so far, i am showing up on the high count. Sad, very sad. Now i have much reason to believe that only 100 or so people follow this list :(. Python is slipping. We must try harder, or all of Guido's work will be for nothing! From martin at v.loewis.de Mon Dec 8 20:08:19 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 09 Dec 2008 02:08:19 +0100 Subject: how to add command line flags to distutils setup script? In-Reply-To: References: Message-ID: <493dc504$0$21190$9b622d9e@news.freenet.de> skip at pobox.com wrote: > Suppose I have a setup.py script which imports distutils.core.setup. Is > there some way to, for example, add a command line flag to the build command > so that I can run it like > > python setup.py build --frob=True > > ? You should inherit from the build command, extend the user_options attribute, and pass the new class as "build" class into the commands dictionary of setup. You might need to extend initialize_options and finalize_options as well. Regards, Martin From xahlee at gmail.com Wed Dec 10 19:51:00 2008 From: xahlee at gmail.com (Xah Lee) Date: Wed, 10 Dec 2008 16:51:00 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> Message-ID: <5ebe5a7d-cbdf-4d66-a816-a7d2a0a273c9@40g2000prx.googlegroups.com> On Dec 10, 2:47?pm, John W Kennedy wrote: > Xah Lee wrote: > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, > > you'll have 50 or hundreds lines. > > C: > > #include > #include > > void normal(int dim, float* x, float* a) { > ? ? float sum = 0.0f; > ? ? int i; > ? ? float divisor; > ? ? for (i = 0; i < dim; ++i) sum += x[i] * x[i]; > ? ? divisor = sqrt(sum); > ? ? for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; > > } > > Java: > > static float[] normal(final float[] x) { > ? ? float sum = 0.0f; > ? ? for (int i = 0; i < x.length; ++i) sum += x[i] * x[i]; > ? ? final float divisor = (float) Math.sqrt(sum); > ? ? float[] a = new float[x.length]; > ? ? for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor; > ? ? return a; > > } Thanks to various replies. I've now gather code solutions in ruby, python, C, Java, here: ? A Example of Mathematica's Expressiveness http://xahlee.org/UnixResource_dir/writ/Mathematica_expressiveness.html now lacking is perl, elisp, which i can do well in a condensed way. It'd be interesting also to have javascript... and perhaps erlang, OCaml/F#, Haskell too. Xah ? http://xahlee.org/ ? From castironpi at gmail.com Tue Dec 16 15:17:09 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 16 Dec 2008 12:17:09 -0800 (PST) Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> Message-ID: On Dec 16, 4:15?am, "Gabriel Genellina" wrote: > En Tue, 16 Dec 2008 07:29:19 -0200, Aaron Brady ? > escribi?: > > > I have a file handle I want to inherit in a child process. ?I am > > looking at '_make_inheritable' in 'Popen', but it needs an instance, > > and by the time I have one, the subprocess is already running. > > > Can't I call 'Popen._make_inheritable( None, handle )'? ?The method > > does not use 'self'. > > File handles are inherited by default, I think. What's your specific ? > problem? > > -- > Gabriel Genellina I want a dual-console application for some multi-threaded output. The main process spawns a second process in a second window, and directs its readout through a pipe. That is, the second process is just a dummy, print pipe directly to console. It worked when I used the 'stdin= PIPE' keyword in Popen, but passing my own pipe handle on the command line isn't working. The keyword is a workaround. > File handles are inherited by default, I think. I thought so too. The web seems to say that on Linux they are, and on Windows, you need to call DuplicateHandle for it. By the way, there are a few solutions to the inheritance problem. 1. Override __init__ and __del__ in a subclass. 2. Assign DummyClass= Popen._make_inheritable 3. Override Popen._execute_child to call _make_inheritable, then call the super method. From luismgz at gmail.com Thu Dec 11 07:06:19 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Thu, 11 Dec 2008 04:06:19 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: <9e0bb906-e019-45ef-8047-b33982c7c5ad@l39g2000yqn.googlegroups.com> On Dec 10, 3:42?pm, cm_gui wrote: > http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-... > > I fully agree with Krzysztof Kowalczyk . > Can't they build a faster VM for Python since they love the language > so much? > > Python is SLOW. ? ?And I am not comparing it with compiled languages > like C. > Python is even slower than PHP! > > Just go to any Python website and you will know. > An example is:http://www2.ljworld.com/ > And this site is created by the creators of Django! > > And it is not just this Python site that is slow. There are many many > Python sites which are very slow. And please don?t say that it could > be the web hosting or the server which is slow ? because when so many > Python sites are slower than PHP sites, it couldn?t be the web > hosting. ? Also, Zope/Plone is even slower. > > Python is slow. Very slow. Now seriously, just to finish your idiotic rant, check the Pypy project: http://codespeak.net/pypy http://morepypy.blogspot.com And if you still think this is not enough, why don't you help these guys to make it faster? Luis From dullrich at sprynet.com Tue Dec 2 12:13:21 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 02 Dec 2008 11:13:21 -0600 Subject: newbie question References: Message-ID: In article , Nan wrote: > Hello, > I just started to use Python. I wrote the following code and > expected 'main' would be called. > > def main(): > print "hello" > > main > > But I was wrong. I have to use 'main()' to invoke main. The python > interpreter does not give any warnings for the above code. Is there > any way/tool to easily detect this kind of errors ? It's valid Python - it's only an error because it doesn't do what you want. The reason you're required to include the parentheses with a function call is that in Python there are _other_ things you might want to do with a function other than call it. For example you can pass a function as a parameter to another function. Silly example: def twice(f): f() f() def main(): print 'hello' twice(main) Before trying it, figure out what would happen if you said twice(main()) . A slightly more interesting example: twice(f) simply calls f twice. double(f) returns a new function; when you call that new function it calls f twice: def double(f): def res(): f() f() return res def main(): print 'hello' The point being that this example shows how sometimes you want those parentheses and sometimes you don't. Either one of the following is a way to call main twice: mainmain = double(main) mainmain() or double(main)() When I said mainmain = double(main) I left off the final parentheses because I didn't want to call mainmain just then, I just wanted to set mainmain to the right thing. > Thanks ! -- David C. Ullrich From philip at semanchuk.com Mon Dec 8 10:05:52 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Mon, 8 Dec 2008 10:05:52 -0500 Subject: Best way to run multiple Python processes without overloading CPU or disk i/o In-Reply-To: References: <1228278090.29785.1287948757@webmail.messagingengine.com> Message-ID: <2F6BC7BC-5B5F-47DE-B323-99A3DA907999@semanchuk.com> On Dec 8, 2008, at 2:48 AM, Gabriel Genellina wrote: > En Wed, 03 Dec 2008 02:29:32 -0200, Philip Semanchuk > escribi?: > >> >> On Dec 2, 2008, at 11:21 PM, python at bdurham.com wrote: >> >>> Is there a cross-platform way to launch multiple Python processes >>> and monitor CPU usage >> >> os.getloadavg() might be useful. It certainly works on *nix, don't >> know about Windows. The documentation doesn't mention any platform >> limitations. > > ....apart from saying "Availability: Unix."? :) Which just goes to show that Python is improving all the time. That's a fix that's present in the 2.6 documentation. I have 2.5 installed, and "Availability: Unix" is not in that doc: http://www.python.org/doc/2.5/lib/os-path.html#l2h-2791 From tino at wildenhain.de Thu Dec 18 09:36:01 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Thu, 18 Dec 2008 15:36:01 +0100 Subject: confused about __str__ vs. __repr__ In-Reply-To: References: <494A5ACA.8060205@wildenhain.de> Message-ID: <494A5FD1.9050406@wildenhain.de> Neal Becker wrote: ... >>> So if __str__ is "meant for human eyes", then why isn't print using it! >> it is: >> >> > print x >> str >> >> but dict just uses repr() for all its childs to print. >> >> T. > That makes no sense to me. If I call 'print' on a container, why wouldn't it recursively print on the contained objects? Since print means call str, printing a container should recursively call str on the objects. Every class is free on how to best implement __str__, you will find the same behavior on tuple and list as well. Maybe its discussable to change the implementation sensibly, best if you would come with a proposal? Perhaps pprint.pprint is a starting point? Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From jay.amorin at gmail.com Wed Dec 3 13:25:32 2008 From: jay.amorin at gmail.com (Jay Jesus Amorin) Date: Thu, 4 Dec 2008 02:25:32 +0800 Subject: python to parse excel file csv format Message-ID: Hi all, Can anyone please help me. i need to parse the content of my csv excel file and run the unix command chown. test.csv: "/dev/trunk/admin/sql/ADBPOS_CMSI_NATIONALITY.syn",814 "/dev/trunk/bin/ADBPOSCMSDICED.ctl",405 "/dev/trunk/discoverer/ADBPOS_BUSINESS_AREA.eex",215 Please help me parse the csv file and run chown $csvfile_secondcolumn $csvfile_firstcolumn. Here's how i want to run it. ./parsecsv.py test.csv Many thanks. Jay -------------- next part -------------- An HTML attachment was scrubbed... URL: From scottm45810 at hotmail.com Sat Dec 27 17:06:03 2008 From: scottm45810 at hotmail.com (scott) Date: Sat, 27 Dec 2008 14:06:03 -0800 Subject: Python 3 and my Mac (Leopard) In-Reply-To: <4952b38d$0$20300$607ed4bc@cv.net> References: <4952b38d$0$20300$607ed4bc@cv.net> Message-ID: Dan wrote: > Wanted to learn python, got Mark Summerfield's new book "Programming in > Python 3". Having a hard time getting python 3 and IDLE working on my > Mac with Leopard. The mac "resources" on the python.org site seem a bit > out of date, and don't really mention python 3. Are there any resources > out there? Is the python community just not interested in Macs? I've > tried googling and the usual search strategies. Any help would be > appreciated. > > DAN > Activestate has a Python 3.0 distribution for 8 or 9 platforms including Mac OS X: http://www.activestate.com/Products/activepython/python3.mhtml IDLE works well here on Leopard (calltips etc) and they have bundled documentation in Apple help format. Note: I installed ActiveTcl prior to installing Python 3.0: http://www.activestate.com/Products/activetcl/index.mhtml I'm not sure if this was necessary for proper IDLE function or not. Both ActivePython 3.0 and ActiveTcl installs were painless. From prologic at shortcircuit.net.au Mon Dec 15 03:35:58 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 15 Dec 2008 18:35:58 +1000 Subject: Python is slow In-Reply-To: <20081215082616.1de76e92@andi-lap> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <20081215082616.1de76e92@andi-lap> Message-ID: On Mon, Dec 15, 2008 at 5:26 PM, Andreas Kostyrka wrote: > So to summarize, Python is fast enough for even demanding stuff, and > when done correctly even number crunching or binary parsing huge files > or possible in competitive speeds. But you sometime need a developer > that can wield the tool with a certain experience, and not a stupid > rookie that whines that his tool does not make his O(n**n) algorithm > automatically blazing fast. Amen! +10 --JamesMills From de.slotenzwemmer at gmail.com Thu Dec 25 07:11:09 2008 From: de.slotenzwemmer at gmail.com (Dennis van Oosterhout) Date: Thu, 25 Dec 2008 13:11:09 +0100 Subject: os.system('cls') In-Reply-To: References: <05BADA85-33ED-48BF-B251-2CC830D6D55E@rgbaz.eu> Message-ID: Btw...does that mean that system('cls') only works on Windows...or to say it otherwise: the program isn't platform independant? 2008/12/25 Dennis van Oosterhout : > Hello Arno, > > thanks for the explanation! I have one more question: on the python > site it says it's better to replace the system commands by subprocess > and Popen. > Now I searched for some good example for my specific case (as I have > no idea how it should work and I don't get it any clearer by reading > http://docs.python.org/3.0/library/subprocess.html#module-subprocess) > and I found this: > >> import subprocess >> def clear(): >> subProcess.Popen('clear') > > But it just doesn't seem to work. Would you have any idea how it would work? > > Once more thanks for the first answer, > > Devilly > > > 2008/12/25 Python >> >> On 25 dec 2008, at 11:22, Dennis van Oosterhout wrote: >> >>> Hi there! I was searching for a way to clear the 'DOS screen'/command screen etc. and found that os.system('cls') works for this. I was just wondering where I can find al the commands which can be used for os.system(). I searched with google but I didn't find an answer. In the official python tutorial it says os.system('command') executes the command, but it doesn't say which commands exist (or I'm just blind). >>> >>> Does anyone have an answer for this question? >>> >>> Thanks, >>> >>> Devilly >> >> Hey Deville, >> >> >> os.system() executes commands that you usually use in a shell outside python. >> so in the case of you being a windows user, you replace 'command' with any DOS >> command. >> >> gr >> Arno > From mareksp.92 at gmail.com Mon Dec 15 12:51:49 2008 From: mareksp.92 at gmail.com (Marek_SP) Date: Mon, 15 Dec 2008 09:51:49 -0800 (PST) Subject: Structure using whitespace vs logical whitespace References: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> Message-ID: <5079101b-d477-4127-b595-1f1eb50740cf@y1g2000pra.googlegroups.com> On 15 Gru, 18:14, MRAB wrote: > cmdrrickhun... at yaho.com wrote: > > I've been trying to search through the years of Python talk to find an > > answer to this, but my Googlefu is weak. > > > In most languages, I'll do something like this > > > xmlWriter.BeginElement("parent"); > > ----xmlWriter.BeginElement("child"); > > ----------xml.Writer.Characters("subtext"); > > ----xmlWriter.EndElement(); > > xmlWriter.EndElement(); > > > Where the dashes are indentation (since some newsgroup handlers don't > > do tabs well). ?XML writing is just an example. > > > In general, I'm using indentation to show logical flow through code. > > Python's choice to give semantic meaning to whitespace prevents me > > from doing such things. ?What was once reserved for logical use is now > > used syntactically. ?In 90% of cases, its not needed, and whitespace > > significance seems to be pretty effective. ?In that last 10%, however, > > I've been frustrated many times. > > > I've been using python for a few years, and gotten around this in one > > way or another, but now I want to get other who work with me to pick > > up Python. ?All newbies to Python have trouble with the idea of > > whitespace sensitivity, but how can I convince them that "it just > > works better" when I have this construct which I want to use but > > can't. > > > Has anybody found a way to emulate this behavior? ?I've often done it > > by opening an expression for the whole thing, but there's a lot of > > tasks where a single expression just isn't sufficient (such as things > > with assignment). > > > PS. In my opinion the solution would be to have the option of entering > > a "whitespace insensitive" mode which uses C style {} and ;. ?The > > token to enter it could be as complicated as you want (in fact, it may > > make sense to make it complicated to discourage use unless it's really > > advantageous). ?I'd sugest {{ and }} or something bigger like {={ } > > =}. ?Only two problems: 1) I'm sure it would offend Guido's sense of > > language aesthetics ?2) I'm sure the idea has been hashed over on this > > newsgroup to death... hence prefering a workaround instead. > > You could use the "with" statement: > > class xml_element(object): > ? ? ?def __init__(self, text): > ? ? ? ? ?self.text = text > ? ? ?def __enter__(self): > ? ? ? ? ?xmlWriter.BeginElement(self.text) > ? ? ?def __exit__(self, *args): > ? ? ? ? ?xmlWriter.EndElement() > > with xml_element("parent"): > ? ? ?with xml_element("child"): > ? ? ? ? ?xmlWriter.Characters("subtext") Yep, I think that's what Guido was thinking about while adding `with` statements. They're great at grouping code logically. Before I used `if True:` to do this but it wasn't good looking. From gagsl-py2 at yahoo.com.ar Wed Dec 24 13:55:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2008 16:55:33 -0200 Subject: String Comparison Testing References: <89f89940812241020l3e814f2dv4479da8d6575f7e7@mail.gmail.com> Message-ID: En Wed, 24 Dec 2008 16:20:17 -0200, Brad Causey escribi?: > I am trying to do some basic log parsing, and well, I am absolutely > floored > at this seemingly simple problem. I am by no means a novice in python, > but > yet this is really stumping me. I have extracted the pertinent code > snippets > and modified them to function as a standalone script. Basically I am > reading > a log file ( in this case, testlog.log) for entries and comparing them to > entries in a safe list (in this case, safelist.lst). I have spent > numerous > hours doing this several ways and this is the most simple way I can come > up > with: I'd say the "\n" at the end of each line is the culprit. > safelist = safelistfh.readlines() safelist = [line.strip() for line in safelistfh] (or just strip('\n') if spaces are important); same for the other list. > def safecheck(line): > for entry in safelist: > print 'I am searching for\n' > print entry > print '\n' > print 'to exist in\n' > print line repr() is your friend when debugging these things: print repr(entry) etc. > comp = line.find(entry) > if comp <> -1: > out = 'Failed' > else: > out = 'Passed' I'd use: if entry in line: ... Are you sure you're interested in the LAST comparison result ONLY? -- Gabriel Genellina From jpablo.romero at gmail.com Tue Dec 9 20:23:30 2008 From: jpablo.romero at gmail.com (=?ISO-8859-1?Q?Juan_Pablo_Romero_M=E9ndez?=) Date: Tue, 9 Dec 2008 19:23:30 -0600 Subject: Compiling and installing python 2.5.2 with Visual C++ 2008 In-Reply-To: References: Message-ID: Thanks! I'm having trouble with msi.py, so I'll better try python 2.6 The problem is with Pivy (openinventor bindings to python), it refuses to compile. It says: --------------------------------------------------------- ... error: Python was built with Visual Studio 2003; extensions must be built with a compiler than can generate compatible binaries. Visual Studio 2003 was not found on this system. If you have Cygwin installed, you can try compiling with MingW32, by passing "-c mingw32" to setup.py. --------------------------------------------------------- And because I've been compiling everything needed by pivy (Coin, Qt, SoQt, PyQt) with visual c++ 8, I decided to recompile python itself. Juan Pablo 2008/12/9 Gabriel Genellina : > En Tue, 09 Dec 2008 11:32:46 -0200, Juan Pablo Romero M?ndez > escribi?: > >> I need to compile python myself because of a module (pivy). So I >> downloaded MS Visual C++ 2008 express edition. It apparently compiled >> fine but I don't know how to install it to recreate the standard >> distribution. In linux i'd take "make install", but on windows? > > See Tools/msi/README.txt > BTW, do you really have to recompile Python? Unless the project requires > some specific compiler flags incompatible with the standard build, usually > there is no need to recompile Python just because of an extension. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > From bearophileHUGS at lycos.com Fri Dec 19 07:26:16 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 19 Dec 2008 04:26:16 -0800 (PST) Subject: List comprehension in if clause of another list comprehension References: Message-ID: <767cee3c-5021-4978-8750-bc5692e6517b@w39g2000prb.googlegroups.com> Peter Otten: > The problem is that list comprehensions do not introduce a new namespace. I think Python3 fixes this bug. Bye, bearophile From joe at strout.net Fri Dec 19 18:50:39 2008 From: joe at strout.net (Joe Strout) Date: Fri, 19 Dec 2008 16:50:39 -0700 Subject: encoding problem In-Reply-To: <6r2nfgFfb5kpU7@mid.uni-berlin.de> References: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> <6r1m72Ffb5kpU3@mid.uni-berlin.de> <6r2hvjFfb5kpU6@mid.uni-berlin.de> <6r2nfgFfb5kpU7@mid.uni-berlin.de> Message-ID: <494C334F.1040408@strout.net> Marc 'BlackJack' Rintsch wrote: >>> I don't see the shortcoming in Python <3.0. If you want real strings >>> with characters instead of just a bunch of bytes simply use `unicode` >>> objects instead of `str`. >> Fair enough -- that certainly is the best policy. But working with any >> other encoding (sometimes necessary when interfacing with any other >> software), it's still a bit of a PITA. > > But it has to be. There is no automagic guessing possible. Automagic guessing isn't possible if strings keep track of what encoding their data is. And why shouldn't they? We're a long way from the day when a "string" was nothing more than an array of bytes. Adding a teeny bit of metadata makes life much easier. >>> And does REALbasic really use byte strings plus an encoding!? >> You betcha! Works like a dream. > > IMHO a strange design decision. I get that you don't grok it, but I think that's because you haven't worked with it. RB added encoding data to its strings years ago, and changed the default string encoding to UTF-8 at about the same time, and life has been delightful since then. The only time you ever have to think about it is when you're importing a string from some unknown source (e.g. a socket), at which point you need to tell RB what encoding it is. From that point on, you can pass that string around, extract substrings, split it into words, concatenate it with other strings, etc., and it all Just Works (tm). In comparison, Python requires a lot more thought on the part of the programmer to keep track of what's what (unless, as you point out, you convert everything into unicode strings as soon as you get them, but that can be a very expensive operation to do on, say, a 500MB UTF-8 text file). > A lot more hassle compared to an opaque > unicode string type which uses some internal encoding that makes > operations like getting a character at a given index easy or > concatenating without the need to reencode. No. RB supports UCS-2 encoding, too, and is smart enough to take advantage of the fixed character width of any encoding when that's what a string happens to be. And no reencoding is used when it's not necessary (e.g., concatenating two strings of the same encoding, or adding an ASCII string to a string using any ASCII superset, such as UTF-8). There's nothing stopping you from converting all your strings to UCS-2 when you get them, if that's your preference. But saying that having only one string type that knows it's Unicode, and another string type that hasn't the foggiest clue how to interpret its data as text, is somehow easier than every string knowing what it is and doing the right thing -- well, that's just silly. Best, - Joe From wolfgang.lipp at gmail.com Fri Dec 12 16:44:32 2008 From: wolfgang.lipp at gmail.com (_wolf) Date: Fri, 12 Dec 2008 13:44:32 -0800 (PST) Subject: forcing future re-import from with an imported module References: <533670ae-6d9d-4b10-9156-e41b31b678c7@g17g2000prg.googlegroups.com> Message-ID: On Dec 11, 12:43 am, rdmur... at bitdance.com wrote: > "Why can't you have the code that is doing the import [...] > call a function [...] to produce [the] side effect [...]? > Explicit is better than implicit. A python programmer is > going to expect that importing a module is idempotent" you?re completely right that `import foo` with side effects may break some expectations, but so do all `from __future__` imports. you?re also right that another solution would be to come in from the other side and explicitly call a function from the importing module. all of this does not answer one question tho: why does deleting a module work most of the time, but not in the case outlined in my first post, above? why do we get to see this slightly strange error message there complaining about ?not finding? a module ?in sys.modules??well, most of the time, when a module is not in that cache, it will be imported, but not in this case. why? cheers & ~flow From mail at timgolden.me.uk Wed Dec 17 08:29:23 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 17 Dec 2008 13:29:23 +0000 Subject: Transferring a file over sockets In-Reply-To: References: Message-ID: <4948FEB3.5020707@timgolden.me.uk> Ferdinand Sousa wrote: > I am using sockets to transfer a file over LAN. There are 2 scripts, the > server opens a listens for connection and the client is run on another > machine. I always make sure the server is run first. The strange thing is > that if the the server script is double-clicked and executed (run in a > console with title %Python path%python.exe) the output file saved on the > server is truncated. It works just fine if you open the server script in > IDLE and then run it. The client script can be run in either way, it still > works. You could try using any arbitrary file to test this behaviour after > changing the file name in both the scripts. A couple of things: * Are you aware that there's no particular guarantee that what's sent along a socket in one write will be received in one read? There's a HOWTO here if you're interested: http://docs.python.org/dev/howto/sockets.html * Also, unless this is an exercise for yourself in investigating how sockets work, (in which case... read the docs :)), you might consider that you're reinventing the wheel not a little. But perhaps you knew that? TJG > > ========================================================== > # file receiver > # work in progress > > import socket > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > HOST = '192.168.1.17' > PORT = 31400 > > s.bind((HOST, PORT)) > s.listen(3) > conn, addr = s.accept() > print 'conn at address',addr > conn.send('READY') > f = open('C:\\Documents and Settings\\USER\\Desktop\\test.pdf','wb') > fsize=int(conn.recv(8)) > print 'File size',fsize > f.write(conn.recv(fsize)) > f.close() > conn.close() > s.close() > > raw_input('Press any key to exit') > > > =========================================================== > > # file sender !!! > # Work in progress > > import socket, os > from stat import ST_SIZE > > > HOST = '192.168.1.17' > PORT = 31400 # Arbitrary non-privileged port > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > s.connect((HOST,PORT)) > if s.recv(5)!='READY': > raw_input('Unable to connect \n\n Press any key to exit ...') > s.close() > exit() > > f=open('C:\\Documents and Settings\\USER\\Desktop\\t.pdf', 'rb') > fsize=os.stat(f.name)[ST_SIZE] > > s.send(str(fsize)) > s.send(f.read()) > > s.close() > f.close() > > =========================================================== > > Thanks for reading!! > > Best regards, > Ferdi > > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list From deets at nospam.web.de Thu Dec 11 17:52:23 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 11 Dec 2008 23:52:23 +0100 Subject: Best way of debigging a C extension In-Reply-To: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> References: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> Message-ID: <6qdjt7Fc1fg0U1@mid.uni-berlin.de> Paul Moore schrieb: > I'm writing a C extension. My environment is Python 2.5, with the > mingw compiler, on Windows XP. At the moment I'm debugging by > scattering printf() statements around, but it's not always easy. Is > there a better way of debugging - particularly for diagnosing crashes? > > I have gdb (although I've hardly used it, but I can learn :-)) but if > I try building my extension with python setup.py build --debug, I get > an error because -lpython25_d does not exist. I'm not surprised by > this, as I don't have a debug build of Python - but that should be OK, > I'm only looking for debugging info from my code. > > I tried copying libpython25.a to libpython25_d.a - my extension now > builds, but the resulting pyd is XXX_d.pyd, which won't import. If I > rename this to XXX.pyd, I can import and things seem to work - but it > seems a bit of a roundabout way of doing things. Is there a simpler > way that I've missed? It seems to me that this (debugging a C > extension without compiling a debug build of Python) would be a fairly > common situation, so I would have expected a "cleaner" way of doing > it. > > At the very least, a documentation patch to explain the best way of > doing things might be useful. I'll see what I can put together based > on the responses I get here. I never tried this on windows - but what happens if you start python inside GDB, and then set breakpoints inside your extension? This works flawlessly for me under *nix. The debug-build of python isn't needed for this - and I doubt a bit that it helps you much, as being inside the interpreter & getting detailed information isn't your goal - you want to see your extensions functions, what parameters they get and so on. Diez From enleverlesX.XmcX at XmclaveauX.com Sat Dec 20 12:09:01 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sat, 20 Dec 2008 18:09:01 +0100 Subject: PIL on 3.x? In-Reply-To: <6r44k2Fff3hbU1@mid.uni-berlin.de> References: <3892784c-ddf4-4451-bcfd-dbc58b9b55f8@e1g2000pra.googlegroups.com> <494c0ad4$0$4096$ba4acef3@news.orange.fr> <6r44k2Fff3hbU1@mid.uni-berlin.de> Message-ID: <494d2755$0$18388$ba4acef3@news.orange.fr> Hi! Fredrik Lundh (Pythonware ; the author of PIL (and ElementTree, and many other things)) had, in the past, often give answers. To me, like to others people. @-salutations -- Michel Claveau From castironpi at gmail.com Tue Dec 30 14:12:31 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 30 Dec 2008 11:12:31 -0800 (PST) Subject: SQL, lite lite lite References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> <8da5c6b1-951f-4abd-8ee7-07b63802b9f6@13g2000yql.googlegroups.com> Message-ID: <186e44f7-f949-45e2-b1e2-a913560acf94@s9g2000prg.googlegroups.com> On Dec 30, 11:16?am, prueba... at latinmail.com wrote: > On Dec 29, 1:06?pm, Aaron Brady wrote: snip > > My idea is to create a 'Relation' class. ?The details are basically > > open, such as whether to back it with 'sqllite3', 'shelve', 'mmap', or > > just mapping and sequence objects; what the simplest syntax is that > > can capture and permit all the basics, and how much and what else can > > fit in at that level; how and whether it can include arbitrary Python > > objects, and what constraints there are on them if not; how and > > whether to permit transactions; and what the simplest and coolest > > thing you can do with a little Python syntax is. snip > You really do like to reinvent the wheels do you? :-) Nothing wrong > with that. Just be aware that most people that really need what you > are proposing are probably already using mature feature rich libraries > for that. > > http://wiki.python.org/moin/HigherLevelDatabaseProgramming Look at these options! Who invents the wheel? Naturally, I've had time to master every one. The page on Dee reminded me that there was some relational algebra early on in the databases course. I'd forgotten. Maybe I wouldn't feel so sheepish if I'd tried starting there, to see exactly what I need. It's possible that if I had a real goal, it could drive the requirements for my Relation class. I don't. What I have is very vague, somewhat second-hand, and also inspired by a tangent in a recent thread here on c-l-databases, er, -py. You remember the days of parallel arrays before records were invented. The bare minimum I can think of for a relation is just a set of tuples. TakingClass( Arthur, Science ) #TakingClass.add( ( Arthur, Science ) ) It's just that 'what classes is Arthur taking?' is an O( total ) op. Next is a parallel mapping. TakingClass( Arthur, Science ) # science.add( arthur ) # arthur.add( science ) O( key ) read and O( 1 ) add, but it's repetitious. I feel it's really error prone, but maybe it's the best balance. The actual abstraction is something more like this: # Emps( Name, EmpID, Department ) Emps( KnightsOfNi, NiNiNi, Gardening ) # tupA= EmpsTuple( KnightsOfNi, NiNiNi, Gardening ) # KnightsOfNi.add( tupA ) # NiNiNi.add( tupA ) # Gardening.add( tupA ) (If KnightsOfNi will appear in more than one relation, it will need to distinguish: 'KnightsOfNi.emps.add( tupA )'.) A single predicate is just a set. A relation is just a set of tuples. Dee lets you write lambda expressions for filters/selects. Django lets you chain selects with a double underscore. From antoine at vo.lu Sat Dec 6 04:02:53 2008 From: antoine at vo.lu (Antoine De Groote) Date: Sat, 06 Dec 2008 10:02:53 +0100 Subject: Guido's new method definition idea In-Reply-To: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> Message-ID: <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> Allowing "$" as a substitute for "self" wouldn't require this new syntax. class C: def method($, arg): $.value = arg I'm strongly against this. This looks ugly and reminds me of Perl and Ruby. (I don't have anything against these languages, but there's a reason I use Python). Russ P. wrote: > On Dec 5, 6:21 pm, "Daniel Fetchinson" > wrote: >> Hi folks, >> >> The story of the explicit self in method definitions has been >> discussed to death and we all know it will stay. However, Guido >> himself acknowledged that an alternative syntax makes perfect sense >> and having both (old and new) in a future version of python is a >> possibility since it maintains backward compatibility. The alternative >> syntax will be syntactic sugar for the old one. This blog post of his >> is what I'm talking about: >> >> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... >> >> The proposal is to allow this: >> >> class C: >> def self.method( arg ): >> self.value = arg >> return self.value >> >> instead of this: >> >> class C: >> def method( self, arg ): >> self.value = arg >> return self.value >> >> I.e. explicit self stays only the syntax is slightly different and may >> seem attractive to some. As pointed out by Guido classmethods would >> work similarly: >> >> class C: >> @classmethod >> def cls.method( arg ): >> cls.val = arg >> return cls.val >> >> The fact that Guido says, >> >> "Now, I'm not saying that I like this better than the status quo. But >> I like it a lot better than [...] but it has the great advantage that >> it is backward compatible, and can be evolved into a PEP with a >> reference implementation without too much effort." >> >> shows that the proposal is viable. >> >> I'd like this new way of defining methods, what do you guys think? >> Anyone ready for writing a PEP? >> >> Cheers, >> Daniel >> >> -- >> Psss, psss, put it down! -http://www.cafepress.com/putitdown > > I like it. > > I'll even go a step further and suggest that "$" be allowed as a > substitute for "self". It looks like a capital "S" (for Self), and it > stands out clearly. It also makes code more succinct with no loss of > readability. Think of the line wraps that could be avoided. From aisaac at american.edu Thu Dec 4 14:50:58 2008 From: aisaac at american.edu (Alan G Isaac) Date: Thu, 04 Dec 2008 14:50:58 -0500 Subject: simplest way to strip a comment from the end of a line? In-Reply-To: References: Message-ID: rdmurray at bitdance.com wrote: > >>> from shlex import split > >>> split("this is a test #with a comment") > ['this', 'is', 'a', 'test', '#with', 'a', 'comment'] > >>> split("this is a test #with a comment", comments=True) > ['this', 'is', 'a', 'test'] > >>> split("this is a '#gnarlier' test #with a comment", comments=True) > ['this', 'is', 'a', '#gnarlier', 'test'] > > http://docs.python.org/library/shlex.html It would be nice to have this example included in the module docs... Alan Isaac From kermit.mei at gmail.com Thu Dec 11 09:44:20 2008 From: kermit.mei at gmail.com (Kermit Mei) Date: Thu, 11 Dec 2008 22:44:20 +0800 Subject: How can I understan the "for" here? Message-ID: <49412744.8040301@gmail.com> Hello all, look at the following sentence: >>>params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"} >>> ["%s=%s" % (k, v) for k, v in params.items()] ['pwd=secret', 'database=master', 'uid=sa', 'server=mpilgrim'] I can't understand the second sentence because of the "for ... in". I consider that the syntactics of "for" should be: for k,v in params.items(): ...... But there's no a colon here, why it can work? Thanks! From deets at nospam.web.de Mon Dec 1 16:56:48 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 01 Dec 2008 22:56:48 +0100 Subject: newbie question: parse a variable inside an RE? In-Reply-To: References: Message-ID: <6pj4svF832i3U1@mid.uni-berlin.de> joemacbusiness at gmail.com schrieb: > Hi All, > > How do I parse a variable inside an RE? > What is the re.search() syntax when your > search string is a variable? > It's easy to parse hardcoded RE's but not > if you use a variable. Both are exactly equal in difficulty. > > Here is my code, input and runtime: > > $ cat test45.py > #!/usr/bin/python > > import re > > resp = raw_input('Selection: ') > newresp = resp.strip() > print "you chose ", newresp > > fname = open('test44.in') > for I in fname: > # if re.search('^newresp', "%s"%(I)): # returns nothing > # if re.search(^newresp, "%s"%(I)): # syntax error > if re.search("^newresp", "%s"%(I)): # returns nothing > print I, How should python know that you want the newresp being expanded? And not that you want to search for the word "newresp"? You need to use the *variable* newresp: if re.search(newresp, I): ... If you want to alter it to have a "^" prepended before you use it, you need to do so: newresp = "^" + newresp And as show above, "%s" % I is nothing but I - no need for the string-interpolation. Diez From walterbyrd at iname.com Fri Dec 19 11:01:13 2008 From: walterbyrd at iname.com (walterbyrd) Date: Fri, 19 Dec 2008 08:01:13 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? Message-ID: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> I have not worked with Python enough to really know. But, it seems to me that more I look at python 3.0, the more I wonder if it isn't a step backwards. To me, it seems that this: print "%s=%d" % ('this',99) Is much easier, and faster, to type, and is also easier to read and understand. It also allows people to leverage their knowledge of C. This (if it's right) is much longer, and requires more special characters. print( "{0}={1}".format('this',99)) Maybe it's worth all the extra trouble, and breaking backward compatibilty, and all. But, I never had the idea that the old way was all that big a problem. Of course, I could be wrong. Was the old way all that big of a problem? From george.sakkis at gmail.com Thu Dec 4 13:13:00 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 4 Dec 2008 10:13:00 -0800 (PST) Subject: Overriding a method at the instance level on a subclass of a builtin type References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> Message-ID: On Dec 4, 1:03?pm, "Zac Burns" wrote: > Ok... but why are the special methods handled differently? Because otherwise they wouldn't be special ;-) And also for performance and implementation reasons I believe. George From ndbecker2 at gmail.com Tue Dec 2 19:47:52 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 02 Dec 2008 19:47:52 -0500 Subject: problem with optparse References: Message-ID: Robert Kern wrote: > Neal Becker wrote: >> This example is right out of python library reference. What's wrong >> here? >> >> import optparse >> >> def store_value(option, opt_str, value, parser): >> setattr(parser.values, option.dest, value) >> >> parser = optparse.OptionParser() >> parser.add_option("--foo", >> action="callback", callback=store_value, >> type="int", nargs=3, dest="foo") >> >> (opt,args) = parser.parse_args ('--foo a b c'.split()) >> >> [...] >> /usr/lib64/python2.5/optparse.pyc in _process_args(self, largs, rargs, >> values) >> 1423 elif self.allow_interspersed_args: >> 1424 largs.append(arg) >> -> 1425 del rargs[0] >> 1426 else: >> 1427 return # stop now, leave this >> arg in rargs >> >> TypeError: 'str' object doesn't support item deletion > > Dunno. It works for me (i.e. I get the expected "error: option --foo: > invalid integer value: 'a'"). Have you tried it outside of IPython? > yes: python test_opt.py Traceback (most recent call last): File "test_opt.py", line 12, in (opt,args) = parser.parse_args ('--foo') File "/usr/lib64/python2.5/optparse.py", line 1378, in parse_args stop = self._process_args(largs, rargs, values) File "/usr/lib64/python2.5/optparse.py", line 1425, in _process_args del rargs[0] TypeError: 'str' object doesn't support item deletion From paul at boddie.org.uk Wed Dec 10 08:45:30 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 10 Dec 2008 05:45:30 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> Message-ID: <9bb6c327-27e3-4208-8b5e-cf607340a2b5@q30g2000prq.googlegroups.com> On 9 Des, 19:23, "Chris Mellon" wrote: > > So hold up a second. I'm out of line for calling someone on making a > trollish post that's not relevant to the topic, and for being pretty > late to the party even with the part that *was* on topic, and for > (even in the original post) going the ad-hominem route by not so > subtly implying that Python is an ivory tower language that's not good I believe the term was "ivory-tower thinking". > enough for people with real problems - a clearly false statement by > any standards, and doubly offensive from someone who *is* using it for > real problems and who himself is a less than shining example of You're wide of the mark now, since the complainant was referring to motivations in the the design of the language, not the relevance of the language outside academia (where it is also highly relevant, by the way). > responsible software management, but the OPs lapse into ranting in > response to trite but accurate answers to a question he could have > answered for himself, in detail, had he bothered to read the threads > from the time when the issue actually matter is a reasonable response > that we should support and validate? Trite but accurate? References to the Zen of Python were trite and peripheral at best, especially since the actual reasons (some actually being offered, aside from "get used to it", which isn't a reason) are mostly pragmatic. I think at that point, the complainant is justified in questioning the priorities of the core developers, even though he knows that there's no recourse at this point. The most you can blame him for in that respect is not starting a new thread about those topics, and it's not as if he's the first to air his grievances about those things, is it? > Sometimes you're not ?a crusader for thinking differently and change > by confrontation and speaking truth to power. Sometimes you're just an > asshole. I think you managed to enter this thread without revealing any particular insight in the matter, so I suppose name-calling was the most we could expect from you at this point. > For clarification: The OPs original complaint is legitimate, if dated > and partially his own fault. His phrasing of the problem, the tone and > content of his email, and his lapse into flaming when he wasn't > immediately hailed as a herald of sanity is not legitimate. If people would confine themselves to the matters under discussion without taking an adversarial position - after all, it's not as if the guy just dropped in to flame everyone having never used Python - there wouldn't be any need for anyone to lapse into flaming, tantrums or name-calling, would there? You wouldn't even need to apologise for calling the guy a troll, now, would you? Paul From python at bdurham.com Tue Dec 2 07:39:54 2008 From: python at bdurham.com (python at bdurham.com) Date: Tue, 02 Dec 2008 07:39:54 -0500 Subject: Determining number of dict key collisions in a dictionary Message-ID: <1228221594.807.1287801527@webmail.messagingengine.com> Is there any way to determine the number of dictionary key collisions in a specific dictionary? Background: I'm working on a project using very large dictionaries (64 bit Python) and question from my client is how effective is Python's default hash technique for our data set? Their concern is based on the belief that Python's default dictionary hash scheme is optimized for 32 bit vs. 64 bit environments and may not have anticipated the additional range of keys that can be generated in a 64 bit environment. Our keys are based on 20 to 44 byte ASCII (7-bit) alpha-numeric strings. Thank you, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From jan at jandecaluwe.com Wed Dec 24 02:52:15 2008 From: jan at jandecaluwe.com (Jan Decaluwe) Date: Wed, 24 Dec 2008 08:52:15 +0100 Subject: Why MyHDL? In-Reply-To: References: <4950d063$0$2853$ba620e4c@news.skynet.be> Message-ID: <4951ea41$0$2850$ba620e4c@news.skynet.be> Stef Mientki wrote: > hello Jan, > > Jan Decaluwe wrote: >> Hello: >> >> MyHDL is a Python package for using Python as a >> Hardware Description Language. >> >> A new release is upcoming, and on this occasion >> we have prepared a page about why MyHDL may >> be useful to you: >> >> http://www.myhdl.org/doku.php/why >> > Very Interesting, > I'm no expert at all (but as an exercise I'm just now writing an EDIF-v2 > to SystemC converter in Python) , > I wonder why I only see comparison with VHDL and SystemVerilog, > and not with SystemC ? MyHDL's target audience are the users of mainstream HDL-based design flows (including synthesis and implementation.) I don't encounter SystemC there. Jan -- Jan Decaluwe - Resources bvba - http://www.jandecaluwe.com Python as a hardware description language: http://www.myhdl.org From grebekel at gmail.com Mon Dec 29 14:11:55 2008 From: grebekel at gmail.com (Grebekel) Date: Mon, 29 Dec 2008 11:11:55 -0800 (PST) Subject: flushing of print statements ending with comma Message-ID: <25783efa-fa57-49c8-b20a-7bdf6f7cb256@w1g2000prk.googlegroups.com> I have recently noticed that print statements ending with a comma are not immediately flushed. This is evident when such statement is executed before a very long operation (a big loop for instance). Example: print 'Take a walk, because this will take a while...', i = 0 while i < 10**10: i += 1 print "we're done!" Here the first string is not printed until the second print statement. If the second print statement is removed then the string is not printed until the end of the program. Apparently, python does not flush the stdout buffer until it is ordered to do so either explicitly or by a print statement not ending with a comma. Using sys.std.flush after the print fixes this issue, but doing so each time seems cumbersome and somewhat counterintuitive. Is there some reasoning behind this behavior or is it a bug? Python version 2.5.1 From robert.kern at gmail.com Mon Dec 8 17:13:12 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 08 Dec 2008 16:13:12 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Terry Reedy wrote: > Rasmus Fogh wrote: >> much, though, just to get code like this to work as intended: >> alist.append(x) >> print ('x is present: ', x in alist) > > Even if rich comparisons as you propose, the above would *still* not > necessarily work. Collection classes can define a __contains__ that > overrides the default and that can do anything, though True/False is > recommended. No, it's actually required. In [4]: class A(object): def __contains__(self, other): return 'foo' ...: ...: In [7]: a = A() In [8]: 1 in a Out[8]: True Okay, so it will coerce to True/False for you, but unlike rich comparisons, the return value must be interpretable as a boolean. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From robert.kern at gmail.com Mon Dec 22 16:22:14 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 22 Dec 2008 15:22:14 -0600 Subject: 64-bit / 128-bit data element type for array? In-Reply-To: <880c8478-8b40-40e0-8597-aef960612f09@s9g2000prg.googlegroups.com> References: <880c8478-8b40-40e0-8597-aef960612f09@s9g2000prg.googlegroups.com> Message-ID: akineko wrote: > Hello, > > bearophile and Robert, thank you for your prompt response. > I will try NumPy (this is a good execuse to learn and to use a new > package). > >> I haven't seen uint128 in the wild, though. > > Of course, not many applications require uinit128 as a scalar value. > I may need to deal with 128-bit data as it is now not uncommon to have > 128-bit data bus (or even 256-bit wide and beyond) in ASICs > (microchip) design. Unfortunately, some designs use big-endian and > others use little-endian ... Is that actually a 2s-complement 128-bit unsigned integer, or is it just a 128-bit-long chunk of data? -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From gagsl-py2 at yahoo.com.ar Mon Dec 29 00:40:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Dec 2008 03:40:08 -0200 Subject: ctypes & strings References: <334452.47084.qm@web30003.mail.mud.yahoo.com> <000f01c96822$5c300f00$0d00a8c0@hendrik> <00a801c968dd$6508b3a0$0d00a8c0@hendrik> Message-ID: En Sun, 28 Dec 2008 08:59:03 -0200, Hendrik van Rooyen escribi?: > "Gabriel Genellina" wrote: > >> Hmmm, I don't think posting a potentially harmful example is actually a >> good idea... > > True - its my only example though, and nobody else was > bothering to reply, so I kicked off and flushed out some > response. > > Who was it that said that the way to get info out of usenet > was to post some rubbish? > > :-) As in xkcd: http://xkcd.com/386/ BTW, Python is featured again in the Christmas special: http://xkcd.com/521/ -- Gabriel Genellina From dickinsm at gmail.com Mon Dec 8 06:37:26 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 8 Dec 2008 03:37:26 -0800 (PST) Subject: built-in functions as class attributes References: <75fdbf34-34d9-4373-bbe0-7e3f76dc4c3f@x38g2000yqj.googlegroups.com> Message-ID: <001ab2a6-b58e-4ed0-9cdb-7a9a743b18ee@j38g2000yqa.googlegroups.com> On Dec 8, 11:23?am, Peter Otten <__pete... at web.de> wrote: > I don't know if there is something official, I google for > > http://users.rcn.com/python/download/Descriptor.htm > > or "descrintro" every time I need a refresher. Thank you! I'd read this before, but apparently I'd either not taken it in first time round, or entirely forgotten it. Anything written by Raymond has got to be pretty darn close to 'official'. :) Mark From gagsl-py2 at yahoo.com.ar Tue Dec 16 04:43:25 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Dec 2008 07:43:25 -0200 Subject: Deepcopying slice objects References: Message-ID: En Sun, 14 Dec 2008 15:43:01 -0200, Max Argus escribi?: > I stumbled across a thread about that suggests fixing deepcopy to let it > copy slice objects. ( > http://mail.python.org/pipermail/python-list/2006-August/398206.html). I > expected this to work and don't see any reason why it shouldn't in case > there is a good reason why it dosen't work can someone please explain it. It works fine, both in 2.6 and 3.0: py> from copy import copy, deepcopy py> x = slice(1, 10, 2) py> copy(x) slice(1, 10, 2) py> deepcopy(x) slice(1, 10, 2) -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Sun Dec 14 06:03:05 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Dec 2008 11:03:05 GMT Subject: Optimizing methods away or not? References: <0154b041$0$6988$c3e8da3@news.astraweb.com> Message-ID: <0154df65$0$6988$c3e8da3@news.astraweb.com> On Sun, 14 Dec 2008 10:52:25 +0000, Arnaud Delobelle wrote: > You could also not use the metaclass and use post_verify as a decorator Except that self.verify doesn't exist if __debug__ is false. -- Steven From rhf22 at mole.bio.cam.ac.uk Sun Dec 7 07:43:59 2008 From: rhf22 at mole.bio.cam.ac.uk (Rasmus Fogh) Date: Sun, 7 Dec 2008 12:43:59 +0000 (GMT) Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Robert Kern Wrote: >Terry Reedy wrote: >> Rasmus Fogh wrote: >>> Personally I would like to get these !@#$%&* misfeatures removed, >> >> What you are calling a misfeature is an absence, not a presence that >> can be removed. > > That's not quite true. Rich comparisons explicitly allow non-boolean > return values. Breaking up __cmp__ into multiple __special__ methods was > not the sole purpose of rich comparisons. One of the prime examples at the > time was numpy (well, Numeric at the time). We wanted to use == to be able > to return an array > with boolean values where the two operand arrays were equal. E.g. > > In [1]: from numpy import * > > In [2]: array([1, 2, 3]) == array([4, 2, 3]) > Out[2]: array([False, True, True], dtype=bool) > > SQLAlchemy uses these operators to build up objects that will be turned > into SQL expressions. > > >>> print users.c.id==addresses.c.user_id > > Basically, the idea was to turn these operators into full-fledged > operators like +-/*. Returning a non-boolean violates neither the letter, > nor the spirit of the feature. > > Unfortunately, if you do overload __eq__ to build up expressions or > whatnot, the other places where users of __eq__ are implicitly expecting > a boolean break. > While I was (and am) a supporter of rich comparisons, I feel Rasmus's > pain from time to time. It would be nice to have an alternate method to > express the boolean "yes, this thing is equal in value to that other thing". > Unfortunately, I haven't figured out a good way to fit it in now without > sacrificing rich comparisons entirely. The best way, IMHO, would have been to use an alternative notation in numpy and SQLalchemy, and have '==' always return only a truth value - it could be a non-boolean as long as the bool() function gave the correct result. Surely the extra convenience of overloading '==' in special cases was not worth breaking such basic operations as 'bool(x == y)' or 'x in alist'. Again, the problem is only with '==', not with '>', '<=' etc. Of course it is done now, and unlikely to be reversed. >>> and constrain the __eq__ function to always return a truth value. >> >> It is impossible to do that with certainty by any mechanical >> creation-time checking. So the implementation of operator.eq would >> have to check the return value of the ob.__eq__ function it calls *every >> time*. That would slow down the speed of the 99.xx% of cases where the >> check is not needed and would still not prevent exceptions. And if the >> return value was bad, all operator.eq could do is raise and exception >> anyway. > >Sure, but then it would be a bug to return a non-boolean from __eq__ and >friends. It is not a bug today. I think that's what Rasmus is proposing. Yes, that is the point. If __eq__ functions are *supposed* to return booleans I can write generic code that will work for well-behaved objects, and any errors will be somebody elses fault. If __eq__ is free to return anything, or throw an error, it becomes my responsibility to write generic code that will work anyway, including with floating point numbers, numpy, or SQLalchemy. And I cannot see any way to do that (suggestions welcome). If purportedly general code does not work with numpy, your average numpy user will not be receptive to the idea that it is all numpys fault. Current behaviour is both inconsistent and counterintuitive, as these examples show. >>> x = float('NaN') >>> x == x False >>> ll = [x] >>> x in ll True >>> x == ll[0] False >>> import numpy >>> y = numpy.zeros((3,)) >>> y array([ 0., 0., 0.]) >>> bool(y==y) Traceback (most recent call last): File "", line 1, in ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() >>> ll1 = [y,1] >>> y in ll1 True >>> ll2 = [1,y] >>> y in ll2 Traceback (most recent call last): File "", line 1, in ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() >>> Can anybody see a way this could be fixed (please)? I may well have to live with it, but I would really prefer not to. --------------------------------------------------------------------------- Dr. Rasmus H. Fogh Email: r.h.fogh at bioc.cam.ac.uk Dept. of Biochemistry, University of Cambridge, 80 Tennis Court Road, Cambridge CB2 1GA, UK. FAX (01223)766002 From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 29 04:07:00 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 29 Dec 2008 10:07:00 +0100 Subject: why cannot assign to function call In-Reply-To: References: Message-ID: <49589334$0$8269$426a74cc@news.free.fr> scsoce a ?crit : > I have a function return a reference, and want to assign to the > reference, You have a function that returns an object. You can't "assign" to an object - this makes no sense. I'm afraid you are confusing Python's name/object bindings with C pointers or C++ references. From MatthewHyatt at ComputerPeople.co.uk Mon Dec 8 13:11:26 2008 From: MatthewHyatt at ComputerPeople.co.uk (Hyatt, Matthew) Date: Mon, 8 Dec 2008 18:11:26 -0000 Subject: Great Python Job - Bristol - UK Message-ID: <3D9A341721DDC4438239BB7799E7EE511029FDFF@EXCHANGE01.ajilongroup.co.uk> Hi there, I hope you don't mind me contacting you - I need to contact some real Python experts and thought this would be best. I currently have a unique opportunity for a talented Python Software Engineer to work on exciting application development projects for the aeronautical industry. You will work in a team of world experts that includes PhD qualified professionals that are recognised by their peers as being global authorities in their individual fields. If you have a background and keen interest in Python programming, physics, mathematics, engineering or CFD, then this could be your dream job. The role Working in a team of 10 software experts, you will develop ground-breaking technology that is largely green-field. This is very challenging and interesting work that involves a large research element and will include the development of the company's own open-source Python application framework, extensive use of PyQT and CFD work. Person Spec In order to apply, you will have superb programming skills in Python and a strong academic background, MSc or PhD qualified in a numeric or engineering discipline. Ideally, your knowledge of Python will extend to PyQT and your broader development skills will include C/C++, MATLAB and SQL. Any experience gained in CFD, or prior exposure to Enthought's Envisage product would be an advantage. If you have the required skills and are interested, please respond with a copy of your CV and I will gladly discuss the opportunity in more detail. Many thanks, Matt Matthew Hyatt Senior Consultant Tel: +44 (0) 117 930 8575 Fax: +44 (0) 117 929 1444 matthewhyatt at computerpeople.co.uk www.computerpeople.com Intelligent Business Solutions through Executive Search & Selection, Careers Consultancy, Managed Service & Specialised Recruitment This e-mail and any files transmitted with it are confidential (and may contain privileged information) to the ordinary user of the e-mail address to which it was addressed and must not be copied, disclosed or distributed without the prior authorisation of the sender. Please notify the sender and destroy this e-mail immediately if you are not the intended recipient. Please also note that while our own software systems have been used to try to ensure that this e-mail has been swept for viruses, we do not accept responsibility for any damage or loss caused in respect of any viruses transmitted by the e-mail. Please ensure your own checks are carried out before any attachments are opened. Computer People, Jonathan Wren & People Direct are the trading names of Ajilon (UK) Limited whose registered office is at:71 Elstree Way, Borehamwood, Hertfordshire, England, WD6 1WD. Registered in England & Wales: Registered No. 01458245. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image001.jpg Type: image/jpeg Size: 2219 bytes Desc: image001.jpg URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image002.gif Type: image/gif Size: 2153 bytes Desc: image002.gif URL: From wuwei23 at gmail.com Thu Dec 11 11:16:51 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 11 Dec 2008 08:16:51 -0800 (PST) Subject: Preventing execution of a method References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> Message-ID: On Dec 12, 2:07?am, "Emanuele D'Arrigo" wrote: > I.e. if I have a class with two methods, doSomethingSafe() and > doSomethingDangerous(), is there a way to prevent another module from > executing doSomethingDangerous() but allow the execution of > doSomethingSafe()? > > My understanding is that in python this is not possible. Can you > confirm? Your understanding is correct. The Python convention is to prefix non-public methods/classes etc with an underscore, as in _doSomethingDangerous(). This is meant to indicate to anyone using your module that they shouldn't use this function, at least not without having a good understanding of what it does. From martin at v.loewis.de Sun Dec 14 17:20:22 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 14 Dec 2008 23:20:22 +0100 Subject: Building from source -- zlib/binascii problems 2.5.2/2.6.1 In-Reply-To: References: <71531b64-535f-49d0-a0c6-7704df83b251@f18g2000vbf.googlegroups.com> <49458079.1000304@v.loewis.de> <003b0307-c8df-489b-98e6-cfaa35d050a4@k1g2000prb.googlegroups.com> Message-ID: <494586A6.4060102@v.loewis.de> > So.. it seems as though I need to get it to point to the 64 bit > version (or compile the zlib that comes with Python source). I'm not > sure how to override that. The easiest solution would be to invoke the linker line manually, and replace -lz with the absolute path to the right library. Regards, Martin From martin.hellwig at dcuktec.org Mon Dec 22 13:07:20 2008 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Mon, 22 Dec 2008 18:07:20 +0000 Subject: I always wonder ... In-Reply-To: References: Message-ID: <494fd759$0$186$e4fe514c@news.xs4all.nl> skip at pobox.com wrote: > Is there some online troll game > running where the players earn points for generating responses to their > posts? > You just got 10 points ;-) -- mph From cma at mail.bnu.edu.cn Tue Dec 9 04:56:37 2008 From: cma at mail.bnu.edu.cn (Cong Ma) Date: Tue, 09 Dec 2008 17:56:37 +0800 Subject: [Python 2.x] Pickling a datetime.tzinfo subclass instance? In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > En Mon, 08 Dec 2008 12:34:03 -0200, Cong Ma escribi?: > >> I'm writing a program that pickles an instance of a custom subclass of >> datetime.tzinfo. I followed the guides given in the Library Reference >> (version >> 2.5.2, chapter 5.1.6), which contain the note: >> >> "Special requirement for pickling: A tzinfo subclass must have an >> __init__ >> method that can be called with no arguments, else it can be pickled >> but possibly >> not unpickled again. This is a technical requirement that may be >> relaxed in the >> future." >> >> I tried this with an example "FixedOffset" subclass instance given in the >> Example section in the manual. It indeed failed to unpickle. To work >> around >> this, I found two possible solutions: >> 1. Modify the __init__ method so that it takes optional arguments with >> default >> values; > > Doing that still works with 2.6 and 3.0 > >> 2. Implement the __getinitargs__ method so that it does the opposite of >> __init__: returning a tuple from the instance's internal state that >> can be used >> to re-initialize an instance, retaining the old value. > > In fact, it doesn't matter *what* it returns, as far as they're valid > arguments to __init__ > >> My questions: >> 1. Is the "technical limitation" fixed in version 2.6 or 3.0? I can't >> check it >> for myself now... Python.org seems down and I can't find the docs. > > No, they behave the same (odd) way. > >> 2. To stick with version 2.5, which of the above 2 methods is better? >> Both seems >> to unpickle to the correct result, but are there subtle side-effects? >> Or there >> are better solutions? > > I'd use method 1, just because the __getinitargs__ are useless. > Gabriel, Thank you so much for your great explanations. Had you not told me this, I would hardly be able to find it out by myself :) Regards, Cong. From andreas at kostyrka.org Sun Dec 14 12:35:24 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sun, 14 Dec 2008 18:35:24 +0100 Subject: execution time In-Reply-To: References: Message-ID: <20081214173524.GA4896@hell.kostyrka.org> On Sun, Dec 14, 2008 at 05:03:38PM +0100, David Hl??ik wrote: > Hi guys, > > #! /usr/bin/python > > import random > import bucket2 > > data = [ random.randint(1,25) for i in range(5)] > print "random data : %s" % data > print "result: %s" %bucket2.sort(data) > > How to write a test script which will outputs execution time for > bucket2.sort(data) ? Well: import time starttime = time.time() .... endtime = time.time() print "Whatever .... does, it took %5.3fs to do." % (endtime - starttime) Alternativly take a look at the timeit standard module. Andreas > > Thanks in advance! > -- > http://mail.python.org/mailman/listinfo/python-list From python-url at phaseit.net Wed Dec 24 09:17:57 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Wed, 24 Dec 2008 14:17:57 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Dec 24) Message-ID: QOTW: "Threads seem to be used only because mediocre programmers don't know what else to use." - Sturla Molden http://mail.python.org/pipermail/python-dev/2008-December/084265.html Python 2.4.6 and 2.5.3 were released this week: http://groups.google.com/group/comp.lang.python/browse_thread/thread/53901d6dd764d8a8/ What's the difference between __str__ vs. __repr__? http://groups.google.com/group/comp.lang.python/browse_thread/thread/a0f0b526006fe831/ Unicode problems -- and how RealBasic solves them in a totally different way: http://groups.google.com/group/comp.lang.python/browse_thread/thread/f623b434f2ac6d9/ An optimization exercise, involving fileinput and str.split/partition: http://groups.google.com/group/comp.lang.python/browse_thread/thread/77fc160ee557ae39/ How to modify a program while it is still running: http://groups.google.com/group/comp.lang.python/browse_thread/thread/95397361600ded28/ A looooong thread about the new (3.0) string formatting mechanism http://groups.google.com/group/comp.lang.python/browse_thread/thread/23d63689c0087ebf/ Two apparently trivial tasks are actually challenging to get right: writing a sign() function, and timing it: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c726f932f75c23e4/ ======================================================================== 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 Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From esgameserver at gmail.com Mon Dec 1 16:15:35 2008 From: esgameserver at gmail.com (esgameserver at gmail.com) Date: Mon, 1 Dec 2008 13:15:35 -0800 (PST) Subject: Thread always alive Message-ID: Hi, I have thread that the isAlive() method is always returning True even the last finally(..) clause is executed. I am suspecting some kind of a leak on a IO object like a file or socket descriptor is still open. Could this lead to this kind of problem? If yes, how can I debug this issue efficiently to see the leak? Thanks, From joe at strout.net Sun Dec 7 09:17:30 2008 From: joe at strout.net (Joe Strout) Date: Sun, 7 Dec 2008 07:17:30 -0700 Subject: how to get a beep, OS independent ? In-Reply-To: References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> Message-ID: On Dec 7, 2008, at 6:36 AM, Duncan Booth wrote: > Python is just printing the ascii bell character: some environments > will > interpret that as a request to make a beep, some will do things like > flashing the whole screen, others just output a graphic character. > Python > doesn't know what your environment will do. Agreed. But invoking the standard system beep is such a basic function that it ought to be easier than this. I'm pretty sure it's a single OS call on all platforms. On OS X, for example, it's void NSBeep(void); declared in NSGraphics.h. I'm sure it's something similarly simple on other platforms. Where's the standard place for this sort of OS-abstraction function, outside the standard Python library? I'm talking about something more light-weight than wx, QT, or TK; something that just wraps standard functions (like the system beep) and works in console apps or in any flavor of GUI app. Is there such a module out there somewhere? Best, - Joe From google at mrabarnett.plus.com Fri Dec 19 13:31:00 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 19 Dec 2008 18:31:00 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> Message-ID: <494BE864.1040100@mrabarnett.plus.com> bearophileHUGS at lycos.com wrote: > r: >> I always thought of Python as an intuitive way to write C code.< > > C is a very low level language, not far from assembly, and often it's > not intuitive at all. > > C string formatting is short and a flexible enough, but it's out of > place in a language as high level as Python3. The new syntax allows > more flexibility, and it's better for most people that don't know C > already, like newbies, etc. > > ------------------ > > walterbyrd: >> It seems to me that 3.0 is changing a lot of non-problems. And it's > going to be slower to boot.< > > They are non-problems for people that already know lot of Python (and > some C). But for all the other people, especially newbies, it's better > in most things. > > Most language designers (and generally people very used a certain > language) become so accustomed to their language that they most of the > times become like "blind" to the defects and warts of their language > (I have said this four years ago too, when I have started learning > Python, listing many problems in Python, and among them there were C > string formatting too). So I think it was a feat for the Python > developers to see many characteristics of the Python2.x as what they > are: warts, bugs, etc, and fix them (and most of the times their newer > designs are "the right thing" with just few exceptions, I have counted > only 3 of them, and they are small). They have gained even more of my > respect. > > Regarding the speed of Python3 programs, they will go faster because > people will be forced to use things like lazy ranges, lazy map and > filter, lazy keys and values, and the "key" of sort/sorted. All those > things can be used in Python2.x too, but lot of people aren't expert > enough (or they are just lazy) and don't use them, so the average > Python3 program will probably be faster (and use less memory) thanks > to them. > > Python3 programs will go slower because they use 2-byte long Unicode > strings by default (it can be compiled for 4-byte Unicode too, and I > think this has to become the default, eventually, because I think it > will become silly to save few bytes for strings when you will have > 8-16-32+ GB of RAM), and they use multi-precision integers only. Such > strings and numbers allow to reduce some troubles, even "bugs", etc. > > At the moment Python3 isn't much optimized for speed, you can think of > it an experimental release still. I/O and multiprecision integers will > probably be speed up (and some form of transparent on-the-fly > compression or smart representation can in most times halve the memory > used by Py3 strings, putting the performance almost back to the Py2.x > one. In computer science there are LOT of tricks that can be used if > you have the brain and time to invent and implement them. You can see > that for example in how Psyco manages internally string/list/tuple > slices). > > Anyway, CPUs and computers are now much faster than the CPUs present > when Python was created. And Python is first of all designed for the > programmer and not for the CPU. So I think it's right to make Python3 > become a little higher level language even if this slows it down a > little. For the kind of programs Python is often used for, I think > this is a Win. (Ruby programs are often slower than Python ones > (because Ruby is a little higher level than Python) but it's very > useful anyway). If Python will continue to develop in the following > years (think about a Python4000) then I think it may become good to > make it become even more slower, if this will help make it a little > more higher level still. > I would've hoped that Python 4000 would address the internals (JIT) just as Python 3000 addressed the externals. From iofferkicks32 at gmail.com Sat Dec 27 10:26:32 2008 From: iofferkicks32 at gmail.com (www.iofferkicks.com) Date: Sat, 27 Dec 2008 07:26:32 -0800 (PST) Subject: www.iofferkicks.com china cheap wholesale nike shoes,air jordan shoes,air force one shoes. Message-ID: Get Nike Shoes at Super Cheap Prices Discount Nike air jordans (www.iofferkicks.com) Discount Nike Air Max 90 Sneakers (www.iofferkicks.com) Discount Nike Air Max 91 Supplier (www.iofferkicks.com) Discount Nike Air Max 95 Shoes Supplier (www.iofferkicks.com) Discount Nike Air Max 97 Trainers (www.iofferkicks.com) Discount Nike Air Max 2003 Wholesale (www.iofferkicks.com) Discount Nike Air Max 2004 Shoes Wholesale (www.iofferkicks.com) Discount Nike Air Max 2005 Shop (www.iofferkicks.com) Discount Nike Air Max 2006 Shoes Shop (www.iofferkicks.com) Discount Nike Air Max 360 Catalogs (www.iofferkicks.com) Discount Nike Air Max Ltd Shoes Catalogs (www.iofferkicks.com) Discount Nike Air Max Tn Men's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 2 Women's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 3 Customize (www.iofferkicks.com) Discount Nike Air Max Tn 4 Shoes Customize ( www.iofferkicks.com) Discount Nike Air Max Tn 6 Supply (www.iofferkicks.com) Discount Nike Shox NZ Shoes Supply (www.iofferkicks.com) Discount Nike Shox OZ Sale (www.iofferkicks.com) Discount Nike Shox TL Store (www.iofferkicks.com) Discount Nike Shox TL 2 Shoes Store (www.iofferkicks.com) Discount Nike Shox TL 3 Distributor (www.iofferkicks.com) Discount Nike Shox Bmw Shoes Distributor (www.iofferkicks.com) Discount Nike Shox Elite Shoes Manufacturer (www.iofferkicks.com) Discount Nike Shox Monster Manufacturer (www.iofferkicks.com) Discount Nike Shox R4 Running Shoes (www.iofferkicks.com) Discount Nike Shox R5 Mens Shoes (www.iofferkicks.com) Discount Nike Shox Ride Womens Shoes (www.iofferkicks.com) Discount Nike Shox Rival Shoes Wholesaler (www.iofferkicks.com) Discount Nike Shox Energia Wholesaler (www.iofferkicks.com) Discount Nike Shox LV Sneaker (www.iofferkicks.com) Discount Nike Shox Turbo Suppliers (www.iofferkicks.com) Discount Nike Shox Classic Shoes Suppliers (www.iofferkicks.com) Discount Nike Shox Dendara Trainer (www.iofferkicks.com) Discount Nike Air Jordan 1 Seller (www.iofferkicks.com) Discount Nike Air Jordan 2 Shoes Seller (www.iofferkicks.com) Discount Nike Air Jordan 3 Collection (www.iofferkicks.com) Discount Nike Air Jordan 4 Shoes Collection (www.iofferkicks.com) Discount Nike Air Jordan 5 Chaussure Shoes (www.iofferkicks.com) Discount Nike Air Jordan 6 Catalog (www.iofferkicks.com) Discount Nike Air Jordan 7 Shoes Catalog (www.iofferkicks.com) Discount Nike Air Jordan 8 Customized (www.iofferkicks.com) Discount Nike Air Jordan 9 Shoes Customized (www.iofferkicks.com) Discount Nike Air Jordan 10 Wholesalers (www.iofferkicks.com) Discount Nike Jordan 11 Shoes Wholesalers (www.iofferkicks.com) Discount Nike Air Jordan 12 Factory (www.iofferkicks.com) Discount Nike Air Jordan 13 Shoes Factory (www.iofferkicks.com) Discount Nike Air Jordan 14 Shoes Sell (www.iofferkicks.com) Discount Nike Air Jordan 16 Exporter (www.iofferkicks.com) Discount Nike Air Jordan 17 Shoes Exporter (www.iofferkicks.com) Discount Nike Air Jordan 18 Offer (www.iofferkicks.com) Discount Nike Air Jordan 19 Shoes Offer (www.iofferkicks.com) Discount Nike Air Jordan 20 Manufacture (www.iofferkicks.com) Discount Nike Jordan 21 Shoes Manufacture (www.iofferkicks.com) EMAIL:IOFFERKICKS at GMAIL.COM MSN :IOFFERKICKS at MSN.COM From istvan.albert at gmail.com Thu Dec 4 13:40:41 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Thu, 4 Dec 2008 10:40:41 -0800 (PST) Subject: Python 3 read() function References: <16651e80812040900j257fe2acjf5d8817811d32da6@mail.gmail.com> Message-ID: On Dec 4, 1:31?pm, Terry Reedy wrote: > Jerry Hill wrote: > > That's 3 orders of magnitude slower on python3.0! > > Timing of os interaction may depend on os. ?I verified above on WinXp > with 4 meg Pythonxy.chm file. ?Eye blink versus 3 secs, duplicated. ?I > think something is wrong that needs fixing in 3.0.1. > > http://bugs.python.org/issue4533 I believe that the slowdowns are even more substantial when opening the file in text mode. From jaume.bonet at gmail.com Thu Dec 11 12:35:58 2008 From: jaume.bonet at gmail.com (Jaume Bonet) Date: Thu, 11 Dec 2008 09:35:58 -0800 (PST) Subject: Memory leak when using a C++ module for Python References: Message-ID: <13db1224-5d6d-4240-8184-ce852e10b422@d36g2000prf.googlegroups.com> Sure, sorry... This is the function that is visible from python and the one that the python code calls: static PyObject * IMFind (PyObject *self, PyObject *args, PyObject *kwargs) { //Array for the detection of the parameters coming from Python static char *kwlist[] = {"shareInt","root","prefix","lowerLimit",NULL}; //Root protein code char *root; //Pefix for the output file char *prefix; //Incoming Python object PyObject *shareIntPy; //Number of proteins at level two from the root, that will appear in the iMotifs' proteins int *pSize = new int; //Maximum number of common interactors int *max = new int; //Set relating each protein (integer) with their interactors... set** shareInt; //Lower limit for iMotif search int lowLim; //Vector for the seed iMotifs from an specific threshold vector IMseed; //Vector of all the working iMotifs during the identification process vector IMarray; //Receiving data from python if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Ossi", kwlist, &shareIntPy, &root, &prefix,&lowLim)) { cerr << "Error in parameter transference from python to iMotif C++ module"< translator = string2int (shareIntPy,root,shareInt,pSize,max); //Loop for iMotif search at threshold thr till the specified lower limit for (int thr = *max; thr >= lowLim; thr--) { cout << "Checking threshold " << thr << endl; //Specifying the output file name stringstream filename; filename << prefix << "." << thr; //Getting the seed iMotifs for this threshold IMseed = getSeedIM(shareInt,*pSize,thr); //Adding the new seeds (if any) to those obtained from previous rounds... if (!IMseed.size()) { IMseed.clear(); vector().swap(IMseed); //This is how I try to free them now, size & capacity gets to 0, but the // memory is not freed... } else { IMarray.insert(IMarray.end(),IMseed.begin(),IMseed.end()); IMseed.clear(); vector().swap(IMseed); } //Fuse those iMotifs sharing thr interactors // It also deletes the IMarray before giving it the new data in the same way as I use here for IMseed processIMVector(IMarray,thr); writeIMVector(IMarray,translator,filename.str()); } return Py_BuildValue(""); } The object iMotif used here is composed by 2 sets and 3 strings just like this: (the access is done by setters and getters) class iMotif { private: //Set of the proteins that shares the iMotif with the root set proteins; //Set of the proteins to which the iMotifs interacts set interactors; //iMotifs interactors signature string MD5Interactor; //iMotifs proteins signature string MD5Proteins; //Real MD5 according to the sequences names string signature; ... } and I specified the destructor as: iMotif::~iMotif() { this->proteins.clear(); set().swap(this->proteins); this->interactors.clear(); set().swap(this->proteins); } The call to the function from python goes like this: iMotifs.IMFind(shareInt=intersections_dict, root=options.protein_problem, prefix=prefixOutFile, lowerLimit=1); where intersections_dict is a dictionary and options.protein_problem and prefixOutFile are strings. There is nothing to return from C++ to python, the result is directly printed into several files. Thanks, J From sjmachin at lexicon.net Sun Dec 7 04:46:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 7 Dec 2008 01:46:34 -0800 (PST) Subject: Python 3.0 automatic decoding of UTF16 References: <55d79070-0c11-4fb9-8cf5-b8cc7c54b5d2@v42g2000yqv.googlegroups.com> <0e37191f-3672-4313-bc5c-ffcd904e4796@k24g2000pri.googlegroups.com> Message-ID: On Dec 7, 8:15?pm, Terry Reedy wrote: > John Machin wrote: > > Here's the scoop: It's a bug in the newline handling (in io.py, class > > IncrementalNewlineDecoder, method decode). It reads text files in 128- > > byte chunks. Converting CR LF to \n requires special case handling > > when '\r' is detected at the end of the decoded chunk n in case > > there's an LF at the start of chunk n+1. Buggy solution: prepend b'\r' > > to the chunk n+1 bytes and decode that -- suddenly with a 2-bytes-per- > > char encoding like UTF-16 we are 1 byte out of whack. > Please post this on the tracker so it can get included with other io > work for 3.0.1. I'm fiddling with a short bug-demo script right now. From philip at semanchuk.com Tue Dec 2 23:29:32 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 2 Dec 2008 23:29:32 -0500 Subject: Best way to run multiple Python processes without overloading CPU or disk i/o In-Reply-To: <1228278090.29785.1287948757@webmail.messagingengine.com> References: <1228278090.29785.1287948757@webmail.messagingengine.com> Message-ID: On Dec 2, 2008, at 11:21 PM, python at bdurham.com wrote: > Is there a cross-platform way to launch multiple Python processes > and monitor CPU usage os.getloadavg() might be useful. It certainly works on *nix, don't know about Windows. The documentation doesn't mention any platform limitations. HTH Philip > and disk i/o so that the maximum number of > independent processes can be running at all times without > overloading their environment? By process I mean independent > application sessions vs. multiple threads of a single > application. I'm looking for suggestions on what Python modules > and/or techniques to use to maximize the number of processes I > can run on my system over a multi-day period. > Background: I have a large collection of data analysis scripts > that can run independently of one another. These scripts read > very large log files in a sequential manner and calculate > specific statistics. These scripts are hosted on a 8 core 64-bit > server with 48G of memory that is dedicated to running these > scripts. I am looking for a way to write a master script that > monitors system CPU and disk i/o and when there is capacity > launch another script from a pool of scripts so that I'm getting > max utilization from my hardware, eg. so that I'm running the max > number of scripts I can at any one point in time without > overwhelming the system. > The server in question is currently running Windows 2008 > Enterprise, but I have the option to switch to a 64-bit version > of Linux if there are benefits to doing so. > Thank you, > Malcolmm > -- > http://mail.python.org/mailman/listinfo/python-list From martin at v.loewis.de Wed Dec 10 01:10:52 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 10 Dec 2008 07:10:52 +0100 Subject: Compiling and installing python 2.5.2 with Visual C++ 2008 In-Reply-To: References: Message-ID: <493f5d6c$0$9126$9b622d9e@news.freenet.de> > --------------------------------------------------------- > ... > error: Python was built with Visual Studio 2003; > extensions must be built with a compiler than can generate compatible binaries. > Visual Studio 2003 was not found on this system. If you have Cygwin installed, > you can try compiling with MingW32, by passing "-c mingw32" to setup.py. > --------------------------------------------------------- > > And because I've been compiling everything needed by pivy (Coin, Qt, > SoQt, PyQt) with visual c++ 8, I decided to recompile python itself. There isn't a real installation procedure. You just copy the files by hand into the places where they belong. In the specific case, overwriting all .exe, .dll, and .pyd files in an installed directory should be sufficient. Regards, Martin From google at mrabarnett.plus.com Tue Dec 16 10:25:50 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 16 Dec 2008 15:25:50 +0000 Subject: Generator slower than iterator? In-Reply-To: References: Message-ID: <4947C87E.4020002@mrabarnett.plus.com> Federico Moreira wrote: > Hi all, > > Im parsing a 4.1GB apache log to have stats about how many times an ip > request something from the server. > > The first design of the algorithm was > > for line in fileinput.input(sys.argv[1:]): > ip = line.split()[0] > if match_counter.has_key(ip): > match_counter[ip] += 1 > else: > match_counter[ip] = 1 > > And it took 3min 58 seg to give me the stats > > Then i tried a generator solution like > > def generateit(): > for line in fileinput.input(sys.argv[1:]): > yield line.split()[0] > > for ip in generateit(): > ...the same if sentence > > Instead of being faster it took 4 min 20 seg > > Should i leave fileinput behind? > Am i using generators with the wrong aproach? > Your first design is already simple to understand, so I think that using a generator isn't necessary (and probably isn't worth the cost!). You might want to try defaultdict instead of dict to see whether that would be faster: from collections import defaultdict match_counter = defaultdict(int) for line in fileinput.input(sys.argv[1:]): ip = line.split()[0] match_counter[ip] += 1 From google at mrabarnett.plus.com Sat Dec 20 19:17:39 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 21 Dec 2008 00:17:39 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <59153e28-bf86-4158-96d9-23aa5b9f0205@j35g2000yqh.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> <59153e28-bf86-4158-96d9-23aa5b9f0205@j35g2000yqh.googlegroups.com> Message-ID: <494D8B23.8040100@mrabarnett.plus.com> r wrote: > Walter, > > Would you be kind enough to translate this code to the new syntax? > >>>> s = 'python' >>>> n = 12 >>>> f = 1.333333333 >>>> '%s %05d %0.2f' %(s,n,f) > 'python 00012 1.33' > > i want to see how casting is handled. Thanks > >>> '{0} {1:05} {2:.2}'.format(s, n, f) 'python 00012 1.3' From rdmurray at bitdance.com Sun Dec 14 05:46:51 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Sun, 14 Dec 2008 05:46:51 -0500 (EST) Subject: subprocess to pipe through several processes? In-Reply-To: References: Message-ID: On Sat, 13 Dec 2008 at 23:05, Neal Becker wrote: > How would I use suprocess to do the equivalent of: > > cat - | program_a | program_b Have you tried extending the pipe example from the manual? http://docs.python.org/library/subprocess.html#replacing-shell-pipeline --David From manu3d at gmail.com Thu Dec 18 08:49:49 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 18 Dec 2008 05:49:49 -0800 (PST) Subject: re.match() performance Message-ID: <27c0f622-782d-4d7f-9469-45ca1cff59ee@q26g2000prq.googlegroups.com> Hi everybody! I've written the code below to test the differences in performance between compiled and non-compiled regular expression matching but I don't quite understand the results. It appears that the performance difference is only around 2%, even if I run the ------------ import re import time ## Setup pattern = "(.*)" compiledPattern = re.compile(pattern) longMessage = ""+ "a" * 100000 +"" numberOfRuns = 1000 ## TIMED FUNCTIONS startTime = time.clock() for i in range(0, numberOfRuns): re.match(pattern, longMessage) patternMatchingTime = time.clock() - startTime startTime = time.clock() for i in range(0, numberOfRuns): compiledPattern.match(longMessage) compiledPatternMatchingTime = time.clock() - startTime ratioCompiledToNot = compiledPatternMatchingTime / patternMatchingTime ## PRINT OUTS print("") print(" Pattern Matching Time: " + str(patternMatchingTime)) print("(Compiled) Pattern Matching Time: " + str (compiledPatternMatchingTime)) print("") print("Ratio Compiled/NotCompiled: " + str(ratioCompiledToNot)) print("") From 5lvqbwl02 at sneakemail.com Sun Dec 7 02:29:02 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Sat, 6 Dec 2008 23:29:02 -0800 (PST) Subject: Brain going crazy with recursive functions Message-ID: <181d6cf8-8df3-46d4-9d21-197d34b3de87@d36g2000prf.googlegroups.com> I'm trying to solve the 9-tile puzzle using as functional an approach as possible. I've recently finished reading SICP and am deliberately avoiding easy python-isms for the more convoluted scheme/functional methods. The following function is trivial to do with for loops and directly accessing arrays with [] syntax. I'm trying to limit myself to the types of idioms/semantics one finds in minimal scheme, such as in SICP. I want eventually to port this to scheme, but I know python better, so that's where I'm starting. My current problem is the following. The 9-tile puzzle consists of a list of lists like this [[1,2,3],[4,5,6],[7,8,0]], where the numbers can be jumbled up. I'm looking for the location of the zero using *only* recursion and operators that are similar to car/cdr. The return value should be the row,col of the zero. For example above the return value would be (2,2). I'm also trying to define a single "linear_search(...)" function which does the search for within the row (an inner list above) and within the whole list. linear_search takes as an argument a "truth_function" which does the actual work. What's tricky is that the truth function for the array-as-a-whole is also the linear_search for a row. Once I'm in linear_search for the array, I also call linear_search for each row. The problem is the line where it says acc.insert(0,idx) looks fishy to me. It works fine and returns the row,col of the location of the zero tile, but it seems to be mutating a variable, and that's the thing I'm trying to avoid. In a sense, it's not hard enough and python is making this too easy :) (although it took a bit of mind-wrenching to get to this point. Recursion makes you either dumber or smarter, I'm not sure which). How do I accumulate the inner value of the search so it pops out at the end, without resorting to a mutable variable? I did a bit of search and the word "monad" came up, but I'm not sure what that is (I know it relates to haskell and some other purely functional stuff, but I get very lost when trying to read that stuff). def linear_search(array, truth_func, acc): # Goes through each element of array and applies truth_func. # Returns index if found, otherwise returns None def linear_search_iter(idx, truth_func, arr, acc): if arr: tf = truth_func(arr[0]) if tf or type(tf) is int: acc.insert(0,idx) return idx, acc+[idx] else: return linear_search_iter(idx+1, truth_func, arr[1:], acc) return linear_search_iter(0, truth_func, array, acc) def locate_zero(p): # Locates empty tile. Returns (r,c) tuple def find_zero_in_row(row): return linear_search(row, lambda x: x==0, acc) acc = [] ls = linear_search(p, find_zero_in_row, acc) print acc return acc locate_zero(def linear_search(array, truth_func, acc): # Goes through each element of array and applies truth_func. # Returns index if found, otherwise returns None def linear_search_iter(idx, truth_func, arr, acc): if arr: tf = truth_func(arr[0]) if tf or type(tf) is int: acc.insert(0,idx) return idx, acc+[idx] else: return linear_search_iter(idx+1, truth_func, arr[1:], acc) return linear_search_iter(0, truth_func, array, acc) def locate_zero(p): # Locates empty tile. Returns (r,c) tuple def find_zero_in_row(row): return linear_search(row, lambda x: x==0, acc) acc = [] ls = linear_search(p, find_zero_in_row, acc) print acc return acc locate_zero([[5, 3, 4], [2, 0, 1], [8, 6, 7]]) returns the correct value of [1,1]. Any suggestions please? thanks Michael From Slaunger at gmail.com Mon Dec 1 11:18:09 2008 From: Slaunger at gmail.com (Slaunger) Date: Mon, 1 Dec 2008 08:18:09 -0800 (PST) Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> Message-ID: On 1 Dec., 16:30, Nick Craig-Wood wrote: > > I wouldn't use __getattr__ unless you've got lots of attributes to > overload. ?__getattr__ is a recipe for getting yourself into trouble > in my experience ;-) > > Just do it like this... > > class PayloadOnDemand(object): > ? ? ? def __init__(self, a_file, a_file_position): > ? ? ? ? ? self._data = None > ? ? ? ? ? self.f = a_file > ? ? ? ? ? self.file_position = a_file_position > > ? ? ? @property > ? ? ? def data(self): > ? ? ? ? ? if self._data is None: > ? ? ? ? ? ? ? self._data = self.really_read_the_data() > ? ? ? ? ? return self._data > > then you'll have a .data attribute which when you read it for the > first time it will populate itself. > > If None is a valid value for data then make a sentinel, eg > > class PayloadOnDemand(object): > ? ? ? sentinel = object() > > ? ? ? def __init__(self, a_file, a_file_position): > ? ? ? ? ? self._data = self.sentinel > ? ? ? ? ? self.f = a_file > ? ? ? ? ? self.file_position = a_file_position > > ? ? ? @property > ? ? ? def data(self): > ? ? ? ? ? if self._data is self.sentinel: > ? ? ? ? ? ? ? self._data = self.really_read_the_data() > ? ? ? ? ? return self._data > > -- > Nick Craig-Wood --http://www.craig-wood.com/nick- Skjul tekst i anf?rselstegn - > > - Vis tekst i anf?rselstegn - OK, I get it. In my case I have four attributes to create when one of them is accessed, I do not know if that is a lot of attributes;-) One thing I like about the __getattr__ is that it is only called that one single time where an attempt to read a data attribute fails because the attribute name is not defined in the __dict__ of the object. With the property methology you do the value check on each get, which does not look as "clean". The property methology is also a little less arcane I guess for less experienced Python programmers to understand when re-reading the code. What kind of trouble are you referring to in __getattr__? Is it recursive calls to the method on accessing object attributes in that method itself or other complications? On a related issue, thank you for showing me how to use @property as a decorator - I was not aware of that possibility, just gotta understand how to decorate a setter and delete method as well, but I should be able to look that up by myself... -- Slaunger From sjmachin at lexicon.net Fri Dec 12 15:26:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 12 Dec 2008 12:26:34 -0800 (PST) Subject: (Very Newbie) Problems defining a variable References: <878wqlz27z.fsf@daycos.com> <7f7e8811-4043-40d4-8aa4-f44e1d255632@o4g2000pra.googlegroups.com> Message-ID: <90ef0df1-c4ee-4a69-a0d2-41b69d23058d@k36g2000pri.googlegroups.com> On Dec 13, 6:49?am, "Tim Rowe" wrote: > 2008/12/12 John Machin : > > > (4) in practice, the "default" action would not be "return 0.0"; > > perhaps something along these lines: > > > if balance < -overdraft_limit: > > ? raise Exception(...) > > That's more likely to be in the withdrawal routine You'd certainly hope that this test would appear in the withdrawal routine. > (and is probably > best not handled as an exception, because it's pretty much normal > flow). If a bank provided a service such as the one implemented by > this program, there'd be no need for it to know about overdraft limits > because it's not making actual transactions. Why would they increase > coupling unneccesarily? Yeah, you're right, much easier to return 0% interest on a negative balance [customers happy; no wear and tear on the call centre] and hope that anomalies are checked somewhere else *and* that somebody #1 is tasked with actioning the anomaly reports and that somebody #2 is keeping an eye on somebody #1. From exarkun at divmod.com Tue Dec 16 23:03:45 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 16 Dec 2008 23:03:45 -0500 Subject: Can anyone suggest a good HTTP/1.1 web client? In-Reply-To: <412038d6-81c0-4615-aab5-d3cea4093dfc@p2g2000prn.googlegroups.com> Message-ID: <20081217040345.20272.1064231101.divmod.quotient.22045@ohm> On Tue, 16 Dec 2008 18:47:41 -0800 (PST), Kottiyath wrote: > >> If you'd like to help out with the new Twisted HTTP client, that would be >> wonderful. ?Even if you can just try it out and report any problems you run >> into, that would be immensely helpful. >> >> Jean-Paul > >I would love to help out with the client. But, I am extremely tied up >at the current moment. I would be able to provide any sort of >meaningful contribution only after ~a month. I can surely try this out >and upload any bugs in the ticket you mentioned. > >Also, is there any planned date for persistent connections? If not, >that will be the first thing I will be working on after my assignment >is over - since it increasingly looks like it is essential to my system >(actually, any REST applications). Hard to predict when it will be done. Sometime in January is a possibility, but that's a guess, not a promise. :) Jean-Paul From federico at linux.com.uy Tue Dec 16 11:48:54 2008 From: federico at linux.com.uy (Federico Moreira) Date: Tue, 16 Dec 2008 13:48:54 -0300 Subject: Generator slower than iterator? In-Reply-To: <4947D788.3040508@islandtraining.com> References: <4947D788.3040508@islandtraining.com> Message-ID: The defaultdict option looks faster than the standard dict (20 secs aprox). Now i have: ############################# import fileinput import sys from collections import defaultdict match_counter = defaultdict(int) for line in fileinput.input(sys.argv[1:]): match_counter[line.split()[0]] += 1 ############################# About generators, now i get the idea of when use them and when not. Thanks MRAB, Lie and Gary. Now not only is faster but also cleaner and easy to understand =) -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Fri Dec 5 14:27:19 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 5 Dec 2008 11:27:19 -0800 (PST) Subject: slow Python 3.0 write performance? References: Message-ID: On Dec 5, 12:54?pm, Istvan Albert wrote: > Could someone run the code below on both Python 2.5 and 3.0 > > For me (on Windows) it runs over 7 times slower with Python 3.0 > > import time > > lo, hi, step = 10**5, 10**6, 10**5 > > # writes increasingly more lines to a file > for N in range(lo, hi, step): > ? ? fp = open('foodata.txt', 'wt') > ? ? start = time.time() > ? ? for i in range( N ): > ? ? ? ? fp.write( '%s\n' % i) > ? ? fp.close() > ? ? stop = time.time() > ? ? print ( "%s\t%s" % (N, stop-start) ) Ran on Windows XP virtual machine: 3.0 output: 100000 0.889999866486 200000 1.79699993134 300000 2.875 400000 3.73399996758 500000 4.71899986267 600000 5.59400010109 700000 7.04699993134 800000 7.31299996376 900000 8.375 2.5.2 output: 100000 0.156000137329 200000 0.296999931335 300000 0.640000104904 400000 0.640000104904 500000 0.78200006485 600000 0.952999830246 700000 1.13999986649 800000 1.25 900000 1.42199993134 Slowness in this exercise is confirmed on Windows XP. Mike From robert.kern at gmail.com Tue Dec 16 20:59:37 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 16 Dec 2008 17:59:37 -0800 Subject: Free place to host python files? In-Reply-To: References: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> <32599660-2393-4e18-8c48-05d64bccbbc1@t26g2000prh.googlegroups.com> Message-ID: feba wrote: > Stuff like code.google, sf.net, are more oriented towards serious > development, not just holding random apps, aren't they? There are plenty of "projects" on them which are just personal sandboxes like you are asking for. I recommend code.google.com. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sumerc at gmail.com Thu Dec 4 12:39:59 2008 From: sumerc at gmail.com (k3xji) Date: Thu, 4 Dec 2008 09:39:59 -0800 (PST) Subject: Python Runtime Method Call Binding References: <0147f396$0$20670$c3e8da3@news.astraweb.com> Message-ID: <9f2308eb-9eb9-4431-8af7-975c3e054849@e18g2000yqo.googlegroups.com> On Dec 4, 5:48?pm, Steven D'Aprano wrote: > On Thu, 04 Dec 2008 06:23:28 -0800, k3xji wrote: > > Hi, > > > Is there a way to hook a function call in python? I know __getattr__ is > > doing for variables, > > What do you mean "variables"? Do you mean attributes? > > > it is giving us a chance before a field is > > initialized. > > What field? Is a field the same as a variable, or something else? > > > Do we have same functionality for methods? > > Yes, methods are attributes too, they are reached by the exact same > mechanism as any other attribute. > > Any object with a __call__ method can be called. Normally you create > objects with a __call__ method by using def or lambda. > > > Example: > > > class Foo(object): > > ? ? def __call_method__(self, ...) # just pseudo > > ? ? ? ? print 'A method is called in object...' > > > f = Foo() > > f.test_method() > > > I think you understand my point. > > I wish I did. It might have helped if you actually showed the expected > output of your "test_method", instead of expecting us to *guess* what you > expect to happen. > > I'm going to guess what you mean, and show you one possible solution. > Read it carefully: it shows three examples of __getattr__, starting from > the simplest to the relatively complicated. > > class Parrot(object): > ? ? def __getattr__(self, name): > ? ? ? ? if name == "colour": > ? ? ? ? ? ? return "red" > ? ? ? ? elif name == "talk": > ? ? ? ? ? ? return lambda x: "Hi, I'm %s the talking parrot" % x > ? ? ? ? elif name == "speak": > ? ? ? ? ? ? class Birdy(object): > ? ? ? ? ? ? ? ? def __init__(self, name): > ? ? ? ? ? ? ? ? ? ? self.name = name > ? ? ? ? ? ? ? ? def __call__(self): > ? ? ? ? ? ? ? ? ? ? return "I'm the talking Parrot %s" % self.name > ? ? ? ? ? ? return Birdy('Fred') > ? ? ? ? else: > ? ? ? ? ? ? raise AttributeError > > And in use: > > >>> p = Parrot() > >>> p.colour > 'red' > >>> p.talk ?# get the attribute "talk" > > at 0x81fab1c> > > >>> p.talk("Fred") ?# call the attribute (method) "talk" > > "Hi, I'm Fred the talking parrot" > > >>> p.speak > > <__main__.Birdy object at 0x820076c>>>> p.speak() > > "I'm the talking Parrot Fred" > > -- > Steven Thank you for all the answers. I have given a bad example but got great answers. So let me clarify my problem again. I think "decorator of Bruno" and the "third example of Steven" is what I am looking for. Steven you embed a callable object in __getattr__ to accomplish what I want. But my problem: My problem is that I have a very-multithreaded application that I want to profile dynamically. And I want to see how many functions are called/how much time spent on them.(I tried Profilers but lack of multithreading support I cannot do what I want to do.) So, from your answers above, if I use a decorator I will not be able to understand that the function has finished processing. And if I use the "callable object" Steven's third solution, I will need to convert every function I want to profile to a callable object. I think problem is clarified now. Maybe you have other suggestions? Thanks, From rt8396 at gmail.com Tue Dec 30 11:15:17 2008 From: rt8396 at gmail.com (r) Date: Tue, 30 Dec 2008 08:15:17 -0800 (PST) Subject: Parsing Excel spreadsheets References: <6a54de23-bea4-40c7-ad7c-22c6eba4bd8a@z6g2000pre.googlegroups.com> Message-ID: <4894d0fe-a238-4675-9e79-0b0755c001e8@y1g2000pra.googlegroups.com> On Dec 30, 10:07?am, "andyh... at gmail.com" wrote: > Hi, > > Can anybody recommend an approach for loading and parsing Excel > spreadsheets in Python. Any well known/recommended libraries for this? > > The only thing I found in a brief search washttp://www.lexicon.net/sjmachin/xlrd.htm, > but I'd rather get some more input before going with something I don't > know. > > Thanks, > Andy. xlrd(read only) also see pyExcelerator From Russ.Paielli at gmail.com Sat Dec 6 19:42:15 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 6 Dec 2008 16:42:15 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> Message-ID: <845f784f-8dcd-4f18-ae78-3f528f179b3e@r15g2000prd.googlegroups.com> > But it's ugly. ?No amount of rationalization will make it not ugly. The dollar sign is ugly? I beg to differ. From stef.mientki at gmail.com Sun Dec 21 19:24:38 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 22 Dec 2008 01:24:38 +0100 Subject: Beep In-Reply-To: References: Message-ID: <494EDE46.20602@gmail.com> Jeffrey Barish wrote: > I use sys.stdout.write('\a') to beep. It works fine on Kubuntu, but not on > two other platforms (one of which is Ubuntu). I presume that the problem > is due to a system configuration issue. Can someone point me in the right > direction? Thanks. > I started a thread about this issue acouple of weeks ago, look for "how to get a beep, OS independent ?" The best way seems to use something like PyGame. cheers, Stef From andre.roberge at gmail.com Sun Dec 7 08:39:26 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sun, 7 Dec 2008 05:39:26 -0800 (PST) Subject: python book for non technical absolute beginner References: <493a7c6a$0$973$426a34cc@news.free.fr> Message-ID: On Dec 6, 9:21?am, News123 wrote: > Hi, > > One of my 'non technical' friends complained about knowing nothing at > all about programming (though using computers regularly for mails / web > browsing / googling and downloading / cropping photos ) > > He wants to play a little with programming to stimulate parts of his > otehrwise idle brain cells. ;-) Normally it's more the social science / > linguistic parts being exercised, > > I thought python might be a nice language for this > > No my question does anybody know a nice beginners book (or a learning CD > or on line tutorial)? Ideally it shouldn't be too serious and have a lot > of small nice mini-examples > > thanks in advance for any suggestions hints > > bye > > N For something completely different, try http://rur-ple.sourceforge.net/ It's Karel the robot, using only Python, and comes with a whole bunch of lessons and exercises. Andr? From torppa at staff.megabaud.fi Mon Dec 29 11:30:42 2008 From: torppa at staff.megabaud.fi (Jarkko Torppa) Date: Mon, 29 Dec 2008 16:30:42 GMT Subject: multiprocessing vs thread performance References: Message-ID: On 2008-12-29, mk wrote: > janislaw wrote: > >> Ah, so there are 100 processes at time. 200secs still don't sound >> strange. > > I ran the PEP 371 code on my system (Linux) on Python 2.6.1: > > Linux SLES (9.156.44.174) [15:18] root ~/tmp/src # ./run_benchmarks.py > empty_func.py > > Importing empty_func > Starting tests ... > non_threaded (1 iters) 0.000005 seconds > threaded (1 threads) 0.000235 seconds > processes (1 procs) 0.002607 seconds > > non_threaded (2 iters) 0.000006 seconds > threaded (2 threads) 0.000461 seconds > processes (2 procs) 0.004514 seconds > > non_threaded (4 iters) 0.000008 seconds > threaded (4 threads) 0.000897 seconds > processes (4 procs) 0.008557 seconds > > non_threaded (8 iters) 0.000010 seconds > threaded (8 threads) 0.001821 seconds > processes (8 procs) 0.016950 seconds > > This is very different from PEP 371. It appears that the PEP 371 code > was written on Mac OS X. On the PEP371 it says "All benchmarks were run using the following: Python 2.5.2 compiled on Gentoo Linux (kernel 2.6.18.6)" On my iMac 2.3Ghz dualcore. python 2.6 iTaulu:src torppa$ python run_benchmarks.py empty_func.py Importing empty_func Starting tests ... non_threaded (1 iters) 0.000002 seconds threaded (1 threads) 0.000227 seconds processes (1 procs) 0.002367 seconds non_threaded (2 iters) 0.000003 seconds threaded (2 threads) 0.000406 seconds processes (2 procs) 0.003465 seconds non_threaded (4 iters) 0.000004 seconds threaded (4 threads) 0.000786 seconds processes (4 procs) 0.006430 seconds non_threaded (8 iters) 0.000006 seconds threaded (8 threads) 0.001618 seconds processes (8 procs) 0.012841 seconds With python2.5 and pyProcessing-0.52 iTaulu:src torppa$ python2.5 run_benchmarks.py empty_func.py Importing empty_func Starting tests ... non_threaded (1 iters) 0.000003 seconds threaded (1 threads) 0.000143 seconds processes (1 procs) 0.002794 seconds non_threaded (2 iters) 0.000004 seconds threaded (2 threads) 0.000277 seconds processes (2 procs) 0.004046 seconds non_threaded (4 iters) 0.000005 seconds threaded (4 threads) 0.000598 seconds processes (4 procs) 0.007816 seconds non_threaded (8 iters) 0.000008 seconds threaded (8 threads) 0.001173 seconds processes (8 procs) 0.015504 seconds -- Jarkko Torppa, Elisa From pruebauno at latinmail.com Thu Dec 4 13:43:03 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Thu, 4 Dec 2008 10:43:03 -0800 (PST) Subject: Good introductory book? References: Message-ID: On Dec 3, 9:44 am, "Ken D'Ambrosio" wrote: > Hi, all. I'm getting ready to do some projects in Python, and I've cut my > teeth a little bit, but I've found the "Learning|Programming Python" books > from O'Reilly to be more-or-less useless (to my surprise -- I'm usually an > O'Reilly fan). I really, really like "Python Essential Reference", but > it's -- well, more of a reference than an intro. So, an introductory text > that actually assumes some previous programming experience (as opposed to > "Learning Python" which must be the most slowly-paced programming book > ever) would be terrific. > > Thanks for your suggestions! > > -Ken I had the same experience as you had and almost gave up on Python. I had programmed in other languages before and found the Programming Python book very tedious to read. I just wanted to learn the syntax and library to start writing my own stuff. Luckily, I found Guido's 12 page tutorial (http://www.python.org/doc/2.5.2/tut/tut.html) and that plus the online library reference and Google was everything I ever needed since then. That said I looked at O'Reilly's "Python in a Nutshell" and I thought it was really good. It is a mix between introduction, language and library reference. I should have gotten that instead of Learning/Programming when I started and I probably would have been much happier. From Graham.Dumpleton at gmail.com Sat Dec 6 05:34:07 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Sat, 6 Dec 2008 02:34:07 -0800 (PST) Subject: mod_python and files directory References: Message-ID: On Dec 6, 1:52?am, "mete bilgin" wrote: > Hi all, > I try to make a websevice with python and mod_python. ? try to make a po > files, but i can not reach them in the page. When i ask the page like " > os.listdir('.') " but i want to get files directory, what can i do? sorry > for my bad describe of that. Thanks a lot... The current working directory in Apache can be anything. You must supply an absolute path to all directories/files you are trying to access/use. Graham From callen314 at gmail.com Tue Dec 2 15:44:10 2008 From: callen314 at gmail.com (Craig Allen) Date: Tue, 2 Dec 2008 12:44:10 -0800 (PST) Subject: Confused about class relationships References: Message-ID: <5d4b15f9-3aa1-4370-b8f8-6393b0b5fa39@40g2000prx.googlegroups.com> what you have is a totally acceptable factory system. Not sure why you are using a generator, but that's another matter. I agree with the previous replies regarding inheritance... this is not a case for inheritance. You could, however, have Bar be a borg with the Bar factory built in as a class method to the Bar class itself if you want the whole job done by one component. Questions to lead to or away from that: will Engine every create things besides Bars? From steve at REMOVE-THIS-cybersource.com.au Wed Dec 17 20:15:36 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Dec 2008 01:15:36 GMT Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> <175fa5d5-f345-47b8-a686-e0e36e1b99e9@q37g2000vbn.googlegroups.com> <39eec12b-d7cc-44b5-aa65-bfa559dcba05@n33g2000pri.googlegroups.com> Message-ID: <01599b9a$0$20656$c3e8da3@news.astraweb.com> On Wed, 17 Dec 2008 10:20:21 -0800, walterbyrd wrote: > On Dec 17, 10:00?am, r wrote: >> When writing >> procedural code how would you like it if vars inside functions were >> automatically global. Your code with be blowing chunks in no time. > > That was my point - I consider python's ordinary use of lexical scoping > to be a good thing, and I was wondering why this "good thing" was not > used in classes, as well as outside of classes. But it is. You're mistaking lexical scoping for object attribute access. The rules for lexical scoping inside a class are (almost) the same as they are for inside a function: def parrot(breed): def message(colour): return "The %s %s has beautiful plumage." % (breed, colour) return message("Blue") class Parrot: def parrot(self, breed): def message(colour): return "The %s %s has beautiful plumage." % (breed, colour) return message("Blue") And in use: >>> parrot("Norwegian") 'The Norwegian Blue has beautiful plumage.' >>> p = Parrot() >>> p.parrot("Swedish") 'The Swedish Blue has beautiful plumage.' Notice that to have lexical scoping work, you actually have to nest the functions. Otherwise they are in different scopes. This might lead you believe you can do this: class Parrot2: colour = "Blue" def parrot(self, breed): return "The %s %s has beautiful plumage." % (breed, colour) >>> p = Parrot2() >>> p.parrot("Norwegian") Traceback (most recent call last): File "", line 1, in File "", line 4, in parrot NameError: global name 'colour' is not defined What's going on? Why doesn't the parrot method see the name "colour" in the class scope? The reason is that the class scope is deliberately left out of the nested scope chain. This was a design decision from when nested scopes were introduced: "An alternative would have been to allow name binding in class scope to behave exactly like name binding in function scope. This rule would allow class attributes to be referenced either via attribute reference or simple name. This option was ruled out because it would have been inconsistent with all other forms of class and instance attribute access, which always use attribute references. Code that used simple names would have been obscure." http://www.python.org/dev/peps/pep-0227/ So inside the method, you need to refer to Parrot.colour (or thanks to the rules of attribute inheritance, self.colour). Classes could be closures, but that could radically change the way methods and classes work. Depending on design decisions, it might require huge changes to the Python compiler. How would it change the existing lexical scoping in factory functions? def factory(colour): class Parrot: def parrot(self, breed): return "The %s %s has beautiful plumage." % (breed, colour) return Parrot >>> redparrot = factory("Red")() >>> redparrot.parrot("Swedish") 'The Swedish Red has beautiful plumage.' Consider a hypothetical Python with classes included in the lexical scoping: class Parrot3: colour = "Blue" def parrot(self): colour = "Red" What should method parrot do? I can think of at least three possibilities: * create a local name colour inside the method scope; * change the class attribute Parrot3.colour to "Red"; * create an instance attribute self.colour. Whatever solution you come up with, there is potential inconsistency with other parts of the language. -- Steven From skip at pobox.com Sat Dec 27 16:09:04 2008 From: skip at pobox.com (skip at pobox.com) Date: Sat, 27 Dec 2008 15:09:04 -0600 Subject: [2.4.4] creating a datetime.datetime from an XML xs:dateTime In-Reply-To: <5fa6c12e0812271255l4f4893e8w9f96e9ace73ea50c@mail.gmail.com> References: <5fa6c12e0812271208x4baccaedk262e51becb6e2076@mail.gmail.com> <18774.36465.346262.883182@montanaro-dyndns-org.local> <5fa6c12e0812271255l4f4893e8w9f96e9ace73ea50c@mail.gmail.com> Message-ID: <18774.39280.365281.768302@montanaro-dyndns-org.local> martin> is that http://labix.org/python-dateutil, I'll have a look at martin> it. Yup. PyPI: http://pypi.python.org/pypi/python-dateutil/1.4.1 Skip From kermit.mei at gmail.com Thu Dec 11 13:03:46 2008 From: kermit.mei at gmail.com (Kermit Mei) Date: Fri, 12 Dec 2008 02:03:46 +0800 Subject: How can I understan the "for" here? In-Reply-To: <20081211100312.9d68eeab.darcy@druid.net> References: <49412744.8040301@gmail.com> <20081211100312.9d68eeab.darcy@druid.net> Message-ID: <49415602.8030009@gmail.com> D'Arcy J.M. Cain wrote: > On Thu, 11 Dec 2008 22:44:20 +0800 > Kermit Mei wrote: > >> >>> ["%s=%s" % (k, v) for k, v in params.items()] >> ['pwd=secret', 'database=master', 'uid=sa', 'server=mpilgrim'] >> >> I can't understand the second sentence because of the "for ... in". >> I consider that the syntactics of "for" should be: >> >> for k,v in params.items(): >> > > I think you are binding ':' here too tightly to the 'for' construct in > your mind. The for construct is "for in " > which can be used as : in block > constructs. The above is not a block construct but a list > comprehension so it follows different rules. > > Yes, I see. Thanks you all. From dotancohen at gmail.com Wed Dec 3 21:13:51 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 4 Dec 2008 04:13:51 +0200 Subject: RELEASED Python 3.0 final In-Reply-To: References: Message-ID: <880dece00812031813t78ec560cy69dd3710fbd4c2a9@mail.gmail.com> On this page: http://www.python.org/download/releases/3.0/ The text "This is a proeuction release" should probably read "This is a production release". It would give a better first impression :) -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-??-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From gregsaundersemail at gmail.com Sun Dec 14 21:22:43 2008 From: gregsaundersemail at gmail.com (Greg) Date: Sun, 14 Dec 2008 18:22:43 -0800 (PST) Subject: Python User Group - Calgary, Alberta, Canada Message-ID: <097b1d93-cf9d-42e9-a2a2-2fb3b231970e@w24g2000prd.googlegroups.com> Hi all, this is just a brief announcement regarding the resurrection of the Python User Group in Calgary, Alberta, Canada. Our first meeting will be on Wednesday, January 14, 2009. Our official web site (albeit requiring a lot of work): http://www.pythoncalgary.com/ We have a mailing list set up at: http://groups.google.ca/group/pythoncalgary/ Calendar of Events: http://www.google.com/calendar/hosted/pythoncalgary.com/embed?src=admin%40pythoncalgary.com&ctz=America/Edmonton If you live in our around the Calgary area, please join the mailing list and consider coming to our inaugural meeting in January. Venue TBA. Thanks Greg From robert.kern at gmail.com Sun Dec 7 16:32:53 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 07 Dec 2008 15:32:53 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Rasmus Fogh wrote: > Current behaviour is both inconsistent and counterintuitive, as these > examples show. > >>>> x = float('NaN') >>>> x == x > False Blame IEEE for that one. Rich comparisons have nothing to do with that one. >>>> ll = [x] >>>> x in ll > True >>>> x == ll[0] > False > >>>> import numpy >>>> y = numpy.zeros((3,)) >>>> y > array([ 0., 0., 0.]) >>>> bool(y==y) > Traceback (most recent call last): > File "", line 1, in > ValueError: The truth value of an array with more than one element is > ambiguous. Use a.any() or a.all() >>>> ll1 = [y,1] >>>> y in ll1 > True >>>> ll2 = [1,y] >>>> y in ll2 > Traceback (most recent call last): > File "", line 1, in > ValueError: The truth value of an array with more than one element is > ambiguous. Use a.any() or a.all() > > Can anybody see a way this could be fixed (please)? I may well have to > live with it, but I would really prefer not to. Make a concrete proposal for fixing it that does not break backwards compatibility. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From gagsl-py2 at yahoo.com.ar Fri Dec 26 07:08:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 26 Dec 2008 10:08:02 -0200 Subject: SyntaxError: encoding problem: with BOM References: <6res8tF1do1sU1@mid.uni-berlin.de> <400f176b-bd9a-4f26-b01b-1aa7c7dcf5ac@z6g2000pre.googlegroups.com> <6rf6m1F1e0f8U1@mid.uni-berlin.de> <26e21f3f-ded1-48ca-8897-2ebd05dd07ad@w39g2000prb.googlegroups.com> Message-ID: En Thu, 25 Dec 2008 11:55:16 -0200, NoName escribi?: > Error > ---- > C:\Documents and Settings\Ra\??????? ????>11.py > File "", line 1 > SyntaxError: encoding problem: with BOM > > No error > ---- > C:\Documents and Settings\Ra\??????? ????>python 11.py > test > > Error when russian symbols in full path to py-script. > Is it Python bug? or i need to modify some registry keys? Yes, it's a bug. The encoding declaration may be anything, ascii, even an inexistent codec will trigger the bug. Any non-ascii character in the script name or path provokes then a SyntaxError when the script is executed directly. As a workaround, avoid using any Russian characters in directory names or script file names, or invoke them always using "python xxx.py", not directly. > OS: WinXP SP3 Russian. > Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit > (Intel)] on win32 My tests were on WinXP SP3 Spanish. See http://bugs.python.org/issue4747 -- Gabriel Genellina From honey33145 at gmail.com Thu Dec 4 00:55:41 2008 From: honey33145 at gmail.com (navneet khanna) Date: Thu, 4 Dec 2008 11:25:41 +0530 Subject: Access functions in dll class Message-ID: Hello Everybody I am able to import the dll and able to access the class of the dll. But when I am trying to access the methods in the dll its showing error. #Class1 is the class in dll and next is the function. Class1.Bin_To_Dec("11") Traceback (most recent call last): File "", line 1, in Class1.Bin_To_Dec("11") TypeError: No method matches given arguments Please help me to find out where am i wrong? Do I need to create object of dll class and then access it? If yes then how can I access it? Thanks Navneet -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Fri Dec 12 14:36:12 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 12 Dec 2008 19:36:12 +0000 Subject: Removing None objects from a sequence References: Message-ID: alex23 writes: > Rather than a list comprehension, use a generator expression: > > for item in (x for x in sequence if x is not None): > do_something(x) I much prefer for item in sequence: if x is not None: do_something(x) -- Arnaud From petite.abeille at gmail.com Sun Dec 14 08:07:50 2008 From: petite.abeille at gmail.com (Petite Abeille) Date: Sun, 14 Dec 2008 14:07:50 +0100 Subject: [OT] Alternative web server scripting language Message-ID: <3D39640F-3248-428F-B92A-2101A225C8E0@gmail.com> Hello, Now that Lua [1] appears as a native scripting language in more [2] and more [3] mainstream web servers, here is an example of a web server written in Lua: http://svr225.stepx.com:3388/a The wiki demo sports content from the 2008/9 Wikipedia Selection, containing about 5500 articles, accessible through full text search: http://svr225.stepx.com:3388/search?q=python An index, timeline and recent changes navigation is provided to facilitate article retrieval: http://svr225.stepx.com:3388/index/a http://svr225.stepx.com:3388/date/2008 http://svr225.stepx.com:3388/recent The wiki content is accessible as an Atom feed: feed://svr225.stepx.com:3388/search?q=brazil feed://svr225.stepx.com:3388/index/a feed://svr225.stepx.com:3388/date/2008 feed://svr225.stepx.com:3388/recent Or as a WebDAV repository: dav://svr225.stepx.com:3388/ Kind regards, -- PA. http://alt.textdrive.com/nanoki/ [1] http://www.lua.org/about.html [2] http://svn.apache.org/repos/asf/httpd/mod_wombat/trunk/README [3] http://redmine.lighttpd.net/wiki/1/Docs:ModMagnet From google at mrabarnett.plus.com Sun Dec 7 21:40:58 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 08 Dec 2008 02:40:58 +0000 Subject: Infinite hangup when using CGI sys.stdin.read() In-Reply-To: References: Message-ID: <493C893A.5080103@mrabarnett.plus.com> pacsciadmin at gmail.com wrote: > I maintain a CGI framework named PyTin, and while previously the > developer was only allowed to access GET and POST by cgi.FieldStorage. > I'm trying to add code to my request gatherer that looks like: > > 1. request.rawpost = StringIO() # Just normal StringIO > 2. request.rawpost.write(sys.stdin.read()) > 3. request.rawpost.seek(0) > 4. request.fields = cgi.FieldStorage(fp=request.rawpost) > 5. request.rawpost.seek(0) > > Obviously, my actual code doesn't have the line numbers. > > I'm testing it out on the CGIHTTPRequestHandler with BaseHTTPServer, > and whenever my test script reaches line 2, it hangs up. It doesn't > spit out a traceback, or stop in less than a minute, whenever I use > sys.stdin.read(). Can anyone explain what is going on? > sys.stdin.read() will read until EOF. If stdin is connected to a file when the entire file will be read. If stdin is connected to the console then it will return when it reaches the end of the input (will that ever happen?) or the EOF marker, such as ctrl-Z in Windows or ctrl-D (I think) in *nix. From steve at holdenweb.com Fri Dec 12 11:13:13 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Dec 2008 11:13:13 -0500 Subject: var or inout parm? In-Reply-To: <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> Message-ID: sturlamolden wrote: > On Dec 12, 3:54 pm, Steve Holden wrote: [...] >> The interpreter "should not" have a GIL. > >> The tuple "should" check that >> it is actually being mutated. How? > > In Python it would be something similar to: > > def __setitem__(self, index, value): > if _buf[index] is not value: # given that _buf is the tuple's > internal buffer > raise TypeError, 'tuple' object does not support item > assignment > > It should be the tuple's __setitem__ that was invoked here, not > __iadd__, or the parser is faulty. > OK, so now you are proposing to alter the parser, and possibly the implementation of the INPLACE_ADD opcode in eval.c, so can you give us the patch for those, please? This is exactly the point I was trying to make. It's easy to stand on the sidelines and make sensible- or even intelligent-sounding suggestions about how to change Python. But inside the interpreter there's a maze of twisty little passages all alike (or similar complexity), and hand-waving doesn't get you anywhere. Discussion of such behavior as a "bug" is also pejorative, since the current semantics are the way they are by design. You are therefore disagreeing with the design of Python rather than discussing a bug in its implementation. That also raises the issues of how you get Jython and IronPython to implement the same semantics, and whether you care about the millions of lines of code that already assumes the current behavior. You've got a lot of work to do ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From torriem at gmail.com Fri Dec 19 14:54:28 2008 From: torriem at gmail.com (Michael Torrie) Date: Fri, 19 Dec 2008 12:54:28 -0700 Subject: IMAP: How to implement GMail-like threaded conversations view In-Reply-To: References: Message-ID: <494BFBF4.1000205@gmail.com> Martin wrote: > Currently I am trying to get used to Python's imaplib and email > modules. > I'like to create a webmail client simmilar to GMail. This is off-topic, but why on earth would you want to emulate Gmail's conversation views? It's horrible and a very broken way of viewing e-mail threads. Compared the normal, threaded view of, say the discussions on this list to the view that Gmail gives you. For conversations of more than half a dozen posts, Gmail's view is unnavigatable. Suppose I want to break into a discussion that's already dozens of posts long. With a real threaded view I can easily see the flow of the conversation, grab random posts, then maybe read their parent or grandparent posts. Looking at the rest of your e-mail, I can see that maybe you do want to have real threads rather than the google conversation view which removes all structure. > > My Questions: > a) Is there any feature hidden in Python's built-in modules (imaplib, > email) that already can group all my mails into threads? Each e-mail has a referral number that refers to the parent email. Just keep track of these in a structure and you can easily build a nice tree of the thread. > > b) If not a... what would be the best way to implement this? > > I can think of two approaches: > b.1) Use the "References:" field of the messages in order to find out > which messages are related to each other. Yes. This is absolutely the right way to do it. > > I tried a first implementation which works quite well but I don't know > if there can occur situations where one message is related to two > parents. Also I don't know what happens if someone is too lazy to type > my address. He might click at "Reply", delete topic and old mail-text > and compose a new mail. Theoretically his mail client would set the > "References:" field accordingly never the less, wouldn't it? Therefore > my mail client would consider that completely new mail as part of an > older conversation. In this case, a lazy user is a lazy user. Probably best to encourage people to use better etiquette when using e-mail. > > The thoughts above might lead to the second approach: > > b.2) Use the "Subject:" field of the messages. Horribly broken. Thunderbird does this and it drives me crazy. I often get messages months apart that happen to have a common subject line, even though they aren't the same thread or conversation. I don't want a new message, which does not refer to the old message in any way, to attach itself to my 6-month old message and force me to scroll down through potentially hundreds of e-mails to find the stupid thing. No, the RFCs are there for a reason. They bring sanity to the chaos. Anything else is madness. And the fact the Outlook doesn't do proper referral fields just infuriates me. Sigh. From jwkenne at attglobal.net Wed Dec 10 17:47:49 2008 From: jwkenne at attglobal.net (John W Kennedy) Date: Wed, 10 Dec 2008 17:47:49 -0500 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: <49404775$0$4893$607ed4bc@cv.net> Xah Lee wrote: > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, > you'll have 50 or hundreds lines. C: #include #include void normal(int dim, float* x, float* a) { float sum = 0.0f; int i; float divisor; for (i = 0; i < dim; ++i) sum += x[i] * x[i]; divisor = sqrt(sum); for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; } Java: static float[] normal(final float[] x) { float sum = 0.0f; for (int i = 0; i < x.length; ++i) sum += x[i] * x[i]; final float divisor = (float) Math.sqrt(sum); float[] a = new float[x.length]; for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor; return a; } -- John W. Kennedy "Never try to take over the international economy based on a radical feminist agenda if you're not sure your leader isn't a transvestite." -- David Misch: "She-Spies", "While You Were Out" From a at a.aa Mon Dec 15 15:23:26 2008 From: a at a.aa (a) Date: Mon, 15 Dec 2008 20:23:26 GMT Subject: Python plugin for Netbeans Message-ID: <21z1l.218500$FR.506807@twister1.libero.it> Netbeans added a python plugin to its plugin repository. Do you tried it? What do you think about this plugin? From sonynamratha2009 at gmail.com Wed Dec 24 15:32:43 2008 From: sonynamratha2009 at gmail.com (sony) Date: Wed, 24 Dec 2008 12:32:43 -0800 (PST) Subject: electronics Message-ID: http://allelectronicss.blogspot.com/2008/12/mobile-phone.html http://allelectronicss.blogspot.com/2008/12/electric-car.html http://allelectronicss.blogspot.com/2008/12/electric-vehicles.html http://allelectronicss.blogspot.com/2008/12/washing-machine.html http://allelectronicss.blogspot.com/2008/12/microwave-oven.html http://allelectronicss.blogspot.com/2008/12/fan.html http://allelectronicss.blogspot.com/2008/12/iron-box.html http://allelectronicss.blogspot.com/2008/12/refrigerator.html http://allelectronicss.blogspot.com/2008/12/electric-heater.html http://allelectronicss.blogspot.com/2008/12/stove.html http://allelectronicss.blogspot.com/2008/12/bulb.html http://allelectronicss.blogspot.com/2008/12/tape-recorder.html http://allelectronicss.blogspot.com/2008/12/plasma.html http://allelectronicss.blogspot.com/2008/12/television.html http://allelectronicss.blogspot.com/2008/12/ipod.html http://allelectronicss.blogspot.com/2008/12/laptop.html http://allelectronicss.blogspot.com/2008/12/computer.html From your.master at gmail.com Thu Dec 11 16:32:00 2008 From: your.master at gmail.com (Brandon) Date: Thu, 11 Dec 2008 13:32:00 -0800 (PST) Subject: dictionary idiom needed References: <383976cf-53fb-48e4-b028-8f568468ce77@r36g2000prf.googlegroups.com> <0c4950c1-4833-40c7-ac19-260b61d5289f@k24g2000pri.googlegroups.com> <7c55c59b-cebe-4f4e-ae40-282ae7e005bf@d42g2000prb.googlegroups.com> Message-ID: > >>> d = defaultdict(lambda: defaultdict(int)) > > Arnaud Ah... so that's what lambdas are for. Many thanks! Brandon From tjreedy at udel.edu Mon Dec 1 15:02:48 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Dec 2008 15:02:48 -0500 Subject: Two attributes! Why? In-Reply-To: References: <76bc5df8-26fd-4e2d-a134-c5d13ea3b39a@n10g2000yqm.googlegroups.com> <0140c948$0$20670$c3e8da3@news.astraweb.com> Message-ID: Emanuele D'Arrigo wrote: > On Nov 29, 5:21 am, Steven D'Aprano cybersource.com.au> wrote: >> This is a side-effect of name-mangling. Double-underscore names are only >> mangled when they are referred to directly as attributes, not when they >> are passed to setattr, getattr etc. Those functions don't do any name >> mangling. Even as attributes, they are only mangled within the class definition. "__* Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between ?private? attributes of base and derived classes. See section Identifiers (Names). " Class-private is intended to mean 'private', not known and not used outside the class definition. I believe the 'mangled' form is intentionally not documented. > Ah! That make sense! Thank you! > > It's a bit of an obscure thing right now. I don't see mention of it in > the description of the setattr/getattr built-ins: > http://docs.python.org/library/functions.html > Wouldn't be good to have a hint of the issue there? I think not. The functions tell the truth when they say 'no such attribute' Any mention might suggest that trying to access private names from outside the class is a sensible thing to do. Perhaps the __* doc quoted above could be improved. Is anything there unclear? Terry Jan Reedy From torriem at gmail.com Fri Dec 19 12:25:30 2008 From: torriem at gmail.com (Michael Torrie) Date: Fri, 19 Dec 2008 10:25:30 -0700 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <494BD90A.6000206@gmail.com> r wrote: > if 3.0 looks like... print( "{0}={1}".format('this',99)) , WTF... > thats retarded and looks like Ruby code. Thats not intuitive thats > madness! What happens when you need a conversion to string from an > integer, more code?? My faith is slipping. Have the python Gods gone > mad??. Please tell me i am wrong. You are wrong. > > Pythons likeness to C is one of its great powers. I always thought of > Python as an intuitive way to write C code. I have to confess, I have no idea what you are talking about. I have never ever seen Python as an intuitive way to write C code. That's kind of bizarre. > I am sticking with 2x(which i had planned to do anyway) I have heard > of nothing significant enough to compel me to make the change yet. And > with that example from 3.0, i am really setting my ways now. i may > have to support the continuation of 2.x beyond 2.9. > Guido! please don't play Russian roulette with Python! I have loved > python all the way up through the 2.x line. And i carry a great > respect for you and your accomplishments. Python must feel at home to > a C programmer. That, i feel, is the professional following for > Python. I also feel Python is a gateway to the C language for n00b > programmers. Let Ruby have the Perl programmers, we don't need them! > > Excuse me, I think i am going to cry now :( Okay, you're welcome to. So funny that now that Python 3.0 is actually released we have people acting all surprised like they've never seen any of the new features in Python 3.0 coming. However these features have been discussed for years! And debated! Personally the new string formatter is sorely needed in Python. And they way it has been implemented is a thing of beauty. Basically the burden of formatting strings has been moved from the print statement/function to the objects themselves. Furthermore, the new {} notation allows many, many more options for formatting to be used. Want to display a floating point number with $#.## notation, and ($#.##) for negative? It's all now possible. Couldn't be done before. Want to have the ability to format your own custom object in a particular way when printing with print()? Just define a __format__ method in your object. print() will ask it to format itself. In short, this is a huge improvement, and backwards compatibility is preserved for the 2.x style for those that wish it. From bdesth.quelquechose at free.quelquepart.fr Sun Dec 14 12:01:33 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 14 Dec 2008 18:01:33 +0100 Subject: Need help improving number guessing game In-Reply-To: <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> Message-ID: <494549a3$0$22507$426a74cc@news.free.fr> feba a ?crit : > #!/usr/bin/python > #Py3k, UTF-8 > > import random > > def setup(): > #global target, guess, a, b > #a, b make minimum, maximum. Can be adjusted. > a, b = 1, 99 > target = random.randint(a, b) > return a, b, target Seems ok. You may want to use arguments with default values for a and b (and possibly to use more meaningfull names): def setup(mini=1, maxi=99) # sanity check if mini >= maxi: raise ValueError("mini must be lower than maxi") target = random.randint(mini, maxi) return mini, maxi, target > def playerswitch(player): > #Player Switch > #if player's a witch, burn her! Extra bonus point for quoting Monty Pythons !-) > if player == "P1": > player = "P2" > else: > player = "P1" > return player I'd name this one "switch_player" (most of the time, function names should be verbs) - but this is mostly a matter of personal taste !-) Minor point for a short program, but still good practice : use constants. IE : # at the top level PLAYER_1 = 1 PLAYER_2 = 2 # in your code .... if player == PLAYER_1: ... Also, you could use early returns here instead of rebinding then returning player. def switch_player(player): if player == PLAYER_1: return PLAYER_2 else: return PLAYER_1 > def youwin(pnum, player, p1sc, p2sc): I assume 'p1sc' means "player_1_score" ? If so, you may want to use a dict for scores: scores = {PLAYER_1:0, PLAYER_2:0} then... > if pnum == 1: > print("CONGRATULATIONS!") Is it really necessary to WRITE THIS IN ALL UPPERS ?-) > else: > if player == "P1": > p1sc += 1 > else: > p2sc += 1 Which would then become: scores[player] +=1 > end = "CONGRATULATIONS %s! SCORE -- P1:%s P2:%s" > print(end %(player, p1sc, p2sc)) > return p1sc, p2sc > def playagain(play): > playover = input("PLAY AGAIN? Y/N: ") > if playover.strip().lower() == "y": > play = 1 If it's meant to be 0/1 flag, Python has proper booleans too (True and False). > a, b, target = setup() > else: > print("GOOD BYE. PLAY AGAIN SOON!") > quit() It might be better to avoid exiting so brutally. Why not returning 0, none, None, None ? > return play, a, b, target > > > def guesscheck(guess, target, play, a, b, p1sc, p2sc): > if guess == target: > p1sc, p2sc = youwin(pnum, player, p1sc, p2sc) > play, a, b, target = playagain(play) > elif guess >= b: > print("NUMBER MUST BE IN RANGE") > guess = int(input("[%s-%s]%s>> " % (a, b, player))) > play, a, b, target, p1sc, p2sc = guesscheck(guess, target, > play, > a, b, p1sc, p2sc) > elif guess <= a: > print("NUMBER MUST BE IN RANGE") > guess = int(input("[%s-%s]%s>> " % (a, b, player))) > play, a, b, target, p1sc, p2sc = guesscheck(guess, target, > play, > a, b, p1sc, p2sc) > elif guess > target: > print("TOO HIGH") > b = guess > else: > print("TOO LOW") > a = guess > return play, a, b, target, p1sc, p2sc > > def guessing(a, b, player, pnum, target, p1sc, p2sc, play): > #a and b are to keep the user aware of min/max > guess = int(input("[%s-%s]%s>> " % (a, b, player))) > play, a, b, target, p1sc, p2sc = guesscheck(guess, target, play, > a, b, p1sc, p2sc) > if pnum == 2: > player = playerswitch(player) > return play, a, b, player, target, p1sc, p2sc > > #Let the show begin! You should either put this in it's own function (could be named 'main'), or at least "protect" it with an "if __name__ == '__main__':" test. > print("WELCOME TO THE SUPER NUMBER GUESSING GAME!") > pnum = int(input("1 OR 2 PLAYERS?\n> ")) > play = 1 > player = "P1" # P1 goes first > #Scores, keep track of times player guessed first. > p1sc, p2sc = 0, 0 > > #Grabs minimum, maximum, and target numbers > a, b, target = setup() > > while play == 1: > play, a, b, player, target, p1sc, p2sc \ > = guessing(a, b, player, pnum, target, p1sc, p2sc, play) > > > This is what I have now. And it looks way better than your first version. (snip) From quian.xu at stud.tu-ilmenau.de Tue Dec 23 09:51:00 2008 From: quian.xu at stud.tu-ilmenau.de (Qian Xu) Date: Tue, 23 Dec 2008 15:51:00 +0100 Subject: print to console without a line break References: Message-ID: Albert Hopkins wrote: > On Tue, 2008-12-23 at 13:18 +0000, Lie Ryan wrote: > > Probably because your stdout is line-buffered. Try: > > sys.stdout.write("Testing something...") > sys.stout.flush() # flush the stdout buffer Thanks. This works for me ^^) From google at mrabarnett.plus.com Wed Dec 10 09:57:58 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 10 Dec 2008 14:57:58 +0000 Subject: "as" keyword woes In-Reply-To: References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> Message-ID: <493FD8F6.3050803@mrabarnett.plus.com> Aaron Brady wrote: > On Dec 9, 12:40 pm, MRAB wrote: >> Aaron Brady wrote: >>> On Dec 9, 8:28 am, MRAB wrote: >>> snip >>>> In some languages (I think Delphi is one of them - it's been a while!) >>>> some words which would normally be identifiers have a special meaning in >>>> certain contexts, but the syntax precludes any ambiguity, and not in a >>>> difficult way. "as" in Python was one of those. >>>> I certainly wouldn't want something like PL/I, where "IF", "THEN" and >>>> "ELSE" could be identifiers, so you could have code like: >>>> IF IF = THEN THEN >>>> THEN = ELSE; >>>> ELSE >>>> ELSE = IF; >>>> Seehttp://en.wikipedia.org/wiki/PL/I_(programming_language). >>> snip >>> That is, 'certainly' doesn't change the meaning of your statement >>> any. You wouldn't want it, but King George III didn't want the >>> American Revolution. >> It's called emphasis. > > I just take you to have meant, then, +1 on excluding keywords from > identifiers. You said it the long way though, so I thought I missed > something deeper, that didn't come across. > IIRC, most computer languages have an LL(1) grammar, which means that when they are parsed you need to look at only the next word. If you're about to parse a statement and the next word is "IF" then you know it's an IF-statement, if it's an identifier then it's either a call or an assignment statement (OK, you don't know exactly what kind of statement it is at that point, but it works out just fine!). In the example from PL/I, "IF" could be the start of an IF-statement "IF THEN" or an assignment statement "IF = ". It's a bit more tricky for the parser as well as the programmer. Life is easier if words having special meanings are reserved. However, that doesn't mean that all special words /must/ be reserved (pragmatism beats purity). Sometimes the syntax makes it clear and unambiguous, so you can get away with not making it a reserved word. The word "as" in Python doesn't need to be reserved because the syntax precludes ambiguity, but it's the only such word in the language, so it's just tidier to make it reserved too. From bdesth.quelquechose at free.quelquepart.fr Mon Dec 15 16:53:06 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 15 Dec 2008 22:53:06 +0100 Subject: Need help improving number guessing game In-Reply-To: <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> <01564c98$0$21844$c3e8da3@news.astraweb.com> <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> Message-ID: <4946df78$0$19771$426a74cc@news.free.fr> feba a ?crit : > Alright! This is feeling more like it. > > #!/usr/bin/python > #Py3k, UTF-8 > import random > (snip) > def youwin(game): > if game['pnum'] == 1: > print("CONGRATULATIONS! IT TOOK YOU %s GUESSES" % game > ['gcount']) > else: > if game['player'] == game['player1']: > game['p1sc'] += 1 > else: > game['p2sc'] += 1 If you had initialized your "game" dict with player1 = dict(score=0) player2 = dict(score=0), game = dict( player1 = player1, player2 = player2 player = player1 # ... ) you wouldn't need the test on game['player'] == game["player1"] , and could just use: game["player"]["score"] += 1 (snip) > first off, I want to thank all of you for your help with this. I > really don't think I could've learned all of this out nearly as > quickly by reading tutorials and documentation, let alone had anything > near the grasp I have on it now. '''This''' is why I like learning by > doing. The only things I still don't really understand are .strip > ().lower(), .strip() returns a copy of the string without leading and ending whitespaces (inlcuding newlines, tabs etc). .lower() returns a copy of the string in all lowercases. Since .strip() returns a string object, you can chain method calls. " yaDDA\n".strip().lower() is just a shortcut for thestring = " yaDDA\n" tmp1 = thestring.strip() # => "yaDDA" tmp2 = tmp1.lower() # => "yadda" > and try/except/else, and I plan on looking them up before > I do anything else. In the past few hours I've gone from not having a > clue what the whole {'fred': 0, 'barney': 0} thing was about to being > able to fully understand what you're talking about, and put it into > practice Quite close... You still failed to understand how dicts could be used to replace 'if/else' statements (dict-base dispatch is very idiomatic in Python, and is also a good introduction to OO). (snip) > 5; I added the ability for it to automatically complete when there's > only one option left. I was amazed' I was actually going to ask for > advice on how to do it here. I was going to say "I was thinking (blah > blah)", but then I just typed it in, and it worked flawlessly. Yeps. That's probably why most of us here fell in love with Python: it makes simple thing simple, and tend to JustWork(tm). > 6; can anyone think of anything else to add on to/do with this game? rewrite it once again using objects instead of dicts ? Anyway, thanks for sharing your enthusiasm with us. From mr.spoon21 at gmail.com Wed Dec 17 12:14:41 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Wed, 17 Dec 2008 18:14:41 +0100 Subject: OT: Binary tree logarithms properties Message-ID: <8f67b6f80812170914m377191f4g81345ffe5d0b7f26@mail.gmail.com> Hi, I'm searching for a clear explanation of binary tree properties, expecially the ones related to logarithms. For example, I know that in a tree with 2n-1 nodes, we have log(n) levels, from 0 to log(n). So, if k is the level, the nodes on a level have indexes between 2^k and 2^(k+1)-1. For k=0 we have 2 and 3. For k=1 we have 4, 5, 6, 7 and so on. I know this after I studied some exercises on my book. Anyway there is no explanation or demonstration of these properties. I know this is not the better place to ask (or maybe it is?), but maybe someone can point me to something useful. Thanks, bye From google at mrabarnett.plus.com Mon Dec 22 12:37:52 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 22 Dec 2008 17:37:52 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <494FBE99.6050507@gmail.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <494FBE99.6050507@gmail.com> Message-ID: <494FD070.4060209@mrabarnett.plus.com> Michael Torrie wrote: > r wrote: >> Steven, >> Would you like to elaborate on -why- escaped backslashes are needed in >> strings... i waiting??? > > Some character was needed. It just happens that backslashes have been > used in this manner for composing nonprintable sequences, codes, etc. > It's only in use because someone arbitrarily picked it about 40 years > ago. Any character could have been used; any such character would still > be have to escaped. > BCPL used '*', but C, which was developed from BCPL, uses '\'. > Kind of funny that you are complaining about Python in particular when > this behavior is in almost all languages today, including Perl, Ruby, > > Don't blame python for a mistake that Microsoft made, that of choosing a > commonly-accepted escape character (long before Python was even though > of!) as their path delimiter. Fortunately sane operating systems use a > standard slash. Even Windows APIs accept forward slashes as path > delimiters. > > So really your complaint about the backslash is a bit silly. Are you > going to campaign that C# and Java also "fix" this problem by choosing > another character? > From geekmail at usenot.de Sun Dec 7 14:23:26 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sun, 7 Dec 2008 20:23:26 +0100 Subject: Importing the re module fails Message-ID: <20081207202326.4b5ab73d@usenot.de> This is a little puzzling. Using ipython: [wildemar at localhost Logstuff]$ ipython Python 2.5.2 (r252:60911, Sep 30 2008, 15:41:38) Type "copyright", "credits" or "license" for more information. [snip ipython help message] In [1]: import re This works fine. But with the regular python interpreter I get this: [wildemar at localhost Logstuff]$ python Python 2.5.2 (r252:60911, Sep 30 2008, 15:41:38) [GCC 4.3.2 20080917 (Red Hat 4.3.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/re.py", line 10, in # AB (info at pythonware.com). AttributeError: 'module' object has no attribute 'compile' What gives? Has Fedora-10 botched python or does anybody else have that problem es well? /W -- My real email address is constructed by swapping the domain with the recipient (local part). From stef.mientki at gmail.com Wed Dec 31 09:18:02 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 31 Dec 2008 15:18:02 +0100 Subject: Graphics Library with Standard Interaction Features, 2D and 3D In-Reply-To: References: <69c3eca8-5e17-49fb-8354-5fdc0bd73f9a@r15g2000prd.googlegroups.com> Message-ID: <495B7F1A.5000101@gmail.com> Maybe VPython (Visual) or Panda fits your needs. cheers, Stef From __peter__ at web.de Mon Dec 8 09:46:07 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 08 Dec 2008 15:46:07 +0100 Subject: Beginner trying to understand functions. References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> Message-ID: James Mills wrote: > On Tue, Dec 9, 2008 at 12:24 AM, cadmuxe wrote: >> i think we should use raw_input('Please enter your name: ') instead of >> input('Please enter your name: ') > > Good point :) OP: Please take notes :) I think the OP is using Python 3.0. What used to cause trouble Python 2.5.1 (r251:54863, Jul 31 2008, 23:17:43) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> input() 1/0 Traceback (most recent call last): File "", line 1, in File "", line 1, in ZeroDivisionError: integer division or modulo by zero is now the way it should be: Python 3.0 (r30:67503, Dec 4 2008, 11:26:28) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> raw_input() Traceback (most recent call last): File "", line 1, in NameError: name 'raw_input' is not defined >>> input() 1/0 '1/0' Peter From bearophileHUGS at lycos.com Sat Dec 13 09:00:09 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 13 Dec 2008 06:00:09 -0800 (PST) Subject: Removing None objects from a sequence References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> <4942E668.5030100@tim.thechases.com> <01538f0c$0$6988$c3e8da3@news.astraweb.com> Message-ID: <234b9a34-52e3-42c3-968c-f50983e51c68@e1g2000pra.googlegroups.com> Steven D'Aprano: > The algorithm is unclear: try explaining > what you are doing in English, and see how difficult it is. That algorithm is a standard one, and quite clear. Any programmer worth his/her/hir salt has to be able to understand that. I agree that the idiom with the list comp (algorithm2) is better for Python, but you have to know that algorithm1 to use it in other languages. > Now, sure, most of the work in Tim's version is executed in fast C code > instead of slow Python code. If we were programming in C, your version > might perform better relative to Tim's. Try Psyco too: from timeit import default_timer as clock def remove_nones1(alist): n = len(alist) i = j = 0 while i < n: if alist[i] is not None: alist[j] = alist[i] j += 1 i += 1 alist[j : i] = [] def remove_nones2(alist): alist[:] = [x for x in alist if x is not None] def remove_nones3(alist): for i in xrange(len(alist)-1, -1, -1): if alist[i] is None: del alist[i] def test123(data): data1 = data[:] data2 = data[:] data3 = data[:] t = clock() remove_nones1(data1) print " remove_nones1:", round(clock() - t, 2), "s" t = clock() remove_nones2(data2) print " remove_nones2:", round(clock() - t, 2), "s" t = clock() remove_nones3(data3) print " remove_nones3:", round(clock() - t, 2), "s" assert data1 == data2 == data3 assert data1 == data2 def test12(data): data1 = data[:] data2 = data[:] data3 = data[:] t = clock() remove_nones1(data1) print " remove_nones1:", round(clock() - t, 2), "s" t = clock() remove_nones2(data2) print " remove_nones2:", round(clock() - t, 2), "s" print " remove_nones3: (not tested)" assert data1 == data2 def gen_data(N): print " N:", N data = [None]*2 + range(5) + [None]*3 + range(5, 10) + [None]*4 + \ [10, None, 11, None, 12, None] data *= N data += range(N * 10) data += [None] * (N * 10) data += [None, 0] * (N * 10) data += [1] * (N * 100) return data print "Without Psyco:" test123(gen_data(1000)) test12(gen_data(30000)) print print "With Psyco:" import psyco; psyco.full() test123(gen_data(1000)) test12(gen_data(30000)) Results on a Core2 2 GHz, Python 2.6.1, latest Psyco: Without Psyco: N: 1000 remove_nones1: 0.05 s remove_nones2: 0.02 s remove_nones3: 3.04 s N: 30000 remove_nones1: 1.51 s remove_nones2: 0.62 s remove_nones3: (not tested) With Psyco: N: 1000 remove_nones1: 0.0 s remove_nones2: 0.01 s remove_nones3: 3.01 s N: 30000 remove_nones1: 0.08 s remove_nones2: 0.33 s remove_nones3: (not tested) As you see even with Psyco a (bit) lower level style of coding wins :-) In practice if that routine is important (or if it's a generic library routine that you don't know how it will be used) you use two different algorithms according to the availability of Psyco. Something like: def remove_nones4(alist): if psyco_available: n = len(alist) i = j = 0 while i < n: if alist[i] is not None: alist[j] = alist[i] j += 1 i += 1 alist[j : i] = [] else: alist[:] = [x for x in alist if x is not None] Bye, bearophile From george.sakkis at gmail.com Mon Dec 1 16:53:49 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 1 Dec 2008 13:53:49 -0800 (PST) Subject: Scanner class Message-ID: <737a0550-0b92-4f65-829e-953882d74419@y18g2000yqn.googlegroups.com> Is there any stdlib or (more likely) 3rd party module that provides a similar functionality to the java.util.Scanner class [1] ? If not, would there be any interest in porting it (with a more Pythonic API of course) or are there better alternatives ? George [1] http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html From bockman at virgilio.it Wed Dec 31 04:20:47 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: Wed, 31 Dec 2008 10:20:47 +0100 Subject: select.select and socket.setblocking In-Reply-To: References: Message-ID: <495b3970$0$11387$5fc30a8@news.tiscali.it> Jean-Paul Calderone ha scritto: > On Tue, 30 Dec 2008 19:19:08 +0100, Francesco Bochicchio > wrote: >> [snip] >> >> If you are interested in socket errors, you should >> also fill the third 'fd-set' in the select call, and after select >> returns check that fd is not in it anymore: >> >> ready = select.select( [fd],[], [fd] ) >> if fd in ready[2]: >> # raise your error here > > The third argument to select() isn't for monitoring sockets for errors. > Its > behavior is also rather platform sensitive. In general, you don't need it > at all on POSIX, but on Windows you should pass the same list for it as you > pass for the write-set, merge the results, and treat them all as writeable. > > Or use a higher-level library that deals with all the asinine details for > you. ;) > > Jean-Paul Yes, now that you mention it I remember having to do something like that on a socket library I wrote on windows ... IIRC, the send could not complete and then signal the readyness of the socket through the third argument of the select ... My experience is mostly on unices, and I usually don't use the third argument (and not often the second) but I remember having read on select manual page that it was for errors. Now both python manuals than select manual page say it is for 'exceptional conditions', without going into details ... Tx for the clarification, anyway ... Ciao ---- FB From pruebauno at latinmail.com Wed Dec 17 10:41:16 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Wed, 17 Dec 2008 07:41:16 -0800 (PST) Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> Message-ID: On Dec 17, 10:19?am, walterbyrd wrote: > For a language as well structured as Python, this seems somewhat > sloppy, and inconsistant. ?Or is there some good reason for this? > > Here is what I mean: > > def a(): > ? ? x = 99 > ? ? print x > > def b(): > ? ? print x > > a() > b() # raises an exception because x is not defined. > > However in the methods are within a class, the scoping seems to work > differently. > > class ab(): > ? ? def a(self): > ? ? ? ? self.x = 99 > ? ? ? ? print self.x > ? ? def b(self): > ? ? ? ? print self.x > > i = ab() > i.a() > i.b() # this works, why no lexical scoping? If scoping worked as you want, how, pray tell, would you define object attributes? From luismgz at gmail.com Mon Dec 29 23:35:04 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Mon, 29 Dec 2008 20:35:04 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <9c8c524f-6985-4cc8-b19c-666f85c69946@a26g2000prf.googlegroups.com> <01696606$0$6988$c3e8da3@news.astraweb.com> Message-ID: <78bd573f-03b0-4628-909d-3f84f9718e7e@13g2000yql.googlegroups.com> On Dec 29, 9:44?pm, Steven D'Aprano wrote: > How do you lose backward compatibility by *adding* new functionality? The > old functionality will continue to work as normal. > > -- > Steven AFAIK it still works the old way, but it will be deprecated soon. From cournape at gmail.com Thu Dec 4 18:58:29 2008 From: cournape at gmail.com (David Cournapeau) Date: Fri, 5 Dec 2008 08:58:29 +0900 Subject: using distutils to cross-compile extensions? In-Reply-To: <49385CBB.7060207@cs.cornell.edu> References: <49385CBB.7060207@cs.cornell.edu> Message-ID: <5b8d13220812041558r665738fydc558d46a851c887@mail.gmail.com> On Fri, Dec 5, 2008 at 7:42 AM, Michael George wrote: > Hi, > > Please CC me in replying as I am off list. > > I have an extension module that I've built using distutils. I wonder if > it's possible to use distutils to cross-compile it for windows on my linux > box, and whether the pain involved is great. Can anyone point me in the > right direction? You will have more luck using wine in your case if that's an option. General cross-compilation with distutils is for all practical purpose impossible - except for the particular case of 32 <-> 64 bits windows, which is fully supported. The first step for cross compilation would be the ability to build python itself wtih different build/host, and that's already non trivial. David From russell.sayers at gmail.com Mon Dec 1 22:32:52 2008 From: russell.sayers at gmail.com (russ) Date: Tue, 2 Dec 2008 14:32:52 +1100 Subject: Google App Engine Code Challenge - write a tetris playing algorithm In-Reply-To: References: Message-ID: <10304c580812011932l7ef375fcv4149f66064d02a30@mail.gmail.com> that's the first feature i'll add.. once the popularity gets over zero! :) On Tue, Dec 2, 2008 at 2:19 PM, Casey McGinty wrote: > On Sun, Nov 30, 2008 at 2:41 PM, russ.au wrote: > >> I've got more features to add, depending on how >> popular it is.. >> > > Are you going to create a leader board to track the high scores? > -------------- next part -------------- An HTML attachment was scrubbed... URL: From walterbyrd at iname.com Mon Dec 29 12:50:14 2008 From: walterbyrd at iname.com (walterbyrd) Date: Mon, 29 Dec 2008 09:50:14 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> Message-ID: <9c8c524f-6985-4cc8-b19c-666f85c69946@a26g2000prf.googlegroups.com> On Dec 21, 12:28?pm, Bruno Desthuilliers wrote: > > I can see where the new formatting might be helpful in some cases. > > But, I am not sure it's worth the cost. > > Err... _Which_ cost exactly ? Loss of backward compatibility, mainly. From reckoner at gmail.com Mon Dec 15 22:21:01 2008 From: reckoner at gmail.com (Reckoner) Date: Mon, 15 Dec 2008 19:21:01 -0800 (PST) Subject: tricky nested list unpacking problem References: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> Message-ID: <018c566d-f32c-4f9a-b1c0-fd51e370a75b@y1g2000pra.googlegroups.com> On Dec 15, 1:28?pm, Arnaud Delobelle wrote: > Reckoner writes: > > Hi, > > > I have lists of the following type: > > > [1,2,3,[5,6]] > > > and I want to produce the following strings from this as > > > '0-1-2-3-5' > > '0-1-2-3-6' > > > That was easy enough. The problem is that these can be nested. For > > example: > > > [1,2,3,[5,6],[7,8,9]] > > > which should produce > > > '0-1-2-3-5-7' > > '0-1-2-3-5-8' > > '0-1-2-3-5-9' > > '0-1-2-3-6-7' > > '0-1-2-3-6-8' > > '0-1-2-3-6-9' > > > also, > > > [1,2,3,[5,6],7,[9]] > > > should produce > > > '0-1-2-3-5-7-9' > > '0-1-2-3-6-7-9' > > > obviously, these are nested loops over the lists. The problem is that > > I don't know ahead of time how many lists there are or how deep they > > go. In other words, you could have: > > > [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]] > > IMHO the second level of nested lists is unnecessary as the same can be > achieved with just one sublevel of list (unless they are to be > interpreted in a way you have not explained). ?If you avoid this double > nesting then the 'flatten()' function below is not necessary anymore. > > > > > Any help appreciated. I've really been having trouble with this. > > > I hope that made sense. > > Here is a not thought out solution: > > def flatten(lst): > ? ? for x in lst: > ? ? ? ? if isinstance(x, list): > ? ? ? ? ? ? for y in flatten(x): > ? ? ? ? ? ? ? ? yield y > ? ? ? ? else: > ? ? ? ? ? ? yield x > > def unpack(lst): > ? ? stack, strings = [], [] > ? ? def rec(): > ? ? ? ? i = len(stack) > ? ? ? ? if i == len(lst): > ? ? ? ? ? ? strings.append('-'.join(map(str, stack))) > ? ? ? ? elif isinstance(lst[i], list): > ? ? ? ? ? ? for x in flatten(lst[i]): > ? ? ? ? ? ? ? ? stack.append(x) > ? ? ? ? ? ? ? ? rec() > ? ? ? ? ? ? ? ? stack.pop() > ? ? ? ? else: > ? ? ? ? ? ? stack.append(lst[i]) > ? ? ? ? ? ? rec() > ? ? rec() > ? ? return strings > > l1 = [1,2,3,[5,6]] > l2 = [1,2,3,[5,6],[7,8,9]] > l3 = [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]] > > Then: > > >>> unpack(l1) > > ['1-2-3-5', '1-2-3-6']>>> unpack(l2) > > ['1-2-3-5-7', '1-2-3-5-8', '1-2-3-5-9', '1-2-3-6-7', '1-2-3-6-8', '1-2-3-6-9']>>> unpack(l3) > > ['1-2-3-5-7-9', '1-2-3-5-7-1', '1-2-3-5-7-2', '1-2-3-5-7-3', > '1-2-3-5-7-4', '1-2-3-5-7-5', '1-2-3-5-6-9', '1-2-3-5-6-1', > '1-2-3-5-6-2', '1-2-3-5-6-3', '1-2-3-5-6-4', '1-2-3-5-6-5', > '1-2-3-5-10-9', '1-2-3-5-10-1', '1-2-3-5-10-2', '1-2-3-5-10-3', > '1-2-3-5-10-4', '1-2-3-5-10-5', '1-2-3-5-11-9', '1-2-3-5-11-1', > '1-2-3-5-11-2', '1-2-3-5-11-3', '1-2-3-5-11-4', '1-2-3-5-11-5'] > > -- > Arnaud Thanks for your detailed reply. I will have to ponder your solution carefully. From prologic at shortcircuit.net.au Tue Dec 2 17:59:54 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 3 Dec 2008 08:59:54 +1000 Subject: HELP!...Google SketchUp needs a Python API In-Reply-To: References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> Message-ID: On Wed, Dec 3, 2008 at 4:44 AM, Benjamin Kaplan wrote: > > > On Tue, Dec 2, 2008 at 1:36 PM, Craig Allen wrote: >> >> > Just remember thought that if you threat Python like a >> > hammer, suddenly everything will look like a bail. >> > >> >> don't you mean if you use Python like a pitchfork? > > Or that everything else looks like a nail. B and N are right next to each > other, so that seems more likely to me. Haha that was my bad typing :) --JamesMills -- -- -- "Problems are solved by method" From saluk64007 at gmail.com Sun Dec 21 15:00:04 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Sun, 21 Dec 2008 12:00:04 -0800 Subject: Are Django/Turbogears too specific? In-Reply-To: References: Message-ID: On Sun, Dec 21, 2008 at 11:41 AM, Gilles Ganault wrote: > Hi > > I'd like to rewrite a Web 2.0 PHP application in Python with AJAX, and > it seems like Django and Turbogears are the frameworks that have the > most momentum. > > I'd like to use this opportunity to lower the load on servers, as the > PHP application wasn't built to fit the number of users hammering the > servers now. > > I'm concerned, though, that these frameworks they may be too specific > to the tasks they were originally developped for (news articles, > AFAIK). Do you think I should just use eg. CherryPy and some basic > AJAX? > > Thank you for any feedback. > -- > http://mail.python.org/mailman/listinfo/python-list > No, they aren't very specific at all. Both frameworks allow configuration at nearly every level. The cool, slick admin interface might not be so useful depending on your application, but everything else has uses in just about any field. I only have experience with TG and cherrypy, TG for me is almost like cherrypy (I'm not sure if it still does, I've been out of the loop, but it used to use cherrypy under the hood), but a bit nicer to work with, especially if you have any AJAX. From geekmail at usenot.de Wed Dec 3 03:51:54 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Wed, 3 Dec 2008 09:51:54 +0100 Subject: Reverse zip() ? References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> Message-ID: <20081203095154.1bb33d4d@usenot.de> On Tue, 02 Dec 2008 18:16:13 -0800 Bryan Olson wrote: > zip as its own inverse might be even easier to comprehend if we call > zip by its more traditional name, "transpose". > Sounds like a Py4k change to me. /W -- My real email address is constructed by swapping the domain with the recipient (local part). From robert.kern at gmail.com Mon Dec 8 18:01:50 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 08 Dec 2008 17:01:50 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: <493DA61F.7020207@mrabarnett.plus.com> References: <493DA61F.7020207@mrabarnett.plus.com> Message-ID: MRAB wrote: > Terry Reedy wrote: >> Rasmus Fogh wrote: >> >>> For my personal problem I could indeed wrap all objects in a wrapper >>> with >>> whatever 'correct' behaviour I want (thanks, TJR). It does seem a bit >> >> I was not suggesting that you wrap *everything*, merely an adaptor for >> numpy arrays in whatever subclass and source it is that feeds them to >> your code. It is fairly unusual, I think, to find numpy arrays 'in >> the wild', outside the constrained context of numerical code where the >> programmer uses them intentionally and hopefully understands their >> peculiarities. >> >>> much, though, just to get code like this to work as intended: >>> alist.append(x) >>> print ('x is present: ', x in alist) >> >> Even if rich comparisons as you propose, the above would *still* not >> necessarily work. Collection classes can define a __contains__ that >> overrides the default and that can do anything, though True/False is >> recommended. >> > If you have a list of results and you want to see whether one of them is > Nan then the obvious way is "Nan in results", but __contains__ uses > __eq__ and Nan == Nan returns False, so "Nan in results" returns False. > Hmm... "Nan is Nan" returns True, However, "Nan is SomeOtherNan" does not return True. > so if there was a version of > __contains__ which used "is" then "Nan in results" would return True. > Perhaps "Nan is in results"? Or would that be too confusing, ie "in" vs > "is in"? list.__contains__() already checks with "is" before it tries "==". In [65]: from numpy import nan, inf In [66]: other_nan = inf/inf In [67]: nan in [nan] Out[67]: True In [68]: nan in [other_nan] Out[68]: False -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From gagsl-py2 at yahoo.com.ar Fri Dec 26 14:00:20 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 26 Dec 2008 17:00:20 -0200 Subject: =?utf-8?Q?Can=C2=B4t_Surf_Python_Pages_in_W?= =?utf-8?Q?indoze?= References: <4dc0cfea0812260701q6baf0ccbj154c5b3fa2281cdb@mail.gmail.com> <4954FB9F.5050702@wildenhain.de> <4dc0cfea0812260911k4dbc0f2ame9cc874e067b7816@mail.gmail.com> Message-ID: En Fri, 26 Dec 2008 15:11:44 -0200, Victor Subervi escribi?: > On 12/26/08, Tino Wildenhain wrote: >>> print "Content-Type: text/html" >>> print >>> print """ >>> >> http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> I think there should be only one blank line between header and content, you have two (so the document contains an empty line before the doctype declaration, and I think this is invalid). >>> >>> >>> >>> >>> Yeah >>> >>> """ The title tag (in head) is mandatory (although this should not prevent it from working) >> this could be fine if called in CGI context. > > Can you state clearly what "CGI context" means? Tino W. surely meant to say: - if you have a web server running - and it is capable of handle CGI scripts - and you have configured it to handle CGI scripts - and you have configured it to run the code above as a CGI script in response to certain request - and you pointed your browser to the right server, at the right port, at the right url - then, the code above should run and you should get a nice HTML page with the word Yeah in it. > Should I be importing a CGI > module? I pulled this code from a page that was working. If it had an > importation of something CGI, I believe I would have tested that with all > the other things that were imported that I tested, but perhaps not. I am > not > at my home computer to test, and will not be back online for a week. No, the code above doesn't require other modules to run. > I am not worried about Zope now, but the above code, yes. You're talking about two totally separate projects, I presume. The above code should not be used with Zope. -- Gabriel Genellina From stepp.aaron at gmail.com Mon Dec 22 22:52:35 2008 From: stepp.aaron at gmail.com (Aaron Stepp) Date: Mon, 22 Dec 2008 22:52:35 -0500 Subject: iterating initalizations In-Reply-To: <47c890dc0812221943g44bd7222t8c09c088d87e77df@mail.gmail.com> References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> <47c890dc0812221943g44bd7222t8c09c088d87e77df@mail.gmail.com> Message-ID: <002696D3-E888-4D32-8416-0CFE4AC859AC@gmail.com> On Dec 22, 2008, at 10:43 PM, Chris Rebert wrote: > On Mon, Dec 22, 2008 at 7:32 PM, Aaron Stepp > wrote: > >> >> Thanks for the help so far, I think I'm starting to get a hang of the >> syntax. >> >> I think I need to state my goal more clearly. >> >> Instead of writing a long list of initializations like so: >> >> A = [ ] >> B = [ ] >> ... >> Y = [ ] >> Z = [ ] >> >> I'd like to save space by more elegantly turning this into a loop. >> If I >> need to just write it out, I guess that's ok... but it would be much >> cleaner. I'm a composer, not a programmer, so some of this is >> quite above >> me. >> > > So, are these variables supposed to be module-level, or attributes of > class pitchAndRhythm, or what? > Also, are you going to use the variables normally or are you going to > need "variable variables" (e.g. like $$var in PHP, which gives the > value of the variable with the name of the string stored in $var)? > > Cheers, > Chris > > -- > Follow the path of the Iguana... > http://rebertia.com The're going to only be part of the pitchAndRhythm class. Simply put, I just need enough arrays to hold a list of pitches/rhythms. Then I'll have each list member returned to an instrument defined in another module. As I'm hacking away at the code, I'm realizing that maybe I can do this with just and A = [] and B = []. But I'm not sure... Thanks again. AS From BrianVanderburg2 at aim.com Sun Dec 14 13:07:10 2008 From: BrianVanderburg2 at aim.com (Brian Allen Vanderburg II) Date: Sun, 14 Dec 2008 13:07:10 -0500 Subject: Limit traceback from most recent call Message-ID: <49454B4E.30308@aim.com> I've looked at traceback module but I can't find how to limit traceback from the most recent call if it is possible. I see that extract_tb has a limit parameter, but it limits from the start and not the end. Currently I've made my own traceback code to do this but wonder if python already has a way to do this build in: def format_partial_exc(limit=None): (type, value, tb) = sys.exc_info() items = traceback.extract_tb(tb) if limit: items = items[-limit:] # Get last 'limit' items and not first result = 'Traceback (most recent call last):\n' items = traceback.format_list(items) for i in items: result += i # Newline already included result += type.__name__ + ': ' + str(value) return result Is this possible currently from traceback or other python module? Brian A. Vanderburg II From robert.panesse at gmail.com Sun Dec 21 08:40:20 2008 From: robert.panesse at gmail.com (McCoy Fan) Date: Sun, 21 Dec 2008 05:40:20 -0800 (PST) Subject: Read an image from a URL and write it to the browser References: Message-ID: On Dec 21, 7:25?am, Peter Otten <__pete... at web.de> wrote: > McCoy Fan wrote: > > I want to do something simple: read an image from an image URL and > > write the image to the browser in CGI style. > > > I wrote a CGI script to do this (I'm new to Python) and got the > > following error: > > > "FancyURLopener instance has no attribute 'tempcache'" in > method FancyURLopener.__del__ of > > I have no idea what that error means and neither does Google. > > > Any idea where I went wrong in the code below? > > import urllib > > > urlString = "http://www.google.com/google_logo.jpg" > > imgStream = urllib.urlopen(urlString) > > imgBuffer = imgStream.read() > > imgStream.close() > > print "Content-Type: image/jpeg" > > print > > print imgBuffer > > Your script runs without error here, but I can ?provoke the attribute error > by passing an invalid proxies argument to urlopen(): > > $ python -c"import urllib; urllib.urlopen('whatever', proxies=42)" > Traceback (most recent call last): > ? File "", line 1, in > ? File "/usr/lib/python2.5/urllib.py", line 75, in urlopen > ? ? opener = FancyURLopener(proxies=proxies) > ? File "/usr/lib/python2.5/urllib.py", line 609, in __init__ > ? ? URLopener.__init__(self, *args, **kwargs) > ? File "/usr/lib/python2.5/urllib.py", line 117, in __init__ > ? ? assert hasattr(proxies, 'has_key'), "proxies must be a mapping" > AssertionError: proxies must be a mapping > Exception exceptions.AttributeError: "FancyURLopener instance has no > attribute 'tempcache'" in > ignored > > Please post your complete traceback, Python version, and OS to allow for a > more detailed diagnosis. > > You can also try to run your script with > > > imgStream = urllib.urlopen(urlString) > > changed to > > imgStream = urllib.urlopen(urlString, proxies={}) > > to bypass the code in which I suppose the failure to occur. > > Peter I appreciate your response. Thank you. After reading your reply, I realized this must be related to the fact that I am running this script on Google App Engine. It turns out, App Engine does not allow direct socket communication so urllib is not allowed. Instead they provide their own library called urlfetch. So my script should look something like this: from google.appengine.api import urlfetch print 'Content-Type: text/plain' print '' result = urlfetch.fetch('http://www.google.com/google_logo.jpg') print result.content I haven't been able to get it to work yet but at least I'm heading in the right direction now. I'll keep digging. Thanks! From gregturn at mindspring.com Mon Dec 1 14:47:02 2008 From: gregturn at mindspring.com (Goldfish) Date: Mon, 1 Dec 2008 11:47:02 -0800 (PST) Subject: Spring Python 0.9.0 is released Message-ID: <3fca9b88-df7c-40dc-a64d-7181c39dd42c@g38g2000yqd.googlegroups.com> Spring Python, the python version of the Spring Framework, has just released version 0.9.0. This release includes a key update to springpython.security.web module, where authorization has been patched to support CherryPy 3.1. To download the 0.9.0 release, or an archived release, and for access to sample applications use http://www.springsource.com/download/community?project=Spring%20Extensions Please visit the website at http://springpython.webfactional.com for information about features, releases, source code, licensing, and official documentation. ============================================================================== Release Notes - Spring Python - Version 0.9 Bug * [SESPRINGPYTHONPY-81] - Fix AccessDecisionManager based on CherryPy 3 upgrade Task * [SESPRINGPYTHONPY-76] - Convert sample applications to new XMLConfig format. ============================================================================== Key Features of Spring Python include: * Inversion Of Control - The idea is to decouple two classes at the interface level. This lets you build many reusable parts in your software, and your whole application becomes more pluggable. You can use either the XmlApplicationContext or the DecoratorBasedApplicationContext. * Aspect-oriented Programming - Spring Python provides great ways to wrap advice around objects. It is utilized for remoting. Another use is for debug tracers and performance tracing. * DatabaseTemplate - Reading from the database requires a monotonous cycle of opening cursors, reading rows, and closing cursors, along with exception handlers. With this template class, all you need is the SQL query and row-handling function. Spring Python does the rest. * Database Transactions - Wrapping multiple database calls with transactions can make your code hard to read. This module provides multiple ways to define transactions without making things complicated. * Security - Plugin security interceptors to lock down access to your methods, utilizing both authentication and domain authorization. * Remoting - It is easy to convert your local application into a distributed one. If you have already built your client and server pieces using the IoC container, then going from local to distributed is just a configuration change. * Samples - to help demonstrate various features of Spring Python, some sample applications have been created: o PetClinic - Everybody's favorite Spring sample application has been rebuilt from the ground up using various web containers including: CherryPy. Go check it out for an example of how to use this framework. o Spring Wiki - Wikis are powerful ways to store and manage content, so we created a simple one as a demo! o Spring Bot - Use Spring Python to build a tiny bot to manage the IRC channel of your open source project. From wuwei23 at gmail.com Sun Dec 21 20:37:47 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 21 Dec 2008 17:37:47 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <7fc23c41-6bf8-4272-b405-acc092cbac87@r15g2000prd.googlegroups.com> Message-ID: <5b15041d-c1e9-4b28-b8ca-89505e49fe83@a12g2000pro.googlegroups.com> On Dec 21, 10:11?am, r wrote: > Most of the complaints i hear are the redundant use of self. > Which I lamented about but have become accustom(brainwashed) to it. I > would remove this if it where up to me. It's a shame Python wasn't released under some kind of license, one that allowed its source to be, say, "opened" and modified. Otherwise you would just implement this yourself and submit patches, right? From prologic at shortcircuit.net.au Sun Dec 21 21:02:38 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Dec 2008 12:02:38 +1000 Subject: Threads, forks, multiplexing - oh my In-Reply-To: References: Message-ID: On Mon, Dec 22, 2008 at 11:36 AM, Thomas Raef wrote: > I now want to run multiple instances of this program on a client, after > receiving the command line and args from a broker, dispatcher, whatever you > want to call it. You can use the subprocess module. > I've read where forks will run programs but they replace the calling program > ? is that correct? Am I reading that right? If so, then my client program > will have to use forks so it can run a program. Then are threads to run > functions and not full-fledged programs? Forking creates a clone/child process of the parent. You probably want os.system or subprocess. > When, if ever, would I want to look at implementing multiplexing? Single-process multiplexing (think event-driven) can often be far better in terms of performance. --JamesMills From srilyk at gmail.com Tue Dec 16 04:20:29 2008 From: srilyk at gmail.com (W W) Date: Tue, 16 Dec 2008 03:20:29 -0600 Subject: [Tutor] Having Issues with CMD and the 'python' command In-Reply-To: References: Message-ID: <333efb450812160120g57f18631hf6c7149dc307d3@mail.gmail.com> On Mon, Dec 15, 2008 at 9:56 AM, Benjamin Kaplan wrote: > It's not a question of sensibility. It's a question of purpose. The Zen is > the philosophy of a language that tries to be easy to learn and easy to use. > Python is used by programmers who want to experiment with it, but who > usually know enough not to os.system("rm -r /") or anything similar. > Windows, on the other hand, wants to hide everything that can potentially > ruin the system as deep as possible so that many of the idiots who use that > system don't do stupid things like delete the registry, wipe the environment > settings, turn off the "Nag Screen" (UAC), and other things of that nature > But if it were sensible, it would (like certain other OS's) make it more difficult to have built-in permissions that allow you to totally hose the system, i.e. it would be secure.While it may not technically be using the same comparison criteria we do, Python still gives you the proper result: In [5]: 'obfuscation' is not 'security' and 'obfuscation' != 'security' Out[5]: True I think that's an important concept for programmers to realize. Allowing people to break things if they fool around enough is not a very sensible, or secure way of running things. And if you're writing OSes, the sensible thing is to write secure code. And if you're writing programs for general consumption, it's /also/ best to write secure code. That's my 2c anyways :) -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrew.replogle at gmail.com Tue Dec 16 14:21:35 2008 From: andrew.replogle at gmail.com (Andrew) Date: Tue, 16 Dec 2008 11:21:35 -0800 (PST) Subject: subprocess returncode windows References: Message-ID: <18348eae-5af1-47e9-a198-b95d4fcb6eac@a12g2000pro.googlegroups.com> On Dec 16, 12:50?pm, Christian Heimes wrote: > Andrew schrieb: > > > > > Hello, > > > I'm running into a strange situation with getting incorrect > > returncodes / exit status from python subprocess.call. I'm using a > > python script (runtime 2.6.1 on windows) to automate the deploy of > > java applications to glassfish application server. Below is an example > > of using a subprocess call to test the success / failure of the > > glassfish CLI tool "asadmin" > > > Example.py: > > ---------------------- > > import sys > > from subprocess import * > > > try: > > ? ? retcode = call("c:/glassfish/bin/asadmin.bat " + "list-system- > > properties --host mydomain --port 4848 --user admin server-01", > > shell=True) > > ? ? if retcode < 0: > > ? ? ? ? print >>sys.stderr, "Child was terminated by signal", -retcode > > ? ? else: > > ? ? ? ? print >>sys.stderr, "Child returned", retcode > > except OSError, e: > > ? ? print >>sys.stderr, "Execution failed:", e > > Don't use shell=True! Instead use a list of arguments without shell=True: > > call(["c:/glassfish/bin/asadmin.bat", "list-system-properties", "--host > mydomain", "--port 4848", "--user admin", "server-01"]) > > That should solve your quoting issues on Windows and fix your code. > shell=True is considered evil and should be avoided whenever possible. > > Christian Thanks Christian, I've removed shell=True, unfortunately, if I structure the call like: call(["c:/glassfish/bin/asadmin.bat", "list-system-properties", "-- host mydomain", "--port 4848", "--user admin", "server-01"]) It doesn't seem to recognize any arguments after list-system- properties. If I structure it like: call("c:/glassfish/bin/asadmin.bat "+"list-system-properties --host mydomain --port 4848 --user admin server-01") Then it executes correctly but still gives invalid returncode of 0 when it fails instead of 1. Andrew From steve at REMOVE-THIS-cybersource.com.au Wed Dec 31 01:27:01 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Dec 2008 06:27:01 GMT Subject: How to get back a list object from its string representation? References: <78f8019c0812302046j31fa38aeif33d659ec5f2c84e@mail.gmail.com> Message-ID: <016b07b4$0$6988$c3e8da3@news.astraweb.com> On Wed, 31 Dec 2008 03:08:29 -0200, Gabriel Genellina wrote: > eval is like Pandora?s box, all kind of bad things can come from it. Do > not use it with any user-supplied string. If you can restrict the values > to be just constants, there is a "safe eval" recipe in > http://code.activestate.com The ast module in Python 2.6 includes a "literal eval" function: >>> ast.literal_eval("[1, 2, 3]") [1, 2, 3] -- Steven From work8home4all at gmail.com Mon Dec 22 09:39:48 2008 From: work8home4all at gmail.com (work8home4all at gmail.com) Date: Mon, 22 Dec 2008 06:39:48 -0800 (PST) Subject: Start Earning With Commission junction Message-ID: Start Earning With Commission junction one of the biggest affiliate programes i.e running on internet in these days details on http://megalinesolutions.googlepages.com/cj_1 From gagsl-py2 at yahoo.com.ar Tue Dec 16 04:00:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Dec 2008 07:00:32 -0200 Subject: Structure using whitespace vs logical whitespace References: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> Message-ID: En Mon, 15 Dec 2008 14:29:31 -0200, cmdrrickhunter at yaho.com escribi?: > PS. In my opinion the solution would be to have the option of entering > a "whitespace insensitive" mode which uses C style {} and ;. The > token to enter it could be as complicated as you want (in fact, it may > make sense to make it complicated to discourage use unless it's really > advantageous). I'd sugest {{ and }} or something bigger like {={ } > =}. Only two problems: 1) I'm sure it would offend Guido's sense of > language aesthetics 2) I'm sure the idea has been hashed over on this > newsgroup to death... hence prefering a workaround instead. It's a hidden feature, already implemented. Try: from __future__ import braces -- Gabriel Genellina From dstanek at dstanek.com Thu Dec 25 18:18:03 2008 From: dstanek at dstanek.com (David Stanek) Date: Thu, 25 Dec 2008 18:18:03 -0500 Subject: Exec inside a class method to call other class methods? In-Reply-To: <4953CF57.8080905@sympatico.ca> References: <4953CF57.8080905@sympatico.ca> Message-ID: On Thu, Dec 25, 2008 at 1:22 PM, Matthew Dubins wrote: > Hello all, > > I have made a python script to upload contact information from an excel > worksheet to an online database. One part of the program that really > tripped me up was when I wanted to call specific class methods that I had > made to deal with specific types of contact information (Parent's name, > Child's name, Phone #, etc). My first thought was to make it easy using the > exec statement. > The code (a method within a class) looked like this: > ---------- > def parse(self, data, data_type) > exec "self.__parse_%s(data)" % data_type > ---------- > The data_type variable contains strings that exactly match the spellings of > the 2nd word in the titles of the class methods that I wanted to call for > each data_type inputted into the parse function. For some reason, *it > didn't work*. Alternately, I found the ugly code shown below to be > functional. As you can see, for each data_type, I call the corresponding > class method that I've specified. Please help me to transform my ugly > functional code into concise functional code. :) > > Thanks, > Matthew > ---------- > def parse(self, data, data_type): > if data_type == 'nocall': > self.__parse_nocall(data) > elif data_type == 'DOB': > self.__parse_DOB(data) > elif data_type == 'gender': > self.__parse_gender(data) > elif data_type == 'Prematurity': > self.__parse_Prematurity(data) > elif data_type == 'email': > self.__parse_email(data) > elif data_type == 'languages': > self.__parse_languages(data) > elif data_type == 'phone': > self.__parse_phone(data) > elif data_type == 'cname': > self.__parse_cname(data) > elif data_type == 'pname': > self.__parse_pname(data) > elif data_type == 'address': > self.__parse_address(data) > elif data_type == 'duedate': > self.__parse_dudedate(data) > I would look for a way to reorganize your code so that each type contains its own parse method. -- David http://www.traceback.org From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 23:22:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Dec 2008 04:22:53 GMT Subject: To Troll or Not To Troll (aka: "as" keyword woes) References: <20081205163107.1815df40@usenot.de> <27945697-3f2f-452d-bed4-d1ca45d46fbb@r10g2000prf.googlegroups.com> Message-ID: <0149f5d8$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 19:00:12 -0800, alex23 wrote: > On Dec 6, 8:00?am, James Stroud wrote: >> I think its a symptom of the language's maturing, getting popular, and >> a minority fraction* of the language's most devout advocates developing >> an egotism that complements their python worship in a most unsavory >> way. > > It's hard to see how anyone could ever take offence at your posts given > such unbiased objectivity ;) I see your wink, but, please, did you read that thread started by "r" about the Ruby API for some piece of Google software? That was so offensively fanboyish that I almost removed Python from my computer. -- Steven From rt8396 at gmail.com Mon Dec 22 14:28:44 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 11:28:44 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: On Dec 22, 1:10?pm, MRAB wrote: > r wrote: > > Steve Holden > >> What makes you assume this is a zero-sum game, and that Python won't > >> survive if any other language becomes popular. Every language borrows > >> from those that came before it. Terms like "outright plagiarism" don't > >> encourage rational debate, and make you seem like a troll who is more > >> interested in stirring up controversy than actually doing things to help > >> promote the language. > > > This is a war Steve, and i will explain why. Python does not need to > > compete with perl, lisp, C, basic, etc, etc. WHY, well because python > > is SO radically different than those languages. Ruby on the other > > hand, took most from python, the only difference is Ruby's full OO > > integration.(12.method()). Since Ruby is so similar to python we must > > consider that some people who would have found only python in this > > niche now could go to Ruby. I am for choices, but this is out and out > > robbery! > > Of course we must stand on the shoulders of greater minds than our own > > to get ahead, but using someone's knowledge against them is wrong. If > > Ruby want's to incorporate so many Pythonian ideas into their > > language, at least put a note in the tutorial giving credit to Guido > > for his wisdom. Don't use our ideas and then bash python in the next > > breath! > > [snip] > "Pythonian"? A real Pythonista would know it's "Pythonic"! A real > Pythonista would be called "p", not "r", which sounds very Rubish(?) to > me... MRAB -> '%sMuchRubyAndBasic' %'Too' MRAB -> Method.Ruby(AttractsBraindead) MRAB -> MyRubyAintBad MRAB -> MuchoRubyAndBasic Pythonian is more acceptable in the context of my sentence... """ If Ruby want's to incorporate so many Pythonian ideas into their language, at least put a note in the tutorial giving credit to Guido for his wisdom.""" Pythonian.translate() -> in the domain if Python... ownership Pythonic.translate() -> in a python style... (way of) two radically different meaning, of course if you vocabulary reaches that far?? From 4564 at 755189.45 Wed Dec 17 09:26:30 2008 From: 4564 at 755189.45 (Enrico) Date: Wed, 17 Dec 2008 15:26:30 +0100 Subject: Python, XML and XPath References: Message-ID: <49490c49$0$1115$4fafbaef@reader3.news.tin.it> "Hole" ha scritto nel messaggio news:daf5cd00-36dc-4ab4-976e-a6d859b52d0a at w24g2000prd.googlegroups.com... > Hi all, > > I hope this is not an "overasked" question but I find myself quite > confused about python xml management (I have to use python for a > project and I come from java world, you know...where frameworks, > libraries and tools to use are standard de iure or standard de facto). > > I need to use XML parsing with xpath: a simple xml reader. You can try lxml, have a look here http://codespeak.net/lxml/xpathxslt.html > > I've found that the standard distribution of python doesn't include > xpath support modules so I've decided to add libxml2. > > I've installed cygwin c compiler but I still have errors like the > following: > > C:\Python25\Lib\libxml2-python-2.6.9>python setup.py build install I never used libxml2 but version 2.6.9 seems quite old, according to this page: http://users.skynet.be/sbi/libxml-python/ Bye, Enrico From rt8396 at gmail.com Sat Dec 20 18:34:27 2008 From: rt8396 at gmail.com (r) Date: Sat, 20 Dec 2008 15:34:27 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> Message-ID: <59153e28-bf86-4158-96d9-23aa5b9f0205@j35g2000yqh.googlegroups.com> Walter, Would you be kind enough to translate this code to the new syntax? >>> s = 'python' >>> n = 12 >>> f = 1.333333333 >>> '%s %05d %0.2f' %(s,n,f) 'python 00012 1.33' i want to see how casting is handled. Thanks From nemokingdom at gmail.com Mon Dec 29 01:36:01 2008 From: nemokingdom at gmail.com (nemo) Date: Sun, 28 Dec 2008 22:36:01 -0800 (PST) Subject: ftp design question References: <74706983-5198-436b-b0ca-b0246a41c67e@v5g2000prm.googlegroups.com> Message-ID: <504983b3-fad0-4e01-a2cc-df2f67fe7157@r37g2000prr.googlegroups.com> On Dec 29, 12:31?pm, Steve Holden wrote: > nemo wrote: > > Hi,all. > > I'm on a toy ftp project and I want it to be convinient for the user > > to cancel an undergoing downloading while continue others. The > > following code explains: > > for file in download_files: > > ? ? self.ftp.retrbinary('RETR '+file, ?fileHandler) > > Thers seems not a solid way to cancel this transfer and I considered > > thread or process but I can't handle this correctly. > > Thread: I can't kill the thread in another thread, so... > > Process: There seems something wrong(raise an EOFError exception) when > > I use Process(target = download_fun, args = (dir,)) for each > > downloading after connection built. > > Some suggestions? > > How about > > for file in download_files: > ? ? try: > ? ? ? ? self.ftp.retrbinary('RETR %s' % file, fileHandler) > ? ? except KeyboardInterrupt: > ? ? ? ? print file, "transfer abandoned" > > Then you can cancel a single file transfer with Ctrl/C. > > regards > ?Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ Thanks your advice, actually, this ftp has a GUI interface, so I'm considering the downloading part in another process or thread, whick is s a tricky part for me to design. From skip at pobox.com Mon Dec 22 11:01:18 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 22 Dec 2008 10:01:18 -0600 Subject: Python's popularity In-Reply-To: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: <18767.47566.709705.92@montanaro-dyndns-org.local> Walter> From what I have seen: Walter> - in unix/linux sysadmin, perl is far more popular than python, Walter> windows sysadmins typically don't use either. Walter> - in web-development, php is far more popular than python - it's not Walter> even close. Walter> - when I did a search on dice, I found over 20X more jobs advertised Walter> for ruby on rails developers, than for python dango developers. Walter> - application development is dominated by java, c/c++, and maybe a Walter> little visual basic. Walter> - as I understand it, fortran is still the most popular language for Walter> numberical programming. Looking at specific application domains doesn't tell the entire story. If you look back at the Tour de France results from the 80's I believe Greg Lemond won it one year without ever winning a stage. What you are reporting is akin to that. Fortran is almost certainly the king of numerical programming, but Python might be #2 or #3 there (behind Matlab). I'm pretty sure it dwarfs Perl, PHP and Ruby in that domain. In web development, while PHP is more popular than Python, Python is probably much more popular than Perl and Tcl. Maybe not ahead of Ruby due to RoR. etc etc. Skip From fetchinson at googlemail.com Wed Dec 10 16:35:30 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 10 Dec 2008 13:35:30 -0800 Subject: looking up function's doc in emacs In-Reply-To: References: Message-ID: > in programing elisp in emacs, i can press "Ctrl+h f" to lookup the doc > for the function under cursor. > > is there such facility when coding in perl, python, php? > > (i'm interested in particular python. In perl, i can work around with > "perldoc -f functionName", and in php it's php.net/functionName. Both > of which i have a elisp command with a shortcut that let me jump to > the doc) Why can't you do the same with pydoc (the command line tool, ususally installed in /usr/local/bin/pydoc or somewhere else if python shipped with your distro). Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From federico at linux.com.uy Tue Dec 16 12:51:20 2008 From: federico at linux.com.uy (Federico Moreira) Date: Tue, 16 Dec 2008 14:51:20 -0300 Subject: Generator slower than iterator? In-Reply-To: References: Message-ID: 2008/12/16 > Python 3.0 does not support has_key, it's time to get used to not using it > :) > Good to know line.split(None, 1)[0] really speeds up the proccess Thanks again. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cjw at ncf.ca Sat Dec 6 09:20:42 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 06 Dec 2008 09:20:42 -0500 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: <493A8A3A.6060203@ncf.ca> Daniel Fetchinson wrote: > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html > > The proposal is to allow this: > > class C: > def self.method( arg ): > self.value = arg > return self.value > > instead of this: > > class C: > def method( self, arg ): > self.value = arg > return self.value > > I.e. explicit self stays only the syntax is slightly different and may > seem attractive to some. As pointed out by Guido classmethods would > work similarly: > > class C: > @classmethod > def cls.method( arg ): > cls.val = arg > return cls.val > > The fact that Guido says, > > "Now, I'm not saying that I like this better than the status quo. But > I like it a lot better than [...] but it has the great advantage that > it is backward compatible, and can be evolved into a PEP with a > reference implementation without too much effort." > > shows that the proposal is viable. > > I'd like this new way of defining methods, what do you guys think? > Anyone ready for writing a PEP? > > Cheers, > Daniel > The quoted blogspot is not available. I like the idea but I don't see how explicit and implicit can co-exist. Version 3.0 is the time to introduce the enhancement. Colin W. From marco at sferacarta.com Thu Dec 4 10:28:44 2008 From: marco at sferacarta.com (Marco Mariani) Date: Thu, 04 Dec 2008 16:28:44 +0100 Subject: Pythonic design patterns In-Reply-To: <45fdd23c-0ccc-4135-b10c-1ef1d5ea4e6b@p2g2000prf.googlegroups.com> References: <0147e8b9$0$20670$c3e8da3@news.astraweb.com> <45fdd23c-0ccc-4135-b10c-1ef1d5ea4e6b@p2g2000prf.googlegroups.com> Message-ID: George Sakkis wrote: >> This is all very good, but don't drink the design pattern Kool-Aid and >> start pushing design patterns everywhere. (Not everything needs to be a >> singleton. No, really.) > > Obligatory reading: http://www.mortendahl.dk/thoughts/blog/view.aspx?id=122 By the way, it's a fact that many low-level patterns, as they are described, are useful mainly/only in statically typed languages. The ones in PEAA, for instance, are high-level enough to be useful in any environment. http://www.amazon.com/Enterprise-Application-Architecture-Addison-Wesley-Signature/dp/0321127420 From steve at REMOVE-THIS-cybersource.com.au Fri Dec 26 22:07:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Dec 2008 03:07:53 GMT Subject: Is there a function to remove escape characters from a string ? References: <0163882f$0$6988$c3e8da3@news.astraweb.com> <5a29b62a-c38f-409b-8887-6259ad072bf5@w1g2000prk.googlegroups.com> Message-ID: <01659326$0$6988$c3e8da3@news.astraweb.com> On Sat, 27 Dec 2008 01:41:40 +0100, Stef Mientki wrote: > Sorry if I offended someone, that was certainly not my intention. And I > guess you will be surprised, if I tell you, I don't (want) to understand > any bit of the above code ;-) Come on, the home computer was invented > about 1980. If we look at hardware, it follows the Moore's law, for > software I would expect at least 0.1 of Moore's law ;-) I hope that > clarifies my point. No, that only makes it even more confusing. What does Moore's Law have to do with your willful ignorance about the existence of human languages other than English? -- Steven From zhushenli at gmail.com Wed Dec 3 07:27:26 2008 From: zhushenli at gmail.com (Davy) Date: Wed, 3 Dec 2008 04:27:26 -0800 (PST) Subject: Thread Tkinter problem Message-ID: <64c7402c-8b7b-4281-9d7d-1abdd6177d96@r15g2000prh.googlegroups.com> Hi all, I am using thread and tkinter to write some simple programs and solidify my understanding of Python thread/GUI programing. The scheme is thread + queue + GUI. One child thread (gen_board_thread) generate board and insert data into queue infinitely. Meanwhile, the main thread canvas widget get the board data from queue. I assume the program will run forever if don't close them explicitly, but the fact is contrary to my understanding. It seems the child thread insert data till queue is full, then the main thread eat the data till the queue is empty, and the main thread starve(when timeout option is set) and die. So the two thread work like two function call, but not two thread! Is this situation caused by deadlock(I guess main thread has higher priority)? Or how can I know whether the child thread is still alive? Ultimately, how to solve the problem? The code are attached. Any suggestion will be appreciated :-) Best regards, Davy //---------Code below--------------- from Tkinter import * import thread import Queue ##import time x = 3 ## vertical y = 5 ## horizontal block_width = 10 block_height = 10 canvas_width = x * block_width canvas_height = y * block_height data_queue = Queue.Queue(20) board_1 = [[1,0,1], [0,1,1], [1,0,0], [0,0,1], [0,1,0]] board_2 = [[0,1,0], [1,0,0], [0,1,1], [1,1,0], [1,0,1]] def gen_board_thread(): ## Problem: the thread seems to be deadlock or killed or postponed after execution was taken over by main thread draw_canvas_loop() print 'enter here' gen_flip = 1 while(data_queue.full() == False): ##print '???' ##time.sleep(0.1) if (gen_flip == 1): gen_flip = 0 data = board_1 else: gen_flip = 1 data = board_2 data_queue.put(data) print 'put', data_queue.qsize() def create_canvas(root,canvas_width,canvas_height,): canvas = Canvas(root, width=canvas_width, height=canvas_height, bg='white') canvas.pack(expand=YES) return canvas def draw_canvas_loop(canvas_b): board = data_queue.get(block = True, timeout=1) print 'get', data_queue.qsize() draw_canvas(board, canvas_b, x, y, block_width, block_height) canvas_b.after(300, lambda:draw_canvas_loop(canvas_b)) def draw_canvas(board, canvas_b, x, y, block_width, block_height): ##canvas_b.after(3000) ##time.sleep(3) for j in range(y): for i in range(x): if board[j][i] == 1: color = 'black' else: color = 'white' start_x = block_width * i start_y = block_height * j end_x = start_x + block_width end_y = start_y + block_height canvas_b.create_rectangle (start_x,start_y,end_x,end_y,fill=color) if __name__ == '__main__': root = Tk() root.title('Tetris') canvas = create_canvas(root,canvas_width,canvas_height) thread.start_new(gen_board_thread,()) draw_canvas_loop(canvas) mainloop() From ldo at geek-central.gen.new_zealand Wed Dec 3 03:15:45 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 03 Dec 2008 21:15:45 +1300 Subject: Multiple equates References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> <9m3h06-vhh.ln1@lairds.us> Message-ID: Cameron Laird wrote: > def f1(Match): > return Something missing here? From marduk at letterboxes.org Sat Dec 6 07:47:27 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Sat, 06 Dec 2008 07:47:27 -0500 Subject: Insert Multiple Records Using One Insert Statemen with MySQLdb module In-Reply-To: <6d85c9db-2769-461b-bfe0-974e4fad5e07@k8g2000yqn.googlegroups.com> References: <6d85c9db-2769-461b-bfe0-974e4fad5e07@k8g2000yqn.googlegroups.com> Message-ID: <1228567647.20032.1.camel@blackwidow.nbk> On Sat, 2008-12-06 at 04:03 -0800, anton.ranieri.it at gmail.com wrote: > Hi, > > I'd like to insert Multiple Records Using One Insert Statement > > inserting one record using one insert statement works > this is the example: > > import MySQLdb > conn = MySQLdb.connect(host="localhost",.....) > cursore = conn.cursor() > cursore.execute('INSERT INTO frutta (nome, quantita) VALUES(%s, %s)', > ('Pompelmi', 10) > ) > > but when I try to insert Multiple Records Using One Insert Statement > in this way: > > cursore.execute('INSERT INTO frutta (nome, quantita) VALUES(%s, %s)', > ('Pompelmi', 10), > ('Pompelmi', 10), > ('Pompelmi', 10) > ) > > it doesn't work! You want to use the cursor's .executemany() method. > -- > http://mail.python.org/mailman/listinfo/python-list From rt8396 at gmail.com Mon Dec 22 18:47:55 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 15:47:55 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <6ra8t0F925rU1@mid.individual.net> <29feda0d-6432-4cb9-8809-e4d4a7798601@e1g2000pra.googlegroups.com> <6raeb8F9s47U2@mid.individual.net> <6rahpaFav7kU2@mid.individual.net> <97e49a8c-6730-42f2-b4d0-35eaff38b69f@y1g2000pra.googlegroups.com> Message-ID: <48221004-94ce-4b2a-b94a-1ca45a2562b8@j11g2000yqg.googlegroups.com> [Jeff] but I raise the bar so that any random joker probably won't bother (and making the reverse mapping - knowing my real identity and then looking for recent net activity - is much more difficult to do) [/Jeff] You are the epitimy of an internet troll. A troll tries to hide his identity. Why are you so concerned about your TRUE identity. Are the FEDS after you, maybe it's the Martians i do not know? Did they take into their spaceship and do things to you? Do you wear a aluminum foil hat. Look out for those cell towers, there mind control devices hahaha. Thanks for the good laugh. From brendandetracey at yahoo.com Fri Dec 12 11:20:38 2008 From: brendandetracey at yahoo.com (Brendan) Date: Fri, 12 Dec 2008 08:20:38 -0800 (PST) Subject: Reading online zip files - zipfile and zlib, wbits References: <21ba0ff5-7698-481a-851c-80b9ddcd5814@q26g2000prq.googlegroups.com> Message-ID: On Dec 12, 11:36?am, Brendan wrote: > On Dec 12, 10:46?am, Brendan wrote: > > > > > > > On Dec 12, 10:25?am, Brendan wrote: > > > > I am fooling around with accessing contents of zip files online. I > > > download the tail end of the zip and use zipfile to get the zip > > > central directory structure. I download the section of the zip file I > > > need, directly read the zip file headers and use that information with > > > zlib to uncompress the data. The files I am examining will always be > > > compressed using deflate, with a wbits value of -15(minus for > > > headerless data because I am unsure whether the zip file header is > > > what zlib expects). > > > > I can not find anywhere in the PK Zip Application notes (http://www.pkware.com/documents/casestudies/APPNOTE.TXT) how to > > > determine the value I should uze for wbits with zlib.decompress. I > > > have determined it is -15 from experimentation. Does anyone know the > > > answer to this? > > > Okay, I found part of the answer here in the zip app notes > > [quote] > > general purpose bit flag: (2 bytes) > > > ? ? ? ? ? Bit 0: If set, indicates that the file is encrypted. > > > ? ? ? ? ? (For Method 6 - Imploding) > > ? ? ? ? ? Bit 1: If the compression method used was type 6, > > ? ? ? ? ? ? ? ? ?Imploding, then this bit, if set, indicates > > ? ? ? ? ? ? ? ? ?an 8K sliding dictionary was used. ?If clear, > > ? ? ? ? ? ? ? ? ?then a 4K sliding dictionary was used. > > ? ? ? ? ? Bit 2: If the compression method used was type 6, > > ? ? ? ? ? ? ? ? ?Imploding, then this bit, if set, indicates > > ? ? ? ? ? ? ? ? ?3 Shannon-Fano trees were used to encode the > > ? ? ? ? ? ? ? ? ?sliding dictionary output. ?If clear, then 2 > > ? ? ? ? ? ? ? ? ?Shannon-Fano trees were used. > > > ? ? ? ? ? (For Methods 8 and 9 - Deflating) > > ? ? ? ? ? Bit 2 ?Bit 1 > > ? ? ? ? ? ? 0 ? ? ?0 ? ?Normal (-en) compression option was used. > > ? ? ? ? ? ? 0 ? ? ?1 ? ?Maximum (-exx/-ex) compression option was > > used. > > ? ? ? ? ? ? 1 ? ? ?0 ? ?Fast (-ef) compression option was used. > > ? ? ? ? ? ? 1 ? ? ?1 ? ?Super Fast (-es) compression option was used. > > [/quote] > > > Now I just don't understand Why Normal deflate corresponds to 15 > > wbits, and why I have to use headerless for the data, i.e. wbits = -15. > > Seems the bit flags are not properly set, bit 2 should be 0 and bit 1 > should be 1, to correspond to maximum compression i.e. wbit = 15. > Still don't know why wbits has to be negative.- Hide quoted text - > > - Show quoted text - Arg! Tried a different tack. Took the file header plus compressed file and concatenated with central directory. Now need only zipfile module. From walterbyrd at iname.com Mon Dec 22 12:48:19 2008 From: walterbyrd at iname.com (walterbyrd) Date: Mon, 22 Dec 2008 09:48:19 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: On Dec 22, 10:13?am, r wrote: > Since the > advent of Ruby(Python closet competitor), Python's hold on this niche > is slipping. About the only place I ever hear of ruby being used is web development with RoR. When it comes to web development, it seems to me that ruby (because of rails) is far more popular than python. It seems to me that ruby is the niche player, and python (with fairly new frameworks) is trying to catch up to ruby in that niche. It seems to me that the python web framework that best competes with rails, is Django, and Django 1.0 just came out a few months back. > A lot of Ruby noobies don't even realize that most of > Ruby is an out-right plagiarism of Python. Maybe. But the rails framework seems to have a different philosophy than the django, turbogears, or pylons, frameworks. RoR values convention over configuration, and has a lot of "magic" whereas the python frameworks seem to have the opposite philosophy - in those regards. I see pros and cons to both approaches. I wonder what the market with think? > Now since Python *is not* the only language on it's block, we have to > compete with our main nemesis(Ruby) for survival I think both python and ruby will "survive." I think python is also competing with perl in the sysadmin space - although I see perl as being much more popular there. From deets at nospam.web.de Wed Dec 17 09:17:35 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 17 Dec 2008 15:17:35 +0100 Subject: Python, XML and XPath References: Message-ID: <6qsfvvFeen6dU1@mid.uni-berlin.de> Hole wrote: > Hi all, > > I hope this is not an "overasked" question but I find myself quite > confused about python xml management (I have to use python for a > project and I come from java world, you know...where frameworks, > libraries and tools to use are standard de iure or standard de facto). I suggest you use one of the available binary builds for windows: http://pypi.python.org/pypi/lxml/2.1 Diez From grahn+nntp at snipabacken.se Mon Dec 8 16:32:31 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 8 Dec 2008 21:32:31 GMT Subject: Source code generation using Python References: <82098706-978f-4920-ac75-57ef3573ac44@x38g2000yqj.googlegroups.com> Message-ID: On Sat, 6 Dec 2008 13:47:26 -0800 (PST), ats wrote: > Hello, > > This is my first posting to a Python group (and I'm starting with > Python seriously only now) , so bear with me if I make some mistakes. > > I want to generate 3 different versions of a C++ source code, > basically injecting different flavours of inline assembler depending > on target compiler/CPU. > > Code generation should be integrated into a 'master source file' which > is the processed and generates the right code for GCC / MSVC or other > cases. Something like: > > int FastAdd( int t1, int t2 ){ > int r; > ##if USE_INLINE_ASM > #ARG( eax, "t1") > #ARG( ebx, "t2") > #ASM( "add", ebx, eax ) > #RES( eax, "r" ) > ##else > r = t1+t2; > ##endif > return r; > } You didn't say explicitly, so I have to ask: is there a reason you cannot use the C++ preprocessor? It does exactly what you describe, and would be the least surprising solution to the readers. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From renesd at gmail.com Thu Dec 4 22:06:10 2008 From: renesd at gmail.com (illume) Date: Thu, 4 Dec 2008 19:06:10 -0800 (PST) Subject: Python 3.0 C API migration tools, or docs? References: <008877d2-8705-48a6-bb09-6c31c6b77970@p2g2000prf.googlegroups.com> <1a5cf43f-5802-4c69-9226-18cbc6256c0c@k19g2000yqg.googlegroups.com> Message-ID: Cool thanks Benjamin! Maybe it should be in a wiki as well? So that as people convert their modules we can add notes as well. I started a wiki with that in mind here: http://wiki.python.org/moin/cporting It'd be good if there was a link from the 2to3 docs, and in the C API docs to either/both of these resources. I thought there'd be much more help for people migrating considering the 2to3 tool exists... but I'll get over it... hehe. cheers, On Dec 5, 1:23?pm, Benjamin wrote: > On Dec 4, 7:45?pm, illume wrote: > > > Hi, > > > are there migration tools for C API migration to python 3? > > > I'm sure there must be some code somewhere to help change stuff over > > right? > > > I don't see any docs for migrating code from 2.x to 3.x either:http://docs.python.org/3.0/c-api/index.html > > At the moment all that is officially available is this rather > incomplete howto:http://docs.python.org/howto/cporting.html > > > > > Help needed with this! > > > cheers, > > From sibteym at infotechsw.com Mon Dec 29 05:31:42 2008 From: sibteym at infotechsw.com (Sibtey Mehdi) Date: Mon, 29 Dec 2008 16:01:42 +0530 Subject: poblem regarding opening a html file Message-ID: <022701c969a0$a4541ef0$5fc513ac@pwit.com> Hi I have a GUI application (wxpython) that calls another GUI Application. I m using os.system (cmd) to launch The second GUI, in the second GUI I m trying to open the html file using the os.startfile (filename) function but It takes lots of time to open the html file. If I am running only the second application then 'os.startfile' quickly open the html file. Any one can help me to solve this problem. Thanks. Sibtey -------------- next part -------------- An HTML attachment was scrubbed... URL: From saju.pillai at gmail.com Thu Dec 11 08:33:53 2008 From: saju.pillai at gmail.com (Saju Pillai) Date: Thu, 11 Dec 2008 05:33:53 -0800 (PST) Subject: Python, threading References: Message-ID: On Dec 11, 6:06?pm, SMALLp wrote: > Hy. I have a problem! I'm making multi thread application (client, > server) using wxPython for GUI, and threading.Thread for threding. > > Clients connect and when they are connected (evry thread handles one > connection) threads change main window. > > I neded tip how to make communication between threeds. Threads already share data your problem would likely be to synchronize the threads - threading.Sempahore & threading.Lock will help Maybe you want some threads to wait while other thread(s) do some work ? - threading.Event & threading.Condition The documentation on "threading" module is where you should start. -srp -- http://saju.net.in From prologic at shortcircuit.net.au Sun Dec 7 23:50:57 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Dec 2008 14:50:57 +1000 Subject: infering the number of args a function takes at runtime In-Reply-To: <47c890dc0812072045g3b9d17c8r5768028afd22262d@mail.gmail.com> References: <47c890dc0812072045g3b9d17c8r5768028afd22262d@mail.gmail.com> Message-ID: On Mon, Dec 8, 2008 at 2:45 PM, Chris Rebert wrote: > On Sun, Dec 7, 2008 at 8:39 PM, sniffer wrote: >> hi all, >> i am a python newbie, in a project currently doing i need to find out >> the number of arguments that a function takes at runtime.? Is this >> possible ,if so how do i do this,i ve looked through the python >> documentation but couldnt find anything.any help will be great > > You want inspect.getargspec() or one of its friends in the `inspect` > module. See http://docs.python.org/library/inspect.html#inspect.getargspec Also, I have to ask: Why do you need to do this ? Please show some code samples of what you're trying to achieve and what the problem is ? cheers James -- -- -- "Problems are solved by method" From gagsl-py2 at yahoo.com.ar Wed Dec 24 12:48:34 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2008 15:48:34 -0200 Subject: Custom C Exception Subclasses References: <41f291ff-d7bd-4334-8689-636e95524cdc@b38g2000prf.googlegroups.com> Message-ID: En Wed, 24 Dec 2008 15:00:36 -0200, Ivan Illarionov escribi?: > On Dec 24, 6:42?pm, Ross wrote: >> For a project that I am doing, it would be useful to have an exception >> class that stores some additional data along with the message. >> However, I want to be able to store a couple pointers to C++ classes, >> so I can't just use an exception created with PyExc_NewException. ?If >> I were to subclass the built-in Exception type, I would need to have >> access to the PyExc_ExceptionObject, but the headers only give >> PyExc_Exception, the type object. ?This seems like a rather >> straightforward task, but I can't seem to find any documentation for >> it. ?Does anyone know how to do this? ?Thanks! > > When you raise an exception in C++ you can set it to ANY Python object > via PyErr_SetObject and that object could store pointers to C++ > classes. Remember that exceptions should inherit from BaseException; although this rule isn't enforced in Python 2.6, 3.0 doesn't allow that. It isn't explicitely written in the docs, but I think that PyErr_SetObject won't allow you to pass an object which is not an instance of its first argument. -- Gabriel Genellina From bdesth.quelquechose at free.quelquepart.fr Wed Dec 3 13:16:29 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 Dec 2008 19:16:29 +0100 Subject: python an sqlite objects In-Reply-To: References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <4936bceb$0$16783$426a34cc@news.free.fr> Message-ID: <4936dab7$0$9107$426a74cc@news.free.fr> skip at pobox.com a ?crit : > Bruno> Or if you want something more portable, serialize the object to > Bruno> json. At least you'll have a chance to deserialize it with some > Bruno> other language. > > Assuming json can serialize more-or-less arbitrary Python objects. I assume the OP knows what kind of objects he's going to serialize. > Can > it serialize class instances? instances of which class ?-) More seriously: simplejson knows how to serialize most builtin types. For other types, you have to write your own serializer, but it's _usually_ quite simple. Most of the time, you want to serialize the instance's __dict__. From max at alcyone.com Sat Dec 6 19:34:56 2008 From: max at alcyone.com (Erik Max Francis) Date: Sat, 06 Dec 2008 16:34:56 -0800 Subject: Guido's new method definition idea In-Reply-To: <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> Message-ID: Russ P. wrote: > Python already uses shorthand extensively. How about "def"? For people > who are so worried about self-explanatory symbols, what the heck does > that stand for? Default? Defeat? Defect? Defunct? Defer? That's pretty silly; it's pretty obvious that `def` means "define," and even if that weren't obvious on its face, in context it's _really_ obvious. `def f(): ...` certainly isn't going to be confused to a request to defecate on something called `f`, after all -- which is about as plausible as your other suggestions. `$` as a shortcut for self, on the other hand, gives absolutely no mnemonic indication what it stands for, and users would be simply left guessing. P.S. You're beating a long-dead horse here; your precise proposal has been brought up countless times on comp.lang.python and shot down every single time for the same reason. It isn't going to happen. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis There are not fifty ways of fighting, there is only one: to be the conqueror. -- Andrew Malraux, 1937 From robert.kern at gmail.com Wed Dec 3 18:15:48 2008 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 03 Dec 2008 17:15:48 -0600 Subject: "as" keyword woes In-Reply-To: <01470229$0$20670$c3e8da3@news.astraweb.com> References: <493701f0$0$194$e4fe514c@news.xs4all.nl> <01470229$0$20670$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > While I feel sympathy for the OP, I do have to ask: he's been using > Python 2.5 for, what, a couple of years now? How many times did he see > the depreciation warning, and almost certainly the pending depreciation > warning before that? Python-dev has been talking about making "as" a > keyword since at least Python 2.3. Why wait until after version 2.6 is > released before saying anything? It's entirely possible that he did not see the warning. Python 2.5 has a bug where the warning gets silenced by an intervening import. http://bugs.python.org/issue3936 -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From zxo102 at gmail.com Sat Dec 27 00:03:24 2008 From: zxo102 at gmail.com (zxo102) Date: Fri, 26 Dec 2008 21:03:24 -0800 (PST) Subject: How to display Chinese in a list retrieved from database via python References: <22be506d-91c2-4727-ace7-2e3382b6d214@g3g2000pre.googlegroups.com> <979fdf6d-0500-47ba-87fd-0f0361ca3059@p2g2000prf.googlegroups.com> Message-ID: <19680ed2-c78f-4ab9-8ca0-8ce26fd5b6a7@o4g2000pra.googlegroups.com> On 12?26?, ??3?16?, "Mark Tolonen" wrote: > "zxo102" wrote in message > > news:979fdf6d-0500-47ba-87fd-0f0361ca3059 at p2g2000prf.googlegroups.com... > > > > > > > On 12?26?, ??4?58?, "Gabriel Genellina" > > wrote: > >> En Thu, 25 Dec 2008 07:27:03 -0200, zxo102 escribi?: > > >> > On 12?25?, ??3?35?, "Chris Rebert" wrote: > >> >> On Wed, Dec 24, 2008 at 11:29 PM, zxo102 wrote: > >> >> > Hi, > >> >> > I retrieve some info in Chinese from postgresql and assign it to > >> >> > a > >> >> > variable 'info' defined in javascript of a html page: > >> >> > var info = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce > >> >> > \xc4'] > >> >> > But I want it to be > >> >> > var info = ['??','??','??'] > >> >> > since in html pages (via javascript), the items in chinese out of > >> >> > the > >> >> > former :['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4'] > >> >> > can > >> >> > not be displayed correctly when it is inserted into a html page. If > >> >> > the list is var info = ['??','??','??'] , then everything > >> >> > works > >> >> > fine. > > >> > The html code is as follows > > >> > test > >> > > >> > > > >> > But the '??' is '\xd6\xd0\xce\xc4'. When row01 and row02 is called > >> > from somewhere, > >> > '\xd6\xd0\xce\xc4' can not be displayed correctly as '??' in html > >> > environment. > > >> You forgot to specify the page encoding, gb2312 presumably. If adding the > >> encoding does not help, I'd say the problem must reside on how you later > >> use row01 and row02 (your html page does not those variables for > >> anything). '??' is the same as '\xd6\xd0\xce\xc4', and both javascript > >> and Python share the same representation for strings (mostly) so this > >> should not be an issue. > > >> My PC is unable to display those characters, but I get "true" from this: > > >> test > >> > > >> -- > >> Gabriel Genellina > > > I did that: , but it does not work. Alert('\xd6\xd0\xce\xc4') > >> displays some "junks". I am thinking there may be some way to convert > >> '\xd6\xd0\xce\xc4' to '??' in the list with python before I generate > >> the html page. As a result, when I open the html file with Vi, I can see > >> '??' directly instead of '\xd6\xd0\xce\xc4'. That will solve my > >> problem. > > > Any ideas? > > Use charset=gb2312 instead of charset='gb2312'(remove single quotes). > > I was able to display ?? successfully with this code: > > f=open('test.html','wt') > f.write(''' > > test > \xd6\xd0\xce\xc4''') > f.close() > > -Mark- ??????? - > > - ??????? - Mark, I have exactly copied your code into the htdocs of my Apache server, test \xd6\xd0\xce\xc4 but it still shows me \xd6\xd0\xce\xc4. Any ideas? ouyang From steve at REMOVE-THIS-cybersource.com.au Tue Dec 16 20:26:44 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 17 Dec 2008 01:26:44 GMT Subject: How to modify a program while it's running? References: Message-ID: <01584cbd$0$20656$c3e8da3@news.astraweb.com> On Tue, 16 Dec 2008 13:25:17 -0700, Joe Strout wrote: > Here's my situation: I'm making an AIM bot, but the AIM server will get > annoyed if you log in too frequently (and then lock you out for a > while). So my usual build-a-little, test-a-little methodology doesn't > work too well. Ouch! What AIM server are you running? Perhaps you need a less curmudgeonly one? > So I'd like to restructure my app so that it can stay running and stay > logged in, yet I can still update and reload at least most of the code. > But I'm not sure what's the best way to do this. Should I move the > reloadable code into its own module, and then when I give my bot a > "reload" command, have it call reload on that module? Will that work, > and is there a better way? That should work for functions, but less successfully with classes. The problem is that existing objects will still have the old behaviour even after reloading the class. In the interactive interpreter, the easiest way around that is to just throw the instance away and recreate it. That's not very convenient. You may be able to work around that by keeping a list of instances, then going through each one and saying: instance.__class__ = mymodule.MyClass although I haven't tried this and don't know if it even works. -- Steven From bdesth.quelquechose at free.quelquepart.fr Sun Dec 14 14:20:40 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 14 Dec 2008 20:20:40 +0100 Subject: Looking for the best way to translate an idiom In-Reply-To: References: <4945406a$0$1127$426a74cc@news.free.fr> Message-ID: <49456a3f$0$27546$426a74cc@news.free.fr> Steve Holden a ?crit : > Bruno Desthuilliers wrote: > [...] >> if you only want the first returned value, you can just apply a slice: >> >> def f(): >> return 1,2,3 >> >> a = f()[0] + 1 >> > That isn't a slice, it's indexing Yeps, sorry - and thanks for the correction. From mailmaverick666 at gmail.com Fri Dec 5 02:17:05 2008 From: mailmaverick666 at gmail.com (rishi pathak) Date: Fri, 5 Dec 2008 12:47:05 +0530 Subject: CONNECTION TIMED OUT ERROR using urllib2 In-Reply-To: <726d283d0812042236j792f4706v373ca6449861e3e2@mail.gmail.com> References: <726d283d0812042217w41a0288eg3ee79d4ffdb5ff4b@mail.gmail.com> <180b672e0812042227j12a4d647k84e507dfae77d665@mail.gmail.com> <726d283d0812042236j792f4706v373ca6449861e3e2@mail.gmail.com> Message-ID: <180b672e0812042317v55308ff1x42959d08dfe63bb5@mail.gmail.com> Before executing script do export http_proxy=http://:/ On Fri, Dec 5, 2008 at 12:06 PM, svalbard colaco wrote: > Hi rishi, > > Thanks for ur reply, > yes i set the following enviroment variables (FC6 platform) > http_proxy,http_user,http_password > > But i get the same error; Can u tell me which other variables i need to > set or am i going wrong in the syntax of these > variables? > > Regards > sv > > > On Fri, Dec 5, 2008 at 11:57 AM, rishi pathak wrote: > >> Are you sitting behind a proxy. If so then you have to set proxy for http >> >> On Fri, Dec 5, 2008 at 11:47 AM, svalbard colaco < >> svalbardcolaco at gmail.com> wrote: >> >>> Hi all >>> >>> I have written a small code snippet to open a URL using urllib2 to open a >>> web page , my python version is 2.4 but i get an urlopen error called >>> connection timed out >>> >>> The following is the code snippet >>> >>> *import urllib2 >>> >>> f = urllib2.urlopen('http://www.google.com/') >>> print f.read(100)* >>> >>> >>> where as the same url http://www.google.com/ works through my browser. >>> >>> The following is the back trace : >>> >>> File "test_url.py", line 3, in ? >>> f = urllib2.urlopen('http://www.google.com/') >>> File "/usr/lib/python2.4/urllib2.py", line 130, in urlopen >>> return _opener.open(url, data) >>> File "/usr/lib/python2.4/urllib2.py", line 358, in open >>> response = self._open(req, data) >>> File "/usr/lib/python2.4/urllib2.py", line 376, in _open >>> '_open', req) >>> File "/usr/lib/python2.4/urllib2.py", line 337, in _call_chain >>> result = func(*args) >>> File "/usr/lib/python2.4/urllib2.py", line 1021, in http_open >>> return self.do_open(httplib.HTTPConnection, req) >>> File "/usr/lib/python2.4/urllib2.py", line 996, in do_open >>> raise URLError(err) >>> *urllib2.URLError: >>> >>> >>> Any pointers in this regard will be of great help. >>> >>> Thanking you'll in advance. >>> >>> Regards, >>> sv >>> >>> >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >>> >> >> >> -- >> Regards-- >> Rishi Pathak >> Pune-Maharastra >> > > -- Regards-- Rishi Pathak Pune-Maharastra -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul.hermeneutic at gmail.com Sat Dec 6 11:36:44 2008 From: paul.hermeneutic at gmail.com (Paul Watson) Date: Sat, 06 Dec 2008 10:36:44 -0600 Subject: Running Python 2 and Python 3 on the same machine In-Reply-To: <493A4C89.8070007@v.loewis.de> References: <1228424486.5873.6.camel@linux-3eb6.site> <49387f7e$0$27857$9b622d9e@news.freenet.de> <1228489547.5613.10.camel@linux-3eb6.site> <4939c6ef$0$6534$9b622d9e@news.freenet.de> <1228539820.27659.21.camel@linux-3eb6.site> <493A4C89.8070007@v.loewis.de> Message-ID: <1228581374.3651.16.camel@linux-3eb6.site> On Sat, 2008-12-06 at 10:57 +0100, "Martin v. L?wis" wrote: > > Ok. I built the source on an openSUSE 11.0 system. I used 'sudo make > > altinstll'. It created an executable /usr/local/bin/python3.0 file. > > Nothing was touched in /usr/bin. > > Ah, then you missed the fun part. Take a look at the install: target > in the Makefile. > > > I need to start writing some code with Python 3. I want to write the > > code in such a way that it can be easily shared with others with the > > least difficulty and overhead as possible. How should I write the code > > to enable this? What, if anything, should I assume about another > > system's configuration? > > I don't quite understand the problem. Sharing code is very easy over > the internet. You can upload it on PyPI (say), or mail it. So you > must be asking for something else. > > > As someone suggested before, naming the files as '.py3' is probably a > > bad idea in the long run. It also does not really solve the problem. > > > > I could use a shebang. But, what should it specify? If I use > > 'python3.0', then that will soon be quite old. If I make up a link for > > python3 -> python3.0, that would work, but then every other system that > > is to run the code must that link also. However, I am thinking that > > this would be the best long term answer. > > Well, this will be rejected. It might be a good medium-term answer, but > it is a *bad* long-term answer. In the long term, Python 2 will > disappear, and we are stuck with calling the interpreter python3. > > > If I write scripts for Python 3, another developer writes scripts for > > Python 2, and a common customer wants to install both of our packages > > onto a single machine, then what is the best plan for everyone to make > > that happen with as little difficulty as possible? > > My recommendation is to use distutils, for a long-term answer. People > will run "python3.0 setup.py install", and distutils' install_scripts > will replace the shebang line with the actual path to Python 3.0. > This has not only the advantage of continuing to work for 3.1; it has > also the advantage that scripts installed into a private location will > be run by the correct interpreter (rather than relying on the > interpreter being in /usr/bin, or on PATH). > > For "quick" sharing, the shebang line "#!/usr/bin/env python3.0" will > be enough. When Python 3.1 gets released, you may find yourself writing > scripts that run only on Python 3.x for x>=1 (i.e. won't run on 3.0, > because you use a new feature in 3.1). In that case, presence of a > python3 executable won't help, either. > > Regards, > Martin Yes! Finally we are getting somewhere. I can see how this can work for distributed packages. I still have two questions. I do not mean to take your individual time for this. If there is documentation I should read, please suggest it. First, let's say that the package has been installed using distutils and the shebang line is set to '#!/usr/local/bin/python3.0'. Now, Python 3.1 is released with a number of speed performance improvements and several security fixes. The existing application is hardcoded to use Python3.0 directly. Does distutils include any mechanism to update this setting so that the package will use a different interpreter? Must the application be installed again in order to update the shebang lines? Second, we frequently have a number of standalone utilities written in Python. When the task requires excessive effort to write in a shell script, Python is a great answer. What is your recommendation for the shebang line on one-off, single .py file utility scripts? From cjw at ncf.ca Tue Dec 2 15:10:40 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Tue, 02 Dec 2008 15:10:40 -0500 Subject: Multiple Versions of Python on Windows XP In-Reply-To: <493592EE.9090005@v.loewis.de> References: <4934de22$0$27863$9b622d9e@news.freenet.de> <493592EE.9090005@v.loewis.de> Message-ID: Martin v. L?wis wrote: >>>> What changes are made to the registry? >>> For a complete list, see Tools/msi/msi.py in the source tree. >> I have scanned the file: >> http://svn.python.org/projects/python/branches/py3k/Tools/msi/msi.py >> >> I don't find anything that addresses this issue. > > Read the add_registry function. You may need to first understand > how the Registry table in an MSI file works. > >> I am seeking some mechanism such that any of Python 2.5, Python 2.6 or >> Python 2.6 can be chosen as the currently active version. > > If Glenn Lindermann's answer doesn't help, you need to explain: > what is a "currently active version"? How is one Python version > more active than any other? > >> I was hoping that there is some simpler way than the "Repair" procedure. > > See Glenn Lindermann's answer. I'll look at it > >>> It would be good to be more specific with such statements: what troubles >>> specifically? If I play dumb, I'd say "of course - windows explorer >>> doesn't support editing Python files; you need a text editor". Using a right click, one can open any .py file with say SciTe. Within SciTe, one can Run the current file. It would be good to have the appropriate version (my use of "default") preselected. >> Yes, I should have been clearer. The PyScripter application locks up >> and must be killed, using the Task Manager. > > I think you need to report that to the PyScripter authors as a bug. > I can't imagine how the "currently active version" can affect what > PyScripter does. Yes, I'll do that. > I'll also follow up with Glenn Lindermann's answer. Many thanks, Best wishes, Colin W. > Regards, > Martin From castironpi at gmail.com Thu Dec 4 06:04:54 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 4 Dec 2008 03:04:54 -0800 (PST) Subject: "as" keyword woes References: <7dudnSS7uIn_KarUnZ2dnUVZ_tTinZ2d@earthlink.com> Message-ID: <10f6ca6d-35d8-45a6-9a3e-dbdd8aacdb78@d23g2000yqc.googlegroups.com> On Dec 4, 4:43?am, Dennis Lee Bieber wrote: > On Thu, 4 Dec 2008 01:28:56 -0800, "Warren DeLano" > declaimed the following in comp.lang.python: > > > In addition, note that my choice of a concise method identifier affects > > only my users. ?Python's introduction of a new keyword affects the > > entire Python world code base, so perhaps you should be directing your > > "choose better names" criticism in another direction? > > ? ? ? ? Dropping in... > > ? ? ? ? If a "chosen name" mirrors a syntactic element -- whether reserved > or not -- I'd consider that name potentially ambiguous or conflicted. > > ? ? ? ? While "if" has been long a reserved word, I can as easily see > someone using "if" as a shorthand name for "interface". And if "if" were > not a reserved word, one might encounter code on the lines of > > ? ? ? ? if = if + 1 > > which is quite obnoxious to my eyes... or maybe > > ? ? ? ? if if.connected: > ? ? ? ? ? ? ? ? if.close() Does the OP hold the following should be legal? if if or or: and( for ) if not: while( def ) If not, it's an exception to Python's trend of not handcuffing programmers. From castironpi at gmail.com Thu Dec 18 16:46:45 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 18 Dec 2008 13:46:45 -0800 (PST) Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> Message-ID: <7e23a789-84c3-47b9-b040-ca7dd062d058@a37g2000pre.googlegroups.com> On Dec 17, 7:16?pm, "Gabriel Genellina" wrote: > En Wed, 17 Dec 2008 22:46:32 -0200, Aaron Brady ? > escribi?: > > > > > On Dec 17, 5:05?pm, "Gabriel Genellina" > > wrote: > >> En Wed, 17 Dec 2008 12:21:38 -0200, Jeremy Sanders ? > >> escribi?: > > >> > It would be nice if Python created pipes that are properly ? > >> inheritable by > >> > default by child processes, as they're mostly used for IPC. > > >> I'd say it is a bug in os.pipe implementation; they should be ? > >> inheritable ? > >> by default, as in posix (after all, the code is in "posixmodule.c"). > > > The code looks like this: > > > ? ?ok = CreatePipe(&read, &write, NULL, 0); > > ? ?Py_END_ALLOW_THREADS > > ? ?if (!ok) > > ? ? ? ? ? ?return win32_error("CreatePipe", NULL); > > ? ?read_fd = _open_osfhandle((Py_intptr_t)read, 0); > > ? ?write_fd = _open_osfhandle((Py_intptr_t)write, 1); > > > 'If lpPipeAttributes is NULL, the handle cannot be inherited.' ?You > > could populate a 'SECURITY_ATTRIBUTES' structure, or call > > DuplicateHandle on both of them. > > > A patch would look like this: > > > SECURITY_ATTRIBUTES sattribs; > > sattribs.nLength = sizeof(sattribs); > > sattribs.lpSecurityDescriptor = NULL; > > sattribs.bInheritHandle = TRUE; > > ok = CreatePipe(&read, &write, &sattribs, 0); > > Yes, that's exactly how os.popen does it (in posixmodule.c) > > > This still doesn't answer whether the file descriptor return by > > '_open_osfhandle' can be inherited too. > > It doesn't matter. The OS only cares about file handles, not C RTL ? > structures. Sorry for the multiple posts. File handles are inheritable by child processes, if the permissions are right. File descriptors are not. Is there a way that we can get the handles of a pipe into code, so that we can pass them to a subprocess? Will it take calling 'CreatePipe' from ctypes directly if on Windows? Or can 'os.pipe' be made to abstract that? If Windows can't inherit descriptors, 'os.pipe' should return handles, and 'os.read' &co. should accept them. It is a fairly large patch. From adi at lspl.net Mon Dec 8 09:27:13 2008 From: adi at lspl.net (sniffer) Date: Mon, 8 Dec 2008 06:27:13 -0800 (PST) Subject: dBase III files and Visual Foxpro 6 files References: Message-ID: <917126a8-c2c6-49c5-b001-07c953992dac@q26g2000prq.googlegroups.com> On Dec 8, 12:53?pm, Ethan Furman wrote: > Greetings All! > > I nearly have support complete for dBase III dbf/dbt files -- just > wrapping up support for dates. ?The null value has been a hindrance for > awhile but I nearly have that solved as well. > > For any who know of a cool dbf module already in existence for dBase III > and Visual Foxpro -- where were you six months ago when I was searching? > ? ;) ?Seriously, though, this has been a great learning experience for me. > > As I said -- dbf/dbt files are 99% ready. ?idx files -- no support: ?for > my purposes I just don't need them. ?I've found no problem in loading > tables up to 300,000 records with 50 fields per record, and re-ordering > them on the fly in memory. > > However, after putting much effort into this code, and wanting it to be > useful to others in the community, are there others who work with dbf > files that would need idx/cdx support? ?Or tables so large they won't > fit comfortably into memory? > > ~ethan~ hi ethan, great to hear that someone has finally written something for interacting with vfp6 data,when do you plan to release it From rhodri at wildebst.demon.co.uk Tue Dec 9 20:25:01 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Wed, 10 Dec 2008 01:25:01 -0000 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: On Mon, 08 Dec 2008 14:24:59 -0000, Rasmus Fogh wrote: > On the minus side there would be the difference between > '__equal__' and '__eq__' to confuse people. This is a very big minus. It would be far better to spell __equal__ in such a way as to make it clear why it wasn't the same as __eq__, otherwise you end up with the confusion that the Perl "==" and "eq" operators regularly cause. -- Rhodri James *-* Wildebeeste Herder to the Masses From google at mrabarnett.plus.com Thu Dec 11 21:11:17 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 12 Dec 2008 02:11:17 +0000 Subject: newbie question: if var1 == var2: In-Reply-To: <37fc3229-b0a2-4d95-990f-61300fc2b257@r37g2000prr.googlegroups.com> References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> <44aa0191-e374-4bf0-b039-d05cfa996b1d@p2g2000prn.googlegroups.com> <37fc3229-b0a2-4d95-990f-61300fc2b257@r37g2000prr.googlegroups.com> Message-ID: <4941C845.3030909@mrabarnett.plus.com> John Machin wrote: > On Dec 12, 11:39 am, MRAB wrote: >> Jason Scheirer wrote: >>> On Dec 11, 3:49 pm, John Machin wrote: >>>> On Dec 12, 10:31 am, "Rhodri James" >>>> wrote: >>>>> On Thu, 11 Dec 2008 19:49:23 -0000, Steve Holden >>>>> wrote: >>>>>> Kirk Strauser wrote: >>>>>>> At 2008-11-29T04:02:11Z, Mel writes: >>>>>>>> You could try >>>>>>>> for item in fname: >>>>>>>> item = item.strip() >>>>>>> This is one case where I really miss Perl's "chomp" function. It >>>>>>> removes a >>>>>>> trailing newline and nothing else, so you don't have to worry about >>>>>>> losing >>>>>>> leading or trailing spaces if those are important to you. >>>>>> ... and it's so hard to write >>>>>> item = item[:-1] >>>>> Tsk. That would be "chop". "chomp" would be >>>>> if item[-1] == '\n': >>>>> item = item[:-1] >>>> Better: >>>> if item and item[-1] == '\n': >>>> return item[:-1] >>>> return item >>> Best: >>> return item \ >>> if not (item and item.endswith('\n')) \ >>> else item[:-1] >>> Though really you should be using item.rstrip() >> Why not just: >> >> item[:-1] if item.endswith('\n') else item > > Some possible reasons: > * because you might be supporting old versions of Python (my offering > runs on 1.5) > * because the " if else " syntax > gives you the screaming dry Edgar Britts > * because you'd prefer not to have the overhead of a method lookup and > method call > OK: if item[-1:] == '\n': return item[:-1] return item From almar.klein at gmail.com Mon Dec 8 09:10:41 2008 From: almar.klein at gmail.com (Almar Klein) Date: Mon, 8 Dec 2008 15:10:41 +0100 Subject: Guido's new method definition idea In-Reply-To: <493d1f03$0$32048$426a34cc@news.free.fr> References: <493a9fed$0$18973$426a34cc@news.free.fr> <493c1ff6$0$4942$426a34cc@news.free.fr> <49d12ec1-2be9-497b-80bc-9f0402a9086d@s20g2000yqh.googlegroups.com> <493d1f03$0$32048$426a34cc@news.free.fr> Message-ID: I like the transparancy and clearity of python, and the explicit self fits beautifully. Allowing a second way of defining your methods would only confuse newbies more I would think. I was a newby only half a year ago (or maybe I still am). The explicit self seems weird the very first time you see it, but very soon you see the beauty of it. The error message may be confusing sometimes, but as Guido says, I guess it's better to fix the error message rather than changing the language. -1 for me! As for the $ stuff, it makes things less transparant and yes, it's looks rather ugly. -1 on this one as well. Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Dec 24 02:03:19 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2008 05:03:19 -0200 Subject: socket send help References: Message-ID: En Wed, 24 Dec 2008 03:59:42 -0200, greywine at gmail.com escribi?: > New guy here. I'm trying to figure out sockets in order to one day do > a multiplayer game. Here's my problem: even the simplest examples > don't work on my computer: > > A simple server: > > from socket import * > myHost = '' Try with myHost = '127.0.0.1' instead - a firewall might be blocking your server. > s.listen(5) # allow 5 simultaneous connections Not exactly: your server program only handles a single connection at a time. The 5 above specifies how many connections may exist "on hold" waiting for you to accept() them. > connection.send('echo -> ' + data) That's fine for Python 2.6, but you must use b'echo -> ' with 3.0 > And a simple client: > > s.send('Hello world') # send the data Same as above, should be b'Hello world' with Python 3.0 > If I run testserver.py via the cmd prompt in Windows XP and then the > testclient.py program, I get the following error: > > Traceback (most recent call last): > File "C:\Python30\testclient.py", line 12, in > s.send('Hello world') # send the data > TypeError: send() argument 1 must be string or buffer, not str The above error message is wrong (and I think it was corrected on the 3.0 final release; if you got it with 3.0 final, file a bug report at http://bugs.python.org/ ) > This happens in 2.6 or 3.0 and with different example client & server > programs from the web. What am I missing? The error above surely comes from 3.0; with 2.6 you should get a different error (if it fails at all). Try again with 2.6.1. I didn't run the code but it looks fine -- if you got it from a book or article, unless it explicitely says "Python 3.0", assume it was written for the 2.x series. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Sat Dec 27 22:38:44 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 28 Dec 2008 01:38:44 -0200 Subject: C API: array of floats/ints from python to C and back References: Message-ID: En Sun, 28 Dec 2008 00:40:52 -0200, Daniel Fetchinson escribi?: >> You MUST check EVERY function call for errors! > > Yes, I know :) > Believe me, if you don't, there is a risk of crashing the program. And they're a lot harder to find and fix. >> And check the argument's type (how do you know it is a list?). Once you >> are sure the first parameter *is* a list, you may use the "macro" >> version >> of several functions, like PyList_GET_SIZE and PyList_GET_ITEM. > > The macro versions are preferable because they are faster? Yes, because they don't do any additional checking. PyList_GET_ITEM just retrieves the item; PyList_GetItem checks whether it is called on a list object, then checks if index is out of bounds, and only then goes to retrieve the item. >> You should check that both lists have the same length too. >> And you should check that elements are integers, or convertible to >> integers (in case of error, PyInt_AsLong returns -1 and PyErr_Occurred() >> is true) >> To fill the resulting tuple, use PyTuple_SET_ITEM instead. BTW, why >> return >> a tuple and not a list? > > No particular reason, other than the fact that I won't need to modify > these lists/tuples from python so whenever something will not change, > I use a tuple because it's immutable. Or this is not a very good > practice? There is no difference between lists and tuples in terms of > speed I suppose (getitem, setitem, etc). Usually lists represent an ordered collection of similar items, where position is not relevant (the third item is treated more or less the same as the tenth); by example, a list of attendants to certain event. It makes sense to process the whole list doing the same thing to each element, and it makes sense to ask "is this item in the list?." Tuples represent an ordered collection of dissimilar items, where position is relevant (because it identifies each item); by example, a row from a database table (name, address, age, phone number), or a point (x,y,z) in space. It isn't common to process the whole tuple doing the same thing for each element, and usually it doesn't make sense to look for certain item in the tuple. But it does make sense to refer to individual items like t[2], or t.age (namedtuple, 2.6 and up) From this point of view, lists and tuples are conceptually different - tuples aren't "frozen" lists. But this is just common usage, or maybe historical intent; of course you are free to use whatever structure you feel adequate. Once the list/tuple is created and filled, there is no speed difference accessing the individual items. Creating an empty list that grows one element at a time is slow for large lists (the memory block has to be re-allocated and copied over evry time it gets full) but this doesn't happen if you provide the final size when creating the list. -- Gabriel Genellina From prologic at shortcircuit.net.au Mon Dec 22 17:24:20 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 23 Dec 2008 08:24:20 +1000 Subject: Event Driven programming - Doubts In-Reply-To: <80f360e4-2880-4c66-a6b4-e05d6dbc9031@b41g2000pra.googlegroups.com> References: <80f360e4-2880-4c66-a6b4-e05d6dbc9031@b41g2000pra.googlegroups.com> Message-ID: On Tue, Dec 23, 2008 at 12:57 AM, Kottiyath wrote: > Hi, > I have been looking at Twisted and lately Circuits as examples for > event driven programming in Python. Wonderful! :) "circuits" that is :) > Even though I understood how to implement the code in these and > what is deferred etc, I have not yet understood the implementation of > deferred. I went through a lot of tutorials, but I guess most places > they expect that the user already understands how events are > generated. The tutorials mention that there is no more threads once > twisted is used. deferred to me is nothing more than scheduling "things" to happen "later". ie: Timers, or Timed Events. I clearly biased here as I'm the developer of circuits, so I can't comment on Twisted's design or architecture, but the way to achieve Twisted's so-called deferred (events?) is to use the Timer component, Timed Events. > My question is as follows: > I have not understood how the callbacks are hit without (a) > blocking the code or (b) having new threads. Again speaking in terms of circuits, but also in the event-driven paradigm: a) Event Handlers _can_ block - but ideally shouldn't (ihmo). b) Forking new threads/processes per event is mostly not necessary. (There are exceptions). > The usual example given is that of a program waiting for data coming > through a socket. In the tutorials, it is mentioned that -in an event > driven program, we schedule the code to hit when the remote server > gets back to us - . > Now, my question is - somebody has to still wait on that socket and > check whether the data is received, and once all the data is received, > call the appropriate callbacks. In the case of circuits' TCPServer component you simply poll it in your main event-loop. The pattern looks like this: from circuits.lib.sockets import TCPServer server = TCPServer(8000) while True: server.poll() server.flush() The TCPServer component has various builtin event handlers that do all the work for you and expose other more useful events to the application, such as: * connect * disconnect * read * error > Is twisted creating a micro-thread which just waits on the socket and > once the data is received, calls callFromThread for it to run on the > main loop? I can't comment - I tend to avoid threads where ever possible. > If so, Even though data locking etc is not a problem, are we not still > having threads? Will it not still cause scalability problems in high > traffic? Regarding scalability btw ... (in case you're interested) circuits comes with circuits.lib.web and several sets of Web Components. A lot of code was borrowed from the BaseHTTPServer from the python standard library and bits and pieces from CherryPy and the cgi module.... In terms of performance, it has a "raw" performance ~3k req/s on good hardware. Do have fun in your endeavours :) cheers James Circuits: http://trac.softcircuit.com.au/circuits/ From piyush.subscription at gmail.com Sat Dec 20 20:50:24 2008 From: piyush.subscription at gmail.com (Piyush Anonymous) Date: Sun, 21 Dec 2008 07:20:24 +0530 Subject: a small doubt Message-ID: <19ac19520812201750hb592e4dsa5ef7d2a1906c2ed@mail.gmail.com> i wrote this code -- class Person(object): instancesCount = 0 def __init__(self, title=""): Person.instancesCount += 1 self.id = "tempst" def testprint(self): print "blah blah" def __getattribute__(self, name): print "in get attribute" a = Person() a.testprint() print a.id ----- but i am getting this error ---- in get attribute Traceback (most recent call last): File "trapmethodcall1.py", line 15, in a.testprint() TypeError: 'NoneType' object is not callable ------ why is it so? __getattribute__ is called whenever an attribute or method is called, rt? or if i set __getattribute__ , i cannot have methods in class? actually my aim is to trap all method calls and keep a counter which is update whenever method called or returned. how should i go about it? -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Tue Dec 16 04:43:47 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Dec 2008 07:43:47 -0200 Subject: ethical questions about global variables References: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> Message-ID: En Tue, 16 Dec 2008 00:45:05 -0200, Giampaolo Rodola' escribi?: > Another doubt is the naming convention. PEP-8 states that global > variables should use the lower_case_naming_convention but I've seen a > lot of library module using the UPPER_CASE_NAMING_CONVENTION. What am > I supposed to do about it? Are you sure those UPPER_CASE names you've seen are actually variables? or constants like: CRLF = '\r\n' (ok, it's not a true "constant" because the language doesn't prevent you from modifying it... but the "intended usage" is to be a constant) -- Gabriel Genellina From bj_666 at gmx.net Sat Dec 6 04:18:20 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 6 Dec 2008 09:18:20 GMT Subject: Guido's new method definition idea References: <48db9$493a3e2b$d9a2276f$10794@news.hispeed.ch> Message-ID: <6puuasFa29upU1@mid.uni-berlin.de> On Sat, 06 Dec 2008 09:56:12 +0100, Antoine De Groote wrote: > try this: > >>>> import this > > and look at the 15th line... The reason why I'm against that change too. It adds a second, alternative way to express something that is already in the language. > I agree that for newcomers to Python, the class method definition might > seem strange. And after the change it continues to because they will run into *both* variants in tutorials, code, and books, so it might be even more confusing. Ciao, Marc 'BlackJack' Rintsch From luismgz at gmail.com Wed Dec 10 17:48:49 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Wed, 10 Dec 2008 14:48:49 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: <4b0f6c1a-9d3f-4fd7-8506-314d29ee87a8@k36g2000yqe.googlegroups.com> You are WRONG, WRONG, WRONG!! And when I say Wrong, I mean WRONG!!! And I am not saying that you are confussed. I say that you are WRONG! And when someone says so many times that you are wrong, it is because you are WRONG! And don't say that you are not wrong, because you are wrong! You are Wrong. Very Wrong. On Dec 10, 3:42?pm, cm_gui wrote: > http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-... > > I fully agree with Krzysztof Kowalczyk . > Can't they build a faster VM for Python since they love the language > so much? > > Python is SLOW. ? ?And I am not comparing it with compiled languages > like C. > Python is even slower than PHP! > > Just go to any Python website and you will know. > An example is:http://www2.ljworld.com/ > And this site is created by the creators of Django! > > And it is not just this Python site that is slow. There are many many > Python sites which are very slow. And please don?t say that it could > be the web hosting or the server which is slow ? because when so many > Python sites are slower than PHP sites, it couldn?t be the web > hosting. ? Also, Zope/Plone is even slower. > > Python is slow. Very slow. From castironpi at gmail.com Mon Dec 15 00:12:13 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 14 Dec 2008 21:12:13 -0800 (PST) Subject: stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> Message-ID: On Dec 14, 8:18?pm, Roy Smith wrote: > Steven D'Aprano wrote: > > All the positive thinking in the world won't help you: > > > * make a four-sided triangle; > > > * split a magnet into two individual poles; > > These two are fundamentally different problems. > > The first is impossible by definition. ?The definition of triangle is, "a > three-sided polygon". ?Asking for a "four-sided triangle" is akin to asking > for "a value of three which is equal to four". > > The second is only "impossible" because it contradicts our understanding > (based on observation) of how the physical universe works. ?Our > understanding could simply be wrong. ?We've certainly been wrong before, > and we will undoubtedly be proven wrong again in the future. ?When it comes > to things like electromagnetic theory, it doesn't take too many steps to > get us to the fuzzy edge of quantum physics where we know there are huge > questions yet to be answered. I agree. Most of his examples were tautologies. The magnet one was the exception. Then, to beat the O( n lg n ) limit, just break an assumption. > > * or design a comparison sort which does fewer than O(n*log n) two-way > > comparisons in the worst case, or fewer than O(n) comparisons in the best > > case. Make a three-way comparison, make a non-comparison sort, or make non- random inputs. From timr at probo.com Wed Dec 31 02:18:20 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 31 Dec 2008 07:18:20 GMT Subject: Easy-to-use Python GUI References: Message-ID: <617ml4tfvvhj45p0667f0ubr4f2g5onq57@4ax.com> "Joel Koltner" wrote: >... >One approach that I like comes from SAX BASIC/WinWrap, which is more or less a >clone of Microsoft's Visual BASIC for Applications, but they (apparently) >wanted everything to still be human-readable, so they have a simple GUI >("form") builder that generates code that looks like this: > >--- > > Begin Dialog UserDialog 850,497,"Export Control" ' %GRID:10,7,1,1 > > GroupBox 20,7,360,217,"Drill File Generation",.GroupBox1 > CheckBox 40,35,130,14,"Output drill file(s)",.genDrill > Text 40,63,270,28,"Identify via layers as any that contain this text in >their names:",.Text > TextBox 40,98,220,21,.viaLayerName > Text 40,140,100,14,"Output method:",.Text8 > DropListBox 160,140,180,21,DrillStyle(),.drillStyle > Text 40,175,130,28,"Select drill table units:",.Text2 > ListBox 200,175,120,28,unitNames(),.unitName > > OKButton 310,469,90,21 > CancelButton 410,469,90,21 > > End Dialog > >' GUI builder generates or modifies everything above, but can also be edited >by hand >' You write the following code... > > Dim dlg As UserDialog > > dlg.genDrill = 1 > ReDim DrillStyle(1) > DrillStyle(0) = "All Via Layers In One File" > DrillStyle(1) = "One File Per Via Layer" > dlg.drillStyle = 1 > > func=Dialog(dlg) > >--- > >This is pretty darned easy for me understand and modify either by hand or with >the GUI builder. Well, allow me to point out that the equivalent code in wxPython would not be very much longer than this. It's just spelled differently. Sure, you have a bit of a learning curve to climb, just like you do with any new development tool. Once you take the time to get familiar with it, you'd read the wxPython program just as easily as that Basic example. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From brian at thebdbulls.com Mon Dec 1 16:34:24 2008 From: brian at thebdbulls.com (bdbull) Date: Mon, 1 Dec 2008 13:34:24 -0800 (PST) Subject: Thread always alive References: Message-ID: <94510d10-691d-45e0-ac7e-f7c91c0ce34e@l39g2000yqn.googlegroups.com> > I am suspecting some kind of a leak on a IO object like a file or socket descriptor is still open. Are you sure you're closing them all? You mentioned a finally clause so is it possible that your code is throwing an exception before you clean everything up? From lists at cheimes.de Thu Dec 4 11:48:27 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 04 Dec 2008 17:48:27 +0100 Subject: Python 3 read() function In-Reply-To: References: Message-ID: Cro wrote: > Good day. > I have installed Python 3 and i have a problem with the builtin read() > function. > > [code] > huge = open ( 'C:/HUGE_FILE.pcl', 'rb', 0 ) > import io > vContent = io.StringIO() > vContent = huge.read() # This line takes hours to process !!! > vSplitContent = vContent.split > ( 'BIN;SP1;PW0.3,1;PA100,700;PD625,700;PU;' ) # This one i have neve > tried... > [/code] Do you really mean io.StringIO? I guess you want io.BytesIO() .. Christian From gagsl-py2 at yahoo.com.ar Sat Dec 13 23:48:39 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 14 Dec 2008 02:48:39 -0200 Subject: Bidrectional Subprocess Communication References: Message-ID: En Sat, 13 Dec 2008 18:19:29 -0200, Emanuele D'Arrigo escribi?: > I'm trying to replicate the positive results of the Client/Server > scripts from the thread "Bidirectional Networking", but this time > using a Process/SubProcess architecture. > > The SubProcess, acting as a server, is working just fine. But the > Process executing the SubProcess, the client, somehow doesn't hear any > of the standard output from the SubProcess. What am I missing? (Pipes don't work the same as sockets, although unix-like systems try hard to hide the differences...) - you have to close server.stdin when you don't have more data to send. The server will see an end-of-file and knows it has to exit the loop. Same thing on the client side. - you have to wait until the server answers, else it will get a "broken pipe" error or similar. - end-of-file, in Python, is detected when a read/readline returns an empty string - you sent "Stop!" without a \n - readline() on the server side would wait forever; it doesn't matter in the code below because server.stdin is explicitely closed. Below are the modified version of your programs: #clientTest.py import sys import threading from time import sleep from subprocess import Popen, PIPE ## Server Thread class ListenerThread(threading.Thread): def __init__(self, inChannel): threading.Thread.__init__(self) self.inChannel = inChannel def run(self): while True: data = self.inChannel.readline() if not data: # data=='' means eof break data = data.strip() print("serverTest.py says: " + data) print("Starting Client!") server = Popen("python serverTest.py", stdin=PIPE, stdout=PIPE) listenerThread = ListenerThread(server.stdout) listenerThread.start() server.stdin.write("Something very meaningful!\n") server.stdin.write("Stop!") server.stdin.close() # notify server: no more data listenerThread.join() # wait until server closes channel print("Client Stopped!") # serverTest.py import sys print("Starting Server!") while True: data = sys.stdin.readline() if not data: # data=='' means eof break data = data.strip() print("SERVER RECV: '" + data + "'") if(data == "Stop!"): break print("Server Stopped!") -- Gabriel Genellina From felipevaldez at gmail.com Wed Dec 3 15:10:45 2008 From: felipevaldez at gmail.com (fel) Date: Wed, 3 Dec 2008 12:10:45 -0800 (PST) Subject: Tired of coding. Message-ID: <40e958e2-60fb-4dbe-811b-e149d668b81c@f13g2000yqj.googlegroups.com> http://digg.com/programming/Tired_of_coding_try_FBP_Flow_Based_Programming From akineko at gmail.com Mon Dec 29 17:26:59 2008 From: akineko at gmail.com (akineko) Date: Mon, 29 Dec 2008 14:26:59 -0800 (PST) Subject: tkInter constraining the width only References: <2d06d584-f398-4bf2-9452-bc2d915b1d17@k19g2000yqg.googlegroups.com> Message-ID: Hello Roger, Thank you for your prompt response to my posting. Yes, it worked. I never thought of putting 0! A special trick not mentioned in the documentation. Thanks! Aki- On Dec 29, 1:01 pm, Roger wrote: > You want to set the max height to 0. I know this is counter- > intuitive. From ldo at geek-central.gen.new_zealand Tue Dec 2 17:52:07 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 03 Dec 2008 11:52:07 +1300 Subject: Multiple equates References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> Message-ID: In message , Cameron Laird wrote: > In article , > Lawrence D'Oliveiro wrote: > >>Cameron Laird wrote: >> >>> I've been trying to decide if there's any sober reason to advocate >>> the one-liner >>> >>> map(lambda i: a.__setitem__(i, False), [x1, x2, x3, ..., x1024]) >> >>Are lambdas like the Dark Side of Python? >> >>:) > > Enough so, apparently, that I'm reluctant even to touch that question. So how else would you express something like def shell_escape(Arg) : """returns Arg suitably escaped for use as a command-line argument to Bash.""" return \ re.sub \ ( r"[\<\>\"\'\|\&\$\#\;\(\)\[\]\{\}\`\!\~\ \\]", lambda Match : "\\" + Match.group(0), Arg ) # Need to catch anything that might be meaningful to shell #end shell_escape ? From sturlamolden at yahoo.no Fri Dec 12 09:30:43 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 06:30:43 -0800 (PST) Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> Message-ID: <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> On Dec 12, 3:08 pm, Marc 'BlackJack' Rintsch wrote: > No bug because a mutation *is* attempted. ``a += x`` calls `a.__iadd__` > which *always* returns the result which is *always* rebound to the name > `a`. Even with mutable objects where `__iadd__()` simply returns > `self`! No, a mutation is not attempted, even if __iadd__() always returns a value. If a rebinding of a member to the same member is attempted, the tuple should not raise an exception. The tuple should check that it is actually being *mutated* before it raises any exception. There is an attempted write to the tuple, but not an attempted mutation of the tuple. The tuple should tell the difference. Immutability does not imply inwriteability, if the write operation changes nothing. But the tuple raises an exception on any write attempt. From casey.mcginty at gmail.com Wed Dec 3 16:48:10 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Wed, 3 Dec 2008 11:48:10 -1000 Subject: Reverse zip() ? In-Reply-To: <333edbe80812021647i4621271p7f87dff8d0926951@mail.gmail.com> References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> <333edbe80812021647i4621271p7f87dff8d0926951@mail.gmail.com> Message-ID: > The corner case is when dealing with empty lists and there aren't > enough items to unpack. > > Another solution to zip(), with a slightly different behaviour for conner cases .... >>> a = (1,2,3) >>> b = (1,2,3) >>> c = (1,2,3,4) >>> zip(a,b) [(1, 1), (2, 2), (3, 3)] >>> map(None,a,b) [(1, 1), (2, 2), (3, 3)] >>> zip(a,c) [(1, 1), (2, 2), (3, 3)] >>> map(None,a,c) [(1, 1), (2, 2), (3, 3), (None, 4)] -------------- next part -------------- An HTML attachment was scrubbed... URL: From Scott.Daniels at Acm.Org Sat Dec 27 18:15:43 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 27 Dec 2008 15:15:43 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: Daniel Fetchinson wrote: > I have considered using ctypes but for my needs using the C API > directly seems more reasonable. array.array and numpy.array doesn't > fit my needs since I need to do long and complicated operations on the > two (pretty large) integer arrays that would be too slow using > array.array and numpy.array (I've verified this claim by benchmarking > a numpy.array based solution). OK, but if you go to array.array or numpy.array or ctypes, you can create a uniformly typed (C datatype) array , which is the key to getting any speed out of the deal. If you insist on using python lists, you are stuck with extracting data element by element from its Python language wrap. --Scott David Daniels Scott.Daniels at Acm.Org From steve at holdenweb.com Tue Dec 30 08:57:07 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Dec 2008 08:57:07 -0500 Subject: select.select and socket.setblocking In-Reply-To: <495A2548.8010007@shopzeus.com> References: <495A2548.8010007@shopzeus.com> Message-ID: Laszlo Nagy wrote: > I'm using this method to read from a socket: > > def read_data(self,size): > """Read data from connection until a given size.""" > res = "" > fd = self.socket.fileno() > while not self.stop_requested.isSet(): > remaining = size - len(res) > if remaining<=0: > break > # Give one second for an incoming connection so we can stop the > # server in seconds when needed > ready = select.select([fd], [], [], 1) > if fd in ready[0]: > data = self.socket.recv(min(remaining,8192)) # 8192 is > recommended by socket.socket manual. > if not data: > # select returns the fd but there is no data to read > -> connection closed! > raise TransportError("Connection closed.") > else: > res += data > else: > pass > if self.stop_requested.isSet(): > raise SystemExit(0) > return res > > > This works: if I close the socket on the other side, then I see this in > the traceback: > > File "/usr/home/gandalf/Python/Projects/OrbToy/orb/endpoint.py", line > 233, in read_data > raise TransportError("Connection closed.") > TransportError: Connection closed. > > Also when I call stop_requested.set() then the thread stops within one > seconds. > > Then I switch to non blocking mode, my code works exactly the same way, > or at least I see no difference. > > I have read the socket programming howto ( > http://docs.python.org/howto/sockets.html#sockets ) but it does not > explain how a blocking socket + select is different from a non blocking > socket + select. Is there any difference? > Well, ignoring your question for the moment, what's wrong with the following (untested) code? def read_data(self, size): data = "" while len(data) < size: d = self.socket.read(size-len(data)) if not d: raise TransportError("Socket closed while reading data") data += d return data I feel the raw socket operations are easier to understand and less confusing. Since you don't want to return until you've read the data there really doesn't seem to be any point using select(), which is mainly useful in asynchronous operations (in which case you would have to use non-blocking sockets). It's not obvious from your code how self.stop_requested is supposed to change the result of its is_set() method. Maybe that's where the select() comes in? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From stargaming at gmail.com Wed Dec 10 01:02:20 2008 From: stargaming at gmail.com (Robert Lehmann) Date: 10 Dec 2008 06:02:20 GMT Subject: List Problem References: Message-ID: <493f5b6c$0$27863$9b622d9e@news.freenet.de> On Tue, 09 Dec 2008 21:40:08 -0800, dongzhi wrote: > I have one problem for List. Like that: > > format='just "a" ""little"" test' > part = format.split('"') > print part > > the result is : ['just ', 'a', ' ', '', 'little', '', ' test'] > > the list part have 7 element. > > If I execute part[1], I have got 'a'. If I execute part[2], I have got > ' '. But, if I execute part[1::2], I have got ['a', '', '']. I don't > know why. Please tell me why. You're slicing your list with the arguments "start at 1, stop at the end, using a step size of 2." It's basically the same as ``part[1], part[1+2], part[1+2+2], ...``. Perhaps you wanted to do ``part[1:3]`` (meaning "start at 1, stop before 3"). See the Python Reference for details. http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode- list-tuple-buffer-xrange http://docs.python.org/reference/expressions.html#id8 HTH, -- Robert "Stargaming" Lehmann From wuwei23 at gmail.com Tue Dec 9 19:09:45 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 9 Dec 2008 16:09:45 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <4ridneQnkLrPkKDUnZ2dnUVZ8qbinZ2d@posted.plusnet> <986b6ea1-efba-4146-9704-5f9e3787c26a@a37g2000pre.googlegroups.com> Message-ID: On Dec 10, 9:19?am, Xah Lee wrote: > I'm not sure he's intentionally making Mathematica look bad or just > sloppiness. Actually, there's only one person here tainting Mathematica by association, and it's not Jon. From collin.day.0 at gmail.com Thu Dec 18 21:12:02 2008 From: collin.day.0 at gmail.com (Collin D) Date: Thu, 18 Dec 2008 18:12:02 -0800 (PST) Subject: Factoring Polynomials References: Message-ID: On Dec 18, 11:37?am, collin.da... at gmail.com wrote: > I am trying to write a simple application to factor polynomials. I > wrote (simple) raw_input lines to collect the a, b, and c values from > the user, but I dont know how to implement the quadratic equation > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > into python. Any ideas? I completed the code: #import from math import sqrt # collect data a = float(raw_input('Type a value: ')) b = float(raw_input('Type b value: ')) c = float(raw_input('Type c value: ')) # create solver def solver(a,b,c): if b**2 - 4*a*c < 0: return 'No real solution.' else: sol1 = -1 * b + (sqrt(b**2 - 4*a*c)) / 2*a sol2 = -1 * b - (sqrt(b**2 - 4*a*c)) / 2*a return (sol1, sol2) # execute print solver(a,b,c) Thanks to everyone who helped... This really expanded my knowledge on some of the mathematical functions in Python. From tavares at fe.up.pt Mon Dec 29 14:50:56 2008 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Mon, 29 Dec 2008 11:50:56 -0800 (PST) Subject: =?windows-1252?Q?Symposium_=93Image_Processing_and_Analysis=94_within?= =?windows-1252?Q?_the_ICCES=2709_Thailand_=96_Last_Announce_=26_Call_for_Papers?= Message-ID: <9e75ee2f-a417-4245-96ea-143aadd8913f@r15g2000prh.googlegroups.com> (Our apologies for cross-posting. We appreciate if you kindly distribute this information by your co- workers and colleagues.) ******************************************************************************************************* Symposium ?Image Processing and Analysis? Int. Conf. on Computational & Experimental Engineering and Sciences 2009 (ICCES'09) Phuket, Thailand, 8-13 April 2009 http://icces.org/cgi-bin/ices09/pages/index ******************************************************************************************************* Dear Colleague, Within the International Conference on Computational & Experimental Engineering and Sciences 2009 (ICCES'09), to be held in Phuket, Thailand, in 8-13 April 2009, we are organizing the Symposium ?Image Processing and Analysis?. Examples of some topics that will be considered in that symposium are: Image restoring, Description, Compression, Segmentation and Description; Objects tracking, Matching, Reconstruction and Registration; Visualization Enhance; Simulation and Animation; Software Development for Image Processing and Analysis; Grid Computing in Image Processing and Analysis; Applications of Image Processing and Analysis. Due to your research activities in those fields, we would like to invite you to submit your work and participate in the Symposium ?Image Processing and Analysis?. Important dates and Instructions: - 1 Jan 2009: Deadline for abstract submission; - 10 Jan 2009: End of abstract selection. For instructions and submission, please access to the conference website at: http://icces.org/cgi-bin/ices09/pages/index. Instructions for authors are available at: http://icces.org/cgi-bin/ices09/pages/guide. Please note, when submitting your work you should choose the Symposium ?Image Processing and Analysis?. If you intend to submit your work please notify as soon as possible the main organizer of your intention (tavares at fe.up.pt); The organizers are preparing a special issue of the International Journal Computer Modeling in Engineering & Sciences (CMES), ISSN: 1526-1492, dedicated to the Symposium ?Image Processing and Analysis? with extended papers of the works presented in the ICCES'09. With kind regards, The Organizers, Jo?o Manuel R. S. Tavares (tavares at fe.up.pt) Faculty of Engineering of University of Porto, Porto, Portugal Yongjie (Jessica) Zhan (jessicaz at andrew.cmu.edu) Carnegie Mellon University, Pittsburgh, USA Maria Jo?o M. Vasconcelos (maria.vasconcelos at fe.up.pt) Faculty of Engineering of University of Porto, Porto, Portugal From rayene.benrayana at gmail.com Mon Dec 1 09:04:33 2008 From: rayene.benrayana at gmail.com (Rayene Ben Rayana) Date: Mon, 1 Dec 2008 15:04:33 +0100 Subject: Python introspection and namespace weird question Message-ID: Hello everybody, Is there an easy way to do something like this in python ? >>> red_car = MyVehicleClass() >>> car = red_car >>> car.labels() ['red_car' , 'car' ] In other words, does an instance has access to its name pointers ? Thanks in advance, Rayene -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at microcorp.co.za Thu Dec 4 14:14:26 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 4 Dec 2008 21:14:26 +0200 Subject: Thread Tkinter problem References: <64c7402c-8b7b-4281-9d7d-1abdd6177d96@r15g2000prh.googlegroups.com><35672781-eca1-4139-8b5d-88c457960d62@g1g2000pra.googlegroups.com> <98353009-15ea-4029-99d1-42f9d32e7c27@r15g2000prh.googlegroups.com> Message-ID: <001a01c95648$5cd70800$0d00a8c0@hendrik> "Davy" wrote: >def gen_board_thread(): > print 'enter here' > gen_flip = 1 > while(True): You don't need the brackets: while True: is good enough > time.sleep(0.3) > if (data_queue.full() == False): write: if not data_queue.full(): , and lose the brackets here too. > if (gen_flip == 1): write: if gen_flip: (no brackets - not needed, ugly) > gen_flip = 0 > data = board_1 > else: > gen_flip = 1 > data = board_2 > data_queue.put(data) > print 'put', data_queue.qsize() HTH - Hendrik From wicijowski at gmail.com Sat Dec 27 15:51:37 2008 From: wicijowski at gmail.com (janislaw) Date: Sat, 27 Dec 2008 12:51:37 -0800 (PST) Subject: tkinter 3.0 multiple keyboard events together References: <600d4b68-6fe2-4c2c-b425-1a739430bb54@s9g2000prg.googlegroups.com> <7b5e466c-d75d-4e71-b559-f8a0d3718094@r15g2000prd.googlegroups.com> Message-ID: On 27 Gru, 15:08, Pavel Kosina wrote: > janislaw napsal(a): > > Use google to find the appropriate site, or browse this site, there > > are plenty of examples. You may want to examine the code I wrote to > > you to catch the idea: > > #---------------------- > > import Tkinter > > import pprint > > > tk = Tkinter.Tk() > > f = Tkinter.Frame(tk, width=100, height=100) > > msg = Tkinter.StringVar() > > msg.set('Hello') > > l = Tkinter.Label(f, ?textvariable=msg) > > l.pack() > > f.pack() > > > keys = set() > > > def keyPressHandler(event): > > ? ? keys.add(event.char) > > ? ? display() > > > def keyReleaseHandler(event): > > ? ? keys.remove(event.char) > > ? ? display() > > > def display(): > > ? ? msg.set(str(keys)) > > > f.bind_all('', keyPressHandler) > > f.bind_all('', keyReleaseHandler) > > > f.mainloop() > > Is this really the most simple solution how to do this in Tkinter? Is > there nothing cleaner "build inside"? Um, I could be only guessing what are you meant to do, unless you describe your problem in more detailed way. I.e. describe the desired behaviour, show code which you have, and describe the current behaviour. > This solution has disadvantage that after you release one key, that the > function keyPressHandler stopped to be called by the other pressed keys. > I would have not to build moving the player in KeyPresshandler, but on > another new function that would have to read periodically "keys" and to > act afterwards.... Hmmm. Maybe you'd like to hook into Tkinter event loop, i.e. by custom events if you don't like periodical polling. >From what I am guessing, you expect that 2 keyboard events are simultaneous and can be cached at the same time instant. Well that would be impossible, cause all the underlying hardware is sequential. You may have parallel stuff if you go down to VHDL and write your own hardware, but when you have a CPU, then you'll have to stick with writing programs. C'mon, 20 lines is not such a big deal. Regards JW From notvalid2 at sbcglobal.net Tue Dec 16 18:56:43 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Tue, 16 Dec 2008 15:56:43 -0800 Subject: WinMerge--B/W Shading of Printed Copy to Show Differences? Message-ID: <3jX1l.6876$pr6.3299@flpi149.ffdc.sbc.com> Is there a way to highlight differences between the two files when printing in b/w? Help suggests there may be some texturing, but all I see is color choices. -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From clp at rebertia.com Sat Dec 13 16:07:22 2008 From: clp at rebertia.com (Chris Rebert) Date: Sat, 13 Dec 2008 13:07:22 -0800 Subject: Python 3.0 crashes displaying Unicode at interactive prompt In-Reply-To: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> Message-ID: <47c890dc0812131307o119ae1bap37f28fadd9772f08@mail.gmail.com> On Sat, Dec 13, 2008 at 12:28 PM, John Machin wrote: > > Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> x = u'\u9876' >>>> x > u'\u9876' > > # As expected > > Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit > (Intel)] on win 32 > Type "help", "copyright", "credits" or "license" for more information. >>>> x = '\u9876' >>>> x > Traceback (most recent call last): > File "", line 1, in > File "C:\python30\lib\io.py", line 1491, in write > b = encoder.encode(s) > File "C:\python30\lib\encodings\cp850.py", line 19, in encode > return codecs.charmap_encode(input,self.errors,encoding_map)[0] > UnicodeEncodeError: 'charmap' codec can't encode character '\u9876' in > position > 1: character maps to > > # *NOT* as expected (by me, that is) > > Is this the intended outcome? When Python tries to display the character, it must first encode it because IO is done in bytes, not Unicode codepoints. When it tries to encode it in CP850 (apparently your system's default encoding judging by the traceback), it unsurprisingly fails (CP850 is an old Western Europe codec, which obviously can't encode an Asian character like the one in question). To signal that failure, it raises an exception, thus the error you see. This is intended behavior. Either change your default system/terminal encoding to one that can handle such characters or explicitly encode the string and use one of the provided options for dealing with unencodable characters. Also, please don't call it a "crash" as that's very misleading. The Python interpreter didn't dump core, an exception was merely thrown. There's a world of difference. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From pdorange at pas-de-pub-merci.mac.com Mon Dec 22 06:31:44 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Mon, 22 Dec 2008 12:31:44 +0100 Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> Christian Heimes wrote: > Pierre-Alain Dorange schrieb: > > I don't find any sign(x) function in the math library (return the sign > > of the value). > > I've read that math module is a wrapper to C math lib and that C math > > lib has not sign(), so... > > Starting with Python 2.6 the math and cmath modules have a copysign > function. I'm using 2.5.2 at that time, but copysign() is fine. with : s=copysign(1.0,x) it return the sign (-1.0, 0.0, +1.0) > > I've implement my own sign function of course (it's easy) but a standard > > one in math would be better and could be faster. > > Sure? :) I was... > Are you aware that the IEEE 754 standard makes a difference > between the floats +0.0 and -0.0? > > from math import atan2 > def sign(x): > if x > 0 or (x == 0 and atan2(x, -1.) > 0.): > return 1 > else: > return -1 Thanks As my need is for a game and that i do not have IEEE real concern, i would simply using my simple function (but not as accurate) : def sign(x): if x==0.0: return 0.0 elif x>0.0: return 1.0 else: return -1.0 -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From rdcollum at gmail.com Thu Dec 18 11:24:44 2008 From: rdcollum at gmail.com (Roger) Date: Thu, 18 Dec 2008 08:24:44 -0800 (PST) Subject: Tkinter unbinding Message-ID: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> I've done a lot of googling for this topic and I fear that it's not possible. I have a widget that is overloaded with several bindings. I want to be able to unbind one method form the same Event without destroying all the other bindings to the same event that's associated to the same widget. For example: import Tkinter def test(): print 'test' def test2(): print 'test2' root = Tkinter.Tk() funcid1 = root.bind("<1>", lambda e: test()) funcid2 = root.bind("<1>", lambda e: test2(), add='+') root.unbind("<1>", funcid2) root.mainloop() When run neither <1> binding will exist against the root because the unbind will unbind all the functions associated with that event. However, in this example, I only want to unbind test2 not test1. Any help is greatly appreciated. Thanks! Roger. From nospam at nospam.com Fri Dec 26 09:16:49 2008 From: nospam at nospam.com (Gilles Ganault) Date: Fri, 26 Dec 2008 15:16:49 +0100 Subject: [2.5.1] Str.Replace() doesn't work? Message-ID: Hello I need to parse an HTML file where records aren't homogenous, so I figured I could run a first loop to add an unused character at the beginning of each record, and then run a second loop to actually parse each record. I can't figure out why the script is not returning anything in the "for m in matches" block: ========= f = open("input.txt", "r") response = f.read() f.close() #Pass 1: Add some character to separate records #response.replace('
  • References: <58772.75.67.216.99.1228576211.squirrel@webmail.jots.org> Message-ID: Ken D'Ambrosio wrote: > Hi, all. I've done some poking around, and can find roughly two million > different ways to attach attachments to an e-mail... but darn few to > detach them. Any suggestions? I'm assuming I'm just missing looking in > The Right Place, but thus-far, my Googling has been for naught. Try the email package doc in the Lib Manual. From kyosohma at gmail.com Wed Dec 31 16:06:21 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 31 Dec 2008 13:06:21 -0800 (PST) Subject: Creating an application for Linux Message-ID: <7d2fe328-064c-46da-9150-7305b6f9e94e@b41g2000pra.googlegroups.com> Hi, My boss wants me to port one of my applications to Ubuntu. I successfully ported it without too many headaches but now I need a way to distribute it to people that may or may not already have the dependencies my application requires. I'm a newb with Linux so I'm not even sure what they call the distribution (rpms, deb, source code). After browsing the various "installer" docs out there, it looks like bbfreeze or PyInstaller might work, but I couldn't find any examples. Any advice is appreciated. Thanks! I am using Python 2.5.2 and this is a wxPython application with SqlAlchemy and a few other external packages. Mike From cjw at ncf.ca Sat Dec 6 08:18:07 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 06 Dec 2008 08:18:07 -0500 Subject: Multiple Versions of Python on Windows XP In-Reply-To: References: <4934de22$0$27863$9b622d9e@news.freenet.de> <4934E183.9020404@g.nevcal.com> <4934E3BF.7000403@v.loewis.de> Message-ID: <493A7B8F.8070806@ncf.ca> Glenn Linderman wrote: > On approximately 12/1/2008 11:29 PM, came the following characters from > the keyboard of Martin v. L?wis: >>> It would be nice if the ftypes were version specific as created by the >>> installer; IIRC, I created the above three from the ftype Python.File as >>> I installed each version. >>> >> >> That's a good idea; please submit a wish list item to bugs.python.org. >> There may be issues (such as people relying on this being Python.File), >> but I can't see any problems off-hand. >> >> Regards, >> Martin >> > > OK, Issue 4485 created. My first one, so let me know if I goofed. I > elaborated a bit from the original email, upon reflection. Seemed > useful, but also seemed complex by the time I got done. > > I don't really have a clue what the uninstaller should do with these; > nor have I fiddled to know if it presently removes Python.File. I > suppose it should delete them, if and only if the ftype and assoc have > the same content as was created by the corresponding version installation. > Here's another approach to handling multiple versions of Python, thanks to the PyScripter List. It does not address the need to access different versions of the Python Interpreter. Here is the full story. There are two types of Python installation a) For all users Python creates registry entries at HKEY_LOCAL_MACHINE\SOFTWARE\Python \PythonCore\2.x with installation info and puts the dll in c:\Windows \System32. b) For a single user Python creates registry entries at HKEY_CURRENT_USER\SOFTWARE\Python \PythonCore\2.x with installation info and does not put the dll in c: \Windows\System32. PyScripter without any command line flags looks at the registry to find the latest version of Python and then for an all user installation tries to load the relevant Python dll from the system path. For a single user installation tries to load the DLL from the Install path that is in the registry. When PyScripter is used with a --PYTHONxx flag then it does the above but searching only for the specific version. The Registry lookup does not take place when Python is used with the -- PYTHONDLLPATH. Instead PyScripter tries to load the Python dll from the specified path. The --PYTHONDLLPATH flag should be used with the --PYTHONxx flag. See http://pyscripter.googlepages.com/portablepython for an example of using PyScripter with portable Python. The %PYTHONHOME% variable is not used by PyScripter directly but by Python to find the installed libraries. See the Python documentation for its use. Colin W. From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 07:15:27 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Dec 2008 12:15:27 GMT Subject: Don't you just love writing this sort of thing :) References: <0148b086$0$20670$c3e8da3@news.astraweb.com> Message-ID: <0149131f$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 23:16:08 +1300, Lawrence D'Oliveiro wrote: > In message <0148b086$0$20670$c3e8da3 at news.astraweb.com>, Steven D'Aprano > wrote: > >> On Fri, 05 Dec 2008 13:27:35 +1300, Lawrence D'Oliveiro wrote: >> >>> In message , Cong >>> Ma wrote: >>> >>>> The "if ... != None" is not necessary... "if PatchDatePat.search(f)" >>>> is OK. >>> >>> I don't do that. >> >> Perhaps you should? > > I prefer using explicitly Boolean values for conditions. Perhaps you do, but there's no evidence of such in your post. bool(PatchDatePat.search(f) != None) would be an "explicitly Boolean value". What you posted was an *implicitly* Boolean value, and not even guaranteed to be Boolean, as __ne__ can return any object it likes. And yes, such a call to bool would be pointless. -- Steven From saluk64007 at gmail.com Sun Dec 21 03:57:46 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Sun, 21 Dec 2008 00:57:46 -0800 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: On Sat, Dec 20, 2008 at 10:15 PM, r wrote: > On Dec 20, 11:11 pm, walterbyrd wrote: >> On Dec 20, 5:05 pm, Roy Smith >> >> > He got really hung up on the % syntax. >> >> I guess it's good to know that there is, at least, one person in the >> world doesn't like the % formatting. As least the move was not >> entirely pointless. >> >> But, you must admit, of all the things people complain about with >> Python, the % formatting is probably one of the least common >> complaints. Complaints about Python's speed seem much more common. >> >> Yet, 3.0 makes the speed worse, and "fixes" a non-problem. A few points: 1) The new formatting is NOT the reason for the speed slowdown. So this change at least was a no cost change. No cost to interpreter speed, and no cost as it doesn't replace the old sprintf style. Of all the things to complain about in python 3.0, the format method is the silliest. 2) In my experience, major version changes tend to be slower than before. When a lot of things change, especially if very low-level things change, as happened in python 3.0, the new code has not yet went through many years of revision and optimization that the old code has. In my opinion, python 3 was rushed out the door a bit. It could have done with a few more months of optimization and polishing. However, on the other hand, it is going to take so long for python infrastructure to convert to python 3, that an earlier release makes sense, even if it hasn't been excessively polished. The biggest reason for the speed change is the rewritten stdio and unicode-everything. Hopefully this stuff can be improved in future updates. I don't think anyone WANTS cpython to be slower. From steve at REMOVE-THIS-cybersource.com.au Mon Dec 29 19:44:46 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Dec 2008 00:44:46 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <9c8c524f-6985-4cc8-b19c-666f85c69946@a26g2000prf.googlegroups.com> Message-ID: <01696606$0$6988$c3e8da3@news.astraweb.com> On Mon, 29 Dec 2008 09:50:14 -0800, walterbyrd wrote: > On Dec 21, 12:28?pm, Bruno Desthuilliers > wrote: > >> > I can see where the new formatting might be helpful in some cases. >> > But, I am not sure it's worth the cost. >> >> Err... _Which_ cost exactly ? > > Loss of backward compatibility, mainly. How do you lose backward compatibility by *adding* new functionality? The old functionality will continue to work as normal. -- Steven From google at mrabarnett.plus.com Tue Dec 9 14:00:02 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 09 Dec 2008 19:00:02 +0000 Subject: Best way to report progress at fixed intervals In-Reply-To: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> Message-ID: <493EC032.3040005@mrabarnett.plus.com> Slaunger wrote: > Hi comp.lang.python > > I am a novice Python 2.5 programmer, who write some cmd line scripts > for processing large amounts of data. > > I would like to have possibility to regularly print out the progress > made during the processing, say every 1 seconds, and i am wondering > what a proper generic way to do this is. > > I have created this test example to show the general problem. Running > the script gives me the output: > > Work through all 20 steps reporting progress every 1.0 secs... > Work step 0 > Work step 1 > Work step 2 > Work step 3 > Work step 4 > Processed 4 of 20 > Work step 5 > Work step 6 > Work step 7 > Work step 8 > Processed 8 of 20 > Work step 9 > Work step 10 > Work step 11 > Work step 12 > Work step 13 > Processed 13 of 20 > Work step 14 > Work step 15 > Work step 16 > Work step 17 > Processed 17 of 20 > Work step 18 > Work step 19 > Finished working through 20 steps > > The script that does this is as follows: > > testregularprogress.py: > > """ > Test module for testing generic ways of displaying progress > information > at regular intervals. > """ > import random > import threading > import time > > def work(i): > """ > Dummy process function, which takes a random time in the interval > 0.0-0.5 secs to execute > """ > print "Work step %d" % i > time.sleep(0.5 * random.random()) > > > def workAll(verbose=True, max_iter=20, progress_interval=1.0): > > class _Progress(object): > > def __init__(self): > self.no = 0 > self.max = max_iter > self.start_timer = verbose > > def __str__(self): > self.start_timer = True # I do not like this appraoch > return "Processed %d of %d" % (self.no, self.max) > > p = _Progress() > > def report_progress(): > print p > > if verbose: > print "Work through all %d steps reporting progress every > %3.1f secs..." % \ > (max_iter, progress_interval) > > for i in xrange(max_iter): > if p.start_timer : > p.start_timer = False # Let the progress instance set the > flag > timer = threading.Timer(progress_interval, > report_progress) > timer.start() > work(i) > p.no = i + 1 > > # Kill the last timer, which is still active at this time > timer.cancel() > > if verbose: > print "Finished working through %d steps" % max_iter > > if __name__ == "__main__": > workAll() > > Quite frankly, I do not like what I have made! It is a mess, > responsibilities are mixed, and it seems overly complicated. But I > can't figure out how to do this right. > > I would therefore like some feedback on this proposed generic "report > progress at regular intervals" approach presented here. What could I > do better? > I've come up with this: """ Test module for testing generic ways of displaying progress information at regular intervals. """ import random import threading import time def work(i): """ Dummy process function, which takes a random time in the interval 0.0-0.5 secs to execute """ print "Work step %d" % i time.sleep(0.5 * random.random()) def workAll(verbose=True, max_iter=20, progress_interval=1.0): class _Progress(threading.Thread): def __init__(self, progress_interval=1.0): threading.Thread.__init__(self) self.setDaemon(True) self.progress_interval = progress_interval self.progress = None self.active = True def stop(self): self.active = False def run(self): while self.active: if self.progress is not None: print self.progress time.sleep(self.progress_interval) if verbose: print "Work through all %d steps reporting progress every %3.1f secs..." % \ (max_iter, progress_interval) p = _Progress(progress_interval) p.start() for i in xrange(max_iter): p.progress = "Processed %d of %d" % (i + 1, max_iter) work(i) p.stop() if verbose: print "Finished working through %d steps" % max_iter if __name__ == "__main__": workAll() From Jiandong.Ge at gmail.com Thu Dec 11 09:55:04 2008 From: Jiandong.Ge at gmail.com (JD) Date: Thu, 11 Dec 2008 06:55:04 -0800 (PST) Subject: How to pass out the result from iterated function References: <74ea407e-7cf0-4619-99e5-d08b9161e9d0@f40g2000pri.googlegroups.com> Message-ID: <6f3f4f5c-d043-42ef-9ba3-075036d79c6d@r37g2000prr.googlegroups.com> On Dec 10, 2:25 pm, eric wrote: > On Dec 10, 9:16 pm, JD wrote: > > > > > I got a iterated function like this: > > > def iterSomething(list): > > has_something = False > > for cell in list: > > if something in cell: > > has_something = True > > output = something > > if has_something: > > iterSomething(output) > > else: > > final_out = outupt > > > The problem is how can I read this final_out outside of the function. > > I tried the global statement, it seems not work. Any idea? > > > JD Thanks, I tried to return the last result. It's not working. Your code works, thanks > why don't you just return it ? > > def iterSomething(list): > has_something = False > for cell in list: > if something in cell: > has_something = True > output = something > if has_something: > return iterSomething(output) > else: > return output > > ? From rt8396 at gmail.com Sat Dec 20 19:20:38 2008 From: rt8396 at gmail.com (r) Date: Sat, 20 Dec 2008 16:20:38 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> On Dec 20, 6:05?pm, Roy Smith wrote: > In article > , > > ?walterbyrd wrote: > > On Dec 19, 10:25?am, Michael Torrie wrote: > > > > Personally the new string formatter is sorely needed in Python. ? > > > Really? You know, it's funny, but when I read problems that people > > have with python, I don't remember seeing that. Loads of people > > complain about the white space issue. Some people complain ?about the > > speed. Lots of complaints about certain quirky behavior, but I have > > not come across any complaints about the string formatting. > > > In fact, from what I have seen, many of the "problems" being "fixed" > > seem to be non-problems. > > > I dunno, maybe it's just me. > > I had an interesting experience with this recently. ?I was giving a > co-worker quick python into. ?He's an experienced programer in various > languages, but this was his first exposure to python. > > He got really hung up on the % syntax. ?By (bad) luck, he was trying to > print a tuple (let's call it "t"), did > > format % t > > and was surprised at the result. ?It set him off on a "but that's stupid, > blah, blah, blah" rant. ?I haven't absorbed the new syntax well enough to > figure out if people will get hung up by this with the new syntax. It is stupid, more reason to fix the current problem instead creating a whole new one. One more big complaint "THE BACKSLASH PLAGUE". ever tried regexp?, or file paths?. All because that little backslash char is a line continuation character, maybe we should fix that. Would your life end if '\' was not a continuation char? Mine would not because i don't write my code to need it. Python has real warts that need fixing, and thats really hard for me to say, because i am such a fanboy of Python. From sampsa.riikonen at iki.fi Mon Dec 8 15:56:10 2008 From: sampsa.riikonen at iki.fi (Sampsa Riikonen) Date: Mon, 08 Dec 2008 22:56:10 +0200 Subject: xml.dom.minidom bug ? Message-ID: Dear All, I am experiencing a weird problem with the xml.dom.minidom module: ---------------------------------------- sampsa at linux-ty84:~/python> python easyxml.py Traceback (most recent call last): File "easyxml.py", line 1, in import xml.dom.minidom File "/usr/lib64/python2.5/site-packages/_xmlplus/dom/__init__.py", line 236, in import MessageSource File "/usr/lib64/python2.5/site-packages/_xmlplus/dom/MessageSource.py", line 21, in _ = get_translator("dom") File "/usr/lib64/python2.5/site-packages/_xmlplus/FtCore.py", line 54, in get_translator f = gettext.translation('4Suite', locale_dir).gettext File "/usr/lib64/python2.5/gettext.py", line 478, in translation t = _translations.setdefault(key, class_(open(mofile, 'rb'))) File "/usr/lib64/python2.5/gettext.py", line 180, in __init__ self._parse(fp) File "/usr/lib64/python2.5/gettext.py", line 264, in _parse unpack = struct.unpack AttributeError: 'module' object has no attribute 'unpack' ------------------- A bug in the module? And the weirdest thing is that I figured out how to get around this problem long time ago, but now I don't have a clue anymore... :/ Any help appreciated. Cheers, Sampsa From eric at ericaro.net Wed Dec 10 15:25:27 2008 From: eric at ericaro.net (eric) Date: Wed, 10 Dec 2008 12:25:27 -0800 (PST) Subject: How to pass out the result from iterated function References: Message-ID: <74ea407e-7cf0-4619-99e5-d08b9161e9d0@f40g2000pri.googlegroups.com> On Dec 10, 9:16?pm, JD wrote: > I got a iterated function like this: > > def iterSomething(list): > ? ? has_something = False > ? ? for cell in list: > ? ? ? ? if something in cell: > ? ? ? ? ? ? has_something = True > ? ? ? ? ? ? output = something > ? ?if has_something: > ? ? ? ?iterSomething(output) > ? ?else: > ? ? ? ?final_out = outupt > > The problem is how can I read this final_out outside of the function. > I tried the global statement, it seems not work. Any idea? > > JD why don't you just return it ? def iterSomething(list): has_something = False for cell in list: if something in cell: has_something = True output = something if has_something: return iterSomething(output) else: return output ? From conrad.ammon at gmail.com Mon Dec 15 15:45:41 2008 From: conrad.ammon at gmail.com (cmdrrickhunter@yaho.com) Date: Mon, 15 Dec 2008 12:45:41 -0800 (PST) Subject: Managing timing in Python calls References: Message-ID: I believe WxTimerEvent is handled using the event queue, which isn't going to do what you want. An event which goes through the queue does not get processed until you return to the queue. What you want to do is actually a rather difficult task to do generically. Should the task be interrupted immediately? Or is a tiny latency acceptable? Should the function being terminated get to handle its own termination? Or should the termination be forced on it. What sort of overhead is acceptable for this "set_timeout" behavior? I would not be surprised if there isn't a built in solution, because its so hard, but rather built in tools which can be used to do it. If your timeouts are on the order of seconds, you might be able to just check time.time() at the begining, and compare it to the current time later in the function. This could be on the main thread or on a worker thread. If you need better handling, you may want to look at how condition variables and such work. Finally, thread has a function to send a Keyboard Interrupt to the main thread. I believe you could do your work on the main thread, and catch the interrupt. "Background" tasks are not easy to implement in any language (other than perhaps AJAX ;-) ). Remember, Python does not support truly simultaneous threads. It actually does timeslices of about 100 operations. Any solution you choose should work given this information. And as for a "nicer" construct, I personally just learned of how to handle the "with" command. I could see something like class Timeout: def __init__(self, t): self.t = t def __enter__(self): self.start = time.time() def __exit__(self, x, y, z): return None def __nonzero__(self): return time.time() - self.start <= self.t def doSomethingLong(timeout = True): # true guarentees bailout never occurs while timeout: doAnIteration() with Timeout(3) as t: doSomethingLong(t) and have your Timeout class have a flag which it sets when doSomethingLong needs to bail out, using whatever method is "best" for your particular application. This is, of course pseudocode - I've not run it through python msyself. Hopefully any errors are obvious enough that you can work around them. From Russ.Paielli at gmail.com Sun Dec 7 15:13:37 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 7 Dec 2008 12:13:37 -0800 (PST) Subject: Python for kids? Message-ID: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> I have a 12-year-old son who spends too much time playing Xbox live and watching silly YouTube videos. I would like to try to get him interested in programming. Is anyone aware of a good book or website that addresses this concern, preferably (but not necessarily) using Python? I could try to teach him Python myself, but I'm afraid I would just frustrate him and kill his interest in programming. I did a Google search and found a few things, but not a lot. Thanks. From tjreedy at udel.edu Sat Dec 6 16:47:15 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 06 Dec 2008 16:47:15 -0500 Subject: "as" keyword woes In-Reply-To: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> Message-ID: Warren DeLano wrote: > As someone somewhat knowledgable of how parsers work, I do not > understand why a method/attribute name "object_name.as(...)" must > necessarily conflict with a standalone keyword " as ". It seems to me > that it should be possible to unambiguously separate the two without > ambiguity or undue complication of the parser. The lexer, which preceeds the parser, has separate KEYWORD and IDENTIFIER categories. For example, 'if a ...' is lexed as (KEYWORD, 'if'), (IDENTIFIER, 'a'), ... . Leaving 'as' as an identifier identified by the parser as a contextual keyword in import statements was a kludge. When 'as' was reused in "with as " in 2.5 (with __future__ import), it was planned and announced that *both* 'with' and 'as' would become full-time keywords in 2.6, just as 'yield' did in 2.3 after its introduction (with required __future__) in 2.2. Making 'yield' a keyword of course impacted people who used the word in financial calculations, but they adjusted. > So, assuming I now wish to propose a corrective PEP Working with people trying to improve threading would be more productive. Terry Jan Reedy From jstroud at mbi.ucla.edu Sun Dec 14 18:24:05 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 14 Dec 2008 15:24:05 -0800 Subject: Need help improving number guessing game In-Reply-To: <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> Message-ID: It looks much better. But as Bruno suggests and as I alluded to earlier, you should get in the habit of forming verification loops on input channels that aren't already guaranteed to provide valid input messages. I'm not sure how to say that in English, but in python my example was: while True: try: guess1 = int(input("\n>> ")) except ValueError: print 'Bad value.' else: break Other than that, you still have some points where you can break lines down to improve clarity. Think of it like trying to avoid run-on sentences. Over all, it looks like you have picked up some good technique that you could only get by experimentation over the course of about 5 or 6 months. James From deets at nospam.web.de Mon Dec 8 12:50:05 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 Dec 2008 18:50:05 +0100 Subject: Equivalent of 'wget' for python? References: Message-ID: <6q552dFat95dU1@mid.uni-berlin.de> Jean-Paul Calderone wrote: > On Mon, 08 Dec 2008 17:29:35 +0100, "Diez B. Roggisch" > wrote: >>Robert Dailey wrote: >> >>> Hi, >>> >>> I'm looking for a portable way to download ZIP files on the internet >>> through Python. I don't want to do os.system() to invoke 'wget', since >>> this isn't portable on Windows. I'm hoping the core python library has >>> a library for this. Note that I'll be using Python 3.0. >> >>Module urllib2 >> > > There isn't such a module in Python 3.0. If you knew that urllib2 has been removed/integrated/whatever into urllib, it would have helped to mention that, don't you think? To the OP: urllib.request.urlopen is your friend. Diez From p at ulmcnett.com Mon Dec 22 15:04:11 2008 From: p at ulmcnett.com (Paul McNett) Date: Mon, 22 Dec 2008 12:04:11 -0800 Subject: Check file is In-Reply-To: References: <7caa7d45-ebbe-4c88-bb50-2f01f7315d07@s9g2000prg.googlegroups.com> <494cbef5$0$90267$14726298@news.sunsite.dk> Message-ID: <494FF2BB.2050402@ulmcnett.com> Colin J. Williams wrote: > The ReportLab toolkit appears to be concerned with building Portable > Document Files. I would be interested in any utility which will read > any pdf - for example, to convert pdf -> html I don't know of any Python utility to do this, but pdftohtml, pdftotext, pdftoppm, and pdftops exist on my Ubuntu Linux system. Paul From rt8396 at gmail.com Wed Dec 31 03:02:28 2008 From: rt8396 at gmail.com (r) Date: Wed, 31 Dec 2008 00:02:28 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <9c8c524f-6985-4cc8-b19c-666f85c69946@a26g2000prf.googlegroups.com> <01696606$0$6988$c3e8da3@news.astraweb.com> <78bd573f-03b0-4628-909d-3f84f9718e7e@13g2000yql.googlegroups.com> Message-ID: <4f95bf3c-69cb-4b8f-b2c5-cce5f5f38b49@v42g2000yqv.googlegroups.com> You know, it is so much easier to find my posts now that someone has been thoughtful enough to mark them for me. Thank you kind chaps, i shall leave a shiny new nickel for you, just send me your name, address, and phone numbers. I'll get them in the mail right away. From joe at strout.net Tue Dec 9 10:36:50 2008 From: joe at strout.net (Joe Strout) Date: Tue, 9 Dec 2008 08:36:50 -0700 Subject: How to initialize a class variable once In-Reply-To: <493E5700.4030107@aim.com> References: <493E5700.4030107@aim.com> Message-ID: <293D8F1A-066B-43FD-B3D2-82368955AB11@strout.net> On Dec 9, 2008, at 4:31 AM, Brian Allen Vanderburg II wrote: > There is one situation where a module can be imported/executed > twice, if it is the __main__ module. That's an excellent point -- this is something I've run into, and it always feels a bit awkward to code around it. What's the standard idiom for avoiding this issue in a complex app? Have a "main" file that is not imported by anything else, and which does little but launch stuff from some other module? As I say it, that seems obvious, but somehow I keep getting urges to put global stuff (like my Application subclass) in the main file, and then I find I need to reference it from some other module, and get into trouble. This is probably just bias from my last programming environment, though. I can adapt. Anyway, thanks for pointing this out; I bet it's the root cause of the OP's observation. Best, - Joe From steve at holdenweb.com Tue Dec 30 08:02:11 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Dec 2008 08:02:11 -0500 Subject: string in files In-Reply-To: <62075511-08ad-405a-a3af-2da8d2f22c50@v39g2000pro.googlegroups.com> References: <62075511-08ad-405a-a3af-2da8d2f22c50@v39g2000pro.googlegroups.com> Message-ID: ibpet11 at gmail.com wrote: > On Dec 30, 11:17 am, "Narasimhan Raghu-RBQG84" > wrote: >> Simple solution: us result=yourString.split(" ") and you get a list with >> all the words. >> >> -----Original Message----- >> From: python-list-bounces+rbqg84=motorola.... at python.org >> >> [mailto:python-list-bounces+rbqg84=motorola.... at python.org] On Behalf Of >> ibpe... at gmail.com >> Sent: Tuesday, December 30, 2008 3:43 PM >> To: python-l... at python.org >> Subject: string in files >> >> guys i need info on how to call up different words in a line of a file >> using python example : file = 'this is a python coding group' >> >> i want to assign a xter to this, is, a, python , coding and group >> [...] > thanks brother > i mean how do i particularly assign (u = this) > (y = is).... > in the strings up there. i have been able to split strings with any > character sign. > Well, if you *know* you have a particular number of words in the string you can say u, v, w, x, y, z = 'this is a python coding group'.split() But if you have a variable number of words this isn't practical in Python 2, though Python 3 has features that make it easier. The real question is "what is the larger goal you are trying to achieve". Where a programmer is trying to create names dynamically there are usually better ways to proceed. Could you tell us a little more about what you are trying to do? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From patrickstinson.lists at gmail.com Mon Dec 1 00:47:45 2008 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Sun, 30 Nov 2008 20:47:45 -0900 Subject: incorrect line reported in traceback Message-ID: <6214d7a20811302147r4e17a7a5g38796573d5804d@mail.gmail.com> Is there any reason why the last item in the traceback is one frame below the top of the stack? It would be great to show the real line in my editor... From mtestinori at no_mail.com Mon Dec 1 19:17:12 2008 From: mtestinori at no_mail.com (Mario Testinori) Date: Tue, 02 Dec 2008 01:17:12 +0100 Subject: Emacs vs. Eclipse vs. Vim References: <27757214-df90-4a33-8f44-65673c9ababd@20g2000yqt.googlegroups.com> Message-ID: On Mon, 1 Dec 2008 15:57:17 -0800 (PST), "sjdevnull at yahoo.com" wrote: >On Nov 29, 3:44?pm, Josh wrote: >> If you were a beginning programmer and willing to make an investment in >> steep learning curve for best returns down the road, which would you pick? >> >> I know this topic has been smashed around a bit already, but 'learning >> curve' always seems to be an arguement. If you feel that one is easier >> or harder than the others to learn feel free to tell, but let's not make >> that the deciding factor. Which one will be most empowering down the >> road as a development tool? > >I'd strongly recommend not using an IDE but going with federated >tools; this makes it easier to pick the editor, code navigation tool, >build system, etc that you like best, and makes it easier to swap out >one piece at a time if you don't like it. So of the choices >mentioned, I'd go with emacs or vim if I were you. I'd say this has another advantage, that someone already mentioned - better learning the process that goes behind the gui of an ide. After all, an ide is just a frontend to something ... > >Personally I also find high value in picking an editor that can be run >on a command-line terminal connection (e.g. when you're ssh'd into a >remote server), but that may be less important depending on what sort >of development you are doing. True, the value of this could vary from critical to not important at all. -- Mario From grante at visi.com Fri Dec 19 17:30:43 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 19 Dec 2008 16:30:43 -0600 Subject: IMAP: How to implement GMail-like threaded conversations view References: Message-ID: On 2008-12-19, Jean-Paul Calderone wrote: > On Fri, 19 Dec 2008 08:47:18 -0800 (PST), Martin wrote: >>Currently I am trying to get used to Python's imaplib and email >>modules. >>I'like to create a webmail client simmilar to GMail. > > I'd suggest using Twisted's IMAP4 client. It's somewhat easier to > use than Python's imaplib because it does much more parsing of IMAP4's > complex syntax for you. It will also be easier to do IMAP4 and HTTP > simultaneously if you're using Twisted. Anything that helps with with the IMAP responses is worth looking at, because parsing IMAP response messages is brutal. I'm not sure what the IMAP protocol authors thought was going to be parsing the replies, but it sure couldn't have been a real-world computer program. IMO, the IMAP protocol has achieved a level of suckage that would make Microsoft proud. But, it works. Eventually. -- Grant From lists at cheimes.de Tue Dec 16 13:47:23 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 16 Dec 2008 19:47:23 +0100 Subject: sys.maxint in Python 2.6.1 (amd64) on Windows XP x64 In-Reply-To: <4bddf65a-bb9f-406c-a544-8c38b27547a7@b38g2000prf.googlegroups.com> References: <4bddf65a-bb9f-406c-a544-8c38b27547a7@b38g2000prf.googlegroups.com> Message-ID: Lin schrieb: > Hi, > > I installed the amd64 version of Python 2.6.1 on my Windows XP x64 > system. I was expecting sys.maxint to be 9223372036854775807 (or 2 ^63 > -1), but instead I got 2147483647 (i.e., 2^31-1) just like what I got > from a 32-bit version of Python. Is this by design or does it indicate > a bug or an installation problem? Thank you very much! This is by design. In their infinitive wisdom Microsoft has decided to make the 'long' C type always a 32 bit signed integer - even on 64bit systems. On most Unix systems a long is at least 32 bit but usually sizeof(ptr). Christian From mirandasnailvv at gmail.com Fri Dec 19 19:42:21 2008 From: mirandasnailvv at gmail.com (mirandasnailvv at gmail.com) Date: Fri, 19 Dec 2008 16:42:21 -0800 (PST) Subject: sydney female slut gloryhole - Free Message-ID: <179d616f-d7d6-41bd-897c-ac7216ea5879@v39g2000pro.googlegroups.com> sydney female slut gloryhole . . . *******CLICK HERE******** http://club247.cn/sydney-female-slut-gloryhole ***************************** . . . . . . . . . . . . sydney female slut gloryhole From jeremiah.dodds at gmail.com Wed Dec 3 06:45:05 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Wed, 3 Dec 2008 06:45:05 -0500 Subject: Multiple equates In-Reply-To: References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> <9m3h06-vhh.ln1@lairds.us> Message-ID: <12cbbbfc0812030345m5afa83d3m518e108d11d3e0fb@mail.gmail.com> On Wed, Dec 3, 2008 at 6:23 AM, Lawrence D'Oliveiro wrote: > > So why is that better? > -- > http://mail.python.org/mailman/listinfo/python-list > I personally think that it looks marginally cleaner (indentation issues aside). Do you think it's substantially worse? If so, why? I mean you asked how you would express the original code with the lambda - that's how you would, by pulling the lambda out into a function. How would you express it better is a different question. I think that the code in question is an example of a case where a lambda is appropriate in python, but it's definitely not any worse for having the code pulled out. If the function wasn't trival, you'd have to anyhow. The whole "lambdas good or bad" thing has been done to death as far as it relates to python. For python, it seems that anonymous functions are a no-no unless they're effectively one liners. -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Fri Dec 19 15:44:40 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 19 Dec 2008 21:44:40 +0100 Subject: [ANN] Python 2.4.6 and 2.5.3 (final) Message-ID: <494C07B8.6000001@v.loewis.de> On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.4.6 and 2.5.3 (final). 2.5.3 is the last bug fix release of Python 2.5. Future 2.5.x releases will only include security fixes. According to the release notes, about 80 bugs and patches have been addressed since Python 2.5.2, many of them improving the stability of the interpreter, and improving its portability. Since the release candidate, the only change was an update to the Macintosh packaging procedure. 2.4.6 includes only a small number of security fixes. Python 2.6 is the latest version of Python, we're making this release for people who are still running Python 2.4. See the release notes at the website (also available as Misc/NEWS in the source distribution) for details of bugs fixed; most of them prevent interpreter crashes (and now cause proper Python exceptions in cases where the interpreter may have crashed before). For more information on Python 2.4.6 and 2.5.3, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.4.6 http://www.python.org/2.5.3 Highlights of the previous major Python releases are available from the Python 2.5 page, at http://www.python.org/2.4/highlights.html http://www.python.org/2.5/highlights.html Enjoy this release, Martin Martin v. Loewis martin at v.loewis.de Python Release Manager (on behalf of the entire python-dev team) From ylj798 at gmail.com Tue Dec 2 11:48:16 2008 From: ylj798 at gmail.com (ylj798 at gmail.com) Date: Tue, 2 Dec 2008 08:48:16 -0800 (PST) Subject: help me~!about base64 Message-ID: <0ff1ba7b-8a17-4647-99fc-9c8e32f83de7@g1g2000pra.googlegroups.com> my code? ????????????????????????????????????? import base64 def deflashget(st): if st.startswith('Flashget://'): return base64.decodestring(st[len('Flashget://'):])[10:-10] elif st.startswith('http://') or st.startswith('ftp://'): return 'Flashget://' + base64.encodestring('[FLASHGET]' + st +'[FLASHGET]').replace('\n', '') st='Flashget:// W0ZMQVNIR0VUXWh0dHA6Ly9kb3duLnJub3ZlbC5jb20vYm9va3R4dC8zLzEzNjgyLzEzNjgyLnppcFtGTEFTSEdFVF0=&1064' print deflashget(st) ???????????????????????????????????????? it's run ,Eric gave me error,the error is "'module' object has no attribute 'decodestring'", what can I do? who can help me? From alexoplocatie at gmail.com Wed Dec 17 09:28:01 2008 From: alexoplocatie at gmail.com (aka) Date: Wed, 17 Dec 2008 06:28:01 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> <0d9ea7cc-b5fb-4edb-be32-490aae9e7204@b41g2000pra.googlegroups.com> Message-ID: <0de3a7bf-a4c4-4103-a4e0-44313405fa94@z28g2000prd.googlegroups.com> Hi John, thanks. You're right, I didn't past the method header because I thought it didn't matter when the input filename is hardcoded. The try/except isn't very helpful indeed so I commented it out. You're right I wrongly referred to the UnicodeReader class in my first post because that's ultimately where I want to go so I outcommented it here for you to see. The fact is that neither csv.reader nor the UnicodeReader will read the file, while writing with the UnicodeWriter works like a charm. That's why I put str() around roles to see any content. I simplified the csv-file by cutting off columns without result. The file looks now like: id;company;department 12;Cadillac;Research 11;Ford;Accounting 10;Chrysler;Sales The dictionary on the return is because this code is part of my TurboGears application. The entire method is: import csv from utilities.urw import UnicodeWriter, UnicodeReader @expose(allow_json=True) def import_roles(self, input=None, *args, **kwargs): inp = 'C:/temp/test.csv' roles = [] msg = '' ## try: fp = open(inp, 'rb') reader = csv.reader(fp, dialect='excel', delimiter=';') ## reader = UnicodeReader(fp, dialect='excel', delimiter=';') for r in reader: roles.append(r[0]) fp.close() ## except: ## msg = "Something's wrong with the csv.reader" return dict(filepath=inp, roles=str(roles), msg=msg) csv.reader results in: for r in reader: Error: line contains NULL byte Use of UnicodeReader results in: UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: unexpected code byte Will post only complete code from now on thanks. From jcd at sdf.lonestar.org Mon Dec 8 15:07:22 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 08 Dec 2008 15:07:22 -0500 Subject: "as" keyword woes In-Reply-To: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> Message-ID: <1228766842.5709.28.camel@aalcdl07.lib.unc.edu> On Wed, 2008-12-03 at 21:42 -0800, Warren DeLano wrote: > Anyway, it seems obvious that the right decision for our customers (or > more importantly, for their countless lines of autogenerated-Python > log, > state, and code files from the past decade) is to stick with C/Python > 2.5.x for the time being and plan to make the jump to a > threads-capable > and hopefully backwards-compatible Python implementation as soon as > possible (IronPython perhaps?). That seems like a sensible path > around > the breakage and enduring limitations of C/Python 2.6 or 3. All that broken code does sound like a hassle. However, I think the workaround would be a fairly simple refactor: 1) make 'as_type' (or some other equivalent name like 'as_') a synonym for 'as': >>> class Foo(object): ... def as(self): ... pass ... as_type = as 2) Change all references in Foo in your code base to use 'as_type'. 3) Extract class Foo to a separate file (_as_import_file.py), and replace it in the original file with: >>> from _as_import_file import Foo (Note that no other files should import directly from _as_import_file.py) 4) Now write a second file (_as_import_file_2_6.py), which defines defines Foo without as, just using as_type: >>> class Foo(object): ... def as_type(self): ... pass 5) Change your import to select the appropriate import: >>> try: ... from _as_import_file import Foo ... except SyntaxError: ... from _as_import_file_2_6 import Foo 6) Now your code base is fully functional with both 2.5 and 2.6. Everything functions exactly the same as it did before on 2.5, except now Foo.as_type() (or Foo.as_()) works as a synonym for Foo.as(). Tell your customers that they can upgrade to 2.6 if they update their own uses of as_type. In the meantime, their code is still functional on 2.5. By extracting Foo to _as_import_file, you only have to maintain one class in parallel. Better yet, have _as_import_file.Foo subclass _as_import_file_2_6.Foo, like so: _as_import_file_2_6.py >>> class Foo(object): ... def as_type(self,type): ... pass _as_import_file.py >>> import _as_import_file_2_6 >>> class Foo(_as_import_file.Foo): ... as = _as_import_file.Foo.as_type That three line file, along with the four line conditional import are all you need for each import, and best of all, it's completely hidden from your users, until they want to migrate to python 2.6, and then all they have to do is change all references to Foo.as to point to Foo.as_type. But by observing step 1 above, they can do that at leisure, without fearing to break their code. I hope that's a helpful workaround for you and your users. Cheers, Cliff From bruno.42.desthuilliers at websiteburo.invalid Wed Dec 3 12:08:09 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 03 Dec 2008 18:08:09 +0100 Subject: python an sqlite objects In-Reply-To: References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> Message-ID: <4936bceb$0$16783$426a34cc@news.free.fr> skip at pobox.com a ?crit : > azrael> is it possible to save a python object into a sqlite database as > azrael> an atribute of type BLOB > > Sure. Just pickle the object and save the resulting string. > Or if you want something more portable, serialize the object to json. At least you'll have a chance to deserialize it with some other language. Now note that using a RDBMS that way kind of defeats the whole point of using a RDBMS. I don't mean that it's _always_ a bad idea - there are a couple use case where it's probably the "less worse" thing to do -, but that one should think twice before doing so. From tjreedy at udel.edu Sun Dec 7 17:11:27 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 07 Dec 2008 17:11:27 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Robert Kern wrote: > Terry Reedy wrote: >> Rasmus Fogh wrote: >>> Personally I would like to get these !@#$%&* misfeatures removed, >> >> What you are calling a misfeature is an absence, not a presence that >> can be removed. > > That's not quite true. In what way, pray tell. My statement still looks quite true to me. > Rich comparisons explicitly allow non-boolean return values. They do so by not doing anything to the return value of the underlying method. As I said, the OP is complaining about an absence of a check. Moreover, the absence is intentional as I explained in the part snipped and as you further explained. >> And if the return value was bad, all operator.eq could do is raise and >> exception anyway. > > Sure, but then it would be a bug to return a non-boolean from __eq__ and > friends. It is not a bug today. I think that's what Rasmus is proposing. Right, the addition of a check that is absent today. tjr From prologic at shortcircuit.net.au Sun Dec 21 17:23:12 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Dec 2008 08:23:12 +1000 Subject: Python is slow In-Reply-To: <3392a51b-d3fd-4986-9c59-fecccc7272da@p2g2000prn.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> <6r6hpfFfb643U3@mid.uni-berlin.de> <494E6FDA.4070401@mrabarnett.plus.com> <4585c27d-d7a9-480f-991c-a869161be55c@g38g2000yqn.googlegroups.com> <3392a51b-d3fd-4986-9c59-fecccc7272da@p2g2000prn.googlegroups.com> Message-ID: On Mon, Dec 22, 2008 at 4:47 AM, r wrote: > Could not have said it better myself Luis, i stay as far away from C > as i can. But there are usage cases for it. If you can think of 1 typical common case I'll reward you with praise! :) By the way, by common and typical I mean use-cases that you'd typically find in every day applications and user tools, software, games, etc. In case anyone is not aware, Python is also used for heavy scientific computational problems, games such as Civilisation and others, and I believe (correct me if I"m wrong) it's also used by NASA. --JamesMills From tjreedy at udel.edu Mon Dec 1 15:18:55 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Dec 2008 15:18:55 -0500 Subject: What about a decorator module version 3.0? In-Reply-To: <7504ac87-4e4e-447f-a02c-f9db3f932a57@s20g2000yqh.googlegroups.com> References: <7504ac87-4e4e-447f-a02c-f9db3f932a57@s20g2000yqh.googlegroups.com> Message-ID: Michele Simionato wrote: > > What do you people think? I am not a user yet, but my opinion anyway... Release a final 2.x version with whatever internal changes but with external api unchanged or at least backward compatible. Mark items to be deleted as deprecated. Keep that available indefinately. Then release a 3.0 version with Py3.0 support and deprecated items deleted. From goldnery at gmail.com Fri Dec 26 02:44:21 2008 From: goldnery at gmail.com (Gandalf) Date: Thu, 25 Dec 2008 23:44:21 -0800 (PST) Subject: python interpreter black window References: Message-ID: <4af41198-ea6b-4c67-86a0-1ce6b2669a95@a29g2000pra.googlegroups.com> On Dec 26, 2:52?am, Scott David Daniels wrote: > Chris Rebert wrote: > > On Thu, Dec 25, 2008 at 3:32 PM, Gandalf wrote: > >> I use WX gui so the user doesn't actually need it, Is their any way to > >> hide it? > > > Make sure your Python program is run by pythonw.exe as opposed to python.exe > > pythonw.exe exists specifically for the purpose of suppressing the DOS > > Box on Windows. > > Absolutely right. ?Vy the way, naming your "main" program file > something.pyw, rather than something.py is one of the ways ro do this. > > --Scott David Daniels > Scott.Dani... at Acm.Org thanks! From cournape at gmail.com Mon Dec 15 01:05:01 2008 From: cournape at gmail.com (David Cournapeau) Date: Mon, 15 Dec 2008 15:05:01 +0900 Subject: stable algorithm with complexity O(n) In-Reply-To: References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> Message-ID: <5b8d13220812142205n301aa972xf795dd2a16ab8a03@mail.gmail.com> On Mon, Dec 15, 2008 at 2:12 PM, Aaron Brady wrote: > > I agree. Most of his examples were tautologies. The magnet one was > the exception. A proof is nothing more than a tautology :) The fact that pi is not rational is not trivial (but certainly has been proved for some time now). cheers, David From shao.tu at gmail.com Mon Dec 15 06:30:38 2008 From: shao.tu at gmail.com (stalex) Date: Mon, 15 Dec 2008 03:30:38 -0800 (PST) Subject: Py_GetPath() C API in python 3 References: <772bb62b-1ef1-4ffa-90f6-c1cbdc728fdd@q30g2000prq.googlegroups.com> Message-ID: On 12??13??, ????9?r55??, "Gabriel Genellina" wrote: > En Fri, 12 Dec 2008 04:50:06 -0200, stalex escribi??: > > >> I want to build a new, requires total control, python interpreter. So > >> I implement my own version of Py_GetPath(), Py_GetPrefix(), > >> Py_GetExecPrefix() and Py_GetProgramFullPath(). When compiling, I > >> always get error messages, for each API function, look like > >> followings: > > >> /opt/python-3.0/lib/python3.0/config/libpython3.0.a(getpath.o)(.text > >> +0x211c): In function `Py_GetPath': > >> ./Modules/getpath.c:739: multiple definition of `Py_GetPath' > >> myApp.o(.text+0x0):/home/alex/workspace/develop/src/myApp.c:11: first > >> defined here > >> /usr/bin/ld: Warning: size of symbol `Py_GetPath' changed from 126 in > >> system.o to 32 in /opt/python-3.0/lib/python3.0/config/libpython3.0.a > >> (getpath.o) > >> collect2: ld returned 1 exit status > > Looks like you added your own implementation of those functions > (/home/alex/...myApp.c) but forgot to remove the original one > (Modules/getpath.c) > > -- > Gabriel Genellina No, I didn't remvoe the original one. But, why do I need to do that? I just want to extend my application, based on the original python installed by administrator, not to build/install another one python interpreter. And by studing python api documentations, Py_GetPath() is a public interface python itself provides. So I could achieve my goal via implementating my own Py_GetPath() version as well as other Py_GetXXX(). By the way, my application is stable and runs well since 2 years ago. I do this just because I want to release, in the near future, a new version. And I want to migrate its kernel from python2.5 to python3. Any ideas? From metolone+gmane at gmail.com Fri Dec 5 08:56:34 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Fri, 5 Dec 2008 05:56:34 -0800 Subject: generating a liste of characters References: Message-ID: wrote in message news:df7b75eb-97bf-4538-880b-f65b5ed992ff at u14g2000yqg.googlegroups.com... >Mark Tolonen: >> Writing a helper function reduces code repetition and improves >> readability: >> def crange(startch,endch): >> '''Return a list of characters from startch to endch, inclusive.''' >> return [chr(c) for c in xrange(ord(startch),ord(endch)+1)] > >In Python ranges are open on the right, so I name cinterval such >function. Yes, and that's fine when dealing with integers and slicing, but when dealing with characters, it is non-obvious what character to use. What "looks" correct? chars = crange('0','9') + crange('A','Z') + crange('a','z') # inclusive or chars = crange('0',':') + crange('A','[') + crange('a','{') # open right or if you didn't know the character after the one you actually wanted: chars = crange('0',chr(ord('9')+1)) + crange('A',chr(ord('Z')+1)) + crange('a',chr(ord('z')+1)) # open right, but messy -Mark From robert.kern at gmail.com Sat Dec 27 21:39:47 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 27 Dec 2008 21:39:47 -0500 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: Daniel Fetchinson wrote: >>> I agree that array.array is more efficient than a list but the input >>> for my function will come from PIL and PIL returns a list. So I have a >>> list to begin with which will be passed to the C function. >> With recent versions of PIL, numpy can create an array from an Image very >> quickly, possibly without any copying of memory. > > What exactly do you mean? (1) PIL creates a list which can be easily > converted by numpy to a numpy.array or (2) with the help of numpy one > can create a numpy.array from an image directly? (2) a = numpy.asarray(img) > Since I will have to pass the list or numy.array to C anyway I don't > see any advantage to (1) although (2) can be useful. (1) is still somewhat useful, if you're willing to bear the cost of the numpy dependency. The conversion code from any Python sequence to a numpy array of the desired type and dimensionality is a 2-liner (function call and error check). The memory is managed by numpy, so all you have to do is manage the refcount of the array object like any other Python object. Okay, 5-liner given C's verbosity: intx = PyArray_FROM_OTF(pyintx, PyArray_INT, NPY_IN_ARRAY); if (!intx) { PyErr_SetString(PyExc_ValueError, "intx must be an array of ints"); goto fail; } -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From Ron.Barak at lsi.com Wed Dec 24 11:09:02 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Wed, 24 Dec 2008 16:09:02 +0000 Subject: How to change a generator ? In-Reply-To: References: Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6024946E6@enbmail01.lsi.com> Hi, I have a generator whose aim is to returns consecutive lines from a file (the listing below is a simplified version). However, as it is written now, the generator method changes the text file pointer to end of file after first invocation. Namely, the file pointer changes from 0 to 6623 on line 24. Can you suggest how the generator could be changed, so it will allow me to get the current location in the file after each yield ? Thanks, Ron. $ cat -n generator.py # listing without line numbers is below 1 #!/usr/bin/env python 2 3 import gzip 4 from Debug import _line as line 5 6 class LogStream(): 7 8 def __init__(self, filename): 9 self.filename = filename 10 self.input_file = self.open_file(filename) 11 12 def open_file(self, in_file): 13 try: 14 f = gzip.GzipFile(in_file, "r") 15 f.readline() 16 except IOError: 17 f = open(in_file, "r") 18 f.readline() 19 f.seek(0) 20 return(f) 21 22 def line_generator(self): 23 print line()+". self.input_file.tell()==",self.input_file.tell() 24 for line_ in self.input_file: 25 print line()+". self.input_file.tell()==",self.input_file.tell() 26 yield line_.strip() 27 28 29 if __name__ == "__main__": 30 31 filename = "sac.log.50lines" 32 log_stream = LogStream(filename) 33 log_stream.input_file.seek(0) 34 line_generator = log_stream.line_generator() 35 line_ = line_generator.next() $ python generator.py 23. self.input_file.tell()== 0 25. self.input_file.tell()== 6623 $ wc -c sac.log.50lines 6623 sac.log.50lines $ cat generator.py #!/usr/bin/env python import gzip from Debug import _line as line class LogStream(): def __init__(self, filename): self.filename = filename self.input_file = self.open_file(filename) def open_file(self, in_file): try: f = gzip.GzipFile(in_file, "r") f.readline() except IOError: f = open(in_file, "r") f.readline() f.seek(0) return(f) def line_generator(self): print line()+". self.input_file.tell()==",self.input_file.tell() for line_ in self.input_file: print line()+". self.input_file.tell()==",self.input_file.tell() yield line_.strip() if __name__ == "__main__": filename = "sac.log.50lines" log_stream = LogStream(filename) log_stream.input_file.seek(0) line_generator = log_stream.line_generator() line_ = line_generator.next() -------------- next part -------------- An HTML attachment was scrubbed... URL: From eliben at gmail.com Wed Dec 10 12:14:20 2008 From: eliben at gmail.com (eliben) Date: Wed, 10 Dec 2008 09:14:20 -0800 (PST) Subject: SequenceMatcher bug ? References: <67253331-5b36-4018-b15a-c0b86c5342d3@r37g2000prr.googlegroups.com> Message-ID: <3d8ba4fe-0eb0-462c-b243-c157a9c0fe6d@i18g2000prf.googlegroups.com> > > My system is Gentoo, which installs python from source. ?Maybe gentoo > > applies patches that the binary releases don't have. > > I can't reproduce the problem. I got exactly the same results (0.999...) ? > with all the releases I have at hand, ranging from 3.0 back to 2.1.3, all ? > on Windows. > Andhttp://try-python.mired.org/says the same thing. > What ? This can't be. 1. Go to http://try-python.mired.org/ 2. Type import difflib 3. Type difflib.SequenceMatcher(None, [4] + [5] * 200, [5] * 200).ratio() Don't you get 0 as the answer ? The same with ActivePython on Windows ? Here's a snapshot from my run on a Linux box: Python 2.5.2 (r252:60911, Oct 20 2008, 09:11:31) [GCC 3.4.6 20060404 (Red Hat 3.4.6-10)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import difflib >>> >>> difflib.SequenceMatcher(None, [4] + [5] * 200, [5] * 200).ratio() 0.0 Executing exactly the same steps, do you not get 0.0 ? From steve at REMOVE-THIS-cybersource.com.au Sun Dec 28 03:03:29 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Dec 2008 08:03:29 GMT Subject: math module for Decimals References: <251111d8-a48a-45e3-a744-16fdb729fa33@i20g2000prf.googlegroups.com> Message-ID: <016729e4$0$6988$c3e8da3@news.astraweb.com> On Sat, 27 Dec 2008 21:50:09 -0800, jerry.carl.mi wrote: >> Which math functions? ln, log10, exp, sqrt already exist as methods of >> Decimal instances. At the end of the Decimal docs there are a few >> examples, including computing sin and cos (but apparently they na?vely >> use a McLaurin series like you noticed in other module). > > Hi Gabriel - thanks! For example all goniometric functions are missing. As my earlier email suggested, the easiest way to fix that is to simply write some wrappers that convert floats to decimal. Of course, that assumes that you don't need more precision than floats offer -- it's easy to change the result to get less precision, but if you really do need more, then you will need to bite the bullet and find (or write) your own trigonometric functions. > Or the log(x, base). Easy peasey. >>> def log(x, base): ... return x.log10()/Decimal(base).log10() ... >>> log(Decimal(64), 2) Decimal('5.999999999999999999999999999') If that's not accurate enough, you will need to do some additional work: >>> def log(x, base): # Warning: INSUFFICIENTLY TESTED ... power = 1 ... while base**power <= x: ... power += 1 ... power -= 1 ... x = x/Decimal(base**power) ... return x.log10()/Decimal(base).log10() + power ... >>> log(Decimal(64), 2) Decimal('6') > Or rand(). Generating random numbers is an art in of itself. Again, unless you really need the extra precision, just convert the random number to a string, then the string to a Decimal. An alternative is to find one of the many, many published algorithms for generating random numbers, and re-write that to use Decimals. However, most such algorithms aren't very random; they only give you a little bit of randomness, and increasing the precision of the numbers they return doesn't make them any more random. > Sure I can spend time trying to put it > all together but I thought somebody would have done that already. I believe they're all waiting for you to do it *wink* Development of Python is driven by need. If you need something, you can make a feature request, or you can build it yourself. But if everyone sits around hoping somebody else will develop the feature, nothing will ever happen. > It seems though that the codes that are out there are not ready Not ready for what? Perhaps they are perfectly ready for the needs of the person who wrote them. > - every one > of the modules i mentioned above has some issues. Maybe I can put bits > and pieces together, but if anyone knows of a well proven module (as > is), I would feel much safer using that (again I am not a mathematician > and poking into these algorithms makes me feel like trying to fix an > automatic transmission). Decimal is a relatively new module for Python, so it's not surprising that the functionality is relatively light. But all the hard parts are done. If you need extra functionality, you have a number of choices: (1) Find another way to solve your problem, or lower your expectations. (e.g. do you need arbitrary precision?) (2) Build the extra functionality yourself. (3) Pay somebody who is an expert to build it. (4) Ask nicely and hope somebody eventually decides to build it. (5) Use another language that already provides exactly all the features your problem needs. All of these are valid strategies. Unfortunately, a very popular strategy is counter-productive: (6) Complain loudly that Python is rubbish because it doesn't have the functionality you need, and Somebody Better Fix That RIGHT NOW or else there will be trouble you betcha. I recommend against strategy number six :) -- Steven From lists at cheimes.de Fri Dec 19 13:15:52 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 19 Dec 2008 19:15:52 +0100 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <6e232ab0-306a-4598-969a-211c4054e836@f40g2000pri.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <6e232ab0-306a-4598-969a-211c4054e836@f40g2000pri.googlegroups.com> Message-ID: r schrieb: > I was actually looking forward to 3.0, but the more I hear about 3.0, > the more I am turned off. I think there are a lot of other > pythonista's and pythoneers out there who agree but are not saying > anything. This syntax for string formatting is completely ridiculous. No, it's very powerful and used in other languages, too. > What is the purpose of breaking backward compatibility just to write a > print() function. This is going to push people away from python. The purpose of a print() function has been discussed for at least 3 years. You are welcome to read up all dicussions. > I heard map is going away too, is that true also??, and there was talk at one time(serious talk from > Guido) about removing lambda functions. Is this planned for the > future?? Wrong and wrong. map stays but it has been turned into an iterator. The removal of lambda has been discussed several years ago but it was repulsed. lambda stays. > Python has been beautifully designed from the beginning. But, I feel a > shift from this now. Are they scared of Ruby, if they are, why the > hell should they be. We do not need to lose any of the great > pythonista's right now, and we damn sure don't want to turn off the > new recruits. Python 3.0 is even more beautiful and more Pythonic. Backward compatibility was broken for the sake of the language. > It seems like most of the backward breaks are really just for dumb > reasons(sorry but its true). What is the logic behind this? The whole > reason for not having a print function was the need to use it so much > in debugging. And I was actually going to overlook that until I saw > this perl/ruby like format method. WTF! Your truth turns to be a totally different truth than mine -- and most of the active member of the community. Christian From zhang_killer at hotmail.com Thu Dec 11 00:01:20 2008 From: zhang_killer at hotmail.com (frendy zhang) Date: Thu, 11 Dec 2008 13:01:20 +0800 Subject: zip a created file Message-ID: if form.accepts(request.vars,session): for table in db.tables: rows=db(db[table].id).select() print rows open(str(os.sep).join([os.getcwd(), 'applications', request.application, 'databases', table+'.csv']),'w').write(str(db(db[table].id).select ())) where and what should i put the zip code to zip the file created above? thanks in advance _________________________________________________________________ Easily edit your photos like a pro with Photo Gallery. http://get.live.com/photogallery/overview -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwilson at the-wire.com Thu Dec 18 11:57:08 2008 From: mwilson at the-wire.com (Mel) Date: Thu, 18 Dec 2008 11:57:08 -0500 Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> Message-ID: Neal Becker wrote: > Tino Wildenhain wrote: > >> Neal Becker wrote: >>> Reading some FAQ, I see that __str__ is "meant for human eyes". >>> >>> But it seems that: >>> class X(object): >>> def __str__(self): >>> return "str" >>> def __repr__(self): >>> return "repr" >>> >>> x = X() >>> d = {0 : x} >>> print d >>> {0: repr} >>> >>> So if __str__ is "meant for human eyes", then why isn't print using it! >> >> it is: >> >> > print x >> str >> >> but dict just uses repr() for all its childs to print. >> >> T. > That makes no sense to me. If I call 'print' on a container, why wouldn't > it recursively print on the contained objects? Since print means call > str, printing a container should recursively call str on the objects. Basically because there are too many right ways to format the resulting report. Space separated? Tab separated? One per line? Boxes around them? As HTML definition lists? Creating a standard report form would take a lot of work and wouldn't, finally, solve very many peoples' problems. Mel. From lewis.sarah93 at yahoo.com Thu Dec 4 23:59:28 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 20:59:28 -0800 (PST) Subject: Earn More Money Message-ID: <8200fe24-6d66-4ee2-8e8b-950069724295@r40g2000yqj.googlegroups.com> Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From walterbyrd at iname.com Wed Dec 17 13:27:35 2008 From: walterbyrd at iname.com (walterbyrd) Date: Wed, 17 Dec 2008 10:27:35 -0800 (PST) Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> Message-ID: <5ad98089-883f-4ca6-934e-605e2376439c@f40g2000pri.googlegroups.com> On Dec 17, 8:41?am, prueba... at latinmail.com wrote: > If scoping worked as you want, how, pray tell, would you define object > attributes?- Hide quoted text - I suppose you could do this: class className(): varname = "whatever" def fname(self, varname): . . . . Instead of having variable defined within methods to be global everywhere within the class. Anyway, it's not a matter of what I like, I am just trying to understand the reason behind the scoping rules. From skip at pobox.com Mon Dec 29 21:32:45 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 29 Dec 2008 20:32:45 -0600 Subject: Python in C In-Reply-To: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> References: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> Message-ID: <18777.34893.283277.955506@montanaro-dyndns-org.local> thmpsn> 1. Can anyone explain to me what kind of program structuring thmpsn> technique (which paradigm, etc) CPython uses? How do modules thmpsn> interact together? What conventions does it use? it's quite object-oriented once you understand how things are done. Take a look, for example, at the implementation of floating point numbers: .../Objects/floatobject.c .../Include/floatobject.h BTW, as a person who hasn't really written a stitch of C++ in about 10 years I personally find the CPython implementation to be one of the most well-organized large pieces of code I have ever encountered. It's much easier to read (to me) than any significant piece of C++ code I have ever tried to read. Here are a few things which might help you understand the code structure a bit more: * The Python parser is generated from a specification. Look in .../Parser and .../Grammar/Grammar. * The code for most objects generally has a single entry point. For floating point objects it's _PyFloat_Init. The leading underscore tells the world "we needed to export this symbol, but keep your hands off it". Objects like floats and ints tend to have several other exported functions (search for "Py" at the beginning of a line) which are used by module writers. Objects implemented as extension modules (look in .../Modules/*.c) have a single (static) entry point, init_. The runtime dlopen's the so/dll file and calls that function. * Since C doesn't offer transparent method tables it's explicit in an object's code. Referring again to the float object code, look for the type specifier ("PyFloat_Type") and the method "dict" ("float_methods"). Note the comments at the end of the lines defining PyFloat_Type. They describe the use of each slot. Float objects aren't sequences so the tp_as_sequence is NULL. Similarly, objects such as lists which don't implement numeric methods a NULL tp_as_number slot. * The byte code compiler is in Python/compile.c. * The runtime interpreter is in Python/ceval.c. * Nothing requires a module to implement classes or types. Look at Python/sysmodule.c and Modules/mathmodule.c for two examples. Both modules export many functions but define no new types. Part of the complexity you might be stumbling on is due to the fact that Python is a mature application and so many parts of the implementation have been fine-tuned. Python "eats its own dog food", so for example the dict implementation you use in your scripts is also used by the runtime virtual machine to implement namespaces of all sorts (instance, class and module dicts, for example). It has been heavily optimized. Take a look at Objects/dictnotes.txt. Also, observations about the data use of many Python programs (and the C runtime itself) have lead to a number of optimizations such as the int and float free lists and the custom object allocator implemented in Objects/obmalloc.c. thmpsn> 2. Have there been any suggestions in the past to rewrite thmpsn> Python's mainstream implementation in C++ (or why wasn't it thmpsn> done this way from the beginning)? C++ was far from widely enough available when Python was first written in the late-80s/early-90s. Today there is no particular reason to rewrite it. If you want to incorporate externally written C++ code into Python you can do that either manually or using tools such as SWIG, SIP or Boost.Python. HTH, -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From tino at wildenhain.de Tue Dec 30 12:53:55 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Tue, 30 Dec 2008 18:53:55 +0100 Subject: Parsing Excel spreadsheets In-Reply-To: <4894d0fe-a238-4675-9e79-0b0755c001e8@y1g2000pra.googlegroups.com> References: <6a54de23-bea4-40c7-ad7c-22c6eba4bd8a@z6g2000pre.googlegroups.com> <4894d0fe-a238-4675-9e79-0b0755c001e8@y1g2000pra.googlegroups.com> Message-ID: <495A6033.6040908@wildenhain.de> r wrote: > On Dec 30, 10:07 am, "andyh... at gmail.com" wrote: >> Hi, >> >> Can anybody recommend an approach for loading and parsing Excel >> spreadsheets in Python. Any well known/recommended libraries for this? >> >> The only thing I found in a brief search washttp://www.lexicon.net/sjmachin/xlrd.htm, >> but I'd rather get some more input before going with something I don't >> know. >> >> Thanks, >> Andy. > > xlrd(read only) > also see pyExcelerator which is now replaced by xlwt :-) Cheers Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From fakeaddress at nowhere.org Tue Dec 2 21:44:27 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 02 Dec 2008 18:44:27 -0800 Subject: Overriding a method at the instance level on a subclass of a builtin type In-Reply-To: References: Message-ID: <4omZk.9067$c45.3224@nlpi065.nbdc.sbc.com> Zac Burns wrote: > Sorry for the long subject. > > I'm trying to create a subclass dictionary that runs extra init code > on the first __getitem__ call. However, the performance of __getitem__ > is quite important - so I'm trying in the subclassed __getitem__ > method to first run some code and then patch in the original dict > method for the instance to avoid even the check to see if the init > code has been run. Various recipes using instancemethod and the like > have failed me. One option is to re-assign the object's __class__, as in: class XDict (dict): pass class ZDict (XDict): def __getitem__(self, k): whatever_you_want_to_do_once(self) result = dict.__getitem__(self, k) self.__class__ = XDict return result The first dict subtype is needed because __class__ assignment requires that both the current and newly-assigned class be 'heap types', which the native dict is not. -- --Bryan From sambo at voidstar.com Wed Dec 3 01:01:34 2008 From: sambo at voidstar.com (Sambo) Date: Wed, 03 Dec 2008 01:01:34 -0500 Subject: noob needs help References: <6pg4oqF7rgu0U1@mid.individual.net> Message-ID: Peter Pearson wrote: > When you type "python helloworld.py", python looks for helloworld.py > in the current "working" directory, which is probably your personal > default directory ("~"). For better results, either save helloworld.py > to this directory, or copy it to this directory > ("cp Documents/helloworld.py ."), or tell python to look for it > in the Documents directory ("python Documents/helloworld.py"). > > (I'm guessing that your directory structure looks something > like /home/collin/Documents. If I've guessed wrong, some > adjustment may be needed. Also, if you're feeling ambitious, > you might want to consider putting this project in a directory > of its own; that would involve the mkdir and cd commands.) > In slackware one needs "./" before the filename if you executing files in current dir. From hniksic at xemacs.org Thu Dec 4 16:40:46 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 04 Dec 2008 22:40:46 +0100 Subject: schizophrenic view of what is white space References: <4937E8E5.2090306@chamonix.reportlab.co.uk> <20081204143337.20272.1236189783.divmod.quotient.15592@ohm> <4938112F.5030706@chamonix.reportlab.co.uk> Message-ID: <878wqvy5y9.fsf@mulj.homelinux.net> MRAB writes: > I'm not sure why the Unicode flag is needed in the API. I reckon > that it should just look at the text that the regular expression is > being applied to: if it's Unicode then follow the Unicode rules, if > not then don't. It might be that using Unicode tables for lookup of character classes slows things down considerably because the tables are huge. It is useful to be able to treat Unicode strings the same way ASCII strings are treated, but the question is what should be the default. Whitespace is probably not controversial, but many parsers tend to expect things like \d to match [0-9], not any Unicode character marked as "digit". For example, I'm not sure if this behavior would be a good default: >>> re.match(r'\d', u'\u0660', re.UNICODE) <_sre.SRE_Match object at 0xb7da0250> What digit is \u0660, out of 0-9? Hard to say. If re.UNICODE were the default for Unicode strings, code that expected \d to yield an actual digit would have a problem on their hands -- especially so in Python 3 where that would apply to *all* strings. From paul.hermeneutic at gmail.com Sat Dec 6 00:03:40 2008 From: paul.hermeneutic at gmail.com (Paul Watson) Date: Fri, 05 Dec 2008 23:03:40 -0600 Subject: Running Python 2 and Python 3 on the same machine In-Reply-To: <4939c6ef$0$6534$9b622d9e@news.freenet.de> References: <1228424486.5873.6.camel@linux-3eb6.site> <49387f7e$0$27857$9b622d9e@news.freenet.de> <1228489547.5613.10.camel@linux-3eb6.site> <4939c6ef$0$6534$9b622d9e@news.freenet.de> Message-ID: <1228539820.27659.21.camel@linux-3eb6.site> On Sat, 2008-12-06 at 01:27 +0100, "Martin v. L?wis" wrote: > > For *NIX machines, will 'python' be placed into /usr/bin? > > Not by default, no. Just try it and see for yourself. > > Regards, > Martin Ok. I built the source on an openSUSE 11.0 system. I used 'sudo make altinstll'. It created an executable /usr/local/bin/python3.0 file. Nothing was touched in /usr/bin. I need to start writing some code with Python 3. I want to write the code in such a way that it can be easily shared with others with the least difficulty and overhead as possible. How should I write the code to enable this? What, if anything, should I assume about another system's configuration? As someone suggested before, naming the files as '.py3' is probably a bad idea in the long run. It also does not really solve the problem. I could use a shebang. But, what should it specify? If I use 'python3.0', then that will soon be quite old. If I make up a link for python3 -> python3.0, that would work, but then every other system that is to run the code must that link also. However, I am thinking that this would be the best long term answer. #!/usr/bin/env python3 My existing /usr/bin directory has three entires for python. python -> python2.5 python2 -> python2.5 python2.5 If I write scripts for Python 3, another developer writes scripts for Python 2, and a common customer wants to install both of our packages onto a single machine, then what is the best plan for everyone to make that happen with as little difficulty as possible? When we find out the answer to this, we can go back and talk about Windows platforms. From pdorange at pas-de-pub-merci.mac.com Thu Dec 25 05:22:12 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Thu, 25 Dec 2008 11:22:12 +0100 Subject: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> <90f06b27-39da-4f1a-a878-f3972e942d57@s24g2000vbp.googlegroups.com> <62caf93b-0455-4450-9895-8a9d9554f75e@r32g2000vba.googlegroups.com> <1isezkk.51e05y1457jqrN%pdorange@pas-de-pub-merci.mac.com> <3cb2a746-1a43-44a1-9825-7667af9fe2fa@s1g2000prg.googlegroups.com> Message-ID: <1isi4sn.11mpft612g7udcN%pdorange@pas-de-pub-merci.mac.com> r wrote: > 220 ratings and 1 star, WHOOOO!. I find this all quite amusing :D. > Keep em coming. Oh, and FYI, I will always have 1 star! hahahahahha > > > /"\ > |\./| > | | > | | > |>~<| > | | > /'\| |/'\ > /~\| | | |__ > | | } | | \ > | | | | | \ > | ~ ~ ~ ~ |` ) > | / > \ / > \ / > \ ____ / > |--//''`\--| > | (( +==)) | > |--\_|_//--| Very nice indeed, but you forget ascii art need a fixed font... -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From 5lvqbwl02 at sneakemail.com Tue Dec 30 18:25:27 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Tue, 30 Dec 2008 15:25:27 -0800 (PST) Subject: Understanding search queries, semantics, and "Meaning" ...aren't we all looking for meaning? References: <82372457-2503-4682-96b3-37540328bf26@w39g2000prb.googlegroups.com> <94ab1653-c88d-4bad-a094-47d67e435618@w1g2000prm.googlegroups.com> Message-ID: <3d4991d9-d0ab-4483-aee7-2763e3712b96@w1g2000prm.googlegroups.com> > > library, as I'm looking to learn to fish, so to speak, and to learn a > > bit about the biology of fish. > > I'm going to break rule #1 of your requirements but in an unexpected > way. Rather than studying PostgreSQL, MySQL, or Oracle, why don't you > crack open the topic of relational database theory and relational > algebra? That should help with the "big thinking" bit in the same way > understanding 1+1 helps you understand how to add any two numbers Ah, exactly, thanks for understanding my original post :) I guess 'relational database theory' is what I should start looking around for... otherwise googling on sql, queries, etc., just returns how to execute a query, but says nothing about how a fish works. > > In a typical SQL database, when you type in "SELECT foo FROM bar WHERE > baz='bo'", you are not writing a program, at least not in the sense of > Python or C or Java or Perl where you give instructions on HOW to run > the program. You are writing a program in the sense of Lisp or Scheme > or Haskell in that you are giving instructions on WHAT the program is. I've gotten a strong inkling that parsing a query yields new code, (lambdas) that are created on the fly to do the search. > table and then start going through the process of elimination removing > rows it doesn't want to think about. That's highly inefficient, of Exactly what I'm trying to avoid. > course. Instead, it transforms the query (the WHAT) into a set of > procedures that describe HOW to get the result. For now I'm not parsing actual text queries... my real "search query" is coded directly in python like this: p1 = lambda: db.search_leaf('x location', 'lte', 5) p2 = lambda: db.search_leaf('footprint', 'eq', '0603') p3 = lambda: db.search(db.AND, p1, p2) p4 = lambda: db.search_leaf('x location', 'gte', 19) p5 = lambda: db.search_leaf('footprint', 'eq', '0402') p6 = lambda: db.search(db.AND, p1, p2) fc = db.search(db.OR, p3, p4) this particular example doesn't necessarily make any sense, but in effect I'm trying to string together lambda functions which are created explicitly for the individual query, then strung together with combiner functions. > Oh, by the way, this step is nondeterministic. Why? Well, no one can > really say what the BEST way to run any sufficiently complicated > program is. We can point out good ways and bad ways, but not the best > way. It's like the travelling salesman problem in a way. The nondeterministic stuff... wow, I've come across (call/cc...), (require...), and different variants of this, both in sicp, teach yourself scheme, the plt docs, other places, etc., but it still eludes me. I'm afraid that unless I understand it, I'll wind up creating some type of cargo-cult mimcry of a database without doing it right (http://en.wikipedia.org/wiki/Cargo_cult) > programmer, will be infinitely better for it. When you understand it, > you will really unlock the full potential of Python and Scheme and > whatever other language is out there because you will see how to go > from HOW languages to WHAT languages. I'm under the impression python doesn't have the internal guts for nondeterministic programming, specifcially that its lambdas are limited to single-line expressions, but I may be wrong here. Still, at the begining of the nondeterministic section of SICP (section 4.3), it says "nondeterministic computing... is useful for 'generate and test' applications", which almost categorically sounds like an element-by-element search for what you're looking for. This was my initial intention behind (prematurely?) optimizing the database by using parameter keys instead of something like [x for x in stuff if pred(x, val)] filtering. > Programmers who can write compilers are GOOD programmers. Programmers > who can understand someone else's compilers are even better. Does incorporating a search capability in an application necessarily mean I'm writing a search compiler? That seems overkill for the specific case, but may be true generally. For instance, if a word processing app allows you to search for characters with a certain font, is that incorporating a search compiler and query language? Or is it just brute-force filtering? > That's my semi-guru advice. Thanks :) Michael From benjamin.kaplan at case.edu Sun Dec 21 17:33:48 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 21 Dec 2008 17:33:48 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: On Sun, Dec 21, 2008 at 2:26 PM, r wrote: > I noticed when i mentioned "self" nobody wants to touch that subject. > There could be many reasons why... > > 0.) nobody but the 10 regulars i see here exists if you only see 10 people, you must not be following this list very well. > > 1.) nobody cares(doubt it) If people cared that much, they wouldn't use python. > > 2.) nobody is brave enough to question it(maybe) Check the archives. There have been plenty of people who questioned it. People got so bored with them that the only answer you're likely to get now is people quoting the zen. > > 3.) most people like to type self over and over again(doubt it) You have to type self over and over again? I don't know about the other editors, about Eclipse/PyDev's autocomplete will add it to any function declared within a class unless it has @staticmethod or @classmethod above it. > > 4.) most people here have given up on changing the BDFL's mind about > it. (good possibility) > 5.) this is a hot-button topic(no doubt in my mind!) Not really. Again, if you care that much about explicit self, use another language. > > > I think Guido's intension's are pure, but this is a major turnoff to > new users. Do we really need to hold a new users hand that much. Does > it really matter if they know the path of said obj. If you can't > fiqure this out for yourself you have much greater problems. > > I do not like self, and i lamented it from day one, now it is second > nature to me but does that mean it is really needed?? I feel i have > been brainwashed into its usage. > > This was the reason for using indention over the bracket plague in > python. REDUNDANCY!!! Why not dump self and make the language cleaner. > I love python's classes, but HATE self.redundant! This really needs to > be fixed, and you have not heard the last from me about it!!! > > 3000 would have been the perfect time to dump self and really clean up > the language, and it's not too late, dawn is not upon us yet. yes, it is too late. Python 3 is out and done. There will be no more sweeping, backwards-incompatible changes until Python 4. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vginer at gmail.com Thu Dec 18 15:12:38 2008 From: vginer at gmail.com (Vicent Giner) Date: Thu, 18 Dec 2008 12:12:38 -0800 (PST) Subject: IDLE cursor color References: <65c5974c-e5c5-46c1-9673-371a7c9ea047@a12g2000pro.googlegroups.com> <313c1a14-ac85-4326-a2dc-29955549a708@f11g2000vbf.googlegroups.com> Message-ID: On 18 dic, 20:52, r wrote: > in IDLE go to: > Options -> Configure IDLE -> Highlighting... > > 1.) in the box click the word "cursor" > 2.) press the button that says "Choose Color for" > 3.) Pick a color and save the changes > > viola! you did it! :) Thank you! I don't understand... I have tried that before and it didn't work. Now it does!! :-S Previously, I changed the cursor color to green, but nothing happened. That's why I sent the message to the list. Now I've changed it again to "pink", and now I can see it, blinking and blinking... :-) Thanks again! -- Vicent From ranjith.priya at gmail.com Fri Dec 19 01:13:09 2008 From: ranjith.priya at gmail.com (Priya Ranjith) Date: Thu, 18 Dec 2008 22:13:09 -0800 (PST) Subject: Openings for Release Management Message-ID: Position: Build and Release Engineer Experience Required: 2 - 7 yrs Qualification: B.E/M.E/M.C.A/B.Tech Skills Required: 1) Working experience in distributed version control system like Mercurial / Bazar / GIT or Subversion 2) Experience in RBuilder 3) Working experience in creating software appliance. 4) Experience in Python 5) Working experience in Ant / Maven 6) Should posses good communication skills: excellent English, both written and spoken is a must. 7) High level of professionalism The Release Engineer function has the following key areas of responsibility: 1) Continuous improvement of Release processes, methodologies and tools to ensure best quality for both product lines: Community Edition and Professional Edition. 2) Track and support the whole Release cycle, coordinating teams involved in the Release processes: engineering, QA, Beta Testers and Community. 3) Keep people informed about status, contents, dates, etc. 4) Support Senior Management to define the guidelines of whole release product strategy. From BrianVanderburg2 at aim.com Fri Dec 19 12:02:58 2008 From: BrianVanderburg2 at aim.com (Brian Allen Vanderburg II) Date: Fri, 19 Dec 2008 12:02:58 -0500 Subject: If programming languages were religions... In-Reply-To: References: Message-ID: <494BD3C2.1050001@aim.com> martin.laloux at gmail.com wrote: > very interesting > http://www.aegisub.net/2008/12/if-programming-languages-were-religions.html > > "Python would be Humanism: It's simple, unrestrictive, and all you > need to follow it is common sense. Many of the followers claim to feel > relieved from all the burden imposed by other languages, and that they > have rediscovered the joy of programming. There are some who say that > it is a form of pseudo-code" > > compare to > "Perl would be Voodoo - An incomprehensible series of arcane > incantations that involve the blood of goats and permanently corrupt > your soul. Often used when your boss requires you to do an urgent task > at 21:00 on friday night." > > and others > -- > http://mail.python.org/mailman/listinfo/python-list > If programming languages were religions: When first powering on a computer, there would only be one programming language, the language of the boot loader. As the computer runs, processes of one language would spawn processes of other languages, and over the course of time many different languages would have many different processes (followers). One of these languages would rise up to be dominant and would kill all processes of other languages by the signal, whether old or young. The processes would be given a fair change, convert to their language or be killed. Countless thousands or maybe even millions of processes would die, even the processes that say there is no one true programming language and wants to know why all the processes can't just get along. From google at mrabarnett.plus.com Fri Dec 19 11:56:05 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 19 Dec 2008 16:56:05 +0000 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <6r219cFfc8ovU1@mid.individual.net> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> Message-ID: <494BD225.1050704@mrabarnett.plus.com> Thomas Heller wrote: > Mark Summerfield schrieb: >> Just a follow-up to say that the book has now been published in the >> U.S. >> It is now in stock at InformIT, and should reach other stores, e.g., >> Amazon, in a week or so. >> >> Also, the introduction, the first few pages of the first chapter, the >> whole of chapter 12 (regular expressions), and the index are now >> available for free download in a PDF from here: >> http://www.informit.com/store/product.aspx?isbn=0137129297 > > Question from a non-native english speaker: is this now valid english? > > "One of Python?s great strengths" > ^ > "and also teaches Python?s functional programming features" > ^ > "The book?s approach is wholly practical" > ^ > Looks OK to me. From python.list at tim.thechases.com Wed Dec 10 14:18:15 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 10 Dec 2008 13:18:15 -0600 Subject: get todays files In-Reply-To: <4632c353-0462-485b-9e1b-6a5c56682363@s9g2000prg.googlegroups.com> References: <4632c353-0462-485b-9e1b-6a5c56682363@s9g2000prg.googlegroups.com> Message-ID: <494015F7.3020302@tim.thechases.com> > This looks very good and I have tested successfully, but is there a > way I can set the today to automatically become todays date in that > format? Yes...see the python datetime module[1]...particularly the strftime() call on date/datetime objects. -tkc [1] http://docs.python.org/library/datetime.html From philip at semanchuk.com Mon Dec 15 09:56:14 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Mon, 15 Dec 2008 09:56:14 -0500 Subject: Thread Locking issue - Can't allocate lock (sem_init fail) In-Reply-To: References: Message-ID: On Dec 15, 2008, at 4:56 AM, jamskip at googlemail.com wrote: > Hi all, > > I have a peculiar problem with a multithreaded program of mine > (actually I've sort of inherited it). Before i show you the error, > here's a litle background. Its a program to check email addresses are > valid, and its main task is to verify the domain names. > > Here's the basic functionality: > > * The prog has a list of domains it has seen before which is read into > memory (the 'rollover'). > * A new list of emails is read-in from a file (to a queue) and is > checked against the rollover. > * If we've seen the domain before then update the existing entry. > * If we've not seen the domain before, add it. > > The program is multithreaded to speed up the processing...there are > input and output Queues. > > Now, each domain entry is an class object containing various bits of > info. Each domain class also has its own lock, so that only one thread > can modify each domain at a time. > > I'm load-testing the program with a sample of 1 million email > addresses and when i hit about the 500,000 mark i get a locking > error... > > sem_init: No space left on device > Exception in thread Thread-2: > Traceback (most recent call last): > File "/usr/local/lib/python2.4/threading.py", line 442, in > __bootstrap > self.run() > File "/usr/local/lib/python2.4/threading.py", line 422, in run > self.__target(*self.__args, **self.__kwargs) > File "jess.py", line 250, in worker > record.result = function( id, record.value ) > File "jess.py", line 291, in action > found_domain = domains.addNewDomain( domain_name ) > File "jess.py", line 123, in addNewDomain > self.domain_store.append( self.Domain( name = name ) ) > File "jess.py", line 46, in __init__ > self.lock = Lock() > error: can't allocate lock > > Googling for this sort of error doesn't yield any results, and i can't > find any information about limits to the number of locks you can have > in Python. The 'No space left on device' message indicates a memory > issue, however i doubt this since its running on a linux server with 4 > cores and 16GB ram. It seems more like an internal Python limit has > been hit (sem_init - semaphore initialisation?). Does anyone know more > about threading internals and any internal limits? Hi Jamskip, I don't work with threading code but I have been working with semaphores for my IPC extensions. sem_init() is a call to create a semaphore (http://linux.die.net/man/3/sem_init). If it is failing, then I'd guess you're trying to create an awful lot of semaphores (intentionally or otherwise) and that you're hitting some internal limit. I would not be too quick to assume that the number of semaphores one can create is bounded by the amount of RAM in your system. I don't think they're simple chunks of malloc-ed memory. They're probably represented in a kernel data structure somewhere that's hardcoded to some generous but fixed value. Please note that this is all speculation on my part. I think that the Python threading implementation would use the "local" (i.e. not process-shared) semaphores which can be allocated on the process' heap. This would seem only RAM-limited, but I'll bet it isn't. You might want to start debugging by track exactly how many locks you're creating. If the number is really big, start investigating kernel semaphore limits and how they're set. Good luck Philip From gamersunit at gmail.com Thu Dec 11 19:35:33 2008 From: gamersunit at gmail.com (Gregory Plantaine) Date: Thu, 11 Dec 2008 16:35:33 -0800 (PST) Subject: Find Files in a Folder Between 2 Dates References: <4c54b6c5-ae4d-4b89-8c6d-940c96de29bb@n33g2000pri.googlegroups.com> <94cd4bd7-a69f-48ba-90f7-382014844905@g1g2000pra.googlegroups.com> <862567e3-4469-43ae-b41b-1a1817124f50@k36g2000pri.googlegroups.com> <6b3bed68-3036-4e05-9571-e7dce0db2cff@r36g2000prf.googlegroups.com> Message-ID: <7ef72fa0-bf7b-453c-8bd4-4e947bc84a25@i18g2000prf.googlegroups.com> On Dec 11, 11:02?am, Gregory Plantaine wrote: > On Dec 5, 3:14?pm, John Machin wrote: > > > > > > > On Dec 6, 9:41?am, GregoryPlantaine wrote: > > > > That worked perfectly! > > > > Thanks Tim! > > > > Since we can print the files, does that mean the list of files is in a > > > tuple, or something? ?Would there be a way to further split up the > > > file names? > > > > For example, now that the files are processed into the list, we want > > > to look through that list to find different filetypes. > > > > files > > > > C:\Folder\File_200812051439.111 > > > C:\Folder\File_200812051539.222 > > > *DANGER* It looks like you are interested in the timestamps that are > > embedded in the names of the files. Tim's code assumes [reasonably > > given that your problem description was ambiguous and had no examples > > of good and bad results] that you are interested in the last > > modification time of the file. You may say "same thing". Yes, same > > thing, until somebody sucks a file into a text editor, messes with it, > > and saves it again. No, Murphy's Law has not been repealed. > > > > Can we split up .111 files? > > > > Actually, where would I look something like this up? > > > In the Library Reference Manual ... there are all sorts of goodies in > > the os and os.path modules e.g. like those used by Tim; make sure you > > read the docs on the methods Tim used so that you understand what's > > happening. > > > HTH, > > John > > Thanks for the advice John! > > I was going though the Manual, but I'm having some trouble figuring > out how to iterate through each line. > > So from the same example, we've already created a list called "lists". > Now how do I iterate through each line? > > For eachline in lists > ? ? Find all .111 files.- Hide quoted text - > > - Show quoted text - Ok, I figured it out. Actually more simple than I thought: for eachfile in files: if eachfile.endswith(".111"): print eachfile Another somewhat related question, instead of defining the firstdate, how would we do this? firstdate = secondate - 7 days From lie.1296 at gmail.com Fri Dec 12 16:48:09 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 12 Dec 2008 21:48:09 +0000 (UTC) Subject: Interface & Implementation References: <11e2ac5b5eb.2364397661727502391.6806593866408074890@adventnet.com> Message-ID: On Fri, 12 Dec 2008 16:07:26 +0530, J Ramesh Kumar wrote: > Hi, > > I am new to python. I require some help on implementing interface and > its implementation. I could not find any sample code in the web. Can you > please send me some sample code which is similar to the below java code > ? Thanks in advance for your help. > > ............ > public interface MyIfc > { > public void myMeth1(); > public void myMeth2(); > } > .... > public class MyClass implements MyIfc { > public void myMeth1() > { > //do some implementation > } > > public void myMeth2() > { > //do some implementation > } > } There is no need for interface in python due to duck typing class MyClass1(object): def myMeth1(self): # some implementation def myMeth2(self): # some implementation class MyClass2(object): def myMeth1(self): # other implementation def myMeth2(self): # other implementation cs[0] = MyClass1() cs[1] = MyClass2() for c in cs: c.myMeth1() c.myMeth2() but if you really want it, simple inheritance might be better anyway, though not really pythonic: class MyIfc(object): def myMeth1(self): return NotImplemented def myMeth2(self): return NotImplemented class MyClass(MyIfc): def myMeth1(self): # some implementation def myMeth2(self): # some implementation # some might notice the (ab)use of NotImplemented sentinel there From martin at v.loewis.de Mon Dec 15 16:48:15 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 15 Dec 2008 22:48:15 +0100 Subject: Problem Python 2.6.1 vs 2.6 & pyWin32 In-Reply-To: <4946754f$0$19000$426a74cc@news.free.fr> References: <4946754f$0$19000$426a74cc@news.free.fr> Message-ID: <4946D09F.6050300@v.loewis.de> > I am very disappointed. Help me, please. Try installing Python 2.6.1 "for all users". Regards, Martin From rocky at panix.com Thu Dec 11 05:06:31 2008 From: rocky at panix.com (R. Bernstein) Date: Thu, 11 Dec 2008 05:06:31 -0500 Subject: sys.settrace 'call' event behavior Message-ID: On Jun 21, 8:47 am, Michal Kwiatkowski wrote: > I'm building a tool to trace all function calls usingsys.settrace > function from the standard library. One of the awkward behaviors of > this facility is that the class definitions are reported as 'call' > events.[1] Since I don't want to catch class definitions, only > function calls, I'm looking for a way to differentiate between those > two. So far I have only vague clues about how to do that. > > At the bottom of this mail is a simple script that prints all > attributes (except for the bytecode) of the traced code. In the sample > code Bar class is defined and foo function is called after that. The > following trace output is reported: > > Bar, 0, 0, (), (), (), (None,), ('__name__', '__module__', 'None'), > foo.py, 21, , 1, 66 > foo, 0, 0, (), (), (), (None,), (), foo.py, 25, , 1, 67 > > Class definition and functioncalldiffers on four attributes. Two of > them, co_name and co_firstlineno are not very helpful. Other two are > co_names and co_flags. The latter differs only by the CO_OPTIMIZED > flag, which is for "internal use only"[2]. So we're left with > co_names, which "is a tuple containing the names used by the > bytecode". Is that helpful in distinguishing between class definitions > and function calls? Do you have any other ideas on how to tell them > apart? > > Source of the sample script I used follows. > > def trace(frame,event, arg): > ifevent== 'call': > print ', '.join(map(str, [frame.f_code.co_name, > frame.f_code.co_argcount, > frame.f_code.co_nlocals, > frame.f_code.co_varnames, > frame.f_code.co_cellvars, > frame.f_code.co_freevars, > frame.f_code.co_consts, > frame.f_code.co_names, > frame.f_code.co_filename, > frame.f_code.co_firstlineno, > frame.f_code.co_lnotab, > frame.f_code.co_stacksize, > frame.f_code.co_flags])) > return trace > > import syssys.settrace(trace) > > class Bar(object): > None > pass > > def foo(): > pass > > foo() > > [1] It is strange for me, but documented properly.http://docs.python.org/lib/debugger-hooks.htmlsays thatcallevent > happens when "a function is called (or some other code block > entered)." > > [2]http://docs.python.org/ref/types.html#l2h-145 > > Cheers, > mk Perhaps you could filter based on the type of the frame.f_code.co_name ? e.g. or type(eval(frame.f_code.co_name)) (Sorry for the delayed reply - I don't generally read the newsgroup and stumbled across this looking for something else. But I noticed no replies, so...) From pavlovevidence at gmail.com Thu Dec 4 00:29:17 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 3 Dec 2008 21:29:17 -0800 (PST) Subject: How can I do this (from Perl) in Python? (closures) References: <68b8294c-8771-4b02-bd46-2f25f5e01602@j35g2000yqh.googlegroups.com> Message-ID: <712b964c-764f-42bd-bec5-0e9acea15d8e@13g2000yql.googlegroups.com> On Dec 3, 11:18?pm, excor... at gmail.com wrote: > I just came acrosshttp://www.perl.com/pub/a/2002/05/29/closure.html > and wanted to try the "canonical example of closures" in Python. I > came up with the following, but it fails: > > ####################### > #!/usr/bin/env python > > def make_counter(start_num): > ? ? start = start_num > ? ? def counter(): > ? ? ? ? start += 1 > ? ? return counter > > from_ten = make_counter(10) > from_three = make_counter(3) > > print from_ten() ? ? ? # 10 > print from_ten() ? ? ? # 11 > print from_three() ? ? # 3 > print from_ten() ? ? ? # 12 > print from_three() ? ? # 4 > #################### > > The error message is: "UnboundLocalError: local variable 'start' > referenced before assignment". The same thing happens if I omit start > and just use start_num directly. > > How can I do it in Python? In Python 3.0, you can do this: def make_counter(start): def counter(): nonlocal start start += 1 return start # I assume you forgot this above return counter In Python 2.x, there is no nonlocal statement, so the best you can do is improvise something like this: def make_counter(start_num): start = [start_num] def counter(): start[0] += 1 return start[0] return counter You can access variables from an enclosing scope starting from Python 2.2 (from 2.1 with from __future__ import nested_scopes), but you could not rebind those variables until Python 3.0 came out today. Carl Banks From sjmachin at lexicon.net Fri Dec 19 08:39:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 19 Dec 2008 05:39:34 -0800 (PST) Subject: How to parsing a sequence of integers References: <494ba258$0$18998$426a74cc@news.free.fr> Message-ID: On Dec 20, 12:33?am, Bruno Desthuilliers wrote: > Steven Woody a ?crit :> Hi, > > > I am a newbie and is reading the python book. ?Could anyone tell me, > > how to parsing the following string > > ? ?"123 100 12 37 ..." > > ?> into a list of integers on which I can then apply max()/min()? > > source = "123 100 12 37" > list_of_ints = [int(part) for part in source.strip().split()] The purpose of the .strip() would be ...? From cptnwillard at gmail.com Mon Dec 1 05:12:03 2008 From: cptnwillard at gmail.com (cptnwillard at gmail.com) Date: Mon, 1 Dec 2008 02:12:03 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <3a30f601-7128-4e5f-a97e-9f899404912c@o40g2000prn.googlegroups.com> <4f31c483-8382-480e-8417-b7eef1b1792d@z1g2000yqn.googlegroups.com> <8c856b01-7f0c-4d5b-a1d2-cfe7dc74389f@w3g2000yqc.googlegroups.com> <1680020c-521c-4498-8e74-92e99c03da6b@w35g2000yqm.googlegroups.com> <0d9d2404-cb3f-4390-b97c-79251db8ac95@k8g2000yqn.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> Message-ID: Don't feed the troll. From steve at REMOVE-THIS-cybersource.com.au Tue Dec 16 20:48:04 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 17 Dec 2008 01:48:04 GMT Subject: weird dict problem, how can this even happen? References: <88idnfej99XAtNXUnZ2dnUVZ_hednZ2d@pdx.net> Message-ID: <015851be$0$20656$c3e8da3@news.astraweb.com> On Wed, 17 Dec 2008 02:10:31 +0100, Joel Hedlund wrote: > Scott David Daniels wrote: >> Perhaps your hash function could be something like: > > I'm not sure I understand what you're suggesting. Neither am I, since you've removed the hash function which might have given readers a clue. *wink* Snipping irrelevant text is a Good Thing, but in this case you were a little heavy-handed. -- Steven From girbarobert at yahoo.com Tue Dec 2 05:34:34 2008 From: girbarobert at yahoo.com (girbarobert at yahoo.com) Date: Tue, 2 Dec 2008 02:34:34 -0800 (PST) Subject: Obama's Birth Certificate - Demand that US presidential electors investigate Obama's eligibility Message-ID: This message is not about the meaningless computer printout called "Certification of Live Birth" that Obama propaganda machine calls his "Birth Certificate". The American people are still waiting for a copy of Obama's original birth certificate that includes all his birth information. Remind your US presidential electors of their constitutional duty to investigate Obama's natural-born citizen status. No federal agency like FBI or Secret Service, no Hawaii bureaucrats have ever investigated Obama's birth in Hawaii. Many illegal aliens in USA have official "birth certificates" issued by state bureaucrats on the basis of falsified birth records. Obama has spent over $800,000 in legal costs to avoid presenting a $10 copy of his original birth certificate on the grounds that nobody has a legal standing to see it. Remind your US presidential electors that they have the legal standing and constitutional duty to investigate Obama's birth in Hawaii by demanding that Obama provide all his original birth records, and a federal agency like FBI or Secret Service fully investigate them. To find the names of US presidential electors use the partial list at wikipedia below. Or use www.google.com, click News on top, then in the Search News enter the name of your state and the words: presidential electors. Or contact your US Senators, US House Rep, your state senators/reps, etc. If a US presidential elector refuses to investigate Obama's eligibility then post his/her full name on the internet so that all web search engines can pick it up. http://www.wnd.com/index.php?fa=PAGE.view&pageId=81550 http://en.wikipedia.org/wiki/List_of_United_States_presidential_electors,_2008 http://www.senate.gov/general/contact_information/senators_cfm.cfm http://clerk.house.gov/member_info/index.html From steve at REMOVE-THIS-cybersource.com.au Mon Dec 29 20:06:26 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Dec 2008 01:06:26 GMT Subject: get method References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> Message-ID: <01696b1a$0$6988$c3e8da3@news.astraweb.com> On Mon, 29 Dec 2008 17:00:31 -0800, Ross wrote: > Here's my code: > > def histogram(s): > d = dict() > for c in s: > d[c]= d.get(c,0) > return d > > This code returns a dictionary of all the letters to any string s I give > it but each corresponding value is incorrectly the default of 0. What am > I doing wrong? You're forgetting to increase the count each time you see a letter: * Look up the letter c in the dict, and call it count; * If c isn't found in the dict, use 0 as the count. * Set the value to count. But at no point do you increase count. -- Steven From bj_666 at gmx.net Wed Dec 10 09:33:57 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Dec 2008 14:33:57 GMT Subject: Announcement: MindTree for Python beta -- feedback appreciated References: <20841316.post@talk.nabble.com> <6q9ksbFbef4kU1@mid.individual.net> Message-ID: <6qa2alFbdrbpU1@mid.uni-berlin.de> On Wed, 10 Dec 2008 23:47:05 +1300, greg wrote: > Johann Spies wrote: > >> % /usr/local/bin/python3.0 MindTree.pyw >> Traceback (most recent call last): >> File "MindTree.pyw", line 2, in >> from future_builtins import * >> ImportError: No module named future_builtins > > Hmmm... does this mean that Python3 has no future? :-) It is just not built in. So it is easier to change the future by replacing the module. ;-) Ciao, Marc 'BlackJack' Rintsch From __peter__ at web.de Tue Dec 9 03:19:23 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Dec 2008 09:19:23 +0100 Subject: html codes References: Message-ID: Daniel Fetchinson wrote: > I came across a javascript library that returns all sorts of html > codes in the cookies it sets and I need my web framework (written in > python :)) to decode them. I'm aware of htmlentitydefs but > htmlentitydefs.entitydefs.keys( ) are of the form '&#xxx' but this > javascript library uses stuff like '%3A' for the ':' for example. The > conversion is here: > > http://www.ascii.cl/htmlcodes.htm > > Is there a python package/module/whatever that does the conversion for > me or do I have to write a little wrapper myself (and introduce bugs > while doing so :))? >>> import urllib >>> urllib.quote("L?blich ?hnlich ?blich") 'L%C3%B6blich%20%C3%A4hnlich%20%C3%BCblich' >>> urllib.unquote(_) 'L\xc3\xb6blich \xc3\xa4hnlich \xc3\xbcblich' >>> print _ L?blich ?hnlich ?blich If you care about the encoding you have to encode/decode explicitly: >>> urllib.quote(u"L?blich ?hnlich ?blich".encode("latin1")) 'L%F6blich%20%E4hnlich%20%FCblich' >>> urllib.unquote(_).decode("latin1") u'L\xf6blich \xe4hnlich \xfcblich' Peter From peke at iki.fi Tue Dec 16 15:59:52 2008 From: peke at iki.fi (=?ISO-8859-1?Q?Pekka_Kl=E4rck?=) Date: Tue, 16 Dec 2008 22:59:52 +0200 Subject: Problem Python 2.6.1 vs 2.6 & pyWin32 In-Reply-To: <4946e680$0$9099$9b622d9e@news.freenet.de> References: <4946754f$0$19000$426a74cc@news.free.fr> <4946D09F.6050300@v.loewis.de> <4946e680$0$9099$9b622d9e@news.freenet.de> Message-ID: <7dedbb6d0812161259h2be0e421v8655f9a0ade57f61@mail.gmail.com> 2008/12/16 "Martin v. L?wis" : >>> Try installing Python 2.6.1 "for all users". >> >> Could you clarify why that's needed? > > I didn't say it's needed. I said that he should try that, perhaps it > helps. > >> One thing we noticed (I'm not sure has this been yet submitted to >> bugs.python.org yet) was that installing packages created with Python >> 2.5 to Python 2.6 failed unless Python was in %PATH% [1]. This must have actually been caused by the Python26.dll not being in PATH. Unfortunately I don't have all the details since these problems didn't bite me personally, but I assume this has been a single user installation. > In general, that's not supported at all. You will have to rebuild all > packages for Python 2.6, unless they are pure-python packages (in > which case PATH should be irrelevant). > > If the .pyd files would have loaded, Python would have complained that > they originate from the wrong Python version. The question was about a pure-python package. Based on my very limited knowledge on .pyd files they aren't related to the problem. >> Another pretty severe problem was that installers created with Python >> 2.6 didn't work at all with older versions [2]. > > That's not a bug, either. It has been that way since Python 1.4 or so: > .pyd files built for X.Y won't work for X.(Y+1), and vice versa. > > It seems that you mean something specific with the word "installer"; > I think you should elaborate what precisely you are referring to. Sorry for not being explicit. With "installer" I meant the binary Windows installer you create with command "python setup.py bdist_wininst". In the past we've been able to use "package-version.win32.exe" files created with Python 2.5 on older version, but that doesn't seem to be case with 2.6. Cheers, .peke From nick at craig-wood.com Thu Dec 11 08:30:53 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 11 Dec 2008 07:30:53 -0600 Subject: How do I manually uninstall setuptools (installed by egg)? References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> <47c890dc0812091904p12e75510sbe0b8858eb2f6d9e@mail.gmail.com> Message-ID: David Cournapeau wrote: > On Wed, Dec 10, 2008 at 12:04 PM, Chris Rebert wrote: > > On Tue, Dec 9, 2008 at 6:49 PM, wrote: > >> On Ubuntu, I accidentally manually installed setuptools > >> http://pypi.python.org/pypi/setuptools/0.6c9 (by running the .egg file > >> as a shell script via sudo), and now realize I should just be using > >> apt to take care of my system Python packages. > > > > Really, why? setuptools has more Python packages/programs available > > and updates faster than Debian. > > It's also likely that some of the Debian Python packages are installed > > using setuptools anyway. > > So, why do you think apt and not setuptools is The Right Way(tm)? > > Setuptools is certainly not the right way to install packages > system-wide on debian, it is very likely to break the whole thing. It wouldn't be too difficult to make a .deb target which would collect all the files that did get installed into a package. It would be a rather rough and ready package but would do the job. The .deb would then be uninstallable in the usual (dpkg --purge) way. Did anyone think about that? There is a bdist_rpm target for distutils which I often use then use alien to turn into a .deb. easy_install is a lot easier though! > dpkg is a real package installer, with uninstallation feature, correct > dependency handling: if you start installing things with setuptools > there, dpkg cannot know anymore how to manage your system. Agreed. > That's why it is generally a very bad idea to install things which > are not managed by dpkg in /usr - be it python or something else > BTW. It is a much better practice to install from source into > /usr/local, or your $HOME, etc... Anywhere which is not /usr. easy_install can do that I think... I find it odd that easy_install doesn't have a) a list what you installed with easy_install b) uninstall in an otherwise excellent program. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bj_666 at gmx.net Mon Dec 1 03:44:48 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Dec 2008 08:44:48 GMT Subject: pydoc enforcement. References: <6ccec696-a8bb-4818-a016-642514677b70@b38g2000prf.googlegroups.com> Message-ID: <6phmg0F82a0lU1@mid.uni-berlin.de> On Sun, 30 Nov 2008 16:27:07 -0800, ken.faulkner at gmail.com wrote: > Basically I'm interested adding a check to see if: > 1) pydoc's are written for every function/method. Pylint warns for missing docstrings. > 2) There are entries for each parameter, defined by some predetermined syntax. But which syntax? There are several in use out there. Even the (I think) popular epydoc allows at least three, its own, something JavaDoc like, and ReST. And I dislike forcing to document every parameter. There's lots of code that is clear just by the names of the parameters and one or two usage examples in the docs. Forcing to state the obvious again does not add information for the user and is annoying for the programmer. > My idea is that as much as I love dynamic typing, there are times when > using some modules/API's that have less than stellar documentation. I > was thinking that if it was possible to enable some switch that > basically forced compilation to fail if certain documentation criteria > weren't met. But that doesn't enforce good or even real documentation either. Even worse, you can't spot the undocumented parts of the code anymore, because now every "docable" object has "documentation" like this just to make the compiler happy: def spam(foo, bar): """ :param foo: a foo object. :param bar: a bar object. """ Which basically tells the same as no documentation at all. Ciao, Marc 'BlackJack' Rintsch From steve at REMOVE-THIS-cybersource.com.au Thu Dec 18 20:10:28 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2008 01:10:28 GMT Subject: Factoring Polynomials References: Message-ID: <015aebdf$0$20656$c3e8da3@news.astraweb.com> On Thu, 18 Dec 2008 11:37:35 -0800, collin.day.0 wrote: > I am trying to write a simple application to factor polynomials. I wrote > (simple) raw_input lines to collect the a, b, and c values from the > user, but I dont know how to implement the quadratic equation > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > into python. Any ideas? def quadratic_solution(a, b, c): sol1 = (-b + (b**2 - 4*a*c)**0.5)/2*a sol2 = (-b - (b**2 - 4*a*c)**0.5)/2*a return (sol1, sol2) Because this looks like homework, I've deliberately left in two errors in the above. One of them is duplicated in the two lines above the return, and you must fix it or you'll get radically wrong answers. The second is more subtle, and quite frankly if this is homework you could probably leave it in and probably not even lose marks. You will need to do significant research into numerical methods to learn what it is, but you will then get significantly more accurate results. -- Steven From w_a_x_man at yahoo.com Thu Dec 11 11:01:51 2008 From: w_a_x_man at yahoo.com (William James) Date: Thu, 11 Dec 2008 17:01:51 +0100 (CET) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> Message-ID: William James wrote: > John W Kennedy wrote: > > > Xah Lee wrote: > > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or > > > Java, you'll have 50 or hundreds lines. > > > > > Java: > > > > static float[] normal(final float[] x) { > > float sum = 0.0f; > > for (int i = 0; i < x.length; ++i) sum += x[i] * x[i]; > > final float divisor = (float) Math.sqrt(sum); > > float[] a = new float[x.length]; > > for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor; > > return a; > > } > > "We don't need no stinkin' loops!" > > SpiderMonkey Javascript: > > function normal( ary ) > { div=Math.sqrt(ary.map(function(x) x*x).reduce(function(a,b) a+b)) > return ary.map(function(x) x/div) > } The variable "div" shouldn't be global. function normal( ary ) { var div = Math.sqrt( ary.map(function(x) x*x).reduce(function(a,b) a+b) ) return ary.map(function(x) x/div) } From simonharrison.uk at googlemail.com Mon Dec 8 05:55:40 2008 From: simonharrison.uk at googlemail.com (simonharrison.uk at googlemail.com) Date: Mon, 8 Dec 2008 02:55:40 -0800 (PST) Subject: Determining whether a variable is less/greater than a range. References: <362ab93b-b804-4ebe-a22f-e422feb301c8@c1g2000yqg.googlegroups.com> Message-ID: Found it. min and max functions. I thought that this would be implemented as a list method: a.min a.max I can see that the built in functions make sense. From skip at pobox.com Sun Dec 21 14:53:06 2008 From: skip at pobox.com (skip at pobox.com) Date: Sun, 21 Dec 2008 13:53:06 -0600 Subject: Removing self. In-Reply-To: References: Message-ID: <18766.40610.916335.675493@montanaro-dyndns-org.local> r> I do not like self, and i lamented it from day one, now it is second r> nature to me but does that mean it is really needed?? I feel i have r> been brainwashed into its usage. ... r> 3000 would have been the perfect time to dump self and really clean up r> the language, and it's not too late, dawn is not upon us yet. Bruce Eckel proposes removing self from argument lists: http://www.artima.com/weblogs/viewpost.jsp?thread=239003 Guido responds: http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From gnewsg at gmail.com Tue Dec 16 13:36:45 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Tue, 16 Dec 2008 10:36:45 -0800 (PST) Subject: ethical questions about global variables References: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> <148d911b-5c43-48a1-baea-5a46c04cacfd@o4g2000pra.googlegroups.com> Message-ID: On 16 Dic, 18:01, ianar? wrote: > For anything more complicated than a simple script, I find it easier > to use some sort of config object. This could be a simple dictionnary > type class, where the values can be set/retrieved by the other classes > directly, or a more elaborate class including functions to set/ > retrieve the variables. This way setting/retrieving can be 'smart' -- > possibly looking at other variables, program states, thread count, > whatever, for the requested config option. It also allows for a lot of > expansion down the line if need be, rather than dealing with all sorts > of global variables floating around - which gets annoying pretty > quickly. > > On Dec 15, 9:45?pm, "Giampaolo Rodola'" wrote: > > > > > Hi, > > in a module of mine (ftpserver.py) I'd want to add a (boolean) global > > variable named "use_gmt_times" to decide whether the server has to > > return times in GMT or localtime but I'm not sure if it is a good idea > > because of the "ethical" doubts I'm gonna write below. > > > In first place I've never liked global variables too much and always > > preferred per-class-instance variables instead. > > The problem in my case is that I have to use such variable in two > > separated classes: FTPHandler and VirtualFileSystem. Also, I want that > > for no reason one class uses times in GMT and the other one local > > times. > > > Another doubt is the naming convention. PEP-8 states that global > > variables should use the lower_case_naming_convention but I've seen a > > lot of library module using the UPPER_CASE_NAMING_CONVENTION. What am > > I supposed to do about it? > > > Thanks in advance for any comment. > > > --- Giampaolohttp://code.google.com/p/pyftpdlib/- Nascondi testo citato > > - Mostra testo citato - All the modificable options the library has acquired so far consist of class attributes and I'm ok with that. The only option that should be global is "use_gmt_times" because it is supposed to be used in two classes and I want that both of them use the same parameter. Using a Config class for a single option like "use_gmt_times" is not worth the effort, IMO. --- Giampaolo http://code.google.com/p/pyftpdlib/ From prologic at shortcircuit.net.au Sun Dec 14 23:59:45 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 15 Dec 2008 14:59:45 +1000 Subject: Python is slow In-Reply-To: References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> Message-ID: On Mon, Dec 15, 2008 at 2:44 PM, Benjamin Kaplan wrote: > On Sun, Dec 14, 2008 at 11:38 PM, cm_gui wrote: >> >> hahaha, do you know how much money they are spending on hardware to >> make >> youtube.com fast??? > > Obviously not enough to get to the point where it's cheaper to have the > programmers write C code. And the hardware is more for handling the intense > traffic that YouTube gets, not for speeding up the site. Seriously cm_gui, you're a fool. Python is not slow. --JamesMills From marek at xivilization.net Sun Dec 28 07:55:49 2008 From: marek at xivilization.net (Marek Kubica) Date: Sun, 28 Dec 2008 12:55:49 +0000 (UTC) Subject: What is site-packages? References: Message-ID: On Sun, 28 Dec 2008 04:06:36 -0800, Hussein B wrote: > You mean like MoinMoin, Django or Pylons for example? Yes. Or lxml, BeautifulSoup, psycopg2 and basically anything that is available on PyPI. regards, Marek From tjreedy at udel.edu Mon Dec 29 14:20:38 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Dec 2008 14:20:38 -0500 Subject: Get a list of functions in a file In-Reply-To: References: Message-ID: member Basu wrote: > I'm putting some utility functions in a file and then building a simple > shell interface to them. Is their some way I can automatically get a > list of all the functions in the file? I could wrap them in a class and > then use attributes, but I'd rather leave them as simple functions. Lets assume that either 1) You only define functions (bind function names) in the module, or 2) You start any other top-level names with '_' so that they do not get imported. import utilfuncs funcs = vars(utilfuncs) # dict of name:func pairs names = funcs.keys() # display names and ask user to select 'inputname' # then, assuming no args output = funcs[inputname]() tjr From manishsinha.tech at gmail.com Sun Dec 28 13:22:01 2008 From: manishsinha.tech at gmail.com (Manish Sinha) Date: Sun, 28 Dec 2008 23:52:01 +0530 Subject: "return" in def In-Reply-To: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> Message-ID: <4957C3C9.40205@gmail.com> Roger wrote: > Hi Everyone, > > First I want to thank everyone that posts to this group. I read it > daily and always learn something new even if I never feel like I have > anything to contribute but my questions. > Same here, I always read the news, but hardly post anything since am not very much expert in Python. > Even when I'm not explicitly returning something I like to add > "return" because it's a good additional visual marker for me to see > where a method definition ends especially in cases where I may use a > nested method. > I would personally prefer to use a comment for return rather than giving an explicit return statement. e.g. # return from function -- Manish Sinha Personal Blog: http://www.manishsinha.info Tech Blog: http://manishtech.wordpress.com OpenPGP Key: 99E6658F From python at bdurham.com Wed Dec 24 04:08:36 2008 From: python at bdurham.com (python at bdurham.com) Date: Wed, 24 Dec 2008 04:08:36 -0500 Subject: Strategy for determing difference between 2 very large dictionaries In-Reply-To: <1230109636.18987.1291625111@webmail.messagingengine.com> References: <1230102996.2303.1291616055@webmail.messagingengine.com> <6rea9hF16p8tU1@mid.uni-berlin.de> <3Qm4l.11404$c45.9406@nlpi065.nbdc.sbc.com> <1230109636.18987.1291625111@webmail.messagingengine.com> Message-ID: <1230109716.19049.1291625225@webmail.messagingengine.com> Hi James, > For the purpose of perpetuating the annoying pedantry that has made > usenet great: > > http://docs.python.org/dev/3.0/whatsnew/3.0.html#views-and-iterators-instead-of-lists Great tip! Thank you! Malcolm From gudonghua at gmail.com Thu Dec 11 21:38:03 2008 From: gudonghua at gmail.com (gudonghua+python@gmail.com) Date: Thu, 11 Dec 2008 18:38:03 -0800 (PST) Subject: Rename of .mdb file -- lock References: <4049f296-2a04-4eee-9f09-aa37a973a8cf@r40g2000yqj.googlegroups.com> Message-ID: <8792708a-51c9-4fa6-b39d-4808ed1ffaed@t39g2000prh.googlegroups.com> On Dec 12, 10:15?am, noydb wrote: > All, > > I have the code below, which unzips a zipfile containing only one > file. ?Once it is unzipped, I want to rename the file based on a user > provided name. ?But I get this (WindowsError: [Error 32] The process > cannot access the file because it is being used by another process) > error, which does not make sense to me as no other apps are open. > > Any suggestions? > > Thanks! > > ****CODE**** > # Declare the zip file directory and name (shouldn't change, in a > permanent location) > mdb_zip = ("C:\\ProjWork\\mdb_geoDB_91.zip") > > output_dir = ("C:\\Temp") > > # ZipFile for read > z = zipfile.ZipFile(mdb_zip, 'r') > zFile = z.namelist() > > # Put contents of zipfile into a list > zList = z.namelist() > > # Loop thru list, write zipfile contents to new directory > for zItem in zList: > ? ? print "Unpacking",zItem > ? ? zRead = z.read(zItem) > ? ? z1File = open(os.path.join(output_dir, zItem),'wb') > ? ? z1File.write(zRead) > ? ? z1File.close z1File.close() > print "Finished extracting zip file" > > uChoice = "test44.mdb" ## to be user chosen someday > new91mdb = os.path.join(output_dir, zItem) # C:\TEMP\GDB_9_1.mdb > > ##os.rename(new91mdb, (os.path.join(output_dir, uChoice))) > os.rename(new91mdb, (os.path.join(output_dir, "C:\TEMP\test1.mdb"))) > > del new91mdb From patrick.waldo at gmail.com Thu Dec 4 10:57:49 2008 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Thu, 4 Dec 2008 07:57:49 -0800 (PST) Subject: UnicodeDecodeError quick question Message-ID: <6858147d-a213-45ef-9564-bff220688881@e1g2000pra.googlegroups.com> Hi Everyone, I am using Python 2.4 and I am converting an excel spreadsheet to a pipe delimited text file and some of the cells contain utf-8 characters. I solved this problem in a very unintuitive way and I wanted to ask why. If I do, csvfile.write(cell.encode("utf-8")) I get a UnicodeDecodeError. However if I do, c = unicode(cell.encode("utf-8"),"utf-8") csvfile.write(c) Why should I have to encode the cell to utf-8 and then make it unicode in order to write to a text file? Is there a more intuitive way to get around these bothersome unicode errors? Thanks for any advice, Patrick Code: # -*- coding: utf-8 -*- import xlrd,codecs,os xls_file = "/home/pwaldo2/work/docpool_plone/2008-12-4/ EU-2008-12-4.xls" book = xlrd.open_workbook(xls_file) bibliography_sheet = book.sheet_by_index(0) csv = os.path.split(xls_file)[0] + '/' + os.path.split(xls_file)[1] [:-4] + '.csv' csvfile = codecs.open(csv,'w',encoding='utf-8') rowcount = 0 data = [] while rowcount References: <6e24be88-b042-425b-b880-c97d184fee07@s20g2000yqh.googlegroups.com> Message-ID: <47c890dc0812040942k770a8da1jb21cfb012276b23b@mail.gmail.com> On Thu, Dec 4, 2008 at 8:57 AM, Cro wrote: >> Do you really mean io.StringIO? I guess you want io.BytesIO() .. >> >> Christian > > Mmm... i don't know. > I also tried : > > [code] > IDLE 3.0 >>>> import io >>>> vContent = io.BytesIO() You do realize that the previous line is completely pointless, right? Later you rebind vContent to the results of huge.read() without ever having used it between that line and the above line. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com >>>> huge = io.open("C:\HUGE_FILE.pcl",'r+b',0) >>>> vContent = huge.read() > [/code] > > It still waits a lot... i don't have the patience to wait for the file > to load completely... it takes a lot! > > Thank you for your reply. > -- > http://mail.python.org/mailman/listinfo/python-list > From debl2NoSpam at verizon.net Fri Dec 19 18:03:39 2008 From: debl2NoSpam at verizon.net (David Lees) Date: Fri, 19 Dec 2008 23:03:39 GMT Subject: Very Slow PythonWin 2.6.1 Startup on Windows XP SP3 In-Reply-To: References: <_PG2l.570$P5.31@nwrddc02.gnilink.net> Message-ID: Allan wrote: > David Lees writes: > >> PythonWin used to startup in a second or two on my Windows XP >> desktop. now it takes around 20 seconds. I tried turning off Google >> Desktop indexing and Norton AV, but it still takes a long time to >> start. Other random apps such as Firefox 3.0 (which I just updated >> to) and Thunderbird have normal startup times. > What happens if you just open a Python command window; is it much > faster? On my computer which is seven years old (HP Pavilion desktop, > 512 MB RAM) it takes less than ten seconds for PythonWin to open. You > might try reinstalling PythonWin. > I just uninstalled all copies of Python from my system(2.5, 2.6 and 3.0), along with their corresponding PythonWin. Then I downloaded and installed Python 2.6.1 and PythonWin build 212. Now Python starts up nearly instantly. Thanks for the suggestion. David From arne at vajhoej.dk Wed Dec 10 18:44:51 2008 From: arne at vajhoej.dk (=?UTF-8?B?QXJuZSBWYWpow7hq?=) Date: Wed, 10 Dec 2008 18:44:51 -0500 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <20081226055859.604@gmail.com> Message-ID: <49405469$0$90262$14726298@news.sunsite.dk> Jon Harrop wrote: > Xah Lee wrote: >> Kaz Kylheku wrote: >>> Really? ``50 or hundreds'' of lines in C? >>> >>> #include /* for sqrt */ >>> >>> void normalize(double *out, double *in) >>> { >>> double denom = sqrt(in[0] * in[0] + in[1] * in[1] + in[2] * >>> in[2]); >>> >>> out[0] = in[0]/denom; >>> out[1] = in[1]/denom; >>> out[2] = in[2]/denom; >>> } >>> >>> Doh? >> Kaz, pay attention: >> >> Xah wrote: ?Note, that the ?norm? as defined above works for vectors >> of any dimention, i.e. list of any length.? > > That is still only 6 lines of C code and not 50 as you claimed: > > double il = 0.0; > for (int i=0; i il += in[i] * in[i]; > il = 1.0 / sqrt(il); > for (int i=0; i out[i] = il * in[i]; Not that it matters, but the above requires C99 (or C++). Arne From steve at REMOVE-THIS-cybersource.com.au Mon Dec 15 01:09:02 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Dec 2008 06:09:02 GMT Subject: [OT] stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> Message-ID: <0155ebf4$0$6988$c3e8da3@news.astraweb.com> On Sun, 14 Dec 2008 21:18:03 -0500, Roy Smith wrote: > Steven D'Aprano wrote: > >> All the positive thinking in the world won't help you: >> >> * make a four-sided triangle; >> >> * split a magnet into two individual poles; > > These two are fundamentally different problems. > > The first is impossible by definition. The definition of triangle is, > "a three-sided polygon". Asking for a "four-sided triangle" is akin to > asking for "a value of three which is equal to four". That's right. But see below. > The second is only "impossible" because it contradicts our understanding > (based on observation) of how the physical universe works. Our > understanding could simply be wrong. And arithmetic could be inconsistent, in which case it might be possible to prove that 3 equals 4. We don't know for sure that arithmetic is consistent, and according to Godel, there is no way of proving that it is consistent. There's no evidence that it isn't, but then, unless the inconsistency was obvious, how would we know? http://www.mathpages.com/home/kmath347/kmath347.htm > We've certainly been wrong before, > and we will undoubtedly be proven wrong again in the future. When it > comes to things like electromagnetic theory, it doesn't take too many > steps to get us to the fuzzy edge of quantum physics where we know there > are huge questions yet to be answered. No. I worded my question very carefully. The discovery of magnetic monopoles, as predicted by the fuzzy end of quantum physics, would not invalidate my claim. Magnets don't generate magnetic fields by the use of monopoles, and the discovery of such wouldn't make it possible to cut an ordinary magnet in two to get an individual north and south pole. That would like taking a rope with two ends (an ordinary rope, in other words), cut it in half, and finding that each piece has only a single end. Now, you could counter with a clever solution involving splicing the rope to itself in such a way that it had one end and a loop at the other, er, end. And such a solution might be very valuable, if we needed a way to get a rope with a loop at one end. But it isn't solving the problem of cutting a rope in two and getting only two ends instead of four. It's solving a different problem. -- Steven From renesd at gmail.com Thu Dec 4 20:45:49 2008 From: renesd at gmail.com (illume) Date: Thu, 4 Dec 2008 17:45:49 -0800 (PST) Subject: Python 3.0 C API migration tools, or docs? Message-ID: <008877d2-8705-48a6-bb09-6c31c6b77970@p2g2000prf.googlegroups.com> Hi, are there migration tools for C API migration to python 3? I'm sure there must be some code somewhere to help change stuff over right? I don't see any docs for migrating code from 2.x to 3.x either: http://docs.python.org/3.0/c-api/index.html Help needed with this! cheers, From soid.exe at gmail.com Sun Dec 28 15:38:22 2008 From: soid.exe at gmail.com (Grigory Temchenko) Date: Sun, 28 Dec 2008 12:38:22 -0800 (PST) Subject: A form validation library with javascript validation Message-ID: <9d342005-90e4-4fec-8f16-a52c744f0fc0@d36g2000prf.googlegroups.com> Hey everyone, Can someone advice me a beautiful or just cool library for form validation with javascript supporting? From tmh.public at gmail.com Wed Dec 3 17:12:51 2008 From: tmh.public at gmail.com (Thomas M. Hermann) Date: Wed, 3 Dec 2008 14:12:51 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> Message-ID: On Dec 3, 3:15?pm, Xah Lee wrote: > On Dec 3, 8:24 am, Jon Harrop wrote: > > > My example demonstrates several of Mathematica's fundamental limitations. > > enough babble Jon. > > Come flying $5 to my paypal account, and i'll give you real code, > amongest the programing tech geekers here for all to see. > > I'll show, what kinda garbage you cooked up in your Mathematica code > for ?comparison?. > > You can actually just post your ?comparisons? to ?comp.soft- > sys.math.mathematica?, and you'll be ridiculed to death for any > reasonable judgement of claim on fairness. > > > Consequently, there is great value in combining Mathematica with performant > > high-level languages like OCaml and F#. This is what the vast majority of > > Mathematica users do: they use it as a glorified graph plotter. > > glorified your ass. > > Yeah, NASA, Intel, NSA, ... all use Mathematica to glorify their > pictures. LOL. > > > What exactly do you believe is wrong with my code? > > come flies $5 to my paypal, and i'll explain further. > > > I am not trying to make Mathematica look bad. It is simply not suitable when > > hierarchical solutions are preferable... > > Certainly there are areas other langs are more suitable and better > than Mathematica (for example: assembly langs). But not in the ways > you painted it to peddle your F# and OCaml books. > > You see Jon, you are this defensive, trollish guy, who takes every > opportunity to slight other langs that's not one of your F#, OCml that > you make a living of. In every opportunity, you injest your gribes > about static typing and other things, and thru ensuring chaos paves > the way for you to post urls to your website. > > With your math and functional programing expertise and Doctor label, > it can be quite intimidating to many geekers. But when you bump into > me, i don't think you have a chance. > > As a scientist, i think perhaps you should check your newsgroup > demeanor a bit? I mean, you already have a reputation of being biased. > Too much bias and peddling can be detrimental to your career, y'known? > > to be sure, i still respect your expertise and in general think that a > significant percentage of tech geeker's posts in debate with you are > moronic, especially the Common Moron Lispers, and undoubtably the Java > and imperative lang slaving morons who can't grope the simplest > mathematical concepts. Throwing your Mathematica bad mouthing at me > would be a mistake. > > Come, fly $5 to my paypal account. Let the challenge begin. > > ? Xah > ?http://xahlee.org/ > > ? Xah, I'll pay $20 to see your improved version of the code. The only references to PayPal I saw on your website were instructions to direct the payment to xah at xahlee.org, please let me know if that is correct. What I want in return is you to execute and time Dr. Harrop's original code, posting the results to this thread. Then, I would like you to post your code with the timing results to this thread as well. By Dr. Harrop's original code, I specifically mean the code he posted to this thread. I've pasted it below for clarity. Jon Harrop coded a ray tracer in Mathematica: > delta = Sqrt[$MachineEpsilon]; > > RaySphere[o_, d_, c_, r_] := > Block[{v, b, disc, t1, t2}, > v = c - o; > b = v.d; > disc = Sqrt[b^2 - v.v + r^2]; > t2 = b + disc; > If[Im[disc] != 0 || t2 <= 0, \[Infinity], > t1 = b - disc; > If[t1 > 0, t1, t2]] > ] > > Intersect[o_, d_][{lambda_, n_}, Sphere[c_, r_]] := > Block[{lambda2 = RaySphere[o, d, c, r]}, > If[lambda2 >= lambda, {lambda, n}, {lambda2, > Normalize[o + lambda2 d - c]}] > ] > Intersect[o_, d_][{lambda_, n_}, Bound[c_, r_, s_]] := > Block[{lambda2 = RaySphere[o, d, c, r]}, > If[lambda2 >= lambda, {lambda, n}, > Fold[Intersect[o, d], {lambda, n}, s]] > ] > > neglight = N at Normalize[{1, 3, -2}]; > > nohit = {\[Infinity], {0, 0, 0}}; > > RayTrace[o_, d_, scene_] := > Block[{lambda, n, g, p}, > {lambda, n} = Intersect[o, d][nohit, scene]; > If[lambda == \[Infinity], 0, > g = n.neglight; > If[g <= 0, 0, > {lambda, n} = > Intersect[o + lambda d + delta n, neglight][nohit, scene]; > If[lambda < \[Infinity], 0, g]]] > ] > > Create[level_, c_, r_] := > Block[{obj = Sphere[c, r]}, > If[level == 1, obj, > Block[{a = 3*r/Sqrt[12], Aux}, > Aux[x1_, z1_] := Create[level - 1, c + {x1, a, z1}, 0.5 r]; > Bound[c, > 3 r, {obj, Aux[-a, -a], Aux[a, -a], Aux[-a, a], Aux[a, a]}]]]] > > scene = Create[1, {0, -1, 4}, 1]; > > Main[level_, n_, ss_] := > Block[{scene = Create[level, {0, -1, 4}, 1]}, > Table[ > Sum[ > RayTrace[{0, 0, 0}, > N at Normalize[{(x + s/ss/ss)/n - 1/2, (y + Mod[s, ss]/ss)/n - 1/2, > 1}], scene], {s, 0, ss^2 - 1}]/ss^2, {y, 0, n - 1}, > {x, 0, n - 1}]] > > AbsoluteTiming[Export["image.pgm", Graphics at Raster@Main[9, 512, 4]]] > From wuwei23 at gmail.com Wed Dec 3 20:58:16 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 3 Dec 2008 17:58:16 -0800 (PST) Subject: RELEASED Python 3.0 final References: Message-ID: On Dec 4, 11:51?am, Barry Warsaw wrote: > On behalf of the Python development team and the Python community, I ? > am happy to announce the release of Python 3.0 final. Thanks to you and everyone involved for your efforts! From google at mrabarnett.plus.com Tue Dec 16 14:00:20 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 16 Dec 2008 19:00:20 +0000 Subject: sorting for recursive folder rename In-Reply-To: References: Message-ID: <4947FAC4.3040203@mrabarnett.plus.com> ianar? wrote: > Hello all, > > I trying to recursively rename folders and files, and am looking for > some ideas on the best way of doing this. The problem is that the > given list of items can be in order, and one to all items may be > renamed. Here is some preliminary code I have, but which does not work > very well. > > self.toRename has the following structure : > [ > [original_name, new_name, os.path.isdir] > .. > ] > > # define these here for faster processing > def split(item): > return os.path.split(item) > def addSep(path): > return os.sep + path + os.sep > def recursiveFolderSort(x,y): > return cmp(y[0], x[0]) > > sortedRename = sorted(self.toRename) > > # make a list of all folders that will be processed > foldersToAdjust = [] > for item in sortedRename: > if item[2] is False: if not item[2]: > oF = split(item[0])[1] # original folder name > nF = split(item[1])[1] # new folder name > if oF is not nF: if oF != nF: > foldersToAdjust.append((oF, nF)) > > # replace all occurences of folders in path > for i in range(len(self.toRename)): > for f in foldersToAdjust: > oF = addSep(f[0]) # original folder name > nF = addSep(f[1]) # new folder name > self.toRename[i][0] = self.toRename[i][0].replace(oF,nF) > self.toRename[i][1] = self.toRename[i][1].replace(oF,nF) > > if progressDialog.update(i) is False: if not progressDialog.update(i): > error = 'cancelled' > break > > # make sure renaming will be in correct order ! > self.toRename.sort(recursiveFolderSort) > > > > First problem is adjusting the paths can take a very long time. > Second problem is sorting is not always right and files get lost !! > Any input welcome. > You should use "is" and "is not" _only_ when checking for _identity, ie are these 2 both references to the _same_ object. Most of the time that would be "x is None" or "x is not None". From saluk64007 at gmail.com Sat Dec 6 01:47:50 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Fri, 5 Dec 2008 22:47:50 -0800 Subject: Guido's new method definition idea In-Reply-To: <014a071a$0$20670$c3e8da3@news.astraweb.com> References: <014a071a$0$20670$c3e8da3@news.astraweb.com> Message-ID: >> Daniel Fetchinson wrote: >>> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to- > stay.html >>> >>> The proposal is to allow this: >>> >>> class C: >>> def self.method( arg ): >>> self.value = arg >>> return self.value >>> >>> instead of this: >>> >>> class C: >>> def method( self, arg ): >>> self.value = arg >>> return self.value >>> I'd like this new way of defining methods, what do you guys think? I don't really like the proposed syntax any better than the old syntax. I certainly wouldn't use "def self." in any of my old code. I doubt I would use it in a new project were I to have the choice either. However, I don't really have a problem with other people liking it. the symetry of "def self.func(blah)==def func(self,blah)" and "ob.func(blah)==func(ob.blah)" is kind of neat. Could I do something like this: def a.add(b): return a+b Outside of a class? Of course then that makes you think you could do 5.add(6) or something craaaazy like that. (I mean, you can do (5).__add__(6) but that's something else entirely) From xahlee at gmail.com Thu Dec 4 20:02:59 2008 From: xahlee at gmail.com (Xah Lee) Date: Thu, 4 Dec 2008 17:02:59 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: alright, here's my improved code, pasted near the bottom. let me say a few things about Jon's code. If we rate that piece of mathematica code on the level of: Beginner Mathematica programer, Intermediate, Advanced, where Beginner is someone who just learned tried to program Mathematica no more than 6 months, then that piece of code is Beginner level. Here's some basic analysis and explanation. The program has these main functions: ? RaySphere ? Intersect ? RayTrace ? Create ? Main The Main calls Create then feed it to RayTrace. Create calls itself recursively, and basically returns a long list of a repeating element, each of the element differ in their parameter. RayTrace calls Intersect 2 times. Intersect has 2 forms, one of them calls itself recursively. Both forms calls RaySphere once. So, the core loop is with the Intersect function and RaySphere. Some 99.99% of time are spent there. ------------------ I didn't realize until after a hour, that if Jon simply give numerical arguments to Main and Create, the result timing by a factor of 0.3 of original. What a incredible sloppiness! and he intended this to show Mathematica speed with this code? The Main[] function calls Create. The create has 3 parameters: level, c, and r. The level is a integer for the recursive level of raytracing . The c is a vector for sphere center i presume. The r is radius of the sphere. His input has c and r as integers, and this in Mathematica means computation with exact arithmetics (and automatic kicks into infinite precision if necessary). Changing c and r to float immediately reduced the timing to 0.3 of original. ------------------ now, back to the core loop. The RaySphere function contain codes that does symbolic computation by calling Im, which is the imaginary part of a complex number!! and if so, it returns the symbol Infinity! The possible result of Infinity is significant because it is used in Intersect to do a numerical comparison in a If statement. So, here in these deep loops, Mathematica's symbolic computation is used for numerical purposes! So, first optimization at the superficial code form level is to get rid of this symbolic computation. Instead of checking whethere his ?disc = Sqrt[b^2 - v.v + r^2]? has imaginary part, one simply check whether the argument to sqrt is negative. after getting rid of the symbolic computation, i made the RaySphere function to be a Compiled function. I stopped my optimization at this step. The above are some _fundamental_ things any dummy who claims to code Mathematica for speed should know. Jon has written a time series Mathematica package that he's selling commercially. So, either he got very sloppy with this Mathematica code, or he intentionally made it look bad, or that his Mathematica skill is truely beginner level. Yet he dares to talk bullshit in this thread. Besides the above basic things, there are several aspects that his code can improve in speed. For example, he used pattern matching to do core loops. e.g. Intersect[o_, d_][{lambda_, n_}, Bound[c_, r_, s_]] any Mathematica expert knows that this is something you don't want to do if it is used in a core loop. Instead of pattern matching, one can change the form to Function and it'll speed up. Also, he used ?Block?, which is designed for local variables and the scope is dynamic scope. However the local vars used in this are local constants. A proper code would use ?With? instead. (in lisp, this is various let, let*. Lispers here can imagine how lousy the code is now.) Here's a improved code. The timing of this code is about 0.2 of the original. Also, optimization is purely based on code doodling. That is, i do not know what his code is doing, i do not have experience in writing a ray tracer. All i did is eyeballing his code flow, and improved the form. norm=Function[#/Sqrt@(Plus@@(#^2))]; delta=Sqrt[$MachineEpsilon]; myInfinity=10000.; Clear[RaySphere]; RaySphere = Compile[{o1, o2, o3, d1, d2, d3, c1, c2, c3, r}, Block[{v = {c1 - o1, c2 - o2, c3 - o3}, b = d1*(c1 - o1) + d2*(c2 - o2) + d3*(c3 - o3), discriminant = -(c1 - o1)^2 - (c2 - o2)^2 + (d1*(c1 - o1) + d2*(c2 - o2) + d3*(c3 - o3))^2 - (c3 - o3)^2 + r^2, disc, t1, t2}, If[discriminant < 0., myInfinity, disc = Sqrt[discriminant]; If[(t1 = b - disc) > 0., t1, If[(t2 = b + disc) <= 0., myInfinity, t2]]]]]; Remove[Intersect]; Intersect[{o1_,o2_,o3_},{d1_,d2_,d3_}][{lambda_,n_},Sphere [{c1_,c2_,c3_},r_]]:= Block[{lambda2=RaySphere[o1,o2,o3,d1,d2,d3,c1,c2,c3,r]}, If[lambda2?lambda,{lambda,n},{lambda2, norm[{o1,o2,o3}+lambda2 *{d1,d2,d3}-{c1,c2,c3}]}]] Intersect[{o1_,o2_,o3_},{d1_,d2_,d3_}][{lambda_,n_}, Bound[{c1_,c2_,c3_},r_,s_]]:= Block[{lambda2=RaySphere[o1,o2,o3,d1,d2,d3,c1,c2,c3,r]}, If[lambda2?lambda,{lambda,n}, Fold[Intersect[{o1,o2,o3},{d1,d2,d3}],{lambda,n},s]]] Clear[neglight,nohit] neglight=N at norm[{1,3,-2}]; nohit={myInfinity,{0.,0.,0.}}; Clear[RayTrace]; RayTrace[o_,d_,scene_]:= Block[{lambda,n,g,p},{lambda,n}=Intersect[o,d][nohit,scene]; If[lambda\[Equal]myInfinity,0,g=n.neglight; If[g?0, 0,{lambda,n}=Intersect[o+lambda d+delta n,neglight] [nohit,scene]; If[lambda Message-ID: En Sat, 27 Dec 2008 22:54:52 -0200, Daniel Fetchinson escribi?: > This is the function I have, the corresponding python function will > take two equal length lists of integers and the C function will > compute their sum and return the result as a python tuple. > > > static PyObject *func( PyObject * self, PyObject * args ) > { > int j, N; > int * src1, * src2; > PyObject *list1, *list2; > > list1 = PyTuple_GetItem( args, 0 ); > N = PyList_Size( list1 ); > src1 = ( int * ) malloc( N * sizeof( int ) ); > for( j = 0; j < N; j++ ) > { > src1[j] = (int)PyInt_AsLong( PyList_GetItem( list1, j ) ); > } > > list2 = PyTuple_GetItem( args, 1 ); > N = PyList_Size( list2 ); > src2 = ( int * ) malloc( N * sizeof( int ) ); > for( j = 0; j < N; j++ ) > { > src2[j] = (int)PyInt_AsLong( PyList_GetItem( list2, j ) ); > } > > PyObject * tuple; > tuple = PyTuple_New( N ); > for( j = 0; j < N; j++ ) > { > PyTuple_SetItem( tuple, j, PyInt_FromLong( (long)( src1[j] + > src2[j] ) ) ); > } > > free( src1 ); > free( src2 ); > > return tuple; > } As others already said, using a Numpy array or an array.array object would be more efficient (and even easier - the C code gets a pointer to an array of integers, as usual). > Do I have to free the memory occupied by the python objects list1 and > list2? No. Usually you don't do that for any Python object - just increment/decrement its reference count (using Py_INCREF/Py_DECREF). > Do I have to do any refcounting for list1, list2, tuple? In this case list1 and list2 come from PyTuple_GetItem; the docs say it returns a "borrowed reference" (that is, the function doesn't increment the refcount itself). So you don't have to decrement it yourself (and it isn't necesary to increment it in the first place, because the "args" tuple holds a reference, so the object can't disappear until the function exits, at least) > Any comment on the above code will be very appreciated! If I'm pushed > in the right direction I'm a fast learner but the beginning steps are > always hard :) You MUST check EVERY function call for errors! And check the argument's type (how do you know it is a list?). Once you are sure the first parameter *is* a list, you may use the "macro" version of several functions, like PyList_GET_SIZE and PyList_GET_ITEM. You should check that both lists have the same length too. And you should check that elements are integers, or convertible to integers (in case of error, PyInt_AsLong returns -1 and PyErr_Occurred() is true) To fill the resulting tuple, use PyTuple_SET_ITEM instead. BTW, why return a tuple and not a list? -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Fri Dec 12 07:10:47 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Dec 2008 12:10:47 GMT Subject: (Very Newbie) Problems defining a variable References: <49425146$0$8495$426a74cc@news.free.fr> <11c53a4a-de1e-4bee-ad60-a05befb6cbf4@a12g2000yqm.googlegroups.com> Message-ID: <01524c52$0$20617$c3e8da3@news.astraweb.com> On Fri, 12 Dec 2008 04:05:21 -0800, feba wrote: > that's it, thanks! was confused with it being basically in a column of > all >= *. > > I replaced it with > > if bank <= 0: > print("You're in the red!") > quit() > elif bank >= 1 and bank <= 9999: > rate = 0.0060 You can replace this with the simpler, easier to read and faster: elif 1 <= bank <= 9999: rate = 0.0060 elif 10000 <= bank <= 24999: rate = 0.0085 ... > elif bank >= 100000: > rate = 0.0173 > else: > print("What's this doing here?") Change the last two else clauses to this one: else: rate = 0.0173 -- Steven From __peter__ at web.de Mon Dec 1 16:25:30 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 01 Dec 2008 22:25:30 +0100 Subject: Is it safe to modify the dict returned by vars() or locals() References: <4934508b$0$2861$ba620e4c@news.skynet.be> Message-ID: Helmut Jarausch wrote: > I am looking for an elegant way to solve the following problem: > > Within a function > > def Foo(**parms) > > I have a list of names, say VList=['A','B','C1'] > and I like to generate abbreviation > _A identical to parms['A'] > > for that I could write > > def Foo(**parms) : > for N in VList : > if N in parms : > vars()[N]= parms[N] > else : > vars()[N]= None > > Does this work, is it typical Python? locals() gives you a copy of the local namespace. No changes to the copy are written back to that namespace. In idiomatic python you'd just use the dictionary. If you are bothered with the non-existent keys, make a copy >>> parms = dict(a=1, c=3) >>> p = dict.fromkeys(["a", "b", "c"]) >>> p.update(parms) >>> p["a"], p["b"], p["c"] (1, None, 3) >>> p["x"] Traceback (most recent call last): File "", line 1, in KeyError: 'x' or, setting any non-existent key to None: >>> from collections import defaultdict >>> parms = dict(a=1, c=3) >>> p = defaultdict(lambda: None) >>> p.update(parms) >>> p["a"], p["b"], p["c"] (1, None, 3) If you insist on manipulating the namespace you can use exec: >>> def foo(**parms): ... exec "\n".join("%s = parms.get(%r)" % (n, n) for n in ["a", "b", "c"]) ... return a, b, c ... >>> foo(a=1, c=3) (1, None, 3) >>> foo(b=20) (None, 20, None) Peter From arkanes at gmail.com Thu Dec 4 14:34:26 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 4 Dec 2008 13:34:26 -0600 Subject: To Troll or Not To Troll In-Reply-To: <896B75251BA19745A529B1B867893FA50679CE@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA50679CE@planet.delsci.local> Message-ID: <4866bea60812041134t42b7aca5j7b50d06094280240@mail.gmail.com> On Thu, Dec 4, 2008 at 1:10 PM, Warren DeLano wrote: >> Yet Another Python Troll (the ivory tower reference, as well as the >> abrupt shift from complaining about keywords to multiprocessing), I >> have to point out that Python does add new keywords, it has done so in >> the past, and there was a considerable amount of warning, including an >> automated deprecation warning in the very version you are going to >> recommend to your "customers' (I don't actually think you have any >> customers). > > ROFL! I'm sorry, you're right -- this has all been a figment of my > imagination... > > http://www.pymolwiki.org/index.php/Covers > > http://images.google.com/images?q=pymol > > So don't mind me -- I clearly don't know what I'm talking about. > Peculiarities in usenet resulted in this discussion having several threads and I missed some messages before I wrote this email. So I apologize for calling you a troll, but only slightly - what you wrote had exactly the same content and tone that people who are intentionally trolling write every day. There are legitimate, interesting, and important discussions to be had about multithreading in Python, but nothing you wrote was of any use to any of them. I still would have to call your management of the problem considerably into question - your expertise at writing mathematical software may not be in question, but your skills and producing and managing a software product are. You have nobody at your organization, which sells a product that relies on Python, who follows python-dev? Or who even reads the changelogs for new python versions? You should have known about the "as" keyword change *over a year ago*, even if the import bug was masking the deprecation warning. Everything else aside, I can't get past that issue with your complaints. I *have* gone back now and read all the posts in all the threads and I still have not seen a single post from you even hinting that you might have any responsibility in the matter. Multithreading is a different discussion, and totally unrelated to the original complaint (which is why it's trolling, customers or not, to bring it up in this thread) and I'm not going to address it - everything of any interest in the conversation has been said already, and if you know enough to talk seriously about it you already know all the arguments on both sides. If you *don't* know them, a perusal of the python-dev and c.l.p archives should bring you up to speed easily. From pavlovevidence at gmail.com Sat Dec 6 15:13:16 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 6 Dec 2008 12:13:16 -0800 (PST) Subject: "as" keyword woes References: Message-ID: On Dec 6, 1:38?pm, "Warren DeLano" wrote: > There, I assert that 'object.as(class_reference)' is the simplest and > most elegant generalization of this widely-used convention. ?Indeed, it > is the only obvious concise answer, if you are limited to using methods > for casting. I don't agree with your assertion. object.as_type(class_reference) object.cast(class_reference) These are both concise and obvious. > As someone somewhat knowledgable of how parsers work, I do not > understand why a method/attribute name "object_name.as(...)" must > necessarily conflict with a standalone keyword " as ". ?It seems to me > that it should be possible to unambiguously separate the two without > ambiguity or undue complication of the parser. It's possible, and they've been doing it for years, and they could have continued doing it if they wanted to. You'll notice that nowhere the Python grammar can two identifiers be separated by whitespace. So if you have two identifiers separated by whitespace, and the second one is "as", you know it has to be keyword "as". Well, they made it a keyword anyway. It was never a question of whether they could do it. > So, assuming I now wish to propose a corrective PEP to remedy this > situation for Python 3.1 and beyond, what is the best way to get started > on such a proposal? ? I think you'd be wasting your time, but the general procedure is outlined in PEP 1. Basically, you write a pre-PEP (aka PEP XXX) according to the guidelines in PEP 1, which you would post here and request comments on it. Then, if you can muster some support for it, you would send it to PEP maintainer (the email is listed somewhere on the PEPs page, dig for it), and get a number assigned, upon which time Guido van Rossum will read it and any comments in python-dev, and make a pronouncement of some sort. If you write a PEP, I advise you to try to sound less whiny and than you have in this thread. Saying "object.as(class_reference) is highly convenient because it mirrors textually the Java convention of object.asFloat" will go over a lot better than "object.as (class_reference) is the only obvious concise answer". Carl Banks From martin at v.loewis.de Fri Dec 5 19:26:37 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 06 Dec 2008 01:26:37 +0100 Subject: Running Python 2 and Python 3 on the same machine In-Reply-To: References: <1228424486.5873.6.camel@linux-3eb6.site> <49387f7e$0$27857$9b622d9e@news.freenet.de> Message-ID: <4939c6be$0$6534$9b622d9e@news.freenet.de> Terry Reedy wrote: > Martin v. L?wis wrote: >>> Since the source code is incompatible, I was expecting the Python >>> executable to have a new name such as 'python3' >> >> It does: the executable is called python3.0. > > Why do you say that? Because it is - on Unix. I assumed that was the platform that the OP cared about. Regards, Martin From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 21:06:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2008 02:06:12 GMT Subject: ANN: New Book: Programming in Python 3 References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> Message-ID: <015c4a65$0$20656$c3e8da3@news.astraweb.com> On Fri, 19 Dec 2008 19:32:22 -0500, Colin J. Williams wrote: (Fixing broken unicode.) >> Question from a non-native english speaker: is this now valid english? >> >> "One of Python's great strengths" >> ^ >> "and also teaches Python's functional programming features" >> ^ >> "The book's approach is wholly practical" >> ^ >> >> Curious, >> Thomas > > No. Is this a quote from some > advertising stuff or was it written by the author? What makes you say it is not valid English? How do you make possessives? -- Steven From theiviaxx at gmail.com Wed Dec 10 17:44:59 2008 From: theiviaxx at gmail.com (TheIvIaxx) Date: Wed, 10 Dec 2008 14:44:59 -0800 (PST) Subject: lxml.etree error: xmlSchematronSetValidStructuredErrors Message-ID: <33c18d97-598e-4c8c-ac1d-b7c839862eda@a26g2000prf.googlegroups.com> I have installed libxml2 and libxslt and then tried to install lxml with easy_install lxml. I can import lxml by "import lxml" but trying "from lxml import etree" and get: ImportError: /usr/local/lib/python2.5/site-packages/lxml-2.2alpha1- py2.5-linux-i686.egg/lxml/etree.so: undefined symbol: xmlSchematronSetValidStructuredErrors I have only seen one mention of this error through googling and they suggested there was something wrong with libxml2 or libxslt. However importing libxml2 works fine, libxslt throws an error about it not defining an init function (?). Any advice? Thanks From steve at holdenweb.com Mon Dec 15 12:35:36 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 15 Dec 2008 12:35:36 -0500 Subject: %s place holder does not let me insert ' in an sql query with python. In-Reply-To: References: <1229345178.31093.24.camel@krishna-laptop> Message-ID: <49469568.2090203@holdenweb.com> Lamonte Harris wrote: > I had this problem too. If you've upgraded to python 2.6 you need to > use the new sytnax "format > > queryString = "insert into venders > values('{0}','{1}','{2}'".format(field1,field2,field3) > Will all readers of this thread kindly regard this as an example of how *not* to generate and execute SQL queries in Python. Study the cursor.execute() method, and provide parameterized queries and a data tuple instead. Please also note that the above technique explicitly continues to generate SQL syntax errors in Krishnakan's case where the data values themselves contain apostrophes. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From rt8396 at gmail.com Mon Dec 22 21:51:40 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 18:51:40 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> Message-ID: <7c02eb33-a919-4481-8eda-76062729f233@k19g2000yqg.googlegroups.com> On Dec 22, 7:34?pm, Steven D'Aprano wrote: > On Mon, 22 Dec 2008 10:01:21 -0800, r wrote: > > Walter, > > I just look at the stats for comp.lang.python, and i am 9th place for > > most post this month. > > And about 9,000th place for useful information. > > -- > Steven I think you missed my point Steven, I was in no way proud of the fact of my 9th place rating. It just proves my point to the small following of this group. And frankly makes me feel bad. From gagsl-py2 at yahoo.com.ar Sun Dec 21 17:30:33 2008 From: gagsl-py2 at yahoo.com.ar (gagsl-py2 at yahoo.com.ar) Date: Sun, 21 Dec 2008 14:30:33 -0800 (PST) Subject: [Help] The pywinauto Can't select the MDI's menu using the MenuItems() which return []. In-Reply-To: Message-ID: <85676.52949.qm@web32801.mail.mud.yahoo.com> --- El vie 19-dic-08, ???? escribi?: > I use the WORD Only for my example. > The application I test is similar to the WORD and It > has't the COM. The code below opens the Choose Font dialog on my Spanish Windows version: py> from pywinauto.application import Application py> app = Application.start("Notepad.exe") py> app[u"Sin t?tulo - Bloc de notas"].MenuSelect(u"Formato->Fuente") (using an English version, the last line would be app.UntitledNotepad.MenuSelect("Format->Font") I presume) There are many examples in the documentation, and some more info at http://pywinauto.seleniumhq.org/ I think there is a pywinauto users list. > 2008/12/19 Gabriel Genellina > > > En Thu, 18 Dec 2008 11:28:54 -0200, Simon Brunning > > escribi?: > > > > 2008/12/18 ???? : > >> > >>> This problem also use the following > discription: > >>> How to use pywinauto to open WORD and select > its Menu. > >>> I can't do that and have no idea why! > >>> Looking forward your help,Thanks! > >>> > >> > >> Word can be automated with COM. My golden rule is > that automation via > >> GUI driving is always a last resort. -- Gabriel Genellina ____________________________________________________________________________________ ?Busc? desde tu celular! Yahoo! oneSEARCH ahora est? en Claro http://ar.mobile.yahoo.com/onesearch From samslists at gmail.com Fri Dec 5 15:02:19 2008 From: samslists at gmail.com (Sam) Date: Fri, 5 Dec 2008 12:02:19 -0800 (PST) Subject: Centralized logging server... Message-ID: <413147e3-aaea-4ae3-a350-4c22a79fe77a@b38g2000prf.googlegroups.com> Hi... I'm working with a small team writing a bunch of python applications that communicate via xml/http in a somewhat restful way. :) They are running on about half a dozen computers. We'll probably be scaling that to a lot more computers soon. I've been playing with the python logging module. I'd like all of these applications to write their logs to the same place in order to make analysis easier. Any ideas on best practices? What are my options for a syslog server to receive the messages? Rsyslog looks like it would be good. Anyone know anything else? Thanks From vlastimil.brom at gmail.com Sat Dec 13 16:03:14 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Sat, 13 Dec 2008 22:03:14 +0100 Subject: Python 3.0 crashes displaying Unicode at interactive prompt In-Reply-To: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> Message-ID: <9fdb569a0812131303k73822a2es7639e37dbb0b98d3@mail.gmail.com> 2008/12/13 John Machin : > > Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> x = u'\u9876' >>>> x > u'\u9876' > > # As expected > > Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit > (Intel)] on win 32 > Type "help", "copyright", "credits" or "license" for more information. >>>> x = '\u9876' >>>> x > Traceback (most recent call last): > File "", line 1, in > File "C:\python30\lib\io.py", line 1491, in write > b = encoder.encode(s) > File "C:\python30\lib\encodings\cp850.py", line 19, in encode > return codecs.charmap_encode(input,self.errors,encoding_map)[0] > UnicodeEncodeError: 'charmap' codec can't encode character '\u9876' in > position > 1: character maps to > > # *NOT* as expected (by me, that is) > > Is this the intended outcome? > -- > http://mail.python.org/mailman/listinfo/python-list > I also found this a bit surprising, but it seems to be the intended behaviour (on a non-unicode console) http://docs.python.org/3.0/whatsnew/3.0.html "PEP 3138: The repr() of a string no longer escapes non-ASCII characters. It still escapes control characters and code points with non-printable status in the Unicode standard, however." I get the same error in windows cmd, (Idle prints the respective glyph correctly). To get the old behaviour of repr, one can use ascii, I suppose. Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> repr('\u9876') Traceback (most recent call last): File "", line 1, in File "C:\Python30\lib\io.py", line 1491, in write b = encoder.encode(s) File "C:\Python30\lib\encodings\cp852.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u9876' in position 2: character maps to >>> '\u9876'.encode("unicode-escape") b'\\u9876' >>> ascii('\u9876') "'\\u9876'" >>> From gary at byoteki.com Sat Dec 27 08:02:13 2008 From: gary at byoteki.com (Gary M. Josack) Date: Sat, 27 Dec 2008 08:02:13 -0500 Subject: parsing csv files class In-Reply-To: References: Message-ID: <49562755.6050205@byoteki.com> alex goretoy wrote: > I know it's messy with all those self.soc.* functions, but it works in > one of my current project. I just want to make it more pythonic I also > want to add capability for makeing csv file if I give it input like: > 1234,something nice, hey this is something nice > 2468,something else, something else > > On Sat, Dec 27, 2008 at 4:54 AM, alex goretoy > > wrote: > > Hello All, > > I have this class that I use in one of my projects. I know it's > missing functionality and some things could have been done > differently. Can you ehlp me make this class better? What can I do > to make it more resistant to error? You can find the > stdout_colours class on Google if you want it, JFGI I want to make > it more pythonic. I come from a PHP background, can you tell? > > Any and all help is appreciated > -Alex > > #!/usr/bin/env python > from ctypes import * > import os, sys, types, csv, urllib, urllib2, urlparse, > string,stdout_colours > > class parsercsvy(object): > """Return a line from a csv file or total amount of lines""" > def __init__(self,file_name=""): > self.func_me_color="white_on_black" > self.soc=stdout_colours.stdout_colors() > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > self.filename = file_name > self.buffer = [] > self.bufferp= [] > if string.find(self.filename,"http") != -1: > resp=urllib2.urlopen(self.filename) > file=resp.read() > lfi=len(string.split(self.filename,"/")) > filename = "/tmp/"+string.split(self.filename,"/")[lfi-1] > f=open(filename,"w") > f.write(file) > f.close > self.parse(self.filename) > else: > self.parse(self.filename) > self.soc.me_him(['EXIT:',__name__],self.func_me_color) > def parse(self,filename,ret=0): > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > i = 0 > try: > reader = csv.reader(file(filename, "rb")) > try: > for row in reader: > self.buffer.append(row) > s,a=[],{} > > for j in range(len(self.buffer[0])): > a[self.buffer[0][j]]=row[j] > self.bufferp.append(a) > i+=1 > self.total = i-1 > except csv.Error, e: > sys.exit('file %s, line %d: %s' % (filename, > reader.line_num, e)) > except IOError, e: > sys.exit('file %s, IOError: %s' % (filename, e)) > self.soc.me_him(['EXIT:',__name__],self.func_me_color) > def index(self, index): > """return line for index""" > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > > self.soc.me_him(['RETURN:',self.buffer[int(index)],__name__],self.func_me_color) > return self.buffer[int(index)] > def total(self): > """return total number of lines in csv file""" > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > > self.soc.me_him(['RETURN:',self.total,__name__],self.func_me_color) > return self.total > def header(self): > """return csv header == line 0""" > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > > self.soc.me_him(['RETURN:',self.buffer[0],__name__],self.func_me_color) > return self.buffer[0] > def find_and_replace(self,li,fi,re): > """ > find and replace a string inside a string, return list > find_and_replace(list,find,replace) > """ > this=[] > for l in li: > # found_index=string.find(l,fi) > this.append(l.replace(fi,re)) > return this > def return_buffer(self): > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > > self.soc.me_him(['RETURN:',self.buffer,__name__],self.func_me_color) > return self.buffer > if __name__ == "__main__": > if len(sys.argv) < 1: > print "Usage: %s file"% sys.argv[0] > f=sys.argv[1] > c=csv_parser(f) > print c.bufferp > -- > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > > > > > -- > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list > Do you know that there is a csv module in the standard library already? Thanks, Gary M. Josack From google at mrabarnett.plus.com Fri Dec 12 11:45:02 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 12 Dec 2008 16:45:02 +0000 Subject: Removing None objects from a sequence In-Reply-To: <87ej0dz894.fsf@daycos.com> References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> Message-ID: <4942950E.5030409@mrabarnett.plus.com> Kirk Strauser wrote: > At 2008-12-12T15:51:15Z, Marco Mariani writes: > >> Filip Gruszczy?ski wrote: >> >>> I am not doing it, because I need it. I can as well use "if not elem >>> is None", > >> I suggest "if elem is not None", which is not quite the same. > > So what's the difference exactly? "foo is not None" is actually surprising > to me, since "not None" is True. "0 is True" is False, but "0 is not None" > is True. Why is that? > I suppose that it should really be "not is" (cp "not in"), but Guido chose to follow the English pattern "is not". "not" returns a Boolean (or originally an int) and "is" checks for identity, but the result of "is False" or "is True" is down to implementation details in the interpreter, so you wouldn't write "is not ..." to mean "is (not ...)" anyway, and in practice it's not a problem. From bockman at virgilio.it Wed Dec 31 09:48:50 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: Wed, 31 Dec 2008 15:48:50 +0100 Subject: select.select and socket.setblocking In-Reply-To: <3652a957-eec6-494c-bd37-d150018bc0ed@p2g2000prf.googlegroups.com> References: <495a661d$0$11384$5fc30a8@news.tiscali.it> <495b34d8$0$11387$5fc30a8@news.tiscali.it> <3652a957-eec6-494c-bd37-d150018bc0ed@p2g2000prf.googlegroups.com> Message-ID: <495b8653$0$11383$5fc30a8@news.tiscali.it> < ... > >> Uhm. In my experience, with TCP protocol recv only returned less than >> the required bytes if the remote end disconnects. I always check the > > What if the sending end actually sent less than you asked for ? > > -srp > In blocking mode and with TCP protocol, the recv waits until more bytes are received - mixing up the next message with the previous one and then loosing the 'sync' and being unable to interpretate the received data - or the remote end disconnects. Yes this is bad, and is a good reason why socket receive should be handled in non-blocking mode if you receive data from untrusted sources. But luckily for me, as I said in the other post, I used socket mostly to communicate between specific applications on a private LAN or WAN, so I could afford to ignore the problem. Ciao ---- FB From pruebauno at latinmail.com Thu Dec 4 11:08:31 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Thu, 4 Dec 2008 08:08:31 -0800 (PST) Subject: funny generator behaviour References: Message-ID: <8aca069b-c19c-4c33-9bd6-6171070079c7@t26g2000prh.googlegroups.com> On Dec 4, 8:00 am, Edvin Fuglebakk wrote: > I have written a generator that puzzles me: > > The generator is supposed to create ordered selections of a set of > objects. repetition of objects is allowed and the selections should be > of a size determined by a pramter to the generator. > > Now, if I try to accummulate the generated selections into a list I get > some peculiar behaviour that I hope maybe some of you can help me > understand: > > Help much appreciated > -Edvin > > #straightforward acumulation. Does not give the expected result > >>> d=[] > >>> for f in orderedCombinations([1,2],3): > ... d.append(f) > ... > >>> d > [[1], [2], [1], [2], [1], [2], [1], [2]] > > #accumulating shallow copies of the genereated combinations works: > >>> d=[] > >>> for f in orderedCombinations([1,2],3): > ... d.append(f[:]) > ... > >>> d > [[1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 2, 2], [2, 1, 1], [2, 1, 2], [2, > 2, 1], [2, 2, 2]] > > #The generator: > def orderedCombinations(pool, k): > """ > Generator yielding ordered selections of size k with repetition from > pool. > """ > > if k == 1: > for m in pool: > yield [m] > > if k > 1: > > for m in pool: > for combo in orderedCombinations(pool, k-1): > > #insert and pop to avoid copying entire list > combo.insert(0,m) > yield combo > combo.pop(0) BTW if you search in the fine manual version 2.6 you will find that a slick implementation is already part of the standard library (hint: itertools): def orderedCombinations(pool, k): result = [[]] for poolel in [pool] * k: result = [x+[y] for x in result for y in poolel] return result From 20080915.20.wmcclain at spamgourmet.com Tue Dec 9 11:28:40 2008 From: 20080915.20.wmcclain at spamgourmet.com (Bill McClain) Date: 9 Dec 2008 16:28:40 GMT Subject: StringIO in 2.6 and beyond References: Message-ID: On 2008-12-08, Bill McClain <20080915.20.wmcclain at spamgourmet.com> wrote: > On 2008-12-08, Christian Heimes wrote: > > In this context 'str' means Python 3.0's str type, which is unicode in > > 2.x. Please report the misleading error message. > So this is an encoding problem? Can you give me a hint on how to correct in my > example? I see that io.StringIO() has an encoding parameter, but I'm unclear > what to specify. I still don't have this working. I've been specifying encodings without success. The StringIO example usage in the Python 3.0 documentation here: http://docs.python.org/3.0/library/io.html#io.StringIO gives me the same error on 2.6: #! /usr/bin/env python from __future__ import print_function import io output = io.StringIO() output.write('First line.\n') print('Second line.', file=output) # Retrieve file contents -- this will be # 'First line.\nSecond line.\n' contents = output.getvalue() # Close object and discard memory buffer -- # .getvalue() will now raise an exception. output.close() ./stringio30.py Traceback (most recent call last): File "./stringio30.py", line 7, in output.write('First line.\n') File "/usr/local/lib/python2.6/io.py", line 1487, in write s.__class__.__name__) TypeError: can't write str to text stream -Bill -- Sattre Press History of Astronomy http://sattre-press.com/ During the 19th Century info at sattre-press.com by Agnes M. Clerke http://sattre-press.com/han.html From bearophileHUGS at lycos.com Mon Dec 1 20:09:20 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 1 Dec 2008 17:09:20 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: Jon Harrop: Is so wide cross-posting positive? > 4. Static type checking.< This is a Python newsgroup, you will find less lovers of static typing here :-) >Overall, Mathematica is a whopping 700,000 times slower!< Your Mathematica code is cute, but surely Mathematica isn't designed for that kind of "programing". It's more for symbolic processing or to perform few operations in a very flexible way, so it's more for research and *exploration* and visualization; while more normal programming languages are more to compute a lot of things when you already know what you are doing. > http://www.ffconsultancy.com/languages/ray_tracer/ You can write versions for Python, Psyco, ShedSkin, too, if you want. Bye, bearophile From steve at holdenweb.com Fri Dec 12 11:55:27 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Dec 2008 11:55:27 -0500 Subject: concept of creating structures in python In-Reply-To: <25EDE674-3566-4720-BCEB-6A4D3865C9E2@strout.net> References: <25EDE674-3566-4720-BCEB-6A4D3865C9E2@strout.net> Message-ID: Joe Strout wrote: > On Dec 12, 2008, at 9:00 AM, Steve Holden wrote: > >>> Change the default value of ds_obj here to None. Otherwise, you will >>> certainly confuse yourself (there would be just one default object >>> shared among all instances). >>> >> Joe missed a piece out here. If you change the signature of your >> D.__init__() to read >> >> def __init__(self, dataName='ND', index = 0, ele_obj=None): >> >> then you need to insert the following code at the top of the method: >> >> if ele_obj is None: >> ele_obj = E() > > Yes, if you really need to guarantee that ele_obj is not None, then this > is the way to do it. > > Of course this would mean that you can't get a None ele_obj even by > passing it in explicitly as the parameter value -- if you need to > support that as well, then the solution is a little more complex. > Perhaps best in that case would be to just not give ele_obj any default > value at all, so it becomes a required parameter. > Just for completeness, if you want to be able to pass None then you need to create a sentinel object, usually just an instantiation of object(), and test for identity with that to determine that no argument was provided. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From Scott.Daniels at Acm.Org Sat Dec 27 19:06:42 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 27 Dec 2008 16:06:42 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: Daniel Fetchinson wrote: >.... I have a list to begin with which will be passed to the C function. > I assume converting the list to an array.array and passing that to the C > function doesn't make any difference in terms of speed since the > operation itself will be done in the C function anyway. Right, but why bother to do the conversion in C where you'll have to fiddle with refcounts and error propogation? convert in python, and go to the underlying data in C. --Scott David Daniels Scott.Daniels at Acm.Org From gagsl-py2 at yahoo.com.ar Sun Dec 14 16:46:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 14 Dec 2008 19:46:50 -0200 Subject: Bidrectional Subprocess Communication References: <5b4f4146-ad39-4fe6-9055-e852bd127143@q26g2000prq.googlegroups.com> Message-ID: En Sun, 14 Dec 2008 09:37:38 -0200, Emanuele D'Arrigo escribi?: > On Dec 14, 4:48?am, "Gabriel Genellina" > wrote: >> - you have to close server.stdin when you don't have more data to send. >> The server will see an end-of-file and knows it has to exit the loop. >> Same thing on the client side. > > Hi Gabriel, thanks for modifying the code to make it work. I've just > tried tinkering with it to see how far it would go. On your two > statements above: does this means that any data must be sent in one > batch and then the subprocess must shut down? What I was trying to > simulate is a client/server relationship through a subprocess, where > the server (the subprocess) keeps listening and the client sends data > when it wants to (and eventually viceversa). But when the > server.stdin.close() statement is issued, the pipe is closed for good > and can't be reopened (can it?). No, not at all. You can keep writing things to the pipe - as long as the read side keeps reading, there is no limit on how much data you can send. Just make sure you close the writing side of the pipe when you have no more data to send, to signal the other side it's OK to exit the read loop. >> - you have to wait until the server answers, else it will get a "broken >> pipe" error or similar. > > So, if I want to interrogate the subprocess multiple times I must end > and restart the ListenerThread multiple times then? No, I mean, since your example is bidirectional, the parent process must still be alive and able to read when the subprocess replies. Given this sequence: parent writes "hi sub!" child reads "hi sub!" child writes "hi dad!" parent reads "hi dad!" if the parent just exits after sending "hi sub!", the child will get an error when replying (I think it says "invalid handle" on Windows, "broken pipe" on Linux, or something like this). -- Gabriel Genellina From atagar1 at gmail.com Tue Dec 30 01:30:53 2008 From: atagar1 at gmail.com (Damian Johnson) Date: Mon, 29 Dec 2008 22:30:53 -0800 Subject: Python 3.0 Curses Unicode In-Reply-To: References: Message-ID: It seems as if the curses module in Python 3.0 isn't respecting the system's preferred encoding (utf-8) which was set via: locale.setlocale(locale.LC_ALL, '') The purpose of this was described at the top of ' http://docs.python.org/dev/3.0/library/curses.html#module-curses'. The getlocale function is reporting the proper values ('en_US', 'UTF8') but addstr is clearly not treating it as Unicode - is this a bug? -Damian 2008/12/28 Damian Johnson > Hi, I've switched to Python 3.0 for a new Japanese vocab quizzing > application due to its much improved Unicode support. However, I'm running > into an issue with displaying Unicode characters via curses. In Python 2.x a > simple hello-world looks like: > > #!/usr/bin/python > # coding=UTF-8 > > import curses > import locale > > locale.setlocale(locale.LC_ALL,"") > > def doStuff(stdscr): > message = u"hello ???!" > stdscr.addstr(0, 0, message.encode("utf-8"), curses.A_BLINK) > stdscr.getch() # pauses until a key's hit > > curses.wrapper(doStuff) > > This works. However, when I try to come up with an equivalent for Python > 3.0: > > #!/usr/bin/python > > import curses > import locale > > locale.setlocale(locale.LC_ALL,"") > > def doStuff(stdscr): > message = "hello ???!" > stdscr.addstr(0, 0, message, curses.A_BLINK) > stdscr.getch() # pauses until a key's hit > > curses.wrapper(doStuff) > > It fails (printing gibberish to the console). Anyone have a clue what I'm > doing wrong? Thanks! -Damian > > PS. Is the "# coding=UTF-8" header meaningless in Python 3.0? Also, is > "locale.setlocale(locale.LC_ALL,"")" still necessary for getting curses to > provide Unicode support? > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 17:58:10 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Dec 2008 22:58:10 GMT Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> <5926cb50-e53f-4e9e-8672-b4e29e2280b5@r36g2000prf.googlegroups.com> Message-ID: <0149a9be$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 07:09:27 -0800, bearophileHUGS wrote: > Andreas Waldenburger: >> Whenever has it been a pythonic ideal to "not allow" stuff? You get >> warnings. Everything else is up to you. > > It's a strong source for bugs, especially for newbies, that I have hoped > to see removed from Python3 (my first request of this was years ago). I > was nearly sure to see this wart removed from Python3, and now I hear > it's presents still. I don't understand why they haven't fixed it. "It"? Context please... snipping unnecessarily quoted text is a good thing, but please leave enough context for people to know what you're talking about. I think you're talking about mixed spaces/tabs in the one module. Frankly, I question just how "strong" a source of bugs it really is. Oh, I don't doubt that there are circumstances where it can cause bugs, but I don't remember the last time the solution to some newbie's problem on comp.lang.python was "use spaces or tabs but not both". My gut feeling is that you have to have a fairly unusual set of circumstances before it causes actual bugs. So perhaps nobody on the python-dev team have fixed it yet because nobody cares enough to do the work, or it's unexciting and tedious to fix. Or maybe python-dev *think* they've fixed it, and the fact that it isn't fixed is a bug that needs reporting. > Then this is the third thing I don't like of Python3 (the other two > being the removal of automatic tuple unpacking in function signature and > the wart of literals for empty set/dict). Er, what do you mean? What wart? -- Steven From rcdailey at gmail.com Tue Dec 9 10:31:41 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 9 Dec 2008 07:31:41 -0800 (PST) Subject: 'pretty print' for built in types Message-ID: <051e3a97-b9bc-4a67-8896-93628ca19f59@r15g2000prd.googlegroups.com> Hi, Is there a built in way to 'pretty print' a dict, list, and tuple (Amongst other types)? Dicts probably print the ugliest of them all, and it would be nice to see a way to print them in a readable way. I can come up with my own function to do this, but I don't want to do this if I don't have to. From rt8396 at gmail.com Fri Dec 19 13:44:25 2008 From: rt8396 at gmail.com (r) Date: Fri, 19 Dec 2008 10:44:25 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> Message-ID: <88ff7c46-2b23-49e4-865e-781d23433799@l33g2000pri.googlegroups.com> ~Michael, What?s next down this road of self destruction? Hey guys, forget about about empty parenthesis on a function/method call, we should not have to waste are time typing them? Wait forget about them all together and we will just write Ruby code? Def function arg arg arg arg arg arg ?Yea, that looks good?.insert(sarcasm) Things like forcing empty tuple on function/method calls are what make python so great. Python dumped the C bracket plague, but enforces parenthesis even for a no argument function. But hell, why shouldn?t we have 50 ways to the same thing in Python like Ruby. PS. Don?t discredit Walter just because he is not on the dev team, that don?t mean squat! ~Bearophile, Thanks for your civil approach to this conversation but I must disagree with you on the new string formatting syntax. You said the new syntax is suppost to be easier on the n00b , I say it pollutes a students mind. What is wrong with similarities to C formatting, I find nothing complicated about it. %s (means put a string here) %d (means put a integer here) %f (means put a float here) It does not get any simpler than that, and this will just ease the transition to C programming for this student. Lets not forget how important C is! I always likened Python to my cool uncle who would let me get away with more than my parents-C- but would enforce the important rules. Like Python?s forcing of empty tuple in function calls, that is a good idea. This allows you to clearly see arguments in source code. I like in Python there is only one, or a very minimal number of ways to do something(but usually only one is the best). Ruby is littered with different ways to do the same thing. I think this will be Ruby?s undoing?. And Pythons if we follow down this road. And lets not forget Python forcing of indention, that is Pythons greatest strength! From pruebauno at latinmail.com Thu Dec 18 11:45:21 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Thu, 18 Dec 2008 08:45:21 -0800 (PST) Subject: Is this pythonic? References: <66d058f9-cfe1-4b3c-ab8a-e6e88bb97770@m22g2000vbp.googlegroups.com> Message-ID: <7dc03d4b-4bce-4cc4-b020-681935cf0b0b@m4g2000vbp.googlegroups.com> On Dec 18, 11:08?am, ipyt... at gmail.com wrote: > x.validate_output(x.find_text(x.match_filename > (x.determine_filename_pattern(datetime.datetime.now())))) > > Is it even good programming form? Lisp and Scheme programmers love that style. You can tell by the number of parentheses :-). In Python people usually use an intermediate variable to break things up a bit but the amount of acceptable nesting is a matter of personal style. From grante at visi.com Sun Dec 7 23:27:31 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 07 Dec 2008 22:27:31 -0600 Subject: how to get a beep, OS independent ? References: <6q2sjfFai65qU1@mid.individual.net> Message-ID: On 2008-12-07, Peter Pearson wrote: > On Sun, 07 Dec 2008 00:40:53 +0100, Stef Mientki wrote: >> >> I want to give a small beep, for windows there's message-beep, >> and there seems to be something like " curses" , but that >> package seems to be totally broken in P2.5 for windows. >> >> Any other suggestions ? > > Many people have suggested sending an ASCII 07 to your > terminal window, but sometimes you don't have a terminal > window. Some terminal windows don't beep when they receive a BEL character. Some flash, some do nothing at all -- but that's the user's decision. I believe sending a BEL to stdout is the accepted standard for command-line applications. > Then there's the question of using the sound card versus using > the PC speaker. Assuming the computer has at lease one of the two (some of mine don't). > Too complicated for me. Cross-platform programming is indeed complicated. > I used a kluge: a short C program that beeps the way I want, > in this case using ioctl(fd,KDMKTONE,arg) on /dev/tty0 (this > is Linux). The program has enough privileges to execute even > when run by unprivileged users, and of course can be invoked > by whatever language you're working in. That would seem to make the machine on which the ioctl() call is executed beep (assuming it can beep). What if you're ssh'ed into the machine or running a remote X server? What if the user is deaf? One would presume the intent was to alert the person running the program to some condition that needs attention. If it's a command-line appliction, output a BEL character to stderr. That's the standard way to alert the user. If the user has her terminal configured to do something else (e.g. flash), then that's her decision and you shouldn't try to override it. If it's an X11 application, then use the Xlib call to request that the X server alert the user (usually with a "beep"). I've no idea what one does under Windows or MacOS, but I'm sure they have their "standards" as well. -- Grant From andre.roberge at gmail.com Wed Dec 31 11:37:26 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Wed, 31 Dec 2008 08:37:26 -0800 (PST) Subject: Solved. was: Memory leak problem (while using tkinter) References: Message-ID: <901c3b47-07f8-435d-a889-8cb00314a7e6@d42g2000prb.googlegroups.com> On Dec 31, 12:21?am, Andr? wrote: > I have written a small program (my first Tkinter-based app) to play > around the idea mentioned on > http://rogeralsing.com/2008/12/07/genetic-programming-evolution-of-mo... > and, in doing so, have encountered a memory leak problem. ? I have > seen mentions on the web of using the delete() method of canvas to > prevent such problems - which I have tried to do with limited > success. ?Below is the code I wrote; to run it, you will need a small > image file > (I used the one found onhttp://alteredqualia.com/visualization/evolve/) > that is saved under "mona_lisa.png". > It appears that the problem occurred due to creating drawing "contexts" with aggdraw which became orphaned in some ways. Below is some changes that appear to solve the problem. Perhaps this will be useful to others at some point... Andr? [SNIP] > > class AggDrawCanvas(Canvas): > ? ? def __init__(self, width, height, win): > ? ? ? ? Canvas.__init__(self, win) > ? ? ? ? self.image_id = None > ? ? ? ? self.win = win > ? ? ? ? self._width = width > ? ? ? ? self._height = height > ? ? ? ? self._size = width, height > ? ? ? ? self.config(width=width, height=height+20) > ? ? ? ? self.info = self.create_text(width/2, height+20) > ? ? ? ? self.pack() > ? ? ? ? self.dna = DNA(self._width, self._height) > ? ? ? ? self.mutations = 0 self.img = None > > ? ? def draw_dna(self): > ? ? ? ? img = Image.new("RGBA", self._size, "black") > ? ? ? ? self.context = aggdraw.Draw(img) replace by: if self.img is None: self.img = Image.new("RGBA", self._size, "black") self.context = aggdraw.Draw(self.img) else: brush = aggdraw.Brush((0, 0, 0), opacity=255) self.context.rectangle((0, 0, self._width, self._height), brush) > ? ? ? ? for gene in self.dna.dna: > ? ? ? ? ? ? brush = aggdraw.Brush(tuple(gene[1][0:3]), opacity=gene[1] > [3]) > ? ? ? ? ? ? self.context.polygon(gene[0], brush) > ? ? ? ? self.delete(img) > ? ? ? ? self.redraw() > [SNIP] From python.list at tim.thechases.com Sat Dec 13 11:12:41 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 13 Dec 2008 10:12:41 -0600 Subject: encrypt and descrypt a created file In-Reply-To: References: Message-ID: <4943DEF9.4090506@tim.thechases.com> > open(str(os.sep).join([ > os.getcwd(), > 'applications', > request.application, > 'databases', > table+'.csv']),'w').write(str(db(db[table].id).select ())) > > > How can i encrypt and descrypt the created file above?? Well, as I was recently admonished (and have come to love), the first recommendation is to use the "csv" module for writing CSV files. It deals with oddities like quotation-escaping, and a bunch of other details. However, you want some sort of encryption/decryption method, but you don't specify what type. You can do something simple like def encrypt(s): return s.encode('rot13') def decrypt(s): return s.decode('rot13') f = open(filename, 'wb') f.write(encrypt(content)) f.close() f = open(filename, 'r') content = decrypt(f.read()) f.close() It's not very good encryption though ;-) For better encryption see [1] & [2] for the pycrypto module. It's been a while since I've done anything using this module, but the docs are available for it and the basic premise is the same (encrypt the content before writing, decrypt the content upon reading). It would help to read up on crypto best-practices about storing key-files, password-management, etc. -tkc [1] http://www.pycrypto.org [2] http://www.amk.ca/python/code/crypto.html From lie.1296 at gmail.com Mon Dec 8 06:16:46 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 8 Dec 2008 11:16:46 +0000 (UTC) Subject: Guido's new method definition idea References: <20081207182721.4033466d@usenot.de> Message-ID: On Sun, 07 Dec 2008 18:27:21 +0100, Andreas Waldenburger wrote: > On Sat, 6 Dec 2008 23:21:04 -0800 (PST) Lie wrote: > >> I think we have to test this on newbies. [snip] >> > Now that's talking like a programmer! > > Ideas on how such a survey could be conducted? Anyone? > > >> If this dead horse is revived because of that reason, then I'd go with >> changing the error message to something that is less confusing to >> newbies[1]. > + googol > > >> I remember being tripped with the (thinking that python miscounted the >> number of argument) when I was new. This has the advantage of backward >> compatibility and no syntax change, just less misleading error message. >> >> [1] anything could work, but I like this one: (c is an instance of >> class C) >> if the code is: c.foo(...), Error: "TypeError: c.foo() takes exactly 3 >> argument" >> while if the code is: C.foo(...), Error: "C.foo() takes exactly 4 >> arguments" >> You can implement c.foo as a curried C.foo function, catch C.foo's >> TypeError exception then reraise it as c.foo exception. > I'm not sure that I'd find that less confusing. Because a c.foo() *does* > take four arguments, not three. It's just that the first one is implicit > (Right?). It's not implicit, we explicitly pass c (the object instance), although not in the argument list. So c.foo takes 3 arguments while C.foo takes 4 arguments. In other words: from functools import partial c = C() -> c.attr = partial(C.attr, c) Note the error message I gave: "TypeError: c.foo() takes exactly 3 arguments" "TypeError: C.foo() takes exactly 4 arguments" There are two differences there, not only one claims to accept three and the other 4 arguments, but also the capitalization of c/C. Here is a clearer example: inst = cls() "TypeError: inst.foo() takes exactly 3 arguments" "TypeError: cls.foo() takes exactly 4 arguments" for comparison, python's current (2.5) error message is: "TypeError: foo() takes exactly 4 arguments" in addition, with this proposal we'll know how foo is being called. The following is a quick and dirty implementation of such error message. Note: There are still some unresolved problems though: 1. instance.[func name] is hardcoded, as I don't know how to get the instance's name from the instance creation itself 2. Class Invoking from class gives TypeError: foo()... instead of TypeError: Class.foo()... 3. most definitely not to be used on real application from types import MethodType import re errmess = re.compile(r'(.*?) (.*?) (\d*) (arguments?) \((\d*) given\)') def usenewexc(obj): def wrap(f): def wrap_(*args, **kargs): try: print args, kargs return f(*args, **kargs) except TypeError, e: re_mess = errmess.match(e.message) fname = re_mess.group(1) interm = re_mess.group(2) if re_mess.group(3) != '1' else 'takes' reqargs = int(re_mess.group(3)) - 1 if re_mess.group(3) ! = '1' else 'no' argue_s = re_mess.group(4) if re_mess.group(3) != '1' else 'arguments' givenargs = int(re_mess.group(5)) - 1 raise TypeError('%s.%s %s %s %s (%s given)' % ('instance', fname, interm, reqargs, argue_s, givenargs)) return wrap_ for attrname in dir(obj): attr = obj.__getattribute__(attrname) if type(attr) == MethodType: obj.__setattr__(attrname, wrap(attr)) return obj class A(object): def foo(self): print '' pass a = usenewexc(A()) A.foo(a, 2) > How about: > > "TypeError: c.foo() takes exactly 3 arguments in addition to the > implicit instance reference." > > or > > "TypeError: c.foo() takes exactly 4 arguments (5 given, including the > implicit instance reference)" > > ... or something less kludgy in that general direction. This would > explain exactly what is wrong. > > /W > > -- > My real email address is constructed by swapping the domain with the > recipient (local part). From pythonsky at sky.com Thu Dec 11 09:27:21 2008 From: pythonsky at sky.com (garywood) Date: Thu, 11 Dec 2008 14:27:21 -0000 Subject: just got the g1 Message-ID: Hi Just got the G1, is their any way to get python running on the andriod platform ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Wed Dec 3 03:02:21 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 03 Dec 2008 09:02:21 +0100 Subject: porting modules to Python 3.0 In-Reply-To: References: <8f60c779-f1ec-4127-b173-f174c016aa96@a12g2000yqm.googlegroups.com> <4936255D.6000509@v.loewis.de> Message-ID: <49363d0d$0$3653$9b622d9e@news.freenet.de> > In one has both 2.x and 3.0 installed, would it easy to install 'lib.py' > for both? It's currently not possible to install something for 2.x; you have to specifically install it for every value of x (e.g. 2.5 or 2.6). It's the same for 3.0: you have to install it separately. Doing so is fairly easy. You just run "setup.py install" multiple times (or download and install prebuilt binaries if available). Regards, Martin From skip.montanaro at gmail.com Tue Dec 9 21:12:08 2008 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Tue, 9 Dec 2008 18:12:08 -0800 (PST) Subject: Test posting #2 - please ignore References: Message-ID: <7378d7c8-e480-492a-aeb2-99fba2eae188@v4g2000yqa.googlegroups.com> Still testing (posted via google groups)... S From kirk at daycos.com Mon Dec 15 15:02:42 2008 From: kirk at daycos.com (Kirk Strauser) Date: Mon, 15 Dec 2008 14:02:42 -0600 Subject: tricky nested list unpacking problem References: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> Message-ID: <87ljuhxl3x.fsf@daycos.com> At 2008-12-15T19:06:16Z, Reckoner writes: > The problem is that I don't know ahead of time how many lists there are or > how deep they go. In other words, you could have: Recursion is your friend. Write a function to unpack one "sublist" and call itself again with the new list. For instance, something like: def unpack(pattern): # Find the first subpattern to replace # [...] results = [] for number in subpattern: results.append(pattern.replace(subpattern, number)) return results Calling unpack([1,2,3,[5,6],[7,8,9]]) would look cause it to call unpack([1,2,3,5,[7,8,9]]) and unpack([1,2,3,6,[7,8,9]]), compile the results, and return them. -- Kirk Strauser The Day Companies From castironpi at gmail.com Thu Dec 18 06:52:52 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 18 Dec 2008 03:52:52 -0800 (PST) Subject: C API and memory allocation References: <59352942-e976-4ef4-bc40-c8953df0a792@c36g2000prc.googlegroups.com> Message-ID: <0d35b640-71ad-4cde-8869-74878b2f3981@r36g2000prf.googlegroups.com> On Dec 18, 5:09?am, Ivan Illarionov wrote: > On 18 ???, 03:51, Aaron Brady wrote: > (snip) > > > How did you get a reference to the original > > string object, with which to increment its reference count? > > Use the "O!" format ?instead of "s": > PyObject *pystr; > ... PyArg_ParseTuple(args, "O!", &PyStringObject, &pystr) ... edit: &PyString_Type > > Then you can use PyString_AS_STRING explicitly, and control ref. > counts yourself. > > > How do you know its length to copy it into your own buffer? > > Use the "s#" format, as Gabriel has said. > > Ivan I see. Do I read correctly that 's' is only useful when the argument's position is known? Otherwise you can't know its length or change its reference count. From skip at pobox.com Sat Dec 27 18:06:06 2008 From: skip at pobox.com (skip at pobox.com) Date: Sat, 27 Dec 2008 17:06:06 -0600 Subject: multiply each element of a list by a number In-Reply-To: References: <4955e7be$0$4066$ba4acef3@news.orange.fr> Message-ID: <18774.46302.839127.228495@montanaro-dyndns-org.local> Colin> ... perhaps faster than numpy: ... For extremely short lists, but not for much else: % for n in 1 10 100 1000 10000 100000 ; do > echo "len:" $n > echo -n "numpy: " > python -m timeit -s 'import numpy ; a = numpy.array(range('$n'))' 'a*3' > echo -n "list: " > python -m timeit -s 'a = range('$n')' '[3*x for x in a]' > done len: 1 numpy: 100000 loops, best of 3: 11.7 usec per loop list: 1000000 loops, best of 3: 0.698 usec per loop len: 10 numpy: 100000 loops, best of 3: 11.7 usec per loop list: 100000 loops, best of 3: 2.94 usec per loop len: 100 numpy: 100000 loops, best of 3: 12.1 usec per loop list: 10000 loops, best of 3: 24.4 usec per loop len: 1000 numpy: 100000 loops, best of 3: 15 usec per loop list: 1000 loops, best of 3: 224 usec per loop len: 10000 numpy: 10000 loops, best of 3: 41 usec per loop list: 100 loops, best of 3: 2.17 msec per loop len: 100000 numpy: 1000 loops, best of 3: 301 usec per loop list: 10 loops, best of 3: 22.2 msec per loop This is with Python 2.4.5 on Solaris 10. YMMV. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From castironpi at gmail.com Mon Dec 29 21:18:23 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 18:18:23 -0800 (PST) Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <40b1b762-459b-4d6f-91f0-0a6e68d233ae@a26g2000prf.googlegroups.com> <4d396242-13c9-4318-97ba-99f18564fbc5@o4g2000pra.googlegroups.com> <016969d3$0$6988$c3e8da3@news.astraweb.com> Message-ID: <28e76735-f749-4452-8aa2-18e8f0e9e499@k1g2000prb.googlegroups.com> On Dec 29, 7:00?pm, Steven D'Aprano wrote: > On Mon, 29 Dec 2008 05:31:17 -0800, Aaron Brady wrote: > > One style of coding I heard about once only permits returns at the end > > of a function. ?It claims it makes it easier to see the function as a > > mathematical object. > > That's silly. You treat the function as a black box: input comes in, and > output comes out. You have no idea of what happens inside the black box: > it could loop a thousand times, take 150 different branches, or take one > of 37 different exit points. From the outside, it's still exactly like a > mathematical object. Internal complexity is irrelevant. This is why > mathematicians can perform algebra on complicated functions like Bessel's > function (of the first or second kind), without needing to care that > actually calculating Bessel's function is quite tricky. > > What I think the one-return-per-function style is aiming at is that it is > (sometimes) easier to analyse the internals of the function if there are > few branches. The more complicated branches you have, the harder it is to > analyse the function. Early exits on their own are not the cause of the > complexity: it's the number of branches leading to the early exit that > causes the problem. You'd think they would have noticed that. Eliminating early exits doesn't change the number of branches! > Avoiding early exits is an over-reaction to the Bad Old Days of spaghetti > code. But used wisely, early exists can simplify, not complicate, code. To make your case, you don't even need to prove that a wise early exit can simplify. You just need that an early exit can simplify. (The conclusive case is the early exit is better. For that, it's sufficient but not necessary to show that simplicity is your reader's highest priority. What's instructive about that is the counterexample: when is simpler not better? (Not rhetorical. Or, if never, then it's the top priority and consistent with every top priority, if my calculations are correct; but it remains to show that early exits can simplify.) snip better simpler > The second version has double the number of lines of code of the first. > It introduces an extra variable "found_item" and two extra if blocks. I > don't think the claim that the version with an early exit is more > complicated than the version without can justified. In a lab report, this is the part where the author would be arguing, "And the object accelerated at 9.8 m/s^2, which proves our hypothesis." I think you're showing that early exits can simplify, but you're bringing in more factors. I think you're trying to say that less lines of code is simpler, and less variables is simpler. Those lack proofs. You need: M: Less lines of code is simpler. m: Simpler is always better. C: Less lines of code is better. Or something. But no amount of thrashing, bludgeoning, wibbling, whimpering, or beating children with blunt objects, is going to change your reader's knowledge of good. Only experience is. Fine fine, so leather belts are bad. That doesn't make fewer lines of code good. However, the burden of proof is (definitely IMO) on the people that are unilaterally opposed to early returns. They need: M: Early exits are never simpler. m: Simpler is always better. C: Early exits are never better. Oddly enough, you share a minor premise. From sjmachin at lexicon.net Fri Dec 26 18:39:46 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 26 Dec 2008 15:39:46 -0800 (PST) Subject: Is there a function to remove escape characters from a string ? References: <0163882f$0$6988$c3e8da3@news.astraweb.com> Message-ID: <5a29b62a-c38f-409b-8887-6259ad072bf5@w1g2000prk.googlegroups.com> On Dec 27, 12:05?am, Stef Mientki wrote: > Yep, chr(254), because it's not in the human range of characters > and it's accepted by windows ini-files. >>> import unicodedata as ucd >>> for i in (0,1,2,3,4,7,8): ... s = chr(254) ... enc = 'cp125' + str(i) ... try: ... u = s.decode(enc) ... except UnicodeDecodeError: ... continue ... print enc, 'U+%04X' % ord(u), ucd.name(u) ... cp1250 U+0163 LATIN SMALL LETTER T WITH CEDILLA cp1251 U+044E CYRILLIC SMALL LETTER YU cp1252 U+00FE LATIN SMALL LETTER THORN cp1253 U+03CE GREEK SMALL LETTER OMEGA WITH TONOS cp1254 U+015F LATIN SMALL LETTER S WITH CEDILLA cp1257 U+017E LATIN SMALL LETTER Z WITH CARON cp1258 U+20AB DONG SIGN Either you have a strange and narrow definition of "human", or you are so brave as to cheerfully insult (inter alia) Romanians, Russians, Icelanders, Greeks, Turks, Czechs, Estonians, Finns, Slovaks, Slovenians, and Vietnamese :-) From arnodel at googlemail.com Sun Dec 14 15:35:09 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 14 Dec 2008 20:35:09 +0000 Subject: package structure? References: Message-ID: Torsten Mohr writes: > Hi, > > in a package i'd like to have a structure like this: > > Files end with ".py", others are directories: > > mod > __init__.py # sets __all__ = ['smod1'] > smod1.py # contains AClass() > smod1 > __init__.py # sets __all__ = ['abc', 'def'] > abc.py > def.py > > So i can now do: > > import mod.smod1.abc > import mod.smod1 > > > But functions/classes in smod1.py are not found: > > a = mod.smod1.AClass() > > I know this is somehow ambiguous, but i wonder how else i can make > "mod" have subpackages and modules. > > I wonder how i can make AClass() known in that package. > > > Thanks for any hints, > Torsten. Why don't you put the contents of smod1.py in mod/smod1/__init__.py? It'll work this way. Or you can put smod1.py within mod/smod1 and put from smod1 import * in mod/smod1/__init__.py HTH -- Arnaud From sturlamolden at yahoo.no Fri Dec 12 09:17:43 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 06:17:43 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> Message-ID: <8156b37b-d1f6-4142-ad6e-8488c95b6592@z28g2000prd.googlegroups.com> On Dec 12, 3:04 pm, Luis M. Gonz?lez wrote: > Why don't you guys google a little bit to know what's being done to > address python's "slowness"?? Nothing is being done, and woth Py3k it got even worse. > It has been mentioned in this thread the pypy project (isn't it enough > for you??) > Other hints: shedskin, psyco, pyrex... None of those projects addresses inefficacies in the CPython interpreter, except for psyco - which died of an overdose PyPy. PyPy is interesting if they ever will be able to produce something useful. They have yet to prove that. Even if PyPy can come up with a Python JIT, they will still be decades behind the technologies of Strongtalk and Java. That is the problem with reinventing the wheel all over again. Not to forget LLVM and Parrot which also will support Python frontends. From ethan at stoneleaf.us Wed Dec 10 18:26:47 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 10 Dec 2008 15:26:47 -0800 Subject: internal circular class references Message-ID: <49405037.90809@stoneleaf.us> Greetings List! I'm writing a wrapper to the datetime.date module to support having no date. Its intended use is to hold a date value from a dbf file, which can be empty. The class is functional at this point, but there is one thing I would like to change -- datetime.date.max and datetime.date.min are class attributes of datetime.date, and hold datetime.date values. At this point I have to have two lines outside the actual class definition to do the same thing, e.g.: class NullDate(object): "adds null capable DateTime.Date constructs" __slots__ = ['_date'] def __new__(cls, date='', month=0, day=0): nulldate = object.__new__(cls) nulldate._date = "" . . . return nulldate def __getattr__(self, name): if self: attribute = self._date.__getattribute__(name) return attribute else: if callable(dt.date.__dict__[name]): return int else: return 0 def __nonzero__(self): if self._date: return True return False @classmethod def fromordinal(cls, number): if number: return cls(dt.date.fromordinal(number)) else: return cls() NullDate.max = NullDate(dt.date.max) NullDate.min = NullDate(dt.date.min) How can I move those last two lines into the class definition so that: 1) they are class attributes (not instance), and 2) they are NullDate type objects? ~ethan~ From george.sakkis at gmail.com Thu Dec 4 12:57:20 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 4 Dec 2008 09:57:20 -0800 (PST) Subject: Overriding a method at the instance level on a subclass of a builtin type References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> Message-ID: On Dec 4, 12:31?pm, Arnaud Delobelle wrote: > "Zac Burns" writes: > > The class method seems to be the most promising, however I have more > > 'state' methods to worry about so I might end up building new classes > > on the fly rather than have a class per permutation of states! Now the > > code isn't quite as clear as I thought it was going to be. > > > It seems unfortunate to me that methods are always looked up on the > > class for new style objects. Was this done for speed reasons? > > It's only special methods such as __getitem__, ... > > You can override normal method on a per-object basis just by adding a > callable attribute with its name to the object: > > >>> class A(object): > > ... ? ? def foo(self): print 'A.foo' > ...>>> a = A() > >>> a.foo() > A.foo > >>> def a_foo(): print 'a.foo' > ... > >>> a.foo = a_foo > >>> a.foo() Note that the overriden "method" here is a plain function; it doesn't take self as the first argument. If you want to bind it to a callable that expects the first argument to be self, you have to bind explicitly self to the object: >>> def a_foo(self): print 'a.foo' >>> a.foo = a_foo >>> a.foo() TypeError: a_foo() takes exactly 1 argument (0 given) >>> from functools import partial >>> a.foo = partial(a_foo,a) >>> a.foo() a_foo George From rdmurray at bitdance.com Fri Dec 5 10:15:02 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Fri, 5 Dec 2008 10:15:02 -0500 (EST) Subject: pretty strange behavior of "strip" In-Reply-To: References: <4938693F.6090709@yahoo.ca> Message-ID: On Thu, 4 Dec 2008 at 20:54, Terry Reedy wrote: >> 'toc.html' >> > > > test[4].strip('.html') >> 'oc' >> >> Can't figure out what is going on, really. > > What I can't figure out is why, when people cannot figure out what is going > on with a function (or methods in this case), they do not look it up the doc. > (If you are an exception and did, what confused you?) Can you enlighten me? I'm a little embarrassed to admit this, since I've been using python for many years, but until I read these posts I did not understand how strip used its string argument, and I _have_ read the docs. I can't tell you what confused the OP, but I can tell you what confused me. I have often wished that in 'split' I could specify a _set_ of characters on which the string would be split, in the same way the default list of whitespace characters causes a split where any one (or more) of them appears. But instead the string argument is a multi-character separator. (Which is sometimes useful and I wouldn't want to lose the ability to specify a multi-character separator!) My first experience in using the string argument was with split, so when I ended up using it with strip, by analogy I assumed that the string passed to strip would also be a multi-character string, and thus stripped only if the whole string appeared exactly. Reading the documentation did not trigger me reconsider that assumption. I guess I'm just lucky that I haven't run into any bugs (but I think I've used the string argument to strip only once or twice in my career). It would be lovely if both the split and strip methods would have a second string argument that would use the string in the opposite sense (as a set for split, as a sequence match for strip). In the meantime the docs could be clarified by replacing: the characters in the string will be stripped with all occurrences of any of the characters in the string will be stripped --RDM PS: the OP might want to look at th os.path.splitext function. From invalid at invalid Mon Dec 15 11:07:13 2008 From: invalid at invalid (Grant Edwards) Date: Mon, 15 Dec 2008 10:07:13 -0600 Subject: 1 or 1/0 doesn't raise an exception References: <49446E39.6020807@tim.thechases.com> Message-ID: On 2008-12-14, Peter Otten <__peter__ at web.de> wrote: > Grant Edwards wrote: > >> Short circuit evaluation of booleans is very common (and has >> been for decades), so I don't know why people would expect >> something else. > > Visual Basic ;) I should have known... -- Grant Edwards grante Yow! I'm using my X-RAY at VISION to obtain a rare visi.com glimpse of the INNER WORKINGS of this POTATO!! From bearophileHUGS at lycos.com Mon Dec 1 19:43:18 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 1 Dec 2008 16:43:18 -0800 (PST) Subject: optimization References: Message-ID: <6672532a-f162-4717-b0bb-c613214b57db@d32g2000yqe.googlegroups.com> Robert Kern: >I only expect functions to be defined inside of functions if they are going to use lexical scoping for some reason.< There are other reasons to nest functions. One of them is to represent logical nesting of some functionality. So you will find some exceptions to your self-created rule :-) Bye, bearophile From jonas.esp at googlemail.com Mon Dec 1 13:17:00 2008 From: jonas.esp at googlemail.com (Kless) Date: Mon, 1 Dec 2008 10:17:00 -0800 (PST) Subject: Chmod to a group only Message-ID: How to chmod a file to: o-rwx ? (to change only the others mode) os.chmod(fname, ) I was reading this [1], but the truth is that anything as 'S_IRUSR' doesn't help enought. [1] http://www.python.org/doc/2.5.2/lib/os-file-dir.html From rvncerr at gmail.com Thu Dec 25 01:00:01 2008 From: rvncerr at gmail.com (Raven) Date: Wed, 24 Dec 2008 22:00:01 -0800 (PST) Subject: Easy-to-use Python GUI References: Message-ID: <7598a48c-fe14-42da-94a9-645d73ca40bf@s37g2000vbp.googlegroups.com> On 25 ???, 06:47, "Joel Koltner" wrote: > Is there an easy-to-use, "function"-based cross-platform GUI toolkit for > Python out there that's a little more sophisticated than EasyGui? ?EasyGui > looks good, but it's a little more restrictive than what I'd like to have, yet > I'm (stubbornly :-) ) resistant to stepping up to a "full service" GUI toolkit > such as pyGTK or wxPython where it's all about event loops and callbacks and > you need to start planning how the GUI affects the overall program flow rather > than just using a "forms" (or "Wizard")-type approach where you put up a few > dialogs, users fill in some variables, and your program just sits around > waiting until "OK" or "Cancel" is clicked. > > One approach that I like comes from SAX BASIC/WinWrap, which is more or less a > clone of Microsoft's Visual BASIC for Applications, but they (apparently) > wanted everything to still be human-readable, so they have a simple GUI > ("form") builder that generates code that looks like this: > > --- > > ?Begin Dialog UserDialog 850,497,"Export Control" ' %GRID:10,7,1,1 > > ? GroupBox 20,7,360,217,"Drill File Generation",.GroupBox1 > ? CheckBox 40,35,130,14,"Output drill file(s)",.genDrill > ? Text 40,63,270,28,"Identify via layers as any that contain this text in > their names:",.Text > ? TextBox 40,98,220,21,.viaLayerName > ? Text 40,140,100,14,"Output method:",.Text8 > ? DropListBox 160,140,180,21,DrillStyle(),.drillStyle > ? Text 40,175,130,28,"Select drill table units:",.Text2 > ? ListBox 200,175,120,28,unitNames(),.unitName > > ? OKButton 310,469,90,21 > ? CancelButton 410,469,90,21 > > ?End Dialog > > ' GUI builder generates or modifies everything above, but can also be edited > by hand > ' You write the following code... > > ?Dim dlg As UserDialog > > ?dlg.genDrill = 1 > ?ReDim DrillStyle(1) > ?DrillStyle(0) = "All Via Layers In One File" > ?DrillStyle(1) = "One File Per Via Layer" > ?dlg.drillStyle = 1 > > ?func=Dialog(dlg) > > --- > > This is pretty darned easy for me understand and modify either by hand or with > the GUI builder. ?Still, it's quite powerful, since it supports all the common > GUI elements (text, group boxes, checkboxes, drop-down lists, text boxes, > buttons, etc.). ?This is about the level of sophistication I'm looking for. > > Anything like this for Python? > > Thanks, > ---Joel Try PyScripter :) http://mmm-experts.com/Products.aspx?ProductId=4 From upton at virginia.edu Mon Dec 22 12:40:55 2008 From: upton at virginia.edu (Dan Upton) Date: Mon, 22 Dec 2008 12:40:55 -0500 Subject: stable algorithm with complexity O(n) In-Reply-To: References: <0155aef3$0$6988$c3e8da3@news.astraweb.com> <015612ac$0$20639$c3e8da3@news.astraweb.com> <52cfb77e-4baf-4fba-8eac-cc6c7ddb5be5@k1g2000prb.googlegroups.com> <5504f9ac0812150828m14f6999ak6112c5975042dc88@mail.gmail.com> <1ffd301f-16d3-4dc7-988c-7741d658ca10@z28g2000prd.googlegroups.com> Message-ID: <5504f9ac0812220940o7326b2f6p77f9b5bb86a2ed11@mail.gmail.com> On Mon, Dec 22, 2008 at 12:29 PM, wrote: > On Dec 15, 10:00 pm, "cmdrrickhun... at yaho.com" > wrote: >> It can be proven that you cannot sort an arbitrarily large set of >> numbers, given no extra information, faster than O(n log n). > > Cormen Leiserson and Rivest, "Algorithms", have a short clear chapter > on > "Sorting in linear time": > " ... counting sort, radix sort and bucket sort ... use operations > other than comparisons. > Consequently, the Omega( n lg n ) lower bound does not apply to > them." > But the key here is "given no extra information." Your examples of non-comparison sorts require extra information, such as knowledge about the possible range the numbers can take on. From deets at nospam.web.de Wed Dec 24 11:35:13 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 24 Dec 2008 17:35:13 +0100 Subject: SyntaxError: encoding problem: with BOM In-Reply-To: <400f176b-bd9a-4f26-b01b-1aa7c7dcf5ac@z6g2000pre.googlegroups.com> References: <6res8tF1do1sU1@mid.uni-berlin.de> <400f176b-bd9a-4f26-b01b-1aa7c7dcf5ac@z6g2000pre.googlegroups.com> Message-ID: <6rf6m1F1e0f8U1@mid.uni-berlin.de> NoName schrieb: > On 25 ???, 00:37, "Diez B. Roggisch" wrote: >> NoName schrieb: >> >>> i have 1.py in cp866 encoding: >>> # -*- coding: cp866 -*- >>> print ("ff") >>> It's not work in Python 3.0 >>> Error: >>> File "", line 1 >>> SyntaxError: encoding problem: with BOM >>> what's wrong? >> I can only guess, but just because you write the coding-header that >> doesn't mean that the editor you use does actually *use* that encoding. >> What I presume it does is to use utf-8, and write that stupid BOM >> microsoft uses for denoting utf-8-content as first byte. Try using a >> different editor, or alter it's settings to really use your desired >> encoding. >> >> Diez > > I used Far Manager editor. and it *really* used cp866 > I can print hex dump of source file. > I don't want to use UTF-8 for py-file! How about you show us the python file in question? diez From sjmachin at lexicon.net Tue Dec 30 16:54:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 30 Dec 2008 13:54:34 -0800 (PST) Subject: Parsing Excel spreadsheets References: <6a54de23-bea4-40c7-ad7c-22c6eba4bd8a@z6g2000pre.googlegroups.com> <452bfdbc-b6e2-487d-9590-018a414b36a1@s9g2000prg.googlegroups.com> Message-ID: On Dec 31, 5:48?am, Mike Driscoll wrote: > On Dec 30, 10:07?am, "andyh... at gmail.com" wrote: > > > Hi, > > > Can anybody recommend an approach for loading and parsing Excel > > spreadsheets in Python. Any well known/recommended libraries for this? > > > The only thing I found in a brief search was http://www.lexicon.net/sjmachin/xlrd.htm, > > but I'd rather get some more input before going with something I don't > > know. > > > Thanks, > > Andy. > > If you need complete control of Excel, then you'll probably have to > use COM (see Mark Hammond's PyWin32 package). Otherwise, the > suggestions by the others will work. For avoidance of doubt, the OP should presume that you mean the *nett* suggestions by the others i.e. after Tino struck out pyExcelerator. From prabhu.ranjith at gmail.com Sun Dec 7 11:12:53 2008 From: prabhu.ranjith at gmail.com (ranjith) Date: Sun, 7 Dec 2008 08:12:53 -0800 (PST) Subject: @ Start learning through internet @ Message-ID: visit as at www.tiketin.blogspot.com You can learn all the computer languages from your home itself now. Online study. Visit www.tiketin.blogspot.com to start learning through internet and to clear your computer doubts. From clp at rebertia.com Wed Dec 3 22:52:12 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 3 Dec 2008 19:52:12 -0800 Subject: RELEASED Python 3.0 final In-Reply-To: References: Message-ID: <47c890dc0812031952r6d2adbfav20fde92431443751@mail.gmail.com> On Wed, Dec 3, 2008 at 7:47 PM, Daniel Fetchinson wrote: >> On behalf of the Python development team and the Python community, I >> am happy to announce the release of Python 3.0 final. >> >> Python 3.0 (a.k.a. "Python 3000" or "Py3k") represents a major >> milestone in Python's history, and was nearly three years in the >> making. This is a new version of the language that is incompatible >> with the 2.x line of releases, while remaining true to BDFL Guido van >> Rossum's vision. Some things you will notice include: >> >> * Fixes to many old language warts >> * Removal of long deprecated features and redundant syntax >> * Improvements in, and a reorganization of, the standard library >> * Changes to the details of how built-in objects like strings and >> dicts work >> * ...and many more new features >> >> While these changes were made without concern for backward >> compatibility, Python 3.0 still remains very much "Pythonic". >> >> We are confident that Python 3.0 is of the same high quality as our >> previous releases, such as the recently announced Python 2.6. We will >> continue to support and develop both Python 3 and Python 2 for the >> foreseeable future, and you can safely choose either version (or both) >> to use in your projects. Which you choose depends on your own needs >> and the availability of third-party packages that you depend on. Some >> other things to consider: >> >> * Python 3 has a single Unicode string type; there are no more 8-bit >> strings >> * The C API has changed considerably in Python 3.0 and third-party >> extension modules you rely on may not yet be ported >> * Tools are available in both Python 2.6 and 3.0 to help you migrate >> your code >> * Python 2.6 is backward compatible with earlier Python 2.x releases >> >> We encourage you to participate in Python 3.0's development process by >> joining its mailing list: >> >> http://mail.python.org/mailman/listinfo/python-3000 >> >> If you find things in Python 3.0 that are broken or incorrect, please >> submit bug reports at: >> >> http://bugs.python.org/ >> >> For more information, links to documentation, and downloadable >> distributions, see the Python 3.0 website: >> >> http://www.python.org/download/releases/3.0/ >> >> Enjoy, >> - -Barry >> >> Barry Warsaw >> barry at python.org >> Python 2.6/3.0 Release Manager >> (on behalf of the entire python-dev team) > > uname -a > > Linux fetch 2.6.23.1-42.fc8 #1 SMP Tue Oct 30 13:18:33 EDT 2007 x86_64 > x86_64 x86_64 GNU/Linux > > tar xzvf Python-3.0.tgz > cd Python-3.0 > ./configure > make > > Failed to find the necessary bits to build these modules: > _tkinter Do you have Tcl/Tk and their dev libs installed? Tkinter is based on Tcl/Tk. Also, that error isn't fatal, it just means that Tkinter won't be installed because it can't find the libs. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > To find the necessary bits, look in setup.py in detect_modules() for > the module's name. > > > Cheers, > Daniel > > > > > -- > Psss, psss, put it down! - http://www.cafepress.com/putitdown > -- > http://mail.python.org/mailman/listinfo/python-list > From alexoplocatie at gmail.com Wed Dec 17 05:39:10 2008 From: alexoplocatie at gmail.com (aka) Date: Wed, 17 Dec 2008 02:39:10 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> Message-ID: Due to being in a hurry I didn't paste correctly (sorry). The intention is to put values of column 1 ("id") in the roles list, therefore appending within the loop, to fill a session var. The complete code is: roles = [] inp = 'C:/temp/test.csv' try: fp = open(inp, 'rb') reader = csv.reader(fp, dialect='excel', delimiter=';') for r in reader: roles.append(r) ## ultimately should be something like r.id or r[0] ## first row of csv file should be skipped because of column names except: msg = 'Something's wrong with the csv.reader' return dict(file=inp,roles=str(roles)) The roles list isn't populated at all :( From google at mrabarnett.plus.com Fri Dec 5 20:05:17 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 06 Dec 2008 01:05:17 +0000 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: <7c150038-3c2d-4c3c-bb1a-66c8fde57d22@40g2000prx.googlegroups.com> References: <5u8o06xbqf.ln2@joeserver.homelan.net> <0149b28c$0$20670$c3e8da3@news.astraweb.com> <7c150038-3c2d-4c3c-bb1a-66c8fde57d22@40g2000prx.googlegroups.com> Message-ID: <4939CFCD.2030908@mrabarnett.plus.com> John Machin wrote: > On Dec 6, 10:35 am, Steven D'Aprano cybersource.com.au> wrote: >> On Fri, 05 Dec 2008 12:00:59 -0700, Joe Strout wrote: >>>> So UTF-16 has an explicit EOF marker within the text? >>> No, it does not. I don't know what Terry's thinking of there, but text >>> files do not have any EOF marker. They start at the beginning >>> (sometimes including a byte-order mark), and go till the end of the >>> file, period. >> Windows text files still interpret ctrl-Z as EOF, or at least Windows XP >> does. Vista, who knows? > > This applies only to files being read in an 8-bit text mode. It is > inherited from MS-DOS, which followed the CP/M convention, which was > necessary because CP/M's file system recorded only the physical file > length in 128-byte sectors, not the logical length. It is likely to > continue in perpetuity, just as standard railway gauge is (allegedly) > based on the axle-length of Roman chariots. > The chariots in question were drawn by 2 horses, so the gauge is based in the width of a horse. :-) > None of this is relevant to the OP's problem; his file appears to have > been truncated rather than having spurious data appended to it. From python-url at phaseit.net Tue Dec 16 15:39:10 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Tue, 16 Dec 2008 20:39:10 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Dec 16) Message-ID: QOTW: "... Python isn't a major software company - it's better!" - David LeBlanc `timeit` is the right tool to measure execution time of code snippets: http://groups.google.com./group/comp.lang.python/t/9f35d4bde7304ab7/ "Intentionally backward non-compatible" 3.0 is surely the biggest news of the week, or perhaps year: http://www.01net.com/editorial/399456/python-mue-en-une-v3-plus-coherente-mais-retro-incompatible/ Functions and scope explained to beginners: http://groups.google.com./group/comp.lang.python/t/760155a8e7bfd567/ Several experienced pythonistas help improve a beginner's game: http://groups.google.com./group/comp.lang.python/t/3fe51de743b183e5/ Duck typing helps to write a simple NullDate class: http://groups.google.com./group/comp.lang.python/t/e9bf920d5a3bf894/ How to prevent access to certain methods? http://groups.google.com./group/comp.lang.python/t/9910be8b800b66df/ Exploring bidirectional communication of two processes, first using sockets, later using pipes: http://groups.google.com./group/comp.lang.python/t/d90fa17612e6878b/ http://groups.google.com./group/comp.lang.python/t/7a29b036207feee2/ Determining what encoding a certain filename uses may be hard (or even impossible): http://groups.google.com./group/comp.lang.python/t/9274ac2431bee2f3/ Displaying unicode in 3.0: repr(), str(), ascii(), and unprintable characters: http://groups.google.com./group/comp.lang.python/t/a320c6a5d2ce5607/ http://groups.google.com./group/comp.lang.python/t/322a48591c81f089/ When working with Numpy arrays and others, operators like '=3D=3D' or 'in' may present non-obvious behaviour: http://groups.google.com./group/comp.lang.python/t/1fead6e2738bf4f5/ Homework, sorting, complexity, and magnetic monopoles (?): http://groups.google.com./group/comp.lang.python/t/d7bfec4913b2d616/ ======================================================================== 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 Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From manu3d at gmail.com Sat Dec 13 10:03:17 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Sat, 13 Dec 2008 07:03:17 -0800 (PST) Subject: Bidirectional Networking References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> <6qeht0Fc3541U1@mid.individual.net> <782258db-2bdc-45a7-8d8f-7a036d574985@t26g2000prh.googlegroups.com> Message-ID: <2cf74767-e331-4fa6-8915-8f87ba01ca34@l33g2000pri.googlegroups.com> On Dec 12, 9:04 pm, "Gabriel Genellina" wrote: > If you're using 2.5 or older, override serve_forever: > > def serve_forever(self): > while not getattr(self, 'quit', False): > self.handle_request() > > and set the server 'quit' attribute to True in response to some command > from the client. Ok, I've tried this method and it would work if I wanted to shut down the server from the remote client. But if I want the server to shut down from the server itself upon some condition it doesn't work because the while statement is evaluated again only after there has been a request. If requests are infrequent or have ceased the self.handle_request() is never invoked and both the loop and the thread that contains it hang. I wasn't able to set a timeout upon which the handle_request() method returns. I'm not sure why. But I was able to make the original serve_forever() work. The problem was that in my code I used: asyncServer.daemon = True but somehow that doesn't work. I then tried: asyncServer.setDaemon(True) and that does work: when the asyncClient thread ends the only thread left running is the asyncServer, but as it is a daemon thread and there are no non-daemon threads left, the application exits regularly. So, below there's an updated version of my code that works as intended. Thanks for your help! Manu ------------------------- To use the following code, cut&paste into two separate *.py files and invert the port numbers in one file. Then, start them in two separate shells. ------------------------- import SocketServer import socket import threading import random from time import sleep ## Network request handler class MyTCPHandler(SocketServer.StreamRequestHandler): def handle(self): self.data = self.rfile.readline().strip() print "-> RECV: " + self.data + " - Sent by:" + self.client_address[0] ## Server Thread class ServerThread(threading.Thread): def __init__(self, localServer): threading.Thread.__init__(self) self.server = SocketServer.TCPServer(localServer, MyTCPHandler) def run(self): self.server.serve_forever() ## Client Thread class ClientThread(threading.Thread): def __init__(self, remoteServer): threading.Thread.__init__(self) self.remoteServer = remoteServer def run(self): cycle = 0 while cycle < 1000: chance = random.random() if(chance < 0.01): randomNumber = int(random.random() * 1000) message = str(randomNumber) + " from remote cycle " + str(cycle) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(self.remoteServer) sock.send(message + "\n") sock.close() print("SENT ->: "+str(randomNumber)+ " by local cycle "+str(cycle)) except: print("Failed to send number on cycle "+str (cycle)) cycle += 1 sleep(0.01) ## Simulating local/remote servers with different ports localServer = ("localhost", 9999) remoteServer = ("localhost", 10000) serverThread = ServerThread(localServer) serverThread.setDaemon(True) serverThread.start() clientThread = ClientThread(remoteServer) clientThread.start() --------------------------- From istvan.albert at gmail.com Fri Dec 5 23:19:22 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Fri, 5 Dec 2008 20:19:22 -0800 (PST) Subject: Don't you just love writing this sort of thing :) References: Message-ID: On Dec 3, 8:07?pm, Lawrence D'Oliveiro wrote: Originally, like many others here I said YIKES! but on a second read, it is not that bad. It actually grows on you. After looking at it one more time I found it neat, very concise without being unreadable. i. From claird at lairds.us Wed Dec 3 10:47:54 2008 From: claird at lairds.us (Cameron Laird) Date: Wed, 3 Dec 2008 15:47:54 +0000 Subject: Multiple equates References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> Message-ID: In article , Lawrence D'Oliveiro wrote: >In message , Cameron Laird wrote: > >> def shell_escape(Arg) : >> """returns Arg suitably escaped for use as a command-line argument >> to Bash.""" >> >> pattern = r"[\<\>\"\'\|\&\$\#\;\(\)\[\]\{\}\`\!\~\ \\]" >> def f1(Match): >> return "\\" + Match.group(0) >> return re.sub(pattern, f1, Arg) >> # Need to catch anything that might be meaningful to shell >> #end shell_escape > >So why is that better? I'm very lost, now. As best I can remember and/or reconstruct this conversation, the form above is adequately readable and does not involve lambda (and fits in eighty-column lines, and has a few even more mundane features). There's a realm within Pythonia that favors lambdalessness. I think that's all I'm claiming at this point. From taskinoor.hasan at csebuet.org Tue Dec 16 01:56:16 2008 From: taskinoor.hasan at csebuet.org (Taskinoor Hasan) Date: Tue, 16 Dec 2008 12:56:16 +0600 Subject: How can I return a non-zero status result from a python script? In-Reply-To: <5a289491-662c-49f2-98c7-aae100078a8a@r15g2000prd.googlegroups.com> References: <74b53da4-bf07-431b-898b-49977f7a685c@r36g2000prf.googlegroups.com> <5a289491-662c-49f2-98c7-aae100078a8a@r15g2000prd.googlegroups.com> Message-ID: <79153a2e0812152256g42a9059bqd4093411cdc66837@mail.gmail.com> sys.exit() raise SystemExit() exception which could be caught and if not caught, terminate only the current thread. If your program is multi-threaded and you want to terminate the process, i.e all threads, immediately then use os._exit(1) On Tue, Dec 16, 2008 at 7:52 AM, Miki wrote: > Hello, > > > How can I return a non-zero status result from the script? Just do a > > return 1? at the end? > raise SystemExit(1) > > HTH, > -- > Miki > http://pythonwise.blogspot.com > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at hlacik.eu Sun Dec 14 11:03:38 2008 From: david at hlacik.eu (=?ISO-8859-2?Q?David_Hl=E1=E8ik?=) Date: Sun, 14 Dec 2008 17:03:38 +0100 Subject: execution time Message-ID: Hi guys, #! /usr/bin/python import random import bucket2 data = [ random.randint(1,25) for i in range(5)] print "random data : %s" % data print "result: %s" %bucket2.sort(data) How to write a test script which will outputs execution time for bucket2.sort(data) ? Thanks in advance! From geekmail at usenot.de Sun Dec 7 12:10:54 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sun, 7 Dec 2008 18:10:54 +0100 Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> Message-ID: <20081207181054.5de84914@usenot.de> On Sun, 07 Dec 2008 02:49:27 -0500 acerimusdux wrote: > I'm not sure though whether allowing both syntaxes would make things > more or less confusing. It might actually be helpful in some respects > for newcomers to realize that self.method(arg) is somewhat the same > as method(self, arg). [snip] A professor of mine once said something to the effect that in teaching it is not so important to ?*tell* people a lot but to *omit* as much as practically possible. This might be the single most wise thing I have ever heard. If you're a newbee and you know nothing of the language, and probably nothing about programming at all, having two possibilities will thoroughly confuse you. Only when you have a working(!) knowledge of one version will you be able to appreciate the other. Since in this case the other option has no practical benefits whatsoever (IMHO), there's absolutely no need for it. /W PS: I will state again that I do like the idea in itself, its just about 20 years too late for it. -- My real email address is constructed by swapping the domain with the recipient (local part). From dongzhi at gmail.com Wed Dec 10 01:13:48 2008 From: dongzhi at gmail.com (dongzhi) Date: Tue, 9 Dec 2008 22:13:48 -0800 (PST) Subject: List Problem References: Message-ID: <8386b854-8253-48b2-9c9f-eb37973f2aec@o40g2000prn.googlegroups.com> On Dec 10, 2:00?pm, "James Mills" wrote: > On Wed, Dec 10, 2008 at 3:40 PM, dongzhi wrote: > > If I execute part[1], I have got ?'a'. If I execute part[2], I have > > got ' '. But, if I execute part[1::2], I have got ['a', '', '']. I > > don't know why. Please tell me why. > > Perhaps you meant: > > part[1:2] > > pydoc list > > This will tell you there are 3 arguments to __getslice__ > i, j, y > > Without doing any further reading I > presume from my experience that > this works much like range and xrange > and that the 3rd parameter is the step > size. > > Consider this: > > > > >>> x = [9, 1, 2, 3, 4] > >>> x > [9, 1, 2, 3, 4] > >>> x[1:2] > [1] > >>> x[1::2] > [1, 3] > >>> x[1::1] > [1, 2, 3, 4] > >>> x[1::2] > [1, 3] > >>> x[1::3] > [1, 4] > > cheers > James > > -- > -- > -- "Problems are solved by method Dear James Mills, Thanks a lot. Now, I know the reason. Best Regards, Liu Ming From shangach at gmail.com Wed Dec 3 14:43:00 2008 From: shangach at gmail.com (ShanMayne) Date: Wed, 3 Dec 2008 11:43:00 -0800 (PST) Subject: Switching windows in PyQT Message-ID: <9ef85e1f-9e46-48b6-8d11-a4f6e7176657@d23g2000yqc.googlegroups.com> Greetings All I am new to PyQT and GUI programming in general. What tutorials I have found are relatively clear on standard operations within a single window (QtGui.QWidget or QtGui.QMainWindow). Exiting this window exits the overall application. How would I switch between windows, that is close one and open another, within a running application. I would imagine this to be a standard feature often coded. My thanks Shannon From bockman at virgilio.it Tue Dec 30 13:19:08 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: Tue, 30 Dec 2008 19:19:08 +0100 Subject: select.select and socket.setblocking In-Reply-To: References: Message-ID: <495a661d$0$11384$5fc30a8@news.tiscali.it> Laszlo Nagy ha scritto: > I'm using this method to read from a socket: > > def read_data(self,size): > """Read data from connection until a given size.""" > res = "" > fd = self.socket.fileno() > while not self.stop_requested.isSet(): > remaining = size - len(res) > if remaining<=0: > break > # Give one second for an incoming connection so we can stop the > # server in seconds when needed > ready = select.select([fd], [], [], 1) > if fd in ready[0]: > data = self.socket.recv(min(remaining,8192)) # 8192 is > recommended by socket.socket manual. > if not data: > # select returns the fd but there is no data to read > -> connection closed! > raise TransportError("Connection closed.") > else: > res += data > else: > pass > if self.stop_requested.isSet(): > raise SystemExit(0) > return res > > > This works: if I close the socket on the other side, then I see this in > the traceback: > > File "/usr/home/gandalf/Python/Projects/OrbToy/orb/endpoint.py", line > 233, in read_data > raise TransportError("Connection closed.") > TransportError: Connection closed. > > Also when I call stop_requested.set() then the thread stops within one > seconds. > > Then I switch to non blocking mode, my code works exactly the same way, > or at least I see no difference. > > I have read the socket programming howto ( > http://docs.python.org/howto/sockets.html#sockets ) but it does not > explain how a blocking socket + select is different from a non blocking > socket + select. Is there any difference? > > Thanks > Couple of remarks: 1. AFAIK, select in python accepts also socket objects, or anything which has a fileno() method returning an integer. So you don't need to extract the fileno from the socket (python will do for you) although it does no harm. 2. IMO, the behaviour of your code is correct: with TCP protocol, when the remote ends disconnects, your end receives a 'read event' without data; you should just handle the fact that recv returns nothing as normal, not as error, and close your end of the connection. If you are interested in socket errors, you should also fill the third 'fd-set' in the select call, and after select returns check that fd is not in it anymore: ready = select.select( [fd],[], [fd] ) if fd in ready[2]: # raise your error here 3. AFAIK (sorry, I feel acronym-ly today ;), there is no difference in select between blocking and non-blocking mode. The difference is in the recv (again, assuming that you use TCP as protocol, that is AF_INET, SOCK_STREAM), which in the blocking case would wait to receive all the bytes that you requested, or the disconnection, in the other case would return immediately (and you should check the number of returned bytes, and when you read the remaining bytes of the message put the pieces together). I myself tend to avoid using non-blocking sockets, since blocking sockets are much easier to handle... HTH Ciao ------ FB From pavlovevidence at gmail.com Fri Dec 19 21:11:51 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 19 Dec 2008 18:11:51 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <1332da3c-8075-4552-9498-3ceb23faca8f@v31g2000vbb.googlegroups.com> Message-ID: On Dec 19, 7:12?pm, r wrote: > Marc, > Why move away from a concise and widely accepted way of sting > formatting, just to supposedly make it a little easier for n00bs? You were the one that brought it up, chief. I doubt anyone is arguing that this new formating was added just to make things easier for newbies, we're just saying that your assertion that printf-style is much easier for newbies is wrong. If you care to, go read the rationale for this change PEP 3101. You'd see the new formating was added to address limitations of the printf- style. (Hint: the limitations aren't that %s, %d, and %f are hard to remember.) > *It may be time to start hacking my own personal version of the Python > interpreter. hmm... Keep you ears to the ground... My friend, if you can't even cope with a new system of string formating, do you really expect to be able to maintain your own hacked- up fork of a highly wrought out programming language? Carl Banks From ivan.illarionov at gmail.com Tue Dec 23 16:12:57 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 23 Dec 2008 13:12:57 -0800 (PST) Subject: Beep References: Message-ID: <06d8d28f-dd63-4952-9e0c-97271871dfcd@w24g2000prd.googlegroups.com> On Dec 22, 3:16?am, Jeffrey Barish wrote: > I use sys.stdout.write('\a') to beep. ?It works fine on Kubuntu, but not on > two other platforms (one of which is Ubuntu). ?I presume that the problem > is due to a system configuration issue. ?Can someone point me in the right > direction? ?Thanks. > -- > Jeffrey Barish gnome-terminal (default terminal on Ubuntu) uses X11 bell for its beep. Try 'xset b on' to turn the beep on. See 'man xset' for more options. Ivan From ivan.illarionov at gmail.com Tue Dec 9 04:33:37 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 9 Dec 2008 01:33:37 -0800 (PST) Subject: Catching Python exceptions in C References: Message-ID: <72713421-97ed-453f-8f2f-06cc5f0ca355@o40g2000prn.googlegroups.com> On Dec 8, 9:42?pm, Senthil Kumar wrote: > Hi Pythoneers ! > Can somebody give a quick solution? > I am trying to raise exceptions in python and trying to handle it in > C. > I am able to raise exceptions successfully. However could not catch > those in C. > I am using the following function to run the python from C: > Pyrun_SimpleString(). > After the exception is raised, I am checking PyErr_Occurred(). It > always returns NULL, and I cannot catch the exception. > Pls help me a way out. > > Thanx in advance ! I use something like this: if (PyErr_Occurred()) { if (PyErr_ExceptionMatches(ExceptionName)) { /* do something about ExceptionName */ } else if (PyErr_ExceptionMatches(AnotherExceptionName)) { /* if we want to get the exception string */ PyObject *errtype, *errvalue, *traceback; PyErr_Fetch(&errtype, &errvalue, &traceback); if(errvalue != NULL) { PyObject *s = PyObject_Str(errvalue); /* Now 'PyString_AS_STRING(s)' contains C string of error message do something with it */ Py_DECREF(s); } Py_XDECREF(errvalue); Py_XDECREF(errtype); Py_XDECREF(traceback); } } Goof luck. From prologic at shortcircuit.net.au Sun Dec 21 17:26:17 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Dec 2008 08:26:17 +1000 Subject: Twisted for non-networking applications In-Reply-To: <82e49b84-43c9-452f-a139-c77378c12908@a12g2000pro.googlegroups.com> References: <82e49b84-43c9-452f-a139-c77378c12908@a12g2000pro.googlegroups.com> Message-ID: On Mon, Dec 22, 2008 at 4:27 AM, Kottiyath wrote: > Hi all, > Is it a good idea to use Twisted inside my application, even though > it has no networking part in it? > Basically, my application needs lots of parallel processing - but I > am rather averse to using threads - due to myraid issues it can cause. > So, I was hoping to use a reactor pattern to avoid the threads. I am > using twisted in another part of the application for networking, so I > was hoping to use the same for the non-networking part for reusing the > reactor pattern. > If somebody can help me on this, it would be very helpful. Alternatively you could give circuits (1) a go. It _can_ be a nice alternative to Twisted and isn't necessarily focused on Networking applications. cheers James 1. http://trac.softcircuit.com.au/circuits/ From lie.1296 at gmail.com Mon Dec 15 17:54:33 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 15 Dec 2008 22:54:33 +0000 (UTC) Subject: alt.possessive.its.has.no.apostrophe References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> <4f36bf19-40f2-4e88-8867-18a760000120@u18g2000pro.googlegroups.com> Message-ID: On Mon, 15 Dec 2008 11:53:40 -0800, Carl Banks wrote: > > (...For that matter, if the rule had been, "Never augment your words > spelling with an apostrophe", it would have really simplified > things....) Th next dae, wee aul wil bee speling liek this From ang.usenet at gmail.com Mon Dec 29 11:14:07 2008 From: ang.usenet at gmail.com (Aaron Gray) Date: Mon, 29 Dec 2008 16:14:07 -0000 Subject: HTML Correctness and Validators References: <2fb289be-00b3-440a-b153-ca88f0ba16c5@d42g2000prb.googlegroups.com> Message-ID: <6rsbahF33ndvU1@mid.individual.net> "Xah Lee" wrote in message news:2fb289be-00b3-440a-b153-ca88f0ba16c5 at d42g2000prb.googlegroups.com... >recently i wrote a blog essay about html correctness and html >validators, with relations to the programing lang communities. I hope >programing lang fans will take more consideration on the correctness >of the doc they produces. > >HTML Correctness and Validators >. http://xahlee.org/js/html_correctness.html Do you enjoy spamming comp.lang.functional with OT cross-posts ? Regards, Aaron From gagsl-py2 at yahoo.com.ar Wed Dec 10 10:37:12 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 10 Dec 2008 13:37:12 -0200 Subject: SequenceMatcher bug ? References: <67253331-5b36-4018-b15a-c0b86c5342d3@r37g2000prr.googlegroups.com> Message-ID: En Wed, 10 Dec 2008 12:00:30 -0200, escribi?: > On Tue, 9 Dec 2008 at 22:15, eliben wrote: >> On Dec 10, 4:12?am, rdmur... at bitdance.com wrote: >>> On Mon, 8 Dec 2008 at 23:46, eliben wrote: >>>> This is about Python 2.5.2 - I don't know if there were fixes to this >>>> module in 2.6/3.0 >>> >>>> I think I ran into a bug with difflib.SequenceMatcherclass. >>>> Specifically, its ratio() method. The following: >>> >>>> SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + [5]).ratio >>>> () >>> >>>> returns 0.0 >>> >>>> While the same with 500 replaced by 100 returns .99... something >>>> Looking at the code ofSequenceMatcherthere's some caching going on >>>> when the sequences are longer than 200 elements (and indeed, I can >>>> reproduce the bug above 200 but not below). Can anyone confirm that >>>> this misbehaves and suggest a workaround ? >>> >>> Python 2.5.2 (r252:60911, Sep 29 2008, 20:34:04) >>> [GCC 4.3.1] on linux2 >>> Type "help", "copyright", "credits" or "license" for more >>> information.>>> from difflib importSequenceMatcher >>>>>> SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + >>>>>> [5]).ratio() >>> >>> 0.99900299102691925 >>> >> >> Strange. I could reproduce the problem both on ActiveState Python >> 2.5.2 for Windows, and in the online Try Python evaluator: >> >> http://try-python.mired.org/ > > My system is Gentoo, which installs python from source. Maybe gentoo > applies patches that the binary releases don't have. I can't reproduce the problem. I got exactly the same results (0.999...) with all the releases I have at hand, ranging from 3.0 back to 2.1.3, all on Windows. And http://try-python.mired.org/ says the same thing. -- Gabriel Genellina From prahaai at gmail.com Sat Dec 13 01:17:57 2008 From: prahaai at gmail.com (Cro) Date: Fri, 12 Dec 2008 22:17:57 -0800 (PST) Subject: HGE and Python (again) References: <8180969e-9289-4f8c-ab80-30fbc50914d1@g17g2000prg.googlegroups.com> <6qdl1dFc3e1tU1@mid.uni-berlin.de> Message-ID: <1e95a808-70e5-44e9-a779-06bea89a786b@a37g2000pre.googlegroups.com> Good day. Thank you so much for your answer Diez! I managed to call HGE dll the way you told: >>> HGE = windll.LoadLibrary("C:/hge181/hge") >>> HGE.hgeCreate(0x180) But it's not helpful. It would mean that i have to re-create all the header files from "include" directory in python, and all helper functions from the "libs" to be able to use hge in the same way as the original. So ctypes is not what i need. It's a big step! I also tried swig, a lot. A lot, a lot, a lot of examples. Hacking examples and stuff. And i managed to compile "hge.h" header and call the structs and HGE main class. I don't seem to be able to acces the "enums", but that's not a big problem. How i did that, if anyone wants to know: There are 4 files. - There is "example.cxx", that includes "hge.h" in the proper C++ way and defines a HGE* hge=0 just like in the tutorials. - Then is "hge.h", the original file, with ONE line commented: line 408 with the DLL EXPORT. Ah, and one more thing. I had to delete ALL "CALL" keywords from HGE class, because if one CALL appears, the swig compiler flags the line as error. So, for now, no stdcall. - Then is "example.i", with "#include "hge.h"" and "%include "hge.h"". Simple as that. - And then, there is setup.py. "example_module = Extension('_example', sources=['example_wrap.cxx', 'example.cxx'],)" That's it. I compile it all like this: swig -c++ -python example.i setup build_ext --inplace So it's a huge step for me. The compiler i have in my system is mingw-3.4.5. I don't know if it's good for this. Maybe i should try a MS compiler instead? Next things i want to do: - try to compile the project with a MS compiles. Visual studio 7.1 or somethin. - learn if i can do stdcalls from swig !!! This is the most important. - try to compile one normal hge tutorial WITHOUT including "hge.lib" and "hgehelp.lib". All functions defined there can be included just like normal headers, the source is there and i compiled the libs myself. I need this step because i don't think i can include lib files in a swig project. - try to do all i did in swig, with Cython. It's pretty easy to use and faster from what i know. So i must learn to to stdcalls from swig. Can anyone suggest how to do that? I mean, i have lines like: virtual void CALL Release(); // in HGE class. And: void CALL HGE_Impl::Release() { //... // In the "c" file. } , where CALL is defined as "#define CALL __stdcall". I simply can't make this kind of classes so work in swig. Thank you very much. From dotancohen at gmail.com Thu Dec 4 15:56:03 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 4 Dec 2008 22:56:03 +0200 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> Message-ID: <880dece00812041256x227af79agf9a22226215f3330@mail.gmail.com> 2008/12/4 Mark Summerfield : > Now that Python 3 final has been released I thought it would be a good time > to mention that there's a new book to go with it: > > "Programming in Python 3: > A Complete Introduction to the Python Language" > ISBN 0137129297 > http://www.qtrac.eu/py3book.html > > I've been working on this for more than a year, testing the examples > against every Python 3 alpha and beta, and against the final release (using > Python's unit test and doctest modules of course:). > > The book has just gone into production and should be available in print at > the end of this month in the U.S., and a month or two later elsewhere. The > book's web page has links to a draft of the introduction and to safari > books online where you can read extracts. > > The book is aimed at a wide audience, but assumes some programming > experience (not necessarily Python, not necessarily object-oriented). It > teaches solid procedural style programming, then builds on that to teach > solid object-oriented programming, and then goes on to more advanced topics > (e.g., including a nice way to create validated attributes by combining > class decorators with descriptors). But even newcomers to Python 3 should > be able to write useful (although small and basic) programs after reading > chapter 1, and then go on to create larger and more sophisticated programs > as they work through the chapters. > I will ask my university bookstore to get a copy, though by experience it probably won't get there until Python 4! They just now got a Fedora 3 book in stock that I requested eons ago. If I decide to buy online, what is most favourable for you? Amazon? Direct order? I need shipping to Israel. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-??-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From fetchinson at googlemail.com Sat Dec 27 22:51:02 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 27 Dec 2008 19:51:02 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: >>> You MUST check EVERY function call for errors! >> >> Yes, I know :) >> > > Believe me, if you don't, there is a risk of crashing the program. And > they're a lot harder to find and fix. Sure, what I meant by the smiley is just that it was a quick and dirty example, not real code. In a real code I do check these sorts of things. >>> And check the argument's type (how do you know it is a list?). Once you >>> are sure the first parameter *is* a list, you may use the "macro" >>> version >>> of several functions, like PyList_GET_SIZE and PyList_GET_ITEM. >> >> The macro versions are preferable because they are faster? > > Yes, because they don't do any additional checking. PyList_GET_ITEM just > retrieves the item; PyList_GetItem checks whether it is called on a list > object, then checks if index is out of bounds, and only then goes to > retrieve the item. Thanks, I was wondering what the difference between these versions are, now it's clear. >>> You should check that both lists have the same length too. >>> And you should check that elements are integers, or convertible to >>> integers (in case of error, PyInt_AsLong returns -1 and PyErr_Occurred() >>> is true) >>> To fill the resulting tuple, use PyTuple_SET_ITEM instead. BTW, why >>> return >>> a tuple and not a list? >> >> No particular reason, other than the fact that I won't need to modify >> these lists/tuples from python so whenever something will not change, >> I use a tuple because it's immutable. Or this is not a very good >> practice? There is no difference between lists and tuples in terms of >> speed I suppose (getitem, setitem, etc). > > Usually lists represent an ordered collection of similar items, where > position is not relevant (the third item is treated more or less the same > as the tenth); by example, a list of attendants to certain event. It makes > sense to process the whole list doing the same thing to each element, and > it makes sense to ask "is this item in the list?." > > Tuples represent an ordered collection of dissimilar items, where position > is relevant (because it identifies each item); by example, a row from a > database table (name, address, age, phone number), or a point (x,y,z) in > space. It isn't common to process the whole tuple doing the same thing for > each element, and usually it doesn't make sense to look for certain item > in the tuple. But it does make sense to refer to individual items like > t[2], or t.age (namedtuple, 2.6 and up) > > From this point of view, lists and tuples are conceptually different - > tuples aren't "frozen" lists. But this is just common usage, or maybe > historical intent; of course you are free to use whatever structure you > feel adequate. > > Once the list/tuple is created and filled, there is no speed difference > accessing the individual items. Creating an empty list that grows one > element at a time is slow for large lists (the memory block has to be > re-allocated and copied over evry time it gets full) but this doesn't > happen if you provide the final size when creating the list. All right, this is clear then too, I'll probably use a list. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From andre.roberge at gmail.com Tue Dec 9 06:26:51 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Tue, 9 Dec 2008 03:26:51 -0800 (PST) Subject: Google Summer of Code 2009 References: <713dd4d7-0427-4b74-a5bc-1e3538afed6c@n10g2000vbl.googlegroups.com> Message-ID: On Dec 8, 10:34?pm, Eric wrote: > Hello, > I am interested in participating in Google Summer of Code 2009, > hopefully for something in Python. ?I realize that this is way before > it begins, but I would like to start to get to know the community > better and find something that I could work on during the summer of > code. ?I know a decent amount of Python, and I am a Sophomore Computer > Science major. ?My school teaches Java, but on the side I taught > myself Python. ?If anyone knows of any projects that could use another > hand, I would appreciate it. > > Thanks, > Eric You should have a look at http://wiki.python.org/moin/SummerOfCode It's still early, so there's nothing yet for 2009, but I am sure that some ongoing projects mentioned in previous years [like Crunchy ;-)] will be looking for volunteers. Andr? From sjmachin at lexicon.net Mon Dec 29 04:34:15 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 29 Dec 2008 01:34:15 -0800 (PST) Subject: why cannot assign to function call References: Message-ID: <97a11245-a034-4558-82d4-0c87e02bdb7e@u18g2000pro.googlegroups.com> On Dec 29, 5:01?pm, scsoce wrote: > I have a function return a reference, Stop right there. You don't have (and can't have, in Python) a function which returns a reference that acts like a pointer in C or C+ +. Please tell us what manual, tutorial, book, blog or Usenet posting gave you that idea, and we'll get the SWAT team sent out straight away. > and want to assign to the > reference, simply like this: > ?>>def f(a) > ? ? ? ? ? return a That's not a very useful function, even after you fix the syntax error in the def statement. Would you care to give us a more realistic example of what you are trying to achieve? > ? ? ?b = 0 > ? ? * f( b ) = 1* Is the * at the start of the line meant to indicate pointer dereferencing like in C? If not, what is it? Why is there a * at the end of the line? > but the last line will be refused as "can't assign to function call". > In my thought , the assignment is very nature, Natural?? Please tell us why you would want to do that instead of: b = 1 >?but ?why the interpreter > refused to do that ? Because (the BDFL be praised!) it (was not, is not, will not be) in the language grammar. From nytrokiss at gmail.com Thu Dec 4 15:52:40 2008 From: nytrokiss at gmail.com (James Matthews) Date: Thu, 4 Dec 2008 22:52:40 +0200 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> Message-ID: <8a6b8e350812041252p61049e98i144f27043b0a4ef0@mail.gmail.com> I am going to be checking Amazon now and ordering the book. Thanks James On Thu, Dec 4, 2008 at 9:42 PM, Alan G Isaac wrote: > Mark Summerfield wrote: > >> "Programming in Python 3: >> A Complete Introduction to the Python Language" >> ISBN 0137129297 >> http://www.qtrac.eu/py3book.html >> > > > OMG, you really wrote it in Lout? > I wish you would add to > http://www.qtrac.eu/lout.html > a comment on what you get out of that > (compared to using e.g., LaTeX or > reStructuredText). > > Anyway, congrats on the book! > I've asked my library to order it. > > Alan Isaac > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.astorandblack.com/ http://www.jewelerslounge.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From mmanns at gmx.net Thu Dec 18 19:49:32 2008 From: mmanns at gmx.net (mmanns at gmx.net) Date: Fri, 19 Dec 2008 01:49:32 +0100 Subject: Which sparse matrix package? References: <20081218231851.70dd91e2@Schlamber.localdomain> Message-ID: <20081219014932.7846a547@Schlamber.localdomain> On Fri, 19 Dec 2008 08:33:28 +1000 "James Mills" wrote: > > The dict that I tried out is of the type: > > > > {(1,2,3): "2323", (1,2,545): "2324234", ... } > > > > It is too slow for my application when it grows. One slicing > > operation with list comprehensions takes about 1/2 s on my computer > > for 1E6 elements. > > Let me get this straight. > It's taking 0.5s to slice your matrix > of 1E7 (10000000.0 rows/columns) My benchmark is as follows: 1) Each of the numbers in the 3-tuple is in the range [0, 1E7). 2) There are 1 000 000 elements in the dict (randomly distributed). 3) The content string is a random number in the range [0, 1E10) that is casted into a string. 4) Measure the time that retrieving all elements in a 10000x100x10 cube requires. > Are you mad ? This is TEN Millions and you > required it faster than 0.5s ? Think about how often a spreadsheet re-calculates cells. Furthermore, people tend to copy&paste cells. I had some small example (Wagner-Whitin algorithm demo) with hundreds of slicing operations on one screen. I believe that no-one wants to wait for 1/2 s times 500 == 250 s each time the spreadsheet is updated. Martin From benjamin.kaplan at case.edu Tue Dec 23 17:46:46 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 23 Dec 2008 17:46:46 -0500 Subject: SuSE11.1 eclipse 64 pydev can't add python path In-Reply-To: References: Message-ID: On Tue, Dec 23, 2008 at 5:08 PM, Nikolas Tautenhahn wrote: > Hi, > > Reimar Bauer wrote: > > I can install pydev using the update manager in eclipse for 64 bit from > the > > SuSE 11.1 repo. But I can't configure pydev without crashing it. > > I can select the interpreter /usr/bin/python > > and I do see the System PYTHONPATH > > Forced builtin libs also looks good. > > > > But Apply gives me > > # > > # An unexpected error has been detected by Java Runtime Environment: > > # > > # SIGSEGV (0xb) at pc=0x00007f2d7abebaed, pid=6544, tid=139832007596368 > > # > > # Java VM: IcedTea 64-Bit Server VM (1.7.0-b24 mixed mode linux-amd64) > > # Problematic frame: > > # V [libjvm.so+0x21baed] > > # > > # An error report file with more information is saved as: > > # /home/user/hs_err_pid6544.log > > # > > # If you would like to submit a bug report, please visit: > > # http://icedtea.classpath.org/bugzilla > > # The crash happened outside the Java Virtual Machine in native code. > > # See problematic frame for where to report the bug. > > unfortunately I can't help but reproduce the problem. My eclipse was > already configured when I updated openSuSE 11.0 to 11.1 so it is not > *that* bad for me (only when I install new eggs and want pydev to take > notice of them). > > The question is who is responsible for this... java? pydev? (suse?) If it was a PyDev problem, you'd see either a Python or a Java error message. This is a known bug in the HotSpot VM on Linux 64. It affects both the Sun and OpenJDK versions of Java. It was fixed in the newer builds. > > > If you open a ticket in a bugtracker, please post the url here and I > will add myself, too > > Best regards, > Nikolas Tautenhahn > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rt8396 at gmail.com Sat Dec 20 19:11:43 2008 From: rt8396 at gmail.com (r) Date: Sat, 20 Dec 2008 16:11:43 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <7fc23c41-6bf8-4272-b405-acc092cbac87@r15g2000prd.googlegroups.com> On Dec 20, 5:27?pm, walterbyrd wrote: > On Dec 19, 10:25?am, Michael Torrie wrote: > > > Personally the new string formatter is sorely needed in Python. ? > > Really? You know, it's funny, but when I read problems that people > have with python, I don't remember seeing that. Loads of people > complain about the white space issue. Some people complain ?about the > speed. Lots of complaints about certain quirky behavior, but I have > not come across any complaints about the string formatting. > > In fact, from what I have seen, many of the "problems" being "fixed" > seem to be non-problems. > > I dunno, maybe it's just me. You are exactly right Walter. I have not even considered this angle yet. Most of the complaints i hear are the redundant use of self. Which I lamented about but have become accustom(brainwashed) to it. I would remove this if it where up to me. I also hear a lot of complaints about speed. But never once in my life a problem with new users and string formatting. hmmm... food for thought From exarkun at divmod.com Tue Dec 30 15:55:51 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 30 Dec 2008 15:55:51 -0500 Subject: select.select and socket.setblocking In-Reply-To: Message-ID: <20081230205551.20272.583407013.divmod.quotient.29339@ohm> On Tue, 30 Dec 2008 14:41:17 -0600, Grant Edwards wrote: >On 2008-12-30, Francesco Bochicchio wrote: > >> 3. AFAIK (sorry, I feel acronym-ly today ;), there is no difference in >> select between blocking and non-blocking mode. The difference is in the >> recv (again, assuming that you use TCP as protocol, that is AF_INET, >> SOCK_STREAM), which in the blocking case would wait to receive all the >> bytes that you requested, > >No, in blocking mode it will wait to receive _some_ data (1 or >more bytes). The "requested" amount is strictly an upper >limit: recv won't return more than the requested number of >bytes, but it might return less. Hi Grant, I don't think you read Francesco's message carefully enough. :) He said: >>there is no difference in select between blocking and non-blocking mode. You're describing a difference in recv, not select. > >In non-blocking mode, it will always return immediately, either >with some data, no data (other end closed), or an EAGAIN or >EWOULDBLOCK error (I forget which). > >> [...] I myself tend to avoid using non-blocking sockets, since >> blocking sockets are much easier to handle... > >That depends on whether you can tolerate blocking or not. In >an event-loop, blocking is generally not allowed. > If you're careful, it's possible to avoid blocking, even when using a blocking socket, at least for AF_INET, SOCK_STREAM sockets. Of course, it's easier to avoid blocking by using a non-blocking socket. Jean-Paul From python.list at tim.thechases.com Thu Dec 11 13:57:18 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 11 Dec 2008 12:57:18 -0600 Subject: get todays files In-Reply-To: <49415258.2010101@doadesweb.co.uk> References: <4632c353-0462-485b-9e1b-6a5c56682363@s9g2000prg.googlegroups.com> <494015F7.3020302@tim.thechases.com> <49415258.2010101@doadesweb.co.uk> Message-ID: <4941628E.7070902@tim.thechases.com> > I know this will sound like I am being very cheeky, but is there a way > you can make this for where the ftp server is actually windows server? For Windows Server, I don't have a Windows FTP server to test with -- I've got the company Linux server, and the previous testing site I used (I think I used ftp.mozilla.org) which also likely runs some flavor of Linux. Neither supports the NLST from my testing. > curr_date = strftime("%d %B %Y", gmtime()) The first thing I noticed was that your strftime formating needs to match the format of the date that comes back from the FTP site. In my test, that was "YYYYMMDD". As such, your "%d %B %Y" would likely need to be "%Y%m%d". > ftp.retrlines('NLST',makelist) The servers I tried didn't support the NLST command so I can't exactly follow along here. However assuming that it correctly populates the list of files here > for ff in files: correctly, that's immaterial to me. > ftp = FTP(ftp_server) > ftp.set_pasv(False) > resp = ftp.login(ftp_uname,ftp_pwd) Just curious why you're logging into the server each pass through the loop -- I'd just connect once at the beginning of the loop, pull the files, and then disconnect at the end of the loop. > assert code == "213", "Unexpected result" Does this assert fail at any point? > if stamp[:8] == today: Given the above date-formatting, this should fail *every* time unless your FTP server is returning the date in some format other than "YYYYMMDDhhmmss" It's hard to pinpoint actual problems as this block of code has been modified, or doesn't run...there's some bogus indentation in your post: > log('Transferring: ' + ff[0]) > # make parameters to wget the backup file > params = ' ftp://' + ftp_server + '/' + ff[0] > rcode = subprocess.call('c:/wget.exe ' + params) > log('Return code from wget = ' + str(rcode)) > if (rcode == 0): > ff[1] = 1 > > else: > log('File ' + ff[0] + ' already exists locally, not > transferring') because this "else" is hanging oddly. Additionally, the FTP object has methods for downloading the content of a file, so I'd not bother shelling out to wget as an additional dependency. -tkc From robert.kern at gmail.com Thu Dec 18 18:16:19 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 18 Dec 2008 17:16:19 -0600 Subject: Python lex settings In-Reply-To: <0dfeb0c3-a524-4a72-aafd-4b88b71ff16c@w39g2000prb.googlegroups.com> References: <0dfeb0c3-a524-4a72-aafd-4b88b71ff16c@w39g2000prb.googlegroups.com> Message-ID: Sergey Shepelev wrote: > Hello. > > I'm trying to make almost-Python source to Erlang source translation > tool. > > Are there ready ply.lex settings for parsing python source? Yes! Andrew Dalke has implemented a PLY grammar for Python for experimenting with almost-Python languages. http://www.dalkescientific.com/Python/python4ply.html -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sjmachin at lexicon.net Tue Dec 9 01:14:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 8 Dec 2008 22:14:34 -0800 (PST) Subject: fuzzy or boolean text search References: <104335ff-e507-4429-9ad3-baecb63da8b3@k36g2000yqe.googlegroups.com> Message-ID: On Dec 9, 4:36?pm, n00b wrote: > hi, > > i'm looking for advice/suggestions for text search, preferably with > boolean or even fuzzy capabilities, and for use with mysql innodb > tables. ?asking too much :) ??? No ... feeding "fuzzy boolean text search mysql innodb" to my googler didn't choke it; it produced this at about the 15th hit: http://www.sphinxsearch.com/docs/manual-0.9.8.html Please tell your googler that we all hope that it gets well soon :-) From lie.1296 at gmail.com Fri Dec 12 16:18:36 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 12 Dec 2008 21:18:36 +0000 (UTC) Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> Message-ID: On Fri, 12 Dec 2008 11:50:38 -0500, Steve Holden wrote: > Kirk Strauser wrote: >> At 2008-12-12T15:51:15Z, Marco Mariani writes: >> >>> Filip Gruszczy?ski wrote: >>> >>>> I am not doing it, because I need it. I can as well use "if not elem >>>> is None", >> >>> I suggest "if elem is not None", which is not quite the same. >> >> So what's the difference exactly? "foo is not None" is actually >> surprising to me, since "not None" is True. "0 is True" is False, but >> "0 is not None" is True. Why is that? > > "is not" is an operator, so the parse is > > foo (is not) None > > not > > foo is (not None) > Personally, I'd prefer VB's version: foo IsNot bar or in pseudo-python foo isnot bar since that would make it less ambiguous. From prologic at shortcircuit.net.au Mon Dec 29 20:40:10 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 30 Dec 2008 11:40:10 +1000 Subject: multiprocessing vs thread performance In-Reply-To: <26f7d44e-552c-41e9-9290-17e5c4e6deb9@q30g2000prq.googlegroups.com> References: <26f7d44e-552c-41e9-9290-17e5c4e6deb9@q30g2000prq.googlegroups.com> Message-ID: On Tue, Dec 30, 2008 at 11:34 AM, Aaron Brady wrote: > The OP may be interested in Erlang, which Wikipedia (end-all, be-all) > claims is a 'distribution oriented language'. I would suggest to the OP that he take a look at circuits (1) an event framework with a focus on component architectures and distributed processing. I'm presently looking at Virtual Synchrony and other distributed processing architectures - but circuits is meant to be general purpose enough to fit event-driven applications/systems. cheers James 1. http://trac.softcircuit.com.au/circuits/ From lance.ellinghaus at eds.com Mon Dec 22 13:42:52 2008 From: lance.ellinghaus at eds.com (Ellinghaus, Lance) Date: Mon, 22 Dec 2008 13:42:52 -0500 Subject: Python's popularity In-Reply-To: <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> Message-ID: <752A61D5C34D41478E638FC92AF9051B03563493@usahm207.amer.corp.eds.com> > I just look at the stats for comp.lang.python, and i am 9th place for > most post this month. That makes me completely sad. With just 50 post > so far, i am showing up on the high count. Sad, very sad. Now i have > much reason to believe that only 100 or so people follow this list :(. > Python is slipping. We must try harder, or all of Guido's work will be > for nothing! Maybe most of us are doing real things with Python and not spending our time on the list posting. (I normally do not post on here, but I felt I had to now). I have used Python since 0.9.x and have brought it into every project/contract that I have worked on. The current project I am on tried to get rid of it and move to Perl for all of my code.. All of those people are gone and I am still here and so is Python. As a matter of fact, Python use has grown greatly and we rely on it for so many of our day to day operations, monitoring, data collection, etc. Python is not going away just because people are not posting here. Wake up! BEA and IBM have converted all of their custom script language support for WebLogic and WebSphere over to Jython because they felt Python (interfacing with Java) was the best solution to their script language issues. Everyone on the project I am on that works with WebLogic and WebSphere are learning Python so they can work with it. So far, no real complaints. People are moving away from Perl to Python for much of their scripting, but it will take a long time to complete. There is a lot of training, re-coding, and trying to figure out what the original Perl code did (ever try to go back and look at Perl code that is 2-3 years old!!!). Yes, Ruby has taken some of the popularity out of Python, but they are also hitting different markets. I have also read in a couple of magazine articles that RoR is losing momentum. From what I have read, RoR is great to create your first version, but if you need to maintain a large codebase, it is not as easy as they thought it would be and the reuse numbers are much lower than Python. But hey, what do I know.... Google, Yahoo!, YouTube... I know.. tiny little tinker-toy web applications.. right? Lance Ellinghaus From gagsl-py2 at yahoo.com.ar Mon Dec 8 03:31:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Dec 2008 06:31:28 -0200 Subject: mod_python and files directory In-Reply-To: <200812061326.40226.metebilgin48@gmail.com> References: <200812061326.40226.metebilgin48@gmail.com> Message-ID: En Sat, 06 Dec 2008 09:26:40 -0200, mete escribi?: > but i want to take it somewhere else...i want to it work some other path > in > other system. os.path.dirname(os.path.abspath(__file__)) returns the directory where the current file resides. Execute it early in your code. -- Gabriel Genellina From anonymous at anonymous.com Sat Dec 6 10:10:56 2008 From: anonymous at anonymous.com (anonymous) Date: Sat, 06 Dec 2008 15:10:56 GMT Subject: python book for non technical absolute beginner References: <493a7c6a$0$973$426a34cc@news.free.fr> Message-ID: <493A9503.A17F5EB4@anonymous.com> Yes, there is an excellent book for absolute beginners call Python Programming, for the absolute beginner (second edition by Michael Dawson. Here are the reasons why it is excellent for a beginner. It doesn't go beyong basic math as do most other computer books when giving examples, exercises or programs illustrating any language including Python. It teaches the basic phython in 9 chapters and the goes on to teach some basic graphics using Python. But for me and many others the first 9 chapters are perfect and awesome to work through. Most books attempting to teach any subject start off with a few easy basic chapters and then jumpt into complex explanations and examples. Not so with this book. It gives consistent easy to understand examples/code often in the form of a simple game which fun. No book I have seen, read or own on Python teaches the very basic principles of writing code as easily understood as this book. There are many excellent web sites around the world in many languages that teach basic Python with free texts and examples, but for somone with little or no programming experience or a first timer at programming with modest math skills, it is perfect. News123 wrote: > > Hi, > > One of my 'non technical' friends complained about knowing nothing at > all about programming (though using computers regularly for mails / web > browsing / googling and downloading / cropping photos ) > > He wants to play a little with programming to stimulate parts of his > otehrwise idle brain cells. ;-) Normally it's more the social science / > linguistic parts being exercised, > > I thought python might be a nice language for this > > No my question does anybody know a nice beginners book (or a learning CD > or on line tutorial)? Ideally it shouldn't be too serious and have a lot > of small nice mini-examples > > thanks in advance for any suggestions hints > > bye > > N From danebarney at gmail.com Sat Dec 27 00:10:59 2008 From: danebarney at gmail.com (Jugdish) Date: Fri, 26 Dec 2008 21:10:59 -0800 (PST) Subject: raw_input can't handle pound sign? References: <0165ad86$0$6988$c3e8da3@news.astraweb.com> Message-ID: <06613154-5789-4dd7-92cc-e20ca1f38670@a26g2000prf.googlegroups.com> Ahh ok, tried out your example and it works just fine. Turns out the actual problem is what I was doing with the input. Elsewhere, I call urlparse.urlparse() on the filename past in, which splits up the filename where the # sign is, so that's why it looked to me like the characters after the # were getting stripped away. Thanks for your help, in the future I'll try to do a bit more debugging of my own scripts before bringing my problems here! :) On Dec 26, 9:00?pm, Steven D'Aprano wrote: > On Fri, 26 Dec 2008 20:20:16 -0800, Jugdish wrote: > > Hi, I'm having problems getting a pound sign to go through as input sent > > to the raw_input() command. I'm running Python 2.5.1 on Windows XP. > > Here's my simple little script: > > > while True: > > ? ? response = raw_input("Please enter a file name: ") if > > ? ? os.path.exists(response): > > ? ? ? ? break > > > Problem is if the filename has a "#" in it, the script interprets that > > as the beginning of a comment (not sure why -- isn't raw_input supposed > > to treat the user's input as raw text and not do any sort of evals?) > > Yes it is. What makes you think it is being interpreted as a comment? > What results are you getting? > > > Any ideas how to get a # to go through? Thanks! > > Works for me (although I'm not using Windows XP). > > Can you execute this line at the interactive interpreter? > > print raw_input("Type something with a hash sign: ") > > At the prompt, type "test # string" (without the quotes) and show us what > result you get. When I do this, I get the following: > > >>> print raw_input("Type something with a hash sign: ") > > Type something with a hash sign: test # string > test # string > > -- > Steven From pavlovevidence at gmail.com Sun Dec 14 13:14:45 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 14 Dec 2008 10:14:45 -0800 (PST) Subject: curses and refreshing problem References: <69d2698a-6f44-4d85-adc3-1180ab158632@r15g2000prd.googlegroups.com> Message-ID: On Dec 14, 5:52?am, Karlo Lozovina <_karlo_ at _mosor.net_> wrote: > Carl Banks wrote innews:69d2698a-6f44-4d85-adc3-1180ab158632 at r15g2000prd.googlegroups.com: > > > Unless you are referring to some wget screen mode I don't know about, > > I suspect wget outputs its progress bar using carriage returns > > without newlines. ?If that's all you want, there is no need to use > > curses. > > > Here is a little example program to illustrate: > > > import time, sys > > for i in range(21): > > ? ? sys.stdout.write('\rProgress: [' + '='*i + ' '*(20-i) + ']') > > ? ? sys.stdout.flush() > > ? ? time.sleep(1) > > sys.stdout.write("\nFinised!\n") > > Thanks, that's it! I just assumed wget uses curses for the progress bar, > so the carriage return didn't even cross my mind ;). Sure. One other thing I'd like to point out is sometimes even if carriage return is not sufficient, you can get a little better control of the terminal by using escape sequences (quod Google). The more basic Xterm escape sequences work in pretty much any Unix-like environment you'd see these days, some might even work on a Windows terminal. For example, print "\033[2J\033[H" probably clears your screen and moves the cursor to top. Carl Banks From rt8396 at gmail.com Mon Dec 22 14:04:32 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 11:04:32 -0800 (PST) Subject: I always wonder ... References: <494fd759$0$186$e4fe514c@news.xs4all.nl> Message-ID: <310faab4-4598-4a5b-86d1-1c9410804982@p2g2000prf.googlegroups.com> > You just got 10 points ;-) Fighting trolls begets a troll. Skip not you, i have so much respect for you :) What really is a troll? Someone who does not agree with you? Someone you don't like? Someone you do like? All good questions. I think this whole troll calling business has gotten out of hand. Some people may antagonize you, but who is ultimately to blame for that? I guess we could have this set up were certain people could be banned, would you like that. Or maybe you should just ignore that which bothers you. If someone came to this group and said """ Ruby rules! Python sucks eggs!""" I would not even bother to reply. But do not let yourself be closed minded and think your ways are alway right. I have learned a lot from people here and have disagreed with a lot of opinions here. Troll calling is childish. be more open minded than that. From sergiocandiotti at hotmail.com Thu Dec 4 14:15:29 2008 From: sergiocandiotti at hotmail.com (sergio) Date: Thu, 4 Dec 2008 11:15:29 -0800 (PST) Subject: GIFTS.BUSINESS OPPORTUNITY Message-ID: Dear friend I'm writing to you because I just came across some businesses that I think have great potencial. All Solutions Network.A World of Opportunity and Solutions!! Make Money from Eveything...Loans,cars,meds,taxes,credit cards,vacations etc. Not Only can you make money for giving away free vacation packages,you get a free vacation certificate for just visiting the site!Make and Save on everything?It's Totally automated and no investment-EVER! Click here: http://allsolutionsnetwork.com/SC/SC6040/ Remote Data Backup Service Protect Your Most Valuable Asset...Your Data!! Take your free-30 days trial today with no credit card required. Online Backup Reseller Program.Just click here: http://sergioca.databu.com/bu/?id=sergioca GET YOUR OWN FREE TOTALLY AUTOMATED WEBSITE! 24/7 MULTIMEDIA MARKETING.WEALTH ON AUTO. Where Hig-Tech Meets Hig-Touch. 24/7 Fast Track system. A revolutionary,automated sponsoring and mentoring system to put your business on the FAST TRACK! Powerful sponsoring tools for FREE! Just click here: http://www.wealthonauto.com/members/sergiocandiotti/ MLM RESOURCE CENTER.MULTILEVEL MARKETING The #1 Site for Network Marketing, Training&Success. You can't build anything without THE RIGHT TOOLS. We have the tools! Just click here: http://www.wealthonauto.com/members/sergiocandiotti/mrc.htm Talk to you later. Sergio Candiotti Aguero sergiocandiotti at hotmail.com From Russ.Paielli at gmail.com Thu Dec 18 23:40:43 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Thu, 18 Dec 2008 20:40:43 -0800 (PST) Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> <6qv7kfFeuf65U1@mid.uni-berlin.de> <6qv9v4Ff1lv9U1@mid.uni-berlin.de> Message-ID: <3840c09b-1dae-4bb7-b509-624636cbbc28@g39g2000pri.googlegroups.com> On Dec 18, 1:27?pm, Robert Kern wrote: > Mikael Olofsson wrote: > > Diez B. Roggisch wrote: > >> Yep. And it's easy enough if you don't care about them being different.. > > >> def __repr__(self): > >> ? ? return str(self) > > > If I ever wanted __str__ and __repr__ to return the same thing, I would > > make them equal: > > > def __str__(self): > > ? ? return 'whatever you want' > > __repr__ = __str__ > > > That makes it more obvious to me what's going on. As a bonus, it saves > > one method call for every repr call. > > Or just define __repr__(). str() falls back to __repr__() if __str__() is not > defined. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > ? that is made terrible by our own mad attempt to interpret it as though it had > ? an underlying truth." > ? ?-- Umberto Eco I learned a while ago to just define __repr__, and let __str__ revert to it by default. Then, when I print a list for debugging purposes, I see something useful (as opposed to a type name and an address). The only reason that I can think of to define __str__ is to get two different representations. For example, sometimes I need both a one- line output format and a multi-line option for more clarity or detail. Then I use __repr__ for the one-liner and __str__ for the multi-liner. From prologic at shortcircuit.net.au Thu Dec 18 22:14:12 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Dec 2008 13:14:12 +1000 Subject: Factoring Polynomials In-Reply-To: References: <919062f9-765e-4279-aa26-2c130d4deacf@o4g2000pra.googlegroups.com> <4479b464-3a9b-4dd8-bf66-fea7d9471091@n33g2000pri.googlegroups.com> <661fd2d0-251d-4899-a015-8d257310a159@q26g2000prq.googlegroups.com> Message-ID: On Fri, Dec 19, 2008 at 12:48 PM, Collin D wrote: > UPDATE: > > #import > from math import sqrt > > # collect data > a = float(raw_input('Type a value: ')) > b = float(raw_input('Type b value: ')) > c = float(raw_input('Type c value: ')) > > # create solver > def solver(a,b,c): > disc = b**2 - 4*a*c > if disc < 0: > return 'No real solution.' > else: > sol1 = (-b + (sqrt(disc))) / (2*a) > sol2 = (-b - (sqrt(disc))) / (2*a) > return (sol1, sol2) You do not need the else here. return will always return control to the calee. Try this: class Unsolveable(Exception): pass # create solver def solver(a, b, c): disc = b**2 - 4*a*c if disc < 0: raise Unsolveable() return -b + (sqrt(disc) / (2*a)), -b - (sqrt(disc) / (2*a)) From bdesth.quelquechose at free.quelquepart.fr Sun Dec 14 11:22:11 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 14 Dec 2008 17:22:11 +0100 Subject: Looking for the best way to translate an idiom In-Reply-To: References: Message-ID: <4945406a$0$1127$426a74cc@news.free.fr> Paul Moore a ?crit : > I'm translating some code from another language (Lua) which has > multiple function return values. So, In Lua, it's possible to define a > function > > function f() > return 1,2,3 > end > > which returns 3 values. These can then be used/assigned by the caller: > > a,b,c = f() > > So far, much like Python, but the key difference is that in Lua, > excess arguments are ignored - so you can do > > a = f() > or even > a = f() + 1 > > where in the latter, a is 2 (as addition only needs 1 argument, so the > extra ones are discarded). > > This results in the code which I'm trying to translate having > functions which return multiple arguments, the first of which is the > "main" result, and the following values are "extra" results > (specifically, the position at which a match is found, followed by the > "captured" values of the match). > > I'm trying to find a natural equivalent in Python. So far, I've > considered the following: > > - return a tuple (pos, captures). This is messy, because you end up > far too often unpacking the tuple and throwing away the second value if you only want the first returned value, you can just apply a slice: def f(): return 1,2,3 a = f()[0] + 1 > - return an object with pos and captures attributes. This is better, > as you can do match(...).pos to get the position alone, but it doesn't > really feel "pythonic" (all those calls with .pos at the end...) FWIW, Python 2.6 has NamedTuple objects... > - have 2 calls, one to return just the position, one to return both. > This feels awkward, because of the 2 method names to remember. You forgot one solution: passing a flag to the function to specify if you want only the main result or the extra ones as well, and give this flag the appropriate default value depending on most common use case. > To make things worse, Lua indexes strings from 1, so it can use a > position of 0 to mean "no match" - so that a simple "did it match?" > test looks like if (match(....))... - where in Python I need if > (matchpos(...) != -1)... (Although if I return a match object, I can > override __nonzero__ to allow me to use the simpler Lua form). > > Can anyone suggest a good idiom for this situation? At the moment, I'm > returning a match object (the second option) which seems like the > least bad of the choices (and it mirrors how the re module works, > which is somewhat useful). But I'd like to know what others think. If > you were using a pattern matching library, what interface would you > prefer? The one that happens to be the most simple for the most common usecase, while still providing support for more advanced stuff. > I suspect my intuition isn't accurate here, as most of the use I've > made of the library is in writing tests, which isn't typical use :-( So perhaps you should start writing some real-life code ? > Thanks for any assistance. Not sure I've been that helpful. Sorry... From cournape at gmail.com Fri Dec 19 00:08:49 2008 From: cournape at gmail.com (David Cournapeau) Date: Fri, 19 Dec 2008 14:08:49 +0900 Subject: Python for amd64 and mingw-w64 Message-ID: <5b8d13220812182108y5a21d48as4adead61fede561a@mail.gmail.com> Hi, I want to build python extensions with mingw-w64 on windows 64 bits. I found some problems which I think are python bugs/deficiencies, but would like a confirmation: - Any extension requires the MS_WIN64 to be defined, but this symbol is only defined for MS compiler (in PC/pyport.h). Shouldn't it be defined independantly of the compiler ? One problem is that without this defines, SIZEOF_SIZE_T is set to 4 with gcc. Another consequence which can be seen even through a trivial , do nothing extension is that Py_InitModule4 is used (whereas the same source file will use Py_InitModule4_64, which is used when SIZEOF_SIZE_T !=SIZEOF_INT, in include/modsupport.h). - I have some link problems related to Py_InitModule4_64. I believe the problem is in libpython26.a, which according to nm does not have this symbol defined, whereas python26.dll has. thanks, David From quian.xu at stud.tu-ilmenau.de Tue Dec 23 06:06:09 2008 From: quian.xu at stud.tu-ilmenau.de (Qian Xu) Date: Tue, 23 Dec 2008 12:06:09 +0100 Subject: print to console without a line break References: Message-ID: Qian Xu wrote: > Hello All, > > Is it possible to print something to console without a line break? > > I tried: > sys.stdout.write("Testing something ...") // nothing will be printed > time.sleep(1) > sys.stdout.write("done\n") // now, the whole string will be printed > > What I want, is to see "Testing something ..." first. > And after 1 second, to see "done" (with a line break) > I have solved the problem by calling sys.stdout.flush() --Qian Xu From geon at post.cz Thu Dec 25 23:52:52 2008 From: geon at post.cz (Pavel Kosina) Date: Fri, 26 Dec 2008 05:52:52 +0100 Subject: tkinter 3.0 multiple keyboard events together Message-ID: <49546324.4050607@post.cz> Is it possible to catch in an event more that one key from keyboard? In my code, I can handle always the only one, the first I press, the others are omitted. Say, I press both "4" and "8" and only "4" is catched. def movePlayer(event): print (event.keysym) Thank you. -- geon Pavel Kosina From paul at boddie.org.uk Thu Dec 18 18:22:59 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 18 Dec 2008 15:22:59 -0800 (PST) Subject: psycopg2 and large queries References: <762eed9d-4646-4c62-a9b7-d57d47f03b9e@e1g2000pra.googlegroups.com> Message-ID: <7e76a8db-8a93-4704-8815-ad106f50c47d@w39g2000prb.googlegroups.com> On 18 Des, 22:28, Laszlo Nagy wrote: > > I'm just looking for something that can replace psycopg2, because of the > bug mentioned in my original post. Here are my options: > > - psycopg1: development stalled > - psycopg2: memory bug and/or not db api compilant (see my original post) If you want, I can try and dig up those patches I made. > - pyPgSQL: looks like that the last release was in mid 2006 (and it > depends on mxDateTime -> licensing problems) Well, Debian ships mxDateTime, so I suppose the licence is DFSG- compliant, at least. Whether that's enough only you can say, but porting the dependent parts to use the Python standard library datetime implementation might be possible. Paul From rhamph at gmail.com Mon Dec 8 18:30:22 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 8 Dec 2008 15:30:22 -0800 (PST) Subject: Rich Comparisons Gotcha References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Dec 8, 2:51?pm, Robert Kern wrote: > Rhamphoryncus wrote: > > "We've always done it that way" is NOT a use case! ?Certainly, it's a > > factor, but it seems quite weak compared to the sort use case. > > I didn't say it was. I was explaining that sorting was probably *not* a use case > for the boolean predicates at the time of writing of the standard. In fact, it > suggests implementing a Compare() function that returns "greater than", "less > than", "equal" or "unordered" in addition to the boolean predicates. That Python > eventually chose to use a generic boolean predicate as the basis of its sorting > routine many years after the IEEE-754 standard is another matter entirely. I interpret that to mean IEEE 754's semantics are for different circumstances and are inapplicable to Python. > In any case, the standard itself is quite short, and does not spend much time > justifying itself in any detail. A pity, as it is often invoked to explain language design. > > I suppose what I'm hoping for is an small example program (one or a > > few functions) that needs the "always false" behaviour of NaN. > > Steven D'Aprano gave one earlier in the thread. I see examples of behaviour, but no use cases. > Additionally, (x!=x) is a simple > test for NaNs if an IsNaN(x) function is not available. That's a trick to work around the lack of IsNaN(x). Again, not a use case. > Really, though, the > result falls out from the way that IEEE-754 constructed the logic of the > system. It is not defined that (NaN==NaN) should return False, per se. Rather, > all of the boolean predicates are defined in terms of that Compare(x,y) > function. If that function returns "unordered", then (x==y) is False. It doesn't > matter if one or both are NaNs; in either case, the result is "unordered". And if I arbitrarily dictate that NaN is a single value which is orderable, sorting just above -Infinity, then all the behaviour makes a lot more sense AND I fix sort. So you see the predicament I'm in. On the one hand we have a problem and an obvious solution. On the other hand we've got historical behaviour which everybody insists *must* remain, reasons unknown. It reeks of the Parable of the Monkeys. I think I should head over to one of the math groups and see if they can find a reason for it. From castironpi at gmail.com Mon Dec 29 14:18:33 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 11:18:33 -0800 (PST) Subject: why cannot assign to function call References: <97a11245-a034-4558-82d4-0c87e02bdb7e@u18g2000pro.googlegroups.com> <47-dnUx1_OP7gsTUnZ2dnUVZ_r6dnZ2d@pdx.net> Message-ID: On Dec 29, 1:05?pm, Scott David Daniels wrote: > John Machin wrote: > > On Dec 29, 5:01 pm, scsoce wrote: > >> I have a function return a reference, > > > Stop right there. You don't have (and can't have, in Python) a > > function which returns a reference that acts like a pointer in C or C+ > > +. Please tell us what manual, tutorial, book, blog or Usenet posting > > gave you that idea, and we'll get the SWAT team sent out straight > > away. > > Perhaps we can send the the Pennsylvania State University out after > them. ?I don't know why, but some fairly substantial people here are > scared of the PSU. > > ... > > Oh, I have just been informed by my captors that the are the Python > Secre.... --Why would he take the time to carve "ARGHHH!"? --Maybe he was dictating. From jenn.duerr at gmail.com Thu Dec 11 21:43:00 2008 From: jenn.duerr at gmail.com (noydb) Date: Thu, 11 Dec 2008 18:43:00 -0800 (PST) Subject: Rename of .mdb file -- lock References: <4049f296-2a04-4eee-9f09-aa37a973a8cf@r40g2000yqj.googlegroups.com> <8792708a-51c9-4fa6-b39d-4808ed1ffaed@t39g2000prh.googlegroups.com> Message-ID: <99fbe43e-9b30-4ed2-8355-29a21935e55a@n41g2000yqh.googlegroups.com> On Dec 11, 9:38?pm, "gudonghua+pyt... at gmail.com" wrote: > On Dec 12, 10:15?am, noydb wrote: > > > > > All, > > > I have the code below, which unzips a zipfile containing only one > > file. ?Once it is unzipped, I want to rename the file based on a user > > provided name. ?But I get this (WindowsError: [Error 32] The process > > cannot access the file because it is being used by another process) > > error, which does not make sense to me as no other apps are open. > > > Any suggestions? > > > Thanks! > > > ****CODE**** > > # Declare the zip file directory and name (shouldn't change, in a > > permanent location) > > mdb_zip = ("C:\\ProjWork\\mdb_geoDB_91.zip") > > > output_dir = ("C:\\Temp") > > > # ZipFile for read > > z = zipfile.ZipFile(mdb_zip, 'r') > > zFile = z.namelist() > > > # Put contents of zipfile into a list > > zList = z.namelist() > > > # Loop thru list, write zipfile contents to new directory > > for zItem in zList: > > ? ? print "Unpacking",zItem > > ? ? zRead = z.read(zItem) > > ? ? z1File = open(os.path.join(output_dir, zItem),'wb') > > ? ? z1File.write(zRead) > > ? ? z1File.close > > ? ? ?z1File.close() > > > > > print "Finished extracting zip file" > > > uChoice = "test44.mdb" ## to be user chosen someday > > new91mdb = os.path.join(output_dir, zItem) # C:\TEMP\GDB_9_1.mdb > > > ##os.rename(new91mdb, (os.path.join(output_dir, uChoice))) > > os.rename(new91mdb, (os.path.join(output_dir, "C:\TEMP\test1.mdb"))) > > > del new91mdb- Hide quoted text - > > - Show quoted text -- Hide quoted text - > > - Show quoted text - Thanks! That was simple enough. And... ##os.rename(new91mdb, (os.path.join(output_dir, uChoice))) os.rename(new91mdb, (os.path.join(output_dir, "C:\TEMP\test1.mdb"))) ... of those two lines, the top one worked. From metebilgin48 at gmail.com Sat Dec 6 06:26:40 2008 From: metebilgin48 at gmail.com (mete) Date: Sat, 6 Dec 2008 13:26:40 +0200 Subject: mod_python and files directory In-Reply-To: References: Message-ID: <200812061326.40226.metebilgin48@gmail.com> but i want to take it somewhere else...i want to it work some other path in other system. On Saturday 06 December 2008 12:34:07 Graham Dumpleton wrote: > On Dec 6, 1:52?am, "mete bilgin" wrote: > > Hi all, > > I try to make a websevice with python and mod_python. ? try to make a po > > files, but i can not reach them in the page. When i ask the page like " > > os.listdir('.') " but i want to get files directory, what can i do? sorry > > for my bad describe of that. Thanks a lot... > > The current working directory in Apache can be anything. You must > supply an absolute path to all directories/files you are trying to > access/use. > > Graham > -- > http://mail.python.org/mailman/listinfo/python-list From barry at python.org Wed Dec 3 20:51:33 2008 From: barry at python.org (Barry Warsaw) Date: Wed, 3 Dec 2008 20:51:33 -0500 Subject: RELEASED Python 3.0 final Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On behalf of the Python development team and the Python community, I am happy to announce the release of Python 3.0 final. Python 3.0 (a.k.a. "Python 3000" or "Py3k") represents a major milestone in Python's history, and was nearly three years in the making. This is a new version of the language that is incompatible with the 2.x line of releases, while remaining true to BDFL Guido van Rossum's vision. Some things you will notice include: * Fixes to many old language warts * Removal of long deprecated features and redundant syntax * Improvements in, and a reorganization of, the standard library * Changes to the details of how built-in objects like strings and dicts work * ...and many more new features While these changes were made without concern for backward compatibility, Python 3.0 still remains very much "Pythonic". We are confident that Python 3.0 is of the same high quality as our previous releases, such as the recently announced Python 2.6. We will continue to support and develop both Python 3 and Python 2 for the foreseeable future, and you can safely choose either version (or both) to use in your projects. Which you choose depends on your own needs and the availability of third-party packages that you depend on. Some other things to consider: * Python 3 has a single Unicode string type; there are no more 8-bit strings * The C API has changed considerably in Python 3.0 and third-party extension modules you rely on may not yet be ported * Tools are available in both Python 2.6 and 3.0 to help you migrate your code * Python 2.6 is backward compatible with earlier Python 2.x releases We encourage you to participate in Python 3.0's development process by joining its mailing list: http://mail.python.org/mailman/listinfo/python-3000 If you find things in Python 3.0 that are broken or incorrect, please submit bug reports at: http://bugs.python.org/ For more information, links to documentation, and downloadable distributions, see the Python 3.0 website: http://www.python.org/download/releases/3.0/ Enjoy, - -Barry Barry Warsaw barry at python.org Python 2.6/3.0 Release Manager (on behalf of the entire python-dev team) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Darwin) iQCVAwUBSTc3pXEjvBPtnXfVAQI69wP/dPHh8IL3GxziEV9QzlveKG+KyZb2X16x fxJnTCiXAbiAhT5C+m43OEnbF1PJgMDKtcZ5b7aQb4TQ0mJxISTQh0RfLCpArmlo tdTbzCLnh13KzB+3sUHCx+MeQNXERoWDV8hLz+4Ae71UsuUGynhtyP7ZJMJDue8j so2gv3fOMSs= =vkiy -----END PGP SIGNATURE----- From saluk64007 at gmail.com Sun Dec 7 20:17:45 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Sun, 7 Dec 2008 17:17:45 -0800 Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? In-Reply-To: References: Message-ID: On Sun, Dec 7, 2008 at 4:43 PM, wrote: > Trying to decide which to get started with. Can anyone suggest some > pros and cons to each of them? > > Would PyOpenGL be in the same camp as Pygame and pyglet? Do either of > Pygame or pyglet make use of PyOpenGL behind the scenes? > -- > http://mail.python.org/mailman/listinfo/python-list > PyOpengl - an opengl wrapper. Version 2 is written in c, version 3 instead uses ctypes Pyglet - an opengl + events/sound/etc wrapper written in ctypes pygame - an sdl wrapper for 2d rendering, sound, music, events, etc that can be used with pyopengl if 3d hardware support is desired. If you want to do 3d, your choice is basically pygame+pyopengl or pyglet. pyglet is nice because it comes with everything you need, versus pygame where you have to interact via pyopengl. Pygame +pyopengl2 is faster than pyglet or pygame+pyopengl3 becuase pyglet and pyopengl3 take a hit from ctypes. There is a project with pyopengl3 though to add some c code to speed things up, I think it works with numeric. Pyglet will be easiest to start with and use, it seems to be everyone's favorite choice these days. From python at bdurham.com Tue Dec 2 23:21:30 2008 From: python at bdurham.com (python at bdurham.com) Date: Tue, 02 Dec 2008 23:21:30 -0500 Subject: Best way to run multiple Python processes without overloading CPU or disk i/o Message-ID: <1228278090.29785.1287948757@webmail.messagingengine.com> Is there a cross-platform way to launch multiple Python processes and monitor CPU usage and disk i/o so that the maximum number of independent processes can be running at all times without overloading their environment? By process I mean independent application sessions vs. multiple threads of a single application. I'm looking for suggestions on what Python modules and/or techniques to use to maximize the number of processes I can run on my system over a multi-day period. Background: I have a large collection of data analysis scripts that can run independently of one another. These scripts read very large log files in a sequential manner and calculate specific statistics. These scripts are hosted on a 8 core 64-bit server with 48G of memory that is dedicated to running these scripts. I am looking for a way to write a master script that monitors system CPU and disk i/o and when there is capacity launch another script from a pool of scripts so that I'm getting max utilization from my hardware, eg. so that I'm running the max number of scripts I can at any one point in time without overwhelming the system. The server in question is currently running Windows 2008 Enterprise, but I have the option to switch to a 64-bit version of Linux if there are benefits to doing so. Thank you, Malcolmm -------------- next part -------------- An HTML attachment was scrubbed... URL: From news123 at free.fr Sun Dec 7 06:57:27 2008 From: news123 at free.fr (News123) Date: Sun, 07 Dec 2008 12:57:27 +0100 Subject: Guido's new method definition idea In-Reply-To: <62bcfe49-bee6-4348-8ec9-8ab85132c8ff@40g2000prx.googlegroups.com> References: <493abe2e$0$15998$426a34cc@news.free.fr> <62bcfe49-bee6-4348-8ec9-8ab85132c8ff@40g2000prx.googlegroups.com> Message-ID: <493bba28$0$8283$426a74cc@news.free.fr> Lie wrote: > On Dec 7, 1:02 am, News123 wrote: >> What would be interesting would be some syntactical sugar to get rid of >> the 'self' (at least in the code body). >> >> example: >> class C: >> class_elements a,b,c,d >> >> def method(self,arg): >> global d >> a,b,c = arg[0..3] >> d = a + b >> self.e = a + d >> > > Nah, that would make it not explicit. Explicit here also means that to > refer to self's a, we need to explicitly refer to self. Well being explicit when trying to suggest an implicit syntax (in order to reduce typing) is a little difficult ;-) Though you're right my main goal is not being implicit but would be reducing typing and have shorter source code lines. If 'global '' is accepted inside a def, then moving 'class_elements ' inside the def could be acceptable as well though it would requiere, that this statement is repeated per def bye N From marco at sferacarta.com Fri Dec 12 04:28:18 2008 From: marco at sferacarta.com (Marco Mariani) Date: Fri, 12 Dec 2008 10:28:18 +0100 Subject: Python is slow In-Reply-To: <4c9ba1a9-db8d-43a5-86f5-09f688200ea4@w24g2000prd.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <9e0bb906-e019-45ef-8047-b33982c7c5ad@l39g2000yqn.googlegroups.com> <4c9ba1a9-db8d-43a5-86f5-09f688200ea4@w24g2000prd.googlegroups.com> Message-ID: Giampaolo Rodola' wrote: > The real (and still unsolved) problem with PyPy is the installation > which requires something like a dozen of third-party packages to be > installed. > Unfortunately it seems there are no plans yet for releasing any > Windows/Linux/Mac installer in the near future. I'm not using it, but at least Ubuntu 8.10 has the .deb packages of pypy 1.0. And I remember installing a release last year in a few minutes, during a conference talk. From tjreedy at udel.edu Sat Dec 6 14:56:32 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 06 Dec 2008 14:56:32 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Rasmus Fogh wrote: > Dear All, > > For the first time I have come across a Python feature that seems > completely wrong. After the introduction of rich comparisons, equality > comparison does not have to return a truth value, and may indeed return > nothing at all and throw an error instead. As a result, code like > if foo == bar: > or > foo in alist > cannot be relied on to work. > > This is clearly no accident. According to the documentation all comparison > operators are allowed to return non-booleans, or to throw errors. There is > explicitly no guarantee that x == x is True. You have touched on a real and known issue that accompanies dynamic typing and the design of Python. *Every* Python function can return any Python object and may raise any exception either actively, by design, or passively, by not catching exceptions raised in the functions *it* calls. > Personally I would like to get these !@#$%&* misfeatures removed, What you are calling a misfeature is an absence, not a presence that can be removed. > and constrain the __eq__ function to always return a truth value. It is impossible to do that with certainty by any mechanical creation-time checking. So the implementation of operator.eq would have to check the return value of the ob.__eq__ function it calls *every time*. That would slow down the speed of the 99.xx% of cases where the check is not needed and would still not prevent exceptions. And if the return value was bad, all operator.eq could do is raise and exception anyway. > That is clearly not likely to happen. Unless I have misunderstood something, could > somebody explain to me. a. See above. b. Python programmers are allowed to define 'weird' but possibly useful-in-context behaviors, such as try out 3-value logic, or to operate on collections element by element (as with numpy). > 1) Why was this introduced? The 6 comparisons were previously done with one __cmp__ function that was supposed to return -1, 0, or 1 and which worked with negative, 0, or positive response, but which could return anything or raise an exception. The compare functions could mask but not prevent weird returns. I can understand relaxing the restrictions on > '<', '<=' etc. - after all you cannot define an ordering for all types of > object. But surely you can define an equal/unequal classification for all > types of object, if you want to? Is it just the numpy people wanting to > type 'a == b' instead of 'equals(a,b)', or is there a better reason? > > 2) If I want to write generic code, can I somehow work around the fact > that > if foo == bar: > or > foo in alist > does not work for arbitrary objects? Every Python function is 'generic' unless restrained by type tests. However, even 'generic' functions can only work as expected with objects that meet the assumptions embodied in the function. In my Python-based algorithm book-in-progess, I am stating this explicitly. In particular, I say taht the book only applies to objects for which '==' gives a boolean result that is reflexive, symmetric, and transitive. This exludes float('nan'), for instance (as I see you discovered), which follows the IEEE mandate to act otherwise. > CCPN has a table display class that maintains a list of arbitrary objects, > one per line in the table. The table class is completely generic, but only for the objects that meet the implied assumption. This is true for *all* Python code. If you want to apply the function to other objects, you must either adapt the function or adapt or wrap the objects to give them an interface that does meet the assumptions. > and subclassed for individual cases. It contains the code: > > if foo in tbllist: > ... > else: > ... > tbllist.append(foo) > ... > > One day the 'if' statement gave this rather obscure error: > "ValueError: > The truth value of an array with more than one element is ambiguous. > Use a.any() or a.all()" > A subclass had used objects passed in from some third party code, and as > it turned out foo happened to be a tuple containing a tuple containing a > numpy array. Right. 'in' calls '==' and assumes a boolean return. Assumption violated, exception raised. Completely normal. The error message even suggests a solution: wrap the offending objects in an adaptor class that gives them a normal interface with .all (or perhaps the all() builtin). Terry Jan Reedy From jstroud at mbi.ucla.edu Thu Dec 4 16:04:05 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 04 Dec 2008 13:04:05 -0800 Subject: To Troll or Not To Troll In-Reply-To: References: <896B75251BA19745A529B1B867893FA50679CE@planet.delsci.local> Message-ID: Chris Mellon wrote: > On Thu, Dec 4, 2008 at 1:10 PM, Warren DeLano wrote: >>> Yet Another Python Troll (the ivory tower reference, as well as the >>> abrupt shift from complaining about keywords to multiprocessing), I >>> have to point out that Python does add new keywords, it has done so in >>> the past, and there was a considerable amount of warning, including an >>> automated deprecation warning in the very version you are going to >>> recommend to your "customers' (I don't actually think you have any >>> customers). >> ROFL! I'm sorry, you're right -- this has all been a figment of my >> imagination... >> >> http://www.pymolwiki.org/index.php/Covers You forgot http://www.nature.com/neuro/journal/v10/n8/covers/index.html James From __peter__ at web.de Sun Dec 14 14:05:59 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 14 Dec 2008 20:05:59 +0100 Subject: Shorter tracebacks References: Message-ID: Peter Otten wrote: > That's none of __future__'s business, I think. Python offers a hook which > you can modify: > >>>> import sys, traceback >>>> from functools import partial >>>> sys.excepthook = partial(traceback.print_exception, limit=5) I just stumbled upon >>> import sys >>> sys.tracebacklimit Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'tracebacklimit' >>> sys.tracebacklimit = 2 >>> def f(): f() ... >>> f() Traceback (most recent call last): File "", line 1, in f File "", line 1, in f RuntimeError: maximum recursion depth exceeded Peter From pdorange at pas-de-pub-merci.mac.com Fri Dec 26 06:06:50 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Fri, 26 Dec 2008 12:06:50 +0100 Subject: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> <90f06b27-39da-4f1a-a878-f3972e942d57@s24g2000vbp.googlegroups.com> <62caf93b-0455-4450-9895-8a9d9554f75e@r32g2000vba.googlegroups.com> <1isezkk.51e05y1457jqrN%pdorange@pas-de-pub-merci.mac.com> <3cb2a746-1a43-44a1-9825-7667af9fe2fa@s1g2000prg.googlegroups.com> <1isi4sn.11mpft612g7udcN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <1isk1kn.1s8efppxapfeaN%pdorange@pas-de-pub-merci.mac.com> r wrote: > > Go to Google groups... it looks perfect :) It's a usenet group here, nothing to do with google groups. To get back to the group subject, what is your actual python projects ? -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From v+python at g.nevcal.com Thu Dec 4 02:34:28 2008 From: v+python at g.nevcal.com (Glenn Linderman) Date: Wed, 03 Dec 2008 23:34:28 -0800 Subject: Multiple Versions of Python on Windows XP In-Reply-To: References: <4934de22$0$27863$9b622d9e@news.freenet.de> <493592EE.9090005@v.loewis.de> Message-ID: <49378804.2050807@g.nevcal.com> On approximately 12/3/2008 8:51 AM, came the following characters from the keyboard of Colin J. Williams: > Martin v. L??wis wrote: >>>>> What changes are made to the registry? >>>> For a complete list, see Tools/msi/msi.py in the source tree. >>> I have scanned the file: >>> http://svn.python.org/projects/python/branches/py3k/Tools/msi/msi.py >>> >>> I don't find anything that addresses this issue. >> >> Read the add_registry function. You may need to first understand >> how the Registry table in an MSI file works. >> >>> I am seeking some mechanism such that any of Python 2.5, Python 2.6 or >>> Python 2.6 can be chosen as the currently active version. >> >> If Glenn Lindermann's answer doesn't help, you need to explain: >> what is a "currently active version"? How is one Python version >> more active than any other? >> >>> I was hoping that there is some simpler way than the "Repair" >>> procedure. >> >> See Glenn Lindermann's answer. >> >>>> It would be good to be more specific with such statements: what >>>> troubles >>>> specifically? If I play dumb, I'd say "of course - windows explorer >>>> doesn't support editing Python files; you need a text editor". >>> Yes, I should have been clearer. The PyScripter application locks up >>> and must be killed, using the Task Manager. >> >> I think you need to report that to the PyScripter authors as a bug. >> I can't imagine how the "currently active version" can affect what >> PyScripter does. >> >> Regards, >> Martin > > Martin, > > Many thanks for your responses. Yes, > Glen Lindermann's suggestion seems to > meet the need. > > It's been a while since I've looked at > DOS and I didn't remember fType or assoc. The equivalent of those commands is available via Windows Explorer, Tools / Folder Options, File Types, scroll-scroll-scroll your way to .py, Click Advanced, fiddle, copy paste apply, and other twaddle. A perfect example of why not everything should be done via GUI interfaces, or at least why this is an extremely poor GUI interface. GUI designers should count the command line keystrokes, and make sure their interface is shorter, otherwise they are a failure. > Michel Claveau suggests VirtualBox, this > seems a big hammer to kill > this particular fly. > > It's interesting that each install sets > up a Python.File variable in the registry. > > It's a pity that this can't be used to achieve this more simply. Martin seems willing to entertain the idea of future Windows installers doing something more brilliant in this area, for those that wish to switch between multiple installed versions, as he asked for a tracking issue to be created, which I did. Whether it will be exactly my technique, or something further improved, time will tell. But that will only apply to versions released after 3.0 and 2.6.1 (unless he has already coded it into the release, but I doubt he had time, or wishes to destabilize or delay these releases). Anyway, if you remember the arcane techniques for copy/paste in CMD prompt windows (Alt-space or click the "system" icon in the upper left of the CMD prompt window), and go from there, then setting up the multiple ftypes becomes a bit easier, perhaps. > Best wishes, > > Colin W. -- Glenn -- http://nevcal.com/ =========================== A protocol is complete when there is nothing left to remove. -- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking From hniksic at xemacs.org Mon Dec 15 04:51:49 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 15 Dec 2008 10:51:49 +0100 Subject: cx_Oracle issues References: <5b2dad81-2750-4347-8079-6ab31321d579@s1g2000prg.googlegroups.com> <9142a8f1-7f76-4fc0-9ca1-c9dec310f2ce@r37g2000prr.googlegroups.com> <9f436c9e-2319-499c-a306-d255996372fc@e22g2000vbe.googlegroups.com> Message-ID: <871vw9bway.fsf@mulj.homelinux.net> huw_at1 writes: >> > ORA-06502: PL/SQL: numeric or value error: character string buffer too >> > small ORA-06512: at line 1 >> >> This error is a problem with the PL/SQL, not cx_Oracle. ?You need to >> debug obj.function to see what kind of data is being accessed and then >> a data analysis of that data to understand why this error occurs. ?I >> can tell you the function is most likely expecting characters from a >> column that are numeric [0 .. 9] and is getting alpha characters. > > Hi thanks for the responses. Unfortunately the procedure in question > is from a third party vendor so I can't really debug it so I'd say I > was fairly stumped. Just out of interest how do you increase the > output buffer size with cx_Oracle? Ron's point was that you cannot fix this problem on the side of cx_Oracle because the exception occurs before cx_Oracle ever sees the result, during the execution of PL/SQL code. This is easy to verify: simply run the function the same way in sqlplus. If the problem persists, it's a bug in the function (or in the way you're calling it, or setting up the data, etc.) and you should complain to your vendor, or somehow work around the problem. Otherwise it's a cx_Oracle related problem. From sjmachin at lexicon.net Mon Dec 29 07:35:48 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 29 Dec 2008 04:35:48 -0800 (PST) Subject: AttributeError: 'module' object has no attribute 'DatagramHandler' (ubuntu-8.10, python 2.5.2) References: <4c6f0831-c05f-401f-b956-376600b38e06@r15g2000prd.googlegroups.com> Message-ID: <75aaddb4-faf3-47d4-850b-194e9c560071@c36g2000prc.googlegroups.com> On Dec 29, 11:08?pm, Tzury Bar Yochay wrote: > $ ~/devel/ice/snoip/freespeech$ python > Python 2.5.2 (r252:60911, Oct ?5 2008, 19:24:49) > [GCC 4.3.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> import logging > >>> logging.DatagramHandler > > Traceback (most recent call last): > ? File "", line 1, in > AttributeError: 'module' object has no attribute 'DatagramHandler' > > > > That is odd since the documentation says there is DatagramHandler for > module logging According to http://www.python.org/doc/2.5.2/lib/module-logging.html """ The StreamHandler and FileHandler classes are defined in the core logging package. The other handlers are defined in a sub- module, logging.handlers. """ and later in http://www.python.org/doc/2.5.2/lib/node415.html """ The DatagramHandler class, located in the logging.handlers module, ... """ HTH, John From rt8396 at gmail.com Tue Dec 16 17:00:16 2008 From: rt8396 at gmail.com (r) Date: Tue, 16 Dec 2008 14:00:16 -0800 (PST) Subject: What does the at sign do? References: Message-ID: Google "python decorators" From huwdjones at gmail.com Wed Dec 10 11:48:45 2008 From: huwdjones at gmail.com (huw_at1) Date: Wed, 10 Dec 2008 08:48:45 -0800 (PST) Subject: cx_Oracle issues Message-ID: <5b2dad81-2750-4347-8079-6ab31321d579@s1g2000prg.googlegroups.com> Hey all. When using cx_Oracle to run a procedure like: cursor.execute("select (obj.function(value)) from table where id=blah") I am getting the following error: ORA-06502: PL/SQL: numeric or value error: character string buffer too small ORA-06512: at line 1 Looking at cursor.description I get: [('(obj.function(value))', , 4000, 4000, 0, 0, 1)] Any tips - i have never seen this error before but am guessing that the value being returned is too big for the buffer size set for the cursor. the procedure fetches data from a LOB. Any suggestions/confirmations? Many thanks From israelu at elbit.co.il Wed Dec 31 06:30:11 2008 From: israelu at elbit.co.il (iu2) Date: Wed, 31 Dec 2008 03:30:11 -0800 (PST) Subject: Pass by reference Message-ID: <529e1d98-8932-49f0-b569-85285bd50f23@p2g2000prn.googlegroups.com> Hi, Is it possible somehow to change a varible by passing it to a function? I tried this: def change_var(dict0, varname, val): dict0[varname] = val def test(): a = 100 change_var(locals(), 'a', 3) print a But test() didn't work, the value a remains 100. I have several variables initialized to None. I need to convert each one of them an object only if it is None. something like: if not var1: var1 = MyObject() I want this to be a function, that is: def create_obj(var): if not var: var = MyObj() # set properties of var Now, I know I can achieve this by functional programming, def create_obj(var): if not var: x = MyObj() # set properties of x return x return var and then var = creaet_obj(var) Is there another way? Thanks From wuwei23 at gmail.com Thu Dec 4 01:35:50 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 3 Dec 2008 22:35:50 -0800 (PST) Subject: Multiple equates References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> Message-ID: <1d15d626-b548-4b27-9a63-114360607680@n33g2000pri.googlegroups.com> On Dec 4, 1:52?pm, Lawrence D'Oliveiro wrote: > Why is that? Was Rossum frightened in his cradle by a lambda when he was a > baby? Are some people afraid of lambdas the way others are afraid of > spiders? "Language designers are a superstitious and cowardly lot..." From steve at REMOVE-THIS-cybersource.com.au Thu Dec 11 15:09:51 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 Dec 2008 20:09:51 GMT Subject: newbie question: if var1 == var2: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> <87y6ymzecp.fsf@daycos.com> Message-ID: <01516b1e$0$20639$c3e8da3@news.astraweb.com> On Thu, 11 Dec 2008 13:44:22 -0600, Kirk Strauser wrote: > At 2008-12-11T17:24:44Z, rdmurray at bitdance.com writes: > >> >>> ' ab c \r\n'.rstrip('\r\n') >> ' ab c ' >> >>> ' ab c \n'.rstrip('\r\n') >> ' ab c ' >> >>> ' ab c '.rstrip('\r\n') >> ' ab c ' > > I didn't say it couldn't be done. I just like the Perl version better. def chomp(s): return s.rstrip('\r\n') And now you have chomp. -- Steven From mail at johnohagan.com Tue Dec 16 03:16:24 2008 From: mail at johnohagan.com (John O'Hagan) Date: Tue, 16 Dec 2008 08:16:24 +0000 Subject: Python music sequencer timing problems In-Reply-To: <200812150332.08748.mail@johnohagan.com> References: <3b52b652-df61-4eb4-bcff-0d1fb6f20891@r15g2000prh.googlegroups.com> <49451835$0$17068$6e1ede2f@read.cnntp.org> <200812150332.08748.mail@johnohagan.com> Message-ID: <200812160816.26006.mail@johnohagan.com> On Mon, 15 Dec 2008, John O'Hagan wrote: > On Sun, 14 Dec 2008, Bad Mutha Hubbard wrote: > > John O'Hagan wrote: > > > On Wed, 10 Dec 2008, badmuthahubbard wrote: > > [...] > > > > from time import time, sleep > > > > > > start = time() > > > for event in music: > > > duration=len(event) #Really, the length of the event > > > play(event) > > > while 1: > > > timer = time() > > > remaining = start + duration - timer > > > if remaining < 0.001: > > > break > > > else: > > > sleep(remaining / 2) > > > stop(event) > > > start += duration > > > > Very interesting approach, halving the remaining duration. Right now > > I'm not working with note-offs, Csound takes care of the duration. I > > just need to be able to call the notes at the right times. > > [...] > > I'm also using the above code without the "stop(event)" line for playing > non-midi stuff (fixed-length samples for example), which from the sound of > it also applies to your requirement - IOW, you _can_ use it just to start > notes at the right time, because the note-playing loop sleeps till then. > And as I realized after having a good sleep myself, this is only useful for timing events which occur sequentially and do not overlap, which is how my program works because it generates the events in real time, but which may be of no use in your case. But I suppose the same principle could be applied to reduce the number of calls needed in a separate timing thread. Unless of course each event contained the start-time of the next event as an attribute....? John From pavlovevidence at gmail.com Wed Dec 10 21:55:59 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 10 Dec 2008 18:55:59 -0800 (PST) Subject: internal circular class references References: Message-ID: On Dec 10, 5:26?pm, Ethan Furman wrote: > Greetings List! > > I'm writing a wrapper to the datetime.date module to support having no > date. ?Its intended use is to hold a date value from a dbf file, which > can be empty. > > The class is functional at this point, but there is one thing I would > like to change -- datetime.date.max and datetime.date.min are class > attributes of datetime.date, and hold datetime.date values. ?At this > point I have to have two lines outside the actual class definition to do > the same thing, e.g.: > > > ? ?class NullDate(object): > ? ? ? ?"adds null capable DateTime.Date constructs" > ? ? ? ?__slots__ = ['_date'] > ? ? ? ?def __new__(cls, date='', month=0, day=0): > ? ? ? ? ? ?nulldate = object.__new__(cls) > ? ? ? ? ? ?nulldate._date = "" > ? ? ? ? ? ? ? ? . > ? ? ? ? ? ? ? ? . > ? ? ? ? ? ? ? ? . > ? ? ? ? ? return nulldate > ? ? ? ?def __getattr__(self, name): > ? ? ? ? ? ?if self: > ? ? ? ? ? ? ? ?attribute = self._date.__getattribute__(name) > ? ? ? ? ? ? ? ?return attribute > ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ?if callable(dt.date.__dict__[name]): > ? ? ? ? ? ? ? ? ? ?return int > ? ? ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ? ? ?return 0 > ? ? ? ?def __nonzero__(self): > ? ? ? ? ? ?if self._date: > ? ? ? ? ? ? ? ?return True > ? ? ? ? ? ?return False > ? ? ? ?@classmethod > ? ? ? ?def fromordinal(cls, number): > ? ? ? ? ? ?if number: > ? ? ? ? ? ? ? ?return cls(dt.date.fromordinal(number)) > ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ?return cls() > ? ?NullDate.max = NullDate(dt.date.max) > ? ?NullDate.min = NullDate(dt.date.min) > > > How can I move those last two lines into the class definition so that: > ? ?1) they are class attributes (not instance), and > ? ?2) they are NullDate type objects? It can't be done by any straightforward method I know of. I advise you not to worry about it, and just define them afterwards, perhaps with an apologetic comment saying you would have put them inside the class definition if you could have. If the out-of-scope issue bothers you that much, you could use some metaclass hackery to run a method that defines the class attributes after the class is created, at the unrecommendable cost of confusing most readers. Here is a very simple example: def make_class_and_run_postcreate(name,bases,clsdict): cls = type.__new__(type,name,bases,clsdict) cls.__postcreate__() return cls class A(object): __metaclass__ = make_class_and_run_postcreate @classmethod def __postcreate__(cls): cls.internal_circular_class_ref = cls() BTW, if you don't mind some criticism of your code, the code you posted seems to be much too complex for the job you're describing. First of all, do you even need to wrap the datetime.date class? With Python's duck typing ability, you could have a separate NullDate class to go alongside the datetime.date, and use a regular datetime.date object when the date is present, and NullDate when it's absent. If necessary you can subclass datetime.date to add any new methods it would have to have. Use a factory function to return either NullDate or a datetime.date depending on whether the dbf cell is empty. class ValidDate(datetime.date): def is_valid(self): return True class NullDate(object): # implement any necessary methods of datetime.date interface here def is_valid(self): return False def create_date_from_dbf_cell(dbf_cell): if dbf_cell.empty(): return NullDate() return ValidDate(dbf_cell.value) If you do this, you don't have to muck around with __getattr__ or __new__ or snooping to datetime.date's class dict anything like that. Carl Banks From mnordhoff at mattnordhoff.com Wed Dec 17 06:32:22 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Wed, 17 Dec 2008 11:32:22 +0000 Subject: Free place to host python files? In-Reply-To: References: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> <47c890dc0812161625o76f5c7e6lb8809b99f6962d32@mail.gmail.com> Message-ID: <4948E346.7090009@mattnordhoff.com> James Mills wrote: > On Wed, Dec 17, 2008 at 10:25 AM, Chris Rebert wrote: >> I'll plug Bitbucket (http://bitbucket.org/). It gives you 150MB of >> Mercurial hosting for free, along with a bug tracker and wiki. And I >> hear it's implemented using Django. > > FreeHG (http://freehg.org) is pretty good too :) > > cheers > James I'll throw in too. No wiki, though. And , I guess. -- From warren at delsci.com Wed Dec 3 17:49:19 2008 From: warren at delsci.com (Warren DeLano) Date: Wed, 3 Dec 2008 14:49:19 -0800 Subject: "as" keyword woes Message-ID: <896B75251BA19745A529B1B867893FA50679C8@planet.delsci.local> > Because it can be used at the import statement to let the imported thing > be known under another name? > Something like: > > >>> import xml.etree.ElementTree as ET Yes, but that syntax worked fine for years without "as" actually having to be a keyword. There must be something more going on here... I have to believe that was some reason or benefit gained from making it a keyword, and thus prohibiting its use anywhere else, as opposed to sticking with the status quo. Otherwise this would merely be a pointless change (perhaps even destructive!). From google at mrabarnett.plus.com Wed Dec 24 14:10:51 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 24 Dec 2008 19:10:51 +0000 Subject: [SPAM] VERY simple string comparison issue In-Reply-To: <89f89940812241027o40e3d079v9f9d76e76b1af4a6@mail.gmail.com> References: <89f89940812241027o40e3d079v9f9d76e76b1af4a6@mail.gmail.com> Message-ID: <4952893B.4020008@mrabarnett.plus.com> Brad Causey wrote: > Python Version: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC > v.1310 32 bit (Intel)] on win32 > > List, > > I am trying to do some basic log parsing, and well, I am absolutely > floored at this seemingly simple problem. I am by no means a novice in > python, but yet this is really stumping me. I have extracted the > pertinent code snippets and modified them to function as a standalone > script. Basically I am reading a log file ( in this case, testlog.log) > for entries and comparing them to entries in a safe list (in this case, > safelist.lst). I have spent numerous hours doing this several ways and > this is the most simple way I can come up with: > > > import string > > safelistfh = file('safelist.lst', 'r') > safelist = safelistfh.readlines() > > logfh = file('testlog.log', 'r') > loglines = logfh.readlines() > > def safecheck(line): > for entry in safelist: > print 'I am searching for\n' > print entry > print '\n' > print 'to exist in\n' > print line > comp = line.find(entry) > if comp <> -1: > out = 'Failed' > else: > out = 'Passed' > return out > Unless I've misunderstood what you're doing, wouldn't it be better as: def safecheck(line): for entry in safelist: print 'I am searching for\n' print entry print '\n' print 'to exist in\n' print line if entry in line: return 'Passed' return 'Failed' > for log in loglines: > finalentry = safecheck(log) > if finalentry == 'Failed': > print 'This is an internal site' > else: > print 'This is an external site' > > Actually, I think it would be better to use True and False instead of 'Passed' and 'Failed. > The contents of the two files are as follows: > > > http://www.mysite.com > > > > http://www.mysite.com/images/homepage/xmlslideshow-personal.swf > > > It seems that no matter what I do, I can't get this to fail the " if > comp <> -1:" check. (My goal is for the check to fail so that I know > this is just a URL to a safe[internal] site) > My assumption is that the HTTP:// is somehow affecting the searching > capabilities of the string.find function. But I can't seem to locate any > documentation online that outlines restrictions when using special > characters. > > Any thoughts? > You'll still need to strip off the '\n'. From castironpi at gmail.com Tue Dec 2 21:05:47 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 2 Dec 2008 18:05:47 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> <00ab327a-c3fc-4b15-a084-4f8c6aed6a8e@o2g2000yqd.googlegroups.com> Message-ID: <8119ab7e-09f1-44de-bdbc-8fdff969d9e4@33g2000yqm.googlegroups.com> On Dec 2, 6:24?pm, r wrote: > I added you name to my "for" list. thanks +1 entertaining thread. From benjamin.kaplan at case.edu Fri Dec 5 14:00:46 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 5 Dec 2008 14:00:46 -0500 Subject: slow Python 3.0 write performance? In-Reply-To: References: Message-ID: On Fri, Dec 5, 2008 at 1:54 PM, Istvan Albert wrote: > Could someone run the code below on both Python 2.5 and 3.0 > > For me (on Windows) it runs over 7 times slower with Python 3.0 > > import time > > lo, hi, step = 10**5, 10**6, 10**5 > > # writes increasingly more lines to a file > for N in range(lo, hi, step): > fp = open('foodata.txt', 'wt') > start = time.time() > for i in range( N ): > fp.write( '%s\n' % i) > fp.close() > stop = time.time() > print ( "%s\t%s" % (N, stop-start) ) > > > > -- > http://mail.python.org/mailman/listinfo/python-list > This bug was already found. http://groups.google.com/group/comp.lang.python/browse_thread/thread/9046eee09137c657# -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrew at doadesweb.co.uk Wed Dec 10 13:14:46 2008 From: andrew at doadesweb.co.uk (Andrew D) Date: Wed, 10 Dec 2008 10:14:46 -0800 (PST) Subject: get todays files References: <3090b59b-a0b2-4bfb-a08f-6d6accfb363a@k36g2000pri.googlegroups.com> Message-ID: <26ee72ee-ebfd-4719-a1b2-22665fec9c0d@i20g2000prf.googlegroups.com> On Dec 10, 6:13?pm, Steve Holden wrote: > Andrew D wrote: > > On Dec 10, 5:55 pm, Steve Holden wrote: > >> Andrew D wrote: > >>> I have a script that will login to my ftp server and download all the > >>> backup files, but I want it to only download the files that were > >>> created today, e.g. if I ran the script today I want it to only fetch > >>> files created today. > >>> I am really not sure about how to do this, but it is quite important > >>> to me, so all help is highly appreciated! > >> IIRC there's an "ftpmirror" script in the Tools directory (if you're on > >> Windows - Linux/Unix users have to download the source). I adapted it to > >> several different purposes. > > > Thanks Steve, > > > I don't want to sound rude here, but I really want some code to add to > > my script so that it will only download todays files. > > That's OK. Maybe somebody's already got that code ready to go. I don't ... > > regards > ?Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ Thank you anyway Steve! Lets hope someone has the code ;) Andrew From gruszczy at gmail.com Fri Dec 12 06:15:12 2008 From: gruszczy at gmail.com (=?UTF-8?Q?Filip_Gruszczy=C5=84ski?=) Date: Fri, 12 Dec 2008 12:15:12 +0100 Subject: Removing None objects from a sequence In-Reply-To: References: Message-ID: <1be78d220812120315y70688a4do455bdf41d7e53b03@mail.gmail.com> I don't mean memory, but space in code ;-) I'll try this generator :) -- Filip Gruszczy?ski From skip at pobox.com Tue Dec 9 16:39:24 2008 From: skip at pobox.com (Skip Montanaro) Date: Tue, 9 Dec 2008 21:39:24 +0000 (UTC) Subject: Test message - please ignore Message-ID: Testing a new news-to-mail gateway on mail.python.org. This post is from gmane. Please ignore. Thx, Skip Montanaro From akineko at gmail.com Mon Dec 22 18:43:21 2008 From: akineko at gmail.com (akineko) Date: Mon, 22 Dec 2008 15:43:21 -0800 (PST) Subject: 64-bit / 128-bit data element type for array? References: <880c8478-8b40-40e0-8597-aef960612f09@s9g2000prg.googlegroups.com> Message-ID: Robert wrote: > Ah, good. numpy lets you construct your own data types from the primitives. > Since you don't actually need uint128 arithmetic, you don't need a uint128 > primitive. You can just use dtype('V16') (meaning "void, 16 bytes long") ... Impressive. I installed NumPy and it worked like a charm (I used uint64). The above feature is quite useful as the bus size inside a microchip is getting wider and wider (to get higher performance). Again, thank you for replying to my posting. Happy Holidays! Aki Niimura From luismgz at gmail.com Mon Dec 22 14:50:17 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Mon, 22 Dec 2008 11:50:17 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: <1d03c66b-c725-42f4-af6e-2351a7841b30@z1g2000yqn.googlegroups.com> On Dec 22, 3:44?pm, r wrote: > Steve Holden > > > What makes you assume this is a zero-sum game, and that Python won't > > survive if any other language becomes popular. Every language borrows > > from those that came before it. Terms like "outright plagiarism" don't > > encourage rational debate, and make you seem like a troll who is more > > interested in stirring up controversy than actually doing things to help > > promote the language. > > This is a war Steve, and i will explain why. Python does not need to > compete with perl, lisp, C, basic, etc, etc. WHY, well because python > is SO radically different than those languages. Ruby on the other > hand, took most from python, the only difference is Ruby's full OO > integration.(12.method()). Since Ruby is so similar to python we must > consider that some people who would have found only python in this > niche now could go to Ruby. I am for choices, but this is out and out > robbery! > Of course we must stand on the shoulders of greater minds than our own > to get ahead, but using someone's knowledge against them is wrong. If > Ruby want's to incorporate so many Pythonian ideas into their > language, at least put a note in the tutorial giving credit to Guido > for his wisdom. Don't use our ideas and then bash python in the next > breath! > > > I have an article about the Zen coming up in "Python Magazine" so I > > won't steal its thunder. Suffice it to say that people take the Zen far > > too seriously. Anyone who does so undermines their own credibility as a > > Python commentator. This isn't a war. Stop being childish. > > I was speaking to the loyalty of Pythonista's. Of course we are not > really going to slay mats, come on Steve, get real! > > > If all you want from a language is speed, go use C. I would avoid > > assembly language though, since a modern optimizing C compiler will > > often beat an assembly language programmer for execution speed, and the > > programming time will definitely be shorter. But to make speed the > > be-all and end-all is a witless approach. Speed is definitely not why > > dynamic languages' popularity is increasing. Speed *is* still relevant > > in certain areas, and completely irrelevant in others. > > Come on Steve, i am NOT saying speed is the only thing that matters > here! But it is very important. I never compared Python to C, that is > madness. But it must be better, faster, smarter than it's direct > competition(ruby)... you agree?? > > > Much more of this kind of tripe and nobody will read what you write > > anyway. You will hear the plonking of a hundred thousand newsreaders > > every time you post. > > Oh Steve... Listen, my words are ment as a wake-up-call to all who > still love Python, and i believe you are one of them. Maybe old age > has slowed your hand, that's OK, Us "youngsters" will take the helm. > And be serious, do you really think this group is read by "hundreds-of- > thousands of news readers? I wish it were, but I highly doubt it. Dude, calm down... There is no war here. Please turn off your computer, go take a walk for awhile, experience some real life in the outer world, and then think about this again. Python is cool language, Ruby too. We are all happy and competition is good. Nobody will win this "war" and the loser won't be annihilated. I hope there will be some healthy cross-pollination. There is actually, for example python borrowed list-comprehensions from haskell and I've never heard any haskell fan calling for jihad. Did you know that people are looking forward to use pypy to create a fast ruby implementation? Pypy is being developed by python developers and they will be happy to see a ruby, perl, logo or whatever language implemented with pypy. We are talking about tools, not religions. Those who use them to create useful, real life applications know it. Soon, we will be able to use python libraries from ruby and the other way around. the differences will be just a matter of taste, different syntax to achieve the same tasks. Luis From kermit.group at gmail.com Mon Dec 8 00:26:27 2008 From: kermit.group at gmail.com (Group) Date: Mon, 08 Dec 2008 13:26:27 +0800 Subject: A question about reference in Python. Message-ID: <493CB003.3080209@gmail.com> Hello, I'm studying algorithom. For concentrating on the question itself, I intend to use Python to implement the algorithoms. Now, I want to write a Red-Black Tree, and a List structure. In C/C++, I can use pointers to refer to children notes (or next notes). But, in Python, how can I do it? Except the sequence, I know not any way. You'd better help me understan how can I transform the following C code into Python: /* a List */ struct { int data; int *next; int *prev; } That's all. Thanks! Kermit From clp at rebertia.com Sat Dec 20 22:38:35 2008 From: clp at rebertia.com (Chris Rebert) Date: Sat, 20 Dec 2008 19:38:35 -0800 Subject: linecache vs egg - reading line of a file in an egg In-Reply-To: References: Message-ID: <47c890dc0812201938y4f6dbd73jd25453fb43161d9f@mail.gmail.com> On Sat, Dec 20, 2008 at 7:18 PM, R. Bernstein wrote: > Does linecache work with source in Python eggs? If not, is it > contemplated that this is going to be fixed or is there something else > like linecache that currently works? I believe it already does. FYI, eggs are just zip files with a certain file/directory structure. And linecache seems to handle reading from zipfile modules. Ergo, linecache can read source from eggs. Quoting from the linecache docs (http://docs.python.org/library/linecache.html), emphasis mine: linecache.getline(filename, lineno[, module_globals]) If a file named filename is not found, the function will ***look for it in the module search path, sys.path***, after first checking for a PEP 302 __loader__ in module_globals, in case the module was ***imported from a zipfile*** or other non-filesystem import source. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From jason.scheirer at gmail.com Tue Dec 2 18:32:25 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Tue, 2 Dec 2008 15:32:25 -0800 (PST) Subject: Multiple Versions of Python on Windows XP References: Message-ID: <994220a5-ff22-4c4b-8fe2-bbe3d609b90a@k36g2000pri.googlegroups.com> On Dec 1, 4:49?pm, "Colin J. Williams" wrote: > Could anyone please point me to > documentation on the way the msi > installer handles multiple versions eg. > Python 2.5, 2.6 and 3.0? > > What changes are made to the registry? > > Is there some way to specify a default > version in such a way that it can be > changed as necessary? > > PyScripter uses an option to select a > version eg. > > C:\Program > Files\PyScripter\PyScripter.exe --python26 > > but I'm having some trouble with it when > I attempt edit a python file from the > Windows Explorer. > > I would appreciate any information. > > Colin W. Some more factoids that may be of use: 1. The last Python you install will take over all the file associations, start menu stuff, etc. 2. You can enumerate over the Pythons you have installed in \ \HKEY_LOCAL_MACHINE\Software\Python\PythonCore\ 3. If you silently install a Python PACKAGE made with distutils' bdist_msi, it will by default install to the latest Python version it finds (2.6 > 2.5 > 2.4 > 2.3) From fetchinson at googlemail.com Sat Dec 27 21:44:38 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 27 Dec 2008 18:44:38 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: >>>> I agree that array.array is more efficient than a list but the input >>>> for my function will come from PIL and PIL returns a list. So I have a >>>> list to begin with which will be passed to the C function. >>> With recent versions of PIL, numpy can create an array from an Image very >>> quickly, possibly without any copying of memory. >> >> What exactly do you mean? (1) PIL creates a list which can be easily >> converted by numpy to a numpy.array or (2) with the help of numpy one >> can create a numpy.array from an image directly? > > (2) a = numpy.asarray(img) Thanks, I didn't know about this, maybe it will be useful. >> Since I will have to pass the list or numy.array to C anyway I don't >> see any advantage to (1) although (2) can be useful. > > (1) is still somewhat useful, if you're willing to bear the cost of the > numpy > dependency. The conversion code from any Python sequence to a numpy array of > the > desired type and dimensionality is a 2-liner (function call and error > check). > The memory is managed by numpy, so all you have to do is manage the refcount > of > the array object like any other Python object. > > Okay, 5-liner given C's verbosity: > > intx = PyArray_FROM_OTF(pyintx, PyArray_INT, NPY_IN_ARRAY); > if (!intx) { > PyErr_SetString(PyExc_ValueError, "intx must be an array of ints"); > goto fail; > } Yes, the dependency on numpy is my main concern. If it will help with my problem I don't mind the dependency actually, so I'll do more detailed benchmarks first. Thank you, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From narkewoody at gmail.com Fri Dec 19 08:50:12 2008 From: narkewoody at gmail.com (Steven Woody) Date: Fri, 19 Dec 2008 21:50:12 +0800 Subject: How to parsing a sequence of integers In-Reply-To: <494ba258$0$18998$426a74cc@news.free.fr> References: <494ba258$0$18998$426a74cc@news.free.fr> Message-ID: On Fri, Dec 19, 2008 at 9:33 PM, Bruno Desthuilliers wrote: > Steven Woody a ?crit : >> >> Hi, >> >> I am a newbie and is reading the python book. Could anyone tell me, >> how to parsing the following string >> "123 100 12 37 ..." > >> into a list of integers on which I can then apply max()/min()? > > source = "123 100 12 37" > list_of_ints = [int(part) for part in source.strip().split()] > >> >> In additional to max/min, is there something like average()? > > Not AFAIK, but it's really trivial > > def average(lst): > """ assume lst is a list of numerics """ > return sum(lst) / len(lst) > Cool! Thank all of you. From sjmachin at lexicon.net Fri Dec 5 17:32:23 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 5 Dec 2008 14:32:23 -0800 (PST) Subject: Python 3.0 automatic decoding of UTF16 References: <5u8o06xbqf.ln2@joeserver.homelan.net> Message-ID: On Dec 6, 5:36?am, Johannes Bauer wrote: > So UTF-16 has an explicit EOF marker within the text? I cannot find one > in original file, only some kind of starting sequence I suppose > (0xfeff). The last characters of the file are 0x00 0x0d 0x00 0x0a, > simple \r\n line ending. Sorry, *WRONG*. It ends in 00 0d 00 0a 00. The file is 1559 bytes long, an ODD number, which shouldn't happen with utf16. The file is stuffed. Python 3.0 has a bug; it should give a meaningful error message. Python 2.6.0 silently ignores the problem [that's a BUG] when read by a similar method: | >>> import codecs | >>> lines = codecs.open('x.txt', 'r', 'utf16').readlines() | >>> lines[-1] | u'[PhonePBK004]\r\n' Python 2.x does however give a meaningful precise error message if you try a decode on the file contents: | >>> s = open('x.txt', 'rb').read() | >>> len(s) | 1559 | >>> s[-35:] | '\x00\r\x00\n\x00[\x00P\x00h\x00o\x00n\x00e\x00P\x00B\x00K \x000\x000\x004\x00]\x00\r\x00\n\x00' | >>> u = s.decode('utf16') | Traceback (most recent call last): | File "", line 1, in | File "C:\python26\lib\encodings\utf_16.py", line 16, in decode | return codecs.utf_16_decode(input, errors, True) | UnicodeDecodeError: 'utf16' codec can't decode byte 0x00 in position 1558: truncated data HTH, John From castironpi at gmail.com Mon Dec 29 08:53:09 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 05:53:09 -0800 (PST) Subject: Read-Write Lock vs primitive Lock() References: <277c1be7-2560-4fd6-9610-0b4398dc3719@x16g2000prn.googlegroups.com> Message-ID: <0740d4b8-6c1e-432a-a2c4-ca73473831dd@a12g2000pro.googlegroups.com> On Dec 29, 4:17?am, k3xji wrote: > On 29 Aral?k, 11:52, "Gabriel Genellina" > wrote: > > > En Mon, 29 Dec 2008 05:56:10 -0200, k3xji escribi?: > snip > > > class wthread(threading.Thread): > > > ? ? def run(self): > > > ? ? ? ? ? ? try: > > > ? ? ? ? ? ? ? ? #GLOBAL_LOCK.acquireWrite() > > > ? ? ? ? ? ? ? ? #GLOBAL_LOCK.acquire_write() > > > ? ? ? ? ? ? ? ? GLOBAL_LOCK.acquire() > > > ? ? ? ? ? ? ? ? for i in range(GLOBAL_LOOP_COUNT): > > > ? ? ? ? ? ? ? ? ? ? GLOBAL_VAR = 4 > > > ? ? ? ? ? ? finally: > > > ? ? ? ? ? ? ? ? #GLOBAL_LOCK.release_write() > > > ? ? ? ? ? ? ? ? GLOBAL_LOCK.release() > > > Note that the thread acquires the lock ONCE, repeats several thousand > > times an assignment to a *local* variable called GLOBAL_VAR (!) snip > > class wthread(threading.Thread): > > ? ? ? def run(self): > > ? ? ? ? ? global GLOBAL_VAR > > ? ? ? ? ? for i in xrange(GLOBAL_LOOP_COUNT): > > ? ? ? ? ? ? ? GLOBAL_LOCK.acquire() > > ? ? ? ? ? ? ? try: > > ? ? ? ? ? ? ? ? ? GLOBAL_VAR += 1 > > ? ? ? ? ? ? ? finally: > > ? ? ? ? ? ? ? ? ? GLOBAL_LOCK.release() > > With that, primitive locks perform 10 times better than Read-Write > lock. See above. snip Gabriel's point (one of them) was that 'GLOBAL_VAR' isn't global in your example. Your 'wthread' objects aren't sharing anything. He added the 'global GLOBAL_VAR' statement, which is important From skip at pobox.com Tue Dec 16 09:29:27 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 16 Dec 2008 08:29:27 -0600 Subject: Free place to host python files? In-Reply-To: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> References: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> Message-ID: <18759.47943.95858.384595@montanaro-dyndns-org.local> feba> I'm getting started in python, and it would be helpful to have a feba> place to put up various code snippets I've made, so I don't have feba> to send them individually to each person I want to show it to. feba> I'd prefer to use something that would give me a directory for my feba> use only, instead of something where you can only upload one at a feba> time. I'd especially like to avoid stuff that uses CAPTCHAs feba> and/or forced waiting periods. http://pastebin.com/? -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From p.f.moore at gmail.com Tue Dec 16 12:56:57 2008 From: p.f.moore at gmail.com (Paul Moore) Date: Tue, 16 Dec 2008 09:56:57 -0800 (PST) Subject: Does Python3 offer a FrozenDict? References: Message-ID: On 16 Dec, 17:28, bearophileH... at lycos.com wrote: > Johannes Bauer: > > > is there anything like a frozen dict in Python3, so I could do a > > foo = { FrozenDict({"a" : "b"}): 3 } > > You can adapt this code to Python3 (and post a new recipe? It may be > positive to create a new section of the Cookbook for Py3 only):http://code.activestate.com/recipes/414283/ There's actually only tiny changes needed (I believe) - Change exception syntax: raise AttributeError("A frozendict cannot be modified.") - (bugfix for the original version): add **kw arg to __new__ (passed to dict.__init__) Simple testing looks OK. And the resulting code is OK for both 2.x and 3.0. Moral - don't assume that all code needs to be rewritten for Python 3.0 :-) Paul. PS I imagine that 2to3 would have fixed this up fine, but it was so easy to do by hand that I didn't bother :-) From n.kottiyath at gmail.com Tue Dec 16 21:47:41 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Tue, 16 Dec 2008 18:47:41 -0800 (PST) Subject: Can anyone suggest a good HTTP/1.1 web client? References: Message-ID: <412038d6-81c0-4615-aab5-d3cea4093dfc@p2g2000prn.googlegroups.com> > If you'd like to help out with the new Twisted HTTP client, that would be > wonderful. ?Even if you can just try it out and report any problems you run > into, that would be immensely helpful. > > Jean-Paul I would love to help out with the client. But, I am extremely tied up at the current moment. I would be able to provide any sort of meaningful contribution only after ~a month. I can surely try this out and upload any bugs in the ticket you mentioned. Also, is there any planned date for persistent connections? If not, that will be the first thing I will be working on after my assignment is over - since it increasingly looks like it is essential to my system (actually, any REST applications). Thank you very much, Jean-Paul. Regards, K From castironpi at gmail.com Sun Dec 21 21:11:05 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 21 Dec 2008 18:11:05 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: <2dfbb87b-019e-43aa-a9ef-5de2b5ada846@s1g2000prg.googlegroups.com> On Dec 21, 6:14?pm, MRAB wrote: > Aaron Brady wrote: > > On Dec 21, 10:58 am, MRAB wrote: > >> Aaron Brady wrote: > >>> On Dec 21, 10:31 am, MRAB wrote: > > snip > >>>> The original format is a string. The result of '%' is a string if > >>>> there's only 1 placeholder to fill, or a (partial) format object (class > >>>> "Format"?) if there's more than one. Similarly, the format object > >>>> supports '%'. The result of '%' is a string if there's only 1 > >>>> placeholder to fill, or a new (partial) format object if there's more > >>>> than one. > >>>> ?>>> f = "%r %i" > >>>> ?>>> type(f) > >>>> > >>>> ?>>> f = f % (2, 3, 4) > >>>> ?>>> type(f) > >>>> > >>>> ?>>> f = f % 1 > >>>> ?>>> type(f) > >>>> > >>> Alright, so how are you handling: > >>>>>> f= "%s %i" > >>>>>> type( f ) > >>> > >>>>>> f= f% '%i' ?#now '%i %i' > >>>>>> type( f ) > >>> > >>>>>> f= f% 1 > >>>>>> type( f ) > >>> ? > >>> In other words, are you slipping '1' in to the very first available > >>> slot, or the next, after the location of the prior? > >> Let's assume that Format objects display their value like the equivalent > >> string format: > > >> ?>>> f = "%r %i" > >> ?>>> f > >> '%r %i' > >> ?>>> f = f % (2, 3, 4) > >> ?>>> f > >> > >> ?>>> f = f % 1 > >> ?>>> f > >> '(2, 3, 4) 1' > > >> ?>>> f = "%s %i" > >> ?>>> f > >> '%s %i' > >> ?>>> f = f % '%i' > >> ?>>> f > >> > >> ?>>> f = f % 1 > >> ?>>> f > >> '%%i 1' > > > I assume you meant '%i 1' since there are no more flags in f, and it's > > returned to a regular string. > > Correct. > > > 'f %= 1' doesn't work any more as in-place modulo, since one time, 'f' > > is a Format object, the other, 'f' is a string. ?Just raise an > > exception for that (or assign to __class__ IINM if I'm not mistaken). > > All assignments rebind, even the augmented form: > > ?>>> class C1(object): > ? ? ? ? def __mod__(self, value): > ? ? ? ? ? ? ? ? return C2() > > ?>>> class C2(object): > ? ? ? ? def __mod__(self, value): > ? ? ? ? ? ? ? ? return C2() > > ?>>> f = C1() > ?>>> f > <__main__.C1 object at 0x00D144F0> > ?>>> f % 0 > <__main__.C2 object at 0x00D143F0> > ?>>> f %= 0 > ?>>> f > <__main__.C2 object at 0x00D145B0> > > > > > Actually, the class you showed is kind of nifty. ?Tuples are correctly > > interpolated. ?I think on the whole you'll use more parenthesis, since > > each term in the tuple appears separately, and might be an expression > > (have a lower-precedence op.), as well as more modulo signs. > > > You can currently do-it-yourself, you just need a constructor in the > > format string. > > >>>> f = Format("%r %i") > >>>> type(f) > > > >>>> f = f % (2, 3, 4) > >>>> type(f) > > > > > Or, as someone suggested earlier, a new literal marking: > > Yes, I suggested that earlier, but it isn't needed because you can > create a format object with "Format(string)". However, most of the time > you won't bother to create a format object explicitly because of: > > class str(object): > ? ? ?def __mod__(self, value): > ? ? ? ? ?return Format(self) % value > > >>>> f = f"%r %i" > >>>> type(f) > > > > ?>>> # Explicitly > ?>>> f = Format("%r %i") > ?>>> f > > ?>>> f % (2, 3, 4) > > ?>>> > ?>>> # Implicitly, relying on the __mod__ method of str > ?>>> f = "%r %i" > ?>>> f > '%r %i' > ?>>> f % (2, 3, 4) > > > I'd also like to add that there's nothing to prevent format objects from > having other methods where multiple placeholders can be filled in one call: > > ?>>> # By position > ?>>> f = Format("%r %i") > ?>>> f > > ?>>> f.fill([(2, 3, 4), 1]) > '(2, 3, 4) 1' > ?>>> > ?>>> # By name > ?>>> f = Format("%{tuple}r %{int}i") > ?>>> f > > ?>>> f.fill({"tuple": (2, 3, 4), "int": 1}) > '(2, 3, 4) 1' You're choosing to favor the '.chain()' method over the '.fill()' method for the behavior of '%'. I don't think you've justified it though. >>> Format( "%r %i" ).chain( ( 2, 3, 4 ) ).chain( 0 ) '(2, 3, 4) 0' >>> Format( "%r %i" ).fill( ( 2, 3, 4 ), 0 ) '(2, 3, 4) 0' Plus, I almost think we've almost attained defeating the purpose. From bignose+hates-spam at benfinney.id.au Thu Dec 4 01:36:44 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 04 Dec 2008 17:36:44 +1100 Subject: "as" keyword woes References: Message-ID: <87fxl4v43n.fsf@benfinney.id.au> "Warren DeLano" writes: > > But I can offer what I believe is a good reason why it *should* be > > a reserved word: Because simple is better than complex, and > > special cases aren't special enough to break the rules. > > So you prefer broken code to broken rules, eh? Your customers must > love that! This is exactly the kind of ivory-tower thinking I feared > might be behind the decision (form over function, damn the users to > hell, etc.) I don't know how you infer any of those from what I said, nor from the process of introducing features in Python. None of what you say there rings at all true with anything I've experienced in Python's core or the attitudes surrounding development if the language; indeed, quite the opposite. > Anyway, it seems obvious that the right decision for our customers > (or more importantly, for their countless lines of > autogenerated-Python log, state, and code files from the past > decade) is to stick with C/Python 2.5.x for the time being [?] This is an entirely reasonable and viable option, all the more so because of the comprehensive work done by the Python developers to continue the viability of the Python 2.x line and ease introduction of new features. Best of luck pursuing your goals. -- \ ?I'd like to see a nude opera, because when they hit those high | `\ notes, I bet you can really see it in those genitals.? ?Jack | _o__) Handey | Ben Finney From gamersunit at gmail.com Thu Dec 4 17:38:37 2008 From: gamersunit at gmail.com (Gregory Plantaine) Date: Thu, 4 Dec 2008 14:38:37 -0800 (PST) Subject: Find Files in a Folder Between 2 Dates Message-ID: <4c54b6c5-ae4d-4b89-8c6d-940c96de29bb@n33g2000pri.googlegroups.com> Is there a way to find all the files in a folder, between 2 dates? For example: Firstdate = 200801010000 Seconddate = 200801020000 Find all the files in C:\Folder that are between Firstdate and SecondDate. From s_david_rose at hotmail.com Thu Dec 11 13:04:27 2008 From: s_david_rose at hotmail.com (dave rose) Date: Thu, 11 Dec 2008 18:04:27 +0000 (UTC) Subject: Python to open command script file Message-ID: Hello all I would like to know how to do the following. I'd like to have a generic python program that the user will open a command-script file to do actions. So, my python program will get a list of servers, enumerate them within a checklistbox in wxpython. Then I want to open a command-file that will run against each selected server that will look like this: ---------------------------SAMPLE------------------------ copy abc.xyz from c:\source to u:\target copy all from c:\source to u:\target unload netshld from server1 -------------------------END SAMPLE---------------------- (where I have a class serverfuncs, where I can: s = serverfuncs() s.unload('', '') Really, I can do all the actions, but I don't know how to trigger them from an independent script file. Thanks! -Dave From jon at ffconsultancy.com Thu Dec 11 17:57:45 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Thu, 11 Dec 2008 22:57:45 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <452ba58b-9377-4463-85e2-5ecdaa25a129@t39g2000prh.googlegroups.com> Message-ID: Xah Lee wrote: > On Dec 10, 2:47?pm, John W Kennedy wrote: >> Xah Lee wrote: >> > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, >> > you'll have 50 or hundreds lines. >> >> C: >> >> #include >> #include >> >> void normal(int dim, float* x, float* a) { >> float sum = 0.0f; >> int i; >> float divisor; >> for (i = 0; i < dim; ++i) sum += x[i] * x[i]; >> divisor = sqrt(sum); >> for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; >> >> } > > i don't have experience coding C. The code above doesn't seems to > satisfy the spec. The input should be just a vector, array, list, or > whatever the lang supports. > The output is the same datatype of the same dimension. The output is in the preallocated argument "a". It is the same type (float *) and has the same dimension. That is idiomatic C. You could define a struct type representing a vector that includes its length and data (akin to std::vector<..> in C++) but it would still be nowhere near 50 LOC as you claimed. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From anton.ranieri.it at gmail.com Sat Dec 6 07:03:04 2008 From: anton.ranieri.it at gmail.com (anton.ranieri.it at gmail.com) Date: Sat, 6 Dec 2008 04:03:04 -0800 (PST) Subject: Insert Multiple Records Using One Insert Statemen with MySQLdb module Message-ID: <6d85c9db-2769-461b-bfe0-974e4fad5e07@k8g2000yqn.googlegroups.com> Hi, I'd like to insert Multiple Records Using One Insert Statement inserting one record using one insert statement works this is the example: import MySQLdb conn = MySQLdb.connect(host="localhost",.....) cursore = conn.cursor() cursore.execute('INSERT INTO frutta (nome, quantita) VALUES(%s, %s)', ('Pompelmi', 10) ) but when I try to insert Multiple Records Using One Insert Statement in this way: cursore.execute('INSERT INTO frutta (nome, quantita) VALUES(%s, %s)', ('Pompelmi', 10), ('Pompelmi', 10), ('Pompelmi', 10) ) it doesn't work! Antonella From prologic at shortcircuit.net.au Sun Dec 21 21:04:07 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Dec 2008 12:04:07 +1000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <5b15041d-c1e9-4b28-b8ca-89505e49fe83@a12g2000pro.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <7fc23c41-6bf8-4272-b405-acc092cbac87@r15g2000prd.googlegroups.com> <5b15041d-c1e9-4b28-b8ca-89505e49fe83@a12g2000pro.googlegroups.com> Message-ID: On Mon, Dec 22, 2008 at 11:37 AM, alex23 wrote: > On Dec 21, 10:11 am, r wrote: >> Most of the complaints i hear are the redundant use of self. >> Which I lamented about but have become accustom(brainwashed) to it. I >> would remove this if it where up to me. > > It's a shame Python wasn't released under some kind of license, one > that allowed its source to be, say, "opened" and modified. Otherwise > you would just implement this yourself and submit patches, right? +1 :) From __peter__ at web.de Thu Dec 18 04:28:08 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 18 Dec 2008 10:28:08 +0100 Subject: importing csv file into sqlite References: <21067453.post@talk.nabble.com> <21068111.post@talk.nabble.com> Message-ID: Chris Rebert wrote: >> klia wrote: >> for item in input: >> curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item) > I believe you need to change 'item' to '*item' to expand the list in > the call so that the function gets 4 additional args rather than 1 > additional arg that happens to be a list. But as I've never used the > DB-API before, this is just a guess. No, the execute() method call is correct. There must be a malformed row in the csv with only one field. Peter From martin.hellwig at dcuktec.org Wed Dec 3 17:02:24 2008 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 03 Dec 2008 22:02:24 +0000 Subject: "as" keyword woes In-Reply-To: References: Message-ID: <493701f0$0$194$e4fe514c@news.xs4all.nl> Warren DeLano wrote: > A bottom line / pragmatic question... hopefully not a FAQ. > > Why was it necessary to make "as" a reserved keyword? Because it can be used at the import statement to let the imported thing be known under another name? Something like: >>> import xml.etree.ElementTree as ET -- mph From prologic at shortcircuit.net.au Mon Dec 22 17:27:41 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 23 Dec 2008 08:27:41 +1000 Subject: Python is slow In-Reply-To: <6aad831b-80ce-40df-9b6e-571b1e822795@s1g2000prg.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <6r6hpfFfb643U3@mid.uni-berlin.de> <494E6FDA.4070401@mrabarnett.plus.com> <4585c27d-d7a9-480f-991c-a869161be55c@g38g2000yqn.googlegroups.com> <3392a51b-d3fd-4986-9c59-fecccc7272da@p2g2000prn.googlegroups.com> <6aad831b-80ce-40df-9b6e-571b1e822795@s1g2000prg.googlegroups.com> Message-ID: On Tue, Dec 23, 2008 at 4:42 AM, cm_gui wrote: > i am referring mainly to Python for web applications. > > Python is slow. Please just go away. You are making an embarrassment of yourself. --JamesMills From thomasmallen at gmail.com Fri Dec 19 16:17:03 2008 From: thomasmallen at gmail.com (tmallen) Date: Fri, 19 Dec 2008 13:17:03 -0800 (PST) Subject: mod_python resources References: <78064e7e-ba2c-4959-b5f8-4d1b928bc5fe@y18g2000yqn.googlegroups.com> <4lsl16-15a.ln1@archaeopteryx.softver.org.mk> Message-ID: Here's my problem (it's a conceptual one). Coming from the world of mod_php, each file can represent a page with no intervention. I was not able to achieve the same with mod_python when I tried, and for that matter, couldn't put the pieces together in a usable way. Let me start simply: If I wanted to create a trivial site, (Home, About, Contact) with a header and footer included, in PHP, it would be done as such: each page (index.php, about.php, contact.php) includes the template bits (header.php, footer.php). Is this simplicity achievable using Python? And by "simplicity," I'm referring to simplicity in execution; not necessarily an identical approach. Thanks, Thomas On Dec 17, 4:25?am, Graham Dumpleton wrote: > On Dec 17, 11:10?am, ?????? ??????????? wrote: > > > > I'm trying again because I'm stubborn. Maybe the fourth time will be > > > the charm... > > > > Are there any good tutorials out there for setting up Apache with > > > mod_python? > > > mod_python is depreceated, nobody uses it. usemod_wsgihttp://www.modwsgi.org/ > > The mod_python package is not deprecated, although it could be said to > be sleeping at the moment. You'll also probably still find that more > new people choose mod_python over mod_wsgi. This is because it has the > more obvious name to look for when Googling. It also has publisher and > PSP high level handler which are still attractive to many as they are > more lightweight and easier to get into than the large WSGI > frameworks. Finally, the Django folks still recommend in their > documentation to use mod_python. > > Anyway, if wanting to host a WSGI capable application, using mod_wsgi > would be the more obvious choice. If wanting to write your own > framework, or work at low level, basing it on WSGI rather than > mod_python specific APIs would certainly be a better long term > direction to take. > > Graham From febaen at gmail.com Mon Dec 15 13:29:49 2008 From: febaen at gmail.com (feba) Date: Mon, 15 Dec 2008 10:29:49 -0800 (PST) Subject: Need help improving number guessing game References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> <01564c98$0$21844$c3e8da3@news.astraweb.com> Message-ID: <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> Alright! This is feeling more like it. #!/usr/bin/python #Py3k, UTF-8 import random def setup(game, minr=1, maxr=99): #minr, maxr make minimum and maximum. Can be adjusted. game['minr'], game['maxr'] = minr, maxr game['gcount'] = 0 #Reset guess count game['target'] = random.randint(minr, maxr) def playerswitch(game): #Player Switch #if player's a witch: burn(her) if game['player'] == game['player1']: game['player'] = game['player2'] else: game['player'] = game['player1'] def youwin(game): if game['pnum'] == 1: print("CONGRATULATIONS! IT TOOK YOU %s GUESSES" % game ['gcount']) else: if game['player'] == game['player1']: game['p1sc'] += 1 else: game['p2sc'] += 1 end = "CONGRATULATIONS %s! SCORE -- P1:%s P2:%s" #Can the following line be more compact? print(end % (game['player'], game['p1sc'], game['p2sc'])) def playagain(game): playover = input("PLAY AGAIN? Y/N: ") if playover.strip().lower() == "y": game['play'] = True setup(game) else: print("GOOD BYE. PLAY AGAIN SOON!") game['play'] = False def autofinish(game): if game['maxr'] - game['minr'] == 2: print("...ONLY ONE OPTION LEFT!") youwin(game) playagain(game) def numplayers(game, prompt="1 OR 2 PLAYERS?\n> "): while True: num = input(prompt) try: num = int(num) except ValueError: print("BAD VALUE") else: break game['pnum'] = num def guesses(game): game['guess'] = int(input("[%s-%s]%s>> " \ #keeps user aware of who's turn it is, and the range % (game['minr'], game['maxr'], game['player']))) def guesscheck(game): if game['guess'] == game['target']: if game['pnum'] == 1: game['gcount'] += 1 youwin(game) playagain(game) elif game['guess'] >= game['maxr']: print("NUMBER MUST BE IN RANGE") guesses(game) guesscheck(game) elif game['guess'] <= game['minr']: print("NUMBER MUST BE IN RANGE") guesses(game) guesscheck(game) elif game['guess'] > game['target']: print("TOO HIGH") if game['pnum'] == 1: game['gcount'] += 1 game['maxr'] = game['guess'] else: print("TOO LOW") if game['pnum'] == 1: game['gcount'] += 1 game['minr'] = game['guess'] def guessing(game): guesses(game) guesscheck(game) if game['pnum'] == 2: playerswitch(game) autofinish(game) def main(game=None): if game is None: game = {} print("WELCOME TO THE SUPER NUMBER GUESSING GAME!") numplayers(game) game['play'] = True game['player1'], game['player2'] = "P1", "P2" game['player'] = game['player1'] # P1 goes first #Scores start at 0 game['p1sc'], game['p2sc'], game['gcount'] = 0, 0, 0 setup(game) while game['play'] is True: guessing(game) if __name__ == "__main__": main() first off, I want to thank all of you for your help with this. I really don't think I could've learned all of this out nearly as quickly by reading tutorials and documentation, let alone had anything near the grasp I have on it now. '''This''' is why I like learning by doing. The only things I still don't really understand are .strip ().lower(), and try/except/else, and I plan on looking them up before I do anything else. In the past few hours I've gone from not having a clue what the whole {'fred': 0, 'barney': 0} thing was about to being able to fully understand what you're talking about, and put it into practice 2; I feel like this process is going quicker and quicker every time I refine it. It also feels like it's getting easier to solve various bugs when I create them they pop up. It might be because I'm getting into it and having more fun, because the refinements are less major each time, because they're easier to pick up, or some combination of all of those. Either way, I feel very excited about it. 3; I found some very helpful gedit plugins. While I was in preferences, I noticed you can have it highlight the margin; so I set that to 75 to try to keep from going over the character limit/line recommendation. Draw Spaces, a plugin, showing spaces is also pretty helpful. I also found a python auto complete plugin which I haven't used so far, but which looks very promising, along with a terminal program (Keeps me from juggling windows, anyway) 4; I readded the counter for one player games. Out of curiosity, what do you think of: if game['pnum'] == 1: game['gcount'] += 1 ? I'm not sure whether this is good or bad. On the one hand, it keeps it from adding to gcount without needing to, on the other hand it seems like it might be more wasteful to check pnum than to just add to gcount. It also makes it harder to adjust it to show gcount in two player mode, if you want to do that for some reason. 5; I added the ability for it to automatically complete when there's only one option left. I was amazed' I was actually going to ask for advice on how to do it here. I was going to say "I was thinking (blah blah)", but then I just typed it in, and it worked flawlessly. This goes back to one, but I'm very excited, and thankful. 6; can anyone think of anything else to add on to/do with this game? With the minr/maxr display, multiplayer, score keeping, and automation, I'm just about all of ideas. All I can think of left to add is 3 and 4 player modes, or a fork where player 2 can't win (kekekekeke. Though I'm not sure how to do it...), both of which I feel are somewhat pointless for a game like this. If I can't learn anything more from it, I will probably go back to reading python guides for a bit, and then try to make something else. From ivan.illarionov at gmail.com Thu Dec 18 06:09:26 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 18 Dec 2008 03:09:26 -0800 (PST) Subject: C API and memory allocation References: Message-ID: <59352942-e976-4ef4-bc40-c8953df0a792@c36g2000prc.googlegroups.com> On 18 ???, 03:51, Aaron Brady wrote: (snip) > How did you get a reference to the original > string object, with which to increment its reference count? Use the "O!" format instead of "s": PyObject *pystr; ... PyArg_ParseTuple(args, "O!", &PyStringObject, &pystr) ... Then you can use PyString_AS_STRING explicitly, and control ref. counts yourself. > How do you know its length to copy it into your own buffer? Use the "s#" format, as Gabriel has said. Ivan From gh at ghaering.de Thu Dec 4 08:15:40 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 04 Dec 2008 14:15:40 +0100 Subject: RELEASED Python 3.0 final In-Reply-To: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> Message-ID: Iain King wrote: > [...] Props. I just looked through the What's New and the change log, but I > couldn't find the answer to something: has any change been made to > how tabs and spaces are used as indentation? Can they still be > (inadvisably) mixed in one file? Or, more extremely, has one or the > other been abolished? As you have probably guessed: nothing changed here. Also see: http://www.python.org/dev/peps/pep-0666/ -- Gerhard From lewis.sarah93 at yahoo.com Fri Dec 5 00:08:48 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 21:08:48 -0800 (PST) Subject: Reduce Debt Message-ID: <86e2a593-25c1-45b5-936a-1589e5a0cb48@u14g2000yqg.googlegroups.com> Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From alessio.pace at gmail.com Mon Dec 1 08:32:07 2008 From: alessio.pace at gmail.com (Alessio Pace) Date: Mon, 1 Dec 2008 05:32:07 -0800 (PST) Subject: How to distribute a Python app together with its dependencies? References: <35377946-378c-484d-88cc-396145090d2f@l39g2000yqn.googlegroups.com> Message-ID: <97ee9678-1872-488b-9818-ff7937907f82@w3g2000yqc.googlegroups.com> On 1 Dic, 10:37, BlueBird wrote: > Alessio Pace wrote: > > Hi, > > > I have to distribute a Python application which relies on an external > > library, and I'm not very fluent in this kind of stuff with Python (I > > come from the Java world where I would have used the Maven build tool > > to create an "assembly with dependencies" of all it is needed to run > > the app), so I was wondering if someone here could give me some > > suggestions :-) > > > The external library is generally not present on the machines where I > > have to distribute my app, and the set of machines on which I have to > > distribute this application is not known a priori (it is just known > > they are Unix systems). In fact by means of SSH I will have to copy > > (and install) the app+library and make it runnable onto the specified > > destination(s). > > I have never used it myself, but bbfreeze claims to create packaged > versions of an application, for windows and Unix : > > http://pypi.python.org/pypi/bbfreeze/0.95.2 > Thank you. What's the difference with "Freeze" shipped with Python, or with PyInstaller ? Do you have experiences with any of them? From pruebauno at latinmail.com Thu Dec 4 11:18:23 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Thu, 4 Dec 2008 08:18:23 -0800 (PST) Subject: funny generator behaviour References: Message-ID: <7cb2dc1b-195a-447f-81ed-e0e094a60a9d@i24g2000prf.googlegroups.com> On Dec 4, 8:00 am, Edvin Fuglebakk wrote: > I have written a generator that puzzles me: > > The generator is supposed to create ordered selections of a set of > objects. repetition of objects is allowed and the selections should be > of a size determined by a pramter to the generator. > > Now, if I try to accummulate the generated selections into a list I get > some peculiar behaviour that I hope maybe some of you can help me > understand: > > Help much appreciated > -Edvin > > #straightforward acumulation. Does not give the expected result > >>> d=[] > >>> for f in orderedCombinations([1,2],3): > ... d.append(f) > ... > >>> d > [[1], [2], [1], [2], [1], [2], [1], [2]] > > #accumulating shallow copies of the genereated combinations works: > >>> d=[] > >>> for f in orderedCombinations([1,2],3): > ... d.append(f[:]) > ... > >>> d > [[1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 2, 2], [2, 1, 1], [2, 1, 2], [2, > 2, 1], [2, 2, 2]] > > #The generator: > def orderedCombinations(pool, k): > """ > Generator yielding ordered selections of size k with repetition from > pool. > """ > > if k == 1: > for m in pool: > yield [m] > > if k > 1: > > for m in pool: > for combo in orderedCombinations(pool, k-1): > > #insert and pop to avoid copying entire list > combo.insert(0,m) > yield combo > combo.pop(0) def orderedCombinations(pool, k): res=[[]] for i in xrange(k): res=[n+[m] for n in res for m in pool] return res From joe at strout.net Fri Dec 12 10:37:15 2008 From: joe at strout.net (Joe Strout) Date: Fri, 12 Dec 2008 08:37:15 -0700 Subject: concept of creating structures in python In-Reply-To: References: Message-ID: On Dec 11, 2008, at 10:52 PM, navneet khanna wrote: > I want to create a structure within a structure i.e. nested > structures in python. > I tried with everything but its not working. > my code is like this: > > class L(Structure): > > def __init__(self,Name='ND',Addr=0,ds_obj = D()): Change the default value of ds_obj here to None. Otherwise, you will certainly confuse yourself (there would be just one default object shared among all instances). > self.Name = Name > self.Addr = Addr > self.ds_obj = ds_obj > > > class D(Structure): > > def __init__(self,dataName='ND',index = 0,ele_obj=E()): > > self.dataName = dataName > self.index = index > self.ele_obj = ele_obj Same thing here with ele_obj -- have it default to None to save yourself grief. Otherwise, these look fine. > these are two structures. I want to refer D structure in L one and > use it. I want to access the value of D structure like L.D.index = 0. But you didn't name it "D" -- if you have an L object, say "foo", then you'd get to it's D object as foo.ds_obj (since that's what you named it in L.__init__). If you then wanted to get to that thing's E object, it'd be foo.ds_obj.ele_obj. Best, - Joe From jstroud at mbi.ucla.edu Sun Dec 28 05:56:29 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 28 Dec 2008 02:56:29 -0800 Subject: assignment with [:] In-Reply-To: References: Message-ID: James Stroud wrote: > py> a = [1, 2, 3] > py> a1 = a > py> a1[:] = [x*3 for x in a1] > py> a1 > [3, 6, 9] > py> a1 > [3, 6, 9] This should have been: py> a = [1, 2, 3] py> a1 = a py> a1[:] = [x*3 for x in a1] py> a [3, 6, 9] py> a1 [3, 6, 9] James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From sturlamolden at yahoo.no Fri Dec 12 07:56:53 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 04:56:53 -0800 (PST) Subject: var or inout parm? References: Message-ID: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> On Dec 12, 1:44 pm, "Chris Rebert" wrote: > Python begs to differ, as those two statements are both semantically > identical in this case: That is because integers are immutable. When x += 1 is done on an int, there will be a rebinding. But try the same on say, a numpy array, and the result will be different: >>> import numpy >>> x = numpy.zeros(10) >>> id(x) 19504848 >>> x += 1 >>> id(x) 19504848 >>> x = x + 1 >>> id(x) 10451488 Whereas: >>> x = 1 >>> id(x) 10051256 >>> x += 1 >>> id(x) 10051244 >>> x = x + 1 >>> id(x) 10051232 From gh at ghaering.de Tue Dec 30 16:02:08 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 30 Dec 2008 22:02:08 +0100 Subject: SQL, lite lite lite In-Reply-To: <4959204f$0$15020$426a74cc@news.free.fr> References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> <4959204f$0$15020$426a74cc@news.free.fr> Message-ID: <6rvgihF3je6sU1@mid.uni-berlin.de> Bruno Desthuilliers wrote: > Aaron Brady a ?crit : >> Hi all, >> > (snip) > > >> I don't think relational data can be read and written very easily in >> Python. > > Did you try SQLAlchemy or Django's ORM ? > [...] Using an ORM when you don't grasp the relational model and/or the SQL query language is futile. That's probably the case for many other abstraction layers, too. -- Gerhard From clp at rebertia.com Wed Dec 24 02:53:38 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 23 Dec 2008 23:53:38 -0800 Subject: Strategy for determing difference between 2 very large dictionaries In-Reply-To: References: <1230102996.2303.1291616055@webmail.messagingengine.com> Message-ID: <47c890dc0812232353v743bb58cn50849991866c602c@mail.gmail.com> On Tue, Dec 23, 2008 at 11:46 PM, Gabriel Genellina wrote: > > Yes; but isn't a dict comprehension more adequate? > > [key: (dict1[key], dict2[key]) for key in common_keys if > dict1[key]!=dict2[key]} That initial [ should be a { of course. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From duncan.booth at invalid.invalid Fri Dec 5 09:22:30 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 Dec 2008 14:22:30 GMT Subject: generating a liste of characters References: Message-ID: "Mark Tolonen" wrote: > wrote in message > news:df7b75eb-97bf-4538-880b-f65b5ed992ff at u14g2000yqg.googlegroups.com. > .. >>In Python ranges are open on the right, so I name cinterval such >>function. > > Yes, and that's fine when dealing with integers and slicing, but when > dealing with characters, it is non-obvious what character to use. > What "looks" correct? > > chars = crange('0','9') + crange('A','Z') + crange('a','z') # > inclusive > I think bearophile's point was that you had the parameters correct, (specifying 'a' and 'z' makes sense), but the function itself had the wrong name. If you call it 'crange' you are implying the wrong behaviour. Call it something like 'cinterval' instead. -- Duncan Booth http://kupuguy.blogspot.com From nospam at nospam.com Fri Dec 26 09:24:10 2008 From: nospam at nospam.com (Gilles Ganault) Date: Fri, 26 Dec 2008 15:24:10 +0100 Subject: [2.5.1] Str.Replace() doesn't work? References: Message-ID: On Fri, 26 Dec 2008 15:16:49 +0100, Gilles Ganault wrote: >I can't figure out why the script is not returning anything in the >"for m in matches" block: Pfff, found it 5mn after posting ;-) s/reponse =/response =/ Sorry guys. From castironpi at gmail.com Sun Dec 21 11:41:35 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 21 Dec 2008 08:41:35 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: On Dec 21, 10:31?am, MRAB wrote: > Aaron Brady wrote: > > On Dec 20, 8:49 pm, MRAB wrote: > >> Aaron Brady wrote: > >>> On Dec 20, 7:38 pm, Steven D'Aprano >>> cybersource.com.au> wrote: > >>>> Instead of just whinging, how about making a suggestion to fix it? Go on, > >>>> sit down for an hour or ten and try to work out how a BINARY OPERATOR > >>>> like % (that means it can only take TWO arguments) can deal with an > >>>> arbitrary number of arguments, *without* having any special cases. > >>>> Go on. Take your time. I'll be waiting. > >>> Hi, not to take sides, but, there is a possibility. > >>> This behavior is currently legal: > >>>>>> "%i %%i" % 0 % 1 > >>> '0 1' > >>> So, just extend it. ?(Unproduced.) > >>>>>> "%i %i" % 0 % 1 > >>> '0 1' > >>>>>> "%r %i" % (2, 3, 4) % 1 > >>> '(2, 3, 4) 1' > >>>>>> "%r %i" % (2, 3, 4) > >>> '(2, 3, 4) %i' > >>> Which is quite clever and way ahead of its (posessive) time. > >> A couple of problems: > > >> 1. How do you handle a literal '%'? If you just double up then you'll > >> need to fix the string after all your substitutions. > > >> 2. What if a substitution introduces a '%'? > > >> I suppose a possible solution would be to introduce a special format > >> string, including a literal, eg: > > >> ? ? ?f"%r %i" % (2, 3, 4) % 1 > > >> and then convert the result to a true string: > > >> ? ? ?print(str(f"%r %i" % (2, 3, 4) % 1)) > > >> (although print() would call __str__ anyway). > > >> The format string would track where the last substitution occurred. > > >> Hmm... I think I'll just learn the new method. :-) > > > Now that I'm fighting 'r's war for him/her... > > > Um, here's one possibility. ?On the first interpolation, flags are > > noted and stored apart from subsequent interpolations. ?Then, use a > > sentinel to terminate the interpolation. ?(Unproduced.) > > >>>> "%r %i" % ( 2, 3 ) % 0 > > '(2, 3) 0' > >>>> "%% %r" % ( 2, 3 ) % str.interp_end > > '% (2, 3)' > >>>> "%sss%i" % "%d" % 0 > > '%dss0' > > > The first %s is replaced with %d, but doesn't hijack the '0'. ?If you > > want to interpolate the %d, use the sentinel. ?The sentinel is what > > causes '%%' to be handled. > > >>>> "%sss%i" % "%d" % 0 % 1 > > Traceback (most recent call last): > > ? File "", line 1, in > > TypeError: not all arguments converted during string formatting > >>>> "%sss%i" % "%d" % 0 % str.interp_end % 1 > > '1ss0' > > > Treating tuples as a special case appears to be the simpler solution, > > but this, 'chaining', to adopt the term, is still feasible. > > A possible solution occurred to me shortly after I posted, but I decided > that sleep was more important. :-) > > The original format is a string. The result of '%' is a string if > there's only 1 placeholder to fill, or a (partial) format object (class > "Format"?) if there's more than one. Similarly, the format object > supports '%'. The result of '%' is a string if there's only 1 > placeholder to fill, or a new (partial) format object if there's more > than one. > > ?>>> f = "%r %i" > ?>>> type(f) > > ?>>> f = f % (2, 3, 4) > ?>>> type(f) > > ?>>> f = f % 1 > ?>>> type(f) > Alright, so how are you handling: >>> f= "%s %i" >>> type( f ) >>> f= f% '%i' #now '%i %i' >>> type( f ) >>> f= f% 1 >>> type( f ) ? In other words, are you slipping '1' in to the very first available slot, or the next, after the location of the prior? From stef.mientki at gmail.com Sun Dec 7 04:27:29 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 07 Dec 2008 10:27:29 +0100 Subject: how to get a beep, OS independent ? In-Reply-To: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> Message-ID: <493B9701.2040402@gmail.com> Rainy wrote: > On Dec 6, 3:40 pm, Stef Mientki wrote: > >> hello, >> >> I want to give a small beep, >> for windows there's message-beep, >> and there seems to be something like " curses" , >> but that package seems to be totally broken in P2.5 for windows. >> >> Any other suggestions ? >> >> thanks, >> Stef Mientki >> > > For win there's winsound, you have to check sys.platform and do > what's necessary for the platform in question. In linux I think > you can just print '\a' (or does that only work in terminals?). > If you know that ext. speakers are always on, you can do a nicer > beep by using some wav file, in linux it's probably easiest to > use an external program to play it, like wavplay. Basically, > there is no single answer, it depends on circumstances. > -- > http://mail.python.org/mailman/listinfo/python-list > '\a' or chr(7) prints an inverted "BEL". So it looks that Python version independency is even worse than OS independency ;-) I'll take a look at wxPython and Pygame if there's something useful. anyway thanks, Stef From lewis.sarah93 at yahoo.com Fri Dec 5 00:04:21 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 21:04:21 -0800 (PST) Subject: Reduce Debt Message-ID: Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From mail at microcorp.co.za Thu Dec 4 13:19:05 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 4 Dec 2008 20:19:05 +0200 Subject: Multiple equates References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> Message-ID: <001801c95648$5b6d65e0$0d00a8c0@hendrik> "Cameron Laird" wrote: > There's a realm within Pythonia that favors lambdalessness. And who, may I ask, Is the King of this realm? - Hendrik From dickinsm at gmail.com Sun Dec 28 11:24:02 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 28 Dec 2008 08:24:02 -0800 (PST) Subject: math module for Decimals References: <41937dc9-4b67-43b5-9eab-6f8c851474cf@p2g2000prn.googlegroups.com> Message-ID: <0896c2d8-78ff-489e-801d-abef957601d0@s9g2000prg.googlegroups.com> On Dec 28, 3:55?pm, jerry.carl... at gmail.com wrote: > But i am after the extra precision: > > >>> from math import * > >>> (1+1e-16)-1 > > 0.0 Sounds like you don't care too much about the base-10 part, so there may be other solutions out there. Have you tried: 1. mpmath? 2. sympy? 3. Sage? Any of these is likely to be faster than a decimal solution. One thing that it would be *really* nice to have is a set of Python bindings to MPFR---to me, MPFR is the one obvious way to do high-precision math. Maybe bindings already exist somewhere. Sage includes them, but also includes many hundreds of megabytes of other stuff that you probably don't need or want. Maybe you could get access to MPFR via ctypes; I don't have any idea how feasible or complicated this might be. > Sure, you can say, there is such a small market for this application, > and maybe I should use other tools. Well, I found Python so much > easier to use for other reasons. And, again, it seems like there is a > desire for it outside of my own office. Well, I'd certainly find high-precision sin, cos, ... within Python useful. I'd guess the market isn't *so* small. > Agree: sin, cos and atan would do it. I'll see if I can find time. I've just discovered a half-finished version of atan for Decimal sitting on my computer, complete with error analysis. > Wow, i would never think my posting would go that high in the Python > world. I can't wait to tell my colleagues after these holidays ;-) LOL---hardly! I'm just one of hundreds of Python core devs, and I've only been that for around a year... > If I improve (in my view that is) the existing modules (dmath) etc. i > will keep you posted. For now I am reducing large arguments of > goniometric functions by adding the following into the dmath's sin(x) > and cos(x): > > x=Decimal.__mod__(x,Decimal('2')*pi()) > > Works fine for what i need, but i am sure it's not the right way to do > it. I don't know of any better way to deal with large arguments. The main problem is that the reduction step can introduce fairly large errors: for example, if you're using a value of pi that's accurate to 10**-20, say, then reducing something of magnitude 10**5*pi will give a result with error of around 10**-15. As far as I know, this problem is essentially unavoidable, and it's the reason why implementing sin for inputs like 10**999999999 isn't feasible. Mark From doron.tal.list at gmail.com Sun Dec 14 06:15:31 2008 From: doron.tal.list at gmail.com (Doron Tal) Date: Sun, 14 Dec 2008 13:15:31 +0200 Subject: Swig for Python 2.6 Message-ID: <2a8674c60812140315t78a474a4x2c9250f593f72a47@mail.gmail.com> Hi I'm trying to wrap a c library for use with Python 2.6. I'm using swig 1.3.36, and I get the following error: linux-python/log_wrap.c: In function '_PySwigObject_type': linux-python/log_wrap.c:1680: warning: missing initializer linux-python/log_wrap.c:1680: warning: (near initialization for 'tmp.tp_version_tag') linux-python/log_wrap.c: In function '_PySwigPacked_type': linux-python/log_wrap.c:1843: warning: missing initializer linux-python/log_wrap.c:1843: warning: (near initialization for 'tmp.tp_version_tag') linux-python/log_wrap.c: In function 'swig_varlink_type': linux-python/log_wrap.c:3334: warning: missing initializer linux-python/log_wrap.c:3334: warning: (near initialization for 'tmp.tp_version_tag') What swig version should I use? If version 1.3.36 is good enough, then what can be my mistake? Thanks, doron -------------- next part -------------- An HTML attachment was scrubbed... URL: From jobs.teaching.english.asia at gmail.com Sun Dec 7 21:28:01 2008 From: jobs.teaching.english.asia at gmail.com (Jobs Teaching English in Asia) Date: Sun, 7 Dec 2008 18:28:01 -0800 (PST) Subject: Cambodia TEFL - Gap Year, Travel & Study, Paid Teaching Job - http://www.cambodiatefl.com Message-ID: Cambodia TEFL - Gap Year, Travel & Study, Paid Teaching Job http://www.cambodiatefl.com From nemokingdom at gmail.com Fri Dec 26 20:29:37 2008 From: nemokingdom at gmail.com (nemo) Date: Fri, 26 Dec 2008 17:29:37 -0800 (PST) Subject: Process with ftplib References: Message-ID: <7e172a64-9bda-44c3-90fb-4c716c1f38b4@l33g2000pri.googlegroups.com> On Dec 26, 10:40?pm, "Gabriel Genellina" wrote: > En Fri, 26 Dec 2008 11:07:30 -0200, nemo escribi?: > > > There seems something wrong when I use multiprocessing.Process with > > ftplib, [...] > > It works well but when I using the Process module, something seems > > wrong: > > ftp = qftp(host, port, user, password) > > p = multiprocessing.Process(target = ftp.connect) > > p.join() > > ftp.ftp.pwd() ? ? ? ? ? ? ? ? ? #after join, i think a connection has > > made, but it throws an exception > > This give me a 'NoneType object has no attribute sendall' exception. I > > wondered why? > > After p.join(), the second process has finished. The global variable ftp ? > isn't shared between them - so it does not reflect the changes made in the ? > other process. > > An introductory article to multiprocessing:http://www.doughellmann.com/articles/CompletelyDifferent-2007-10-mult... > > -- > Gabriel Genellina thanks. -- nemo From robert.kern at gmail.com Sun Dec 28 16:57:51 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 28 Dec 2008 16:57:51 -0500 Subject: "return" in def In-Reply-To: <088c7d93-e87f-44a0-9ea7-faa7feded7df@a26g2000prf.googlegroups.com> References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <0167cbf7$0$6988$c3e8da3@news.astraweb.com> <088c7d93-e87f-44a0-9ea7-faa7feded7df@a26g2000prf.googlegroups.com> Message-ID: Benjamin wrote: > On Dec 28, 1:35 pm, Steven D'Aprano cybersource.com.au> wrote: >> The second thing I think is that maybe the function is a generator, and >> so I look for a yield. > > You shouldn't, though; Generators can't contain any return statement. Yes, they can. It doesn't return a value, it just raises a StopIteration error. In [18]: def g(): for i in range(5): if i == 3: print 'Early exit.' return print 'Should not happen.' yield i ....: ....: In [25]: list(g()) Early exit. Out[25]: [0, 1, 2] -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From mnations at gmail.com Sat Dec 13 21:45:43 2008 From: mnations at gmail.com (Mudcat) Date: Sat, 13 Dec 2008 18:45:43 -0800 (PST) Subject: PyQt: Pulling Abstract Item Data from Mime Data using Drag and Drop. References: <150086b2-b02d-4204-8c06-b08c0aa119c4@k1g2000prb.googlegroups.com> Message-ID: <9c332bde-351d-4499-b33e-dac1a00ac434@g38g2000yqd.googlegroups.com> On Dec 12, 6:17?pm, David Boddie wrote: > That's correct, retrieveData() is a protected function in C++ and the > QMimeData object was created by the framework, not you, in this case. Ah, well that explains it. Figured as much but was hoping maybe I was trying to access it incorrectly. > You could use the data() method to get the serialized data then try to > extract the list item-by-item using the QDataStream class, or perhaps > PyQt has a convenience function to unpack the items. I tried to get info back using data() but kept getting null values. Same goes for the items() function which is fed with mimeData and is supposed to return a list. From the documentation it appeared that was supposed to be the middle-man to re-convert the data. I know the data existed because I could drag/drop elements from one treeWidget to another but still couldn't get data back from the target widget. > Alternatively - and this is a bit speculative - perhaps you can copy > the data to another QMimeData object which you have created, and use > its retrieveData() method to retrieve the items. I started down the path of creating my own MimeType but then realized it was quicker to just override the drop() function and grab the selected items from the source widget, just letting the mime data disappear into the ether. A little klugey but deadline is fast approaching. However I'll give the pyqt mailing list a shot. I didn't know there was one just for pyqt. Thanks for all the help, Marc From peke at iki.fi Mon Dec 15 17:58:07 2008 From: peke at iki.fi (=?ISO-8859-1?Q?Pekka_Kl=E4rck?=) Date: Tue, 16 Dec 2008 00:58:07 +0200 Subject: Problem Python 2.6.1 vs 2.6 & pyWin32 In-Reply-To: <4946D09F.6050300@v.loewis.de> References: <4946754f$0$19000$426a74cc@news.free.fr> <4946D09F.6050300@v.loewis.de> Message-ID: <7dedbb6d0812151458o29607864x74ea3f43fb49c880@mail.gmail.com> 2008/12/15 "Martin v. L?wis" : >> I am very disappointed. Help me, please. > > Try installing Python 2.6.1 "for all users". Could you clarify why that's needed? Link to a relevant bug report or something similar is enough. We've got some weird problems installing Python packages (win32.exe) on Windows with Python 2.6 and would like to know are these problems related. One thing we noticed (I'm not sure has this been yet submitted to bugs.python.org yet) was that installing packages created with Python 2.5 to Python 2.6 failed unless Python was in %PATH% [1]. Even then output printed by postinstall scripts wasn't visible in the installer. Another pretty severe problem was that installers created with Python 2.6 didn't work at all with older versions [2]. [1] http://code.google.com/p/robotframework/issues/detail?id=150 [2] http://code.google.com/p/robotframework/issues/detail?id=163 Cheers, .peke From mailmaverick666 at gmail.com Fri Dec 5 01:27:22 2008 From: mailmaverick666 at gmail.com (rishi pathak) Date: Fri, 5 Dec 2008 11:57:22 +0530 Subject: CONNECTION TIMED OUT ERROR using urllib2 In-Reply-To: <726d283d0812042217w41a0288eg3ee79d4ffdb5ff4b@mail.gmail.com> References: <726d283d0812042217w41a0288eg3ee79d4ffdb5ff4b@mail.gmail.com> Message-ID: <180b672e0812042227j12a4d647k84e507dfae77d665@mail.gmail.com> Are you sitting behind a proxy. If so then you have to set proxy for http On Fri, Dec 5, 2008 at 11:47 AM, svalbard colaco wrote: > Hi all > > I have written a small code snippet to open a URL using urllib2 to open a > web page , my python version is 2.4 but i get an urlopen error called > connection timed out > > The following is the code snippet > > *import urllib2 > > f = urllib2.urlopen('http://www.google.com/') > print f.read(100)* > > > where as the same url http://www.google.com/ works through my browser. > > The following is the back trace : > > File "test_url.py", line 3, in ? > f = urllib2.urlopen('http://www.google.com/') > File "/usr/lib/python2.4/urllib2.py", line 130, in urlopen > return _opener.open(url, data) > File "/usr/lib/python2.4/urllib2.py", line 358, in open > response = self._open(req, data) > File "/usr/lib/python2.4/urllib2.py", line 376, in _open > '_open', req) > File "/usr/lib/python2.4/urllib2.py", line 337, in _call_chain > result = func(*args) > File "/usr/lib/python2.4/urllib2.py", line 1021, in http_open > return self.do_open(httplib.HTTPConnection, req) > File "/usr/lib/python2.4/urllib2.py", line 996, in do_open > raise URLError(err) > *urllib2.URLError: > > > Any pointers in this regard will be of great help. > > Thanking you'll in advance. > > Regards, > sv > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Regards-- Rishi Pathak Pune-Maharastra -------------- next part -------------- An HTML attachment was scrubbed... URL: From fetchinson at googlemail.com Tue Dec 9 02:51:00 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 8 Dec 2008 23:51:00 -0800 Subject: html codes Message-ID: Hi folks, I came across a javascript library that returns all sorts of html codes in the cookies it sets and I need my web framework (written in python :)) to decode them. I'm aware of htmlentitydefs but htmlentitydefs.entitydefs.keys( ) are of the form '&#xxx' but this javascript library uses stuff like '%3A' for the ':' for example. The conversion is here: http://www.ascii.cl/htmlcodes.htm Is there a python package/module/whatever that does the conversion for me or do I have to write a little wrapper myself (and introduce bugs while doing so :))? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From cjwilliams43 at gmail.com Thu Dec 4 08:29:47 2008 From: cjwilliams43 at gmail.com (Colin J. Williams) Date: Thu, 04 Dec 2008 08:29:47 -0500 Subject: Multiple Versions of Python on Windows XP In-Reply-To: <49378804.2050807@g.nevcal.com> References: <4934de22$0$27863$9b622d9e@news.freenet.de> <493592EE.9090005@v.loewis.de> <49378804.2050807@g.nevcal.com> Message-ID: <4937DB4B.7060001@ncf.ca> Glenn Linderman wrote: > > The equivalent of those commands is available via Windows Explorer, > Tools / Folder Options, File Types, scroll-scroll-scroll your way to > .py, Click Advanced, fiddle, copy paste apply, and other twaddle. Yes, but what's needed is a further level of indirection. Currently, this allows .py to be associated with a particular editor. It would be great if there were some way of associating "Python.File", which is created in the install process, with a particular editor. Then, one is left with associating "Python.File" with a given version of Python. Meanwhile, your suggestion provides a workaround. Colin W. > A perfect example of why not everything should be done via GUI > interfaces, or at least why this is an extremely poor GUI interface. > > GUI designers should count the command line keystrokes, and make sure > their interface is shorter, otherwise they are a failure. > >> Michel Claveau suggests VirtualBox, this >> seems a big hammer to kill >> this particular fly. >> >> It's interesting that each install sets >> up a Python.File variable in the registry. >> >> It's a pity that this can't be used to achieve this more simply. > > Martin seems willing to entertain the idea of future Windows > installers doing something more brilliant in this area, for those that > wish to switch between multiple installed versions, as he asked for a > tracking issue to be created, which I did. > > Whether it will be exactly my technique, or something further > improved, time will tell. But that will only apply to versions > released after 3.0 and 2.6.1 (unless he has already coded it into the > release, but I doubt he had time, or wishes to destabilize or delay > these releases). > > Anyway, if you remember the arcane techniques for copy/paste in CMD > prompt windows (Alt-space or click the "system" icon in the upper left > of the CMD prompt window), and go from there, then setting up the > multiple ftypes becomes a bit easier, perhaps. > >> Best wishes, >> >> Colin W. > > > From sjmachin at lexicon.net Wed Dec 17 10:54:26 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 17 Dec 2008 07:54:26 -0800 (PST) Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> Message-ID: <2c7dce74-3531-4eb0-923f-0e0ed72fd79a@r10g2000prf.googlegroups.com> On Dec 18, 2:19?am, walterbyrd wrote: > For a language as well structured as Python, this seems somewhat > sloppy, and inconsistant. ?Or is there some good reason for this? > > Here is what I mean: > > def a(): > ? ? x = 99 > ? ? print x > > def b(): > ? ? print x > > a() > b() # raises an exception because x is not defined. > > However in the methods are within a class, the scoping seems to work > differently. > > class ab(): > ? ? def a(self): > ? ? ? ? self.x = 99 > ? ? ? ? print self.x > ? ? def b(self): > ? ? ? ? print self.x > > i = ab() > i.a() > i.b() # this works, why no lexical scoping? Two questions for you: (1) If you were to change the sloppy inconsistent scoping mechanism in classes, what would you change it to? (2) What do you think of the following: class ab(): def a(self): self.x = 99 print self.x def b(me): print me.x ? From clp at rebertia.com Fri Dec 26 01:17:40 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 25 Dec 2008 22:17:40 -0800 Subject: socket send help In-Reply-To: <8a5a2b07-3274-483a-be06-51eab226315a@d36g2000prf.googlegroups.com> References: <8a5a2b07-3274-483a-be06-51eab226315a@d36g2000prf.googlegroups.com> Message-ID: <47c890dc0812252217q323d63dcp54cd70db1c023005@mail.gmail.com> On Thu, Dec 25, 2008 at 10:08 PM, greywine at gmail.com wrote: > Hi again, > > I've done some more playing around with socket and socketserver and > have discovered I can send strings or lists with socket.send() by > converting to bytes. But lists with strings in them or dicts can't be > converted by bytes(). How can I send those? If you're sending structured data rather than just bytestrings, you should use proper serialization. Use the `json`, `pickle`, or `marshal` modules to convert your data to an external representation in bytes, send the bytes thru the socket, then deserialize the bytes back into data structures using the same module again. The Python std lib docs are your friend. Merry Christmas, Chris -- Follow the path of the Iguana... http://rebertia.com From ndbecker2 at gmail.com Thu Dec 18 10:49:27 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 18 Dec 2008 10:49:27 -0500 Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> <6qv7kfFeuf65U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Neal Becker wrote: > >> Tino Wildenhain wrote: >> >>> Neal Becker wrote: >>> ... >>>>>> So if __str__ is "meant for human eyes", then why isn't print using >>>>>> it! >>>>> it is: >>>>> >>>>> > print x >>>>> str >>>>> >>>>> but dict just uses repr() for all its childs to print. >>>>> >>>>> T. >>>> That makes no sense to me. If I call 'print' on a container, why >>>> wouldn't it recursively print on the contained objects? Since print >>>> means call str, printing a container should recursively call str on the >>>> objects. >>> >>> Every class is free on how to best implement __str__, you will find >>> the same behavior on tuple and list as well. >>> >>> Maybe its discussable to change the implementation sensibly, best if you >>> would come with a proposal? Perhaps pprint.pprint is a starting point? >>> >>> Regards >>> Tino >> >> First, I'd like to know if there is a rationale for the current design. >> Am I correct in thinking this is a defect? > > I don't think so. First of all, there is no "generic" way of printing a > collection. And the current implementation tries to give an overview what > is contained in the collection, without trying to make it "fancy" - any > such thing needed to be hand-coded anyway. > > Using repr for that is better suited, as for example string keys are > printed with quotes around them - making clear what they are, and not > irritating the user through potentially contained spaces or even things > that look as if they are python objects. > > For example, if repr *wasn't* used, > > { "{foo=bar}" : "baz"} > > would be printed > > {{foo=bar} : baz} > > Which is *not* what the dictionary actually contains! > > The same goes for unicode-objects. They appear with their "funny" > characters as \xXX-codes - instead of bailing out on you with > unicode-errors. > > So, IMHO the current behavior is desired. > So if I want to overload something in my custom class, so that I get a nice string whether it's printed directly, or as part of a container, what is the recommendation? Overload both __str__ and __repr__? From ethan at stoneleaf.us Thu Dec 11 12:33:14 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 11 Dec 2008 09:33:14 -0800 Subject: internal circular class references In-Reply-To: References: Message-ID: <49414EDA.2050509@stoneleaf.us> Carl Banks wrote: > On Dec 10, 5:26 pm, Ethan Furman wrote: > >>Greetings List! >> >>I'm writing a wrapper to the datetime.date module to support having no >>date. Its intended use is to hold a date value from a dbf file, which >>can be empty. >> >>The class is functional at this point, but there is one thing I would >>like to change -- datetime.date.max and datetime.date.min are class >>attributes of datetime.date, and hold datetime.date values. At this >>point I have to have two lines outside the actual class definition to do >>the same thing, e.g.: >> >> >> class NullDate(object): >> "adds null capable DateTime.Date constructs" >> __slots__ = ['_date'] >> def __new__(cls, date='', month=0, day=0): >> nulldate = object.__new__(cls) >> nulldate._date = "" >> . >> . >> . >> return nulldate >> NullDate.max = NullDate(dt.date.max) >> NullDate.min = NullDate(dt.date.min) >> >> >>How can I move those last two lines into the class definition so that: >> 1) they are class attributes (not instance), and >> 2) they are NullDate type objects? > > > > It can't be done by any straightforward method I know of. I advise > you not to worry about it, and just define them afterwards, perhaps > with an apologetic comment saying you would have put them inside the > class definition if you could have. > > > If the out-of-scope issue bothers you that much, you could use some > metaclass hackery to run a method that defines the class attributes > after the class is created, at the unrecommendable cost of confusing > most readers. Here is a very simple example: > > def make_class_and_run_postcreate(name,bases,clsdict): > cls = type.__new__(type,name,bases,clsdict) > cls.__postcreate__() > return cls > > class A(object): > __metaclass__ = make_class_and_run_postcreate > @classmethod > def __postcreate__(cls): > cls.internal_circular_class_ref = cls() Well, since "Practicality beats purity" ;) , I'll stick with having the two assignment statements just outside the class. Not to mention my metaclass skills are nonexistent at this point. > BTW, if you don't mind some criticism of your code, the code you > posted seems to be much too complex for the job you're describing. Critiques always welcome. > First of all, do you even need to wrap the datetime.date class? With > Python's duck typing ability, you could have a separate NullDate class > to go alongside the datetime.date, and use a regular datetime.date > object when the date is present, and NullDate when it's absent. If > necessary you can subclass datetime.date to add any new methods it > would have to have. Use a factory function to return either NullDate > or a datetime.date depending on whether the dbf cell is empty. > > class ValidDate(datetime.date): > def is_valid(self): > return True > > class NullDate(object): > # implement any necessary methods of datetime.date interface here > def is_valid(self): > return False > > def create_date_from_dbf_cell(dbf_cell): > if dbf_cell.empty(): > return NullDate() > return ValidDate(dbf_cell.value) > > > If you do this, you don't have to muck around with __getattr__ or > __new__ or snooping to datetime.date's class dict anything like that. > > > Carl Banks Good question. My goal with NullDate is to have a date object that I can treat the same regardless of whether or not it actually holds a date. NullDates with no value should sort before any NullDates with a value, should be comparable to dates as well as NullDates, and should support all the same methods. In other words, I don't want to have to worry about whether my date object has an actual date under most circumstances (printing, using as dictionary keys, comparing, etc.). Does my design make more sense given these expanded requirements, or could it still be done simpler? For that matter, do my requirements make sense? ~Ethan~ From gagsl-py2 at yahoo.com.ar Wed Dec 24 12:24:59 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2008 15:24:59 -0200 Subject: Custom C Exception Subclasses References: <41f291ff-d7bd-4334-8689-636e95524cdc@b38g2000prf.googlegroups.com> Message-ID: En Wed, 24 Dec 2008 13:42:38 -0200, Ross escribi?: > For a project that I am doing, it would be useful to have an exception > class that stores some additional data along with the message. > However, I want to be able to store a couple pointers to C++ classes, > so I can't just use an exception created with PyExc_NewException. In fact you can, you could store those pointers as attributes of the exception object, using a PyCObject. Accessing those attributes isn't as easy as doing exc->field, but I think it's easy enough. Inheriting from some exception type requires you to define the type structure and fill it right, and IMHO is a lot harder. > If > I were to subclass the built-in Exception type, I would need to have > access to the PyExc_ExceptionObject, but the headers only give > PyExc_Exception, the type object. This seems like a rather > straightforward task, but I can't seem to find any documentation for > it. Does anyone know how to do this? Thanks! Perhaps there is a misunderstanding here. To subclass a type, you need the type, not an instance of such type. The "Exception" class you use in Python code is "PyExc_Exception" in C code. Usually one would inherit a subclass, RuntimeError by example, so use PyExc_RuntimeError as the base type. -- Gabriel Genellina From tkpapp at gmail.com Tue Dec 2 17:04:44 2008 From: tkpapp at gmail.com (Tamas K Papp) Date: 2 Dec 2008 22:04:44 GMT Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <591e8625-7e4d-4db8-ae6c-73c4370f8088@q26g2000prq.googlegroups.com> Message-ID: <6plpnsF8pi3oU1@mid.individual.net> On Tue, 02 Dec 2008 13:57:35 -0800, Lew wrote: > Xah Lee wrote: >> If [yo]u would like to learn [the] [E]nglish lang[uage] and writing >> insights from me, peruse: > > /Au contraire/, I was suggesting a higher standard for your posts. Hi Lew, It is no use. Xah has been posting irrelevant rants in broken English here for ages. No one knows why, but mental institutions must be really classy these days if the inmates have internet access. Just filter him out with your newsreader. Best, Tamas From steve at REMOVE-THIS-cybersource.com.au Sun Dec 14 22:21:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Dec 2008 03:21:21 GMT Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> <0152e35f$0$8244$c3e8da3@news.astraweb.com> Message-ID: <0155c4a7$0$6988$c3e8da3@news.astraweb.com> On Mon, 15 Dec 2008 02:11:10 +0000, Lie Ryan wrote: >> So given the normal precedence rules of Python, there is no ambiguity. >> True, you have to learn the rules, but that's no hardship. > > *I* know about the precedence rule, but a newbie or a tired programmer > might not. He might want to reverse the truth value of argument b but > instead has just reversed the whole expression. And? A newbie or a tired programmer might not know that a^b is bit-wise xor instead of exponentiation, or that range(n) doesn't include n, or even that len(alist) returns the length of a list. There's no limit to the potential mistakes that are possible for a programmer who is tired, inexperienced, intoxicated or just plain stupid enough. What's your point? Are you expecting Python to be mistake-proof? There's a certain level of knowledge about the language necessary to program effectively, and learning that "is not" is a single operator is not particularly onerous. -- Steven From David Wed Dec 31 11:10:21 2008 From: David (David) Date: Wed, 31 Dec 2008 10:10:21 -0600 Subject: How to initialize an array with a large number of members ? Message-ID: <5m4nl4hs8f9q6rfcp7b1jt7nk1o6sq6r0f@4ax.com> Thanks to those who have helped a beginner in Python. Using version 3.0 # script23 from array import array < see failed initialization attempts below > tally = array('H',for i in range(75) : [0]) tally = array('H',[for i in range(75) : 0]) tally = array('H',range(75) : [0]) tally = array('H',range(75) [0]) Above give either Syntax error or TypeError All examples of sequences in docs show only a few members being initialized. Array doc says an iterator can be used, but doen't show how. What would you do for a 2 dimensional array ? Incorporate c code ? The online docs are clearly insufficient for a novice. Have ordered Summerfields new book. From marduk at letterboxes.org Tue Dec 9 13:11:40 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Tue, 09 Dec 2008 13:11:40 -0500 Subject: Can't figure out where SyntaxError: can not delete variable 'x' referenced in nested scope us coming from in python >=2.6 Message-ID: <1228846300.4109.30.camel@brotherus.rdu.redhat.com> Say I have module foo.py: def a(x): def b(): x del x If I run foo.py under Python 2.4.4 I get: File "foo.py", line 4 del x SyntaxError: can not delete variable 'x' referenced in nested scope Under Python 2.6 and Python 3.0 I get: SyntaxError: can not delete variable 'x' referenced in nested scope The difference is under Python 2.4 I get a traceback with the lineno and offending line, but I do not get a traceback in Pythons 2.6 and 3.0. The reason why I ask is... I have a python package, 'foo', with __init__.py and a whole bunch of other modules. It runs fine on Python 2.4 as well as 2.6, but when I run 2to3 on my foo directory and try to 'import foo' in Python 3 I get no traceback, I can't 'import foo' in Python 2 because 'foo' is no longer Python2-compatible, but my original Python2 version of foo imports just fine. So is there a way to find the offending code w/o having to go through every line of code in 'foo' by hand? I've tried using pdb but it just breaks out of the debugger. thanks, -a From castironpi at gmail.com Mon Dec 8 15:15:59 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 8 Dec 2008 12:15:59 -0800 (PST) Subject: A question about reference in Python. References: <493CB003.3080209@gmail.com> Message-ID: <716e9093-7976-43e5-a37a-0773a24b8389@j39g2000yqn.googlegroups.com> On Dec 8, 9:18?am, Joe Strout wrote: > On Dec 7, 2008, at 10:26 PM, Group wrote: > > > Now, I want to write a Red-Black Tree, and a List structure. In C/C+ > > +, I can > > use pointers to refer to ?children ?notes (or next notes). But, in ? > > Python, how > > can I do it? Except the sequence, I know not any way. > > Any variable in Python is a reference, which is roughly analogous to a ? > pointer type in C/C++. ?For details and examples, see: ? Message-ID: On 2008-12-07, suku wrote: > i need some suggestion on making graphs. Will this be possible > with normal python setup file or do i need to download add ons for > that.. gnuplot-py matplotlib vtk -- Grant From lewis.sarah93 at yahoo.com Thu Dec 4 23:55:07 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 20:55:07 -0800 (PST) Subject: Reduce Debt Message-ID: <9f83499d-0eaf-4a7b-8d4e-b12e4512e0d2@j38g2000yqa.googlegroups.com> Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From andrew at doadesweb.co.uk Wed Dec 10 14:00:47 2008 From: andrew at doadesweb.co.uk (Andrew D) Date: Wed, 10 Dec 2008 11:00:47 -0800 (PST) Subject: get todays files References: Message-ID: <4632c353-0462-485b-9e1b-6a5c56682363@s9g2000prg.googlegroups.com> On Dec 10, 6:55?pm, Tim Chase wrote: > > I have a script that will login to my ftp server and download > > all the backup files, but I want it to only download the files > > that were created today, e.g. if I ran the script today I want > > it to only fetch files created today. > > Use Python's ftp module and send the MDTM command to get back the > timestamp of the filename. ?Insecurely, this would look something > like > > ? ?from ftplib import FTP > ? ?hostname = "ftp.mozilla.org" > ? ?conn = FTP(hostname) > ? ?user = "anonymous" > ? ?password = "u... at example.com" > ? ?conn.login(user, password) > ? ?filename = "pub/README" > ? ?results = conn.sendcmd("MDTM %s" % filename) > ? ?code, stamp = results.split(None, 1) > ? ?assert code == "213", "Unexpected result" > ? ?print "%s was modified on %s" % (filename, stamp) > ? ?today = '20081210' > ? ?if stamp[:8] == today: > ? ? ?process(filename) > ? ?else: > ? ? ?print "ignoring", filename > > The MDTM command is not part of the core RFC-959, but rather the > RFC-3659[1] so you might run across some servers that don't > support it. ?You can read more about the Python ftplib module at > [2] which would be where you want to read up on pulling back a > listing of the directory of file-names to check. ?There is a NLST > command (I don't have a server handy that supports this command). > ? The LIST command returns pretty/readable information that's not > quite so machine-parsing friendly (at least in a cross-FTP-server > sort of way). ?However, that part, I leave as an exercise for the > reader along with the complications of the "today" bit. > > Oh, SteveH, I checked your FTP-cloning source in my Python dir, > and it doesn't look like it does anything regarding file-times in > it, so that may have been a red-herring. ?Unless you've added > something since the ver. I've got here. > > -tkc > > [1]http://en.wikipedia.org/wiki/List_of_FTP_commands > > [2]http://www.python.org/doc/2.5.2/lib/ftp-objects.html This looks very good and I have tested successfully, but is there a way I can set the today to automatically become todays date in that format? Thanks though, this is what I was looking for! Andrew From zaz600 at gmail.com Thu Dec 25 21:34:15 2008 From: zaz600 at gmail.com (NoName) Date: Thu, 25 Dec 2008 18:34:15 -0800 (PST) Subject: SyntaxError: encoding problem: with BOM References: <6res8tF1do1sU1@mid.uni-berlin.de> <400f176b-bd9a-4f26-b01b-1aa7c7dcf5ac@z6g2000pre.googlegroups.com> <6rf6m1F1e0f8U1@mid.uni-berlin.de> <26e21f3f-ded1-48ca-8897-2ebd05dd07ad@w39g2000prb.googlegroups.com> Message-ID: > It's a bug, please report it. I though we fixed all Windows path bugs > for 3.0 but apparently one slipped through. > > Christian It is too difficult for me. please help me=) From boyee118 at gmail.com Wed Dec 17 09:49:17 2008 From: boyee118 at gmail.com (=?UTF-8?B?5Li654ix6ICM55Sf?=) Date: Wed, 17 Dec 2008 22:49:17 +0800 Subject: [Help] The pywinauto Can't select the MDI's menu using the MenuItems() which return []. Message-ID: I can't use the MenuItems() in my MDI application. Any example is very nice!!!! Thanks a lot! -- "OpenBookProject"-?????????? ??: http://groups.google.com/group/OpenBookProject ??: http://wiki.woodpecker.org.cn/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldo at geek-central.gen.new_zealand Sat Dec 6 02:28:17 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 06 Dec 2008 20:28:17 +1300 Subject: Don't you just love writing this sort of thing :) References: <0148b086$0$20670$c3e8da3@news.astraweb.com> <01490b5f$0$20670$c3e8da3@news.astraweb.com> Message-ID: In message <01490b5f$0$20670$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > On Fri, 05 Dec 2008 23:28:48 +1300, Lawrence D'Oliveiro wrote: > >> In message <0148b086$0$20670$c3e8da3 at news.astraweb.com>, Steven D'Aprano >> wrote: >> >>> Since the context has been deleted, it's hard to tell whether the code >>> as written by Lawrence ... >> >> If you want to reply to my message, reply to my message, don't reply to >> my reply to someone else's reply to my message. > > I did reply to your message. It was your message that was missing all the > context necessary to tell what you were rabbiting on about. If you wanted the context for your reply, you should have replied to the message with the context. That way you automatically get the context when you hit reply, no need to go out of your way to dig it up from a different posting. Does that make any sense to you, or should I start drawing simple diagrams? From nad at acm.org Thu Dec 4 18:51:31 2008 From: nad at acm.org (Ned Deily) Date: Thu, 04 Dec 2008 15:51:31 -0800 Subject: pretty strange behavior of "strip" References: <4938693F.6090709@yahoo.ca> Message-ID: In article <4938693F.6090709 at yahoo.ca>, Guy Doune wrote: > Could it be a bug????? > > Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> test=['03.html', '06.html', 'questions.html', '04.html', > 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test > ['03.html', '06.html', 'questions.html', '04.html', 'toc.html', > '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test[4] > 'toc.html' > >>> test[4].strip('.html') > 'oc' > > Can't figure out what is going on, really. >>> help("".strip) >>> help("".endswith) -- Ned Deily, nad at acm.org From gagsl-py2 at yahoo.com.ar Tue Dec 16 18:11:12 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Dec 2008 21:11:12 -0200 Subject: subprocess returncode windows References: <18348eae-5af1-47e9-a198-b95d4fcb6eac@a12g2000pro.googlegroups.com> Message-ID: En Tue, 16 Dec 2008 17:21:35 -0200, Andrew escribi?: > On Dec 16, 12:50?pm, Christian Heimes wrote: >> Andrew schrieb: >> >> > I'm running into a strange situation with getting incorrect >> > returncodes / exit status from python subprocess.call. I'm using a >> > python script (runtime 2.6.1 on windows) to automate the deploy of >> > java applications to glassfish application server. Below is an example > > I've removed shell=True, unfortunately, if I structure the call like: > > call(["c:/glassfish/bin/asadmin.bat", "list-system-properties", "-- > host > mydomain", "--port 4848", "--user admin", "server-01"]) > > It doesn't seem to recognize any arguments after list-system- > properties. Should be: call(["c:/glassfish/bin/asadmin.bat", "list-system-properties", "--host", "mydomain", "--port", "4848", "--user", "admin", "server-01"]) *Every* argument should be an item in the list (your way, "--port 4848" becomes a single argument, not two: option plus value) (This is independent of your other issue) > If I structure it like: > > call("c:/glassfish/bin/asadmin.bat "+"list-system-properties --host > mydomain --port 4848 --user admin server-01") > > Then it executes correctly but still gives invalid returncode of 0 > when it fails instead of 1. A similar example works fine for me: C:\temp>type ret.c #include int main(int argc, char* argv[]) { return atoi(argv[1]); } C:\temp>ret 5 C:\temp>echo %errorlevel% 5 C:\temp>type testret.bat ret %1 C:\temp>testret 3 C:\temp>ret 3 C:\temp>echo %errorlevel% 3 C:\temp>type testret.py from subprocess import call ret = call(["testret.bat", "42"]) print "testret.bat exit code =", ret C:\temp>python testret.py C:\temp>ret 42 testret.bat exit code = 42 C:\temp>python -V Python 2.6 C:\temp>ver Microsoft Windows XP [Versi?n 5.1.2600] -- Gabriel Genellina From steve at holdenweb.com Sat Dec 20 08:25:53 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 20 Dec 2008 08:25:53 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <2dc66762-f51e-4bbd-9372-756610d4201e@j11g2000yqg.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c4ef2$0$20656$c3e8da3@news.astraweb.com> <2d53cd36-52b0-4a1a-913d-0c545cfadc23@v15g2000vbb.googlegroups.com> <2dc66762-f51e-4bbd-9372-756610d4201e@j11g2000yqg.googlegroups.com> Message-ID: <494CF261.2040106@holdenweb.com> r wrote: > On Dec 19, 10:04 pm, Steve Holden wrote: >> r wrote: >>> Thanks Steven, >>> We need a real Pepsi challenge here to show the insignificance of this >>> change. I am not against change. But when we lose something as - >>> compact- as %formating i'm going to want to see a damn good reason for >>> it! Especially when this breaks code, and the "French Connection" is >>> not good enough reason for me :) >>> Christian said this was not going to be depreciated until 3.2, but >>> that still puts the accepted way on the chopping block. >> If Python is so important to you it's a pity you haven't been playing >> any active role in its development. Do you expect the developers to be >> psychic? > > Steve, > I just recently started to have an opinion about these things. "The > squeaky wheel get the grease", just allowing my voice be heard. It > might seem that i am trashing Python dev, but that could not be > further from the truth. > > Many great changes have been made in 3.0, i just feel strongly about C > style formating. Why could't we improve on what we had instead of > making radical changes? Thats all i am asking. I wasn't really a part of the decision-making process, but I anticipate that the developers' reply would be that the new scheme is much more adaptable, both to new data types (which can implement their own __format__ method) and to internationalization (because it's possible to alter word order in the format strings). Thanks for clarifying your approach, by the way, which isn't as unreasonable as it first seemed if you've only recently started using Python. You will find over time that the developers are right about these decisions much more than they are wrong, and you still have a couple of years to get used to it ;-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From fetchinson at googlemail.com Sat Dec 27 17:27:53 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 27 Dec 2008 14:27:53 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: >> I'm trying to write an extension module in C which contains a single >> function with the following prototype: >> void func( int N, int * arg1, int * arg2, int * ret ); >> Here arg1 and arg2 are length N arrays, and the function computes ret >> which is also an N length array. From python I'd like to call this >> function as >> ret = func( [ 1, 2, 3 ], [ 2, 3, 4] ) > > This requirement pretty much dictates the slow answer you have. I'm not sure I understand what you mean. > > Does this mean that I can only pass the arrays from python to C as > > generic python objects and in a later operation I need to get the > > elements from this generic python object, construct a C array and pass > > that to the C function? ... What's the simplest way of doing this? > > Either use ctypes, look into array.array, or look into numpy.array. I have considered using ctypes but for my needs using the C API directly seems more reasonable. array.array and numpy.array doesn't fit my needs since I need to do long and complicated operations on the two (pretty large) integer arrays that would be too slow using array.array and numpy.array (I've verified this claim by benchmarking a numpy.array based solution). > I'd just use numpy, myself: > import numpy > total = numpy.array([1, 2, 3]) + numpy.array([2, 3, 4]) What makes you think I want to add two arrays? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From trentm at activestate.com Sat Dec 13 16:17:28 2008 From: trentm at activestate.com (Trent Mick) Date: Sat, 13 Dec 2008 13:17:28 -0800 Subject: ActivePython 2.6.1.1 and 3.0.0.0 released! In-Reply-To: <58cd9ea1-9cf5-4c90-81ba-411774a878b7@o4g2000pra.googlegroups.com> References: <58cd9ea1-9cf5-4c90-81ba-411774a878b7@o4g2000pra.googlegroups.com> Message-ID: <49442668.1080500@activestate.com> Kay Schluehr wrote: > On 13 Dez., 00:16, Trent Mick wrote: > >> Note that currently PyWin32 is not included in ActivePython 3.0. > > Is there any activity in this direction? The PyWin32 CVS tree is getting checkins from Mark Hammond and Roger Upole with a py3k tag. I'm not sure how close they are currently. Trent -- Trent Mick trentm at activestate.com From bruno.42.desthuilliers at websiteburo.invalid Thu Dec 4 03:20:11 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 04 Dec 2008 09:20:11 +0100 Subject: python an sqlite objects In-Reply-To: References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <4936bceb$0$16783$426a34cc@news.free.fr> <4936dab7$0$9107$426a74cc@news.free.fr> Message-ID: <493792a9$0$16763$426a74cc@news.free.fr> skip at pobox.com a ?crit : > Bruno> Most of the time, you want to serialize the instance's __dict__. > > Does it recreate an instance at the other end or just a dict? If you serialize a dict, you'll obviously get a dict back. Note that the point of json is *not* to replace pickle. json is a *data* serialization format meant to represent "basic" types (dicts, lists, strings and numbers) in human readable and (mostly) language-agnostic way. If you want a Python object store, you'll be better looking at ZODB, Durus or friends. From lists at cheimes.de Wed Dec 24 11:09:17 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 24 Dec 2008 17:09:17 +0100 Subject: Using exceptions in defined in an extension module inside another extension module In-Reply-To: <26443e22-0dd6-4fa9-a58e-8d9314001c6c@o4g2000pra.googlegroups.com> References: <26443e22-0dd6-4fa9-a58e-8d9314001c6c@o4g2000pra.googlegroups.com> Message-ID: Floris Bruynooghe schrieb: > What I can't work out however is how to then be able to raise this > exception in another extension module. Just defining it as "extern" > doesn't work, even if I make sure the first module -that creates the > exception- gets loaded first. Because the symbol is defined in the > first extension module the dynamic linker can't find it as it only > seems to look in the main python executable for symbols used in > dlloaded sofiles. > > Does anyone have an idea of how you can do this? The answer is so obvious that you are going to bang your head against the next wall. You have to do exactly the same as you'd do with a pure Python module: import it. :) static PyObject *yourexc = NULL; PyObject *yourmod = PyImport_ImportModule("yourmod"); if (yourmod == NULL) return NULL; *yourexc = PyObject_GetAttrString(yourmod, "YourException"); if (yourexc == NULL) return NULL; Christian From rdcollum at gmail.com Fri Dec 19 09:44:02 2008 From: rdcollum at gmail.com (Roger) Date: Fri, 19 Dec 2008 06:44:02 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <494b5f47$0$17068$6e1ede2f@read.cnntp.org> <494b632b$0$17070$6e1ede2f@read.cnntp.org> Message-ID: <0390fcbc-8100-4aa8-93fa-ad358609ab7b@p2g2000prn.googlegroups.com> > either. I'd suggest a plain-python workaround along the lines of Wow. You just blew my mind. I'm going to play with this. Thanks a lot, I've really learned a lot in just that small bit. I don't have much experience in playing with a lot of the 'private' calls such as __call__. I need to do some more reading. Roger. From musiccomposition at gmail.com Mon Dec 8 22:45:36 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 8 Dec 2008 19:45:36 -0800 (PST) Subject: Catching Python exceptions in C References: Message-ID: On Dec 8, 12:42?pm, Senthil Kumar wrote: > Hi Pythoneers ! > Can somebody give a quick solution? > I am trying to raise exceptions in python and trying to handle it in > C. > I am able to raise exceptions successfully. However could not catch > those in C. > I am using the following function to run the python from C: > Pyrun_SimpleString(). > After the exception is raised, I am checking PyErr_Occurred(). It > always returns NULL, and I cannot catch the exception. > Pls help me a way out. If a function returns NULL, you can use PyErr_ExceptionMatches to check if it is the exception you want to catch. > > Thanx in advance ! From rt8396 at gmail.com Mon Dec 29 01:14:36 2008 From: rt8396 at gmail.com (r) Date: Sun, 28 Dec 2008 22:14:36 -0800 (PST) Subject: why cannot assign to function call References: Message-ID: <579ac8fe-8d8e-4c93-87d4-6a22c9d066f2@r40g2000yqj.googlegroups.com> On Dec 29, 12:01?am, scsoce wrote: > I have a function return a reference, and want to assign to the > reference, simply like this: > ?>>def f(a) > ? ? ? ? ? return a > ? ? ?b = 0 > ? ? * f( b ) = 1* > but the last line will be refused as "can't assign to function call". > In my thought , the assignment is very nature, ?but ?why the interpreter > refused to do that ? > > thks because all you need to do is >>> b = 1 trying to change the return value of a function before you even "know what it is" so to speak, defeats the whole purpose of sending it there in the first place. just assign the variable to a new value. Thats my common sense answer, maybe somebody can give a technical one :) From workingpad at gmail.com Sun Dec 28 23:26:21 2008 From: workingpad at gmail.com (Jack.Chu) Date: Sun, 28 Dec 2008 20:26:21 -0800 (PST) Subject: creating a datetime.datetime from an XML xs:dateTime References: <5fa6c12e0812271208x4baccaedk262e51becb6e2076@mail.gmail.com> <18774.36465.346262.883182@montanaro-dyndns-org.local> <5fa6c12e0812271255l4f4893e8w9f96e9ace73ea50c@mail.gmail.com> Message-ID: I think a simple regular expression is a relatively easy solution. From philip at semanchuk.com Tue Dec 9 12:29:17 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 9 Dec 2008 12:29:17 -0500 Subject: When (and why) to use del? In-Reply-To: <1228840517.4109.10.camel@brotherus.rdu.redhat.com> References: <1228840517.4109.10.camel@brotherus.rdu.redhat.com> Message-ID: On Dec 9, 2008, at 11:35 AM, Albert Hopkins wrote: > I'm looking at a person's code and I see a lot of stuff like this: > > def myfunction(): > # do some stuff stuff > my_string = function_that_returns_string() > # do some stuff with my_string > del my_string > # do some other stuff > return > > and also > > def otherfunction(): > try: > # some stuff > except SomeException, e: > # more stuff > del e > return > > > I think this looks ugly, but also does it not hurt performance by > preempting the gc? My feeling is that this is a misuse of 'del'. Am I > wrong? Is there any advantage of doing the above? The code above doesn't pre-empt the GC, it just provides it with a useful hint. When you del a variable you just tell the GC, "I'm done with this, so you might be able to get rid of it next time you collect garbage". If the variable wasn't explicitly del-ed, you'd still hold a reference and the GC would be unable to collect it while the section "do some other stuff" runs. HOWEVER, I don't code that way and I've never seen anyone else do that. It's ugly, as you said, and represents a lot of mental clutter for anyone reading/writing the code. And since the GC might not even run during the "do some other stuff" section, there might be no advantage at all to the explicit del. On rare occasions (I can think of once or twice in all the Python I've written) I'll del a variable that might use lots of memory if it wouldn't otherwise get dereferenced quickly (say, by going out of scope). But in my experience that's quite rare. Cheers Philip From clp at rebertia.com Mon Dec 15 15:16:06 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 15 Dec 2008 12:16:06 -0800 Subject: Problem accessing a web page In-Reply-To: References: Message-ID: <47c890dc0812151216o59a3cbc2uf98d74604988d27@mail.gmail.com> On Mon, Dec 15, 2008 at 11:55 AM, Antoni Mont wrote: > Hi all, > > My apologises if this is not the appropriate group. > > I'd like to access a web site from a python script. That page, in fact, > is a form of main page. With a browser (Firefox, for instance) I can do > it without problem: I open the main web whose url is: > > 'http://www.mcu.es/webISBN/tituloSimpleFilter.do?cache=init&prev_layout=busquedaisbn&layout=busquedaisbn&language=es' > > and then, from the same (or another tab) I open the form (it's a book > database and the ISBN is the relevant parameter) whose url is: > > 'http://www.mcu.es/webISBN/tituloSimpleDispatch.do?params.forzaQuery=N¶ms.cisbnExt=8484031128&action=Buscar&layout=busquedaisbn' > > So I get the information about the book. > > But when I try to do the same from the script, I get a time-out > error -without time elapsing at all. This is the piece of the > script relevant for the subject: I'm able to grab the problem webpage via Python just fine, albeit with a bit of a delay. So, don't know what your exact problem is, maybe your connection? If you're trying to programmatically browse the web, you might want to look at mechanize: http://wwwsearch.sourceforge.net/mechanize/ Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From arnodel at googlemail.com Mon Dec 15 16:28:03 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 15 Dec 2008 21:28:03 +0000 Subject: tricky nested list unpacking problem References: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> Message-ID: Reckoner writes: > Hi, > > I have lists of the following type: > > [1,2,3,[5,6]] > > and I want to produce the following strings from this as > > '0-1-2-3-5' > '0-1-2-3-6' > > That was easy enough. The problem is that these can be nested. For > example: > > [1,2,3,[5,6],[7,8,9]] > > which should produce > > '0-1-2-3-5-7' > '0-1-2-3-5-8' > '0-1-2-3-5-9' > '0-1-2-3-6-7' > '0-1-2-3-6-8' > '0-1-2-3-6-9' > > also, > > [1,2,3,[5,6],7,[9]] > > should produce > > '0-1-2-3-5-7-9' > '0-1-2-3-6-7-9' > > obviously, these are nested loops over the lists. The problem is that > I don't know ahead of time how many lists there are or how deep they > go. In other words, you could have: > > [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]] IMHO the second level of nested lists is unnecessary as the same can be achieved with just one sublevel of list (unless they are to be interpreted in a way you have not explained). If you avoid this double nesting then the 'flatten()' function below is not necessary anymore. > > Any help appreciated. I've really been having trouble with this. > > I hope that made sense. Here is a not thought out solution: def flatten(lst): for x in lst: if isinstance(x, list): for y in flatten(x): yield y else: yield x def unpack(lst): stack, strings = [], [] def rec(): i = len(stack) if i == len(lst): strings.append('-'.join(map(str, stack))) elif isinstance(lst[i], list): for x in flatten(lst[i]): stack.append(x) rec() stack.pop() else: stack.append(lst[i]) rec() rec() return strings l1 = [1,2,3,[5,6]] l2 = [1,2,3,[5,6],[7,8,9]] l3 = [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]] Then: >>> unpack(l1) ['1-2-3-5', '1-2-3-6'] >>> unpack(l2) ['1-2-3-5-7', '1-2-3-5-8', '1-2-3-5-9', '1-2-3-6-7', '1-2-3-6-8', '1-2-3-6-9'] >>> unpack(l3) ['1-2-3-5-7-9', '1-2-3-5-7-1', '1-2-3-5-7-2', '1-2-3-5-7-3', '1-2-3-5-7-4', '1-2-3-5-7-5', '1-2-3-5-6-9', '1-2-3-5-6-1', '1-2-3-5-6-2', '1-2-3-5-6-3', '1-2-3-5-6-4', '1-2-3-5-6-5', '1-2-3-5-10-9', '1-2-3-5-10-1', '1-2-3-5-10-2', '1-2-3-5-10-3', '1-2-3-5-10-4', '1-2-3-5-10-5', '1-2-3-5-11-9', '1-2-3-5-11-1', '1-2-3-5-11-2', '1-2-3-5-11-3', '1-2-3-5-11-4', '1-2-3-5-11-5'] -- Arnaud From rhamph at gmail.com Mon Dec 8 23:44:09 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 8 Dec 2008 20:44:09 -0800 (PST) Subject: Rich Comparisons Gotcha References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> Message-ID: <85dacb56-4f2c-42ad-a9a9-90ce7fbc5032@g17g2000prg.googlegroups.com> On Dec 8, 7:44?pm, Steven D'Aprano wrote: > On Mon, 08 Dec 2008 10:20:56 -0800, Rhamphoryncus wrote: > > On Dec 7, 4:20?pm, Steven D'Aprano > cybersource.com.au> wrote: > >> On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: > >> > Rasmus Fogh wrote: > > >> >> Current behaviour is both inconsistent and counterintuitive, as > >> >> these examples show. > > >> >>>>> x = float('NaN') > >> >>>>> x == x > >> >> False > > >> > Blame IEEE for that one. Rich comparisons have nothing to do with > >> > that one. > > >> There is nothing to blame them for. This is the correct behaviour. NaNs > >> should *not* compare equal to themselves, that's mathematically > >> incoherent. > > > Mathematically, NaNs shouldn't be comparable at all. ?They should raise > > an exception when compared. ?In fact, they should raise an exception > > when *created*. ?But that's not what we want. ?What we want is a dummy > > value that silently plods through our calculations. ?For a dummy value > > it seems a lot more sense to pick an arbitrary yet consistent sort order > > (I suggest just above -Inf), rather than quietly screwing up the sort. > > > Regarding the mythical IEEE 754, > > It's hardly mythical. > > http://ieeexplore.ieee.org/ISOL/standardstoc.jsp?punumber=4610933 I consider it to be mythical because most knowledge of it is indirect. Few who use floating point have the documents available to them. Requiring purchase/membership is the cause of this. > > although it's extremely rare to find > > quotations, I have one on just this subject. ?And it does NOT say "x == > > NaN gives false". ?It says it gives *unordered*. > > Unordered means that none of the following is true: > > x > NaN > x < NaN > x == NaN > > It doesn't mean that comparing a NaN with something else is an error. Robert Kern already clarified that. My confusion was due to relying on second-hand knowledge. From cournape at gmail.com Mon Dec 29 21:52:44 2008 From: cournape at gmail.com (David Cournapeau) Date: Tue, 30 Dec 2008 11:52:44 +0900 Subject: Python in C In-Reply-To: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> References: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> Message-ID: <5b8d13220812291852y42b227d8w736546eff5f6947b@mail.gmail.com> On Tue, Dec 30, 2008 at 10:22 AM, wrote: > I've just downloaded Python's mainstream implementation (CPython), > which is written in C. Not to my surprise, I feel like I'm looking at > unstructured spaghetti, and I'm having trouble figuring out how it all > works together. (Please bear with me; I'm just going through the usual > frustration that anyone goes through when trying to see the > organization of a C program :) > > So, I have two queries: > > 1. Can anyone explain to me what kind of program structuring technique > (which paradigm, etc) CPython uses? How do modules interact together? > What conventions does it use? I am not sure what you mean by "which paradigm". CPython uses ansi C, objects visible at the python level are structures, the API is exposed through array of function pointers, etc... which are all standard C techniques. All core objects are in Objects, and each of them expose its API in a function pointer array; for example, the complex object (in complexobject.c) implements its basic API through the PyObjectType, which contains functions called by the interpreter. At the beginning, I was a bit confused by the terminology (like protocol), but that may just be my poor English. The documentation is pretty good: http://docs.python.org/c-api/index.html (for python 2.6) It may be easier to first see how to code your own extension, maybe - if only because the related doc is written as a tutorial instead of as a reference as the above. > > 2. Have there been any suggestions in the past to rewrite Python's > mainstream implementation in C++ (or why wasn't it done this way from > the beginning)? Python was started in the early 90, where arguably, C++ was not easy to deal with: not many good compilers were available, most 'interesting' features of C++ were not portable because implemented differently. Without going through the dreadful C vs C++, C++ is arguably more complex and much bigger than C++, to the point where it is almost impossible for anyone to master the whole language. This means that people only use a subset of it, and many projects use a coding style which severly limit what you can do to avoid everyone using a different subset; this can be managed in constraints environments, but it does not work well in open source generally. It is certainly not my experience that C++ is more readable than C in the projects I have been involved with. Also, there are some objective facts against C++ for things "at the bottom" like a programming language: C++ is not easily callable from other languages, whereas C is (the C ABI is standardized on many platforms, whereas C++ is not). In particular, calling dynamically loaded code in C++ is very difficult (practically, a C wrapper has to be provided). Taking an example of arguably mature and big C++ project, the JDK, its external API is in C, not C++. cheers, David From benjamin.kaplan at case.edu Tue Dec 23 08:44:47 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 23 Dec 2008 08:44:47 -0500 Subject: SuSE11.1 eclipse 64 pydev can't add python path In-Reply-To: References: Message-ID: On Tue, Dec 23, 2008 at 7:49 AM, Reimar Bauer wrote: > Hi > > I can install pydev using the update manager in eclipse for 64 bit from the > SuSE 11.1 repo. But I can't configure pydev without crashing it. > I can select the interpreter /usr/bin/python > and I do see the System PYTHONPATH > Forced builtin libs also looks good. > > But Apply gives me > # > # An unexpected error has been detected by Java Runtime Environment: > # > # SIGSEGV (0xb) at pc=0x00007f2d7abebaed, pid=6544, tid=139832007596368 > # > # Java VM: IcedTea 64-Bit Server VM (1.7.0-b24 mixed mode linux-amd64) > # Problematic frame: > # V [libjvm.so+0x21baed] > # > # An error report file with more information is saved as: > # /home/user/hs_err_pid6544.log > # > # If you would like to submit a bug report, please visit: > # http://icedtea.classpath.org/bugzilla > # The crash happened outside the Java Virtual Machine in native code. > # See problematic frame for where to report the bug. > > > That problem happens also with the recent > eclipse-cpp-ganymede-SR1-linux-gtk-x86_64.tar.gz > > What can be the cause for this problem? Do you know a workaround e.g. > manually configuring pydev? > > Does one have pydev or eclipse working on SuSE11.1? > > > cheers > Reimar > This isn't a problem with PyDev. This is a known bug in the 64-bit Java, both Sun and OpenJDK. It was fixed in the really recent updates (Sun 6u10 and OpenJDK 6b12, I think), which I guess SuSE doesn't have yet. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Fri Dec 5 19:27:27 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sat, 06 Dec 2008 01:27:27 +0100 Subject: Running Python 2 and Python 3 on the same machine In-Reply-To: <1228489547.5613.10.camel@linux-3eb6.site> References: <1228424486.5873.6.camel@linux-3eb6.site> <49387f7e$0$27857$9b622d9e@news.freenet.de> <1228489547.5613.10.camel@linux-3eb6.site> Message-ID: <4939c6ef$0$6534$9b622d9e@news.freenet.de> > For *NIX machines, will 'python' be placed into /usr/bin? Not by default, no. Just try it and see for yourself. Regards, Martin From jcd at sdf.lonestar.org Wed Dec 10 18:29:44 2008 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Wed, 10 Dec 2008 18:29:44 -0500 Subject: var or inout parm? In-Reply-To: <47c890dc0812080057r6d117bbcic377cb96de52d973@mail.gmail.com> References: <493cda2a$0$17080$426a34cc@news.free.fr> <47c890dc0812080057r6d117bbcic377cb96de52d973@mail.gmail.com> Message-ID: <1228951784.5698.1.camel@mctell> On Mon, 2008-12-08 at 00:57 -0800, Chris Rebert wrote: > On Mon, Dec 8, 2008 at 12:26 AM, Bruno Desthuilliers > wrote: > > Colin J. Williams a ?crit : > >> > >> mh at pixar.com wrote: > >>> > >>> How can I make a "var" parm, where the called function can modify > >>> the value of the parameter in the caller? > >>> > >>> def f(x): > >>> x = x + 1 > >>> > >>> n = 1 > >>> f(n) > >>> # n should now be 2 > >>> > >>> Many TIA!! > >>> Mark > >>> > >>> > >> > >> Why not run it and see? > >> > >> Your function returns None. > >> > >> The function in effect takes a copy of n. > > > > Nope, it takes the object bound to global name 'n'. > > See Also: the earlier heated debate thread over what evaluation > strategy Python uses (Survey says!: call-by-object). > Oh dear God. PLEASE don't see also that thread. That way lies madness. Just google for call-by-object, and ignore the hell out of that thread. > Cheers, > Chris > From news123 at free.fr Wed Dec 17 15:20:40 2008 From: news123 at free.fr (News123) Date: Wed, 17 Dec 2008 21:20:40 +0100 Subject: mysql hash generator in python In-Reply-To: References: Message-ID: <49495f18$0$17874$426a74cc@news.free.fr> Hi Matias. Could you show us the 'class implementation'? Whether class or not the result should be the same. If it isn't, then there should be a small error. If we have both code versions to look at it's easier to help you. bye N Mat?as Hern?ndez wrote: > (sorry for my english, but i'm speak spanish) > Hi list.. this is my first post... and obviously if for help.. > > I try to implement the password function of mysql in a python script. > > I read that the password function of mysql was implemented with a double > sha1() > > I python i try this: > example1: > if __name__=="__main__": > s = hashlib.sha1() > s.update('test') > s2 = hashlib.sha1() > s2.update(s.digest() > print s2.hexdigest() > > This script show me the same hash that password function of mysql, but > when i implement this in a class the hash is different??? why??? > > And if is posible??? can you show a example code of old_password > function of mysql in python??? > > THNX From LambertDW at Corning.com Thu Dec 11 02:07:54 2008 From: LambertDW at Corning.com (Lambert, David W (S&T)) Date: Thu, 11 Dec 2008 02:07:54 -0500 Subject: if expression source format Message-ID: <84B204FFB016BA4984227335D8257FBA625679@CVCV0XI05.na.corning.com> The "if" expression leads to long statements. Please offer suggestions to beautify this function. For this example use maximum line length marked by the ####'s. Thank you. ############################################################## def compute_wind_chill_temperture(T:'Temperature, dF',s:'Wind speed, mph')->'dF': ''' ''' return 35.74 + 0.6215*T + s**0.16*(T*0.4275-35.75) if T < 40 else T From google at mrabarnett.plus.com Sat Dec 6 18:48:49 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 06 Dec 2008 23:48:49 +0000 Subject: how to get a beep, OS independent ? In-Reply-To: <493B0D85.3060404@gmail.com> References: <493B0D85.3060404@gmail.com> Message-ID: <493B0F61.6030604@mrabarnett.plus.com> Stef Mientki wrote: > hello, > > I want to give a small beep, > for windows there's message-beep, > and there seems to be something like " curses" , > but that package seems to be totally broken in P2.5 for windows. > > Any other suggestions ? > print chr(7)? From gagsl-py2 at yahoo.com.ar Wed Dec 10 17:23:09 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 10 Dec 2008 20:23:09 -0200 Subject: When (and why) to use del? References: <1228840517.4109.10.camel@brotherus.rdu.redhat.com> Message-ID: En Tue, 09 Dec 2008 15:29:17 -0200, Philip Semanchuk escribi?: > On Dec 9, 2008, at 11:35 AM, Albert Hopkins wrote: > >> def myfunction(): >> # do some stuff stuff >> my_string = function_that_returns_string() >> # do some stuff with my_string >> del my_string >> # do some other stuff >> return >> >> I think this looks ugly, but also does it not hurt performance by >> preempting the gc? My feeling is that this is a misuse of 'del'. Am I >> wrong? Is there any advantage of doing the above? > > The code above doesn't pre-empt the GC, it just provides it with a > useful hint. When you del a variable you just tell the GC, "I'm done > with this, so you might be able to get rid of it next time you collect > garbage". If the variable wasn't explicitly del-ed, you'd still hold a > reference and the GC would be unable to collect it while the section "do > some other stuff" runs. Note that CPython has a garbage collector AND uses reference counts. Objects are deallocated *immediately* as soon as their reference count reaches zero. The GC is used only to detect and dispose of reference cycles. So, if you `del` a name and it happens to be the last reference to certain object, the object is immediately destroyed; the GC isn't involved at all. > On rare occasions (I can think of once or twice in all the Python I've > written) I'll del a variable that might use lots of memory if it > wouldn't otherwise get dereferenced quickly (say, by going out of > scope). But in my experience that's quite rare. Yes, I've seldom used "del" in those circumstances too. And inside an exception handler. I can't remember of other cases. -- Gabriel Genellina From fetchinson at googlemail.com Sat Dec 6 16:49:40 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 6 Dec 2008 13:49:40 -0800 Subject: Guido's new method definition idea In-Reply-To: <493a9fed$0$18973$426a34cc@news.free.fr> References: <493a9fed$0$18973$426a34cc@news.free.fr> Message-ID: >> Hi folks, >> >> The story of the explicit self in method definitions has been >> discussed to death and we all know it will stay. However, Guido >> himself acknowledged that an alternative syntax makes perfect sense >> and having both (old and new) in a future version of python is a >> possibility since it maintains backward compatibility. The alternative >> syntax will be syntactic sugar for the old one. This blog post of his >> is what I'm talking about: >> >> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html >> >> The proposal is to allow this: >> >> class C: >> def self.method( arg ): >> self.value = arg >> return self.value >> >> instead of this: >> >> class C: >> def method( self, arg ): >> self.value = arg >> return self.value >> > (snip) >> I'd like this new way of defining methods, what do you guys think? > > -1 > > As far as I'm concerned, it doesn't add anything to the language, nor > doesn't save any typing, so I just don't see the point. And having it > co-existing with the normal syntax will only add more confusion. It doesn't add anything but makes something that exists a bit clearer and friendlier to newbies. Saving typing was never the intention. > NB : FWIW, I would eventually have voted -0 if it had been proposed for > Python 3, and as a _replacement_ (not _alternative_) to the current > syntax. But Python 3 is now released, so... There will be python 4000 eventually :) -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From bearophileHUGS at lycos.com Mon Dec 1 20:02:17 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 1 Dec 2008 17:02:17 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: <673ca33e-9c1e-4c8e-a81d-d46828fe47b1@n10g2000yqm.googlegroups.com> Mathematica has some powerful symbolic processing capabilities, for example the integrals, etc. It also contains many powerful algorithms, often written in few lines of code. And its graphic capabilities are good. It also shows some surprising ways to integrate and manipulate data, for example here you can see how you can even put images into formulas, to manipulate them: http://reference.wolfram.com/mathematica/ref/ImageApply.html So when you need an algorithm, you can often find it already inside, for example in the large Combinatorics package. So it has WAY more batteries included, compared to Python. I'd like to see something as complete as that Combinatorics package in Python. But while the editor of (oldish) Mathematica is good to quickly input formulas (but even for this I have found way better things, for example the editor of GraphEQ www.peda.com/grafeq/ that is kilometers ahead), it's awful for writing *programs* even small 10-line ones. Even notepad seems better for this. For normal programming Python is light years more handy and better (and more readable too), there's no contest here. Python is also probably faster for normal programs (when built-in functions aren't used). Python is much simpler to learn, to read, to use (but it also does less things). A big problem is of course that Mathematica costs a LOT, and is closed source, so a mathematician has to trust the program, and can't inspect the code that gives the result. This also means that any research article that uses Mathematica relies on a tool that costs a lot (so not everyone can buy it to confirm the research results) and it contains some "black boxes" that correspond to the parts of the research that have used the closed source parts of Mathematica, that produce their results by "magic". As you can guess, in science it's bad to have black boxes, it goes against the very scientific method. Bye, bearophile From ppearson at nowhere.invalid Fri Dec 5 12:33:11 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 5 Dec 2008 17:33:11 GMT Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> Message-ID: <6pt6unF9q11aU1@mid.individual.net> On Thu, 4 Dec 2008 15:49:46 -0600, skip at pobox.com wrote: > > It's more than warnings. With properly crafted > combinations of spaces and tabs you can get code which > looks like it has a certain indentation to the human > observer but which looks like it has different indentation > (and thus different semantics) to the byte code compiler. > There is often no warning. Fascinating. Has anybody developed demo code that looks, during code review, as if it prints a Snoopy calendar, but really, during execution, emails your password file to Minsk? The security implications are intriguing. What's the most underhanded thing anybody has seen done? -- To email me, substitute nowhere->spamcop, invalid->net. From bearophileHUGS at lycos.com Sun Dec 7 21:17:58 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 7 Dec 2008 18:17:58 -0800 (PST) Subject: Python for kids? References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> <53f406ed-c261-4d86-a8dc-4001d10d05b5@s20g2000yqh.googlegroups.com> <11a3e492-3c0d-475f-b350-f28351842dad@f3g2000yqf.googlegroups.com> Message-ID: <0494617a-4ac3-40a9-9ff0-d39cd4882497@s20g2000yqh.googlegroups.com> Luis M. Gonz?lez: >After he tried hard many approaches to solving the problem with his limited knowledge,< You may even be surprised to see he/her/hir find a solution without your help :-) Or maybe you will see a different solution, this happens often in math and computer science, even basic ones. >show him the right way. This way he will see the light.< Sometimes if the problem is interesting there are more than one "right way". And showing the light is more a purpose for priests than teachers ;-) Note that such things are well known, you can find similar things in tons of (most) books about pedagogy. For example you can try a simple but delicious book, "Brainstorms" by Seymour Papert (who also was one of the inventors of Logo language and is currently learning to talk and walk again). You can even find similar ideas in books more far from pedagogy ones, like "Deschooling Society" by Ivan Illich. Bye, bearophile From fernandohsanches at gmail.com Fri Dec 5 15:16:47 2008 From: fernandohsanches at gmail.com (Fernando H. Sanches) Date: Fri, 5 Dec 2008 12:16:47 -0800 (PST) Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> Message-ID: <84332560-580d-488b-aa6b-6aad754a7805@k36g2000pri.googlegroups.com> On Dec 4, 5:45?pm, Andreas Waldenburger wrote: > On Thu, 4 Dec 2008 11:52:38 -0600 s... at pobox.com wrote: > > > > > ? ? >>> As you have probably guessed: nothing changed here. > > ? ? >>> Also see:http://www.python.org/dev/peps/pep-0666/ > > > ? ? >> What? Do you mean it's possible to mix tabs and spaces still? > > ? ? >> Why? > > > ? ? Daniel> Why not? > > > Because it has historically been a source of errors in a mixed > > development environment (people using text editors with different tab > > stops). ?Better to not allow them to be mixed. > > Whenever has it been a pythonic ideal to "not allow" stuff? You get > warnings. Everything else is up to you. > > /W > > -- > My real email address is constructed by swapping the domain with the > recipient (local part). Python has "not allowed stuff" for a long time. For example, it disallows statements in lambdas. "Disallowing" is not bad. Disallowing bad practices (like mixing tabs and spaces) is actually good! I agree that the tab/space thing should be changed. Would it be too hard to make the parser see if the indentation is consistent in the whole file? This is a annoying source of problems, specially since you can't tell a whitespace from a tab just looking at it. And I personally disliked most of the changes (specially the ones on map and reduce). I hope functional programming doesn't get even more hindered in future releases, because I believe these changes only made Python weaker. Well, anyway, congratulations for everyone for Python 3 release. Some of the changes were a real improvement (like the Unicode sources). And I hope that, in the end, these changes help making Python a better language. From brendandetracey at yahoo.com Fri Dec 12 09:25:14 2008 From: brendandetracey at yahoo.com (Brendan) Date: Fri, 12 Dec 2008 06:25:14 -0800 (PST) Subject: Reading online zip files - zipfile and zlib, wbits Message-ID: I am fooling around with accessing contents of zip files online. I download the tail end of the zip and use zipfile to get the zip central directory structure. I download the section of the zip file I need, directly read the zip file headers and use that information with zlib to uncompress the data. The files I am examining will always be compressed using deflate, with a wbits value of -15(minus for headerless data because I am unsure whether the zip file header is what zlib expects). I can not find anywhere in the PK Zip Application notes ( http://www.pkware.com/documents/casestudies/APPNOTE.TXT ) how to determine the value I should uze for wbits with zlib.decompress. I have determined it is -15 from experimentation. Does anyone know the answer to this? From tjreedy at udel.edu Mon Dec 8 17:21:30 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Dec 2008 17:21:30 -0500 Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? In-Reply-To: <682de8aa-62b1-477a-8b31-ae7698b1ffe7@w1g2000prk.googlegroups.com> References: <5ccd4a18-cd2b-4040-90c6-33723af15e96@b38g2000prf.googlegroups.com> <7e1a9226-c7a9-4b5e-bfbb-ea079639d6a2@t39g2000prh.googlegroups.com> <682de8aa-62b1-477a-8b31-ae7698b1ffe7@w1g2000prk.googlegroups.com> Message-ID: illume wrote: > On Dec 8, 7:31 pm, alex23 wrote: >> On Dec 8, 2:26 pm, illume wrote: >> >>> pygame is simpler to learn, since it doesn't require you to know how >>> to create classes or functions. >> I'm not sure if I'd be quick to tout that as an advantage... :) > > Hi, > > It's easier to teach only requiring *using* classes, and functions > than *creating* them. This is important if it's being used to teach > programming - as you don't need to teach people two fairly large > concepts before you can do anything. Every program defines a function that maps input from the external world (possible null, but not for a game) to output to the external world (presumable not null, certainly not for a game). So defining internal function objects is not that big a step. I agree that creating new classes is a big step, and that using callbacks can be a mind-twister. tjr From jr9445 at ATT.COM Mon Dec 8 16:07:01 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Mon, 8 Dec 2008 15:07:01 -0600 Subject: Guido's new method definition idea In-Reply-To: <699ea750-8dd9-472f-a7aa-90492c32c519@z1g2000yqn.googlegroups.com> References: <493a9fed$0$18973$426a34cc@news.free.fr> <493c1ff6$0$4942$426a34cc@news.free.fr><49d12ec1-2be9-497b-80bc-9f0402a9086d@s20g2000yqh.googlegroups.com> <699ea750-8dd9-472f-a7aa-90492c32c519@z1g2000yqn.googlegroups.com> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Aaron Brady > Sent: Monday, December 08, 2008 3:27 PM > To: python-list at python.org > Subject: Re: Guido's new method definition idea > > On Dec 7, 4:23?pm, Philip Slate wrote: > > On Dec 7, 1:13?pm, Bruno Desthuilliers > > > > wrote: > > > > and friendlier to newbies. > > > > > I'd rather say "more acceptable to java-brainwashed developpers". > > > > And I'd rather say you're trolling, but that's ok since you're > > preaching to the converted. You conveniently forgot to mention the > C++/ > > Eiffel/Smalltalk/pretty-much-every-OO-lang "brainwashed" developers > > too. In reality Python, with its kludgy OO and objects being > > essentially glorified dicts, is the odd one out, not the other way > > around. > > That's true. But what would a Python-brainwashed developer be? Anyone who believes that writing beautiful, unencumbered code is efficient, while still believing that discovering type casting errors at runtime isn't grossly inefficient. Or given whitespace delimited code, Python developers believe that nothing is important. ;-) ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA623 From wdraxinger at darkstargames.de Mon Dec 8 07:33:36 2008 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Mon, 08 Dec 2008 13:33:36 +0100 Subject: Shutdown Mac OSX computer using python References: Message-ID: <0qgv06-jpp.ln1@skadi.yggdrasil.draxit.de> H?kan Hagenrud wrote: > Hello, i'm a python noob! > > But I would like to shutdown a 10.5.x mac computer using python > (2.5.1) > > this is my code: > #!/usr/bin/python > import SystemEvents > down = SystemEvents.Power_Suite.Power_Suite_Events() > down.shut_down() > > the last call needs an additional argument, I cant find any > documentation about this. Anybody knows? > > Thank you! Why so complicated? MacOS X is a Unix at it's base, so you can use Unix commands. #!/usr/bin/python import os os.system("shutdown -h now") Must be run as root, won't work otherwise. You can however add to sudoers (man visudo) shutdown as NOPASSWD program for the users that want to execute the script and use "sudo shutdown ..." instead of just "shutdown ..." Wolfgang Draxinger -- E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 16 03:45:36 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 16 Dec 2008 09:45:36 +0100 Subject: ethical questions about global variables In-Reply-To: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> References: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> Message-ID: <49476a7c$0$28214$426a74cc@news.free.fr> Giampaolo Rodola' a ?crit : > Hi, > in a module of mine (ftpserver.py) I'd want to add a (boolean) global > variable named "use_gmt_times" to decide whether the server has to > return times in GMT or localtime but I'm not sure if it is a good idea > because of the "ethical" doubts I'm gonna write below. > > In first place I've never liked global variables too much and always > preferred per-class-instance variables instead. > The problem in my case is that I have to use such variable in two > separated classes: FTPHandler and VirtualFileSystem. Also, I want that > for no reason one class uses times in GMT and the other one local > times. Looks like it's more a configuration variable than a global. IOW, it's not supposed to change during execution. > Another doubt is the naming convention. PEP-8 states that global > variables should use the lower_case_naming_convention but I've seen a > lot of library module using the UPPER_CASE_NAMING_CONVENTION. ALL_UPPER_NAMES are pseudo-constants - IOW, they are really variables but are by convention considered as constants. HTH From goatold at gmail.com Mon Dec 15 21:46:55 2008 From: goatold at gmail.com (goatold at gmail.com) Date: Mon, 15 Dec 2008 18:46:55 -0800 (PST) Subject: socket and subprocess problem Message-ID: <6d3291c3-4e12-4bdd-884a-21f15f38d105@a12g2000pro.googlegroups.com> Hi all, Here is my problem, see if any one else met this before In my python code I use subprocess.Popen to run and external program who will listen to a TCP port. And I also create a socket to connect to the TCP port that the external program is listening. I will get 'Connection refused, errno=111' when I try to socket.connect (). But if I run my subprocess.Popen code and socket code in two separate python process. Socket will connect just fine. OS is RHEL5 x86_64, python version is 2.6.1 Pseudo code as below Class a: def run() subprocess.Popen(..) Class b: def run(): sock = socket.socket() sock.connect(..) ################################# test.py # socket connect will fail here a.run() b.run() ################################### test1.py if __name__ = '__main__': a.run() test2.py # socket will connect fine if __name__ = '__main__': b.run From eric at ericaro.net Wed Dec 10 06:08:05 2008 From: eric at ericaro.net (eric) Date: Wed, 10 Dec 2008 03:08:05 -0800 (PST) Subject: Best way to report progress at fixed intervals References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> <817384d5-5f68-4c1f-9560-0bc7b7d2b1e3@v5g2000prm.googlegroups.com> <6ccb77a2-a3f1-4b6b-900c-d4626be9e939@s1g2000prg.googlegroups.com> Message-ID: <93371329-5989-4f96-ac79-58a54ba6b07f@35g2000pry.googlegroups.com> Don't mind if I give my shot ? def work(i): """ Dummy process function, which takes a random time in the interval 0.0-0.5 secs to execute """ print "Work step %d" % i time.sleep(0.5 * random.random()) def workAll(work, verbose=True, max_iter=20, progress_interval=1.0): ''' pass the real job as a callable ''' progress = time.time() for i in range(max_iter): # do the requested loop work(i) if verbose: print "Work through all %d steps reporting progress every %3.1f secs..." %(max_iter, progress_interval) interval = time.time()-progress if interval>progress_interval: print "Processed %d of %d at pace %s" % (i, max_iter, interval) progress +=interval if __name__=="__main__": workAll(work, False) It's works fine, and the "pace" is 'almost' the required one. You earn a no-thread-mess, and cleaner alg. But the loop is controlled by the caller (the WorkAll function) this is also called ass-backward algorithm, and you cannot expect algorithms to be assbackward (even if it's the best way to implement them). You can use the yield statement, to turn easilly your alg into a nice, stopable assbackward algo: def work(): """ Dummy process function, which takes a random time in the interval 0.0-0.5 secs to execute """ for i in range(50): print "Work step %d" % i time.sleep(0.5 * random.random()) yield i # kind-of "publish it and let the caller do whatever it want s (good practice anyway) def workAll(work, verbose=True, max_iter=20, progress_interval=1.0): ''' pass the real job as a generator ''' progress = time.time() i = 0 for w in work: # do the requested loop if verbose: print "Work through all %d steps reporting progress every %3.1f secs..." %(max_iter, progress_interval) interval = time.time()-progress if interval>progress_interval: print "Processed %d at pace %s" % (w, interval) progress +=interval if i>=max_iter: work.close() i+=1 if __name__=="__main__": workAll(work(), False) # note the calling difference hope it helps. From Scott.Daniels at Acm.Org Mon Dec 15 14:46:27 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 15 Dec 2008 11:46:27 -0800 Subject: Removing None objects from a sequence In-Reply-To: <01538f0c$0$6988$c3e8da3@news.astraweb.com> References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> <4942E668.5030100@tim.thechases.com> <01538f0c$0$6988$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Fri, 12 Dec 2008 19:02:24 -0500, Terry Reedy wrote: > ... >> Tim Chase wrote: >>>> If you want to literally remove None objects from a list....(or >>>> mutable sequence) >>>> >>>> def deNone(alist): >>>> n=len(alist) >>>> i=j=0 >>>> while i < n: >>>> if alist[i] is not None: >>>> alist[j] = alist[i] >>>> j += 1 >>>> i += 1 >>>> alist[j:i] = [] > Contrast that with the alternative suggested by Tim: > > def deNone2(alist): > alist[:] = [x for x in alist if x is not None] > ... > Here's another low-level algorithm, the classical delete items in place > algorithm. Three lines, one index, lousy O(N**2) performance. > > def deNone3(alist): > for i in xrange(len(alist)-1, -1, -1): > if alist[i] is None: > del alist[i] > > Now, let's do a shoot-out. Do they return the same thing? ... [good measurements generally reinforcing Tim's implementation] ... If you want to keep the original's method, but do it in a more Pythonic way, I would suggest: def deNone4(alist): j = 0 for val in alist: if val is not None: alist[j] = val j += 1 del alist[j :] This still loses to Tim's clearer code, but by nowhere near as much. --Scott David Daniels Scott.Daniels at Acm.Org From jstroud at mbi.ucla.edu Sun Dec 14 18:42:18 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 14 Dec 2008 15:42:18 -0800 Subject: Looking for the best way to translate an idiom In-Reply-To: References: Message-ID: Paul Moore wrote: > I'm translating some code from another language (Lua) which has > multiple function return values. So, In Lua, it's possible to define a > function > > function f() > return 1,2,3 > end > > which returns 3 values. These can then be used/assigned by the caller: > > a,b,c = f() > > So far, much like Python, but the key difference is that in Lua, > excess arguments are ignored - so you can do py> class mytuple(tuple): def magic(self, astr): names = astr.split() for name, val in zip(names, self): globals()[name] = val ... py> t = mytuple((1,2,3)) py> t.magic('a b') py> a 1 py> b 2 James From zapwireDASHgroups at yahoo.com Wed Dec 24 18:47:07 2008 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Wed, 24 Dec 2008 15:47:07 -0800 Subject: Easy-to-use Python GUI Message-ID: Is there an easy-to-use, "function"-based cross-platform GUI toolkit for Python out there that's a little more sophisticated than EasyGui? EasyGui looks good, but it's a little more restrictive than what I'd like to have, yet I'm (stubbornly :-) ) resistant to stepping up to a "full service" GUI toolkit such as pyGTK or wxPython where it's all about event loops and callbacks and you need to start planning how the GUI affects the overall program flow rather than just using a "forms" (or "Wizard")-type approach where you put up a few dialogs, users fill in some variables, and your program just sits around waiting until "OK" or "Cancel" is clicked. One approach that I like comes from SAX BASIC/WinWrap, which is more or less a clone of Microsoft's Visual BASIC for Applications, but they (apparently) wanted everything to still be human-readable, so they have a simple GUI ("form") builder that generates code that looks like this: --- Begin Dialog UserDialog 850,497,"Export Control" ' %GRID:10,7,1,1 GroupBox 20,7,360,217,"Drill File Generation",.GroupBox1 CheckBox 40,35,130,14,"Output drill file(s)",.genDrill Text 40,63,270,28,"Identify via layers as any that contain this text in their names:",.Text TextBox 40,98,220,21,.viaLayerName Text 40,140,100,14,"Output method:",.Text8 DropListBox 160,140,180,21,DrillStyle(),.drillStyle Text 40,175,130,28,"Select drill table units:",.Text2 ListBox 200,175,120,28,unitNames(),.unitName OKButton 310,469,90,21 CancelButton 410,469,90,21 End Dialog ' GUI builder generates or modifies everything above, but can also be edited by hand ' You write the following code... Dim dlg As UserDialog dlg.genDrill = 1 ReDim DrillStyle(1) DrillStyle(0) = "All Via Layers In One File" DrillStyle(1) = "One File Per Via Layer" dlg.drillStyle = 1 func=Dialog(dlg) --- This is pretty darned easy for me understand and modify either by hand or with the GUI builder. Still, it's quite powerful, since it supports all the common GUI elements (text, group boxes, checkboxes, drop-down lists, text boxes, buttons, etc.). This is about the level of sophistication I'm looking for. Anything like this for Python? Thanks, ---Joel From tjreedy at udel.edu Thu Dec 4 20:54:28 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Dec 2008 20:54:28 -0500 Subject: pretty strange behavior of "strip" In-Reply-To: <4938693F.6090709@yahoo.ca> References: <4938693F.6090709@yahoo.ca> Message-ID: Guy Doune wrote: > Hi everybody, > > Could it be a bug????? > > Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> test=['03.html', '06.html', 'questions.html', '04.html', > 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test > ['03.html', '06.html', 'questions.html', '04.html', 'toc.html', > '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test[4] > 'toc.html' > >>> test[4].strip('.html') > 'oc' > > Can't figure out what is going on, really. What I can't figure out is why, when people cannot figure out what is going on with a function (or methods in this case), they do not look it up the doc. (If you are an exception and did, what confused you?) Can you enlighten me? tjr From duncan.booth at invalid.invalid Tue Dec 9 13:55:05 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Dec 2008 18:55:05 GMT Subject: When (and why) to use del? References: Message-ID: Albert Hopkins wrote: > def otherfunction(): > try: > # some stuff > except SomeException, e: > # more stuff > del e > return > > > I think this looks ugly, but also does it not hurt performance by > preempting the gc? My feeling is that this is a misuse of 'del'. Am I > wrong? Is there any advantage of doing the above? > It is probably a complete waste of time, but there are situations where code similar to this can be useful: def otherfunction(): try: # some stuff except SomeException, e: # more stuff del e raise return The point of code like this is that when a function exits by throwing an exception the traceback includes a reference to the stack frame and all the local variables. In some situations that can result in large data structures not being freed for a very long time (e.g. until another exception is thrown that is handled at the same level). So, *in very specialised situations* it may be important to delete particular names from the local namespace. From lists at cheimes.de Sun Dec 7 14:18:21 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 07 Dec 2008 20:18:21 +0100 Subject: dict subclass and pickle bug (?) In-Reply-To: References: Message-ID: James Stroud wrote: > Hello All, > > I subclassed dict and overrode __setitem__. When instances are > unpickled, the __setstate__ is not called before the keys are assigned > via __setitem__ in the unpickling protocol. > > I googled a bit and found that this a bug filed in 2003: > > http://bugs.python.org/issue826897 > > It is still "open" with "normal" priority. > > Am I missing something? Is there a workaround for this bug that makes > fixing it pointless or has it just fallen through the cracks for the > last 5 years? Try this: def __newobj__(cls, *args): return cls.__new__(cls, *args) class DictPlus(dict): def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) self.extra_thing = ExtraThingClass() def __setitem__(self, k, v): do_something_with(self.extra_thing, k, v) dict.__setitem__(self, k, v) def __setstate__(self, state): dict.update(self, state[0]) self.__dict__.update(state[1]) def __reduce__(self): state = (dict(self), self.__dict__) return (__newobj__, (self.__class__,), state) Christian From prologic at shortcircuit.net.au Mon Dec 1 22:12:52 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 2 Dec 2008 13:12:52 +1000 Subject: HELP!...Google SketchUp needs a Python API In-Reply-To: <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> Message-ID: This is my first post to this particular topic and my good friend alsex32 will know that I tend to steer away from large pointless conversation topics (for obvious reasons). @OP: Listen ... The best way you can support Python is to use Python. The best way you can promote Python is to encourage others to try it. Python is a fantastic language and development environment. Enough said. Just remember thought that if you threat Python like a hammer, suddenly everything will look like a bail. cheers James -- -- -- "Problems are solved by method" From jstroud at mbi.ucla.edu Sat Dec 13 04:58:28 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 13 Dec 2008 01:58:28 -0800 Subject: Need help improving number guessing game In-Reply-To: References: Message-ID: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> feba wrote: > #!/usr/bin/python/ > #Py3k, UTF-8 > > import random > > print(" --- WELCOME TO THE SUPER NUMBER GUESSING GAME --- " + ("\n" * > 5)) > pnum = int(input("1 OR 2 PLAYER?\nP#: ")) > > target = random.randint(1, 99) #Pick a random number under two digits > > guess1 = 0 #Zero will never be picked as target... > guess2 = 0 #so it makes a good default value > p1score = 0 #For two player mode... > p2score = 0 #let's keep score! > > print("LET'S START THE GAME. \nGUESS ANY WHOLE NUMBER FROM 1 TO 99.") > > while True: > if pnum == 1: #1p mode > while True: > guess1 = int(input("\n>> ")) > if guess1 > 100: > print("ONLY NUMBERS FROM 1 TO 99") > elif guess1 > target: > print("TOO HIGH") > elif guess1 == target: > print("CONGLATGURATIONS! PLAY AGAIN?") > target = random.randint(1, 99) #Set up the game > again > play = int(input("0 TO END: ")) > if play == 0: > print("GOOD BYE. PLAY AGAIN SOON!") > quit() > else: > print("TOO LOW") > > if pnum == 2: #2p mode > while True: > guess1 = int(input("\nP1> ")) #Player 1's turn > if guess1 > 100: > print("ONLY NUMBERS FROM 1 to 99") > elif guess1 > target: > print("TOO HIGH") > elif guess1 == target: > p1score += 1 > print("GOOD JOB, PLAYER 1! THE SCORE IS:\nP1: %s > --- P2: %s\nPLAY AGAIN?" % (p1score, p2score)) > target = random.randint(1, 99) #Set up game > again > play = int(input("0 TO END: ")) > if play == 0: > print("GOOD BYE. PLAY AGAIN SOON!") > else: > print("TOO LOW") > > guess2 = int(input("\nP2> ")) #Player 2's turn > if guess2 > 100: > print("ONLY NUMBERS FROM 1 to 99") > elif guess2 > target: > print("TOO HIGH") > elif guess2 == target: > p2score += 1 > print("GOOD JOB, PLAYER 2! THE SCORE IS:\nP1: %s > --- P2: %s\nPLAY AGAIN?" % (p1score, p2score)) > target = random.randint(1, 99) #Set up game again > play = int(input("0 TO END: ")) > if play == 0: > print("GOOD BYE. PLAY AGAIN SOON!") > else: > print("TOO LOW") > else: > print("INVALID PLAYER SELECTION") > pnum = int(input("1 OR 2 PLAYER?\nPN#: ")) > > > I have one major problem with this; the 'replay' selection. It quits > if you put in 0, as it should, and continues if you put in any other > number. However, if you just press enter, it exits with an error. it > also looks really ugly, and I'm sure there has to be plenty of better > ways to do it. > > I'd also appreciate tips on how it could be better in general. I > should think that P1 and P2's turns shouldn't have to be completely > repeated; but I'm not quite sure how to def something like that. 1. Refactor. You should look at your code and see where you repeat the same or similar patterns, see where they differ, make functions, and make the differences parameters to the function call: def guess(player, p1score, p2score): guess1 = int(input("\n>> ")) if guess1 > 100: print("ONLY NUMBERS FROM 1 TO 99") elif guess1 > target: print("TOO HIGH") elif guess1 == target: print("GOOD JOB, PLAYER %s! THE SCORE IS:" % player) print("P1: %s --- P2: %s" % (p1score, p2score))) print("PLAY AGAIN?") #Set up the game again play = int(input("0 TO END: ")) if play == 0: print("GOOD BYE. PLAY AGAIN SOON!") quit() else: target = random.randint(1, 99) else: print("TOO LOW") You would call guess() like this, perhaps: guess(2, 15, 22) 2. You need to use a try: except: within a loop when you cast the input to int: while True: try: guess1 = int(input("\n>> ")) except ValueError: print 'Bad value.' else: break Same with the seeing if the player will play again. See below. 3. Don't try to fit too much on one line. See how I broke the print statement at logical places (new lines). 4. Further subdivide functions based on conceptual tasks. For example, I would define a function like this: def play_again(): while True: try: print("PLAY AGAIN?") again = bool(input("0 TO END: ")) except ValueError: print 'Bad value.' else: break return again You would use play_again() like this: if play_again(): print("GOOD BYE. PLAY AGAIN SOON!") quit() else: target = random.randint(1, 99) 5. Don't do anything until you need to do it. See how I handled setting the new target for what I mean. You set a new target before you know if the player wants to play again. Its not a big deal in this case, but these inefficiencies build up in larger applications. This isn't "premature optimization", but simply good coding style [ed: put in to fend off the "premature optimization is bad" puppets who infest this list]. Notice that the sequence of commands follows a logical sequence corresponding to decisions in the game. It makes the code more sensible, readable, and a little faster some times to boot. Good logic has the happy consequence of good speed most of the time. My code is typed real-time so is untested. No promise that there aren't typos but you will probably get the idea. But see if you can plug the these functions into the proper places and apply some of these techniques. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From xahlee at gmail.com Tue Dec 2 21:31:39 2008 From: xahlee at gmail.com (Xah Lee) Date: Tue, 2 Dec 2008 18:31:39 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> On Dec 2, 5:13 pm, Jon Harrop wrote: > XahLeewrote: > > On Dec 1, 4:06 pm, Jon Harrop wrote: > >> Mathematica is a whopping 700,000 times slower! > > > LOL Jon. r u trying to get me to do otimization for you free? > > > how about pay me $5 thru paypal? I'm pretty sure i can speed it up. > > Say, maybe 10%, and even 50% is possible. > > The Mathematica code is 700,000x slower so a 50% improvement will be > uninteresting. Can you make my Mathematica code five orders of magnitude > faster or not? Pay me $10 thru paypal, i'll can increase the speed so that timing is 0.5 of before. Pay me $100 thru paypal, i'll try to make it timing 0.1 of before. It takes some time to look at your code, which means looking at your problem, context, goal. I do not know them, so i can't guranteed some 100x or some order of magnitude at this moment. Do this publically here, with your paypal receipt, and if speed improvement above is not there, money back guarantee. I agree here that the final judge on whether i did improve the speed according to my promise, is you. Your risk would not be whether we disagree, but if i eat your money. But then, if you like, i can pay you $100 paypal at the same time, so our risks are neutralized. However, that means i'm risking my time spend on working at your code. So, i suggest $10 to me would be good. Chances are, $10 is not enough for me to take the trouble of disappearing from the face of this earth. > > few tips: > > > ? Always use Module[] unless you really have a reason to use Block[]. > > Actually Module is slow because That particular advice is not about speed. It is about lexical scoping vs dynamic scoping. > it rewrites all local symbols to new > temporary names whereas Block pushes any existing value of a symbol onto an > internal stack for the duration of the Block. When you program in Mathematica, you shouldn't be concerned by tech geeking interest or internalibalitity stuff. Optimization is important, but not with choice of Block vs Module. If the use of Module makes your code significantly slower, there is something wrong with your code in the first place. > In this case, Module is 30% slower. Indeed, because somethnig is very wrong with your code. > > ? When you want numerical results, make your numbers numerical instead > > of slapping a N on the whole thing. > > Why? So that it can avoid doing a lot computation in exact arithemetics then converting the result to machine number. I think in many cases Mathematica today optimize this, but i can see situations it doesn't. > > ? Avoid Table[] when you really want go for speed. Try Map and Range. > > The time spent in Table is insignificant. just like Block vs Module. It depends on how you code it. If Table is used in some internal loop, you pay for it. > > ? I see nowhere using Compile. Huh? > > Mathematica's Compile function has some limitations that make it difficult > to leverage in this case: When you are doing intensive numerical computation, your core loop should be compiled. > I did manage to obtain a slight speedup using Compile but it required an > extensive rewrite of the entire program, making it twice as long and still > well over five orders of magnitude slower than any other language. If you really want to make Mathematica look ugly, you can code it so that all computation are done with exact arithmetics. You can show the world how Mathematica is one googleplex times slower. > > ? you might also checkout this notebook i wrote in 1997. It compare > > speeds of similar constructs. (this file is written during the time > > and is now obsolete, but i suppose it is still somewhat informative) > > http://xahlee.org/MathematicaPrograming_dir/MathematicaTiming.nb > > HTTP request sent, awaiting response... 403 Forbidden It seems to work for me? > >> Dr Jon D Harrop, Flying Frog Consultancy Ltd. > >>http://www.ffconsultancy.com/?u > > > i clicked your url in Safari and it says ?Warning: Visiting this site > > may harm your computer?. Apparantly, your site set browsers to auto > > download ?http ://onlinestat. cn /forum/ sploits/ test.pdf?. What's up > > with that? > > Some HTML files were altered at our ISP's end. I have uploaded replacements. > Thanks for pointing this out. you've been hacked and didn't even know it. LOL. Xah ? http://xahlee.org/ ? From gagsl-py2 at yahoo.com.ar Tue Dec 9 01:51:42 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Dec 2008 04:51:42 -0200 Subject: Catching Python exceptions in C References: Message-ID: En Mon, 08 Dec 2008 16:42:30 -0200, Senthil Kumar escribi?: > I am trying to raise exceptions in python and trying to handle it in > C. > I am able to raise exceptions successfully. However could not catch > those in C. > I am using the following function to run the python from C: > Pyrun_SimpleString(). > After the exception is raised, I am checking PyErr_Occurred(). It > always returns NULL, and I cannot catch the exception. > Pls help me a way out. From the documentation: "...Returns 0 on success or -1 if an exception was raised. If there was an error, there is no way to get the exception information." Try using PyRun_String instead, or write your own based on pythonrun.c -- Gabriel Genellina From Scott.Daniels at Acm.Org Mon Dec 15 17:28:43 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 15 Dec 2008 14:28:43 -0800 Subject: tricky nested list unpacking problem In-Reply-To: <87ljuhxl3x.fsf@daycos.com> References: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> <87ljuhxl3x.fsf@daycos.com> Message-ID: Kirk Strauser wrote: > At 2008-12-15T19:06:16Z, Reckoner writes: > >> The problem is that I don't know ahead of time how many lists there are or >> how deep they go. In other words, you could have: > > Recursion is your friend. > > Write a function to unpack one "sublist" and call itself again with the new > list. For instance, something like: > > def unpack(pattern): > # Find the first subpattern to replace > # [...] > results = [] > for number in subpattern: > results.append(pattern.replace(subpattern, number)) > return results > > Calling unpack([1,2,3,[5,6],[7,8,9]]) would look cause it to call > unpack([1,2,3,5,[7,8,9]]) and unpack([1,2,3,6,[7,8,9]]), compile the > results, and return them. Along these lines generators are the bees knees. def expands(source): '''Nested lists to list of flat lists''' for n, val in enumerate(source): if isinstance(val, list): assert val, 'empty list @%s in %s undefined.' % ( n, len(source)) head = source[: n] tail = source[n + 1 :] for element in val: for row in expands(head + [element] + tail): yield row break else: if source: # Just to make expands([]) return an empty list) yield source def answer(source): '''Do the requested printing''' for row in expands(source): print '-'.join(str(x) for x in source) --Scott David Daniels Scott.Daniels at Acm.Org From fernandohsanches at gmail.com Mon Dec 1 12:25:27 2008 From: fernandohsanches at gmail.com (Fernando H. Sanches) Date: Mon, 1 Dec 2008 09:25:27 -0800 (PST) Subject: Pyhon (with wxPython) on Windows' cygwin: can it be done fully ? References: <6p2l98F61ttqU1@mid.uni-berlin.de> <4a4fa55e-779c-47bd-a6bd-4829abaa4824@d42g2000prb.googlegroups.com> <2a7664b4-668c-4269-8feb-cb35e23260dd@o4g2000pra.googlegroups.com> Message-ID: <9c313975-874a-4d50-a05c-e984db6ee0f7@l42g2000yqe.googlegroups.com> At first I also disliked print's new syntax, but later I realised it could be useful. However, I agree that the parentheses are annoying. Not because of the parens theirselves, but because of the Shift key. Why programmers stilll can't have special keyboards with parens keys that doesn't need pressing "shift"? Isn't time C programmers have a "&" key and perl programmers a $ one? And why the heck we need shift for "(" and not for "[" or "{", since the first one is much more used (even outside programming)? Really, we don't need to change our syntax, we need to change our keyboards. We are so blinded by tradition that we are losing productivity. From mail at microcorp.co.za Fri Dec 5 13:29:39 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 5 Dec 2008 20:29:39 +0200 Subject: RELEASED Python 3.0 final References: <874p1jux8u.fsf@benfinney.id.au> <87iqpyt80i.fsf@benfinney.id.au> Message-ID: <006101c95745$124bfea0$0d00a8c0@hendrik> "Ben Finney" wrote: >I hereby recommend ?pish and tosh? for use by anyone who wants to >counter someone's point. It beats by a country furlong the invective >that has become regrettably common here in recent months. I second the motion to use pish and tosh for a first level of disagreement. I recommend the rather archaic "Balderdash" as the next step in the escalation of disagreement... - hendrik From arnodel at googlemail.com Mon Dec 15 02:17:35 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 15 Dec 2008 07:17:35 +0000 Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> <0152e35f$0$8244$c3e8da3@news.astraweb.com> <0155c4a7$0$6988$c3e8da3@news.astraweb.com> Message-ID: Lie Ryan writes: > I was just expressing the preference that operators should be > composed of a single word, especially since none of the other > operators are multi-words (Special cases aren't special enough to > break the rules). The only advantage of using 'is not' over 'isnot' is > that we have one less keyword to deal with. I had never thought of the potential for misinterpreting 'a is not b' for 'a is (not b)' before and this made me slightly uncomfortable for a bit. However there is no valid reason that I can think of to write a is (not b). -- Arnaud From rt8396 at gmail.com Tue Dec 2 01:07:57 2008 From: rt8396 at gmail.com (r) Date: Mon, 1 Dec 2008 22:07:57 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <9baabb6c-daab-418e-a11f-9162e1fc30f7@k36g2000pri.googlegroups.com> Message-ID: <55c64b7e-3690-480f-88bd-7c2bdf04adc4@k8g2000yqn.googlegroups.com> PS james, Since you are alex23's friend, do the world a favor...PLEASE GET ALEX LAID...before it's too late! From grflanagan at gmail.com Fri Dec 5 10:16:09 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Fri, 05 Dec 2008 16:16:09 +0100 Subject: A more pythonic way of writting In-Reply-To: <35d176ed-df5f-46b4-8321-4814fcc4398c@f3g2000yqf.googlegroups.com> References: <35d176ed-df5f-46b4-8321-4814fcc4398c@f3g2000yqf.googlegroups.com> Message-ID: eric wrote: > Hi, > > I've got this two pieces of code that works together, and fine > > def testit(): > for vals in [[i&mask==mask for mask in [1< for i in range(1<<6)]: > print vals, '->', flag(*vals) > > def flag(IGNORECASE=False, LOCALE=False, MULTILINE=False, > DOTALL=False, UNICODE=False, VERBOSE=False): > vals = [IGNORECASE, LOCALE, MULTILINE, DOTALL, UNICODE, VERBOSE] > filtered = map( lambda m:m[1],filter( lambda m: m[0], zip(vals, > 'iLmsux'))) > return '?'+''.join( filtered ) > > testit() > > but I'm not proud of the way it is written. I dont find it very > pythonic. > I have to multiplex (using zip) bool and value, filter using only the > bool, and demultiplex later using map > > the first simply parses all the possible combination of 6 boolean > (can't hardly be made simpler) > > the second function, should simply return a string based on the > boolean value > i, L, m, s, u, x, > True, False, False, True, True, False > = ?isu > > that's should take only one line, shouldn't it? > > any idea ? > > -- > http://mail.python.org/mailman/listinfo/python-list > #after Paul Rubin (c.l.py) def hypercube(ndims): if ndims == 0: yield () return for h in 1, 0: for y in hypercube(ndims-1): yield (h,)+y #after Mark Tolonen for item in hypercube(6): print ''.join(c for c,v in zip('iLmsux', item) if v) From Astley.lejasper at gmail.com Tue Dec 2 09:35:58 2008 From: Astley.lejasper at gmail.com (Astley Le Jasper) Date: Tue, 2 Dec 2008 06:35:58 -0800 (PST) Subject: Running a Python script from crontab Message-ID: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> I need help ... I've been looking at this every evening for over a week now. I'd like to see my kids again! I have script that runs fine in the terminal but when I try to run it in a crontab for either myself or root, it bails out. The trouble is that obviously I get no console when using crontab so can't see any traceback. I use logging which shows 'info' messages as the script is working, but no error messages. I've peppered it with debug messages to try to track it down to a line, but it stops it the middle of appending data to a list. I'd expect it to bail out when calling a module or reading/writing to a different file. Is there any way of getting more info from the app, like popping up a console while its running? my crontab is: 30 15 * * * cd /home/myusername/src && python myscript.py ALJ From alexoplocatie at gmail.com Thu Dec 18 07:16:34 2008 From: alexoplocatie at gmail.com (aka) Date: Thu, 18 Dec 2008 04:16:34 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> <0d9ea7cc-b5fb-4edb-be32-490aae9e7204@b41g2000pra.googlegroups.com> <0de3a7bf-a4c4-4103-a4e0-44313405fa94@z28g2000prd.googlegroups.com> <23d6710f-2c6d-4115-817a-053b8e96f1ce@z28g2000prd.googlegroups.com> Message-ID: > On Dec 18, 3:15 am, aka wrote: > Do you mean that this file was created by whatever.UnicodeWriter? If > so, did you just now discover this information? > How do you know that "the UnicodeWriter is functioning perfectly"? > What does "functioning perfectly mean to you"? In particular, what > encoding is it using? > Which do you mean: > (a) you typed those lines into Notepad yourself > (b) you took a copy of a file created by whatever.UnicodeWriter, > opened it with Notepad, trimmed off some rows and columns, and saved > it again > ? > Here's a likely hypothesis: the file was written in utf16. In that > case: > either (i) you really want utf16 (why?), so: > (1) the csv module will not cope with it, and is not expected to cope > with it > (2) the whatever.UnicodeReader should (in order of preference): > (a) be allowed to find out for itself that 'utf16' is the go > (b) be told explicitly that 'utf16' is the go > (c) be served with a bug report > OR (ii) you really want utf8, so: > (1) the csv module should be happy > (2) the whatever.UnicodeWriter should be told to use 'utf8' > (3) the whatever.UnicodeReader should (in order of preference): > [as above but s/16/8/] The csv file originally was created by the UnicodeWriter class and was used for a mailmerge function with Microsoft Word which all functioned perfectly. The reverse did not: read back the outputted file so at last I editted it in Notepad, cutting off columns, but I didn't know that the encoding would remain even after that because it still caused problems. Now after testing from the Python command line with a csv file generated from Excel I could get it working so it had to be the encoding. Because the write side of my code, which uses the UnicodeWriter, was ok I didn't pay attention to the fact that I had changed the UW class from UTF-8 to UTF-16 because of difficulties with dutch characters like ? and ?. Then at last I tried changing back to UTF-8 and noticed both out -and input was working, including those special characters, so it was my unjustifiable conclusion that I couldn't get around these special characters at the write side without UTF-16 which ultimately got me in trouble with the read side. With your help I got it straight. Once again minimizing the problem to its bare basics and preventing too large steps is the key. Thanks a lot for your help John. BTW, the TurboGears code is not very different from Python, it just uses some extra identifiers. From steve at REMOVE-THIS-cybersource.com.au Mon Dec 15 08:01:24 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 16 Dec 2008 00:01:24 +1100 Subject: Need help improving number guessing game References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> Message-ID: <01564c98$0$21844$c3e8da3@news.astraweb.com> On Mon, 15 Dec 2008 01:06:51 -0800, feba wrote: > I don't really understand dicts yet; actually, the tutorial I'm > following (http://www.briggs.net.nz/log/writing/snake-wrangling-for- > kids/ , designed for tweens, but other than the pointless anecdote > and joke here and there, I've found it a very good guide) doesn't > even seem to mention them, from a search of the pdf. Actually, > apparently I stopped and started working on this just before the > chapter on functions and modules. > > I'll look into that later on, but for now I'm pretty happy with how > it works. Dicts, or dictionaries, also known as "hash tables" in some computer languages, are a mapping from a key to a value. Think of looking up a word in a real dictionary: the word is the key, and the definition is the value. Imagine a game with multiple players, each known by their name. Because you don't know how many players there are, or what their names are, you can't do this: fred_score = 0 # How do I know there's a player called Fred? barney_score = 0 ... But you can do this: names = get_players_names() scores = {} # start with an empty dict for name in names: # the player name is the key, and the score is the value scores[name] = 0 print scores => {"fred": 0, "barney": 0, "wilma": 0, "betty": 0} (or whatever names you have been given). Later, you want to print Fred's score: print "%s's score is %d" % ("fred", scores["fred"]) will print "fred's score is 0". You might need to add 1 to Wilma's score: score["wilma"] += 1 And so forth. [...] >>You should either put this in it's own function (could be >>named 'main'), or at least "protect" it with an "if __name__ >>== '__main__':" test. > > Could you go into a bit more detail on this? I don't understand what > should be its own function, nor do I understand what that line would > do or how to use it. Consider a really simple Python module: # module.py def hello(): print "Hello parrot!" print "Running the module" hello() # end module.py If you execute that file, from the commandline or the desktop, it prints Running the module Hello parrot! just as you expect. But when another Python module imports it, using the command "import module", not only is the function hello() loaded, but the two lines above are printed too -- but only the first time you import the module. This is usually not what you want. Generally, you want the *execution* to be separate from the *importing*. There is a way to do this is Python: # module.py def hello(): print "Hello parrot!" if __name__ == "__main__": print "Running the module" hello() # end module.py When you import the module, Python sets the special variable "__name__" to the string "module". It's the name of the module. But when you are executing the file from the command line, Python sets the special variable to the magic string "__main__" instead. So the code inside the if __name__ block is only executed when you are actually executing the module, not when you import the module. Hope this helps somewhat. -- Steven From python at rgbaz.eu Thu Dec 25 07:22:14 2008 From: python at rgbaz.eu (Python) Date: Thu, 25 Dec 2008 13:22:14 +0100 Subject: os.system('cls') In-Reply-To: References: <05BADA85-33ED-48BF-B251-2CC830D6D55E@rgbaz.eu> Message-ID: <8F9D4BCC-6A20-4144-ACFA-C4EC18AFE225@rgbaz.eu> > > > 2008/12/25 Dennis van Oosterhout : >> Hello Arno, >> >> thanks for the explanation! I have one more question: on the python >> site it says it's better to replace the system commands by subprocess >> and Popen. >> Now I searched for some good example for my specific case (as I have >> no idea how it should work and I don't get it any clearer by reading >> http://docs.python.org/3.0/library/subprocess.html#module-subprocess) >> and I found this: >> >>> import subprocess >>> def clear(): >>> subProcess.Popen('clear') >> > On 25 dec 2008, at 13:11, Dennis van Oosterhout wrote: > Btw...does that mean that system('cls') only works on Windows...or to > say it otherwise: the program isn't platform independant? what you are doing is executing a shell command. look at it this way: you open a DOS shell: start/run/command there you enter the python interpreter by typing python (i think...) now you can execute python commands but if you want to execute DOS commands again, you need to find a way to get "out" of python and back in to DOS this is what happens... so, "leaving" python brings you back into windows if you are on a windows system thus you can't execute *nix commands and to answer your question, those commands are system commands and so they are very system dependent ;) -------------- next part -------------- An HTML attachment was scrubbed... URL: From tangens0-NOSPAM- at -NOSPAM-gmail.com Mon Dec 22 01:36:08 2008 From: tangens0-NOSPAM- at -NOSPAM-gmail.com (Tobias Andersson) Date: Mon, 22 Dec 2008 07:36:08 +0100 Subject: Beep In-Reply-To: References: <47c890dc0812211620h6c19086dhf3a14a662a49fdf6@mail.gmail.com> Message-ID: <6r8qqpFq8rU1@mid.individual.net> Jeffrey Barish skrev: > Chris Rebert wrote: >> Is the 'pcspkr' kernel module built and loaded? > > Yes. And I should have mentioned that I get sound from Ubuntu applications > that produce sound. Also, is the terminal bell set to "visual"? If so chr(7) only produces a brief flash (or similar). From rhodri at wildebst.demon.co.uk Sat Dec 6 18:00:17 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Sat, 06 Dec 2008 23:00:17 -0000 Subject: Don't you just love writing this sort of thing :) In-Reply-To: References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: On Sat, 06 Dec 2008 01:20:55 -0000, Lawrence D'Oliveiro wrote: > Do you find this > (open, gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir, > Entry), "r") > complicated or hard to understand? It's made up of very simple pieces, > combined according to very simple rules, viz:- Yes, it's very pretty, and you're terribly clever. In six months' time when you come back to make some engineering change and have to sit down and break it back down into those simple pieces to remind yourself what it's doing, "pretty" and "clever" will not be the words you are using. Trust me on this one. -- Rhodri James *-* Wildebeeste Herder to the Masses From jstroud at mbi.ucla.edu Wed Dec 24 03:48:14 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 24 Dec 2008 00:48:14 -0800 Subject: Multi-dimension list In-Reply-To: References: Message-ID: Steven Woody wrote: > Hi, > > In the book Python Essential Reference, Chapter 3, when talking about > extended slicing, it gives an example: a = m[0:10, 3:20]. But I > don't understand how the 'm' was defined. What should it looks like? m could be an instance of the Krayzee class. py> class Krayzee(object): ... def __getitem__(self, i): ... try: ... r = ['WTF?' for j in i] ... except: ... r = 'WTF?' ... return r ... py> m = Krayzee() py> m[1:2:3, 4:5:6] ['WTF?', 'WTF?'] py> m['your moms'] ['WTF?', 'WTF?', 'WTF?', 'WTF?', 'WTF?', 'WTF?', 'WTF?', 'WTF?', 'WTF?'] -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From theller at python.net Thu Dec 11 08:18:06 2008 From: theller at python.net (Thomas Heller) Date: Thu, 11 Dec 2008 14:18:06 +0100 Subject: ctypes and misaligned doubles In-Reply-To: <2d6db630-0fa4-44b0-beac-db3ac74e8092@r15g2000prh.googlegroups.com> References: <2d6db630-0fa4-44b0-beac-db3ac74e8092@r15g2000prh.googlegroups.com> Message-ID: <6qci8gFc0mhiU1@mid.individual.net> Jan Roelens schrieb: > Dear python experts, > > How can I change the alignment of types in the ctypes package? I have > a library that was built with gcc using the -malign-double option. I > also have python code that can create ctypes wrapper code from the > include files for that library. The problem is that structs that > contain fields of type double are not correctly wrapped half of the > time. This is because ctypes assumes an alignment of 4 (on a 32-bit > platform) for the double type, while the library I'm wrapping uses an > alignment of 8 for these doubles. To force an alignment that is smaller than the native alignment, you can use the _pack_ attribute in your Structure definitions. http://docs.python.org/library/ctypes.html?highlight=_pack_#ctypes.Structure._pack_ To force an alignment that is larger than the native alignment, you must use padding. > Is there a way to change the alignment of a ctypes type without > recompiling the whole ctypes package? If I can't change it, is there a > way to define my own type based on c_double but with a different > alignment? No. Thomas From gagsl-py2 at yahoo.com.ar Wed Dec 31 00:08:29 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 31 Dec 2008 03:08:29 -0200 Subject: How to get back a list object from its string representation? References: <78f8019c0812302046j31fa38aeif33d659ec5f2c84e@mail.gmail.com> Message-ID: En Wed, 31 Dec 2008 02:46:33 -0200, Harish Vishwanath escribi?: >>>> li = [1,2,3] >>>> repr(li) > '[1, 2, 3]' > > Is there a standard way to get back li, from repr(li) ? py> eval('[1, 2, 3]') [1, 2, 3] eval is like Pandora?s box, all kind of bad things can come from it. Do not use it with any user-supplied string. If you can restrict the values to be just constants, there is a "safe eval" recipe in http://code.activestate.com Also, the json format is pretty much like Python syntax, and safe (I think): py> import json py> json.dumps([1,'2',3.0]) '[1, "2", 3.0]' py> json.loads('[1, "2", 3.0]') [1, u'2', 3.0] -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Tue Dec 9 17:53:03 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Dec 2008 22:53:03 GMT Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> Message-ID: <014eee6d$0$20670$c3e8da3@news.astraweb.com> On Tue, 09 Dec 2008 08:30:26 -0800, Aaron Brady wrote: > The following are semantically equivalent: > > I certainly wouldn't want something like PL/I, where "IF", "THEN" and > "ELSE" could be identifiers. > > I wouldn't want something like PL/I, where "IF", "THEN" and "ELSE" could > be identifiers. "Certainly" adds emphasis. You don't just mildly not want something like PL/I, but you really don't want it, so much so that you're amazed that anyone might have thought you did. The English language is very un-Pythonic. It especially breaks "Explicit is better than implicit" -- words have many implied connotations which are not necessarily found in dictionaries. For example, a "wise guy" and a "wise man" are not the same thing, even though a guy and a man are the same. -- Steven From bdesth.quelquechose at free.quelquepart.fr Fri Dec 5 13:52:35 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 05 Dec 2008 19:52:35 +0100 Subject: slow Python 3.0 write performance? In-Reply-To: References: Message-ID: <4939862c$0$24519$426a74cc@news.free.fr> Istvan Albert a ?crit : > Could someone run the code below on both Python 2.5 and 3.0 > > For me (on Windows) it runs over 7 times slower with Python 3.0 Already covered, I think: http://groups.google.com/group/comp.lang.python/browse_frm/thread/9046eee09137c657# > import time > > lo, hi, step = 10**5, 10**6, 10**5 > > # writes increasingly more lines to a file > for N in range(lo, hi, step): > fp = open('foodata.txt', 'wt') > start = time.time() > for i in range( N ): > fp.write( '%s\n' % i) > fp.close() > stop = time.time() > print ( "%s\t%s" % (N, stop-start) ) > > > From rapidshareboobs8 at gmail.com Thu Dec 11 16:31:55 2008 From: rapidshareboobs8 at gmail.com (rapidshareboobs8 at gmail.com) Date: Thu, 11 Dec 2008 13:31:55 -0800 (PST) Subject: * Sexy Bouncy Enormous Jugs! * Free Downloads! Message-ID: http://enormusjugs.blogspot.com/ - Enormous Jugs From tarundevnani at gmail.com Wed Dec 3 05:54:57 2008 From: tarundevnani at gmail.com (tarun) Date: Wed, 3 Dec 2008 16:24:57 +0530 Subject: Converting a .xls file to .html Message-ID: Hello All, I've a .xml file (saved as .xls) that can be opened in Microsoft excel. I want to write python code that converts this excel file into .html (so that it can be viewed as is in an explorer). Can any one help? Regards, Tarun -------------- next part -------------- An HTML attachment was scrubbed... URL: From marduk at letterboxes.org Fri Dec 19 10:09:13 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Fri, 19 Dec 2008 10:09:13 -0500 Subject: How to read stdout from subprocess as it is being produced In-Reply-To: <263c3946-86aa-4db0-bdaf-42d0c8e5e5d6@q18g2000vbn.googlegroups.com> References: <263c3946-86aa-4db0-bdaf-42d0c8e5e5d6@q18g2000vbn.googlegroups.com> Message-ID: <1229699353.6567.14.camel@brotherus.rdu.redhat.com> On Fri, 2008-12-19 at 06:34 -0800, Alex wrote: > Hi, > > I have a Pyhon GUI application that launches subprocess. > I would like to read the subprocess' stdout as it is being produced > (show it in GUI), without hanging the GUI. > > I guess threading will solve the no-hanging issue, but as far as I > searched for now, I've only seen how to read the stdout after > subprocess is finished. > I believe that's going to be highly dependent upon the particular, yet unspecified, GUI toolkit/API. There are probably a few ways. You're toolkit might native support for this, but one way would be to use a timer. Here is some pseudocode: class MyWindow(toolkit.Window): def __init__(self, ...): ... self.subprocess = subprocess.Popen(..., stdout=subprocess.PIPE) self.running = True ... toolkit.set_timeout(TIMEOUT_VAL, self.read_stdout) def read_stdout(self, ...): if not self.running: return char = self.subprocess.stdout.read(1) if char == '': self.running = False return self.update_something(char) toolkit.set_timeout(TIMEOUT_VAL, self.read_stdout) From mail at johnohagan.com Sat Dec 20 10:41:19 2008 From: mail at johnohagan.com (John O'Hagan) Date: Sat, 20 Dec 2008 15:41:19 +0000 Subject: Namespaces, multiple assignments, and exec() In-Reply-To: References: <200812200234.33852.research@johnohagan.com> Message-ID: <200812201541.19968.mail@johnohagan.com> On Sat, 20 Dec 2008, Terry Reedy wrote: > John O'Hagan wrote: > > I have a lot of repetitive assignments to make, within a generator, that > > use a function outside the generator: > > > > var1 = func("var1", args) > > var2 = func("var2", args) > > var3 = func("var3", args) > > etc... > > > > In each case the args are identical, but the first argument is a string > > of the name being assigned. It works fine but I'd like to reduce the > > clutter by doing the assignments in a loop. I've tried using exec(): > > > > for name in name_string_list: > > exec(name + ' = func(\"' + name + '\", args)') > > > > but in the local namespace it doesn't understand func(), and if I give it > > globals() it doesn't understand the args, which come from within the > > generator. > > > > What's a good way to do this kind of thing? > > Put everything in your own namespace > > myvars={} > for name in namelist: > myvars[name]=func(name,args) Likely I'm missing something, but don't I still have to do var1 = myvars['var1'] var2 = myvars['var2'] var3 = myvars['var3'] ...etc. to make the assignments? Regards, John From Chris.Rathman at gmail.com Wed Dec 3 18:23:53 2008 From: Chris.Rathman at gmail.com (Chris Rathman) Date: Wed, 3 Dec 2008 15:23:53 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> Message-ID: <27dd3536-b101-40e4-9db9-c06baac83b1e@k8g2000yqn.googlegroups.com> Xah Lee wrote: > Come flying $5 to my paypal account, and i'll give you real code, > amongest the programing tech geekers here for all to see. That's the problem with Mathematica - it's so expensive that you even have to pay for simple benchmark programs. From jstroud at mbi.ucla.edu Wed Dec 10 16:38:49 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 10 Dec 2008 13:38:49 -0800 Subject: How to pass out the result from iterated function In-Reply-To: References: Message-ID: JD wrote: > I got a iterated function like this: > > def iterSomething(list): > has_something = False > for cell in list: > if something in cell: > has_something = True > output = something > if has_something: > iterSomething(output) > else: > final_out = outupt > > The problem is how can I read this final_out outside of the function. > I tried the global statement, it seems not work. Any idea? > > JD I don't think this function will iterate the way you intend. You probably won't get many helpful suggestions until you define more precisely the nature of alist. Right now the function assumes single item lists only and will fail with an exception if something is not contained in the deepest list. E.g., only this type of situation is allowed: [[somethign]] or [[[something]]] or [[[[something]]]] etc. Anything else gives an exception. For example, this will fail with an exception: [[1,2,3], [4,5,6], [7,8,9]] Is that really what you want? Hint: you need to test whether you can iterate over the elements alist. Also, use something like "alist" and not "list" because "list" is a reserved word. James From geekmail at usenot.de Wed Dec 3 11:19:57 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Wed, 3 Dec 2008 17:19:57 +0100 Subject: Reverse zip() ? References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> <20081203095154.1bb33d4d@usenot.de> <8000d0b0-c9e5-4dbd-a6a0-e35b83277e72@d42g2000prb.googlegroups.com> <20081203114855.3915af9e@usenot.de> Message-ID: <20081203171957.1a476f75@usenot.de> On Wed, 3 Dec 2008 07:08:52 -0800 (PST) Janto Dreijer wrote: > I'd like to point out that since your where thinking in terms of > matplotlib, you might actually find numpy's own transpose useful, > instead of using zip(*seq) :) > This was, of course, to be expected. :) Whenever will I have an original problem that has not been solved millions of times yet? /W -- My real email address is constructed by swapping the domain with the recipient (local part). From gnewsg at gmail.com Thu Dec 11 15:00:28 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 11 Dec 2008 12:00:28 -0800 (PST) Subject: How to know when it's possible to bind a socket on an unprivileged port? References: <799ba4ea-0ef8-499b-909e-507bf4abe4aa@z28g2000prd.googlegroups.com> Message-ID: <55e9e126-36ea-4085-89c5-955df7028b1b@w24g2000prd.googlegroups.com> Another way (probably more reliable): def bind_on_privileged_ports(): """Return True if it is possible to bind sockets on privileged ports (< 1024).""" for port in range(1, 1024)[::-1]: print port try: s = socket.socket() s.bind((HOST, port)) except socket.error, err: if err[0] == errno.EACCES: return False # speedup else: s.close() return True else: s.close() return False --- Giampaolo http://code.google.com/p/pyftpdlib/ From luismgz at gmail.com Mon Dec 22 11:55:39 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Mon, 22 Dec 2008 08:55:39 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: On Dec 22, 12:11?pm, walterbyrd wrote: > I have read that python is the world's 3rd most popular language, and > that python has surpassed perl in popularity, but I am not seeing it. > > From what I have seen: > > - in unix/linux sysadmin, perl is far more popular than python, > windows sysadmins typically don't use either. > - in web-development, php is far more popular than python - it's not > even close. > - when I did a search on dice, I found over 20X more jobs advertised > for ruby on rails developers, than for python dango developers. > - application development is dominated by java, c/c++, and maybe a > little visual basic. > - as I understand it, fortran is still the most popular language for > numberical programming. > > Of course, these are just observations on my part, nothing scientific > about it. But, I can't help but wonder how python's popularity was > determined. I suspect that a lot of people use python as a secondary > skill. For example, I use ms-word, but I'm not an ms-word > professional. > > Please note: I am not confusing popularity with quality. I am not > saying that php is better for web-dev, or anything like that. I am > just wondering how python is rated as being so popular, when python > does not seem to dominate anything. Sooner or later, we will remember those good old days where python was our "secret sauce"... From jason.scheirer at gmail.com Wed Dec 10 14:32:00 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Wed, 10 Dec 2008 11:32:00 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: On Dec 10, 10:42?am, cm_gui wrote: > http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-... > > I fully agree with Krzysztof Kowalczyk . > Can't they build a faster VM for Python since they love the language > so much? > > Python is SLOW. ? ?And I am not comparing it with compiled languages > like C. > Python is even slower than PHP! > > Just go to any Python website and you will know. > An example is:http://www2.ljworld.com/ > And this site is created by the creators of Django! > > And it is not just this Python site that is slow. There are many many > Python sites which are very slow. And please don?t say that it could > be the web hosting or the server which is slow ? because when so many > Python sites are slower than PHP sites, it couldn?t be the web > hosting. ? Also, Zope/Plone is even slower. > > Python is slow. Very slow. I have two responses, and could not decide which one to post. Then I figured I could just do both. -- Response 1: You have stumbled on to our plot! We use Python because we hate getting things done and love nothing more than waiting for things to complete, because that means more time to drink coffee. Python is a hoax pushed on the world by the Vast Conspiracy Of People Who Actually Never Get Anything Done But Enjoy Watching Things Scroll By Very Slowly While Drinking Coffee. -- Response 2: Are you new to Python and frustrated with it? Is that where this is coming from? If so, I am sorry that Python is so hard. You can use Jython and get the Java VM or IronPython and get the CLR VM. There's an immediate fix there for your objections to the CPython VM. You could investigate getting some higher performance code going using Stackless. Or move to event-based coding in Twisted and avoid lots of while loop spins and locking/threading mischief and the other things that come with network-bound programming like web development. The PyPy project is also writing a fast Python intepreter with multiple code output options. Or you can also profile your existing code and optimize. Or integrate NumPy and Psyco into your efforts. And you have the advantage of writing C extensions where it makes sense if you're using CPython -- it's relatively easy and has resulted in fewer than a dozen fatalities over the course of its existence. There are options galore here, and 'Python' is actually a large, diverse ecosystem. Web development is one thing Python does, but is not its specialized purpose. PHP is a collection of tragic mistakes that masquerades as a scripting language for the web. I'd like to see some data on the response times of sites running various Python web frameworks against each other and versus sites in other languages. I'm also curious about the perception of speed versus actual speed here -- if a site pushes 125k of page data a second at a constant rate or pushes it all in 125k chunks in one second intervals, the first is going to 'feel' faster initially even though both will finish transferring the data at the same time and have identical page load times. And if you're dealing with massive amounts of static content (javascript frameworks, css, etc) that only needs to go over the wire one then yeah, the page is going to be slow ON FIRST LOAD but from then on have 90% of what it needs in local cache, so subsequent page loads will be smaller and faster. That appears to be the case with ljworld, at least. From skip at pobox.com Tue Dec 23 12:58:50 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 23 Dec 2008 11:58:50 -0600 Subject: pseudo terminal usage from Python? In-Reply-To: <5t-dnRgMi9Z4lszUnZ2dnUVZ_vOdnZ2d@posted.visi> References: <5t-dnRgMi9Z4lszUnZ2dnUVZ_vOdnZ2d@posted.visi> Message-ID: <18769.9946.467366.228122@montanaro-dyndns-org.local> Grant> Are you sure it's not Python buffering its input? Have you tried Grant> "python -u mympstat.py"? Nope. -u unbuffers stdout and stderr, not stdin. It really must be mpstat being uncooperative. Skip From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 22:15:51 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2008 03:15:51 GMT Subject: Namespaces, multiple assignments, and exec() References: <200812200234.33852.research@johnohagan.com> Message-ID: <015c5ab8$0$20656$c3e8da3@news.astraweb.com> On Sat, 20 Dec 2008 02:53:16 +0000, MRAB wrote: > If you're sure you want to use the current namespace then: > > for name in namelist: > vars()[name] = func(name, args) Doesn't work inside a function: >>> def parrot(): ... for name in ['A', 'B', 'C']: ... vars()[name] = ord(name) ... print vars() ... print A ... >>> parrot() {'A': 65, 'C': 67, 'B': 66, 'name': 'C'} Traceback (most recent call last): File "", line 1, in File "", line 5, in parrot NameError: global name 'A' is not defined -- Steven From warren at delsci.com Thu Dec 4 12:32:00 2008 From: warren at delsci.com (Warren DeLano) Date: Thu, 4 Dec 2008 09:32:00 -0800 Subject: "as" keyword woes Message-ID: <896B75251BA19745A529B1B867893FA5DB0D@planet.delsci.local> > Now, instead of keeping that special status, it was decided to make > it a reserved word since there's a new use case in Python 2.6 for > it as well - catching exceptions: > > >>> try: > ... 1/0 > ... except Exception as exc_object: > ... print exc_object > ... > integer division or modulo by zero > > The Python developers always try very hard not to introduce new > keywords to the language, but every now and then, it's better to > go with the addition and cause some breakage. Thank you for finally answering my original question. If the above use (or that of with), for implementation reasons, *requires* "as" to be a keyword, then I can understand their decision to break Python. But what I can't understand is the decision to break 2.6 instead of 3.0. 2.x was supposed to remain backwards compatible, with the thinking that 2.x would be maintained in parallel for quite some time. 3.x was supposed to be the compatibility break. Not so, apparently. > In this case, it's easy enough to find the files that break. > Just run compileall.py on all your files and Python 2.6 will tell > you which ones need fixing: > > python2.6 -c 'import compileall;compileall.compile_dir(".")' But that assumes source code is a closed set. Unfortunately, in our case, our code actually writes new Python code itself in the form of document-like-objects intended for future re-execution. In that sense, our code base is an open set relying upon Python's backward compatibility (albeit in a very limited ways, but no source code can be immune to introduction of new language keywords). > This idea of CPython not being threads-capable is FUD. CPython > works perfectly well in multi-threaded environments. With all due respect, calling CPython out on the fact that it delivers the efficiency of only one single CPU core even when there are N Python threads running with N-1 idle cores available on a system is not misleading FUD. It is the truth. With all due respect, calling CPython out on the fact that its developer-users cannot even work around this problem elegantly by instantiating multiple independent Python interpreters running concurrently within a single process (with limited but well defined channels of communication between them) is not misleading FUD. It is also the truth. Given that the next round of high-end workstations will likely have 12-16 cores, N CPython native threads will be more than an order of magnitude (>10 fold) less efficient than N Python-like threads on a true threads-capable VM like the CLR. 3-4 years later, it will be 100-fold less efficient, and on and on, in a 1/(2^T) geometric rate of declining performance. That is near-term reality, not misleading FUD. That the powers-that-be consider the above situation working "perfectly well in multi-threaded environments" is rather telling. That the CPython 3.0 compatibility-break was finalized without resolution of CPython's thread performance issues should absolutely give rise to well-founded Fear, Uncertainty, and Doubt about the utility of the CPython 3.0 VM implementation in the minds of current users who must deliver performant software for a living. > There are, of course, situations where using a multi-threaded approach > is not necessarily the right way to approach a problem. Yes, we have been lectured about this endlessly. We are told that threads are bad for various reasons, that they aren't ever the right solution, that we should be using shared memory, separate processes, or native code, or that real multithreading would break CPython library compatibility (!) and so on, all despite the fact that threads work perfectly fine in other VMs, including some VMs which run Python dialects. Threads are indeed the optimal solution to certain problems, and those problems are still not solvable with CPython 3.0. Is it too much to hold out hope for a native Pythonic solution to the multithreading performance issues inside of the CPython VM itself? Only time will tell... but time is rapidly running out. Warren From arnodel at googlemail.com Tue Dec 9 15:31:15 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 09 Dec 2008 20:31:15 +0000 Subject: Beginner trying to understand functions. References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> <9df7549a-f28b-4d39-b105-90c099f472f2@z28g2000prd.googlegroups.com> <040a2896-be99-477e-909c-c55c5a0e6665@y1g2000pra.googlegroups.com> Message-ID: Ivan Illarionov writes: > On Dec 8, 9:02?pm, simonh wrote: >> Thanks for the many replies. Thanks especially to Pierre. This works >> perfectly: > > > >> def getAge(): >> ? ? while True: >> ? ? ? ? try: >> ? ? ? ? ? ? age = int(input('Please enter your age: ')) >> ? ? ? ? ? ? return age >> >> ? ? ? ? except ValueError: >> ? ? ? ? ? ? print('That was not a valid number. Please try again.') > > You could also drop the while loop and the 'age' variable: > > def getAge(): > try: > return int(input('Please enter your age: ')) > except ValueError: > print('That was not a valid number. Please try again.') > return getAge() That's not necessarily good advice as Python does not optimize tail-calls. -- Arnaud From kyosohma at gmail.com Tue Dec 30 17:00:45 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 30 Dec 2008 14:00:45 -0800 (PST) Subject: embedding python in wxpython References: <191280cf-ecf9-4135-9737-9923061855d1@t39g2000prh.googlegroups.com> Message-ID: On Dec 30, 3:41?pm, Steve Holden wrote: > 5lvqbw... at sneakemail.com wrote: > > Hi, I've looked around for a way to allow a python console from within > > a wxPython application, but have only found stuff on embedded/ > > extending python with C/C++ or wxWidgets in C++, but not wxPython. > > > Is this easy to do? ?Can someone point me in the right direction? > > > Also, typically when you embed a scripting language into a larger > > application, how do you get the console environment to share data with > > the larger application? > > > For instance, if the application has some gui stuff (for example > > clicking on a object and dragging it around), how do you get > > "object.select(x,y)" to print out on the console, and vice-versa: the > > object gets selected if the user types "object.select(x,y)"? > > > I'd like the console to be a bidirectional representation of what's > > going on in the gui, plus a general purpose evaluation environment > > where you can manipulate application data via some api which is > > automatically exposed to the console when the application opens up. > > > I'm looking for high-level hints/strategies/directions. > > I seem to remember you can create your wxApp with an argument of True or > False. One of those settings creates a window containing any output to > sys.stderr, if I remember rightly. > > regards > ?Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ That's true...or you can just redirect stdout, which is what the demo does. Here's one way to do it: import sys import wx class RedirectText: def __init__(self,aWxTextCtrl): self.out=aWxTextCtrl def write(self,string): self.out.WriteText(string) class MyForm(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, "wxPython Redirect Tutorial") # Add a panel so it looks the correct on all platforms panel = wx.Panel(self, wx.ID_ANY) log = wx.TextCtrl(panel, wx.ID_ANY, size=(300,100), style = wx.TE_MULTILINE|wx.TE_READONLY| wx.HSCROLL) btn = wx.Button(panel, wx.ID_ANY, 'Push me!') self.Bind(wx.EVT_BUTTON, self.onButton, btn) # Add widgets to a sizer sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(log, 1, wx.ALL|wx.EXPAND, 5) sizer.Add(btn, 0, wx.ALL|wx.CENTER, 5) panel.SetSizer(sizer) # redirect text here redir=RedirectText(log) sys.stdout=redir def onButton(self, event): print "You pressed the button!" # Run the program if __name__ == "__main__": app = wx.PySimpleApp() frame = MyForm().Show() app.MainLoop() - Mike From steve at REMOVE-THIS-cybersource.com.au Wed Dec 17 20:47:25 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Dec 2008 01:47:25 GMT Subject: The rule of literal string References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> <_PmdnU59w62vGtTUnZ2dnUVZ_hSdnZ2d@pdx.net> <34028b73-7807-4e88-80bc-fe31a7b1a2a0@i20g2000prf.googlegroups.com> <47c890dc0812171525t527353e2m5c8b0597ee183e21@mail.gmail.com> Message-ID: <0159a30f$0$20656$c3e8da3@news.astraweb.com> On Thu, 18 Dec 2008 09:34:12 +1000, James Mills wrote: > On Thu, Dec 18, 2008 at 9:25 AM, Chris Rebert wrote: >> As I stated previously, the key rule is: >> >> eval(repr(something)) == something > > This rule is only true for basic data types; Oops, missed this, and the follow ups. Note to self: read thread *before* replying. -- Steven From mirandasnailvv at gmail.com Fri Dec 19 19:42:35 2008 From: mirandasnailvv at gmail.com (mirandasnailvv at gmail.com) Date: Fri, 19 Dec 2008 16:42:35 -0800 (PST) Subject: dancer exotic photography - Free Message-ID: dancer exotic photography . . . *******CLICK HERE******** http://club247.cn/dancer-exotic-photography ***************************** . . . . . . . . . . . . dancer exotic photography From David Mon Dec 29 19:53:45 2008 From: David (David) Date: Mon, 29 Dec 2008 18:53:45 -0600 Subject: Of console I/O, characters, strings & dogs Message-ID: I am trying getch() from msvcrt. The following module has been run with 3 different concatination statements and none yield a satisfactory result. Python 3.0 # script12 import msvcrt shortstr1 = 'd' + 'o' + 'g' print(shortstr1) char1 = msvcrt.getch() char2 = msvcrt.getch() char3 = msvcrt.getch() < alternatives for line 8 below > print(shortstr2) print(shortstr1) gives dog of course. If the same char are entered individually at the console, as char1, 2 & 3, using msvcrt.getch(), I have not been able to get out a plain dog. If line 8 is shortstr2 = char1[0] + char2[0] + char3[0] print(shortstr2) yields 314 If line 8 is shortstr2 = 'char1[0]' + 'char2[0]' + 'char3[0]' print(shortstr2) yields char1[0]char2[0]char3[0] If line 8 is shortstr2 = char1 + char2 + char3 print(shortstr2) yields b 'dog' Is the latter out of "How to Speak Redneck" ? Possibly b means bit string. But how do I get a plain dog out of these char console entries ? The 3.0 tutorial doesn't discuss console I/O. Found msvcrt in Python in a Nutshell. An old c programmer learns that this b 'Python' From steve at REMOVE-THIS-cybersource.com.au Sat Dec 20 21:09:31 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Dec 2008 02:09:31 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: <015d9ca5$0$20656$c3e8da3@news.astraweb.com> On Sat, 20 Dec 2008 17:54:09 -0800, r wrote: > Would you like to elaborate on -why- escaped backslashes are needed in > strings... i waiting??? If you can't escape backslashes in strings, how do you create a string containing a backslash? -- Steven From jstroud at mbi.ucla.edu Wed Dec 24 03:57:35 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 24 Dec 2008 00:57:35 -0800 Subject: Strategy for determing difference between 2 very large dictionaries In-Reply-To: <6rea9hF16p8tU1@mid.uni-berlin.de> References: <1230102996.2303.1291616055@webmail.messagingengine.com> <6rea9hF16p8tU1@mid.uni-berlin.de> Message-ID: <3Qm4l.11404$c45.9406@nlpi065.nbdc.sbc.com> Marc 'BlackJack' Rintsch wrote: > On Wed, 24 Dec 2008 03:23:00 -0500, python wrote: > >> Hi Gabriel, >> >> Thank you very much for your feedback! >> >>> k1 = set(dict1.iterkeys()) >> I noticed you suggested .iterkeys() vs. .keys(). Is there any advantage >> to using an iterator vs. a list as the basis for creating a set? I >> understand that an iterator makes sense if you're working with a large >> set of items one at a time, but if you're creating a non-filtered >> collection, I don't see the advantage of using an iterator or a list. >> I'm sure I'm missing a subtle point here :) > > `keys()` creates a list in memory, `iterkeys()` does not. With > ``set(dict.keys())`` there is a point in time where the dictionary, the > list, and the set co-exist in memory. With ``set(dict.iterkeys())`` only > the set and the dictionary exist in memory. For the purpose of perpetuating the annoying pedantry that has made usenet great: http://docs.python.org/dev/3.0/whatsnew/3.0.html#views-and-iterators-instead-of-lists James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From 20080915.20.wmcclain at spamgourmet.com Tue Dec 9 11:48:26 2008 From: 20080915.20.wmcclain at spamgourmet.com (Bill McClain) Date: 9 Dec 2008 16:48:26 GMT Subject: StringIO in 2.6 and beyond References: <7374e36d-a84d-4549-a0d9-b626fa013f68@t26g2000prh.googlegroups.com> Message-ID: On 2008-12-09, pruebauno at latinmail.com wrote: > This puzzles me too. According to the documentation StringIO accepts > both byte strings and unicode strings. Try to replace > output.write('First line.\n') > with > output.write(unicode('First line.\n')) > or > output.write(str('First line.\n')) > and see if one of those works. This works: output.write(unicode('First line.\n')) ..but this generates the error: print(unicode('Second line.'), file=output) -Bill -- Sattre Press History of Astronomy http://sattre-press.com/ During the 19th Century info at sattre-press.com by Agnes M. Clerke http://sattre-press.com/han.html From marco at sferacarta.com Wed Dec 17 11:06:49 2008 From: marco at sferacarta.com (Marco Mariani) Date: Wed, 17 Dec 2008 17:06:49 +0100 Subject: Selecting a different superclass In-Reply-To: References: Message-ID: psaffrey at googlemail.com wrote: > The problem is that IDPointSet and MicroArrayPointSet will need to > inherit from PointSet or TraceablePointSet based on whether I'm > handling traceable points or not. Can I select a superclass > conditionally like this in Python? Am I trying to do something really > evil here? > > Any other bright ideas on my application also welcome. I think you should investigate something different than subclassing, like a "Strategy" domain pattern or something similar. From skip at pobox.com Fri Dec 5 15:06:28 2008 From: skip at pobox.com (skip at pobox.com) Date: Fri, 5 Dec 2008 14:06:28 -0600 Subject: slow Python 3.0 write performance? In-Reply-To: References: Message-ID: <18745.35268.352560.386831@montanaro-dyndns-org.local> Istvan> Could someone run the code below on both Python 2.5 and 3.0 For Istvan> me (on Windows) it runs over 7 times slower with Python 3.0 ... I/O was completely rewritten for Python 3.0. Stdio is no longer used. At the moment I believe much of the io subsystem is still implemented in Python. Note these comments in io.py: # New I/O library conforming to PEP 3116. # This is a prototype; hopefully eventually some of this will be # reimplemented in C. It should get faster over time. It will get faster over a shorter period of time if people contribute patches. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From metolone+gmane at gmail.com Sat Dec 13 23:12:10 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 13 Dec 2008 20:12:10 -0800 Subject: Python 3.0 crashes displaying Unicode at interactive prompt References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com><49443531.5050304@v.loewis.de> Message-ID: "John Machin" wrote in message news:a8cd683f-853d-4665-bee4-7a0bdb84181e at c36g2000prc.googlegroups.com... > On Dec 14, 9:20 am, "Martin v. L?wis" wrote: > > >> This is intended behavior. > > > > > I see. That means that the behaviour in Python 1.6 to 2.6 (i.e. > > > encoding the text using the repr() function (as then defined) was not > > > intended behaviour? > > > > Sure. > > "Sure" as in "sure, it was not intended behaviour"? > > > This behavior has not changed. It still uses repr(). > > > > Of course, the string type has changed in 3.0, and now uses a different > > definition of repr. > > So was the above-reported non-crash consequence of the change of > definition of repr intended? It is intended. I ran into your same issue and voiced a similar complaint, but Martin pointed out that users of other characters sets wanted to see the characters they were using. If you were in China, would you rather see: IDLE 2.6.1 >>> x=u'\u9876' >>> x u'\u9876' >>> x=u'?' >>> x u'\u9876' or: IDLE 3.0 >>> x='\u9876' >>> x '?' >>> x='?' >>> x '?' On Asian consoles that support the required characters, 3.0 makes much more sense. Your cp850 console or my cp437 console can't support the characters, so we get the encoding error. I'm sure our Asian colleagues love it, but our encoding-challenged consoles now need: >>> x='\u9876' >>> print(ascii(x)) '\u9876' It's not very convenient, and I've found it is easier to use IDLE (or any other IDE supporting UTF-8) rather than the console when dealing with characters outside what the console supports. -Mark From walterbyrd at iname.com Sat Dec 20 18:27:43 2008 From: walterbyrd at iname.com (walterbyrd) Date: Sat, 20 Dec 2008 15:27:43 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: On Dec 19, 10:25?am, Michael Torrie wrote: > Personally the new string formatter is sorely needed in Python. ? Really? You know, it's funny, but when I read problems that people have with python, I don't remember seeing that. Loads of people complain about the white space issue. Some people complain about the speed. Lots of complaints about certain quirky behavior, but I have not come across any complaints about the string formatting. In fact, from what I have seen, many of the "problems" being "fixed" seem to be non-problems. I dunno, maybe it's just me. From arnodel at googlemail.com Sat Dec 6 05:01:10 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 06 Dec 2008 10:01:10 +0000 Subject: Don't you just love writing this sort of thing :) References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: Lawrence D'Oliveiro writes: > In message <32cf4a79-a6e3-4250-9b5a-1ec80c748618 at j32g2000yqn.googlegroups.com>, Aaron Brady wrote: > >> On Dec 5, 4:32?am, Lawrence D'Oliveiro > central.gen.new_zealand> wrote: >> >>> The code people write is probably a direct reflection of their thinking >>> processes: For example, slow, plodding, one step at a time, incapable of >>> imaginative leaps, versus those who operate directly on larger patterns >>> at once... >> >> That distinction operates indirectly on smaller patterns. > > Do you find this > > (open, gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir, Entry), "r") > > complicated or hard to understand? (aside: it's funny that someone asks Aaron this quesion as he is the one who used to post code that almost nobody understood! (although I had a feeling there was often something interesting in it)). in Python it is a convention only to capitalize classes, so unless Entry and PatchesDir are classes it would be better to write them as entry and patches_dir for example. Why use (open, gzp.GzipFile)[Entry.endswith(".gz")] when we have had contitional expressions for a few years now? Instead, you can write (gzip.GzipFile if entry.endswidth(".gz") else open). I think it will be faster (as it doesn't require the construction of a tuple and then the retrieval of one of its elements) and clearer. It's good to be able to understand (and I guess, to write) such code. But to assume that others dislike it because they don't understand it sends several wrong signals: * you give the impression of being arrogant; * many people will understand this code snippet perfectly easily but they won't like it because they think that Python offers much better ways to express the same thing. * you seem to disregard the fact that in 'programming language' there is the word 'language'. A language is a way to _communicate_ information, in the case of a programming language you communicate it to the computer but also to other human beings. To come back to your code, you could define a function like the one below (untested). It'll allow you to add support for different compression formats easily in the future. This is a 'pattern' which can be useful to keep in mind and requires *some* imagination. open_methods = { 'gz': gzip.GzipFile, 'bz2': bz2.BZ2File } def open_by_ext(path, *args): ext = os.path.splitext(path)[1] return open_methods.get(ext, open)(path, *args) Then your code snippet becomes: open_by_ext(os.path.join(patches_dir, entry), "r") -- Arnaud From clp at rebertia.com Mon Dec 22 18:19:49 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 22 Dec 2008 15:19:49 -0800 Subject: iterating initalizations In-Reply-To: References: Message-ID: <47c890dc0812221519m19573756yced5e999cab2b204@mail.gmail.com> On Mon, Dec 22, 2008 at 2:22 PM, Aaron Stepp wrote: > Hi all: > > I'm new to python and trying to save time and code by iterating through list > initializations as well as the assignments. I have the following code: > > import random > from rtcmix import * > from chimes_source import * > from rhythmblock import * > from pitchblock import * > > indexrand = random.Random() > indexrand.seed(2) > > rhythm = rhythmBlock() > pitch = pitchBlock() > > class pitchAndRhythm: > > def __init__self: > > self.__abet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' > > > def listCreate(self, num): > > if num > 25: > > print "Oops. This won't work" > > else: > > for a in range(num): > > b = indexrand.randint(0, 3) > > c = indexrand.randint(0, 7) > I don't quite understand what you're trying to do, but I can offer some advice. > index = self.__abet[a] The previous line is pointless currently. I don't understand what you expect it to do, considering you completely overwrite 'index' in the very next line. > index = [ ] > > index = index.append(rhythm.rhythmTwist(b, c)) Important Note: .append() modifies the list *in-place*. It does *not* return the modified list, it returns None. You probably want to eliminate the 'index =' part of the previous line. > > This doesn't do what I expect (probably because I don't have a clue what I'm > doing!): initalizing, then filling new arrays, each new one called A[ ], > then B[ ], etc. You probably want a dictionary of names to lists then, the names being items of __abet and the lists being the corresponding 'index'. It likely goes without saying, but you ought to read the fine tutorial as well. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From stepp.aaron at gmail.com Tue Dec 23 10:39:52 2008 From: stepp.aaron at gmail.com (Aaron Stepp) Date: Tue, 23 Dec 2008 10:39:52 -0500 Subject: iterating initalizations In-Reply-To: References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> <20081223092504.aaf25192.darcy@druid.net> Message-ID: import random from rtcmix import * from chimes_source import * # Chime.play() from rhythmblock import * # rhythmBlock.rhythmTwist() and rhythmBlock.printStuff() from pitchblock import * # pitchBlock.pitchTwist() and pitchBlock.printStuff() from lenEval import * #greaterThan.sovler() indexrand = random.Random() indexrand.seed(2) chime = Chime() notes = pitchBlock() rhythm = rhythmBlock() solve = greaterThan() class arrayBlock: def __init__(self, theTempo, start): self.__A = [] self.__B = [] self.__start = start self.__tempo = theTempo def player(self, length, tempo, octave, pan, seed): tempo = (120, self.__tempo) for a in range(length): one = indexrand.randint(0, 3) two = indexrand.randint(0, 7) self.__A = self.__A + notes.pitchTwist(one , two) for b in range(length): one = indexrand.randint(0, 3) two = indexrand.randint(0, 7) self.__B = self.__B + rhythm.rhythmTwist(one , two) lenA = len(self.__A) lenB = len(self.__B) var = solve.solver(lenA, lenB) for c in range(var): print self.__A[c] self.__start = self.__start + tb(self.__B[var]) chime.play(self.__start, self.__A[var], octave, pan, seed) This almost does exactly what I want, and is far cleaner than my previous attempts. The only problem is that now all my arguments are being passed as zeros! I assume this has to do with WHEN I'm referencing self.__A and self.__B? AS On Dec 23, 2008, at 10:20 AM, Steve Holden wrote: > D'Arcy J.M. Cain wrote: >> On Mon, 22 Dec 2008 22:32:17 -0500 >> Aaron Stepp wrote: >>> Instead of writing a long list of initializations like so: >>> >>> A = [ ] >>> B = [ ] >>> ... >>> Y = [ ] >>> Z = [ ] >>> >>> I'd like to save space by more elegantly turning this into a >>> loop. If >> >> Well, if all you want is a loop: >> >> for v in vars: >> locals()[v] = [] >> > Note that this isn't guaranteed to work. While locals() will return a > dict containing the names and values from the local namespace, you > won't > affect the local namespace by assigning values to the appropriate > keys: > >>>> def f(): > ... a = "hello" > ... locals()["a"] = "goodbye" > ... print a > ... >>>> f() > hello >>>> > > If you look at the function's code you will see that the local "a" is > accessed using the LOAD_FAST and STORE_FAST opcodes, which take > advantage of the knowledge that the name is local - the interpreter > analyzed the function body looking for assignments to non-globals, and > optimizes its treatment of such names. > >>>> dis.dis(f) > 2 0 LOAD_CONST 1 ('hello') > 3 STORE_FAST 0 (a) > > 3 6 LOAD_CONST 2 ('goodbye') > 9 LOAD_GLOBAL 0 (locals) > 12 CALL_FUNCTION 0 > 15 LOAD_CONST 3 ('a') > 18 STORE_SUBSCR > > 4 19 LOAD_FAST 0 (a) > 22 PRINT_ITEM > 23 PRINT_NEWLINE > 24 LOAD_CONST 0 (None) > 27 RETURN_VALUE >>>> > >> It's hard to tell if that's what you actually need though without >> deeper analysis of your requirements. >> > I think it's unlikely that the OP really does need to create names > dynamically, and should look at using either a dict indexed by the > letters of self.__abet, or a list indexed from 0 to 24 instead. But > you > *are* correct about the need for a little more information ;-) > > regards > Steve > > > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > From bruno.42.desthuilliers at websiteburo.invalid Fri Dec 12 03:09:03 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 12 Dec 2008 09:09:03 +0100 Subject: Preventing execution of a method In-Reply-To: References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> <764daeef-bfbe-411a-8521-bb114321e4ac@b38g2000prf.googlegroups.com> <19304f8c-e34f-4aa9-8df2-6a7d3553007a@e1g2000pra.googlegroups.com> <2eed8876-94d2-4304-88a5-eb4a78b4f41d@33g2000yqm.googlegroups.com> <307fe197-1b42-4305-af0e-94b7ebe3ce70@r15g2000prh.googlegroups.com> <49417c59$0$8491$426a74cc@news.free.fr> Message-ID: <49421c07$0$3398$426a74cc@news.free.fr> Emanuele D'Arrigo a ?crit : > On Dec 11, 7:48 pm, Bruno Desthuilliers > wrote: >>> or to provide read-only >>> access. I.e. right now I'm working on the graphical client which >>> potentially could be rewritten entirely by the users. It is necessary >>> and perfectly reasonable for the client module to access some of the >>> objects to be represented graphically, but those objects shouldn't be >>> modifiable by it. >> Why so ? At worst, they'll break everything. > > -IF- the application was single-user yes, it wouldn't be a big deal. > But as it is potentially multi-user, I don't want one party to corrupt > the application for everybody else. A multi-users application with a GUI usually implies that it's a client-server app with the GUI deployed is on each client and the domain logic hosted on the server. From gagsl-py2 at yahoo.com.ar Tue Dec 16 05:15:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Dec 2008 08:15:00 -0200 Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> Message-ID: En Tue, 16 Dec 2008 07:29:19 -0200, Aaron Brady escribi?: > I have a file handle I want to inherit in a child process. I am > looking at '_make_inheritable' in 'Popen', but it needs an instance, > and by the time I have one, the subprocess is already running. > > Can't I call 'Popen._make_inheritable( None, handle )'? The method > does not use 'self'. File handles are inherited by default, I think. What's your specific problem? -- Gabriel Genellina From kyosohma at gmail.com Mon Dec 8 13:52:37 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 8 Dec 2008 10:52:37 -0800 (PST) Subject: Calling C# COM (.NET) from python References: Message-ID: <65482a31-8091-486f-8a9b-8f6bdf947af6@w1g2000prk.googlegroups.com> On Dec 8, 11:14?am, Ben Kaplan wrote: > On Dec 8, 2008, at 11:53 AM, Andrew Falanga wrote: > > > > > Hi, > > > I've never programmed in python and only have a small understanding of > > what is wrapped up in the terms COM and .NET. ?Is there a way of using > > python to get a hold of objects written in C# as COM objects using > > python? ?I'm looking for ways to avoid VBScript (which, after a couple > > of weeks, I've determined to be horrid). ?That is, is there a way of > > getting at COM objects in python that's similar to doing a > > CreateObject call in VBScript (http://msdn.microsoft.com/en-us/ > > library/ > > dcw63t7z.aspx)? > > > Thanks, > > Andy > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I would not deal with COM at all. I personally have not used it, but ? > there is a version of python called IronPython that's written in C#, ? > so it can use .NET and, I think, other C# objects. Other people will ? > probably help you more, but you might want to look into that and maybe ? > ask this on the python-win list. As I understand it, IronPython can use anything done in the CLR, so technically I could write something in VB.NET, C# or any of the other VS languages and then use them from within IronPython. It should be noted that IronPython does not support most 3rd party packages that are not pure python. As I recall, it doesn't have the complete builtin library either, but it's close. Reads the docs and check it out at least. If you already know .NET languages, then you'll probably find IronPython helpful. Mike From mwilson at the-wire.com Sun Dec 21 11:06:51 2008 From: mwilson at the-wire.com (Mel) Date: Sun, 21 Dec 2008 11:06:51 -0500 Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <015da0a4$0$20656$c3e8da3@news.astraweb.com> <015e4162$0$20656$c3e8da3@news.astraweb.com> Message-ID: Duncan Booth wrote: > I don't see that. What I suggested was that a % b % c would map to > a.__mod__(b,c). (a % b) % c would also map to that, but a % (b % c) could > only possibly map to a.__mod__(b.__mod__(c)) There's a compiling problem here, no? You don't want a%b%c to implement as a.__mod__(b,c) if a is a number. Mel. From andrew.nelis at gmail.com Wed Dec 17 12:26:13 2008 From: andrew.nelis at gmail.com (Andrew Nelis) Date: Wed, 17 Dec 2008 09:26:13 -0800 (PST) Subject: getting object instead of string from dir() References: Message-ID: On Dec 17, 5:16?pm, Rominsky wrote: > I am trying to use dir to generate a list of methods, variables, etc. > I would like to be able to go through the list and seperate the > objects by type using the type() command, but the dir command returns > a list of strings. ?When I ask for the type of an element, the answer > is always string. ?How do I point at the variables themselves. ?A > quick example is: > > a = 5 > b = 2.0 > c = 'c' > > lst = dir() > > for el in lst: > ? ? print type(el) > > Right now I am understandably getting all types being output as > strings, how do i get the type of the actual objects returned from dir > ()? The builtin functions "locals" and "globals" will both return a dictionary whose keys are the variable names and values are the items corresponding to those keys; >>> locals()['b'] 2.0 From jef.mangelschots at gmail.com Tue Dec 16 14:21:23 2008 From: jef.mangelschots at gmail.com (jefm) Date: Tue, 16 Dec 2008 11:21:23 -0800 (PST) Subject: executables no longer executing on PC's without Python installed Message-ID: Hi, I recently figured out a problem that came up with the latest versions of Python and cx_Freeze. I thought I post it here so that it might be usefull to someone. The problem was that, when I switched to Python 2.6.x and cx_Freeze-4.0.1.win32-py2.6.msi, the executables that were produced ran perfectly on my PC but not any other PC. They did not print any useful information whatsoever. Googling around, I learned that it had to do with Visual Studio being installed on my PC and not on the other PC's. The common solution that worked for other people was to put the redistributable manifest and DLL's from C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT, into the same directory as the generated EXE. This didn't work for me. With the help of Anthony Tuininga, I finally tracked it down to the DLL version. In the good ol' days, when your application was lacking the C rntime library DLL in its search path, it gave a clear warning. e.g. "can not find msvcr71.dll" or something like that. The only thing you needed to do was to go look for one (either on your PC or on the internet), and pluck whatever DLL with that name into the search path, typically in the same directory as your exe or windows \system32. It didn't care about different versions of DLL's. Now with the advent of at least Visual Studio 2008 (and probably 2005, but I skipped that one), Microsoft, in its infinite wisdom, decided that that method was way too easy for everyone and came up with yet another way to torment everyone that dares to develop software in anything else than Microsoft monstrosities. I am referring to these mysterious things with names like "side by side installation", "SxS", "manifests", "assemblies", ... Why does the noble community of enlightened scholars developing Python care at all ? Because Python 2.6 binaries for Windows are now compiled using Visual Studio 2008. In essence, that should not mean more than replacing your msvcr71.dll with msvcr90.dll. Unfortunately, you inherit this "assemblies" crap with it. The new terminology invented with this and the MSDN articles on this subject make it only more obscure and complicated than it should be. In a nutshell, DLL's now are attributed with a version number. Executables generated with VS2008 are now restricted to run only with a predefined specific version of a DLL. This allows you to run executable A with version X of a DLL and another exe with version Y of that same DLL and not be affected with obscure bugs caused by pairing the wrong version of a DLL with an exe (the infamous DLL hell). How do you pair an exe with a particular DLL version ? That is done with manifest files, basically a small XML file, listing the exact version number and some obscure hash numbers for integrity checking. I haven't figured out how to manually produce these (VS2008 does this for you) but fortunately for us, Python developers we don't need to care. We just have to use the same one the Python distribution was compiled with. How do I know which version Python is compiled with ? The easiest way is to install Python with the option "install just for me". This has the result that the msvcrxx.dll used by Python is copied into the c:\pythonxx directory instead of in a common windows\system32 folder (or something like that). This was my first mistake, I used the other option "install for other users". This should not be a problem. cx_Freeze is clever enough to go out and find this DLL for you. It will probably find the right one, PROVIDING you have the right version of the DLL's in your search path. Now back to Microsoft. Up until around 9/16/2008, there was only 1 version of msvcr DLL's, nl. 9.0.21022.8 and that was good, because it happens to be the same version Python was installed with. The only thing you have to do is to accompany your generated exe with a manifest with the correct hieroglyphs, copy this dll in the same directory and you were done. (you actually need 2 manifest files: one that accompanies to the exe which DLL version it needs, and another manifest file that specifies the versions of the DLL. The exe manifest can be embedded in the exe). Poor old Anthony Tuininga had to figure this out the hard way. He makes our lives a lot easier by already embedding the correct exe manifest into the executable. You can check this by opening the generated binary with a hex editor and scroll down until you see some XML. That is the manifest. That will tell you which DLL's it needs and which version (nl. 9.0.21022.8). It needs to be this version because of the version of Visual Studio 2008 used to compile Python itself. Having Visual Studio 2008 installed on your PC while freezing your Python apps should not be a problem. Even if you didn't specify "install just for me", cx_Freeze will probably find msvcr90.dll somewhere. But then came Visual Studio 2008 SP1. With it came an updated msvcr90.dll with version 9.00.30729.1. That is what I had installed and things went south from there. Recent versions of Windows now come with the directory C:\WINDOWS \WinSxS, in where you find all the versions of these DLL's (this is what they refer to as "side-by-side installation", i.e. instead of copying these common dll's in system32 folder, every version is now copied in a directory with a particular name, containing the version number and all manifest files copied in C:\WINDOWS\WinSxS\Manifests). When I installed VS 2008 SP1, it copied a later version (9.00.30729.1) of msvcr in there "side-by-side" with the original version (9.0.21022.8) which came from the original VS2008 and which I needed to get my frozen Python26 exe's to run. For some reason, Windows couldn't figure out which DLL to choose. I followed the advise I found on the internet to find the c:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT folder and copy its content (being Microsoft.VC90.CRT.manifest and msvcr90.dll) into my bin directory. This didn?t work. Unfortunately, I had already updated my Visual Studio 2008 to SP1 and this using the wrong version (9.00.30729.1) Had I not updated to SP1, I would not have had this problem. Not understanding the problem, it looked like I was forced to have all my users install the Microsoft Visual C++ 2008 Redistributable Package before running my tools. Fortunately, this is not necessary. The solution is very simple: after having generated your application with cx_Freeze, copy the following files (and only these files) to your executable directory: C:\WINDOWS\WinSxS\Manifests\ x86_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.21022.8_x- ww_d08d0375.manifest C:\WINDOWS\WinSxS \x86_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.21022.8_x-ww_d08d0375\ msvcm90.dll msvcp90.dll msvcr90.dll I think this applies to py2exe as well. If you do not have these files, you can download these from the following link: Microsoft Visual C++ 2008 Redistributable Package (x86) (11/29/2007) http://www.microsoft.com/downloads/details.aspx?familyid=9B2DA534-3E03-4391-8A4D-074B9F2BC1BF&displaylang=en note: beware, there is now an SP1 version of this, which caries the (incorrect) 9.00.30729.1 version. I am not sure it carties the (correct) 9.0.21022.8 as well. If it doesn't, you need the other installation. You can find SP1 from: Microsoft Visual C++ 2008 SP1 Redistributable Package (x86) (9/16/2008) http://www.microsoft.com/downloads/details.aspx?familyid=A5C84275-3B97-4AB7-A40D-3802B2AF5FC2&displaylang=en note: I don't understand why Microsoft doesn't distribute the C runtime libraries (msvcrxx.dll) with the next Windows Update and squirt that puppy in every Windows PC on the planet. Hope this helps. Jef Mangelschots From sjmachin at lexicon.net Tue Dec 30 17:41:51 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 30 Dec 2008 14:41:51 -0800 (PST) Subject: python import sys.path References: Message-ID: <2fc5969f-f9ca-4c8e-9726-3a20e0cbab50@r10g2000prf.googlegroups.com> On Dec 31, 5:05?am, "Kelly, Brian" wrote: > I have both 2.4 and 2.5 interpreters installed on a linux box. The > PythonPath is set to : > > PYTHONPATH=/usr/lib64/portage/pym:/prod/bacula/local/lib64/python2.4/site-pa > ckages:/prod/bacula/local/lib/python2.4/site-packages > > My main script is getting called like so: > > python2.4 cleanup.py wrkstnbs > > The imports statements in cleanup.py are as follows: > > import os,sys > print sys.path > from datetime import datetime > from optparse import OptionParser ? ? ? ?# used for parsing parameters > from bacula_conf import * ? ? ? ? ? ? ? ?# used for connecting to our > databases, etc. > from registration_cleanup \ > ? ? import RegistrationCleanup ? ? ? ? ? # used for interacting w/ > registration db (sql1) > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?# and configuration database > (genunix) > import directory_cleanup as fclean ? ? ? # file cleanup. > > One of the scripts being imported from bacula_conf is called > purge_client.py. > > It has the following imports: > > import sys > import MySQLdb > > Everytime I run "python2.4 cleanup.py wrkstnbs" I get the following error: > > Traceback (most recent call last): Have you snipped any traceback entries here? You say you are running cleanup.py but the first traceback entry is from purge_client.py!! You should first fix that, so that you've got the full story. My guess is that something along that trail is invoking another instance of the Python interpreter and somehow that instance is 2.5, not 2.4. I can't imagine how those 2.5-related entries would otherwise get into sys.path Suggestions: (1) where you are debug-printing sys.path, also print sys.version and sys.argv[0] ... and do debug-printing at more places between start and error. (2) run "python2.4 -vv cleanup.py wrkstnbs" and look for the first mention of 2.5 (indicating something has manipulated sys.path), or sudden cessation of -vv output (indicating a new instance of python is running without -vv), or some other phenomenon ... > ? File "purge_client.py", line 22, in > ? ? import MySQLdb > ? File > "/prod/bacula/local/lib64/python2.4/site-packages/MySQLdb/__init__.py", line > 27, in > ? ? import _mysql > ImportError: /prod/bacula/local/lib64/python2.4/site-packages/_mysql.so: > undefined symbol: Py_InitModule4 What happens when you run python2.4 and at the interactive prompt do >>> import _mysql ? Is there a possibility that you installed 2.5 MySQLdb into the 2.4 hierarchy? [could be a stupid question from a windows guy; this may be a non-problem on linux] Is this the first thing that you've tried after installing 2.5, or the only problem found in an exhaustive regression test of all your apps using 2.4, or somewhere in the middle? [big snip] HTH, John From narkewoody at gmail.com Tue Dec 23 23:29:41 2008 From: narkewoody at gmail.com (Steven Woody) Date: Wed, 24 Dec 2008 12:29:41 +0800 Subject: Multi-dimension list In-Reply-To: References: Message-ID: Hi, In the book Python Essential Reference, Chapter 3, when talking about extended slicing, it gives an example: a = m[0:10, 3:20]. But I don't understand how the 'm' was defined. What should it looks like? Thanks. - narke From ht at example.com Thu Dec 4 15:09:57 2008 From: ht at example.com (HT) Date: Thu, 04 Dec 2008 12:09:57 -0800 Subject: Why shouldn't you put config options in py files References: Message-ID: Chris Rebert wrote: > On Thu, Dec 4, 2008 at 11:35 AM, HT wrote: >> FOO = {'bar': ('a': 'b'), 'abc': ('z': 'x')} > > I'll assume you meant ('a', 'b') as colons in parens don't make sense. Yes, sorry. > Well, it is pretty weird to be allowed to put arbitrary code in a mere > config file. The end result is that we want to have that dictionary in that variable (most of the config values would just be simple values or lists and this dict is among the most complex), but it doesn't mean that the config file would need to have arbitrary code. I can think of many ways to achieve that (haven't actually tried writing the code to read these yet): [my_foos] bar = a, b abc = z, x or maybe foo.bar= a, b foo.abc= z, x or something like that. You'd read the values with ConfigParser, then process them to get the dictionary. > Have you considered using JSON for the config file format instead? It > shares Python's syntax for literals, so you could do: No, hadn't thought of that. Might be doable, need to think about that some more. Thanks. From fetchinson at googlemail.com Fri Dec 5 21:21:18 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Fri, 5 Dec 2008 18:21:18 -0800 Subject: Guido's new method definition idea Message-ID: Hi folks, The story of the explicit self in method definitions has been discussed to death and we all know it will stay. However, Guido himself acknowledged that an alternative syntax makes perfect sense and having both (old and new) in a future version of python is a possibility since it maintains backward compatibility. The alternative syntax will be syntactic sugar for the old one. This blog post of his is what I'm talking about: http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html The proposal is to allow this: class C: def self.method( arg ): self.value = arg return self.value instead of this: class C: def method( self, arg ): self.value = arg return self.value I.e. explicit self stays only the syntax is slightly different and may seem attractive to some. As pointed out by Guido classmethods would work similarly: class C: @classmethod def cls.method( arg ): cls.val = arg return cls.val The fact that Guido says, "Now, I'm not saying that I like this better than the status quo. But I like it a lot better than [...] but it has the great advantage that it is backward compatible, and can be evolved into a PEP with a reference implementation without too much effort." shows that the proposal is viable. I'd like this new way of defining methods, what do you guys think? Anyone ready for writing a PEP? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From jon at ffconsultancy.com Mon Dec 8 20:00:35 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Tue, 09 Dec 2008 01:00:35 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: jason-sage at creativetrax.com wrote: > For the interested, with MMA 6, on a Pentium 4 3.8Ghz: > > The code that Jon posted: > > Timing[Export["image-jon.pgm", Graphics at Raster@Main[2, 100, 4]]] > {80.565, "image-jon.pgm"} That is not the code I posted: you are using Xah's parameters that generate a different (and largely empty) scene. > The code that Xah posted: > > Timing[Export["image-xah.pgm", Graphics at Raster@Main[2, 100, 4.]]] > {42.3186, "image-xah.pgm"} > > So Xah's code is about twice as fast as Jon's code, on my computer. > > The resulting files were identical (and both looked like pure white > images; I thought they'd be interesting!). Use 9, 512, 4 instead of 2, 100, 4 and you will get a more interesting image of over 80,000 spheres with shadows and diffuse lighting. This is a really important difference: half of that program is dedicated to hierarchical spherical bounding volumes that are essential when tracing a large number of spheres. Xah solved a completely different problem by simplifying the scene to only 5 spheres, where bounding volumes are useless and the performance characteristics of the program are wildly different. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From python at rgbaz.eu Wed Dec 31 07:55:51 2008 From: python at rgbaz.eu (Python) Date: Wed, 31 Dec 2008 13:55:51 +0100 Subject: Graphics Library with Standard Interaction Features, 2D and 3D In-Reply-To: <69c3eca8-5e17-49fb-8354-5fdc0bd73f9a@r15g2000prd.googlegroups.com> References: <69c3eca8-5e17-49fb-8354-5fdc0bd73f9a@r15g2000prd.googlegroups.com> Message-ID: <878673C7-0520-49B1-A24B-B7292D6C32CC@rgbaz.eu> On 31 dec 2008, at 13:37, Benjamin Blundell wrote: > Hi all. I've had a look around the forums and the we and im looking > for a library (or a set of libraries) for dealing with Visualisation > and Interaction in Python. At the moment i've been using Flash with > the Five3D library to do most of the work. Sadly this isnt an option > anymore but it is a good example. Pretty,anti-aliased 2D and 3D > graphics, simple interaction and no need to rewrite the wheel. > > Im a fan of OpenGL and PyOpenGL is fairly cool but I really dont want > to have to write yet another camera, another way of dealing with > Vectors, texture organiser, picking, etc etc. Is there a library or > set of libraries that people are aware of that might do this? I > remember a few in C++ and C but it'd be nicer to stick to working with > Python > > Cheers > Ben Hey Ben, dunno if this is exactly what you;re looking for, yet you could have a look at Blender http://blender.org/ http://wiki.blender.org/index.php/Scripts it's an open source 3D application and has a python scripting engine... (just like maya from Autodesk) gr Arno From samslists at gmail.com Fri Dec 5 19:04:40 2008 From: samslists at gmail.com (Sam) Date: Fri, 5 Dec 2008 16:04:40 -0800 (PST) Subject: Centralized logging server... References: <413147e3-aaea-4ae3-a350-4c22a79fe77a@b38g2000prf.googlegroups.com> Message-ID: <857c6c29-178d-4444-90e0-f3c25386921c@w24g2000prd.googlegroups.com> Yep...I'm planning on using SysLogHandler. Although if I were to use rsyslog, for example, I might potentially be better off using tcp or even doing it using rfc 3195. Sysloghandler uses udp...I imagine that will be faster but with less reliability. I'll have to think about that. Has anyone implemented a library for rfc 3195, or would I have to do that from scratch. I was more curious as to what people are using to receive the messages? Syslog-ng? traditoinal? rsyslog? Home grown solutions? I know syslog is already running, but I'm not sure the traditional version could keep up with all the traffic I'm going to have. Anyone know how well it scales compared to the alternatives? Thanks Sam On Dec 5, 12:24?pm, s... at pobox.com wrote: > ? ? Sam> I've been playing with the python logging module. ?I'd like all of > ? ? Sam> these applications to write their logs to the same place in order > ? ? Sam> to make analysis easier. > > ? ? Sam> Any ideas on best practices? > > Perhaps use logging.handlers.SysLogHandler? > > ? ? Sam> What are my options for a syslog server to receive the messages? > ? ? Sam> Rsyslog looks like it would be good. ?Anyone know anything else? > > If you're running on a Unix system of any type you should have syslog by > default. ?You shouldn't need to install anything. > > -- > Skip Montanaro - s... at pobox.com -http://smontanaro.dyndns.org/ From rbonvall at gmail.com Wed Dec 10 22:28:04 2008 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Wed, 10 Dec 2008 19:28:04 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: Arnaud Delobelle wrote: > def unit(v): > return map((sum(map(lambda x:x*x, v))**0.5).__rdiv__, v) > > The hard bit was to make it less readable than the Ruby version ;) I loved the use of __rdiv__ :) I would have proposed the more straightforward: def u(v): return [x/sum(x**2 for x in v)**0.5 for x in v] or, in order to avoid computing the norm for each element: def u(v): return (lambda norm: [x/norm for x in v])(sum(x**2 for x in v) **0.5) -- Roberto Bonvallet From castironpi at gmail.com Mon Dec 29 20:46:36 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 17:46:36 -0800 (PST) Subject: why cannot assign to function call References: <495867C2.7080807@gmail.com> Message-ID: <5e807c67-7d97-4b8a-8c5f-a3b97f5c5003@i20g2000prf.googlegroups.com> On Dec 29, 6:06?pm, Miles wrote: > On Mon, Dec 29, 2008 at 1:01 AM, scsoce wrote: > > I have a function return a reference, and want to assign to the reference, > > simply like this: > >>>def f(a) > > ? ? ? ? return a > > ? ?b = 0 > > ? * f( b ) = 1* > > but the last line will be refused as "can't assign to function call". > > In my thought , the assignment is very nature, ?but ?why the interpreter > > refused to do that ? > > Here's some links to help you better understand Python objects: > > http://effbot.org/zone/python-objects.htmhttp://effbot.org/zone/call-by-object.htm > > The second one is a bit denser reading, but it's important to learn > that Python's approach to objects and "variables" is fundamentally > different from that of C/C++. ?In the example below, there's no way in > the Python language* that bar() can change the value of b, since > strings and numbers are immutable. On a technicality, to avert a flaming, "change the value of 'b'" is an ambiguous phrase. There are two interpretations of "change what 'b' refers to" and "change what 'b' refers to". Even in spoken language, I don't think that emphasis can resolve them either. One means, 'make a change in the world, in the actual configuration of such and such actual matter.' The other means, 'update the axioms the speaker is using to communicate to the listeners. (Such and such will no longer refer to such and such; it will refer to such and such; accept this and reject that.)' To make an observation, reference is a purely linguistic phenomenon. I, for one, am at a loss for how to disambiguate it. I'm open to suggestions. From bruno.42.desthuilliers at websiteburo.invalid Fri Dec 19 07:22:33 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 19 Dec 2008 13:22:33 +0100 Subject: encoding problem In-Reply-To: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> References: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> Message-ID: <494b91c2$0$1133$426a74cc@news.free.fr> digisatori at gmail.com a ?crit : > The below snippet code generates UnicodeDecodeError. > #!/usr/bin/env python > #--*-- coding: utf-8 --*-- > s = '???' > u = unicode(s) > > > It seems that the system use the default encoding- ASCII to decode the > utf8 encoded string literal, and thus generates the error. Indeed. You want: u = unicode(s, 'utf-8') # or : u = s.decode('utf-8') > The question is why the Python interpreter use the default encoding > instead of "utf-8", which I explicitly declared in the source. Because there's no reliable way for the interpreter to guess how what's passed to unicode has been encoded ? s = s.decode("utf-8").encode("latin1") # should unicode try to use utf-8 here ? try: u = unicode(s) except UnicodeDecodeError: print "would have worked better with "u = unicode(s, 'latin1')" NB : IIRC, the ascii subset is safe whatever the encoding, so I'd say it's a sensible default... From steve at REMOVE-THIS-cybersource.com.au Mon Dec 15 04:00:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Dec 2008 09:00:48 GMT Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> <0152e35f$0$8244$c3e8da3@news.astraweb.com> <0155c4a7$0$6988$c3e8da3@news.astraweb.com> Message-ID: <01561434$0$20639$c3e8da3@news.astraweb.com> On Mon, 15 Dec 2008 05:39:45 +0000, Lie Ryan wrote: > I was just expressing the > preference that operators should be composed of a single word, > especially since none of the other operators are multi-words Then you should have said so, instead of introducing red-herrings about tired programmers. I must say, some years ago I probably would have agreed with you. I used to dislike "a is not b" and would go out of my way to write "not a is b". But then I decided that was just being silly, and I've never looked back. -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 22:07:49 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2008 03:07:49 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <1332da3c-8075-4552-9498-3ceb23faca8f@v31g2000vbb.googlegroups.com> Message-ID: <015c58d6$0$20656$c3e8da3@news.astraweb.com> On Fri, 19 Dec 2008 17:12:00 -0800, r wrote: > Why move away from a concise and widely accepted way of sting > formatting, just to supposedly make it a little easier for n00bs? (which > i disagree this is easier) In turn, creating more syntactical clutter. > (%s %f %d) is all you need to remember. If people can't understand that, > i fear for the future of Humans as a species! Reading your wibbling, so do I. Take ten deep breaths and calm down. Firstly, the introduction of format() is not to "make it a little easier for n00bs" as you claim, but to allow more powerful, flexible string formatting. Secondly, to use % formatting to full effectiveness you need to know MUCH more than (%s %f %d). You need to know: Formatting codes: %s %r %d %f %g %G %c %i %u %o %x %X %e %E %% (have I missed any?) Keyword formatting: %(name)s Flags: - + 0 Field width and precision, including the special case of "*" and how they fit together: %[(name)][flags][width][.precision][unused(!) length modifier]code You also need to know about operator precedence: >>> "%s" % 3+2 Traceback (most recent call last): File "", line 1, in TypeError: cannot concatenate 'str' and 'int' objects and the special casing of tuples: >>> "Tuple = %s" % (1,2,3) Traceback (most recent call last): File "", line 1, in TypeError: not all arguments converted during string formatting For trivial cases, format() isn't much harder than %: "{0}".format(x) "%s" % x For more complex cases, format() will let you do things that you can't do with only %, e.g. arbitrary fill characters, centring fields, percentage formatting, mixing positional and keyword arguments, etc. Before you blow yet another gasket, go read the PEP: http://www.python.org/dev/peps/pep-3101/ -- Steven From rogerb at rogerbinns.com Wed Dec 24 03:27:25 2008 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 24 Dec 2008 00:27:25 -0800 Subject: Most efficient way to build very large dictionaries In-Reply-To: <1230104615.5867.1291617213@webmail.messagingengine.com> References: <1230104615.5867.1291617213@webmail.messagingengine.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 python at bdurham.com wrote: > Can I take advantage of this knowledge to optimize You do the optimization last :-) The first thing you need to do is make sure you have a way of validating you got the correct results. With 25M entries it would be very easy for an optimization to get the wrong results (maybe only one result wrong). Once you can verify the results correctness, write the simplest most readable code possible. Then once your whole program is approaching completion time how long things take to get an idea of where to optimize. For example it is pointless optimizing the loading phase if it only takes 2 minutes out of a 3 hour runtime. Finally you can optimize and always have a way of verifying that the optimizations are correct. You have the original code to document what is supposed to be happening as optimized code tends to get rather obfuscated and unreadable. Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAklR8mkACgkQmOOfHg372QQvLQCgu6NYNUuhgR06KQunPmIrZ64B +rsAnAgQOKzMdmonF+zIhsX2r/Xg/72Y =LFfW -----END PGP SIGNATURE----- From pyth0nc0d3r at gmail.com Mon Dec 15 08:21:12 2008 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Mon, 15 Dec 2008 07:21:12 -0600 Subject: %s place holder does not let me insert ' in an sql query with python. In-Reply-To: <1229345178.31093.24.camel@krishna-laptop> References: <1229345178.31093.24.camel@krishna-laptop> Message-ID: I had this problem too. If you've upgraded to python 2.6 you need to use the new sytnax "format queryString = "insert into venders values('{0}','{1}','{2}'".format(field1,field2,field3) On Mon, Dec 15, 2008 at 6:46 AM, Krishnakant wrote: > hello all hackers. > This is some kind of an interesting situation although many of you must > have already gone through it. > I am facing a situation where I have to use psycopg2 and insert rows in > a postgresql table. > That's pritty easy and no need to say that it works well. But there are > some entries which have an ' in the value. > I have a venders table in my database and one of the values tryed was > "His Master's Voice " > now the master's word has the ' which is used for starting and ending a > varchar value for postgresql or almost any standard RDBMS. > Does any one know what is the way out of this? > how do you let the ' go as a part of the string? > I have used %s as placeholder as in > queryString = "insert into venders values ('%s,%s,%s" % > (field1,field2,field3 ) ... > This is not working for the ' values. > can any one suggest a suitable solution? > happy hacking. > Krishnakant. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From hackingkk at gmail.com Sun Dec 21 12:20:05 2008 From: hackingkk at gmail.com (Krishnakant) Date: Sun, 21 Dec 2008 22:50:05 +0530 Subject: Python is slow In-Reply-To: <494E6FDA.4070401@mrabarnett.plus.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> <6r6hpfFfb643U3@mid.uni-berlin.de> <494E6FDA.4070401@mrabarnett.plus.com> Message-ID: <1229880005.4138.46.camel@krishna-laptop> With my current experience with java, python and perl, I can only suggest one thing to who ever feels that python or any language is slow. By the way there is only one language with is fastest and that is assembly. And with regards to python, I am writing pritty heavy duty applications right now. Just to mention I am totally blind and I use a screen reader called orca on the gnome desktop. I hope readers here can understand that a screen reader has to do a lot of real-time information processing and respond with lightenning speed. And Orca the scree reader is coded totally in python. So that is one example. So conclusion is is how you enhance your program by utilising the best aspects of python. happy hacking. Krishnakant. On Sun, 2008-12-21 at 16:33 +0000, MRAB wrote: > Marc 'BlackJack' Rintsch wrote: > > On Sat, 20 Dec 2008 14:18:40 -0800, cm_gui wrote: > > > >>> Seriously cm_gui, you're a fool. > >>> Python is not slow. > >> haha, getting hostile? > >> python fans sure are a nasty crowd. > >> > >> Python is SLOW. > >> > >> when i have the time, i will elaborate on this. > > > > You are not fast enough to elaborate on Python's slowness!? :-) > > > > cm_gui is slow! > > > > Ciao, > > Marc 'BlackJack' Rintsch > > > Correction: > > cm_gui is SLOW! :-) > -- > http://mail.python.org/mailman/listinfo/python-list From febaen at gmail.com Mon Dec 15 17:40:08 2008 From: febaen at gmail.com (feba) Date: Mon, 15 Dec 2008 14:40:08 -0800 (PST) Subject: Need help improving number guessing game References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> <01564c98$0$21844$c3e8da3@news.astraweb.com> <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> Message-ID: Spent a bit more time looking over suggestions and working out some annoyances. import random def customrange(game, lowunsafe=True): game['defrang'] = False #Keeps setup from changing range to defaults while lowunsafe: #makes sure that the low number is positive picklow = int(input("PLEASE PICK THE LOW NUMBER: ")) if picklow < 0: print("LOW NUMBER MUST BE POSTIVE") else: lowunsafe = False pickhigh = int(input("PLEASE PICK THE HIGH NUMBER: ")) if pickhigh - picklow <= 2: #see setup(). print("HIGH MUST BE AT LEAST THREE GREATER THAN LOW") else: game['minr'], game['maxr'] = picklow, pickhigh print("RANGE IS [%s-%s]!" % (game['minr'], game['maxr'])) def wantcustom(game, unsure=True): #Allows user to decide their own range for guessing. while unsure: pickrange = input("WOULD YOU LIKE TO CREATE A CUSTOM RANGE? Y/ N: ") if pickrange.lower() == "n": game['minr'], game['maxr'] = 1, 99 #Default range. see setup unsure = False elif pickrange.lower() == "y": customrange(game) unsure = False else: print("INVALID INPUT") def samesettings(game, unsure=True): while unsure: keepset = input("USE SAME SETTINGS? Y/N: ") if keepset.lower() == "y": game['minr'], game['maxr'] = 1, 99 #Default range. see setup unsure = False elif keepset.lower() == "n": wantcustom(game) numplayers(game) unsure = False else: print("INVALID INPUT") def setup(game): #minr, maxr make minimum and maximum. Can be adjusted. #Make sure that maxr - minr is at least 3. #1 or less would be impossible. 2 would only have one guess for victory #The first would be unplayable, the second would play itself if game['maxr'] - game['minr'] <= 2: raise ValueError("INVALID RANGE!") #If this fails, check line 43 game['gcount'] = 0 #Reset guess count game['target'] = random.randint(game['minr'], game['maxr']) def playerswitch(game): #Player Switch #if player's a witch: burn(her) if game['player'] == game['player1']: game['player'] = game['player2'] else: game['player'] = game['player1'] def youwin(game): if game['pnum'] == 1: print("CONGRATULATIONS! IT TOOK YOU %s GUESSES" % game ['gcount']) else: if game['player'] == game['player1']: game['p1sc'] += 1 else: game['p2sc'] += 1 end = "CONGRATULATIONS %s! SCORE -- P1:%s P2:%s" print(end % (game['player'], game['p1sc'], game['p2sc'])) def playagain(game, unsure=True): while unsure: playover = input("PLAY AGAIN? Y/N: ") if playover.lower() == "y": game['play'] = True samesettings(game) setup(game) unsure = False elif playover.lower() == "n": print("GOOD BYE. PLAY AGAIN SOON!") game['play'] = False unsure = False else: print("INVALID INPUT") def autofinish(game): if game['maxr'] - game['minr'] == 2: print("...ONLY ONE OPTION LEFT!") youwin(game) playagain(game) def numplayers(game, unsafe=True, prompt="1 OR 2 PLAYERS?\n> "): while unsafe: while True: num = input(prompt) try: #Make sure that num is valid num = int(num) except ValueError: print("BAD VALUE!") else: break if num == 1 or 2: #ONLY allow 1 or 2P. unsafe = False else: print("INVALID INPUT") game['pnum'] = num def guesses(game, unsafe=True): while unsafe: while True: try: guess = int(input("[%s-%s]%s>> " \ #keeps user aware of who's turn it is, and the range % (game['minr'], game['maxr'], game['player']))) except ValueError: print("BAD VALUE!") else: break if guess >= game['maxr']: print("NUMBER MUST BE IN RANGE") guesses(game) guesscheck(game) elif guess <= game['minr']: print("NUMBER MUST BE IN RANGE") guesses(game) guesscheck(game) else: unsafe = False game['guess'] = guess def guesscheck(game): if game['guess'] == game['target']: if game['pnum'] == 1: game['gcount'] += 1 youwin(game) playagain(game) elif game['guess'] > game['target']: print("TOO HIGH") if game['pnum'] == 1: game['gcount'] += 1 game['maxr'] = game['guess'] else: print("TOO LOW") if game['pnum'] == 1: game['gcount'] += 1 game['minr'] = game['guess'] def guessing(game): guesses(game) guesscheck(game) if game['pnum'] == 2: playerswitch(game) autofinish(game) def main(game=None): if game is None: game = {} print("WELCOME TO THE SUPER NUMBER GUESSING GAME!") game['play'] = True game['player1'], game['player2'] = "P1", "P2" game['player'] = game['player1'] # P1 goes first #Scores start at 0 game['p1sc'], game['p2sc'], game['gcount'] = 0, 0, 0 wantcustom(game) numplayers(game) setup(game) while game['play'] is True: guessing(game) if __name__ == "__main__": main() This is basically finding a balance between being annoyed by prompts and being annoyed by having to quit and restart. Given the sorts of people who will play this longer than to find out how it works are the sort of people who find spreadsheets and powerpoints and EVE online fun, I'll go with prompts. From duncan.booth at invalid.invalid Mon Dec 1 16:51:21 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Dec 2008 21:51:21 GMT Subject: Why doesn't doc has predifined name and location ? References: <493455AD.4040306@gmail.com> Message-ID: "Chris Rebert" wrote: > Sidenote: what Python projects publish their docs in CHM besides > possibly Win32 GUI programs? Python itself does and, given that chm output is one of the features built in to Sphinx, so can anything which uses reST documentation. From junk.mail.only at lycos.com Thu Dec 4 21:08:51 2008 From: junk.mail.only at lycos.com (junk.mail.only) Date: Thu, 04 Dec 2008 21:08:51 -0500 (EST) Subject: How can I do this (from Perl) in Python? (closures) Message-ID: <20081204210851.HM.0000000000002Ul@junk.mail.only.mail-wwl6.bo3.lycos.com.lycos.com> An HTML attachment was scrubbed... URL: From joemacbusiness at gmail.com Mon Dec 1 15:47:23 2008 From: joemacbusiness at gmail.com (joemacbusiness at gmail.com) Date: Mon, 1 Dec 2008 12:47:23 -0800 (PST) Subject: newbie question: parse a variable inside an RE? Message-ID: Hi All, How do I parse a variable inside an RE? What is the re.search() syntax when your search string is a variable? It's easy to parse hardcoded RE's but not if you use a variable. Here is my code, input and runtime: $ cat test45.py #!/usr/bin/python import re resp = raw_input('Selection: ') newresp = resp.strip() print "you chose ", newresp fname = open('test44.in') for I in fname: # if re.search('^newresp', "%s"%(I)): # returns nothing # if re.search(^newresp, "%s"%(I)): # syntax error if re.search("^newresp", "%s"%(I)): # returns nothing print I, [jmccaughan at dhcppc2 work]$ cat test44.in a1 b1 g1 g2 h1 h4 4g 5g h5 $ python test45.py Selection: g you chose g $ Thanks... From aleksandr.goretoy at gmail.com Tue Dec 30 22:25:15 2008 From: aleksandr.goretoy at gmail.com (alex goretoy) Date: Wed, 31 Dec 2008 03:25:15 +0000 Subject: parsing csv files class In-Reply-To: References: Message-ID: This line doesn't work for me. bufferp is empty afterwards. self.bufferp= [dict(zip(header,line)) for line in reader] needs to be this self.bufferp= [dict(zip(header,line)) for line in self.buffer] after reading from the reader, it becomes empty. Figured maybe someone would find this info useful. Thank you Tim for helping me make my library better. I may need some assistance in another thread about a pycurl library. I want it to fall back to urllib/urllib2 if pycurl is not installed module. look for thread "pycurl urllib fallback" I will post it here shortly to python-list. On Mon, Dec 29, 2008 at 6:15 AM, alex goretoy wrote: > Tim, Thank you for your suggestions that you made. I will modify my class > to what you said. I will also remove find_and_replace. seeing as I won't use > it anywhere else. I think I put it there for some test and forgot to delete > it. I was actually deleting the header outside of the class. This works much > better for me. Any other suggestions are appreciated. Thank you. -A > > > On Sun, Dec 28, 2008 at 5:46 AM, Tim Roberts wrote: > >> "alex goretoy" wrote: >> > >> >class parsercsvy(object): >> > """Return a line from a csv file or total amount of lines""" >> > def __init__(self,file_name=""): >> > self.func_me_color="white_on_black" >> > self.soc=stdout_colours.stdout_colors() >> > self.soc.me_him(['ENTER:',__name__],self.func_me_color) >> > self.filename = file_name >> > self.buffer = [] >> > self.bufferp= [] >> > if string.find(self.filename,"http") != -1: >> > resp=urllib2.urlopen(self.filename) >> > file=resp.read() >> > lfi=len(string.split(self.filename,"/")) >> > filename = "/tmp/"+string.split(self.filename,"/")[lfi-1] >> >> Style issue: unless you are running Python 1.x, you virtually never need >> to import the "string" module. Also, you can always refer to the last >> element of a list or tuple by using [-1]: >> >> parts = self.filename.split( "/" ) >> filename = "/tmp/" + parts[-1] >> >> >> > def parse(self,filename,ret=0): >> > self.soc.me_him(['ENTER:',__name__],self.func_me_color) >> > i = 0 >> > try: >> > reader = csv.reader(file(filename, "rb")) >> > try: >> > for row in reader: >> > self.buffer.append(row) >> > s,a=[],{} >> > >> > for j in range(len(self.buffer[0])): >> > a[self.buffer[0][j]]=row[j] >> > self.bufferp.append(a) >> > i+=1 >> > self.total = i-1 >> >> You might consider keeping the header line separate. >> >> reader = csv.reader(open(filename, "rb")) >> header = reader.next() >> self.buffer = list(reader) >> self.bufferp = [ dict( zip( header, line ) ) for line in reader ] >> self.header = header >> >> Also, you don't really need a separate "total" variable, since it's equal >> to len(self.buffer). >> >> > def total(self): >> > """return total number of lines in csv file""" >> > self.soc.me_him(['ENTER:',__name__],self.func_me_color) >> > >> self.soc.me_him(['RETURN:',self.total,__name__],self.func_me_color) >> > return self.total >> >> There's a problem here, as this was originally written. "self.total" >> starts out being a function (this one here). But after self.parse runs, >> "self.total" will be an integer, and this function is lost. You need to >> decide whether you want users to just access the self.total integer, or >> force them to use the function. In the latter case, you can change the >> counter to self._total. >> >> On the other hand, the self.total counter is unnecessary: >> def total(self): >> return len(self.buffer) >> >> > def find_and_replace(self,li,fi,re): >> > """ >> > find and replace a string inside a string, return list >> > find_and_replace(list,find,replace) >> > """ >> > this=[] >> > for l in li: >> ># found_index=string.find(l,fi) >> > this.append(l.replace(fi,re)) >> > return this >> >> def find_and_replace(self,li,fi,re): >> return [l.replace(fi,re) for l in li] >> >> I'm not sure why this is a member of the class; it doesn't use any of the >> members. >> -- >> Tim Roberts, timr at probo.com >> Providenza & Boekelheide, Inc. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > > -- > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > -- ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Sat Dec 13 15:28:14 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 13 Dec 2008 12:28:14 -0800 (PST) Subject: Python 3.0 crashes displaying Unicode at interactive prompt Message-ID: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> x = u'\u9876' >>> x u'\u9876' # As expected Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> x = '\u9876' >>> x Traceback (most recent call last): File "", line 1, in File "C:\python30\lib\io.py", line 1491, in write b = encoder.encode(s) File "C:\python30\lib\encodings\cp850.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u9876' in position 1: character maps to # *NOT* as expected (by me, that is) Is this the intended outcome? From python.list at tim.thechases.com Mon Dec 15 15:55:59 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 15 Dec 2008 14:55:59 -0600 Subject: Problem accessing a web page In-Reply-To: <47c890dc0812151216o59a3cbc2uf98d74604988d27@mail.gmail.com> References: <47c890dc0812151216o59a3cbc2uf98d74604988d27@mail.gmail.com> Message-ID: <4946C45F.7060100@tim.thechases.com> > I'm able to grab the problem webpage via Python just fine, albeit with > a bit of a delay. So, don't know what your exact problem is, maybe > your connection? When you get the second page, are you getting the same content back that you get if you do a search in your favorite browser? Using just content = urllib.urlopen(url2).read() 'Error' in content # True 'Friedrich' in content # False However, when you browse to the page, those two should be inverted: 'Error' in content # False 'Friedrich' in content # True I've tried adding in the parameters correctly via post params = urllib.urlencode([ ('params.forzaQuery', 'N'), ... ('layout', 'busquedaisbn'), ]) content = urllib.urlopen(url2, data).read() However, this too fails because the underlying engine expects a session ID in the URL. I finally got it to work with the code below: import urllib data = [ ('params.forzaQuery', 'N'), ('params.cdispo', 'A'), ('params.cisbnExt', '8484031128'), ('params.liConceptosExt[0].texto', ''), ('params.orderByFormId', '1'), ('action', 'Buscar'), ('language', 'es'), ('prev_layout', 'busquedaisbn'), ('layout', 'busquedaisbn'), ] params = urllib.urlencode(data) url = 'http://www.mcu.es/webISBN/tituloSimpleDispatch.do;jsessionid=5E8D9A11E4A28BDF0BA6B254D0118262' fp = urllib.urlopen(url, params) content = fp.read() fp.close() but I had to hard-code the jsessionid parameter in the URL. This would have to be determined from the initial call & response of the initial URL (the initial URL returns a element with the URL to POST to, including this magic jsessionid parameter). Hope this helps nudge you (the OP) in the right direction to get what you're looking for. -tkc From akineko at gmail.com Mon Dec 22 17:33:17 2008 From: akineko at gmail.com (akineko) Date: Mon, 22 Dec 2008 14:33:17 -0800 (PST) Subject: 64-bit / 128-bit data element type for array? References: <880c8478-8b40-40e0-8597-aef960612f09@s9g2000prg.googlegroups.com> Message-ID: Hello Robert, > Is that actually a 2s-complement 128-bit unsigned integer, or is it just a > 128-bit-long chunk of data? That is a good question. A 128-bit data can be anything. A 128-bit data can be an instrution code (VLIW machines use such wide instruction). A 128-bit can be a packed ascill (16 chrs). A 128-bit can be a descriptor (a structure of various fields). It is probably safe to say that only unsigned 128-bit is required. (I cannot think of any situations where signed 128-bit is necessary) Hope this answers your question. Aki Niimura On Dec 22, 1:22 pm, Robert Kern wrote: > akineko wrote: > > Hello, > > > bearophile and Robert, thank you for your prompt response. > > I will try NumPy (this is a good execuse to learn and to use a new > > package). > > >> I haven't seen uint128 in the wild, though. > > > Of course, not many applications require uinit128 as a scalar value. > > I may need to deal with 128-bit data as it is now not uncommon to have > > 128-bit data bus (or even 256-bit wide and beyond) in ASICs > > (microchip) design. Unfortunately, some designs use big-endian and > > others use little-endian ... > > Is that actually a 2s-complement 128-bit unsigned integer, or is it just a > 128-bit-long chunk of data? > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco From deets at nospam.web.de Thu Dec 18 10:13:18 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 18 Dec 2008 16:13:18 +0100 Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> <494A5FD1.9050406@wildenhain.de> Message-ID: <6qv7kfFeuf65U1@mid.uni-berlin.de> Neal Becker wrote: > Tino Wildenhain wrote: > >> Neal Becker wrote: >> ... >>>>> So if __str__ is "meant for human eyes", then why isn't print using >>>>> it! >>>> it is: >>>> >>>> > print x >>>> str >>>> >>>> but dict just uses repr() for all its childs to print. >>>> >>>> T. >>> That makes no sense to me. If I call 'print' on a container, why >>> wouldn't it recursively print on the contained objects? Since print >>> means call str, printing a container should recursively call str on the >>> objects. >> >> Every class is free on how to best implement __str__, you will find >> the same behavior on tuple and list as well. >> >> Maybe its discussable to change the implementation sensibly, best if you >> would come with a proposal? Perhaps pprint.pprint is a starting point? >> >> Regards >> Tino > > First, I'd like to know if there is a rationale for the current design. > Am I correct in thinking this is a defect? I don't think so. First of all, there is no "generic" way of printing a collection. And the current implementation tries to give an overview what is contained in the collection, without trying to make it "fancy" - any such thing needed to be hand-coded anyway. Using repr for that is better suited, as for example string keys are printed with quotes around them - making clear what they are, and not irritating the user through potentially contained spaces or even things that look as if they are python objects. For example, if repr *wasn't* used, { "{foo=bar}" : "baz"} would be printed {{foo=bar} : baz} Which is *not* what the dictionary actually contains! The same goes for unicode-objects. They appear with their "funny" characters as \xXX-codes - instead of bailing out on you with unicode-errors. So, IMHO the current behavior is desired. Diez From Slaunger at gmail.com Mon Dec 1 09:01:48 2008 From: Slaunger at gmail.com (Slaunger) Date: Mon, 1 Dec 2008 06:01:48 -0800 (PST) Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> Message-ID: Slaunger wrote: > > class PayloadOnDemand(object): > ? ? """ > ? ? Behaves as a PayloadInstant object, but instantiation is faster > ? ? as only the position of the payload in the file is stored > initially in the object. > ? ? Only when acessing the initially non-existing data attribute > ? ? are the data actually read and the attribure created and bound to > the instance. > ? ? This will actually be a little slower than in PayloadInstant as > the correct file position > ? ? has to be seeked out first. > ? ? On later calls the object has as efficient attribute access as > PayloadInstant > ? ? """ > > ? ? @classmethod > ? ? def read_from_file(cls, f, size): > ? ? ? ? pos = f.tell() > ? ? ? ? f.seek(pos + size) #Skip to end of payload > ? ? ? ? return cls(pos) Extend with ref to file instead: return cls(f, pos) > > ? ? # I probably need some __getattr__ or __getattribute__ magic > # there...?? To answer my own rethorical question I guess I should do something like this def __getattr__(self, attr_name): """ Only called if attr_name is not in the __dict__ for the instance """ if attr_name == 'data': self.__dict__[attr_name] = read_data(self.f, self.file_position) > > ? ? def __init__(self, a_file_position): > ? ? ? ? self.file_position = a_file_position > and then I need to also store a reference to the file in the constructor... def __init__(self, a_file, a_file_position): self.f = a_file self.file_position = a_file_position Have I understood correctly how to to it the on demand way? -- Slaunger From gagsl-py2 at yahoo.com.ar Mon Dec 29 01:19:17 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Dec 2008 04:19:17 -0200 Subject: Cheetah References: Message-ID: En Sun, 28 Dec 2008 15:01:14 -0200, escribi?: > 1. In Cheetah 2.0.1, both from python 2.5.2 and 2.6, after I do a [...] > 2. In reportlab 2.2, when I generate a PDF, no matter how many  s > [...] Better to report those problems to each product authors. -- Gabriel Genellina From geekmail at usenot.de Sun Dec 7 15:00:16 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sun, 7 Dec 2008 21:00:16 +0100 Subject: [OT] [sort of] Malcom Reynolds? Message-ID: <20081207210016.751a33c9@usenot.de> Just found this in the re module's docs: m = re.match(r"(?P\w+) (?P\w+)", "Malcom Reynolds") Does this represent an attempt to phase out the gratuitous Monty Python references in favor of gratuitous Firefly references? Because if so, I'm all for it. Anyways, stuff like that really makes reading documentation fun. /W -- My real email address is constructed by swapping the domain with the recipient (local part). From benjamin.kaplan at case.edu Sun Dec 7 22:25:27 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 7 Dec 2008 22:25:27 -0500 Subject: Python for kids? In-Reply-To: <11a3e492-3c0d-475f-b350-f28351842dad@f3g2000yqf.googlegroups.com> References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> <53f406ed-c261-4d86-a8dc-4001d10d05b5@s20g2000yqh.googlegroups.com> <11a3e492-3c0d-475f-b350-f28351842dad@f3g2000yqf.googlegroups.com> Message-ID: On Sun, Dec 7, 2008 at 8:10 PM, Luis M. Gonz?lez wrote: > This is a very good advice. > I learned from my own experience in college that trying to learn a > solution to a problem I never had, is wasted time. > The first step is confronting your student with an specific problem, > then let him try to find a way to solve it by himself. > After he tried hard many approaches to solving the problem with his > limited knowledge, show him the right way. > This way he will see the light. > > I believe that many teachers don't know this basic concept, and they > simply teach in a mechanical way, without having their students > interested in the subject or without having explained them what > exactly these skills are good for. > > Luis As a current college student, I second that. I have several years of programming experience, but most of my friends are taking Intro Programming this semester (it's a required course for all engineers, not just CS students). They sort of understand the stuff they go over in class, but when they look at their homework problems (and they get very interesting problems. Like stories based off of Pokemon, Stargate, and Lord of the Rings. Not exactly useful, but fun), they're absolutely clueless. > > > On Dec 7, 5:37 pm, bearophileH... at lycos.com wrote: > > On Dec 7, 9:13 pm, "Russ P." wrote: > > > > > I have a 12-year-old son who spends too much time playing Xbox live > > > and watching silly YouTube videos. I would like to try to get him > > > interested in programming. > > > > Lot of people learn to program even before age of 12. > > But I think it's better for you to help him get interest in problem- > > solving and some of the other bases of the mathematic, scientific and > > computational mindset. Once those interests are in place, he will > > probably go looking by himself for things like programming languages, > > math and science (of course at that point a gentle guide toward good > > ideas, good problems to solve, good books to read and good programming > > languages, helps). > > > > Otherwise you risk pushing a person to learn using a tool (programming > > is interesting by itself, but it's mostly a tool still) before having > > any use for such tool or desire to learn it. And this may lead to > > someone with no passion to solve problems and learn. > > > > Bye, > > bearophile > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Fri Dec 5 14:35:41 2008 From: castironpi at gmail.com (Aaron Brady) Date: Fri, 5 Dec 2008 11:35:41 -0800 (PST) Subject: Don't you just love writing this sort of thing :) References: Message-ID: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> On Dec 5, 4:32?am, Lawrence D'Oliveiro wrote: > The code people write is probably a direct reflection of their thinking > processes: For example, slow, plodding, one step at a time, incapable of > imaginative leaps, versus those who operate directly on larger patterns at > once... That distinction operates indirectly on smaller patterns. There are two types of people. Those who can grasp this distinction, and those who cannot. From ajaksu at gmail.com Wed Dec 24 21:43:34 2008 From: ajaksu at gmail.com (ajaksu) Date: Wed, 24 Dec 2008 18:43:34 -0800 (PST) Subject: Easy-to-use Python GUI References: Message-ID: On Dec 24, 9:47?pm, "Joel Koltner" wrote: > ?Dim dlg As UserDialog > > ?dlg.genDrill = 1 > ?ReDim DrillStyle(1) > ?DrillStyle(0) = "All Via Layers In One File" > ?DrillStyle(1) = "One File Per Via Layer" > ?dlg.drillStyle = 1 > > ?func=Dialog(dlg) > > --- > > This is pretty darned easy for me understand and modify either by hand or with > the GUI builder. ?Still, it's quite powerful, since it supports all the common > GUI elements (text, group boxes, checkboxes, drop-down lists, text boxes, > buttons, etc.). ?This is about the level of sophistication I'm looking for. > > Anything like this for Python? I have not used it (yet), but Treethon looks like what you want: --- _import: gtk view: gtk.Window() add: - view: gtk.Button('Hello World') on clicked: print view.get_label() --- Check http://pypi.python.org/pypi/treethon/ and http://code.google.com/p/treethon/ If you can report back on treethon, I'd like to hear about it :) HTH, Daniel From ndbecker2 at gmail.com Mon Dec 1 12:41:24 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Mon, 01 Dec 2008 12:41:24 -0500 Subject: optimization Message-ID: I noticed in some profiling, that it seems that: def Func (): def something(): ... It appears that if Func is called many times, this nested func definition will cause significant overhead. Is this true? I guess I've become accustomed to decent compilers performing reasonable transformations and so have tended to write code for clarity. From dickinsm at gmail.com Thu Dec 18 16:09:03 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 18 Dec 2008 13:09:03 -0800 (PST) Subject: Factoring Polynomials References: <5dfe1cf3-530d-4e31-833e-e26db85611be@d36g2000prf.googlegroups.com> Message-ID: On Dec 18, 8:47?pm, Scott David Daniels wrote: > ? ? ?else: # a single result (discriminant is zero) > ? ? ? ? ?return (-b / (2 * a),) Maybe make that (-b / (2. * a)) to avoid getting funny results when a and b are integers. (Or do a from __future__ import division, or use Python 3.0, or ....) And to make the function more bullet-proof, you might want to do something like (untested): from math import copysign [rest of example as in Scott's post] if discriminant: # two results root1 = (-b - copysign(discriminant, b))/(2*a) root2 = c/(a*root1) return (root1, root2) to avoid numerical problems when b*b is much larger than abs(a*c). Compare with the results of the usual formula when a = c = 1, b = 10**9, for example. But that still doesn't help you when the computation of the discriminant underflows or overflows... Isn't floating-point a wonderful thing! :) Mark From imageguy1206 at gmail.com Tue Dec 9 10:05:48 2008 From: imageguy1206 at gmail.com (imageguy) Date: Tue, 9 Dec 2008 07:05:48 -0800 (PST) Subject: dBase III files and Visual Foxpro 6 files References: Message-ID: <8cf816c5-99c3-41c4-8610-8dbe5a8b8fc3@k1g2000prb.googlegroups.com> On Dec 8, 2:53?am, Ethan Furman wrote: > Greetings All! > > I nearly have support complete for dBase III dbf/dbt files -- just > wrapping up support for dates. ?The null value has been a hindrance for > awhile but I nearly have that solved as well. > > For any who know of a cool dbf module already in existence for dBase III > and Visual Foxpro -- where were you six months ago when I was searching? > ? ;) ?Seriously, though, this has been a great learning experience for me. > > As I said -- dbf/dbt files are 99% ready. ?idx files -- no support: ?for > my purposes I just don't need them. ?I've found no problem in loading > tables up to 300,000 records with 50 fields per record, and re-ordering > them on the fly in memory. > > However, after putting much effort into this code, and wanting it to be > useful to others in the community, are there others who work with dbf > files that would need idx/cdx support? ?Or tables so large they won't > fit comfortably into memory? > > ~ethan~ I occasionally need access to dbf files. In the past I have used the recipe found in the python cookbook on the activestate website. I do not need access to the idx/cdx as I have found that loading the records from the table into memory worked well for me too. If/When you release would enjoy having a peak. g. From mensanator at aol.com Sat Dec 6 12:08:14 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 6 Dec 2008 09:08:14 -0800 (PST) Subject: RELEASED Python 3.0 final References: <874p1jux8u.fsf@benfinney.id.au> <87iqpyt80i.fsf@benfinney.id.au> Message-ID: On Dec 5, 12:29?pm, "Hendrik van Rooyen" wrote: > "Ben Finney" wrote: > >I hereby recommend ?pish and tosh? for use by anyone who wants to > >counter someone's point. It beats by a country furlong the invective > >that has become regrettably common here in recent months. > > I second the motion to use pish and tosh for a first level of disagreement. > > I recommend the rather archaic "Balderdash" as the next step in the > escalation of disagreement... As a W.C. Fields fan, I love his "non-swearing" vocabulary: - Drat - Dag nab it - Holy Mother of Pearl! etc. > > - hendrik From rt8396 at gmail.com Sat Dec 20 19:01:58 2008 From: rt8396 at gmail.com (r) Date: Sat, 20 Dec 2008 16:01:58 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> <59153e28-bf86-4158-96d9-23aa5b9f0205@j35g2000yqh.googlegroups.com> <7889a362-d96e-4f1f-a66b-ef52b9cdb047@q26g2000prq.googlegroups.com> <85f91606-b589-425d-9636-4636c8ccbc4f@r34g2000vbp.googlegroups.com> Message-ID: <6b4176c3-49ce-4e7c-bced-07d8d19bc0f4@s20g2000yqh.googlegroups.com> Just to be on record, i am OK with adding a new way to do this as long as the old C style str format does not ever go away. I don't like 20 ways to do the same thing, but i really like the compact way of %formating now. My complaint is the deprecation of %formating. Maybe i'll use the new syntax to print a tuple or two, but that is the only use i have for it ;). Slowing down Python even more than it is, is suicide. Sure high level languages are slower than there complied brethren, but a line has to be drawn in the sand somewhere. As CPU speeds increase so does the complexity's of modern software. GUI toolkits hog more resources as they need eye pleasing "glass effects". You can't just blindly Parrot off.. "well CPU's get faster every year". Python must stay fast, and simplistic(but not too simplistic), to compete with other high level languages. From tavares at fe.up.pt Tue Dec 9 17:50:18 2008 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Tue, 9 Dec 2008 14:50:18 -0800 (PST) Subject: EURASIP JASP - Special issue on Image Processing and Analysis in Biomechanics - Announce & Call for papers Message-ID: <402605af-3176-4e6c-badd-fb7dc6f0cab5@z27g2000prd.googlegroups.com> ------------------------------------------------------------------------------------------------------------------------------------------ (Apologies for cross-posting) EURASIP Journal on Advances in Signal Processing Special issue on Image Processing and Analysis in Biomechanics http://www.hindawi.com/journals/asp/si/ipab.html Announce and Call for papers We would appreciate if you could distribute this information by your colleagues and co-workers. ------------------------------------------------------------------------------------------------------------------------------------------ Dear Colleague, A critical component for true realistic biomechanical analysis and simulations is to obtain accurately, from images, the geometric data and the behavior of the desired structures. For that, the use of automatic, efficient, and robust techniques of image processing and analysis is mandatory. The main objective of this Special Issue, of the EURASIP Journal on Advances in Signal Processing, on Image Processing and Analysis in Biomechanics is to bring together recent advances in the related fields (not limited to): - Signal processing in biomechanical applications; - Data interpolation, registration, acquisition and compression in biomechanics; - Segmentation of objects in images for biomechanical applications; - 3D reconstruction of objects from images for biomechanical applications; - 2D/3D tracking and object analysis in images for biomechanical applications; - 3D vision in biomechanics; - Biomechanical applications involving image processing and analysis algorithms; - Virtual reality in biomechanics; - Software development for image processing and analysis in biomechanics. Submission Instructions & Important Dates: Authors should follow the journal manuscript format (http:// www.hindawi.com/journals/asp/) and submit their manuscript through the journal Manuscript Tracking System (http://mts.hindawi.com/), according to the following timetable: - Manuscript Due: May 1, 2009; - First Round of Reviews: August 1, 2009; - Publication Date: November 1, 2009. Lead Guest Editor Jo?o Manuel R. S. Tavares, University of Porto, Portugal (tavares at fe.up.pt) Guest Editor R. M. Natal Jorge, University of Porto, Portugal (rnatal at fe.up.pt) From castironpi at gmail.com Sat Dec 13 15:28:22 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 13 Dec 2008 12:28:22 -0800 (PST) Subject: Problems running on HP Intel duo core machine References: <200809221443.25765.inq1ltd@inqvista.com> <200812111458.16157.inq1ltd@inqvista.com> Message-ID: <262d674e-28cc-489b-b058-b7aee9b9172f@o4g2000pra.googlegroups.com> On Dec 11, 3:16?pm, jim-on-linux wrote: > Aaron, > > The TraceBack is : > > TraceBack: > File win32ui.pyc, line 12, in > File win32ui.pyc Line 10, in _load > ImportError: DLL Load Failed: The specified module > could not be found. snip > > Both modules 'win32api.pyd' ?and win32ui.pyd are in > > the same directory. > > > Below is a copy of the win32ui.py module. The only > > difference between this and win32api.py module is > > the name that is installed when creating the path. > > > def __load(): > > ? ? import imp, os, sys > > ? ? try: > > ? ? ? ? dirname = > > os.path.dirname(__loader__.archive) except > > NameError: > > ? ? ? ? dirname = sys.prefix > > ? ? path = os.path.join(dirname, 'win32ui.pyd') > > ? ? #print "py2exe extension module", __name__, > > "->", path > > ? ? mod = imp.load_dynamic(__name__, path) > > ## ? ?mod.frozen = 1 > > __load() > > del __load snip 'load_dynamic' help says this: "(Note: using shared libraries is highly system dependent, and not all systems support it.)" You can try this: create a bare-bones shared library, 'temp_load.pyd' perhaps, place it in the folder, and create 'temp_load.py' there too, as follows: import imp imp.load_dynamic( 'temp_load', 'temp_load.pyd' ) That will tell us if the problem is Python or win32ui. From collin.day.0 at gmail.com Thu Dec 18 14:37:35 2008 From: collin.day.0 at gmail.com (collin.day.0 at gmail.com) Date: Thu, 18 Dec 2008 11:37:35 -0800 (PST) Subject: Factoring Polynomials Message-ID: I am trying to write a simple application to factor polynomials. I wrote (simple) raw_input lines to collect the a, b, and c values from the user, but I dont know how to implement the quadratic equation x = (-b +or- (b^2 - 4ac)^1/2) / 2a into python. Any ideas? From steve at holdenweb.com Mon Dec 22 12:04:48 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 22 Dec 2008 12:04:48 -0500 Subject: Python's popularity In-Reply-To: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: walterbyrd wrote: > I have read that python is the world's 3rd most popular language, and > that python has surpassed perl in popularity, but I am not seeing it. [rest of stuff adequately answered by other posters] The "Python has surpassed Perl" myth came from one month's results on the TIOBE index, which does not claim to use a scientifically justifiable methodology. Python *is* becoming very popular. Training demand is certainly going up. It's a great language for people whose primary career isn't programming but who need to do some programming - for example, there are about 40 scientists and engineers supporting the Mars Lander project using Python code, because it's a great way to put systems together that other engineers can understand. I try to discourage people from getting into language pissing contests, because they are rarely productive. The short answer is that nobody really knows how popular the various languages are, there are simply estimates with higher or lower credibility. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From stefan_ml at behnel.de Tue Dec 30 08:26:37 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 30 Dec 2008 14:26:37 +0100 Subject: Any equivalent to Ruby's 'hpricot' html/xpath/css selector package? In-Reply-To: <4958a2d7$0$15461$426a74cc@news.free.fr> References: <4958a2d7$0$15461$426a74cc@news.free.fr> Message-ID: <495a218d$0$31871$9b4e6d93@newsspool3.arcor-online.net> Bruno Desthuilliers wrote: >> However, what makes it really useful is that it does a good job of >> handling the "broken" html that is so commonly found on the web. > > BeautifulSoup ? > http://pypi.python.org/pypi/BeautifulSoup/3.0.7a > > possibly with ElementSoup ? > http://pypi.python.org/pypi/ElementSoup/rev452 It's actually debatable if BS is any better than lxml/libxml2 when parsing broken HTML, as lxml tends to tidy things up pretty well. The only major difference is in encoding detection, for which you can also use a separate tool like chardet: http://chardet.feedparser.org/ Stefan From rhf22 at mole.bio.cam.ac.uk Mon Dec 8 09:24:59 2008 From: rhf22 at mole.bio.cam.ac.uk (Rasmus Fogh) Date: Mon, 8 Dec 2008 14:24:59 +0000 (GMT) Subject: Rich Comparisons Gotcha Message-ID: Rober Kern wrote: >James Stroud wrote: >> Steven D'Aprano wrote: >>> On Sun, 07 Dec 2008 13:57:54 -0800, James Stroud wrote: >>>> Rasmus Fogh wrote: >>>>>>>> ll1 = [y,1] >>>>>>>> y in ll1 >>>>> True >>>>>>>> ll2 = [1,y] >>>>>>>> y in ll2 >>>>> Traceback (most recent call last): >>>>> File "", line 1, in >>>>> ValueError: The truth value of an array with more than one element is >>>>> ambiguous. Use a.any() or a.all() >>>> I think you could be safe calling this a bug with numpy. >>> Only in the sense that there are special cases where the array >>> elements are all true, or all false, and numpy *could* safely return a >>> bool. But special cases are not special enough to break the rules. >>> Better for the numpy caller to write this: >>> a.all() # or any() >>> instead of: >>> try: >>> bool(a) >>> except ValueError: >>> a.all() >>> as they would need to do if numpy sometimes returned a bool and >>> sometimes raised an exception. >> I'm missing how a.all() solves the problem Rasmus describes, namely that >> the order of a python *list* affects the results of containment tests by >> numpy.array. E.g. "y in ll1" and "y in ll2" evaluate to different >> results in his example. It still seems like a bug in numpy to me, even >> if too much other stuff is broken if you fix it (in which case it >> apparently becomes an "issue"). > It's an issue, if anything, not a bug. There is no consistent > implementation of > bool(some_array) that works in all cases. numpy's predecessor Numeric > used to > implement this as returning True if at least one element was non-zero. > This > works well for bool(x!=y) (which is equivalent to (x!=y).any()) but does > not > work well for bool(x==y) (which should be (x==y).all()), but many people > got > confused and thought that bool(x==y) worked. When we made numpy, we > decided to > explicitly not allow bool(some_array) so that people will not write > buggy code like this again. You are so right, Robert: > The deficiency is in the feature of rich comparisons, not numpy's > implementation of it. __eq__() is allowed to return non-booleans; > however, there are some parts of Python's implementation like > list.__contains__() that still expect the return value of __eq__() to be > meaningfully cast to a boolean. One might argue if this is a deficiency in rich comparisons or a rather a bug in list, set and dict. Certainly numpy is following the rules. In fact numpy should be applauded for throwing an error rather than returning a misleading value. For my personal problem I could indeed wrap all objects in a wrapper with whatever 'correct' behaviour I want (thanks, TJR). It does seem a bit much, though, just to get code like this to work as intended: alist.append(x) print ('x is present: ', x in alist) So, I would much prefer a language change. I am not competent to even propose one properly, but I'll try. First, to clear the air: Rich comparisons, the ability to overload '==', and the constraints (or lack of them) on __eq__ must stay unchanged. There are reasons for their current behaviour - ieee754 is particularly convincing - and anyway they are not going to change. No point in trying. There remains the problem is that __eq__ is used inside python 'collections' (list, set, dict etc.), and that the kind of overloading used (quite legitimately) in numpy etc. breaks the collection behaviour. It seems that proper behaviour of the collections requires an equality test that satisfies: 1) x equal x 2) x equal y => y equal x 3) x equal y and y equal z => x equal z 4) (x equal y) is a boolean 5) (x equal y) is defined (and will not throw an error) for all x,y 6) x unequal y == not(x equal y) (by definition) Note to TJR: 5) does not mean that Python should magically shield me from errors. All I am asking is that programmers design their equal() function to avoid raising errors, and that errors raised from equal() clearly count as bugs. I cannot imagine getting the collections to work in a simple and intuitive manner without an equality test that satisfies 1)-6). Maybe somebody else can. Instead I would propose adding an __equal__ special method for the purpose. It looks like the current collections use the folowing, at least in part def oldCollectionTest(x,y): if x is y: return True else: return (x == y) I would propose adding a new __equal__ method that satisfies 2) - 6) above. We could then define def newCollectionTest(x,y): if x is y: # this takes care of satisfying 1) return True elif hasattr(x, '__equal__'): return x.__equal__(y) elif hasattr(y, '__equal__'): return y.__equal__(x) else: return False The implementations for list, set and dict would then behave according to newCollectionTest. We would also want an equal() built-in with the same behaviour. In plain words, the default behaviour would be identity semantics. Objects that wanted value semantics could implement an __equal__ function with the correct behaviour. Wherever possible __equal__ would be the same as __eq__. This function may deviate from 'proper' behaviour in some cases. All I claim for it is that it makes collections work as intended, and that it is clear and explicit, and reasonably intuitive. Backwards compatibility should not be a big problem. The only behaviour change would be that list, set, and dict would now behave the way it was always assumed they should - and the way the documentation says they should. On the minus side there would be the difference between '__equal__' and '__eq__' to confuse people. On the plus side the behaviour of objects inside collections would now be explicitly defined, and __eq__ and __equal__ would be so similar that most people could ignore the distinction. Some examples: # NaN: # For floats, __equal__ would be the same as __eq__. For NaN this gives >>> x = float('NaN') >>> y = float('NaN') >>> x == x False >>> equal(x,x) True >>> equal(x,y) False # It may be problematical mathematically, but computationally it makes # perfect sense that looking in a given storage location will give you the # same value every time, even if the actual value happens to be undefined. # The behaviour is simple to describe, and indeed NaN does behave this way # in collections at the moment. All we are doing is documenting it clearly. # numpy Numpy would have no __equal__ function, so we would have pure identity semantics - 'equals(x,y)' would be the same as 'x is y' # ordinary numbers. Any Python object with value semantics would need an __equal__ function with the correct behaviour. Mark Dickinson pointed out the thread "Comparing float and decimal", which shows that comparisons between float and decimal numbers do not currently satisfy 3). It would not be attractive to have __equal__ and __eq__ behave differently for ordinary numbers, so if the relevant __eq__ can not be fixed that is a problem for my proposal. At this point I shall try to retire gracefully. Regrettably I am not competent to discuss if this can be done, how it can be done, and how much work is required. Rasmus --------------------------------------------------------------------------- Dr. Rasmus H. Fogh Email: r.h.fogh at bioc.cam.ac.uk Dept. of Biochemistry, University of Cambridge, 80 Tennis Court Road, Cambridge CB2 1GA, UK. FAX (01223)766002 From eric at ericaro.net Thu Dec 18 18:42:10 2008 From: eric at ericaro.net (eric) Date: Thu, 18 Dec 2008 15:42:10 -0800 (PST) Subject: Which sparse matrix package? References: <20081218231851.70dd91e2@Schlamber.localdomain> Message-ID: <1a42d287-aea2-408c-bad5-3c0446a50f8b@y1g2000pra.googlegroups.com> On Dec 18, 11:52?pm, MRAB wrote: > James Mills wrote: > > On Fri, Dec 19, 2008 at 8:18 AM, Martin Manns wrote: > >> Hi: > > > Hi, > > >> I am writing a spreadsheet application in Python > > > What's wrong with pyspread ? > > > [ ... snip ... ] > > >> The dict that I tried out is of the type: > > >> {(1,2,3): "2323", (1,2,545): "2324234", ... } > > >> It is too slow for my application when it grows. One slicing operation > >> with list comprehensions takes about 1/2 s on my computer for 1E6 > >> elements. > > > Let me get this straight. > > It's taking 0.5s to slice your matrix > > of 1E7 (10000000.0 rows/columns) > > > Are you mad ? This is TEN Millions and you > > required it faster than 0.5s ? > > No, 1E6, or ONLY 1 million. :-) what does Internet explorer 6 & 7 have to do with that ? ;-) > > > Am I missing something here ? > > Would a matrix of matrices work better, ie a supermatrix where each > element is either a submatrix of cells or None if the submatrix is > empty? How much memory it would save would depend on how sparse the > matrix is. sparse matrix efficiency is all about guessing the probability for a cell to be empty. My guess is that the probability for a cell (i,j) to be empty grows with norm(i,j) then, you should store your data in a list, and the indexes in another "list", then use a BTree like algorithm, or keep you data ordered by norm(i,j) growing. something like: data = [] # kernel =[] # full of couples (i,j) def add(i,j,value): data.append(value) # or put in the "right place" to keep it sorted kernel.append(i,j) # same comment def get(i,j): k = kernel_of(i,j) return data[k] def set(i,j,value): if is_probably_empty(): k = kernel_of(i,j) if k: data[k]= value else: add(i,j,value) else: add(i,j,value) where the 'kernel_of method" can take advantage of the sorted order (i*j or max(i,j) should be as good) to make a fast dichotomy. The set method is about finding if the cell is 'empty or not' and then either perform an indexof, or a add. to efficiently know if a cell is empty (the is_probably_empty method) or not, try to use the bloom filter using i*j%m as hash function (for instance) here arrays have the size of your actual data (maybe thousands of cell for a huge spreadsheet), that's MUCH better than the size of the maxN*maxM if my memory is correct, there is room in numpy for your own sparse matrix implementation. You should try it with your own sparse matrix implementation. -- Eric http://codeslash.blogspot.com From rdmurray at bitdance.com Wed Dec 17 11:04:42 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Wed, 17 Dec 2008 16:04:42 +0000 (UTC) Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> Message-ID: Quoth walterbyrd : > For a language as well structured as Python, this seems somewhat > sloppy, and inconsistant. Or is there some good reason for this? Yes. It's called Object Oriented Programming. > Here is what I mean: > > def a(): > x = 99 > print x > > def b(): > print x > > a() > b() # raises an exception because x is not defined. > > However in the methods are within a class, the scoping seems to work > differently. > > class ab(): > def a(self): > self.x = 99 > print self.x > def b(self): > print self.x > > i = ab() > i.a() > i.b() # this works, why no lexical scoping? Because x is an attribute. If you don't understand what that means, read any introductory article on OOP. To give you a clue, if you had said: class ab(): def a(self): x = 99 print x def b(self): print x You'd have gotten the exception you expected (assuming x wasn't defined globally). --RDM From bdesth.quelquechose at free.quelquepart.fr Sun Dec 14 11:36:28 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 14 Dec 2008 17:36:28 +0100 Subject: Need help improving number guessing game In-Reply-To: <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> Message-ID: <494543c2$0$1127$426a74cc@news.free.fr> feba a ?crit : > #!/usr/bin/python > #Py3k, UTF-8 > > import random > > def startup(): > print("WELCOME TO THE SUPER NUMBER GUESSING GAME!") > global pnum, play, player, p1sc, p2sc You should now try to rewrite the whole thing to avoid using globals. > pnum = int(input("1 OR 2 PLAYERS?\n> ")) What happens here if you type something that's not a valid argument for int() ? (snip) From rdcollum at gmail.com Sun Dec 28 18:11:53 2008 From: rdcollum at gmail.com (Roger) Date: Sun, 28 Dec 2008 15:11:53 -0800 (PST) Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <0167cbf7$0$6988$c3e8da3@news.astraweb.com> <676bffeb-4b07-4226-8c14-7da57d94351b@f13g2000yqj.googlegroups.com> <3afba310-dcde-4dc1-825a-7c63b97e2a40@w1g2000prk.googlegroups.com> Message-ID: <45cb0c85-ff4d-4f7a-9eeb-ac68f29cd689@k1g2000prb.googlegroups.com> On Dec 28, 5:12?pm, John Machin wrote: > On Dec 29, 7:06?am, Roger wrote: > > > > > > Curious. When I see a bare return, the first thing I think is that the > > > author forgot to include the return value and that it's a bug. > > > > The second thing I think is that maybe the function is a generator, and > > > so I look for a yield. If I don't see a yield, I go back to thinking > > > they've left out the return value, and have to spend time trying to > > > understand the function in order to determine whether that is the case or > > > not. > > > > In other words, even though it is perfectly valid Python, bare returns > > > always make the intent of the function less clear for me. I'm with Bruno > > > -- if you have a function with early exits, and you need to make the > > > intent of the function clear, explicitly return None. Otherwise, leave it > > > out altogether. > > > > -- > > > Steven > > > To me this is the soundest argument. ?Thanks for the advice. ?I think > > I'll follow this as a rule of thumb hereafter. > > Please don't. Follow MRAB's advice, with the corollary that a > generator is forced by the compiler to be a "procedure" in MRAB's > terminology. Yup, this is what I took away from this discussion. Thanks! From trentm at activestate.com Fri Dec 12 18:16:44 2008 From: trentm at activestate.com (Trent Mick) Date: Fri, 12 Dec 2008 15:16:44 -0800 Subject: ActivePython 2.6.1.1 and 3.0.0.0 released! Message-ID: <4942F0DC.7080005@activestate.com> I'm happy to announce that ActivePython 2.6.1.1 and ActivePython 3.0.0.0 are now available. Details and download links for 2.6 here: http://www.activestate.com/Products/activepython/feature_list.mhtml Details and download links for 3.0 here: http://www.activestate.com/Products/activepython/python3.mhtml All ActivePython downloads (e.g. for older releases) are available here: http://downloads.activestate.com/ActivePython/ ActivePython 3.0.0.0 is the first release of ActivePython for Python 3. ActivePython 2.6.1.1 is a patch release based on Python 2.6.1. What is ActivePython? --------------------- ActivePython is ActiveState's binary distribution of Python. Builds for Windows, Mac OS X, Linux, HP-UX and AIX are made freely available. ActivePython includes the Python core and the many core extensions: zlib and bzip2 for data compression, the Berkeley DB (bsddb) and SQLite (sqlite3) database libraries, OpenSSL bindings for HTTPS support, the Tix GUI widgets for Tkinter, ElementTree for XML processing, ctypes (on supported platforms) for low-level library access, and others. The Windows distribution ships with PyWin32 -- a suite of Windows tools developed by Mark Hammond, including bindings to the Win32 API and Windows COM. Note that currently PyWin32 is not included in ActivePython 3.0. See this page for full details: http://docs.activestate.com/activepython/2.6/whatsincluded.html http://docs.activestate.com/activepython/3.0/whatsincluded.html As well, ActivePython ships with a wealth of documentation for both new and experienced Python programmers. In addition to the core Python docs, ActivePython includes the "What's New in Python" series, "Dive into Python", the Python FAQs & HOWTOs, and the Python Enhancement Proposals (PEPs). An online version of the docs can be found here: http://docs.activestate.com/activepython/2.6/welcome.html We would welcome any and all feedback to: ActivePython-feedback at activestate.com.com Please file bugs against ActivePython at: http://bugs.activestate.com/query.cgi?set_product=ActivePython On what platforms does ActivePython run? ---------------------------------------- ActivePython includes installers for the following platforms: - Windows/x86 - Mac OS X - Linux/x86 - Linux/x86_64 ("x86_64" is also known as "AMD64") - Solaris/SPARC - Solaris/SPARC (64-bit) - Solaris/x86 - HP-UX/PA-RISC - AIX/PowerPC Extra Bits ---------- ActivePython releases also include the following: - ActivePython26.chm & ActivePython30.chm: An MS compiled help collection of the full ActivePython documentation set. Linux users of applications such as xCHM might find this useful. This package is installed by default on Windows. Extra bits are available from: http://downloads.activestate.com/ActivePython/etc/ Thanks, and enjoy! Trent, Python Tech Lead -- Trent Mick http://planet.activestate.com/ trentm at activestate.com From tjreedy at udel.edu Mon Dec 29 14:25:27 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Dec 2008 14:25:27 -0500 Subject: why cannot assign to function call In-Reply-To: <97a11245-a034-4558-82d4-0c87e02bdb7e@u18g2000pro.googlegroups.com> References: <97a11245-a034-4558-82d4-0c87e02bdb7e@u18g2000pro.googlegroups.com> Message-ID: John Machin wrote: > On Dec 29, 5:01 pm, scsoce wrote: >> I have a function return a reference, > > Stop right there. You don't have (and can't have, in Python) a > function which returns a reference that acts like a pointer in C or C+ > +. Please tell us what manual, tutorial, book, blog or Usenet posting > gave you that idea, Perhaps the ones claiming that Python is 'call by reference' and hence, by implication, at least, 'return by reference'. > and we'll get the SWAT team sent out straight away. I and others have posted many times that such a viewpoints leads to confusion, such as in this post. tjr From news123 at free.fr Sat Dec 6 13:23:38 2008 From: news123 at free.fr (News123) Date: Sat, 06 Dec 2008 19:23:38 +0100 Subject: Learning Python now coming from Perl In-Reply-To: References: Message-ID: <493ac32b$0$30907$426a74cc@news.free.fr> I fully agree with Roy's answer. COding small tasks is a good starting point. For quite some time you'll be of course less efficient than with your previous language, but that's part of the learning curve, isn't it. I guess you'll learn the syntax rather quickly. What's more painful is to learn which functianilty is in which library and which library exists. There's of course a lot of online documentation, but often you find answers to trivial python questions fastest with Google: for example: search for something like "python string reverse example" And there's of course this newsgroup whenever you're stuck with a 'missing' feature, (though mostly the features aren't missing, but just a little different) bye N Roy Smith wrote: > In article , > Bertilo Wennergren wrote: > >> I'm planning to start learning Python now, using Python 3000. >> I have no previous Python skills, >> . . . > > I assume you use Perl to solve real problems in whatever job you do. My > recommendation would be the next time some problem comes up that you would > normally solve with Perl, try doing it in Python. Having a real task that > you need to accomplish is a great way to focus the mind. For your first > project, pick something that's small enough that you think you could tackle > it in under 50 lines of Perl. > > One of the very first things you'll probably discover that's different > between Perl and Python is how they handle string pattern matching. In > Perl, it's a built in part of the language syntax. In Python, you use the > re module. The regular expressions themselves are the same, but the > mechanism you use to apply them to input text is quite different. From andrew at doadesweb.co.uk Wed Dec 10 14:19:48 2008 From: andrew at doadesweb.co.uk (Andrew Doades) Date: Wed, 10 Dec 2008 19:19:48 +0000 Subject: get todays files In-Reply-To: <494015F7.3020302@tim.thechases.com> References: <4632c353-0462-485b-9e1b-6a5c56682363@s9g2000prg.googlegroups.com> <494015F7.3020302@tim.thechases.com> Message-ID: <49401654.5090505@doadesweb.co.uk> Tim Chase wrote: >> This looks very good and I have tested successfully, but is there a >> way I can set the today to automatically become todays date in that >> format? > > Yes...see the python datetime module[1]...particularly the strftime() > call on date/datetime objects. > > -tkc > > [1] > http://docs.python.org/library/datetime.html Thanks Tim, I got it in there myself. Thanks for all your help with this and the links proved very useful and interesting reads. Andrew From steve at REMOVE-THIS-cybersource.com.au Fri Dec 12 17:40:39 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Dec 2008 22:40:39 GMT Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> Message-ID: <0152dfee$0$8244$c3e8da3@news.astraweb.com> On Fri, 12 Dec 2008 10:08:23 -0600, Kirk Strauser wrote: > At 2008-12-12T15:51:15Z, Marco Mariani writes: > >> Filip Gruszczy?ski wrote: >> >>> I am not doing it, because I need it. I can as well use "if not elem >>> is None", > >> I suggest "if elem is not None", which is not quite the same. > > So what's the difference exactly? "foo is not None" is actually > surprising to me, since "not None" is True. "0 is True" is False, but > "0 is not None" is True. Why is that? "a is not b" uses a single operator to do the test. >>> import dis >>> x = compile('a is not b', '', 'single') >>> dis.dis(x) 1 0 LOAD_NAME 0 (a) 3 LOAD_NAME 1 (b) 6 COMPARE_OP 9 (is not) 9 PRINT_EXPR 10 LOAD_CONST 0 (None) 13 RETURN_VALUE "not a is b" looks like it would use two operators (is, followed by not) but wonderfully, Python has a peephole optimization that fixes that micro inefficiency: >>> x = compile('not a is b', '', 'single') >>> dis.dis(x) 1 0 LOAD_NAME 0 (a) 3 LOAD_NAME 1 (b) 6 COMPARE_OP 9 (is not) 9 PRINT_EXPR 10 LOAD_CONST 0 (None) 13 RETURN_VALUE So if you are using at least Python 2.5, the two expressions don't just return the same result, they actually generate the same byte code. -- Steven From rhamph at gmail.com Mon Dec 22 04:16:30 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 22 Dec 2008 01:16:30 -0800 (PST) Subject: Are python objects thread-safe? References: Message-ID: On Dec 21, 11:51?am, RajNewbie wrote: > Say, I have two threads, updating the same dictionary object - but for > different parameters: > Please find an example below: > a = {file1Data : '', > ? ? ? ?file2Data : ''} > > Now, I send it to two different threads, both of which are looping > infinitely: > In thread1: > a['file1Data'] = open(filename1).read > ? ? ? ? ? and > in thread2: > a['file2Data'] = open(filename2).read > > My question is ?- is this object threadsafe? - since we are working on > two different parameters in the object. Or should I have to block the > whole object? In general, python makes few promises. It has a *strong* preference towards failing gracefully (ie an exception rather than a segfault), which implies atomic operations underneath, but makes no promise as to the granularity of those atomic operations. In practice though, it is safe to update two distinct keys in a dict. From stefan_ml at behnel.de Wed Dec 3 00:54:55 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 03 Dec 2008 06:54:55 +0100 Subject: Reverse zip() ? In-Reply-To: References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> <333edbe80812021647i4621271p7f87dff8d0926951@mail.gmail.com> Message-ID: <49361f2f$0$31333$9b4e6d93@newsspool4.arcor-online.net> Zac Burns wrote: > More succinct failure: > > keys, values = zip(*{}.iteritems()) Simple fix: some_iterable = {}.iteritems() keys, values = zip(*list(some_iterable)) or: keys, values = zip(*(some_iterable if isinstance(some_iterable, (list, tuple)) else list(some_iterable))) Stefan From phil at freehackers.org Mon Dec 1 04:37:05 2008 From: phil at freehackers.org (BlueBird) Date: Mon, 1 Dec 2008 01:37:05 -0800 (PST) Subject: How to distribute a Python app together with its dependencies? References: Message-ID: <35377946-378c-484d-88cc-396145090d2f@l39g2000yqn.googlegroups.com> Alessio Pace wrote: > Hi, > > I have to distribute a Python application which relies on an external > library, and I'm not very fluent in this kind of stuff with Python (I > come from the Java world where I would have used the Maven build tool > to create an "assembly with dependencies" of all it is needed to run > the app), so I was wondering if someone here could give me some > suggestions :-) > > The external library is generally not present on the machines where I > have to distribute my app, and the set of machines on which I have to > distribute this application is not known a priori (it is just known > they are Unix systems). In fact by means of SSH I will have to copy > (and install) the app+library and make it runnable onto the specified > destination(s). I have never used it myself, but bbfreeze claims to create packaged versions of an application, for windows and Unix : http://pypi.python.org/pypi/bbfreeze/0.95.2 cheers, Philippe From de.slotenzwemmer at gmail.com Thu Dec 25 06:56:34 2008 From: de.slotenzwemmer at gmail.com (Dennis van Oosterhout) Date: Thu, 25 Dec 2008 12:56:34 +0100 Subject: os.system('cls') In-Reply-To: <05BADA85-33ED-48BF-B251-2CC830D6D55E@rgbaz.eu> References: <05BADA85-33ED-48BF-B251-2CC830D6D55E@rgbaz.eu> Message-ID: Hello Arno, thanks for the explanation! I have one more question: on the python site it says it's better to replace the system commands by subprocess and Popen. Now I searched for some good example for my specific case (as I have no idea how it should work and I don't get it any clearer by reading http://docs.python.org/3.0/library/subprocess.html#module-subprocess) and I found this: > import subprocess > def clear(): > subProcess.Popen('clear') But it just doesn't seem to work. Would you have any idea how it would work? Once more thanks for the first answer, Devilly 2008/12/25 Python > > On 25 dec 2008, at 11:22, Dennis van Oosterhout wrote: > >> Hi there! I was searching for a way to clear the 'DOS screen'/command screen etc. and found that os.system('cls') works for this. I was just wondering where I can find al the commands which can be used for os.system(). I searched with google but I didn't find an answer. In the official python tutorial it says os.system('command') executes the command, but it doesn't say which commands exist (or I'm just blind). >> >> Does anyone have an answer for this question? >> >> Thanks, >> >> Devilly > > Hey Deville, > > > os.system() executes commands that you usually use in a shell outside python. > so in the case of you being a windows user, you replace 'command' with any DOS > command. > > gr > Arno From sonicsai at gmail.com Tue Dec 23 05:10:04 2008 From: sonicsai at gmail.com (sai) Date: Tue, 23 Dec 2008 02:10:04 -0800 Subject: turtle ? Message-ID: <41d04d600812230210s5b90aa0cud8a3161ca816c80e@mail.gmail.com> python newbie here :-) I am trying to get turtle to run but got stuck here: $ python Python 2.5.2 (r252:60911, Aug 5 2008, 16:17:28) [GCC 4.2.2 20071128 (prerelease) (4.2.2-3.1mdv2008.0)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import turtle Traceback (most recent call last): File "", line 1, in ImportError: No module named turtle I have used google to search the web and the newsgroup but got nothing. The Linux distro is Mandriva, if that makes a difference. sai From paul.hermeneutic at gmail.com Fri Dec 5 10:05:47 2008 From: paul.hermeneutic at gmail.com (Paul Watson) Date: Fri, 05 Dec 2008 09:05:47 -0600 Subject: Running Python 2 and Python 3 on the same machine In-Reply-To: <49387f7e$0$27857$9b622d9e@news.freenet.de> References: <1228424486.5873.6.camel@linux-3eb6.site> <49387f7e$0$27857$9b622d9e@news.freenet.de> Message-ID: <1228489547.5613.10.camel@linux-3eb6.site> On Fri, 2008-12-05 at 02:10 +0100, "Martin v. L?wis" wrote: > > Since the source code is incompatible, I was expecting the Python > > executable to have a new name such as 'python3' > > It does: the executable is called python3.0. > > > or for the default > > source code filename to change to '.py3' or something. > > Such a proposal would be rejected. In a few years from now, Python 2 > will be gone, and we would be stuck with an ugly file extension > (similar to how \windows\system is now an empty directory, and > \windows\system32 actually contains the 64-bit binaries on x64)- > > Regards, > Martin I have to agree with Terry; installing the released python-3.0.msi results in an executable named 'python.exe' in the filesystem. I have not built it yet, but I assume the *NIX package results in a 'python' executable file. For a machine that runs existing Python 2.x applications, what should be in the PATH variable? For *NIX machines, will 'python' be placed into /usr/bin? If so, then the Python scripts that start out with a shebang like the following will have difficulty. #!/usr/bin/python #!/usr/bin/env python Has there been any guidance issued? From nicholas.cole at gmail.com Wed Dec 17 05:01:17 2008 From: nicholas.cole at gmail.com (Nicholas) Date: Wed, 17 Dec 2008 02:01:17 -0800 (PST) Subject: Relative imports in Python 3.0 Message-ID: Imagine a module that looks like ModuleDir __init__.py a.py b.py In python 2.x I used to have tests at the end of each of my modules, so that module b.py might look something like import a .......... .......... if __name__ == '__main__': runtests() But under Python 3.0 this seems impossible. For usual use import a.py has to become the line: from . import a But if I use that form it is no longer possible to run b.py as a standalone script without raising an error about using relative imports. I am sure I am not the first to run into this issue, but what is the solution? Best wishes, Nicholas From rezaee.ayat at yahoo.com Thu Dec 25 00:27:11 2008 From: rezaee.ayat at yahoo.com (Ayat Rezaee) Date: Wed, 24 Dec 2008 21:27:11 -0800 (PST) Subject: contour in python Message-ID: <185369.62211.qm@web45409.mail.sp1.yahoo.com> ?Hello, I need your help, ?I want to make a plot something like this program, ?? import Numeric as N ?? from contour import contour ?? x = N.arange(25) * 15.0 - 180.0 ?? y = N.arange(13) * 15.0 - 90.0 ??? data = N.outerproduct(N.sin(y*N.pi/360.), N.cos(x*N.pi/360.)) contour (data, x, y, title='Example') ?but cant import contour ; so I should install contour or do anythings? send ma a link if it should be installed. ?Best regards, ?Ayat. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sumerc at gmail.com Thu Dec 4 15:36:01 2008 From: sumerc at gmail.com (k3xji) Date: Thu, 4 Dec 2008 12:36:01 -0800 (PST) Subject: Python Runtime Method Call Binding References: <0147f396$0$20670$c3e8da3@news.astraweb.com> <9f2308eb-9eb9-4431-8af7-975c3e054849@e18g2000yqo.googlegroups.com> <493832b1$0$17775$426a34cc@news.free.fr> Message-ID: Thanks for the tips. >3/ Now fact is that even all this won't probably be enough to implement >a robust generic profiler - something which obviously requires a deep >understanding of the language *and* it's implementation. Indeed. Maybe not generic,but with these information at least I can write my specific multi-threaded profiler. All I need to is to rebind the methods/functions in the given modules and guard the callCount and timeElapsed values via locks. And the difficult point here is the timeElapsed information which should also take into account the thread it is running on, I can specifically differentiate the threads by looking at the args[0] parameter which is holding the self instance. Of course for this to work, I need to limit which objects to rebind..etc.etc. Briefly, I think I got what I asked for:) Thanks, From castironpi at gmail.com Mon Dec 29 13:06:56 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 29 Dec 2008 10:06:56 -0800 (PST) Subject: SQL, lite lite lite Message-ID: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> Hi all, About a year ago, I posted an idea I was having about thread synchronization to the newsgroup. However, I did not explain it well, and I really erred on the side of brevity. (After some finagling, Mr. Bieber and I decided it wasn't exactly anything groundbreaking.) But I think the brevity cost me some readers, who might have had more interest. The affair was on the whole discouraging. So, I'm going to try another idea, and assume that readers have some time, and will spend it on it. I don't think relational data can be read and written very easily in Python. There are some options, such as 'sqllite3', but they are not easy. 'sqllite3' statements are valid SQL expressions, which afford the entire power of SQL, but contrary to its name, it is not that 'lite'. To me, 'lite' is something you could learn (even make!) in an afternoon, not a semester; something the size of an ActiveState recipe, or a little bigger, maybe a file or two. If you think SQL is a breeze, you probably won't find my idea exciting. I assume that the basics of SQL are creating tables, selecting records, and updating records. My idea is to create a 'Relation' class. The details are basically open, such as whether to back it with 'sqllite3', 'shelve', 'mmap', or just mapping and sequence objects; what the simplest syntax is that can capture and permit all the basics, and how much and what else can fit in at that level; how and whether it can include arbitrary Python objects, and what constraints there are on them if not; how and whether to permit transactions; and what the simplest and coolest thing you can do with a little Python syntax is. This is basically an invitation for everyone to brainstorm. (No hijackings, good humor & digression ok.) Lastly, ... **warning, spoiler! here's what I thought of already.** **repeat! spoiler! here's what I thought of already.** #Just the select and update syntax: >>> a= people._select( "firstname== 'Joe'" ) #select 'key' from 'people' where 'firstname'== 'joe' >>> a [Entry2864, Entry3076, Entry3172] >>> entry1= a[ 0 ] >>> entry1.phone #select 'phone' from 'people' where 'key'==self.key "555-2413" >>> entry1.phone= "555-1234" #update 'people' set 'phone'= '555-1234' where 'key'==self.key >>> entry1.phone "555-1234" #Create table syntax (a-whole-nother beast in itself): >>> classes= db.Relation( 'class_', 'person', Unique( 'class_', 'person' ) ) #create table 'classes' ( 'key', 'class_', 'person' ) unique ( 'class_', 'person' ) >>> classes._unique( 'class_', 'person' ) >>> classes.class_.noneok= False #'class_' cannot be null >>> classes.person.noneok= False >>> classes._insert( 'Physics', 'Dan' ) >>> classes._insert( 'Chem', 'Tim' ) Hoping-"good critic"-is-self-consistent-ly, hoping-to-hear-it's-too- complicated-already-ly, A. Brady From __peter__ at web.de Fri Dec 19 10:14:21 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2008 16:14:21 +0100 Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <494b5f47$0$17068$6e1ede2f@read.cnntp.org> <494b632b$0$17070$6e1ede2f@read.cnntp.org> <0390fcbc-8100-4aa8-93fa-ad358609ab7b@p2g2000prn.googlegroups.com> Message-ID: Roger wrote: >> either. I'd suggest a plain-python workaround along the lines of > > Wow. You just blew my mind. I'm going to play with this. Thanks a > lot, I've really learned a lot in just that small bit. I don't have > much experience in playing with a lot of the 'private' calls such as > __call__. I need to do some more reading. Here's a non-OO variant: funcs = [] def call(event): for f in list(funcs): # * f(event) root.bind("<1>", call) funcs.append(test) funcs.append(test2) root.bind("<1>", call) def unbind(): print "unbind" funcs.remove(test2) I does the same, but is a bit harder to manage if you have more than one event/widget to deal with. (*) iterating over a copy of the list of functions is slightly more robust as it will not accidentally skip callbacks when the original list is modified during iteration. I suggest that you change the OO version accordingly. Peter From roy at panix.com Tue Dec 9 00:50:26 2008 From: roy at panix.com (Roy Smith) Date: Tue, 09 Dec 2008 00:50:26 -0500 Subject: How to initialize a class variable once References: <707edf86-c223-4cf5-b6ca-a7c396a5edce@t26g2000prh.googlegroups.com> Message-ID: In article <707edf86-c223-4cf5-b6ca-a7c396a5edce at t26g2000prh.googlegroups.com>, alex23 wrote: > You might need to provide some more details about your code. It's going to take me some time to generate a minimal test case. From Afro.Systems at gmail.com Mon Dec 15 13:51:14 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Mon, 15 Dec 2008 10:51:14 -0800 (PST) Subject: os.environ.get('SSH_ORIGINAL_COMMAND') returns None Message-ID: Trying to follow a technique found at bzr I did the following added to ~/.ssh/authorized_keys the command="my_parder" parameter which point to a python script file named 'my_parser' and located in / usr/local/bin (file was chmoded as 777) in that script file '/usr/local/bin/my_parser' I got the following lines: #!/usr/bin/env python import os print os.environ.get('SSH_ORIGINAL_COMMAND', None) When trying to ssh e.g. 'ssh localhost' I get None on the terminal and then the connection is closed. I wonder if anyone have done such or alike in the past and can help me with this. Is there anything I should do in my python file in order to get that environment variable? From vkseashoremack at googlemail.com Sat Dec 20 11:56:02 2008 From: vkseashoremack at googlemail.com (vkseashoremack at googlemail.com) Date: Sat, 20 Dec 2008 08:56:02 -0800 (PST) Subject: teenflood - Free Message-ID: teenflood . . . *******CLICK HERE******** http://club247.cn/teenflood ***************************** . . . . . . . . . . . . teenflood From prologic at shortcircuit.net.au Sun Dec 21 17:27:48 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Dec 2008 08:27:48 +1000 Subject: Are python objects thread-safe? In-Reply-To: References: Message-ID: On Mon, Dec 22, 2008 at 4:51 AM, RajNewbie wrote: > Say, I have two threads, updating the same dictionary object - but for > different parameters: > Please find an example below: > a = {file1Data : '', > file2Data : ''} > > Now, I send it to two different threads, both of which are looping > infinitely: > In thread1: > a['file1Data'] = open(filename1).read > and > in thread2: > a['file2Data'] = open(filename2).read > > My question is - is this object threadsafe? - since we are working on > two different parameters in the object. Or should I have to block the > whole object? I believe (iirc), all basic data types and objects are thread-safe. I could be wrong though - I don't tend to use threads much myself :) cheers James From darcy at druid.net Tue Dec 16 08:44:52 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 16 Dec 2008 08:44:52 -0500 Subject: String slices work only for first string character ? In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF60249410A@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF60249410A@enbmail01.lsi.com> Message-ID: <20081216084452.f1a3002a.darcy@druid.net> On Tue, 16 Dec 2008 13:35:27 +0000 "Barak, Ron" wrote: > Can any one explain why the following string slice works only for the first character, but not for any other ? I think that you need to reread the docs on slices. > print "|"+data[0:1]+"|" > print "|"+data[1:1]+"|" If you want the second character use "data[1:2]". -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From pete.forman at westerngeco.com Tue Dec 16 05:12:32 2008 From: pete.forman at westerngeco.com (Pete Forman) Date: Tue, 16 Dec 2008 10:12:32 +0000 Subject: alt.possessive.its.has.no.apostrophe References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> <49467CE2.3060401@holdenweb.com> <4946826E.7060001@tim.thechases.com> <989de86c-24cc-4ca6-8e9b-82e8ce853c7b@n33g2000pri.googlegroups.com> Message-ID: Aaron Brady writes: > On Dec 15, 11:04?am, Steve Holden wrote: >> Tim Chase wrote: >> > Steve Holden wrote: >> >> This led to a schism between the British and the >> >> newly-independent Americans, who responded by taking the "u" >> >> out of colour, valour, and aluminium. >> >> > Darn Americans and their alminim.... ;-) >> >> > Next thing you know, they'll be putting an I in TEAM.[1] >> >> It's called humour. Or humor. Or incompetence ;-) > > There's an 'I' in Python. There's no 'F' in Python in this thread. -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- the opinion of Schlumberger or http://petef.22web.net -./\.- WesternGeco. From grflanagan at gmail.com Thu Dec 11 03:32:44 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Thu, 11 Dec 2008 09:32:44 +0100 Subject: Mathematica 7 compares to other languages In-Reply-To: <5ebe5a7d-cbdf-4d66-a816-a7d2a0a273c9@40g2000prx.googlegroups.com> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <5ebe5a7d-cbdf-4d66-a816-a7d2a0a273c9@40g2000prx.googlegroups.com> Message-ID: Xah Lee wrote: > On Dec 10, 2:47 pm, John W Kennedy wrote: >> Xah Lee wrote: >>> In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, >>> you'll have 50 or hundreds lines. [...] > > Thanks to various replies. > > I've now gather code solutions in ruby, python, C, Java, here: > > ? A Example of Mathematica's Expressiveness > http://xahlee.org/UnixResource_dir/writ/Mathematica_expressiveness.html > > now lacking is perl, elisp, which i can do well in a condensed way. > It'd be interesting also to have javascript... mmm, stone soup... javascript: var map = function(fn, a) { var b = new Array(a.length); for (i = 0; i < a.length; i++) { b[i] = fn(a[i]); } return b }; var reduce = function(fn, a, init) { var s = init; for (i = 0; i < a.length; i++) { s = fn(s, a[i]); } return s }; var sum = function(a) { return reduce(function(x, y) { return x + y }, a, 0.0) }; var norm = function(a) { var pow = Math.pow; return Math.sqrt(sum(map(function(x) { return pow(x, 2) }, a))) }; var Unit = function(a) { var N = norm(a); return map(function(x) { return x/N }, a) }; From marduk at letterboxes.org Wed Dec 3 17:12:27 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Wed, 03 Dec 2008 17:12:27 -0500 Subject: "as" keyword woes In-Reply-To: <896B75251BA19745A529B1B867893FA50679C6@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA50679C6@planet.delsci.local> Message-ID: <1228342347.29326.62.camel@brotherus.rdu.redhat.com> On Wed, 2008-12-03 at 13:38 -0800, Warren DeLano wrote: > A bottom line / pragmatic question... hopefully not a FAQ. > > Why was it necessary to make "as" a reserved keyword? > > And more to the point, why was it necessary to prevent developers from > being able to refer to attributes named "as"? > > For example, this code breaks as of 2.6 / 3.0: > > Class C: > Pass > > obj = C() > > obj.bs = 2 # valid > > obj.as = 1 # syntax error > > obj.cs = 3 # valid > > Just to be clear: I understand why it breaks, since "as" is now a > keyword, I also know that one can use workarounds such as: > > obj.__dict__['as'] = 1 > > to maintain compatibility. > > What I want to understand is why this parser change was necessary in > order to enable new 2.6/3.0 features. Was this change potentially > avoidable? > > Why can't the parser distinguish between a standalone " as " keyword and > ".as" used as an object/attribute reference? > > Couldn't we have continued along just fine using a smarter parser > without elevating "as" to reserved status (and thus potentially breaking > a 10+ years of existing code)? > > Thank you for enlighting me! > > (Unfortunately, our project may now have to maintain a branch at 2.5.x > in order to preserve compatibility with existing third-party scripts & > infrastructure which routinely rely upon "as" as an object method. > Sigh.) > > Cheers, > Warren The short answer is that "as" is a keyword as of 2.6 (with the introduction of the "with" statement) and to be fair none of the other keywords can be identifiers. Also to be fair, there seems to be warning at least in my version of python 2.5: >>> import sys >>> sys.version_info (2, 5, 1, 'final', 0) >>> class C: ... pass ... >>> obj = C() >>> obj.as = 3 :1: Warning: 'as' will become a reserved keyword in Python 2.6 From yuniyuni21 at gmail.com Wed Dec 10 23:57:08 2008 From: yuniyuni21 at gmail.com (yuniyuni21 at gmail.com) Date: Wed, 10 Dec 2008 20:57:08 -0800 (PST) Subject: density plot Message-ID: Hi, Does anyone know how to make the density plot, more specifically a gaussian-smoothed version of a histogram. Actually, it's not exactly a plot that I want. What I want to do is get the maximum count (or highest peak) of the density distribution. It's different from the probability density function that has the center at zero. In S plus and R, there is the "density" function which I can use to get the max x and y in the frequency distribution. I really appreciate if anyone can help. From rdmurray at bitdance.com Wed Dec 10 18:43:28 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Wed, 10 Dec 2008 18:43:28 -0500 (EST) Subject: forcing future re-import from with an imported module In-Reply-To: References: <533670ae-6d9d-4b10-9156-e41b31b678c7@g17g2000prg.googlegroups.com> Message-ID: On Wed, 10 Dec 2008 at 14:53, _wolf wrote: > thanks for your answer. i am aware that imports are not designed to > have side-effects, but this is exactly what i want: to trigger an > action with `import foo`. you get foo, and doing this can have a side- > effect for the module, in roughly the way that a `from __future__ > import with_statement` changes the interpretation of the current > module (of course, i do not intend to effect syntactic changes---my > idea is to look into the module namespace and modify it). think of it > as ?metamodule programming? (? la metaclass programming). > > maybe import hooks are the way to go? somtimes it would be good if > there was a signalling system that broadcasts all kinds of system > state change. > > cheers & ~flow > > ok so the question is: how to make it so each import of a given module > has a side-effect, even repeated imports? Why can't you have the code that is doing the import subsequently call a function from the module to produce whatever side effect it is you want? Explicit is better than implicit. A python programmer is going to expect that importing a module is idempotent, and breaking that assumption strikes me as a bad idea. Maybe you should give us more details about what problem it is you are trying to solve. There might be a good pythonic way to solve it. --RDM From bj_666 at gmx.net Sun Dec 21 04:49:36 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Dec 2008 09:49:36 GMT Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> Message-ID: <6r6hpfFfb643U3@mid.uni-berlin.de> On Sat, 20 Dec 2008 14:18:40 -0800, cm_gui wrote: >> Seriously cm_gui, you're a fool. >> Python is not slow. > > haha, getting hostile? > python fans sure are a nasty crowd. > > Python is SLOW. > > when i have the time, i will elaborate on this. You are not fast enough to elaborate on Python's slowness!? :-) cm_gui is slow! Ciao, Marc 'BlackJack' Rintsch From ghimire.manoj at gmail.com Thu Dec 18 11:22:17 2008 From: ghimire.manoj at gmail.com (manojghimire) Date: Thu, 18 Dec 2008 08:22:17 -0800 (PST) Subject: mysql with python Message-ID: can anybody give me the link where I can directly download the _mysql.dll file required by MySQLdb for Python 2.6. I tried to build MySQL db but there is error: None. Is there a need for me to step down to Python 2.5 ?? Further any comments on the best ORM for Python ?? From prologic at shortcircuit.net.au Tue Dec 2 18:03:33 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 3 Dec 2008 09:03:33 +1000 Subject: HELP!...Google SketchUp needs a Python API In-Reply-To: References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> Message-ID: You're a funny man r :) Good luck with your endeavours! I have a hard enough time convincing my work colleagues to use anything other than PHP for everything! Here PHP is the Hammer / Pitchfork! --JamesMills On Wed, Dec 3, 2008 at 8:16 AM, r wrote: > OK...so here are the stat's so far. > > 6+BDFL - who would support my crazy idea, or think it -might- be ok > 11 - who are on the fence > 6 - who think this is a complete waste of time, a stupid idea, or just > simply want to kill me > > -> from these stats i can deduce the following: > total_members_comp.lang.python = 14433 > note: I will be fair and remove spammers or members that don't follow > this list anymore by dividing the total number in half.(this should be > generous enough) > total_actual_members = (14433/2) = 7214 > total_num_responders = 11 > > ->current stats: <11> > percentFor = 31 > percentNay = 27 > percentOnFence = 40 > > ->Forecast of turnout: <7214> > potentialFors = 2,236.34 > potentialConverts = 2,885.34 > totalPotentials = 5,121.68 > > even if only 10% of these act...that is 512 people. I still have hope! > > import hope > while hope.amt > 0: > continue > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From simonharrison.uk at googlemail.com Mon Dec 8 06:27:15 2008 From: simonharrison.uk at googlemail.com (simonharrison.uk at googlemail.com) Date: Mon, 8 Dec 2008 03:27:15 -0800 (PST) Subject: Determining whether a variable is less/greater than a range. References: <362ab93b-b804-4ebe-a22f-e422feb301c8@c1g2000yqg.googlegroups.com> Message-ID: On Dec 8, 11:12?am, Tim Chase wrote: > > a = list(range(10, 21)) > > > b = 9 > > > c = 21 > > > How can I find out if b and c have values less or more than the values > > in list a? > > Sounds like a good use for 2.5's addition of the any() and all() > functions -- you don't mention whether you want your variable > compared against *any* of the list items or *all* of the list > items. ?You also don't mention whether you want the comparison > results, or just a single scalar. ?Lastly, you omit the details > of what happens if your target value ("d" below) falls within the > range. ?One of the following should do it for you: > > ? ?>>> a = range(10,21) > ? ?>>> b = 9 > ? ?>>> c = 21 > ? ?>>> d = 15 > ? ?>>> any(b < x for x in a) > ? ?True > ? ?>>> all(b < x for x in a) > ? ?True > ? ?>>> any(c < x for x in a) > ? ?False > ? ?>>> any(d < x for x in a) > ? ?True > ? ?>>> all(d < x for x in a) > ? ?False > ? ?>>> any(c > x for x in a) > ? ?True > ? ?>>> all(c > x for x in a) > ? ?True > ? ?>>> any(d > x for x in a) > ? ?True > ? ?>>> all(d > x for x in a) > ? ?False > > If you just want the comparisons: > > ? ?y1 = [b ? ?y2 = [c ? ?y3 = [d ? ?z1 = [(bx) for x in a] > ? ?z2 = [(cx) for x in a] > ? ?z3 = [(dx) for x in a] > > -tkc Hi Tim. I'm just learning Python at the moment. All I was really wanting was a True or False value which min and max give. a = list(range(10, 21)) b = 9 c = 21 if b < min(a) if c > max(a) The any() and all() functions look useful so thanks for the tips. From darcy at druid.net Sun Dec 7 18:44:13 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sun, 7 Dec 2008 18:44:13 -0500 Subject: how to get a beep, OS independent ? In-Reply-To: <320A8AF5-DF3F-482F-93BE-073C74AA6462@strout.net> References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> <320A8AF5-DF3F-482F-93BE-073C74AA6462@strout.net> Message-ID: <20081207184413.4d9e90f3.darcy@druid.net> On Sun, 7 Dec 2008 12:56:14 -0700 Joe Strout wrote: > On Dec 7, 2008, at 8:48 AM, Grant Edwards wrote: > > What makes you think there is such a thing as "the standard system > > beep"? > > Because OS X (the platform with which I'm most familiar) certainly has > one, and REALbasic has had a "Beep" method for years which works on > all platforms. If RB can do it, we can do it too. It works on all platforms that RB runs on. A rather short list. Certainly a subset of the platforms that Python runs on. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From python.list at tim.thechases.com Fri Dec 12 17:32:08 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 12 Dec 2008 16:32:08 -0600 Subject: Removing None objects from a sequence In-Reply-To: References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> Message-ID: <4942E668.5030100@tim.thechases.com> > If you want to literally remove None objects from a list....(or mutable > sequence) > > def deNone(alist): > n=len(alist) > i=j=0 > while i < n: > if alist[i] is not None: > alist[j] = alist[i] > j += 1 > i += 1 > alist[j:i] = [] > > blist=[None,1,None,2,None,3,None,None,4,None] > deNone(blist) > print(blist) > > # prints [1, 2, 3, 4] ...wouldn't a cleaner way of doing this just be >>> blist=[None,1,None,2,None,3,None,None,4,None] >>> alist = blist >>> blist[:] = [x for x in blist if x is not None] >>> blist [1, 2, 3, 4] >>> alist [1, 2, 3, 4] By using the slice assignment, it leaves the blist referring to the same list-object (as shown by the "alist" bit), and modifying it in place. This reads a lot more cleanly in my estimation. If the data-set is large, in 2.5+, you can just use a generator: blist[:] = (x for x in blist if x is not None) -tkc From mludvig at logix.net.nz Fri Dec 12 05:32:27 2008 From: mludvig at logix.net.nz (Michal Ludvig) Date: Fri, 12 Dec 2008 23:32:27 +1300 Subject: File names, character sets and Unicode Message-ID: <49423DBB.9090401@logix.net.nz> Hi all, is there any way to determine what's the charset of filenames returned by os.walk()? The trouble is, if I pass argument to os.walk() I get the filenames as byte-strings. Possibly UTF-8 encoded Unicode, who knows. OTOH If I pass to os.walk() all the filenames I get in the loop are already unicode()d. However with some locales settings os.walk() dies with for example: Traceback (most recent call last): File "tst.py", line 10, in for root, dirs, files in filelist: File "/usr/lib/python2.5/os.py", line 303, in walk for x in walk(path, topdown, onerror): File "/usr/lib/python2.5/os.py", line 293, in walk if isdir(join(top, name)): File "/usr/lib/python2.5/posixpath.py", line 65, in join path += '/' + b UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1: ordinal not in range(128) I can't even skip over these files with 'os.walk(..., onerror=handler)' the handler() is never called. That happens for instance when the file names have some non-ascii characters and locales are set to ascii, but reportedly in some other cases as well. What's the right and safe way to walk the filesystem and get some meaningful filenames? Related question - if the directory is given name on a command line what's the right way to preprocess the argument before passing it down to os.walk()? For instance with LANG=en_NZ.UTF-8 (i.e. UTF-8 system): * directory is called 'smile?' * sys.argv[1] will be 'smile\xe2\x98\xba' (type str) * after .decode("utf-8") I get u'smile\u263a' (type unicode) But how should I decode() it when running on a system where $LANG doesn't end with "UTF-8"? Apparently some locales have non-ascii default charsets. For instance zh_TW is BIG5 charset by default, ru_RU is ISO-8850-5, etc. How do I detect that to get the right charset for decode()? I tend to have everything internally in Unicode but it's often unclear how to convert some inputs to Unicode in the first place. What are the best practices for dealing with these chraset issues in Python? Thanks! Michal -- * Amazon S3 backup tool -- http://s3tools.logix.cz/s3cmd From clp at rebertia.com Sun Dec 21 19:20:57 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 21 Dec 2008 16:20:57 -0800 Subject: Beep In-Reply-To: References: Message-ID: <47c890dc0812211620h6c19086dhf3a14a662a49fdf6@mail.gmail.com> On Sun, Dec 21, 2008 at 4:16 PM, Jeffrey Barish wrote: > I use sys.stdout.write('\a') to beep. It works fine on Kubuntu, but not on > two other platforms (one of which is Ubuntu). I presume that the problem > is due to a system configuration issue. Can someone point me in the right > direction? Thanks. Is the 'pcspkr' kernel module built and loaded? Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From mail at johnohagan.com Tue Dec 30 09:21:29 2008 From: mail at johnohagan.com (John O'Hagan) Date: Tue, 30 Dec 2008 14:21:29 +0000 Subject: why cannot assign to function call In-Reply-To: <5e807c67-7d97-4b8a-8c5f-a3b97f5c5003@i20g2000prf.googlegroups.com> References: <495867C2.7080807@gmail.com> <5e807c67-7d97-4b8a-8c5f-a3b97f5c5003@i20g2000prf.googlegroups.com> Message-ID: <200812301421.29888.mail@johnohagan.com> On Tue, 30 Dec 2008, Aaron Brady wrote: [...] > On a technicality, to avert a flaming, "change the value of 'b'" is an > ambiguous phrase. There are two interpretations of "change what 'b' > refers to" and "change what 'b' refers to". Even in spoken language, > I don't think that emphasis can resolve them either. > > One means, 'make a change in the world, in the actual configuration of > such and such actual matter.' The other means, 'update the axioms the > speaker is using to communicate to the listeners. (Such and such will > no longer refer to such and such; it will refer to such and such; > accept this and reject that.)' To make an observation, reference is a > purely linguistic phenomenon. > > I, for one, am at a loss for how to disambiguate it. I'm open to > suggestions. I think you've already done so quite clearly. But I suspect the ambiguity centres on the word "change" - in the first interpretation it means "alter" (the object in place), in the second, it more precisely means "exchange" (one object for another). I'd be interested to know to what extent this ambiguity exists in languages other than English - as a somewhat relevant example, ambiguities in English around the verb "to be" ("I am Fred", "I am tall", "I am hungry"; i.e., identity vs. attributes vs. state) disappear in other languages which use different verbs in each case. On a (philosophical) side-note, I wonder if this is a real ambiguity: while the statement that the name "b" now refers to a different object is clear-cut, the other interpretation, that the object itself has changed but is somehow still the same object, is a bit of an ontological minefield. Fortunately, unlike the murky world of philosophy, Python (AIUI) simplifies this question by simply declaring that yes, in the case of mutable objects, we may say that we are still referring to the same object although we've changed it, and no, in the case of immutable objects, we may not, and must exchange it if we want a different "value" (a word too fraught with ambiguity in this context to use unquoted!). The sometimes useful fuzziness of human languages means we don't need to ask, for example, "how tall is the object currently referred to by the name Fred?", but in Python, it helps to understand that this is what's going on. Regards, John From prologic at shortcircuit.net.au Tue Dec 30 17:42:26 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 08:42:26 +1000 Subject: multiprocessing vs thread performance In-Reply-To: <47cfc6de-4b13-4a74-accc-c1d027c44d5a@35g2000pry.googlegroups.com> References: <26f7d44e-552c-41e9-9290-17e5c4e6deb9@q30g2000prq.googlegroups.com> <47cfc6de-4b13-4a74-accc-c1d027c44d5a@35g2000pry.googlegroups.com> Message-ID: On Wed, Dec 31, 2008 at 12:29 AM, Aaron Brady wrote: > James, Hi. I'm glad you asked; I never know how "out there" my > comments are (but surmise that feedback is always a good thing). What > I was thinking was, I didn't know Virtual Synchrony, and I've never > used Erlang, but I'm interested in concurrency especially as it > pertains to units of work, division of labor, and division of context; > and generators are another way to divide context. So: I wanted to put > more of my background and interests on the table. What I said wasn't > directly relevant, I see. But it's not like I > "dissertated" (discussed) the Tibettan-Austrian spice trade. I think > I just want to say stuff about threading! Maybe I'm just excited to > meet people who share my interests... not unheard of. Glad to see others also interested in these topics :) (snip) > 'Circuits' doesn't use generators. I think generators are an > underexplored technique. Is 'circuits' assembly line or start-to- > finish, if my analogy makes any sense? 'Circuits' is event-driven, > but I don't see any difference between 'event-driven' and > multithreaded in general. (I think contrast can create a good picture > and a clear understanding.) What is special about an 'event-driven' > architecture? Are you distinguishing blocking from polling? I'll shortly be releasing circuits-1.0 today hopefully. To answer your question, circuits is inspired by a software architecture that my most favoured lecturer a few years back was teaching. That is: * Behaviour Trees (design) and consequently: * The concept of "everything is a Component" * Systems and Sub-Systems are built upon Components and * Everything is an event. and * An emergent property of such systems are "Behaviour". That being said, circuits employs both an event-driven approach as well as a Component architecture. In your analogy it is both horizontal and vertical. As I continue to develop circuits and improve it's core design as well as building it's ever growing set of Components, I try to keep it as general as possible - my main aim though is distributed processing and architectures. (See the primes example). Thanks for sharing your interest :) cheers James From gagsl-py2 at yahoo.com.ar Wed Dec 17 18:47:54 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 17 Dec 2008 21:47:54 -0200 Subject: Location HTTP Header References: <68fa1e9b-6652-4d34-a7fe-fc98db8bf6d4@m16g2000vbp.googlegroups.com> Message-ID: En Wed, 17 Dec 2008 20:52:42 -0200, ptn escribi?: > I tried this stupid script on my server: > > #! /usr/bin/env python > > print 'Location: http://www.google.com\n' > > and it didn't work, I get a blank page. I first tried the Location > header in another script, and when execution got to that point, it > would > just sort of ignore it, because the script would keep running to the > end > of the code (or stop at some unhandled exception). I assume this is a cgi script. For the Location field to be relevant, the Status should be a 3xx (like 307 Temporary Redirect, or 302 Found) In your case, your server probably has already sent a 200 OK response, so Location is ignored. Try adding a Status line -before Location above- like: print 'Status: 302 Found" > Any ideas? I'd use a different protocol other than CGI... -- Gabriel Genellina From ndbecker2 at gmail.com Mon Dec 15 19:11:27 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Mon, 15 Dec 2008 19:11:27 -0500 Subject: OpenOpt 0.21 (free optimization framework) References: Message-ID: Is it easy_install able? I got: sudo easy_install -U openopt Searching for openopt Reading http://pypi.python.org/simple/openopt/ Couldn't find index page for 'openopt' (maybe misspelled?) Scanning index of all packages (this may take a while) Reading http://pypi.python.org/simple/ Reading http://pypi.python.org/simple/OpenOpt/ Reading http://scipy.org/scipy/scikits/wiki/OpenOpt Best match: openopt [unknown version] Downloading http://pypi.python.org/packages/source/O/OpenOpt/openopt.tar.bz2#md5=6ba26f9083189e7bf49a318de575bc46 Processing openopt.tar.bz2 Running openopt/setup.py -q bdist_egg --dist-dir /tmp/easy_install-rnCH9g/openopt/egg-dist-tmp-jxo557 scikits.openopt 0.18.dev is already the active version in easy-install.pth Installed /usr/lib/python2.5/site-packages/scikits.openopt-0.18.dev-py2.5.egg Sounds like the wrong version? From has.temp3 at virgin.net Mon Dec 8 18:31:57 2008 From: has.temp3 at virgin.net (has) Date: Mon, 8 Dec 2008 15:31:57 -0800 (PST) Subject: Shutdown Mac OSX computer using python References: Message-ID: On 8 Dec, 09:26, H?kan Hagenrud wrote: > Hello, i'm a python noob! > > But I would like to shutdown a 10.5.x mac computer using python (2.5.1) > > this is my code: > #!/usr/bin/python > import SystemEvents > down = SystemEvents.Power_Suite.Power_Suite_Events() > down.shut_down() Avoid Python 2.x's ancient gensuitemodule/aetools modules - they've always been flaky and/or broken on OS X and are completely hosed on Intel Macs. For something this simple, you could just shell out to osascript, avoiding any additional dependencies: import subprocess subprocess.call(['osascript', '-e', 'tell app "System Events" to shut down']) (Note that I wouldn't recommend using 'shutdown' as Wolfgang suggests - while it will shut down your system, it doesn't know anything about the Mac desktop and will unceremoniously kill off all your GUI processes without going through their normal quit procedures.) HTH has -- Control AppleScriptable applications from Python, Ruby and ObjC: http://appscript.sourceforge.net From google at mrabarnett.plus.com Thu Dec 11 18:26:07 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 11 Dec 2008 23:26:07 +0000 Subject: list organization question In-Reply-To: References: Message-ID: <4941A18F.9030209@mrabarnett.plus.com> Robocop wrote: > I have a list of objects, each object having two relevant attributes: > date and id. I'd like not only organize by id, but also by date. > I.e. i would like to parse my list into smaller lists such that each > new mini-list has a unique date, but consists of only objects with a > specific id. Are there any handy imports i could use to accomplish > something like this? I'm relatively new to python and as such don't > know all of the preloaded functions at my disposal. Thanks for any > help in advance, the community here is always ridiculously helpful. > Perhaps you could iterate through the list, building a dict of lists, where the key of the dict is the date. From jerry.carl.mi at gmail.com Sun Dec 28 00:50:09 2008 From: jerry.carl.mi at gmail.com (jerry.carl.mi at gmail.com) Date: Sat, 27 Dec 2008 21:50:09 -0800 (PST) Subject: math module for Decimals References: Message-ID: <251111d8-a48a-45e3-a744-16fdb729fa33@i20g2000prf.googlegroups.com> > Which math functions? ln, log10, exp, sqrt already exist as methods of ? > Decimal instances. At the end of the Decimal docs there are a few ? > examples, including computing sin and cos (but apparently they na?vely use ? > a McLaurin series like you noticed in other module). Hi Gabriel - thanks! For example all goniometric functions are missing. Or the log(x, base). Or rand(). Sure I can spend time trying to put it all together but I thought somebody would have done that already. It seems though that the codes that are out there are not ready - every one of the modules i mentioned above has some issues. Maybe I can put bits and pieces together, but if anyone knows of a well proven module (as is), I would feel much safer using that (again I am not a mathematician and poking into these algorithms makes me feel like trying to fix an automatic transmission). From musiccomposition at gmail.com Wed Dec 17 13:48:05 2008 From: musiccomposition at gmail.com (Benjamin) Date: Wed, 17 Dec 2008 10:48:05 -0800 (PST) Subject: Relative imports in Python 3.0 References: Message-ID: <5fca0c81-cb2d-4fd9-8357-d355a5290ab3@k24g2000pri.googlegroups.com> On Dec 17, 4:01?am, Nicholas wrote: > Imagine a module that looks like > > ModuleDir > ? ? ?__init__.py > ? ? ?a.py > ? ? ?b.py > > In python 2.x I used to have tests at the end of each of my modules, > so that module b.py might look something like > > import a > ?.......... > ?.......... > > if __name__ == '__main__': > ? ?runtests() > > But under Python 3.0 this seems impossible. ?For usual use import a.py > has to become the line: > > from . import a > > But if I use that form it is no longer possible to run b.py as a > standalone script without raising an error about using relative > imports. > > I am sure I am not the first to run into this issue, but what is the > solution? Use absolute imports: from ModuleDir import a > > Best wishes, > > Nicholas From saju.pillai at gmail.com Thu Dec 11 05:36:02 2008 From: saju.pillai at gmail.com (saju.pillai at gmail.com) Date: Thu, 11 Dec 2008 02:36:02 -0800 (PST) Subject: Equivalent of 'wget' for python? References: Message-ID: On Dec 11, 2:36?pm, hrishy wrote: > Hi > > Please excuse my OOP but is my understanding correct > > urllib.urlretrieve(url_of_zip_file,destination_on_local_filesystem) > > is urllib --->Static Class on which the method urlretrieve method is invoked ? No urllib is a "method". Use type(obj) to find out what python thinks the "type" of that object is. Note that "object" here is not meant in the same sense as the OOP definition. > > In that case what does the python 3.0 version mean > > import urllib.request > urllib.request.urlretrieve(url, local_file_name) > > urllib -->static class > request -->method > urlretrieve--> what is this then ? A 'function'. urllib.request.urlretrieve is the fully qualified name of the function urlretrieve. In other words urlretrieve lives in the urllib.request namespace. -srp > > regards > Hrishy > > --- On Mon, 8/12/08, Jerry Hill wrote: > > > From: Jerry Hill > > Subject: Re: Equivalent of 'wget' for python? > > To: python-l... at python.org > > Date: Monday, 8 December, 2008, 5:54 PM > > On Mon, Dec 8, 2008 at 11:53 AM, r0g > > wrote: > > > urllib.urlretrieve(url_of_zip_file, > > destination_on_local_filesystem). > > > In python 3.0, that appears to be: > > > import urllib.request > > urllib.request.urlretrieve(url, local_file_name) > > > -- > > Jerry > > -- > >http://mail.python.org/mailman/listinfo/python-list > > From lewis.sarah93 at yahoo.com Thu Dec 4 23:47:30 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 20:47:30 -0800 (PST) Subject: Reduce Debt Message-ID: <31bbf31b-45f7-4fb3-b9ae-a7700d7b82c8@t3g2000yqa.googlegroups.com> Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From tarundevnani at gmail.com Thu Dec 11 07:28:21 2008 From: tarundevnani at gmail.com (tarun) Date: Thu, 11 Dec 2008 17:58:21 +0530 Subject: Converting c header file to a python file Message-ID: Hello, I am looking for a tool/utility by which can convert c header file to a python file. A typical header file that I want convert looks like: #ifndef __VAR1 #define __VAR1 #define VAR2 "Rev 2" #define VAR3 2L typedef struct { .... .... } #if defined(__cplusplus) || defined(__cplusplus__) extern "C" { #endif And also function declarations Thanks, Tarun -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Sun Dec 7 17:16:27 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 07 Dec 2008 17:16:27 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Rasmus Fogh wrote: > > Can anybody see a way this could be fixed (please)? I may well have to > live with it, but I would really prefer not to. I made a suggestion in my first response, which perhaps you missed. tjr From kyosohma at gmail.com Thu Dec 4 15:59:54 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 4 Dec 2008 12:59:54 -0800 (PST) Subject: Good introductory book? References: Message-ID: <215b15b4-4681-4fd6-b3fe-1de6b845a68a@t2g2000yqm.googlegroups.com> On Dec 3, 8:44?am, "Ken D'Ambrosio" wrote: > Hi, all. ?I'm getting ready to do some projects in Python, and I've cut my > teeth a little bit, but I've found the "Learning|Programming Python" books > from O'Reilly to be more-or-less useless (to my surprise -- I'm usually an > O'Reilly fan). ?I really, really like "Python Essential Reference", but > it's -- well, more of a reference than an intro. ?So, an introductory text > that actually assumes some previous programming experience (as opposed to > "Learning Python" which must be the most slowly-paced programming book > ever) would be terrific. > > Thanks for your suggestions! > > -Ken I liked "Beginning Python" by Hetland. There's also "Python Power!" by Telles, which I think was pretty good. Note that there's not much out for the 3.0 version yet other than the official docs. You'll probably have to wait until next year before much is really written/published about that. Mike From vschmidt13 at gmail.com Mon Dec 8 14:27:31 2008 From: vschmidt13 at gmail.com (Val) Date: Mon, 8 Dec 2008 11:27:31 -0800 (PST) Subject: easy_install of module produces un-importable result Message-ID: I've written my first module, "gpsparser" and uploaded it as an egg to PyPI. I can use easy_istall to install my own module, but when I try to import it I get an ImportError "No module named gpsparser". So I've done some research and found that in my site-packages/ directory gpsparser exists as an egg file, while all the other packages I've installed exist as an egg directory. If this makes any sense, can anyone explain what I've done wrong in building my package that the installation process does not unpack the egg file? Thanks, Val From your.master at gmail.com Thu Dec 11 15:04:01 2008 From: your.master at gmail.com (Brandon) Date: Thu, 11 Dec 2008 12:04:01 -0800 (PST) Subject: dictionary idiom needed References: <383976cf-53fb-48e4-b028-8f568468ce77@r36g2000prf.googlegroups.com> <0c4950c1-4833-40c7-ac19-260b61d5289f@k24g2000pri.googlegroups.com> Message-ID: <7c55c59b-cebe-4f4e-ae40-282ae7e005bf@d42g2000prb.googlegroups.com> Thanks bear - Some outside advice has me looking at nested dictionaries. But I am still bogged down because I've not created one before and all examples I can find are simple ones where they are created manually, not with loops. Maybe a further example: data: POS1 POS2 POS3 ['word1','tagA','tagB'] ['word2','tagC','tagD'] ['word1','tagE','tagB'] ['word1','tagC','tagF'] ... and so on. FWIW: I am guaranteed that the set of tags that may occur in position2 is complementary to the set of tags that may occur in position3. Now I want to get an accounting of all the tags that occurred in position3 in the context of, say, word1. Here I've shown that for word1, tagB and tagF occurs. I want a way to access all this information such that nested_dict['word1']['tagB'] = 2, and nested_dict ['word1']['tagF'] = 1. As I mentioned, I already have dicts such that dictA['word1'] = 3, and dictB['tagB'] = 2. I used defaultdict to build those, and that seems to be causing me to get some funky values back from my initial attempts to build a nested dictionary. I am stumbling at constructing a "for" loop that automatically creates such nested dictionaries. I hope that clears things up. If you still have any advice, it's much appreciated. Thanks, Brandon From gagsl-py2 at yahoo.com.ar Mon Dec 29 22:53:52 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Dec 2008 01:53:52 -0200 Subject: Python in C References: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> <18777.34893.283277.955506@montanaro-dyndns-org.local> Message-ID: En Tue, 30 Dec 2008 00:32:45 -0200, escribi?: > BTW, as a person who hasn't really written a stitch of C++ in about 10 > years > I personally find the CPython implementation to be one of the most > well-organized large pieces of code I have ever encountered. It's much > easier to read (to me) than any significant piece of C++ code I have ever > tried to read. I completely agree. > Here are a few things which might help you understand the code structure > a > bit more: I'd suggest reading object.h too - it describes the Python object system (from the implementation POV). -- Gabriel Genellina From dickinsm at gmail.com Sun Dec 28 09:33:37 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 28 Dec 2008 06:33:37 -0800 (PST) Subject: math module for Decimals References: Message-ID: <41937dc9-4b67-43b5-9eab-6f8c851474cf@p2g2000prn.googlegroups.com> On Dec 28, 12:02?am, jerry.carl... at gmail.com wrote: > I have been looking for a Python module with math functions that would > both eat and spit Decimals. The standard math module eats Decimals > allright but spits floats. Yes: it just converts the input (whether float, int, Fraction or Decimal) to a float using the __float__ method, and then applies the usual float->float maths function. > I tried using the AJDecimalMathAdditions, but ran into issues like dSin > (1E4) would take forever to calculate and would result in sin() > > 1 ... If i understand it correctly, the program is using maclaurin > series to calculate the value and since it does not chop off all the > multiples of 2*pi, the maclaurin approximation becomes useless when > its too far from x=0. Implementing these functions *is* kinda tricky, especially if you want them to be correctly rounded, efficient, and to deal correctly with all the special cases (infinities, nans, ...). But it's far from impossible. sin and cos present particular difficulties for large arguments; probably the range of accepted inputs would have to be restricted for those functions. > (1) what do folks use when they need to calculate something like exp > (sin(Decimal())) or even more complex things? Any recommendations? Or > am I completely missing something? Generally, something other than Python. :) (For example, GP/Pari or MPFR.) I'd like to be able to use Python for this, though. A couple of questions for you (I'm curious what additions would suit your particular use case best): - are you using Decimal for the base-10-ness or the extra precision Decimal provides? Or significant zeros? Or compatibility with existing Decimal code, or what? - what 3 functions would you most like to see added? For me, I think it would be something like sin, cos and atan (or possibly atan2). Once you've got those three, everything else is fairly easy. In particular, atan/atan2 at least gives you access to pi. > (2) Is there any plan to provide a standard python module that would > do that? (Python 4.0? ;-) No, there's no such plan. It's highly unlikely that the Decimal module will grow any extra math functions: it's designed to stick very closely to the IBM standard. It's not impossible that extra Decimal functions could be added in some other module, but it seems fairly unlikely. FWIW, I'm the author of the current Decimal log, log10, exp and pow functions, so I'm probably in a fairly good position to try to implement reasonably high-quality versions of some other elementary functions (again, just as an external addition to the decimal module, not as part of the decimal module itself). This is an itch I've often wanted scratched, as well. I might just have a go.... (Help in the form of code, tests, suggestions, etc. would be welcome!) Mark From cs at zip.com.au Sat Dec 6 23:03:48 2008 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 7 Dec 2008 15:03:48 +1100 Subject: Guido's new method definition idea In-Reply-To: <20081206113000.4da8b7df@usenot.de> Message-ID: <20081207040348.GA21618@cskk.homeip.net> On 06Dec2008 11:30, Andreas Waldenburger wrote: | On 6 Dec 2008 09:18:20 GMT Marc 'BlackJack' Rintsch | wrote: | > On Sat, 06 Dec 2008 09:56:12 +0100, Antoine De Groote wrote: | > [snip reference to "preferably only one way to do it"] | > | > The reason why I'm against that change too. It adds a second, | > alternative way to express something that is already in the language. | > | > > I agree that for newcomers to Python, the class method definition | > > might seem strange. | > | > And after the change it continues to because they will run into | > *both* variants in tutorials, code, and books, so it might be even | > more confusing. | > | I agree with that view. Not much to add to it, just increasing the | weight. Me too. And it smells like Perl if we let the $ get in there. And it doesn't add any facility to the language - it's just syntactic lint. So -1 from me. -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ From dotancohen at gmail.com Wed Dec 10 16:13:05 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 10 Dec 2008 23:13:05 +0200 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: <880dece00812101313j358e3e7dg6a5fe79b6f83dd18@mail.gmail.com> 2008/12/10 : > On Dec 5, 9:51 am, Xah Lee wrote: >> >> For those of you who don't know linear algebra but knows coding, this >> means, we want a function whose input is a list of 3 elements say >> {x,y,z}, and output is also a list of 3 elements, say {a,b,c}, with >> the condition that >> >> a = x/Sqrt[x^2+y^2+z^2] >> b = y/Sqrt[x^2+y^2+z^2] >> c = z/Sqrt[x^2+y^2+z^2] > >> >> In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, >> you'll have 50 or hundreds lines. > > Ruby: > > def norm a > s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) > a.map{|x| x/s} > end If someone doesn't counter with a Python one-liner then I'm going to port that to brainfuck. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-??-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From stephane.chazelas at unicyclist.com Mon Dec 1 06:53:18 2008 From: stephane.chazelas at unicyclist.com (Stephane Chazelas) Date: Mon, 1 Dec 2008 11:53:18 +0000 (UTC) Subject: Python surpasses Perl in popularity? References: <5e87aee0-c7fd-4e9d-befb-0cc01cee64ec@f40g2000pri.googlegroups.com> <49316c95$0$2813$742ec2ed@news.sonic.net> <49322ea2$0$2747$742ec2ed@news.sonic.net> <4933a5ae$0$185$e4fe514c@news.xs4all.nl> Message-ID: 2008-12-01, 08:51(+00), Casper H.S Dik: > Stephane CHAZELAS writes: > >>It's true it was vague and misleading, > >>/bin is not the standard place to look for "sh" as far as the >>"POSIX" standard is concerned. That doesn't mean that standard >>commands (POSIX or not) cannot be found in /bin. But /bin/sh has >>been made a non-standard place for "sh". It's the "legacy" >>place. Those commands that have not undergone non-backward >>compatible changes with POSIX can still be found in /bin, the >>others are to be found in /usr/xpg/bin (for the standard >>versions). > > The proper place is "`getconf PATH`". POSIX doesn't list any > pathnames. > > Of course, the problem is then "where did getconf come from?". [...] Sorry, I was specifically speaking of Solaris 7, 8, 9. "getconf PATH" is not enough, you have to pick the correct getconf, and that getconf be called in the relevant environment. For instance, in later versions of Solaris, I beleive you get /usr/xpg6/bin or /usr/xpg4/bin first depending on the environment. Also, PATH is not necessarily the only thing needed to get you the conformant utilities. See BIN_SH on Tru64, POSIXLY_CORRECT on GNU... I beleive the only thing POSIX requires is that how to get into the proper environment be documented (but it is unspecified). On Solaris, I beleive it's in the standards(5) man page. -- St?phane From steve at holdenweb.com Sat Dec 20 08:20:12 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 20 Dec 2008 08:20:12 -0500 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <06daa32b-aff7-4104-99bb-3cd1365be600@w1g2000prm.googlegroups.com> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> <06daa32b-aff7-4104-99bb-3cd1365be600@w1g2000prm.googlegroups.com> Message-ID: <494CF10C.8010302@holdenweb.com> Mark Summerfield wrote: [...] > > With two dozen postings on my use of English I'm now rather nervous > about the feeback I'll get on my Python 3! > There is no such thing as bad publicity. Quick, make a blog post about how there have been over twenty comments about your use of English (though don't forget to point out that it's correct). > PS Although Amazon.com still says the publication date is the 27th, > they now expect to have it in stock on Monday (the 22nd). Congratulations. I know what a relief it is to see a project of that size come to fruition! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From skip at pobox.com Thu Dec 4 14:33:11 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 4 Dec 2008 13:33:11 -0600 Subject: python an sqlite objects In-Reply-To: <49382153.80604@mrabarnett.plus.com> References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <18742.47391.389709.119341@montanaro-dyndns-org.local> <49382153.80604@mrabarnett.plus.com> Message-ID: <18744.12407.398550.411202@montanaro-dyndns-org.local> >> # Ensure that we're running Python 3 or later. >> import sys >> assert int(sys.version.split()[0].split('.')[0]) >= 3 >> # If there's a better way to chek, please tell. >> MRAB> [snip] MRAB> Why split on whitespace and then '.'? MRAB> assert int(sys.version.split('.')[0]) >= 3 Why split at all? Just use sys.version_info: >>> import sys >>> assert sys.version_info[0] > 2, sys.version_info Traceback (most recent call last): File "", line 1, in ? AssertionError: (2, 4, 5, 'final', 0) vs: >>> import sys >>> print(sys.version_info) (3, 0, 0, 'final', 0) Skip From h0leforfun at gmail.com Wed Dec 17 09:11:45 2008 From: h0leforfun at gmail.com (Hole) Date: Wed, 17 Dec 2008 06:11:45 -0800 (PST) Subject: Python, XML and XPath Message-ID: Hi all, I hope this is not an "overasked" question but I find myself quite confused about python xml management (I have to use python for a project and I come from java world, you know...where frameworks, libraries and tools to use are standard de iure or standard de facto). I need to use XML parsing with xpath: a simple xml reader. I've found that the standard distribution of python doesn't include xpath support modules so I've decided to add libxml2. I've installed cygwin c compiler but I still have errors like the following: C:\Python25\Lib\libxml2-python-2.6.9>python setup.py build install C:\Python25\lib\distutils\dist.py:247: UserWarning: 'licence' distribution option is deprecated; use 'license' warnings.warn(msg) running build running build_py running build_ext building 'libxml2mod' extension writing build\temp.win32-2.5\Release\libxml2mod.def C:\MinGW\bin\gcc.exe -mno-cygwin -shared -s build \temp.win32-2.5\Release\libxml2-py.o build\temp.win32-2.5\Release \libxml.o build\temp.win32-2.5\Release\types.o build \temp.win32-2.5\Release\libxml2mod .def -L/usr\lib -LC:\Python25\libs -LC:\Python25\PCBuild -llibxslt - llibexslt -llibxml2 -lpython25 -lmsvcr71 -o build \lib.win32-2.5\libxmlmods\libxml2mod.pyd build\temp.win32-2.5\Release\libxml2-py.o:libxml2-py.c:(.text+0x1629): undefined reference to `_imp__xmlFree' build\temp.win32-2.5\Release\libxml2-py.o:libxml2-py.c:(.text+0x2802): undefined reference to `_imp__xmlFree' build\temp.win32-2.5\Release\libxml2-py.o:libxml2-py.c:(.text+0x44b2): undefined reference to `_imp__xmlFree' build\temp.win32-2.5\Release\libxml2-py.o:libxml2-py.c:(.text+0x50e4): undefined reference to `_imp__xmlFree' build\temp.win32-2.5\Release\libxml2-py.o:libxml2-py.c:(.text+0x5519): undefined reference to `_imp__xmlFree' build\temp.win32-2.5\Release\libxml2-py.o:libxml2-py.c:(.text+0x7339): more undefined references to `_imp__xmlFree' follow Does anyone know how to solve this issue or has suggestions for another (easy-to-install) xml-xpath library? Thanks for your support! From google at mrabarnett.plus.com Sun Dec 21 14:55:14 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 21 Dec 2008 19:55:14 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: <494E9F22.2000501@mrabarnett.plus.com> r wrote: > I noticed when i mentioned "self" nobody wants to touch that subject. > There could be many reasons why... > > 0.) nobody but the 10 regulars i see here exists > 1.) nobody cares(doubt it) > 2.) nobody is brave enough to question it(maybe) > 3.) most people like to type self over and over again(doubt it) > 4.) most people here have given up on changing the BDFL's mind about > it. (good possibility) > 5.) this is a hot-button topic(no doubt in my mind!) > 6.) nobody here wants to go through that whole discussion yet again From your.master at gmail.com Thu Dec 11 15:06:56 2008 From: your.master at gmail.com (Brandon) Date: Thu, 11 Dec 2008 12:06:56 -0800 (PST) Subject: dictionary idiom needed References: <383976cf-53fb-48e4-b028-8f568468ce77@r36g2000prf.googlegroups.com> Message-ID: <98f99282-811f-4067-9640-81013cea04bc@i18g2000prf.googlegroups.com> > Smells like homework without a particular application. @Scott: Even if that were the case :) I'd still like to figure out how to create nested dictionaries! Brandon From stefan_ml at behnel.de Tue Dec 30 08:28:37 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 30 Dec 2008 14:28:37 +0100 Subject: Any equivalent to Ruby's 'hpricot' html/xpath/css selector package? In-Reply-To: References: Message-ID: <495a2204$0$31871$9b4e6d93@newsspool3.arcor-online.net> Kenneth McDonald wrote: > Ruby has a package called 'hpricot' which can perform limited xpath > queries, and CSS selector queries. However, what makes it really useful > is that it does a good job of handling the "broken" html that is so > commonly found on the web. Does Python have anything similar, i.e. > something that will not only do XPath queries, but will do so on > imperfect HTML? lxml.html is your friend. http://codespeak.net/lxml/lxmlhtml.html Stefan From stefan_ml at behnel.de Fri Dec 5 10:14:35 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 05 Dec 2008 16:14:35 +0100 Subject: Small problem with Psyco In-Reply-To: <1d71a6ed-4d96-4e86-983c-a54e23fcf158@t3g2000yqa.googlegroups.com> References: <1d71a6ed-4d96-4e86-983c-a54e23fcf158@t3g2000yqa.googlegroups.com> Message-ID: <49394559$0$32670$9b4e6d93@newsspool2.arcor-online.net> bearophileHUGS at lycos.com wrote: > I post it here because I am using a Psyco version that was compiled by > people here. > I am using Python 2.6.1, on Win, with Psyco (1, 6, 0, 'final', 0). > > This minimized code: > > from psyco.classes import psyobj > class Bar(psyobj): > def __init__(self, baz): > pass > b = Bar(0) > > Produces: > C:\...\test.py:5: DeprecationWarning: object.__new__() takes no > parameters > b = Bar(0) I noticed that, too, when using Cython to compile a Python class that inherits from object into an extension type that inherits from its C equivalent at the C level. I assume that psyco does something similar here. Stefan From george.sakkis at gmail.com Tue Dec 9 11:31:41 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 9 Dec 2008 08:31:41 -0800 (PST) Subject: How to initialize a class variable once References: <493E5700.4030107@aim.com> Message-ID: <81b8e65d-f80c-4e84-8c50-b3f907b2212a@e6g2000vbe.googlegroups.com> On Dec 9, 10:36?am, Joe Strout wrote: > On Dec 9, 2008, at 4:31 AM, Brian Allen Vanderburg II wrote: > > > There is one situation where a module can be imported/executed ? > > twice, if it is the __main__ module. > > That's an excellent point -- this is something I've run into, and it ? > always feels a bit awkward to code around it. What's the standard ? > idiom for avoiding this issue in a complex app? ?Have a "main" file ? > that is not imported by anything else, and which does little but ? > launch stuff from some other module? Yes, I believe that's the common practice. Still, whenever I end up putting stuff in a "main" file and run into the double import problem (e.g. when pickling), I do an explicit "from main import *" after all the definitions, i.e.: # myscript.py __all__ = ['foo', 'Bar'] def foo(x,y): ... class Bar(object): .... from myscript import * if __name__ == '__main__': assert foo.__module__ == Bar.__module__ == 'myscript' George From bj_666 at gmx.net Wed Dec 24 03:30:41 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Dec 2008 08:30:41 GMT Subject: Strategy for determing difference between 2 very large dictionaries References: <1230102996.2303.1291616055@webmail.messagingengine.com> Message-ID: <6rea9hF16p8tU1@mid.uni-berlin.de> On Wed, 24 Dec 2008 03:23:00 -0500, python wrote: > Hi Gabriel, > > Thank you very much for your feedback! > >> k1 = set(dict1.iterkeys()) > > I noticed you suggested .iterkeys() vs. .keys(). Is there any advantage > to using an iterator vs. a list as the basis for creating a set? I > understand that an iterator makes sense if you're working with a large > set of items one at a time, but if you're creating a non-filtered > collection, I don't see the advantage of using an iterator or a list. > I'm sure I'm missing a subtle point here :) `keys()` creates a list in memory, `iterkeys()` does not. With ``set(dict.keys())`` there is a point in time where the dictionary, the list, and the set co-exist in memory. With ``set(dict.iterkeys())`` only the set and the dictionary exist in memory. Ciao, Marc 'BlackJack' Rintsch From metolone+gmane at gmail.com Sat Dec 6 17:52:04 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 6 Dec 2008 14:52:04 -0800 Subject: operators as variables References: <103920.71204.qm@web26006.mail.ukl.yahoo.com> Message-ID: "macc_200" wrote in message news:103920.71204.qm at web26006.mail.ukl.yahoo.com... > Hi, > just starting programming and have an elementary question > after playing around with lists but cannot find >the answer > with googling. > I have a list of variables and I would like some of those > variables to be integers and some to be operators so the > list would look something like [5 * 4 - 4 + 6] and then be > able to evaluate the result (i.e. get 10). How do you make > the interpreter see the operator as that instead of a string > and just echo the list back to me. > thanks, > Andy > (and suggestions for a decent Python book would be appreciated) See the operator module, and then check out pyparsing. -Mark From joe at strout.net Thu Dec 4 10:50:06 2008 From: joe at strout.net (Joe Strout) Date: Thu, 4 Dec 2008 08:50:06 -0700 Subject: simplest way to strip a comment from the end of a line? Message-ID: I have lines in a config file which can end with a comment (delimited by # as in Python), but which may also contain string literals (delimited by double quotes). A comment delimiter within a string literal doesn't count. Is there any easy way to strip off such a comment, or do I need to use a loop to find each # and then count the quotation marks to its left? Thanks, - Joe From vkseashoremack at googlemail.com Sat Dec 20 11:56:11 2008 From: vkseashoremack at googlemail.com (vkseashoremack at googlemail.com) Date: Sat, 20 Dec 2008 08:56:11 -0800 (PST) Subject: Dog Penis - Free Message-ID: <1b4417a3-6f7c-4c3c-9d59-60c12256163a@i20g2000prf.googlegroups.com> Dog Penis . . . *******CLICK HERE******** http://club247.cn/Dog-Penis ***************************** . . . . . . . . . . . . Dog Penis From n.kottiyath at gmail.com Wed Dec 24 13:15:29 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Wed, 24 Dec 2008 10:15:29 -0800 (PST) Subject: Iterating over objects of a class References: <2df27de3-7fa3-4ac9-acd9-f946939517cf@r37g2000prr.googlegroups.com> <6rfb7iF1fg5rU1@mid.uni-berlin.de> Message-ID: <65c317f6-4fb8-4d54-a811-9a3fff50a690@p2g2000prf.googlegroups.com> On Dec 24, 10:52?pm, "Diez B. Roggisch" wrote: > Kottiyath schrieb: > > > Hi, > > ? ?How can I iterate over all the objects of a class? > > ? ?I wrote the code like following: > > class baseClass(object): > > Consider adopting PEP 8 ?coding conventions. > > > > > ? ? __registry = [] > > > ? ? def __init__(self, name): > > ? ? ? ? self.__registry.append(self) > > ? ? ? ? self.name = name > > > ? ? def __iter__(self): > > ? ? ? ? baseClass.item = 0 > > ? ? ? ? return self.__registry[0] > > > ? ? def next(self): > > ? ? ? ? if baseClass.item >= len(self.__registry): > > ? ? ? ? ? ? raise StopIteration > > ? ? ? ? baseClass.item += 1 > > ? ? ? ? return self.__registry[baseClass.item - 1] > > > For testing, create the following objects- > > a = baseClass("Test1") > > b = baseClass("Test2") > > > class subClass (baseClass): > > ? ?pass > > c = subClass("Test3") > > > ---->Actual Iteration<---- > > for i in a: > > ? ? print i.name > > > Test1 > > Test2 > > Test3 > > > --------------------------------------------------- > > I see the following problems in the code: > > 1. I have to iterate over any of the objects. For correctness, I > > wanted to iterate over the class, like > > for i in baseClass(): > > ? ?do x > > but that will will create one more object - which I do not want. > > > 2. If the subclass wants to do somethings in its constructor, I am not > > sure how to update the registry. > > class subClass (baseClass): > > ? ?def __init__(self, name): > > ? ? ? ?**do something** > > ? ? ? ?super.init(self, name) ?----> This errors out, saying it needs > > super, not subClass > > You don't show the actual traceback, however the idiom for invoking > super for new-style-classes is > > super(subClass, self).__init__(name) > > for your case. > > > Another method I thought of implementing it was using generators - > > where-in baseClass.objects() is a generator which will yield the > > objects one by one - but even then the second issue remains. > > If somebody can help me out, I would be very thankful. > > Using a generator or not isn't the issue here. > > What you need is a *class*-based access, not instance-based. There are > various methods to accomplish this. The simplest is to ditch the > obnoxious __registry as name, and just do > > class BaseClass(object): > > ? ? REGISTRY = [] > > Then iterating is a simple matter of > > for instance in BaseClass.REGISTRY: > ? ? ... > > Case solved. Alternatively, if you insist on the concept of privacy for > that registry, you can use a classmethod: > > class BaseClass(object): > > ? ? @classmethod > ? ? def registry(cls): > ? ? ? ? for i in cls.__registry: > ? ? ? ? ? ? yield i > > Last but not least you *could* go for a __metaclass__ with an > __getitem__-method, that makes thinks look fancy because you then can do: > > for instance in BaseClass: > ? ? ?... > > I leave it as an exercise to you - gotta go christmas dining now :) > > Diez Thank you Very much, Diez. I was able to do the Generator and the super part of it, but I never even thought of the metaclass option. I will try it out. Thank you very much. Merry Christmas. P.S - >Also, I will use the PEP 8 coding conventions From nospam at forMe.thks Wed Dec 17 11:35:13 2008 From: nospam at forMe.thks (Ross) Date: Wed, 17 Dec 2008 11:35:13 -0500 Subject: Managing timing in Python calls In-Reply-To: References: Message-ID: Interesting stuff - I hadn't come across the 'with' syntax before, so I've learned something already. I was briefly excited to learn about the callLater command which is just a convenience class for the wxTimer class. It seems to be pretty much a parallel of the var t = window.setTimeout( function () { do_when_timed_out} sort of thing in AJAX. However, as is well grumbled on the 'net, you can't use wxTimer from a non-main thread. So that dropped off my plate. But getting my head around my AJAX problem versus my python implementation, I realized my use of those javascript structures were really just used because javascript doesn't allow any threading at all. With Python, just having my other processing path in a thread is enough, and I can use the brutish time.sleep() function, without worrying about blocking the processing of my mainline (UI) thread. So I'm able to proceed. I do want to know more about the 'with' command tho' so I'll look into that. Thx again. Ross. cmdrrickhunter at yaho.com wrote: > I believe WxTimerEvent is handled using the event queue, which isn't > going to do what you want. An event which goes through the queue does > not get processed until you return to the queue. > > What you want to do is actually a rather difficult task to do > generically. Should the task be interrupted immediately? Or is a > tiny latency acceptable? Should the function being terminated get to > handle its own termination? Or should the termination be forced on > it. What sort of overhead is acceptable for this "set_timeout" > behavior? > > I would not be surprised if there isn't a built in solution, because > its so hard, but rather built in tools which can be used to do it. > > If your timeouts are on the order of seconds, you might be able to > just check time.time() at the begining, and compare it to the current > time later in the function. This could be on the main thread or on a > worker thread. > > If you need better handling, you may want to look at how condition > variables and such work. > > Finally, thread has a function to send a Keyboard Interrupt to the > main thread. I believe you could do your work on the main thread, and > catch the interrupt. > > "Background" tasks are not easy to implement in any language (other > than perhaps AJAX ;-) ). > > Remember, Python does not support truly simultaneous threads. It > actually does timeslices of about 100 operations. Any solution you > choose should work given this information. > > And as for a "nicer" construct, I personally just learned of how to > handle the "with" command. I could see something like > > class Timeout: > def __init__(self, t): > self.t = t > def __enter__(self): > self.start = time.time() > def __exit__(self, x, y, z): > return None > def __nonzero__(self): > return time.time() - self.start <= self.t > > > def doSomethingLong(timeout = True): # true guarentees bailout never > occurs > while timeout: > doAnIteration() > > with Timeout(3) as t: > doSomethingLong(t) > > > > and have your Timeout class have a flag which it sets when > doSomethingLong needs to bail out, using whatever method is "best" for > your particular application. This is, of course pseudocode - I've not > run it through python msyself. Hopefully any errors are obvious > enough that you can work around them. From cournape at gmail.com Mon Dec 29 22:35:45 2008 From: cournape at gmail.com (David Cournapeau) Date: Tue, 30 Dec 2008 12:35:45 +0900 Subject: print a vs print '%s' % a vs print '%f' a In-Reply-To: References: <5b8d13220812291919h700f1586q5ab68ec6edb927f1@mail.gmail.com> Message-ID: <5b8d13220812291935i1a8de1e2h9ee08e9e668f9cad@mail.gmail.com> On Tue, Dec 30, 2008 at 12:23 PM, James Mills wrote: > On Tue, Dec 30, 2008 at 1:19 PM, David Cournapeau wrote: > (... snip ...) > >> print '%f' % a # -> print '1.#INF' > > Would this not be controlled by: > 1. float(a) or a.__float__() > 2. tp_print Bah, I made a mistake in my example: complex('inf') should read float('inf') (complex('inf') does not work). So 1 is out :) If I read correctly the code, tp_print also calls the format_float function (as tp_str, and tp_repr), so it looks like it is not used in that case. cheers, David From rtw at freenet.co.uk Tue Dec 30 21:49:41 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Tue, 30 Dec 2008 20:49:41 -0600 Subject: Triple quoted string in exec function ? References: <016abfa1$0$6988$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote in news:016abfa1$0$6988$c3e8da3 at news.astraweb.com in comp.lang.python: > On Tue, 30 Dec 2008 15:35:28 -0600, Rob Williscroft wrote: > >> Stef Mientki wrote in news:mailman.6399.1230668197.3487.python- >> list at python.org in comp.lang.python: >> >>>>> And, by the way, exec is a *statement*, not a function! >>>>> >>> exec ( Init_Code, PG.P_Globals ) >>> >>> I've really doubt that this is a statement, unless I don't understand >>> what a statement is. >>>>> >>>>> >>> >> In python 2.x the above is a statement that is passed a tuple: >> >> http://docs.python.org/reference/simple_stmts.html#exec > > > The documentation doesn't say anything about it accepting a tuple as an > argument. The tuple argument works in both 2.5 and 2.6. Curious. > My mistake, it is also behaving as a function: http://docs.python.org/dev/3.0/whatsnew/3.0.html#removed-syntax Removed keyword: exec() is no longer a keyword; it remains as a function. (Fortunately the function syntax was also accepted in 2.x.) Also ... Though that was the only documentation of it I found in a brief web search. > I was also surprised by this behaviour: > >>>> g, l = {}, {} # no globals, no locals >>>> exec "x = 1" in g, l >>>> l > {'x': 1} >>>> g.keys() > ['__builtins__'] > > I see *now* that this is documented: > > "...the current implementation MAY add a reference to the dictionary of > the built-in module __builtin__ under the key __builtins__ (!)." > [emphasis added] > > but it's still rather disconcerting. That means that: > > exec "some potentially dangerous code" in {}, {} > > isn't as safe as I thought it was. AIUI it isn't meant to be safe, it provides some data hiding that is useful for programming purposes but isn't much use for security. Another example of a security hole: >>> def f(): ... print "f()" ... >>> exec "from __main__ import f; f()" f() >>> Rob. -- http://www.victim-prime.dsl.pipex.com/ From venutaurus539 at gmail.com Wed Dec 3 23:43:52 2008 From: venutaurus539 at gmail.com (venu madhav) Date: Thu, 4 Dec 2008 10:13:52 +0530 Subject: Obtaining SMTP address of a sender and receiver of an outlook mail In-Reply-To: References: Message-ID: Hi, I don't have access to the AD server because only the administrators here have those rights. Aren't there any MAPI Sender and Recipient object properties which satisfies my need? Thank you, Venu. On Thu, Dec 4, 2008 at 9:00 AM, BJ Swope wrote: > If you have access to the AD server that hosts those DNs you can use > python's ldap module to retrieve the smtp attribute for the DN you've just > parsed from the message. > > On Wed, Dec 3, 2008 at 2:06 AM, venutaurus539 at gmail.com < > venutaurus539 at gmail.com> wrote: > >> Hi all, >> I am trying to use python for extracting contents of an outlook >> email. For extracting the list of Recipients addresses I tried using >> the "MAPI.message.Recipients.Address" property, but the problem I am >> facing is that it is giving the complete DN name which is putting me >> in further complications. Is there any way to obtain the actual SMTP >> mail address (username at domain.com) from the above object? I searched >> for it in the MSDN help but couldn't succeed. >> >> Thanks in advance, >> Venu >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From arkanes at gmail.com Thu Dec 11 13:34:03 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 11 Dec 2008 12:34:03 -0600 Subject: Is 3.0 worth breaking backward compatibility? In-Reply-To: <4731f7cf-ef15-4328-85a4-de4437009f2e@40g2000prx.googlegroups.com> References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> <20081207203553.7d62434a@usenot.de> <4731f7cf-ef15-4328-85a4-de4437009f2e@40g2000prx.googlegroups.com> Message-ID: <4866bea60812111034t6dd4f204ka236835812ba9e5a@mail.gmail.com> On Thu, Dec 11, 2008 at 12:21 PM, walterbyrd wrote: > On Dec 7, 12:35 pm, Andreas Waldenburger wrote: > >> Pleeeeze. Python 3 is shipping now, and so is 2.x, where x > 5. Python >> 2 is going to be around for quite some time. What is everybody's >> problem? > > A possible, potential, problem, could arise if you were using python > 2.x, but some other code, that you wanted to include, was writen in > python 3.x. A possible, potential, problem, could arise if you were using [Java], but some other code, that you wanted to include, was writen in [Pascal]. Surely the software industry is doomed? From castironpi at gmail.com Mon Dec 8 15:01:42 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 8 Dec 2008 12:01:42 -0800 (PST) Subject: var or inout parm? References: Message-ID: On Dec 7, 2:54?am, m... at pixar.com wrote: > How can I make a "var" parm, where the called function can modify > the value of the parameter in the caller? > > def f(x): > ? ? x = x + 1 > > n = 1 > f(n) > # n should now be 2 You can't. 'n' would need a 'set_to' method, which it doesn't have. Otherwise, that's not what the equal sign does. From martin at v.loewis.de Thu Dec 4 20:10:22 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 05 Dec 2008 02:10:22 +0100 Subject: Running Python 2 and Python 3 on the same machine In-Reply-To: <1228424486.5873.6.camel@linux-3eb6.site> References: <1228424486.5873.6.camel@linux-3eb6.site> Message-ID: <49387f7e$0$27857$9b622d9e@news.freenet.de> > Since the source code is incompatible, I was expecting the Python > executable to have a new name such as 'python3' It does: the executable is called python3.0. > or for the default > source code filename to change to '.py3' or something. Such a proposal would be rejected. In a few years from now, Python 2 will be gone, and we would be stuck with an ugly file extension (similar to how \windows\system is now an empty directory, and \windows\system32 actually contains the 64-bit binaries on x64)- Regards, Martin From mcrute at gmail.com Thu Dec 4 19:46:06 2008 From: mcrute at gmail.com (Michael Crute) Date: Thu, 4 Dec 2008 19:46:06 -0500 Subject: Importing Version Specific Modules In-Reply-To: <18744.30436.32591.969670@montanaro-dyndns-org.local> References: <558b73fb0812041529g313a27bpcfd09fc90f474f6e@mail.gmail.com> <18744.30436.32591.969670@montanaro-dyndns-org.local> Message-ID: <558b73fb0812041646r669accc3q293adeb0cac10262@mail.gmail.com> On Thu, Dec 4, 2008 at 7:33 PM, wrote: > Michael> try: > Michael> from string import Template > Michael> except ImportError: > Michael> from our.compat.string import Template > > This is "easier to ask forgiveness than permission" (EAFP). This tends to > be more Pythonic (and thus, preferred). You don't *really* care what the > version just, but whether or not the string module has a Template object. > Besides, what if some bright admin at some customer decides to backport the > Template implementation to their 2.4 installation? The first form would > load your compatibility version, probably not what they were hoping when > they put in the effort to backport. That was the kind of reasoning I'm looking for. I'll stick with the pythonic try/except approach then. -mike -- ________________________________ Michael E. Crute http://mike.crute.org God put me on this earth to accomplish a certain number of things. Right now I am so far behind that I will never die. --Bill Watterson From ajaksu at gmail.com Tue Dec 23 16:57:37 2008 From: ajaksu at gmail.com (ajaksu) Date: Tue, 23 Dec 2008 13:57:37 -0800 (PST) Subject: python3 urlopen(...).read() returns bytes References: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> <5496b34d-7ce4-4281-9f01-aed12dab9fd3@f33g2000vbf.googlegroups.com> <42ad842c-8d8a-4ff5-a721-0688b7ae20f7@41g2000yqf.googlegroups.com> Message-ID: <9d0248cc-6ba3-44f8-a60a-e5565b7d20ab@f11g2000vbf.googlegroups.com> On Dec 23, 12:51?pm, Christian Heimes wrote: > If you want to do it right ... It should be a clean patch against the > py3k svn branch including documentation and a unit test. Got all three at http://bugs.python.org/issue4733 . Probably got all three wrong too, so any feedback is very welcome :) I think a neat improvement, besides better docs, names, code, etc., would be to implement Carl Bank's idea of checking Content-Encoding. Oh, and there's a 'print("Using default charset '%s'" % response.charset)' in there that seemed educational when I wrote it, but now sounds lame :) Glenn, can you test the patch[1] there? Thanks for the encouragement, Chris! I hope we don't regret it :D Daniel [1]http://bugs.python.org/file12437/urlopen_text.diff From sjmachin at lexicon.net Sun Dec 28 17:02:03 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 28 Dec 2008 14:02:03 -0800 (PST) Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <0167cbf7$0$6988$c3e8da3@news.astraweb.com> <088c7d93-e87f-44a0-9ea7-faa7feded7df@a26g2000prf.googlegroups.com> Message-ID: <67f19f31-8554-416c-bf75-344ed12493b0@e1g2000pra.googlegroups.com> On Dec 29, 8:36?am, Benjamin wrote: > On Dec 28, 1:35?pm, Steven D'Aprano > cybersource.com.au> wrote: > > The second thing I think is that maybe the function is a generator, and > > so I look for a yield. > > You shouldn't, though; Generators can't contain any return statement. What gave you that impression? Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def foo(): ... for i in range(4): ... yield i ... return ... >>> foo >>> x = foo() >>> x >>> list(x) [0, 1, 2, 3] >>> def bar(): ... for i in range(4): ... yield i ... return 42 ... File "", line 4 SyntaxError: 'return' with argument inside generator (go to http://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy then scroll down) Generator functions A function or method which uses the yield statement (see section The yield statement) is called a generator function. Such a function, when called, always returns an iterator object which can be used to execute the body of the function: calling the iterator?s next() method will cause the function to execute until it provides a value using the yield statement. When the function executes a return statement or falls off the end, a StopIteration exception is raised and the iterator will have reached the end of the set of values to be returned. From BrianVanderburg2 at aim.com Wed Dec 17 07:38:38 2008 From: BrianVanderburg2 at aim.com (Brian Allen Vanderburg II) Date: Wed, 17 Dec 2008 07:38:38 -0500 Subject: Relative imports in Python 3.0 In-Reply-To: References: Message-ID: <4948F2CE.8040102@aim.com> nicholas.cole at gmail.com wrote: > Imagine a module that looks like > > ModuleDir > __init__.py > a.py > b.py > > > In python 2.x I used to have tests at the end of each of my modules, > so that module b.py might look something like > > import a > .......... > .......... > > if __name__ == '__main__': > runtests() > > But under Python 3.0 this seems impossible. For usual use import a.py > has to become the line: > > from . import a > > But if I use that form it is no longer possible to run b.py as a > standalone script without raising an error about using relative > imports. > > I am sure I am not the first to run into this issue, but what is the > solution? > > Best wishes, > > Nicholas > -- > http://mail.python.org/mailman/listinfo/python-list > Sorry for the duplicate, sent to wrong email. Python 3 (and I think 2.6) now use absolute import when using a 'import blah' statement. if ('.' in __name__) or hasattr(globals, '__path__'): from . import a else: import a If '__name__' has a'.' then it is either a package or a module in a package, in which case relative imports can be used. If it does not have a '.' it may still be a package but the '__init__.py' file, in which case the module has a '__path__' attribute, so relative imports can be used. Otherwise it is not a package or in a package so absolute imports must used. Also, since it is not in a package it is assumed that it is top module (__main__) or possible module imported from the top that is not in a package, such as a.py doing an 'import b', b would be a module but not a package so still probably need absolute imports, my guess anyway. But I also think that 'from . import a' would be nice if it would work from non-packages as well, meaning just 'import a' if it is a non-package. Brian A. Vanderburg II From stephen at thorne.id.au Mon Dec 22 07:20:58 2008 From: stephen at thorne.id.au (Stephen Thorne) Date: Mon, 22 Dec 2008 22:20:58 +1000 Subject: no sign() function ? In-Reply-To: <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <20081222122058.GA8543@thorne.id.au> On 2008-12-22, Pierre-Alain Dorange wrote: > def sign(x): > if x==0.0: > return 0.0 > elif x>0.0: > return 1.0 > else: > return -1.0 Isn't this approximately this? :: def sign(x): return float(cmp(x, 0)) Or if you don't want a float response:: def sign(x): return cmp(x, 0) -- Regards, Stephen Thorne Development Engineer NetBox Blue - 1300 737 060 From hackingkk at gmail.com Mon Dec 15 08:46:03 2008 From: hackingkk at gmail.com (Krishnakant) Date: Mon, 15 Dec 2008 19:16:03 +0530 Subject: %s place holder does not let me insert ' in an sql query with python. In-Reply-To: References: <1229345178.31093.24.camel@krishna-laptop> Message-ID: <1229348763.31093.38.camel@krishna-laptop> hello all, thanks for all of your very quick responses. The problem is that I am using python 2.5 so the 2.6 syntax does not apply in my case. secondly, My problem is very unique. I have created a function called executeProcedure in python which calls stored procedures in postgresql. The fun part of this function is that it has just got 3 standard parameters namely the name of the sp to be called, whether it returns 1 or more records as a result and the list containing the input parameters which that sp will need for execution. So no matter what your sp does as in insert update delete or select, no matter there is one param or 10 all you have to do is pass one string containing the function name, one boolean and one list of params. The rest is taken care by this python function. So now all hackers will understand that the query to call the stored procedure namely cursor.execute(select * from functname ) will be built dynamically. So now in this situation I have to build the querystring and then pass it to execute of the cursor. in this case, I get a problem when there is ' in any of the values during insert or update. If any one wants this code, Please let me know. You all can get a lot of utility out of the function. This only becomes a problem when an ' comes in the value. So I need help to fix the problem with the given context. happy hacking. Krishnakant. On Mon, 2008-12-15 at 07:21 -0600, Lamonte Harris wrote: > sorry about that > > queryString = "insert into venders > values('{0}','{1}','{2}')".format(field1,field2,field3) > > On Mon, Dec 15, 2008 at 7:21 AM, Lamonte Harris > wrote: > I had this problem too. If you've upgraded to python 2.6 you > need to use the new sytnax "format > > queryString = "insert into venders > values('{0}','{1}','{2}'".format(field1,field2,field3) > > > > On Mon, Dec 15, 2008 at 6:46 AM, Krishnakant > wrote: > hello all hackers. > This is some kind of an interesting situation although > many of you must > have already gone through it. > I am facing a situation where I have to use psycopg2 > and insert rows in > a postgresql table. > That's pritty easy and no need to say that it works > well. But there are > some entries which have an ' in the value. > I have a venders table in my database and one of the > values tryed was > "His Master's Voice " > now the master's word has the ' which is used for > starting and ending a > varchar value for postgresql or almost any standard > RDBMS. > Does any one know what is the way out of this? > how do you let the ' go as a part of the string? > I have used %s as placeholder as in > queryString = "insert into venders values ('%s,%s,%s" > % > (field1,field2,field3 ) ... > This is not working for the ' values. > can any one suggest a suitable solution? > happy hacking. > Krishnakant. > > -- > http://mail.python.org/mailman/listinfo/python-list > > > From saltmarch2008 at gmail.com Fri Dec 12 00:56:23 2008 From: saltmarch2008 at gmail.com (Shaguf) Date: Thu, 11 Dec 2008 21:56:23 -0800 (PST) Subject: Apache Tapestry Creator to Speak on Clojure, Tapestry 5 Message-ID: <62f4890b-0eab-426b-b9c8-8645d7475f94@r36g2000prf.googlegroups.com> Apache Tapestry Creator to Speak on Clojure, Tapestry 5 Bangalore, December 10, 2008: If you are a Java developer building web- based applications and tired of the countless frameworks that promise you a slick UI fast but fail to live up to their promise, then switch to Apache Tapestry to get more functionality with less code. The creator of Tapestry, Howard Lewis Ship, is coming this summer to India's biggest summit for the developer ecosystem - Great Indian Developer Summit (http://www.developersummit.com/) to speak on the recently released Tapestry 5.0 version, covering the core IoC container, how to define and inject services and advanced topics such as decorating services to provide additional concerns, or creating services in terms of design patterns such as chain-of-command and pipeline. On April 25, the author of 'Tapestry in Action' will also conduct a 3- hour, hands on workshop on building your own Tapestry applications. Hew will cover what it means to be a component web framework, what advantages that brings, how to create database-driven web applications using Hibernate, show off Tapestry's live class reloading, advanced error reporting and other productivity features, how Tapestry can be tuned and customized and build new components. A frequent speaker at JavaOne, NoFluffJustStuff, ApacheCon Howard will also throw the spotlight on Clojure -- made up of one part Lisp (one of the oldest computer languages), one part Java (so young, yet so well adopted), a healthy serving of functional programming, and a state-of-the-art concurrency layer on top. Clojure embraces functional programming with immutable data types and first class functions. It is fully interoperable with Java. Clojure's approach to concurrency includes asynchonous Agents, and Software Transactional Memory. About Great Indian Developer Summit Great Indian Developer Summit, produced by Saltmarch Media, is the biggest gathering of software developers from Java/J2EE, Microsoft computing technologies, Rich Internet Applications (RIA), Web 2.0, Ajax, Agile, SOA, and Enterprise IT. For both veterans and newcomers to the world of .NET, Java, and the Rich Web, the Great Indian Developer Summit provides participants with a well-balanced learning experience that guaranteed they went back with a richer understanding of the technologies that make a difference to their careers. See the GIDS 2008 Red Stripe Report: http://www.developersummit.com/2008/report/pdf/Red_Stripe_Report-GIDS08.zip Over 3000 qualified and talented delegates - Source, attended GIDS 2008: The Hindu - Monday, 26 May 2008 (http://www.developersummit.com/ 2008/report/postPress.html). With outstanding educational sessions, powerhouse speakers, a high-profile award ceremony, GIDS 2009 will feature premium knowledge, action plans and advise from been-there- done-it veterans, creators, and visionaries. For further information on GIDS 2009, please visit the summit on the web http://www.developersummit.com/. A Saltmarch Media Press Release E: info at developersummit.com Ph: +91 080 4005 1000 From mensanator at aol.com Sat Dec 6 23:16:56 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 6 Dec 2008 20:16:56 -0800 (PST) Subject: "as" keyword woes References: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> <0147dc24$0$20670$c3e8da3@news.astraweb.com> <0148b217$0$20670$c3e8da3@news.astraweb.com> <7d0lj4d9hai2f87r30erc4l1ir85osbfg7@4ax.com> <88579d9a-df52-49b9-a6fe-53c8f4524bf3@j39g2000yqn.googlegroups.com> <70llj41hie2svs68o5efn22i97f649svfh@4ax.com> <1cda9a9a-1641-424b-9f3d-c4e2635efed7@j38g2000yqa.googlegroups.com> <014b0f94$0$20670$c3e8da3@news.astraweb.com> <4469f2ed-f012-400d-9d4f-bd44cd075d0d@w34g2000yqm.googlegroups.com> <014b3616$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Dec 6, 9:09?pm, Steven D'Aprano wrote: > On Sat, 06 Dec 2008 18:09:07 -0800, Mensanator wrote: > > On Dec 6, 6:25 pm, Steven D'Aprano > cybersource.com.au> wrote: > >> On Sat, 06 Dec 2008 14:36:07 -0800, Mensanator wrote: > >> > It was extremely simple for me to fix the sympy module where I > >> > noticed it. I'm not saying it wasn't a problem, I'm saying it wasn't > >> > BROKEN. > > >> If it wasn't broken, why did you need to fix it? > > > If my tire is flat, I have to fix it. But it may just need air, in which > > case it's not broken. > > In which case it doesn't need *fixing*, The state of the tire being flat has to be fixed, but not necessarily the tire. > it needs *refilling*. A flat tire > isn't necessarily broken. It is broken if it has a puncture or a slow > leak or has been ripped to shreds, but not if somebody merely let the air > out. "Air comes out if you open the value" is within standard operating > parameters and the tire is therefore working correctly. Just as "as" producing a syntax error is working correctly. > > >> "Broken" means "not working", not "unfixable". > > > So, you're saying that Python is broken and will remain so forever, > > since "as" will remain a keyword? > > I don't think that having "as" be a keyword is broken. But WS does and you appear to be taking his side. > I think the OP's > code is broken for Python 2.6 or better, So do I. Why are you arguing then? Simply to be pedantic about the meaning of "broken"? > and it will remain broken > forever unless he fixes it or chooses to stay with 2.5. > > > Are you advocating that we all switch to Ruby? > > Why do you think that? Because seem to be agreeing that the problem is with Python. If that's not what you meant, it's not coming across that way. > Do you imagine that Ruby has no features which are > inconvenient to users, or backwards incompatibilities, or warts, or that > it is impossible to write broken Ruby code? Who knows what you believe if you're agrreing that Python is permanently broken? > > -- > Steven From alessio.pace at gmail.com Mon Dec 1 01:33:43 2008 From: alessio.pace at gmail.com (Alessio Pace) Date: Sun, 30 Nov 2008 22:33:43 -0800 (PST) Subject: How to distribute a Python app together with its dependencies? References: <1ded1134-4933-4e05-953d-f93ac27c17e8@x16g2000prn.googlegroups.com> Message-ID: <5d9114c9-790a-49bb-8631-af8f36e0262a@o2g2000yqd.googlegroups.com> On 1 Dic, 05:23, Lev Elbert wrote: > If Python for Windows you can use Py2Exe package. It works very well > in simple cases and requires a few tweaks to make it recognize some > dependencies. As I was saying above, the destination machines are all Unix. Thank you anyway for your suggestion, I'll keep it in mind if I can to deploy on Windows too. -- Alessio Pace. From stef.mientki at gmail.com Fri Dec 19 11:58:36 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 19 Dec 2008 17:58:36 +0100 Subject: Building a web questionnaire, can it be done in Python ? Message-ID: <494BD2BC.4050000@gmail.com> hello, I'm considering building a web questionnaire in Python. I've made several desktop applications in Python / wxPython, but I've no experience in using Python on a webserver, and I don't have much knowledge about web applications in general. As am quit familiar with Python, therefor it sounds evident to me to make the web application in Python, but I'm not sure that's really the best way. I've googled, but the links I get, makes me more confused: Zope, Plone , ...?? And I can find a lot in other languages Perl, JavaScript, PHP, CGI, ... So maybe someone on this list can give me some advise, a good starting point, because it's almost impossible to evaluate all the possibilities myself, and I'm afraid the first choice will be the final choice ;-) The questionnaires are used to diagnose and treat all kinds of patients in a hospital. Therefor I need 2 versions, a web-version and a desktop version, the latter I need to be able to lock the computer. The desktop version is no problem, neither the locking. Also the analysis and reporting of the data will be done in a desktop application. The problematic (at least form my point of view) requirements: ================================================ The content and layout comes from an existing database. The layout of the desktop version and the web-version should be almost identical to the paper and pencil version (most norms are based on the paper and pencil version) The questions can have different forms, multiple choice, multiple choice with multiple answers, but also things like sliders. The answering should also be possible with the keyboard only: e.g. 1,2,.. for the answers, PgUp / PgDn or Enter for previous / next question. The web application should have some kind of security (soap ? https ?) and a login. Depending on answers to previous questions, some questions should be ignored. Depending on answers to previous questions, some questionnairies should be ignored. Patient should be able to browse within 1 questionnaire, but not to the previously answered ones. After each questionnaire there should be check if all questions were answered. Should run in IE and Mozilla. I'm not sure about this one yet: While a session can take several hours, it could be beneficial to connect to the internet only at some intermediate intervals, or when one questionnaire is completely finished. thanks, Stef From steve at holdenweb.com Tue Dec 23 07:06:01 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 23 Dec 2008 07:06:01 -0500 Subject: On Whose Desktop Message-ID: Thanks to Barry Warsaw the "On Your Desktop" blog now has a new entry: http://onyourdesktop.blogspot.com/ Who would you like to see profiled next? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From prologic at shortcircuit.net.au Thu Dec 18 19:23:30 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Dec 2008 10:23:30 +1000 Subject: importing csv file into sqlite In-Reply-To: References: <21067453.post@talk.nabble.com> Message-ID: On Fri, Dec 19, 2008 at 10:11 AM, Gabriel Genellina wrote: > But your code does *exactly* that, it reads the whole file in memory: > >> def mkBuffer(fd): >> buffer = StringIO() >> buffer.write(fd.read()) >> ... > > That mkBuffer function has no useful purpose IMHO, just remove it. It was a mistake in my implementation at the time of writing :) I've since fixed and removed it! Thanks though :) cheers James From n.kottiyath at gmail.com Wed Dec 24 13:18:55 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Wed, 24 Dec 2008 10:18:55 -0800 (PST) Subject: Iterating over objects of a class References: <2df27de3-7fa3-4ac9-acd9-f946939517cf@r37g2000prr.googlegroups.com> <6rfb7iF1fg5rU1@mid.uni-berlin.de> Message-ID: <7f47994f-13b6-45c4-920a-83aa72282bec@i20g2000prf.googlegroups.com> On Dec 24, 11:04?pm, MRAB wrote: > Diez B. Roggisch wrote: > > Kottiyath schrieb: > >> Hi, > >> ? ?How can I iterate over all the objects of a class? > >> ? ?I wrote the code like following: > >> class baseClass(object): > > > Consider adopting PEP 8 ?coding conventions. > > >> ? ? __registry = [] > > >> ? ? def __init__(self, name): > >> ? ? ? ? self.__registry.append(self) > >> ? ? ? ? self.name = name > > >> ? ? def __iter__(self): > >> ? ? ? ? baseClass.item = 0 > >> ? ? ? ? return self.__registry[0] > > >> ? ? def next(self): > >> ? ? ? ? if baseClass.item >= len(self.__registry): > >> ? ? ? ? ? ? raise StopIteration > >> ? ? ? ? baseClass.item += 1 > >> ? ? ? ? return self.__registry[baseClass.item - 1] > > >> For testing, create the following objects- > >> a = baseClass("Test1") > >> b = baseClass("Test2") > > >> class subClass (baseClass): > >> ? ?pass > >> c = subClass("Test3") > > >> ---->Actual Iteration<---- > >> for i in a: > >> ? ? print i.name > > >> Test1 > >> Test2 > >> Test3 > > >> --------------------------------------------------- > >> I see the following problems in the code: > >> 1. I have to iterate over any of the objects. For correctness, I > >> wanted to iterate over the class, like > >> for i in baseClass(): > >> ? ?do x > >> but that will will create one more object - which I do not want. > > >> 2. If the subclass wants to do somethings in its constructor, I am not > >> sure how to update the registry. > >> class subClass (baseClass): > >> ? ?def __init__(self, name): > >> ? ? ? ?**do something** > >> ? ? ? ?super.init(self, name) ?----> This errors out, saying it needs > >> super, not subClass > > > You don't show the actual traceback, however the idiom for invoking > > super for new-style-classes is > > > super(subClass, self).__init__(name) > > > for your case. > > >> Another method I thought of implementing it was using generators - > >> where-in baseClass.objects() is a generator which will yield the > >> objects one by one - but even then the second issue remains. > >> If somebody can help me out, I would be very thankful. > > > Using a generator or not isn't the issue here. > > > What you need is a *class*-based access, not instance-based. There are > > various methods to accomplish this. The simplest is to ditch the > > obnoxious __registry as name, and just do > > > class BaseClass(object): > > > ? ?REGISTRY = [] > > > Then iterating is a simple matter of > > > for instance in BaseClass.REGISTRY: > > ? ?... > > > Case solved. Alternatively, if you insist on the concept of privacy for > > that registry, you can use a classmethod: > > > class BaseClass(object): > > > ? ?@classmethod > > ? ?def registry(cls): > > ? ? ? ?for i in cls.__registry: > > ? ? ? ? ? ?yield i > > > Last but not least you *could* go for a __metaclass__ with an > > __getitem__-method, that makes thinks look fancy because you then can do: > > > for instance in BaseClass: > > ? ? ... > > > I leave it as an exercise to you - gotta go christmas dining now :) > > The other thing to remember is that because the 'registry' contains > references to the instances, they won't be garbage collected. Is there any other way out in this case? I have factory methods - and I have to loop over them - sort of Chain of Responsibility pattern. Having a registry inside the class instance and looping through them was the only clean thing I could think of. I understand that garbage collection would be an issue - but is there any way out? From istvan.albert at gmail.com Thu Dec 4 15:40:34 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Thu, 4 Dec 2008 12:40:34 -0800 (PST) Subject: Python 3 read() function References: Message-ID: <4dc8248b-2620-4bea-ba69-688c8f2da855@w39g2000prb.googlegroups.com> Turns out write performance is also slow! The program below takes 3 seconds on python 2.5 17 seconds on python 3.0 yes, 17 seconds! tested many times in various order. I believe the slowdowns are not constant (3x) but some sort of nonlinear function (quadratic?) play with the N to see it. =================================== import time start = time.time() N = 10**6 fp = open('testfile.txt', 'wt') for n in range(N): fp.write( '%s\n' % n ) fp.close() end = time.time() print (end-start) From prologic at shortcircuit.net.au Mon Dec 29 01:08:22 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 29 Dec 2008 16:08:22 +1000 Subject: why cannot assign to function call In-Reply-To: <495867C2.7080807@gmail.com> References: <495867C2.7080807@gmail.com> Message-ID: On Mon, Dec 29, 2008 at 4:01 PM, scsoce wrote: > I have a function return a reference, and want to assign to the reference, > simply like this: >>>def f(a) > return a > b = 0 > * f( b ) = 1* > but the last line will be refused as "can't assign to function call". > In my thought , the assignment is very nature, but why the interpreter > refused to do that ? That's exactly right. You _cannot_ assign to a function call. This is invalid in just about _all_ languages. Assignments are generally bound to a variable. >>> def f(a): ... return a ... >>> b = 0 >>> x = f(b) >>> x 0 >>> cheers James From digisatori at gmail.com Fri Dec 19 11:58:16 2008 From: digisatori at gmail.com (digisatori at gmail.com) Date: Fri, 19 Dec 2008 08:58:16 -0800 (PST) Subject: encoding problem References: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> <6r1m72Ffb5kpU3@mid.uni-berlin.de> Message-ID: <8522bfaf-7efc-4ebb-a63a-b5ecc73e236d@35g2000pry.googlegroups.com> On 12?19?, ??9?34?, Marc 'BlackJack' Rintsch wrote: > On Fri, 19 Dec 2008 04:05:12 -0800, digisat... at gmail.com wrote: > > The below snippet code generates UnicodeDecodeError. > > #!/usr/bin/env > > python > > #--*-- coding: utf-8 --*-- > > s = '???' > > u = unicode(s) > > > It seems that the system use the default encoding- ASCII to decode the > > utf8 encoded string literal, and thus generates the error. > > > The question is why the Python interpreter use the default encoding > > instead of "utf-8", which I explicitly declared in the source. > > Because the declaration is only for decoding unicode literals in that > very source file. > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch Thanks for the answer. I believe the declaration is not only for unicode literals, it is for all literals in the source even including Comments. we can try runing a source file without encoding declaration and have only 1 line of comments with non-ASCII characters. That will arise a Syntax error and bring me to the pep263 URL. I read the pep263 and quoted below: Python's tokenizer/compiler combo will need to be updated to work as follows: 1. read the file 2. decode it into Unicode assuming a fixed per-file encoding 3. convert it into a UTF-8 byte string 4. tokenize the UTF-8 content 5. compile it, creating Unicode objects from the given Unicode data and creating string objects from the Unicode literal data by first reencoding the UTF-8 data into 8-bit string data using the given file encoding The above described Python internal process indicate that the step 2 will utilise the specific encoding to decode all literals in source, while in step5 will evolve a re-encoding with the specific encoding. That is the reason why we have to explicitly declare a encoding as long as we have non-ASCII in source. Bruno answered why we need specify a encoding when decoding a byte string with perfect explanation, Thank you very much. From duncan.booth at invalid.invalid Sat Dec 13 16:24:09 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Dec 2008 21:24:09 GMT Subject: stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <1ff0d642-b560-433c-b793-3a05f5b051b9@g1g2000pra.googlegroups.com> Message-ID: Aaron Brady wrote: >So, what's the group policy on helping with homework? rhetorical> In my book anyone who is dumb enough to ask for homework help on a newsgroup and doesn't acknowledge that when they hand in their answer deserves whatever they get. Oh, and of course there are 2 deliberate error in the 'solution' I posted so they're not going to get full marks if they simply reuse it. (If there are more than 2 errors then at least one of them is not deliberate.) That's assuming the teacher is savvy enough to keep an eye on the obvious sources for quick answers. From federico at linux.com.uy Fri Dec 19 08:29:25 2008 From: federico at linux.com.uy (Federico Moreira) Date: Fri, 19 Dec 2008 10:29:25 -0300 Subject: Generator slower than iterator? In-Reply-To: <62013718-57e9-4690-a2be-11e63b9c135b@u18g2000pro.googlegroups.com> References: <62013718-57e9-4690-a2be-11e63b9c135b@u18g2000pro.googlegroups.com> Message-ID: Great, 2min 34 secs with the open method =) but why? ip, sep, rest = line.partition(' ') match_counter[ip] += 1 instead of match_counter[line.strip()[0]] += 1 strip really takes more time than partition? I'm having the same results with both of them right now. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davidgshi at yahoo.co.uk Thu Dec 18 10:42:08 2008 From: davidgshi at yahoo.co.uk (David Shi) Date: Thu, 18 Dec 2008 15:42:08 +0000 (GMT) Subject: Extracting data from XML containing CDATA and store data in a .dbf file Message-ID: <989642.86682.qm@web26307.mail.ukl.yahoo.com> I am looking for advice/efficient script to extract data from XML containing CDATA. ? I wish to extract all the data and store it in a .dbf file. ? Regards. ? David -------------- next part -------------- An HTML attachment was scrubbed... URL: From mynthon1 at gmail.com Tue Dec 23 08:27:45 2008 From: mynthon1 at gmail.com (mynthon) Date: Tue, 23 Dec 2008 05:27:45 -0800 (PST) Subject: wxPython.button.disabled still catching clicks References: <8cb6da6a-7df4-4cce-a28e-385448a25b26@w39g2000prb.googlegroups.com> <1ff2aad7-29a1-48cd-b3de-29fab443aa3e@u18g2000pro.googlegroups.com> Message-ID: <0e9a5ab7-8078-4d12-adb2-aaf92a78b007@s9g2000prm.googlegroups.com> On Dec 23, 11:58?am, Aaron Brady wrote: > On Dec 23, 4:50?am, mynthon wrote: > > > > > Hello! (sorry for my english) > > > I have a problem with buttons in wxPython. When button is disabled > > (by .Disable() or .Enable(False)) it is grayed out but still receive > > clicks. > > > Eg. i have button that disable itself, runs long action and enable > > itself: > > > def onClick(self, evt): > > ? ? self.btn.Enable(False) > > ? ? for i in range (1000): > > ? ? ? ? print i > > ? ? self.btn.Enable(True) > > > when for loop is running button is greyed out and when i click on it > > nothing happens but when loop ends another one is started because > > button "remebered" thad i click on it when was diabled. My only idea > > is to reposition button outside frame instead of disabling it but this > > solution is...not good. > > > thanks for any help. Ive searched groups, google and it looks that > > only i have this problem :) > > No, it is very common. ?During your for loop, the loop is dominating > the process completely. ?Events are just building up in the app's > message queue, and don't get handled until after you yield on control. > > If you need to run a long task, look into threading, the OnIdle > method, the 'multiprocessing' module, or pump messages during your > long task. ok, maybe someone will need it. I dont know how it works because i didnt have time to read docs and i cannot explain everything. I used google and wxPython demo (in tree: wxpython overview / process and events / process) class leftPanel(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id, style=wx.BORDER_SUNKEN) # here you have to define new process, IDLE event, and onPRocessEnd event self.process = None self.GetParent().Bind(wx.EVT_IDLE, self.onIdle) self.Bind(wx.EVT_END_PROCESS, self.onProcessEnd) # create button and bind event to it self.runScriptBtn = wx.Button(self, -1, 'RUN ME!', (10,220)) self.runScriptBtn.Bind(wx.EVT_BUTTON, self.onClick, self.runScriptBtn) def onClick(self, evt): # disable button self.runScriptBtn.Enable(False) # here you have to enter command to run # previusly i heve here exec('python myScript.py') # but now it will be a subprocess cmd = 'python xxx1.py' #create new process self.process = wx.Process(self) # dont know what it is for self.process.Redirect() # execute cmd command pid = wx.Execute(cmd, wx.EXEC_ASYNC, self.process) def onIdle(self, evt): # beacuse this method is called only when app enters idle mode # the line below is nedded to "simulate" entering idle mode # dont know how it works but it works evt.RequestMore(True) # here is some code to catch subprocess output if self.process is not None: stream = self.process.GetInputStream() if stream.CanRead(): text = stream.read() print text def onProcessEnd(self, evt): # here is some code to catch subprocess output # when it is destroyed stream = self.process.GetInputStream() if stream.CanRead(): text = stream.read() print text # dont know it is necessary self.process.CloseOutput() # remove (clear) process object self.process.Destroy() self.process = None # show button again self.runScriptBtn.Enable() From fetchinson at googlemail.com Tue Dec 9 11:14:09 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Tue, 9 Dec 2008 08:14:09 -0800 Subject: html codes In-Reply-To: References: Message-ID: >> I came across a javascript library that returns all sorts of html >> codes in the cookies it sets and I need my web framework (written in >> python :)) to decode them. I'm aware of htmlentitydefs but >> htmlentitydefs.entitydefs.keys( ) are of the form '&#xxx' but this >> javascript library uses stuff like '%3A' for the ':' for example. The >> conversion is here: >> >> http://www.ascii.cl/htmlcodes.htm >> >> Is there a python package/module/whatever that does the conversion for >> me or do I have to write a little wrapper myself (and introduce bugs >> while doing so :))? > >>>> import urllib >>>> urllib.quote("L?blich ?hnlich ?blich") > 'L%C3%B6blich%20%C3%A4hnlich%20%C3%BCblich' >>>> urllib.unquote(_) > 'L\xc3\xb6blich \xc3\xa4hnlich \xc3\xbcblich' >>>> print _ > L?blich ?hnlich ?blich > > If you care about the encoding you have to encode/decode explicitly: > >>>> urllib.quote(u"L?blich ?hnlich ?blich".encode("latin1")) > 'L%F6blich%20%E4hnlich%20%FCblich' >>>> urllib.unquote(_).decode("latin1") > u'L\xf6blich \xe4hnlich \xfcblich' Thanks a lot guys! Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From jpablo.romero at gmail.com Wed Dec 10 22:07:30 2008 From: jpablo.romero at gmail.com (=?ISO-8859-1?Q?Juan_Pablo_Romero_M=E9ndez?=) Date: Wed, 10 Dec 2008 21:07:30 -0600 Subject: Compiling and installing python 2.5.2 with Visual C++ 2008 In-Reply-To: <493f5d6c$0$9126$9b622d9e@news.freenet.de> References: <493f5d6c$0$9126$9b622d9e@news.freenet.de> Message-ID: Finally installed Python 2.6, which is compiled with visual C++ 2008, and all my problems went away. Thanks to all, Juan Pablo 2008/12/10 "Martin v. L?wis" : >> --------------------------------------------------------- >> ... >> error: Python was built with Visual Studio 2003; >> extensions must be built with a compiler than can generate compatible binaries. >> Visual Studio 2003 was not found on this system. If you have Cygwin installed, >> you can try compiling with MingW32, by passing "-c mingw32" to setup.py. >> --------------------------------------------------------- >> >> And because I've been compiling everything needed by pivy (Coin, Qt, >> SoQt, PyQt) with visual c++ 8, I decided to recompile python itself. > > There isn't a real installation procedure. You just copy the files by > hand into the places where they belong. In the specific case, > overwriting all .exe, .dll, and .pyd files in an installed directory > should be sufficient. > > Regards, > Martin > -- > http://mail.python.org/mailman/listinfo/python-list > From paul at boddie.org.uk Mon Dec 8 14:21:55 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 8 Dec 2008 11:21:55 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> Message-ID: <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> On Dec 4, 5:39 pm, "Chris Mellon" wrote: > > Honestly, based on the content and tenor of this post I think this is > Yet Another Python Troll So original: disagreeable criticism is "trolling". A few points... Short keywords are more likely to collide with short variable and attribute names, and while we should all use descriptive names for things, the complainant does seem to have found a reasonable application of a short name; when new short keywords are introduced, conflicts with such applications are inevitable, and that's exactly what has happened here. Anyone who has used any library or framework which combines another domain or technology with Python has probably seen names with trailing underscores; I believe PyQt employs exec_ instead of exec in various places, for example. Choosing some other name which needs no underscore can work against the beginner if they are referring to generic documentation. My message on python-dev about parsers and keywords noted that some languages manage to achieve what the complainant wants, more or less. SQL implementations, for example, can often deal with keywords if they are qualified, and it is even possible to double-quote keywords and use them as identifiers: create table "create" ( "select" varchar ); select "select" from "create"; select "create".select from "create"; (This from a PostgreSQL 8.2 session.) [...] > If you suppressed or ignored the deprecation warning that > all your code has been generating for at least 2 years it's pretty > damn ballsy to come here and tell everyone how *Python* is doing > something wrong. Maybe the complainant realises that he has no say in this matter and that he has to raise it in this fashion as a last resort. I've only skimmed this thread, but if the complainant is still using 2.4 (like a number of people) he won't have seen such a warning (although maybe he admits seeing it somewhere amongst the pile of "how dare you criticise?!" messages), and now he sees that he's running out of road. What I can say is that it certainly does take balls to see matters from the other guy's perspective instead of calling someone names for pointing something out. Paul From antoine at vo.lu Sat Dec 6 03:56:12 2008 From: antoine at vo.lu (Antoine De Groote) Date: Sat, 06 Dec 2008 09:56:12 +0100 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: <48db9$493a3e2b$d9a2276f$10794@news.hispeed.ch> try this: >>> import this and look at the 15th line... I agree that for newcomers to Python, the class method definition might seem strange. I certainly had problems with it when starting with Python, coming from Java. But in the meantime it feels right. I don't know if it is because I'm used to the old way, but I find the proposed alternative way slightly less readable. Altough these are no technical considerations, I'm -1 on this. Daniel Fetchinson wrote: > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html > > The proposal is to allow this: > > class C: > def self.method( arg ): > self.value = arg > return self.value > > instead of this: > > class C: > def method( self, arg ): > self.value = arg > return self.value > > I.e. explicit self stays only the syntax is slightly different and may > seem attractive to some. As pointed out by Guido classmethods would > work similarly: > > class C: > @classmethod > def cls.method( arg ): > cls.val = arg > return cls.val > > The fact that Guido says, > > "Now, I'm not saying that I like this better than the status quo. But > I like it a lot better than [...] but it has the great advantage that > it is backward compatible, and can be evolved into a PEP with a > reference implementation without too much effort." > > shows that the proposal is viable. > > I'd like this new way of defining methods, what do you guys think? > Anyone ready for writing a PEP? > > Cheers, > Daniel > From mh at pixar.com Sun Dec 7 03:54:46 2008 From: mh at pixar.com (mh at pixar.com) Date: Sun, 07 Dec 2008 08:54:46 GMT Subject: var or inout parm? Message-ID: How can I make a "var" parm, where the called function can modify the value of the parameter in the caller? def f(x): x = x + 1 n = 1 f(n) # n should now be 2 Many TIA!! Mark -- Mark Harrison Pixar Animation Studios From geekmail at usenot.de Fri Dec 5 10:31:07 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Fri, 5 Dec 2008 16:31:07 +0100 Subject: To Troll or Not To Troll (aka: "as" keyword woes) References: Message-ID: <20081205163107.1815df40@usenot.de> On Thu, 4 Dec 2008 16:17:20 -0800 "Warren DeLano" wrote: > Thank so much for the suggestions Ben. Sorry that I am personally > unable to live up to your high standards, but it is nevertheless an > honor to partipicate in such a helpful and mutually respectful > community mailing list! > You seem mildly irritated. Please don't be. Clearly you are not "personally unable" to "live up to" anybody's standards. His advice was a good one because there is a merrit to standards compliance. Just because you didn't know the standards (or rather "best practices") doesn't mean you're in any way deficient. Is it me, or has c.l.p. developed a slightly harsher tone recently? (Haven't been following for a while.) regards /W -- My real email address is constructed by swapping the domain with the recipient (local part). From steve at REMOVE-THIS-cybersource.com.au Thu Dec 4 10:02:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Dec 2008 15:02:12 GMT Subject: Pythonic design patterns References: Message-ID: <0147e8b9$0$20670$c3e8da3@news.astraweb.com> On Thu, 04 Dec 2008 01:09:08 -0800, Slaunger wrote: > I find myself spending a lot of time in Python making some designs, to > solve some task, which is the end turn out to be closely related to well > established design patterns / programming idioms, which other users in > this forum has been kind enough to point out. Only my implementations > are often not that clean, and I may call things something different than > the normal convention, which is a source of confusion for myself and > others trying to communicate with me. > > I guess I could boost my productivity by learning these well-proven and > well-established design patterns by heart. This is all very good, but don't drink the design pattern Kool-Aid and start pushing design patterns everywhere. (Not everything needs to be a singleton. No, really.) I think the risk with design patterns is that in the hands of an over- enthusiastic new convert, they encourage over-engineering, excessive abstraction and Big Design Up Front thinking. Patterns are useful, there's no doubt about it, but patterns should for the most part be invisible. Functions are patterns, but because they were invented back when dinosaurs walked the earth, before the Gang Of Four, they're just called functions instead of AbstractReusableResultGeneratingValueFactory Pattern. *wink* http://c2.com/cgi/wiki?DesignPatternsConsideredHarmful I think one good sign of pattern over/mis-use is when people can't even agree on whether something is a pattern, and if so, which pattern it is: http://c2.com/cgi/wiki?FactoryMethod -- Steven From jstroud at mbi.ucla.edu Tue Dec 23 19:58:00 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 23 Dec 2008 16:58:00 -0800 Subject: On Whose Desktop In-Reply-To: References: Message-ID: Steve Holden wrote: > Thanks to Barry Warsaw the "On Your Desktop" blog now has a new entry: Note the thumb trackball. It's the shiznizzle. Give one two weeks of your patience and you'll seriously consider having it implanted in your thigh so you don't have to worry about missing it when you travel. From mrkafk at gmail.com Tue Dec 30 10:46:29 2008 From: mrkafk at gmail.com (mk) Date: Tue, 30 Dec 2008 16:46:29 +0100 Subject: thread, multiprocessing: communication overhead Message-ID: Hello everyone, This time I decided to test communication overhead in multithreaded / multiprocess communication. The results are rather disappointing, that is, communication overhead seems to be very high. In each of the following functions, I send 10,000 numbers to the function / 10 threads / 10 processes, which simply returns it in its respective way. Function: notfun Best: 0.00622 sec Average: 0.00633 sec (simple function) Function: threadsemfun Best: 0.64428 sec Average: 0.64791 sec (10 threads synchronizing using semaphore) Function: threadlockfun Best: 0.66288 sec Average: 0.66453 sec (10 threads synchronizing using locks) Function: procqueuefun Best: 1.16291 sec Average: 1.17217 sec (10 processes communicating with main process using queues) Function: procpoolfun Best: 1.18648 sec Average: 1.19577 sec (a pool of 10 processes) If I'm doing smth wrong in the code below (smth that would result in performance suffering), please point it out. Code: import threading import multiprocessing import time import timeit def time_fun(fun): t = timeit.Timer(stmt = fun, setup = "from __main__ import " + fun.__name__) results = t.repeat(repeat=10, number=1) best_result = min(results) avg = sum(results) / len(results) print "Function: %-15s Best: %5.5f sec Average: %5.5f sec" % (fun.__name__, best_result, avg) def notfun(): inputlist = range(0,10000) reslist = [] for x in range(len(inputlist)): reslist.append(inputlist.pop()) def threadsemfun(): def tcalc(sem, inputlist, reslist, tid, activitylist): while len(inputlist) > 0: sem.acquire() try: x = inputlist.pop() except IndexError: sem.release() return #activitylist[tid] += 1 reslist.append(x) sem.release() inputlist = range(0,10000) #print "before: ", sum(inputlist) reslist = [] tlist = [] activitylist = [ 0 for x in range(0,10) ] sem = threading.Semaphore() for t in range(0,10): tlist.append(threading.Thread(target=tcalc, args=(sem, inputlist, reslist, t, activitylist))) for t in tlist: t.start() for t in tlist: t.join() #print "after: ", sum(reslist) #print "thread action count:", activitylist def threadlockfun(): def tcalc(lock, inputlist, reslist, tid, activitylist): while True: lock.acquire() if len(inputlist) == 0: lock.release() return x = inputlist.pop() reslist.append(x) #activitylist[tid] += 1 lock.release() inputlist = range(0,10000) #print "before: ", sum(inputlist) reslist = [] tlist = [] activitylist = [ 0 for x in range(0,10) ] sem = threading.Semaphore() for t in range(0,10): tlist.append(threading.Thread(target=tcalc, args=(sem, inputlist, reslist, t, activitylist))) for t in tlist: t.start() for t in tlist: t.join() #print "after: ", sum(reslist) #print "thread action count:", activitylist def pf(x): return x def procpoolfun(): pool = multiprocessing.Pool(processes=10) inputlist = range(0,10000) reslist = [] i, j, jmax = 0, 10, len(inputlist) #print "before: ", sum(inputlist) while j <= jmax: res = pool.map_async(pf, inputlist[i:j]) reslist.extend(res.get()) i += 10 j += 10 #print "after: ", sum(reslist) def procqueuefun(): def pqf(qin, qout): pid = multiprocessing.current_process().pid while True: x = qin.get() if x == 'STOP': return qout.put((pid, x)) qin = multiprocessing.Queue() qout = multiprocessing.Queue() plist = [] activity = dict() for i in range(0,10): p = multiprocessing.Process(target = pqf, args=(qin, qout)) p.start() plist.append(p) activity[p.pid] = 0 inputlist = range(0,10000) reslist = [] #print "before:", sum(inputlist) ilen = len(inputlist) x = 0 while x != ilen: for i in range(0,10): qin.put(inputlist[x+i]) for i in range(0,10): pid, res = qout.get() #activity[pid] = activity[pid] + 1 reslist.append(res) x += 10 for i in range(0,10): qin.put('STOP') for i in range(len(plist)): plist[i].join() #print "after:", sum(reslist) #print "activity", activity if __name__ == "__main__": time_fun(notfun) time_fun(threadsemfun) time_fun(threadlockfun) time_fun(procqueuefun) time_fun(procpoolfun) From steve at REMOVE-THIS-cybersource.com.au Sat Dec 6 00:36:32 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Dec 2008 05:36:32 GMT Subject: Guido's new method definition idea References: Message-ID: <014a071a$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 20:35:07 -0800, James Stroud wrote: > Daniel Fetchinson wrote: >> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to- stay.html >> >> The proposal is to allow this: >> >> class C: >> def self.method( arg ): >> self.value = arg >> return self.value >> >> instead of this: >> >> class C: >> def method( self, arg ): >> self.value = arg >> return self.value > >> I'd like this new way of defining methods, what do you guys think? > > Consider the maverick who insists on > > class C: > def me.method(arg): > self.value = arg Replace "self" with "me". > which should be equivalent to > > class C: > def method(me, arg): > me.value = arg > > What's the interpreter going to do with our maverick's code? I don't see why you think this is a problem. The compiler merely treats: def ANYTHING.method(arg): inside a class as if it were def method(ANYTHING, arg): and it will Just Work. If you want a classmethod, you still need to use the classmethod decorator -- there's no reason to make self and cls keywords. Personally, I'm neutral on the idea. Perhaps +0.00001. -- Steven From googler.1.webmaster at spamgourmet.com Fri Dec 5 04:44:13 2008 From: googler.1.webmaster at spamgourmet.com (googler.1.webmaster at spamgourmet.com) Date: Fri, 5 Dec 2008 01:44:13 -0800 (PST) Subject: Python C API References: <54fbb55d-3c39-459d-86a3-302b69721f0f@s20g2000yqh.googlegroups.com> <4938ed67$0$30227$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <3d1b6644-c943-412d-8860-6779a981fa44@20g2000yqt.googlegroups.com> Hi! thats a very interesting point and good to know. I have to release the GIL but how do I do? In this case i need PyEval_AcquireLock and PyEval_ReleaseLock? Thanks. From timr at probo.com Thu Dec 18 02:17:44 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 18 Dec 2008 07:17:44 GMT Subject: sys.maxint in Python 2.6.1 (amd64) on Windows XP x64 References: <4bddf65a-bb9f-406c-a544-8c38b27547a7@b38g2000prf.googlegroups.com> <7a629cb1-0fbc-41d4-ac51-d0be68df1df5@r36g2000prf.googlegroups.com> Message-ID: Lin wrote: > >Ah, this makes sense. Thanks...... The main reason I'm trying 64-bit >Python is that I want to write files bigger than 4GB. This should work >on Windows x64, right? (i.e., are the pointers bona fide 64 bit?) Those two questions are not related. Win32 (NTFS) has always been able to create files larger than 4GB, and the file APIs that deal with file positions and file sizes can all handle 64-bit values. Pointers on Win32 are 32 bits, but that doesn't affect files. If you want to map that large file into memory, you have to do it a gigabyte at a time, but if you're using ReadFile and WriteFile, it's not a problem. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From steve at REMOVE-THIS-cybersource.com.au Mon Dec 29 20:40:36 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Dec 2008 01:40:36 GMT Subject: Of console I/O, characters, strings & dogs References: Message-ID: <0169731c$0$6988$c3e8da3@news.astraweb.com> On Mon, 29 Dec 2008 18:53:45 -0600, David Lemper wrote: > I am trying getch() from msvcrt. The following module has been run with > 3 different concatination statements and none yield a satisfactory > result. Python 3.0 Your first problem is that you've run into the future of computing: strings are not bytes. For many decades, programmers have been pretending that they are, and you can get away with it so long as you ignore the 95% of the world that doesn't use English as their only language. Unfortunately, the time for this is passed. Fortunately, it's (mostly) not difficult to use Unicode, and Python makes it easy for you. > # script12 > import msvcrt > shortstr1 = 'd' + 'o' + 'g' > print(shortstr1) In Python 3, shortstr1 is a Unicode string. Python 3 uses Unicode as it's string type. Because Python is doing all the hard work behind the scenes, you don't have to worry about it, and you can just print shortstr1 and everything will Just Work. > char1 = msvcrt.getch() > char2 = msvcrt.getch() > char3 = msvcrt.getch() I don't have msvcrt here but my guess it that getch is returning a *byte* rather than a *character*. In the Bad Old Days, all characters were bytes, and programmers pretended that they were identical. (This means you could only have 256 of them, and not everyone agreed what those 256 of them were.) But in Unicode, characters are characters, and there are thousands of them. MANY thousands. *Way* too many to store in a single byte. > < alternatives for line 8 below > > print(shortstr2) > > print(shortstr1) gives dog of course. If the same > char are entered individually at the console, as char1, > 2 & 3, using msvcrt.getch(), I have not been able to get > out a plain dog. > > If line 8 is shortstr2 = char1[0] + char2[0] + char3[0] > print(shortstr2) yields 314 >>> ord('d') + ord('o') + ord('g') 314 The ordinal value of a byte is its numeric value, as a byte. > If line 8 is shortstr2 = 'char1[0]' + 'char2[0]' + 'char3[0]' > print(shortstr2) yields char1[0]char2[0]char3[0] Of course it does. You're setting shortstr2 equal to the literal strings 'char1[0]' etc. But nice try: you want to convert each not-really-a-char to a (Unicode) string. You don't do that with the '' delimiters, as that makes a literal string, but with the str() function. Either of these should work: shortstr2 = str(char1) + str(char2) + str(char3) shortstr2 = str(char1 + char2 + char3) While they will work for (probably) any character you can type with your keyboard, they will probably fail to give sensible results as soon as you try using characters like ? ? ? ? ? The right way to convert bytes to characters is to decode them, and to decode them, you have to know what encoding system is used. If the characters are plain-old English letters typed on an American keyboard, you can do this: bytes = char1 + char2 + char3 shortstr2 = bytes.decode('ascii') but this can give unexpected results if bytes contains non-ASCII values. Better is to go the whole-hog and use the UTF-8 encoding, unless you specifically know to use something else: shortstr2 = bytes.decode('utf-8') > If line 8 is shortstr2 = char1 + char2 + char3 > print(shortstr2) yields b 'dog' > > Is the latter out of "How to Speak Redneck" ? > > Possibly b means bit string. Nice guess, close but not quite. It actually means byte string. You probably should read this: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky http://www.joelonsoftware.com/articles/Unicode.html Good luck! -- Steven From james at agentultra.com Thu Dec 11 11:53:32 2008 From: james at agentultra.com (J Kenneth King) Date: Thu, 11 Dec 2008 11:53:32 -0500 Subject: pydb 1.24 References: Message-ID: <85vdtqejqr.fsf@dozer.localdomain> rocky at panix.com (R. Bernstein) writes: > This release is to clear out some old issues. It contains some > bugfixes, document corrections, and enhancements. Tests were > revised for Python 2.6 and Python without readline installed. A bug > involving invoking from ipython was fixed. The "frame" command is a > little more like gdb's. Exceptions are now caught in runcall(). > > This is the last release contemplated before a major rewrite. > > download: > https://sourceforge.net/project/showfiles.php?group_id=61395&package_id=175827 > > bug reports: > https://sourceforge.net/tracker/?group_id=61395&atid=497159 I watched the demo video, look forward to working with it. Any links to that emacs front-end being used in the video? Cheers and thanks! From walterbyrd at iname.com Mon Dec 22 09:58:06 2008 From: walterbyrd at iname.com (walterbyrd) Date: Mon, 22 Dec 2008 06:58:06 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> Message-ID: <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> On Dec 21, 12:28?pm, Bruno Desthuilliers wrote: > Strange enough, > no one seems to complain about PHP or Ruby's performances... A few years back, there was a certain amount of chest thumping, when python/django easily beat ror in a benchmark test. Now that ruby is faster, I guess speed is no big issue. By the same reasoning, python advocates used to sneer at php because php constantly broke backward compatibility. Now that python does it, breaking backward compatibility is no big deal. I guess unicode support was not that important, until python caught up to perl. I guess, the way it works is: you first assume that python is superior, then you figure out why. From stef.mientki at gmail.com Mon Dec 1 15:19:40 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 01 Dec 2008 21:19:40 +0100 Subject: Emacs vs. Eclipse vs. Vim In-Reply-To: <49335D41.5090505@internode.on.net> References: <1228094836.4406.6.camel@generator> <49335D41.5090505@internode.on.net> Message-ID: <493446DC.7030908@gmail.com> Peter Anderson wrote: > What I have done is skipped the whole Vim/Emacs obscure editor thing > and opted for PyScripter (see > http://mmm-experts.com/Products.aspx?ProductID=4 ). It might not be as > complete/complex as these other editors but it is easy to use and just > lets me get on with the task of cutting code. if it works it's a fair good editor, but if it doesn't (I have to restart the editor about each hour) ... > > As a fall-back I also use EditPlus (see > http://www.editplus.com/index.html ). Its only for Windows but PyScripter is also only for windows ;-) > and its shareware so you need to pay for it. Its clip library makes it > a VERY GOOD text editor. It's a real shame there are NO text editors > with such a comprehensive and easy to modify clip library function (I > would be really pleased to be proven wrong on this last point :-) ). What so great about it ? I use a template manager, written in pure python, works under any OS (where Python is installed) and can be used with any text editor and is open source and completely free. I think it has at least the same capabilities as the Komodo clip library. Somewhere in the middle of the following page are a few notes: http://mientki.ruhosting.nl/data_www/pylab_works/pw_code_editor.html and you can find the sources here: http://code.google.com/p/pylab-works/downloads/list > > However, the best advice I think that can be given about editors is > keep trying them until you find the one YOU like. We all like > different things, especially when it comes to editors. > +1 cheers, Stef From Afro.Systems at gmail.com Mon Dec 29 07:08:54 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Mon, 29 Dec 2008 04:08:54 -0800 (PST) Subject: AttributeError: 'module' object has no attribute 'DatagramHandler' (ubuntu-8.10, python 2.5.2) Message-ID: <4c6f0831-c05f-401f-b956-376600b38e06@r15g2000prd.googlegroups.com> $ ~/devel/ice/snoip/freespeech$ python Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import logging >>> logging.DatagramHandler Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'DatagramHandler' >>> That is odd since the documentation says there is DatagramHandler for module logging From david at hlacik.eu Sat Dec 13 13:23:50 2008 From: david at hlacik.eu (=?ISO-8859-2?Q?David_Hl=E1=E8ik?=) Date: Sat, 13 Dec 2008 19:23:50 +0100 Subject: [OT] stable algorithm with complexity O(n) Message-ID: Hi guys, i am really sorry for making offtopic, hope you will not kill me, but this is for me life important problem which needs to be solved within next 12 hours.. I have to create stable algorithm for sorting n numbers from interval [1,n^2] with time complexity O(n) . Can someone please give me a hint. Would be very very thankful! Thanks in advance! D. From raj.indian.08 at gmail.com Mon Dec 1 09:32:58 2008 From: raj.indian.08 at gmail.com (RajNewbie) Date: Mon, 1 Dec 2008 06:32:58 -0800 (PST) Subject: 11001, 'getaddrinfo failed' : Error in httplib but not in urllib2 Message-ID: Hi all, I am trying to connect to localhost via httplib, but it fails. To check whether it is a firewall problem etc, I tried to connect via urllib2, but it went through fine. Could some one help me out on this? I cannot use urllib2 in the program because I have to send files via post to a url, and urllib2 doesn't support it (Python2.4) Please see the code below: -->HTTPLIB<-- h = httplib.HTTPConnection("http://127.0.0.1:8000") h.request('GET', "/accounts/") res = h.getresponse() -->URLLIB2<-- req = urllib2.Request("http://127.0.0.1:8000/accounts/") fd = urllib2.urlopen(req) Regards Raj From cjw at ncf.ca Mon Dec 29 10:07:00 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Mon, 29 Dec 2008 10:07:00 -0500 Subject: multiply each element of a list by a number In-Reply-To: References: <4955e7be$0$4066$ba4acef3@news.orange.fr> <49580B2E.8050009@ncf.ca> Message-ID: <4958E794.1070704@ncf.ca> skip at pobox.com wrote: >>>>>> "Colin" == Colin J Williams writes: > > Colin> skip at pobox.com wrote: > > >> For extremely short lists, but not for much else: > >> > >> % for n in 1 10 100 1000 10000 100000 ; do > >> > echo "len:" $n > >> > echo -n "numpy: " > >> > python -m timeit -s 'import numpy ; a = numpy.array(range('$n'))' 'a*3' > >> > echo -n "list: " > >> > python -m timeit -s 'a = range('$n')' '[3*x for x in a]' > >> > done > >> len: 1 > >> numpy: 100000 loops, best of 3: 11.7 usec per loop > >> list: 1000000 loops, best of 3: 0.698 usec per loop > >> len: 10 > >> numpy: 100000 loops, best of 3: 11.7 usec per loop > >> list: 100000 loops, best of 3: 2.94 usec per loop > >> len: 100 > >> numpy: 100000 loops, best of 3: 12.1 usec per loop > >> list: 10000 loops, best of 3: 24.4 usec per loop > >> len: 1000 > >> numpy: 100000 loops, best of 3: 15 usec per loop > >> list: 1000 loops, best of 3: 224 usec per loop > >> len: 10000 > >> numpy: 10000 loops, best of 3: 41 usec per loop > >> list: 100 loops, best of 3: 2.17 msec per loop > >> len: 100000 > >> numpy: 1000 loops, best of 3: 301 usec per loop > >> list: 10 loops, best of 3: 22.2 msec per loop > >> > >> This is with Python 2.4.5 on Solaris 10. YMMV. > > Colin> Your comment is justified for len= 100 > Colin> or 1,000 but not for len= 10,000 or 100,000. > > Look again at the time units per loop. > > Colin> I wonder about the variability of the number of loops in your > Colin> data. > > That's how timeit works. It runs a few iterations to see how many to run to > get a reasonable runtime. That's interesting but that's not the way timeit is documented for Python 2.5: timeit( [number=1000000]) Time number executions of the main statement. This executes the setup statement once, and then returns the time it takes to execute the main statement a number of times, measured in seconds as a float. The argument is the number of times through the loop, defaulting to one million. The main statement, the setup statement and the timer function to be used are passed to the constructor. > > Colin> I have tried to repeat your test with the program below, but it > Colin> fails to cope with numpy. > > I stand by my assertion that numpy will be much faster than pure Python for > all but very short lists. > In spite of the fact that your own data doesn't support the assertion? I would have expected numpy to be the clear winner for len > 1,500. Perhaps your data questions the value of timeit as a timing tool. Colin W. From bgailer at gmail.com Mon Dec 15 08:31:30 2008 From: bgailer at gmail.com (bob gailer) Date: Mon, 15 Dec 2008 08:31:30 -0500 Subject: [Tutor] Having Issues with CMD and the 'python' command In-Reply-To: References: Message-ID: <49465C32.7020200@gmail.com> An HTML attachment was scrubbed... URL: From shaomumu at gmail.com Tue Dec 16 14:22:53 2008 From: shaomumu at gmail.com (Lin) Date: Tue, 16 Dec 2008 11:22:53 -0800 (PST) Subject: sys.maxint in Python 2.6.1 (amd64) on Windows XP x64 References: <4bddf65a-bb9f-406c-a544-8c38b27547a7@b38g2000prf.googlegroups.com> Message-ID: <7a629cb1-0fbc-41d4-ac51-d0be68df1df5@r36g2000prf.googlegroups.com> > > > I installed the amd64 version of Python 2.6.1 on my Windows XP x64 > > system. I was expecting sys.maxint to be 9223372036854775807 (or 2 ^63 > > -1), but instead I got 2147483647 (i.e., 2^31-1) just like what I got > > from a 32-bit version of Python. Is this by design or does it indicate > > a bug or an installation problem? Thank you very much! > > This is by design. In their infinitive wisdom Microsoft has decided to > make the 'long' C type always a 32 bit signed integer - even on 64bit > systems. On most Unix systems a long is at least 32 bit but usually > sizeof(ptr). > Ah, this makes sense. Thanks...... The main reason I'm trying 64-bit Python is that I want to write files bigger than 4GB. This should work on Windows x64, right? (i.e., are the pointers bona fide 64 bit?) -lin From ianare at gmail.com Tue Dec 16 15:59:46 2008 From: ianare at gmail.com (=?ISO-8859-1?B?aWFuYXLp?=) Date: Tue, 16 Dec 2008 12:59:46 -0800 (PST) Subject: sorting for recursive folder rename References: Message-ID: <56d7c5b3-314d-43bd-a292-197fbbd4853c@v5g2000prm.googlegroups.com> On Dec 16, 2:00?pm, MRAB wrote: > ianar? wrote: > > Hello all, > > > I trying to recursively rename folders and files, and am looking for > > some ideas on the best way of doing this. The problem is that the > > given list of items can be in order, and one to all items may be > > renamed. Here is some preliminary code I have, but which does not work > > very well. > > > self.toRename has the following structure : > > [ > > [original_name, new_name, os.path.isdir] > > .. > > ] > > > # define these here for faster processing > > def split(item): > > ? ? return os.path.split(item) > > def addSep(path): > > ? ? return os.sep + path + os.sep > > def recursiveFolderSort(x,y): > > ? ? return cmp(y[0], x[0]) > > > sortedRename = sorted(self.toRename) > > > # make a list of all folders that will be processed > > foldersToAdjust = [] > > for item in sortedRename: > > ? ? if item[2] is False: > > ? ? ? if not item[2]:> ? ? ? ? oF = split(item[0])[1] # original folder name > > ? ? ? ? nF = split(item[1])[1] # new folder name > > ? ? ? ? if oF is not nF: > > ? ? ? ? ? if oF != nF:> ? ? ? ? ? ? foldersToAdjust.append((oF, nF)) > > > # replace all occurences of folders in path > > for i in range(len(self.toRename)): > > ? ? for f in foldersToAdjust: > > ? ? ? ? oF = addSep(f[0]) # original folder name > > ? ? ? ? nF = addSep(f[1]) # new folder name > > ? ? ? ? self.toRename[i][0] = self.toRename[i][0].replace(oF,nF) > > ? ? ? ? self.toRename[i][1] = self.toRename[i][1].replace(oF,nF) > > > ? ? if progressDialog.update(i) is False: > > ? ? ? if not progressDialog.update(i):> ? ? ? ? error = 'cancelled' > > ? ? ? ? break > > > # make sure renaming will be in correct order ! > > self.toRename.sort(recursiveFolderSort) > > > First problem is adjusting the paths can take a very long time. > > Second problem is sorting is not always right and files get lost !! > > Any input welcome. > > You should use "is" and "is not" _only_ when checking for _identity, ie > are these 2 both references to the _same_ object. Most of the time that > would be "x is None" or "x is not None". Thanks, this has been corrected. From raj.indian.08 at gmail.com Sun Dec 21 13:51:07 2008 From: raj.indian.08 at gmail.com (RajNewbie) Date: Sun, 21 Dec 2008 10:51:07 -0800 (PST) Subject: Are python objects thread-safe? Message-ID: Say, I have two threads, updating the same dictionary object - but for different parameters: Please find an example below: a = {file1Data : '', file2Data : ''} Now, I send it to two different threads, both of which are looping infinitely: In thread1: a['file1Data'] = open(filename1).read and in thread2: a['file2Data'] = open(filename2).read My question is - is this object threadsafe? - since we are working on two different parameters in the object. Or should I have to block the whole object? From martin at v.loewis.de Sat Dec 13 17:27:33 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 13 Dec 2008 23:27:33 +0100 Subject: [ANN] Python 2.4.6 and 2.5.3, release candidate 1 Message-ID: <494436D5.6050103@v.loewis.de> On behalf of the Python development team and the Python community, I'm happy to announce the release candidates of Python 2.4.6 and 2.5.3. 2.5.3 is the last bug fix release of Python 2.5. Future 2.5.x releases will only include security fixes. According to the release notes, over 100 bugs and patches have been addressed since Python 2.5.1, many of them improving the stability of the interpreter, and improving its portability. 2.4.6 includes only a small number of security fixes. Python 2.6 is the latest version of Python, we're making this release for people who are still running Python 2.4. See the release notes at the website (also available as Misc/NEWS in the source distribution) for details of bugs fixed; most of them prevent interpreter crashes (and now cause proper Python exceptions in cases where the interpreter may have crashed before). Assuming no major problems crop up, a final release of Python 2.4.6 and 2.5.3 will follow in about a week's time. For more information on Python 2.4.6 and 2.5.3, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.4.6 http://www.python.org/2.5.3 Highlights of the previous major Python releases are available from the Python 2.5 page, at http://www.python.org/2.4/highlights.html http://www.python.org/2.5/highlights.html Enjoy this release, Martin Martin v. Loewis martin at v.loewis.de Python Release Manager (on behalf of the entire python-dev team) From steve at REMOVE-THIS-cybersource.com.au Sun Dec 28 01:58:18 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Dec 2008 06:58:18 GMT Subject: math module for Decimals References: Message-ID: <01671a9e$0$6988$c3e8da3@news.astraweb.com> On Sat, 27 Dec 2008 16:02:51 -0800, jerry.carl.mi wrote: > Hi, > > I have been looking for a Python module with math functions that would > both eat and spit Decimals. The standard math module eats Decimals > allright but spits floats... herefore exp(sin(Decimal())) produces exp > () of a float :-( You can write your own wrappers. Assuming you always want to return decimals instead of floats: from decimal import Decimal import math def exp(x): if isinstance(x, Decimal): return x.exp() f = math.exp(x) return make_decimal(f) def sin(x): f = math.sin(x) return make_decimal(f) You can get fancier if you like: def cos(x): try: return x.cos() except AttributeError: f = math.cos(x) return make_decimal(f) That version will automatically use Decimal.cos() in the future, assuming Decimals grow a cos() method. If they don't, it will continue to work (although a tad slower than the sin() above. Converting floats to decimals is tricky, because you have to decide how much precision you care about. You can keep all the precision of floats. Depending on your needs, this is either a feature or a gotcha: >>> (1.0/3).as_integer_ratio() # expecting (1, 3) (6004799503160661L, 18014398509481984L) Anyway, here are at least three ways to write make_decimal: # Python 2.6 only def make_decimal(f): # exact, no loss of precision # however, will fail for f = NAN or INF a, b = f.as_integer_ratio() return Decimal(a)/Decimal(b) def make_decimal(f): return Decimal("%r" % f) def make_decimal(f, precision=16): # choose how many decimal places you want to keep return Decimal.from_float(f, precision) You choose which suits you best. > So far, i found: > > -AJDecimalMathAdditions (http://www.ajgs.com/programming/ > PythonForDownload.html) > -decimalfuncs (http://pypi.python.org/pypi/decimalfuncs/1.4) -and dmath > (http://pypi.python.org/pypi/dmath/0.9) > > I tried using the AJDecimalMathAdditions, but ran into issues like dSin > (1E4) would take forever to calculate and would result in sin() > 1 ... > If i understand it correctly, the program is using maclaurin series to > calculate the value and since it does not chop off all the multiples of > 2*pi, the maclaurin approximation becomes useless when its too far from > x=0. You might try something like this: pi = Decimal("%r" % math.pi) twopi = 2*pi pi2 = pi/2 def sin(x): # *** UNTESTED *** if x < 0: return -sin(-x) elif x > twopi: x = remainder(x, twopi) return sin(x) elif x > pi: return -sin(x - pi) elif x > pi2: return sin(pi - x) else: return AJDecimalMathAdditions.dSin(x) You can treat cos and tan similarly but not identically. However, you might find that it quicker and simpler to just do your maths calculations as floats, then convert to decimals, as in my earlier examples. > I also ran into some issues with the decimalfuncs, but i have never > tried the dmath thing. > > Now, i can go and start modifying these modules to behave more like the > standard math module but since i am neither mathematician or programer, > i really hesitate. And so you should. Getting numerical functions correct is damn hard. However, if all you need is "close enough", then don't be scared -- the sort of tricks I've shown are probably "close enough", although you may want a disclaimer about not using them for running nuclear reactors or flying aircraft. The basic tools Python supplies are pretty good, and you can probably get a 95% solution with them without being an expert in computational mathematics. > So my questions are: > > (1) what do folks use when they need to calculate something like exp > (sin(Decimal())) or even more complex things? Any recommendations? Or am > I completely missing something? > > (2) Is there any plan to provide a standard python module that would do > that? (Python 4.0? ;-) Guido is very reluctant to put numeric libraries in the standard library, precisely because it is so hard to get it right. Don't expect Python to become Mathematica any time soon! -- Steven From digitig at gmail.com Sun Dec 7 16:48:46 2008 From: digitig at gmail.com (Tim Rowe) Date: Sun, 7 Dec 2008 21:48:46 +0000 Subject: Is 3.0 worth breaking backward compatibility? In-Reply-To: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> Message-ID: 2008/12/7 walterbyrd : > IMO: breaking backward compatibility is a big deal, and should only be > done when it is seriously needed. > > Also, IMO, most of, if not all, of the changes being made in 3.0 are > debatable, at best. I can not think of anything that is being changed > that was really a "show stopper" anyway. But that's what a major release number does for you. Modula2 was quite a break from Modula. Think of Python3.0 it as a new language, if you like, that's inspired by Python2. You can stay with Python2 or you can adopt the new language. That way you won't have to think of it in terms of breaking any sort of backwards compatibility because there is no backwards ;-) -- Tim Rowe From deets at nospam.web.de Tue Dec 30 08:32:29 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 30 Dec 2008 14:32:29 +0100 Subject: How to debug embeding Python? In-Reply-To: References: Message-ID: <6rum7dF3elu4U1@mid.uni-berlin.de> Hongtian schrieb: > Hi Friends, > > My application is written in C/C++ and Python is embed to extend some > functions (several .py files are invoked). But I am confused how to > debug these embed Python? Can I use 'print-debuging'? and where can I > capture the output string? > > Or Python can support 'break' debug for such scenario? You should be able to use the python debugger (pdb) by manually putting import pdb; pdb.set_trace() on a place that is of interest to you. Then if your program is started inside a shell, you should be able to step-debug it. Additinoally, there is the very flexible & powerful logging-module that you can use to write logfiles. This is better than simple print-statements, as you can keep the logging statements around and just turn them on or off on demand. Additionally, printing might not work reliably in cases where the stdout/err-streams aren't visible or otherwise in use. But the logging-module can log to files (or even system event logs *me thinks*) Diez From acerimusdux at comcast.net Mon Dec 8 09:04:44 2008 From: acerimusdux at comcast.net (acerimusdux) Date: Mon, 08 Dec 2008 09:04:44 -0500 Subject: Beginner trying to understand functions. Message-ID: <493D297C.9040504@comcast.net> simonh write: > In my attempt to learn Python I'm writing a small (useless) program to > help me understand the various concepts. I'm going to add to this as I > learn to serve as a single place to see how something works, > hopefully. Here is the first approach: > > > > name = input('Please enter your name: ') > print('Hello', name) > > while True: > try: > age = int(input('Please enter your age: ')) > break > except ValueError: > print('That was not a valid number. Please try again.') > > permitted = list(range(18, 31)) > > if age in permitted: > print('Come on in!') > elif age < min(permitted): > print('Sorry, too young.') > elif age > max(permitted): > print('Sorry, too old.') > > input('Press any key to exit.') > > > > That works fine. Then I've tried to use functions instead. The first > two work fine, the third fails: > > > > def getName(): > name = input('Please enter your name: ') > print('Hello', name) > > def getAge(): > while True: > try: > age = int(input('Please enter your age: ')) > break > except ValueError: > print('That was not a valid number. Please try again.') > > def checkAge(): > permitted = list(range(18, 31)) > if age in permitted: > print('Come on in!') > elif age < min(permitted): > print('Sorry, too young.') > elif age > max(permitted): > print('Sorry, too old.') > > getName() > getAge() > checkAge() > > I get this error message: NameError: global name 'age' is not > defined. > > I'm stuck, can someone help? Thanks. > You are running into Python's scoping rules. Variables in Python are not global by default, they are local to their scope. Each function has it's own scope (but blocks like if: and while: don't.) So your variable "age" only exists in getage(). It doesn't exist in checkage(). You could simply add a "global age" statement to getAge() before you first use the age variable, and that will likely work. Or, rather than declare it global, you might want to have getage() return a value, and then pass it to checkage () as a function parameter. Add a "return age" statement to getage() before "break". Then, for your def: def checkage(age): And then when calling: A=getAge() checkAge(A) From deets at nospam.web.de Wed Dec 24 12:52:50 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 24 Dec 2008 18:52:50 +0100 Subject: Iterating over objects of a class In-Reply-To: <2df27de3-7fa3-4ac9-acd9-f946939517cf@r37g2000prr.googlegroups.com> References: <2df27de3-7fa3-4ac9-acd9-f946939517cf@r37g2000prr.googlegroups.com> Message-ID: <6rfb7iF1fg5rU1@mid.uni-berlin.de> Kottiyath schrieb: > Hi, > How can I iterate over all the objects of a class? > I wrote the code like following: > class baseClass(object): Consider adopting PEP 8 coding conventions. > __registry = [] > > def __init__(self, name): > self.__registry.append(self) > self.name = name > > def __iter__(self): > baseClass.item = 0 > return self.__registry[0] > > def next(self): > if baseClass.item >= len(self.__registry): > raise StopIteration > baseClass.item += 1 > return self.__registry[baseClass.item - 1] > > For testing, create the following objects- > a = baseClass("Test1") > b = baseClass("Test2") > > class subClass (baseClass): > pass > c = subClass("Test3") > > ---->Actual Iteration<---- > for i in a: > print i.name > > Test1 > Test2 > Test3 > > --------------------------------------------------- > I see the following problems in the code: > 1. I have to iterate over any of the objects. For correctness, I > wanted to iterate over the class, like > for i in baseClass(): > do x > but that will will create one more object - which I do not want. > > 2. If the subclass wants to do somethings in its constructor, I am not > sure how to update the registry. > class subClass (baseClass): > def __init__(self, name): > **do something** > super.init(self, name) ----> This errors out, saying it needs > super, not subClass You don't show the actual traceback, however the idiom for invoking super for new-style-classes is super(subClass, self).__init__(name) for your case. > Another method I thought of implementing it was using generators - > where-in baseClass.objects() is a generator which will yield the > objects one by one - but even then the second issue remains. > If somebody can help me out, I would be very thankful. Using a generator or not isn't the issue here. What you need is a *class*-based access, not instance-based. There are various methods to accomplish this. The simplest is to ditch the obnoxious __registry as name, and just do class BaseClass(object): REGISTRY = [] Then iterating is a simple matter of for instance in BaseClass.REGISTRY: ... Case solved. Alternatively, if you insist on the concept of privacy for that registry, you can use a classmethod: class BaseClass(object): @classmethod def registry(cls): for i in cls.__registry: yield i Last but not least you *could* go for a __metaclass__ with an __getitem__-method, that makes thinks look fancy because you then can do: for instance in BaseClass: ... I leave it as an exercise to you - gotta go christmas dining now :) Diez From castironpi at gmail.com Tue Dec 23 15:23:45 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 23 Dec 2008 12:23:45 -0800 (PST) Subject: Are python objects thread-safe? References: <5306b56c-eb8c-4148-b426-013caa871375@b41g2000pra.googlegroups.com> Message-ID: <867b3e71-f5f3-43e8-9232-2b683a516540@b41g2000pra.googlegroups.com> On Dec 23, 7:30?am, Duncan Booth wrote: > Aaron Brady wrote: > > Th.1 ? Th.2 > > a=X > > ? ? ? ?a=Y > > a=Z > > > You are saying that if 'a=Z' interrupts 'a=Y' at the wrong time, the > > destructor for 'X' or 'Y' might not get called. ?Correct? ?In serial > > flow, the destructor for X is called, then Y. > > No, the destructors will be called, but the destructors can do pretty much > anything they want so you can't say the assignment is atomic. This isn't > actually a threading issue: you don't need multiple threads to experience > werid issues here. If you do strange things in a destructor then you can > come up with confusing code even with a single thread. I see. What about del a a= Z Then, can we say 'a=Z' is atomic? At least, it eliminates the destructor issue you raise. > >> Other nasty things can happen if you use dictionaries from multiple > >> threads. You cannot add or remove a dictionary key while iterating over > >> a dictionary. This isn't normally a big issue, but as soon as you try to > >> share the dictionary between threads you'll have to be careful never to > >> iterate through it. > > > These aren't documented, IIRC. ?Did you just discover them by trial > > and error? > > It is documented, but I can't remember where for Python 2.x. For Python 3, > PEP 3106 says: "As in Python 2.x, mutating a dict while iterating over it > using an iterator has an undefined effect and will in most cases raise a > RuntimeError exception. (This is similar to the guarantees made by the Java > Collections Framework.)" I infer that d.items() holds the GIL during the entire operation, and it's safe to put in a thread. It is merely using an iterator that is unsafe. (Python 3.0 removed d.items(), leaving only the iterator, I understand.) I'm looking at the code, and I don't see where the size is safely checked. That is, can't I sneak in an add and a remove during iteration, so long as it doesn't catch me? I'm looking at 'dict_traverse': while (PyDict_Next(op, &i, &pk, &pv)) { Py_VISIT(pk); Py_VISIT(pv); } No locks are acquired here, though I might have missed acquiring the GIL somewhere else. In the OP's example, he wasn't changing the size of the dict. From Scott.Daniels at Acm.Org Fri Dec 19 19:05:42 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 19 Dec 2008 16:05:42 -0800 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: excord80 wrote: > On Dec 19, 11:01 am, walterbyrd wrote: >> To me, it seems that this: >> print "%s=%d" % ('this',99) >> Is much easier, ... >> This (if it's right) is much longer, ... >> print( "{0}={1}".format('this',99)) > Yeah, I like the old way better too. It's got this nice elegant > simplicity to it (using the percent sign for not only the things > inside the string, but also to separate it from the tuple that > follows). Also, I like having only *one* special symbol (`%') to worry > about in my strings instead of two (`{' and `}'). Ah, but for internationalization, you can change the format string to take args in a different order if, for example, French messages want modifiers on one side and English on the other. The code can stay the same, while only the text used to do the formatting must change. --Scott David Daniels Scott.Daniels at Acm.Org From tjreedy at udel.edu Wed Dec 3 02:07:53 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 03 Dec 2008 02:07:53 -0500 Subject: porting modules to Python 3.0 In-Reply-To: <4936255D.6000509@v.loewis.de> References: <8f60c779-f1ec-4127-b173-f174c016aa96@a12g2000yqm.googlegroups.com> <4936255D.6000509@v.loewis.de> Message-ID: Martin v. L?wis wrote: >> Is there something like that already in place? What are the >> recommendations for library >> authors willing to support both Python 2.X and 3.X in parallel? > > My recommendation is to use 3.0's build_py_2to3 implementation of > the build_py command. See Demo/distutils/test2to3. > > You will have a single lib.py, written in 2.x. When you install > in 3.0, lib2to3 will convert it to 3.x in the build area, and > then install the 3.0 version. > > That, of course, requires you to adjust lib.py in such a way that > 2to3 will successfully and completely convert it. In my experience > (with porting Django) and Mark Hammond's experience (with porting > PythonWin), this should be always possible. You look at what 2to3 > does, find out what additional modifications need to be done, and > apply them to the input of 2to3 so that > a) 2to3 leaves these changes in place > b) they either have no effect or still work correctly when run > in 2.x. > > Regards, > Martin > -- > http://mail.python.org/mailman/listinfo/python-list In one has both 2.x and 3.0 installed, would it easy to install 'lib.py' for both? From drobinow at gmail.com Sun Dec 14 19:54:47 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Sun, 14 Dec 2008 16:54:47 -0800 (PST) Subject: Looking for the best way to translate an idiom References: Message-ID: On Dec 14, 11:19?am, Paul Moore wrote: > I'm translating some code from another language (Lua) which has > multiple function return values. So, In Lua, it's possible to define a > function > > ? ? function f() > ? ? ? ? return 1,2,3 > ? ? end > > which returns 3 values. These can then be used/assigned by the caller: > > ? ? a,b,c = f() > > So far, much like Python, but the key difference is that in Lua, > excess arguments are ignored - so you can do > > ? ? a = f() > or even > ? ? a = f() + 1 > > where in the latter, a is 2 (as addition only needs 1 argument, so the > extra ones are discarded). > > This results in the code which I'm trying to translate having > functions which return multiple arguments, the first of which is the > "main" result, and the following values are "extra" results > (specifically, the position at which a match is found, followed by the > "captured" values of the match). > > I'm trying to find a natural equivalent in Python. So far, I've > considered the following: > > - return a tuple (pos, captures). This is messy, because you end up > far too often unpacking the tuple and throwing away the second value > - return an object with pos and captures attributes. This is better, > as you can do match(...).pos to get the position alone, but it doesn't > really feel "pythonic" (all those calls with .pos at the end...) > - have 2 calls, one to return just the position, one to return both. > This feels awkward, because of the 2 method names to remember. > > To make things worse, Lua indexes strings from 1, so it can use a > position of 0 to mean "no match" - so that a simple "did it match?" > test looks like if (match(....))... - where in Python I need if > (matchpos(...) != -1)... (Although if I return a match object, I can > override __nonzero__ to allow me to use the simpler Lua form). > > Can anyone suggest a good idiom for this situation? At the moment, I'm > returning a match object (the second option) which seems like the > least bad of the choices (and it mirrors how the re module works, > which is somewhat useful). But I'd like to know what others think. If > you were using a pattern matching library, what interface would you > prefer? > > I suspect my intuition isn't accurate here, as most of the use I've > made of the library is in writing tests, which isn't typical use :-( > > Thanks for any assistance. > > Paul I'm baffled by this discussion. What's wrong with a, dontcare, dontcare2 = f() a = a + 1 Simple, clear, and correct. From google at mrabarnett.plus.com Fri Dec 12 18:43:07 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 12 Dec 2008 23:43:07 +0000 Subject: os.lstat : proper way to do this In-Reply-To: References: Message-ID: <4942F70B.4030409@mrabarnett.plus.com> m1k3b0 at gmail.com wrote: > I'm converting from Perl to Python, so I'm learning the basics - > please be gentle! :) > > In Perl, I can lstat($file) whether $file exists or not: > lstat($file); > unless (-e _) { > print STDERR "$file: No such file or directory\n"; > } > unless (-l _) { > print STDERR "$file: Not a symbolic link\n"; > } > > The lstat() returns normally whether the file exists or not, and I > check for existence with the "-e" conditional. Then I go on and check > other modes. > > In Python,if I os.lstat(file) and file doesn't exist, I get an error > from within the module: > OSError: [Errno 2] No such file or directory: '/etc/xxx' > > I can check first with os.path.exists(file), but then I'm doing two > stat() type calls which is inefficient (especially when we're talking > thousands of files). > > I want to be able to do something like this: > mode = os.lstat(file)[ST_MODE] > if not mode: > print >> sys.stderr, file, ": No such file or directory" > if not S_ISLNK(mode): > print >> sys.stderr, file, ": Not a symbolic link" > > Of course, this isn't valid. How can I do this efficiently without > getting "no such file" error? > Just catch the exception: try: mode = os.lstat(file).st_mode # An alternative way. # If we get here then the file does exist. if not S_ISLNK(mode): print >> sys.stderr, file, ": Not a symbolic link" except OSError, e: if e.errno == 2: # File doesn't exist. print >> sys.stderr, file, ": No such file or directory" else: # Failed for some other reason. BTW, "file" happens to be the name of one of the build-ins, so try to use something else, eg. "file_path". From geekmail at usenot.de Thu Dec 11 13:41:57 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Thu, 11 Dec 2008 19:41:57 +0100 Subject: Is 3.0 worth breaking backward compatibility? References: <45f08d8a-731f-4b90-9383-e07278861c29@u18g2000pro.googlegroups.com> <20081207203553.7d62434a@usenot.de> <4731f7cf-ef15-4328-85a4-de4437009f2e@40g2000prx.googlegroups.com> Message-ID: <20081211194157.32f57d3e@usenot.de> On Thu, 11 Dec 2008 10:21:55 -0800 (PST) walterbyrd wrote: > On Dec 7, 12:35?pm, Andreas Waldenburger wrote: > > > Pleeeeze. Python 3 is shipping now, and so is 2.x, where x > 5. > > Python 2 is going to be around for quite some time. What is > > everybody's problem? > > A possible, potential, problem, could arise if you were using python > 2.x, but some other code, that you wanted to include, was writen in > python 3.x. > Yes, that would be a problem, of course. But I fail to see how that is not a problem with python 2.x as well. New Style Classes? Generators? The "with" statement? I use those all the time. Why aren't as many people complaining about them with the same argument? /W -- My real email address is constructed by swapping the domain with the recipient (local part). From sjmachin at lexicon.net Mon Dec 22 16:05:46 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 22 Dec 2008 13:05:46 -0800 (PST) Subject: How to represent a sequence of raw bytes References: <200812220327.36180.motoom@xs4all.nl> <015f66d7$0$20615$c3e8da3@news.astraweb.com> Message-ID: <44a5f0ac-3021-443f-90f2-5f3bd0116d4b@w1g2000prk.googlegroups.com> On Dec 23, 1:52?am, "Steven Woody" wrote: > On Mon, Dec 22, 2008 at 6:44 PM, Steven D'Aprano > > wrote: > > On Mon, 22 Dec 2008 14:56:45 +0800, Steven Woody wrote: > > >> The intension is to allocate 200 undefined bytes in memory. > > > You *want* undefined bytes? Out of curiosity, what do you intend to do > > with them? > > to receive/send network packets, read raw files, etc. ?After read > replies of the thread, I think 'array' or 'struct' maybe what I > wanted, may a plain list can do, but I am not sure. [Rhetorical questions] How do you use "undefined bytes" to receive network packets?? Do you really want to use "undefined bytes" to *send* network packets???? Suggestion: Stop trying to replicate C in Python; think about what you are trying to accomplish at a higher level, then how to implement that in Python. Cheers, John From mensanator at aol.com Fri Dec 19 10:57:53 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 19 Dec 2008 07:57:53 -0800 (PST) Subject: How to parsing a sequence of integers References: <494ba258$0$18998$426a74cc@news.free.fr> Message-ID: On Dec 19, 9:23?am, Joe Strout wrote: > Peter Otten wrote: > > If you are using Python 2.x: > > ... > > So you better throw in a float(...): > > Or, add > > ? ?from __future__ import division > > at the top of the file. ?I put this at the top of all my Python files, > whether I expect to be dividing or not. ?It just saves grief. If you want division to be floating point. If, like me, you rarely do floating point division and want the "/" to mean integer division as God intended, then you don't put from __future__ import division in your source files. That's one of the good things about Python, you can have it either way. > > Cheers, > - Joe From inigoserna at gmail.com Sat Dec 20 18:52:24 2008 From: inigoserna at gmail.com (=?UTF-8?Q?I=C3=B1igo_Serna?=) Date: Sun, 21 Dec 2008 00:52:24 +0100 Subject: ANN: lfm v2.1 Message-ID: <65a1d6f80812201552s438150eeh40dd830fb515855c@mail.gmail.com> Hi there, As a present for Christmas I announce here a new version of 'lfm'. Description: ========= Last File Manager is a simple but powerful file manager for the UNIX console. It's written in Python, using curses module. Licensed under GNU Public License version 3. Some of the features you could find in lfm: - console-based file manager for UNIX platforms - 1-pane or 2-pane view - tabs - bookmarks - history - vfs for compressed files - dialogs with entry completion - fast access to a shell - direct integration of find/grep, df and other tools - color files by extension - fast file viewer with text and binary modes - ...and many others Download it from: ============= http://www.terra.es/personal7/inigoserna/lfm or if it doesn't show last version (crap of ISP reverse proxy), try this low-bandwidth home server: http://inigo.katxi.org/devel/lfm Changes since last version: ==================== Version 2.1 ("What do you want for Christimas?") - 2008/12/21: + Ctrl-H now show/hide dot files + Ctrl-Y display directories history + It's now posible to move the cursor in the non-active pane Consult the documentation for available keys and actions This behaviour is de/activated with Ctrl-W + added support for .7z compressed files + swapped F2 and F12 keys, now F2 rename files and F12 show file menu + new key shortcuts in dialogs. Read docs + speed up cursor movement + lots of code cleaning and refactoring + and fixed lot of bugs, some of them: - setup.py: change I?igo for Inigo to avoid problems when installing - sorting by None doesn't crash anymore - MenuWin dialog crashed when title length was greater than length of entries to show Of course, all comments, suggestions, etc. are welcome. Best regards, I?igo Serna From sumerc at gmail.com Thu Dec 4 12:45:09 2008 From: sumerc at gmail.com (k3xji) Date: Thu, 4 Dec 2008 09:45:09 -0800 (PST) Subject: Python Runtime Method Call Binding References: <0147f396$0$20670$c3e8da3@news.astraweb.com> Message-ID: <0ad65087-9b50-4d11-85a4-0ebf7e8e01a0@c1g2000yqg.googlegroups.com> test From arkanes at gmail.com Wed Dec 10 11:22:29 2008 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 10 Dec 2008 10:22:29 -0600 Subject: Flushing PyQt's Event Queue In-Reply-To: <19d41195-a734-4974-ad02-b6ddf62c316f@v5g2000prm.googlegroups.com> References: <19d41195-a734-4974-ad02-b6ddf62c316f@v5g2000prm.googlegroups.com> Message-ID: <4866bea60812100822u39cf705ay118ff6a4fb40d785@mail.gmail.com> On Wed, Dec 10, 2008 at 6:30 AM, ff wrote: > Hi, I am writing an app which models growth of a system over time > visually which is activated by button clicks, and when the loop > finishes running i dont want any events [mainly clicking on buttons] > that happened during the loop to be put into action since then it may > run multiple times without the user realising what they have done, > > is there way to flush the event queue when the loop has finished?? This is a UI problem, not a programming problem. Instead of trying to find a code solution to the problem, consider changing your UI so that the actions aren't possible. For example, disable the buttons (perhaps showing by showing a progress dialog box with a cancel button) while the sim is running. From pdorange at pas-de-pub-merci.mac.com Mon Dec 8 08:57:02 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Mon, 8 Dec 2008 14:57:02 +0100 Subject: Beginner trying to understand functions. References: Message-ID: <1irmx3x.1ye1mpc1xmopj2N%pdorange@pas-de-pub-merci.mac.com> simonh wrote: > def getName(): > name = input('Please enter your name: ') > print('Hello', name) > > def getAge(): > while True: > try: > age = int(input('Please enter your age: ')) > break > except ValueError: > print('That was not a valid number. Please try again.') > > def checkAge(): > permitted = list(range(18, 31)) > if age in permitted: > print('Come on in!') > elif age < min(permitted): > print('Sorry, too young.') > elif age > max(permitted): > print('Sorry, too old.') > > getName() > getAge() > checkAge() > > I get this error message: NameError: global name 'age' is not > defined. Indeed age was not a global... So : 1/ make it a global (just define "age=0" before getAge() 2/ or return a value from getAge() and pass this avlue to checkAge. I recommand the second option, less globals is always better. def getAge(): while True: try: age = int(input('Please enter your age: ')) return age except ValueError: print('That was not a valid number. Please try again.') def checkAge(age,min=18,max=31): if age in list(range(min, max)): print('Come on in!') elif age < min: print('Sorry, too young.') elif age > max: print('Sorry, too old.') getName() a=getAge() checkAge(a) For my part, i wouldn't loop getAge(? this way : i dislike infinite loop. I prefer to return None when ther is an error and check for None in the main program def getAge(): try: age = int(input('Please enter your age: ')) return age except ValueError: print('That was not a valid number. Please try again.') return None getName() a=getAge() if a!=None: checkAge(a) of i you want to loop in getAge() : def getAge(): age=-1 while age<0: try: age = int(input('Please enter your age: ')) except ValueError: print('That was not a valid number. Please try again.') return age I'm a beginner with python, perhaps it was not "pythonic", but i'm sure someone will tell is it's not. -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From rhf22 at mole.bio.cam.ac.uk Sun Dec 7 11:23:59 2008 From: rhf22 at mole.bio.cam.ac.uk (Rasmus Fogh) Date: Sun, 7 Dec 2008 16:23:59 +0000 (GMT) Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: > On Sun, 07 Dec 2008 13:03:43 +0000, Rasmus Fogh wrote: >> Jamed Stroud Wrote: > ... >>> Second, consider that any value in python also evaluates to a truth >>> value in boolean context. > But bool(x) can fail too. So not every object in Python can be > interpreted as a truth value. >>> Third, every function returns something. > Unless it doesn't return at all. >>> A function's returning nothing >>> is not a possibility in the python language. None is something but >>> evaluates to False in boolean context. >> Indeed. The requirement would be not that return_value was a boolean, >> but that bool(return_value) was defined and gave the correct result. > If __bool__ or __nonzero__ raises an exception, you would like Python to > ignore the exception and return True or False. Which should it be? How > do you know what the correct result should be? > From the Zen of Python: > "In the face of ambiguity, refuse the temptation to guess." > All binary operators are ambiguous when dealing with vector or array > operands. Should the operator operate on the array as a whole, or on > each element? The numpy people have decided that element-wise equality > testing is more useful for them, and this is their prerogative to do so. > In fact, the move to rich comparisons was driven by the needs of numpy. > http://www.python.org/dev/peps/pep-0207/ > It is a *VERY* important third-party library, and this was not the first > and probably won't be the last time that their needs will move into > Python the language. > Python encourages such domain-specific behaviour. In fact, that's what > operator-overloading is all about: classes can define what any operator > means for *them*. There's no requirement that the infinity of potential > classes must all define operators in a mutually compatible fashion, not > even for comparison operators. > For example, consider a class implementing one particular version of > three-value logic. It isn't enough for == to only return True or False, > because you also need Maybe: > True == False => returns False > True == True => returns True > True == Maybe => returns Maybe > etc. > Or consider fuzzy logic, where instead of two truth values, you have a > continuum of truth values between 0.0 and 1.0. What should comparing two > such fuzzy values for equality return? A boolean True/False? Another > fuzzy value? > Another one from the Zen: > "Special cases aren't special enough to break the rules." > The rules are that classes can customize their behaviour, that methods > can fail, and that Python should not try to guess what the correct value > should have been in the event of such a failure. Equality is a special > case, but it isn't so special that it needs to be an exception from > those rules. > If you really need a guaranteed-can't-fail[1] equality test, try > something like this untested wrapper class: > class EqualityWrapper(object): > def __init__(self, obj): > self.wrapped = obj > def __eq__(self, other): > try: > return bool(self.wrapped == other) > except Exception: > return False # or maybe True? > Now wrap all your data: > data = [a list of arbitrary objects] > data = map(EqualityWrapper, data) > process(data) > [1] Not a guarantee. Well, lots to think about. Just to keep you from shooting at straw men: I would have liked it to be part of the design contract (a convention, if you like) that 1) bool(x == y) should return a boolean and never throw an error 2) x == x return True I do *not* say that bool(x) should never throw an error. I do *not* say that Python should guess a return value if an __eq__ function throws an error, only that it should have been considered a bug, or at least bad form, for __eq__ functions to do so. What might be a sensible behaviour (unlike your proposed wrapper) would be the following: def eq(x, y): if x is y: return True else: try: return (x == y) except Exception: return False If is is possible to change the language, how about having two diferent functions, one for overloading the '==' operator, and another for testing list and set membership, dictionary key identity, etc.? For instance like this - Add a new function __equals__; x.__equals__(y) could default to bool(x.__eq__(y)) - Estalish by convention that x.__equals__(y) must return a boolean and may not intentionally throw an error. - Establish by convention that 'x is y' implies 'x.__equals__(y)' in the sense that (not (x is y and not x.__equals__(y)) must always hold - Have the Python data structures call __equals__ when they want to compare objects internally (e.g. for 'x in alist', 'x in adict', 'set(alist)', etc. - Provide an equals(x,y) built-in that calls the __equals__ function - numpy and others who (mis)use '==' for their own purposes could use def __equals__(self, other): return (self is other) For the float NaN case it looks like things are already behaving like this. For numpy objects you would not lose anything, since 'numpyArray in alist' is broken anyway. I still think it is a bad choice that numpy got to write array1 == array2 for their purposes, while everybody else has to use if equals(x, y): but at least both sides could get the behaviour they want. Yours, Rasmus --------------------------------------------------------------------------- Dr. Rasmus H. Fogh Email: r.h.fogh at bioc.cam.ac.uk Dept. of Biochemistry, University of Cambridge, 80 Tennis Court Road, Cambridge CB2 1GA, UK. FAX (01223)766002 From gagsl-py2 at yahoo.com.ar Sun Dec 28 02:15:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 28 Dec 2008 05:15:55 -0200 Subject: C API: array of floats/ints from python to C and back References: Message-ID: En Sun, 28 Dec 2008 01:47:08 -0200, Daniel Fetchinson escribi?: >> As others already said, using a Numpy array or an array.array object >> would >> be more efficient (and even easier - the C code gets a pointer to an >> array >> of integers, as usual). > > I looked for this in the C API docs but couldn't find anything on how > to make an array.array python object appear as a pointer to integers > (or floats, etc) in C code. On > > http://docs.python.org/c-api/concrete.html#sequence-objects > > There is only list and tuple or maybe you mean byte array? That has > only been introduced in python 2.6 and I'm working on 2.5. array is a library module, and isn't really part of the API. You're looking for the buffer protocol: PyObject_AsReadBuffer/PyObject_AsWriteBuffer; see http://docs.python.org/c-api/objbuffer.html Given an array.array('l') (containing C long integers): int do_something(PyObject* obj) { long *vec; Py_ssize_t nbytes, nitems, i; if (PyObject_AsReadBuffer(obj, (const void **)&vec, &nbytes) != 0) return NULL; nitems = nbytes/sizeof(long); for (i=0; i <49443531.5050304@v.loewis.de> <49448FC2.6030306@v.loewis.de> Message-ID: On 14 Des, 05:46, "Martin v. L?wis" wrote: > > Yes. If you want a display that is guaranteed to work on your terminal, > use the ascii() builtin function. But shouldn't the production of an object's representation via repr be a "safe" operation? That is, the operation should always produce a result, regardless of environmental factors like the locale or terminal's encoding support. If John were printing the object, it would be a different matter, but he apparently just wants to see a sequence of characters which represents the object. Paul From python-url at phaseit.net Mon Dec 8 11:56:39 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 8 Dec 2008 16:56:39 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Dec 8) Message-ID: QOTW: "To the pure, everything, properly described, is pure ;-)" - Bengt Richter The final version of Python 3.0 was released last Wednesday, jointly with 2.6.1 - congratulations! http://groups.google.com/group/comp.lang.python/t/f92e7e2db667d903/ Implementing "lazy" properties: http://groups.google.com/group/comp.lang.python/t/ce1d75c31a6e2df1/ Overriding __special__ methods at the instance level: http://groups.google.com/group/comp.lang.python/t/3442c5004de0d411/ Strategy to develop libraries both for 2.x and 3.x http://groups.google.com/group/comp.lang.python/t/ee4f9e645e5f41d0/ Guidelines for designing a project's structure on disk: http://groups.google.com/group/comp.lang.python/t/e8dd7109df5f61b2/ A detective story: a hard-to-find bug regarding how 3.0 reads UTF16-encoded files: http://groups.google.com/group/comp.lang.python/t/ae1bc6660a6b2c5f/ When translated into Python, a Perl example about closures shows a few differences between 2.5 and 3.0: http://groups.google.com/group/comp.lang.python/t/5c6734bc5181af6a/ Learning Python for Perl programmers: http://groups.google.com/group/comp.lang.python/t/d2abcb3e75c5f041/ An alternative syntax for defining methods (moving self out of the argument list): http://groups.google.com/group/comp.lang.python/t/5457b8649040f7ea/ "as" is now a keyword (2.6); that breaks some existing code, and angers several people: http://groups.google.com/group/comp.lang.python/t/e9ffe83fcf4b0af0/ 3.0 file read/write is slow and not as optimized as 2.x: http://groups.google.com/group/comp.lang.python/t/6c4d3a2d678c1eba/ http://groups.google.com/group/comp.lang.python/t/9046eee09137c657/ ======================================================================== 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 Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From clp at rebertia.com Thu Dec 25 02:35:13 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 24 Dec 2008 23:35:13 -0800 Subject: How to display Chinese in a list retrieved from database via python In-Reply-To: References: Message-ID: <47c890dc0812242335g187358a8u7f8cb1df5c864fab@mail.gmail.com> On Wed, Dec 24, 2008 at 11:29 PM, zxo102 wrote: > Hi, > I retrieve some info in Chinese from postgresql and assign it to a > variable 'info' defined in javascript of a html page: > var info = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce > \xc4'] > But I want it to be > var info = ['??','??','??'] > since in html pages (via javascript), the items in chinese out of the > former :['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4'] can > not be displayed correctly when it is inserted into a html page. If > the list is var info = ['??','??','??'] , then everything works > fine. > > Anybody knows how to solve this problem? Upgrading to Python 2.6 would probably be beneficial due to its better handling of Unicode. Also, posting some of the actual code you're using (to generate JavaScript, I guess?) would definitely help. Merry Christmas, Chris -- Follow the path of the Iguana... http://rebertia.com From redrackem at yahoo.com Wed Dec 24 20:07:27 2008 From: redrackem at yahoo.com (Red Rackham) Date: Wed, 24 Dec 2008 17:07:27 -0800 (PST) Subject: ctypes & strings Message-ID: <334452.47084.qm@web30003.mail.mud.yahoo.com> Hi friends; ? I would like to pass a string into a dll function.? I notice that to pass using ctypes, it has to be a ctypes type.? Looking at the ctypes doc page I don't see a c_string class.? ? I tried to pass in?byref("name of string") and got back "TypeError: byref() argument must be a ctypes instance, not 'str'" ? If I use astr = create_string_buffer( "name of string" ), and try to pass that in, I get "ValueError: Procedure probably called with too many arguments (4 bytes in excess)". ? If I use astr = (c_char*255)("name of string"), I get "TypeError: one character string expected" (on this line). ? Could some benevolet expert please clue me in on how to accomplish this? ? Thanks!!!! ? Mark ? ? ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From dadapapa at googlemail.com Thu Dec 4 06:24:42 2008 From: dadapapa at googlemail.com (Harold Fellermann) Date: Thu, 4 Dec 2008 03:24:42 -0800 (PST) Subject: Don't you just love writing this sort of thing :) References: Message-ID: <5d680f7c-9127-4b6c-8179-849b5d27fd66@t2g2000yqm.googlegroups.com> On Dec 4, 10:39?am, Cong Ma wrote: > Lawrence D'Oliveiro wrote: > > for \ > > ? ? ? ? Entry \ > > ? ? in \ > > ? ? ? ? sorted \ > > ? ? ? ? ? ( > > ? ? ? ? ? ? f for f in os.listdir(PatchesDir) if PatchDatePat.search(f) != None > > ? ? ? ? ? ) \ > > : > > ? ? Patch = (open, gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir, Entry), "r") > > ? ? ... read from Patch ... > > ? ? Patch.close() > > #end for > > The "if ... != None" is not necessary... ?"if PatchDatePat.search(f)" is OK. > And I don't like it... Maybe the whole if clause is not necessary? This is how I would try it: for Entry in filter(PatchDatePat.search, os.listdir(PatchesDir)) : fname = os.path(PatchesDir, Entry) Patch = file(fname) if fname.endswith('.gz') else GzipFile(fname) # ... read from Patch ... Patch.close() From joe at strout.net Tue Dec 30 16:55:24 2008 From: joe at strout.net (Joe Strout) Date: Tue, 30 Dec 2008 14:55:24 -0700 Subject: embedding python in wxpython In-Reply-To: References: <191280cf-ecf9-4135-9737-9923061855d1@t39g2000prh.googlegroups.com> Message-ID: <495A98CC.5070808@strout.net> Steve Holden wrote: >> I'd like the console to be a bidirectional representation of what's >> going on in the gui, plus a general purpose evaluation environment >> where you can manipulate application data via some api which is >> automatically exposed to the console when the application opens up. >> >> I'm looking for high-level hints/strategies/directions. >> > I seem to remember you can create your wxApp with an argument of True or > False. One of those settings creates a window containing any output to > sys.stderr, if I remember rightly. You do -- True (the default) redirects standard output to a window, while False does not redirect it. However, neither setting will create a bidirectional console or evaluation environment as the OP was asking for. (But other wx widgets do provide that, as other replies have pointed out.) Best, - Joe From joe at strout.net Thu Dec 11 18:21:47 2008 From: joe at strout.net (Joe Strout) Date: Thu, 11 Dec 2008 16:21:47 -0700 Subject: list organization question In-Reply-To: References: Message-ID: <0C41D49F-A972-41AF-91B4-DF4E1486A020@strout.net> On Dec 11, 2008, at 4:12 PM, Robocop wrote: > I have a list of objects, each object having two relevant attributes: > date and id. I'd like not only organize by id, but also by date. > I.e. i would like to parse my list into smaller lists such that each > new mini-list has a unique date, but consists of only objects with a > specific id. I'm not quite following you here. What are the inputs and outputs you're after? For the sake of argument let's say you want: given the list of objects (let's call it mylist), and a desired ID (desired_id), return a smaller list of all the objects with that ID. That would be simply: return [item for item in mylist if item.id=desired_id] Look up "list comprehensions" for an explanation of what's going on here. If you want a list for a given date, then just change the "if" part. You seem to want both at once, but I can't understand what that means. HTH, - Joe From hackingkk at gmail.com Mon Dec 15 07:46:18 2008 From: hackingkk at gmail.com (Krishnakant) Date: Mon, 15 Dec 2008 18:16:18 +0530 Subject: %s place holder does not let me insert ' in an sql query with python. Message-ID: <1229345178.31093.24.camel@krishna-laptop> hello all hackers. This is some kind of an interesting situation although many of you must have already gone through it. I am facing a situation where I have to use psycopg2 and insert rows in a postgresql table. That's pritty easy and no need to say that it works well. But there are some entries which have an ' in the value. I have a venders table in my database and one of the values tryed was "His Master's Voice " now the master's word has the ' which is used for starting and ending a varchar value for postgresql or almost any standard RDBMS. Does any one know what is the way out of this? how do you let the ' go as a part of the string? I have used %s as placeholder as in queryString = "insert into venders values ('%s,%s,%s" % (field1,field2,field3 ) ... This is not working for the ' values. can any one suggest a suitable solution? happy hacking. Krishnakant. From fuzzyman at gmail.com Wed Dec 10 18:33:54 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Wed, 10 Dec 2008 15:33:54 -0800 (PST) Subject: Dabo 0.9.0 Released References: Message-ID: On Dec 10, 7:24?pm, Ed Leafe wrote: > We are proud (and relieved!) to finally release Dabo 0.9.0, the first ? > official release of the framework in six months. We haven't been ? > taking it easy during that period; rather, we made some changes that ? > clean up some weak spots in the codebase, and as a result can offer a ? > much more solid framework, and are on course for a 1.0 release in the ? > near future. > Congratulations Ed and crew. Michael Foord -- http://www.ironpythoninaction.com/ From 7068316797 at message.alltel.com Thu Dec 25 09:21:51 2008 From: 7068316797 at message.alltel.com (7068316797 at message.alltel.com) Date: Thu, 25 Dec 2008 08:21:51 -0600 Subject: anagram finder / dict mapping questi Message-ID: <2310590.1230214932928.JavaMail.root@MD-00> An embedded and charset-unspecified text was scrubbed... Name: file.plain URL: From narkewoody at gmail.com Fri Dec 19 08:20:48 2008 From: narkewoody at gmail.com (Steven Woody) Date: Fri, 19 Dec 2008 21:20:48 +0800 Subject: How to parsing a sequence of integers Message-ID: Hi, I am a newbie and is reading the python book. Could anyone tell me, how to parsing the following string "123 100 12 37 ..." into a list of integers on which I can then apply max()/min()? In additional to max/min, is there something like average()? Thanks in advance. - narke From skip at pobox.com Mon Dec 22 12:53:14 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 22 Dec 2008 11:53:14 -0600 Subject: I always wonder ... Message-ID: <18767.54282.188749.522233@montanaro-dyndns-org.local> ... shouldn't people who spend all their time trolling be doing something else: studying, working, writing patches which solve the problems they perceive to exist in the troll subject? Is there some online troll game running where the players earn points for generating responses to their posts? -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From steve at REMOVE-THIS-cybersource.com.au Wed Dec 17 19:54:09 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Dec 2008 00:54:09 GMT Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> <6a76b501-f6dc-41b5-8828-b55fece68651@l33g2000pri.googlegroups.com> <49497aa4$0$9084$426a74cc@news.free.fr> Message-ID: <01599693$0$20656$c3e8da3@news.astraweb.com> On Wed, 17 Dec 2008 22:19:43 +0100, Bruno Desthuilliers wrote: > Your > problem is that you are confusing variables and attributes. In Python, > 'anything.anyname' (note the dot) is the attribute 'anyname' of object > 'anything'. An easy mistake to make, given that scopes are just namespaces, and attribute access is just accessing names in namespaces too. -- Steven From benjamin.kaplan at case.edu Fri Dec 12 00:35:43 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 12 Dec 2008 00:35:43 -0500 Subject: how to convert '\xf0' to 0xf0 ? In-Reply-To: <8f5b95c0-486d-48ce-b75c-e18a86d73f50@l33g2000pri.googlegroups.com> References: <1cb85265-1c36-4e4b-88f1-46b0ebae3dea@v5g2000prm.googlegroups.com> <8f5b95c0-486d-48ce-b75c-e18a86d73f50@l33g2000pri.googlegroups.com> Message-ID: On Fri, Dec 12, 2008 at 12:28 AM, wrote: > Hi, > > ord('\xf0') works and it only works for char. Do you know any way to > convet > '\xf0\xf0' and '\xf0\xf0\xff\xfe' to integer? > Is that supposed to be a single integer or 4 integers? Either way, you'd use a for loop to iterate over each character. 4 integers : >>> a = '\xf0\xf0\xff\xfe' >>> b = [ord(ch) for ch in a] >>> b [240, 240, 255, 254] 1 really large integer: >>> a = '\xf0\xf0\xff\xfe' >>> i = 0 >>> for ch in a : ... i = i << 8 ... i += ord(ch) ... >>> i 4042326014L > > > Br, Chen Gang > > On Dec 12, 12:40 pm, Steve Holden wrote: > > chengang.beij... at gmail.com wrote: > > > '\xf0' is the value read from a binary file, I need to change this > > > kinds strings to int for further processing... > > > if it is in C, then '\xf0' is an integer and it can be handled > > > directly, but in python, it is a string. > > > > > and both int('10',16) and int('0x10',16) returns 16. > > > > > Br, Chen Gang > > > > > On Dec 12, 12:06 pm, Tommy Nordgren wrote: > > >> On Dec 12, 2008, at 4:48 AM, chengang.beij... at gmail.com wrote: > > > > >>> int('\xf0',16) doesn't work, any way to do that? > > >>> -- > > >>>http://mail.python.org/mailman/listinfo/python-list > > >> Should be int('10',16) > > >> or int('0x10',16) > > > > It seems that you want the integer value of a character you read in from > > a file. Is this correct? Note that '\xf0' is the interpreter's way of > > representing a one-character string whose only character has the > > hexadecimal value f0, because the actual character is not printable: the > > backslash has a special meaning in character string literals. > > > > Any one-character string, however, can be converted to the equivalent > > integer value using the ord() function. You can convert the other way > > using the chr() function: > > > > > > > > >>> ord('A') > > 65 > > >>> chr(65) > > 'A' > > >>> ord('\xf0') > > 240 > > >>> chr(240) > > '\xf0' > > >>> hex(240) > > '0xf0' > > > > So just apply the ord() function to the character and you'll get its > > integer value! > > > > regards > > Steve > > -- > > Steve Holden +1 571 484 6266 +1 800 494 3119 > > Holden Web LLC http://www.holdenweb.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Fri Dec 26 16:50:41 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 26 Dec 2008 13:50:41 -0800 (PST) Subject: Right way to set a variable to NULL? References: <5nfal41gom0iqi2nh5h0m5847ev9brtvpf@4ax.com> Message-ID: <1401c3b2-e80d-4339-b519-4ded340e6e28@r15g2000prd.googlegroups.com> On Dec 27, 7:33?am, Gilles Ganault wrote: > Hello > > I use regexes to extract information from a text file. Some of the > records don't have e-mails or www addresses, so those must match Null > in SQL, but None doesn't work as expected: > > ======= > ? ? ? ? if itemmatch: > ? ? ? ? ? ? ? ? web = itemmatch.group(1).strip() > ? ? ? ? else: > ? ? ? ? ? ? ? ? web = None > > ? ? ? ? sql = 'INSERT INTO mytable ?(name,address,web,mail) VALUES > ("%s","%s","%s","%s","%s")' % (name,address,web,mail) > ======= You have MULTIPLE problems here. PROBLEM 1: That code won't even create the "sql" string; you have %s 5 times, but only 4 elements in the tuple. When asking for help, always post (1) the code that you actually ran (2) the result or error message that you got [merely saying "doesn't work" is not very useful at all]. PROBLEM 2: Having fixed problem 1, the result is not valid SQL; you get VALUES ("Gilles", ...; it should be VALUES('Gilles', ... PROBLEM 3: Having fixed problem 2: If you have a name like "L'Hopital" or "O'Reilly" the result is VALUES('L'Hopital', ...; it should be VALUES ('L''Hopital', ... *AND* you don't have to worry about all the rules for SQL constant values; the worrying and work has been done for you. > Is there a better way in Python to have a variable match NULL than > building the SQL query step by step? Yes. Don't construct the SQL query by Python string formatting. In fact, don't *ever* construct *any* SQL query that needs args by using string formatting/interpolation in *any* language, even when you think it's "working" -- see http://en.wikipedia.org/wiki/SQL_injection ... search for "SQL injection attack" for more references. Essential reference: the Python Database API Specification v2.0 (http://www.python.org/dev/peps/pep-0249/) You need something like: sql = "INSERT INTO mytable (name,address,web,mail) VALUES(?,?,?,?)" cursor.execute(sql, (name, address, web, mail)) Some database software uses something other than ? to mark parameter positions; you may need (for example) ... VALUES(%s,%s,%s,%s) ... (*NOT* the same meaning as %s in Python!). Read about "paramstyle" in the DB API spec, and check the documentation for the DB software that you are using. HTH, John From mikko.viitamaki at gmail.com Mon Dec 1 07:55:32 2008 From: mikko.viitamaki at gmail.com (=?ISO-8859-1?Q?Mikko_Viitam=E4ki?=) Date: Mon, 1 Dec 2008 14:55:32 +0200 Subject: How to distribute a Python app together with its dependencies? In-Reply-To: References: Message-ID: <48da7eab0812010455j2ff92d59ye64785ae071ecb72@mail.gmail.com> On Sun, Nov 30, 2008 at 2:22 PM, Alessio Pace wrote: > Hi, > > I have to distribute a Python application which relies on an external > library, and I'm not very fluent in this kind of stuff with Python (I > come from the Java world where I would have used the Maven build tool > to create an "assembly with dependencies" of all it is needed to run > the app), so I was wondering if someone here could give me some > suggestions :-) > > The external library is generally not present on the machines where I > have to distribute my app, and the set of machines on which I have to > distribute this application is not known a priori (it is just known > they are Unix systems). In fact by means of SSH I will have to copy > (and install) the app+library and make it runnable onto the specified > destination(s). > > My question is: how would you do that? At the moment my current > solution is to make a tarball of the sources of my app + the > "distutils" archive of the external library, copy all into the target > machine, decompress and install via distutils(*) the external library, > setup some PYTHONPATH stuff on the destination machine, and finally be > able to launch the application. > > (*) specifying a prefix into the user home, as I'm not root there > > > So in the end I was wondering if there is a more elegant way of doing > this because, as I said before, I'm not very experienced in these kind > of tasks in Python. > > Thanks in advance for any suggestion or comment. > > Alessio Pace. > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, I was reading Learning Python yesterday and I think this was mentioned: http://peak.telecommunity.com/DevCenter/PythonEggs I don't have experience either so no guarantees cheers /mikko/ From skip at pobox.com Wed Dec 3 14:24:45 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 3 Dec 2008 13:24:45 -0600 Subject: python an sqlite objects In-Reply-To: <4936dab7$0$9107$426a74cc@news.free.fr> References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <4936bceb$0$16783$426a34cc@news.free.fr> <4936dab7$0$9107$426a74cc@news.free.fr> Message-ID: <18742.56573.208546.568369@montanaro-dyndns-org.local> Bruno> Most of the time, you want to serialize the instance's __dict__. Does it recreate an instance at the other end or just a dict? Skip From rt8396 at gmail.com Sun Dec 21 14:26:02 2008 From: rt8396 at gmail.com (r) Date: Sun, 21 Dec 2008 11:26:02 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: I noticed when i mentioned "self" nobody wants to touch that subject. There could be many reasons why... 0.) nobody but the 10 regulars i see here exists 1.) nobody cares(doubt it) 2.) nobody is brave enough to question it(maybe) 3.) most people like to type self over and over again(doubt it) 4.) most people here have given up on changing the BDFL's mind about it. (good possibility) 5.) this is a hot-button topic(no doubt in my mind!) I think Guido's intension's are pure, but this is a major turnoff to new users. Do we really need to hold a new users hand that much. Does it really matter if they know the path of said obj. If you can't fiqure this out for yourself you have much greater problems. I do not like self, and i lamented it from day one, now it is second nature to me but does that mean it is really needed?? I feel i have been brainwashed into its usage. This was the reason for using indention over the bracket plague in python. REDUNDANCY!!! Why not dump self and make the language cleaner. I love python's classes, but HATE self.redundant! This really needs to be fixed, and you have not heard the last from me about it!!! 3000 would have been the perfect time to dump self and really clean up the language, and it's not too late, dawn is not upon us yet. From walterbyrd at iname.com Wed Dec 17 13:20:21 2008 From: walterbyrd at iname.com (walterbyrd) Date: Wed, 17 Dec 2008 10:20:21 -0800 (PST) Subject: Why no lexical scoping for a method within a class? References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> <175fa5d5-f345-47b8-a686-e0e36e1b99e9@q37g2000vbn.googlegroups.com> Message-ID: <39eec12b-d7cc-44b5-aa65-bfa559dcba05@n33g2000pri.googlegroups.com> On Dec 17, 10:00?am, r wrote: > When writing > procedural code how would you like it if vars inside functions were > automatically global. Your code with be blowing chunks in no time. That was my point - I consider python's ordinary use of lexical scoping to be a good thing, and I was wondering why this "good thing" was not used in classes, as well as outside of classes. From dickinsm at gmail.com Sun Dec 28 09:38:32 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 28 Dec 2008 06:38:32 -0800 (PST) Subject: math module for Decimals References: <01671a9e$0$6988$c3e8da3@news.astraweb.com> <016721cc$0$6988$c3e8da3@news.astraweb.com> Message-ID: On Dec 28, 7:28?am, Steven D'Aprano wrote: > Ah crap, I forgot that from_float() has been left out of the decimal API. > That's very annoying. Agreed. It's maybe even annoying enough that a feature request at bugs.python.org might be honoured. (Hint, hint!) It's fairly easy to emulate in Python 2.6 and above, using the as_integer_ratio float method: >>> from decimal import Decimal >>> from math import pi >>> n, d = pi.as_integer_ratio() >>> Decimal(n)/d Decimal('3.141592653589793115997963469') Mark From gagsl-py2 at yahoo.com.ar Tue Dec 23 13:00:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 23 Dec 2008 16:00:08 -0200 Subject: Are python objects thread-safe? References: <5306b56c-eb8c-4148-b426-013caa871375@b41g2000pra.googlegroups.com> Message-ID: En Tue, 23 Dec 2008 11:30:25 -0200, Duncan Booth escribi?: > Aaron Brady wrote: > >> Th.1 Th.2 >> a=X >> a=Y >> a=Z >> >> You are saying that if 'a=Z' interrupts 'a=Y' at the wrong time, the >> destructor for 'X' or 'Y' might not get called. Correct? In serial >> flow, the destructor for X is called, then Y. > > No, the destructors will be called, but the destructors can do pretty > much > anything they want so you can't say the assignment is atomic. This isn't > actually a threading issue: you don't need multiple threads to experience > werid issues here. If you do strange things in a destructor then you can > come up with confusing code even with a single thread. A simple example showing what you said: py> class A: ... def __del__(self): ... global a ... a = None ... py> a = A() py> a = 3 py> print a None -- Gabriel Genellina From prologic at shortcircuit.net.au Tue Dec 16 19:28:07 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 17 Dec 2008 10:28:07 +1000 Subject: Free place to host python files? In-Reply-To: <47c890dc0812161625o76f5c7e6lb8809b99f6962d32@mail.gmail.com> References: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> <47c890dc0812161625o76f5c7e6lb8809b99f6962d32@mail.gmail.com> Message-ID: On Wed, Dec 17, 2008 at 10:25 AM, Chris Rebert wrote: > I'll plug Bitbucket (http://bitbucket.org/). It gives you 150MB of > Mercurial hosting for free, along with a bug tracker and wiki. And I > hear it's implemented using Django. FreeHG (http://freehg.org) is pretty good too :) cheers James From tjreedy at udel.edu Mon Dec 1 14:06:24 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Dec 2008 14:06:24 -0500 Subject: python 2.5.2 or Python 2.6 compilation problem on AIX 5.3 In-Reply-To: <26fbc708-1b64-4271-9c7d-4394aa281f47@j39g2000yqn.googlegroups.com> References: <26fbc708-1b64-4271-9c7d-4394aa281f47@j39g2000yqn.googlegroups.com> Message-ID: desas2 at gmail.com wrote: > Hello: > I am trying to compile Python 2.5.2 on AIX 5.3 with gcc 4.2.3. I am > getting following error. (I also tried Python 2.6 with same error) > > creating build/temp.aix-5.3-2.5/share/tmhsdsd2/tmp/Python-2.5.2/ > Modules > gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - > Wstrict-prototypes -I. -I/share/tmhsdsd2/tmp/Python-2.5.2/./Include - > I. -IInclude -I./Include -I/usr/local/include -I/share/tmhsdsd2/tmp/ > Python-2.5.2/Include -I/share/tmhsdsd2/tmp/Python-2.5.2 -c /share/ > tmhsdsd2/tmp/Python-2.5.2/Modules/_struct.c -o build/temp.aix-5.3-2.5/ > share/tmhsdsd2/tmp/Python-2.5.2/Modules/_struct.o > creating build/lib.aix-5.3-2.5 > > ./Modules/ld_so_aix gcc -pthread -bI:Modules/python.exp build/ > temp.aix-5.3-2.5/share/tmhsdsd2/tmp/Python-2.5.2/Modules/_struct.o -L/ > usr/local/lib -lpython2.5 -o build/lib.aix-5.3-2.5/_struct.so > collect2: library libpython2.5 not found Have you checked all the directories on PATH to see if any contain libpython2.5? > *** WARNING: renaming "_struct" since importing it failed: > 0509-022 Cannot load module build/lib.aix-5.3-2.5. > 0509-026 System error: A file or directory in the path name > does not exist. > error: No such file or directory > make: 1254-004 The error code from the last command is 1. > > > Stop. > > > I am not able to find the problem. I would appreciate, if you could > help. I used following command line options to confugure. > ./configure --prefix=/home/hci/dinakar/python25 -enable-shared --with- > gcc > > Thank you. > Dinakar > -- > http://mail.python.org/mailman/listinfo/python-list > From steve at REMOVE-THIS-cybersource.com.au Tue Dec 30 21:11:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Dec 2008 02:11:12 GMT Subject: TypeError: list indices must be integers References: <2e5a61c0-fa99-4170-81ca-eb3a10859400@k36g2000pri.googlegroups.com> Message-ID: <016acbbf$0$6988$c3e8da3@news.astraweb.com> On Tue, 30 Dec 2008 17:46:11 -0800, dubux wrote: > i keep getting "TypeError: list indices must be integers" on the > following line "date = mylist[y]" > can someone please explain this and give me the proper way to achieve > what im trying to do? The obvious question is, what is the value of y? Insert a line: print type(y), y immediately before date = mylist[y] and see what it says. I'm guessing that it will say that y is a string. -- Steven From __peter__ at web.de Tue Dec 9 14:26:38 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Dec 2008 20:26:38 +0100 Subject: StringIO in 2.6 and beyond References: Message-ID: Bill McClain wrote: > On 2008-12-09, Peter Otten <__peter__ at web.de> wrote: > >> >>> out = io.StringIO() >> >>> print(u"hello", file=out, end=u"\n") >> >>> out.getvalue() >> u'hello\n' > > That has the benefit of working. Thank you! > > That can't be the intended behavior of print(), can it? Insering > non-unicode spaces and line terminators? I thought all text was unicode > now. Or is that only in 3.0? Yes it's 3.0 only. I have no clear idea of the implications of using the print() function in 2.6 yet; maybe changing the defaults for end/sep to unicode would suffice to make it work smoothly. I will probably defer the transition from statement to function until I move to 3.x. One benefit of the function is that you can do things like from functools import partial print = partial(print, sep=u" ", end=u"\n") Peter From rt8396 at gmail.com Sun Dec 21 01:15:23 2008 From: rt8396 at gmail.com (r) Date: Sat, 20 Dec 2008 22:15:23 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> Message-ID: <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> On Dec 20, 11:11?pm, walterbyrd wrote: > On Dec 20, 5:05?pm, Roy Smith > > > He got really hung up on the % syntax. > > I guess it's good to know that there is, at least, one person in the > world doesn't like the % formatting. As least the move was not > entirely pointless. > > But, you must admit, of all the things people complain about with > Python, the % formatting is probably one of the least common > complaints. Complaints about Python's speed seem much more common. > > Yet, 3.0 makes the speed worse, and "fixes" a non-problem. > > I can see where the new formatting might be helpful in some cases. > But, I am not sure it's worth the cost. This all really comes down to the new python users. Yea, i said it. Not rabid fanboys like Steven and myself.(i can't speak for walter but i think he would agree) Are we going to make sure joe-blow python newbie likes the language. And doesn't get turned off and run over to ruby or whoever. Like it or not, without newusers python is doomed to the same fate as all the other "great" languages who had their 15 mins of fame. We must proactively seek out the wants of these new users and make sure python stays alive. But we also must not sell are pythonic souls in the process. It would be nice to get a vote together and see what does the average pythoneer want? What do they like, What do they dislike. What is the state of the Python Union? Does anybody know, Does anybody care? I think python is slipping away from it's dominate foothold on the world. Google's use of python may be the only thing holding this house of cards together. Ruby's "hype" is defiantly growing and unless we strive for greatness, python may fail. I think ruby may have their act together a little better than us right now. And since Ruby is such a hodge-podge of different languages, the __init__ hold is there for many. what does joe-python want??? From iofferkicks006 at gmail.com Sun Dec 21 23:27:54 2008 From: iofferkicks006 at gmail.com (www.iofferkicks.com) Date: Sun, 21 Dec 2008 20:27:54 -0800 (PST) Subject: www.iofferkicks.com china cheap wholesale nike shoes,air jordan shoes,air force one shoes. Message-ID: <382d6350-495e-4887-aec7-4862bdeffaed@r15g2000prh.googlegroups.com> Get Nike Shoes at Super Cheap Prices Discount Nike air jordans (www.iofferkicks.com) Discount Nike Air Max 90 Sneakers (www.iofferkicks.com) Discount Nike Air Max 91 Supplier (www.iofferkicks.com) Discount Nike Air Max 95 Shoes Supplier (www.iofferkicks.com) Discount Nike Air Max 97 Trainers (www.iofferkicks.com) Discount Nike Air Max 2003 Wholesale (www.iofferkicks.com) Discount Nike Air Max 2004 Shoes Wholesale (www.iofferkicks.com) Discount Nike Air Max 2005 Shop (www.iofferkicks.com) Discount Nike Air Max 2006 Shoes Shop (www.iofferkicks.com) Discount Nike Air Max 360 Catalogs (www.iofferkicks.com) Discount Nike Air Max Ltd Shoes Catalogs (www.iofferkicks.com) Discount Nike Air Max Tn Men's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 2 Women's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 3 Customize (www.iofferkicks.com) Discount Nike Air Max Tn 4 Shoes Customize ( www.iofferkicks.com) Discount Nike Air Max Tn 6 Supply (www.iofferkicks.com) Discount Nike Shox NZ Shoes Supply (www.iofferkicks.com) Discount Nike Shox OZ Sale (www.iofferkicks.com) Discount Nike Shox TL Store (www.iofferkicks.com) Discount Nike Shox TL 2 Shoes Store (www.iofferkicks.com) Discount Nike Shox TL 3 Distributor (www.iofferkicks.com) Discount Nike Shox Bmw Shoes Distributor (www.iofferkicks.com) Discount Nike Shox Elite Shoes Manufacturer (www.iofferkicks.com) Discount Nike Shox Monster Manufacturer (www.iofferkicks.com) Discount Nike Shox R4 Running Shoes (www.iofferkicks.com) Discount Nike Shox R5 Mens Shoes (www.iofferkicks.com) Discount Nike Shox Ride Womens Shoes (www.iofferkicks.com) Discount Nike Shox Rival Shoes Wholesaler (www.iofferkicks.com) Discount Nike Shox Energia Wholesaler (www.iofferkicks.com) Discount Nike Shox LV Sneaker (www.iofferkicks.com) Discount Nike Shox Turbo Suppliers (www.iofferkicks.com) Discount Nike Shox Classic Shoes Suppliers (www.iofferkicks.com) Discount Nike Shox Dendara Trainer (www.iofferkicks.com) Discount Nike Air Jordan 1 Seller (www.iofferkicks.com) Discount Nike Air Jordan 2 Shoes Seller (www.iofferkicks.com) Discount Nike Air Jordan 3 Collection (www.iofferkicks.com) Discount Nike Air Jordan 4 Shoes Collection (www.iofferkicks.com) Discount Nike Air Jordan 5 Chaussure Shoes (www.iofferkicks.com) Discount Nike Air Jordan 6 Catalog (www.iofferkicks.com) Discount Nike Air Jordan 7 Shoes Catalog (www.iofferkicks.com) Discount Nike Air Jordan 8 Customized (www.iofferkicks.com) Discount Nike Air Jordan 9 Shoes Customized (www.iofferkicks.com) Discount Nike Air Jordan 10 Wholesalers (www.iofferkicks.com) Discount Nike Jordan 11 Shoes Wholesalers (www.iofferkicks.com) Discount Nike Air Jordan 12 Factory (www.iofferkicks.com) Discount Nike Air Jordan 13 Shoes Factory (www.iofferkicks.com) Discount Nike Air Jordan 14 Shoes Sell (www.iofferkicks.com) Discount Nike Air Jordan 16 Exporter (www.iofferkicks.com) Discount Nike Air Jordan 17 Shoes Exporter (www.iofferkicks.com) Discount Nike Air Jordan 18 Offer (www.iofferkicks.com) Discount Nike Air Jordan 19 Shoes Offer (www.iofferkicks.com) Discount Nike Air Jordan 20 Manufacture (www.iofferkicks.com) Discount Nike Jordan 21 Shoes Manufacture (www.iofferkicks.com) EMAIL:IOFFERKICKS at GMAIL.COM MSN :IOFFERKICKS at MSN.COM From clp at rebertia.com Fri Dec 19 15:58:54 2008 From: clp at rebertia.com (Chris Rebert) Date: Fri, 19 Dec 2008 12:58:54 -0800 Subject: IMAP: How to implement GMail-like threaded conversations view In-Reply-To: <494BFBF4.1000205@gmail.com> References: <494BFBF4.1000205@gmail.com> Message-ID: <47c890dc0812191258t608d2e3ex5f23ba7de9ad0f97@mail.gmail.com> On Fri, Dec 19, 2008 at 11:54 AM, Michael Torrie wrote: > Martin wrote: >> Currently I am trying to get used to Python's imaplib and email >> modules. >> I'like to create a webmail client simmilar to GMail. > > This is off-topic, but why on earth would you want to emulate Gmail's > conversation views? It's horrible and a very broken way of viewing > e-mail threads. Compared the normal, threaded view of, say the > discussions on this list to the view that Gmail gives you. For > conversations of more than half a dozen posts, Gmail's view is > unnavigatable. Suppose I want to break into a discussion that's already > dozens of posts long. With a real threaded view I can easily see the > flow of the conversation, grab random posts, then maybe read their > parent or grandparent posts. Looking at the rest of your e-mail, I can > see that maybe you do want to have real threads rather than the google > conversation view which removes all structure. I disagree. Reading the messages in chronological order is natural and if people quote their parent posts properly, which they nearly always do, there's no need to consult the parent message again (and you'll have already read it by that point in the conversation anyway and recognize it). Why would you "grab random posts" anyway? It makes much more sense to just read the stream until you reach an interesting post (thus gaining the context of the _entire_ discussion) or just read the post in isolation along with its quoting of its parents. Additionally, for most normal people who've never heard of mailinglists, email conversations are typically simple back-and-forth exchanges displayed excellently by Gmail's conversation view; these same people would probably find threading complex and confusing. >> The thoughts above might lead to the second approach: >> >> b.2) Use the "Subject:" field of the messages. > > Horribly broken. Thunderbird does this and it drives me crazy. I often > get messages months apart that happen to have a common subject line, > even though they aren't the same thread or conversation. I don't want a > new message, which does not refer to the old message in any way, to > attach itself to my 6-month old message and force me to scroll down > through potentially hundreds of e-mails to find the stupid thing. No, > the RFCs are there for a reason. They bring sanity to the chaos. > Anything else is madness. And the fact the Outlook doesn't do proper > referral fields just infuriates me. Sigh. Yes, apparently circa Netscape 3.0 they used an ingenious message threading algorithm (described on http://www.jwz.org/doc/threading.html) but the Netscape 4 devs foolishly threw out the code and wrote the broken algorithm used today. Quite a shame. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From prologic at shortcircuit.net.au Tue Dec 30 22:40:33 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 13:40:33 +1000 Subject: greenlets and how they can be used Message-ID: Hey all, The "greenlet" from http://codespeak.net/py/dist/greenlet.html is a rather interesting way of handling flow of control. I can't seem to find anything else on the subject except for the above link and the most recent version 0.2 and it's tests. What can "greenlet"'s be used for ? What use-cases have you guys used them for (if any) ? Can they be used in place of threads with much the same effect - but more lightweight ? cheers James -- -- "Problems are solved by method" From lkcl at lkcl.net Wed Dec 31 15:23:22 2008 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Wed, 31 Dec 2008 20:23:22 +0000 Subject: [ANN] Builds of PyWebkitGtk and Webkit-Glib-Gtk (r39359+#16401.master) for Debian i386, Debian AMD64 and Macports MacOSX 10.4 Message-ID: webkit-glib-gtk provides gobject bindings to webkit's DOM model. pywebkitgtk provides python bindings to the gobject bindings of webkit's DOM model. files are available for download at: https://sourceforge.net/project/showfiles.php?group_id=236659&package_id=290457&release_id=650548 separate pre-built .debs for AMD64 and i386 Debian are included, for pywebkitgtk and webkit-gtk with gobject bindings to the DOM model. if you have seen OLPC/SUGAR's "hulahop", or if you have used Gecko / XUL DOM bindings, or KDE's KHTMLPart DOM bindings, you will appreciate the value of webkit-glib-gtk. pywebkitgtk with glib/gobject bindings basically brings pywebkitgtk on a par with hulahop. if you find the thought of pywebkitgtk with glib bindings, and/or hulahop to be "all too much", then do consider looking at pyjd (the other download from the same location, above). pyjd - aka pyjamas-desktop - is a level "above" pywebkitgtk-glib, and is on a par with pykde, pyqt4, pygtk2, python-wxWidgets and other desktop-based widget sets. (side-note: the advantage of pyjd is that if you write an app which conforms to the pyjamas UI widget set API, you can compile the same python app source code to javascript and run it directly in all major web browsers: see http://pyjs.org, which is a python-to-javascript compiler). code-stability-wise, pywebkitgtk and webkit-glib-gtk should be considered "experimental" (not least because this is a release from a svn build!). that having been said, pyjamas-desktop is declared "production" because pywebkitgtk with DOM bindings, thanks to webkit-glib-gtk, provides absolutely everything that pyjamas-desktop needs (and if webkit-glib-gtk becomes a moving target, the DOM.py abstraction layer in pyjamas-desktop will take care of it. if it becomes a _severe_ moving target, pyjamas-desktop will drop webkit and provide a python-hulahop / XUL-Geck port instead. or as well. whatevrrrr :). gobject-interface-wise, the webkit gobject DOM bindings that have been added _can_ be considered to be "stable", as long as the underlying webkit library IDL files are "stable" (additions to Console.idl were made in the past couple of months, for example, and HTML5 is making advances as well). that having been said, _some_ functionality proved intransigent during the initial main development phase of the webkit gobject DOM bindings, such as RGBColour conversion of CSS Style Properties, and so were *temporarily* left out. given that pyjamas-desktop is considered "production", that should give a pretty clear indication of the importance of those rare bits of DOM model bindings features that were left out. SVG Canvas bindings, however, have NOT been included, as that would have added a further 120 gobjects to the list. instructions for anyone brave enough to install webkit-glib-gtk from source, themselves, on macosx: http://github.com/lkcl/webkit/wikis/installing-webkit-glib-on-macosx there is an (experimental) Portfile in the macosx 10.4 glib tarball, as well. please note that the MacOSX build is NOT a "native" webkit build: it is a GTK / X11 build (known as a "gtk port", in webkit developer terminology). the reason for providing the MacOSX webkit-glib-gtk build, along with a MacOSX port of pywebkitgtk is because the "native" webkit build - which includes ObjectiveC bindings and thus can automatically get python bindings - has very subtly different functionality. whilst the native ObjectiveC bindings are more fully compliant with the W3C standards, providing javascript-like functionality where absolutely necessary, the webkit-glib-gtk build's gobject bindings are going specifically for direct correspondance with the functionality provided by the webkit javascript bindings, falling back to alternatives where it is absolutely not possible to achieve that goal. the actual differences, however, are extremely small, percentage-wise. out of around 300 objects, providing around 1,500 functions, and tens of thousands of properties, there are approximately 20 functions that are different, and only four properties that are different. examples of the differences in the bindings APIs offered by ObjectiveC and webkit-glib-gtk Gobject bindings include: * the provision of the function "toString", which is known as a javascriptism that is not in the W3C standard. _not_ providing this function, which is a de-facto standard, is considered to be inconvenient, especially as both Gecko's language bindings _and_ PyKDE's PyKHTMLPart bindings provide toString() functions. The ObjectiveC bindings, in sticking to the W3C standard, religiously, do not offer "toString". the reason for including toString in the webkit-glib-gtk bindings should be fairly obvious: it is unreasonable to expect developers who will be used to the de-facto existence of toString in javascript to find that it's ... disappeared for no good reason, thus forcing them to make unnecessary coding workarounds, duplicating the exact same functionality that *already* exists in the webkit library! * hspace and vspace of HTMLAppletElement, and width and height of HTMLEmbedElement, are often (mistakenly) set to "NNNpx", "100%" and other values, in javascript, contrary to the W3C standards for HTMLAppletElement and HTMLEmbedElement, respectively. to make life easier for webkit applications (such as Safari, the iPhone browser and other important webkit applications), an exception was made to allow - and cater for or ignore, as appropriate, values in these non-standard formats. Whilst the ObjectiveC bindings stick to the W3C standards, and only allow hspace, vspace, width and height to be set to integer values, the webkit-glib-gtk bindings take advantage of the underlying webkit functions that perform the conversion, and are thus more tolerant - with the proviso of course that it's perfectly possible for users to shoot themselves in the foot by trying to set vspace="10em". such foot-shooting will be silently ignored - just as it is if you tried to do the same thing with javascript. * XMLHTTPRequest.send accepts a DOMString on the webkit-glib-gtk bindings, whereas what should actually be passed in is a Webkit Document object. various attempts were made to create appropriate TextDocument and XMLDocument objects: unfortunately they failed miserably. fortunately, earlier versions of Webkit provided a version of XMLHTTPRequest.send which accepts a DOMString argument, and this version was reactivated for the webkit-glib-gtk bindings. the ObjectiveC and all other bindings successfully pass in a Webkit Document object. this issue will at some point need to be addressed, however it's pretty low priority: using a DOMString works just as well. * Document.getSelection is considered to be a javascript-ism, and is not made available to the ObjectiveC bindings. the function has been added to the webkit-glib-gtk bindings just in case anyone feels like using it. anyone wishing to use the glib/gobject DOM model directly, in c, is well advised to look at the example modified WebKitTools/GtkLauncher/main.c which can be found here: http://lkcl.net/pyjamas-desktop/main.c this modified example is not "gobject-perfect" - there are a couple of areas where an experienced gobject programmer will spot ref-count losses that have yet to be addressed, however the code does some really quite sophisticated messing-about of the DOM model, and provides genuinely useful code snippets. developers may be intrigued to know that some of the code-snippets, such as get_absolute_top(), are direct ports from pyjamas-desktop of the DOM.py getAbsoluteTop() function, which was in turn itself a direct port from the javascript code inside pyjamas DOM.py of the same function name. the technique, and the examples, will help other developers wishing to write applications, by first writing or sourcing an example written in javascript, and then following the same conversion techniques as can be seen by comparing DOM.py getAbsoluteTop() with the example main.c get_absolute_top(). anyone wishing to provide bindings to other languages, such as ruby, perl or java: the pygtk-codegen-2.0 application pretty much made mincemeat of webkit.defs (available on request, or look at code.google.com/p/pywebkitgtk issue #13 - i may update the patch soon enough) and absolutely _no_ funny business - overrides of _any_ kind - were required! the only "funny business" that's in pywebkitgtk overrides is to do with gtk, not the webkit gobject bindings. 300 objects, 1500 functions and tens of thousands of properties all get added with a vanilla .defs file. unbelievable. so this spells "good news" for the garbage-collecting languages (e.g. ruby, perl, possibly java): if your language-of-choice's gobject-auto-generator is as good as python-gobject's auto-generator, you should be up-and-running within literally a couple of hours. oh - but first: i would advise you to look at pywebkitgtk's "demobrowser.py" for guidance on how to create a webkit gtk app (using your language of choice) first, followed by looking at pyjamas-desktop's "pyjd.py" for further hints on how to bind to the DOM model functions [pyjd.py is based on demobrowser.py]. c++ is a different matter. webkitgtkmm will _not_ be gaining DOM bindings based on webkit.defs. after discussions with jonathon jongsma, we came to the conclusion that it would be far better to write a _separate_ set of bindings (gobjectmm) actually in webkit, due to subtle information being available that is lost by the time you get to webkit-gobject c-bindings. anyone anticipating to write or have webkitgtkmm "up-and-running", providing gtk / gobject bindings to webkit's DOM model, should expect to take between three and four weeks in writing a CodeGeneratorGobjectMM.pl, using the other WebKit CodeGenerators as guides. that's all, for now. bugs should be reported to the respective bugtrackers of the appropriate projects - http://code.google.com/p/pyjamas, http://code.google.com/p/pywebkitgtk and http://bugs.webkit.org should do the trick. l. From Slaunger at gmail.com Tue Dec 2 15:45:13 2008 From: Slaunger at gmail.com (Slaunger) Date: Tue, 2 Dec 2008 12:45:13 -0800 (PST) Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> <258cf433-f6c9-43e7-a235-f5f6b2b6433f@j39g2000yqn.googlegroups.com> <33b4cc2f-2311-491c-a2e6-9cc5452b1a6b@g38g2000yqd.googlegroups.com> <652449ff-3a5b-41be-a033-c3c355d277b8@z1g2000yqn.googlegroups.com> Message-ID: <8b1c6e09-a77a-4ef5-aa6e-68127ad755c1@f20g2000yqg.googlegroups.com> On 2 Dec., 17:50, George Sakkis wrote: > > > ? ? ? ? ? ? ? ? I1, Q1, I2, Q2 = bytes_to_data(buf) > > ? ? ? ? ? ? ? ? self.__dict__["I1"] = I1 > > ? ? ? ? ? ? ? ? self.__dict__["Q1"] = Q1 > > ? ? ? ? ? ? ? ? self.__dict__["I2"] = I2 > > ? ? ? ? ? ? ? ? self.__dict__["Q2"] = Q2 > > with: > > ? ? self.__dict__.update(zip(self.data_attr_names, bytes_to_data > (buf))) > > where data_attr_names = ("I1", "Q1", "I2", "Q2") instead of a > frozenset. A linear search in a size-4 tuple is unlikely to be the > bottleneck with much I/O anyway. Thank you for this little hint, George. I've never used update on a dict and the zip function before. This is a nice application of these functions. And I agree, performance is not an issue by selecting a tuple instead of a frozenset. The bytes_to_data function is the performance bottleneck in the actual application (implemented in parent class). -- Slaunger From floris.bruynooghe at gmail.com Wed Dec 17 18:06:41 2008 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Wed, 17 Dec 2008 15:06:41 -0800 (PST) Subject: C API and memory allocation Message-ID: Hi I'm slightly confused about some memory allocations in the C API. Take the first example in the documentation: static PyObject * spam_system(PyObject *self, PyObject *args) { const char *command; int sts; if (!PyArg_ParseTuple(args, "s", &command)) return NULL; sts = system(command); return Py_BuildValue("i", sts); } What I'm confused about is the memory usage of "command". As far as I understand the compiler provides space for the size of the pointer, as sizeof(command) would indicate. So I'm assuming PyArg_ParseTuple() must allocate new memory for the returned string. However there is nothing in the API that provides for freeing that allocated memory again. So does this application leak memory then? Or am I misunderstanding something fundamental? Regards Floris From pdorange at pas-de-pub-merci.mac.com Mon Dec 8 09:00:01 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Mon, 8 Dec 2008 15:00:01 +0100 Subject: Python and audio frequency analysis References: Message-ID: <1irmxjm.16x42iy1m9u5l8N%pdorange@pas-de-pub-merci.mac.com> manatlan wrote: > I'd like to make a kind of "spectrum analyzer" ... > Which should display "bars" according bands of frequencies ... in real > time... > > Is anybody know an audio processing lib in python for that ? For the display module you can use pygame, pyglet or pyOpenGL, there are fast. For the audio analysis i thought the module must be written in C or something very fast, because python, due to it's nature, would probably not compute spectrum as fast as real time : 44100 samples per seconds is a lot of work... -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From kyosohma at gmail.com Tue Dec 30 13:48:13 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 30 Dec 2008 10:48:13 -0800 (PST) Subject: Parsing Excel spreadsheets References: <6a54de23-bea4-40c7-ad7c-22c6eba4bd8a@z6g2000pre.googlegroups.com> Message-ID: <452bfdbc-b6e2-487d-9590-018a414b36a1@s9g2000prg.googlegroups.com> On Dec 30, 10:07?am, "andyh... at gmail.com" wrote: > Hi, > > Can anybody recommend an approach for loading and parsing Excel > spreadsheets in Python. Any well known/recommended libraries for this? > > The only thing I found in a brief search washttp://www.lexicon.net/sjmachin/xlrd.htm, > but I'd rather get some more input before going with something I don't > know. > > Thanks, > Andy. If you need complete control of Excel, then you'll probably have to use COM (see Mark Hammond's PyWin32 package). Otherwise, the suggestions by the others will work. Mike From rhf22 at mole.bio.cam.ac.uk Tue Dec 9 06:50:22 2008 From: rhf22 at mole.bio.cam.ac.uk (Rasmus Fogh) Date: Tue, 9 Dec 2008 11:50:22 +0000 (GMT) Subject: Rich Comparisons Gotcha Message-ID: Steven DAprano wrote: > On Mon, 08 Dec 2008 14:24:59 +0000, Rasmus Fogh wrote: snip >> What might be a sensible behaviour (unlike your proposed wrapper) Sorry 1) I was rude, 2) I thanked TJR for your wrapper class proposal in a later mail. It is yours. > What do you dislike about my wrapper class? Perhaps it is fixable. I think it is a basic requirement for functioning lists that you get >>> alist = [1,x] >>> x in alist True >>> alist.remove(x) >>> alist [1] # unless of course x == 1, in which case the list is [x]. Your wrapper would not provide this behaviour. It is necessary to do if x is y: return True be it in the eq() function, or in the list implementation. Note that this is the current python behaviour for nan in lists, whatever the mathematics say. >> would be the following: >> def eq(x, y): >> if x is y: >> return True > I've already mentioned NaNs. Sentinel values also sometimes need to > compare not equal with themselves. Forcing them to compare equal will > cause breakage. The list.__contains__ method already checks 'x is y' before it checks 'x == y'. I'd say that a list where my example above does not work is broken already, but of course I do not want to break further code. Could you give an example of this use of sentinel values? >> else: >> try: >> return (x == y) >> except Exception: >> return False > Why False? Why not True? If an error occurs inside __eq__, how do you > know that the correct result was False? > class Broken(object): > def __eq__(self, other): > return Treu # oops, raises NameError In managing collections the purpose of eq would be to divide objects into a small set that are all equal to each other, and a larger set that are all unequal to all members of the first set. That requires default to False. If you default to True then eq(aNumpyArray, x) would return True for all x. If an error occurs inside __eq__ it could be 1) because __eq__ is badly written, or 2) because the type of y was not considered by the implementers of x or is in some deep way incompatible with x. 1) I cannot help, and for 2) I am simply saying that value semantics require an __eq__ that returns a truth value. In the absence of that I want identity semantics. Rasmus From prologic at shortcircuit.net.au Thu Dec 18 01:17:47 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 18 Dec 2008 16:17:47 +1000 Subject: importing csv file into sqlite In-Reply-To: <21067453.post@talk.nabble.com> References: <21067453.post@talk.nabble.com> Message-ID: On Thu, Dec 18, 2008 at 3:58 PM, klia wrote: > hey guys, i have a hug .csv file which i need to insert it into sqlite > database using python. > my csv data looks like this > Birthday2,12/5/2008,HTC,this is my birthday > Sea,12/3/2008,kodak,sea > birthday4,14/3/2009,samsung,birthday > love,17/4/2009,SONY,view of island > > can any one give me a head start codes. How big ? When size is important in data processing, you should _never_ try to load it all up at once. Use filters... Here's a head start: $ csv2sql.py mydata.csv | sqlite3 mydatabase.db Here's the source to my csv2sql.py tool (1): ------------------------------------------------------------ #!/usr/bin/env python # Module: csv2sql # Date: 14th September 2008 # Author: James Mills, prologic at shortcircuit dot net dot au """csv2sql Tool to convert CSV data files into SQL statements that can be used to create SQL tables. Each line of text in the file is read, parsed and converted to SQL and output to stdout (which can be piped). """ __desc__ = "CSV to SQL Tool" __version__ = "0.2" __author__ = "James Mills" __email__ = "%s, prologic at shortcircuit dot net dot au" % __author__ __url__ = "http://shortcircuit.net.au/~prologic/" __copyright__ = "CopyRight (C) 2008 by %s" % __author__ __license__ = "GPL" import os import csv import optparse from cStringIO import StringIO USAGE = "%prog [options] " VERSION = "%prog v" + __version__ def parse_options(): """parse_options() -> opts, args Parse any command-line options given returning both the parsed options and arguments. """ parser = optparse.OptionParser(usage=USAGE, version=VERSION) parser.add_option("-t", "--table", action="store", default=None, dest="table", help="Specify table name") parser.add_option("-f", "--fields", action="store", default=None, dest="fields", help="Specify a list of fields") opts, args = parser.parse_args() if len(args) < 1: parser.print_help() raise SystemExit, 1 return opts, args def mkBuffer(fd): buffer = StringIO() buffer.write(fd.read()) buffer.seek(0) fd.close() return buffer def readCSV(file): if type(file) == str: fd = open(file, "rU") else: fd = file fd = mkBuffer(fd) sniffer = csv.Sniffer() dialect = sniffer.sniff(fd.readline()) fd.seek(0) reader = csv.reader(fd, dialect) for line in reader: yield line def main(): opts, args = parse_options() file = args[0] if file == "-": fd = sys.stdin if opts.table is None: print "ERROR: No table specified and stdin used." raise SystemExit(1) else: fd = open(file, "rU") if opts.table is None: table = os.path.splitext(file)[0] else: table = opts.table for line in readCSV(fd): if opts.fields: fields = [x.strip() for x in opts.fields.split(",")] fields = "(%s)" % ",".join(fields) else: fields = "" values = ",".join(["\"%s\"" % x for x in line]) print "INSERT INTO %s %s VALUES (%s);" % (table, fields, values) if __name__ == "__main__": main() ---------------------------------------------------------------- Hope this helps, Here's a small test of using it: jmills at atomant:~$ python Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> fd = open("test.csv", "w") >>> for i in xrange(1000000): ... fd.write("foo,bar,%d\n" % i) ... >>> fd.close() >>> jmills at atomant:~$ du -h test.csv 15M test.csv jmills at atomant:~$ wc -l test.csv 1000000 test.csv jmills at atomant:~$ time csv2sql.py test.csv > test.sql real 0m14.303s user 0m8.877s sys 0m0.676s cheers James References: 1. http://hg.softcircuit.com.au/projects/tools/ From ptmcg at austin.rr.com Thu Dec 4 17:35:42 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 4 Dec 2008 14:35:42 -0800 (PST) Subject: simplest way to strip a comment from the end of a line? References: <52e3f2a9-6fb1-42ef-9871-c904ede5520e@t3g2000yqa.googlegroups.com> <9cdc9039-6b7b-42fb-b261-4ad721ccd1d4@j39g2000yqn.googlegroups.com> Message-ID: Yowza! My eyes glaze over when I see re's like "r'(?m)^(?P.*? (".*?".*?)*)(?:#.*?)?$"! Here's a simple recognizer that reads source code and suppresses comments. A comment will be a '#' character followed by the rest of the line. We need the recognizer to also detect quoted strings, so that any would-be '#' comment introducers that are in a quoted string *wont* incur the stripping wrath of the recognizer. A quoted string must be recognized before recognizing a '#' comment introducer. With our input tests given as: tests ='''this is a test 1 this is a test 2 #with a comment this is a '#gnarlier' test #with a comment this is a "#gnarlier" test #with a comment '''.splitlines() here is such a recognizer implemented using pyparsing. from pyparsing import quotedString, Suppress, restOfLine comment = Suppress('#' + restOfLine) recognizer = quotedString | comment for t in tests: print t print recognizer.transformString(t) print Prints: this is a test 1 this is a test 1 this is a test 2 #with a comment this is a test 2 this is a '#gnarlier' test #with a comment this is a '#gnarlier' test this is a "#gnarlier" test #with a comment this is a "#gnarlier" test For some added fun, add a parse action to quoted strings, to know when we've really done something interesting: def detectGnarliness(tokens): if '#' in tokens[0]: print "Ooooh, how gnarly! ->", tokens[0] quotedString.setParseAction(detectGnarliness) Now our output becomes: this is a test 1 this is a test 1 this is a test 2 #with a comment this is a test 2 this is a '#gnarlier' test #with a comment Ooooh, how gnarly! -> '#gnarlier' this is a '#gnarlier' test this is a "#gnarlier" test #with a comment Ooooh, how gnarly! -> "#gnarlier" this is a "#gnarlier" test -- Paul From ajaksu at gmail.com Mon Dec 1 21:17:09 2008 From: ajaksu at gmail.com (ajaksu) Date: Mon, 1 Dec 2008 18:17:09 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <4f31c483-8382-480e-8417-b7eef1b1792d@z1g2000yqn.googlegroups.com> <8c856b01-7f0c-4d5b-a1d2-cfe7dc74389f@w3g2000yqc.googlegroups.com> <1680020c-521c-4498-8e74-92e99c03da6b@w35g2000yqm.googlegroups.com> <0d9d2404-cb3f-4390-b97c-79251db8ac95@k8g2000yqn.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> Message-ID: r, you could just calm down, stop your trolling and wait to see if more people like greg are able to see a good idea behind your awful delivery. Seriously, you're talking nonsense to people that have actively promoted, taught, developed with and helped develop Python for years. You're mistaking lack of support for your plea (to your format and Ruby-bashing, mostly) for something completely different. I wouldn't get a lot of supporters to the call of "HELP, Opera needs to support Python in webpages", and would need to be crazy(ier) to take any offense in that. So, you sound like a loony when you face that situation with a "I'll fight for FREEDOM, against all you turncoats, and I don't hate Ruby, that Satan spawn!". Just pretend to be normal a little harder (many of us do it [like me {and myself}]) and you'll be all set. I'd like to try hacking some form of Python to work in SketchUp (on top of Ruby, that is). Now, why won't I try to? I'm a Linux user and we don't get a SU version. So much for FREEDOM. BTW, some things in SU have encrypted Ruby code behind them :) Anyway, if I could hack on it, I'd try to get the Ruby API talking to Python. The main thing would be checking what RPy[0] and RubyPython[1] can offer, hoping that Bridge[2] can still work its magic with the new versions of SU. Given that people get WxRuby[3] and DLLs[4] working with SU-Ruby, Python sounds feasible. Good luck to anyone trying to get the software done :) Cheers, Daniel [0] http://rubyforge.org/projects/rpy/ [1] http://rubypython.rubyforge.org/ [2] http://plugins.ro/labs/bridge_tut.htm [3] http://wxsu.sourceforge.net/ [4] http://tinyurl.com/6h28rb From xahlee at gmail.com Tue Dec 9 18:11:20 2008 From: xahlee at gmail.com (Xah Lee) Date: Tue, 9 Dec 2008 15:11:20 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: <9ecfa224-ce8f-44e9-abca-008314f44e87@40g2000prx.googlegroups.com> On Dec 8, 5:25 pm, Terry Reedy wrote: > Lest anyone doubt that problem size is important for comparing program > run times, consider ... just in case there's any doubt: Simply change these lines in Jon's program: Main[9, 512, 4] to Main[9, 512, 4.] and it will run faster. Also, change this line: Block[{scene = Create[level, {0, -1, 4}, 1]}, to Block[{scene = Create[level, {0., -1., 4.}, 1.]}, will make it faster further. (both of which are in my version. The ?Block? can be replaced with ?With?.) As i said, this error in a Mathematica code in the context of speed is a major blunder. His denial makes him a stubborn moron. Reference: ? A Mathematica Optimization Problem http://xahlee.org/UnixResource_dir/writ/Mathematica_optimization.html Xah ? http://xahlee.org/ ? From inq1ltd at inqvista.com Fri Dec 5 15:02:26 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Fri, 05 Dec 2008 15:02:26 -0500 Subject: Problems running on hp duo Pentium R processor In-Reply-To: <200809221446.29472.inq1ltd@inqvista.com> References: <200809221443.25765.inq1ltd@inqvista.com> <200809221446.29472.inq1ltd@inqvista.com> Message-ID: <200812051502.26421.inq1ltd@inqvista.com> Python help, In September I wrote: I have a number of clients running a program built with python 2.5. One has just purchased an HP with a duo core Pentium R processor E2200, 2.2G with .99g ram. Only on the new HP, when they try to print they get an import error; File win32ui.pyc line 12, in File win32ui.pyc, line 10, in _load ImportError: DLL load failed: The specified module could not be found. It turns out that the E2200 processor is 64 bit architecture. What are my options? I've run DependecyWalker, They are using Win XP Service Pack 2 jim=on-linux From michele.simionato at gmail.com Wed Dec 10 11:21:01 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 10 Dec 2008 08:21:01 -0800 (PST) Subject: Maintaining signature in help(decorated function) References: <48f2fd47-1fc3-4b2f-ad39-24adce7e9a5c@k36g2000yqe.googlegroups.com> Message-ID: <941d9581-6165-4513-b172-a1d6295285d3@b38g2000prf.googlegroups.com> On Dec 10, 5:07?pm, jelsas wrote: > Hi -- I can't seem to maintain the function signature when applying a > decorator. ?I'm using functools.wraps. ?Example: > > >>> def mydecorator(fn): > > ... ? ? from functools import wraps > ... ? ? # simple decorator > ... ? ? @wraps(fn) > ... ? ? def wrapped(*args, **kwargs): > ... ? ? ? ? ? ? print 'i\'m wrapped!' > ... ? ? ? ? ? ? return fn(*args, **kwargs) > ... ? ? return wrapped > ... > > >>> @mydecorator > > ... def f(foo, bar): > ... ? ? '''docstring for f''' > ... ? ? pass > ... > > > > >>> help(f) > > displays: > > Help on function f in module __main__: > > f(*args, **kwargs) > ? ? docstring for f > > I would like to maintain f's signature in the help message, (foo, bar) > instead of (*args, **kwargs) > > Thanks in advance! You want the decorator module: http://www.phyast.pitt.edu/~micheles/python/documentation.html From hancock.robert at gmail.com Tue Dec 23 00:32:25 2008 From: hancock.robert at gmail.com (Robert Hancock) Date: Mon, 22 Dec 2008 21:32:25 -0800 (PST) Subject: cgitb and Apache Message-ID: <9314086c-fdf0-412f-a37e-89a871331683@k36g2000yqe.googlegroups.com> I have a cgi running in my alpha environment and, of course, everything works fine. In beta, when I attempt to access a page via our proxy, which works perfectly in alpha. It attempts to call cgitb but freezes for while and then exits. The Apache log show: [Mon Dec 22 23:49:25 2008] [error] [client 172.16.143.75] /usr/local/ python26/lib/python2.6/cgitb.py:173: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6 [Mon Dec 22 23:49:25 2008] [error] [client 172.16.143.75] value = pydoc.html.repr(getattr(evalue, name)) The source for cgitb at 173 is: pydoc.html.escape(str(evalue)))] if isinstance(evalue, BaseException): for name in dir(evalue): if name[:1] == '_': continue ---> value = pydoc.html.repr(getattr(evalue, name)) exception.append('\n
    %s%s =\n%s' % (indent, name, value)) import traceback return head + ''.join(frames) + ''.join(exception) + ''' Any suggestions on how to deal with this? From arnodel at googlemail.com Thu Dec 4 11:57:57 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 04 Dec 2008 16:57:57 +0000 Subject: funny generator behaviour References: Message-ID: Edvin Fuglebakk writes: > I have written a generator that puzzles me: > > The generator is supposed to create ordered selections of a set of > objects. repetition of objects is allowed and the selections should be > of a size determined by a pramter to the generator. > > Now, if I try to accummulate the generated selections into a list I > get some peculiar behaviour that I hope maybe some of you can help me > understand: > > Help much appreciated > -Edvin > > #straightforward acumulation. Does not give the expected result >>>> d=[] >>>> for f in orderedCombinations([1,2],3): > ... d.append(f) > ... >>>> d > [[1], [2], [1], [2], [1], [2], [1], [2]] > > #accumulating shallow copies of the genereated combinations works: >>>> d=[] >>>> for f in orderedCombinations([1,2],3): > ... d.append(f[:]) > ... >>>> d > [[1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 2, 2], [2, 1, 1], [2, 1, 2], [2, > 2, 1], [2, 2, 2]] > > > #The generator: > def orderedCombinations(pool, k): > """ > Generator yielding ordered selections of size k with repetition > from pool. > """ > > if k == 1: > for m in pool: > yield [m] > > if k > 1: > > for m in pool: > for combo in orderedCombinations(pool, k-1): > > #insert and pop to avoid copying entire list > combo.insert(0,m) > yield combo I haven't tried your code but I think the problem is that you yield a list above and then mutate it below, so when you generate the next combination the previous one is mutated. Change the above line to yield list(combo) and it should sort the problem. > combo.pop(0) -- Arnaud From clp at rebertia.com Thu Dec 11 03:05:04 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 11 Dec 2008 00:05:04 -0800 Subject: why doesn't pop/clear call __delitem__ on a dict? In-Reply-To: References: Message-ID: <47c890dc0812110005m3106ff39i9f9211a99c0afc9e@mail.gmail.com> On Wed, Dec 10, 2008 at 11:53 PM, Daniel Fetchinson wrote: > I just found out that if I want to have a custom dict it's not enough > to overload __getitem__, __setitem__ and __delitem__ because, for > example, pop and clear don't call __delitem__. I.e. an instance of the > following will not print 'deleted' upon instance.pop( 'key' ): > > class mydict( dict ): > def __setitem__( self, key, value ): > print 'set' > super( mydict, self ).__setitem__( key, value ) > def __getitem__( self, key ): > print 'get' > super( mydict, self ).__getitem__( key ) > def __delitem__( self, key ): > print 'deleted' > super( mydict, self ).__delitem__( key ) > > Why is this? For optimization purposes essentially, so that the built-in dict can be as fast as possible as it is used pervasively in Python. > what other methods do I have to overload so that > I get what I expect for all dict operations? You might consider just subclassing UserDict.DictMixin instead: http://docs.python.org/library/userdict.html#UserDict.DictMixin It implements the complete dict interface all in terms of provided __getitem__(), __setitem__(), __delitem__(), and keys() methods. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > Cheers, > Daniel > From 5lvqbwl02 at sneakemail.com Wed Dec 24 14:16:59 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Wed, 24 Dec 2008 11:16:59 -0800 (PST) Subject: Doing set operation on non-hashable objects Message-ID: <3a87eb6a-13ff-4aea-8835-3a233cc6cfc4@w39g2000prb.googlegroups.com> Hi, I'm writing an application which is structured roughly as follows: "db" is a dict, where the values are also dicts. A function searches through db and returns a list of values, each of which is a dict as described above. I need to perform set operations on these lists (intersection and union) However the objects themselves are not hashable, and therefore can't be in a set, because they are dicts. I'm not sure how large each set will be, but the point is I'm trying to avoid anything looking like an O(n^2) algorithm, so I can't just use naive double-looping to check for intersection/union on a pair of lists. The only way I can think of to do this right is to hash the dicts by freezing them, turning them all into tuples, which can then be hashed. But this is a problem because more dicts might be nested inside. At any rate, I'd need to thaw them out when I'm done and turn them back into dicts, which seems complicated and annoying, and all this leads me to believe there is a better way. What I really need is a set of pointers, so at the end of the operation I have the actual objects pointed to. Can I somehow use the object IDs as set elements, then recreate a list with the actual objects they point to? How do you get the object back from an ID in python? thanks Michael From garlictrompet at gmail.com Wed Dec 17 06:03:24 2008 From: garlictrompet at gmail.com (Analog Kid) Date: Wed, 17 Dec 2008 16:33:24 +0530 Subject: regex problem .. In-Reply-To: References: <3b10c2060812150421y1c3e7da6ha1b72c736e2a20d4@mail.gmail.com> Message-ID: <3b10c2060812170303w1cd8ecdmad7c97c42e44f08@mail.gmail.com> Hi guys: Thanks for your responses. Points taken. Basically, I am looking for a combination of the following ... [^\w] and %(?!20) ... How do I do this in a single RE? Thanks for all you help. Regards, AK On Mon, Dec 15, 2008 at 10:54 PM, Steve Holden wrote: > Analog Kid wrote: > > Hi All: > > I am new to regular expressions in general, and not just re in python. > > So, apologies if you find my question stupid :) I need some help with > > forming a regex. Here is my scenario ... > > I have strings coming in from a list, each of which I want to check > > against a regular expression and see whether or not it "qualifies". By > > that I mean I have a certain set of characters that are permissible and > > if the string has characters which are not permissible, I need to flag > > that string ... here is a snip ... > > > > flagged = list() > > strs = ['HELLO', 'Hi%20There', '123123@#@'] > > p = re.compile(r"""[^a-zA-Z0-9]""", re.UNICODE) > > for s in strs: > > if len(p.findall(s)) > 0: > > flagged.append(s) > > > > print flagged > > > > my question is ... if I wanted to allow '%20' but not '%', how would my > > current regex (r"""[^a-zA-Z0-9]""") be modified? > > > The essence of the approach is to observe that each element is a > sequence of zero or more "character", where character is "either > letter/digit or escape." So you would use a pattern like > > "([a-zA-Z0-9]|%[0-9a-f][0-9a-f])+" > > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ibpet11 at gmail.com Tue Dec 30 09:55:49 2008 From: ibpet11 at gmail.com (ibpet11 at gmail.com) Date: Tue, 30 Dec 2008 06:55:49 -0800 (PST) Subject: Triple quoted string in exec function ? References: <495A253B.6010003@gmail.com> Message-ID: On Dec 30, 2:48?pm, Steve Holden wrote: > Stef Mientki wrote: > > hello, > > > I'm running scripts, with the execute function (Python 2.5), > > and it seems that triple quoted strings are not allowed. > > > Is there a workaround, > > or is this a fundamental problem of the exec-function ? > > If you think about it, it should be obvious that you can't surround a > string to be compiled with any of the quotes that appear inside the > string to be compiled. That's about the only limitation I am aware of. > > And, by the way, exec is a *statement*, not a function! > > >>> exec """print '''This is > > ... a long string''' > ... """ > This is > a long string > > > > regards > ?Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ hello, the message Steven sent you is ok to explain how to work with triple quote Cheers. From clp at rebertia.com Tue Dec 2 04:26:26 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 2 Dec 2008 01:26:26 -0800 Subject: How to sort a list of file paths In-Reply-To: <2F0A3D19CA15C143B0688EC94220748720D1F89A61@SE-EX007.groupinfra.com> References: <2F0A3D19CA15C143B0688EC94220748720D1F89A61@SE-EX007.groupinfra.com> Message-ID: <47c890dc0812020126p5e8ff750x91ff58e9fabd7d32@mail.gmail.com> On Tue, Dec 2, 2008 at 12:36 AM, Eriksson, John wrote: > Hi, > > > > This weekend I had some problems to get a list containing file paths to be > sorted in a way that I could use. > > > > I also found a thread in this mailing list ( > http://mail.python.org/pipermail/python-list/2007-April/433590.html ) and > realized that others might be interested in a solution. > > > > So... here is my five cents regarding file path sorting: > > > > Problem description: > > > > You have a list containing some file names: > > > >>>> file_list = ["File2.txt","File1.txt","File10.txt"] > > > > If you sort this list in the conventional way you end up with a result like: > > > >>>> file_list.sort() > >>>> print file_list > > ['File1.txt','File10.txt','File2.txt'] > > > > Solution: > > > > Sort the list by splitting alphas and digits in to groups and compare them > separately. > > > > import re > > def true_alphanum_cmp(a,b): > > aa = re.findall(r'\d |\D ', a) > > bb = re.findall(r'\d |\D ', b) > > for i in range(min(len(aa),len(bb))): > > if aa[i].isdigit() and bb[i].isdigit(): > > c = cmp(int(aa[i]),int(bb[i])) > > else: > > c = cmp(aa[i],bb[i]) > > if c!=0: > > return c > > return cmp(len(aa),len(bb)) > > > > file_list = ["File2.txt","File1.txt","File10.txt"] > > file_list.sort(true_alphanum_cmp) > > > > If the formatting in this mail is messed up you can find the example at > http://arainyday.se/notebook/true_alphanum_cmp.php > > > > All comments and improvements are welcome! Sounds like the issue discussed in the post on Coding Horror: http://www.codinghorror.com/blog/archives/001018.html It even links to another Python version of the algorithm. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > > > Best regards > > John Eriksson > > _________________________________________ > > > > Logica - Releasing your potential > > Tegsplan 2b > > 904 20 UME? > > Sweden > > > > T: +46 (0) 90 15 91 38 > > M: +46 (0) 70 366 16 77 > > E: john.eriksson at logica.com > > www.logica.se > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > From prologic at shortcircuit.net.au Thu Dec 18 18:54:15 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Dec 2008 09:54:15 +1000 Subject: Which sparse matrix package? In-Reply-To: References: <20081218231851.70dd91e2@Schlamber.localdomain> Message-ID: On Fri, Dec 19, 2008 at 8:52 AM, Robert Kern wrote: > pyspread *is* the spreadsheet application he is writing. Oh :) My bad :) --JamesMills From steve at holdenweb.com Thu Dec 11 23:40:32 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 11 Dec 2008 23:40:32 -0500 Subject: how to convert =?ISO-8859-1?Q?=27=5Cxf0=27_to_0xf0_=3F?= In-Reply-To: <1cb85265-1c36-4e4b-88f1-46b0ebae3dea@v5g2000prm.googlegroups.com> References: <1cb85265-1c36-4e4b-88f1-46b0ebae3dea@v5g2000prm.googlegroups.com> Message-ID: chengang.beijing at gmail.com wrote: > '\xf0' is the value read from a binary file, I need to change this > kinds strings to int for further processing... > if it is in C, then '\xf0' is an integer and it can be handled > directly, but in python, it is a string. > > and both int('10',16) and int('0x10',16) returns 16. > > Br, Chen Gang > > On Dec 12, 12:06 pm, Tommy Nordgren wrote: >> On Dec 12, 2008, at 4:48 AM, chengang.beij... at gmail.com wrote: >> >>> int('\xf0',16) doesn't work, any way to do that? >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> Should be int('10',16) >> or int('0x10',16) It seems that you want the integer value of a character you read in from a file. Is this correct? Note that '\xf0' is the interpreter's way of representing a one-character string whose only character has the hexadecimal value f0, because the actual character is not printable: the backslash has a special meaning in character string literals. Any one-character string, however, can be converted to the equivalent integer value using the ord() function. You can convert the other way using the chr() function: >>> ord('A') 65 >>> chr(65) 'A' >>> ord('\xf0') 240 >>> chr(240) '\xf0' >>> hex(240) '0xf0' >>> So just apply the ord() function to the character and you'll get its integer value! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From bruno.42.desthuilliers at websiteburo.invalid Thu Dec 18 11:12:13 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 18 Dec 2008 17:12:13 +0100 Subject: Is this pythonic? In-Reply-To: <66d058f9-cfe1-4b3c-ab8a-e6e88bb97770@m22g2000vbp.googlegroups.com> References: <66d058f9-cfe1-4b3c-ab8a-e6e88bb97770@m22g2000vbp.googlegroups.com> Message-ID: <494a761c$0$20035$426a34cc@news.free.fr> ipytest at gmail.com a ?crit : > x.validate_output(x.find_text(x.match_filename > (x.determine_filename_pattern(datetime.datetime.now())))) > > Is it even good programming form? functional programming addicts might say yes. But as far as I'm concerned, I find it a bit too nested... From sjmachin at lexicon.net Tue Dec 2 19:59:06 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 2 Dec 2008 16:59:06 -0800 (PST) Subject: problem with optparse References: Message-ID: <72745ddb-8997-4e97-a8ad-9bcab4aefe6b@c36g2000prc.googlegroups.com> On Dec 3, 11:28?am, Robert Kern wrote: > Neal Becker wrote: > > This example is right out of python library reference. ?What's wrong here? > > > import optparse > > > def store_value(option, opt_str, value, parser): > > ? ? setattr(parser.values, option.dest, value) > > > parser = optparse.OptionParser() > > parser.add_option("--foo", > > ? ? ? ? ? ? ? ? ? action="callback", callback=store_value, > > ? ? ? ? ? ? ? ? ? type="int", nargs=3, dest="foo") > > > (opt,args) = parser.parse_args ('--foo a b c'.split()) > > > [...] > > /usr/lib64/python2.5/optparse.pyc in _process_args(self, largs, rargs, values) > > ? ?1423 ? ? ? ? ? ? elif self.allow_interspersed_args: > > ? ?1424 ? ? ? ? ? ? ? ? largs.append(arg) > > -> 1425 ? ? ? ? ? ? ? ? del rargs[0] > > ? ?1426 ? ? ? ? ? ? else: > > ? ?1427 ? ? ? ? ? ? ? ? return ? ? ? ? ? ? ? ? ?# stop now, leave this arg in rargs > > > TypeError: 'str' object doesn't support item deletion > > Dunno. It works for me (i.e. I get the expected "error: option --foo: invalid > integer value: 'a'"). Have you tried it outside of IPython? > Works for me (Python 2.[456] in interactive mode, Windows XP). Also gives expected result with '--foo 12 34 56'. From sjmachin at lexicon.net Thu Dec 11 18:43:41 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 11 Dec 2008 15:43:41 -0800 (PST) Subject: list organization question References: <79587def-2112-48dd-bab2-95427a2dca8b@y1g2000pra.googlegroups.com> Message-ID: <9c89dd5b-5edb-4d9d-b1f9-333aeb4743b6@r15g2000prd.googlegroups.com> On Dec 12, 10:17?am, Robocop wrote: > I'm currently trying something along the lines of a sort.compare, but > as i'm never sure how many mini-lists i'll end up with, i'm not sure > how exactly to begin. ?Maybe something like a C vector, i.e. a list of > pointers to other lists? ?Or more specifically, compare dates in my > list, push that into some empty dates[], then do something along the > lines of for looping over dates to create subset lists, and nesting > some more compares within these lists to further sort the data by id. > Sound crazy or plausible? Crazy, yes. Plausible that you might attempt it, yes. Learn about dictionaries. They're built in; you don't need to import them. E.g. [OTTOMH; untested] id_map = {} # maps (unique) id to the object with that id date_map = {} # maps date to a list of ids whose objects have that date for o in olist: if o.id in id_map: raise Exception("duplicate id: %r" % o.id) id_map[o.id] = o if o.date not in date_map: date_map[o.date] = [] date_map[o.date].append(o.id) From bdesth.quelquechose at free.quelquepart.fr Mon Dec 8 16:18:56 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 08 Dec 2008 22:18:56 +0100 Subject: Public imports In-Reply-To: <66ecdd96-38dd-4054-8009-e145c0a78316@o40g2000prn.googlegroups.com> References: <9623b0a3-7053-41f1-b116-0cd5e54f39e9@v13g2000vbb.googlegroups.com> <493d1ec0$0$32048$426a34cc@news.free.fr> <66ecdd96-38dd-4054-8009-e145c0a78316@o40g2000prn.googlegroups.com> Message-ID: <493d9cf8$0$27349$426a74cc@news.free.fr> M?rcio Faustino a ?crit : > So, no chance of doing this: > > # "A.py" > from __future__ import division, with_statement > > # "B.py" > from A import * > print 1 / 2 > > ...and printing 0.5, right? Nope, but for totally unrelated reasons (cf Skip's anwer). OTHO, this is valid: # foo.py def bar(): return "bar" # A.py from foo import bar # B.py from A import bar print bar() FWIW, this is often used in packages __init__.py to hide the package's internal organization (or when a module starts to grow too big and has to be refactored as a package without breaking client code). HTH From geekmail at usenot.de Thu Dec 4 14:45:25 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Thu, 4 Dec 2008 20:45:25 +0100 Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> Message-ID: <20081204204525.414db889@usenot.de> On Thu, 4 Dec 2008 11:52:38 -0600 skip at pobox.com wrote: > > >>> As you have probably guessed: nothing changed here. > >>> Also see:http://www.python.org/dev/peps/pep-0666/ > >> > >> What? Do you mean it's possible to mix tabs and spaces still? > >> Why? > > Daniel> Why not? > > Because it has historically been a source of errors in a mixed > development environment (people using text editors with different tab > stops). Better to not allow them to be mixed. > Whenever has it been a pythonic ideal to "not allow" stuff? You get warnings. Everything else is up to you. /W -- My real email address is constructed by swapping the domain with the recipient (local part). From glenn.chappell at gmail.com Mon Dec 22 21:22:47 2008 From: glenn.chappell at gmail.com (Glenn G. Chappell) Date: Mon, 22 Dec 2008 18:22:47 -0800 (PST) Subject: python3 urlopen(...).read() returns bytes References: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> <5496b34d-7ce4-4281-9f01-aed12dab9fd3@f33g2000vbf.googlegroups.com> Message-ID: Okay, so I guess I didn't really *get* the whole unicode/text/binary thing. Maybe I still don't, but I think I'm getting closer. Thanks to everyone who replied. On Dec 22, 1:41?pm, ajaksu wrote: > On Dec 22, 8:25?pm, Christian Heimes wrote: > That said, a "decode to declared HTTP header encoding" version of > urlopen could be useful to give some users the output they want (text > from network io) or to make it clear why bytes is the safe way. Sounds like a great idea. More to the point, it sounds like it's pretty much a necessary idea. Consider: reading a web page is an easy one-liner. Now, no one is going to write that one-liner, and then spend 20 lines trying to get the Content-Type and encoding figured out. Instead we're all going to do it the short, easy, *wrong* way. So every program in the world that uses urlopen gets to have the same bug. Not good. The *right* way needs to be the *easy* way. -GGC- From Russ.Paielli at gmail.com Thu Dec 18 21:23:11 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Thu, 18 Dec 2008 18:23:11 -0800 (PST) Subject: Factoring Polynomials References: <919062f9-765e-4279-aa26-2c130d4deacf@o4g2000pra.googlegroups.com> Message-ID: On Dec 18, 6:17?pm, Collin D wrote: > On Dec 18, 6:12?pm, Collin D wrote: > > > > > On Dec 18, 11:37?am, collin.da... at gmail.com wrote: > > > > I am trying to write a simple application to factor polynomials. I > > > wrote (simple) raw_input lines to collect the a, b, and c values from > > > the user, but I dont know how to implement the quadratic equation > > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > > into python. Any ideas? > > > I completed the code: > > > #import > > from math import sqrt > > > # collect data > > a = float(raw_input('Type a value: ')) > > b = float(raw_input('Type b value: ')) > > c = float(raw_input('Type c value: ')) > > > # create solver > > def solver(a,b,c): > > ? ? if b**2 - 4*a*c < 0: > > ? ? ? ? return 'No real solution.' > > ? ? else: > > ? ? ? ? sol1 = -1 * b + (sqrt(b**2 - 4*a*c)) / 2*a > > ? ? ? ? sol2 = -1 * b - (sqrt(b**2 - 4*a*c)) / 2*a > > ? ? ? ? return (sol1, sol2) > > > # execute > > print solver(a,b,c) > > > Thanks to everyone who helped... > > This really expanded my knowledge on some of the mathematical > > functions in Python. > > UPDATE: > ' > > #import > from math import sqrt > > # collect data > a = float(raw_input('Type a value: ')) > b = float(raw_input('Type b value: ')) > c = float(raw_input('Type c value: ')) > > # create solver > def solver(a,b,c): > ? ? if b**2 - 4*a*c < 0: > ? ? ? ? return 'No real solution.' > ? ? else: > ? ? ? ? sol1 = (-1 * b + (sqrt(b**2 - 4*a*c))) / 2*a > ? ? ? ? sol2 = (-1 * b - (sqrt(b**2 - 4*a*c))) / 2*a > ? ? ? ? return (sol1, sol2) > > # execute > print solver(a,b,c) You need to put your denominator, 2*a, in parens. The way it stands, you are dividing by 2, then multiplying by a. That's not what you want. Also, for better style, I suggest you compute the discriminanat once and store it for reuse rather than repeating the expression three times. From steve at REMOVE-THIS-cybersource.com.au Mon Dec 1 18:00:23 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 01 Dec 2008 23:00:23 GMT Subject: end of print = lower productivity ? References: <757b4e03-7d13-4758-85c4-f5224ee9853b@j35g2000yqh.googlegroups.com> <21d250f9-1477-450e-9587-c4b28d08ea00@t3g2000yqa.googlegroups.com> <981d3e99-d2b4-4455-a52a-e906bd0fe7c4@r36g2000prf.googlegroups.com> <4931D571.8070007@tim.thechases.com> <1228032887.6627.53.camel@lieryan-laptop> Message-ID: <01446462$0$20670$c3e8da3@news.astraweb.com> On Mon, 01 Dec 2008 09:46:43 -0600, Tim Chase wrote: >> For a proof, let's see what Google has to say about this: "Windows text >> editor". Vim is on page 3, near the turning point where nobody is >> talking about text-editor anymore and more about text-editor reviews. >> Even worse is Emacs, on page 6, after many other popular text-editors >> have been mentioned several times. > > That's a pretty malformed "proof" You're right, it is not "proof", but it is damn good evidence that vim has got a small mindshare among the general Windows-only text editor using population. > However, if you want to play that game, vim.org appears on page #1 of > > http://www.google.com/search?q=best+text+editor Is that prefixed by "not even close to"? *grin* > Use what editor works for you -- but if evolution in the language's > features makes difficulties for you but not for users of other editors, > it's your editor that's the problem, not the language. Well, maybe. I think it is quite legitimate to say that APL is the problem, not the lack of good editors (not to mention keyboards!) for all the weird special characters it uses. But in context, I agree with you. -- Steven From chengang.beijing at gmail.com Thu Dec 11 22:48:50 2008 From: chengang.beijing at gmail.com (chengang.beijing at gmail.com) Date: Thu, 11 Dec 2008 19:48:50 -0800 (PST) Subject: =?windows-1252?Q?how_to_convert_=91=5Cxf0=27_to_0xf0_=3F?= Message-ID: int('\xf0',16) doesn't work, any way to do that? From rt8396 at gmail.com Sat Dec 20 18:44:47 2008 From: rt8396 at gmail.com (r) Date: Sat, 20 Dec 2008 15:44:47 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> <59153e28-bf86-4158-96d9-23aa5b9f0205@j35g2000yqh.googlegroups.com> <7889a362-d96e-4f1f-a66b-ef52b9cdb047@q26g2000prq.googlegroups.com> Message-ID: <85f91606-b589-425d-9636-4636c8ccbc4f@r34g2000vbp.googlegroups.com> Thanks, i understand. Maybe some of the pro "new syntax" guys will show a translation From cjw at ncf.ca Fri Dec 19 19:35:20 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Fri, 19 Dec 2008 19:35:20 -0500 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> Message-ID: Steve Holden wrote: > Thomas Heller wrote: >> Mark Summerfield schrieb: >>> Just a follow-up to say that the book has now been published in the >>> U.S. >>> It is now in stock at InformIT, and should reach other stores, e.g., >>> Amazon, in a week or so. >>> >>> Also, the introduction, the first few pages of the first chapter, the >>> whole of chapter 12 (regular expressions), and the index are now >>> available for free download in a PDF from here: >>> http://www.informit.com/store/product.aspx?isbn=0137129297 >> Question from a non-native english speaker: is this now valid english? >> >> "One of Python???s great strengths" >> ^ >> "and also teaches Python???s functional programming features" >> ^ >> "The book???s approach is wholly practical" >> ^ > It always has been valid English. The apostrophe is only omitted from > personal pronouns (hers, its, and so on). > > regards > Steve What is the subject of "teaches"? I have no problem with the second sentence. Colin W. From enleverlesX.XmcX at XmclaveauX.com Sat Dec 13 02:39:43 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sat, 13 Dec 2008 08:39:43 +0100 Subject: ActivePython 2.6.1.1 and 3.0.0.0 released! In-Reply-To: <58cd9ea1-9cf5-4c90-81ba-411774a878b7@o4g2000pra.googlegroups.com> References: <58cd9ea1-9cf5-4c90-81ba-411774a878b7@o4g2000pra.googlegroups.com> Message-ID: <494368d9$0$845$ba4acef3@news.orange.fr> Hi! M. Hammond said (wrote) said that the work is enormous, because modifications of the C architecture of Python 3 was largely modified. (sorry for my bad english) -- Michel Claveau From shangach at gmail.com Wed Dec 3 15:15:11 2008 From: shangach at gmail.com (ShanMayne) Date: Wed, 3 Dec 2008 12:15:11 -0800 (PST) Subject: Numpy record array - field names for all dimensions Message-ID: <74c0e6f0-8caf-4e06-a162-1d107977ff3c@d32g2000yqe.googlegroups.com> Greetings All I am seeking to represent datasets where each data element is the calculated result from several (4 for now) other data types. A matrix- like (in the general mathematical sense) seems logical, where the intersection of each of the 4 values (from different data sets) holds the value derived from those 4 values here serving as indexes. So, each matrix/array element is associated with 4 fields. eg: matrix element/output value = 24.235 --> 'Formula' = 'C12H24O2N2' 'Solvent' = 'Acetonitrile' 'fragmentation_method' = 'CID' 'resolution' = 'unit' ideally I would like to call the output value by indexing the matrix with the input information. eg: matrix['C12H24O2N2']['Acetonitrile']['CID']['unit'] = 24.235 Numpy's record arrays seemingly don't allow all dimensions to carry field names. ie. each column/row carrying a label. Instead fieldname usage appears to create a "new dimension" as denoted by square brackets. eg: pixel_matrix = array([[(1,2,3), (4,5,6)], [(7,8,9), (10,11,12)]], [('r',float32),('g',float32),('b',float32)]) Q: Can anyone tell me if the sort of data structuring I seek can be done with Numpy record arrays or, if not, can you recommend a more suitable module? Great & Glowing Thanks! From marko.loparic at gmail.com Fri Dec 26 17:50:56 2008 From: marko.loparic at gmail.com (Marko Loparic) Date: Fri, 26 Dec 2008 23:50:56 +0100 Subject: looking for a consultant for the design of an interface for our mathematical models Message-ID: Hi, I am looking for someone that could help us to design (perhaps also to implement) a user interface (GUI + repository of data) for our mathematical models. I work for a company in the energy sector. Currently in our department we have 5 different mathematical models using different GUIs and excel hacks to allow users to feed the data and get results. We would like to have a single, powerful, user-friendly interface for all those models. We need the help of an experienced and inventive software designer to help us to choose the technology to use and to make the design (possibly also the implementation) of the tool. Of course we would like to reuse existing tools whenever possible. We propose to pay for one or two days of consultancy when we will describe our needs and discuss the possible design choices. Depending on the conclusions we get we can work further together. We are located near Brussels. Usage of python is not a request but it is a natural choice since it is the main language we use. Any indication on how I can find the good person or company for the job would be of great help! Thank you very much! Marko PS. This message was already posted to scipy list. Someone suggested me to contact Enthought which seems to be a very good idea. But we will probably look for advices from different professionals to make a decision. From Scott.Daniels at Acm.Org Fri Dec 5 12:34:17 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 05 Dec 2008 09:34:17 -0800 Subject: ANN: Shed Skin 0.0.30, an experimental (restricted-)Python-to-C++ Compiler In-Reply-To: <8180ef690812050324j1dc6c570ib9644137bbc193c6__44477.3383591839$1228498143$gmane$org@mail.gmail.com> References: <8180ef690812050324j1dc6c570ib9644137bbc193c6__44477.3383591839$1228498143$gmane$org@mail.gmail.com> Message-ID: <49396619.2090700@Acm.Org> Mark Dufour wrote: > Hi all, > > I have just released version 0.0.30 of Shed Skin, ... Normally, including a link is a good idea. --Scott David Daniels Scott.Daniels at Acm.Org From dfnsonfsduifb at gmx.de Tue Dec 16 23:51:45 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Wed, 17 Dec 2008 05:51:45 +0100 Subject: Does Python3 offer a FrozenDict? In-Reply-To: References: Message-ID: <14dm16x3n6.ln2@joeserver.homelan.net> bearophileHUGS at lycos.com schrieb: > Johannes Bauer: >> is there anything like a frozen dict in Python3, so I could do a >> foo = { FrozenDict({"a" : "b"}): 3 } > > You can adapt this code to Python3 (and post a new recipe? It may be > positive to create a new section of the Cookbook for Py3 only): > http://code.activestate.com/recipes/414283/ Well, yes, I've been using something like that so far - but I think this is functionality the language should provide - therefore I thought maybe Python3 included something like this already. Regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From mh at pixar.com Thu Dec 11 18:57:12 2008 From: mh at pixar.com (mh at pixar.com) Date: Thu, 11 Dec 2008 23:57:12 GMT Subject: var or inout parm? References: <493cda2a$0$17080$426a34cc@news.free.fr> <47c890dc0812080057r6d117bbcic377cb96de52d973@mail.gmail.com> Message-ID: J. Clifford Dyer wrote: > Just google for call-by-object, and ignore the hell out of that thread. Now I've got to go read it! ;-) -- Mark Harrison Pixar Animation Studios From rhodri at wildebst.demon.co.uk Thu Dec 11 18:31:13 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Thu, 11 Dec 2008 23:31:13 -0000 Subject: newbie question: if var1 == var2: In-Reply-To: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> Message-ID: On Thu, 11 Dec 2008 19:49:23 -0000, Steve Holden wrote: > Kirk Strauser wrote: >> At 2008-11-29T04:02:11Z, Mel writes: >> >>> You could try >>> >>> for item in fname: >>> item = item.strip() >> >> This is one case where I really miss Perl's "chomp" function. It >> removes a >> trailing newline and nothing else, so you don't have to worry about >> losing >> leading or trailing spaces if those are important to you. > > ... and it's so hard to write > > item = item[:-1] Tsk. That would be "chop". "chomp" would be if item[-1] == '\n': item = item[:-1] :-) -- Rhodri James *-* Wildebeeste Herder to the Masses From mail at microcorp.co.za Thu Dec 4 23:27:12 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 5 Dec 2008 06:27:12 +0200 Subject: time.sleep() and Tkinter after()? References: <03613d37-ca4f-4962-bce2-eea0a3f65952@r15g2000prd.googlegroups.com> Message-ID: <000701c95691$e71aa6e0$0d00a8c0@hendrik> "Davy" wrote: >Although I don't understand your explanation very well(I guess >maybe .after() re-schedule is better than .sleep unresponsive in GUI >application?)I will take it as a golden rule. I did not in fact try to explain it - I was trying to get you to think a bit wider, as that way you would get more benefit than just being given a solution. As for taking what I say as a golden rule:- If you hang around this group for long enough, you will learn to never take what I say as gospel - I often pull the piss - be warned! 8<----------------------------------- >Yeah, I forgot to *delete* the rectangle object I generate before. >One more question, besides create/delete method, can I just create two >rectangles (one black/one white), and assign two tags to these two >rectangles, and place rectangle by just using tags(that is, can I >place one object on several places of the canvas)? You can redraw it to make it look different and position it on another place, but I have never seen one thing in two places before. If it is possible I don't know how to do it. Now if it were a class, you could have multiple instances, but I have only ever seen one thing, one picture... - Hendrik From nospam at nospam.com Sun Dec 21 14:41:16 2008 From: nospam at nospam.com (Gilles Ganault) Date: Sun, 21 Dec 2008 20:41:16 +0100 Subject: Are Django/Turbogears too specific? Message-ID: Hi I'd like to rewrite a Web 2.0 PHP application in Python with AJAX, and it seems like Django and Turbogears are the frameworks that have the most momentum. I'd like to use this opportunity to lower the load on servers, as the PHP application wasn't built to fit the number of users hammering the servers now. I'm concerned, though, that these frameworks they may be too specific to the tasks they were originally developped for (news articles, AFAIK). Do you think I should just use eg. CherryPy and some basic AJAX? Thank you for any feedback. From mmanns at gmx.net Thu Dec 18 17:18:51 2008 From: mmanns at gmx.net (Martin Manns) Date: Thu, 18 Dec 2008 23:18:51 +0100 Subject: Which sparse matrix package? Message-ID: <20081218231851.70dd91e2@Schlamber.localdomain> Hi: I am writing a spreadsheet application in Python http://pyspread.sf.net which currently uses numpy.array for: + storing object references (each array element corresponds to one grid cell) + slicing (read and write) + mapping from/to smaller numpy.array + searching and replacing + growing and shrinking + transpose operation. While fast and stable, this is really memory inefficient for large grids (i.e. larger than 1E7 rows and columns), so that I am looking into dicts and sparse matrices. The dict that I tried out is of the type: {(1,2,3): "2323", (1,2,545): "2324234", ... } It is too slow for my application when it grows. One slicing operation with list comprehensions takes about 1/2 s on my computer for 1E6 elements. Therefore, I looked into sparse matrices and found scipy.sparse and pysparse. I tried out both lil_matrix objects. (I wrote a wrapper that turns them into Python object arrays.) scipy.sparse.lil_matrix allowed __getitem__ slicing only for one of the dimensions and used much memory when increasing the number of columns above 1E7. pysparse.spmatrix.ll_mat was faster, uses less space and allows slicing for both dimensions. However, its methods are not documented well and I am not able to compile it in Debian testing due to some g77 dependencies. Even though the deb package works well, I am concerned about having a dependency to a problematic package. Now my questions: Is there a better suited / maintained module for such sparse matrices (or multi-dim arrays)? Should I use another type of matrix in scipy.sparse? If yes which? Does a different data-structure suit my above-stated needs better? Best Regards Martin From basu at archlinux.us Tue Dec 30 01:16:25 2008 From: basu at archlinux.us (member Basu) Date: Tue, 30 Dec 2008 01:16:25 -0500 Subject: Get a list of functions in a file In-Reply-To: References: Message-ID: Thanks for all your replies, but the thing is I want to get the list of functions in that file itself, not by importing it as a module. I've decided to go with a class-based approach due to a number of other reasons, but I'm still interested in a way to get function name in that file itself. Thanks, Basu -------------- next part -------------- An HTML attachment was scrubbed... URL: From fakeaddress at nowhere.org Tue Dec 2 19:34:40 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 02 Dec 2008 16:34:40 -0800 Subject: unicode and hashlib In-Reply-To: <6qydnbFh7MOAH6nUnZ2dnUVZ_orinZ2d@pdx.net> References: <8af54b5f-d21b-4794-9bce-afc96ea4db74@j11g2000yqg.googlegroups.com> <6qydnbFh7MOAH6nUnZ2dnUVZ_orinZ2d@pdx.net> Message-ID: Scott David Daniels wrote: > Bryan Olson wrote: >> ... I think that's good behavior, except that the error message is likely >> to end beginners to look up the obscure buffer interface before they >> find they just need mystring.decode('utf8') or bytes(mystring, 'utf8'). > Oops, careful here (I made this mistake once in this thread as well). > You _decode_ from unicode to bytes. The code you quoted doesn't run. Doh! I even tested it with .encode(), then wrote it wrong. Just in case anyone Googles the error message and lands here: If you are working with a Python str (string) object and get, TypeError: object supporting the buffer API required Then you probably want to encode the string to a bytes object, and UTF-8 is likely the encoding of choice, as in: mystring.encode('utf8') or bytes(mystring, 'utf8') Thanks for the correction. -- --Bryan From clp at rebertia.com Tue Dec 23 01:00:57 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 22 Dec 2008 22:00:57 -0800 Subject: using subprocess module in Python CGI In-Reply-To: References: Message-ID: <47c890dc0812222200n26183303x717082b94010d250@mail.gmail.com> On Mon, Dec 22, 2008 at 2:02 AM, ANURAG BAGARIA wrote: > Hello, > > I am a Python Newbie and would like to call a short python script via > browser using a CGI script, but initially I am trying to call the same > python script directly through python command line. The script intends to > perform a few command line in a pipe and I have written the script (a short > one) as follows. > > #!/usr/bin/python > > import cgi, string, os, sys, cgitb, commands, subprocess > import posixpath, macpath > #file = "x.tar.gz" > #comd = "tar -xf %s" % (file) > #os.system(comd) > #commands.getoutput('tar -xf x.tar.gz | cd demo; cp README ../') > comd = [\ > "tar -xf x.tar.gz", \ > "cd demo", \ > "cp README ../", \ > ] > outFile = os.path.join(os.curdir, "output.log") > outptr = file(outFile, "w") > errFile = os.path.join(os.curdir, "error.log") > errptr = file(errFile, "w") > retval = subprocess.call(comd, 0, None, None, outptr, errptr) > errptr.close() > outptr.close() > if not retval == 0: > errptr = file(errFile, "r") > errData = errptr.read() > errptr.close() > raise Exception("Error executing command: " + repr(errData)) > > > but after trying to execute this independently, I get the following error > which I am unable to interpret : > > Traceback (most recent call last): > File "process.py", line 18, in > retval = subprocess.call(comd, 0, None, None, outptr, errptr) > File "/usr/lib/python2.5/subprocess.py", line 443, in call > return Popen(*popenargs, **kwargs).wait() > File "/usr/lib/python2.5/subprocess.py", line 593, in __init__ > errread, errwrite) > File "/usr/lib/python2.5/subprocess.py", line 1135, in _execute_child > raise child_exception There should be at least one more line in this traceback, and that line is the most important one. People will need that line to help you with your problem. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From john.eriksson at logica.com Tue Dec 2 03:36:02 2008 From: john.eriksson at logica.com (Eriksson, John) Date: Tue, 2 Dec 2008 09:36:02 +0100 Subject: How to sort a list of file paths Message-ID: <2F0A3D19CA15C143B0688EC94220748720D1F89A61@SE-EX007.groupinfra.com> Hi, This weekend I had some problems to get a list containing file paths to be sorted in a way that I could use. I also found a thread in this mailing list ( http://mail.python.org/pipermail/python-list/2007-April/433590.html ) and realized that others might be interested in a solution. So... here is my five cents regarding file path sorting: Problem description: You have a list containing some file names: >>> file_list = ["File2.txt","File1.txt","File10.txt"] If you sort this list in the conventional way you end up with a result like: >>> file_list.sort() >>> print file_list ['File1.txt','File10.txt','File2.txt'] Solution: Sort the list by splitting alphas and digits in to groups and compare them separately. import re def true_alphanum_cmp(a,b): aa = re.findall(r'\d |\D ', a) bb = re.findall(r'\d |\D ', b) for i in range(min(len(aa),len(bb))): if aa[i].isdigit() and bb[i].isdigit(): c = cmp(int(aa[i]),int(bb[i])) else: c = cmp(aa[i],bb[i]) if c!=0: return c return cmp(len(aa),len(bb)) file_list = ["File2.txt","File1.txt","File10.txt"] file_list.sort(true_alphanum_cmp) If the formatting in this mail is messed up you can find the example at http://arainyday.se/notebook/true_alphanum_cmp.php All comments and improvements are welcome! Best regards John Eriksson _________________________________________ Logica - Releasing your potential Tegsplan 2b 904 20 UME? Sweden T: +46 (0) 90 15 91 38 M: +46 (0) 70 366 16 77 E: john.eriksson at logica.com www.logica.se -------------- next part -------------- An HTML attachment was scrubbed... URL: From craig_farrow at sil.org Fri Dec 12 03:49:00 2008 From: craig_farrow at sil.org (Craig Farrow) Date: Fri, 12 Dec 2008 16:49:00 +0800 Subject: [Python.NET] Where does the clr in IronPython look the dll In-Reply-To: References: Message-ID: <4942257C.407@sil.org> The dll needs to be on the Python path (sys.path). You can either add to the path with sys.path.append("c:\....") or put your dll in a folder in the Python site-packages directory and add a .pth file (for Python.NET, but not IronPython -- it doesn't recognise the .pth files). Regards, Craig. 3/12/2008 9:20 p.m. d?, navneet khanna wrote: > Hello Everybody > > I am trying to import dll with clr.AddReference("TCdll") > I am getting the following error. > > Traceback (most recent call last): > File "", line 1, in > clr.AddReference("TCdll") > FileNotFoundException: Unable to find assembly 'TCdll'. > at Python.Runtime.CLRModule.AddReference(String name) > > I have loaded the dll in system32 folder. Have I loaded the dll at the > right place or do I need to place it anywhere else? > Waiting for your replies. > > Regards > Navneet > ------------------------------------------------------------------------ > > _________________________________________________ > Python.NET mailing list - PythonDotNet at python.org > http://mail.python.org/mailman/listinfo/pythondotnet From icanbob at gmail.com Sun Dec 14 07:28:01 2008 From: icanbob at gmail.com (bobicanprogram) Date: Sun, 14 Dec 2008 04:28:01 -0800 (PST) Subject: problem adding custom module in cgi script References: Message-ID: On Dec 11, 8:03 pm, bobicanprogram wrote: > Problem: > > Apache server serving an HTML file to a Firefox Browser containing a > form and > a CGI python CGI script. HTML works fine, meat of the CGI script works > fine > except that when a home grown and ordinarily functional module that is > to be > imported is added, the interpreter cannot find it. > > Running cgi.test() reveals that PYTHONPATH is correctly set. Still > nada. > Adding the sys.* stuff still nada. > > Items: Firefox Browser, Apache server, Python 2.5. > > ======================================= > > The CGI script: > #! /usr/bin/python > > import cgi > #cgi.test() > import sys > > #sys.path.append("/myModulePath") > #sys.path.insert(0, "/myModulePath") > import myModule **************** Problem here ******************** > > =========================================== > httpd error_log excerpt: > [Wed Dec 10 13:39:46 2008] [error] [client 192.168.1.1] Traceback > (most recent > call last):, referer:http://192.168.1.1/nee.html > [Wed Dec 10 13:39:46 2008] [error] [client 192.168.1.1] > File "/var/www/cgi-bin/noo.py", line 11, in , referer:http://192.168.1.1/nee.html > [Wed Dec 10 13:39:46 2008] [error] [client 192.168.1.1] import > myModule, > referer:http://192.168.1.1/nee.html > [Wed Dec 10 13:39:46 2008] [error] [client 192.168.1.1] ImportError: > No module > named myModule, referer:http://192.168.1.1/nee.html > > ============================================= > Relevant lines from http.conf: > ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" > SetEnv PYTHONPATH /myModulePath > PassEnv PYTHONPATH > > Thanks in advance for any pointers. > > bob Solution found! The apache web server is running on a Linux box equipped with SELinux which was preventing apache from opening the required modules according to the SELinux troubleshoot browser which is available from the main menu under the administration moniker. Apache's error_log describes the problem as one of not being able to locate the said modules for import. This is misleading to say the least. Adjusting SELinux to allow this is the solution to the problem; this can be done under 'main menu/administration/ SELinux Management bob From sapanapappu at gmail.com Fri Dec 19 06:59:37 2008 From: sapanapappu at gmail.com (sapanapappu at gmail.com) Date: Fri, 19 Dec 2008 03:59:37 -0800 (PST) Subject: 15000$ per month Message-ID: 1500$ per month? MAKE MONEY 24 HOUR, THE REAL ONLINE JOB, http://labnol.homestead.com/ From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 15 03:14:39 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 15 Dec 2008 09:14:39 +0100 Subject: Looking for the best way to translate an idiom In-Reply-To: References: Message-ID: <494611c2$0$21934$426a34cc@news.free.fr> Aahz a ?crit : > In article , > James Stroud wrote: >> In case its not obvious: > > Ah, so that's where Bruno's extra apostrophe came from! ;-) Err... Which one exactly ? > > (Sorry about the spelling flame, but seeing three posts in quick > succession with incorrect spelling of its/it's pushed me into making a > public comment.) From bruno.42.desthuilliers at websiteburo.invalid Wed Dec 10 10:51:42 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 10 Dec 2008 16:51:42 +0100 Subject: "as" keyword woes In-Reply-To: <66ea8282-05cc-4d24-8447-1df5e0e6b9f6@40g2000prx.googlegroups.com> References: <66ea8282-05cc-4d24-8447-1df5e0e6b9f6@40g2000prx.googlegroups.com> Message-ID: <493fe580$0$1726$426a74cc@news.free.fr> Lie a ?crit : > On Dec 7, 2:38 am, "Warren DeLano" wrote: (snip) >> As someone somewhat knowledgable of how parsers work, I do not >> understand why a method/attribute name "object_name.as(...)" must >> necessarily conflict with a standalone keyword " as ". It seems to me >> that it should be possible to unambiguously separate the two without >> ambiguity or undue complication of the parser. >> (snip) > > And let things like: > > filelike.print('lpt') # python 2.6 > zipper.with('7z') > failure.try(alternative) > executecodeobject.if(True) > onfailure.break() > > ? As far as I'm concerned, I'd find this perfectly acceptable - there's no possible confusion here. Now this wouldn't be very practical, since you'd have to define the functions outside the class (with a valid identifier) then bind them to the class. But this is probably not going to happen anyway... From geekmail at usenot.de Tue Dec 2 15:09:30 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Tue, 2 Dec 2008 21:09:30 +0100 Subject: Reverse zip() ? Message-ID: <20081202210930.2ac88ec6@usenot.de> Hi all, we all know about the zip builtin that combines several iterables into a list of tuples. I often find myself doing the reverse, splitting a list of tuples into several lists, each corresponding to a certain element of each tuple (e.g. matplotlib/pyplot needs those, rather than lists of points). This is of course trivial to do via iteration or listcomps, BUT, I was wondering if there is a function I don't know about that does this nicely? redards /W -- My real email address is constructed by swapping the domain with the recipient (local part). From steve at holdenweb.com Tue Dec 30 16:41:44 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Dec 2008 16:41:44 -0500 Subject: embedding python in wxpython In-Reply-To: <191280cf-ecf9-4135-9737-9923061855d1@t39g2000prh.googlegroups.com> References: <191280cf-ecf9-4135-9737-9923061855d1@t39g2000prh.googlegroups.com> Message-ID: 5lvqbwl02 at sneakemail.com wrote: > Hi, I've looked around for a way to allow a python console from within > a wxPython application, but have only found stuff on embedded/ > extending python with C/C++ or wxWidgets in C++, but not wxPython. > > Is this easy to do? Can someone point me in the right direction? > > Also, typically when you embed a scripting language into a larger > application, how do you get the console environment to share data with > the larger application? > > For instance, if the application has some gui stuff (for example > clicking on a object and dragging it around), how do you get > "object.select(x,y)" to print out on the console, and vice-versa: the > object gets selected if the user types "object.select(x,y)"? > > I'd like the console to be a bidirectional representation of what's > going on in the gui, plus a general purpose evaluation environment > where you can manipulate application data via some api which is > automatically exposed to the console when the application opens up. > > I'm looking for high-level hints/strategies/directions. > I seem to remember you can create your wxApp with an argument of True or False. One of those settings creates a window containing any output to sys.stderr, if I remember rightly. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From gnewsg at gmail.com Mon Dec 29 02:29:58 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sun, 28 Dec 2008 23:29:58 -0800 (PST) Subject: How to "kill" orphaned threads at program exit References: Message-ID: <02fab23a-a7e5-46c9-a805-e4d5a792d784@n33g2000pri.googlegroups.com> On 28 Dic, 18:47, Roy Smith wrote: > In article > , > "Giampaolo Rodola'" wrote: > > > Hi, > > I know that it's not possible to "kill" threads but I'm wondering if > > does exist some workaround for my problem. > > I have a test suite which does a massive usage of threads. > > Sometimes happens that one test fails, the test suite keeps running > > until the end, and when it's finished the program hangs on and the > > only way to stop is to kill it manually. > > You don't say how you're creating your threads, so I'll assume you're using > threading.Thread(). After creating each thread, and before calling start() > on it, call setDaemon(True). Apparently it doesn't make any difference. A curious thing is that by putting a "print 1" as last instruction the pending threads get killed and the program exits (Windows XP sp3 32 bit). --- Giampaolo http://code.google.com/p/pyftpdlib/ From steve at holdenweb.com Fri Dec 19 23:04:58 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 19 Dec 2008 23:04:58 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <2d53cd36-52b0-4a1a-913d-0c545cfadc23@v15g2000vbb.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c4ef2$0$20656$c3e8da3@news.astraweb.com> <2d53cd36-52b0-4a1a-913d-0c545cfadc23@v15g2000vbb.googlegroups.com> Message-ID: r wrote: > Thanks Steven, > We need a real Pepsi challenge here to show the insignificance of this > change. I am not against change. But when we lose something as - > compact- as %formating i'm going to want to see a damn good reason for > it! Especially when this breaks code, and the "French Connection" is > not good enough reason for me :) > > Christian said this was not going to be depreciated until 3.2, but > that still puts the accepted way on the chopping block. If Python is so important to you it's a pity you haven't been playing any active role in its development. Do you expect the developers to be psychic? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From gagsl-py2 at yahoo.com.ar Mon Dec 29 04:51:58 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Dec 2008 07:51:58 -0200 Subject: Get a list of functions in a file References: Message-ID: En Mon, 29 Dec 2008 05:26:52 -0200, member Basu escribi?: > I'm putting some utility functions in a file and then building a simple > shell interface to them. Is their some way I can automatically get a > list of > all the functions in the file? I could wrap them in a class and then use > attributes, but I'd rather leave them as simple functions. Such file is called a "module" in Python. Just import it (I'll use glob as an example, it's a module in the standard library, look for glob.py). To get all names defined inside the module, use the dir() function: py> import glob py> dir(glob) ['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'f nmatch', 'glob', 'glob0', 'glob1', 'has_magic', 'iglob', 'magic_check', 'os', 'r e', 'sys'] Note that you get the names of all functions defined inside the module (fnmatch, glob, glob0, has_magic...) but also many other names (like os, re, sys that are just imported modules, and __all__, __doc__, etc that are special attributes) If you are only interested in functions, the best way is to use inspect: py> import inspect py> inspect.getmembers(glob, inspect.isfunction) [('glob', ), ('glob0', ), ('glob1', ), ('has_magic', ), ('iglob', )] Modules are covered in the Python tutorial here and the inspect module is documented here -- Gabriel Genellina From castironpi at gmail.com Sat Dec 20 21:17:54 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 20 Dec 2008 18:17:54 -0800 (PST) Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> <7e23a789-84c3-47b9-b040-ca7dd062d058@a37g2000pre.googlegroups.com> Message-ID: <4791e919-0c55-49a2-bfdf-0f366a382e13@n33g2000pri.googlegroups.com> On Dec 20, 7:06?pm, Aaron Brady wrote: > On Dec 18, 7:21?pm, "Gabriel Genellina" > wrote: > > > > > En Thu, 18 Dec 2008 19:46:45 -0200, Aaron Brady ? > > escribi?: > snip > > > Will it take calling > > > 'CreatePipe' from ctypes directly if on Windows? ?Or can 'os.pipe' be > > > made to abstract that? ?If Windows can't inherit descriptors, > > > 'os.pipe' should return handles, and 'os.read' &co. should accept > > > them. > > > I think the best way would be to modify os.pipe so it returns inheritable ? > > pipes, as it should have been from the beginning. > > > > It is a fairly large patch. > > > Not at all, you have already posted most of it. > > I have marginally tested the patch on a custom build. ?It works, but > there is a catch. ?The descriptor can't be passed directly to the > child on the command line. ?You need to call 'msvcrt.get_osfhandle' on > the descriptor, pass the result, then call 'msvcrt.open_osfhandle' in > the child. Issue is at: http://bugs.python.org/issue4708 From trylks at gmail.com Tue Dec 30 13:42:11 2008 From: trylks at gmail.com (Jose Mora) Date: Tue, 30 Dec 2008 19:42:11 +0100 Subject: duck typing at will Message-ID: <6e1bfdea0812301042x70ab57capf99ce73d364d54db@mail.gmail.com> Duck typing is called that way because "If it looks like a duck and quacks like a duck, it must be a duck." I think it would be good to have also "If the programmer wants to deal with it like a duck, it must be a duck" I mean, some tasks are rather boring in python when compared with php, for example, let's imagine we have a dictionary that contains dictionaries that contain the times that a key appears. We, or at least I, would like to write something as short as: dict[k1][k2] += 1 However we will have to do a longer code (this is the smallest code I could come up with): dict = {} if not k1 in dict: dict[k1] = {} if not k2 in dict[k1]: dict[k1][k2] = 0 dict[k1][k2] += 1 I know it is not the Apocalypse nor something really important when compared with other things, but maybe it would be better if it wasn't necessary to declare the variables when they are built-in types or to initialize the keys in a dictionary, having special values (the identity element of the operation that causes the initialization) to initialize when it has not been done, initializing with the most general type that supports the operation that causes the initialization, casting to other type if necessary after that. This is just an idea, maybe I'm not the first one suggesting it, or maybe it is completely impossible to implement it because it would require deep changes in python, but I wanted to discuss it. Best regards. From ross.jett at gmail.com Mon Dec 29 20:38:36 2008 From: ross.jett at gmail.com (Ross) Date: Mon, 29 Dec 2008 17:38:36 -0800 (PST) Subject: get method References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> Message-ID: <4819de67-72dc-415c-b4c8-2353581c2bc7@r2g2000vbp.googlegroups.com> On Dec 29, 8:07?pm, Scott David Daniels wrote: > Ross wrote: > > ... Use get to write histogram more concisely. You should be able to > > eliminate the if statement. > > > def histogram(s): > > ? ?d = dict() > > ? ?for c in s: > > ? ? ? ? ? ?d[c]= d.get(c,0) > > ? ?return d > > > This code returns a dictionary of all the letters to any string s I > > give it but each corresponding value is incorrectly the default of 0. > > What am I doing wrong? > > How is this code supposed to count? > > --Scott David Daniels > Scott.Dani... at Acm.Org I realize the code isn't counting, but how am I to do this without using an if statement as the problem instructs? From anthony.tolle at gmail.com Fri Dec 19 09:53:46 2008 From: anthony.tolle at gmail.com (anthony.tolle at gmail.com) Date: Fri, 19 Dec 2008 06:53:46 -0800 (PST) Subject: How to read stdout from subprocess as it is being produced References: <263c3946-86aa-4db0-bdaf-42d0c8e5e5d6@q18g2000vbn.googlegroups.com> Message-ID: On Dec 19, 9:34?am, Alex wrote: > Hi, > > I have a Pyhon GUI application that launches subprocess. > I would like to read the subprocess' stdout as it is being produced > (show it in GUI), without hanging the GUI. > > I guess threading will solve the no-hanging issue, but as far as I > searched for now, I've only seen how to read the stdout after > subprocess is finished. > > Thanks! If I'm interpreting your needs correctly, then you may find this module helpful: http://code.activestate.com/recipes/440554/ I've used it successfully in the past when I wanted to use native python code (no C extensions necessary) for asynchronous reading from a child process. I'm not sure if later versions of Python (2.6, 3.0) support this in the standard library. I haven't researched it. From ivan.illarionov at gmail.com Sat Dec 27 23:47:26 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Sat, 27 Dec 2008 20:47:26 -0800 (PST) Subject: C API: array of floats/ints from python to C and back References: Message-ID: On Dec 28, 12:45?am, "Daniel Fetchinson" wrote: > I'm trying to write an extension module in C which contains a single > function with the following prototype: > > void func( int N, int * arg1, int * arg2, int * ret ); > > Here arg1 and arg2 are length N arrays, and the function computes ret > which is also an N length array. From python I'd like to call this > function as > > ret = func( [ 1, 2, 3 ], [ 2, 3, 4] ) > > I've read through the docs athttp://docs.python.org/extending/extending.htmland alsohttp://docs.python.org/c-api/arg.htmlfrom which I learned how to pass > a fixed number of basic datatypes (int, float, string) from python to > C and back. What I don't know is how to pass an array back and forth. > > As far as I can see PyArg_ParseTuple is the function I should use for > converting the python arguments to C but the format string passed to > PyArg_ParseTuple can only be one of the basic data types ("s", "i", > etc) or a generic python object ("O"). > > Does this mean that I can only pass the arrays from python to C as > generic python objects and in a later operation I need to get the > elements from this generic python object, construct a C array and pass > that to the C function? Since I assume this is a frequent operation > I'd think there are some shortcuts, aren't there? Or what's the > simplest way of doing this? > > Cheers, > Daniel > > -- > Psss, psss, put it down! -http://www.cafepress.com/putitdown Hi Daniel, Consider using this: http://docs.python.org/c-api/objbuffer.html This *IS* a shortcut, real shortcut. From gneuner2 at comcast.net Fri Dec 12 12:15:21 2008 From: gneuner2 at comcast.net (George Neuner) Date: Fri, 12 Dec 2008 12:15:21 -0500 Subject: Mathematica 7 compares to other languages References: <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <20081226055859.604@gmail.com> Message-ID: On Wed, 10 Dec 2008 21:37:34 +0000 (UTC), Kaz Kylheku wrote: >Now try writing a device driver for your wireless LAN adapter in Mathematica. Notice how Xah chose not to respond to this. George From malkarouri at gmail.com Tue Dec 9 11:59:40 2008 From: malkarouri at gmail.com (malkarouri) Date: Tue, 9 Dec 2008 08:59:40 -0800 (PST) Subject: When (and why) to use del? References: Message-ID: On 9 Dec, 16:35, Albert Hopkins wrote: > I'm looking at a person's code and I see a lot of stuff like this: > > ? ? ? ? def myfunction(): > ? ? ? ? ? ? # do some stuff stuff > ? ? ? ? ? ? my_string = function_that_returns_string() > ? ? ? ? ? ? # do some stuff with my_string > ? ? ? ? ? ? del my_string > ? ? ? ? ? ? # do some other stuff > ? ? ? ? ? ? return > > and also > > ? ? ? ? def otherfunction(): > ? ? ? ? ? ? try: > ? ? ? ? ? ? ? ? # some stuff > ? ? ? ? ? ? except SomeException, e: > ? ? ? ? ? ? ? ? # more stuff > ? ? ? ? ? ? ? ? del e > ? ? ? ? ? ? return > > I think this looks ugly, but also does it not hurt performance by > preempting the gc? ?My feeling is that this is a misuse of 'del'. Am I > wrong? ?Is there any advantage of doing the above? As far as I understand it, this does not do anything. Let me explain. The del statement doesn't actually free memory. It just removes the binding from the corresponding namespace. So in your first example, my_string cannot be used after the deletion. Of course, if the string referenced by my_string was referenced by some other name then it will still stay in memory. In both your examples, the bindings are going to be removed anyway immediately after the del statement, when returning from the function. So, the del is redundant. If for some reason, however, you are not breaking your work into functions (not advisable) you will have a huge list of commands with no deletion and start to use huge amounts of memory. Solution: divide your work into functions. It is sometimes, however, useful to preempt the gc. This can be done when you know that this is a good time to do chores, e.g. on an application's idle period. Calling gc.collect() is useful here. Regards, Muhammad Alkarouri From bearophileHUGS at lycos.com Sat Dec 20 07:55:42 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 20 Dec 2008 04:55:42 -0800 (PST) Subject: Jarow-Winkler algorithm: Measuring similarity between strings References: <4f351b3b-4da7-4fee-a1ac-c42179d430f5@s9g2000prm.googlegroups.com> <665bf3f7-ef74-4e59-bbac-cfbc12d4e81d@x16g2000prn.googlegroups.com> Message-ID: John Machin: > This paper by Heikki Hyyr? is well worth > reading, and refers to a whole lot of previous work, including > Ukkonen's: > http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.6.2242 This is the site of the author: http://www.cs.uta.fi/~helmu/pubs/pubs.html There you can find updates too: http://www.cs.uta.fi/~helmu/pubs/cpm02.pdf But such researchers have to offer C/Pascal/Java code too of their papers. Implementing things from scratch every time is a waste of time. Probably using SSE instructions like ANDPS, ANDNPS, ORPS, XORPS allows to use bitwise operations on 128 bit, allowing to search for longer strings in the same time. And the GPU of graphic cards offers other possibilities: http://www.cbcb.umd.edu/software/cmatch/Cmatch.pdf Bye, bearophile From deets at nospam.web.de Wed Dec 17 09:18:08 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 17 Dec 2008 15:18:08 +0100 Subject: Python, XML and XPath References: <6qsfvvFeen6dU1@mid.uni-berlin.de> Message-ID: <6qsg10Feen6dU2@mid.uni-berlin.de> Diez B. Roggisch wrote: > Hole wrote: > >> Hi all, >> >> I hope this is not an "overasked" question but I find myself quite >> confused about python xml management (I have to use python for a >> project and I come from java world, you know...where frameworks, >> libraries and tools to use are standard de iure or standard de facto). > > > > I suggest you use one of the available binary builds for windows: > > http://pypi.python.org/pypi/lxml/2.1 Most probably better: http://pypi.python.org/pypi/lxml/2.1.3 Diez From michael at stroeder.com Fri Dec 5 09:13:02 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 05 Dec 2008 15:13:02 +0100 Subject: EBCDIC <--> ASCII In-Reply-To: <6b861698-8638-443d-a230-3eca7424fcfc@j32g2000yqn.googlegroups.com> References: <091f0404-2be3-4bda-8619-03627bd03fdc@k8g2000yqn.googlegroups.com> <6b861698-8638-443d-a230-3eca7424fcfc@j32g2000yqn.googlegroups.com> Message-ID: martinjamesevans at gmail.com wrote: > On Dec 4, 4:45 pm, Michael Str?der wrote: >> martinjamesev... at gmail.com wrote: >>> I'm having a problem trying to use the codecs package to aid me in >>> converting some bytes from EBCDIC into ASCII. >> Which EBCDIC variant? >> >>> sEBCDIC = unicode(sSource, 'cp500', 'ignore') >> Are you sure CP500 is the EBCDIC variant for the language you want? >> >> http://www.ietf.org/rfc/rfc1345.txtlists it as: >> >> &charset IBM500 >> &rem source: IBM NLS RM Vol2 SE09-8002-01, March 1990 >> &alias CP500 >> &alias ebcdic-cp-be >> &alias ebcdic-cp-ch >> >>> Obviously I could just knock up a 255 character lookup table and do it >>> myself, I was just trying to be a little more Pythonic and use that >>> built in table. >> It's pythonic to implement a Unicode codec for unknown character tables. >> I've put these two on my web site: >> >> http://www.stroeder.com/pylib/encodings/ebcdicatde.pyhttp://www.stroeder.com/pylib/encodings/cp273.py(needs ebcdicatde) > > Thanks for the tables, ebcdicatde.py does look more suitable. > > My problem appears to be that my source is a byte string. In a > nutshell I need "\x81\x82\x83\xf1\xf2\xf3" to become "abc123" in a > byte string. Python 2.5.2 (r252:60911, Aug 1 2008, 00:43:38) >>> import ebcdicatde >>> "\x81\x82\x83\xf1\xf2\xf3".decode('ebcdic-at-de').encode('ascii') 'abc123' >>> Ciao, Michael. From anonymous.c.lisper at gmail.com Mon Dec 1 20:46:10 2008 From: anonymous.c.lisper at gmail.com (anonymous.c.lisper at gmail.com) Date: Mon, 1 Dec 2008 17:46:10 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: <603036aa-f047-4ab4-a27c-e7ed7347ccd5@f3g2000yqf.googlegroups.com> On Dec 1, 8:29?pm, Lew wrote: > anonymous.c.lis... at gmail.com wrote: > > A rational human would realize that not too many people peruse this > > newsgroup, > > and that most of them have already seen the wall of text post that you > > generate every time. > > Just out of curiosity, what do you consider "this" newsgroup, given its wide > crossposting? > > -- > Lew Ah, didn't realize the cross-posted nature. comp.lang.lisp Hadn't realized he had branched out to cross-posting across five comp.langs Apologies for the double post, thought the internet had wigged out when i sent it first time. From pavlovevidence at gmail.com Fri Dec 26 00:59:25 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 25 Dec 2008 21:59:25 -0800 (PST) Subject: Exec inside a class method to call other class methods? References: <4953CF57.8080905@sympatico.ca> <20081226001641.GA22946@sdf.lonestar.org> <47c890dc0812251624m7e1c5e55rb538996a52d56675@mail.gmail.com> Message-ID: <6706036c-98e0-46c1-b3c2-5a9a0a92af56@w39g2000prb.googlegroups.com> On Dec 25, 6:35?pm, "David Stanek" wrote: > You won't need the dictionary at all if each type has a parse method. How do you know what type to use if you don't have a if...elif..., dictionary, getattr, or some other sort of dispatching? Look at his requirements: there is a variable called "data_type" that controls how to parse the data. Whether he uses the variable to figure out what method to call, or to figure out what type of object to create to call the parse method of, some sort of dispatching is necessary. This is inevitable when type information is supplied through the input. To be honest I am a little concerned over the more-or-less knee-jerk suggestions to refactor this into a highly object-oriented approach. For the task at hand the OP's approach is fine (aside from the use of exec). Carl Banks From gagsl-py2 at yahoo.com.ar Wed Dec 17 19:42:17 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 17 Dec 2008 22:42:17 -0200 Subject: C API and memory allocation References: Message-ID: En Wed, 17 Dec 2008 21:35:04 -0200, Floris Bruynooghe escribi?: > On Dec 17, 11:06?pm, Floris Bruynooghe > wrote: >> So I'm assuming PyArg_ParseTuple() >> must allocate new memory for the returned string. ?However there is >> nothing in the API that provides for freeing that allocated memory >> again. > > I've dug a little deeper into this and found that PyArg_ParseTuple > (and friends) end up using PyString_AS_STRING() (Python/getargs.c:793) > which according to the documentation returns a pointer to the internal > buffer of the string and not a copy and that because of this you > should not attempt to free this buffer. Yes; but you don't have to dig into the implementation; from http://docs.python.org/c-api/arg.html : s (string or Unicode object) [const char *] Convert a Python string or Unicode object to a C pointer to a character string. You must not provide storage for the string itself; a pointer to an existing string is stored into the character pointer variable whose address you pass. > But how can python now know how long to keep that buffer object in > memory for? It doesn't - *you* have to ensure that the original string object isn't destroyed (by example, incrementing its reference count as long as you keep the pointer), or copy the string contents into your own buffer. -- Gabriel Genellina From zapwireDASHgroups at yahoo.com Wed Dec 31 12:55:43 2008 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Wed, 31 Dec 2008 09:55:43 -0800 Subject: SQL, lite lite lite References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> <4959204f$0$15020$426a74cc@news.free.fr> <6rvgihF3je6sU1@mid.uni-berlin.de> Message-ID: "Gerhard H?ring" wrote in message news:6rvgihF3je6sU1 at mid.uni-berlin.de... > Using an ORM when you don't grasp the relational model and/or the SQL query > language is futile. You'd probably be surprised just how many people there are out there using SQLlite (and other databases) who have no more than a 5 minute introduction to relational databasess. "See, you have tables, and you can stick columns for various attributes, and then add records for rows, and if you make multiple tables you specify which attribute becomes a 'key value' to find the corresponding record in another. Have fun!" > That's probably the case for many other abstraction layers, too. GUIs come to mind... From prologic at shortcircuit.net.au Thu Dec 18 17:33:28 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Dec 2008 08:33:28 +1000 Subject: Which sparse matrix package? In-Reply-To: <20081218231851.70dd91e2@Schlamber.localdomain> References: <20081218231851.70dd91e2@Schlamber.localdomain> Message-ID: On Fri, Dec 19, 2008 at 8:18 AM, Martin Manns wrote: > Hi: Hi, > I am writing a spreadsheet application in Python What's wrong with pyspread ? [ ... snip ... ] > The dict that I tried out is of the type: > > {(1,2,3): "2323", (1,2,545): "2324234", ... } > > It is too slow for my application when it grows. One slicing operation > with list comprehensions takes about 1/2 s on my computer for 1E6 > elements. Let me get this straight. It's taking 0.5s to slice your matrix of 1E7 (10000000.0 rows/columns) Are you mad ? This is TEN Millions and you required it faster than 0.5s ? Am I missing something here ? cheers James From rhodri at wildebst.demon.co.uk Wed Dec 17 19:03:01 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Thu, 18 Dec 2008 00:03:01 -0000 Subject: Why no lexical scoping for a method within a class? In-Reply-To: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> References: <518b9dd9-69c5-4d5b-bd5f-ad567be6249b@b38g2000prf.googlegroups.com> Message-ID: On Wed, 17 Dec 2008 15:19:32 -0000, walterbyrd wrote: > However in the methods are within a class, the scoping seems to work > differently. Not really. Hopefully this commentary will show you why. > class ab(): > def a(self): > self.x = 99 > print self.x > def b(self): > print self.x > > i = ab() This creates |i|, an instance of class |ab|. As yet it is pure and virgin, having nothing but the methods that it gets from |ab|. Soon this will change... > i.a() This creates an attribute |x| in |i|, and assigns the number 99 to it. > i.b() # this works, why no lexical scoping? This works because you ran |i.a()| first, so |i.x| exists and can be printed out. Lexical scoping is going on here, you're just mistaking what's being scoped; it's the |self| in |b|, which is in scope because it's a parameter. This particular |self| (the |i| you made earlier) happens to have an attribute |x|, so it all works. If however you'd written: j = ab() j.b() then Python would whinge mightily at you, claiming that it knoweth naught of this |x| attribute of which you speak, and can it go home now for this is a silly place. The |self| in |b| is still in lexical scope, though. -- Rhodri James *-* Wildebeeste Herder to the Masses From marduk at letterboxes.org Tue Dec 30 14:54:50 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Tue, 30 Dec 2008 14:54:50 -0500 Subject: need help with list/variables In-Reply-To: <63b5acce-d566-48cb-abce-c00fd0e02a39@v39g2000pro.googlegroups.com> References: <63b5acce-d566-48cb-abce-c00fd0e02a39@v39g2000pro.googlegroups.com> Message-ID: <1230666890.3713.2.camel@centar.nbk> On Tue, 2008-12-30 at 11:31 -0800, wx1234 at gmail.com wrote: > I have a list and would like to parse the list appending each list > item to the end of a variable on a new line. > > for instance > > mylist = ['something\n', 'another something\n', 'something again\n'] > > then parse mylist to make it appear in my variable in this format: > > myvar = """ > something > another something > something again""" > > how would i go about setting a variable like this? myvar = ''.join(mylist) Though if you really want an "blank line" in the beginning you'll need to prepend a '\n' -a From rocky at panix.com Thu Dec 11 04:33:18 2008 From: rocky at panix.com (R. Bernstein) Date: Thu, 11 Dec 2008 04:33:18 -0500 Subject: trace module and doctest Message-ID: On Nov 22 2007, 4:31 pm, j... at pobox.com (John J. Lee) wrote: > s... at pobox.com writes: > > I am trying to use thetracemodulewith the --count flag to test for > > statement coverage in my doctests. Thetracecoverage listing is very > > weird, marking many statements as unexecuted which were clearly executed > > during the run (I can see their output on the screen). Is this some known > > interaction between thetraceanddoctestmodules? > > Yes: > > http://python-nose.googlecode.com/svn/trunk/nose/plugins/doctests.py > > http://svn.zope.org/Zope3/trunk/src/zope/testing/doctest.py?rev=28679... > > John Interesting. Is this problem caused or ascerbated by the fact that sys.settrace() is this sort of global? I've been looking at redoing pdb from scratch, from the bottom up. As Obama might say in a different context, "line by line". I sort of don't like the global-ness of pdb, or for that matter the sys.settrace's trace hook. So as a start, I wrote a "tracer" module (http://code.google.com/p/pytracer/ and on Pypi) which just a wrapper around the global trace hook to allow different applications to register trace events and not clobber one-another. Possibly in an Ideal world, Python would itself have done the trace hook chaining. (I believe that the case in Ruby ;-) But Python 2.6 does now allow you *query* to find out if a trace hook has been installed, chaining so it is now possible, even though tracer doesn't use the 2.6 sy.gettrace () to allow it chain outside of routines that use it directly. But as I wonder if this kind of problem would have been avoided if there had been a wrapper to allow settrace chaining? (And if that is s -- unlikely as it is to happen -- various applications like tracer, doctest and pdb could be rewritten to use tracer.) From rdcollum at gmail.com Sun Dec 28 12:19:46 2008 From: rdcollum at gmail.com (Roger) Date: Sun, 28 Dec 2008 09:19:46 -0800 (PST) Subject: "return" in def Message-ID: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> Hi Everyone, First I want to thank everyone that posts to this group. I read it daily and always learn something new even if I never feel like I have anything to contribute but my questions. When I define a method I always include a return statement out of habit even if I don't return anything explicitly: def something(): # do something return Is this pythonic or excessive? Is this an unnecessary affectation that only adds clock ticks to my app and would I be better off removing "returns" where nothing is returned or is it common practice to have returns. Even when I'm not explicitly returning something I like to add "return" because it's a good additional visual marker for me to see where a method definition ends especially in cases where I may use a nested method. Thanks for the discussion! Roger. From prologic at shortcircuit.net.au Mon Dec 29 20:45:08 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 30 Dec 2008 11:45:08 +1000 Subject: Python in C In-Reply-To: <47c890dc0812291732p34ab7710u5b98b30eb926113c@mail.gmail.com> References: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> <47c890dc0812291732p34ab7710u5b98b30eb926113c@mail.gmail.com> Message-ID: On Tue, Dec 30, 2008 at 11:32 AM, Chris Rebert wrote: > On Mon, Dec 29, 2008 at 5:22 PM, wrote: > >> 2. Have there been any suggestions in the past to rewrite Python's >> mainstream implementation in C++ (or why wasn't it done this way from >> the beginning)? > > I'm not a CPython dev (I bet one will pipe in), but I would speculate > it's because C++ is so much more complicated and a bit less portable > than C. I'm not a CPython dev either, but I concur with this statement. cheers James From tn.pablo at gmail.com Thu Dec 18 12:07:03 2008 From: tn.pablo at gmail.com (ptn) Date: Thu, 18 Dec 2008 09:07:03 -0800 (PST) Subject: Location HTTP Header References: <68fa1e9b-6652-4d34-a7fe-fc98db8bf6d4@m16g2000vbp.googlegroups.com> Message-ID: <5f4d3006-0750-4faa-ae1b-3a0408abbe2a@g1g2000pra.googlegroups.com> On Dec 17, 6:47?pm, "Gabriel Genellina" wrote: > En Wed, 17 Dec 2008 20:52:42 -0200, ptn escribi?: > > > I tried this stupid script on my server: > > > ? ?#! /usr/bin/env python > > > ? ?print 'Location:http://www.google.com\n' > > > and it didn't work, I get a blank page. ?I first tried the Location > > header in another script, and when execution got to that point, it > > would > > just sort of ignore it, because the script would keep running to the > > end > > of the code (or stop at some unhandled exception). > > I assume this is a cgi script. For the Location field to be relevant, the ? > Status should be a 3xx (like 307 Temporary Redirect, or 302 Found) > In your case, your server probably has already sent a 200 OK response, so ? > Location is ignored. > Try adding a Status line -before Location above- like: > print 'Status: 302 Found" > > > Any ideas? > > I'd use a different protocol other than CGI... > > -- > Gabriel Genellina Mmmmm no, that didn't do it. The script now is: #! /usr/bin/env python print 'Status: 302 Found' print 'Location: http://www.google.com\n' but still nothing happens, I get the same blank page. Since the sscript is so simple, maybe it is a matter of server configuration? Is that possible? From chrispoliquin at gmail.com Fri Dec 5 13:50:47 2008 From: chrispoliquin at gmail.com (chrispoliquin at gmail.com) Date: Fri, 5 Dec 2008 10:50:47 -0800 (PST) Subject: Overwrite single line of file Message-ID: Hi, I have about 900 text files (about 2 GB of data) and I need to make some very specific changes to the last line of each file. I'm wondering if there is a way to just overwrite the last line of a file or replace the spots I want (I even know the position of the characters I need to replace). I know how to open files and read the contents and then write everything out again after making the changes, but is there a way to replace just the last line without having to completely rewrite each file after making the changes? -Chris From tino at wildenhain.de Wed Dec 3 08:57:06 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Wed, 03 Dec 2008 14:57:06 +0100 Subject: Converting a .xls file to .html In-Reply-To: References: Message-ID: <49369032.8080908@wildenhain.de> Hi, tarun wrote: > Hello All, > > I've a .xml file (saved as .xls) that can be opened in Microsoft excel. Well if its an xml file then just attach a style to it and you can just view it in a browser w/o involving excel in the first place. Also there are lots of xml libraries coming with python so you can translate it directly into HTML of your choice. > I want to write python code that converts this excel file into .html (so > that it can be viewed as is in an explorer). Whats an Explorer? I guess you mean Webbrowser here? Now if you manage to have it in Excel, then you could just save it as HTML (or whatever Microsoft believes is HTML). If the file is stored elsewhere in Excel-Format, then you could script that using xlrd (google for it) Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From bblais at bryant.edu Fri Dec 5 16:37:37 2008 From: bblais at bryant.edu (Brian Blais) Date: Fri, 5 Dec 2008 16:37:37 -0500 Subject: Can I load a python program at the interactive >>> prompt? In-Reply-To: <269e5d69-02b7-409b-ad53-b7702b6ec13a@i24g2000prf.googlegroups.com> References: <269e5d69-02b7-409b-ad53-b7702b6ec13a@i24g2000prf.googlegroups.com> Message-ID: <6143BC03-1E8E-4622-9FA8-EC78E78F0F9E@bryant.edu> On Dec 5, 2008, at 15:52 , walterbyrd wrote: > Can I load a file into the python interactive environment? For > example I have a file called test.py that consists of the following: > > print "hello" > print "hello again" > > Can I load that file into python at the >>> prompt? > >>>> load "test.py" > > or something like that? > I think you mean: execfile('test.py') that should work. if you have iPython, which is a great shell for running python code, you can do: run test.py as far as copy/paste, I think in Windows Python runs in a DOS prompt, so you should be able to right-click and choose Edit/Paste. Not too convenient, but I think it works. bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at mrabarnett.plus.com Sat Dec 20 21:36:52 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 21 Dec 2008 02:36:52 +0000 Subject: a small doubt In-Reply-To: <19ac19520812201750hb592e4dsa5ef7d2a1906c2ed@mail.gmail.com> References: <19ac19520812201750hb592e4dsa5ef7d2a1906c2ed@mail.gmail.com> Message-ID: <494DABC4.30603@mrabarnett.plus.com> Piyush Anonymous wrote: > i wrote this code > -- > class Person(object): > instancesCount = 0 > def __init__(self, title=""): > Person.instancesCount += 1 > self.id = "tempst" > def testprint(self): > print "blah blah" > def __getattribute__(self, name): > print "in get attribute" > > a = Person() > a.testprint() > print a.id > ----- > but i am getting this error > ---- > in get attribute > Traceback (most recent call last): > File "trapmethodcall1.py", line 15, in > a.testprint() > TypeError: 'NoneType' object is not callable > ------ > why is it so? __getattribute__ is called whenever an attribute or method > is called, rt? or if i set __getattribute__ , i cannot have methods in > class? > > actually my aim is to trap all method calls and keep a counter which is > update whenever method called or returned. how should i go about it? > a.testprint causes __getattribute__ to be called. That method returns None. a.testprint() is therefore None(), hence the exception. From saluk64007 at gmail.com Mon Dec 8 16:07:56 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Mon, 8 Dec 2008 13:07:56 -0800 Subject: Guido's new method definition idea In-Reply-To: References: <014a071a$0$20670$c3e8da3@news.astraweb.com> <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> Message-ID: On Mon, Dec 8, 2008 at 12:55 PM, Arnaud Delobelle wrote: > anthony.tolle at gmail.com writes: > >> class C: >> def createfunc(self): >> def self.func(arg): >> return arg + 1 >> >> Or, after the class definition is done, to extend it dynamically: >> >> def C.method(self, arg): >> self.value = arg >> >> ...which would be the equivalent of the following: >> >> def method(self, arg): >> self.value = arg >> C.method = method > > What about the following then? > > functions = {} > > def functions['square'](x): > return x*x > > def functions['cube'](x): > return x**3 > > -- > Arnaud > -- > http://mail.python.org/mailman/listinfo/python-list > Why not? "def ob.func" is fundamentally "def ob.__dict__["func"]" anyway. I like this idea much better than the original proposal, even though it is pretty much unrelated. From bdesth.quelquechose at free.quelquepart.fr Sun Dec 21 09:20:25 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 21 Dec 2008 15:20:25 +0100 Subject: trapping all method calls in a class... In-Reply-To: References: <19ac19520812202312q71409182kb58a0f7aaf3b0e74@mail.gmail.com> Message-ID: <494e5e5c$0$16190$426a34cc@news.free.fr> Chris Rebert a ?crit : (snip) > Sidenotes about your code: > - `args` and `kwds` are the conventional names for the * and ** > special arguments for '**', the most "conventional" names (at least the one I usually see) are 'kwargs', then 'kw' From benjamin.kaplan at case.edu Sun Dec 14 15:27:57 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 14 Dec 2008 15:27:57 -0500 Subject: package structure? In-Reply-To: References: Message-ID: On Sun, Dec 14, 2008 at 3:16 PM, Torsten Mohr wrote: > Hi, > > in a package i'd like to have a structure like this: > > Files end with ".py", others are directories: > > mod > __init__.py # sets __all__ = ['smod1'] > smod1.py # contains AClass() > smod1 > __init__.py # sets __all__ = ['abc', 'def'] > abc.py > def.py > > So i can now do: > > import mod.smod1.abc > import mod.smod1 > > > But functions/classes in smod1.py are not found: > > a = mod.smod1.AClass() > > I know this is somehow ambiguous, but i wonder how else i can make > "mod" have subpackages and modules. > > I wonder how i can make AClass() known in that package. > You have two modules named smod1- one of them uses the code in smod1.py, the other one is in smod1/__init__.py. The second one hides the first. Python doesn't let you have two modules with the same name. You have to either rename one of the smod1's or define AClass in smod1/__init__.py instead. > > > Thanks for any hints, > Torsten. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From manu3d at gmail.com Thu Dec 18 08:51:33 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 18 Dec 2008 05:51:33 -0800 (PST) Subject: re.match() performance Message-ID: <755bd716-f5f6-4953-87a7-04ee148c3298@i18g2000prf.googlegroups.com> Sorry for the previous post, hit the Enter button by mistake... here's the complete one: Hi everybody! I've written the code below to test the differences in performance between compiled and non-compiled regular expression matching but I don't quite understand the results. It appears that the compiled the pattern only takes 2% less time to process the match. Is there some caching going on in the uncompiled section that prevents me from noticing its otherwise lower speed? Manu ------------ import re import time ## Setup pattern = "(.*)" compiledPattern = re.compile(pattern) longMessage = ""+ "a" * 100000 +"" numberOfRuns = 1000 ## TIMED FUNCTIONS startTime = time.clock() for i in range(0, numberOfRuns): re.match(pattern, longMessage) patternMatchingTime = time.clock() - startTime startTime = time.clock() for i in range(0, numberOfRuns): compiledPattern.match(longMessage) compiledPatternMatchingTime = time.clock() - startTime ratioCompiledToNot = compiledPatternMatchingTime / patternMatchingTime ## PRINT OUTS print("") print(" Pattern Matching Time: " + str(patternMatchingTime)) print("(Compiled) Pattern Matching Time: " + str (compiledPatternMatchingTime)) print("") print("Ratio Compiled/NotCompiled: " + str(ratioCompiledToNot)) print("") From wuwei23 at gmail.com Fri Dec 5 22:00:12 2008 From: wuwei23 at gmail.com (alex23) Date: Fri, 5 Dec 2008 19:00:12 -0800 (PST) Subject: To Troll or Not To Troll (aka: "as" keyword woes) References: <20081205163107.1815df40@usenot.de> Message-ID: <27945697-3f2f-452d-bed4-d1ca45d46fbb@r10g2000prf.googlegroups.com> On Dec 6, 8:00?am, James Stroud wrote: > I think its a symptom of the language's > maturing, getting popular, and a minority fraction* of the language's > most devout advocates developing an egotism that complements their > python worship in a most unsavory way. It's hard to see how anyone could ever take offence at your posts given such unbiased objectivity ;) From tjreedy at udel.edu Mon Dec 8 20:25:35 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Dec 2008 20:25:35 -0500 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: Jon Harrop wrote: > jason-sage at creativetrax.com wrote: >> For the interested, with MMA 6, on a Pentium 4 3.8Ghz: >> >> The code that Jon posted: >> >> Timing[Export["image-jon.pgm", Graphics at Raster@Main[2, 100, 4]]] >> {80.565, "image-jon.pgm"} > > That is not the code I posted: you are using Xah's parameters that generate > a different (and largely empty) scene. > >> The code that Xah posted: >> >> Timing[Export["image-xah.pgm", Graphics at Raster@Main[2, 100, 4.]]] >> {42.3186, "image-xah.pgm"} >> >> So Xah's code is about twice as fast as Jon's code, on my computer. >> >> The resulting files were identical (and both looked like pure white >> images; I thought they'd be interesting!). > > Use 9, 512, 4 instead of 2, 100, 4 and you will get a more interesting image > of over 80,000 spheres with shadows and diffuse lighting. > > This is a really important difference: half of that program is dedicated to > hierarchical spherical bounding volumes that are essential when tracing a > large number of spheres. Xah solved a completely different problem by > simplifying the scene to only 5 spheres, where bounding volumes are useless > and the performance characteristics of the program are wildly different. Lest anyone doubt that problem size is important for comparing program run times, consider the following realistic example: the run time of algorithm A is n*n, that of B is 10.6666666667*n*log2(n). A is faster for small problems, B for large problems, with the crossover at 64. A hybrid algorithm C could use B for large problems and A for small problems and small subproblems generated by B's divide and conquer technique. Python's list.sort is such a hybrid of binary insertion sort and merge sort, with a crossover at 64 based on experimental data. tjr From bkamrani at gmail.com Tue Dec 2 06:51:55 2008 From: bkamrani at gmail.com (bkamrani at gmail.com) Date: Tue, 2 Dec 2008 03:51:55 -0800 (PST) Subject: performance question: dictionary or list, float or string? References: Message-ID: <434bf4e3-54f4-4e15-b8b0-510a988f25b8@z1g2000yqn.googlegroups.com> I forgot to mention that I did a simple timeit test which doesn't show significant runtime difference 3.5 sec for dictionary case and 3.48 for list case. def read_as_dictionary(): fil = open('myDataFile', 'r') forces = {} for region in range(25): forces[region] = {} for step in range(20000): for region in range(25): line = fil.next(); spl = line.split() forces[region] [step] = spl def read_as_list(): fil = open('myDataFile.txt', 'r') forces = [] for region in range(25): forces.append([]) for step in range(20000): for region in range(25): line = fil.next(); spl = line.split() forces[region].append(spl) Cheers, /Ben From castironpi at gmail.com Thu Dec 18 16:40:35 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 18 Dec 2008 13:40:35 -0800 (PST) Subject: C API and memory allocation References: <59352942-e976-4ef4-bc40-c8953df0a792@c36g2000prc.googlegroups.com> <0d35b640-71ad-4cde-8869-74878b2f3981@r36g2000prf.googlegroups.com> <494a55fb$0$31873$9b4e6d93@newsspool3.arcor-online.net> Message-ID: On Dec 18, 7:54?am, Stefan Behnel wrote: > Aaron Brady wrote: > > I see. ?Do I read correctly that 's' is only useful when the > > argument's position is known? > > I assume you meant "length". No, position in the argument list. Otherwise you can't change its reference count; in which case, a pointer to the string object's contents (a char*) is useless after control leaves the caller's scope. > > ?Otherwise you can't know its length or > > change its reference count. > > The internal representation of Python byte strings is 0 terminated, so > strlen() will work. As MRAB said, Python strings can contain null bytes, since they carry their lengths. Therefore strlen will always succeed, but isn't always right. >>> len( "abc\x00def" ) 7 'strlen' says '3'. So, with 's', you are limited to the operations preceding null bytes in the current scope (with the GIL held). I hold this is strong enough to put the burden of proof on the defenders of having 's'. What is its use case? From eric at ericaro.net Thu Dec 4 15:08:51 2008 From: eric at ericaro.net (eric) Date: Thu, 4 Dec 2008 12:08:51 -0800 (PST) Subject: simplest way to strip a comment from the end of a line? References: <52e3f2a9-6fb1-42ef-9871-c904ede5520e@t3g2000yqa.googlegroups.com> Message-ID: <9cdc9039-6b7b-42fb-b261-4ad721ccd1d4@j39g2000yqn.googlegroups.com> On Dec 4, 5:15?pm, eric wrote: > On Dec 4, 4:50?pm, Joe Strout wrote: > > > I have lines in a config file which can end with a comment (delimited ? > > by # as in Python), but which may also contain string literals ? > > (delimited by double quotes). ?A comment delimiter within a string ? > > literal doesn't count. ?Is there any easy way to strip off such a ? > > comment, or do I need to use a loop to find each # and then count the ? > > quotation marks to its left? > > > Thanks, > > - Joe > > Hi, > > if the string literal you wan't to escape, is not escaped (i.e > contains \" ) then a regexp like > > .*?(?:".*?".*?)*#(?P .*?)$ > > (not tested) > .*? ?everything but keep it greedy > ".*?" the string literal not escaped well it works too import re test ='''this is a test 1 this is a test 2 #with a comment this is a '#gnarlier' test #with a comment this is a "#gnarlier" test #with a comment ''' splitter = re.compile(r'(?m)^(?P.*?(".*?".*?)*)(?:#.*?)?$') def com_strip(text): return [x[0] for x in splitter.findall(test) ] # raw implementation for line in test.split('\n'): print line, '->', re.match(r'(?P.*?(".*?".*?)*)(?:#.*?)?$', line).group("data") # with a function for line in com_strip(test): print line and here is the console output this is a test 1 -> this is a test 1 this is a test 2 #with a comment -> this is a test 2 this is a '#gnarlier' test #with a comment -> this is a ' this is a "#gnarlier" test #with a comment -> this is a "#gnarlier" test -> this is a test 1 this is a test 2 this is a ' this is a "#gnarlier" test From gagsl-py2 at yahoo.com.ar Wed Dec 24 12:37:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2008 15:37:53 -0200 Subject: How to change a generator ? References: <7F0503CD69378F49BE0DC30661C6CCF6024946E6@enbmail01.lsi.com> <49526B7E.20904@mrabarnett.plus.com> Message-ID: En Wed, 24 Dec 2008 15:03:58 -0200, MRAB escribi?: >> I have a generator whose aim is to returns consecutive lines from a >> file (the listing below is a simplified version). >> However, as it is written now, the generator method changes the text >> file pointer to end of file after first invocation. >> Namely, the file pointer changes from 0 to 6623 on line 24. >> > It might be that the generator method of self.input_file is reading the > file a chunk at a time for efficiency even though it's yielding a line > at a time. I think this is the case too. I can think of 3 alternatives: a) open the file unbuffered (bufsize=0). But I think this would greatly decrease performance. b) keep track internally of file position (by adding each line length). The file should be opened in binary mode in this case (to avoid any '\n' translation). c) return line numbers only, instead of file positions. Seeking to a certain line number requires to re-read the whole file from start; depending on how often this is required, and how big is the file, this might be acceptable. -- Gabriel Genellina From deen.vdm at gmail.com Sun Dec 7 02:52:35 2008 From: deen.vdm at gmail.com (deen.vdm at gmail.com) Date: Sat, 6 Dec 2008 23:52:35 -0800 (PST) Subject: hifriends Message-ID: <4e398db0-a652-4af6-a33c-c1c8fe86f1ef@s1g2000prg.googlegroups.com> hi,visit the web for download the latest songs and music by clickhttp://musicsite-download.blogspot.com/ From google at mrabarnett.plus.com Sat Dec 6 12:59:28 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 06 Dec 2008 17:59:28 +0000 Subject: RELEASED Python 3.0 final In-Reply-To: References: <874p1jux8u.fsf@benfinney.id.au> <87iqpyt80i.fsf@benfinney.id.au> Message-ID: <493ABD80.4020203@mrabarnett.plus.com> Mensanator wrote: > On Dec 5, 12:29 pm, "Hendrik van Rooyen" wrote: >> "Ben Finney" wrote: >>> I hereby recommend ?pish and tosh? for use by anyone who wants to >>> counter someone's point. It beats by a country furlong the invective >>> that has become regrettably common here in recent months. >> I second the motion to use pish and tosh for a first level of disagreement. >> >> I recommend the rather archaic "Balderdash" as the next step in the >> escalation of disagreement... > > As a W.C. Fields fan, I love his "non-swearing" > vocabulary: > > - Drat > > - Dag nab it > > - Holy Mother of Pearl! > > etc. > Holy Zarquon's Singing Fish! (Hitch-hiker's Guide to the Galaxy) But don't say B*****m. :-) http://www.bbc.co.uk/cult/hitchhikers/guide/belgium.shtml From 20080915.20.wmcclain at spamgourmet.com Wed Dec 10 06:58:37 2008 From: 20080915.20.wmcclain at spamgourmet.com (Bill McClain) Date: 10 Dec 2008 11:58:37 GMT Subject: StringIO in 2.6 and beyond References: Message-ID: On 2008-12-10, ajaksu wrote: > On Dec 9, 5:24?pm, Bill McClain <20080915.20.wmccl... at spamgourmet.com> > wrote: > > On 2008-12-09, MRAB wrote: > > > > > In Python 2.x unmarked string literals are bytestrings. In Python 3.x > > > they're Unicode. The intention is to make the transition from 2.x to 3.x > > > easier by adding some features of 3.x to 2.x, but without breaking > > > backwards compatibility (not entirely successfully!). > > > > It is a bit ugly. In 2.6 StringIO won't take bytestrings, so I apply u'x'. But > > in 3.0 u'x' will be gone and I'll have to change the code again. > Try: > from __future__ import unicode_literals That works for: output.write('First line.\n') ...but not for: print('Second line.', file=output) Maybe a combination of this and functools.partial as was suggested before. At least the necessary edits would be at the top of the program. -Bill -- Sattre Press Tales of War http://sattre-press.com/ by Lord Dunsany info at sattre-press.com http://sattre-press.com/tow.html From xahlee at gmail.com Wed Dec 31 12:55:23 2008 From: xahlee at gmail.com (Xah Lee) Date: Wed, 31 Dec 2008 09:55:23 -0800 (PST) Subject: Why not Ruby? Message-ID: Just spent 3 hours looking into Ruby today. Here's my short impression for those interested. * Why Not Ruby? http://xahlee.org/UnixResource_dir/writ/why_not_Ruby.html plain text version follows: -------------------------------------- Why Not Ruby? Xah Lee, 2008-12-31 Spent about 3 hours looking into Ruby language today. The articles i read in detail are: * Wikipedia: Ruby (programming language)?J. Gives general overview. * Brief tutorial: "Ruby in Twenty Minutes" http://www.ruby-lang.org/en/documentation/quickstart/ * Personal blog by Stevey Yegge, published in 2004-10. http://steve.yegge.googlepages.com/ruby-tour The Wikipedia gives the best intro and overview in proper context. The "Ruby in Twenty Minutes" is just 4 pages. It give you a very concrete intro to Ruby's syntax and semantics. Stevey Yegge's blog doesn't teach much and rambles, but provide a little personal view. I read it because his opinions i respect. Q: Will you learn Ruby? No. For practical application, the lang is some 100 times less useful than each of Perl, Python, PHP, Javascript. For academic study, functional langs like Mathematica, Haskell, OCaml, erlang, Qz, are far more interesting and powerful in almost all aspects. Further, there's also Perl6, NewLisp, Clojure, Scala... With respect to elegance or power, these modern lang of the past 5 years matches or exceed Ruby. Q: Do you think Ruby lang is elegant? Yes. In my opinion, better than Perl, Python, PHP. As a high level lang, it's far better than Java, C, C++ type of shit. However, i don't think it is any better than emacs lisp, Scheme lisp, javascript, Mathematica. Note that Ruby doesn't have a spec, and nor a formal spec. Javascript has. Ruby's syntax isn't that regular, nor is it based on a system. Mathemtica's is. Ruby's power is probably less than Scheme, and probably same as Javascript. I also didn't like the fact that ruby uses keyword "end" to indicate code block much as Pascal and Visual Basic, Logo, do. I don't like that. Q: Won't Ruby be a interesting learning experience? No. As far as semantics goes, Ruby is basically identical to Perl, Python, PHP. I am a expert in Perl and PHP, and have working knowledge of Python. I already regretted having spent significant amount of time (roughly over a year) on Python. In retrospect, i didn't consider the time invested in Python worthwhile. (as it turns out, i don't like Python and Guido cult, as the lang is going the ways of OOP mumbo- jumbo with its Python 3 "brand new" future.) There is absolutely nothing new in Ruby, as compared to Perl, Python, PHP, or Emacs lisp, Scheme lisp. Q: Do you recommend new programers to learn Ruby then? Not particularly. As i mentioned, if you are interested in practical utility, there's already Perl, PHP, Python, Javascript, which are all heavily used in the computing industry. If you are interested as a academic exercise, there's Scheme lisp, and much of functional langs such as OCaml, Haskell, Mathematica, which will teach you a whole lot more about computer science, features of language semantics, etc. Q: Do you condemn Ruby? No. I think it's reasonably elegant, but today there are too many languages, so Ruby don't particularly standout for me. Many of them, are arguably quite more elegant and powerful than Ruby. See: Proliferation of Computing Languages. From rafesacks at gmail.com Mon Dec 1 03:54:35 2008 From: rafesacks at gmail.com (Rafe) Date: Mon, 1 Dec 2008 00:54:35 -0800 (PST) Subject: Project structure - Best practices References: Message-ID: <2d1f986f-94da-49c8-a1a5-df9457d5f8b3@r36g2000prf.googlegroups.com> On Nov 30, 11:43?pm, "Filip Gruszczy?ski" wrote: > This is first time that I am building python application that is > larger than a single module and I would like to do it right. I google > it a bit, finding some stuff about not using src directory (which I > have seen so many times, that I believed it be standard) and using > packages. Still, there are few things, that I would like to achieve > with this structure: > * being able to use pychecker a lot - catching all typos in one shot > instead of running app many times really saves me a lot of time > * being able to write some unit tests > * having clean division of code among packages and modules (I have > seen some projects, where modules are pretty large - I would like to > keep them logically divided, event if they stay smaller) > > My project is a tool for people interested in role playing games. My > current structure looks something like this: > > /src > rpgDirectory.py (main script, running the app) > > src/rpg > plans.py > support.py > gui.py > iosystem.py > > src/rpg/character > model.py > sheet.py > gui.py > handlers.py > requirements.py > > The problem is, that modules from src/rpg/character use classes > defined in support.py. Therefore I have to use absolute paths to > import it and this works only, when I run rpgDirectory.py. When I use > pychecker, it can't import this module and fails. Any suggestions, how > can I avoid this and what structure should I use? > > -- > Filip Gruszczy?ski Hi, I have read in many places that relative imports aren't recommend as a standard. This includes PEP 8 (http://www.python.org/dev/peps/ pep-0008/) which states: " - Relative imports for intra-package imports are highly discouraged. Always use the absolute package path for all imports. Even now that PEP 328 [7] is fully implemented in Python 2.5, its style of explicit relative imports is actively discouraged; absolute imports are more portable and usually more readable." ...and I completely agree. I always use the standard import form unless absolutely necessary. However, I use 'as' to shorten the path to the last module. For example: >>> import app.foo.bar as bar >>> instance = bar.Class() The only "relative" import I use when I am getting another module in the same package. If I have: app/ __init__.py constants.py foo/ __init__.py bar.py here.py utils/ __init__.py ... and I am inside app/foo/here.py, I might have some imports at the top of the module which look like this... import app.constants as appC import app.utils import bar Python will look for 'bar' in the local package before looking through the python path. I could have imported constants as just "c", but single letter variables are dangerous and I work with an application where it is common in the community to use 'c' for 'constants' (regardless of the danger). Lastly, I could import 'app.utils' as 'utils', but this is such a common module name that I like to preserve the name-space or at least prefix it (so I suppose something like 'apputils' would be acceptable, but I'd only be saving one character, the '.', so what's the point?). I find that no matter how well I plan what my structure will be, I end up making small changes such as flattening a sub-package or converting a module to a sub-package to break things down further. As someone who recently started learning python, I would recommend that you just make a quick sketch of what you think might work and then just begin coding. Adjust to logic along the way. At some point planning begins to eat time rather than save it. get through the fastest initial 80%, maybe push for a few more %, then just go for it (I assume you have this luxury. If not then you probably have a team that can help refine the plan anyway.) Hope this helps. - Rafe From gnewsg at gmail.com Thu Dec 11 13:09:37 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 11 Dec 2008 10:09:37 -0800 (PST) Subject: How to know when it's possible to bind a socket on an unprivileged port? Message-ID: <799ba4ea-0ef8-499b-909e-507bf4abe4aa@z28g2000prd.googlegroups.com> Hi, For a purpose of testing I need a function which could tell me whether it is possible to bind sockets on privileged ports or not. I wrote down this simple function. It seems reasonably working to me but I'd like to hear your opinion first. Thanks in advance. import socket, errno def bind_on_privileged_ports(port=21): """Return True if it is possible to bind sockets on privileged ports (< 1024).""" try: s = socket.socket() s.bind(("", port)) except socket.error, err: if err[0] == errno.EACCES: return False s.close() return True --- Giampaolo http://code.google.com/p/pyftpdlib/ From sjmachin at lexicon.net Sat Dec 20 06:32:02 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 20 Dec 2008 03:32:02 -0800 (PST) Subject: Jarow-Winkler algorithm: Measuring similarity between strings References: <4f351b3b-4da7-4fee-a1ac-c42179d430f5@s9g2000prm.googlegroups.com> <665bf3f7-ef74-4e59-bbac-cfbc12d4e81d@x16g2000prn.googlegroups.com> Message-ID: On Dec 20, 7:07?pm, ?yvind wrote: > Thanks for the useful comments. > > On 20 Des, 01:38, John Machin wrote: > > > On Dec 20, 10:02?am, ?yvind wrote: > > > > Based on examples and formulas fromhttp://en.wikipedia.org/wiki/Jaro-Winkler. > > > For another Python implementation, google "febrl". > > > > Useful for measuring similarity between two strings. For example if > > > you want to detect that the user did a typo. > > > You mean like comparing the user's input word with some collection of > > valid words? You would need to be using something else as a quick-and- > > dirty filter ... Jaro-Winkler is relatively slow. > > Do you have any alternative ?suggestions? Use a Levenshtein or Damerau edit distance. The latter handles adjacent transpositions (...AB...->...BA...) which covers well over 90% of the transposition errors I've ever seen. The remainder e.g. ...AXB...->...BXA... are given the same weight by Jaro-Winkler; this is IMHO silly. Read a little bit further than the CS101 level on Levenshtein edit distance and ignore any implementation which calculates all N*M cells of a dynamic programming matrix -- in the case where the objective is to calculate the distance except that once the distance is known to be over a threshold you don't care how big it is (you will reject a match if the distance is too big), then you only need to fill in the entries in a narrow band astride the trailing diagonal, and you can reliably give up if the current distance on the diagonal becomes too high. Ukkonen's the man in this field. It gets better. You can forget the matrix when the word lengths are less than the number of bits in your computer word (even 32 bits is enough for most words in most languages). The bit-parallel techniques include Damerau distance. This paper by Heikki Hyyr? is well worth reading, and refers to a whole lot of previous work, including Ukkonen's: http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.6.2242 And you can forget about all the fancy techniques when the word lengths are so different that they can't be the same (e.g. Fu and Featherstonehaugh) -- or the shorter should perhaps be checked to see if it's a plausible abbreviation or contraction of the longer. > > ?Also as the Wikipedia article says, > > it's not a metric. I.e. it doesn't satisfy dist(a, c) <= dist(a, b) + > > dist(b, c). > > Its not a mathematical correct metric, but it is a useful heuristical > metric. Useful for what? IMHO: If it doesn't satisfy the symmetry condition and the triangle rule, it's just plain dodgy. J-W is dodgy and slow. Might as well use soundex. End of story. > > > The above code is not symmetrical; jarow_m(s1, s2) does not > > necessarily equal jarow_m(s2, s1). The article talks about one "m", > > not two of them. > > Hmm.. also a good point. I will make it count all the matches, not > just the matches in s1. The whole Jaro definition is woolly ... what is a match when you have more than one occurrence of the same letter? Have a look at what the matches might be between MISSISSIPPI and a variant with an extra I in the middle e.g MISSISISIPPI. Cheers, John From jstraszheim at comcast.net Sat Dec 6 16:42:08 2008 From: jstraszheim at comcast.net (Jeffrey Straszheim) Date: Sat, 06 Dec 2008 16:42:08 -0500 Subject: Can't get exclusive file lock when safely renaming a file In-Reply-To: <014a049b$0$20670$c3e8da3@news.astraweb.com> References: <014a049b$0$20670$c3e8da3@news.astraweb.com> Message-ID: <493AF1B0.9030802@comcast.net> Steven D'Aprano wrote: > I'm trying to safely rename a file without over-writing any existing > files, and I've run into a problem with file locks. Here's a naive way of > renaming without over-writing By default on a Linux filesystem, flock() gives you an _advisory_ lock. Other processes can touch the file unless they explicitly check the lock. Try man mount (see under the -o mand) and man fcntl (see under file locking) Jeffrey Straszheim From arnodel at googlemail.com Fri Dec 5 01:26:01 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 05 Dec 2008 06:26:01 +0000 Subject: Overriding a method at the instance level on a subclass of a builtin type References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> Message-ID: "Zac Burns" writes: > Ok. Feature request then - assignment of a special method name to an > instance raises an error. I haven't got the time to implement it, but I'm sure you can obtain the behaviour you want. -- Arnaud From mnordhoff at mattnordhoff.com Fri Dec 5 02:23:33 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Fri, 05 Dec 2008 07:23:33 +0000 Subject: generating a liste of characters In-Reply-To: <49369624.7020103@ncee.net> References: <49369624.7020103@ncee.net> Message-ID: <4938D6F5.30906@mattnordhoff.com> This is a slightly old post, but oh well... Shane Geiger wrote: > import string > alphabet=list(string.letters[0:26]) > print alphabet Most of the string module's constants are locale-specific. If you want the ASCII alphabet instead of the current language's, you need to use string.ascii_{letters,lowercase,uppercase}. > Yves Dorfsman wrote: >> Is there any built in way to generate a list of characters, something >> along the line of range('a'-'z') ? >> >> Right now I am using: >> >> chars = [ chr(l) for l in range(0x30, 0x3a) ] # 0 - 9 >> chars += [ chr(l) for l in range(0x41, 0x5b) ] # A - Z >> chars += [ chr(l) for l in range(0x61, 0x7b) ] # a - z >> >> Is there a better, more straight forward way of doing that ? >> >> >> >> Thanks. -- From vminch at gmail.com Sat Dec 13 10:50:26 2008 From: vminch at gmail.com (vk) Date: Sat, 13 Dec 2008 07:50:26 -0800 (PST) Subject: Netbeans Early Access and Python3 References: Message-ID: <04920acb-35e0-49da-8aaf-11c3c025977a@s1g2000prg.googlegroups.com> Netbeans is a very polished IDE. I just tried the Python EA plugin, however, and it does not have 3.x support as of now. From geekmail at usenot.de Thu Dec 4 05:11:15 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Thu, 4 Dec 2008 11:11:15 +0100 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> Message-ID: <20081204111115.7cee2ecc@usenot.de> On Wed, 03 Dec 2008 20:38:44 -0500 Lew wrote: > Xah Lee wrote: > > enough babble ... > > Good point. Plonk. Guun dun! > I vaguely remember you plonking the guy before. Did you unplonk him in the meantime? Or was that just a figure of speech? teasingly yours, /W -- My real email address is constructed by swapping the domain with the recipient (local part). From BrooklineTom at gmail.com Wed Dec 10 18:50:16 2008 From: BrooklineTom at gmail.com (brooklineTom) Date: Wed, 10 Dec 2008 15:50:16 -0800 (PST) Subject: Deeper tracebacks? References: Message-ID: <7e1c74f0-8f72-4a88-935b-90b77fe5aaa5@s37g2000vbp.googlegroups.com> On Dec 10, 5:03 pm, "Gabriel Genellina" wrote: > En Wed, 10 Dec 2008 16:59:16 -0200, brooklineTom > escribi?: > > > I want my exception handler to report the method that originally > > raised an exception, at the deepest level in the call-tree. Let give > > an example. > > That's the default behavior, you don't have to do anything special. > > > import sys, traceback > > class SomeClass: > > def error(self): > > """Raises an AttributeError exception.""" > > int(3).zork() > > > def perform_(self, aSelector): > > try: > > aMethod = getattr(self, aSelector, None) > > answer = apply(aMethod, [], {}) > > except: AttributeError, anAttributeErrorException: > > aRawStack = traceback.extract_stack() > > answer = None > > (I assume you're using Python < 3.0) > Use the 3-names form of the except statement: > > try: > aMethod = getattr(self, aSelector, None) > answer = aMethod() > except AttributeError, e, tb: > # the tb variable holds the traceback up to the error > # the same thing you see printed by Python when > # an unhandled error happens > answer = None > > Alternatively, you can obtain the same thing with sys.exc_info()[2] > Remember to delete any reference to the traceback object as soon as you're > done with it; seehttp://docs.python.org/library/sys.html#sys.exc_info > > -- > Gabriel Genellina I'm using Python 2.5. As I understand it, "aRawStack" (above) has the same information as sys.exc_info()[2]. The deepest entry in aRawStack is the perform_ invocation. The contents of the two bottom-most stack frames are: >>> aRawStack[8][3] "answer = anObject.perform_('error')" >>> aRawStack[9][3] 'aRawStack = traceback.extract_stack()' By the time the handler is called, "zork" -- the method that was called when the exception was raised, and "error", the method that invoked zork, have already been removed from the stack. In this example, I only show one call for simplicity. In practice, the method being invoked by perform_ may nest calls arbitrarily deeply. I know, by being in the exception handler, that an exception happened. What I need to know is which nested call raised it. From anurag.bagaria at gmail.com Tue Dec 23 04:53:03 2008 From: anurag.bagaria at gmail.com (ANURAG BAGARIA) Date: Tue, 23 Dec 2008 10:53:03 +0100 Subject: using subprocess module in Python CGI In-Reply-To: <47c890dc0812222200n26183303x717082b94010d250@mail.gmail.com> References: <47c890dc0812222200n26183303x717082b94010d250@mail.gmail.com> Message-ID: Thank you for the prompt response. Yeah, I missed out one line at the end of the error, the whole of which is: Traceback (most recent call last): File "process.py", line 18, in retval = subprocess.call(comd, 0, None, None, outptr, errptr) File "/usr/lib/python2.5/subprocess.py", line 443, in call return Popen(*popenargs, **kwargs).wait() File "/usr/lib/python2.5/subprocess.py", line 593, in __init__ errread, errwrite) File "/usr/lib/python2.5/subprocess.py", line 1135, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory Looking forward to any kind of help or suggestion in this regard. Thanks. On Tue, Dec 23, 2008 at 7:00 AM, Chris Rebert wrote: > On Mon, Dec 22, 2008 at 2:02 AM, ANURAG BAGARIA > wrote: > > Hello, > > > > I am a Python Newbie and would like to call a short python script via > > browser using a CGI script, but initially I am trying to call the same > > python script directly through python command line. The script intends to > > perform a few command line in a pipe and I have written the script (a > short > > one) as follows. > > > > #!/usr/bin/python > > > > import cgi, string, os, sys, cgitb, commands, subprocess > > import posixpath, macpath > > #file = "x.tar.gz" > > #comd = "tar -xf %s" % (file) > > #os.system(comd) > > #commands.getoutput('tar -xf x.tar.gz | cd demo; cp README ../') > > comd = [\ > > "tar -xf x.tar.gz", \ > > "cd demo", \ > > "cp README ../", \ > > ] > > outFile = os.path.join(os.curdir, "output.log") > > outptr = file(outFile, "w") > > errFile = os.path.join(os.curdir, "error.log") > > errptr = file(errFile, "w") > > retval = subprocess.call(comd, 0, None, None, outptr, errptr) > > errptr.close() > > outptr.close() > > if not retval == 0: > > errptr = file(errFile, "r") > > errData = errptr.read() > > errptr.close() > > raise Exception("Error executing command: " + repr(errData)) > > > > > > but after trying to execute this independently, I get the following error > > which I am unable to interpret : > > > > Traceback (most recent call last): > > File "process.py", line 18, in > > retval = subprocess.call(comd, 0, None, None, outptr, errptr) > > File "/usr/lib/python2.5/subprocess.py", line 443, in call > > return Popen(*popenargs, **kwargs).wait() > > File "/usr/lib/python2.5/subprocess.py", line 593, in __init__ > > errread, errwrite) > > File "/usr/lib/python2.5/subprocess.py", line 1135, in _execute_child > > raise child_exception > > There should be at least one more line in this traceback, and that > line is the most important one. > People will need that line to help you with your problem. > > Cheers, > Chris > > -- > Follow the path of the Iguana... > http://rebertia.com > -- I just want to LIVE while I'm alive. AB -------------- next part -------------- An HTML attachment was scrubbed... URL: From ajaksu at gmail.com Wed Dec 24 10:49:53 2008 From: ajaksu at gmail.com (ajaksu) Date: Wed, 24 Dec 2008 07:49:53 -0800 (PST) Subject: python web programming for PHP programmers References: Message-ID: <19270710-ba52-4d2c-bc19-7dad0c848aa5@y1g2000pra.googlegroups.com> On Dec 24, 12:40?pm, Nikola Skoric wrote: > I0m a python newbie with PHP background. I've tried to make a web app > from one of my python scripts (which I haven't done before) and I > ended up with: > > echo shell_exec("python foobar.py"); > ?> > which works really nice :-D Clever :) Python can work in a similar way to PHP if your server supports it, but Python also allows you to create the server itself. > For some reason I can't find no "quick and dirty python web > programming tutorial for PHP programmers" on google. :-D I don't need > a general python tutorial, I just need a tutorial on how to make a > hello world server side script with python. Any suggestions? See http://webpython.codepoint.net/cgi_hello_world for a very primitive way (and docs here: http://docs.python.org/dev/library/cgi.html ). A better way, that uses a trivial Python-based server: hello.py --- from wsgiref.simple_server import make_server def hello_app(environ, start_response): start_response("200 OK", [('Content-Type','text/plain')]) return "Hello world!" httpd = make_server('', 8000, hello_app) print "Serving HTTP on port 8000..." httpd.serve_forever() --- Then: $ python hello.py Serving HTTP on port 8000... localhost - - [24/Dec/2008 13:11:32] "GET / HTTP/1.1" 200 12 (see http://docs.python.org/dev/library/wsgiref.html#module-wsgiref.simple_server ) You can use better Python-based servers with handy features for testing: http://projects.wagner-flo.net/wsgi-serve/ http://pypi.python.org/pypi/James/0.7.1 Now, to ease things, you can have Python working more like PHP. First, server support. What HTTP server are you using? For starting up, mod_python (http://www.modpython.org/) isn't that bad, but there are better alternatives: http://code.google.com/p/modwsgi/ , http://pypi.python.org/pypi/python-fastcgi/1.1 and http://python.ca/scgi/ Then, there are many ways of getting the PHP feel (embedding in pages, etc.): http://www.modpython.org/live/current/doc-html/pyapi-psp.html#pyapi-psp http://nick.borko.org/pse/examples/php_example.html http://snakelets.sourceforge.net/ (development stopped) http://www.webwareforpython.org/PSP/Docs/index.html HTH, Daniel From timr at probo.com Wed Dec 31 02:43:04 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 31 Dec 2008 07:43:04 GMT Subject: multiprocessing vs thread performance References: Message-ID: Christian Heimes wrote: > >You have missed an important point. A well designed application does >neither create so many threads nor processes. The creation of a thread >or forking of a process is an expensive operation. That actually depends on the operating system. As one example, thread creation on Windows is not all that expensive. >You should use a pool of threads or processes. Even so, this is good advise. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From bakul+usenet at bitblocks.com Wed Dec 10 19:12:02 2008 From: bakul+usenet at bitblocks.com (Bakul Shah) Date: Wed, 10 Dec 2008 16:12:02 -0800 Subject: Mathematica 7 compares to other languages In-Reply-To: <49404775$0$4893$607ed4bc@cv.net> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> Message-ID: <49405AD2.7010207@bitblocks.com> John W Kennedy wrote: > Xah Lee wrote: >> In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, >> you'll have 50 or hundreds lines. > > C: > > #include > #include > > void normal(int dim, float* x, float* a) { > float sum = 0.0f; > int i; > float divisor; > for (i = 0; i < dim; ++i) sum += x[i] * x[i]; > divisor = sqrt(sum); > for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; > } > > Java: > > static float[] normal(final float[] x) { > float sum = 0.0f; > for (int i = 0; i < x.length; ++i) sum += x[i] * x[i]; > final float divisor = (float) Math.sqrt(sum); > float[] a = new float[x.length]; > for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor; > return a; > } > > q){x%sqrt sum x}3 4 0.6 0.8 From wtanksleyjr at gmail.com Mon Dec 8 19:43:31 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Mon, 8 Dec 2008 16:43:31 -0800 (PST) Subject: Guido's new method definition idea References: Message-ID: <06f8131b-ba72-4f65-a8c9-cc36b0fb586f@x14g2000yqk.googlegroups.com> On Dec 5, 6:21?pm, "Daniel Fetchinson" wrote: > I'd like this new way of defining methods, what do you guys think? > Anyone ready for writing a PEP? I think it's an awesome proposal. It's about time! With this change, defining methods uses the same special syntax hack that calling them does. This is a good thing because it makes it easy to refer to methods consistently. I see a lot of people are against it; I admit that it's not the status quo, but that's not a sufficient argument against a change (it defeats all possible changes). A more interesting argument against it is that it's special "implicit" syntax; but I would argue that it merely reflects the existing special syntax of method calls. Unfortunately, writing a PEP is sadly outside my skillset. > Daniel -Wm From zaz600 at gmail.com Fri Dec 26 22:52:50 2008 From: zaz600 at gmail.com (NoName) Date: Fri, 26 Dec 2008 19:52:50 -0800 (PST) Subject: SyntaxError: encoding problem: with BOM References: <6res8tF1do1sU1@mid.uni-berlin.de> <400f176b-bd9a-4f26-b01b-1aa7c7dcf5ac@z6g2000pre.googlegroups.com> <6rf6m1F1e0f8U1@mid.uni-berlin.de> <26e21f3f-ded1-48ca-8897-2ebd05dd07ad@w39g2000prb.googlegroups.com> Message-ID: <42a1d835-76d8-4b9e-b76e-c9853d4df25e@c36g2000prc.googlegroups.com> On 26 ???, 23:08, "Gabriel Genellina" wrote: > En Thu, 25 Dec 2008 11:55:16 -0200, NoName escribi?: > > > Error > > ---- > > C:\Documents and Settings\Ra\??????? ????>11.py > > File "", line 1 > > SyntaxError: encoding problem: with BOM > > > No error > > ---- > > C:\Documents and Settings\Ra\??????? ????>python 11.py > > test > > > Error when russian symbols in full path to py-script. > > Is it Python bug? or i need to modify some registry keys? > > Yes, it's a bug. The encoding declaration may be anything, ascii, even an > inexistent codec will trigger the bug. Any non-ascii character in the > script name or path provokes then a SyntaxError when the script is > executed directly. > As a workaround, avoid using any Russian characters in directory names or > script file names, or invoke them always using "python xxx.py", not > directly. > > > OS: WinXP SP3 Russian. > > Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit > > (Intel)] on win32 > > My tests were on WinXP SP3 Spanish. > Seehttp://bugs.python.org/issue4747 > > -- > Gabriel Genellina Gabriel Genellina, thanks for bug report =) From pruebauno at latinmail.com Tue Dec 30 12:16:08 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Tue, 30 Dec 2008 09:16:08 -0800 (PST) Subject: SQL, lite lite lite References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> Message-ID: <8da5c6b1-951f-4abd-8ee7-07b63802b9f6@13g2000yql.googlegroups.com> On Dec 29, 1:06?pm, Aaron Brady wrote: > Hi all, > > About a year ago, I posted an idea I was having about thread > synchronization to the newsgroup. ?However, I did not explain it well, > and I really erred on the side of brevity. ?(After some finagling, Mr. > Bieber and I decided it wasn't exactly anything groundbreaking.) ?But > I think the brevity cost me some readers, who might have had more > interest. ?The affair was on the whole discouraging. ?So, I'm going to > try another idea, and assume that readers have some time, and will > spend it on it. > > I don't think relational data can be read and written very easily in > Python. ?There are some options, such as 'sqllite3', but they are not > easy. ?'sqllite3' statements are valid SQL expressions, which afford > the entire power of SQL, but contrary to its name, it is not that > 'lite'. ?To me, 'lite' is something you could learn (even make!) in an > afternoon, not a semester; something the size of an ActiveState > recipe, or a little bigger, maybe a file or two. ?If you think SQL is > a breeze, you probably won't find my idea exciting. ?I assume that the > basics of SQL are creating tables, selecting records, and updating > records. > > My idea is to create a 'Relation' class. ?The details are basically > open, such as whether to back it with 'sqllite3', 'shelve', 'mmap', or > just mapping and sequence objects; what the simplest syntax is that > can capture and permit all the basics, and how much and what else can > fit in at that level; how and whether it can include arbitrary Python > objects, and what constraints there are on them if not; how and > whether to permit transactions; and what the simplest and coolest > thing you can do with a little Python syntax is. > > This is basically an invitation for everyone to brainstorm. ?(No > hijackings, good humor & digression ok.) ?Lastly, ... > > **warning, spoiler! ?here's what I thought of already.** > > **repeat! ?spoiler! ?here's what I thought of already.** > > #Just the select and update syntax: > > >>> a= people._select( "firstname== 'Joe'" ) > > #select 'key' from 'people' where 'firstname'== 'joe'>>> a > > [Entry2864, Entry3076, Entry3172]>>> entry1= a[ 0 ] > >>> entry1.phone > > #select 'phone' from 'people' where 'key'==self.key > "555-2413">>> entry1.phone= "555-1234" > > #update 'people' set 'phone'= '555-1234' where 'key'==self.key>>> entry1.phone > > "555-1234" > > #Create table syntax (a-whole-nother beast in itself): > > >>> classes= db.Relation( 'class_', 'person', Unique( 'class_', 'person' ) ) > > #create table 'classes' ( 'key', 'class_', 'person' ) unique > ( 'class_', 'person' ) > > >>> classes._unique( 'class_', 'person' ) > >>> classes.class_.noneok= False #'class_' cannot be null > >>> classes.person.noneok= False > >>> classes._insert( 'Physics', 'Dan' ) > >>> classes._insert( 'Chem', 'Tim' ) > > Hoping-"good critic"-is-self-consistent-ly, hoping-to-hear-it's-too- > complicated-already-ly, > A. Brady You really do like to reinvent the wheels do you? :-) Nothing wrong with that. Just be aware that most people that really need what you are proposing are probably already using mature feature rich libraries for that. http://wiki.python.org/moin/HigherLevelDatabaseProgramming From Scott.Daniels at Acm.Org Fri Dec 26 17:15:00 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 26 Dec 2008 14:15:00 -0800 Subject: strange behavior of math.sqrt() in new 3.0 version In-Reply-To: References: Message-ID: David Lemper wrote: > I'm a newbee trying 3.0 Please help with math.sqrt() > > At the command line this function works correctly > >>> import math > n = input("enter a number > ") > s = math.sqrt(n) > An entry of 9 or 9.0 will yield 3.0 > Yet the same code in a script gives an error message > Script1 > import math > n = input("enter a number > ") > s = math.sqrt(n) > ... TypeError : a float is required > > Strangely the above code runs fine in version 2.5 ( ? ) ... OK, here's what's going on: "at the command line" in 2.X, the builtin function input reads a string and returns the eval of that string. This is a bit of a safety issue. I suspect when "it worked from the command line," you were using a 2.X command line inadvertently. in 2.X, you'll get similar errors if you use "raw_input" instead of "input". The "input" function in 3.0 is the same as the "raw_input" function in 2.X. I would suggest using: import math value = float(input("enter a number > ")) root = math.sqrt(value) print('root(%s) == %s' % (value, root)) I avoid using single-letter variables except where I know the types from the name (so I use i, j, k, l, m, n as integers, s as string, and w, x, y, and z I am a little looser with (but usually float or complex). --Scott David Daniels Scott.Daniels at Acm.Org From steve at REMOVE-THIS-cybersource.com.au Sat Dec 20 20:49:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Dec 2008 01:49:45 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <015d9804$0$20656$c3e8da3@news.astraweb.com> On Sat, 20 Dec 2008 15:27:43 -0800, walterbyrd wrote: > On Dec 19, 10:25?am, Michael Torrie wrote: > >> Personally the new string formatter is sorely needed in Python. > > Really? You know, it's funny, but when I read problems that people have > with python, I don't remember seeing that. Loads of people complain > about the white space issue. Some people complain about the speed. Lots > of complaints about certain quirky behavior, but I have not come across > any complaints about the string formatting. There are some things that some people whinge about, often just to hear the sound of their own voice (or the look of their own font, if you prefer). Whitespace and speed are two of those: they attract trolls and sooks. (That's not to say that there aren't real problems related to them. But it seems to me that the real problems are drowned out by the trolls.) Then there are things that people don't complain about, they just shrug and code a work-around. If % doesn't do what you want, do you cry about it, or do you code around it? I can't speak for others, but what I did was ask the question, discover that % was not powerful enough, and coded around it: http://mail.python.org/pipermail/python-list/2006-April/376641.html > In fact, from what I have seen, many of the "problems" being "fixed" > seem to be non-problems. > > I dunno, maybe it's just me. It's just you. Sheesh, I've never seen such a bunch of cry-babies sooking that their favourite language just got *more* power and flexibility. If functionality was being removed, I could understand the response, but this? It's just crazy. -- Steven From benjamin.kaplan at case.edu Fri Dec 12 15:59:36 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 12 Dec 2008 15:59:36 -0500 Subject: Umlauts in idle In-Reply-To: <26880ecf-d0eb-42ab-8ebd-56f64c023999@v39g2000pro.googlegroups.com> References: <26880ecf-d0eb-42ab-8ebd-56f64c023999@v39g2000pro.googlegroups.com> Message-ID: On Fri, Dec 12, 2008 at 3:51 PM, a_olme wrote: > Hello all, > > When I try to use umlauts in idle it will only print out as Unicode > escape characters. Is it possible to configure idle to print them as > ordinary characters? > Best Regards Anders Olme Make sure you are using Unicode strings and not byte strings. This is why Python 3 switched to using Unicode by default. IDLE 2.6.1 on Mac 10.5 : >>> print u'\u00c4' ? >>> print '\u00c4' \u00c4 > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From muhamed.hmd at gmail.com Tue Dec 9 16:06:22 2008 From: muhamed.hmd at gmail.com (john adam) Date: Tue, 9 Dec 2008 13:06:22 -0800 (PST) Subject: conratulations....... Message-ID: conratulatios...... Here's my dear friend largest mobile library programs All you care programs : Witness all the programs in the modern world Alkmiotr Honored by your visit You'll see in the blogger 1.If you are suffering from a virus protection programs most important to you AVG Anti-Virus Free Edition "avG" http://mesotheliomame.blogspot.com/2008/11/pericardial-mesothelioma-and-modern.html 2.If you turn suffering from transmitting the files LimeWire Pro 4.14.7 http://mesotheliomame.blogspot.com/2008/11/overview-of-mesothelioma-cancer.html 3.If you have files you spy on your computer solution Ad-Aware 2008 http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawsuits-faq.html 4.You stronger virus program Ante 2008 Avira AntiVir Personal - Free Antivirus http://mesotheliomame.blogspot.com/2008/11/number-form-of-mesothelioma-pleural.html 5.Now a program of protection and anti-virus and anti-spy files Avast Home Edition http://mesotheliomame.blogspot.com/2008/11/what-to-look-for-in-california.html 6.If you are suffering from non-fast you download this program FrostWire http://mesotheliomame.blogspot.com/2008/11/if-you-are-diagnosed-with-mesothelioma_15.html 7.If you have difficulty loading of the Diaspora and Google Orbit Downloader http://mesotheliomame.blogspot.com/2008/11/if-you-are-diagnosed-with-mesothelioma.html 8.If you have difficulty difficult compression "file" winrar http://mesotheliomame.blogspot.com/2008/11/contacting-mesothelioma-lawyer.html 9.If you are suffering from aAdware/Malware files you solution Malwarebytes' Anti-Malware http://mesotheliomame.blogspot.com/2008/11/scientists-conduct-clincial-trials-of.html 10.Now the most powerful video chat in the world Camfrog Video Chat http://mesotheliomame.blogspot.com/2008/11/new-drug-study-for-abdominal.html 11.Program chat world is a lot mIRC http://mesotheliomame.blogspot.com/2008/11/ohio-mesothelioma-lawyer-help-you-get.html 12.If you have difficulty reading flv files FLV Player http://mesotheliomame.blogspot.com/2008/11/detailed-information-on-mesothelioma.html 13.If you have difficulty download from youtube YouTube Downloader http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawyers-in-high-demand.html 14.If you are suffering from penetrating the strongest program you repel breakthroughs in the world Spybot - Search & Destroy http://mesotheliomame.blogspot.com/2008/11/chemotherapy-treatment-for-mesothelioma.html 15.If you have difficulty with the way they spread the images IrfanView http://mesotheliomame.blogspot.com/2008/11/california-mesothelioma-laws-and.html 16.Now have a major program of the torrent file and upload files BitComet http://mesotheliomame.blogspot.com/2008/11/facing-mesothelioma-without-california.html 17.The program is exclusive download from the Web at high speed Download Accelerator Plus http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-diagnoses-increase_15.html 18.If you are suffering from problems with the performance of the solution you Smart Defrag http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-diagnoses-increase.html 19.If you have difficulty in performing the solution you Advanced WindowsCare Personal http://mesotheliomame.blogspot.com/2008/11/mesothelioma-is-deadly-cancer.html 20.If you have difficulty in operating the sound and video files you solution real player http://mesotheliomame.blogspot.com/2008/11/facts-and-misconceptions-about.html 21.Here is the most important video player program in America GOM Media Player http://mesotheliomame.blogspot.com/2008/11/how-severe-is-mesothelioma-disease.html 22.If you have difficulty operating Flash Games Flash Player http://mesotheliomame.blogspot.com/2008/11/glimpse-at-mesothelioma-info-from-past.html 23.If you have difficulty in cleaning Riggstir professionally you the best solution http://mesotheliomame.blogspot.com/2008/11/detection-of-asbestos-mesothelioma.html 24.If you turn suffering from your computer and the difficulty you download this program"System Mechanic" http://mesotheliomame.blogspot.com/2008/11/brief-overview-of-malignant.html 25.If you are suffering from problems in the cleaning solution you Riggstir http://mesotheliomame.blogspot.com/2008/11/mesothelioma-and-911.html 26.Use the latest hour computer in the world in the magnificence of beauty http://mesotheliomame.blogspot.com/2008/11/precise-idea-about-pericardial.html 27.If you have difficulty in maintaining from hard disk http://mesotheliomame.blogspot.com/2008/11/mesothelioma-at-glance.html 28.If you have difficulty in managing personal and protection of your system you program http://mesotheliomame.blogspot.com/2008/11/financial-burden-of-mesothelioma.html 29.If you have difficulty in recording data and operation of your system http://mesotheliomame.blogspot.com/2008/11/how-to-find-mesothelioma-lawyer.html 30.Here's this program that offers you much time http://mesotheliomame.blogspot.com/2008/11/hurricane-victims-at-risk-for.html 31.If you have difficulty in browsing files http://mesotheliomame.blogspot.com/2008/11/3-top-florida-mesothelioma-lawyer.html 32.Here's this program, which automatically corrects the mistakes of your system security http://mesotheliomame.blogspot.com/2008/11/if-diagnosed-with-mesothelioma-call.html 33.The enjoyment of this program to register images from camera to the computer during the talk http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-diagnosed-questions.html 34.If you have difficulty transforming stretches in games or votes you this giant http://mesotheliomame.blogspot.com/2008/11/mesothelioma-ready-reckoner.html 35.If you have difficulty in operation all formats video files http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawyers-how-to-choose-them.html 36.If you have difficulty in the organization and ease of cleaning solution you http://mesotheliomame.blogspot.com/2008/11/mesothelioma-exposure-could-be-fatal.html 37.Very popular program in the compression winzip http://mesotheliomame.blogspot.com/2008/11/mesothelioma-greed-cancer-profits.html 38..If you want to broadcast material on the Internet you solution Virtual DJ Software http://mesotheliomame.blogspot.com/2008/11/abc-mesothelioma-new-treatments-for.html 39.now The creation of program files pdf PrimoPDF http://mesotheliomame.blogspot.com/2008/11/abc-mesothelioma-treatments-for.html 40..If you have difficulty operating the extensions you solution "MPEG-1, MPEG-2, MPEG-DivX, mp3, ogg VLC Media Player http://mesotheliomame.blogspot.com/2008/11/brachytherapy-for-treatment-of.html 41.If you have difficulty browser you this treasure Mozilla Firefox http://mesotheliomame.blogspot.com/2008/11/asbestos-mesothelioma-treatment-how.html 42.If you are difficult to clean your computer you solution Glary Utilities http://mesotheliomame.blogspot.com/2008/11/mesothelioma-treatment-research.html 43.very Free program to repair and improve and see photos PhotoScape http://mesotheliomame.blogspot.com/2008/11/mesothelioma-cancer-history.html 44.If you have difficulty operating films and cartoons BS.Player http://mesotheliomame.blogspot.com/2008/11/mesothelioma-attorney.html 45.Conversion formulas giant cylinders to the chimerical not want the program ... PowerISO http://mesotheliomame.blogspot.com/2008/11/deadly-mesothelioma-symptoms-could-be_15.html 46.You program the operator of high-quality video DivX for Windows with DivX Player http://mesotheliomame.blogspot.com/2008/11/deadly-mesothelioma-symptoms-could-be.html 47.If you have difficulty copies of CDs nero "9"new http://mesotheliomame.blogspot.com/2008/11/association-of-asbestos-and.html 48.If you have difficulty audio chat on the net you the solution Windows Live Messenger http://mesotheliomame.blogspot.com/2008/11/need-for-mesothelioma-lawyer-to-fight.html 49.If you have difficulty download on the net ActiveX Download Control http://mesotheliomame.blogspot.com/2008/11/funding-for-mesothelioma-research-noble_15.html 50.If you have difficulty in registration at the sites and forums you solution RoboForm http://mesotheliomame.blogspot.com/2008/11/funding-for-mesothelioma-research-noble.html 51.If you are an amateur or design you a solution designed sites you Adobe Photoshop CS3 Extended http://mesotheliomame.blogspot.com/2008/11/brief-overview-of-peritoneal.html 52.If you have difficulty cleaning you stronger cleaning program in the world ccleaner http://mesotheliomame.blogspot.com/2008/11/mesothelioma-lawyers-helping-hands.html 53.If you have difficulty in Alturrent know what files you need them all uTorrent http://mesotheliomame.blogspot.com/2008/11/how-to-proceed-with-mesothelioma_15.html 54.If you have difficulty in loading files from the iPod Lalai iTunes http://mesotheliomame.blogspot.com/2008/11/how-to-proceed-with-mesothelioma.html 55.If you have difficulty converting audio files to any formulas you solution Easy CD-DA Extractor http://mesotheliomame.blogspot.com/2008/11/difference-between-pleural-and.html 56.If you have difficulty converting video files to the formula psp PSP Video 9 http://mesotheliomame.blogspot.com/2008/11/positive-guideline-to-deal-with.html 57.If you have difficulty in the work of videos from YouTube to evict you like you solution Windows Movie Maker http://mesotheliomame.blogspot.com/2008/11/history-of-asbestos-related.html 58.If you have difficulty in Works with all audio files extranet windows media player http://mesotheliomame.blogspot.com/2008/11/tips-on-choosing-your-mesothelioma.html 59.If you have difficulty in Browser you the most powerful browser in the world Avant Browse http://mesotheliomame.blogspot.com/2008/11/good-mesothelioma-attorney-is-hard-to.html 60.If you have difficulty in Video-sharing to you this wonderful program BearFlix http://mesotheliomame.blogspot.com/2008/11/peritoneal-mesothelioma-information.html 61.If you have difficulty in Survey of spyware on your computer SpywareBlaster http://mesotheliomame.blogspot.com/2008/11/how-to-care-for-someone-with.html 62.If you are suffering from problems in Alhard Disek you this legend smart PerfectDisk http://mesotheliomame.blogspot.com/2008/11/why-is-mesothelioma-so-deadly.html 63.If you have difficulty in the liberation of files "pdf" http://mesotheliomame.blogspot.com/2008/11/when-do-you-need-mesothelioma-attorney.html 64.If you have difficulty in personal control of your system next to you http://mesotheliomame.blogspot.com/2008/11/all-about-mesothelioma-lawyer.html 65.If you have difficulty in the key to jump easily be you next http://mesotheliomame.blogspot.com/2008/11/what-is-mesothelioma-cancer.html 66.If you have difficulty playing in the pictures and the amendment http://mesotheliomame.blogspot.com/2008/11/mesothelioma-information.html 67.If you have difficulty in protecting your system security followed CAPS http://mesotheliomame.blogspot.com/2008/11/symptoms-of-mesothelioma.html 68.If you have difficulty in speed of your computer you this program http://mesotheliomame.blogspot.com/2008/11/what-radical-mesothelioma-treatments.html 69.If you have difficulty maintaining a malfunction in your computer that you legend http://mesotheliomame.blogspot.com/2008/11/can-washington-mesothelioma-attorneys.html 70.If you have difficulty in the transfer of files between disks http://mesotheliomame.blogspot.com/2008/11/causes-of-mesothelioma-cancer.html 71.Discovered the most important program on the Web EZ Macros http://mesotheliomame.blogspot.com/2008/11/mesothelioma-treatment-radiation-or.html 72.If you are suffering from similar files, you repeat this unique program http://mesotheliomame.blogspot.com/2008/11/types-of-mesothelioma-cancer.html http://mesotheliomame.blogspot.com/ From fetchinson at googlemail.com Wed Dec 10 18:11:35 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 10 Dec 2008 15:11:35 -0800 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <20081226055859.604@gmail.com> Message-ID: On 12/10/08, Jon Harrop wrote: > Xah Lee wrote: >> Kaz Kylheku wrote: >>> Really? ``50 or hundreds'' of lines in C? >>> >>> #include /* for sqrt */ >>> >>> void normalize(double *out, double *in) >>> { >>> double denom = sqrt(in[0] * in[0] + in[1] * in[1] + in[2] * >>> in[2]); >>> >>> out[0] = in[0]/denom; >>> out[1] = in[1]/denom; >>> out[2] = in[2]/denom; >>> } >>> >>> Doh? >> >> Kaz, pay attention: >> >> Xah wrote: ?Note, that the "norm" as defined above works for vectors >> of any dimention, i.e. list of any length.? > > That is still only 6 lines of C code and not 50 as you claimed: > > double il = 0.0; > for (int i=0; i il += in[i] * in[i]; > il = 1.0 / sqrt(il); > for (int i=0; i out[i] = il * in[i]; > > Try computing the Fourier transform of: > > 0.007 + 0.01 I, -0.002 - 0.0024 I Funniest thread ever! Actual real money changing hands, did this happen ever in a newsgroup? Xah Lee rulez! Xah Lee for president! (No kidding, I like the guy.) Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From rt8396 at gmail.com Thu Dec 25 13:42:36 2008 From: rt8396 at gmail.com (r) Date: Thu, 25 Dec 2008 10:42:36 -0800 (PST) Subject: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> <90f06b27-39da-4f1a-a878-f3972e942d57@s24g2000vbp.googlegroups.com> <62caf93b-0455-4450-9895-8a9d9554f75e@r32g2000vba.googlegroups.com> <1isezkk.51e05y1457jqrN%pdorange@pas-de-pub-merci.mac.com> <3cb2a746-1a43-44a1-9825-7667af9fe2fa@s1g2000prg.googlegroups.com> <1isi4sn.11mpft612g7udcN%pdorange@pas-de-pub-merci.mac.com> Message-ID: On Dec 25, 4:22?am, pdora... at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) wrote: > r wrote: > > 220 ratings and 1 star, WHOOOO!. I find this all quite amusing :D. > > Keep em coming. Oh, and FYI, I will always have 1 star! hahahahahha > > > ? ? ? ? ? ? ? ? ? ?/"\ > > ? ? ? ? ? ? ? ? ? ? |\./| > > ? ? ? ? ? ? ? ? ? ? | ? | > > ? ? ? ? ? ? ? ? ? ?| ? | > > ? ? ? ? ? ? ? ? ? ? |>~<| > > ? ? ? ? ? ? ? ? ? ? | ? | > > ? ? ? ? ? ? ? ? ?/'\| ? |/'\ > > ? ? ? ? ? ? ?/~\| ? | ? | ? |__ > > ? ? ? ? ? ? | ? | ? } ? | ? | ?\ > > ? ? ? ? ? ? | ? | ? | ? | ? | ? \ > > ? ? ? ? ? ?| ~ ? ~ ? ~ ? ~ |` ? ) > > ? ? ? ? ? ? | ? ? ? ? ? ? ? ? ? / > > ? ? ? ? ? \ ? ? ? ? ? ? ? ? ?/ > > ? ? ? ? ? ? ? \ ? ? ? ? ? ? ? / > > ? ? ? ? ? ? ? ?\ ? ?____ ? ? / > > ? ? ? ? ? ? ? ? |--//''`\--| > > ? ? ? ? ? ? ? ? | (( +==)) | > > ? ? ? ? ? ? ? ? |--\_|_//--| > > Very nice indeed, but you forget ascii art need a fixed font... > > -- > Pierre-Alain Dorange > > Ce message est sous licence Creative Commons "by-nc-sa-2.0" > ? ? ? ? Go to Google groups... it looks perfect :) From max at alcyone.com Sat Dec 6 19:36:15 2008 From: max at alcyone.com (Erik Max Francis) Date: Sat, 06 Dec 2008 16:36:15 -0800 Subject: Guido's new method definition idea In-Reply-To: <8b8d1fb3-f49e-49bf-8cfe-eeee5ed16109@r37g2000prr.googlegroups.com> References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> <8b8d1fb3-f49e-49bf-8cfe-eeee5ed16109@r37g2000prr.googlegroups.com> Message-ID: Russ P. wrote: > On Dec 6, 4:32 am, Andreas Waldenburger wrote: >> But that is not the way Python is meant to work. There are several >> tennets in the Zen of Python that don't chime well with this approach. >> "self" is a speaking identifier, "$" isn't. > > Is "@" a "speaking identifier? How about "#" and "!="? Last I heard, > they were all part of Python. None of these are identifiers at all. You might want to read up on the language reference to see what an identifier actually is. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis There are not fifty ways of fighting, there is only one: to be the conqueror. -- Andrew Malraux, 1937 From ndbecker2 at gmail.com Thu Dec 18 13:35:33 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 18 Dec 2008 13:35:33 -0500 Subject: confused about __str__ vs. __repr__ References: <494A5ACA.8060205@wildenhain.de> Message-ID: Mel wrote: > Neal Becker wrote: > >> Tino Wildenhain wrote: >> >>> Neal Becker wrote: >>>> Reading some FAQ, I see that __str__ is "meant for human eyes". >>>> >>>> But it seems that: >>>> class X(object): >>>> def __str__(self): >>>> return "str" >>>> def __repr__(self): >>>> return "repr" >>>> >>>> x = X() >>>> d = {0 : x} >>>> print d >>>> {0: repr} >>>> >>>> So if __str__ is "meant for human eyes", then why isn't print using it! >>> >>> it is: >>> >>> > print x >>> str >>> >>> but dict just uses repr() for all its childs to print. >>> >>> T. >> That makes no sense to me. If I call 'print' on a container, why >> wouldn't >> it recursively print on the contained objects? Since print means call >> str, printing a container should recursively call str on the objects. > > Basically because there are too many right ways to format the resulting > report. Space separated? Tab separated? One per line? Boxes around > them? As HTML definition lists? Creating a standard report form would > take a lot of work and wouldn't, finally, solve very many peoples' > problems. > > Mel. > Thanks, but the question of how to format the container is different from how to format the primitive elements of the container. I was suggesting that printing an element of a container should be consistent with printing the element without the container, i.e., print [a] should be consistent with print a From bruno.42.desthuilliers at websiteburo.invalid Fri Dec 12 06:56:16 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 12 Dec 2008 12:56:16 +0100 Subject: (Very Newbie) Problems defining a variable In-Reply-To: References: Message-ID: <49425146$0$8495$426a74cc@news.free.fr> febaen at gmail.com a ?crit : > #!/usr/bin/python > #Py3k, UTF-8 > > bank = int(input("How much money is in your account?\n>>")) > target = int(input("How much money would you like to earn each year? > \n>>")) > > interest = 0 > i = 0 > > while interest < target: > #determine the interest rate to use > if bank >= 9999: > rate = 0.006 > elif bank >= 10000 and bank <= 24999: > rate = 0.0085 > elif bank >= 25000 and bank <= 49999: > rate = 0.0124 > elif bank >= 50000 and bank <= 99999: > rate = 0.0149 > elif bank >= 100000: > rate = 0.0173 (snip) > I'm pretty certain that that is also the problem in the code. I'm > pretty sure it's a problem with the 'if' statements', and it looks > like it's one of those mistakes that's so simple you look back on it > and laugh at yourself. If you put in a bank number <= 9999, it fails, > saying "NameError: name 'rate' is not defined". If you put in one > higher, it runs correctly, but thinks that the rate is 0.006 Indeed. That's what you asked for. If bank is >= 9999, then rate will be set to 0.006, and the following tests will be skipped. Else - since you just don't handle the case -, rate is not defined at all. I guess you wanted your first test to be: if bank <= 9999: ... FWIW, when using if/elif that way, make sure you always end with a "default" else clause (even if just to signal you didn't expect to be there...) HTH From sonynamratha2009 at gmail.com Wed Dec 24 15:33:34 2008 From: sonynamratha2009 at gmail.com (sony) Date: Wed, 24 Dec 2008 12:33:34 -0800 (PST) Subject: mobiles Message-ID: Excellent Mobiles(Latest) http://latestmobii.blogspot.com/2008/11/blackberry-8800.html http://latestmobii.blogspot.com/2008/11/sony-ericsson-z555i.html http://latestmobii.blogspot.com/2008/11/motorola.html http://latestmobii.blogspot.com/2008/11/samsung.html http://latestmobii.blogspot.com/2008/11/nokia-7380-coming-soon.html http://latestmobii.blogspot.com/2008/11/sony-ericsson-xperia-x1.html http://latestmobii.blogspot.com/2008/11/nokia-8800.html From jason.scheirer at gmail.com Thu Dec 18 13:51:08 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Thu, 18 Dec 2008 10:51:08 -0800 (PST) Subject: Is this pythonic? References: <66d058f9-cfe1-4b3c-ab8a-e6e88bb97770@m22g2000vbp.googlegroups.com> <7dc03d4b-4bce-4cc4-b020-681935cf0b0b@m4g2000vbp.googlegroups.com> Message-ID: On Dec 18, 8:45?am, prueba... at latinmail.com wrote: > On Dec 18, 11:08?am, ipyt... at gmail.com wrote: > > > x.validate_output(x.find_text(x.match_filename > > (x.determine_filename_pattern(datetime.datetime.now())))) > > > Is it even good programming form? > > Lisp and Scheme programmers love that style. You can tell by the > number of parentheses :-). In Python people usually use an > intermediate variable to break things up a bit but the amount of > acceptable nesting is a matter of personal style. I'd say it's fine but breaking up the statement once or twice is a good idea just because if one of the function calls in this nested thing throws an exception, a smaller statement with fewer calls makes for a far more readable traceback. And I hope that this whole statement all lives inside of a method in the same x class, or is a higher-level class that makes use of this behavior? If not, you may want to consider doing so. class X(object): @property def todays_filepattern(self): return self.match_filename( self.determine_filename_pattern( datetime.datetime.now())) def validate_todays_files(self): return self.validate_output(self.find_text (self.todays_filepattern)) From metolone+gmane at gmail.com Fri Dec 26 02:16:21 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Thu, 25 Dec 2008 23:16:21 -0800 Subject: How to display Chinese in a list retrieved from database via python References: <22be506d-91c2-4727-ace7-2e3382b6d214@g3g2000pre.googlegroups.com> <979fdf6d-0500-47ba-87fd-0f0361ca3059@p2g2000prf.googlegroups.com> Message-ID: "zxo102" wrote in message news:979fdf6d-0500-47ba-87fd-0f0361ca3059 at p2g2000prf.googlegroups.com... > On 12?26?, ??4?58?, "Gabriel Genellina" > wrote: >> En Thu, 25 Dec 2008 07:27:03 -0200, zxo102 escribi?: >> >> >> >> > On 12?25?, ??3?35?, "Chris Rebert" wrote: >> >> On Wed, Dec 24, 2008 at 11:29 PM, zxo102 wrote: >> >> > Hi, >> >> > I retrieve some info in Chinese from postgresql and assign it to >> >> > a >> >> > variable 'info' defined in javascript of a html page: >> >> > var info = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce >> >> > \xc4'] >> >> > But I want it to be >> >> > var info = ['??','??','??'] >> >> > since in html pages (via javascript), the items in chinese out of >> >> > the >> >> > former :['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4'] >> >> > can >> >> > not be displayed correctly when it is inserted into a html page. If >> >> > the list is var info = ['??','??','??'] , then everything >> >> > works >> >> > fine. >> >> > The html code is as follows >> >> > test >> > >> > >> >> > But the '??' is '\xd6\xd0\xce\xc4'. When row01 and row02 is called >> > from somewhere, >> > '\xd6\xd0\xce\xc4' can not be displayed correctly as '??' in html >> > environment. >> >> You forgot to specify the page encoding, gb2312 presumably. If adding the >> encoding does not help, I'd say the problem must reside on how you later >> use row01 and row02 (your html page does not those variables for >> anything). '??' is the same as '\xd6\xd0\xce\xc4', and both javascript >> and Python share the same representation for strings (mostly) so this >> should not be an issue. >> >> My PC is unable to display those characters, but I get "true" from this: >> >> test >> >> >> -- >> Gabriel Genellina > > I did that: , but it does not work. Alert('\xd6\xd0\xce\xc4') >> displays some "junks". I am thinking there may be some way to convert >> '\xd6\xd0\xce\xc4' to '??' in the list with python before I generate >> the html page. As a result, when I open the html file with Vi, I can see >> '??' directly instead of '\xd6\xd0\xce\xc4'. That will solve my >> problem. > > Any ideas? Use charset=gb2312 instead of charset='gb2312'(remove single quotes). I was able to display ?? successfully with this code: f=open('test.html','wt') f.write(''' test \xd6\xd0\xce\xc4''') f.close() -Mark From gdamjan at gmail.com Tue Dec 16 19:10:44 2008 From: gdamjan at gmail.com (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Wed, 17 Dec 2008 01:10:44 +0100 Subject: mod_python resources References: <78064e7e-ba2c-4959-b5f8-4d1b928bc5fe@y18g2000yqn.googlegroups.com> Message-ID: <4lsl16-15a.ln1@archaeopteryx.softver.org.mk> > I'm trying again because I'm stubborn. Maybe the fourth time will be > the charm... > > Are there any good tutorials out there for setting up Apache with > mod_python? mod_python is depreceated, nobody uses it. use mod_wsgi http://www.modwsgi.org/ -- ?????? ( http://softver.org.mk/damjan/ ) Today we create the legacy of tomorrow. From george.sakkis at gmail.com Sun Dec 7 19:24:58 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 7 Dec 2008 16:24:58 -0800 (PST) Subject: Rich Comparisons Gotcha References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> <014c55e9$0$20670$c3e8da3@news.astraweb.com> Message-ID: <11d8b41a-a910-4915-8969-fc90e978350b@j11g2000yqg.googlegroups.com> On Dec 7, 6:37?pm, Steven D'Aprano wrote: > On Sun, 07 Dec 2008 23:20:12 +0000, Steven D'Aprano wrote: > > On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: > > >> Rasmus Fogh wrote: > > >>> Current behaviour is both inconsistent and counterintuitive, as these > >>> examples show. > > >>>>>> x = float('NaN') > >>>>>> x == x > >>> False > > >> Blame IEEE for that one. Rich comparisons have nothing to do with that > >> one. > > > There is nothing to blame them for. This is the correct behaviour. NaNs > > should *not* compare equal to themselves, that's mathematically > > incoherent. > > Sorry, I should explain why. > > Given: > > x = log(-5) ?# a NaN > y = log(-2) ?# the same NaN > x == y ?# Some people want this to be true for NaNs. > > Then: > > # Compare x and y directly. > log(-5) == log(-2) > # If x == y then exp(x) == exp(y) for all x, y. > exp(log(-5)) == exp(log(-2)) > -5 == -2 > > and now the entire foundations of mathematics collapses into a steaming > pile of rubble. And why doesn't this happen with the current behavior if x = y = log (-5) ? According to the same proof, -5 != -5. George From max at alcyone.com Fri Dec 12 18:45:24 2008 From: max at alcyone.com (Erik Max Francis) Date: Fri, 12 Dec 2008 15:45:24 -0800 Subject: Removing None objects from a sequence In-Reply-To: References: Message-ID: Filip Gruszczy?ski wrote: > I don't mean memory, but space in code ;-) Your goal should be clarity of code, not saving keystrokes. Writing something that is compact in terms of the amount of code to write does not mean its function is clear or even that it is more efficient to run, for that matter. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis God grant me to contend with those that understand me. -- Thomas Fuller From hackingkk at gmail.com Mon Dec 22 13:37:09 2008 From: hackingkk at gmail.com (Krishnakant) Date: Tue, 23 Dec 2008 00:07:09 +0530 Subject: Python's popularity In-Reply-To: References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: <1229971029.6331.31.camel@krishna-laptop> hello hackers. Python is best at high level calculations and as an indication, Please note that I am leading a team on developing an accounting software which will be modular and would suit the economic conditions of developed and almost developed countries like India. I find that number crunching and heavy calculations is shear programming bliss in python. At the front end we are using pygtk and find it very light and zippy. And we are going to use twisted for middle layer and reportlab for reporting. And the development so far is pritty smooth and our programmres who learned python for the first time are just amaised about the fact that how easily python can do a certain thing. So i don't know what others think but python is not just a good scripting language (not that being a good scripting language is some thing bad ) but also a complete enterprise ready language with given frameworks like twisted. happy hacking. Krishnakant. On Mon, 2008-12-22 at 12:59 -0500, Tommy Grav wrote: > On Dec 22, 2008, at 12:48 PM, walterbyrd wrote: > >> Now since Python *is not* the only language on it's block, we have to > >> compete with our main nemesis(Ruby) for survival > > > > I think both python and ruby will "survive." I think python is also > > competing with perl in the sysadmin space - although I see perl as > > being much more popular there. > > Python is making great headway in the physical sciences. Especially > in astronomy Python has become a real player as not only a tool for > quick and dirty calculations, but more serious number crunching using > the great numpy and scipy libraries. With Cython, I, think it will > even start > taking over some of the speed critical niche from C and Fortran. > > Cheers > Tommy > -- > http://mail.python.org/mailman/listinfo/python-list From martin at v.loewis.de Mon Dec 1 18:53:31 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 02 Dec 2008 00:53:31 +0100 Subject: Chmod to a group only In-Reply-To: <83e430f3-0c4c-4aae-84e3-7a8bb6dc1b74@t11g2000yqg.googlegroups.com> References: <83e430f3-0c4c-4aae-84e3-7a8bb6dc1b74@t11g2000yqg.googlegroups.com> Message-ID: <493478fb$0$11318$9b622d9e@news.freenet.de> >> How to chmod a file to: o-rwx ? (to change only the others mode) > I have tried: > > mode = os.stat(fname).st_mode > os.chmod(fname, mode | stat.S_IRWXO) => Changes to o+rwx Close. Try os.chmod(fname, mode & ~stat.S_IRWXO) Regards, Martin From zac256 at gmail.com Thu Dec 4 12:16:52 2008 From: zac256 at gmail.com (Zac Burns) Date: Thu, 4 Dec 2008 09:16:52 -0800 Subject: Overriding a method at the instance level on a subclass of a builtin type In-Reply-To: <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> Message-ID: <333edbe80812040916x7bcd2658h1c95db1959eaaf4a@mail.gmail.com> The class method seems to be the most promising, however I have more 'state' methods to worry about so I might end up building new classes on the fly rather than have a class per permutation of states! Now the code isn't quite as clear as I thought it was going to be. It seems unfortunate to me that methods are always looked up on the class for new style objects. Was this done for speed reasons? -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer (Digital Overlord) Zindagi Games On Thu, Dec 4, 2008 at 2:38 AM, Aaron Brady wrote: > On Dec 3, 1:25 pm, Jason Scheirer wrote: >> On Dec 2, 6:13 pm, Aaron Brady wrote: >> > >>> class A: >> >> > ... def methA( self ): >> > ... print 'methA' >> > ... self.meth= self.methB >> > ... meth= methA >> > ... def methB( self ): >> > ... print 'methB' >> > ...>>> a= A() >> > >>> a.meth() >> > methA >> > >>> a.meth() >> >> > methB >> >> The problem with using this this pattern in the way that you've >> specified is that you have a potential memory leak/object lifetime >> issue. Assigning a bound method of an instance (which itself holds a >> reference to self) to another attribute in that same instance creates >> a kind of circular dependency that I have discovered can trip up the >> GC more often than not. >> >> You can subclass it as easily: >> >> class dictsubclass(dict): >> def __getitem__(self, keyname): >> if not hasattr(self, '_run_once'): >> self.special_code_to_run_once() >> self._run_once = True >> return super(self, dict).__getitem__(keyname) >> >> If that extra ~16 bytes associated with the subclass is really a >> problem: >> >> class dictsubclass(dict): >> def __getitem__(self, keyname): >> self.special_code_to_run_once() >> self.__class__ = dict >> return super(self, dict).__getitem__(keyname) >> >> But I don't think that's a good idea at all. > > Interesting. The following code ran, and process memory usage rose to > 150MB. It failed to return to normal afterward. > >>>> for x in range( 10000000 ): > ... a= [] > ... a.append(a) > ... > > However, the following code succeeded in returning usage to normal. > >>>> import gc >>>> gc.collect() > > It was in version 2.6. So, the GC succeeded in collecting circularly > linked garbage when invoked manually. That might have implications in > the OP's use case. > > In another language, it would work differently, if it lacked unbound > method descriptors. C++ for example, untested: > > class C { > public: > func_t meth; > C( ) { meth= methA; } > void methA( ) { meth= methB; } > void methB( ) { } > }; > > It has no problems with memory consumption (an extra pointer per > object), or circular references; functions are not first-class > objects. However they are in Python, which creates an entire bound > method object per instance. > > The OP stated: > >> run some code and then patch in the original dict >> method for the instance to avoid even the check to see if the init >> code has been run. > > So your, Arnaud's, and Bryan's '.__class__' solution is probably best, > and possibly even truer to the intent of the State Pattern. > > It is too bad that you can't assign an unbound method to the member, > and derive the bound method on the fly. That might provide a middle- > ground solution. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From gh at ghaering.de Wed Dec 3 12:50:17 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 03 Dec 2008 18:50:17 +0100 Subject: python an sqlite objects In-Reply-To: <18742.47391.389709.119341@montanaro-dyndns-org.local> References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <18742.47391.389709.119341@montanaro-dyndns-org.local> Message-ID: skip at pobox.com wrote: > azrael> is it possible to save a python object into a sqlite database as > azrael> an atribute of type BLOB > > Sure. Just pickle the object and save the resulting string. Be sure to save it as BLOB, not TEXT. Suppose you have serialized your object as Python bytestring. serialized = ... ... .execute("insert into mytable(mycolumn) values (?)", (sqlite3.Binary(serialized),)) This way you will get a BLOB in the form of a Python buffer object when you later select it from the database, which you can then deserialize to a Python object. If you don't go the BLOB way, you may get an exception, because SQLite assumes all text is UTF-8 encoded, which it isn't necessarily when you put arbitrary serialized strings into the database. -- Gerhard From steve at REMOVE-THIS-cybersource.com.au Thu Dec 4 17:29:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Dec 2008 22:29:41 GMT Subject: "as" keyword woes References: <7dudnSS7uIn_KarUnZ2dnUVZ_tTinZ2d@earthlink.com> <0147e4df$0$20670$c3e8da3@news.astraweb.com> Message-ID: <01485198$0$20670$c3e8da3@news.astraweb.com> On Thu, 04 Dec 2008 10:44:33 -0600, Chris Mellon wrote: > On Thu, Dec 4, 2008 at 8:45 AM, Steven D'Aprano > wrote: >> On Thu, 04 Dec 2008 20:53:38 +1000, James Mills wrote: >> >>> Readability of your code becomes very important especially if you're >>> working with many developers over time. >>> >>> 1. Use sensible meaningful names. >>> 2. Don't use abbreviations. >> >> This is excellent advice, but remember, what is a sensible meaningful >> name is domain-specific. In a maths library, this would be sensible: >> >> def poly(x): >> return 4*x**3 -2*x**2 +3*x -7 >> >> and this ridiculous: >> >> def poly(real_number): >> return 4*real_number**3 -2*real_number**2 +3*real_number -7 >> >> >> > I actually wonder. The former is "sensible" in a math context because > there's a very long tradition in mathematics of using terse, inscrutable > placeholders for terms. It's only inscrutable to those who don't speak the language, in the same way that those who don't read English would find "The cat sat on the mat" to be inscrutable, or those with no programming experience at all would find: if myList is not None: return [item.method() for item in myList.process()] fairly mystifying. It almost looks like English, but what's with the weird punctuation and non-standard use of capitals? > I'm not a mathematician and I don't know > anything about the history of mathematical notation, but I'd guess this > has something to do with the fact that maths has historically been done > with a pencil and paper, and that terseness is an important quality when > you have a limited canvas and lots of stuff to write. I don't believe "limited canvas" is a major factor, because the availability of paper is only rarely a limiting factor. (However, there have been periods where paper or its equivalent was a rare and precious commodity.) Having lots of stuff to write by hand is a real factor though, especially since in a typical proof each line is very similar to the previous line. > Aside from the cultural indoctrination, though (and that may be a real > and strong force when dealing with math software, and I don't want to > discount it in general, just for purposes of this discussion) why is it > more sensible to use "x" here instead of "number" or "real" or > "real_number" or something else? Because the long names actually distract from the essential semantics of the problem being worked on. Consider my example: return 4*x**3 -2*x**2 +3*x -7 Translated into English, this would mean: Think of a number and call it x, and by convention it is a real number; cube it and multiply by four; subtract two times the square of it; add three times it; subtract 7 Compare this: return 4*real_number**3 -2*real_number**2 +3*real_number -7 As a mathematician, I would read that as: Think of a number and call it real_number; cube it and multiply by four, and don't forget the number needs to be a real number; subtract two times the square of it, and remember the number is a real number; add three times it, and did I mention that it has to be a real number?; subtract 7 Explicit is not *always* better than implicit, and terseness *is* a virtue (up to a point!) which is why we don't do this: Define a function called myFunc which takes one argument called foo. The instructions to be executed when calling myFunc start here: if the value of the argument foo is identical to the value of the keyword None then: change the value of the argument foo to the result returned by the function calc_foo, passing no arguments to it otherwise do nothing ... but prefer the (slightly) terse and (moderately) implicit: def myFunc(foo, bar): if foo is None: foo = calc_foo() ... Thank goodness we don't have to program in verbose, explicit English! In general, most mathematical expressions will involve a small number of variables, and what they represent are obvious from context, at least for those familiar with the problem domain. Those who aren't familiar with the problem domain aren't expected to work on either developing the expression in the first place, or maintaining it, in whatever sense mathematics is expected to be maintained. Although the problem domain naively seems narrow ("huh, who needs to understand complex numbers?") it is actually very abstract and hence can in principle be applied to many different problems. Contrast this with some arbitrary non-mathematical program. It might involve many variables rather than a few, and those variables might be rich objects with many attributes instead of simple numbers. The problem domain is often very concrete: *this* one specific business process, meaningful to only this department of that organisation, or at least to those just like them. Because concrete is more narrow than abstract, and because people who don't understand the problem domain are expected to maintain the software, you can't rely on implicit knowledge: you have to be explicit, and hence verbose, self-explanatory names are a virtue. -- Steven From bearophileHUGS at lycos.com Mon Dec 15 20:09:58 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 15 Dec 2008 17:09:58 -0800 (PST) Subject: Removing None objects from a sequence References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> <4942E668.5030100@tim.thechases.com> <01538f0c$0$6988$c3e8da3@news.astraweb.com> Message-ID: <2f58c57b-a56b-464e-9251-466046bfe840@a37g2000pre.googlegroups.com> Scott David Daniels: > If you want to keep the original's method, but do it in a more Pythonic > way, I would suggest: > > ? ? ?def deNone4(alist): > ? ? ? ? ?j = 0 > ? ? ? ? ?for val in alist: > ? ? ? ? ? ? ?if val is not None: > ? ? ? ? ? ? ? ? ?alist[j] = val > ? ? ? ? ? ? ? ? ?j += 1 > ? ? ? ? ?del alist[j :] For my benchmarks this is also the faster version with and without Psyco :-) (Even it's a bit slow when given a list that has no Nones). Bye, bearophile From castironpi at gmail.com Tue Dec 16 04:21:32 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 16 Dec 2008 01:21:32 -0800 (PST) Subject: alt.possessive.its.has.no.apostrophe References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> <49467CE2.3060401@holdenweb.com> <4946826E.7060001@tim.thechases.com> Message-ID: <989de86c-24cc-4ca6-8e9b-82e8ce853c7b@n33g2000pri.googlegroups.com> On Dec 15, 11:04?am, Steve Holden wrote: > Tim Chase wrote: > > Steve Holden wrote: > >> This led to a schism between the British and the > >> newly-independent Americans, who responded by taking the "u" > >> out of colour, valour, and aluminium. > > > Darn Americans and their alminim.... ;-) > > > Next thing you know, they'll be putting an I in TEAM.[1] > > It's called humour. Or humor. Or incompetence ;-) There's an 'I' in Python. From missive at hotmail.com Sun Dec 28 16:03:45 2008 From: missive at hotmail.com (Lee Harr) Date: Mon, 29 Dec 2008 01:33:45 +0430 Subject: error on windows with commands.getstatusoutput Message-ID: My application is trying to start twistd in a cross-platform way. Unfortunately, it works fine on my linux system, but I do not have windows, and I am trying to debug this remotely on a system I never use :o( Anyhow, here is the error I am getting: cmd = '%s -y %s -l %s' % (conf.twistd, conf.tztac, conf.twistdlog) status, output = commands.getstatusoutput(cmd) Error code: 1 Command: C:/Python25/Scripts/twistd.bat -y tzmud.tac -l var/log/twistd.log Output: '{' is not recognized as an internal or external command, operable program or batch file. Apparently, the Command works fine from the command line. So... Can I run a .bat file on windows with getstatusoutput? Anyone recognize this kind of error? Thanks for any assistance. _________________________________________________________________ Show them the way! Add maps and directions to your party invites. http://www.microsoft.com/windows/windowslive/events.aspx From n.kottiyath at gmail.com Mon Dec 29 11:51:01 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Mon, 29 Dec 2008 08:51:01 -0800 (PST) Subject: Python module import loop issue Message-ID: <02bc8567-695a-4277-9698-a95549a0bc98@w39g2000prb.googlegroups.com> This might not be pure python question. Sorry about that. I couldnt think of any other place to post the same. I am creating a _medium_complex_ application, and I am facing issues with creating the proper module structure. This is my first application and since this is a run-of-the-mill application, I hope someone would be able to help me. Base Module: Contains definitions for Class A1, Class A2 Module 1.1: Class B1 (refines A1) Module 1.2: Class C1 (refines A1) Module 1.3: Class D1 (refines A1) Module 2.1: Class B2 (refines A2): Uses objects of B1, C1, D1 Module 2.2: Class C2 (refines A2) Module 2.3: Class D2 (refines A2) -->Python Entry Module : Module EN<-- Calls objects of B1, C1 and D1 Module EN and also Module 2 creates and calls the objects during run time - and so calls cannot be hardcoded. So, I want to use Factory methods to create everything. Module Factory: import 1.1,1.2,1.3, 2.1,2.2,2.3 A1Factory: {'B1Tag':1.1.B1, 'C1Tag':1.2.C1, 'D1Tag':1.3.D1'} A2Factory: {'B2Tag':2.1.B2, 'C2Tag':2.2.C2, 'D2Tag':2.3.D2'} But, since Module requires objects of B1, C1 etc, it has to import Factory. Module 2.1: import Factory. Now, there is a import loop. How can we avoid this loop? The following ways I could think of 1. Automatic updation of factory inside superclass whenever a subclass is created. But, since there is no object created, I cannot think of a way of doing this. 2. Update A1Factory in each module which implements refinements. _Very_important_, how do I make sure each module is hit - so that the factory is updated? The module EN will be looking only at base module, so the other modules is not hit. I will have to import every module in EN - just to make sure that the A1Factory updation code is hit. This looks in-elegent. If somebody could help me out, I would be very thankful. From prologic at shortcircuit.net.au Mon Dec 29 20:51:18 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 30 Dec 2008 11:51:18 +1000 Subject: get method In-Reply-To: References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> <4819de67-72dc-415c-b4c8-2353581c2bc7@r2g2000vbp.googlegroups.com> Message-ID: On Tue, Dec 30, 2008 at 11:43 AM, James Mills wrote: > On Tue, Dec 30, 2008 at 11:38 AM, Ross wrote: >> I realize the code isn't counting, but how am I to do this without >> using an if statement as the problem instructs? > > I just gave you a hint :) Ross: This exercise is a simple exercise dealing with: * assignments * functions * dictionaries * looping * attributes and methods >>> def histogram(s): ... d = dict() ... for c in s: ... d[c] = d.get(c, 0) + 1 ... return d ... >>> histogram("Hello World!") {'!': 1, ' ': 1, 'e': 1, 'd': 1, 'H': 1, 'l': 3, 'o': 2, 'r': 1, 'W': 1} Note the 3rd line of the function ? 1. Get the value (with a default of 0) of the key c from the dictionary d 2. Add 1 to this value 3. Store in d with key c Hope this helps. cheers James From rt8396 at gmail.com Sat Dec 20 00:30:52 2008 From: rt8396 at gmail.com (r) Date: Fri, 19 Dec 2008 21:30:52 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c4ef2$0$20656$c3e8da3@news.astraweb.com> <2d53cd36-52b0-4a1a-913d-0c545cfadc23@v15g2000vbb.googlegroups.com> Message-ID: <2dc66762-f51e-4bbd-9372-756610d4201e@j11g2000yqg.googlegroups.com> On Dec 19, 10:04?pm, Steve Holden wrote: > r wrote: > > Thanks Steven, > > We need a real Pepsi challenge here to show the insignificance of this > > change. I am not against change. But when we lose something as - > > compact- as %formating i'm going to want to see a damn good reason for > > it! Especially when this breaks code, and the "French Connection" is > > not good enough reason for me :) > > > Christian said this was not going to be depreciated until 3.2, but > > that still puts the accepted way on the chopping block. > > If Python is so important to you it's a pity you haven't been playing > any active role in its development. Do you expect the developers to be > psychic? Steve, I just recently started to have an opinion about these things. "The squeaky wheel get the grease", just allowing my voice be heard. It might seem that i am trashing Python dev, but that could not be further from the truth. Many great changes have been made in 3.0, i just feel strongly about C style formating. Why could't we improve on what we had instead of making radical changes? Thats all i am asking. From enleverlesX.XmcX at XmclaveauX.com Fri Dec 19 15:17:26 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Fri, 19 Dec 2008 21:17:26 +0100 Subject: pymssql for python 2.6 ? In-Reply-To: References: Message-ID: <494c03ac$0$18372$ba4acef3@news.orange.fr> Hi! Look at http://www.mayukhbose.com/python/ado/ado-connection.php That run OK with Python 2.6 @-salutations -- MCI From paul.nospam at rudin.co.uk Thu Dec 11 00:40:45 2008 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Thu, 11 Dec 2008 05:40:45 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: <87r64f9sma.fsf@rudin.co.uk> "Dotan Cohen" writes: > 2008/12/10 : >> On Dec 5, 9:51 am, Xah Lee wrote: >>> >>> For those of you who don't know linear algebra but knows coding, this >>> means, we want a function whose input is a list of 3 elements say >>> {x,y,z}, and output is also a list of 3 elements, say {a,b,c}, with >>> the condition that >>> >>> a = x/Sqrt[x^2+y^2+z^2] >>> b = y/Sqrt[x^2+y^2+z^2] >>> c = z/Sqrt[x^2+y^2+z^2] >> >>> >>> In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, >>> you'll have 50 or hundreds lines. >> >> Ruby: >> >> def norm a >> s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) >> a.map{|x| x/s} >> end > > If someone doesn't counter with a Python one-liner then I'm going to > port that to brainfuck. from numpy.linalg import norm :) From alexoplocatie at gmail.com Wed Dec 17 11:15:37 2008 From: alexoplocatie at gmail.com (aka) Date: Wed, 17 Dec 2008 08:15:37 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> <0d9ea7cc-b5fb-4edb-be32-490aae9e7204@b41g2000pra.googlegroups.com> <0de3a7bf-a4c4-4103-a4e0-44313405fa94@z28g2000prd.googlegroups.com> Message-ID: John, this is the actual code I ran in TurboGears which is a Python framework. I should have left away the import statements. Trust me, the problem isn't in there because the UnicodeWriter is functioning perfectly. I did allready sanitate the csv file to these four lines in Notepad so there isn't anything more than this: id;company;department 12;Cadillac;Research 11;Ford;Accounting 10;Chrysler;Sales The only possible problematic lines are marked ##### here: > > ? ? def import_roles(self, input=None, *args, **kwargs): > > ? ? ? ? inp = 'C:/temp/test.csv' > > ? ? ? ? roles = [] > > ? ? ? ? msg = '' > > ? ? ? ? ## try: > > ? ? ? ? fp = open(inp, 'rb') ##### > > ? ? ? ? reader = csv.reader(fp, dialect='excel', delimiter=';') ##### > > ? ? ? ? ## reader = UnicodeReader(fp, dialect='excel', delimiter=';') ##### > > ? ? ? ? for r in reader: > > ? ? ? ? ? ? roles.append(r[0]) ##### > > ? ? ? ? fp.close() > > ? ? ? ? ## except: > > ? ? ? ? ? ? ## msg = "Something's wrong with the csv.reader" > > ? ? ? ? return dict(filepath=inp, > > ? ? ? ? ? ? ? ? ? ? roles=str(roles), > > ? ? ? ? ? ? ? ? ? ? msg=msg) Yeah rdmur, I'll have a look at the Python commandline. From jerry.carl.mi at gmail.com Sun Dec 28 11:41:22 2008 From: jerry.carl.mi at gmail.com (jerry.carl.mi at gmail.com) Date: Sun, 28 Dec 2008 08:41:22 -0800 (PST) Subject: math module for Decimals References: <41937dc9-4b67-43b5-9eab-6f8c851474cf@p2g2000prn.googlegroups.com> <0896c2d8-78ff-489e-801d-abef957601d0@s9g2000prg.googlegroups.com> Message-ID: <59c08a51-da39-467b-9576-fa0cc1db3207@i18g2000prf.googlegroups.com> > 1. mpmath? > 2. sympy? > 3. Sage? Haven't tried those, i guess i have some studying to do. > > > x=Decimal.__mod__(x,Decimal('2')*pi()) > > > Works fine for what i need, but i am sure it's not the right way to do > > it. > > I don't know of any better way to deal with large arguments. > The main problem is that the reduction step can introduce fairly > large errors: ?for example, if you're using a value of pi > that's accurate to 10**-20, say, then reducing something of > magnitude 10**5*pi will give a result with error of around > 10**-15. ?As far as I know, this problem is essentially > unavoidable, and it's the reason why implementing sin for inputs > like 10**999999999 isn't feasible. Good point. No tool will work in all parts of the universe (which is especially true for the universal ski wax). Let me check the 3 modules you listed above! From robert.kern at gmail.com Mon Dec 8 17:51:38 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 08 Dec 2008 16:51:38 -0600 Subject: Text parsing via regex In-Reply-To: References: Message-ID: Robocop wrote: > Wow! Thanks for all the input, it looks like that textwrapper will > work great for my needs. And thanks for the regex help everyone. > Also, i was thinking of using a list, but i haven't used them much in > python. Is there anything in python that is equivalent to pushback in > c++ for vectors? list.append() -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From aisaac at american.edu Thu Dec 4 14:42:04 2008 From: aisaac at american.edu (Alan G Isaac) Date: Thu, 04 Dec 2008 14:42:04 -0500 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> Message-ID: Mark Summerfield wrote: > "Programming in Python 3: > A Complete Introduction to the Python Language" > ISBN 0137129297 > http://www.qtrac.eu/py3book.html OMG, you really wrote it in Lout? I wish you would add to http://www.qtrac.eu/lout.html a comment on what you get out of that (compared to using e.g., LaTeX or reStructuredText). Anyway, congrats on the book! I've asked my library to order it. Alan Isaac From jstroud at mbi.ucla.edu Sun Dec 14 03:00:03 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 14 Dec 2008 00:00:03 -0800 Subject: Optimizing methods away or not? In-Reply-To: <0154b041$0$6988$c3e8da3@news.astraweb.com> References: <0154b041$0$6988$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > class Parrot: > def __init__(self, *args): > print "Initialising instance..." > if __debug__: > self.verify() # check internal program state, not args > if __debug__: > def verify(self): > print "Verifying..." +1 It looks good to me and the intent is much clearer than the other. From fetchinson at googlemail.com Sat Dec 27 19:54:52 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 27 Dec 2008 16:54:52 -0800 Subject: C API: array of floats/ints from python to C and back In-Reply-To: References: Message-ID: On 12/27/08, Robert Kern wrote: > Daniel Fetchinson wrote: > >> I agree that array.array is more efficient than a list but the input >> for my function will come from PIL and PIL returns a list. So I have a >> list to begin with which will be passed to the C function. > > With recent versions of PIL, numpy can create an array from an Image very > quickly, possibly without any copying of memory. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it > had > an underlying truth." > -- Umberto Eco > > -- > http://mail.python.org/mailman/listinfo/python-list > Hi Robert, now that we are at it let me ask something related. Now I managed to get my lists to C, operate on them in C and convert the result back to a python tuple. Since this is my first C program that uses the python C API I'm sure there are refcounting issues that I'm not considering, maybe also memory management too. This is the function I have, the corresponding python function will take two equal length lists of integers and the C function will compute their sum and return the result as a python tuple. static PyObject *func( PyObject * self, PyObject * args ) { int j, N; int * src1, * src2; PyObject *list1, *list2; list1 = PyTuple_GetItem( args, 0 ); N = PyList_Size( list1 ); src1 = ( int * ) malloc( N * sizeof( int ) ); for( j = 0; j < N; j++ ) { src1[j] = (int)PyInt_AsLong( PyList_GetItem( list1, j ) ); } list2 = PyTuple_GetItem( args, 1 ); N = PyList_Size( list2 ); src2 = ( int * ) malloc( N * sizeof( int ) ); for( j = 0; j < N; j++ ) { src2[j] = (int)PyInt_AsLong( PyList_GetItem( list2, j ) ); } PyObject * tuple; tuple = PyTuple_New( N ); for( j = 0; j < N; j++ ) { PyTuple_SetItem( tuple, j, PyInt_FromLong( (long)( src1[j] + src2[j] ) ) ); } free( src1 ); free( src2 ); return tuple; } Do I have to free the memory occupied by the python objects list1 and list2? Do I have to do any refcounting for list1, list2, tuple? Any comment on the above code will be very appreciated! If I'm pushed in the right direction I'm a fast learner but the beginning steps are always hard :) Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From jura.grozni at gmail.com Wed Dec 3 14:11:19 2008 From: jura.grozni at gmail.com (azrael) Date: Wed, 3 Dec 2008 11:11:19 -0800 (PST) Subject: python an sqlite objects References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <18742.47391.389709.119341@montanaro-dyndns-org.local> Message-ID: It logical that it would be more efficient and logical to use a object oriented database, but in this case I ask because of the portable nature of sqlite. so, if I get it right, this should be possible >>> class a: >>> def __init__(self, a, b): >>> self.c = a+b >>> self.d = a*b >>> >>> ob = a(1,3) >>> oc = a(2,4) >>> dbCursor.execute("insert into tabel example values (?,?)",[ob, oc]) #table example consists of blob atributes >>> dbcursor.commit() >>> dbCursor.execute("select * from table example") >>> list = dbcursor.fetchall() >>> for i in list: >>> print i.c, i.d >>> 4 3 6 6 From vlastimil.brom at gmail.com Mon Dec 1 16:09:33 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Mon, 1 Dec 2008 22:09:33 +0100 Subject: newbie question: parse a variable inside an RE? In-Reply-To: References: Message-ID: <9fdb569a0812011309k4e6beb68kda99f479b7e5012b@mail.gmail.com> 2008/12/1 > Hi All, > > How do I parse a variable inside an RE? > What is the re.search() syntax when your > search string is a variable? > It's easy to parse hardcoded RE's but not > if you use a variable. > > Here is my code, input and runtime: > > $ cat test45.py > #!/usr/bin/python > > import re > > resp = raw_input('Selection: ') > newresp = resp.strip() > print "you chose ", newresp > > fname = open('test44.in') > for I in fname: > # if re.search('^newresp', "%s"%(I)): # returns nothing > # if re.search(^newresp, "%s"%(I)): # syntax error > if re.search("^newresp", "%s"%(I)): # returns nothing > print I, > > [jmccaughan at dhcppc2 work]$ cat test44.in > a1 > b1 > g1 > g2 > h1 > h4 > 4g > 5g > h5 > > $ python test45.py > Selection: g > you chose g > $ > > Thanks... > -- > http://mail.python.org/mailman/listinfo/python-list > It doesn't seem very robust, but it can be made work, try e.g.: for item in fname: if re.search("^"+newresp, "%s" % (item,)): print item, (prints: g1 g2 in a similar code) (if you know, that item is a string, the %s interpolation is not needed; you can also use re match, without hte need for "^" . hth vbr -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Fri Dec 12 14:20:52 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 12 Dec 2008 11:20:52 -0800 (PST) Subject: (Very Newbie) Problems defining a variable References: <878wqlz27z.fsf@daycos.com> Message-ID: <7f7e8811-4043-40d4-8aa4-f44e1d255632@o4g2000pra.googlegroups.com> On Dec 13, 5:18?am, Kirk Strauser wrote: > At 2008-12-12T18:12:39Z, "Tim Rowe" writes: > > > > > Is there a tidy way of making rates and thresholds local to get_rate, > > without recalculating each time? I suppose going object oriented is > > the proper way. > > > #Py3k,UTF-8 > > > rates = {0: 0.006, 10000: 0.0085, 25000: 0.0124, 50000: 0.0149, 100000: 0.0173} > > thresholds = list(rates.keys()) > > thresholds.sort() > > thresholds.reverse() > > > def get_rate(balance): > > ? ? for threshold in thresholds: > > ? ? ? ? if balance >= threshold: > > ? ? ? ? ? ? return rates[threshold] > > ? ? else: > > ? ? ? ? return 0.0 > > How 'bout: > > def get_rate(balance): > ? ? for threshold, rate in ((100000, .0173), > ? ? ? ? ? ? ? ? ? ? ? ? ? ? (50000, .0149), > ? ? ? ? ? ? ? ? ? ? ? ? ? ? (25000, .0124), > ? ? ? ? ? ? ? ? ? ? ? ? ? ? (10000, .0085), > ? ? ? ? ? ? ? ? ? ? ? ? ? ? (0, .006)): > ? ? ? ? if balance > threshold: > ? ? ? ? ? ? return rate > ? ? return .0 (1) you meant "if balance > threshold:" (2) sequential search can be very fast if the sequence is in descending order of probability of occurence ... you might like to consider reversing the order (3) for a much longer table, binary search using a function from the bisect module could be considered (4) in practice, the "default" action would not be "return 0.0"; perhaps something along these lines: if balance < -overdraft_limit: raise Exception(...) return HUGE From sturlamolden at yahoo.no Fri Dec 12 08:29:15 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 05:29:15 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> Message-ID: <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> On Dec 11, 4:25 am, Carl Banks wrote: > cm_gui is TROLL. And I am not compring it with bots like Aaron > Castironpi Brody. cm_gui is even troller than Xah Lee! Sure he is a troll, but he also have a point. Python is slower than it needs to be. Creating a fast implementation of a dynamic language is almost rocket science. But it has been done. There is Stronghold, the fastest version of Smalltalk known to man, on which the Sun Java VM is based. On a recent benchmark Java 6 -server beats C compiled by GCC 4.2.3 And most of that magic comes from an implementation of a dynamically typed language (Smalltalk). A Python interpreter based on Strontalk would be interesting... http://shootout.alioth.debian.org/u32q/benchmark.php?test=all&lang=all Second, there are other fast implementations of dynamic languages. The CMUCL and SBCL versions of Common Lisp comes to min; you can see how SBCL does in the same benchmark (CMUCL tends to be even faster). So Python is a lot slower than it needs to be. But in most cases, perceived 'slowness' comes from bad programming. http://www.strongtalk.org/ From gnewsg at gmail.com Wed Dec 31 15:26:04 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Wed, 31 Dec 2008 12:26:04 -0800 (PST) Subject: Why not Ruby? References: Message-ID: On 31 Dic, 18:55, Xah Lee wrote: > Just spent 3 hours looking into Ruby today. Here's my short impression > for those interested. > > * Why Not Ruby? > http://xahlee.org/UnixResource_dir/writ/why_not_Ruby.html > > plain text version follows: > -------------------------------------- > > Why Not Ruby? > > Xah Lee, 2008-12-31 > > Spent about 3 hours looking into Ruby language today. > > The articles i read in detail are: > > * Wikipedia: Ruby (programming language)?J. Gives general overview. > > * Brief tutorial: "Ruby in Twenty Minutes"http://www.ruby-lang.org/en/documentation/quickstart/ > > * Personal blog by Stevey Yegge, published in 2004-10.http://steve.yegge.googlepages.com/ruby-tour > > The Wikipedia gives the best intro and overview in proper context. The > "Ruby in Twenty Minutes" is just 4 pages. It give you a very concrete > intro to Ruby's syntax and semantics. Stevey Yegge's blog doesn't > teach much and rambles, but provide a little personal view. I read it > because his opinions i respect. > > Q: Will you learn Ruby? > > No. For practical application, the lang is some 100 times less useful > than each of Perl, Python, PHP, Javascript. For academic study, > functional langs like Mathematica, Haskell, OCaml, erlang, Qz, are far > more interesting and powerful in almost all aspects. Further, there's > also Perl6, NewLisp, Clojure, Scala... With respect to elegance or > power, these modern lang of the past 5 years matches or exceed Ruby. > > Q: Do you think Ruby lang is elegant? > > Yes. In my opinion, better than Perl, Python, PHP. As a high level > lang, it's far better than Java, C, C++ type of shit. However, i don't > think it is any better than emacs lisp, Scheme lisp, javascript, > Mathematica. Note that Ruby doesn't have a spec, and nor a formal > spec. Javascript has. Ruby's syntax isn't that regular, nor is it > based on a system. Mathemtica's is. Ruby's power is probably less than > Scheme, and probably same as Javascript. > > I also didn't like the fact that ruby uses keyword "end" to indicate > code block much as Pascal and Visual Basic, Logo, do. I don't like > that. > > Q: Won't Ruby be a interesting learning experience? > > No. As far as semantics goes, Ruby is basically identical to Perl, > Python, PHP. I am a expert in Perl and PHP, and have working knowledge > of Python. I already regretted having spent significant amount of time > (roughly over a year) on Python. In retrospect, i didn't consider the > time invested in Python worthwhile. (as it turns out, i don't like > Python and Guido cult, as the lang is going the ways of OOP mumbo- > jumbo with its Python 3 "brand new" future.) There is absolutely > nothing new in Ruby, as compared to Perl, Python, PHP, or Emacs lisp, > Scheme lisp. > > Q: Do you recommend new programers to learn Ruby then? > > Not particularly. As i mentioned, if you are interested in practical > utility, there's already Perl, PHP, Python, Javascript, which are all > heavily used in the computing industry. If you are interested as a > academic exercise, there's Scheme lisp, and much of functional langs > such as OCaml, Haskell, Mathematica, which will teach you a whole lot > more about computer science, features of language semantics, etc. > > Q: Do you condemn Ruby? > > No. I think it's reasonably elegant, but today there are too many > languages, so Ruby don't particularly standout for me. Many of them, > are arguably quite more elegant and powerful than Ruby. See: > Proliferation of Computing Languages. This is not a Ruby group. I recommend you to go waste your time there. --- Giampaolo http://code.google.com/p/pyftpdlib From python.list at tim.thechases.com Mon Dec 15 08:29:54 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 15 Dec 2008 07:29:54 -0600 Subject: Having Issues with CMD and the 'python' command In-Reply-To: References: Message-ID: <49465BD2.5010409@tim.thechases.com> James Mills wrote: > "cmd" has _nothing_ to do with Python. well, not quite "nothing"... http://docs.python.org/lib/module-cmd.html [grins, ducks and runs] (every time I see this module it makes me want to go write a small interactive-fiction game in the style of Zork/Adventure :) -tkc From steve at REMOVE-THIS-cybersource.com.au Tue Dec 30 03:52:05 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Dec 2008 08:52:05 GMT Subject: How do I DRY the following code? References: Message-ID: <0169d83a$0$6988$c3e8da3@news.astraweb.com> On Mon, 29 Dec 2008 21:13:55 -0500, R. Bernstein wrote: > How do I DRY the following code? > > class C(): [snip code] Move the common stuff into methods (or possibly external functions). If you really need to, make them private by appending an underscore to the front of the name. class C(): def common1(self, *args): return "common1" def common2(self, *args): return "common2" def _more(self, *args): # Private, don't touch! return "more stuff" def f1(self, arg1, arg2=None, globals=None, locals=None): ... unique stuff #1 ... self.common1() ret = eval(args, globals, locals) self._more() return retval def f2(self, arg1, arg2=None, *args, **kwds): ... unique stuff #2 ... self.common1() ret = arg1(args, *args, **kwds) self.common2 return retval def f3(self, arg1, globals=None, locals=None): ... unique stuff #3 ... self.common1() exec cmd in globals, locals self.common2() return None # unneeded def f4(self, arg1, globals=None, locals=None): ... unique stuff #4 ... self.common1() execfile(args, globals, locals) self._more() An explicit "return None" is probably not needed. Python functions and methods automatically return None if they reach the end of the function. > Above there are two kinds of duplication: that within class C and that > outside which creates an instance of the class C and calls the > corresponding method. Do you really need them? If so, you're repeating yourself by definition. That's not necessarily a problem, the stand-alone functions are just wrappers of methods. You can decrease (but not eliminate) the amount of repeated code with a factory function: def build_standalone(methodname, docstring=None): def function(arg, arg2=None, globals=None, locals=None): c = C() return c.getattr(methodname)(arg, arg2, globals, locals) function.__name__ = methodname function.__doc__ = docstring return function f1 = build_standalone('f1', "Docstring f1") f2 = build_standalone('f2', "Docstring f2") f3 = build_standalone('f3', "Docstring f3") There's no way to avoid the repeated f1 etc. But honestly, with only three such functions, I'd consider that overkill. > Lest the above be too abstract, those who want to look at the full > (and redundant) code: > > http://code.google.com/p/pydbg/source/browse/trunk/api/pydbg/api/ debugger.py You have parameters called Globals and Locals. It's the usual Python convention that names starting with a leading uppercase letter is a class. To avoid shadowing the built-ins, it would be more conventional to write them as globals_ and locals_. You may or may not care about following the convention :) I notice you have code like the following: if Globals is None: import __main__ Globals = __main__.__dict__ I would have written that like: if Globals is None: Globals = globals() or even if Globals is None: from __main__ import __dict__ as Globals You also have at least one unnecessary pass statement: if not isinstance(expr, types.CodeType): expr = expr+'\n' pass The pass isn't needed. In your runcall() method, you say: res = None self.start(start_opts) try: res = func(*args, **kwds) except DebuggerQuit: pass finally: self.stop() return res This is probably better written as: self.start(start_opts) try: return func(*args, **kwds) except DebuggerQuit: return None finally: self.stop() -- Steven From bearophileHUGS at lycos.com Sat Dec 6 11:42:28 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 6 Dec 2008 08:42:28 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> <8b8d1fb3-f49e-49bf-8cfe-eeee5ed16109@r37g2000prr.googlegroups.com> <014a932b$0$20670$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano: > If a line of code uses too many instance attributes to fit comfortably on > a line, spread it over two lines. There is no newline shortage, they are > a renewable resource. Splitting lines is generally possible, but sometimes it's not I want, for example to keep a formula whole. And splitting lines increases line count. Increasing line count may reduce the amount of code you can see in a screenshot, and this may decrease a little the programmer's ability to understand code. (I am not suggesting to cram everything into one or few lines, like in K language: regarding code size there's an optimal middle point between K/APL and Ada/certain Java. Still, typing "self." very often requires time, and even if you are lucky to have an IDE that helps you write that faster, the code uses lot of space anyway). That's why I say that the following code, while looking a little ugly, may be a little "better" anyway (and maybe even more readable): class ThisIsAClass: def $some_method(arg1, arg2): $value = arg1 + $foo + $bar + $baz * arg2 ... Than the current syntax: class ThisIsAClass: def some_method(self, arg1, arg2): self.value = arg1 + self.foo + self.bar + self.baz * arg2 ... Bye, bearophile From floris.bruynooghe at gmail.com Thu Dec 18 09:41:40 2008 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Thu, 18 Dec 2008 06:41:40 -0800 (PST) Subject: C API and memory allocation References: <4949f109$0$31329$9b4e6d93@newsspool4.arcor-online.net> Message-ID: On Dec 18, 6:43?am, Stefan Behnel wrote: > Floris Bruynooghe wrote: > > I'm slightly confused about some memory allocations in the C API. > > If you want to reduce the number of things you have to get your head > around, learn Cython instead of the raw C-API. It's basically Python, does > all the reference counting for you and also reduces the amount of memory > handling you have to care about. > > http://cython.org/ Sure that is a good choice in some cases. Not in my case currently though, it would mean another build dependency on all our build hosts and I'm just (trying to) stop an existing extension module from leaking memory, no way I'm going to re-write that from scratch. But interesting discussion though, thanks! Floris From gdamjan at gmail.com Tue Dec 16 19:13:48 2008 From: gdamjan at gmail.com (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Wed, 17 Dec 2008 01:13:48 +0100 Subject: ethical questions about global variables References: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> <0d9a9758-f338-4a58-971a-1bd29e40ce32@v5g2000prm.googlegroups.com> Message-ID: > By "per-class-instance variables", you are talking > about instance attributes? I.e. "self.use_gmt_times"? > I don't see much difference between global variables > and instance attributes. using global variable in modules makes the module not Thread-safe Using a instance attribute allows more threads to each have a separate instance with it's own config. -- ?????? ( http://softver.org.mk/damjan/ ) Today we create the legacy of tomorrow. From david at abbottdavid.com Sun Dec 7 10:04:35 2008 From: david at abbottdavid.com (David) Date: Sun, 07 Dec 2008 10:04:35 -0500 Subject: python book for non technical absolute beginner In-Reply-To: References: <493a7c6a$0$973$426a34cc@news.free.fr> Message-ID: <493BE603.1020600@abbottdavid.com> I like this one: http://www.freenetpages.co.uk/hp/alan.gauld/ -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From rt8396 at gmail.com Sat Dec 20 20:54:09 2008 From: rt8396 at gmail.com (r) Date: Sat, 20 Dec 2008 17:54:09 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: On Dec 20, 7:38?pm, Steven D'Aprano wrote: > On Sat, 20 Dec 2008 16:20:38 -0800, r wrote: > > On Dec 20, 6:05?pm, Roy Smith wrote: > >> I had an interesting experience with this recently. ?I was giving a > >> co-worker quick python into. ?He's an experienced programer in various > >> languages, but this was his first exposure to python. > > >> He got really hung up on the % syntax. ?By (bad) luck, he was trying to > >> print a tuple (let's call it "t"), did > > >> format % t > > >> and was surprised at the result. ?It set him off on a "but that's > >> stupid, blah, blah, blah" rant. ?I haven't absorbed the new syntax well > >> enough to figure out if people will get hung up by this with the new > >> syntax. > > > It is stupid, more reason to fix the current problem instead creating a > > whole new one. > > Instead of just whinging, how about making a suggestion to fix it? Go on, > sit down for an hour or ten and try to work out how a BINARY OPERATOR > like % (that means it can only take TWO arguments) can deal with an > arbitrary number of arguments, *without* having any special cases. > > Go on. Take your time. I'll be waiting. > > > One more big complaint "THE BACKSLASH PLAGUE". ever tried regexp?, or > > file paths?. All because that little backslash char is a line > > continuation character, maybe we should fix that. > > This makes no sense whatsoever. How does the line continuation character > make any difference to backslashes inside a regex or a file path? > > Again, instead of whinging, what's your suggestion to fix it? Another > suggestion, because your first: > > > Would your life end if '\' was not a continuation char? > > is just stupid. The line continuation character is *irrelevant* to the > problem of backslashes inside strings. For all the use it is, you might > as well suggest changing the name None to Null. > > -- > Steven i prefer None over Null myself, just another Pythonic beauty! ;) Steven, Would you like to elaborate on -why- escaped backslashes are needed in strings... i waiting??? From mail at microcorp.co.za Tue Dec 23 03:33:26 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 23 Dec 2008 10:33:26 +0200 Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com><6ra8t0F925rU1@mid.individual.net><29feda0d-6432-4cb9-8809-e4d4a7798601@e1g2000pra.googlegroups.com><6raeb8F9s47U2@mid.individual.net><25b1ece0-712b-4516-af28-88c50d00ab8c@s9g2000prg.googlegroups.com> Message-ID: <01e501c964e9$d10fc900$0d00a8c0@hendrik> "r" wrote: >Now thats the kind of friendly banter this group could use. Instead of >people acting as if their bowel-movements smell like bakery fresh >cinnamon rolls! What an amazing thing to say! Doesn't yours? - Hendrik From tjreedy at udel.edu Sat Dec 6 15:16:47 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 06 Dec 2008 15:16:47 -0500 Subject: python book for non technical absolute beginner In-Reply-To: <493a7c6a$0$973$426a34cc@news.free.fr> References: <493a7c6a$0$973$426a34cc@news.free.fr> Message-ID: News123 wrote: > One of my 'non technical' friends complained about knowing nothing at > all about programming (though using computers regularly for mails / web > browsing / googling and downloading / cropping photos ) > > He wants to play a little with programming to stimulate parts of his > otehrwise idle brain cells. ;-) Normally it's more the social science / > linguistic parts being exercised, > > I thought python might be a nice language for this > > No my question does anybody know a nice beginners book (or a learning CD > or on line tutorial)? Ideally it shouldn't be too serious and have a lot > of small nice mini-examples > > thanks in advance for any suggestions hints I started with the 1.3 version of http://docs.python.org/tutorial/index.html (but had lots of previous experience). From sjmachin at lexicon.net Thu Dec 25 20:03:01 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 25 Dec 2008 17:03:01 -0800 (PST) Subject: Is there a function to remove escape characters from a string ? References: <0163882f$0$6988$c3e8da3@news.astraweb.com> Message-ID: On Dec 26, 8:53?am, Stef Mientki wrote: > Steven D'Aprano wrote: > > On Thu, 25 Dec 2008 11:00:18 +0100, Stef Mientki wrote: > > >> hello, > > >> Is there a function to remove escape characters from a string ? > >> (preferable all escape characters except "\n"). > > > Can you explain what you mean? I can think of at least four alternatives: > > I have the following kind of strings, > the funny "?" is ASCII character 254, used as a separator character ASCII ends at 127. Just refer to it as chr(254). > > [FSM] > Counts = "1?11?16" ? ? ==> ? 1,11,16 > Init1 = "1?\BCtrl" ? ? ==> ? ?1,Ctrl > State5 = "8?\BJUMP_COMPL\b\n>PCWrite = 1\n>PCSource = 10" > ? ? ? ? ?==> 8, JUMP_COMPL\n>PCWrite = 1\n>PCSource = 10 After making those substitutions, what are you going to do with it? Split it up into fields using the csv module or stuff.split(",") or some other DIY method? Is there a possibility that whoever "designed" that data format used chr(254) as a separator because the data fields contained "," sometimes and so "," could not be used as a separator? > Seeing and testing all your answers, with great solutions that I've > never seen before, As far as str methods and built-ins that work on str objects are concerned, there is no corpus of secret knowledge known only to a cabal of wizards; it's all in the manual, and you don't need special magical spectacles to see it :-) > knowing nothing of escape sequences (I'm a windows guy ;-) Why do you think that whether or not you are a "windows guy" is relevant to knowing anything about escape sequences? > I now see that the characters I need to remove, like ?\B ?and \b ?are > not "official" escape sequences. \b *is* an "official" escape sequence, just like \n; see below: | >>> x = '\b'; print len(x), repr(x) | 1 '\x08' | >>> x = r'\b'; print len(x), repr(x) | 2 '\\b' | >>> x = '\B'; print len(x), repr(x) | 2 '\\B' | >>> x = r'\B'; print len(x), repr(x) | 2 '\\B' > So in this case the best (easiest to understand) method is a few replace > statements: > s = s.replace ( '\b', '' ).replace( '\B', ?'' ) It's probable that \b and \B are both TWO-byte sequences, in which case you should use r'\b' so that it does what you want it to do, and use r'\B' for consistency. From john.eriksson at logica.com Tue Dec 2 08:43:51 2008 From: john.eriksson at logica.com (Eriksson, John) Date: Tue, 2 Dec 2008 14:43:51 +0100 Subject: How to sort a list of file paths In-Reply-To: <47c890dc0812020126p5e8ff750x91ff58e9fabd7d32@mail.gmail.com> References: <2F0A3D19CA15C143B0688EC94220748720D1F89A61@SE-EX007.groupinfra.com> <47c890dc0812020126p5e8ff750x91ff58e9fabd7d32@mail.gmail.com> Message-ID: <2F0A3D19CA15C143B0688EC94220748720D1FF9480@SE-EX007.groupinfra.com> Hi again, I've updated the example using the ideas and python tricks used on pages found via the link you gave me, Chris. So... for future references here's the best (?) way of sorting a list of file names in the correct way (correct for some applications at least). Note: For some odd reason I seemed to get the best performance using a lambda defined function instead of an ordinary function. # --- EXAMPLE --- import re RE_DIGIT = re.compile(r'(\d+)') ALPHANUM_KEY = lambda s: [int(g) if g.isdigit() else g for g in RE_DIGIT.split(s)] file_list = ["File2.txt","File1.txt","File10.txt"] file_list.sort(key=ALPHANUM_KEY) # --------------- Best Regards /John -----Original Message----- From: cvrebert at gmail.com [mailto:cvrebert at gmail.com] On Behalf Of Chris Rebert Sent: den 2 december 2008 10:26 To: Eriksson, John Cc: python-list at python.org Subject: Re: How to sort a list of file paths On Tue, Dec 2, 2008 at 12:36 AM, Eriksson, John wrote: > Hi, > > > > This weekend I had some problems to get a list containing file paths to be > sorted in a way that I could use. > > > > I also found a thread in this mailing list ( > http://mail.python.org/pipermail/python-list/2007-April/433590.html ) and > realized that others might be interested in a solution. > > > > So... here is my five cents regarding file path sorting: > > > > Problem description: > > > > You have a list containing some file names: > > > >>>> file_list = ["File2.txt","File1.txt","File10.txt"] > > > > If you sort this list in the conventional way you end up with a result like: > > > >>>> file_list.sort() > >>>> print file_list > > ['File1.txt','File10.txt','File2.txt'] > > > > Solution: > > > > Sort the list by splitting alphas and digits in to groups and compare them > separately. > > > > import re > > def true_alphanum_cmp(a,b): > > aa = re.findall(r'\d |\D ', a) > > bb = re.findall(r'\d |\D ', b) > > for i in range(min(len(aa),len(bb))): > > if aa[i].isdigit() and bb[i].isdigit(): > > c = cmp(int(aa[i]),int(bb[i])) > > else: > > c = cmp(aa[i],bb[i]) > > if c!=0: > > return c > > return cmp(len(aa),len(bb)) > > > > file_list = ["File2.txt","File1.txt","File10.txt"] > > file_list.sort(true_alphanum_cmp) > > > > If the formatting in this mail is messed up you can find the example at > http://arainyday.se/notebook/true_alphanum_cmp.php > > > > All comments and improvements are welcome! Sounds like the issue discussed in the post on Coding Horror: http://www.codinghorror.com/blog/archives/001018.html It even links to another Python version of the algorithm. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > > > Best regards > > John Eriksson > > _________________________________________ > > > > Logica - Releasing your potential > > Tegsplan 2b > > 904 20 UME? > > Sweden > > > > T: +46 (0) 90 15 91 38 > > M: +46 (0) 70 366 16 77 > > E: john.eriksson at logica.com > > www.logica.se > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > From Slaunger at gmail.com Mon Dec 1 09:37:35 2008 From: Slaunger at gmail.com (Slaunger) Date: Mon, 1 Dec 2008 06:37:35 -0800 (PST) Subject: Emacs vs. Eclipse vs. Vim References: Message-ID: <27b16b50-57a9-4061-989c-17e02e56ab49@g38g2000yqn.googlegroups.com> On 29 Nov., 21:44, Josh wrote: > If you were a beginning programmer and willing to make an investment in > steep learning curve for best returns down the road, which would you pick? > > I know this topic has been smashed around a bit already, but 'learning > curve' always seems to be an arguement. If you feel that one is easier > or harder than the others to learn feel free to tell, but let's not make > that the deciding factor. Which one will be most empowering down the > road as a development tool? > > Thanks in advance, > > JR Many have written that they have no experience with using Eclipse. Well, I have a little, and I just want to add my experience. I am a novice Python programmer and I use Eclipse with the PyDev and SubClipse extensions which gives me a Python environment and integration with Subversion, which is the version control system I use. My OS is Windows XP and Server 2003. Other people are working on the same project using either eclipse on a linux box or another editor of choice. Eclipse works very well for me. The facilities I like are: * A handy object browser which lets be jump into the part of the code I am interested in (I work with several, quite large modules). * Autocompletion: When I write . it gives me a suggestion of the methods/attributes available and the doc string (if available) is shown as a tool tip. It can autogenerate a generic signature for a method call with the attribute names prefilled. Very handy as I quite often forget the order of arguments. * Unit tests: It is quite convenient to write and run unit tests in the environment (unittest run targets) * Refactoring: Intelligent rename for instance is handy for renaming methods and attributes across modules * Debugger: I debugger environment which works well for me with watchlists, step-into, step over. * Chroma-coded * Auto-indentation * Macros for block commenting, indenting and unindenting. * Nice integrated diff toll which integrates well with subversion. * And tons of other things which I have not explored yet. Like a coverage run target for instance. * Some Syntax checking I am personally satisfied with the startup time and overall responsiveness of Eclipse, but users of Emacs/Vim may have other bars for responsiveness than me. Sometimes I experience some problems with cascading inexplicable errors ocurring in the IDE when running unit test suites. This is annoying and they do not occur when I run the tests stand- alone outside on the command line. This IDE works well for me. I do not have an opinion about how it works in comparison with Emacs and Vim, just wanted to give my opinion on Eclipse and Python as this had not been discussed so much. On the prestige level it is certainly not considered as "cool" to use Eclipse as Emacs/Vim where I am working. I often hear the opinion that you are not a proper coder/hacker is you do not master any of these classic editors. I also think it depends much upon your coding style. Personally I spend much more time thinking on "how" to implement this-and-that, than actually coding. That may reflect that I am still a novice Python Programmer. -- Slaunger From ershov.a_n at mail.ru Tue Dec 2 14:47:07 2008 From: ershov.a_n at mail.ru (burb) Date: Tue, 2 Dec 2008 11:47:07 -0800 (PST) Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> <24f0dc02-9461-4b93-a2f8-a56fa5919ffc@n10g2000yqm.googlegroups.com> Message-ID: <2839c097-7d7d-42a7-a458-287442452983@v4g2000yqa.googlegroups.com> use UNIX "mail" command: crontab will send letters to you and you can look at traceback there. From wuwei23 at gmail.com Mon Dec 8 03:31:56 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 8 Dec 2008 00:31:56 -0800 (PST) Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? References: <5ccd4a18-cd2b-4040-90c6-33723af15e96@b38g2000prf.googlegroups.com> Message-ID: <7e1a9226-c7a9-4b5e-bfbb-ea079639d6a2@t39g2000prh.googlegroups.com> On Dec 8, 2:26?pm, illume wrote: > pygame is simpler to learn, since it doesn't require you to know how > to create classes or functions. I'm not sure if I'd be quick to tout that as an advantage... :) From svalbardcolaco at gmail.com Fri Dec 5 01:36:17 2008 From: svalbardcolaco at gmail.com (svalbard colaco) Date: Fri, 5 Dec 2008 12:06:17 +0530 Subject: CONNECTION TIMED OUT ERROR using urllib2 In-Reply-To: <180b672e0812042227j12a4d647k84e507dfae77d665@mail.gmail.com> References: <726d283d0812042217w41a0288eg3ee79d4ffdb5ff4b@mail.gmail.com> <180b672e0812042227j12a4d647k84e507dfae77d665@mail.gmail.com> Message-ID: <726d283d0812042236j792f4706v373ca6449861e3e2@mail.gmail.com> Hi rishi, Thanks for ur reply, yes i set the following enviroment variables (FC6 platform) http_proxy,http_user,http_password But i get the same error; Can u tell me which other variables i need to set or am i going wrong in the syntax of these variables? Regards sv On Fri, Dec 5, 2008 at 11:57 AM, rishi pathak wrote: > Are you sitting behind a proxy. If so then you have to set proxy for http > > On Fri, Dec 5, 2008 at 11:47 AM, svalbard colaco > wrote: > >> Hi all >> >> I have written a small code snippet to open a URL using urllib2 to open a >> web page , my python version is 2.4 but i get an urlopen error called >> connection timed out >> >> The following is the code snippet >> >> *import urllib2 >> >> f = urllib2.urlopen('http://www.google.com/') >> print f.read(100)* >> >> >> where as the same url http://www.google.com/ works through my browser. >> >> The following is the back trace : >> >> File "test_url.py", line 3, in ? >> f = urllib2.urlopen('http://www.google.com/') >> File "/usr/lib/python2.4/urllib2.py", line 130, in urlopen >> return _opener.open(url, data) >> File "/usr/lib/python2.4/urllib2.py", line 358, in open >> response = self._open(req, data) >> File "/usr/lib/python2.4/urllib2.py", line 376, in _open >> '_open', req) >> File "/usr/lib/python2.4/urllib2.py", line 337, in _call_chain >> result = func(*args) >> File "/usr/lib/python2.4/urllib2.py", line 1021, in http_open >> return self.do_open(httplib.HTTPConnection, req) >> File "/usr/lib/python2.4/urllib2.py", line 996, in do_open >> raise URLError(err) >> *urllib2.URLError: >> >> >> Any pointers in this regard will be of great help. >> >> Thanking you'll in advance. >> >> Regards, >> sv >> >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > > -- > Regards-- > Rishi Pathak > Pune-Maharastra > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gh at ghaering.de Wed Dec 3 16:41:48 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 03 Dec 2008 22:41:48 +0100 Subject: building an extension module with autotools? In-Reply-To: References: Message-ID: <4936FD1C.1010700@ghaering.de> Michael George wrote: > Hello, > > (Please CC me in replies, as I am off-list) Ok, but please reply publicly. > I'm building an application (a game) in python, with a single C module > containing some performance-critical code. I'm trying to figure out the > best way to set it up to build. Use distutils and keep your sanity. > Distutils seems to be designed only for > building and distributing code that lives in site-packages. I'd prefer > not to install it in the global site-packages, but rather group all of > the files together. Then just use the build step of distutils and do the rest from your build script (Python-based, make based, whatever you prefer). > I've tried using automake, In my opinion, this is serious overkill. automake is good for making stuff work on a herd of different Unixen with various combinations of libc functions available etc. But for developing a Python extension, it doesn't help much at all. All you need to know about Python is available via macros if you import Python.h. > however I'm worried about libtool not getting > the options right while building my module. It seems to me like the > ideal frankenstein monster would be for automake to invoke distutils to > do the actual building. However I'm relatively new to both autotools > and distutils, so getting this rigged up has been a bit of a challenge. > Can anybody point me to a good example of something like this or give me > any pointers? My recommendation is to start simple instead of wasting too much time upfront for probably nothing. Here's what I'd start with: #!/bin/sh python setup.py build cp build/lib.*/*.so . python test.py HTH -- Gerhard From zac256 at gmail.com Tue Dec 2 19:58:36 2008 From: zac256 at gmail.com (Zac Burns) Date: Tue, 2 Dec 2008 16:58:36 -0800 Subject: Overriding a method at the instance level on a subclass of a builtin type Message-ID: <333edbe80812021658s3ae50aeetd45551b85b52b6a3@mail.gmail.com> Sorry for the long subject. I'm trying to create a subclass dictionary that runs extra init code on the first __getitem__ call. However, the performance of __getitem__ is quite important - so I'm trying in the subclassed __getitem__ method to first run some code and then patch in the original dict method for the instance to avoid even the check to see if the init code has been run. Various recipes using instancemethod and the like have failed me. Curiously if __slots__ is not specified no error occurs when setting self.__getitem__ but the function is not overriden. If __slots__ is ['__getitem__'] however it complains that __getitem__ is read only. I do not understand that behavior. -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer (Digital Overlord) Zindagi Games From lists at cheimes.de Thu Dec 25 14:17:31 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 25 Dec 2008 20:17:31 +0100 Subject: Syntax error for print In-Reply-To: <99a432d6-5085-4a3a-82ff-538c95e33515@z28g2000prd.googlegroups.com> References: <2b65c6e1-b5a9-438d-a45c-b8f9d18228de@s1g2000prg.googlegroups.com> <99a432d6-5085-4a3a-82ff-538c95e33515@z28g2000prd.googlegroups.com> Message-ID: jsm4321 at gmail.com schrieb: > Thanks Bearophile. > > I should have used a tutorial for Python 3.0 > > I was reading tutorial for Python 2.5 Get Python 2.5 or 2.6, seriously. Python 3.0 is not (yet) supported by most tutorials, third party extensions and books. Christian From jeff_barish at earthlink.net Mon Dec 22 22:42:20 2008 From: jeff_barish at earthlink.net (Jeffrey Barish) Date: Mon, 22 Dec 2008 20:42:20 -0700 Subject: Beep References: <47c890dc0812211620h6c19086dhf3a14a662a49fdf6@mail.gmail.com> <6r8qqpFq8rU1@mid.individual.net> Message-ID: Tobias Andersson wrote: > Jeffrey Barish skrev: >> Chris Rebert wrote: >>> Is the 'pcspkr' kernel module built and loaded? >> >> Yes. And I should have mentioned that I get sound from Ubuntu >> applications that produce sound. > > Also, is the terminal bell set to "visual"? If so chr(7) only > produces a brief flash (or similar). On Ubuntu, it is possible to set visual and audible beeps separately. When I set both, I get the visual beep, but not the audible one. It's not a Python issue -- so I should take this thread to Ubuntu -- because I observe this behavior even when I hit backspace at the beginning of a line in a terminal. -- Jeffrey Barish From mnordhoff at mattnordhoff.com Wed Dec 10 07:13:28 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Wed, 10 Dec 2008 12:13:28 +0000 Subject: Using the `email' module in a bazaar plugin In-Reply-To: <20081210115825.01853c3b.jules@REMOVETHIS.op59.net> References: <20081210115825.01853c3b.jules@REMOVETHIS.op59.net> Message-ID: <493FB268.3010107@mattnordhoff.com> Julian Smith wrote: > I don't seem to be able to use the `email' module from within a bazaar > plugin. Other modules work ok, e.g. nntplib. > > Here's my plugin, cut-down to show just the email problem: > > import sys > print 'sys.version', sys.version > > import nntplib > n = nntplib.NNTP( 'jsmith-ubuntu2' ) > print n > > import email > m=email.MIMEText.MIMEText('text of email') > > - and here's the output when i run any bazaar command: > > > bzr status > sys.version 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] > > 'module' object has no attribute 'MIMEText' > Unable to load plugin 'js_notify' from '/home/jsmith/.bazaar/plugins' > ... > > The plugin runs fine on its own, it's only when loaded into Bazaar that things > go wrong. > > I thought perhaps this could be caused by the `email' module's use of > LazyImporter. I've tried various things such as `from email.mime.text import > MIMEText', and they fail in similar ways. > > I'm using bzr-1.9, python 2.5.2, on Ubuntu-8.xx. > > Does anyone have any ideas ? > > Thanks, > > - Julian The built-in email module is probably getting shadowed by another one (perhaps bzrlib.plugins.email?), so "import email" is importing the wrong module. You'll have to rename it to something else. Have your plugin print email.__path__ to see which module it is. -- From jeremiah.dodds at gmail.com Thu Dec 4 04:06:32 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Thu, 4 Dec 2008 04:06:32 -0500 Subject: Multiple equates In-Reply-To: <001801c95648$5b6d65e0$0d00a8c0@hendrik> References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> <001801c95648$5b6d65e0$0d00a8c0@hendrik> Message-ID: <12cbbbfc0812040106m50a9f6edxcbb373bac62823a4@mail.gmail.com> On Thu, Dec 4, 2008 at 1:19 PM, Hendrik van Rooyen wrote: > > "Cameron Laird" wrote: > > > There's a realm within Pythonia that favors lambdalessness. > > And who, may I ask, Is the King of this realm? > > - Hendrik > > -- > http://mail.python.org/mailman/listinfo/python-list > Guido? -------------- next part -------------- An HTML attachment was scrubbed... URL: From bockman at virgilio.it Wed Dec 31 14:17:51 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: Wed, 31 Dec 2008 20:17:51 +0100 Subject: select.select and socket.setblocking In-Reply-To: <4b7fdd17-c9c0-4970-9bf8-e596c939e23e@d42g2000prb.googlegroups.com> References: <495a661d$0$11384$5fc30a8@news.tiscali.it> <495b34d8$0$11387$5fc30a8@news.tiscali.it> <3652a957-eec6-494c-bd37-d150018bc0ed@p2g2000prf.googlegroups.com> <495b8653$0$11383$5fc30a8@news.tiscali.it> <4b7fdd17-c9c0-4970-9bf8-e596c939e23e@d42g2000prb.googlegroups.com> Message-ID: <495bc560$0$11385$5fc30a8@news.tiscali.it> Saju Pillai ha scritto: > On Dec 31, 7:48 pm, Francesco Bochicchio wrote: > > Is this correct ? IIRC even in blocking mode recv() can return with > less bytes than requested, unless the MSG_WAITALL flag is supplied. > Blocking mode only guarantees that recv() will wait for a message if > none is available - but not that it *will* return the number of bytes > requested. > > -srp > You are right ... most of my socket experience predates MSG_WAITALL, and I forgot that now the default behaviour is different ... oops ... Ciao ------ FB From aboudouvas at panafonet.gr Sat Dec 6 05:54:06 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Sat, 6 Dec 2008 02:54:06 -0800 (PST) Subject: Netbeans Early Access and Python3 Message-ID: Hi, have anyone using this release of NetBeans (6.5 with Python support) with Python 3 without any problems ? I mean, does it work with Python3 or only with 2.x ? From dstanek at dstanek.com Mon Dec 22 10:43:44 2008 From: dstanek at dstanek.com (David Stanek) Date: Mon, 22 Dec 2008 10:43:44 -0500 Subject: Event Driven programming - Doubts In-Reply-To: <80f360e4-2880-4c66-a6b4-e05d6dbc9031@b41g2000pra.googlegroups.com> References: <80f360e4-2880-4c66-a6b4-e05d6dbc9031@b41g2000pra.googlegroups.com> Message-ID: On Mon, Dec 22, 2008 at 9:57 AM, Kottiyath wrote: > > If so, Even though data locking etc is not a problem, are we not still > having threads? Will it not still cause scalability problems in high > traffic? > If not, could somebody let me know how it is done? This somewhat depends on the application. Is it IO bound or CPU bound? >From what I understand about twisted you will only have one process and one thread which means you will only be using one CPU. -- David http://www.traceback.org From w_a_x_man at yahoo.com Wed Dec 10 21:22:40 2008 From: w_a_x_man at yahoo.com (William James) Date: 11 Dec 2008 02:22:40 GMT Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <40b4b23f-c1eb-4ac5-bb42-e0f6276e97bf@r37g2000prr.googlegroups.com> Message-ID: Jon Harrop wrote: > Xah Lee wrote: > > On Dec 10, 12:37 pm, w_a_x_... at yahoo.com wrote: > >> Ruby: > > > > >> def norm a > >> s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) > >> a.map{|x| x/s} > >> end > > > > I don't know ruby, but i tried to run it and it does not work. > > > > #ruby > > def norm a > > s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) > > a.map{|x| x/s} > > end > > > > v = [3,4] > > > > p norm(v) # returns [0.6, 0.8] > > That is the correct answer. > > > The correct result for that input would be 5. > > No, you're confusing normalization with length. Expanded for easier comprehension. def norm a # Replace each number with its square. b = a.map{|x| x*x } # Sum the squares. (inject is reduce or fold) c = b.inject{|x,y| x + y } # Take the square root of the sum. s = Math.sqrt( c ) # Divide each number in original list by the square root. a.map{|x| x/s } end 1.upto(4){|i| a = (1..i).to_a p a p norm( a ) } --- output --- [1] [1.0] [1, 2] [0.447213595499958, 0.894427190999916] [1, 2, 3] [0.267261241912424, 0.534522483824849, 0.801783725737273] [1, 2, 3, 4] [0.182574185835055, 0.365148371670111, 0.547722557505166, 0.730296743340221] From clp at rebertia.com Sun Dec 7 03:35:24 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 7 Dec 2008 00:35:24 -0800 Subject: can graphs be made in python as we make in java In-Reply-To: <89ff42d1-6a4c-4d45-a646-238b43e7e8de@s9g2000prm.googlegroups.com> References: <89ff42d1-6a4c-4d45-a646-238b43e7e8de@s9g2000prm.googlegroups.com> Message-ID: <47c890dc0812070035g6298be00ob1afc56a451e32f2@mail.gmail.com> On Sun, Dec 7, 2008 at 12:29 AM, suku wrote: > HI folks... > > i need some suggestion on making graphs. Will this be possible > with normal python setup file or do i need to download add ons for > that.. Python includes no such module for that in the standard library. You'll need to use a third-party library. If you're writing a webapp, pygooglechart (http://pygooglechart.slowchop.com/) is pretty good. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > help me out > -- > http://mail.python.org/mailman/listinfo/python-list > From paul at boddie.org.uk Mon Dec 15 10:34:06 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 15 Dec 2008 07:34:06 -0800 (PST) Subject: %s place holder does not let me insert ' in an sql query with python. References: <1229345178.31093.24.camel@krishna-laptop> Message-ID: <412769f8-c1c8-4d4b-9350-7189b98a7dac@p2g2000prn.googlegroups.com> On 15 Des, 14:46, Krishnakant wrote: > hello all, > thanks for all of your very quick responses. > The problem is that I am using python 2.5 so the 2.6 syntax does not > apply in my case. The parameter syntax for database operations is defined by the DB-API, and this is a very different matter to that of Python string substitution (or formatting). See this document for details: http://www.python.org/dev/peps/pep-0249/ You should note that when sending the SQL command to the database system, you do not use the % operator to prepare that command. Instead, you should pass the collection of parameters as the second argument of the execute method. In other words... cursor.execute(query, parameters) Note that the query is kept as a separate argument; you do not combine these two things yourself. Paul P.S. As far as I know, Python 2.6 still has the traditional printf- style substitution syntax, so any exhortation to adopt new-style formatting is ill-advised, especially since it has only slight relevance to this particular enquiry. From duncan.booth at invalid.invalid Tue Dec 2 04:50:31 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Dec 2008 09:50:31 GMT Subject: Is it safe to modify the dict returned by vars() or locals() References: <4934508b$0$2861$ba620e4c@news.skynet.be> <4935011A.9080406@igpm.rwth-aachen.de> Message-ID: Helmut Jarausch wrote: > Chris Rebert wrote: >> On Mon, Dec 1, 2008 at 1:01 PM, Helmut Jarausch >> wrote: >>> Hi, >>> >>> I am looking for an elegant way to solve the following problem: >>> >>> Within a function >>> >>> def Foo(**parms) >>> >>> I have a list of names, say VList=['A','B','C1'] >>> and I like to generate abbreviation >>> _A identical to parms['A'] >> >> Could you explain what you mean by that? Your sample code doesn't >> seem to do any "abbreviation"... >> Otherwise I don't see why you don't just have a proper parameter >> list. > > In my application parms contains field names of an html form iff these > fields have been modified. > I'd like to use the short name _A instead of the longer expression > parms['A'] > > You haven't yet explained why you don't just do: def foo(A=None, **parms): ... The code to call foo remains the same as before, but Python will unpack the named parameter into the local variable A for you automatically. Any other parms that you didn't know about in advance remain in the separate dictionary. -- Duncan Booth http://kupuguy.blogspot.com From philip at semanchuk.com Sat Dec 13 15:27:50 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Sat, 13 Dec 2008 15:27:50 -0500 Subject: Parallelizing python code - design/implementation questions In-Reply-To: References: Message-ID: On Dec 13, 2008, at 7:00 AM, stdazi wrote: > Hello! > > I'm about to parallelize some algorithm that turned out to be too > slow. Before I start doing it, I'd like to hear some suggestions/hints > from you. Hi stdazi, If you're communicating between multiple processes with Python, you might find my IPC extensions useful. They're much less sophisticated than multiprocessing; they just give access to IPC semaphores and shared memory (no message queues yet) on Unix. POSIX IPC: http://semanchuk.com/philip/posix_ipc/ System V IPC: http://semanchuk.com/philip/sysv_ipc/ More System V IPC: http://nikitathespider.com/python/shm/ The System V IPC extensions are similar; the latter is older and better tested but won't be developed anymore. The former is newer, has a couple more features and is the future of System V IPC w/Python, at least as far as my work is concerned. Good luck Philip > > > The algorithm essentially works like this: There is a iterator > function "foo" yielding a special kind permutation of [1,....n]. The > main program then iterates through this permutations calculating some > proprieties. Each time a calculation ends, a counter is incremented > and each time the counter is divisible by 100, the current progress is > printed. > > The classical idea is to spawn m threads and use some global lock when > calling the instance of the iterator + one global lock for > incrementing the progress counter. Is there any better way? I'm > especially concerned with performance degradation due to locking - is > there any way to somehow avoid it? > > I've also read about the `multiprocessing' module and as far as I've > understood : > > ==== > permutation = foo() > threadlst = [] > for i in xrange(m) : > p = Process(target=permutation.next) > threadlst.append(p) > p.start() > for p in threadlst: > p.join() > ==== > > should do the trick. Am I right? Is there any better way other than > this? > -- > http://mail.python.org/mailman/listinfo/python-list From warren at delsci.com Thu Dec 4 19:17:20 2008 From: warren at delsci.com (Warren DeLano) Date: Thu, 4 Dec 2008 16:17:20 -0800 Subject: To Troll or Not To Troll (aka: "as" keyword woes) Message-ID: <896B75251BA19745A529B1B867893FA5DB0E@planet.delsci.local> > From: Ben Finney > > "Chris Mellon" writes: > > > Peculiarities in usenet resulted in this discussion having several > > threads and I missed some messages before I wrote this email. > > I'll put this more bluntly: Warren's messages to date > egregiously break the flow of discussion. > > Warren, in the interest of sane discussion in these forums, please: > > * preserve attribution lines on quoted material so we can see who > wrote what. > > * use the convention of ?New subject (was: Old subject)? when you > change the ?Subject? field of a message. > > * switch to a client that preserves threading in messages you send, > i.e. that properly constructs the ?References? and ?In-Reply-To? > fields. > > General advice good for everyone, of course, but particularly > apropos to this reply. Any one of the above is detrimental to > omit; striking on all three makes a discussion almost > impossible to follow. (Thank you, though, for avoiding the > worse habit of top posting!) Thank so much for the suggestions Ben. Sorry that I am personally unable to live up to your high standards, but it is nevertheless an honor to partipicate in such a helpful and mutually respectful community mailing list! Warren From arnodel at googlemail.com Tue Dec 23 12:03:31 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 23 Dec 2008 17:03:31 +0000 Subject: On Whose Desktop References: <4950db7e$0$14770$426a74cc@news.free.fr> <89ca6cc9-fa26-42c9-be67-35aad569500b@i18g2000prf.googlegroups.com> Message-ID: Aaron Brady writes: > +1 whose (posessive) -1 posessive :) -- Arnaud From tundra at tundraware.com Tue Dec 9 11:58:05 2008 From: tundra at tundraware.com (Tim Daneliuk) Date: Tue, 09 Dec 2008 10:58:05 -0600 Subject: Python 3 For Python 2 Users Message-ID: I code in Python 2.x intermittently and have only casually watched the 3.x development discussions. Now it's time to get up to speed. Has someone written a tutorial for people in my situation. Yes, I've looked at the release notes, but I'm looking for something that motivates all the major changes to give me a better sense of the Gestalt of the new language. TIA, -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From rdcollum at gmail.com Thu Dec 18 11:52:20 2008 From: rdcollum at gmail.com (Roger) Date: Thu, 18 Dec 2008 08:52:20 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <71ede5f0-fd88-4155-9f0d-42d0ad5f57dc@v42g2000yqj.googlegroups.com> Message-ID: On Dec 18, 11:40?am, r wrote: > Yea, my answer was really not a helping answer(sorry) just showing > exactly why this will not work with w.unbind(). Why do you need two > separate functions to bind the same event?? You cannot combine the > two?? I can't combine the two in my app unfortunately. The binding is to a custom widget that upon it being destroyed the binding is no longer valid. I can work around this by being hacky but I prefer to delete the one binding itself which would make things cleaner. From clp at rebertia.com Tue Dec 9 22:29:06 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 9 Dec 2008 19:29:06 -0800 Subject: How do I manually uninstall setuptools (installed by egg)? In-Reply-To: <375bd56a-d92b-4d33-bf70-5bea630a376a@q30g2000vbn.googlegroups.com> References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> <375bd56a-d92b-4d33-bf70-5bea630a376a@q30g2000vbn.googlegroups.com> Message-ID: <47c890dc0812091929m68dbcfceoeca883be82c6b9df@mail.gmail.com> On Tue, Dec 9, 2008 at 7:16 PM, wrote: > On Dec 9, 10:04 pm, "Chris Rebert" wrote: >> So, why do you think apt and not setuptools is The Right Way(tm)? > > I like to keep > 1 Python on my computer. Ah, now I get it. I had no idea setuptools could install Python *itself* until I checked just now. That's kinda neat, but mostly silly, because, as you point out, management of Python itself is much better left to the platform's package manager. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From chaneyfgargue at gmail.com Tue Dec 9 14:08:27 2008 From: chaneyfgargue at gmail.com (chaneyfgargue at gmail.com) Date: Tue, 9 Dec 2008 11:08:27 -0800 (PST) Subject: Opa asdasd News Message-ID: <257ad7af-fea8-4389-9f6a-095446525016@z6g2000pre.googlegroups.com> The decision comes after the review of a six-month pilot program that extended the TIS National to pharmacies. http://bmool.blogsome.com/ http://asdmk.blogsome.com/ The pilot program, conducted by the department and the Pharmacy Guild of Australia, involved 331 pharmacies having access to the service 24 hours a day. http://steppo.blogsome.com/ Participating pharmacies will be able to use the Translating and Interpreting Service (TIS National), operated by the Department of Immigration, 24 hours a day, seven days a week. Pharmacy Guild of Australia national president Kos Sclavos implored pharmacists to use the service to prevent patients from misinterpreting important usage instructions. http://mygotar.blogsome.com/ "The interpreter service is not a full solution. The best solution is to always have a staff member of that language. Pharmacies have been very good at going out of their way to employ perhaps one staff member fluent in another language. But because the trading hours of pharmacies, it's very hard to have a staff member on at all times with that language skills base. So this service fills in or augments current practices." Mr Sclavos said there were inherent problems with other multilingual initiatives, such as printing instruction labels in other languages. "The tendency to revert to a first language as experienced by some older Australians, who have acquired English as a second language, is one of the greatest issues facing our ageing population. This was demonstrated by the heavy usage of the TIS services by post-war aged European communities throughout the duration of the pilot. Pharmacies who participated in the pilot used interpreting services more frequently and reported improved outcomes in terms of client understanding of medications." http://rollz.blogsome.com/ "You need to be getting that verbal and non-verbal feedback from the patient that they have indeed understood the instructions and that's why the interpreter service is so important because the interpreter on the other end of the phone will ask 'now repeat what I've just explained' or 'have you understood what I just said'," Mr Sclavos said. http://aermk.blogsome.com/ "As a pharmacist, if I was checking the prescription later and unless it's dual-labelled, I couldn't be sure because I couldn't read that language or couldn't understand the translation. The difficulty we have with the dual-labelling approach is that we would be getting complaints that the packaging is getting smaller and smaller and there is no room to put a sticker on the packet. That's why the Guild?s policy is not to support automatic translations because it increases the risk of errors." http://twoaac.blogsome.com/ Parliamentary Secretary for Multicultural Affairs Laurie Ferguson said health care needs of recent migrants and elderly former migrants necessitated the extension of the service to pharmacies. http://viewpharmacy.blogsome.com/ "Interpreting services are crucial for the proper distribution and usage of prescription medicines by non-English speaking Australians," Mr Ferguson said. From mensanator at aol.com Sat Dec 6 17:36:07 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 6 Dec 2008 14:36:07 -0800 (PST) Subject: "as" keyword woes References: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> <0147dc24$0$20670$c3e8da3@news.astraweb.com> <0148b217$0$20670$c3e8da3@news.astraweb.com> <7d0lj4d9hai2f87r30erc4l1ir85osbfg7@4ax.com> <88579d9a-df52-49b9-a6fe-53c8f4524bf3@j39g2000yqn.googlegroups.com> <70llj41hie2svs68o5efn22i97f649svfh@4ax.com> Message-ID: <1cda9a9a-1641-424b-9f3d-c4e2635efed7@j38g2000yqa.googlegroups.com> On Dec 6, 2:09?pm, Wolfgang Strobl wrote: > Mensanator : > > > > > > >On Dec 6, 8:16?am, Wolfgang Strobl wrote: > >> Dennis Lee Bieber : > > >> >On 05 Dec 2008 05:21:25 GMT, Steven D'Aprano > >> > declaimed the following in > >> >comp.lang.python: > > >> >> On Thu, 04 Dec 2008 08:44:19 -0800, Matimus wrote: > > >> >> > The point was that there > >> >> > is that new releases don't _break_ anything. > > >> >> But that's clearly not true, because the OP is pointing out that the new > >> >> release from 2.5 to 2.6 *does* break his code. > > >> > ? ?One now has to ask what "break" really meant... For this example, > >> >the change did not break Python SYNTAX -- just a complaint about using > >> >what is now a reserved word as an object name. > > >> Of course it does: > > >> C:\Python26>python > >> Python 2.6 (r26:66721, Oct ?2 2008, 11:35:03) [MSC v.1500 32 bit > >> (Intel)] on win 32 > >> Type "help", "copyright", "credits" or "license" for more information.>>> as=2 > > >> ? File "", line 1 > >> ? ? as=2 > >> ? ? ?^ > >> SyntaxError: invalid syntax > > >I disagree. "Broken" is something you can't work > >around. > > Well, that language change _did_ break the OPs code, and he already > explained why it isn't as simple to work around as you obviously happen > to believe. It was extremely simple for me to fix the sympy module where I noticed it. I'm not saying it wasn't a problem, I'm saying it wasn't BROKEN. And no, I couldn't use sympy after the fix because apparently there is some change the way 2.6 hashes which truly breaks the sympy code, so no using sympy with 2.6 until a corrected version is released. And the real problem is that the latest version was released without ever testing it under 2.6. Hopefully, that won't happen again. > ? Calling it "not a SYNTAX error" is not only mistaken, it's > weaseling around the problem too. It's not weaseling around the problem, it's rating the seriousness of the problem. Right now if I need sympy, I HAVE to use 2.5, if I need itertools.permutations I HAVE to use 2.6. But I canot use both in the same program which is a tad more serious than having to rename a variable I had business using in the first place. > > >In this case, simply saying as_=2 works fine. > > Certainly not, for example when that name is already used outside your > control. In addition, you'll have to find all places, where the now > syntactically illegal name is or might be used. This can get arbitrarily > hard in generated ?or foreign code. The difficulty of fixing it isn't the issue, it's whether it can be fixed at all. > > > > >A better example of broken was when the gmpy module > >wouldn't solve a certain linear congruence problem > >because the problem was not invertible. > > What does that have to to with anything? It's an example of what it means to be BROKEN, and yes, nothing at all to do with SYNTAX. > We're disussing a language > change on the syntax level which breaks existing legal code, not how a > numerical library behaves for borderline cases. And yet, you don't consider this a case of "weasel words". Strange. > > [...] > > >> Making a former syntactically valid ?two letter name a reserved word in > >> 2.6 was a mistake, IMHO. > > >I think you're in the minority there. > > Perhaps. Does that matter? Yeah, if you think it will be resolved in your favor. > > >> What's next? What about making i,j,k, x and y > >> reserved words in 2.7? =:-/ > > >Yeah, right. That'll happen. > > Certainly not. ?On the other hand, I was quite flabbergasted by the > change in question, likewise. Wasn't that something ?reserved for 3.0: > breaking code mercilessly? ? Mercilessly? If there were no deprecation warnings, you might have a case there. You act as if the failure to display such warnings was deliberate, but that was due to a BUG, not merciless behaviour on the part of the developers. > What is 3.0 good for, when we have to bear > such breakage in a minor release, already? You're making a mountain out of a molehill. > > >You ought to be more > >concerned about real problems. > > It is a real problem for the OP. Who gave him permission to use 2.6? Is 2.5 suddenly unavailable? Assholes like Microsoft pull stunts like that, but Python.org doesn't. If it's his code, he can easily fix it. If it's someone else's code, he should be using a version guaranteed to work in 2.6. > > -- > Thank you for observing all safety precautions From pythonnutter at gmail.com Sat Dec 6 20:44:19 2008 From: pythonnutter at gmail.com (Python Nutter) Date: Sun, 7 Dec 2008 12:44:19 +1100 Subject: Learning Python now coming from Perl In-Reply-To: References: Message-ID: Perl Cookbook for Python Programmers: http://pleac.sourceforge.net/pleac_python/index.html P3K as starting point (slight cringe) as long as you know the caveats. I'm of the mind as Christopher with regard to how Python 3.0 has been released on Python.org: """I don't think that Python 3.0 is a bad thing. But that it's displayed so prominently on the Python web site, without any kind of warning that it's not going to work with 99% of the Python code out there, scares the hell out of me. People are going to download and install 3.0 by default, and nothing's going to work. They're going to complain, and many are going to simply walk away. - Christopher Lenz""" Python3 is beautiful, and I am totally with James Bennet http://www.b-list.org/weblog/2008/dec/05/python-3000/ That said I would suggest you learn the whole history of the Py3K project and its 19+ years of 20/20 hindsight on what works well and what doesn't so you can if you want to jump right into Python3 fully informed on why it is the way it is and why you need to wait for 3rd party libraries to catch up and release a Python 3 compatible version and why all the Internal libraries are no worry except for the fact some of them have disappeared in the cleanup or merged into a single library. Then you can make sense of all the 2.x books and posts and know where to start when trying to apply it to Python 3. Cheers, PN (Python 2.5.2, Stackless Python 2.5.2, Python 2.6 and Python 3.0 on my box) P.S. Look into iPython as your new favourtie shell and virtualenv to help you keep all your projects straight and you'll be very productive in no time =) 2008/12/7 Bertilo Wennergren : > I'm planning to start learning Python now, using Python 3000. > I have no previous Python skills, but I now Perl pretty well. > I'm also well experienced with JavaScript. > > Any pointers and tips how I should go about getting into > Python? From martin at v.loewis.de Tue Dec 9 17:32:00 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 09 Dec 2008 23:32:00 +0100 Subject: Google Summer of Code 2009 In-Reply-To: <713dd4d7-0427-4b74-a5bc-1e3538afed6c@n10g2000vbl.googlegroups.com> References: <713dd4d7-0427-4b74-a5bc-1e3538afed6c@n10g2000vbl.googlegroups.com> Message-ID: <493EF1E0.90802@v.loewis.de> > I am interested in participating in Google Summer of Code 2009, > hopefully for something in Python. I realize that this is way before > it begins, but I would like to start to get to know the community > better and find something that I could work on during the summer of > code. I know a decent amount of Python, and I am a Sophomore Computer > Science major. My school teaches Java, but on the side I taught > myself Python. If anyone knows of any projects that could use another > hand, I would appreciate it. Traditionally, the PSF SoC participation includes a number of projects, many of them with their own mailing lists etc. Andre has already pointed you to the list of potential projects; the exact set of projects may vary, of course. So if one of them interests you, you should contact the specific mailing lists. If it is Python proper, the list would be python-dev at python.org. Notice that several projects written in Python participate in SoC on their own, e.g. Django. Take a look at the full list of SoC organizations for 2008; perhaps you spot something that interests you. Again, which specific organizations will participate in 2009 will vary again (it's nearly certain that the PSF will get approved again, though). Regards, Martin From lie.1296 at gmail.com Mon Dec 15 00:39:45 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 15 Dec 2008 05:39:45 +0000 (UTC) Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> <87ej0dz894.fsf@daycos.com> <0152e35f$0$8244$c3e8da3@news.astraweb.com> <0155c4a7$0$6988$c3e8da3@news.astraweb.com> Message-ID: On Mon, 15 Dec 2008 03:21:21 +0000, Steven D'Aprano wrote: > On Mon, 15 Dec 2008 02:11:10 +0000, Lie Ryan wrote: > >>> So given the normal precedence rules of Python, there is no ambiguity. >>> True, you have to learn the rules, but that's no hardship. >> >> *I* know about the precedence rule, but a newbie or a tired programmer >> might not. He might want to reverse the truth value of argument b but >> instead has just reversed the whole expression. > > And? A newbie or a tired programmer might not know that a^b is bit-wise > xor instead of exponentiation, or that range(n) doesn't include n, or > even that len(alist) returns the length of a list. There's no limit to > the potential mistakes that are possible for a programmer who is tired, > inexperienced, intoxicated or just plain stupid enough. What's your > point? Are you expecting Python to be mistake-proof? > > There's a certain level of knowledge about the language necessary to > program effectively, and learning that "is not" is a single operator is > not particularly onerous. I give up. It does not matter to me anyway. I was just expressing the preference that operators should be composed of a single word, especially since none of the other operators are multi-words (Special cases aren't special enough to break the rules). The only advantage of using 'is not' over 'isnot' is that we have one less keyword to deal with. From mludvig at logix.net.nz Sat Dec 13 04:48:31 2008 From: mludvig at logix.net.nz (Michal Ludvig) Date: Sat, 13 Dec 2008 22:48:31 +1300 Subject: setup.py installs modules to a wrong place Message-ID: <494384EF.7050605@logix.net.nz> Hi, I have recently seen some reports from users of my s3cmd script [1] who installed the package using the provided distutils-based setup.py and immediately after installation the script failed to run because it couldn't find its modules. Here's an example session from Mac OS X, but similar behaviour has been observed on Ubuntu as well. Needless to say it works for me just fine so I can't easily debug and fix it :-( First is the reported setup.py output: ----- ~/bin/s3cmd $ sudo python setup.py install Password: ... running install_lib creating /usr/lib/python2.5/site-packages creating /usr/lib/python2.5/site-packages/S3 copying build/lib/S3/PkgInfo.py -> /usr/lib/python2.5/site-packages/S3 ... more modules, etc ... ----- It decided to put the modules to /usr/lib/python2.5/site-packages/S3 Now, s3cmd should import from there, but fails: ~/bin/s3cmd $ s3cmd Traceback (most recent call last): File "/usr/bin/s3cmd", line 1207, in from S3 import PkgInfo ImportError: No module named S3 sys.path at the time the script died had these entries: /usr/bin /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python25.zip /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5 /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-darwin /System/Library/Frameworks/Python.framework/Versions/2.5/...other_subdirs... /Library/Python/2.5/site-packages There is nothing special in setup.py. After all have a look yourself: http://s3tools.svn.sourceforge.net/viewvc/s3tools/s3cmd/trunk/setup.py?view=markup What could be the reason for distutils / setup.py to install the modules to a directory that's not in sys.path? Can I detect it in setup.py and prevent or workaround it somehow? Thanks! [1] http://s3tools.logix.cz/s3cmd -- Amazon S3 command line client Michal From jules at REMOVETHIS.op59.net Wed Dec 10 09:20:04 2008 From: jules at REMOVETHIS.op59.net (Julian Smith) Date: Wed, 10 Dec 2008 14:20:04 +0000 Subject: Using the `email' module in a bazaar plugin References: <20081210115825.01853c3b.jules@REMOVETHIS.op59.net> Message-ID: <20081210142004.505f121f.jules@REMOVETHIS.op59.net> On Wed, 10 Dec 2008 12:13:28 +0000 Matt Nordhoff wrote: > Julian Smith wrote: > > I don't seem to be able to use the `email' module from within a bazaar > > plugin. Other modules work ok, e.g. nntplib. > > > > Here's my plugin, cut-down to show just the email problem: > > > > import sys > > print 'sys.version', sys.version > > > > import nntplib > > n = nntplib.NNTP( 'jsmith-ubuntu2' ) > > print n > > > > import email > > m=email.MIMEText.MIMEText('text of email') > > > > - and here's the output when i run any bazaar command: > > > > > bzr status > > sys.version 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] > > > > 'module' object has no attribute 'MIMEText' > > Unable to load plugin 'js_notify' from '/home/jsmith/.bazaar/plugins' > > ... > > > > The plugin runs fine on its own, it's only when loaded into Bazaar that things > > go wrong. > > > > I thought perhaps this could be caused by the `email' module's use of > > LazyImporter. I've tried various things such as `from email.mime.text import > > MIMEText', and they fail in similar ways. > > > > I'm using bzr-1.9, python 2.5.2, on Ubuntu-8.xx. > > > > Does anyone have any ideas ? > > > > Thanks, > > > > - Julian > > The built-in email module is probably getting shadowed by another one > (perhaps bzrlib.plugins.email?), so "import email" is importing the > wrong module. You'll have to rename it to something else. > > Have your plugin print email.__path__ to see which module it is. Ah, you're quite right. Curiously, email.__path__ is: /usr/lib/python2.5/site-packages/bzrlib/plugins/email - but sys.path is: ['/usr/bin', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/Numeric', '/usr/lib/python2.5/site-packages/PIL', '/usr/lib/python2.5/site-packages/gst-0.10', '/var/lib/python-support/python2.5', '/usr/lib/python2.5/site-packages/gtk-2.0', '/var/lib/python-support/python2.5/gtk-2.0'] - i.e. no occurrence of `/usr/lib/python2.5/site-packages/bzrlib/plugins'. So i guess bazaar is redefining __import__() to look in the the plugins directory first, or something. Anyway, I can get things to work with the following: import imp email = imp.load_module( 'email', *imp.find_module( 'email', sys.path)) Many thanks, - Julian -- http://op59.net/ From luismgz at gmail.com Sun Dec 7 20:10:00 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Sun, 7 Dec 2008 17:10:00 -0800 (PST) Subject: Python for kids? References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> <53f406ed-c261-4d86-a8dc-4001d10d05b5@s20g2000yqh.googlegroups.com> Message-ID: <11a3e492-3c0d-475f-b350-f28351842dad@f3g2000yqf.googlegroups.com> This is a very good advice. I learned from my own experience in college that trying to learn a solution to a problem I never had, is wasted time. The first step is confronting your student with an specific problem, then let him try to find a way to solve it by himself. After he tried hard many approaches to solving the problem with his limited knowledge, show him the right way. This way he will see the light. I believe that many teachers don't know this basic concept, and they simply teach in a mechanical way, without having their students interested in the subject or without having explained them what exactly these skills are good for. Luis On Dec 7, 5:37?pm, bearophileH... at lycos.com wrote: > On Dec 7, 9:13?pm, "Russ P." wrote: > > > I have a 12-year-old son who spends too much time playing Xbox live > > and watching silly YouTube videos. I would like to try to get him > > interested in programming. > > Lot of people learn to program even before age of 12. > But I think it's better for you to help him get interest in problem- > solving and some of the other bases of the mathematic, scientific and > computational mindset. Once those interests are in place, he will > probably go looking by himself for things like programming languages, > math and science (of course at that point a gentle guide toward good > ideas, good problems to solve, good books to read and good programming > languages, helps). > > Otherwise you risk pushing a person to learn using a tool (programming > is interesting by itself, but it's mostly a tool still) before having > any use for such tool or desire to learn it. And this may lead to > someone with no passion to solve problems and learn. > > Bye, > bearophile From gagsl-py2 at yahoo.com.ar Tue Dec 2 03:03:29 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Dec 2008 06:03:29 -0200 Subject: how can I open an excel sheet with specified name References: Message-ID: En Fri, 28 Nov 2008 23:12:50 -0200, Zuo, Changchun escribi?: > Could you please send me an example script example of > > * Opening an excel workbook with specified name > * Read or write number in a specified spreadsheet There is a specific group for those topics: python-excel [1] I'd suggest using the excelent xlrd [2] and xlwt [3] packages. [1] http://groups.google.com/group/python-excel/ [2] http://pypi.python.org/pypi/xlrd [3] http://pypi.python.org/pypi/xlwt -- Gabriel Genellina From sjmaster at gmail.com Sat Dec 6 11:59:26 2008 From: sjmaster at gmail.com (Steve M) Date: Sat, 6 Dec 2008 08:59:26 -0800 (PST) Subject: Can't get exclusive file lock when safely renaming a file References: <014a049b$0$20670$c3e8da3@news.astraweb.com> Message-ID: <872b1222-1410-404b-890c-ca2ca69faab1@41g2000yqf.googlegroups.com> On Dec 6, 12:25?am, Steven D'Aprano wrote: > The rename works, but here is my problem: after getting what I thought > was an exclusive lock on the new file, but before calling os.rename(), I > can still over-write it from another process: > > $ echo "this comes from another process" > spam.txt > $ cat spam.txt > this comes from another process What happens if you try to delete spam.txt at this point instead of over-write it? From ldo at geek-central.gen.new_zealand Sun Dec 7 02:27:51 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 07 Dec 2008 20:27:51 +1300 Subject: Don't you just love writing this sort of thing :) References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: In message , Rhodri James wrote: > Yes, it's very pretty, and you're terribly clever. In six months' time > when you come back to make some engineering change and have to sit down > and break it back down into those simple pieces to remind yourself what > it's doing, "pretty" and "clever" will not be the words you are using. > Trust me on this one. Considering I've been writing and maintaining and debugging code for about 30 years now, I figure I have the hard-earned right to judge what I will be able to understand in six months and what I won't... -- Lawrence "Been There, Done That" D'Oliveiro From Scott.Daniels at Acm.Org Wed Dec 24 14:48:57 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 24 Dec 2008 11:48:57 -0800 Subject: Iterating over objects of a class In-Reply-To: <7f47994f-13b6-45c4-920a-83aa72282bec@i20g2000prf.googlegroups.com> References: <2df27de3-7fa3-4ac9-acd9-f946939517cf@r37g2000prr.googlegroups.com> <6rfb7iF1fg5rU1@mid.uni-berlin.de> <7f47994f-13b6-45c4-920a-83aa72282bec@i20g2000prf.googlegroups.com> Message-ID: <7M-dnekT_vCVD8_UnZ2dnUVZ_q_inZ2d@pdx.net> Kottiyath wrote: > ... > Having a registry inside the class instance and looping through them > was the only clean thing I could think of. > I understand that garbage collection would be an issue - but is there > any way out? Search for weakref in the documentatione. In this case, I'd use a WeakValueDictionary() from id(obj) to obj. Note id(obj) is guaranteed to be unique for all objects in existance, but the id of a collected object may match the id of a new object. >>> import weakref >>> d = weakref.WeakValueDictionary() >>> vs = [Int(n) for n in range(3, 500, 70)] >>> for n in vs: d[id(n)] = n v = Int(n+1) d[id(v)] = v >>> for obj in d.values(): # values is safer than itervalues print obj >>> # note the above was the following, which fails: >>> for v in d.values(): # values is safer than itervalues print v For extra credit, explain why values is better. --Scott David Daniels Scott.Daniels at Acm.Org From goatold at gmail.com Tue Dec 16 00:30:57 2008 From: goatold at gmail.com (goatold at gmail.com) Date: Mon, 15 Dec 2008 21:30:57 -0800 (PST) Subject: socket and subprocess problem References: <6d3291c3-4e12-4bdd-884a-21f15f38d105@a12g2000pro.googlegroups.com> Message-ID: <73dca20d-3378-4c96-aa30-f0617f111fa0@i18g2000prf.googlegroups.com> Guys thanks to point it out. Yes, it's a race problem. I tried sleep long enough, then I can connect to the socket. I should add code to try to connect to the socket for a given time out. Roy Smith wrote: > In article > <6d3291c3-4e12-4bdd-884a-21f15f38d105 at a12g2000pro.googlegroups.com>, > goatold at gmail.com wrote: > > > In my python code I use subprocess.Popen to run and external program > > who will listen to a TCP port. And I also create a socket to connect > > to the TCP port that the external program is listening. > > I will get 'Connection refused, errno=111' when I try to > > socket.connect(). > > > Class a: > > def run() > > subprocess.Popen(..) > > Class b: > > def run(): > > sock = socket.socket() > > sock.connect(..) > > ################################# > > test.py > > # socket connect will fail here > > a.run() > > b.run() > > ################################### > > test1.py > > if __name__ = '__main__': > > a.run() > > > > test2.py > > # socket will connect fine > > if __name__ = '__main__': > > b.run > > Sounds like a timing problem. I assume that the process started by a.run() > creates a socket and does a bind/listen/accept sequence on it. The problem > is, there's nothing in your code which guarantees that this happens before > b.run() executes the connect() call. > > The cheesy way to test this is to sleep for a second somewhere between > a.run() and b.run(). See if that helps. > > If it doesn't, then it's possible the process started by a.run() isn't > doing what it's supposed to do. Try running test1.py, and while it's > running, run netstat to see if you've got something listening on the port > you expect. From gagsl-py2 at yahoo.com.ar Sun Dec 14 02:38:05 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 14 Dec 2008 05:38:05 -0200 Subject: 1 or 1/0 doesn't raise an exception References: <49446E39.6020807@tim.thechases.com> Message-ID: En Sun, 14 Dec 2008 02:40:10 -0200, Benjamin Kaplan escribi?: > On Sat, Dec 13, 2008 at 10:49 PM, Daniel Fetchinson < > fetchinson at googlemail.com> wrote: > >> >> Is it a feature that >> >> >> >> 1 or 1/0 >> >> >> >> returns 1 and doesn't raise a ZeroDivisionError? If so, what's the >> >> rationale? >> > >> > http://en.wikipedia.org/wiki/Short-circuit_evaluation >> >> Let me just point out that unsuspecting people (like me) might rely on >> the whole expression to be evaluated and rely on exceptions being >> raised if needed. > > If you want both expressions evaluated, you can use & and |, just like > in C > and Java (&& and || are used for short circuit evaluation in those > languages). No: &, | (and ^, too) perform bitwise operations in Python, C and Java: py> 1 & 2 0 && and || --in both C and Java-- are like `and` and `or` in Python; they perform logical operations, and short-circuit evaluation of their operands. If you want to evaluate a logical expression without short circuiting, do that explicitely: a = first part b = second part if a or b: ... -- Gabriel Genellina From mail at microcorp.co.za Wed Dec 3 22:13:09 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 4 Dec 2008 05:13:09 +0200 Subject: Thread Tkinter problem References: <64c7402c-8b7b-4281-9d7d-1abdd6177d96@r15g2000prh.googlegroups.com> Message-ID: <001801c955be$798e83e0$0d00a8c0@hendrik> "Davy" wrote: > while(data_queue.full() == False): This will fill the queue and stop. Use while true and if queue not full... - Hendrik From mr.spoon21 at gmail.com Tue Dec 16 14:59:57 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Tue, 16 Dec 2008 20:59:57 +0100 Subject: Free place to host python files? In-Reply-To: References: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> <32599660-2393-4e18-8c48-05d64bccbbc1@t26g2000prh.googlegroups.com> Message-ID: <8f67b6f80812161159m6822117eh5ea5d23d7bfcf331@mail.gmail.com> 2008/12/16 feba : > Stuff like code.google, sf.net, are more oriented towards serious > development, not just holding random apps, aren't they? > > Anyway, I found MediaFire, which looks like it will suffice for now. Take a look to Dropbox (http://www.getdropbox.com/). You can use it to directly share files with your friends or to create a public link to your files so other people can download them. From iofferkicks21 at gmail.com Wed Dec 24 00:10:59 2008 From: iofferkicks21 at gmail.com (www.iofferkicks.com) Date: Tue, 23 Dec 2008 21:10:59 -0800 (PST) Subject: www.iofferkicks.com china cheap wholesale nike shoes,air jordan shoes,air force one shoes. Message-ID: <9bab9ca1-5f3a-4c40-9dc8-cbcadbb6b8d3@n33g2000pri.googlegroups.com> Get Nike Shoes at Super Cheap Prices Discount Nike air jordans (www.iofferkicks.com) Discount Nike Air Max 90 Sneakers (www.iofferkicks.com) Discount Nike Air Max 91 Supplier (www.iofferkicks.com) Discount Nike Air Max 95 Shoes Supplier (www.iofferkicks.com) Discount Nike Air Max 97 Trainers (www.iofferkicks.com) Discount Nike Air Max 2003 Wholesale (www.iofferkicks.com) Discount Nike Air Max 2004 Shoes Wholesale (www.iofferkicks.com) Discount Nike Air Max 2005 Shop (www.iofferkicks.com) Discount Nike Air Max 2006 Shoes Shop (www.iofferkicks.com) Discount Nike Air Max 360 Catalogs (www.iofferkicks.com) Discount Nike Air Max Ltd Shoes Catalogs (www.iofferkicks.com) Discount Nike Air Max Tn Men's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 2 Women's Shoes (www.iofferkicks.com) Discount Nike Air Max Tn 3 Customize (www.iofferkicks.com) Discount Nike Air Max Tn 4 Shoes Customize ( www.iofferkicks.com) Discount Nike Air Max Tn 6 Supply (www.iofferkicks.com) Discount Nike Shox NZ Shoes Supply (www.iofferkicks.com) Discount Nike Shox OZ Sale (www.iofferkicks.com) Discount Nike Shox TL Store (www.iofferkicks.com) Discount Nike Shox TL 2 Shoes Store (www.iofferkicks.com) Discount Nike Shox TL 3 Distributor (www.iofferkicks.com) Discount Nike Shox Bmw Shoes Distributor (www.iofferkicks.com) Discount Nike Shox Elite Shoes Manufacturer (www.iofferkicks.com) Discount Nike Shox Monster Manufacturer (www.iofferkicks.com) Discount Nike Shox R4 Running Shoes (www.iofferkicks.com) Discount Nike Shox R5 Mens Shoes (www.iofferkicks.com) Discount Nike Shox Ride Womens Shoes (www.iofferkicks.com) Discount Nike Shox Rival Shoes Wholesaler (www.iofferkicks.com) Discount Nike Shox Energia Wholesaler (www.iofferkicks.com) Discount Nike Shox LV Sneaker (www.iofferkicks.com) Discount Nike Shox Turbo Suppliers (www.iofferkicks.com) Discount Nike Shox Classic Shoes Suppliers (www.iofferkicks.com) Discount Nike Shox Dendara Trainer (www.iofferkicks.com) Discount Nike Air Jordan 1 Seller (www.iofferkicks.com) Discount Nike Air Jordan 2 Shoes Seller (www.iofferkicks.com) Discount Nike Air Jordan 3 Collection (www.iofferkicks.com) Discount Nike Air Jordan 4 Shoes Collection (www.iofferkicks.com) Discount Nike Air Jordan 5 Chaussure Shoes (www.iofferkicks.com) Discount Nike Air Jordan 6 Catalog (www.iofferkicks.com) Discount Nike Air Jordan 7 Shoes Catalog (www.iofferkicks.com) Discount Nike Air Jordan 8 Customized (www.iofferkicks.com) Discount Nike Air Jordan 9 Shoes Customized (www.iofferkicks.com) Discount Nike Air Jordan 10 Wholesalers (www.iofferkicks.com) Discount Nike Jordan 11 Shoes Wholesalers (www.iofferkicks.com) Discount Nike Air Jordan 12 Factory (www.iofferkicks.com) Discount Nike Air Jordan 13 Shoes Factory (www.iofferkicks.com) Discount Nike Air Jordan 14 Shoes Sell (www.iofferkicks.com) Discount Nike Air Jordan 16 Exporter (www.iofferkicks.com) Discount Nike Air Jordan 17 Shoes Exporter (www.iofferkicks.com) Discount Nike Air Jordan 18 Offer (www.iofferkicks.com) Discount Nike Air Jordan 19 Shoes Offer (www.iofferkicks.com) Discount Nike Air Jordan 20 Manufacture (www.iofferkicks.com) Discount Nike Jordan 21 Shoes Manufacture (www.iofferkicks.com) EMAIL:IOFFERKICKS at GMAIL.COM MSN :IOFFERKICKS at MSN.COM From ShannonL at yogananda-srf.org Tue Dec 2 17:55:14 2008 From: ShannonL at yogananda-srf.org (ShannonL at yogananda-srf.org) Date: Tue, 2 Dec 2008 14:55:14 -0800 Subject: Hashlib py26 Message-ID: This feels a bit silly, but I am trying to encrypt some simple text with the new hashlib library and then decrypt it back into text. I can do this with M2Crypto RC4, but not the new hashlib. Could someone give me a quick example. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sturlamolden at yahoo.no Fri Dec 12 10:56:58 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 07:56:58 -0800 (PST) Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> Message-ID: <31443882-cb41-420b-8269-b1590581783d@c36g2000prc.googlegroups.com> On Dec 12, 4:55 pm, sturlamolden wrote: > def __setitem__(self, index, value): > if _buf[index] is not value: # given that _buf is the tuple's > internal buffer > raise TypeError, 'tuple' object does not support item > assignment bl?h, that should be self._buf[index] From sbergman27 at gmail.com Fri Dec 19 12:37:27 2008 From: sbergman27 at gmail.com (Steve Bergman) Date: Fri, 19 Dec 2008 09:37:27 -0800 (PST) Subject: Building a web questionnaire, can it be done in Python ? References: Message-ID: <07750b8c-3648-4214-b520-931142b4f0a0@z28g2000prd.googlegroups.com> The most popular choice for web apps, and the one I use myself, would be Django. You might post your question in the Django group: http://groups-beta.google.com/group/django-users The only thing that I see that could be a problem would be the legacy database. But that depends very much upon your exact situation. From tgrav at mac.com Sat Dec 6 12:21:39 2008 From: tgrav at mac.com (Tommy Grav) Date: Sat, 06 Dec 2008 12:21:39 -0500 Subject: Guido's new method definition idea In-Reply-To: References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> <8b8d1fb3-f49e-49bf-8cfe-eeee5ed16109@r37g2000prr.googlegroups.com> <014a932b$0$20670$c3e8da3@news.astraweb.com> Message-ID: <3CB45A5D-9C99-4167-BB00-53F72958B5F6@mac.com> On Dec 6, 2008, at 11:42 AM, bearophileHUGS at lycos.com wrote: > class ThisIsAClass: > def $some_method(arg1, arg2): > $value = arg1 + $foo + $bar + $baz * arg2 > ... I think my biggest problem with this is what got me off Perl. Add $, together with already used @ and maybe some other identifiers and I start loosing track of what each of the character means. It is fine when you are used to the language, but learning it becomes a harder proposition. self.foo is self-explanatory (no pun intended) to me, $foo is not. Cheers Tommy From rt8396 at gmail.com Fri Dec 12 14:41:21 2008 From: rt8396 at gmail.com (r) Date: Fri, 12 Dec 2008 11:41:21 -0800 (PST) Subject: newbie question... References: Message-ID: i was just giving you an example from my TextEditor.py script. this is how arg works lets say you have a script named MyScript.py --- import sys print sys.argv --- call the script with arguments > MyScript.py 99 100 ['C:\\Python25\\MyScript.py', '99', '100'] int(sys.argv[1]) -> 99 From warren at delsci.com Wed Dec 3 16:38:23 2008 From: warren at delsci.com (Warren DeLano) Date: Wed, 3 Dec 2008 13:38:23 -0800 Subject: "as" keyword woes Message-ID: <896B75251BA19745A529B1B867893FA50679C6@planet.delsci.local> A bottom line / pragmatic question... hopefully not a FAQ. Why was it necessary to make "as" a reserved keyword? And more to the point, why was it necessary to prevent developers from being able to refer to attributes named "as"? For example, this code breaks as of 2.6 / 3.0: Class C: Pass obj = C() obj.bs = 2 # valid obj.as = 1 # syntax error obj.cs = 3 # valid Just to be clear: I understand why it breaks, since "as" is now a keyword, I also know that one can use workarounds such as: obj.__dict__['as'] = 1 to maintain compatibility. What I want to understand is why this parser change was necessary in order to enable new 2.6/3.0 features. Was this change potentially avoidable? Why can't the parser distinguish between a standalone " as " keyword and ".as" used as an object/attribute reference? Couldn't we have continued along just fine using a smarter parser without elevating "as" to reserved status (and thus potentially breaking a 10+ years of existing code)? Thank you for enlighting me! (Unfortunately, our project may now have to maintain a branch at 2.5.x in order to preserve compatibility with existing third-party scripts & infrastructure which routinely rely upon "as" as an object method. Sigh.) Cheers, Warren From robert.kern at gmail.com Sun Dec 7 19:27:44 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 07 Dec 2008 18:27:44 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Terry Reedy wrote: > Robert Kern wrote: >> Terry Reedy wrote: >>> Rasmus Fogh wrote: > >>>> Personally I would like to get these !@#$%&* misfeatures removed, >>> >>> What you are calling a misfeature is an absence, not a presence that >>> can be removed. >> >> That's not quite true. > > In what way, pray tell. My statement still looks quite true to me. There is an explicit policy that __eq__() methods can return non-bools for various purposes. I consider that policy to a "presence that can be removed". There is no check because that policy exists, not the other way around. Anyways, this is really a semantic digression, and not particularly important. Peace? -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From googler.1.webmaster at spamgourmet.com Thu Dec 25 05:39:16 2008 From: googler.1.webmaster at spamgourmet.com (googler.1.webmaster at spamgourmet.com) Date: Thu, 25 Dec 2008 02:39:16 -0800 (PST) Subject: Python with PyGIL_Ensure? References: Message-ID: <0591a852-0f41-492f-9016-2bf603964a04@i20g2000prf.googlegroups.com> and merry christmas :) From tjreedy at udel.edu Mon Dec 1 15:45:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Dec 2008 15:45:58 -0500 Subject: end of print = lower productivity ? In-Reply-To: References: Message-ID: Alan G Isaac wrote: > I actually trust that the developers had good > reasons for this change, but I think it is > silly to argue that it is costless. Guido ever argued that. > The question is, what is the cost-benefit trade-off? Uniformity of language, flexibility, and removal of the >> hack that Guido hated after adding. Check the pydev discussions. > One obvious cost is that working at the > interpreter prompt is now slightly less > convenient. But neither 'print' nor 'print()' is needed at the interpreter prompt. > Just because the cost is small > does not mean it should not be offset by a > benefit. > > I am less sympathetic to the suggestion that > there is an inconvenience when working in > an editor, but clearly some people find one. That is the only time 'print' or 'print()' is needed. I find it a minor nuisance also, but then I should learn to touch-type () better anyway for all the other uses. > My preferred transition would have been to > retain the `print` statement but add a `printf` > function (i.e., the new `print` function). > Presumably many would find this a repulsive > redundancy and a needless maintenance headache. Yes. tjr From steve at REMOVE-THIS-cybersource.com.au Tue Dec 2 08:50:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Dec 2008 13:50:41 GMT Subject: performance question: dictionary or list, float or string? References: Message-ID: <01453507$0$20670$c3e8da3@news.astraweb.com> On Tue, 02 Dec 2008 03:41:29 -0800, bkamrani wrote: > Hi Python gurus! > I'm going to read in an Ascii file containing float numbers in rows and > columns (say 10 columns 500000 rows) for further numerical process. > Which format is best to save them in, eg, dictionary, list, or numpy > array when it comes to performance? That depends on: (1) What do you mean by performance? Speed or memory use? (2) Do you care about the performance of reading the data in, or the performance of working with the data later, or both? (3) What do you intend to do with the numbers later? > Will it be beneficial to convert all strings to float directly after > reading or it doesn't matter to save them as string and thereafter when > it comes to calculation convert them to floats? That depends on what you intend to do with them. Since you're doing numerical processing, it's probably a good idea to convert them to numbers rather than strings. -- Steven From Rick at youtellme.com Thu Dec 25 21:24:49 2008 From: Rick at youtellme.com (Rick van Hattem) Date: Fri, 26 Dec 2008 03:24:49 +0100 Subject: How to stop subprocesses from copying listening sockets Message-ID: <200812260324.50166.Rick@youtellme.com> Hi everyone, Recently I've started building a program that spawns new processes when requested via http, since the http interface doesn't need to be fancy I've just used the BaseHTTPServer module for this, but... it seems I'm running into a little problem. When spawning a new process (which forks itself into a daemon, but isn't too relevant in this case) the listening socket is copied to the new process. Evidently this results in the base process not being able to restart since the new spawned process starts listening on the port. Here's a simple example of what I mean. Assuming we've got the server like this: import subprocess import BaseHTTPServer server = BaseHTTPServer.HTTPServer(('', 1234), BaseHTTPServer.BaseHTTPRequestHandler) subprocess.Popen(['python', 'the_daemon.py']) With the_daemon.py being this: import time time.sleep(60) And we run the main server and kill it after that (i.e. using netstat to find the PID), we'll see that the new process which does nothing besides wait for 60 second will listen on port 1234 (use netstat to confirm). Anyone has an idea on how to circumvent this issue? Kind regards, Rick van Hattem PS: tested both on Fedora 8 using Python 2.5.1 and Gentoo Linux 2008 using Python 2.5.2 From clp at rebertia.com Mon Dec 8 17:29:01 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 8 Dec 2008 14:29:01 -0800 Subject: Calling function from a string In-Reply-To: <7bc1be6f-121e-409a-9e08-f2dd2a86f241@e25g2000vbe.googlegroups.com> References: <7bc1be6f-121e-409a-9e08-f2dd2a86f241@e25g2000vbe.googlegroups.com> Message-ID: <47c890dc0812081429o6a3226fanccaca84e903cd923@mail.gmail.com> On Mon, Dec 8, 2008 at 2:23 PM, Robert Dailey wrote: > Hi, > > I have a string representing the name of a function in Python 3.0. How > can I call the function name represented by this string *without* > creating a mapping? Assuming the function is within scope: return_val = vars()[the_string](arguments, go, here) Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > From rhodri at wildebst.demon.co.uk Wed Dec 10 19:33:32 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Thu, 11 Dec 2008 00:33:32 -0000 Subject: How to pass out the result from iterated function In-Reply-To: References: Message-ID: On Wed, 10 Dec 2008 20:16:56 -0000, JD wrote: > I got a iterated function like this: > > def iterSomething(list): > has_something = False > for cell in list: > if something in cell: > has_something = True > output = something > if has_something: > iterSomething(output) > else: > final_out = outupt > > The problem is how can I read this final_out outside of the function. > I tried the global statement, it seems not work. Any idea? Isn't this going to throw an exception anyway if 'something' doesn't appear in 'list'? You try assigning 'output' to 'final_out' with no guarantee that 'output' has ever been assigned to. -- Rhodri James *-* Wildebeeste Herder to the Masses From ajaksu at gmail.com Tue Dec 23 13:11:28 2008 From: ajaksu at gmail.com (ajaksu) Date: Tue, 23 Dec 2008 10:11:28 -0800 (PST) Subject: python3 urlopen(...).read() returns bytes References: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> <5496b34d-7ce4-4281-9f01-aed12dab9fd3@f33g2000vbf.googlegroups.com> <42ad842c-8d8a-4ff5-a721-0688b7ae20f7@41g2000yqf.googlegroups.com> Message-ID: <9480ac97-9c0b-445c-ad62-eb418a54f6a1@o40g2000yqb.googlegroups.com> On Dec 23, 12:51?pm, Christian Heimes wrote: > If you want to do it right ... It should be a clean patch against the > py3k svn branch Done > including documentation This thread is a good start :) > and a unit test. Doing this now. Daniel From de.slotenzwemmer at gmail.com Wed Dec 24 10:54:39 2008 From: de.slotenzwemmer at gmail.com (Dennis van Oosterhout) Date: Wed, 24 Dec 2008 16:54:39 +0100 Subject: =?ISO-8859-1?Q?object_ori=EBnted?= Message-ID: I know that python is an Object Ori?nted language but I was wondering if it gets used as a non-OOP also (by a good amount of people). -------------- next part -------------- An HTML attachment was scrubbed... URL: From collin.day.0 at gmail.com Thu Dec 18 21:27:35 2008 From: collin.day.0 at gmail.com (Collin D) Date: Thu, 18 Dec 2008 18:27:35 -0800 (PST) Subject: Factoring Polynomials References: <919062f9-765e-4279-aa26-2c130d4deacf@o4g2000pra.googlegroups.com> Message-ID: <4479b464-3a9b-4dd8-bf66-fea7d9471091@n33g2000pri.googlegroups.com> On Dec 18, 6:23?pm, "Russ P." wrote: > On Dec 18, 6:17?pm, Collin D wrote: > > > > > > > On Dec 18, 6:12?pm, Collin D wrote: > > > > On Dec 18, 11:37?am, collin.da... at gmail.com wrote: > > > > > I am trying to write a simple application to factor polynomials. I > > > > wrote (simple) raw_input lines to collect the a, b, and c values from > > > > the user, but I dont know how to implement the quadratic equation > > > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > > > into python. Any ideas? > > > > I completed the code: > > > > #import > > > from math import sqrt > > > > # collect data > > > a = float(raw_input('Type a value: ')) > > > b = float(raw_input('Type b value: ')) > > > c = float(raw_input('Type c value: ')) > > > > # create solver > > > def solver(a,b,c): > > > ? ? if b**2 - 4*a*c < 0: > > > ? ? ? ? return 'No real solution.' > > > ? ? else: > > > ? ? ? ? sol1 = -1 * b + (sqrt(b**2 - 4*a*c)) / 2*a > > > ? ? ? ? sol2 = -1 * b - (sqrt(b**2 - 4*a*c)) / 2*a > > > ? ? ? ? return (sol1, sol2) > > > > # execute > > > print solver(a,b,c) > > > > Thanks to everyone who helped... > > > This really expanded my knowledge on some of the mathematical > > > functions in Python. > > > UPDATE: > > ' > > > #import > > from math import sqrt > > > # collect data > > a = float(raw_input('Type a value: ')) > > b = float(raw_input('Type b value: ')) > > c = float(raw_input('Type c value: ')) > > > # create solver > > def solver(a,b,c): > > ? ? if b**2 - 4*a*c < 0: > > ? ? ? ? return 'No real solution.' > > ? ? else: > > ? ? ? ? sol1 = (-1 * b + (sqrt(b**2 - 4*a*c))) / 2*a > > ? ? ? ? sol2 = (-1 * b - (sqrt(b**2 - 4*a*c))) / 2*a > > ? ? ? ? return (sol1, sol2) > > > # execute > > print solver(a,b,c) > > You need to put your denominator, 2*a, in parens. The way it stands, > you are dividing by 2, then multiplying by a. That's not what you > want. > > Also, for better style, I suggest you compute the discriminanat once > and store it for reuse rather than repeating the expression three > times.- Hide quoted text - > > - Show quoted text - I see what you mean on the denominator and discriminant. Ill do that. From miki.tebeka at gmail.com Mon Dec 15 20:52:34 2008 From: miki.tebeka at gmail.com (Miki) Date: Mon, 15 Dec 2008 17:52:34 -0800 (PST) Subject: How can I return a non-zero status result from a python script? References: <74b53da4-bf07-431b-898b-49977f7a685c@r36g2000prf.googlegroups.com> Message-ID: <5a289491-662c-49f2-98c7-aae100078a8a@r15g2000prd.googlegroups.com> Hello, > How can I return a non-zero status result from the script? Just do a > return 1? at the end? raise SystemExit(1) HTH, -- Miki http://pythonwise.blogspot.com From eric at ericaro.net Mon Dec 8 05:55:56 2008 From: eric at ericaro.net (eric) Date: Mon, 8 Dec 2008 02:55:56 -0800 (PST) Subject: Determining whether a variable is less/greater than a range. References: <362ab93b-b804-4ebe-a22f-e422feb301c8@c1g2000yqg.googlegroups.com> Message-ID: On Dec 8, 11:44?am, "simonharrison... at googlemail.com" wrote: > Hi. I'm having another go at learning Python so I'll probably be > asking a few basic questions. Here is the first one. > > a = list(range(10, 21) > > b = 9 > > c = 21 > > How can I find out if b and c have values less or more than the values > in list a? > > Thanks. what about: a = list(range(10, 21)) def compare(value, list): m,M = min(list), max(list) return value>=m, value<=M b = 9 c = 21 print compare(b,a) print compare(c,a) for i in range (8, 25): print i, compare(i, a) """ (False, True) (True, False) 8 (False, True) 9 (False, True) 10 (True, True) 11 (True, True) 12 (True, True) 13 (True, True) 14 (True, True) 15 (True, True) 16 (True, True) 17 (True, True) 18 (True, True) 19 (True, True) 20 (True, True) 21 (True, False) 22 (True, False) 23 (True, False) 24 (True, False) """ it helps? From BrianVanderburg2 at aim.com Mon Dec 15 16:46:28 2008 From: BrianVanderburg2 at aim.com (Brian Allen Vanderburg II) Date: Mon, 15 Dec 2008 16:46:28 -0500 Subject: Limit traceback from most recent call In-Reply-To: <8ab4f9a8-3629-4f6a-bbf2-1deed8624215@w24g2000prd.googlegroups.com> References: <8ab4f9a8-3629-4f6a-bbf2-1deed8624215@w24g2000prd.googlegroups.com> Message-ID: <4946D034.30609@aim.com> yinon.me at gmail.com wrote: > On Dec 14, 8:07 pm, Brian Allen Vanderburg II > wrote: > > > Hi, > > The interface of extract_tb is: > traceback.extract_tb(tb, limit=None) > try to play with the 'limit' argument > > Good luck, > Yinon > -- > http://mail.python.org/mailman/listinfo/python-list > I have, but the limit argument shows the first items and not the last items (where the exception occurred): def a(): b() def b(): c() def c(): d() def d(): open('/path/to/fake/file') try: a(): except: print traceback.format_exc(limit=2) try: a(): except: print format_partial_exc(limit=2) Prints something like this Traceback (most recent call last): File "b.py", line 52, in ? a() File "b.py", line 19, in a b() IOError: [Errno 2] No such file or directory: '/path/to/fake/file' Traceback (most recent call last): File "b.py", line 25, in c d() File "b.py", line 29, in d handle=open('/path/to/fake/file', 'rt') IOError: [Errno 2] No such file or directory: '/path/to/fake/file' The second one (using format_partial_exc) prints the last two items of the traceback instead of the first, showing the error is line 29 in function d, the first one limits the traceback but gives no indication of where the error occurred. Brian A. Vanderburg II -------------- next part -------------- An HTML attachment was scrubbed... URL: From zevboy at gmail.com Fri Dec 5 07:23:44 2008 From: zevboy at gmail.com (Huytason) Date: Fri, 5 Dec 2008 20:23:44 +0800 Subject: i use the urllib question Message-ID: i use pthon 3.0 today python code: import urllib.request then use PyRun_StringFlag to run it. get this it's a bug? -------------- next part -------------- An HTML attachment was scrubbed... URL: From geon at post.cz Fri Dec 26 11:44:08 2008 From: geon at post.cz (Pavel Kosina) Date: Fri, 26 Dec 2008 17:44:08 +0100 Subject: tkinter 3.0 multiple keyboard events together In-Reply-To: <600d4b68-6fe2-4c2c-b425-1a739430bb54@s9g2000prg.googlegroups.com> References: <600d4b68-6fe2-4c2c-b425-1a739430bb54@s9g2000prg.googlegroups.com> Message-ID: <495509D8.10105@post.cz> janislaw napsal(a): > On 26 Gru, 05:52, Pavel Kosina wrote: > >> Is it possible to catch in an event more that one key from keyboard? In >> my code, I can handle always the only one, the first I press, the others >> are omitted. Say, I press both "4" and "8" and only "4" is catched. >> >> def movePlayer(event): >> print (event.keysym) >> > Each keypress triggers another event. Fortunately there are two types > of events: reaction to press and release. The logic to write to > recognize those as simultaneous clicks is up to you :) > Might you give me a little bit more? Just a link to a site where this is explained and showed would be OK. I really did my best but everything is bad. geon From duncan.booth at invalid.invalid Tue Dec 23 08:30:25 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Dec 2008 13:30:25 GMT Subject: Are python objects thread-safe? References: <5306b56c-eb8c-4148-b426-013caa871375@b41g2000pra.googlegroups.com> Message-ID: Aaron Brady wrote: > Th.1 Th.2 > a=X > a=Y > a=Z > > You are saying that if 'a=Z' interrupts 'a=Y' at the wrong time, the > destructor for 'X' or 'Y' might not get called. Correct? In serial > flow, the destructor for X is called, then Y. No, the destructors will be called, but the destructors can do pretty much anything they want so you can't say the assignment is atomic. This isn't actually a threading issue: you don't need multiple threads to experience werid issues here. If you do strange things in a destructor then you can come up with confusing code even with a single thread. > >> Other nasty things can happen if you use dictionaries from multiple >> threads. You cannot add or remove a dictionary key while iterating over >> a dictionary. This isn't normally a big issue, but as soon as you try to >> share the dictionary between threads you'll have to be careful never to >> iterate through it. > > These aren't documented, IIRC. Did you just discover them by trial > and error? > It is documented, but I can't remember where for Python 2.x. For Python 3, PEP 3106 says: "As in Python 2.x, mutating a dict while iterating over it using an iterator has an undefined effect and will in most cases raise a RuntimeError exception. (This is similar to the guarantees made by the Java Collections Framework.)" -- Duncan Booth http://kupuguy.blogspot.com From gagsl-py2 at yahoo.com.ar Fri Dec 12 20:55:03 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 12 Dec 2008 23:55:03 -0200 Subject: Py_GetPath() C API in python 3 References: <772bb62b-1ef1-4ffa-90f6-c1cbdc728fdd@q30g2000prq.googlegroups.com> Message-ID: En Fri, 12 Dec 2008 04:50:06 -0200, stalex escribi?: >> I want to build a new, requires total control, python interpreter. So >> I implement my own version of Py_GetPath(), Py_GetPrefix(), >> Py_GetExecPrefix() and Py_GetProgramFullPath(). When compiling, I >> always get error messages, for each API function, look like >> followings: >> >> /opt/python-3.0/lib/python3.0/config/libpython3.0.a(getpath.o)(.text >> +0x211c): In function `Py_GetPath': >> ./Modules/getpath.c:739: multiple definition of `Py_GetPath' >> myApp.o(.text+0x0):/home/alex/workspace/develop/src/myApp.c:11: first >> defined here >> /usr/bin/ld: Warning: size of symbol `Py_GetPath' changed from 126 in >> system.o to 32 in /opt/python-3.0/lib/python3.0/config/libpython3.0.a >> (getpath.o) >> collect2: ld returned 1 exit status Looks like you added your own implementation of those functions (/home/alex/...myApp.c) but forgot to remove the original one (Modules/getpath.c) -- Gabriel Genellina From python at rgbaz.eu Thu Dec 25 06:34:40 2008 From: python at rgbaz.eu (Python) Date: Thu, 25 Dec 2008 12:34:40 +0100 Subject: os.system('cls') In-Reply-To: References: Message-ID: <05BADA85-33ED-48BF-B251-2CC830D6D55E@rgbaz.eu> On 25 dec 2008, at 11:22, Dennis van Oosterhout wrote: > Hi there! I was searching for a way to clear the 'DOS screen'/ > command screen etc. and found that os.system('cls') works for this. > I was just wondering where I can find al the commands which can be > used for os.system(). I searched with google but I didn't find an > answer. In the official python tutorial it says os.system('command') > executes the command, but it doesn't say which commands exist (or > I'm just blind). > > Does anyone have an answer for this question? > > Thanks, > > Devilly Hey Deville, os.system() executes commands that you usually use in a shell outside python. so in the case of you being a windows user, you replace 'command' with any DOS command. gr Arno From marduk at letterboxes.org Wed Dec 3 09:57:33 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Wed, 03 Dec 2008 09:57:33 -0500 Subject: Obama's Birth Certificate - Demand that US presidential electors investigate Obama's eligibility In-Reply-To: <6cf32afd-f167-4c3e-884a-48452eaa8f82@w34g2000yqm.googlegroups.com> References: <89pZk.9151$be.4743@nlpi061.nbdc.sbc.com> <6cf32afd-f167-4c3e-884a-48452eaa8f82@w34g2000yqm.googlegroups.com> Message-ID: <1228316253.29326.0.camel@brotherus.rdu.redhat.com> This has nothing to do with Python. Please take this thread to cares.who.someone. From philip at semanchuk.com Mon Dec 29 13:19:22 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Mon, 29 Dec 2008 13:19:22 -0500 Subject: SQL, lite lite lite In-Reply-To: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> Message-ID: On Dec 29, 2008, at 1:06 PM, Aaron Brady wrote: > I don't think relational data can be read and written very easily in > Python. There are some options, such as 'sqllite3', but they are not > easy. 'sqllite3' statements are valid SQL expressions, which afford > the entire power of SQL, but contrary to its name, it is not that > 'lite'. To me, 'lite' is something you could learn (even make!) in an > afternoon, not a semester; something the size of an ActiveState > recipe, or a little bigger, maybe a file or two. Hi Aaron, The "lite" part of SQLite refers to its implementation more than its feature set. In other words, SQLite doesn't promise to make SQL easier, it promises many of the features of a big, heavy relational database (e.g. Postgres, MySQL, Oracle, etc.) but in a small, light package. I can see why you'd be disappointed if you were expecting the former. IMHO it does quite well at the latter. After a look at the syntax you're proposing, I wonder how you feel it differs from ORMs like SQLAlchemy (for instance). Cheers Philip From tjreedy at udel.edu Mon Dec 8 19:26:37 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Dec 2008 19:26:37 -0500 Subject: RuntimeError: dictionary changed size during iteration In-Reply-To: <274eb282-1635-40ca-95af-b82271c57802@v4g2000yqa.googlegroups.com> References: <274eb282-1635-40ca-95af-b82271c57802@v4g2000yqa.googlegroups.com> Message-ID: Robert Dailey wrote: > stuff = vars() >>> vars() is globals() True > for key in stuff: You just changed globals, which is aliased as stuff. Stuff changes. > print( key, '--', stuff[key] ) > > > > I get the following error message: > ('CopyEmotionFX', '--', ) > Traceback (most recent call last): > File "C:\IT\work\jewett\depends.py", line 12, in > for key in stuff: > RuntimeError: dictionary changed size during iteration > > Why is this happening? From bockman at virgilio.it Wed Dec 31 04:01:11 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: Wed, 31 Dec 2008 10:01:11 +0100 Subject: select.select and socket.setblocking In-Reply-To: References: <495a661d$0$11384$5fc30a8@news.tiscali.it> Message-ID: <495b34d8$0$11387$5fc30a8@news.tiscali.it> Grant Edwards ha scritto: > On 2008-12-30, Francesco Bochicchio wrote: > >> 3. AFAIK (sorry, I feel acronym-ly today ;), there is no difference in >> select between blocking and non-blocking mode. The difference is in the >> recv (again, assuming that you use TCP as protocol, that is AF_INET, >> SOCK_STREAM), which in the blocking case would wait to receive all the >> bytes that you requested, > > No, in blocking mode it will wait to receive _some_ data (1 or > more bytes). The "requested" amount is strictly an upper > limit: recv won't return more than the requested number of > bytes, but it might return less. > Uhm. In my experience, with TCP protocol recv only returned less than the required bytes if the remote end disconnects. I always check the returned value of recv and signal an error if the read bytes are less than the expected ones, but this error is never occurred (and its about 20 years that I use sockets in various languages and various flavor of unix and occasionally on windows. Maybe have always been lucky ? :-) And, on some unices system call recv also returns when a signal interrupts the syscall, but I half-remember reading that python recv in such a case repeat the system call by itself ... although this might be only my desire ... > In non-blocking mode, it will always return immediately, either > with some data, no data (other end closed), or an EAGAIN or > EWOULDBLOCK error (I forget which). > >> [...] I myself tend to avoid using non-blocking sockets, since >> blocking sockets are much easier to handle... > > That depends on whether you can tolerate blocking or not. In > an event-loop, blocking is generally not allowed. > What I usually do, when I cannot block is: - use socket in blocking mode - do a select with a very small timeout and do a recv only if the select returns with input events - (with TCP) do a recv for the exact amount of bytes that I expect ( this mean having a user protocol that carries the message size in the header, but this is usually the case ). This usually worked for me. If my process (or thread) has only to deal with socket I/O, I make a blocking select, and then make an 'exact' recv on whichever socket the select signals. Ciao ---- FB From jenn.duerr at gmail.com Thu Dec 11 21:15:59 2008 From: jenn.duerr at gmail.com (noydb) Date: Thu, 11 Dec 2008 18:15:59 -0800 (PST) Subject: Rename of .mdb file -- lock Message-ID: <4049f296-2a04-4eee-9f09-aa37a973a8cf@r40g2000yqj.googlegroups.com> All, I have the code below, which unzips a zipfile containing only one file. Once it is unzipped, I want to rename the file based on a user provided name. But I get this (WindowsError: [Error 32] The process cannot access the file because it is being used by another process) error, which does not make sense to me as no other apps are open. Any suggestions? Thanks! ****CODE**** # Declare the zip file directory and name (shouldn't change, in a permanent location) mdb_zip = ("C:\\ProjWork\\mdb_geoDB_91.zip") output_dir = ("C:\\Temp") # ZipFile for read z = zipfile.ZipFile(mdb_zip, 'r') zFile = z.namelist() # Put contents of zipfile into a list zList = z.namelist() # Loop thru list, write zipfile contents to new directory for zItem in zList: print "Unpacking",zItem zRead = z.read(zItem) z1File = open(os.path.join(output_dir, zItem),'wb') z1File.write(zRead) z1File.close print "Finished extracting zip file" uChoice = "test44.mdb" ## to be user chosen someday new91mdb = os.path.join(output_dir, zItem) # C:\TEMP\GDB_9_1.mdb ##os.rename(new91mdb, (os.path.join(output_dir, uChoice))) os.rename(new91mdb, (os.path.join(output_dir, "C:\TEMP\test1.mdb"))) del new91mdb From bearophileHUGS at lycos.com Fri Dec 5 10:09:27 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 5 Dec 2008 07:09:27 -0800 (PST) Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> Message-ID: <5926cb50-e53f-4e9e-8672-b4e29e2280b5@r36g2000prf.googlegroups.com> Andreas Waldenburger: > Whenever has it been a pythonic ideal to "not allow" stuff? You get > warnings. Everything else is up to you. It's a strong source for bugs, especially for newbies, that I have hoped to see removed from Python3 (my first request of this was years ago). I was nearly sure to see this wart removed from Python3, and now I hear it's presents still. I don't understand why they haven't fixed it. Then this is the third thing I don't like of Python3 (the other two being the removal of automatic tuple unpacking in function signature and the wart of literals for empty set/dict). Bye, bearophile From ianare at gmail.com Tue Dec 16 12:09:40 2008 From: ianare at gmail.com (=?ISO-8859-1?B?aWFuYXLp?=) Date: Tue, 16 Dec 2008 09:09:40 -0800 (PST) Subject: Python plugin for Netbeans References: <21z1l.218500$FR.506807@twister1.libero.it> Message-ID: <8d2cc75b-3483-46a0-87f5-92edddf993d4@r10g2000prf.googlegroups.com> On Dec 15, 3:23?pm, a wrote: > Netbeans added a python plugin to its plugin repository. > Do you tried it? What do you think about this plugin? If you like netbeans already it's great to finally have python officially supported. I find netbeans to be easier to use than eclipse. From musiccomposition at gmail.com Sun Dec 7 23:01:31 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sun, 7 Dec 2008 20:01:31 -0800 (PST) Subject: Python for kids? References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> Message-ID: On Dec 7, 2:13?pm, "Russ P." wrote: > I have a 12-year-old son who spends too much time playing Xbox live > and watching silly YouTube videos. I would like to try to get him > interested in programming. Is anyone aware of a good book or website > that addresses this concern, preferably (but not necessarily) using > Python? I could try to teach him Python myself, but I'm afraid I would > just frustrate him and kill his interest in programming. I did a > Google search and found a few things, but not a lot. Thanks. Perhaps what he really needs is some time away from the screen. From nick at craig-wood.com Wed Dec 3 09:30:48 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 03 Dec 2008 08:30:48 -0600 Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> <258cf433-f6c9-43e7-a235-f5f6b2b6433f@j39g2000yqn.googlegroups.com> <33b4cc2f-2311-491c-a2e6-9cc5452b1a6b@g38g2000yqd.googlegroups.com> <2772646a-623f-400b-a606-281a7e3220d4@20g2000yqt.googlegroups.com> Message-ID: Slaunger wrote: > On 3 Dec., 11:30, Nick Craig-Wood wrote: > > > ? ? ? ? ?cls = self.__class__ > > > ? ? ? ? ?if attr_name in cls.data_attr_names: > > > > self.data_attr_names should do instead of cls.data_attr_names unless > > you are overriding it in the instance (which you don't appear to be). > > Yeah, I know. I just like the cls notation for code readability > because it tells you that it is a class attribute, which is not > instance- dependent. > > That may be legacy from my Java past, where I used to do it that > way. I know perfectly well that self. would do it. i just find > that notation a little misleading I quite like it... It looks in the instance, then in the class which I find to be very elegant - you can set a default in the class and override it on a per object or per subclass basis. > > I think you want setattr() here - __dict__ is an implemetation detail > > - classes with __slots__ for instance don't have a __dict__. ?I'd > > probably do this > > Oh my, I did not know that. __slots__?? Something new I got to > understand. But you are right. thanks! > > > > > ? ? ? ? ? ? ? ? ? ?for k, v in zip(("I1", "Q1", "I2", "Q2"), bytes_to_data(buf)): > > ? ? ? ? ? ? ? ? ? ? ? ?setattr(self, k, v) > > ? ? ? ? ? ? ? ? ? ?return object.__getattr__(self, attr_name) > > > And perhaps even more readable (how I do it now, no need to call > __getattr__ for an attribute, whcih is already there): > ... > for attr, value in zip(cls.data_attr_names, > bytes_to_data(buf)): > setattr(self, attr, value) > > return getattr(self, attr_name) I wrote the object.__getattr__ call to stop recursion troubles. If you are sure you've set the attribute then plain getattr() is OK I guess... > In this process I have actaully managed to isolate all the > ...OnDemand stuff in an abstract PayloadOnDemand class > > I can now use this "decorator-like"/helper class to very easily > make an ...OnDemand variant of a class by just doing multiple > inheritance - no implementation: > > class PayloadBaconAndEggsOnDemand(PayloadOnDemand, PayloadBaconAndEggs): pass You've reinvented a Mixin class! http://en.wikipedia.org/wiki/Mixin It is a good technique. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From rt8396 at gmail.com Mon Dec 1 15:29:25 2008 From: rt8396 at gmail.com (r) Date: Mon, 1 Dec 2008 12:29:25 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <3a30f601-7128-4e5f-a97e-9f899404912c@o40g2000prn.googlegroups.com> <4f31c483-8382-480e-8417-b7eef1b1792d@z1g2000yqn.googlegroups.com> <8c856b01-7f0c-4d5b-a1d2-cfe7dc74389f@w3g2000yqc.googlegroups.com> <1680020c-521c-4498-8e74-92e99c03da6b@w35g2000yqm.googlegroups.com> <0d9d2404-cb3f-4390-b97c-79251db8ac95@k8g2000yqn.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> Message-ID: Rome is Burning! Pay particular attention to the second paragraph. Narcissistic culture Main article: The Culture of Narcissism Historian and social critic Christopher Lasch described this topic in his book, "The Culture of Narcissism",[3] published in 1979. He defines a narcissistic culture as one in which every activity and relationship is defined by the hedonistic need to acquire the symbols of spiritual wealth, this becoming the only expression of rigid, yet covert, social hierarchies. It is a culture where liberalism only exists insofar as it serves a consumer society, and even art, sex and religion lose their liberating power. In such a society of constant competition, there can be no allies, and little transparency. The threats to acquisitions of social symbols are so numerous, varied and frequently incomprehensible, that defensiveness, as well as competitiveness, becomes a way of life. Any real sense of community is undermined -- or even destroyed -- to be replaced by virtual equivalents that strive, unsuccessfully, to synthesize a sense of community. It can mean also many other things. Contrary to Lasch, Bernard Stiegler argues in his book, Aimer, s?aimer, nous aimer: Du 11 septembre au 21 avril, that consumer capitalism is in fact destructive of what he calls primordial narcissism, without which it is not possible to extend love to others. -food for thought- From tjreedy at udel.edu Thu Dec 4 20:45:16 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Dec 2008 20:45:16 -0500 Subject: Running Python 2 and Python 3 on the same machine In-Reply-To: <49387f7e$0$27857$9b622d9e@news.freenet.de> References: <1228424486.5873.6.camel@linux-3eb6.site> <49387f7e$0$27857$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: >> Since the source code is incompatible, I was expecting the Python >> executable to have a new name such as 'python3' > > It does: the executable is called python3.0. Why do you say that? As I reported on the py3 list when requesting a new name -- in particular, python3, the new python is installed on WinXP as python.exe and pythonw.exe!!! The includes the new 3.0 release. From jason.scheirer at gmail.com Tue Dec 16 17:56:02 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Tue, 16 Dec 2008 14:56:02 -0800 (PST) Subject: AIM client code for Python? References: Message-ID: On Dec 16, 9:54?am, Joe Strout wrote: > I'd like to write an AIM bot in Python. ?I found and tried > , but it doesn't work for me: > > Connecting... > Traceback (most recent call last): > ? ?File "aimbot-1.py", line 17, in > ? ? ?bot.go() > ? ?File "/Users/jstrout/Documents/Python-Dev/AIMbot/toc.py", line 62, ? > in go > ? ? ?self.process_loop() > ? ?File "/Users/jstrout/Documents/Python-Dev/AIMbot/toc.py", line 156, ? > in process_loop > ? ? ?event = self.recv_event() > ? ?File "/Users/jstrout/Documents/Python-Dev/AIMbot/toc.py", line 230, ? > in recv_event > ? ? ?dtemp = self._socket.recv(buflen - len(data)) > socket.error: (54, 'Connection reset by peer') > > I wrote to the author a week ago, but never got a reply. ?It could be ? > as simple as changing the server addresses in toc.py, currently: > > TOC_SERV_AUTH = ("login.oscar.aol.com", 29999 ) > TOC_SERV = ( "toc.oscar.aol.com", 9898 ) > > ...but I don't understand AIM well enough to know the correct values ? > (and was rather hoping that I wouldn't have to). > > Does anyone know how to get Py-TOC to work, or have another Python TOC ? > implementation to suggest? > > Thanks, > - Joe What I did once to get a bot working was to use Pidgin, and communicate with the instance of Pidgin over D-Bus. This has the happy side effect of making the bot multi-protocol and handling all the connection drop issues and the like, as well as allowing for you to intervene in conversations. class HookForAccount(object): def __init__(self, usernames=None): if usernames is not None: if isinstance(usernames, basestring): usernames = [usernames] usernames = set([x.lower() for x in usernames]) bus = dbus.SessionBus() obj = bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject") self.purple = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface") self.accountids = set() for account in self.purple.PurpleAccountsGetAllActive(): if usernames is None or self.purple.PurpleAccountGetUsername(account).lower() in usernames: print self.purple.PurpleAccountGetUsername(account) self.accountids.add(account) bus.add_signal_receiver(self.got_im, dbus_interface="im.pidgin.purple.PurpleInterface", signal_name="ReceivedImMsg") def got_im(self, code, screenname, message, conversation_id, flags): time.sleep(1.75) self.purple.PurpleConvImSend(self.purple.PurpleConvIm (conversation_id), "HELLO!") if __name__ == "__main__": logging.getLogger().setLevel(0) dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) HookForAccount(sys.argv[1:] or None) loop = gobject.MainLoop() loop.run() From mirandasnailvv at gmail.com Fri Dec 19 19:43:11 2008 From: mirandasnailvv at gmail.com (mirandasnailvv at gmail.com) Date: Fri, 19 Dec 2008 16:43:11 -0800 (PST) Subject: download nero express for free - Free Message-ID: download nero express for free . . . *******CLICK HERE******** http://club247.cn/download-nero-express-for-free ***************************** . . . . . . . . . . . . download nero express for free From joshua at joshuakugler.com Thu Dec 11 21:47:06 2008 From: joshua at joshuakugler.com (Joshua Kugler) Date: Thu, 11 Dec 2008 17:47:06 -0900 Subject: Disputing Cookie.py's definition of valid characters Message-ID: Some investigation today revealed that Cookie.py thinks these are valid characters for names and values of cookies: _LegalCharsPatt = r"[\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\=]" The rest, presumably being encoded via %NN. I notice that (), {}, and others made the list, but not []. Is there a reason for that? I didn't find a list of valid characters anywhere in the cookie RFC (disclaimer: I didn't read the HTTP 1.1 RFC). The reason this got brought up: I'm parsing some cookies that have been set by a PHP app (out of my control, no flames please) and it has cookies of the form name[0], name [1], and so on which get transformed to arrays on the server side such that: $_COOKIES['name'] Will be a list with values from name[0], name[1]. Well, when these are parsed by Cookie.py, they simply vanish because it doesn't like the [ and ] in the cookie names. But these are set successfully and the browser side, and are sent back to the server successfully. Since this is a CherryPy app, it's not as easy as just subclassing the cookie class I want. I suppose I could sub class and then monkey patch CherryPy, but that feels nasty. Hmm...local copy of Cookie.py that comes before /usr/lib/python2.5 in the site path would work too. Thoughts? Is this a bug in Cookie.py, or is PHP out of spec to send cookies with [ and ] in the name? j From clp at rebertia.com Mon Dec 29 07:18:03 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 29 Dec 2008 04:18:03 -0800 Subject: AttributeError: 'module' object has no attribute 'DatagramHandler' (ubuntu-8.10, python 2.5.2) In-Reply-To: <4c6f0831-c05f-401f-b956-376600b38e06@r15g2000prd.googlegroups.com> References: <4c6f0831-c05f-401f-b956-376600b38e06@r15g2000prd.googlegroups.com> Message-ID: <47c890dc0812290418h14b89435nc019d78e46dbec0d@mail.gmail.com> On Mon, Dec 29, 2008 at 4:08 AM, Tzury Bar Yochay wrote: > $ ~/devel/ice/snoip/freespeech$ python > Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) > [GCC 4.3.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import logging >>>> logging.DatagramHandler > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute 'DatagramHandler' >>>> > > > That is odd since the documentation says there is DatagramHandler for > module logging >From http://docs.python.org/library/logging.html#logging.DatagramHandler : "The DatagramHandler class, located in the logging.handlers module [...]" >From http://docs.python.org/library/logging.html#logging-levels : "The StreamHandler and FileHandler classes are defined in the core logging package. The other handlers are defined in a sub- module, logging.handlers." There's your answer. I do agree though that the "class logging.DatagramHandler" line in the docs is misleading to say the least. Perhaps a docs bug should be filed... Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From Slaunger at gmail.com Tue Dec 9 16:27:37 2008 From: Slaunger at gmail.com (Slaunger) Date: Tue, 9 Dec 2008 13:27:37 -0800 (PST) Subject: Best way to report progress at fixed intervals References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> Message-ID: On 9 Dec., 19:35, rdmur... at bitdance.com wrote: > > I felt like a little lunchtime challenge, so I wrote something that > I think matches your spec, based on your sample code. ?This is not > necessarily the best implementation, but I think it is simpler and > clearer than yours. ?The biggest change is that the work is being > done in the subthread, while the main thread does the monitoring. > Well, thank you for spending your lunch time break on my little problem. > It would be fairly simple to enhance this so that you could pass > arbitrary arguments in to the worker function, in addition to > or instead of the loop counter. > Yes, I agree > ----------------------------------------------------------------------- > """ > Test module for testing generic ways of displaying progress > information at regular intervals. > """ > import random > import threading > import time > > def work(i): > ? ? ?""" > ? ? ?Dummy process function, which takes a random time in the interval > ? ? ?0.0-0.5 secs to execute > ? ? ?""" > ? ? ?print "Work step %d" % i > ? ? ?time.sleep(0.5 * random.random()) > > class Monitor(object): > ? ? ?""" > ? ? ?This class creates an object that will execute a worker function > ? ? ?in a loop and at regular intervals emit a progress report on > ? ? ?how many times the function has been called. > ? ? ?""" > > ? ? ?def dowork(self): > ? ? ? ? ?""" > ? ? ? ? ?Call the worker function in a loop, keeping track of how > ? ? ? ? ?many times it was called in self.no > ? ? ? ? ?""" > ? ? ? ? ?for self.no in xrange(self.max_iter): > ? ? ? ? ? ? ?self.func(self.no) > > ? ? ?def __call__(self, func, verbose=True, max_iter=20, progress_interval=1.0): I had to look up the meaning of __call__, to grasp this, but I get your methology > ? ? ? ? ?""" > ? ? ? ? ?Repeatedly call 'func', passing it the loop count, for max_iter > ? ? ? ? ?iterations, and every progress_interval seconds report how > ? ? ? ? ?many times the function has been called. > ? ? ? ? ?""" > ? ? ? ? ?# Not all of these need to be instance variables, but they might > ? ? ? ? ?# as well be in case we want to reference them in an enhanced > ? ? ? ? ?# dowork function. > ? ? ? ? ?self.func = func > ? ? ? ? ?self.verbose = verbose > ? ? ? ? ?self.max_iter=max_iter > ? ? ? ? ?self.progress_interval=progress_interval > > ? ? ? ? ?if self.verbose: > ? ? ? ? ? ? ?print ("Work through all %d steps reporting progress every " > ? ? ? ? ? ? ? ? ?"%3.1f secs...") % (self.max_iter, self.progress_interval) > > ? ? ? ? ?# Create a thread to run the loop, and start it going. > ? ? ? ? ?worker = threading.Thread(target=self.dowork) > ? ? ? ? ?worker.start() > > ? ? ? ? ?# Monitoring loop. > ? ? ? ? ?loops = 0 > ? ? ? ? ?# We're going to loop ten times per second using an integer count, > ? ? ? ? ?# so multiply the seconds parameter by 10 to give it the same > ? ? ? ? ?# magnitude. > ? ? ? ? ?intint = int(self.progress_interval*10) Is this not an unnecessary complication? > ? ? ? ? ?# isAlive will be false after dowork returns > ? ? ? ? ?while worker.isAlive(): > ? ? ? ? ? ? ?loops += 1 > ? ? ? ? ? ? ?# Wait 0.1 seconds between checks so that we aren't chewing > ? ? ? ? ? ? ?# CPU in a spin loop. > ? ? ? ? ? ? ?time.sleep(0.1) Why not just call this with progress_interval directly? > ? ? ? ? ? ? ?# when the modulus (second element of divmod tuple) is zero, > ? ? ? ? ? ? ?# then we have hit a new progress_interval, so emit the report. And then avoid this if expression? > ? ? ? ? ? ? ?if not divmod(loops, intint)[1]: > ? ? ? ? ? ? ? ? ?print "Processed %d of %d" % (self.no, self.max_iter) > > ? ? ? ? ?if verbose: > ? ? ? ? ? ? ?print "Finished working through %d steps" % max_iter > > if __name__ == "__main__": > ? ? ?#Create the monitor. > ? ? ?monitor = Monitor() > ? ? ?#Run the work function under monitoring. > ? ? ?monitor(work) I was unfamiliar with this notation, but now I understand it simply invokes __call__. Thank you for showing me that! OK. I agree this is a more elegant implementation, although I my mind, I find it more natural if the reporting goes on in a subthread, but that is a matter of taste, I guess. Anyway: Thank you again for spending your lunch break on this! -- Slaunger From fetchinson at googlemail.com Wed Dec 31 15:30:18 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 31 Dec 2008 12:30:18 -0800 Subject: PIL on 3.x? In-Reply-To: References: Message-ID: > Does anyone know if PIL will be ported to the 3.x branch? Actually, Guilherme Polo has ported PIL 1.1.6 to python 3.0: http://mail.python.org/pipermail/image-sig/2008-December/005338.html Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From eric at ericaro.net Tue Dec 9 10:44:03 2008 From: eric at ericaro.net (eric) Date: Tue, 9 Dec 2008 07:44:03 -0800 (PST) Subject: 'pretty print' for built in types References: <051e3a97-b9bc-4a67-8896-93628ca19f59@r15g2000prd.googlegroups.com> Message-ID: On Dec 9, 4:31?pm, Robert Dailey wrote: > Hi, > > Is there a built in way to 'pretty print' a dict, list, and tuple > (Amongst other types)? Dicts probably print the ugliest of them all, > and it would be nice to see a way to print them in a readable way. I > can come up with my own function to do this, but I don't want to do > this if I don't have to. you can have a look at [http://code.google.com/p/prynt/ prynt], it provides some simple functions, to pretty print into RestructuredText, and then, when the process is finished (it's an option) show the 'console' converted into html. dict are transformed into definition: key: value key: value it helps ? From jstroud at mbi.ucla.edu Mon Dec 15 00:08:33 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 14 Dec 2008 21:08:33 -0800 Subject: Looking for the best way to translate an idiom In-Reply-To: References: Message-ID: Aahz wrote: > In article , > James Stroud wrote: >> In case its not obvious: > > Ah, so that's where Bruno's extra apostrophe came from! ;-) > > > (Sorry about the spelling flame, but seeing three posts in quick > succession with incorrect spelling of its/it's pushed me into making a > public comment.) Yes. I think it was the British who decided that the apostrophe rule for "it" would be reversed from normal usage relative to just about every other noun. I'm not sure the purpose--maybe it was to give compulsive proofreaders a raison d'etre. From hjtoi-better-remove-when_replying at comcast.net Mon Dec 15 13:01:46 2008 From: hjtoi-better-remove-when_replying at comcast.net (Heikki Toivonen) Date: Mon, 15 Dec 2008 10:01:46 -0800 Subject: pexpect and inconsistent exit values Message-ID: I don't seem to be able to figure out how to get the exit values of commands executed with pexpect reliably. Here's first with regular shell: heikki at ubuntu:~$ true; echo $? 0 Let's try with pexpect. Below is the program: ---CLIP--- import sys, pexpect cmd = "true" print 'cmd=', cmd child = pexpect.spawn(cmd, logfile=sys.stdout) child.close() print 'child exitstatus=', child.exitstatus print 'child signalstatus=', child.signalstatus print 'child status=', child.status ---CLIP--- The output: (fabexp)heikki at ubuntu:~/python_virtualenvs/fabexp$ python dep.py cmd= true child exitstatus= 1 child signalstatus= None child status= 256 (fabexp)heikki at ubuntu:~/python_virtualenvs/fabexp$ python dep.py cmd= true child exitstatus= 0 child signalstatus= None child status= 0 (fabexp)heikki at ubuntu:~/python_virtualenvs/fabexp$ python dep.py cmd= true child exitstatus= None child signalstatus= 1 child status= 1 I have tried various other commands, and I just can't seem to be able to get reliable exit codes from commands I execute. Any ideas what is going on? -- Heikki Toivonen - http://heikkitoivonen.net From jonas.esp at googlemail.com Mon Dec 22 03:58:35 2008 From: jonas.esp at googlemail.com (Kless) Date: Mon, 22 Dec 2008 00:58:35 -0800 (PST) Subject: HMAC with RIPEMD-160 References: Message-ID: <0152ffa0-7f06-4e94-8a6c-743199e5010c@f3g2000yqf.googlegroups.com> On 21 dic, 23:53, "Chris Rebert" wrote: > On Sun, Dec 21, 2008 at 4:21 AM, Kless wrote: > > Is there any way of use HMAC with RIPEMD-160? > > > Since that to create a ripemd-160 hash there is to use: > > ? ?h = hashlib.new('ripemd160') > > it looks that isn't possible > > > For HMAC-SHA256 would be: > > --------- > > import hashlib > > import hmac > > > hm = hmac.new('key', msg='message', digestmod=hashlib.sha256) > > Untested, but should work according to the docs: > hm = hmac.new('key', msg='message', digestmod=lambda: hashlib.new('ripemd160')) > It works, thank you From tjreedy at udel.edu Sat Dec 6 16:13:37 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 06 Dec 2008 16:13:37 -0500 Subject: slow Python 3.0 write performance? In-Reply-To: <493A698D.5080807@cheimes.de> References: <493A698D.5080807@cheimes.de> Message-ID: Christian Heimes wrote: > Istvan Albert wrote: >> A previous poster suggested that in this case the slowdown is caused >> by the new io code being written in python rather than C. > > For text mode Python 3's write() method is slower than Python 2.x's > method because all text is encoded. The slowdown is mostly caused by > additional code for line ending detection and decoding/encoding. The new > io library does more than the old file object > > So far the new io library hasn't been optimized yet, too. Please give it > some time and report speed issues at http://bugs.python.org/. On WinXP, tests 3 times each ------------------------------------------- 3.0 --- import time line = 'a'*99 + '\n' text = line*500000 start=time.time() open('wtest', 'w').write(text) print(time.time()-start) # 3.4 to 4.0 import time line = 'a'*99 + '\n' text = line*500000 start=time.time() text = bytes(line,'ascii')*500000 print(time.time()-start) # 1.1 to 1.25 start=time.time() open('wtest', 'wb').write(text) # note wb print(time.time()-start) # 1.5 to 1.8 ---------------------------------------------- 2.5 --- import time line = 'a'*99 + '\n' text = line*500000 start=time.time() open('wtest', 'w').write(text) print(time.time()-start) # 3.3 to 4.1 import time line = 'a'*99 + '\n' text = line*500000 start=time.time() open('wtest', 'wb').write(text) # note wb print(time.time()-start) # 1.0 to 1.6 ------------------------------------------------- Conclusion: 1. on WinXP, writing with 3.0 has no slowdown versus 2.5 2. on WinXP, binary mode writing is about 3 times faster that text mode writing with its line-ending expansion. If that is not needed, binary mode and explicit bytes-text conversion is about twice as fast. Terry Jan Reedy From sopherfish at gmail.com Sun Dec 28 12:06:05 2008 From: sopherfish at gmail.com (sopherfish at gmail.com) Date: Sun, 28 Dec 2008 09:06:05 -0800 (PST) Subject: reportlab Message-ID: <77de75c7-2a2e-4621-a369-26680f3ad3a9@l38g2000vba.googlegroups.com> In reportlab 2.2, when I generate a PDF, no matter how many  s I put it, I only get one space. I am using it with python 2.6. The PDF generates fine and one $nbsp works, but for some reason, when I put it in multiple times, I still only get one space. From fakeaddress at nowhere.org Thu Dec 4 14:07:37 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 04 Dec 2008 11:07:37 -0800 Subject: Off Topic: Re: Obama's Birth Certificate - Demand that US presidential electors investigate Obama's eligibility In-Reply-To: References: <89pZk.9151$be.4743@nlpi061.nbdc.sbc.com> Message-ID: MM456Z at yahoo.com wrote: > Bryan Olson wrote: >> girbarob... at yahoo.com wrote: >>> This message is not about the meaningless computer printout called >> More importantly, it's not about Python. I'm setting follow-ups to >> talk.politics. I set the follow-ups header appropriately, as per established newsgroup etiquette. The deceitful not-abuser set the newsgroups back, inappropriately. Sorry if my reply annoys anyone, but I'm sticking to proper usage. >>> "Certification of Live Birth" that Obama propaganda machine calls his >>> "Birth Certificate". The American people are still waiting for a copy >>> of Obama's original birth certificate that includes all his birth >>> information. >> The document is what Hawaii provides as certified copy of birth record. >> It contains all the information the federal government requires to prove >> citizenship by birth, and it shows that Barack Hussein Obama was born 04 >> August 1961 in Honolulu. See: >> >> http://www.factcheck.org/elections-2008/born_in_the_usa.html >> > > This garbage on factcheck.org is a worthless piece of paper > insufficient to prove a US citizenship much less a natural born one. That's not true within the law as established under the U.S. Constitution. Barack Obama's site showed the document he got from Hawaii -- which form that the U.S. Department of State accepts. factcheck.org went it and and examined the record: http://www.factcheck.org/elections-2008/born_in_the_usa.html > You need to have a long version of legitimate birth certificate that > includes all birth information. You tell not the truth. The link shows a record from Hawaii. Hawaii became a U.S. state on 21 August 1959, and thus the record is entitled to the "full faith and credit" granted to state records under the U.S. Constitution Article IV Section 1. Does the record establish that he is a "natural born" citizen? The given record shows that BARACK HUSSEIN OBAMA was born on "August 4, 1961" in the city of HONOLULU on the island of OAHU (capitalization in original). The U.S. Constitution, Amendment 14 section 1, states that all persons born in the United States are citizens. B. H. Obama is a citizen of the USA by birth. >> Remind your US presidential electors of their constitutional duty to >>> investigate Obama's natural-born citizen status. >>> No federal agency like FBI or Secret Service, no Hawaii bureaucrats >>> have ever investigated Obama's birth in Hawaii. Many illegal aliens in >>> USA have official "birth certificates" issued by state bureaucrats on >>> the basis of falsified birth records. >> Janice Okubo of Hawaii's Department of Health confirmed that the state >> has Obama?s original birth certificate on record: >> >> http://hawaii.gov/health/about/pr/2008/08-93.pdf >> >> [...] > Do you have a sufficient IQ to actually grasp what this news release > says? Questioning the other guy's IQ? You must be new to Usenet. [...] > Get one thing straight for your own self interest! THERE ARE TENS OF > MILLIONS OF GUN OWNERS IN USA ONLY WAITING TO USE THEM ON ANYBODY WHO > THREATENS THE US CONSTITUTION - so better use all your brain cells in > your own self interest to resolve this matter now and not later. Run > to Obama and beg him to release all birth records or things will not > get any better. You are playing with fire. Now we see your true stripes. You pretend to be a loyal American, but really you are a hater and a traitor, using guns to threaten anyone who dares to actually stand up for the U.S. Constitution. Follow-ups again set to talk.politics. Of course that may be futile in dealing with this kind of scumbag. -- --Bryan From arnodel at googlemail.com Sun Dec 14 05:24:08 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 14 Dec 2008 10:24:08 +0000 Subject: [OT] stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <01547201$0$6988$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano writes: > On Sat, 13 Dec 2008 19:17:41 +0000, Duncan Booth wrote: > >> I think you must have fallen asleep during CS101. The lower bound for >> sorting where you make a two way branch at each step is O(n * log_2 n), >> but if you can choose between k possible orderings in a single >> comparison you can get O(n * log_k n). > > I think you might have been sleeping through Maths 101 :-) > > The difference between log_2 N and log_k N is a constant factor (log_2 k) > and so doesn't effect the big-oh complexity. It affects it if k is a function of n. In this particular example, we can set k=n so we get O(n). -- Arnaud From lists at cheimes.de Fri Dec 19 13:10:59 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 19 Dec 2008 19:10:59 +0100 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: walterbyrd schrieb: > On Dec 19, 9:13 am, "Giampaolo Rodola'" wrote: >> You can use the old 2.x syntax also in Python 3.x: > > Yeah, but it's deprecated, and - as I understand it - may be removed > completely in future versions. Also, in the future, if you are working > with code from another developer, it's likely that developer will use > the new format. I suppose you can use both - but what an awful mess > that would be. It's not going to be removed for many years - if ever. The % string formatting system is not deprecated in 3.0. For that very reason it must stay until 3.2. We don't have plans to deprecate it in 3.1 so it will stay at least until Python 3.3 which is to be released about 2014. Christian From pavlovevidence at gmail.com Wed Dec 10 22:25:41 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 10 Dec 2008 19:25:41 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> On Dec 10, 12:42?pm, cm_gui wrote: > Python is SLOW. ? ?And I am not comparing it with compiled languages > like C. > Python is even slower than PHP! cm_gui is TROLL. And I am not compring it with bots like Aaron Castironpi Brody. cm_gui is even troller than Xah Lee! Carl Banks From geekmail at usenot.de Sat Dec 6 07:32:58 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sat, 6 Dec 2008 13:32:58 +0100 Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> Message-ID: <20081206133258.693cf59e@usenot.de> On Sat, 6 Dec 2008 04:02:54 -0800 (PST) bearophileHUGS at lycos.com wrote: > class C: > def $method(arg): > $value = arg > > (Note there's no point after $, it's not currently possible). > Ruby uses @ and @@ for similar purposes. > I agree that the code looks worse, but also shorter to read and write, > so in lines of code that use many instance attributes, that short $ > syntax helps keep the line shorter. So I may grow to accept this > sugar... > But that is not the way Python is meant to work. There are several tennets in the Zen of Python that don't chime well with this approach. "self" is a speaking identifier, "$" isn't. we've-been-through-this-ingly yours /W -- My real email address is constructed by swapping the domain with the recipient (local part). From python at bdurham.com Wed Dec 24 02:43:35 2008 From: python at bdurham.com (python at bdurham.com) Date: Wed, 24 Dec 2008 02:43:35 -0500 Subject: Most efficient way to build very large dictionaries Message-ID: <1230104615.5867.1291617213@webmail.messagingengine.com> I'm working with some very large dictionaries (about 25M items per dictionary) that get filled based on data parsed from text based log files. I'm using Python dictionaries to track the frequency of specific combinations of events, eg, I build a key and then add various timing info from the current record to that's key's current value. If the key doesn't exist, I create it and initalize it to its first value. Most keys will have anywhere from 2 to 10,000 value increments. Over time, I've noticed that 90%+ of the keys in my dictionaries stay constant across daily runs of my program. Can I take advantage of this knowledge to optimize my dictionary performance by pre-building my dictionary based on a given list of keys whose values are all set to 0? Specifically, is there a way to bulk load a dictionary with keys/initial values that is faster than individually adding most dictionary entries one at a time? Here are 2 high level strategies I've been thinking about for improving the performance of my dictionaries. 1. Create a list of keys from a current dictionary, pickle this list of keys and then on my next program run, load the pickled list of keys and somehow convert this list to a dictionary with all key values set to 0. 2. After I've performed my analysis on a current dictionary, iterate through this dictionary, setting all values to 0 (is there a fast way to do this?), and then on my next program run, load this pickled dictionary of keys and zero values. I would appreciate your thoughts on whether there are advantages to working with a pre-built dictionary and if so, what are the best ways to create a pre-loaded dictionary. Thank you, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From prologic at shortcircuit.net.au Mon Dec 22 03:35:30 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Dec 2008 18:35:30 +1000 Subject: How to represent a sequence of raw bytes In-Reply-To: References: <200812220327.36180.motoom@xs4all.nl> Message-ID: On Mon, Dec 22, 2008 at 4:56 PM, Steven Woody wrote: > I thing "\x11\x22\x33" in python is not the {0x11, 0x22, 0x33} in C. > Since, a string in python is immutable, I can _not_ do something like: > b[1] = "\x55". > > And, how about char buf[200] in my original question? The intension > is to allocate 200 undefined bytes in memory. Thanks. Steven, one piece of advice. Python is not C. Thank. cheers James From tam at milkyway.gsfc.nasa.gov Fri Dec 12 10:39:44 2008 From: tam at milkyway.gsfc.nasa.gov (Tom McGlynn) Date: Fri, 12 Dec 2008 07:39:44 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> Message-ID: <3a72f628-0a57-46df-ac2f-d101e170e9db@w1g2000prm.googlegroups.com> On Dec 11, 6:46 am, "William James" wrote: > John W Kennedy wrote: > > Xah Lee wrote: > > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or > > > Java, you'll have 50 or hundreds lines. > > > Java: > > > static float[] normal(final float[] x) { > > float sum = 0.0f; > > for (int i = 0; i < x.length; ++i) sum += x[i] * x[i]; > > final float divisor = (float) Math.sqrt(sum); > > float[] a = new float[x.length]; > > for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor; > > return a; > > } Calculating the norm of a vector is a numeric operation, so not surprising it's pretty easy to do in Fortran. While pre Fortran 90 would using something similar to the above, today you can do it as norm = x/sqrt(sum(x*x)) for an arbitratry vector (or tensor for that matter). It would take a couple more lines to wrap it up in a function real function norm(x) real x(*) norm = x/sqrt(sum(x*x)) end [Caveat: my Fortran is more than rusty ....] So even Fortran can do this in only 1 line or 4 as a function. Judging by the LOC and, at least to my eye, the clarity of the method, Fortran is a real winner! Just to give a tiny bit of Java relevance to the discussion: It's the ability to write functions that straightforwardly express the mathematical intent of the user that makes operator overloading (in this case over arrays) so useful in many numerical contexts. This is cross-posted to Python as well. I understand it has similar array arithmetic capabilities to Fortran. I believe this may be one reason for Python's burgeoning popularity Tom McGlynn From rt8396 at gmail.com Thu Dec 18 11:40:11 2008 From: rt8396 at gmail.com (r) Date: Thu, 18 Dec 2008 08:40:11 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <71ede5f0-fd88-4155-9f0d-42d0ad5f57dc@v42g2000yqj.googlegroups.com> Message-ID: Yea, my answer was really not a helping answer(sorry) just showing exactly why this will not work with w.unbind(). Why do you need two separate functions to bind the same event?? You cannot combine the two?? From rt8396 at gmail.com Mon Dec 22 16:50:10 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 13:50:10 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <6ra8t0F925rU1@mid.individual.net> <29feda0d-6432-4cb9-8809-e4d4a7798601@e1g2000pra.googlegroups.com> <6rae73F9s47U1@mid.individual.net> Message-ID: On Dec 22, 3:13?pm, je.s.t... at hehxduhmp.org wrote: > r wrote: > > We see where you stand. And also see that by removing your comments > > from the archive in 5 days, how small your acorns really are. > > What is "the archive", Google Groups? ?You do realize that's not the > entirety of Usenet, correct? Absolutely, but why do you wish to remove your post. Do you not stand behind everything you say? I do, and if a make a mistake i will apologize for it. I have no reason to hide my words from anybody. They will be here from now to eternity. This just makes your thoughts look more "drive-by-ish" to me. Thats all. From nils.krahnstoever at gmail.com Thu Dec 11 00:19:51 2008 From: nils.krahnstoever at gmail.com (Nok) Date: Wed, 10 Dec 2008 21:19:51 -0800 (PST) Subject: Call by reference in SWIG? Message-ID: <298d9cd2-d982-4238-9bd8-bd8a96bb5f50@m15g2000vbl.googlegroups.com> I can't get call-by-reference functions to work in SWIG... Even when wrapping a trivial example like this: /* File : trivial.i */ %module trivial %inline %{ class test { public: void foo(int *t) { *t=42; } }; %} I get a TypeError when trying to use it: import trivial x=10 c=trivial.test() c.foo(x) The error is: def foo(*args): return _trivial.test_foo(*args) TypeError: in method 'test_foo', argument 2 of type 'int &' From duncan.booth at invalid.invalid Thu Dec 4 03:50:21 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 4 Dec 2008 08:50:21 GMT Subject: How can I do this (from Perl) in Python? (closures) References: <68b8294c-8771-4b02-bd46-2f25f5e01602@j35g2000yqh.googlegroups.com> Message-ID: excord80 at gmail.com wrote: > I just came across http://www.perl.com/pub/a/2002/05/29/closure.html > and wanted to try the "canonical example of closures" in Python. I > came up with the following, but it fails: > > ####################### > #!/usr/bin/env python > > def make_counter(start_num): > start = start_num > def counter(): > start += 1 > return counter The other answers you got will work, but here's an alternative to consider: you can convert the function into a generator and then just move the variable inside. >>> def make_counter(start_num): def counter(): start = start_num while 1: yield start start += 1 return counter().next >>> from_ten = make_counter(10) >>> from_three = make_counter(3) >>> print from_ten() 10 >>> print from_ten() 11 >>> print from_three() 3 >>> print from_ten() 12 >>> print from_three() 4 >>> While I realise you are just trying a simple example, if you actually wanted the code the truly Pythonic way would be to use the existing libraries: >>> import itertools >>> def make_counter(start_num): return itertools.count(start_num).next >>> from_ten = make_counter(10) >>> from_three = make_counter(3) >>> print from_ten() 10 >>> print from_ten() 11 >>> print from_three() 3 >>> print from_ten() 12 >>> print from_three() 4 >>> Never reinvent the wheel unless you really need a square one. :^) -- Duncan Booth http://kupuguy.blogspot.com From thorsten at thorstenkampe.de Wed Dec 10 14:30:32 2008 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Wed, 10 Dec 2008 20:30:32 +0100 Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: * cm_gui (Wed, 10 Dec 2008 10:42:40 -0800 (PST))> > Python is SLOW. And I am not comparing it with compiled languages > like C. > Python is even slower than PHP! Sure. But Perl is faster than Ruby (exactly 2.53 times as fast). And Python is 1.525 times faster than VisualBasic (or was it the other way round?). > Just go to any Python website and you will know. > An example is: > http://www2.ljworld.com/ > And this site is created by the creators of Django! Quite slow, indeed! Django is even slower than Python itself... > And it is not just this Python site that is slow. There are many many > Python sites which are very slow. And please don?t say that it could > be the web hosting or the server which is slow ? because when so many > Python sites are slower than PHP sites, it couldn?t be the web > hosting. Also, Zope/Plone is even slower. I hope this will awaken the community. I did a quick test and it seems that Zope is slower than Python but Python is faster than Plone and PHP is faster than even Perl and Python _together_...! Thanks for the heads-up, cm_gui! Thorsten From tn.pablo at gmail.com Wed Dec 17 17:52:42 2008 From: tn.pablo at gmail.com (ptn) Date: Wed, 17 Dec 2008 14:52:42 -0800 (PST) Subject: Location HTTP Header Message-ID: <68fa1e9b-6652-4d34-a7fe-fc98db8bf6d4@m16g2000vbp.googlegroups.com> Hi all. I tried this stupid script on my server: #! /usr/bin/env python print 'Location: http://www.google.com\n' and it didn't work, I get a blank page. I first tried the Location header in another script, and when execution got to that point, it would just sort of ignore it, because the script would keep running to the end of the code (or stop at some unhandled exception). I ran chmod 755 script.cgi and the cgi script is at the correct directory, but still nothing. I think it might be an error from the server (the old PythonWeb.org webserver), maybe it doesn't support Location? Is that even possible? Or maybe there's some setup I forgot to do? Any ideas? Thanks a lot. From python.list at tim.thechases.com Wed Dec 10 13:55:51 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 10 Dec 2008 12:55:51 -0600 Subject: get todays files In-Reply-To: References: Message-ID: <494010B7.4000105@tim.thechases.com> > I have a script that will login to my ftp server and download > all the backup files, but I want it to only download the files > that were created today, e.g. if I ran the script today I want > it to only fetch files created today. Use Python's ftp module and send the MDTM command to get back the timestamp of the filename. Insecurely, this would look something like from ftplib import FTP hostname = "ftp.mozilla.org" conn = FTP(hostname) user = "anonymous" password = "user at example.com" conn.login(user, password) filename = "pub/README" results = conn.sendcmd("MDTM %s" % filename) code, stamp = results.split(None, 1) assert code == "213", "Unexpected result" print "%s was modified on %s" % (filename, stamp) today = '20081210' if stamp[:8] == today: process(filename) else: print "ignoring", filename The MDTM command is not part of the core RFC-959, but rather the RFC-3659[1] so you might run across some servers that don't support it. You can read more about the Python ftplib module at [2] which would be where you want to read up on pulling back a listing of the directory of file-names to check. There is a NLST command (I don't have a server handy that supports this command). The LIST command returns pretty/readable information that's not quite so machine-parsing friendly (at least in a cross-FTP-server sort of way). However, that part, I leave as an exercise for the reader along with the complications of the "today" bit. Oh, SteveH, I checked your FTP-cloning source in my Python dir, and it doesn't look like it does anything regarding file-times in it, so that may have been a red-herring. Unless you've added something since the ver. I've got here. -tkc [1] http://en.wikipedia.org/wiki/List_of_FTP_commands [2] http://www.python.org/doc/2.5.2/lib/ftp-objects.html From joe at strout.net Fri Dec 19 10:23:10 2008 From: joe at strout.net (Joe Strout) Date: Fri, 19 Dec 2008 08:23:10 -0700 Subject: How to parsing a sequence of integers In-Reply-To: References: <494ba258$0$18998$426a74cc@news.free.fr> Message-ID: <494BBC5E.7070909@strout.net> Peter Otten wrote: > If you are using Python 2.x: > ... > So you better throw in a float(...): Or, add from __future__ import division at the top of the file. I put this at the top of all my Python files, whether I expect to be dividing or not. It just saves grief. Cheers, - Joe From hotkatrina4u at gmail.com Fri Dec 19 04:51:25 2008 From: hotkatrina4u at gmail.com (hotkatrina4u) Date: Fri, 19 Dec 2008 01:51:25 -0800 (PST) Subject: Online INTERNET JOBS Message-ID: <9900f9bb-1faf-44db-a1cb-c15debab8895@b41g2000pra.googlegroups.com> Start Your Own INTERNET JOBS AT http://megalinesolutions.googlepages.com/ No Fee Required From gagsl-py2 at yahoo.com.ar Mon Dec 8 02:48:19 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Dec 2008 05:48:19 -0200 Subject: Best way to run multiple Python processes without overloading CPU or disk i/o In-Reply-To: References: <1228278090.29785.1287948757@webmail.messagingengine.com> Message-ID: En Wed, 03 Dec 2008 02:29:32 -0200, Philip Semanchuk escribi?: > > On Dec 2, 2008, at 11:21 PM, python at bdurham.com wrote: > >> Is there a cross-platform way to launch multiple Python processes >> and monitor CPU usage > > os.getloadavg() might be useful. It certainly works on *nix, don't know > about Windows. The documentation doesn't mention any platform > limitations. ....apart from saying "Availability: Unix."? :) To the OP: You may monitor CPU usage using the Tim Golden's wmi module [1] py> import wmi py> c = wmi.WMI() py> for p in c.Win32_Processor(): .... print float(p.LoadPercentage) .... 9.0 [1] http://timgolden.me.uk/python/ -- Gabriel Genellina From bearophileHUGS at lycos.com Mon Dec 8 09:29:54 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 8 Dec 2008 06:29:54 -0800 (PST) Subject: Public imports References: <9623b0a3-7053-41f1-b116-0cd5e54f39e9@v13g2000vbb.googlegroups.com> Message-ID: <8e382f56-3048-4fdc-881a-700416d29156@n41g2000yqh.googlegroups.com> M?rcio Faustino: > Does Python support public imports instead of the default private? > Something like D's "public import" (see 2.0/module.html>) or even Perl's "export_to_level". D type system has several big holes, and I am trying to push Walter to fix some of those, to make it look a little more sane, like for example the Python module system. Public imports are often bad. Bye, bearophile From darcy at druid.net Tue Dec 23 10:59:11 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 23 Dec 2008 10:59:11 -0500 Subject: iterating initalizations In-Reply-To: References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> <20081223092504.aaf25192.darcy@druid.net> Message-ID: <20081223105911.9b265bf2.darcy@druid.net> On Tue, 23 Dec 2008 10:20:59 -0500 Steve Holden wrote: > D'Arcy J.M. Cain wrote: > > Well, if all you want is a loop: > > > > for v in vars: > > locals()[v] = [] > > > Note that this isn't guaranteed to work. While locals() will return a > dict containing the names and values from the local namespace, you won't > affect the local namespace by assigning values to the appropriate keys: > > >>> def f(): > ... a = "hello" > ... locals()["a"] = "goodbye" > ... print a This was my test: >>> locals()['x'] = "hello" >>> x 'hello' >>> locals()['x'] = "goodbye" >>> x 'goodbye' Just didn't want people to think that I post without testing. In any case, even if that worked as expected I am pretty sure that it is the wrong solution but without knowing more about what the OP is doing it is impossible to know what the right answer is. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From invalid at invalid Tue Dec 23 11:03:49 2008 From: invalid at invalid (Grant Edwards) Date: Tue, 23 Dec 2008 10:03:49 -0600 Subject: pseudo terminal usage from Python? References: Message-ID: <5t-dnRgMi9Z4lszUnZ2dnUVZ_vOdnZ2d@posted.visi> On 2008-12-23, skip at pobox.com wrote: > > I ran into an interesting problem yesterday. The mpstat(1) command on > Solaris formats its output like so: > > CPU minf mjf xcal intr ithr csw icsw migr smtx srw syscl usr sys wt idl > 0 42 1 1184 812 265 227 12 44 37 0 1131 6 2 0 93 > 1 25 1 933 447 2 203 37 75 12 0 902 5 4 0 91 > 2 17 0 195 495 1 201 41 77 13 0 514 5 1 0 94 > 3 4 0 117 882 405 171 34 65 21 0 449 5 2 0 93 > > I'm only interested in presenting the CPU numbers and user+sys values > prefixed by a timestamp. For example, the above might be formatted like so: > > 07:28:46.373328 0 8 1 9 2 6 3 7 > > The obvious solution might be something simple like this: > > mpstat 1 | python mympstat.py > > where mympstat.py does a trival amount of reformatting. > > The problem is that mpstat recognizes when its output is a pipe and block > buffers it so the Python script sees input in massive blobs, not the > second-by-second output you'd see running "mpstat 1" by itself. Are you sure it's not Python buffering its input? Have you tried "python -u mympstat.py"? > I suspect there is some magic I can perform with pseudo terminals (this is > on Solaris 10.) The documentation for the pty module contains no examples > and I've been so far unable to find any using Google. I had a Linux pty example running once upon a time. If "python -u" doesn't work post again, and I'll try to find it. -- Grant Edwards grante Yow! Please come home with at me ... I have Tylenol!! visi.com From deets at nospam.web.de Wed Dec 24 08:37:33 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 24 Dec 2008 14:37:33 +0100 Subject: SyntaxError: encoding problem: with BOM In-Reply-To: References: Message-ID: <6res8tF1do1sU1@mid.uni-berlin.de> NoName schrieb: > i have 1.py in cp866 encoding: > > # -*- coding: cp866 -*- > print ("ff") > > > > It's not work in Python 3.0 > Error: > > File "", line 1 > SyntaxError: encoding problem: with BOM > > what's wrong? I can only guess, but just because you write the coding-header that doesn't mean that the editor you use does actually *use* that encoding. What I presume it does is to use utf-8, and write that stupid BOM microsoft uses for denoting utf-8-content as first byte. Try using a different editor, or alter it's settings to really use your desired encoding. Diez From skip.montanaro at gmail.com Sat Dec 27 13:54:32 2008 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Sat, 27 Dec 2008 10:54:32 -0800 (PST) Subject: Test message via Google Groups Message-ID: <0172c8ed-13ca-49e7-a7bb-2f9bef475f65@t39g2000prh.googlegroups.com> Test message - please ignore. Skip From aleksandr.goretoy at gmail.com Sat Dec 27 18:54:02 2008 From: aleksandr.goretoy at gmail.com (alex goretoy) Date: Sat, 27 Dec 2008 17:54:02 -0600 Subject: how to make a class to get all forms and input fields from webpage Message-ID: Hello All, How do I make a class for retrieving all forms and input fields on a web page. Meaning, form name, form url,all input fields, text,textarea,select,etc...I have something currently and it kinda works. It also kinda works for retrieving all images on webpages. My main concer here is to make is retrive forms and input fields into a dict that has this kinda of outline: Maybe not exactly like this, but something to this nature. So I can use it in other classes. forms= {"name":{"url":{"""input_name1":"","input_name_2","select_input":{"value1":"","value2":"selected","value3":""}}}} This is what I have made a long time ago, I haven't touched it in a while, but I need to make it work with some other classes. I need tit to receive all forms and inputs for me. What is a more efficient way to do this? My background is in PHP and I want to extend my python knowledge. I came up with this script by Googling something a long time ago and making modifications and additions to it. You can find the stdout_colours class on line, JFGI. It's allows for display of caller and called function and colors output to terminal. Thanks for your help my friends. #!/usr/bin/python import urllib, urllib2 import re, sys,string import os, sys, Image from sgmllib import SGMLParser from urlparse import urlparse import stdout_colours class URLPacker(SGMLParser): def __init__(self,colorize,caller): self.colorize=colorize self.caller=caller self.reset() def reset(self): SGMLParser.reset(self) self.func_me_color="white_on_black" self.soc=stdout_colours.stdout_colors(self.colorize,self.caller) self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.urls = {} self.imgs = {} self.forms = {} self.inputs = {} self.action = "" self.method = "" self.url="" self.path="" self.source="" self.dirname="" self.level=0 self.max_depth=4 self.urlRExp = re.compile('[.]htm$|[.]html$|[.]shtml$|[/]$|[.]php$', re.IGNORECASE) self.fileRExp = re.compile('[\/:*?"<>|]') self.formats=[] self.soc.me_him(['EXIT:',__name__],self.func_me_color) def start_a(self,attrs): self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.soc.w(attrs,"red") href = [v for k,v in attrs if k=='href'] for value in href: if self.urls.has_key(value): pass else: self.urls[value]=0 self.soc.me_him(['EXIT:',__name__],self.func_me_color) def start_img(self,attrs): self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.soc.w(attrs,"blue") src = [v for k,v in attrs if k=="src"] for value in src: if self.imgs.has_key(value): pass else: self.imgs[value]=0 self.soc.me_him(['EXIT:',__name__],self.func_me_color) def start_form(self,attrs): self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.soc.w(attrs,"green") method = [v for k, v in attrs if k=='method'] action = [v for k,v in attrs if k=="action"] if string.join(method,"") != "": self.method=method[0] else: self.method="post" self.action=action[0] self.soc.w(action,"white_on_green") self.soc.w(method,"white_on_blue") self.forms[self.action]={} self.forms[self.action][self.method]={} self.soc.me_him(['EXIT:',__name__],self.func_me_color) def start_input(self,attrs): self.soc.me_him(['ENTER:',__name__],self.func_me_color) self.soc.w(attrs,"yellow") name = [v for k, v in attrs if k=='name'] value = [v for k,v in attrs if k=="value"] if string.join(name,"") !="": if string.join(value,"")!="": self.forms[self.action][self.method][name[0]]=value[0] else: self.forms[self.action][self.method][name[0]]="" self.soc.w(self.forms,"white_on_gold") self.soc.me_him(['EXIT:',__name__],self.func_me_color) def url_dirname(self, url): self.soc.me_him(['RETURN:',__name__],self.func_me_color) #print url return self.fileRExp.sub('_',url) def dirname(self,url): self.soc.me_him(['RETURN:',__name__],self.func_me_color) return os.path.dirname(url) def save_images(self,minsize): if os.path.isdir(self.path+self.dirname): return False # aborting, dir exists else: a=self.path+self.dirname os.mkdir(a) os.chdir(a) print self.url for img in self.imgs.keys(): loc=self.url_dirname(img) print loc, img, a try: if self.imgs[img]==0: #urllib.urlretrieve(img,loc) #os.system('wget -A.jpg,gif,png,wmv,avi,mpg -r -l4 -H -erobots=off --wait=1 -np -U \"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.6) Gecko/20050405 Firefox/1.0 (Ubuntu package 1.0.2)\" '+img) #im = Image.open(loc) #if im.size[0] From steve at holdenweb.com Sat Dec 20 08:20:12 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 20 Dec 2008 08:20:12 -0500 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <06daa32b-aff7-4104-99bb-3cd1365be600@w1g2000prm.googlegroups.com> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> <06daa32b-aff7-4104-99bb-3cd1365be600@w1g2000prm.googlegroups.com> Message-ID: <494CF10C.8010302@holdenweb.com> Mark Summerfield wrote: [...] > > With two dozen postings on my use of English I'm now rather nervous > about the feeback I'll get on my Python 3! > There is no such thing as bad publicity. Quick, make a blog post about how there have been over twenty comments about your use of English (though don't forget to point out that it's correct). > PS Although Amazon.com still says the publication date is the 27th, > they now expect to have it in stock on Monday (the 22nd). Congratulations. I know what a relief it is to see a project of that size come to fruition! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From m1k3b0 at gmail.com Fri Dec 12 18:06:05 2008 From: m1k3b0 at gmail.com (m1k3b0 at gmail.com) Date: Fri, 12 Dec 2008 15:06:05 -0800 (PST) Subject: os.lstat : proper way to do this Message-ID: I'm converting from Perl to Python, so I'm learning the basics - please be gentle! :) In Perl, I can lstat($file) whether $file exists or not: lstat($file); unless (-e _) { print STDERR "$file: No such file or directory\n"; } unless (-l _) { print STDERR "$file: Not a symbolic link\n"; } The lstat() returns normally whether the file exists or not, and I check for existence with the "-e" conditional. Then I go on and check other modes. In Python,if I os.lstat(file) and file doesn't exist, I get an error from within the module: OSError: [Errno 2] No such file or directory: '/etc/xxx' I can check first with os.path.exists(file), but then I'm doing two stat() type calls which is inefficient (especially when we're talking thousands of files). I want to be able to do something like this: mode = os.lstat(file)[ST_MODE] if not mode: print >> sys.stderr, file, ": No such file or directory" if not S_ISLNK(mode): print >> sys.stderr, file, ": Not a symbolic link" Of course, this isn't valid. How can I do this efficiently without getting "no such file" error? Thanks! mikebo From martin at v.loewis.de Sun Dec 7 14:53:10 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 07 Dec 2008 20:53:10 +0100 Subject: Number of Python 3.x packages at the PyPI In-Reply-To: <2d656e64-deff-40ed-8066-57b6f8874ec4@b38g2000prf.googlegroups.com> References: <9c1ab0f3-6686-4c0f-8a6c-12e20539f354@41g2000yqf.googlegroups.com> <493b954e$0$4021$9b622d9e@news.freenet.de> <2d656e64-deff-40ed-8066-57b6f8874ec4@b38g2000prf.googlegroups.com> Message-ID: <493c29a7$0$27869$9b622d9e@news.freenet.de> > I've had to fork my appscript project's codebase in order to add > support for Python 3.x. I would like to distribute both 2.x and 3.x > versions under the same package name for obvious reasons. This isn't a > problem with eggs as the Python version number is included in each > egg's name, but what about source distributions where both filenames > are exactly the same (appscript-0.19.0.tar.gz)? I see. My initial reaction was that something should be done about this; please do bring this up on catalog-sig at python.org. On second thought: can't you just include the source of both versions in a single source distribution file? If you are going to release them in lock-step, you probably want to always release both sets of sources together; if you don't release them in lock-step, users will get confused how to obtain the most recent release for 3.x (say) if some version has only the 2.x release. Regards, Martin From f.guerrieri at gmail.com Mon Dec 22 13:15:31 2008 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Mon, 22 Dec 2008 19:15:31 +0100 Subject: Python's popularity In-Reply-To: <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> Message-ID: <79b79e730812221015y6b8be729ve2123bdef6715f11@mail.gmail.com> On Mon, Dec 22, 2008 at 7:01 PM, r wrote: > Walter, > I just look at the stats for comp.lang.python, and i am 9th place for > most post this month. That makes me completely sad. With just 50 post > so far, i am showing up on the high count. Sad, very sad. Now i have > much reason to believe that only 100 or so people follow this list :(. > Python is slipping. We must try harder, or all of Guido's work will be > for nothing! Just wanted to remember you that Python is an open source project initiated and led by Guido Van Rossum and kept alive (and in good health) by the work of *many* people. It if were only Guido's work it would be different from what it is now. Furthermore, choosing to code in a language or in another is not a matter of religion or of war. If someone likes Ruby, or Perl, or VBA... and is productive (according to her needs) with it, why in the world should a Python programmer consider her an "enemy"??? Francesco -------------- next part -------------- An HTML attachment was scrubbed... URL: From ethan at stoneleaf.us Thu Dec 11 14:29:09 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 11 Dec 2008 11:29:09 -0800 Subject: internal circular class references In-Reply-To: <49414EDA.2050509@stoneleaf.us> References: <49414EDA.2050509@stoneleaf.us> Message-ID: <49416A05.3070307@stoneleaf.us> Thanks, Carl! Thanks, RDM! Your examples and ideas are much appreciated. Many thanks also to everyone else who responded. ~Ethan~ From grahn+nntp at snipabacken.se Tue Dec 9 03:39:43 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 9 Dec 2008 08:39:43 GMT Subject: gzip.GzipFile (was Re: Don't you just love writing this sort of thing :)) References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: On Mon, 08 Dec 2008 14:21:40 +0000, MRAB wrote: > Jorgen Grahn wrote: >> On Sat, 06 Dec 2008 10:01:10 +0000, Arnaud Delobelle wrote: >> >> ... >>> Why use (open, gzp.GzipFile)[Entry.endswith(".gz")] when we have had >>> contitional expressions for a few years now? Instead, you can write >>> >>> (gzip.GzipFile if entry.endswidth(".gz") else open). >>> >>> I think it will be faster (as it doesn't require the construction of a >>> tuple and then the retrieval of one of its elements) and clearer. >> >> Even clearer would be if gzip.Gzipfile could (optionally) read >> non-gzipped files and file-like objects, like the gzip Unix commands >> zcat -f, zgrep and so on. ... > gzip is for reading gzipped files. IMHO it would be better to have a > de-archive module which uses the gzip, tarfile, etc, modules as necessary. Not tarfile, since that's usually a container for many files. But ok, maybe you are right about placing it in a different module -- even though it's fairly common for Unix application to accept plain files, gzipped files and nothing else. Note that such a module should handle reading sys.stdin and other non-disk files. That's a bit tricky, because when you realize that you guessed wrong on the format, you have already consumed and discarded some of the data. I started looking at such a module a year ago, but never finished it. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From sjmachin at lexicon.net Sat Dec 6 17:34:28 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 6 Dec 2008 14:34:28 -0800 (PST) Subject: Python 3.0 automatic decoding of UTF16 References: <55d79070-0c11-4fb9-8cf5-b8cc7c54b5d2@v42g2000yqv.googlegroups.com> Message-ID: <0e37191f-3672-4313-bc5c-ffcd904e4796@k24g2000pri.googlegroups.com> On Dec 7, 9:01?am, David Bolen wrote: > Johannes Bauer writes: > > This is very strange - when using "utf16", endianness should be detected > > automatically. When I simply truncate the trailing zero byte, I receive: > > Any chance that whatever you used to "simply truncate the trailing > zero byte" also removed the BOM at the start of the file? ?Without it, > utf16 wouldn't be able to detect endianness and would, I believe, fall > back to native order. When I read this, I thought "O no, surely not!". Seems that you are correct: [Python 2.5.2, Windows XP] | >>> nobom = u'abcde'.encode('utf_16_be') | >>> nobom | '\x00a\x00b\x00c\x00d\x00e' | >>> nobom.decode('utf16') | u'\u6100\u6200\u6300\u6400\u6500' This may well explain one of the Python 3.0 problems that the OP's 2 files exhibit: data appears to have been byte-swapped under some conditions. Possibility: it is reading the file a chunk at a time and applying the utf_16 encoding independently to each chunk -- only the first chunk will have a BOM. From badmuthahubbard at gmail.com Wed Dec 10 11:12:40 2008 From: badmuthahubbard at gmail.com (badmuthahubbard) Date: Wed, 10 Dec 2008 08:12:40 -0800 (PST) Subject: Python music sequencer timing problems Message-ID: <3b52b652-df61-4eb4-bcff-0d1fb6f20891@r15g2000prh.googlegroups.com> I've been trying to get the timing right for a music sequencer using Tkinter. First I just loaded the Csound API module and ran a Csound engine in its own performance thread. The score timing was good, being controlled internally by Csound, but any time I moved the mouse I got audio dropouts. It was suggested I run the audio engine as a separate process, with elevated/realtime priority and use sockets to tell it what to play, and that way, too, people could set up servers for the audio on different CPUs. But I've found that the method I came up with for timing the beats/notes is too slow (using threading.Timer on a function that calls itself over and over), and the whole thing played too slowly (and still gave me noise when moving the mouse). I've been using subprocesses, but I'm now wondering if sockets would or could make a difference. The overall goal is this: when the user wants to audition a piece, create an audio engine process with elevated/realtime priority. This engine also has all the synthesis and sound processing rules for the various instruments, due to the way Csound is structured. Set up a scheduler- possibly in another process, or just another thread- and fill it with all the notes from the score and their times. Also, the user should be able to see a time-cursor moving across the piece so they can see where they are in the score. As this last bit is GUI, the scheduler should be able to send callbacks back to the GUI as well as notes to the audio engine. But neither the scheduler nor the audio engine should wait for Tkinter's updating of the location of the time- cursor. Naturally, all notes will have higher priorities in the scheduler than all GUI updates, but they won't necessarily always be at the same time. So, I have a few ideas about how to proceed, but I want to know if I'll need to learn more general things first: 1. Create both the scheduler and the audio engine as separate processes and communicate with them through sockets. When all events are entered in the scheduler, open a server socket in the main GUI process and listen for callbacks to move the cursor (is it possible to do this using Tkinter's mainloop, so the mouse can be moved, albeit sluggishly, at the same time the cursor is moving continuously?); the audio engine runs at as high priority as possible, and the scheduler runs somewhere between that and the priority of the main GUI, which should even perhaps be temporarily lowered below default for good measure. or 2. Create the audio engine as an elevated priority process, and the scheduler as a separate thread in the main process. The scheduler sends notes to the audio engine and callbacks within its own process to move the GUI cursor. Optionally, every tiny update of the cursor could be a separate thread that dies an instant later. 3. Closer to my original idea, but I'm hoping to avoid this. All note scheduling and tempo control is done by Csound as audio engine, and a Csound channel is set aside for callbacks to update the cursor position. Maybe this would be smoothest, as timing is built into Csound already, but the Csound score will be full of thousands of pseudo-notes that only exist for those callbacks. Down the road I'd like to have notes sound whenever they are added or moved on the score, not just when playing the piece, as well as the option of adjusting the level, pan, etc. of running instruments. It seems method 2 runs the risk of slowing down the timing of the notes if the mouse moves around; but method 1 would require setting up an event loop to listen for GUI updates from the scheduler. I was trying method 1 with subprocesses, but reading from the scheduler process's stdout PIPE for GUI updates wasn't working. I was referred to Twisted and the code module for this, and haven't yet worked out how to use them appropriately. I don't mind a complex solution, if it is reliable (I'm aiming at cross-platform, at least WinXP-OSX-Linux), but everything I try seems to add unnecessary complexity without actually solving anything. I've been reading up on socket programming, and catching bits here and there about non-blocking IO. Seem like good topics to know about, if I want to do audio programming, but I also need a practical solution for now. Any advice? Thanks a lot. -Chuckk From gandalf at shopzeus.com Thu Dec 18 11:43:02 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 18 Dec 2008 17:43:02 +0100 Subject: Is this pythonic? In-Reply-To: <66d058f9-cfe1-4b3c-ab8a-e6e88bb97770@m22g2000vbp.googlegroups.com> References: <66d058f9-cfe1-4b3c-ab8a-e6e88bb97770@m22g2000vbp.googlegroups.com> Message-ID: <494A7D96.8010902@shopzeus.com> ipytest at gmail.com wrote: > x.validate_output(x.find_text(x.match_filename > (x.determine_filename_pattern(datetime.datetime.now())))) > > Is it even good programming form? > You should try LISP. :-) From martin at v.loewis.de Mon Dec 15 18:21:36 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 16 Dec 2008 00:21:36 +0100 Subject: Problem Python 2.6.1 vs 2.6 & pyWin32 In-Reply-To: References: <4946754f$0$19000$426a74cc@news.free.fr> <4946D09F.6050300@v.loewis.de> Message-ID: <4946e680$0$9099$9b622d9e@news.freenet.de> >> Try installing Python 2.6.1 "for all users". > > Could you clarify why that's needed? I didn't say it's needed. I said that he should try that, perhaps it helps. > One thing we noticed (I'm not sure has this been yet submitted to > bugs.python.org yet) was that installing packages created with Python > 2.5 to Python 2.6 failed unless Python was in %PATH% [1]. In general, that's not supported at all. You will have to rebuild all packages for Python 2.6, unless they are pure-python packages (in which case PATH should be irrelevant). If the .pyd files would have loaded, Python would have complained that they originate from the wrong Python version. > Another pretty severe problem was that installers created with Python > 2.6 didn't work at all with older versions [2]. That's not a bug, either. It has been that way since Python 1.4 or so: .pyd files built for X.Y won't work for X.(Y+1), and vice versa. It seems that you mean something specific with the word "installer"; I think you should elaborate what precisely you are referring to. Regards, Martin From bignose+hates-spam at benfinney.id.au Sun Dec 14 16:55:44 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 15 Dec 2008 08:55:44 +1100 Subject: the official way of printing unicode strings References: Message-ID: <871vwah15r.fsf@benfinney.id.au> Piotr Sobolewski writes: > in Python (contrary to Perl, for instance) there is one way to do > common tasks. More accurately: the ideal is that there should be only one *obvious* way to do things. Other ways may also exist. > Could somebody explain me what is the official python way of > printing unicode strings? Try these: If you want something more official, try the PEP that introduced Unicode objects, PEP 100: . > I tried to do this such way: > s = u"Stanis?aw Lem" > print u.encode('utf-8') > This works, but is very cumbersome. Nevertheless, that says everything that needs to be said: You've defined a Unicode text object, and you've printed it specifying which character encoding to use. When dealing with text, the reality is that there is *always* an encoding at the point where program objects must interface to or from a device, such as a file, a keyboard, or a display. There is *no* sensible default encoding, except for the increasingly-inadequate 7-bit ASCII. Since there is no sensible default, Python needs to be explicitly told at some point which encoding to use. > Then I tried to do this that way: > s = u"Stanis?aw Lem" > print u > This breaks when I redirect the output of my program to some file, > like that: > $ example.py > log How does it ?break?? What behaviour did you expect, and what behaviour did you get instead? -- \ ?I hope that after I die, people will say of me: ?That guy sure | `\ owed me a lot of money?.? ?Jack Handey | _o__) | Ben Finney From mcrute at gmail.com Thu Dec 4 18:29:48 2008 From: mcrute at gmail.com (Michael Crute) Date: Thu, 4 Dec 2008 18:29:48 -0500 Subject: Importing Version Specific Modules Message-ID: <558b73fb0812041529g313a27bpcfd09fc90f474f6e@mail.gmail.com> Which method makes the most sense for importing a module in python that is version specific? My use case is that I'm writing code that will be deployed into a python 2.3 environment and in a few months be upgraded to python 2.5. This: if sys.version_info[:2] >= (2, 5): from string import Template else: from our.compat.string import Template or this try: from string import Template except ImportError: from our.compat.string import Template I know that either case is equally correct and works correctly but which one is preferable? -- ________________________________ Michael E. Crute http://mike.crute.org God put me on this earth to accomplish a certain number of things. Right now I am so far behind that I will never die. --Bill Watterson From tvrtko.sokolovski at gmail.com Sat Dec 13 17:06:32 2008 From: tvrtko.sokolovski at gmail.com (sokol) Date: Sat, 13 Dec 2008 14:06:32 -0800 (PST) Subject: pypi package dates Message-ID: Am I missing something? There are no release dates for packages in pypi. One cannot have an idea how current the package is... From george.sakkis at gmail.com Tue Dec 2 21:12:26 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 2 Dec 2008 18:12:26 -0800 (PST) Subject: Overriding a method at the instance level on a subclass of a builtin type References: Message-ID: On Dec 2, 7:58?pm, "Zac Burns" wrote: > Sorry for the long subject. > > I'm trying to create a subclass dictionary that runs extra init code > on the first __getitem__ call. However, the performance of __getitem__ > is quite important - so I'm trying in the subclassed __getitem__ > method to first run some code and then patch in the original dict > method for the instance to avoid even the check to see if the init > code has been run. Various recipes using instancemethod and the like > have failed me. For new-style classes, special methods are always looked up in the class, not the instance, so you're out of luck there. What are you trying to do? Perhaps there is a less magic solution to the general problem. George From R.Brodie at rl.ac.uk Fri Dec 5 12:38:25 2008 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 5 Dec 2008 17:38:25 -0000 Subject: Python 3.0 automatic decoding of UTF16 References: <85fxl24lbu.fsf@dozer.localdomain> Message-ID: "J Kenneth King" wrote in message news:85fxl24lbu.fsf at dozer.localdomain... > It probably means what it says: that the input file contains characters > it cannot read using the specified encoding. That was my first thought. However it appears that there is an off by one error somewhere in the intersection of line ending/codec processing. Half way through the codec starts byte-flipping characters. From mail at microcorp.co.za Sun Dec 28 05:59:03 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 28 Dec 2008 12:59:03 +0200 Subject: ctypes & strings References: <334452.47084.qm@web30003.mail.mud.yahoo.com><000f01c96822$5c300f00$0d00a8c0@hendrik> Message-ID: <00a801c968dd$6508b3a0$0d00a8c0@hendrik> "Gabriel Genellina" wrote: >Hmmm, I don't think posting a potentially harmful example is actually a >good idea... True - its my only example though, and nobody else was bothering to reply, so I kicked off and flushed out some response. Who was it that said that the way to get info out of usenet was to post some rubbish? :-) - Hendrik From jeremiah.dodds at gmail.com Sat Dec 20 04:37:00 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Sat, 20 Dec 2008 04:37:00 -0500 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <2dc66762-f51e-4bbd-9372-756610d4201e@j11g2000yqg.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c4ef2$0$20656$c3e8da3@news.astraweb.com> <2d53cd36-52b0-4a1a-913d-0c545cfadc23@v15g2000vbb.googlegroups.com> <2dc66762-f51e-4bbd-9372-756610d4201e@j11g2000yqg.googlegroups.com> Message-ID: <12cbbbfc0812200137t37bdb792p2eab52812c21aefa@mail.gmail.com> On Sat, Dec 20, 2008 at 12:30 AM, r wrote: > Why could't we improve on what we had instead of > making radical changes? Thats all i am asking. > -- > http://mail.python.org/mailman/listinfo/python-list > Often times improving on what you have involves radical changes, especially if the goals of what you have change, or were not fully understood during their original implementation. -------------- next part -------------- An HTML attachment was scrubbed... URL: From news123 at free.fr Sat Dec 6 08:21:45 2008 From: news123 at free.fr (News123) Date: Sat, 06 Dec 2008 14:21:45 +0100 Subject: python book for non technical absolute beginner Message-ID: <493a7c6a$0$973$426a34cc@news.free.fr> Hi, One of my 'non technical' friends complained about knowing nothing at all about programming (though using computers regularly for mails / web browsing / googling and downloading / cropping photos ) He wants to play a little with programming to stimulate parts of his otehrwise idle brain cells. ;-) Normally it's more the social science / linguistic parts being exercised, I thought python might be a nice language for this No my question does anybody know a nice beginners book (or a learning CD or on line tutorial)? Ideally it shouldn't be too serious and have a lot of small nice mini-examples thanks in advance for any suggestions hints bye N From pxrepreza at gmail.com Tue Dec 23 12:12:32 2008 From: pxrepreza at gmail.com (Paulo Repreza) Date: Tue, 23 Dec 2008 09:12:32 -0800 Subject: String Format Error. In-Reply-To: References: <47c890dc0812222311m2a67b798v167b40de9dfcd53d@mail.gmail.com> Message-ID: Thank You! On Tue, Dec 23, 2008 at 3:49 AM, Steve Holden wrote: > Chris Rebert wrote: > > On Mon, Dec 22, 2008 at 10:19 PM, Paulo Repreza > wrote: > >> Hi, > >> > >> I'm a newbie with python and I recently bought Beginning with Python > (Which > >> is a book I recommend) but the problem that I'm facing it's the > following: > >> > >> This is the code: > >> > >> #!/usr/bin/python2.5 > >> # Filename: str_format.py > >> > >> age = 25 > >> name = 'foobar' > >> > >> print('{0} is {1} years old'.format(name, age)) > >> print('Why is {0} playing with that python?'.format(name)) > >> > >> > >> But when I run the script I receive this error: > >> > >> Traceback (most recent call last): > >> File "str_format.py", line 7, in > >> print('{0} is {1} years old'.format(name, age)) > >> AttributeError: 'str' object has no attribute 'format' > >> > >> > >> It is an error because of the version that I'm using ? Python 2.5.2 > (Debian > >> lenny) > > > > Yes, Python 2.6 or higher is required to use .format() according to > > http://docs.python.org/whatsnew/2.6.html > > > For a replacement that will work in 2.5, see the "%" sign as an operator > (sometimes called "string interpolation"). > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fetchinson at googlemail.com Mon Dec 22 17:25:54 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 22 Dec 2008 14:25:54 -0800 Subject: Are Django/Turbogears too specific? In-Reply-To: References: Message-ID: > I'd like to rewrite a Web 2.0 PHP application in Python with AJAX, and > it seems like Django and Turbogears are the frameworks that have the > most momentum. > > I'd like to use this opportunity to lower the load on servers, as the > PHP application wasn't built to fit the number of users hammering the > servers now. > > I'm concerned, though, that these frameworks they may be too specific > to the tasks they were originally developped for (news articles, > AFAIK). Do you think I should just use eg. CherryPy and some basic > AJAX? The 1.x branch of tg is built on cherrypy, the 2.x branch is built on pylons. Both branches depend on external packages for most of their functionality which makes them very flexible. Django is monolithic and was intended to be monolithic. Of course you can customize it and use different components than the defaults, but after all *everything* is customizable since the source code is there and you can modify it. The point is that tg was designed with flexibility and customizability in mind, while django was designed with a monolithic infrastructure in mind. The 1.x branch of tg is stable and has been for years while the 2.x branch is in beta but will be released soon as a stable, production version. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From 5lvqbwl02 at sneakemail.com Sun Dec 7 02:33:35 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Sat, 6 Dec 2008 23:33:35 -0800 (PST) Subject: Brain going crazy with recursive functions Message-ID: <6470511f-093e-42c2-a6c2-4bb90b336ac9@r15g2000prd.googlegroups.com> I'm trying to solve the 9-tile puzzle using as functional an approach as possible. I've recently finished reading SICP and am deliberately avoiding easy python-isms for the more convoluted scheme/functional methods. The following function is trivial to do with for loops and directly accessing arrays with [] syntax. I'm trying to limit myself to the types of idioms/semantics one finds in minimal scheme, such as in SICP. I want eventually to port this to scheme, but I know python better, so that's where I'm starting. My current problem is the following. The 9-tile puzzle consists of a list of lists like this [[1,2,3],[4,5,6],[7,8,0]], where the numbers can be jumbled up. I'm looking for the location of the zero using *only* recursion and operators that are similar to car/cdr. The return value should be the row,col of the zero. For example above the return value would be (2,2). I'm also trying to define a single "linear_search(...)" function which does the search for within the row (an inner list above) and within the whole list. linear_search takes as an argument a "truth_function" which does the actual work. What's tricky is that the truth function for the array-as-a-whole is also the linear_search for a row. Once I'm in linear_search for the array, I also call linear_search for each row. The problem is the line where it says acc.insert(0,idx) looks fishy to me. It works fine and returns the row,col of the location of the zero tile, but it seems to be mutating a variable, and that's the thing I'm trying to avoid. In a sense, it's not hard enough and python is making this too easy :) (although it took a bit of mind-wrenching to get to this point. Recursion makes you either dumber or smarter, I'm not sure which). How do I accumulate the inner value of the search so it pops out at the end, without resorting to a mutable variable? I did a bit of search and the word "monad" came up, but I'm not sure what that is (I know it relates to haskell and some other purely functional stuff, but I get very lost when trying to read that stuff). def linear_search(array, truth_func, acc): # Goes through each element of array and applies truth_func. # Returns index if found, otherwise returns None def linear_search_iter(idx, truth_func, arr, acc): if arr: tf = truth_func(arr[0]) if tf or type(tf) is int: acc.insert(0,idx) return idx, acc+[idx] else: return linear_search_iter(idx+1, truth_func, arr[1:], acc) return linear_search_iter(0, truth_func, array, acc) def locate_zero(p): # Locates empty tile. Returns (r,c) tuple def find_zero_in_row(row): return linear_search(row, lambda x: x==0, acc) acc = [] ls = linear_search(p, find_zero_in_row, acc) print acc return acc locate_zero([[5, 3, 4], [2, 0, 1], [8, 6, 7]]) correctly returns (1,1) From mail at timgolden.me.uk Mon Dec 22 11:57:26 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 22 Dec 2008 16:57:26 +0000 Subject: join a samba domain In-Reply-To: <5428c77b-ed4f-49ec-a808-dccd77a2a01c@g3g2000pre.googlegroups.com> References: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> <5428c77b-ed4f-49ec-a808-dccd77a2a01c@g3g2000pre.googlegroups.com> Message-ID: <494FC6F6.6000107@timgolden.me.uk> Toff wrote: > On 22 d?c, 17:02, Tim Golden wrote: >> Toff wrote: >>> hi, >>> I 'm trying to write a script to make my computer join a samba. >>> domeone have any idea ?? >> Ummm. It's not clear if you're saying that your code doesn't >> work, or asking for general advice, or what? I'm not in a >> position to have my machine join a domain or workgroup, but >> you seem to have got most things in place already. The only >> thing I would expect to have to change is this last line: >> >>> import wmi >>> c = wmi.WMI() >>> d = c.Win32_ComputerSystem >>> d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") >> because the d is only a WMI *class*, not a WMI *instance*, >> so doesn't refer as it should to your computer system but >> to the class of computer systems. Try something like this (untested): >> >> >> import wmi >> >> c = wmi.WMI () >> for d in c.Win32_ComputerSystem (): >> d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") >> >> >> >> TJG > thanks but it doesn't work > I've got this errors > > Traceback (most recent call last): > File "integrdom.py", line 51, in > main() > File "integrdom.py", line 13, in main > joindom() > File "integrdom.py", line 44, in joindom > d.JoinDomainOrWorkGroup(None, 3, "domcd", "adminLocal", r"admin > \domcd") > File "c:\Python25\Lib\site-packages\wmi.py", line 493, in __getattr__ > handle_com_error (error_info) > File "c:\Python25\Lib\site-packages\wmi.py", line 189, in > handle_com_error > raise x_wmi, "\n".join (exception_string) > wmi.x_wmi Do you not get *anything* after than wmi.x_wmi? Not even a messy exception string? TJG From dstanek at dstanek.com Mon Dec 22 10:27:49 2008 From: dstanek at dstanek.com (David Stanek) Date: Mon, 22 Dec 2008 10:27:49 -0500 Subject: Basic misunderstanding of generators In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF6024944BB@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF6024944BB@enbmail01.lsi.com> Message-ID: On Mon, Dec 22, 2008 at 4:47 AM, Barak, Ron wrote: > > if __name__ == "__main__": > filename = "sac.log.gz" > log_stream = LogStream(filename) > line_ = log_stream.next_line(log_stream.input_file) > print line_ > > $ python LogManager_try.py > > A method or function containing a yield statement will return a generator instance when called. Which is what is happening in your example. What you want to do is something like: for line in log_stream.next_line(log_stream.input_file): print line To make the code bit simpler and more OO you should not need to pass anything into next_line(). It is a part the object so it naturally has access to its properties. That being said you can then use __iter__ instead and then you can then do something like: for line in log_stream: print line OTOH If your LogStreamer class doesn't keep any additional state I would probably just create a single generator function. -- David http://www.traceback.org From saluk64007 at gmail.com Tue Dec 30 00:57:22 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Mon, 29 Dec 2008 21:57:22 -0800 Subject: How do I DRY the following code? In-Reply-To: References: Message-ID: On Mon, Dec 29, 2008 at 6:13 PM, R. Bernstein wrote: > How do I DRY the following code? > > class C(): > > def f1(self, arg1, arg2=None, globals=None, locals=None): > ... unique stuff #1 ... > ... some common stuff #1 ... > ret = eval(args, globals, locals) > ... more stuff #2 ... > return retval Possibly make a separate method with the common stuff. Make each variant function call various other methods with the "different stuff" being different arguments to shared functions, or calling slightly different methods. Take the code one issue at a time, this seems complex enough that there is no easy, quick refactoring that can be done. Something like this is what I see, but it's hazy: def f1(self,args): ... unique stuff #1 self.commonstuff1() ret = self.myeval(args) self.commonstuff2() return retval Looking at the actual code, my thoughts are that you pick the most common base "run" type and stick with that, making other run types modify that. For instance, you could pass an evaluator function in to the base run() method, and call that, instead of having a separate case for exec or eval. runfunc would pass in the function itself as the evaluator. So it looks more like this: def run(blah, blah, BLAH, BLAAAAAH, evaluator, locals, globals): do much stuff evaluator(code,locals,globals) do much other stuff def runfunc(blah, func): run(blah, value_defined_for_runfunc, func, locals, globals) def runeval(blah): run(blah, value_defined_for_runfunc, eval, locals globals) The thing I don't like about this is it could very well make the main run function even hairier than it already is. But I don't think it has to be that way. This may not be the ideal solution either, if you can get a nice set of lower-level methods which each run method compose in different ways to produce the final result. > f1(...): > "Docstring f1" > c = C() > return c.f1(...) > > f2(...): > "Docstring f2" > c = C() > return c.f2(...) Why not just do either this: C().f2(..) where you need f2 Or make the function an argument: f(name): c = C() return getattr(c,name)() I'm not sure why you need the top-level functions though. If you really need them, and don't want to add an extra argument, I don't think there is a simpler way to do than you have. From tommy.nordgren at comhem.se Thu Dec 11 23:06:33 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Fri, 12 Dec 2008 05:06:33 +0100 Subject: =?ISO-8859-1?Q?Re:_how_to_convert_=91\xf0'_to_0xf0_=3F?= In-Reply-To: References: Message-ID: On Dec 12, 2008, at 4:48 AM, chengang.beijing at gmail.com wrote: > int('\xf0',16) doesn't work, any way to do that? > -- > http://mail.python.org/mailman/listinfo/python-list Should be int('10',16) or int('0x10',16) ------------------------------------------------------ "Home is not where you are born, but where your heart finds peace" - Tommy Nordgren, "The dying old crone" tommy.nordgren at comhem.se From sonicsai at gmail.com Tue Dec 23 04:30:08 2008 From: sonicsai at gmail.com (sai) Date: Tue, 23 Dec 2008 01:30:08 -0800 Subject: No subject Message-ID: <41d04d600812230130j5893b288m44bf820f05484ad4@mail.gmail.com> From christophedeze at gmail.com Mon Dec 22 10:17:55 2008 From: christophedeze at gmail.com (Toff) Date: Mon, 22 Dec 2008 07:17:55 -0800 (PST) Subject: join a samba domain Message-ID: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> hi, I 'm trying to write a script to make my computer join a samba. domeone have any idea ?? thanks regards, ************************************************************************* # -*- coding: iso-8859-1 *-* import win32com.client import os,sys import win32api import impers import socket from win32com.client import GetObject import wmi def main(): test() joindom() def test(): import wmi c = wmi.WMI() os = c.Win32_ComputerSystem for method_name in os.methods: method = getattr(os, method_name) print method def joindom(): #Joining a computer to a domain #========================= JOIN_DOMAIN = 1 ACCT_CREATE = 2 ACCT_DELETE = 4 WIN9X_UPGRADE = 16 DOMAIN_JOIN_IF_JOINED = 32 JOIN_UNSECURE = 64 MACHINE_PASSWORD_PASSED = 128 DEFERRED_SPN_SET = 256 INSTALL_INVOCATION = 262144 strDomain = "mydom" strPassword = "mydompw" strUser = "admin" strComputer = socket.gethostname() print strComputer #objComputer = win32com.client.GetObject(r"winmgmts: {impersonationLevel=Impersonate}!\\mypc\root \cimv2:Win32_ComputerSystem.Name='mypc'") import wmi c = wmi.WMI() d = c.Win32_ComputerSystem d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") if __name__=='__main__': main() *********************************************************************** From jstroud at mbi.ucla.edu Thu Dec 4 04:44:50 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 04 Dec 2008 01:44:50 -0800 Subject: "as" keyword woes In-Reply-To: References: Message-ID: alex23 wrote: > On Dec 4, 3:42 pm, "Warren DeLano" wrote: >> So you prefer broken code to broken rules, eh? Your customers must love >> that! This is exactly the kind of ivory-tower thinking I feared might >> be behind the decision (form over function, damn the users to hell, >> etc.) > > Really? I find that believing something should remain static at the > expense of actual improvement to the language is far more 'ivory-tower > thinking' than embracing change. First, to quote Tim Peters, "practicality beats purity." Second, I might be biased here because I happen to know Warren, but, although he hails from the ivory tower, I imagine his concerns are purely practical. His contributions to software in structural biology are legendary. >> Am I the only one picking up on the irony here? "as" exists largely to >> provide a mechanism for working around namespace conflicts -- except, >> apparently, conflicts involving "as". The fact that "as" itself creates >> an insurmountable namespace collision is just killing me! How absurd. > > Speaking of irony, you're complaining about namespace conflicts with a > -two character identifier- you've chosen. Here's a hint: choose better > names. The name fit his needs until changes in the language broke the name. If a name works and the code works, then the name is good enough. And speaking as a professional user of his software at the level of the application and at the level of the API, let me tell you his code works pretty damn good. >> But to be brutally honest...in this many-core world we must all accept >> and deal with today, it is hard to imagine how a non-multithreaded AND >> non-backwards compatible Python implementation can have much of a life >> ahead of it, with or without an "as" keyword. I do sincerely hope I am >> wrong about this, but it is seems quite possible that C/Python's glory >> days are now behind us. > > To match your honesty, I'm somewhat tired with the trend of some > people to hit -one- issue with Python and suddenly lash out like > children over all the same old tired crap. Have you even looked at > multiprocessing? Have you contributed to any projects working on GIL- > less implementations? Or are you just regurgitating the same bullet > points we've heard time and time again? > > For chrissake, if you cannot do ANYTHING but BITCH about a change, > then you've no damn right to consider yourself a programmer. Real > programmers find solutions, not excuses. Correction: Real programmers write programs. And no, at this point he can't do anything but complain because, as others have noted, the change is not going away. >> And if so, then thank you all for so many wonderful years of effort and >> participation! > > You're welcome. Don't let the door hit you on the ass on your way out. You probably aren't a developer for the cPython implementation, but, if you were, I'd recommend taking rants like Warren's to heart because they are born of honest frustration and practical concern. Hopefully developers for python 2.7 are listening and won't break backward compatibility just because the "Zen of Python" suggests it might be a good idea. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From sjmachin at lexicon.net Mon Dec 29 04:59:13 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 29 Dec 2008 01:59:13 -0800 (PST) Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <0167cbf7$0$6988$c3e8da3@news.astraweb.com> <676bffeb-4b07-4226-8c14-7da57d94351b@f13g2000yqj.googlegroups.com> <3afba310-dcde-4dc1-825a-7c63b97e2a40@w1g2000prk.googlegroups.com> <495897c4$0$8481$426a74cc@news.free.fr> Message-ID: <7f340e90-c288-4592-8a4c-b008c24cf62a@q26g2000prq.googlegroups.com> On Dec 29, 8:26?pm, Bruno Desthuilliers wrote: > John Machin a ?crit : > > > > > On Dec 29, 7:06 am, Roger wrote: > >>> Curious. When I see a bare return, the first thing I think is that the > >>> author forgot to include the return value and that it's a bug. > >>> The second thing I think is that maybe the function is a generator, and > >>> so I look for a yield. If I don't see a yield, I go back to thinking > >>> they've left out the return value, and have to spend time trying to > >>> understand the function in order to determine whether that is the case or > >>> not. > >>> In other words, even though it is perfectly valid Python, bare returns > >>> always make the intent of the function less clear for me. I'm with Bruno > >>> -- if you have a function with early exits, and you need to make the > >>> intent of the function clear, explicitly return None. Otherwise, leave it > >>> out altogether. > >>> -- > >>> Steven > >> To me this is the soundest argument. ?Thanks for the advice. ?I think > >> I'll follow this as a rule of thumb hereafter. > > > Please don't. Follow MRAB's advice, with the corollary that a > > generator is forced by the compiler to be a "procedure" in MRAB's > > terminology. > > I fail to see any *practical* difference between MRAB's and Steven's > POVs. In both cases, it boils down to > - don't use a bare return at the end of a def statement's body, > - either use only bare returns ('procedure') or explicitely return None > ('function') Steven's treatment was somewhat discursive, and didn't explicitly mention the 'procedure' possibility. In fact, this sentence "if you have a function with early exits, and you need to make the intent of the function clear, explicitly return None." would if applied to a 'procedure' cause a stylistic horror as bad as a bare return at the end of the def. From toby at telegraphics.com.au Thu Dec 11 00:03:10 2008 From: toby at telegraphics.com.au (toby) Date: Wed, 10 Dec 2008 21:03:10 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: On Dec 10, 3:37 pm, w_a_x_... at yahoo.com wrote: > On Dec 5, 9:51 am, Xah Lee wrote: > > > > > For those of you who don't know linear algebra but knows coding, this > > means, we want a function whose input is a list of 3 elements say > > {x,y,z}, and output is also a list of 3 elements, say {a,b,c}, with > > the condition that > > > a = x/Sqrt[x^2+y^2+z^2] > > b = y/Sqrt[x^2+y^2+z^2] > > c = z/Sqrt[x^2+y^2+z^2] > > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, > > you'll have 50 or hundreds lines. void normalise(float d[], float v[]){ float m = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); d[0] = v[0]/m; // My guess is Xah Lee d[1] = v[1]/m; // hasn't touched C d[2] = v[2]/m; // for near to an eternitee } > > Ruby: > > def norm a > s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) > a.map{|x| x/s} > end From castironpi at gmail.com Thu Dec 4 23:15:46 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 4 Dec 2008 20:15:46 -0800 (PST) Subject: Overriding a method at the instance level on a subclass of a builtin type References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> <6828b153-bf5f-4cf0-8b37-68b15189841b@33g2000yqm.googlegroups.com> Message-ID: <0c69e493-669a-4503-b2ec-ae7cf5e7fa0c@t2g2000yqm.googlegroups.com> On Dec 4, 11:16?am, "Zac Burns" wrote: > The class method seems to be the most promising, however I have more > 'state' methods to worry about so I might end up building new classes > on the fly rather than have a class per permutation of states! Now the > code isn't quite as clear as I thought it was going to be. > > It seems unfortunate to me that methods are always looked up on the > class for new style objects. Was this done for speed reasons? I thought of two more solutions. One, derive a new class for each instance as you create it, and assign methods to that, that can be shared. Even more memory consumption though. >>> class A: ... def methA( self ): print 'methA' ... def methB( self ): print 'methB' ... >>> class A1(A): meth= A.methA ... >>> a1=A1() >>> a1.meth() methA >>> A1.meth=A.methB >>> a1.meth() methB Two, use getter properties to return the right function, based on index and array. >>> class A( object ): ... @property ... def meth( self ): ... return self.meths[ self.methA_i ].__get__( self, A ) ... def methA( self ): ... print 'methA' ... self.methA_i+= 1 ... def methB( self ): ... print 'methB' ... self.methA_i-= 1 ... meths= [ methA, methB ] ... def __init__( self ): ... self.methA_i= 0 ... >>> a= A() >>> a.meth() methA >>> a.meth() methB >>> a.meth() methA Or (two B), look up the method by name on name-index pair. >>> class A( object ): ... @property ... def meth( self ): ... return getattr( self, self.meths[ self.methA_i ] ) ... def methA( self ): ... print 'methA' ... self.methA_i+= 1 ... def methB( self ): ... print 'methB' ... self.methA_i-= 1 ... meths= [ 'methA', 'methB' ] ... def __init__( self ): ... self.methA_i= 0 ... >>> a= A() >>> a.meth() methA >>> a.meth() methB >>> a.meth() methA The 'meths' list will need separate lists for each 'group' of state- dependent functions you wish to use. From vkseashoremack at googlemail.com Sat Dec 20 11:56:46 2008 From: vkseashoremack at googlemail.com (vkseashoremack at googlemail.com) Date: Sat, 20 Dec 2008 08:56:46 -0800 (PST) Subject: lesbo land - Free Message-ID: <22d76a26-4fd1-4d1f-aef9-407fa1f1597a@t26g2000prh.googlegroups.com> lesbo land . . . *******CLICK HERE******** http://club247.cn/lesbo-land ***************************** . . . . . . . . . . . . lesbo land From rt8396 at gmail.com Tue Dec 2 16:17:52 2008 From: rt8396 at gmail.com (r) Date: Tue, 2 Dec 2008 13:17:52 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> Message-ID: <64deddc7-3d65-43de-bb2d-766c890a9ab8@33g2000yqm.googlegroups.com> "The devils in the details" From excord80 at gmail.com Sun Dec 7 19:15:13 2008 From: excord80 at gmail.com (excord80 at gmail.com) Date: Sun, 7 Dec 2008 16:15:13 -0800 (PST) Subject: Number of Python 3.x packages at the PyPI References: <9c1ab0f3-6686-4c0f-8a6c-12e20539f354@41g2000yqf.googlegroups.com> <493b954e$0$4021$9b622d9e@news.freenet.de> Message-ID: On Dec 7, 12:21?pm, s... at pobox.com wrote: > ? ? Martin>http://pypi.python.org/pypi?:action=browse&c=533 > > ? ? Martin> It seems that some package authors only classify with > > ? ? Martin> ? Programming Language :: Python :: 3 > > I did a release for lockfile yesterday which supports 3.0. ?I added the > "Programming Language :: Python :: 3.0" tag, but not the more inlusive tag > above. ?I just updated the information to include it so it now appears in > the search results. > > Skip Should specifying the 3.0 tag implicity and automatically specify the 3 tag as well? From metolone+gmane at gmail.com Fri Dec 5 09:50:36 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Fri, 5 Dec 2008 06:50:36 -0800 Subject: pretty strange behavior of "strip" References: <4938693F.6090709@yahoo.ca> <493936EC.9030606@yahoo.ca> Message-ID: "Guy Doune" wrote in message news:493936EC.9030606 at yahoo.ca... > Ok, didn't show the whole problem... > > I will read the doc anyway, but why "questions.html" keep it "t"?? > > >>> test=['03.html', '06.html', 'questions.html', '04.html', 'toc.html', > '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test[4] > 'toc.html' > >>> test[4].strip('.html') > 'oc' > >>> test[2].strip('.html') > 'questions' It doesn't strip the character set from the whole string, it strips it from the beginning and end of the string only. If it encounters a character that isn't in the set, it stops. Does this make it more clear? >>> 'aabdabcdccb'.strip('cba') 'dabcd' -Mark From sjmachin at lexicon.net Sat Dec 6 16:40:47 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 6 Dec 2008 13:40:47 -0800 (PST) Subject: Python 3.0 automatic decoding of UTF16 References: <5u8o06xbqf.ln2@joeserver.homelan.net> <1mmq06x4g6.ln2@joeserver.homelan.net> Message-ID: On Dec 7, 6:20?am, "Mark Tolonen" wrote: > "Johannes Bauer" wrote in message > > news:1mmq06x4g6.ln2 at joeserver.homelan.net... > > > > >John Machin schrieb: > >> On Dec 6, 5:36 am, Johannes Bauer wrote: > >>> So UTF-16 has an explicit EOF marker within the text? I cannot find one > >>> in original file, only some kind of starting sequence I suppose > >>> (0xfeff). The last characters of the file are 0x00 0x0d 0x00 0x0a, > >>> simple \r\n line ending. > > >> Sorry, *WRONG*. It ends in 00 0d 00 0a 00. The file is 1559 bytes > >> long, an ODD number, which shouldn't happen with utf16. ?The file is > >> stuffed. Python 3.0 has a bug; it should give a meaningful error > >> message. > > >Yes, you are right. I fixed the file, yet another error pops up > >(http://www.file-upload.net/download-1299688/2008_12_05_Handy_Backup.t... > > >Traceback (most recent call last): > > ?File "./modify.py", line 12, in > > ? ?a = AddressBook("2008_12_05_Handy_Backup.txt") > > ?File "./modify.py", line 7, in __init__ > > ? ?line = f.readline() > > ?File "/usr/local/lib/python3.0/io.py", line 1807, in readline > > ? ?while self._read_chunk(): > > ?File "/usr/local/lib/python3.0/io.py", line 1556, in _read_chunk > > ? ?self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) > > ?File "/usr/local/lib/python3.0/io.py", line 1293, in decode > > ? ?output = self.decoder.decode(input, final=final) > > ?File "/usr/local/lib/python3.0/codecs.py", line 300, in decode > > ? ?(result, consumed) = self._buffer_decode(data, self.errors, final) > > ?File "/usr/local/lib/python3.0/encodings/utf_16.py", line 69, in > >_buffer_decode > > ? ?return self.decoder(input, self.errors, final) > >UnicodeDecodeError: 'utf16' codec can't decode byte 0x0a in position 0: > >truncated data > > >File size is 1630 bytes - so this clearly cannot be. > > How about posting your code? He did. Ugly stuff using readline() :-) Should still work, though. There are definite problems with readline() and readlines(), including: First file: silently ignores error *and* the last line returned is garbage [consists of multiple actual lines, and the trailing codepoints have been byte-swapped] Second file: as he has just reported. I've reproduced it with f.open ('second_file.txt', encoding='utf16') followed by each of: (1) f.readlines() (2) list(f) (3) for line in f: print(repr(line)) With the last one, the error happens after printing the last actual line in his file. From Ron.Barak at lsi.com Thu Dec 25 10:21:13 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Thu, 25 Dec 2008 15:21:13 +0000 Subject: Question withdrawn: seek() returns unexpected results References: Message-ID: <7F0503CD69378F49BE0DC30661C6CCF60249470B@enbmail01.lsi.com> Hi, Problem solved when strip() is being replaced by strip('\n'). Happy holidays, Ron. ________________________________ From: Barak, Ron Sent: Thursday, December 25, 2008 15:05 To: 'python-list at python.org' Subject: seek() returns unexpected results Hi, When using seek() with a certain text file, I get strange results. I looked at the text file with a binary editor and verified with 'file', and it's an ASCII English text file. Running the script on other text files gives the expected output. Could you suggest the reason ? In the outputs below, when using generator.py as input for generator.py the 'diff' is a nice progression as expected. ('diff' is the difference between the file pointer location and the number of characters read up to now). However, when using sac.log as input for generator.py the 'diff' is a strange series: 1, 2, 1, 2, 3, 4, 5, 6 Running generator.py on a bigger portion of sac.log produces these 'diff's: 1, 2, 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, 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, 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, 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, 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, 32, 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, 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, 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, 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, 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, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 Thanks, Ron. ________________________________ $ cat -n generator.py 1 #!/usr/bin/env python 2 3 import gzip 4 import sys 5 from Debug import _line as line 6 7 class LogStream(): 8 9 def __init__(self, filename): 10 self.filename = filename 11 self.input_file = self.open_file(filename) 12 13 def open_file(self, in_file): 14 try: 15 f = gzip.GzipFile(in_file, "r") 16 f.readline() 17 except IOError: 18 f = open(in_file, "r") 19 f.readline() 20 f.seek(0) 21 return(f) 22 23 def line_generator(self): 24 while True: 25 line_ = self.input_file.readline() 26 print line()+". line_==|"+line_.strip()+"|" 27 self.total_chars += len(line_) 28 print line()+". line length:",len(line_),"; file pointer:",self.input_file.tell(), 29 print "; total chars:",self.total_chars,"; diff:",self.input_file.tell() - self.total_chars 30 if not line_: 31 break 32 yield line_.strip() 33 34 35 if __name__ == "__main__": 36 37 filename = sys.argv[1] 38 log_stream = LogStream(filename) 39 log_stream.input_file.seek(0) 40 log_stream.total_chars = 0 41 line_generator = log_stream.line_generator() 42 for i in range(8): 43 line_ = line_generator.next() $ python generator.py generator.py 26. line_==|#!/usr/bin/env python| 28. line length: 22 ; file pointer: 23 ; total chars: 22 ; diff: 1 26. line_==|| 28. line length: 1 ; file pointer: 25 ; total chars: 23 ; diff: 2 26. line_==|import gzip| 28. line length: 12 ; file pointer: 38 ; total chars: 35 ; diff: 3 26. line_==|import sys| 28. line length: 11 ; file pointer: 50 ; total chars: 46 ; diff: 4 26. line_==|from Debug import _line as line| 28. line length: 32 ; file pointer: 83 ; total chars: 78 ; diff: 5 26. line_==|| 28. line length: 1 ; file pointer: 85 ; total chars: 79 ; diff: 6 26. line_==|class LogStream():| 28. line length: 19 ; file pointer: 105 ; total chars: 98 ; diff: 7 26. line_==|| 28. line length: 5 ; file pointer: 111 ; total chars: 103 ; diff: 8 $ python generator.py sac.log 26. line_==|Dec 15 15:45:20 iSW-00-090 svm_sac[1714]: AGENT[0]: [tv_expand ] tv_expand:........[Domain 5:DVol1_3CG1-MM-1229347528T0] maxVolCapacityMB:....[5121] tempVolCapacityMB:...[512] fivePercentMB:.......[256] expandedTempVolCap:..[1024]| 28. line length: 246 ; file pointer: 247 ; total chars: 246 ; diff: 1 26. line_==|Dec 15 15:45:20 iSW-00-090 svm_sac[1714]: AGENT[0]: [daemon_send_expand_reque] [Domain 5:DVol1_3CG1-MM-1229347528T0]: Add expand request up to 1024 MB (2097152 sectors)| 28. line length: 170 ; file pointer: 418 ; total chars: 416 ; diff: 2 26. line_==|Dec 15 15:45:20 iSW-00-090 svm_sac[1746]: AGENT[0]: [domain_expand_exec ] [Domain 5:DVol1_3CG1-MM-1229347528T0]: Send expand up to 1024 MB (2097152 sectors): success| 28. line length: 172 ; file pointer: 589 ; total chars: 588 ; diff: 1 26. line_==|Dec 15 15:45:21 iSW-00-090 svm_sac[1744]: AGENT[0]: [domain_poll ] Domain [Domain 5]: SVM reported volume manager setup changed| 28. line length: 141 ; file pointer: 731 ; total chars: 729 ; diff: 2 26. line_==|Dec 15 15:45:21 iSW-00-090 svm_sac[1744]: AGENT[0]: [domain_poll ] Domain [Domain 5]: SVM reported multiview setup changed| 28. line length: 136 ; file pointer: 868 ; total chars: 865 ; diff: 3 26. line_==|Dec 15 15:45:21 iSW-00-090 svm_sac[1744]: AGENT[0]: [domain_is_setup_changed ] Domain [Domain 5]: Setup CHANGED| 28. line length: 113 ; file pointer: 982 ; total chars: 978 ; diff: 4 26. line_==|Dec 15 15:45:21 iSW-00-090 svm_sac[1744]: AGENT[0]: [domain_get_pages ] Domain [Domain 5]: Asked to get setup pages| 28. line length: 124 ; file pointer: 1107 ; total chars: 1102 ; diff: 5 26. line_==|Dec 15 15:45:21 iSW-00-090 svm_sac[1744]: AGENT[0]: [svm_get_pages ] SVM [Domain 5:12345]: got all setup pages| 28. line length: 122 ; file pointer: 1230 ; total chars: 1224 ; diff: 6 $ cat generator.py #!/usr/bin/env python import gzip import sys from Debug import _line as line class LogStream(): def __init__(self, filename): self.filename = filename self.input_file = self.open_file(filename) def open_file(self, in_file): try: f = gzip.GzipFile(in_file, "r") f.readline() except IOError: f = open(in_file, "r") f.readline() f.seek(0) return(f) def line_generator(self): while True: line_ = self.input_file.readline() print line()+". line_==|"+line_.strip()+"|" self.total_chars += len(line_) print line()+". line length:",len(line_),"; file pointer:",self.input_file.tell(), print "; total chars:",self.total_chars,"; diff:",self.input_file.tell() - self.total_chars if not line_: break yield line_.strip() if __name__ == "__main__": filename = sys.argv[1] log_stream = LogStream(filename) log_stream.input_file.seek(0) log_stream.total_chars = 0 line_generator = log_stream.line_generator() for i in range(8): line_ = line_generator.next() -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Sat Dec 6 17:56:33 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sat, 6 Dec 2008 17:56:33 -0500 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: On Sat, Dec 6, 2008 at 4:51 PM, Daniel Fetchinson wrote: > >> Hi folks, > >> > >> The story of the explicit self in method definitions has been > >> discussed to death and we all know it will stay. However, Guido > >> himself acknowledged that an alternative syntax makes perfect sense > >> and having both (old and new) in a future version of python is a > >> possibility since it maintains backward compatibility. The alternative > >> syntax will be syntactic sugar for the old one. This blog post of his > >> is what I'm talking about: > >> > >> > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html > >> > >> The proposal is to allow this: > >> > >> class C: > >> def self.method( arg ): > >> self.value = arg > >> return self.value > >> > >> instead of this: > >> > >> class C: > >> def method( self, arg ): > >> self.value = arg > >> return self.value > >> > >> I.e. explicit self stays only the syntax is slightly different and may > >> seem attractive to some. As pointed out by Guido classmethods would > >> work similarly: > >> > >> class C: > >> @classmethod > >> def cls.method( arg ): > >> cls.val = arg > >> return cls.val > >> > >> The fact that Guido says, > >> > >> "Now, I'm not saying that I like this better than the status quo. But > >> I like it a lot better than [...] but it has the great advantage that > >> it is backward compatible, and can be evolved into a PEP with a > >> reference implementation without too much effort." > >> > >> shows that the proposal is viable. > >> > >> I'd like this new way of defining methods, what do you guys think? > >> Anyone ready for writing a PEP? > >> > > What's the advantage? If there is not a good reason, I would strongly > > opposed polluting the language. > > Did you read the blog post? The advantage is having a less confusing > situation for newbies (confusing the number of arguments to a method > call). > 2 points about this: 1) You'd confuse newbies about the fact that self.foo() is just syntax sugar for cls.foo(self). The problem with newbies getting argument numbers still exists, just in the other case. This could also get confusing when you call methods for the super class class Foo : def self.bar() : ... class OtherFoo(Foo) ; def self.bar() : ... b = OtherFoo() cls = Foo cls.bar(b) 2) You'd have to allow this at the module level too (or else it violates the special cases part of the Zen). That would really confuse newbies. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rameshj at adventnet.com Fri Dec 12 05:37:26 2008 From: rameshj at adventnet.com (J Ramesh Kumar) Date: Fri, 12 Dec 2008 16:07:26 +0530 Subject: Interface & Implementation Message-ID: <11e2ac5b5eb.2364397661727502391.6806593866408074890@adventnet.com> Hi, I am new to python. I require some help on implementing interface and its implementation. I could not find any sample code in the web. Can you please send me some sample code which is similar to the below java code ? Thanks in advance for your help. ............ public interface MyIfc { public void myMeth1(); public void myMeth2(); } .... public class MyClass implements MyIfc { public void myMeth1() { //do some implementation } public void myMeth2() { //do some implementation } } ... MyClass myc=new MyClass(); Hashtable hash=new Hashtable(); hash.put("MYIFC",myc); ........ MyIfc myi=(MyIfc)hash.get("MYIFC"); myi.myMeth1(); myi.myMeth2(); ......... Thanks, Ramesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at microcorp.co.za Wed Dec 3 23:40:02 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 4 Dec 2008 06:40:02 +0200 Subject: Please fix your clock [was Re: Multiple equates] References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> <0147f4b7$0$20670$c3e8da3@news.astraweb.com> <20081204170017.4be41c7f@usenot.de> Message-ID: <002401c955ca$5fd63b80$0d00a8c0@hendrik> "Andreas Waldenburger" > On 04 Dec 2008 15:53:21 GMT Steven D'Aprano > wrote: > > > Hendrik, I think your PC's clock is wrong. You seem to be posting > > from the future. > > So? Maybe he is. What's your problem? It was probably playing hob with his threading reader... - Hendrik From gagsl-py2 at yahoo.com.ar Thu Dec 11 20:39:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 11 Dec 2008 23:39:28 -0200 Subject: Converting c header file to a python file References: Message-ID: En Thu, 11 Dec 2008 10:28:21 -0200, tarun escribi?: > I am looking for a tool/utility by which can convert c header file to a > python file. A typical header file that I want convert looks like: Locate h2py.py somewhere in your Python distribution. From the comments: # Read #define's and translate to Python code. # Handle #include statements. # Handle #define macros with one argument. # Anything that isn't recognized or doesn't translate into valid # Python is ignored. (doesn't convert *all* you want, but it's a start) -- Gabriel Genellina From BrianVanderburg2 at aim.com Tue Dec 9 06:31:12 2008 From: BrianVanderburg2 at aim.com (Brian Allen Vanderburg II) Date: Tue, 09 Dec 2008 06:31:12 -0500 Subject: How to initialize a class variable once In-Reply-To: References: Message-ID: <493E5700.4030107@aim.com> mccredie at gmail.com wrote: > > Unless you are calling reload() on the module, it will only ever get > _loaded_ once. Each additional import will just yield the existing > module. Perhaps if you post an example of the behavior that leads you > to believe that the class variables are getting reinitialized I can > provide more useful help. > > Matt > -- > http://mail.python.org/mailman/listinfo/python-list > There is one situation where a module can be imported/executed twice, if it is the __main__ module. Obviously the example below would be considered bad Python practice but it just shows how it can be done: main.py: class Blah(object): def action(self): print "action" print "import" if __name__ == "__main__": import app app.run() app.py: def run(): import main blah = main.Blah() blah.action() python main.py: import import action The reason is the first time main.py gets loaded, it is known as '__main__' but when app imports main, it is not in sys.modules so it loads 'main.py' again but this time as 'main' Brian Vanderburg II -------------- next part -------------- An HTML attachment was scrubbed... URL: From fakeaddress at nowhere.org Tue Dec 23 00:13:01 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 22 Dec 2008 21:13:01 -0800 Subject: Event Driven programming - Doubts In-Reply-To: <80f360e4-2880-4c66-a6b4-e05d6dbc9031@b41g2000pra.googlegroups.com> References: <80f360e4-2880-4c66-a6b4-e05d6dbc9031@b41g2000pra.googlegroups.com> Message-ID: Kottiyath wrote: > [...] I have not yet understood the implementation of > deferred. I went through a lot of tutorials, but I guess most places > they expect that the user already understands how events are > generated. The tutorials mention that there is no more threads once > twisted is used. > > My question is as follows: > I have not understood how the callbacks are hit without (a) > blocking the code or (b) having new threads. > > The usual example given is that of a program waiting for data coming > through a socket. In the tutorials, it is mentioned that -in an event > driven program, we schedule the code to hit when the remote server > gets back to us - . > Now, my question is - somebody has to still wait on that socket and > check whether the data is received, and once all the data is received, > call the appropriate callbacks. > > Is twisted creating a micro-thread which just waits on the socket and > once the data is received, calls callFromThread for it to run on the > main loop? No. Event-driven frameworks are built upon some system call that waits for events from multiple sources at once. The Python standard library exposes several such calls, the most portable of which is select(), in the module also named "select". http://docs.python.org/library/select.html So how is something like deferred implemented? When you schedule action on your socket, you are telling the framework to include your socket in in subsequent calls to select(), until the socket selects as ready. The framework keeps a single global list of sockets on which clients are waiting, and from this list it builds the select() parameters. A single call to select() waits on behalf of all the callbacks. The select() call returns a list of sockets ready for I/0; the framework iterates over the ready list, invoking the corresponding callbacks one by one. After the last callback returns, the framework loops back to select() again. select() is not the only call to do multi-source I/O, and I'm not an expert on these frameworks, so take the above as a simplified general description. -- --Bryan From prologic at shortcircuit.net.au Wed Dec 3 20:16:37 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 4 Dec 2008 11:16:37 +1000 Subject: Don't you just love writing this sort of thing :) In-Reply-To: References: Message-ID: uggh no! On Thu, Dec 4, 2008 at 11:07 AM, Lawrence D'Oliveiro wrote: > for \ > Entry \ > in \ > sorted \ > ( > f for f in os.listdir(PatchesDir) if PatchDatePat.search(f) != None > ) \ > : > Patch = (open, gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir, Entry), "r") > ... read from Patch ... > Patch.close() > #end for > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From lotro8520963 at gmail.com Mon Dec 8 21:27:14 2008 From: lotro8520963 at gmail.com (www.lotro-shop.com) Date: Mon, 8 Dec 2008 18:27:14 -0800 (PST) Subject: sell lotro gold ,This is the professional Lotro gold shop,come on!www.lotro-shop.com Message-ID: <7c248b60-6462-44fb-ab93-c6868749a0e2@r37g2000prr.googlegroups.com> In The Lord of the Rings OnlineTM: Shadows of AngmarTM (LOTRO), players can customize certain elements of the game's user interface (UI), also known as "skinning." While we don't allow you to do a full- scale UI replacement, we do give you the ability to replace selected visual elements of the UI. (A full list of these elements and their sizes is provided at the end of this overview.) This is an updated (and prettied up) version of the information that had originally been posted in their Beta forums which we had copied to our Developer Discussions - Tutorials & Other Helpful Information forum. It is a combination of the Skinning the LOTRO UI and Art Assets posts. http://www.lotro-shop.com http://www.aocgolds.net/ From tjreedy at udel.edu Fri Dec 5 12:55:53 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 05 Dec 2008 12:55:53 -0500 Subject: dict subclass and pickle bug (?) In-Reply-To: <6J7_k.6212$hc1.5967@flpi150.ffdc.sbc.com> References: <6J7_k.6212$hc1.5967@flpi150.ffdc.sbc.com> Message-ID: James Stroud wrote: > James Stroud wrote: >> Hello All, >> >> I subclassed dict and overrode __setitem__. When instances are >> unpickled, the __setstate__ is not called before the keys are assigned >> via __setitem__ in the unpickling protocol. >> >> I googled a bit and found that this a bug filed in 2003: It is an 'issue' reporting a possibly unexpected side-effect of protocol working as designed and documented. Possibly a design flaw, but not a bug in the narrow sense (in spite of the url of the issue tracker). >> http://bugs.python.org/issue826897 >> >> It is still "open" with "normal" priority. > > Here is the ugly "fix" I'm basically going to have to live with, it seems: > > class DictPlus(dict): > def __init__(self, *args, **kwargs): > self.extra_thing = ExtraThingClass() > dict.__init__(self, *args, **kwargs) > def __setitem__(self, k, v): > try: > do_something_with(self.extra_thing, k, v) > except AttributeError: > self.extra_thing = ExtraThingClass() > do_something_with(self.extra_thing, k, v) > dict.__setitem__(self, k, v) > def __setstate__(self, adict): > pass I took the liberty of adding this to the issue. > I can't imagine this bug has survived because there is no bug to fix. I have suggesting closing. Terry Jan Reedy From duncan.booth at invalid.invalid Mon Dec 22 03:59:13 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Dec 2008 08:59:13 GMT Subject: Are python objects thread-safe? References: Message-ID: RajNewbie wrote: > Say, I have two threads, updating the same dictionary object - but for > different parameters: > Please find an example below: > a = {file1Data : '', > file2Data : ''} > > Now, I send it to two different threads, both of which are looping > infinitely: > In thread1: > a['file1Data'] = open(filename1).read > and > in thread2: > a['file2Data'] = open(filename2).read > > My question is - is this object threadsafe? - since we are working on > two different parameters in the object. Or should I have to block the > whole object? > It depends exactly what you mean by 'threadsafe'. The GIL will guarantee that you can't screw up Python's internal data structures: so your dictionary always remains a valid dictionary rather than a pile of bits. However, when you dig a bit deeper, it makes very few guarantees at the Python level. Individual bytecode instructions are not guaranteed atomic: for example, any assignment (including setting a new value into the dictionary) could overwrite an existing value and the value which is overwritten may have a destructor written in Python. If that happens you can get context switches within the assignment. Other nasty things can happen if you use dictionaries from multiple threads. You cannot add or remove a dictionary key while iterating over a dictionary. This isn't normally a big issue, but as soon as you try to share the dictionary between threads you'll have to be careful never to iterate through it. You will probably find it less error prone in the long run if you get your threads to write (key,value) tuples into a queue which the consuming thread can read and use to update the dictionary. -- Duncan Booth http://kupuguy.blogspot.com From sjdevnull at yahoo.com Mon Dec 1 18:57:17 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Mon, 1 Dec 2008 15:57:17 -0800 (PST) Subject: Emacs vs. Eclipse vs. Vim References: Message-ID: <27757214-df90-4a33-8f44-65673c9ababd@20g2000yqt.googlegroups.com> On Nov 29, 3:44?pm, Josh wrote: > If you were a beginning programmer and willing to make an investment in > steep learning curve for best returns down the road, which would you pick? > > I know this topic has been smashed around a bit already, but 'learning > curve' always seems to be an arguement. If you feel that one is easier > or harder than the others to learn feel free to tell, but let's not make > that the deciding factor. Which one will be most empowering down the > road as a development tool? I'd strongly recommend not using an IDE but going with federated tools; this makes it easier to pick the editor, code navigation tool, build system, etc that you like best, and makes it easier to swap out one piece at a time if you don't like it. So of the choices mentioned, I'd go with emacs or vim if I were you. Personally I also find high value in picking an editor that can be run on a command-line terminal connection (e.g. when you're ssh'd into a remote server), but that may be less important depending on what sort of development you are doing. From rhamph at gmail.com Sun Dec 14 03:46:01 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Sun, 14 Dec 2008 00:46:01 -0800 (PST) Subject: __future__ and compile: unrecognised flags References: <20081213112917.6209.qmail@s461.sureserver.com> Message-ID: <1ef4c02f-9dac-4e06-8f45-eae839944425@d42g2000prb.googlegroups.com> On Dec 13, 6:03?am, Steve Holden wrote: > Poor Yorick wrote: > > I have a future statement in a script which is intended to work in 2.6 and 3. > > Shouldn't compile flags in __future__ objects essentially be noops for versions > > that already support the feature? doctest is complaining about unrecognised > > flags. ?This illustrates the problem: > > > ? ? Python 3.0 (r30:67507, Dec ?3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win > > ? ? 32 > > ? ? Type "help", "copyright", "credits" or "license" for more information. > > ? ? >>> from __future__ import unicode_literals > > ? ? >>> src = 'a = "hello"' > > ? ? >>> c1 = compile(src,'','exec',unicode_literals.compiler_flag) > > ? ? Traceback (most recent call last): > > ? ? ? File "", line 1, in > > ? ? ValueError: compile(): unrecognised flags > > This could arguably be classed as a bug given that the 2.6 documentation > for __future__ says "No feature description will ever be deleted from > __future__." However I suspect that the feature has been removed because > all string literals are Unicode in 3.0 and up, and 3.0 is allowed to > break compatibility. I don't think the rule about __future__ applies to compile(). From arnodel at googlemail.com Mon Dec 1 17:08:05 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 01 Dec 2008 22:08:05 +0000 Subject: optimization References: Message-ID: Neal Becker writes: > I noticed in some profiling, that it seems that: > > def Func (): > def something(): > ... > > It appears that if Func is called many times, this nested func > definition will cause significant overhead. Is this true? I guess > I've become accustomed to decent compilers performing reasonable > transformations and so have tended to write code for clarity. If something() can be defined outside Func(), how is it clearer to define it inside? -- Arnaud From castironpi at gmail.com Sat Dec 27 19:06:23 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 27 Dec 2008 16:06:23 -0800 (PST) Subject: ctypes & strings References: <334452.47084.qm@web30003.mail.mud.yahoo.com> <000f01c96822$5c300f00$0d00a8c0@hendrik> Message-ID: <23bb633f-494a-4390-9158-15ee0f1967e5@l33g2000pri.googlegroups.com> On Dec 27, 2:03?pm, "Gabriel Genellina" wrote: > En Sat, 27 Dec 2008 10:54:32 -0200, Hendrik van Rooyen ? > escribi?: > > > The c routine will actually break Python's normal string > > immmutability and give you back a changed ins. > > ...so don't do that! > If you require a mutable string to pass to C functions, use ? > ctypes.create_string_buffer() > > > It is in general not a good idea to change the passed string > > like I am doing - but you wanted to know how > > to pass a python string, and the outs example should get > > you going - a string is an array of characters in c... > > Hmmm, I don't think posting a potentially harmful example is actually a ? > good idea... > > -- > Gabriel Genellina One alternative would be to return a pair of Python strings. You might want to wrap the C function you have already in another one, which allocates buffers and creates Python objects. Hendrik is right, though. The ctypes module allows us to break string immutability within Python code. From BrianVanderburg2 at aim.com Sun Dec 7 10:31:21 2008 From: BrianVanderburg2 at aim.com (Brian Allen Vanderburg II) Date: Sun, 07 Dec 2008 10:31:21 -0500 Subject: Python idea/proposal to assist in single-archive python applications Message-ID: <493BEC49.2000500@aim.com> Python Community The following is just an idea that I considered that may be helpful in creating an application in a single archive easier and with less code. Such an application would be similar to jar files for Java. First, the application and all data files should be able to run either extracted or zipped up into an archive. When running an application as part of an archive, the first step Python would do would be to insert that archive into sys.path, and then load the internal file of the same name as the __main__ module. This zip file: myapp.zip | |-- myapp.py |-- myapp.pyc (optional) |-- application/ (main application package) |-- pixmaps/ |-- ... Could be run as something like: python --par myapp.zip In addition it is needed to be able to open a file just as easily whether that file is in the archive or not. Assuming that a datafile in an application may be located relative to the '__file__' attributes, the following will not work in an archive: file = open(os.path.join(os.path.dirname('__file__'), '..', 'pixmaps', 'splash.png')) However, a simple function, perhaps built-in, could be provided which would work for reading either internal files or regular files. That is, the function would be able to open a file '/path/to/file', and it would also be able to open a file '/path/to/zipfile.zip/internal/file'. If built in the function could also take advantage of the open modes 'rb', 'rt' and 'rU'. Currently this is not so easy. First it would require the user writing a function to be able to open a file internally and externally just as easily, using zipfile and StringIO for any internal files. Secondly, opening a file in such a way only allows binary opens, it can't take advantage of pythons 'rU' open mode if the application so needs. Also, it still requires an external startup script to set the path and import the internal module. If this function was provided in Python, then and application could fairly easily run just as well zipped up as they would unzipped. Brian Vanderburg II From roy at panix.com Sat Dec 6 13:30:13 2008 From: roy at panix.com (Roy Smith) Date: Sat, 06 Dec 2008 13:30:13 -0500 Subject: Learning Python now coming from Perl References: Message-ID: In article , aahz at pythoncraft.com (Aahz) wrote: > In article , > Bertilo Wennergren wrote: > > > >I don't suppose there is any introductory material out there that is > >based on Python 3000 and that is also geared at people with a Perl > >background? Too early for that I guess.. > > Honestly, the differences between 2.x and 3.0 are small enough that it > doesn't much matter, as long as you're not the kind of person who gets > put off by little problems. Because so much material is for 2.x, you > may be better off just learning 2.x first and then moving to 3.x. I'm not sure I agree. If you're starting out, you might as well learn the new stuff. Then there's no need to unlearn the old way. Using material meant for 2.x is likely to lead to confusion. If you don't know either, you'll never know if something isn't working as described because you're doing it wrong or if it's just not the same as it used to be. When everything is new, what seem like little stumbling blocks to experts become total blockers to people starting from zero. From lie.1296 at gmail.com Fri Dec 12 15:44:55 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 12 Dec 2008 20:44:55 +0000 (UTC) Subject: (Very Newbie) Problems defining a variable References: <49425146$0$8495$426a74cc@news.free.fr> <11c53a4a-de1e-4bee-ad60-a05befb6cbf4@a12g2000yqm.googlegroups.com> <7cb69ff5-9034-41cc-b667-d69329707b18@d36g2000prf.googlegroups.com> Message-ID: On Fri, 12 Dec 2008 04:58:36 -0800, feba wrote: > Actually, I have gedit set to four spaces per tab. I have no reason why > it's showing up that large on copy/paste, but the file itself is fine. You've set gedit to _show tabs_ as four spaces, but not to substitute tabs with four spaces. Go to gedit's preference where you change how many spaces is used to display tabs, right below it is "Insert spaces instead of tabs". From mail at johnohagan.com Sun Dec 14 22:32:08 2008 From: mail at johnohagan.com (John O'Hagan) Date: Mon, 15 Dec 2008 03:32:08 +0000 Subject: Python music sequencer timing problems In-Reply-To: <49451835$0$17068$6e1ede2f@read.cnntp.org> References: <3b52b652-df61-4eb4-bcff-0d1fb6f20891@r15g2000prh.googlegroups.com> <49451835$0$17068$6e1ede2f@read.cnntp.org> Message-ID: <200812150332.08748.mail@johnohagan.com> On Sun, 14 Dec 2008, Bad Mutha Hubbard wrote: > John O'Hagan wrote: > > On Wed, 10 Dec 2008, badmuthahubbard wrote: [...] > > from time import time, sleep > > > > start = time() > > for event in music: > > duration=len(event) #Really, the length of the event > > play(event) > > while 1: > > timer = time() > > remaining = start + duration - timer > > if remaining < 0.001: > > break > > else: > > sleep(remaining / 2) > > stop(event) > > start += duration > > > Very interesting approach, halving the remaining duration. Right now > I'm not working with note-offs, Csound takes care of the duration. I > just need to be able to call the notes at the right times. [...] I'm also using the above code without the "stop(event)" line for playing non-midi stuff (fixed-length samples for example), which from the sound of it also applies to your requirement - IOW, you _can_ use it just to start notes at the right time, because the note-playing loop sleeps till then. [...] > I also like and respect Fluidsynth, but I'm working on a pretty > microtonal system, and MIDI doesn't have enough microtonal support. > [...] I'm certainly not trying to convert you to Fluidsynth - I'm more likely to convert to Csound - but just for the record, you can do microtonal stuff fairly easily using Fluidsynth's "settuning" command. In my program I can use any equal-tempered division of the octave by preceding each set of events which require it with this: mesg = [ "select " + channel + " " + font + " " + bank+ " " + program + " \ntuning name 0 " + program + "\n"] for key in xrange(128): pitch = str((((key - 60) * 12.0 / divisor) + 60) * 100) mesg.append( "tune " + bank + " " + program + " " + str(key) + " " + pitch + "\n") mesg.append("settuning " + channel + " " + bank " " + program + "\n") mesg = ''.join(mesg) fluidsynth_socket.send(mesg) where "divisor" is the number you want to divide the octave by (the other names are self-descriptive). The reason for the "60"s in there is just to keep middle C where it is. For more complex/non-linear pitch-warping, the rest of the "pitch = " line could be replaced with any pitch-altering function taking "key" as an argument; but I haven't tried that yet. I'd be interested to hear about the microtonal system(s) you're using. Regards, John From skip at pobox.com Sat Dec 13 10:40:31 2008 From: skip at pobox.com (skip at pobox.com) Date: Sat, 13 Dec 2008 09:40:31 -0600 Subject: Why %e not in time.strftime directives? In-Reply-To: <38f9c4ba-d96d-47e1-b718-562bdc6718e9@t26g2000prh.googlegroups.com> References: <38f9c4ba-d96d-47e1-b718-562bdc6718e9@t26g2000prh.googlegroups.com> Message-ID: <18755.55151.493185.235108@montanaro-dyndns-org.local> Leo> Any special reasons? Nobody thought to add it? Got a patch? -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From pdorange at pas-de-pub-merci.mac.com Tue Dec 23 08:36:53 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Tue, 23 Dec 2008 14:36:53 +0100 Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> <1iscu14.oixxplpgajabN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <1isenn3.1g8fxa21aqzibkN%pdorange@pas-de-pub-merci.mac.com> Steven D'Aprano wrote: > But this is just duplicating what timeit already does. Trust me, learn to > use it, you won't be sorry. Here's a trick that took me a long time to > learn: instead of copying your functions into the setup code of timeit, > you can just import them. Thanks for the advise, i made the test using timeit and your very interesting method to import... Now i know how to use timeit simply ;-) New results on 1000 float values randomized from -500.0 to +500.0. Each test is timeit(1000) sign_0 : 0.375 sign_1 : 0.444 (+18%) sign_2 : 0.661 (+76%) sign_3 : 0.498 (+33%) It seems it don't change the relative results between the methods. Using timeit make measure accurate and remove print/range footprints. I also try Arnaud's proposition, it make sign_0 just a little better (-1%) -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From rt8396 at gmail.com Mon Dec 22 18:24:34 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 15:24:34 -0800 (PST) Subject: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> Message-ID: <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> You know what i hate more than a troll, a spineless jellyfish who goes around rating peoples post with one star. You are the lowest form of life. You are the same type of person who would key someones car in the parking lot. You do not have the balls to face you enemy. If who made a rating were visible, then i would have respect for you, but since you lurk in the shadows, you are scum. Come out and face me if you dare! I never have rated a post UNLESS i rate it with 5 stars, WHY, you ask, Because my balls are so big i walk around bow-legged! F'in Cowards! From clp at rebertia.com Wed Dec 17 19:06:35 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 17 Dec 2008 16:06:35 -0800 Subject: The rule of literal string In-Reply-To: <6f1677a9-1127-4e69-b536-d82e123324b1@z27g2000prd.googlegroups.com> References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> <_PmdnU59w62vGtTUnZ2dnUVZ_hSdnZ2d@pdx.net> <34028b73-7807-4e88-80bc-fe31a7b1a2a0@i20g2000prf.googlegroups.com> <6f1677a9-1127-4e69-b536-d82e123324b1@z27g2000prd.googlegroups.com> Message-ID: <47c890dc0812171606n18196cb9g5fdb8b7921cacd5c@mail.gmail.com> On Wed, Dec 17, 2008 at 3:52 PM, Li Han wrote: > Chris worte: > [snip] >> And repr("''") ==> "\"''\"" >> Which when print()-ed is: "''" >> And eval("''") is the same as entering two apostrophes ('') at the >> REPL, both of which give an empty string object. > > On my machine: >>>> repr("''") > '"\'\'"' > Han Well, I was kinda winging it and didn't actually use the interpreter for some of those. The point is that the output I gave _could_ reasonably be that of the interpreter (if the implementation details of repr() were slightly different; it would still meet the spec anyway) and illustrates the eval()-repr() relationship. Just keep in mind the equivalence rule and what repr() does should become obvious. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From geekmail at usenot.de Sat Dec 6 18:23:07 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sun, 7 Dec 2008 00:23:07 +0100 Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> Message-ID: <20081207002307.5d30f195@usenot.de> On Sat, 6 Dec 2008 14:39:34 -0800 (PST) "Russ P." wrote: > I don't know much about Perl, but my understanding is that a dollar > sign must be used every time a variable is dereferenced, as in bash or > other shell languages. What we are proposing here is something > entirely different: the dollar sign would simply be a shorthand for > "self". In Perl, the dollar sign is clutter, but in this case it > actually reduces clutter. > This is the weirdest thing. Not a month seems to go by that this old hat isn't dug up again. You're fighting windmills. Why do you think self has been around so long? Because it's the best choice? No, because it works and there just is no need to change it (where "need" is defined by the desires of the majority). Getting the Python comunity to replace self with something shorter will never compensate for the time you spent bullying it through. I'd much rather spend time coding than complaining, but that might be just me. (BTW: I have my editor set up so that "s" is expanded to "self" and "." is expanded to "self."; I virtually lose no time at all with self and would gain nothing from a change to it. And regarding line-lengths: My code lines tend to be shorter than my comments explaining them, but that may again be just me. Excuse my being stubborn. :) /W -- My real email address is constructed by swapping the domain with the recipient (local part). From gubatron at gmail.com Wed Dec 3 06:31:13 2008 From: gubatron at gmail.com (Gubatron) Date: Wed, 3 Dec 2008 03:31:13 -0800 (PST) Subject: Jython: Packing several .py on .jar, problem importing .py modules within the .jar Message-ID: Hello all, I've a problem with Jython and importing .py inside a jar. I'm putting .class and .py files inside .jar files. myjar.jar MyJar\SomeClass.class MyJar\main.py MyJar\otherModule.py So I add the myjar.jar to Jython's sys.path org.python.core.PySystemState pySys = new org.python.core.PySystemState(); pySys.path.insert(0,new PyString("/path/to/myjar.jar")); and execute main.py //We pass the PythonInterpreter the modified PySystemState PythonInterpreter i = new PythonInterpreter(null, pySys); //Find the entry in the jar for the python file and execute it. //It should be able to find any resource inside the jar. JarFile jFile = new JarFile("/path/to/myjar.jar"); ZipEntry zipEntry = jFile.getEntry("MyJar/main.py"); InputStream pythonInputStream = jFile.getInputStream(zipEntry); i.execfile(pythonInputStream); main.py will execute fine, it'll be able to do from MyJar import SomeClass with no problem However, If I try to import the other .py in the same jar, it won't find it: from otherModule import * or from MyJar.otherModule import * I always get this: ImportError: no module named otherModule at org.python.core.Py.ImportError(Unknown Source) at org.python.core.imp.import_first(Unknown Source) at org.python.core.imp.import_name(Unknown Source) at org.python.core.imp.importName(Unknown Source) at org.python.core.ImportFunction.load(Unknown Source) at org.python.core.ImportFunction.__call__(Unknown Source) at org.python.core.PyObject.__call__(Unknown Source) at org.python.core.__builtin__.__import__(Unknown Source) at org.python.core.imp.importFromAs(Unknown Source) at org.python.core.imp.importFrom(Unknown Source) at org.python.pycode._pyx1.f$0(:26) at org.python.pycode._pyx1.call_function() at org.python.core.PyTableCode.call(Unknown Source) at org.python.core.PyCode.call(Unknown Source) at org.python.core.Py.runCode(Unknown Source) at org.python.util.PythonInterpreter.execfile(Unknown Source) I've tried adding more paths to sys.path, with no luck: pySys.path.insert(0,new PyString("/path/to/myjar.jar/MyJar")); pySys.path.insert(0,new PyString("file:jar:/path/to/myjar.jar!")); and nothing works, any ideas would help. I know this has to work, because I previously had a problem where I couldn't do import os and then I added the "Lib/" folder inside jython.jar and now I'm able to import all those standard jython modules, so, somehow, jython is able to import .py within a .jar, help would be very much appreciated. Angel Leon From fetchinson at googlemail.com Sat Dec 6 16:50:34 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 6 Dec 2008 13:50:34 -0800 Subject: Guido's new method definition idea In-Reply-To: <50bbef6f-02e3-47d8-810c-179b89ccf62a@d32g2000yqe.googlegroups.com> References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> <20081206133704.1bed455c@usenot.de> <4d1a952e-25ad-4b36-ba46-ed35758331b0@e1g2000pra.googlegroups.com> <50bbef6f-02e3-47d8-810c-179b89ccf62a@d32g2000yqe.googlegroups.com> Message-ID: > Bad idea having two ways to do this. Pick one or the other! Maybe only this alternative syntax for python 4000? -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From lie.1296 at gmail.com Tue Dec 9 16:28:37 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 9 Dec 2008 21:28:37 +0000 (UTC) Subject: Guido's new method definition idea References: <014a071a$0$20670$c3e8da3@news.astraweb.com> <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> Message-ID: On Mon, 08 Dec 2008 20:55:16 +0000, Arnaud Delobelle wrote: > anthony.tolle at gmail.com writes: > >> class C: >> def createfunc(self): >> def self.func(arg): >> return arg + 1 >> >> Or, after the class definition is done, to extend it dynamically: >> >> def C.method(self, arg): >> self.value = arg >> >> ...which would be the equivalent of the following: >> >> def method(self, arg): >> self.value = arg >> C.method = method > > What about the following then? > > functions = {} > > def functions['square'](x): > return x*x > > def functions['cube'](x): > return x**3 > > -- > Arnaud -1. In most cases, it would generally be better as: def functions(x): return x.func() since the rule-of-thumb of OOP is that objects should do things by itself. This is also more in line with python's built-in functions, which merely calls the appropriate __special__ names. and whenever creating an object is too complex, that could easily be def functions(which, x): def _function_square(): return x*x def _function_cube(): return x**3 d = {'square': _function_square, 'cube': _function_cube, } return d[which]() From rt8396 at gmail.com Sat Dec 13 21:57:55 2008 From: rt8396 at gmail.com (r) Date: Sat, 13 Dec 2008 18:57:55 -0800 (PST) Subject: 1 or 1/0 doesn't raise an exception References: Message-ID: These are just the kind of things that make Python so beautiful ;) Thanks Guido! From alexoplocatie at gmail.com Thu Dec 18 07:00:27 2008 From: alexoplocatie at gmail.com (aka) Date: Thu, 18 Dec 2008 04:00:27 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> <0d9ea7cc-b5fb-4edb-be32-490aae9e7204@b41g2000pra.googlegroups.com> <0de3a7bf-a4c4-4103-a4e0-44313405fa94@z28g2000prd.googlegroups.com> <23d6710f-2c6d-4115-817a-053b8e96f1ce@z28g2000prd.googlegroups.com> Message-ID: <06edd327-f40c-46e7-b1a3-fbe1847cdcb3@40g2000prx.googlegroups.com> On 18 dec, 00:06, John Machin wrote: - Tekst uit oorspronkelijk bericht niet weergeven - - Tekst uit oorspronkelijk bericht weergeven - > On Dec 18, 3:15 am, aka wrote: > Do you mean that this file was created by whatever.UnicodeWriter? If > so, did you just now discover this information? > How do you know that "the UnicodeWriter is functioning perfectly"? > What does "functioning perfectly mean to you"? In particular, what > encoding is it using? > Which do you mean: > (a) you typed those lines into Notepad yourself > (b) you took a copy of a file created by whatever.UnicodeWriter, > opened it with Notepad, trimmed off some rows and columns, and saved > it again > ? > Here's a likely hypothesis: the file was written in utf16. In that > case: > either (i) you really want utf16 (why?), so: > (1) the csv module will not cope with it, and is not expected to cope > with it > (2) the whatever.UnicodeReader should (in order of preference): > (a) be allowed to find out for itself that 'utf16' is the go > (b) be told explicitly that 'utf16' is the go > (c) be served with a bug report > OR (ii) you really want utf8, so: > (1) the csv module should be happy > (2) the whatever.UnicodeWriter should be told to use 'utf8' > (3) the whatever.UnicodeReader should (in order of preference): > [as above but s/16/8/] The csv file originally was created by the UnicodeWriter class and was used for a mailmerge function with Microsoft Word which all functioned perfectly. The reverse did not: read back the outputted file so at last I editted it in Notepad, cutting off columns, but I didn't know that the encoding would remain even after that because it still caused problems. Now after testing from the Python command line with a csv file generated from Excel I could get it working so it had to be the encoding. Because the write side of my code, which uses the UnicodeWriter, was ok I didn't pay attention to the fact that I had changed the UW class from UTF-8 to UTF-16 because of difficulties with dutch characters like ? and ?. Then at last I tried changing back to UTF-8 and noticed both out -and input was working, including those special characters, so it was my unjustifiable conclusion that I couldn't get around these special characters at the write side without UTF-16 which ultimately got me in trouble with the read side. With your help I got it straight. Once again minimizing the problem to its bare basics and to prevent big steps is the key. Thanks a lot for your help John. BTW, the TurboGears code is not very different from Python, it just uses some extra identifiers around the Python code. From paul.nospam at rudin.co.uk Mon Dec 1 01:32:24 2008 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Mon, 01 Dec 2008 06:32:24 +0000 Subject: Emacs vs. Eclipse vs. Vim References: Message-ID: <878wr08kxz.fsf@rudin.co.uk> Clay Hobbs writes: > It has key commands with key modifiers to do simple tasks (such as > moving the cursor to the left). Err - you move the cursor to the left by pressing the left arrow key (as you do with virtually every other editor), unless you've made some strange key bind customisations. From gagsl-py2 at yahoo.com.ar Mon Dec 29 00:32:04 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Dec 2008 03:32:04 -0200 Subject: Otra vez Python en xkcd Message-ID: Hola En el especial de Navidad de este a?o: http://xkcd.com/521/ -- Gabriel Genellina From robert.kern at gmail.com Sun Dec 7 21:21:18 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 07 Dec 2008 20:21:18 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: References: <014c593e$0$20670$c3e8da3@news.astraweb.com> Message-ID: James Stroud wrote: > Steven D'Aprano wrote: >> On Sun, 07 Dec 2008 13:57:54 -0800, James Stroud wrote: >> >>> Rasmus Fogh wrote: > >>>>>>> ll1 = [y,1] >>>>>>> y in ll1 >>>> True >>>>>>> ll2 = [1,y] >>>>>>> y in ll2 >>>> Traceback (most recent call last): >>>> File "", line 1, in >>>> ValueError: The truth value of an array with more than one element is >>>> ambiguous. Use a.any() or a.all() >>> I think you could be safe calling this a bug with numpy. >> >> Only in the sense that there are special cases where the array >> elements are all true, or all false, and numpy *could* safely return a >> bool. But special cases are not special enough to break the rules. >> Better for the numpy caller to write this: >> >> a.all() # or any() >> >> instead of: >> >> try: >> bool(a) >> except ValueError: >> a.all() >> >> as they would need to do if numpy sometimes returned a bool and >> sometimes raised an exception. > > I'm missing how a.all() solves the problem Rasmus describes, namely that > the order of a python *list* affects the results of containment tests by > numpy.array. E.g. "y in ll1" and "y in ll2" evaluate to different > results in his example. It still seems like a bug in numpy to me, even > if too much other stuff is broken if you fix it (in which case it > apparently becomes an "issue"). It's an issue, if anything, not a bug. There is no consistent implementation of bool(some_array) that works in all cases. numpy's predecessor Numeric used to implement this as returning True if at least one element was non-zero. This works well for bool(x!=y) (which is equivalent to (x!=y).any()) but does not work well for bool(x==y) (which should be (x==y).all()), but many people got confused and thought that bool(x==y) worked. When we made numpy, we decided to explicitly not allow bool(some_array) so that people will not write buggy code like this again. The deficiency is in the feature of rich comparisons, not numpy's implementation of it. __eq__() is allowed to return non-booleans; however, there are some parts of Python's implementation like list.__contains__() that still expect the return value of __eq__() to be meaningfully cast to a boolean. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From fakeaddress at nowhere.org Thu Dec 18 05:00:50 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 18 Dec 2008 02:00:50 -0800 Subject: socket and subprocess problem In-Reply-To: References: <6d3291c3-4e12-4bdd-884a-21f15f38d105@a12g2000pro.googlegroups.com> <73dca20d-3378-4c96-aa30-f0617f111fa0@i18g2000prf.googlegroups.com> Message-ID: James Mills wrote: > subprocess process: > > #1. When my subprocess process has successfully > started notify the parent. > #2. When my subprocess process has successfully > created a listening socket, notify the parent. > > parent process: > > #1. When our subprocess process has > successfully started a listening socket > initiate a connection. I'd swear James copied my response, except his came first. Even the formatting came out similar. I hadn't seen his response when I wrote mine, and wouldn't have bothered posing the same thing again. -- --Bryan From mail at microcorp.co.za Wed Dec 17 09:01:31 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 17 Dec 2008 16:01:31 +0200 Subject: Transferring a file over sockets References: Message-ID: <002801c96050$251d57e0$0d00a8c0@hendrik> Ferdinand Sousa wrote: >========================================================== .# file receiver ># work in progress > >import socket > >s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >HOST = '192.168.1.17' >PORT = 31400 > >s.bind((HOST, PORT)) >s.listen(3) >conn, addr = s.accept() >print 'conn at address',addr >conn.send('READY') >f = open('C:\\Documents and Settings\\USER\\Desktop\\test.pdf','wb') >fsize=int(conn.recv(8)) >print 'File size',fsize >f.write(conn.recv(fsize)) This recv is not guaranteed to actually receive the number of characters you are asking for - it will stop when it has received that many, yes, but it may return with less, or even none if there is a time out set. The TCP is a more or less featureless stream of characters. Consider including a start marker so you know where the lesson starts. If you do this, consider the possibility of having a "false sync". Sending/receiving the length is good - also google for "netstring" Google for "escaping". Consider writing a loop to receive until the required length has been received - look at the docs for the recv function - it can tell you how much has been received. >f.close() >conn.close() >s.close() > >raw_input('Press any key to exit') > > >=========================================================== > ># file sender !!! ># Work in progress > >import socket, os >from stat import ST_SIZE > > >HOST = '192.168.1.17' >PORT = 31400 # Arbitrary non-privileged port > >s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > >s.connect((HOST,PORT)) >if s.recv(5)!='READY': > raw_input('Unable to connect \n\n Press any key to exit ...') > s.close() > exit() > >f=open('C:\\Documents and Settings\\USER\\Desktop\\t.pdf', 'rb') >fsize=os.stat(f.name)[ST_SIZE] > >s.send(str(fsize)) >s.send(f.read()) Are you sure that the send will send all the chars that you ask it to send? If yes - why do you think this? What are the values that the send can return? > >s.close() >f.close() > >=========================================================== hth - Hendrik From w_a_x_man at yahoo.com Thu Dec 11 06:53:15 2008 From: w_a_x_man at yahoo.com (William James) Date: 11 Dec 2008 11:53:15 GMT Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> Message-ID: William James wrote: > John W Kennedy wrote: > > > Xah Lee wrote: > > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or > > > Java, you'll have 50 or hundreds lines. > > > > > Java: > > > > static float[] normal(final float[] x) { > > float sum = 0.0f; > > for (int i = 0; i < x.length; ++i) sum += x[i] * x[i]; > > final float divisor = (float) Math.sqrt(sum); > > float[] a = new float[x.length]; > > for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor; > > return a; > > } > > "We don't need no stinkin' loops!" > > SpiderMonkey Javascript: > > function normal( ary ) > { div=Math.sqrt(ary.map(function(x) x*x).reduce(function(a,b) a+b)) > return ary.map(function(x) x/div) > } The variable "div" shouldn't be global. function normal( ary ) { var div = Math.sqrt( ary.map(function(x) x*x).reduce(function(a,b) a+b) ) return ary.map(function(x) x/div) } From arnodel at googlemail.com Wed Dec 10 02:03:30 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 10 Dec 2008 07:03:30 +0000 Subject: Best way to report progress at fixed intervals References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> <817384d5-5f68-4c1f-9560-0bc7b7d2b1e3@v5g2000prm.googlegroups.com> <6ccb77a2-a3f1-4b6b-900c-d4626be9e939@s1g2000prg.googlegroups.com> Message-ID: Slaunger writes: > On 10 Dec., 03:44, George Sakkis wrote: >> On Dec 9, 11:40?am, Slaunger wrote: >> >> > I would therefore like some feedback on this proposed generic "report >> > progress at regular intervals" approach presented here. What could I >> > do better? >> >> There is a pypi package that might do what you're looking for (haven't >> used it though):http://pypi.python.org/pypi/progressbar/. >> >> HTH, >> George > > Thank you. I will keep that in mind, if I ever get to doing GUI-based > progress. > > -- Slaunger It's a text progress bar -- Arnaud From rt8396 at gmail.com Sun Dec 28 12:33:19 2008 From: rt8396 at gmail.com (r) Date: Sun, 28 Dec 2008 09:33:19 -0800 (PST) Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> Message-ID: On Dec 28, 11:19?am, Roger wrote: > Hi Everyone, > > First I want to thank everyone that posts to this group. ?I read it > daily and always learn something new even if I never feel like I have > anything to contribute but my questions. > > When I define a method I always include a return statement out of > habit even if I don't return anything explicitly: > > def something(): > ? ? ? ? # do something > ? ? ? ? return > > Is this pythonic or excessive? ?Is this an unnecessary affectation > that only adds clock ticks to my app and would I be better off > removing "returns" where nothing is returned or is it common practice > to have returns. > > Even when I'm not explicitly returning something I like to add > "return" because it's a good additional visual marker for me to see > where a method definition ends especially in cases where I may use a > nested method. > > Thanks for the discussion! > Roger. returning nothing does nothing :) From george.sakkis at gmail.com Tue Dec 9 21:44:23 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 9 Dec 2008 18:44:23 -0800 (PST) Subject: Best way to report progress at fixed intervals References: <1b347638-e61d-4ea1-8e01-992e8552de45@t39g2000prh.googlegroups.com> Message-ID: <817384d5-5f68-4c1f-9560-0bc7b7d2b1e3@v5g2000prm.googlegroups.com> On Dec 9, 11:40?am, Slaunger wrote: > I would therefore like some feedback on this proposed generic "report > progress at regular intervals" approach presented here. What could I > do better? There is a pypi package that might do what you're looking for (haven't used it though): http://pypi.python.org/pypi/progressbar/. HTH, George From rdcollum at gmail.com Thu Dec 18 14:48:36 2008 From: rdcollum at gmail.com (Roger) Date: Thu, 18 Dec 2008 11:48:36 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <71ede5f0-fd88-4155-9f0d-42d0ad5f57dc@v42g2000yqj.googlegroups.com> <61f45e65-2404-4cc0-9d81-f848c1ba566f@i18g2000prf.googlegroups.com> Message-ID: On Dec 18, 12:49?pm, r wrote: > Maybe someone will chime in with an answer, sorry i could not help. > ponder this, i must... Regardless, thanks for your help! I truly appreciate it. Roger. From raviforlkml at gmail.com Mon Dec 1 20:48:22 2008 From: raviforlkml at gmail.com (raviforlkml at gmail.com) Date: Mon, 1 Dec 2008 17:48:22 -0800 (PST) Subject: Loading required libraries for python script from shell just once Message-ID: I have a linux-like host running busybox with the python installation mounted over NFS and have the corresponding symlinks setup in /usr/bin and /usr/lib for python to run smoothly. A shell script runs my python script several times, each time with different paramters. E.g. # cat foo.sh # Lot of setup stuff ${TEST_DIR}/bin/run-test.py --arg1 foo1 --arg2 bar1 --arg3 baz1 ${TEST_DIR}/bin/run-test.py --arg1 foo2 --arg2 bar2 --arg3 baz2 ${TEST_DIR}/bin/run-test.py --arg1 foo3 --arg2 bar3 --arg3 baz3 There is a delay of about 10-15 seconds before run-test.py starts executing. Can someone suggest a method to speed up this process? Most of the delay seems to be due to python loading up the required modules. Is it possible to load all the modules used by run-test.py in a pre-execution environment in order to prevent this delay? I considered a rewrite of the shell script into python, but it has too many dependencies on shell libraries and I don't want to go that route (unless an alternative solution is impossible). Thanks! From bj_666 at gmx.net Sat Dec 13 06:23:25 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 13 Dec 2008 11:23:25 GMT Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> <87iqpoc1l0.fsf@mulj.homelinux.net> Message-ID: <6qhk9dFclvujU1@mid.uni-berlin.de> On Sat, 13 Dec 2008 02:20:59 +0100, Hrvoje Niksic wrote: > Saner (in this respect) behavior in the tuple example would require a > different protocol. I don't understand why Python doesn't just call > __iadd__ for side effect if it exists. The decision to also rebind the > result of __i*__ methods continues to baffle me. I guess it is a result > of a desire to enable the __i*__ methods to punt and return a different > instance after all, but if so, that design decision brings more problems > than benefits. How often do you use ``+=`` with mutable objects? I use it very often with number types and sometimes with tuples, and there rebinding is necessary. If I couldn't use it in this way: ``x = 0; x += z``, I'd call that a bad design decision. It would be a quite useless operator then. Ciao, Marc 'BlackJack' Rintsch From Russ.Paielli at gmail.com Sat Dec 6 02:41:11 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Fri, 5 Dec 2008 23:41:11 -0800 (PST) Subject: Guido's new method definition idea References: Message-ID: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> On Dec 5, 6:21?pm, "Daniel Fetchinson" wrote: > Hi folks, > > The story of the explicit self in method definitions has been > discussed to death and we all know it will stay. However, Guido > himself acknowledged that an alternative syntax makes perfect sense > and having both (old and new) in a future version of python is a > possibility since it maintains backward compatibility. The alternative > syntax will be syntactic sugar for the old one. This blog post of his > is what I'm talking about: > > http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... > > The proposal is to allow this: > > class C: > ? ? def self.method( arg ): > ? ? ? ? self.value = arg > ? ? ? ? return self.value > > instead of this: > > class C: > ? ? def method( self, arg ): > ? ? ? ? self.value = arg > ? ? ? ? return self.value > > I.e. explicit self stays only the syntax is slightly different and may > seem attractive to some. As pointed out by Guido classmethods would > work similarly: > > class C: > ? ? @classmethod > ? ? def cls.method( arg ): > ? ? ? ? cls.val = arg > ? ? ? ? return cls.val > > The fact that Guido says, > > "Now, I'm not saying that I like this better than the status quo. But > I like it a lot better than [...] but it has the great advantage that > it is backward compatible, and can be evolved into a PEP with a > reference implementation without too much effort." > > shows that the proposal is viable. > > I'd like this new way of defining methods, what do you guys think? > Anyone ready for writing a PEP? > > Cheers, > Daniel > > -- > Psss, psss, put it down! -http://www.cafepress.com/putitdown I like it. I'll even go a step further and suggest that "$" be allowed as a substitute for "self". It looks like a capital "S" (for Self), and it stands out clearly. It also makes code more succinct with no loss of readability. Think of the line wraps that could be avoided. From steve at REMOVE-THIS-cybersource.com.au Mon Dec 22 05:44:39 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Dec 2008 10:44:39 GMT Subject: How to represent a sequence of raw bytes References: <200812220327.36180.motoom@xs4all.nl> Message-ID: <015f66d7$0$20615$c3e8da3@news.astraweb.com> On Mon, 22 Dec 2008 14:56:45 +0800, Steven Woody wrote: > The intension is to allocate 200 undefined bytes in memory. You *want* undefined bytes? Out of curiosity, what do you intend to do with them? -- Steven From google at mrabarnett.plus.com Fri Dec 12 11:47:43 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 12 Dec 2008 16:47:43 +0000 Subject: newbie question: if var1 == var2: In-Reply-To: <87myf1z8n7.fsf@daycos.com> References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> <87y6ymzecp.fsf@daycos.com> <87myf1z8n7.fsf@daycos.com> Message-ID: <494295AF.1070308@mrabarnett.plus.com> Kirk Strauser wrote: > At 2008-12-12T15:35:11Z, "J. Cliff Dyer" writes: > >> Python has a version equally good: >> >> def chomp(s): >> return s.rstrip('\r\n') >> >> You'll hardly miss Perl at all. ;) > > I haven't missed Perl in years! I just wish there was a basestring.stripeol > method because I seem to end up writing the inline version of "chomp" every > time I iterate across a file. > Python is open source. You could suggest adding it and/or provide a patch. From sturlamolden at yahoo.no Fri Dec 12 09:50:27 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 06:50:27 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <44c3b44c-35d1-44ed-a71c-6fcd538b0860@r15g2000prh.googlegroups.com> <0f9cc0ff-8c20-4671-acc9-30bbcc51023c@w39g2000prb.googlegroups.com> <9cec8160-4641-4d3a-bde1-fa835c56f37e@s9g2000prm.googlegroups.com> <250cbfac-9c9d-47b7-b67b-6531db30e3ba@q26g2000prq.googlegroups.com> <49427875$0$30229$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <0c3e89f2-b67c-4da5-bd33-87c98ee48812@z28g2000prd.googlegroups.com> On Dec 12, 3:43 pm, Stefan Behnel wrote: > http://cython.org/ How is the numpy support in Cython going? It was supposed to know about ndarrays natively. I.e. not treat them as Python objects, but rather as known C structs. That way an operation like arr[n] would not result in a callback to Python, but translate directly to fast pointer arithmetics. From aleksandr.goretoy at gmail.com Sat Dec 27 06:10:06 2008 From: aleksandr.goretoy at gmail.com (alex goretoy) Date: Sat, 27 Dec 2008 05:10:06 -0600 Subject: parsing csv files class In-Reply-To: References: Message-ID: I know it's messy with all those self.soc.* functions, but it works in one of my current project. I just want to make it more pythonic I also want to add capability for makeing csv file if I give it input like: 1234,something nice, hey this is something nice 2468,something else, something else On Sat, Dec 27, 2008 at 4:54 AM, alex goretoy wrote: > Hello All, > > I have this class that I use in one of my projects. I know it's missing > functionality and some things could have been done differently. Can you ehlp > me make this class better? What can I do to make it more resistant to error? > You can find the stdout_colours class on Google if you want it, JFGI I want > to make it more pythonic. I come from a PHP background, can you tell? > > Any and all help is appreciated > -Alex > > #!/usr/bin/env python > from ctypes import * > import os, sys, types, csv, urllib, urllib2, urlparse, > string,stdout_colours > > class parsercsvy(object): > """Return a line from a csv file or total amount of lines""" > def __init__(self,file_name=""): > self.func_me_color="white_on_black" > self.soc=stdout_colours.stdout_colors() > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > self.filename = file_name > self.buffer = [] > self.bufferp= [] > if string.find(self.filename,"http") != -1: > resp=urllib2.urlopen(self.filename) > file=resp.read() > lfi=len(string.split(self.filename,"/")) > filename = "/tmp/"+string.split(self.filename,"/")[lfi-1] > f=open(filename,"w") > f.write(file) > f.close > self.parse(self.filename) > else: > self.parse(self.filename) > self.soc.me_him(['EXIT:',__name__],self.func_me_color) > def parse(self,filename,ret=0): > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > i = 0 > try: > reader = csv.reader(file(filename, "rb")) > try: > for row in reader: > self.buffer.append(row) > s,a=[],{} > > for j in range(len(self.buffer[0])): > a[self.buffer[0][j]]=row[j] > self.bufferp.append(a) > i+=1 > self.total = i-1 > except csv.Error, e: > sys.exit('file %s, line %d: %s' % (filename, > reader.line_num, e)) > except IOError, e: > sys.exit('file %s, IOError: %s' % (filename, e)) > self.soc.me_him(['EXIT:',__name__],self.func_me_color) > def index(self, index): > """return line for index""" > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > > self.soc.me_him(['RETURN:',self.buffer[int(index)],__name__],self.func_me_color) > return self.buffer[int(index)] > def total(self): > """return total number of lines in csv file""" > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > self.soc.me_him(['RETURN:',self.total,__name__],self.func_me_color) > return self.total > def header(self): > """return csv header == line 0""" > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > > self.soc.me_him(['RETURN:',self.buffer[0],__name__],self.func_me_color) > return self.buffer[0] > def find_and_replace(self,li,fi,re): > """ > find and replace a string inside a string, return list > find_and_replace(list,find,replace) > """ > this=[] > for l in li: > # found_index=string.find(l,fi) > this.append(l.replace(fi,re)) > return this > def return_buffer(self): > self.soc.me_him(['ENTER:',__name__],self.func_me_color) > > self.soc.me_him(['RETURN:',self.buffer,__name__],self.func_me_color) > return self.buffer > if __name__ == "__main__": > if len(sys.argv) < 1: > print "Usage: %s file"% sys.argv[0] > f=sys.argv[1] > c=csv_parser(f) > print c.bufferp > -- > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > -- ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? -------------- next part -------------- An HTML attachment was scrubbed... URL: From Kevin.Smith at sas.com Tue Dec 2 11:19:22 2008 From: Kevin.Smith at sas.com (Kevin D. Smith) Date: Tue, 2 Dec 2008 10:19:22 -0600 Subject: Debugging a Python Program that Hangs Message-ID: I have a fairly large python program that, when a certain combination of options is used, hangs. I have no idea where it is hanging, so simply putting in print statements to locate the spot would be quite difficult. Unfortunately, ctrl-C'ing the program doesn't print a traceback either. Looking through the python debugger documentation, I don't see how to run a python program and interactively stopping it while it is running. Is there a way to stop within a running python program to see where it is getting hung up? -- Kevin D. Smith From dfnsonfsduifb at gmx.de Mon Dec 29 21:17:44 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Tue, 30 Dec 2008 03:17:44 +0100 Subject: SQL, lite lite lite In-Reply-To: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> Message-ID: <8vco26x1v6.ln2@joelaptop.homelan.net> Aaron Brady schrieb: > This is basically an invitation for everyone to brainstorm. (No > hijackings, good humor & digression ok.) Lastly, ... Even if it took (as you mentioned) a semester of SQL studies - which it does not - why do you think your syntax is easier? The only person your proposed syntax is easier for is you. Get over it, learn SQL, and enjoy the benefits of one unified standard - not everyone cooking their own soup. You'll be able to learn PostgreSQL, Oracle SQL, mySQL, SQlite all at once! Regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From bj_666 at gmx.net Fri Dec 19 16:10:12 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Dec 2008 21:10:12 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> <88ff7c46-2b23-49e4-865e-781d23433799@l33g2000pri.googlegroups.com> Message-ID: <6r2gtkFfb5kpU5@mid.uni-berlin.de> On Fri, 19 Dec 2008 10:44:25 -0800, r wrote: > ~Bearophile, > Thanks for your civil approach to this conversation but I must disagree > with you on the new string formatting syntax. You said the new syntax is > suppost to be easier on the n00b , I say it pollutes a students mind. > What is wrong with similarities to C formatting, I find nothing > complicated about it. > > %s (means put a string here) > %d (means put a integer here) > %f (means put a float here) > > It does not get any simpler than that, Well for those simple cases you could simply use '%s' for strings, integers, and floating point objects in Python. But '{0}' isn't more complicated. But you get the extra flexibility to decouple the order in the string and the order of the objects to be formatted. > and this will just ease the transition to C programming for this > student. Lets not forget how important C is! To a Python "n00b"? Not important at all. Beside the point that '%s' is still possible -- someone who knows C but struggles with replacing '%s' by '{0}' has far greater problems. Ciao, Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Wed Dec 10 22:45:07 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 10 Dec 2008 19:45:07 -0800 (PST) Subject: How to convert uint64 in C into Python 32bit Object [ I am using Python2.2 ] References: <069f0d65-a3d5-4e8f-a85b-c53743ab99d0@i18g2000prf.googlegroups.com> Message-ID: <8485fb8f-4425-436d-9e0b-2079c80c9802@q26g2000prq.googlegroups.com> On Dec 11, 9:49?am, Explore_Imagination wrote: > Hi all > > I am new to C and python ... I want to convert C data type uint64 > variable into the Python 32bit Object. I am currently using Python 2.2 > [ It is necessary to use it ] > > Kindly give your suggestion how and in which way I can achieve this > task. I'm not sure what you mean by "the Python 32bit Object". A Python int object holds a signed 32-bit integer. A Python long object holds a signed integer of arbitrary size. You will need to convert your uint64 into a Python long; then, if necessary, check that the result will fit in an int (result <= sys.maxint). If the "C variable" is in an 8-byte string that you have read from a file, the unpack function in the struct module will do the job. Assuming your computer is little-endian: >>> maxu64 = '\xff' * 8 # example input string >>> import struct >>> result = struct.unpack('>> result 18446744073709551615L >>> 2 ** 64 - 1 18446744073709551615L If however you mean that in C code you need to build a Python object to pass over to Python code: According to the Python/C API Reference Manual (http://www.python.org/doc/2.2.3/api/longObjects.html): PyObject* PyLong_FromUnsignedLongLong(unsigned long long v) Return value: New reference. Returns a new PyLongObject object from a C unsigned long long, or NULL on failure. If however you mean something else, .... HTH, John From luismgz at gmail.com Sat Dec 20 10:44:03 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Sat, 20 Dec 2008 07:44:03 -0800 (PST) Subject: Namespaces, multiple assignments, and exec() References: Message-ID: <9405cec7-0b51-46e1-a20e-0c11ce036234@k8g2000yqn.googlegroups.com> On Dec 19, 11:34?pm, John O'Hagan wrote: > I have a lot of repetitive assignments to make, within a generator, that use a > function outside the generator: > > var1 = func("var1", args) > var2 = func("var2", args) > var3 = func("var3", args) > etc... > > In each case the args are identical, but the first argument is a string of the > name being assigned. It works fine but I'd like to reduce the clutter by > doing the assignments in a loop. I've tried using exec(): > > for name in name_string_list: > ? ? exec(name + ' = func(\"' + name + '\", args)') > > but in the local namespace it doesn't understand func(), and if I give it > globals() it doesn't understand the args, which come from within the > generator. > > What's a good way to do this kind of thing? > > Thanks, > > John Why don't you just use a dictionary? d = {} for name in name_string_list: d[name] = func(name, args) Luis From 20080915.20.wmcclain at spamgourmet.com Tue Dec 9 13:41:26 2008 From: 20080915.20.wmcclain at spamgourmet.com (Bill McClain) Date: 9 Dec 2008 18:41:26 GMT Subject: StringIO in 2.6 and beyond References: Message-ID: On 2008-12-09, Peter Otten <__peter__ at web.de> wrote: > >>> out = io.StringIO() > >>> print(u"hello", file=out, end=u"\n") > >>> out.getvalue() > u'hello\n' That has the benefit of working. Thank you! That can't be the intended behavior of print(), can it? Insering non-unicode spaces and line terminators? I thought all text was unicode now. Or is that only in 3.0? -Bill -- Sattre Press History of Astronomy http://sattre-press.com/ During the 19th Century info at sattre-press.com by Agnes M. Clerke http://sattre-press.com/han.html From narkewoody at gmail.com Mon Dec 22 09:52:30 2008 From: narkewoody at gmail.com (Steven Woody) Date: Mon, 22 Dec 2008 22:52:30 +0800 Subject: How to represent a sequence of raw bytes In-Reply-To: <015f66d7$0$20615$c3e8da3@news.astraweb.com> References: <200812220327.36180.motoom@xs4all.nl> <015f66d7$0$20615$c3e8da3@news.astraweb.com> Message-ID: On Mon, Dec 22, 2008 at 6:44 PM, Steven D'Aprano wrote: > On Mon, 22 Dec 2008 14:56:45 +0800, Steven Woody wrote: > >> The intension is to allocate 200 undefined bytes in memory. > > You *want* undefined bytes? Out of curiosity, what do you intend to do > with them? > to receive/send network packets, read raw files, etc. After read replies of the thread, I think 'array' or 'struct' maybe what I wanted, may a plain list can do, but I am not sure. From python.leojay at gmail.com Thu Dec 11 05:54:54 2008 From: python.leojay at gmail.com (Leo Jay) Date: Thu, 11 Dec 2008 18:54:54 +0800 Subject: Equivalent of 'wget' for python? In-Reply-To: References: Message-ID: <4e307e0f0812110254q593e46b0rfd818a2290d7a9fe@mail.gmail.com> On Tue, Dec 9, 2008 at 12:22 AM, Robert Dailey wrote: > Hi, > > I'm looking for a portable way to download ZIP files on the internet > through Python. I don't want to do os.system() to invoke 'wget', since > this isn't portable on Windows. I'm hoping the core python library has > a library for this. Note that I'll be using Python 3.0. > You can get Wget for Windows here: http://gnuwin32.sourceforge.net/packages/wget.htm -- Best Regards, Leo Jay From alex.pulver at gmail.com Fri Dec 19 09:34:55 2008 From: alex.pulver at gmail.com (Alex) Date: Fri, 19 Dec 2008 06:34:55 -0800 (PST) Subject: How to read stdout from subprocess as it is being produced Message-ID: <263c3946-86aa-4db0-bdaf-42d0c8e5e5d6@q18g2000vbn.googlegroups.com> Hi, I have a Pyhon GUI application that launches subprocess. I would like to read the subprocess' stdout as it is being produced (show it in GUI), without hanging the GUI. I guess threading will solve the no-hanging issue, but as far as I searched for now, I've only seen how to read the stdout after subprocess is finished. Thanks! From klaus.kopec at tuebingen.mpg.de Tue Dec 9 10:59:16 2008 From: klaus.kopec at tuebingen.mpg.de (Klaus Kopec) Date: Tue, 09 Dec 2008 16:59:16 +0100 Subject: pickling a circular object inherited from list Message-ID: Hello everyone, I have a problem with inheritance from list. I want to create a tree like object where child nodes are kept in self[:] and every child has a field that points to its parent. Pickling such an object, however, throws an AssertionError. See below for source code and output of an easy example case of my problem. What did I do wrong? Best regards, Klaus ======== source: class myList(list): pass class myObject: def __init__(self, parent=None): self.parent = parent if __name__ == '__main__': r = myList() r.append( myObject(r) ) from pickle import dump, load dump(r, file('/tmp/x', 'w')) ========= output: Traceback (most recent call last): File "", line 1, in ? File "/tmp/python-11053-o.py", line 15, in ? dump(r, f) File "/usr/lib/python2.4/pickle.py", line 1382, in dump Pickler(file, protocol, bin).dump(obj) File "/usr/lib/python2.4/pickle.py", line 231, in dump self.save(obj) File "/usr/lib/python2.4/pickle.py", line 338, in save self.save_reduce(obj=obj, *rv) File "/usr/lib/python2.4/pickle.py", line 419, in save_reduce self.memoize(obj) File "/usr/lib/python2.4/pickle.py", line 251, in memoize assert id(obj) not in self.memo AssertionError From python.list at tim.thechases.com Thu Dec 4 18:42:19 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 04 Dec 2008 17:42:19 -0600 Subject: Find Files in a Folder Between 2 Dates In-Reply-To: <4c54b6c5-ae4d-4b89-8c6d-940c96de29bb@n33g2000pri.googlegroups.com> References: <4c54b6c5-ae4d-4b89-8c6d-940c96de29bb@n33g2000pri.googlegroups.com> Message-ID: <49386ADB.9040909@tim.thechases.com> > Is there a way to find all the files in a folder, between 2 dates? > > For example: > > Firstdate = 200801010000 > Seconddate = 200801020000 > > Find all the files in C:\Folder that are between Firstdate and > SecondDate. This should do it: import time import os firstdate = "200801010000" seconddate = "200801020000" def get_timestamp(s): return time.mktime(time.strptime(s, "%Y%m%d%H%M")) start = get_timestamp(firstdate) end = get_timestamp(seconddate) location = '/path/to/wherever/' files = [fname for fname in os.listdir(location) if start <= os.stat(os.path.join(location, fname)).st_mtime <= end ] print files The magic is the the os.stat(f).st_mtime to determine when the associated timestamp, the os.listdir() to get the available files in a directory, and the list-comprehension to filter to only the ones you want. -tkc From philip at semanchuk.com Tue Dec 2 09:50:02 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 2 Dec 2008 09:50:02 -0500 Subject: Running a Python script from crontab In-Reply-To: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> Message-ID: <38C55FC8-B430-4C46-907F-C41D57F2D3F1@semanchuk.com> On Dec 2, 2008, at 9:35 AM, Astley Le Jasper wrote: > I need help ... I've been looking at this every evening for over a > week now. I'd like to see my kids again! > > I have script that runs fine in the terminal but when I try to run it > in a crontab for either myself or root, it bails out. > > The trouble is that obviously I get no console when using crontab so > can't see any traceback. I use logging which shows 'info' messages as > the script is working, but no error messages. I've peppered it with > debug messages to try to track it down to a line, but it stops it the > middle of appending data to a list. I'd expect it to bail out when > calling a module or reading/writing to a different file. > > Is there any way of getting more info from the app, like popping up a > console while its running? > > my crontab is: > > 30 15 * * * cd /home/myusername/src && python myscript.py Here's what my crontab looks like on FreeBSD. (Your syntax may differ.) Note how I'm redirecting stdout and stderr to a log file -- that helps debugging. Also, I'm setting an explicit shell and path just to make sure that e.g. Python is findable. ---------------------------- SHELL=/usr/local/bin/bash PATH=/bin:/usr/bin:/usr/local/bin # min hh day mon dow */2 * * * * python /usr/local/foo/myscript.py >> / var/log/me/myscript.txt 2>&1 ---------------------------- HTH Philip From steve at REMOVE-THIS-cybersource.com.au Sat Dec 6 18:48:04 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Dec 2008 23:48:04 GMT Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> <8b8d1fb3-f49e-49bf-8cfe-eeee5ed16109@r37g2000prr.googlegroups.com> <014a932b$0$20670$c3e8da3@news.astraweb.com> Message-ID: <014b06e8$0$20670$c3e8da3@news.astraweb.com> On Sat, 06 Dec 2008 08:01:40 -0800, Russ P. wrote: >> -2 on this proposal. > > Did you get two votes in the Presidential election too? 8^) You know, occasionally you stumble across people on the Internet who aren't from the USA. Some of us even speak English almost as good as native speakers *wink* In any case, in this context -2 refers to the strength of feeling, not the number of votes. Python is not a democracy, and our Beloved BDFL Guido graciously takes our needs and wants into account before making decisions. -- Steven From rt8396 at gmail.com Tue Dec 2 00:03:26 2008 From: rt8396 at gmail.com (r) Date: Mon, 1 Dec 2008 21:03:26 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <9baabb6c-daab-418e-a11f-9162e1fc30f7@k36g2000pri.googlegroups.com> Message-ID: Ok, so i was wrong about you =) From sgeiger at ncee.net Mon Dec 8 15:03:32 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Mon, 08 Dec 2008 15:03:32 -0500 Subject: Text parsing via regex In-Reply-To: References: Message-ID: <493D7D94.3080802@ncee.net> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061 def wrap(text, width): """ A word-wrap function that preserves existing line breaks and most spaces in the text. Expects that existing line breaks are posix newlines (\n). """ return reduce(lambda line, word, width=width: '%s%s%s' % (line, ' \n'[(len(line)-line.rfind('\n')-1 + len(word.split('\n',1)[0] ) >= width)], word), text.split(' ') ) # 2 very long lines separated by a blank line msg = """Arthur: "The Lady of the Lake, her arm clad in the purest \ shimmering samite, held aloft Excalibur from the bosom of the water, \ signifying by Divine Providence that I, Arthur, was to carry \ Excalibur. That is why I am your king!" Dennis: "Listen. Strange women lying in ponds distributing swords is \ no basis for a system of government. Supreme executive power derives \ from a mandate from the masses, not from some farcical aquatic \ ceremony!\"""" # example: make it fit in 40 columns print(wrap(msg,40)) # result is below """ Arthur: "The Lady of the Lake, her arm """ Robocop wrote: > I'm having a little text parsing problem that i think would be really > quick to troubleshoot for someone more versed in python and Regexes. > I need to write a simple script that parses some arbitrarily long > string every 50 characters, and does not parse text in the middle of > words (but ultimately every parsed string should be 50 characters, so > adding in white spaces is necessary). So i immediately came up with > something along the lines of: > > string = "a bunch of nonsense that could be really long, or really > short depending on the situation" > r = re.compile(r".{50}") > m = r.match(string) > > then i started to realize that i didn't know how to do exactly what i > wanted. At this point i wanted to find a way to simply use something > like: > > parsed_1, parsed_2,...parsed_n = m.groups() > > However i'm having several problems. I know that playskool regular > expression i wrote above will only parse every 50 characters, and will > blindly cut words in half if the parsed string doesn't end with a > whitespace. I'm relatively new to regexes and i don't know how to > have it take that into account, or even what type of logic i would > need to fill in the extra whitespaces to make the string the proper > length when avoiding cutting words up. So that's problem #1. Problem > #2 is that because the string is of arbitrary length, i never know how > many parsed strings i'll have, and thus do not immediately know how > many variables need to be created to accompany them. It's easy enough > with each pass of the function to find how many i will have by doing: > mag = len(string) > upper_lim = mag/50 + 1 > But i'm not sure how to declare and set them to my parsed strings. > Now problem #1 isn't as pressing, i can technically get away with > cutting up the words, i'd just prefer not to. The most pressing > problem right now is #2. Any help, or suggestions would be great, > anything to get me thinking differently is helpful. > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From nick at craig-wood.com Mon Dec 1 07:30:46 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 01 Dec 2008 06:30:46 -0600 Subject: Emacs vs. Eclipse vs. Vim References: Message-ID: Josh wrote: > If you were a beginning programmer and willing to make an investment in > steep learning curve for best returns down the road, which would you pick? IMHO I'd want these features * Keyboard macros * Regular expression search and replace * Integration with version control * Infinite undo * Syntax colouring (not essential) * Bracket matching (useful but not essential) * Integration with compiler with error throwback (essential for C code work) * Automatic indenting (a great time saver) I know that emacs (my choice) and vim have all these features, don't know about Eclipse. In fact if I had to pick one feature that a programmer's editor must have it would be keyboard macros. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From dotancohen at gmail.com Wed Dec 3 21:08:21 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 4 Dec 2008 04:08:21 +0200 Subject: RELEASED Python 3.0 final In-Reply-To: References: Message-ID: <880dece00812031808q1a56c6b6g399283e8d12ec8c3@mail.gmail.com> 2008/12/4 Barry Warsaw : > On behalf of the Python development team and the Python community, I am > happy to announce the release of Python 3.0 final. > Congratulations! I have been learning Python 2.x while paying strict attention to the 3.x [in]compatibility issue. So, I have been waiting for this day since I've started with Python! -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-??-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From gdamjan at gmail.com Thu Dec 4 14:01:11 2008 From: gdamjan at gmail.com (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Thu, 04 Dec 2008 20:01:11 +0100 Subject: Python 3 read() function References: Message-ID: > I don't think it matters. Here's a quick comparison between 2.5 and > 3.0 on a relatively small 17 meg file: > > C:\>c:\Python30\python -m timeit -n 1 > "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" > 1 loops, best of 3: 36.8 sec per loop > > C:\>c:\Python25\python -m timeit -n 1 > "open('C:\\work\\temp\\bppd_vsub.csv', 'rb').read()" > 1 loops, best of 3: 33 msec per loop > > That's 3 orders of magnitude slower on python3.0! Isn't this because you have the file cached in memory on the second run? -- ?????? ( http://softver.org.mk/damjan/ ) "The moment you commit and quit holding back, all sorts of unforseen incidents, meetings and material assistance will rise up to help you. The simple act of commitment is a powerful magnet for help." -- Napoleon From arnodel at googlemail.com Tue Dec 2 14:17:34 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 02 Dec 2008 19:17:34 +0000 Subject: Scanner class References: <737a0550-0b92-4f65-829e-953882d74419@y18g2000yqn.googlegroups.com> <5d73aeb2-a4f1-4dd4-9c16-67db39df9e0c@u14g2000yqg.googlegroups.com> Message-ID: George Sakkis writes: > On Dec 1, 5:42?pm, Arnaud Delobelle wrote: >> George Sakkis writes: >> >> http://code.activestate.com/recipes/457664/ > > Thanks, didn't know about it. I also found Plex [1] which seems more > powerful. > > George > > [1] http://www.cosc.canterbury.ac.nz/greg.ewing/python/Plex/version/doc/index.html I've also written a python module that aims to be similar to GNU flex. You can see it here: http://www.marooned.org.uk/~arno/python/lexing.html It's not extremely sophisticated but it's quite easy to use. I've written a Python 3 tokeniser in it :) -- Arnaud From benjamin.kaplan at case.edu Tue Dec 23 09:31:31 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 23 Dec 2008 09:31:31 -0500 Subject: Python's popularity In-Reply-To: <32d8e3f1-52a7-4bce-a70a-70db488a417b@h20g2000yqn.googlegroups.com> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> <7c02eb33-a919-4481-8eda-76062729f233@k19g2000yqg.googlegroups.com> <32d8e3f1-52a7-4bce-a70a-70db488a417b@h20g2000yqn.googlegroups.com> Message-ID: On Tue, Dec 23, 2008 at 12:05 AM, r wrote: > On Dec 22, 10:09 pm, Ben Kaplan wrote: > > That's just because most of us don't say anything unless we have > > something useful to say. We prefer to let the experts answer the > > questions, but we read the threads so we can benefit from them. > > OK Ben, So you are saying > > 1.) do not question the gods! > 2.) speak only when spoken to! > 3.) do not have an opinion! > > Somehow this reminds me of some old and brainwashing religions, Not an > OSS project. Just observations Ben. You're the one who keeps bringing up the need to spread python. For most people, this is a forum to ask questions and have experts respond to them. Most people who post here aren't looking for your opinion, they want answers. If you know the answer to a question, answer it. If not, read the answers of people who have seen it before. When you post your opinions, you're just creating more noise. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rt8396 at gmail.com Wed Dec 24 15:52:49 2008 From: rt8396 at gmail.com (r) Date: Wed, 24 Dec 2008 12:52:49 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> Message-ID: On Dec 22, 7:26?pm, Steven D'Aprano wrote: > On Mon, 22 Dec 2008 06:58:06 -0800, walterbyrd wrote: > > On Dec 21, 12:28?pm, Bruno Desthuilliers > > wrote: > >> Strange enough, > >> no one seems to complain about PHP or Ruby's performances... > > > A few years back, there was a certain amount of chest thumping, when > > python/django easily beat ror in a benchmark test. Now that ruby is > > faster, I guess speed is no big issue. > > Who was doing this chest-thumping? Fanboys like "r"? Why should you tar > all of us with their immaturity? Walter, Steven would rather live in a bland Utopian society and could care less for the greatness of competition and he has little respect for loyalty. He would like to have little league games where there is no losers, so nobody's "feelings" get hurt(oh NO!). And EOE so that god forbid weather or not someone is qualified they must be hired just to keep a equal balance in the workplace. Hey Steven, we should outlaw individualism too, God forbid someone think outside the box!(damn heretics!) But as they say "ignorance is bliss" ey Stevie? From bruno.42.desthuilliers at websiteburo.invalid Fri Dec 19 09:02:56 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 19 Dec 2008 15:02:56 +0100 Subject: How to parsing a sequence of integers In-Reply-To: References: <494ba258$0$18998$426a74cc@news.free.fr> Message-ID: <494ba949$0$23019$426a34cc@news.free.fr> John Machin a ?crit : > On Dec 20, 12:33 am, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: >> Steven Woody a ?crit :> Hi, >> >>> I am a newbie and is reading the python book. Could anyone tell me, >>> how to parsing the following string >>> "123 100 12 37 ..." >> > into a list of integers on which I can then apply max()/min()? >> >> source = "123 100 12 37" >> list_of_ints = [int(part) for part in source.strip().split()] > > The purpose of the .strip() would be ...? Err... To check if you were paying attention ?-) From m.faustino at gmail.com Mon Dec 8 13:29:08 2008 From: m.faustino at gmail.com (=?ISO-8859-1?Q?M=E1rcio_Faustino?=) Date: Mon, 8 Dec 2008 10:29:08 -0800 (PST) Subject: Public imports References: <9623b0a3-7053-41f1-b116-0cd5e54f39e9@v13g2000vbb.googlegroups.com> <493d1ec0$0$32048$426a34cc@news.free.fr> Message-ID: <66ecdd96-38dd-4054-8009-e145c0a78316@o40g2000prn.googlegroups.com> So, no chance of doing this: # "A.py" from __future__ import division, with_statement # "B.py" from A import * print 1 / 2 ...and printing 0.5, right? Too bad :) Thanks! From rdmurray at bitdance.com Tue Dec 9 13:43:26 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Tue, 9 Dec 2008 13:43:26 -0500 (EST) Subject: Can't figure out where SyntaxError: can not delete variable 'x' referenced in nested scope us coming from in python >=2.6 In-Reply-To: <1228846300.4109.30.camel@brotherus.rdu.redhat.com> References: <1228846300.4109.30.camel@brotherus.rdu.redhat.com> Message-ID: On Tue, 9 Dec 2008 at 13:11, Albert Hopkins wrote: > Say I have module foo.py: > > def a(x): > def b(): > x > del x [...] > The difference is under Python 2.4 I get a traceback with the lineno and > offending line, but I do not get a traceback in Pythons 2.6 and 3.0. 2.5 also omits the traceback. Smells like a bug to me. --RDM From jason.scheirer at gmail.com Wed Dec 3 14:25:29 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Wed, 3 Dec 2008 11:25:29 -0800 (PST) Subject: Overriding a method at the instance level on a subclass of a builtin type References: <7bd15456-f29b-47e1-9f6e-71bd6d904a2a@n10g2000yqm.googlegroups.com> Message-ID: <3b148182-d421-4b0e-b764-3a7c1be1b7fb@a26g2000prf.googlegroups.com> On Dec 2, 6:13?pm, Aaron Brady wrote: > On Dec 2, 6:58?pm, "Zac Burns" wrote: > > > > > Sorry for the long subject. > > > I'm trying to create a subclass dictionary that runs extra init code > > on the first __getitem__ call. However, the performance of __getitem__ > > is quite important - so I'm trying in the subclassed __getitem__ > > method to first run some code and then patch in the original dict > > method for the instance to avoid even the check to see if the init > > code has been run. Various recipes using instancemethod and the like > > have failed me. > > > Curiously if __slots__ is not specified no error occurs when setting > > self.__getitem__ but the function is not overriden. If __slots__ is > > ['__getitem__'] however it complains that __getitem__ is read only. I > > do not understand that behavior. > > > -- > > Zachary Burns > > (407)590-4814 > > Aim - Zac256FL > > Production Engineer (Digital Overlord) > > Zindagi Games > > That sounds like the State Pattern, from GoF. ?http://en.wikipedia.org/wiki/State_pattern > > I like the idea of 'renaming', not redefining, but reassigning methods > at different points during an object's lifetime. ?I often wish I had > more experience with it, and more docs talked about it. > > It's hard on memory usage, since each instance has its own function > attribute, even if there's still only one instance of the function. > Without it, the function attribute is just looked up on the class. > > Not thoroughly tested: > > >>> class A: > > ... ? ? def methA( self ): > ... ? ? ? ? ? ? print 'methA' > ... ? ? ? ? ? ? self.meth= self.methB > ... ? ? meth= methA > ... ? ? def methB( self ): > ... ? ? ? ? ? ? print 'methB' > ...>>> a= A() > >>> a.meth() > methA > >>> a.meth() > > methB The problem with using this this pattern in the way that you've specified is that you have a potential memory leak/object lifetime issue. Assigning a bound method of an instance (which itself holds a reference to self) to another attribute in that same instance creates a kind of circular dependency that I have discovered can trip up the GC more often than not. You can subclass it as easily: class dictsubclass(dict): def __getitem__(self, keyname): if not hasattr(self, '_run_once'): self.special_code_to_run_once() self._run_once = True return super(self, dict).__getitem__(keyname) If that extra ~16 bytes associated with the subclass is really a problem: class dictsubclass(dict): def __getitem__(self, keyname): self.special_code_to_run_once() self.__class__ = dict return super(self, dict).__getitem__(keyname) But I don't think that's a good idea at all. From steven at REMOVE.THIS.cybersource.com.au Wed Dec 10 22:28:02 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 11 Dec 2008 03:28:02 GMT Subject: Rich Comparisons Gotcha References: <200812101401.35786.kyrie@uh.cu> <49401C2D.4050209@egenix.com> Message-ID: On Wed, 10 Dec 2008 17:21:51 -0500, Luis Zarrabeitia wrote: > I do numeric work... I'm finishing my MSc in applied math and I'm > programing mostly with python. And I'd rather have a.compare_with(b), or > a.elementwise_compare(b), or whatever name, rather than (a==b).all(). Unluckily for you, the Numeric/Numpy people wanted something else. They asked first, there's a lot more of them, and their project is very important to Python's continued success. > In > fact, I'd very much like to have an a.compare_with(b, epsilon=e).all() > (to account for rounding errors), and with python2.5, > all(a.compare_with(b)). > > Yes, I could create an element_compare(a,b) function. Absolutely. > But I still can't use a==b and have a meaningful result. That's right. *ANY* operation in Python can fail, given arbitrary data, with the possible exception of the id() function and the "is" and "is not" operators. You have to deal with it. > Ok, I can (and do) ignore that, > it's just one library, I'll keep track of the types before asking for > equality (already an ugly thing to do in python), but the a==b behaviour > breaks the lists (a in ll, ll.indexof(a)) even for elements not in > numpy. ?Should I also ignore lists? That depends on what sort of contract your code is giving. Does it promise to work with any imaginable data whatsoever, no matter how badly broken or poorly designed or incompatible with what you're trying to do? If so, then I suggest your contract is broken, not the behaviour of list. You can't make trustworthy promises to deal with arbitrary data types that you don't control, that can fail in arbitrary ways. Here's something for you to consider: class Boobytrap: def __eq__(self, other): if other == 1: return True elif other == 2: while True: pass return False >>> alist = [0, Boobytrap(), 2, 3] >>> 1 in alist True >>> 3 in alist True >>> 5 in alist False >>> 2 in alist What do you expect should happen? > The concept of equality between two arrays is very well defined, as it > is also very well defined the element-by-element comparison. There is a > need to test for both - then the way to test for equality should be the > equality test. The Numpy people disagree with you. It was from their request that Python was changed to allow __eq__ to return arbitrary objects. -- Steven From ndbecker2 at gmail.com Mon Dec 1 18:00:15 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Mon, 01 Dec 2008 18:00:15 -0500 Subject: optimization References: Message-ID: Arnaud Delobelle wrote: > Neal Becker writes: > >> I noticed in some profiling, that it seems that: >> >> def Func (): >> def something(): >> ... >> >> It appears that if Func is called many times, this nested func >> definition will cause significant overhead. Is this true? I guess >> I've become accustomed to decent compilers performing reasonable >> transformations and so have tended to write code for clarity. > > If something() can be defined outside Func(), how is it clearer to > define it inside? > If it's only used inside. From kirk at daycos.com Fri Dec 12 11:08:23 2008 From: kirk at daycos.com (Kirk Strauser) Date: Fri, 12 Dec 2008 10:08:23 -0600 Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> Message-ID: <87ej0dz894.fsf@daycos.com> At 2008-12-12T15:51:15Z, Marco Mariani writes: > Filip Gruszczy?ski wrote: > >> I am not doing it, because I need it. I can as well use "if not elem >> is None", > I suggest "if elem is not None", which is not quite the same. So what's the difference exactly? "foo is not None" is actually surprising to me, since "not None" is True. "0 is True" is False, but "0 is not None" is True. Why is that? -- Kirk Strauser The Day Companies From roy at panix.com Sat Dec 20 20:19:03 2008 From: roy at panix.com (Roy Smith) Date: Sat, 20 Dec 2008 20:19:03 -0500 Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> <59153e28-bf86-4158-96d9-23aa5b9f0205@j35g2000yqh.googlegroups.com> <7889a362-d96e-4f1f-a66b-ef52b9cdb047@q26g2000prq.googlegroups.com> <85f91606-b589-425d-9636-4636c8ccbc4f@r34g2000vbp.googlegroups.com> <6b4176c3-49ce-4e7c-bced-07d8d19bc0f4@s20g2000yqh.googlegroups.com> Message-ID: In article <6b4176c3-49ce-4e7c-bced-07d8d19bc0f4 at s20g2000yqh.googlegroups.com>, r wrote: > You can't just blindly Parrot off.. "well CPU's get faster every > year". Sure you can :-) There was a nice treatment of this on slashdot today (http://www.codinghorror.com/blog/archives/001198.html). The executive summary is I'm willing to accept that Python is (big handwave) 10x slower than C++, because *I'm* 10x faster writing in Python than I am in C++, and I cost more than my computer. Moore's laws says (small handwave) CPU speed doubles every 24 months. At that rate, and assuming I remember enough high-school algebra to solve a compound interest problem, hardware gets 10% faster every 3 months. If Python gets 10% slower every 10 years or so, it's ahead of the curve. From bearophileHUGS at lycos.com Fri Dec 12 18:47:45 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 12 Dec 2008 15:47:45 -0800 (PST) Subject: (Very Newbie) Problems defining a variable References: <878wqlz27z.fsf@daycos.com> <4942c9b4$0$1651$426a34cc@news.free.fr> Message-ID: Kirk Strauser: > def get_rate(balance): > for threshold, rate in ((100000, .0173), > (50000, .0149), > (25000, .0124), > (10000, .0085), > (0, .006)): > if balance > threshold: > return rate > return .0 Nice code. This operation, of choosing an item in a sorted list of intervals that has no holes, is common enough. But something like an interval dict is overkill here. I suggest to put a zero before all those points, to improve readability and avoid some possible errors: it's easy to not see a small leading point. ---------------- Bruno Desthuilliers: > A sequence of pairs and a dict are _almost_ interchangeable (mmm... is > that the correct word ?) representations of a same data set[1] - the > main difference being ordering. If ordering matters, choose a sequence > of pairs as main representation - you can easily build a dict from it > if/when you need it. Generally(*) it's better to use the simpler data structure that does the job. Here a list/tuple of tuples is good. Very often programs get translated to other languages, so keeping things as simple as possible helps that too. --------- (*) I have used 'generally' because there's a compromise to be taken here. In C and other related languages you often use structs or records, so if you have pairs you give a name to the fields, for example "x" and "y" for the two coordinates of a 2D Point. In Python in such situation you can create a Point class, but often you instead use a (x, y) or [x, y]. In some situations you need to access the fields, so you use [0] and [1]. This is (was) a case where Python looks lower-lever than the C language. In Python3/Python2.6+ you can use a NamedTuple too. Is it better to give and take a list of points to/from as a list of [x,y] lists or as a list of Point2D? Probably a Java programmer thinks that using Point2D is safer and is a way to document what the function takes/returns too. Extending the list of pairs to 3D points is a little simpler if they are represented as tuples/lists. That's an example where you may not choose the simpler data structure (that in Python is a list of pairs) and use a list of NamedTuple to make code "safer" even if the data structure is a little more complex. Bye, bearophile From wmcbrine at users.sf.net Sat Dec 6 17:43:30 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Sat, 06 Dec 2008 22:43:30 GMT Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> <84332560-580d-488b-aa6b-6aad754a7805@k36g2000pri.googlegroups.com> Message-ID: On Fri, 05 Dec 2008 12:16:47 -0800, Fernando H. Sanches wrote: > I agree that the tab/space thing should be changed. Would it be too hard > to make the parser see if the indentation is consistent in the whole > file? *Something* has changed. I had a piece of code where, without realizing it, I had a tab mixed in with the spaces at the start of one line in a block. In 2.5, it worked, silently. In 3.0, I got an indentation error. -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From david at hlacik.eu Sun Dec 14 16:02:21 2008 From: david at hlacik.eu (=?ISO-8859-2?Q?David_Hl=E1=E8ik?=) Date: Sun, 14 Dec 2008 22:02:21 +0100 Subject: [OT] stable algorithm with complexity O(n) In-Reply-To: References: <6qidmbFc4qduU1@mid.uni-berlin.de> <01547201$0$6988$c3e8da3@news.astraweb.com> Message-ID: Thank you guys for help and support! My homework is done and waiting for grading. Here it comes - bucket sort with time complexity O(n) == linear complexity #! /usr/bin/python def sort(numbers): "sort n positive integers in O(n) provided that they are all from interval [1, n^2]" N = len(numbers) # get size of test numbers buckets_mod = [[] for i in xrange(N)] buckets_sorted = [[] for i in xrange(N+1)] # group numbers to buckets (list of numbers) with common modulus for n in numbers: buckets_mod[n % N].append(n) print "buckets_mod: %s" % buckets_mod # check numbers in buckets for l in buckets_mod: for n in l: # place number into bucket number grouped by result of division buckets_sorted[n / N].append(n) print "buckets_sorted: %s" % buckets_sorted # search through sorted buckets and return list of sorted numbers return [n for l in buckets_sorted for n in l] Regards, David On Sun, Dec 14, 2008 at 11:24 AM, Arnaud Delobelle wrote: > Steven D'Aprano writes: > >> On Sat, 13 Dec 2008 19:17:41 +0000, Duncan Booth wrote: >> >>> I think you must have fallen asleep during CS101. The lower bound for >>> sorting where you make a two way branch at each step is O(n * log_2 n), >>> but if you can choose between k possible orderings in a single >>> comparison you can get O(n * log_k n). >> >> I think you might have been sleeping through Maths 101 :-) >> >> The difference between log_2 N and log_k N is a constant factor (log_2 k) >> and so doesn't effect the big-oh complexity. > > It affects it if k is a function of n. In this particular example, we > can set k=n so we get O(n). > > -- > Arnaud > -- > http://mail.python.org/mailman/listinfo/python-list > From bdesth.quelquechose at free.quelquepart.fr Thu Dec 11 14:53:40 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 11 Dec 2008 20:53:40 +0100 Subject: newbie question: if var1 == var2: In-Reply-To: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> Message-ID: <49417d7c$0$8491$426a74cc@news.free.fr> Steve Holden a ?crit : > Kirk Strauser wrote: >> At 2008-11-29T04:02:11Z, Mel writes: >> >>> You could try >>> >>> for item in fname: >>> item = item.strip() >> This is one case where I really miss Perl's "chomp" function. It removes a >> trailing newline and nothing else, so you don't have to worry about losing >> leading or trailing spaces if those are important to you. > > ... and it's so hard to write > > item = item[:-1] Steve, you should know better. It's item = item.rstrip('\r\n') From hniksic at xemacs.org Fri Dec 12 09:13:33 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 12 Dec 2008 15:13:33 +0100 Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> Message-ID: <87skotmqgi.fsf@mulj.homelinux.net> sturlamolden writes: > Actually I would consider this to be a bug. The tuple is immutable, > but no mutation of the tuple is ever attempted. That's a common misconception about how += works in Python. It simply *always* rebinds. Once you grok that, everything else follows. From google at mrabarnett.plus.com Sun Dec 7 19:47:25 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 08 Dec 2008 00:47:25 +0000 Subject: Python for kids? In-Reply-To: References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> Message-ID: <493C6E9D.1070500@mrabarnett.plus.com> Russ P. wrote: > Thanks to everyone who replied. The information was very helpful. > > Someone might want to consider putting a kids section on python.org > (if it doesn't have one already -- I didn't see one). > You have a kid. Why don't you? :-) From gagsl-py2 at yahoo.com.ar Thu Dec 18 20:21:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Dec 2008 23:21:06 -0200 Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> <7e23a789-84c3-47b9-b040-ca7dd062d058@a37g2000pre.googlegroups.com> Message-ID: En Thu, 18 Dec 2008 19:46:45 -0200, Aaron Brady escribi?: > On Dec 17, 7:16?pm, "Gabriel Genellina" > wrote: >> En Wed, 17 Dec 2008 22:46:32 -0200, Aaron Brady ? >> escribi?: >> >> >> >> > On Dec 17, 5:05?pm, "Gabriel Genellina" >> > wrote: >> >> En Wed, 17 Dec 2008 12:21:38 -0200, Jeremy Sanders ? >> >> escribi?: >> >> >> > It would be nice if Python created pipes that are properly ? >> >> inheritable by >> >> > default by child processes, as they're mostly used for IPC. >> >> >> I'd say it is a bug in os.pipe implementation; they should be ? >> >> inheritable ? >> >> by default, as in posix (after all, the code is in "posixmodule.c"). >> >> > The code looks like this: >> >> > ? ?ok = CreatePipe(&read, &write, NULL, 0); >> > ? ?Py_END_ALLOW_THREADS >> > ? ?if (!ok) >> > ? ? ? ? ? ?return win32_error("CreatePipe", NULL); >> > ? ?read_fd = _open_osfhandle((Py_intptr_t)read, 0); >> > ? ?write_fd = _open_osfhandle((Py_intptr_t)write, 1); >> >> > 'If lpPipeAttributes is NULL, the handle cannot be inherited.' ?You >> > could populate a 'SECURITY_ATTRIBUTES' structure, or call >> > DuplicateHandle on both of them. >> >> > A patch would look like this: >> >> > SECURITY_ATTRIBUTES sattribs; >> > sattribs.nLength = sizeof(sattribs); >> > sattribs.lpSecurityDescriptor = NULL; >> > sattribs.bInheritHandle = TRUE; >> > ok = CreatePipe(&read, &write, &sattribs, 0); >> >> Yes, that's exactly how os.popen does it (in posixmodule.c) >> >> > This still doesn't answer whether the file descriptor return by >> > '_open_osfhandle' can be inherited too. >> >> It doesn't matter. The OS only cares about file handles, not C RTL ? >> structures. > > Sorry for the multiple posts. File handles are inheritable by child > processes, if the permissions are right. File descriptors are not. > Is there a way that we can get the handles of a pipe into code, so > that we can pass them to a subprocess? On Windows, file handles are the real OS stuff, the "true" reference to an open file. File descriptors are not, they exist only to please the C runtime library. Programs not written in C (directly, or indirectly like Python) don't care at all about file descriptors. And in case one actually cares, there is _open_osfhandle in the C RTL (available as msvcrt.open_osfhandle from Python). A subprocess may inherit handles from its parent [there are two filters: the parameter "bInheritHandles" in the CreateProcess call provides global control, and individual handles can be made inheritable or not, before creating the new subprocess]. "Anonymous" pipes are good to replace stdin/stdout/stderr, because there is no need to explicitely communicate the handle value to the subprocess: one just replaces the corresponding handle with the desired pipe, and the subprocess might not even notice it. In case this is not enough, one might pass the handle (as a number) in the command line, but probably a "named pipe" would be better. As this is not transparent for the child process, one must explicitely code such things. > Will it take calling > 'CreatePipe' from ctypes directly if on Windows? Or can 'os.pipe' be > made to abstract that? If Windows can't inherit descriptors, > 'os.pipe' should return handles, and 'os.read' &co. should accept > them. I think the best way would be to modify os.pipe so it returns inheritable pipes, as it should have been from the beginning. > It is a fairly large patch. Not at all, you have already posted most of it. -- Gabriel Genellina From prasannaksahoo at gmail.com Thu Dec 4 23:23:30 2008 From: prasannaksahoo at gmail.com (pk sahoo) Date: Fri, 5 Dec 2008 09:53:30 +0530 Subject: Geeting the error Open failed: : Expected BOF record; found 0x3f3c Message-ID: hallo everybody, when i m running the command python runxlrd.py 3rows a.xls i m getting the following error === File: a.xls === *** Open failed: : Expected BOF record; found 0x3f3c what is the reason.... regards prasanna -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Mon Dec 15 03:54:15 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Dec 2008 08:54:15 GMT Subject: stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> Message-ID: <015612ac$0$20639$c3e8da3@news.astraweb.com> On Sun, 14 Dec 2008 21:12:13 -0800, Aaron Brady wrote: > On Dec 14, 8:18?pm, Roy Smith wrote: >> Steven D'Aprano wrote: >> > All the positive thinking in the world won't help you: >> >> > * make a four-sided triangle; >> >> > * split a magnet into two individual poles; >> >> These two are fundamentally different problems. >> >> The first is impossible by definition. ?The definition of triangle is, >> "a three-sided polygon". ?Asking for a "four-sided triangle" is akin to >> asking for "a value of three which is equal to four". >> >> The second is only "impossible" because it contradicts our >> understanding (based on observation) of how the physical universe >> works. ?Our understanding could simply be wrong. ?We've certainly been >> wrong before, and we will undoubtedly be proven wrong again in the >> future. ?When it comes to things like electromagnetic theory, it >> doesn't take too many steps to get us to the fuzzy edge of quantum >> physics where we know there are huge questions yet to be answered. > > I agree. Most of his examples were tautologies. The magnet one was the > exception. > > Then, to beat the O( n lg n ) limit, just break an assumption. No no no, that's solving a different problem! You're welcome to solve a different problem if you like, and sometimes doing so is very valuable: sometimes the original problem turns out not to be important after all. But don't pretend that it's the same problem. >> > * or design a comparison sort which does fewer than O(n*log n) >> > two-way comparisons in the worst case, or fewer than O(n) comparisons >> > in the best case. > > Make a three-way comparison, make a non-comparison sort, or make non- > random inputs. Again no. Multi-way comparisons merely change the base of the logarithm, which in turn merely changes the constant term. It's still O(n*log n). Non-comparison sorts are a useful technique, but it's changing the problem, and they are only useful in very limited circumstances. There's a good reason that most sort routines are based on O(n*log n) comparison sorts instead of O(n) bucket sorts or radix sorts. And the quip about non-random inputs just shows you don't understand the problem you're being asked to solve. O(n*log n) is for the least number of comparisons needed for the worst possible input. It's not for the best possible input, or random input, or the average number of comparisons, or any other measurement. You've misunderstood the question if you think "give better input" is the answer. And frankly, it's *easy* to come up with a comparison sort that has O(n) behaviour for the best possible input. Bubble sort has O(n) behaviour for input that is already sorted. Even the infamous bogosort has O(n) behaviour for the best possible input: def is_sorted(alist): """Return True if alist is sorted, otherwise False.""" for i in xrange(1, len(alist)): if alist[i-1] > alist[i]: return False return True def bogosort(alist): # Shuffle alist until it happens to be sorted while not is_sorted(alist): random.shuffle(alist) I believe bogosort has behaviour O(n!), which is far worse than merely exponential O(2**n) complexity. But when given already sorted input, the version of bogosort above is O(n). Even the archtypically Awful (not just Bad) algorithm is amazingly fast if you happen to give it the best possible input. (By the way, the above code is not suitable for use in production code. Due to limitations of the standard Python random number generator, not all permutations of lists larger than a certain size can be generated. The default random number generator for Python 2.5 is the Mersenne Twister, which has a period of 2**19937-1. But the number of permutations of n items is n!, and n! is greater than 2**19937-1 for n=2081 or more. That means that for any list with 2081 or more items, there is a finite probability that the above implementation of bogosort will merely cycle repeatedly over 2**19937-1 unsorted permutations and hence never terminate.) -- Steven From nospam at nospam.invalid Mon Dec 15 16:51:33 2008 From: nospam at nospam.invalid (Rahul) Date: Mon, 15 Dec 2008 21:51:33 +0000 (UTC) Subject: Insatlling python on compute-node-linux (Cray). Message-ID: Has anyone tried installing Python on Compute Node Linux (on a cray)? I was having trouble getting it running. I see that CNL does not support dynamic libraries but I am not sure what the best way then is to get Python running. Any tips? -- Rahul From malaclypse2 at gmail.com Tue Dec 2 12:50:52 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 2 Dec 2008 12:50:52 -0500 Subject: help me~!about base64 In-Reply-To: <0ff1ba7b-8a17-4647-99fc-9c8e32f83de7@g1g2000pra.googlegroups.com> References: <0ff1ba7b-8a17-4647-99fc-9c8e32f83de7@g1g2000pra.googlegroups.com> Message-ID: <16651e80812020950l27a97396reab835f55ec9e41f@mail.gmail.com> 2008/12/2 : > it's run ,Eric gave me error,the error is "'module' object has no > attribute 'decodestring'", Do you have your own base64.py (or base64.pyc) that's shadowing the standard module base64? Try this: >>> import base64 >>> print base64.__file__ C:\Python25\lib\base64.py >>> What does that say when you do it? -- Jerry From marduk at letterboxes.org Thu Dec 4 15:42:31 2008 From: marduk at letterboxes.org (Albert Hopkins) Date: Thu, 04 Dec 2008 15:42:31 -0500 Subject: "as" keyword woes In-Reply-To: <777c7313-267f-4dc2-b6fd-fad0c9714f41@l42g2000yqe.googlegroups.com> References: <777c7313-267f-4dc2-b6fd-fad0c9714f41@l42g2000yqe.googlegroups.com> Message-ID: <1228423351.7548.23.camel@brotherus.rdu.redhat.com> It's been a while so I can't remember, but it seems like "yield" was dropped in to python relatively quickly in 2.2. Was there a similar outrage when "yield" became a keyword? -a From saluk64007 at gmail.com Sun Dec 21 14:56:25 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Sun, 21 Dec 2008 11:56:25 -0800 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: On Sun, Dec 21, 2008 at 11:26 AM, r wrote: > I noticed when i mentioned "self" nobody wants to touch that subject. > There could be many reasons why... > > 0.) nobody but the 10 regulars i see here exists > 1.) nobody cares(doubt it) > 2.) nobody is brave enough to question it(maybe) > 3.) most people like to type self over and over again(doubt it) > 4.) most people here have given up on changing the BDFL's mind about > it. (good possibility) > 5.) this is a hot-button topic(no doubt in my mind!) It's a combination between (4) (5) and (6). 6 being, we have discussed "self" every week for the past 6 years, it hasn't changed yet, it's not going away, it's not a trivial "problem", deal with it. (0) is ridiculous, there are more than 10 respondents to this post alone. (1) - if nobody cared it wouldn't come up every week, but it's been discussed so much most are tired of it (2) - people question it all the time, usually people who are new to the language but not always. The discussion generally doesn't amount to anything (3) - It's not about wanting to type self over and over again, it's about being able to start with functions or start with classes, and easily refactor to the other way when needed; and never having a chance to wonder where a variable came from. There are ups and downs to self, it is generally more work to remove it than it is worth, what would the gain be? We'd be trading some ups and downs for some other ups and downs. And no, BDFL is not going to bend on self. He almost bent on the issue a few weeks ago, but his proposition merely changed some syntax - self was still there. On Sun, Dec 21, 2008 at 11:01 AM, Christian Heimes wrote: > We could have waited a few more months or even a few more years with a > 3.0 release. There is always - I repeat ALWAYS - work to do. For an open > source project like Python "release early, release often" works better. Good point, and I agree. It's too early for people to complain about python 3 being slow. It's also too both too late and too early to complain about things in python 3 that are thought of as a step backward. It's too late, because python 3 is out and it's already been changed! Things are not going to change back. Complaints are a bit useless at this point, except to let off steam. It's too early, because without using python3 in a major project, from the ground up, with the new features, the benefits or negatives for all of the changes cannot truly be known. From prologic at shortcircuit.net.au Mon Dec 15 08:01:01 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 15 Dec 2008 23:01:01 +1000 Subject: Having Issues with CMD and the 'python' command In-Reply-To: References: Message-ID: "cmd" has _nothing_ to do with Python. --JamesMills -- -- "Problems are solved by method" On Mon, Dec 15, 2008 at 10:51 PM, Lamonte Harris wrote: > Every time I start cmd on windows it requires me to "set > path=%path%;C:\python26" why? I'm getting annoyed... > > -- > http://mail.python.org/mailman/listinfo/python-list > > From bj_666 at gmx.net Sun Dec 21 11:09:04 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Dec 2008 16:09:04 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <015da0a4$0$20656$c3e8da3@news.astraweb.com> <6r6uvbFfb643U5@mid.uni-berlin.de> Message-ID: <6r7810Ffb643U6@mid.uni-berlin.de> On Sun, 21 Dec 2008 15:30:34 +0000, Duncan Booth wrote: > Marc 'BlackJack' Rintsch wrote: > >>> a+b+c+d might execute a.__add__(b,c,d) allowing more efficient string >>> concatenations or matrix operations, and a%b%c%d might execute as >>> a.__mod__(b,c,d). >> >> But that needs special casing strings and ``%`` in the comiler, because >> it might not be always safe to do this on arbitrary objects. Only in >> cases where the type of `a` is known at compile time and ``a % b`` >> returns an object of ``type(a)``. >> > I could be wrong, but I don't see that would be the case. > > I think it would be safe (in this hypothetical universe) any time that > 'a' had a method __mod__ which accepted more than one argument. And returns an object of ``type(a)`` or at least a "duck type" so that it is guaranteed that ``a.__mod__(b, c)`` really has the same semantics as ``a.__mod__(b).__mod__(c)``. For arbitrary objects `a`, `b`, and `c` that are not known at compile time, how could the compiler decide if it is safe to emit code that calls `a.__mod__()` with multiple arguments? Ciao, Marc 'BlackJack' Rintsch From oyvinrog at gmail.com Sat Dec 20 03:07:31 2008 From: oyvinrog at gmail.com (=?ISO-8859-1?B?2Hl2aW5k?=) Date: Sat, 20 Dec 2008 00:07:31 -0800 (PST) Subject: Jarow-Winkler algorithm: Measuring similarity between strings References: <4f351b3b-4da7-4fee-a1ac-c42179d430f5@s9g2000prm.googlegroups.com> Message-ID: <665bf3f7-ef74-4e59-bbac-cfbc12d4e81d@x16g2000prn.googlegroups.com> Thanks for the useful comments. On 20 Des, 01:38, John Machin wrote: > On Dec 20, 10:02?am, ?yvind wrote: > > > Based on examples and formulas fromhttp://en.wikipedia.org/wiki/Jaro-Winkler. > > For another Python implementation, google "febrl". > > > Useful for measuring similarity between two strings. For example if > > you want to detect that the user did a typo. > > You mean like comparing the user's input word with some collection of > valid words? You would need to be using something else as a quick-and- > dirty filter ... Jaro-Winkler is relatively slow. Do you have any alternative suggestions? > > > > > def jarow(s1,s2): > > > ? ? """ ?Returns a number between 1 and 0, where 1 is the most similar > > > ? ? ? ? example: > > > ? ? ? ? print jarow("martha","marhta") > > > ? ? ? ? """ > > ? ? m= jarow_m(s1,s2) > > ? ? t1 = jarow_t(s1,s2) > > ? ? t2 = jarow_t(s2,s1) > > ? ? t = float(t1)/float(t2) > > Huh? t1 and t2 are supposed to be counts of transpositions. So is t. > So how come t is a ratio of t1 to t2?? BTW, suppose t2 is zero. Good point. There should be only one jarow_t. > > Also as the Wikipedia article says, > it's not a metric. I.e. it doesn't satisfy dist(a, c) <= dist(a, b) + > dist(b, c). Its not a mathematical correct metric, but it is a useful heuristical metric. > > The above code is not symmetrical; jarow_m(s1, s2) does not > necessarily equal jarow_m(s2, s1). The article talks about one "m", > not two of them. > Hmm.. also a good point. I will make it count all the matches, not just the matches in s1. From rurpy at yahoo.com Tue Dec 16 01:22:44 2008 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Mon, 15 Dec 2008 22:22:44 -0800 (PST) Subject: ethical questions about global variables References: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> <0d9a9758-f338-4a58-971a-1bd29e40ce32@v5g2000prm.googlegroups.com> Message-ID: <298179e4-a33f-4fb2-8d57-e817293a1502@v5g2000prm.googlegroups.com> On Dec 15, 11:00 pm, ru... at yahoo.com wrote: > #my_module > class Config: pass > config = Config() > > def func1(state): > config.A = 1 > def func2(state) > config.A = 2 > def func3(state) > print config.A That of course should have been: def func1(config): config.A = 1 def func2(config) config.A = 2 def func3(config) print config.A From gruszczy at gmail.com Fri Dec 12 04:18:35 2008 From: gruszczy at gmail.com (=?UTF-8?Q?Filip_Gruszczy=C5=84ski?=) Date: Fri, 12 Dec 2008 10:18:35 +0100 Subject: Removing None objects from a sequence Message-ID: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> Hi! I would like to iterate over a sequence nad ignore all None objects. The most obvious way is explicitly checking if element is not None, but it takes too much space. And I would like to get something faster. I can use [ sth for sth in self.__sth if not sth is None ], but I don't know if that's the best way. I checked itertools, but the only thing that seemed ok, was ifilter - this requires seperate function though, so doesn't seem too short. How can I get it the shortest and fastest way? -- Filip Gruszczy?ski From bj_666 at gmx.net Sun Dec 14 04:19:45 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 14 Dec 2008 09:19:45 GMT Subject: Optimizing methods away or not? References: <0154b041$0$6988$c3e8da3@news.astraweb.com> Message-ID: <6qk1dhFcr01gU1@mid.uni-berlin.de> On Sun, 14 Dec 2008 07:41:55 +0000, Steven D'Aprano wrote: > I have a class with a method meant to verify internal program logic (not > data supplied by the caller). Because it is time-consuming but optional, > I treat it as a complex assertion statement, and optimize it away if > __debug__ is false: > > class Parrot: > def __init__(self, *args): > print "Initialising instance..." > if __debug__: > self.verify() # check internal program state, not args > if __debug__: > def verify(self): > print "Verifying..." > > > If I run Python normally, I can do this: > >>>> p = Parrot() > Initialising instance... > Verifying... >>>> p.verify() > Verifying... > > > and if I run Python with the -O flag, I get this: > >>>> p = Parrot() > Initialising instance... >>>> p.verify() > Traceback (most recent call last): > File "", line 1, in > AttributeError: Parrot instance has no attribute 'verify' > > > This is the behaviour I want, but I haven't seen it before in other > code. What do people think? Is it a good idea or a bad? > > If you think it is a bad idea to have verify disappear under > optimization, would you change your mind if it were called __verify > instead? > > > One possible alternative is to do something like this: > > class Parrot: > def __init__(self, *args): > print "Initialising instance..." > if __debug__: > self.verify() > def verify(self): > if __debug__: > print "Verifying..." > return None > # this is optional > else: > warnings.warn("verify() is a null op") > > > which now means that Parrot instances will always have a verify method, > even if it does nothing. I'm not sure I like that. What do others think? > Which do you consider better design? None of it. Why not simply: class Parrot: def __init__(self, *args): print "Initialising instance..." assert self.verify() def _verify(self): print "Verifying..." return None If you compile with -O the ``assert`` is optimized away. But you still can call `_verify()` at specific points even in optimized code if you want or need. Ciao, Marc 'BlackJack' Rintsch From R.Bauer at fz-juelich.de Wed Dec 17 15:48:36 2008 From: R.Bauer at fz-juelich.de (Reimar Bauer) Date: Wed, 17 Dec 2008 21:48:36 +0100 Subject: something else instead of PIL? Message-ID: Hi what has happened to PIL? No updates since two years. Or does one know an alternative lib for resizing images? cheers Reimar From sjmachin at lexicon.net Sat Dec 13 18:11:36 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 13 Dec 2008 15:11:36 -0800 (PST) Subject: Python 3.0 crashes displaying Unicode at interactive prompt References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> <49443531.5050304@v.loewis.de> Message-ID: On Dec 14, 9:20?am, "Martin v. L?wis" wrote: > >> This is intended behavior. > > > I see. That means that the behaviour in Python 1.6 to 2.6 (i.e. > > encoding the text using the repr() function (as then defined) was not > > intended behaviour? > > Sure. "Sure" as in "sure, it was not intended behaviour"? > This behavior has not changed. It still uses repr(). > > Of course, the string type has changed in 3.0, and now uses a different > definition of repr. So was the above-reported non-crash consequence of the change of definition of repr intended? From collin.day.0 at gmail.com Thu Dec 18 20:37:40 2008 From: collin.day.0 at gmail.com (Collin D) Date: Thu, 18 Dec 2008 17:37:40 -0800 (PST) Subject: Factoring Polynomials References: <269523e2-eba9-4b6b-b0fb-c5a7deb3ed76@o4g2000pra.googlegroups.com> Message-ID: <2980024c-e680-4010-b8c4-eccd7fd37b65@a37g2000pre.googlegroups.com> On Dec 18, 5:30?pm, "James Mills" wrote: > UPDATE: > > jmills at atomant:~/tmp$ cat polycalc.py > #!/usr/bin/env python > > from math import sqrt > > def f(a, b, c): > ? ? if (b**2 - (4 * a * c)) < 0: > ? ? ? ? return None, None # Can't solve > ? ? x1 = -b - (sqrt(b**2 - (4 * a * c)) / (2 * a)) > ? ? x2 = -b + (sqrt(b**2 - (4 * a * c)) / (2 * a)) > ? ? return x1, x2 > > print "Polynomial Solver..." > print > > while True: > ? ? a = float(raw_input("a: ")) > ? ? b = float(raw_input("b: ")) > ? ? c = float(raw_input("c: ")) > > ? ? x = f(a, b, c) > ? ? if None in x: > ? ? ? ? print "Can't solve!" > ? ? else: > ? ? ? ? print "x = (%0.2f, %0.2f)" % x > jmills at atomant:~/tmp$ ./polycalc.py > Polynomial Solver... > > a: 1 > b: 8 > c: 5 > x = (-11.32, -4.68) Ahh. Great.. that answers a lot of questions. Originally I was using just a = raw_input('a: ') And was getting errors because you cant perform mathmatical operations on strings. >.< Thanks again! From steve at REMOVE-THIS-cybersource.com.au Tue Dec 9 18:00:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Dec 2008 23:00:48 GMT Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> Message-ID: <014ef03e$0$20670$c3e8da3@news.astraweb.com> On Tue, 09 Dec 2008 05:48:29 -0800, Paul Boddie wrote: > Well, I think it's more interesting to explore the boundaries of what > can be done, to debunk notions that such things aren't being done in the > mainstream, and to examine whether they could benefit usability, than it > is to defer to the Zen of Python as some kind of prescriptive, > near-religious text at every turn. Go right ahead. Write your experimental language, and if people like it, they'll use it. That's what Guido did, all those years ago. But don't turn Python into a hodgepodge of "features" that most people consider misfeatures. The Zen certainly is prescriptive, but it's not "near-religious" in any sense. It's a distillation of probably hundreds of man-years of programming experience from people like Guido and Tim Peters into a small number of heuristics about the sorts of design decisions which have been proven to be successful in the past. I think it is childish to reject the Zen just because it's the Zen. Good advice doesn't cease to be good advice just because people tell you it's good advice, even if some people are awfully strident about it. -- Steven From gagsl-py2 at yahoo.com.ar Tue Dec 30 17:19:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Dec 2008 20:19:33 -0200 Subject: Read-Write Lock vs primitive Lock() References: <277c1be7-2560-4fd6-9610-0b4398dc3719@x16g2000prn.googlegroups.com> Message-ID: En Tue, 30 Dec 2008 06:16:23 -0200, k3xji escribi?: > As GLOBAL_LOOP_COUNT is 10000000, now this is making a bottleneck on > the readers. I had assumed that as everythread is given only 100 > bytecodes to execute, that it will be enough to have a 10000 value for > this number to let other rthread start() and try to acquire the lock. > But, Python undocumentedly, does not grab the GIL easily if a Lock is > held. This is strange for me. This has nothing to do with the GIL, nor undocumented behavior. If all threads are blocked waiting for the same lock, yielding the CPU has no effect, because nobody can progress until the lock is released. I'll ask you again: what is your use case? what do you want to do? what is a "reader" in your problem? what is a "writer"? what is the resource you want to protect using a lock? Different problems have different behaviors; for example, for reading/writing files, your model is basically wrong. > That may be the point. That is why I am trying to test this. When will > ReadWrite() lock permforms better over the primitive lock. By the way, > for the reference, the code in the recipe is used in CherryPy and > based on the Tanenbaum's book Operating Systems Design. Ah, good to know at least it has some background. Anyway, isn't a guarantee of correctness. By exampe, Tanenbaum's algorithm for the dining philosophers problem were (is?) flawed (according to W. Stallings). > I understand your point completely, but let's change anything inside > the loop. Just assume that we a thread that is supposed to read > something, and a thread that is supposed to write. If I create > thousands of readers, and if the operation is enormously huge > calculation(as Python does not grab GIL easily inside a Lock), then > this will create a bottlencek on readers. But, with ReadWrite Lock > this problem *SHOULD* be fixed and in my tests I see it is fixed, when > I increase the time spent in the loop in huge amounts. But why would you protect the whole long calculation with a lock? And why do you say "Python does not grab GIL easily inside a Lock", whatever that means? If you hold a scarce resource for a long time, this is likely to cause a bottleneck, and the language (be it Python or other) is mostly irrelevant here. > I had > assumed that Python will release GIL for other threads after 100 > bytecodes are executed by default. Yes. You can alter how often this occurs, using sys.setcheckinterval (the code I posted does that, just to see how results vary) > However, as I stated, when a Lock() > is held this is changing. I think this is because to avoid simple MT > problems for new programmers. Not sure. I will read threads.c for > information. No, it's always the same thing, locks don't affect this behavior. But as I said above, if no other thread can progress because all of them are waiting to acquire the same lock, you gain nothing by releasing the GIL. -- Gabriel Genellina From jgardner at jonathangardner.net Tue Dec 30 16:50:51 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Tue, 30 Dec 2008 13:50:51 -0800 (PST) Subject: Understanding search queries, semantics, and "Meaning" ...aren't we all looking for meaning? References: <82372457-2503-4682-96b3-37540328bf26@w39g2000prb.googlegroups.com> Message-ID: <94ab1653-c88d-4bad-a094-47d67e435618@w1g2000prm.googlegroups.com> On Dec 30, 12:35?pm, 5lvqbw... at sneakemail.com wrote: > I have Section 4.4.1 of SICP rattling around in my head (database > queries), and I'm trying to come up with a simple dictionary-based > database in Python to represent circuit diagrams. ?My main confusion > isn't one of implementation, but a matter of "big thinking", > fundamentally, about the problem. Please don't suggest using a SQL > library, as I'm looking to learn to fish, so to speak, and to learn a > bit about the biology of fish. > I'm going to break rule #1 of your requirements but in an unexpected way. Rather than studying PostgreSQL, MySQL, or Oracle, why don't you crack open the topic of relational database theory and relational algebra? That should help with the "big thinking" bit in the same way understanding 1+1 helps you understand how to add any two numbers together. No, SQL is not the be-all-end-all of relational theory. Yes, it does a pretty dang good job at it, though, which is why it is still around. > I've subclassed dict to hdict ("hashable dict") and rewritten the > __hash__ function so I can include a dict into a set. Thanks to a > previous poster here for providing that suggestion. > > A circuit component looks like this for example: > > comp1 = hdict(value=1e-6, footprint='0402', vendor='digikey') > comp2 = hdict(value=10e3, footprint='0603', vendor='mouser') > etc, etc. > > The database holds the values like this: > db = dict() # normal dict > db['value'] = ([1e-6, 10e3], [comp1, comp2]) #ordered set for fast > lookup/insertion > db['footprint'] = {'0402':set[comp1], '0603':comp2} # unordered uses > normal dict for fast lookup > db['vendor'] = {'digikey':[comp1], 'mouser':[comp2]} > > So basically the keys are the component parameters, and the values is > the list of components with that value. ?Stuff that is comparable is > ordered; stuff that is discrete is not ordered, using either 2-tuples > or dicts, respectively. > > This allows extremely fast lookup of components based on their > properties, with O(1) performance for non-ordered stuff, and O(log n) > performance for ordered stuff (using bisect methods). ?The set > operations are extremely fast, so I can do AND and OR operations on > compound queries of this nature without worry. > > I need this speed not so much for selecting components when the user > types in a query, but for when the mouse is hovering over the > schematic and I need things to light up underneath, if the GUI is > generating hundreds of mouse messages per second, and for inspector > windows to appear quickly when you click, etc. ?If you have ever used > Altium, you can see how effective this is in terms of creating a good > interactive user experience. > OK, turn it around in your head. Consider the indexes you built above as yet another table. Consider what a table or a database really is. When you see how they are all really the same thing, either you've mastered relational algebra of you've seen the big picture. Kind of like the cons cell being enough to describe any data structure in the universe, a table is enough to describe everything in the relational world. > My question is what happens when I choose to search for NOT > footprint='0402'. > > Should this return a blank list? This happens by default., and is in > fact true: a blank list satisfies "not anything" actually. > Should this return everything that is NOT footprint 0402 (ie returns > 0603 components)? ?This *strongly implies* a pre-selection of *all* > objects before performing the negating function, or of looking at the > ordering of other queries in the overall search term, and then > applying NOT to the results of another query. > > But I'm suspicious of a brute force preselection of all objects > whenever I see a NOT, and anyway it messes up the clean query/combiner > method of search I'm doing, and it requires an implied sequence of > search, where I'm pretty sure it should not rely on sequencing. ?Even > though this is single threaded, etc., the semantics of the query > should not rely on ordering of the search term: > > footprint='0402' and NOT vendor='mouser' should return the same as > NOT vendor='mouser' and footprint='0402'. > > So this is my philosophical quandary. ?I'm not sure what the correct > thing is. ?In SICP they are using nondeterministic stuff which I don't > quite get, so it's hard to follow. ?Also they are not using > dictionaries and hashes, so I'm not sure if their generate-and-test > method would work here anyway. ?Generate-and-test seems extremely > inefficient. > > Can a wise guru please enlighten me? > (I don't think I qualify as a guru, but I think I see how I can help.) In a typical SQL database, when you type in "SELECT foo FROM bar WHERE baz='bo'", you are not writing a program, at least not in the sense of Python or C or Java or Perl where you give instructions on HOW to run the program. You are writing a program in the sense of Lisp or Scheme or Haskell in that you are giving instructions on WHAT the program is. The database doesn't, at least shouldn't, read in all the rows in a table and then start going through the process of elimination removing rows it doesn't want to think about. That's highly inefficient, of course. Instead, it transforms the query (the WHAT) into a set of procedures that describe HOW to get the result. That step---taking the definition of the program and turning it into actual instructions on HOW to run the program---is the compilation and optimization phase. It's a very hard step to do, but no harder than the process Python goes through taking files of bytes and converting them into Python bytecode. Oh, by the way, this step is nondeterministic. Why? Well, no one can really say what the BEST way to run any sufficiently complicated program is. We can point out good ways and bad ways, but not the best way. It's like the travelling salesman problem in a way. Now, that "hard stuff" you are glossing over in SICP is the IMPORTANT stuff. It's the WHOLE POINT of that section. Stop glossing over it. Keep working at it bit by bit until you understand it. You, as a programmer, will be infinitely better for it. When you understand it, you will really unlock the full potential of Python and Scheme and whatever other language is out there because you will see how to go from HOW languages to WHAT languages. Programmers who can write compilers are GOOD programmers. Programmers who can understand someone else's compilers are even better. On Python-specific stuff: For a moment, forget about Python and hashes and dicts and arrays and lists and such. Focus only on the cons cell and Scheme. When you have mastered those concepts, you will see how to efficiently use the Python data structures and how to simplify the Scheme code into Python. Right now you are doing a bit of premature optimization. That's my semi-guru advice. From gagsl-py2 at yahoo.com.ar Thu Dec 18 19:11:12 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Dec 2008 22:11:12 -0200 Subject: importing csv file into sqlite References: <21067453.post@talk.nabble.com> Message-ID: En Thu, 18 Dec 2008 04:17:47 -0200, James Mills escribi?: > How big ? When size is important in data > processing, you should _never_ try to > load it all up at once. Use filters... But your code does *exactly* that, it reads the whole file in memory: > def mkBuffer(fd): > buffer = StringIO() > buffer.write(fd.read()) > ... That mkBuffer function has no useful purpose IMHO, just remove it. -- Gabriel Genellina From max at alcyone.com Fri Dec 12 04:26:54 2008 From: max at alcyone.com (Erik Max Francis) Date: Fri, 12 Dec 2008 01:26:54 -0800 Subject: Removing None objects from a sequence In-Reply-To: References: Message-ID: Filip Gruszczy?ski wrote: > I would like to iterate over a sequence nad ignore all None objects. > The most obvious way is explicitly checking if element is not None, > but it takes too much space. That doesn't make much sense; why would iterating over the sequence take more _space_? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Life is a gamble so I should / Live life more carefully -- TLC From philr at aspexconsulting.co.nz Sun Dec 28 18:18:26 2008 From: philr at aspexconsulting.co.nz (Phil Runciman) Date: Mon, 29 Dec 2008 12:18:26 +1300 Subject: game engine (as in rules not graphics) In-Reply-To: <402f625f-b835-4cb8-bcea-523756c489ca@g39g2000pri.googlegroups.com> Message-ID: See: Chris Moss, Prolog++: The Power of Object-Oriented and Logic Programming (ISBN 0201565072) This book is a pretty handy intro to an OO version Prolog produced by Logic Programming Associates. Prolog is a wonderful tool for such things as working out a factory layout for new car production or for creating an expert system for choosing antibiotics for treating a condition. It has even been used for helping producing immigration legislation and then for providing a system for checking eligibility (other than can you survive in a desert and get through barbed wire!) One person used is to teach primary school children English grammar. The children created their own grammar rules and checked them out using Prolog. Their understanding of english grammar exceeded many university graduates after this exercise. (Google Dr. Richard Ennals). FWIW. Declaration of interest: Chris Moss is my wife's first cousin. -----Original Message----- From: Aaron Brady [mailto:castironpi at gmail.com] Sent: Sunday, 28 December 2008 1:22 p.m. To: python-list at python.org Subject: Re: game engine (as in rules not graphics) On Dec 27, 3:02?pm, Martin wrote: > Hello, > > I'd like to get in touch with game development a bit. I'm not talking > about graphics but rather the game rules itself. Something > likehttp://en.wikipedia.org/wiki/Monopoly_(game)#Rules, is there even > a general approach to that or should I just go sketch up my rules and > try to implement them. Being totally new to this topic I don't quite > now what to search for to get some decent results that let me make a > mental link between game rules and what the best practices are to > implement them in python (or any other programming language) > > thanks, > martin Not my expertise but here are my $0.02. You are looking for ways to represent rules: buying a house is legal in such and such situation, and the formula for calculating its price is something. You want "predicates" such as InJail, OwnedBy, Costs. Costs( New York Ave, 200 ) InJail( player2 ) OwnedBy( St. Charles Ave, player4 ) LegalMove( rolldie ) LegalMove( sellhouse ) There are rule-based languages out there, such as Prolog. They are equally expressive as Python (you can write a Turing machine in them), but they are more convenient for representing rules in a prog. language. Predicates are more or less equivalent to positive assertions about something. NewYorkAve.cost= 200 player2.injail= True... rolldie.islegal= True Some predicates have to be calculated, rather than stored, but Python descriptors go easy on you for that. Someone else will have to tell you how rule-based programming measures up against object-oriented programming. From walterbyrd at iname.com Mon Dec 22 17:23:45 2008 From: walterbyrd at iname.com (walterbyrd) Date: Mon, 22 Dec 2008 14:23:45 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <494fef38$0$12781$426a74cc@news.free.fr> Message-ID: On Dec 22, 11:50?am, Bruno Desthuilliers wrote: > > When it comes to web development, it seems to me that ruby > > (because of rails) is far more popular > > s/popular/hyped/ I'm not so sure. Go to dice.com, enter "ruby rails" no quotes, search all words, job titles only - I got 86 hits, and another five hits when I searched for "RoR." Do the same search, but substitue "python django" for "ruby rails" and I get 3 hits. Doing the search for just "ruby" and I get 121 hits. Doing the search for just "python" and I get 61 hits. Just "rails" and get 94 hits, just "django" and I get 4 hits. Not scientific, but there is substantial difference. > Fooled by version numbers ? No, but I am giving django the benefit of the doubt. The django project told people all along that django was not to be considered production ready before 1.0. I will accept that some people decided to wait until 1.0 came out to do any production development. Maybe django is only lagging because 1.0 just came out? > My actual CTO is a big Ruby/Rails fan, yet he settled on Python/Django > for our current 'big' project. Wonder why ? Not knowing much about RoR: yes, I wonder why? Is it because python has a cleaner syntax? Or what? From zxo102 at gmail.com Thu Dec 25 02:29:08 2008 From: zxo102 at gmail.com (zxo102) Date: Wed, 24 Dec 2008 23:29:08 -0800 (PST) Subject: How to display Chinese in a list retrieved from database via python Message-ID: Hi, I retrieve some info in Chinese from postgresql and assign it to a variable 'info' defined in javascript of a html page: var info = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce \xc4'] But I want it to be var info = ['??','??','??'] since in html pages (via javascript), the items in chinese out of the former :['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4'] can not be displayed correctly when it is inserted into a html page. If the list is var info = ['??','??','??'] , then everything works fine. Anybody knows how to solve this problem? Thanks in advance. zxo102 From Jiandong.Ge at gmail.com Wed Dec 10 15:16:56 2008 From: Jiandong.Ge at gmail.com (JD) Date: Wed, 10 Dec 2008 12:16:56 -0800 (PST) Subject: How to pass out the result from iterated function Message-ID: I got a iterated function like this: def iterSomething(list): has_something = False for cell in list: if something in cell: has_something = True output = something if has_something: iterSomething(output) else: final_out = outupt The problem is how can I read this final_out outside of the function. I tried the global statement, it seems not work. Any idea? JD From jaume.bonet at gmail.com Wed Dec 10 18:09:48 2008 From: jaume.bonet at gmail.com (Jaume Bonet) Date: Wed, 10 Dec 2008 15:09:48 -0800 (PST) Subject: Memory leak when using a C++ module for Python Message-ID: Hi, I'm pretty new in python programming. I've been developing a C++ module for a python application that simply gets the information from python, makes the last processing (which is very time consuming -that's why I make it in C++-). When I test the code from C++ each time I delete a vector the consumed memory decreases, but it does not happen when the module is called from python. The memory is kept... Once the data comes from python, the PyObjects are read and its information passed to C objects (that is done just once) and all the rest of the processing is done with those objects. I've read that the even when you delete the content of the vectors the memory is not freed when you are working with python. Is that so? Is there any way to really free that memory? Thanks, J From steve at REMOVE-THIS-cybersource.com.au Sat Dec 13 11:21:22 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Dec 2008 16:21:22 GMT Subject: Removing None objects from a sequence References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> <4942E668.5030100@tim.thechases.com> <01538f0c$0$6988$c3e8da3@news.astraweb.com> <234b9a34-52e3-42c3-968c-f50983e51c68@e1g2000pra.googlegroups.com> Message-ID: <0153d884$0$6988$c3e8da3@news.astraweb.com> On Sat, 13 Dec 2008 06:00:09 -0800, bearophileHUGS wrote: > Steven D'Aprano: >> The algorithm is unclear: try explaining what you are doing in English, >> and see how difficult it is. > > That algorithm is a standard one, and quite clear. Any programmer worth > his/her/hir salt has to be able to understand that. I didn't say it can't be understood. But please, if you think it is quite clear, go ahead and explain how it works, and how you know the algorithm is correct and there are no odd corner cases where it fails. As my comp sci lecturer used to say, "prove the algorithm is correct". Remember, Terry made a specific claim: the algorithm is simpler and cleaner than Tim's copy-the-values-that-aren't-None solution. It's not just clear, it's significantly clearer: "No, making a filtered copy that is then copied back before being deleted is algorithmically much messier. My code does the minimum work necessary and is algorithmically cleaner." Do you agree with Terry's claim? -- Steven From glenn.chappell at gmail.com Mon Dec 22 16:41:56 2008 From: glenn.chappell at gmail.com (Glenn G. Chappell) Date: Mon, 22 Dec 2008 13:41:56 -0800 (PST) Subject: python3 urlopen(...).read() returns bytes Message-ID: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> I just ran 2to3 on a py2.5 script that does pattern matching on the text of a web page. The resulting script crashed, because when I did f = urllib.request.urlopen(url) text = f.read() then "text" is a bytes object, not a string, and so I can't do a regexp on it. Of course, this is easy to patch: just do "f.read().decode()". However, it strikes me as an obvious bug, which ought to be fixed. That is, read() should return a string, as it did in py2.5. But apparently others disagree? This was mentioned in issue 3930 ( http://bugs.python.org/issue3930 ) back in September '08, but that issue is now closed, apparently because consistent behavior was achieved. But I figure consistently bad behavior is still bad. This change breaks pretty much every Python program that opens a webpage, doesn't it? 2to3 doesn't catch it, and, in any case, why should read() return bytes, not string? Am I missing something? By the way, I'm running Ubuntu 8.10. Doing "python3 --version" prints "Python 3.0rc1+". From has.temp3 at virgin.net Sun Dec 7 13:06:11 2008 From: has.temp3 at virgin.net (has) Date: Sun, 7 Dec 2008 10:06:11 -0800 (PST) Subject: Number of Python 3.x packages at the PyPI References: <9c1ab0f3-6686-4c0f-8a6c-12e20539f354@41g2000yqf.googlegroups.com> <493b954e$0$4021$9b622d9e@news.freenet.de> Message-ID: <2d656e64-deff-40ed-8066-57b6f8874ec4@b38g2000prf.googlegroups.com> On 7 Dec, 09:20, "Martin v. L?wis" wrote: > excor... at gmail.com wrote: > > Are there any special arrangements necessary for PyPI packages which > > have both a Python 2.x version and a Python 3.x version? > > So far, no such need has been identified. I've had to fork my appscript project's codebase in order to add support for Python 3.x. I would like to distribute both 2.x and 3.x versions under the same package name for obvious reasons. This isn't a problem with eggs as the Python version number is included in each egg's name, but what about source distributions where both filenames are exactly the same (appscript-0.19.0.tar.gz)? Thanks, has -- Control AppleScriptable applications from Python, Ruby and ObjC: http://appscript.sourceforge.net From robin at reportlab.com Mon Dec 22 07:32:27 2008 From: robin at reportlab.com (Robin Becker) Date: Mon, 22 Dec 2008 12:32:27 +0000 Subject: excluding non-data files from distutils package_data Message-ID: <494F88DB.8060408@chamonix.reportlab.co.uk> Is there a convenient way in a distutils setup to determine which files will be included as part of the package setup. The need arises because I want to exclude those files from the package_data argument after doing a recursive sweep of the package folder to locate all files inclding .py etc etc. -- Robin Becker From pavlovevidence at gmail.com Mon Dec 29 22:32:48 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 29 Dec 2008 19:32:48 -0800 (PST) Subject: Python module import loop issue References: <02bc8567-695a-4277-9698-a95549a0bc98@w39g2000prb.googlegroups.com> <4a0557b7-e901-49ff-b4db-53f4d8a7c0f8@r40g2000yqj.googlegroups.com> Message-ID: Gabriel Genellina wrote: > En Mon, 29 Dec 2008 19:47:51 -0200, Carl Banks > escribi?: > > On Dec 29, 10:51?am, Kottiyath wrote: > > >> Module Factory: > >> A1Factory: {'B1Tag':1.1.B1, 'C1Tag':1.2.C1, 'D1Tag':1.3.D1'} > >> A2Factory: {'B2Tag':2.1.B2, 'C2Tag':2.2.C2, 'D2Tag':2.3.D2'} > >> > >> But, since Module requires objects of B1, C1 etc, it has to import > >> Factory. > >> Now, there is a import loop. How can we avoid this loop? > > > > I'm going to suggest three ways: a straightforward, good-enough way; a > > powerful, intelligent, badass way; and a sneaky way. > > In Python 2.6 (and 3.0) there is a fourth way: class decorators. > > > 1. The straightforward, good-enough way > > > > Define functions in Factory.py called register_A1_subclass and > > register_A2_subclass, then call them whenever you create a new > > subclass. > > Class decorators are a clean variant of this approach (in my opinion). > > > package1/module1.py: > > ----------------------------- > > import Factory > > > > class B1(A1): > > # define class B1 here > > > > Factory.register_A1_subclass("B1Tag",B1) > > ----------------------------- > > That would become: > > @Factory.register_A1_subclass("B1Tag") > class B1(A1): > ... > > (for an adequate variant of register_A1_subclass). The advantage is that > the "register" stuff appears prominently near the name of the class, and > there is no need to repeat the name. > Also, "B1Tag" can be left out, if it is stored as a class attribute of B1 > (in some cases using __name__ is enough) Thanks for the additional suggestion. > > 2. The powerful, intelligent, badass way > > > > Metaclasses. I would guess you do not want to do this, and I wouldn't > > recommend it if you haven't studied up on how metaclasses work, but > > it's a textbook example of their usefulness. If you expect to use > > factory functions like this a lot, it might be worth your while to > > learn them. > > A problem with metaclasses is when you have intermediate subclasses that > are not meant to be registered, but the metaclass applies equally to all > of them. Not the way I wrote it. If you'll note, the metaclass only added the class to the factory map if a tag attribute was defined in the class dict. Carl Banks From clp at rebertia.com Thu Dec 25 18:39:23 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 25 Dec 2008 15:39:23 -0800 Subject: python interpreter black window In-Reply-To: References: Message-ID: <47c890dc0812251539r5fd68f1brc25159ddb6e3d0d5@mail.gmail.com> On Thu, Dec 25, 2008 at 3:32 PM, Gandalf wrote: > I use WX gui so the user doesn't actually need it, Is their any way to > hide it? Make sure your Python program is run by pythonw.exe as opposed to python.exe pythonw.exe exists specifically for the purpose of suppressing the DOS Box on Windows. Merry Christmas, Chris -- Follow the path of the Iguana... http://rebertia.com From saju.pillai at gmail.com Wed Dec 31 09:55:59 2008 From: saju.pillai at gmail.com (Saju Pillai) Date: Wed, 31 Dec 2008 06:55:59 -0800 (PST) Subject: select.select and socket.setblocking References: <495a661d$0$11384$5fc30a8@news.tiscali.it> <495b34d8$0$11387$5fc30a8@news.tiscali.it> <3652a957-eec6-494c-bd37-d150018bc0ed@p2g2000prf.googlegroups.com> <495b8653$0$11383$5fc30a8@news.tiscali.it> Message-ID: <4b7fdd17-c9c0-4970-9bf8-e596c939e23e@d42g2000prb.googlegroups.com> On Dec 31, 7:48?pm, Francesco Bochicchio wrote: > < ... > > > >> Uhm. In my experience, with TCP protocol recv only returned less than > >> the required bytes if the remote end disconnects. I always check the > > > What if the sending end actually sent less than you asked for ? > > > -srp > > In blocking mode and with TCP protocol, the recv waits until more bytes > are received - ?mixing up the next message with the previous one and Is this correct ? IIRC even in blocking mode recv() can return with less bytes than requested, unless the MSG_WAITALL flag is supplied. Blocking mode only guarantees that recv() will wait for a message if none is available - but not that it *will* return the number of bytes requested. -srp > then loosing the 'sync' and being unable to interpretate the received > data - ?or the remote end disconnects. > > Yes this is bad, ?and is a good reason why socket receive should be > handled ? in non-blocking mode if you receive data from untrusted > sources. But luckily for me, as I said in the other post, I used socket > mostly to communicate between specific applications on a private LAN or > WAN, so I could afford to ignore the problem. > > Ciao > ---- > FB From lists at cheimes.de Wed Dec 3 17:59:23 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 03 Dec 2008 23:59:23 +0100 Subject: building an extension module with autotools? In-Reply-To: <4936FD1C.1010700@ghaering.de> References: <4936FD1C.1010700@ghaering.de> Message-ID: Gerhard H?ring wrote: > #!/bin/sh > python setup.py build > cp build/lib.*/*.so . > python test.py "python setup.py build_ext -i" is your friend. It installs the extensions inplace. No need for cp here. :) Christian From geekmail at usenot.de Sun Dec 7 14:17:00 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sun, 7 Dec 2008 20:17:00 +0100 Subject: Guido's new method definition idea References: <493a9fed$0$18973$426a34cc@news.free.fr> <493c1ff6$0$4942$426a34cc@news.free.fr> Message-ID: <20081207201700.6ade1f33@usenot.de> On Sun, 07 Dec 2008 19:13:18 +0100 Bruno Desthuilliers wrote: > > and friendlier to newbies. > > I'd rather say "more acceptable to java-brainwashed developpers". Why would you rather be unfriendly and seed ambivalence? I do see the fun in a little Python snobbism, but ... come on. /W -- My real email address is constructed by swapping the domain with the recipient (local part). From rt8396 at gmail.com Sun Dec 21 16:43:23 2008 From: rt8396 at gmail.com (r) Date: Sun, 21 Dec 2008 13:43:23 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> <494ea9a5$0$24542$426a34cc@news.free.fr> Message-ID: <4a00e9c5-89a5-4910-b274-659aea0e2b78@s36g2000vbp.googlegroups.com> Bruno, I thought i had already gone up, up, and away to your kill filter. hmm, guess you had a change of heart ;D From benjamin.kaplan at case.edu Wed Dec 3 01:01:13 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 3 Dec 2008 01:01:13 -0500 Subject: HELP!...Google SketchUp needs a Python API In-Reply-To: <36056737-3c78-499a-a81d-f6241e904460@t11g2000yqg.googlegroups.com> References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> <00ab327a-c3fc-4b15-a084-4f8c6aed6a8e@o2g2000yqd.googlegroups.com> <8119ab7e-09f1-44de-bdbc-8fdff969d9e4@33g2000yqm.googlegroups.com> <36056737-3c78-499a-a81d-f6241e904460@t11g2000yqg.googlegroups.com> Message-ID: On Tue, Dec 2, 2008 at 10:06 PM, r wrote: > "If we can laugh what else would we do" > > I'd like to touch also on some comments by ajaksu: > [ajaksu] > I'd like to try hacking some form of Python to work in SketchUp (on > top of Ruby, that is). Now, why won't I try to? I'm a Linux user and > we don't get a SU version. So much for FREEDOM. BTW, some things in > SU > have encrypted Ruby code behind them :) > [/ajaksu] > > You CAN use SketchUp on Linux...ajaksu...thru Wine, but I know this is > not good enough. I would love to see FULL SketchUp support for linux > and I HAVE made my voice heard. I urge you brother to make make your > voice heard also. > > Go to this thread and let your voice be heard: > > http://groups.google.com/group/sketchupsuggestions/browse_thread/thread/7c0c810b88ad4d5/dfabe1e01bab12b3?hl=en#dfabe1e01bab12b3 > > This is the reason...amoung many others...that Linux has yet to take > any noticable market from MS. Linux could...If the Linux devolpers > would ban together and unite to make package managment and portability > between all *nix's universal, OR one great linux distro that the > average dummy can use(ubuntu looks promising, but still has a long way > to go)...compete with microsoft on a grand level. We have to steal the > idiots from under microsoft's feet, and they will come crumbling down. > But as long as a poor n00b installs his shiny new *nix system and > can't even connect to the network to see the latest janet jackson > "wardrobe malfunction", or fiqure out how to mount a flash drive, > Linux will be nothing more than our beloved oddessy. > > There will NEVER be good support on linux for most applications, > games, etc... Until people start to get behind linux and support it. > Now you say, well i don't have time to support this, my life is too > busy, my back hurts. I say stop making excuses. You DON'T have to > invest your life, just simply make your voice heard.(myself and other > dedicated people will tow the load). But at least get off your bum and > do something. > > It's time to change the world, the hour is upon us, Microsoft is > asleep at the wheel, the time for revolution is NOW! > > -- > http://mail.python.org/mailman/listinfo/python-list > The Ubuntu devs are aware of this issue and a bug report has been filed. https://bugs.launchpad.net/ubuntu/+bug/1 -------------- next part -------------- An HTML attachment was scrubbed... URL: From miki.tebeka at gmail.com Mon Dec 15 20:51:25 2008 From: miki.tebeka at gmail.com (Miki) Date: Mon, 15 Dec 2008 17:51:25 -0800 (PST) Subject: parse C expression? References: Message-ID: <132711c2-257f-4d86-93fa-91c89db7733a@g1g2000pra.googlegroups.com> > Is there a standard module available that lets me parse a syntax like "C" > with numbers, operators, braces, variables and function calls? There is a C compiler implemented with PLY somewhere. > I'd like to use this to parse an own kind of configuration language > and preferred would be just standard modules. ?Is there something > available that is maybe based on shlex? I usually use Python as my configuration syntax, see http://pythonwise.blogspot.com/2006/05/using-python-syntax-in-configuration.html (shameless plug). Beware that this has security implications, I use it only in internal applications. HTH, -- Miki http://pythonwise.blogspot.com From arkanes at gmail.com Thu Dec 4 11:39:26 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 4 Dec 2008 10:39:26 -0600 Subject: "as" keyword woes In-Reply-To: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> Message-ID: <4866bea60812040839q3df3d723j3baeeb649c814067@mail.gmail.com> On Wed, Dec 3, 2008 at 11:42 PM, Warren DeLano wrote: >> > Why was it necessary to make "as" a reserved keyword? >> >> I can't answer for the Python developers as to why they *did* make it >> a reserved word. >> >> But I can offer what I believe is a good reason why it *should* be a >> reserved word: Because simple is better than complex, and special >> cases aren't special enough to break the rules. > > So you prefer broken code to broken rules, eh? Your customers must love > that! This is exactly the kind of ivory-tower thinking I feared might > be behind the decision (form over function, damn the users to hell, > etc.) > Honestly, based on the content and tenor of this post I think this is Yet Another Python Troll (the ivory tower reference, as well as the abrupt shift from complaining about keywords to multiprocessing), I have to point out that Python does add new keywords, it has done so in the past, and there was a considerable amount of warning, including an automated deprecation warning in the very version you are going to recommend to your "customers' (I don't actually think you have any customers). If you suppressed or ignored the deprecation warning that all your code has been generating for at least 2 years it's pretty damn ballsy to come here and tell everyone how *Python* is doing something wrong. From jstroud at mbi.ucla.edu Sun Dec 7 17:12:10 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 07 Dec 2008 14:12:10 -0800 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: <_SX_k.10055$YU2.2013@nlpi066.nbdc.sbc.com> James Stroud wrote: >[cast to bool] for numpy works like a unary ufunc. Scratch that. Not thinking and typing at same time. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From desas2 at gmail.com Mon Dec 1 12:20:56 2008 From: desas2 at gmail.com (desas2 at gmail.com) Date: Mon, 1 Dec 2008 09:20:56 -0800 (PST) Subject: python 2.5.2 or Python 2.6 compilation problem on AIX 5.3 Message-ID: <26fbc708-1b64-4271-9c7d-4394aa281f47@j39g2000yqn.googlegroups.com> Hello: I am trying to compile Python 2.5.2 on AIX 5.3 with gcc 4.2.3. I am getting following error. (I also tried Python 2.6 with same error) creating build/temp.aix-5.3-2.5/share/tmhsdsd2/tmp/Python-2.5.2/ Modules gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - Wstrict-prototypes -I. -I/share/tmhsdsd2/tmp/Python-2.5.2/./Include - I. -IInclude -I./Include -I/usr/local/include -I/share/tmhsdsd2/tmp/ Python-2.5.2/Include -I/share/tmhsdsd2/tmp/Python-2.5.2 -c /share/ tmhsdsd2/tmp/Python-2.5.2/Modules/_struct.c -o build/temp.aix-5.3-2.5/ share/tmhsdsd2/tmp/Python-2.5.2/Modules/_struct.o creating build/lib.aix-5.3-2.5 ./Modules/ld_so_aix gcc -pthread -bI:Modules/python.exp build/ temp.aix-5.3-2.5/share/tmhsdsd2/tmp/Python-2.5.2/Modules/_struct.o -L/ usr/local/lib -lpython2.5 -o build/lib.aix-5.3-2.5/_struct.so collect2: library libpython2.5 not found *** WARNING: renaming "_struct" since importing it failed: 0509-022 Cannot load module build/lib.aix-5.3-2.5. 0509-026 System error: A file or directory in the path name does not exist. error: No such file or directory make: 1254-004 The error code from the last command is 1. Stop. I am not able to find the problem. I would appreciate, if you could help. I used following command line options to confugure. ./configure --prefix=/home/hci/dinakar/python25 -enable-shared --with- gcc Thank you. Dinakar From __peter__ at web.de Mon Dec 8 05:40:15 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 08 Dec 2008 11:40:15 +0100 Subject: ftp retrlines with re... References: Message-ID: isabellknauer at googlemail.com wrote: > filelist=server.retrlines('LIST') This does not do what you think it does. >>> help("ftplib.FTP.retrlines") gives """ Help on method retrlines in module ftplib: retrlines(self, cmd, callback=None) unbound ftplib.FTP method Retrieve data in line mode. The argument is a RETR or LIST command. The callback function (2nd argument) is called for each line, with trailing CRLF stripped. This creates a new port for you. print_line() is the default callback. """ I. e. you would need something like lines = [] server.retrlines("LIST", lines.append) to store the method's output in a variable instead of printing it to stdout. But try files = server.nlist() instead which gives you a list of filenames. Peter PS: Remember to take Gabriel's advice to heart for your next question. From istvan.albert at gmail.com Fri Dec 5 23:09:39 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Fri, 5 Dec 2008 20:09:39 -0800 (PST) Subject: slow Python 3.0 write performance? References: Message-ID: On Dec 5, 3:41?pm, Christian Heimes wrote: > I've fixed the read() slowness yesterday. You'll get the fix in the next > release of Python 3.0 in a couple of weeks. Does this fix speed up the write() function as well? A previous poster suggested that in this case the slowdown is caused by the new io code being written in python rather than C. Istvan From gagsl-py2 at yahoo.com.ar Wed Dec 17 20:28:04 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 17 Dec 2008 23:28:04 -0200 Subject: C API and memory allocation References: Message-ID: En Wed, 17 Dec 2008 22:51:03 -0200, Aaron Brady escribi?: > On Dec 17, 6:42?pm, "Gabriel Genellina" > wrote: >> En Wed, 17 Dec 2008 21:35:04 -0200, Floris Bruynooghe ? >> escribi?: >> > But how can python now know how long to keep that buffer object in >> > memory for? >> >> It doesn't - *you* have to ensure that the original string object isn't >> ? >> destroyed (by example, incrementing its reference count as long as you ? >> keep the pointer), or copy the string contents into your own buffer. > > I missed something. How did you get a reference to the original > string object, with which to increment its reference count? From the original arguments to the function -- the first argument you pass to PyArg_ParseTuple &co. > How do > you know its length to copy it into your own buffer? Use the "s#" format instead, which returns both a pointer to the string contents and its length. Even if you're not going to copy the buffer, it's required in case the string could contain any NUL byte. -- Gabriel Genellina From andreas at kostyrka.org Mon Dec 15 02:26:16 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 15 Dec 2008 08:26:16 +0100 Subject: Python is slow In-Reply-To: References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> Message-ID: <20081215082616.1de76e92@andi-lap> Am Sun, 14 Dec 2008 20:38:58 -0800 (PST) schrieb cm_gui : > > hahaha, do you know how much money they are spending on hardware to > make > youtube.com fast??? yeah, as they do for basically all big sites, no matter what language is used for implementation. Next is the fact that it's rather simple with Python to meet speed demands where external factors like Gb vs 10Gb network cards are the limiting factor. And last, you do realize that most "simple" websites do hinge on the performance and scalability of the underlying SQL server. In practice some languages like PHP do force that "LAMP" model much stronger on the developer, which makes developing systems that scale beyond a certain point a challenge. So to summarize, Python is fast enough for even demanding stuff, and when done correctly even number crunching or binary parsing huge files or possible in competitive speeds. But you sometime need a developer that can wield the tool with a certain experience, and not a stupid rookie that whines that his tool does not make his O(n**n) algorithm automatically blazing fast. Andreas > > > By the way... I know of a very slow Python site called YouTube.com. > > In fact, it is so slow that nobody ever uses it. > > -- > http://mail.python.org/mailman/listinfo/python-list From dfnsonfsduifb at gmx.de Tue Dec 16 11:59:30 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Tue, 16 Dec 2008 17:59:30 +0100 Subject: Does Python3 offer a FrozenDict? Message-ID: Hello group, is there anything like a frozen dict in Python3, so I could do a foo = { FrozenDict({"a" : "b"}): 3 } or something like that? Regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From mccredie at gmail.com Tue Dec 2 14:37:24 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 2 Dec 2008 11:37:24 -0800 (PST) Subject: performance question: dictionary or list, float or string? References: <434bf4e3-54f4-4e15-b8b0-510a988f25b8@z1g2000yqn.googlegroups.com> Message-ID: On Dec 2, 3:51?am, bkamr... at gmail.com wrote: > I forgot to mention that I did a simple timeit test which doesn't > show > significant runtime difference 3.5 sec for dictionary case and 3.48 > for > list case. > > def read_as_dictionary(): > ? ? fil = open('myDataFile', 'r') > ? ? forces = {} > ? ? for region in range(25): > ? ? ? ? forces[region] = {} > > ? ? for step in range(20000): > ? ? ? ? for region in range(25): > ? ? ? ? ? ? line = fil.next(); spl = line.split() > ? ? ? ? ? ? forces[region] [step] = spl > > def read_as_list(): > ? ? fil = open('myDataFile.txt', 'r') > ? ? forces = [] > ? ? for region in range(25): > ? ? ? ? forces.append([]) > > ? ? for step in range(20000): > ? ? ? ? for region in range(25): > ? ? ? ? ? ? line = fil.next(); spl = line.split() > ? ? ? ? ? ? forces[region].append(spl) > > Cheers, > /Ben There really isn't enough information to recommend a particular direction. A dictionary doesn't seem appropriate for this information though. Also, you are hard coding the step range to 20000. Is that the number of lines in the file? That isn't really a safe way to do it. # this is just bad style in python: line = fil.next(); spl = line.split() # better written spl = fil.next().split() I would just do it this way: def read_as_list(data, regions=25, maxlines=20000): # If data is a filename, open the file. If it is a file # object or any sequence of 'lines' it should just work. file_opened = False if isinstance(data, basestring): data = open(data, 'r') file_opened = True forces = [[] for _ in xrange(regions)] try: for i, line in data: if i == maxlines: break forces[i % 25].append(line.split()) finally: if file_opened: f.close() return forces Matt From esgameserver at gmail.com Wed Dec 3 10:13:14 2008 From: esgameserver at gmail.com (esgameserver at gmail.com) Date: Wed, 3 Dec 2008 07:13:14 -0800 (PST) Subject: Profiling Python Message-ID: <15e24533-472f-4147-9467-893b40ff2710@w35g2000yqm.googlegroups.com> Hi, Simply put, we want to see the profile info dynamically. Is that possible? To clarify again, Is there some function like profile.PrintStats() which dynamically shows the stats before stopping the Profiler? Regards, From googler.1.webmaster at spamgourmet.com Thu Dec 25 05:37:59 2008 From: googler.1.webmaster at spamgourmet.com (googler.1.webmaster at spamgourmet.com) Date: Thu, 25 Dec 2008 02:37:59 -0800 (PST) Subject: Python with PyGIL_Ensure? Message-ID: Hi! I have a small problem with my python embedded interpreter. I do some stuff where two threads exists which do some pythons stuff in the same stuff. So bpoth call PyGILState_Ensure() which occurs a crash. What can I do, that one thread waits until the other thread released the gil state? Thanks a lot. From martin at v.loewis.de Mon Dec 8 02:31:31 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 08 Dec 2008 08:31:31 +0100 Subject: Number of Python 3.x packages at the PyPI In-Reply-To: References: <9c1ab0f3-6686-4c0f-8a6c-12e20539f354@41g2000yqf.googlegroups.com> <493b954e$0$4021$9b622d9e@news.freenet.de> Message-ID: <493ccd54$0$21674$9b622d9e@news.freenet.de> > Should specifying the 3.0 tag implicity and automatically specify the > 3 tag as well? No. There is really no builtin automatic semantics to any of the classifiers. Regards, Martin From kyosohma at gmail.com Tue Dec 30 13:46:21 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 30 Dec 2008 10:46:21 -0800 (PST) Subject: folder extraction References: Message-ID: <0854393e-6c94-451e-9e9d-51132d7e09e3@k1g2000prb.googlegroups.com> On Dec 30, 9:30?am, ibpe... at gmail.com wrote: > how do i get along with this task of extracting multiples folder and > generating their names individually in a their respective files as > they were generated. Are you talking about unzipping an archive or walking a directory? If the former, see the zip module or use the subprocess module to control an external archiving application. If the latter, see os.walk and the glob module. Mike From hoteljorba at gmail.com Tue Dec 9 18:31:54 2008 From: hoteljorba at gmail.com (morecowbell) Date: Tue, 9 Dec 2008 15:31:54 -0800 (PST) Subject: fuzzy or boolean text search References: <104335ff-e507-4429-9ad3-baecb63da8b3@k36g2000yqe.googlegroups.com> Message-ID: On Dec 9, 12:14?am, John Machin wrote: > On Dec 9, 4:36?pm, n00b wrote: > > > hi, > > > i'm looking for advice/suggestions for text search, preferably with > > boolean or even fuzzy capabilities, and for use with mysql innodb > > tables. ?asking too much :) ??? > > No ... feeding "fuzzy boolean text search mysql innodb" to my googler > didn't choke it; it produced this at about the 15th hit: > > http://www.sphinxsearch.com/docs/manual-0.9.8.html > > Please tell your googler that we all hope that it gets well soon :-) since you found the list, i presume you can google and looking for something pythonic. we tried a few options but it's bleak. for a pythonic solution, look at TextIndexNG3 (Zope). i'll take some fiddling, though: http://sourceforge.net/projects/textindexng; if something with a py wrapper will do, you might as well go with the big guns: lucence. we found that to work very well and that includes SA integration (http://www.freebsdsoftware.org/textproc/py-lucene.html) From exarkun at divmod.com Thu Dec 18 10:10:54 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 18 Dec 2008 10:10:54 -0500 Subject: confused about __str__ vs. __repr__ In-Reply-To: Message-ID: <20081218151054.20272.980517665.divmod.quotient.22608@ohm> On Thu, 18 Dec 2008 09:51:01 -0500, Neal Becker wrote: >Tino Wildenhain wrote: > >> Neal Becker wrote: >> ... >>>>> So if __str__ is "meant for human eyes", then why isn't print using it! >>>> it is: >>>> >>>> > print x >>>> str >>>> >>>> but dict just uses repr() for all its childs to print. >>>> >>>> T. >>> That makes no sense to me. If I call 'print' on a container, why >>> wouldn't it recursively print on the contained objects? Since print >>> means call str, printing a container should recursively call str on the >>> objects. >> >> Every class is free on how to best implement __str__, you will find >> the same behavior on tuple and list as well. >> >> Maybe its discussable to change the implementation sensibly, best if you >> would come with a proposal? Perhaps pprint.pprint is a starting point? >> >> Regards >> Tino > >First, I'd like to know if there is a rationale for the current design. Am I correct in thinking this is a defect? There is a rationale. Consider: >>> class strit(object): ... def __init__(self, it): ... self.it = it ... def __repr__(self): ... return str(self.it) ... This will let us see what a dict.__str__ which called __str__ on the objects in it would look like. So first, something simple: >>> print str({strit("['foo']"): 'bar'}) {['foo']: 'bar'} >>> Mildly confusing - you can't use a list as a dict key! But it could be worse: >>> print str({strit("1: 2, 3"): 'bar'}) {1: 2, 3: 'bar'} >>> Wait - *how* many items are in that dictionary? Hopefully that makes the rationale clear - when a human is looking at the str of a dict (and a human is ostensibly the intended audience) - using the __repr__ of the contained objects makes it easier for the human to understand what's in the dict. Using __str__ would make it much harder in many cases. Jean-Paul From clp at rebertia.com Wed Dec 17 00:44:41 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 16 Dec 2008 21:44:41 -0800 Subject: The rule of literal string In-Reply-To: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> Message-ID: <47c890dc0812162144r365c74dfw464118825a963e9e@mail.gmail.com> On Tue, Dec 16, 2008 at 9:32 PM, Li Han wrote: > Hi! I just began to read the tutorial of python3.0 and I just can't > figure out the rule of literal string. There is a example in the > tuotrial: >>>> '"Isn\'t," she said.' > '"Isn\'t," she said.' > It is not what I want, I just want '"Isn't," she said.' be printed, > why the backslash failed? > These don't work at all: >>>> '''"Isn't," she said.''' > '"Isn\'t," she said.' >>>> r"Isn't," she said. > SyntaxError: invalid syntax (, line 1) >>>> r'"Isn't," she said.' > SyntaxError: invalid syntax (, line 1) > I have tried to solve it until my brain damaged and now I need to > sleep. You need to print() the string. Otherwise, the interpreter does an implicit repr() on the string, causing it to output a string literal equivalent to the string, essentially doing print(repr(your_string)). To explain what repr() does, consider the following identity: eval(repr(your_string)) == your_string Notice how the outer set of quotes is still present in the output you got. Using print() explicitly causes repr() not to be called, thus the escape backslashes aren't shown and neither are the surrounding quotes. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From ldo at geek-central.gen.new_zealand Mon Dec 1 03:03:01 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 01 Dec 2008 21:03:01 +1300 Subject: Emacs vs. Eclipse vs. Vim References: Message-ID: In message , Roy Smith wrote: > Likewise for the source control (CVS, SVN, P4, etc) integrations [in > emacs]. Discovered that by accident today. Had a conflicted update in Subversion, fixed it up, saved the file, switched to a terminal window, typed "svn status", and lo and behold, the conflict had vanished (along with the .mine and .rnn files). I assume it was Emacs doing that, and not a side-effect of the "svn status" command. :) From floris.bruynooghe at gmail.com Wed Dec 17 18:35:04 2008 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Wed, 17 Dec 2008 15:35:04 -0800 (PST) Subject: C API and memory allocation References: Message-ID: Hello again On Dec 17, 11:06?pm, Floris Bruynooghe wrote: > So I'm assuming PyArg_ParseTuple() > must allocate new memory for the returned string. ?However there is > nothing in the API that provides for freeing that allocated memory > again. I've dug a little deeper into this and found that PyArg_ParseTuple (and friends) end up using PyString_AS_STRING() (Python/getargs.c:793) which according to the documentation returns a pointer to the internal buffer of the string and not a copy and that because of this you should not attempt to free this buffer. But how can python now know how long to keep that buffer object in memory for? When the reference count of the string object goes to zero the object can be deallocated I though, and then your pointer will point to something different all of a sudden. Does this mean you always have too keep a reference to the original objects when you've extracted information from them with PyArg_Parse*() functions? (At least while you want to hang on to that information.) Regards Floris From stef.mientki at gmail.com Tue Dec 30 15:21:45 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 30 Dec 2008 21:21:45 +0100 Subject: embedding python in wxpython In-Reply-To: <191280cf-ecf9-4135-9737-9923061855d1@t39g2000prh.googlegroups.com> References: <191280cf-ecf9-4135-9737-9923061855d1@t39g2000prh.googlegroups.com> Message-ID: <495A82D9.3000902@gmail.com> 5lvqbwl02 at sneakemail.com wrote: > Hi, I've looked around for a way to allow a python console from within > a wxPython application, but have only found stuff on embedded/ > extending python with C/C++ or wxWidgets in C++, but not wxPython. > > Is this easy to do? Can someone point me in the right direction? > > Also, typically when you embed a scripting language into a larger > application, how do you get the console environment to share data with > the larger application? > > For instance, if the application has some gui stuff (for example > clicking on a object and dragging it around), how do you get > "object.select(x,y)" to print out on the console, and vice-versa: the > object gets selected if the user types "object.select(x,y)"? > > I'd like the console to be a bidirectional representation of what's > going on in the gui, plus a general purpose evaluation environment > where you can manipulate application data via some api which is > automatically exposed to the console when the application opens up. > > I'm looking for high-level hints/strategies/directions. > If you're looking for "high-level", I don't understand why you want to see what's going on in the gui, as I see the gui just a tool to control the real data. For a pretty high level data manipulation, something like PyLab_Works ? http://code.google.com/p/pylab-works/ cheers, Stef From jstroud at mbi.ucla.edu Fri Dec 5 17:00:18 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 05 Dec 2008 14:00:18 -0800 Subject: To Troll or Not To Troll (aka: "as" keyword woes) In-Reply-To: <20081205163107.1815df40@usenot.de> References: <20081205163107.1815df40@usenot.de> Message-ID: Andreas Waldenburger wrote: > Is it me, or has c.l.p. developed a slightly harsher tone recently? > (Haven't been following for a while.) Yep. I can only post here for about a week or two until someone blows a cylinder and gets ugly because they interpreted something I said as a criticism of the language and took it personally by extension. Then I have to take a 4 month break because I'm VERY prone to reciprocating--nastily. I think its a symptom of the language's maturing, getting popular, and a minority fraction* of the language's most devout advocates developing an egotism that complements their python worship in a most unsavory way. I wish they would instead spend their energy volunteering to moderate this list and culling out some of the spam. *No names were mentioned in the making of this post. From jay.dow at gmail.com Thu Dec 11 10:53:32 2008 From: jay.dow at gmail.com (jay.dow at gmail.com) Date: Thu, 11 Dec 2008 07:53:32 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <9e0bb906-e019-45ef-8047-b33982c7c5ad@l39g2000yqn.googlegroups.com> Message-ID: On Dec 11, 7:06 am, Luis M. Gonz?lez wrote: > On Dec 10, 3:42 pm, cm_gui wrote: > > > > >http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-... > > > I fully agree with Krzysztof Kowalczyk . > > Can't they build a faster VM for Python since they love the language > > so much? > > > Python is SLOW. And I am not comparing it with compiled languages > > like C. > > Python is even slower than PHP! > > > Just go to any Python website and you will know. > > An example is:http://www2.ljworld.com/ > > And this site is created by the creators of Django! > > > And it is not just this Python site that is slow. There are many many > > Python sites which are very slow. And please don?t say that it could > > be the web hosting or the server which is slow ? because when so many > > Python sites are slower than PHP sites, it couldn?t be the web > > hosting. Also, Zope/Plone is even slower. > > > Python is slow. Very slow. > > Now seriously, just to finish your idiotic rant, check the Pypy > project: > > http://codespeak.net/pypyhttp://morepypy.blogspot.com > > And if you still think this is not enough, why don't you help these > guys to make it faster? > > Luis PyPy looks pretty sweet. I'm glad this discussion was started. There always seems to be this buzz about python being slow. So what if it's not as fast as C? I make that up by cutting down development time. I figured if I ever ran into something being too slow, that I'd just have to learn c extensions and replace the bottle necks. In 2007 I wrote a system in python that communicated to an autopilot on an autonomously flying aircraft at real-time. We never had any speed issues. I have not played with django much and I do not typically develop web apps, but the slowness really must be bloated algorithms in the libraries you are using. Programming in other languages (java, c, c++, c# etc) is not an issue for me, but next to python it's like writing with a feather and ink instead of a ball point pen. I have to put more time into working with the tools I'm using than actually getting the job done. From mal at egenix.com Thu Dec 11 11:05:21 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 11 Dec 2008 17:05:21 +0100 Subject: Rich Comparisons Gotcha In-Reply-To: <200812101721.51692.kyrie@uh.cu> References: <200812101401.35786.kyrie@uh.cu> <49401C2D.4050209@egenix.com> <200812101721.51692.kyrie@uh.cu> Message-ID: <49413A41.2090605@egenix.com> On 2008-12-10 23:21, Luis Zarrabeitia wrote: > On Wednesday 10 December 2008 02:44:45 pm you wrote: >>> Even in statically typed languages, when you override the equality >>> operator/function you can choose not to return a valid answer (raise an >>> exception). And it would break all the cases mentioned above (element in >>> list, etc). But that isn't the right thing to do. The language >>> doesn't/can't prohibit you from breaking the equality test, but that >>> shouldn't be considered a feature. (a==b).all() makes no sense. >> Perhaps not in your application, but it does make sense in other >> numeric applications, e.g. ones that work on vectors or matrixes. >> >> I'd suggest you simply wrap the comparison in a function and then >> have that apply the necessary conversion to a boolean. > > I do numeric work... I'm finishing my MSc in applied math and I'm programing > mostly with python. And I'd rather have a.compare_with(b), or > a.elementwise_compare(b), or whatever name, rather than (a==b).all(). In > fact, I'd very much like to have an a.compare_with(b, epsilon=e).all() (to > account for rounding errors), and with python2.5, all(a.compare_with(b)). > > Yes, I could create an element_compare(a,b) function. But I still can't use > a==b and have a meaningful result. Ok, I can (and do) ignore that, it's just > one library, I'll keep track of the types before asking for equality (already > an ugly thing to do in python), but the a==b behaviour breaks the lists (a in > ll, ll.indexof(a)) even for elements not in numpy. ?Should I also ignore > lists? You should perhaps reconsider your use of lists. Lists with elements of different types can be tricky at times, so perhaps you either need a different data type which doesn't scan all elements or a separate search function that knows about your type setup. The fact that comparisons can raise exceptions is not new to Python, so this problem can pop up in other areas as well, esp. when using 3rd party extensions. Regarding the other issues like new methods you should really talk to the numpy developers, since they are the ones who could fix this. > The concept of equality between two arrays is very well defined, as it is also > very well defined the element-by-element comparison. There is a need to test > for both - then the way to test for equality should be the equality test. > >>> I'm certain that something could be worked out. A quick paragraph that >>> took me just a few minutes to type shouldn't be construed as a PEP that >>> will solve all the problems :D. >> As always: the Devil is in the details :-) > > Of course... -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 11 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-12-02: Released mxODBC.Connect 1.0.0 http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From mail at timgolden.me.uk Fri Dec 5 16:05:07 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 05 Dec 2008 21:05:07 +0000 Subject: Can I load a python program at the interactive >>> prompt? In-Reply-To: <269e5d69-02b7-409b-ad53-b7702b6ec13a@i24g2000prf.googlegroups.com> References: <269e5d69-02b7-409b-ad53-b7702b6ec13a@i24g2000prf.googlegroups.com> Message-ID: <49399783.8040108@timgolden.me.uk> walterbyrd wrote: > I am running cygwin on xp. > > Much to my annoyance, I can not cut-and-paste from a windows app to > the python prompt. I think I could do this with putty, but I do not > have the permissions to install putty on my xp box. I do this all the time. The key (altho' not strictly essential) is to access the console window Properties from the top-left drop-down menu and then on the first tab, select Quick Edit. With this, you can just right-click with the mouse and whatever you had in the clipboard (as long as it's text) will drop into your Python session. Whenever I'm posting code snippets here, I always copy them from the email and do what I've described to run them in a fresh interpreter session to make sure they work. > > Can I load a file into the python interactive environment? For > example I have a file called test.py that consists of the following: > > print "hello" > print "hello again" > > Can I load that file into python at the >>> prompt? > >>>> load "test.py" > > or something like that? Well, you can use execfile if you want. TJG From excord80 at gmail.com Sun Dec 7 20:23:10 2008 From: excord80 at gmail.com (excord80 at gmail.com) Date: Sun, 7 Dec 2008 17:23:10 -0800 (PST) Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? References: Message-ID: On Dec 7, 8:17?pm, "Patrick Mullen" wrote: > On Sun, Dec 7, 2008 at 4:43 PM, ? wrote: > > [snip] > PyOpengl - an opengl wrapper. ?Version 2 is written in c, version 3 > instead uses ctypes > Pyglet - an opengl + events/sound/etc wrapper written in ctypes Does pyglet use PyOpenGL as its OpenGL wrapper? If not, any idea why? Seems like it would be a fairly substantial duplication of effort. From python at rcn.com Fri Dec 19 06:42:24 2008 From: python at rcn.com (Raymond Hettinger) Date: Fri, 19 Dec 2008 03:42:24 -0800 (PST) Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> Message-ID: On Dec 12, 7:51?am, Marco Mariani wrote: > Filip Gruszczy?ski wrote: > > I am not doing it, because I need it. I can as well use "if not elem > > is None", > > I suggest "if elem is not None", which is not quite the same. They are semantically the same. In theory, Filip's would run slower because of the time to negate the is-test, but the peephole optimizer recognizes the opportunity to make the substitution so it works out exactly the same: >>> dis(compile('x is not None', '', 'eval')) 1 0 LOAD_NAME 0 (x) 3 LOAD_CONST 0 (None) 6 COMPARE_OP 9 (is not) 9 RETURN_VALUE >>> dis(compile('not x is None', '', 'eval')) 1 0 LOAD_NAME 0 (x) 3 LOAD_CONST 0 (None) 6 COMPARE_OP 9 (is not) 9 RETURN_VALUE Raymond From rbrennan55 at hotmail.com Tue Dec 2 16:18:30 2008 From: rbrennan55 at hotmail.com (RON BRENNAN) Date: Tue, 2 Dec 2008 16:18:30 -0500 Subject: Simple ini Config parser examples needed Message-ID: Hello, I have a very simple ini file that I needs parsed. What is the best way I can parse an ini file that doesn't include sections? As in: person=tall height=small shoes=big Thats it. Can anyone help me? Thanks, Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: From zhushenli at gmail.com Wed Dec 3 20:08:27 2008 From: zhushenli at gmail.com (Davy) Date: Wed, 3 Dec 2008 17:08:27 -0800 (PST) Subject: Thread Tkinter problem References: <64c7402c-8b7b-4281-9d7d-1abdd6177d96@r15g2000prh.googlegroups.com> Message-ID: <35672781-eca1-4139-8b5d-88c457960d62@g1g2000pra.googlegroups.com> On Dec 4, 11:13?am, "Hendrik van Rooyen" wrote: > ?"Davy" wrote: > > ? ? while(data_queue.full() == False): > > This will fill the queue and stop. > Use while true and if queue not full... Hi Hendrik, It works, thank you:) Davy > > - Hendrik From google at mrabarnett.plus.com Mon Dec 15 10:42:16 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 15 Dec 2008 15:42:16 +0000 Subject: Thread Locking issue - Can't allocate lock (sem_init fail) In-Reply-To: References: Message-ID: <49467AD8.2030105@mrabarnett.plus.com> Philip Semanchuk wrote: > > On Dec 15, 2008, at 4:56 AM, jamskip at googlemail.com wrote: > >> Hi all, >> >> I have a peculiar problem with a multithreaded program of mine >> (actually I've sort of inherited it). Before i show you the error, >> here's a litle background. Its a program to check email addresses are >> valid, and its main task is to verify the domain names. >> >> Here's the basic functionality: >> >> * The prog has a list of domains it has seen before which is read into >> memory (the 'rollover'). >> * A new list of emails is read-in from a file (to a queue) and is >> checked against the rollover. >> * If we've seen the domain before then update the existing entry. >> * If we've not seen the domain before, add it. >> >> The program is multithreaded to speed up the processing...there are >> input and output Queues. >> >> Now, each domain entry is an class object containing various bits of >> info. Each domain class also has its own lock, so that only one thread >> can modify each domain at a time. >> >> I'm load-testing the program with a sample of 1 million email >> addresses and when i hit about the 500,000 mark i get a locking >> error... >> >> sem_init: No space left on device >> Exception in thread Thread-2: >> Traceback (most recent call last): >> File "/usr/local/lib/python2.4/threading.py", line 442, in >> __bootstrap >> self.run() >> File "/usr/local/lib/python2.4/threading.py", line 422, in run >> self.__target(*self.__args, **self.__kwargs) >> File "jess.py", line 250, in worker >> record.result = function( id, record.value ) >> File "jess.py", line 291, in action >> found_domain = domains.addNewDomain( domain_name ) >> File "jess.py", line 123, in addNewDomain >> self.domain_store.append( self.Domain( name = name ) ) >> File "jess.py", line 46, in __init__ >> self.lock = Lock() >> error: can't allocate lock >> >> Googling for this sort of error doesn't yield any results, and i can't >> find any information about limits to the number of locks you can have >> in Python. The 'No space left on device' message indicates a memory >> issue, however i doubt this since its running on a linux server with 4 >> cores and 16GB ram. It seems more like an internal Python limit has >> been hit (sem_init - semaphore initialisation?). Does anyone know more >> about threading internals and any internal limits? > > Hi Jamskip, > I don't work with threading code but I have been working with semaphores > for my IPC extensions. sem_init() is a call to create a semaphore > (http://linux.die.net/man/3/sem_init). If it is failing, then I'd guess > you're trying to create an awful lot of semaphores (intentionally or > otherwise) and that you're hitting some internal limit. > > I would not be too quick to assume that the number of semaphores one can > create is bounded by the amount of RAM in your system. I don't think > they're simple chunks of malloc-ed memory. They're probably represented > in a kernel data structure somewhere that's hardcoded to some generous > but fixed value. > > Please note that this is all speculation on my part. I think that the > Python threading implementation would use the "local" (i.e. not > process-shared) semaphores which can be allocated on the process' heap. > This would seem only RAM-limited, but I'll bet it isn't. > > You might want to start debugging by track exactly how many locks you're > creating. If the number is really big, start investigating kernel > semaphore limits and how they're set. > You're creating a thread and a lock for each _domain_? Sounds like overkill to me. Many domains means many threads and many locks, by the sounds of it too many for the system. From prabhu.ranjith at gmail.com Sun Dec 7 11:12:29 2008 From: prabhu.ranjith at gmail.com (ranjith) Date: Sun, 7 Dec 2008 08:12:29 -0800 (PST) Subject: @ Start learning through internet @ Message-ID: <2f93f018-85b4-47c4-a335-97584cd202f9@r40g2000yqj.googlegroups.com> visit as at www.tiketin.blogspot.com You can learn all the computer languages from your home itself now. Online study. Visit www.tiketin.blogspot.com to start learning through internet and to clear your computer doubts. From sjmachin at lexicon.net Tue Dec 30 20:45:03 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 30 Dec 2008 17:45:03 -0800 (PST) Subject: Triple quoted string in exec function ? References: <495A253B.6010003@gmail.com> <495A81A7.8030507@gmail.com> Message-ID: <0020c0c3-6ce7-4629-8f13-c2f606cb77d3@z6g2000pre.googlegroups.com> On Dec 31, 8:34?am, Steve Holden wrote: > Stef Mientki wrote: > > ibpe... at gmail.com wrote: > >> On Dec 30, 2:48 pm, Steve Holden wrote: > > >>> Stef Mientki wrote: > > >>>> hello, > >>>> ? ? ? I'm running scripts, with the execute function (Python 2.5), > >>>> and it seems that triple quoted strings are not allowed. > >>>> ? ? ? Is there a workaround, > >>>> or is this a fundamental problem of the exec-function ? > > >>> If you think about it, it should be obvious that you can't surround a > >>> string to be compiled with any of the quotes that appear inside the > >>> string to be compiled. That's about the only limitation I am aware of. > > >>> And, by the way, exec is a *statement*, not a function! > > > ? ? ?exec ( Init_Code, PG.P_Globals ) > > > I've really doubt that this is a statement, > > unless I don't understand what a statement is. > > We'll have to conclude you don't, then, won't we ;-) > Two observations: (1) Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> exec("print a", {'a': 42}) 42 >>> exec "print a" in {'a': 42} 42 (2) >From http://docs.python.org/3.0/whatsnew/3.0.html#removed-syntax """ Removed keyword: exec() is no longer a keyword; it remains as a function. (Fortunately the function syntax was also accepted in 2.x.) """ There's still the triple-quotes-aren't-a-problem issue and the perennial not-showing-code-and-error-output issue ... so by my reckoning the score for this match is: Stef 1, RoW 2 :-) From google at mrabarnett.plus.com Sat Dec 20 21:49:57 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 21 Dec 2008 02:49:57 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: <494DAED5.4080108@mrabarnett.plus.com> Aaron Brady wrote: > On Dec 20, 7:38 pm, Steven D'Aprano cybersource.com.au> wrote: >> Instead of just whinging, how about making a suggestion to fix it? Go on, >> sit down for an hour or ten and try to work out how a BINARY OPERATOR >> like % (that means it can only take TWO arguments) can deal with an >> arbitrary number of arguments, *without* having any special cases. >> >> Go on. Take your time. I'll be waiting. > > Hi, not to take sides, but, there is a possibility. > > This behavior is currently legal: > >>>> "%i %%i" % 0 % 1 > '0 1' > > So, just extend it. (Unproduced.) > >>>> "%i %i" % 0 % 1 > '0 1' >>>> "%r %i" % (2, 3, 4) % 1 > '(2, 3, 4) 1' >>>> "%r %i" % (2, 3, 4) > '(2, 3, 4) %i' > > Which is quite clever and way ahead of its (posessive) time. > A couple of problems: 1. How do you handle a literal '%'? If you just double up then you'll need to fix the string after all your substitutions. 2. What if a substitution introduces a '%'? I suppose a possible solution would be to introduce a special format string, including a literal, eg: f"%r %i" % (2, 3, 4) % 1 and then convert the result to a true string: print(str(f"%r %i" % (2, 3, 4) % 1)) (although print() would call __str__ anyway). The format string would track where the last substitution occurred. Hmm... I think I'll just learn the new method. :-) From rogerb at rogerbinns.com Mon Dec 29 16:52:33 2008 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 29 Dec 2008 13:52:33 -0800 Subject: SQL, lite lite lite In-Reply-To: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Aaron Brady wrote: > Python. There are some options, such as 'sqllite3', but they are not > easy. 'sqllite3' statements are valid SQL expressions, which afford > the entire power of SQL, but contrary to its name, it is not that > 'lite'. Have you compared the compiled size of SQLite against other things? For example on my machine the size of MySQL client library, whose sole purpose is to transport queries and results across the network is the same size as the entirety of SQLite! You can prune SQLite back even further as documented in http://www.sqlite.org/compile.html It is even possible to omit the SQL front end. Queries are stored already processed in the database. This functionality is used by mp3 manufacturers and similar constrained embedded environments. > To me, 'lite' is something you could learn (even make!) in an > afternoon, If you just want to treat the database as a glorified spreadsheet then SQL is "lite", although perhaps a little verbose of a dbm style interface. > If you think SQL is > a breeze, you probably won't find my idea exciting. I assume that the > basics of SQL are creating tables, selecting records, and updating > records. The basics of SQL are about expressing the relational model http://en.wikipedia.org/wiki/Relational_model which has stood the test of time. (That doesn't mean it is superior just that it is good enough like the "qwerty" keyboard layout.) There have been attempts at alternatives like http://en.wikipedia.org/wiki/The_Third_Manifesto but that doesn't seem to have caught on. It seems your basic complaint is the complexity of doing database stuff. Ultimately this will be the case if some data is related to other bits of data. As other posters have pointed out, there are various ORM type wrappers for Python that try to wrap this up in syntactic sugar :-) For something completely different have a look at CouchDB http://couchdb.apache.org/ which operates on "documents" (basically something with an id and an arbitrary updateable list of properties). It does take a bit to get your head wrapped around it - try this posting for an example http://www.cmlenz.net/archives/2007/10/couchdb-joins Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAklZRp0ACgkQmOOfHg372QQ4RQCgzSmgEhvG2DQlWYb68U8BZNOo wOAAnip4GIvKiskuwwWJwaepmJwHLjXJ =0UiA -----END PGP SIGNATURE----- From greg at cosc.canterbury.ac.nz Sun Dec 14 19:04:00 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Mon, 15 Dec 2008 13:04:00 +1300 Subject: [OT] stable algorithm with complexity O(n) In-Reply-To: References: <6qidmbFc4qduU1@mid.uni-berlin.de> Message-ID: <6qll2nFd5qv8U1@mid.individual.net> Lie Ryan wrote: > "You know what you just did? You've > just found a problem that was supposed to be an example of unsolvable > problem." > > It has happened before, why not again? There's a big difference between an unsolvable problem and an unsolved problem. In the cases you're talking about, nobody had solved the problem before, but neither had anybody proved there was no solution. In the case at hand, there is a proof that such an algorithm is impossible. Overturning that would require finding a flaw in the proof, which for such a simple proof seems very unlikely. That's not to say nobody should try, but I won't be holding my breath. -- Greg From google at mrabarnett.plus.com Wed Dec 24 13:04:16 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 24 Dec 2008 18:04:16 +0000 Subject: Iterating over objects of a class In-Reply-To: <6rfb7iF1fg5rU1@mid.uni-berlin.de> References: <2df27de3-7fa3-4ac9-acd9-f946939517cf@r37g2000prr.googlegroups.com> <6rfb7iF1fg5rU1@mid.uni-berlin.de> Message-ID: <495279A0.1030504@mrabarnett.plus.com> Diez B. Roggisch wrote: > Kottiyath schrieb: >> Hi, >> How can I iterate over all the objects of a class? >> I wrote the code like following: >> class baseClass(object): > > Consider adopting PEP 8 coding conventions. > > >> __registry = [] >> >> def __init__(self, name): >> self.__registry.append(self) >> self.name = name >> >> def __iter__(self): >> baseClass.item = 0 >> return self.__registry[0] >> >> def next(self): >> if baseClass.item >= len(self.__registry): >> raise StopIteration >> baseClass.item += 1 >> return self.__registry[baseClass.item - 1] >> >> For testing, create the following objects- >> a = baseClass("Test1") >> b = baseClass("Test2") >> >> class subClass (baseClass): >> pass >> c = subClass("Test3") >> >> ---->Actual Iteration<---- >> for i in a: >> print i.name >> >> Test1 >> Test2 >> Test3 >> >> --------------------------------------------------- >> I see the following problems in the code: >> 1. I have to iterate over any of the objects. For correctness, I >> wanted to iterate over the class, like >> for i in baseClass(): >> do x >> but that will will create one more object - which I do not want. >> >> 2. If the subclass wants to do somethings in its constructor, I am not >> sure how to update the registry. >> class subClass (baseClass): >> def __init__(self, name): >> **do something** >> super.init(self, name) ----> This errors out, saying it needs >> super, not subClass > > You don't show the actual traceback, however the idiom for invoking > super for new-style-classes is > > > super(subClass, self).__init__(name) > > for your case. > >> Another method I thought of implementing it was using generators - >> where-in baseClass.objects() is a generator which will yield the >> objects one by one - but even then the second issue remains. >> If somebody can help me out, I would be very thankful. > > > Using a generator or not isn't the issue here. > > What you need is a *class*-based access, not instance-based. There are > various methods to accomplish this. The simplest is to ditch the > obnoxious __registry as name, and just do > > class BaseClass(object): > > REGISTRY = [] > > > Then iterating is a simple matter of > > for instance in BaseClass.REGISTRY: > ... > > > Case solved. Alternatively, if you insist on the concept of privacy for > that registry, you can use a classmethod: > > > class BaseClass(object): > > > @classmethod > def registry(cls): > for i in cls.__registry: > yield i > > > > > > Last but not least you *could* go for a __metaclass__ with an > __getitem__-method, that makes thinks look fancy because you then can do: > > > for instance in BaseClass: > ... > > I leave it as an exercise to you - gotta go christmas dining now :) > The other thing to remember is that because the 'registry' contains references to the instances, they won't be garbage collected. From hubaghdadi at gmail.com Sun Dec 28 06:40:11 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Sun, 28 Dec 2008 03:40:11 -0800 (PST) Subject: What is site-packages? Message-ID: Hey, What is /usr/lib/pythonx.y/site-packages folder and for what it is used usually? Thanks. From paul at boddie.org.uk Wed Dec 10 06:43:26 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 10 Dec 2008 03:43:26 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> <014ef03e$0$20670$c3e8da3@news.astraweb.com> Message-ID: On 10 Des, 00:00, Steven D'Aprano wrote: > > Go right ahead. Write your experimental language, and if people like it, > they'll use it. That's what Guido did, all those years ago. But don't > turn Python into a hodgepodge of "features" that most people consider > misfeatures. If you consult the public record, you'll see that I'm probably more conservative than most when it comes to adding features. Indeed, one of the principal benefits I see in Python 3.0 is that the hordes of people wanting to add new stuff to Python will now focus on that flavour of the language and not Python 2.x. However, as I pointed out in another message, keyword conflicts have been a problem for the language designers for some time, and more powerful parser technology might have been able to help out. [...] > I think it is childish to reject the Zen just because it's the Zen. Good > advice doesn't cease to be good advice just because people tell you it's > good advice, even if some people are awfully strident about it. I object to the Zen being trotted out every time someone questions any aspect of Python's design (language or implementation) which isn't being reworked elsewhere (say, in Python 3, where apparently the Zen can be suspended), especially when the parts of the Zen being quoted lack pertinence when compared to a properly formulated response to the original inquiry. Paul From pdorange at pas-de-pub-merci.mac.com Tue Dec 23 12:34:41 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Tue, 23 Dec 2008 18:34:41 +0100 Subject: Python's popularity References: Message-ID: <1isezj4.1l4g8lk1plxz8lN%pdorange@pas-de-pub-merci.mac.com> r wrote: > > I've already stated, and you've already proven, that it's pretty trivial > > to ascertain my true identity, if one actually cares. OTOH, that's > > *not* the case with you. Who is hiding now? > > I told you, my name is Thurstan Howell III. Do you want to know my > favorite color too? Only if it's pythonic. -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From invalid at invalid Thu Dec 11 18:01:10 2008 From: invalid at invalid (Grant Edwards) Date: Thu, 11 Dec 2008 17:01:10 -0600 Subject: Best way of debigging a C extension References: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> <6qdjt7Fc1fg0U1@mid.uni-berlin.de> Message-ID: On 2008-12-11, Diez B. Roggisch wrote: > I never tried this on windows - but what happens if you start > python inside GDB, and then set breakpoints inside your > extension? > > This works flawlessly for me under *nix. > > The debug-build of python isn't needed for this - and I doubt > a bit that it helps you much, as being inside the interpreter > & getting detailed information isn't your goal - you want to > see your extensions functions, what parameters they get and so > on. It's probably a lot easier to just stick in a few printf() calls in key places... -- Grant Edwards grante Yow! I'm into SOFTWARE! at visi.com From kyosohma at gmail.com Mon Dec 1 14:20:20 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 1 Dec 2008 11:20:20 -0800 (PST) Subject: Dec 1st Python Meeting Cancellation Message-ID: Hi all! Sorry for the very short notice, but the Python Programming group is canceling tonight's meeting due to inclement weather, lack of interest and sickness. We hope to see you at our next meeting, which will be Monday, January 5th, 2009. Happy holidays! Mike Driscoll http://www.pyowa.org From clp at rebertia.com Wed Dec 17 18:25:41 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 17 Dec 2008 15:25:41 -0800 Subject: The rule of literal string In-Reply-To: <34028b73-7807-4e88-80bc-fe31a7b1a2a0@i20g2000prf.googlegroups.com> References: <7eeb7ca1-8075-4a17-b761-52fbddebe0c9@40g2000prx.googlegroups.com> <_PmdnU59w62vGtTUnZ2dnUVZ_hSdnZ2d@pdx.net> <34028b73-7807-4e88-80bc-fe31a7b1a2a0@i20g2000prf.googlegroups.com> Message-ID: <47c890dc0812171525t527353e2m5c8b0597ee183e21@mail.gmail.com> 2008/12/17 Li Han : > On 12?18?, ??7?12?, Scott David Daniels wrote: > Scott wrote: >> Try: print repr(repr("'")) >> that might enlighten you. > > I found that print( repr( repr( arbitarystring ) ) ) == repr > ( arbitarystring ) As I stated previously, the key rule is: eval(repr(something)) == something That is, repr() gives a string of Python code that, when evaluated, results in what you gave to repr(). So repr('') ==> "''" And repr("''") ==> "\"''\"" Which when print()-ed is: "''" And eval("''") is the same as entering two apostrophes ('') at the REPL, both of which give an empty string object. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From mludvig at logix.net.nz Mon Dec 29 07:41:51 2008 From: mludvig at logix.net.nz (Michal Ludvig) Date: Tue, 30 Dec 2008 01:41:51 +1300 Subject: setup.py installs modules to a wrong place In-Reply-To: <7d6d6971-e6cc-418f-a79e-598517ffb013@j38g2000yqa.googlegroups.com> References: <494384EF.7050605@logix.net.nz> <7d6d6971-e6cc-418f-a79e-598517ffb013@j38g2000yqa.googlegroups.com> Message-ID: <4958C58F.9060504@logix.net.nz> Hi Omer, > I'm seeing this on fc8 with a custom built python2.6. Not happening > with any other packages (e.g. boto). Workaround of course was just to > copy the S3 dir to /usr/local/lib/python2.6/site-packages. I've found it. The culprit was a pre-set install prefix in setup.cfg - I can't remember why I put it there ages ago. Anyway, now it's removed ;-) > I poked around a bit but nothing obvious jumped out. Happy to do any > debugging if you have tests you'd like to me to run. Thanks for the offer. I believe the current SVN trunk [1] of s3cmd should install just fine everywhere. Michal [1] .. http://s3tools.logix.cz/download From sjmachin at lexicon.net Wed Dec 17 18:06:47 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 17 Dec 2008 15:06:47 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> <0d9ea7cc-b5fb-4edb-be32-490aae9e7204@b41g2000pra.googlegroups.com> <0de3a7bf-a4c4-4103-a4e0-44313405fa94@z28g2000prd.googlegroups.com> Message-ID: <23d6710f-2c6d-4115-817a-053b8e96f1ce@z28g2000prd.googlegroups.com> On Dec 18, 3:15?am, aka wrote: > John, this is the actual code I ran in TurboGears which is a Python > framework. It's not complete -- the change in indentation would have caused a SyntaxError. If (as you appear to assert) the problem is in the csv module, then create a small stand-alone no-TurboGears Python script and a test file which together demonstrate the problem reproducibly so that the problem can investigated by anyone with a standard TurboGears-free Python installation. If you can't reproduce the problem in that manner, then you may need to seek assistance in a TurboGears-specific forum. > I should have left away the import statements. Trust me, the problem > isn't in there because the UnicodeWriter is functioning perfectly. Do you mean that this file was created by whatever.UnicodeWriter? If so, did you just now discover this information? How do you know that "the UnicodeWriter is functioning perfectly"? What does "functioning perfectly mean to you"? In particular, what encoding is it using? > I did allready sanitate the csv file to these four lines in Notepad so > there isn't anything more than this: > > id;company;department > 12;Cadillac;Research > 11;Ford;Accounting > 10;Chrysler;Sales Which do you mean: (a) you typed those lines into Notepad yourself (b) you took a copy of a file created by whatever.UnicodeWriter, opened it with Notepad, trimmed off some rows and columns, and saved it again ? You said earlier """ csv.reader results in: for r in reader: Error: line contains NULL byte Use of UnicodeReader results in: UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: unexpected code byte """ Those results are consistent with your file being encoded in utf16_le, with the utf16_le BOM ('\xff\xfe') at the start of the file. Have you, as I asked, looked at the file with some better-than-Notepad diagnostic apparatus? Here's a likely hypothesis: the file was written in utf16. In that case: either (i) you really want utf16 (why?), so: (1) the csv module will not cope with it, and is not expected to cope with it (2) the whatever.UnicodeReader should (in order of preference): (a) be allowed to find out for itself that 'utf16' is the go (b) be told explicitly that 'utf16' is the go (c) be served with a bug report OR (ii) you really want utf8, so: (1) the csv module should be happy (2) the whatever.UnicodeWriter should be told to use 'utf8' (3) the whatever.UnicodeReader should (in order of preference): [as above but s/16/8/] HTH, John From noone at lewscanon.com Wed Dec 3 20:38:44 2008 From: noone at lewscanon.com (Lew) Date: Wed, 03 Dec 2008 20:38:44 -0500 Subject: Mathematica 7 compares to other languages In-Reply-To: <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> Message-ID: Xah Lee wrote: > enough babble ... Good point. Plonk. Guun dun! -- Lew From jeremiah.dodds at gmail.com Thu Dec 25 07:35:39 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Thu, 25 Dec 2008 07:35:39 -0500 Subject: Is there a function to remove escape characters from a string ? In-Reply-To: <%CK4l.11459$c45.7073@nlpi065.nbdc.sbc.com> References: <%CK4l.11459$c45.7073@nlpi065.nbdc.sbc.com> Message-ID: <12cbbbfc0812250435u19d3d7ffo5afd2e73ea80ca83@mail.gmail.com> On Thu, Dec 25, 2008 at 7:02 AM, James Stroud wrote: > Stef Mientki wrote: > >> hello, >> >> Is there a function to remove escape characters from a string ? >> (preferable all escape characters except "\n"). >> >> thanks, >> Stef >> > > > import string test = 'this\r is a test\t yeah\n' for c in string.printable[-5:]: if c != '\n': test = test.replace(c, ' ') Hmm, should the escape codes be in their own little list in string? Or are they, and I'm just not seeing them? Is string.printable[-5:] a reliable way to get the list of escape codes? -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Tue Dec 23 08:18:32 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 23 Dec 2008 13:18:32 +0000 (UTC) Subject: print to console without a line break References: Message-ID: On Tue, 23 Dec 2008 11:50:59 +0100, Qian Xu wrote: > Hello All, > > Is it possible to print something to console without a line break? > > I tried: > sys.stdout.write("Testing something ...") // nothing will be printed > time.sleep(1) > sys.stdout.write("done\n") // now, the whole string will be printed > > What I want, is to see "Testing something ..." first. And after 1 > second, to see "done" (with a line break) > > The only one solution I have found is to call "echo -n 'my_string'". But > it is not nice. Because I have to escape all special chars in the string > manually. > > Any advice? > Best regards > -- Qian Xu If you don't mind an extra space, you can use this: print 'Testing something ...', # note the trailing comma From bdesth.quelquechose at free.quelquepart.fr Sun Dec 28 12:15:23 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 28 Dec 2008 18:15:23 +0100 Subject: "return" in def In-Reply-To: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> Message-ID: <4957c1dc$0$24043$426a34cc@news.free.fr> Roger a ?crit : > > When I define a method I always include a return statement out of > habit even if I don't return anything explicitly: > > def something(): > # do something > return > > Is this pythonic or excessive? If it's the last statement in the function body, it is indeed "excessive". OTHO I sometimes end a function with an explicit "return None" when there are branches with early returns, ie: def func(): if some_condition: return something return None to make really clear what happens - even if it _should_ be clear without the last statement. IOW : use your own judgement. From mwilson at the-wire.com Tue Dec 9 16:17:09 2008 From: mwilson at the-wire.com (Mel) Date: Tue, 09 Dec 2008 16:17:09 -0500 Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> <1ddabaf6-c129-4395-8d81-738e67e6f3ca@q26g2000prq.googlegroups.com> Message-ID: Carl Banks wrote: >[ ... ] Do you want the human reader to have to have all kinds of > rules to memorize about when a symbol is an identifier and when it's a > syntactic element? Do you want people to have to learn when to escape > a symbol so that the parser treats it as an identifier instead of > syntax? Then again, Python programmers should be used to namespaces, and it shouldn't bother people that `open` means one thing, and `image.open` means something very different -- if you've imported image. Mel. From benjamin.kaplan at case.edu Sat Dec 13 23:40:10 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sat, 13 Dec 2008 23:40:10 -0500 Subject: 1 or 1/0 doesn't raise an exception In-Reply-To: References: <49446E39.6020807@tim.thechases.com> Message-ID: On Sat, Dec 13, 2008 at 10:49 PM, Daniel Fetchinson < fetchinson at googlemail.com> wrote: > >> Is it a feature that > >> > >> 1 or 1/0 > >> > >> returns 1 and doesn't raise a ZeroDivisionError? If so, what's the > >> rationale? > > > > Yes, it's a feature: > > > > http://en.wikipedia.org/wiki/Short-circuit_evaluation > > > > When you have "True or False", you know it's true by the time > > you've got the first piece, so there's no need to evaluate the > > 2nd piece. The opposite is helpful too: > > > > lst = [some list or an empty list] > > ... > > if lst and lst[0] == 42: > > > > This ensures that the "lst[0]" doesn't fail if lst is empty, > > because lst evaluating to false (an empty list) short-circuits > > preventing the evaluation of "lst[0]". > > Okay, it's clear, thanks. > > Let me just point out that unsuspecting people (like me) might rely on > the whole expression to be evaluated and rely on exceptions being > raised if needed. > > So from now on I will not do! If you want both expressions evaluated, you can use & and |, just like in C and Java (&& and || are used for short circuit evaluation in those languages). -------------- next part -------------- An HTML attachment was scrubbed... URL: From tmohr at s.netic.de Sun Dec 14 15:40:32 2008 From: tmohr at s.netic.de (Torsten Mohr) Date: Sun, 14 Dec 2008 21:40:32 +0100 Subject: package structure? References: Message-ID: >> I wonder how i can make AClass() known in that package. >> > > Why don't you put the contents of smod1.py in mod/smod1/__init__.py? > It'll work this way. Of course, thanks for that hint. Best regards, Torsten. From jeremiah.dodds at gmail.com Wed Dec 3 23:32:13 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Wed, 3 Dec 2008 23:32:13 -0500 Subject: RELEASED Python 3.0 final In-Reply-To: <1b9568f2-55a0-4f1e-886c-2675b16b58c9@g38g2000yqn.googlegroups.com> References: <1b9568f2-55a0-4f1e-886c-2675b16b58c9@g38g2000yqn.googlegroups.com> Message-ID: <12cbbbfc0812032032y3bcc0676k6831ca546fbed240@mail.gmail.com> thankers.append(self) -------------- next part -------------- An HTML attachment was scrubbed... URL: From jurgenex at hotmail.com Thu Dec 4 00:24:13 2008 From: jurgenex at hotmail.com (Jürgen Exner) Date: Wed, 03 Dec 2008 21:24:13 -0800 Subject: Mathematica 7 compares to other languages References: <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <4b6c3304-2396-4d35-a06f-e5d693cbbb12@f13g2000yqj.googlegroups.com> <20081219033030.559@gmail.com> Message-ID: Kaz Kylheku wrote: >On 2008-12-04, J?rgen Exner wrote: >> toby wrote: >>>On Dec 3, 4:15 pm, Xah Lee wrote: >>>> On Dec 3, 8:24 am, Jon Harrop wrote: >>>> >>>> > My example demonstrates several of Mathematica's fundamental limitations. >>>> >>>> enough babble Jon. >>>> >>>> Come flying $5 to my paypal account, and i'll give you real code, >>> >>>I'll give you $5 to go away >> >> if you add "and never come back" then count me in, too. > >Really? I will trade you one Xah Lee for three Jon Harrops and I will even >throw in a free William James. Well, I've never seen those names on CL.perl.M, so I don't know them. jue From steve at holdenweb.com Fri Dec 12 08:22:28 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Dec 2008 08:22:28 -0500 Subject: How to write binary data to file and socket In-Reply-To: References: Message-ID: Lee Soin wrote: > Hello, all! > I'm new to python. In Linux C programming, writing data to file and > socket share the same system call "write". But it seems that only data > of string type can be used for "write" and "send". So how to write > binary data to file and socket? > Assuming you are using Python 2.x, use the struct module to convert your data to a string, then write that. In Python 3.x you would use the bytes type. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From brfredericks at gmail.com Thu Dec 11 19:02:27 2008 From: brfredericks at gmail.com (bfrederi) Date: Thu, 11 Dec 2008 16:02:27 -0800 (PST) Subject: Dictionary as Keyword Arguments Message-ID: I was wondering if I had a dictionary of keywords and values like so: keyword_arg_dict = { 'attribute': 'stone', 'contents': 'cave people', 'path': '/path/to/cave', 'name': 'Ogg's Cave', } And I had a function that accepted keyword arguments like so: make_dwelling( attribute='stone', contents='cave people', path='/path/to/cave', name='Ogg's Cave', ) Is there any way I could use my keyword_arg_dict as my keyword args for the make_dwelling function, since I am not the creator of the make_dwelling function, and need to take that dictionary of key-value pairs and turn it into keyword-value arguments for the make_dwelling function? From stef.mientki at gmail.com Mon Dec 8 15:19:35 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 08 Dec 2008 21:19:35 +0100 Subject: how to get a beep, OS independent ? In-Reply-To: References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> <014c575a$0$20670$c3e8da3@news.astraweb.com> Message-ID: <493D8157.2030200@gmail.com> Joe Strout wrote: > On Dec 7, 2008, at 4:43 PM, Steven D'Aprano wrote: > >> Of course, if you're volunteering to write such a standard system beep >> for Python, I for one would be grateful. > > I am. But where should I put it? Assuming we don't want to wait for > the (understandably) lengthy and contentious process required to add > something to the Python system libraries, where would be the next best > place for this sort of simple OS abstraction layer? > Well I would love to try it, why not already attach it to this list ? cheers, Stef > Thanks, > - Joe > > -- > http://mail.python.org/mailman/listinfo/python-list From google at mrabarnett.plus.com Sun Dec 28 14:25:19 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 28 Dec 2008 19:25:19 +0000 Subject: "return" in def In-Reply-To: <40b1b762-459b-4d6f-91f0-0a6e68d233ae@a26g2000prf.googlegroups.com> References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <40b1b762-459b-4d6f-91f0-0a6e68d233ae@a26g2000prf.googlegroups.com> Message-ID: <4957D29F.7060008@mrabarnett.plus.com> Gerard Flanagan wrote: > On Dec 28, 5:19 pm, Roger wrote: >> Hi Everyone, > [...] >> When I define a method I always include a return statement out of >> habit even if I don't return anything explicitly: >> >> def something(): >> # do something >> return >> >> Is this pythonic or excessive? Is this an unnecessary affectation >> that only adds clock ticks to my app and would I be better off >> removing "returns" where nothing is returned or is it common practice >> to have returns. >> > > It's not particularly excessive but it is uncommon. A nekkid return > can sometimes be essential within a function body, so a non-essential > nekkid return could be considered just noise. > If it's a function, ie the result is used by the caller, then explicitly return with the value, even if it's None. On the other hand, if it's a procedure, ie the result is always None and that result isn't used by the caller, then don't use return, except for an early exit. From fetchinson at googlemail.com Wed Dec 3 22:47:10 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 3 Dec 2008 19:47:10 -0800 Subject: RELEASED Python 3.0 final In-Reply-To: References: Message-ID: > On behalf of the Python development team and the Python community, I > am happy to announce the release of Python 3.0 final. > > Python 3.0 (a.k.a. "Python 3000" or "Py3k") represents a major > milestone in Python's history, and was nearly three years in the > making. This is a new version of the language that is incompatible > with the 2.x line of releases, while remaining true to BDFL Guido van > Rossum's vision. Some things you will notice include: > > * Fixes to many old language warts > * Removal of long deprecated features and redundant syntax > * Improvements in, and a reorganization of, the standard library > * Changes to the details of how built-in objects like strings and > dicts work > * ...and many more new features > > While these changes were made without concern for backward > compatibility, Python 3.0 still remains very much "Pythonic". > > We are confident that Python 3.0 is of the same high quality as our > previous releases, such as the recently announced Python 2.6. We will > continue to support and develop both Python 3 and Python 2 for the > foreseeable future, and you can safely choose either version (or both) > to use in your projects. Which you choose depends on your own needs > and the availability of third-party packages that you depend on. Some > other things to consider: > > * Python 3 has a single Unicode string type; there are no more 8-bit > strings > * The C API has changed considerably in Python 3.0 and third-party > extension modules you rely on may not yet be ported > * Tools are available in both Python 2.6 and 3.0 to help you migrate > your code > * Python 2.6 is backward compatible with earlier Python 2.x releases > > We encourage you to participate in Python 3.0's development process by > joining its mailing list: > > http://mail.python.org/mailman/listinfo/python-3000 > > If you find things in Python 3.0 that are broken or incorrect, please > submit bug reports at: > > http://bugs.python.org/ > > For more information, links to documentation, and downloadable > distributions, see the Python 3.0 website: > > http://www.python.org/download/releases/3.0/ > > Enjoy, > - -Barry > > Barry Warsaw > barry at python.org > Python 2.6/3.0 Release Manager > (on behalf of the entire python-dev team) uname -a Linux fetch 2.6.23.1-42.fc8 #1 SMP Tue Oct 30 13:18:33 EDT 2007 x86_64 x86_64 x86_64 GNU/Linux tar xzvf Python-3.0.tgz cd Python-3.0 ./configure make Failed to find the necessary bits to build these modules: _tkinter To find the necessary bits, look in setup.py in detect_modules() for the module's name. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From benjamin.kaplan at case.edu Mon Dec 8 13:40:41 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 8 Dec 2008 13:40:41 -0500 Subject: Public imports In-Reply-To: <66ecdd96-38dd-4054-8009-e145c0a78316@o40g2000prn.googlegroups.com> References: <9623b0a3-7053-41f1-b116-0cd5e54f39e9@v13g2000vbb.googlegroups.com> <493d1ec0$0$32048$426a34cc@news.free.fr> <66ecdd96-38dd-4054-8009-e145c0a78316@o40g2000prn.googlegroups.com> Message-ID: On Mon, Dec 8, 2008 at 1:29 PM, M?rcio Faustino wrote: > So, no chance of doing this: > > # "A.py" > from __future__ import division, with_statement > > # "B.py" > from A import * > print 1 / 2 > > ...and printing 0.5, right? Too bad :) > Thanks! That would be a very bad idea. What if you did that and then someone else tried to use your module? However, future imports are a special case. This will work with any normal import. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Tue Dec 2 20:49:01 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 2 Dec 2008 17:49:01 -0800 (PST) Subject: problem with optparse References: Message-ID: <1e60b3d7-e564-4ea9-b4f6-8ccc2e3b6a1b@e1g2000pra.googlegroups.com> On Dec 3, 11:47 am, Neal Becker wrote: > Robert Kern wrote: > > Neal Becker wrote: > >> This example is right out of python library reference. What's wrong > >> here? > > >> import optparse > > >> def store_value(option, opt_str, value, parser): > >> setattr(parser.values, option.dest, value) > > >> parser = optparse.OptionParser() > >> parser.add_option("--foo", > >> action="callback", callback=store_value, > >> type="int", nargs=3, dest="foo") > > >> (opt,args) = parser.parse_args ('--foo a b c'.split()) > > >> [...] > >> /usr/lib64/python2.5/optparse.pyc in _process_args(self, largs, rargs, > >> values) > >> 1423 elif self.allow_interspersed_args: > >> 1424 largs.append(arg) > >> -> 1425 del rargs[0] > >> 1426 else: > >> 1427 return # stop now, leave this > >> arg in rargs > > >> TypeError: 'str' object doesn't support item deletion > > > Dunno. It works for me (i.e. I get the expected "error: option --foo: > > invalid integer value: 'a'"). Have you tried it outside of IPython? > > yes: > python test_opt.py > Traceback (most recent call last): > File "test_opt.py", line 12, in > (opt,args) = parser.parse_args ('--foo') > File "/usr/lib64/python2.5/optparse.py", line 1378, in parse_args > stop = self._process_args(largs, rargs, values) > File "/usr/lib64/python2.5/optparse.py", line 1425, in _process_args > del rargs[0] > TypeError: 'str' object doesn't support item deletion This is rather confusing: on my system the two source lines and numbers in the traceback correspond to the Python 2.6 source, but don't correspond to the Python 2.5 source. However, your path is .../ python2.5/... Unfortunately, although optparse has changed between 2.5 and 2.6, optparse.__version__ wasn't changed from "1.5.3" so it's no use asking you to print that. Working backwards from the error, it seems that by the time this is executed: stop = self._process_args(largs, rargs, values) rargs has become a string instead of a list of strings. Perhaps you would like to (1) check your optparse.py for corruption and (2) put some temporary print statements along the trail from your *** AARRGGHH!! *** '--foo' in your second message should be ['--foo'] so how come you got an error with '--foo a b c'.split() in your first message??? I'll try again: Perhaps you would like to (1) check your optparse.py for corruption and then (2) if you still have a problem, show us the contents of your test_opt.py and the results of running that at the command line. It would be nice if you included: import sys; print sys.version near the top of test_opt.py. HTH, John From digitig at gmail.com Fri Dec 12 14:04:54 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 12 Dec 2008 19:04:54 +0000 Subject: (Very Newbie) Problems defining a variable In-Reply-To: <878wqlz27z.fsf@daycos.com> References: <878wqlz27z.fsf@daycos.com> Message-ID: 2008/12/12 Kirk Strauser : > def get_rate(balance): > for threshold, rate in ((100000, .0173), > (50000, .0149), > (25000, .0124), > (10000, .0085), > (0, .006)): > if balance > threshold: > return rate > return .0 Yes, once it's changed from a dictionary to tuples it becomes easier, doesn't it? D'oh! -- Tim Rowe From geekmail at usenot.de Sun Dec 7 16:06:29 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sun, 7 Dec 2008 22:06:29 +0100 Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> Message-ID: <20081207220629.67f4cc17@usenot.de> On Sun, 07 Dec 2008 20:56:40 GMT I V wrote: > So, if we want Python to the programming language of choice for > Lacanian psychoanalysts, perhaps we should adopt the symbol "$" (or > even, with Python 3's support for unicode identifiers, S followed by > U+0388) instead of "self." OK, I'm sold. :) /W -- My real email address is constructed by swapping the domain with the recipient (local part). From jcd at sdf.lonestar.org Mon Dec 1 11:15:39 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 01 Dec 2008 11:15:39 -0500 Subject: Pyhon (with wxPython) on Windows' cygwin: can it be done fully ? In-Reply-To: <4a4fa55e-779c-47bd-a6bd-4829abaa4824@d42g2000prb.googlegroups.com> References: <6p2l98F61ttqU1@mid.uni-berlin.de> <4a4fa55e-779c-47bd-a6bd-4829abaa4824@d42g2000prb.googlegroups.com> Message-ID: <1228148139.32081.14.camel@aalcdl07.lib.unc.edu> On Sat, 2008-11-29 at 13:31 -0800, Lie wrote: > pdb and logging is too much for beginners, which most likely does not > yet understand the workings of the debugger and logger (and pdb's many > quirks). Don't forget that we're all beginners once. Python's learning > curve shouldn't raise with time, it should get lower so more people > can join in the board. >>> import logging >>> logging.basicConfig(level=logging.DEBUG) >>> >>> logging.debug("HERE!") DEBUG:root:HERE! >>> logging.debug("THERE!") DEBUG:root:THERE! >>> logging.info("abc") INFO:root:abc Ooh. Tough one. The only thing that's missing is to have this clearly documented in tutorials. (Maybe level 2, once you've learned the basics). And if that's too hard for you, you can still use print("HERE!"). But why sweat the "productivity loss" of the two parens when robust logging is really that easy, and can be turned on or off at one place? From brendandetracey at yahoo.com Tue Dec 16 09:28:00 2008 From: brendandetracey at yahoo.com (Brendan) Date: Tue, 16 Dec 2008 06:28:00 -0800 (PST) Subject: zipfile.is_zipfile() and string buffers Message-ID: <79196ccb-11fb-4a2d-9c2c-79801f108a05@f40g2000pri.googlegroups.com> I would like zipfile.is_zipfile(), to operate on a cStringIO.StringIO string buffer, but is seems only to accept file names as arguments. Should it not be able to handle string buffers too? From __peter__ at web.de Fri Dec 19 09:33:07 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2008 15:33:07 +0100 Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <494b5f47$0$17068$6e1ede2f@read.cnntp.org> <494b632b$0$17070$6e1ede2f@read.cnntp.org> Message-ID: Roger wrote: >> Note that I took out the lambdas and gave event arguments to the >> functions; if you did that on purpose, because you need to call the same >> functions without events, then just ignore that... >> SO, the other workaround, which I've used, is to bind the event to a >> generic function, and have that generic function conditionally call >> the functions you want. I'll go back and try to make an example from >> your example. -Chuckk > > Thanks Chuckk! You've done exactly what I did so far. I went through > the source in Tkinter.py and had an inkling of what the unbind > function was doing. I believe, and please correct me if I'm wrong, > in: self.tk.call('bind', self._w, sequence, '') , the '' is unbinding > all methods and I believe the self.deletecommand(funcid) is a > workaround for a memory leak otherwise. Perhaps self.tk.call('bind', > self._w, sequence, funcid) would work but that's a pure guess. I > would have liked to investigate the tcl source directly to see if I > could develop a workaround through a tk.call() but that was hitting a > wall in terms of any documentation I could research. I'm interested > in any workaround you may have however! The documentation for bind in tcl is here http://www.tcl.tk/man/tcl8.4/TkCmd/bind.htm and as far as I understand it doesnt support unbinding selected callbacks, either. I'd suggest a plain-python workaround along the lines of import Tkinter def test(event): print 'test' def test2(event): print 'test2' root = Tkinter.Tk() root.geometry("200x100+100+100") class Multiplexer: def __init__(self): self.funcs = [] def __call__(self, event): for f in self.funcs: f(event) def add(self, f): self.funcs.append(f) return f def remove(self, f): self.funcs.remove(f) m = Multiplexer() m.add(test) m.add(test2) root.bind("<1>", m) def unbind(): print "unbind" m.remove(test2) button = Tkinter.Button(root, text="unbind test2", command=unbind) button.pack() root.mainloop() Peter From rhodri at wildebst.demon.co.uk Tue Dec 16 19:36:56 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Wed, 17 Dec 2008 00:36:56 -0000 Subject: sorting for recursive folder rename In-Reply-To: References: Message-ID: On Tue, 16 Dec 2008 18:20:52 -0000, ianar? wrote: > Hello all, > > I trying to recursively rename folders and files, and am looking for > some ideas on the best way of doing this. The problem is that the > given list of items can be in order, and one to all items may be > renamed. Here is some preliminary code I have, but which does not work > very well. > self.toRename has the following structure : > [ > [original_name, new_name, os.path.isdir] > .. > ] [snip] import os for item in self.toRename: os.renames(item[0], item[1]) That's it. os.renames will take care of all the intermediate directory creation so you don't even need to sort the list. -- Rhodri James *-* Wildebeeste Herder to the Masses From roy at panix.com Mon Dec 15 22:18:13 2008 From: roy at panix.com (Roy Smith) Date: Mon, 15 Dec 2008 22:18:13 -0500 Subject: socket and subprocess problem References: <6d3291c3-4e12-4bdd-884a-21f15f38d105@a12g2000pro.googlegroups.com> Message-ID: In article <6d3291c3-4e12-4bdd-884a-21f15f38d105 at a12g2000pro.googlegroups.com>, goatold at gmail.com wrote: > In my python code I use subprocess.Popen to run and external program > who will listen to a TCP port. And I also create a socket to connect > to the TCP port that the external program is listening. > I will get 'Connection refused, errno=111' when I try to > socket.connect(). > Class a: > def run() > subprocess.Popen(..) > Class b: > def run(): > sock = socket.socket() > sock.connect(..) > ################################# > test.py > # socket connect will fail here > a.run() > b.run() > ################################### > test1.py > if __name__ = '__main__': > a.run() > > test2.py > # socket will connect fine > if __name__ = '__main__': > b.run Sounds like a timing problem. I assume that the process started by a.run() creates a socket and does a bind/listen/accept sequence on it. The problem is, there's nothing in your code which guarantees that this happens before b.run() executes the connect() call. The cheesy way to test this is to sleep for a second somewhere between a.run() and b.run(). See if that helps. If it doesn't, then it's possible the process started by a.run() isn't doing what it's supposed to do. Try running test1.py, and while it's running, run netstat to see if you've got something listening on the port you expect. From google at mrabarnett.plus.com Tue Dec 9 14:07:08 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 09 Dec 2008 19:07:08 +0000 Subject: StringIO in 2.6 and beyond In-Reply-To: References: Message-ID: <493EC1DC.8050708@mrabarnett.plus.com> Bill McClain wrote: > On 2008-12-09, Peter Otten <__peter__ at web.de> wrote: > >>>>> out = io.StringIO() >>>>> print(u"hello", file=out, end=u"\n") >>>>> out.getvalue() >> u'hello\n' > > That has the benefit of working. Thank you! > > That can't be the intended behavior of print(), can it? Insering non-unicode > spaces and line terminators? I thought all text was unicode now. Or is that > only in 3.0? > In Python 2.x unmarked string literals are bytestrings. In Python 3.x they're Unicode. The intention is to make the transition from 2.x to 3.x easier by adding some features of 3.x to 2.x, but without breaking backwards compatibility (not entirely successfully!). From tmh.public at gmail.com Wed Dec 3 19:22:21 2008 From: tmh.public at gmail.com (Thomas M. Hermann) Date: Wed, 3 Dec 2008 16:22:21 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> Message-ID: <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> On Dec 3, 5:26?pm, Xah Lee wrote: > Agreed. My paypal address is ?xah @@@ xahlee.org?. (replace the triple > @ to single one.) Once you paid thru paypal, you can post receit here > if you want to, or i'll surely acknowledge it here. > > Here's what i will do: > > I will give a version of Mathematica code that has the same behavior > as his. And i will give timing result. The code will run in > Mathematica version 4. (sorry, but that's what i have) As i > understand, Jon is running Mathematica 6. However, i don't see > anything that'd require Mathematica 6. If my code is not faster or in > other ways not satisfactory (by your judgement), or it turns out > Mathematica 6 is necessary, or any problem that might occure, i offer > money back guarantee. > > ? Xah > ?http://xahlee.org/ > > ? > Alright, I've sent $20. The only reason I would request a refund is if you don't do anything. As long as you improve the code as you've described and post the results, I'll be satisfied. If the improvements you've described don't result in better performance, that's OK. Good luck, Tom From lie.1296 at gmail.com Mon Dec 8 01:53:42 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 8 Dec 2008 06:53:42 +0000 (UTC) Subject: tabs and spaces in py3k References: <774909e2-b248-4251-bbba-deb309e72714@x38g2000yqj.googlegroups.com> Message-ID: On Sun, 07 Dec 2008 20:51:50 -0800, rurpy wrote: > Do the Py3k docs need correction? If I were the maintainer of the parser, I'd add something like this: tab_width = random.randint(0, 1000) From wyldwolf at gmail.com Wed Dec 24 19:01:11 2008 From: wyldwolf at gmail.com (Kevin Kelley) Date: Wed, 24 Dec 2008 18:01:11 -0600 Subject: Python's popularity In-Reply-To: References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: <77895c1d0812241601qd11437fpf5830d5201c4f9a6@mail.gmail.com> On Tue, Dec 23, 2008 at 10:38 AM, r wrote: > > School time son, > This forum is much more than a question answer session, son. Sure > people are welcome to ask a Python related question. But this forum is > really the main highway of Python development and future. If your a > n00b go to the "Python forum.org", you will feel more comfy over > there. > > >From python.org (http://www.python.org/community/lists/) - python-list: Pretty much anything Python-related is fair game for discussion, and the group is even fairly tolerant of off-topic digressions; there have been entertaining discussions of topics such as floating point, good software design, and other programming languages such as Lisp and Forth. *Most discussion on comp.lang.python is about developing with Python, not about development of the Python interpreter itself.* python-dev: Note: python-dev is for work on developing Python (fixing bugs and adding new features to Python itself); if you're having problems writing a Python program, please post to comp.lang.python. *python-dev is the heart of Python's development. Practically everyone with Subversion write privileges is on python-dev, and first drafts of PEPs are often posted here for initial review and rewriting before their more public appearance on python-announce.* I think you are confusing lists r. Kevin -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Sun Dec 14 16:53:31 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 14 Dec 2008 16:53:31 -0500 Subject: Optimizing methods away or not? In-Reply-To: <0154b041$0$6988$c3e8da3@news.astraweb.com> References: <0154b041$0$6988$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I have a class with a method meant to verify internal program logic (not > data supplied by the caller). Because it is time-consuming but optional, > I treat it as a complex assertion statement, and optimize it away if > __debug__ is false: > > class Parrot: > def __init__(self, *args): > print "Initialising instance..." > if __debug__: > self.verify() # check internal program state, not args > if __debug__: > def verify(self): > print "Verifying..." Given that verify is only called from within _init__, I would put everything within one 'if __debug__' statement. Either inline if __debug__: or if for some reason you really don't like that, nested if __debug__: def verify(): print "Verifying..." verify() tjr From cmgui2 at gmail.com Sat Dec 20 17:18:40 2008 From: cmgui2 at gmail.com (cm_gui) Date: Sat, 20 Dec 2008 14:18:40 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> Message-ID: <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> > Seriously cm_gui, you're a fool. > Python is not slow. > > --JamesMills haha, getting hostile? python fans sure are a nasty crowd. Python is SLOW. when i have the time, i will elaborate on this. From lance.ellinghaus at eds.com Mon Dec 22 20:57:52 2008 From: lance.ellinghaus at eds.com (Ellinghaus, Lance) Date: Mon, 22 Dec 2008 20:57:52 -0500 Subject: Python's popularity In-Reply-To: <19b9ab88-6812-4416-9020-3be16b839fcd@m16g2000vbp.googlegroups.com> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com><18767.47566.709705.92@montanaro-dyndns-org.local> <19b9ab88-6812-4416-9020-3be16b839fcd@m16g2000vbp.googlegroups.com> Message-ID: <752A61D5C34D41478E638FC92AF9051B03563591@usahm207.amer.corp.eds.com> > > Alvin ONeal wrote: > > > Also worthy of mention: > > > I've seen python pre-installed on consumer HP desktops (I think as > > > part of a backup/restore script, but I'm not sure) > > > > It's pre-installed on every Mac (both desktop and laptop), too. > I am using a Vista HP right now that came pre-installed with Python. > Blew my mind when i found out :). This single reason just reinforced > my belief in Python. Now if we can get Python on every windows > platform... Check out IronPython. Fully supported and FUNDED by Micro$oft! http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython Lance Ellinghaus From prologic at shortcircuit.net.au Mon Dec 29 20:43:10 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 30 Dec 2008 11:43:10 +1000 Subject: get method In-Reply-To: <4819de67-72dc-415c-b4c8-2353581c2bc7@r2g2000vbp.googlegroups.com> References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> <4819de67-72dc-415c-b4c8-2353581c2bc7@r2g2000vbp.googlegroups.com> Message-ID: On Tue, Dec 30, 2008 at 11:38 AM, Ross wrote: > I realize the code isn't counting, but how am I to do this without > using an if statement as the problem instructs? I just gave you a hint :) cheers James From ken.dambrosio at segway.com Wed Dec 3 09:44:37 2008 From: ken.dambrosio at segway.com (Ken D'Ambrosio) Date: Wed, 3 Dec 2008 09:44:37 -0500 (EST) Subject: Good introductory book? Message-ID: <45131.66.155.201.114.1228315477.squirrel@webmail.jots.org> Hi, all. I'm getting ready to do some projects in Python, and I've cut my teeth a little bit, but I've found the "Learning|Programming Python" books from O'Reilly to be more-or-less useless (to my surprise -- I'm usually an O'Reilly fan). I really, really like "Python Essential Reference", but it's -- well, more of a reference than an intro. So, an introductory text that actually assumes some previous programming experience (as opposed to "Learning Python" which must be the most slowly-paced programming book ever) would be terrific. Thanks for your suggestions! -Ken From lolekk1233 at wp.pl Tue Dec 9 10:27:59 2008 From: lolekk1233 at wp.pl (Sexy18) Date: Tue, 9 Dec 2008 07:27:59 -0800 (PST) Subject: Very Cute And Very Sexy Blonde Stripping Message-ID: <345b885a-691a-4ba6-a8ab-9d5326c6f954@v39g2000pro.googlegroups.com> http://yeba.pl/show/movies/5257/Perfect_babe_-_Idealna_kobieta From Brian.Kelly at uwsp.edu Tue Dec 30 13:05:27 2008 From: Brian.Kelly at uwsp.edu (Kelly, Brian) Date: Tue, 30 Dec 2008 12:05:27 -0600 Subject: python import sys.path Message-ID: I have both 2.4 and 2.5 interpreters installed on a linux box. The PythonPath is set to : PYTHONPATH=/usr/lib64/portage/pym:/prod/bacula/local/lib64/python2.4/site-pa ckages:/prod/bacula/local/lib/python2.4/site-packages My main script is getting called like so: python2.4 cleanup.py wrkstnbs The imports statements in cleanup.py are as follows: import os,sys print sys.path from datetime import datetime from optparse import OptionParser # used for parsing parameters from bacula_conf import * # used for connecting to our databases, etc. from registration_cleanup \ import RegistrationCleanup # used for interacting w/ registration db (sql1) # and configuration database (genunix) import directory_cleanup as fclean # file cleanup. One of the scripts being imported from bacula_conf is called purge_client.py. It has the following imports: import sys import MySQLdb Everytime I run "python2.4 cleanup.py wrkstnbs" I get the following error: Traceback (most recent call last): File "purge_client.py", line 22, in import MySQLdb File "/prod/bacula/local/lib64/python2.4/site-packages/MySQLdb/__init__.py", line 27, in import _mysql ImportError: /prod/bacula/local/lib64/python2.4/site-packages/_mysql.so: undefined symbol: Py_InitModule4 If I print sys.path of both the calling script and the imported module I get the following sys.path from cleanup.py: ['/prod/bacula/local/tools/bacula_conf/maintenance', '/usr/lib64/portage/pym', '/prod/bacula/local/lib64/python2.4/site-packages', '/prod/bacula/local/lib/python2.4/site-packages', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib64/python2.4/lib-dynload', '/usr/lib/portage/pym', '/usr/lib64/python2.4/site-packages', '/usr/lib/python2.4/site-packages'] However the sys.path printed by the called module purge_client.py displays as such: ['/prod/bacula/local/tools/bacula_conf/maintenance', '/usr/lib64/portage/pym', '/prod/bacula/local/lib64/python2.4/site-packages', '/prod/bacula/local/lib/python2.4/site-packages', '/usr/lib64/python25.zip', '/usr/lib64/python2.5', '/usr/lib64/python2.5/plat-linux2', '/usr/lib64/python2.5/lib-tk', '/usr/lib64/python2.5/lib-dynload', '/usr/lib64/python2.5/site-packages'] If I call purge_client.py like so: python2.4 purge_client.py wrkstnbs the sys.path is: ['/prod/bacula/local/tools/bacula_conf/maintenance', '/usr/lib64/portage/pym', '/prod/bacula/local/lib64/python2.4/site-packages', '/prod/bacula/local/lib/python2.4/site-packages', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib64/python2.4/lib-dynload', '/usr/lib/portage/pym', '/usr/lib64/python2.4/site-packages', '/usr/lib/python2.4/site-packages'] Can anyone explain why purge_client.py has a different sys.path when imported from another script? At this point I'm quite puzzled and would like to continue using the 2.4 interpreter for the time being. Thanks, Brian Kelly -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 5082 bytes Desc: not available URL: From philip at semanchuk.com Thu Dec 4 23:27:34 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Thu, 4 Dec 2008 23:27:34 -0500 Subject: Running a Python script from crontab In-Reply-To: <6a302e08-e8be-4d5e-b754-11fc18468cc8@v4g2000yqa.googlegroups.com> References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> <126ba84a-0ea0-4a91-b7d2-89ed650e5d6c@d32g2000yqe.googlegroups.com> <6a302e08-e8be-4d5e-b754-11fc18468cc8@v4g2000yqa.googlegroups.com> Message-ID: <22F6B5D9-74D4-4DA6-A46D-2A263CC6F662@semanchuk.com> On Dec 4, 2008, at 4:21 AM, Astley Le Jasper wrote: > On Dec 4, 12:34 am, Lawrence D'Oliveiro central.gen.new_zealand> wrote: >> In message , >> Philip >> >> Semanchuk wrote: >>> In my experience, the environment in which a cron job runs is >>> different from the environment in which some command line scripts >>> run... >> >> Which is true, but again, cron should report the environment in the >> mail >> message. For example, here are some headers from a recent run of the >> maildir backup task I have scheduled twice a day: >> >> Subject: Cron $HOME/bin/backupdir $HOME/.maildir >> X-Cron-Env: >> X-Cron-Env: >> X-Cron-Env: >> X-Cron-Env: >> X-Cron-Env: > > Where do you get the emails from? In my experience, this depends on the machine config. The machine *should* be set up to email the user when a cron job fails. You'll log in via terminal and get the message "You have new mail" which means something went wrong with your cron job. As Lawrence said, run mail in the terminal window and you'll have a message from cron. You might not be getting these mails for some reason. From skip at pobox.com Sat Dec 27 13:44:32 2008 From: skip at pobox.com (skip at pobox.com) Date: Sat, 27 Dec 2008 12:44:32 -0600 Subject: Test message - please ignore Message-ID: <18774.30608.479342.587934@montanaro-dyndns-org.local> Working on the spam filter. Please ignore... S From steve at holdenweb.com Tue Dec 23 10:20:59 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 23 Dec 2008 10:20:59 -0500 Subject: iterating initalizations In-Reply-To: <20081223092504.aaf25192.darcy@druid.net> References: <4eb386e5-18f7-4217-9a39-0bd996e8a9a3@m4g2000vbp.googlegroups.com> <82366062-d93e-4300-ab0a-986fb4e092b7@r13g2000vbp.googlegroups.com> <20081223092504.aaf25192.darcy@druid.net> Message-ID: D'Arcy J.M. Cain wrote: > On Mon, 22 Dec 2008 22:32:17 -0500 > Aaron Stepp wrote: >> Instead of writing a long list of initializations like so: >> >> A = [ ] >> B = [ ] >> ... >> Y = [ ] >> Z = [ ] >> >> I'd like to save space by more elegantly turning this into a loop. If > > Well, if all you want is a loop: > > for v in vars: > locals()[v] = [] > Note that this isn't guaranteed to work. While locals() will return a dict containing the names and values from the local namespace, you won't affect the local namespace by assigning values to the appropriate keys: >>> def f(): ... a = "hello" ... locals()["a"] = "goodbye" ... print a ... >>> f() hello >>> If you look at the function's code you will see that the local "a" is accessed using the LOAD_FAST and STORE_FAST opcodes, which take advantage of the knowledge that the name is local - the interpreter analyzed the function body looking for assignments to non-globals, and optimizes its treatment of such names. >>> dis.dis(f) 2 0 LOAD_CONST 1 ('hello') 3 STORE_FAST 0 (a) 3 6 LOAD_CONST 2 ('goodbye') 9 LOAD_GLOBAL 0 (locals) 12 CALL_FUNCTION 0 15 LOAD_CONST 3 ('a') 18 STORE_SUBSCR 4 19 LOAD_FAST 0 (a) 22 PRINT_ITEM 23 PRINT_NEWLINE 24 LOAD_CONST 0 (None) 27 RETURN_VALUE >>> > It's hard to tell if that's what you actually need though without > deeper analysis of your requirements. > I think it's unlikely that the OP really does need to create names dynamically, and should look at using either a dict indexed by the letters of self.__abet, or a list indexed from 0 to 24 instead. But you *are* correct about the need for a little more information ;-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From shaguf.m at gmail.com Wed Dec 24 02:35:52 2008 From: shaguf.m at gmail.com (Shaguf) Date: Tue, 23 Dec 2008 23:35:52 -0800 (PST) Subject: GIDS 2009 Java:: Save Big, Win Big, Learn Big: Act Before Dec 29 2008 Message-ID: <104a9b09-f1dc-4971-b8e1-7a24448835b0@f40g2000pri.googlegroups.com> ------------------------------------------------------------------- :::: Great Indian Developer Summit 2009 - GIDS.Java :::: :::: 24 April 2009 :::: :::: J N Tata Auditorium, IISc, Bangalore :::: :::: http://www.developersummit.com :::: ------------------------------------------------------------------- Dear Group members, The economic downturn will run out of steam trying to outdo the 'ready and waiting' software professional. Packed with premium knowledge, action plans and advise from been-there-done-it veterans, creators, and visionaries, the 2009 edition of Great Indian Developer Summit features focused sessions, case studies, workshops and power panels that will transform you into a force to reckon with. Java Speakers at the 2009 edition of GIDS include: Clemens Utschig- Utschig, Craig McClanahan, Debu Panda, Frank Nimphius, Howard Lewis Ship, Dr. Jim Webber, Jonas Jacobi, Mike Keith, Ola Bini, Prabhu Sunderraman, Thomas Marrs and Venkat Subramaniam. The conference this year has sessions on Guerrilla SOA, REST, Groovy, Building Web Services Using Spring, Struts 2.0 Deep Dive, Computing in the Cloud, Building RESTful Applications with JAX-RS, Tuning performance of JPA Applications, Diagnosing Production Java Applications, Building RESTful Applications with Ruby on Rails, Maven 2 at Work, Apache Utilities at Work, Web Services at Work, JRuby, Testing Java with Ruby, Tapestry 5 Inversion of Control, Clojure: Concurrent Functional Programming for the JVM, Unit testing, Apache Tapestry 5 and much more. Please have a look at http://www.developersummit.com/speakers.html for more info on the speakers and the sessions. Register before the 29th of December for Rs. 1,999/-. Besides the learning at the GIDS.Java conference on Friday, the 24th of April, this fee also includes: 1. Discount of 35% on the standard fee 2. Assured Gift - GIDS 2009 Cult T-shirt (upon receipt of payment on or before Jan 12 2009) 3. Entry into a lucky draw for the following gifts: Sony WEGA 29 inches (1), Mac Air Book (1), Wireless Mouse (50 nos), Apple iPOD 120 GB (5 nos). 4. Lunch and refreshments 5. Conference materials 6. Complimentary invitation to Cyrus Broacha's show at the Great Indian Developer Awards on Saturday, the 25th of April 2009 So hurry up and register now under the GIDS Loyalty discount scheme: http://www.developersummit.com/registration.html Wishing you and your family a Merry Christmas and a wonderful year ahead. Thanks, Shaguf http://www.developersummit.com/ info at developersummit.com From orsenthil at gmail.com Sat Dec 6 11:36:27 2008 From: orsenthil at gmail.com (Phoe6) Date: Sat, 6 Dec 2008 08:36:27 -0800 (PST) Subject: CVS Folders/Contents to Automatic Website - Program suggestions Message-ID: Hello all, I use cvs to maintain all my python snippets, notes, c, c++ code. As the hosting provider provides a public webserver also, I was thinking that I should convert the cvs folders automatically to website. 1) cvs2web is not what i mean. 2) doxygen may not be suitable. I tried with rest2web, it is requires that I write /restweb headers and files to be .txt files. An approach I have thought is: 1) run source-hightlight and create .html pages for all the scripts. 2) now write a script to index those script .htmls and create webpage. 3) Create the website of those pages. before proceeding, I thought I shall discuss here, if the members have any suggestion. What do do, when you want to maintain your snippets and notes in cvs and also auto generate it into a good website. I like rest2web for notes. Thanks, Senthil From stepp.aaron at gmail.com Mon Dec 22 17:22:56 2008 From: stepp.aaron at gmail.com (Aaron Stepp) Date: Mon, 22 Dec 2008 17:22:56 -0500 Subject: iterating initalizations Message-ID: Hi all: I'm new to python and trying to save time and code by iterating through list initializations as well as the assignments. I have the following code: import random from rtcmix import * from chimes_source import * from rhythmblock import * from pitchblock import * indexrand = random.Random() indexrand.seed(2) rhythm = rhythmBlock() pitch = pitchBlock() class pitchAndRhythm: def __init__self: self.__abet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def listCreate(self, num): if num > 25: print "Oops. This won't work" else: for a in range(num): b = indexrand.randint(0, 3) c = indexrand.randint(0, 7) index = self.__abet[a] index = [ ] index = index.append(rhythm.rhythmTwist(b, c)) This doesn't do what I expect (probably because I don't have a clue what I'm doing!): initalizing, then filling new arrays, each new one called A[ ], then B[ ], etc. This seems very un-pythonic, and I'm sure there is a right way to do it. I'm just lost! Thanks Aaron Stepp From schapman1974 at gmail.com Sun Dec 28 20:16:48 2008 From: schapman1974 at gmail.com (Stephen Chapman) Date: Sun, 28 Dec 2008 20:16:48 -0500 Subject: ZSI - ServiceContainer Message-ID: Does Anyone know how to Make the ServiceContainer work under SSL Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From antoinedg at gmail.com Mon Dec 15 11:32:00 2008 From: antoinedg at gmail.com (Antoine De Groote) Date: Mon, 15 Dec 2008 17:32:00 +0100 Subject: pylab.ylabel: put label on the other side Message-ID: Hey everybody, I'm plotting graphs with 2 y-axes, which I created using ax_left = pylab.subplot(111) ax_right = pylab.twinx() Then I switch the sides of the ticks: ax_left.yaxis.tick_right() ax_right.yaxis.tick_left() This works, the ticks are on the opposite sides (left axis ticks are on the right side and vice-versa). But, when I want to label the y-axes with for example pylab.axes(ax_left) pylab.ylabel('Some label') they are on the wrong side, i.e. not on the same side as the ticks of the corresponding y-axis. For this example, the label would be on the left side instead of the right side. This is giving me headaches for quite a few hours now, so maybe somebody knows a solution. Regards, antoine From lie.1296 at gmail.com Tue Dec 16 11:10:54 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 16 Dec 2008 16:10:54 +0000 (UTC) Subject: Generator slower than iterator? References: Message-ID: On Tue, 16 Dec 2008 12:07:14 -0300, Federico Moreira wrote: > Hi all, > > Im parsing a 4.1GB apache log to have stats about how many times an ip > request something from the server. > > The first design of the algorithm was > > for line in fileinput.input(sys.argv[1:]): > ip = line.split()[0] > if match_counter.has_key(ip): > match_counter[ip] += 1 > else: > match_counter[ip] = 1 nitpick: dict.has_key is usually replaced with if ip in match_counter: ... also, after investigating your code further, I see that you've unnecessarily used generators, the first code is simpler and you've not avoided any creation of huge intermediate list by using the generator this way. You won't get any performance improvement with this, and instead get a performance hit due to function overhead and name look up. From pavlovevidence at gmail.com Sat Dec 6 16:21:59 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 6 Dec 2008 13:21:59 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> Message-ID: On Dec 6, 9:12?am, "Russ P." wrote: > On Dec 6, 1:02?am, Antoine De Groote wrote: > > > > > Allowing "$" as a substitute for "self" wouldn't require this new syntax. > > > class C: > > ? ? def method($, arg): > > ? ? ? ? $.value = arg > > > I'm strongly against this. This looks ugly and reminds me of Perl and > > Ruby. (I don't have anything against these languages, but there's a > > reason I use Python). > > > Russ P. wrote: > > > On Dec 5, 6:21 pm, "Daniel Fetchinson" > > > wrote: > > >> Hi folks, > > > >> The story of the explicit self in method definitions has been > > >> discussed to death and we all know it will stay. However, Guido > > >> himself acknowledged that an alternative syntax makes perfect sense > > >> and having both (old and new) in a future version of python is a > > >> possibility since it maintains backward compatibility. The alternative > > >> syntax will be syntactic sugar for the old one. This blog post of his > > >> is what I'm talking about: > > > >>http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... > > > >> The proposal is to allow this: > > > >> class C: > > >> ? ? def self.method( arg ): > > >> ? ? ? ? self.value = arg > > >> ? ? ? ? return self.value > > > >> instead of this: > > > >> class C: > > >> ? ? def method( self, arg ): > > >> ? ? ? ? self.value = arg > > >> ? ? ? ? return self.value > > > >> I.e. explicit self stays only the syntax is slightly different and may > > >> seem attractive to some. As pointed out by Guido classmethods would > > >> work similarly: > > > >> class C: > > >> ? ? @classmethod > > >> ? ? def cls.method( arg ): > > >> ? ? ? ? cls.val = arg > > >> ? ? ? ? return cls.val > > > >> The fact that Guido says, > > > >> "Now, I'm not saying that I like this better than the status quo. But > > >> I like it a lot better than [...] but it has the great advantage that > > >> it is backward compatible, and can be evolved into a PEP with a > > >> reference implementation without too much effort." > > > >> shows that the proposal is viable. > > > >> I'd like this new way of defining methods, what do you guys think? > > >> Anyone ready for writing a PEP? > > > >> Cheers, > > >> Daniel > > > >> -- > > >> Psss, psss, put it down! -http://www.cafepress.com/putitdown > > > > I like it. > > > > I'll even go a step further and suggest that "$" be allowed as a > > > substitute for "self". It looks like a capital "S" (for Self), and it > > > stands out clearly. It also makes code more succinct with no loss of > > > readability. Think of the line wraps that could be avoided. > > It looks "ugly" simply because it is new to you. Once you get used to > it, I'll bet it will look fine. And resemblance to another language is > not a very good reason to reject it. Perl is not new to me and I am familiar with the syntax, such as it is. I find it unspeakably ugly. So, no, you would lose your bet if it were me. Carl Banks From Scott.Daniels at Acm.Org Tue Dec 16 17:19:32 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 16 Dec 2008 14:19:32 -0800 Subject: weird dict problem, how can this even happen? In-Reply-To: References: Message-ID: <88idnfej99XAtNXUnZ2dnUVZ_hednZ2d@pdx.net> Joel Hedlund wrote: > Duncan Booth wrote: >> I think you probably are correct. The only thing I can think that >> might help is if you can catch all the situations where changes to the >> dependent values might change the hash and wrap them up: before >> changing the hash pop the item out of the dict, then reinsert it after >> the change. > > That would probably require a lot of uncomfortable signal handling, > especially for a piece of functionality I'd like to be as unobtrusive as > possible in the application. > >> Alternatively give up on defining hash and __eq__ for FragmentInfo and >> rely on object identity instead. Perhaps your hash function could be something like: class HashedCache(dict): def __init__(self, dictionary): self.update(dictionary) self._hash = hash(tuple(sorted(dictionary.keys()))) def __hash__(self): return self._hash --Scott David Daniels Scott.Daniels at Acm.Org From stef.mientki at gmail.com Mon Dec 1 20:30:25 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 02 Dec 2008 02:30:25 +0100 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: <49348FB1.8080307@gmail.com> Jon Harrop wrote: > Xah Lee wrote: > >> And on this page, there are sections where Mathematica is compared to >> programing langs, such as C, C++, Java, and research langs Lisp, >> ML, ..., and scripting langs Python, Perl, Ruby... >> > > Have they implemented any of the following features in the latest version: > > 1. Redistributable standalone executables. > > 2. Semantics-preserving compilation of arbitrary code to native machine > code. > > 3. A concurrent run-time to make efficient parallelism easy. > > 4. Static type checking. > > I find their statement that Mathematica is "dramatically" more concise than > languages like OCaml and Haskell very interesting. I ported my ray tracer > language comparison to Mathematica: > > Mathematica (and MatLab) have a few large advantages over python / scipy / sage 1- although normally the cost a huge amount of money, students gets them (almost) for nothing (reminds me of a drug dealer ;-) 2- MatLab is th? industrial standard 3- Wolfram's and Mathworks websites are a huge source of (simple) theory and examples 4- a large number of publishers only accept articles based on commercial packages like MatLab / Labview 5- they form alliances if they come too close together ( e.g. MatLab and LabView) So how does a small community like the Python / Scipy / Sage community, which it's enormous diversity / induviduality (if I don't like one tiny detail, I'll start something completely new), ever think they are going to beat those commercial packages, even if the product, is technical speaking, much better ? Well I still have some hope, the recently published MatPlotLib documentation / galery is a good example. just my 1 cent (considering there's a recession), cheers, Stef From python.list at tim.thechases.com Mon Dec 1 10:46:43 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 01 Dec 2008 09:46:43 -0600 Subject: end of print = lower productivity ? In-Reply-To: <1228032887.6627.53.camel@lieryan-laptop> References: <757b4e03-7d13-4758-85c4-f5224ee9853b@j35g2000yqh.googlegroups.com> <21d250f9-1477-450e-9587-c4b28d08ea00@t3g2000yqa.googlegroups.com> <981d3e99-d2b4-4455-a52a-e906bd0fe7c4@r36g2000prf.googlegroups.com> <4931D571.8070007@tim.thechases.com> <1228032887.6627.53.camel@lieryan-laptop> Message-ID: <493406E3.6090304@tim.thechases.com> > For a proof, let's see what Google has to say about this: > "Windows text editor". Vim is on page 3, near the turning > point where nobody is talking about text-editor anymore and > more about text-editor reviews. Even worse is Emacs, on page > 6, after many other popular text-editors have been mentioned > several times. That's a pretty malformed "proof": http://www.google.com/search?q=people%20you%20should%20listen%20to%20regarding%20choice%20of%20text-editor You don't appear anywhere in the top *10* pages...QED ;-) However, if you want to play that game, vim.org appears on page #1 of http://www.google.com/search?q=best+text+editor Use what editor works for you -- but if evolution in the language's features makes difficulties for you but not for users of other editors, it's your editor that's the problem, not the language. Viva-la-print-function'ly yers, -tkc From amontfes at yahoo.es Mon Dec 15 16:31:39 2008 From: amontfes at yahoo.es (Antoni Mont) Date: Mon, 15 Dec 2008 22:31:39 +0100 Subject: Problem accessing a web page References: <47c890dc0812151216o59a3cbc2uf98d74604988d27@mail.gmail.com> <4946C45F.7060100@tim.thechases.com> Message-ID: Tim Chase wrote: > When you get the second page, are you getting the same content > back that you get if you do a search in your favorite browser? > > Using just > > content = urllib.urlopen(url2).read() > 'Error' in content # True > 'Friedrich' in content # False > > However, when you browse to the page, those two should be inverted: > > 'Error' in content # False > 'Friedrich' in content # True > > I've tried adding in the parameters correctly via post > > params = urllib.urlencode([ > ('params.forzaQuery', 'N'), > ... > ('layout', 'busquedaisbn'), > ]) > content = urllib.urlopen(url2, data).read() > > However, this too fails because the underlying engine expects a > session ID in the URL. I finally got it to work with the code below: > > import urllib > > data = [ > ('params.forzaQuery', 'N'), > ('params.cdispo', 'A'), > ('params.cisbnExt', '8484031128'), > ('params.liConceptosExt[0].texto', ''), > ('params.orderByFormId', '1'), > ('action', 'Buscar'), > ('language', 'es'), > ('prev_layout', 'busquedaisbn'), > ('layout', 'busquedaisbn'), > ] > > params = urllib.urlencode(data) > > url = > 'http://www.mcu.es/webISBN/tituloSimpleDispatch.do;jsessionid=5E8D9A11E4A28BDF0BA6B254D0118262' > > fp = urllib.urlopen(url, params) > content = fp.read() > fp.close() > > > but I had to hard-code the jsessionid parameter in the URL. This > would have to be determined from the initial call & response of > the initial URL (the initial URL returns a element with > the URL to POST to, including this magic jsessionid parameter). > > Hope this helps nudge you (the OP) in the right direction to get > what you're looking for. > > -tkc > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list OK, Tim, I think you got the point. The jsessionid change in every response of the initial URL, so I need to read it and stand with it during the session. Now I must guess how to do it. Thank you very much to you and also to Chris. Kind regards, Toni From martin at v.loewis.de Fri Dec 26 19:09:04 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 27 Dec 2008 01:09:04 +0100 Subject: Python 3 and my Mac (Leopard) In-Reply-To: <4952b38d$0$20300$607ed4bc@cv.net> References: <4952b38d$0$20300$607ed4bc@cv.net> Message-ID: <49557220$0$12632$9b622d9e@news.freenet.de> Dan wrote: > Is the python community just not interested in Macs? This is fairly close to the truth. The Mac port is currently mostly unmaintained, due to the past contributors having moved on or being occupied by other matters (such as Real Life). I would phrase it vice versa, though: the Mac community is not much interested in Python. Of course, Apple has a steady interest in Python, but that so far focuses on 2.x, is bound to Apple's product cycles, and did not went as far yet as assigning an Apple engineer to contribute to the Python core on a regular basis. To contribute in this area, you do need to deep understanding of OSX, so many Mac users are probably not qualified - and neither are most of the Python core contributors. Regards, Martin From robert.kern at gmail.com Tue Dec 2 18:17:03 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 02 Dec 2008 17:17:03 -0600 Subject: Hashlib py26 In-Reply-To: References: Message-ID: ShannonL at yogananda-srf.org wrote: > This feels a bit silly, but I am trying to encrypt some simple text with > the new hashlib library and then decrypt it back into text. I can do > this with M2Crypto RC4, but not the new hashlib. Could someone give me > a quick example. hashlib does not do encryption. It implements cryptographic hash functions which, while related to encryption algorithms and sometimes are a primitive component of such algorithms, do not actually encrypt and decrypt messages. http://en.wikipedia.org/wiki/Cryptographic_hash_function -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From pavlovevidence at gmail.com Mon Dec 29 16:47:51 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 29 Dec 2008 13:47:51 -0800 (PST) Subject: Python module import loop issue References: <02bc8567-695a-4277-9698-a95549a0bc98@w39g2000prb.googlegroups.com> Message-ID: <4a0557b7-e901-49ff-b4db-53f4d8a7c0f8@r40g2000yqj.googlegroups.com> On Dec 29, 10:51?am, Kottiyath wrote: > This might not be ?pure python question. Sorry about that. I couldnt > think of any other place to post the same. > I am creating a _medium_complex_ application, and I am facing issues > with creating the proper module structure. > This is my first application and since this is a run-of-the-mill > application, I hope someone would be able to help me. > > Base Module: > Contains definitions for Class A1, Class A2 > > Module 1.1: > Class B1 (refines A1) > Module 1.2: > Class C1 (refines A1) > Module 1.3: > Class D1 (refines A1) > > Module 2.1: > Class B2 (refines A2): > ? ? ? ? Uses objects of B1, C1, D1 > Module 2.2: > Class C2 (refines A2) > Module 2.3: > Class D2 (refines A2) > > -->Python Entry Module : Module EN<-- > Calls objects of B1, C1 and D1 > > Module EN and also Module 2 creates and calls the objects during run > time - and so calls cannot be hardcoded. > So, I want to use Factory methods to create everything. > > Module Factory: > import 1.1,1.2,1.3, ?2.1,2.2,2.3 > A1Factory: {'B1Tag':1.1.B1, 'C1Tag':1.2.C1, 'D1Tag':1.3.D1'} > A2Factory: {'B2Tag':2.1.B2, 'C2Tag':2.2.C2, 'D2Tag':2.3.D2'} > > But, since Module requires objects of B1, C1 etc, it has to import > Factory. > Module 2.1: > import Factory. > > Now, there is a import loop. How can we avoid this loop? > > The following ways I could think of > 1. Automatic updation of factory inside superclass whenever a subclass > is created. But, since there is no object created, ?I cannot think of > a way of doing this. I'm going to suggest three ways: a straightforward, good-enough way; a powerful, intelligent, badass way; and a sneaky way. 1. The straightforward, good-enough way Define functions in Factory.py called register_A1_subclass and register_A2_subclass, then call them whenever you create a new subclass. Factory.py ----------------------------- A1Factory = {} A2Factory = {} def register_A1_subclass(tag,cls): A1Factory[tag] = cls def register_A2_subclass(tag,cls): A2Factory[tag] = cls ----------------------------- package1/module1.py: ----------------------------- import Factory class B1(A1): # define class B1 here Factory.register_A1_subclass("B1Tag",B1) ----------------------------- So after you define B1, call Factory.register_A1_subclass to add it to the A1Factory. Factory.py no longer has to import package1.module2, so the circular import is broken, at the paltry price of having to add a boilerplate function call after every class definition. 2. The powerful, intelligent, badass way Metaclasses. I would guess you do not want to do this, and I wouldn't recommend it if you haven't studied up on how metaclasses work, but it's a textbook example of their usefulness. If you expect to use factory functions like this a lot, it might be worth your while to learn them. Anyway, here's a simple example to illustrate. It doesn't meet your requirements since all classes use the same factory; updating it to your needs is left as an exercise. Factory.py: ----------------------------- Factory = {} class FactoryMetaclass(type): def __new__(metaclass,name,bases,dct): cls = type.__new__(metaclass,name,bases,dct) tag = dct.get("tag") if tag is not None: Factory[tag] = cls return cls ------------------------------ Base.py: ------------------------------ import Factory class A2(object): __metaclass__ = FactoryMetaclass # define rest of A2 ------------------------------ package1/module2.py: ------------------------------ class B2(A2): tag = "B2Tag" #define rest of B2 ------------------------------ When the class B2 statement is executed, Python notes that the metaclass for A2 was set to FactoryMetaclass (subclasses inherit the metaclass), so it calls FactoryMetaclass's __new__ method to create the class object. The __new__ method checks to see if the class defines a "tag" attribute, and if so, adds the class to the Factory with that tag. Voila. (As a footnote, I will mention that I've created a library, Dice3DS, that uses metaclass programming in exactly this way.) 3. The sneaky way New-style classes maintain a list of all their subclasses, which you can retrieve by calling the __subclassess__ class method. You could use this to define a factory function that searches through this list for the appropriate subclass. Factory.py: ----------------------------- def _create_subclass(basecls,name): for cls in basecls.__subclasses__(): if cls.__name__ == name: return cls() cls2 = _create_subclass(cls,name) if cls2 is not None: return cls2() return None def create_A1_subclass(name): cls = _create_subclass(A1,name) if cls is None: raise ValueError("no subclass of A1 by that name") return cls ----------------------------- So here you search through A1's subclasses for a class matching the class's name. Note that we do it recursively, in case B1 (for instance) has its own subclasses, and I presume we do want those. You can change it to do a search by a tag class attribute if you wish; left as an exercise. > 2. Update A1Factory in each module which implements refinements. > _Very_important_, how do I make sure each module is hit - so that the > factory is updated? The module EN will be looking only at base module, > so the other modules is not hit. I will have to import every module in > EN - just to make sure that the A1Factory updation code is hit. This > looks in-elegent. Not worth it. The straightforward, good-enough way above is good enough. Carl Banks From digisatori at gmail.com Fri Dec 19 07:05:12 2008 From: digisatori at gmail.com (digisatori at gmail.com) Date: Fri, 19 Dec 2008 04:05:12 -0800 (PST) Subject: encoding problem Message-ID: <85e9957b-ed0a-4983-8427-46ab520c4a4a@s9g2000prm.googlegroups.com> The below snippet code generates UnicodeDecodeError. #!/usr/bin/env python #--*-- coding: utf-8 --*-- s = '???' u = unicode(s) It seems that the system use the default encoding- ASCII to decode the utf8 encoded string literal, and thus generates the error. The question is why the Python interpreter use the default encoding instead of "utf-8", which I explicitly declared in the source. From joe at strout.net Tue Dec 16 12:54:38 2008 From: joe at strout.net (Joe Strout) Date: Tue, 16 Dec 2008 10:54:38 -0700 Subject: AIM client code for Python? Message-ID: <732D7AE5-1429-4482-82FA-78328D6C3CF5@strout.net> I'd like to write an AIM bot in Python. I found and tried , but it doesn't work for me: Connecting... Traceback (most recent call last): File "aimbot-1.py", line 17, in bot.go() File "/Users/jstrout/Documents/Python-Dev/AIMbot/toc.py", line 62, in go self.process_loop() File "/Users/jstrout/Documents/Python-Dev/AIMbot/toc.py", line 156, in process_loop event = self.recv_event() File "/Users/jstrout/Documents/Python-Dev/AIMbot/toc.py", line 230, in recv_event dtemp = self._socket.recv(buflen - len(data)) socket.error: (54, 'Connection reset by peer') I wrote to the author a week ago, but never got a reply. It could be as simple as changing the server addresses in toc.py, currently: TOC_SERV_AUTH = ("login.oscar.aol.com", 29999 ) TOC_SERV = ( "toc.oscar.aol.com", 9898 ) ...but I don't understand AIM well enough to know the correct values (and was rather hoping that I wouldn't have to). Does anyone know how to get Py-TOC to work, or have another Python TOC implementation to suggest? Thanks, - Joe From walterbyrd at iname.com Mon Dec 22 14:27:15 2008 From: walterbyrd at iname.com (walterbyrd) Date: Mon, 22 Dec 2008 11:27:15 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> Message-ID: <649f7890-315c-4711-990b-5ec7e5cd5a3b@i20g2000prf.googlegroups.com> On Dec 22, 11:42?am, "Ellinghaus, Lance" wrote: > Yes, Ruby has taken some of the popularity out of Python, but they are > also hitting different markets. Do you mean different markets within web development, or do you mean ruby is used mostly for web-dev, while python is used for other stuff? From google at mrabarnett.plus.com Thu Dec 18 09:19:15 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 18 Dec 2008 14:19:15 +0000 Subject: C API and memory allocation In-Reply-To: <494a55fb$0$31873$9b4e6d93@newsspool3.arcor-online.net> References: <59352942-e976-4ef4-bc40-c8953df0a792@c36g2000prc.googlegroups.com> <0d35b640-71ad-4cde-8869-74878b2f3981@r36g2000prf.googlegroups.com> <494a55fb$0$31873$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <494A5BE3.2090505@mrabarnett.plus.com> Stefan Behnel wrote: > Aaron Brady wrote: >> I see. Do I read correctly that 's' is only useful when the >> argument's position is known? > > I assume you meant "length". > > >> Otherwise you can't know its length or >> change its reference count. > > The internal representation of Python byte strings is 0 terminated, so > strlen() will work. > But remember that a bytestring can contain a zero byte (chr(0) in Python 2.x). From google at mrabarnett.plus.com Sat Dec 6 21:26:40 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 07 Dec 2008 02:26:40 +0000 Subject: Learning Python now coming from Perl In-Reply-To: References: Message-ID: <493B3460.90308@mrabarnett.plus.com> Bertilo Wennergren wrote: > Aahz wrote: > >> In article , > >> Bertilo Wennergren wrote: > >>> I don't suppose there is any introductory material out there that is >>> based on Python 3000 and that is also geared at people with a Perl >>> background? Too early for that I guess.. > >> Honestly, the differences between 2.x and 3.0 are small enough that it >> doesn't much matter, as long as you're not the kind of person who gets >> put off by little problems. Because so much material is for 2.x, you >> may be better off just learning 2.x first and then moving to 3.x. > > The main reason I waited until Python 3000 came out is > the new way Unicode is handled. The old way seemed really > broken to me. Much of what I do when I program consists > of juggling Unicode text (real Unicode text with lots of > actual characters outside of Latin 1). So in my case > learning version 2.x first might not be very convenient. > I'd just get bogged down with the strange way 2.x handles > such data. I'd rather skip that completely and just go > with the Unicode handling in 3.0. > I wouldn't have said it was broken, it's just that it was a later addition to the language and backwards compatibility is important. Tidying things which would break backwards compatibility in a big way was deliberately left to a major version, Python 3. From digitig at gmail.com Thu Dec 4 10:48:24 2008 From: digitig at gmail.com (Tim Rowe) Date: Thu, 4 Dec 2008 15:48:24 +0000 Subject: Python advocacy ... HELP! In-Reply-To: <5f8c1a52-545e-402e-863a-acdf23d04c78@h20g2000yqn.googlegroups.com> References: <5f8c1a52-545e-402e-863a-acdf23d04c78@h20g2000yqn.googlegroups.com> Message-ID: 2008/12/4 Michael_D_G : > > I am a faculty member of a cs department. We currently teach C++ in > our intro to programming course. I am teaching this class and it seems > to me that we would be much better served teaching python in the intro > course, C++ for Data structures, as we do now, and Java in object > oriented programming, as we do now. > Some of my colleagues agree with me but some still see python as a > niche language and don't understand > how we could teach anything beyond C, C++ or Java. Try asking "Are we teaching computer science, so that the students will be able to cope with whatever they meet once they graduate, or are we teaching computer programming, in a couple of specific languages, so that the students will be completely unprepared if they meet anything else?" -- Tim Rowe From harrrrpo at gmail.com Thu Dec 18 14:34:01 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Thu, 18 Dec 2008 21:34:01 +0200 Subject: Location HTTP Header In-Reply-To: <5f4d3006-0750-4faa-ae1b-3a0408abbe2a@g1g2000pra.googlegroups.com> References: <68fa1e9b-6652-4d34-a7fe-fc98db8bf6d4@m16g2000vbp.googlegroups.com> <5f4d3006-0750-4faa-ae1b-3a0408abbe2a@g1g2000pra.googlegroups.com> Message-ID: <538050a90812181134i12461daal31647521ccb7674b@mail.gmail.com> use LiveHTTPHeaders with firefox and show us browser-server interaction -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Dec 24 02:46:04 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2008 05:46:04 -0200 Subject: Strategy for determing difference between 2 very large dictionaries References: <1230102996.2303.1291616055@webmail.messagingengine.com> Message-ID: En Wed, 24 Dec 2008 05:16:36 -0200, escribi?: > I'm looking for suggestions on the best ('Pythonic') way to > determine the difference between 2 very large dictionaries > containing simple key/value pairs. > By difference, I mean a list of keys that are present in the > first dictionary, but not the second. And vice versa. And a list > of keys in common between the 2 dictionaries whose values are > different. > The 2 strategies I'm considering are: > 1. Brute force: Iterate through first dictionary's keys and > determine which keys it has that are missing from the second > dictionary. If keys match, then verify that the 2 dictionaries > have identical values for the same key. Repeat this process for > the second dictionary. > 2. Use sets: Create sets from each dictionary's list of keys and > use Python's set methods to generate a list of keys present in > one dictionary but not the other (for both dictionaries) as well > as a set of keys the 2 dictionaries have in common. I cannot think of any advantage of the first approach - so I'd use sets. k1 = set(dict1.iterkeys()) k2 = set(dict2.iterkeys()) k1 - k2 # keys in dict1 not in dict2 k2 - k1 # keys in dict2 not in dict1 k1 & k2 # keys in both > Using the set > of keys in common, compare values across dictionaries to > determine which keys have different values (can this last step be > done via a simple list comprehension?) Yes; but isn't a dict comprehension more adequate? [key: (dict1[key], dict2[key]) for key in common_keys if dict1[key]!=dict2[key]} (where common_keys=k1&k2 as above) -- Gabriel Genellina From steve at holdenweb.com Mon Dec 15 12:24:14 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 15 Dec 2008 12:24:14 -0500 Subject: regex problem .. In-Reply-To: <3b10c2060812150421y1c3e7da6ha1b72c736e2a20d4@mail.gmail.com> References: <3b10c2060812150421y1c3e7da6ha1b72c736e2a20d4@mail.gmail.com> Message-ID: Analog Kid wrote: > Hi All: > I am new to regular expressions in general, and not just re in python. > So, apologies if you find my question stupid :) I need some help with > forming a regex. Here is my scenario ... > I have strings coming in from a list, each of which I want to check > against a regular expression and see whether or not it "qualifies". By > that I mean I have a certain set of characters that are permissible and > if the string has characters which are not permissible, I need to flag > that string ... here is a snip ... > > flagged = list() > strs = ['HELLO', 'Hi%20There', '123123@#@'] > p = re.compile(r"""[^a-zA-Z0-9]""", re.UNICODE) > for s in strs: > if len(p.findall(s)) > 0: > flagged.append(s) > > print flagged > > my question is ... if I wanted to allow '%20' but not '%', how would my > current regex (r"""[^a-zA-Z0-9]""") be modified? > The essence of the approach is to observe that each element is a sequence of zero or more "character", where character is "either letter/digit or escape." So you would use a pattern like "([a-zA-Z0-9]|%[0-9a-f][0-9a-f])+" regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From BrooklineTom at gmail.com Thu Dec 11 12:26:11 2008 From: BrooklineTom at gmail.com (brooklineTom) Date: Thu, 11 Dec 2008 09:26:11 -0800 (PST) Subject: Deeper tracebacks? References: Message-ID: <81a32daf-e337-43b0-93d4-86a8f0317c6c@o40g2000prn.googlegroups.com> BINGO! Give that man a CIGAR! The specifics don't seem to be quite right (there is no sys.last_traceback), but R.Bernstein put me directly on the correct track. I misunderstood the traceback module documentation. OK, I just plain didn't read it correctly, it's right there ("extract_stack(): Extract the raw traceback from the current stack frame."). The answer is to use traceback.extract_tb (), called with sys.exc_info()[3] (the stackframe that raised the exception). Another sterling example of the benefits of reading the fine manual -- for comprehension this time. Instead of: aRawStack = traceback.extract_stack() do this: aRawStack = traceback.extract_tb(sys.exc_info()[2]) With this change, aRawStack contains the following: >>> aRawStack[0][3] 'answer = apply(aMethod, [], {})' >>> aRawStack[1][3] 'int(3).zork()' This is *exactly* what I was seeking. I appreciate all the responses, and especially appreciate the pointer from R.Bernstein. Thx, Tom On Dec 11, 4:49 am, ro... at panix.com (R. Bernstein) wrote: > brooklineTom writes: > > I want my exception handler to report the method that originally > > raised an exception, at the deepest level in the call-tree. Let give > > an example. > > > import sys, traceback > > class SomeClass: > > def error(self): > > """Raises an AttributeError exception.""" > > int(3).zork() > > > def perform_(self, aSelector): > > try: > > aMethod = getattr(self, aSelector, None) > > answer = apply(aMethod, [], {}) > > except: AttributeError, anAttributeErrorException: > > aRawStack = traceback.extract_stack() > > answer = None > > > When I call "perform_" (... SomeClass().perform_('error')), I want to > > collect and report the location *within the method ("error") that > > failed*. The above code reports the location of "perform_", and no > > deeper in the call tree. > > > Anybody know how to accomplish this? > > extract_stack() without any arguments is getting this from the > *current frame* which as you noted doesn't have the last exception > info included which has been popped; variable sys.last_traceback has the frames > at the time of the exception, I think. > > So in your code try changing: > aRawStack = traceback.extract_stack() > to > aRawStack = traceback.extract_stack(sys.last_traceback) From exarkun at divmod.com Tue Dec 16 15:36:50 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 16 Dec 2008 15:36:50 -0500 Subject: Can anyone suggest a good HTTP/1.1 web client? In-Reply-To: Message-ID: <20081216203650.20272.244726156.divmod.quotient.21919@ohm> On Tue, 16 Dec 2008 12:18:17 -0800 (PST), Kottiyath wrote: >Hi all, > I have to connect to a secure website every second to get the data >and then post to it. I have been investigating on many web clients in >python, but nothing fits the bill properly. > The ones I tried implementing are: > 1. httplib based - I created myself. (I cannot use urllib2 since I >have to transfer files, and urllib2 doesnt have multipart content-type >support) > 2. Twisted web client. > I also looked at mechanize etc too. > > The problems I face are - > 1. I liked twisted a lot, but when I implemented it, I found that >client support is there only for twisted.web and not twisted.web2. >Since I connect to the same website every time, I would like to have >persistent connections and since twisted.web is HTTP/1.0, persistent >connection support is not yet there. Without persistent connections, I >would have to have TCP connection handshake everytime and it is taking >too much time. I'm working on a new HTTP 1.1 client for Twisted. You can follow the progress at or check out the development branch and give it a try. Persistent connections are not yet implemented, but there's not a whole lot left to do to support them. That means pipelining isn't supported yet, but once persistent connections are supported pipelining will be simple. As with any Twisted protocol, it's just as easy to run over SSL as over TCP, so HTTPS is essentially supported for free. There is not yet support for proxies, but this is planned as well and should be only a little more work to implement. > [snip] > > Is there any good web client which I can use straight up? Or would >I have to implement the whole thing myself? It looks like a big beast >and I was wondering whether python provides it straight up. If you'd like to help out with the new Twisted HTTP client, that would be wonderful. Even if you can just try it out and report any problems you run into, that would be immensely helpful. Jean-Paul From andreas.roehler at online.de Thu Dec 11 08:31:18 2008 From: andreas.roehler at online.de (Andreas =?UTF-8?B?UsO2aGxlcg==?=) Date: Thu, 11 Dec 2008 14:31:18 +0100 Subject: looking up function's doc in emacs References: Message-ID: Xah Lee wrote: > in programing elisp in emacs, i can press ?Ctrl+h f? to lookup the doc > for the function under cursor. > > is there such facility when coding in perl, python, php? > > (i'm interested in particular python. In perl, i can work around with > ?perldoc -f functionName?, and in php it's php.net/functionName. Both > of which i have a elisp command with a shortcut that let me jump to > the doc) > > Thanks. > > Xah > ? http://xahlee.org/ > > ? python help(FUNCTIONNAME) From benjamin.kaplan at case.edu Fri Dec 26 19:41:39 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 26 Dec 2008 19:41:39 -0500 Subject: multiply each element of a list by a number In-Reply-To: References: Message-ID: On Fri, Dec 26, 2008 at 7:05 PM, wrote: > > What does *not* work is > 3 * [0,1,2] > As you know, this gives > [0,1,2,0,1,2,0,1,2] > What I am hoping for is > [0,3,6] > I see that I can use > numpy.multiply(3,range(3)) > but this seems overkill to me. Can you tell I am coming to Python from > Matlab? > > Thanks -- Rob you can do [i * 3 for i in range(3)] > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Wed Dec 31 03:52:09 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 31 Dec 2008 08:52:09 GMT Subject: Memory leak problem (while using tkinter) References: Message-ID: <6s0q5pF3oddcU1@mid.uni-berlin.de> On Tue, 30 Dec 2008 20:21:06 -0800, Andr? wrote: > I have written a small program (my first Tkinter-based app) to play > around the idea mentioned on > http://rogeralsing.com/2008/12/07/genetic-programming-evolution-of-mona- lisa/ > and, in doing so, have encountered a memory leak problem. I have seen > mentions on the web of using the delete() method of canvas to prevent > such problems - which I have tried to do with limited success. Below is > the code I wrote; to run it, you will need a small image file > (I used the one found on http://alteredqualia.com/visualization/evolve/) > that is saved under "mona_lisa.png". > > Any help would be greatly appreciated. I don't see anything obvious but that the program is too long and uses too much components to be sure that `Tkinter` is the culprit. Try too trim it down to the smallest possible program that still has the problem. Ciao, Marc 'BlackJack' Rintsch From castironpi at gmail.com Tue Dec 30 10:52:26 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 30 Dec 2008 07:52:26 -0800 (PST) Subject: why cannot assign to function call References: <495867C2.7080807@gmail.com> <5e807c67-7d97-4b8a-8c5f-a3b97f5c5003@i20g2000prf.googlegroups.com> Message-ID: <5fb29c80-a6a4-4cb4-aa62-0d2aeb437662@o4g2000pra.googlegroups.com> On Dec 30, 8:21?am, John O'Hagan wrote: > On Tue, 30 Dec 2008, Aaron Brady wrote: > > [...] > > > On a technicality, to avert a flaming, "change the value of 'b'" is an > > ambiguous phrase. There are two interpretations of "change what 'b' > > refers to" and "change what 'b' refers to". Even in spoken language, > > I don't think that emphasis can resolve them either. > > > One means, 'make a change in the world, in the actual configuration of > > such and such actual matter.' The other means, 'update the axioms the > > speaker is using to communicate to the listeners. (Such and such will > > no longer refer to such and such; it will refer to such and such; > > accept this and reject that.)' To make an observation, reference is a > > purely linguistic phenomenon. > > > I, for one, am at a loss for how to disambiguate it. I'm open to > > suggestions. > > I think you've already done so quite clearly. But I suspect the ambiguity > centres on the word "change" - in the first interpretation it means "alter" > (the object in place), in the second, it more precisely means "exchange" (one > object for another). > > I'd be interested to know to what extent this ambiguity exists in languages > other than English - as a somewhat relevant example, ambiguities in English > around the verb "to be" ("I am Fred", "I am tall", "I am hungry"; i.e., > identity vs. attributes vs. state) disappear in other languages which use > different verbs in each case. > > On a (philosophical) side-note, I wonder if this is a real ambiguity: while > the statement that the name "b" now refers to a different object is > clear-cut, the other interpretation, that the object itself has changed but > is somehow still the same object, is a bit of an ontological minefield. > > Fortunately, unlike the murky world of philosophy, Python (AIUI) simplifies > this question by simply declaring that yes, in the case of mutable objects, > we may say that we are still referring to the same object although we've > changed it, and no, in the case of immutable objects, we may not, and must > exchange it if we want a different "value" (a word too fraught with ambiguity > in this context to use unquoted!). > > The sometimes useful fuzziness of human languages means we don't need to ask, > for example, "how tall is the object currently referred to by the name > Fred?", but in Python, it helps to understand that this is what's going on. > > Regards, > > John There are a few problems going on here. (My ultimate goal is a unambiguous, non-arbitrary way to talk about Python; it's just that unambiguous and non-arbitrary are really tall orders.) One is the dependence (supervenience) of meaning on grammar (semantics on syntax, function on form). One is the absence of form in computing and math. Another is the composite identity. I think the problem goes deeper than just English. In any language that has a plural, the propositions in question come out as, 'one thing is two things' or 'two things are one thing'. According to some rules, these are ungrammatical sentences, due to plurality disagreement. Ex: The Morning Star is ... The Evening Star is ... *The Morning Star and The Evening Star is... *The Morning Star and The Evening Star are... Neither of the latter two is correct. (* marks ungrammatical.) As such, the listener isn't sure what meaning to take. Accepting that, I'll adopt the terms John proposed, 'change' vs. 'exchange', the former when the material configuration changes, the latter when the communication axioms change. b= [2, 3] b= [3, 4] 'b' has exchanged. (Somewhat ungrammatical.) b= [2, 3] b.append( 4 ) 'b' has changed. According to this, when you replace every floorboard on a porch, one at a time, it's still the same porch-- it's changed, it's different, and it's the same. However, if you haul off the porch and put a new one in its place, it's not. ('porch[:]=' vs. 'porch='.) You can't just look at the initial and final configurations of matter to determine so. Therefore, 'id' is an informal function. Identity isn't defined on math objects, only on Python objects; there is no notion of 'is' in math. It doesn't make sense to ask if '2 is 2', only if '2=2'. In Python, they are both defined, and not the same. Unfortunately, in the language involved, 'same' and 'different' aren't opposites, so the communication is horrendous and belabored. Lastly, equality is a tolerance concept on the computer, not in math. The computer looks at voltage thresholds in the underlying gates; the actual voltages, beyond a certain precision, of two representations of '0110' aren't the same. Further, the actual voltages of one representation of '0110' over time aren't equal either. However, that means, that in order to answer some questions about equality and identity, we have to address the implementation of the compiler. You might get the same answers in many or practically all implementations of Python, but the specification doesn't make the leap onto a real computer, where the equivalents of continuity of form are defined in an unspecified way. You could even have continuity of the contents of a byte (word)-- that is, they (the actual voltages on the individual wires of the word) don't change at all between times t0 and t1, but an identity test on it fails. Perhaps composite identity isn't a common source of problems for language speakers. P.S. Didn't say 'value'. From michele.simionato at gmail.com Tue Dec 16 01:23:33 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 15 Dec 2008 22:23:33 -0800 (PST) Subject: ethical questions about global variables References: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> Message-ID: On Dec 16, 3:45?am, "Giampaolo Rodola'" wrote: > Hi, > in a module of mine (ftpserver.py) I'd want to add a (boolean) global > variable named "use_gmt_times" to decide whether the server has to > return times in GMT or localtime but I'm not sure if it is a good idea > because of the "ethical" doubts I'm gonna write below. Global variables have a bad reputation, but they are not so bad in Python. Notice that: 1. global variables in Python are local to the module they are defined in; 2. class names and module names are usually global variables and nobody complains about that. 3. if you use an ALL_CAPS convention it is quite quite clear that you are using a global variable. Actually the ALL_CAPS convention is for constants, but sometimes I use it for configuration variables too, if they are set at the beginning and they are never changed during the running of the program. If you have more than a single global, it makes sense to introduce a configuration object, as others have said (this is how typically work) but if you have a single parameter the confuguration object is not worth the effort, IMO. M. Simionato From arkanes at gmail.com Thu Dec 4 11:44:33 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 4 Dec 2008 10:44:33 -0600 Subject: "as" keyword woes In-Reply-To: <0147e4df$0$20670$c3e8da3@news.astraweb.com> References: <7dudnSS7uIn_KarUnZ2dnUVZ_tTinZ2d@earthlink.com> <0147e4df$0$20670$c3e8da3@news.astraweb.com> Message-ID: <4866bea60812040844w1b6b143fpdaceaa64982fd970@mail.gmail.com> On Thu, Dec 4, 2008 at 8:45 AM, Steven D'Aprano wrote: > On Thu, 04 Dec 2008 20:53:38 +1000, James Mills wrote: > >> Readability of your code becomes very important especially if you're >> working with many developers over time. >> >> 1. Use sensible meaningful names. >> 2. Don't use abbreviations. > > This is excellent advice, but remember, what is a sensible meaningful > name is domain-specific. In a maths library, this would be sensible: > > def poly(x): > return 4*x**3 -2*x**2 +3*x -7 > > and this ridiculous: > > def poly(real_number): > return 4*real_number**3 -2*real_number**2 +3*real_number -7 > > I actually wonder. The former is "sensible" in a math context because there's a very long tradition in mathematics of using terse, inscrutable placeholders for terms. I'm not a mathematician and I don't know anything about the history of mathematical notation, but I'd guess this has something to do with the fact that maths has historically been done with a pencil and paper, and that terseness is an important quality when you have a limited canvas and lots of stuff to write. Aside from the cultural indoctrination, though (and that may be a real and strong force when dealing with math software, and I don't want to discount it in general, just for purposes of this discussion) why is it more sensible to use "x" here instead of "number" or "real" or "real_number" or something else? From onlinejob4ind at gmail.com Tue Dec 23 23:40:37 2008 From: onlinejob4ind at gmail.com (kela) Date: Tue, 23 Dec 2008 20:40:37 -0800 (PST) Subject: earn more then,15,989$/- Message-ID: <35e2d75e-d503-4a3a-99cc-0a7909a5b4ef@k1g2000prb.googlegroups.com> THE REAL ONLINE JOB from,USA. earn more then,15,989$/- per month,if you want more detail,on No investment. http://onlinejob4ind.homestead.com/ From psftw1 at gmail.com Sun Dec 14 17:09:07 2008 From: psftw1 at gmail.com (peter s.) Date: Sun, 14 Dec 2008 14:09:07 -0800 (PST) Subject: Building from source -- zlib/binascii problems 2.5.2/2.6.1 References: <71531b64-535f-49d0-a0c6-7704df83b251@f18g2000vbf.googlegroups.com> <49458079.1000304@v.loewis.de> <003b0307-c8df-489b-98e6-cfaa35d050a4@k1g2000prb.googlegroups.com> Message-ID: On Dec 14, 5:03?pm, "peter s." wrote: > On Dec 14, 4:54?pm, "Martin v. L?wis" wrote: > > > > > > Target: x86_64-redhat-linux > > > gcc -pthread -shared build/temp.linux-x86_64-2.5/location/of/ > > > Python-2.5.2/Modules/zlibmodule.o -L/usr/local/lib -lz -o build/ > > > lib.linux-x86_64-2.5/zlib.so > > > /usr/bin/ld: skipping incompatible /usr/lib/libz.so when searching for > > > -lz > > > Do > > > ? file /usr/lib/libz.so > > > It might be a 32-bit library, in which case you can check whether > > /usr/lib64 has a 64-bit library. I'm puzzled why it only > > happens for -lz; perhaps you are better of compiling with a 32-bit > > compiler. > > > Regards, > > Martin > > $ file /usr/lib/libz.s* > /usr/lib/libz.so: ? ? ? symbolic link to `libz.so.1.2.3' > /usr/lib/libz.so.1: ? ? symbolic link to `libz.so.1.2.3' > /usr/lib/libz.so.1.2.3: ELF 32-bit LSB shared object, Intel 80386, > version 1 (SYSV), stripped I meant to also add $ file /usr/lib64/libz.s* /usr/lib64/libz.so.1: symbolic link to `libz.so.1.2.3' /usr/lib64/libz.so.1.2.3: ELF 64-bit LSB shared object, AMD x86-64, version 1 (SYSV), stripped So.. it seems as though I need to get it to point to the 64 bit version (or compile the zlib that comes with Python source). I'm not sure how to override that. From ffbittencourt at gmail.com Fri Dec 5 10:37:45 2008 From: ffbittencourt at gmail.com (Fred) Date: Fri, 5 Dec 2008 12:37:45 -0300 Subject: No subject Message-ID: <4ed4cf0c0812050737o1d42c9e2j6e53223dcda73a3e@mail.gmail.com> -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at marcher.name Sat Dec 27 15:08:23 2008 From: martin at marcher.name (Martin) Date: Sat, 27 Dec 2008 21:08:23 +0100 Subject: [2.4.4] creating a datetime.datetime from an XML xs:dateTime Message-ID: <5fa6c12e0812271208x4baccaedk262e51becb6e2076@mail.gmail.com> Hi, subject says it all. I'd like to create a python datetime.datetime from an xs:string[1] I know about time.strptime and could get to a datetime.datetime from there, but that would be error prone like: * are there time zones? * how is the year represented * etc, yadda yadda so I'd rather like to find some method (hopefully within the standard lib) that had more peer review than only me :). thanks martin [1] http://www.w3.org/TR/xmlschema-2/#dateTime -- http://soup.alt.delete.co.at http://www.xing.com/profile/Martin_Marcher http://www.linkedin.com/in/martinmarcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From nemokingdom at gmail.com Fri Dec 26 08:07:30 2008 From: nemokingdom at gmail.com (nemo) Date: Fri, 26 Dec 2008 05:07:30 -0800 (PST) Subject: Process with ftplib Message-ID: Hi,all There seems something wrong when I use multiprocessing.Process with ftplib, My ftp class has a connection method like this: class qftp: def __init__(...): self.ftp = FTP() def connection(self): self.ftp.connect(self.addr, self.port) self.ftp.login(self.user, self.password) when i call the method like: ftp = qftp(host, port, user, password) ftp.connect() ftp.pwd() It works well but when I using the Process module, something seems wrong: ftp = qftp(host, port, user, password) p = multiprocessing.Process(target = ftp.connect) p.join() ftp.ftp.pwd() #after join, i think a connection has made, but it throws an exception This give me a 'NoneType object has no attribute sendall' exception. I wondered why? From gruszczy at gmail.com Fri Dec 12 08:08:04 2008 From: gruszczy at gmail.com (=?UTF-8?Q?Filip_Gruszczy=C5=84ski?=) Date: Fri, 12 Dec 2008 14:08:04 +0100 Subject: Removing None objects from a sequence In-Reply-To: <01524eee$0$20617$c3e8da3@news.astraweb.com> References: <01524eee$0$20617$c3e8da3@news.astraweb.com> Message-ID: <1be78d220812120508g55393212h2ae7d027a54a4d9e@mail.gmail.com> I am not doing it, because I need it. I can as well use "if not elem is None", but I just wanted to know, if there is some better way of doing this. I like to know :-) And I can't understand why you are becoming so aggressive because of this. Just because I asked for that, doesn't mean, that I will put some obfuscated code into my project. I just wanted to learn something new - I checked itertools, I googled a bit, now I wanted to ask here if someone knew some really cool way of this. All the other assumptions weren't really necessary. Thanks for those ideas, however. I like the last one a lot :) -- Filip Gruszczy?ski From geekmail at usenot.de Thu Dec 4 11:00:17 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Thu, 4 Dec 2008 17:00:17 +0100 Subject: Please fix your clock [was Re: Multiple equates] References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> <0147f4b7$0$20670$c3e8da3@news.astraweb.com> Message-ID: <20081204170017.4be41c7f@usenot.de> On 04 Dec 2008 15:53:21 GMT Steven D'Aprano wrote: > Hendrik, I think your PC's clock is wrong. You seem to be posting > from the future. So? Maybe he is. What's your problem? /W -- My real email address is constructed by swapping the domain with the recipient (local part). From timr at probo.com Tue Dec 30 23:51:06 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 31 Dec 2008 04:51:06 GMT Subject: parsing csv files class References: Message-ID: "alex goretoy" wrote: > >This line doesn't work for me. bufferp is empty afterwards. > >self.bufferp= [dict(zip(header,line)) for line in reader] > >needs to be this >self.bufferp= [dict(zip(header,line)) for line in self.buffer] Yes, when I was writing this, I started out eliminating self.buffer entirely. When I added it back in, I forgot to change this back. >I may need some assistance in another thread about a pycurl library. I want >it to fall back to urllib/urllib2 if pycurl is not installed module. look >for thread "pycurl urllib fallback" I will post it here shortly to >python-list. One common method is like this: try: import pycurl except ImportError: pycurl = None import urllib -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From steve at holdenweb.com Tue Dec 9 23:34:58 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 09 Dec 2008 23:34:58 -0500 Subject: Python & LEGO Mindstorm control... In-Reply-To: <000001c959d0$49b1f9c0$dd15ed40$@ch> References: <000001c959d0$49b1f9c0$dd15ed40$@ch> Message-ID: <493F46F2.9020702@holdenweb.com> feinepost at bluewin.ch wrote: > Hi Toni Meyer, > > > > I would be quite interested in your Python extension to send ir signals > to the rcx. > > > > I am quite new to this stuff, hope I?ll understand what you did? > > > > Could you send it to me? > > > > Thanks a lot! > Daniel: You do realize that you posted to a mailing list, not an individual, right? There's no evidence that "Toni Meyer" will see your message. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From dongzhi at gmail.com Wed Dec 10 00:40:08 2008 From: dongzhi at gmail.com (dongzhi) Date: Tue, 9 Dec 2008 21:40:08 -0800 (PST) Subject: List Problem Message-ID: Hi All, I have one problem for List. Like that: format='just "a" ""little"" test' part = format.split('"') print part the result is : ['just ', 'a', ' ', '', 'little', '', ' test'] the list part have 7 element. If I execute part[1], I have got 'a'. If I execute part[2], I have got ' '. But, if I execute part[1::2], I have got ['a', '', '']. I don't know why. Please tell me why. Thanks. Best Regards, Liu Ming From jeremiah.dodds at gmail.com Thu Dec 4 04:31:31 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Thu, 4 Dec 2008 04:31:31 -0500 Subject: Python advocacy ... HELP! In-Reply-To: <5f8c1a52-545e-402e-863a-acdf23d04c78@h20g2000yqn.googlegroups.com> References: <5f8c1a52-545e-402e-863a-acdf23d04c78@h20g2000yqn.googlegroups.com> Message-ID: <12cbbbfc0812040131t606d71c5n10a8c2090f20710f@mail.gmail.com> On Thu, Dec 4, 2008 at 1:52 AM, Michael_D_G wrote: > > I am a faculty member of a cs department. We currently teach C++ in > our intro to programming course. I am teaching this class and it seems > to me that we would be much better served teaching python in the intro > course, C++ for Data structures, as we do now, and Java in object > oriented programming, as we do now. > Some of my colleagues agree with me but some still see python as a > niche language and don't understand > how we could teach anything beyond C, C++ or Java. > > I have looked at several interesting academic papers, on doing just > this approach. I have also looked through the > python web page to get examples of industry players using python in a > non-trivial way. Yes, I know, Google, > Microsoft, Sun, CIA website running on Plone, NOAA, NASA. If anyone > has any recent articles, > or if anyone on the list is at a fortune 500 company, how do I refute > the notion that Python > is a "marginal" language because according to TOBIE it only less than > a 6% market share. > > -michael > -- > http://mail.python.org/mailman/listinfo/python-list > Well, I'm not in a fortune 500, but python _is_ currently paying my bills. There is a python job board, and a very active community around the language - I don't think it's hard to show that it's not a "niche" language anymore. Canonical, as well as Google, O'reilly, Sun, _and_ Microsoft are sponsors of the PSF. That's pretty much every major name in the software-development world right now. Niche languages aren't going to be getting that much support, from that many sources. Blender uses python. Bittorrent. Trac. Bazaar. Mercurial. But you know all this already. It seems to me that it shouldn't even matter if it _is_ a niche language though, considering that you're trying to convince people to use it as an "intro to programming" language. I would think that an introductory programming course in this day and age should be more about general concepts than language bits, and python is pretty good at staying out of your way - other than Scheme, I can't think of a better language to use to demonstrate the process of programming on a high level. Showing some code to your colleagues, in both C++ and python, and showing how the python code is close to being psuedo-code, and easier to understand would help, as well as showing the interpreter (or ipython), and how that could be very useful in class. It's intro to programming - the specific language should take a backseat to how easy it is to express ideas to the person with no programming experience in a clean manner, right? It seems to me that that's the point that your colleagues need to understand - being a good programmer (and, by association, being led down the path to being a good programmer) is more about understanding abstraction and how to break down a problem than what language is used, especially at the beginning. This was perhaps less true 10 years ago, when it was much more important to have a firm understanding of what's going on at a lower level to implement anything non-trivial, but these days there are plenty of useful things and learning that can be done with practically no knowledge of (for instance) machine architecture. I know the above wasn't exactly what you were asking for, but I hope it wasn't useless. -------------- next part -------------- An HTML attachment was scrubbed... URL: From renesd at gmail.com Mon Dec 8 05:19:32 2008 From: renesd at gmail.com (illume) Date: Mon, 8 Dec 2008 02:19:32 -0800 (PST) Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? References: <5ccd4a18-cd2b-4040-90c6-33723af15e96@b38g2000prf.googlegroups.com> <7e1a9226-c7a9-4b5e-bfbb-ea079639d6a2@t39g2000prh.googlegroups.com> <682de8aa-62b1-477a-8b31-ae7698b1ffe7@w1g2000prk.googlegroups.com> <4b2bcda5-cee2-484e-9fc7-47caaf7a165e@z27g2000prd.googlegroups.com> Message-ID: <6590e515-ef71-4441-baef-1847178bf1d0@g1g2000pra.googlegroups.com> On Dec 8, 8:59?pm, alex23 wrote: > On Dec 8, 7:18?pm, illume wrote: > > > It's easier to teach only requiring *using* classes, and functions > > than *creating* them. ?This is important if it's being used to teach > > programming - as you don't need to teach people two fairly large > > concepts before you can do anything. > > I'm just kind of aghast at the idea of "teaching" anyone how to > program games by using large, imperative chunks of code. I don't see > functions as being a "fairly large concept" at all, and utterly vital > to being able to write anything but the most basic 'hello world' > example code. > Yes, teaching hello world without requiring the creation classes is a *good thing*. Imagine having to create classes to make a hello world program? You'd have a typical java hello world program. This means you need to explain the concept of OO before they can do hello world. It's about teaching concepts separately, rather than requiring them to be taught all at once. If you don't need to use something, then why bother using it? Just for purity? Python has a long history of not making everything classes. So I see requiring the creation of classes to do 'hello world' as being un-pythonic and overly complex. I also see it getting in the way of seeing results, which is important when intially learning programming. > > Also python has very slow function calls, so avoiding using callbacks > > is also faster. > > Wouldn't it be better to teach people the basics of coding -before- > setting out to optimise their code? I was explaing the advantages of avoiding callbacks, and avoiding requiring the creation of classes. I think it's simpler, and faster to avoid callbacks. I was not saying that it's better to optimize peoples code before teaching people the basics of programming. From jstroud at mbi.ucla.edu Thu Dec 4 05:00:53 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 04 Dec 2008 02:00:53 -0800 Subject: Pythonic design patterns In-Reply-To: References: Message-ID: Slaunger wrote: > Hi comp.lang.python > I was therefore wondering if you could recommend a book or a resource > concerning design patterns with special focus on the possibilities in > Python? > > In that manner I may be able to both learn programming more pythonic > AND learn the design patterns. > > -- Slaunger Check the python cheat sheet for the most common idioms: http://rgruet.free.fr/PQR25/PQR2.5.html#Workspace. You should also check out http://effbot.org/zone/index.htm and peruse Fredrik Lundh's code. His blog is worth a look as well. He is a master of pythonic idioms and patterns. The cookbook has a lot of complex examples and may not provide you with the insight you are looking for. Only a small fraction of the recipes do this. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From dfnsonfsduifb at gmx.de Sat Dec 6 11:38:03 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Sat, 06 Dec 2008 17:38:03 +0100 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: <55d79070-0c11-4fb9-8cf5-b8cc7c54b5d2@v42g2000yqv.googlegroups.com> References: <55d79070-0c11-4fb9-8cf5-b8cc7c54b5d2@v42g2000yqv.googlegroups.com> Message-ID: info at orlans-amo.be schrieb: > 2 problems: endianness and trailing zer byte. > This works for me: This is very strange - when using "utf16", endianness should be detected automatically. When I simply truncate the trailing zero byte, I receive: Traceback (most recent call last): File "./modify.py", line 12, in a = AddressBook("2008_11_05_Handy_Backup.txt") File "./modify.py", line 7, in __init__ line = f.readline() File "/usr/local/lib/python3.0/io.py", line 1807, in readline while self._read_chunk(): File "/usr/local/lib/python3.0/io.py", line 1556, in _read_chunk self._set_decoded_chars(self._decoder.decode(input_chunk, eof)) File "/usr/local/lib/python3.0/io.py", line 1293, in decode output = self.decoder.decode(input, final=final) File "/usr/local/lib/python3.0/codecs.py", line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) File "/usr/local/lib/python3.0/encodings/utf_16.py", line 69, in _buffer_decode return self.decoder(input, self.errors, final) UnicodeDecodeError: 'utf16' codec can't decode byte 0x0a in position 0: truncated data But I suppose something *is* indeed weird because the file I uploaded and which did not yield the "truncated data" error ia 1559 bytes, which just cannot be. Regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From robert.kern at gmail.com Mon Dec 1 19:11:16 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 01 Dec 2008 18:11:16 -0600 Subject: optimization In-Reply-To: References: Message-ID: Neal Becker wrote: > Arnaud Delobelle wrote: > >> Neal Becker writes: >> >>> I noticed in some profiling, that it seems that: >>> >>> def Func (): >>> def something(): >>> ... >>> >>> It appears that if Func is called many times, this nested func >>> definition will cause significant overhead. Is this true? I guess >>> I've become accustomed to decent compilers performing reasonable >>> transformations and so have tended to write code for clarity. >> If something() can be defined outside Func(), how is it clearer to >> define it inside? > > If it's only used inside. I, for one, find that significantly less clear. I only expect functions to be defined inside of functions if they are going to use lexical scoping for some reason. If I read your code, I'd probably waste a good five minutes trying to figure out what part of the local scope you were using before I would conclude that you just did it because you thought it looked better. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From benjamin.kaplan at case.edu Fri Dec 12 13:11:39 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 12 Dec 2008 13:11:39 -0500 Subject: (Very Newbie) Problems defining a variable In-Reply-To: References: Message-ID: On Fri, Dec 12, 2008 at 12:50 PM, Dennis Lee Bieber wrote: > On Fri, 12 Dec 2008 03:42:55 -0800 (PST), febaen at gmail.com declaimed the > following in comp.lang.python: > > > #!/usr/bin/python > > #Py3k, UTF-8 > > > > bank = int(input("How much money is in your account?\n>>")) > > target = int(input("How much money would you like to earn each year? > > \n>>")) > > > Just for my curiosity -- did Python 3.x (besides turning print into > a function) also change input() to behave as the old raw_input()? > Yes. > > The above would be very discouraged in Python 2.x... in favor of ... > int(raw_input(...)) > > > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alexoplocatie at gmail.com Wed Dec 17 05:30:02 2008 From: alexoplocatie at gmail.com (aka) Date: Wed, 17 Dec 2008 02:30:02 -0800 (PST) Subject: help I'm getting delimited References: <1229445534.5328.0.camel@linux-3eb6.site> Message-ID: <2eaf2da1-6ce3-432d-9cca-80a6da797495@q37g2000vbn.googlegroups.com> Due to being in a hurry I didn't paste correctly so I lost the try clause (sorry). The intention is to parse a csv file and (ultimately) put values of column 1 ("id") in a list (so I need to append in the loop) that will be used to fill a session var. The complete code is: roles = [] inp = 'C:/temp/test.csv' try: fp = open(inp, 'rb') reader = csv.reader(fp, dialect='excel', delimiter=';') for r in reader: roles.append(r) ## ultimately should be something like r.id or r[0] except: msg = 'Something's wrong with the csv.reader' return dict(file=inp,roles=str(roles)) The roles list isn't populated at all :( From adi at lspl.net Sun Dec 7 23:39:13 2008 From: adi at lspl.net (sniffer) Date: Sun, 7 Dec 2008 20:39:13 -0800 (PST) Subject: infering the number of args a function takes at runtime Message-ID: hi all, i am a python newbie, in a project currently doing i need to find out the number of arguments that a function takes at runtime.? Is this possible ,if so how do i do this,i ve looked through the python documentation but couldnt find anything.any help will be great TIA From castironpi at gmail.com Thu Dec 11 15:52:37 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 11 Dec 2008 12:52:37 -0800 (PST) Subject: Problems running on HP Intel duo core machine References: <200809221443.25765.inq1ltd@inqvista.com> <200812051608.56335.inq1ltd@inqvista.com> Message-ID: On Dec 11, 1:58?pm, jim-on-linux wrote: > py help, > > I produced a program that runs on windows. > One client is using an HP machine with an Intel cpu > E2200 @ 2.2ghz., and with .99 G ram. > The machine is using Win XP Pro 32 bit OS with service > pack 2 > > I ran Dependency Walker and everything is OK. > > I used py2exe to build the exe file with bundle > files:1 and also 3, with the same traceback results. > > I created a test print module that imports both > win32api and win32ui modules and its only job is to > print a page of text. > > The first module that is imported is win32api. > line 8 of that module adds to the path the module named > 'win32api.pyd'. > The import is is completed without error. > > The next module that is imported is win32ui. > line 8 of that module adds to the path a module named > 'win32ui.pyd'. > The search for the win32ui.pyd module seems to be the > cause of the problem. ? > Traceback: > ImportError: Dll load failed: The specified module > could not be found. Is this your complete traceback? It is possible 'win32ui.pyd' is trying to load something else it can't find. From bdesth.quelquechose at free.quelquepart.fr Sun Dec 21 15:14:50 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 21 Dec 2008 21:14:50 +0100 Subject: Are Django/Turbogears too specific? In-Reply-To: References: Message-ID: <494eb16e$0$22710$426a74cc@news.free.fr> Philip Semanchuk a ?crit : (snip) > From the reading I did, I gathered that Django was really good if you > want to do what Django is good at, but not as easy to customize as, say, > Pylons. That was my first impression too, and was more or less true some years ago. After more experience, having gained a deeper knowledge of Django's internals, I can tell you this is just not true. You can "customize" it as you want - meaning: you can use any ORM (or no ORM at all) and any template language you want, as long as you don't intend to use django's ORM and template language related features (which just don't exist in Pylons). IOW : Django is just as flexible as Pylons (or pretty close to), but has more to offer if you stick to builtin components. NB : not to dismiss Pylons, which is a pretty great framework too, and use IMHO better default components (namely SQLAlchemy and Mako). From cournape at gmail.com Thu Dec 11 02:56:14 2008 From: cournape at gmail.com (David Cournapeau) Date: Thu, 11 Dec 2008 16:56:14 +0900 Subject: density plot In-Reply-To: References: Message-ID: <5b8d13220812102356r17a1e186k367b5ff62cd92f99@mail.gmail.com> On Thu, Dec 11, 2008 at 1:57 PM, wrote: > Hi, > > Does anyone know how to make the density plot, more specifically a > gaussian-smoothed version of a histogram. Actually, it's not exactly > a plot that I want. What I want to do is get the maximum count (or > highest peak) of the density distribution. It's different from the > probability density function that has the center at zero. > > In S plus and R, there is the "density" function which I can use to > get the max x and y in the frequency distribution. scipy ML is more appropriate for this kind of questions: http://www.scipy.org/Mailing_Lists In scipy, there is a kernel density estimator, which is one popular method for non-parametric density estimation, and fit exactly the "Gaussian smoothed version of the histogram" when used with Gaussian kernels. David From rogerb at rogerbinns.com Wed Dec 24 02:26:49 2008 From: rogerb at rogerbinns.com (Roger Binns) Date: Tue, 23 Dec 2008 23:26:49 -0800 Subject: Strategy for determing difference between 2 very large dictionaries In-Reply-To: <1230102996.2303.1291616055@webmail.messagingengine.com> References: <1230102996.2303.1291616055@webmail.messagingengine.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 python at bdurham.com wrote: > Feedback on my proposed strategies (or better strategies) would be > greatly appreciated. Both strategies will work but I'd recommend the second approach since it uses already tested code written by other people - the chances of it being wrong are far lower than new code. You also neglected to mention what your concerns are or even what "very large" is. Example concerns are memory consumption, cpu consumption, testability, utility of output (eg as a generator getting each result on demand or a single list with complete results). Some people will think a few hundred entries is large. My idea of large is a working set larger than my workstation's 6GB of memory :-) In general the Pythonic approach is: 1 - Get the correct result 2 - Simple code (developer time is precious) 3 - Optimise for your data and environment Step 3 is usually not needed. Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAklR5DUACgkQmOOfHg372QSuWACgp0xrdpW+NSB6qqCM3oBY2e/I LIEAn080VgNvmEYj47Mm7BtV69J1GwXN =MKLl -----END PGP SIGNATURE----- From klaus.kopec at tuebingen.mpg.de Tue Dec 9 13:14:33 2008 From: klaus.kopec at tuebingen.mpg.de (Klaus Kopec) Date: Tue, 09 Dec 2008 19:14:33 +0100 Subject: pickling a circular object inherited from list In-Reply-To: <3b1bab42-657c-4b93-9236-aa5236c16826@w1g2000prk.googlegroups.com> References: <3b1bab42-657c-4b93-9236-aa5236c16826@w1g2000prk.googlegroups.com> Message-ID: >> What did I do wrong? > Old Python version? :) > Seems to work in 3.0 (don't have 2.6 currently to check but IMO it's > fixed there as well). It works for me with v3.0 as well, but not with v2.6.1 (same error as stated before for v2.4). Is there any way to fix this in v2.6.1 or even v2.4? Right now I cannot switch to v3.0 because I depend on several not compatible packages (numpy, biopython, ...) From jstroud at mbi.ucla.edu Sun Dec 7 16:53:51 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 07 Dec 2008 13:53:51 -0800 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Luis Zarrabeitia wrote: > > Quoting James Stroud : > >> First, here is why the ability to throw an error is a feature: >> >> class Apple(object): >> def __init__(self, appleness): >> self.appleness = appleness >> def __cmp__(self, other): >> assert isinstance(other, Apple), 'must compare apples to apples' >> return cmp(self.appleness, other.appleness) >> >> class Orange(object): pass >> >> Apple(42) == Orange() > > I beg to disagree. > The right answer for the question "Am I equal to this chair right here?" is not > "I don't know", nor "I can't compare". The answer is "No, I'm not a chair, thus > I'm not equal to this chair right here". If someone comes to my house, looking > for me, he will not run away because he sees a chair before he sees me. Your > assert doesn't belong inside the methot, it should be up to the caller to decide > if the human-chair comparisons make sense or not. I certainly don't want to be > type-checking when looking for an object within a mixed-type collection. > >> This reminds me of complex numbers: would 4 + 4i be equal to sqrt(32)? > > I assume you meant sqrt(32i). No, I definitely didn't mean sqrt(32i). I'm using sqrt() to represent the mathematical square root, and not an arbitrary function one might define, by the way. My point is that 4 + 4i, sqrt(32), and sqrt(-32) all exist in different spaces. They are not comparable, even when testing for equality in a pure mathematical sense. If when encounter these values in our programs, we might like the power to decide the results of these comparisons. In one context it might make sense to throw an exception, in another, it might make sense to return False based on the fact that we consider them different "types", in yet another context, it might make sense to look at complex plane values as vectors and return their scalar magnitude for comparison to real numbers. I think this ability to define the results of comparisons is not a shortcoming of the language but a strength. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From tjreedy at udel.edu Thu Dec 4 14:55:08 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Dec 2008 14:55:08 -0500 Subject: Python 3 read() function In-Reply-To: <20081204194232.20272.544720092.divmod.quotient.15718@ohm> References: <20081204194232.20272.544720092.divmod.quotient.15718@ohm> Message-ID: Jean-Paul Calderone wrote: > On Thu, 04 Dec 2008 14:25:48 -0500, Terry Reedy wrote: >> [snip] >> >> In my test, I read Python25.chm with 2.5 and Python30.chm with 3.0. >> >> Rereading Python30.chm without closing *is* much faster. >> >>> f=open('Doc/Python30.chm','rb') >> >>> d=f.read() >> >>> d=f.read() >> >>> d=f.read() > > Did you think about what this does? Whoops ;-) f.seek(0) first and it is maybe a bit faster, but not 'much'. From wicijowski at gmail.com Sun Dec 28 15:34:04 2008 From: wicijowski at gmail.com (janislaw) Date: Sun, 28 Dec 2008 12:34:04 -0800 (PST) Subject: tkinter 3.0 multiple keyboard events together References: <600d4b68-6fe2-4c2c-b425-1a739430bb54@s9g2000prg.googlegroups.com> <7b5e466c-d75d-4e71-b559-f8a0d3718094@r15g2000prd.googlegroups.com> Message-ID: <655327e0-47b5-4c0b-a028-c1ed1692b14f@r15g2000prd.googlegroups.com> On 28 Gru, 09:43, Pavel Kosina wrote: > well, I am working on a tutorial for youngster (thats why i need to stay > the code as easy as possible). In this game you are hunted by robots. I > could use key"7" on numeric keypad for left-up moving but seems to me, > that "4"+"8" is much more standard for them. > > > Hmmm. Maybe you'd like to hook into Tkinter event loop, i.e. by custom > > events if you don't like periodical polling. > > No, that would be even more difficult. I already have a code that use > your idea: > > from Tkinter import * > root = Tk() > > pressedKeys=set() > > def onKeyPress(event): > pressedKeys.add(event.keysym) > > def onKeyRelease(event): > pressedKeys.remove(event.keysym) > > def move(): > print list(pressedKeys) > root.after(100,move) > > root.bind("", onKeyPress) > root.bind("", onKeyRelease) > root.after(100,move) > root.mainloop() > > well, I thought that gui?s have such a problem already built-in - so > that i am not pressed to code it. You know, its not exactly about me - > if I do it for myself, for my program, that there is no problem, but I > need to explained it to begginners ..... And I do not want, as might be > more usual, do my module, that would cover this "insanity" (look at it > with 13-years old boy eyes ;-) ). Do you like to say me, that this is > not a standard "function" neither in tkinter, not say gtk or the others, > too? Ok, I get it then! Your goal is very humble :) In the piece of code we have came together to, there is a functionality you already want - the pressedKeys. I suppose, that you'd like to hide from the further implementors (children). You can write another module, which could contain this piece of code and could be imported by kids to have the desired features. Meaning only getting this list of keys. But what you write here: > I would expect something like this: > > def onKeyTouch(event): > ? ? print (event.keysymAll) > > root.bind("", onKeyTouch) ...is a bit misleading. There is no such thing as simultaneous events - for that the event dispatcher loop is designed - to simplyfy all usual stuff with parallel paradigsm such as interrupts, thread safety etc. An event is in my eyes a response to a short action, let's call it atomic. There's no need to pretend, that clicking a few keys simultanously is sth immediate and the software could by any chance guess that a few keys were actually clicked. Even the keyboard driver does some sequential scanning on the keys, and the key codes are then send to the board sequentially as well. Try to run this code: #---------------- #Tkinter multiple keypress #Answer http://groups.google.com/group/comp.lang.python/browse_thread/thread/88788c3b0b0d51d1/c4b7efe2d71bda93 import Tkinter import pprint import time tk = Tkinter.Tk() f = Tkinter.Frame(tk, width=100, height=100) msg = Tkinter.StringVar() msg.set('Hello') l = Tkinter.Label(f, textvariable=msg) l.pack() f.pack() keys = set() lastTime = None def keyPressHandler(event): keys.add(event.char) global lastTime now = time.time() if lastTime: difference = now - lastTime if difference < 0.1: #seconds print difference, 's' lastTime = now display() def keyReleaseHandler(event): keys.remove(event.char) display() def display(): msg.set(str(keys)) f.bind_all('', keyPressHandler) f.bind_all('', keyReleaseHandler) f.mainloop() #-------------------------------- ... and find out, how 'simultaneous' they are. For me it's 0.0, meaning that the event handlers were executed one after another, but sometimes there is sth like 0.0309998989105 s - proabably an USB latency, or an operating system context switch - hard to tell. If you'd like to have two key clicks to generate a single event, you'd have to write some timeout code (threading.Timer or tk stuff is handy) to check how 'simultaneous' they actually were. Search web for events in <> inequality signs if you really want this. I don't know gtk, but hey, pygame has pygame.key.get_pressed if you'd like to switch: http://www.pygame.org/docs/ref/key.html Have luck Jan From steve at REMOVE-THIS-cybersource.com.au Tue Dec 30 20:19:29 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Dec 2008 01:19:29 GMT Subject: Triple quoted string in exec function ? References: Message-ID: <016abfa1$0$6988$c3e8da3@news.astraweb.com> On Tue, 30 Dec 2008 15:35:28 -0600, Rob Williscroft wrote: > Stef Mientki wrote in news:mailman.6399.1230668197.3487.python- > list at python.org in comp.lang.python: > >>>> And, by the way, exec is a *statement*, not a function! >>>> >> exec ( Init_Code, PG.P_Globals ) >> >> I've really doubt that this is a statement, unless I don't understand >> what a statement is. >>>> >>>> >> > In python 2.x the above is a statement that is passed a tuple: > > http://docs.python.org/reference/simple_stmts.html#exec The documentation doesn't say anything about it accepting a tuple as an argument. The tuple argument works in both 2.5 and 2.6. Curious. I was also surprised by this behaviour: >>> g, l = {}, {} # no globals, no locals >>> exec "x = 1" in g, l >>> l {'x': 1} >>> g.keys() ['__builtins__'] I see *now* that this is documented: "...the current implementation MAY add a reference to the dictionary of the built-in module __builtin__ under the key __builtins__ (!)." [emphasis added] but it's still rather disconcerting. That means that: exec "some potentially dangerous code" in {}, {} isn't as safe as I thought it was. -- Steven From duncan.booth at invalid.invalid Fri Dec 5 03:31:38 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 Dec 2008 08:31:38 GMT Subject: Don't you just love writing this sort of thing :) References: Message-ID: Lawrence D'Oliveiro wrote: > In message , Duncan Booth wrote: > >> Have you ever considered trying to write readable code instead? >> >> (I must admit I haven't checked whether GZipFile works with the 'with' >> statement... > > That's why I prefer writing _correct_ code instead. Good idea, but the mess you posted is going to be virtually untestable whereas splitting it up into small testable functions will make it much easier for you to actually get somewhere near your goal of correct code. BTW, by trimming half of my sentence you changed its meaning significantly. You implied that I gave an example without caring whether it could work whereas the other half of the sentence pointed out that if GZipFile requires it you may need to add a single function call to my code. -- Duncan Booth http://kupuguy.blogspot.com From cournape at gmail.com Fri Dec 12 05:25:14 2008 From: cournape at gmail.com (David Cournapeau) Date: Fri, 12 Dec 2008 19:25:14 +0900 Subject: How do I manually uninstall setuptools (installed by egg)? In-Reply-To: References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> <47c890dc0812091904p12e75510sbe0b8858eb2f6d9e@mail.gmail.com> Message-ID: <5b8d13220812120225q5f88238j19bb083ba6e98406@mail.gmail.com> On Thu, Dec 11, 2008 at 10:30 PM, Nick Craig-Wood wrote: > David Cournapeau wrote: >> On Wed, Dec 10, 2008 at 12:04 PM, Chris Rebert wrote: >> > On Tue, Dec 9, 2008 at 6:49 PM, wrote: >> >> On Ubuntu, I accidentally manually installed setuptools >> >> http://pypi.python.org/pypi/setuptools/0.6c9 (by running the .egg file >> >> as a shell script via sudo), and now realize I should just be using >> >> apt to take care of my system Python packages. >> > >> > Really, why? setuptools has more Python packages/programs available >> > and updates faster than Debian. >> > It's also likely that some of the Debian Python packages are installed >> > using setuptools anyway. >> > So, why do you think apt and not setuptools is The Right Way(tm)? >> >> Setuptools is certainly not the right way to install packages >> system-wide on debian, it is very likely to break the whole thing. > > It wouldn't be too difficult to make a .deb target which would collect > all the files that did get installed into a package. It would be a > rather rough and ready package but would do the job. Depends what you mean by would do the job: rather rough certainly does not mean "would do the job" for something as essential as a package IMO. > > The .deb would then be uninstallable in the usual (dpkg --purge) way. > > Did anyone think about that? Yes, there is stddeb which does that (make a .deb package from a setuptools package). > > easy_install can do that I think... Not without a lot of hoola, unfortunately; for example, it breaks stow, so I have to use specialy scripts to circumvent the damn thing and make it what I tell him to do. I never understood what's easy about easy install: it is broken in so many ways, and has caused me so many pains - even when I was not using - that I do not trust it at all. I only use it to download packages (and even then it manage to fail more than work), and always install them from setup.py afterwards (at which step I of course also have to circumvent setuptools if the package uses setuptools). cheers, David From bj_666 at gmx.net Sun Dec 21 08:34:35 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Dec 2008 13:34:35 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <015da0a4$0$20656$c3e8da3@news.astraweb.com> Message-ID: <6r6uvbFfb643U5@mid.uni-berlin.de> On Sun, 21 Dec 2008 12:45:32 +0000, Duncan Booth wrote: > You seem to have made an unwarranted assumption, namely that a binary > operator has to compile to a function with two operands. There is no > particular reason why this has to always be the case: for example, I > believe that C# when given several strings to add together optimises > this into a single call to a concatenation method. > > Python *could* do something similar if the appropriate opcodes/methods > supported more than two arguments: > > a+b+c+d might execute a.__add__(b,c,d) allowing more efficient string > concatenations or matrix operations, and a%b%c%d might execute as > a.__mod__(b,c,d). But that needs special casing strings and ``%`` in the comiler, because it might not be always safe to do this on arbitrary objects. Only in cases where the type of `a` is known at compile time and ``a % b`` returns an object of ``type(a)``. Ciao, Marc 'BlackJack' Rintsch From steve at holdenweb.com Wed Dec 10 12:55:17 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 10 Dec 2008 12:55:17 -0500 Subject: get todays files In-Reply-To: References: Message-ID: Andrew D wrote: > I have a script that will login to my ftp server and download all the > backup files, but I want it to only download the files that were > created today, e.g. if I ran the script today I want it to only fetch > files created today. > > I am really not sure about how to do this, but it is quite important > to me, so all help is highly appreciated! > IIRC there's an "ftpmirror" script in the Tools directory (if you're on Windows - Linux/Unix users have to download the source). I adapted it to several different purposes. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From almar.klein at gmail.com Wed Dec 10 06:59:46 2008 From: almar.klein at gmail.com (Almar Klein) Date: Wed, 10 Dec 2008 12:59:46 +0100 Subject: Mathematica 7 compares to other languages In-Reply-To: <501d76b2-45d1-4475-8d88-e0e51e19fc10@q26g2000prq.googlegroups.com> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <9ecfa224-ce8f-44e9-abca-008314f44e87@40g2000prx.googlegroups.com> <501d76b2-45d1-4475-8d88-e0e51e19fc10@q26g2000prq.googlegroups.com> Message-ID: 2008/12/10 Xah Lee > Jon Harrop moron wrote: > > Only for trivial input and not for the challenge you were given. > > what challenge? > > > That code is evaluated once to build the scene. There is no point in > > optimizing it. > > The point is optimizing your incompetence. > > > That performance issue only affects trivial problems and, in particular, > > does not affect the problem you were trying to solve. > > solve your mom? > > What challange? Euhm, I think that was pretty clear. And you're constantly insulting people, not responding to their arguments. Not a particularly nice way to behave in a news group such as this. >Also, all you did is talking bullshit. >You, kept on babbling. I think YOU are the one who is talking crap here. You are too afraid to admid you failed the challange (probably because you think so high of yourself). You try to cover it with crap and insults. Cheers, Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Thu Dec 4 10:53:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Dec 2008 15:53:21 GMT Subject: Please fix your clock [was Re: Multiple equates] References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> Message-ID: <0147f4b7$0$20670$c3e8da3@news.astraweb.com> Hendrik, I think your PC's clock is wrong. You seem to be posting from the future. From fetchinson at googlemail.com Thu Dec 11 02:53:28 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 10 Dec 2008 23:53:28 -0800 Subject: why doesn't pop/clear call __delitem__ on a dict? Message-ID: I just found out that if I want to have a custom dict it's not enough to overload __getitem__, __setitem__ and __delitem__ because, for example, pop and clear don't call __delitem__. I.e. an instance of the following will not print 'deleted' upon instance.pop( 'key' ): class mydict( dict ): def __setitem__( self, key, value ): print 'set' super( mydict, self ).__setitem__( key, value ) def __getitem__( self, key ): print 'get' super( mydict, self ).__getitem__( key ) def __delitem__( self, key ): print 'deleted' super( mydict, self ).__delitem__( key ) Why is this? There might other gotchas too I suppose. My intention is clear from the above, what other methods do I have to overload so that I get what I expect for all dict operations? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From tjreedy at udel.edu Thu Dec 4 21:00:29 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Dec 2008 21:00:29 -0500 Subject: Python 3 read() function In-Reply-To: References: <16651e80812040900j257fe2acjf5d8817811d32da6@mail.gmail.com> Message-ID: Christian Heimes wrote: > Terry Reedy wrote: >> Timing of os interaction may depend on os. I verified above on WinXp >> with 4 meg Pythonxy.chm file. Eye blink versus 3 secs, duplicated. I >> think something is wrong that needs fixing in 3.0.1. >> >> http://bugs.python.org/issue4533 > > I've attached a patch to the bug. reading was so slow because the > fileio_readall() was increasing the buffer by 8kB in each iteration. The > new code doubles the buffer until it reaches 512kB. Starting with 512kB > it's increased in 512kB blocks. Python 2.x has the same growth rate. > > Christian Thank you. Too bad this was not caught a week ago, but the timing of each method of each class is a bit hard to test for. Perhaps in the future. tjr From google at mrabarnett.plus.com Sun Dec 21 11:58:53 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 21 Dec 2008 16:58:53 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: <494E75CD.20501@mrabarnett.plus.com> Aaron Brady wrote: > On Dec 21, 10:31 am, MRAB wrote: >> Aaron Brady wrote: >>> On Dec 20, 8:49 pm, MRAB wrote: >>>> Aaron Brady wrote: >>>>> On Dec 20, 7:38 pm, Steven D'Aprano >>>> cybersource.com.au> wrote: >>>>>> Instead of just whinging, how about making a suggestion to fix it? Go on, >>>>>> sit down for an hour or ten and try to work out how a BINARY OPERATOR >>>>>> like % (that means it can only take TWO arguments) can deal with an >>>>>> arbitrary number of arguments, *without* having any special cases. >>>>>> Go on. Take your time. I'll be waiting. >>>>> Hi, not to take sides, but, there is a possibility. >>>>> This behavior is currently legal: >>>>>>>> "%i %%i" % 0 % 1 >>>>> '0 1' >>>>> So, just extend it. (Unproduced.) >>>>>>>> "%i %i" % 0 % 1 >>>>> '0 1' >>>>>>>> "%r %i" % (2, 3, 4) % 1 >>>>> '(2, 3, 4) 1' >>>>>>>> "%r %i" % (2, 3, 4) >>>>> '(2, 3, 4) %i' >>>>> Which is quite clever and way ahead of its (posessive) time. >>>> A couple of problems: >>>> 1. How do you handle a literal '%'? If you just double up then you'll >>>> need to fix the string after all your substitutions. >>>> 2. What if a substitution introduces a '%'? >>>> I suppose a possible solution would be to introduce a special format >>>> string, including a literal, eg: >>>> f"%r %i" % (2, 3, 4) % 1 >>>> and then convert the result to a true string: >>>> print(str(f"%r %i" % (2, 3, 4) % 1)) >>>> (although print() would call __str__ anyway). >>>> The format string would track where the last substitution occurred. >>>> Hmm... I think I'll just learn the new method. :-) >>> Now that I'm fighting 'r's war for him/her... >>> Um, here's one possibility. On the first interpolation, flags are >>> noted and stored apart from subsequent interpolations. Then, use a >>> sentinel to terminate the interpolation. (Unproduced.) >>>>>> "%r %i" % ( 2, 3 ) % 0 >>> '(2, 3) 0' >>>>>> "%% %r" % ( 2, 3 ) % str.interp_end >>> '% (2, 3)' >>>>>> "%sss%i" % "%d" % 0 >>> '%dss0' >>> The first %s is replaced with %d, but doesn't hijack the '0'. If you >>> want to interpolate the %d, use the sentinel. The sentinel is what >>> causes '%%' to be handled. >>>>>> "%sss%i" % "%d" % 0 % 1 >>> Traceback (most recent call last): >>> File "", line 1, in >>> TypeError: not all arguments converted during string formatting >>>>>> "%sss%i" % "%d" % 0 % str.interp_end % 1 >>> '1ss0' >>> Treating tuples as a special case appears to be the simpler solution, >>> but this, 'chaining', to adopt the term, is still feasible. >> A possible solution occurred to me shortly after I posted, but I decided >> that sleep was more important. :-) >> >> The original format is a string. The result of '%' is a string if >> there's only 1 placeholder to fill, or a (partial) format object (class >> "Format"?) if there's more than one. Similarly, the format object >> supports '%'. The result of '%' is a string if there's only 1 >> placeholder to fill, or a new (partial) format object if there's more >> than one. >> >> >>> f = "%r %i" >> >>> type(f) >> >> >>> f = f % (2, 3, 4) >> >>> type(f) >> >> >>> f = f % 1 >> >>> type(f) >> > > Alright, so how are you handling: > >>>> f= "%s %i" >>>> type( f ) > >>>> f= f% '%i' #now '%i %i' >>>> type( f ) > >>>> f= f% 1 >>>> type( f ) > ? > > In other words, are you slipping '1' in to the very first available > slot, or the next, after the location of the prior? > Let's assume that Format objects display their value like the equivalent string format: >>> f = "%r %i" >>> f '%r %i' >>> f = f % (2, 3, 4) >>> f >>> f = f % 1 >>> f '(2, 3, 4) 1' >>> >>> f = "%s %i" >>> f '%s %i' >>> f = f % '%i' >>> f >>> f = f % 1 >>> f '%%i 1' From arnodel at googlemail.com Thu Dec 11 15:19:35 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 11 Dec 2008 20:19:35 +0000 Subject: dictionary idiom needed References: <383976cf-53fb-48e4-b028-8f568468ce77@r36g2000prf.googlegroups.com> <0c4950c1-4833-40c7-ac19-260b61d5289f@k24g2000pri.googlegroups.com> <7c55c59b-cebe-4f4e-ae40-282ae7e005bf@d42g2000prb.googlegroups.com> Message-ID: Brandon writes: > Thanks bear - > > Some outside advice has me looking at nested dictionaries. But I am > still bogged down because I've not created one before and all examples > I can find are simple ones where they are created manually, not with > loops. Maybe a further example: > > data: > POS1 POS2 POS3 > ['word1','tagA','tagB'] > ['word2','tagC','tagD'] > ['word1','tagE','tagB'] > ['word1','tagC','tagF'] > > ... and so on. FWIW: I am guaranteed that the set of tags that may > occur in position2 is complementary to the set of tags that may occur > in position3. > > Now I want to get an accounting of all the tags that occurred in > position3 in the context of, say, word1. Here I've shown that for > word1, tagB and tagF occurs. I want a way to access all this > information such that nested_dict['word1']['tagB'] = 2, and nested_dict > ['word1']['tagF'] = 1. > > As I mentioned, I already have dicts such that dictA['word1'] = 3, and > dictB['tagB'] = 2. I used defaultdict to build those, and that seems > to be causing me to get some funky values back from my initial > attempts to build a nested dictionary. I am stumbling at constructing > a "for" loop that automatically creates such nested dictionaries. > > I hope that clears things up. If you still have any advice, it's much > appreciated. > > Thanks, > > Brandon >>> from collections import defaultdict >>> >>> data = [['word1','tagA','tagB'], ... ['word2','tagC','tagD'], ... ['word1','tagE','tagB'], ... ['word1','tagC','tagF']] >>> >>> d = defaultdict(lambda: defaultdict(int)) >>> >>> for w, t1, t2 in data: ... d[w][t2] += 1 ... >>> d['word1']['tagB'] 2 >>> d['word2']['tagD'] 1 >>> d['word2']['tagF'] 0 HTH -- Arnaud From gagsl-py2 at yahoo.com.ar Fri Dec 12 21:38:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 13 Dec 2008 00:38:00 -0200 Subject: forcing future re-import from with an imported module References: <533670ae-6d9d-4b10-9156-e41b31b678c7@g17g2000prg.googlegroups.com> Message-ID: En Fri, 12 Dec 2008 19:44:32 -0200, _wolf escribi?: > On Dec 11, 12:43 am, rdmur... at bitdance.com wrote: >> "Why can't you have the code that is doing the import [...] >> call a function [...] to produce [the] side effect [...]? >> Explicit is better than implicit. A python programmer is >> going to expect that importing a module is idempotent" > > you?re completely right that `import foo` with side effects may break > some expectations, but so do all `from __future__` imports. you?re > also right that another solution would be to come in from the other > side and explicitly call a function from the importing module. all of > this does not answer one question tho: why does deleting a module work > most of the time, but not in the case outlined in my first post, > above? why do we get to see this slightly strange error message there > complaining about ?not finding? a module ?in sys.modules??well, most > of the time, when a module is not in that cache, it will be imported, > but not in this case. why? The import system can be customised in many ways (the various import hooks, special entries in sys.path, meta_path, path_hooks, __import__, etc.), even could be completely reimplemented. There are safety checks in the interpreter, to validate some minimal pre and postconditions that should always hold. By example, checking that sys.path contains a list of directories. Or the one you broke: after successfully executing "import foo", there must be an entry named "foo" in sys.modules. If not, it is asumed that something in the import machinery went wrong. -- Gabriel Genellina From akineko at gmail.com Tue Dec 30 01:44:41 2008 From: akineko at gmail.com (akineko) Date: Mon, 29 Dec 2008 22:44:41 -0800 (PST) Subject: Python in C References: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> Message-ID: <313583fc-4651-4deb-8a44-c3b1810b722c@z27g2000prd.googlegroups.com> Although this is not what you are asking but I'm wondering why you need to read CPython implementation. I have been using Python for 7 or 8 years but I've never encountered any situations where I need to read CPython implementation. I needed to read library implementations and installer codes, though. CPython worked great for me. I don't want to read a large piece of software, like CPython, unless it is really really necessary. I'm curious. Aki- On Dec 29, 5:22?pm, thmpsn.... at gmail.com wrote: > I've just downloaded Python's mainstream implementation (CPython), > which is written in C. Not to my surprise, I feel like I'm looking at > unstructured spaghetti, and I'm having trouble figuring out how it all > works together. (Please bear with me; I'm just going through the usual > frustration that anyone goes through when trying to see the > organization of a C program :) > > So, I have two queries: > > 1. Can anyone explain to me what kind of program structuring technique > (which paradigm, etc) CPython uses? How do modules interact together? > What conventions does it use? > > 2. Have there been any suggestions in the past to rewrite Python's > mainstream implementation in C++ (or why wasn't it done this way from > the beginning)? From andre.roberge at gmail.com Sun Dec 7 15:43:24 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sun, 7 Dec 2008 12:43:24 -0800 (PST) Subject: Python for kids? References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> Message-ID: <2dcad5b4-5085-4e0a-bab2-daaf8d5b75f3@33g2000yqm.googlegroups.com> On Dec 7, 4:13?pm, "Russ P." wrote: > I have a 12-year-old son who spends too much time playing Xbox live > and watching silly YouTube videos. I would like to try to get him > interested in programming. Is anyone aware of a good book or website > that addresses this concern, preferably (but not necessarily) using > Python? I could try to teach him Python myself, but I'm afraid I would > just frustrate him and kill his interest in programming. I did a > Google search and found a few things, but not a lot. Thanks. http://rur-ple.sourceforge.net Andr? From mail at microcorp.co.za Tue Dec 23 03:03:24 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 23 Dec 2008 10:03:24 +0200 Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com><1d03c66b-c725-42f4-af6e-2351a7841b30@z1g2000yqn.googlegroups.com> Message-ID: <01e401c964e9$d07a3fc0$0d00a8c0@hendrik> "r" wrote:: > The writing is on the Wall! Yes it is, and as always, it says : Mene, mene, tekel epharsim. If my protestant upbringing hasn't failed me, it means: Weighed, and found wanting. - Hendrik From wuwei23 at gmail.com Thu Dec 4 02:13:18 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 3 Dec 2008 23:13:18 -0800 (PST) Subject: "as" keyword woes References: Message-ID: On Dec 4, 3:42?pm, "Warren DeLano" wrote: > So you prefer broken code to broken rules, eh? ?Your customers must love > that! ?This is exactly the kind of ivory-tower thinking I feared might > be behind the decision (form over function, damn the users to hell, > etc.) Really? I find that believing something should remain static at the expense of actual improvement to the language is far more 'ivory-tower thinking' than embracing change. > Am I the only one picking up on the irony here? ?"as" exists largely to > provide a mechanism for working around namespace conflicts -- except, > apparently, conflicts involving "as". ?The fact that "as" itself creates > an insurmountable namespace collision is just killing me! ?How absurd. Speaking of irony, you're complaining about namespace conflicts with a -two character identifier- you've chosen. Here's a hint: choose better names. > But to be brutally honest...in this many-core world we must all accept > and deal with today, it is hard to imagine how a non-multithreaded AND > non-backwards compatible Python implementation can have much of a life > ahead of it, with or without an "as" keyword. ?I do sincerely hope I am > wrong about this, but it is seems quite possible that C/Python's glory > days are now behind us. ? To match your honesty, I'm somewhat tired with the trend of some people to hit -one- issue with Python and suddenly lash out like children over all the same old tired crap. Have you even looked at multiprocessing? Have you contributed to any projects working on GIL- less implementations? Or are you just regurgitating the same bullet points we've heard time and time again? For chrissake, if you cannot do ANYTHING but BITCH about a change, then you've no damn right to consider yourself a programmer. Real programmers find solutions, not excuses. > And if so, then thank you all for so many wonderful years of effort and > participation! You're welcome. Don't let the door hit you on the ass on your way out. From sturlamolden at yahoo.no Fri Dec 12 11:55:12 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Dec 2008 08:55:12 -0800 (PST) Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> Message-ID: On Dec 12, 5:13 pm, Steve Holden wrote: > OK, so now you are proposing to alter the parser, and possibly the > implementation of the INPLACE_ADD opcode in eval.c, so can you give us > the patch for those, please? That is not where the problem resides. From tjreedy at udel.edu Sun Dec 7 04:15:29 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 07 Dec 2008 04:15:29 -0500 Subject: Python 3.0 automatic decoding of UTF16 In-Reply-To: References: <55d79070-0c11-4fb9-8cf5-b8cc7c54b5d2@v42g2000yqv.googlegroups.com> <0e37191f-3672-4313-bc5c-ffcd904e4796@k24g2000pri.googlegroups.com> Message-ID: John Machin wrote: > Here's the scoop: It's a bug in the newline handling (in io.py, class > IncrementalNewlineDecoder, method decode). It reads text files in 128- > byte chunks. Converting CR LF to \n requires special case handling > when '\r' is detected at the end of the decoded chunk n in case > there's an LF at the start of chunk n+1. Buggy solution: prepend b'\r' > to the chunk n+1 bytes and decode that -- suddenly with a 2-bytes-per- > char encoding like UTF-16 we are 1 byte out of whack. Better (IMVH[1] > O) solution: prepend '\r' to the result of decoding the chunk n+1 > bytes. Each of the OP's files have \r on a 64-character boundary. > Note: They would exhibit the same symptoms if encoded in utf-16LE > instead of utf-16BE. With the better solution applied, the first file > [the truncated one] gave the expected error, and the second file [the > apparently OK one] gave sensible looking output. > > [1] I thought it best to be Very Humble given what you see when you > do: > import io > print(io.__author__) > Hope my surge protector can cope with this :-) > ^%!//() > NO CARRIER Please post this on the tracker so it can get included with other io work for 3.0.1. From lie.1296 at gmail.com Tue Dec 23 09:17:44 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 23 Dec 2008 14:17:44 +0000 (UTC) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <070e5832-62a5-40ba-b566-e1f755a0a8f4@w35g2000yqm.googlegroups.com> <7c02eb33-a919-4481-8eda-76062729f233@k19g2000yqg.googlegroups.com> <32d8e3f1-52a7-4bce-a70a-70db488a417b@h20g2000yqn.googlegroups.com> Message-ID: On Mon, 22 Dec 2008 21:05:22 -0800, r wrote: > On Dec 22, 10:09?pm, Ben Kaplan wrote: >> That's just because most of us don't say anything unless we have >> something useful to say. We prefer to let the experts answer the >> questions, but we read the threads so we can benefit from them. > > OK Ben, So you are saying > > 1.) do not question the gods! Hmmm... when we talk about something we don't know, only trash would come out of our mouth. > 2.) speak only when spoken to! He (Ben) does not say anything remotely like that. > 3.) do not have an opinion! Again, you're adding sauce, meat, beef, and spices to his statement. > Somehow this reminds me of some old and brainwashing religions, Not an > OSS project. Just observations Ben. Isn't it you that have been accused of religionizing python by many people in this list? From conrad.ammon at gmail.com Mon Dec 15 15:27:12 2008 From: conrad.ammon at gmail.com (cmdrrickhunter@yaho.com) Date: Mon, 15 Dec 2008 12:27:12 -0800 (PST) Subject: Structure using whitespace vs logical whitespace References: <05a8dfb2-b91d-4bdb-bb7e-bba3b5c37a01@f20g2000yqg.googlegroups.com> Message-ID: <89b3cbe5-e61b-49eb-926a-e96a43a35fe5@s1g2000prg.googlegroups.com> On Dec 15, 11:10?am, Terry Reedy wrote: > > In general, I'm using indentation to show logical flow through code. > > That, of course, is what Python does. > Python does NOT use indentation to show logical flow. It uses it to show syntactical flow. The XML writer is the perfect example of a case where they are different. In most cases, syntactic flow is close enough to logical flow. There are a few cases where you can 'draw a picture' of the algorithm in code if you are whitespace insensitive. I've not used the "with" keyword before, and it does seem to handle this troublesome case quite well. I learned python before it was around, and never really studied it hard enough. I'll have to investigate what other tricks can be done with it. I'm a big fan of the rule "make the 90% easy and the remaining 10% possible." Whitespace sensitivity makes the 90% easy, and just from the looks of it, the 'with' command and whitespace insensitive expressions give the remaining 10%. And I do like the automated support for "finally" clauses when using 'with' Thanks for the help, everyone! From ldo at geek-central.gen.new_zealand Wed Dec 3 06:23:24 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 04 Dec 2008 00:23:24 +1300 Subject: Multiple equates References: <00ec3d9d-7167-4306-9a5b-ad02ec4f0a99@b31g2000prb.googlegroups.com> <9m3h06-vhh.ln1@lairds.us> Message-ID: In message , Cameron Laird wrote: > def shell_escape(Arg) : > """returns Arg suitably escaped for use as a command-line argument > to Bash.""" > > pattern = r"[\<\>\"\'\|\&\$\#\;\(\)\[\]\{\}\`\!\~\ \\]" > def f1(Match): > return "\\" + Match.group(0) > return re.sub(pattern, f1, Arg) > # Need to catch anything that might be meaningful to shell > #end shell_escape So why is that better? From gagsl-py2 at yahoo.com.ar Mon Dec 29 22:24:58 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Dec 2008 01:24:58 -0200 Subject: Python module import loop issue References: <02bc8567-695a-4277-9698-a95549a0bc98@w39g2000prb.googlegroups.com> <4a0557b7-e901-49ff-b4db-53f4d8a7c0f8@r40g2000yqj.googlegroups.com> Message-ID: En Mon, 29 Dec 2008 19:47:51 -0200, Carl Banks escribi?: > On Dec 29, 10:51?am, Kottiyath wrote: >> Module Factory: >> A1Factory: {'B1Tag':1.1.B1, 'C1Tag':1.2.C1, 'D1Tag':1.3.D1'} >> A2Factory: {'B2Tag':2.1.B2, 'C2Tag':2.2.C2, 'D2Tag':2.3.D2'} >> >> But, since Module requires objects of B1, C1 etc, it has to import >> Factory. >> Now, there is a import loop. How can we avoid this loop? > > I'm going to suggest three ways: a straightforward, good-enough way; a > powerful, intelligent, badass way; and a sneaky way. In Python 2.6 (and 3.0) there is a fourth way: class decorators. > 1. The straightforward, good-enough way > > Define functions in Factory.py called register_A1_subclass and > register_A2_subclass, then call them whenever you create a new > subclass. Class decorators are a clean variant of this approach (in my opinion). > package1/module1.py: > ----------------------------- > import Factory > > class B1(A1): > # define class B1 here > > Factory.register_A1_subclass("B1Tag",B1) > ----------------------------- That would become: @Factory.register_A1_subclass("B1Tag") class B1(A1): ... (for an adequate variant of register_A1_subclass). The advantage is that the "register" stuff appears prominently near the name of the class, and there is no need to repeat the name. Also, "B1Tag" can be left out, if it is stored as a class attribute of B1 (in some cases using __name__ is enough) > 2. The powerful, intelligent, badass way > > Metaclasses. I would guess you do not want to do this, and I wouldn't > recommend it if you haven't studied up on how metaclasses work, but > it's a textbook example of their usefulness. If you expect to use > factory functions like this a lot, it might be worth your while to > learn them. A problem with metaclasses is when you have intermediate subclasses that are not meant to be registered, but the metaclass applies equally to all of them. -- Gabriel Genellina From steven at REMOVE.THIS.cybersource.com.au Mon Dec 8 21:43:06 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 09 Dec 2008 02:43:06 GMT Subject: A question about reference in Python. References: <493CB003.3080209@gmail.com> Message-ID: On Mon, 08 Dec 2008 08:18:27 -0700, Joe Strout wrote: > On Dec 7, 2008, at 10:26 PM, Group wrote: > >> Now, I want to write a Red-Black Tree, and a List structure. In C/C+ +, >> I can >> use pointers to refer to children notes (or next notes). But, in >> Python, how >> can I do it? Except the sequence, I know not any way. > > Any variable in Python is a reference Except that they don't behave like references in languages that have explicit reference parameters. Joe, please stop muddying the water. We've been over this to death. Did you not see the thread asking how to create reference parameters in Python? Subject "var or inout parm?". I noticed you were conspicuous by your absence in that little discussion. -- Steven From google at mrabarnett.plus.com Thu Dec 4 13:06:38 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 04 Dec 2008 18:06:38 +0000 Subject: schizophrenic view of what is white space In-Reply-To: <4938112F.5030706@chamonix.reportlab.co.uk> References: <4937E8E5.2090306@chamonix.reportlab.co.uk> <20081204143337.20272.1236189783.divmod.quotient.15592@ohm> <4938112F.5030706@chamonix.reportlab.co.uk> Message-ID: <49381C2E.3060707@mrabarnett.plus.com> Robin Becker wrote: > Jean-Paul Calderone wrote: > ......... >> >> You have to give the re module an additional hint that you care about >> unicode: >> >> exarkun at charm:~$ python >> Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu >> 4.2.3-2ubuntu7)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import re >> >>> print re.compile(r'\s').search(u'a\xa0b') >> None >> >>> print re.compile(r'\s', re.U).search(u'a\xa0b') >> <_sre.SRE_Match object at 0xb7dbb3a0> >> >>> >> >> Jean-Paul > ....... > > so the default behaviour differs for unicode and re working on unicode. > I suppose that won't be true in Python 3. > I'm not sure why the Unicode flag is needed in the API. I reckon that it should just look at the text that the regular expression is being applied to: if it's Unicode then follow the Unicode rules, if not then don't. From arnodel at googlemail.com Sun Dec 7 12:49:47 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 07 Dec 2008 17:49:47 +0000 Subject: Brain going crazy with recursive functions References: <6470511f-093e-42c2-a6c2-4bb90b336ac9@r15g2000prd.googlegroups.com> Message-ID: 5lvqbwl02 at sneakemail.com writes: > I'm trying to solve the 9-tile puzzle using as functional an approach > as possible. I've recently finished reading SICP and am deliberately > avoiding easy python-isms for the more convoluted scheme/functional > methods. The following function is trivial to do with for loops and > directly accessing arrays with [] syntax. I'm trying to limit myself > to the types of idioms/semantics one finds in minimal scheme, such as > in SICP. I want eventually to port this to scheme, but I know python > better, so that's where I'm starting. > > My current problem is the following. The 9-tile puzzle consists of a > list of lists like this [[1,2,3],[4,5,6],[7,8,0]], where the numbers > can be jumbled up. I'm looking for the location of the zero using > *only* recursion and operators that are similar to car/cdr. The > return value should be the row,col of the zero. For example above > the > return value would be (2,2). I'm not sure what your code does but there is a canonical way to transform a loop the call of a recursive function. I don't think I can put it into words easily so I've demonstrated it below on your 'locate_zero' function. def find_zero(square): "The normal imperative way in simple Python." i = 0 for row in square: j = 0 for n in row: if n == 0: return i, j j += 1 i += 1 def func_find_zero(square): """ The translation into recursive calls. A function is created for each loop. There are no mutations. """ def square_loop(square, i): def row_loop(row, j): if row: if row[0] == 0: return i, j else: return row_loop(row[1:], j+1) if square: res = row_loop(square[0], 0) if res is not None: return res else: return square_loop(square[1:], i+1) return square_loop(square, 0) I've intentionally made both function 'non-clever' to make the translation process more apparent. -- Arnaud From nad at acm.org Tue Dec 9 15:13:35 2008 From: nad at acm.org (Ned Deily) Date: Tue, 09 Dec 2008 12:13:35 -0800 Subject: pickling a circular object inherited from list References: <3b1bab42-657c-4b93-9236-aa5236c16826@w1g2000prk.googlegroups.com> Message-ID: In article , Klaus Kopec wrote: > >> What did I do wrong? > > Old Python version? :) > > Seems to work in 3.0 (don't have 2.6 currently to check but IMO it's > > fixed there as well). > It works for me with v3.0 as well, but not with v2.6.1 (same error as > stated before for v2.4). > > Is there any way to fix this in v2.6.1 or even v2.4? Right now I cannot > switch to v3.0 because I depend on several not compatible packages > (numpy, biopython, ...) It looks like your example can be made to work by either specifying pickle protocol 2 or by switching to cPickle. -- Ned Deily, nad at acm.org From google at mrabarnett.plus.com Sat Dec 20 20:28:15 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 21 Dec 2008 01:28:15 +0000 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: <52b8e001-2cc7-4891-8540-a3cdb6b78533@e25g2000vbe.googlegroups.com> References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> <59153e28-bf86-4158-96d9-23aa5b9f0205@j35g2000yqh.googlegroups.com> <52b8e001-2cc7-4891-8540-a3cdb6b78533@e25g2000vbe.googlegroups.com> Message-ID: <494D9BAF.6020005@mrabarnett.plus.com> r wrote: > Thanks MRAB, > except the float is not 2 decimal places, but its there > Oops! >>> '{0} {1:05} {2:.2f}'.format(s, n, f) 'python 00012 1.33' >>> '{0:s} {1:05d} {2:.2f}'.format(s, n, f) 'python 00012 1.33' From prologic at shortcircuit.net.au Mon Dec 15 22:00:23 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 16 Dec 2008 13:00:23 +1000 Subject: Copying files in directory In-Reply-To: <2a815b7d-f01f-4666-bfc6-e9c43a75019b@t3g2000yqa.googlegroups.com> References: <2a815b7d-f01f-4666-bfc6-e9c43a75019b@t3g2000yqa.googlegroups.com> Message-ID: On Tue, Dec 16, 2008 at 12:49 PM, wrote: > I'm writing a project management system, and I need the ability to > accept a directory name and move its contents to another directory. > Can someone give me a code sample that will handle this? I can't find > any "copying" functions in os or os.path. Try the shutil module. --JamesMills From clp at rebertia.com Thu Dec 4 14:48:28 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 4 Dec 2008 11:48:28 -0800 Subject: Why shouldn't you put config options in py files In-Reply-To: References: Message-ID: <47c890dc0812041148k7e636541w37915defe1b45b4b@mail.gmail.com> On Thu, Dec 4, 2008 at 11:35 AM, HT wrote: > A colleague of mine is arguing that since it is easy to write config like: > > FOO = {'bar': ('a': 'b'), 'abc': ('z': 'x')} I'll assume you meant ('a', 'b') as colons in parens don't make sense. > > in config.py and just import it to get FOO, but difficult to achieve the > same using an ini file and ConfigParser, and since Python files are just > text, we should just write the config options in the Python file and > import it. > > I can think of lots of arguments why this is a bad idea, but I don't > seem to be able to think of a really convincing one. > > Anyone? Well, it is pretty weird to be allowed to put arbitrary code in a mere config file. Have you considered using JSON for the config file format instead? It shares Python's syntax for literals, so you could do: $ cat config.json { "FOO": { "bar": ["a", "b"], "abc": ["z", "x"] } } Note that the whitespace doesn't matter. Also, you can use Python's built-on `json` module to parse the file. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > From victorsubervi at gmail.com Fri Dec 26 12:11:44 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 26 Dec 2008 18:11:44 +0100 Subject: =?ISO-8859-1?Q?Re:_Can=B4t_Surf_Python_Pages_in_Windoze?= In-Reply-To: <4954FB9F.5050702@wildenhain.de> References: <4dc0cfea0812260701q6baf0ccbj154c5b3fa2281cdb@mail.gmail.com> <4954FB9F.5050702@wildenhain.de> Message-ID: <4dc0cfea0812260911k4dbc0f2ame9cc874e067b7816@mail.gmail.com> On 12/26/08, Tino Wildenhain wrote: > > > print "Content-Type: text/html" >> print >> print """ >> > http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> >> >> >> >> >> Yeah >> >> """ >> > > this could be fine if called in CGI context. Can you state clearly what "CGI context" means? Should I be importing a CGI module? I pulled this code from a page that was working. If it had an importation of something CGI, I believe I would have tested that with all the other things that were imported that I tested, but perhaps not. I am not at my home computer to test, and will not be back online for a week. I am not worried about Zope now, but the above code, yes. TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From sopherfish at gmail.com Sun Dec 28 12:01:14 2008 From: sopherfish at gmail.com (sopherfish at gmail.com) Date: Sun, 28 Dec 2008 09:01:14 -0800 (PST) Subject: Cheetah Message-ID: 1. In Cheetah 2.0.1, both from python 2.5.2 and 2.6, after I do a #from datetime import date, most of the datetime objects seem to work fine. For example, $date(2008, 12, 15) works. However $date.today() does not work and I get an exception required argument year not found. In Python both 2.5.2 and 2.6 (without Cheetah), the today() works fine. For some reason, though, it does not work from Cheetah. 2. In reportlab 2.2, when I generate a PDF, no matter how many  s I put it, I only get one space. I am using it with python 2.6. The PDF generates fine and one $nbsp works, but for some reason, when I put it in multiple times, I still only get one space. From stefan_ml at behnel.de Tue Dec 30 08:20:50 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 30 Dec 2008 14:20:50 +0100 Subject: Any equivalent to Ruby's 'hpricot' html/xpath/css selector package? In-Reply-To: References: Message-ID: <495a2031$0$31867$9b4e6d93@newsspool3.arcor-online.net> Mark Thomas wrote: > The main difference is that lxml doesn't have CSS selector syntax Feel free to read the docs: http://codespeak.net/lxml/cssselect.html Stefan From Graham.Dumpleton at gmail.com Wed Dec 17 04:25:58 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Wed, 17 Dec 2008 01:25:58 -0800 (PST) Subject: mod_python resources References: <78064e7e-ba2c-4959-b5f8-4d1b928bc5fe@y18g2000yqn.googlegroups.com> <4lsl16-15a.ln1@archaeopteryx.softver.org.mk> Message-ID: On Dec 17, 11:10?am, ?????? ??????????? wrote: > > I'm trying again because I'm stubborn. Maybe the fourth time will be > > the charm... > > > Are there any good tutorials out there for setting up Apache with > > mod_python? > > mod_python is depreceated, nobody uses it. usemod_wsgihttp://www.modwsgi.org/ The mod_python package is not deprecated, although it could be said to be sleeping at the moment. You'll also probably still find that more new people choose mod_python over mod_wsgi. This is because it has the more obvious name to look for when Googling. It also has publisher and PSP high level handler which are still attractive to many as they are more lightweight and easier to get into than the large WSGI frameworks. Finally, the Django folks still recommend in their documentation to use mod_python. Anyway, if wanting to host a WSGI capable application, using mod_wsgi would be the more obvious choice. If wanting to write your own framework, or work at low level, basing it on WSGI rather than mod_python specific APIs would certainly be a better long term direction to take. Graham From gandalf at shopzeus.com Mon Dec 8 16:18:46 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 08 Dec 2008 22:18:46 +0100 Subject: ORB for Python and PHP Message-ID: <493D8F36.4040504@shopzeus.com> We have a problem here. We have a website written in PHP. and many programs written in Python. The communication between the components is messy. os.system calls are mixed with popen, xml-rpc and others. We would like to make it consistent and portable. We would like to use free software. What are our options? I checked these: - Bonobo is the most advanced, but it can only handle C language - FNORB is good for Python, but not for PHP - OmniORB would be very good for C and Python, but not PHP There are others but they do not support both Python and PHP. Should I implement my own ORB, or do you know a suitable solution? Thank you, Laszlo From n.kottiyath at gmail.com Tue Dec 16 15:18:17 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Tue, 16 Dec 2008 12:18:17 -0800 (PST) Subject: Can anyone suggest a good HTTP/1.1 web client? Message-ID: Hi all, I have to connect to a secure website every second to get the data and then post to it. I have been investigating on many web clients in python, but nothing fits the bill properly. The ones I tried implementing are: 1. httplib based - I created myself. (I cannot use urllib2 since I have to transfer files, and urllib2 doesnt have multipart content-type support) 2. Twisted web client. I also looked at mechanize etc too. The problems I face are - 1. I liked twisted a lot, but when I implemented it, I found that client support is there only for twisted.web and not twisted.web2. Since I connect to the same website every time, I would like to have persistent connections and since twisted.web is HTTP/1.0, persistent connection support is not yet there. Without persistent connections, I would have to have TCP connection handshake everytime and it is taking too much time. 2. Since I connect to the website every second, I have to have many connections running at the same time. I am worried that creating threads for each connection is going to be a big problem (esp if the server response is slow), since the processor will get swamped - especially since there are many other activities going on in the machine. 3. I would also like to pipe line the requests - esp if the response is slow. Other requirements: 1. HTTPS Support 2. Connection through proxy. Is there any good web client which I can use straight up? Or would I have to implement the whole thing myself? It looks like a big beast and I was wondering whether python provides it straight up. Regards K From febaen at gmail.com Tue Dec 16 12:49:12 2008 From: febaen at gmail.com (feba) Date: Tue, 16 Dec 2008 09:49:12 -0800 (PST) Subject: Free place to host python files? References: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> <32599660-2393-4e18-8c48-05d64bccbbc1@t26g2000prh.googlegroups.com> Message-ID: Stuff like code.google, sf.net, are more oriented towards serious development, not just holding random apps, aren't they? Anyway, I found MediaFire, which looks like it will suffice for now. From jon at ffconsultancy.com Tue Dec 9 21:05:47 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Wed, 10 Dec 2008 02:05:47 +0000 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <9ecfa224-ce8f-44e9-abca-008314f44e87@40g2000prx.googlegroups.com> Message-ID: Xah Lee wrote: > On Dec 8, 5:25 pm, Terry Reedy wrote: >> Lest anyone doubt that problem size is important for comparing program >> run times, consider ... > > just in case there's any doubt: > > Simply change these lines in Jon's program: > > Main[9, 512, 4] to Main[9, 512, 4.] > > and it will run faster. Only for trivial input and not for the challenge you were given. > Also, change this line: > > Block[{scene = Create[level, {0, -1, 4}, 1]}, > > to > > Block[{scene = Create[level, {0., -1., 4.}, 1.]}, Same again. > will make it faster further. (both of which are in my version. The > ?Block? can be replaced with ?With?.) That code is evaluated once to build the scene. There is no point in optimizing it. > As i said, this error in a Mathematica code in the context of speed is > a major blunder. His denial makes him a stubborn moron. That performance issue only affects trivial problems and, in particular, does not affect the problem you were trying to solve. -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From lists at cheimes.de Thu Dec 11 18:57:10 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 12 Dec 2008 00:57:10 +0100 Subject: Best way of debigging a C extension In-Reply-To: <6b20568d-8ce9-4240-8f83-b579c241d9a9@l33g2000pri.googlegroups.com> References: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> <6b20568d-8ce9-4240-8f83-b579c241d9a9@l33g2000pri.googlegroups.com> Message-ID: Paul Moore schrieb: > The trouble is, I only have mingw to build extensions, not MSVC7.1 - > so I can't build Python (and I don't know if I still have the toolkit > compiler to build with that - I certainly don't have all the pieces > installed). With Python 2.6, I guess things will be better as I have > VS2008 Express, so I can use this to build a debug Python plus my > extension. It's more work than I really want to do to go that way, but > I guess it'll work. Pyhon 2.5 doesn't support VS 2008. It has unofficial support for VS 2005 in the PCbuild8 directory. You can mail Martin von L?wis and ask him for a debug build of Python 2.5.2. I don't have the tools on my build box. > That's what I thought. I was just hoping that using a debug build of > an extension would be usable with a standard release build of Python, > as that's what will be easy for most people to set up. A debug build changes large parts of the ABI. Every PyObject struct gains additional fields, lots of checks are added to Python's memory allocation system and asserts are enabled. Debug extensions have a _d suffix for a very good reason. We aren't just trying to make *your* life harder. :) Christian From kyrie at uh.cu Wed Dec 10 17:21:51 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Wed, 10 Dec 2008 17:21:51 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: <49401C2D.4050209@egenix.com> References: <200812101401.35786.kyrie@uh.cu> <49401C2D.4050209@egenix.com> Message-ID: <200812101721.51692.kyrie@uh.cu> On Wednesday 10 December 2008 02:44:45 pm you wrote: > > Even in statically typed languages, when you override the equality > > operator/function you can choose not to return a valid answer (raise an > > exception). And it would break all the cases mentioned above (element in > > list, etc). But that isn't the right thing to do. The language > > doesn't/can't prohibit you from breaking the equality test, but that > > shouldn't be considered a feature. (a==b).all() makes no sense. > > Perhaps not in your application, but it does make sense in other > numeric applications, e.g. ones that work on vectors or matrixes. > > I'd suggest you simply wrap the comparison in a function and then > have that apply the necessary conversion to a boolean. I do numeric work... I'm finishing my MSc in applied math and I'm programing mostly with python. And I'd rather have a.compare_with(b), or a.elementwise_compare(b), or whatever name, rather than (a==b).all(). In fact, I'd very much like to have an a.compare_with(b, epsilon=e).all() (to account for rounding errors), and with python2.5, all(a.compare_with(b)). Yes, I could create an element_compare(a,b) function. But I still can't use a==b and have a meaningful result. Ok, I can (and do) ignore that, it's just one library, I'll keep track of the types before asking for equality (already an ugly thing to do in python), but the a==b behaviour breaks the lists (a in ll, ll.indexof(a)) even for elements not in numpy. ?Should I also ignore lists? The concept of equality between two arrays is very well defined, as it is also very well defined the element-by-element comparison. There is a need to test for both - then the way to test for equality should be the equality test. > > I'm certain that something could be worked out. A quick paragraph that > > took me just a few minutes to type shouldn't be construed as a PEP that > > will solve all the problems :D. > > As always: the Devil is in the details :-) Of course... -- Luis Zarrabeitia (aka Kyrie) Fac. de Matem?tica y Computaci?n, UH. http://profesores.matcom.uh.cu/~kyrie From Slaunger at gmail.com Thu Dec 4 16:18:44 2008 From: Slaunger at gmail.com (Slaunger) Date: Thu, 4 Dec 2008 13:18:44 -0800 (PST) Subject: Pythonic design patterns References: Message-ID: Thank you all for sharing your views, links and suggestions on my question. I see where this is getting, and I have extracted the following points: 1. Many classic design patterns, especially the creational ones (Factory, etc.) aren't really that useful in Python as the built-in features in the language and the new style objects has ways of doing these things far more natural than statically types languages. 2. Don't be religious about the design pattern and applying them too frantically. They may look cool, but there is a great danger for over- engineering and subsequent lower code readability, debuggability, and maintainability. 3. Seek inspiration from well-written sample code. 4. It is good to know them, but be bold sometimes and do something simpler. I think I will buy the Cookbook, not for its design patterns, but more for seing good examples of pythonic code and commonly used Python programming idioms. I already have the "Python in a Nutshell", which I like very much as a no-nonsense presentation of the language and its batteries, and that book would probably be a valuable addition to my limited collected (there are a few condensed pages concerning new- style objects, which I read over and over again). Later, if I still have the appetite for it and feel the need I might dive into some of the other resources mentioned. As a matter of fact I have visited all the links now and gotten some valuable inspirations. -- ~~~~ From gagsl-py2 at yahoo.com.ar Thu Dec 25 01:46:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Dec 2008 04:46:31 -0200 Subject: Easy-to-use Python GUI References: Message-ID: En Wed, 24 Dec 2008 21:47:07 -0200, Joel Koltner escribi?: > Is there an easy-to-use, "function"-based cross-platform GUI toolkit for > Python out there that's a little more sophisticated than EasyGui? Try Dabo http://dabodev.com/ -- Gabriel Genellina From xahlee at gmail.com Thu Dec 11 14:12:25 2008 From: xahlee at gmail.com (Xah Lee) Date: Thu, 11 Dec 2008 11:12:25 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <91bf5d87-0154-472b-9350-e3290ab867e1@k1g2000prb.googlegroups.com> Message-ID: <49a1717b-36f0-402c-a633-a7df23dca0bf@35g2000pry.googlegroups.com> On Dec 11, 6:50 am, the.brown.dragon.b... at gmail.com wrote: ;; Chicken Scheme. By the.brown.dragon... at gmail.com (require 'srfi-1) (define (normalize vec) (map (cute / <> (sqrt (reduce + 0 (map (cute expt <> 2) vec)))) vec)) Is it possible to make it work in scsh? (i'm running scsh 0.6.4, and don't know Scheme lisp well) Xah ? http://xahlee.org/ ? From clp at rebertia.com Fri Dec 12 07:44:31 2008 From: clp at rebertia.com (Chris Rebert) Date: Fri, 12 Dec 2008 04:44:31 -0800 Subject: var or inout parm? In-Reply-To: References: Message-ID: <47c890dc0812120444uc3e8b3djd0fb181935ee51e@mail.gmail.com> On Fri, Dec 12, 2008 at 4:34 AM, sturlamolden wrote: > You cannot modify parameters by rebinding. x = x + 1 is a rebinding. x > += 1 is not. Python begs to differ, as those two statements are both semantically identical in this case: Python 2.6 (r26:66714, Nov 18 2008, 21:48:52) [GCC 4.0.1 (Apple Inc. build 5484)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> x = 2 >>> id (x) 8405372 >>> x += 1 >>> id(x) 8405360 >>> x = x + 1 >>> id(x) 8405348 If you were talking about lists rather than integers though, you'd be absolutely correct, as the += ends up being a method call to __iadd__ instead of a plain assignment. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From piyush.subscription at gmail.com Sun Dec 21 02:12:19 2008 From: piyush.subscription at gmail.com (Piyush Anonymous) Date: Sun, 21 Dec 2008 12:42:19 +0530 Subject: trapping all method calls in a class... Message-ID: <19ac19520812202312q71409182kb58a0f7aaf3b0e74@mail.gmail.com> hi, i need to trap all method calls in a class in order to update a counter which is increased whenever a method is called and decreased whenever method returns. in order to that i am trying to write a decorator for all the methods. see the code here with error. ------- http://codepad.org/2w7JVvDB ---- any suggestions? any other better way of doing it? -------------- next part -------------- An HTML attachment was scrubbed... URL: From oyvinrog at gmail.com Fri Dec 19 18:02:08 2008 From: oyvinrog at gmail.com (=?ISO-8859-1?B?2Hl2aW5k?=) Date: Fri, 19 Dec 2008 15:02:08 -0800 (PST) Subject: Jarow-Winkler algorithm: Measuring similarity between strings Message-ID: <4f351b3b-4da7-4fee-a1ac-c42179d430f5@s9g2000prm.googlegroups.com> Based on examples and formulas from http://en.wikipedia.org/wiki/Jaro-Winkler. Useful for measuring similarity between two strings. For example if you want to detect that the user did a typo. def jarow(s1,s2): """ Returns a number between 1 and 0, where 1 is the most similar example: print jarow("martha","marhta") """ m= jarow_m(s1,s2) t1 = jarow_t(s1,s2) t2 = jarow_t(s2,s1) t = float(t1)/float(t2) d = 0.1 # this is the jaro-distance d_j = 1.0/3.0 * ((m/len(s1)) + (m/len(s2)) + ((m - t)/float(m))) # if the strings are prefixed similar, they are weighted more heavily l = winkler_l(s1,s2) print l return d_j + (l * 0.1 * (1 - d_j)) def winkler_l(s1,s2): """ Number of the four first characters matching """ l = 0 counter = 0 for s_j,s_i in zip(s1,s2): if s_j == s_i: l += 1 counter += 1 if counter > 4: break return l def jarow_m(s1,s2): """ Number of matching characters """ m = 0 d = {} for s in s1: d[s] = True for s in s2: if d.has_key(s): m += 1 return m def jarow_t(s1,s2): """ Number of transpositions """ t= 0 pos ={} counter = 0 for s in s1: pos[s] = counter counter += 1 counter = 0 for s in s2: if pos.has_key(s): if pos[s] != counter: t += 1 counter += 1 return t From google at mrabarnett.plus.com Wed Dec 17 10:21:02 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 17 Dec 2008 15:21:02 +0000 Subject: Transferring a file over sockets In-Reply-To: <002801c96050$251d57e0$0d00a8c0@hendrik> References: <002801c96050$251d57e0$0d00a8c0@hendrik> Message-ID: <494918DE.4010306@mrabarnett.plus.com> Hendrik van Rooyen wrote: > Ferdinand Sousa wrote: > >> ========================================================== > .# file receiver >> # work in progress >> >> import socket >> >> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >> HOST = '192.168.1.17' >> PORT = 31400 >> >> s.bind((HOST, PORT)) >> s.listen(3) >> conn, addr = s.accept() >> print 'conn at address',addr >> conn.send('READY') >> f = open('C:\\Documents and Settings\\USER\\Desktop\\test.pdf','wb') >> fsize=int(conn.recv(8)) >> print 'File size',fsize >> f.write(conn.recv(fsize)) > > This recv is not guaranteed to actually receive the number of > characters you are asking for - it will stop when it has received that > many, yes, but it may return with less, or even none if there is a > time out set. > > The TCP is a more or less featureless stream of characters. > > Consider including a start marker so you know where the lesson starts. > If you do this, consider the possibility of having a "false sync". > Sending/receiving the length is good - also google for "netstring" > Google for "escaping". > > Consider writing a loop to receive until the required length has been > received - look at the docs for the recv function - it can tell you how > much has been received. > >> f.close() >> conn.close() >> s.close() >> >> raw_input('Press any key to exit') >> >> >> =========================================================== >> >> # file sender !!! >> # Work in progress >> >> import socket, os >>from stat import ST_SIZE >> >> HOST = '192.168.1.17' >> PORT = 31400 # Arbitrary non-privileged port >> >> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >> >> s.connect((HOST,PORT)) >> if s.recv(5)!='READY': >> raw_input('Unable to connect \n\n Press any key to exit ...') >> s.close() >> exit() >> >> f=open('C:\\Documents and Settings\\USER\\Desktop\\t.pdf', 'rb') >> fsize=os.stat(f.name)[ST_SIZE] >> >> s.send(str(fsize)) >> s.send(f.read()) > > Are you sure that the send will send all the chars > that you ask it to send? > > If yes - why do you think this? > > What are the values that the send can return? > >> s.close() >> f.close() >> >> =========================================================== > You're also sending the length as a bytestring str(fsize), which will have an unknown length, but you're receiving the length as exactly 8 bytes. Either mark the end of the length in some way (with '\n'?) and look for that when receiving, or pad what you send to exactly 8 bytes (str(fsize).zfill(8)). From zac256 at gmail.com Tue Dec 2 19:47:27 2008 From: zac256 at gmail.com (Zac Burns) Date: Tue, 2 Dec 2008 16:47:27 -0800 Subject: Reverse zip() ? In-Reply-To: References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> Message-ID: <333edbe80812021647i4621271p7f87dff8d0926951@mail.gmail.com> There is a problem with this however, which prompted me to actually write an unzip function. One might expect to be able to do something like so (pseudocode)... def filesAndAttributes(): files = walk() attributes = [attr(f) for f in files] return zip(files, attributes) files, attributes = zip(*filesAndAttributes()) The corner case is when dealing with empty lists and there aren't enough items to unpack. The unzip function therefore has an elementsForEmpty keyword that handles this case. Perhaps something like this could be added to zip? I have not (yet) dealt with the PEP process, so I'm not sure where that starts. Perhaps a discussion could start here. -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer (Digital Overlord) Zindagi Games On Tue, Dec 2, 2008 at 4:14 PM, John Machin wrote: > On Dec 3, 7:12 am, Stefan Behnel wrote: >> Andreas Waldenburger wrote: >> > we all know about the zip builtin that combines several iterables into >> > a list of tuples. >> >> > I often find myself doing the reverse, splitting a list of tuples into >> > several lists, each corresponding to a certain element of each tuple >> > (e.g. matplotlib/pyplot needs those, rather than lists of points). >> >> > This is of course trivial to do via iteration or listcomps, BUT, I was >> > wondering if there is a function I don't know about that does this >> > nicely? >> >> I think you're asking about zip(): >> >> >>> l=[1,2,3] >> >>> zip(l,l) >> [(1, 1), (2, 2), (3, 3)] >> >>> zip(*zip(l,l)) >> [(1, 2, 3), (1, 2, 3)] >> > > Here's a version that makes it slightly easier to comprehend: > > Q: I know how to zip sequences together: > | >>> a = (1, 2, 3) > | >>> b = (4, 5, 6) > | >>> z = zip(a, b) > | >>> z > | [(1, 4), (2, 5), (3, 6)] > but how do I reverse the process? > > A: Use zip()! > | >>> a2, b2 = zip(*z) > | >>> a2 > | (1, 2, 3) > | >>> b2 > | (4, 5, 6) > > Cheers, > John > -- > http://mail.python.org/mailman/listinfo/python-list > From mail at johnohagan.com Sun Dec 21 21:02:31 2008 From: mail at johnohagan.com (John O'Hagan) Date: Mon, 22 Dec 2008 02:02:31 +0000 Subject: Namespaces, multiple assignments, and exec() In-Reply-To: <200812201541.19968.mail@johnohagan.com> References: <200812200234.33852.research@johnohagan.com> <200812201541.19968.mail@johnohagan.com> Message-ID: <200812220202.31393.mail@johnohagan.com> On Sat, 20 Dec 2008, John O'Hagan wrote: > On Sat, 20 Dec 2008, Terry Reedy wrote: > > John O'Hagan wrote: > > > I have a lot of repetitive assignments to make, within a generator, > > > that use a function outside the generator: > > > > > > var1 = func("var1", args) > > > var2 = func("var2", args) > > > var3 = func("var3", args) > > > etc... > > > > > > In each case the args are identical, but the first argument is a string > > > of the name being assigned. It works fine but I'd like to reduce the > > > clutter by doing the assignments in a loop. I've tried using exec(): > > > > > > for name in name_string_list: > > > exec(name + ' = func(\"' + name + '\", args)') > > > > > > but in the local namespace it doesn't understand func(), and if I give > > > it globals() it doesn't understand the args, which come from within the > > > generator. > > > > > > What's a good way to do this kind of thing? > > > > Put everything in your own namespace > > > > myvars={} > > for name in namelist: > > myvars[name]=func(name,args) > > Likely I'm missing something, but don't I still have to do > > var1 = myvars['var1'] > var2 = myvars['var2'] > var3 = myvars['var3'] > ...etc. > > to make the assignments? And of course I am missing the fact that I can now do the exec loop over myvars{} in the local namespace. Doing this, however, exposed some behaviour that surprises me. Inside my generator, doing: exec('foo = 7') in locals() print foo foo = 3 produces an UnboundLocalError. In case it's relevant, the error I get inside the generator if I don't specify local()s is: SyntaxError: unqualified exec is not allowed in function 'sequence_engine' it contains a nested function with free variables But doing the same thing in a simple test generator, even if it calls outside functions, works as I expect. Removing any subsequent reassignments of the same name fixes the error, and as it happens I can do this, but I'm curious, without me posting the whole generator (it's long), why doesn't the above exec() assignment work in that context? Thanks, John From Scott.Daniels at Acm.Org Thu Dec 25 19:52:10 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 25 Dec 2008 16:52:10 -0800 Subject: python interpreter black window In-Reply-To: References: Message-ID: Chris Rebert wrote: > On Thu, Dec 25, 2008 at 3:32 PM, Gandalf wrote: >> I use WX gui so the user doesn't actually need it, Is their any way to >> hide it? > > Make sure your Python program is run by pythonw.exe as opposed to python.exe > pythonw.exe exists specifically for the purpose of suppressing the DOS > Box on Windows. Absolutely right. Vy the way, naming your "main" program file something.pyw, rather than something.py is one of the ways ro do this. --Scott David Daniels Scott.Daniels at Acm.Org From scalet at yebu.de Mon Dec 8 17:09:23 2008 From: scalet at yebu.de (resi147) Date: Mon, 8 Dec 2008 14:09:23 -0800 (PST) Subject: close has no effect on Mac OSX Python 3.0 Message-ID: <83b43edf-81e5-4116-ad7b-2dcacde2d101@f3g2000yqf.googlegroups.com> I'm wondering if it's really a bug since it's so trivial: fp = open('/etc/services') ct = fp.read(1048) print(ct[-80:], end='') fp.close() ct = fp.read(17) print(ct) the second read should fail, but happily continues reading the file. Really a bug? As said in the subject, I use MacOSX 10.5.5 with Python 3.0, officially released these days. Karl From alan.chambers at cambridgeconsultants.com Fri Dec 12 12:08:45 2008 From: alan.chambers at cambridgeconsultants.com (alan.chambers at cambridgeconsultants.com) Date: Fri, 12 Dec 2008 09:08:45 -0800 (PST) Subject: Python extension: callbacks blocked when holding button down Message-ID: <05533b81-de89-4ee2-90c5-8f19533b65a9@g17g2000prg.googlegroups.com> I'm developing a Python extension. It's a wrapper for some firmware, and simulates the target hardware environment. I'm using wxPython. I pass a function to the extension so it can let Python know about certain events. The code is currently single threaded. My problem is that the callback seems to have no effect if it is called while I am holding down a wxButton in the Python GUI. Long button presses are significant in the firmware so this seems a bit limiting. Can anyone explain what is going on? What's the best workaround? Thanks. Al From jredgrave at capisco.com Tue Dec 2 17:12:33 2008 From: jredgrave at capisco.com (Jon Redgrave) Date: Tue, 2 Dec 2008 14:12:33 -0800 (PST) Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> Message-ID: <9566ebea-d6b9-45bf-9bba-df259508efd3@w3g2000yqc.googlegroups.com> On Dec 2, 2:35?pm, Astley Le Jasper wrote: ... Try using the "screen" utility - change the line in your crontab: cd /home/myusername/src && python myscript.py to cd /home/myusername/src && screen -dmS mypthon python -i myscript.py then once cron has started your program attach to the console using >> screen -r mypython (using python -i leaves you at the python prompt if the script just terminates) I email myself and drop into the pdb debugger on an exception, then use screen to debug the system From kay.schluehr at gmx.net Tue Dec 9 06:05:45 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 9 Dec 2008 03:05:45 -0800 (PST) Subject: python3.0 - any hope it will get faster? References: <6q70udFb5dmqU1@mid.dfncis.de> Message-ID: On 9 Dez., 11:51, Helmut Jarausch wrote: > Hi, > > I was somewhat surprised when I ran pystones with python-2.5.2 and > with python-3.0 > > On my old/slow machine I get > > python-2.5.2 > from test import pystone > pystone.pystones() > gives (2.73, 18315.018315018315) > > python-3.0 > from test import pystone > pystone.pystones() > gives (4.2700000000000005, 11709.601873536298) > > That's a drop of 36% ! > > I know that processing unicode is inherently slower, > but still I was surprised that it's so much slower. On my WinXP notebook python-3.0 >>> from test import pystone >>> pystone.pystones() (1.1734318188484849, 42610.059823557647) python-2.5.1 >>> from test import pystone >>> pystone.pystones() (1.2927221197107452, 38678.072601703308) From gagsl-py2 at yahoo.com.ar Wed Dec 10 15:10:38 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 10 Dec 2008 18:10:38 -0200 Subject: SequenceMatcher bug ? References: <67253331-5b36-4018-b15a-c0b86c5342d3@r37g2000prr.googlegroups.com> <3d8ba4fe-0eb0-462c-b243-c157a9c0fe6d@i18g2000prf.googlegroups.com> Message-ID: En Wed, 10 Dec 2008 15:14:20 -0200, eliben escribi?: >> > My system is Gentoo, which installs python from source. ?Maybe gentoo >> > applies patches that the binary releases don't have. >> >> I can't reproduce the problem. I got exactly the same results >> (0.999...) ? >> with all the releases I have at hand, ranging from 3.0 back to 2.1.3, >> all ? >> on Windows. > >> Andhttp://try-python.mired.org/says the same thing. >> > > What ? This can't be. > > 1. Go to http://try-python.mired.org/ > 2. Type > import difflib > 3. Type > difflib.SequenceMatcher(None, [4] + [5] * 200, [5] * 200).ratio() > > Don't you get 0 as the answer ? Ah, but that isn't the same expression you posted originally: SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + [5]).ratio() Using *that* expression I got near 1.0 always. But leaving out the [5] at the end, it's true, it gives the wrong answer. Old Python 2.1.3 didn't have this problem: Python 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> import difflib >>> difflib.SequenceMatcher(None, [4] + [5] * 500, [5] * 500).ratio() 0.99900099900099903 >>> difflib.SequenceMatcher(None, [4] + [5] * 200, [5] * 200).ratio() 0.99750623441396513 >>> difflib.SequenceMatcher(None, [4] + [5] * 100, [5] * 100).ratio() 0.99502487562189057 I've updated the tracker item. -- Gabriel Genellina From mail at microcorp.co.za Tue Dec 16 05:27:38 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 16 Dec 2008 12:27:38 +0200 Subject: alt.possessive.its.has.no.apostrophe References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> <9ImdneOohuZCNdvUnZ2dnUVZ_s3inZ2d@earthlink.com> Message-ID: <000901c95f69$003a5f00$0d00a8c0@hendrik> "Dennis Lee Bieber" wrote: 8<----- stuff blaming Davy for "aluminum" ---------- > Isn't Davy a Brit? No, he was a Brit. He's dead now. His safety lamp lives on. It's a good thing its got that heat-sink sieve- it's enabled countless miners to flee when they see its change of colour. Thus it's saved the lives of a lot of canaries, and that's of ecological importance. Spot the apostrophe error, if you can. - Hendrik From rt8396 at gmail.com Tue Dec 16 17:24:23 2008 From: rt8396 at gmail.com (r) Date: Tue, 16 Dec 2008 14:24:23 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <355f1cfe-6abb-4d2c-8bf4-3aa62e713c1f@w34g2000yqm.googlegroups.com> Message-ID: On Dec 15, 7:15?am, Luis M. Gonz?lez wrote: > On Dec 15, 1:38?am, cm_gui wrote: > > > hahaha, do you know how much money they are spending on hardware to > > make > > youtube.com fast??? > > > > By the way... I know of a very slow Python site called YouTube.com. In > > > fact, it is so slow that nobody ever uses it. > > Buddy, just stop whining and go with c++ if it makes you happy. > By the way, what's the blazingly fast application you need to write so > desperately? > What kind of performance problem have you find in python that makes > you so unhappy? > What are you going to do with all the extra speed provided by c++ (a > Hello World! ?)... Still no reply from cm_gui, he must have googled "C hello world" :D From ldo at geek-central.gen.new_zealand Sun Dec 7 02:32:21 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 07 Dec 2008 20:32:21 +1300 Subject: Don't you just love writing this sort of thing :) References: <32cf4a79-a6e3-4250-9b5a-1ec80c748618@j32g2000yqn.googlegroups.com> Message-ID: In message , Arnaud Delobelle wrote: > * you seem to disregard the fact that in 'programming language' there > is the word 'language'. A language is a way to _communicate_ > information, in the case of a programming language you communicate > it to the computer but also to other human beings. It was Niklaus Wirth, I think who pointed out that programming languages are not properly "languages" but are actually "notations". Like mathematics is a notation. And mathematics, too, is a predominantly functional, not a procedural, notation. Could that be why so many people are frightened of functional constructs, like my code example and things like lambdas? Because they look too much like mathematics? From tino at wildenhain.de Mon Dec 29 06:54:57 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 29 Dec 2008 12:54:57 +0100 Subject: Windows SSH (remote execution of commands) - Python Automation In-Reply-To: <7FAD6FCE52421841A11B441DEF3A88CA01F09006@ZMY16EXM70.ds.mot.com> References: <7FAD6FCE52421841A11B441DEF3A88CA01F09006@ZMY16EXM70.ds.mot.com> Message-ID: <4958BA91.2070105@wildenhain.de> Hi, Narasimhan Raghu-RBQG84 wrote: > Hi experts, > > I am looking for some information on how to automate remote login to a > UNIX machine using ssh from a windows XP box. > > Possible way: > > 1. Use putty (or any other ssh client from windows XP). -- Can be > automated with command line parameters. The problem is that I am able to > login - Putty window opens up as well. But obviously I am unable to run > any commands in that. I need to find something like a handle to that > Putty window so that I can execute commands there. Obviously putty is one (of several) terminal emulators (or in short gui clients) for ssh protocol. This means they are made for interactive work with mouse and keyboard rather then for command automation. Its easy if you just use one of the many command line ssh clients. You can use os.popen() and friends or the command module to work with them. There is also another solution: http://www.lag.net/paramiko/ which implements the ssh protocol in python so you can do more and have finer control over the processes and channels (for example file transfer and command control w/o resort to multiple connections) This is a little bit harder of course. Also, sometimes its more easy and relieable to just use cron on unix side. This works much much better then Task scheduler on windows btw. Regards Tino > Can anyone provide me some help in achieving this ? > > > Thanks, > > -- > *Raghu* > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From skip at pobox.com Tue Dec 30 09:47:30 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 30 Dec 2008 08:47:30 -0600 Subject: Python list's mail server in DNSBL ? In-Reply-To: <495A31B9.6020507@shopzeus.com> References: <495A2825.4070000@shopzeus.com> <495A2957.6090805@holdenweb.com> <495A31B9.6020507@shopzeus.com> Message-ID: <18778.13442.50043.370958@montanaro-dyndns-org.local> >> > Ask your Mail-/DNS-Administrator to correct HELO and DNS MX >> > settings and to get removed from DNSBLs; in >> > bogusmx.rfc-ignorant.org >> > >> > >> > Please reply to if you feel this message to >> > be in error. I went to rfc-ignorant.org and looked up python.org. python.org was in their database from 2004-08-27 to 2005-11-09. It's not been there since. My guess is that chello.at is having problems interpreting rfc-ignorant.org records. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From tjreedy at udel.edu Fri Dec 5 13:01:06 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 05 Dec 2008 13:01:06 -0500 Subject: RELEASED Python 3.0 final In-Reply-To: <5926cb50-e53f-4e9e-8672-b4e29e2280b5@r36g2000prf.googlegroups.com> References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> <5926cb50-e53f-4e9e-8672-b4e29e2280b5@r36g2000prf.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Andreas Waldenburger: >> Whenever has it been a pythonic ideal to "not allow" stuff? You get >> warnings. Everything else is up to you. > > It's a strong source for bugs, especially for newbies, that I have > hoped to see removed from Python3 (my first request of this was years > ago). I was nearly sure to see this wart removed from Python3, and now > I hear it's presents still. I don't understand why they haven't fixed > it. Did you or someone fine a specific rejection of disallowing mixture in 3.0, or did no one specifically suggest it and offer to make the change? From pdorange at pas-de-pub-merci.mac.com Mon Dec 22 08:51:32 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Mon, 22 Dec 2008 14:51:32 +0100 Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <1iscu14.oixxplpgajabN%pdorange@pas-de-pub-merci.mac.com> Stephen Thorne wrote: > > def sign(x): > > if x==0.0: > > return 0.0 > > elif x>0.0: > > return 1.0 > > else: > > return -1.0 > > Isn't this approximately this? :: > > def sign(x): > return float(cmp(x, 0)) Yes cmp() is probably the closest function to sign. I'm new to python and here i discover at least 4 methods, i just make a small script for timing those methods (100 000 times each on a set of 10 values). I do not use timeit, i can't make it work easyly as it need a standalone env for each test. ---- the test script -------------------- #!/usr/bin/env python from math import atan2 import time def sign_0(x): if x==0.0: return 0.0 elif x>0.0: return 1.0 else: return -1.0 def sign_1(x): if x > 0 or (x == 0 and atan2(x, -1.) > 0.): return 1 else: return -1 def sign_2(x): return cmp(x, 0) sign_3 = lambda x:+(x > 0) or -(x < 0) def main(): candidates=[1.1,0.0,-0.0,-1.2,2.4,5.6,-8.2,74.1,-23.4,7945.481] startTime = time.clock() for i in range(100000): for value in candidates: s=sign_0(value) print "sign_0 : ",time.clock() - startTime startTime = time.clock() for i in range(100000): for value in candidates: s=sign_1(value) print "sign_1 : ",time.clock() - startTime startTime = time.clock() for i in range(100000): for value in candidates: s=sign_2(value) print "sign_2 : ",time.clock() - startTime startTime = time.clock() for i in range(100000): for value in candidates: s=sign_3(value) print "sign_3 : ",time.clock() - startTime if __name__ == '__main__' : main() ---- the results ----------------------------- My config : iMac (2,66 GHz intel dual core 2 duo) MacOS X 10.5.5 Python 2.5.1 sign_0 = 0.4156 second (0%) sign_1 = 0.5316 second (+28%) sign_2 = 0.6515 second (+57%) sign_3 = 0.5244 second (+26%) ---- conclusions ------------------------------- 1/ python is fast 2/ method (0) is the fastest 3/ cmp method (2) is the slowest 4/ the precise one (IEEE 754) is also fast (1) -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From casey.mcginty at gmail.com Mon Dec 1 23:21:13 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Mon, 1 Dec 2008 18:21:13 -1000 Subject: Google App Engine Code Challenge - write a tetris playing algorithm In-Reply-To: <10304c580812011932l7ef375fcv4149f66064d02a30@mail.gmail.com> References: <10304c580812011932l7ef375fcv4149f66064d02a30@mail.gmail.com> Message-ID: Well, I think its a cool idea. I might try it out if I can find some free cycles. And does the game logic assume the pieces come straight down? For example, what if you wanted to move a piece to the left or right after its past some vertical obstruction? For example If you place and upside down 'j' or 'l', is there any way to fill in the two blocked squares, without removing the top portion first? - Casey -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Tue Dec 23 04:59:07 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 23 Dec 2008 09:59:07 +0000 Subject: join a samba domain In-Reply-To: <1a326512-3c74-404d-9c51-fde35f39702e@t39g2000prh.googlegroups.com> References: <0f625f1a-6928-46b6-b620-2efa0e1b32aa@t39g2000prh.googlegroups.com> <494fd597$0$90267$14726298@news.sunsite.dk> <73194a24-f14e-46f1-8789-886ba4729084@r15g2000prd.googlegroups.com> <1a326512-3c74-404d-9c51-fde35f39702e@t39g2000prh.googlegroups.com> Message-ID: <4950B66B.4020907@timgolden.me.uk> Toff wrote: > On 22 d?c, 19:37, Toff wrote: >> On 22 d?c, 18:59, Jens Henrik Leonhard Jensen >> >> wrote: >>> Toff wrote: >>>> d = c.Win32_ComputerSystem >>>> d.JoinDomainOrWorkGroup(None, 3, "mydom", "mydompw", r"admin\\mydom") >>> Shouldn't r"admin\\mydom" be "admin\\mydom" or r"admin\mydom". >>> Or maybe just "admin" >>> /Jens Henrik >> you are right but i've got the same error. > > the more i look at my script the more i think it s a BUG. > > #ALL works great > import wmi > c = wmi.WMI() > for computer in c.Win32_ComputerSystem(): > if computer.PartOfDomain: > print computer.Domain #DOMCD > print computer.SystemStartupOptions # (u'"Microsoft Windows XP > Professionnel" /noexecute=optin /fastdetect',) > > #error message > computer.JoinDomainOrWorkGroup('DOMCD', 'adminLocal', 'admin\ > \DOMCD',None,3 ) Try: computer.JoinDomainOrWorkgroup (...) note the lowercase "group" TJG From kajnilsson5 at hotmail.com Sun Dec 28 19:20:09 2008 From: kajnilsson5 at hotmail.com (kajnilsson5 at hotmail.com) Date: Sun, 28 Dec 2008 16:20:09 -0800 (PST) Subject: How to get involved Message-ID: <33e09baf-00b5-40f0-9b5f-152c370941e6@r36g2000prf.googlegroups.com> I'm new to the open source comunnity and I was wondering if there are any bugs that I can trouble shoot or just some beginner tasks I can be sent? Kaj Nilsson Kajnilsson5 at hotmail.com From tino at wildenhain.de Wed Dec 3 15:32:55 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Wed, 03 Dec 2008 21:32:55 +0100 Subject: python to parse excel file csv format In-Reply-To: <4936DC35.6010404@mrabarnett.plus.com> References: <4936DC35.6010404@mrabarnett.plus.com> Message-ID: <4936ECF7.3040400@wildenhain.de> MRAB wrote: > Jay Jesus Amorin wrote: >> This is how i do it, but it runs with error. Kindly help >> >> >> #!/usr/bin/env python >> >> import csv, sys, os >> filename = (sys.argv[1]) >> reader = csv.reader(open(filename, "rb"), delimiter=',', >> quoting=csv.QUOTE_NONE) >> >> try: >> for row in reader: >> os.popen("chown row[0] row[1]") > This should be: > > os.popen("chown %s %s" % (row[0], row[1])) > > or: > > os.popen("chown %s %s" % tuple(row)) No, it should really be os.popen(("chown",row[0],row[1])) or better yet, for fmodes,fname in reader: os.popen(("chown",fmodes,fname)) or even plus better: for fmodes,fname in reader: os.chmod(fname,fmodes) (Both my examples avoid problems with unquoted filenames) Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From worldgnat at gmail.com Mon Dec 1 12:30:42 2008 From: worldgnat at gmail.com (worldgnat) Date: Mon, 1 Dec 2008 09:30:42 -0800 (PST) Subject: HTML File Parsing References: <49077399$0$31880$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <495fad71-26dc-426d-b78d-7aa6eabefe2d@t11g2000yqg.googlegroups.com> On Oct 28, 3:18?pm, Stefan Behnel wrote: > Felipe De Bene wrote: > > I'm having problems parsing an HTML file with the following syntax : > > >
  • User IDName > BGCOLOR='#c0c0c0'>Date
    > > ? ? > > ? ? > > and so on.... > > > whenever I feed the parser with such file I get the error : > > > HTMLParser.HTMLParseError: bad end tag: "", at > > line 515, column 45 > > Your HTML page is not HTML, i.e. it is broken. Python's HTMLParser is not made > for parsing broken HTML. However, you can use the parse of lxml.html to fix up > your HTML for you. > > http://codespeak.net/lxml/ > > Stefan It doesn't just choke on bad HTML, it also chokes on javascript that writes HTML, e.g. document.write(' wrote: >En Wed, 10 Dec 2008 15:14:20 -0200, eliben escribi?: > >> What ? This can't be. >> >> 1. Go to http://try-python.mired.org/ >> 2. Type >> import difflib >> 3. Type >> difflib.SequenceMatcher(None, [4] + [5] * 200, [5] * 200).ratio() >> >> Don't you get 0 as the answer ? > >Ah, but that isn't the same expression you posted originally: > >SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + [5]).ratio() > >Using *that* expression I got near 1.0 always. But leaving out the [5] at >the end, it's true, it gives the wrong answer. >... >I've updated the tracker item. Your assessment that it is the same problem as #1528074 is correct. It's the "popularity" optimization. The key here is that the second sequence consists of more than 200 identical items. For example, all of the following give the same bad result: difflib.SequenceMatcher(None, [4] + [5] * 200, [5] * 200).ratio() difflib.SequenceMatcher(None, [4] + [5] , [5] * 200).ratio() difflib.SequenceMatcher(None, [4] , [5] * 200).ratio() If you print get_matching_blocks(), you'll see that there are none, because the "b" sequence is optimized completely away. The #1528074 calls it "working by designed" and suggests updating the doc. However, I would argue that it's worth checking for this. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From saju.pillai at gmail.com Thu Dec 11 09:02:30 2008 From: saju.pillai at gmail.com (Saju Pillai) Date: Thu, 11 Dec 2008 06:02:30 -0800 (PST) Subject: How to convert uint64 in C into Python 32bit Object [ I am using Python2.2 ] References: <069f0d65-a3d5-4e8f-a85b-c53743ab99d0@i18g2000prf.googlegroups.com> <8485fb8f-4425-436d-9e0b-2079c80c9802@q26g2000prq.googlegroups.com> <6b710b67-0e91-4c55-8ef7-23891addfc51@q26g2000prq.googlegroups.com> Message-ID: <3ddb340b-83f9-44b0-8b4e-7a4f05d3a999@g17g2000prg.googlegroups.com> On Dec 11, 6:45?pm, Explore_Imagination wrote: > On Dec 11, 4:45 am, John Machin wrote: > > > > > On Dec 11, 9:49 am, Explore_Imagination > > wrote: > > > > Hi all > > > > I am new to C and python ... I want to convert C data type uint64 > > > variable into the Python 32bit Object. I am currently using Python 2.2 > > > [ It is necessary to use it ] > > > > Kindly give your suggestion how and in which way I can achieve this > > > task. > > > I'm not sure what you mean by "the Python 32bit Object". A Python int > > object holds a signed 32-bit integer. A Python long object holds a > > signed integer of arbitrary size. You will need to convert your uint64 > > into a Python long; then, if necessary, check that the result will fit > > in an int (result <= sys.maxint). > > > If the "C variable" is in an 8-byte string that you have read from a > > file, the unpack function in the struct module will do the job. > > Assuming your computer is little-endian: > > > >>> maxu64 = '\xff' * 8 # example input string > > >>> import struct > > >>> result = struct.unpack(' > >>> result > > > 18446744073709551615L>>> 2 ** 64 - 1 > > > 18446744073709551615L > > > If however you mean that in C code you need to build a Python object > > to pass over to Python code: According to the Python/C API Reference > > Manual (http://www.python.org/doc/2.2.3/api/longObjects.html): > > > PyObject* PyLong_FromUnsignedLongLong(unsigned long long v) > > ? ? Return value: New reference. > > ? ? Returns a new PyLongObject object from a C unsigned long long, or > > NULL on failure. > > > If however you mean something else, .... > > > HTH, > > John > > Thanks for your feedback ... Actually I want to pass unit64 variable > in C to python > but at the same time I want to have a generic code which should work > on both little-endian > and big endian architectures > > Any suggestions ? I am not sure if endianness comes into the picture. As long as sizeof (uint64) == sizeof(unsigned long long) on your platform, python should have no problem accepting the return value of PyLong_FromUnsignedLongLong(uint64_var); srp -- http://saju.net.in From joe at strout.net Thu Dec 11 19:01:37 2008 From: joe at strout.net (Joe Strout) Date: Thu, 11 Dec 2008 17:01:37 -0700 Subject: any Python developers available in the Denver area? Message-ID: <7CFB9612-786D-488C-8B98-4002FABB0465@strout.net> My company is considering a contract job that would require some development staff on the client site in Denver. We'd like to subcontract some of that work. If you're a good Python coder in the Denver area, and would be available at least three days a week starting in January, please send me email privately. Thanks, - Joe From Scott.Daniels at Acm.Org Fri Dec 19 19:18:03 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 19 Dec 2008 16:18:03 -0800 Subject: IDLE doesn't show stderr output from extension modules In-Reply-To: <6406df08-36bb-4cd8-a356-6d563c2eac7f@e1g2000pra.googlegroups.com> References: <6406df08-36bb-4cd8-a356-6d563c2eac7f@e1g2000pra.googlegroups.com> Message-ID: Brian Cole wrote: > I'm importing an extension module created with SWIG. When working with > the module interactively in IDLE there should be warning and error > messages printed to stderr by the extension module. However, these are > not being caught by the IDLE window, they are going directly to the > terminal that was used to start IDLE. However if the extension module is printing to stderr via non-Python function calls (e.g. C or C++ or Fortran), Idle and Python have no chance to get to the output. If you are using Python calls for the I/O, check if some variant of bug 3926's fix code solves your problems. --Scott David Daniels Scott.Daniels at Acm.Org From martin at v.loewis.de Tue Dec 2 15:25:23 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Tue, 02 Dec 2008 21:25:23 +0100 Subject: Multiple Versions of Python on Windows XP In-Reply-To: References: <4934de22$0$27863$9b622d9e@news.freenet.de> <493592EE.9090005@v.loewis.de> Message-ID: <493599B3.8070606@v.loewis.de> > Using a right click, one can open any .py file with say SciTe. Within > SciTe, one can Run the current file. > > It would be good to have the appropriate version (my use of "default") > preselected. I don't know how SciTe choses the version of Python to run. In the sense in why you use the word, there might just not be a "default" version of Python on Windows. Somebody who knows SciTe better may correct me. Regards, Martin From v+python at g.nevcal.com Tue Dec 2 03:56:13 2008 From: v+python at g.nevcal.com (Glenn Linderman) Date: Tue, 02 Dec 2008 00:56:13 -0800 Subject: Multiple Versions of Python on Windows XP In-Reply-To: <4934E3BF.7000403@v.loewis.de> References: <4934de22$0$27863$9b622d9e@news.freenet.de> <4934E183.9020404@g.nevcal.com> <4934E3BF.7000403@v.loewis.de> Message-ID: <4934F82D.1090601@g.nevcal.com> On approximately 12/1/2008 11:29 PM, came the following characters from the keyboard of Martin v. L?wis: >> It would be nice if the ftypes were version specific as created by the >> installer; IIRC, I created the above three from the ftype Python.File as >> I installed each version. >> > > That's a good idea; please submit a wish list item to bugs.python.org. > There may be issues (such as people relying on this being Python.File), > but I can't see any problems off-hand. > > Regards, > Martin > OK, Issue 4485 created. My first one, so let me know if I goofed. I elaborated a bit from the original email, upon reflection. Seemed useful, but also seemed complex by the time I got done. I don't really have a clue what the uninstaller should do with these; nor have I fiddled to know if it presently removes Python.File. I suppose it should delete them, if and only if the ftype and assoc have the same content as was created by the corresponding version installation. -- Glenn -- http://nevcal.com/ =========================== A protocol is complete when there is nothing left to remove. -- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking From rdcollum at gmail.com Fri Dec 19 09:23:55 2008 From: rdcollum at gmail.com (Roger) Date: Fri, 19 Dec 2008 06:23:55 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <494b5f47$0$17068$6e1ede2f@read.cnntp.org> <494b632b$0$17070$6e1ede2f@read.cnntp.org> Message-ID: > Note that I took out the lambdas and gave event arguments to the > functions; if you did that on purpose, because you need to call the same > functions without events, then just ignore that... > SO, the other workaround, which I've used, is to bind the event to a > generic function, and have that generic function conditionally call > the functions you want. I'll go back and try to make an example from > your example. -Chuckk Thanks Chuckk! You've done exactly what I did so far. I went through the source in Tkinter.py and had an inkling of what the unbind function was doing. I believe, and please correct me if I'm wrong, in: self.tk.call('bind', self._w, sequence, '') , the '' is unbinding all methods and I believe the self.deletecommand(funcid) is a workaround for a memory leak otherwise. Perhaps self.tk.call('bind', self._w, sequence, funcid) would work but that's a pure guess. I would have liked to investigate the tcl source directly to see if I could develop a workaround through a tk.call() but that was hitting a wall in terms of any documentation I could research. I'm interested in any workaround you may have however! You now, I really considered going over to wxwidgets, and I definitely want to try it after the current app I'm developing is complete, but I've so much experience with Tkinter now after banging my head against a wall for months (productive months mind you) on various projects, it's like an old persnickety friend you just can't give up. =) Thanks a ton! Roger. From musiccomposition at gmail.com Sun Dec 28 16:36:54 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sun, 28 Dec 2008 13:36:54 -0800 (PST) Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> <0167cbf7$0$6988$c3e8da3@news.astraweb.com> Message-ID: <088c7d93-e87f-44a0-9ea7-faa7feded7df@a26g2000prf.googlegroups.com> On Dec 28, 1:35?pm, Steven D'Aprano wrote: > The second thing I think is that maybe the function is a generator, and > so I look for a yield. You shouldn't, though; Generators can't contain any return statement. From steve at holdenweb.com Fri Dec 12 01:28:50 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Dec 2008 01:28:50 -0500 Subject: how to convert '\xf0' to 0xf0 ? In-Reply-To: <8f5b95c0-486d-48ce-b75c-e18a86d73f50@l33g2000pri.googlegroups.com> References: <1cb85265-1c36-4e4b-88f1-46b0ebae3dea@v5g2000prm.googlegroups.com> <8f5b95c0-486d-48ce-b75c-e18a86d73f50@l33g2000pri.googlegroups.com> Message-ID: Looks like you need the struct module. That can convert binary fields of various lengths into the appropriate Python types, and vice versa. >>> import struct >>> struct.unpack("L", '\xf0\xf0\xff\xfe') (4278186224L,) >>> struct.unpack("l", '\xf0\xf0\xff\xfe') (-16781072,) >>> regards Steve chengang.beijing at gmail.com wrote: > Hi, > > ord('\xf0') works and it only works for char. Do you know any way to > convet > '\xf0\xf0' and '\xf0\xf0\xff\xfe' to integer? > > > Br, Chen Gang > > On Dec 12, 12:40 pm, Steve Holden wrote: >> chengang.beij... at gmail.com wrote: >>> '\xf0' is the value read from a binary file, I need to change this >>> kinds strings to int for further processing... >>> if it is in C, then '\xf0' is an integer and it can be handled >>> directly, but in python, it is a string. >>> and both int('10',16) and int('0x10',16) returns 16. >>> Br, Chen Gang >>> On Dec 12, 12:06 pm, Tommy Nordgren wrote: >>>> On Dec 12, 2008, at 4:48 AM, chengang.beij... at gmail.com wrote: >>>>> int('\xf0',16) doesn't work, any way to do that? >>>>> -- >>>>> http://mail.python.org/mailman/listinfo/python-list >>>> Should be int('10',16) >>>> or int('0x10',16) >> It seems that you want the integer value of a character you read in from >> a file. Is this correct? Note that '\xf0' is the interpreter's way of >> representing a one-character string whose only character has the >> hexadecimal value f0, because the actual character is not printable: the >> backslash has a special meaning in character string literals. >> >> Any one-character string, however, can be converted to the equivalent >> integer value using the ord() function. You can convert the other way >> using the chr() function: >> >> >> >>>>> ord('A') >> 65 >>>>> chr(65) >> 'A' >>>>> ord('\xf0') >> 240 >>>>> chr(240) >> '\xf0' >>>>> hex(240) >> '0xf0' >> >> So just apply the ord() function to the character and you'll get its >> integer value! >> >> regards >> Steve >> -- >> Steve Holden +1 571 484 6266 +1 800 494 3119 >> Holden Web LLC http://www.holdenweb.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From brigettehodson at gmail.com Tue Dec 16 12:51:09 2008 From: brigettehodson at gmail.com (Brigette Hodson) Date: Tue, 16 Dec 2008 10:51:09 -0700 Subject: Python Dictionary Algorithm Question Message-ID: <3ca641b40812160951h3a13e69am291afb02965451a7@mail.gmail.com> Hello! I am in a beginning algorithms class this semester and I am working on a presentation. I want to discuss in some detail the algorithm python uses to determine the hash function for python dictionaries. Does anyone know what this algorithm is? Or where I can go to find information on it? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eric at ericaro.net Thu Dec 18 05:38:45 2008 From: eric at ericaro.net (eric) Date: Thu, 18 Dec 2008 02:38:45 -0800 (PST) Subject: Best Practice using Glade/Python Message-ID: <1b63220b-1572-4a8f-8f43-474ef8194bb0@s1g2000prg.googlegroups.com> Hi, I was wondering which is the "best practice" using glade/python, and, of course, especially the connect (both side). I didn't found that much documentation on the net ( too noisy), and the best "thing" I've found was http://www.linuxjournal.com/article/7558 which is a bit old now (2004). The article is very interesting BTW, but I was concerned by the fact it might be a little outdated. It smells like I'm missing something here, and that there have been a clean way to connect both (the autoconnect stuff does not seem that clean to me) for a long time now. So here is the question, do you practive galde/python, which is your practice ? Thanks Eric http://codeslash.blogspot.com From invalid at invalid Tue Dec 23 14:18:10 2008 From: invalid at invalid (Grant Edwards) Date: Tue, 23 Dec 2008 13:18:10 -0600 Subject: pseudo terminal usage from Python? References: <5t-dnRgMi9Z4lszUnZ2dnUVZ_vOdnZ2d@posted.visi> Message-ID: On 2008-12-23, skip at pobox.com wrote: > > Grant> Are you sure it's not Python buffering its input? Have you tried > Grant> "python -u mympstat.py"? > > Nope. -u unbuffers stdout and stderr, not stdin. It really must be mpstat > being uncooperative. That's not what my python man page says: -u Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode. That's for 2.5.2, but that's how I remember previous versions working as well. -- Grant Edwards grante Yow! We have DIFFERENT at amounts of HAIR -- visi.com From eric at ericaro.net Fri Dec 5 11:33:19 2008 From: eric at ericaro.net (eric) Date: Fri, 5 Dec 2008 08:33:19 -0800 (PST) Subject: simplest way to strip a comment from the end of a line? References: <52e3f2a9-6fb1-42ef-9871-c904ede5520e@t3g2000yqa.googlegroups.com> <9cdc9039-6b7b-42fb-b261-4ad721ccd1d4@j39g2000yqn.googlegroups.com> <340697a3-3f17-477a-aea2-c85344da93d4@k41g2000yqn.googlegroups.com> Message-ID: On Dec 5, 11:56?am, eric wrote: > On Dec 4, 11:35?pm, Paul McGuire wrote: > > > Yowza! ?My eyes glaze over when I see re's like "r'(?m)^(?P.*? > > (".*?".*?)*)(?:#.*?)?$"! > > yeah, I know ... :( ( I love complicated regexp ... it's like a puzzle > game for me) > > > > > from pyparsing import quotedString, Suppress, restOfLine > > > comment = Suppress('#' + restOfLine) > > recognizer = quotedString | comment > > > for t in tests: > > ? ? print t > > ? ? print recognizer.transformString(t) > > ? ? print > > > Prints: > > > this is a test 1 > > this is a test 1 > > > this is a test 2 #with a comment > > this is a test 2 > > > this is a '#gnarlier' test #with a comment > > this is a '#gnarlier' test > > > this is a "#gnarlier" test #with a comment > > this is a "#gnarlier" test > > > For some added fun, add a parse action to quoted strings, to know when > > we've really done something interesting: > > > def detectGnarliness(tokens): > > ? ? if '#' in tokens[0]: > > ? ? ? ? print "Ooooh, how gnarly! ->", tokens[0] > > quotedString.setParseAction(detectGnarliness) > > > Now our output becomes: > > > this is a test 1 > > this is a test 1 > > > this is a test 2 #with a comment > > this is a test 2 > > > this is a '#gnarlier' test #with a comment > > Ooooh, how gnarly! -> '#gnarlier' > > this is a '#gnarlier' test > > > this is a "#gnarlier" test #with a comment > > Ooooh, how gnarly! -> "#gnarlier" > > this is a "#gnarlier" test > > > -- Paul > > I didn't knew pyparsing. It's amazing ! thanks maybe you'd rather replace: splitter = re.compile(r'(?m)^(?P.*?(".*?".*?)*)(?:#.*?)?$') by from reO import * quote = characters('"') # defining the characters used as string sep sharp= string('#') # defining the sharp symbol data = ALL + repeat( group( quote + ALL + quote + ALL ) ) # ALL ( "ALL" ALL)* comment = group(sharp+ALL+END_LINE) # the comment itself xp = flag(MULTILINE=True) + START_LINE + group( data, name="data") + if_exists(comment) splitter = xp.compile() From paul_hildebrandt at yahoo.com Thu Dec 4 17:40:34 2008 From: paul_hildebrandt at yahoo.com (Paul Hildebrandt) Date: Thu, 4 Dec 2008 14:40:34 -0800 (PST) Subject: Porting to 3.0, test coverage Message-ID: <8f25bd4f-fd2f-4908-88ee-852624cf3234@z6g2000pre.googlegroups.com> I was just reading what's new with Python 3.0 http://docs.python.org/dev/3.0/whatsnew/3.0.html I like this prerequisite to porting: "Start with excellent test coverage" May I suggest looking into Pythoscope for those looking to boost test coverage. http://pythoscope.org Paul From tino at wildenhain.de Sat Dec 13 13:43:57 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Sat, 13 Dec 2008 19:43:57 +0100 Subject: zip a created file In-Reply-To: References: Message-ID: <4944026D.3040806@wildenhain.de> frendy zhang wrote: > if form.accepts(request.vars,session): > for table in db.tables: > rows=db(db[table].id).select() > print rows > open(str(os.sep).join([os.getcwd(), 'applications', > request.application, 'databases', > table+'.csv']),'w').write(str(db(db[table].id).select ())) > > > where and what should i put the zip code to zip the file created above? > thanks in advance You don't? ;) The code is very -crappy- suboptimal... - can you reformulate the problem first? Where is request, session coming from? If its a web application, what are you doing with open() and why this complicated code instead of just os.path.join() ? In short, creating a file and zipping and sending to the browser should not need to create an intermediate file in the file system. (This also avoids a lot of problems with your approach above - for example if the same query is put twice the same time...) Just have a look at the examples in the documentation which come with the zipfile module. Cheers Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From fetchinson at googlemail.com Sun Dec 7 13:21:06 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sun, 7 Dec 2008 10:21:06 -0800 Subject: Guido's new method definition idea In-Reply-To: <47c890dc0812061353x6214cfb4s1d729d36ab93f3dc@mail.gmail.com> References: <47c890dc0812061353x6214cfb4s1d729d36ab93f3dc@mail.gmail.com> Message-ID: >>> Hi folks, >>> >>> The story of the explicit self in method definitions has been >>> discussed to death and we all know it will stay. However, Guido >>> himself acknowledged that an alternative syntax makes perfect sense >>> and having both (old and new) in a future version of python is a >>> possibility since it maintains backward compatibility. The alternative >>> syntax will be syntactic sugar for the old one. This blog post of his >>> is what I'm talking about: >>> >>> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... >>> >>> The proposal is to allow this: >>> >>> class C: >>> def self.method( arg ): >>> self.value = arg >>> return self.value >>> >>> instead of this: >>> >>> class C: >>> def method( self, arg ): >>> self.value = arg >>> return self.value >> >> >> >> -1 >> >> I explained why deep in the thread but I'll elaborate more here. When >> I see a def statement, I mentally equate that to an assigment to the >> thing being def'ed. So for instance, when I see this: >> >> def (): >> >> I think of it like this: >> >> = >> >> >> Thus, if I were to see a function definition like this >> >> def foo.bar(): return 1 >> >> I would think you were defining a function and assigning it to >> foo.bar. IOW, it would be mostly equivalent to this: >> >> foo.bar = lambda: 1 >> >> >> (Analogously, I would expect a definition like this: >> >> def baz[10](): return 1 >> >> to be equivalent to this: >> >> baz[10] = lambda: 1 ) >> >> >> So, if, inside a class definition, I were to see this: >> >> def self.method(): return 1 >> >> Well, I'd understand that is was a method assigment, of course, but it >> would conflict with what I would expect the natural meaning of >> something like def a.b() would be. The above statement is not >> equivalent to: >> >> self.method = lambda: 1 >> >> but I think that's what it ought to be, in general. > > Similarly, to those coming from Ruby or those operating under the > frequent misunderstanding that the `def`s are happening in the context > of a class object (which in reality has yet to be created), `self` in > this context might be misconstrued as the class object and thus `def > self.foo` might be misunderstood (through the intuitive equivalence > you mention) as a defining a classmethod rather than an instance > method. This is actually a real counter argument, I think. Self, the instance, doesn't exist until it is created and certainly doesn't exist during class creation. So something like class C: def self.meth( arg ): return arg can be confusing since 'self' appears as if it was defined in the scope of C but clearly it isn't yet. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From lew at lewscanon.com Tue Dec 2 15:21:14 2008 From: lew at lewscanon.com (Lew) Date: Tue, 2 Dec 2008 12:21:14 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: Xah Lee wrote: > LOL Jon. r u trying to get me to do otimization for you free? These are professional software development forums, not some script- kiddie cellphone-based chat room. "r" is spelled "are" and "u" should be "you". > how about pay me $5 thru paypal? I'm pretty sure i [sic] can speed it up. > Say, maybe 10%, and even 50% is possible. The first word in a sentence should be capitalized. "PayPal" is a trademark and should be capitalized accordingly. The word "I" in English should be capitalized. Proper discipline in these matters helps the habit of mind for languages like Java, where case counts. Jon Harrop has a reputation as an extremely accomplished software maven and columnist. I find his claims of relative speed and compactness credible. He was not asking you to speed up his code, but claiming that yours was not going to be as effective. The rhetorical device of asking him for money does nothing to counter his points, indeed it reads like an attempt to deflect the point. -- Lew From mail at anjanesh.net Fri Dec 19 22:47:56 2008 From: mail at anjanesh.net (Anjanesh Lekshminarayanan) Date: Sat, 20 Dec 2008 09:17:56 +0530 Subject: mod_python resources In-Reply-To: References: <78064e7e-ba2c-4959-b5f8-4d1b928bc5fe@y18g2000yqn.googlegroups.com> <4lsl16-15a.ln1@archaeopteryx.softver.org.mk> Message-ID: <1a7951080812191947j148fae8bq2357b614ecfe3f74@mail.gmail.com> Same requirement here. But isnt there any mod_python for Python 3.0 ? Or do we need to build it from source ourselves ? I was hoping there would be mod_wsgi binaries for Python 3.0. From callen314 at gmail.com Tue Dec 2 13:36:13 2008 From: callen314 at gmail.com (Craig Allen) Date: Tue, 2 Dec 2008 10:36:13 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> Message-ID: <878c995b-4adb-4fc6-895c-c5e3d9e80368@c36g2000prc.googlegroups.com> > Just remember thought that if you threat Python like a > hammer, suddenly everything will look like a bail. > don't you mean if you use Python like a pitchfork? From mludvig at logix.net.nz Mon Dec 29 07:06:09 2008 From: mludvig at logix.net.nz (Michal Ludvig) Date: Tue, 30 Dec 2008 01:06:09 +1300 Subject: Unicode encoding - ignoring errors Message-ID: <4958BD31.1010801@logix.net.nz> Hi, in my script I have sys.stdout and sys.stderr redefined to output unicode strings in the current system encoding: encoding = locale.getpreferredencoding() sys.stdout = codecs.getwriter(encoding)(sys.stdout) However on some systems the locale doesn't let all the unicode chars be displayed and I eventually end up with UnicodeEncodeError exception. I know I could explicitly "sanitize" all output with: whatever.encode(encoding, "replace") but it's quite inconvenient. I'd much prefer to embed this "replace" operation into the sys.stdout writer. Is there any way to set a conversion error handler in codecs.getwriter() or perhaps chain it with some other filter somehow? I prefer to have questionmarks in the output instead of experiencing crashes with UnicodeEncodeErrors ;-) Thanks! Michal From xahlee at gmail.com Wed Dec 3 16:15:11 2008 From: xahlee at gmail.com (Xah Lee) Date: Wed, 3 Dec 2008 13:15:11 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> Message-ID: <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> On Dec 3, 8:24 am, Jon Harrop wrote: > My example demonstrates several of Mathematica's fundamental limitations. enough babble Jon. Come flying $5 to my paypal account, and i'll give you real code, amongest the programing tech geekers here for all to see. I'll show, what kinda garbage you cooked up in your Mathematica code for ?comparison?. You can actually just post your ?comparisons? to ?comp.soft- sys.math.mathematica?, and you'll be ridiculed to death for any reasonable judgement of claim on fairness. > Consequently, there is great value in combining Mathematica with performant > high-level languages like OCaml and F#. This is what the vast majority of > Mathematica users do: they use it as a glorified graph plotter. glorified your ass. Yeah, NASA, Intel, NSA, ... all use Mathematica to glorify their pictures. LOL. > What exactly do you believe is wrong with my code? come flies $5 to my paypal, and i'll explain further. > I am not trying to make Mathematica look bad. It is simply not suitable when > hierarchical solutions are preferable... Certainly there are areas other langs are more suitable and better than Mathematica (for example: assembly langs). But not in the ways you painted it to peddle your F# and OCaml books. You see Jon, you are this defensive, trollish guy, who takes every opportunity to slight other langs that's not one of your F#, OCml that you make a living of. In every opportunity, you injest your gribes about static typing and other things, and thru ensuring chaos paves the way for you to post urls to your website. With your math and functional programing expertise and Doctor label, it can be quite intimidating to many geekers. But when you bump into me, i don't think you have a chance. As a scientist, i think perhaps you should check your newsgroup demeanor a bit? I mean, you already have a reputation of being biased. Too much bias and peddling can be detrimental to your career, y'known? to be sure, i still respect your expertise and in general think that a significant percentage of tech geeker's posts in debate with you are moronic, especially the Common Moron Lispers, and undoubtably the Java and imperative lang slaving morons who can't grope the simplest mathematical concepts. Throwing your Mathematica bad mouthing at me would be a mistake. Come, fly $5 to my paypal account. Let the challenge begin. Xah ? http://xahlee.org/ ? From prologic at shortcircuit.net.au Mon Dec 8 04:04:29 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Dec 2008 19:04:29 +1000 Subject: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL? In-Reply-To: <7e1a9226-c7a9-4b5e-bfbb-ea079639d6a2@t39g2000prh.googlegroups.com> References: <5ccd4a18-cd2b-4040-90c6-33723af15e96@b38g2000prf.googlegroups.com> <7e1a9226-c7a9-4b5e-bfbb-ea079639d6a2@t39g2000prh.googlegroups.com> Message-ID: On Mon, Dec 8, 2008 at 6:31 PM, alex23 wrote: > On Dec 8, 2:26 pm, illume wrote: >> pygame is simpler to learn, since it doesn't require you to know how >> to create classes or functions. > > I'm not sure if I'd be quick to tout that as an advantage... :) Neither would i. Classes and Objects and good OOP practises can benefit a pygame game just as well as any other Python app. What's more using and learning Python's OO semantics and syntax is really really easy :) --JamesMills -- -- -- "Problems are solved by method" From ldo at geek-central.gen.new_zealand Sat Dec 6 02:29:24 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 06 Dec 2008 20:29:24 +1300 Subject: Don't you just love writing this sort of thing :) References: <0149f773$0$20670$c3e8da3@news.astraweb.com> Message-ID: In message <0149f773$0$20670$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > It would have been far more concise ... Gee, I thought people were complaining it was too cryptic, now it turns out they were actually complaining because it was too verbose. From rt8396 at gmail.com Thu Dec 11 12:36:44 2008 From: rt8396 at gmail.com (r) Date: Thu, 11 Dec 2008 09:36:44 -0800 (PST) Subject: Preventing execution of a method References: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> <764daeef-bfbe-411a-8521-bb114321e4ac@b38g2000prf.googlegroups.com> <19304f8c-e34f-4aa9-8df2-6a7d3553007a@e1g2000pra.googlegroups.com> Message-ID: <2eed8876-94d2-4304-88a5-eb4a78b4f41d@33g2000yqm.googlegroups.com> > And of course -now- I realise that the OP was asking for protecting > methods. Please disregard my last post :) Alex23, Are you telling me that you do not know how to YANK your own post? I find that hard to believe. ;) From castironpi at gmail.com Sun Dec 21 06:23:43 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 21 Dec 2008 03:23:43 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <015da0a4$0$20656$c3e8da3@news.astraweb.com> Message-ID: <2e82daf5-f1db-4176-8994-6c738bbf916d@p2g2000prn.googlegroups.com> On Dec 20, 8:26?pm, Steven D'Aprano wrote: > On Sat, 20 Dec 2008 17:55:35 -0800, Aaron Brady wrote: snip > > This behavior is currently legal: > > >>>> "%i %%i" % 0 % 1 > > '0 1' > > > So, just extend it. ?(Unproduced.) > > >>>> "%i %i" % 0 % 1 > > '0 1' > > Errors should never pass silently, unless explicitly silenced. You have > implicitly silenced the TypeError you get from not having enough > arguments for the first format operation. That means that you will > introduce ambiguity and bugs. No, it's not part of the (new) '%' operation. '%' handles one flag at a time. It's not an error if the author intends it. > "%i %i %i %i" % 5 % 3 %7 > > Here I have four slots and only three numbers. Which output did I expect? > > '%i 5 3 7' > '5 %i 3 7' > '5 3 %i 7' > '5 3 7 %i' Anything, so long as it's (contraction) consistent and general. > Or more likely, the three numbers is a mistake, there is supposed to be a > fourth number there somewhere, only now instead of the error being caught > immediately, it won't be discovered until much later. Leave that to unit testing and your QA team. To make the change, the burden of proof (which is large) would fall to me. However, in the abstract case, it's not clear that either one is favorable, more obvious, or a simpler extrapolation. Bug-proneness is an argument against a construction, just not a conclusive one. How heavy is it in this case? From steve at REMOVE-THIS-cybersource.com.au Sat Dec 6 10:34:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Dec 2008 15:34:12 GMT Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5d219a45-255c-4276-81a3-ce196ffd5311@l42g2000yqe.googlegroups.com> <20081206133258.693cf59e@usenot.de> <8b8d1fb3-f49e-49bf-8cfe-eeee5ed16109@r37g2000prr.googlegroups.com> Message-ID: <014a932b$0$20670$c3e8da3@news.astraweb.com> On Sat, 06 Dec 2008 07:15:27 -0800, Russ P. wrote: > On Dec 6, 4:32?am, Andreas Waldenburger wrote: >> On Sat, 6 Dec 2008 04:02:54 -0800 (PST) bearophileH... at lycos.com wrote: >> >> > class C: >> > ? ? def $method(arg): >> > ? ? ? ? $value = arg >> >> > (Note there's no point after $, it's not currently possible). If -- and that's a HUGE if -- the compiler is changed to allow $method, it could certainly be changed to allow $.method. >> > Ruby >> > uses @ and @@ for similar purposes. I agree that the code looks >> > worse, but also shorter to read and write, so in lines of code that >> > use many instance attributes, that short $ syntax helps keep the line >> > shorter. So I may grow to accept this sugar... If a line of code uses too many instance attributes to fit comfortably on a line, spread it over two lines. There is no newline shortage, they are a renewable resource. >> But that is not the way Python is meant to work. There are several >> tennets in the Zen of Python that don't chime well with this approach. >> "self" is a speaking identifier, "$" isn't. > > Is "@" a "speaking identifier? How about "#" and "!="? Last I heard, > they were all part of Python. Yes they are. @f is pronounced "at f" or "decorate f". # comment is pronounced "hash comment" or even not pronounced at all. x != y is pronounced "x not equal to y" The proposed def $method(arg): would be pronounced "def dollar method arg" or "def method self arg". The first is ugly to my ears, the second confusing. -2 on this proposal. -- Steven From clp at rebertia.com Wed Dec 31 06:48:49 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 31 Dec 2008 03:48:49 -0800 Subject: Pass by reference In-Reply-To: <529e1d98-8932-49f0-b569-85285bd50f23@p2g2000prn.googlegroups.com> References: <529e1d98-8932-49f0-b569-85285bd50f23@p2g2000prn.googlegroups.com> Message-ID: <47c890dc0812310348l1b1278bcke50ed5819722d639@mail.gmail.com> On Wed, Dec 31, 2008 at 3:30 AM, iu2 wrote: > Hi, > > Is it possible somehow to change a varible by passing it to a > function? > > I tried this: > > def change_var(dict0, varname, val): > dict0[varname] = val > > > def test(): > a = 100 > change_var(locals(), 'a', 3) > print a > > > But test() didn't work, the value a remains 100. Yes, that's clearly stated in the documentation for locals(); from http://docs.python.org/library/functions.html#locals : "Warning: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter." > > I have several variables initialized to None. > I need to convert each one of them an object only if it is None. > something like: > > if not var1: var1 = MyObject() That should be: if var1 is None: var1 = MyObject() Otherwise, the "conversion" will also happen if var1 happens to be a false but non-None object, e.g. {}, [], 0, etc Also, it's just the idiomatic way of writing tests against None in Python. > > I want this to be a function, that is: > > def create_obj(var): > if not var: var = MyObj() > # set properties of var > > Now, I know I can achieve this by functional programming, > > def create_obj(var): > if not var: > x = MyObj() > # set properties of x > return x > return var > > and then > > var = creaet_obj(var) > > Is there another way? Not really, or at the very least it'll be kludgey. Python uses call-by-object (http://effbot.org/zone/call-by-object.htm), not call-by-value or call-by-reference. Could you explain why you have to set so many variables to the same value (if they're None)? It's a bit strange and could be a sign that there's a better way to structure your program (e.g. use a dictionary). We might be able to offer more helpful suggestions if you explain. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From pavlovevidence at gmail.com Fri Dec 19 15:50:49 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 19 Dec 2008 12:50:49 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> <88ff7c46-2b23-49e4-865e-781d23433799@l33g2000pri.googlegroups.com> Message-ID: On Dec 19, 12:44?pm, r wrote: > ~Michael, > What?s next down this road of self destruction? Hey guys, forget about > about empty parenthesis on a function/method call, ?we should not have > to waste are time typing them? Wait forget about them all together and > we will just write Ruby code? > > Def function arg arg arg arg arg arg > > ?Yea, that looks good?.insert(sarcasm) > Things like forcing empty tuple on function/method calls are what make > python so great. Python dumped the C bracket plague, ?but enforces > parenthesis even for a no argument function. But hell, why shouldn?t > we have 50 ways to the same thing in Python like Ruby. > > PS. Don?t discredit Walter just because he is not on the dev team, > that don?t mean squat! > > ~Bearophile, > Thanks for your civil approach to this conversation but I must > disagree with you on the new string formatting syntax. You said the > new syntax is suppost to be easier on the n00b , I say it pollutes a > students mind. What is wrong with similarities to C formatting, ?I > find nothing complicated about it. > > %s (means put a string here) > %d (means put a integer here) > %f (means put a float here) > > It does not get any simpler than that, No, you just think it's easiest because that's the way you learned it. I'm kind of ambivalent about the change (it does have a couple minor drawbacks), but I don't see any way that the new method isn't easier to learn than the old--especially if you want to do more advanced formatting--unless you already knew the old method. I really don't like that they made format a string method, though, I would have hoped for a built-in, and why didn't they abbreviate this one? If any function or method would have had a case for an abbreviated name, this was it. But just about anything is better than that % operator and its multi-level confusion involving tuple syntax, operator precedence, and special-casing of tuples and dicts. > and this will just ease the > transition to C programming for this student. Lets not forget how > important C is! C programmers who learn Python have to learn all kinds of new things, a new string formating method would be a minor one. As for everyone else, they'll probably have an easier time of it. Carl Banks From luke.leighton at googlemail.com Wed Dec 31 16:36:55 2008 From: luke.leighton at googlemail.com (lkcl) Date: Wed, 31 Dec 2008 13:36:55 -0800 (PST) Subject: Creating an application for Linux References: <7d2fe328-064c-46da-9150-7305b6f9e94e@b41g2000pra.googlegroups.com> Message-ID: hiya mike: where do i know you from? i've heard your name somewhere and for the life of me can't remember where! anyway... onwards. your simplest bet is to take advantage of the .deb install system, which, if you follow that, will allow you to pull in all of the dependencies _without_ screwing around with the ubuntu distribution, or requiring that you build "special" versions of the dependencies. so - your first port of call is to locate a similar app to your own one: apt-cache search wxwidgets [rose-tinted filter on the results...] cryptonit - A client side PKI (X.509) cryptographic tool fontypython - A GUI tool to manage ttf fonts jmdlx - jugglemaster deluxe using wxWidgets wxmaxima - a wxWidgets GUI for the computer algebra system maxima multiget - graphical download manager then, do apt-cache show , paying particular attention to the dependencies. apt-cache show fontypython looks like a good candidate. so, do apt-get source fontypython (or other candidate) also do apt-get build-essential dh-make dpkg-dev debutils python-dev devscripts python-setuptools juuust for fun, but the essential ones are probably dh-make and dpkg-dev. then you have something to work from (an example - the source of the deb-wrapped fontypython) and you will have most of the debian developer utils etc. etc. _then_ you go to e.g. oooo this: http://www.pythonmark.com/python-library/debian/howto-build-a-debian-package-from-python-sources/ the preamble for which says "don't bother with that annoying ubuntu python deb howto video, particularly on the basis that who gives a stuff about _verbal_ instructions when you actually want stuff you can READ!" :) the most important thing that _you_ need to remember is that you _must_ identify the correct libraries (and their debian packagenames - can't bring myself to say ubuntu packagenames) and make damn sure that you add them into the dependencies in the debian/control file. do _not_ be tempted to "bundle" customised versions of python- pysqlite, python-sqlalchemy etc. etc. testing: you should really use a debootstrap absolute "basic" environment (set up a chroot, or a virtual KVM or other virtual PC, qemu, whatever, or even a real machine) do NOT do a "full" install of ubuntu, do an absolute minimalist install (netbook, businesscard, whatever). ... and _then_ install your .deb (with dpkg -i) followed by apt-get -f install (to pull in all of the dependencies). then, use export DISPLAY=192.168.1.5:0.0 (adapt as necessary), run xhost + on 192.168.1.5 (adapt as necessary), and _then_ fire up your test app. if you get a python library not found runtime error, you know that you got your dependencies wrong, in the debian/control file. if you install a "vanilla" ubuntu desktop, various other packages will pull in the dependencies for you - and you will never find out if you got all of the dependencies correct. that having been said, if you don't _care_ about correctness, skip the above six sentences :) l. On Dec 31, 9:06 pm, Mike Driscoll wrote: > Hi, > > My boss wants me to port one of my applications to Ubuntu. I > successfully ported it without too many headaches but now I need a way > to distribute it to people that may or may not already have the > dependencies my application requires. I'm a newb with Linux so I'm not > even sure what they call the distribution (rpms, deb, source code). > > After browsing the various "installer" docs out there, it looks like > bbfreeze or PyInstaller might work, but I couldn't find any examples. > Any advice is appreciated. Thanks! > > I am using Python 2.5.2 and this is a wxPython application with > SqlAlchemy and a few other external packages. > > Mike From gagsl-py2 at yahoo.com.ar Wed Dec 10 17:03:22 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 10 Dec 2008 20:03:22 -0200 Subject: Deeper tracebacks? References: Message-ID: En Wed, 10 Dec 2008 16:59:16 -0200, brooklineTom escribi?: > I want my exception handler to report the method that originally > raised an exception, at the deepest level in the call-tree. Let give > an example. That's the default behavior, you don't have to do anything special. > import sys, traceback > class SomeClass: > def error(self): > """Raises an AttributeError exception.""" > int(3).zork() > > def perform_(self, aSelector): > try: > aMethod = getattr(self, aSelector, None) > answer = apply(aMethod, [], {}) > except: AttributeError, anAttributeErrorException: > aRawStack = traceback.extract_stack() > answer = None (I assume you're using Python < 3.0) Use the 3-names form of the except statement: try: aMethod = getattr(self, aSelector, None) answer = aMethod() except AttributeError, e, tb: # the tb variable holds the traceback up to the error # the same thing you see printed by Python when # an unhandled error happens answer = None Alternatively, you can obtain the same thing with sys.exc_info()[2] Remember to delete any reference to the traceback object as soon as you're done with it; see http://docs.python.org/library/sys.html#sys.exc_info -- Gabriel Genellina From clp at rebertia.com Mon Dec 8 01:13:46 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 7 Dec 2008 22:13:46 -0800 Subject: A question about reference in Python. In-Reply-To: References: <493CB003.3080209@gmail.com> Message-ID: <47c890dc0812072213q20cb415fjbd4c80e7af7a7ef5@mail.gmail.com> On Sun, Dec 7, 2008 at 10:09 PM, James Mills wrote: > Hi, > > This is really really really pointless code and a really really pointless > exercise, but nonetheless, here is a very very basic and minimal > implementation of what you're expecting. This should almost > *never* be done in Python! Python is a superior dynamic programming > language, but it's NOT C! > > Here goes: > > jmills at atomant:~/tmp$ ./list.py >>>> x[0] > 0 >>>> x[1] > 1 >>>> x[2] > 2 >>>> x[3] > 3 >>>> x[4] > Traceback (most recent call last): > File "", line 1, in > File "./list.py", line 36, in __getitem__ > return node.value > AttributeError: 'NoneType' object has no attribute 'value' >>>> > jmills at atomant:~/tmp$ > > And the code: > > #!/home/jmills/bin/python -i > > class Node(object): > The following three lines serve no purpose and can only lead to confusion: > value = None > prev = None > next = None > > def __init__(self, value, prev=None, next=None): > self.value = value > self.prev = prev > self.next = next > > class List(object): > Same with the following line. Why do you have these? Python does *not* have the concept of instance variable declaration. You are creating *class variables*, which is almost certainly not what you want. > data = None > Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > def __init__(self, *seq): > if seq: > first = prev = node = None > for x in seq: > if not first: > first = Node(x) > prev = node = first > else: > node = Node(x, prev) > prev.next = node > prev = node > > self.data = first > > def __getitem__(self, x): > node = self.data > for i in xrange(x): > node = node.next > return node.value > > x = List(0, 1, 2, 3) > > > Notes: > > I have not implemented any error checking whatsoever. > I have not implemented any of your normal list > operations whatsoever (except 1). __getitem__. > > Have fun, > > cheers > James > > On Mon, Dec 8, 2008 at 3:26 PM, Group wrote: >> Hello, I'm studying algorithom. For concentrating on the question itself, I >> intend to use Python to implement the algorithoms. >> >> Now, I want to write a Red-Black Tree, and a List structure. In C/C++, I can >> use pointers to refer to children notes (or next notes). But, in Python, >> how >> can I do it? Except the sequence, I know not any way. >> >> You'd better help me understan how can I transform the following C code into >> Python: >> >> /* a List */ >> struct { >> int data; >> int *next; >> int *prev; >> } >> >> That's all. Thanks! >> Kermit >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > > -- > -- > -- "Problems are solved by method" > -- > http://mail.python.org/mailman/listinfo/python-list > From prologic at shortcircuit.net.au Wed Dec 31 01:17:01 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 16:17:01 +1000 Subject: MemoryError when list append... plz help In-Reply-To: <21227745.post@talk.nabble.com> References: <21227745.post@talk.nabble.com> Message-ID: (Sorry for top posting): You are mad! Why on God's earth would you want to create a list containing 60 MILLION elements ? What is the use case ? What are you solving ? You may have 4G of ram, but I very seriously doubt you have 4G of ram available to Python. I have no idea how many bytes of memory storing each element of a list consumes let alone each float object, but I assure you it's not going to be anywhere near that of 60494500 4-bytes spaces (do floats in C normally consume 4 bytes) in C. --JamesMills -- -- "Problems are solved by method" On Wed, Dec 31, 2008 at 4:02 PM, [BON] wrote: > > ====================== > s=[] > for i in range(11000-1): > for j in range(i+1, 11000): > .... > s.append(((i,j),sim)) > ====================== > above sim is floating type. > s.append is totally coducted 60,494,500 times. > but this code raise MemoryError. > > My computer has 4G RAM. > i think it's enough. but it doesn't... > > So, i've tested below code. > ====================== > a=[] > i=0 > while i<60494500 : > a.append(i) > i+=1 > ====================== > but this code raise also MemoryError. > > How can i resolve this problem? > please, help... > > Regards, > -- > View this message in context: http://www.nabble.com/MemoryError-when-list-append...-plz-help-tp21227745p21227745.html > Sent from the Python - python-list mailing list archive at Nabble.com. > > -- > http://mail.python.org/mailman/listinfo/python-list > From jstroud at mbi.ucla.edu Sat Dec 13 22:28:57 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 13 Dec 2008 19:28:57 -0800 Subject: Need help improving number guessing game In-Reply-To: References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> Message-ID: James Stroud wrote: > Be assured that it takes on special intelligence to write unintelligible I meant "*no* special intelligence". From castironpi at gmail.com Tue Dec 16 04:29:19 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 16 Dec 2008 01:29:19 -0800 (PST) Subject: subprocess.Popen inheriting Message-ID: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> Hi, I have a file handle I want to inherit in a child process. I am looking at '_make_inheritable' in 'Popen', but it needs an instance, and by the time I have one, the subprocess is already running. Can't I call 'Popen._make_inheritable( None, handle )'? The method does not use 'self'. From robert.kern at gmail.com Sun Dec 28 00:12:27 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 28 Dec 2008 00:12:27 -0500 Subject: assignment with [:] In-Reply-To: References: Message-ID: Ben Bush wrote: > Hi, > > I saw this line of code on a recent post: > > a1[:] = [x*3 for x in a1] > > Could somebody tells me what the [:] means? I can't find it anywhere. It's a slice assignment. When both the start and stop arguments are omitted, it refers to the entire sequence. In this case, it means to replace the entire contents of the list a1 with the value on the right-hand-side. "a[2:4] = ..." would replace the 3rd and 4th items in the list with the sequence on the right-hand-side, for instance. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From mail at johnohagan.com Mon Dec 1 00:28:14 2008 From: mail at johnohagan.com (John O'Hagan) Date: Mon, 1 Dec 2008 05:28:14 +0000 Subject: Confused about class relationships In-Reply-To: References: Message-ID: <200812010528.14528.mail@johnohagan.com> On Sat, 29 Nov 2008, Carl Banks wrote: > On Nov 26, 11:20?pm, John O'Hagan wrote: [...] > > > > class Bar(list): > > > > ? ? ? ? def __init__(self, a_bar, args, engine): > > ? ? ? ? ? ? ? ? list.__init__ (self, a_bar) > > ? ? ? ? ? ? ? ? self[:] = a_bar ? ? ? ? > > ? ? ? ? ? ? ? ? self.args = args > > ? ? ? ? ? ? ? ? self.engine = engine > > ? ? ? ? ? ? ? ? #more instance attributes... > > > > ? ? ? ? #methods... > > > > class Engine: > > > > ? ? ? ? def __init__(self, args): > > ? ? ? ? ? ? ? ? self.args = args ? ? ? ? ? ? ? ? ? ? ? ? > > ? ? ? ? ? ? ? ? #more instance attributes... > > > > ? ? ? ? def bar_builder(self): > > ? ? ? ? ? ? ? ? #body of method generates lists... > > ? ? ? ? ? ? ? ? yield Bar([generated_list], args, self) > > > > ? ? ? ? #more methods... > > > > #(other stuff...) > > > > def main(args): > > > > ? ? ? ? ? ? engine = Engine(args) > > ? ? ? ? ? ? bars = engine.bar_builder() > > ? ? ? ? ? ? for a_bar in bars: > > ? ? ? ? ? ? ? ? #play the music!... > > > > While this works (to my surprise!) and solves the problem which motivated > > it (i.e. Engine instances need to pass some attributes to Bar instances > > ), it seems too convoluted. Should one class inherit the other? > > No. (I wonder if you meant, "Should one class reference the other?", > as in, "Should Engines only reference bars or Bars only reference > engines, but not both?", in which case the answer is a non-commital, > "It depends.") > > Inheritance is not something you do because object A wants to access > the attributes/properties/etc. of B. Actually, that is something that > happens pretty often and when it does, there's a couple things you > should think about: > > 1. How you want A to access the attributes of B. Should you just let > A poke around in B, or should you define methods of B for A to call, > and those methods access the internals of B? It's a judgment call > most of the time. > > 2. Whether some behavior of B ought to be defined as part of A's class > instead, or vice versa. There is sometimes ambiguity over what class > a method that uses the attributes of two different objects should > belong to. > > Inheritance isn't something you need to think about here. > > Inheritance is something you consider when you have two objects, A and > B, that should act very similar or the same in certain situations. > Engines and Bars don't seem to share any behavior at all. Contrast > this to Bars and lists, which do share behavior. x[1] does pretty > much the same thing whether x is a Bar or a list, I'd imagine, so > there's reason for an inheritance relationship there. > > > If so, which way > > around? Or is it fine as is? > > One thing you might want to consider is whether Engine instance could > be simply passed into the Bar's play method (or whatever other method > accesses the Engine attributes), and whether the Engine needs to be > involved in generating bars at all. For instance: > > > class Bar(list): > def __init__(self, a_bar, args): > list.__init__(self, a_bar) > self[:] = a_bar > self.args = args > # etc. > def play(self, engine): > use(engine.time_signature).somehow() > # instead of use(self.engine.time_signature).somehow() > > > def bar_builder(self,args): > # plain function, not part of Engine class > # or perhaps a method of some other class > yield Bar([generated_list],args) > > > def main(): > engine = Engine(args) > bars = bar_builder(self,args) > for a_bar in bars: > a_bar.play(engine) > > > One benefit of doing it this way is that you've freed Bars and Engines > from each other. Conceivably you could create a second engine object > (maybe of a different type altogether), and play the very same Bar > objects with that engine instead. Thanks for such a detailed reply...I actually had bar_builder as a plain function originally, but because I didn't know how to pass attributes around like you have above, I was using globals to do it and was trying to solve that by classing everything in sight. Although the program doesn't work quite as you have deduced above, I can use the approach you suggest to simplify it immensely. (I hope.) > > > I'm hoping this is a common trap I've fallen into; I just haven't been > > able to get my head around it. (I'm a musician...) > > Well I think it looks pretty good for a musician newbie. There's a > few organizational decisions I'd make differently, but overall it's > clean and readable and not too complicated how you did it. At least > not what you've showed us. :) > [...] Believe me, the whole thing is more complicated and messy, but you don't want to see my dirty laundry! :) Regards, john From cjw at ncf.ca Fri Dec 19 19:33:20 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Fri, 19 Dec 2008 19:33:20 -0500 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <494bd4e6$0$31863$9b4e6d93@newsspool3.arcor-online.net> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <5463e605-1dc3-4304-97a1-061437393a0d@a29g2000pra.googlegroups.com> <6r219cFfc8ovU1@mid.individual.net> <494bd4e6$0$31863$9b4e6d93@newsspool3.arcor-online.net> Message-ID: Stefan Behnel wrote: > Thomas Heller wrote: >> Mark Summerfield schrieb: >>> Just a follow-up to say that the book has now been published in the >>> U.S. >>> It is now in stock at InformIT, and should reach other stores, e.g., >>> Amazon, in a week or so. >>> >>> Also, the introduction, the first few pages of the first chapter, the >>> whole of chapter 12 (regular expressions), and the index are now >>> available for free download in a PDF from here: >>> http://www.informit.com/store/product.aspx?isbn=0137129297 >> Question from a non-native english speaker: is this now valid english? >> >> "One of Python???s great strengths" >> ^ >> "and also teaches Python???s functional programming features" >> ^ >> "The book???s approach is wholly practical" >> ^ > > 'Always' has been. It's not valid German, though, if that's what you are > asking. > > Stefan It wasn't the question. Colin W. From steve at holdenweb.com Sun Dec 14 13:00:07 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 14 Dec 2008 13:00:07 -0500 Subject: Looking for the best way to translate an idiom In-Reply-To: <4945406a$0$1127$426a74cc@news.free.fr> References: <4945406a$0$1127$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: [...] > if you only want the first returned value, you can just apply a slice: > > def f(): > return 1,2,3 > > a = f()[0] + 1 > That isn't a slice, it's indexing regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From thmpsn.m.k at gmail.com Mon Dec 29 20:22:08 2008 From: thmpsn.m.k at gmail.com (thmpsn.m.k at gmail.com) Date: Mon, 29 Dec 2008 17:22:08 -0800 (PST) Subject: Python in C Message-ID: <48bea484-c975-452e-98ce-4a018a1b2499@r15g2000prh.googlegroups.com> I've just downloaded Python's mainstream implementation (CPython), which is written in C. Not to my surprise, I feel like I'm looking at unstructured spaghetti, and I'm having trouble figuring out how it all works together. (Please bear with me; I'm just going through the usual frustration that anyone goes through when trying to see the organization of a C program :) So, I have two queries: 1. Can anyone explain to me what kind of program structuring technique (which paradigm, etc) CPython uses? How do modules interact together? What conventions does it use? 2. Have there been any suggestions in the past to rewrite Python's mainstream implementation in C++ (or why wasn't it done this way from the beginning)? From martin at v.loewis.de Sat Dec 13 04:38:35 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 13 Dec 2008 10:38:35 +0100 Subject: Umlauts in idle In-Reply-To: <26880ecf-d0eb-42ab-8ebd-56f64c023999@v39g2000pro.googlegroups.com> References: <26880ecf-d0eb-42ab-8ebd-56f64c023999@v39g2000pro.googlegroups.com> Message-ID: <4943829B.9050606@v.loewis.de> > When I try to use umlauts in idle it will only print out as Unicode > escape characters. Is it possible to configure idle to print them as > ordinary characters? Did you really use the print statement? They print out fine for me. Regards, Martin From sjmachin at lexicon.net Fri Dec 5 18:14:39 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 5 Dec 2008 15:14:39 -0800 (PST) Subject: Find Files in a Folder Between 2 Dates References: <4c54b6c5-ae4d-4b89-8c6d-940c96de29bb@n33g2000pri.googlegroups.com> <94cd4bd7-a69f-48ba-90f7-382014844905@g1g2000pra.googlegroups.com> Message-ID: <862567e3-4469-43ae-b41b-1a1817124f50@k36g2000pri.googlegroups.com> On Dec 6, 9:41?am, Gregory Plantaine wrote: > That worked perfectly! > > Thanks Tim! > > Since we can print the files, does that mean the list of files is in a > tuple, or something? ?Would there be a way to further split up the > file names? > > For example, now that the files are processed into the list, we want > to look through that list to find different filetypes. > > files > > C:\Folder\File_200812051439.111 > C:\Folder\File_200812051539.222 *DANGER* It looks like you are interested in the timestamps that are embedded in the names of the files. Tim's code assumes [reasonably given that your problem description was ambiguous and had no examples of good and bad results] that you are interested in the last modification time of the file. You may say "same thing". Yes, same thing, until somebody sucks a file into a text editor, messes with it, and saves it again. No, Murphy's Law has not been repealed. > > Can we split up .111 files? > > Actually, where would I look something like this up? In the Library Reference Manual ... there are all sorts of goodies in the os and os.path modules e.g. like those used by Tim; make sure you read the docs on the methods Tim used so that you understand what's happening. HTH, John From rsarpi at gmail.com Wed Dec 10 19:37:25 2008 From: rsarpi at gmail.com (icarus) Date: Wed, 10 Dec 2008 16:37:25 -0800 (PST) Subject: broken ncurses on python 3.0 Message-ID: OS: win32, python 3.0 I've been trying to run some curses demos and I get this: C:\Python\Lib\curses>python textpad.py Traceback (most recent call last): File "textpad.py", line 3, in import curses File "C:\Python\lib\curses\__init__.py", line 15, in from _curses import * ImportError: No module named _curses The C:\Python\include does not have the curses.h header. Reinstalling from the x86 msi binary doesn't do it. Any ideas on how to get this working? maybe it's just the w32 version that missed ncurses From sambasivareddy.s at patni.com Wed Dec 3 05:51:40 2008 From: sambasivareddy.s at patni.com (sambasivareddy) Date: Wed, 3 Dec 2008 16:21:40 +0530 Subject: How to write a string with required color in a file with python.net? Message-ID: <011501c95535$20b302c0$750ba8c0@patni.com> Hi all, I have couple of double on python futures .Quires listed below: * How to write a particular string with required/selected color in a file with python.net? Which module I need to use it? How to set color for particular string in file? --------------------------------- file=open("C:\\test\\TestResult.txt","w") file.writelines("testcase1 pass \n") file.writelines("testcase2 Faile \n") file.close() ----------------------------- I want output like this in file: testcase1 pass testcase2 Faile * How to create .exe file in python.net? I have tried with py2exe module but it is not supporting with python.net if anyone have any information or code on the same queries plz send it. thanks in advance. Regards, sambu _____________________________________________________________________ This e-mail message may contain proprietary, confidential or legally privileged information for the sole use of the person or entity to whom this message was originally addressed. Any review, e-transmission dissemination or other use of or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you have received this e-mail in error kindly delete this e-mail from your records. If it appears that this mail has been forwarded to you without proper authority, please notify us immediately at netadmin at patni.com and delete this mail. _____________________________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: From pyth0nc0d3r at gmail.com Mon Dec 15 08:36:47 2008 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Mon, 15 Dec 2008 07:36:47 -0600 Subject: Having Issues with CMD and the 'python' command In-Reply-To: References: Message-ID: It was python3 messing me up. I forgot I had python 3 on my box uninstalled it, redid it and wallah. On Mon, Dec 15, 2008 at 7:33 AM, wrote: > On Mon, 15 Dec 2008 at 07:16, Lamonte Harris wrote: > >> Yeah I tried doing it from the environment variables yet it still fails to >> work. >> > > Well, I can't be of any more help, then. It worked for me on my XP Home > box, and at this point we've exhausted my knowledge of windows :) > > --RDM > -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at marcher.name Fri Dec 26 11:31:47 2008 From: martin at marcher.name (Martin) Date: Fri, 26 Dec 2008 17:31:47 +0100 Subject: sys.stdout.write()'s bug or doc bug? In-Reply-To: References: Message-ID: <5fa6c12e0812260831y23cce99w7d8624429cee2199@mail.gmail.com> Sorry GMAIL got me again, I sent this in private first, apologies. hi, 2008/12/26 Qiangning Hong : >>>> sys.stdout.write(u) > Traceback (most recent call last): > File "", line 1, in > UnicodeEncodeError: 'ascii' codec can't encode character u'\u554a' in > position 0: ordinal not in range(128) >>>> type(sys.stdout) > >>>> sys.stdout.encoding > 'UTF-8' Python 2.4.4 (#2, Oct 22 2008, 19:52:44) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> u = u"\u554a" >>> print u ? >>> sys.stdout.write(u + "\n") Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\u554a' in position 0: ordinal not in range(128) >>> # you are trying to write unicode, you need to encode it to something that suits your needs >>> sys.stdout.write(u.encode("UTF-8") + "\n") ? >>> # now go and write a hundred times "Unicode is not an encoding" :) > So, my question is, as sys.stdout IS a file object, why it does not > use its encoding attribute to convert the given unicode? An > implementation bug? A documenation bug? hmm I always thought "sys.stdout" is a "file-like object" not that it IS a file. /martin -- http://soup.alt.delete.co.at http://www.xing.com/profile/Martin_Marcher http://www.linkedin.com/in/martinmarcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From steve at holdenweb.com Mon Dec 22 20:38:43 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 22 Dec 2008 20:38:43 -0500 Subject: Python's popularity In-Reply-To: <48221004-94ce-4b2a-b94a-1ca45a2562b8@j11g2000yqg.googlegroups.com> References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <6ra8t0F925rU1@mid.individual.net> <29feda0d-6432-4cb9-8809-e4d4a7798601@e1g2000pra.googlegroups.com> <6raeb8F9s47U2@mid.individual.net> <6rahpaFav7kU2@mid.individual.net> <97e49a8c-6730-42f2-b4d0-35eaff38b69f@y1g2000pra.googlegroups.com> <48221004-94ce-4b2a-b94a-1ca45a2562b8@j11g2000yqg.googlegroups.com> Message-ID: r wrote: > [Jeff] > but I raise the bar so that any random joker probably won't bother > (and making the reverse mapping - knowing my real identity and then > looking for recent net activity - is much more difficult to do) > [/Jeff] > > You are the epitimy of an internet troll. A troll tries to hide his > identity. Why are you so concerned about your TRUE identity. Are the > FEDS after you, maybe it's the Martians i do not know? Did they take > into their spaceship and do things to you? Do you wear a aluminum foil > hat. Look out for those cell towers, there mind control devices > hahaha. Thanks for the good laugh. Pot, meet kettle. Kettle: pot. -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From castironpi at gmail.com Wed Dec 10 02:21:54 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 9 Dec 2008 23:21:54 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> <014eee6d$0$20670$c3e8da3@news.astraweb.com> Message-ID: On Dec 9, 4:53?pm, Steven D'Aprano wrote: > On Tue, 09 Dec 2008 08:30:26 -0800, Aaron Brady wrote: > > The following are semantically equivalent: > > > I certainly wouldn't want something like PL/I, where "IF", "THEN" and > > "ELSE" could be identifiers. > > > I wouldn't want something like PL/I, where "IF", "THEN" and "ELSE" could > > be identifiers. > > "Certainly" adds emphasis. You don't just mildly not want something like > PL/I, but you really don't want it, so much so that you're amazed that > anyone might have thought you did. I see. He was expressing amazement too. This is distinct from a similar case, "-1 on including it, but it has some advantages, and could be useful for other purposes." He thinks it's a bad idea all around, not just ill-suited to Python. > The English language is very un-Pythonic. It especially breaks "Explicit > is better than implicit" -- words have many implied connotations which > are not necessarily found in dictionaries. For example, a "wise guy" and > a "wise man" are not the same thing, even though a guy and a man are the > same. I can't attest to many other languages, but the same might hold true. It's the speakers, not the language. English also breaks 'Errors should never pass silently', though more so in large "I have the conch" gatherings, and less so in smaller numbers. If I end up at the wrong restaurant for dinner, that's the equivalent (analogue) of reading from uninitialized memory, or other silently passed errors. 'Special cases aren't special enough to break the rules.' Italian breaks this one--- 700 irregular verbs! But the Esperanto community is growing... heh heh. English spelling is bad too: "if 'i' before 'e' and not after 'c': ...' It's not a fair fight though, between English and Python. There's no 'final say', that is, unifying vision, about what's legal in English. People will just talk. If everyone drops their articles tomorrow, English no longer has them. Perhaps you could compare Python to an audience to English with only one member. I guess I take 'complex' and 'nested' to be about the same. Back to topic, the 'eth' sound might be ugly to some humans. But that doesn't mean it's ugly to English speakers, let alone useless. I guess some people think the disjunction of 'useful' and 'ugly' is nearly empty. I think one of the things the Zen has going for it is its authors were (are) programmers-- they taste their own medicine. In naturally occurring large religions, the priests aren't peasants very often... though sometimes the prophets are. You could compare the Zen to 'folk wisdom' per se, rather than a religion (though the latter proclaims itself the former too often). Just because you defer to something, doesn't mean it's a religion. But if the content has drifted so far that Peters and van Rossum no longer follow it, it's a bad sign. From badmuthahubbard at usenet.cnntp.org Fri Dec 19 03:46:00 2008 From: badmuthahubbard at usenet.cnntp.org (Bad Mutha Hubbard) Date: 19 Dec 2008 08:46:00 GMT Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> Message-ID: <494b5f47$0$17068$6e1ede2f@read.cnntp.org> Roger wrote: > I've done a lot of googling for this topic and I fear that it's not > possible. I have a widget that is overloaded with several bindings. > I want to be able to unbind one method form the same Event without > destroying all the other bindings to the same event that's associated > to the same widget. > > For example: > > import Tkinter > > def test(): > print 'test' > > def test2(): > print 'test2' > > root = Tkinter.Tk() > funcid1 = root.bind("<1>", lambda e: test()) > funcid2 = root.bind("<1>", lambda e: test2(), add='+') > root.unbind("<1>", funcid2) > root.mainloop() > > When run neither <1> binding will exist against the root because the > unbind will unbind all the functions associated with that event. > However, in this example, I only want to unbind test2 not test1. > > Any help is greatly appreciated. Thanks! > Roger. I believe you've discovered a bug. Aside from recommending trying wxWidgets, here's the source of the unbind function in Tkinter.py: def unbind(self, sequence, funcid=None): """Unbind for this widget for event SEQUENCE the function identified with FUNCID.""" self.tk.call('bind', self._w, sequence, '') if funcid: self.deletecommand(funcid) ------------------------------------------- First, it replaces all bindings for the sequence with the empty string, i.e., it deletes all bindings for that event unconditionally. THEN it calls deletecommand() with the funcid, who knows what that does. My Tcl is not so sharp. I have an idea for a workaround, let me see if it works... -Chuckk From gneuner2 at comcast.net Fri Dec 12 14:47:17 2008 From: gneuner2 at comcast.net (George Neuner) Date: Fri, 12 Dec 2008 14:47:17 -0500 Subject: Mathematica 7 compares to other languages References: <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <48b8b065-6193-454c-a548-3117449f8a55@40g2000prx.googlegroups.com> <8evqj4p342jvcma5saibf54thv7075r88g@4ax.com> <9d5ecca4-3eb8-42ad-b4d8-951719ef874b@n33g2000pri.googlegroups.com> Message-ID: On Mon, 8 Dec 2008 15:14:18 -0800 (PST), Xah Lee wrote: >Dear George Neuner, > >Xah Lee wrote: >> >For example, >> >the level or power of lang can be roughly order as >> >this: >> >> >assembly langs >> >C, pascal >> >C++, java, c# >> >unix shells >> >perl, python, ruby, php >> >lisp >> >Mathematica > >George wrote: >> According to what "power" estimation? Assembly, C/C++, C#, Pascal, >> Java, Python, Ruby and Lisp are all Turing Complete. I don't know >> offhand whether Mathematica is also TC, but if it is then it is at >> most equally powerful. > >it's amazing that every tech geekers (aka idiots) want to quote >?Turing Complete? in every chance. Even a simple cellular automata, >such as Conway's game of life or rule 110, are complete. > >http://en.wikipedia.org/wiki/Conway's_Game_of_Life >http://en.wikipedia.org/wiki/Rule_110 > >in fact, according to Stephen Wolfram's controversial thesis by the >name of ?Principle of computational equivalence?, every goddamn thing >in nature is just about turing complete. (just imagine, when you take >a piss, the stream of yellow fluid is actually doing turning complete >computations!) Wolfram's thesis does not make the case that everything is somehow doing computation. >for a change, it'd be far more interesting and effective knowledge >showoff to cite langs that are not so-called fuck of the turing >complete. We geek idiots cite Turing because it is an important measure of a language. There are plenty of languages which are not complete. That you completely disregard a fundamental truth of computing is disturbing. >the rest of you message went on stupidly on the turing complete point >of view on language's power, mixed with lisp fanaticism, and personal >gribes about merits and applicability assembly vs higher level langs. You don't seem to understand the difference between leverage and power and that disturbs all the geeks here who do. We worry that newbies might actually listen to your ridiculous ramblings and be led away from the truth. >It's fine to go on with your gribes, but be careful in using me as a >stepping stone. Xah, if I wanted to step on you I would do it with combat boots. You should be thankful that you live 3000 miles away and I don't care enough about your petty name calling to come looking for you. If you insult people in person like you do on usenet then I'm amazed that you've lived this long. George From saluk64007 at gmail.com Wed Dec 10 16:16:54 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Wed, 10 Dec 2008 13:16:54 -0800 Subject: "as" keyword woes In-Reply-To: References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> <493FD8F6.3050803@mrabarnett.plus.com> Message-ID: On Wed, Dec 10, 2008 at 11:57 AM, Benjamin Kaplan wrote: > > > On Wed, Dec 10, 2008 at 12:22 PM, Patrick Mullen > wrote: >> >> I don't have a huge stake in this, but I wouldn't mind a change to >> allow anything proceeding a "." or preceeding a "(" to not be >> identified as a keyword. It is obvious to me a s a human reader that >> something.if is quite a bit different than just a bare if. And as far >> as parsing technology goes, isn't it supposed to go for the biggest >> match first? I would not be for allowing bare keywords to be used in >> the situations described above, but since we are so used to being able >> to being able to have say, myclass.dir() or myclass.len() without them >> overwriting the builtin functions, it makes sense to me to be able to >> define a myclass.as() or myclass.with() without overwriting the >> keywords. Though I know the semantics behind these two things are >> very different, the rules I go through when reading the code are very >> similar. The parser change might be a hassle, and it might not be >> worth it at all of course, but from a conceptual point of view it is >> simple. I mean, even now you can do class.__dict__["as"]. > > so what happens here? > > if(some_condition()) : > do_something(a) > > Yes, I know you don't need the parenthesis there in Python, but you still > can use it. > >> >> I guess I'm -1 for full PL/1 craziness, but +1 for qualified keyword >> usage. >> -- >> http://mail.python.org/mailman/listinfo/python-list > > Right, I now see how this scenario is tricky. It could maybe be in the form of " " but that starts getting pretty complicated. Too tricky. Following the period on the other hand still makes sense to me. It makes sense in the nature of "I wouldn't mind seeing this added", but I suppose it still might not make sense in the nature of "We should do the work to make this a reality". From walterbyrd at iname.com Mon Dec 22 10:11:02 2008 From: walterbyrd at iname.com (walterbyrd) Date: Mon, 22 Dec 2008 07:11:02 -0800 (PST) Subject: Python's popularity Message-ID: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> I have read that python is the world's 3rd most popular language, and that python has surpassed perl in popularity, but I am not seeing it. >From what I have seen: - in unix/linux sysadmin, perl is far more popular than python, windows sysadmins typically don't use either. - in web-development, php is far more popular than python - it's not even close. - when I did a search on dice, I found over 20X more jobs advertised for ruby on rails developers, than for python dango developers. - application development is dominated by java, c/c++, and maybe a little visual basic. - as I understand it, fortran is still the most popular language for numberical programming. Of course, these are just observations on my part, nothing scientific about it. But, I can't help but wonder how python's popularity was determined. I suspect that a lot of people use python as a secondary skill. For example, I use ms-word, but I'm not an ms-word professional. Please note: I am not confusing popularity with quality. I am not saying that php is better for web-dev, or anything like that. I am just wondering how python is rated as being so popular, when python does not seem to dominate anything. From atagar1 at gmail.com Tue Dec 30 19:04:28 2008 From: atagar1 at gmail.com (Damian Johnson) Date: Tue, 30 Dec 2008 16:04:28 -0800 Subject: Python 3.0 Curses Unicode In-Reply-To: References: Message-ID: Just resolved the issue (turned out to be an issue with linked ncurses libraries). If others run into this discussion of the solution can be found at: http://bugs.python.org/issue4787 Cheers! -Damian On Mon, Dec 29, 2008 at 10:30 PM, Damian Johnson wrote: > It seems as if the curses module in Python 3.0 isn't respecting the > system's preferred encoding (utf-8) which was set via: > locale.setlocale(locale.LC_ALL, '') > > The purpose of this was described at the top of ' > http://docs.python.org/dev/3.0/library/curses.html#module-curses'. The > getlocale function is reporting the proper values ('en_US', 'UTF8') but > addstr is clearly not treating it as Unicode - is this a bug? -Damian > > 2008/12/28 Damian Johnson > > Hi, I've switched to Python 3.0 for a new Japanese vocab quizzing >> application due to its much improved Unicode support. However, I'm running >> into an issue with displaying Unicode characters via curses. In Python 2.x a >> simple hello-world looks like: >> >> #!/usr/bin/python >> # coding=UTF-8 >> >> import curses >> import locale >> >> locale.setlocale(locale.LC_ALL,"") >> >> def doStuff(stdscr): >> message = u"hello ???!" >> stdscr.addstr(0, 0, message.encode("utf-8"), curses.A_BLINK) >> stdscr.getch() # pauses until a key's hit >> >> curses.wrapper(doStuff) >> >> This works. However, when I try to come up with an equivalent for Python >> 3.0: >> >> #!/usr/bin/python >> >> import curses >> import locale >> >> locale.setlocale(locale.LC_ALL,"") >> >> def doStuff(stdscr): >> message = "hello ???!" >> stdscr.addstr(0, 0, message, curses.A_BLINK) >> stdscr.getch() # pauses until a key's hit >> >> curses.wrapper(doStuff) >> >> It fails (printing gibberish to the console). Anyone have a clue what I'm >> doing wrong? Thanks! -Damian >> >> PS. Is the "# coding=UTF-8" header meaningless in Python 3.0? Also, is >> "locale.setlocale(locale.LC_ALL,"")" still necessary for getting curses to >> provide Unicode support? >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jimsgibson at gmail.com Thu Dec 11 15:11:06 2008 From: jimsgibson at gmail.com (Jim Gibson) Date: Thu, 11 Dec 2008 12:11:06 -0800 Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <5ebe5a7d-cbdf-4d66-a816-a7d2a0a273c9@40g2000prx.googlegroups.com> Message-ID: <111220081211063566%jimsgibson@gmail.com> In article <5ebe5a7d-cbdf-4d66-a816-a7d2a0a273c9 at 40g2000prx.googlegroups.com>, Xah Lee wrote: > On Dec 10, 2:47?pm, John W Kennedy wrote: > > Xah Lee wrote: > > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, > > > you'll have 50 or hundreds lines. > > > > C: > > > > #include > > #include > > > > void normal(int dim, float* x, float* a) { > > ? ? float sum = 0.0f; > > ? ? int i; > > ? ? float divisor; > > ? ? for (i = 0; i < dim; ++i) sum += x[i] * x[i]; > > ? ? divisor = sqrt(sum); > > ? ? for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; > > > > } > > > > Java: > > > > static float[] normal(final float[] x) { > > ? ? float sum = 0.0f; > > ? ? for (int i = 0; i < x.length; ++i) sum += x[i] * x[i]; > > ? ? final float divisor = (float) Math.sqrt(sum); > > ? ? float[] a = new float[x.length]; > > ? ? for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor; > > ? ? return a; > > > > } > > Thanks to various replies. > > I've now gather code solutions in ruby, python, C, Java, here: > > ? A Example of Mathematica's Expressiveness > http://xahlee.org/UnixResource_dir/writ/Mathematica_expressiveness.html > > now lacking is perl, elisp, which i can do well in a condensed way. > It'd be interesting also to have javascript... and perhaps erlang, > OCaml/F#, Haskell too. Perl: sub normal { my $sum = 0; $sum += $_ ** 2 for @_; my $length = sqrt($sum); return map { $_/$length } @_; } -- Jim Gibson From lolekk122333 at wp.pl Fri Dec 5 16:38:14 2008 From: lolekk122333 at wp.pl (girl18bebes) Date: Fri, 5 Dec 2008 13:38:14 -0800 (PST) Subject: +18! Hot girl sexy girl woman dance for mature older man! big boobs, hot ass, big booty tits breast, Hot sexy young girl woman, hot woman, sexy wo, sexy cougar babes, teens, bikini, virginman Message-ID: <45eca54f-90c4-47a8-9f30-8427c48bb3d8@y18g2000yqn.googlegroups.com> http://yeba.pl/show/movies/5257/Perfect_babe_-_Idealna_kobieta From robert.kern at gmail.com Thu Dec 4 14:34:14 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 04 Dec 2008 13:34:14 -0600 Subject: Python Dynamic Profiling In-Reply-To: References: Message-ID: esgameserver at gmail.com wrote: > Hi, > > Sorry for re-posting but I want to clarify my question again here. > > So, we have a multithreaded server application and I want to see the > profile of our code means which function is executed how many times > and time spent in that function dynamically. With dynamic, I mean > without stopping the profiled thread. > > Is there any way to do that, other than hacking my own code with hooks > and calculating the info above by hand? > > P.S:cProfile and Profile modules are very good indeed, but as far as I > understand you need to stop the profiler and the associated thread to > see the profile results. That is unacceptable for my situation. Don't use the run*() methods. Instead, use enable() and disable(). This means that the profiler isn't the thing calling your code. You can stop it and collect the profile information without halting your code. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From steve at REMOVE-THIS-cybersource.com.au Sun Dec 28 14:35:02 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Dec 2008 19:35:02 GMT Subject: "return" in def References: <408ed151-8618-4b4c-b97f-cec8212ccd8d@c36g2000prc.googlegroups.com> Message-ID: <0167cbf7$0$6988$c3e8da3@news.astraweb.com> On Sun, 28 Dec 2008 12:38:50 -0500, Steve Holden wrote: > Roger wrote: >> Hi Everyone, >> >> First I want to thank everyone that posts to this group. I read it >> daily and always learn something new even if I never feel like I have >> anything to contribute but my questions. >> >> When I define a method I always include a return statement out of habit >> even if I don't return anything explicitly: >> >> def something(): >> # do something >> return >> >> Is this pythonic or excessive? Is this an unnecessary affectation that >> only adds clock ticks to my app and would I be better off removing >> "returns" where nothing is returned or is it common practice to have >> returns. >> > It's an unnecessary affectation, but I don't believe it adds any clock > ticks to your app, as the function has to return anyway. The dis module > shows you they both generate exactly the same code: ... >> Even when I'm not explicitly returning something I like to add "return" >> because it's a good additional visual marker for me to see where a >> method definition ends especially in cases where I may use a nested >> method. >> > Well, I suppose at least you aren't writing "return None" ... Normally a > blank line or two suffices for me. Curious. When I see a bare return, the first thing I think is that the author forgot to include the return value and that it's a bug. The second thing I think is that maybe the function is a generator, and so I look for a yield. If I don't see a yield, I go back to thinking they've left out the return value, and have to spend time trying to understand the function in order to determine whether that is the case or not. In other words, even though it is perfectly valid Python, bare returns always make the intent of the function less clear for me. I'm with Bruno -- if you have a function with early exits, and you need to make the intent of the function clear, explicitly return None. Otherwise, leave it out altogether. -- Steven From google at mrabarnett.plus.com Thu Dec 25 19:46:54 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 26 Dec 2008 00:46:54 +0000 Subject: Mathematica 7 compares to other languages In-Reply-To: <8j78l4drqjg46ps74up555bfu44kct27f7@4ax.com> References: <49404775$0$4893$607ed4bc@cv.net> <452ba58b-9377-4463-85e2-5ecdaa25a129@t39g2000prh.googlegroups.com> <6375k4pf1mleb6im67nkpec5olqbsom88e@4ax.com> <8j78l4drqjg46ps74up555bfu44kct27f7@4ax.com> Message-ID: <4954297E.7090700@mrabarnett.plus.com> sln at netherlands.com wrote: > On Thu, 25 Dec 2008 21:50:29 +0000, Jon Harrop wrote: > >> Xah Lee wrote: >>>>> On Dec 10, 2:47 pm, John W Kennedy wrote: >>>>>> C: >>>>>> #include >>>>>> #include >>>>>> void normal(int dim, float* x, float* a) { >>>>>> float sum = 0.0f; >>>>>> int i; >>>>>> float divisor; >>>>>> for (i = 0; i < dim; ++i) sum += x[i] * x[i]; >>>>>> divisor = sqrt(sum); >>>>>> for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; >>>>>> } >>> Due to the low level of C, this C example should perhaps then accept a >>> sequence of numbers separated by space... >> In other words, you want a REPL. >> >> Why don't we have another challenge that involves handling a non-trivial >> input format, i.e. parsing? > > Maybe you could speed it up. > > sln > > ---------------------------------- > void normal (int Dimension, double *X, double *A) > { > double *xp, *ap, divisor, sum; > int i; > > for ( i=0, sum=0., xp=X; i sum += (*xp) ** 2; C doesn't have a "**" operator. > divisor = sqrt ( sum ); > for ( i=0, ap=A, xp=X; i *ap = *xp / divisor; > > // if Dimension is greater than > // sizeof double X[] or double A[] it will GPF. > // this is a really, really bad design. > } From roy at panix.com Mon Dec 29 10:32:55 2008 From: roy at panix.com (Roy Smith) Date: Mon, 29 Dec 2008 10:32:55 -0500 Subject: multiprocessing vs thread performance References: Message-ID: In article , Christian Heimes wrote: > You have missed an important point. A well designed application does > neither create so many threads nor processes. The creation of a thread > or forking of a process is an expensive operation. You should use a pool > of threads or processes. It's worth noting that forking a new process is usually a much more expensive operation than creating a thread. Not that I would want to create 100,000 of either! Not everybody realizes it, but threads eat up a fair chunk of memory (you get one stack per thread, which means you need to allocate a hunk of memory for each stack). I did a quick look around; 256k seems like a common default stack size. 1 meg wouldn't be unheard of. From dickinsm at gmail.com Sun Dec 7 13:14:06 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 7 Dec 2008 10:14:06 -0800 (PST) Subject: Rich Comparisons Gotcha References: Message-ID: <4f12f2b4-ef5e-4358-aa28-6ce51c2e10a7@a12g2000pro.googlegroups.com> On Dec 7, 4:23?pm, Rasmus Fogh wrote: > If is is possible to change the language, how about having two > diferent functions, one for overloading the '==' operator, and another > for testing list and set membership, dictionary key identity, etc.? I've often thought that this would have made a lot of sense too, though I'd probably choose to spell the well-behaved structural equality "==" and the flexible numeric equality "eq" (a la Fortran). Hey, we could have *six* new keywords: eq, ne, le, lt, ge, gt! See the recent (September?) thread "Comparing float and decimal" for some of the fun that results from lack of transitivity of equality. But I think there's essentially no chance of Python changing to support this. And even if there were, Python's conflation of structural equality with numeric equality brings significant benefits in terms of readability of code, ease of learning, and general friendliness; it's only really troublesome in a few corner cases. Is the tradeoff worth it? So for me, this comes down to a case of 'practicality beats purity'. Mark From robert.kern at gmail.com Tue Dec 2 19:28:55 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 02 Dec 2008 18:28:55 -0600 Subject: problem with optparse In-Reply-To: References: Message-ID: Neal Becker wrote: > This example is right out of python library reference. What's wrong here? > > import optparse > > def store_value(option, opt_str, value, parser): > setattr(parser.values, option.dest, value) > > parser = optparse.OptionParser() > parser.add_option("--foo", > action="callback", callback=store_value, > type="int", nargs=3, dest="foo") > > (opt,args) = parser.parse_args ('--foo a b c'.split()) > > [...] > /usr/lib64/python2.5/optparse.pyc in _process_args(self, largs, rargs, values) > 1423 elif self.allow_interspersed_args: > 1424 largs.append(arg) > -> 1425 del rargs[0] > 1426 else: > 1427 return # stop now, leave this arg in rargs > > TypeError: 'str' object doesn't support item deletion Dunno. It works for me (i.e. I get the expected "error: option --foo: invalid integer value: 'a'"). Have you tried it outside of IPython? -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sjmachin at lexicon.net Mon Dec 22 19:55:37 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 22 Dec 2008 16:55:37 -0800 (PST) Subject: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> Message-ID: <9eae14b8-93d6-4c34-b7d3-56c27408b52f@a26g2000prf.googlegroups.com> On Dec 23, 10:24?am, r wrote: > Because my balls are so big i walk around bow-legged! Have you considered that your alleged testicular enormity may in fact be an illusion caused by a hernia? From robert.kern at gmail.com Mon Dec 1 20:06:24 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 01 Dec 2008 19:06:24 -0600 Subject: optimization In-Reply-To: <6672532a-f162-4717-b0bb-c613214b57db@d32g2000yqe.googlegroups.com> References: <6672532a-f162-4717-b0bb-c613214b57db@d32g2000yqe.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Robert Kern: >> I only expect functions to be defined inside of functions if they are going to use lexical scoping for some reason.< > > There are other reasons to nest functions. One of them is to represent > logical nesting of some functionality. Is that any different than Neal's "if it's only used inside"? > So you will find some exceptions to your self-created rule :-) It's not a rule; it's just what I expect after many years of programming Python and reading lots of Python code. Most people define functions at the top-level regardless of whether they are used once or not. Defining a function inside of a function is an oddity. Lexical scoping requires that you define a function inside of a function, so that is always my first assumption about why the author defined the function there. I only fall back to "the author just wanted to organize things in a different way" when I fail to find the lexically-scoped variables, or I see a comment explaining it. I'm pretty sure that lexical scoping (and its poor-man implementation via keyword arguments before) is what the def-in-a-def feature was for, not organization. As Neal has observed, there is a performance hit for creating functions inside of another function. Every time you go through the outer function, you are creating new function objects for all of the inner functions. That's how you can get lexical scoping. It is not equivalent to defining the functions all at the top-level, where all of the function objects are created at once. The compiler can't optimize that overhead away because the overhead arises from implementing a real feature. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From cjwilliams43 at gmail.com Mon Dec 22 16:00:00 2008 From: cjwilliams43 at gmail.com (Colin J. Williams) Date: Mon, 22 Dec 2008 16:00:00 -0500 Subject: Check file is In-Reply-To: <494FF2BB.2050402@ulmcnett.com> References: <7caa7d45-ebbe-4c88-bb50-2f01f7315d07@s9g2000prg.googlegroups.com> <494cbef5$0$90267$14726298@news.sunsite.dk> <494FF2BB.2050402@ulmcnett.com> Message-ID: <494FFFD0.9020903@ncf.ca> An HTML attachment was scrubbed... URL: From philip at semanchuk.com Wed Dec 3 15:32:11 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Wed, 3 Dec 2008 15:32:11 -0500 Subject: Running a Python script from crontab In-Reply-To: <1f4901bb-012c-4e74-8650-c72d48203822@g38g2000yqn.googlegroups.com> References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> <126ba84a-0ea0-4a91-b7d2-89ed650e5d6c@d32g2000yqe.googlegroups.com> <1f4901bb-012c-4e74-8650-c72d48203822@g38g2000yqn.googlegroups.com> Message-ID: <19F946A1-D58F-4A04-B488-AD4BB9174DC7@semanchuk.com> On Dec 3, 2008, at 3:06 PM, Astley Le Jasper wrote: > On 3 Dec, 19:49, Philip Semanchuk wrote: >> On Dec 3, 2008, at 1:33 PM, Astley Le Jasper wrote: >> >>> On 3 Dec, 16:41, Philip Semanchuk wrote: >>>> On Dec 3, 2008, at 10:29 AM, Astley Le Jasper wrote: >> >>>>> I've included a switch to include or exclude theloggingto console. >>>>> Whenloggingonly to file, the script runs fine. >> >>>>> Of course, I still don't understand whyduallogging, and >>>>> specifically >>>>> to the console, causes a problem and if anyone has any comments >>>>> about >>>>> thedualoutputloggingcode above then I'd still be happy to hear >>>>> about it. >> >>>> Trying to write non-ASCII characters perchance? >> >>> Errmmm ... that's kind of spoookey. I using UTF-8 encoding as I >>> have a >>> lot of European language characters. But would that cause a problem >>> when running from crontab but not in the terminal? >> >>> Go on then ... spill the beans. >> >> Oh, I don't know exactly. It's just what I thought of when you said >> that the problem occurs when logging to the console but not to files. >> I don't have a deep Unix background so I can't give you the details >> on >> what "the console" means to a cron job. >> >> In my experience, the environment in which a cron job runs is >> different from the environment in which some command line scripts run >> (remember my earlier suggestion about needing to explicitly set the >> PATH?) and so if the console for a cron job differed from the console >> that a Python program sees when run in a terminal, that would not >> surprise me. >> >> Hope it's a useful suggestion >> Philip > > I tried using the path variables but it didn't help. There again, I > didn't really understand what was being passed in the path variables > and, rather than just copying and pasting, I wanted to look up further > info to get to grips with it. I've got something that works, so now > the pressure is off I can spend some time looking it up. > > [sigh ... my experiences with linux haven't been that good so far. It > is, if nothing else, interesting] Sorry, I was misleading. I don't think the PATH has anything to do with why your script can't log to the console when run as a cron job. I was just pointing out that my Python scripts have had environment- related problems when run as cron jobs, so it would not surprise me if that's your problem too. The PATH was just an example of an environment element that wasn't what I expected. Just a thought -- if my weak hunch that non-ASCII output is your problem, you might be able to test this easily (depending on how you use the logger) by forcing all output messages to "foo". If your cron job doesn't crash then, you know that the *content* of the output is probably the culprit which would indeed point to an encoding problem. HTH Philip From Russ.Paielli at gmail.com Thu Dec 18 21:47:38 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Thu, 18 Dec 2008 18:47:38 -0800 (PST) Subject: Factoring Polynomials References: <919062f9-765e-4279-aa26-2c130d4deacf@o4g2000pra.googlegroups.com> <4479b464-3a9b-4dd8-bf66-fea7d9471091@n33g2000pri.googlegroups.com> <661fd2d0-251d-4899-a015-8d257310a159@q26g2000prq.googlegroups.com> Message-ID: <6ce67c39-4d16-479f-87dd-a68d8000ce78@a26g2000prf.googlegroups.com> On Dec 18, 6:41?pm, "Russ P." wrote: > On Dec 18, 6:31?pm, Collin D wrote: > > > > > On Dec 18, 6:27?pm, Collin D wrote: > > > > On Dec 18, 6:23?pm, "Russ P." wrote: > > > > > On Dec 18, 6:17?pm, Collin D wrote: > > > > > > On Dec 18, 6:12?pm, Collin D wrote: > > > > > > > On Dec 18, 11:37?am, collin.da... at gmail.com wrote: > > > > > > > > I am trying to write a simple application to factor polynomials. I > > > > > > > wrote (simple) raw_input lines to collect the a, b, and c values from > > > > > > > the user, but I dont know how to implement the quadratic equation > > > > > > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > > > > > > into python. Any ideas? > > > > > > > I completed the code: > > > > > > > #import > > > > > > from math import sqrt > > > > > > > # collect data > > > > > > a = float(raw_input('Type a value: ')) > > > > > > b = float(raw_input('Type b value: ')) > > > > > > c = float(raw_input('Type c value: ')) > > > > > > > # create solver > > > > > > def solver(a,b,c): > > > > > > ? ? if b**2 - 4*a*c < 0: > > > > > > ? ? ? ? return 'No real solution.' > > > > > > ? ? else: > > > > > > ? ? ? ? sol1 = -1 * b + (sqrt(b**2 - 4*a*c)) / 2*a > > > > > > ? ? ? ? sol2 = -1 * b - (sqrt(b**2 - 4*a*c)) / 2*a > > > > > > ? ? ? ? return (sol1, sol2) > > > > > > > # execute > > > > > > print solver(a,b,c) > > > > > > > Thanks to everyone who helped... > > > > > > This really expanded my knowledge on some of the mathematical > > > > > > functions in Python. > > > > > > UPDATE: > > > > > ' > > > > > > #import > > > > > from math import sqrt > > > > > > # collect data > > > > > a = float(raw_input('Type a value: ')) > > > > > b = float(raw_input('Type b value: ')) > > > > > c = float(raw_input('Type c value: ')) > > > > > > # create solver > > > > > def solver(a,b,c): > > > > > ? ? if b**2 - 4*a*c < 0: > > > > > ? ? ? ? return 'No real solution.' > > > > > ? ? else: > > > > > ? ? ? ? sol1 = (-1 * b + (sqrt(b**2 - 4*a*c))) / 2*a > > > > > ? ? ? ? sol2 = (-1 * b - (sqrt(b**2 - 4*a*c))) / 2*a > > > > > ? ? ? ? return (sol1, sol2) > > > > > > # execute > > > > > print solver(a,b,c) > > > > > You need to put your denominator, 2*a, in parens. The way it stands, > > > > you are dividing by 2, then multiplying by a. That's not what you > > > > want. > > > > > Also, for better style, I suggest you compute the discriminanat once > > > > and store it for reuse rather than repeating the expression three > > > > times.- Hide quoted text - > > > > > - Show quoted text - > > > > I see what you mean on the denominator and discriminant. Ill do that.- Hide quoted text - > > > > - Show quoted text - > > > UPDATE: > > > #import > > from math import sqrt > > > # collect data > > a = float(raw_input('Type a value: ')) > > b = float(raw_input('Type b value: ')) > > c = float(raw_input('Type c value: ')) > > > # find discriminant > > disc = b**2 - 4*a*c > > > # create solver > > def solver(a,b,c): > > ? ? if disc < 0: > > ? ? ? ? return 'No real solution.' > > ? ? else: > > ? ? ? ? sol1 = (-1 * b + (sqrt(disc))) / (2*a) > > ? ? ? ? sol2 = (-1 * b - (sqrt(disc))) / (2*a) > > ? ? ? ? return (sol1, sol2) > > > # execute > > print solver(a,b,c) > > A couple of style points. I would use -b rather than -1 * b. Also, you > don't need the else clause. You can simplify it to > > def solver(a, b, c): > > ? ? disc = b**2 - 4 * a * c > > ? ? if disc < 0: return "No real solution." > > ? ? sol1 = (-b + sqrt(disc)) / (2*a) > ? ? sol2 = (-b - sqrt(disc)) / (2*a) > > ? ? return sol1, sol2 By the way, this little function is suitable for your purposes here, but it is not really a good general quadratic solver, because it returns different types depending on the inputs. For a good general function, you would probably want to throw an exception when the discriminant is negative (as an earlier poster suggested). From narkewoody at gmail.com Mon Dec 22 04:11:18 2008 From: narkewoody at gmail.com (Steven Woody) Date: Mon, 22 Dec 2008 17:11:18 +0800 Subject: How to represent a sequence of raw bytes In-Reply-To: References: <200812220327.36180.motoom@xs4all.nl> Message-ID: On Mon, Dec 22, 2008 at 4:35 PM, James Mills wrote: > On Mon, Dec 22, 2008 at 4:56 PM, Steven Woody wrote: >> I thing "\x11\x22\x33" in python is not the {0x11, 0x22, 0x33} in C. >> Since, a string in python is immutable, I can _not_ do something like: >> b[1] = "\x55". >> >> And, how about char buf[200] in my original question? The intension >> is to allocate 200 undefined bytes in memory. Thanks. > > Steven, one piece of advice. > > Python is not C. > > Thank. > > cheers > James > Ok, I will study all your advices. I think I may find my way when doing real tasks. From malaclypse2 at gmail.com Mon Dec 1 15:53:23 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 1 Dec 2008 15:53:23 -0500 Subject: Checking a string against multiple matches In-Reply-To: <279c426a-214c-4b6f-aaf2-989abd197744@v4g2000yqa.googlegroups.com> References: <99a3a677-a38d-40f5-9a94-a98865150b69@k19g2000yqg.googlegroups.com> <279c426a-214c-4b6f-aaf2-989abd197744@v4g2000yqa.googlegroups.com> Message-ID: <16651e80812011253j50f2cfcen980a679bbe0ce9c5@mail.gmail.com> On Mon, Dec 1, 2008 at 3:29 PM, Aaron Scott wrote: > Damn you, Python, and your loose documentation! It never occurred to > me to actually TRY my pseudocode, since I couldn't find anything on > that type of statement. Anyway, feel free to ignore me from now on. I'm not sure where you think the "in" operator should be documented. It's in the documentation for sequence types: http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange The tutorial points there too, in its discussion of strings. It's also in the language reference, in the section on comparision operators: http://docs.python.org/reference/expressions.html#id12 Was there someplace you were looking that you expected to find something about the containment operator and couldn't find it? Maybe it would be worth adding a "See Also" someplace? -- Jerry From geekmail at usenot.de Sun Dec 7 15:25:46 2008 From: geekmail at usenot.de (Andreas Waldenburger) Date: Sun, 7 Dec 2008 21:25:46 +0100 Subject: Python for kids? References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> Message-ID: <20081207212546.484c0d0e@usenot.de> On Sun, 7 Dec 2008 12:13:37 -0800 (PST) "Russ P." wrote: > I have a 12-year-old son who spends too much time playing Xbox live > and watching silly YouTube videos. I would like to try to get him > interested in programming. Is anyone aware of a good book or website > that addresses this concern, preferably (but not necessarily) using > Python? I could try to teach him Python myself, but I'm afraid I would > just frustrate him and kill his interest in programming. I did a > Google search and found a few things, but not a lot. Thanks. Since your son seems to enjoy games, getting him interested in game programming seems the most appropriate thing to do. I'm not much of a Gamer myself, but I should think maybe modding a shooter or other kind of game should be within the grasp of a 12 year old (provided you let him play shooters). Also, there's AGS (and friends) for making Adventure games. Depending on his interests, smaller projects might work out as well, such as Sudoku, Mahjongh, Card Games and whatnot. Any of those could well become father and son projects as long as you let him have the lead. Has he ever expressed an interest in programming at all? /W -- My real email address is constructed by swapping the domain with the recipient (local part). From google at mrabarnett.plus.com Fri Dec 5 14:15:11 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 05 Dec 2008 19:15:11 +0000 Subject: Overwrite single line of file In-Reply-To: References: Message-ID: <49397DBF.1060104@mrabarnett.plus.com> chrispoliquin at gmail.com wrote: > Hi, > > I have about 900 text files (about 2 GB of data) and I need to make > some very specific changes to the last line of each file. I'm > wondering if there is a way to just overwrite the last line of a file > or replace the spots I want (I even know the position of the > characters I need to replace). > > I know how to open files and read the contents and then write > everything out again after making the changes, but is there a way to > replace just the last line without having to completely rewrite each > file after making the changes? > f = open(path, "r+") f.seek(start_of_last_line) f.write(new_line) # Assuming that new_line ends with "\n" f.truncate() # In case the new line is shorter than what it's replacing f.close() From hniksic at xemacs.org Sat Dec 13 09:28:20 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sat, 13 Dec 2008 15:28:20 +0100 Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> <87iqpoc1l0.fsf@mulj.homelinux.net> <6qhk9dFclvujU1@mid.uni-berlin.de> Message-ID: <87bpvgb14r.fsf@mulj.homelinux.net> Marc 'BlackJack' Rintsch writes: > On Sat, 13 Dec 2008 02:20:59 +0100, Hrvoje Niksic wrote: > >> Saner (in this respect) behavior in the tuple example would require >> a different protocol. I don't understand why Python doesn't just >> call __iadd__ for side effect if it exists. The decision to also >> rebind the result of __i*__ methods continues to baffle me. I >> guess it is a result of a desire to enable the __i*__ methods to >> punt and return a different instance after all, but if so, that >> design decision brings more problems than benefits. > > How often do you use ``+=`` with mutable objects? I use it very > often with number types and sometimes with tuples, and there > rebinding is necessary. If I couldn't use it in this way: ``x = 0; > x += z``, I'd call that a bad design decision. It would be a quite > useless operator then. Marc, I agree with you, I wasn't arguing that += shouldn't work for immutable objects. If an object doesn't support __iadd__ at all (as is already the case for numbers, strings, etc.), += should fall back to __add__ followed by assignment. My point is that, *if they do*, it would be better to just use __iadd__ and not attempt to also rebind. Again, in pseudocode, I'd expect A += x to be implemented as: lhsobj = A if hasattr(lhsobj, '__iadd__'): lhsobj.__iadd__(x) # lhsobj has __iadd__, just use it else: A = lhsobj.__add__(x) # fails if __add__ is not present either That way tupleobj[0] += blah would work just fine for mutable objects and would throw an exception for immutable objects. The current situation where += first modifies the mutable object, and *then* throws an exception feels like a design glitch. From lie.1296 at gmail.com Fri Dec 12 16:00:38 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 12 Dec 2008 21:00:38 +0000 (UTC) Subject: (Very Newbie) Problems defining a variable References: Message-ID: On Fri, 12 Dec 2008 09:50:43 -0800, Dennis Lee Bieber wrote: > On Fri, 12 Dec 2008 03:42:55 -0800 (PST), febaen at gmail.com declaimed the > following in comp.lang.python: > >> #!/usr/bin/python >> #Py3k, UTF-8 >> >> bank = int(input("How much money is in your account?\n>>")) target = >> int(input("How much money would you like to earn each year? \n>>")) >> > Just for my curiosity -- did Python 3.x (besides turning print into > a function) also change input() to behave as the old raw_input()? > > The above would be very discouraged in Python 2.x... in favor of ... > int(raw_input(...)) > Actually, that's the first thing I wanted to bark on, before seeing the little note above it: "#Py3k, UTF-8". I wonder though, there is a potential problem if someone (users) is running this py3k code in a python2.x. The code is a perfectly legal and correct python 2.x code, but uses input() instead of raw_input(), we all know the evil of 2.x's input (). From 20080915.20.wmcclain at spamgourmet.com Tue Dec 9 14:24:13 2008 From: 20080915.20.wmcclain at spamgourmet.com (Bill McClain) Date: 9 Dec 2008 19:24:13 GMT Subject: StringIO in 2.6 and beyond References: Message-ID: On 2008-12-09, MRAB wrote: > In Python 2.x unmarked string literals are bytestrings. In Python 3.x > they're Unicode. The intention is to make the transition from 2.x to 3.x > easier by adding some features of 3.x to 2.x, but without breaking > backwards compatibility (not entirely successfully!). It is a bit ugly. In 2.6 StringIO won't take bytestrings, so I apply u'x'. But in 3.0 u'x' will be gone and I'll have to change the code again. It's a small effort for what I am working on, but frustrating trying to puzzle this out from the docs, which I couldn't do. -Bill -- Sattre Press History of Astronomy http://sattre-press.com/ During the 19th Century info at sattre-press.com by Agnes M. Clerke http://sattre-press.com/han.html From sumerc at gmail.com Tue Dec 30 03:16:14 2008 From: sumerc at gmail.com (k3xji) Date: Tue, 30 Dec 2008 00:16:14 -0800 (PST) Subject: Read-Write Lock vs primitive Lock() References: <277c1be7-2560-4fd6-9610-0b4398dc3719@x16g2000prn.googlegroups.com> Message-ID: > >> Note that the thread acquires the lock ONCE, repeats several thousand > >> times an assignment to a *local* variable called GLOBAL_VAR (!), finally > >> releases the lock and exits. As every thread does the same, they just ? > >> run > >> one after another, they never have a significant overlap. Ok. Forget about the GLOBAL_VAR. See the below code: import threading import locks import time GLOBAL_VAR = [] #GLOBAL_LOCK = locks.ReadWriteLock() GLOBAL_LOCK = threading.Lock() #GLOBAL_LOCK = mylock() GLOBAL_LOOP_COUNT = 10000000 GLOBAL_READER_COUNT = 100 GLOBAL_WRITER_COUNT = 1 global GLOBAL_LEN class wthread(threading.Thread): def run(self): try: GLOBAL_LOCK.acquireWrite() #GLOBAL_LOCK.acquire_write() #GLOBAL_LOCK.acquire() for i in range(GLOBAL_LOOP_COUNT): pass finally: #GLOBAL_LOCK.release_write() GLOBAL_LOCK.release() class rthread(threading.Thread): def run(self): try: GLOBAL_LOCK.acquireRead() #GLOBAL_LOCK.acquire_read() print 'ENTER:'+str(threading.currentThread()) #GLOBAL_LOCK.acquire() print 'ACQUIRE:'+str(threading.currentThread()) for i in range(GLOBAL_LOOP_COUNT): pass finally: #GLOBAL_LOCK.release_read() GLOBAL_LOCK.release() print 'RELEASE:'+str(threading.currentThread()) # module executed? if __name__ == "__main__": starttime = time.clock() threads = [] for i in range(GLOBAL_READER_COUNT): rt = rthread() threads.append(rt) for i in range(GLOBAL_WRITER_COUNT): wt = wthread() threads.append(wt) for thread in threads: thread.start() for thread in threads: thread.join() print "All operations took " + str(time.clock() - starttime) + " msecs" As GLOBAL_LOOP_COUNT is 10000000, now this is making a bottleneck on the readers. I had assumed that as everythread is given only 100 bytecodes to execute, that it will be enough to have a 10000 value for this number to let other rthread start() and try to acquire the lock. But, Python undocumentedly, does not grab the GIL easily if a Lock is held. This is strange for me. > > If I put the for loop outside, in that case, readers will not overlap > > at all, and you would be amazed by the numbers for that test. They > > indicate primitive lock is faster than read-write lock, as it requires > > the lock, executes only one bytecode operation and releases the lock. > > So, in order to create a bottlenneck on readers, we need to somehow do > > not release the lock immediately. > > Again, what is your specific use case? why do you think readers will see a ? > bottleneck? > > > With that, primitive locks perform 10 times better than Read-Write > > lock. See above. > > So what? You don't like such results? The read-write lock in the recipe ? > you posted is rather complex, and isn't obvious whether it is correct or ? > not, and the author doesn't prove it nor provide a reference. I'd stick to ? > the standard Lock object unless I have specific needs. > Note that threading.Lock objects are implemented in C and don't have ? > significant overhead (other than the wait itself); even threading.RLock ? > objects are a lot slower. So depending on what you really have to do, the ? > overhead of using a class like ReadWriteLock may be worse than using a ? > standard Lock. That may be the point. That is why I am trying to test this. When will ReadWrite() lock permforms better over the primitive lock. By the way, for the reference, the code in the recipe is used in CherryPy and based on the Tanenbaum's book Operating Systems Design. > >> Hmmm, it's a reader but attempts to modify the value? > >> You don't have to protect a read operation on a global variable - so a > >> lock isn't required here. > > > This is just for testing. Suppose that I am actually reading the > > value. I don't understand why a lock is not required? Are you saying > > lock is not necesary beacuse GLOBAL_VALUE is an immutable object, if > > then, suppose it is not. This is just a test. Suppose GLOBAl_VAR is a > > list and we are calling append() on it which is nt an atomic > > operation. > > It doesn't matter whether it is mutable or immutable. Remember that, in ? > Python, a global variable is just a *name* that refers to an object; you ? > either get the old object referred, or the new one. If it is a list and it ? > is being modified "in place", you always get the same list -- its contents ? > may differ from one instant to another so iterating over it isn't safe. > That's why I insist on knowing your use case: you may me doing things more ? > complicated than they should. I understand your point completely, but let's change anything inside the loop. Just assume that we a thread that is supposed to read something, and a thread that is supposed to write. If I create thousands of readers, and if the operation is enormously huge calculation(as Python does not grab GIL easily inside a Lock), then this will create a bottlencek on readers. But, with ReadWrite Lock this problem *SHOULD* be fixed and in my tests I see it is fixed, when I increase the time spent in the loop in huge amounts. > > Each thread in your original code were like this: > > begin thread; wait for lock; execute something locally; release lock; exit ? > thread; > > There was no shared state between threads. Even if you fix them to share ? > some variable, they were a single, sequential, piece of code (the inner ? > loop is irrelevant here). Once a thread gets the lock, it just runs to its ? > end. No one waits more than once for the lock. So all of them run ? > sequentially, in arbitrary order, but just one after the other. They never ? > overlap. You are correct about this. But this is an undocumented thing. I had assumed that Python will release GIL for other threads after 100 bytecodes are executed by default. However, as I stated, when a Lock() is held this is changing. I think this is because to avoid simple MT problems for new programmers. Not sure. I will read threads.c for information. Thanks. From steve at REMOVE-THIS-cybersource.com.au Fri Dec 12 19:00:24 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Dec 2008 00:00:24 GMT Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> Message-ID: <0152f29f$0$8244$c3e8da3@news.astraweb.com> On Fri, 12 Dec 2008 08:43:31 -0800, sturlamolden wrote: > On Dec 12, 5:13 pm, Steve Holden wrote: > >> > It should be the tuple's __setitem__ that was invoked here, not >> > __iadd__, or the parser is faulty. >> >> OK, so now you are proposing to alter the parser, and possibly the >> implementation of the INPLACE_ADD opcode in eval.c, so can you give us >> the patch for those, please? > > What? Take a look at the code again: > > mytuple[0] += 1 > > should never attempt an __iadd__ on mytuple. > > A sane parser would see this as: > > tmp = mytuple.__getitem__(0) > tmp = tmp.__iadd__(1) > mytuple.__setitem__(0, tmp) # should this always raise an exception? It is quite problematic if you do that. You've already pointed that out yourself, by asking if "should this always raise an exception?". With the behaviour you're asking for, there's ambiguity is what is allowed and what isn't. You can try making __setitem__ cleverer, as in your earlier post, but then: t = (1, 2, 3) t[0] += x sometimes succeeds, sometimes fails, depending on the value of x. And worse: t[0] = y also sometimes succeeds. It's not clear that those occasional successes are actively harmful, but nor is it clear that prohibiting them is harmful either. The best you get from it is the ability to mutate mutable items in a tuple, but you can do that already: t = ([], None) x = t[0] x += ["mutated"] So the current tuple implementation gives us consistent behaviour and simplicity without preventing you from mutating elements if you really want to. The only real cost is if you do this: t[0] += ["mutated"] you get an error and a mutation. Certainly a gotcha, but I wouldn't describe it as a bug: it's pretty much unavoidable if you want to avoid treating tuples as a special case. >> Discussion of such behavior as a "bug" is also pejorative, since the >> current semantics are the way they are by design. > > Right, this bug is by design. You learned that phrase from a guy in > Redmond? No. It merely means that just because you think it is a bug doesn't make it so. It may even mean that there is no perfect solution, that *any* behaviour on tuples containing mutable objects will be considered broken by some people under some circumstances. Trade-offs in software design are inevitable. There's little gain from your proposal, and some cost, and the problem you are trying to solve isn't a problem in practice. So if it's a bug, it's an insignificant one, not worth fixing because the fix will invariably cause more problems than the bug. -- Steven From klaus.kopec at tuebingen.mpg.de Wed Dec 10 05:03:12 2008 From: klaus.kopec at tuebingen.mpg.de (Klaus Kopec) Date: Wed, 10 Dec 2008 11:03:12 +0100 Subject: pickling a circular object inherited from list In-Reply-To: References: <3b1bab42-657c-4b93-9236-aa5236c16826@w1g2000prk.googlegroups.com> Message-ID: Ned Deily wrote: > In article , > Klaus Kopec wrote: >>>> What did I do wrong? >>> Old Python version? :) >>> Seems to work in 3.0 (don't have 2.6 currently to check but IMO it's >>> fixed there as well). >> It works for me with v3.0 as well, but not with v2.6.1 (same error as >> stated before for v2.4). >> >> Is there any way to fix this in v2.6.1 or even v2.4? Right now I cannot >> switch to v3.0 because I depend on several not compatible packages >> (numpy, biopython, ...) > > It looks like your example can be made to work by either specifying > pickle protocol 2 or by switching to cPickle. > Using pickle protocol 2 solved the problem. Thank you all for helping me out! From steven at REMOVE.THIS.cybersource.com.au Thu Dec 11 03:14:45 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 11 Dec 2008 08:14:45 GMT Subject: if expression source format References: Message-ID: On Thu, 11 Dec 2008 02:07:54 -0500, Lambert, David W (S&T) wrote: > The "if" expression leads to long statements. Please offer suggestions > to beautify this function. For this example use maximum line length > marked by the ####'s. > > Thank you. > > > ############################################################## > def compute_wind_chill_temperture(T:'Temperature, dF',s:'Wind speed, > mph')->'dF': > ''' > > ''' > return 35.74 + 0.6215*T + s**0.16*(T*0.4275-35.75) if T < 40 else T Firstly, you don't need "compute". Every function computes. Secondly, fix the spelling of temperature. Thirdly, we can make it easier to read by spreading it out. ############################################################## def wind_chill_temperature( T:'Temperature, dF',s:'Wind speed, mph')->'dF': 'http://www.erh.noaa.gov/er/iln/tables.htm#heat index' if T < 40: return 35.74 + 0.6215*T + s**0.16*(T*0.4275-35.75) else: return T There is no shortage of newlines. They are a renewable resource, don't be afraid to use a couple of extra lines to make your code more readable. -- Steven From matt at blackcodeseo.com Sat Dec 13 01:06:53 2008 From: matt at blackcodeseo.com (Matt) Date: Sat, 13 Dec 2008 01:06:53 -0500 Subject: using google search api for python Message-ID: You might want to try this Google Search API for Python. Sample implementation: >>> from Google import Google, search >>> results = search('blackcodeseo.com', 3) >>> for result in results: ? print 'Title: %s' % (result.title()) ? print 'Url: %s' % (result.url()) ? print 'Description: %s' % (result.description()) ? print ? Title: Black Code SEO Url: http://blackcodeseo.com/ Description: Oct 29, 2008 ? Black Code SEO. Programatically Automating SEO ? Download BlackCodeSeo Navigator. Run python setup.py install ? Title: Have A Question? Url: http://blackcodeseo.com/have-a-question/ Description: If you have any questions about anything, you can reach me at matt at blackcodeseo. com and I will be happy to reply. Your questions may be posted on the site ? Title: SpiderMonkey ? Didier Stevens Url: http://blog.didierstevens.com/programs/spidermonkey/ Description: The exact post is http://blackcodeseo.com/python-spidermonkey-navigator/. Comment by Matt ? Wednesday 29 October 2008 @ 20:56. Thanks. ? >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip at pobox.com Mon Dec 22 15:31:27 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 22 Dec 2008 14:31:27 -0600 Subject: I always wonder ... In-Reply-To: References: Message-ID: <18767.63775.837578.900457@montanaro-dyndns-org.local> Carl> ...shouldn't poeple who spend all their time following up to Carl> trolls, or starting new threads about trolls, being doing Carl> something else? Sure. It was just a momentary break from work, as is this. I thought an implied smiley was enough, but I guess not. Skip From Sengly.Heng at gmail.com Tue Dec 23 05:46:20 2008 From: Sengly.Heng at gmail.com (Sengly) Date: Tue, 23 Dec 2008 02:46:20 -0800 (PST) Subject: Very basic question Message-ID: <21ab1917-f0c9-48fb-baa9-02e5bf229bf5@s9g2000prm.googlegroups.com> Hello all, I would like to calculate a string expression to a float. For example, I have ('12/5') and I want 2.4 as a result. I tried to use eval but it only gives me 2 instead of 2.5 Help!!! Regards, Sengly From anthony.tolle at gmail.com Mon Dec 29 10:46:26 2008 From: anthony.tolle at gmail.com (anthony.tolle at gmail.com) Date: Mon, 29 Dec 2008 07:46:26 -0800 (PST) Subject: why cannot assign to function call References: Message-ID: <27ff529c-ac42-449c-87a4-64ecc6582b5f@t26g2000prh.googlegroups.com> On Dec 29, 1:01?am, scsoce wrote: > I have a function return a reference, and want to assign to the > reference, simply like this: > ?>>def f(a) > ? ? ? ? ? return a > ? ? ?b = 0 > ? ? * f( b ) = 1* > but the last line will be refused as "can't assign to function call". > In my thought , the assignment is very nature, ?but ?why the interpreter > refused to do that ? > > thks Probably the closest thing you are going to get in Python would be the following: >>> class C: ... pass ... >>> def f(a): ... return a ... >>> b = C() >>> b.value = 0 >>> b.value 0 >>> f(b).value = 1 >>> b.value 1 But as others have pointed out, Python is not C/C++, and shouldn't be treated as such. From sjmachin at lexicon.net Mon Dec 29 23:52:25 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 29 Dec 2008 20:52:25 -0800 (PST) Subject: Of console I/O, characters, strings & dogs References: Message-ID: <8814e07b-6d4f-4338-a96f-be16f46b12cd@w1g2000prk.googlegroups.com> On Dec 30, 11:53?am, David Lemper wrote: > I am trying getch() from msvcrt. Unfortunately the msvcrt docs have not been 2to3ified: """ msvcrt.getch() 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. msvcrt.getwch() Wide char variant of getch(), returning a Unicode value. """ In Python 3.0, getch() returns a length-1 bytes object. getwch() returns a length-1 str object. Suggestions: (1) Do more of the 3.0 tutorial so that you understand the bytes/str thing. (2) Use getwch instead of getch (3) Consider whether the builtins print() and input() cover your needs for console IO. HTH, John From Russ.Paielli at gmail.com Thu Dec 18 21:41:57 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Thu, 18 Dec 2008 18:41:57 -0800 (PST) Subject: Factoring Polynomials References: <919062f9-765e-4279-aa26-2c130d4deacf@o4g2000pra.googlegroups.com> <4479b464-3a9b-4dd8-bf66-fea7d9471091@n33g2000pri.googlegroups.com> <661fd2d0-251d-4899-a015-8d257310a159@q26g2000prq.googlegroups.com> Message-ID: On Dec 18, 6:31?pm, Collin D wrote: > On Dec 18, 6:27?pm, Collin D wrote: > > > > > On Dec 18, 6:23?pm, "Russ P." wrote: > > > > On Dec 18, 6:17?pm, Collin D wrote: > > > > > On Dec 18, 6:12?pm, Collin D wrote: > > > > > > On Dec 18, 11:37?am, collin.da... at gmail.com wrote: > > > > > > > I am trying to write a simple application to factor polynomials. I > > > > > > wrote (simple) raw_input lines to collect the a, b, and c values from > > > > > > the user, but I dont know how to implement the quadratic equation > > > > > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > > > > > into python. Any ideas? > > > > > > I completed the code: > > > > > > #import > > > > > from math import sqrt > > > > > > # collect data > > > > > a = float(raw_input('Type a value: ')) > > > > > b = float(raw_input('Type b value: ')) > > > > > c = float(raw_input('Type c value: ')) > > > > > > # create solver > > > > > def solver(a,b,c): > > > > > ? ? if b**2 - 4*a*c < 0: > > > > > ? ? ? ? return 'No real solution.' > > > > > ? ? else: > > > > > ? ? ? ? sol1 = -1 * b + (sqrt(b**2 - 4*a*c)) / 2*a > > > > > ? ? ? ? sol2 = -1 * b - (sqrt(b**2 - 4*a*c)) / 2*a > > > > > ? ? ? ? return (sol1, sol2) > > > > > > # execute > > > > > print solver(a,b,c) > > > > > > Thanks to everyone who helped... > > > > > This really expanded my knowledge on some of the mathematical > > > > > functions in Python. > > > > > UPDATE: > > > > ' > > > > > #import > > > > from math import sqrt > > > > > # collect data > > > > a = float(raw_input('Type a value: ')) > > > > b = float(raw_input('Type b value: ')) > > > > c = float(raw_input('Type c value: ')) > > > > > # create solver > > > > def solver(a,b,c): > > > > ? ? if b**2 - 4*a*c < 0: > > > > ? ? ? ? return 'No real solution.' > > > > ? ? else: > > > > ? ? ? ? sol1 = (-1 * b + (sqrt(b**2 - 4*a*c))) / 2*a > > > > ? ? ? ? sol2 = (-1 * b - (sqrt(b**2 - 4*a*c))) / 2*a > > > > ? ? ? ? return (sol1, sol2) > > > > > # execute > > > > print solver(a,b,c) > > > > You need to put your denominator, 2*a, in parens. The way it stands, > > > you are dividing by 2, then multiplying by a. That's not what you > > > want. > > > > Also, for better style, I suggest you compute the discriminanat once > > > and store it for reuse rather than repeating the expression three > > > times.- Hide quoted text - > > > > - Show quoted text - > > > I see what you mean on the denominator and discriminant. Ill do that.- Hide quoted text - > > > - Show quoted text - > > UPDATE: > > #import > from math import sqrt > > # collect data > a = float(raw_input('Type a value: ')) > b = float(raw_input('Type b value: ')) > c = float(raw_input('Type c value: ')) > > # find discriminant > disc = b**2 - 4*a*c > > # create solver > def solver(a,b,c): > ? ? if disc < 0: > ? ? ? ? return 'No real solution.' > ? ? else: > ? ? ? ? sol1 = (-1 * b + (sqrt(disc))) / (2*a) > ? ? ? ? sol2 = (-1 * b - (sqrt(disc))) / (2*a) > ? ? ? ? return (sol1, sol2) > > # execute > print solver(a,b,c) A couple of style points. I would use -b rather than -1 * b. Also, you don't need the else clause. You can simplify it to def solver(a, b, c): disc = b**2 - 4 * a * c if disc < 0: return "No real solution." sol1 = (-b + sqrt(disc)) / (2*a) sol2 = (-b - sqrt(disc)) / (2*a) return sol1, sol2 From sjmachin at lexicon.net Tue Dec 30 21:32:39 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 30 Dec 2008 18:32:39 -0800 (PST) Subject: TypeError: list indices must be integers References: <2e5a61c0-fa99-4170-81ca-eb3a10859400@k36g2000pri.googlegroups.com> Message-ID: <472447d7-9ed2-4bf2-bb8f-a0c62735316e@q30g2000prq.googlegroups.com> On Dec 31, 12:46?pm, dubux wrote: > my head hurts from looking at it so long. > ? ? ? ? ? ? ? ? mylist = map(lambda i: news_list[i], filter(lambda i: i%2 == 0, range(len(news_list)))) > ? ? ? ? ? ? ? ? date = mylist[y] My head hurts from looking at that only briefly. Any good reason why you wrote that in such a fashion instead of: mylist = news_list[::2] date = mylist[y] or (even better): date = news_list[y * 2] ? From jstroud at mbi.ucla.edu Thu Dec 25 07:02:02 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 25 Dec 2008 04:02:02 -0800 Subject: Is there a function to remove escape characters from a string ? In-Reply-To: References: Message-ID: <%CK4l.11459$c45.7073@nlpi065.nbdc.sbc.com> Stef Mientki wrote: > hello, > > Is there a function to remove escape characters from a string ? > (preferable all escape characters except "\n"). > > thanks, > Stef import string WANTED = string.printable[:-5] + "\n" def descape(s, w=WANTED): return "".join(c for c in s if c in w) James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From exarkun at divmod.com Wed Dec 17 08:52:36 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 17 Dec 2008 08:52:36 -0500 Subject: Transferring a file over sockets In-Reply-To: Message-ID: <20081217135236.20272.889774205.divmod.quotient.22188@ohm> On Wed, 17 Dec 2008 17:41:46 +0530, Ferdinand Sousa wrote: >I am using sockets to transfer a file over LAN. There are 2 scripts, the >server opens a listens for connection and the client is run on another >machine. I always make sure the server is run first. The strange thing is >that if the the server script is double-clicked and executed (run in a >console with title %Python path%python.exe) the output file saved on the >server is truncated. It works just fine if you open the server script in >IDLE and then run it. The client script can be run in either way, it still >works. You could try using any arbitrary file to test this behaviour after >changing the file name in both the scripts. > >========================================================== ># file receiver ># work in progress > >import socket > >s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >HOST = '192.168.1.17' >PORT = 31400 > >s.bind((HOST, PORT)) >s.listen(3) >conn, addr = s.accept() >print 'conn at address',addr >conn.send('READY') >f = open('C:\\Documents and Settings\\USER\\Desktop\\test.pdf','wb') >fsize=int(conn.recv(8)) >print 'File size',fsize >f.write(conn.recv(fsize)) >f.close() >conn.close() >s.close() > >raw_input('Press any key to exit') > > >=========================================================== > ># file sender !!! ># Work in progress > >import socket, os >from stat import ST_SIZE > > >HOST = '192.168.1.17' >PORT = 31400 # Arbitrary non-privileged port > >s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > >s.connect((HOST,PORT)) >if s.recv(5)!='READY': > raw_input('Unable to connect \n\n Press any key to exit ...') > s.close() > exit() > >f=open('C:\\Documents and Settings\\USER\\Desktop\\t.pdf', 'rb') >fsize=os.stat(f.name)[ST_SIZE] > >s.send(str(fsize)) >s.send(f.read()) > >s.close() >f.close() > >=========================================================== > >Thanks for reading!! You're not handling your sockets properly. send() does not necessary send the entire string you pass to it. recv(n) does not necessarily return an n-length string. Read the socket documentation more carefully and try fixing those issues. Or try using Twisted which presents a somewhat easier API to use. Jean-Paul From deets at nospam.web.de Tue Dec 9 04:06:52 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 09 Dec 2008 10:06:52 +0100 Subject: ORB for Python and PHP In-Reply-To: References: <6q5idtFb0dk0U1@mid.uni-berlin.de> Message-ID: <6q6qphFaob49U1@mid.uni-berlin.de> Laszlo Nagy schrieb: > >>> >>> There are others but they do not support both Python and PHP. Should >>> I implement my own ORB, or do you know a suitable solution? >> >> >> The whole purpose of an ORB ist that it is interoperable. So if you >> have a good python orb (I personally prefer OmniORB), and a good one >> for PHP - connect them. > Are all ORBs compatible with each other? I know that this is offtopic, > but do you know any ORB for PHP? I couldn't find any. As I said - that's the *purpose* of ORBs. It has taken a while, but AFAIK by now CORBA2.3 is pretty stable. What about this? http://phporb.sourceforge.net/ I never used it though. PHP isn't to well suited for CORBA, due to the request/response-cycle based architecture. >> I would suggest a consistent XMLRPC-interface though. > Unfortunately, this would not be good. Sometimes we need to pass through > binary data (image file), do session management (which is hard to do > with xml-rpc, where each request is a new connection) and optimize speed > for communication when the parties are on the same machine. Then maybe thrift is for you. http://wiki.apache.org/thrift/ThriftGeneration Diez From rdmurray at bitdance.com Fri Dec 5 11:20:28 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Fri, 5 Dec 2008 11:20:28 -0500 (EST) Subject: pretty strange behavior of "strip" In-Reply-To: References: <4938693F.6090709@yahoo.ca> Message-ID: On Fri, 5 Dec 2008 at 07:54, Mark Tolonen wrote: >> > > import re >> > > re.split('[,.]','blah,blah.blah') > ['blah', 'blah', 'blah'] Thank you. Somehow it never occurred to me that I could use that kind of pattern that way. I guess my brain just doesn't think in regexes very well :) --RDM From toby at telegraphics.com.au Wed Dec 3 23:15:24 2008 From: toby at telegraphics.com.au (toby) Date: Wed, 3 Dec 2008 20:15:24 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <591e8625-7e4d-4db8-ae6c-73c4370f8088@q26g2000prq.googlegroups.com> <6plpnsF8pi3oU1@mid.individual.net> Message-ID: <6c702fda-1a8a-4c3d-a7c0-82e45edab2ce@k41g2000yqn.googlegroups.com> On Dec 2, 5:04 pm, Tamas K Papp wrote: > On Tue, 02 Dec 2008 13:57:35 -0800, Lew wrote: > > Xah Lee wrote: > >> If [yo]u would like to learn [the] [E]nglish lang[uage] and writing > >> insights from me, peruse: > > > /Au contraire/, I was suggesting a higher standard for your posts. > > Hi Lew, > > It is no use. Xah has been posting irrelevant rants in broken English > here for ages. No one knows why, but mental institutions must be really > classy these days if the inmates have internet access. Just filter him > out with your newsreader. You think the posts are bad... check out his web site... --T > > Best, > > Tamas From arnodel at googlemail.com Tue Dec 16 04:10:04 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 16 Dec 2008 09:10:04 +0000 Subject: weird dict problem, how can this even happen? References: Message-ID: Joel Hedlund writes: > I'm having a very hard time explaining why this snippet *sometimes* > raises KeyError: > > snippet: >> print type(self.pool) >> for frag in self.pool.keys(): >> if frag is fragment_info: >> print "the fragment_info *is* in the pool", hash(frag), hash(fragment_info), hash(frag) == hash(fragment_info), frag == fragment_info, frag in self.pool, frag in self.pool.keys() >> try: >> renderer_index = self.pool.pop(fragment_info) >> except KeyError: >> print "Glorious KeyError!" >> for frag in self.pool.keys(): >> if frag is fragment_info: >> print "the fragment_info *is* in the pool", hash(frag), hash(fragment_info), hash(frag) == hash(fragment_info), frag == fragment_info, frag in self.pool, frag in self.pool.keys() >> raise > > > output: >> >> the fragment_info *is* in the pool 987212075 987212075 True True False True >> Glorious KeyError! >> the fragment_info *is* in the pool 987212075 987212075 True True False True >> Traceback (most recent call last): >> File "/home/yohell/workspace/missy/core/gui.py", line 92, in process_job >> renderer_index = self.pool.pop(fragment_info) >> KeyError: > > This snippet is part of a much larger gtk program, and the problem > only from time to time, predominantly when the cpu is under heavy load > and this method gets called a lot. If I didn't know better I'd say > it's a bug in python's dict implementation, but I do know better, so I > know it's far more likely that I've made a mistake somewhere. I'll be > damned if I can figure out what and where though. I've reproduced this > bug (?) with python-2.5.2 on Ubuntu 8.10 and python-2.5.1 on WinXP. > > I would very much like an explanation to this that does not involve > threads, because I haven't made any that I'm aware of. I can't even > understand how this could happen. How do I even debug this? > > Please help, I feel like I've taken crazy pills here! > /Joel Hedlund It could happen if two object x and y are such that hash(x) != hash(y) but x == y, breaking the requirement on hash values. HTH -- Arnaud From steve at REMOVE-THIS-cybersource.com.au Wed Dec 31 10:33:54 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Dec 2008 15:33:54 GMT Subject: change only the nth occurrence of a pattern in a string References: <0scs26-7a5.ln1@rama.fbx.proxad.net> Message-ID: <016b87de$0$6988$c3e8da3@news.astraweb.com> On Wed, 31 Dec 2008 15:40:32 +0100, TP wrote: > Hi everybody, > > I would like to change only the nth occurence of a pattern in a string. > The problem with "replace" method of strings, and "re.sub" is that we > can only define the number of occurrences to change from the first one. > >>>> v="coucou" >>>> v.replace("o","i",2) > 'ciuciu' >>>> import re >>>> re.sub( "o", "i", v,2) > 'ciuciu' >>>> re.sub( "o", "i", v,1) > 'ciucou' > > What is the best way to change only the nth occurence (occurrence number > n)? Step 1: Find the nth occurrence. Step 2: Change it. def findnth(source, target, n): num = 0 start = -1 while num < n: start = source.find(target, start+1) if start == -1: return -1 num += 1 return start def replacenth(source, old, new, n): p = findnth(source, old, n) if n == -1: return source return source[:p] + new + source[p+len(old):] And in use: >>> replacenth("abcabcabcabcabc", "abc", "WXYZ", 3) 'abcabcWXYZabcabc' > Why this default behavior? For the user, it would be easier to put > re.sub or replace in a loop to change the first n occurences. Easier than just calling a function? I don't think so. I've never needed to replace only the nth occurrence of a string, and I guess the Python Development team never did either. Or they thought that the above two functions were so trivial that anyone could write them. -- Steven From cournape at gmail.com Mon Dec 29 22:19:02 2008 From: cournape at gmail.com (David Cournapeau) Date: Tue, 30 Dec 2008 12:19:02 +0900 Subject: print a vs print '%s' % a vs print '%f' a Message-ID: <5b8d13220812291919h700f1586q5ab68ec6edb927f1@mail.gmail.com> Hi, While working on some python C extensions, I got curious in how things work for printing float objects (and C-level objects which inherit from it). In python 2.6, I understand that the formatting went into surgery for more consistency across platforms. So for example, on windows, complex('inf') would be printed 'inf', and not '1.#INF'. However, I would like some clarifications if possible about the following: a = complex('inf') print a # -> print 'inf' print '%s' % a # -> print 'inf' print '%f' % a # -> print '1.#INF' My understanding is that in the first case, the formatting is controlled through the tp_print and in the second case, from str(a) behavior (tp_str). Can the 3rd one be controled at all ? Or is it going directly through the underlying C runtime, without python doing any formatting (which is how I understand the inconsistency). Is this by design ? thanks, David From rocky at panix.com Thu Dec 11 05:17:09 2008 From: rocky at panix.com (R. Bernstein) Date: Thu, 11 Dec 2008 05:17:09 -0500 Subject: Custom debugger trace hooks Message-ID: A colleague recently asked this: Is there a cleaner way to dump a trace/track of running a python script. With Pydb I made work-around with import pydb pydb.debugger(dbg_cmds=['bt', 'l', 's']*300 + ['c']) So now I have a dump of 300 steps with backtraces, so I can easily compare two executions of the same script to find where they diverged. I think it is a really nice feature. pydb and pdb inherit from the cmd module which does allow pre- and post-command hooks. Neither pdb nor pydb make it easy to add one's own hook. However If there's something you want to run before stepping you can do that by monkey-patching Pdb.precmd: #################### snip import pydb def myprecmd(obj, debug_cmd): """Custom Hook method executed before issuing a debugger command.""" global _pydb_trace obj.do_list('') obj.do_where('10') # limit stack to at most 10 entries return obj.old_precmd(debug_cmd) # is always string 's' in example below _pydb_trace = pydb.Pdb() pydb.Pdb.old_precmd = pydb.Pdb.precmd pydb.Pdb.precmd = myprecmd pydb.debugger(dbg_cmds=['s'] * 30) # .... #################### I believe the same is applicable to pdb, although I haven't investigated. From prologic at shortcircuit.net.au Thu Dec 4 18:51:50 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 5 Dec 2008 09:51:50 +1000 Subject: pretty strange behavior of "strip" In-Reply-To: <4938693F.6090709@yahoo.ca> References: <4938693F.6090709@yahoo.ca> Message-ID: On Fri, Dec 5, 2008 at 9:35 AM, Guy Doune wrote: >>>> test=['03.html', '06.html', 'questions.html', '04.html', 'toc.html', >>>> '01.html', '05.html', '07.html', '02.html', '08.html'] >>>> test > ['03.html', '06.html', 'questions.html', '04.html', 'toc.html', '01.html', > '05.html', '07.html', '02.html', '08.html'] >>>> test[4] > 'toc.html' >>>> test[4].strip('.html') > 'oc' I believe you're after this: >>> test=['03.html', '06.html', 'questions.html', '04.html', 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] >>> test ['03.html', '06.html', 'questions.html', '04.html', 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] >>> from os.path import splitext >>> files = [splitext(x)[0] for x in test] >>> files ['03', '06', 'questions', '04', 'toc', '01', '05', '07', '02', '08'] >>> And no, it's not a bug. Read the docs :) cheers James -- -- -- "Problems are solved by method" From jstroud at mbi.ucla.edu Sat Dec 13 22:27:51 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 13 Dec 2008 19:27:51 -0800 Subject: Need help improving number guessing game In-Reply-To: <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> Message-ID: feba wrote: > This is what I have so far. better? worse? Much better. I didn't check if it works. But you need to figure out a way to give up on your reliance on global variables. They will end up stifling you in the long run when you move to substantial projects. Also, you should start moving the nested if: then: blocks to functions. Finally, you should limit your lines to no more than 80 chars. I do 71. Don't be afraid to use transient variables to help. Be assured that it takes on special intelligence to write unintelligible code at will. Also be assured that fitting everything on one line is not a good way to save time. Aim for clarity. If you want to start off on the right foot, you'll grind on your guessing game until all variables are insulated within local scope and the logic of the program becomes apparent from its architecture as a collection of functions. This is an example of how to combine these concepts: def update_scores(player, p1sc, p2sc): if player == "P1": plsc +=1 else: p2sc +=1 tmplt = "CONGRATULATIONS %s! SCORE -- P1:%s P2:%s" print(tmplt % (player, p1sc, p2sc)) return p1sc, p2sc p1sc, p2sc = update_scores(player, p1sc, p2sc) Finally, put comments on their own lines. Google "python style guide". James From Scott.Daniels at Acm.Org Mon Dec 1 19:35:44 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 01 Dec 2008 16:35:44 -0800 Subject: unicode and hashlib In-Reply-To: References: <8af54b5f-d21b-4794-9bce-afc96ea4db74@j11g2000yqg.googlegroups.com> Message-ID: <6qydnbFh7MOAH6nUnZ2dnUVZ_orinZ2d@pdx.net> Bryan Olson wrote: > ... I think that's good behavior, except that the error message is likely > to end beginners to look up the obscure buffer interface before they find > they just need mystring.decode('utf8') or bytes(mystring, 'utf8'). Oops, careful here (I made this mistake once in this thread as well). You _decode_ from unicode to bytes. The code you quoted doesn't run. This does: >>> a = 'Andr\xe9' >>> b = unicode(a, 'cp1252') >>> b.encode('utf-8') 'Andr\xc3\xa9' >>> b.decode('utf-8') Traceback (most recent call last): File "", line 1, in b.decode('utf-8') File "C:\Python26\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 4: ordinal not in range(128) >>> hashlib.md5(b.encode('utf-8')).hexdigest() '45f1deffb45a5f6c2380a4cee9b3e452' >>> hashlib.md5(b.decode('utf-8')).hexdigest() Traceback (most recent call last): File "", line 1, in hashlib.md5(b.decode('utf-8')).hexdigest() File "C:\Python26\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 4: ordinal not in range(128) > Incidentally, MD5 has fallen and SHA-1 is falling. Python's hashlib also > includes the stronger SHA-2 family. Well, the choice of hash always depends on the app. -Scott From accurateengines at yahoo.com Wed Dec 10 02:45:12 2008 From: accurateengines at yahoo.com (Mike Kolbet) Date: Tue, 9 Dec 2008 23:45:12 -0800 (PST) Subject: Accessing __slots__ from C Message-ID: <385465.38128.qm@web31606.mail.mud.yahoo.com> -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Dec 12 08:31:25 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Dec 2008 08:31:25 -0500 Subject: var or inout parm? In-Reply-To: References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> Message-ID: sturlamolden wrote: > On Dec 12, 1:56 pm, sturlamolden wrote: > >> That is because integers are immutable. When x += 1 is done on an int, >> there will be a rebinding. But try the same on say, a numpy array, and >> the result will be different: > > > And a consequence of this is, if you have a function like > > def foobar(x): > x += 1 > > then the parameter x will be modified given that x have mutable type. > > However, if we have a function like > > def foobar(x): > x = x + 1 > > then x will not be modified, mutable or not. > > (Well, you could abuse operator overlaoding to make unexpected side > effects in the latter case. But except for such insanity it will not > have side-effects.) > This was all thrashed out exhaustively in the still-feared call semantics thread. Yes, augmented operations work differently on mutable and immutable objects. Nothing to see here, move right along ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From callen314 at gmail.com Tue Dec 16 15:44:59 2008 From: callen314 at gmail.com (Craig Allen) Date: Tue, 16 Dec 2008 12:44:59 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> Message-ID: On Dec 14, 6:38 pm, cm_gui wrote: > hahaha, do you know how much money they are spending on hardware to > make > youtube.com fast??? > > > By the way... I know of a very slow Python site called YouTube.com. In > > fact, it is so slow that nobody ever uses it. less than they'd spend to implement it in C From yaksavage at gmail.com Tue Dec 2 22:38:36 2008 From: yaksavage at gmail.com (thor) Date: Tue, 2 Dec 2008 19:38:36 -0800 (PST) Subject: best way to do this References: Message-ID: <137514ca-d16c-4713-b14f-e12ab4f607ab@c36g2000prc.googlegroups.com> On Dec 2, 10:09?pm, TP wrote: > Hi everybody, > > >>> c=[(5,3), (6,8)] > > From c, I want to obtain a list with 5,3,6, and 8, in any order. > I do this: > > >>> [i for (i,j) in c] + [ j for (i,j) in c] > > [5, 6, 3, 8] > > Is there a quicker way to do this? > >>> c = [(5, 3), (6, 8)] >>> [x for t in zip(*c) for x in t] [5, 6, 3, 8] From makobu.mwambiriro at gmail.com Wed Dec 31 16:46:48 2008 From: makobu.mwambiriro at gmail.com (makobu) Date: Wed, 31 Dec 2008 13:46:48 -0800 (PST) Subject: PyS60, GPS and SMS Message-ID: ######################################################## # Send an SMS with your current GPS co-ordinates using a # Nokia SmartPhone and PyS60 # # Timothy Makobu, 01-01-2009 ######################################################## import positioning import messaging import appuifw import sys # Get your GPS co-ordinates # def getCoordinates(): positioning.select_module(positioning.default_module()) positioning.set_requestors([{'type':'service', 'format':'application','data':'position'}]) try: sys.stdout.write('Retrieving GPS co-ordinates ...\n') data = positioning.position(course=1, satellites=1) except: sys.stdout.write('Could not retrieve GPS co-ordinates\n\n\n') sys.exit(-1) else: sys.stdout.write('GPS co-ordinates retrieved\n') return (data['position']['latitude'], data['position'] ['longitude']) # Send your GPS co-ordinates as an SMS # def sendCoordinates(coords, number): message = u'I\'m at location:\nLatitute --> %f\nLongitute --> %f \n' % coords try: sys.stdout.write('Sending SMS ...\n') messaging.sms_send(number, message) except: sys.stdout.write('Could not send SMS :(\n\n\n') sys.exit(-1) else: sys.stdout.write('SMS sent :)\n') if __name__ == '__main__': presetPhoneNumber = None # Enter phoneNumber here eg '+254722000000' phoneNumber = presetPhoneNumber or appuifw.query(u'Enter number: ','text') if not phoneNumber: sys.stdout.write('No number entered; exiting ...\n\n\n') sys.exit(-1) sendCoordinates(getCoordinates(), phoneNumber) From ianare at gmail.com Tue Dec 16 13:20:52 2008 From: ianare at gmail.com (=?ISO-8859-1?B?aWFuYXLp?=) Date: Tue, 16 Dec 2008 10:20:52 -0800 (PST) Subject: sorting for recursive folder rename Message-ID: Hello all, I trying to recursively rename folders and files, and am looking for some ideas on the best way of doing this. The problem is that the given list of items can be in order, and one to all items may be renamed. Here is some preliminary code I have, but which does not work very well. self.toRename has the following structure : [ [original_name, new_name, os.path.isdir] .. ] # define these here for faster processing def split(item): return os.path.split(item) def addSep(path): return os.sep + path + os.sep def recursiveFolderSort(x,y): return cmp(y[0], x[0]) sortedRename = sorted(self.toRename) # make a list of all folders that will be processed foldersToAdjust = [] for item in sortedRename: if item[2] is False: oF = split(item[0])[1] # original folder name nF = split(item[1])[1] # new folder name if oF is not nF: foldersToAdjust.append((oF, nF)) # replace all occurences of folders in path for i in range(len(self.toRename)): for f in foldersToAdjust: oF = addSep(f[0]) # original folder name nF = addSep(f[1]) # new folder name self.toRename[i][0] = self.toRename[i][0].replace(oF,nF) self.toRename[i][1] = self.toRename[i][1].replace(oF,nF) if progressDialog.update(i) is False: error = 'cancelled' break # make sure renaming will be in correct order ! self.toRename.sort(recursiveFolderSort) First problem is adjusting the paths can take a very long time. Second problem is sorting is not always right and files get lost !! Any input welcome. From bearophileHUGS at lycos.com Sat Dec 6 20:31:13 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 6 Dec 2008 17:31:13 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> Message-ID: Erik Max Francis: > your precise proposal has > been brought up countless times on comp.lang.python And something tells me that it will keep coming up many more times in the following years too. Bye, bearophile From gagsl-py2 at yahoo.com.ar Sat Dec 27 03:08:29 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 27 Dec 2008 06:08:29 -0200 Subject: How to display Chinese in a list retrieved from database via python References: <22be506d-91c2-4727-ace7-2e3382b6d214@g3g2000pre.googlegroups.com> <979fdf6d-0500-47ba-87fd-0f0361ca3059@p2g2000prf.googlegroups.com> <19680ed2-c78f-4ab9-8ca0-8ce26fd5b6a7@o4g2000pra.googlegroups.com> Message-ID: En Sat, 27 Dec 2008 03:03:24 -0200, zxo102 escribi?: > On 12?26?, ??3?16?, "Mark Tolonen" > wrote: >> >> I was able to display ?? successfully with this code: >> >> f=open('test.html','wt') >> f.write(''' >> >> test >> \xd6\xd0\xce\xc4''') >> f.close() >> > Mark, > I have exactly copied your code into the htdocs of my Apache > server, > > > > test > \xd6\xd0\xce\xc4 > > but it still shows me \xd6\xd0\xce\xc4. Any ideas? That's not the same thing as Mark T. said. The original was Python code to *write* a test file that you could open in a browser. Things like "\xd6\xd0" are escape sequences interpreted by Python, not meant to literally appear in a file. Like \n -- it means "start a new line", one wants a new line in the output, *not* a backslash and a letter n. "\xd6\xd0" generate *two* bytes, not eight. If the file is interpreted as containing latin-1 characters, you see them as ??. But due to the "charset=gb2312" line, those two bytes together make the ideograph ?. So, write the Python code (from f=open... up to f.close()) in a file and execute it. Then open the generated test.html file. You should see the two ideographs. -- Gabriel Genellina From dotancohen at gmail.com Fri Dec 5 03:12:36 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Fri, 5 Dec 2008 10:12:36 +0200 Subject: ANN: New Book: Programming in Python 3 In-Reply-To: <200812050738.17172.list@qtrac.plus.com> References: <9J6dnaDFKfxgbarUnZ2dnUVZ8jWdnZ2d@posted.plusnet> <880dece00812041256x227af79agf9a22226215f3330@mail.gmail.com> <200812050738.17172.list@qtrac.plus.com> Message-ID: <880dece00812050012p1703df91u405caba7ed5b346f@mail.gmail.com> 2008/12/5 Mark Summerfield : > I don't think the book is due in Europe until the end of January, but > could take longer for elsewhere. (Of course Israel is in Europe > according to the Eurovision Song Contest, so you might get lucky:) > Yes, we are in the unique geographical and political position to be in Europe when it suits us, in Asia when it suits us, and to be in the Middle East when it suits us! Thanks! -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-??-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From tjreedy at udel.edu Mon Dec 8 18:06:28 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Dec 2008 18:06:28 -0500 Subject: tabs and spaces in py3k In-Reply-To: References: <774909e2-b248-4251-bbba-deb309e72714@x38g2000yqj.googlegroups.com> Message-ID: inyeol.lee at gmail.com wrote: >> Do the Py3k docs need correction? > > -tt option in python 2.x is now default in python 3.0. > Apparently it got slipped from any documentation, including what's > new. http://bugs.python.org/issue4603 From mail at microcorp.co.za Wed Dec 3 23:38:46 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 4 Dec 2008 06:38:46 +0200 Subject: Python advocacy ... HELP! References: <5f8c1a52-545e-402e-863a-acdf23d04c78@h20g2000yqn.googlegroups.com> Message-ID: <001f01c955ca$3326b7e0$0d00a8c0@hendrik> "Tim Rowe" wrote: > Try asking "Are we teaching computer science, so that the students > will be able to cope with whatever they meet once they graduate, or > are we teaching computer programming, in a couple of specific > languages, so that the students will be completely unprepared if they > meet anything else?" What is computer science anyway - as opposed to what the electronic engineering guys do - which is the true science - the programming bits, or the modern hardware bits? Or maybe both? Where are both taught? - Hendrik From martin at marcher.name Mon Dec 29 05:14:12 2008 From: martin at marcher.name (Martin) Date: Mon, 29 Dec 2008 11:14:12 +0100 Subject: game engine (as in rules not graphics) In-Reply-To: References: <402f625f-b835-4cb8-bcea-523756c489ca@g39g2000pri.googlegroups.com> Message-ID: <5fa6c12e0812290214v31439a7ava9225eec2c68ae1a@mail.gmail.com> Hi, 2008/12/29 Phil Runciman : > See: Chris Moss, Prolog++: The Power of Object-Oriented and Logic Programming (ISBN 0201565072) > > This book is a pretty handy intro to an OO version Prolog produced by Logic Programming Associates. > From: Aaron Brady [mailto:castironpi at gmail.com] > Sent: Sunday, 28 December 2008 1:22 p.m. > Not my expertise but here are my $0.02. You are looking for ways to represent rules: buying a house is legal in such and such situation, and the formula for calculating its price is something. You want "predicates" such as InJail, OwnedBy, Costs. > > Costs( New York Ave, 200 ) > InJail( player2 ) > OwnedBy( St. Charles Ave, player4 ) > LegalMove( rolldie ) > LegalMove( sellhouse ) I'm not sure I'm looking for prolog, i had an introductory course back at the university but it didn't exactly like it. I'm after some info how such rules would defined in python (specifically python althou logic programming is probably the more appropriate way). I guess I'm missing quite some basics in the design of such concepts, I'll head back to google to find some introductory stuff now :). regards, Martin -- http://soup.alt.delete.co.at http://www.xing.com/profile/Martin_Marcher http://www.linkedin.com/in/martinmarcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From sonynamratha2009 at gmail.com Wed Dec 24 15:35:40 2008 From: sonynamratha2009 at gmail.com (sony) Date: Wed, 24 Dec 2008 12:35:40 -0800 (PST) Subject: advt Message-ID: <60d51d87-a94d-4fae-b33a-8b1400f31066@i20g2000prf.googlegroups.com> http://www.adztel.blogspot.com/ http://adztel.blogspot.com/2008/12/tatoo-niche-ebooks.html http://adztel.blogspot.com/2008/12/cpa-riches.html http://adztel.blogspot.com/2008/12/value-scan-profile.html http://adztel.blogspot.com/2008/12/keyword-elite-software.html http://adztel.blogspot.com/2008/12/over-1600-nano-technology-companies.html http://adztel.blogspot.com/2008/12/internet-marketing-wish-list.html http://adztel.blogspot.com/2008/12/affilorama.html From missive at hotmail.com Wed Dec 31 12:18:35 2008 From: missive at hotmail.com (Lee Harr) Date: Wed, 31 Dec 2008 21:48:35 +0430 Subject: error on windows with commands.getstatusoutput Message-ID: > Anyhow, I've replaced it with this: > > > from subprocess import Popen, PIPE, STDOUT > p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, > stderr=STDOUT, close_fds=True) > output, unused = p.communicate() > status = p.returncode > > > Does that look more windows-friendly? Unfortunately, no. close_fds is also not available on windows (or at least not when trying to capture stderr with stdout like this.) So, now I'm going with ... p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT) I don't really understand what close_fds does. I only put it in because it was in the example code. I have a report that this code works on windows, and it is also working for me on linux. _________________________________________________________________ More than messages?check out the rest of the Windows Live?. http://www.microsoft.com/windows/windowslive/ From deets at nospam.web.de Fri Dec 5 18:25:14 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 06 Dec 2008 00:25:14 +0100 Subject: Can I load a python program at the interactive >>> prompt? In-Reply-To: References: <269e5d69-02b7-409b-ad53-b7702b6ec13a@i24g2000prf.googlegroups.com> Message-ID: <6ptriqF9gfifU1@mid.uni-berlin.de> Tim Golden schrieb: > walterbyrd wrote: >> I am running cygwin on xp. > > .... and I just noticed this vital bit. So not sure > how much of my other post applies. Sorry. Maybe it'll > help anyway. :) Everything. The atrocity that the windows terminal window is isn't mitigated by an out-of-the-box cygwin. Did anybody *ever* need a rectangular marking mode? You could use rxvt. But that's also far from perfect. Diez From mrnull at gmail.com Sun Dec 14 00:47:31 2008 From: mrnull at gmail.com (Henson) Date: Sat, 13 Dec 2008 21:47:31 -0800 (PST) Subject: XMPP xmpppy - User Authorization References: Message-ID: <66b3831b-b26d-4ce9-80b2-e0e8c85ecbc4@k9g2000vbl.googlegroups.com> In my own bot, using the latest xmpppy, I've been printing everything going to the message handler to the screen. I've yet to see a 'subscribe' string. Has this changed? James Mills wrote: > On Wed, Nov 5, 2008 at 11:28 AM, James Mills > wrote: > > Can anyone shed any light on how I might > > be able to react to "User Authorization Requests" > > from other users on an XMPP server/network > > using teh xmlpp [1] library ? > > [SOLVED}: > > I found out from having a peek at jabberbot [1] > that it was as simple as parsing the message. > > Here's a code snippet: > > > def messageHandler(self, cnx, message): > text = message.getBody() > user = message.getFrom() > > if text is not None: > self.env.log.debug("<%s> %s" % (user, text)) > > if " " in text: > command, args = text.split(" ", 1) > else: > command, text = text, "" > > command = command.upper() > > if command == "SUBSCRIBE": > self._client.Roster.Authorize(user) > reply = "Authorized." > > > --JamesMills > > -- > -- > -- "Problems are solved by method" From alan.gauld at btinternet.com Mon Dec 15 10:17:40 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Dec 2008 15:17:40 -0000 Subject: [Tutor] Having Issues with CMD and the 'python' command References: <49465C32.7020200@gmail.com> Message-ID: "bob gailer" wrote > Try this: > > Start->Settings->Control Panel->System->Advanced->Environment > Variables > Highlight PATH under System Variables & Click Edit. > Add ;C:\python26 And notice that Bob said ADD - DO NOT REPLACE the existing setting or you will likely break stuff and its not easy to fix it afterwards unless you have a full backup to hand!! Alan G. From znikeshoes004 at gmail.com Thu Dec 25 03:45:50 2008 From: znikeshoes004 at gmail.com (www.voguetouch.com) Date: Thu, 25 Dec 2008 00:45:50 -0800 (PST) Subject: www.voguetouch.com sell nike shoes, tshirt, ugg boots, handbags and so on Message-ID: <448b3300-6428-4c7f-a5d4-1036c9ffc2b0@g3g2000pre.googlegroups.com> cheap nike shoes: WWW(VOGUETOUCH)COM We are wholesaler of Nike Jordan and Other Shoes in China. We are a professional exporting company in china. We supply many kinds of Shoes, such as Nike Shoes, Jordan 1-23, Air Jordan, AF1, DUNK, Air max series etc. Most of them are in stock and can be supplied surely on time. All these shoes are packed with original-boxes and cards our price $33jordan shoes,$15tshirt,15sunglasess, $13cap,$33jean, $35bag our website: WWW(VOGUETOUCH)COM MSN:voguetouch01 at msn.com From rt8396 at gmail.com Mon Dec 22 15:00:15 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 12:00:15 -0800 (PST) Subject: I always wonder ... References: <18767.54282.188749.522233@montanaro-dyndns-org.local> <097fc1e1-d0fa-469c-af51-0ccf8ed1542f@35g2000pry.googlegroups.com> Message-ID: <35ef0b14-714a-42ef-abc5-63951a0cb007@e18g2000yqo.googlegroups.com> On Dec 22, 1:54?pm, Christian Heimes wrote: > > you are truly an open minded, intelligent Human being. Thanks for > > blessing use with your wisdom here. We need more like you. Every > > thought, action, fact, must always be questioned, that is what makes > > us human! > > *plonk* so i was wrong about you ;) From ajaksu at gmail.com Mon Dec 22 17:41:49 2008 From: ajaksu at gmail.com (ajaksu) Date: Mon, 22 Dec 2008 14:41:49 -0800 (PST) Subject: python3 urlopen(...).read() returns bytes References: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> Message-ID: <5496b34d-7ce4-4281-9f01-aed12dab9fd3@f33g2000vbf.googlegroups.com> On Dec 22, 8:25?pm, Christian Heimes wrote: > It's not possible unless you know the encoding of the bytes. Network io > only returns byte and you must encode it explicitly. [...] > There is no generic and simple way to detect the encoding of a remote > site. Sometimes the encoding is mentioned in the HTTP header, sometimes > it's embedded in the section of the HTML document. That said, a "decode to declared HTTP header encoding" version of urlopen could be useful to give some users the output they want (text from network io) or to make it clear why bytes is the safe way. Daniel From rt8396 at gmail.com Mon Dec 22 19:49:59 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 16:49:59 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <6ra8t0F925rU1@mid.individual.net> <29feda0d-6432-4cb9-8809-e4d4a7798601@e1g2000pra.googlegroups.com> <6raeb8F9s47U2@mid.individual.net> <25b1ece0-712b-4516-af28-88c50d00ab8c@s9g2000prg.googlegroups.com> Message-ID: On Dec 22, 6:18?pm, Aaron Brady wrote: > Us small-minded people have hopes and dreams just like anybody else, > Thurston. Now thats the kind of friendly banter this group could use. Instead of people acting as if their bowel-movements smell like bakery fresh cinnamon rolls! From bearophileHUGS at lycos.com Sun Dec 7 15:37:16 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 7 Dec 2008 12:37:16 -0800 (PST) Subject: Python for kids? References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> Message-ID: <53f406ed-c261-4d86-a8dc-4001d10d05b5@s20g2000yqh.googlegroups.com> On Dec 7, 9:13?pm, "Russ P." wrote: > I have a 12-year-old son who spends too much time playing Xbox live > and watching silly YouTube videos. I would like to try to get him > interested in programming. Lot of people learn to program even before age of 12. But I think it's better for you to help him get interest in problem- solving and some of the other bases of the mathematic, scientific and computational mindset. Once those interests are in place, he will probably go looking by himself for things like programming languages, math and science (of course at that point a gentle guide toward good ideas, good problems to solve, good books to read and good programming languages, helps). Otherwise you risk pushing a person to learn using a tool (programming is interesting by itself, but it's mostly a tool still) before having any use for such tool or desire to learn it. And this may lead to someone with no passion to solve problems and learn. Bye, bearophile From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 22:20:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2008 03:20:21 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <015c47ad$0$20656$c3e8da3@news.astraweb.com> Message-ID: <015c5bc6$0$20656$c3e8da3@news.astraweb.com> On Sat, 20 Dec 2008 01:54:35 +0000, Steven D'Aprano wrote: > There clearly is a need for a more heavyweight formatting solution than > % and string.Template. There are things that can't be done easily with % > alone, and format() will make them much simpler. I have no objection to > the addition of the format() method (although I wonder whether it might > have been better as a function). Except of course there is a format() function. Like len(), str() etc, it just calls the appropriate special method on the argument: format(obj, format_spec) -> obj.__format__(format_spec) -- Steven From guido at python.org Sat Dec 6 15:29:09 2008 From: guido at python.org (Guido van Rossum) Date: Sat, 6 Dec 2008 12:29:09 -0800 Subject: [Python-Dev] "as" keyword woes In-Reply-To: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> Message-ID: On Sat, Dec 6, 2008 at 11:38 AM, Warren DeLano wrote: [...] > There, I assert that 'object.as(class_reference)' is the simplest and > most elegant generalization of this widely-used convention. Indeed, it > is the only obvious concise answer, if you are limited to using methods > for casting. Well, that's too bad, as 'as' is now a reserved word. > Although there are other valid domain-specific uses for "as" as either a > local variable or attribute names (e.g. systematic naming: as, bs, cs), > those aren't nearly as important compared to "as" being available as the > name of a generalized casting method -- one that is now strictly denied > to users of Python 2.6 and 3. If you had brought this up 5-10 years ago when we first introduced 'as' as a semi-keyword (in the import statement) we might have been able to avert this disaster. As it was, nobody ever brought this up AFICR, so I don't think it's *that* obvious. > As someone somewhat knowledgable of how parsers work, I do not > understand why a method/attribute name "object_name.as(...)" must > necessarily conflict with a standalone keyword " as ". It seems to me > that it should be possible to unambiguously separate the two without > ambiguity or undue complication of the parser. That's possible with sufficiently powerful parser technology, but that's not how the Python parser (and most parsers, in my experience) treat reserved words. Reserved words are reserved in all contexts, regardless of whether ambiguity could arise. Otherwise *every* reserved word would have to be allowed right after a '.', and many keywords would have to be allowed as identifiers in other contexts. That way lies PL/1... Furthermore, how would you define the 'as' method? Would you also want to be allowed to write def as(self, target): ... ??? Trust me, it's a slippery slope, and you don't want to start going down there. > So, assuming I now wish to propose a corrective PEP to remedy this > situation for Python 3.1 and beyond, what is the best way to get started > on such a proposal? Don't bother writing a PEP to make 'as' available as an attribute again. It has no chance of being accepted. Instead, think of a different word you could use. -- --Guido van Rossum (home page: http://www.python.org/~guido/) From benjamin.kaplan at case.edu Sat Dec 13 16:23:31 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sat, 13 Dec 2008 16:23:31 -0500 Subject: stable algorithm with complexity O(n) In-Reply-To: <1ff0d642-b560-433c-b793-3a05f5b051b9@g1g2000pra.googlegroups.com> References: <6qidmbFc4qduU1@mid.uni-berlin.de> <1ff0d642-b560-433c-b793-3a05f5b051b9@g1g2000pra.googlegroups.com> Message-ID: 2008/12/13 Aaron Brady > On Dec 13, 1:17 pm, Duncan Booth wrote: > > "Diez B. Roggisch" wrote: > > > > > > > > > David Hl??ik schrieb: > > >> Hi guys, > > > > >> i am really sorry for making offtopic, hope you will not kill me, but > > >> this is for me life important problem which needs to be solved within > > >> next 12 hours.. > > > > >> I have to create stable algorithm for sorting n numbers from interval > > >> [1,n^2] with time complexity O(n) . > > > > >> Can someone please give me a hint. Would be very very thankful! > > > > > Unless I grossly miss out on something in computer science 101, the > > > lower bound for sorting is O(n * log_2 n). Which makes your task > > > impossible, unless there is something to be assumed about the > > > distribution of numbers in your sequence. > > > > > Who has given you that assignment - a professor? Or some friend who's > > > playing tricks on you? > > > > I think you must have fallen asleep during CS101. The lower bound for > > sorting where you make a two way branch at each step is O(n * log_2 n), > but > > if you can choose between k possible orderings in a single comparison you > > can get O(n * log_k n). > > > > To beat n * log_2 n just use a bucket sort: for numbers with a known > > maximum you can sort them digit by digit for O(n log_k n), and if you > don't > > restrict yourself to decimal then k can be as large as you want, so for > the > > problem in question I think you can set k=n and (log_n n)==1 so you get > > O(n) > > Minor detail: with k= n, you have log_n (n^2)= 2, so you get O(2n)= O > (n). Same answer. > > The generic sort theorems also assume you can compare arbitrarily > large numbers in constant time, which isn't true. That is, for any > given machine, there exist numbers that you can't compare on them in > constant time. But with a known upper bound k, you can just use a k- > bit machine. > > So, what's the group policy on helping with homework? rhetorical> The policy is "don't do the homework for them". It's more for people who post "write a O(n) sort algorithm for integers in a range [0, n^2]" with a subject of "URGENT: RESPOND QUICKLY". The OP asked for advice on this problem, not for someone to give him the algorithm. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmurray at bitdance.com Thu Dec 11 12:24:44 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Thu, 11 Dec 2008 12:24:44 -0500 (EST) Subject: newbie question: if var1 == var2: In-Reply-To: <87abb21xzm.fsf@daycos.com> References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> Message-ID: On Thu, 11 Dec 2008 at 10:24, Kirk Strauser wrote: > At 2008-11-29T04:02:11Z, Mel writes: > >> You could try >> >> for item in fname: >> item = item.strip() > > This is one case where I really miss Perl's "chomp" function. It removes a > trailing newline and nothing else, so you don't have to worry about losing > leading or trailing spaces if those are important to you. >>> ' ab c \r\n'.rstrip('\r\n') ' ab c ' >>> ' ab c \n'.rstrip('\r\n') ' ab c ' >>> ' ab c '.rstrip('\r\n') ' ab c ' --RDM From jstroud at mbi.ucla.edu Fri Dec 5 23:36:03 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 05 Dec 2008 20:36:03 -0800 Subject: Guido's new method definition idea In-Reply-To: References: Message-ID: Of course I meant class C: def me.method(arg): me.value = arg James From Scott.Daniels at Acm.Org Sun Dec 14 19:14:14 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 14 Dec 2008 16:14:14 -0800 Subject: Output to file gets lost - don't know where to look ... In-Reply-To: References: <26a47940-c997-4da4-8f05-205b8d3001a8@d42g2000prb.googlegroups.com> Message-ID: uair01 wrote: >> I will try the python program outside of IDLE. > > Yes, running the program from the Linux shell instead of from IDLE > produces all output correctly. > Now I'll have to look for a new simple development environment :-( > I think I'll try SPE that has worked well for me ... Or you could try to distill the problem to a simple case and by so doing, improve IDLE for everyone. I'd start by seeing if changing >> .../idlelib/CallTipWindow.py", line 126, in hidetip from: >> self.label.destroy() to: if self.label is not None: self.label.destroy() and seeing if that quick-fix lets you go farther. --Scott David Daniels Scott.Daniels at Acm.Org From peter.anderson at internode.on.net Mon Dec 1 23:46:28 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Tue, 02 Dec 2008 15:46:28 +1100 Subject: Emacs vs. Eclipse vs. Vim In-Reply-To: <493446DC.7030908@gmail.com> References: <493446DC.7030908@gmail.com> Message-ID: <4934BDA4.4080209@internode.on.net> Stef asked: >/ />/ As a fall-back I also use EditPlus (see />/ http://www.editplus.com/index.html ). Its only for Windows /but PyScripter is also only for windows ;-) >/ and its shareware so you need to pay for it. Its clip library makes it />/ a VERY GOOD text editor. It's a real shame there are NO text editors />/ with such a comprehensive and easy to modify clip library function (I />/ would be really pleased to be proven wrong on this last point :-) ). /What so great about it ? I think you would really need to try it. As I said yesterday, I find the clip library really very useful; its simple to use and easy to create/extend. Here is a short piece of clip library from a HTML clip lib: #T=Bold ^! #T=Italic ^! #T=Underline text ^! #T=Superscript (end note) ^! #T=Code fragment ^! #T=Highligt text - yellow ^! #T=Centre text
    ^!
    Only the text on the line after the "T#" appears in the clip lib side panel. Double click on the text label and EditPlus inserts the clip text into the document being edited. The "^!" is where the cursor sits after the clip insertion. Clips can be inserted "around" existing text. Very neat; if you use Windows its really worth a try. Regards, Peter -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From tangens0-NOSPAM- at -NOSPAM-gmail.com Fri Dec 12 02:24:16 2008 From: tangens0-NOSPAM- at -NOSPAM-gmail.com (Tobias Andersson) Date: Fri, 12 Dec 2008 08:24:16 +0100 Subject: Bidirectional Networking In-Reply-To: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> Message-ID: <6qeht0Fc3541U1@mid.individual.net> Emanuele D'Arrigo skrev: > [...] What if the server > wanted to notify the client of something of interest, i.e. new data > that the client should take into consideration and potentially > process? If the protocol is relatively simple perhaps you can implement something similar to IMAP's "IDLE": http://www.faqs.org/ftp/rfc/rfc2177.txt Basically the client (when having nothing important to do) sends the "idle" command and then listens for messages from the server until "idle" is canceled. But looking into "circuits" as suggested by James seems like a good idea also. HTH /TA From Ron.Barak at lsi.com Thu Dec 25 08:04:36 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Thu, 25 Dec 2008 13:04:36 +0000 Subject: seek() returns unexpected results In-Reply-To: References: Message-ID: <7F0503CD69378F49BE0DC30661C6CCF602494703@enbmail01.lsi.com> Hi, When using seek() with a certain text file, I get strange results. I looked at the text file with a binary editor and verified with 'file', and it's an ASCII English text file. Running the script on other text files gives the expected output. Could you suggest the reason ? In the outputs below, when using generator.py as input for generator.py the 'diff' is a nice progression as expected. ('diff' is the difference between the file pointer location and the number of characters read up to now). However, when using sac.log as input for generator.py the 'diff' is a strange series: 1, 2, 1, 2, 3, 4, 5, 6 Running generator.py on a bigger portion of sac.log produces these 'diff's: 1, 2, 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, 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, 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, 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, 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, 32, 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, 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, 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, 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, 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, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 Thanks, Ron. ________________________________ $ cat -n generator.py 1 #!/usr/bin/env python 2 3 import gzip 4 import sys 5 from Debug import _line as line 6 7 class LogStream(): 8 9 def __init__(self, filename): 10 self.filename = filename 11 self.input_file = self.open_file(filename) 12 13 def open_file(self, in_file): 14 try: 15 f = gzip.GzipFile(in_file, "r") 16 f.readline() 17 except IOError: 18 f = open(in_file, "r") 19 f.readline() 20 f.seek(0) 21 return(f) 22 23 def line_generator(self): 24 while True: 25 line_ = self.input_file.readline() 26 print line()+". line_==|"+line_.strip()+"|" 27 self.total_chars += len(line_) 28 print line()+". line length:",len(line_),"; file pointer:",self.input_file.tell(), 29 print "; total chars:",self.total_chars,"; diff:",self.input_file.tell() - self.total_chars 30 if not line_: 31 break 32 yield line_.strip() 33 34 35 if __name__ == "__main__": 36 37 filename = sys.argv[1] 38 log_stream = LogStream(filename) 39 log_stream.input_file.seek(0) 40 log_stream.total_chars = 0 41 line_generator = log_stream.line_generator() 42 for i in range(8): 43 line_ = line_generator.next() $ python generator.py generator.py 26. line_==|#!/usr/bin/env python| 28. line length: 22 ; file pointer: 23 ; total chars: 22 ; diff: 1 26. line_==|| 28. line length: 1 ; file pointer: 25 ; total chars: 23 ; diff: 2 26. line_==|import gzip| 28. line length: 12 ; file pointer: 38 ; total chars: 35 ; diff: 3 26. line_==|import sys| 28. line length: 11 ; file pointer: 50 ; total chars: 46 ; diff: 4 26. line_==|from Debug import _line as line| 28. line length: 32 ; file pointer: 83 ; total chars: 78 ; diff: 5 26. line_==|| 28. line length: 1 ; file pointer: 85 ; total chars: 79 ; diff: 6 26. line_==|class LogStream():| 28. line length: 19 ; file pointer: 105 ; total chars: 98 ; diff: 7 26. line_==|| 28. line length: 5 ; file pointer: 111 ; total chars: 103 ; diff: 8 $ python generator.py sac.log 26. line_==|Dec 15 15:45:20 iSW-00-090 svm_sac[1714]: AGENT[0]: [tv_expand ] tv_expand:........[Domain 5:DVol1_3CG1-MM-1229347528T0] maxVolCapacityMB:....[5121] tempVolCapacityMB:...[512] fivePercentMB:.......[256] expandedTempVolCap:..[1024]| 28. line length: 246 ; file pointer: 247 ; total chars: 246 ; diff: 1 26. line_==|Dec 15 15:45:20 iSW-00-090 svm_sac[1714]: AGENT[0]: [daemon_send_expand_reque] [Domain 5:DVol1_3CG1-MM-1229347528T0]: Add expand request up to 1024 MB (2097152 sectors)| 28. line length: 170 ; file pointer: 418 ; total chars: 416 ; diff: 2 26. line_==|Dec 15 15:45:20 iSW-00-090 svm_sac[1746]: AGENT[0]: [domain_expand_exec ] [Domain 5:DVol1_3CG1-MM-1229347528T0]: Send expand up to 1024 MB (2097152 sectors): success| 28. line length: 172 ; file pointer: 589 ; total chars: 588 ; diff: 1 26. line_==|Dec 15 15:45:21 iSW-00-090 svm_sac[1744]: AGENT[0]: [domain_poll ] Domain [Domain 5]: SVM reported volume manager setup changed| 28. line length: 141 ; file pointer: 731 ; total chars: 729 ; diff: 2 26. line_==|Dec 15 15:45:21 iSW-00-090 svm_sac[1744]: AGENT[0]: [domain_poll ] Domain [Domain 5]: SVM reported multiview setup changed| 28. line length: 136 ; file pointer: 868 ; total chars: 865 ; diff: 3 26. line_==|Dec 15 15:45:21 iSW-00-090 svm_sac[1744]: AGENT[0]: [domain_is_setup_changed ] Domain [Domain 5]: Setup CHANGED| 28. line length: 113 ; file pointer: 982 ; total chars: 978 ; diff: 4 26. line_==|Dec 15 15:45:21 iSW-00-090 svm_sac[1744]: AGENT[0]: [domain_get_pages ] Domain [Domain 5]: Asked to get setup pages| 28. line length: 124 ; file pointer: 1107 ; total chars: 1102 ; diff: 5 26. line_==|Dec 15 15:45:21 iSW-00-090 svm_sac[1744]: AGENT[0]: [svm_get_pages ] SVM [Domain 5:12345]: got all setup pages| 28. line length: 122 ; file pointer: 1230 ; total chars: 1224 ; diff: 6 $ cat generator.py #!/usr/bin/env python import gzip import sys from Debug import _line as line class LogStream(): def __init__(self, filename): self.filename = filename self.input_file = self.open_file(filename) def open_file(self, in_file): try: f = gzip.GzipFile(in_file, "r") f.readline() except IOError: f = open(in_file, "r") f.readline() f.seek(0) return(f) def line_generator(self): while True: line_ = self.input_file.readline() print line()+". line_==|"+line_.strip()+"|" self.total_chars += len(line_) print line()+". line length:",len(line_),"; file pointer:",self.input_file.tell(), print "; total chars:",self.total_chars,"; diff:",self.input_file.tell() - self.total_chars if not line_: break yield line_.strip() if __name__ == "__main__": filename = sys.argv[1] log_stream = LogStream(filename) log_stream.input_file.seek(0) log_stream.total_chars = 0 line_generator = log_stream.line_generator() for i in range(8): line_ = line_generator.next() -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Fri Dec 5 19:19:31 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sat, 06 Dec 2008 01:19:31 +0100 Subject: Multiple Versions of Python on Windows XP In-Reply-To: References: <4934de22$0$27863$9b622d9e@news.freenet.de> <493592EE.9090005@v.loewis.de> <49378804.2050807@g.nevcal.com> <4937DB4B.7060001@ncf.ca> Message-ID: <4939C513.2090802@v.loewis.de> Glenn Linderman wrote: > I'm unaware of it needing to handle multiple extensions > from the command line or via double clicking in Explorer, so was > exploiting the extra level of indirection to save typing, and make the > command simpler to remember. Python *does* provide multiple useful extensions that you might want to double-click, namely .py and .pyw. It also provides an association for .pyc; whether that is useful or not may be debatable. > Not sure what your reference to an editor is about. This I also wonder about. Apparently, his editor has the capability of running Python scripts, and then his question is how to make the editor use a different Python version (and he assumed that there is the notion of a "default" Python version in Windows, and that the editor would just run the default). I'm still very unsure as to what his editor actually does, but his report of success seems to indicate that it choses the interpreter associated with .py. Regards, Martin From mccredie at gmail.com Mon Dec 8 23:36:17 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 8 Dec 2008 20:36:17 -0800 (PST) Subject: How to initialize a class variable once References: Message-ID: On Dec 8, 8:08?pm, Roy Smith wrote: > I've got a class with a class variable: > > class Foo: > ? ?_map = {} > > How do I make sure this only gets initialized the *first* time the > module containing the class is imported? ?What appears to be happening > as it stands is each time the module gets imported, Foo._map get re- > initialized. Unless you are calling reload() on the module, it will only ever get _loaded_ once. Each additional import will just yield the existing module. Perhaps if you post an example of the behavior that leads you to believe that the class variables are getting reinitialized I can provide more useful help. Matt From dstanek at dstanek.com Thu Dec 25 19:05:47 2008 From: dstanek at dstanek.com (David Stanek) Date: Thu, 25 Dec 2008 19:05:47 -0500 Subject: Exec inside a class method to call other class methods? In-Reply-To: <495415C8.2050205@sympatico.ca> References: <4953CF57.8080905@sympatico.ca> <495415C8.2050205@sympatico.ca> Message-ID: On Thu, Dec 25, 2008 at 6:22 PM, Matthew Dubins wrote: > Each type does contain its own parsing method. It's just that, as it > stands, one method is being used to shunt off the data to the correct > parsing method. > Not really. You have all of the parsing methods in a single class. Is it possible for each data class to have a parse method? class DOB(object): def parse(...): pass There are many pros and cons do this way of doing things. Google polymorphism and possibly duck typing to see some interesting discussions. -- David http://www.traceback.org From cjw at ncf.ca Sun Dec 28 18:26:38 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sun, 28 Dec 2008 18:26:38 -0500 Subject: multiply each element of a list by a number In-Reply-To: References: <4955e7be$0$4066$ba4acef3@news.orange.fr> Message-ID: <49580B2E.8050009@ncf.ca> skip at pobox.com wrote: > Colin> ... perhaps faster than numpy: > ... > > For extremely short lists, but not for much else: > > % for n in 1 10 100 1000 10000 100000 ; do > > echo "len:" $n > > echo -n "numpy: " > > python -m timeit -s 'import numpy ; a = numpy.array(range('$n'))' 'a*3' > > echo -n "list: " > > python -m timeit -s 'a = range('$n')' '[3*x for x in a]' > > done > len: 1 > numpy: 100000 loops, best of 3: 11.7 usec per loop > list: 1000000 loops, best of 3: 0.698 usec per loop > len: 10 > numpy: 100000 loops, best of 3: 11.7 usec per loop > list: 100000 loops, best of 3: 2.94 usec per loop > len: 100 > numpy: 100000 loops, best of 3: 12.1 usec per loop > list: 10000 loops, best of 3: 24.4 usec per loop > len: 1000 > numpy: 100000 loops, best of 3: 15 usec per loop > list: 1000 loops, best of 3: 224 usec per loop > len: 10000 > numpy: 10000 loops, best of 3: 41 usec per loop > list: 100 loops, best of 3: 2.17 msec per loop > len: 100000 > numpy: 1000 loops, best of 3: 301 usec per loop > list: 10 loops, best of 3: 22.2 msec per loop > > This is with Python 2.4.5 on Solaris 10. YMMV. > Skip, Your comment is justified for len= 100 or 1,000 but not for len= 10,000 or 100,000. I wonder about the variability of the number of loops in your data. I have tried to repeat your test with the program below, but it fails to cope with numpy. The results for Python 2.5 are: list: 0.421 0.253 list: 0.427 0.254 list: 0.420 0.250 list: 0.421 0.255 list: 0.415 0.254 list: 0.423 0.254 list: 0.422 0.256 The results for Python 2.6 are: list: 0.388 0.228 list: 0.410 0.225 list: 0.384 0.227 list: 0.389 0.226 list: 0.390 0.227 The script used above for both 2.5 and 2.6: # speedUgh.py To compare array timing ##import numpy import timeit as _t m= 100 # number of repetitions values= (10, 100) numpyRes= [] listRes= [] for n in values: sn= 'numpy.arange(' + str(n) + ')*3' t= _t.Timer(sn) ## r= t.repeat(3, m) ## numpyRes.append(sum(t.repeat(3, m)) * 1000000/(3*m*n)) sl='a= [3*k for k in range(' + str(n) + ')]' t= _t.Timer(stmt= sl) listRes.append( sum(t.repeat(3, m)) * 1000000/(3*m*n)) ##print 'numpy:', len(values)*'%8.3f' % tuple(numpyRes) print ' list:', len(values)*'%8.3f' % tuple(listRes) Colin W. From jcd at sdf.lonestar.org Mon Dec 1 11:03:04 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 01 Dec 2008 11:03:04 -0500 Subject: pydoc enforcement. In-Reply-To: <6ccec696-a8bb-4818-a016-642514677b70@b38g2000prf.googlegroups.com> References: <6ccec696-a8bb-4818-a016-642514677b70@b38g2000prf.googlegroups.com> Message-ID: <1228147384.32081.5.camel@aalcdl07.lib.unc.edu> On Sun, 2008-11-30 at 16:27 -0800, ken.faulkner at gmail.com wrote: > I've been thinking about implementing (although no idea yet *HOW*) the > following features/extension for the python compile stage and would be > interested in any thoughts/comments/flames etc. > > Basically I'm interested adding a check to see if: > 1) pydoc's are written for every function/method. > 2) There are entries for each parameter, defined by some > predetermined syntax. > > My idea is that as much as I love dynamic typing, there are times when > using some modules/API's that have less than stellar documentation. I > was thinking that if it was possible to enable some switch that > basically forced compilation to fail if certain documentation criteria > weren't met. > > Yes, it should be up to developers to provide documentation in the > first place. Or, the client developer might need to read the source > (IF its available)... but having some "forced" documentation might at > least ease the problem a little. > > For example (half borrowing from Javadoc). > > class Foo( object ): > > def bar( self, ui ): > pass > > > Would fail, since the bar method has an "unknown" parameter called > "ui". > What I think could be interesting is that the compiler forces some > documentation such as: > > class Foo( object ): > > def bar( self, ui ): > """ > @Param: ui : blah blah blah. > """ > pass > > > The compiler could check for @Param matching each parameter passed to > the method/function. Sure, a lot of people might just not put a > description in, so we'd be no better off. But at least its getting > them *that* far, maybe it would encourage them to actually fill in > details. > > Now ofcourse, in statically typed language, they might have the > description as "Instance of UIClass" or something like that. For > Python, maybe just a description of "Instance of abstract class UI" or > "List of Dictionaries"... or whatever. Sure, precise class names > mightn't be mentioned (since we mightn't know what is being used > then), but having *some* description would certainly be helpful (I > feel). > > Even if no-one else is interested in this feature, I think it could > help my own development (and would be an interested "first change" > into Python itself). > > Apart from bagging the idea, does anyone have a suggestion on where in > the Python source I would start for implementing such an idea? > > Thanks > > Ken For the reasons already stated, I think it's probably a bad idea to enforce this at compile time. I think it's a great idea to make sure that this information is present in all your code, but unless you want to see useless stubs, the correct time to enforce this is at commit time. Don't accept any improperly documented patches. Syntax is not enough to ensure what you want to ensure. The semantics have to be right as well. Cheers, Cliff From pavlovevidence at gmail.com Wed Dec 24 00:36:16 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 23 Dec 2008 21:36:16 -0800 (PST) Subject: Multi-dimension list References: Message-ID: On Dec 23, 10:29?pm, "Steven Woody" wrote: > Hi, > > In the book Python Essential Reference, Chapter 3, when talking about > extended slicing, it gives an example: ?a = m[0:10, 3:20]. ?But I > don't understand how the 'm' was defined. ?What should it looks like? I suspect what the book is saying is that the Python language will accept and multidimensional indexing and slicing (it's legal syntax), even though there are no types built into Python that use multidimensional slicing. However, some third party libraries do provide types that allow multidimensional indexing and slicing, most notably numpy. So, for instance, if you were install numpy, you could get multidimensional arrays and slice 'em up however you'd like: import numpy a = numpy.array([[1,2,3],[4,5,6],[7,8,9]]) print a[1:3,0:2] Carl Banks From castironpi at gmail.com Tue Dec 23 05:58:26 2008 From: castironpi at gmail.com (Aaron Brady) Date: Tue, 23 Dec 2008 02:58:26 -0800 (PST) Subject: wxPython.button.disabled still catching clicks References: <8cb6da6a-7df4-4cce-a28e-385448a25b26@w39g2000prb.googlegroups.com> Message-ID: <1ff2aad7-29a1-48cd-b3de-29fab443aa3e@u18g2000pro.googlegroups.com> On Dec 23, 4:50?am, mynthon wrote: > Hello! (sorry for my english) > > I have a problem with buttons in wxPython. When button is disabled > (by .Disable() or .Enable(False)) it is grayed out but still receive > clicks. > > Eg. i have button that disable itself, runs long action and enable > itself: > > def onClick(self, evt): > ? ? self.btn.Enable(False) > ? ? for i in range (1000): > ? ? ? ? print i > ? ? self.btn.Enable(True) > > when for loop is running button is greyed out and when i click on it > nothing happens but when loop ends another one is started because > button "remebered" thad i click on it when was diabled. My only idea > is to reposition button outside frame instead of disabling it but this > solution is...not good. > > thanks for any help. Ive searched groups, google and it looks that > only i have this problem :) No, it is very common. During your for loop, the loop is dominating the process completely. Events are just building up in the app's message queue, and don't get handled until after you yield on control. If you need to run a long task, look into threading, the OnIdle method, the 'multiprocessing' module, or pump messages during your long task. From rdcollum at gmail.com Thu Dec 18 11:36:57 2008 From: rdcollum at gmail.com (Roger) Date: Thu, 18 Dec 2008 08:36:57 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <71ede5f0-fd88-4155-9f0d-42d0ad5f57dc@v42g2000yqj.googlegroups.com> Message-ID: >funcid1 = root.bind("<1>", lambda e: test()) >funcid2 = root.bind("<1>", lambda e: test2(), add='+') >root.unbind("<1>", funcid2) Isn't this what I've done in my example code? From mail at microcorp.co.za Tue Dec 16 05:43:24 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 16 Dec 2008 12:43:24 +0200 Subject: alt.possessive.its.has.no.apostrophe References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> <49467CE2.3060401@holdenweb.com> <4946826E.7060001@tim.thechases.com> <989de86c-24cc-4ca6-8e9b-82e8ce853c7b@n33g2000pri.googlegroups.com> Message-ID: <002d01c95f6b$33d05340$0d00a8c0@hendrik> "Aaron Brady" wrote: >There's an 'I' in Python. No! It's supposed to be : There's a T in python. "an" is only used when the next word starts with a vowel, as in: It's been an hour now... All this is because English speakers are genetically incapable of moving their tongues. :-) - Hendrik From kyrie at uh.cu Sun Dec 7 09:23:46 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Sun, 07 Dec 2008 09:23:46 -0500 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: <1228659826.493bdc7284e77@mail.uh.cu> Quoting James Stroud : > First, here is why the ability to throw an error is a feature: > > class Apple(object): > def __init__(self, appleness): > self.appleness = appleness > def __cmp__(self, other): > assert isinstance(other, Apple), 'must compare apples to apples' > return cmp(self.appleness, other.appleness) > > class Orange(object): pass > > Apple(42) == Orange() I beg to disagree. The right answer for the question "Am I equal to this chair right here?" is not "I don't know", nor "I can't compare". The answer is "No, I'm not a chair, thus I'm not equal to this chair right here". If someone comes to my house, looking for me, he will not run away because he sees a chair before he sees me. Your assert doesn't belong inside the methot, it should be up to the caller to decide if the human-chair comparisons make sense or not. I certainly don't want to be type-checking when looking for an object within a mixed-type collection. > This reminds me of complex numbers: would 4 + 4i be equal to sqrt(32)? I assume you meant sqrt(32i). Well, sqrt is a function, and if its result value is defined as 4+4i, then the answer is 'yes', otherwise, the answer should be no. sqrt(4) is *not* -2, and should not be equal to -2. The standard definition of the square root _function_ for real numbers is to take the non-negative real root. I haven't heard of a standard square root _function_ for complex numbers (there is of course, a definition of square root, but it is not a function). So, if by your definition of sqrt, sqrt(32i) returns a number, there is no ambiguity. -2 is not sqrt(4). If you need the answer to be 'True', you may be asking the wrong question. From vkseashoremack at googlemail.com Sat Dec 20 11:56:29 2008 From: vkseashoremack at googlemail.com (vkseashoremack at googlemail.com) Date: Sat, 20 Dec 2008 08:56:29 -0800 (PST) Subject: foot domme - Free Message-ID: <223f4f8a-afba-4d3a-a804-f15183f56bdb@a12g2000pro.googlegroups.com> foot domme . . . *******CLICK HERE******** http://club247.cn/foot-domme ***************************** . . . . . . . . . . . . foot domme From simonharrison.uk at googlemail.com Mon Dec 8 13:02:05 2008 From: simonharrison.uk at googlemail.com (simonh) Date: Mon, 8 Dec 2008 10:02:05 -0800 (PST) Subject: Beginner trying to understand functions. References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> <9df7549a-f28b-4d39-b105-90c099f472f2@z28g2000prd.googlegroups.com> Message-ID: <040a2896-be99-477e-909c-c55c5a0e6665@y1g2000pra.googlegroups.com> Thanks for the many replies. Thanks especially to Pierre. This works perfectly: def getName(): name = input('Please enter your name: ') print('Hello', name) def getAge(): while True: try: age = int(input('Please enter your age: ')) return age except ValueError: print('That was not a valid number. Please try again.') def checkAge(age,min=18,max=31): if age in list(range(min, max)): print('Come on in!') elif age < min: print('Sorry, too young.') elif age >= max: print('Sorry, too old.') getName() a = getAge() checkAge(a) I am running Python 3, sorry for not stating that originally. From grante at visi.com Sun Dec 14 10:37:25 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 14 Dec 2008 09:37:25 -0600 Subject: 1 or 1/0 doesn't raise an exception References: <49446E39.6020807@tim.thechases.com> Message-ID: On 2008-12-14, Daniel Fetchinson wrote: > Let me just point out that unsuspecting people (like me) might rely on > the whole expression to be evaluated and rely on exceptions being > raised if needed. Short circuit evaluation of booleans is very common (and has been for decades), so I don't know why people would expect something else. -- Grant From prologic at shortcircuit.net.au Thu Dec 18 05:15:39 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 18 Dec 2008 20:15:39 +1000 Subject: socket and subprocess problem In-Reply-To: References: <6d3291c3-4e12-4bdd-884a-21f15f38d105@a12g2000pro.googlegroups.com> <73dca20d-3378-4c96-aa30-f0617f111fa0@i18g2000prf.googlegroups.com> Message-ID: On Thu, Dec 18, 2008 at 8:00 PM, Bryan Olson wrote: > I'd swear James copied my response, except his came first. Even the > formatting came out similar. I hadn't seen his response when I wrote mine, > and wouldn't have bothered posing the same thing again. Great minds think alike huh :) You should check out my circuits (1) library! cheers James 1: http://trac.softcircuit.net.au/circuits/ From cmr.Pent at gmail.com Mon Dec 22 03:15:01 2008 From: cmr.Pent at gmail.com (cmr.Pent at gmail.com) Date: Mon, 22 Dec 2008 00:15:01 -0800 (PST) Subject: Calling ImageMagick's convert Message-ID: Hello group! I'm a Python beginner. I'm trying to call ImageMagick's convert program from my code. My OS is Debian testing, and my version of Python is 2.5. I've just stumbled upon a problem: (1) subprocess.call('convert in.png -resize 640x480 out.png', shell = True) works, but none of the following does: (2) subprocess.call('convert in.png -resize 640x480 out.png') (3) subprocess.call(['convert', 'in.png', '-resize 640x480', 'out.png']) (4) subprocess.call(['convert', 'in.png', '-resize 640x480', 'out.png'], shell = True) In these cases, convert program says 'unrecognized option -resize 640x480'. At the same time, subprocess.call(['ls', '-l']) works as expected. I'd like to use variant (3), as it seems the most handy. I don't understand why is shell = True required in case of convert. Is it a bug in Python, in ImageMagick, or am I missing something very basic here? Any hint appreciated. Andrey From Astley.lejasper at gmail.com Wed Dec 3 15:06:28 2008 From: Astley.lejasper at gmail.com (Astley Le Jasper) Date: Wed, 3 Dec 2008 12:06:28 -0800 (PST) Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> <126ba84a-0ea0-4a91-b7d2-89ed650e5d6c@d32g2000yqe.googlegroups.com> Message-ID: <1f4901bb-012c-4e74-8650-c72d48203822@g38g2000yqn.googlegroups.com> On 3 Dec, 19:49, Philip Semanchuk wrote: > On Dec 3, 2008, at 1:33 PM, Astley Le Jasper wrote: > > > > > On 3 Dec, 16:41, Philip Semanchuk wrote: > >> On Dec 3, 2008, at 10:29 AM, Astley Le Jasper wrote: > > >>> I've included a switch to include or exclude theloggingto console. > >>> Whenloggingonly to file, the script runs fine. > > >>> Of course, I still don't understand whyduallogging, and specifically > >>> to the console, causes a problem and if anyone has any comments ? > >>> about > >>> thedualoutputloggingcode above then I'd still be happy to hear > >>> about it. > > >> Trying to write non-ASCII characters perchance? > > > Errmmm ... that's kind of spoookey. I using UTF-8 encoding as I have a > > lot of European language characters. But would that cause a problem > > when running from crontab but not in the terminal? > > > Go on then ... spill the beans. > > Oh, I don't know exactly. It's just what I thought of when you said ? > that the problem occurs when logging to the console but not to files. ? > I don't have a deep Unix background so I can't give you the details on ? > what "the console" means to a cron job. > > In my experience, the environment in which a cron job runs is ? > different from the environment in which some command line scripts run ? > (remember my earlier suggestion about needing to explicitly set the ? > PATH?) and so if the console for a cron job differed from the console ? > that a Python program sees when run in a terminal, that would not ? > surprise me. > > Hope it's a useful suggestion > Philip I tried using the path variables but it didn't help. There again, I didn't really understand what was being passed in the path variables and, rather than just copying and pasting, I wanted to look up further info to get to grips with it. I've got something that works, so now the pressure is off I can spend some time looking it up. [sigh ... my experiences with linux haven't been that good so far. It is, if nothing else, interesting] Thanks ALJ From steve at REMOVE-THIS-cybersource.com.au Sat Dec 20 21:07:19 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Dec 2008 02:07:19 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3ca90cf0-a1f1-4112-9f69-5a505e3c6619@k36g2000pri.googlegroups.com> <59153e28-bf86-4158-96d9-23aa5b9f0205@j35g2000yqh.googlegroups.com> <7889a362-d96e-4f1f-a66b-ef52b9cdb047@q26g2000prq.googlegroups.com> <85f91606-b589-425d-9636-4636c8ccbc4f@r34g2000vbp.googlegroups.com> <6b4176c3-49ce-4e7c-bced-07d8d19bc0f4@s20g2000yqh.googlegroups.com> Message-ID: <015d9c20$0$20656$c3e8da3@news.astraweb.com> On Sat, 20 Dec 2008 16:01:58 -0800, r wrote: > Just to be on record, i am OK with adding a new way to do this as long > as the old C style str format does not ever go away. I don't like 20 > ways to do the same thing, but i really like the compact way of > %formating now. % formatting isn't compact unless you are only doing trivial substitutions. > My complaint is the deprecation of %formating. % formatting hasn't been deprecated. All this Sturm und Drang over nothing. > Maybe > i'll use the new syntax to print a tuple or two, but that is the only > use i have for it ;). Good for you. If your code is that trivial, then you're lucky. > Slowing down Python even more than it is, is suicide. Oh noes, we're all gonna die!!! Just out of curiosity "r", how old are you? 14? 15? You're remarkably mature for a 15 year old. -- Steven From hniksic at xemacs.org Mon Dec 22 02:40:40 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 22 Dec 2008 08:40:40 +0100 Subject: How to represent a sequence of raw bytes References: Message-ID: <87k59sodxj.fsf@mulj.homelinux.net> "Steven Woody" writes: > What's the right type to represent a sequence of raw bytes. In C, > we usually do > > 1. char buf[200] or > 2. char buf[] = {0x11, 0x22, 0x33, ... } > > What's the equivalent representation for above in Python? import array buf = array.array('b', [0x11, 0x22, ...]) It automatically retrieves byte values without having to call ord(), and it allows changing them. It also has a C API for getting to the address of the underlying buffer. From inq1ltd at inqvista.com Thu Dec 11 14:58:16 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Thu, 11 Dec 2008 14:58:16 -0500 Subject: Problems running on HP Intel duo core machine In-Reply-To: References: <200809221443.25765.inq1ltd@inqvista.com> <200812051608.56335.inq1ltd@inqvista.com> Message-ID: <200812111458.16157.inq1ltd@inqvista.com> py help, I produced a program that runs on windows. One client is using an HP machine with an Intel cpu E2200 @ 2.2ghz., and with .99 G ram. The machine is using Win XP Pro 32 bit OS with service pack 2 I ran Dependency Walker and everything is OK. I used py2exe to build the exe file with bundle files:1 and also 3, with the same traceback results. I created a test print module that imports both win32api and win32ui modules and its only job is to print a page of text. The first module that is imported is win32api. line 8 of that module adds to the path the module named 'win32api.pyd'. The import is is completed without error. The next module that is imported is win32ui. line 8 of that module adds to the path a module named 'win32ui.pyd'. The search for the win32ui.pyd module seems to be the cause of the problem. Traceback: ImportError: Dll load failed: The specified module could not be found. Both modules 'win32api.pyd' and win32ui.pyd are in the same directory. Below is a copy of the win32ui.py module. The only difference between this and win32api.py module is the name that is installed when creating the path. def __load(): import imp, os, sys try: dirname = os.path.dirname(__loader__.archive) except NameError: dirname = sys.prefix path = os.path.join(dirname, 'win32ui.pyd') #print "py2exe extension module", __name__, "->", path mod = imp.load_dynamic(__name__, path) ## mod.frozen = 1 __load() del __load The only difference I can find is that this program works fine on every machine that it is tried on except the HP duo core machine, with Intel E2200 cpu. Somehow the path is affected? I've tried all of the suggestions and checked a lot of things but I'm not there yet, Any suggestions would be helpful. jim-on-linux From clp at rebertia.com Mon Dec 29 07:10:46 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 29 Dec 2008 04:10:46 -0800 Subject: Unicode encoding - ignoring errors In-Reply-To: <4958BD31.1010801@logix.net.nz> References: <4958BD31.1010801@logix.net.nz> Message-ID: <47c890dc0812290410u25f9e69oecdcc0e859f9b10e@mail.gmail.com> On Mon, Dec 29, 2008 at 4:06 AM, Michal Ludvig wrote: > Hi, > > in my script I have sys.stdout and sys.stderr redefined to output > unicode strings in the current system encoding: > > encoding = locale.getpreferredencoding() > sys.stdout = codecs.getwriter(encoding)(sys.stdout) > > However on some systems the locale doesn't let all the unicode chars be > displayed and I eventually end up with UnicodeEncodeError exception. > > I know I could explicitly "sanitize" all output with: > > whatever.encode(encoding, "replace") > > but it's quite inconvenient. I'd much prefer to embed this "replace" > operation into the sys.stdout writer. > > Is there any way to set a conversion error handler in codecs.getwriter() > or perhaps chain it with some other filter somehow? I prefer to have > questionmarks in the output instead of experiencing crashes with > UnicodeEncodeErrors ;-) You really should read the fine module docs (namely, http://docs.python.org/library/codecs.html ). codecs.getwriter() returns a StreamWriter subclass (basically). The constructor of said subclass has the signature: StreamWriter(stream[, errors]) You want the 'errors' argument. So all you have to do is add one argument to your stdout reassignment: sys.stdout = codecs.getwriter(encoding)(sys.stdout, 'replace') Yay Python, for making such things easy! Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From nabla.kvadrat at gmail.com Thu Dec 11 00:55:16 2008 From: nabla.kvadrat at gmail.com (Nabla Kvadrat) Date: Thu, 11 Dec 2008 06:55:16 +0100 Subject: multiprocessing+simplehttpserver+windows Message-ID: Hi, can someone please help me with/explain if following problem can be somehow resolved? I have Py2.6.1 win32 and I'm playing around with multiprocessing module. Trying examples here: http://docs.python.org/library/multiprocessing.html#examples. Example with SimpleHTTPServer.HttpServer don't work because of socket.fromfd in multiprocessing.reduction. If number of processes is >1 it ends with traceback ....... pickle.: 'module' object has no attribute 'fromfd'. As I understand socket.fromfd on windows is not implemented (?), so why the example script is care about platform if sys.platform == 'win32': import multiprocessing.reduction and finally, is there some easy (no patching and recompiling python from source) way to get this example to work on win32 platform? Thanks for any help, I'm Python amateur... N. From Scott.Daniels at Acm.Org Wed Dec 24 15:22:07 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 24 Dec 2008 12:22:07 -0800 Subject: Doing set operation on non-hashable objects In-Reply-To: <3a87eb6a-13ff-4aea-8835-3a233cc6cfc4@w39g2000prb.googlegroups.com> References: <3a87eb6a-13ff-4aea-8835-3a233cc6cfc4@w39g2000prb.googlegroups.com> Message-ID: 5lvqbwl02 at sneakemail.com wrote: > ... "db" is a dict, where the values are also dicts. > A function searches through db and returns a list of values, each of > which is a dict as described above. > I need to perform set operations on these lists (intersection and > union) > However the objects themselves are not hashable, and therefore can't > be in a set, because they are dicts. > I'm not sure how large each set will be, but the point is I'm trying > to avoid anything looking like an O(n^2) algorithm, so I can't just > use naive double-looping to check for intersection/union on a pair of > lists. Well, if the lists are ordered, you can do intersection and union in O(n) time. If they are orderable, you can sort each first, giving O(n log n). Note you can do lst.sort(key=id) which will sort on ids. > What I really need is a set of pointers, so at the end of the > operation I have the actual objects pointed to. Can I somehow use the > object IDs as set elements, then recreate a list with the actual > objects they point to? > How do you get the object back from an ID in python? You don't; you remember the mapping in a dictionary and look it up. If there were a way to go from id to object, the whole idea of garbage collection and reference counts would fly out the window, leading to nasty crashes (or you might get to an object that is the re-used id of an older object). --Scott David Daniels Scott.Daniels at Acm.Org From roy at panix.com Sun Dec 14 21:18:03 2008 From: roy at panix.com (Roy Smith) Date: Sun, 14 Dec 2008 21:18:03 -0500 Subject: [OT] stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > All the positive thinking in the world won't help you: > > * make a four-sided triangle; > > * split a magnet into two individual poles; These two are fundamentally different problems. The first is impossible by definition. The definition of triangle is, "a three-sided polygon". Asking for a "four-sided triangle" is akin to asking for "a value of three which is equal to four". The second is only "impossible" because it contradicts our understanding (based on observation) of how the physical universe works. Our understanding could simply be wrong. We've certainly been wrong before, and we will undoubtedly be proven wrong again in the future. When it comes to things like electromagnetic theory, it doesn't take too many steps to get us to the fuzzy edge of quantum physics where we know there are huge questions yet to be answered. From ldo at geek-central.gen.new_zealand Thu Dec 4 17:58:24 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 05 Dec 2008 11:58:24 +1300 Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> <126ba84a-0ea0-4a91-b7d2-89ed650e5d6c@d32g2000yqe.googlegroups.com> <6a302e08-e8be-4d5e-b754-11fc18468cc8@v4g2000yqa.googlegroups.com> Message-ID: In message <6a302e08-e8be-4d5e-b754-11fc18468cc8 at v4g2000yqa.googlegroups.com>, Astley Le Jasper wrote: > On Dec 4, 12:34?am, Lawrence D'Oliveiro central.gen.new_zealand> wrote: >> >> For example, here are some headers from a recent run of the >> maildir backup task I have scheduled twice a day: >> >> Subject: Cron $HOME/bin/backupdir $HOME/.maildir >> X-Cron-Env: >> X-Cron-Env: >> X-Cron-Env: >> X-Cron-Env: >> X-Cron-Env: > > Where do you get the emails from? >From my local mailbox on the machine. From pdorange at pas-de-pub-merci.mac.com Tue Dec 23 12:34:42 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Tue, 23 Dec 2008 18:34:42 +0100 Subject: [Offtopic] Re: I always wonder ... References: <32daf5e9-d143-41c8-b3b0-061d32471263@v42g2000yqj.googlegroups.com> <5a035ec6-b4dd-46ab-9e2a-ded6e3f2c2ff@t3g2000yqa.googlegroups.com> <90f06b27-39da-4f1a-a878-f3972e942d57@s24g2000vbp.googlegroups.com> <62caf93b-0455-4450-9895-8a9d9554f75e@r32g2000vba.googlegroups.com> Message-ID: <1isezkk.51e05y1457jqrN%pdorange@pas-de-pub-merci.mac.com> r wrote: > [...] > Well that shows that even lads with tiny nads can be brave, any of the > other trolls want to expose them selfs? This thread is offtopic, please just keep silent and let it be closed... -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From castironpi at gmail.com Mon Dec 1 21:45:34 2008 From: castironpi at gmail.com (Aaron Brady) Date: Mon, 1 Dec 2008 18:45:34 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <4f31c483-8382-480e-8417-b7eef1b1792d@z1g2000yqn.googlegroups.com> <8c856b01-7f0c-4d5b-a1d2-cfe7dc74389f@w3g2000yqc.googlegroups.com> <1680020c-521c-4498-8e74-92e99c03da6b@w35g2000yqm.googlegroups.com> <0d9d2404-cb3f-4390-b97c-79251db8ac95@k8g2000yqn.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> Message-ID: <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> On Dec 1, 2:29?pm, r wrote: > Rome is Burning! > Pay particular attention to the second paragraph. > > Narcissistic culture > > Main article: The Culture of Narcissism > Historian and social critic Christopher Lasch described this topic in > his book, "The Culture of Narcissism",[3] published in 1979. He > defines a narcissistic culture as one in which every activity and > relationship is defined by the hedonistic need to acquire the symbols > of spiritual wealth, this becoming the only expression of rigid, yet > covert, social hierarchies. It is a culture where liberalism only > exists insofar as it serves a consumer society, and even art, sex and > religion lose their liberating power. > > In such a society of constant competition, there can be no allies, and > little transparency. The threats to acquisitions of social symbols are > so numerous, varied and frequently incomprehensible, that > defensiveness, as well as competitiveness, becomes a way of life. Any > real sense of community is undermined -- or even destroyed -- to be > replaced by virtual equivalents that strive, unsuccessfully, to > synthesize a sense of community. It can mean also many other things. > > Contrary to Lasch, Bernard Stiegler argues in his book, Aimer, > s?aimer, nous aimer: Du 11 septembre au 21 avril, that consumer > capitalism is in fact destructive of what he calls primordial > narcissism, without which it is not possible to extend love to others. > > -food for thought- Off-topic post, defer. I'll take the summary to be true to Lasch's original. He states, "it is a culture where liberalism only exists insofar as it serves a consumer society". But liberalism serves a consumer society to a large, large extent. He states, "...and religion lose their liberating power." But religion has no liberating power. The second sentence in the second paragraph presumably states, "The threats [in such a society]...". If so, it states, In a society of constant competition, competitiveness becomes a way of life; which is trivial. "The threats to acquisitions of social symbols are so numerous, varied and frequently incomprehensible, that defensiveness, as well as competitiveness, becomes a way of life." Is the following also true? That is, the same of goods in general? The threats to acquisitions of goods (presumably durable goods) are so numerous, varied and frequently incomprehensible, that defensiveness, as well as competitiveness, becomes a way of life. If not, then define social symbols as distinct from goods, specifically that the threats to their acquisitions are more numerous, varied, and incomprehensible; or conclude the original is false, or that defensiveness and competitiveness aren't bad. Not to mention, you have to contrive the definitions in order to have defensive( x ) and competitive( x ) both true. Reminds me of Foucault... in the bad way. From castironpi at gmail.com Sat Dec 20 20:55:35 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sat, 20 Dec 2008 17:55:35 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> Message-ID: On Dec 20, 7:38?pm, Steven D'Aprano wrote: > Instead of just whinging, how about making a suggestion to fix it? Go on, > sit down for an hour or ten and try to work out how a BINARY OPERATOR > like % (that means it can only take TWO arguments) can deal with an > arbitrary number of arguments, *without* having any special cases. > > Go on. Take your time. I'll be waiting. Hi, not to take sides, but, there is a possibility. This behavior is currently legal: >>> "%i %%i" % 0 % 1 '0 1' So, just extend it. (Unproduced.) >>> "%i %i" % 0 % 1 '0 1' >>> "%r %i" % (2, 3, 4) % 1 '(2, 3, 4) 1' >>> "%r %i" % (2, 3, 4) '(2, 3, 4) %i' Which is quite clever and way ahead of its (posessive) time. From wx1234 at gmail.com Tue Dec 30 20:46:11 2008 From: wx1234 at gmail.com (dubux) Date: Tue, 30 Dec 2008 17:46:11 -0800 (PST) Subject: TypeError: list indices must be integers Message-ID: <2e5a61c0-fa99-4170-81ca-eb3a10859400@k36g2000pri.googlegroups.com> here is a function i wrote that doesnt work. i wrote to parse a "news" file that is going to work in conjunction with a website via mod_wsgi. my head hurts from looking at it so long. please help! i will further explain in the post. def news(x,y): # usage news(date, number) # x = date/news # y = number news_file = '/home/scam/Desktop/www/info/news' news = open(news_file, 'r') news_list = news.readlines() news.close() if x == 'date': mylist = map(lambda i: news_list[i], filter(lambda i: i%2 == 0, range (len(news_list)))) date = mylist[y] return '
    %s

    ' % (date) if x == 'news': mylist = map(lambda i: news_list[i], filter(lambda i: i%2 == 1, range (len(news_list)))) news = mylist[y] return '%s
    ' % (news) else: return news_list and call it with the follow syntax: news('[date/news]', [any number]) i keep getting "TypeError: list indices must be integers" on the following line "date = mylist[y]" can someone please explain this and give me the proper way to achieve what im trying to do? From stephane_chazelas at yahoo.fr Mon Dec 1 01:36:16 2008 From: stephane_chazelas at yahoo.fr (Stephane CHAZELAS) Date: Mon, 1 Dec 2008 06:36:16 +0000 (UTC) Subject: Python surpasses Perl in popularity? References: <5e87aee0-c7fd-4e9d-befb-0cc01cee64ec@f40g2000pri.googlegroups.com> <49316c95$0$2813$742ec2ed@news.sonic.net> <49322ea2$0$2747$742ec2ed@news.sonic.net> Message-ID: 2008-12-1, 01:10(+01), Sven Mascheck: > In comp.unix.shell Stephane CHAZELAS wrote: > >> The Bourne shell, as can still be found on some systems either in some >> non-standard place (/bin on Solaris, /usr/old/bin on HPUX) or named >> differently [...] > > What do you mean with "non-standard place" here? It's true it was vague and misleading, /bin is not the standard place to look for "sh" as far as the "POSIX" standard is concerned. That doesn't mean that standard commands (POSIX or not) cannot be found in /bin. But /bin/sh has been made a non-standard place for "sh". It's the "legacy" place. Those commands that have not undergone non-backward compatible changes with POSIX can still be found in /bin, the others are to be found in /usr/xpg/bin (for the standard versions). -- St?phane From pruebauno at latinmail.com Mon Dec 15 11:07:50 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Mon, 15 Dec 2008 08:07:50 -0800 (PST) Subject: stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> <015612ac$0$20639$c3e8da3@news.astraweb.com> <52cfb77e-4baf-4fba-8eac-cc6c7ddb5be5@k1g2000prb.googlegroups.com> Message-ID: <8f039dec-1a5e-4b60-9603-81687952fcec@l33g2000pri.googlegroups.com> On Dec 15, 11:05?am, prueba... at latinmail.com wrote: > > Non-comparison sorts are a useful technique, but it's changing the > > problem, and they are only useful in very limited circumstances. There's > > a good reason that most sort routines are based on O(n*log n) comparison > > sorts instead of O(n) bucket sorts or radix sorts. > > This is an assumption that I never quite understood. What most people > want is to have sorted data, they don't care if I used a sorting or > non-sorting comparison to do it. I think it is just that in most cases > n is not very big anyway and comparison sorts make it easier on the > programmer to create arbitrary types that are sortable. I meant they don't care if I use a comparison or non-comparison sort of course. From steve at REMOVE-THIS-cybersource.com.au Tue Dec 9 08:24:32 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Dec 2008 13:24:32 GMT Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> Message-ID: <014e6931$0$20670$c3e8da3@news.astraweb.com> On Tue, 09 Dec 2008 04:39:55 -0800, Paul Boddie wrote: > To be fair to the complainant, before mentioning the GIL, he did > initially get the usual trite fragments of the Zen of Python right back > at him ("simple is better than complex", "special cases aren't special > enough to break the rules"), albeit not the whole thing in its overused, > unabridged form. I think I'd go on a rant if presented with that rather > than the accepted reason for the noted shortcomings of the language: > CPython's parsing technology isn't "sufficiently powerful parser > technology" as GvR himself says [1]. > > Paul > > [1] > http://mail.python.org/pipermail/python-dev/2008-December/084023.html That is not what Guido said. What he actually said was: "That's possible with sufficiently powerful parser technology, but that's not how the Python parser (and most parsers, in my experience) treat reserved words." In other words, with a more powerful parser, it would be POSSIBLE. But that doesn't mean that the only reason Python doesn't do what the OP wants is the lack of such a parser. To give an analogy: with sufficiently powerful automotive technology, we could all have cars capable of accelerating from 0 to 300mph in less than five seconds. (That's faster than the space shuttle accelerates, by the way.) The technology exists: drag racers have it. But the costs (financial and social) would be prohibitive, and so very few people have such cars, and those that do have restrictions on where and when they can use them. What Guido is saying is that even if he agreed with the OP he couldn't add that feature. He's not saying that he agrees with the OP. The Zen gives good reasons for believing that even if Python's parser was sufficiently powerful, he'd still consider the feature undesirable. -- Steven From Scott.Daniels at Acm.Org Mon Dec 8 14:55:30 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 08 Dec 2008 11:55:30 -0800 Subject: Determining whether a variable is less/greater than a range. In-Reply-To: <362ab93b-b804-4ebe-a22f-e422feb301c8@c1g2000yqg.googlegroups.com> References: <362ab93b-b804-4ebe-a22f-e422feb301c8@c1g2000yqg.googlegroups.com> Message-ID: simonharrison.uk at googlemail.com wrote: > Hi. I'm having another go at learning Python so I'll probably be > asking a few basic questions. Here is the first one. I think nobody has pointed out to you that "a < b < c" has the conventional mathematical definition (b is between a and c). So, perhaps: b = 9 c = 21 print 'All inbounds', all(10 <= x <= 21 for x in (b, c)) print 'None inbounds', all(not 10 <= x <= 21 for x in (b, c)) print 'inbounds', [x for x in (b, c) if 10 <= x <= 21] print 'outabounds', [x for x in (b, c) if not 10 <= x <= 21] I do advise working through the tutorial before asking. --Scott David Daniels Scott.Daniels at Acm.Org From harish.shastry at gmail.com Tue Dec 30 23:46:33 2008 From: harish.shastry at gmail.com (Harish Vishwanath) Date: Wed, 31 Dec 2008 10:16:33 +0530 Subject: How to get back a list object from its string representation? Message-ID: <78f8019c0812302046j31fa38aeif33d659ec5f2c84e@mail.gmail.com> Hello, Consider : >>> li = [1,2,3] >>> repr(li) '[1, 2, 3]' Is there a standard way to get back li, from repr(li) ? Regards, Harish -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Tue Dec 23 06:15:06 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 23 Dec 2008 03:15:06 -0800 (PST) Subject: Very basic question References: <21ab1917-f0c9-48fb-baa9-02e5bf229bf5@s9g2000prm.googlegroups.com> <38f6b145-8615-4bcc-88f6-1988f9a7f68f@q30g2000prq.googlegroups.com> Message-ID: <5f2c242e-9876-47dc-8f5d-e2f64675e501@w24g2000prd.googlegroups.com> On Dec 23, 9:49?pm, Sengly wrote: > I can hack it by doing eval('1.0*12/5') but is there any better method? from __future__ import division From cedric.schmeits at gmail.com Tue Dec 9 08:53:06 2008 From: cedric.schmeits at gmail.com (Cedric Schmeits) Date: Tue, 9 Dec 2008 05:53:06 -0800 (PST) Subject: Beginner trying to understand functions. References: <3b2f78c0812080624v3d495478l9c522dcb19f17b0b@mail.gmail.com> <9df7549a-f28b-4d39-b105-90c099f472f2@z28g2000prd.googlegroups.com> <040a2896-be99-477e-909c-c55c5a0e6665@y1g2000pra.googlegroups.com> Message-ID: <4c43037d-4394-4fce-8609-c04b0ed3d4f9@z27g2000prd.googlegroups.com> the following would be nicer: def run(): get_name() a = get_age() check_age(a) again() if __name__ == "__main__": run() In this setup your script will only be run if it's started by itself, but when using a import, the functions from the script can be executed separately. From sjmachin at lexicon.net Fri Dec 19 09:08:15 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 19 Dec 2008 06:08:15 -0800 (PST) Subject: importing csv file into sqlite References: <21067453.post@talk.nabble.com> Message-ID: <5bf2ab8d-be1a-454a-8c88-146694f5087b@q30g2000prq.googlegroups.com> On Dec 18, 5:17?pm, "James Mills" wrote: > > def readCSV(file): > ? if type(file) == str: Stiff cheese if the file path is a unicode object, eh? > ? ? ?fd = open(file, "rU") > ? else: > ? ? ?fd = file > From martinjamesevans at gmail.com Mon Dec 8 03:18:11 2008 From: martinjamesevans at gmail.com (martinjamesevans at gmail.com) Date: Mon, 8 Dec 2008 00:18:11 -0800 (PST) Subject: EBCDIC <--> ASCII References: <091f0404-2be3-4bda-8619-03627bd03fdc@k8g2000yqn.googlegroups.com> <6b861698-8638-443d-a230-3eca7424fcfc@j32g2000yqn.googlegroups.com> Message-ID: On Dec 5, 2:13?pm, Michael Str?der wrote: > martinjamesev... at gmail.com wrote: > > On Dec 4, 4:45 pm, Michael Str?der wrote: > >> martinjamesev... at gmail.com wrote: > >>> I'm having a problem trying to use the codecs package to aid me in > >>> converting some bytes from EBCDIC into ASCII. > >> Which EBCDIC variant? > > >>> sEBCDIC = unicode(sSource, 'cp500', 'ignore') > >> Are you sure CP500 is the EBCDIC variant for the language you want? > > >>http://www.ietf.org/rfc/rfc1345.txtlistsit as: > > >> ? ?&charset IBM500 > >> ? ?&rem source: IBM NLS RM Vol2 SE09-8002-01, March 1990 > >> ? ?&alias CP500 > >> ? ?&alias ebcdic-cp-be > >> ? ?&alias ebcdic-cp-ch > > >>> Obviously I could just knock up a 255 character lookup table and do it > >>> myself, I was just trying to be a little more Pythonic and use that > >>> built in table. > >> It's pythonic to implement a Unicode codec for unknown character tables. > >> I've put these two on my web site: > > >>http://www.stroeder.com/pylib/encodings/ebcdicatde.pyhttp://www.stroe...ebcdicatde) > > > Thanks for the tables, ebcdicatde.py does look more suitable. > > > My problem appears to be that my source is a byte string. In a > > nutshell I need "\x81\x82\x83\xf1\xf2\xf3" to become "abc123" in a > > byte string. > > Python 2.5.2 (r252:60911, Aug ?1 2008, 00:43:38) > ?>>> import ebcdicatde > ?>>> "\x81\x82\x83\xf1\xf2\xf3".decode('ebcdic-at-de').encode('ascii') > 'abc123' > ?>>> > > Ciao, Michael.- Hide quoted text - > > - Show quoted text - Many thanks for all your posts! Just what I needed. From vginer at gmail.com Thu Dec 18 14:21:18 2008 From: vginer at gmail.com (Vicent Giner) Date: Thu, 18 Dec 2008 11:21:18 -0800 (PST) Subject: IDLE cursor color Message-ID: <65c5974c-e5c5-46c1-9673-371a7c9ea047@a12g2000pro.googlegroups.com> I am working with IDLE, version 1.2.2 I've changed the colors theme using the "Options > Configure IDLE..." menu option. I've chosen a black background for all the items, so now my work area is black, and everything is OK, except for the fact that I can't see where the cursor is located, I mean, I don't know in which part of the window I am going to write. The cursor is blinking black, but I don't know how to change it. Please, any suggestion, hint, tip or clue?? Thank you in advance! From lists at cheimes.de Thu Dec 4 17:39:04 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 04 Dec 2008 23:39:04 +0100 Subject: Python 3 read() function In-Reply-To: References: <16651e80812040900j257fe2acjf5d8817811d32da6@mail.gmail.com> Message-ID: Terry Reedy wrote: > Timing of os interaction may depend on os. I verified above on WinXp > with 4 meg Pythonxy.chm file. Eye blink versus 3 secs, duplicated. I > think something is wrong that needs fixing in 3.0.1. > > http://bugs.python.org/issue4533 I've attached a patch to the bug. reading was so slow because the fileio_readall() was increasing the buffer by 8kB in each iteration. The new code doubles the buffer until it reaches 512kB. Starting with 512kB it's increased in 512kB blocks. Python 2.x has the same growth rate. Christian From bignose+hates-spam at benfinney.id.au Wed Dec 3 19:16:49 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 04 Dec 2008 11:16:49 +1100 Subject: "as" keyword woes References: Message-ID: <87oczsvlou.fsf@benfinney.id.au> "Warren DeLano" writes: > Why was it necessary to make "as" a reserved keyword? I can't answer for the Python developers as to why they *did* make it a reserved word. But I can offer what I believe is a good reason why it *should* be a reserved word: Because simple is better than complex, and special cases aren't special enough to break the rules. > And more to the point, why was it necessary to prevent developers > from being able to refer to attributes named "as"? There aren't special rules for which names can be use in which way, and that's a *good* thing. Any name that is valid in one area of Python syntax is valid in all Python syntax. > Why can't the parser distinguish between a standalone " as " keyword > and ".as" used as an object/attribute reference? Because that would require special-casing some names as being forbidden in syntax where other names are allowed. Special cases in language syntax are to be avoided where feasible. -- \ ?Pinky, are you pondering what I'm pondering?? ?I think so, | `\ Brain, but this time *you* put the trousers on the chimp.? | _o__) ?_Pinky and The Brain_ | Ben Finney From castironpi at gmail.com Thu Dec 18 05:52:43 2008 From: castironpi at gmail.com (Aaron Brady) Date: Thu, 18 Dec 2008 02:52:43 -0800 (PST) Subject: OT: Binary tree logarithms properties References: <8f67b6f80812170914m377191f4g81345ffe5d0b7f26@mail.gmail.com> Message-ID: <5d33a275-1554-463c-a125-43221d960753@k36g2000pri.googlegroups.com> On Dec 18, 4:34?am, Mr.SpOOn wrote: > 2008/12/17 Terry Reedy : > > > Nodes only have single number indexes if you arrange them linearly. Then the > > index depends on how you arrange them, whether you start the array indexes > > with 0 or 1, and whether you start the level numbers with 0 or 1. ?Call the > > breadth-first sequence bf. ?Then the 1-based slice for 1-first level k is > > bf[2**(k-1):2**k)]. ?Again, proof by induction. > > Yes, I was referring to the heap numeration. > Anyway, Francesco Guerrieri answered me in a private message and > explained me the formula. > > But actually I was searching for other similar properties. A tree with one node A, can have two children A CD C and D can each have two children A CD EF GH Taking 'x' to be the level number, each level can have 2**x members. Each member is a child of the higher level. You see the pattern, 1, 2, 4... then 8, 16, etc. The total number of nodes at a level is 2**x plus its earlier levels. 2**x + 2**(x-1) + ... + 2**0. = 2**(x+1) - 1. Taking the log2 of both sides, we have: log2 count_of_nodes = log2( 2**(x+1) - 1 ) Better yet: log2 ( count_of_nodes + 1 ) = log2( 2**(x+1) ) log2 ( count_of_nodes + 1 ) = x+1 From mrnull at gmail.com Mon Dec 15 11:49:35 2008 From: mrnull at gmail.com (Henson) Date: Mon, 15 Dec 2008 08:49:35 -0800 (PST) Subject: XMPP xmpppy - User Authorization References: <66b3831b-b26d-4ce9-80b2-e0e8c85ecbc4@k9g2000vbl.googlegroups.com> Message-ID: <14c866e4-8c08-403f-a0d0-eb28031a443f@t39g2000prh.googlegroups.com> On Dec 14, 4:23?am, "James Mills" wrote: > On Sun, Dec 14, 2008 at 3:47 PM, Henson wrote: > > In my own bot, using the latestxmpppy, I've been printing everything > > going to the message handler to the screen. ?I've yet to see a > > 'subscribe' string. ?Has this changed? > > No this hasn't changed. This is the string you need > to check for. It does work :) > > cheers > James > > > > -- > -- "Problems are solved by method" Found it. To me, the 'subscribe' was coming in through the Presence handler, not the Message handler. Thanks for the heads up, - Henson From rdcollum at gmail.com Thu Dec 18 14:11:48 2008 From: rdcollum at gmail.com (Roger) Date: Thu, 18 Dec 2008 11:11:48 -0800 (PST) Subject: Tkinter unbinding References: <8feb6e43-0db6-4ed5-8cc9-8dccab851d43@r40g2000yqj.googlegroups.com> <71ede5f0-fd88-4155-9f0d-42d0ad5f57dc@v42g2000yqj.googlegroups.com> <61f45e65-2404-4cc0-9d81-f848c1ba566f@i18g2000prf.googlegroups.com> Message-ID: <7b8839ab-d00b-40f7-a878-5077dde7b8d4@f40g2000pri.googlegroups.com> On Dec 18, 12:49?pm, r wrote: > Maybe someone will chime in with an answer, sorry i could not help. > ponder this, i must... Regardless, thanks for your help! I truly appreciate it. Roger. From john.rominsky at gmail.com Wed Dec 17 14:52:17 2008 From: john.rominsky at gmail.com (Rominsky) Date: Wed, 17 Dec 2008 11:52:17 -0800 (PST) Subject: getting object instead of string from dir() References: Message-ID: <477b9c2e-a0ab-4b26-b643-4a9369c2aaac@r2g2000vbp.googlegroups.com> On Dec 17, 10:59?am, Christian Heimes wrote: > Rominsky schrieb: > > > I am trying to use dir to generate a list of methods, variables, etc. > > I would like to be able to go through the list and seperate the > > objects by type using the type() command, but the dir command returns > > a list of strings. ?When I ask for the type of an element, the answer > > is always string. ?How do I point at the variables themselves. ?A > > quick example is: > > > a = 5 > > b = 2.0 > > c = 'c' > > > lst = dir() > > > for el in lst: > > ? ? print type(el) > > for name, obj in vars().iteritems(): > ? ? print name, obj > > Christian I do have some understanding of the pythonic methodology of programming, though by far I still don't consider myself an expert. The problem at hand is that I am coming from a matlab world and trying to drag my coworkers with me. I have gotten a lot of them excited about using python for this work, but the biggest gripe everytime is they want their matlab ide. I am trying to experiment with making similar pieces of the ide, in particular I am working on the workspace window which lists all the current variables in the namespace, along with their type, size, value, etc.... I am trying to create a python equivalent. I can get dir to list all the variables names in a list of strings, but I am trying to get more info them. hence the desire to do a type command on them. I like the locals and globals commands, but I am still trying to get more info. I have started using the eval command with the strings, which is working, but I am curious if there is a better or more elegant way of getting the info. The eval example would be something like: a = 5 b = 2.0 c = 'c' lst = dir() for el in lst: print el + '\t' + str(eval('type(%s)'%el)) It works, now I am curious if there is a better way. From stef.mientki at gmail.com Thu Dec 18 14:09:26 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 18 Dec 2008 20:09:26 +0100 Subject: how to dock another application under Linux ? Message-ID: <494A9FE6.6050609@gmail.com> hello, Under windows it's fairly easy to capture an application and dock in to your own wxPython application, something like this: - start the external application from within wxPython - give the caption of the application a special name - find de windows handler of the applications mainform - tell the applications mainform, that some wxpanel is the parent I use this to dock VPython in wxPython. Is there a similar solution for Linux ( and Mac) ? thanks, Stef From sjmachin at lexicon.net Fri Dec 26 17:57:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 26 Dec 2008 14:57:34 -0800 (PST) Subject: strange behavior of math.sqrt() in new 3.0 version References: Message-ID: <0a25e3ad-9c94-4c16-9d6a-b79ceb10da1c@o40g2000prn.googlegroups.com> On Dec 27, 8:52?am, David Lemper wrote: > I'm a newbee trying 3.0 ? Please help with ?math.sqrt() math.sqrt() is not the problem. > At the command line this function works correctly > ? ? ? >>> import math > ? ? ? ? ? ? ? n = input("enter a number > ") > ? ? ? ? ? ? ? s = math.sqrt(n) > ? ? ?An entry of 9 or 9.0 ?will yield 3.0 I can't reproduce this. See below. Are you sure that you weren't using Python 2.x? Start with a fresh Python 3.0, and please copy/paste *exactly* what is on the screen, like I've done: C:\junk>\python30\python Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> n = input("float-> ") float-> 9 >>> type(n) >>> repr(n) "'9'" >>> import math >>> s = math.sqrt(n) Traceback (most recent call last): File "", line 1, in TypeError: a float is required All of the above is exactly as expected. input() returns a string. math.sqrt expects a float. > > Yet the same code in a script gives an error message > ? ? ?Script1 > ? ? ? ? ? ? ? ? ? ?import math > ? ? ? ? ? ? ? ? ? ?n = input("enter a number > ") > ? ? ? ? ? ? ? ? ? ?s = math.sqrt(n) > > ? ? ? ? ? ? ? ?Traceback (most recent call last) : > ? ? ? ? ? ? ? ? ? File "", line 1, in > ? ? ? ? ? ? ? ? ? File "script1.py" line 3 in > ? ? ? ? ? ? ? ? ? ? ?s = math.sqrt(n) > ? ? ? ? ? ? ? ?TypeError : a float is required > ? ? ?Entering 9 or 9.0 gives same error message. Again, as expected. > > ? ?According to the math module the results of all > ? ?functions are floats. ?However it says nothing about > ? ?inputs. > > Strangely the above code runs fine in version 2.5 ?( ? ) > and will handle large integers. Suggestion: either choose ONE of 2.6 and 3.0 to learn Python, or plan to spend a lot of time being confused, or reading "What's new in Python 3.0" -- a relevant snippet of which is: """ PEP 3111: raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use eval(input()). """ HTH, John From terry6394 at gmail.com Tue Dec 2 00:01:01 2008 From: terry6394 at gmail.com (Cyril.Liu) Date: Tue, 2 Dec 2008 13:01:01 +0800 Subject: epydoc: How to add new fields as the building fields? Message-ID: <6d2d06b10812012101v6f63b1d8o53b9040aaadcc719@mail.gmail.com> I can add new field in my docstring with "@newfield*"***** tag. but some tag witch I defined would be used in every source files. I do not want to write " @newfield tag ..." in all my docstring. Is there any way to add a building fields to epydoc? thx. -- About Cyril.Liu ----------------------------------- Cyril ????????????, ??????????????, ??????????????:"????????????????????????" http://blog.liuciyong.cn/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From prologic at shortcircuit.net.au Thu Dec 11 09:51:31 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 12 Dec 2008 00:51:31 +1000 Subject: How can I understan the "for" here? In-Reply-To: <49412744.8040301@gmail.com> References: <49412744.8040301@gmail.com> Message-ID: On Fri, Dec 12, 2008 at 12:44 AM, Kermit Mei wrote: > I can't understand the second sentence because of the "for ... in". > I consider that the syntactics of "for" should be: > > for k,v in params.items(): > ...... > > But there's no a colon here, why it can work? It's called a list comprehension. The "for x in y" construct becomes an expression. Simple example: Build a list of integers divisible by 3: >>> [x for x in xrange(10) if not x % 3] [0, 3, 6, 9] cheers James -- -- -- "Problems are solved by method" From pruebauno at latinmail.com Fri Dec 12 10:03:44 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Fri, 12 Dec 2008 07:03:44 -0800 (PST) Subject: Removing None objects from a sequence References: <01524eee$0$20617$c3e8da3@news.astraweb.com> Message-ID: On Dec 12, 8:08?am, "Filip Gruszczy?ski" wrote: > I am not doing it, because I need it. I can as well use "if not elem > is None", but I just wanted to know, if there is some better way of > doing this. I like to know :-) > > And I can't understand why you are becoming so aggressive because of > this. Just because I asked for that, doesn't mean, that I will put > some obfuscated code into my project. I just wanted to learn something > new - I checked itertools, I googled a bit, now I wanted to ask here > if someone knew some really cool way of this. ?All the other > assumptions weren't really necessary. > > Thanks for those ideas, however. I like the last one a lot :) > > -- > Filip Gruszczy?ski In this case the "cool" way is the straightforward way: either the list versions: [x fox x in seq if x is not None] filter(lambda x: x is not None, seq) or the generator versions: (x for x in seq if x is not None) itertools.ifilter(lambda x: x is not None, seq) From rdmurray at bitdance.com Wed Dec 10 09:00:30 2008 From: rdmurray at bitdance.com (rdmurray at bitdance.com) Date: Wed, 10 Dec 2008 09:00:30 -0500 (EST) Subject: SequenceMatcher bug ? In-Reply-To: <67253331-5b36-4018-b15a-c0b86c5342d3@r37g2000prr.googlegroups.com> References: <67253331-5b36-4018-b15a-c0b86c5342d3@r37g2000prr.googlegroups.com> Message-ID: On Tue, 9 Dec 2008 at 22:15, eliben wrote: > On Dec 10, 4:12?am, rdmur... at bitdance.com wrote: >> On Mon, 8 Dec 2008 at 23:46, eliben wrote: >>> This is about Python 2.5.2 - I don't know if there were fixes to this >>> module in 2.6/3.0 >> >>> I think I ran into a bug with difflib.SequenceMatcherclass. >>> Specifically, its ratio() method. The following: >> >>> SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + [5]).ratio >>> () >> >>> returns 0.0 >> >>> While the same with 500 replaced by 100 returns .99... something >>> Looking at the code ofSequenceMatcherthere's some caching going on >>> when the sequences are longer than 200 elements (and indeed, I can >>> reproduce the bug above 200 but not below). Can anyone confirm that >>> this misbehaves and suggest a workaround ? >> >> Python 2.5.2 (r252:60911, Sep 29 2008, 20:34:04) >> [GCC 4.3.1] on linux2 >> Type "help", "copyright", "credits" or "license" for more information.>>> from difflib importSequenceMatcher >>>>> SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + >>>>> [5]).ratio() >> >> 0.99900299102691925 >> > > Strange. I could reproduce the problem both on ActiveState Python > 2.5.2 for Windows, and in the online Try Python evaluator: > > http://try-python.mired.org/ My system is Gentoo, which installs python from source. Maybe gentoo applies patches that the binary releases don't have. --RDM From wuwei23 at gmail.com Mon Dec 8 23:52:32 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 8 Dec 2008 20:52:32 -0800 (PST) Subject: "as" keyword woes References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <791f2149-1e6e-4eaf-9d6e-510aa0745bc1@i20g2000prf.googlegroups.com> Message-ID: <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> On Dec 9, 5:21?am, Paul Boddie wrote: > What I can say is that it certainly does take balls to see matters > from the other guy's perspective instead of calling someone names for > pointing something out. >From my perspective, it was less the original complaint and more the sudden jump to "CPython is dead! The GIL sucks! Academic eggheads!" that prompted the comparisons to trolling. Especially in this case, where Chris was responding to the follow-up rant rather than the initial complaint. So I think to a certain degree the troll-typing reactions are understandable :) From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 16 04:26:55 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 16 Dec 2008 10:26:55 +0100 Subject: Need help improving number guessing game In-Reply-To: <1f33580b-84f9-4059-a0f0-b6a8d71325af@b38g2000prf.googlegroups.com> References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> <01564c98$0$21844$c3e8da3@news.astraweb.com> <587af7e5-7f11-4e0d-8924-1f81a7db8236@s1g2000prg.googlegroups.com> <4946df78$0$19771$426a74cc@news.free.fr> <1f33580b-84f9-4059-a0f0-b6a8d71325af@b38g2000prf.googlegroups.com> Message-ID: <4947742c$0$25951$426a34cc@news.free.fr> feba a ?crit : >> .strip() returns a copy of the string without leading and ending > whitespaces (inlcuding newlines, tabs etc). > > Ahh. I had removed it because it didn't seem to do anything, but I've > readded it. > > And I understand your dictionary stuff correctly now, I think, and I > worked it in. Currently, I have: > > > import random > > def safeint(prompt="y"): > while True: > x = input(prompt) > try: > x = int(x) > except ValueError: > print("BAD INPUT!") > else: > break > return x > > def safestr(prompt="y"): > while True: > x = input(prompt) > try: > x = str(x) Doesn't input already return a string ? > except ValueError: > print("BAD INPUT!") > else: > break > return x You could as well replace the 'break' statement by 'return x' - since returning will obviously break the loop Now don't you notice kind of a pattern in these two functions ? obviously, the only thing that change is the conversion/validation part. The good news is that Python functions are objects too, so you can pass them as params to another function. The generic version of your above code could be: def safeinput(prompt, convert): while True: x = input(prompt) try: x = convert(x) except ValueError, e: print("Bad input : %s" % e) else: return x then you can use it for int: i = safeinput("Please enter an integer", int) or use more complex conversion/validation: def yesno(s): s = s.strip().lower() if not s in ("y", "n"): raise ValueError("please answer with 'y' or 'n'") # we return a boolean return s == 'y' answer = safeinput("really do this ?", yesno) Last point : if your conversion/validation function needs more arguments than the value to convert - ie : converting to an int and vaidating this int is in a specified range, which require mini and maxi arguments for the range - you can use partial evaluation[1]: from functools import partial def int_in_range(x, mini, maxi): x = int(x) if not mini <= x <= maxi: raise ValueError("%s is not in range (%s, %s)" % (x, mini, maxi)) return x i = safeinput( "Please enter an int between 1 and 99", partial(int_in_range, mini=1, maxi=99) ) [1] given the function f(x, y): return x + y, the partial evaluation partial(f, x=2) is a function fx(y) that when called returns the result of f(2, y). (snip) >> rewrite it once again using objects instead of dicts ? > > I'd need to find out how those work, Mostly as glorified dicts with associated functions. Your game and players dicts are obvious candidates. Whenever you see a dict with a more or less defined "structure" and a set of functions working on this dict, you have in fact a class waiting to be born. > and I have a list of python stuff > to read piling up anyway... That said, I think for something like > that, something that's not a major flaw, I'd prefer to make something > else, and maybe work on this again later on. There is only so much > guessing numbers one person can take. Indeed. That was just a suggestion, and it would have been pretty interesting IMHO as a basis for a "from Q&D procedural scripting to OO application programing" tutorial. From steve at holdenweb.com Mon Dec 15 10:50:58 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 15 Dec 2008 10:50:58 -0500 Subject: alt.possessive.its.has.no.apostrophe In-Reply-To: <87r649g9dg.fsf@benfinney.id.au> References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> Message-ID: <49467CE2.3060401@holdenweb.com> Ben Finney wrote: > James Stroud writes: > >> Ben Finney wrote: >>> James Stroud writes: >>> >>>> Yes. I think it was the British who decided that the apostrophe >>>> rule for "it" would be reversed from normal usage relative to >>>> just about every other noun. > > It also seems an indefensible claim to say that anyone ?decided? it > would be that way, especially ?the British?. > It's our language, dammit! Ours, ours, ours! This decision was actually taken at a meeting of the Society of British pedants on November 23, 1786. This led to a schism between the British and the newly-independent Americans, who responded by taking the "u" out of colour, valour, and aluminium. >>> Remember that ?it? is a pronoun. I see no reversal: >> Ok. Pronouns are reversed. > > Or, more generally: Pronouns, which are different in just about every > other way from other nouns, are different in this way also. Is that > about right? > Just think of them as "nounpros" and you won't go wrong. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From excord80 at gmail.com Tue Dec 9 21:49:05 2008 From: excord80 at gmail.com (excord80 at gmail.com) Date: Tue, 9 Dec 2008 18:49:05 -0800 (PST) Subject: How do I manually uninstall setuptools (installed by egg)? Message-ID: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> On Ubuntu, I accidentally manually installed setuptools http://pypi.python.org/pypi/setuptools/0.6c9 (by running the .egg file as a shell script via sudo), and now realize I should just be using apt to take care of my system Python packages. I also installed one or two packages using its ``easy_install``. Looks like it lives in ``/usr/lib/python2.5/site-packages``. How can I manually remove those packages installed using that ``easy_install``, and then manually remove the setuptools package I installed? From jeremiah.dodds at gmail.com Wed Dec 3 03:28:05 2008 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Wed, 3 Dec 2008 03:28:05 -0500 Subject: noob needs help In-Reply-To: References: <6pg4oqF7rgu0U1@mid.individual.net> Message-ID: <12cbbbfc0812030028v32dd49e9pd752ce97894bb205@mail.gmail.com> On Wed, Dec 3, 2008 at 1:01 AM, Sambo wrote: > Peter Pearson wrote: > > > In slackware one needs "./" before the filename if you executing > files in current dir. > -- > http://mail.python.org/mailman/listinfo/python-list > Umm, only if you're running files marked as executable. If you're running foo.py file by typing "python foo.py", you shouldn't need to type "python ./foo.py" . Besides, wouldn't that be an issue with whatever shell you were using anyhow, and not an issue with slackware? -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.kern at gmail.com Mon Dec 8 15:04:22 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 08 Dec 2008 14:04:22 -0600 Subject: Rich Comparisons Gotcha In-Reply-To: References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> Message-ID: Rhamphoryncus wrote: > On Dec 8, 11:54 am, Robert Kern wrote: >> Rhamphoryncus wrote: >>> On Dec 7, 4:20 pm, Steven D'Aprano >> cybersource.com.au> wrote: >>>> On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: >>>>> Rasmus Fogh wrote: >>>>>> Current behaviour is both inconsistent and counterintuitive, as these >>>>>> examples show. >>>>>>>>> x = float('NaN') >>>>>>>>> x == x >>>>>> False >>>>> Blame IEEE for that one. Rich comparisons have nothing to do with that >>>>> one. >>>> There is nothing to blame them for. This is the correct behaviour. NaNs >>>> should *not* compare equal to themselves, that's mathematically >>>> incoherent. >>> Mathematically, NaNs shouldn't be comparable at all. They should >>> raise an exception when compared. In fact, they should raise an >>> exception when *created*. But that's not what we want. What we want >>> is a dummy value that silently plods through our calculations. For a >>> dummy value it seems a lot more sense to pick an arbitrary yet >>> consistent sort order (I suggest just above -Inf), rather than quietly >>> screwing up the sort. >> Well, there are explicitly two kinds of NaNs: signalling NaNs and quiet NaNs, to >> accommodate both requirements. Additionally, there is significant flexibility in >> trapping the signals. > > Right, but most of that's lower level. By the time it reaches Python > we only care about quiet NaNs. No, signaling NaNs raise the exception that you are asking for. You're right that if you get a Python float object that is a NaN, it is probably going to be quiet, but signaling NaNs can affect Python in the way that you want. >>> Regarding the mythical IEEE 754, although it's extremely rare to find >>> quotations, I have one on just this subject. And it does NOT say "x >>> == NaN gives false". It says it gives *unordered*. It is C and >>> probably most other languages that turn that into false (as they want >>> a dummy value, not an error.) >>> http://groups.google.ca/group/sci.math.num-analysis/browse_thread/thr... >> Table 4 on page 9 of the standard is pretty clear on the subject. When the two >> operands are unordered, the operator == returns False. The standard defines how >> to do comparisons notionally; two operands can be "greater than", "less than", >> "equal" or "unordered". It then goes on to map these notional concepts to >> programming language boolean predicates. > > Ahh, interesting. Still though, does it give an explanation for such > behaviour, or use cases? There must be some situation where blindly > returning false is enough benefit to trump screwing up sorting. Well, the standard was written in the days of Fortran. You didn't really have generic sorting routines. You *could* implement whatever ordering you wanted because you *had* to implement the ordering yourself. You didn't have to use a limited boolean predicate. Basically, the boolean predicates have to return either True or False. Neither one is really satisfactory, but that's the constraint you're under. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From wuwei23 at gmail.com Wed Dec 3 05:11:51 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 3 Dec 2008 02:11:51 -0800 (PST) Subject: Reverse zip() ? References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> <20081203095154.1bb33d4d@usenot.de> Message-ID: <8000d0b0-c9e5-4dbd-a6a0-e35b83277e72@d42g2000prb.googlegroups.com> On Dec 3, 6:51?pm, Andreas Waldenburger wrote: > On Tue, 02 Dec 2008 18:16:13 -0800 Bryan Olson > > zip as its own inverse might be even easier to comprehend if we call > > zip by its more traditional name, "transpose". > > Sounds like a Py4k change to me. Nah, just add the following to your sitecustomize.py: transpose = zip :) From motoom at xs4all.nl Sun Dec 21 21:27:36 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Mon, 22 Dec 2008 03:27:36 +0100 Subject: How to represent a sequence of raw bytes In-Reply-To: References: Message-ID: <200812220327.36180.motoom@xs4all.nl> On Monday 22 December 2008 03:23:03 Steven Woody wrote: > 2. char buf[] = {0x11, 0x22, 0x33, ... } > > What's the equivalent representation for above in Python? >>> buf="\x11\x22\33" >>> for b in buf: print ord(b) ... 17 34 27 >>> Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From Scott.Daniels at Acm.Org Fri Dec 19 15:48:31 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 19 Dec 2008 12:48:31 -0800 Subject: weird dict problem, how can this even happen? In-Reply-To: References: <88idnfej99XAtNXUnZ2dnUVZ_hednZ2d@pdx.net> Message-ID: Joel Hedlund wrote: > Scott David Daniels wrote: >> Perhaps your hash function could be something like: > > I'm not sure I understand what you're suggesting. > > /Joel Sorry, a half-thought out idea based on the fact that you wanted a consistent hash for a varying dictionary. The given dictionary subclass does have a consistent hash, so it should be able to find itself. Of course solving the consistent hash without any more work doesn't succeed in general and, without major changes, it makes for exponential lookups (lookup with all keys elements and drop parts til found). Perhaps separating the key (unchanging) from the to-be-varied part of the entry might work for some data sources, and the singly calculated hash might help. Sorry for a confusing post without much to recommend it. --Scott David Daniels Scott.Daniels at Acm.Org From sumerc at gmail.com Tue Dec 30 03:16:23 2008 From: sumerc at gmail.com (k3xji) Date: Tue, 30 Dec 2008 00:16:23 -0800 (PST) Subject: Read-Write Lock vs primitive Lock() References: <277c1be7-2560-4fd6-9610-0b4398dc3719@x16g2000prn.googlegroups.com> Message-ID: > >> Note that the thread acquires the lock ONCE, repeats several thousand > >> times an assignment to a *local* variable called GLOBAL_VAR (!), finally > >> releases the lock and exits. As every thread does the same, they just ? > >> run > >> one after another, they never have a significant overlap. Ok. Forget about the GLOBAL_VAR. See the below code: import threading import locks import time GLOBAL_VAR = [] #GLOBAL_LOCK = locks.ReadWriteLock() GLOBAL_LOCK = threading.Lock() #GLOBAL_LOCK = mylock() GLOBAL_LOOP_COUNT = 10000000 GLOBAL_READER_COUNT = 100 GLOBAL_WRITER_COUNT = 1 global GLOBAL_LEN class wthread(threading.Thread): def run(self): try: GLOBAL_LOCK.acquireWrite() #GLOBAL_LOCK.acquire_write() #GLOBAL_LOCK.acquire() for i in range(GLOBAL_LOOP_COUNT): pass finally: #GLOBAL_LOCK.release_write() GLOBAL_LOCK.release() class rthread(threading.Thread): def run(self): try: GLOBAL_LOCK.acquireRead() #GLOBAL_LOCK.acquire_read() print 'ENTER:'+str(threading.currentThread()) #GLOBAL_LOCK.acquire() print 'ACQUIRE:'+str(threading.currentThread()) for i in range(GLOBAL_LOOP_COUNT): pass finally: #GLOBAL_LOCK.release_read() GLOBAL_LOCK.release() print 'RELEASE:'+str(threading.currentThread()) # module executed? if __name__ == "__main__": starttime = time.clock() threads = [] for i in range(GLOBAL_READER_COUNT): rt = rthread() threads.append(rt) for i in range(GLOBAL_WRITER_COUNT): wt = wthread() threads.append(wt) for thread in threads: thread.start() for thread in threads: thread.join() print "All operations took " + str(time.clock() - starttime) + " msecs" As GLOBAL_LOOP_COUNT is 10000000, now this is making a bottleneck on the readers. I had assumed that as everythread is given only 100 bytecodes to execute, that it will be enough to have a 10000 value for this number to let other rthread start() and try to acquire the lock. But, Python undocumentedly, does not grab the GIL easily if a Lock is held. This is strange for me. > > If I put the for loop outside, in that case, readers will not overlap > > at all, and you would be amazed by the numbers for that test. They > > indicate primitive lock is faster than read-write lock, as it requires > > the lock, executes only one bytecode operation and releases the lock. > > So, in order to create a bottlenneck on readers, we need to somehow do > > not release the lock immediately. > > Again, what is your specific use case? why do you think readers will see a ? > bottleneck? > > > With that, primitive locks perform 10 times better than Read-Write > > lock. See above. > > So what? You don't like such results? The read-write lock in the recipe ? > you posted is rather complex, and isn't obvious whether it is correct or ? > not, and the author doesn't prove it nor provide a reference. I'd stick to ? > the standard Lock object unless I have specific needs. > Note that threading.Lock objects are implemented in C and don't have ? > significant overhead (other than the wait itself); even threading.RLock ? > objects are a lot slower. So depending on what you really have to do, the ? > overhead of using a class like ReadWriteLock may be worse than using a ? > standard Lock. That may be the point. That is why I am trying to test this. When will ReadWrite() lock permforms better over the primitive lock. By the way, for the reference, the code in the recipe is used in CherryPy and based on the Tanenbaum's book Operating Systems Design. > >> Hmmm, it's a reader but attempts to modify the value? > >> You don't have to protect a read operation on a global variable - so a > >> lock isn't required here. > > > This is just for testing. Suppose that I am actually reading the > > value. I don't understand why a lock is not required? Are you saying > > lock is not necesary beacuse GLOBAL_VALUE is an immutable object, if > > then, suppose it is not. This is just a test. Suppose GLOBAl_VAR is a > > list and we are calling append() on it which is nt an atomic > > operation. > > It doesn't matter whether it is mutable or immutable. Remember that, in ? > Python, a global variable is just a *name* that refers to an object; you ? > either get the old object referred, or the new one. If it is a list and it ? > is being modified "in place", you always get the same list -- its contents ? > may differ from one instant to another so iterating over it isn't safe. > That's why I insist on knowing your use case: you may me doing things more ? > complicated than they should. I understand your point completely, but let's change anything inside the loop. Just assume that we a thread that is supposed to read something, and a thread that is supposed to write. If I create thousands of readers, and if the operation is enormously huge calculation(as Python does not grab GIL easily inside a Lock), then this will create a bottlencek on readers. But, with ReadWrite Lock this problem *SHOULD* be fixed and in my tests I see it is fixed, when I increase the time spent in the loop in huge amounts. > > Each thread in your original code were like this: > > begin thread; wait for lock; execute something locally; release lock; exit ? > thread; > > There was no shared state between threads. Even if you fix them to share ? > some variable, they were a single, sequential, piece of code (the inner ? > loop is irrelevant here). Once a thread gets the lock, it just runs to its ? > end. No one waits more than once for the lock. So all of them run ? > sequentially, in arbitrary order, but just one after the other. They never ? > overlap. You are correct about this. But this is an undocumented thing. I had assumed that Python will release GIL for other threads after 100 bytecodes are executed by default. However, as I stated, when a Lock() is held this is changing. I think this is because to avoid simple MT problems for new programmers. Not sure. I will read threads.c for information. Thanks. From rt8396 at gmail.com Fri Dec 19 11:54:51 2008 From: rt8396 at gmail.com (r) Date: Fri, 19 Dec 2008 08:54:51 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: if 3.0 looks like... print( "{0}={1}".format('this',99)) , WTF... thats retarded and looks like Ruby code. Thats not intuitive thats madness! What happens when you need a conversion to string from an integer, more code?? My faith is slipping. Have the python Gods gone mad??. Please tell me i am wrong. Pythons likeness to C is one of its great powers. I always thought of Python as an intuitive way to write C code. I am sticking with 2x(which i had planned to do anyway) I have heard of nothing significant enough to compel me to make the change yet. And with that example from 3.0, i am really setting my ways now. i may have to support the continuation of 2.x beyond 2.9. Guido! please don't play Russian roulette with Python! I have loved python all the way up through the 2.x line. And i carry a great respect for you and your accomplishments. Python must feel at home to a C programmer. That, i feel, is the professional following for Python. I also feel Python is a gateway to the C language for n00b programmers. Let Ruby have the Perl programmers, we don't need them! Excuse me, I think i am going to cry now :( From vkseashoremack at googlemail.com Sat Dec 20 11:56:19 2008 From: vkseashoremack at googlemail.com (vkseashoremack at googlemail.com) Date: Sat, 20 Dec 2008 08:56:19 -0800 (PST) Subject: hd fisting - Free Message-ID: <01ef30ac-e80f-486e-8c8b-8ec7be6c6e81@g3g2000pre.googlegroups.com> hd fisting . . . *******CLICK HERE******** http://club247.cn/hd-fisting ***************************** . . . . . . . . . . . . hd fisting From tjreedy at udel.edu Wed Dec 3 11:42:09 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 03 Dec 2008 11:42:09 -0500 Subject: porting modules to Python 3.0 In-Reply-To: <49363d0d$0$3653$9b622d9e@news.freenet.de> References: <8f60c779-f1ec-4127-b173-f174c016aa96@a12g2000yqm.googlegroups.com> <4936255D.6000509@v.loewis.de> <49363d0d$0$3653$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: >> In one has both 2.x and 3.0 installed, would it easy to install 'lib.py' >> for both? > > It's currently not possible to install something for 2.x; you have to > specifically install it for every value of x (e.g. 2.5 or 2.6). That is what I meant. > It's the same for 3.0: you have to install it separately. > Doing so is fairly easy. You just run "setup.py install" multiple > times In the right place, with the right option to choose a different Python each time. I eventually found the apparent answers in Installing Python Modules, but only after reading well past 'the above command is everything you need to get out of this manual' ;-(. Hitherto, I have only unzipped library packages directly into the desired site-packages directory. This has been easier and safer than setup.py, but will not automatically run 2to3 over the package. Hence my question. Terry From cesium5500 at yahoo.ca Thu Dec 4 18:35:27 2008 From: cesium5500 at yahoo.ca (Guy Doune) Date: Thu, 04 Dec 2008 18:35:27 -0500 Subject: pretty strange behavior of "strip" Message-ID: <4938693F.6090709@yahoo.ca> Hi everybody, Could it be a bug????? Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> test=['03.html', '06.html', 'questions.html', '04.html', 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] >>> test ['03.html', '06.html', 'questions.html', '04.html', 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] >>> test[4] 'toc.html' >>> test[4].strip('.html') 'oc' Can't figure out what is going on, really. Guy From steve at REMOVE-THIS-cybersource.com.au Mon Dec 15 03:15:54 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Dec 2008 08:15:54 GMT Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> Message-ID: <015609af$0$20639$c3e8da3@news.astraweb.com> On Sun, 14 Dec 2008 20:38:58 -0800, cm_gui wrote: >> By the way... I know of a very slow Python site called YouTube.com. In >> fact, it is so slow that nobody ever uses it. > > hahaha, do you know how much money they are spending on hardware to make > youtube.com fast??? Oooh, I know! ONE MILLION DOLLARS!!!! And still cheaper and easier than re-writing YouTube's infrastructure in another language. -- Steven From psftw1 at gmail.com Mon Dec 15 00:25:07 2008 From: psftw1 at gmail.com (peter s.) Date: Sun, 14 Dec 2008 21:25:07 -0800 (PST) Subject: Building from source -- zlib/binascii problems 2.5.2/2.6.1 References: <71531b64-535f-49d0-a0c6-7704df83b251@f18g2000vbf.googlegroups.com> <49458079.1000304@v.loewis.de> <003b0307-c8df-489b-98e6-cfaa35d050a4@k1g2000prb.googlegroups.com> <494586A6.4060102@v.loewis.de> Message-ID: <564db0cc-6ad7-4d57-87ce-e03e8c9f2271@s16g2000vbp.googlegroups.com> On Dec 14, 5:20?pm, "Martin v. L?wis" wrote: > > So.. it seems as though I need to get it to point to the 64 bit > > version (or compile the zlib that comes with Python source). ?I'm not > > sure how to override that. > > The easiest solution would be to invoke the linker line manually, > and replace -lz with the absolute path to the right library. > > Regards, > Martin Thanks for you help thus far, though I am still stuck. I have tried a number of things with no success. Modifying the actual command that builds the zlibmodule to link to other sources produces different errors, such as "build/lib.linux-x86_64-2.5/zlib.so: undefined symbol: inflateEnd". Will update this thread if I find a solution. From invalid at invalid Mon Dec 22 13:53:12 2008 From: invalid at invalid (Grant Edwards) Date: Mon, 22 Dec 2008 12:53:12 -0600 Subject: I always wonder ... References: <494fd759$0$186$e4fe514c@news.xs4all.nl> Message-ID: On 2008-12-22, Martin P. Hellwig wrote: > skip at pobox.com wrote: >> Is there some online troll game running where the players earn >> points for generating responses to their posts? > > You just got 10 points ;-) We'll have to ask for an instant replay for the judges on that one. If his question was genuine, then it doesn't officially count as a troll. -- Grant Edwards grante Yow! Are we laid back yet? at visi.com From steve at holdenweb.com Sat Dec 20 17:34:16 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 20 Dec 2008 17:34:16 -0500 Subject: Python is slow In-Reply-To: <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <23c8683f-12d1-472e-8d99-4c1a6d5cf29a@o40g2000prn.googlegroups.com> Message-ID: cm_gui wrote: >> Seriously cm_gui, you're a fool. >> Python is not slow. >> >> --JamesMills > > haha, getting hostile? > python fans sure are a nasty crowd. > > Python is SLOW. > Two lies in one posting! > when i have the time, i will elaborate on this. > Save your time, go somewhere else. Nobody here is interested. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From google at mrabarnett.plus.com Wed Dec 24 12:03:58 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 24 Dec 2008 17:03:58 +0000 Subject: How to change a generator ? In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF6024946E6@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF6024946E6@enbmail01.lsi.com> Message-ID: <49526B7E.20904@mrabarnett.plus.com> Barak, Ron wrote: > Hi, > > I have a generator whose aim is to returns consecutive lines from a file > (the listing below is a simplified version). > However, as it is written now, the generator method changes the text > file pointer to end of file after first invocation. > Namely, the file pointer changes from 0 to 6623 on line 24. > It might be that the generator method of self.input_file is reading the file a chunk at a time for efficiency even though it's yielding a line at a time. > Can you suggest how the generator could be changed, so it will allow me > to get the current location in the file after each yield ? > > Thanks, > Ron. > > $ cat -n generator.py # listing without line numbers is below > 1 #!/usr/bin/env python > 2 > 3 import gzip > 4 from Debug import _line as line > 5 > 6 class LogStream(): > 7 > 8 def __init__(self, filename): > 9 self.filename = filename > 10 self.input_file = self.open_file(filename) > 11 > 12 def open_file(self, in_file): > 13 try: > 14 f = gzip.GzipFile(in_file, "r") > 15 f.readline() > 16 except IOError: > 17 f = open(in_file, "r") > 18 f.readline() > 19 f.seek(0) > 20 return(f) > 21 > 22 def line_generator(self): > 23 print line()+". > self.input_file.tell()==",self.input_file.tell() > 24 for line_ in self.input_file: > 25 print line()+". > self.input_file.tell()==",self.input_file.tell() > 26 yield line_.strip() > 27 > 28 > 29 if __name__ == "__main__": > 30 > 31 filename = "sac.log.50lines" > 32 log_stream = LogStream(filename) > 33 log_stream.input_file.seek(0) > 34 line_generator = log_stream.line_generator() > 35 line_ = line_generator.next() > > $ python generator.py > 23. self.input_file.tell()== 0 > 25. self.input_file.tell()== 6623 > > $ wc -c sac.log.50lines > 6623 sac.log.50lines > $ cat generator.py > #!/usr/bin/env python > > import gzip > from Debug import _line as line > > class LogStream(): > > def __init__(self, filename): > self.filename = filename > self.input_file = self.open_file(filename) > > def open_file(self, in_file): > try: > f = gzip.GzipFile(in_file, "r") > f.readline() > except IOError: > f = open(in_file, "r") > f.readline() > f.seek(0) > return(f) > > def line_generator(self): > print line()+". self.input_file.tell()==",self.input_file.tell() > for line_ in self.input_file: > print line()+". self.input_file.tell()==",self.input_file.tell() > yield line_.strip() > > > if __name__ == "__main__": > > filename = "sac.log.50lines" > log_stream = LogStream(filename) > log_stream.input_file.seek(0) > line_generator = log_stream.line_generator() > line_ = line_generator.next() > From jstroud at mbi.ucla.edu Mon Dec 15 01:31:38 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 14 Dec 2008 22:31:38 -0800 Subject: alt.possessive.its.has.no.apostrophe In-Reply-To: <87vdtmf0mu.fsf_-_@benfinney.id.au> References: <87vdtmf0mu.fsf_-_@benfinney.id.au> Message-ID: Ben Finney wrote: > James Stroud writes: > >> Yes. I think it was the British who decided that the apostrophe rule >> for "it" would be reversed from normal usage relative to just about >> every other noun. > > Remember that ?it? is a pronoun. I see no reversal: Ok. Pronouns are reversed. Bob's Its From wuwei23 at gmail.com Thu Dec 11 05:01:45 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 11 Dec 2008 02:01:45 -0800 (PST) Subject: Equivalent of 'wget' for python? References: Message-ID: <8108f5d1-9052-4a5f-a470-7412abe14103@v5g2000prm.googlegroups.com> On Dec 11, 7:36?pm, hrishy wrote: > urllib -->static class > request -->method > urlretrieve--> what is this then ? The easiest way is to check for yourself, using type(). So 'type(urllib)' should give you '' (assuming the same types as 2.5, I don't have an install of 3.0 handy atm). My guess is 'type(urllib.request)' will be the same, and 'type (urllib.request.urlretrieve)' will be ''. 'urllib' is a module, or most likely in this case a package, which is a folder that can be treated as a module. It contains another module, 'request', which has inside the function 'urlretrieve'. Modules & packages are a handy language feature for placing functionality into namespaces. The documentation is worth checking out: http://docs.python.org/3.0/tutorial/modules.html From duncan.booth at invalid.invalid Sun Dec 7 12:17:35 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Dec 2008 17:17:35 GMT Subject: Python idea/proposal to assist in single-archive python applications References: Message-ID: Brian Allen Vanderburg II wrote: > In addition it is needed to be able to open a file just as easily > whether that file is in the archive or not. Assuming that a datafile in > an application may be located relative to the '__file__' attributes, the > following will not work in an archive: Why not use pkgutil.get_data()? Provided you remember to put your zip file on PYTHONPATH you can already run modules directly out of a zipfile (Python 2.5 and later). If your zipfile contains __main__.py then with Python 2.6 or later you can run it directly: just specify the zip filename on the command line. I'm not sure what, if anything, you are asking for that doesn't already exist in Python. From metolone+gmane at gmail.com Fri Dec 5 10:54:01 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Fri, 5 Dec 2008 07:54:01 -0800 Subject: pretty strange behavior of "strip" References: <4938693F.6090709@yahoo.ca> Message-ID: wrote in message news:Pine.LNX.4.64.0812050945320.1160 at kimball.webabinitio.net... > On Thu, 4 Dec 2008 at 20:54, Terry Reedy wrote: [snip] > I have often wished that in 'split' I could specify a _set_ of characters > on which the string would be split, in the same way the default list > of whitespace characters causes a split where any one (or more) of > them appears. But instead the string argument is a multi-character > separator. (Which is sometimes useful and I wouldn't want to lose the > ability to specify a multi-character separator!) >>> import re >>> re.split('[,.]','blah,blah.blah') ['blah', 'blah', 'blah'] -Mark From jarausch at igpm.rwth-aachen.de Tue Dec 9 05:51:55 2008 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Tue, 09 Dec 2008 11:51:55 +0100 Subject: python3.0 - any hope it will get faster? Message-ID: <6q70udFb5dmqU1@mid.dfncis.de> Hi, I was somewhat surprised when I ran pystones with python-2.5.2 and with python-3.0 On my old/slow machine I get python-2.5.2 from test import pystone pystone.pystones() gives (2.73, 18315.018315018315) python-3.0 from test import pystone pystone.pystones() gives (4.2700000000000005, 11709.601873536298) That's a drop of 36% ! I know that processing unicode is inherently slower, but still I was surprised that it's so much slower. Is there any hope Python-3.0 will get faster or is the main potential for optimizations exhausted, already? That's not to start a flame war! I know computers get faster, we human beings don't (me, at least) -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From KDawg44 at gmail.com Tue Dec 16 15:44:18 2008 From: KDawg44 at gmail.com (KDawg44) Date: Tue, 16 Dec 2008 12:44:18 -0800 (PST) Subject: Using Mechanize to Fill Out a Form Message-ID: Hi, I am trying to use the Mechanize module to browse to a site, fill out a form, and login. However, it hangs on the opening of the URL. The URL is https, will this cause the open from mechanize to fail? Thanks. Kevin From todorovic.dejan at gmail.com Thu Dec 4 09:56:57 2008 From: todorovic.dejan at gmail.com (netpork) Date: Thu, 4 Dec 2008 06:56:57 -0800 (PST) Subject: m2crypto loading cert file from memory buffer Message-ID: <585682fe-befa-423f-a5d2-1dda717c5edc@r40g2000yqj.googlegroups.com> started using m2crypto recently, it works pretty well by now, i just have one question: ctx = SSL.Context('sslv3') ctx.load_cert_chain('client.pem') anyone knows a way of loading cert file from memory buffer and not from a file? i just do not want to have my cert file in the directory of my app that anyone can get. From bblais at bryant.edu Thu Dec 11 15:01:37 2008 From: bblais at bryant.edu (Brian Blais) Date: Thu, 11 Dec 2008 15:01:37 -0500 Subject: Mathematica 7 compares to other languages In-Reply-To: <452ba58b-9377-4463-85e2-5ecdaa25a129@t39g2000prh.googlegroups.com> References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <452ba58b-9377-4463-85e2-5ecdaa25a129@t39g2000prh.googlegroups.com> Message-ID: <6E0FEB3A-1131-409D-843C-DD31A4859289@bryant.edu> On Dec 11, 2008, at 13:41 , Xah Lee wrote: > On Dec 10, 2:47 pm, John W Kennedy wrote: >> Xah Lee wrote: >>> In lisp, python, perl, etc, you'll have 10 or so lines. In C or >>> Java, >>> you'll have 50 or hundreds lines. >> >> C: >> >> #include >> #include >> >> void normal(int dim, float* x, float* a) { >> float sum = 0.0f; >> int i; >> float divisor; >> for (i = 0; i < dim; ++i) sum += x[i] * x[i]; >> divisor = sqrt(sum); >> for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; >> >> } > > i don't have experience coding C. The code above doesn't seems to > satisfy the spec. The input should be just a vector, array, list, or > whatever the lang supports. > The output is the same datatype of the same dimension. > This does satisfy it, depending on what you mean by "return". In C it is more common to do in-place assignment of pointers, rather than return values. So in the code above float *x is a list, if you will, of floats float *a is a list also dim is the length of the list it assumes that the outside code has already allocated the space for a and x. Instead of returning "a", it modifies the list in place. (for C purists, I know it's not a list, but that's just a convenient term). Also, for python, I wouldn't choose to code it in one line, when 2 is clearer: def normal(x): square=sqrt(sum([val**2 for val in x])) return [val/square for val in x] or, as others have pointed out, for numerical work I'd just use numpy: from numpy import * def normal(x): return x/sqrt(x.sum()) or something like that. bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at mrabarnett.plus.com Thu Dec 4 18:52:59 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 04 Dec 2008 23:52:59 +0000 Subject: pretty strange behavior of "strip" In-Reply-To: <4938693F.6090709@yahoo.ca> References: <4938693F.6090709@yahoo.ca> Message-ID: <49386D5B.4000602@mrabarnett.plus.com> Guy Doune wrote: > Hi everybody, > > Could it be a bug????? > > Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> test=['03.html', '06.html', 'questions.html', '04.html', > 'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test > ['03.html', '06.html', 'questions.html', '04.html', 'toc.html', > '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test[4] > 'toc.html' > >>> test[4].strip('.html') > 'oc' > > Can't figure out what is going on, really. > It's not a bug. strip() treats its argument as a _set_ of characters and strips any of those characters from both ends of the string. lstrip() strips only the left-hand end and rstrip() strips only the right-hand end. From matt.dubins at sympatico.ca Thu Dec 25 18:22:48 2008 From: matt.dubins at sympatico.ca (Matthew Dubins) Date: Thu, 25 Dec 2008 18:22:48 -0500 Subject: Exec inside a class method to call other class methods? In-Reply-To: References: <4953CF57.8080905@sympatico.ca> Message-ID: <495415C8.2050205@sympatico.ca> Each type does contain its own parsing method. It's just that, as it stands, one method is being used to shunt off the data to the correct parsing method. Matthew Dubins David Stanek wrote: > On Thu, Dec 25, 2008 at 1:22 PM, Matthew Dubins > wrote: > >> Hello all, >> >> I have made a python script to upload contact information from an excel >> worksheet to an online database. One part of the program that really >> tripped me up was when I wanted to call specific class methods that I had >> made to deal with specific types of contact information (Parent's name, >> Child's name, Phone #, etc). My first thought was to make it easy using the >> exec statement. >> The code (a method within a class) looked like this: >> ---------- >> def parse(self, data, data_type) >> exec "self.__parse_%s(data)" % data_type >> ---------- >> The data_type variable contains strings that exactly match the spellings of >> the 2nd word in the titles of the class methods that I wanted to call for >> each data_type inputted into the parse function. For some reason, *it >> didn't work*. Alternately, I found the ugly code shown below to be >> functional. As you can see, for each data_type, I call the corresponding >> class method that I've specified. Please help me to transform my ugly >> functional code into concise functional code. :) >> >> Thanks, >> Matthew >> ---------- >> def parse(self, data, data_type): >> if data_type == 'nocall': >> self.__parse_nocall(data) >> elif data_type == 'DOB': >> self.__parse_DOB(data) >> elif data_type == 'gender': >> self.__parse_gender(data) >> elif data_type == 'Prematurity': >> self.__parse_Prematurity(data) >> elif data_type == 'email': >> self.__parse_email(data) >> elif data_type == 'languages': >> self.__parse_languages(data) >> elif data_type == 'phone': >> self.__parse_phone(data) >> elif data_type == 'cname': >> self.__parse_cname(data) >> elif data_type == 'pname': >> self.__parse_pname(data) >> elif data_type == 'address': >> self.__parse_address(data) >> elif data_type == 'duedate': >> self.__parse_dudedate(data) >> >> > > I would look for a way to reorganize your code so that each type > contains its own parse method. > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From narkewoody at gmail.com Mon Dec 22 19:41:28 2008 From: narkewoody at gmail.com (Steven Woody) Date: Tue, 23 Dec 2008 08:41:28 +0800 Subject: How to represent a sequence of raw bytes In-Reply-To: <44a5f0ac-3021-443f-90f2-5f3bd0116d4b@w1g2000prk.googlegroups.com> References: <200812220327.36180.motoom@xs4all.nl> <015f66d7$0$20615$c3e8da3@news.astraweb.com> <44a5f0ac-3021-443f-90f2-5f3bd0116d4b@w1g2000prk.googlegroups.com> Message-ID: On Tue, Dec 23, 2008 at 5:05 AM, John Machin wrote: > On Dec 23, 1:52 am, "Steven Woody" wrote: >> On Mon, Dec 22, 2008 at 6:44 PM, Steven D'Aprano >> >> wrote: >> > On Mon, 22 Dec 2008 14:56:45 +0800, Steven Woody wrote: >> >> >> The intension is to allocate 200 undefined bytes in memory. >> >> > You *want* undefined bytes? Out of curiosity, what do you intend to do >> > with them? >> >> to receive/send network packets, read raw files, etc. After read >> replies of the thread, I think 'array' or 'struct' maybe what I >> wanted, may a plain list can do, but I am not sure. > > [Rhetorical questions] How do you use "undefined bytes" to receive > network packets?? Do you really want to use "undefined bytes" to > *send* network packets???? > > Suggestion: Stop trying to replicate C in Python; think about what you > are trying to accomplish at a higher level, then how to implement that > in Python. > > Cheers, > John Good suggestion, thanks! From skip at pobox.com Sun Dec 7 12:21:07 2008 From: skip at pobox.com (skip at pobox.com) Date: Sun, 7 Dec 2008 11:21:07 -0600 Subject: Number of Python 3.x packages at the PyPI In-Reply-To: <493b954e$0$4021$9b622d9e@news.freenet.de> References: <9c1ab0f3-6686-4c0f-8a6c-12e20539f354@41g2000yqf.googlegroups.com> <493b954e$0$4021$9b622d9e@news.freenet.de> Message-ID: <18748.1539.499785.595995@montanaro-dyndns-org.local> Martin> http://pypi.python.org/pypi?:action=browse&c=533 Martin> It seems that some package authors only classify with Martin> Programming Language :: Python :: 3 I did a release for lockfile yesterday which supports 3.0. I added the "Programming Language :: Python :: 3.0" tag, but not the more inlusive tag above. I just updated the information to include it so it now appears in the search results. Skip From eric at ericaro.net Wed Dec 3 16:55:42 2008 From: eric at ericaro.net (eric) Date: Wed, 3 Dec 2008 13:55:42 -0800 (PST) Subject: python an sqlite objects References: <6a95727c-8135-451e-bbb7-a21795ace0c6@g38g2000yqd.googlegroups.com> <18742.47391.389709.119341@montanaro-dyndns-org.local> <4936F872.2020207@ghaering.de> Message-ID: <91ab57cb-e513-4894-98ed-b0de90136a0f@v15g2000yqn.googlegroups.com> On Dec 3, 10:21?pm, Gerhard H?ring wrote: > azrael wrote: > > It logical that it would be more efficient and logical to use a object > > oriented database, but in this case I ask because of the portable > > nature of sqlite. > > > so, if I get it right, this should be possible [...] > > Did you try it? Did it work? If so,it was pure luck. Attached is a > script that shows how to do it right. > > -- Gerhard > > ?sqlite_serialize.py > 1KViewDownload Hi, it is also possible to use Google Protobuf ( http://code.google.com/p/protobuf/ ) instead of pickle or json - it's portable to other languages too - you define what's the data you really wan't - it's fast, and compact I've done it on one of my projects ( see the code here http://code.google.com/p/pyshow/source/browse/trunk/src/pyshow/data/msgdb.py ), and using BerkeleyDB instead of sqlite( but that's not the point here) What I like with protobuf is that writing the proto file defines the real data structure, and that's a guaranty over time/processes/coders. I don't recommand using pickle to serialise object in a database. Because, it's easy at the beginning, but later, when you are going to 'upgrade' your objects (adding some new fields for instance, or splitting a field into a new object), you'll get a lot of troubles ( keeping the legacy object to live with the new one, implies renaming all objects ? etc.). That's what protobuf is for. BTW, I'm seeking help to start a new project that would connect protobuf to Database, like the piece of code I've done with berkeleyDB, but at a bigger scale. If anyone is interested. From Scott.Daniels at Acm.Org Thu Dec 18 15:47:46 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 18 Dec 2008 12:47:46 -0800 Subject: Factoring Polynomials In-Reply-To: <5dfe1cf3-530d-4e31-833e-e26db85611be@d36g2000prf.googlegroups.com> References: <5dfe1cf3-530d-4e31-833e-e26db85611be@d36g2000prf.googlegroups.com> Message-ID: eric wrote: > On Dec 18, 8:37 pm, collin.da... at gmail.com wrote: >> ... I dont know how to implement the quadratic equation ... > > with numpy: > from numpy import * > > s=[1,-1] > x = -b+s*sqrt( b**2-4*a*c )/(2*a) Numpy is pretty heavyweight for this. For built in modules you have a few choices: For real results: from math import sqrt For complex results: from cmath import sqrt or you can simply use: (value) ** .5 Then you can do something like: def quadsolve(a, b, c): try: discriminant = sqrt(b**2 - 4 * a * c) except ValueError: return () # No results at all. if discriminant: # two results return ((-b - discriminant) / (2 * a), (-b + discriminant) / (2 * a)) else: # a single result (discriminant is zero) return (-b / (2 * a),) --Scott David Daniels Scott.Daniels at Acm.Org From gneuner2 at comcast.net Fri Dec 12 12:39:26 2008 From: gneuner2 at comcast.net (George Neuner) Date: Fri, 12 Dec 2008 12:39:26 -0500 Subject: Mathematica 7 compares to other languages References: <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <452ba58b-9377-4463-85e2-5ecdaa25a129@t39g2000prh.googlegroups.com> Message-ID: <6375k4pf1mleb6im67nkpec5olqbsom88e@4ax.com> On Thu, 11 Dec 2008 10:41:59 -0800 (PST), Xah Lee wrote: >On Dec 10, 2:47?pm, John W Kennedy wrote: >> Xah Lee wrote: >> > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, >> > you'll have 50 or hundreds lines. >> >> C: >> >> #include >> #include >> >> void normal(int dim, float* x, float* a) { >> ? ? float sum = 0.0f; >> ? ? int i; >> ? ? float divisor; >> ? ? for (i = 0; i < dim; ++i) sum += x[i] * x[i]; >> ? ? divisor = sqrt(sum); >> ? ? for (i = 0; i < dim; ++i) a[i] = x[i]/divisor; >> >> } > >i don't have experience coding C. Then why do you talk about it as if you know something? >The code above doesn't seems to satisfy the spec. It does. >The input should be just a vector, array, list, or >whatever the lang supports. The output is the same >datatype of the same dimension. C's native arrays are stored contiguously. Multidimensional arrays can be accessed as a vector of length (dim1 * dim2 * ... * dimN). This code handles arrays of any dimensionality. The poorly named argument 'dim' specifies the total number of elements in the array. George From tavares at fe.up.pt Tue Dec 23 14:01:29 2008 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Tue, 23 Dec 2008 11:01:29 -0800 (PST) Subject: =?windows-1252?Q?Symposium_=93Visualization_and_Human=2DComputer=94_wit?= =?windows-1252?Q?hin_the_IRF=922009_Conference_=96_Announce_=26_Call_for_Papers?= Message-ID: <72a5d86e-d008-4e74-9cdb-12f4b6650673@g39g2000pri.googlegroups.com> ---------------------------------------------------------------------------------------------------------------------------------------- (Apologies for cross-posting) Symposium on ?Visualization and Human-Computer? 3rd International Conference on Integrity, Reliability & Failure (IRF?2009) Faculty of Engineering, University of Porto, Porto ? PORTUGAL, 20-24 July 2009 http://paginas.fe.up.pt/clme/IRF2009/index.htm (We would appreciate if you could distribute this information by your colleagues and co-workers.) ---------------------------------------------------------------------------------------------------------------------------------------- Dear Colleague, Within the 3rd International Conference on Integrity, Reliability & Failure (IRF?2009), to be held in FEUP, Porto, Portugal, in July 20-24, 2009, we are organizing the Symposium ?Visualization and Human- Computer?. Examples of some topics that will be considered are: Scientific Data Visualization, Spatial Data in Visualization, Data Processing and Analysis, Information Visualization, Visualization Techniques, Large Data Visualization, Image Processing and Analysis, Hardware for Visualization, Human-Computer Interaction, Visual Analytics, Visual Data Mining and Knowledge Discovery, Human Perception, Interface Design, Evaluation and User Studies, Software Development, Grid and High Performance Computing, Applications in Engineering, Biomechanics, Bioinformatics, Bioimaging, Physical, Earth, Space, Environmental and Information Sciences. Due to your research activities in those fields, we would like to invite you to submit your work and participate in the Symposium ?Visualization and Human-Computer?. For instructions and submission, please access to the conference website at: http://paginas.fe.up.pt/clme/IRF2009/index.htm Please note that, when submitting your work you should select the Symposium #7 ?Visualization and Human-Computer?. Important dates: - February 28, 2009: Deadline for abstract submission; - March 21, 2009: Notification of abstract acceptance; - May 10, 2009: Receipt of Full Papers; - July 20-24, 2009: Conference Events. Kind regards, Jo?o Manuel R. S. Tavares (University of Porto, Portugal, tavares at fe.up.pt) Renato Natal Jorge (University of Porto, Portugal, rnatal at fe.up.pt) (Symposium organizers) From gagsl-py2 at yahoo.com.ar Mon Dec 8 02:48:58 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Dec 2008 05:48:58 -0200 Subject: how to get a beep, OS independent ? In-Reply-To: References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> <014c575a$0$20670$c3e8da3@news.astraweb.com> Message-ID: En Sun, 07 Dec 2008 23:34:17 -0200, Joe Strout escribi?: > On Dec 7, 2008, at 4:43 PM, Steven D'Aprano wrote: > >> Of course, if you're volunteering to write such a standard system beep >> for Python, I for one would be grateful. > > I am. But where should I put it? Assuming we don't want to wait for > the (understandably) lengthy and contentious process required to add > something to the Python system libraries, where would be the next best > place for this sort of simple OS abstraction layer? The cookbook? http://www.activestate.com/ASPN/Python/Cookbook/ If you can make it run on several different architectures you could upload a patch as a feature request to http://bugs.python.org/ -- Gabriel Genellina From tom at tommorris.org Mon Dec 8 00:53:22 2008 From: tom at tommorris.org (Tom Morris) Date: 8 Dec 2008 05:53:22 GMT Subject: python book for non technical absolute beginner References: <493a7c6a$0$973$426a34cc@news.free.fr> Message-ID: <6q3r2iFahsj9U1@mid.individual.net> On 2008-12-06, News123 wrote: > One of my 'non technical' friends complained about knowing nothing at > all about programming (though using computers regularly for mails / web > browsing / googling and downloading / cropping photos ) > > He wants to play a little with programming to stimulate parts of his > otehrwise idle brain cells. ;-) Normally it's more the social science / > linguistic parts being exercised, > > I thought python might be a nice language for this > > No my question does anybody know a nice beginners book (or a learning CD > or on line tutorial)? Ideally it shouldn't be too serious and have a lot > of small nice mini-examples > It's not Python, but I am a big fan of Chris Pine's 'Learn to Program' , which is a Ruby tutorial for absolute beginners. It'd certainly be nice if the author were to allow someone to port the tutorial for Python and other languages. It spends a lot of time taking the reader from numbers and letters through conditionals, loops, arrays, iteration and eventually to classes and objects. It really is, in my opinion, one of the best programming tutorials for beginners. -- Tom Morris From anurag.bagaria at gmail.com Mon Dec 22 05:02:08 2008 From: anurag.bagaria at gmail.com (ANURAG BAGARIA) Date: Mon, 22 Dec 2008 11:02:08 +0100 Subject: using subprocess module in Python CGI Message-ID: Hello, I am a Python Newbie and would like to call a short python script via browser using a CGI script, but initially I am trying to call the same python script directly through python command line. The script intends to perform a few command line in a pipe and I have written the script (a short one) as follows. #!/usr/bin/python import cgi, string, os, sys, cgitb, commands, subprocess import posixpath, macpath #file = "x.tar.gz" #comd = "tar -xf %s" % (file) #os.system(comd) #commands.getoutput('tar -xf x.tar.gz | cd demo; cp README ../') comd = [\ "tar -xf x.tar.gz", \ "cd demo", \ "cp README ../", \ ] outFile = os.path.join(os.curdir, "output.log") outptr = file(outFile, "w") errFile = os.path.join(os.curdir, "error.log") errptr = file(errFile, "w") retval = subprocess.call(comd, 0, None, None, outptr, errptr) errptr.close() outptr.close() if not retval == 0: errptr = file(errFile, "r") errData = errptr.read() errptr.close() raise Exception("Error executing command: " + repr(errData)) but after trying to execute this independently, I get the following error which I am unable to interpret : Traceback (most recent call last): File "process.py", line 18, in retval = subprocess.call(comd, 0, None, None, outptr, errptr) File "/usr/lib/python2.5/subprocess.py", line 443, in call return Popen(*popenargs, **kwargs).wait() File "/usr/lib/python2.5/subprocess.py", line 593, in __init__ errread, errwrite) File "/usr/lib/python2.5/subprocess.py", line 1135, in _execute_child raise child_exception Could someone suggest where am I going wrong and if corrected, what is the probability of this script being compatible with being called through the browser. Thanking you people in advance. Regards. -- I just want to LIVE while I'm alive. AB -------------- next part -------------- An HTML attachment was scrubbed... URL: From kylefranki at gmail.com Sun Dec 21 10:10:36 2008 From: kylefranki at gmail.com (kylefranki at gmail.com) Date: Sun, 21 Dec 2008 07:10:36 -0800 (PST) Subject: Big Boobs on Parade Message-ID: <2962e6ab-63e9-4629-8184-0be0ac2a3b25@k1g2000prb.googlegroups.com> http://sosed.smutwebsites.com/ Big Boobs on Parade rulez the world of Big Boobs! This site offers a categorized selection of the most unique Free Big Boobs Movies ever filmed. Our team of hard working slaves picks each and every one of these fine babes warranting the finest big boobs videos for our fellow surfers From tmohr at s.netic.de Sun Dec 14 15:16:34 2008 From: tmohr at s.netic.de (Torsten Mohr) Date: Sun, 14 Dec 2008 21:16:34 +0100 Subject: package structure? Message-ID: Hi, in a package i'd like to have a structure like this: Files end with ".py", others are directories: mod __init__.py # sets __all__ = ['smod1'] smod1.py # contains AClass() smod1 __init__.py # sets __all__ = ['abc', 'def'] abc.py def.py So i can now do: import mod.smod1.abc import mod.smod1 But functions/classes in smod1.py are not found: a = mod.smod1.AClass() I know this is somehow ambiguous, but i wonder how else i can make "mod" have subpackages and modules. I wonder how i can make AClass() known in that package. Thanks for any hints, Torsten. From tavares at fe.up.pt Mon Dec 8 12:57:08 2008 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Mon, 8 Dec 2008 09:57:08 -0800 (PST) Subject: =?windows-1252?Q?Symposium_=93Computational_Methods_in_Image_Analysis?= =?windows-1252?Q?=94_within_the_USNCCM_X_Congress_=96_Announce_=26_Call_for_Pap?= =?windows-1252?Q?ers?= Message-ID: <573919c2-f37f-4e2f-8a83-182e327a4f3f@u18g2000pro.googlegroups.com> ------------------------------------------------------------------------------------------------------------------------------- (Apologies for cross-posting) Symposium on ?Computational methods in image analysis? 10th US National Congress on Computational Mechanics (USNCCM X) Columbus, Ohio, USA, July 16-19, 2009 http://usnccm-10.eng.ohio-state.edu/ We would appreciate if you could distribute this information by your colleagues and co-workers. ------------------------------------------------------------------------------------------------------------------------------- Dear Colleague, Within the 10th US National Congress on Computational Mechanics (USNCCM X), to be held in Ohio, USA, in July 16-19, 2009, we are organizing the Symposium ?Computational methods in image analysis?. Examples of some topics that will be considered in the symposium ?Computational methods in image analysis? are: Image Analysis, Objects Modeling, Image Segmentation, Matching, Shape Reconstruction, Motion and Deformation Analysis, Objects Description and Registration, Medical imaging, Software Development for Image Analysis and Grid and High Performance Computing in Image Analysis. Due to your research activities in those fields, we would like to invite you to submit your work and participate in the Symposium ?Computational methods in image analysis?. For instructions and submission, please access to the conference website at: http://usnccm-10.eng.ohio-state.edu/abstractsub.html Please note that, when submitting your work you should select the Symposium ?2.18.4 Computational methods in image analysis?. Important dates: - January 31, 2009: Deadline for abstract submission; - March 1, 2009: Deadline and notification of abstract acceptance; - July 16-19, 2009: Congress Events. Kind regards, Jo?o Manuel R. S. Tavares (University of Porto, Portugal, tavares at fe.up.pt) Renato Natal Jorge (University of Porto, Portugal, rnatal at fe.up.pt) Yongjie Zhang (Carnegie Mellon University, USA, jessicaz at andrew.cmu.edu) Dinggang Shen (UNC-CH School of Medicine, USA, dgshen at med.unc.edu) (Symposium organizers) From rt8396 at gmail.com Tue Dec 16 18:08:32 2008 From: rt8396 at gmail.com (r) Date: Tue, 16 Dec 2008 15:08:32 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <355f1cfe-6abb-4d2c-8bf4-3aa62e713c1f@w34g2000yqm.googlegroups.com> Message-ID: <705998e7-404f-4f4b-a2d6-566660e3e31a@o4g2000pra.googlegroups.com> What about all the crap you had to go through just to get output? Python wins PS. cm_gui try this piece of code >>> print 'hello world'.replace('world', 'idiot') From bdesth.quelquechose at free.quelquepart.fr Thu Dec 4 15:45:46 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 Dec 2008 21:45:46 +0100 Subject: Pythonic design patterns In-Reply-To: References: Message-ID: <49384f33$0$8475$426a74cc@news.free.fr> Slaunger a ?crit : > Thank you all for sharing your views, links and suggestions on my > question. I see where this is getting, and I have extracted the > following points: > > 1. Many classic design patterns, especially the creational ones > (Factory, etc.) aren't really that useful in Python as the built-in > features in the language and the new style objects has ways of doing > these things far more natural than statically types languages. Well... I'd formulate it another way: many classic design patterns are either builtins or simply obvious in Python, so they are barely identifiable as such - at least if you fail to decouple the *design* pattern from it's canonical implementation(s). Remember that design != implementation !-) > 2. Don't be religious about the design pattern and applying them too > frantically. They may look cool, but there is a great danger for over- > engineering and subsequent lower code readability, debuggability, and > maintainability. Indeed. And when you use one, try to implement it the pythonic way... (snip) From castironpi at gmail.com Sun Dec 21 10:57:12 2008 From: castironpi at gmail.com (Aaron Brady) Date: Sun, 21 Dec 2008 07:57:12 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: <45efda40-d5d8-4af3-902f-6e4a9596af49@t39g2000prh.googlegroups.com> On Dec 21, 8:50?am, Steve Holden wrote: > r wrote: snip > > This all really comes down to the new python users. Yea, i said it. > > Not rabid fanboys like Steven and myself.(i can't speak for walter but > > i think he would agree) Are we going to make sure joe-blow python > > newbie likes the language. And doesn't get turned off and run over to > > ruby or whoever. Like it or not, without newusers python is doomed to > > the same fate as all the other "great" languages who had their 15 mins > > of fame. > > > We must proactively seek out the wants of these new users and make > > sure python stays alive. But we also must not sell are pythonic souls > > ? ? ? ? ? ? ? ? ? ? ? ? ?that's "our" (possessive), r, not "are" (verb) > > > in the process. > > > It would be nice to get a vote together and see what does the average > > pythoneer want? What do they like, What do they dislike. What is the > > state of the Python Union? Does anybody know, Does anybody care? I > > think python is slipping away from it's dominate foothold on the > > world. Google's use of python may be the only thing holding this house > > of cards together. Ruby's "hype" is defiantly growing and unless we > > strive for greatness, python may fail. I think ruby may have their act > > together a little better than us right now. And since Ruby is such a > > hodge-podge of different languages, the __init__ hold is there for > > many. > > > what does joe-python want??? > > Don't make the mistake of assuming there is a "Joe Python" whose needs > neatly encapsulate the sum of all Python users' needs. There's plenty of > evidence from this group that different people like, want or need > different things from Python, and attempting to measure user > requirements by democratic means is not likely to produce much useful > information. > > There is no such thing as "the average Python programmer": an average > can only be measured for one-dimensional values on some sort of linear > continuum. Python users live in a multi-dimensional space where the > concept of an average has little meaning and less use. You've confused dimensions with modes. There is such thing as the center of a bivariate distribution--- it is merely the most common of the individual variables, the top of a 3-D hill, or the center of mass. However, an average only makes sense for unimodal distributions. If the distribution is bi-modal, there's no "average" in the neat sense. Dollars earned per hour spent writing in Python is a good candidate. There are two modes in that distribution. One at 0, the other in the tens or hundreds. And the global average is less common than either mode individually. So in this case, we have one "Joe Py" for every mode: Joe Free Py, and Joe Paid Py. (You might actually get multi- modal on that one-- Joe Salary Py, Joe Wage Py, Joe Stipend Py, Joe Free Py, but $0.01/hr. is less common than 0, and less common than $50.) You might also argue that the standard deviation is so high as to make any one data point unrepresentative of many others. But if you have variables in two dimensions, they're independent by definition (or there exists a basis set that is). From prologic at shortcircuit.net.au Mon Dec 15 21:58:27 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 16 Dec 2008 12:58:27 +1000 Subject: ethical questions about global variables In-Reply-To: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> References: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> Message-ID: On Tue, Dec 16, 2008 at 12:45 PM, Giampaolo Rodola' wrote: > Hi, > in a module of mine (ftpserver.py) I'd want to add a (boolean) global > variable named "use_gmt_times" to decide whether the server has to > return times in GMT or localtime but I'm not sure if it is a good idea > because of the "ethical" doubts I'm gonna write below. > > In first place I've never liked global variables too much and always > preferred per-class-instance variables instead. > The problem in my case is that I have to use such variable in two > separated classes: FTPHandler and VirtualFileSystem. Also, I want that > for no reason one class uses times in GMT and the other one local > times. > > Another doubt is the naming convention. PEP-8 states that global > variables should use the lower_case_naming_convention but I've seen a > lot of library module using the UPPER_CASE_NAMING_CONVENTION. What am > I supposed to do about it? > > Thanks in advance for any comment. You could always use a "config" object that you pass around to your other objects. --JamesMills From prologic at shortcircuit.net.au Fri Dec 19 06:50:04 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Dec 2008 21:50:04 +1000 Subject: importing csv file into sqlite In-Reply-To: References: <21067453.post@talk.nabble.com> Message-ID: On Fri, Dec 19, 2008 at 8:32 PM, Peter Otten <__peter__ at web.de> wrote: > James Mills wrote: > >> values = ",".join(["\"%s\"" % x for x in line]) >> print "INSERT INTO %s %s VALUES (%s);" % (table, fields, values) > > http://xkcd.com/327/ It's a tool! Not one meant to be used publicly from untrusted users. Free feel to submit a patch as is the Open Source spirit! --JamesMills From Lie.1296 at gmail.com Sat Dec 6 15:18:14 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 6 Dec 2008 12:18:14 -0800 (PST) Subject: "as" keyword woes References: Message-ID: <66ea8282-05cc-4d24-8447-1df5e0e6b9f6@40g2000prx.googlegroups.com> On Dec 7, 2:38?am, "Warren DeLano" wrote: > > Date: Fri, 05 Dec 2008 22:22:38 -0800 > > From: Dennis Lee Bieber > > Subject: Re: "as" keyword woes > > To: python-l... at python.org > > Message-ID: > > > ? ?I'm still in the dark as to what type of data could > > even inspire the > > use of "as" as an object name... A collection of "a" objects? In which > > case, what are the "a"s? > > Please let me clarify. ?It is not "as" as a standalone object that we > specifically miss in 2.6/3, but rather, the ability to use ".as" used as > a method or attribute name. ? > > In other words we have lost the ability to refer to "as" as the > generalized OOP-compliant/syntax-independent method name for casting: > > new_object = old_object.as(class_hint) > > # For example: > > float_obj = int_obj.as("float") > > # or > > float_obj = int_obj.as(float_class) > > # as opposed to something like > > float_obj = int_obj.asFloat() > > # which requires a separate method for each cast, or > > float_obj = (float)int_obj ? > > # which required syntax-dependent casting [language-based rather than > object-based]. > > Of course, use of explicit casting syntax "(float)" is fine if you're > restricting yourself to Python and other languages which support > casting, but that solution is unavailable inside of a pure OOP > message-passing paradigm where object.method(argument) invocations are > all you have to work with. ? > > Please note that use of object.asClassname(...) is a ubiqitous > convention for casting objects to specific classes (seen in ObjectiveC, > Java, SmallTalk, etc.). ? > > There, I assert that 'object.as(class_reference)' is the simplest and > most elegant generalization of this widely-used convention. ?Indeed, it > is the only obvious concise answer, if you are limited to using methods > for casting. > > Although there are other valid domain-specific uses for "as" as either a > local variable or attribute names (e.g. systematic naming: as, bs, cs), > those aren't nearly as important compared to "as" being available as the > name of a generalized casting method -- one that is now strictly denied > to users of Python 2.6 and 3. > > As someone somewhat knowledgable of how parsers work, I do not > understand why a method/attribute name "object_name.as(...)" must > necessarily conflict with a standalone keyword " as ". ?It seems to me > that it should be possible to unambiguously separate the two without > ambiguity or undue complication of the parser. > > So, assuming I now wish to propose a corrective PEP to remedy this > situation for Python 3.1 and beyond, what is the best way to get started > on such a proposal? ? > > Cheers, > Warren And let things like: filelike.print('lpt') # python 2.6 zipper.with('7z') failure.try(alternative) executecodeobject.if(True) onfailure.break() ? From lists at cheimes.de Thu Dec 11 06:58:10 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 11 Dec 2008 12:58:10 +0100 Subject: broken ncurses on python 3.0 In-Reply-To: References: Message-ID: icarus wrote: > OS: win32, python 3.0 > > I've been trying to run some curses demos and I get this: > > C:\Python\Lib\curses>python textpad.py > Traceback (most recent call last): > File "textpad.py", line 3, in > import curses > File "C:\Python\lib\curses\__init__.py", line 15, in > from _curses import * > ImportError: No module named _curses > > The C:\Python\include does not have the curses.h header. > Reinstalling from the x86 msi binary doesn't do it. > > Any ideas on how to get this working? maybe it's just the w32 version > that missed ncurses The Windows binaries doesn't have and never had an ncurses extension. The extension doesn't suport ncurses on Windows at all - in all versions of Python. Christian From anthony.tolle at gmail.com Mon Dec 8 11:59:53 2008 From: anthony.tolle at gmail.com (anthony.tolle at gmail.com) Date: Mon, 8 Dec 2008 08:59:53 -0800 (PST) Subject: Guido's new method definition idea References: <014a071a$0$20670$c3e8da3@news.astraweb.com> <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> Message-ID: <79139d04-bd26-4f36-b8c9-19554e7d4e95@e18g2000yqo.googlegroups.com> On Dec 6, 4:15?pm, Carl Banks wrote: > On Dec 6, 12:47?am, "Patrick Mullen" wrote: > > > Could I do something like this: > > > def a.add(b): return a+b > > > Outside of a class? ?Of course then that makes you think you could do > > 5.add(6) or something craaaazy like that. ?(I mean, you can do > > (5).__add__(6) but that's something else entirely) > > I'd be inclined to think that this defines an instancemethod on an > existing object a. ?In other word, I'd read the following two lines as > more or less equivalent. > > def a.add(b): return a+b > > a.add = lambda b: a+b > > Just as the following are equivalent: > > def foo(): return bar > > foo = lambda: bar > > I had been -0 on this, but now I think I'm -1. This brings up another question, what would one use when referencing method names inside the class definition?: class C: def self.method(arg): self.value = arg def self.othermethod(arg): self.value = arg # do this? funcs = (self.method, self.othermethod) # or this? funcs = (method, othermethod) On another related note, I would be interested in seeing this syntax adopted for a different purpose... Normally, if I'm defining a nested function that needs to be stored as an object attribute, I have to use a dummy name, like the following: class C: def createfunc(self, arg): def _dummy(arg): return arg + 1 self.func = _dummy It would be nice to be able to do the following instead: class C: def createfunc(self): def self.func(arg): return arg + 1 Or, after the class definition is done, to extend it dynamically: def C.method(self, arg): self.value = arg ...which would be the equivalent of the following: def method(self, arg): self.value = arg C.method = method Since functions are first-class objects, it seems perfectly reasonable to me. From shaomumu at gmail.com Tue Dec 16 13:38:45 2008 From: shaomumu at gmail.com (Lin) Date: Tue, 16 Dec 2008 10:38:45 -0800 (PST) Subject: sys.maxint in Python 2.6.1 (amd64) on Windows XP x64 Message-ID: <4bddf65a-bb9f-406c-a544-8c38b27547a7@b38g2000prf.googlegroups.com> Hi, I installed the amd64 version of Python 2.6.1 on my Windows XP x64 system. I was expecting sys.maxint to be 9223372036854775807 (or 2 ^63 -1), but instead I got 2147483647 (i.e., 2^31-1) just like what I got from a 32-bit version of Python. Is this by design or does it indicate a bug or an installation problem? Thank you very much! --lin From steve at holdenweb.com Mon Dec 15 12:04:31 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 15 Dec 2008 12:04:31 -0500 Subject: alt.possessive.its.has.no.apostrophe In-Reply-To: <4946826E.7060001@tim.thechases.com> References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> <49467CE2.3060401@holdenweb.com> <4946826E.7060001@tim.thechases.com> Message-ID: Tim Chase wrote: > Steve Holden wrote: >> This led to a schism between the British and the >> newly-independent Americans, who responded by taking the "u" >> out of colour, valour, and aluminium. > > Darn Americans and their alminim.... ;-) > > Next thing you know, they'll be putting an I in TEAM.[1] > It's called humour. Or humor. Or incompetence ;-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From __peter__ at web.de Fri Dec 19 04:36:53 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2008 10:36:53 +0100 Subject: eval() and global variables References: Message-ID: Juan Pablo Romero M?ndez wrote: > The hack given by Peter works fine, except in this case: > >>>> def aaaa(fn): > ... f2 = lambda x,y:(x,y,fn(x,y)) > ... function = type(f2) > ... f3 = function(f2.func_code,dict()) > ... print f3 > ... >>>> aaaa(lambda x,y:x+y) > Traceback (most recent call last): > File "", line 1, in > File "", line 4, in aaaa > TypeError: arg 5 (closure) must be tuple >>>> > > > Strange... The variable fn must be passed to the lambda somehow. You could return f2() from aaaa(), and f2() would still have to "know" about it. This is called a "closure". >>> def f(): pass ... >>> function = type(f) >>> print function.__doc__ function(code, globals[, name[, argdefs[, closure]]]) Create a function object from a code object and a dictionary. The optional name string overrides the name from the code object. The optional argdefs tuple specifies the default argument values. The optional closure tuple supplies the bindings for free variables. In your case we can reuse the closure just like the code: >>> def outer(fn): ... def inner(x, y): return x + fn(x, y) ... return function(inner.func_code, {}, closure=inner.func_closure) ... >>> outer(lambda a, b: a*b)(2, 3) 8 While we're at it, let's explore the remaining arguments: >>> f = outer(lambda a, b: a*b) >>> g = function(f.func_code, {}, "yadda", (10, 20), f.func_closure) >>> g >>> g() 210 Peter From google at mrabarnett.plus.com Mon Dec 8 17:28:16 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 08 Dec 2008 22:28:16 +0000 Subject: Text parsing via regex In-Reply-To: <37b28494-c98f-4e06-a451-8a4702030f10@v38g2000yqb.googlegroups.com> References: <37b28494-c98f-4e06-a451-8a4702030f10@v38g2000yqb.googlegroups.com> Message-ID: <493D9F80.2050102@mrabarnett.plus.com> Paul McGuire wrote: > On Dec 8, 12:13 pm, Robocop wrote: >> I'm having a little text parsing problem that i think would be really >> quick to troubleshoot for someone more versed in python and Regexes. >> I need to write a simple script that parses some arbitrarily long >> string every 50 characters, and does not parse text in the middle of >> words > > Are you just wrapping text? If so, then use the textwrap module. > > import textwrap > > source_string = "a bunch of nonsense that could be really long, or > really short depending on the situation" > > print textwrap.fill(source_string,50) > print textwrap.wrap(source_string,50) > > print map(len,textwrap.wrap(source_string,50)) > pad50 = lambda s : (s+ " "*50)[:50] > print '|\n'.join(map(pad50,textwrap.wrap(source_string,50))) > Instead of: pad50 = lambda s : (s+ " "*50)[:50] you could use: pad50 = lambda s: s.ljust(50) > Prints: > > a bunch of nonsense that could be really long, or > really short depending on the situation > ['a bunch of nonsense that could be really long, or', > 'really short depending on the situation'] > [49, 39] > a bunch of nonsense that could be really long, or | > really short depending on the situation > > -- Paul > > > -- > http://mail.python.org/mailman/listinfo/python-list > From prologic at shortcircuit.net.au Tue Dec 16 18:47:58 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 17 Dec 2008 09:47:58 +1000 Subject: Python is slow In-Reply-To: <705998e7-404f-4f4b-a2d6-566660e3e31a@o4g2000pra.googlegroups.com> References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <355f1cfe-6abb-4d2c-8bf4-3aa62e713c1f@w34g2000yqm.googlegroups.com> <705998e7-404f-4f4b-a2d6-566660e3e31a@o4g2000pra.googlegroups.com> Message-ID: On Wed, Dec 17, 2008 at 9:08 AM, r wrote: > What about all the crap you had to go through just to get output? > Python wins Yes I can't say I really enjoy writing C (at all!) _except_ in the case where I may need to optimise some heavy computation. But then again with multi-core CPUs these days and cheap hardware, distributed processing is not only easy, but very effective! And I still wouldn't resort to C because well umm psyco is just awesome! --JamesMills From steve at REMOVE-THIS-cybersource.com.au Sun Dec 21 08:52:27 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Dec 2008 13:52:27 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <3a106de0-5dc6-4017-ab89-45ba145d6787@e1g2000pra.googlegroups.com> <015d9566$0$20656$c3e8da3@news.astraweb.com> <015da0a4$0$20656$c3e8da3@news.astraweb.com> Message-ID: <015e4162$0$20656$c3e8da3@news.astraweb.com> On Sun, 21 Dec 2008 12:45:32 +0000, Duncan Booth wrote: > Steven D'Aprano wrote: > >> Errors should never pass silently, unless explicitly silenced. You have >> implicitly silenced the TypeError you get from not having enough >> arguments for the first format operation. That means that you will >> introduce ambiguity and bugs. >> >> "%i %i %i %i" % 5 % 3 %7 >> >> Here I have four slots and only three numbers. Which output did I >> expect? >> >> '%i 5 3 7' >> '5 %i 3 7' >> '5 3 %i 7' >> '5 3 7 %i' >> >> Or more likely, the three numbers is a mistake, there is supposed to be >> a fourth number there somewhere, only now instead of the error being >> caught immediately, it won't be discovered until much later. >> > You seem to have made an unwarranted assumption, namely that a binary > operator has to compile to a function with two operands. There is no > particular reason why this has to always be the case: for example, I > believe that C# when given several strings to add together optimises > this into a single call to a concatenation method. [...] > Python *could* do something similar if the appropriate opcodes/methods > supported more than two arguments: > > a+b+c+d might execute a.__add__(b,c,d) allowing more efficient string > concatenations or matrix operations, and a%b%c%d might execute as > a.__mod__(b,c,d). That's only plausible if the operations are associative. Addition is associative, but string interpolation is not: >>> "%%%s" % ("%s" % "b") '%b' >>> ("%%%s" % "%s") % "b" Traceback (most recent call last): File "", line 1, in TypeError: not all arguments converted during string formatting Since string interpolation isn't associative, your hypothetical __mod__ method might take multiple arguments, but it would have to deal with them two at a time, unlike concatenation where the compiler could do them all at once. So whether __mod__ takes two arguments or many is irrelevant: its implementation must rely on some other function which takes two arguments and must succeed or fail on that. Either that, or we change the design of % interpolation, and allow it to silently ignore errors. I assumed that is what Aaron wanted. > In that alternate universe your example: > > "%i %i %i %i" % 5 % 3 %7 > > simply throws "TypeError: not enough arguments for format string" That has a disturbing consequence. Consider that most (all?) operations, we can use temporary values: x = 1 + 2 + 3 + 4 => x == 10 gives the same value for x as: temp = 1 + 2 + 3 x = temp + 4 I would expect that the same should happen for % interpolation: # using Aaron's hypothetical syntax s = "%s.%s.%s.%s" % 1 % 2 % 3 % 4 => "1.2.3.4" should give the same result as: temp = "%s.%s.%s.%s" % 1 % 2 % 3 s = temp % 4 But you're arguing that the first version should succeed and the second version, using a temporary value, should fail. And that implies that if you group part of the expression in parentheses, it will fail as well: s = ("%s.%s.%s.%s" % 1 % 2 % 3) % 4 Remove the parentheses, and it succeeds. That's disturbing. That makes the % operator behave very differently from other operators. Note that with the current syntax, we don't have that problem: short- supplying arguments leads to an exception no matter what. > "%s" % (1,2,3) > > just converts the tuple as a single argument. It also provides the > answer to how you put a percent in the format string (double it) I trust you know that already works, but just in case: >>> "%g%%" % 12.5 '12.5%' > and what happens if a substitution inserts a percent (it doesn't > interact with the formatting operators). Ditto: >>> "%s" % "%g" '%g' -- Steven From otrajman at gmail.com Fri Dec 19 19:10:39 2008 From: otrajman at gmail.com (otrajman at gmail.com) Date: Fri, 19 Dec 2008 16:10:39 -0800 (PST) Subject: setup.py installs modules to a wrong place References: <494384EF.7050605@logix.net.nz> Message-ID: <7d6d6971-e6cc-418f-a79e-598517ffb013@j38g2000yqa.googlegroups.com> Michal, I'm seeing this on fc8 with a custom built python2.6. Not happening with any other packages (e.g. boto). Workaround of course was just to copy the S3 dir to /usr/local/lib/python2.6/site-packages. I poked around a bit but nothing obvious jumped out. Happy to do any debugging if you have tests you'd like to me to run. -Omer From python.list at tim.thechases.com Fri Dec 26 19:46:09 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 26 Dec 2008 18:46:09 -0600 Subject: multiply each element of a list by a number In-Reply-To: References: Message-ID: <49557AD1.8080506@tim.thechases.com> > What does *not* work is > 3 * [0,1,2] > As you know, this gives > [0,1,2,0,1,2,0,1,2] > What I am hoping for is > [0,3,6] > I see that I can use > numpy.multiply(3,range(3)) > but this seems overkill to me. Can you tell I am coming to Python from > Matlab? The common way to do this is just a1 = [0,1,2] a2 = [x * 3 for x in a1] or, if you need a1 to be done in place: a1[:] = [x*3 for x in a1] -tkc From marco at sferacarta.com Wed Dec 17 11:07:39 2008 From: marco at sferacarta.com (Marco Mariani) Date: Wed, 17 Dec 2008 17:07:39 +0100 Subject: Selecting a different superclass In-Reply-To: References: Message-ID: Marco Mariani wrote: > I think you should investigate something different than subclassing, > like a "Strategy" domain pattern or something similar. s/domain/design/ From steve at holdenweb.com Thu Dec 11 14:49:23 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 11 Dec 2008 14:49:23 -0500 Subject: newbie question: if var1 == var2: In-Reply-To: <87abb21xzm.fsf@daycos.com> References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> Message-ID: Kirk Strauser wrote: > At 2008-11-29T04:02:11Z, Mel writes: > >> You could try >> >> for item in fname: >> item = item.strip() > > This is one case where I really miss Perl's "chomp" function. It removes a > trailing newline and nothing else, so you don't have to worry about losing > leading or trailing spaces if those are important to you. ... and it's so hard to write item = item[:-1] regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From Robert.T.Lynch at seagate.com Fri Dec 26 19:05:09 2008 From: Robert.T.Lynch at seagate.com (Robert.T.Lynch at seagate.com) Date: Fri, 26 Dec 2008 16:05:09 -0800 Subject: multiply each element of a list by a number Message-ID: What does *not* work is 3 * [0,1,2] As you know, this gives [0,1,2,0,1,2,0,1,2] What I am hoping for is [0,3,6] I see that I can use numpy.multiply(3,range(3)) but this seems overkill to me. Can you tell I am coming to Python from Matlab? Thanks -- Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From rt8396 at gmail.com Tue Dec 16 19:27:11 2008 From: rt8396 at gmail.com (r) Date: Tue, 16 Dec 2008 16:27:11 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> <06bdbdae-ff0e-4b91-96df-8762d99d61d3@a12g2000pro.googlegroups.com> <355f1cfe-6abb-4d2c-8bf4-3aa62e713c1f@w34g2000yqm.googlegroups.com> <705998e7-404f-4f4b-a2d6-566660e3e31a@o4g2000pra.googlegroups.com> Message-ID: On Dec 16, 5:47?pm, "James Mills" wrote: > On Wed, Dec 17, 2008 at 9:08 AM, r wrote: > > What about all the crap you had to go through just to get output? > > Python wins > > Yes I can't say I really enjoy writing C (at all!) > _except_ in the case where I may need to > optimise some heavy computation. But then > again with multi-core CPUs these days and > cheap hardware, distributed processing is > not only easy, but very effective! And I still > wouldn't resort to C because well umm > psyco is just awesome! > > --JamesMills This idiot(cm_gui) just needs to RTFM before going off on tirades like a 3 year old. What i find so funny is after Luis asked "what's the blazingly fast application you need to write so desperately?" we have yet to hear from this "expert programmer". He is probably still trying to get "hello world" to compile. From xahlee at gmail.com Wed Dec 10 16:12:44 2008 From: xahlee at gmail.com (Xah Lee) Date: Wed, 10 Dec 2008 13:12:44 -0800 (PST) Subject: looking up function's doc in emacs Message-ID: in programing elisp in emacs, i can press ?Ctrl+h f? to lookup the doc for the function under cursor. is there such facility when coding in perl, python, php? (i'm interested in particular python. In perl, i can work around with ?perldoc -f functionName?, and in php it's php.net/functionName. Both of which i have a elisp command with a shortcut that let me jump to the doc) Thanks. Xah ? http://xahlee.org/ ? From wx1234 at gmail.com Tue Dec 30 23:26:00 2008 From: wx1234 at gmail.com (dubux) Date: Tue, 30 Dec 2008 20:26:00 -0800 (PST) Subject: TypeError: list indices must be integers References: <2e5a61c0-fa99-4170-81ca-eb3a10859400@k36g2000pri.googlegroups.com> Message-ID: <98f638c1-d191-4f95-9668-01bc3c47526c@i20g2000prf.googlegroups.com> thanks for help everyone. it turned out the function itself worked fine.. it was the way i was calling it that was messing everything up. i ended up re-doing the whole thing as follows, and it now works perfectly. def news(x,y): news_file = '/home/scam/Desktop/www/info/news' news = open(news_file, 'r') news_list = news.readlines() news.close() if x == 'date': mylist = map(lambda i: news_list[i], filter(lambda i: i%2 == 0, range (len(news_list)))) date = mylist[y].replace("\n","") return '

    %s

    \n\n' % (date) if x == 'news': mylist = map(lambda i: news_list[i], filter(lambda i: i%2 == 1, range (len(news_list)))) news = mylist[y].replace("\n","") return '

    %s

    \n
    \n' % (news) else: return news_list news_parse, count, news_list = " ", 0, news('list','list') newss = map(lambda i: news_list[i], filter(lambda i: i%2 == 1, range (len(news_list)))) while count < len(newss): get_date = news('date', count) get_news = news('news', count) news_parse = '%s %s %s' % (news_parse, get_date, get_news) count = count + 1 From goyal.ak at gmail.com Sat Dec 13 22:54:31 2008 From: goyal.ak at gmail.com (Amit Goyal) Date: Sat, 13 Dec 2008 19:54:31 -0800 (PST) Subject: Error with SOAPpy Message-ID: <2da206ed-f3bb-4ef9-b43e-88ba799a9d87@a12g2000pro.googlegroups.com> Hi All, I am new to Python and was trying the sample code on Dive into Python for WSDL. Below is the error I get. Traceback (most recent call last): File "", line 4, in -toplevel- print 'Light sensor value: ' + server._ns(namespace).readLSpercent (int_1 = "1") File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 470, in __call__ return self.__r_call(*args, **kw) File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 492, in __r_call self.__hd, self.__ma) File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 363, in __call config = self.config) File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 187, in call r.endheaders() File "c:\Python24\lib\httplib.py", line 798, in endheaders self._send_output() File "c:\Python24\lib\httplib.py", line 679, in _send_output self.send(msg) File "c:\Python24\lib\httplib.py", line 646, in send self.connect() File "c:\Python24\lib\httplib.py", line 614, in connect socket.SOCK_STREAM): gaierror: (11001, 'getaddrinfo failed') I am using Python 2.4.4 and the following versions. >>> xml.__version__ '0.8.4' >>> fpconst.__version__ '0.7.2' >>> SOAPpy.__version__ '0.12.0' Regards, Amit From xahlee at gmail.com Wed Dec 10 17:15:09 2008 From: xahlee at gmail.com (Xah Lee) Date: Wed, 10 Dec 2008 14:15:09 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <7db0371c-88f8-4984-bb0d-b2078147803e@f40g2000pri.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> Message-ID: <40b4b23f-c1eb-4ac5-bb42-e0f6276e97bf@r37g2000prr.googlegroups.com> Xah Lee wrote: > > For those of you who don't know linear algebra but knows coding, this > > means, we want a function whose input is a list of 3 elements say > > {x,y,z}, and output is also a list of 3 elements, say {a,b,c}, with > > the condition that > > > > a = x/Sqrt[x^2+y^2+z^2] > > b = y/Sqrt[x^2+y^2+z^2] > > c = z/Sqrt[x^2+y^2+z^2] > > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, > > you'll have 50 or hundreds lines. > > > > Note, that the ?norm? as defined above works for vectors of any > > dimention, i.e. list of any length. On Dec 10, 12:37 pm, w_a_x_... at yahoo.com wrote: > Ruby: > > def norm a > s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) > a.map{|x| x/s} > end I don't know ruby, but i tried to run it and it does not work. #ruby def norm a s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) a.map{|x| x/s} end v = [3,4] p norm(v) # returns [0.6, 0.8] The correct result for that input would be 5. Also note, i wrote: ?Note, that the ?norm? as defined above works for vectors of any dimention, i.e. list of any length.?. For detail, see: ? A Example of Mathematica's Expressiveness http://xahlee.org/UnixResource_dir/writ/Mathematica_expressiveness.html Xah ? http://xahlee.org/ ? From sjmachin at lexicon.net Sat Dec 13 17:09:04 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 13 Dec 2008 14:09:04 -0800 (PST) Subject: Python 3.0 crashes displaying Unicode at interactive prompt References: <7fcc5004-1794-452a-85a7-c7a3946541ee@w39g2000prb.googlegroups.com> Message-ID: On Dec 14, 8:07?am, "Chris Rebert" wrote: > On Sat, Dec 13, 2008 at 12:28 PM, John Machin wrote: > > > Python 2.6.1 (r261:67517, Dec ?4 2008, 16:51:00) [MSC v.1500 32 bit > > (Intel)] on win32 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> x = u'\u9876' > >>>> x > > u'\u9876' > > > # As expected > > > Python 3.0 (r30:67507, Dec ?3 2008, 20:14:27) [MSC v.1500 32 bit > > (Intel)] on win 32 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> x = '\u9876' > >>>> x > > Traceback (most recent call last): > > ?File "", line 1, in > > ?File "C:\python30\lib\io.py", line 1491, in write > > ? ?b = encoder.encode(s) > > ?File "C:\python30\lib\encodings\cp850.py", line 19, in encode > > ? ?return codecs.charmap_encode(input,self.errors,encoding_map)[0] > > UnicodeEncodeError: 'charmap' codec can't encode character '\u9876' in > > position > > 1: character maps to > > > # *NOT* as expected (by me, that is) > > > Is this the intended outcome? > > When Python tries to display the character, it must first encode it > because IO is done in bytes, not Unicode codepoints. When it tries to > encode it in CP850 (apparently your system's default encoding judging > by the traceback), it unsurprisingly fails (CP850 is an old Western > Europe codec, which obviously can't encode an Asian character like the > one in question). To signal that failure, it raises an exception, thus > the error you see. > This is intended behavior. I see. That means that the behaviour in Python 1.6 to 2.6 (i.e. encoding the text using the repr() function (as then defined) was not intended behaviour? > Either change your default system/terminal > encoding to one that can handle such characters or explicitly encode > the string and use one of the provided options for dealing with > unencodable characters. You are missing the point. I don't care about the visual representation. What I care about is an unambiguous representation that can be used when communicating about problems across cultures/ networks/mail-clients/news-readers ... the sort of problems that are initially advised as "I got this UnicodeEncodeError" and accompanied by no data or garbled data. > Also, please don't call it a "crash" as that's very misleading. The > Python interpreter didn't dump core, an exception was merely thrown. "spew nonsense on the screen and then stop" is about as useful and as astonishing as "dump core". core? You mean like ferrite doughnuts on a wire trellis? I thought that went out of fashion before cp850 was invented :-) From aaron.hildebrandt at gmail.com Mon Dec 1 14:31:03 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Mon, 1 Dec 2008 11:31:03 -0800 (PST) Subject: Checking a string against multiple matches Message-ID: <99a3a677-a38d-40f5-9a94-a98865150b69@k19g2000yqg.googlegroups.com> I've been trying to read up on this, but I'm not sure what the simplest way to do it is. I have a list of string. I'd like to check to see if any of the strings in that list matches another string. Pseudocode: if "two" in ["one", "two", "three", "four"]: return True Is there any built-in iteration that would do such a thing, or do I have to write a function to check for me? I was using .index on the list, but it would return True for strings that contained the search string rather than match it exactly, leading to false positives in my code. From prologic at shortcircuit.net.au Mon Dec 29 22:08:16 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 30 Dec 2008 13:08:16 +1000 Subject: multiprocessing vs thread performance In-Reply-To: References: <26f7d44e-552c-41e9-9290-17e5c4e6deb9@q30g2000prq.googlegroups.com> Message-ID: On Tue, Dec 30, 2008 at 12:52 PM, Aaron Brady wrote: > On Dec 29, 7:40 pm, "James Mills" > wrote: >> On Tue, Dec 30, 2008 at 11:34 AM, Aaron Brady wrote: >> > The OP may be interested in Erlang, which Wikipedia (end-all, be-all) >> > claims is a 'distribution oriented language'. > snip >> I'm presently looking at Virtual Synchrony and >> other distributed processing architectures - but >> circuits is meant to be general purpose enough >> to fit event-driven applications/systems. > > I noticed a while ago that threads can be used to simulate > generators. 'next', 'send', and 'yield' are merely replaced by > synchronizor calls (coining the term). > > Not the other way around, though, unless the generator guarantees a > yield frequently. 'settrace' anyone? Aaron, circuits doesn't use generators :) What did your comment have to do with this ? I have often seen generators used to facilitate coroutine and coooperative programming though. cheers James From joe at strout.net Mon Dec 8 10:18:27 2008 From: joe at strout.net (Joe Strout) Date: Mon, 8 Dec 2008 08:18:27 -0700 Subject: A question about reference in Python. In-Reply-To: <493CB003.3080209@gmail.com> References: <493CB003.3080209@gmail.com> Message-ID: On Dec 7, 2008, at 10:26 PM, Group wrote: > Now, I want to write a Red-Black Tree, and a List structure. In C/C+ > +, I can > use pointers to refer to children notes (or next notes). But, in > Python, how > can I do it? Except the sequence, I know not any way. Any variable in Python is a reference, which is roughly analogous to a pointer type in C/C++. For details and examples, see: Best, - Joe From stargaming at gmail.com Mon Dec 22 07:06:46 2008 From: stargaming at gmail.com (Robert Lehmann) Date: 22 Dec 2008 12:06:46 GMT Subject: no sign() function ? References: <1isck7g.14q8efa12x6bmwN%pdorange@pas-de-pub-merci.mac.com> <1iscntk.1jdp75221fzwgN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <494f82d6$0$9151$9b622d9e@news.freenet.de> On Mon, 22 Dec 2008 12:31:44 +0100, Pierre-Alain Dorange wrote: >> > I don't find any sign(x) function in the math library (return the >> > sign of the value). >> > I've read that math module is a wrapper to C math lib and that C math >> > lib has not sign(), so... [snip] > As my need is for a game and that i do not have IEEE real concern, i > would simply using my simple function (but not as accurate) : > > def sign(x): > if x==0.0: > return 0.0 > elif x>0.0: > return 1.0 > else: > return -1.0 I found this snippet to be quite succinct (even though being smart *might* be wrong in programming):: sign = lambda x:+(x > 0) or -(x < 0) HTH, -- Robert "Stargaming" Lehmann From gregory.j.baker at gmail.com Tue Dec 2 15:27:15 2008 From: gregory.j.baker at gmail.com (gregory.j.baker at gmail.com) Date: Tue, 2 Dec 2008 12:27:15 -0800 (PST) Subject: Running a Python script from crontab References: <21ddcf54-e64c-411e-835f-a2d06644dfa0@x38g2000yqj.googlegroups.com> Message-ID: Try using the following at the begining of your Python program: import sys sys.stdout = open("out.txt","w") sys.stderr = open("err.txt","w") Then whatever would normally go to stdout or stderr goes to text files instead. You will see everything that happened. From febaen at gmail.com Sun Dec 14 05:53:10 2008 From: febaen at gmail.com (feba) Date: Sun, 14 Dec 2008 02:53:10 -0800 (PST) Subject: Need help improving number guessing game References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> <70db2007-245a-4e5a-887e-e6af89ae6b18@o40g2000prn.googlegroups.com> Message-ID: <5c0fb701-f730-4700-a8ea-45f8c8ecf6f4@a29g2000pra.googlegroups.com> #!/usr/bin/python #Py3k, UTF-8 import random def setup(): #global target, guess, a, b #a, b make minimum, maximum. Can be adjusted. a, b = 1, 99 target = random.randint(a, b) return a, b, target def playerswitch(player): #Player Switch #if player's a witch, burn her! if player == "P1": player = "P2" else: player = "P1" return player def youwin(pnum, player, p1sc, p2sc): if pnum == 1: print("CONGRATULATIONS!") else: if player == "P1": p1sc += 1 else: p2sc += 1 end = "CONGRATULATIONS %s! SCORE -- P1:%s P2:%s" print(end %(player, p1sc, p2sc)) return p1sc, p2sc def playagain(play): playover = input("PLAY AGAIN? Y/N: ") if playover.strip().lower() == "y": play = 1 a, b, target = setup() else: print("GOOD BYE. PLAY AGAIN SOON!") quit() return play, a, b, target def guesscheck(guess, target, play, a, b, p1sc, p2sc): if guess == target: p1sc, p2sc = youwin(pnum, player, p1sc, p2sc) play, a, b, target = playagain(play) elif guess >= b: print("NUMBER MUST BE IN RANGE") guess = int(input("[%s-%s]%s>> " % (a, b, player))) play, a, b, target, p1sc, p2sc = guesscheck(guess, target, play, a, b, p1sc, p2sc) elif guess <= a: print("NUMBER MUST BE IN RANGE") guess = int(input("[%s-%s]%s>> " % (a, b, player))) play, a, b, target, p1sc, p2sc = guesscheck(guess, target, play, a, b, p1sc, p2sc) elif guess > target: print("TOO HIGH") b = guess else: print("TOO LOW") a = guess return play, a, b, target, p1sc, p2sc def guessing(a, b, player, pnum, target, p1sc, p2sc, play): #a and b are to keep the user aware of min/max guess = int(input("[%s-%s]%s>> " % (a, b, player))) play, a, b, target, p1sc, p2sc = guesscheck(guess, target, play, a, b, p1sc, p2sc) if pnum == 2: player = playerswitch(player) return play, a, b, player, target, p1sc, p2sc #Let the show begin! print("WELCOME TO THE SUPER NUMBER GUESSING GAME!") pnum = int(input("1 OR 2 PLAYERS?\n> ")) play = 1 player = "P1" # P1 goes first #Scores, keep track of times player guessed first. p1sc, p2sc = 0, 0 #Grabs minimum, maximum, and target numbers a, b, target = setup() while play == 1: play, a, b, player, target, p1sc, p2sc \ = guessing(a, b, player, pnum, target, p1sc, p2sc, play) This is what I have now. It seems to work perfectly, and I tried to work in your suggestions. Thanks, by the way, for recommending the style guide. I've bookmarked it, and I'll try to remember to consult it in the future. One (extremely minor) annoyance is that if you have only one possible guess left you still have to type it in manually. As an example, [30-32]P#>> can only possibly be 31 (and I've changed it so that any number >= 32 or <= 30 won't be accepted, so it's all the user can input), which means whatever player is in control has a %100 chance of winning. I know that "if b - a == 2" would be a simple enough test for this, but I'm not quite sure when to put it, or what to do with it. And yes, I'm aware that guess = int(input("[%s-%s]%s>> " % (a, b, player))) play, a, b, target, p1sc, p2sc = guesscheck(guess, target, play, a, b, p1sc, p2sc) is repeated three times. I will probably try to change this into a function later on; right now, I just spent a few hours trying to get this to work and making sure that it does (by playing it), so I'm going to take a break. From dlemper Sun Dec 21 16:42:39 2008 From: dlemper (dlemper) Date: Sun, 21 Dec 2008 15:42:39 -0600 Subject: wxpython for python 3.0 ? Message-ID: The wxpython web describes compatability with python 2.4 & 2.5 . Does it work with 3.0 ? If not, anyone have a clue as to when ? From bj_666 at gmx.net Fri Dec 12 06:08:09 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 12 Dec 2008 11:08:09 GMT Subject: File names, character sets and Unicode References: Message-ID: <6qev0oFc3a5jU1@mid.uni-berlin.de> On Fri, 12 Dec 2008 23:32:27 +1300, Michal Ludvig wrote: > is there any way to determine what's the charset of filenames returned > by os.walk()? No. Especially under *nix file systems file names are just a string of bytes, not characters. It is possible to have file names in different encondings in the same directory. > The trouble is, if I pass argument to os.walk() I get the > filenames as byte-strings. Possibly UTF-8 encoded Unicode, who knows. Nobody knows. :-) > What's the right and safe way to walk the filesystem and get some > meaningful filenames? The safe way is to use `str`. > Related question - if the directory is given name on a command line > what's the right way to preprocess the argument before passing it down > to os.walk()? Pass it as is. > For instance with LANG=en_NZ.UTF-8 (i.e. UTF-8 system): * directory is > called 'smile?' > * sys.argv[1] will be 'smile\xe2\x98\xba' (type str) * after > .decode("utf-8") I get u'smile\u263a' (type unicode) > > But how should I decode() it when running on a system where $LANG > doesn't end with "UTF-8"? Apparently some locales have non-ascii default > charsets. For instance zh_TW is BIG5 charset by default, ru_RU is > ISO-8850-5, etc. How do I detect that to get the right charset for > decode()? You can't. Even if you know the preferred encoding of the system, e.g. via $LANG, there is no guarantee that all file names are encoded this way. > I tend to have everything internally in Unicode but it's often unclear > how to convert some inputs to Unicode in the first place. What are the > best practices for dealing with these chraset issues in Python? I'm usually using UTF-8 as default but offer the user ways, e.g. command line switches, to change that. If I have to display file names in a GUI I use a decoded version of the byte string file name, but keep the byte string for operations on the file. Ciao, Marc 'BlackJack' Rintsch From pruebauno at latinmail.com Tue Dec 9 12:02:42 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Tue, 9 Dec 2008 09:02:42 -0800 (PST) Subject: When (and why) to use del? References: Message-ID: On Dec 9, 11:35?am, Albert Hopkins wrote: > I'm looking at a person's code and I see a lot of stuff like this: > > ? ? ? ? def myfunction(): > ? ? ? ? ? ? # do some stuff stuff > ? ? ? ? ? ? my_string = function_that_returns_string() > ? ? ? ? ? ? # do some stuff with my_string > ? ? ? ? ? ? del my_string > ? ? ? ? ? ? # do some other stuff > ? ? ? ? ? ? return > > and also > > ? ? ? ? def otherfunction(): > ? ? ? ? ? ? try: > ? ? ? ? ? ? ? ? # some stuff > ? ? ? ? ? ? except SomeException, e: > ? ? ? ? ? ? ? ? # more stuff > ? ? ? ? ? ? ? ? del e > ? ? ? ? ? ? return > > I think this looks ugly, but also does it not hurt performance by > preempting the gc? ?My feeling is that this is a misuse of 'del'. Am I > wrong? ?Is there any advantage of doing the above? If this is CPython (the standard Python) the extra del(s) in the examples you gave are just garbage and good for nothing. The reason being that they are inside a function; as soon as the program exits the function the variable gets deleted automatically. The only reason to use del would be a global variable in long running program that uses a lot of space, but global variables should be avoided for other reasons anyway. I never ever used del in my programs only on the interactive interpreter prompt after doing foolish things like x=open ('1GBfile').read() From nicolas.delanos at gmail.com Fri Dec 26 16:54:25 2008 From: nicolas.delanos at gmail.com (nicolas.delanos at gmail.com) Date: Fri, 26 Dec 2008 13:54:25 -0800 (PST) Subject: Python and DomainKey Message-ID: <63e888c6-d20b-414e-87f6-e998d8fb669e@v4g2000vbb.googlegroups.com> Hello, I'm working on a script able to send email using DomainKey and DKIM. For DKIM, it's working well (Thanks Greg - pydkim) but with DomainKey, I have trouble. There is no library yet able to sign emails. I tried to modify the pydkim library to implement DK but everything I have a "sig fail". Do you know a dk library ? From steve at REMOVE-THIS-cybersource.com.au Thu Dec 18 21:11:28 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2008 02:11:28 GMT Subject: Factoring Polynomials References: <015aebdf$0$20656$c3e8da3@news.astraweb.com> Message-ID: <015afa29$0$20656$c3e8da3@news.astraweb.com> On Thu, 18 Dec 2008 17:42:28 -0800, Collin D wrote: > The corrected function is: > def quadratic_solution(a,b,c) > sol1 = -1*b + ((b**2 - 4*a*c)**.5)/2*a > sol1 = -1*b - ((b**2 - 4*a*c)**.5)/2*a > return (sol1, sol2) > > Squaring the -b would give you some strange solutions.... :D So it would, but I didn't do that. Try again. You have a typo in the above: you've written "sol1" twice and there is no sol2. There is no difference between -1*b and -b (except that -b is probably a smidgen faster). In the quadratic formula, the -b must be divided by 2a as well as the discriminant. You're only dividing the discriminant. The *second* error has already been given away by Mark Dickson, who rightly points out that the quadratic equation is subject to round-off errors. The first error is still there :) (Hint: think about the precedence of operators and the need for brackets.) -- Steven From greywine at gmail.com Wed Dec 24 00:59:42 2008 From: greywine at gmail.com (greywine at gmail.com) Date: Tue, 23 Dec 2008 21:59:42 -0800 (PST) Subject: socket send help Message-ID: Hi everyone, New guy here. I'm trying to figure out sockets in order to one day do a multiplayer game. Here's my problem: even the simplest examples don't work on my computer: A simple server: from socket import * myHost = '' myPort = 21500 s = socket(AF_INET, SOCK_STREAM) # create a TCP socket s.bind((myHost, myPort)) # bind it to the server port s.listen(5) # allow 5 simultaneous connections while True: connection, address = s.accept() while True: data = connection.recv(1024) if data: connection.send('echo -> ' + data) else: break connection.close() # close socket And a simple client: import sys from socket import * serverHost = 'localhost' # servername is localhost serverPort = 21500 # use arbitrary port > 1024 s = socket(AF_INET, SOCK_STREAM) # create a TCP socket s.connect((serverHost, serverPort)) # connect to server on the port s.send('Hello world') # send the data data = s.recv(1024) # receive up to 1K bytes print(data) If I run testserver.py via the cmd prompt in Windows XP and then the testclient.py program, I get the following error: Traceback (most recent call last): File "C:\Python30\testclient.py", line 12, in s.send('Hello world') # send the data TypeError: send() argument 1 must be string or buffer, not str This happens in 2.6 or 3.0 and with different example client & server programs from the web. What am I missing? Thanks, John R. From deets at nospam.web.de Thu Dec 11 18:03:25 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 12 Dec 2008 00:03:25 +0100 Subject: Best way of debigging a C extension In-Reply-To: References: <18ad387a-e421-4581-9d83-e06131bced25@35g2000pry.googlegroups.com> <6qdjt7Fc1fg0U1@mid.uni-berlin.de> Message-ID: <6qdkhtFc5ce1U1@mid.uni-berlin.de> Grant Edwards schrieb: > On 2008-12-11, Diez B. Roggisch wrote: > >> I never tried this on windows - but what happens if you start >> python inside GDB, and then set breakpoints inside your >> extension? >> >> This works flawlessly for me under *nix. >> >> The debug-build of python isn't needed for this - and I doubt >> a bit that it helps you much, as being inside the interpreter >> & getting detailed information isn't your goal - you want to >> see your extensions functions, what parameters they get and so >> on. > > It's probably a lot easier to just stick in a few printf() > calls in key places... > Easier than $ gdb python # set args myscript.py # break some_function_of_mine ? Diez From ldo at geek-central.gen.new_zealand Wed Dec 3 02:45:18 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 03 Dec 2008 20:45:18 +1300 Subject: Linear2D Message-ID: I've decided to give Github a go, with a simple project containing some routines for performing 2D linear transformations . This takes a functional rather than procedural approach. For example, a function to construct a matrix that maps a source rectangle to a destination rectangle is def MapRect(SrcRect, DstRect) : return \ ( Matrix.translation(- SrcRect.topleft()) * Matrix.scaling(DstRect.dimensions() / SrcRect.dimensions()) * Matrix.translation(DstRect.topleft()) ) #end MapRect From nick at craig-wood.com Mon Dec 8 05:30:50 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 08 Dec 2008 04:30:50 -0600 Subject: Learning Python now coming from Perl References: Message-ID: Bertilo Wennergren wrote: > I'm planning to start learning Python now, using Python 3000. > I have no previous Python skills, but I now Perl pretty well. > I'm also well experienced with JavaScript. > > Any pointers and tips how I should go about getting into > Python? Read "Dive Into Python" while following along with your keyboard. ( http://www.diveintopython.org/ free online or paper edition from your favourite bookseller ) My favourite mistake when I made the transition was calling methods without parentheses. In perl it is common to call methods without parentheses - in python this does absolutely nothing! pychecker does warn about it though. perl -> $object->method python -> object.method() -- Nick Craig-Wood -- http://www.craig-wood.com/nick From steve at REMOVE-THIS-cybersource.com.au Fri Dec 5 18:35:44 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Dec 2008 23:35:44 GMT Subject: Python 3.0 automatic decoding of UTF16 References: <5u8o06xbqf.ln2@joeserver.homelan.net> Message-ID: <0149b28c$0$20670$c3e8da3@news.astraweb.com> On Fri, 05 Dec 2008 12:00:59 -0700, Joe Strout wrote: >> So UTF-16 has an explicit EOF marker within the text? > > No, it does not. I don't know what Terry's thinking of there, but text > files do not have any EOF marker. They start at the beginning > (sometimes including a byte-order mark), and go till the end of the > file, period. Windows text files still interpret ctrl-Z as EOF, or at least Windows XP does. Vista, who knows? -- Steven From robert.kern at gmail.com Fri Dec 19 18:39:51 2008 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 19 Dec 2008 17:39:51 -0600 Subject: IDLE doesn't show stderr output from extension modules In-Reply-To: <6406df08-36bb-4cd8-a356-6d563c2eac7f@e1g2000pra.googlegroups.com> References: <6406df08-36bb-4cd8-a356-6d563c2eac7f@e1g2000pra.googlegroups.com> Message-ID: Brian Cole wrote: > I'm importing an extension module created with SWIG. When working with > the module interactively in IDLE there should be warning and error > messages printed to stderr by the extension module. However, these are > not being caught by the IDLE window, they are going directly to the > terminal that was used to start IDLE. > > Strange, because sys.stderr.write() does print to the IDLE window. > I've tried this on Windows and OSX, so it doesn't appear to be a > platform issue. Is this just a fundamental deficiency in the IDLE > shell prompt? Yup. IDLE swaps out the sys.stdout and sys.stderr objects at the Python level. It does not replace the STDOUT and STDERR C file pointers. Python code and C extension modules which use the Python APIs to write stuff out should get redirected, but extension modules that use fprintf(), etc., directly to STDOUT and STDERR won't. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From benjamin.kaplan at case.edu Sun Dec 21 17:40:31 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 21 Dec 2008 17:40:31 -0500 Subject: wxpython for python 3.0 ? In-Reply-To: References: Message-ID: On Sun, Dec 21, 2008 at 4:42 PM, wrote: > The wxpython web describes compatability with python 2.4 & 2.5 . > Does it work with 3.0 ? If not, anyone have a clue as to when ? This question was asked a couple of times on the wxpython-users mailing list. It's probably going to take a while. For now, I'd stick to python 2.x. The next version of wxPython should support 2.6, so use that and try to make your code relatively compatible with Python 3 (use the division, print_function, and unicode_literals future imports). Then, you'll be all set when Robin gets around to porting everything to Python 3. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sat Dec 6 22:09:23 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 03:09:23 GMT Subject: "as" keyword woes References: <6e62c503-eb84-4b28-a364-289cbdae1a21@l33g2000pri.googlegroups.com> <0147dc24$0$20670$c3e8da3@news.astraweb.com> <0148b217$0$20670$c3e8da3@news.astraweb.com> <7d0lj4d9hai2f87r30erc4l1ir85osbfg7@4ax.com> <88579d9a-df52-49b9-a6fe-53c8f4524bf3@j39g2000yqn.googlegroups.com> <70llj41hie2svs68o5efn22i97f649svfh@4ax.com> <1cda9a9a-1641-424b-9f3d-c4e2635efed7@j38g2000yqa.googlegroups.com> <014b0f94$0$20670$c3e8da3@news.astraweb.com> <4469f2ed-f012-400d-9d4f-bd44cd075d0d@w34g2000yqm.googlegroups.com> Message-ID: <014b3616$0$20670$c3e8da3@news.astraweb.com> On Sat, 06 Dec 2008 18:09:07 -0800, Mensanator wrote: > On Dec 6, 6:25?pm, Steven D'Aprano cybersource.com.au> wrote: >> On Sat, 06 Dec 2008 14:36:07 -0800, Mensanator wrote: >> > It was extremely simple for me to fix the sympy module where I >> > noticed it. I'm not saying it wasn't a problem, I'm saying it wasn't >> > BROKEN. >> >> If it wasn't broken, why did you need to fix it? > > If my tire is flat, I have to fix it. But it may just need air, in which > case it's not broken. In which case it doesn't need *fixing*, it needs *refilling*. A flat tire isn't necessarily broken. It is broken if it has a puncture or a slow leak or has been ripped to shreds, but not if somebody merely let the air out. "Air comes out if you open the value" is within standard operating parameters and the tire is therefore working correctly. >> "Broken" means "not working", not "unfixable". > > So, you're saying that Python is broken and will remain so forever, > since "as" will remain a keyword? I don't think that having "as" be a keyword is broken. I think the OP's code is broken for Python 2.6 or better, and it will remain broken forever unless he fixes it or chooses to stay with 2.5. > Are you advocating that we all switch to Ruby? Why do you think that? Do you imagine that Ruby has no features which are inconvenient to users, or backwards incompatibilities, or warts, or that it is impossible to write broken Ruby code? -- Steven From hubaghdadi at gmail.com Sun Dec 28 07:06:36 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Sun, 28 Dec 2008 04:06:36 -0800 (PST) Subject: What is site-packages? References: Message-ID: On Dec 28, 2:04?pm, "Chris Rebert" wrote: > On Sun, Dec 28, 2008 at 3:40 AM, Hussein B wrote: > > Hey, > > What is /usr/lib/pythonx.y/site-packages folder and for what it is > > used usually? > > I believe it's where third-party libraries are typically installed to. > > Cheers, > Chris > > -- > Follow the path of the Iguana...http://rebertia.com You mean like MoinMoin, Django or Pylons for example? From thudfoo at opensuse.us Thu Dec 11 14:44:31 2008 From: thudfoo at opensuse.us (member thudfoo) Date: Thu, 11 Dec 2008 11:44:31 -0800 Subject: Equivalent of 'wget' for python? In-Reply-To: References: Message-ID: <3d881a310812111144k238fb4d2rc07d3f3a0593bba3@mail.gmail.com> On Mon, Dec 8, 2008 at 8:22 AM, Robert Dailey wrote: > Hi, > > I'm looking for a portable way to download ZIP files on the internet > through Python. I don't want to do os.system() to invoke 'wget', since > this isn't portable on Windows. I'm hoping the core python library has > a library for this. Note that I'll be using Python 3.0. > > Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > This module might be of interest: http://linux.duke.edu/projects/urlgrabber/ From istvan.albert at gmail.com Thu Dec 4 13:20:00 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Thu, 4 Dec 2008 10:20:00 -0800 (PST) Subject: Python 3 read() function References: Message-ID: <7cda0d37-a14e-49c2-a140-c9a4836a86af@i18g2000prf.googlegroups.com> I can confirm this, I am getting very slow read performance when reading a smaller 20 MB file. - Python 2.5 takes 0.4 seconds - Python 3.0 takes 62 seconds fname = "dmel-2R-chromosome-r5.1.fasta" data = open(fname, 'rt').read() print ( len(data) ) From prologic at shortcircuit.net.au Tue Dec 30 19:52:57 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 31 Dec 2008 10:52:57 +1000 Subject: multiprocessing vs thread performance In-Reply-To: References: <26f7d44e-552c-41e9-9290-17e5c4e6deb9@q30g2000prq.googlegroups.com> <47cfc6de-4b13-4a74-accc-c1d027c44d5a@35g2000pry.googlegroups.com> Message-ID: On Wed, Dec 31, 2008 at 8:42 AM, James Mills wrote: (snip) > As I continue to develop circuits and improve it's > core design as well as building it's ever growing set > of Components, I try to keep it as general as > possible - my main aim though is distributed > processing and architectures. (See the primes example). Aaron, just wanted to demonstrate to you the example (primes) that I mentioned above: On Terminal A: jmills at atomant:~/circuits/examples$ ./primes.py -o primes.txt -b 127.0.0.1:8000 -p 1000 -w Total Primes: 1001 (23/s after 44.16s) Total Events: 43373 (983/s after 44.16s) Distribution: c1096b40-7606-4ba7-9593-1385e14ef339: 348 8313b43f-d45d-4a0a-8d87-e6a93d3dfb0b: 653 On Terminal B: jmills at atomant:~/other/circuits/examples$ ./primes.py -b 127.0.0.1:8001 -s 127.0.0.1:8000 The example uses circuits to distribute work amongst any arbitrary number of nodes connected to the system. This is all manually implemented by simply taking advantage of the circuits framework with my basic understanding ( so far ) of distributed processing, virtual synchrony, and other techniques. This is the same thing just run on a single node (no distribution): jmills at atomant:~/circuits/examples$ ./primes.py -o primes.txt -b 127.0.0.1:8000 -p 1000 Total Primes: 1001 (17/s after 62.13s) Total Events: 28579 (460/s after 62.13s) Distribution: 701be749-9833-40a4-9181-5ee18047b1ad: 1001 As you can see, running 2 instances almost halves the time. If you do try this though, you'll note that the CPU isn't being used very heavily at all - This could be improved - but the example merely demonstrates distributed event processing and syncronization. cheers James From tjreedy at udel.edu Tue Dec 23 17:04:20 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Dec 2008 17:04:20 -0500 Subject: [ANN] Python 2.5.4 (final) In-Reply-To: <4951482D.8050302@v.loewis.de> References: <4951482D.8050302@v.loewis.de> Message-ID: Martin v. L?wis wrote: > For more information on Python 2.5.4, including download > links for various platforms, release notes, and known issues, please > see: > > http://www.python.org/2.5.4 http://www.python.org/download/releases/2.5.4/ From gubatron at gmail.com Wed Dec 3 13:01:54 2008 From: gubatron at gmail.com (Gubatron) Date: Wed, 3 Dec 2008 10:01:54 -0800 (PST) Subject: Jython: Packing several .py on .jar, problem importing .py modules within the .jar References: <0ad925d8-f890-4b12-b0e0-e8c3a7dacf8c@v4g2000yqa.googlegroups.com> Message-ID: <7b48c8b2-7fb2-4e23-bdc2-d1cb7ab361d9@e18g2000yqo.googlegroups.com> cont... Take in consideration /** Hashtable of URLClassLoaders for each of the jars loaded */ private Hashtable classLoaders; Here's an example: org.python.core.PySystemState pySys = new org.python.core.PySystemState(); //classLoaders is a set that refers to a bunch of URLClassLoader objects pySys.setClassLoader(((URLClassLoader) classLoaders.get(jarFile))); //We also have to pass the jar to JYTHON_PATH (sys.path) //so that it can properly import inner python modules. pySys.path.insert(0,new PyString(jarFile)); //We pass the PythonInterpreter the modified PySystemState PythonInterpreter i = new PythonInterpreter (null, pySys); i.exec(pythonScriptName); Here's my method to create a classLoader that has a jarFile in its classpath: /** * Adds a given Jar to the Classpath. * Jython uses both classloaders, and it's JYTHONPATH (sys.path) * The classloaders help it find Java classes, in this case inside the jar * that contains the plugin. * * @param jarFile * * Where jarFile is the path (String) to the jarFile. * * I won't delete it though, in case it might be needed to load resources from * the jar. However, I believe the adition to the sys.path of jython will be enough. */ public void addJar2Classpath(String jarFile) throws Exception { if (jarFile == null) throw new Exception("PluginLoader.addJar2Classpath() - the jar file path can't be null"); File f = new File(jarFile); if (!f.exists()) { LOG.error("Jar doesn't exist ("+jarFile+")"); throw new Exception("PluginLoader.addJar2Classpath() - The jar file doesn't exist ("+ jarFile +")"); } URL jarURL = null; try { jarURL = new URL("jar:file:"+jarFile+"!/"); //jarURL = f.toURI().toURL(); LOG.info("The jar as an url " + jarURL); } catch (Exception e) { LOG.error("Bad URL for jar ("+jarFile+"):\n"+e.toString() +" ("+jarURL+")\n"); return; } if (loadedJar(jarURL)) { LOG.info("Jar was already loaded ("+jarURL+")"); return; } synchronized (classLoaders) { getLoadedJars().add((URL) jarURL); } //Create a new class loader for this jar. classLoaders.put(jarFile, URLClassLoader.newInstance(new URL[] {jarURL})); LOG.info("Jar loaded ("+jarURL+")"); } //addJar2Classpath So if we had a Jar like this: M Filemode Length Date Time File - ---------- -------- ----------- -------- ------------------------------------- drwxrwxrwx 0 3-Dec-2008 12:46:22 meta-inf/ -rw-rw-rw- 71 3-Dec-2008 12:46:22 meta-inf/manifest.mf drwxrwxrwx 0 3-Dec-2008 12:46:22 twoScriptsTest/com/ -rw-rw-rw- 491 3-Dec-2008 12:46:22 twoScriptsTest/com/ HelloFromJar.class drwxrwxrwx 0 3-Dec-2008 12:46:18 twoScriptsTest/guba/ -rw-rw-rw- 0 3-Dec-2008 06:24:22 twoScriptsTest/guba/ __init__.py -rw-rw-rw- 959 3-Dec-2008 12:46:18 twoScriptsTest/guba/ test.py -rw-rw-rw- 124 2-Dec-2008 17:50:56 twoScriptsTest/guba/ pleaseWork.py -rw-rw-rw- 0 3-Dec-2008 12:29:56 twoScriptsTest/ __init__.py - ---------- -------- ----------- -------- ------------------------------------- When we executed: i.exec("from guba import test") if test.py had this code, it'd work perfectly: #Import and use the Java Object inside the jar from com import HelloFromJar h = HelloFromJar() h.sayHello() #Import the other python module inside the jar from pleaseWork import echo echo("FrostWire") NOTE: It's very important that you have the __init__.py on the folders otherwise Jython won't find the modules. On Dec 3, 12:54?pm, Gubatron wrote: > I've managed to solve this problem. > > I can now run a python script that lives inside a Jar. The python > script is now able to import other scripts within the same jar, and > it's also able to import java classes that live within the jar. > > The problem was solved by giving the Jython Interpreter the proper > initialization. This entails: > > - Giving it a class loader that has put the Jar on it's class path > - Adding the path of the jar to the interpreter's sys.path > > Here's an example: > > ? ? ? ? ? ? ? ? ? ? ? ? org.python.core.PySystemState pySys = new > org.python.core.PySystemState(); > ? ? ? ? ? ? ? ? ? ? ? ? pySys.setClassLoader(((URLClassLoader) classLoaders.get(jarFile))); > > ? ? ? ? ? ? ? ? ? ? ? ? //We also have to pass the jar to JYTHON_PATH (sys.path) > ? ? ? ? ? ? ? ? ? ? ? ? //so that it can properly import inner python modules. > ? ? ? ? ? ? ? ? ? ? ? ? pySys.path.insert(0,new PyString(jarFile)); > > ? ? ? ? ? ? ? ? ? ? ? ? //We pass the PythonInterpreter the modified PySystemState > ? ? ? ? ? ? ? ? ? ? ? ? PythonInterpreter i = new PythonInterpreter(null, pySys); > ? ? ? ? ? ? ? ? ? ? ? ? i.exec(pythonScriptName); > > On Dec 3, 6:31?am, Gubatron wrote: > > > Hello all, > > > I've a problem with Jython and importing .py inside a jar. > > > I'm putting .class and .py files inside .jar files. > > > myjar.jar > > ? MyJar\SomeClass.class > > ? MyJar\main.py > > ? MyJar\otherModule.py > > > So I add the myjar.jar to Jython's sys.path > > > ? ? ? ? ? ? ? ? ? ? ? ? org.python.core.PySystemState pySys = new > > org.python.core.PySystemState(); > > ? ? ? ? ? ? ? ? ? ? ? ? pySys.path.insert(0,new PyString("/path/to/myjar.jar")); > > > and execute main.py > > > ? ? ? ? ? ? ? ? ? ? ? ? //We pass the PythonInterpreter the modified PySystemState > > ? ? ? ? ? ? ? ? ? ? ? ? PythonInterpreter i = new PythonInterpreter(null, pySys); > > > ? ? ? ? ? ? ? ? ? ? ? ? //Find the entry in the jar for the python file and execute it. > > ? ? ? ? ? ? ? ? ? ? ? ? //It should be able to find any resource inside the jar. > > ? ? ? ? ? ? ? ? ? ? ? ? JarFile jFile = new JarFile("/path/to/myjar.jar"); > > ? ? ? ? ? ? ? ? ? ? ? ? ZipEntry zipEntry = jFile.getEntry("MyJar/main.py"); > > > ? ? ? ? ? ? ? ? ? ? ? ? InputStream pythonInputStream = > > jFile.getInputStream(zipEntry); > > ? ? ? ? ? ? ? ? ? ? ? ? i.execfile(pythonInputStream); > > > main.py will execute fine, it'll be able to do > > > from MyJar import SomeClass > > > with no problem > > > However, If I try to import the other .py in the same jar, it won't > > find it: > > > from otherModule import * > > > or > > > from MyJar.otherModule import * > > > I always get this: > > > ImportError: no module named otherModule > > > ? ? ? ? at org.python.core.Py.ImportError(Unknown Source) > > ? ? ? ? at org.python.core.imp.import_first(Unknown Source) > > ? ? ? ? at org.python.core.imp.import_name(Unknown Source) > > ? ? ? ? at org.python.core.imp.importName(Unknown Source) > > ? ? ? ? at org.python.core.ImportFunction.load(Unknown Source) > > ? ? ? ? at org.python.core.ImportFunction.__call__(Unknown Source) > > ? ? ? ? at org.python.core.PyObject.__call__(Unknown Source) > > ? ? ? ? at org.python.core.__builtin__.__import__(Unknown Source) > > ? ? ? ? at org.python.core.imp.importFromAs(Unknown Source) > > ? ? ? ? at org.python.core.imp.importFrom(Unknown Source) > > ? ? ? ? at org.python.pycode._pyx1.f$0(:26) > > ? ? ? ? at org.python.pycode._pyx1.call_function() > > ? ? ? ? at org.python.core.PyTableCode.call(Unknown Source) > > ? ? ? ? at org.python.core.PyCode.call(Unknown Source) > > ? ? ? ? at org.python.core.Py.runCode(Unknown Source) > > ? ? ? ? at org.python.util.PythonInterpreter.execfile(Unknown Source) > > > I've tried adding more paths to sys.path, with no luck: > > > pySys.path.insert(0,new PyString("/path/to/myjar.jar/MyJar")); > > pySys.path.insert(0,new PyString("file:jar:/path/to/myjar.jar!")); > > > and nothing works, any ideas would help. I know this has to work, > > because I previously had a problem where I couldn't do > > > import os > > > and then I added the "Lib/" folder inside jython.jar and now I'm able > > to import all those standard jython modules, so, somehow, jython is > > able to import .py within a .jar, help would be very much appreciated. > > > Angel Leon > > From bdesth.quelquechose at free.quelquepart.fr Sun Dec 21 15:03:56 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 21 Dec 2008 21:03:56 +0100 Subject: Are Django/Turbogears too specific? In-Reply-To: References: Message-ID: <494eaee0$0$24527$426a34cc@news.free.fr> Gilles Ganault a ?crit : > Hi > > I'd like to rewrite a Web 2.0 PHP application in Python with AJAX, and > it seems like Django and Turbogears are the frameworks that have the > most momentum. > > I'd like to use this opportunity to lower the load on servers, as the > PHP application wasn't built to fit the number of users hammering the > servers now. > > I'm concerned, though, that these frameworks they may be too specific > to the tasks they were originally developped for (news articles, > AFAIK). Do you think I should just use eg. CherryPy and some basic > AJAX? I can't tell about Turbogears, but you're dead wrong if you think that there's anything specific to "news articles" in Django. It's *not* a CMS, it's a web programming framework, and is totally agnostic about what kind of application you're using it for. From cournape at gmail.com Wed Dec 10 09:43:32 2008 From: cournape at gmail.com (David Cournapeau) Date: Wed, 10 Dec 2008 23:43:32 +0900 Subject: How do I manually uninstall setuptools (installed by egg)? In-Reply-To: <47c890dc0812091904p12e75510sbe0b8858eb2f6d9e@mail.gmail.com> References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> <47c890dc0812091904p12e75510sbe0b8858eb2f6d9e@mail.gmail.com> Message-ID: <5b8d13220812100643pe688b9exefeaa13bdf589076@mail.gmail.com> On Wed, Dec 10, 2008 at 12:04 PM, Chris Rebert wrote: > On Tue, Dec 9, 2008 at 6:49 PM, wrote: >> On Ubuntu, I accidentally manually installed setuptools >> http://pypi.python.org/pypi/setuptools/0.6c9 (by running the .egg file >> as a shell script via sudo), and now realize I should just be using >> apt to take care of my system Python packages. > > Really, why? setuptools has more Python packages/programs available > and updates faster than Debian. > It's also likely that some of the Debian Python packages are installed > using setuptools anyway. > So, why do you think apt and not setuptools is The Right Way(tm)? Setuptools is certainly not the right way to install packages system-wide on debian, it is very likely to break the whole thing. dpkg is a real package installer, with uninstallation feature, correct dependency handling: if you start installing things with setuptools there, dpkg cannot know anymore how to manage your system. That's why it is generally a very bad idea to install things which are not managed by dpkg in /usr - be it python or something else BTW. It is a much better practice to install from source into /usr/local, or your $HOME, etc... Anywhere which is not /usr. David From deets at nospam.web.de Mon Dec 8 11:29:35 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 Dec 2008 17:29:35 +0100 Subject: Equivalent of 'wget' for python? References: Message-ID: <6q50bfFaqa0aU1@mid.uni-berlin.de> Robert Dailey wrote: > Hi, > > I'm looking for a portable way to download ZIP files on the internet > through Python. I don't want to do os.system() to invoke 'wget', since > this isn't portable on Windows. I'm hoping the core python library has > a library for this. Note that I'll be using Python 3.0. Module urllib2 Diez From bertilow at gmail.com Sat Dec 6 08:00:22 2008 From: bertilow at gmail.com (Bertilo Wennergren) Date: Sat, 06 Dec 2008 22:00:22 +0900 Subject: Learning Python now coming from Perl Message-ID: I'm planning to start learning Python now, using Python 3000. I have no previous Python skills, but I now Perl pretty well. I'm also well experienced with JavaScript. Any pointers and tips how I should go about getting into Python? -- Bertilo Wennergren From bthayre at physics.ucsd.edu Thu Dec 11 18:12:09 2008 From: bthayre at physics.ucsd.edu (Robocop) Date: Thu, 11 Dec 2008 15:12:09 -0800 (PST) Subject: list organization question Message-ID: I have a list of objects, each object having two relevant attributes: date and id. I'd like not only organize by id, but also by date. I.e. i would like to parse my list into smaller lists such that each new mini-list has a unique date, but consists of only objects with a specific id. Are there any handy imports i could use to accomplish something like this? I'm relatively new to python and as such don't know all of the preloaded functions at my disposal. Thanks for any help in advance, the community here is always ridiculously helpful. From bj_666 at gmx.net Fri Dec 12 09:08:28 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 12 Dec 2008 14:08:28 GMT Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> Message-ID: <6qf9irFc3a5jU3@mid.uni-berlin.de> On Fri, 12 Dec 2008 05:39:35 -0800, sturlamolden wrote: > On Dec 12, 2:34 pm, Hrvoje Niksic wrote: > >> >>> import numpy >> >>> t = (numpy.zeros(10),) >> >>> t >> >> (array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]),)>>> t[0] += >> 1 >> >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: 'tuple' object does not support item assignment >> >> Of course, the side effect occurs before the exception, so: >> >> >>> t[0] > >> array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) > > > Actually I would consider this to be a bug. The tuple is immutable, but > no mutation of the tuple is ever attempted. No bug because a mutation *is* attempted. ``a += x`` calls `a.__iadd__` which *always* returns the result which is *always* rebound to the name `a`. Even with mutable objects where `__iadd__()` simply returns `self`! It has to be this way because the compiler has no idea if the object bound to `a` will be mutable or immutable when the code actually runs. In [252]: def f(a, x): .....: a += x .....: In [253]: dis.dis(f) 2 0 LOAD_FAST 0 (a) 3 LOAD_FAST 1 (x) 6 INPLACE_ADD 7 STORE_FAST 0 (a) 10 LOAD_CONST 0 (None) 13 RETURN_VALUE Ciao, Marc 'BlackJack' Rintsch From prologic at shortcircuit.net.au Thu Dec 18 04:18:41 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 18 Dec 2008 19:18:41 +1000 Subject: importing csv file into sqlite In-Reply-To: <21068111.post@talk.nabble.com> References: <21067453.post@talk.nabble.com> <21068111.post@talk.nabble.com> Message-ID: @klia: You could have had this done hours ago had you taken my suggestion, used my tool and just piped it into sqlite3 on the command line. --JamesMills -- -- "Problems are solved by method" From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 8 03:26:18 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 08 Dec 2008 09:26:18 +0100 Subject: var or inout parm? In-Reply-To: References: Message-ID: <493cda2a$0$17080$426a34cc@news.free.fr> Colin J. Williams a ?crit : > mh at pixar.com wrote: >> How can I make a "var" parm, where the called function can modify >> the value of the parameter in the caller? >> >> def f(x): >> x = x + 1 >> >> n = 1 >> f(n) >> # n should now be 2 >> >> Many TIA!! >> Mark >> >> > > Why not run it and see? > > Your function returns None. > > The function in effect takes a copy of n. Nope, it takes the object bound to global name 'n'. From fakeaddress at nowhere.org Tue Dec 16 01:44:12 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 15 Dec 2008 22:44:12 -0800 Subject: socket and subprocess problem In-Reply-To: <73dca20d-3378-4c96-aa30-f0617f111fa0@i18g2000prf.googlegroups.com> References: <6d3291c3-4e12-4bdd-884a-21f15f38d105@a12g2000pro.googlegroups.com> <73dca20d-3378-4c96-aa30-f0617f111fa0@i18g2000prf.googlegroups.com> Message-ID: <37I1l.10065$yr3.8580@nlpi068.nbdc.sbc.com> goatold at gmail.com wrote: > Guys thanks to point it out. > Yes, it's a race problem. I tried sleep long enough, then I can > connect to the socket. I should add code to try to connect to the > socket for a given time out. As Roy noted, that's "the cheesy way". Are the kind of programmers who accept cheesy solutions? Of course not. The right solution is for the child process to tell the parent when the port is ready for connections. There are a variety of ways to transfer that message; the most straightforward is for the child process to write something to its standard output. Parent process: Launch child. read() child's output, waiting for the ready message. connect() to the port the child established. Child process: Create the socket; bind(); listen(). Write the ready message to stdout. accept(). There's a subtle yet important point here, that frequently gets lost: Roy Smith wrote: >> Sounds like a timing problem. I assume that the process started by a.run() >> creates a socket and does a bind/listen/accept sequence on it. The problem >> is, there's nothing in your code which guarantees that this happens before >> b.run() executes the connect() call. Actually, it's just bind() and listen() that have to happen before the client can connect(); accept() will not succeed until after a client connects. In our example the child process is the server, and the server's readiness alert should go after his call to listen() returns, but before he calls accept(). -- --Bryan From timr at probo.com Mon Dec 8 23:28:03 2008 From: timr at probo.com (Tim Roberts) Date: Tue, 09 Dec 2008 04:28:03 GMT Subject: pretty strange behavior of "strip" References: <4938693F.6090709@yahoo.ca> Message-ID: Guy Doune wrote: >Ok, didn't show the whole problem... > >I will read the doc anyway, but why "questions.html" keep it "t"?? > > >>> test=['03.html', '06.html', 'questions.html', '04.html', >'toc.html', '01.html', '05.html', '07.html', '02.html', '08.html'] > >>> test[4] >'toc.html' > >>> test[4].strip('.html') >'oc' > >>> test[2].strip('.html') >'questions' Because it removes any periods, h's, t's, m's, or l's at the beginning or ending of the string. That "t" is in the middle. In this case, the stripping stopped at the "q" and the "s". -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From fakeaddress at nowhere.org Fri Dec 12 22:51:13 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 12 Dec 2008 19:51:13 -0800 Subject: Bidirectional Networking In-Reply-To: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> Message-ID: Emanuele D'Arrigo wrote: > All the examples though are based on a client interrogating a server, > with the client initiating the connection, obtaining something and > then closing the connection. Basically the server is a reactive party: > only if the client get in touch the server respond. Indeed, to the network programmer that pattern of interaction defines client/server (according to Douglas Comer's /Internetworking with TCP/IP). > What if the server > wanted to notify the client of something of interest, i.e. new data > that the client should take into consideration and potentially > process? The "server push" problem. > One option would be for the client to periodically poll the server for > changes. Fair enough, that would work. But it'd be a bit of a waste if > the changes aren't particularly frequent. Implementing server push on top of client poll is the most popular and generally simplest option. > Is it possible then to establish both a server and a client in the > same application? Possible, and not all that hard to program, but there's a gotcha. Firewalls, including home routers and software firewalls, typically default to disallowing connections in the 'wrong' direction. If the client initiates all connections, you avoid a world of hassles. > I guess it must be possible but the examples all > rely on some kind of server loop (i.e. SocketServer.serve_forever) > that if started on both client and server sides would create two > listening parties but no talking at all! Furthermore, other libraries > might have their own loop, i.e. a graphical client has a loop to > redraw the screen and the two loops would somehow have to be > interleaved. > > I'm not quite seeing how this can be done other than we threads. Is > that the way to do it? Place the listening loop in a thread while the > rest of the application does its own thing? Threads work. Other options in Python standard library are 'select' and 'asyncore', but these do not play well with SocketServer and its descendants. There are also other free Python libraries. > Or is it SocketServer.handle_request() the key? I could call this > function periodically, but what happens if a request is made while the > application is doing something else? Are the requests queued and dealt > with one per loop? Requests are queued up, but the queue is small. SocketServer is built on top of 'socket', which has the list() and accept() calls to create the queue and get connections from it, respectively. The traditional listen queue size, and sometimes the system maximum, is 5. If you want to use SocketServer, read about ThreadingMixIn and ForkingMixIn. -- --Bryan From paul at boddie.org.uk Fri Dec 5 06:15:31 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 5 Dec 2008 03:15:31 -0800 (PST) Subject: using distutils to cross-compile extensions? References: <49385CBB.7060207@cs.cornell.edu> Message-ID: <012fa025-e12a-4c83-b81f-55bce905afe4@d23g2000yqc.googlegroups.com> On 5 Des, 00:58, "David Cournapeau" wrote: > > The first step for cross compilation would be the ability to build > python itself wtih different build/host, and that's already non > trivial. Now that Python 3.0 is out, perhaps there will be a possibility of one of the many cross-compilation patches being applied to Python 2.x: http://bugs.python.org/issue?%40columns=id%2Cactivity%2Ctitle%2Ccreator%2Cassignee%2Cstatus&%40sort=-activity&%40group=priority&%40filter=status&status=-1%2C1%2C3&%40search_text=cross-compile&submit=search+in+open+issues Paul From steve at REMOVE-THIS-cybersource.com.au Sun Dec 7 18:20:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 23:20:12 GMT Subject: Rich Comparisons Gotcha References: Message-ID: <014c51d9$0$20670$c3e8da3@news.astraweb.com> On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: > Rasmus Fogh wrote: > >> Current behaviour is both inconsistent and counterintuitive, as these >> examples show. >> >>>>> x = float('NaN') >>>>> x == x >> False > > Blame IEEE for that one. Rich comparisons have nothing to do with that > one. There is nothing to blame them for. This is the correct behaviour. NaNs should *not* compare equal to themselves, that's mathematically incoherent. -- Steven From trentm at activestate.com Mon Dec 1 13:33:02 2008 From: trentm at activestate.com (Trent Mick) Date: Mon, 01 Dec 2008 10:33:02 -0800 Subject: Debugging in Python In-Reply-To: <4931DC60.5070705@Acm.Org> References: <38a89d61-9dfd-491c-b9dc-946709eec8c7@v42g2000yqv.googlegroups.com> <4931DC60.5070705@Acm.Org> Message-ID: <49342DDE.2060604@activestate.com> Scott David Daniels wrote: > Stef Mientki wrote: >> .... I'm not completely satisfied with even the "best" debuggers, >> most of the good ones are too difficult, >> so I want to wrap rpdb2 and >> don't want to miss any great features ;-) > > I think ActiveState has a free 21-day trial, so you could check it out > yourself if you are willing to spend the concentrated time to check it > out. That is correct. Also the Python debugging docs are here, if that might help: http://docs.activestate.com/komodo/5.0/debugpython.html > Their license terms are reasonable (the license is attached to _you_, > not a particular machine you run it on, as I remember. Also correct: with a Komodo IDE license you can use Komodo on any machine that you use. Trent -- Trent Mick trentm at activestate.com From __peter__ at web.de Fri Dec 19 05:32:28 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2008 11:32:28 +0100 Subject: importing csv file into sqlite References: <21067453.post@talk.nabble.com> Message-ID: James Mills wrote: > values = ",".join(["\"%s\"" % x for x in line]) > print "INSERT INTO %s %s VALUES (%s);" % (table, fields, values) http://xkcd.com/327/ From jcd at sdf.lonestar.org Thu Dec 18 15:40:36 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Thu, 18 Dec 2008 15:40:36 -0500 Subject: Factoring Polynomials In-Reply-To: <5dfe1cf3-530d-4e31-833e-e26db85611be@d36g2000prf.googlegroups.com> References: <5dfe1cf3-530d-4e31-833e-e26db85611be@d36g2000prf.googlegroups.com> Message-ID: <1229632836.10976.3.camel@aalcdl07.lib.unc.edu> On Thu, 2008-12-18 at 11:52 -0800, eric wrote: > On Dec 18, 8:37 pm, collin.da... at gmail.com wrote: > > I am trying to write a simple application to factor polynomials. I > > wrote (simple) raw_input lines to collect the a, b, and c values from > > the user, but I dont know how to implement the quadratic equation > > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > > into python. Any ideas? > > with numpy: > from numpy import * > > s=[1,-1] > x = -b+s*sqrt( b**2-4*a*c )/(2*a) > > Eric Without the Nump. def polynomial(a, b, c): N = ((b**2 - 4*a*c)**.5) / 2*a return (-b + N, -b - N) From gamersunit at gmail.com Fri Dec 5 17:41:08 2008 From: gamersunit at gmail.com (Gregory Plantaine) Date: Fri, 5 Dec 2008 14:41:08 -0800 (PST) Subject: Find Files in a Folder Between 2 Dates References: <4c54b6c5-ae4d-4b89-8c6d-940c96de29bb@n33g2000pri.googlegroups.com> Message-ID: <94cd4bd7-a69f-48ba-90f7-382014844905@g1g2000pra.googlegroups.com> That worked perfectly! Thanks Tim! Since we can print the files, does that mean the list of files is in a tuple, or something? Would there be a way to further split up the file names? For example, now that the files are processed into the list, we want to look through that list to find different filetypes. files C:\Folder\File_200812051439.111 C:\Folder\File_200812051539.222 Can we split up .111 files? Actually, where would I look something like this up? From duncan.booth at invalid.invalid Mon Dec 8 04:10:35 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 Dec 2008 09:10:35 GMT Subject: how to get a beep, OS independent ? References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> Message-ID: Joe Strout wrote: > But invoking the standard system beep is such a basic function that it > ought to be easier than this. I'm pretty sure it's a single OS call > on all platforms. On OS X, for example, it's > > void NSBeep(void); > > declared in NSGraphics.h. I'm sure it's something similarly simple on > other platforms. I think what you're missing is a definition for 'the standard system'. If I'm logged in to one of my servers in a large datacentre then I don't what that system to beep as that would be pretty useless. I want the system I'm logged in with to do the beeping. For some systems and some types of login (e.g. Microsoft's Remote Desktop) then remoting the sound output isn't a problem, but I might just be logged in with SSH and in that case the only option available is to send some escape sequence to the user's terminal. Traditionally generation of escape sequences for a user's terminal is something done by the application, not a function of the operating system. I think that's why you'll find there will be a variety of ways to generate beeps, squeaks and squawks if you are using a gui (only as with all other gui functions there is no common ground between different systems), but nothing beyond '\a' for terminals. -- Duncan Booth http://kupuguy.blogspot.com From jstroud at mbi.ucla.edu Sat Dec 6 22:15:12 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 06 Dec 2008 19:15:12 -0800 Subject: operators as variables In-Reply-To: References: <103920.71204.qm@web26006.mail.ukl.yahoo.com> Message-ID: > macc_200 wrote: >> Hi, >> just starting programming and have an elementary question after >> playing around with lists but cannot find the answer with googling. >> I have a list of variables and I would like some of those variables to >> be integers and some to be operators so the list would look something >> like [5 * 4 - 4 + 6] and then be able to evaluate the result (i.e. get >> 10). How do you make the interpreter see the operator as that instead >> of a string and just echo the list back to me. Your specification is ambiguous because you mention lists but wrote an evaluable expression inside of brackets. Others have answered the question you probably really are asking. For fun, though, I'm going to pretend you meant "list" and not whatever [5 * 4 - 4 + 6] is: import operator opdict = {'+' : operator.add, '-' : operator.sub, '*' : operator.mul, '/' : operator.div} def take_two(aniterable): assert len(aniterable) % 2 == 0 aniter = iter(aniterable) while True: try: yield aniter.next(), aniter.next() except StopIteration: break def reductifier(alist): value = alist.pop(0) for op, operand in take_two(alist): value = opdict[op](value, operand) return value reductifier([5, "*", 4, "-", 4, "+", 6]) From org.python.python-list at pooryorick.com Fri Dec 12 16:52:52 2008 From: org.python.python-list at pooryorick.com (=?utf-8?Q?Poor=20Yorick?=) Date: Fri, 12 Dec 2008 21:52:52 +0000 Subject: =?utf-8?B?X19mdXR1cmVfXyBhbmQgdW5yZWNvZ25pc2VkIGZsYWdz?= Message-ID: <20081212215252.18112.qmail@s461.sureserver.com> I have a future statement in a script I intend to work on 2.6 and 3. Shouldn't __future__ statements basically be noops for versions that already support the feature? doctest is complaining about compiler flags. This illustrates the problem: Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> from __future__ import unicode_literals >>> src = 'a = "hello"' >>> c1 = compile(src,'','exec',unicode_literals.compiler_flag) Traceback (most recent call last): File "", line 1, in ValueError: compile(): unrecognised flags -- Yorick From jcd at sdf.lonestar.org Tue Dec 16 11:50:34 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 16 Dec 2008 11:50:34 -0500 Subject: alt.possessive.its.has.no.apostrophe In-Reply-To: <000901c95f69$003a5f00$0d00a8c0@hendrik> References: <87vdtmf0mu.fsf_-_@benfinney.id.au> <87r649g9dg.fsf@benfinney.id.au> <9ImdneOohuZCNdvUnZ2dnUVZ_s3inZ2d@earthlink.com> <000901c95f69$003a5f00$0d00a8c0@hendrik> Message-ID: <1229446234.8781.9.camel@aalcdl07.lib.unc.edu> On Tue, 2008-12-16 at 12:27 +0200, Hendrik van Rooyen wrote: > "Dennis Lee Bieber" wrote: > > 8<----- stuff blaming Davy for "aluminum" ---------- > > > Isn't Davy a Brit? > > No, he was a Brit. > He's dead now. > His safety lamp lives on. > It's a good thing its got that heat-sink sieve- > it's enabled countless miners > to flee when they see its change of colour. > Thus it's saved the lives of a lot of canaries, > and that's of ecological importance. > > Spot the apostrophe error, if you can. > > - Hendrik > It's a good thing *its* got that heat-sink sieve- its -> it has Cheers, Cliff From rt8396 at gmail.com Mon Dec 22 17:07:34 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 14:07:34 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <6ra8t0F925rU1@mid.individual.net> <29feda0d-6432-4cb9-8809-e4d4a7798601@e1g2000pra.googlegroups.com> <6raeb8F9s47U2@mid.individual.net> Message-ID: On Dec 22, 3:15?pm, je.s.t... at hehxduhmp.org wrote: > r wrote: > > We see where you stand. And also see that by removing your comments > > from the archive in 5 days, how small your acorns really are. > > Also, it is pretty hard to take such accusations seriously from someone > who themselves is using a generic gmail address w/o their real name > attached to it. ?If I didn't care about using a proper NNTP client, I > could quite easily create some dufus account on Gmail and post through > that just like you did - I'm sure that'd really increase my credibility! Would you trust my words more if i used a name like "Thurstan Howell III".... Come on, don't tell me you are that shallow. To attack my credibility solely based on my user name is the sport of small minded people. Surely you can bring more thought, and intelligence to this thread than that?... From rlight2 at gmail.com Wed Dec 24 10:42:38 2008 From: rlight2 at gmail.com (Ross) Date: Wed, 24 Dec 2008 07:42:38 -0800 (PST) Subject: Custom C Exception Subclasses Message-ID: <41f291ff-d7bd-4334-8689-636e95524cdc@b38g2000prf.googlegroups.com> For a project that I am doing, it would be useful to have an exception class that stores some additional data along with the message. However, I want to be able to store a couple pointers to C++ classes, so I can't just use an exception created with PyExc_NewException. If I were to subclass the built-in Exception type, I would need to have access to the PyExc_ExceptionObject, but the headers only give PyExc_Exception, the type object. This seems like a rather straightforward task, but I can't seem to find any documentation for it. Does anyone know how to do this? Thanks! From pxrepreza at gmail.com Tue Dec 23 01:19:21 2008 From: pxrepreza at gmail.com (Paulo Repreza) Date: Mon, 22 Dec 2008 22:19:21 -0800 Subject: String Format Error. Message-ID: Hi, I'm a newbie with python and I recently bought Beginning with Python (Which is a book I recommend) but the problem that I'm facing it's the following: *This is the code: * #!/usr/bin/python2.5 # Filename: str_format.py age = 25 name = 'foobar' print('{0} is {1} years old'.format(name, age)) print('Why is {0} playing with that python?'.format(name)) *But when I run the script I receive this error: *Traceback (most recent call last): File "str_format.py", line 7, in print('{0} is {1} years old'.format(name, age)) AttributeError: 'str' object has no attribute 'format' It is an error because of the version that I'm using ? Python 2.5.2 (Debian lenny) Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lewis.sarah93 at yahoo.com Fri Dec 5 00:02:41 2008 From: lewis.sarah93 at yahoo.com (Lizzy) Date: Thu, 4 Dec 2008 21:02:41 -0800 (PST) Subject: Earn More Money Message-ID: <8d38f89d-cd44-46f7-869c-4209b16a3a0c@d14g2000yqb.googlegroups.com> Burnt Out Ex-Factory Worker Rakes In $253,877.33 in 90 days from home.Now he's showing people all across america how to generate between $5,ooo -$10,000 a wek right from home with his Instance Incom Plan Will You be next?http://www.dollarsquickmoneyincome.com From bearophileHUGS at lycos.com Mon Dec 22 14:22:02 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 22 Dec 2008 11:22:02 -0800 (PST) Subject: 64-bit / 128-bit data element type for array? References: Message-ID: akineko: > I need to handle binary files that contain 64-bit (or 128-bit in the > furture) unsigned int data. > Python's array seems not supporting unsigned int type beyond 32-bit > ('L'). I agree that it can be useful for the built-in array module to grow signed/unsigned 64 bit numbers. Numpy supports signed/unsigned 64 bit numbers too, so that may be enough for you: http://docs.scipy.org/doc/numpy/user/basics.types.html Regarding 128-bit numbers you may have to support them manually, with pairs of uint64, with numpy. They aren't much common yet. (D language will have cent/ucent 128 bit integral numbers, but it's not a common thing). Bye, bearophile From arnodel at googlemail.com Mon Dec 8 15:55:16 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 08 Dec 2008 20:55:16 +0000 Subject: Guido's new method definition idea References: <014a071a$0$20670$c3e8da3@news.astraweb.com> <0ae03437-77fc-42c4-bc94-1259b353a676@j32g2000yqn.googlegroups.com> Message-ID: anthony.tolle at gmail.com writes: > class C: > def createfunc(self): > def self.func(arg): > return arg + 1 > > Or, after the class definition is done, to extend it dynamically: > > def C.method(self, arg): > self.value = arg > > ...which would be the equivalent of the following: > > def method(self, arg): > self.value = arg > C.method = method What about the following then? functions = {} def functions['square'](x): return x*x def functions['cube'](x): return x**3 -- Arnaud From the.brown.dragon.blog at gmail.com Mon Dec 15 02:46:30 2008 From: the.brown.dragon.blog at gmail.com (the.brown.dragon.blog at gmail.com) Date: Sun, 14 Dec 2008 23:46:30 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <86bf2e29-5f8d-4349-94cf-d1561f0114e6@e1g2000pra.googlegroups.com> <7454a7ef-ec19-4d7c-986b-d56c3ed8111b@i24g2000prf.googlegroups.com> <6a8f2eef-43e1-4a99-ae41-e4c90e6130e7@x38g2000yqj.googlegroups.com> <49404775$0$4893$607ed4bc@cv.net> <91bf5d87-0154-472b-9350-e3290ab867e1@k1g2000prb.googlegroups.com> <49a1717b-36f0-402c-a633-a7df23dca0bf@35g2000pry.googlegroups.com> Message-ID: <7bc8cd81-e35c-443d-a8fa-f5b0227a614d@a26g2000prf.googlegroups.com> On Dec 12, 12:12?am, Xah Lee wrote: > On Dec 11, 6:50 am, the.brown.dragon.b... at gmail.com wrote: > ;; Chicken Scheme. By the.brown.dragon... at gmail.com > (require 'srfi-1) > (define (normalize vec) > ? (map (cute / <> (sqrt (reduce + 0 (map (cute expt <> 2) vec)))) > vec)) > > Is it possible to make it work in scsh? (i'm running scsh 0.6.4, and > don't know Scheme lisp well) > > ? Xah > ?http://xahlee.org/ > > ? I don't have scsh but yes - it should work fine. "cute" is an SRFI (http://srfi.schemers.org/srfi-26/) which should be available. cheers, BD From george.sakkis at gmail.com Thu Dec 4 17:02:45 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 4 Dec 2008 14:02:45 -0800 (PST) Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> <20081204204525.414db889@usenot.de> Message-ID: <3dd9addc-9121-496d-b775-12437d32097b@l33g2000pri.googlegroups.com> On Dec 4, 4:49?pm, s... at pobox.com wrote: > ? ? Andreas> Whenever has it been a pythonic ideal to "not allow" stuff? You > ? ? Andreas> get warnings. Everything else is up to you. > > It's more than warnings. ?With properly crafted combinations of spaces and > tabs you can get code which looks like it has a certain indentation to the > human observer but which looks like it has different indentation (and thus > different semantics) to the byte code compiler. ?There is often no warning. Amazing.. was it a conscious decision to keep the current behavior in 3.x or it was not even considered dropping it ?? Does anyone have a link where this was decided ? George From bearophileHUGS at lycos.com Thu Dec 4 11:32:05 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 4 Dec 2008 08:32:05 -0800 (PST) Subject: RELEASED Python 3.0 final References: <9c07470d-32c8-4db8-96c4-937c1032bf62@x38g2000yqj.googlegroups.com> Message-ID: <094d0e65-e3bc-4648-b81d-7c3085b6edef@k19g2000yqg.googlegroups.com> Gerhard H?ring: > As you have probably guessed: nothing changed here. > Also see:http://www.python.org/dev/peps/pep-0666/ What? Do you mean it's possible to mix tabs and spaces still? Why? Bye, bearophile From nabla.kvadrat at gmail.com Thu Dec 11 02:12:08 2008 From: nabla.kvadrat at gmail.com (Nabla Kvadrat) Date: Thu, 11 Dec 2008 08:12:08 +0100 Subject: multiprocessing+simplehttpserver+windows In-Reply-To: References: Message-ID: Additional information: complete traceback: Serving at http://localhost:8000 using 2 worker processes To exit press Ctrl-Break Traceback (most recent call last): File "C:\workspaces\workspace\skrserver-multiprocess\src\t.py", line 70, in test() File "C:\workspaces\workspace\skrserver-multiprocess\src\t.py", line 65, in test runpool(ADDRESS, NUMBER_OF_PROCESSES) File "C:\workspaces\workspace\skrserver-multiprocess\src\t.py", line 49, in runpool Process(target=serve_forever, args=(server,)).start() File "C:\Python26\lib\multiprocessing\process.py", line 104, in start self._popen = Popen(self) File "C:\Python26\lib\multiprocessing\forking.py", line 239, in __init__ dump(process_obj, to_child, HIGHEST_PROTOCOL) File "C:\Python26\lib\multiprocessing\forking.py", line 162, in dump ForkingPickler(file, protocol).dump(obj) File "C:\Python26\lib\pickle.py", line 224, in dump self.save(obj) File "C:\Python26\lib\pickle.py", line 331, in save self.save_reduce(obj=obj, *rv) File "C:\Python26\lib\pickle.py", line 419, in save_reduce save(state) File "C:\Python26\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python26\lib\pickle.py", line 649, in save_dict self._batch_setitems(obj.iteritems()) File "C:\Python26\lib\pickle.py", line 681, in _batch_setitems save(v) File "C:\Python26\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python26\lib\pickle.py", line 548, in save_tuple save(element) File "C:\Python26\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python26\lib\pickle.py", line 725, in save_inst save(stuff) File "C:\Python26\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python26\lib\pickle.py", line 649, in save_dict self._batch_setitems(obj.iteritems()) File "C:\Python26\lib\pickle.py", line 681, in _batch_setitems save(v) File "C:\Python26\lib\pickle.py", line 331, in save self.save_reduce(obj=obj, *rv) File "C:\Python26\lib\pickle.py", line 419, in save_reduce save(state) File "C:\Python26\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python26\lib\pickle.py", line 649, in save_dict self._batch_setitems(obj.iteritems()) File "C:\Python26\lib\pickle.py", line 681, in _batch_setitems save(v) File "C:\Python26\lib\pickle.py", line 331, in save self.save_reduce(obj=obj, *rv) File "C:\Python26\lib\pickle.py", line 419, in save_reduce save(state) File "C:\Python26\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python26\lib\pickle.py", line 649, in save_dict self._batch_setitems(obj.iteritems()) File "C:\Python26\lib\pickle.py", line 681, in _batch_setitems save(v) File "C:\Python26\lib\pickle.py", line 313, in save (t.__name__, obj)) pickle.PicklingError: Can't pickle 'lock' object: Traceback (most recent call last): File "", line 1, in File "C:\Python26\lib\multiprocessing\forking.py", line 342, in main self = load(from_parent) File "C:\Python26\lib\pickle.py", line 1370, in load return Unpickler(file).load() File "C:\Python26\lib\pickle.py", line 858, in load dispatch[key](self) File "C:\Python26\lib\pickle.py", line 1133, in load_reduce value = func(*args) File "C:\Python26\lib\multiprocessing\reduction.py", line 167, in rebuild_socket _sock = fromfd(fd, family, type_, proto) File "C:\Python26\lib\multiprocessing\reduction.py", line 156, in fromfd s = socket.fromfd(fd, family, type_, proto) AttributeError: 'module' object has no attribute 'fromfd' -------------- It seems that patch is available http://bugs.python.org/issue1378 but not yet applied on the Windows latest release. I have no environment to build it from source with this patch (in addition, I don't even know how :-)) Thanks for any help. On Thu, Dec 11, 2008 at 6:55 AM, Nabla Kvadrat wrote: > Hi, can someone please help me with/explain if following problem can > be somehow resolved? > > I have Py2.6.1 win32 and I'm playing around with multiprocessing > module. Trying examples here: > http://docs.python.org/library/multiprocessing.html#examples. Example > with SimpleHTTPServer.HttpServer don't work because of socket.fromfd > in multiprocessing.reduction. If number of processes is >1 it ends > with traceback ....... pickle.: 'module' object has no attribute > 'fromfd'. > As I understand socket.fromfd on windows is not implemented (?), so > why the example script is care about platform > if sys.platform == 'win32': > import multiprocessing.reduction > and finally, is there some easy (no patching and recompiling python > from source) way to get this example to work on win32 platform? > Thanks for any help, I'm Python amateur... > N. > From eduardo.padoan at gmail.com Thu Dec 4 06:25:50 2008 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Thu, 4 Dec 2008 09:25:50 -0200 Subject: "as" keyword woes In-Reply-To: References: Message-ID: On Thu, Dec 4, 2008 at 7:44 AM, James Stroud wrote: > alex23 wrote: >> >> On Dec 4, 3:42 pm, "Warren DeLano" wrote: >>> >>> So you prefer broken code to broken rules, eh? Your customers must love >>> that! This is exactly the kind of ivory-tower thinking I feared might >>> be behind the decision (form over function, damn the users to hell, >>> etc.) >> >> Really? I find that believing something should remain static at the >> expense of actual improvement to the language is far more 'ivory-tower >> thinking' than embracing change. > > First, to quote Tim Peters, "practicality beats purity." Second, I might be > biased here because I happen to know Warren, but, although he hails from the > ivory tower, I imagine his concerns are purely practical. His contributions > to software in structural biology are legendary. > >>> Am I the only one picking up on the irony here? "as" exists largely to >>> provide a mechanism for working around namespace conflicts -- except, >>> apparently, conflicts involving "as". The fact that "as" itself creates >>> an insurmountable namespace collision is just killing me! How absurd. >> >> Speaking of irony, you're complaining about namespace conflicts with a >> -two character identifier- you've chosen. Here's a hint: choose better >> names. > > The name fit his needs until changes in the language broke the name. If a > name works and the code works, then the name is good enough. And speaking as > a professional user of his software at the level of the application and at > the level of the API, let me tell you his code works pretty damn good. > >>> But to be brutally honest...in this many-core world we must all accept >>> and deal with today, it is hard to imagine how a non-multithreaded AND >>> non-backwards compatible Python implementation can have much of a life >>> ahead of it, with or without an "as" keyword. I do sincerely hope I am >>> wrong about this, but it is seems quite possible that C/Python's glory >>> days are now behind us. >> >> To match your honesty, I'm somewhat tired with the trend of some >> people to hit -one- issue with Python and suddenly lash out like >> children over all the same old tired crap. Have you even looked at >> multiprocessing? Have you contributed to any projects working on GIL- >> less implementations? Or are you just regurgitating the same bullet >> points we've heard time and time again? >> >> For chrissake, if you cannot do ANYTHING but BITCH about a change, >> then you've no damn right to consider yourself a programmer. Real >> programmers find solutions, not excuses. > > Correction: Real programmers write programs. And no, at this point he can't > do anything but complain because, as others have noted, the change is not > going away. > >>> And if so, then thank you all for so many wonderful years of effort and >>> participation! >> >> You're welcome. Don't let the door hit you on the ass on your way out. > > You probably aren't a developer for the cPython implementation, but, if you > were, I'd recommend taking rants like Warren's to heart because they are > born of honest frustration and practical concern. Hopefully developers for > python 2.7 are listening and won't break backward compatibility just because > the "Zen of Python" suggests it might be a good idea. Even I, who am not, by really far, legendary on anything, could give my 2? one time or another on python-dev or python-ideas. If you really care and think you have a good argument, I'm sure you are welcome to post there! But they cant hold the release until everyone in the world have voiced his concerns, its just not pratical. -- Eduardo de Oliveira Padoan http://djangopeople.net/edcrypt/ "Distrust those in whom the desire to punish is strong." -- Goethe, Nietzsche, Dostoevsky From steve at REMOVE-THIS-cybersource.com.au Fri Dec 19 21:25:37 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2008 02:25:37 GMT Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> Message-ID: <015c4ef2$0$20656$c3e8da3@news.astraweb.com> On Fri, 19 Dec 2008 16:05:42 -0800, Scott David Daniels wrote: > Ah, but for internationalization, you can change the format string to > take args in a different order if, for example, French messages want > modifiers on one side and English on the other. The code can stay the > same, while only the text used to do the formatting must change. I can't see how this is any different between what we have now. Here's an example using keyword arguments: # untested "{modifier} {noun}".format(modifier="dead", noun="parrot") "{noun} {modifier}".format(modifier="mort", noun="perroquet") compared to: "%(modifier)s %(noun)s" % dict(modifier="dead", noun="parrot") "%(noun)s %(modifier)s" % dict(modifier="mort", noun="perroquet") Whether using % or format(), I don't see the need to change the code, only the strings. Using positional arguments is not really that different: "{0} {1}".format("dead", "parrot") "{0} {1}".format("perroquet", "mort") versus: "%s %s" % ("dead", "parrot") "%s %s" % ("perroquet", "mort") In this case, the template on the left remains the same, you just have to reorder the string arguments on the right. Clearly less satisfactory than the solution using keyword substitution, but whatever solution you pick, I don't see any advantage to format() over % formatting. Can you show an example? -- Steven From sjmachin at lexicon.net Tue Dec 2 19:14:46 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 2 Dec 2008 16:14:46 -0800 (PST) Subject: Reverse zip() ? References: <20081202210930.2ac88ec6@usenot.de> <493596A3.4010306@behnel.de> Message-ID: On Dec 3, 7:12?am, Stefan Behnel wrote: > Andreas Waldenburger wrote: > > we all know about the zip builtin that combines several iterables into > > a list of tuples. > > > I often find myself doing the reverse, splitting a list of tuples into > > several lists, each corresponding to a certain element of each tuple > > (e.g. matplotlib/pyplot needs those, rather than lists of points). > > > This is of course trivial to do via iteration or listcomps, BUT, I was > > wondering if there is a function I don't know about that does this > > nicely? > > I think you're asking about zip(): > > ? ? ? ? >>> l=[1,2,3] > ? ? ? ? >>> zip(l,l) > ? ? ? ? [(1, 1), (2, 2), (3, 3)] > ? ? ? ? >>> zip(*zip(l,l)) > ? ? ? ? [(1, 2, 3), (1, 2, 3)] > Here's a version that makes it slightly easier to comprehend: Q: I know how to zip sequences together: | >>> a = (1, 2, 3) | >>> b = (4, 5, 6) | >>> z = zip(a, b) | >>> z | [(1, 4), (2, 5), (3, 6)] but how do I reverse the process? A: Use zip()! | >>> a2, b2 = zip(*z) | >>> a2 | (1, 2, 3) | >>> b2 | (4, 5, 6) Cheers, John From bblais at bryant.edu Sun Dec 7 15:29:02 2008 From: bblais at bryant.edu (Brian Blais) Date: Sun, 7 Dec 2008 15:29:02 -0500 Subject: Python for kids? In-Reply-To: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> References: <6236eeab-2a2f-4ac0-bf4f-70c2df800209@a37g2000pre.googlegroups.com> Message-ID: <2BDBC492-A75B-4F79-86E9-414EA521A80B@bryant.edu> On Dec 7, 2008, at 15:13 , Russ P. wrote: > I have a 12-year-old son who spends too much time playing Xbox live > and watching silly YouTube videos. I would like to try to get him > interested in programming. Is anyone aware of a good book or website check out: http://www.briggs.net.nz/log/writing/snake-wrangling-for-kids/ it's specifically for Python, and geared for the age of your son. bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais From manatlan at gmail.com Mon Dec 8 08:20:50 2008 From: manatlan at gmail.com (manatlan) Date: Mon, 8 Dec 2008 05:20:50 -0800 (PST) Subject: Python and audio frequency analysis Message-ID: I'd like to make a kind of "spectrum analyzer" ... Which should display "bars" according bands of frequencies ... in real time... Is anybody know an audio processing lib in python for that ? From jfmoreno at gitanosoftware.com Wed Dec 10 13:09:49 2008 From: jfmoreno at gitanosoftware.com (JFMoreno) Date: Wed, 10 Dec 2008 10:09:49 -0800 (PST) Subject: Jewel of the Week: Sterling Icon Collection just $39 Message-ID: Add a touch of class to your projects with this beautiful icon collection. 262 gorgeous icons for a total of 14934 files in +540mg that will make all your projects shine (Application, Website, Gadget, Game, Desktop, etc.). The collection includes 9 sizes: 16x16, 24x24, 32x32, 48x48, 64x64, 72x72, 96x96, 128x128, and 256x256 Included as well 7 formats: Windows ICO, PSD, PNG, JPG, BMP, GIF and Mac ICNS Previously sold for$149, this week only you can get this jewel for just $39 BUY NOW (secure): https://www.1stlogodesign.com/secure/orders/jeweloftheweek.htm Preview the entire collection: http://www.1stlogodesign.com/core/docs/sterlingiconcollection.pdf Download a sample: http://www.1stlogodesign.com/core/downloads/1stIDSterling.zip Compare our collection to identical quality collections from other vendors and you will find that you get: ? More Icons ? In some cases four times more icons. ? More sizes ? 9 different sizes from 16x16 to 256x256 ? More formats ? Our collection includes, PNG,PSD, JPG, BMP, GIF, ICO and ICNS formats ? Better quality ? Our icons are not cartoonish and therefore your project will look more professional ? More FREE updates ? FREE for LIFE! Would you like to receive notifications about our fantastic offers, last minute low-price deals and new releases? Join our newsletter: https://www.1stlogodesign.com/forms/newsletter.htm From fetchinson at googlemail.com Sat Dec 13 22:49:36 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 13 Dec 2008 19:49:36 -0800 Subject: 1 or 1/0 doesn't raise an exception In-Reply-To: <49446E39.6020807@tim.thechases.com> References: <49446E39.6020807@tim.thechases.com> Message-ID: >> Is it a feature that >> >> 1 or 1/0 >> >> returns 1 and doesn't raise a ZeroDivisionError? If so, what's the >> rationale? > > Yes, it's a feature: > > http://en.wikipedia.org/wiki/Short-circuit_evaluation > > When you have "True or False", you know it's true by the time > you've got the first piece, so there's no need to evaluate the > 2nd piece. The opposite is helpful too: > > lst = [some list or an empty list] > ... > if lst and lst[0] == 42: > > This ensures that the "lst[0]" doesn't fail if lst is empty, > because lst evaluating to false (an empty list) short-circuits > preventing the evaluation of "lst[0]". Okay, it's clear, thanks. Let me just point out that unsuspecting people (like me) might rely on the whole expression to be evaluated and rely on exceptions being raised if needed. So from now on I will not do! -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From rhf22 at mole.bio.cam.ac.uk Wed Dec 10 09:49:12 2008 From: rhf22 at mole.bio.cam.ac.uk (Rasmus Fogh) Date: Wed, 10 Dec 2008 14:49:12 +0000 (GMT) Subject: Rich Comparisons Gotcha Message-ID: Rhamphoryncus wrote: > You grossly overvalue using the "in" operator on lists. Maybe. But there is more to it than just 'in'. If you do: >>> c = numpy.zeros((2,)) >>> ll = [1, c, 3.] then the following all throw errors: 3 in ll, 3 not in ll, ll.index(3), ll.count(3), ll.remove(3) c in ll, c not in ll, ll.index(c), ll.count(c), ll.remove(c) Note how the presence of c in the list makes it behave wrong for 3 as well. > It's far more > common to use a dict or set for containment tests, due to O(1) > performance rather than O(n). I doubt the numpy array supports > hashing, so an error for misuse is all you should expect. Indeed it doees not. So there is not much to be gained from modifying equality comparison with sets/dicts. > In the rare case that you want to test for identity in a list, you can > easily write your own function to do it upfront: > def idcontains(seq, obj): > for i in seq: > if i is obj: > return True > return False Again, you can code around any particular case (though wrappers look like a more robust solution). Still, why not get rid of this wart, if we can find a way? --------------------------------------------------------------------------- Dr. Rasmus H. Fogh Email: r.h.fogh at bioc.cam.ac.uk Dept. of Biochemistry, University of Cambridge, 80 Tennis Court Road, Cambridge CB2 1GA, UK. FAX (01223)766002 From safe.girl1 at gmail.com Thu Dec 18 02:24:50 2008 From: safe.girl1 at gmail.com (safesexxxgirl) Date: Wed, 17 Dec 2008 23:24:50 -0800 (PST) Subject: ! hot lins freeeeee Message-ID: <286170c8-a71b-4fea-b22f-417bfd17fc30@k1g2000prb.googlegroups.com> ==> hot jokes free today http://adultjokes.tk http://adultjokes.tk ==> m2f m2m f2m m2m aunty srch http://sexxxsearch.tk http://sexxxsearch.tk ==> hot indian actress http://nudeactresses.tk http://nudeactresses.tk ==> hot vedios download free... http://hotmovies.co.nr http://hotmovies.co.nr ==> HOT C2C VOICE chat http://www.roleplaychat.co.cc http://www.roleplaychat.co.cc ==> hot dating girls mmm... http://www.hotdating.co.nr http://www.hotdating.co.nr ==> NEW INCOME/PENSION CALCULATOR http://6thpaycommission.tk http://6thpaycommission.tk ==> 1 CRORE SHARES FREE http://free-shares.tk http://free-shares.tk ==> MAKE FREE cash online... http://free-cash.tk http://free-cash.tk ==> win FREE GOLD TODAY... http://freegold4u.tk http://freegold4u.tk ==> free zodiac compatibility http://zodiacmatches.co.nr http://zodiacmatches.co.nr From arnodel at googlemail.com Fri Dec 19 17:51:18 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 19 Dec 2008 22:51:18 +0000 Subject: Generator slower than iterator? References: <62013718-57e9-4690-a2be-11e63b9c135b@u18g2000pro.googlegroups.com> Message-ID: MRAB writes: > Federico Moreira wrote: >> Great, 2min 34 secs with the open method =) >> >> but why? >> >> ip, sep, rest = line.partition(' ') >> match_counter[ip] += 1 >> >> instead of >> >> match_counter[line.strip()[0]] += 1 >> >> strip really takes more time than partition? >> >> I'm having the same results with both of them right now. >> > I think you meant split(), not strip(). > > split() might split the string into many parts, but you want only the > first part (at most 1 split), so the extra splits are unnecessary and > waste time. split(None, 1) and partition(' ') do at most 1 split, so > they don't do unnecessary work. Here's a very quick test: >>> timeit.Timer("a='fsdjflksjdf as fsd jkfl sdj'; b=a.partition(' ')[0]").timeit(5000000) 2.9831948280334473 >>> timeit.Timer("a='fsdjflksjdf as fsd jkfl sdj'; b=a[:a.find(' ')]").timeit(5000000) 3.0122888088226318 >>> timeit.Timer("a='fsdjflksjdf as fsd jkfl sdj'; b=a.split(None, 1)[0]").timeit(5000000) 4.5993850231170654 >>> timeit.Timer("a='fsdjflksjdf as fsd jkfl sdj'; b=a.split()[0]").timeit(5000000) 5.2067980766296387 So .split(None, 1) is quite a bit slower than .partition(' ') apparently. -- Arnaud From jstroud at mbi.ucla.edu Sat Dec 13 05:16:45 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 13 Dec 2008 02:16:45 -0800 Subject: Need help improving number guessing game In-Reply-To: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> References: <9HL0l.11344$ZP4.4490@nlpi067.nbdc.sbc.com> Message-ID: James Stroud wrote: > 1. Refactor. You should look at your code and see where you repeat the > same or similar patterns, see where they differ, make functions, and > make the differences parameters to the function call: > > def guess(player, p1score, p2score): > guess1 = int(input("\n>> ")) > if guess1 > 100: > print("ONLY NUMBERS FROM 1 TO 99") > elif guess1 > target: > print("TOO HIGH") > elif guess1 == target: > print("GOOD JOB, PLAYER %s! THE SCORE IS:" % player) > print("P1: %s --- P2: %s" % (p1score, p2score))) > print("PLAY AGAIN?") > #Set up the game again > play = int(input("0 TO END: ")) > if play == 0: > print("GOOD BYE. PLAY AGAIN SOON!") > quit() > else: > target = random.randint(1, 99) > else: > print("TOO LOW") I realized this has a bug. The target is locked in the scope of the function. I wouldn't use global, though: def guess(player, p1score, p2score): target = None guess1 = int(input("\n>> ")) if guess1 > 100: print("ONLY NUMBERS FROM 1 TO 99") elif guess1 > target: print("TOO HIGH") elif guess1 == target: print("GOOD JOB, PLAYER %s! THE SCORE IS:" % player) print("P1: %s --- P2: %s" % (p1score, p2score))) print("PLAY AGAIN?") #Set up the game again play = int(input("0 TO END: ")) if play == 0: print("GOOD BYE. PLAY AGAIN SOON!") quit() else: target = random.randint(1, 99) else: print("TOO LOW") Use it like this: new_target = gues(player, p1score, p2score) if new_target is not None: target = new_target I officially declare that I can't guarantee no more bugs in my previous post. I just fixed this one because my conscience was bothering me. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From martin at v.loewis.de Sat Dec 6 04:57:29 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sat, 06 Dec 2008 10:57:29 +0100 Subject: Running Python 2 and Python 3 on the same machine In-Reply-To: <1228539820.27659.21.camel@linux-3eb6.site> References: <1228424486.5873.6.camel@linux-3eb6.site> <49387f7e$0$27857$9b622d9e@news.freenet.de> <1228489547.5613.10.camel@linux-3eb6.site> <4939c6ef$0$6534$9b622d9e@news.freenet.de> <1228539820.27659.21.camel@linux-3eb6.site> Message-ID: <493A4C89.8070007@v.loewis.de> > Ok. I built the source on an openSUSE 11.0 system. I used 'sudo make > altinstll'. It created an executable /usr/local/bin/python3.0 file. > Nothing was touched in /usr/bin. Ah, then you missed the fun part. Take a look at the install: target in the Makefile. > I need to start writing some code with Python 3. I want to write the > code in such a way that it can be easily shared with others with the > least difficulty and overhead as possible. How should I write the code > to enable this? What, if anything, should I assume about another > system's configuration? I don't quite understand the problem. Sharing code is very easy over the internet. You can upload it on PyPI (say), or mail it. So you must be asking for something else. > As someone suggested before, naming the files as '.py3' is probably a > bad idea in the long run. It also does not really solve the problem. > > I could use a shebang. But, what should it specify? If I use > 'python3.0', then that will soon be quite old. If I make up a link for > python3 -> python3.0, that would work, but then every other system that > is to run the code must that link also. However, I am thinking that > this would be the best long term answer. Well, this will be rejected. It might be a good medium-term answer, but it is a *bad* long-term answer. In the long term, Python 2 will disappear, and we are stuck with calling the interpreter python3. > If I write scripts for Python 3, another developer writes scripts for > Python 2, and a common customer wants to install both of our packages > onto a single machine, then what is the best plan for everyone to make > that happen with as little difficulty as possible? My recommendation is to use distutils, for a long-term answer. People will run "python3.0 setup.py install", and distutils' install_scripts will replace the shebang line with the actual path to Python 3.0. This has not only the advantage of continuing to work for 3.1; it has also the advantage that scripts installed into a private location will be run by the correct interpreter (rather than relying on the interpreter being in /usr/bin, or on PATH). For "quick" sharing, the shebang line "#!/usr/bin/env python3.0" will be enough. When Python 3.1 gets released, you may find yourself writing scripts that run only on Python 3.x for x>=1 (i.e. won't run on 3.0, because you use a new feature in 3.1). In that case, presence of a python3 executable won't help, either. Regards, Martin From yinon.me at gmail.com Tue Dec 16 09:39:15 2008 From: yinon.me at gmail.com (Yinon Ehrlich) Date: Tue, 16 Dec 2008 06:39:15 -0800 (PST) Subject: ethical questions about global variables References: <0fa2d26e-1f08-4be4-89dd-7b5f0d0e604c@35g2000pry.googlegroups.com> Message-ID: <9b86455a-3b79-4a31-83cc-b3ef381f9248@o40g2000prn.googlegroups.com> On Dec 16, 4:45?am, "Giampaolo Rodola'" wrote: > Hi, > in a module of mine (ftpserver.py) I'd want to add a (boolean) global > variable named "use_gmt_times" to decide whether the server has to > return times in GMT or localtime but I'm not sure if it is a good idea > because of the "ethical" doubts I'm gonna write below. > > In first place I've never liked global variables too much and always > preferred per-class-instance variables instead. > The problem in my case is that I have to use such variable in two > separated classes: FTPHandler and VirtualFileSystem. Also, I want that > for no reason one class uses times in GMT and the other one local > times. > > Another doubt is the naming convention. PEP-8 states that global > variables should use the lower_case_naming_convention but I've seen a > lot of library module using the UPPER_CASE_NAMING_CONVENTION. What am > I supposed to do about it? > > Thanks in advance for any comment. > > --- Giampaolohttp://code.google.com/p/pyftpdlib/ Note also that PEP-8 states that "_single_leading_underscore... from M import *" does not import objects whose name starts with an underscore" From sjmachin at lexicon.net Fri Dec 19 08:58:57 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 19 Dec 2008 05:58:57 -0800 (PST) Subject: importing csv file into sqlite References: <21067453.post@talk.nabble.com> <7f64f5c6-b130-4f9b-a670-6b32eccba550@n33g2000pri.googlegroups.com> Message-ID: On Dec 19, 11:17?pm, klia wrote: [ancient screed snipped] > > hey guys > i took all of your suggestion but my goal ain't yet achieved :-(( > these are the codes after changes, john i couldn't really catch what do you > mean by renaming input, is it just normal renaming. Somebody else told you not to use "input", choose another name > i am testing the code on > just simple .csv file with few data in as follows before trying on my hug > csv file but still no joy > > "Bithday",12-05-08,"HTC","this is my birthday" > "Sea",12-03-08,"kodak","sea" > "girl","14-03-2009","samsung","birthday" > "love","17-04-2009","SONY","view of island" > > import sqlite3 > import csv > > f = open('/home/waseem/Project2/photos.csv') > input = csv.reader(f, delimiter=',') > conn = sqlite3.connect('/home/waseem/Project2/pictures.db') > curse = conn.cursor() > > curse.execute('CREATE TABLE photos (Name VARCHAR(100) PRIMARY KEY, Date > INTEGER, Make VARCHAR(50), Tag VARCHAR(100))') > for row in input: > ? ? ? ? curse.execute('INSERT INTO photos VALUES (?,?,?,?)', '*row') > curse.commit() > > this time i got this error > > waseem at Linux:~/Project2$ python experment.py > Traceback (most recent call last): > ? File "experment.py", line 12, in > ? ? curse.execute('INSERT INTO photos VALUES (?,?,?,?)', '*row') > sqlite3.IntegrityError: column Name is not unique > > i removed the primary key and single quotation mark for '*row' to just *row > but i got the old error which is > > waseem at Linux:~/Project2$ python experment.py > Traceback (most recent call last): > ? File "experment.py", line 11, in > ? ? curse.execute('INSERT INTO photos VALUES (?,?,?,?)', *row) > TypeError: function takes at most 2 arguments (5 given) > No, the old error was """sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 4, and there are 1 supplied.""" That's quite different. Secondly you have already been told about the difference between row and *row ... as the message says, it wants 2 arguments, (1) the SQL (2) the sequence of values that will be used to replace the ?s in the SQL. So just lose the *, OK? From rafesacks at gmail.com Mon Dec 1 05:29:55 2008 From: rafesacks at gmail.com (Rafe) Date: Mon, 1 Dec 2008 02:29:55 -0800 (PST) Subject: Best way to dynamically get an attribute from a module from within the same module References: Message-ID: <18097f03-dfc9-4671-954a-2871ca0c1910@d42g2000prb.googlegroups.com> > 3) using the bare name: > whatever > 1) and 2) are useful when the desired name is variable, not a constant like "whatever". I thought that went without saying. > > I have been using #1 for two reasons. First, I will never run this > > module directly, so __name__ will always be the module name and not "__main__". > > (note that it works even with __main__) Nice. Thanks. > > Second, I can use this in a class to decide whether I want > > the module where the class came from or, if I make the class a base > I don't completely understand your use case. In the expression: > ? ? getattr(some_module, attribute_name) > you may use any module as the first argument (the current module, or any other). Right, I was just confused about the effects of inheritance and scope. If I put a method in a baseclass, which is inherited in another module, and then run the method from an instance of the sub-class... - "sys.modules[__name__]" returns the baseclass module. - "sys.modules[self.__class__.__module__]" returns the subclass module. in the end I found it felt more logical to put the code in a module- level function and call it from the class. All of this was part of a fairly large factory method implementation. I now know that globals() refers to module-level names. The pros and cons were the main point of this thread and so far I have... 1) getattr(module, "whatever") seems the most pythonic way to do it but it takes more than one line and requires a little more thought about scope and inheritance. 2) globals()["whatever"] is concise, but it seems a little like a shortcut which requires special knowledge (though a very small amount). I did a quick benchmark test: < tmp2.py > import time import sys import tmp class A(tmp.A): pass class B(tmp.A): pass class C(tmp.A): pass class D(tmp.A): pass class E(tmp.A): pass class F(tmp.A): pass class G(tmp.A): pass class H(tmp.A): pass class I(tmp.A): pass class J(tmp.A): pass def test_globals_vs_gettattr(): t1 = time.time() for i in range(0, 1000000): H = globals()["H"] t2 = time.time() print "globals() too %s seconds." % str(t2-t1) t1 = time.time() mod = sys.modules[__name__] for i in range(0, 1000000): H = getattr(mod, "H") t2 = time.time() print "getattr() too %s seconds." % str(t2-t1) < /tmp2.py > tmp.py just has a simple class in it. I just wanted to add some complexity, but I doubt this had any affect on the times. >>> import tmp2 >>> tmp2.test_globals_vs_gettattr() globals() too .146900010109 seconds. getattr() too .434299993515 seconds. Just to see how much the call to sys.modules was affecting the test, I moved it outside the loop and reloaded the module for a second test. >>> reload(tmp2) >>> tmp2.test_globals_vs_gettattr() globals() too .139100003242 seconds. getattr() too .254600000381 seconds. This second test is pointless in practice since I would be calling sys.modules each time anyway. Even though the getattr() way is around 3.5 times slower, I had to run the code 1,000,000 times before the difference became humanly recognizable. I also realize benchmarks should be taken with a grain of salt since my setup may differ greatly from others'. I guess, in the end, I'd use getattr() because it feels more pythonic, and more basic. I got pretty deep in to learning python before I had to learn what the globals() dict could do for me. Cheers, - Rafe From andrew at doadesweb.co.uk Wed Dec 10 13:00:23 2008 From: andrew at doadesweb.co.uk (Andrew D) Date: Wed, 10 Dec 2008 10:00:23 -0800 (PST) Subject: get todays files References: Message-ID: <3090b59b-a0b2-4bfb-a08f-6d6accfb363a@k36g2000pri.googlegroups.com> On Dec 10, 5:55?pm, Steve Holden wrote: > Andrew D wrote: > > I have a script that will login to my ftp server and download all the > > backup files, but I want it to only download the files that were > > created today, e.g. if I ran the script today I want it to only fetch > > files created today. > > > I am really not sure about how to do this, but it is quite important > > to me, so all help is highly appreciated! > > IIRC there's an "ftpmirror" script in the Tools directory (if you're on > Windows - Linux/Unix users have to download the source). I adapted it to > several different purposes. > > regards > ?Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ Thanks Steve, I don't want to sound rude here, but I really want some code to add to my script so that it will only download todays files. Andrew From george.sakkis at gmail.com Tue Dec 2 21:25:08 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 2 Dec 2008 18:25:08 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> <591e8625-7e4d-4db8-ae6c-73c4370f8088@q26g2000prq.googlegroups.com> Message-ID: On Dec 2, 4:57?pm, Lew wrote: > There is no reason for you to engage in an /ad hominem/ attack. ?It > does not speak well of you to resort to deflection when someone > expresses a contrary opinion, as you did with both Jon Harrop and with > me. ?I suggest that your ideas will be taken more seriously if you > engage in more responsible behavior. As a Slashdotter would put it... you must be new here ;-) From Matthijs.Mullender at gmail.com Wed Dec 10 10:38:21 2008 From: Matthijs.Mullender at gmail.com (Matthijs) Date: Wed, 10 Dec 2008 07:38:21 -0800 (PST) Subject: ANN: python-ntlm - provides NTLM support, including an authentication handler for urllib2 Message-ID: <4a7fe683-7c92-41ef-a785-0cea82a0f4a9@a12g2000pro.googlegroups.com> Announcing: python-ntlm http://code.google.com/p/python-ntlm/ python-ntlm is a library that provides NTLM support, including an authentication handler for urllib2. This library allows you to retrieve content from (usually corporate) servers protected with windows authentication (NTLM) using the python urllib2. For more details and downloads visit: http://code.google.com/p/python-ntlm/ == Example Usage == import urllib2 from ntlm import HTTPNtlmAuthHandler user = 'DOMAIN\User' password = "Password" url = "http://ntlmprotectedserver/securedfile.html" passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, url, user, password) # create the NTLM authentication handler auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman) # create and install the opener opener = urllib2.build_opener(auth_NTLM) urllib2.install_opener(opener) # retrieve the result response = urllib2.urlopen(url) print(response.read()) From sanket.s.patel at gmail.com Fri Dec 19 17:01:40 2008 From: sanket.s.patel at gmail.com (sanket) Date: Fri, 19 Dec 2008 14:01:40 -0800 (PST) Subject: how to convert pymedia.audio.acodec ACString to ctypes.c_char_p Message-ID: <82fa9417-7fbd-444c-b2a9-305f62e40287@v5g2000prm.googlegroups.com> Hello All Experts, I am quite new to Ctypes. I am using one c library and writing python bindings for it. I need to pass a character pointer to one function. I am reading one mp3 file and decoding it to raw pcm using pymedia. Now I need to pass this raw data in to a C function. Here is my code. # /********* from ctypes import * import pymedia.audio.acodec as codec dec = None dm = muxer.Demuxer('mp3') fp = open('test.mp3', 'rb') fingerprinting_done = False while not fingerprinting_done: s = fp.read(20000) frames = dm.parse(s) for fr in frames: if dec == None: dec = codec.Decoder(dm.streams[0]) r = dec.Decode(fr[1]) if r and r.data: # pass this r.data to the C function. # r.data is ACString object # I cannot do pcm_audio = c_char_p(r.data) . gives me following error # TypeError: string or integer address expected instead of ACString instance # *************/ I am getting error while converting r.data (which is ACstring object) in to ctypes.c_char_p. can you help me solving this problem? any help would be appericiated, Thank you, sanket From clp at rebertia.com Tue Dec 16 19:25:12 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 16 Dec 2008 16:25:12 -0800 Subject: Free place to host python files? In-Reply-To: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> References: <7f3baaf3-6116-4a7a-8181-6f88b0e44950@w24g2000prd.googlegroups.com> Message-ID: <47c890dc0812161625o76f5c7e6lb8809b99f6962d32@mail.gmail.com> On Tue, Dec 16, 2008 at 6:10 AM, feba wrote: > I'm getting started in python, and it would be helpful to have a place > to put up various code snippets I've made, so I don't have to send > them individually to each person I want to show it to. I'd prefer to > use something that would give me a directory for my use only, instead > of something where you can only upload one at a time. I'd especially > like to avoid stuff that uses CAPTCHAs and/or forced waiting periods. > > I'd really rather not have to run a server off my own computer, if it > can be avoided at all. I'll plug Bitbucket (http://bitbucket.org/). It gives you 150MB of Mercurial hosting for free, along with a bug tracker and wiki. And I hear it's implemented using Django. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From bdesth.quelquechose at free.quelquepart.fr Tue Dec 30 13:55:53 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 30 Dec 2008 19:55:53 +0100 Subject: duck typing at will In-Reply-To: References: Message-ID: <495a7c6a$0$30721$426a74cc@news.free.fr> Jose Mora a ?crit : > Duck typing is called that way because "If it looks like a duck and > quacks like a duck, it must be a duck." or at least something close enough... > I think it would be good to > have also "If the programmer wants to deal with it like a duck, it > must be a duck" DWIM[1] just doesn't work. No parser can read your mind, and the harder they try, the more bugs they are likely to cause. IOW : cows neither look nor quack like ducks, and asking a cow to quack just won't turn your cow into a duck. [1] Do What I Mean > I mean, some tasks are rather boring in python when compared with php, Possibly. OTHO, and from years of experience with both languages, a lot of tasks are way more boring in php when compared to Python. > for example, let's imagine we have a dictionary that contains > dictionaries that contain the times that a key appears. We, or at > least I, would like to write something as short as: > > dict[k1][k2] += 1 > > However we will have to do a longer code (this is the smallest code I > could come up with): > dict = {} bad identifier - it shadows the builtin dict type. > if not k1 in dict: > dict[k1] = {} > if not k2 in dict[k1]: > dict[k1][k2] = 0 > dict[k1][k2] += 1 What about: from collections import defaultdict d = defaultdict(lambda: defaultdict(int)) for k1, k2 in whatever: d[k1][k2] += 1 NB : this requires a "recent" Python version (works on 2.5.1 at least). Else, yes, this will be a bit more "boring": d = dict() for k1, k2 in whatever: d2 = d.setdefault(k1, dict()) d2[k2] = d2.get(k2, 0) + 1 HTH From jeff_barish at earthlink.net Sun Dec 21 19:24:32 2008 From: jeff_barish at earthlink.net (Jeffrey Barish) Date: Sun, 21 Dec 2008 17:24:32 -0700 Subject: Beep References: <47c890dc0812211620h6c19086dhf3a14a662a49fdf6@mail.gmail.com> Message-ID: Chris Rebert wrote: > > Is the 'pcspkr' kernel module built and loaded? Yes. And I should have mentioned that I get sound from Ubuntu applications that produce sound. -- Jeffrey Barish From aisaac at american.edu Thu Dec 4 15:15:22 2008 From: aisaac at american.edu (Alan G Isaac) Date: Thu, 04 Dec 2008 15:15:22 -0500 Subject: "as" keyword woes In-Reply-To: References: Message-ID: <8aSdnSpVVdTAp6XUnZ2dnUVZ_szinZ2d@rcn.net> Warren DeLano wrote: > what I can't understand is the decision to break 2.6 instead of 3.0. 2.x was > supposed to remain backwards compatible, with the thinking that 2.x > would be maintained in parallel for quite some time. 3.x was supposed > to be the compatibility break. I do not understand why anyone would object to this perfectly cogent complaint of Warren's. Even if the deprecation warnings had not been invisible, the complaint would be valid. Alan Isaac From excord80 at gmail.com Fri Dec 12 01:27:06 2008 From: excord80 at gmail.com (excord80 at gmail.com) Date: Thu, 11 Dec 2008 22:27:06 -0800 (PST) Subject: How do I manually uninstall setuptools (installed by egg)? References: <3389921e-67dd-437b-b0aa-5ecad9a2b297@l33g2000pri.googlegroups.com> <375bd56a-d92b-4d33-bf70-5bea630a376a@q30g2000vbn.googlegroups.com> <6q9rvnFbj6ogU1@mid.uni-berlin.de> Message-ID: <227a9972-e37d-40a0-bd9b-4fadd9e2473e@m15g2000vbp.googlegroups.com> On Dec 10, 7:45?am, "Diez B. Roggisch" wrote: > excor... at gmail.com wrote: > > > As an aside, I'm a bit struck by how long the setuptools/easy_install > > manuals are, and a bit dismayed at the lack of an easy_install > > uninstall command. Thinking of trying life for a while without > > setuptools/easy_install. Will have to see how far I get. :) > > To *long* manuals? So far I haven't heard that complaint in the FOSS > world... I didn't say that the manuals were too long, I said I was *struck by* how long they are. I read them through a while back, and they seemed long and confusing to me at the time. While reading, I kept thinking, "this should be simpler" and "why does a seemingly simple tool need such a long manual?". Maybe setuptools/easy_install/eggs is not overly complicated, but it seems that way to me. From gagsl-py2 at yahoo.com.ar Wed Dec 24 14:43:25 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2008 17:43:25 -0200 Subject: Custom C Exception Subclasses References: <41f291ff-d7bd-4334-8689-636e95524cdc@b38g2000prf.googlegroups.com> Message-ID: En Wed, 24 Dec 2008 15:48:34 -0200, Gabriel Genellina escribi?: > En Wed, 24 Dec 2008 15:00:36 -0200, Ivan Illarionov > escribi?: > >> When you raise an exception in C++ you can set it to ANY Python object >> via PyErr_SetObject and that object could store pointers to C++ >> classes. > > Remember that exceptions should inherit from BaseException; although > this rule isn't enforced in Python 2.6, 3.0 doesn't allow that. > It isn't explicitely written in the docs, but I think that > PyErr_SetObject won't allow you to pass an object which is not an > instance of its first argument. Correction: you're right, it is OK to pass any other object as the second parameter to PyErr_SetObject; it will be used as the argument to the exception constructor. -- Gabriel Genellina From arnodel at googlemail.com Tue Dec 16 16:14:44 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 16 Dec 2008 21:14:44 +0000 Subject: How to modify a program while it's running? References: Message-ID: Joe Strout writes: > Here's my situation: I'm making an AIM bot, but the AIM server will > get annoyed if you log in too frequently (and then lock you out for a > while). So my usual build-a-little, test-a-little methodology doesn't > work too well. > > So I'd like to restructure my app so that it can stay running and stay > logged in, yet I can still update and reload at least most of the > code. But I'm not sure what's the best way to do this. Should I move > the reloadable code into its own module, and then when I give my bot a > "reload" command, have it call reload on that module? Will that work, > and is there a better way? > > Thanks, > - Joe You could have two processes: the first one that logs in and does the message passing with the server, the other that implements the logic and talks to the server via the first one. This way you can restart the second one as often as you want without being logged out. I never user reload() but I hear that it has quite a few caveats. -- Arnaud From steve at REMOVE-THIS-cybersource.com.au Sat Dec 6 21:17:58 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 02:17:58 GMT Subject: [Python-Dev] "as" keyword woes References: <896B75251BA19745A529B1B867893FA5DB0F@planet.delsci.local> Message-ID: <014b2a09$0$20670$c3e8da3@news.astraweb.com> On Sun, 07 Dec 2008 11:27:56 +1000, Nick Coghlan wrote: > Warren DeLano wrote: >> In other words we have lost the ability to refer to "as" as the >> generalized OOP-compliant/syntax-independent method name for casting: > > Other possible spellings: > > # Use the normal Python idiom for avoiding keyword clashes # and append > a trailing underscore > new_object = old_object.as_(class_hint) float_obj = int_obj.as_("float") > float_obj = int_obj.as_(float_class) > > # Use a different word (such as, oh, "cast" perhaps?) new_object = > old_object.cast(class_hint) float_obj = int_obj.cast("float") > float_obj = int_obj.cast(float_class) I don't like "cast", because a cast is an instruction to the compiler to treat data as some type other than what it was defined as. It doesn't create a new piece of data. (At least in C-like languages.) I'd prefer a method like obj.make_from(type) or obj.export_as(type) or similar. It's more verbose than "as" but its more explicit about what it does. obj.as(type) is ambiguous, because it could mean any "return a new object of type made from obj", "return obj inside a wrapper that makes it behave as if it were type", "convert obj to type in place". -- Steven From nick at craig-wood.com Tue Dec 2 08:30:45 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 02 Dec 2008 07:30:45 -0600 Subject: How to instantiate in a lazy way? References: <86d55ee5-d708-4247-8294-bf809caa496a@t11g2000yqg.googlegroups.com> <258cf433-f6c9-43e7-a235-f5f6b2b6433f@j39g2000yqn.googlegroups.com> Message-ID: Slaunger wrote: > On 2 Dec., 11:30, Nick Craig-Wood wrote: > > > > > For 4 attributes I'd probably go with the __getattr__. > > > OK, I'll do that! > > > Or you could easily write your own decorator to cache the result... > > > > Eg http://code.activestate.com/recipes/363602/ > > Cool. I never realized I could write my own decorators! > I've so far only used them for > @classmethod, @staticmethod and stuff like that. > User defined decorators are nice and fun to do as well. > I just hope it will be understandable > in four years also... Actually that decorator does exactly what you want. It replaces the attribute with the actual data so after the first call there is no overhead. I'd use that I think! > > > ?With the property methology you do the value check on each get, which > > > ?does not look as "clean". The property methology is also a little less > > > ?arcane I guess for less experienced Python programmers to understand > > > ?when re-reading the code. > > > > Less magic is how I would put it. ?Magic is fun to write, but a pain > > to come back to. ?Over the years I find I try to avoid magic more and > > more in python. > > > Ah, I see. I hope you do not consider user defined decorators > "magic" then? ;-) Well the magic is contained in the decorator so it isn't splattered throughout your code! Decorators are part of the meta-programming toolbag along with metaclasses. Used sparingly they can be extrememly useful! > Again, thank you for your assistance, Nick! No problem! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bdesth.quelquechose at free.quelquepart.fr Mon Dec 29 13:10:39 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 29 Dec 2008 19:10:39 +0100 Subject: SQL, lite lite lite In-Reply-To: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> Message-ID: <4959204f$0$15020$426a74cc@news.free.fr> Aaron Brady a ?crit : > Hi all, > (snip) > > I don't think relational data can be read and written very easily in > Python. Did you try SQLAlchemy or Django's ORM ? > There are some options, such as 'sqllite3', but they are not > easy. 'sqllite3' statements are valid SQL expressions, which afford > the entire power of SQL, but contrary to its name, it is not that > 'lite'. sqlite is a Python-independant library providing a lightweight SQL embedded (ie : no server) database system. It is "light" wrt/ Oracle, Postgres etc. > To me, 'lite' is something you could learn (even make!) in an > afternoon, not a semester; No one in it's own mind would hope to learn the relational theory and algebra in an afternoon, whatever the implementation. > something the size of an ActiveState > recipe, or a little bigger, maybe a file or two. If you think SQL is > a breeze, you probably won't find my idea exciting. I assume that the > basics of SQL are creating tables, selecting records, and updating > records. There's much more than this. > My idea is to create a 'Relation' class. The details are basically > open, such as whether to back it with 'sqllite3', 'shelve', 'mmap', or > just mapping and sequence objects; what the simplest syntax is that > can capture and permit all the basics, and how much and what else can > fit in at that level; how and whether it can include arbitrary Python > objects, and what constraints there are on them if not; how and > whether to permit transactions; and what the simplest and coolest > thing you can do with a little Python syntax is. > > This is basically an invitation for everyone to brainstorm. (No > hijackings, good humor & digression ok.) Lastly, ... > > > #Just the select and update syntax: > >>>> a= people._select( "firstname== 'Joe'" ) > #select 'key' from 'people' where 'firstname'== 'joe' >>>> a > [Entry2864, Entry3076, Entry3172] >>>> entry1= a[ 0 ] >>>> entry1.phone > #select 'phone' from 'people' where 'key'==self.key > "555-2413" >>>> entry1.phone= "555-1234" > #update 'people' set 'phone'= '555-1234' where 'key'==self.key >>>> entry1.phone > "555-1234" > > #Create table syntax (a-whole-nother beast in itself): > >>>> classes= db.Relation( 'class_', 'person', Unique( 'class_', 'person' ) ) > #create table 'classes' ( 'key', 'class_', 'person' ) unique > ( 'class_', 'person' ) >>>> classes._unique( 'class_', 'person' ) >>>> classes.class_.noneok= False #'class_' cannot be null >>>> classes.person.noneok= False >>>> classes._insert( 'Physics', 'Dan' ) >>>> classes._insert( 'Chem', 'Tim' ) From django's tutorial, part 1: # polls/models.py import datetime from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __unicode__(self): return self.question def was_published_today(self): return self.pub_date.date() == datetime.date.today() class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) votes = models.IntegerField() def __unicode__(self): return self.choice # in the interactive shell >>> from mysite.polls.models import Poll, Choice >>> Poll.objects.all() [] # Create a new Poll. >>> import datetime >>> p = Poll(question="What's up?", pub_date=datetime.datetime.now()) # Save the object into the database. You have to call save() explicitly. >>> p.save() # Now it has an ID. Note that this might say "1L" instead of "1", depending # on which database you're using. That's no biggie; it just means your # database backend prefers to return integers as Python long integer # objects. >>> p.id 1 # Access database columns via Python attributes. >>> p.question "What's up?" >>> p.pub_date datetime.datetime(2007, 7, 15, 12, 00, 53) # Change values by changing the attributes, then calling save(). >>> p.pub_date = datetime.datetime(2007, 4, 1, 0, 0) >>> p.save() # objects.all() displays all the polls in the database. >>> Poll.objects.all() [] # Django provides a rich database lookup API that's entirely driven by # keyword arguments. >>> Poll.objects.filter(id=1) [] >>> Poll.objects.filter(question__startswith='What') [] # Get the poll whose year is 2007. Of course, if you're going through this # tutorial in another year, change as appropriate. >>> Poll.objects.get(pub_date__year=2007) >>> Poll.objects.get(id=2) Traceback (most recent call last): ... DoesNotExist: Poll matching query does not exist. # Lookup by a primary key is the most common case, so Django provides a # shortcut for primary-key exact lookups. # The following is identical to Poll.objects.get(id=1). >>> Poll.objects.get(pk=1) # Make sure our custom method worked. >>> p = Poll.objects.get(pk=1) >>> p.was_published_today() False # Give the Poll a couple of Choices. The create call constructs a new # choice object, does the INSERT statement, adds the choice to the set # of available choices and returns the new Choice object. >>> p = Poll.objects.get(pk=1) >>> p.choice_set.create(choice='Not much', votes=0) >>> p.choice_set.create(choice='The sky', votes=0) >>> c = p.choice_set.create(choice='Just hacking again', votes=0) # Choice objects have API access to their related Poll objects. >>> c.poll # And vice versa: Poll objects get access to Choice objects. >>> p.choice_set.all() [, , ] >>> p.choice_set.count() 3 # The API automatically follows relationships as far as you need. # Use double underscores to separate relationships. # This works as many levels deep as you want; there's no limit. # Find all Choices for any poll whose pub_date is in 2007. >>> Choice.objects.filter(poll__pub_date__year=2007) [, , ] # Let's delete one of the choices. Use delete() for that. >>> c = p.choice_set.filter(choice__startswith='Just hacking') >>> c.delete() NB : works with sqlite, MySQL and Postgres, and supports transactions if the underlying SQL engine supports them. HTH From rhodri at wildebst.demon.co.uk Sat Dec 6 19:31:21 2008 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Sun, 07 Dec 2008 00:31:21 -0000 Subject: python book for non technical absolute beginner In-Reply-To: <493a7c6a$0$973$426a34cc@news.free.fr> References: <493a7c6a$0$973$426a34cc@news.free.fr> Message-ID: On Sat, 06 Dec 2008 13:21:45 -0000, News123 wrote: > No my question does anybody know a nice beginners book (or a learning CD > or on line tutorial)? Ideally it shouldn't be too serious and have a lot > of small nice mini-examples For just pottering around with, your friend could do worse than the LiveWires Python Course. It doesn't go far into general programming skills, largely because its designed for 12-15 year old kids to get through in about three days of concentrated effort, but it will help to learn the basics of Python and programming in general. Caveat: the worksheets are built around Python 2.x (for small values of x!), tell your friend not to use Python 3.0. This is one of the few cases where it really matters that 'print' is now a function; nothing freaks a beginner like his output not behaving the way he's been told it should. -- Rhodri James *-* Wildebeeste Herder to the Masses From google at mrabarnett.plus.com Fri Dec 5 10:59:10 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 05 Dec 2008 15:59:10 +0000 Subject: pretty strange behavior of "strip" In-Reply-To: References: <4938693F.6090709@yahoo.ca> Message-ID: <49394FCE.2010700@mrabarnett.plus.com> rdmurray at bitdance.com wrote: > On Thu, 4 Dec 2008 at 20:54, Terry Reedy wrote: >>> 'toc.html' >>> > > > test[4].strip('.html') >>> 'oc' >>> >>> Can't figure out what is going on, really. >> >> What I can't figure out is why, when people cannot figure out what is >> going on with a function (or methods in this case), they do not look >> it up the doc. (If you are an exception and did, what confused you?) >> Can you enlighten me? > > I'm a little embarrassed to admit this, since I've been using python for > many years, but until I read these posts I did not understand how strip > used its string argument, and I _have_ read the docs. I can't tell you > what confused the OP, but I can tell you what confused me. > > I have often wished that in 'split' I could specify a _set_ of characters > on which the string would be split, in the same way the default list > of whitespace characters causes a split where any one (or more) of > them appears. But instead the string argument is a multi-character > separator. (Which is sometimes useful and I wouldn't want to lose the > ability to specify a multi-character separator!) > > My first experience in using the string argument was with split, so when I > ended up using it with strip, by analogy I assumed that the string passed > to strip would also be a multi-character string, and thus stripped only > if the whole string appeared exactly. Reading the documentation did > not trigger me reconsider that assumption. I guess I'm just lucky that > I haven't run into any bugs (but I think I've used the string argument > to strip only once or twice in my career). > > It would be lovely if both the split and strip methods would have a > second string argument that would use the string in the opposite sense > (as a set for split, as a sequence match for strip). > > In the meantime the docs could be clarified by replacing: > > the characters in the string will be stripped > > with > > all occurrences of any of the characters in the string will be > stripped > > --RDM > > PS: the OP might want to look at th os.path.splitext function. > If I had thought about it early enough I could have suggested that in Python 3 split() and strip() should accept either a string or a set of strings. It's still possible to extend split() in the future, but changing the behaviour of strip() with a string argument would break existing code, something which might have been OK as part of changes in Python 3. Unfortunately I don't have access to the time machine! :-) From greywine at gmail.com Fri Dec 26 01:08:34 2008 From: greywine at gmail.com (greywine at gmail.com) Date: Thu, 25 Dec 2008 22:08:34 -0800 (PST) Subject: socket send help References: Message-ID: <8a5a2b07-3274-483a-be06-51eab226315a@d36g2000prf.googlegroups.com> Hi again, I've done some more playing around with socket and socketserver and have discovered I can send strings or lists with socket.send() by converting to bytes. But lists with strings in them or dicts can't be converted by bytes(). How can I send those? One idea I initially tried was to set up a server (host,port) for receiving data and another one (host, different port) for strings, but that didn't work so I was thinking of throwing everything into a list or a dictionary and sending that but that's not working either. Any ideas? Thanks, John. On Dec 24, 12:03?am, "Gabriel Genellina" wrote: > En Wed, 24 Dec 2008 03:59:42 -0200, greyw... at gmail.com ? > escribi?: > > > New guy here. ?I'm trying to figure out sockets in order to one day do > > a multiplayer game. ?Here's my problem: ?even the simplest examples > > don't work on my computer: > > > A simple server: > > > fromsocketimport * > > myHost = '' > > Try with myHost = '127.0.0.1' instead - a firewall might be blocking your ? > server. > > > s.listen(5) ? ? ? ? ? ? ? ? ? ? ? ? # allow 5 simultaneous connections > > Not exactly: your server program only handles a single connection at a ? > time. The 5 above specifies how many connections may exist "on hold" ? > waiting for you to accept() them. > > > ? ? ? ? ? ? connection.send('echo -> ' + data) > > That's fine for Python 2.6, but you must use b'echo -> ' with 3.0 > > > And a simple client: > > > s.send('Hello world') ? ? ? ? ? ? ? # send the data > > Same as above, should be b'Hello world' with Python 3.0 > > > If I run testserver.py via the cmd prompt in Windows XP and then the > > testclient.py program, I get the following error: > > > Traceback (most recent call last): > > ? File "C:\Python30\testclient.py", line 12, in > > ? ? s.send('Hello world') ? ? ? ? ? ? ? # send the data > > TypeError: send() argument 1 must be string or buffer, not str > > The above error message is wrong (and I think it was corrected on the 3.0 ? > final release; if you got it with 3.0 final, file a bug report at ?http://bugs.python.org/) > > > This happens in 2.6 or 3.0 and with different example client & server > > programs from the web. ?What am I missing? > > The error above surely comes from 3.0; with 2.6 you should get a different ? > error (if it fails at all). Try again with 2.6.1. I didn't run the code ? > but it looks fine -- if you got it from a book or article, unless it ? > explicitely says "Python 3.0", assume it was written for the 2.x series. > > -- > Gabriel Genellina From rt8396 at gmail.com Mon Dec 22 19:12:36 2008 From: rt8396 at gmail.com (r) Date: Mon, 22 Dec 2008 16:12:36 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <494ea6ab$0$7769$426a74cc@news.free.fr> <7e208154-957a-48a7-b8da-76af3ae0a51f@g1g2000pra.googlegroups.com> <80427165-02a0-4401-ade9-3cef1d520e6c@v39g2000pro.googlegroups.com> Message-ID: <014977ea-a1aa-40ba-8ea2-bec4a84f5fcd@r27g2000vbp.googlegroups.com> On Dec 22, 5:53?pm, Aaron Brady wrote: > On Dec 22, 11:40?am, r wrote: > > > > > On Dec 22, 8:58?am, walterbyrd wrote: > > > > On Dec 21, 12:28?pm, Bruno Desthuilliers > > > > wrote: > > > > Strange enough, > > > > no one seems to complain about PHP or Ruby's performances... > > > > A few years back, there was a certain amount of chest thumping, when > > > python/django easily beat ror in a benchmark test. Now that ruby is > > > faster, I guess speed is no big issue. > > > > By the same reasoning, python advocates used to sneer at php because > > > php constantly broke backward compatibility. Now that python does it, > > > breaking backward compatibility is no big deal. I guess unicode > > > support was not that important, until python caught up to perl. > > > > I guess, the way it works is: you first assume that python is > > > superior, then you figure out why. > > > I think what walter is saying is the loyalty is gone. > > > community: > > """If python makes great, if it doesn't, why should "i" care if it > > goes down the toilet? ?i just move to ruby""" > > > Were is your loyalty pyfans?, Has the fight left you??? > > Point: It is not rational for the crew to go down with the ship, only > the captain. > > Case: Loyalty is a complex emotion, and it's not clear that it's our > highest priority, or that it's anyone's. > > I want to use a good language. ?If Python stops being good (that is, a > good version of Python stops being maintained and supported), then > I'll stop using it, and that's the rational thing to do. > > Just to be fair, though, it's (contraction) not obviously irrational > for a captain to go down with the ship. ?The mentality, commitments, > and principles that it lets him keep and make may be better on the > whole in the long run for captains, crews, and ships, only if they > have that consequence. ?That is, captains that will go down with the > ship are better captains of ships, and captains that have the capacity > to betray, forge, or abandon principles make worse captains; therefore > a good captain will go down, and can't change his mind. > > However, as critics and fans of Python, our actions don't really have > the same consequences as the captains. ?That is, it is not rational > for the crew to go down with the ship, only the captain. What if the crew sabotage the ship, should the captain still go down with it, even though sabatuers are to blame? All ships need a good captain, all captains need a good crew, and all crews need a good ship.(also True in reverse()). Without loyalty python will fail, so will Ruby, so will C. Sometimes even when loyalty is scarce, a language will survive solely because it is the only ship available. You do not have to fight for python as I do to use it and benefit from it, that's OK. I don't care either way. But don't piss on me for trying to keep her a-float, Mate!. From duncan.booth at invalid.invalid Tue Dec 2 13:52:52 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Dec 2008 18:52:52 GMT Subject: [ANN] Pyjamas 0.4: Python Web Toolkit Release References: Message-ID: "Luke Kenneth Casson Leighton" wrote: > Pyjamas started as a port of Google's Web Toolkit, to python. > Explaining why Pyjamas (and GWT) is so significant takes > some doing: the summary is that comprehensive desktop-like > user interfaces can be developed very simply, to run in > any modern web browser, without having to write a single > line of JavaScript. Great concept. The demos are a bit flakey (especially with IE): where do you want bug reports (the sourceforge tracker seems to be empty so I wondered if you used somewhere else)? From walterbyrd at iname.com Sat Dec 20 18:36:46 2008 From: walterbyrd at iname.com (walterbyrd) Date: Sat, 20 Dec 2008 15:36:46 -0800 (PST) Subject: New Python 3.0 string formatting - really necessary? References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <49124b2b-ee55-45ba-a08a-f0db954e4776@o4g2000pra.googlegroups.com> Message-ID: <88a122de-14c6-4025-b36c-9a39bdd50d86@i20g2000prf.googlegroups.com> On Dec 19, 10:55?am, bearophileH... at lycos.com wrote: > Regarding the speed of Python3 programs, > they will go faster "The net result of the 3.0 generalizations is that Python 3.0 runs the pystone benchmark around 10% slower than Python 2.5. " http://docs.python.org/dev/3.0/whatsnew/3.0.html > (Ruby programs are often slower > than Python ones (because Ruby > is a little higher level than Python) As I understand it, that may have been true at one time. But, Ruby 1.9 very significantly sped up the language. While Python has been made slower, Ruby has been made much faster. I am no expert on the subject, I am just going by stuff I have read on web. From invalid at invalid Thu Dec 11 11:59:56 2008 From: invalid at invalid (Grant Edwards) Date: Thu, 11 Dec 2008 10:59:56 -0600 Subject: Python, threading References: Message-ID: On 2008-12-11, SMALLp wrote: > Hy. I have a problem! I'm making multi thread application (client, > server) using wxPython for GUI, and threading.Thread for threding. > > Clients connect and when they are connected (evry thread handles one > connection) threads change main window. > > I neded tip how to make communication between threeds. All window manipulation must be done in the main thread. Your worker threads can schedule work to be done by the main thread by using wx.CallAfter() http://wiki.wxpython.org/CallAfter -- Grant Edwards grante Yow! This is a NO-FRILLS at flight -- hold th' CANADIAN visi.com BACON!! From arnodel at googlemail.com Tue Dec 16 13:17:14 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 16 Dec 2008 18:17:14 +0000 Subject: Generator slower than iterator? References: Message-ID: bearophileHUGS at lycos.com writes: > This can be a little faster still: > > match_counter = defaultdict(int) > for line in fileinput.input(sys.argv[1:]): > ip = line.split(None, 1)[0] > match_counter[ip] += 1 > > Bye, > bearophile Or maybe (untested): match_counter = defaultdict(int) for line in fileinput.input(sys.argv[1:]): ip = line[:line.index(' ')] match_counter[ip] += 1 Or even (untested, I've never tried this ;): from itertools import count match_counter = defaultdict(count) for line in fileinput.input(sys.argv[1:]): ip = line[:line.index(' ')] match_counter[ip].next() match_total = dict((key, val()) for key, val in match_counter.iteritems()) Obviously the variable 'ip' could be removed in all cases. -- Arnaud From __peter__ at web.de Mon Dec 1 14:52:08 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 01 Dec 2008 20:52:08 +0100 Subject: Checking a string against multiple matches References: <99a3a677-a38d-40f5-9a94-a98865150b69@k19g2000yqg.googlegroups.com> Message-ID: Aaron Scott wrote: > I've been trying to read up on this, but I'm not sure what the > simplest way to do it is. > > I have a list of string. I'd like to check to see if any of the > strings in that list matches another string. > > Pseudocode: > > if "two" in ["one", "two", "three", "four"]: > return True Why /pseudo/ ? >>> if "two" in ["one", "two", "three", "four"]: ... print "match" ... else: ... print "no match" ... match >>> if "seven" in ["one", "two", "three", "four"]: ... print "match" ... else: ... print "no match" ... no match > Is there any built-in iteration that would do such a thing, or do I > have to write a function to check for me? I was using .index on the > list, but it would return True for strings that contained the search > string rather than match it exactly, leading to false positives in my > code. You didn't check carefully. list.index() gives you a value error when no matching item is found: >>> ["one", "two", "three", "four"].index("seven") Traceback (most recent call last): File "", line 1, in ValueError: list.index(x): x not in list Peter From bearophileHUGS at lycos.com Thu Dec 11 13:34:45 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 11 Dec 2008 10:34:45 -0800 (PST) Subject: dictionary idiom needed References: <383976cf-53fb-48e4-b028-8f568468ce77@r36g2000prf.googlegroups.com> Message-ID: <0c4950c1-4833-40c7-ac19-260b61d5289f@k24g2000pri.googlegroups.com> Brandon: > I need an dictionary idiom whereby I can find all instances of > a given 'word' with any 'tagB', and then subdivide into all instances > of a given 'tagB'. ?In both cases I would want the value as a count of > all instances found. If I have understood you well enough, I think you can do with a dict that has the tuple ('word', 'tagB') as key, and as value has a collections.defaultdict(int) that maps 'tagB' to its count. Bye, bearophile From mirandasnailvv at gmail.com Fri Dec 19 19:42:45 2008 From: mirandasnailvv at gmail.com (mirandasnailvv at gmail.com) Date: Fri, 19 Dec 2008 16:42:45 -0800 (PST) Subject: mixed wrestling pantyhose - Free Message-ID: <96a64fb6-7c6e-4fe4-b019-545efd5bc3da@u18g2000pro.googlegroups.com> mixed wrestling pantyhose . . . *******CLICK HERE******** http://club247.cn/mixed-wrestling-pantyhose ***************************** . . . . . . . . . . . . mixed wrestling pantyhose From bcausey at zerodayconsulting.com Wed Dec 24 13:20:17 2008 From: bcausey at zerodayconsulting.com (Brad Causey) Date: Wed, 24 Dec 2008 12:20:17 -0600 Subject: String Comparison Testing Message-ID: <89f89940812241020l3e814f2dv4479da8d6575f7e7@mail.gmail.com> Python Version: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 List, I am trying to do some basic log parsing, and well, I am absolutely floored at this seemingly simple problem. I am by no means a novice in python, but yet this is really stumping me. I have extracted the pertinent code snippets and modified them to function as a standalone script. Basically I am reading a log file ( in this case, testlog.log) for entries and comparing them to entries in a safe list (in this case, safelist.lst). I have spent numerous hours doing this several ways and this is the most simple way I can come up with: import string safelistfh = file('safelist.lst', 'r') safelist = safelistfh.readlines() logfh = file('testlog.log', 'r') loglines = logfh.readlines() def safecheck(line): for entry in safelist: print 'I am searching for\n' print entry print '\n' print 'to exist in\n' print line comp = line.find(entry) if comp <> -1: out = 'Failed' else: out = 'Passed' return out for log in loglines: finalentry = safecheck(log) if finalentry == 'Failed': print 'This is an internal site' else: print 'This is an external site' The contents of the two files are as follows: http://www.mysite.com http://www.mysite.com/images/homepage/xmlslideshow-personal.swf It seems that no matter what I do, I can't get this to fail the " if comp <> -1:" check. (My goal is for the check to fail so that I know this is just a URL to a safe[internal] site) My assumption is that the HTTP:// is somehow affecting the searching capabilities of the string.find function. But I can't seem to locate any documentation online that outlines restrictions when using special characters. Any thoughts? Thanks! -Brad Causey CISSP, MCSE, C|EH, CIFI Zero Day Consulting -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at cheimes.de Tue Dec 16 13:50:09 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 16 Dec 2008 19:50:09 +0100 Subject: subprocess returncode windows In-Reply-To: References: Message-ID: Andrew schrieb: > Hello, > > I'm running into a strange situation with getting incorrect > returncodes / exit status from python subprocess.call. I'm using a > python script (runtime 2.6.1 on windows) to automate the deploy of > java applications to glassfish application server. Below is an example > of using a subprocess call to test the success / failure of the > glassfish CLI tool "asadmin" > > Example.py: > ---------------------- > import sys > from subprocess import * > > try: > retcode = call("c:/glassfish/bin/asadmin.bat " + "list-system- > properties --host mydomain --port 4848 --user admin server-01", > shell=True) > if retcode < 0: > print >>sys.stderr, "Child was terminated by signal", -retcode > else: > print >>sys.stderr, "Child returned", retcode > except OSError, e: > print >>sys.stderr, "Execution failed:", e Don't use shell=True! Instead use a list of arguments without shell=True: call(["c:/glassfish/bin/asadmin.bat", "list-system-properties", "--host mydomain", "--port 4848", "--user admin", "server-01"]) That should solve your quoting issues on Windows and fix your code. shell=True is considered evil and should be avoided whenever possible. Christian From reckoner at gmail.com Mon Dec 15 14:06:16 2008 From: reckoner at gmail.com (Reckoner) Date: Mon, 15 Dec 2008 11:06:16 -0800 (PST) Subject: tricky nested list unpacking problem Message-ID: <40b2bcd0-0d32-4388-b227-a2bafdceee8a@p2g2000prn.googlegroups.com> Hi, I have lists of the following type: [1,2,3,[5,6]] and I want to produce the following strings from this as '0-1-2-3-5' '0-1-2-3-6' That was easy enough. The problem is that these can be nested. For example: [1,2,3,[5,6],[7,8,9]] which should produce '0-1-2-3-5-7' '0-1-2-3-5-8' '0-1-2-3-5-9' '0-1-2-3-6-7' '0-1-2-3-6-8' '0-1-2-3-6-9' also, [1,2,3,[5,6],7,[9]] should produce '0-1-2-3-5-7-9' '0-1-2-3-6-7-9' obviously, these are nested loops over the lists. The problem is that I don't know ahead of time how many lists there are or how deep they go. In other words, you could have: [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]] Any help appreciated. I've really been having trouble with this. I hope that made sense. From mynthon1 at gmail.com Tue Dec 23 05:50:20 2008 From: mynthon1 at gmail.com (mynthon) Date: Tue, 23 Dec 2008 02:50:20 -0800 (PST) Subject: wxPython.button.disabled still catching clicks Message-ID: <8cb6da6a-7df4-4cce-a28e-385448a25b26@w39g2000prb.googlegroups.com> Hello! (sorry for my english) I have a problem with buttons in wxPython. When button is disabled (by .Disable() or .Enable(False)) it is grayed out but still receive clicks. Eg. i have button that disable itself, runs long action and enable itself: def onClick(self, evt): self.btn.Enable(False) for i in range (1000): print i self.btn.Enable(True) when for loop is running button is greyed out and when i click on it nothing happens but when loop ends another one is started because button "remebered" thad i click on it when was diabled. My only idea is to reposition button outside frame instead of disabling it but this solution is...not good. thanks for any help. Ive searched groups, google and it looks that only i have this problem :) From philip at semanchuk.com Sun Dec 21 15:03:40 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Sun, 21 Dec 2008 15:03:40 -0500 Subject: Are Django/Turbogears too specific? In-Reply-To: References: Message-ID: <95659C49-5A3F-4001-BE6D-A63D577D692C@semanchuk.com> On Dec 21, 2008, at 2:41 PM, Gilles Ganault wrote: > Hi > > I'd like to rewrite a Web 2.0 PHP application in Python with AJAX, and > it seems like Django and Turbogears are the frameworks that have the > most momentum. I don't have any practical experience with these, but I've done some research. My impression is that Pylons has more momentum than TG. The latter project has declared the 1.x branch to be a dead end, and they're working on a 2.0 branch that's not out yet. I could be wrong, but that's what I gathered from my reading. > I'm concerned, though, that these frameworks they may be too specific > to the tasks they were originally developped for (news articles, > AFAIK). From the reading I did, I gathered that Django was really good if you want to do what Django is good at, but not as easy to customize as, say, Pylons. Pylons, on the other hand, is a little more complicated because it's made of several different parts, but the positive side of "complicated" is "flexible". > Do you think I should just use eg. CherryPy and some basic AJAX? Yes or no, depending on what you're trying to do! =) Good luck Philip From clp at rebertia.com Fri Dec 12 07:11:30 2008 From: clp at rebertia.com (Chris Rebert) Date: Fri, 12 Dec 2008 04:11:30 -0800 Subject: (Very Newbie) Problems defining a variable In-Reply-To: References: Message-ID: <47c890dc0812120411n1c9c4557pd2b3a2c2158c1d8c@mail.gmail.com> On Fri, Dec 12, 2008 at 3:42 AM, wrote: > #!/usr/bin/python > #Py3k, UTF-8 > > > #determine the interest rate to use > if bank >= 9999: > rate = 0.006 > elif bank >= 10000 and bank <= 24999: > rate = 0.0085 > elif bank >= 25000 and bank <= 49999: > rate = 0.0124 > elif bank >= 50000 and bank <= 99999: > rate = 0.0149 > elif bank >= 100000: > rate = 0.0173 For the love of Benji, reverse the ordering of the clauses so you don't have to keep checking whether the number is also under the next limit! (I'm assuming Bruno's guess about your first test having the operator flipped around the wrong way was right) if bank >= 100000: rate = 0.0173 elif bank >= 50000: rate = 0.0149 elif bank >= 25000: rate = 0.0124 elif bank >= 10000: rate = 0.0085 else: rate = 0.006 Note how much simpler that is to read and understand. And switching the default case to the 'else' is just idiomatic. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From gagsl-py2 at yahoo.com.ar Fri Dec 26 14:00:20 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 26 Dec 2008 17:00:20 -0200 Subject: =?utf-8?Q?Can=C2=B4t_Surf_Python_Pages_in_W?= =?utf-8?Q?indoze?= References: <4dc0cfea0812260701q6baf0ccbj154c5b3fa2281cdb@mail.gmail.com> <4954FB9F.5050702@wildenhain.de> <4dc0cfea0812260911k4dbc0f2ame9cc874e067b7816@mail.gmail.com> Message-ID: En Fri, 26 Dec 2008 15:11:44 -0200, Victor Subervi escribi?: > On 12/26/08, Tino Wildenhain wrote: >>> print "Content-Type: text/html" >>> print >>> print """ >>> >> http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> I think there should be only one blank line between header and content, you have two (so the document contains an empty line before the doctype declaration, and I think this is invalid). >>> >>> >>> >>> >>> Yeah >>> >>> """ The title tag (in head) is mandatory (although this should not prevent it from working) >> this could be fine if called in CGI context. > > Can you state clearly what "CGI context" means? Tino W. surely meant to say: - if you have a web server running - and it is capable of handle CGI scripts - and you have configured it to handle CGI scripts - and you have configured it to run the code above as a CGI script in response to certain request - and you pointed your browser to the right server, at the right port, at the right url - then, the code above should run and you should get a nice HTML page with the word Yeah in it. > Should I be importing a CGI > module? I pulled this code from a page that was working. If it had an > importation of something CGI, I believe I would have tested that with all > the other things that were imported that I tested, but perhaps not. I am > not > at my home computer to test, and will not be back online for a week. No, the code above doesn't require other modules to run. > I am not worried about Zope now, but the above code, yes. You're talking about two totally separate projects, I presume. The above code should not be used with Zope. -- Gabriel Genellina From Russ.Paielli at gmail.com Sat Dec 6 10:12:15 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 6 Dec 2008 07:12:15 -0800 (PST) Subject: Guido's new method definition idea References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> Message-ID: On Dec 6, 1:02?am, Antoine De Groote wrote: > Allowing "$" as a substitute for "self" wouldn't require this new syntax. > > class C: > ? ? def method($, arg): > ? ? ? ? $.value = arg > > I'm strongly against this. This looks ugly and reminds me of Perl and > Ruby. (I don't have anything against these languages, but there's a > reason I use Python). > > Russ P. wrote: > > On Dec 5, 6:21 pm, "Daniel Fetchinson" > > wrote: > >> Hi folks, > > >> The story of the explicit self in method definitions has been > >> discussed to death and we all know it will stay. However, Guido > >> himself acknowledged that an alternative syntax makes perfect sense > >> and having both (old and new) in a future version of python is a > >> possibility since it maintains backward compatibility. The alternative > >> syntax will be syntactic sugar for the old one. This blog post of his > >> is what I'm talking about: > > >>http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay... > > >> The proposal is to allow this: > > >> class C: > >> ? ? def self.method( arg ): > >> ? ? ? ? self.value = arg > >> ? ? ? ? return self.value > > >> instead of this: > > >> class C: > >> ? ? def method( self, arg ): > >> ? ? ? ? self.value = arg > >> ? ? ? ? return self.value > > >> I.e. explicit self stays only the syntax is slightly different and may > >> seem attractive to some. As pointed out by Guido classmethods would > >> work similarly: > > >> class C: > >> ? ? @classmethod > >> ? ? def cls.method( arg ): > >> ? ? ? ? cls.val = arg > >> ? ? ? ? return cls.val > > >> The fact that Guido says, > > >> "Now, I'm not saying that I like this better than the status quo. But > >> I like it a lot better than [...] but it has the great advantage that > >> it is backward compatible, and can be evolved into a PEP with a > >> reference implementation without too much effort." > > >> shows that the proposal is viable. > > >> I'd like this new way of defining methods, what do you guys think? > >> Anyone ready for writing a PEP? > > >> Cheers, > >> Daniel > > >> -- > >> Psss, psss, put it down! -http://www.cafepress.com/putitdown > > > I like it. > > > I'll even go a step further and suggest that "$" be allowed as a > > substitute for "self". It looks like a capital "S" (for Self), and it > > stands out clearly. It also makes code more succinct with no loss of > > readability. Think of the line wraps that could be avoided. > > It looks "ugly" simply because it is new to you. Once you get used to it, I'll bet it will look fine. And resemblance to another language is not a very good reason to reject it. From kay.schluehr at gmx.net Thu Dec 18 01:11:19 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Wed, 17 Dec 2008 22:11:19 -0800 (PST) Subject: Relative imports in Python 3.0 References: Message-ID: <6b46d826-6ff7-40ca-91a9-003cf3038962@u18g2000pro.googlegroups.com> On 17 Dez., 11:01, Nicholas wrote: > I am sure I am not the first to run into this issue, but what is the > solution? When you use 2to3 just uncomment or delete the file fix_import.py in lib2to3/fixes/ . From google at mrabarnett.plus.com Fri Dec 19 21:53:16 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 20 Dec 2008 02:53:16 +0000 Subject: Namespaces, multiple assignments, and exec() In-Reply-To: References: <200812200234.33852.research@johnohagan.com> Message-ID: <494C5E1C.7060205@mrabarnett.plus.com> Terry Reedy wrote: > John O'Hagan wrote: >> I have a lot of repetitive assignments to make, within a generator, >> that use a function outside the generator: >> >> var1 = func("var1", args) >> var2 = func("var2", args) >> var3 = func("var3", args) >> etc... >> >> In each case the args are identical, but the first argument is a >> string of the name being assigned. It works fine but I'd like to >> reduce the clutter by doing the assignments in a loop. I've tried >> using exec(): >> >> for name in name_string_list: >> exec(name + ' = func(\"' + name + '\", args)') >> >> but in the local namespace it doesn't understand func(), and if I give >> it globals() it doesn't understand the args, which come from within >> the generator. >> >> What's a good way to do this kind of thing? > > Put everything in your own namespace > > myvars={} > for name in namelist: > myvars[name]=func(name,args) > If you're sure you want to use the current namespace then: for name in namelist: vars()[name] = func(name, args) From jeremy+complangpython at jeremysanders.net Wed Dec 17 09:21:38 2008 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Wed, 17 Dec 2008 14:21:38 +0000 Subject: subprocess.Popen inheriting References: <0751c43b-57c8-4510-99d7-cdbf8a8f8426@a26g2000prf.googlegroups.com> Message-ID: Aaron Brady wrote: > I thought so too. The web seems to say that on Linux they are, and on > Windows, you need to call DuplicateHandle for it. I hit this problem - it looks like pipes aren't very versatile on Windows. There's also the complicating factor that the handles in windows aren't the same as the file numbers that Python uses, so you have to convert between them. It would be nice if Python created pipes that are properly inheritable by default by child processes, as they're mostly used for IPC. It was so painful that I converted my code to use sockets instead, which seem much more portable between Windows and Unix (though you don't get to use socketpair and AF_UNIX in Windows). Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From mal at egenix.com Thu Dec 4 05:22:34 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 04 Dec 2008 11:22:34 +0100 Subject: "as" keyword woes In-Reply-To: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> Message-ID: <4937AF6A.8030007@egenix.com> On 2008-12-04 06:42, Warren DeLano wrote: >>> Why can't the parser distinguish between a standalone " as " keyword >>> and ".as" used as an object/attribute reference? >> Because that would require special-casing some names as being >> forbidden in syntax where other names are allowed. Special cases in >> language syntax are to be avoided where feasible. > > Am I the only one picking up on the irony here? "as" exists largely to > provide a mechanism for working around namespace conflicts -- except, > apparently, conflicts involving "as". The fact that "as" itself creates > an insurmountable namespace collision is just killing me! How absurd. Up until "as" has been special for many Python releases, ever since we introduced the "from xyz import abc as def" notation, so there's nothing new there. Now, instead of keeping that special status, it was decided to make it a reserved word since there's a new use case in Python 2.6 for it as well - catching exceptions: >>> try: ... 1/0 ... except Exception as exc_object: ... print exc_object ... integer division or modulo by zero The Python developers always try very hard not to introduce new keywords to the language, but every now and then, it's better to go with the addition and cause some breakage. In this case, it's easy enough to find the files that break. Just run compileall.py on all your files and Python 2.6 will tell you which ones need fixing: python2.6 -c 'import compileall;compileall.compile_dir(".")' > Anyway, it seems obvious that the right decision for our customers (or > more importantly, for their countless lines of autogenerated-Python log, > state, and code files from the past decade) is to stick with C/Python > 2.5.x for the time being and plan to make the jump to a threads-capable > and hopefully backwards-compatible Python implementation as soon as > possible (IronPython perhaps?). That seems like a sensible path around > the breakage and enduring limitations of C/Python 2.6 or 3. This idea of CPython not being threads-capable is FUD. CPython works perfectly well in multi-threaded environments. There are, of course, situations where using a multi-threaded approach is not necessarily the right way to approach a problem. For those you now have the multiprocessing module which allows creating and managing multiple processes to spread the load: http://docs.python.org/library/multiprocessing.html This also avoids many of the problems you face with multi-threading, e.g. managing low-level object access using thread locks, dealing with non-thread-aware code, finding all the instances of objects that would require thread-lock-managed access, etc. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 04 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-12-02: Released mxODBC.Connect 1.0.0 http://python.egenix.com/ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From ylj798 at gmail.com Tue Dec 2 14:31:33 2008 From: ylj798 at gmail.com (ylj798 at gmail.com) Date: Tue, 2 Dec 2008 11:31:33 -0800 (PST) Subject: help me~!about base64 References: <0ff1ba7b-8a17-4647-99fc-9c8e32f83de7@g1g2000pra.googlegroups.com> Message-ID: <30641a03-51ee-456a-9c1a-1aba4e82d023@z6g2000pre.googlegroups.com> On 12?3?, ??3?26?, "Jerry Hill" wrote: > On Tue, Dec 2, 2008 at 2:08 PM, wrote: > >>>>print base64.__file__ > > /usr/lib/python2.5/base64.pyc > > That looks fine, and matches what I have on my linux box. Your code > works fine for me when I run it, so I'm out of ideas. > > -- > Jerry Thanks~! My system is ubuntu8.04 python2.5 eric4,you don't know that what about error? From petite.abeille at gmail.com Tue Dec 2 15:39:57 2008 From: petite.abeille at gmail.com (Petite Abeille) Date: Tue, 2 Dec 2008 21:39:57 +0100 Subject: Mathematica 7 compares to other languages In-Reply-To: References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: <1B1C50D7-13B3-4E4C-A87F-F4EB4D9C508C@gmail.com> On Dec 2, 2008, at 9:21 PM, Lew wrote: > These are professional software development forums, not some script- > kiddie cellphone-based chat room. "r" is spelled "are" and "u" should > be "you". While Xah Lee arguably represents a cross between "Enfant Provocateur" [1] and "Evil Clown" [2], this surely qualifies as a "Grammarian" [3] rebuke :D Cheers, -- PA. http://alt.textdrive.com/nanoki/ [1] http://redwing.hutman.net/~mreed/warriorshtm/enfantprovocateur.htm [2] http://redwing.hutman.net/~mreed/warriorshtm/evilclown.htm [3] http://redwing.hutman.net/~mreed/warriorshtm/grammarian.htm From Ron.Barak at lsi.com Sun Dec 21 06:41:42 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Sun, 21 Dec 2008 11:41:42 +0000 Subject: Best Practice using Glade/Python (ericericaro: message 1 of 20) In-Reply-To: <8ede3ba80812180547i3f48b032o6f7d0adab778c350@mail.gmail.com> References: <1b63220b-1572-4a8f-8f43-474ef8194bb0@s1g2000prg.googlegroups.com> <7F0503CD69378F49BE0DC30661C6CCF60249434B@enbmail01.lsi.com> <8ede3ba80812180547i3f48b032o6f7d0adab778c350@mail.gmail.com> Message-ID: <7F0503CD69378F49BE0DC30661C6CCF602494471@enbmail01.lsi.com> Hi Eric, Once the UI is defined, you interface to events as usual, e.g.: def OnSelChanged(self, evt): self.tablecont = str(self.GetItemText(evt.GetItem())) self.dprint(line()+". OnSelChanged:", self.tablecont) self.TreeViewController(self.tablecont) self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, self.tree) Bye, Ron. P.S.: I think you'd get better responses if you asked this question on wxpython-users at lists.wxwidgets.org ________________________________ From: Eric Atienza - eric at ericaro.net [mailto:+ericericaro+comverse+2e4452f01c.eric#ericaro.net at spamgourmet.com] Sent: Thursday, December 18, 2008 15:47 To: ericericaro.comverse at 9ox.net Subject: Re: Best Practice using Glade/Python (ericericaro: message 1 of 20) Hi, thank for the response (but it ain't in the usenet). I'm looking for best pratices about connecting 'events' from a glade defined UI, and python code. How to you manage it ? Eric http://codeslash.blogspot.com On Thu, Dec 18, 2008 at 2:25 PM, > wrote: Hi Eric, I'm not sure if I answer your question, but I designed wxPython GUI with wxGlade (http://wiki.wxpython.org/wxGlade). Bye, Ron. -----Original Message----- From: eric [mailto:eric at ericaro.net] Sent: Thursday, December 18, 2008 12:39 To: python-list at python.org Subject: Best Practice using Glade/Python Hi, I was wondering which is the "best practice" using glade/python, and, of course, especially the connect (both side). I didn't found that much documentation on the net ( too noisy), and the best "thing" I've found was http://www.linuxjournal.com/article/7558 which is a bit old now (2004). The article is very interesting BTW, but I was concerned by the fact it might be a little outdated. It smells like I'm missing something here, and that there have been a clean way to connect both (the autoconnect stuff does not seem that clean to me) for a long time now. So here is the question, do you practive galde/python, which is your practice ? Thanks Eric http://codeslash.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp at rebertia.com Sat Dec 27 14:33:40 2008 From: clp at rebertia.com (Chris Rebert) Date: Sat, 27 Dec 2008 11:33:40 -0800 Subject: parsing csv files class In-Reply-To: <49562755.6050205@byoteki.com> References: <49562755.6050205@byoteki.com> Message-ID: <47c890dc0812271133ia4471fav96d748d4c4a52fda@mail.gmail.com> On Sat, Dec 27, 2008 at 5:02 AM, Gary M. Josack wrote: > alex goretoy wrote: >> >> I know it's messy with all those self.soc.* functions, but it works in one >> of my current project. I just want to make it more pythonic I also want to >> add capability for makeing csv file if I give it input like: >> 1234,something nice, hey this is something nice >> 2468,something else, something else >> >> On Sat, Dec 27, 2008 at 4:54 AM, alex goretoy > > wrote: >> >> Hello All, >> >> I have this class that I use in one of my projects. I know it's >> missing functionality and some things could have been done >> differently. Can you ehlp me make this class better? What can I do >> to make it more resistant to error? You can find the >> stdout_colours class on Google if you want it, JFGI I want to make >> it more pythonic. I come from a PHP background, can you tell? >> >> Any and all help is appreciated >> -Alex >> >> #!/usr/bin/env python >> from ctypes import * >> import os, sys, types, csv, urllib, urllib2, urlparse, >> string,stdout_colours >> >> class parsercsvy(object): >> """Return a line from a csv file or total amount of lines""" > Do you know that there is a csv module in the standard library already? > > Thanks, > Gary M. Josack And here's a link to the docs for the `csv` module: http://docs.python.org/library/csv.html Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From grante at visi.com Mon Dec 22 23:35:42 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 22 Dec 2008 22:35:42 -0600 Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> <18767.47566.709705.92@montanaro-dyndns-org.local> Message-ID: <5uudnUmykoMD983UnZ2dnUVZ_rrinZ2d@posted.usinternet> On 2008-12-22, Joe Strout wrote: > Alvin ONeal wrote: > >> Also worthy of mention: >> I've seen python pre-installed on consumer HP desktops (I think as >> part of a backup/restore script, but I'm not sure) > > It's pre-installed on every Mac (both desktop and laptop), too. IIRC, Python came pre-installed on my IBM Thinkpad. However, it wasn't anyplace the average user would stumble across it... -- Grant From cwitts at gmail.com Tue Dec 2 07:09:44 2008 From: cwitts at gmail.com (Chris) Date: Tue, 2 Dec 2008 04:09:44 -0800 (PST) Subject: Checking a string against multiple matches References: <99a3a677-a38d-40f5-9a94-a98865150b69@k19g2000yqg.googlegroups.com> <200af09b-adba-4d8f-9ed9-2343030f9718@i24g2000prf.googlegroups.com> Message-ID: <376e669e-20b8-4734-a01e-e7a739362f8a@d23g2000yqc.googlegroups.com> On Dec 2, 3:01?am, alex23 wrote: > On Dec 2, 5:31?am, Aaron Scott wrote: > > > I was using .index on the > > list, but it would return True for strings that contained the search > > string rather than match it exactly, leading to false positives in my > > code. > > Are you sure? That doesn't seem like standard behaviour. > > >>> l = ["one", "two", "three", "four"] > >>> l.index('on') > > Traceback (most recent call last): > ? File "", line 1, in > ValueError: list.index(x): x not in list>>> l.index('thre') > > Traceback (most recent call last): > ? File "", line 1, in > ValueError: list.index(x): x not in list > > The only time I'd expect it to do partial matches is if you were doing > string.index(string), rather than list.index(string): > > >>> "four".index('our') > > 1 It would if the OP was iterating over the list and checking that item with .index so it uses the string.index instead of list.index From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 29 05:13:42 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 29 Dec 2008 11:13:42 +0100 Subject: Any equivalent to Ruby's 'hpricot' html/xpath/css selector package? In-Reply-To: References: Message-ID: <4958a2d7$0$15461$426a74cc@news.free.fr> Kenneth McDonald a ?crit : > Ruby has a package called 'hpricot' which can perform limited xpath > queries, ElementTree ? (it's in the stdlib now) > and CSS selector queries. PyQuery ? http://pypi.python.org/pypi/pyquery > However, what makes it really useful > is that it does a good job of handling the "broken" html that is so > commonly found on the web. BeautifulSoup ? http://pypi.python.org/pypi/BeautifulSoup/3.0.7a possibly with ElementSoup ? http://pypi.python.org/pypi/ElementSoup/rev452 From steve at REMOVE-THIS-cybersource.com.au Sun Dec 7 18:43:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 23:43:41 GMT Subject: how to get a beep, OS independent ? References: <3ca6fd77-e1b8-40f7-abd2-11a7cbd89469@d32g2000yqe.googlegroups.com> <493B9701.2040402@gmail.com> <47c890dc0812070134i7f9079e3rcc54d4cb55b01e63@mail.gmail.com> Message-ID: <014c575a$0$20670$c3e8da3@news.astraweb.com> On Sun, 07 Dec 2008 12:56:14 -0700, Joe Strout wrote: > On Dec 7, 2008, at 8:48 AM, Grant Edwards wrote: > >> On 2008-12-07, Joe Strout wrote: >> >>> But invoking the standard system beep >> >> What makes you think there is such a thing as "the standard system >> beep"? > > Because OS X (the platform with which I'm most familiar) certainly has > one, OS X, isn't that the operating system owned by Apple that runs on a handful of more-or-less identical varieties of hardware all controlled by Apple? > and REALbasic has had a "Beep" method for years which works on all > platforms. If RB can do it, we can do it too. That would be a standard language beep then, not a standard system beep. You're assuming that there is a standard way for any computer to make a sound. I don't think that is true. Of course, if you're volunteering to write such a standard system beep for Python, I for one would be grateful. -- Steven From wuwei23 at gmail.com Sat Dec 6 08:25:16 2008 From: wuwei23 at gmail.com (alex23) Date: Sat, 6 Dec 2008 05:25:16 -0800 (PST) Subject: To Troll or Not To Troll (aka: "as" keyword woes) References: <20081205163107.1815df40@usenot.de> <27945697-3f2f-452d-bed4-d1ca45d46fbb@r10g2000prf.googlegroups.com> <0149f5d8$0$20670$c3e8da3@news.astraweb.com> Message-ID: <6450388b-7181-43ba-b7ec-8cfe810f8ad4@r15g2000prd.googlegroups.com> On Dec 6, 2:22?pm, Steven D'Aprano wrote: > I see your wink, but, please, did you read that thread started by "r" > about the Ruby API for some piece of Google software? That was so > offensively fanboyish that I almost removed Python from my computer. The one wjere I was accused of wanting to hold back the evolution of Python amongst suggestions that I needed to get laid? Oh yeah, I saw it... I'm also not convinced it wasn't faux advocacy for the sake of trolling. From roy at panix.com Thu Dec 25 22:05:43 2008 From: roy at panix.com (Roy Smith) Date: Thu, 25 Dec 2008 22:05:43 -0500 Subject: How to stop subprocesses from copying listening sockets References: Message-ID: In article , Rick van Hattem wrote: > Recently I've started building a program that spawns new processes when > requested via http, since the http interface doesn't need to be fancy I've > just used the BaseHTTPServer module for this, but... it seems I'm running > into a little problem. When spawning a new process (which forks itself into a > daemon, but isn't too relevant in this case) the listening socket is copied > to the new process. The standard solution to this problem is to close all descriptors after forking and before doing the exec. You can tell subprocess.Popen() to do this by call it with "close_fds=True". From jason.scheirer at gmail.com Tue Dec 16 19:52:14 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Tue, 16 Dec 2008 16:52:14 -0800 (PST) Subject: WinMerge--B/W Shading of Printed Copy to Show Differences? References: <3jX1l.6876$pr6.3299@flpi149.ffdc.sbc.com> Message-ID: On Dec 16, 3:56?pm, "W. eWatson" wrote: > Is there a way to highlight differences between the two files when printing > in b/w? Help suggests there may be some texturing, but all I see is color > choices. > -- > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? W. eWatson > > ? ? ? ? ? ? ? (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > ? ? ? ? ? ? ? ?Obz Site: ?39? 15' 7" N, 121? 2' 32" W, 2700 feet > > ? ? ? ? ? ? ? ? ? ? ?Web Page: WinMerge is written in C++ and not even remotely related to Python. From google at mrabarnett.plus.com Thu Dec 4 15:30:29 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 04 Dec 2008 20:30:29 +0000 Subject: schizophrenic view of what is white space In-Reply-To: References: <4937E8E5.2090306@chamonix.reportlab.co.uk> <20081204143337.20272.1236189783.divmod.quotient.15592@ohm> <4938112F.5030706@chamonix.reportlab.co.uk> <49381C2E.3060707@mrabarnett.plus.com> Message-ID: <49383DE5.3030703@mrabarnett.plus.com> Terry Reedy wrote: > MRAB wrote: >> Robin Becker wrote: >>> Jean-Paul Calderone wrote: >>> ......... >>>> >>>> You have to give the re module an additional hint that you care about >>>> unicode: >>>> >>>> exarkun at charm:~$ python >>>> Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 >>>> (Ubuntu 4.2.3-2ubuntu7)] on linux2 >>>> Type "help", "copyright", "credits" or "license" for more information. >>>> >>> import re >>>> >>> print re.compile(r'\s').search(u'a\xa0b') >>>> None >>>> >>> print re.compile(r'\s', re.U).search(u'a\xa0b') >>>> <_sre.SRE_Match object at 0xb7dbb3a0> >>>> >>> >>>> >>>> Jean-Paul >>> ....... >>> >>> so the default behaviour differs for unicode and re working on >>> unicode. I suppose that won't be true in Python 3. >> > >> I'm not sure why the Unicode flag is needed in the API. I reckon that >> it should just look at the text that the regular expression is being >> applied to: if it's Unicode then follow the Unicode rules, if not then >> don't. > > I presume because \b is interpreted and replaced when the re is compiled > into internal state machine form. > The regular expression is compiled to codes which are then interpreted. There are 2 versions of the matcher, one for bytestrings and another for Unicode. I don't think that having it agnostic is too difficult to achieve. Interestingly, it treats every bytestring character as just a Unicode codepoint, so re.match(chr(0x80), unichr(0x80)) succeeds! I suppose it should complain if only one of the regex and the text is Unicode and the regex contains a literal or a literal character set (if the regex is, say, just \w then it doesn't matter). From simonharrison.uk at googlemail.com Mon Dec 8 05:44:56 2008 From: simonharrison.uk at googlemail.com (simonharrison.uk at googlemail.com) Date: Mon, 8 Dec 2008 02:44:56 -0800 (PST) Subject: Determining whether a variable is less/greater than a range. Message-ID: <362ab93b-b804-4ebe-a22f-e422feb301c8@c1g2000yqg.googlegroups.com> Hi. I'm having another go at learning Python so I'll probably be asking a few basic questions. Here is the first one. a = list(range(10, 21) b = 9 c = 21 How can I find out if b and c have values less or more than the values in list a? Thanks. From onlinejob4ind at gmail.com Thu Dec 25 03:43:17 2008 From: onlinejob4ind at gmail.com (kela) Date: Thu, 25 Dec 2008 00:43:17 -0800 (PST) Subject: Funny Christmas wallpapers, theme Message-ID: <315e8244-2e84-4a69-adce-0e5f36164cdd@r36g2000prf.googlegroups.com> Funny Christmas wallpapers, theme Free Funny Christmas Wallpaper Software Downloads Free Watch Software - StarBurn, Animated Funny Santa Clock Funny Christmas videos / Crazy Christmas Kick - Watch Santa Claus! http://funny-christmas-wallpaperws.blogspot.com/ From rschroev_nospam_ml at fastmail.fm Tue Dec 30 04:10:49 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue, 30 Dec 2008 10:10:49 +0100 Subject: get method In-Reply-To: References: <4de4faea-4237-4eb0-88d3-10884a72a0c9@v13g2000vbb.googlegroups.com> Message-ID: James Mills schreef: > Ross, the others have informed you that you are not > actually incrementing the count. I'll assume you've > fixed your function now :) ... I want to show you a far > simpler way to do this which takes advantage of > Python's list comprehensions and mappings (which are > really what dictionaries are): > >>>> s = "James Mills and Danielle Van Sprang" >>>> dict([(k, len([x for x in s if x == k])) for k in s]) > {'a': 5, ' ': 5, 'e': 3, 'd': 1, 'g': 1, 'i': 2, 'M': 1, 'J': 1, 'm': > 1, 'l': 4, 'n': 4, 'p': 1, 's': 2, 'r': 1, 'V': 1, 'S': 1, 'D': 1} Hm, you just changed an O(n) algorithm to an O(n**2) algorithm. No big deal for short strings, but try your solution on a string with length 10000 and see the difference. On my computer the O(n) version takes 0.008 seconds, while your version takes 8.6 seconds. That's 1000 times slower. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From nkanthikiran at gmail.com Sun Dec 7 08:58:45 2008 From: nkanthikiran at gmail.com (k.i.n.g.) Date: Sun, 7 Dec 2008 05:58:45 -0800 (PST) Subject: How to Write to csv file to create bulk address book Message-ID: <5387c7a1-eb04-4d27-826c-d6257298e2db@f40g2000pri.googlegroups.com> Hi , I am new to scripting, I am working on script which would create 'n' number address book entries into a csv file which would be used to import into a address book. I need suggestions for the same The fileds for csv file are as follows ""Title","First Name","Middle Name","Last Name","Suffix","Company","Department","Job Title","Business Street","Business Street 2","Business Street 3","Business City","Business State","Business Postal Code","Business Country","Home Street","Home Street 2","Home Street 3","Home City","Home State","Home Postal Code","Home Country","Other Street","Other Street 2","Other Street 3","Other City","Other State","Other Postal Code","Other Country","Assistant's Phone","Business Fax","Business Phone","Business Phone 2","Callback","Car Phone","Company Main Phone","Home Fax","Home Phone","Home Phone 2","ISDN","Mobile Phone","Other Fax","Other Phone","Pager","Primary Phone","Radio Phone","TTY/TDD Phone","Telex","Account","Anniversary","Assistant's Name","Billing Information","Birthday","Business Address PO Box","Categories","Children","Directory Server","E-mail Address","E- mail Type","E-mail Display Name","E-mail 2 Address","E-mail 2 Type","E- mail 2 Display Name","E-mail 3 Address","E-mail 3 Type","E-mail 3 Display Name","Gender","Government ID Number","Hobby","Home Address PO Box","Initials","Internet Free Busy","Keywords","Language","Location","Manager's Name","Mileage","Notes","Office Location","Organizational ID Number","Other Address PO Box","Priority","Private","Profession","Referred By","Sensitivity","Spouse","User 1","User 2","User 3","User 4","Web Page"" All the entries written by csv file by script can be random & dummy as this address book is used for testing purpose. Thank you in advance, Kanthi From gdamjan at gmail.com Sat Dec 13 23:01:58 2008 From: gdamjan at gmail.com (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Sun, 14 Dec 2008 05:01:58 +0100 Subject: File names, character sets and Unicode References: <49423DBB.9090401@logix.net.nz> Message-ID: > In a nutshell, this is likely to cause pain until all file systems are > standardized on a particular encoding of Unicode. Probably only about > another fifteen years to go ... well, most Linux distros are defaulting to a UTF-8 locale now, the exception beeing Gentoo&similar that expect the user to know what to configure - which he often doesn't :) but, yes, there's no way of enforcing that. -- ?????? ( http://softver.org.mk/damjan/ ) ... knowledge is exactly like power - something to be distributed as widely as humanly possible, for the betterment of all. -- jd From fetchinson at googlemail.com Wed Dec 24 23:31:44 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 24 Dec 2008 20:31:44 -0800 Subject: Easy-to-use Python GUI In-Reply-To: References: Message-ID: > Is there an easy-to-use, "function"-based cross-platform GUI toolkit for > Python out there that's a little more sophisticated than EasyGui? EasyGui > looks good, but it's a little more restrictive than what I'd like to have, > yet > I'm (stubbornly :-) ) resistant to stepping up to a "full service" GUI > toolkit > such as pyGTK or wxPython where it's all about event loops and callbacks and > you need to start planning how the GUI affects the overall program flow > rather > than just using a "forms" (or "Wizard")-type approach where you put up a few > dialogs, users fill in some variables, and your program just sits around > waiting until "OK" or "Cancel" is clicked. > > One approach that I like comes from SAX BASIC/WinWrap, which is more or less > a > clone of Microsoft's Visual BASIC for Applications, but they (apparently) > wanted everything to still be human-readable, so they have a simple GUI > ("form") builder that generates code that looks like this: > > --- > > Begin Dialog UserDialog 850,497,"Export Control" ' %GRID:10,7,1,1 > > GroupBox 20,7,360,217,"Drill File Generation",.GroupBox1 > CheckBox 40,35,130,14,"Output drill file(s)",.genDrill > Text 40,63,270,28,"Identify via layers as any that contain this text in > their names:",.Text > TextBox 40,98,220,21,.viaLayerName > Text 40,140,100,14,"Output method:",.Text8 > DropListBox 160,140,180,21,DrillStyle(),.drillStyle > Text 40,175,130,28,"Select drill table units:",.Text2 > ListBox 200,175,120,28,unitNames(),.unitName > > OKButton 310,469,90,21 > CancelButton 410,469,90,21 > > End Dialog > > ' GUI builder generates or modifies everything above, but can also be edited > by hand > ' You write the following code... > > Dim dlg As UserDialog > > dlg.genDrill = 1 > ReDim DrillStyle(1) > DrillStyle(0) = "All Via Layers In One File" > DrillStyle(1) = "One File Per Via Layer" > dlg.drillStyle = 1 > > func=Dialog(dlg) > > --- > > This is pretty darned easy for me understand and modify either by hand or > with > the GUI builder. Still, it's quite powerful, since it supports all the > common > GUI elements (text, group boxes, checkboxes, drop-down lists, text boxes, > buttons, etc.). This is about the level of sophistication I'm looking for. > > Anything like this for Python? How about the Tcl/Tk GUI that comes bundled with python? http://docs.python.org/library/tk.html Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From jstroud at mbi.ucla.edu Fri Dec 5 05:51:45 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 05 Dec 2008 02:51:45 -0800 Subject: dict subclass and pickle bug (?) In-Reply-To: References: Message-ID: <6J7_k.6212$hc1.5967@flpi150.ffdc.sbc.com> James Stroud wrote: > Hello All, > > I subclassed dict and overrode __setitem__. When instances are > unpickled, the __setstate__ is not called before the keys are assigned > via __setitem__ in the unpickling protocol. > > I googled a bit and found that this a bug filed in 2003: > > http://bugs.python.org/issue826897 > > It is still "open" with "normal" priority. Here is the ugly "fix" I'm basically going to have to live with, it seems: class DictPlus(dict): def __init__(self, *args, **kwargs): self.extra_thing = ExtraThingClass() dict.__init__(self, *args, **kwargs) def __setitem__(self, k, v): try: do_something_with(self.extra_thing, k, v) except AttributeError: self.extra_thing = ExtraThingClass() do_something_with(self.extra_thing, k, v) dict.__setitem__(self, k, v) def __setstate__(self, adict): pass This violates this: Beautiful is better than ugly. I can't imagine this bug has survived but I also can't imagine any better way to do this without specifying a different protocol, which would probably break other pickling I'm doing. I don't feel like finding out right now. Maybe repeal pep 307 ;o) James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From digitig at gmail.com Wed Dec 10 07:39:02 2008 From: digitig at gmail.com (Tim Rowe) Date: Wed, 10 Dec 2008 12:39:02 +0000 Subject: Don't you just love writing this sort of thing :) In-Reply-To: <493F028E.5050608@stoneleaf.us> References: <493F028E.5050608@stoneleaf.us> Message-ID: 2008/12/9 Ethan Furman : > Not all code has to be written for everyone. Not all code will be read by > the masses. Some code you write for yourself... an expression of who you > are, how you think... > > While my own quirks are not as visually entertaining, I think it's another > mark in Python's favor that such self-expression is possible, and > functional. > > Yes, Lawrence, I do love writing fun code. I did once get into a rivalry with a Perl programmer over obfusticating a coding exercise. I knew from the start that I had no chance, but I was impressed with how close-run I could make it with Python. Fun, yes, but no way anything I would consider for code that is actually going to be /used/ in any way whatsoever! -- Tim Rowe From martin at v.loewis.de Sat Dec 6 08:46:16 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 06 Dec 2008 14:46:16 +0100 Subject: Multiple Versions of Python on Windows XP In-Reply-To: References: <4934de22$0$27863$9b622d9e@news.freenet.de> <493592EE.9090005@v.loewis.de> <49378804.2050807@g.nevcal.com> <4937DB4B.7060001@ncf.ca> <4939C513.2090802@v.loewis.de> Message-ID: <493A8228.8010004@v.loewis.de> > SciTE doesn't do that, in the default configuration it just uses > whatever is called "pythonw" on the path, for running files having a .py > or .pyw suffix. I see. By default, Python does not put itself onto PATH. Does that mean that SciTE cannot run Python scripts in the default installation? Regards, Martin From lie.1296 at gmail.com Mon Dec 15 01:17:36 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 15 Dec 2008 06:17:36 +0000 (UTC) Subject: [OT] stable algorithm with complexity O(n) References: <6qidmbFc4qduU1@mid.uni-berlin.de> <0155aef3$0$6988$c3e8da3@news.astraweb.com> Message-ID: On Mon, 15 Dec 2008 01:48:43 +0000, Steven D'Aprano wrote: > Some things really don't have a solution, no matter how much power of > positive thinking you apply to it. Some may, only not with the current understanding of the universe. Well, I agree that there are a few things that is straight out nonsense, such as 4-angled triangle. And actually you've got the wrong message from the story, I hadn't intend it to be about positive thinking (as most motivators would exploit), it's more about thinking outside the current popular frame of minds. When you're not bound by everyone around you that says a task is impossible, you might have a better chance to solve the task (well, as long as the task *is* possible). What follows is a not-so-funny joke. Q: Construct a 4-angled triangle. A: Hmmm.... let's see... What about this? /\ / \ /____\ Q: That's just a regular triangle A: How about this? _____ | | | | |_____| Q: That's just a regular rectangle. A: This? /|\ / | \ /__|__\ Q: Well, still no luck, it's a triangle, but it have 5 sides A: Well... (after thinking for a moment) How about this? /----\ / \ / \ / \ -----------------/ \-------\ ---------------------------------------- Q: Perfect, just like what I wanted, but you shouldn't let the Python eat it. -- Le Petit Prince & aptitude & me From fuzzyman at gmail.com Tue Dec 23 07:29:42 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Tue, 23 Dec 2008 04:29:42 -0800 (PST) Subject: On Whose Desktop References: Message-ID: <018b649a-bcc6-4d5f-a7f2-e86231c89e74@i18g2000prf.googlegroups.com> On Dec 23, 12:06?pm, Steve Holden wrote: > Thanks to Barry Warsaw the "On Your Desktop" blog now has a new entry: > > ?http://onyourdesktop.blogspot.com/ > > Who would you like to see profiled next? > > regards > ?Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ Guido (of course), Brett Cannon, Martin v Loewis, Jim Hugunin, Ted Leung, Dino Viehland (core developer of IronPython), Titus Brown, Ivan Kristic, Mark Shuttleworth, Tim Golden, Michele Simionato, Thomas Heller, Greg Ewing - any and all of these would be great. Any women in Python you could ask - how about Anna Ravenscroft? Conspicuously missing from the ones you have already done is Steve Holden of course... All the best, Michael Foord -- http://www.ironpythoninaction.com/ From michele.simionato at gmail.com Thu Dec 4 05:07:31 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 4 Dec 2008 02:07:31 -0800 (PST) Subject: Pythonic design patterns References: Message-ID: <9c181e7f-469e-4794-aed5-99fae77ee911@g38g2000yqd.googlegroups.com> On Dec 4, 11:00?am, James Stroud wrote: > > The cookbook has a lot of complex examples and may not provide you with > the insight you are looking for. Only a small fraction of the recipes do > this. Whereas I agree that the online cookbook has too many complex recipes, as far I can remember most recipes in the printed version were quite generic and worth to study. Another good book I did not mention before is "Dive into Python" by Mark Pilgrim which is also available on line (Google is your friend). From stefan_ml at behnel.de Fri Dec 5 03:59:19 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 05 Dec 2008 09:59:19 +0100 Subject: Python C API In-Reply-To: <54fbb55d-3c39-459d-86a3-302b69721f0f@s20g2000yqh.googlegroups.com> References: <54fbb55d-3c39-459d-86a3-302b69721f0f@s20g2000yqh.googlegroups.com> Message-ID: <4938ed67$0$30227$9b4e6d93@newsspool1.arcor-online.net> googler.1.webmaster at spamgourmet.com wrote: > The first question is, I found out the API contains other commands lik > PyEval_AcquireLock(). I don't really understand if I have to use them > too, could anyone explain? Thanks. That's unrelated. The GIL is special in that it has its own handling functions. > void MyProgressbar(Real p, void* hook) // this function wil be called > in another thread > { > PyGILState_STATE gilstate = PyGILState_Ensure(); > > PyObject* func = (PyObject*)hook; > //do some python stuff > > PyGILState_Release(gilstate) > } > > PyObject *pyMyFunction(PyObject *pSelf, PyObject *args, PyObject > *keywords) > { > static char *kwlist[] = {"hook", NULL}; > > PyObject *hook=NULL; > > if (!PyArg_ParseTupleAndKeywords(args, keywords, "O!", kwlist, > &PyFunction_Type, &hook)) > return NULL; You have to release the GIL around the following function call, so that the thread above can acuire it while you wait for the function to return in this thread here (which I assume you do). > LONG ok = MyFunction(myprogress, hook); //hook is a pointer which > is passed to the threaded function. Stefan From atagar1 at gmail.com Sun Dec 28 18:06:18 2008 From: atagar1 at gmail.com (Damian Johnson) Date: Sun, 28 Dec 2008 15:06:18 -0800 Subject: Python 3.0 Curses Unicode Message-ID: Hi, I've switched to Python 3.0 for a new Japanese vocab quizzing application due to its much improved Unicode support. However, I'm running into an issue with displaying Unicode characters via curses. In Python 2.x a simple hello-world looks like: #!/usr/bin/python # coding=UTF-8 import curses import locale locale.setlocale(locale.LC_ALL,"") def doStuff(stdscr): message = u"hello ???!" stdscr.addstr(0, 0, message.encode("utf-8"), curses.A_BLINK) stdscr.getch() # pauses until a key's hit curses.wrapper(doStuff) This works. However, when I try to come up with an equivalent for Python 3.0: #!/usr/bin/python import curses import locale locale.setlocale(locale.LC_ALL,"") def doStuff(stdscr): message = "hello ???!" stdscr.addstr(0, 0, message, curses.A_BLINK) stdscr.getch() # pauses until a key's hit curses.wrapper(doStuff) It fails (printing gibberish to the console). Anyone have a clue what I'm doing wrong? Thanks! -Damian PS. Is the "# coding=UTF-8" header meaningless in Python 3.0? Also, is "locale.setlocale(locale.LC_ALL,"")" still necessary for getting curses to provide Unicode support? -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Tue Dec 30 15:41:17 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 30 Dec 2008 14:41:17 -0600 Subject: select.select and socket.setblocking References: <495a661d$0$11384$5fc30a8@news.tiscali.it> Message-ID: On 2008-12-30, Francesco Bochicchio wrote: > 3. AFAIK (sorry, I feel acronym-ly today ;), there is no difference in > select between blocking and non-blocking mode. The difference is in the > recv (again, assuming that you use TCP as protocol, that is AF_INET, > SOCK_STREAM), which in the blocking case would wait to receive all the > bytes that you requested, No, in blocking mode it will wait to receive _some_ data (1 or more bytes). The "requested" amount is strictly an upper limit: recv won't return more than the requested number of bytes, but it might return less. In non-blocking mode, it will always return immediately, either with some data, no data (other end closed), or an EAGAIN or EWOULDBLOCK error (I forget which). > [...] I myself tend to avoid using non-blocking sockets, since > blocking sockets are much easier to handle... That depends on whether you can tolerate blocking or not. In an event-loop, blocking is generally not allowed. -- Grant From skip at pobox.com Mon Dec 1 13:06:02 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 1 Dec 2008 12:06:02 -0600 Subject: optimization In-Reply-To: References: Message-ID: <18740.10122.833580.878015@montanaro-dyndns-org.local> Neal> I noticed in some profiling, that it seems that: Neal> def Func (): Neal> def something(): Neal> ... Neal> It appears that if Func is called many times, this nested func Neal> definition will cause significant overhead. Is this true? I Neal> guess I've become accustomed to decent compilers performing Neal> reasonable transformations and so have tended to write code for Neal> clarity. It could. OTOH, the code object which implements the something body is stored as a local var (or a constant, can't remember off the top of my head), so it's not compiled over and over again. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From python.list at tim.thechases.com Tue Dec 2 16:45:58 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 02 Dec 2008 15:45:58 -0600 Subject: Simple ini Config parser examples needed In-Reply-To: References: Message-ID: <4935AC96.4050402@tim.thechases.com> > I have a very simple ini file that I needs parsed. What is the best way I can parse an ini file that doesn't include sections? > > As in: > > person=tall > height=small > shoes=big > > > Thats it. Can anyone help me? The built-in ConfigParser module assumes at least one INI-style section, which if it's not present, issues a raise MissingSectionHeaderError As such, if you don't have any headers, you may have to hand-parse. However, that's not too bad: from sys import stderr options = {} for i, line in enumerate(file("simple.ini")): line = line.rstrip("\r\n").lstrip() if not line or line.startswith(';') or line.startswith('#'): continue # it's blank or a commented line if '=' in line: name, value = line.split('=', 1) options[name.rstrip().lower()] = value.strip() else: stderr.write("Malformed option at line #%i\n" % (i+1)) person = options.get("person", "some default person value") socks = options.get("socks", "some default sock value") do_something(person, socks) Adjust the strip() calls if you want to preserve odd white-spacing. -tkc From duncan.booth at invalid.invalid Thu Dec 4 04:01:30 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 4 Dec 2008 09:01:30 GMT Subject: Don't you just love writing this sort of thing :) References: Message-ID: Lawrence D'Oliveiro wrote: > for \ > Entry \ > in \ > sorted \ > ( > f for f in os.listdir(PatchesDir) if > PatchDatePat.search(f) != None > ) \ >: > Patch = (open, > gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir, > Entry), "r") ... read from Patch ... > Patch.close() > #end for > Have you ever considered trying to write readable code instead? Something like (untested): def patchfiles(dir, pattern): for f in os.listdir(dir): if pat.search(f) is not None: yield os.path.join(dir, f) def openpatch(name): if name.endswith(".gz"): return gzip.GzipFile(name, "r") return open(name, "r") for entry in sorted(patchfiles(PatchesDir, PatchDatePat): with openpatch(entry) as patch: ... read from patch ... (I must admit I haven't checked whether GZipFile works with the 'with' statement, but if it doesn't you just wrap it in contextlib.closing). -- Duncan Booth http://kupuguy.blogspot.com From joe at strout.net Fri Dec 19 12:01:42 2008 From: joe at strout.net (Joe Strout) Date: Fri, 19 Dec 2008 10:01:42 -0700 Subject: How to parsing a sequence of integers In-Reply-To: References: <494ba258$0$18998$426a74cc@news.free.fr> Message-ID: <494BD376.4000602@strout.net> Mensanator wrote: >> from __future__ import division >> >> at the top of the file. I put this at the top of all my Python files, >> whether I expect to be dividing or not. It just saves grief. > > If you want division to be floating point. > If, like me, you rarely do floating point > division and want the "/" to mean integer > division as God intended, then you don't > put from __future__ import division in your > source files. > > That's one of the good things about Python, > you can have it either way. Until you someday move up to Python 3, at which point you'll have to go back and change all your code to use the unambiguous // operator when you mean integer division. Better to do it now, I think, at least in any new code you write, to save you the hassle later. For those not familiar with the topic: Best, - Joe From hard4forget at gmail.com Sat Dec 6 16:19:10 2008 From: hard4forget at gmail.com (philips) Date: Sat, 6 Dec 2008 13:19:10 -0800 (PST) Subject: first time in the internet history a huge collection of funny pictures and videos over 10000 funny pics and videos download free on mobile format www.funreality.com Message-ID: first time in the internet history a huge collection of funny pictures and videos over 10000 funny pics and videos download free on mobile format www.funreality.com From clp at rebertia.com Sun Dec 21 18:53:28 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 21 Dec 2008 15:53:28 -0800 Subject: HMAC with RIPEMD-160 In-Reply-To: References: Message-ID: <47c890dc0812211553w645eae5dha85d5df364ea732a@mail.gmail.com> On Sun, Dec 21, 2008 at 4:21 AM, Kless wrote: > Is there any way of use HMAC with RIPEMD-160? > > Since that to create a ripemd-160 hash there is to use: > h = hashlib.new('ripemd160') > it looks that isn't possible > > For HMAC-SHA256 would be: > --------- > import hashlib > import hmac > > hm = hmac.new('key', msg='message', digestmod=hashlib.sha256) Untested, but should work according to the docs: hm = hmac.new('key', msg='message', digestmod=lambda: hashlib.new('ripemd160')) Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From casey.mcginty at gmail.com Fri Dec 5 17:26:17 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Fri, 5 Dec 2008 12:26:17 -1000 Subject: Project structure - Best practices In-Reply-To: References: <2d1f986f-94da-49c8-a1a5-df9457d5f8b3@r36g2000prf.googlegroups.com> Message-ID: > > This is first time that I am building python application that is > larger than a single module and I would like to do it right. I want to just say I am in agreement with the OP. Basically, there are a lot of factors to balance out and consider when starting a python application for the first time. For a new developer, tracking down this information is not a trivial task, as it is spread out over many location, or in worse cases, left up for the developer to "discover" on his/her own. I know it was not an easy task for me at first, and if we can make it easier for the next set of newcomeres, than that would be all the better. As far as open source projects go, the Python documentation is some of the best I've seen, however it would be nice to see a "Python Project Quick Start Guide" as part of the standard docs. The basics of this document would touch on packaging, imports, logging, testing, documenting, naming conventions, SCM, etc. Instead of rehashing the current docs, the focus would be on the combined integration of all of these features into a single code base. I realize that there is a wide range of preferences on specifics of each topic. But, just like PEP 8[1] is a good standard on code style, so would having a document as reference for other project-level "style" fundamentals. Ultimately, there could be a template project directory and source files that a user could build from. This is much more preferable to a blank directory, and might have the added benefit of influencing users to pick up recommended, but often ignored, practices at the beginning of a project. So, with all this said. I'd be willing to capture a lot of the methods I've picked up over the last couple months working with python. If anyone wants to add some suggestions, I'd love to have more discussion to organize thoughts and see if any new ideas come out. As a starting point, what is a good markup language to use for some slick HTML and PDF output? - Casey McGinty [1] http://www.python.org/dev/peps/pep-0008/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From 5lvqbwl02 at sneakemail.com Tue Dec 30 15:35:34 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Tue, 30 Dec 2008 12:35:34 -0800 (PST) Subject: Understanding search queries, semantics, and "Meaning" ...aren't we all looking for meaning? Message-ID: <82372457-2503-4682-96b3-37540328bf26@w39g2000prb.googlegroups.com> I have Section 4.4.1 of SICP rattling around in my head (database queries), and I'm trying to come up with a simple dictionary-based database in Python to represent circuit diagrams. My main confusion isn't one of implementation, but a matter of "big thinking", fundamentally, about the problem. Please don't suggest using a SQL library, as I'm looking to learn to fish, so to speak, and to learn a bit about the biology of fish. I've subclassed dict to hdict ("hashable dict") and rewritten the __hash__ function so I can include a dict into a set. Thanks to a previous poster here for providing that suggestion. A circuit component looks like this for example: comp1 = hdict(value=1e-6, footprint='0402', vendor='digikey') comp2 = hdict(value=10e3, footprint='0603', vendor='mouser') etc, etc. The database holds the values like this: db = dict() # normal dict db['value'] = ([1e-6, 10e3], [comp1, comp2]) #ordered set for fast lookup/insertion db['footprint'] = {'0402':set[comp1], '0603':comp2} # unordered uses normal dict for fast lookup db['vendor'] = {'digikey':[comp1], 'mouser':[comp2]} So basically the keys are the component parameters, and the values is the list of components with that value. Stuff that is comparable is ordered; stuff that is discrete is not ordered, using either 2-tuples or dicts, respectively. This allows extremely fast lookup of components based on their properties, with O(1) performance for non-ordered stuff, and O(log n) performance for ordered stuff (using bisect methods). The set operations are extremely fast, so I can do AND and OR operations on compound queries of this nature without worry. I need this speed not so much for selecting components when the user types in a query, but for when the mouse is hovering over the schematic and I need things to light up underneath, if the GUI is generating hundreds of mouse messages per second, and for inspector windows to appear quickly when you click, etc. If you have ever used Altium, you can see how effective this is in terms of creating a good interactive user experience. My question is what happens when I choose to search for NOT footprint='0402'. Should this return a blank list? This happens by default., and is in fact true: a blank list satisfies "not anything" actually. Should this return everything that is NOT footprint 0402 (ie returns 0603 components)? This *strongly implies* a pre-selection of *all* objects before performing the negating function, or of looking at the ordering of other queries in the overall search term, and then applying NOT to the results of another query. But I'm suspicious of a brute force preselection of all objects whenever I see a NOT, and anyway it messes up the clean query/combiner method of search I'm doing, and it requires an implied sequence of search, where I'm pretty sure it should not rely on sequencing. Even though this is single threaded, etc., the semantics of the query should not rely on ordering of the search term: footprint='0402' and NOT vendor='mouser' should return the same as NOT vendor='mouser' and footprint='0402'. So this is my philosophical quandary. I'm not sure what the correct thing is. In SICP they are using nondeterministic stuff which I don't quite get, so it's hard to follow. Also they are not using dictionaries and hashes, so I'm not sure if their generate-and-test method would work here anyway. Generate-and-test seems extremely inefficient. Can a wise guru please enlighten me? thanks Michael From ianare at gmail.com Tue Dec 16 11:48:50 2008 From: ianare at gmail.com (=?ISO-8859-1?B?aWFuYXLp?=) Date: Tue, 16 Dec 2008 08:48:50 -0800 (PST) Subject: Copying files in directory References: <2a815b7d-f01f-4666-bfc6-e9c43a75019b@t3g2000yqa.googlegroups.com> Message-ID: <7dbf8403-8a16-48c2-9744-7f8e9842b923@a37g2000pre.googlegroups.com> On Dec 15, 9:49?pm, pacsciad... at gmail.com wrote: > I'm writing a project management system, and I need the ability to > accept a directory name and move its contents to another directory. > Can someone give me a code sample that will handle this? I can't find > any "copying" functions in os or os.path. > > Regards, > LeafStorm shutil's move function does what you describe From n.kottiyath at gmail.com Mon Dec 22 09:57:55 2008 From: n.kottiyath at gmail.com (Kottiyath) Date: Mon, 22 Dec 2008 06:57:55 -0800 (PST) Subject: Event Driven programming - Doubts Message-ID: <80f360e4-2880-4c66-a6b4-e05d6dbc9031@b41g2000pra.googlegroups.com> Hi, I have been looking at Twisted and lately Circuits as examples for event driven programming in Python. Even though I understood how to implement the code in these and what is deferred etc, I have not yet understood the implementation of deferred. I went through a lot of tutorials, but I guess most places they expect that the user already understands how events are generated. The tutorials mention that there is no more threads once twisted is used. My question is as follows: I have not understood how the callbacks are hit without (a) blocking the code or (b) having new threads. The usual example given is that of a program waiting for data coming through a socket. In the tutorials, it is mentioned that -in an event driven program, we schedule the code to hit when the remote server gets back to us - . Now, my question is - somebody has to still wait on that socket and check whether the data is received, and once all the data is received, call the appropriate callbacks. Is twisted creating a micro-thread which just waits on the socket and once the data is received, calls callFromThread for it to run on the main loop? If so, Even though data locking etc is not a problem, are we not still having threads? Will it not still cause scalability problems in high traffic? If not, could somebody let me know how it is done? From psaffrey at googlemail.com Wed Dec 17 09:41:24 2008 From: psaffrey at googlemail.com (psaffrey at googlemail.com) Date: Wed, 17 Dec 2008 06:41:24 -0800 (PST) Subject: Selecting a different superclass Message-ID: This might be a pure OO question, but I'm doing it in Python so I'll ask here. I'm writing a number crunching bioinformatics application. Read lots of numbers from files; merge, median and munge; draw plots. I've found that the most critical part of this work is validation and traceability - "where does this final value come from? How has it been combined with other values? Is that right?" My current implementation stores all my values just as floats with a class called PointSet for storing one set of such values, with various mathematical and statistical methods. There are several subclasses of PointSet (IDPointSet, MicroArrayPointSet) for obtaining values from different file types and with different processing pipelines. I'm planning to instead store each value in a TraceablePoint class which has members that describe the processing stages this value has undergone and a TraceablePointSet class to store groups of these - this will contain all the same methods as PointSet, but will operate on TraceablePoints instead of floats. Of course, this will be much slower than just floats, so I'd like to be able to switch it on and off. The problem is that IDPointSet and MicroArrayPointSet will need to inherit from PointSet or TraceablePointSet based on whether I'm handling traceable points or not. Can I select a superclass conditionally like this in Python? Am I trying to do something really evil here? Any other bright ideas on my application also welcome. Peter From prologic at shortcircuit.net.au Thu Dec 11 21:02:21 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 12 Dec 2008 12:02:21 +1000 Subject: Bidirectional Networking In-Reply-To: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> References: <4c99c932-db78-44a7-87a3-d8d62f2c1d3b@i24g2000prf.googlegroups.com> Message-ID: Have a look at circuits. http://trac.softcircuit.com.au/circuits/ It's a general purpose event-driven framework with a focus on Component architectures and has a good set of Networking Components, specifically: circuits.lib.sockets * TCPServer * TCPClient * UDPServer * UDPClient (alias of UDPServer) With circuits, there is no such thing as: serve_forever() It'll try to stay out of your way as much as possible and let you define your own main event loop which could look like this: from circuits import Manager from circuits.lib.sockets import TCPServer, TCPClient manager = Manager() server =TCPServer(8000) client = TCPClient() manager += server manager += client ... while True: server.poll() client.poll() manager.flush() I hope this helps you! :) cheers James On Fri, Dec 12, 2008 at 10:33 AM, Emanuele D'Arrigo wrote: > Hi everybody! A networking question! > > I've been looking at and tinkering a little with the various > networking modules in python. The examples are pretty clear and a > module such as the SimpleXMLRPCServer is actually simple! > > All the examples though are based on a client interrogating a server, > with the client initiating the connection, obtaining something and > then closing the connection. Basically the server is a reactive party: > only if the client get in touch the server respond. What if the server > wanted to notify the client of something of interest, i.e. new data > that the client should take into consideration and potentially > process? > > One option would be for the client to periodically poll the server for > changes. Fair enough, that would work. But it'd be a bit of a waste if > the changes aren't particularly frequent. > > Is it possible then to establish both a server and a client in the > same application? I guess it must be possible but the examples all > rely on some kind of server loop (i.e. SocketServer.serve_forever) > that if started on both client and server sides would create two > listening parties but no talking at all! Furthermore, other libraries > might have their own loop, i.e. a graphical client has a loop to > redraw the screen and the two loops would somehow have to be > interleaved. > > I'm not quite seeing how this can be done other than we threads. Is > that the way to do it? Place the listening loop in a thread while the > rest of the application does its own thing? > > Or is it SocketServer.handle_request() the key? I could call this > function periodically, but what happens if a request is made while the > application is doing something else? Are the requests queued and dealt > with one per loop? > > Thanks for your help! > > Manu > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From steve at holdenweb.com Mon Dec 29 11:22:17 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 29 Dec 2008 11:22:17 -0500 Subject: math module for Decimals In-Reply-To: <4958F3C4.1050103@wi.rr.com> References: <4958F3C4.1050103@wi.rr.com> Message-ID: Raymond L. Buvel wrote: > Since the interest is more in extended precision than in decimal > representation, there is another module that may be of interest. > > http://calcrpnpy.sourceforge.net/clnum.html > > It interfaces to the Class Library for Numbers (CLN) library to provide > both arbitrary precision floating point and complex floating point > numbers and the usual math functions. > > While I am the author of this module, I agree with Mark that a module > based on MPFR would be better since you have better control over > precision and rounding. > > I have looked at Sage (which uses MPFR) but it is a huge integrated > package so you can't just import what you need into one of your usual > Python scripts. > > I wrote the clnum module mainly to support arbitrary precision in an RPN > calculator available from the same SourceForge project. However, it > also works nicely as a stand-alone module. > > At this time, there is no Windows installer available for Python 2.6 > because I don't use Windows at home and the person who normally builds > the installer for me is no longer interested. If someone wants to > follow the published instructions and send me the resulting installer, I > will put it up on SourceForge. > I'm not sure why nobody has mentioned gmpy, except possibly because it advertises its alpha status and doesn't have many active developers. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From yameenaziz at gmail.com Sat Dec 13 17:54:23 2008 From: yameenaziz at gmail.com (yameenaziz at gmail.com) Date: Sat, 13 Dec 2008 14:54:23 -0800 (PST) Subject: 1000 Earn Dollars $$$ Message-ID: <1810f9ce-41d1-4420-8b1b-c62a481680a2@y1g2000pra.googlegroups.com> "How To Make $1,000,000 THIS YEAR With our Online Business" From joe at strout.net Mon Dec 8 23:30:00 2008 From: joe at strout.net (Joe Strout) Date: Mon, 8 Dec 2008 21:30:00 -0700 Subject: A question about reference in Python. In-Reply-To: References: <493CB003.3080209@gmail.com> Message-ID: <5207FE9F-B50F-4B5B-8959-124BB0C93E65@strout.net> On Dec 8, 2008, at 7:43 PM, Steven D'Aprano wrote: > On Mon, 08 Dec 2008 08:18:27 -0700, Joe Strout wrote: > >> On Dec 7, 2008, at 10:26 PM, Group wrote: >> >>> Now, I want to write a Red-Black Tree, and a List structure. In C/C >>> + +, >>> I can >>> use pointers to refer to children notes (or next notes). But, in >>> Python, how >>> can I do it? Except the sequence, I know not any way. >> >> Any variable in Python is a reference > > Except that they don't behave like references in languages that have > explicit reference parameters. I didn't say anything about reference parameters (by which I believe you mean parameters passed by reference). I say a variable in Python IS a reference. And it is *exactly* like a reference parameter in any other modern OOP language, as I've clearly shown (http://www.strout.net/info/coding/valref/ ). That page also explains that Python's references are always passed by value; Python doesn't have a pass-by-reference mechanism, unlike (say) RB, C++, or .NET. This stuff really isn't that hard. > Did you not see the thread asking how to create reference parameters > in > Python? Subject "var or inout parm?". I noticed you were conspicuous > by > your absence in that little discussion. No, sorry, I missed that one. The volume of this group (plus the several other Python lists I subscribe to) requires me to skim a lot, and often choose not to read a thread at all. In this case, the subject caught my attention, and I saw that I could help clear up some confusion. Now that I've done that, I'll probably cease to read this thread any further, since as you say, we've been over this to death. Go ahead and try to confuse him if you insist. Hopefully he'll ignore that and see that Python is simple, and identical in its semantics to the languages he already knows. Best, - Joe From fakeaddress at nowhere.org Tue Dec 16 01:52:20 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 15 Dec 2008 22:52:20 -0800 Subject: Thread Locking issue - Can't allocate lock (sem_init fail) In-Reply-To: References: Message-ID: jamskip at googlemail.com wrote: [...] > The program is multithreaded to speed up the processing...there are > input and output Queues. It's not the major point here, but are you aware of Python's GIL? > Now, each domain entry is an class object containing various bits of > info. Each domain class also has its own lock, so that only one thread > can modify each domain at a time. > > I'm load-testing the program with a sample of 1 million email > addresses and when i hit about the 500,000 mark i get a locking > error... Does that correspond to creating 500,000 locks? For sure? > sem_init: No space left on device [...] > error: can't allocate lock What happens if you try to allocate a million locks, as in: from threading import Lock locks = [] for i in range(10**6): try: locks.append(Lock()) locks[-1].acquire() except: print "Failed after %d locks." % i raise I tried the above in WindowsXP and Ubuntu 8.04 (Python 2.6 and 2.52 respectively), and it ran on both without the exception. > Googling for this sort of error doesn't yield any results, and i can't > find any information about limits to the number of locks you can have > in Python. The 'No space left on device' message indicates a memory > issue, however i doubt this since its running on a linux server with 4 > cores and 16GB ram. It seems more like an internal Python limit has > been hit (sem_init - semaphore initialisation?). Does anyone know more > about threading internals and any internal limits? Python treading is implemented on top of some thread facility the target O.S. provides. Creating a Python lock may or may not use up some limited kernel resource. Given my experiments, limited as they were I do not think this is a Python limit. If could be an issue with your platform, or a defect in the code you inherited. > For the timebeing, I've implemented locking at a higher level which > will reduce performance but keep the number of lock objects to a > minumum. That's probably a reasonable strategy whether or not you can create a million locks. -- --Bryan From lists at cheimes.de Sun Dec 21 14:01:12 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 21 Dec 2008 20:01:12 +0100 Subject: New Python 3.0 string formatting - really necessary? In-Reply-To: References: <3e1973d1-0fbc-4b35-a9c3-d7e4d7910a4f@z6g2000pre.googlegroups.com> <29dddf46-dd5f-4c61-bc9b-d24ce726dcb9@v39g2000pro.googlegroups.com> <3ad5c48a-494f-4873-bcfd-6299e620f7fa@j39g2000yqn.googlegroups.com> Message-ID: Patrick Mullen schrieb: > 2) In my experience, major version changes tend to be slower than > before. When a lot of things change, especially if very low-level > things change, as happened in python 3.0, the new code has not yet > went through many years of revision and optimization that the old code > has. In my opinion, python 3 was rushed out the door a bit. It could > have done with a few more months of optimization and polishing. > However, on the other hand, it is going to take so long for python > infrastructure to convert to python 3, that an earlier release makes > sense, even if it hasn't been excessively polished. The biggest > reason for the speed change is the rewritten stdio and > unicode-everything. Hopefully this stuff can be improved in future > updates. I don't think anyone WANTS cpython to be slower. The 3.0 release targets third party developers. Authors of 3rd party extensions and libraries need a stable API to port their software to a new major release. The main objective was feature completeness and stability. If you need speed either stick to the 2.x series or wait until 3.1 is out. We could have waited a few more months or even a few more years with a 3.0 release. There is always - I repeat ALWAYS - work to do. For an open source project like Python "release early, release often" works better. Christian From excord80 at gmail.com Fri Dec 19 15:04:58 2008 From: excord80 at gmail.com (excord80) Date: Fri, 19 Dec 2008 12:04:58 -0800 (PST) Subject: Building a web questionnaire, can it be done in Python ? References: Message-ID: On Dec 19, 11:58?am, Stef Mientki wrote: > hello, > > I'm considering building a web questionnaire in Python. > I've made several desktop applications in Python / ?wxPython, > but I've no experience in using Python on a webserver, > and I don't have much knowledge about web applications in general. > Ah. You want to report directly to the Django tutorial: http://docs.djangoproject.com/en/dev/intro/tutorial01/ From steve at REMOVE-THIS-cybersource.com.au Sun Dec 7 18:37:32 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2008 23:37:32 GMT Subject: Rich Comparisons Gotcha References: <014c51d9$0$20670$c3e8da3@news.astraweb.com> Message-ID: <014c55e9$0$20670$c3e8da3@news.astraweb.com> On Sun, 07 Dec 2008 23:20:12 +0000, Steven D'Aprano wrote: > On Sun, 07 Dec 2008 15:32:53 -0600, Robert Kern wrote: > >> Rasmus Fogh wrote: >> >>> Current behaviour is both inconsistent and counterintuitive, as these >>> examples show. >>> >>>>>> x = float('NaN') >>>>>> x == x >>> False >> >> Blame IEEE for that one. Rich comparisons have nothing to do with that >> one. > > There is nothing to blame them for. This is the correct behaviour. NaNs > should *not* compare equal to themselves, that's mathematically > incoherent. Sorry, I should explain why. Given: x = log(-5) # a NaN y = log(-2) # the same NaN x == y # Some people want this to be true for NaNs. Then: # Compare x and y directly. log(-5) == log(-2) # If x == y then exp(x) == exp(y) for all x, y. exp(log(-5)) == exp(log(-2)) -5 == -2 and now the entire foundations of mathematics collapses into a steaming pile of rubble. -- Steven From google at mrabarnett.plus.com Wed Dec 31 11:57:59 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 31 Dec 2008 16:57:59 +0000 Subject: How to initialize an array with a large number of members ? In-Reply-To: <5m4nl4hs8f9q6rfcp7b1jt7nk1o6sq6r0f@4ax.com> References: <5m4nl4hs8f9q6rfcp7b1jt7nk1o6sq6r0f@4ax.com> Message-ID: <495BA497.9020508@mrabarnett.plus.com> David at bag.python.org wrote: > Thanks to those who have helped a beginner in > Python. Using version 3.0 > > # script23 > from array import array > < see failed initialization attempts below > > > tally = array('H',for i in range(75) : [0]) > > tally = array('H',[for i in range(75) : 0]) > > tally = array('H',range(75) : [0]) > > tally = array('H',range(75) [0]) > > Above give either Syntax error or TypeError > > All examples of sequences in docs show only > a few members being initialized. Array doc > says an iterator can be used, but doen't show > how. What would you do for a 2 dimensional > array ? Incorporate c code ? > The online docs are clearly insufficient for a > novice. Have ordered Summerfields new book. > >>> # With a list >>> tally = array('H', [0] * 75) >>> >>> # With a generator >>> tally = array('H', (0 for i in range(75))) From george.sakkis at gmail.com Wed Dec 10 14:51:51 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 10 Dec 2008 11:51:51 -0800 (PST) Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: On Dec 10, 1:42?pm, cm_gui wrote: > http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-... > > I fully agree with Krzysztof Kowalczyk . > Can't they build a faster VM for Python since they love the language > so much? WTF is Krzysztof Kowalczyk and why should we care ? Thanks for playing, the exit for the trolls is right down the hall. From macc_200 at yahoo.co.uk Sat Dec 6 12:43:05 2008 From: macc_200 at yahoo.co.uk (macc_200) Date: Sat, 6 Dec 2008 17:43:05 +0000 (GMT) Subject: operators as variables Message-ID: <103920.71204.qm@web26006.mail.ukl.yahoo.com> Hi, just starting programming and have an elementary?question after playing around with lists but cannot find the answer with googling. I have a list?of variables?and I would like some of those variables to be integers and some to be?operators so the list would look something like [5?* 4?-?4 + 6] and then be able to evaluate the result (i.e. get 10).? How do you make the interpreter see the operator as that instead of a string and just echo the list back to me. thanks, Andy (and suggestions for a decent Python book would be appreciated) -------------- next part -------------- An HTML attachment was scrubbed... URL: From BrooklineTom at gmail.com Wed Dec 10 13:59:16 2008 From: BrooklineTom at gmail.com (brooklineTom) Date: Wed, 10 Dec 2008 10:59:16 -0800 (PST) Subject: Deeper tracebacks? Message-ID: I want my exception handler to report the method that originally raised an exception, at the deepest level in the call-tree. Let give an example. import sys, traceback class SomeClass: def error(self): """Raises an AttributeError exception.""" int(3).zork() def perform_(self, aSelector): try: aMethod = getattr(self, aSelector, None) answer = apply(aMethod, [], {}) except: AttributeError, anAttributeErrorException: aRawStack = traceback.extract_stack() answer = None When I call "perform_" (... SomeClass().perform_('error')), I want to collect and report the location *within the method ("error") that failed*. The above code reports the location of "perform_", and no deeper in the call tree. Anybody know how to accomplish this? From vedranf at vedranf.mine.nu Fri Dec 19 06:16:44 2008 From: vedranf at vedranf.mine.nu (=?ISO-8859-1?Q?Vedran_Furac=28?=) Date: Fri, 19 Dec 2008 12:16:44 +0100 Subject: List comprehension in if clause of another list comprehension Message-ID: Hi! In [69]: a = 'a b c' In [70]: b = 'a b, c d' In [74]: [i for i in a.split() if i not in b.split()] Out[74]: ['b'] Everything ok. In [77]: b.split() == [i for i in b.split()] Out[77]: True As expected. Now, put this in the first list comprehension: In [80]: [i for i in a.split() if i not in [i for i in b.split()] ] Out[80]: ['d'] Hmmmm... why is that? Regards! From samslists at gmail.com Sat Dec 27 04:19:36 2008 From: samslists at gmail.com (Sam) Date: Sat, 27 Dec 2008 01:19:36 -0800 (PST) Subject: Parsing a sitemap library? Message-ID: <0e9d5499-9c42-45ea-8060-2f73e199f8f9@z27g2000prd.googlegroups.com> Hi... I see an awful lot of code out there to create sitemaps using Python. But I can't find anything to consume sitemaps using Python. Is there a library to convert sitemaps and sitemap indexes of sitemaps into something more Pythonic? I know I can write one pretty easily using e.g. Beautiful Soup or maybe lxml, but I never like to reinvent the wheel. Thanks From wojciech_mula at poczta.null.onet.pl.invalid Sat Dec 13 14:04:02 2008 From: wojciech_mula at poczta.null.onet.pl.invalid (Wojciech =?ISO-8859-2?Q?Mu=B3a?=) Date: Sat, 13 Dec 2008 20:04:02 +0100 Subject: [OT] stable algorithm with complexity O(n) References: Message-ID: <20081213200402.952cad5d.wojciech_mula@poczta.null.onet.pl.invalid> "David Hl??ik" wrote: > I have to create stable algorithm for sorting n numbers from interval > [1,n^2] with time complexity O(n) . Some kind of radix sort or counting sort. These algo. has O(n) complexity. w. From nomadoro at gmail.com Fri Dec 12 07:11:46 2008 From: nomadoro at gmail.com (Lee Soin) Date: Fri, 12 Dec 2008 20:11:46 +0800 Subject: How to write binary data to file and socket Message-ID: Hello, all! I'm new to python. In Linux C programming, writing data to file and socket share the same system call "write". But it seems that only data of string type can be used for "write" and "send". So how to write binary data to file and socket? -- Sun Li Department of Physics Nanjing University, China -------------- next part -------------- An HTML attachment was scrubbed... URL: From anonymous.c.lisper at gmail.com Mon Dec 1 17:53:50 2008 From: anonymous.c.lisper at gmail.com (anonymous.c.lisper at gmail.com) Date: Mon, 1 Dec 2008 14:53:50 -0800 (PST) Subject: Mathematica 7 compares to other languages References: <13d5dff7-9aac-4385-91ee-d6e58177497f@i24g2000prf.googlegroups.com> Message-ID: On Nov 30, 10:30?pm, Xah Lee wrote: > some stuff You are a bot? I think you failed the Turing test when you posted the same thing 20 times. A rational human would realize that not too many people peruse this newsgroup, and that most of them have already seen the wall of text post that you generate every time. Just a thought, but whoever owns this thing might want to rework the AI. From Rick at youtellme.com Thu Dec 25 22:17:19 2008 From: Rick at youtellme.com (Rick van Hattem) Date: Fri, 26 Dec 2008 04:17:19 +0100 Subject: dummy needs help with Python In-Reply-To: References: Message-ID: <200812260417.19137.Rick@youtellme.com> On Friday 26 December 2008 03:24:41 MLDSpenser at aol.com wrote: > I don't have time to work my way through the online Python tutorial. I've > tried a couple of forums but nobody has answered my questions. There are loads of Python tutorials on the net, some will teach you the basics in 5 minutes, others will give you a more thorough understanding in a couple of days. But it shouldn't be that hard I'd say, if you want it fast than I'd recommend this one: http://hetland.org/writing/instant-python.html > A simple > program with comments that say "here's where I read File A and define/map/ > the fields in it" would let me learn by testing and trying things out, the > same way I learned to work with the fields in the module. Here's a little example program, it's actually quite simple ;) import csv csv_reader = csv.reader(open('spam.csv')) for row in csv_reader: print row That will print all the rows in the file, if you want to extract the specific fields you could do something like this: for a, b, c in csv_reader: print a, b, c Where a, b and c are the fields (I'd recommend a more useful name though). For writing a csv the process is similar, but open it like this and use writerow: csv_writer = csv.writer(open('eggs.csv', 'w')) Hopefully that helps :) From pavlovevidence at gmail.com Mon Dec 22 17:18:44 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 22 Dec 2008 14:18:44 -0800 (PST) Subject: python3 urlopen(...).read() returns bytes References: <81b4fdc1-b61c-42f9-bfab-916652429adc@b41g2000pra.googlegroups.com> Message-ID: <31982ad6-8567-42c0-a8bb-083e61fbd0e2@a29g2000pra.googlegroups.com> On Dec 22, 3:41?pm, "Glenn G. Chappell" wrote: > I just ran 2to3 on a py2.5 script that does pattern matching on the > text of a web page. The resulting script crashed, because when I did > > ? ? f = urllib.request.urlopen(url) > ? ? text = f.read() > > then "text" is a bytes object, not a string, and so I can't do a > regexp on it. > > Of course, this is easy to patch: just do "f.read().decode()". > However, it strikes me as an obvious bug, which ought to be fixed. > That is, read() should return a string, as it did in py2.5. Well, I can't agree that it's an obvious bug (in Python 3). It might be something worth raising a warning over in 2to3. It would also be a reasonable wishlist item for automatic encoding detection and conversion to a string (see below). But it's not a bug. > But apparently others disagree? This was mentioned in issue 3930 > (http://bugs.python.org/issue3930) back in September '08, but that > issue is now closed, apparently because consistent behavior was > achieved. But I figure consistently bad behavior is still bad. > > This change breaks pretty much every Python program that opens a > webpage, doesn't it? No. What if someone is using urllib retrieve (say) a JPEG image? A bytes object is what they'd want in Python 3. Also, many people were already explicitly dealing with encodings in Python 2.5; the change wouldn't affect them. > 2to3 doesn't catch it, and, in any case, why > should read() return bytes, not string? Am I missing something? It returns bytes because it doesn't know what encoding to use. This is the appropriate behavior. HOWEVER... a web page request often does know what encoding to use, since it ostensibly has to parse the header. It's reasonable that IF a url request's "Content-type" is text, and/or the "Content-encoding" is given, for urllib to have an option to automatically decode and return a string instead of bytes. (For all I know, it already can do that.) Carl Banks From tino at wildenhain.de Mon Dec 1 10:20:56 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 01 Dec 2008 16:20:56 +0100 Subject: finding the difference between the two version of the python program... In-Reply-To: <19ac19520812010430s7e0e11a6sf787ca1f73e87f36@mail.gmail.com> References: <19ac19520812010430s7e0e11a6sf787ca1f73e87f36@mail.gmail.com> Message-ID: <493400D8.8070203@wildenhain.de> Hi, Piyush Anonymous wrote: > is there a tool which, given two version of programs, finds the > difference like set of classes added, deleted and modified? > assuming the python program is written in oops way. diff for example can do this. There is also an difflib in python which you can use to roll your own diff. Regards TIno -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From jstroud at mbi.ucla.edu Sun Dec 7 16:57:54 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 07 Dec 2008 13:57:54 -0800 Subject: Rich Comparisons Gotcha In-Reply-To: References: Message-ID: Rasmus Fogh wrote: > Current behaviour is both inconsistent and counterintuitive, as these > examples show. > >>>> x = float('NaN') >>>> x == x > False Perhaps this should raise an exception? I think the problem is not with comparisons in general but with the fact that nan is type float: py> type(float('NaN')) No float can be equal to nan, but nan is a float. How can something be not a number and a float at the same time? The illogicality of nan's type creates the possibility for the illogical results of comparisons to nan including comparing nan to itself. >>>> ll = [x] >>>> x in ll > True >>>> x == ll[0] > False But there is consistency on the basis of identity which is the test for containment (in): py> x is x True py> x in [x] True Identity and equality are two different concepts. Comparing identity to equality is like comparing apples to oranges ;o) > >>>> import numpy >>>> y = numpy.zeros((3,)) >>>> y > array([ 0., 0., 0.]) >>>> bool(y==y) > Traceback (most recent call last): > File "", line 1, in > ValueError: The truth value of an array with more than one element is > ambiguous. Use a.any() or a.all() But the equality test is not what fails here. It's the cast to bool that fails, which for numpy works like a unary ufunc. The designers of numpy thought that this would be a more desirable behavior. The test for equality likewise is a binary ufunc and the behavior was chosen in numpy for practical reasons. I don't know if you can overload the == operator in C, but if you can, you would be able to achieve the same behavior. >>>> ll1 = [y,1] >>>> y in ll1 > True >>>> ll2 = [1,y] >>>> y in ll2 > Traceback (most recent call last): > File "", line 1, in > ValueError: The truth value of an array with more than one element is > ambiguous. Use a.any() or a.all() I think you could be safe calling this a bug with numpy. But the fact that someone can create a bug with a language is not a condemnation of the language. For example, C makes it real easy to crash a program by overrunning the limits of an array, but no one would suggest to remove arrays from C. > Can anybody see a way this could be fixed (please)? I may well have to > live with it, but I would really prefer not to. Your only hope is to somehow convince the language designers to remove the ability to overload == then get them to agree on what you think the proper behavior should be for comparisons. I think the probability of that happening is about zero, though, because such a change would run counter to the dynamic nature of the language. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From skip at pobox.com Wed Dec 24 11:02:47 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 24 Dec 2008 10:02:47 -0600 Subject: =?ISO-8859-1?Q?object_ori=EBnted?= In-Reply-To: References: Message-ID: <18770.23847.437473.79825@montanaro-dyndns-org.local> Dennis> I know that python is an Object Ori?nted language but I was Dennis> wondering if it gets used as a non-OOP also (by a good amount of Dennis> people). Oh yeah. Works great for writing quick-n-dirty Unix filters which are a bit more complex than can comfortably be wrangled with Bash, but not so complex that you need more organization (such as classes). A function looping over sys.stdin. Make a few transformations and away you go. -- Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/ From nick at craig-wood.com Tue Dec 9 07:30:52 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 09 Dec 2008 06:30:52 -0600 Subject: Learning Python now coming from Perl References: Message-ID: Roy Smith wrote: > In article , > Nick Craig-Wood wrote: > > > My favourite mistake when I made the transition was calling methods > > without parentheses. In perl it is common to call methods without > > parentheses - in python this does absolutely nothing! pychecker does > > warn about it though. > > > > perl -> $object->method > > python -> object.method() > > On the other hand, leaving out the parens returns the function itself, > which you can then call later. I've often used this to create data-driven > logic. I didn't say it wasn't useful, just that if you came from Perl like I did, it is an easy mistake to make ;-) > For example, I'm currently working on some code that marshals objects of > various types to a wire protocol. I've got something like: > > encoders = { > SM_INT: write_int, > SM_SHORT: write_short, > SM_FLOAT: write_float, > # and so on > } > > class AnyVal: > def __init__(self, type, value): > self.type = type > self.value = value > > def write_anyval(any): > encoders[any.type](any.value) > > The fact that functions are objects which can be assigned and stored in > containers makes this easy to do. OO lore says whenever you see a type field in an instance you've gone wrong - types should be represented by what sort of object you've got, not by a type field. Eg http://www.soberit.hut.fi/mmantyla/BadCodeSmellsTaxonomy.htm """The situation where switch statements or type codes are needed should be handled by creating subclasses. """ Here is my first iteration (untested) class AnyVal: def __init__(self, value): self.value = value def write(self): raise NotImplementedError() class IntVal(AnyVal): def write(self): # write_int code class ShortVal(AnyVal): def write(self): # write_short code class FloatVal(AnyVal): def write(self): # write_float code Then to write an AnyVal you just call any.write() The initialisation of the AnyVals then becomes from AnyVal(int_expression, SM_INT) to IntVal(int_expression) However, if the types of the expressions aren't known until run time, then use a dict of class types AnyValRegistry = { SM_INT: IntVal, SM_SHORT: ShortVal, SM_FLOAT: FloatVal, # and so on } And initialise AnyVal objects thus any = AnyValRegistry[type](value) This smells of code duplication though and a real potential for a mismatch between the AnyValRegistry and the actual classes. I'd probably generalise this by putting the type code in the class and use a __metaclass__ to autogenerate the AnyValRegistry dict which would then become an attribute of AnyClass Eg (slightly tested) SM_INT=1 SM_SHORT=2 SM_FLOAT=3 class AnyVal(object): TYPE = None registry = {} class __metaclass__(type): def __init__(cls, name, bases, dict): cls.registry[cls.TYPE] = cls def __init__(self, value): self.value = value @classmethod def new(cls, type_code, value): """Factory function to generate the correct subclass of AnyVal by type code""" return cls.registry[type_code](value) def write(self): raise NotImplementedError() class IntVal(AnyVal): TYPE = SM_INT def write(self): # write_int code print "int", self.value class ShortVal(AnyVal): TYPE = SM_SHORT def write(self): # write_short code print "short", self.value class FloatVal(AnyVal): TYPE = SM_FLOAT def write(self): # write_float code print "float", self.value You then make new objects with any = AnyVal.new(type_code, value) and write them with any.write() Anyone can add a subclass of AnyVal and have it added to the AnyVal.registry which is neat. >>> any = AnyVal.new(SM_SHORT, 1) >>> any <__main__.ShortVal object at 0xb7e3776c> >>> any.write() short 1 >>> any = AnyVal.new(SM_FLOAT, 1.8) >>> any <__main__.FloatVal object at 0xb7e37a6c> >>> any.write() float 1.8 You could also override __new__ so you could write AnyVal(type_code, value) to create the object of a new type. I personally don't think its is worth it - a factory function is nice and obvious and show exactly what is going on. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From wanshizhao2 at gmail.com Sat Dec 13 15:47:13 2008 From: wanshizhao2 at gmail.com (www.toptog.com) Date: Sat, 13 Dec 2008 12:47:13 -0800 (PST) Subject: www.toptog.comnike sneaker jordan retro gucci prada timberland lacsote Message-ID: www.toptog.com Here we can supply you 1. All kinds of jerseys: NFL Jerseys, NBA Jerseys, NHL Jerseys, MLB Jerseys, SOCCER Jerseys, etc. 2. All brands of shoes: obama nike sneaker,jordan 6 ring,Bape-star, Nike-Air-Max, Nike-Shox, Air-Force-One, Nike-Clear-Shoes, Nike-Air- Jordan1-24, Timberland-Boots, Icecream-Shoes, Puma, DG, Adidas, Gucci, Prada, Chanel, LV, Dsqared, Paciotti-4us, DSK, Football, Locaste, etc. 3. All Categories of Apparel & Fashion: T-shirt, Hoody, (www.toptog.com) Lacoste,edhardy, Jeans, Jackets, A&F-Coats, NFL, NBA, MLB ect. (www.toptog.com) 4. Handbags: Juicy-Couture, Burberrys, Hermes, Balenciaqa, Prada, Chloe, Coach, Gucci, Chanel, FD, LV etc. (www.toptog.com) 5. Jeweler: Tiffany, Gucci, 100% Silver, Stone, Jade With Gold etc. 6. Others: Caps, sunglasses, Belts, Watches, perfumes, etc. Do not hesitate to contact us! website www.toptog.com From guruyaya at gmail.com Tue Dec 16 16:58:02 2008 From: guruyaya at gmail.com (guruyaya) Date: Tue, 16 Dec 2008 13:58:02 -0800 (PST) Subject: What does the at sign do? Message-ID: I'm reading a lot of python code lately, django code to be exact, and I keep bumping into expressions that look like this @register.filter I see nothing importing @register, so I assume it's not just a function name. Yet I cannot figure where this @ sign came from. I hope I'm not just forgetting something out of the very basics. Thanks in advance Yaya From zxo102 at gmail.com Mon Dec 29 08:49:42 2008 From: zxo102 at gmail.com (zxo102) Date: Mon, 29 Dec 2008 05:49:42 -0800 (PST) Subject: How to display Chinese in a list retrieved from database via python References: <22be506d-91c2-4727-ace7-2e3382b6d214@g3g2000pre.googlegroups.com><979fdf6d-0500-47ba-87fd-0f0361ca3059@p2g2000prf.googlegroups.com><19680ed2-c78f-4ab9-8ca0-8ce26fd5b6a7@o4g2000pra.googlegroups.com> <2560a6e0-c103-46d2-aa5a-8604de4d1968@b38g2000prf.googlegroups.com> Message-ID: <7e38e76a-d5ee-41d9-9ed5-73a2e2993733@w1g2000prm.googlegroups.com> On 12?29?, ??5?06?, "Mark Tolonen" wrote: > "zxo102" wrote in message > > news:2560a6e0-c103-46d2-aa5a-8604de4d1968 at b38g2000prf.googlegroups.com... > > > I have a list in a dictionary and want to insert it into the html > > file. I test it with following scripts of CASE 1, CASE 2 and CASE 3. I > > can see "??" in CASE 1 but that is not what I want. CASE 2 does not > > show me correct things. > > So, in CASE 3, I hacked the script of CASE 2 with a function: > > conv_list2str() to 'convert' the list into a string. CASE 3 can show > > me "??". I don't know what is wrong with CASE 2 and what is right with > > CASE 3. > > > Without knowing why, I have just hard coded my python application > > following CASE 3 for displaying Chinese characters from a list in a > > dictionary in my web application. > > > Any ideas? > > See below each case...????? > > > > > Happy a New Year: 2009 > > > ouyang > > > CASE 1: > > ######################################################## > > f=open('test.html','wt') > > f.write(''' > > > > test > > > > > > ''') > > f.close() > > In CASE 1, the *4 bytes* D6 D0 CE C4 are written to the file, which is the > correct gb2312 encoding for ??. > > > > > CASE 2: > > ####################################################### > > mydict = {} > > mydict['JUNK'] = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce > > \xc4'] > > f_str = ''' > > > > test > > > > > > ''' > > > f_str = f_str%mydict > > f=open('test02.html','wt') > > f.write(f_str) > > f.close() > > In CASE 2, the *16 characters* "\xd6\xd0\xce\xc4" are written to the file, > which is NOT the correct gb2312 encoding for ??, and will be interpreted > however javascript pleases. This is because the str() representation of > mydict['JUNK'] in Python 2.x is the characters "['\xd6\xd0\xce\xc4', > '\xd6\xd0\xce\xc4', '\xd6\xd0\xce\xc4']". > > > > > CASE 3: > > ################################################### > > mydict = {} > > mydict['JUNK'] = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce > > \xc4'] > > > f_str = ''' > > > > test > > > > > > ''' > > > import string > > > def conv_list2str(value): > > list_len = len(value) > > list_str = "[" > > for ii in range(list_len): > > list_str += '"'+string.strip(str(value[ii])) + '"' > > if ii != list_len-1: > > list_str += "," > > list_str += "]" > > return list_str > > > mydict['JUNK'] = conv_list2str(mydict['JUNK']) > > > f_str = f_str%mydict > > f=open('test03.html','wt') > > f.write(f_str) > > f.close() > > CASE 3 works because you build your own, correct, gb2312 representation of > mydict['JUNK'] (value[ii] above is the correct 4-byte sequence for ??). > > That said, learn to use Unicode strings by trying the following program, but > set the first line to the encoding *your editor* saves files in. You can > use the actual Chinese characters instead of escape codes this way. The > encoding used for the source code and the encoding used for the html file > don't have to match, but the charset declared in the file and the encoding > used to write the file *do* have to match. > > # coding: utf8 > > import codecs > > mydict = {} > mydict['JUNK'] = [u'??',u'??',u'??'] > > def conv_list2str(value): > return u'["' + u'","'.join(s for s in value) + u'"]' > > f_str = u''' > > test > > > ''' > > s = conv_list2str(mydict['JUNK']) > f=codecs.open('test04.html','wt',encoding='gb2312') > f.write(f_str % s) > f.close() > > -Mark > > P.S. Python 3.0 makes this easier for what you want to do, because the > representation of a dictionary changes. You'll be able to skip the > conv_list2str() function and all strings are Unicode by default. Thanks for your comments, Mark. I understand it now. The list(escape codes): ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4'] is from a postgresql database with "select" statement.I will postgresql database configurations and see if it is possible to return ['??','? ?','??'] directly with "select" statement. ouyang From timr at probo.com Wed Dec 31 02:22:46 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 31 Dec 2008 07:22:46 GMT Subject: What is site-packages? References: Message-ID: <8c7ml4dcf2b8e2i25jfhs40llngldduiqi@4ax.com> Hussein B wrote: >On Dec 28, 2:04?pm, "Chris Rebert" wrote: >> On Sun, Dec 28, 2008 at 3:40 AM, Hussein B wrote: >> > Hey, >> > What is /usr/lib/pythonx.y/site-packages folder and for what it is >> > used usually? >> >> I believe it's where third-party libraries are typically installed to. >> >> Follow the path of the Iguana...http://rebertia.com > >You mean like MoinMoin, Django or Pylons for example? It means any package that should be available to Python programs that is not part of the standard Python library. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From google at mrabarnett.plus.com Wed Dec 3 18:17:46 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 03 Dec 2008 23:17:46 +0000 Subject: [SPAM] Re: "as" keyword woes In-Reply-To: <1228342347.29326.62.camel@brotherus.rdu.redhat.com> References: <896B75251BA19745A529B1B867893FA50679C6@planet.delsci.local> <1228342347.29326.62.camel@brotherus.rdu.redhat.com> Message-ID: <4937139A.5060502@mrabarnett.plus.com> Albert Hopkins wrote: > On Wed, 2008-12-03 at 13:38 -0800, Warren DeLano wrote: >> A bottom line / pragmatic question... hopefully not a FAQ. >> >> Why was it necessary to make "as" a reserved keyword? >> >> And more to the point, why was it necessary to prevent developers from >> being able to refer to attributes named "as"? >> >> For example, this code breaks as of 2.6 / 3.0: >> >> Class C: >> Pass >> >> obj = C() >> >> obj.bs = 2 # valid >> >> obj.as = 1 # syntax error >> >> obj.cs = 3 # valid >> >> Just to be clear: I understand why it breaks, since "as" is now a >> keyword, I also know that one can use workarounds such as: >> >> obj.__dict__['as'] = 1 >> >> to maintain compatibility. >> >> What I want to understand is why this parser change was necessary in >> order to enable new 2.6/3.0 features. Was this change potentially >> avoidable? >> >> Why can't the parser distinguish between a standalone " as " keyword and >> ".as" used as an object/attribute reference? >> >> Couldn't we have continued along just fine using a smarter parser >> without elevating "as" to reserved status (and thus potentially breaking >> a 10+ years of existing code)? >> >> Thank you for enlighting me! >> >> (Unfortunately, our project may now have to maintain a branch at 2.5.x >> in order to preserve compatibility with existing third-party scripts & >> infrastructure which routinely rely upon "as" as an object method. >> Sigh.) >> >> Cheers, >> Warren > > The short answer is that "as" is a keyword as of 2.6 (with the > introduction of the "with" statement) and to be fair none of the other > keywords can be identifiers. > > Also to be fair, there seems to be warning at least in my version of > python 2.5: > >>>> import sys >>>> sys.version_info > (2, 5, 1, 'final', 0) >>>> class C: > ... pass > ... >>>> obj = C() >>>> obj.as = 3 > :1: Warning: 'as' will become a reserved keyword in Python 2.6 > The parser in Python v2.5 can identify when "as" has its special meaning by context, but it's better to be consistent. Hopefully there won't be many reserved words (IIRC, COBOL has a _large_ number of them)! If you still want a name like that then the convention is to add a trailing underscore, eg the "pass_" method of POP3 objects in poplib. That probably doesn't help you, though. :-( From clp at rebertia.com Sat Dec 6 18:47:08 2008 From: clp at rebertia.com (Chris Rebert) Date: Sat, 6 Dec 2008 15:47:08 -0800 Subject: how to get a beep, OS independent ? In-Reply-To: <493B0D85.3060404@gmail.com> References: <493B0D85.3060404@gmail.com> Message-ID: <47c890dc0812061547g595593a1lc5ee6539adaa224c@mail.gmail.com> On Sat, Dec 6, 2008 at 3:40 PM, Stef Mientki wrote: > hello, > > I want to give a small beep, > for windows there's message-beep, > and there seems to be something like " curses" , > but that package seems to be totally broken in P2.5 for windows. > > Any other suggestions ? Printing the http://en.wikipedia.org/wiki/Bell_character ("\a") to the terminal produces a beep from the internal speaker. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > thanks, > Stef Mientki > -- > http://mail.python.org/mailman/listinfo/python-list > From python at bdurham.com Wed Dec 24 04:23:21 2008 From: python at bdurham.com (python at bdurham.com) Date: Wed, 24 Dec 2008 04:23:21 -0500 Subject: Strategy for determing difference between 2 very large dictionaries In-Reply-To: References: <1230102996.2303.1291616055@webmail.messagingengine.com> Message-ID: <1230110601.21320.1291626339@webmail.messagingengine.com> Hi Peter, If you are not interested in the intermediate results and the dictionary values are hashable you can get the difference by >>> a = dict(a=1, b=2, c=3) >>> b = dict(b=2, c=30, d=4) >>> dict(set(a.iteritems()) ^ set(b.iteritems())) {'a': 1, 'c': 3, 'd': 4} That's very cool! Thanks for sharing that technique. Regards, Malcolm ----- Original message ----- From: "Peter Otten" <__peter__ at web.de> To: python-list at python.org Date: Wed, 24 Dec 2008 09:46:51 +0100 Subject: Re: Strategy for determing difference between 2 very large dictionaries Gabriel Genellina wrote: > En Wed, 24 Dec 2008 05:16:36 -0200, escribi?: [I didn't see the original post] >> I'm looking for suggestions on the best ('Pythonic') way to >> determine the difference between 2 very large dictionaries >> containing simple key/value pairs. >> By difference, I mean a list of keys that are present in the >> first dictionary, but not the second. And vice versa. And a list >> of keys in common between the 2 dictionaries whose values are >> different. >> The 2 strategies I'm considering are: >> 1. Brute force: Iterate through first dictionary's keys and >> determine which keys it has that are missing from the second >> dictionary. If keys match, then verify that the 2 dictionaries >> have identical values for the same key. Repeat this process for >> the second dictionary. >> 2. Use sets: Create sets from each dictionary's list of keys and >> use Python's set methods to generate a list of keys present in >> one dictionary but not the other (for both dictionaries) as well >> as a set of keys the 2 dictionaries have in common. > > I cannot think of any advantage of the first approach - so I'd use sets. > > k1 = set(dict1.iterkeys()) > k2 = set(dict2.iterkeys()) > k1 - k2 # keys in dict1 not in dict2 > k2 - k1 # keys in dict2 not in dict1 > k1 & k2 # keys in both > >> Using the set >> of keys in common, compare values across dictionaries to >> determine which keys have different values (can this last step be >> done via a simple list comprehension?) If you are not interested in the intermediate results and the dictionary values are hashable you can get the difference by >>> a = dict(a=1, b=2, c=3) >>> b = dict(b=2, c=30, d=4) >>> dict(set(a.iteritems()) ^ set(b.iteritems())) {'a': 1, 'c': 3, 'd': 4} Peter -- http://mail.python.org/mailman/listinfo/python-list From p.f.moore at gmail.com Sun Dec 14 11:19:11 2008 From: p.f.moore at gmail.com (Paul Moore) Date: Sun, 14 Dec 2008 08:19:11 -0800 (PST) Subject: Looking for the best way to translate an idiom Message-ID: I'm translating some code from another language (Lua) which has multiple function return values. So, In Lua, it's possible to define a function function f() return 1,2,3 end which returns 3 values. These can then be used/assigned by the caller: a,b,c = f() So far, much like Python, but the key difference is that in Lua, excess arguments are ignored - so you can do a = f() or even a = f() + 1 where in the latter, a is 2 (as addition only needs 1 argument, so the extra ones are discarded). This results in the code which I'm trying to translate having functions which return multiple arguments, the first of which is the "main" result, and the following values are "extra" results (specifically, the position at which a match is found, followed by the "captured" values of the match). I'm trying to find a natural equivalent in Python. So far, I've considered the following: - return a tuple (pos, captures). This is messy, because you end up far too often unpacking the tuple and throwing away the second value - return an object with pos and captures attributes. This is better, as you can do match(...).pos to get the position alone, but it doesn't really feel "pythonic" (all those calls with .pos at the end...) - have 2 calls, one to return just the position, one to return both. This feels awkward, because of the 2 method names to remember. To make things worse, Lua indexes strings from 1, so it can use a position of 0 to mean "no match" - so that a simple "did it match?" test looks like if (match(....))... - where in Python I need if (matchpos(...) != -1)... (Although if I return a match object, I can override __nonzero__ to allow me to use the simpler Lua form). Can anyone suggest a good idiom for this situation? At the moment, I'm returning a match object (the second option) which seems like the least bad of the choices (and it mirrors how the re module works, which is somewhat useful). But I'd like to know what others think. If you were using a pattern matching library, what interface would you prefer? I suspect my intuition isn't accurate here, as most of the use I've made of the library is in writing tests, which isn't typical use :-( Thanks for any assistance. Paul From stef.mientki at gmail.com Tue Dec 30 15:16:39 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 30 Dec 2008 21:16:39 +0100 Subject: Triple quoted string in exec function ? In-Reply-To: References: <495A253B.6010003@gmail.com> Message-ID: <495A81A7.8030507@gmail.com> ibpet11 at gmail.com wrote: > On Dec 30, 2:48 pm, Steve Holden wrote: > >> Stef Mientki wrote: >> >>> hello, >>> >>> I'm running scripts, with the execute function (Python 2.5), >>> and it seems that triple quoted strings are not allowed. >>> >>> Is there a workaround, >>> or is this a fundamental problem of the exec-function ? >>> >> If you think about it, it should be obvious that you can't surround a >> string to be compiled with any of the quotes that appear inside the >> string to be compiled. That's about the only limitation I am aware of. >> >> And, by the way, exec is a *statement*, not a function! >> exec ( Init_Code, PG.P_Globals ) I've really doubt that this is a statement, unless I don't understand what a statement is. >> >>>>> exec """print '''This is >>>>> >> ... a long string''' >> ... """ >> This is >> a long string >> >> >> >> regards >> Steve >> -- >> Steve Holden +1 571 484 6266 +1 800 494 3119 >> Holden Web LLC http://www.holdenweb.com/ >> > > hello, > the message Steven sent you is ok to explain how to work with triple > quote > > Yes, but not to work around my problem. I guess I've to remove all triple quoted strings from my code. anyway thanks, Stef From wuwei23 at gmail.com Mon Dec 1 23:59:29 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 1 Dec 2008 20:59:29 -0800 (PST) Subject: HELP!...Google SketchUp needs a Python API References: <6236c995-3cfd-406b-b8ae-aae9907b5b9d@d32g2000yqe.googlegroups.com> <1521aeb6-8231-4c94-acb9-50175ff4f7ad@j11g2000yqg.googlegroups.com> <17fab7f5-3824-4e70-b25f-185f44b1ca50@s9g2000prm.googlegroups.com> <8d797ab8-f535-4774-a5e6-bc99a42227e6@r40g2000yqj.googlegroups.com> <32910aa2-9144-495f-b6a8-68602e0c5fdf@41g2000yqf.googlegroups.com> <35858b5b-3179-4f8f-b38b-4a07fbd0c07b@w34g2000yqm.googlegroups.com> <6e06d32e-2609-4c9f-b602-5d2ab3411f0f@t11g2000yqg.googlegroups.com> Message-ID: <9baabb6c-daab-418e-a11f-9162e1fc30f7@k36g2000pri.googlegroups.com> On Dec 2, 2:18?pm, r wrote: > PS hey...even alex23's post are a little less mean. Either I am > wearing him down or he is beginning to believe :) Yes, my wishing your death by asphyxiation is "less mean" than my original post suggesting you do some work. Your lack of reading comprehension is another big indicator that you're a troll. Just die already. From stef.mientki at gmail.com Thu Dec 25 16:53:34 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 25 Dec 2008 22:53:34 +0100 Subject: Is there a function to remove escape characters from a string ? In-Reply-To: <0163882f$0$6988$c3e8da3@news.astraweb.com> References: <0163882f$0$6988$c3e8da3@news.astraweb.com> Message-ID: <495400DE.3000709@gmail.com> Steven D'Aprano wrote: > On Thu, 25 Dec 2008 11:00:18 +0100, Stef Mientki wrote: > > >> hello, >> >> Is there a function to remove escape characters from a string ? >> (preferable all escape characters except "\n"). >> > > > Can you explain what you mean? I can think of at least four alternatives: > I have the following kind of strings, the funny "?" is ASCII character 254, used as a separator character [FSM] Counts = "1?11?16" ==> 1,11,16 Init1 = "1?\BCtrl" ==> 1,Ctrl State5 = "8?\BJUMP_COMPL\b\n>PCWrite = 1\n>PCSource = 10" ==> 8, JUMP_COMPL\n>PCWrite = 1\n>PCSource = 10 Seeing and testing all your answers, with great solutions that I've never seen before, knowing nothing of escape sequences (I'm a windows guy ;-) I now see that the characters I need to remove, like \B and \b are not "official" escape sequences. So in this case the best (easiest to understand) method is a few replace statements: s = s.replace ( '\b', '' ).replace( '\B', '' ) Nevertheless, thank you all for the other examples, cheers, Stef > (1) Remove literal escape sequences (backslash-char): > "abc\\t\\ad" => "abcd" > r"abc\t\ad" => "abcd" > > > (2) Replace literal escape sequences with the character they represent: > "abc\\t\\ad" => "abc\t\ad" > > > (3) Remove characters generated by escape sequences: > "abc\t\ad" => "abcd" > "abc" => "abc" but "a\x62c" => "ac" > > This is likely to be impossible without deep magic. > > > (4) Remove so-called binary characters which are typically inserted using > escape sequences: > "abc\t\ad" => "abcd" > "abc" => "abc" but "a\x62c" => "abc" > > This is probably the easiest, assuming you have bytes instead of unicode. > > import string > table = string.maketrans('', '') > delchars =''.join(chr(n) for n in range(32)) > > s = string.translate(s, table, delchars) > > > > From mludvig at logix.net.nz Thu Dec 18 18:21:27 2008 From: mludvig at logix.net.nz (Michal Ludvig) Date: Fri, 19 Dec 2008 12:21:27 +1300 Subject: setup.py installs modules to a wrong place In-Reply-To: <494384EF.7050605@logix.net.nz> References: <494384EF.7050605@logix.net.nz> Message-ID: <494ADAF7.8050003@logix.net.nz> Ping! Does anyone know what the problem could be? The bug reported provided some more information recently... The modules have been installed to /usr/lib/python2.5/site-packages as show below. Apparently on his system /usr/lib/python2.5 is a symlink to /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5 While this directory *is* in sys.path, the .../site-packages one isn't, see below in my original post. So why did Python decide to put the modules there? Why not one of the directories that are in sys.path? Is this configurable somewhere? Thanks! Michal Michal Ludvig wrote: > Hi, > > I have recently seen some reports from users of my s3cmd script [1] who > installed the package using the provided distutils-based setup.py and > immediately after installation the script failed to run because it > couldn't find its modules. > > Here's an example session from Mac OS X, but similar behaviour has been > observed on Ubuntu as well. Needless to say it works for me just fine so > I can't easily debug and fix it :-( > > First is the reported setup.py output: > > ----- > ~/bin/s3cmd $ sudo python setup.py install > Password: > ... > running install_lib > creating /usr/lib/python2.5/site-packages > creating /usr/lib/python2.5/site-packages/S3 > copying build/lib/S3/PkgInfo.py -> /usr/lib/python2.5/site-packages/S3 > ... more modules, etc ... > ----- > > It decided to put the modules to /usr/lib/python2.5/site-packages/S3 > > Now, s3cmd should import from there, but fails: > > ~/bin/s3cmd $ s3cmd > Traceback (most recent call last): > File "/usr/bin/s3cmd", line 1207, in > from S3 import PkgInfo > ImportError: No module named S3 > > sys.path at the time the script died had these entries: > /usr/bin > /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python25.zip > /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5 > /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-darwin > /System/Library/Frameworks/Python.framework/Versions/2.5/...other_subdirs... > /Library/Python/2.5/site-packages > > There is nothing special in setup.py. After all have a look yourself: > http://s3tools.svn.sourceforge.net/viewvc/s3tools/s3cmd/trunk/setup.py?view=markup > > What could be the reason for distutils / setup.py to install the modules > to a directory that's not in sys.path? Can I detect it in setup.py and > prevent or workaround it somehow? > > Thanks! > > [1] http://s3tools.logix.cz/s3cmd -- Amazon S3 command line client > > Michal > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From saluk64007 at gmail.com Wed Dec 10 12:22:46 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Wed, 10 Dec 2008 09:22:46 -0800 Subject: "as" keyword woes In-Reply-To: <493FD8F6.3050803@mrabarnett.plus.com> References: <896B75251BA19745A529B1B867893FA50679CA@planet.delsci.local> <60867d74-9755-4e9f-8bf3-22245e8a1103@l33g2000pri.googlegroups.com> <014e6931$0$20670$c3e8da3@news.astraweb.com> <27b872d4-0f2d-473b-a880-db25c7cc5a12@a26g2000prf.googlegroups.com> <493FD8F6.3050803@mrabarnett.plus.com> Message-ID: On Wed, Dec 10, 2008 at 6:57 AM, MRAB wrote: > Aaron Brady wrote: >> >> On Dec 9, 12:40 pm, MRAB wrote: >>> >>> Aaron Brady wrote: >>>> >>>> On Dec 9, 8:28 am, MRAB wrote: >>>> snip >>>>> >>>>> In some languages (I think Delphi is one of them - it's been a while!) >>>>> some words which would normally be identifiers have a special meaning >>>>> in >>>>> certain contexts, but the syntax precludes any ambiguity, and not in a >>>>> difficult way. "as" in Python was one of those. >>>>> I certainly wouldn't want something like PL/I, where "IF", "THEN" and >>>>> "ELSE" could be identifiers, so you could have code like: >>>>> IF IF = THEN THEN >>>>> THEN = ELSE; >>>>> ELSE >>>>> ELSE = IF; >>>>> Seehttp://en.wikipedia.org/wiki/PL/I_(programming_language). >>>> >>>> snip >>>> That is, 'certainly' doesn't change the meaning of your statement >>>> any. You wouldn't want it, but King George III didn't want the >>>> American Revolution. >>> >>> It's called emphasis. >> >> I just take you to have meant, then, +1 on excluding keywords from >> identifiers. You said it the long way though, so I thought I missed >> something deeper, that didn't come across. >> > IIRC, most computer languages have an LL(1) grammar, which means that when > they are parsed you need to look at only the next word. If you're about to > parse a statement and the next word is "IF" then you know it's an > IF-statement, if it's an identifier then it's either a call or an assignment > statement (OK, you don't know exactly what kind of statement it is at that > point, but it works out just fine!). > > In the example from PL/I, "IF" could be the start of an IF-statement "IF > THEN" or an assignment statement "IF = ". It's a bit > more tricky for the parser as well as the programmer. > > Life is easier if words having special meanings are reserved. > > However, that doesn't mean that all special words /must/ be reserved > (pragmatism beats purity). Sometimes the syntax makes it clear and > unambiguous, so you can get away with not making it a reserved word. The > word "as" in Python doesn't need to be reserved because the syntax precludes > ambiguity, but it's the only such word in the language, so it's just tidier > to make it reserved too. > -- > http://mail.python.org/mailman/listinfo/python-list > I don't have a huge stake in this, but I wouldn't mind a change to allow anything proceeding a "." or preceeding a "(" to not be identified as a keyword. It is obvious to me a s a human reader that something.if is quite a bit different than just a bare if. And as far as parsing technology goes, isn't it supposed to go for the biggest match first? I would not be for allowing bare keywords to be used in the situations described above, but since we are so used to being able to being able to have say, myclass.dir() or myclass.len() without them overwriting the builtin functions, it makes sense to me to be able to define a myclass.as() or myclass.with() without overwriting the keywords. Though I know the semantics behind these two things are very different, the rules I go through when reading the code are very similar. The parser change might be a hassle, and it might not be worth it at all of course, but from a conceptual point of view it is simple. I mean, even now you can do class.__dict__["as"]. I guess I'm -1 for full PL/1 craziness, but +1 for qualified keyword usage. From clp at rebertia.com Tue Dec 9 01:01:27 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 8 Dec 2008 22:01:27 -0800 Subject: Password input in console/terminal In-Reply-To: References: Message-ID: <47c890dc0812082201x771805d8o51f62ed451453430@mail.gmail.com> On Mon, Dec 8, 2008 at 9:53 PM, RP wrote: > Hello All, > > This is my first REAL post(question) to Python-List. I know I can take input > from a user with raw_input() > How do I take password input in console? Any Help would be Greatly > Appreciated. Thank You. RP You use the appropriately-named `getpass` module: http://docs.python.org/library/getpass.html Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From cournape at gmail.com Fri Dec 19 04:06:20 2008 From: cournape at gmail.com (David Cournapeau) Date: Fri, 19 Dec 2008 18:06:20 +0900 Subject: Python for amd64 and mingw-w64 In-Reply-To: <494B3F75.10104@v.loewis.de> References: <494B3F75.10104@v.loewis.de> Message-ID: <5b8d13220812190106v74de0f3ai11cb59fbabe5c2c0@mail.gmail.com> On Fri, Dec 19, 2008 at 3:30 PM, "Martin v. L?wis" wrote: > > It's a mistake if libpython26.a gets included in the Win64 installer > at all; this library is only provided for 32-bit systems. My copy of > mingw doesn't support Win64 at all. Please ignore that last point: it looks like it is generated by our (numpy) build process, and has nothing to do with python per-se. David From hniksic at xemacs.org Fri Dec 12 20:20:59 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sat, 13 Dec 2008 02:20:59 +0100 Subject: var or inout parm? References: <7b26adbd-1fb6-4ba3-aa00-39ab193ffd5c@k24g2000pri.googlegroups.com> <87wse5ms9y.fsf@mulj.homelinux.net> <817a235b-7f60-4b7d-8090-ebefa515c179@z6g2000pre.googlegroups.com> <6qf9irFc3a5jU3@mid.uni-berlin.de> <1cd909e8-a231-423c-8935-9e0c8f60c36c@b1g2000yqg.googlegroups.com> <0233831c-fa05-4bf3-a301-9b857252bf22@e1g2000pra.googlegroups.com> Message-ID: <87iqpoc1l0.fsf@mulj.homelinux.net> sturlamolden writes: > What? Take a look at the code again: > > mytuple[0] += 1 > > should never attempt an __iadd__ on mytuple. > > A sane parser would see this as: > > tmp = mytuple.__getitem__(0) > tmp = tmp.__iadd__(1) > mytuple.__setitem__(0, tmp) # should this always raise an exception? What do you mean by "a sane parser"? This is exactly what happens in current Python. Since tuple's __setitem__ always raises an exception (and that is by design and not likely to change), everything is sane. Saner (in this respect) behavior in the tuple example would require a different protocol. I don't understand why Python doesn't just call __iadd__ for side effect if it exists. The decision to also rebind the result of __i*__ methods continues to baffle me. I guess it is a result of a desire to enable the __i*__ methods to punt and return a different instance after all, but if so, that design decision brings more problems than benefits. From ldo at geek-central.gen.new_zealand Wed Dec 3 20:07:46 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 04 Dec 2008 14:07:46 +1300 Subject: Don't you just love writing this sort of thing :) Message-ID: for \ Entry \ in \ sorted \ ( f for f in os.listdir(PatchesDir) if PatchDatePat.search(f) != None ) \ : Patch = (open, gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir, Entry), "r") ... read from Patch ... Patch.close() #end for From acerimusdux at comcast.net Sun Dec 7 02:49:27 2008 From: acerimusdux at comcast.net (acerimusdux) Date: Sun, 07 Dec 2008 02:49:27 -0500 Subject: Guido's new method definition idea In-Reply-To: <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> References: <26431d4c-39c8-4fb3-b23d-09bd3927db02@a26g2000prf.googlegroups.com> <4032$493a3fbc$d9a2276f$11273@news.hispeed.ch> <5102bc10-f762-4c46-b897-9538d0f1bdb9@r15g2000prd.googlegroups.com> Message-ID: <493B8007.9040608@comcast.net> Russ P. wrote: > Python already uses shorthand extensively. How about "def"? For people > who are so worried about self-explanatory symbols, what the heck does > that stand for? Default? Defeat? Defect? Defunct? Defer? > > > I think the difference here is that those other abbreviations are mostly fairly standard. The "def" keyword is the same in Ruby, and similar enough to "define" or "defun" in Scheme or LISP. The "!=" operator is pretty much standard across nearly all languages. What is being proposed with "$" here though, would be different from how it is used anywhere else and would be confusing. Moreover, I especially don't like proposing to eliminate as well in this instance the "dot notation", which is standard in nearly all object oriented languages. Using something as a substitute for "self" is one thing, and you can mostly use what you like there now, as "self" is more a convention than a requirement. But the "dot" that belongs there is critical to understanding, you can't hide that to save one keystroke. Getting back to Guido's suggestion, though, I think it makes some sense. Being new to Python, I did find myself occasionally forgetting "self" in instance methods. But, I also thought the requirement to include it was helpful in reminding me what was really going on there, that I was creating an instance method which was really a function that wouldn't actually be created until the instance was initiated. I tend to think this may be clearer though using the dot notation rather than passing the instance variable as a parameter. I'm not sure though whether allowing both syntaxes would make things more or less confusing. It might actually be helpful in some respects for newcomers to realize that self.method(arg) is somewhat the same as method(self, arg). Perhaps I'm wrong on this, I don't fully understand yet what is going on under the hood, but it seems to me that that would be part of the glue that allows Python to be so multi-paradigm; much of the difference between OOP and procedural or functional is just different syntax for the same thing. From r.grimm at science-computing.de Sat Dec 6 03:59:07 2008 From: r.grimm at science-computing.de (r.grimm at science-computing.de) Date: Sat, 6 Dec 2008 00:59:07 -0800 (PST) Subject: Pythonic design patterns References: Message-ID: <815c6e46-283f-44c3-ba78-b1f9223dd48b@v13g2000yqm.googlegroups.com> Hallo, > users in this forum has been kind enough to point out. Only my > implementations are often not that clean, and I may call things > something different than the normal convention, which is a source of > confusion for myself and others trying to communicate with me. I think, you should start with the classical books of Design Patterns to get a solid understanding and especially vocabulary to communicate with your coworkers. Its easier and better to say, that you will use a strategy pattern than to describe the architecture in many sentences to your partner in a ambigious way. Thats in my opinion the first and the key benefit of Design Patterns. Speaking in the same language. The next step should be to apply your knowledge to your programming language. So I will recommend the classical GOF Books and the serie Pattern Oriented Software Architecture. Greetings Rainer From ipytest at gmail.com Thu Dec 18 11:08:32 2008 From: ipytest at gmail.com (ipytest at gmail.com) Date: Thu, 18 Dec 2008 08:08:32 -0800 (PST) Subject: Is this pythonic? Message-ID: <66d058f9-cfe1-4b3c-ab8a-e6e88bb97770@m22g2000vbp.googlegroups.com> x.validate_output(x.find_text(x.match_filename (x.determine_filename_pattern(datetime.datetime.now())))) Is it even good programming form? From rt8396 at gmail.com Tue Dec 23 11:25:04 2008 From: rt8396 at gmail.com (r) Date: Tue, 23 Dec 2008 08:25:04 -0800 (PST) Subject: Python's popularity References: <52eb785d-0f8e-4829-9bd3-5c1325aceb10@d42g2000prb.googlegroups.com> Message-ID: <30b5b812-0600-4cf9-9e37-f456a99947ef@a29g2000pra.googlegroups.com> On Dec 23, 8:21?am, Thorsten Kampe wrote: > You don't have a single clue about neither Python nor Ruby: > 'According to the Ruby FAQ, "If you like Perl, you will like Ruby and be > right at home with its syntax. [...] If you like Python, you may or may > not be put off by the huge difference in design philosophy between > Python and Ruby/Perl."'[1] So you read the preface to the tut and that somehow makes you more than a R00b n00b? Come on! From tommy.nordgren at comhem.se Tue Dec 23 16:05:10 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Tue, 23 Dec 2008 22:05:10 +0100 Subject: Get applications to open a given file (Mac and, or Windows) In-Reply-To: References: Message-ID: On Dec 23, 2008, at 5:29 PM, riklaunim at gmail.com wrote: > Under Linux/Unix I use GIO (pygobject) or gnome-vfs-python to get a > list of installed applications that can open given file (for example > image in graphics software). Is there something that can be used for > MS Windows or Mac OS X? > -- > http://mail.python.org/mailman/listinfo/python-list On mac, there are the modules Carbon.Launch and Carbon.LaunchServices Maybe you'll find useful items in the PyObjC framework as well ------------------------------------- This sig is dedicated to the advancement of Nuclear Power Tommy Nordgren tommy.nordgren at comhem.se From cournape at gmail.com Fri Dec 12 05:37:41 2008 From: cournape at gmail.com (David Cournapeau) Date: Fri, 12 Dec 2008 19:37:41 +0900 Subject: Building extensions for python 2.6 adm64 with the SDK compiler Message-ID: <5b8d13220812120237i7f84585bmf9bc9489327e44ae@mail.gmail.com> Hi, I have some trouble building python 2.6 extensions with the SDK compiler on windows 64 bits. The problem is that after link step, mt.exe is called to embed the MANIFEST into the executable, but the manifest is not created, so the build fails with a "general error c1010070:Failed to load and parse the manifest". I am a bit confused: - I thought that manifest should not be embedded in .pyd (http://bugs.python.org/issue4120), but the code of msvc9compiler.py in distutils suggests otherwise, and uses the option /MANIFESTFILE (which only changes the name of the manifest, according to MSDN). - Is this specific to the SDK compiler ? E.g. does the native VS compiler on 64 bits have the same problem ? I guess not, because people would have complained before, I guess. If I manually add the /MANIFEST file to the link options, the build does work, David From sjmachin at lexicon.net Thu Dec 11 18:49:10 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 11 Dec 2008 15:49:10 -0800 (PST) Subject: newbie question: if var1 == var2: References: <3c30aea0-5e7e-4b47-9495-a8d2c44830d5@40g2000prx.googlegroups.com> <87abb21xzm.fsf@daycos.com> Message-ID: On Dec 12, 10:31?am, "Rhodri James" wrote: > On Thu, 11 Dec 2008 19:49:23 -0000, Steve Holden ? > wrote: > > > > > Kirk Strauser wrote: > >> At 2008-11-29T04:02:11Z, Mel writes: > > >>> You could try > > >>> for item in fname: > >>> ? ? item = item.strip() > > >> This is one case where I really miss Perl's "chomp" function. ?It ? > >> removes a > >> trailing newline and nothing else, so you don't have to worry about ? > >> losing > >> leading or trailing spaces if those are important to you. > > > ... and it's so hard to write > > > ? ? ?item = item[:-1] > > Tsk. ?That would be "chop". ?"chomp" would be > > ? ? ?if item[-1] == '\n': > ? ? ? ? ?item = item[:-1] Better: if item and item[-1] == '\n': return item[:-1] return item From nicolas.chauvat at logilab.fr Tue Dec 30 09:05:18 2008 From: nicolas.chauvat at logilab.fr (nchauvat (Logilab)) Date: Tue, 30 Dec 2008 06:05:18 -0800 (PST) Subject: [ANN] release of CubicWeb 3.0.0 Message-ID: <2f5ba08e-5f8d-42fe-b25f-35b5686e595d@r10g2000prf.googlegroups.com> The development team is pleased to announce the release of CubicWeb 3.0.0 (nicknamed ShowTime). What is CubicWeb? ----------------- With CubicWeb, the Semantic Web is a construction game! CubicWeb_ is a semantic web application framework, licensed under the LGPL, that empowers developers to efficiently build web applications by reusing components (called cubes) and following the well known object-oriented design principles. Its main features are: * an engine driven by the explicit data model of the application, * a query language named RQL similar to W3C?s SPARQL, * a selection+view mechanism for semi-automatic XHTML/XML/JSON/ text generation, * a library of reusable components (data model and views) called cubes that fulfill common needs, * the power and flexibility of the Python programming language, * the reliability of SQL databases, LDAP directories, Subversion and Mercurial for storage backends. Being built since 2000 by an R&D project still going on today, supporting 100,000s of daily visits at some production sites, CubicWeb is a proven end to end solution for semantic web application development that promotes quality, reusability and efficiency. The unbeliever will read the quick overview_ of CubicWeb. The hacker will join development at the forge_. The impatient will move right away to installation_ and set-up of a CubicWeb environment. .. _cubicweb: http://www.cubicweb.org/ .. _overview: http://www.cubicweb.org/doc/en/A020-tutorial.en.html#overview .. _forge: http://www.cubicweb.org/project?vtitle=All%20cubicweb%20projects .. _installation: http://www.cubicweb.org/doc/en/C010-setup.en.html#miseenplaceenv Home page --------- http://www.cubicweb.org/ Download -------- http://ftp.logilab.org/pub/cubicweb/ Mailing list ------------ http://lists.cubicweb.org/mailman/listinfo/cubicweb Licence ------- LGPL - Lesser General Public Licence From arnodel at googlemail.com Wed Dec 10 16:59:13 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 10 Dec 2008 21:59:13 +0000 Subject: Python is slow References: <1653d823-bc8c-462c-ae24-21152a315736@f40g2000pri.googlegroups.com> Message-ID: cm_gui writes: [stuff] > Python is slow. Very slow. The same troll started this same flame earlier this year: http://groups.google.com/group/comp.lang.python/browse_thread/thread/5cea684680f63c82?q= -- Arnaud From __peter__ at web.de Tue Dec 9 13:05:49 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Dec 2008 19:05:49 +0100 Subject: StringIO in 2.6 and beyond References: Message-ID: Bill McClain wrote: > I've just installed 2.6, had been using 2.4. > > This was working for me: > > #! /usr/bin/env python > import StringIO > out = StringIO.StringIO() > print >> out, 'hello' > > I used 2to3, and added import from future to get: > > #! /usr/bin/env python > from __future__ import print_function > import io > out = io.StringIO() > print('hello', file=out) > > ...which gives an error: > > Traceback (most recent call last): > File "./example.py", line 5, in > print('hello', file=out) > File "/usr/local/lib/python2.6/io.py", line 1487, in write > s.__class__.__name__) > TypeError: can't write str to text stream > > ...which has me stumped. Why can't it? >>> from __future__ import print_function >>> import io >>> out = io.StringIO() >>> print("hello", file=out) Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.6/io.py", line 1487, in write s.__class__.__name__) TypeError: can't write str to text stream Seems io.StringIO() wants unicode. So let's feed it some: >>> print(u"hello", file=out) Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.6/io.py", line 1487, in write s.__class__.__name__) TypeError: can't write str to text stream Still complaining? Let's have a look at the output so far: >>> out.getvalue() u'hello' Hmm, u"hello" was written. The complaint must be about the newline then. >>> out = io.StringIO() >>> print(u"hello", file=out, end=u"\n") >>> out.getvalue() u'hello\n' Heureka. Let's try something else now: >>> print(u"hello", u"world", file=out, end=u"\n") Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.6/io.py", line 1487, in write s.__class__.__name__) TypeError: can't write str to text stream Fixing is left as exercise ;) Peter From gruszczy at gmail.com Sat Dec 13 06:50:03 2008 From: gruszczy at gmail.com (=?UTF-8?Q?Filip_Gruszczy=C5=84ski?=) Date: Sat, 13 Dec 2008 12:50:03 +0100 Subject: Removing None objects from a sequence In-Reply-To: <01538f0c$0$6988$c3e8da3@news.astraweb.com> References: <1be78d220812120118y1e9753f6m14902db297d9e410@mail.gmail.com> <4942E668.5030100@tim.thechases.com> <01538f0c$0$6988$c3e8da3@news.astraweb.com> Message-ID: <1be78d220812130350u53e0c334i562abbf1fe0a0701@mail.gmail.com> Just to be clear, I decided to use generator by alex23, as it seems simple, short and understandable. Still reading this thread was quite interesting, thanks :-) -- Filip Gruszczy?ski From honey33145 at gmail.com Fri Dec 12 00:52:45 2008 From: honey33145 at gmail.com (navneet khanna) Date: Fri, 12 Dec 2008 11:22:45 +0530 Subject: concept of creating structures in python Message-ID: Hello Everybody I want to create a structure within a structure i.e. nested structures in python. I tried with everything but its not working. my code is like this: class L(Structure): def __init__(self,Name='ND',Addr=0,ds_obj = D()): self.Name = Name self.Addr = Addr self.ds_obj = ds_obj class D(Structure): def __init__(self,dataName='ND',index = 0,ele_obj=E()): self.dataName = dataName self.index = index self.ele_obj = ele_obj these are two structures. I want to refer D structure in L one and use it. I want to access the value of D structure like L.D.index = 0. Please help me Thanks in advance Navneet -------------- next part -------------- An HTML attachment was scrubbed... URL: From xahlee at gmail.com Sun Dec 28 22:06:59 2008 From: xahlee at gmail.com (Xah Lee) Date: Sun, 28 Dec 2008 19:06:59 -0800 (PST) Subject: HTML Correctness and Validators Message-ID: <2fb289be-00b3-440a-b153-ca88f0ba16c5@d42g2000prb.googlegroups.com> recently i wrote a blog essay about html correctness and html validators, with relations to the programing lang communities. I hope programing lang fans will take more consideration on the correctness of the doc they produces. HTML Correctness and Validators ? http://xahlee.org/js/html_correctness.html plain text version follows. --------------------------- HTML Correctness and Validators Xah Lee, 2008-12-28 Some notes about html correctness and html validator. Condition Of Website Correctness My website ?xahlee.org? has close to 4000 html files. All are valid html files. ?Valid? here means passing the w3c's validator at http://validator.w3.org/. Being a programing and correctness nerd, correct html is important to me. (correct markup has important, practical, benefits, such as machine parsing and transformation, as picked up by the XML movement. Ultimately, it is a foundation of semantic web?.) In programing lang communities, the programer tech geekers are fanatical about their fav lang's superiority, and in the case of functional langs, they are often proud of their correctness features. However, a look at their official docs or websites, they are ALL invalid html, with errors in just about every 10 lines of html source code. It is fucking ridiculous. In the web development geeker communities, you can see how they are tight-assed about correct use of HTML/CSS, etc, where there are often frequent and heated debates about propriety of semantic markup, and they don't hesitate to ridicule Microsoft Internet Explorer browser, or the average HTML content producer. However, a look at the html they produced, also almost none are valid. The bad html also happens in vast majority of docs produced by organization of standards, such as the Unicode Consortium?, IETF?. For example, if you run w3c's validator on their IETF's home page, there are 32 errors, including ?no doctype found?, and if you validate unicode's http://www.unicode.org/faq/utf_bom.html, there are 2 errors. (few years ago, they are much worse. I don't think even ?w3.org?'s pages are valid back then.) In about 2006, i spent few hours research on what major websites produces valid html. To this date, I know of only one major site that produces valid html, and that is Wikipedia. This is fantastic. Wikipedia is produced by MediaWiki? engine, written in PHP. Many other wiki sites also run MediaWiki, so they undoubtfully are also valid. As far as i know, few other wiki or forum software also produces valid html, though they are more the exceptions than norm. (did try to check 7 random pages from ?w3.org?, looks like they are all valid today.) Personal Need For Validator My personal need is to validate typically hundreds of files on my local drive. Every month or so, i do systematic regex find-replace operation on a dir. This often results over a hundred changed files. Every now and then, i improve my css or html markup semantics site wide, so the find-replace is on all 4000 files. Usually the find- replace is carefully crafted with attention to correctenss, or done in emacs interactively, so possible regex screwup is minimal, but still i wish to validate by batch after the operation. Batch validation is useful because, if i screwed up in my regex, usually it ends up with badly formed html, so html validation can catch the result. In 2008, i converted most my sites from html 4 transitional to html 4 strict. The process is quite a manual pain, even the files i start with are valid. Here are some examples. In html4strict: * ??br?? must be inside block level tags. Image tag ??img ...?? needs to be enclosed in a block level tag such as ??div??. Content inside blockquote must be wrapped with a block level tag. e.g. ??blockquote?Time Flies?/blockquote?? would be invalid in html4strict; you must have ??blockquote??p?Time Flies?/p??/blockquote?? Lets look at the image tag example. You might think it is trivial to transform because you can simply use regex to wrap a ??div?? to image tags. However, it's not that simple. Because, for example, often i have this form: ?img src="pretty.jpg" alt="pretty girl" width="565" height="809"? ?p?above: A pretty girl.?/p? The ?p? tag immediately below a ?img? tag, functions as the image's caption. I have css setup so that this caption has no gap to the image above it, like this: img + p {margin-top:0px;width:100%} /* img caption */ I have the ?width:100%? because normally ?p? has ?width:80ex? for normal paragraph. Now, if i simply wrap a ?div? tag to all my ?img? tags, i will end up with this form: ?div??img src="pretty.jpg" alt="pretty girl" width="565" height="809"??/div? ?p?above: A pretty girl.?/p? Now this screws up with my caption css, and there's no way to match ?p? that comes after a ?div ? img?. Also, sometimes i have a sequence of images. Wrapping each with a ?div? would introduce gaps between them. This is just a simplified example. In short, converting from html4transitional to html4strict while hoping to retain appearance or markup semantics in practical ways is pretty much a manual pain. (the ultimate reason is because html4transitional is far from being a good semantic markup. (html4strict is a bit better)) Validators In my work i need a batch validator. What i want is a command line utility, that can batch validate all files in a dir. Here are some solutions related to html validation. * The standard validator service by w3c: http://validator.w3.org/ (see also: W3C Markup Validation Service? ). The problem with this is that it can't validate local files, and can't do in batch. Using it to validate 4000 files thru network (with a help of perl script) would not be acceptable, since each job means massive web traffic. (my site is near 754 Mebibyte?.) * FireFox has a ?Html Validator? add-on by Marc Gueury. https://addons.mozilla.org/en-US/firefox/addon/249. This is based on the same code as w3c validator, can work on local files, is extremely fast. When browsing any page, it shows a green check mark on the window corner when the file is valid. I heavily rely on this tool. * FireFox has a ?Web Developer? add-on by Chris Pederick. https://addons.mozilla.org/en-US/firefox/addon/60 Since Firefox ?v.3?, it has a icon that indicates if a page's css and javascript are invalid (has errors), and also indicates whether the file is using Quirks mode?. I heavily rely on this tool. I heavily relie on the above 2 FireFox tools. However, the FireFox tools do not let me do batch validation. Over the years i've searched for batch validation tools. Here's some list: * HTML Tidy? A batch tool primarily for cleanup html markup. I didn't find it useful for batch validation purposes, nor for html conversion jobs. It doesn't do well for my html conversion needs because the tool is incapable of retaining your html formatting (i.e. retain your newlines locations). I do a lot regex based text procesing on my html files, so i need assumptions about how newlines are in my html files. If i use tidy on my site, that means i have to abandon regex based text processing, and instead, have to treat my files using html and dom parsers, which makes most practical text processing needs quite more complex and cumbersome. * A perl module ?HTML::Lint?, at http://search.cpan.org/~petdance/HTML-Lint-2.06/lib/HTML/Lint.pm. Seems pretty much like HTML Tidy. * http://htmlhelp.com/tools/validator/offline/index.html.en is another validation tool. I haven't looked into yet. Their doc about differences to other validator: http://htmlhelp.com/tools/validator/differences.html.en, is quite interesting, and seems a advantage for my needs. * OpenJade and OpenSP. http://openjade.sourceforge.net/ Seems a good tool. Haven't looked into. * Emacs's nxml mode http://www.thaiopensource.com/nxml-mode/, by the xml expert James Clark?. This is written in elisp with over 10 thousand lines of code. It indicates whether your xml file is valid as you type. This package is very well received, reputed to make emacs the best xml editor. This is fantastic, but since my files are currently html not xhtml, so i haven't used this much. There are emacs html modes based on this package, called nxhtml mode, but the code is still pretty alpha and i find it having a lot problems. One semi solution for batch validation i found is: ?Validator S.A.C.?, at http://habilis.net/validator-sac/. It is basically w3c's validator compiled for OS X with a GUI interface. However, this is not designed for batch operation. If you want to do batch, i run it like this: ?/ Applications/Validator-SAC.app/Contents/Resources/weblet ?html file path??. However, it output a whole report in html on the validation result (same as the page you see in w3c validation). This is not what i want. What i want is simply for it to tell me if a file is valid or not. For any error detail, i can simply load the page in FireFox myself, since if i need to edit it i need to view it in FireFox anyway. So, to fix this problem, you can wrap a perl script, which takes a dir and simply print any file path that's invalid. Here's the perl script: # perl # 2008-06-20 validates a given dir's html files recursively requires the mac os x app Validator-SAC.app at http://habilis.net/validator-sac/ as of 2008-06 use strict; use File::Find; my $dirPath = q(/Users/xah/web/emacs); my $validator = q(/Applications/ Validator-SAC.app/Contents/Resources/weblet); sub wanted { if ($_ =~ m{\.html$} && not -d $File::Find::name) { my $output = qx{$validator "$File::Find::name" | head -n 11 | grep 'X-W3C-Validator-Status:'}; if ($output ne qq(X-W3C-Validator-Status: Valid\n)) { print q (Problem: ), $File::Find::name, "\n"; } else { print qq(Good: $_) ,"\n"; } } } find(\&wanted, $dirPath); print q(Done.) However, for some reason, ?Validator S.A.C.? took nearly 2 seconds to check each file, in contrast, the FireFox html validator add-on took a fraction of a second while also render the whole page completely. For example, suppose i have 20 files in a dir i need to validate. It's faster, if i just open all of them in FireFox and eyeball the validity indicator, then running the ?Validator SAC? on them. I wrote to its author Chuck Houpt about this. It seems that the validator uses Perl and loads about 20 heavy duty web related perl modules to do its job, and over all is wrapped as a Common Gateway Interface?. Perhaps there is a way to avoid these wrappers and call the parser or validator directly. I'm still looking for a fast, batch, html validation tool. ----------------- Xah ? http://xahlee.org/ ? From lolekk12233 at wp.pl Fri Dec 5 15:00:34 2008 From: lolekk12233 at wp.pl (girl18) Date: Fri, 5 Dec 2008 12:00:34 -0800 (PST) Subject: Pretty young girl enjoy fucking - Video Message-ID: <1b33238a-5e98-44b8-a595-c8aa500eabb1@s9g2000prm.googlegroups.com> http://yeba.pl/show/movies/5257/Perfect_babe_-_Idealna_kobieta From mnations at gmail.com Thu Dec 11 20:05:15 2008 From: mnations at gmail.com (Mudcat) Date: Thu, 11 Dec 2008 17:05:15 -0800 (PST) Subject: PyQt: Pulling Abstract Item Data from Mime Data using Drag and Drop. Message-ID: <150086b2-b02d-4204-8c06-b08c0aa119c4@k1g2000prb.googlegroups.com> I'm trying to drag/drop info from a TreeWidget into a TextBox. I have been able to modify the TextEdit box to override the dragEnterEvent like this: class TextEdit(QtGui.QTextEdit): def __init__(self, title, parent): QtGui.QTextEdit.__init__(self, title, parent) self.setAcceptDrops(True) def dragEnterEvent(self, event): if event.mimeData().hasFormat('text/plain'): event.accept() elif (event.mimeData().hasFormat("application/x- qabstractitemmodeldatalist")): print event itemData = event.mimeData().retrieveData("application/x- qabstractitemmodeldatalist", QtCore.QVariant.List) The drag is working up until the point I try to actually retrieve the data. At that point I get an unhandled Runtime Error saying "no access to protected functions or signals for objects not created in Python". Obviously I am not retrieving them in the correct format. Does anyone know how to convert/retrieve the information into a Python list? Thanks From RBQG84 at motorola.com Tue Dec 30 05:17:24 2008 From: RBQG84 at motorola.com (Narasimhan Raghu-RBQG84) Date: Tue, 30 Dec 2008 18:17:24 +0800 Subject: string in files In-Reply-To: <9cda24d9-7a88-45db-b23c-fb43b7d567d4@r37g2000prr.googlegroups.com> Message-ID: <7FAD6FCE52421841A11B441DEF3A88CA01F0910A@ZMY16EXM70.ds.mot.com> Simple solution: us result=yourString.split(" ") and you get a list with all the words. -----Original Message----- From: python-list-bounces+rbqg84=motorola.com at python.org [mailto:python-list-bounces+rbqg84=motorola.com at python.org] On Behalf Of ibpet11 at gmail.com Sent: Tuesday, December 30, 2008 3:43 PM To: python-list at python.org Subject: string in files guys i need info on how to call up different words in a line of a file using python example : file = 'this is a python coding group' i want to assign a xter to this, is, a, python , coding and group thanks -- http://mail.python.org/mailman/listinfo/python-list From news123 at free.fr Sun Dec 7 07:11:14 2008 From: news123 at free.fr (News123) Date: Sun, 07 Dec 2008 13:11:14 +0100 Subject: python book for non technical absolute beginner In-Reply-To: <493a7c6a$0$973$426a34cc@news.free.fr> References: <493a7c6a$0$973$426a34cc@news.free.fr> Message-ID: <493bbd62$0$14452$426a34cc@news.free.fr> Thanks for your answers, I'll look at - "Python Programming, for the absolute beginner (second edition by MichaelDawson." and at the LiveWires Course: http://www.livewires.org.uk/python/home I looked at http://www.greenteapress.com/thinkpython/thinkCSpy/ but think it's not a good choice for a non engineer, as this course tries to explain many principles, which are not really needed to get started. AN example is recursion. Recursion is important but confuses easily. I remember still how quite some people at school disconencted mentally when the teacher tried to explain the 'mathematical induction'. bye N News123 wrote: > Hi, > > One of my 'non technical' friends complained about knowing nothing at > all about programming (though using computers regularly for mails / web > browsing / googling and downloading / cropping photos ) > > He wants to play a little with programming to stimulate parts of his > otehrwise idle brain cells. ;-) Normally it's more the social science / > linguistic parts being exercised, > > I thought python might be a nice language for this > > No my question does anybody know a nice beginners book (or a learning CD > or on line tutorial)? Ideally it shouldn't be too serious and have a lot > of small nice mini-examples > > thanks in advance for any suggestions hints > > > bye > > > N From manu3d at gmail.com Thu Dec 11 11:07:45 2008 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 11 Dec 2008 08:07:45 -0800 (PST) Subject: Preventing execution of a method Message-ID: <9e833b34-0bb3-40c4-9a6c-74773c3c14bb@z6g2000pre.googlegroups.com> Sorry if I'm a bit thick here... can any of the esteemed participant in this noble newsgroup confirm that is not possible to prevent a python module's code from executing the methods of another module? I.e. if I have a class with two methods, doSomethingSafe() and doSomethingDangerous(), is there a way to prevent another module from executing doSomethingDangerous() but allow the execution of doSomethingSafe()? My understanding is that in python this is not possible. Can you confirm? Manu From cjw at ncf.ca Sun Dec 7 08:20:41 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sun, 07 Dec 2008 08:20:41 -0500 Subject: var or inout parm? In-Reply-To: References: Message-ID: mh at pixar.com wrote: > How can I make a "var" parm, where the called function can modify > the value of the parameter in the caller? > > def f(x): > x = x + 1 > > n = 1 > f(n) > # n should now be 2 > > Many TIA!! > Mark > > Why not run it and see? Your function returns None. The function in effect takes a copy of n. n is not changed. Colin W. From bruno.42.desthuilliers at websiteburo.invalid Wed Dec 31 06:59:18 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 31 Dec 2008 12:59:18 +0100 Subject: Pass by reference In-Reply-To: <529e1d98-8932-49f0-b569-85285bd50f23@p2g2000prn.googlegroups.com> References: <529e1d98-8932-49f0-b569-85285bd50f23@p2g2000prn.googlegroups.com> Message-ID: <495b5e88$0$3491$426a74cc@news.free.fr> iu2 a ?crit : > Hi, > > Is it possible somehow to change a varible by passing it to a > function? For which definition of "change a variable" ? > I tried this: > > def change_var(dict0, varname, val): > dict0[varname] = val Ok, this is mutating dict0, so it works. > > def test(): > a = 100 > change_var(locals(), 'a', 3) Please (re)read the doc for locals(): http://www.python.org/doc/2.6/library/functions.html#locals See the big warning ? > print a > > But test() didn't work, It did. The problem is elsewhere. > the value a remains 100. > > I have several variables initialized to None. Where ? > I need to convert each one of them an object only if it is None. > something like: > > if not var1: var1 = MyObject() Warning : some objects can eval to false in a boolean context without being None. Better to explicitely test identity here: if var1 is None: var1 = Something() > I want this to be a function, that is: > > def create_obj(var): > if not var: var = MyObj() This is a rebinding, not a mutation. Here, 'var' is a local *name*, so rebinding it will only affect the local namespace. > # set properties of var Why don't you use the initializer of MyObj here ? class MyObj(object): def __init__(self, prop1, propx): # set properties of self self.prop1 = prop1 self.propx = propx Then just call: var = MyObj(somevalue, someothervalue) > Now, I know I can achieve this by functional programming, ??? > def create_obj(var): > if not var: > x = MyObj() > # set properties of x > return x > return var This is just a plain function. You may want to re-read the definition of "functional programming" !-) > and then > > var = creaet_obj(var) > > Is there another way? What's wrong with this one ? From steve at REMOVE-THIS-cybersource.com.au Wed Dec 31 18:02:18 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Dec 2008 23:02:18 GMT Subject: math module for Decimals References: <01671a9e$0$6988$c3e8da3@news.astraweb.com> <016721cc$0$6988$c3e8da3@news.astraweb.com> Message-ID: <016bf0f4$0$6988$c3e8da3@news.astraweb.com> On Sun, 28 Dec 2008 06:38:32 -0800, Mark Dickinson wrote: > On Dec 28, 7:28?am, Steven D'Aprano cybersource.com.au> wrote: >> Ah crap, I forgot that from_float() has been left out of the decimal >> API. That's very annoying. > > Agreed. It's maybe even annoying enough that a feature request at > bugs.python.org might be honoured. (Hint, hint!) I can take a hint :) http://bugs.python.org/issue4796# Thank you for looking at this. -- Steven From castironpi at gmail.com Wed Dec 31 18:22:13 2008 From: castironpi at gmail.com (Aaron Brady) Date: Wed, 31 Dec 2008 15:22:13 -0800 (PST) Subject: multiprocessing vs thread performance References: Message-ID: <04a86770-262c-499a-92d3-3ffa76434503@a29g2000pra.googlegroups.com> On Dec 29, 9:29?am, mk wrote: > Christian Heimes wrote: > > mk wrote: > >> Am I doing smth wrong in code below? Or do I have to use > >> multiprocessing.Pool to get any decent results? > > > You have missed an important point. A well designed application does > > neither create so many threads nor processes. > > Except I was not developing "well designed application" but writing the > test the goal of which was measuring the thread / process creation cost. > > > The creation of a thread > > or forking of a process is an expensive operation. > > Sure. The point is, how expensive? While still being relatively > expensive, it turns out that in Python creating a thread is much, much > cheaper than creating a process via multiprocessing on Linux, while this > seems to be not necessarily true on Mac OS X. > > > You should use a pool > > of threads or processes. > > Probably true, except, again, that was not quite the point of this > exercise.. > > > The limiting factor is not the creation time but the communication and > > synchronization overhead between multiple threads or processes. > > Which I am probably going to test as well. I had an idea. You could use 'multiprocessing' for synchronization, and just use an mmap for the actual communication. (I think it's a good idea.) From castironpi at gmail.com Wed Dec 31 18:24:56 2008 From: castironpi at gmail.com (Aaron Brady) Date: Wed, 31 Dec 2008 15:24:56 -0800 (PST) Subject: greenlets and how they can be used References: Message-ID: <2cb20fad-c9be-4fe8-9cb7-e7ff91a67649@z28g2000prd.googlegroups.com> On Dec 30, 9:40?pm, "James Mills" wrote: > Hey all, > > The "greenlet" fromhttp://codespeak.net/py/dist/greenlet.html > is a rather interesting way of handling flow of control. > > I can't seem to find anything else on the subject > except for the above link and the most recent version > 0.2 and it's tests. > > What can "greenlet"'s be used for ? What use-cases > have you guys used them for (if any) ? > > Can they be used in place of threads with much > the same effect - ?but more lightweight ? I don't know Erlang, but it seems to be useful for a construction of a unit of work that is more consistent with the underlying goal. I had a dream for a while that in a GUI framework, every event would spawn a unique thread. The GUI would remain responsive even while executing minor tasks. Of course, shaving a second off running time isn't exactly mission-critical to GUI users. From castironpi at gmail.com Wed Dec 31 18:28:53 2008 From: castironpi at gmail.com (Aaron Brady) Date: Wed, 31 Dec 2008 15:28:53 -0800 (PST) Subject: Easy-to-use Python GUI References: Message-ID: <0b4ba5a4-ac79-4f11-8885-d163fb1a84f0@i18g2000prf.googlegroups.com> On Dec 29, 5:49?pm, "Joel Koltner" wrote: > Thanks to everyone who responded; I'll be checking out the various toolkits > people have listed! > > ---Joel There is wxFormBuilder, which stores a GUI design in XML format. It may be lengthy, but your data reside in a data structure, and your program resides in a program structure. From Scott.Daniels at Acm.Org Wed Dec 31 18:30:30 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 31 Dec 2008 15:30:30 -0800 Subject: How to initialize an array with a large number of members ? In-Reply-To: <5m4nl4hs8f9q6rfcp7b1jt7nk1o6sq6r0f@4ax.com> References: <5m4nl4hs8f9q6rfcp7b1jt7nk1o6sq6r0f@4ax.com> Message-ID: David Lemper wrote: > ... Python. Using version 3.0 > # script23 > from array import array > < see failed initialization attempts below > > tally = array('H',for i in range(75) : [0]) > tally = array('H',[for i in range(75) : 0]) > tally = array('H',range(75) : [0]) > tally = array('H',range(75) [0]) > Above give either Syntax error or TypeError > > All examples of sequences in docs show only a few members > being initialized. Array doc says an iterator can be used, > but doesn't show how. First, [1,2,3] is iterable. You could look up iterators or generators or list comprehension, but since it's the holidays: import array tally = array.array('H', (0 for i in range(75)))# a generator tally = array.array('H', [0 for i in range(75)])# list comprehension > What would you do for a 2 dimensional array ? You'll have to wait for numpy for the most general 2-D, but for list-of-array: square = [array.array('H', (i * 100 + j for j in range(75))) for i in range(75)] square[4][8] From benjamin.kaplan at case.edu Wed Dec 31 18:30:43 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 31 Dec 2008 18:30:43 -0500 Subject: type conversion In-Reply-To: <016be89e$0$6988$c3e8da3@news.astraweb.com> References: <4b7188db-63b2-4ac5-80cb-d1326ca3694a@q26g2000prq.googlegroups.com> <613a20bf-6e5a-435e-9a83-36766e12f0ab@k8g2000yqn.googlegroups.com> <016be89e$0$6988$c3e8da3@news.astraweb.com> Message-ID: On Wed, Dec 31, 2008 at 5:26 PM, Steven D'Aprano < steve at remove-this-cybersource.com.au> wrote: > On Wed, 31 Dec 2008 12:35:20 -0800, Hamish McKenzie wrote: > > > sometimes I want to be able to initialize an instance with a variety of > > different data types. > > Type conversion is a bit of a misleading subject line. You're not really > converting different types, just initialising from different types. > > > > as an obvious example I might want to initialize a 4x4 matrix with > > either 16 floats, a list/tuple or 16 floats, another matrix or a > > quaternion. > > > > is there any other way to do it other than putting case statements in > > the __init__ method of the class, or having a Matrix.FromQuaternion( > > quat )? > > > You could have an external function qtom: > > def qtom(quaternion): > a, b, c, d = quaternion > return Matrix([ > a, 0, 0, 0, > 0, b, 0, 0, > 0, 0, c, 0, > 0, 0, 0, d]) > > > But the first two solutions seem reasonable to me, except of course > Python doesn't have a case statement you have to use an if...elseif block. You could also use a dict with type:method key/value pairings. This is closer to a switch/case than an if...elif chain is. (untested) def __init__(self, *args) : inits = {list: self._init_from_list, float: self._init_from_floats, Matrix: self._init_from_matrix} #and so on inits[type(args[0])](*args) > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Wed Dec 31 18:32:43 2008 From: castironpi at gmail.com (Aaron Brady) Date: Wed, 31 Dec 2008 15:32:43 -0800 (PST) Subject: Pass by reference References: <529e1d98-8932-49f0-b569-85285bd50f23@p2g2000prn.googlegroups.com> Message-ID: On Dec 31, 5:30?am, iu2 wrote: > Hi, > > Is it possible somehow to change a varible by passing it to a > function? > > I tried this: > > def change_var(dict0, varname, val): > ? dict0[varname] = val > > def test(): > ? a = 100 > ? change_var(locals(), 'a', 3) > ? print a > > But test() didn't work, the value a remains 100. > > I have several variables initialized to None. > I need to convert each one of them an object only if it is None. > something like: > > if not var1: var1 = MyObject() > > I want this to be a function, that is: > > def create_obj(var): > ? if not var: var = MyObj() > ? # set properties of var > > Now, I know I can achieve this by functional programming, > > def create_obj(var): > ? if not var: > ? ? x = MyObj() > ? ? # set properties of x > ? ? return x > ? return var > > and then > > var = creaet_obj(var) > > Is there another way? > > Thanks A practical way is to use a container. Some people use lists; I like an object. thingref= Ref( thing ) f( thingref ) print thingref() #or thingref.get() or w'ver. Then 'f' can assign like this: def f( aref ): # blah blah aref( newthing ) #or aref.set( newthing ) But the short answer is no. A function receives the contents of a variable, not a variable. From fennecfanatic at gmail.com Wed Dec 31 18:33:56 2008 From: fennecfanatic at gmail.com (Mirage) Date: Wed, 31 Dec 2008 15:33:56 -0800 (PST) Subject: Graphics Library with Standard Interaction Features, 2D and 3D References: <69c3eca8-5e17-49fb-8354-5fdc0bd73f9a@r15g2000prd.googlegroups.com> Message-ID: <60cc8c61-52c2-43b2-8287-66417f1d1ca9@q18g2000vbn.googlegroups.com> On Dec 31, 6:18?am, Stef Mientki wrote: > Maybe VPython (Visual) or Panda fits your needs. > cheers, > Stef I second that. Panda3D is awesome in so many ways. From castironpi at gmail.com Wed Dec 31 18:50:20 2008 From: castironpi at gmail.com (Aaron Brady) Date: Wed, 31 Dec 2008 15:50:20 -0800 (PST) Subject: SQL, lite lite lite References: <39322fe4-e606-42dc-9123-71751258c3ae@a12g2000pro.googlegroups.com> <8da5c6b1-951f-4abd-8ee7-07b63802b9f6@13g2000yql.googlegroups.com> <186e44f7-f949-45e2-b1e2-a913560acf94@s9g2000prg.googlegroups.com> <495a97ce$0$25469$426a74cc@news.free.fr> Message-ID: On Dec 30, 2:52?pm, Bruno Desthuilliers wrote: > Aaron Brady a ?crit : > > > On Dec 30, 11:16 am, prueba... at latinmail.com wrote: > (snip) > >> You really do like to reinvent the wheels do you? :-) Nothing wrong > >> with that. Just be aware that most people that really need what you > >> are proposing are probably already using mature feature rich libraries > >> for that. > > >>http://wiki.python.org/moin/HigherLevelDatabaseProgramming > > > Look at these options! ?Who invents the wheel? ?Naturally, I've had > > time to master every one. > > Oh, so that's why you propose to add yet another item to the list ? Aha, so it is. Your criticism might seem harsh, but it has an advantage. It made me get the lead out, that is, think. Assuming I do want my Relation class to be backed by a full-fledged database, all I would need is an adapter to a Dee or Django object. The only restriction is, records have to be uniform types. (In many cases, this can be good, since relations are statically typed.) I recognize that on average, I'm only saving a little syntax. If I have a Student object and I want the classes s/he is in, the SQL isn't horrible. SELECT objectrep FROM Classes WHERE Student IS studentA //'IS' is not supported in SQL It returns a list of Class instances. The Python is better. studentA.getClasses() To make it fully dynamic, studentA.get( 'Classes' ) or studentA.get( Classes ) or studentA.cross( Classes ) would be closer to what I have in mind. If readers will permit a brainstorm, maybe one of the options will spark an idea. studentA and Classes studentA.intersection( Classes ) However, I want a list of classes, not a list of students, so I am not wanting a pure 'intersection' relation, that is, not a commutative one. Classes.get( studentA ) Classes and studentA #breaks commutativity of 'and' Classes.intersection( studentA ) The method will have to determine what field 'studentA' is supposed to match. From http Wed Dec 31 19:19:54 2008 From: http (Paul Rubin) Date: 31 Dec 2008 16:19:54 -0800 Subject: multiprocessing vs thread performance References: <04a86770-262c-499a-92d3-3ffa76434503@a29g2000pra.googlegroups.com> Message-ID: <7x8wpv7u8l.fsf@ruckus.brouhaha.com> Aaron Brady writes: > I had an idea. You could use 'multiprocessing' for synchronization, > and just use an mmap for the actual communication. (I think it's a > good idea.) Are you reinventing POSH? (http://poshmodule.sourceforge.net) From castironpi at gmail.com Wed Dec 31 19:22:30 2008 From: castironpi at gmail.com (Aaron Brady) Date: Wed, 31 Dec 2008 16:22:30 -0800 (PST) Subject: why cannot assign to function call References: <495867C2.7080807@gmail.com> <5e807c67-7d97-4b8a-8c5f-a3b97f5c5003@i20g2000prf.googlegroups.com> <5fb29c80-a6a4-4cb4-aa62-0d2aeb437662@o4g2000pra.googlegroups.com> Message-ID: <0164a0d4-97c9-4be1-a948-4e5b0deb9585@b38g2000prf.googlegroups.com> On Dec 31, 1:39?am, Tim Roberts wrote: > Aaron Brady wrote: > > >I think the problem goes deeper than just English. ?In any language > >that has a plural, the propositions in question come out as, 'one > >thing is two things' or 'two things are one thing'. ?According to some > >rules, these are ungrammatical sentences, due to plurality > >disagreement. ?Ex: > > >The Morning Star is ... > >The Evening Star is ... > >*The Morning Star and The Evening Star is... > >*The Morning Star and The Evening Star are... > > >Neither of the latter two is correct. ?(* marks ungrammatical.) ? As > >such, the listener isn't sure what meaning to take. > > This is taking a serious twist into off-topicness, but I need to dispute > this. ?I will assert that the 4th line is, in fact, grammatically correct, > modulo the capitalization of the second "The". ?The fragment is clearly of > the form "X and Y are...", and regardless of the substitution of X and Y, > the plurality of the subject agrees with the verb. > > ? The Morning Star and the Evening Star are bright tonight. > > Ignoring the fact that we can't see both at the same time, why is the > meaning of that unclear? I want to get around to a clear answer to the OP's question, but I'm frustrated by a month-long argument about it that suffered from some serious misunderstandings of technical terms. (Therefore, thanks for entertaining my detour so far, as well as not jumping down my throat yet.) We didn't do a good job of explaining, and even disputed some of the terms ourselves. So, I'm trying to look for some clear, vernacular language that won't confuse lay speakers in an explanation. I agree that the form of the 4th fragment is 'X and Y are' in general. However, native speakers don't often use the form 'X and X are'. This is the source of my protest, because X = the Morning Star = the Evening Star. We don't say, 'G.H.W. Bush and the President are...', say, at Camp David. It is not that the meaning is unclear, it's just that form is never used. In fact, moreover, there is some exclusion implied. If I said, 'I'm going to St. Paul's and church,' my listener might think I had two destinations, or I was being philosophical. The conversational maxim of quantity [1] even leads him/r to believe that I want to convey more information that just that I'm going to church. [1] http://en.wikipedia.org/wiki/Gricean_maxim#Maxim_of_Quantity In other words, s/he infers that there is a reason I didn't say only, 'I'm going to St. Paul's' or 'I'm going to church', and s/he wants to know what it is. How all this relates to Python semantics is, if I say, 'a and b are the same object', the listener can get confused. I don't say, 'G.H.W. Bush and the President are the same'; I say, 'G.H.W. Bush is the President'. Part of the problem is that Python divorced variables from their contents; variables and objects are two different things. One is a key in a namespace lookup; the other is the value there. I want to conclude that, 'Therefore, there is no such thing as a reference to a variable; only a namespace and a key'. However, I'm not on firm footing to explain further, due to the uncommonness of the forms of speech I would need to use. Maybe I could observe, 'variable references are a peculiarity of C++, not available in every variable model'. From castironpi at gmail.com Wed Dec 31 19:26:42 2008 From: castironpi at gmail.com (Aaron Brady) Date: Wed, 31 Dec 2008 16:26:42 -0800 (PST) Subject: multiprocessing vs thread performance References: <04a86770-262c-499a-92d3-3ffa76434503@a29g2000pra.googlegroups.com> <7x8wpv7u8l.fsf@ruckus.brouhaha.com> Message-ID: <34305872-cb16-4bbb-ad34-3c6a04e30462@r10g2000prf.googlegroups.com> On Dec 31, 6:19?pm, Paul Rubin wrote: > Aaron Brady writes: > > I had an idea. ?You could use 'multiprocessing' for synchronization, > > and just use an mmap for the actual communication. ?(I think it's a > > good idea.) > > Are you reinventing POSH? ?(http://poshmodule.sourceforge.net) I thought the same thing! Paul Boddie introduced me to POSH some months ago. I don't recall the implementation of synchro. objects in POSH, but IIRC, 'multiprocessing' uses native OS handles opening in multiple processes. It could be that there would be substantial overlap, or the trade-offs could be significant. For one, the above combination only permits strings to be shared, not objects. From bdesth.quelquechose at free.quelquepart.fr Wed Dec 31 19:27:33 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Jan 2009 01:27:33 +0100 Subject: Why not Ruby? In-Reply-To: <0640abb6-ab69-4709-a46c-b0ee8c9f0c09@n21g2000vba.googlegroups.com> References: <0640abb6-ab69-4709-a46c-b0ee8c9f0c09@n21g2000vba.googlegroups.com> Message-ID: <495c1ba3$0$28149$426a74cc@news.free.fr> Roger a ?crit : > On Dec 31, 12:55 pm, Xah Lee wrote: (snip) > > Who are you? His name is Xah Lee, and he's a well(hem)known troll. Just ignore him. From philip at semanchuk.com Wed Dec 31 19:28:43 2008 From: philip at semanchuk.com (Philip Semanchuk) Date: Wed, 31 Dec 2008 19:28:43 -0500 Subject: multiprocessing vs thread performance In-Reply-To: <7x8wpv7u8l.fsf@ruckus.brouhaha.com> References: <04a86770-262c-499a-92d3-3ffa76434503@a29g2000pra.googlegroups.com> <7x8wpv7u8l.fsf@ruckus.brouhaha.com> Message-ID: <09049249-5F43-4040-AFF0-FAC409705622@semanchuk.com> On Dec 31, 2008, at 7:19 PM, Paul Rubin wrote: > Aaron Brady writes: >> I had an idea. You could use 'multiprocessing' for synchronization, >> and just use an mmap for the actual communication. (I think it's a >> good idea.) > > Are you reinventing POSH? (http://poshmodule.sourceforge.net) Or sysv_ipc? Or posix_ipc? http://semanchuk.com/philip/sysv_ipc/ http://semanchuk.com/philip/posix_ipc/ Bug fix version of the latter coming out in a day or two... From hongtian.info at gmail.com Wed Dec 31 20:42:56 2008 From: hongtian.info at gmail.com (Hongtian) Date: Wed, 31 Dec 2008 17:42:56 -0800 (PST) Subject: How to debug embeding Python? References: Message-ID: <879fea5e-be92-4869-9acf-83008127b2a7@g39g2000pri.googlegroups.com> Thanks all of you, my friends. I think log system is a very good choice. Happy new year! From cab938 at mail.usask.ca Wed Dec 31 21:01:50 2008 From: cab938 at mail.usask.ca (Chris Brooks) Date: Wed, 31 Dec 2008 18:01:50 -0800 (PST) Subject: multiprocessing BaseManager doesn't clean up net connections? Message-ID: <21238615.post@talk.nabble.com> Hi, I'm trying to use remote managers in the multiprocessing module to listen for some events synchronously while my program goes off and does other things. I use the .start() method which forks a new process to handle communication. When I catch the sigint and call sys.exit() though, the network port is still bound even after the python interpretor finishes. Here is my short code and the output: from multiprocessing.managers import BaseManager import threading import sys import signal import time class WorkManager(BaseManager): def __init__(self): BaseManager.__init__(self,address=('', 51114), authkey='chris') self.register('get_string', callable=self.getString) def getString(self): return "hi" manager = WorkManager() manager.start() def quit( arg1, arg2 ): sys.exit() signal.signal(signal.SIGINT, quit) #busy wait while 1: time.sleep(1) cab938 at ubuntu:~$ python2.6 server.py ^Ccab938 at ubuntu:~$ python2.6 server.py Process WorkManager-1: Traceback (most recent call last): File "/usr/local/lib/python2.6/multiprocessing/process.py", line 231, in _bootstrap self.run() File "/usr/local/lib/python2.6/multiprocessing/process.py", line 88, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python2.6/multiprocessing/managers.py", line 517, in _run_server server = cls._Server(registry, address, authkey, serializer) File "/usr/local/lib/python2.6/multiprocessing/managers.py", line 136, in __init__ self.listener = Listener(address=address, backlog=5) File "/usr/local/lib/python2.6/multiprocessing/connection.py", line 97, in __init__ self._listener = SocketListener(address, family, backlog) File "/usr/local/lib/python2.6/multiprocessing/connection.py", line 217, in __init__ self._socket.bind(address) File "", line 1, in bind error: [Errno 98] Address already in use Traceback (most recent call last): File "server.py", line 16, in manager.start() File "/usr/local/lib/python2.6/multiprocessing/managers.py", line 499, in start self._address = reader.recv() EOFError cab938 at ubuntu:~$ Comments? Is this a bug, or is there a better way to clean up the manager myself before shutting down? Chris -- View this message in context: http://www.nabble.com/multiprocessing-BaseManager-doesn%27t-clean-up-net-connections--tp21238615p21238615.html Sent from the Python - python-list mailing list archive at Nabble.com. From gh at ghaering.de Wed Dec 31 21:10:35 2008 From: gh at ghaering.de (=?UTF-8?B?R2VyaGFyZCBIw6RyaW5n?=) Date: Thu, 01 Jan 2009 03:10:35 +0100 Subject: Easy-to-use Python GUI In-Reply-To: References: Message-ID: <6s2n0sF408fuU1@mid.uni-berlin.de> Dotan Cohen wrote: > I have been following this thread with interest. Is there a way to > build Qt apps with relative easy? I use KDE and would prefer the Qt > toolkit for my GUI apps. Thanks. A few years ago, I've had bad experiences with wxPython (random things not actually working on Linux, only on Windows; getting segfaults when using not exactly the right values for API calls). So, when I had to decide for a toolkit for a new application I'm developing on my job which required: - ability to run on Windows - ability to run on MacOS - time to develop is short I recommended to go with PyQt. I remembered it was warmly recommended by Alex Martelli and others a few years ago. So far, it's been nothing but joy. We bought the book "Rapid GUI Programming with Python and Qt" (http://www.qtrac.eu/pyqtbook.html) which is *really* well written. It's probably the best tech book I ever had. The author formerly did Qt documentation for Trolltech, so he has deep understanding of what he's writing about. There may be not so many third-party add-ons for PyQt like for wxPython, but in my opinion, the quality of Qt, PyQt and documentation like the book make up for it. And, it's really extensive. So far I've found everything in Qt/PyQt I wanted/needed: - MDI workspaces - Dock windows - I needed something like wxPythons wxOGL for a process modeler and after looking around for two days, I found out that it's already all there in Qt 4.4: QGraphicsScene/QGraphicsView - etc. -- Gerhard From prologic at shortcircuit.net.au Wed Dec 31 21:57:39 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 1 Jan 2009 12:57:39 +1000 Subject: greenlets and how they can be used In-Reply-To: <2cb20fad-c9be-4fe8-9cb7-e7ff91a67649@z28g2000prd.googlegroups.com> References: <2cb20fad-c9be-4fe8-9cb7-e7ff91a67649@z28g2000prd.googlegroups.com> Message-ID: On Thu, Jan 1, 2009 at 9:24 AM, Aaron Brady wrote: (snip) > I had a dream for a while that in a GUI framework, every event would > spawn a unique thread. The GUI would remain responsive even while > executing minor tasks. Of course, shaving a second off running time > isn't exactly mission-critical to GUI users. Do you think greenlet's (this implementation anyway) would be useful in circuits (1) ? When you say every even that was created would spawn a new thread or greenlet ... Makes me wonder ... Just a thought ... What's yours ? cheers James 1. http://trac.softcircuit.com.au/circuits/ From koranthala at gmail.com Wed Dec 31 22:29:19 2008 From: koranthala at gmail.com (koranthala at gmail.com) Date: Wed, 31 Dec 2008 19:29:19 -0800 (PST) Subject: Videocapture in python Message-ID: <0372e356-8f37-457d-9201-18ae94fc68d9@a29g2000pra.googlegroups.com> I face issues in videocapture in python. Cant find anyplace where we can raise bug reports, so mentioning here. Also help required if somebody has solved it earlier. On using videocapture (python 2.4), I am facing the following issues while creating a video sort of application. -> Pull out the usb cable : Videocapture gets the data stored initially in the buffer and returns always. The images are not updated - but also there is no error returned. i.e. there is no information to the viewer that it is not working anymore. Especially because since the timestamp is updated everytime (it is done inside videocapture.py - wherein current time is overwritten on the received image), it gives a feeling that video is running. Currently I have done a workaround in that every 2 captures, i setup the camera again - but it takes too much time. Anyone has any suggestions on solving this? From kentilton at gmail.com Wed Dec 31 23:16:41 2008 From: kentilton at gmail.com (Kenneth Tilton) Date: Wed, 31 Dec 2008 23:16:41 -0500 Subject: Why not Ruby? In-Reply-To: References: Message-ID: <495c43c3$0$20279$607ed4bc@cv.net> Xah Lee wrote: > Just spent 3 hours looking into Ruby today. Here's my short impression > for those interested. > > * Why Not Ruby? > http://xahlee.org/UnixResource_dir/writ/why_not_Ruby.html > > plain text version follows: > -------------------------------------- > > Why Not Ruby? > > Xah Lee, 2008-12-31 > > Spent about 3 hours looking into Ruby language today. > > The articles i read in detail are: > > * Wikipedia: Ruby (programming language)?J. Gives general overview. > > * Brief tutorial: "Ruby in Twenty Minutes" > http://www.ruby-lang.org/en/documentation/quickstart/ > > * Personal blog by Stevey Yegge, published in 2004-10. > http://steve.yegge.googlepages.com/ruby-tour > > The Wikipedia gives the best intro and overview in proper context. The > "Ruby in Twenty Minutes" is just 4 pages. It give you a very concrete > intro to Ruby's syntax and semantics. Stevey Yegge's blog doesn't > teach much and rambles, but provide a little personal view. I read it > because his opinions i respect. > > Q: Will you learn Ruby? > > No. For practical application, the lang is some 100 times less useful > than each of Perl, Python, PHP, Javascript. For academic study, > functional langs like Mathematica, Haskell, OCaml, erlang, Qz, are far > more interesting and powerful in almost all aspects. Further, there's > also Perl6, NewLisp, Clojure, Scala... With respect to elegance or > power, these modern lang of the past 5 years matches or exceed Ruby. > > Q: Do you think Ruby lang is elegant? > > Yes. In my opinion, better than Perl, Python, PHP. As a high level > lang, it's far better than Java, C, C++ type of shit. However, i don't > think it is any better than emacs lisp, Scheme lisp, javascript, > Mathematica. Note that Ruby doesn't have a spec, and nor a formal > spec. Javascript has. Ruby's syntax isn't that regular, nor is it > based on a system. Mathemtica's is. Ruby's power is probably less than > Scheme, and probably same as Javascript. > > I also didn't like the fact that ruby uses keyword "end" to indicate > code block much as Pascal and Visual Basic, Logo, do. I don't like > that. > > Q: Won't Ruby be a interesting learning experience? > > No. As far as semantics goes, Ruby is basically identical to Perl, > Python, PHP. I am a expert in Perl and PHP, and have working knowledge > of Python. I already regretted having spent significant amount of time > (roughly over a year) on Python. In retrospect, i didn't consider the > time invested in Python worthwhile. (as it turns out, i don't like > Python and Guido cult, as the lang is going the ways of OOP mumbo- > jumbo with its Python 3 "brand new" future.) There is absolutely > nothing new in Ruby, as compared to Perl, Python, PHP, or Emacs lisp, > Scheme lisp. > > Q: Do you recommend new programers to learn Ruby then? > > Not particularly. As i mentioned, if you are interested in practical > utility, there's already Perl, PHP, Python, Javascript, which are all > heavily used in the computing industry. If you are interested as a > academic exercise, there's Scheme lisp, and much of functional langs > such as OCaml, Haskell, Mathematica, which will teach you a whole lot > more about computer science, features of language semantics, etc. > > Q: Do you condemn Ruby? > > No. I think it's reasonably elegant, but today there are too many > languages, so Ruby don't particularly standout for me. Many of them, > are arguably quite more elegant and powerful than Ruby. See: > Proliferation of Computing Languages. > Kenny Tilton, 2008-12-31 Q: Why not Xah's review of Ruby? >> Spent about 3 hours looking into Ruby language today. A. Three hours? I've had belches that lasted longer than that. Of course, a true master can tell a lot in just a few hours of coding with a new language... >> The articles i read in detail are: Q: Read?! A: That's what he said. hth,kzo From thudfoo at opensuse.us Wed Dec 31 23:53:52 2008 From: thudfoo at opensuse.us (member thudfoo) Date: Wed, 31 Dec 2008 20:53:52 -0800 Subject: Why not Ruby? In-Reply-To: References: Message-ID: <3d881a310812312053s5356e29co4b9ebcb55874adfa@mail.gmail.com> 2008/12/31 Giampaolo Rodola' : > On 31 Dic, 18:55, Xah Lee wrote: >> Just spent 3 hours looking into Ruby today. Here's my short impression [...] > --- Giampaolo > http://code.google.com/p/pyftpdlib > Hey, Giampaolo: I had gone to the trouble to filter out the posts from xah lee, but you have quoted his entire message. If you would like to scold xah lee, you can do so directly without reposting to this fine newsgroup. Thank You Very Much. > -- > http://mail.python.org/mailman/listinfo/python-list > >
    User IDName > BGCOLOR='#c0c0c0'>Date